@wildshard/shard-format 0.68.1 → 0.69.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.68.1",
3
+ "version": "0.69.1",
4
4
  "description": "The raw shardfile format: the spec, the validator and a validate CLI. The public, versioned contract every other repo builds on.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
package/src/cli/pack.ts CHANGED
@@ -58,7 +58,7 @@ interface HeldIndex {
58
58
  readonly build: Readonly<{ sourceHash: string }>
59
59
  readonly files: readonly Listed[]
60
60
  readonly packs?: readonly PackRow[] | undefined
61
- readonly schemas: readonly Listed[]
61
+ readonly schemas?: readonly Listed[] | undefined
62
62
  readonly sections: readonly Section[]
63
63
  }
64
64
 
@@ -33,6 +33,15 @@ const LEGACY_SPELLING = '0.1'
33
33
  const NONE = 0
34
34
  /** Deprecated in the current format with no data change: a shard file of any version may still carry it. */
35
35
  const CURRENT = '0.1.0.1'
36
+ /** Format 0.1.0.2's envelope (SHARD-COMPAT CP14, FORMAT-PRUNE FP4 and FP25). */
37
+ const ENVELOPE = '0.1.0.2'
38
+ const LEGACY_LAYOUT = 2
39
+ /** FORMAT-PRUNE FP4: always empty, never read. */
40
+ const EMPTY_INDEX_FIELDS: readonly (readonly [string, string | undefined])[] = [
41
+ ['schemas', undefined],
42
+ ['runtime', 'files'],
43
+ ['runtime', 'lines'],
44
+ ]
36
45
  /** FORMAT-PRUNE FP15: OF30 cut B leaves these as plain JSON nothing reads. */
