@wildshard/shard-format 0.69.2 → 0.71.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 (73) hide show
  1. package/package.json +21 -3
  2. package/src/cli/corpus-candidate.ts +228 -0
  3. package/src/cli/corpus-command.ts +67 -0
  4. package/src/cli/corpus-pins.ts +73 -0
  5. package/src/cli/corpus-report.ts +36 -0
  6. package/src/cli/corpus-tar.ts +28 -0
  7. package/src/cli/corpus-usage.ts +106 -0
  8. package/src/cli/corpus.ts +50 -68
  9. package/src/cli/format-diff-data.ts +89 -0
  10. package/src/cli/format-diff-lock.ts +122 -0
  11. package/src/cli/format-diff-normal.ts +300 -0
  12. package/src/cli/format-diff-paths.ts +103 -0
  13. package/src/cli/format-diff-range.ts +112 -0
  14. package/src/cli/format-diff-report.ts +30 -0
  15. package/src/cli/format-diff-rules.ts +232 -0
  16. package/src/cli/format-diff.ts +226 -0
  17. package/src/cli/main.ts +81 -32
  18. package/src/cli/pack.ts +20 -3
  19. package/src/cli/validate.ts +1 -1
  20. package/src/format/clientOwnership.ts +1 -1
  21. package/src/format/clientTrails.ts +121 -46
  22. package/src/format/cook-data.ts +22 -3
  23. package/src/format/cook-deprecations.ts +53 -0
  24. package/src/format/cook-preparation.ts +105 -70
  25. package/src/format/creature-rest-rig.ts +248 -0
  26. package/src/format/creature-skin-bounds.ts +146 -0
  27. package/src/format/deprecations.ts +30 -21
  28. package/src/format/edge-observations.ts +67 -0
  29. package/src/format/empty-shardfile.ts +4 -2
  30. package/src/format/entry-read-set.ts +147 -0
  31. package/src/format/format-migrate-rebuild.ts +4 -1
  32. package/src/format/format-migrate.ts +10 -5
  33. package/src/format/format-migration-envelope.ts +40 -0
  34. package/src/format/format-migration-prune.ts +42 -1
  35. package/src/format/format-migrations.ts +10 -1
  36. package/src/format/format-window.ts +71 -0
  37. package/src/format/immutable.ts +4 -1
  38. package/src/format/json-schema.ts +1468 -0
  39. package/src/format/lootEconomy.ts +4 -1
  40. package/src/format/mat4.ts +225 -0
  41. package/src/format/memory-armed.json +1 -9
  42. package/src/format/memory-armed.ts +46 -17
  43. package/src/format/memory-epoch.ts +10 -3
  44. package/src/format/memory-line.ts +17 -6
  45. package/src/format/outputFields.ts +3 -2
  46. package/src/format/outputIndex.ts +41 -6
  47. package/src/format/platformDataSections.ts +5 -0
  48. package/src/format/platformFileFamilies.ts +3 -3
  49. package/src/format/play-area.ts +95 -0
  50. package/src/format/policy-verdict.ts +12 -2
  51. package/src/format/preparation-checks.ts +100 -0
  52. package/src/format/preparation-spec.ts +45 -0
  53. package/src/format/registeredJson.ts +2 -2
  54. package/src/format/runtime-tier.ts +14 -7
  55. package/src/format/save-revision.ts +105 -0
  56. package/src/format/schema-source.ts +70 -0
  57. package/src/format/sections.ts +4 -1
  58. package/src/format/server-plan.ts +42 -0
  59. package/src/format/server-reads.ts +23 -0
  60. package/src/format/shardSchema.ts +9 -4
  61. package/src/format/shardSections.ts +17 -7
  62. package/src/format/shardfile-assets.ts +5 -5
  63. package/src/format/shardfile-stream-admit.ts +19 -10
  64. package/src/format/shardfile-stream-facts.ts +2 -1
  65. package/src/format/shardfile-stream.ts +2 -3
  66. package/src/format/shardfileValidation.ts +16 -9
  67. package/src/format/species-deprecations.ts +79 -0
  68. package/src/format/stateLineage.ts +15 -7
  69. package/src/format/tread-boxes.ts +65 -0
  70. package/src/format/vehicle-hulls.ts +124 -0
  71. package/src/format/version.ts +96 -10
  72. package/src/format/whole-inputs.ts +51 -0
  73. package/src/tools/runtime-hosts.json +4 -0
