@wildshard/shard-format 0.69.1 → 0.70.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/shard-format",
3
- "version": "0.69.1",
3
+ "version": "0.70.0",
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": {
@@ -19,6 +19,7 @@
19
19
  "src/format/*.ts",
20
20
  "!src/format/*.test.ts",
21
21
  "!src/format/*.golden-specs.ts",
22
+ "!src/format/lock/**",
22
23
  "src/format/memoryGates.json",
23
24
  "src/format/memory-armed.json",
24
25
  "src/format/empty-shardfile.json",
@@ -240,6 +241,7 @@
240
241
  "./outputDownload": "./src/format/outputDownload.ts",
241
242
  "./outputFields": "./src/format/outputFields.ts",
242
243
  "./outputIndex": "./src/format/outputIndex.ts",
244
+ "./preparationSpec": "./src/format/preparation-spec.ts",
243
245
  "./overdraw": "./src/format/overdraw.ts",
244
246
  "./pageLife": "./src/format/pageLife.ts",
245
247
  "./pagePreparation": "./src/format/pagePreparation.ts",
@@ -458,6 +460,10 @@
458
460
  "test:ci": "node --test 'src/ci/**/*.test.ts'",
459
461
  "test:chain": "node --test 'src/tools/*.chain.ts'",
460
462
  "test:format": "vitest run src/format --testTimeout=30000 --maxWorkers=2",
463
+ "lock:write": "node src/tools/format-lock.ts --write",
464
+ "check:lock": "node src/tools/format-lock.ts",
465
+ "check:format-gate": "node src/tools/format-gate.ts",
466
+ "corpus:usage": "node src/cli/main.ts corpus --cache tmp/corpus --usage corpus/usage.json",
461
467
  "check:asks": "node kit/scripts/asks.mjs check",
462
468
  "check:agents": "node .githooks/agents-md.mjs lint",
463
469
  "check:parity": "node scripts/agent-parity.mjs --strict",
@@ -466,7 +472,7 @@
466
472
  "agents:sync": "node scripts/agent-sync.mjs",
467
473
  "md:wrap": "node kit/scripts/md-wrap.mjs",
468
474
  "test:hooks": "node --test '.githooks/*.test.mjs'",
469
- "check": "pnpm check:bin-pins && pnpm typecheck && pnpm lint && pnpm lint:format && pnpm format:check && pnpm test && pnpm test:format && pnpm check:asks && pnpm check:agents && pnpm check:agent-sync && pnpm test:agent-hooks && pnpm check:parity && node --check scripts/chromium-keychain-check.mjs && node --test test/tooling/chrome-keychain.test.mjs test/tooling/disk-land.test.mjs test/tooling/lane-live.test.mjs test/tooling/keep-copy.test.mjs test/tooling/leftovers-report.test.mjs test/tooling/reap-report.test.mjs && pnpm check:wire",
475
+ "check": "pnpm check:bin-pins && pnpm typecheck && pnpm lint && pnpm lint:format && pnpm format:check && pnpm test && pnpm check:lock && pnpm check:format-gate && node --test src/ci/exports-unique.test.ts && pnpm test:format && pnpm check:asks && pnpm check:agents && pnpm check:agent-sync && pnpm test:agent-hooks && pnpm check:parity && node --check scripts/chromium-keychain-check.mjs && node --test test/tooling/chrome-keychain.test.mjs test/tooling/disk-land.test.mjs test/tooling/lane-live.test.mjs test/tooling/keep-copy.test.mjs test/tooling/leftovers-report.test.mjs test/tooling/reap-report.test.mjs && pnpm check:wire",
470
476
  "check:wire": "pnpm --dir packages/wire check && pnpm --dir packages/wire test && pnpm check:wire-proofs",
471
477
  "check:wire-proofs": "node --test src/scripts/wire/recordings-proof.mjs src/scripts/wire/graph-proof.mjs src/scripts/wire/prepared-frame-proof.mjs",
472
478
  "bench": "pnpm --dir packages/wire bench",
