@wildshard/shard-format 0.26.0 → 0.28.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 (50) hide show
  1. package/package.json +3 -1
  2. package/src/format/actorMoves.ts +32 -0
  3. package/src/format/audio-mp4.ts +1 -1
  4. package/src/format/audioProfiles.ts +1 -1
  5. package/src/format/brains.ts +3 -3
  6. package/src/format/builtIndexes.ts +2 -2
  7. package/src/format/clientChannels.ts +3 -3
  8. package/src/format/clientScripts.ts +1 -1
  9. package/src/format/contentBounds.ts +1 -1
  10. package/src/format/creature-layers.ts +44 -1
  11. package/src/format/creature-projectile.ts +32 -0
  12. package/src/format/creature-ranks.ts +37 -0
  13. package/src/format/creature-sizes.ts +45 -4
  14. package/src/format/creature-volumes.ts +5 -4
  15. package/src/format/creatures.ts +20 -3
  16. package/src/format/crowds.ts +1 -1
  17. package/src/format/deviceMemoryCost.ts +2 -2
  18. package/src/format/directorStages.ts +3 -3
  19. package/src/format/flyers.ts +2 -2
  20. package/src/format/grazers.ts +2 -2
  21. package/src/format/items.ts +1 -1
  22. package/src/format/materialGraph.ts +7 -7
  23. package/src/format/materials.ts +10 -10
  24. package/src/format/memoryAdmission.ts +1 -1
  25. package/src/format/namedJsonContracts.ts +1 -1
  26. package/src/format/nativeGround.ts +3 -3
  27. package/src/format/navigation.ts +2 -2
  28. package/src/format/parsed-json.ts +91 -0
  29. package/src/format/placement-page-text.ts +281 -0
  30. package/src/format/questHost.ts +1 -1
  31. package/src/format/rows.ts +18 -5
  32. package/src/format/runtime-tier.ts +56 -0
  33. package/src/format/runtimeBinds.ts +6 -6
  34. package/src/format/runtimeCost.ts +1 -1
  35. package/src/format/runtimeSpawns.ts +2 -2
  36. package/src/format/scaledPostContract.ts +2 -2
  37. package/src/format/scriptAbi.ts +1 -1
  38. package/src/format/scriptWireV2.ts +1 -1
  39. package/src/format/shardSchema.ts +2 -2
  40. package/src/format/shardfile-assets.ts +1 -1
  41. package/src/format/shardfileValidation.ts +2 -1
  42. package/src/format/skin-file.ts +3 -0
  43. package/src/format/skinData.ts +39 -19
  44. package/src/format/skins.ts +21 -2
  45. package/src/format/sourceResidency.ts +1 -1
  46. package/src/format/spawnCombat.ts +10 -5
  47. package/src/format/standalone-catalogue.ts +1 -1
  48. package/src/format/terrain.ts +1 -1
  49. package/src/format/validationReceipt.ts +2 -2
  50. package/src/format/weaponProfiles.ts +2 -2
@@ -35,7 +35,7 @@ export const ChallengeGrazerSchema: v.SchemaWithPipe<readonly [v.StrictObjectSch
35
35
  windupField: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9._:-]*$/u), v.maxLength(128)),
36
36
  recoveryField: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9._:-]*$/u), v.maxLength(128)),
37
37
  }), v.check(row => distinctChallenge(row), 'Distinct challenge strikes and fields, ordered perception'));
38
- /** Admitted timed challenge policy; stable actor phase and contact recipes arrive from trusted loader ports. */
38
+ /** Admitted timed challenge policy; stable actor phase and contact recipes arrive from native loader ports. */
39
39
 
40
40
  /** Reject nonfinite tuning, unknown fields and conflicting identities before installation. */
41
41
  export function parseChallengeGrazer(data: unknown): ShardChallengeGrazer { return v.parse(ChallengeGrazerSchema, data); }
@@ -56,7 +56,7 @@ export const GrazerSchema: v.VariantSchema<'pattern', readonly [
56
56
  v.pipe(v.strictObject({ ...ChallengeGrazerSchema.pipe[0].entries, kind: v.literal('grazer'), pattern: v.literal('circle-challenge') }),
57
57
  v.check(row => distinctChallenge(row), 'Distinct challenge strikes and fields, ordered perception')),
58
58
  ]);
59
- /** Admitted grazer data; floor, RNG and body authority remain trusted pattern-specific ports. */
59
+ /** Admitted grazer data; floor, RNG and body authority remain native pattern-specific ports. */
60
60
 
61
61
  /** Admit either pattern without constructing a policy, body or random stream. */
62
62
  export function parseGrazer(data: unknown): ShardGrazer { return v.parse(GrazerSchema, data); }
@@ -5,7 +5,7 @@ import * as v from 'valibot';
5
5
  import { MeleeContactsSchema, NativeMeleeRowSchema, WeaponProfileSchema, type MeleeContactRow } from './weaponProfiles.ts';
6
6
  import { isJsonData } from './json.ts';
7
7
 
8
- /** The bounded authored family/context name, also checked by the trusted family installer. */
8
+ /** The bounded authored family/context name, also checked by the native family installer. */
9
9
  export const ItemFamilyNameSchema: v.GenericSchema<ItemFamilyNameRowsInput, ItemFamilyNameRows> = v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9.-]*$/u), v.maxLength(128));
10
10
  const name = ItemFamilyNameSchema;
