@wildshard/shard-format 0.67.0 → 0.68.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.
Files changed (45) hide show
  1. package/package.json +7 -19
  2. package/src/cli/corpus-deprecations.ts +57 -0
  3. package/src/cli/corpus-gate.ts +114 -0
  4. package/src/cli/corpus-migrated.ts +68 -0
  5. package/src/cli/corpus.ts +300 -0
  6. package/src/cli/main.ts +41 -0
  7. package/src/format/cook-preparation.ts +22 -6
  8. package/src/format/creature-layers.ts +4 -0
  9. package/src/format/deprecations.ts +228 -0
  10. package/src/format/empty-shardfile.json +56 -0
  11. package/src/format/empty-shardfile.ts +43 -0
  12. package/src/format/format-migrate-inventory.ts +142 -0
  13. package/src/format/format-migrate-rebuild.ts +269 -0
  14. package/src/format/format-migrate.ts +290 -0
  15. package/src/format/format-migration-journal.ts +129 -0
  16. package/src/format/format-migration-ops.ts +230 -0
  17. package/src/format/format-migration-prune.ts +106 -0
  18. package/src/format/format-migrations.ts +124 -0
  19. package/src/format/issue-codes.ts +3 -1
  20. package/src/format/journal-glyphs.json +12 -0
  21. package/src/format/memory-armed.json +1 -39
  22. package/src/format/memory-armed.ts +41 -8
  23. package/src/format/memory-epoch.ts +2 -2
  24. package/src/format/memory-line.ts +4 -3
  25. package/src/format/memoryAdmission.ts +1 -1
  26. package/src/format/policy-verdict.ts +95 -0
  27. package/src/format/rows.ts +6 -4
  28. package/src/format/runtime-tier.ts +3 -3
  29. package/src/format/shardSections.ts +11 -1
  30. package/src/format/shardfile-assets.ts +12 -8
  31. package/src/format/shardfile-stream-admit.ts +41 -16
  32. package/src/format/shardfile-stream-rows.ts +3 -1
  33. package/src/format/shardfile-stream.ts +12 -9
  34. package/src/format/shardfileValidation.ts +30 -18
  35. package/src/format/stateLineage.ts +1 -1
  36. package/src/format/version.ts +11 -13
  37. package/src/format/baked-terrain.golden.json +0 -2760
  38. package/src/format/colliders.golden.json +0 -1619
  39. package/src/format/forest-placement.golden.json +0 -4588
  40. package/src/format/geometry-layout.golden.json +0 -180
  41. package/src/format/interact-table.golden.json +0 -340
  42. package/src/format/item-catalogue.golden.json +0 -2310
  43. package/src/format/memory-ratchet.ts +0 -107
  44. package/src/format/small-laws.golden.json +0 -57
  45. package/src/format/terrain-field.golden.json +0 -3998
package/src/cli/main.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises'
2
3
  import { parseArgs } from 'node:util'
3
4
 
5
+ import { corpusGate, readKnownFailures } from './corpus-gate.ts'
6
+ import { corpusReport, runCorpus } from './corpus.ts'
4
7
  import { packFolder } from './pack.ts'
5
8
  import { summary, validateShardfile } from './validate.ts'
6
9
  import { readVersion } from './version.ts'
@@ -13,6 +16,9 @@ const NONE = 0
13
16
 
14
17
  // Arguments start after [node, script] in process.argv.
15
18
  const FIRST_CLI_ARG = 2
19
+ const DEFAULT_API = 'https://api.wildshard.io'
20
+ const DEFAULT_CACHE = 'tmp/corpus'
21
+ const KNOWN_FAILURES = 'corpus/known-failures.json'
16
22
 
