@wildshard/dev 0.0.0-stage → 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.
Files changed (139) hide show
  1. package/bin/wildshard.mjs +75 -0
  2. package/lint/host-callbacks.d.mts +6 -0
  3. package/lint/host-callbacks.mjs +123 -0
  4. package/lint/ratchet.json +3 -0
  5. package/package.json +101 -3
  6. package/scripts/audit-assets.d.mts +10 -0
  7. package/scripts/audit-assets.mjs +151 -0
  8. package/scripts/bake/coatFiles.d.mts +6 -0
  9. package/scripts/bake/coatFiles.mjs +37 -0
  10. package/scripts/bake/navmeshGround.ts +22 -0
  11. package/scripts/bake/near-placeholder.mjs +331 -0
  12. package/scripts/bake/viewmodelBytes.ts +26 -0
  13. package/scripts/bake/viewmodelPage.ts +11 -0
  14. package/scripts/bake-catalogue.mjs +44 -0
  15. package/scripts/bake-check.mjs +54 -0
  16. package/scripts/bake-chunk.mjs +124 -0
  17. package/scripts/bake-cloud-field.mjs +24 -0
  18. package/scripts/bake-coats.mjs +110 -0
  19. package/scripts/bake-data-maps.d.mts +24 -0
  20. package/scripts/bake-data-maps.mjs +78 -0
  21. package/scripts/bake-entry-programs.mjs +126 -0
  22. package/scripts/bake-geometry.mjs +106 -0
  23. package/scripts/bake-ktx2.mjs +477 -0
  24. package/scripts/bake-map-glb.mjs +127 -0
  25. package/scripts/bake-map-rest.d.mts +7 -0
  26. package/scripts/bake-map-rest.mjs +50 -0
  27. package/scripts/bake-maps.mjs +200 -0
  28. package/scripts/bake-navmesh.mjs +259 -0
  29. package/scripts/bake-packs.mjs +129 -0
  30. package/scripts/bake-pickups.mjs +102 -0
  31. package/scripts/bake-query-terrain.mjs +64 -0
  32. package/scripts/bake-textures.mjs +80 -0
  33. package/scripts/bake-viewmodel-sets.mjs +137 -0
  34. package/scripts/bake-voxel-ao.mjs +119 -0
  35. package/scripts/bake-water-ripples.mjs +25 -0
  36. package/scripts/browser-imports.d.mts +2 -0
  37. package/scripts/browser-imports.mjs +40 -0
  38. package/scripts/browser-machine-loader-proof.mjs +39 -0
  39. package/scripts/browser-machine-loader.d.mts +8 -0
  40. package/scripts/browser-machine-loader.mjs +87 -0
  41. package/scripts/browser-playwright.d.mts +10 -0
  42. package/scripts/browser-playwright.mjs +5 -0
  43. package/scripts/browser-test.d.mts +4 -0
  44. package/scripts/browser-test.mjs +18 -0
  45. package/scripts/build-sdk.mjs +95 -0
  46. package/scripts/build-shardfiles.d.mts +7 -0
  47. package/scripts/build-shardfiles.mjs +230 -0
  48. package/scripts/capture-hero.mjs +211 -0
  49. package/scripts/chromium-keychain.d.mts +1 -0
  50. package/scripts/chromium-keychain.mjs +7 -0
  51. package/scripts/entry-reads/crawl.ts +152 -0
  52. package/scripts/gen-host-catalogue.d.mts +14 -0
  53. package/scripts/gen-host-catalogue.mjs +108 -0
  54. package/scripts/gen-shards.d.mts +17 -0
  55. package/scripts/gen-shards.mjs +311 -0
  56. package/scripts/goldens/plot-inputs.d.mts +12 -0
  57. package/scripts/goldens/plot-inputs.mjs +46 -0
  58. package/scripts/gpu-texmem.mjs +98 -0
  59. package/scripts/ktx2-ab.mjs +111 -0
  60. package/scripts/map-bake-frames.d.mts +4 -0
  61. package/scripts/map-bake-frames.mjs +23 -0
  62. package/scripts/map-world.mjs +162 -0
  63. package/scripts/memory-product.mjs +62 -0
  64. package/scripts/music/export-midi.mjs +69 -0
  65. package/scripts/named-blob-output.d.mts +8 -0
  66. package/scripts/named-blob-output.mjs +48 -0
  67. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  68. package/scripts/preparation-browser.mjs +25 -0
  69. package/scripts/preparation-seed.mjs +15 -0
  70. package/scripts/prepare-product.d.mts +14 -0
  71. package/scripts/prepare-product.mjs +133 -0
  72. package/scripts/prove-walk.mjs +83 -0
  73. package/scripts/push-tables.d.mts +1 -0
  74. package/scripts/push-tables.mjs +28 -0
  75. package/scripts/record-shard-mounts.mjs +133 -0
  76. package/scripts/section-inventory.ts +209 -0
  77. package/scripts/shard-build-pool.d.mts +4 -0
  78. package/scripts/shard-build-pool.mjs +53 -0
  79. package/scripts/shard-milestones.d.mts +15 -0
  80. package/scripts/shard-milestones.mjs +105 -0
  81. package/scripts/shard-progress.mjs +212 -0
  82. package/scripts/shardfile-cold-boot.mjs +79 -0
  83. package/scripts/shardfile-rolldown.d.mts +2 -0
  84. package/scripts/shardfile-rolldown.mjs +32 -0
  85. package/scripts/shardfile-vite.d.mts +4 -0
  86. package/scripts/shardfile-vite.mjs +20 -0
  87. package/scripts/site-facts.mjs +88 -0
  88. package/scripts/test-template-gate.mjs +44 -0
  89. package/scripts/tex-tiers.mjs +240 -0
  90. package/scripts/unused-assets.mjs +173 -0
  91. package/scripts/wildshard.d.mts +4 -0
  92. package/scripts/wildshard.mjs +146 -0
  93. package/scripts/witness-generation.d.mts +10 -0
  94. package/scripts/witness-generation.mjs +45 -0
  95. package/src/.oxlintrc.json +12 -0
  96. package/src/cli/bin.mjs +8 -0
  97. package/src/cli/content-command.ts +44 -0
  98. package/src/cli/content.ts +287 -0
  99. package/src/cli/grid/command.ts +48 -0
  100. package/src/cli/grid/grid.ts +155 -0
  101. package/src/cli/help.ts +262 -0
  102. package/src/cli/hero/adopt.ts +109 -0
  103. package/src/cli/install-home.ts +40 -0
  104. package/src/cli/main.ts +142 -0
  105. package/src/cli/version.ts +63 -0
  106. package/src/server/app.ts +19 -0
  107. package/src/server/serve.ts +49 -0
  108. package/src/sharddev/bake/json.mjs +84 -0
  109. package/src/sharddev/bake/mapRest.ts +57 -0
  110. package/src/sharddev/bake/nativeRaster.ts +106 -0
  111. package/src/sharddev/bake/source-loader.mjs +55 -0
  112. package/src/sharddev/bake/splatLayers.ts +29 -0
  113. package/src/sharddev/bootInventory.ts +132 -0
  114. package/src/sharddev/check.ts +125 -0
  115. package/src/sharddev/checkProject.ts +134 -0
  116. package/src/sharddev/cli.ts +207 -0
  117. package/src/sharddev/dev.ts +150 -0
  118. package/src/sharddev/devClient.ts +120 -0
  119. package/src/sharddev/devRoot.ts +6 -0
  120. package/src/sharddev/engineMusic.ts +23 -0
  121. package/src/sharddev/projectEntryProof.ts +32 -0
  122. package/src/sharddev/test/diskScriptScenario.ts +88 -0
  123. package/src/sharddev/test/scriptScenario.ts +254 -0
  124. package/src/sharddev/tsconfig.json +3 -0
  125. package/src/sharddev/watch/page.ts +288 -0
  126. package/src/sharddev/watch/pageEntry.ts +44 -0
  127. package/src/sharddev/watch/parity-baseline.json +22 -0
  128. package/src/sharddev/watch/parity.mjs +194 -0
  129. package/src/sharddev/watch/proof.mjs +199 -0
  130. package/src/sharddev/watch/socket.ts +57 -0
  131. package/src/sharddev/watch/watch.ts +382 -0
  132. package/src/shared/health.ts +10 -0
  133. package/src/tools/build-web.ts +59 -0
  134. package/src/web/app.tsx +53 -0
  135. package/src/web/index.html +12 -0
  136. package/src/web/main.tsx +10 -0
  137. package/tsconfig.author.json +25 -0
  138. package/tsconfig.json +47 -0
  139. package/README.md +0 -3