11
11
  const weaponId: v.GenericSchema<`weapon.${string}`> = v.custom<`weapon.${string}`>((value) => typeof value === 'string' && /^weapon\.[a-z][a-zA-Z0-9.-]*$/u.test(value) && value.length <= 128);
@@ -111,7 +111,7 @@ export interface GraphParam {
111
111
  readonly max?: number;
112
112
  readonly bind?: GraphBinding;
113
113
  /**
114
- * Texture only: data bypasses sRGB conversion; absent retains the colour role. `lent`: no admitted file, a trusted
114
+ * Texture only: data bypasses sRGB conversion; absent retains the colour role. `lent`: no admitted file, a host-owned
115
115
  * runtime lends the sampled texture (`setTexture`, swapped without a program change; a 1×1 black stand-in until then)
116
116
  * and `value` only names the slot; a texture it decodes at run time (a baked sky key) is sampled as it is.
117
117
  */
@@ -218,7 +218,7 @@ export interface GraphStages {
218
218
  /** a graph */
219
219
  export interface GraphIr {
220
220
  readonly version: typeof GRAPH_IR_VERSION;
221
- /** Explicit per-program ceilings. Raising the defaults requires trusted runtime authority. */
221
+ /** Explicit per-program ceilings. Raising the defaults requires native runtime authority. */
222
222
  readonly budget?: GraphBudget;
223
223
  /** a material (vertex.offset + surface), a screen pass (post) or a shard's declared fog (fog, selected by materials) */
224
224
  readonly kind: 'material' | 'post' | 'fog';
@@ -252,10 +252,10 @@ export interface GraphBudget {
252
252
  }
253
253
  /** the default ceilings (a starter graph: the measure preset is ≈ 60 nodes, ≈ 170 instructions) */
254
254
  export const DEFAULT_GRAPH_BUDGET: GraphBudget = { nodes: 160, samplers: 4, instructions: 480 };
255
- /** Hard ceilings for a trusted declaration; loop trips remain charged to the estimated cost. */
255
+ /** Hard ceilings for a native declaration; loop trips remain charged to the estimated cost. */
256
256
  export const MAX_GRAPH_BUDGET: GraphBudget = Object.freeze({ nodes: 4096, samplers: 16, instructions: 8192 });
257
257
 
258
- /** Raw graph JSON bounds, enforced before typing or compiler work; trusted presets supply their own node budget. */
258
+ /** Raw graph JSON bounds, enforced before typing or compiler work; host-owned presets supply their own node budget. */
259
259
  export const GRAPH_ADMISSION_LIMITS: Readonly<{ bytes: 96000; depth: 64; }> = Object.freeze({ bytes: 96_000, depth: 64 });
260
260
  /** whether JSON writes `value` as itself in quotes: printable ASCII with no quote or backslash (a loop, not a regex: Node's
261
261
  * type stripping rewrote the regex's escaped bracket and broke it) */
@@ -560,7 +560,7 @@ export interface GraphValidationOptions {
560
560
  readonly stateFields?: readonly string[];
561
561
  readonly budget?: GraphBudget;
562
562
  /** Host authority to use an explicit declaration; content cannot grant this. */
563
- readonly trustedBudget?: boolean;
563
+ readonly declaredBudget?: boolean;
564
564
  /** the directional lights a `sun` sub-graph is built for (1 … SUN_CASCADES_MAX; SUN_CASCADES when absent) */
565
565
  readonly cascades?: number;
566
566
  }
@@ -624,7 +624,7 @@ interface Scope {
624
624
  * every reason it is refused.
625
625
  */
626
626
  export function validateGraph(input: unknown, opts: GraphValidationOptions = {}): GraphValidation {
627
- const rawErrors = graphAdmissionErrors(input, opts.trustedBudget === true ? MAX_GRAPH_BUDGET.nodes : opts.budget?.nodes ?? DEFAULT_GRAPH_BUDGET.nodes);
627
+ const rawErrors = graphAdmissionErrors(input, opts.declaredBudget === true ? MAX_GRAPH_BUDGET.nodes : opts.budget?.nodes ?? DEFAULT_GRAPH_BUDGET.nodes);
628
628
  if (rawErrors.length > 0) return { ok: false, errors: rawErrors };
629
629
  const errors: string[] = [];
630
630
  const fail = (msg: string): null => { errors.push(msg); return null; };
@@ -639,7 +639,7 @@ export function validateGraph(input: unknown, opts: GraphValidationOptions = {})
639
639
  const value = declared[key];
640
640
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > MAX_GRAPH_BUDGET[key]) return { ok: false, errors: [`graph: declared budget ${key} must be 1–${MAX_GRAPH_BUDGET[key]}`] };
641
641
  }
642
- if (opts.trustedBudget !== true) return { ok: false, errors: ['graph: declared budget requires trusted runtime authority'] };
642
+ if (opts.declaredBudget !== true) return { ok: false, errors: ['graph: declared budget requires native runtime authority'] };
643
643
  budget = { nodes: Number(declared.nodes), samplers: Number(declared['samplers']), instructions: Number(declared['instructions']) };
644
644
  }
645
645
  if (input.version !== GRAPH_IR_VERSION) fail(`graph: version ${String(input.version)} (this engine reads ${GRAPH_IR_VERSION})`);
@@ -11,7 +11,7 @@ import type { Shardfile } from './shardSchema.ts';
11
11
 
12
12
  const graph = v.pipe(v.unknown(), v.rawTransform(({ dataset, addIssue, NEVER }): GraphIr => {
13
13
  if (!isJsonData(dataset.value)) { addIssue({ message: 'material graph is plain JSON data' }); return NEVER; }
14
- const checked = validateGraph(dataset.value, { trustedBudget: true });
14
+ const checked = validateGraph(dataset.value, { declaredBudget: true });
15
15
  if (!checked.ok) { addIssue({ message: checked.errors.join('; ') }); return NEVER; }
16
16
  // a catalogue slot holds a material or the shard's declared fog (O11: a material selects it by id), never a post pass
17
17
  if (checked.graph.kind === 'post') { addIssue({ message: 'material slot requires a material or fog graph, not a post pass' }); return NEVER; }
@@ -38,7 +38,7 @@ export function presetLooks(familyLooks: Shardfile['look']['familyLooks']): { to
38
38
  /**
39
39
  * A graph file's JSON (SF59): `file` returns an admitted file's bytes (undefined: not present). Throws when the file is
40
40
  * missing, past the inline slot's byte bound, or not UTF-8 JSON; the graph itself is validated by the caller under the
41
- * author caps (a graph file is authored content, never a trusted preset).
41
+ * author caps (a graph file is authored content, never a native preset).
42
42
  */
43
43
  export function graphFileJson(hash: string, file: (hash: string) => Uint8Array | undefined): unknown {
44
44
  const bytes = file(hash);
@@ -47,13 +47,13 @@ export function graphFileJson(hash: string, file: (hash: string) => Uint8Array |
47
47
  try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { throw new Error(`material graph file ${hash} is not UTF-8 JSON`); }
48
48
  }
49
49
  /**
50
- * A graph material's IR (D74: graph files): a graph file's JSON, its bytes from `file`, validated under the trusted budget
50
+ * A graph material's IR (D74: graph files): a graph file's JSON, its bytes from `file`, validated under the host-owned budget
51
51
  * (product admission already held it to its caps and bindings, `graphFileRules`), or an inline entry's IR. Throws for a
52
52
  * preset reference or a missing or invalid file.
53
53
  */
54
54
  export function materialGraphIr(entry: MaterialEntry, file: (hash: string) => Uint8Array | undefined): GraphIr {
55
55
  if (entry.family !== 'graph' || !('file' in entry)) throw new Error('material graph IR needs a graph file (a built shard file carries no inline graph)');
56
- const checked = validateGraph(graphFileJson(entry.file, file), { trustedBudget: true });
56
+ const checked = validateGraph(graphFileJson(entry.file, file), { declaredBudget: true });
57
57
  if (!checked.ok) throw new Error(`material graph file ${entry.file}: ${checked.errors.join('; ')}`);
58
58
  return checked.graph;
59
59
  }
@@ -130,7 +130,7 @@ export interface GraphBindingSources { readonly day: ReadonlyMap<string, 'float'
130
130
  /**
131
131
  * The admitted binding names of a shardfile (SF59): the canonical dotted day-key channels its look keys carry and its
132
132
  * declared public i32 / f64 state fields as `shared.<field>` / `player.<field>`, plus, as for material curves
133
- * (`curveStateFields`), its host-owned numeric fields when a trusted runtime binds `state` (the runtime hands the client
133
+ * (`curveStateFields`), its host-owned numeric fields when a native runtime binds `state` (the runtime hands the client
134
134
  * their live values). Admission and the client's compile both use these lists, never a compiler default that allows any name.
135
135
  */
136
136
  export function graphBindingSources(source: Pick<Shardfile, 'look' | 'state'> & Partial<Pick<Shardfile, 'runtime' | 'questHost'>>): GraphBindingSources {
@@ -151,7 +151,7 @@ function numericFields(state: Shardfile['state'], privacy: 'public' | 'host'): s
151
151
 
152
152
  /**
153
153
  * Check graph uniform bindings against admitted day channels and public numeric state declarations. A preset reference
154
- * must be expressible as a built-in preset (`presetRefusal`, the rule the engine's preset door applies; the trusted preset
154
+ * must be expressible as a built-in preset (`presetRefusal`, the rule the engine's preset door applies; the native preset
155
155
  * programs are held to `PRESET_GRAPH_BUDGET` by the engine's own tests, never the author caps); a graph file must be a
156
156
  * JSON file of the library closure (`files` / `library` given: its bytes are validated by product admission, `graphFileRules`).
157
157
  */
@@ -167,7 +167,7 @@ export function materialGraphRules(source: Pick<Shardfile, 'look' | 'state'> & P
167
167
  continue;
168
168
  }
169
169
  if ('preset' in material) { const refusal = presetRefusal(material.preset); if (refusal !== null) errors.push(`material ${materialId}: ${refusal}`); continue; }
170
- const checked = validateGraph(material.graph, { dayKeys: [...dayChannels.keys()], stateFields, trustedBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
170
+ const checked = validateGraph(material.graph, { dayKeys: [...dayChannels.keys()], stateFields, declaredBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
171
171
  if (!checked.ok) { errors.push(...checked.errors.map((error) => `material ${materialId}: ${error}`)); continue; }
172
172
  errors.push(...bindingTypeErrors(materialId, checked.graph, dayChannels));
173
173
  const fog = checked.graph.effectState?.fog;
@@ -192,7 +192,7 @@ export function graphFileRules(source: Pick<Shardfile, 'look' | 'state' | 'files
192
192
  if (material.family !== 'graph' || !('file' in material)) continue;
193
193
  let ir: unknown;
194
194
  try { ir = graphFileJson(material.file, bytes); } catch (error) { errors.push(`material ${materialId}: ${error instanceof Error ? error.message : 'graph file'}`); continue; }
195
- const checked = validateGraph(ir, { dayKeys: [...dayChannels.keys()], stateFields, trustedBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
195
+ const checked = validateGraph(ir, { dayKeys: [...dayChannels.keys()], stateFields, declaredBudget: source.runtime !== null && source.runtime !== undefined || hasDeclaredClientPage(source) });
196
196
  if (!checked.ok) { errors.push(...checked.errors.map((error) => `material ${materialId}: ${error}`)); continue; }
197
197
  if (checked.graph.kind === 'post') { errors.push(`material ${materialId}: a graph file in a material slot holds a material or fog graph, not a post pass`); continue; }
198
198
  const fog = checked.graph.effectState?.fog, target = typeof fog === 'string' ? source.look.materials[fog] : undefined;
@@ -261,7 +261,7 @@ export function curveAt(curve: Curve, d: number): number {
261
261
 
262
262
  /**
263
263
  * State-bound material curves (`look.curves`): per catalogue family entry, numbers that move with a declared public numeric
264
- * state field (`shared.<name>` / `player.<name>`), or a host-owned numeric shared field when a trusted runtime binds
264
+ * state field (`shared.<name>` / `player.<name>`), or a host-owned numeric shared field when a native runtime binds
265
265
  * `state` (its runtime hands the client the live value), each the curve's value at the field's live value (clamped 0 … 1). A
266
266
  * `param` is a dot path into the entry with its defaults filled (`ground.shade.tint.0`) that resolves to a number its
267
267
  * family can move without a new program (`MOVABLE_FAMILY_PARAMS`). The client evaluates them in its material tick, only
@@ -291,7 +291,7 @@ export function curvedParams(params: FamilyMaterialParams, curves: readonly { re
291
291
  return out;
292
292
  }
293
293
  /**
294
- * The fields a material curve may read: every public numeric field, and, when a trusted runtime binds `state`
294
+ * The fields a material curve may read: every public numeric field, and, when a native runtime binds `state`
295
295
  * (`runtime.binds`), its host-owned numeric shared fields too (the runtime hands the client their live values).
296
296
  */
297
297
  function curveStateFields(source: Pick<Shardfile, 'state' | 'runtime'> & Partial<Pick<Shardfile, 'questHost'>>): ReadonlySet<string> {
@@ -8,7 +8,7 @@ export interface AdmissionMeasurement {
8
8
  readonly residentBaseBytes?: number;
9
9
  readonly rev: string; readonly device: string; readonly evidence: string;
10
10
  }
11
- /** Trusted callers report only the total-memory envelope here. Parser, hash, script and content-understatement guards are separate. */
11
+ /** Host-owned callers report only the total-memory envelope here. Parser, hash, script and content-understatement guards are separate. */
12
12
  export interface MemoryAdmissionRequest {
13
13
  readonly stage: 'runtime' | 'declared' | 'actual' | 'resident';
14
14
  readonly owner: string; readonly id: string;
@@ -54,7 +54,7 @@ export const PageReturnRowsSchema: v.GenericSchema<PageReturnRowsInput, PageRetu
54
54
 
55
55
  export const ReturnProgramSchema: v.StrictObjectSchema<{ readonly script: v.GenericSchema<ReturnProgramRowsInput['script'], ReturnProgramRows['script']>; readonly bytes: v.GenericSchema<ReturnProgramRowsInput['bytes'], ReturnProgramRows['bytes']>; readonly v2: v.ExactOptionalSchema<v.GenericSchema<Exclude<ReturnProgramRowsInput['v2'], undefined>, Exclude<ReturnProgramRows['v2'], undefined>>, undefined>; }, undefined> = v.strictObject({ script: v.unknown(), bytes: v.string(),v2: v.exactOptional(ReturnProjectionV2Schema) });
56
56
  const operations = ['$ref', '$call', '$new', '$fn', '$set', '$if', '$or', '$coalesce', '$eq', '$not', '$sequence'];
57
- /** Draft-07 wire contract for the trusted assembly language. Constants and
57
+ /** Draft-07 wire contract for the host-owned assembly language. Constants and
58
58
  * operands are bounded JSON values; tag names and row/module shapes are closed.
59
59
  * checkedHeadlessAssembly additionally checks depth, references and real exports. */
60
60
  export const HEADLESS_ASSEMBLY_JSON_SCHEMA: { $schema: string; type: string; additionalProperties: boolean; required: string[]; definitions: { key: { type: string; minLength: number; maxLength: number; not: { enum: string[]; }; }; value: { anyOf: ({ type: string[]; maxItems?: never; items?: never; maxProperties?: never; propertyNames?: never; additionalProperties?: never; minProperties?: never; } | { type: string; maxItems: number; items: { $ref: string; }; maxProperties?: never; propertyNames?: never; additionalProperties?: never; minProperties?: never; } | { type: string; maxProperties: number; propertyNames: { allOf: ({ $ref: string; pattern?: never; } | { pattern: string; $ref?: never; })[]; enum?: never; }; additionalProperties: { $ref: string; }; maxItems?: never; items?: never; minProperties?: never; } | { type: string; minProperties: number; maxProperties: number; propertyNames: { enum: string[]; allOf?: never; }; additionalProperties: { $ref: string; }; maxItems?: never; items?: never; })[]; }; rows: { type: string; maxItems: number; items: { type: string; additionalProperties: boolean; required: string[]; properties: { name: { $ref: string; }; value: { $ref: string; }; }; }; }; installRows: { type: string; maxItems: number; items: { type: string; additionalProperties: boolean; required: string[]; properties: { name: { $ref: string; }; value: { anyOf: ({ $ref: string; type?: never; additionalProperties?: never; required?: never; properties?: never; } | { type: string; additionalProperties: boolean; required: string[]; properties: { $native: { anyOf: ({ const: string; type?: never; additionalProperties?: never; required?: never; properties?: never; } | { type: string; additionalProperties: boolean; required: string[]; properties: { kind: { const: string; }; speed: { type: string; exclusiveMinimum: number; }; }; const?: never; })[]; }; }; $ref?: never; })[]; }; }; }; }; }; properties: { version: { const: number; }; modules: { type: string; propertyNames: { type: string; pattern: string; }; additionalProperties: { type: string; maxItems: number; uniqueItems: boolean; items: { $ref: string; }; }; }; constants: { $ref: string; }; prepare: { $ref: string; }; install: { $ref: string; }; level: { $ref: string; }; ports: { $ref: string; }; entries: { $ref: string; }; }; } = {
@@ -1,7 +1,7 @@
1
1
  import * as v from 'valibot';
2
2
  import type { ShardEntryways } from './entryways.ts';
3
3
 
4
- /** Original native WSTR terrain retained by a trusted world-only hybrid; this declaration never installs collision. */
4
+ /** Original native WSTR terrain retained by a native world-only runtime shard; this declaration never installs collision. */
5
5
  export const NativeGroundSchema: v.GenericSchema<NativeGroundInput, NativeGround> = v.strictObject({ version: v.literal(1), file: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u)) });
6
6
  /** The immutable native payload; resolution, seed and landscape identity derive from admitted bytes. */
7
7
 
@@ -17,11 +17,11 @@ export interface NativeGroundSource {
17
17
  edge: Record<ShardEntryways[number]['edge'], { heights: readonly number[] }>;
18
18
  entryways: ShardEntryways;
19
19
  }
20
- /** Native ground is an independent critical root with one trusted collision owner, never another compiled collider. */
20
+ /** Native ground is an independent critical root with one host-owned collision owner, never another compiled collider. */
21
21
  export function nativeGroundRules(source: NativeGroundSource): string[] {
22
22
  const data = source.nativeGround; if (data === null) return [];
23
23
  const errors: string[] = [];
24
- if (source.runtime === null) errors.push('native ground requires a trusted runtime declaration');
24
+ if (source.runtime === null) errors.push('native ground requires a native runtime declaration');
25
25
  if (source.terrain !== null || source.meshCollision !== null) errors.push('native ground and compiled collision are mutually exclusive');
26
26
  const file = source.files.find(row => row.hash === data.file);
27
27
  if (file?.kind !== 'binary' || file.dependencies.length > 0 || !source.critical.includes(data.file)) errors.push('native ground is an independent critical binary root');
@@ -14,9 +14,9 @@ export const NavigationSchema: v.GenericSchema<NavigationInput, Navigation> = v.
14
14
  origin: point, tileSize: positive, tiles: v.pipe(v.array(v.tuple([coordinate, coordinate])), v.maxLength(4096)) })), v.minLength(1), v.maxLength(16)) });
15
15
  /** An admitted immutable navigation declaration, with exact WSNM bounds and ordered agent tile grids. */
16
16
 
17
- /** Trusted level transport: admitted product bytes or the manifest's declared immutable URL. */
17
+ /** Native level transport: admitted product bytes or the manifest's declared immutable URL. */
18
18
  export type NavigationContent = { row: unknown; bytes: Uint8Array } | { row: unknown; url: string };
19
- /** Validate a declaration supplied by a trusted manifest or author boundary before any transport read. */
19
+ /** Validate a declaration supplied by a native manifest or author boundary before any transport read. */
20
20
  export function parseNavigation(input: unknown): Navigation { return v.parse(NavigationSchema, input); }
21
21
  /** Build the declaration from original bytes without resampling, re-encoding or sorting tiles/layers. */
22
22
  export function describeNavigation(file: string, bytes: Uint8Array): Navigation {
@@ -0,0 +1,91 @@
1
+ // MG10 / ENGINE-MEMORY EM17: checks for a value fresh from `JSON.parse`, which
2
+ // is plain data by construction: own enumerable data properties, ordinary
3
+ // prototypes, dense arrays, and no symbols, accessors or cycles. `isJsonData`
4
+ // reads a property descriptor for every key to prove that of any value; for
5
+ // parsed text only its node and depth bounds and canonical numbers are left,
6
+ // and this walk checks them without allocating.
7
+
8
+ type Fields = Readonly<Record<string, unknown>>
9
+ type Check = (value: unknown) => boolean
10
+
11
+ const NONE = 0
12
+ const ONE = 1
13
+ const NEGATIVE_ZERO = -0
14
+ const NODE_LIMIT = 100_000
15
+ const DEPTH_LIMIT = 64
16
+
17
+ const fields = (value: unknown): value is Fields =>
18
+ typeof value === 'object' && value !== null && !Array.isArray(value)
19
+ const items = (value: unknown): readonly unknown[] | undefined =>
20
+ Array.isArray(value) ? value : undefined
21
+ const own = (value: Fields, key: string): unknown =>
22
+ Object.hasOwn(value, key) ? value[key] : undefined
23
+ const canonical = (value: number): boolean =>
24
+ Number.isFinite(value) && !Object.is(value, NEGATIVE_ZERO)
25
+
26
+ /** One walk's node count, against `isJsonData`'s bound. */
27
+ class Walk {
28
+ private nodes = NONE
29
+
30
+ public fits(value: unknown, depth: number, skip?: string): boolean {
31
+ this.nodes += ONE
32
+ if (this.nodes > NODE_LIMIT || depth > DEPTH_LIMIT) {
33
+ return false
34
+ }
35
+ if (typeof value === 'number') {
36
+ return canonical(value)
37
+ }
38
+ const list = items(value)
39
+ if (list !== undefined) {
40
+ return this.fitsItems(list, depth + ONE)
41
+ }
42
+ return !fields(value) || this.fitsFields(value, depth + ONE, skip)
43
+ }
44
+
45
+ private fitsItems(list: readonly unknown[], depth: number): boolean {
46
+ for (const item of list) {
47
+ if (!this.fits(item, depth)) {
48
+ return false
49
+ }
50
+ }
51
+ return true
52
+ }
53
+
54
+ private fitsFields(value: Fields, depth: number, skip?: string): boolean {
55
+ for (const key in value) {
56
+ if (
57
+ Object.hasOwn(value, key) &&
58
+ key !== skip &&
59
+ !this.fits(value[key], depth)
60
+ ) {
61
+ return false
62
+ }
63
+ }
64
+ return true
65
+ }
66
+ }
67
+
68
+ /**
69
+ * `isJsonData`'s verdict for a `JSON.parse` value: at most 100,000 values,
70
+ * none deeper than 64, every number finite and not -0. `skip` leaves one key
71
+ * of the root object out. Only for `JSON.parse` output.
72
+ */
73
+ const parsedJsonFits = (value: unknown, skip?: string): boolean =>
74
+ new Walk().fits(value, NONE, skip)
75
+
76
+ /** An array of at most `max` items, each passing `check`. */
77
+ function listOf(value: unknown, max: number, check: Check): boolean {
78
+ const list = items(value)
79
+ if (list === undefined || list.length > max) {
80
+ return false
81
+ }
82
+ for (const item of list) {
83
+ if (!check(item)) {
84
+ return false
85
+ }
86
+ }
87
+ return true
88
+ }
89
+
90
+ export { fields, items, listOf, own, parsedJsonFits }
91
+ export type { Check, Fields }
@@ -0,0 +1,281 @@
1
+ import { fields, items, listOf, own, parsedJsonFits } from './parsed-json.ts'
2
+ import { parseWorldScenePlacementPage } from './worldScenePlacement.ts'
3
+
4
+ import type { Check, Fields } from './parsed-json.ts'
5
+ import type { WorldScenePlacementPage } from './worldScenePlacement.ts'
6
+
7
+ // MG10 / ENGINE-MEMORY EM17: a placement page read straight from its text.
8
+ // Nine's boot allocated about 110 MB parsing 6 MB of pages: the JSON guard's
9
+ // property descriptors, entry and item copies, valibot's rebuilt output and
10
+ // the failed branch of the pose union. A value fresh from `JSON.parse` is plain
11
+ // data by construction (own enumerable data properties, ordinary prototypes,
12
+ // dense arrays, no symbols, accessors or cycles), so the guard reduces to its
13
+ // node and depth bounds and canonical numbers. A page whose every object,
14
+ // tuple and record matches the schema exactly is already what valibot would
15
+ // rebuild, so it is admitted as it stands. Anything else takes
16
+ // `parseWorldScenePlacementPage`, which stays the contract and the only source
17
+ // of refusals: this path never admits a page that one refuses (the
18
+ // differential fuzz in the test).
19
+
20
+ type Entries = readonly (readonly [string, Check])[]
21
+
22
+ const NONE = 0
23
+ const ONE = 1
24
+ const COORD_LIMIT = 1e6
25
+ const ID_MAX = 256
26
+ const ROWS_MAX = 16
27
+ const POSES_MAX = 8192
28
+ const BOXES_MAX = 49_152
29
+ const BOX_STRIDE = 6
30
+ const COLLIDERS_MAX = 32_768
31
+ const FLOORS_MAX = 4096
32
+ const KNOTS_MIN = 2
33
+ const KNOTS_MAX = 8
34
+ const SPLIT_MAX = 2048
35
+ const PAIR = 2
36
+ const TRIPLE = 3
37
+ const MATRIX = 16
38
+
39
+ const has = (value: object, key: string): boolean => Object.hasOwn(value, key)
40
+ const poseFits = (pose: unknown): boolean => parsedJsonFits(pose)
41
+
42
+ /** `placementPageData`'s verdict for a `JSON.parse` value. */
43
+ function parsedPageData(page: unknown): boolean {
44
+ const rows = fields(page) ? items(own(page, 'rows')) : undefined
45
+ if (rows === undefined || rows.length > ROWS_MAX) {
46
+ return false
47
+ }
48
+ if (rows.length !== ONE) {
49
+ return parsedJsonFits(page)
50
+ }
51
+ const [row] = rows
52
+ return (
53
+ parsedJsonFits(page, 'rows') &&
54
+ fields(row) &&
55
+ parsedJsonFits(row, 'poses') &&
56
+ listOf(own(row, 'poses'), POSES_MAX, poseFits)
57
+ )
58
+ }
59
+
60
+ const idOk = (value: unknown): boolean =>
61
+ typeof value === 'string' && value.length > NONE && value.length <= ID_MAX
62
+ const finiteOk = (value: unknown): value is number =>
63
+ typeof value === 'number' &&
64
+ Number.isFinite(value) &&
65
+ value >= -COORD_LIMIT &&
66
+ value <= COORD_LIMIT
67
+ const distanceOk = (value: unknown): boolean => finiteOk(value) && value >= NONE
68
+ const boolOk = (value: unknown): boolean => typeof value === 'boolean'
69
+ const finites = (value: unknown, length: number): value is readonly number[] =>
70
+ Array.isArray(value) &&
71
+ value.length === length &&
72
+ listOf(value, length, finiteOk)
73
+ const pairOk = (value: unknown): boolean => finites(value, PAIR)
74
+ const tripleOk = (value: unknown): boolean => finites(value, TRIPLE)
75
+ const matrixOk = (value: unknown): boolean => finites(value, MATRIX)
76
+ const oneOf =
77
+ (...options: readonly unknown[]): Check =>
78
+ (value: unknown): boolean =>
79
+ options.includes(value)
80
+
81
+ /** Every key of `value`, inherited enumerable ones too (valibot's strict check reads them), is known. */
82
+ function keysWithin(value: Fields, known: ReadonlySet<string>): boolean {
83
+ for (const key in value) {
84
+ if (!known.has(key)) {
85
+ return false
86
+ }
87
+ }
88
+ return true
89
+ }
90
+ /** Absent, or own and passing: an inherited value would be rebuilt as own. */
91
+ const optional = (value: Fields, key: string, check: Check): boolean =>
92
+ !(key in value) || (has(value, key) && check(value[key]))
93
+ function allPass(value: Fields, entries: Entries, need: boolean): boolean {
94
+ for (const [key, check] of entries) {
95
+ if (
96
+ need
97
+ ? !has(value, key) || !check(value[key])
98
+ : !optional(value, key, check)
99
+ ) {
100
+ return false
101
+ }
102
+ }
103
+ return true
104
+ }
105
+ /** A strict object of `need` and `may` fields, its key lists built once. */
106
+ function strictShape(
107
+ need: Readonly<Record<string, Check>>,
108
+ may: Readonly<Record<string, Check>>,
109
+ ): Check {
110
+ const known = new Set([...Object.keys(need), ...Object.keys(may)])
111
+ const needed: Entries = Object.entries(need)
112
+ const allowed: Entries = Object.entries(may)
113
+ return (value: unknown): boolean =>
114
+ fields(value) &&
115
+ keysWithin(value, known) &&
116
+ allPass(value, needed, true) &&
117
+ allPass(value, allowed, false)
118
+ }
119
+
120
+ // Valibot's record drops these keys from its output.
121
+ const DROPPED = new Set(['__proto__', 'prototype', 'constructor'])
122
+ function paramsOk(value: unknown): boolean {
123
+ if (!fields(value)) {
124
+ return false
125
+ }
126
+ for (const key in value) {
127
+ if (!has(value, key) || DROPPED.has(key) || !idOk(key)) {
128
+ return false
129
+ }
130
+ }
131
+ return true
132
+ }
133
+ const AXES = ['x', 'y', 'z'] as const
134
+ const axes = (
135
+ ...more: readonly (readonly [string, Check])[]
136
+ ): Record<string, Check> =>
137
+ Object.fromEntries([
138
+ ...AXES.map((axis): [string, Check] => [axis, finiteOk]),
139
+ ...more,
140
+ ])
141
+ const yxzOk = strictShape(
142
+ { scale: finiteOk, yaw: finiteOk },
143
+ { pitch: finiteOk, roll: finiteOk, yawAtan2: pairOk },
144
+ )
145
+ const POSE_MAY = { color: tripleOk, params: paramsOk, variant: idOk }
146
+ const matrixPoseOk = strictShape(axes(['matrix', matrixOk]), POSE_MAY)
147
+ const yxzPoseOk = strictShape(axes(['yxz', yxzOk]), POSE_MAY)
148
+ // The schema's pose union: one of its two strict objects, never both.
149
+ function poseOk(value: unknown): boolean {
150
+ if (!fields(value)) {
151
+ return false
152
+ }
153
+ const matrix = has(value, 'matrix')
154
+ if (matrix === has(value, 'yxz')) {
155
+ return false
156
+ }
157
+ return matrix ? matrixPoseOk(value) : yxzPoseOk(value)
158
+ }
159
+ const tierPairOk = strictShape({ desktop: distanceOk, phone: distanceOk }, {})
160
+ const tierNumberOk = (value: unknown): boolean =>
161
+ distanceOk(value) || tierPairOk(value)
162
+ const cullOk = strictShape(
163
+ {},
164
+ {
165
+ bounds: oneOf('sphere', 'box'),
166
+ far: tierNumberOk,
167
+ flat: boolOk,
168
+ from: oneOf('origin', 'bounds'),
169
+ frustum: boolOk,
170
+ keepNear: finiteOk,
171
+ lodBy: oneOf('copy', 'set'),
172
+ minAngular: tierNumberOk,
173
+ radiusBias: finiteOk,
174
+ step: distanceOk,
175
+ view: oneOf('forest'),
176
+ },
177
+ )
178
+ const boxesOk = (value: unknown): boolean =>
179
+ listOf(value, BOXES_MAX, finiteOk) &&
180
+ Array.isArray(value) &&
181
+ value.length % BOX_STRIDE === NONE
182
+ const drawnIntoOk = strictShape({ boxes: boxesOk, part: idOk }, {})
183
+ // Knots rise strictly along their first value; heights are distances.
184
+ function knotOk(knot: unknown): boolean {
185
+ if (!finites(knot, TRIPLE)) {
186
+ return false
187
+ }
188
+ const [, height] = knot
189
+ return distanceOk(height)
190
+ }
191
+ function rises(knots: readonly unknown[]): boolean {
192
+ let before = Number.NEGATIVE_INFINITY
193
+ for (const knot of knots) {
194
+ const [along = Number.NaN] = finites(knot, TRIPLE) ? knot : []
195
+ if (!(along > before)) {
196
+ return false
197
+ }
198
+ before = along
199
+ }
200
+ return true
201
+ }
202
+ function profileOk(value: unknown): boolean {
203
+ const knots = items(value)
204
+ return (
205
+ knots !== undefined &&
206
+ knots.length >= KNOTS_MIN &&
207
+ listOf(knots, KNOTS_MAX, knotOk) &&
208
+ rises(knots)
209
+ )
210
+ }
211
+ const floorOk = strictShape(
212
+ { ...axes(), hd: distanceOk, hw: distanceOk },
213
+ { profile: profileOk, rot: finiteOk, slope: finiteOk, tilt: finiteOk },
214
+ )
215
+ const splitOk = (value: unknown): boolean =>
216
+ typeof value === 'number' &&
217
+ Number.isInteger(value) &&
218
+ value >= ONE &&
219
+ value <= SPLIT_MAX
220
+ const pieceOk = strictShape(
221
+ { id: idOk },
222
+ {
223
+ floorPolicy: oneOf('first', 'highest'),
224
+ floors: (value: unknown): boolean => listOf(value, FLOORS_MAX, floorOk),
225
+ follows: oneOf('copy'),
226
+ name: idOk,
227
+ solidFloor: boolOk,
228
+ split: splitOk,
229
+ },
230
+ )
231
+ const rowOk = strictShape(
232
+ {
233
+ draw: oneOf('single', 'instanced', 'batched', 'merged'),
234
+ id: idOk,
235
+ model: idOk,
236
+ poses: (value: unknown): boolean => listOf(value, POSES_MAX, poseOk),
237
+ },
238
+ {
239
+ batch: idOk,
240
+ colliders: (value: unknown): boolean =>
241
+ Array.isArray(value) && value.length <= COLLIDERS_MAX,
242
+ cull: cullOk,
243
+ drawnInto: drawnIntoOk,
244
+ name: idOk,
245
+ piece: pieceOk,
246
+ sortObjects: boolOk,
247
+ tier: oneOf('phone', 'desktop'),
248
+ },
249
+ )
250
+ const rowId = (row: unknown): unknown => (fields(row) ? own(row, 'id') : row)
251
+ const rowsOk = (value: unknown): boolean =>
252
+ listOf(value, ROWS_MAX, rowOk) &&
253
+ Array.isArray(value) &&
254
+ value.length > NONE &&
255
+ new Set(value.map((row: unknown): unknown => rowId(row))).size ===
256
+ value.length
257
+ const pageShapeOk = strictShape({ rows: rowsOk, version: oneOf(ONE) }, {})
258
+
259
+ /**
260
+ * True when `value`, fresh from `JSON.parse`, is a placement page
261
+ * `parseWorldScenePlacementPage` admits and would rebuild unchanged (key order
262
+ * aside). False is no verdict: the caller asks the schema. Only for
263
+ * `JSON.parse` output; another value may carry accessors or prototypes.
264
+ */
265
+ function plainPlacementPage(value: unknown): value is WorldScenePlacementPage {
266
+ return parsedPageData(value) && pageShapeOk(value)
267
+ }
268
+
269
+ /**
270
+ * A placement page from its JSON text, as the client reads it: admitted as it
271
+ * stands when it is plain and exact, otherwise through
272
+ * `parseWorldScenePlacementPage` (its output, or its refusal).
273
+ */
274
+ function parseWorldScenePlacementPageText(
275
+ text: string,
276
+ ): WorldScenePlacementPage {
277
+ const value: unknown = JSON.parse(text)
278
+ return plainPlacementPage(value) ? value : parseWorldScenePlacementPage(value)
279
+ }
280
+
281
+ export { parseWorldScenePlacementPageText, plainPlacementPage }
@@ -105,7 +105,7 @@ export const QuestHostSchema: v.GenericSchema<unknown, QuestHostRow> = v.pipe(ra
105
105
  /** Compile the bounded graph, command and stage composition without installing runtime services. */
106
106
  export function parseQuestHost(input: unknown): QuestHostRow { return v.parse(QuestHostSchema, input); }
107
107
 
108
- /** Root admission binds a native quest host to declared flags and its existing hybrid quest owner. */
108
+ /** Root admission binds a native quest host to declared flags and its existing runtime quest owner. */
109
109
  export function questHostBindingRules(row: QuestHostRow | null | undefined, flags: readonly string[], bound: boolean): readonly string[] {
110
110
  if (row === null || row === undefined) return [];
111
111
  const errors: string[] = [];