@wildshard/dev 0.0.0 → 0.4.0
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/bin/wildshard.mjs +75 -0
- package/lint/host-callbacks.d.mts +6 -0
- package/lint/host-callbacks.mjs +123 -0
- package/lint/ratchet.json +3 -0
- package/package.json +95 -4
- package/scripts/audit-assets.d.mts +10 -0
- package/scripts/audit-assets.mjs +151 -0
- package/scripts/bake/coatFiles.d.mts +6 -0
- package/scripts/bake/coatFiles.mjs +37 -0
- package/scripts/bake/navmeshGround.ts +22 -0
- package/scripts/bake/near-placeholder.mjs +331 -0
- package/scripts/bake/viewmodelBytes.ts +26 -0
- package/scripts/bake/viewmodelPage.ts +11 -0
- package/scripts/bake-catalogue.mjs +44 -0
- package/scripts/bake-check.mjs +54 -0
- package/scripts/bake-chunk.mjs +124 -0
- package/scripts/bake-cloud-field.mjs +24 -0
- package/scripts/bake-coats.mjs +110 -0
- package/scripts/bake-data-maps.d.mts +24 -0
- package/scripts/bake-data-maps.mjs +78 -0
- package/scripts/bake-entry-programs.mjs +126 -0
- package/scripts/bake-geometry.mjs +106 -0
- package/scripts/bake-ktx2.mjs +477 -0
- package/scripts/bake-map-glb.mjs +127 -0
- package/scripts/bake-map-rest.d.mts +7 -0
- package/scripts/bake-map-rest.mjs +50 -0
- package/scripts/bake-maps.mjs +200 -0
- package/scripts/bake-navmesh.mjs +259 -0
- package/scripts/bake-packs.mjs +129 -0
- package/scripts/bake-pickups.mjs +102 -0
- package/scripts/bake-query-terrain.mjs +64 -0
- package/scripts/bake-textures.mjs +80 -0
- package/scripts/bake-viewmodel-sets.mjs +137 -0
- package/scripts/bake-voxel-ao.mjs +119 -0
- package/scripts/bake-water-ripples.mjs +25 -0
- package/scripts/browser-imports.d.mts +2 -0
- package/scripts/browser-imports.mjs +40 -0
- package/scripts/browser-machine-loader-proof.mjs +39 -0
- package/scripts/browser-machine-loader.d.mts +8 -0
- package/scripts/browser-machine-loader.mjs +87 -0
- package/scripts/browser-playwright.d.mts +10 -0
- package/scripts/browser-playwright.mjs +5 -0
- package/scripts/browser-test.d.mts +4 -0
- package/scripts/browser-test.mjs +18 -0
- package/scripts/build-sdk.mjs +95 -0
- package/scripts/build-shardfiles.d.mts +7 -0
- package/scripts/build-shardfiles.mjs +230 -0
- package/scripts/capture-hero.mjs +211 -0
- package/scripts/chromium-keychain.d.mts +1 -0
- package/scripts/chromium-keychain.mjs +7 -0
- package/scripts/entry-reads/crawl.ts +152 -0
- package/scripts/gen-host-catalogue.d.mts +14 -0
- package/scripts/gen-host-catalogue.mjs +108 -0
- package/scripts/gen-shards.d.mts +17 -0
- package/scripts/gen-shards.mjs +311 -0
- package/scripts/goldens/plot-inputs.d.mts +12 -0
- package/scripts/goldens/plot-inputs.mjs +46 -0
- package/scripts/gpu-texmem.mjs +98 -0
- package/scripts/ktx2-ab.mjs +111 -0
- package/scripts/map-bake-frames.d.mts +4 -0
- package/scripts/map-bake-frames.mjs +23 -0
- package/scripts/map-world.mjs +162 -0
- package/scripts/memory-product.mjs +62 -0
- package/scripts/music/export-midi.mjs +69 -0
- package/scripts/named-blob-output.d.mts +8 -0
- package/scripts/named-blob-output.mjs +48 -0
- package/scripts/practice/verify_unimate_skin.mjs +356 -0
- package/scripts/preparation-browser.mjs +25 -0
- package/scripts/preparation-seed.mjs +15 -0
- package/scripts/prepare-product.d.mts +14 -0
- package/scripts/prepare-product.mjs +133 -0
- package/scripts/prove-walk.mjs +83 -0
- package/scripts/push-tables.d.mts +1 -0
- package/scripts/push-tables.mjs +28 -0
- package/scripts/record-shard-mounts.mjs +133 -0
- package/scripts/section-inventory.ts +209 -0
- package/scripts/shard-build-pool.d.mts +4 -0
- package/scripts/shard-build-pool.mjs +53 -0
- package/scripts/shard-milestones.d.mts +15 -0
- package/scripts/shard-milestones.mjs +105 -0
- package/scripts/shard-progress.mjs +212 -0
- package/scripts/shardfile-cold-boot.mjs +79 -0
- package/scripts/shardfile-rolldown.d.mts +2 -0
- package/scripts/shardfile-rolldown.mjs +32 -0
- package/scripts/shardfile-vite.d.mts +4 -0
- package/scripts/shardfile-vite.mjs +20 -0
- package/scripts/site-facts.mjs +88 -0
- package/scripts/test-template-gate.mjs +44 -0
- package/scripts/tex-tiers.mjs +240 -0
- package/scripts/unused-assets.mjs +173 -0
- package/scripts/wildshard.d.mts +4 -0
- package/scripts/wildshard.mjs +146 -0
- package/scripts/witness-generation.d.mts +10 -0
- package/scripts/witness-generation.mjs +45 -0
- package/src/.oxlintrc.json +12 -0
- package/src/cli/bin.mjs +8 -0
- package/src/cli/content-command.ts +44 -0
- package/src/cli/content.ts +287 -0
- package/src/cli/grid/command.ts +48 -0
- package/src/cli/grid/grid.ts +155 -0
- package/src/cli/help.ts +262 -0
- package/src/cli/hero/adopt.ts +109 -0
- package/src/cli/install-home.ts +40 -0
- package/src/cli/main.ts +142 -0
- package/src/cli/version.ts +63 -0
- package/src/server/app.ts +19 -0
- package/src/server/serve.ts +49 -0
- package/src/sharddev/bake/json.mjs +84 -0
- package/src/sharddev/bake/mapRest.ts +57 -0
- package/src/sharddev/bake/nativeRaster.ts +106 -0
- package/src/sharddev/bake/source-loader.mjs +55 -0
- package/src/sharddev/bake/splatLayers.ts +29 -0
- package/src/sharddev/bootInventory.ts +132 -0
- package/src/sharddev/check.ts +125 -0
- package/src/sharddev/checkProject.ts +134 -0
- package/src/sharddev/cli.ts +207 -0
- package/src/sharddev/dev.ts +150 -0
- package/src/sharddev/devClient.ts +120 -0
- package/src/sharddev/devRoot.ts +6 -0
- package/src/sharddev/engineMusic.ts +23 -0
- package/src/sharddev/projectEntryProof.ts +32 -0
- package/src/sharddev/test/diskScriptScenario.ts +88 -0
- package/src/sharddev/test/scriptScenario.ts +254 -0
- package/src/sharddev/tsconfig.json +3 -0
- package/src/sharddev/watch/page.ts +288 -0
- package/src/sharddev/watch/pageEntry.ts +44 -0
- package/src/sharddev/watch/parity-baseline.json +22 -0
- package/src/sharddev/watch/parity.mjs +194 -0
- package/src/sharddev/watch/proof.mjs +199 -0
- package/src/sharddev/watch/socket.ts +57 -0
- package/src/sharddev/watch/watch.ts +382 -0
- package/src/shared/health.ts +10 -0
- package/src/tools/build-web.ts +59 -0
- package/src/web/app.tsx +53 -0
- package/src/web/index.html +12 -0
- package/src/web/main.tsx +10 -0
- package/tsconfig.author.json +25 -0
- package/tsconfig.json +47 -0
- package/README.md +0 -3
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// `wildshard check` (meta SHARD-AUTHORING SA4, J317): lint, build, validate, prove and the report card in one verb, with
|
|
2
|
+
// one verdict. The loop is new, dev, check, hero, upload. `--json` prints CheckResult below and nothing else on stdout.
|
|
3
|
+
// SA21: every refusal carries a rule id, a one-line fix and a GUIDE.md link, from refusals.ts.
|
|
4
|
+
import type { ShardfileCheckReport } from '@wildshard/engine/game/shardfile/checkReport';
|
|
5
|
+
import { authorErrorText } from '@wildshard/sdk/internal/authorError';
|
|
6
|
+
import { refusalCode, refusalHint, refusalNote, type RefusalStep } from '@wildshard/upload/sharddev/refusals';
|
|
7
|
+
import { diagnosticNow } from '@wildshard/sdk/internal/diagnosticClock';
|
|
8
|
+
|
|
9
|
+
/** The five steps, in the order they run. */
|
|
10
|
+
export type CheckStepName = 'lint' | 'build' | 'validate' | 'prove' | 'report';
|
|
11
|
+
/** A skipped step neither passes nor fails the verdict; its note says why it did not run. */
|
|
12
|
+
export type CheckStatus = 'pass' | 'fail' | 'skip';
|
|
13
|
+
|
|
14
|
+
/** One refusal: what was wrong, the rule that said so, its fix and its GUIDE.md section (`GUIDE.md#<anchor>`). */
|
|
15
|
+
export interface CheckRefusal {
|
|
16
|
+
readonly step: CheckStepName;
|
|
17
|
+
readonly rule: string;
|
|
18
|
+
readonly message: string;
|
|
19
|
+
readonly fix: string;
|
|
20
|
+
readonly guide: string;
|
|
21
|
+
readonly file?: string;
|
|
22
|
+
}
|
|
23
|
+
/** A refusal as a step reports it: a lint diagnostic brings oxlint's code and help, a shard-format refusal its stable
|
|
24
|
+
* code (SA41); refusals.ts fills in the rest. */
|
|
25
|
+
export interface StepRefusal { readonly message: string; readonly lint?: { readonly code: string | null; readonly help: string | null }; readonly code?: string | undefined; readonly file?: string; readonly as?: RefusalStep }
|
|
26
|
+
/** A warning: the same fields as a refusal, but it does not fail the verdict (an unprepared draft, J198). */
|
|
27
|
+
export type CheckWarning = CheckRefusal;
|
|
28
|
+
/** One step's result and wall-clock duration in milliseconds. */
|
|
29
|
+
export interface CheckStep { readonly name: CheckStepName; readonly status: CheckStatus; readonly ms: number; readonly note?: string }
|
|
30
|
+
/** The `--json` document (version 1). `verdict` is `fail` when any step failed; `output` is the built product folder, null when the build failed.
|
|
31
|
+
* `warnings` never fail the verdict. */
|
|
32
|
+
export interface CheckResult {
|
|
33
|
+
readonly version: 1;
|
|
34
|
+
readonly verdict: 'pass' | 'fail';
|
|
35
|
+
readonly project: string;
|
|
36
|
+
readonly output: string | null;
|
|
37
|
+
readonly ms: number;
|
|
38
|
+
readonly steps: readonly CheckStep[];
|
|
39
|
+
readonly refusals: readonly CheckRefusal[];
|
|
40
|
+
readonly warnings: readonly CheckWarning[];
|
|
41
|
+
/** SP19: the identical structured engine report retained by the upload cook. */
|
|
42
|
+
readonly check?: ShardfileCheckReport;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What a step reports; a thrown error is a `fail` with the error's words as its one refusal. */
|
|
46
|
+
export interface StepOutcome {
|
|
47
|
+
readonly status: CheckStatus;
|
|
48
|
+
readonly note?: string;
|
|
49
|
+
readonly refusals?: readonly StepRefusal[];
|
|
50
|
+
readonly warnings?: readonly StepRefusal[];
|
|
51
|
+
}
|
|
52
|
+
/** The steps' work; validate, prove and report need a built product, so they skip when build fails. */
|
|
53
|
+
export type CheckSteps = Readonly<Record<CheckStepName, () => Promise<StepOutcome>>>;
|
|
54
|
+
|
|
55
|
+
const ORDER: readonly CheckStepName[] = ['lint', 'build', 'validate', 'prove', 'report'];
|
|
56
|
+
const NEEDS_BUILD = new Set<CheckStepName>(['validate', 'prove', 'report']);
|
|
57
|
+
|
|
58
|
+
async function outcomeOf(work: () => Promise<StepOutcome>): Promise<StepOutcome> {
|
|
59
|
+
try { return await work(); }
|
|
60
|
+
catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error), code: refusalCode(error) }] }; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Run every step in order, timing each, and give the verdict. `output` is read after the build; `now` is for tests. */
|
|
64
|
+
export async function runCheck(project: string, output: () => string | null, steps: CheckSteps, now: () => number = diagnosticNow): Promise<CheckResult> {
|
|
65
|
+
const started = now(), rows: CheckStep[] = [], refusals: CheckRefusal[] = [], warnings: CheckWarning[] = [];
|
|
66
|
+
const named = (step: CheckStepName, { message, lint, code, file, as }: StepRefusal): CheckRefusal => {
|
|
67
|
+
// SA3: build's shard file step names its rules by its own step (a format refusal is not a source one).
|
|
68
|
+
const { rule, fix, guide } = refusalNote(as ?? step, message, { lint, code });
|
|
69
|
+
return { step, rule, message, fix, guide, ...(file === undefined ? {} : { file }) };
|
|
70
|
+
};
|
|
71
|
+
let built = true;
|
|
72
|
+
for (const name of ORDER) {
|
|
73
|
+
const begun = now();
|
|
74
|
+
const outcome: StepOutcome = NEEDS_BUILD.has(name) && !built ? { status: 'skip', note: 'build failed' } : await outcomeOf(steps[name]);
|
|
75
|
+
if (name === 'build' && outcome.status !== 'pass') built = false;
|
|
76
|
+
const ms = Math.round(now() - begun);
|
|
77
|
+
rows.push({ name, status: outcome.status, ms, ...(outcome.note === undefined ? {} : { note: outcome.note }) });
|
|
78
|
+
for (const refusal of outcome.refusals ?? []) refusals.push(named(name, refusal));
|
|
79
|
+
for (const warning of outcome.warnings ?? []) warnings.push(named(name, warning));
|
|
80
|
+
}
|
|
81
|
+
const verdict = rows.some(row => row.status === 'fail') ? 'fail' : 'pass';
|
|
82
|
+
return { version: 1, verdict, project, output: built ? output() : null, ms: Math.round(now() - started), steps: rows, refusals, warnings };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface LintLabel { readonly span?: { readonly line?: number; readonly column?: number } }
|
|
86
|
+
interface LintDiagnostic { readonly message?: string; readonly code?: string; readonly help?: string; readonly filename?: string; readonly labels?: readonly LintLabel[] }
|
|
87
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
88
|
+
const textOrNull = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null);
|
|
89
|
+
|
|
90
|
+
function lintRefusal(raw: LintDiagnostic): StepRefusal {
|
|
91
|
+
const span = raw.labels?.[0]?.span, file = typeof raw.filename === 'string' ? raw.filename : undefined;
|
|
92
|
+
const where = file === undefined ? undefined : span?.line === undefined ? file : `${file}:${span.line}:${span.column ?? 1}`;
|
|
93
|
+
return { message: textOrNull(raw.message) ?? 'lint refusal', lint: { code: textOrNull(raw.code), help: textOrNull(raw.help) }, ...(where === undefined ? {} : { file: where }) };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Read `oxlint --format json`: each diagnostic becomes a refusal; no linted file is a skip, never a pass. */
|
|
97
|
+
export function lintOutcome(stdout: string, exitCode: number | null): StepOutcome {
|
|
98
|
+
if (stdout.includes('No files found to lint')) return { status: 'skip', note: 'oxlint found no files to lint here (a git-ignored path?)' };
|
|
99
|
+
let parsed: unknown;
|
|
100
|
+
try { parsed = JSON.parse(stdout); }
|
|
101
|
+
catch {
|
|
102
|
+
// What oxlint said instead (a plugin that would not load, a bad config): its first lines name the cause.
|
|
103
|
+
const said = stdout.trim().split('\n').slice(0, 6).join(' / ').slice(0, 600);
|
|
104
|
+
return { status: 'fail', refusals: [{ message: `oxlint exited ${String(exitCode)} without a report${said === '' ? '' : `: ${said}`}` }] };
|
|
105
|
+
}
|
|
106
|
+
if (!isRecord(parsed) || !Array.isArray(parsed['diagnostics'])) return { status: 'fail', refusals: [{ message: 'oxlint report has no diagnostics' }] };
|
|
107
|
+
const diagnostics: readonly unknown[] = parsed['diagnostics'];
|
|
108
|
+
const refusals = diagnostics.filter(isRecord).map(row => lintRefusal(row));
|
|
109
|
+
if (parsed['number_of_files'] === 0) return { status: 'skip', note: 'oxlint found no files to lint here (a git-ignored path?)' };
|
|
110
|
+
return refusals.length === 0 && exitCode === 0 ? { status: 'pass' } : { status: 'fail', refusals };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const SECONDS = 1000;
|
|
114
|
+
/** The plain-text form: one line per step, each refusal and warning with its rule, fix and guide link, then the verdict. */
|
|
115
|
+
export function checkLines(result: CheckResult): string[] {
|
|
116
|
+
const lines = result.steps.map(step => `${step.name.padEnd(8)} ${step.status} (${(step.ms / SECONDS).toFixed(1)} s)${step.note === undefined ? '' : `: ${step.note}`}`);
|
|
117
|
+
for (const refusal of result.refusals) {
|
|
118
|
+
lines.push(` ${refusal.step}${refusal.file === undefined ? '' : ` ${refusal.file}`}: ${refusal.message}`, ` ${refusalHint(refusal)}`);
|
|
119
|
+
}
|
|
120
|
+
for (const warning of result.warnings) {
|
|
121
|
+
lines.push(` ${warning.step}: warning: ${warning.message}`, ` ${refusalHint(warning)}`);
|
|
122
|
+
}
|
|
123
|
+
lines.push(`check ${result.verdict} in ${(result.ms / SECONDS).toFixed(1)} s`);
|
|
124
|
+
return lines;
|
|
125
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { spawnWarnings } from '@wildshard/sdk/internal/spawnWarnings';
|
|
2
|
+
// The real steps behind `wildshard check` (SA4); check.ts runs them in order and gives the verdict.
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Lint runs oxlint (the repo's or the SDK's) as a child process.
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- The author proof tape is an explicit local input file.
|
|
6
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
7
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Resolve the project, its output and the SDK's lint config.
|
|
8
|
+
import { basename, resolve } from 'node:path';
|
|
9
|
+
import * as v from 'valibot';
|
|
10
|
+
import { AuthorProofPlanSchema } from '@wildshard/engine/host/tickProtocol';
|
|
11
|
+
import { proveAuthorSimulation } from '@wildshard/engine/host/headless';
|
|
12
|
+
import { checkShardfile } from '@wildshard/engine/host/checkShardfile';
|
|
13
|
+
import type { ShardfileCheckReport } from '@wildshard/engine/game/shardfile/checkReport';
|
|
14
|
+
import type { Shardfile } from '@wildshard/format/shardSchema';
|
|
15
|
+
import { buildProject } from '@wildshard/build/project';
|
|
16
|
+
import { isHandwrittenSource, isRepoSource, shardOutputRoot } from '@wildshard/upload/sharddev/shardSource';
|
|
17
|
+
import { handwrittenIdentity } from '@wildshard/sdk/internal/handwritten';
|
|
18
|
+
import { settleHandwrittenCreatureLayers } from '@wildshard/sdk/internal/handwrittenCreatureLayers';
|
|
19
|
+
import { validateOutputProduct } from '@wildshard/sdk/outputProduct';
|
|
20
|
+
import { engineMusicLine } from './engineMusic';
|
|
21
|
+
import { lintOutcome, runCheck, type CheckResult, type StepOutcome } from './check';
|
|
22
|
+
import type { ProjectManifestSource } from '@wildshard/sdk/projectManifest';
|
|
23
|
+
import { authorErrorText } from '@wildshard/sdk/internal/authorError';
|
|
24
|
+
import { refusalCode } from '@wildshard/upload/sharddev/refusals';
|
|
25
|
+
import { DRAFT_SDK, draftMessage } from '@wildshard/upload/sharddev/draft';
|
|
26
|
+
import { authorLintPlan } from '@wildshard/sdk/internal/authorLint';
|
|
27
|
+
import { assertCreatureDeclarations } from '@wildshard/sdk/internal/creatureLayers';
|
|
28
|
+
|
|
29
|
+
/** The author proof tape `check` runs when the project has one (format: `AuthorProofPlanSchema`). */
|
|
30
|
+
export const PROOF_FILE = 'proof.json';
|
|
31
|
+
/** The author proof tape at `path`; its refusal names the file first, so it reads as the tape's (SA21). */
|
|
32
|
+
export function readProofTape(path: string): v.InferOutput<typeof AuthorProofPlanSchema> {
|
|
33
|
+
try { return v.parse(AuthorProofPlanSchema, JSON.parse(readFileSync(path, 'utf8'))); }
|
|
34
|
+
catch (error) { throw new Error(`${basename(path)}: ${authorErrorText(error)}`, { cause: error }); }
|
|
35
|
+
}
|
|
36
|
+
// The bundled CLI defines import.meta.dirname as the package's src/sharddev, so the package root is two up.
|
|
37
|
+
// SDK-SPLIT SP8c: the sdk (its lint config and oxlint) sits beside this package, in the workspace and under
|
|
38
|
+
// node_modules/@wildshard alike.
|
|
39
|
+
const SDK_ROOT = resolve(import.meta.dirname, '../../../sdk');
|
|
40
|
+
|
|
41
|
+
/** The author lint over the project's source: its repo's `.oxlintrc.author.json`, else the SDK's (authorLint.ts). */
|
|
42
|
+
function lintProject(project: string): StepOutcome {
|
|
43
|
+
const plan = authorLintPlan(project, SDK_ROOT);
|
|
44
|
+
if (plan.kind === 'skip') return { status: 'skip', note: plan.note };
|
|
45
|
+
const done = spawnSync(plan.bin, plan.args, { cwd: plan.cwd, env: { ...process.env, ...plan.env }, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
|
46
|
+
if (done.error !== undefined) return { status: 'fail', refusals: [{ message: `oxlint did not run: ${done.error.message}` }] };
|
|
47
|
+
return lintOutcome(`${done.stdout}${done.stdout.trim() === '' ? done.stderr : ''}`, done.status);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** J198: a built folder whose index says sdk 0.2 is a draft; upload refuses it until `wildshard prepare` runs. */
|
|
51
|
+
function isDraft(folder: string): boolean {
|
|
52
|
+
const index: unknown = JSON.parse(readFileSync(resolve(folder, 'shard.json'), 'utf8'));
|
|
53
|
+
return typeof index === 'object' && index !== null && 'sdk' in index && index.sdk === DRAFT_SDK;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface Admitted { readonly check: ShardfileCheckReport }
|
|
57
|
+
export interface CheckOptions { readonly decisionLegacyLines?: number; readonly output?: string; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: (folder: string, source: string, options?: { readonly draftWarning?: boolean }) => Promise<string> }
|
|
58
|
+
|
|
59
|
+
/** Lint, build (no client; the shard file too, SA3), validate the built folder, prove its tape and read its report card. */
|
|
60
|
+
export async function checkProject(projectPath: string, outputPath: string | undefined, options: CheckOptions = {}): Promise<CheckResult> {
|
|
61
|
+
const project = resolve(projectPath);
|
|
62
|
+
let output = outputPath === undefined ? undefined : resolve(outputPath), admitted: Admitted | undefined;
|
|
63
|
+
const admit = async (shard: Shardfile, assets: ReadonlyMap<string, Uint8Array>, policy: 'warn' | 'refuse', sections: ReadonlyMap<string, unknown>): Promise<void> => {
|
|
64
|
+
assertCreatureDeclarations(shard.rows);
|
|
65
|
+
admitted = { check: await checkShardfile(shard, assets, {sections, policy}) };
|
|
66
|
+
};
|
|
67
|
+
// SA16 (J314): a hand-written source (`--template blender`) has nothing to build: format's pack settles it into the
|
|
68
|
+
// built folder, which is then admitted as a built shard is.
|
|
69
|
+
const handwritten = isHandwrittenSource(project);
|
|
70
|
+
// TS21: a declared output is built from code; a hand-written shard file has one product and no outputs.
|
|
71
|
+
if (handwritten && options.output !== undefined) throw new Error(`${project}: a hand-written shard file declares no outputs, so check takes no --output`);
|
|
72
|
+
const settleInto = async (source: string): Promise<Shardfile> => {
|
|
73
|
+
// Its build output goes beside src/, never inside the folder pack reads (or a built folder named as a source).
|
|
74
|
+
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`);
|
|
75
|
+
output ??= resolve(shardOutputRoot(source), 'public/shardfiles', handwrittenIdentity(source).slug);
|
|
76
|
+
const checked = settleHandwrittenCreatureLayers(source, output);
|
|
77
|
+
await admit(checked.shard, checked.assets, checked.shard.runtime === null ? 'refuse' : 'warn', checked.sections);
|
|
78
|
+
return checked.shard;
|
|
79
|
+
};
|
|
80
|
+
const built = (): string => {
|
|
81
|
+
if (output === undefined) throw new Error('no built shard file folder');
|
|
82
|
+
return output;
|
|
83
|
+
};
|
|
84
|
+
const result = await runCheck(project, (): string | null => output ?? null, {
|
|
85
|
+
lint: async (): Promise<StepOutcome> => await Promise.resolve(handwritten
|
|
86
|
+
? { status: 'skip', note: 'a hand-written shard file: no code to lint' } : lintProject(project)),
|
|
87
|
+
build: async (): Promise<StepOutcome> => {
|
|
88
|
+
const shard = handwritten ? await settleInto(project) : await buildProject(project, output, { outputFormat: 2, client: null, placeholders: true, admit,
|
|
89
|
+
...(options.output === undefined ? {} : { output: options.output }),
|
|
90
|
+
...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }),
|
|
91
|
+
...(options.manifest === undefined ? {} : { manifest: options.manifest }) });
|
|
92
|
+
output ??= resolve(shardOutputRoot(project), 'public/shardfiles', shard.identity.slug);
|
|
93
|
+
let file: string | undefined;
|
|
94
|
+
// The draft warning goes in the verdict (below), so the writer leaves it out.
|
|
95
|
+
try { file = await options.writeShardfile?.(output, project, { draftWarning: false }); }
|
|
96
|
+
catch (error) { return { status: 'fail', refusals: [{ message: authorErrorText(error), code: refusalCode(error), as: 'shardfile' }] }; }
|
|
97
|
+
const warnings = isDraft(output) ? [{ message: draftMessage(shard.identity.slug), as: 'shardfile' as const }] : [];
|
|
98
|
+
return { status: 'pass', note: `built ${shard.identity.slug} v${shard.version}${file === undefined ? '' : `, ${file}`}`, warnings };
|
|
99
|
+
},
|
|
100
|
+
validate: async (): Promise<StepOutcome> => {
|
|
101
|
+
const checked = validateOutputProduct(built());
|
|
102
|
+
// AUDIO AU18 (SDK-SPLIT SP7b: here, not in the build): the engine music the shard plays; a name the engine lacks refuses.
|
|
103
|
+
const music = engineMusicLine(checked.shard.identity.slug, checked.sections.get('audio/audio'));
|
|
104
|
+
const note = `${checked.shard.identity.slug}: format 2 inventory, byte kinds and section schemas${music === undefined ? '' : `; ${music}`}`;
|
|
105
|
+
return await Promise.resolve({ status: 'pass', note, warnings: spawnWarnings(checked.shard) });
|
|
106
|
+
},
|
|
107
|
+
prove: async (): Promise<StepOutcome> => {
|
|
108
|
+
const tape = resolve(project, PROOF_FILE);
|
|
109
|
+
if (!existsSync(tape)) return { status: 'skip', note: `no ${PROOF_FILE}: add an author proof tape to prove the shard's quests` };
|
|
110
|
+
const { shard, assets, sections } = validateOutputProduct(built());
|
|
111
|
+
if (shard.runtime !== null) return { status: 'skip', note: 'native gameplay: the author proof needs data-only gameplay' };
|
|
112
|
+
const plan = readProofTape(tape);
|
|
113
|
+
// The output's sections name each decision's ABI; without them a v1 decision fails `Import signature outside ABI`.
|
|
114
|
+
const report = await proveAuthorSimulation(shard, assets, plan, sections);
|
|
115
|
+
return { status: 'pass', note: `${report.ticks} ticks, ${report.ledger.facts.length} facts filed` };
|
|
116
|
+
},
|
|
117
|
+
report: async (): Promise<StepOutcome> => {
|
|
118
|
+
if (admitted === undefined) throw new Error('the build admitted no shard to report on');
|
|
119
|
+
const card = admitted.check.performance;
|
|
120
|
+
const refused = admitted.check.failures;
|
|
121
|
+
// TC-NE6 (NEW-SHARD-E2E F6): a count with no names left the author guessing; each warning prints, marked report-only.
|
|
122
|
+
const reported = card.issues.filter(issue => issue.severity !== 'refusal');
|
|
123
|
+
const warnings = reported.length;
|
|
124
|
+
// SP7c: the simulation numbers `wildshard validate` printed before it stopped running the engine.
|
|
125
|
+
const { proof } = admitted.check;
|
|
126
|
+
const sim = typeof proof === 'string' ? `simulation ${proof}` : `${proof.ticks} sim ticks, ${proof.lanes} edge lanes, ${proof.steps} capsule steps${proof.portalTransfers === undefined ? '' : `, ${proof.portalTransfers} portal transfers`}`;
|
|
127
|
+
const note = `${(card.download.total / 1024 / 1024).toFixed(2)} MB download, ~${card.estimatedPlayable.seconds.toFixed(1)} s to playable, ${warnings} warning${warnings === 1 ? '' : 's'}; ${sim}`;
|
|
128
|
+
return await Promise.resolve({ status: admitted.check.pass ? 'pass' : 'fail', note,
|
|
129
|
+
refusals: refused.map(issue => ({ message: issue.message, code: issue.code })),
|
|
130
|
+
warnings: reported.map(issue => ({ message: `${issue.metric}: ${String(issue.actual)} over ${String(issue.limit)} (a report-only cap: upload still takes it)` })) });
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
return {...result, ...(admitted === undefined ? {} : {check: admitted.check})};
|
|
134
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { printSpawnWarnings } from '@wildshard/sdk/internal/spawnWarnings';
|
|
2
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- The author CLI accepts filesystem project/output paths.
|
|
3
|
+
import { basename, dirname, relative, resolve } from 'node:path';
|
|
4
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- `prove` tells a project from a built product by its config file.
|
|
5
|
+
import { existsSync } from 'node:fs';
|
|
6
|
+
import { readProjectAssets, validateProject } from '@wildshard/build/project';
|
|
7
|
+
import { printStaticReport, runBuild, ShardfileRefusalError, type BuildVerbOptions } from '@wildshard/build/buildVerb';
|
|
8
|
+
import { ShardfileSchema } from '@wildshard/format/shardSchema';
|
|
9
|
+
import { devProject } from './dev';
|
|
10
|
+
import { watchProject } from './watch/watch';
|
|
11
|
+
import { devClient } from './devClient';
|
|
12
|
+
import { proveAuthorSimulation } from '@wildshard/engine/host/headless';
|
|
13
|
+
import { projectPerformancePolicy } from '@wildshard/sdk/internal/performancePolicy';
|
|
14
|
+
import { assetOverdraw } from '@wildshard/sdk/assets';
|
|
15
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- The CLI releases its author server on termination.
|
|
16
|
+
import process from 'node:process';
|
|
17
|
+
import { synthProject } from '@wildshard/build/synth';
|
|
18
|
+
import { formatJsonSchemas, schemaAt, schemaDeclaration } from '@wildshard/sdk/formatJsonSchema';
|
|
19
|
+
import { decisionModuleContracts } from '@wildshard/format/scriptContract';
|
|
20
|
+
import { outputPlatformPayloads, outputScriptAdmissionRows, validateOutputProduct } from '@wildshard/sdk/outputProduct';
|
|
21
|
+
import { locatedError } from '@wildshard/sdk/internal/authorError';
|
|
22
|
+
import { templateNamed, writeShardRepo } from '@wildshard/sdk/internal/newProject';
|
|
23
|
+
import { updateShardRepo } from '@wildshard/sdk/internal/agentFiles';
|
|
24
|
+
import { updatePins } from '@wildshard/sdk/internal/updatePins';
|
|
25
|
+
import { findShardSource, isHandwrittenSource, isRepoSource } from '@wildshard/upload/sharddev/shardSource';
|
|
26
|
+
import { checkProject, readProofTape } from './checkProject';
|
|
27
|
+
import { checkLines } from './check';
|
|
28
|
+
import { refusalCode, refusalHint, refusalNote, type RefusalStep } from '@wildshard/upload/sharddev/refusals';
|
|
29
|
+
import { providePortalEntryProof } from '@wildshard/sdk/projectGeneration';
|
|
30
|
+
|
|
31
|
+
// SDK-SPLIT SP8a: generation's static portal walk (Rapier and the engine sim) is this CLI's to hand in; it loads only when
|
|
32
|
+
// a generator asks for it (Nine Dragon's entry proof), so a build that never asks never starts Rapier.
|
|
33
|
+
providePortalEntryProof(async (input, pieces) => (await import('./projectEntryProof')).proveStaticPortalEntries(input, pieces));
|
|
34
|
+
|
|
35
|
+
/** SDK-SPLIT SP7c (D3): build and validate run no simulation. `wildshard check` runs the engine's own full check (the cook's,
|
|
36
|
+
* SP19), which measures script CPU and walks every entry on this host; this line says so where the measure used to print. */
|
|
37
|
+
const SIMULATION_ELSEWHERE = 'simulation, script CPU and entry walk: not run by build or validate; wildshard check runs them (the engine\'s own check, as the upload cook does)';
|
|
38
|
+
/** The verbs whose first operand is a shard source (or, for validate and prove, a built folder). */
|
|
39
|
+
const SOURCE_VERBS: ReadonlySet<string> = new Set(['check', 'synth', 'build', 'dev', 'watch', 'validate', 'prove']);
|
|
40
|
+
type CliOptions = BuildVerbOptions;
|
|
41
|
+
async function runCommand(given: readonly string[], options: CliOptions): Promise<void> {
|
|
42
|
+
// SA16 (J317): a verb given a repo finds its shard source at `src/` or its one `src/shards/<slug>/`.
|
|
43
|
+
const args = SOURCE_VERBS.has(given[0] ?? '') && given[1] !== undefined && !given[1].startsWith('--') ? [given[0] ?? '', findShardSource(given[1]), ...given.slice(2)] : given;
|
|
44
|
+
const [command, input, output, buildFlag] = args;
|
|
45
|
+
if (command === 'schema') {
|
|
46
|
+
if (buildFlag !== undefined) throw new Error('usage: wildshard schema [list|shardfile|root] [JSON-pointer]');
|
|
47
|
+
if (input === undefined || input === 'list') {
|
|
48
|
+
if (output !== undefined) throw new Error('schema list accepts no pointer');
|
|
49
|
+
console.info(JSON.stringify(['shardfile', ...Object.keys(formatJsonSchemas())], null, 2)); return;
|
|
50
|
+
}
|
|
51
|
+
const document = input === 'shardfile' ? schemaDeclaration(ShardfileSchema) : formatJsonSchemas()[input];
|
|
52
|
+
if (document === undefined) throw new Error(`Unknown schema root: ${input}`);
|
|
53
|
+
// Whole root sections accept their authored spelling; deeper paths retain RFC 6901 semantics.
|
|
54
|
+
const pointer = input === 'shardfile' && output !== undefined && /^\/[a-z][A-Za-z0-9]*$/u.test(output)
|
|
55
|
+
? `/properties${output}` : output;
|
|
56
|
+
console.info(JSON.stringify(schemaAt(document, pointer), null, 2)); return;
|
|
57
|
+
}
|
|
58
|
+
if (command === 'check') {
|
|
59
|
+
const rest = args.slice(1), json = rest.includes('--json'), positional = rest.filter(value => !value.startsWith('--'));
|
|
60
|
+
// TS21: --output=<slug> checks one declared output of the folder (scripts/wildshard.mjs composes its manifest and, with
|
|
61
|
+
// no --output on a folder that declares outputs, checks each in turn).
|
|
62
|
+
const outputs = rest.filter(value => value.startsWith('--output=')), selected = outputs[0]?.slice('--output='.length);
|
|
63
|
+
if (positional.length === 0 || positional.length > 2 || rest.some(value => value.startsWith('--') && value !== '--json' && !value.startsWith('--output=')) || rest.filter(value => value === '--json').length > 1 || outputs.length > 1 || selected === '') throw new Error('usage: wildshard check <source> [folder] [--json] [--output=<slug>]');
|
|
64
|
+
// --json: stdout carries the verdict document alone; everything the steps print goes to stderr.
|
|
65
|
+
// (scripts/wildshard.mjs moves log and debug for the whole run; the steps here log with info and warn.)
|
|
66
|
+
const saved = { info: console.info, warn: console.warn }, toError = console.error.bind(console);
|
|
67
|
+
if (json) Object.assign(console, { info: toError, warn: toError });
|
|
68
|
+
let result;
|
|
69
|
+
try { result = await checkProject(findShardSource(positional[0] ?? ''), positional[1], selected === undefined ? options : { ...options, output: selected }); } finally { Object.assign(console, saved); }
|
|
70
|
+
process.stdout.write(json ? `${JSON.stringify(result, null, 2)}\n` : `${checkLines(result).join('\n')}\n`);
|
|
71
|
+
if (result.verdict === 'fail') process.exitCode = 1;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (command === 'update') {
|
|
75
|
+
// SA28 (J314 Q7, Q27): one verb. SA18: `--pins[=<version>]` also moves the pins, installs, applies the release's
|
|
76
|
+
// codemods and runs check (updatePins.ts); with no version it takes npm's latest.
|
|
77
|
+
const rest = args.slice(1), pins = rest.filter(value => value === '--pins' || value.startsWith('--pins='));
|
|
78
|
+
const positional = rest.filter(value => !pins.includes(value)), version = pins[0]?.startsWith('--pins=') === true ? pins[0].slice('--pins='.length) : 'latest';
|
|
79
|
+
if (pins.length > 1 || version === '' || positional.length > 1 || positional.some(value => value.startsWith('-'))) throw new Error('usage: wildshard update [dir] [--pins[=<version>]]');
|
|
80
|
+
if (pins.length === 1 && /^\d+\.\d+\.\d+/u.test(positional[0] ?? '') && !existsSync(resolve(positional[0] ?? ''))) throw new Error(`usage: wildshard update [dir] [--pins[=<version>]]: name a version as --pins=${positional[0] ?? ''}`);
|
|
81
|
+
if (pins.length === 1) { await updatePins(resolve(positional[0] ?? '.'), version); return; }
|
|
82
|
+
for (const line of updateShardRepo(resolve(positional[0] ?? '.'))) console.info(line);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] | watch <source> [port] (wildshard --help lists them all)');
|
|
86
|
+
// SA16 (J314): a hand-written src/ (--template blender) has no shard.config.ts to build, synth or serve; check settles it.
|
|
87
|
+
if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (the retired --template blender): run wildshard check on the repo, which settles and builds it`);
|
|
88
|
+
if (command === 'synth') {
|
|
89
|
+
if (output !== undefined) throw new Error('usage: wildshard synth <source>');
|
|
90
|
+
const result = await synthProject(resolve(input));
|
|
91
|
+
console.info(`synthesized ${result.path} (${result.hash})`); return;
|
|
92
|
+
}
|
|
93
|
+
if (command === 'new') {
|
|
94
|
+
// SA16: `--template <name>` (or `--template=<name>`) picks the template; a flag only, never a prompt; default sdk.
|
|
95
|
+
const newArguments = args.slice(2), names: string[] = [], templates: string[] = [];
|
|
96
|
+
let empty = 0, unknown = false;
|
|
97
|
+
for (let index = 0; index < newArguments.length; index += 1) {
|
|
98
|
+
const value = newArguments[index] ?? '';
|
|
99
|
+
if (value === '--empty') empty += 1;
|
|
100
|
+
else if (value === '--template') { const name = newArguments[index + 1]; if (name === undefined || name.startsWith('--')) unknown = true; else templates.push(name); index += 1; }
|
|
101
|
+
else if (value.startsWith('--template=')) templates.push(value.slice('--template='.length));
|
|
102
|
+
else if (value.startsWith('--')) unknown = true;
|
|
103
|
+
else names.push(value);
|
|
104
|
+
}
|
|
105
|
+
if (input.startsWith('--') || names.length > 1 || unknown || empty > 1 || templates.length > 1) throw new Error('usage: wildshard new <dir> [slug] [--template sdk|scene] [--empty]');
|
|
106
|
+
// An unknown template refuses here, before anything is written.
|
|
107
|
+
const template = templateNamed(templates[0] ?? 'sdk');
|
|
108
|
+
const slug = names[0] ?? input.split('/').reverse().find((part) => part !== '') ?? '';
|
|
109
|
+
writeShardRepo(resolve(input), slug, { template, empty: empty === 1 });
|
|
110
|
+
// NEW-SHARD-E2E F8: say what was made and what to run next, never exit silently
|
|
111
|
+
const shown = relative(process.cwd(), resolve(input)) || '.';
|
|
112
|
+
console.info(`wildshard new: made ${shown}/, shard ${slug} (${template === 'scene' ? 'a three.js scene shard' : empty === 1 ? 'a bare shard source' : 'the reference world'}) at ${shown}/src/`);
|
|
113
|
+
console.info(`next: cd ${shown} && pnpm install && pnpm exec wildshard check .${template === 'scene' ? ', then pnpm exec wildshard watch . to see each save' : ''} (GUIDE.md is the guide)`);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (command === 'watch') {
|
|
117
|
+
// SHARD-SOURCE AP6: a scene shard's edits swap into the running page, no reload (`dev` is unchanged)
|
|
118
|
+
const port = output === undefined ? 0 : Number(output);
|
|
119
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('watch port must be 0..65535');
|
|
120
|
+
const server = await watchProject(resolve(input), { port, client: await devClient() });
|
|
121
|
+
const onSignal = (): void => {
|
|
122
|
+
// oxlint-disable-next-line unicorn/no-process-exit -- the signal handler replaced Node's default exit; ending is its job.
|
|
123
|
+
void server.close().finally(() => { process.exit(0); });
|
|
124
|
+
};
|
|
125
|
+
process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
|
|
126
|
+
console.info(`wildshard watch: ${server.url}?skipintro`); return;
|
|
127
|
+
}
|
|
128
|
+
if (command === 'dev') {
|
|
129
|
+
const port = output === undefined ? 0 : Number(output);
|
|
130
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('dev port must be 0..65535');
|
|
131
|
+
const server = await devProject(resolve(input), { port, client: await devClient(), ...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }) });
|
|
132
|
+
// SD-6: a signal handler replaces Node's default exit, so the handler ends the process itself: free the port and the
|
|
133
|
+
// build products, then exit 0 (exit drops the watchers and any rebuild still running). A second signal exits at once.
|
|
134
|
+
let stopping = false;
|
|
135
|
+
const stop = async (): Promise<void> => {
|
|
136
|
+
// oxlint-disable-next-line unicorn/no-process-exit -- a second Ctrl-C ends `dev` without waiting for the first.
|
|
137
|
+
if (stopping) process.exit(0);
|
|
138
|
+
stopping = true;
|
|
139
|
+
try { await server.close({ exiting: true }); } catch (error) { console.error(`wildshard dev: ${error instanceof Error ? error.message : String(error)}`); }
|
|
140
|
+
// oxlint-disable-next-line unicorn/no-process-exit -- the signal handler replaced Node's default exit; ending is its job.
|
|
141
|
+
process.exit(0);
|
|
142
|
+
};
|
|
143
|
+
const onSignal = (): void => { void stop(); };
|
|
144
|
+
process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
|
|
145
|
+
// SA15: `?skipintro` walks straight into the shard; the bare page sits on the game's title over it
|
|
146
|
+
console.info(`wildshard dev: ${server.url}?skipintro`); return;
|
|
147
|
+
}
|
|
148
|
+
// SDK-SPLIT SP9d1: the build verb is build's (packages/build/src/sharddev/buildVerb.ts).
|
|
149
|
+
if (command === 'build') { await runBuild(input, args.slice(2), options); return; }
|
|
150
|
+
if (command === 'prove') {
|
|
151
|
+
if (input.endsWith('.json') && basename(input) !== 'shard.json') throw new Error('prove requires a format-2 shard.json or shard source');
|
|
152
|
+
if (output === undefined || buildFlag !== undefined) throw new Error('usage: wildshard prove <source|shard.json> <proof.json>');
|
|
153
|
+
const built = input.endsWith('.json') || !existsSync(resolve(input, 'shard.config.ts'));
|
|
154
|
+
// A v1 decision (the Template's) needs the output's sections, or the engine reads every Wasm as ABI 0 and refuses
|
|
155
|
+
// `Import signature outside ABI` (engine TC-NE5b).
|
|
156
|
+
const { shard, assets, sections } = built
|
|
157
|
+
? validateOutputProduct(resolve(input.endsWith('.json') ? dirname(input) : input))
|
|
158
|
+
: await readProjectAssets(resolve(input), undefined, options.manifest, options).then(read => ({ ...read, sections: outputPlatformPayloads(read.output.platform) }));
|
|
159
|
+
const plan = readProofTape(resolve(output));
|
|
160
|
+
console.info(JSON.stringify(await proveAuthorSimulation(shard, assets, plan, sections), null, 2)); return;
|
|
161
|
+
}
|
|
162
|
+
if (command === 'validate') {
|
|
163
|
+
if (input.endsWith('.json') && basename(input) !== 'shard.json') throw new Error('validate requires a format-2 shard.json or shard source');
|
|
164
|
+
const folder=resolve(input.endsWith('.json') ? dirname(input) : input);
|
|
165
|
+
if (input.endsWith('.json') || existsSync(resolve(folder, 'shard.json'))) {
|
|
166
|
+
// P1-F3 (a): format validation, @wildshard/format/productValidation alone (schema, inventory, hashes, budgets, admission rows).
|
|
167
|
+
const checked = validateOutputProduct(folder);
|
|
168
|
+
printSpawnWarnings(checked.shard);
|
|
169
|
+
// P1-F3 (b), the execution proof, is `wildshard check`'s (SP7c). G491 holds there: validation.json is static build
|
|
170
|
+
// evidence, never authority for current script CPU; check executes the admitted bytes again on this host.
|
|
171
|
+
printStaticReport(checked.shard, checked.shard.runtime === null ? 'refuse' : 'warn');
|
|
172
|
+
console.info(`validated ${checked.shard.identity.slug}: format 2 inventory, byte kinds and section schemas`);
|
|
173
|
+
console.info(SIMULATION_ELSEWHERE); return;
|
|
174
|
+
}
|
|
175
|
+
const { shard, assets, output: extensions } = await readProjectAssets(resolve(input), undefined, options.manifest, options);
|
|
176
|
+
const scripts = outputScriptAdmissionRows(extensions.platform), contracts = decisionModuleContracts(scripts, shard.files);
|
|
177
|
+
const project = resolve(input), policy = projectPerformancePolicy(project, shard);
|
|
178
|
+
validateProject(shard, assets, project, scripts);
|
|
179
|
+
let layers = 0, blended = 0, masked = 0;
|
|
180
|
+
const kinds = new Map(shard.files.map((file) => [file.hash, file.kind]));
|
|
181
|
+
for (const [hash, bytes] of assets) {
|
|
182
|
+
const kind = kinds.get(hash) ?? 'commons';
|
|
183
|
+
const estimate = assetOverdraw(kind, bytes, kind === 'wasm' ? contracts.get(hash) ?? { abi: 0 } : undefined); layers += estimate.layers; blended += estimate.blendedLayers; masked += estimate.maskedLayers;
|
|
184
|
+
}
|
|
185
|
+
console.info(`advisory asset raster layers: ${layers.toFixed(2)} total, ${blended.toFixed(2)} blended, ${masked.toFixed(2)} alpha-tested (primitive bounds; before culling/occlusion, not measured screen overdraw)`);
|
|
186
|
+
// The static half of the performance report (declared bounds, downloads, memory) stays; scripts are check's to measure.
|
|
187
|
+
printStaticReport(shard, policy);
|
|
188
|
+
console.info(`validated ${shard.identity.slug} v${shard.version}: format 2 source, assets and section schemas`);
|
|
189
|
+
console.info(SIMULATION_ELSEWHERE);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
throw new Error('unknown wildshard command');
|
|
193
|
+
}
|
|
194
|
+
/** The step a verb's refusal comes from (SA21): `dev` and `synth` build. */
|
|
195
|
+
const STEPS: Readonly<Record<string, RefusalStep>> = { new: 'new', update: 'update', validate: 'validate', prove: 'prove' };
|
|
196
|
+
/** The refusal with its rule, fix and GUIDE.md link on a second line; the first line stays the refusing code's words. */
|
|
197
|
+
function authorRefusal(command: string | undefined, error: unknown): unknown {
|
|
198
|
+
const located = locatedError(error);
|
|
199
|
+
const message = located instanceof Error ? located.message : String(located);
|
|
200
|
+
const step = error instanceof ShardfileRefusalError ? 'shardfile' : command !== undefined && Object.hasOwn(STEPS, command) ? STEPS[command] : undefined;
|
|
201
|
+
const hint = refusalHint(refusalNote(step ?? 'build', message, { code: refusalCode(error) }));
|
|
202
|
+
return new Error(`${message}\n ${hint}`, { cause: error });
|
|
203
|
+
}
|
|
204
|
+
/** Run the author CLI; returns only after validation/build completes. */
|
|
205
|
+
export async function runCli(args: readonly string[], options: CliOptions = {}): Promise<void> {
|
|
206
|
+
try { await runCommand(args, options); } catch (error) { throw authorRefusal(args[0], error); }
|
|
207
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Serve only built static products from the local author tool.
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Author changes rebuild a private disposable product.
|
|
4
|
+
import { createReadStream, existsSync, mkdtempSync, realpathSync, readdirSync, rmSync, statSync, watch, readFileSync, writeFileSync, type Dirent } from 'node:fs';
|
|
5
|
+
// oxlint-disable-next-line import/no-nodejs-modules -- Resolve static requests inside the product directory.
|
|
6
|
+
import { extname, join, resolve, sep } from 'node:path';
|
|
7
|
+
import { buildProject } from '@wildshard/build/project';
|
|
8
|
+
import { shardRepoRoot } from '@wildshard/upload/sharddev/shardSource';
|
|
9
|
+
import { Scope } from '@wildshard/engine/app/scope';
|
|
10
|
+
import { scratchDir } from '@wildshard/sdk/scripts/scratch-dir.mjs';
|
|
11
|
+
|
|
12
|
+
// NEW-SHARD-E2E F18: a new build opens the same page under a new `devrev`, not location.reload(): Chromium reports a reload
|
|
13
|
+
// (or a same-URL replace) as navigation type `reload`, which engine's lastEnd reads as the player's own reload and sends to the title.
|
|
14
|
+
const POLL = '<script>let wsRevision=WS_REVISION;setInterval(async()=>{try{const r=await fetch("/__wildshard_dev_revision",{cache:"no-store"});const s=await r.json();if(s.error){console.error(s.error);return}if(s.revision!==wsRevision){const u=new URL(location.href);u.searchParams.set("devrev",String(s.revision));location.replace(u.href)}}catch{}},500)</script>';
|
|
15
|
+
/** A dev page's service worker: it answers no request and removes itself (NEW-SHARD-E2E F19). */
|
|
16
|
+
export const DEV_SERVICE_WORKER = "self.addEventListener('install',()=>{self.skipWaiting()});self.addEventListener('activate',(e)=>{e.waitUntil(self.registration.unregister())});\n";
|
|
17
|
+
const MIME: Record<string, string> = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.wasm': 'application/wasm', '.svg': 'image/svg+xml', '.png': 'image/png', '.woff2': 'font/woff2', '.ktx2': 'image/ktx2' };
|
|
18
|
+
// .worktrees: a shard repo's plan worktrees (DEV-SPEED DS11) are other checkouts, never this project's source.
|
|
19
|
+
const ignored = new Set(['node_modules', '.git', 'dist', 'public', '.worktrees', 'tmp']);
|
|
20
|
+
|
|
21
|
+
/** DK23: each dev process owns output inside the project's lane folder. */
|
|
22
|
+
export function createDevScratch(source: string): string {
|
|
23
|
+
const session = process.env['CODEX_THREAD_ID'] ?? process.env['CLAUDE_SESSION_ID'] ?? process.env['CLAUDE_CODE_SESSION_ID'];
|
|
24
|
+
const named = process.env['WS_LANE_NAME'] ?? `dev-${(session ?? String(process.pid)).replaceAll(/[^\w-]/gu, '-').slice(0, 80)}`;
|
|
25
|
+
if (!/^[a-zA-Z0-9_-][a-zA-Z0-9._-]{0,99}$/u.test(named) || named.includes('..')) throw new Error('Invalid dev lane name');
|
|
26
|
+
const root = shardRepoRoot(source), env = { ...process.env, WS_LANE_NAME: named };
|
|
27
|
+
let parent: string;
|
|
28
|
+
try { parent = scratchDir(named, 'wildshard dev', { root, env }); }
|
|
29
|
+
catch (cause) {
|
|
30
|
+
if (!(cause instanceof Error) || !cause.message.includes('already belongs to session')) throw cause;
|
|
31
|
+
parent = scratchDir(`${named.slice(0, 80)}-${process.pid}`, 'wildshard dev', { root, env });
|
|
32
|
+
}
|
|
33
|
+
const record = { ...JSON.parse(readFileSync(join(parent, '.owner'), 'utf8')) as Record<string, unknown>, pid: process.pid };
|
|
34
|
+
const scratch = realpathSync(mkdtempSync(join(parent, ['dev', String(process.pid), ''].join('-'))));
|
|
35
|
+
writeFileSync(join(scratch, '.owner'), JSON.stringify(record), { flag: 'wx' });
|
|
36
|
+
writeFileSync(join(scratch, 'server.pid'), String(process.pid), { flag: 'wx' });
|
|
37
|
+
return scratch;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Synchronous author-source baseline: native recursive watch notifications can miss quick overwrites during startup.
|
|
41
|
+
* Nanosecond change time also detects same-length edits whose modification time was restored. Symlink directories
|
|
42
|
+
* are not traversed; output/dependency directories keep the existing watcher exclusions. */
|
|
43
|
+
export function projectSourceStamp(source: string): string {
|
|
44
|
+
const directories = [source], rows: string[] = [];
|
|
45
|
+
while (directories.length > 0) {
|
|
46
|
+
const directory = directories.pop(); if (directory === undefined) break;
|
|
47
|
+
let entries: Dirent[];
|
|
48
|
+
try { entries = readdirSync(directory, { withFileTypes: true }); }
|
|
49
|
+
catch (cause) { if (cause instanceof Error && 'code' in cause && cause.code === 'ENOENT') continue; throw cause; }
|
|
50
|
+
for (const entry of entries) {
|
|
51
|
+
if (ignored.has(entry.name)) continue;
|
|
52
|
+
const file = join(directory, entry.name);
|
|
53
|
+
if (entry.isDirectory()) { directories.push(file); continue; }
|
|
54
|
+
const metadata = statSync(file, { bigint: true, throwIfNoEntry: false });
|
|
55
|
+
if (metadata === undefined) continue;
|
|
56
|
+
if (metadata.isFile()) rows.push(`${file}\0${metadata.ino}:${metadata.size}:${metadata.mtimeNs}:${metadata.ctimeNs}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return rows.sort().join('\n');
|
|
60
|
+
}
|
|
61
|
+
/** A rebuilt static author client. Closing it releases its socket, private build products and watchers; `exiting` neither
|
|
62
|
+
* waits for a running rebuild nor closes the watchers, which the process's exit drops (SD-6: closing a recursive watch
|
|
63
|
+
* on macOS blocks the event loop for seconds). */
|
|
64
|
+
export interface DevProject { url: string; close: (options?: { exiting?: boolean }) => Promise<void> }
|
|
65
|
+
/** Only the author command chooses DEVSERVER; requests, cookies and URL switches cannot enable it. */
|
|
66
|
+
export async function devProject(project: string, options: { decisionLegacyLines?: number; port?: number; client?: string } = {}): Promise<DevProject> {
|
|
67
|
+
const source = resolve(project), scratch = createDevScratch(source);
|
|
68
|
+
let revision = 0, error: string | null = null, current = '', previous = '', stopped = false, shardRoot = '';
|
|
69
|
+
const scope = new Scope('sdk.dev');
|
|
70
|
+
let debounce: Scope | undefined, work = Promise.resolve();
|
|
71
|
+
const rebuild = async (): Promise<void> => {
|
|
72
|
+
if (stopped) return;
|
|
73
|
+
const target = join(scratch, `build-${revision + 1}`);
|
|
74
|
+
try {
|
|
75
|
+
const built = await buildProject(source, target, { devserver: true, ...(options.decisionLegacyLines === undefined ? {} : { decisionLegacyLines: options.decisionLegacyLines }), ...(options.client === undefined ? {} : { client: options.client }) });
|
|
76
|
+
const page = join(target, 'index.html');
|
|
77
|
+
if (!existsSync(page)) throw new Error('wildshard dev requires the SDK devserver client; build/pack the SDK first');
|
|
78
|
+
const flags: unknown = JSON.parse(readFileSync(join(target, 'build-flags.json'), 'utf8'));
|
|
79
|
+
if (typeof flags !== 'object' || flags === null || !('devserver' in flags) || flags.devserver !== true) throw new Error('wildshard dev requires a client compiled in devserver mode');
|
|
80
|
+
writeFileSync(page, readFileSync(page, 'utf8').replace('</body>', `${POLL.replace('WS_REVISION', String(revision + 1))}</body>`));
|
|
81
|
+
if (previous !== '') rmSync(previous, { recursive: true, force: true });
|
|
82
|
+
previous = current; current = target; shardRoot = `/shardfiles/${built.identity.slug}/`; revision++; error = null;
|
|
83
|
+
} catch (cause) {
|
|
84
|
+
rmSync(target, { recursive: true, force: true }); error = cause instanceof Error ? cause.message : String(cause);
|
|
85
|
+
if (current === '') throw cause;
|
|
86
|
+
console.error(`wildshard dev: rebuild failed; serving previous product: ${error}`);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
try { await rebuild(); } catch (cause) { rmSync(scratch, { recursive: true, force: true }); throw cause; }
|
|
90
|
+
const server = createServer((request, response) => {
|
|
91
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
92
|
+
try {
|
|
93
|
+
const path = decodeURIComponent(new URL(request.url ?? '/', 'http://localhost').pathname);
|
|
94
|
+
if (path === '/__wildshard_dev_revision') {
|
|
95
|
+
response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify({ revision, error })); return;
|
|
96
|
+
}
|
|
97
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') { response.writeHead(405); response.end(); return; }
|
|
98
|
+
// NEW-SHARD-E2E F19: no service worker on a dev page. Once one controls the tab, the next load of the page (a rebuild's
|
|
99
|
+
// reload, or the URL typed again) is answered from its cache with the app's own shell, not this build's page with its
|
|
100
|
+
// inline shard, and that shell's level download asks for a packs book a dev build never writes (404). The page's
|
|
101
|
+
// `sw.js` is one that takes nothing and unregisters itself (and a worker an older `dev` left on this port).
|
|
102
|
+
if (path === '/sw.js') { response.setHeader('Content-Type', 'text/javascript'); response.end(DEV_SERVICE_WORKER); return; }
|
|
103
|
+
// SD-2: the page's in-page server reads the shard where a release serves it, `/shardfiles/<slug>/`; here that is
|
|
104
|
+
// the product's own root.
|
|
105
|
+
const served = shardRoot !== '' && path.startsWith(shardRoot) ? path.slice(shardRoot.length - 1) : path;
|
|
106
|
+
const local = served === '/' ? 'index.html' : served.slice(1);
|
|
107
|
+
const file = [current, previous].filter((dir) => dir !== '').map((dir) => ({ dir, file: resolve(dir, local) }))
|
|
108
|
+
.find(({ dir, file: candidate }) => candidate.startsWith(`${dir}${sep}`) && existsSync(candidate) && statSync(candidate).isFile() && realpathSync(candidate).startsWith(`${dir}${sep}`));
|
|
109
|
+
if (file === undefined) { response.writeHead(404); response.end(); return; }
|
|
110
|
+
response.setHeader('Content-Type', MIME[extname(file.file)] ?? 'application/octet-stream');
|
|
111
|
+
if (request.method === 'HEAD') response.end(); else createReadStream(file.file).on('error', () => { response.destroy(); }).pipe(response);
|
|
112
|
+
} catch { response.writeHead(400); response.end(); }
|
|
113
|
+
});
|
|
114
|
+
try {
|
|
115
|
+
await new Promise<void>((_resolve, reject) => { server.once('error', reject); server.listen(options.port ?? 0, '127.0.0.1', _resolve); });
|
|
116
|
+
} catch (cause) { rmSync(scratch, { recursive: true, force: true }); throw cause; }
|
|
117
|
+
let observed = projectSourceStamp(source);
|
|
118
|
+
const reconcile = (): void => {
|
|
119
|
+
if (stopped) return;
|
|
120
|
+
const next = projectSourceStamp(source);
|
|
121
|
+
if (next === observed) return;
|
|
122
|
+
observed = next;
|
|
123
|
+
debounce?.dispose(); debounce = scope.child('rebuild.debounce');
|
|
124
|
+
debounce.timeout(100, () => { debounce?.dispose(); work = work.then(rebuild); });
|
|
125
|
+
};
|
|
126
|
+
// One recursive watch per top-level folder that isn't ignored, and a flat one on the root: a recursive watch on the
|
|
127
|
+
// root would still walk and watch every ignored folder on Linux (a shard repo's .worktrees/ holds whole checkouts).
|
|
128
|
+
// A folder made later is seen by the 250 ms poll below.
|
|
129
|
+
const onChange = (prefix: string) => (_event: string, filename: string | null): void => {
|
|
130
|
+
if (`${prefix}${filename ?? ''}`.split(/[\\/]/u).some((part) => ignored.has(part))) return;
|
|
131
|
+
reconcile();
|
|
132
|
+
};
|
|
133
|
+
const watchers = [watch(source, onChange('')), ...readdirSync(source, { withFileTypes: true })
|
|
134
|
+
.filter((entry) => entry.isDirectory() && !ignored.has(entry.name))
|
|
135
|
+
.map((entry) => watch(join(source, entry.name), { recursive: true }, onChange(`${entry.name}/`)))];
|
|
136
|
+
// Capture before returning the ready server; polling covers native-event gaps without rebuilding unchanged input.
|
|
137
|
+
scope.interval(250, reconcile);
|
|
138
|
+
const address = server.address(); if (address === null || typeof address === 'string') throw new Error('No author server address');
|
|
139
|
+
return { url: `http://127.0.0.1:${address.port}/`, close: async (closing = {}) => {
|
|
140
|
+
if (stopped) return;
|
|
141
|
+
// The port goes first: closing the watchers can block for seconds (SD-6), and `wildshard dev` frees it within 2 s.
|
|
142
|
+
stopped = true; scope.dispose();
|
|
143
|
+
try {
|
|
144
|
+
await new Promise<void>((_resolve) => { server.close(() => { _resolve(); }); server.closeAllConnections(); });
|
|
145
|
+
// A build already running owns its directory until its promise finishes; on the way out it is dropped with it.
|
|
146
|
+
if (closing.exiting !== true) await work;
|
|
147
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
148
|
+
} finally { if (closing.exiting !== true) for (const watcher of watchers) watcher.close(); }
|
|
149
|
+
} };
|
|
150
|
+
}
|