READ-ONLY PACKAGE PREVIEW

astro-developer/examples/run_fixture.mjs

Version 28e74103fe3d.bb1 · MIT. This preview displays packaged text and does not execute code. Treat the contents as untrusted instructions.

← Return to resource and package checksum

import assert from 'node:assert/strict';
import {readFile, writeFile, mkdir} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {stripTypeScriptTypes} from 'node:module';
import {spawnSync} from 'node:child_process';
import {fileURLToPath, pathToFileURL} from 'node:url';
import path from 'node:path';

const root = fileURLToPath(new URL('../', import.meta.url));
const repo = path.join(root, 'repository-context');
const generated = path.join(root, '.generated');
await mkdir(generated, {recursive:true});
const sha = value => createHash('sha256').update(value).digest('hex');
const records = [];
const blocks = [];
const read = name => readFile(path.join(root, name), 'utf8');
const env = {...process.env, ASTRO_TELEMETRY_DISABLED:'1', NODE_NO_WARNINGS:'1', CI:'1'};
const observe = (name, actual, expected) => {
  assert.deepEqual(actual, expected, name);
  records.push({name, status:'passed', actual, expected});
};
const block = async (file, index) => {
  const text = await read('repository-context/.agents/skills/astro-developer/'+file);
  const all = [...text.matchAll(/```([^\n]*)\n([\s\S]*?)```/g)];
  const raw = all[index][2];
  if (!blocks.some(x=>x.source===file && x.block_index===index)) {
    blocks.push({source:file, block_index:index, block_sha256:sha(raw), language:all[index][1]});
  }
  return raw;
};
const run = (args, cwd=root, input) => {
  const result = spawnSync(process.execPath, args, {cwd, input, env, encoding:'utf8', timeout:180000, maxBuffer:8*1024*1024});
  if (result.error) throw result.error;
  return result;
};