37
46
  const SPECIES_PROGRAM_FAMILY: readonly string[] = [
38
47
  'actors/species-programs',
@@ -72,6 +81,50 @@ const RULES: readonly DeprecationRule[] = [
72
81
  uses: (shard: Readonly<DeprecationInput>): boolean =>
73
82
  field(shard.index, 'version') === LEGACY_SPELLING,
74
83
  },
84
+ {
85
+ id: 'shard.version',
86
+ path: 'shard.json version beside the layout marker formatVersion 2 (SHARD-COMPAT CP14)',
87
+ since: ENVELOPE,
88
+ replacement:
89
+ 'formatVersion: the four-part format version, with no version field',
90
+ migration: 'cp14-format-version',
91
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
92
+ field(shard.index, 'formatVersion') === LEGACY_LAYOUT,
93
+ },
94
+ {
95
+ id: 'shard.empty-fields',
96
+ path: 'shard.json schemas, runtime.files and runtime.lines (FORMAT-PRUNE FP4)',
97
+ since: ENVELOPE,
98
+ replacement: 'nothing: each is always empty and no reader reads it',
99
+ migration: 'fp4-drop-empty-index-fields',
100
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
101
+ EMPTY_INDEX_FIELDS.some(
102
+ ([outer, inner]: readonly [string, string | undefined]): boolean =>
103
+ inner === undefined
104
+ ? field(shard.index, outer) !== undefined
105
+ : field(field(shard.index, outer), inner) !== undefined,
106
+ ),
107
+ },
108
+ {
109
+ id: 'requires.sdk',
110
+ path: 'shard.json requires.sdk (SHARD-COMPAT CP8): a copy of the format version',
111
+ since: ENVELOPE,
112
+ replacement:
113
+ 'nothing: formatVersion names the format; writers stop sourcing it, then it goes at zero users',
114
+ migration: undefined,
115
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
116
+ field(field(shard.index, 'requires'), 'sdk') !== undefined,
117
+ },
118
+ {
119
+ id: 'requires.capabilities',
120
+ path: 'shard.json requires.capabilities (FORMAT-PRUNE FP4): always empty, never read',
121
+ since: ENVELOPE,
122
+ replacement:
123
+ 'nothing: the build source hash covers it, so writers stop sourcing it, then it goes at zero users',
124
+ migration: undefined,
125
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
126
+ field(field(shard.index, 'requires'), 'capabilities') !== undefined,
127
+ },
75
128
  {
76
129
  id: 'manifest.gridShardfile',
77
130
  path: 'sections/ui/level manifest.gridShardfile (and the discovery mount)',
@@ -17,6 +17,10 @@ import {
17
17
  verifyInventory,
18
18
  } from './format-migrate-inventory.ts'
19
19
  import { rebuildInventory } from './format-migrate-rebuild.ts'
20
+ import {
21
+ declaredShardfileFormat,
22
+ writeShardfileFormat,
23
+ } from './format-migration-envelope.ts'
20
24
  import {
21
25
  FORMAT_MIGRATIONS,
22
26
  checkMigrations,
@@ -117,7 +121,7 @@ function admitOriginal(files: Files, hash: Hash, to: string): Admitted {
117
121
  const cook = rawCook === undefined ? undefined : readCookData(rawCook)
118
122
  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- read only for its slug, sdk, files and cook row
119
123
  requireCookPreparation(index as unknown as OutputIndex, cook, hash)
120
- return { index, cook, from: checkWindow(index['version'], to) }
124
+ return { index, cook, from: checkWindow(declaredShardfileFormat(index), to) }
121
125
  }
122
126
 
123
127
  const MOUNT = /^mounts\/.*\.json$/u
@@ -154,7 +158,7 @@ function runSteps(
154
158
  ): void {
155
159
  for (const step of steps) {
156
160
  step.apply(shard)
157
- shard.index['version'] = step.to
161
+ writeShardfileFormat(shard.index, step.to)
158
162
  }
159
163
  }
160
164
 
@@ -254,7 +258,7 @@ function migrateShardfile(
254
258
  return {
255
259
  files: copy,
256
260
  from: admitted.from,
257
- to: String(admitted.index['version']),
261
+ to: String(declaredShardfileFormat(admitted.index)),
258
262
  applied: steps.map((step: Readonly<FormatMigration>): string => step.id),
259
263
  chainId: chainId(migrations, options.hash),
260
264
  digest: options.hash(copy.get(INDEX) ?? new Uint8Array()),
@@ -0,0 +1,72 @@
1
+ // oxlint-disable typescript/prefer-readonly-parameter-types -- a step edits the shard it is handed, in place
2
+ /** Format 0.1.0.2's chain steps (SHARD-COMPAT CP14, FORMAT-PRUNE FP4 and FP25, J486). The runner writes the copy's
3
+ * version into `formatVersion` from 0.1.0.2 on (`writeShardfileFormat`), replacing the frozen layout marker `2`; these
4
+ * steps drop the fields the new envelope no longer carries. Every dropped field held nothing: `version` repeats the
5
+ * format version, and the other four are always empty with no reader. */
6
+ import { LEGACY_LAYOUT, writesIndexFormatVersion } from './version.ts'
7
+
8
+ import type { FormatMigration, MigratingShard } from './format-migrations.ts'
9
+
10
+ type JsonRecord = Record<string, unknown>
11
+
12
+ const ENVELOPE = '0.1.0.2'
13
+
14
+ function isRecord(value: unknown): value is JsonRecord {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
16
+ }
17
+
18
+ /** SHARD-COMPAT CP14 (FP25): `version` becomes `formatVersion`; the layout marker goes in the same step. */
19
+ const formatVersionField: FormatMigration = {
20
+ id: 'cp14-format-version',
21
+ to: ENVELOPE,
22
+ touches: 'data',
23
+ affects: [],
24
+ apply: (shard: MigratingShard): void => {
25
+ Reflect.deleteProperty(shard.index, 'version')
26
+ },
27
+ }
28
+
29
+ /** FORMAT-PRUNE FP4: `schemas`, `runtime.files` and `runtime.lines`, always empty, never read. `requires.capabilities` stays:
30
+ * it is part of the assembled source the build's source hash covers, so it goes only with the writers that stop sourcing it. */
31
+ const dropEmptyIndexFields: FormatMigration = {
32
+ id: 'fp4-drop-empty-index-fields',
33
+ to: ENVELOPE,
34
+ touches: 'data',
35
+ affects: [],
36
+ apply: (shard: MigratingShard): void => {
37
+ const { index } = shard
38
+ Reflect.deleteProperty(index, 'schemas')
39
+ const { runtime } = index
40
+ if (isRecord(runtime)) {
41
+ Reflect.deleteProperty(runtime, 'files')
42
+ Reflect.deleteProperty(runtime, 'lines')
43
+ }
44
+ },
45
+ }
46
+
47
+ /** The format version a `shard.json` declares, as written, or `undefined`: `formatVersion` from 0.1.0.2, else the
48
+ * legacy `version` beside the layout marker. */
49
+ function declaredShardfileFormat(index: Readonly<JsonRecord>): unknown {
50
+ const declared: unknown = index['formatVersion']
51
+ return declared === LEGACY_LAYOUT || declared === undefined
52
+ ? index['version']
53
+ : declared
54
+ }
55
+
56
+ /** Write a copy's format version the way that version spells it: `formatVersion` from 0.1.0.2 (with no `version`),
57
+ * else `version` beside the layout marker. */
58
+ function writeShardfileFormat(index: JsonRecord, version: string): void {
59
+ if (writesIndexFormatVersion(version)) {
60
+ Reflect.deleteProperty(index, 'version')
61
+ index['formatVersion'] = version
62
+ } else {
63
+ index['version'] = version
64
+ }
65
+ }
66
+
67
+ export {
68
+ declaredShardfileFormat,
69
+ dropEmptyIndexFields,
70
+ formatVersionField,
71
+ writeShardfileFormat,
72
+ }
@@ -2,6 +2,10 @@
2
2
  /** The migration chain's registry (SHARD-COMPAT CP1, J486). A migration is one pure, data-only step that rewrites an
3
3
  * older shard file's JSON to a newer format version. It is not a save migration (`migrations.ts`) and not a catalogue
4
4
  * schema change (api-server). The change's author adds its migration here in the same release (J486, Q49). */
5
+ import {
6
+ dropEmptyIndexFields,
7
+ formatVersionField,
8
+ } from './format-migration-envelope.ts'
5
9
  import { journalGlyphImages } from './format-migration-journal.ts'
6
10
  import { dropRuntimeTrust, shardfilePointer } from './format-migration-prune.ts'
7
11
  import {
@@ -65,6 +69,8 @@ const FORMAT_MIGRATIONS: readonly FormatMigration[] = [
65
69
  journalGlyphImages,
66
70
  shardfilePointer,
67
71
  dropRuntimeTrust,
72
+ formatVersionField,
73
+ dropEmptyIndexFields,
68
74
  ]
69
75
 
70
76
  /** Whether a file at `version` still needs a step that writes `to`. The legacy two-part spelling sits just below its
@@ -0,0 +1,33 @@
1
+ /** The two `shard.json` envelopes' version fields (SHARD-COMPAT CP14, FORMAT-PRUNE FP25), shared by every index
2
+ * reader: the full parser (`outputIndex.ts`), the lineage reader and the download reader. */
3
+ import { exactOptional, literal, picklist, union } from 'valibot'
4
+
5
+ import {
6
+ INDEX_FORMAT_VERSIONS,
7
+ LEGACY_INDEX_VERSIONS,
8
+ LEGACY_LAYOUT,
9
+ } from './version.ts'
10
+
11
+ import type {
12
+ ExactOptionalSchema,
13
+ LiteralSchema,
14
+ PicklistSchema,
15
+ UnionSchema,
16
+ } from 'valibot'
17
+
18
+ /** `formatVersion`: the frozen layout marker `2` (formats 0.1 to 0.1.0.1), or the format version itself (0.1.0.2 on). */
19
+ const IndexFormatVersionSchema: UnionSchema<
20
+ [
21
+ LiteralSchema<typeof LEGACY_LAYOUT, undefined>,
22
+ PicklistSchema<typeof INDEX_FORMAT_VERSIONS, undefined>,
23
+ ],
24
+ undefined
25
+ > = union([literal(LEGACY_LAYOUT), picklist(INDEX_FORMAT_VERSIONS)])
26
+
27
+ /** `version`: only the legacy envelope carries it, beside the layout marker. */
28
+ const LegacyIndexVersionSchema: ExactOptionalSchema<
29
+ PicklistSchema<typeof LEGACY_INDEX_VERSIONS, undefined>,
30
+ undefined
31
+ > = exactOptional(picklist(LEGACY_INDEX_VERSIONS))
32
+
33
+ export { IndexFormatVersionSchema, LegacyIndexVersionSchema }
@@ -8,12 +8,15 @@ const completeReturn:v.GenericSchema<v.InferInput<typeof ReturnProgramSchema>,v.
8
8
  const finite = v.pipe(v.number(), v.finite());
9
9
  const key = v.pipe(v.string(), v.minLength(1), v.maxLength(128));
10
10
  const point = v.strictObject({ x: finite, z: finite });
11
+ /** FORMAT-PRUNE FP3: no reader in any repo; optional now, and Driftwood stops writing it at its Track F row (SM1). */
12
+ const legacyMemory = v.exactOptional(v.array(v.strictObject({ from: key, to: key, axis: v.picklist(['x', 'z', 'zero']) })));
11
13
  /** Mixed native roster policy, pose, reserve and physical volley composition. */
12
14
  export const MixedPopulationSchema: v.StrictObjectSchema<{ readonly step: v.GenericSchema<MixedPopulationRowsInput['step'], MixedPopulationRows['step']>; readonly limit: v.GenericSchema<MixedPopulationRowsInput['limit'], MixedPopulationRows['limit']>; readonly attackTurnCap: v.GenericSchema<MixedPopulationRowsInput['attackTurnCap'], MixedPopulationRows['attackTurnCap']>; readonly hunted: v.GenericSchema<MixedPopulationRowsInput['hunted'], MixedPopulationRows['hunted']>; readonly floorKinds: v.GenericSchema<MixedPopulationRowsInput['floorKinds'], MixedPopulationRows['floorKinds']>; readonly practice: v.GenericSchema<MixedPopulationRowsInput['practice'], MixedPopulationRows['practice']>; readonly reserve: v.GenericSchema<MixedPopulationRowsInput['reserve'], MixedPopulationRows['reserve']>; readonly volley: v.GenericSchema<MixedPopulationRowsInput['volley'], MixedPopulationRows['volley']>; readonly poses: v.GenericSchema<MixedPopulationRowsInput['poses'], MixedPopulationRows['poses']>; readonly perch: v.GenericSchema<MixedPopulationRowsInput['perch'], MixedPopulationRows['perch']>; }, undefined> = v.strictObject({
13
15
  step: key, limit: v.pipe(finite, v.integer(), v.minValue(1), v.maxValue(256)),
14
16
  attackTurnCap: finite, hunted: v.array(key), floorKinds: v.array(key),
15
17
  practice: v.strictObject({ at: point, fade: finite, delay: finite, away: finite }),
16
- reserve: v.strictObject({ kind: key, variant: key, scale: v.tuple([finite, finite]), legacyMemory: v.array(v.strictObject({ from: key, to: key, axis: v.picklist(['x', 'z', 'zero']) })) }),
18
+ reserve: v.strictObject({ kind: key, variant: key, scale: v.tuple([finite, finite]),
19
+ legacyMemory }),
17
20
  volley: v.strictObject({ owner: key, strike: key, tags: v.array(v.custom<`${string}.${string}`>(value => typeof value === 'string' && /^[a-z][a-zA-Z0-9.-]*\.[a-zA-Z0-9.-]+$/u.test(value))) }),
18
21
  poses: v.array(v.strictObject({ kind: key, clips: v.array(NumericPoseSchema),
19
22
  lift: v.exactOptional(v.tuple([finite, finite, finite, finite])) })),
@@ -66,7 +69,7 @@ interface MixedPopulationRowsInputFields {
66
69
  number,
67
70
  number
68
71
  ];
69
- legacyMemory: ({
72
+ legacyMemory?: ({
70
73
  from: string;
71
74
  to: string;
72
75
  axis: 'x' | 'z' | 'zero';
@@ -154,7 +157,7 @@ interface MixedPopulationRowsFields {
154
157
  number,
155
158
  number
156
159
  ];
157
- legacyMemory: ({
160
+ legacyMemory?: ({
158
161
  from: string;
159
162
  to: string;
160
163
  axis: 'x' | 'z' | 'zero';
@@ -1,4 +1,5 @@
1
1
  import * as v from 'valibot';
2
+ import { IndexFormatVersionSchema } from './index-format-version.ts';
2
3
 
3
4
  interface Measured { readonly path: string; readonly hash: string; readonly bytes: number }
4
5
  export interface OutputDownloadIndex {
@@ -18,9 +19,11 @@ export function readOutputDownloadIndex(input: unknown): OutputDownloadIndex {
18
19
  const bytes = v.pipe(v.number(), v.safeInteger(), v.minValue(0));
19
20
  const hash = v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u));
20
21
  const measured = { path, hash, bytes };
21
- const index = v.parse(v.object({ format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2),
22
+ const listed = v.pipe(v.array(v.object(measured)), v.maxLength(128));
23
+ // SHARD-COMPAT CP14: either envelope; format 0.1.0.2 drops the always-empty schemas list (FORMAT-PRUNE FP4).
24
+ const parsed = v.parse(v.object({ format: v.literal('wildshard.shardfile'), formatVersion: IndexFormatVersionSchema,
22
25
  sections: v.pipe(v.array(v.object({ ...measured, name: v.string() })), v.maxLength(256)),
23
- schemas: v.pipe(v.array(v.object(measured)), v.maxLength(128)),
26
+ schemas: v.exactOptional(listed),
24
27
  // The compiler and runtime share tier/variant selection. Dropping these
25
28
  // existing index facts here reserves bodies this device will never read.
26
29
  files: v.pipe(v.array(v.object({ path, hash, compressed: bytes, name: v.exactOptional(v.string()),
@@ -28,6 +31,7 @@ export function readOutputDownloadIndex(input: unknown): OutputDownloadIndex {
28
31
  runtime: v.unknown(),
29
32
  packs: v.exactOptional(v.pipe(v.array(v.object({ ...measured, entries: v.pipe(v.array(v.object({ hash, offset: bytes, bytes })), v.maxLength(8192)) })), v.maxLength(64))),
30
33
  }), input);
34
+ const index = { ...parsed, schemas: parsed.schemas ?? [] };
31
35
  const paths = ['shard.json', 'validation.json', ...index.sections.map(row => row.path), ...index.schemas.map(row => row.path), ...index.files.map(row => row.path)];
32
36
  if (new Set(paths).size !== paths.length) throw new Error('Duplicate shard file download path');
33
37
  return index;
@@ -2,6 +2,7 @@ import type { Shardfile } from './shardSchema.ts';
2
2
  import type { PlatformSectionName } from './sections.ts';
3
3
  import type { PlatformDataSections } from './platformDataSections.ts';
4
4
  import type { OutputIndex } from './outputIndex.ts';
5
+ import { shardfileFormatOf } from './version.ts';
5
6
 
6
7
  export interface SectionMapping { readonly name: PlatformSectionName; readonly fields: readonly (keyof Shardfile)[]; readonly row?: keyof Shardfile['rows']; readonly spawns?: true; }
7
8
  /** Root-key envelopes preserve optional-field absence and every existing host's values. */
@@ -105,7 +106,7 @@ export function outputSectionPayloads(source: Shardfile): ReadonlyMap<string, un
105
106
  export function assembleOutputTransport(index: OutputIndex, sections: ReadonlyMap<string, unknown>, checks?: { readonly bounds: (name: string, value: unknown) => void; readonly platform: (name: keyof PlatformDataSections, value: unknown) => void; readonly fields: (name: string, value: object) => Record<string, unknown> }): Record<string, unknown> {
106
107
  // J91: the server class is the product index's alone, never a field of the Shardfile a client admits.
107
108
  const {server:_server,audioWaiver:_audioWaiver,...admission}=index.admission;
108
- const result: Record<string, unknown> = {version:index.version,identity:index.identity,requires:index.requires,...admission,files:index.files.filter(file => file.commons !== true).map(({path: _path,name: _name,tier: _tier,variantOf: _variant,commons: _commons,jsonSchema: _schema,kind,...rest}) => Object.assign(rest,{kind:kind === 'tile' || kind === 'bin' ? 'binary' : kind})),runtime:index.runtime === null ? null : {kind:index.runtime.kind,cost:index.runtime.cost,binds:index.runtime.binds}};
109
+ const result: Record<string, unknown> = {version:shardfileFormatOf(index),identity:index.identity,requires:index.requires,...admission,files:index.files.filter(file => file.commons !== true).map(({path: _path,name: _name,tier: _tier,variantOf: _variant,commons: _commons,jsonSchema: _schema,kind,...rest}) => Object.assign(rest,{kind:kind === 'tile' || kind === 'bin' ? 'binary' : kind})),runtime:index.runtime === null ? null : {kind:index.runtime.kind,cost:index.runtime.cost,binds:index.runtime.binds}};
109
110
  if (sections.size !== index.sections.length || index.sections.some(entry => !sections.has(entry.name))) throw new Error('Missing or surplus output section');
110
111
  const rows: Record<string, unknown> = {};
111
112
  for (const entry of index.sections) {
@@ -15,8 +15,9 @@ import { ClientPlanRuntimeSchema } from './runtime.ts';
15
15
  import { RuntimeSpawnsSchema } from './runtimeSpawns.ts';
16
16
  import { RowsSchema } from './rows.ts';
17
17
  import { ShardHashSchema, ShardNaturalSchema, IdentitySchema, RequiresSchema, FilesSchema, type ShardIdentityInput, type ShardRequiresInput, type ShardReferencesInput, type ShardIdentity, type ShardRequires, type ShardReferences } from './shardSections.ts';
18
- import { SHARDFILE_VERSIONS } from './version.ts';
19
- import type { ShardfileVersion } from './version.ts';
18
+ import { LEGACY_LAYOUT } from './version.ts';
19
+ import { IndexFormatVersionSchema, LegacyIndexVersionSchema } from './index-format-version.ts';
20
+ import type { IndexFormatVersion, LegacyIndexVersion } from './version.ts';
20
21
  import { isJsonData, isJsonDataWithFileSchemas } from './json.ts';
21
22
  import { clientOwnershipRules } from './clientOwnership.ts';
22
23
  import { PLATFORM_DATA_SECTIONS } from './platformDataSections.ts';
@@ -27,17 +28,24 @@ const path = v.pipe(v.string(), v.maxLength(240), v.regex(/^(?:[a-zA-Z0-9_-][a-z
27
28
  const sectionName = v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9-]*\/[a-zA-Z][a-zA-Z0-9_-]*$/u));
28
29
  const measuredFile = { path, hash: ShardHashSchema, bytes: ShardNaturalSchema };
29
30
  const section = v.strictObject({ ...measuredFile, name: sectionName, schema: v.pipe(v.string(), v.maxLength(240)) });
31
+ /** Always empty; format 0.1.0.2 drops it (FORMAT-PRUNE FP4). */
32
+ const emptySchemas = v.exactOptional(v.pipe(v.array(v.strictObject(measuredFile)), v.maxLength(0)));
30
33
  const cookRow = v.exactOptional(v.strictObject({ ...measuredFile, path: v.literal('cook.json') }));
31
34
  const costs = v.omit(FilesSchema.pipe[0].item, ['kind']).entries;
32
35
  const fileSchema = v.strictObject({ ...costs, path, kind: v.picklist(['glb', 'ktx2', 'audio', 'json', 'wasm', 'tile', 'bin', 'image']), name: v.exactOptional(v.pipe(v.string(), v.maxLength(240))), tier: v.exactOptional(v.picklist(['phone', 'desktop'])), variantOf: v.exactOptional(v.pipe(v.string(), v.minLength(1), v.maxLength(240))), commons: v.exactOptional(v.literal(true)), jsonSchema: v.exactOptional(v.record(v.string(), v.unknown())) });
33
36
  /** `trust` is retired (OF1): new indexes omit it, old products still carry their value and nothing reads it. */
34
- const runtime = v.strictObject({ ...v.omit(ClientPlanRuntimeSchema.pipe[0], ['spawns']).entries, trust: v.exactOptional(v.unknown()), files: v.pipe(v.array(v.strictObject({ ...measuredFile, lines: ShardNaturalSchema })), v.maxLength(0)), lines: v.literal(0) });
37
+ /** `files` and `lines` are always empty: the 0.1.0.2 envelope drops them (FORMAT-PRUNE FP4), the legacy one still carries them. */
38
+ const runtimeFiles = v.exactOptional(v.pipe(v.array(v.strictObject({ ...measuredFile, lines: ShardNaturalSchema })), v.maxLength(0)));
39
+ const runtime = v.strictObject({ ...v.omit(ClientPlanRuntimeSchema.pipe[0], ['spawns']).entries, trust: v.exactOptional(v.unknown()), files: runtimeFiles, lines: v.exactOptional(v.literal(0)) });
35
40
  /** Format 2 inventories every emitted byte except its index and validation receipt. */
36
41
  export const OutputIndexSchema: v.GenericSchema<OutputIndexRowsInput, OutputIndexRows> & { readonly entries: { readonly [Key in keyof OutputIndexRows]-?: v.GenericSchema<OutputIndexRowsInput[Key], OutputIndexRows[Key]> } } = v.strictObject({
37
- format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2), sdk: v.picklist(['0.2', '0.3']), version: v.picklist(SHARDFILE_VERSIONS),
42
+ format: v.literal('wildshard.shardfile'),
43
+ /** SHARD-COMPAT CP14 (FP25): the format version itself from 0.1.0.2; the legacy envelope carries the frozen layout marker
44
+ * `2` here and its version in `version`. `checkIndexEnvelope` holds each envelope to its own fields. */
45
+ formatVersion: IndexFormatVersionSchema, sdk: v.picklist(['0.2', '0.3']), version: LegacyIndexVersionSchema,
38
46
  identity: IdentitySchema, build: v.strictObject({ sourceHash: ShardHashSchema, validator: v.pipe(v.string(), v.minLength(1), v.maxLength(160)) }), requires: RequiresSchema,
39
47
  admission: v.strictObject({ budgets: ShardfileFieldSchemas.budgets, serverBudget: ShardfileFieldSchemas.serverBudget, authorCaps: ShardfileFieldSchemas.authorCaps, critical: ShardfileFieldSchemas.critical, library: ShardfileFieldSchemas.library, late: v.exactOptional(AdmissionLateSchema), server: v.exactOptional(AdmissionServerSchema), audioWaiver: v.exactOptional(AudioWaiverSchema) }),
40
- sections: v.pipe(v.array(section), v.maxLength(256)), schemas: v.pipe(v.array(v.strictObject(measuredFile)), v.maxLength(0)),
48
+ sections: v.pipe(v.array(section), v.maxLength(256)), schemas: emptySchemas,
41
49
  files: v.pipe(v.array(fileSchema), v.maxLength(8192)), runtime: v.nullable(runtime),
42
50
  ktx2Costs: v.exactOptional(v.pipe(v.record(ShardHashSchema,v.strictObject({rgba:ShardNaturalSchema,astc:ShardNaturalSchema,bc7:ShardNaturalSchema})),v.check(rows=>Object.keys(rows).length<=8192,'bounded texture cost table'))),
43
51
  /** iPhone downloads I5: content-hashed concatenations of the small sections, schemas and files, so a reader can fetch
@@ -63,8 +71,37 @@ export function parseOutputDescriptorIndex(input: unknown): OutputIndex | null {
63
71
  if (!isJsonDataWithFileSchemas(input)) throw new Error('Shardfile descriptor requires bounded plain JSON');
64
72
  return isOutputIndex(input) ? parseOutputIndexRows(input) : null;
65
73
  }
74
+ /** The fields only the legacy envelope (`formatVersion: 2`, formats 0.1 to 0.1.0.1) carries; 0.1.0.2 drops each
75
+ * (SHARD-COMPAT CP14; FORMAT-PRUNE FP3 `runtime.trust`, FP4 the always-empty index lists). */
76
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
77
+ function legacyIndexFields(index: OutputIndex): readonly string[] {
78
+ return [
79
+ index.version === undefined ? undefined : 'version',
80
+ index.schemas === undefined ? undefined : 'schemas',
81
+ index.runtime?.files === undefined ? undefined : 'runtime.files',
82
+ index.runtime?.lines === undefined ? undefined : 'runtime.lines',
83
+ index.runtime === null || !Object.hasOwn(index.runtime, 'trust') ? undefined : 'runtime.trust',
84
+ ].filter((field): field is string => field !== undefined);
85
+ }
86
+ /** Hold each envelope to its own fields: the legacy one keeps every field its readers require, 0.1.0.2 carries none. */
87
+ // oxlint-disable-next-line typescript/prefer-readonly-parameter-types -- valibot output, only read
88
+ function checkIndexEnvelope(index: OutputIndex): void {
89
+ const carried = legacyIndexFields(index);
90
+ if (index.formatVersion !== LEGACY_LAYOUT) {
91
+ if (carried.length > 0) {
92
+ throw new Error(`Format ${index.formatVersion} drops ${carried.join(', ')} (shard.json)`);
93
+ }
94
+ return;
95
+ }
96
+ const needed = ['version', 'schemas', ...index.runtime === null ? [] : ['runtime.files', 'runtime.lines']];
97
+ const missing = needed.filter((field: string): boolean => !carried.includes(field));
98
+ if (missing.length > 0) {
99
+ throw new Error(`Legacy shard.json (formatVersion 2) needs ${missing.join(', ')}`);
100
+ }
101
+ }
66
102
  function parseOutputIndexRows(input: unknown): OutputIndex {
67
103
  const index = v.parse(OutputIndexSchema, input);
104
+ checkIndexEnvelope(index);
68
105
  if (index.sdk === '0.3' && index.cook === undefined) { throw new Error(`Missing cook preparation: run wildshard prepare <folder> --base <exact-preview-url> (${index.identity.slug})`); }
69
106
  if (index.sdk === '0.3' && index.cook !== undefined && index.cook.bytes > MAX_COOK_BYTES) { throw new Error('Cook preparation exceeds byte cap'); }
70
107
  const paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
@@ -76,7 +113,7 @@ function parseOutputIndexRows(input: unknown): OutputIndex {
76
113
  }
77
114
  }
78
115
  if (index.sections.reduce((total, entry) => total + entry.bytes, 0) > limits.sourceBytes) throw new Error('Output sections exceed the source byte cap');
79
- for (const entry of [...index.sections, ...index.schemas, ...index.files, ...index.runtime?.files ?? []]) {
116
+ for (const entry of [...index.sections, ...index.schemas ?? [], ...index.files, ...index.runtime?.files ?? []]) {
80
117
  if (entry.path.split('/').some(part => part === '.' || part === '..') || paths.has(entry.path)) throw new Error('Duplicate or escaping output path');
81
118
  paths.add(entry.path);
82
119
  }
@@ -108,7 +145,7 @@ function parseOutputIndexRows(input: unknown): OutputIndex {
108
145
  }
109
146
  if (!serverFilesExclusive(index.admission.server ?? [], index.files)) throw new Error('A server file is never also a client file');
110
147
  // I5: a pack lives beside the blobs, is listed once, and holds only listed members at their exact sizes, in order
111
- const members = new Map([...index.sections, ...index.schemas].map(entry => [entry.hash, entry.bytes] as const));
148
+ const members = new Map([...index.sections, ...index.schemas ?? []].map(entry => [entry.hash, entry.bytes] as const));
112
149
  for (const entry of index.files) members.set(entry.hash, entry.compressed);
113
150
  for (const pack of index.packs ?? []) {
114
151
  if (pack.path !== `blobs/pack/${pack.hash}.pack` || paths.has(pack.path)) throw new Error('Duplicate or mismatched pack path');
@@ -160,9 +197,9 @@ export function assembleOutputShardfile(input: unknown, sections: ReadonlyMap<st
160
197
  /** Exact admitted data, independent of validator implementation metadata. */
161
198
  interface OutputIndexRowsInputFields {
162
199
  format: "wildshard.shardfile";
163
- formatVersion: 2;
200
+ formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
164
201
  sdk: "0.2" | "0.3";
165
- version: ShardfileVersion;
202
+ version?: LegacyIndexVersion;
166
203
  identity: ShardIdentityInput;
167
204
  build: {
168
205
  sourceHash: string;
@@ -187,7 +224,7 @@ interface OutputIndexRowsInputFields {
187
224
  hash: string;
188
225
  bytes: number;
189
226
  }[];
190
- schemas: {
227
+ schemas?: {
191
228
  path: string;
192
229
  hash: string;
193
230
  bytes: number;
@@ -226,13 +263,13 @@ interface OutputIndexRowsInputFields {
226
263
  } | undefined;
227
264
  runtime: {
228
265
  trust?: unknown;
229
- files: {
266
+ files?: {
230
267
  lines: number;
231
268
  path: string;
232
269
  hash: string;
233
270
  bytes: number;
234
271
  }[];
235
- lines: 0;
272
+ lines?: 0;
236
273
  kind: "client-plan";
237
274
  cost: {
238
275
  imagesFirst?: {
@@ -258,9 +295,9 @@ interface OutputIndexRowsInputFields {
258
295
  export type OutputIndexRowsInput = { [Key in keyof OutputIndexRowsInputFields]: OutputIndexRowsInputFields[Key] };
259
296
  interface OutputIndexRowsFields {
260
297
  format: "wildshard.shardfile";
261
- formatVersion: 2;
298
+ formatVersion: typeof LEGACY_LAYOUT | IndexFormatVersion;
262
299
  sdk: "0.2" | "0.3";
263
- version: ShardfileVersion;
300
+ version?: LegacyIndexVersion;
264
301
  identity: ShardIdentity;
265
302
  build: {
266
303
  sourceHash: string;
@@ -285,7 +322,7 @@ interface OutputIndexRowsFields {
285
322
  hash: string;
286
323
  bytes: number;
287
324
  }[];
288
- schemas: {
325
+ schemas?: {
289
326
  path: string;
290
327
  hash: string;
291
328
  bytes: number;
@@ -324,13 +361,13 @@ interface OutputIndexRowsFields {
324
361
  } | undefined;
325
362
  runtime: {
326
363
  trust?: unknown;
327
- files: {
364
+ files?: {
328
365
  lines: number;
329
366
  path: string;
330
367
  hash: string;
331
368
  bytes: number;
332
369
  }[];
333
- lines: 0;
370
+ lines?: 0;
334
371
  kind: "client-plan";
335
372
  cost: {
336
373
  imagesFirst?: {
@@ -15,7 +15,8 @@ interface Listed {
15
15
  }
16
16
  interface Members {
17
17
  readonly sections: readonly Listed[]
18
- readonly schemas: readonly Listed[]
18
+ /** Absent from format 0.1.0.2 on (FORMAT-PRUNE FP4). */
19
+ readonly schemas?: readonly Listed[] | undefined
19
20
  readonly files: readonly Listed[]
20
21
  }
21
22
  type Assets = ReadonlyMap<string, Uint8Array>
@@ -123,7 +124,7 @@ function packFromMembers(
123
124
  index: Members,
124
125
  read: ReadFile,
125
126
  ): Uint8Array {
126
- const rows = [...index.sections, ...index.schemas, ...index.files]
127
+ const rows = [...index.sections, ...(index.schemas ?? []), ...index.files]
127
128
  const paths = new Map(
128
129
  rows.map((row: Listed): [string, string] => [row.hash, row.path]),
129
130
  )
@@ -38,7 +38,7 @@ function memberPaths(
38
38
  index: OutputIndex,
39
39
  ): ReadonlyMap<string, string> {
40
40
  return new Map(
41
- [...index.sections, ...index.schemas, ...index.files].map(
41
+ [...index.sections, ...(index.schemas ?? []), ...index.files].map(
42
42
  (row: Readonly<{ hash: string; path: string }>): [string, string] => [
43
43
  row.hash,
44
44
  row.path,
@@ -3,7 +3,7 @@ import { assertMigrationCompatibility } from './migrations.ts';
3
3
  import { StateSchema } from './state.ts';
4
4
  import type { Shardfile } from './shardSchema.ts';
5
5
  import { isJsonDataWithFileSchemas } from './json.ts';
6
- import { SHARDFILE_VERSIONS } from './version.ts';
6
+ import { IndexFormatVersionSchema, LegacyIndexVersionSchema } from './index-format-version.ts';
7
7
  import { SHARDFILE_ADMISSION_LIMITS as limits } from './admissionLimits.ts';
8
8
 
9
9
  const identity = v.object({ slug: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9.-]*$/u)),
@@ -16,11 +16,13 @@ export function parseStateLineage(input: unknown): StateLineage { return v.parse
16
16
  const path = v.pipe(v.string(), v.maxLength(240), v.regex(/^(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/u));
17
17
  const measured = { path, hash: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/u)),
18
18
  bytes: v.pipe(v.number(), v.integer(), v.minValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)) };
19
- const inventory = v.object({ format: v.literal('wildshard.shardfile'), formatVersion: v.literal(2), sdk: v.picklist(['0.2', '0.3']),
20
- version: v.picklist(SHARDFILE_VERSIONS), identity,
19
+ const lineageSchemas = v.exactOptional(v.pipe(v.array(v.strictObject(measured)), v.maxLength(128)));
20
+ // SHARD-COMPAT CP14: either envelope; 0.1.0.2 names its format in formatVersion and drops version and schemas.
21
+ const inventory = v.object({ format: v.literal('wildshard.shardfile'), formatVersion: IndexFormatVersionSchema, sdk: v.picklist(['0.2', '0.3']),
22
+ version: LegacyIndexVersionSchema, identity,
21
23
  sections: v.pipe(v.array(v.strictObject({ ...measured, name: v.pipe(v.string(), v.regex(/^[a-z][a-zA-Z0-9-]*\/[a-zA-Z][a-zA-Z0-9_-]*$/u)),
22
24
  schema: v.pipe(v.string(), v.maxLength(240)) })), v.maxLength(256)),
23
- schemas: v.pipe(v.array(v.strictObject(measured)), v.maxLength(128)) });
25
+ schemas: lineageSchemas });
24
26
  export interface OutputLineageIndex {
25
27
  readonly identity: { readonly slug: string; readonly revision: number };
26
28
  readonly sections: readonly { readonly path: string; readonly hash: string; readonly bytes: number; readonly name: string; readonly schema: string }[];
@@ -30,7 +32,8 @@ export interface OutputLineageIndex {
30
32
  * Obsolete host/asset declarations are never parsed or admitted by this reader. */
31
33
  export function parseOutputLineageIndex(input: unknown): OutputLineageIndex {
32
34
  if (!isJsonDataWithFileSchemas(input)) throw new Error('Shardfile descriptor requires bounded plain JSON');
33
- const index = v.parse(inventory, input), paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
35
+ const parsed = v.parse(inventory, input), paths = new Set(['shard.json', 'validation.json']), names = new Set<string>();
36
+ const index = { ...parsed, schemas: parsed.schemas ?? [] };
34
37
  if (index.sections.reduce((total, row) => total + row.bytes, 0) > limits.sourceBytes) throw new Error('Output sections exceed the source byte cap');
35
38
  for (const row of [...index.sections, ...index.schemas]) {
36
39
  if (row.path.split('/').some(part => part === '.' || part === '..') || paths.has(row.path)) throw new Error('Duplicate or escaping output path');
@@ -3,14 +3,30 @@
3
3
  const ZERO = 0
4
4
  const ONE = 1
5
5
 
6
- const SHARDFILE_VERSION = '0.1.0.1'
7
- /** Legacy 0.1 is the byte-preserving spelling of 0.1.0.0. */
8
- const SHARDFILE_VERSIONS: readonly [
6
+ const SHARDFILE_VERSION = '0.1.0.2'
7
+ /** Formats whose `shard.json` names its version in `version`, beside the frozen layout marker `formatVersion: 2`.
8
+ * Legacy 0.1 is the byte-preserving spelling of 0.1.0.0. */
9
+ const LEGACY_INDEX_VERSIONS: readonly ['0.1', '0.1.0.0', '0.1.0.1'] = [
9
10
  '0.1',
10
11
  '0.1.0.0',
11
- typeof SHARDFILE_VERSION,
12
- ] = ['0.1', '0.1.0.0', SHARDFILE_VERSION] as const
12
+ '0.1.0.1',
13
+ ] as const
14
+ /** Formats whose `shard.json` names its version in `formatVersion` (SHARD-COMPAT CP14, FORMAT-PRUNE FP25): the
15
+ * layout marker and `version` are gone, so a reader tells the two envelopes apart by the field's type. */
16
+ const INDEX_FORMAT_VERSIONS: readonly [typeof SHARDFILE_VERSION] = [
17
+ SHARDFILE_VERSION,
18
+ ] as const
19
+ const SHARDFILE_VERSIONS: readonly [
20
+ ...typeof LEGACY_INDEX_VERSIONS,
21
+ ...typeof INDEX_FORMAT_VERSIONS,
22
+ ] = [...LEGACY_INDEX_VERSIONS, ...INDEX_FORMAT_VERSIONS] as const
13
23
  type ShardfileVersion = (typeof SHARDFILE_VERSIONS)[number]
24
+ type LegacyIndexVersion = (typeof LEGACY_INDEX_VERSIONS)[number]
25
+ type IndexFormatVersion = (typeof INDEX_FORMAT_VERSIONS)[number]
26
+ /** The frozen layout marker the legacy envelope carries in `formatVersion`. */
27
+ const LEGACY_LAYOUT = 2
28
+ /** The first format that writes its version in `formatVersion`. */
29
+ const SHARDFILE_VERSION_INDEX_RENAME = '0.1.0.2'
14
30
  type ShardfileVersionParts = readonly [number, number, number, number]
15
31
 
16
32
  /** Read canonical bounded decimal components; the legacy two-part spelling has zero counters. */
@@ -67,9 +83,88 @@ function compatibleShardfileVersion(
67
83
  }
68
84
  }
69
85
 
86
+ /** The format version a `shard.json` declares: `formatVersion` when it is a version string (0.1.0.2 on), else the
87
+ * legacy `version` beside the layout marker `formatVersion: 2`. Throws when neither names a format. */
88
+ function shardfileFormatOf(index: unknown): ShardfileVersion {
89
+ const declared: unknown =
90
+ typeof index === 'object' && index !== null
91
+ ? Reflect.get(index, 'formatVersion')
92
+ : undefined
93
+ const legacy: unknown =
94
+ typeof index === 'object' && index !== null
95
+ ? Reflect.get(index, 'version')
96
+ : undefined
97
+ const found: unknown = declared === LEGACY_LAYOUT ? legacy : declared
98
+ const known = SHARDFILE_VERSIONS.find(
99
+ (version: string): boolean => version === found,
100
+ )
101
+ if (known === undefined) {
102
+ throw new Error('Shardfile index names no known format version')
103
+ }
104
+ return known
105
+ }
106
+
107
+ /** Whether a format version writes the 0.1.0.2 envelope (`formatVersion` as the version, no `version`). */
108
+ function writesIndexFormatVersion(version: string): boolean {
109
+ return (
110
+ compareShardfileVersions(version, SHARDFILE_VERSION_INDEX_RENAME) >= ZERO
111
+ )
112
+ }
113
+
114
+ /** A copy of a JSON object without `keys`; anything else as it is. */
115
+ function withoutKeys(value: unknown, keys: readonly string[]): unknown {
116
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
117
+ return value
118
+ }
119
+ return Object.fromEntries(
120
+ Object.entries(value).filter(
121
+ ([key]: readonly [string, unknown]): boolean => !keys.includes(key),
122
+ ),
123
+ )
124
+ }
125
+
126
+ /** The rows `outputIndexEnvelope` returns: the writer's own rows, typed so it keeps reading them, with `version` and
127
+ * `schemas` possibly gone and `formatVersion` possibly the version string. */
128
+ type IndexEnvelope<Rows> = Omit<Rows, 'formatVersion' | 'schemas' | 'version'> &
129
+ Readonly<{
130
+ formatVersion: unknown
131
+ version?: unknown
132
+ schemas?: unknown
133
+ }>
134
+
135
+ /** SHARD-COMPAT CP14: writers build the legacy `shard.json` rows (`formatVersion: 2`, `version`, the always-empty lists)
136
+ * and pass them here. At a `version` of 0.1.0.2 or later this returns the envelope that version writes: `formatVersion`
137
+ * is the version, and `version`, `schemas`, `runtime.files`, `runtime.lines` and `runtime.trust` go. An older
138
+ * `version` comes back unchanged. */
139
+ function outputIndexEnvelope<Rows extends Readonly<Record<string, unknown>>>(
140
+ rows: Rows,
141
+ ): IndexEnvelope<Rows> {
142
+ const { version } = rows
143
+ const { version: _version, schemas: _schemas, ...rest } = rows
144
+ const envelope: Record<string, unknown> =
145
+ typeof version !== 'string' || !writesIndexFormatVersion(version)
146
+ ? { ...rows }
147
+ : {
148
+ ...rest,
149
+ formatVersion: version,
150
+ runtime: withoutKeys(rest['runtime'], ['files', 'lines', 'trust']),
151
+ }
152
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the writer's own rows; only envelope fields change
153
+ return envelope as IndexEnvelope<Rows>
154
+ }
155
+
70
156
  export {
157
+ outputIndexEnvelope,
158
+ type IndexEnvelope,
71
159
  SHARDFILE_VERSION,
72
160
  SHARDFILE_VERSIONS,
161
+ LEGACY_INDEX_VERSIONS,
162
+ INDEX_FORMAT_VERSIONS,
163
+ LEGACY_LAYOUT,
164
+ type LegacyIndexVersion,
165
+ type IndexFormatVersion,
166
+ shardfileFormatOf,
167
+ writesIndexFormatVersion,
73
168
  SHARDFILE_FLOOR,
74
169
  type ShardfileVersion,
75
170
  type ShardfileVersionParts,