@@ -0,0 +1,38 @@
1
+ import { readFile } from 'node:fs/promises'
2
+
3
+ import { corpusGate, readKnownFailures } from './corpus-gate.ts'
4
+ import { corpusUsage, writeUsage } from './corpus-usage.ts'
5
+ import { corpusReport, runCorpus } from './corpus.ts'
6
+ import { readVersion } from './version.ts'
7
+
8
+ interface CorpusArgs {
9
+ readonly api: string
10
+ readonly cache: string
11
+ readonly usage: string | undefined
12
+ }
13
+
14
+ const EXIT_OK = 0
15
+ const EXIT_INVALID = 3
16
+ const NONE = 0
17
+ const KNOWN_FAILURES = 'corpus/known-failures.json'
18
+
19
+ /** `shard-format corpus`: every kept original, as stored (FE3), gated by FE5's known failures; `--usage` writes FE13's record. */
20
+ async function corpusCommand(args: Readonly<CorpusArgs>): Promise<number> {
21
+ const validator = await readVersion()
22
+ const rows = await runCorpus({ api: args.api, cache: args.cache, validator })
23
+ process.stdout.write(`${corpusReport(rows)}\n`)
24
+ if (args.usage !== undefined) {
25
+ await writeUsage(args.usage, corpusUsage(rows, validator, new Date()))
26
+ }
27
+ // SHARD-COMPAT FE5: only a failure not listed with its owner blocks a release.
28
+ const listed = await readFile(KNOWN_FAILURES, 'utf8').catch(
29
+ (): string => '[]',
30
+ )
31
+ const gate = corpusGate(rows, readKnownFailures(listed))
32
+ if (gate.lines.length > NONE) {
33
+ process.stdout.write(`${gate.lines.join('\n')}\n`)
34
+ }
35
+ return gate.blocking.length > NONE ? EXIT_INVALID : EXIT_OK
36
+ }
37
+
38
+ export { corpusCommand }
@@ -0,0 +1,85 @@
1
+ import { writeFile } from 'node:fs/promises'
2
+
3
+ import { array, number, parse, record, strictObject, string } from 'valibot'
4
+
5
+ import type { CorpusRow } from './corpus.ts'
6
+
7
+ // SHARD-COMPAT FE13: what the delete gate reads. `shard-format corpus
8
+ // --usage <file>` records, for every kept original, the deprecated paths it
9
+ // uses (FE7) and the chain steps it needs to validate (an original the
10
+ // format refuses as stored, judged through the chain: `migrated: <ids>`).
11
+ // A deprecated part or a migration step may be deleted only while its list
12
+ // here is empty and the record is fresh.
13
+
14
+ interface Usage {
15
+ readonly measuredAt: string
16
+ readonly validator: string
17
+ readonly originals: number
18
+ readonly deprecations: Readonly<Record<string, readonly string[]>>
19
+ readonly migrations: Readonly<Record<string, readonly string[]>>
20
+ }
21
+
22
+ const Users = record(string(), array(string()))
23
+ const UsageSchema = strictObject({
24
+ measuredAt: string(),
25
+ validator: string(),
26
+ originals: number(),
27
+ deprecations: Users,
28
+ migrations: Users,
29
+ })
30
+ const MIGRATED = 'migrated: '
31
+ const INDENT = 1
32
+
33
+ function add(
34
+ users: Map<string, string[]>,
35
+ ids: readonly string[],
36
+ name: string,
37
+ ): void {
38
+ for (const id of ids) {
39
+ users.set(id, [...(users.get(id) ?? []), name])
40
+ }
41
+ }
42
+
43
+ function stepsOf(reason: string | undefined): readonly string[] {
44
+ return reason?.startsWith(MIGRATED) === true
45
+ ? reason
46
+ .slice(MIGRATED.length)
47
+ .split(',')
48
+ .map((step: string): string => step.trim())
49
+ .filter((step: string): boolean => step !== '')
50
+ : []
51
+ }
52
+
53
+ /** Who uses each deprecated path and each chain step, over the kept originals. */
54
+ function corpusUsage(
55
+ rows: readonly Readonly<CorpusRow>[],
56
+ validator: string,
57
+ measuredAt: Readonly<Date>,
58
+ ): Usage {
59
+ const deprecations = new Map<string, string[]>()
60
+ const migrations = new Map<string, string[]>()
61
+ for (const found of rows) {
62
+ const name = `${found.slug} r${String(found.revision)}`
63
+ add(deprecations, found.deprecations, name)
64
+ add(migrations, stepsOf(found.reason), name)
65
+ }
66
+ return {
67
+ measuredAt: measuredAt.toISOString(),
68
+ validator,
69
+ originals: rows.length,
70
+ deprecations: Object.fromEntries(deprecations),
71
+ migrations: Object.fromEntries(migrations),
72
+ }
73
+ }
74
+
75
+ async function writeUsage(file: string, usage: Readonly<Usage>): Promise<void> {
76
+ await writeFile(file, `${JSON.stringify(usage, undefined, INDENT)}\n`)
77
+ }
78
+
79
+ /** A usage record's text, checked. */
80
+ function readUsage(text: string): Usage {
81
+ return parse(UsageSchema, JSON.parse(text))
82
+ }
83
+
84
+ export { corpusUsage, readUsage, writeUsage }
85
+ export type { Usage }
@@ -0,0 +1,89 @@
1
+ import type { Json } from './format-diff-lock.ts'
2
+ import type { DataRow } from './format-diff-normal.ts'
3
+
4
+ // SHARD-COMPAT FE2: the findings type, and how a plain data row (an option
5
+ // list, a limit constant, a table) is classified. Schema rows:
6
+ // format-diff-rules.ts.
7
+
8
+ type ChangeKind = 'additive' | 'breaking' | 'deprecation' | 'review'
9
+ type MigrationOp =
10
+ | 'drop'
11
+ | 'fill'
12
+ | 'map'
13
+ | 'moveSection'
14
+ | 'rename'
15
+ | 'renameKind'
16
+
17
+ interface Finding {
18
+ readonly kind: ChangeKind
19
+ readonly what: string
20
+ readonly op?: MigrationOp
21
+ }
22
+
23
+ interface Change extends Finding {
24
+ readonly path: string
25
+ readonly rename?: { readonly from: string; readonly to: string }
26
+ }
27
+
28
+ const RAISE_NAME = /(?:max|limit|cap|budget|ceiling)[^.#]*$/iu
29
+ const FLOOR_NAME = /(?:min|floor)[^.#]*$/iu
30
+ const NONE = 0
31
+ const NEXT = 1
32
+
33
+ function finding(kind: ChangeKind, what: string, op?: MigrationOp): Finding {
34
+ return op === undefined ? { kind, what } : { kind, what, op }
35
+ }
36
+
37
+ /** A limit's move: up widens a ceiling, down widens a floor. */
38
+ function directed(widens: boolean, what: string): Finding {
39
+ return finding(widens ? 'additive' : 'breaking', what)
40
+ }
41
+
42
+ /** Members added only widen; any removed is a break (an old file may hold it). */
43
+ function setFinding(
44
+ what: string,
45
+ before: readonly Json[],
46
+ after: readonly Json[],
47
+ ): Finding {
48
+ const was = new Set(before.map((item: Json): string => JSON.stringify(item)))
49
+ const now = new Set(after.map((item: Json): string => JSON.stringify(item)))
50
+ const gone = [...was].filter((item: string): boolean => !now.has(item))
51
+ const added = [...now].filter((item: string): boolean => !was.has(item))
52
+ if (gone.length > NONE) {
53
+ return finding('breaking', `${what} removes ${gone.join(', ')}`, 'map')
54
+ }
55
+ return added.length > NONE
56
+ ? finding('additive', `${what} adds ${added.join(', ')}`)
57
+ : finding('review', `${what} reordered`)
58
+ }
59
+
60
+ /** A number constant by its name: a ceiling, a floor, or for review. */
61
+ function numberFinding(name: string, before: number, after: number): Finding {
62
+ const moved = `${name} ${String(before)} -> ${String(after)}`
63
+ if (RAISE_NAME.test(name)) {
64
+ return directed(after > before, moved)
65
+ }
66
+ if (FLOOR_NAME.test(name)) {
67
+ return directed(after < before, moved)
68
+ }
69
+ return finding('review', moved)
70
+ }
71
+
72
+ /** A plain data row: option lists by membership, named limits by direction, the rest for review. */
73
+ function dataFinding(path: string, before: DataRow, after: DataRow): Finding {
74
+ const name = path.slice(path.lastIndexOf('#') + NEXT)
75
+ if (Array.isArray(before.value) && Array.isArray(after.value)) {
76
+ return setFinding(
77
+ path.endsWith('|') ? 'options' : 'list',
78
+ before.value,
79
+ after.value,
80
+ )
81
+ }
82
+ if (typeof before.value === 'number' && typeof after.value === 'number') {
83
+ return numberFinding(name, before.value, after.value)
84
+ }
85
+ return finding('review', `${name} value changed`)
86
+ }
87
+
88
+ export { dataFinding, directed, finding, setFinding }
89
+ export type { Change, ChangeKind, Finding, MigrationOp }
@@ -0,0 +1,122 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { mkdir, readdir, readFile, rm, stat } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { promisify } from 'node:util'
5
+
6
+ // SHARD-COMPAT FE2: read a format lock (FE1) from a folder or a git ref.
7
+ // A lock is `src/format/lock/`: `index.json` (chain id, exclusions) and one
8
+ // `<subpath>.json` of rows per package subpath.
9
+
10
+ type Json =
11
+ | boolean
12
+ | number
13
+ | string
14
+ | null
15
+ | readonly Json[]
16
+ | { readonly [key: string]: Json }
17
+
18
+ interface LockData {
19
+ readonly chainId: string
20
+ readonly rows: Readonly<Record<string, Json>>
21
+ readonly excluded: Readonly<Record<string, string>>
22
+ }
23
+
24
+ // eslint-disable-next-line typescript/strict-void-return -- Node execFile returns a child while its callback supplies the result.
25
+ const run = promisify(execFile)
26
+ const LOCK_FOLDER = 'src/format/lock'
27
+ const INDEX = 'index.json'
28
+ const MAX_OUTPUT = 268_435_456
29
+ const SAFE_REF = /[^A-Za-z0-9._-]/gu
30
+
31
+ function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
33
+ }
34
+
35
+ function assemble(
36
+ names: readonly string[],
37
+ parsed: readonly unknown[],
38
+ root: string,
39
+ ): LockData {
40
+ const index = parsed[names.indexOf(INDEX)]
41
+ if (!isRecord(index) || typeof index['chainId'] !== 'string') {
42
+ throw new Error(`${root}: no format lock (no ${INDEX} with a chainId)`)
43
+ }
44
+ const rows: Record<string, Json> = {}
45
+ for (const [at, body] of parsed.entries()) {
46
+ if (names[at] !== INDEX && isRecord(body)) {
47
+ Object.assign(rows, body)
48
+ }
49
+ }
50
+ const excluded = isRecord(index['excluded']) ? index['excluded'] : {}
51
+ return {
52
+ chainId: index['chainId'],
53
+ rows,
54
+ excluded: Object.fromEntries(
55
+ Object.entries(excluded).map(
56
+ ([key, why]: readonly [string, unknown]): readonly [string, string] => [
57
+ key,
58
+ String(why),
59
+ ],
60
+ ),
61
+ ),
62
+ }
63
+ }
64
+
65
+ /** The lock in one folder (the lock folder itself, or a checkout holding src/format/lock). */
66
+ async function readLockFolder(folder: string): Promise<LockData> {
67
+ const inner = path.join(folder, LOCK_FOLDER)
68
+ const found = await stat(inner).catch((): undefined => undefined)
69
+ const root = found?.isDirectory() === true ? inner : folder
70
+ const listed = await readdir(root)
71
+ const names = listed.filter((name: string): boolean => name.endsWith('.json'))
72
+ const parsed = await Promise.all(
73
+ names.map(async (name: string): Promise<unknown> => {
74
+ const body = await readFile(path.join(root, name), 'utf8')
75
+ return JSON.parse(body)
76
+ }),
77
+ )
78
+ return assemble(names, parsed, root)
79
+ }
80
+
81
+ /** The lock at a git ref, extracted under ./tmp/format-diff/<ref>. */
82
+ async function readLockRef(ref: string, cwd: string): Promise<LockData> {
83
+ const out = path.join(cwd, 'tmp/format-diff', ref.replaceAll(SAFE_REF, '_'))
84
+ await rm(out, { recursive: true, force: true })
85
+ await mkdir(out, { recursive: true })
86
+ const { stdout } = await run(
87
+ 'git',
88
+ ['ls-tree', '-r', '--name-only', ref, '--', `${LOCK_FOLDER}/`],
89
+ { cwd, encoding: 'utf8', maxBuffer: MAX_OUTPUT },
90
+ )
91
+ if (stdout.trim() === '') {
92
+ throw new Error(
93
+ `${ref} has no format lock (FE1 landed after 0.69.2): build one with \`pnpm lock:write\` in a checkout of it and pass that folder`,
94
+ )
95
+ }
96
+ await run(
97
+ 'sh',
98
+ [
99
+ '-c',
100
+ 'git archive "$1" "$2" | tar -x -C "$3"',
101
+ 'sh',
102
+ ref,
103
+ LOCK_FOLDER,
104
+ out,
105
+ ],
106
+ { cwd, maxBuffer: MAX_OUTPUT },
107
+ )
108
+ return await readLockFolder(out)
109
+ }
110
+
111
+ /** A lock from a folder when one exists at that path, else from a git ref in cwd. */
112
+ async function readLock(where: string, cwd: string): Promise<LockData> {
113
+ const found = await stat(path.resolve(cwd, where)).catch(
114
+ (): undefined => undefined,
115
+ )
116
+ return found?.isDirectory() === true
117
+ ? await readLockFolder(path.resolve(cwd, where))
118
+ : await readLockRef(where, cwd)
119
+ }
120
+
121
+ export { isRecord, readLock, readLockFolder }
122
+ export type { Json, LockData }
@@ -0,0 +1,300 @@
1
+ import { isRecord } from './format-diff-lock.ts'
2
+
3
+ import type { Json } from './format-diff-lock.ts'
4
+
5
+ // SHARD-COMPAT FE2: a lock's rows put in a form two versions compare on.
6
+ // 1. A `ref` row takes its target's row and the target's whole subtree, so
7
+ // sharing a schema or walking modules in a new order moves nothing.
8
+ // 2. `expects` is dropped: it is message text derived from the other facts.
9
+ // 3. A wrapper (optional, nullable, ...) folds into the node it wraps, as a
10
+ // `wrap` list, so making a field optional changes one row, not the path
11
+ // of every row under it.
12
+ // 4. A variant option is keyed by its discriminating literal (`|=boss`), not
13
+ // its index, so inserting an option renames none of the others.
14
+
15
+ interface SchemaRow {
16
+ readonly kind: 'schema'
17
+ readonly type: string
18
+ readonly wrap: readonly string[]
19
+ readonly facts: Readonly<Record<string, Json>>
20
+ }
21
+ interface DataRow {
22
+ readonly kind: 'data'
23
+ readonly value: Json
24
+ }
25
+ type Row = DataRow | SchemaRow
26
+
27
+ const MARKS: ReadonlySet<string> = new Set(['.', '[', '|', '?', '{'])
28
+ const SCHEMA_KEYS: ReadonlySet<string> = new Set([
29
+ 'async',
30
+ 'default',
31
+ 'expects',
32
+ 'getter',
33
+ 'literal',
34
+ 'pipe',
35
+ 'requirement',
36
+ 'type',
37
+ ])
38
+ const WRAPPERS: ReadonlySet<string> = new Set([
39
+ 'exact_optional',
40
+ 'non_nullable',
41
+ 'non_nullish',
42
+ 'non_optional',
43
+ 'nullable',
44
+ 'nullish',
45
+ 'optional',
46
+ 'undefinedable',
47
+ ])
48
+ const MAX_PASSES = 64
49
+ const OPTION = /^(?<group>.*)\|(?<index>\d+)$/u
50
+ const UNSAFE = /[.[|?{}#]/gu
51
+ const NONE = 0
52
+ const NEXT = 1
53
+ const HALF = 2
54
+ const SEGMENT = /\|\d+/gu
55
+
56
+ function refOf(value: Json | undefined): string | undefined {
57
+ return isRecord(value) && typeof value['ref'] === 'string'
58
+ ? value['ref']
59
+ : undefined
60
+ }
61
+
62
+ /** The first index in a sorted list at or after `key`. */
63
+ function lowerBound(sorted: readonly string[], key: string): number {
64
+ let low = NONE
65
+ let high = sorted.length
66
+ while (low < high) {
67
+ const middle = Math.floor((low + high) / HALF)
68
+ if ((sorted[middle] ?? '') < key) {
69
+ low = middle + NEXT
70
+ } else {
71
+ high = middle
72
+ }
73
+ }
74
+ return low
75
+ }
76
+
77
+ /** The keys strictly under `prefix` (a mark follows it), from a sorted list. */
78
+ function under(sorted: readonly string[], prefix: string): readonly string[] {
79
+ const found: string[] = []
80
+ for (const key of sorted.slice(lowerBound(sorted, prefix))) {
81
+ if (!key.startsWith(prefix)) {
82
+ break
83
+ }
84
+ if (MARKS.has(key.charAt(prefix.length))) {
85
+ found.push(key)
86
+ }
87
+ }
88
+ return found
89
+ }
90
+
91
+ function expandOnce(rows: ReadonlyMap<string, Json>): Map<string, Json> {
92
+ const sorted = [...rows.keys()].toSorted()
93
+ const out = new Map(rows)
94
+ for (const [key, value] of rows) {
95
+ const target = refOf(value)
96
+ const row = target === undefined ? undefined : rows.get(target)
97
+ if (target !== undefined && row !== undefined) {
98
+ out.set(key, row)
99
+ for (const sub of under(sorted, target)) {
100
+ out.set(`${key}${sub.slice(target.length)}`, rows.get(sub) ?? row)
101
+ }
102
+ }
103
+ }
104
+ return out
105
+ }
106
+
107
+ /** Every `ref` replaced by its target and the target's subtree. */
108
+ function expandRefs(raw: Readonly<Record<string, Json>>): Map<string, Json> {
109
+ let rows = new Map(Object.entries(raw))
110
+ let passes = NONE
111
+ while (
112
+ passes < MAX_PASSES &&
113
+ [...rows.values()].some(
114
+ (value: Json): boolean => refOf(value) !== undefined,
115
+ )
116
+ ) {
117
+ rows = expandOnce(rows)
118
+ passes += NEXT
119
+ }
120
+ return rows
121
+ }
122
+
123
+ function withoutExpects(pipe: Json): Json {
124
+ return Array.isArray(pipe)
125
+ ? pipe.map((action: Json): Json =>
126
+ isRecord(action)
127
+ ? Object.fromEntries(
128
+ Object.entries(action).filter(
129
+ ([key]: readonly [string, Json]): boolean => key !== 'expects',
130
+ ),
131
+ )
132
+ : action,
133
+ )
134
+ : pipe
135
+ }
136
+
137
+ /** One raw row as a schema node's facts (without `expects`) or plain data. */
138
+ function rowOf(value: Json): Row {
139
+ if (
140
+ !isRecord(value) ||
141
+ typeof value['type'] !== 'string' ||
142
+ !Object.keys(value).every((key: string): boolean => SCHEMA_KEYS.has(key))
143
+ ) {
144
+ return { kind: 'data', value }
145
+ }
146
+ const facts: Record<string, Json> = {}
147
+ for (const [key, fact] of Object.entries(value)) {
148
+ if (key !== 'type' && key !== 'expects') {
149
+ facts[key] = key === 'pipe' ? withoutExpects(fact) : fact
150
+ }
151
+ }
152
+ return { kind: 'schema', type: value['type'], wrap: [], facts }
153
+ }
154
+
155
+ /** A wrapper row folded over the row it wraps. */
156
+ function folded(outer: SchemaRow, inner: Row): Row {
157
+ if (inner.kind === 'data') {
158
+ return inner
159
+ }
160
+ const outerFacts = Object.entries(outer.facts).map(
161
+ ([key, fact]: readonly [string, Json]): readonly [string, Json] => [
162
+ `wrap:${key}`,
163
+ fact,
164
+ ],
165
+ )
166
+ return {
167
+ ...inner,
168
+ wrap: [...outer.wrap, outer.type, ...inner.wrap],
169
+ facts: { ...inner.facts, ...Object.fromEntries(outerFacts) },
170
+ }
171
+ }
172
+
173
+ /** Wrappers folded into the nodes they wrap, under paths without `?`. */
174
+ function foldWrappers(rows: ReadonlyMap<string, Json>): Map<string, Row> {
175
+ const out = new Map<string, Row>()
176
+ for (const key of [...rows.keys()].toSorted()) {
177
+ const row = rowOf(rows.get(key) ?? '')
178
+ const at = key.replaceAll('?', '')
179
+ const outer = out.get(at)
180
+ out.set(
181
+ at,
182
+ outer?.kind === 'schema' && WRAPPERS.has(outer.type) && key !== at
183
+ ? folded(outer, row)
184
+ : row,
185
+ )
186
+ }
187
+ return out
188
+ }
189
+
190
+ function literalText(value: Json | undefined): string {
191
+ if (value === undefined) {
192
+ return ''
193
+ }
194
+ return typeof value === 'string' ? value : JSON.stringify(value)
195
+ }
196
+
197
+ /** Each node's direct literal children, by node path then field name. */
198
+ function literalChildren(
199
+ rows: ReadonlyMap<string, Row>,
200
+ ): ReadonlyMap<string, ReadonlyMap<string, string>> {
201
+ const out = new Map<string, Map<string, string>>()
202
+ for (const [key, row] of rows) {
203
+ const dot = key.lastIndexOf('.')
204
+ const name = key.slice(dot + NEXT)
205
+ if (
206
+ row.kind === 'schema' &&
207
+ row.type === 'literal' &&
208
+ dot > NONE &&
209
+ !/[[|{]/u.test(name)
210
+ ) {
211
+ const parent = key.slice(NONE, dot)
212
+ const children = out.get(parent) ?? new Map<string, string>()
213
+ children.set(name, literalText(row.facts['literal']))
214
+ out.set(parent, children)
215
+ }
216
+ }
217
+ return out
218
+ }
219
+
220
+ /** The literal each option of one union holds under a name every option shares, by option path. */
221
+ function discriminants(
222
+ literals: ReadonlyMap<string, ReadonlyMap<string, string>>,
223
+ options: readonly string[],
224
+ ): readonly (readonly [string, string])[] {
225
+ const found = options.map(
226
+ (option: string): ReadonlyMap<string, string> =>
227
+ literals.get(option) ?? new Map<string, string>(),
228
+ )
229
+ const name = [...(found.at(NONE)?.keys() ?? [])].find(
230
+ (candidate: string): boolean => {
231
+ const values = found.map(
232
+ (children: ReadonlyMap<string, string>): string | undefined =>
233
+ children.get(candidate),
234
+ )
235
+ return (
236
+ values.every(
237
+ (value: string | undefined): boolean => value !== undefined,
238
+ ) && new Set(values).size === values.length
239
+ )
240
+ },
241
+ )
242
+ return name === undefined
243
+ ? []
244
+ : options.map((option: string, at: number): readonly [string, string] => [
245
+ option,
246
+ (found[at]?.get(name) ?? '').replaceAll(UNSAFE, '_'),
247
+ ])
248
+ }
249
+
250
+ /** A key with every renamed option segment (`|n`) spelled by its literal (`|=boss`). */
251
+ function renamed(key: string, renames: ReadonlyMap<string, string>): string {
252
+ let out = ''
253
+ let from = NONE
254
+ for (const match of key.matchAll(SEGMENT)) {
255
+ const end = match.index + match[NONE].length
256
+ const literal = renames.get(key.slice(NONE, end))
257
+ if (
258
+ literal !== undefined &&
259
+ (end === key.length || MARKS.has(key.charAt(end)))
260
+ ) {
261
+ out += `${key.slice(from, match.index)}|=${literal}`
262
+ from = end
263
+ }
264
+ }
265
+ return `${out}${key.slice(from)}`
266
+ }
267
+
268
+ /** Variant options keyed by their discriminating literal. */
269
+ function keyVariants(rows: ReadonlyMap<string, Row>): Map<string, Row> {
270
+ const groups = new Map<string, string[]>()
271
+ for (const key of rows.keys()) {
272
+ const group = OPTION.exec(key)?.groups?.['group']
273
+ if (group !== undefined) {
274
+ groups.set(group, [...(groups.get(group) ?? []), key])
275
+ }
276
+ }
277
+ const literals = literalChildren(rows)
278
+ const renames = new Map(
279
+ [...groups.values()].flatMap(
280
+ (options: readonly string[]): readonly (readonly [string, string])[] =>
281
+ discriminants(literals, options),
282
+ ),
283
+ )
284
+ return new Map(
285
+ [...rows].map(
286
+ ([key, row]: readonly [string, Row]): readonly [string, Row] => [
287
+ renamed(key, renames),
288
+ row,
289
+ ],
290
+ ),
291
+ )
292
+ }
293
+
294
+ /** A lock's rows in compare form. */
295
+ function normalRows(raw: Readonly<Record<string, Json>>): Map<string, Row> {
296
+ return keyVariants(foldWrappers(expandRefs(raw)))
297
+ }
298
+
299
+ export { MARKS, normalRows, WRAPPERS }
300
+ export type { DataRow, Row, SchemaRow }