@@ -0,0 +1,147 @@
1
+ /* oxlint-disable complexity, curly, max-lines-per-function, max-params, max-statements, no-continue, no-magic-numbers, sort-vars, typescript/explicit-function-return-type, typescript/prefer-readonly-parameter-types -- moved verbatim from engine (SHARD-COMPAT PR6e), so the cook's entry set stays the same set byte for byte */
2
+ // SHARD-COMPAT PR6e (J487): which files a tier reads before control, a rule over the shard, its index and its
3
+ // sections, so the cook, the client's totals and any tool compute one set without engine code. Moved verbatim
4
+ // from engine `src/cook/game/entryReadSet.ts`.
5
+ import { controlFileHashes } from './admissionControl.ts'
6
+ import { spawnViewSceneFiles } from './spawnView.ts'
7
+ import { entryFileSteps, tierLibrarySteps } from './tierSelection.ts'
8
+ import { otherTierSplatFiles, wholeGeometryInputs } from './whole-inputs.ts'
9
+
10
+ import type { OutputIndex } from './outputIndex.ts'
11
+ import type { Shardfile } from './shardSchema.ts'
12
+
13
+ /** The same required, active entry selection for totals and read-ahead. Default (the Shardfile path every player gets):
14
+ * today's entry set; streamed/late-only bodies and the other device's variants are not entry IO. `whole` (DL5, G872:
15
+ * "no deferring level content past control"; read only with Debug > Level download > Runtime packs until a memory
16
+ * reading backs it): the whole level on this tier, every byte its play can load, resident at control. */
17
+ export function entryReadSet(
18
+ source: Shardfile,
19
+ tier: 'phone' | 'desktop',
20
+ index: Pick<OutputIndex, 'files' | 'sections' | 'schemas'>,
21
+ sections: ReadonlyMap<string, unknown>,
22
+ whole = false,
23
+ fence: ReadonlySet<string> = new Set(),
24
+ ): ReadonlySet<string> {
25
+ const required = controlFileHashes(source),
26
+ steps = entryFileSteps(source, tier, { index, sections })
27
+ let turn = steps.next()
28
+ while (turn.done !== true) turn = steps.next()
29
+ const wanted = new Set(
30
+ [...index.sections, ...(index.schemas ?? [])].map(row => row.hash),
31
+ )
32
+ // `turn.value` is what this tier streams after control today: still required, so the whole level keeps it.
33
+ for (const file of index.files)
34
+ if (
35
+ required.has(file.hash) &&
36
+ (whole
37
+ ? file.tier === undefined || file.tier === tier
38
+ : !turn.value.has(file.hash))
39
+ )
40
+ wanted.add(file.hash)
41
+ // `late` only schedules a library member after control (controlFileHashes leaves it out); the level still loads it
42
+ // in play. Tile streaming loads every tile of the tier (every LOD) as the player moves; control requires none.
43
+ const late = new Set((source.late ?? []).map(row => row.hash)),
44
+ byHash = new Map(source.files.map(file => [file.hash, file]))
45
+ const tileFiles = whole
46
+ ? source.tiles.flatMap(tile =>
47
+ tile.files.map(ref => ref.replace(/^commons:/u, '')),
48
+ )
49
+ : []
50
+ const tierOf = new Map(index.files.map(file => [file.hash, file.tier])),
51
+ seen = new Set<string>()
52
+ // DL21: the spawn-view fence attaches a tiled scene library's chunks within its reach before control, `late` or not
53
+ // (Nine's native-slabs: 8 files a cold visit fetched one by one inside the fence, none in this set), so the default
54
+ // set carries them and they download with the rest, in parallel and counted.
55
+ // DL22: and the files a recorded cold boot read before control (`fence`, the shard's fence-reads.json mapped to this
56
+ // product's hashes): late models and props tiles the setup steps fetch on demand. A recorded read is a fact, so it
57
+ // passes the tier check: Driftwood's phone reads 46 `models/fixed/` files tagged desktop, and left out they read loose.
58
+ const pending = whole
59
+ ? [...source.library.filter(hash => late.has(hash)), ...tileFiles]
60
+ : [...spawnViewSceneFiles(sections), ...fence]
61
+ while (pending.length > 0) {
62
+ const hash = pending.pop()
63
+ if (hash === undefined || seen.has(hash)) continue
64
+ seen.add(hash)
65
+ pending.push(...(byHash.get(hash)?.dependencies ?? []))
66
+ const fileTier = tierOf.get(hash)
67
+ if (
68
+ tierOf.has(hash) &&
69
+ (fileTier === undefined || fileTier === tier || fence.has(hash))
70
+ )
71
+ wanted.add(hash)
72
+ }
73
+ if (whole) {
74
+ // The other device's payloads and the variants this tier never fetches: tier selection's own verdict (named
75
+ // desktop files, the smaller texture-mode alternatives, the other tier's horizons and scene models), sp-o1's census.
76
+ const library = tierLibrarySteps(source, tier, { index, sections })
77
+ let step = library.next()
78
+ while (step.done !== true) step = library.next()
79
+ for (const hash of step.value) wanted.delete(hash)
80
+ // Per-tier tables, `{phone: X, desktop: Y}` (cover cells, scene model files, held decals, lent atlases, Explorer
81
+ // books): their loaders read `[TIER]`, so a file named only as the other tier's value is never read on this one.
82
+ const other = tier === 'phone' ? 'desktop' : 'phone',
83
+ otherOnly = new Set<string>(),
84
+ elsewhere = new Set<string>()
85
+ const walk = (value: unknown, skip: boolean): void => {
86
+ if (typeof value === 'string') {
87
+ ;(skip ? otherOnly : elsewhere).add(value)
88
+ return
89
+ }
90
+ if (Array.isArray(value)) {
91
+ for (const item of value) walk(item, skip)
92
+ return
93
+ }
94
+ if (typeof value !== 'object' || value === null) return
95
+ const table = 'phone' in value && 'desktop' in value
96
+ for (const [key, item] of Object.entries(value))
97
+ walk(item, skip || (table && key === other))
98
+ }
99
+ for (const value of sections.values()) walk(value, false)
100
+ const hashOf = new Map(
101
+ index.files.flatMap(
102
+ file =>
103
+ [
104
+ [file.hash, file.hash],
105
+ [file.path, file.hash],
106
+ ...(file.name === undefined
107
+ ? []
108
+ : [[file.name, file.hash] as const]),
109
+ ] as const,
110
+ ),
111
+ )
112
+ const kept = new Set<string>()
113
+ for (const name of elsewhere) {
114
+ const hash = hashOf.get(name)
115
+ if (hash !== undefined) kept.add(hash)
116
+ }
117
+ const needed = new Set(
118
+ [...wanted].flatMap(hash => byHash.get(hash)?.dependencies ?? []),
119
+ )
120
+ for (const name of otherOnly) {
121
+ const hash = hashOf.get(name)
122
+ if (hash !== undefined && !kept.has(hash) && !needed.has(hash))
123
+ wanted.delete(hash)
124
+ }
125
+ }
126
+ for (const hash of otherTierSplatFiles(source, tier)) wanted.delete(hash)
127
+ const plan = sections.get('client/plan'),
128
+ features: unknown =
129
+ typeof plan === 'object' && plan !== null
130
+ ? Reflect.get(plan, 'features')
131
+ : undefined
132
+ // This host starts its complete native intake before construction. These
133
+ // are actual mandatory reads, even when a tile is outside the spawn view.
134
+ if (
135
+ Array.isArray(features) &&
136
+ features.some(
137
+ (row: unknown) =>
138
+ typeof row === 'object' &&
139
+ row !== null &&
140
+ Reflect.get(row, 'kind') === 'world.assembly' &&
141
+ typeof Reflect.get(row, 'library') === 'string',
142
+ )
143
+ ) {
144
+ for (const hash of wholeGeometryInputs(source.props, true)) wanted.add(hash)
145
+ }
146
+ return wanted
147
+ }
@@ -12,6 +12,7 @@ import {
12
12
  rows,
13
13
  } from './format-migrate-inventory.ts'