17
23
  const USAGE = `Usage: shard-format <command> [options]
18
24
 
@@ -24,6 +30,10 @@ Commands:
24
30
  Tar a folder into a shardfile: what its sections
25
31
  measure follows them, and format's validator must
26
32
  pass. Writes <slug>.tar by default
33
+ corpus [--api <url>] [--cache <dir>]
34
+ Validate every stored shard file the API keeps,
35
+ as stored originals; list every failure. Exits 3
36
+ when any fails
27
37
 
28
38
  Options:
29
39
  --version Print the version
@@ -35,6 +45,8 @@ interface CliArgs {
35
45
  readonly operands: readonly string[]
36
46
  readonly help: boolean
37
47
  readonly out: string | undefined
48
+ readonly api: string
49
+ readonly cache: string
38
50
  readonly version: boolean
39
51
  }
40
52
 
@@ -45,6 +57,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
45
57
  options: {
46
58
  help: { type: 'boolean', default: false },
47
59
  out: { type: 'string' },
60
+ api: { type: 'string', default: DEFAULT_API },
61
+ cache: { type: 'string', default: DEFAULT_CACHE },
48
62
  version: { type: 'boolean', default: false },
49
63
  },
50
64
  })
@@ -54,6 +68,8 @@ function parseCliArgs(argv: readonly string[]): CliArgs {
54
68
  operands,
55
69
  help: values.help,
56
70
  out: values.out,
71
+ api: values.api,
72
+ cache: values.cache,
57
73
  version: values.version,
58
74
  }
59
75
  }
@@ -113,6 +129,28 @@ async function pack(args: CliArgs): Promise<number> {
113
129
  return await packReport(dir, args.out)
114
130
  }
115
131
 
132
+ async function corpus(args: CliArgs): Promise<number> {
133
+ if (args.operands.length > NONE) {
134
+ process.stderr.write(`shard-format: corpus takes no operands\n\n${USAGE}`)
135
+ return EXIT_USAGE
136
+ }
137
+ const rows = await runCorpus({
138
+ api: args.api,
139
+ cache: args.cache,
140
+ validator: await readVersion(),
141
+ })
142
+ process.stdout.write(`${corpusReport(rows)}\n`)
143
+ // SHARD-COMPAT FE5: only a failure not listed with its owner blocks a release.
144
+ const listed = await readFile(KNOWN_FAILURES, 'utf8').catch(
145
+ (): string => '[]',
146
+ )
147
+ const gate = corpusGate(rows, readKnownFailures(listed))
148
+ if (gate.lines.length > NONE) {
149
+ process.stdout.write(`${gate.lines.join('\n')}\n`)
150
+ }
151
+ return gate.blocking.length > NONE ? EXIT_INVALID : EXIT_OK
152
+ }
153
+
116
154
  async function runCommand(args: CliArgs): Promise<number> {
117
155
  if (args.command === undefined) {
118
156
  return printUsage(EXIT_USAGE)
@@ -123,6 +161,9 @@ async function runCommand(args: CliArgs): Promise<number> {
123
161
  if (args.command === 'pack') {
124
162
  return await pack(args)
125
163
  }
164
+ if (args.command === 'corpus') {
165
+ return await corpus(args)
166
+ }
126
167
  process.stderr.write(
127
168
  `shard-format: unknown command ${args.command}\n\n${USAGE}`,
128
169
  )
@@ -191,6 +191,14 @@ function programMountValid(
191
191
  )
192
192
  }
193
193
  }
194
+ function failureOf(run: () => void): string | undefined {
195
+ try {
196
+ run()
197
+ return undefined
198
+ } catch (error: unknown) {
199
+ return error instanceof Error ? error.message : String(error)
200
+ }
201
+ }
194
202
  function requireCookPreparation(
195
203
  index: Frozen<OutputIndex>,
196
204
  cook:
@@ -218,14 +226,22 @@ function requireCookPreparation(
218
226
  if (cook?.version !== VERSION) {
219
227
  throw new Error(`Missing cook preparation: run ${fix}`)
220
228
  }
221
- if (
222
- cook.inputHash !==
229
+ // SHARD-COMPAT PR5 (J487): every failing prepared part is named, not the first.
230
+ const failures = [
231
+ cook.inputHash ===
223
232
  digest(cookPreparationBytes(index, cook.mounts, cook.renderer))
224
- ) {
225
- throw new Error(`stale cook preparation: run ${fix}`)
233
+ ? undefined
234
+ : `stale cook preparation: run ${fix}`,
235
+ failureOf((): void => {
236
+ fenceValid(index, { fence: cook.fence ?? [], mounts: cook.mounts }, fix)
237
+ }),
238
+ failureOf((): void => {
239
+ programMountValid(index, cook, digest)
240
+ }),
241
+ ].filter((row: string | undefined): row is string => row !== undefined)
242
+ if (failures.length > ZERO) {
243
+ throw new Error(failures.join('; '))
226
244
  }
227
- fenceValid(index, { fence: cook.fence ?? [], mounts: cook.mounts }, fix)
228
- programMountValid(index, cook, digest)
229
245
  }
230
246
  function readEntryPrograms(input: unknown): EntryPrograms {
231
247
  return parse(EntryProgramsSchema, input)
@@ -279,3 +279,7 @@ export {
279
279
  } from './creature-attackable.ts'
280
280
  export type { CreatureAttackable } from './creature-attackable.ts'
281
281
  export type { CreatureBody } from './creature-body.ts'
282
+
283
+ // ONE-FORMAT OF30: a declared species row's optional view projection (rows.ts), lent from its own module
284
+ export { ActorProjectionV2Schema } from './actorProjectionV2.ts'
285
+ export type { ActorProjectionV2Rows } from './actorProjectionV2.ts'
@@ -0,0 +1,228 @@
1
+ // oxlint-disable typescript/prefer-readonly-parameter-types -- the index is valibot output, only read
2
+ /** The deprecation counter (SHARD-COMPAT FE7, J486). A deprecated path still validates; it carries the version that
3
+ * deprecated it and its replacement, both validators warn when a shard file uses it, and the corpus counts the kept
4
+ * files using each (`shard-format corpus`). A path with a migration is mended by the chain; one without waits for its
5
+ * users to reach zero before it is deleted. */
6
+ import type { OutputIndex } from './outputIndex.ts'
7
+
8
+ /** One deprecated path. */
9
+ interface Deprecation {
10
+ /** Stable id the warnings and the corpus count use. */
11
+ readonly id: string
12
+ /** Where it sits in a shard file, in words. */
13
+ readonly path: string
14
+ /** The format version that deprecated it. */
15
+ readonly since: string
16
+ /** What to write instead. */
17
+ readonly replacement: string
18
+ /** The chain step that mends it, or `undefined` when nothing can (`format-migrations.ts`). */
19
+ readonly migration: string | undefined
20
+ }
21
+
22
+ /** What a deprecation test reads: the index and each section by name. */
23
+ interface DeprecationInput {
24
+ readonly index: Readonly<OutputIndex> | Readonly<Record<string, unknown>>
25
+ readonly sections: ReadonlyMap<string, unknown>
26
+ }
27
+
28
+ interface DeprecationRule extends Deprecation {
29
+ readonly uses: (shard: Readonly<DeprecationInput>) => boolean
30
+ }
31
+
32
+ const LEGACY_SPELLING = '0.1'
33
+ const NONE = 0
34
+ /** Deprecated in the current format with no data change: a shard file of any version may still carry it. */
35
+ const CURRENT = '0.1.0.1'
36
+ /** FORMAT-PRUNE FP15: OF30 cut B leaves these as plain JSON nothing reads. */
37
+ const SPECIES_PROGRAM_FAMILY: readonly string[] = [
38
+ 'actors/species-programs',
39
+ 'look/hull-book',
40
+ 'look/rigged-hulls',
41
+ ]
42
+
43
+ function field(value: unknown, key: string): unknown {
44
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
45
+ ? Reflect.get(value, key)
46
+ : undefined
47
+ }
48
+
49
+ /** Whether `key` names a field anywhere inside `value`. */
50
+ function hasKey(value: unknown, key: string): boolean {
51
+ const pending: unknown[] = [value]
52
+ while (pending.length > NONE) {
53
+ const next = pending.pop()
54
+ if (typeof next === 'object' && next !== null) {
55
+ if (!Array.isArray(next) && Object.hasOwn(next, key)) {
56
+ return true
57
+ }
58
+ const children: readonly unknown[] = Object.values(next)
59
+ pending.push(...children)
60
+ }
61
+ }
62
+ return false
63
+ }
64
+
65
+ const RULES: readonly DeprecationRule[] = [
66
+ {
67
+ id: 'version.two-part',
68
+ path: 'shard.json version and requires.sdk spelled "0.1"',
69
+ since: '0.1.0.0',
70
+ replacement: 'the four-part "0.1.0.0"',
71
+ migration: 'fp6-four-part-version',
72
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
73
+ field(shard.index, 'version') === LEGACY_SPELLING,
74
+ },
75
+ {
76
+ id: 'manifest.gridShardfile',
77
+ path: 'sections/ui/level manifest.gridShardfile (and the discovery mount)',
78
+ since: '0.1.0.1',
79
+ replacement: 'manifest.shardfile',
80
+ migration: 'fp8-shardfile-pointer',
81
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
82
+ field(
83
+ field(shard.sections.get('ui/level'), 'manifest'),
84
+ 'gridShardfile',
85
+ ) !== undefined,
86
+ },
87
+ {
88
+ id: 'runtime.trust',
89
+ path: 'shard.json runtime.trust',
90
+ since: '0.1.0.1',
91
+ replacement: 'nothing: no reader reads it',
92
+ migration: 'fp3-drop-runtime-trust',
93
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
94
+ field(field(shard.index, 'runtime'), 'trust') !== undefined,
95
+ },
96
+ ...SPECIES_PROGRAM_FAMILY.map((name: string): DeprecationRule => ({
97
+ id: `section.${name}`,
98
+ path: `sections/${name} (the species-program family, FORMAT-PRUNE FP15)`,
99
+ since: CURRENT,
100
+ replacement:
101
+ 'species rows and authored looks (actors/species); nothing reads it once OF30 lands',
102
+ migration: undefined,
103
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
104
+ shard.sections.has(name),
105
+ })),
106
+ {
107
+ id: 'items.legacySlot',
108
+ path: 'an item equipment row legacySlot: a closed list of engine-native weapon names (FORMAT-PRUNE FP17)',
109
+ since: CURRENT,
110
+ replacement:
111
+ 'none yet: it goes with engine native weapon slots, so a new item names no slot',
112
+ migration: undefined,
113
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
114
+ [...shard.sections.values()].some((section: unknown): boolean =>
115
+ hasKey(section, 'legacySlot'),
116
+ ),
117
+ },
118
+ {
119
+ id: 'admission.server',
120
+ path: 'shard.json admission.server (native assembly, FORMAT-PRUNE FP16)',
121
+ since: CURRENT,
122
+ replacement:
123
+ 'the server primitives: the server derives every host (OF17b3)',
124
+ migration: undefined,
125
+ uses: (shard: Readonly<DeprecationInput>): boolean =>
126
+ field(field(shard.index, 'admission'), 'server') !== undefined,
127
+ },
128
+ ]
129
+
130
+ /** A `legacy*` field that maps an old save key or saved shape: it stays, undeprecated, until a save wipe (J149), so a
131
+ * shard that keeps old players' saves working is not warned (FORMAT-PRUNE FP17). */
132
+ interface SaveBridge {
133
+ readonly path: string
134
+ /** The engine code that reads old saves through it. */
135
+ readonly reader: string
136
+ }
137
+
138
+ /** FP17's sort of the `legacy*` fields. `items.legacySlot` is shard data only, so it is a deprecation above; the
139
+ * species book's `piercing.legacy` goes with the species-program family (FP15); none can be migrated by data alone. */
140
+ const SAVE_BRIDGES: readonly SaveBridge[] = [
141
+ {
142
+ path: 'loadout bow.legacyItem',
143
+ reader: 'engine client/game/loadout/held.ts',
144
+ },
145
+ {
146
+ path: 'quest persistence legacyNamespace',
147
+ reader: 'engine shared/game/quest/persistence.ts',
148
+ },
149
+ {
150
+ path: 'quest story repair legacyObservation',
151
+ reader: 'engine client/game/plugin/ui.ts',
152
+ },
153
+ {
154
+ path: 'quest story persistence reward.legacy',
155
+ reader: 'engine shared/game/quest/persistence.ts',
156
+ },
157
+ {
158
+ path: 'elite feature legacy (versions, scripts, stun, upgrades)',
159
+ reader: 'engine server/game/quest/eliteFeature.ts',
160
+ },
161
+ {
162
+ path: 'spawn script legacy (spec, acc, rng, groups)',
163
+ reader: 'engine server/game/population/spawnScript.ts',
164
+ },
165
+ ]
166
+
167
+ /** Every deprecated path, without its test. */
168
+ const DEPRECATIONS: readonly Deprecation[] = RULES.map(
169
+ ({ uses: _uses, ...row }: Readonly<DeprecationRule>): Deprecation => row,
170
+ )
171
+
172
+ /** The deprecations a shard file uses, in registry order. */
173
+ function deprecationsUsed(
174
+ shard: Readonly<DeprecationInput>,
175
+ ): readonly Deprecation[] {
176
+ return RULES.filter((rule: Readonly<DeprecationRule>): boolean =>
177
+ rule.uses(shard),
178
+ ).map(
179
+ ({ uses: _uses, ...row }: Readonly<DeprecationRule>): Deprecation => row,
180
+ )
181
+ }
182
+
183
+ /** What a validator returns about warnings: its own, then one per deprecated path the file uses, and their ids. */
184
+ interface DeprecationReport {
185
+ /** Admitted with a warning: grandfathered script side lines (`SCRIPT_SIDE_GRANDFATHER`, SERVER-PARITY SS11) and each
186
+ * deprecated path the file uses (FE7). */
187
+ readonly warnings: readonly string[]
188
+ /** FE7: the ids of the deprecated paths the file uses. */
189
+ readonly deprecations: readonly string[]
190
+ }
191
+
192
+ /** The warning a validator gives for one used deprecation. */
193
+ function deprecationWarning(row: Readonly<Deprecation>): string {
194
+ const mend =
195
+ row.migration === undefined
196
+ ? 'no migration: it is deleted once no kept file uses it'
197
+ : `the chain mends it (${row.migration})`
198
+ return `deprecated since ${row.since} (${row.id}): ${row.path}; use ${row.replacement}; ${mend}`
199
+ }
200
+
201
+ /** A validator's warnings with the file's deprecations added (FE7). */
202
+ function deprecationReport(
203
+ shard: Readonly<DeprecationInput>,
204
+ warnings: readonly string[],
205
+ ): DeprecationReport {
206
+ const used = deprecationsUsed(shard)
207
+ return {
208
+ warnings: [
209
+ ...warnings,
210
+ ...used.map((row: Readonly<Deprecation>): string =>
211
+ deprecationWarning(row),
212
+ ),
213
+ ],
214
+ deprecations: used.map((row: Readonly<Deprecation>): string => row.id),
215
+ }
216
+ }
217
+
218
+ export {
219
+ DEPRECATIONS,
220
+ SAVE_BRIDGES,
221
+ type SaveBridge,
222
+ type DeprecationReport,
223
+ deprecationReport,
224
+ type Deprecation,
225
+ type DeprecationInput,
226
+ deprecationWarning,
227
+ deprecationsUsed,
228
+ }
@@ -0,0 +1,56 @@
1
+ {
2
+ "accent": "sand",
3
+ "requires": {
4
+ "capabilities": [],
5
+ "commons": [],
6
+ "commonsWire": {},
7
+ "commonsCosts": {}
8
+ },
9
+ "budgets": {
10
+ "library": { "resident": 0, "compressed": 0 },
11
+ "sim": { "resident": 0, "compressed": 0 },
12
+ "overlap": 0
13
+ },
14
+ "entryways": [
15
+ { "edge": "north", "at": [0, 0, 250] },
16
+ { "edge": "east", "at": [250, 0, 0] },
17
+ { "edge": "south", "at": [0, 0, -250] },
18
+ { "edge": "west", "at": [-250, 0, 0] }
19
+ ],
20
+ "look": {
21
+ "families": [],
22
+ "grade": { "exposure": 0, "saturation": 1, "contrast": 1, "lut": null },
23
+ "clock": "engine",
24
+ "dayOverride": null,
25
+ "keys": []
26
+ },
27
+ "sim": {
28
+ "fixedHz": 60,
29
+ "scriptTickDivisor": 2,
30
+ "commandVersion": 0,
31
+ "snapshotVersion": 0,
32
+ "scripts": []
33
+ },
34
+ "state": {
35
+ "version": 1,
36
+ "sharedOwner": "host",
37
+ "playerKey": "actorId",
38
+ "shared": [],
39
+ "player": []
40
+ },
41
+ "authorCaps": { "players": 32, "speed": 15 },
42
+ "serverBudget": {
43
+ "tickMicros": 1000,
44
+ "memory": 1000000,
45
+ "entities": 100,
46
+ "commandsPerTick": 32
47
+ },
48
+ "edgeSamples": 257,
49
+ "edgeGrey": 0.5,
50
+ "edgeHeight": 0,
51
+ "files": [],
52
+ "tiles": [],
53
+ "library": [],
54
+ "critical": [],
55
+ "far": null
56
+ }
@@ -0,0 +1,43 @@
1
+ /** The one starting shard file (FORMAT-PRUNE FP11), admitted by the format's own parser, so a new project starts
2
+ * from a file the game accepts. Engine and sharddev `author.ts` re-export it. */
3
+ import { ENTRY_WIDTH } from './contentBounds.ts'
4
+ import start from './empty-shardfile.json' with { type: 'json' }
5
+ import { parseShardfile } from './shardSchema.ts'
6
+ import { SHARDFILE_VERSION } from './version.ts'
7
+
8
+ import type { Shardfile } from './shardSchema.ts'
9
+
10
+ /** Each starting door is as wide as the format's entry width. */
11
+ function widened(
12
+ row: Readonly<{ edge: string; at: readonly number[] }>,
13
+ ): object {
14
+ return { edge: row.edge, at: row.at, width: ENTRY_WIDTH }
15
+ }
16
+
17
+ /** A valid empty world; add baked content before shipping a playable shard. */
18
+ function emptyShardfile(identity: Readonly<Shardfile['identity']>): Shardfile {
19
+ const { edgeSamples, edgeGrey, edgeHeight, requires, entryways, ...rest } =
20
+ start
21
+ const edge = {
22
+ heights: Array.from({ length: edgeSamples }, (): number => edgeHeight),
23
+ colours: Array.from({ length: edgeSamples }, (): number[] => [
24
+ edgeGrey,
25
+ edgeGrey,
26
+ edgeGrey,
27
+ ]),
28
+ roadHeight: edgeHeight,
29
+ }
30
+ return parseShardfile({
31
+ ...rest,
32
+ version: SHARDFILE_VERSION,
33
+ identity,
34
+ requires: { sdk: SHARDFILE_VERSION, ...requires },
35
+ entryways: entryways.map(
36
+ (row: Readonly<{ edge: string; at: readonly number[] }>): object =>
37
+ widened(row),
38
+ ),
39
+ edge: { north: edge, south: edge, east: edge, west: edge },
40
+ })
41
+ }
42
+
43
+ export { emptyShardfile }
@@ -0,0 +1,142 @@
1
+ /** The migration chain's view of an original's inventory (SHARD-COMPAT CP1). It reads `shard.json` as plain JSON, never
2
+ * through the current schema, so an older shape is read before it is migrated. */
3
+ import { readCanonicalJson } from './shardfileValidation.ts'
4
+
5
+ type Files = ReadonlyMap<string, Uint8Array>
6
+ type Hash = (bytes: Readonly<Uint8Array>) => string
7
+ type JsonRecord = Record<string, unknown>
8
+
9
+ interface Listed {
10
+ readonly path: string
11
+ readonly hash: string
12
+ readonly bytes: number
13
+ }
14
+
15
+ const INDEX = 'shard.json'
16
+ const RECEIPT = 'validation.json'
17
+
18
+ /** A plain JSON object, kept by reference so a step's edit lands in the copy. */
19
+ function record(value: unknown, where: string): JsonRecord {
20
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
21
+ throw new TypeError(`Migration input needs an object at ${where}`)
22
+ }
23
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- checked a plain object just above; edits stay in place
24
+ return value as JsonRecord
25
+ }
26
+ function rows(value: unknown): readonly JsonRecord[] {
27
+ if (!Array.isArray(value)) {
28
+ return []
29
+ }
30
+ return value.map((row: unknown): JsonRecord =>
31
+ record(row, 'an inventory row'),
32
+ )
33
+ }
34
+ function listed(row: Readonly<JsonRecord>, size = 'bytes'): Listed {
35
+ const { path, hash } = row
36
+ const bytes = row[size]
37
+ if (
38
+ typeof path !== 'string' ||
39
+ typeof hash !== 'string' ||
40
+ typeof bytes !== 'number'
41
+ ) {
42
+ throw new TypeError('Migration input has a malformed inventory row')
43
+ }
44
+ return { path, hash, bytes }
45
+ }
46
+ function listedRows(value: unknown, size = 'bytes'): readonly Listed[] {
47
+ return rows(value).map((row: Readonly<JsonRecord>): Listed =>
48
+ listed(row, size),
49
+ )
50
+ }
51
+ function optionalRecord(value: unknown, where: string): JsonRecord {
52
+ return value === undefined || value === null ? {} : record(value, where)
53
+ }
54
+
55
+ /** Every byte the index and its cook file's mounts list, packs aside. */
56
+ function inventory(
57
+ index: Readonly<JsonRecord>,
58
+ cook: Readonly<JsonRecord> | undefined,
59
+ ): readonly Listed[] {
60
+ const admission = optionalRecord(index['admission'], 'admission')
61
+ const runtime = optionalRecord(index['runtime'], 'runtime')
62
+ const cookRow =
63
+ index['cook'] === undefined ? [] : [listed(record(index['cook'], 'cook'))]
64
+ return [
65
+ ...listedRows(index['sections']),
66
+ ...listedRows(index['schemas']),
67
+ ...listedRows(index['files'], 'compressed'),
68
+ ...listedRows(admission['server']),
69
+ ...listedRows(runtime['files']),
70
+ ...cookRow,
71
+ ...listedRows(cook?.['mounts']),
72
+ ]
73
+ }
74
+
75
+ /** Refuse a missing, changed or unlisted byte before any step runs. A tarball may leave a pack out, since its members
76
+ * ship anyway; a carried pack is checked like any listed file. */
77
+ function verifyInventory(
78
+ files: Files,
79
+ {
80
+ index,
81
+ cook,
82
+ }: Readonly<{
83
+ index: Readonly<JsonRecord>
84
+ cook: Readonly<JsonRecord> | undefined
85
+ }>,
86
+ hash: Hash,
87
+ ): void {
88
+ const carried = listedRows(index['packs']).filter(
89
+ (row: Readonly<Listed>): boolean => files.has(row.path),
90
+ )
91
+ const seen = new Set([INDEX, RECEIPT])
92
+ for (const entry of [...inventory(index, cook), ...carried]) {
93
+ const bytes = files.get(entry.path)
94
+ if (bytes?.length !== entry.bytes || hash(bytes) !== entry.hash) {
95
+ throw new Error(`Original hash or size mismatch: ${entry.path}`)
96
+ }
97
+ seen.add(entry.path)
98
+ }
99
+ for (const path of files.keys()) {
100
+ if (!seen.has(path)) {
101
+ throw new Error(`Unlisted original file: ${path}`)
102
+ }
103
+ }
104
+ }
105
+
106
+ function readJson(files: Files, path: string): unknown {
107
+ const bytes = files.get(path)
108
+ if (bytes === undefined) {
109
+ throw new Error(`Original lacks ${path}`)
110
+ }
111
+ return readCanonicalJson(bytes)
112
+ }
113
+
114
+ /** Each section's payload by name. */
115
+ function readSections(
116
+ files: Files,
117
+ index: Readonly<JsonRecord>,
118
+ ): Map<string, unknown> {
119
+ const sections = new Map<string, unknown>()
120
+ for (const row of rows(index['sections'])) {
121
+ if (typeof row['name'] === 'string') {
122
+ sections.set(row['name'], readJson(files, listed(row).path))
123
+ }
124
+ }
125
+ return sections
126
+ }
127
+
128
+ export {
129
+ INDEX,
130
+ RECEIPT,
131
+ type Files,
132
+ type Hash,
133
+ type JsonRecord,
134
+ type Listed,
135
+ listed,
136
+ listedRows,
137
+ readJson,
138
+ readSections,
139
+ record,
140
+ rows,
141
+ verifyInventory,
142
+ }