@wildshard/sdk 0.2.5 → 0.2.7
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 +49 -39
- package/docs/api/EXPORT-TIERS.md +204 -0
- package/lint/export-tiers.json +176 -0
- package/package.json +3 -2
- package/scripts/build-shardfiles.mjs +7 -6
- package/scripts/capture-hero.mjs +53 -14
- package/scripts/export-tiers.mjs +57 -0
- package/scripts/scratch-dir.mjs +95 -0
- package/scripts/shard-build-pool.mjs +1 -1
- package/scripts/wildshard.mjs +24 -1
- 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/skills/wildshard-upgrade/SKILL.md +11 -4
- package/src/cli/help.ts +2 -2
- package/src/sharddev/agentFiles.ts +3 -2
- 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/dev.ts +21 -12
- package/src/sharddev/devClient.ts +81 -0
- package/src/sharddev/newProject.ts +1 -3
- package/src/sharddev/project.ts +7 -4
- package/src/sharddev/updatePins.ts +144 -40
|
@@ -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;
|
|
@@ -195,7 +196,7 @@ export async function buildShardfiles(root,options={}) {
|
|
|
195
196
|
const counters=createBuildCacheCounters(),stop=observeBuildCache(counters);
|
|
196
197
|
let complete=false;
|
|
197
198
|
try {const result=await buildShardfilesWork(root,options,counters);complete=true;return result;}
|
|
198
|
-
finally {stop();console.info(formatBuildCacheReport(counters.snapshot(complete)));}
|
|
199
|
+
finally {stop();if(process.env.WILDSHARD_CACHE_REPORT==='1')console.info(formatBuildCacheReport(counters.snapshot(complete)));}
|
|
199
200
|
}
|
|
200
201
|
|
|
201
202
|
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
package/scripts/capture-hero.mjs
CHANGED
|
@@ -4,15 +4,16 @@
|
|
|
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';
|
|
@@ -40,11 +41,35 @@ function servedName(shard) {
|
|
|
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);
|
|
@@ -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,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
|
+
}
|
|
@@ -30,7 +30,7 @@ export async function runShardBuildPool(items, work, prepare) {
|
|
|
30
30
|
export function runShardBuild(args, signal, cacheReport) {
|
|
31
31
|
return new Promise((resolve, reject) => {
|
|
32
32
|
const child = spawn(process.execPath, ['--import', fileURLToPath(import.meta.resolve('@wildshard/engine/scripts/shardfile-inputs.mjs')), resolvePath(import.meta.dirname, 'wildshard.mjs'), ...args], {
|
|
33
|
-
cwd: process.cwd(), env: {...process.env,WILDSHARD_WORLD_TEXTURE_CACHE:process.env.WILDSHARD_WORLD_TEXTURE_CACHE??resolvePath(shardfileCacheRoot(),'.world-textures-v1')}, signal, stdio: ['ignore', 'inherit', 'pipe'],
|
|
33
|
+
cwd: process.cwd(), env: {...process.env,...(cacheReport===undefined?{}:{WILDSHARD_CACHE_REPORT:'1'}),WILDSHARD_WORLD_TEXTURE_CACHE:process.env.WILDSHARD_WORLD_TEXTURE_CACHE??resolvePath(shardfileCacheRoot(),'.world-textures-v1')}, signal, stdio: ['ignore', 'inherit', 'pipe'],
|
|
34
34
|
});
|
|
35
35
|
// Forward all diagnostics, retaining only a bounded tail for the pool's error.
|
|
36
36
|
let stderrTail = '';
|
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
|
}
|
|
@@ -107,5 +128,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
|
|
|
107
128
|
complete=true;
|
|
108
129
|
}
|
|
109
130
|
catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }
|
|
110
|
-
|
|
131
|
+
// The counters line is for the build pool, which sets WILDSHARD_CACHE_REPORT=1 for the children whose report it reads,
|
|
132
|
+
// and for debugging a build's cache; an author's run, refusals included, does not print it.
|
|
133
|
+
finally {stop();if(process.env.WILDSHARD_CACHE_REPORT==='1')console.error(`\n${formatBuildCacheReport(counters.snapshot(complete))}`);}
|
|
111
134
|
}
|
|
@@ -20,9 +20,8 @@ Run each step from the project folder. Read the step's section first: it says wh
|
|
|
20
20
|
instead where a step is not built yet.
|
|
21
21
|
|
|
22
22
|
1. **new**: `wildshard new <dir>` started this repo. `GUIDE.md#1-the-loop`; every flag in `GUIDE.md#every-verb`.
|
|
23
|
-
2. **dev**:
|
|
24
|
-
|
|
25
|
-
way in needs the Wildshard team.
|
|
23
|
+
2. **dev**: `wildshard dev .` serves the shard on localhost; open the URL it prints. `GUIDE.md#walking-your-shard`,
|
|
24
|
+
and what reloads on save in `GUIDE.md#4-what-reloads-under-dev`. Done when you have walked it.
|
|
26
25
|
3. **check**: `wildshard check .` after every change. `GUIDE.md#1-the-loop`; what it measures in
|
|
27
26
|
`GUIDE.md#3-budgets`. Done when the last line reads `check pass`.
|
|
28
27
|
4. **hero**: capture a new hero after your last change to the world. `GUIDE.md#the-hero`, then step 1 of
|
|
@@ -23,13 +23,12 @@ guide heading with that anchor.
|
|
|
23
23
|
These steps need `src/manifest.json`, which `wildshard new` writes for the default template only; without it, write
|
|
24
24
|
down that the hero needs the Wildshard team.
|
|
25
25
|
|
|
26
|
-
1. **
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
3. **
|
|
32
|
-
rewritten.
|
|
26
|
+
1. **A served build carrying this exact shard source:** `wildshard dev .`, left running (`GUIDE.md#the-hero`). Done
|
|
27
|
+
when it prints its URL.
|
|
28
|
+
2. **Capture.** `wildshard hero . --base <that url>` (`GUIDE.md#the-hero`). The `data:` card `new` wrote becomes
|
|
29
|
+
`card/thumb.jpg`, `card/portrait.jpg` and `card/landscape.jpg`, named in both `manifest.json` and
|
|
30
|
+
`data/card.json`. Done when `hero.json` and the three images are rewritten.
|
|
31
|
+
3. **Stop `dev`** with Ctrl-C. Done when its port is free.
|
|
33
32
|
4. **Look at all three images** with your own eyes or the Read tool: the shard, not a loading screen, a black frame or
|
|
34
33
|
another shard. Done when each shows the current world.
|
|
35
34
|
5. **Commit** the images and `hero.json` together (`GUIDE.md#uploading` step 2), then `wildshard check .`. Done at
|
|
@@ -43,8 +43,8 @@ Read `GUIDE.md#2-the-shard-source` before your first edit: it says what ships in
|
|
|
43
43
|
6. **Check.** `wildshard check .` (`GUIDE.md#1-the-loop`). The report card measures draws, triangles, memory and
|
|
44
44
|
download against their limits (`GUIDE.md#3-budgets`); a refusal names its fix, for example
|
|
45
45
|
`GUIDE.md#budget-triangles` or `GUIDE.md#budget-download`. Done when the last line reads `check pass`.
|
|
46
|
-
7. **See it in the world.**
|
|
47
|
-
|
|
46
|
+
7. **See it in the world.** `wildshard dev .`, then walk to where the model stands (`GUIDE.md#walking-your-shard`).
|
|
47
|
+
Done when you have seen it there.
|
|
48
48
|
8. **The hero.** The world changed, so before the next upload follow the `wildshard-goldens` skill
|
|
49
49
|
(`GUIDE.md#the-hero`). Done when that skill's hero steps are done, or you have written down that this repo has no
|
|
50
50
|
`manifest.json` card to capture.
|
|
@@ -10,16 +10,23 @@ blender` repo pins only the first two, as dev dependencies (`GUIDE.md#2-the-shar
|
|
|
10
10
|
moves every pin together, then the shard source must build again on them. `GUIDE.md` at the repo root holds the
|
|
11
11
|
facts; a pointer `GUIDE.md#<anchor>` is the guide heading with that anchor.
|
|
12
12
|
|
|
13
|
+
Run the newest CLI once to move, whatever sdk the repo is on now:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
pnpm --package=@wildshard/sdk@latest dlx wildshard update --pins
|
|
17
|
+
```
|
|
18
|
+
|
|
13
19
|
`wildshard update --pins` does the move in one command (`GUIDE.md#7-wildshard-update`): it moves every pin to the
|
|
14
|
-
release, runs `pnpm install`, applies the release's codemods, rewrites the guide and skills, and runs check.
|
|
20
|
+
release, runs `pnpm install`, applies the release's codemods, rewrites the guide and skills, and runs check. An
|
|
21
|
+
installed 0.2.4 or older refuses the flag, and 0.2.5 refuses a repo that lists the sdk as `@wildshard/sharddev` or by
|
|
22
|
+
a GitHub pin, so start from the line above.
|
|
15
23
|
|
|
16
24
|
## The steps, in order
|
|
17
25
|
|
|
18
26
|
1. **Start clean.** Commit your own changes, then `wildshard check .` on the old pins; if it fails, fix that first.
|
|
19
27
|
Done when `git status` is clean and check passes, so any later refusal is the upgrade's.
|
|
20
|
-
2. **Move:** `pnpm
|
|
21
|
-
|
|
22
|
-
`pnpm --package=@wildshard/sdk@latest dlx wildshard update --pins`. Done when it prints a line per pin it moved.
|
|
28
|
+
2. **Move:** `pnpm --package=@wildshard/sdk@latest dlx wildshard update --pins` for npm's latest sdk, or
|
|
29
|
+
`--pins=<version>` in place of `--pins` for one release. Done when it prints a line per pin it moved.
|
|
23
30
|
3. **Read its last line.** `on @wildshard/sdk <version>, check pass` means the move is done: go to step 5. A line
|
|
24
31
|
ending `[update-pins] fix: ...` is a refusal: read `GUIDE.md#update-pins` in the guide now in the repo;
|
|
25
32
|
`[update-pins-dirty]` (`GUIDE.md#update-pins-dirty`) means go back to step 1.
|
package/src/cli/help.ts
CHANGED
|
@@ -53,8 +53,8 @@ const VERBS: Readonly<Record<string, string>> = {
|
|
|
53
53
|
hero: `hero <source> --base <served-build-url>
|
|
54
54
|
Capture the shard's hero (thumb, portrait,
|
|
55
55
|
landscape) in headless Chromium from a served build
|
|
56
|
-
of this candidate
|
|
57
|
-
content
|
|
56
|
+
of this candidate (the URL \`wildshard dev .\` prints),
|
|
57
|
+
and stamp hero.json with its content
|
|
58
58
|
hero <source> --stamp-existing
|
|
59
59
|
No capture: stamp the hero images already in the
|
|
60
60
|
shard source as current. WARNING: use it ONLY when
|
|
@@ -101,7 +101,8 @@ function sdkVersion(root: string): string {
|
|
|
101
101
|
return typeof parsed === 'object' && parsed !== null && 'version' in parsed && typeof parsed.version === 'string' ? parsed.version : 'unknown';
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
/** A shard repo is a folder whose package.json lists `@wildshard/sdk` (`new` writes it; a blender repo as a dev dependency)
|
|
104
|
+
/** A shard repo is a folder whose package.json lists `@wildshard/sdk` (`new` writes it; a blender repo as a dev dependency)
|
|
105
|
+
* or `@wildshard/sharddev`, the name the org's shard repos list it under (a GitHub pin, or an `npm:@wildshard/sdk` alias). */
|
|
105
106
|
export function assertShardRepo(project: string): void {
|
|
106
107
|
const file = resolve(project, 'package.json');
|
|
107
108
|
let parsed: unknown;
|
|
@@ -109,7 +110,7 @@ export function assertShardRepo(project: string): void {
|
|
|
109
110
|
catch (error) { throw new Error(`update: ${project} is not a shard repo: its package.json is not valid JSON (${error instanceof Error ? error.message : String(error)})`, { cause: error }); }
|
|
110
111
|
const fields: unknown[] = typeof parsed === 'object' && parsed !== null
|
|
111
112
|
? [Reflect.get(parsed, 'dependencies'), Reflect.get(parsed, 'devDependencies')] : [];
|
|
112
|
-
if (!fields.some(field => typeof field === 'object' && field !== null && Object.hasOwn(field, '@wildshard/sdk'))) throw new Error(`update: ${project} is not a shard repo: its package.json does not list @wildshard/sdk (or it has none)`);
|
|
113
|
+
if (!fields.some(field => typeof field === 'object' && field !== null && (Object.hasOwn(field, '@wildshard/sdk') || Object.hasOwn(field, '@wildshard/sharddev')))) throw new Error(`update: ${project} is not a shard repo: its package.json does not list @wildshard/sdk or @wildshard/sharddev (or it has none)`);
|
|
113
114
|
}
|
|
114
115
|
|
|
115
116
|
/** `wildshard update [dir]`: sync the agent files of the shard repo at `project`, and say what changed, one line each. */
|
|
@@ -140,21 +140,48 @@ function oneDraw(geometry: ReturnType<typeof placeholderGeometry>, name: string)
|
|
|
140
140
|
return staticGlb([{ geometry, material: new MeshStandardMaterial({ color: 0xffffff, vertexColors: true }), castShadow: false }], name);
|
|
141
141
|
}
|
|
142
142
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
*/
|
|
147
|
-
|
|
143
|
+
type FarRow = NonNullable<Shardfile['far']>;
|
|
144
|
+
/** The §3.2 far caps a far row is admitted under (`CONTENT_CAPS.far`). */
|
|
145
|
+
export interface FarCaps { readonly resident: number; readonly compressed: number; readonly triangles: number; readonly draws: number }
|
|
146
|
+
/** Whether a far row fits every §3.2 far cap. */
|
|
147
|
+
function farWithinCaps(far: FarRow, caps: FarCaps = CONTENT_CAPS.far): boolean {
|
|
148
|
+
return far.decoded + far.gpu <= caps.resident && far.compressed <= caps.compressed && far.triangles <= caps.triangles && far.draws <= caps.draws;
|
|
149
|
+
}
|
|
150
|
+
/** The far GLB, its impostor, and the far row with the impostor (`far`) and without it (`meshOnly`). */
|
|
151
|
+
async function farRows(grid: PlaceholderGrid, look: PlaceholderLook, parts: readonly PlaceholderPart[]) {
|
|
148
152
|
const geometry = placeholderGeometry(grid, look, parts);
|
|
149
153
|
const bytes = oneDraw(geometry, 'far-proxy'), file = fileRow(bytes);
|
|
150
154
|
geometry.computeBoundingBox(); const box = geometry.boundingBox; if (box === null) throw new Error('Missing far bounds');
|
|
151
155
|
const baked = await bakeFarImpostor(geometry, look.family);
|
|
152
156
|
// Admit the defining image envelope, including decode workspace and RGBA fallback; runtime packing stays RGBA 5551.
|
|
153
157
|
const impostorFile: PlaceholderFile = { hash: hashImmutableBytes(baked.png), kind: 'image', compressed: baked.png.length, ...assetCost('image', baked.png), dependencies: [], critical: false };
|
|
154
|
-
const
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return {
|
|
158
|
+
const meshOnly: FarRow = { bounds: { min: box.min.toArray(), max: box.max.toArray() }, files: [file.hash], compressed: file.compressed, decoded: file.decoded, gpu: file.gpu, triangles: file.triangles, draws: file.draws };
|
|
159
|
+
const far: FarRow = { ...meshOnly, files: [file.hash, impostorFile.hash], impostor: { file: impostorFile.hash, ...baked.row },
|
|
160
|
+
compressed: file.compressed + impostorFile.compressed, decoded: file.decoded + impostorFile.decoded, gpu: file.gpu + impostorFile.gpu };
|
|
161
|
+
return { far, meshOnly, file, impostorFile, bytes, impostor: baked.png, look: { family: look.family, haze: look.haze, ...(look.grade === undefined ? {} : { grade: look.grade }), ...(look.band === undefined ? {} : { band: look.band }) } };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Bake one far proxy (a single-draw GLB) and its impostor (G539: the camera-facing tile atlas the far tier draws past the
|
|
166
|
+
* proxy's band, `bakeFarImpostor`), refused over any §3.2 far cap. Only one of the two draws at a time; both are resident.
|
|
167
|
+
*/
|
|
168
|
+
export async function bakeFarPlaceholder(grid: PlaceholderGrid, look: PlaceholderLook, parts: readonly PlaceholderPart[] = []): Promise<{ manifest: FarManifest; bytes: Uint8Array; impostor: Uint8Array }> {
|
|
169
|
+
const { far, file, impostorFile, bytes, impostor, look: runtime } = await farRows(grid, look, parts);
|
|
170
|
+
if (!farWithinCaps(far)) throw new Error(`Far proxy exceeds content caps: ${JSON.stringify(far)}`);
|
|
171
|
+
return { manifest: { far, file, impostorFile, look: runtime }, bytes, impostor };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* `wildshard build`'s generic far proxy for a shard that ships none: the far bake with its impostor, or the GLB alone
|
|
176
|
+
* (the proxy then draws at every distance) when the pair would breach a §3.2 far cap, as an authored far's impostor is
|
|
177
|
+
* dropped (`authoredFarImpostor`); refused only when the GLB alone breaches one. `impostor` is null when dropped.
|
|
178
|
+
*/
|
|
179
|
+
export async function projectFarPlaceholder(grid: PlaceholderGrid, look: PlaceholderLook, caps: FarCaps = CONTENT_CAPS.far): Promise<{ far: FarRow; file: PlaceholderFile; bytes: Uint8Array; impostor: { file: PlaceholderFile; bytes: Uint8Array } | null }> {
|
|
180
|
+
const rows = await farRows(grid, look, []);
|
|
181
|
+
if (farWithinCaps(rows.far, caps)) return { far: rows.far, file: rows.file, bytes: rows.bytes, impostor: { file: rows.impostorFile, bytes: rows.impostor } };
|
|
182
|
+
if (!farWithinCaps(rows.meshOnly, caps)) throw new Error(`Far proxy exceeds content caps: ${JSON.stringify(rows.meshOnly)}`);
|
|
183
|
+
console.warn(`far impostor dropped: the proxy and its impostor are ${rows.far.decoded + rows.far.gpu} B resident (cap ${caps.resident}), ${rows.far.compressed} B compressed (cap ${caps.compressed}); the far proxy draws at every distance`);
|
|
184
|
+
return { far: rows.meshOnly, file: rows.file, bytes: rows.bytes, impostor: null };
|
|
158
185
|
}
|
|
159
186
|
|
|
160
187
|
/** A baked `terrain.bin` (the WSTR lattice) as a placeholder grid. */
|
|
@@ -504,7 +531,7 @@ async function authoredFarImpostor(shard: Shardfile, assets: Map<string, Uint8Ar
|
|
|
504
531
|
const baked = await bakeFarImpostor(geometry, 'pbr');
|
|
505
532
|
const file: PlaceholderFile = { hash: hashImmutableBytes(baked.png), kind: 'image', compressed: baked.png.length, ...assetCost('image', baked.png), dependencies: [], critical: false };
|
|
506
533
|
const next = { ...far, files: [...far.files, file.hash], impostor: { file: file.hash, ...baked.row }, compressed: far.compressed + file.compressed, decoded: far.decoded + file.decoded, gpu: far.gpu + file.gpu };
|
|
507
|
-
if (next
|
|
534
|
+
if (!farWithinCaps(next)) return shard;
|
|
508
535
|
assets.set(file.hash, baked.png);
|
|
509
536
|
return { ...shard, files: [...shard.files, file], far: next };
|
|
510
537
|
}
|
|
@@ -567,9 +594,9 @@ export async function projectPlaceholders(project: Shardfile, assets: Map<string
|
|
|
567
594
|
const grid = colliderGrid(collider), look = shardfileLook(shard), files = [...shard.files];
|
|
568
595
|
let far = shard.far, near = shard.near;
|
|
569
596
|
if (far === null) {
|
|
570
|
-
const baked = await
|
|
571
|
-
far = baked.
|
|
572
|
-
|
|
597
|
+
const baked = await projectFarPlaceholder(grid, look);
|
|
598
|
+
far = baked.far; files.push(baked.file); assets.set(baked.file.hash, baked.bytes);
|
|
599
|
+
if (baked.impostor !== null) { files.push(baked.impostor.file); assets.set(baked.impostor.file.hash, baked.impostor.bytes); }
|
|
573
600
|
}
|
|
574
601
|
if (near === undefined) {
|
|
575
602
|
const baked = await bakeNearPlaceholder({ grid, look, prototypes: await shardfileWorld(shard, assets), residentBytes: Math.min(NEAR_BAKE.residentBytes, NEAR_PLACEHOLDER_LIMITS.contentBytes) });
|
|
@@ -59,7 +59,7 @@ function isDraft(folder: string): boolean {
|
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
interface Admitted { readonly shard: Shardfile; readonly observed: PerformanceObservations; readonly policy: 'warn' | 'refuse' }
|
|
62
|
-
export interface CheckOptions { readonly decisionLegacyLines?: number; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: (folder: string, source: string, options?: { readonly draftWarning?: boolean }) => Promise<string> }
|
|
62
|
+
export interface CheckOptions { readonly decisionLegacyLines?: number; readonly output?: string; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: (folder: string, source: string, options?: { readonly draftWarning?: boolean }) => Promise<string> }
|
|
63
63
|
|
|
64
64
|
/** Lint, build (no client; the shard file too, SA3), validate the built folder, prove its tape and read its report card. */
|
|
65
65
|
export async function checkProject(projectPath: string, outputPath: string | undefined, options: CheckOptions = {}): Promise<CheckResult> {
|
|
@@ -73,6 +73,8 @@ export async function checkProject(projectPath: string, outputPath: string | und
|
|
|
73
73
|
// SA16 (J314): a hand-written source (`--template blender`) has nothing to build: format's pack settles it into the
|
|
74
74
|
// built folder, which is then admitted as a built shard is.
|
|
75
75
|
const handwritten = isHandwrittenSource(project);
|
|
76
|
+
// TS21: a declared output is built from code; a hand-written shard file has one product and no outputs.
|
|
77
|
+
if (handwritten && options.output !== undefined) throw new Error(`${project}: a hand-written shard file declares no outputs, so check takes no --output`);
|
|
76
78
|
const settleInto = async (source: string): Promise<Shardfile> => {
|
|
77
79
|
// Its build output goes beside src/, never inside the folder pack reads (or a built folder named as a source).
|
|
78
80
|
if (!isRepoSource(source)) throw new Error(`${source}: a hand-written shard file builds only from a repo's src/: run wildshard check on the repo`);
|
|
@@ -91,6 +93,7 @@ export async function checkProject(projectPath: string, outputPath: string | und
|
|
|
91
93
|
? { status: 'skip', note: 'a hand-written shard file: no code to lint' } : lintProject(project)),
|
|
92
94
|
build: async (): Promise<StepOutcome> => {
|
|
93
95
|
const shard = handwritten ? await settleInto(project) : await buildProject(project, output, { outputFormat: 2, client: null, placeholders: true, admit,
|
|
96
|
+
...(options.output === undefined ? {} : { output: options.output }),
|
|
94
97
|
...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }),
|
|
95
98
|
...(options.manifest === undefined ? {} : { manifest: options.manifest }) });
|
|
96
99
|
output ??= resolve(shardOutputRoot(project), 'public/shardfiles', shard.identity.slug);
|