14
14
  import { assembleOutputShardfile } from './outputIndex.ts'
15
+ import { asWrittenIdentity } from './save-revision.ts'
15
16
  import { validationSourceBytes } from './validationReceipt.ts'
16
17
 
17
18
  import type { Hash, JsonRecord, Listed } from './format-migrate-inventory.ts'
@@ -165,7 +166,9 @@ function rebuildSourceHash(
165
166
  ): void {
166
167
  const source = assembleOutputShardfile(copy.index, shard.sections)
167
168
  record(copy.index['build'], 'build')['sourceHash'] = copy.hash(
168
- validationSourceBytes(source),
169
+ validationSourceBytes(
170
+ asWrittenIdentity(source, copy.index['formatVersion']),
171
+ ),
169
172
  )
170
173
  }
171
174
 
@@ -5,7 +5,7 @@
5
5
  * It is deterministic (canonical JSON, no clock, network or randomness), always starts from the original, and twice
6
6
  * equals once. */
7
7
  import { readCookData } from './cook-data.ts'
8
- import { requireCookPreparation } from './cook-preparation.ts'
8
+ import { isPreparedCook, requireCookPreparation } from './cook-preparation.ts'
9
9
  import {
10
10
  INDEX,
11
11
  RECEIPT,
@@ -50,6 +50,8 @@ interface MigrateOptions {
50
50
  readonly to?: string
51
51
  /** The steps to run; the registry by default (tests inject their own). */
52
52
  readonly migrations?: readonly FormatMigration[]
53
+ /** FE11: called after each step with the shard as that step left it (the per-step goldens). */
54
+ readonly onStep?: (id: string, shard: Readonly<MigratingShard>) => void
53
55
  }
54
56
 
55
57
  interface MigratedShardfile {
@@ -77,7 +79,6 @@ interface Admitted {
77
79
  }
78
80
 
79
81
  const RUNNER = 1
80
- const PREPARED = 3
81
82
  const NONE = 0
82
83
 
83
84
  function chainId(migrations: readonly FormatMigration[], hash: Hash): string {
@@ -155,10 +156,12 @@ function rendersAgain(steps: readonly FormatMigration[]): boolean {
155
156
  function runSteps(
156
157
  shard: MigratingShard,
157
158
  steps: readonly FormatMigration[],
159
+ onStep: MigrateOptions['onStep'],
158
160
  ): void {
159
161
  for (const step of steps) {
160
162
  step.apply(shard)
161
163
  writeShardfileFormat(shard.index, step.to)
164
+ onStep?.(step.id, shard)
162
165
  }
163
166
  }
164
167
 
@@ -189,6 +192,7 @@ function writeCopy(
189
192
  mountText: ReadonlyMap<string, string>
190
193
  steps: readonly FormatMigration[]
191
194
  hash: Hash
195
+ onStep: MigrateOptions['onStep']
192
196
  }>,
193
197
  ): Map<string, Uint8Array> {
194
198
  const { index } = shard
@@ -201,7 +205,7 @@ function writeCopy(
201
205
  (row: Readonly<{ path: string }>): string => row.path,
202
206
  ),
203
207
  ])
204
- runSteps(shard, plan.steps)
208
+ runSteps(shard, plan.steps, plan.onStep)
205
209
  const out = new Map(
206
210
  [...files].filter(
207
211
  ([path]: readonly [string, Uint8Array]): boolean => !gone.has(path),
@@ -210,7 +214,7 @@ function writeCopy(
210
214
  const copy = { index, out, hash: plan.hash }
211
215
  rebuildInventory(copy, shard, {
212
216
  mountText,
213
- reseal: cook?.version === PREPARED && !rendersAgain(plan.steps),
217
+ reseal: isPreparedCook(cook) && !rendersAgain(plan.steps),
214
218
  })
215
219
  copy.out.set(INDEX, validationSourceBytes(index))
216
220
  return copy.out
@@ -220,7 +224,7 @@ function preparationOf(
220
224
  cook: Readonly<CookData> | undefined,
221
225
  steps: readonly FormatMigration[],
222
226
  ): MigratedShardfile['preparation'] {
223
- if (cook?.version !== PREPARED) {
227
+ if (!isPreparedCook(cook)) {
224
228
  return 'none'
225
229
  }
226
230
  return rendersAgain(steps) ? 'stale' : 'author'
@@ -254,6 +258,7 @@ function migrateShardfile(
254
258
  mountText,
255
259
  steps,
256
260
  hash: options.hash,
261
+ onStep: options.onStep,
257
262
  })
258
263
  return {
259
264
  files: copy,
@@ -3,6 +3,7 @@
3
3
  * version into `formatVersion` from 0.1.0.2 on (`writeShardfileFormat`), replacing the frozen layout marker `2`; these
4
4
  * steps drop the fields the new envelope no longer carries. Every dropped field held nothing: `version` repeats the
5
5
  * format version, and the other four are always empty with no reader. */
6
+ import { LEGACY_PREPARATION_SPEC, PREPARED_SDK } from './preparation-spec.ts'
6
7
  import { LEGACY_LAYOUT, writesIndexFormatVersion } from './version.ts'
7
8
 
8
9
  import type { FormatMigration, MigratingShard } from './format-migrations.ts'
@@ -10,6 +11,8 @@ import type { FormatMigration, MigratingShard } from './format-migrations.ts'
10
11
  type JsonRecord = Record<string, unknown>
11
12
 
12
13
  const ENVELOPE = '0.1.0.2'
14
+ const PREPARATION_MARKER = '0.1.0.3'
15
+ const SAVE_REVISION = '0.1.0.4'
13
16
 
14
17
  function isRecord(value: unknown): value is JsonRecord {
15
18
  return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -44,6 +47,41 @@ const dropEmptyIndexFields: FormatMigration = {
44
47
  },
45
48
  }
46
49
 
50
+ /** SHARD-COMPAT PR4 (J487, FORMAT-PRUNE FP5 folded in): the `sdk` marker becomes `preparation`, the spec version the
51
+ * file was prepared to. `'0.3'` (prepared) is spec 3, the only spec that marker ever meant; `'0.2'` (built, not
52
+ * prepared) leaves no field. Data only: the copy's `cook.json` stays spec 3 and its input hash is re-sealed over the
53
+ * new index. */
54
+ const preparationMarker: FormatMigration = {
55
+ id: 'pr4-preparation-marker',
56
+ to: PREPARATION_MARKER,
57
+ touches: 'data',
58
+ affects: [],
59
+ apply: (shard: MigratingShard): void => {
60
+ const { index } = shard
61
+ if (index['sdk'] === PREPARED_SDK) {
62
+ index['preparation'] = LEGACY_PREPARATION_SPEC
63
+ }
64
+ Reflect.deleteProperty(index, 'sdk')
65
+ },
66
+ }
67
+
68
+ /** FORMAT-PRUNE FP26 (J493): the save lineage `identity.revision` is spelled `identity.saveRevision`. Data only: the
69
+ * number is kept, so every save keyed by it still matches. */
70
+ const saveRevisionName: FormatMigration = {
71
+ id: 'fp26-save-revision',
72
+ to: SAVE_REVISION,
73
+ touches: 'data',
74
+ affects: [],
75
+ apply: (shard: MigratingShard): void => {
76
+ const { identity } = shard.index
77
+ if (!isRecord(identity) || !Object.hasOwn(identity, 'revision')) {
78
+ return
79
+ }
80
+ identity['saveRevision'] = identity['revision']
81
+ Reflect.deleteProperty(identity, 'revision')
82
+ },
83
+ }
84
+
47
85
  /** The format version a `shard.json` declares, as written, or `undefined`: `formatVersion` from 0.1.0.2, else the
48
86
  * legacy `version` beside the layout marker. */
49
87
  function declaredShardfileFormat(index: Readonly<JsonRecord>): unknown {
@@ -68,5 +106,7 @@ export {
68
106
  declaredShardfileFormat,
69
107
  dropEmptyIndexFields,
70
108
  formatVersionField,
109
+ preparationMarker,
110
+ saveRevisionName,
71
111
  writeShardfileFormat,
72
112
  }
@@ -2,6 +2,8 @@
2
2
  /** FORMAT-PRUNE's same-version chain steps (J486): each writes the one way a 0.1.0.1 reader already admits, so writers
3
3
  * can stop writing the other way with no format bump. Both are repairs: they also run on 0.1.0.1 files that still carry
4
4
  * the old shape. Refusing the old shape in new uploads waits until the API and engine read migrated copies (CP2, FE9). */
5
+ import { RETIRED_SCHEMA_SOURCES, retiredSchemaSource } from './schema-source.ts'
6
+
5
7
  import type { FormatMigration, MigratingShard } from './format-migrations.ts'
6
8
 
7
9
  type JsonRecord = Record<string, unknown>
@@ -10,6 +12,8 @@ const OLD_POINTER = 'gridShardfile'
10
12
  const POINTER = 'shardfile'
11
13
  const CURRENT = '0.1.0.1'
12
14
  const NONE = 0
15
+ /** FP10 runs at format 0.1.0.4, the format that first reads the current id. */
16
+ const SCHEMA_SOURCE_VERSION = '0.1.0.4'
13
17
 
14
18
  function isRecord(value: unknown): value is JsonRecord {
15
19
  return typeof value === 'object' && value !== null && !Array.isArray(value)
@@ -103,4 +107,41 @@ const dropRuntimeTrust: FormatMigration = {
103
107
  repairs: carriesTrust,
104
108
  }
105
109
 
106
- export { dropRuntimeTrust, shardfilePointer }
110
+ /** Each named JSON file's schema block in the index that names a retired id. */
111
+ function staleSchemaBlocks(
112
+ shard: Readonly<MigratingShard>,
113
+ ): readonly JsonRecord[] {
114
+ const { files } = shard.index
115
+ if (!Array.isArray(files)) {
116
+ return []
117
+ }
118
+ return files
119
+ .map((file: unknown): unknown =>
120
+ isRecord(file) ? file['jsonSchema'] : undefined,
121
+ )
122
+ .filter(
123
+ (block: unknown): block is JsonRecord =>
124
+ isRecord(block) && retiredSchemaSource(block['$comment']),
125
+ )
126
+ }
127
+
128
+ /** FORMAT-PRUNE FP10: a named JSON file's `jsonSchema.$comment` names the current defining module, not a retired
129
+ * one (`directorProduct` became `directorDocument`). Only the index changes; the file's bytes and hash stay. */
130
+ const schemaSource: FormatMigration = {
131
+ id: 'fp10-schema-source',
132
+ to: SCHEMA_SOURCE_VERSION,
133
+ touches: 'data',
134
+ affects: [],
135
+ apply: (shard: MigratingShard): void => {
136
+ for (const block of staleSchemaBlocks(shard)) {
137
+ const { $comment: old } = block
138
+ if (typeof old === 'string') {
139
+ block['$comment'] = RETIRED_SCHEMA_SOURCES[old]
140
+ }
141
+ }
142
+ },
143
+ repairs: (shard: Readonly<MigratingShard>): boolean =>
144
+ staleSchemaBlocks(shard).length > NONE,
145
+ }
146
+
147
+ export { dropRuntimeTrust, schemaSource, shardfilePointer }
@@ -5,9 +5,15 @@
5
5
  import {
6
6
  dropEmptyIndexFields,
7
7
  formatVersionField,
8
+ preparationMarker,
9
+ saveRevisionName,
8
10
  } from './format-migration-envelope.ts'
9
11
  import { journalGlyphImages } from './format-migration-journal.ts'
10
- import { dropRuntimeTrust, shardfilePointer } from './format-migration-prune.ts'
12
+ import {
13
+ dropRuntimeTrust,
14
+ schemaSource,
15
+ shardfilePointer,
16
+ } from './format-migration-prune.ts'
11
17
  import {
12
18
  SHARDFILE_VERSIONS,
13
19
  compareShardfileVersions,
@@ -71,6 +77,9 @@ const FORMAT_MIGRATIONS: readonly FormatMigration[] = [
71
77
  dropRuntimeTrust,
72
78
  formatVersionField,
73
79
  dropEmptyIndexFields,
80
+ preparationMarker,
81
+ saveRevisionName,
82
+ schemaSource,
74
83
  ]
75
84
 
76
85
  /** Whether a file at `version` still needs a step that writes `to`. The legacy two-part spelling sits just below its
@@ -0,0 +1,71 @@
1
+ /** SHARD-COMPAT CP2 (J486): a shard file outside the reader's window is refused with a typed error, before the
2
+ * index schema runs, so a reader (the API's admission) can answer "above: retry once I update" apart from "below the
3
+ * floor: migrate or re-upload" instead of an opaque schema error. */
4
+ import {
5
+ SHARDFILE_FLOOR,
6
+ SHARDFILE_VERSION,
7
+ compareShardfileVersions,
8
+ LEGACY_LAYOUT,
9
+ parseShardfileVersion,
10
+ } from './version.ts'
11
+
12
+ const NONE = 0
13
+
14
+ /** The declared format sits above the reader (a newer file) or below its floor. */
15
+ class ShardfileFormatWindowError extends Error {
16
+ public readonly declared: string
17
+ public readonly reader: string
18
+ public readonly floor: string
19
+ public readonly above: boolean
20
+
21
+ public constructor(declared: string, reader: string, above: boolean) {
22
+ super(
23
+ above
24
+ ? `shard.json is format ${declared}, above this reader's ${reader}: it is read once the reader updates`
25
+ : `shard.json is format ${declared}, below the floor ${SHARDFILE_FLOOR}: migrate it or upload it again`,
26
+ )
27
+ this.name = 'ShardfileFormatWindowError'
28
+ this.declared = declared
29
+ this.reader = reader
30
+ this.floor = SHARDFILE_FLOOR
31
+ this.above = above
32
+ }
33
+ }
34
+
35
+ function field(index: unknown, name: string): unknown {
36
+ return typeof index === 'object' && index !== null
37
+ ? Reflect.get(index, name)
38
+ : undefined
39
+ }
40
+
41
+ /** The declared format as written (`formatVersion`, or the legacy `version` beside the layout marker), or
42
+ * `undefined` when it is no canonical version: the schema then says why. */
43
+ function declaredOf(index: unknown): string | undefined {
44
+ const declared = field(index, 'formatVersion')
45
+ const found = declared === LEGACY_LAYOUT ? field(index, 'version') : declared
46
+ try {
47
+ parseShardfileVersion(found)
48
+ } catch {
49
+ return undefined
50
+ }
51
+ return typeof found === 'string' ? found : undefined
52
+ }
53
+
54
+ /** Throw `ShardfileFormatWindowError` for an index whose declared format this reader cannot read. */
55
+ function assertFormatWindow(
56
+ index: unknown,
57
+ reader: string = SHARDFILE_VERSION,
58
+ ): void {
59
+ const declared = declaredOf(index)
60
+ if (declared === undefined) {
61
+ return
62
+ }
63
+ if (compareShardfileVersions(declared, reader) > NONE) {
64
+ throw new ShardfileFormatWindowError(declared, reader, true)
65
+ }
66
+ if (compareShardfileVersions(declared, SHARDFILE_FLOOR) < NONE) {
67
+ throw new ShardfileFormatWindowError(declared, reader, false)
68
+ }
69
+ }
70
+
71
+ export { ShardfileFormatWindowError, assertFormatWindow }
@@ -29,7 +29,10 @@ function canonical(input: unknown): unknown {
29
29
  return input.map((item: unknown): unknown => canonical(item))
30
30
  }
31
31
  if (typeof input === 'object' && input !== null) {
32
- const entries = Object.entries(input).toSorted(byKey)
32
+ // Object.entries already creates a fresh array. The Node author entry also
33
+ // gets typechecked from consumers that use the ES2022 library.
34
+ // oxlint-disable-next-line unicorn/no-array-sort -- Sort only the fresh entries array.
35
+ const entries = Object.entries(input).sort(byKey)
33
36
  return Object.fromEntries(
34
37
  entries.map(
35
38
  ([key, value]: readonly [string, unknown]): [string, unknown] => [