Files
ziran/tests/web_bundle_runtime.cjs
waozi 0743573d59 Project Ziran modules that store types from converted TypeScript
zi-api asks for a checked TypeScript dependency when a stored record type or generic argument is unresolved, ts2zi stages that strict checked module, and projection resumes, so Ziran modules can store types defined in converted TypeScript and type modules can convert before their Ziran users. Module origins resolve through the authored span, and a cyclic storage dependency is reported as ts2zi.native.projection_cycle.
2026-12-01 17:07:08 -03:00

166 lines
9.9 KiB
JavaScript

const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const createPlayground = require(process.env.ZIRAN_PLAYGROUND_RUNTIME || '../site/assets/playground-runtime.js');
async function main() {
let diagnostics = [];
const assets = [];
const runtime = await createPlayground({
printErr: line => diagnostics.push(line),
locateFile(name, directory) {
assets.push(name);
return directory + name;
},
});
runtime.FS.mkdir('/sources');
runtime.FS.mkdir('/library');
runtime.FS.writeFile('/library/math.zi', '#program_export\nDouble :: (value: s32) -> s32 { return value * 2; }');
function build(source, entry = 'Answer') {
diagnostics = [];
runtime.FS.writeFile('/sources/app.zi', source);
return runtime.ccall('BuildBundle', 'number', Array(7).fill('string'),
['/sources', '/std\nexample=/library', '/sources/app.zi', 'app', entry, '', '/result.zx']);
}
assert.equal(build('#import "example/math"\nAnswer :: () -> s32 { return Double(21); }'), 0, diagnostics.join('\n'));
const first = runtime.FS.readFile('/result.zx');
assert.ok(first.length > 100);
assert.equal(build('#import "example/math"\nAnswer :: () -> s32 { return Double(21); }'), 0);
assert.deepEqual(runtime.FS.readFile('/result.zx'), first, 'Repeat compilations produce the same bundle');
assert.notEqual(build('Answer :: () -> s32 { return missing_value; }'), 0);
assert.match(diagnostics.join('\n'), /missing_value/);
assert.throws(() => runtime.FS.readFile('/result.zx'), 'A failed build must remove the old output');
assert.notEqual(build('Other :: () -> s32 { return 1; }'), 0);
assert.equal(build('Answer :: () -> s64 { return 9007199254740993; }'), 0, diagnostics.join('\n'));
assert.equal(build('#import "std/text"\nAnswer :: () -> s32 { return cast(s32)StartsWithFoldASCII("自然", "自"); }'), 0, diagnostics.join('\n'));
assert.equal(await runtime.buildBundle('/sources', '/std\nexample=/library', '/sources/app.zi',
'app', 'Answer', '', '/result.zx'), 0, diagnostics.join('\n'));
assert.ok(!assets.some(name => name.startsWith('ts2zi')), 'Ziran-only builds leave the TypeScript assets unloaded');
runtime.FS.writeFile('/sources/capability.zi', 'host :: #system_library "host_api";\nCompute :: (value: s32) -> s32 #foreign host;\n#program_export\nAnswer :: () -> s32 { return Compute(40); }\n');
const provider = 'interface Props { value: s32; }\nfunction Echo(props: Props): s32 { return props.value; }\nexport function Compute(value: s32): s32 {\n return <Echo value={value + s32(2)}/>;\n}\n';
function bound(source, project) {
diagnostics = [];
runtime.FS.writeFile('/sources/provider.tsx', source);
return runtime.buildBundle('/sources', '/std\nexample=/library', '/sources/capability.zi\n/sources/provider.tsx',
'capability', 'Answer', 'capability:Compute=provider:Compute', '/result.zx', project);
}
assert.equal(await bound(provider), 0, diagnostics.join('\n'));
const typed = runtime.FS.readFile('/result.zx');
assert.ok(typed.length > 100);
assert.notEqual(await bound('export function Compute(value: number): number { return value; }'), 0);
assert.match(diagnostics.join('\n'), /signature mismatch/);
assert.throws(() => runtime.FS.readFile('/result.zx'));
assert.notEqual(await bound(provider.replace('value={value', 'misspelled={value')), 0);
assert.match(diagnostics.join('\n'), /provider\.tsx:4:\d+/);
assert.match(diagnostics.join('\n'), /misspelled/);
assert.throws(() => runtime.FS.readFile('/result.zx'));
const borrowed = 'import { Text, TextCopy } from "std/vec";\n' +
'export function Leak(): string {\n const owned: Text = TextCopy("temporary");\n return TextView(owned);\n}\n' + provider;
assert.notEqual(await bound(borrowed), 0);
assert.match(diagnostics.join('\n'), /provider\.tsx:4:\d+:[^\n]*returned text view borrows local or temporary storage/);
assert.throws(() => runtime.FS.readFile('/result.zx'));
assert.equal(await bound(provider), 0, diagnostics.join('\n'));
assert.deepEqual(runtime.FS.readFile('/result.zx'), typed);
assert.deepEqual(assets.filter(name => name.startsWith('ts2zi')), ['ts2zi-wasm-exec.js', 'ts2zi.wasm.gz']);
const imported = 'import { Double } from "example/math";\n' + provider.replace('value + s32(2)', 'Double(value)');
assert.equal(await bound(imported), 0, diagnostics.join('\n'));
assert.notDeepEqual(runtime.FS.readFile('/result.zx'), typed);
runtime.FS.writeFile('/sources/math.ts', 'export function Double(value: s32): s32 { return value * s32(2); }');
runtime.FS.writeFile('/sources/tsconfig.json', JSON.stringify({
compilerOptions: {
strict: true,
module: 'ESNext',
moduleResolution: 'Bundler',
jsx: 'preserve',
paths: {'@local/math': ['./math.ts']},
},
files: ['provider.tsx'],
}));
assert.equal(await bound(imported.replace('example/math', '@local/math'), '/sources/tsconfig.json'),
0, diagnostics.join('\n'));
runtime.FS.writeFile('/sources/chart.ts', 'export interface Chart { width: s32 }');
runtime.FS.writeFile('/sources/holder.zi', '#import, file "chart.ts";\n' +
'Holder :: struct { chart: Chart }\n' +
'Read :: (holder: Holder) -> s32 { return holder.chart.width }\n');
function storedChart(width) {
diagnostics = [];
const source = 'import { Holder, Read } from "./holder.zi";\n' +
`export function main(): s32 { const holder: Holder = {chart: {width: ${width}}}; return Read(holder); }`;
runtime.FS.writeFile('/sources/chart_app.ts', source);
return runtime.buildBundle('/sources', '/std', '/sources/chart_app.ts', 'chart_app', 'main', '', '/result.zx');
}
assert.equal(await storedChart('s32(7)'), 0, diagnostics.join('\n'));
const chartBundle = runtime.FS.readFile('/result.zx');
assert.ok(chartBundle.length > 100);
assert.notEqual(await storedChart('false'), 0);
assert.match(diagnostics.join('\n'), /chart_app\.ts:2:\d+: TS2322/);
assert.throws(() => runtime.FS.readFile('/result.zx'));
assert.equal(await storedChart('s32(7)'), 0, diagnostics.join('\n'));
assert.deepEqual(runtime.FS.readFile('/result.zx'), chartBundle);
const workshop = '/sources/workshop_passes';
const example = path.join(__dirname, '../examples/workshop_passes');
const workshopSource = fs.readFileSync(path.join(example, 'app.tsx'), 'utf8');
runtime.FS.mkdir(workshop);
runtime.FS.writeFile(`${workshop}/inventory.ts`, fs.readFileSync(path.join(example, 'inventory.ts')));
async function buildWorkshop(source) {
diagnostics = [];
runtime.FS.writeFile(`${workshop}/app.tsx`, source);
return runtime.buildBundle(workshop, '/std', `${workshop}/app.tsx`, 'app', 'main', '', '/result.zx');
}
assert.equal(await buildWorkshop(workshopSource), 0, diagnostics.join('\n'));
const workshopBundle = runtime.FS.readFile('/result.zx');
assert.ok(workshopBundle.length > 100);
assert.notEqual(await buildWorkshop(workshopSource.replace('quantity={3n}', 'quantity={3}')), 0);
assert.match(diagnostics.join('\n'), /app\.tsx:\d+:\d+: TS2322/);
assert.throws(() => runtime.FS.readFile('/result.zx'));
assert.equal(await buildWorkshop(workshopSource), 0, diagnostics.join('\n'));
assert.deepEqual(runtime.FS.readFile('/result.zx'), workshopBundle);
// Exercise the public seven-string ABI in real Wasm, beyond both old caps.
const roots = Array.from({length: 273}, (_, i) => `/root${i}`);
for (const [i, root] of roots.entries()) {
runtime.FS.mkdir(root);
runtime.FS.writeFile(`${root}/Marker${i}.zi`, `Marker :: ${i};`);
}
runtime.FS.writeFile(`${roots[64]}/R64.zi`, 'Value64 :: () -> s32 { return 20; }');
runtime.FS.writeFile(`${roots[272]}/R272.zi`, 'Value272 :: () -> s32 { return 21; }');
runtime.FS.writeFile(`${roots[0]}/Winner.zi`, 'First :: () -> s32 { return 1; }');
runtime.FS.writeFile(`${roots[272]}/Winner.zi`, 'First :: () -> s32 { return wrong_root; }');
runtime.FS.mkdir('/inputs');
const inputs = Array.from({length: 273}, (_, i) => `/inputs/Input${i}.zi`);
for (let i = 0; i < inputs.length; i++)
runtime.FS.writeFile(inputs[i], `Unused${i} :: ${i};`);
runtime.FS.writeFile(inputs[272], '#import "R64"\n#import "R272"\n#import "Winner"\nAnswer :: () -> s32 { return Value64() + Value272() + First(); }');
function many(search = roots, files = inputs) {
diagnostics = [];
return runtime.ccall('BuildBundle', 'number', Array(7).fill('string'),
['/sources', search.join('\n'), files.join('\n'), 'Input272', 'Answer', '', '/result.zx']);
}
assert.equal(many(), 0, diagnostics.join('\n'));
const large = runtime.FS.readFile('/result.zx');
assert.ok(large.length > 100);
// Empty lines retain their existing separator semantics.
assert.equal(many(['', ...roots, ''], ['', ...inputs, '']), 0, diagnostics.join('\n'));
assert.deepEqual(runtime.FS.readFile('/result.zx'), large);
const fails = (search, files, diagnostic) => {
assert.notEqual(many(search, files), 0);
if (diagnostic) assert.match(diagnostics.join('\n'), diagnostic);
assert.throws(() => runtime.FS.readFile('/result.zx'));
assert.equal(many(), 0, diagnostics.join('\n'));
assert.deepEqual(runtime.FS.readFile('/result.zx'), large);
};
for (let repeat = 0; repeat < 3; repeat++) {
fails([...roots, '/missing-root'], inputs, /module search path is unavailable/);
fails(roots, [...inputs, '/inputs/missing.zi'], /missing/);
fails([...roots].reverse(), inputs, /wrong_root/);
fails(roots, []);
}
if (process.env.ZIRAN_BUNDLE_OUTPUT)
require('node:fs').writeFileSync(process.env.ZIRAN_BUNDLE_OUTPUT, large);
console.log('Web BuildBundle: 273 roots and inputs, last-root/last-input resolution, first-root ordering, empty separators, diagnostics, stale-output removal, repeated error recovery passed');
console.log('Browser bundle compiler: checked TSX providers, signature rejection, authored diagnostics, named imports, deterministic output, 64-bit values, UTF-8, stale-output removal and recovery passed');
}
main().catch(error => { console.error(error); process.exitCode = 1; });