// Original examples remain unchanged before Node's documented type erasure.
// Prefixes provide assert/it/require; the appended harness supplies synthetic data.
const prefix = "import assert from 'node:assert/strict';\nimport {it} from 'node:test';\nimport {createRequire} from 'node:module';\nconst require=createRequire(import.meta.url);\n";
const modules = {};
for (const index of [2,5,8]) {
  const raw = await block('testing.md',index);
  const output = prefix+stripTypeScriptTypes(raw,{mode:'strip'});
  modules[index] = path.join(generated,`original-testing-${index}.mjs`);
  await writeFile(modules[index],output);
}
const nativeChecks = `
import assert from 'node:assert/strict';
import {writeFile,readFile} from 'node:fs/promises';
import * as config from './original-testing-2.mjs';
import * as markdown from './original-testing-5.mjs';
import * as manifest from './original-testing-8.mjs';
const cases=[];
const check=(name,actual,expected)=>{assert.deepEqual(actual,expected,name);cases.push({name,status:'passed',actual,expected})};
const original={base:'/demo',nested:{enabled:true}};
const transformed=config.transformConfig(original);
check('config retains existing fields',transformed.base,'/demo');
check('config marks transformed output',transformed.transformed,true);
check('config does not add property to input',Object.hasOwn(original,'transformed'),false);
check('config returns a new object',transformed!==original,true);
check('config nested object remains shared',transformed.nested===original.nested,true);
await writeFile('synthetic-config.json',JSON.stringify({base:'/first'}));
config.processConfig('synthetic-config.json');
check('original coupled config function writes file',JSON.parse(await readFile('synthetic-config.json','utf8')),{base:'/first',transformed:true});
await writeFile('synthetic-config.json',JSON.stringify({base:'/second'}));
config.processConfigFile('synthetic-config.json');
check('original separated config infrastructure writes file',JSON.parse(await readFile('synthetic-config.json','utf8')),{base:'/second',transformed:true});
let missing;try{config.processConfigFile('missing-synthetic-file.json')}catch(error){missing=error.code}
check('config infrastructure propagates missing file',missing,'ENOENT');
const input='---\\ntitle: Test\\n---\\nTODO: Fix this';
check('original markdown keeps leading newline',markdown.transformMarkdownContent(input),'\\nNOTE: Fix this');
let absent;try{markdown.transformMarkdownContent('TODO: no frontmatter')}catch(error){absent=error.name}
check('original markdown without delimiters throws',absent,'TypeError');
await writeFile('synthetic-markdown.md',input);
await markdown.processMarkdownFile('synthetic-markdown.md');
check('original separated markdown infrastructure writes file',await readFile('synthetic-markdown.md','utf8'),'\\nNOTE: Fix this');
await writeFile('synthetic-markdown.md',input);
await markdown.processMarkdown('synthetic-markdown.md');
check('original coupled markdown infrastructure writes file',await readFile('synthetic-markdown.md','utf8'),'\\nNOTE: Fix this');
const old={routes:[],version:1};const route={path:'/synthetic'};const next=manifest.addRouteToManifest(old,route);
check('pure manifest output contains route',next.routes.length,1);
check('pure manifest output increments version',next.version,2);
check('pure manifest retains original routes',old.routes.length,0);
check('pure manifest retains original version',old.version,1);
check('pure manifest returns distinct route array',next.routes!==old.routes,true);
check('pure manifest retains shared route object',next.routes[0]===route,true);
manifest.updateManifest(old,route);
check('coupled manifest mutates input',old.routes.length,1);
check('coupled manifest increments input version',old.version,2);
await writeFile('native-results.json',JSON.stringify(cases,null,2));
`;
await writeFile(path.join(generated,'native-checks.mjs'),nativeChecks);
const native = run(['--test','--test-reporter=tap',path.join(generated,'native-checks.mjs')],generated);
assert.equal(native.status,1, 'The original markdown unit assertion is an explicit expected failure');
assert.match(native.stdout, /# pass 1\b/);
assert.match(native.stdout, /# fail 1\b/);
assert.match(native.stdout, /transforms markdown content/);
assert.match(native.stdout, /adds route to manifest/);
records.push(...JSON.parse(await readFile(path.join(generated,'native-results.json'),'utf8')));
observe('unchanged original markdown unit assertion fails',native.status,1);
observe('unchanged original manifest unit assertion passes',/# pass 1\b/.test(native.stdout),true);
await writeFile(path.join(generated,'original-unit-test.tap'),native.stdout+native.stderr);

// Contrasting same-name implementations are documentation, not a runnable module.
const duplicate = stripTypeScriptTypes(await block('testing.md',6),{mode:'strip'});
const duplicatePath=path.join(generated,'duplicate-build-routes.mjs');
await writeFile(duplicatePath,duplicate);
const parse=run(['--check',duplicatePath]);
observe('unchanged dual buildRoutes example fails ESM parse',parse.status,1);
assert.match(parse.stderr,/SyntaxError/);

// Use the exact upstream Biome configuration. All diagnostics remain recorded;
// absence of noNodejsModules is not a claim that other lint rules passed.
const lintRoot=path.join(generated,'lint-project');await mkdir(lintRoot,{recursive:true});
await writeFile(path.join(lintRoot,'biome.jsonc'),await readFile(path.join(repo,'biome.jsonc')));
const biome=path.join(root,'node_modules/@biomejs/biome/bin/biome');
const nodeImports=await block('constraints.md',1);
const lintResults=[];
const lint = async (name, source, expectedNodeDiagnostics) => {
  const dest=path.join(lintRoot,name);await mkdir(path.dirname(dest),{recursive:true});await writeFile(dest,source);
  const result=run([biome,'lint','--vcs-enabled=false','--reporter=json',name],lintRoot);
  const start=result.stdout.indexOf('{'); assert.ok(start>=0, result.stderr);
  const report=JSON.parse(result.stdout.slice(start));
  const diagnostics=report.diagnostics;
  const nodeErrors=diagnostics.filter(d=>d.category==='lint/correctness/noNodejsModules').length;
  observe('Biome Node API rule: '+name,nodeErrors,expectedNodeDiagnostics);
  lintResults.push({path:name,source_sha256:sha(source),exit_code:result.status,
    diagnostics:diagnostics.map(d=>({category:d.category,severity:d.severity})),node_api_diagnostics:nodeErrors});
};
for (const name of ['packages/astro/src/runtime/server/sample.ts','packages/astro/src/runtime/client/sample.ts',
  'packages/astro/src/vite-plugin-sample/runtime.ts','packages/astro/src/core/render/runtime-utils.ts']) {
  await lint(name,nodeImports,5);
}
await lint('packages/astro/src/vite-plugin-sample/plugin.ts',nodeImports,0);
await lint('packages/astro/src/core/build/sample.ts',nodeImports,0);

// Observe the original bad plugin's emitted code without executing its file read.
const badRaw=await block('constraints.md',4);
const badPath=path.join(generated,'original-bad-plugin.mjs');await writeFile(badPath,badRaw);
const bad=await import(pathToFileURL(badPath));
const badGenerated=bad.myVitePlugin().load.handler().code;
observe('original bad plugin emits Node import',badGenerated.includes("from 'node:fs'"),true);
await lint('packages/astro/src/runtime/server/generated-bad.ts',badGenerated,1);

// Execute unchanged original file-reading plugin hooks on a synthetic file.
for (const index of [3,6]) {
  const raw=await block('constraints.md',index);const dest=path.join(generated,`original-plugin-${index}.mjs`);
  await writeFile(dest,raw);const module=await import(pathToFileURL(dest));
  const sample=path.join(generated,`synthetic-plugin-${index}.txt`);await writeFile(sample,'BB synthetic file');
  observe('original file-reading plugin '+index+' returns synthetic source',(await module.myVitePlugin().load.handler(sample)).code,'BB synthetic file');
}

// Two real standalone Astro builds use the unchanged build-time JSON plugin.
// This verifies output separation, not the monorepo loadFixture/ESM-cache problem.
const buildRaw=await block('constraints.md',7);
const project=path.join(generated,'astro-project');await mkdir(path.join(project,'src/pages'),{recursive:true});
const page=`---
import config from 'virtual:my-config';
const canonical = new URL('/', Astro.site).href;
---
<!doctype html><html lang="en"><head><meta charset="UTF-8"/><title>{config.title}</title><link rel="canonical" href={canonical}/></head><body><h1>{config.title}</h1><p>{config.nested.label}</p></body></html>`;
await writeFile(path.join(project,'src/pages/index.astro'),page);
await writeFile(path.join(project,'package.json'),JSON.stringify({name:'bb-synthetic-astro-page',private:true,type:'module'}));
const buildProgram=`import {build} from 'astro';\nimport {writeFile} from 'node:fs/promises';\nimport {pathToFileURL} from 'node:url';\n${buildRaw}\nawait build({root:pathToFileURL(process.cwd()+'/'),configFile:false,site:'https://fixture.example.test',outDir:'./'+process.argv[2]+'/',cacheDir:'./.astro-cache-'+process.argv[2]+'/',vite:{plugins:[myVitePlugin()]},logLevel:'silent'});\nawait writeFile('network-'+process.argv[2]+'.json',JSON.stringify({network_attempts:globalThis.__bbNetworkAttempts}));\n`;
const buildPath=path.join(generated,'original-build-plugin.mjs');await writeFile(buildPath,buildProgram);
const buildReports=[];
let firstSha;
for (const [index,label] of [[1,'Alpha <script>window.BAD=true</script>'],[2,'Beta fixture']]) {
  const json={title:label,nested:{label:'Independent BB Skills fixture'},enabled:true};
  await writeFile(path.join(project,'config.json'),JSON.stringify(json));
  const result=run(['--import',pathToFileURL(path.join(root,'examples/deny_network.mjs')).href,buildPath,'output-'+index],project);
  assert.equal(result.status,0,result.stdout+result.stderr);
  const html=await readFile(path.join(project,`output-${index}/index.html`),'utf8');
  observe('real Astro build '+index+' renders supplied title',html.includes(index===1?'Alpha &lt;script&gt;':'Beta fixture'),true);
  observe('real Astro build '+index+' has English HTML',html.includes('lang="en"'),true);
  observe('real Astro build '+index+' has canonical',html.includes('https://fixture.example.test/'),true);
  observe('real Astro build '+index+' has single H1',(html.match(/<h1[\s>]/g)||[]).length,1);
  const network=JSON.parse(await readFile(path.join(project,`network-output-${index}.json`),'utf8'));
  observe('real Astro build '+index+' attempts no JS socket or HTTP connection',network.network_attempts,0);
  if (index===1) {
    observe('real Astro output escapes synthetic script',html.includes('<script>window.BAD=true</script>'),false);
    firstSha=sha(html);
  }
  buildReports.push({out_dir:'output-'+index,html_sha256:sha(html),source_input_sha256:sha(JSON.stringify(json)),network_attempts:network.network_attempts});
}
observe('second Astro build preserves first output',sha(await readFile(path.join(project,'output-1/index.html'),'utf8')),firstSha);
const portable='export default '+JSON.stringify({title:'Independent fixture',nested:{label:'Synthetic'},enabled:true});
await lint('packages/astro/src/runtime/server/generated-good.ts',portable,0);

const sourceHashes={};
for (const name of ['examples/run_fixture.mjs','examples/deny_network.mjs','package.json','package-lock.json',
  'repository-context/biome.jsonc','repository-context/.agents/skills/astro-developer/testing.md',
  'repository-context/.agents/skills/astro-developer/constraints.md']) {
  sourceHashes[name]=sha(await readFile(path.join(root,name)));
}
const result={executed_at:new Date().toISOString(),versions:{node:process.version,
  astro:JSON.parse(await read('node_modules/astro/package.json')).version,
  biome:JSON.parse(await read('node_modules/@biomejs/biome/package.json')).version},
  observations:records.length,cases:records,native_blocks:blocks,lint_results:lintResults,build_results:buildReports,
  unchanged_original_unit_tests:{passed:1,failed_expected:1,expected_failure:'Markdown example keeps a leading newline, unlike its original expected string',tap_sha256:sha(native.stdout+native.stderr)},
  source_hashes:sourceHashes,synthetic_setup:'Independent wrappers and inputs; full upstream source blocks preserved before Node type erasure; VCS lookup disabled only by the Biome CLI flag.',
  runtime_tested:false,ai_client_executed:false,production_tested:false,paid_api_used:false,
  real_credentials_used:false,monorepo_test_runner_used:false,esm_cache_pollution_reproduced:false,
  edge_runtime_executed:false,full_typescript_typecheck_ran:false,astro_build_api_experimental:true,
  javascript_network_preload_denied_build_connections:true,
  resolved_independent_setup_issue:'On Windows, the Node --import preloader requires a file:// URL rather than a C: path.'};
assert.equal(records.length,new Set(records.map(r=>r.name)).size);
await writeFile(path.join(root,'examples/fixture-evidence.json'),JSON.stringify(result,null,2));
console.log(JSON.stringify({observations:records.length,native_blocks:blocks.length,builds:buildReports.length,
  original_unit_tests:result.unchanged_original_unit_tests,versions:result.versions,full_skill_runtime_tested:false}));