@@ -0,0 +1,49 @@
1
+ import { once } from 'node:events'
2
+ import { fileURLToPath } from 'node:url'
3
+
4
+ import { serve as serveNode } from '@hono/node-server'
5
+ import { serveStatic } from '@hono/node-server/serve-static'
6
+
7
+ import { createApp } from './app.ts'
8
+
9
+ // The built web app, if this repo has one: src/dist/web (src/tools/build-web.ts).
10
+ const WEB_ROOT = fileURLToPath(new URL('../dist/web', import.meta.url))
11
+
12
+ const LOOPBACK_HOST = '127.0.0.1'
13
+
14
+ interface ServeOptions {
15
+ readonly port: number
16
+ readonly version: string
17
+ }
18
+
19
+ interface RunningServer {
20
+ readonly url: string
21
+ readonly close: () => Promise<void>
22
+ }
23
+
24
+ export async function serve(options: ServeOptions): Promise<RunningServer> {
25
+ const app = createApp({ version: options.version })
26
+ app.use('/*', serveStatic({ root: WEB_ROOT }))
27
+ app.get('/*', serveStatic({ root: WEB_ROOT, path: 'index.html' }))
28
+
29
+ const server = serveNode({
30
+ fetch: app.fetch,
31
+ hostname: LOOPBACK_HOST,
32
+ port: options.port,
33
+ })
34
+ await once(server, 'listening')
35
+
36
+ const address = server.address()
37
+ if (address === null || typeof address === 'string') {
38
+ throw new Error('sharddev: server is not listening on a TCP port')
39
+ }
40
+
41
+ return {
42
+ url: `http://${LOOPBACK_HOST}:${String(address.port)}`,
43
+ close: async (): Promise<void> => {
44
+ const closed = once(server, 'close')
45
+ server.close()
46
+ await closed
47
+ },
48
+ }
49
+ }
@@ -0,0 +1,84 @@
1
+ // Emit one retained authoring function's JSON or explicit byte product. I/O belongs to this Node driver.
2
+ // node --import ./src/sharddev/bake/source-loader.mjs src/sharddev/bake/json.mjs <entry> <exported-function> <output>
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Only the build driver writes the generated JSON output.
4
+ import { lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Source and output paths must stay in the isolated tree.
6
+ import { dirname, isAbsolute, resolve, sep } from 'node:path';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Import the explicitly named retained authoring recipe.
8
+ import { pathToFileURL } from 'node:url';
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- This executable reads its explicit producer arguments.
10
+ import process from 'node:process';
11
+ import { assertJsonRows, jsonOutputGuard } from '@wildshard/engine/scripts/json-output-guard.mjs';
12
+
13
+ const args = process.argv.slice(2);
14
+ const entry = args.at(0), binding = args.at(1), output = args.at(2);
15
+ const binary = args.length === 4 && args.at(3) === '--bytes';
16
+ const multiple = args.length === 4 && args.at(3) === '--files';
17
+ if ((!binary && !multiple && args.length !== 3) || entry === undefined || binding === undefined || output === undefined) throw new Error('generate-json: entry, function and output required');
18
+ const root = process.cwd(), guard = jsonOutputGuard(root), sourceOwner = entry.split('/').at(2);
19
+ /** Restrict source and destination to explicit regular paths in the isolated generation tree. @param {string} path */
20
+ function confined(path) {
21
+ if (isAbsolute(path) || path.includes('\\') || path.split('/').some(part => part === '' || part === '.' || part === '..')) throw new Error('generate-json: path must stay inside the generation tree');
22
+ const parts = path.split('/');
23
+ for (let length = 1; length <= parts.length; length++) {
24
+ const prefix = resolve(root, ...parts.slice(0, length));
25
+ try {
26
+ // Canonical existing prefixes need only exact path probes, not ancestor
27
+ // metadata reads that look like recursive content scans to the recorder.
28
+ if (realpathSync.native(prefix) !== prefix) throw new Error('generate-json: symlink refused');
29
+ } catch (error) {
30
+ // A dangling or looping link cannot canonicalize. Retain the original
31
+ // lstat refusal before accepting any missing output path.
32
+ try { if (lstatSync(prefix).isSymbolicLink()) throw new Error('generate-json: symlink refused', { cause: error }); }
33
+ catch (statError) { if (!(statError instanceof Error && 'code' in statError && statError.code === 'ENOENT')) throw statError; }
34
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error;
35
+ }
36
+ }
37
+ const target = resolve(root, path);
38
+ if (!target.startsWith(root + sep)) throw new Error('generate-json: escaping path refused');
39
+ return target;
40
+ }
41
+ const source = confined(entry), destination = confined(output);
42
+ /** @type {unknown} */
43
+ const author = await import(pathToFileURL(source).href);
44
+ if (author === null || typeof author !== 'object' || !(binding in author)) throw new Error('generate-json: named authoring function required');
45
+ const generate = Reflect.get(author, binding);
46
+ if (typeof generate !== 'function') throw new Error('generate-json: named authoring function required');
47
+ /** Byte recipes receive only a confined, read-only asset reader. @param {string} url */
48
+ function readAsset(url) {
49
+ if (typeof url !== 'string' || !url.startsWith('/assets/')) throw new Error('generate-json: asset URL required');
50
+ return new Uint8Array(readFileSync(confined(`public${url}`)));
51
+ }
52
+ /** An author-only file recipe reads only its own explicit authored files, never trusted runtime or another shard.
53
+ * @param {string} path */
54
+ function readSource(path) {
55
+ const owner = sourceOwner, parts = typeof path === 'string' ? path.split('/') : [];
56
+ if (owner === undefined || parts.at(0) !== 'src' || parts.at(1) !== 'shards' || parts.at(2) !== owner || !['generators', 'data', 'assets', 'quests', 'behaviour', 'blender'].includes(parts.at(3) ?? '')) throw new Error('generate-json: own authored input required');
57
+ return new Uint8Array(readFileSync(confined(path)));
58
+ }
59
+ /** @type {unknown} */
60
+ const value = binary ? await generate(readAsset) : multiple ? await generate(readSource) : await generate();
61
+ if (multiple) {
62
+ const owner = entry.split('/').at(2), project = `src/shards/${owner}`;
63
+ if (owner === undefined || !entry.startsWith(`${project}/generators/`) || output !== project || !(value instanceof Map) || value.size === 0 || value.size > 512) throw new Error('generate-json: bounded own-project file map required');
64
+ /** @type {[string, Uint8Array][]} */
65
+ const files = [];
66
+ // Admit every path and byte value before writing any output.
67
+ for (const item of value.entries()) {
68
+ /** @type {unknown} */
69
+ const name = item[0], bytes = item[1];
70
+ if (typeof name !== 'string' || !(bytes instanceof Uint8Array) || bytes.length > 25_000_000) throw new Error('generate-json: relative byte outputs required');
71
+ const path = confined(`${output}/${name}`); guard(path, bytes); files.push([path, bytes]);
72
+ }
73
+ for (const [path, bytes] of files) { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, bytes); }
74
+ } else if (binary) {
75
+ if (!(value instanceof Uint8Array)) throw new Error('generate-json: byte recipe must return Uint8Array');
76
+ guard(destination, value);
77
+ mkdirSync(dirname(destination), { recursive: true }); writeFileSync(destination, value);
78
+ } else {
79
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') throw new Error('generate-json: authoring function returned no JSON data');
80
+ assertJsonRows(value, output);
81
+ const bytes = JSON.stringify(value); guard(destination, bytes);
82
+ mkdirSync(dirname(destination), { recursive: true });
83
+ writeFileSync(destination, `${bytes}\n`);
84
+ }
@@ -0,0 +1,57 @@
1
+ import { BufferGeometry, Group, InstancedMesh, MeshBasicMaterial } from 'three';
2
+ import { createClientChannelView } from '@wildshard/engine/game/plugin/clientChannelView';
3
+ import { moverChannelValues, type MoverPose } from '@wildshard/format/moverPose';
4
+ import { parseClientChannels } from '@wildshard/format/clientChannels';
5
+
6
+ /** Only the initial private transforms and instance slots used by the map projection. */
7
+ export interface MapRestNode {
8
+ readonly id: string;
9
+ readonly position?: readonly [number, number, number];
10
+ readonly rotation?: readonly [number, number, number];
11
+ readonly quaternion?: readonly [number, number, number, number];
12
+ readonly scale?: readonly [number, number, number];
13
+ readonly order?: 'XYZ' | 'YXZ' | 'ZXY' | 'ZYX' | 'YZX' | 'XZY';
14
+ readonly visible?: boolean;
15
+ readonly instances?: number;
16
+ readonly matrices?: readonly number[];
17
+ }
18
+ /** Initial presentation rows; all numbers retain the native CPU channel projection. */
19
+ export interface MapRestRows {
20
+ readonly version: 1;
21
+ readonly nodes: Readonly<Record<string, { position: number[]; quaternion: number[]; scale: number[]; visible: boolean; matrices?: number[] }>>;
22
+ }
23
+
24
+ /** Project declared mover rest poses without a renderer, physics installation or filesystem authority.
25
+ * Every instance slot must be initialized; missing movers and incomplete coverage refuse. */
26
+ export function mapSceneRest(scene: { readonly nodes: readonly MapRestNode[] }, input: unknown, poses: readonly (MoverPose & { readonly id: string })[]): MapRestRows {
27
+ const programs = parseClientChannels(input), targets = new Map<string, Group | InstancedMesh>(), coverage = new Map<string, Uint8Array>();
28
+ const nodes: Record<string, MapRestRows['nodes'][string]> = {}, movers = new Map(poses.map(pose => [pose.id, pose]));
29
+ const geometry = new BufferGeometry(), material = new MeshBasicMaterial();
30
+ try {
31
+ for (const row of scene.nodes) {
32
+ const target = row.instances === undefined ? new Group() : new InstancedMesh(geometry, material, row.instances);
33
+ if (row.position !== undefined) target.position.fromArray(row.position);
34
+ if (row.rotation !== undefined) target.rotation.set(...row.rotation, row.order ?? 'XYZ');
35
+ if (row.quaternion !== undefined) target.quaternion.fromArray(row.quaternion);
36
+ if (row.scale !== undefined) target.scale.fromArray(row.scale);
37
+ if (row.visible !== undefined) target.visible = row.visible;
38
+ if (row.matrices !== undefined && target instanceof InstancedMesh) target.instanceMatrix.array.set(row.matrices);
39
+ if (row.instances !== undefined) coverage.set(row.id, new Uint8Array(row.instances).fill(row.matrices === undefined ? 0 : 1));
40
+ targets.set(row.id, target);
41
+ }
42
+ for (const program of programs) {
43
+ if (program.mover === undefined) throw new Error(`Map rest needs a declared mover: ${program.id}`);
44
+ const pose = movers.get(program.mover); if (pose === undefined) throw new Error(`Missing map rest pose ${program.mover}`);
45
+ const view = createClientChannelView(program, targets);
46
+ view.evaluate({ time: 0, delta: 0, values: moverChannelValues(view.reads, pose, {}) });
47
+ for (const connector of program.connectors ?? []) {
48
+ const slots = coverage.get(connector.target), span = connector.instances;
49
+ if (slots !== undefined && span !== undefined) slots.fill(1, span.start, span.start + span.capacity);
50
+ }
51
+ }
52
+ for (const [id, slots] of coverage) if (slots.some(value => value === 0)) throw new Error(`Incomplete map rest instance slots ${id}`);
53
+ for (const [id, target] of targets) nodes[id] = { position: target.position.toArray(), quaternion: target.quaternion.toArray(), scale: target.scale.toArray(), visible: target.visible,
54
+ ...(target instanceof InstancedMesh ? { matrices: Array.from(target.instanceMatrix.array) } : {}) };
55
+ return { version: 1, nodes };
56
+ } finally { geometry.dispose(); material.dispose(); }
57
+ }
@@ -0,0 +1,106 @@
1
+ import { KEYCHAIN_ARGS } from '../../../scripts/chromium-keychain.mjs';
2
+ import { build } from 'vite';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- The explicit author bundler converts file URLs on its native host.
4
+ import { fileURLToPath } from 'node:url';
5
+ import { devices, webkit, chromium, type BrowserContextOptions, type Page } from "../../../scripts/browser-playwright.mjs";
6
+
7
+ /** Setup operations required from a native reference page. */
8
+ export interface NativeRasterPage {
9
+ readonly setContent: (html: string) => Promise<unknown>;
10
+ readonly addScriptTag: (input: { content: string; type?: string }) => Promise<unknown>;
11
+ }
12
+ /** Explicit author browser factory; alternate hosts preserve the same setup and cleanup contract. */
13
+ export interface NativeRasterHost<P extends NativeRasterPage> {
14
+ readonly launch: (options: { headless: true; args?: string[] }) => Promise<{
15
+ readonly newContext: (options: BrowserContextOptions | undefined) => Promise<{ readonly newPage: () => Promise<P> }>;
16
+ readonly close: () => Promise<void>;
17
+ }>;
18
+ }
19
+ /** A native author reference page; the caller holds browser-lane and owns its finite lifetime. */
20
+ export interface NativeRasterSession<P extends NativeRasterPage = Page> {
21
+ readonly page: P;
22
+ readonly dispose: () => Promise<void>;
23
+ }
24
+ /** A bundled painter and its original document. Module tags are opt-in, as for native addScriptTag. */
25
+ export interface NativeRasterInput {
26
+ readonly html: string;
27
+ readonly source: string;
28
+ readonly module?: boolean;
29
+ }
30
+
31
+ const nativeHost: NativeRasterHost<Page> = { launch: options => webkit.launch(options) };
32
+ const chromiumHost: NativeRasterHost<Page> = { launch: options => chromium.launch({ ...options, args: [...KEYCHAIN_ARGS, ...(options.args ?? [])] }) };
33
+
34
+ /** An author page whose routes and document preparation remain caller-owned. */
35
+ export interface NativeRasterBrowserInput {
36
+ readonly engine: 'webkit' | 'chromium';
37
+ readonly args?: readonly string[];
38
+ }
39
+
40
+ /** Open the original phone author context before the caller installs routes or navigates.
41
+ * Caller holds browser-lane; browser flags are copied before launch and setup refusals close partial resources. */
42
+ export function openNativeRasterPage(input: NativeRasterBrowserInput): Promise<NativeRasterSession>;
43
+ /** Use an explicit author host with the same profile, flag ownership and cleanup. */
44
+ export function openNativeRasterPage<P extends NativeRasterPage>(input: NativeRasterBrowserInput, host: NativeRasterHost<P>): Promise<NativeRasterSession<P>>;
45
+ export function openNativeRasterPage<P extends NativeRasterPage>(input: NativeRasterBrowserInput, host?: NativeRasterHost<P>): Promise<NativeRasterSession<P> | NativeRasterSession> {
46
+ return host === undefined ? openRasterPage(input.engine === 'chromium' ? chromiumHost : nativeHost, input.args) : openRasterPage(host, input.args);
47
+ }
48
+
49
+ async function openRasterPage<P extends NativeRasterPage>(host: NativeRasterHost<P>, args?: readonly string[]): Promise<NativeRasterSession<P>> {
50
+ const options = { headless: true as const, ...(args === undefined ? {} : { args: [...args] }) };
51
+ const browser = await host.launch(options);
52
+ try {
53
+ const context = await browser.newContext(devices['iPhone 16 Pro']);
54
+ const page = await context.newPage();
55
+ return { page, dispose: () => browser.close() };
56
+ } catch (error) {
57
+ await browser.close();
58
+ throw error;
59
+ }
60
+ }
61
+
62
+ /** Open the existing phone WebKit reference raster without installing a page/game service.
63
+ * Snapshot input before yielding; release the browser if any preparation step refuses. */
64
+ export function openNativeRaster(input: NativeRasterInput): Promise<NativeRasterSession>;
65
+ /** Open an explicitly supplied author host with the same page lifetime. */
66
+ export function openNativeRaster<P extends NativeRasterPage>(input: NativeRasterInput, host: NativeRasterHost<P>): Promise<NativeRasterSession<P>>;
67
+ export function openNativeRaster<P extends NativeRasterPage>(input: NativeRasterInput, host?: NativeRasterHost<P>): Promise<NativeRasterSession<P> | NativeRasterSession> {
68
+ return host === undefined ? prepareNativeRaster(input, nativeHost) : prepareNativeRaster(input, host);
69
+ }
70
+
71
+ async function prepareNativeRaster<P extends NativeRasterPage>(input: NativeRasterInput, host: NativeRasterHost<P>): Promise<NativeRasterSession<P>> {
72
+ const { html, source, module } = input;
73
+ const session = await openRasterPage(host);
74
+ try {
75
+ const { page } = session;
76
+ await page.setContent(html);
77
+ await page.addScriptTag(module === true ? { type: 'module', content: source } : { content: source });
78
+ return session;
79
+ } catch (error) {
80
+ await session.dispose();
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ /** Explicit native-reference bundle settings; painters and publication remain caller-owned. */
86
+ export interface NativeRasterBundle {
87
+ readonly root: string | URL;
88
+ readonly entry: string | URL;
89
+ readonly format: 'es' | 'iife';
90
+ readonly name?: string;
91
+ readonly fileName?: string;
92
+ readonly discardModuleSideEffects?: boolean;
93
+ }
94
+
95
+ /** Bundle one native reference page with the original offline target and split policy.
96
+ * Missing code stays undefined so the author retains its defining refusal. No Vite plugin is installed. */
97
+ export async function bundleNativeRaster(input: NativeRasterBundle): Promise<string | undefined> {
98
+ const { format, name, fileName, discardModuleSideEffects } = input;
99
+ const root = typeof input.root === 'string' ? input.root : fileURLToPath(input.root);
100
+ const entry = typeof input.entry === 'string' ? input.entry : fileURLToPath(input.entry);
101
+ const result = await build({ configFile: false, logLevel: 'silent', publicDir: false, root,
102
+ build: { write: false, target: 'esnext', minify: false,
103
+ lib: { entry, formats: [format], ...(name === undefined ? {} : { name }), ...(fileName === undefined ? {} : { fileName }) },
104
+ rolldownOptions: { ...(discardModuleSideEffects === true ? { treeshake: { moduleSideEffects: false } } : {}), output: { codeSplitting: false } } } });
105
+ return (Array.isArray(result) ? result : [result]).flatMap(bundle => 'output' in bundle ? bundle.output : []).find(chunk => chunk.type === 'chunk')?.code;
106
+ }
@@ -0,0 +1,55 @@
1
+ // Node authoring resolution only: no app identity, service installers, simulation bindings or browser shims.
2
+ import '@wildshard/engine/scripts/format-hook.mjs';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- The authoring CLI installs only Node source resolution.
4
+ import { registerHooks } from 'node:module';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve regular files in the isolated authoring tree.
6
+ import { existsSync, statSync } from 'node:fs';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Confine recipe imports to their source tree.
8
+ import { relative, resolve, sep } from 'node:path';
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- Inspect resolved module URLs before loading source.
10
+ import { fileURLToPath } from 'node:url';
11
+ // oxlint-disable-next-line import/no-nodejs-modules -- The generator argument identifies its single shard owner.
12
+ import process from 'node:process';
13
+
14
+ const root = process.cwd(); // P4: the shard repo. A tool in an installed package passes the /node_modules/ rule below.
15
+ // Node normalises the script argument to an absolute path before preloads run.
16
+ const script = process.argv.at(1);
17
+ const driver = script === undefined ? '' : relative(root, resolve(script)).split(sep).join('/');
18
+ // Confined SDK drivers name their source explicitly; direct producers own their script path.
19
+ const source = /src\/sharddev\/bake\/(?:navigation-)?json\.mjs$/u.test(driver) ? process.argv.at(2) : script;
20
+ const candidate = source === undefined ? '' : relative(root, resolve(source)).split(sep).join('/');
21
+ const entry = /^src\/shards\/[^/]+\/generators\//u.test(candidate) ? candidate : undefined;
22
+ const shard = entry?.split('/')[2];
23
+ if (shard === undefined) throw new Error('Authoring loader requires an explicit shard-owned generator');
24
+ const folders = new Set(['generators', 'data', 'quests', 'blender', 'assets', 'behaviour']);
25
+
26
+ /** Refuse even computed imports into trusted code after Node resolves workspace links. @param {string} url */
27
+ function authoringOnly(url) {
28
+ if (!url.startsWith('file:')) return;
29
+ const file = relative(root, fileURLToPath(url)).split(sep).join('/');
30
+ if (file.startsWith('../') && !file.includes('/node_modules/')) throw new Error(`Authoring dependency escapes the source tree: ${file}`);
31
+ if (!file.startsWith('src/')) return; // Node and installed third-party dependencies are build infrastructure.
32
+ const parts = file.split('/'), layer = parts[1];
33
+ if (parts.includes('runtime') || parts.some(part => part.endsWith('-legacy')) ||
34
+ (layer === 'shards' ? parts[2] !== shard || !folders.has(parts[3]) : !['sdk', 'sharddev', 'commons', 'format'].includes(layer))) {
35
+ throw new Error(`Non-authoring dependency refused: ${file}`);
36
+ }
37
+ }
38
+
39
+ registerHooks({
40
+ resolve(specifier, context, next) {
41
+ if (specifier.startsWith('.') && context.parentURL?.startsWith('file:')) {
42
+ const base = new URL(specifier, context.parentURL);
43
+ for (const suffix of ['', '.ts', '.mjs', '.js']) {
44
+ const url = new URL(base.href + suffix);
45
+ if (existsSync(fileURLToPath(url)) && statSync(fileURLToPath(url)).isFile()) {
46
+ authoringOnly(url.href);
47
+ return { url: url.href, shortCircuit: true };
48
+ }
49
+ }
50
+ }
51
+ const result = next(specifier, context);
52
+ authoringOnly(result.url);
53
+ return result;
54
+ },
55
+ });
@@ -0,0 +1,29 @@
1
+ // SDK-SPLIT SP8a: split from `bake/splatGround` (the sdk's bake builder) because it reads the engine's texture table
2
+ // (`filePolicy`, boot data); it moves to the dev package with SP8b.
3
+ import { filePolicy } from '@wildshard/engine/boot/filePolicy';
4
+ import type { Ktx2Table } from '@wildshard/engine/boot/gpuFiles';
5
+
6
+ /** One tier's four splat layers by role, as public asset paths. */
7
+ export interface SplatLayerPaths { colour: string[]; normal: string[]; arm: string[] }
8
+ /**
9
+ * The KTX2 files four native ground layers (`groundLayers` ids, in splat channel order) draw from on each tier, exactly as the
10
+ * runtime's texture arrays resolve them (`filePolicy(tier, 'ktx2', table).layer`: the engine table under the shard's own,
11
+ * the phone's `.phone` variants, found in `inventory`: the public files, keyed by URL); throws when a layer has no `#layer` KTX2.
12
+ */
13
+ export function splatLayerFiles(ids: readonly string[], table: Ktx2Table, inventory: Readonly<Record<string, number | true>>): { desktop: SplatLayerPaths; phone: SplatLayerPaths } {
14
+ if (ids.length !== 4) throw new Error('A splat ground has four layers');
15
+ const tier = (name: 'phone' | 'desktop'): SplatLayerPaths => {
16
+ const policy = filePolicy(name, 'ktx2', table, inventory), roles: SplatLayerPaths = { colour: [], normal: [], arm: [] };
17
+ for (const id of ids) {
18
+ const [colour, normal, arm] = policy.pbr(id).map(url => {
19
+ const file = policy.layer(url);
20
+ if (!file.endsWith('.ktx2')) throw new Error(`Splat layer ${url} has no ${name} #layer KTX2`);
21
+ return file;
22
+ });
23
+ if (colour === undefined || normal === undefined || arm === undefined) throw new Error(`Splat layer ${id} lost a role`);
24
+ roles.colour.push(colour); roles.normal.push(normal); roles.arm.push(arm);
25
+ }
26
+ return roles;
27
+ };
28
+ return { desktop: tier('desktop'), phone: tier('phone') };
29
+ }
@@ -0,0 +1,132 @@
1
+ import { filePolicy } from '@wildshard/engine/boot/filePolicy';
2
+ // QA mini row 37: the URL constants come from node-safe modules. Engine `boot/bakedApi` also holds browser loaders whose
3
+ // dynamic imports split an author config into two chunks, which `wildshard build` refuses. A shard's own boot rows import the
4
+ // same two modules (`@wildshard/engine/boot/bakedUrls`, `@wildshard/engine/physics/wasmUrl`), never `boot/bakedApi`.
5
+ import { CLOUD_FIELD_URL } from '@wildshard/engine/boot/bakedUrls';
6
+ import { RAPIER_WASM_URL } from '@wildshard/engine/physics/wasmUrl';
7
+
8
+ /** Authoring inputs are explicit presence/byte tables, never a live download service. */
9
+ export type BootInventory = Readonly<Record<string, number | true>>;
10
+ /** One concrete output tier. */
11
+ export type BootTier = 'phone' | 'desktop';
12
+ /** A declared texture encoding. */
13
+ export type BootTextures = 'img' | 'ktx2';
14
+ /** Ordered reads by loading phase. */
15
+ export type BootSources = Readonly<Record<'sky' | 'baked' | 'terrain' | 'trees' | 'physics' | 'cabins' | 'props' | 'art' | 'music' | 'sfx', readonly string[]>>;
16
+ /** A resolved value for each output tier and texture mode. */
17
+ export interface BootModes<T> { readonly modes: Readonly<Record<BootTier, Readonly<Record<BootTextures, T>>>> }
18
+ /** Explicit per-tier GPU aliases, with author aliases overriding shared assets. */
19
+ export type BootGpuFiles = Readonly<Record<BootTier, Readonly<Record<string, string>>>>;
20
+
21
+ /** Resolve phone fallbacks and GPU aliases using only the supplied inventory.
22
+ * Ordering and duplicate handling remain the caller's responsibility. */
23
+ export function bootFilePolicy(tier: BootTier, mode: BootTextures, table: BootGpuFiles, inventory: BootInventory): { phone: (url: string) => string; gpu: (url: string) => string } {
24
+ if (inventory === undefined || inventory === null) throw new Error('Boot authoring requires an explicit inventory');
25
+ const { phone, gpu } = filePolicy(tier, mode, table, inventory);
26
+ return { phone, gpu };
27
+ }
28
+
29
+ /** S4: a shard's phone stand-ins, read off the baked files: `/assets/<folder>/astc6/<the path under /assets/gpu>`, each with its
30
+ * own hash (scripts/bake-astc6.mjs). The overlay is the listing, so no table sits in the source. */
31
+ export function phoneOverlayRows(phone: Readonly<Record<string, string>>, listed: readonly string[], folder: string): Readonly<Record<string, string>> {
32
+ const plain = (url: string): string => url.replace(/-[a-f0-9]{8}(?=\.[a-z0-9]+$)/u, '');
33
+ const baked = new Map(listed.map(url => [plain(url), url]));
34
+ if (baked.size !== listed.length) throw new Error('Two phone overlay files share one name');
35
+ const rows: Record<string, string> = {};
36
+ for (const [served, gpu] of Object.entries(phone)) {
37
+ const file = baked.get(plain(gpu).replace('/assets/gpu/', `/assets/${folder}/astc6/`));
38
+ if (file !== undefined) rows[served] = file;
39
+ }
40
+ return rows;
41
+ }
42
+
43
+ /** Shared sky bytes participate only when explicitly present in the author inventory. */
44
+ export function sharedBootTextures(inventory: BootInventory): string[] {
45
+ return CLOUD_FIELD_URL in inventory ? [CLOUD_FIELD_URL] : [];
46
+ }
47
+
48
+ /** The engine's required physics input in native boot order, as an independent author row. */
49
+ export function sharedBootPhysics(): readonly [typeof RAPIER_WASM_URL] { return [RAPIER_WASM_URL]; }
50
+
51
+ /** Owned native bake-texture namespace used by retained author boot recipes.
52
+ * The owner is a bounded project id, never a caller-supplied URL or path. */
53
+ export function bakedBootTextureSource<const Owner extends string>(owner: Owner): { readonly publicPrefix: `/assets/baked/${Owner}/tex/` } {
54
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(owner) || owner.length > 64) throw new Error('Invalid baked texture owner');
55
+ return { publicPrefix: `/assets/baked/${owner}/tex/` };
56
+ }
57
+
58
+ export interface BootRecipe {
59
+ readonly source: { readonly urls: readonly string[] | Readonly<Record<BootTier, readonly string[]>> }
60
+ | { readonly concat: readonly string[] } | { readonly publicPrefix: string }
61
+ | { readonly pbr: readonly string[] } | { readonly gltf: readonly string[] }
62
+ | { readonly tablePrefix: string } | { readonly pages: string }
63
+ | { readonly available: readonly string[]; readonly fallback: readonly string[] };
64
+ readonly map?: readonly ('gpu' | 'layer')[];
65
+ readonly present?: boolean;
66
+ readonly unique?: boolean;
67
+ readonly excludeParts?: readonly string[];
68
+ readonly excludeBasenamePrefix?: string;
69
+ readonly except?: string;
70
+ readonly aliases?: string;
71
+ }
72
+ /** External immutable inventories and aliases, supplied by the same build/runtime owner as the GPU table. */
73
+ export interface BootRecipeInputs {
74
+ /** Offline presence facts: retained file sizes or guaranteed declared build outputs. */
75
+ readonly inventory: BootInventory;
76
+ readonly pages?: Readonly<Record<string, Readonly<Record<BootTier, Readonly<Record<string, { readonly image: string }>>>>>>;
77
+ readonly aliases?: Readonly<Record<string, Readonly<Record<string, string>>>>;
78
+ }
79
+ export type BootRecipes = Readonly<Record<string, BootRecipe>>;
80
+ const isUrlList = (value: readonly string[] | Readonly<Record<BootTier, readonly string[]>>): value is readonly string[] => Array.isArray(value);
81
+ /** Resolve an ordered author recipe against explicit immutable inventory facts.
82
+ * Keeps native recursion/file limits, transform order and strict metadata refusals; never borrows the page inventory. */
83
+ export function bootRecipeFiles(recipes: BootRecipes, name: string, tier: BootTier, tex: BootTextures,
84
+ table: BootGpuFiles, inputs: BootRecipeInputs): string[] {
85
+ if (inputs === undefined || inputs.inventory === undefined || inputs.inventory === null) throw new Error('Boot authoring requires an explicit inventory');
86
+ const inventory = inputs.inventory, policy = filePolicy(tier, tex, table, inventory);
87
+ let visits = 0;
88
+ const run = (id: string, chain: readonly string[]): string[] => {
89
+ if (chain.includes(id) || chain.length >= 16 || ++visits > 256) throw new Error('Boot recipe cycle or bound exceeded');
90
+ const row = recipes[id];
91
+ if (row === undefined) throw new Error(`Missing boot recipe ${id}`);
92
+ const src = row.source, next = [...chain, id];
93
+ let urls: string[];
94
+ if ('urls' in src) urls = [...(isUrlList(src.urls) ? src.urls : src.urls[tier])];
95
+ else if ('concat' in src) urls = src.concat.flatMap(ref => run(ref, next));
96
+ else if ('publicPrefix' in src) urls = Object.keys(inventory).filter(url => url.startsWith(src.publicPrefix));
97
+ else if ('pbr' in src) urls = src.pbr.flatMap(policy.pbr);
98
+ else if ('gltf' in src) urls = src.gltf.flatMap(assetId => [`/assets/models/${assetId}/${assetId}.gltf`, `/assets/models/${assetId}/${assetId}.bin`, ...['diff', 'nor_gl', 'arm'].map(kind => `/assets/models/${assetId}/textures/${assetId}_${kind}_1k.jpg`)]);
99
+ else if ('tablePrefix' in src) urls = tex === 'ktx2' ? Object.keys(table[tier]).filter(url => url.startsWith(src.tablePrefix)).sort().flatMap(url => table[tier][url] ?? []) : [];
100
+ else if ('pages' in src) {
101
+ const pages = inputs.pages?.[src.pages]?.[tier];
102
+ if (pages === undefined) throw new Error(`Missing boot pages ${src.pages}`);
103
+ urls = Object.keys(pages).sort().map(key => {
104
+ const page = pages[key], mapped = table[tier][key];
105
+ if (tex === 'ktx2' && mapped === undefined) throw new Error(`Missing boot page stand-in ${key}`);
106
+ if (page === undefined) throw new Error(`Missing boot page ${key}`);
107
+ return tex === 'ktx2' ? mapped ?? page.image : page.image;
108
+ });
109
+ } else urls = src.available.every(url => url in inventory) ? [...src.available] : [...src.fallback];
110
+ if (row.excludeParts !== undefined) urls = urls.filter(url => !row.excludeParts?.some(part => url.includes(part)));
111
+ if (row.excludeBasenamePrefix !== undefined) urls = urls.filter(url => !url.slice(url.lastIndexOf('/') + 1).startsWith(row.excludeBasenamePrefix ?? ''));
112
+ if (row.unique === true) urls = [...new Set(urls)];
113
+ for (const transform of row.map ?? []) urls = urls.map(policy[transform]);
114
+ if (row.present === true) urls = urls.filter(url => url in inventory);
115
+ if (row.except !== undefined) { const excluded = new Set(run(row.except, next)); urls = urls.filter(url => !excluded.has(url)); }
116
+ if (row.aliases !== undefined) {
117
+ const aliases = inputs.aliases?.[row.aliases];
118
+ if (aliases === undefined) throw new Error(`Missing boot aliases ${row.aliases}`);
119
+ urls = urls.map(url => aliases[url] ?? url);
120
+ }
121
+ if (urls.length > 4096) throw new Error('Boot recipe file bound exceeded');
122
+ return urls;
123
+ };
124
+ return run(name, []);
125
+ }
126
+ /** Resolve every byte category through the same ordered recipe interpreter. */
127
+ export function bootRecipeSources(recipes: BootRecipes, sources: Readonly<Record<keyof BootSources, string>>,
128
+ tier: BootTier, tex: BootTextures, table: BootGpuFiles, inputs: BootRecipeInputs): BootSources {
129
+ const files = (key: keyof BootSources): readonly string[] => bootRecipeFiles(recipes, sources[key], tier, tex, table, inputs);
130
+ return { sky: files('sky'), baked: files('baked'), terrain: files('terrain'), trees: files('trees'), physics: files('physics'),
131
+ cabins: files('cabins'), props: files('props'), art: files('art'), music: files('music'), sfx: files('sfx') };
132
+ }