Files
Charlie CheeverandClaude Opus 5.5 d0db59ecb0 An unchanged deploy reuses its app and filesystem helper compilation
A deploy's bake now writes its receipts to a directory kept with the
owning Cargo cache (`bakeOutput`) instead of a per-run directory that the
app crates' build scripts watch, so an unchanged deploy no longer reruns
them and recompiles the app crates. Each publication receives a copy of
only the completed receipts, after `copyBake` checks them against the
production receipt, the plan's digest, the artifact graph and every
product's bytes. The web bake's receipt is read by name, so an
interrupted native bake cannot block a later deploy.

With `CARGO_TARGET_DIR` set, the checked filesystem helper lives in that
cache, under a directory per checkout, so a deploy that recreates its
source capture reuses it. The helper's input digest now also covers the
compiler Cargo would run: `rustc -vV` of `RUSTC` (or `CARGO_BUILD_RUSTC`,
or the `rustc` rustup resolves in the checkout), asked once per process,
so another compiler or a toolchain alias that an update moved is built
again. The tests that build captured fixtures clear an inherited
`CARGO_TARGET_DIR`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-13 14:55:33 -08:00

344 lines
24 KiB
JavaScript

import { test } from 'bun:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { chmodSync, copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, posix, relative, resolve, win32 } from 'node:path';
import { classify, publishRoot } from './deploy.mjs';
import { DirectoryOrigin } from './origin.mjs';
import { filesystemHelper } from './filesystem.mjs';
import { buildRust, rustArtifact, localBlob, prepareRustBundle, publishedSignature, rustAbi, rustBundle, rustCard, rustCards, rustFiles, rustReceipt, tieredBytes, tieredNative } from './rust.mjs';
import { rustRuntime } from '../host/web/rust-glue.js';
test('the resident Rust baker builds and runs host-dev once for repeated requests', () => {
const script = `
import assert from 'node:assert/strict';
import { mock } from 'bun:test';
import { EventEmitter } from 'node:events';
import { resolve } from 'node:path';
import { PassThrough, Writable } from 'node:stream';
import * as processes from 'node:child_process';
let builds = 0, starts = 0, requests = 0;
const appTarget = resolve('fixture target'), target = resolve(appTarget, 'rust-tools');
mock.module('node:child_process', () => ({ ...processes,
spawnSync(command, args, options) {
assert.equal(command, 'cargo');
assert.ok(args.includes('exact-logic-bake'));
assert.equal(args[args.indexOf('--profile') + 1], 'host-dev');
assert.ok(!args.includes('--release'));
assert.equal(options.env.CARGO_TARGET_DIR, target);
builds++;
return { status: 0, stdout: '', stderr: '' };
},
spawn(command, args, options) {
assert.equal(command, resolve(target, 'host-dev/exact-logic-bake'));
assert.deepEqual(args, ['--serve']);
assert.equal(options.env.CARGO_TARGET_DIR, target);
starts++;
const child = new EventEmitter();
child.stdout = new PassThrough(); child.stderr = new PassThrough();
child.stdin = new Writable({ write(bytes, encoding, done) {
assert.deepEqual(JSON.parse(String(bytes)), ['candidate', String(++requests)]);
queueMicrotask(() => child.stdout.write('{"ok":true}\\n')); done();
} });
child.kill = () => { child.stdout.end(); child.stderr.end(); };
queueMicrotask(() => child.stdout.write('{"ready":true,"pid":42}\\n'));
return child;
},
}));
const { RustBaker } = await import('./scripts/rust.mjs');
const baker = new RustBaker({ target: appTarget, workspace: process.cwd() }, {});
try { await baker.bake(['candidate', '1']); await baker.bake(['candidate', '2']); }
finally { baker.close(); }
assert.deepEqual([builds, starts, requests], [1, 1, 2]);
`;
const result = spawnSync(process.execPath, ['-e', script], { cwd: resolve(import.meta.dir, '..'), encoding: 'utf8', timeout: 10_000 });
assert.equal(result.status, 0, result.stdout + result.stderr);
});
test('trapping module cleanup cannot throw through the resident Wasm import', () => {
const original=globalThis.WebAssembly, log=console.error;
const memory=new original.Memory({initial:1});
const trap=()=>{throw new original.RuntimeError('unreachable');};
try {
globalThis.WebAssembly={...original,Memory:original.Memory,
Module:class {static imports(){return [];}},
Instance:class {constructor(){this.exports={memory,exact_logic_abi:()=>2,
exact_logic_create:()=>1,exact_logic_destroy:trap,exact_logic_alloc:()=>16,
exact_logic_dealloc:trap,exact_logic_call:()=>0,exact_logic_output:()=>32,
exact_logic_output_len:()=>1};}},
};
console.error=()=>{};
const runtime=rustRuntime(()=>memory),handle=runtime.load(0,1,2);
assert.ok(handle);
assert.equal(runtime.load(0,1,3),0,'a module of another ABI than the host passes is refused');
assert.equal(runtime.call(handle,0,1),0xffffffff);
assert.doesNotThrow(()=>runtime.drop(handle));
assert.ok(runtime.load(0,1,2),'another module can still be instantiated');
} finally {globalThis.WebAssembly=original;console.error=log;}
});
test('one produced Rust pair becomes exact platform assets and requirements', () => {
const app={id:'com.exact.test'}, plan=Buffer.from('plan'), bytes=Buffer.from('module');
const compat={target:'aarch64-apple-ios',inputs:{rustMode:'wasm',grantCeiling:'fs:notes',rustGrants:'fs:notes'}};
const receipt=rustReceipt(app,compat,plan,bytes,'wasm32-unknown-unknown','wasm');
assert.equal(receipt.abi,rustAbi());
const produced={plan,variants:{wasm:{receipt,bytes}}};
const cards=rustCards(rustFiles(produced));
assert.equal(cards.wasm.module.sha256,receipt.module.sha256);
const base={plan:{...rustCard('app.plan',plan),bytes:plan},assets:[],platforms:{}};
const build={compat,graph:{artifacts:[{name:'app.plan',requires:{sources:'embedded',plan:1}}]}};
const result=rustBundle(app,base,build,produced);
base.platforms.ios=result.bundle;
assert.doesNotThrow(()=>JSON.stringify(base));
assert.deepEqual(result.bundle.assets.map(a=>a.name),['rust/app.module.json','rust/app.module.wasm']);
assert.deepEqual(result.build.graph.artifacts[0].requires,{plan:1,rustMode:'wasm',rustAbi:rustAbi(),rustTarget:'wasm32-unknown-unknown',grantCeiling:'fs:notes',rustGrants:'fs:notes'});
assert.equal(result.build.graph.artifacts[2].sha256,receipt.module.sha256);
const off=rustBundle(app,base,{...build,compat:{...compat,inputs:{rustMode:'off'}}},produced);
assert.deepEqual(off.bundle.assets,[]);
assert.equal(off.bundle.platforms,undefined);
const corrupt=rustFiles(produced);corrupt.set('rust/wasm/app.module.wasm',Buffer.from('changed'));
assert.throws(()=>rustCards(corrupt),/does not match/);
});
test('mixed Rust receipts use source grants while artifact requirements retain the union ceiling', () => {
const app={id:'com.exact.mixed'},plan=Buffer.from('plan'),bytes=Buffer.from('module');
const javascript='net.fetch https://example.test/',rust='fs.read app:/data/rust';
const compat={inputs:{rustMode:'wasm',javascriptGrants:javascript,rustGrants:rust,grantCeiling:rust+'\n'+javascript}};
const receipt=rustReceipt(app,compat,plan,bytes,'wasm32-unknown-unknown','wasm');
assert.equal(receipt.grants,rust);
const result=rustBundle(app,{plan:{...rustCard('app.plan',plan),bytes:plan},assets:[]},{compat,graph:{artifacts:[{name:'app.plan',requires:{}}]}},{plan,variants:{wasm:{receipt,bytes}}});
assert.equal(result.build.graph.artifacts[0].requires.grantCeiling,compat.inputs.grantCeiling);
assert.equal(result.build.graph.artifacts[0].requires.rustGrants,rust);
assert.throws(()=>rustReceipt(app,{inputs:{...compat.inputs,grantCeiling:javascript}},plan,bytes,'wasm32-unknown-unknown','wasm'),/exceed/);
assert.throws(()=>rustReceipt(app,{inputs:{grantCeiling:rust}},plan,bytes,'wasm32-unknown-unknown','wasm'),/source grants/);
});
test('publisher companion acquisition binds exact local bytes and isolates concurrent bakes', () => {
const root=mkdtempSync(resolve(tmpdir(),'exact-rust-record-'));
try {
const releases=resolve(root,'.exact/streams/test/releases'), blobs=resolve(root,'.exact/blobs');
mkdirSync(releases,{recursive:true});mkdirSync(blobs,{recursive:true});
const assets=[['rust/app.module.json',Buffer.from('{}')],['rust/app.module.wasm',Buffer.from('wasm')]].map(([name,bytes])=>{
const card=rustCard(name,bytes);writeFileSync(resolve(blobs,card.sha256),bytes);
return {name,bytes:card.bytes,sha256:card.sha256,url:`./${card.sha256}`};
});
const record=resolve(releases,'1.json');writeFileSync(record,JSON.stringify({envelope:{},assets:{assets}}));
const app={manifest:{rust:true}};
const env={EXACT_UPDATE_RECEIPT:record,EXACT_UPDATE_TRUST:'production',EXACT_BAKE_OUTPUT:resolve(root,'bake')};
const a=prepareRustBundle(app,'ios','aarch64-apple-ios',env);
const b=prepareRustBundle(app,'ios','aarch64-apple-ios',env);
assert.notEqual(a,b);
assert.equal(readFileSync(resolve(a,'app.module.wasm'),'utf8'),'wasm');
assert.throws(()=>prepareRustBundle({manifest:{rust:false}},'ios','aarch64-apple-ios',env),/incompatible/);
writeFileSync(resolve(blobs,assets[1].sha256),'bad');
assert.throws(()=>prepareRustBundle(app,'ios','aarch64-apple-ios',env),/differ from signed receipt/);
} finally {rmSync(root,{recursive:true,force:true});}
});
test('a release record finds its local blobs under either platform separator', () => {
const sha='a'.repeat(64);
assert.equal(localBlob('/p/.exact/streams/s/releases/1.json',sha,posix),`/p/.exact/blobs/${sha}`);
assert.equal(localBlob('C:\\p\\.exact\\streams\\s\\releases\\1.json',sha,win32),`C:\\p\\.exact\\blobs\\${sha}`);
assert.equal(localBlob('C:/p/.exact/streams/s/releases/1.json',sha,win32),`C:\\p\\.exact\\blobs\\${sha}`);
assert.equal(localBlob('/p/receipts/1.json',sha,posix),null);
assert.equal(localBlob('C:\\p\\receipts\\1.json',sha,win32),null);
});
test('tiered publication binds both executors to one target, plan and module digest', () => {
const app={id:'com.exact.tiered'},plan=Buffer.from('plan');
const wasm=Buffer.from([0,97,115,109,1,0,0,0]),native=Buffer.from('native image');
const compat={target:'aarch64-apple-darwin',inputs:{rustMode:'tiered',rustGrants:'',grantCeiling:''}};
const produced={plan,variants:{wasm:{receipt:rustReceipt(app,compat,plan,wasm,'wasm32-unknown-unknown','wasm'),bytes:wasm},native:{receipt:rustReceipt(app,compat,plan,native,compat.target,'native'),bytes:native}}};
const result=rustBundle(app,{plan:{...rustCard('app.plan',plan),bytes:plan},assets:[]},{compat,graph:{artifacts:[{name:'app.plan',requires:{sources:'embedded'}}]}},produced);
const [meta,image]=result.bundle.assets,receipt=JSON.parse(meta.bytes);
assert.equal(receipt.executor,'tiered');assert.equal(receipt.target,compat.target);
assert.equal(image.name,'rust/app.module.bin');
assert.equal(image.bytes.readUInt32LE(8),wasm.length);
assert.deepEqual(image.bytes.subarray(12,12+wasm.length),wasm);
assert.deepEqual(image.bytes.subarray(12+wasm.length),native);
assert.equal(receipt.module.sha256,image.sha256);
assert.equal(result.build.graph.artifacts[0].requires.rustMode,'tiered');
const files=rustFiles({plan,variants:{...produced.variants,tiered:{receipt,bytes:image.bytes}}});
assert.equal(rustCards(files).tiered.target,compat.target);
files.set(`rust/tiered/${compat.target}/app.module.bin`,Buffer.from('changed native'));
assert.throws(()=>rustCards(files),/does not match/);
});
test('tiered mode inherits ordinary environment and platform overrides', async () => {
const {rustPolicy}=await import('./app.mjs');
const manifest={rust:{platforms:{macos:{dev:'tiered',prod:'native'},linux:{mode:'tiered',prod:false}}}};
assert.equal(rustPolicy(manifest,'macos'),'tiered');
assert.equal(rustPolicy(manifest,'macos','prod'),'native');
assert.equal(rustPolicy(manifest,'linux'),'tiered');
assert.equal(rustPolicy(manifest,'linux','prod'),'off');
assert.equal(rustPolicy(manifest,'ios'),'wasm');
assert.equal(rustPolicy(manifest,'web'),'browser');
for(const platform of ['web','ios'])assert.throws(()=>rustPolicy({rust:'tiered'},platform),/unavailable/);
});
// Two throwaway self-signed identities in a private keychain, never the
// machine's own. One explicit designated requirement makes the CDHash the same
// under both certificates, so only the leaf decides that case.
test.skipIf(process.platform !== 'darwin')('a published module signature stands only for the same code and certificate', () => {
const dir=mkdtempSync(resolve(tmpdir(),'exact-signature-test-')), keychain=resolve(dir,'test.keychain-db');
// macOS's own LibreSSL: OpenSSL 3 (Homebrew's, first on many PATHs) writes a
// PKCS#12 that `security import` rejects as a failed MAC.
const OPENSSL='/usr/bin/openssl';
const sh=(cmd,args)=>{const r=spawnSync(cmd,args,{cwd:dir,encoding:'utf8'});assert.equal(r.status,0,`${cmd} ${args[0]}: ${r.stderr}`);return r.stdout;};
try {
sh('security',['create-keychain','-p','exact',keychain]);
sh('security',['unlock-keychain','-p','exact',keychain]);
for (const name of ['A','B']) {
sh(OPENSSL,['req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',`${name}.key`,'-out',`${name}.crt`,'-subj',`/CN=Exact Test Signing ${name}`,
'-addext','extendedKeyUsage=critical,codeSigning','-addext','keyUsage=critical,digitalSignature','-addext','basicConstraints=critical,CA:false']);
sh(OPENSSL,['pkcs12','-export','-out',`${name}.p12`,'-inkey',`${name}.key`,'-in',`${name}.crt`,'-passout','pass:exact']);
sh('security',['import',`${name}.p12`,'-k',keychain,'-P','exact','-T','/usr/bin/codesign']);
}
sh('security',['set-key-partition-list','-S','apple-tool:,apple:,codesign:','-s','-k','exact',keychain]);
const dylib=(value)=>{writeFileSync(resolve(dir,'probe.c'),`int exact_probe(void){return ${value};}\n`);sh('clang',['-dynamiclib','-o','probe.dylib','probe.c']);return readFileSync(resolve(dir,'probe.dylib'));};
let n=0;
const sign=(bytes,identity)=>{
const path=resolve(dir,`s${n++}`,'module.dylib');mkdirSync(resolve(path,'..'));writeFileSync(path,bytes);
sh('codesign',['--force','--timestamp=none','--options','runtime','-r=designated => identifier "module"',...(identity?['--keychain',keychain,'--sign',`Exact Test Signing ${identity}`]:['--sign','-']),path]);
return readFileSync(path);
};
const code=dylib(7), changed=dylib(8);
const published=sign(code,'A'), again=sign(code,'A');
assert.deepEqual(publishedSignature(again,published),published,'the same code and certificate reuse the published signature');
assert.equal(publishedSignature(sign(changed,'A'),published),null,'changed code signs afresh');
assert.equal(publishedSignature(sign(code,'B'),published),null,'another certificate signs afresh, though the CDHash matches');
assert.equal(publishedSignature(sign(code,null),published),null,'an ad-hoc signature has no certificate to match');
const tampered=Buffer.from(published), at=tampered.indexOf(Buffer.from([0xe0,0x00,0x80,0x52]));
assert.ok(at>0,'the fixture returns 7 with mov w0, #7');
Buffer.from([0x20,0x01,0x80,0x52]).copy(tampered,at);
assert.equal(publishedSignature(again,tampered),null,'code changed under an intact CodeDirectory does not verify');
for (const missing of [null,Buffer.from('not a module'),published.subarray(0,4096)]) assert.equal(publishedSignature(again,missing),null,'a missing or unreadable release signs afresh');
const wasm=Buffer.concat([Buffer.from([0,97,115,109,1,0,0,0]),Buffer.from('module')]);
assert.deepEqual(tieredNative(tieredBytes(wasm,published)),published);
assert.equal(tieredNative(Buffer.from('EXLT')),null);
} finally {
spawnSync('security',['delete-keychain',keychain]);
rmSync(dir,{recursive:true,force:true});
}
}, 120000);
test('Rust artifact discovery accepts Cargo paths from Windows and Unix', () => {
const wasm = String.raw`C:\My Apps\target\rust-modules\wasm32-unknown-unknown\debug\probe.wasm`;
const dll = String.raw`C:\My Apps\target\rust-modules\x86_64-pc-windows-msvc\debug\probe.dll`;
const unix = '/my apps/target/wasm32-unknown-unknown/debug/probe.wasm';
assert.equal(rustArtifact([dll, wasm], 'wasm32-unknown-unknown'), wasm);
assert.equal(rustArtifact([wasm, dll], 'x86_64-pc-windows-msvc'), dll);
assert.equal(rustArtifact([dll, unix], 'wasm32-unknown-unknown'), unix);
assert.equal(rustArtifact([unix.replace('/wasm32-', '/not-wasm32-')], 'wasm32-unknown-unknown'), undefined);
});
test('external Rust modules have identical bytes in relocated cold source captures', async () => {
const root = resolve(import.meta.dir, '..');
mkdirSync(resolve(root, 'target'), { recursive: true });
const dir = mkdtempSync(resolve(root, 'target/rust-reproducible-'));
const write = (path, bytes) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, bytes); };
const previousHelper = process.env.EXACT_FILESYSTEM_HELPER;
const previousTarget = process.env.CARGO_TARGET_DIR;
try {
const helper = filesystemHelper();
delete process.env.CARGO_TARGET_DIR;
// Copy the builder's imports too: each capture must resolve its own Exact checkout and path dependencies.
const pending = ['scripts/rust.mjs'], sources = new Map(), parser = new Bun.Transpiler({ loader: 'js' });
while (pending.length) {
const path = pending.pop();
if (sources.has(path)) continue;
const text = readFileSync(resolve(root, path), 'utf8');
sources.set(path, text);
for (const request of parser.scanImports(text.replace(/^#![^\n]*/, ''))) if (request.kind === 'import-statement' && request.path.startsWith('.')) {
pending.push(relative(root, resolve(root, dirname(path), request.path)));
}
}
const builds = [];
for (const name of ['left', 'right']) {
const sourceRoot = resolve(dir, name), sdk = resolve(sourceRoot, 'exact2'), workspace = resolve(sourceRoot, 'app');
for (const [path, text] of sources) write(resolve(sdk, path), text);
for (const path of ['rust-toolchain.toml', 'scripts/rustc/exact-rustc', 'logic/abi/src/lib.rs']) write(resolve(sdk, path), readFileSync(resolve(root, path)));
chmodSync(resolve(sdk, 'scripts/rustc/exact-rustc'), 0o755);
const capturedHelper = resolve(sdk, 'target/exact-filesystem-tool', basename(helper));
mkdirSync(dirname(capturedHelper), { recursive: true }); copyFileSync(helper, capturedHelper);
process.env.EXACT_FILESYSTEM_HELPER = capturedHelper;
write(resolve(sdk, 'Cargo.toml'), '[workspace]\nmembers=["dep"]\n');
write(resolve(sdk, 'dep/Cargo.toml'), '[package]\nname="capture-dep"\nversion="0.1.0"\nedition="2021"\n');
write(resolve(sdk, 'dep/src/lib.rs'), 'pub fn path() -> &\'static str { file!() }\n');
write(resolve(sourceRoot, 'shared/Cargo.toml'), '[workspace]\n[package]\nname="outside-dep"\nversion="0.1.0"\nedition="2021"\n');
write(resolve(sourceRoot, 'shared/src/lib.rs'), 'pub fn path() -> &\'static str { file!() }\n');
write(resolve(workspace, 'Cargo.toml'), '[workspace]\n[package]\nname="capture-module"\nversion="0.1.0"\nedition="2021"\n[lib]\ncrate-type=["cdylib"]\n[dependencies]\ncapture-dep={path="../exact2/dep"}\noutside-dep={path="../shared"}\n');
write(resolve(workspace, 'src/lib.rs'), '#[no_mangle] pub extern "C" fn path_byte(at: usize) -> u8 { capture_dep::path().as_bytes()[at] }\n#[no_mangle] pub extern "C" fn outside_path_byte(at: usize) -> u8 { outside_dep::path().as_bytes()[at] }\n');
write(resolve(workspace, 'app.contract'), 'component App\n view\n');
write(resolve(workspace, 'app.json'), '{}');
const app = { id: 'test.capture', dir: workspace, workspace, target: resolve(dir, name, 'target'), manifest: { rust: { module: { package: 'capture-module' } } } };
const { buildRust: build } = await import(resolve(sdk, 'scripts/rust.mjs'));
// The plan stays fixed while this test checks compilation and publication.
const compile = () => build(app, { profile: 'release', env: { ...process.env, CARGO_NET_OFFLINE: 'true', EXACT_SOURCE_ROOT: sourceRoot }, compat: { inputs: { rustGrants: '', grantCeiling: '' } },
baker: { bake: async args => writeFileSync(args[3], 'plan') } });
const first = await compile();
builds.push({ app, compile, first, sourceRoot });
}
const bytes = builds.map(b => b.first.variants.wasm.bytes);
for (let i = 0; i < builds.length; i++) assert.ok(!bytes[i].includes(Buffer.from(builds[i].sourceRoot)), 'module contains no capture path');
assert.ok(bytes[0].equals(bytes[1]), 'relocated SDK and external path dependencies must produce identical module bytes');
assert.deepEqual(builds[0].first.variants.wasm.receipt, builds[1].first.variants.wasm.receipt);
const origin = new DirectoryOrigin(resolve(dir, 'origin'));
const web = (name, module) => {
const out = resolve(dir, name);
write(resolve(out, 'app.js'), 'export const ready = true;\n');
write(resolve(out, 'app.module.wasm'), module);
return out;
};
await publishRoot({ origin, row: {}, web: web('first', bytes[0]) });
const row = async module => (await classify({ app: builds[1].app, opts: {}, origin, channel: 'prod',
snapshot: { commit: 'fixture', dirty: false, changes: [] }, release: 'fixture', web: web('next', module), compat: {}, platforms: [], wantOrigin: true })).rows[0];
assert.equal((await row(bytes[1])).action, 'current');
write(resolve(builds[1].sourceRoot, 'shared/src/lib.rs'), 'pub fn path() -> &\'static str { "changed" }\n');
const changed = await builds[1].compile();
assert.equal((await row(changed.variants.wasm.bytes)).action, 'publish');
} finally {
if (previousHelper === undefined) delete process.env.EXACT_FILESYSTEM_HELPER; else process.env.EXACT_FILESYSTEM_HELPER = previousHelper;
if (previousTarget === undefined) delete process.env.CARGO_TARGET_DIR; else process.env.CARGO_TARGET_DIR = previousTarget;
rmSync(dir, { recursive: true, force: true });
}
}, 120000);
for (const configuration of ['string', 'array', 'cfg', 'build', 'forced-encoded']) for (const encoded of [true, false]) test(`Rust modules build with spaces, ${encoded ? 'encoded' : 'configured'} flags and ${configuration} target flags`, async () => {
const root = resolve(import.meta.dir, '../target');
mkdirSync(root, {recursive:true});
const dir = mkdtempSync(resolve(root, 'rust app '));
try {
writeFileSync(resolve(dir, 'Cargo.toml'), '[workspace]\n[package]\nname="path-probe"\nversion="0.1.0"\nedition="2021"\n[lib]\npath="lib.rs"\ncrate-type=["cdylib"]\n');
writeFileSync(resolve(dir, 'lib.rs'), `#[cfg(not(${encoded && configuration !== 'forced-encoded' ? 'probe="a b"' : 'probe_config'}))] compile_error!("selected flag lost");\n#[no_mangle] pub extern "C" fn probe() -> u32 {42}\n`);
mkdirSync(resolve(dir, '.cargo'));
const configured = configuration !== 'array' ? '"--cfg=probe_config"' : '["--cfg=probe_config"]';
const tables = configuration === 'build' ? ['build'] : configuration === 'cfg' ? [`target.'cfg(all(any(unix, target_arch = "wasm32"), not(target_os = "windows")))'`] : ['target.wasm32-unknown-unknown', `target.${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-apple-darwin`];
writeFileSync(resolve(dir, '.cargo/config.toml'), configuration === 'forced-encoded' ? '[env]\nCARGO_ENCODED_RUSTFLAGS = {value="--cfg=probe_config", force=true}\n' : tables.map(table => `[${table}]\nrustflags=${configured}\n`).join(''));
writeFileSync(resolve(dir, 'app.contract'), '');
writeFileSync(resolve(dir, 'app.json'), '{}');
const app = {id:'com.exact.path-probe',dir,workspace:dir,target:resolve(dir,'target'),manifest:{rust:{module:{package:'path-probe'}}}};
const env = {...process.env, CARGO_ENCODED_RUSTFLAGS:'--cfg\x1fprobe="a b"\x1f--check-cfg=cfg(probe,values("a b"))'};
for (const name of Object.keys(env)) if (name === 'RUSTFLAGS' || /^CARGO_(TARGET_.*_RUSTFLAGS|BUILD_RUSTFLAGS)$/.test(name)) delete env[name];
if (!encoded) delete env.CARGO_ENCODED_RUSTFLAGS;
const built = await buildRust(app, {env, compat:{inputs:{rustGrants:'',grantCeiling:''}},
nativeTarget:process.platform === 'darwin' ? `${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-apple-darwin` : null,
// This regression exercises compilation and artifact discovery; baking is independent of the paths Cargo sees.
baker:{bake:async args => writeFileSync(args[3], 'plan')},
});
const {instance} = await WebAssembly.instantiate(built.variants.wasm.bytes);
assert.equal(instance.exports.probe(), 42);
if (process.platform === 'darwin') assert.ok(built.variants.native.bytes.length > 0);
for (const target of ['wasm32-unknown-unknown', ...(process.platform === 'darwin' ? [`${process.arch === 'arm64' ? 'aarch64' : 'x86_64'}-apple-darwin`] : [])]) {
const fingerprints = resolve(app.target, 'rust-modules', target, 'debug/.fingerprint');
const crate = readdirSync(fingerprints).find(name => name.startsWith('path-probe-'));
const flags = JSON.parse(readFileSync(resolve(fingerprints, crate, 'lib-path_probe.json'))).rustflags;
assert.ok(flags.includes(`--remap-path-prefix=${app.target}/rust-modules=/rust-modules`));
assert.equal(flags.includes('-Clink-arg=-Wl,-install_name,@rpath/app.module.dylib'), target.includes('apple'));
if (target.includes('apple')) assert.ok(flags.some(flag => flag.startsWith('--cfg=exact_apple_deployment_targets=')));
}
} finally {rmSync(dir, {recursive:true,force:true});}
}, 120_000);