@wildshard/sdk 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIDE.md +36 -37
- package/docs/api/EXPORT-TIERS.md +204 -0
- package/lint/export-tiers.json +176 -0
- package/lint/sdk-plugin.mjs +16 -4
- package/package.json +3 -2
- package/scripts/bake-data-maps.mjs +10 -4
- package/scripts/bake-entry-programs.mjs +28 -20
- package/scripts/build-shardfiles.mjs +6 -5
- package/scripts/capture-hero.mjs +56 -17
- package/scripts/chromium-keychain-check.mjs +4 -2
- package/scripts/chromium-keychain.mjs +3 -1
- package/scripts/export-tiers.mjs +57 -0
- package/scripts/preparation-preview.mjs +45 -0
- package/scripts/prepare-product.mjs +22 -4
- package/scripts/scratch-dir.mjs +95 -0
- package/scripts/wildshard.mjs +21 -0
- package/skills/wildshard/SKILL.md +2 -3
- package/skills/wildshard-goldens/SKILL.md +6 -7
- package/skills/wildshard-mockup-to-model/SKILL.md +2 -2
- package/src/cli/help.ts +7 -5
- package/src/sharddev/bake/placeholders.ts +40 -13
- package/src/sharddev/checkProject.ts +4 -1
- package/src/sharddev/cli.ts +22 -5
- package/src/sharddev/clientPage.ts +19 -0
- package/src/sharddev/cookInput.ts +2 -1
- package/src/sharddev/dev.ts +21 -12
- package/src/sharddev/devClient.ts +118 -0
- package/src/sharddev/newProject.ts +1 -3
- package/src/sharddev/project.ts +7 -4
- package/src/sharddev/refusals.ts +1 -1
- package/src/sharddev/shardSource.ts +16 -0
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// G508: normal generation job; reads only declared JSON, terrain and GLB data.
|
|
3
3
|
import { createRequire } from 'node:module';
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
5
|
-
import { dirname, resolve, sep } from 'node:path';
|
|
5
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
6
6
|
import { pathToFileURL } from 'node:url';
|
|
7
7
|
import { MapRaster } from '../src/sharddev/bake/mapRaster.ts';
|
|
8
|
+
import { isRepoSource, shardFolderName } from '../src/sharddev/shardSource.ts';
|
|
8
9
|
import { readMapGeometry, stylizeMap } from '@wildshard/engine/scripts/map-painter.mjs';
|
|
9
10
|
import { MAP_METRES, mapPixelHash, mapSettingsPath, mapStampPath, mapShards, mapTilesHash } from '@wildshard/engine/scripts/map-hash.mjs';
|
|
10
11
|
|
|
@@ -19,7 +20,10 @@ export async function rasterDataMap(settings, data, { output, glbs, label = 'map
|
|
|
19
20
|
const raster = new MapRaster(1000, settings, readMapGeometry);
|
|
20
21
|
const { paintMapGeometry } = await import('../src/sharddev/bake/mapScenes.ts');
|
|
21
22
|
const source = data.input;
|
|
22
|
-
|
|
23
|
+
// A model URL is a file under the repo's public/. SA44: a caller that knows the shard's place passes `model`; the
|
|
24
|
+
// default is `src/shards/<slug>/`'s, three folders below the repo root.
|
|
25
|
+
const model = data.model ?? (url => source(`../../../public${url}`));
|
|
26
|
+
await paintMapGeometry(raster, settings, { input: source, model, json: data.json, bytes: data.bytes }, { output, glbs, label });
|
|
23
27
|
const own = output === undefined ? undefined : settings.outputs?.[output];
|
|
24
28
|
const style = own?.style ?? settings.style;
|
|
25
29
|
const pixels = stylizeMap(raster, style);
|
|
@@ -35,7 +39,9 @@ export async function rasterDataMap(settings, data, { output, glbs, label = 'map
|
|
|
35
39
|
/** Every repository file by its path, as a shard's pure map producer reads its inputs. @param {string} root */
|
|
36
40
|
export const repoSource = root => path => new Uint8Array(readFileSync(resolve(root, path)));
|
|
37
41
|
export async function paintDataMap(root, slug, { output, glbs, sources } = {}) {
|
|
38
|
-
|
|
42
|
+
// SA44: a single-shard repo keeps its source at src/, one folder below the root, not src/shards/<slug>/.
|
|
43
|
+
const single = resolve(root, 'src'), dir = isRepoSource(single) && shardFolderName(single) === slug ? single : resolve(root, 'src/shards', slug);
|
|
44
|
+
const settings = json(mapSettingsPath(dir)), toPublic = relative(dir, resolve(root, 'public')).split(sep).join('/');
|
|
39
45
|
const tilesHash = mapTilesHash(dir);
|
|
40
46
|
const declared = settings.inputs.map(file => resolve(dir, file));
|
|
41
47
|
const input = file => {
|
|
@@ -46,7 +52,7 @@ export async function paintDataMap(root, slug, { output, glbs, sources } = {}) {
|
|
|
46
52
|
const source = file => sources?.get(file) ?? input(file);
|
|
47
53
|
const readBytes = file => { const value = source(file); return value instanceof Uint8Array ? value : readFileSync(value); };
|
|
48
54
|
const rows = file => JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(readBytes(file)));
|
|
49
|
-
const { raster, pixels } = await rasterDataMap(settings, { input: source, json: rows, bytes: readBytes }, { output, glbs, label: slug });
|
|
55
|
+
const { raster, pixels } = await rasterDataMap(settings, { input: source, model: url => source(`${toPublic}${url}`), json: rows, bytes: readBytes }, { output, glbs, label: slug });
|
|
50
56
|
const own = output === undefined ? undefined : settings.outputs?.[output], style = own?.style ?? settings.style, painter = settings.painter;
|
|
51
57
|
const product = output ?? slug, image = resolve(root, 'public/assets', product, 'map/top.webp');
|
|
52
58
|
mkdirSync(dirname(image), { recursive: true });
|
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
// Shaders step asks for it. A stale list costs only wasted links: re-bake after a shader or material change.
|
|
6
6
|
// node scripts/bake-entry-programs.mjs --base <served build URL> [--check] <slug>...
|
|
7
7
|
// --check: write nothing; print how many of the build's entry programs the committed list already holds.
|
|
8
|
+
// --inline (SA43): the page carries the candidate inline (`wildshard prepare`'s own preview of engine's preparation
|
|
9
|
+
// client); it enters at `?skipintro` as `wildshard dev` does, with the page's service worker off (`sw=0`), so every read
|
|
10
|
+
// reaches the recorder from the network.
|
|
8
11
|
// Run through scripts/browser-lane.sh.
|
|
9
12
|
import {webkit,devices} from 'playwright';
|
|
10
13
|
import {existsSync,readFileSync,writeFileSync} from 'node:fs';
|
|
@@ -14,7 +17,7 @@ import {loadingCardIndex} from '@wildshard/engine/scripts/loading-benchmark/cata
|
|
|
14
17
|
import {preparationSaveSeed} from './preparation-seed.mjs';
|
|
15
18
|
|
|
16
19
|
const args=process.argv.slice(2), flag=name=>{const at=args.indexOf(name);if(at===-1)return null;const [value]=args.splice(at,2).slice(1);return value;};
|
|
17
|
-
const base=flag('--base'), output=flag('--out'), wantedHeader=flag('--header'), title=flag('--title'), check=args.includes('--check'), slugs=args.filter(arg=>!arg.startsWith('--'));
|
|
20
|
+
const base=flag('--base'), output=flag('--out'), wantedHeader=flag('--header'), title=flag('--title'), check=args.includes('--check'), inline=args.includes('--inline'), slugs=args.filter(arg=>!arg.startsWith('--'));
|
|
18
21
|
if(base===null||slugs.length===0)throw new Error('usage: bake-entry-programs.mjs --base <url> [--check] <slug>...');
|
|
19
22
|
|
|
20
23
|
/** Every program linked between the tap and control, in link order (the page's own WebGL2 calls, read in place). */
|
|
@@ -58,26 +61,31 @@ async function record(browser,slug){
|
|
|
58
61
|
for(const file of manifest.files??[])if(typeof file.hash==='string')hashes.add(file.hash);
|
|
59
62
|
}));
|
|
60
63
|
});
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const matches=title===null?[]:names.flatMap((name,index)=>name.toLowerCase().includes(title.toLowerCase())?[index]:[]);
|
|
65
|
-
if(matches.length>1)throw new Error(`Candidate card ambiguous: ${title}`);
|
|
66
|
-
if(title!==null&&matches.length===0){
|
|
67
|
-
// Grid-only products have no standalone picker card. Exercise the
|
|
68
|
-
// existing one-shot arrival contract, as the full-catalogue boot proof.
|
|
69
|
-
await context.addInitScript(({epoch,slug,title})=>{
|
|
70
|
-
if(new URL(location.href).searchParams.get('chunk')!==slug)return;
|
|
71
|
-
const prefix=epoch===0?'wildshard.save.v2.':`wildshard.save.v2@${epoch}.`;
|
|
72
|
-
const data=JSON.stringify({slug,name:title,mode:'enter',at:Date.now()});
|
|
73
|
-
sessionStorage.setItem(`${prefix}session`,JSON.stringify({keys:{titleArrival:{v:1,data},'travel.handoff':{v:1,data:{v:1,from:null,to:slug,mode:'enter',arrive:null,carry:[],at:Date.now()}}}}));
|
|
74
|
-
},{epoch,slug,title});
|
|
75
|
-
const arrival=new URL(base);arrival.searchParams.set('chunk',slug);
|
|
76
|
-
await page.goto(arrival.href,{waitUntil:'load'});
|
|
64
|
+
if(inline){
|
|
65
|
+
const entry=new URL(base);entry.searchParams.set('skipintro','');entry.searchParams.set('sw','0');
|
|
66
|
+
await page.goto(entry.href,{waitUntil:'load'});
|
|
77
67
|
}else{
|
|
78
|
-
await page.
|
|
79
|
-
|
|
80
|
-
await page.locator('.ws-menu-
|
|
68
|
+
await page.goto(base,{waitUntil:'load'});
|
|
69
|
+
await page.locator('.ws-main-select').click();
|
|
70
|
+
const names=await page.locator('.ws-menu-card b').allTextContents();
|
|
71
|
+
const matches=title===null?[]:names.flatMap((name,index)=>name.toLowerCase().includes(title.toLowerCase())?[index]:[]);
|
|
72
|
+
if(matches.length>1)throw new Error(`Candidate card ambiguous: ${title}`);
|
|
73
|
+
if(title!==null&&matches.length===0){
|
|
74
|
+
// Grid-only products have no standalone picker card. Exercise the
|
|
75
|
+
// existing one-shot arrival contract, as the full-catalogue boot proof.
|
|
76
|
+
await context.addInitScript(({epoch,slug,title})=>{
|
|
77
|
+
if(new URL(location.href).searchParams.get('chunk')!==slug)return;
|
|
78
|
+
const prefix=epoch===0?'wildshard.save.v2.':`wildshard.save.v2@${epoch}.`;
|
|
79
|
+
const data=JSON.stringify({slug,name:title,mode:'enter',at:Date.now()});
|
|
80
|
+
sessionStorage.setItem(`${prefix}session`,JSON.stringify({keys:{titleArrival:{v:1,data},'travel.handoff':{v:1,data:{v:1,from:null,to:slug,mode:'enter',arrive:null,carry:[],at:Date.now()}}}}));
|
|
81
|
+
},{epoch,slug,title});
|
|
82
|
+
const arrival=new URL(base);arrival.searchParams.set('chunk',slug);
|
|
83
|
+
await page.goto(arrival.href,{waitUntil:'load'});
|
|
84
|
+
}else{
|
|
85
|
+
await page.locator(`.ws-menu-dots i[data-i="${title===null?loadingCardIndex(names,slug):matches[0]}"]`).click();
|
|
86
|
+
// ENTER WORLD opens a fresh document and a fresh measured link list.
|
|
87
|
+
await page.locator('.ws-menu-play').click();
|
|
88
|
+
}
|
|
81
89
|
}
|
|
82
90
|
await page.waitForFunction(()=>window.__wildshard?.world?.hud?.entered===true&&!document.querySelector('.ws-load'),undefined,{timeout:240000});
|
|
83
91
|
const version=await(await page.request.get(new URL('/version.json',base).href)).json();
|
|
@@ -14,7 +14,7 @@ import { randomBytes } from 'node:crypto';
|
|
|
14
14
|
import { InputHashMemo } from '@wildshard/engine/scripts/bake-input-hashes.mjs';
|
|
15
15
|
import { productInputKey, productToolchainKey, matchingProductInputKey, publishProductInputs } from '@wildshard/engine/scripts/shardfile-inputs.mjs';
|
|
16
16
|
import { quietCli } from '@wildshard/engine/scripts/quiet-cli.mjs';
|
|
17
|
-
import { outputManifest, shardOutputs } from '@wildshard/engine/scripts/shard-outputs.mjs';
|
|
17
|
+
import { outputManifest, shardOutputs, shardSourceDir, shardSourceFolders } from '@wildshard/engine/scripts/shard-outputs.mjs';
|
|
18
18
|
import { usesProgramDiscovery } from '@wildshard/engine/scripts/program-discovery.mjs';
|
|
19
19
|
import { shardfileValidationRevision } from '@wildshard/engine/scripts/shardfile-validation-revision.mjs';
|
|
20
20
|
import { runShardBuild, runShardBuildPool } from './shard-build-pool.mjs';
|
|
@@ -45,7 +45,6 @@ async function buildShardfilesWork(root, { strict = [process.env.CI, process.env
|
|
|
45
45
|
const outputRoot = resolve(root, 'out');
|
|
46
46
|
// Discard the retired discovery artifact left by older builds.
|
|
47
47
|
rmSync(resolve(outputRoot, 'catalog.json'), { force: true });
|
|
48
|
-
const projects = resolve(root, 'src/shards');
|
|
49
48
|
let count = 0;
|
|
50
49
|
const stale = [], runtimeReport = [];
|
|
51
50
|
// A folder may emit many products. Its shared source closure and prerequisite
|
|
@@ -60,7 +59,9 @@ async function buildShardfilesWork(root, { strict = [process.env.CI, process.env
|
|
|
60
59
|
if (issues === undefined) { issues = runtimeCopyIssues(root, project); runtimeChecks.set(project, issues); }
|
|
61
60
|
return issues;
|
|
62
61
|
};
|
|
63
|
-
|
|
62
|
+
// SA42 (SA16's rule): a single-shard repo's source is `src/` (its folder named by its slug), a multi-shard repo's is
|
|
63
|
+
// `src/shards/<folder>/`. The engine's shard-outputs owns the layout, so every product helper below agrees with it.
|
|
64
|
+
const folders = shardSourceFolders(root, ['shard.config.ts']).sort((a, b) => a.localeCompare(b));
|
|
64
65
|
// SF88g: a folder with declared outputs (scripts/shard-outputs.mjs) builds one product per output, each to out/<slug>
|
|
65
66
|
const products = folders.flatMap(folder => (shardOutputs(root, folder) ?? [{ slug: folder }]).map(row => ({ name: row.slug, folder, output: row.slug === folder ? undefined : row.slug })));
|
|
66
67
|
const built = products.map(row => row.name).sort((a, b) => a.localeCompare(b));
|
|
@@ -72,7 +73,7 @@ async function buildShardfilesWork(root, { strict = [process.env.CI, process.env
|
|
|
72
73
|
}
|
|
73
74
|
for (const slug of scope ?? only ?? []) if (!built.includes(slug)) throw new Error(`wildshard build: --shard=${slug} is not an output this repo builds (${built.join(', ')})`);
|
|
74
75
|
const bound = (only === undefined || strict ? [] : products).filter(({ folder, output }) => {
|
|
75
|
-
const manifest = resolve(
|
|
76
|
+
const manifest = resolve(shardSourceDir(root, folder), 'manifest.json');
|
|
76
77
|
if (!existsSync(manifest)) return false;
|
|
77
78
|
const row = output === undefined ? undefined : shardOutputs(root, folder)?.find(entry => entry.slug === output);
|
|
78
79
|
return usesProgramDiscovery(row === undefined ? JSON.parse(readFileSync(manifest, 'utf8')) : outputManifest(root, folder, row));
|
|
@@ -98,7 +99,7 @@ async function buildShardfilesWork(root, { strict = [process.env.CI, process.env
|
|
|
98
99
|
await runShardBuildPool(ordered, async ({ name, folder, output }, signal) => {
|
|
99
100
|
if (scope !== undefined && !scope.includes(name)) return;
|
|
100
101
|
const buildOne = args => build === runWildshard ? runShardBuild(args, signal, report=>{counters.merge(report);}) : build(args);
|
|
101
|
-
const project =
|
|
102
|
+
const project = shardSourceDir(root, folder);
|
|
102
103
|
try {
|
|
103
104
|
const started = performance.now();
|
|
104
105
|
const map = productMapInput(project, output), expected = map?.tilesHash ?? null;
|
package/scripts/capture-hero.mjs
CHANGED
|
@@ -4,19 +4,20 @@
|
|
|
4
4
|
// content it shows. `wildshard build` refuses a cut whose stamp no longer matches the content (src/cli/hero/hero.ts).
|
|
5
5
|
// Jake, 2026-11-12 17:14 Cancún: "you have to update the hero images for the templates."
|
|
6
6
|
//
|
|
7
|
-
// Serve the candidate first
|
|
8
|
-
//
|
|
7
|
+
// Serve the candidate first: `wildshard dev .` (SA17; its page enters the shard by `?skipintro`), or an engine build
|
|
8
|
+
// (engine: `scripts/serve-build.sh --shard <slug>`), and run this from the shard project root. A new project's
|
|
9
|
+
// generated `data:` card gets files of its own: `card/<slot>.jpg`, and manifest.json names them after the capture. Headless Chromium on the real GPU (Metal), never a visible window. The view is `hero.json`'s `camera`
|
|
9
10
|
// ({ pos: [x,y,z], look: [x,y,z], fov, center }, engine scripts/hero-shots.mjs's view shape) when the shard declares
|
|
10
11
|
// one, else the player's own spawn view. Sizes: thumb 640x360, portrait 804x1626, landscape 1600x900.
|
|
11
12
|
//
|
|
12
13
|
// `wildshard hero <shard-dir> --stamp-existing` captures nothing: it stamps the hero files already there as showing
|
|
13
14
|
// the content now. It exists for a shard repo that gains this check with curated heroes and no stamp. WARNING: use it
|
|
14
15
|
// only when those images match the current content; a wrong stamp hides a stale hero until the next content change.
|
|
15
|
-
import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
17
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
17
18
|
import { heroSlotFiles, writeHeroStamp } from '../src/cli/hero/stamp.ts';
|
|
18
19
|
import { stampExistingHero } from '../src/cli/hero/adopt.ts';
|
|
19
|
-
import { findShardSource, shardFolderName } from '../src/sharddev/shardSource.ts';
|
|
20
|
+
import { findShardSource, shardFolderName, shardRepoRoot } from '../src/sharddev/shardSource.ts';
|
|
20
21
|
|
|
21
22
|
const SCALE = 2;
|
|
22
23
|
const VIEWS = { portrait: { width: 402, height: 813 }, landscape: { width: 800, height: 450 }, thumb: { width: 320, height: 180 } };
|
|
@@ -34,17 +35,41 @@ function jpegSize(bytes) {
|
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
/** The name SHARD SELECT shows this shard under: its built product's, else the manifest's. */
|
|
37
|
-
function servedName(shard) {
|
|
38
|
-
const product = resolve(shard, '
|
|
38
|
+
export function servedName(shard) {
|
|
39
|
+
const product = resolve(shardRepoRoot(shard), 'out', shardFolderName(shard), 'shard.json');
|
|
39
40
|
if (existsSync(product)) return JSON.parse(readFileSync(product, 'utf8')).identity.name;
|
|
40
41
|
return String(JSON.parse(readFileSync(join(shard, 'manifest.json'), 'utf8')).name);
|
|
41
42
|
}
|
|
42
43
|
|
|
43
|
-
/**
|
|
44
|
+
/** The served root, so the URL `wildshard dev` prints (`…/?skipintro`) works as `--base` as well as a bare origin. */
|
|
45
|
+
function servedRoot(base) {
|
|
46
|
+
const url = new URL(base);
|
|
47
|
+
url.search = ''; url.hash = '';
|
|
48
|
+
return url.href.replace(/\/+$/u, '');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** True when `base` is a `wildshard dev` server: it answers its reload poll, `/__wildshard_dev_revision`. */
|
|
52
|
+
async function isDevServer(base) {
|
|
53
|
+
try {
|
|
54
|
+
const response = await fetch(`${base.replace(/\/+$/u, '')}/__wildshard_dev_revision`, { cache: 'no-store' });
|
|
55
|
+
return response.ok && typeof (await response.json()).revision === 'number';
|
|
56
|
+
} catch { return false; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Enter the shard the way a player does: SHARD SELECT, its card, ENTER WORLD (hidden shards are Developer cards).
|
|
60
|
+
* A `wildshard dev` page serves this shard alone and enters it by `?skipintro`; its SHARD SELECT lists engine's. */
|
|
44
61
|
async function enter(page, base, name, log) {
|
|
45
|
-
const
|
|
46
|
-
|
|
62
|
+
const dev = await isDevServer(base);
|
|
63
|
+
const url = `${base.replace(/\/+$/u, '')}/?${dev ? 'skipintro&' : ''}mute=1&sw=0&tier=desktop&nolock=1&perf=0`;
|
|
64
|
+
log(dev ? `hero: loading ${url} (wildshard dev)` : `hero: loading ${url}, card "${name}"`);
|
|
47
65
|
await page.goto(url, { waitUntil: 'load' });
|
|
66
|
+
if (!dev) await selectCard(page, base, name);
|
|
67
|
+
await page.waitForFunction(() => Boolean(window.__wildshard?.world?.hud?.entered && window.__wildshard?.world?.game) && document.querySelector('.ws-load') === null,
|
|
68
|
+
undefined, { timeout: 240000, polling: 500 });
|
|
69
|
+
if (await page.evaluate(() => window.__wildshard.world.hud.paused)) await page.keyboard.press('Escape');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function selectCard(page, base, name) {
|
|
48
73
|
await page.locator('.ws-main-select').click({ timeout: 120000 });
|
|
49
74
|
await page.locator('.ws-menu-card').first().waitFor({ timeout: 60000 });
|
|
50
75
|
const names = await page.evaluate(() => [...document.querySelectorAll('.ws-menu-card')].map(card => card.querySelector('b')?.textContent?.trim() ?? ''));
|
|
@@ -53,18 +78,20 @@ async function enter(page, base, name, log) {
|
|
|
53
78
|
await page.evaluate(index => document.querySelector(`.ws-menu-dots i[data-i="${index}"]`)?.click(), at);
|
|
54
79
|
await sleep(1000);
|
|
55
80
|
await page.locator('.ws-menu-play').click();
|
|
56
|
-
await page.waitForFunction(() => Boolean(window.__wildshard?.world?.hud?.entered && window.__wildshard?.world?.game) && document.querySelector('.ws-load') === null,
|
|
57
|
-
undefined, { timeout: 240000, polling: 500 });
|
|
58
|
-
if (await page.evaluate(() => window.__wildshard.world.hud.paused)) await page.keyboard.press('Escape');
|
|
59
81
|
}
|
|
60
82
|
|
|
61
|
-
export async function captureHero(shard,
|
|
83
|
+
export async function captureHero(shard, given, { name = servedName(shard), log = console.info } = {}) {
|
|
84
|
+
const base = servedRoot(given);
|
|
62
85
|
// Loaded here, so --stamp-existing needs no browser or engine to resolve.
|
|
63
86
|
const [{ chromium }, { NAME_ASKED, saveFixture }, { KEYCHAIN_ARGS }] = await Promise.all([
|
|
64
87
|
import('playwright'), import('@wildshard/engine/scripts/debug-settings.mjs'), import('./chromium-keychain.mjs')]);
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
88
|
+
// A `data:` slot (new's generated card) is captured to card/<slot>.jpg and named in both card files after; any other
|
|
89
|
+
// slot must already name a file in the shard folder.
|
|
90
|
+
const files = { ...(await heroSlotFiles(shard)) }, card = JSON.parse(readFileSync(join(shard, 'manifest.json'), 'utf8')).card ?? {};
|
|
91
|
+
const missing = Object.keys(VIEWS).filter(slot => files[slot] === undefined && String(card[slot]).startsWith('data:'));
|
|
92
|
+
const unnamed = Object.keys(VIEWS).filter(slot => files[slot] === undefined && !missing.includes(slot));
|
|
93
|
+
if (unnamed.length > 0) throw new Error(`${join(shard, 'manifest.json')}: card.${unnamed.join(', card.')} must name a file in the shard folder (e.g. card/${unnamed[0]}.jpg)`);
|
|
94
|
+
for (const slot of missing) files[slot] = join(shard, 'card', `${slot}.jpg`);
|
|
68
95
|
const stampFile = join(shard, 'hero.json');
|
|
69
96
|
const camera = existsSync(stampFile) ? JSON.parse(readFileSync(stampFile, 'utf8')).camera : undefined;
|
|
70
97
|
const errors = [], shots = {};
|
|
@@ -110,11 +137,23 @@ export async function captureHero(shard, base, { name = servedName(shard), log =
|
|
|
110
137
|
} finally { await browser.close(); }
|
|
111
138
|
if (errors.length > 0) throw new Error(`page errors during capture, nothing written: ${errors.slice(0, 3).join(' | ')}`);
|
|
112
139
|
// Write every file, then the stamp, so a failed capture leaves the old hero and its old stamp.
|
|
140
|
+
if (missing.length > 0) mkdirSync(join(shard, 'card'), { recursive: true });
|
|
113
141
|
for (const [slot, bytes] of Object.entries(shots)) {
|
|
114
142
|
const partial = `${files[slot]}.partial`;
|
|
115
143
|
try { writeFileSync(partial, bytes); renameSync(partial, files[slot]); } finally { rmSync(partial, { force: true }); }
|
|
116
144
|
log(`hero: wrote ${files[slot]}`);
|
|
117
145
|
}
|
|
146
|
+
if (missing.length > 0) {
|
|
147
|
+
const named = Object.fromEntries(missing.map(slot => [slot, `/src/shards/${shardFolderName(shard)}/card/${slot}.jpg`]));
|
|
148
|
+
// new writes the card twice, manifest.json and the reference world's data/card.json, and build refuses a pair that
|
|
149
|
+
// differs; so the slots move in both. Each file keeps its own layout (new writes them on one line).
|
|
150
|
+
for (const file of ['manifest.json', join('data', 'card.json')].map(name => join(shard, name)).filter(existsSync)) {
|
|
151
|
+
const text = readFileSync(file, 'utf8'), json = JSON.parse(text);
|
|
152
|
+
json.card = { ...json.card, ...named };
|
|
153
|
+
writeFileSync(file, `${/^\{\s*\n/u.test(text) ? JSON.stringify(json, null, 2) : JSON.stringify(json)}\n`);
|
|
154
|
+
log(`hero: ${file} card.${missing.join(', card.')} now name card/*.jpg`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
118
157
|
return await writeHeroStamp(shard, { base, ...(camera === undefined ? {} : { camera }) });
|
|
119
158
|
}
|
|
120
159
|
|
|
@@ -122,7 +161,7 @@ if (process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(import
|
|
|
122
161
|
const [dir, flag, base] = process.argv.slice(2);
|
|
123
162
|
const adopt = flag === '--stamp-existing' && base === undefined;
|
|
124
163
|
if (dir === undefined || (!adopt && (flag !== '--base' || base === undefined))) {
|
|
125
|
-
console.error('usage: wildshard hero <source> --base <served-build-url> (serve the candidate first:
|
|
164
|
+
console.error('usage: wildshard hero <source> --base <served-build-url> (serve the candidate first: `wildshard dev .` prints its URL)');
|
|
126
165
|
console.error(' wildshard hero <source> --stamp-existing WARNING: no capture; stamps the hero images already there as current.');
|
|
127
166
|
console.error(' Use it ONLY when you have looked at those images and they show the current content; a wrong stamp hides a stale hero.');
|
|
128
167
|
process.exit(2);
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
// Conservative source guard for Chromium launchers, without a parser dependency.
|
|
2
|
+
import { KEYCHAIN_ARGS } from './chromium-keychain.mjs';
|
|
3
|
+
|
|
2
4
|
const childMethods = ['spawn', 'spawnSync', 'execFile', 'execFileSync', 'exec', 'execSync'];
|
|
3
5
|
const browserBinary = /chrom(?:e|ium)|executablePath\s*\(/iu;
|
|
4
6
|
|
|
@@ -11,7 +13,7 @@ function shellProblems(/** @type {string} */ text) {
|
|
|
11
13
|
if (!command || command[1].startsWith('#') || command[1].includes('=')) return [];
|
|
12
14
|
const program = command[1].replace(/\$\{?(\w+)\}?/gu, (_all, name) => variables.get(name) ?? name);
|
|
13
15
|
if (!browserBinary.test(program)) return [];
|
|
14
|
-
return
|
|
16
|
+
return KEYCHAIN_ARGS.every(flag => command[2].includes(flag)) ? [] : ['bare Chromium shell executable'];
|
|
15
17
|
});
|
|
16
18
|
}
|
|
17
19
|
|
|
@@ -95,7 +97,7 @@ export function keychainProblems(/** @type {string} */ text) {
|
|
|
95
97
|
return value;
|
|
96
98
|
};
|
|
97
99
|
const safe = (/** @type {string} */ value) => /\.\.\.\s*KEYCHAIN_ARGS\b/u.test(expand(value))
|
|
98
|
-
||
|
|
100
|
+
|| KEYCHAIN_ARGS.every(flag => expand(value).includes(flag));
|
|
99
101
|
const names = [...childMethods];
|
|
100
102
|
const namespaces = new Set([...text.matchAll(/import\s+\*\s+as\s+(\w+)\s+from\s+['"](?:node:)?child_process['"]/gu)].map(match => match[1]));
|
|
101
103
|
for (const match of text.matchAll(/import\s+(\w+)\s+from\s+['"](?:node:)?child_process['"]/gu)) namespaces.add(match[1]);
|
|
@@ -2,4 +2,6 @@
|
|
|
2
2
|
// keychain for "Chrome for Testing Safe Storage" and a dialog lands on the desktop at each launch. Playwright adds them
|
|
3
3
|
// by default, but a raw `spawn` of the executable skips its defaults, so every launch site spreads them explicitly and
|
|
4
4
|
// test/tooling/chrome-keychain.test.mjs refuses a launch file that does not.
|
|
5
|
-
|
|
5
|
+
// `--mute-audio` rides along (Jake, 2026-11-13: "headless chromium with volume off"), so a launch that forgets it
|
|
6
|
+
// still cannot play a game's sound out of Jake's speakers.
|
|
7
|
+
export const KEYCHAIN_ARGS = Object.freeze(['--use-mock-keychain', '--password-store=basic', '--mute-audio']);
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// SHARD-AUTHORING SA5 (J317): every @wildshard/sdk export is in one tier (lint/export-tiers.json): contract, rows,
|
|
2
|
+
// scripts, bake kit or internal. `exportTierProblems` names each unclassed export, stale row and unknown tier;
|
|
3
|
+
// `renderExportTiers` is docs/api/EXPORT-TIERS.md, the API doc that shows each export's tier.
|
|
4
|
+
// node scripts/export-tiers.mjs write docs/api/EXPORT-TIERS.md
|
|
5
|
+
// node scripts/export-tiers.mjs --check fail on a problem or a stale page
|
|
6
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { dirname, resolve } from 'node:path';
|
|
8
|
+
import { pathToFileURL } from 'node:url';
|
|
9
|
+
|
|
10
|
+
const ROOT = resolve(import.meta.dirname, '..');
|
|
11
|
+
export const TIERS = ['contract', 'rows', 'scripts', 'bake kit', 'internal'];
|
|
12
|
+
export const TIER_FILE = 'lint/export-tiers.json';
|
|
13
|
+
export const TIER_PAGE = 'docs/api/EXPORT-TIERS.md';
|
|
14
|
+
|
|
15
|
+
const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
|
|
16
|
+
/** The package's exports and the tier file, read from `root`.
|
|
17
|
+
* @param {string} [root] @returns {{ exports: Record<string, unknown>, tiers: { tiers: Record<string, string>, exports: Record<string, string> } }} */
|
|
18
|
+
export function readExportTiers(root = ROOT) {
|
|
19
|
+
return { exports: readJson(resolve(root, 'package.json')).exports ?? {}, tiers: readJson(resolve(root, TIER_FILE)) };
|
|
20
|
+
}
|
|
21
|
+
/** One line per problem; empty when every export has exactly one known tier and every row names an export.
|
|
22
|
+
* @param {Record<string, unknown>} exports @param {{ tiers: Record<string, string>, exports: Record<string, string> }} tiers @returns {string[]} */
|
|
23
|
+
export function exportTierProblems(exports, tiers) {
|
|
24
|
+
const problems = [];
|
|
25
|
+
for (const tier of TIERS) if (typeof tiers.tiers?.[tier] !== 'string') problems.push(`tier "${tier}" has no description in ${TIER_FILE}`);
|
|
26
|
+
for (const tier of Object.keys(tiers.tiers ?? {})) if (!TIERS.includes(tier)) problems.push(`unknown tier "${tier}" in ${TIER_FILE}`);
|
|
27
|
+
for (const subpath of Object.keys(exports)) {
|
|
28
|
+
const tier = tiers.exports?.[subpath];
|
|
29
|
+
if (tier === undefined) problems.push(`unclassed export ${subpath}: give it a tier (${TIERS.join(', ')}) in ${TIER_FILE}`);
|
|
30
|
+
else if (!TIERS.includes(tier)) problems.push(`export ${subpath} has unknown tier "${tier}"`);
|
|
31
|
+
}
|
|
32
|
+
for (const subpath of Object.keys(tiers.exports ?? {})) if (!Object.hasOwn(exports, subpath)) problems.push(`${TIER_FILE} classes ${subpath}, which package.json does not export`);
|
|
33
|
+
return problems;
|
|
34
|
+
}
|
|
35
|
+
const specifier = (subpath) => `@wildshard/sdk${subpath === '.' ? '' : `/${subpath.slice(2)}`}`;
|
|
36
|
+
const target = (value) => (typeof value === 'string' ? value : JSON.stringify(value));
|
|
37
|
+
/** docs/api/EXPORT-TIERS.md: each tier, what it promises, and its exports with the file each resolves to.
|
|
38
|
+
* @param {Record<string, unknown>} exports @param {{ tiers: Record<string, string>, exports: Record<string, string> }} tiers @returns {string} */
|
|
39
|
+
export function renderExportTiers(exports, tiers) {
|
|
40
|
+
const sections = TIERS.map((tier) => {
|
|
41
|
+
const rows = Object.keys(exports).filter((subpath) => tiers.exports[subpath] === tier).sort();
|
|
42
|
+
return `## ${tier} (${rows.length})\n\n${tiers.tiers[tier]}\n\n| Export | Tier | File |\n|---|---|---|\n${rows.map((subpath) => `| \`${specifier(subpath)}\` | ${tier} | \`${target(exports[subpath])}\` |`).join('\n')}\n`;
|
|
43
|
+
});
|
|
44
|
+
return `# @wildshard/sdk exports, by tier\n\n<!-- generated by scripts/export-tiers.mjs from package.json exports and ${TIER_FILE}: do not edit -->\n\n${Object.keys(exports).length} exports. A shard project imports from contract, rows, scripts and the bake kit; internal may change in any release. A new export needs a row in \`${TIER_FILE}\` (\`test/export-tiers.test.ts\` fails without one); then run \`node scripts/export-tiers.mjs\`.\n\n${sections.join('\n')}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
48
|
+
const { exports, tiers } = readExportTiers(ROOT), problems = exportTierProblems(exports, tiers);
|
|
49
|
+
if (problems.length > 0) { console.error(problems.join('\n')); process.exit(1); }
|
|
50
|
+
const page = renderExportTiers(exports, tiers), path = resolve(ROOT, TIER_PAGE);
|
|
51
|
+
if (process.argv.includes('--check')) {
|
|
52
|
+
let current = '';
|
|
53
|
+
try { current = readFileSync(path, 'utf8'); } catch { /* missing reads as stale */ }
|
|
54
|
+
if (current !== page) { console.error(`${TIER_PAGE} is stale: run node scripts/export-tiers.mjs`); process.exit(1); }
|
|
55
|
+
} else { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, page); }
|
|
56
|
+
console.info(`export tiers: ${Object.keys(exports).length} exports classed`);
|
|
57
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SHARD-AUTHORING SA43: the preview `wildshard prepare <folder>` records in when no --base is given. It serves engine's
|
|
2
|
+
// preparation client (a WILDSHARD_PREPARATION_ONLY production build, fetched at this package's engine pin, src/sharddev/
|
|
3
|
+
// devClient.ts) with the candidate's shard.json inline as `ws-shardfile`, as `wildshard dev` serves the devserver client,
|
|
4
|
+
// and the candidate folder beside the page (as `wildshard build` lays a client over its product) and where a release
|
|
5
|
+
// serves a shard, `/shardfiles/<slug>/`. No engine checkout is needed.
|
|
6
|
+
import {createServer} from 'node:http';
|
|
7
|
+
import {createReadStream,existsSync,readFileSync,realpathSync,statSync} from 'node:fs';
|
|
8
|
+
import {extname,resolve,sep} from 'node:path';
|
|
9
|
+
|
|
10
|
+
const MIME={'.html':'text/html','.js':'text/javascript','.css':'text/css','.json':'application/json','.wasm':'application/wasm','.svg':'image/svg+xml',
|
|
11
|
+
'.png':'image/png','.jpg':'image/jpeg','.webp':'image/webp','.woff2':'font/woff2','.ktx2':'image/ktx2','.m4a':'audio/mp4','.ogg':'audio/ogg','.glb':'model/gltf-binary'};
|
|
12
|
+
|
|
13
|
+
/** A file under `root` for the request path `local`, or undefined (never one outside it, symlinks included). */
|
|
14
|
+
function inside(root,local){
|
|
15
|
+
const file=resolve(root,local);
|
|
16
|
+
if(!file.startsWith(`${root}${sep}`)||!existsSync(file)||!statSync(file).isFile())return undefined;
|
|
17
|
+
return realpathSync(file).startsWith(`${root}${sep}`)?file:undefined;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Serve `client` with the candidate `dir` (a built shard file folder) inline; resolves to {url, close}. */
|
|
21
|
+
export async function preparationPreview(client,dir,{clientPage}){
|
|
22
|
+
client=realpathSync(resolve(client));dir=realpathSync(resolve(dir));
|
|
23
|
+
const header=readFileSync(resolve(dir,'shard.json'),'utf8'),slug=JSON.parse(header).identity.slug;
|
|
24
|
+
// The inline descriptor is the candidate's own index bytes, `<` escaped as `wildshard build` writes it.
|
|
25
|
+
const recorded=existsSync(resolve(dir,'programs',`${slug}.json`));
|
|
26
|
+
const page=clientPage(readFileSync(resolve(client,'index.html'),'utf8'),header.trim().replaceAll('<','\\u003c'),slug,recorded);
|
|
27
|
+
const shardRoot=`/shardfiles/${slug}/`;
|
|
28
|
+
const server=createServer((request,response)=>{
|
|
29
|
+
response.setHeader('Cache-Control','no-store');
|
|
30
|
+
try{
|
|
31
|
+
if(request.method!=='GET'&&request.method!=='HEAD'){response.writeHead(405);response.end();return;}
|
|
32
|
+
const path=decodeURIComponent(new URL(request.url??'/','http://localhost').pathname);
|
|
33
|
+
if(path==='/'||path==='/index.html'){response.setHeader('Content-Type','text/html');response.end(request.method==='HEAD'?undefined:page);return;}
|
|
34
|
+
// The inline product reads beside the page, as `wildshard build` lays the client over the product folder (the
|
|
35
|
+
// client's file wins); the in-page server reads where a release serves the shard.
|
|
36
|
+
const file=path.startsWith(shardRoot)?inside(dir,path.slice(shardRoot.length)):inside(client,path.slice(1))??inside(dir,path.slice(1));
|
|
37
|
+
if(file===undefined){response.writeHead(404);response.end();return;}
|
|
38
|
+
response.setHeader('Content-Type',MIME[extname(file)]??'application/octet-stream');
|
|
39
|
+
if(request.method==='HEAD')response.end();else createReadStream(file).on('error',()=>{response.destroy();}).pipe(response);
|
|
40
|
+
}catch{response.writeHead(400);response.end();}
|
|
41
|
+
});
|
|
42
|
+
await new Promise((done,fail)=>{server.once('error',fail);server.listen(0,'127.0.0.1',()=>{done(undefined);});});
|
|
43
|
+
const address=server.address();if(address===null||typeof address==='string')throw new Error('No preparation preview address');
|
|
44
|
+
return {url:`http://127.0.0.1:${address.port}/`,slug,close:()=>new Promise(done=>{server.close(()=>{done(undefined);});server.closeAllConnections();})};
|
|
45
|
+
}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// J198: prepare an already built candidate using actual phone WebKit links.
|
|
3
3
|
// Draft sdk 0.2 output is not relabelled until this exact product enters.
|
|
4
4
|
import {createHash} from 'node:crypto';
|
|
5
|
-
import {
|
|
5
|
+
import {spawn} from 'node:child_process';
|
|
6
6
|
import {readFileSync,writeFileSync,mkdirSync,mkdtempSync,rmSync,readdirSync,statSync,lstatSync} from 'node:fs';
|
|
7
7
|
import {tmpdir} from 'node:os';
|
|
8
8
|
import {join,resolve,dirname} from 'node:path';
|
|
@@ -80,7 +80,20 @@ export async function finishPreparation(dir,recording,originalHeader){
|
|
|
80
80
|
return {slug:index.identity.slug,fence:fence.length,programs:programs.programs.length,renderer,document:programs.build};
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
/** SA43: with no --base, serve engine's preparation client (fetched at this package's engine pin) around the candidate. */
|
|
84
|
+
async function ownPreview(dir){
|
|
85
|
+
const {preparationClient}=await import('../src/sharddev/devClient.ts');
|
|
86
|
+
const {clientPage}=await import('../src/sharddev/clientPage.ts');
|
|
87
|
+
const {preparationPreview}=await import('./preparation-preview.mjs');
|
|
88
|
+
return preparationPreview(await preparationClient(),dir,{clientPage});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function prepareProduct(dir,base,inline=false){
|
|
92
|
+
if(base===undefined){
|
|
93
|
+
const preview=await ownPreview(dir);
|
|
94
|
+
console.error(`wildshard prepare: serving engine's preparation client at ${preview.url}`);
|
|
95
|
+
try{return await prepareProduct(dir,preview.url,true);}finally{await preview.close();}
|
|
96
|
+
}
|
|
84
97
|
const header=readFileSync(join(dir,'shard.json')),index=parseOutputIndex(JSON.parse(header));
|
|
85
98
|
const scratch=mkdtempSync(join(tmpdir(),'wildshard-prepare-'));
|
|
86
99
|
try{
|
|
@@ -88,7 +101,12 @@ export async function prepareProduct(dir,base){
|
|
|
88
101
|
const script=fileURLToPath(new URL('./bake-entry-programs.mjs',import.meta.url));
|
|
89
102
|
// Like the existing recorder, the operator runs this command through the
|
|
90
103
|
// engine browser-lane wrapper. Do not acquire a second nested browser slot.
|
|
91
|
-
|
|
104
|
+
// Not spawnSync: with no --base this process serves the preview the recorder reads (SA43).
|
|
105
|
+
const run=await new Promise(done=>{
|
|
106
|
+
const child=spawn(process.execPath,[script,'--base',base,'--out',out,'--header',hash(header),'--title',index.identity.name,...(inline?['--inline']:[]),index.identity.slug],{stdio:'inherit',timeout:300000});
|
|
107
|
+
child.once('error',error=>{done({error,status:null});});
|
|
108
|
+
child.once('exit',status=>{done({error:undefined,status});});
|
|
109
|
+
});
|
|
92
110
|
if(run.error!==undefined||run.status!==0)throw new Error('Phone WebKit preparation did not pass; candidate left as a draft');
|
|
93
111
|
return await finishPreparation(dir,json(scratch,'recording.json'),header);
|
|
94
112
|
}finally{rmSync(scratch,{recursive:true,force:true});}
|
|
@@ -96,6 +114,6 @@ export async function prepareProduct(dir,base){
|
|
|
96
114
|
|
|
97
115
|
if(process.argv[1]!==undefined&&resolve(process.argv[1])===fileURLToPath(import.meta.url)){
|
|
98
116
|
const [dir,flag,base]=process.argv.slice(2);
|
|
99
|
-
if(dir===undefined||flag!=='--base'||base===undefined)throw new Error('usage: wildshard prepare <folder> --base <exact-preview-url>');
|
|
117
|
+
if(dir===undefined||(flag!==undefined&&(flag!=='--base'||base===undefined)))throw new Error('usage: wildshard prepare <folder> [--base <exact-preview-url>]');
|
|
100
118
|
console.log(JSON.stringify(await prepareProduct(resolve(dir),base)));
|
|
101
119
|
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// repo-kit's scratch folder maker (meta docs/plans/REPO-DISK-PLAN.md row DK3). One copy lives in repo-kit; every org
|
|
3
|
+
// repo and singleplayer carries a byte-identical copy at scripts/scratch-dir.mjs (DK8 checks the copies).
|
|
4
|
+
//
|
|
5
|
+
// node scripts/scratch-dir.mjs <task> "<purpose>"
|
|
6
|
+
//
|
|
7
|
+
// creates <repo>/tmp/<task>/ and tmp/<task>/.owner, then prints the folder's absolute path. .owner is JSON: the session
|
|
8
|
+
// id ($CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else the Codex lane name in $WS_LANE_NAME), the lane name, the
|
|
9
|
+
// herdr pane ($HERDR_PANE_ID), the start time and the purpose. DK4's SessionEnd hook removes the folders whose .owner
|
|
10
|
+
// names the ending session; a .keep file in the folder (one line: why to keep it) stops that and DK6's 3-day sweep.
|
|
11
|
+
//
|
|
12
|
+
// <task> is one plain folder name: letters, digits, '.', '_' and '-', not starting with '.', never containing '/' or
|
|
13
|
+
// '..'. The helper deletes nothing. It refuses a folder that already exists unless that folder's .owner names this
|
|
14
|
+
// same session (then it prints the path again), so it never takes over another lane's or an ownerless folder.
|
|
15
|
+
import { mkdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
|
|
16
|
+
import { join, resolve } from 'node:path';
|
|
17
|
+
import { pathToFileURL } from 'node:url';
|
|
18
|
+
|
|
19
|
+
const ROOT = resolve(import.meta.dirname, '..');
|
|
20
|
+
const TASK = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/u;
|
|
21
|
+
|
|
22
|
+
/** Why a task name is refused, or null when it is a plain folder name.
|
|
23
|
+
* @param {string} task @returns {string | null} */
|
|
24
|
+
export function refuseTask(task) {
|
|
25
|
+
if (typeof task !== 'string' || task === '') return 'a task name is required';
|
|
26
|
+
if (task.includes('/') || task.includes('\\')) return `task "${task}" contains a path separator`;
|
|
27
|
+
if (task.includes('..')) return `task "${task}" contains ".."`;
|
|
28
|
+
if (task.length > 100) return `task "${task}" is longer than 100 characters`;
|
|
29
|
+
if (!TASK.test(task)) return `task "${task}" must be letters, digits, ".", "_" and "-", not starting with "."`;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The .owner record for a new folder.
|
|
34
|
+
* @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now */
|
|
35
|
+
export function ownerRecord(task, purpose, env, now) {
|
|
36
|
+
const lane = env.WS_LANE_NAME || null;
|
|
37
|
+
return {
|
|
38
|
+
task,
|
|
39
|
+
session: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
|
|
40
|
+
lane,
|
|
41
|
+
pane: env.HERDR_PANE_ID || null,
|
|
42
|
+
started: now.toISOString(),
|
|
43
|
+
purpose,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param {string} path @returns {{session?: unknown} | null} */
|
|
48
|
+
function readOwner(path) {
|
|
49
|
+
try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Make <root>/tmp/<task>/ and its .owner; returns the folder's absolute path. Throws on a refused name, an empty
|
|
53
|
+
* purpose, or a folder that exists and is not this session's.
|
|
54
|
+
* @param {string} task @param {string} purpose
|
|
55
|
+
* @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date}} [options] */
|
|
56
|
+
export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date() } = {}) {
|
|
57
|
+
const refusal = refuseTask(task);
|
|
58
|
+
if (refusal) throw new Error(refusal);
|
|
59
|
+
if (typeof purpose !== 'string' || purpose.trim() === '') throw new Error('a purpose is required');
|
|
60
|
+
const tmp = join(resolve(root), 'tmp');
|
|
61
|
+
const dir = join(tmp, task);
|
|
62
|
+
const owner = ownerRecord(task, purpose.trim(), env, now);
|
|
63
|
+
mkdirSync(tmp, { recursive: true });
|
|
64
|
+
try {
|
|
65
|
+
mkdirSync(dir);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;
|
|
68
|
+
const existing = readOwner(join(dir, '.owner'));
|
|
69
|
+
if (existing && owner.session && existing.session === owner.session) return dir;
|
|
70
|
+
throw new Error(existing
|
|
71
|
+
? `${dir} already belongs to session ${String(existing.session)}; pick another task name`
|
|
72
|
+
: `${dir} already exists with no .owner; pick another task name`);
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
writeFileSync(join(dir, '.owner'), `${JSON.stringify(owner, null, 2)}\n`, { flag: 'wx' });
|
|
76
|
+
} catch (error) {
|
|
77
|
+
rmdirSync(dir); // only the empty folder this call just made
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
return dir;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
84
|
+
const [task = '', purpose = '', ...rest] = process.argv.slice(2);
|
|
85
|
+
if (rest.length > 0 || task === '--help' || task === '-h') {
|
|
86
|
+
console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>"');
|
|
87
|
+
process.exit(2);
|
|
88
|
+
}
|
|
89
|
+
try {
|
|
90
|
+
console.log(scratchDir(task, purpose));
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.error(`scratch-dir: ${error instanceof Error ? error.message : String(error)}`);
|
|
93
|
+
process.exit(1);
|
|
94
|
+
}
|
|
95
|
+
}
|
package/scripts/wildshard.mjs
CHANGED
|
@@ -84,6 +84,27 @@ export async function runWildshard(args) {
|
|
|
84
84
|
folder: output?.slug ?? folder, ...(output !== undefined ? { composed: outputManifest(root, folder, output.row) } : existsSync(resolve(project, 'manifest.json')) ? { file: resolve(project, 'manifest.json') } : {}),
|
|
85
85
|
imageRoots: [{ prefix: `/src/shards/${folder}/`, directory: project }, { prefix: '/assets/', directory: resolve(root, 'public/assets') }],
|
|
86
86
|
};
|
|
87
|
+
// TS21: `check` on a folder that declares outputs (and no --output) checks each output with its own composed manifest,
|
|
88
|
+
// into <folder>/<slug> when a folder is named, and gives one verdict, as build-shards builds each output.
|
|
89
|
+
const declared = args[0] === 'check' && selected === undefined && project !== undefined && existsSync(resolve(project, 'shard.config.ts')) ? shardOutputs(root, folder) : null;
|
|
90
|
+
if (declared !== null) {
|
|
91
|
+
if (args.includes('--json')) throw new Error(`wildshard check: ${folder} declares ${declared.length} outputs; --json checks one: add --output=<slug>`);
|
|
92
|
+
const rest = args.slice(2), extra = rest.filter(arg => !arg.startsWith('--'));
|
|
93
|
+
if (extra.length > 1 || rest.some(arg => arg.startsWith('--'))) throw new Error('usage: wildshard check <source> [folder] [--json] [--output=<slug>]');
|
|
94
|
+
const [into] = extra, failed = [], before = process.exitCode;
|
|
95
|
+
for (const { slug } of declared) {
|
|
96
|
+
console.info(`== ${slug}`);
|
|
97
|
+
process.exitCode = undefined;
|
|
98
|
+
// A setup error (a missing manifest, a refused source) fails this output; the rest are still checked.
|
|
99
|
+
try { await runWildshard(['check', project, ...(into === undefined ? [] : [resolve(into, slug)]), `--output=${slug}`]); }
|
|
100
|
+
catch (error) { console.error(`${slug}: ${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; }
|
|
101
|
+
if (process.exitCode !== undefined && process.exitCode !== 0) failed.push(slug);
|
|
102
|
+
}
|
|
103
|
+
process.exitCode = before;
|
|
104
|
+
console.info(`check ${failed.length === 0 ? 'pass' : 'fail'}: ${declared.length} outputs${failed.length === 0 ? '' : `, failed: ${failed.join(', ')}`}`);
|
|
105
|
+
if (failed.length > 0) process.exitCode = 1;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
87
108
|
const legacy = project === undefined ? undefined : decisionLegacyLines(root, folder);
|
|
88
109
|
await (await runner)(args, { ...(legacy === undefined ? {} : { decisionLegacyLines: legacy }), ...(manifest === undefined ? {} : { manifest }), writeShardfile });
|
|
89
110
|
}
|