@fabrika/auth-core 0.9.0-dev.3 → 0.9.0-dev.30

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 (51) hide show
  1. package/package.json +3 -2
  2. package/src/canonical-path.ts +18 -0
  3. package/src/client-address.ts +74 -0
  4. package/src/contract-canonical.ts +159 -1
  5. package/src/contract-encoding.ts +181 -0
  6. package/src/contract.ts +203 -11
  7. package/src/dev-environment.ts +6 -0
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +72 -0
  11. package/src/framework-variables.ts +15 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +9 -0
  14. package/src/locale.ts +13 -1
  15. package/src/managed-environment.ts +140 -0
  16. package/src/membership.ts +12 -4
  17. package/src/ops.ts +1933 -0
  18. package/src/permissions.ts +42 -0
  19. package/src/public-egress.ts +168 -0
  20. package/src/requirement.ts +5 -2
  21. package/src/rpc.ts +8 -8
  22. package/src/sha256.ts +52 -14
  23. package/src/terminal.ts +105 -0
  24. package/src/token.ts +73 -13
  25. package/src/types.ts +63 -2
  26. package/src/wire.ts +7 -0
  27. package/types/src/canonical-path.d.ts +6 -0
  28. package/types/src/client-address.d.ts +7 -0
  29. package/types/src/contract-canonical.d.ts +11 -1
  30. package/types/src/contract-encoding.d.ts +18 -0
  31. package/types/src/contract.d.ts +188 -10
  32. package/types/src/dev-environment.d.ts +5 -0
  33. package/types/src/egress.d.ts +27 -0
  34. package/types/src/endpoint-digest.d.ts +5 -0
  35. package/types/src/framework-release.d.ts +25 -0
  36. package/types/src/framework-variables.d.ts +12 -1
  37. package/types/src/iam-mail.d.ts +92 -0
  38. package/types/src/index.d.ts +9 -0
  39. package/types/src/locale.d.ts +11 -1
  40. package/types/src/managed-environment.d.ts +32 -0
  41. package/types/src/membership.d.ts +8 -3
  42. package/types/src/ops.d.ts +657 -0
  43. package/types/src/permissions.d.ts +12 -0
  44. package/types/src/public-egress.d.ts +31 -0
  45. package/types/src/requirement.d.ts +2 -2
  46. package/types/src/rpc.d.ts +5 -5
  47. package/types/src/sha256.d.ts +10 -0
  48. package/types/src/terminal.d.ts +72 -0
  49. package/types/src/token.d.ts +36 -11
  50. package/types/src/types.d.ts +42 -2
  51. package/types/src/wire.d.ts +6 -0
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.9.0-dev.3",
3
+ "version": "0.9.0-dev.30",
4
4
  "type": "module",
5
+ "sideEffects": false,
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -23,7 +24,7 @@
23
24
  }
24
25
  },
25
26
  "scripts": {
26
- "typecheck": "tsc --noEmit",
27
+ "typecheck": "tsrs --build tsconfig.test.json",
27
28
  "test": "bun test"
28
29
  }
29
30
  }
@@ -50,6 +50,24 @@ export function rawRequestTarget(url: string): RequestTarget {
50
50
  return target.pathname === '' ? { pathname: '/', search: target.search } : target
51
51
  }
52
52
 
53
+ /**
54
+ * The absolute URL of `path` on `origin`, or `null` when `path` is not a path of that origin: the one rule for a
55
+ * redirect or return target that must stay on its own origin. A leading `//` or any `\` would make a browser read a
56
+ * host from it, and a browser strips a tab or newline before parsing, so no control character is admitted.
57
+ */
58
+ export function sameOriginTarget(origin: string, path: string): string | null {
59
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\') || [...path].some(isControl)) {
60
+ return null
61
+ }
62
+ const target = new URL(path, origin)
63
+ return target.origin === origin ? target.toString() : null
64
+ }
65
+
66
+ function isControl(character: string): boolean {
67
+ const code = character.charCodeAt(0)
68
+ return code < 0x20 || code === 0x7f
69
+ }
70
+
53
71
  /** A segment one reader decodes and another refuses would route differently, so a malformed escape is refused. */
54
72
  function isDecodable(segment: string): boolean {
55
73
  try {
@@ -0,0 +1,74 @@
1
+ // The client a per-client abuse bucket counts, derived from the address an ingress wrote. IAM and the application
2
+ // runtime both key on it, so one client is one bucket on either side.
3
+
4
+ /** Longest header value read; an IPv6 address with a zone id fits with room to spare. */
5
+ const MAX_ADDRESS_LENGTH = 64
6
+
7
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/
8
+ const HEXTET = /^[0-9a-f]{1,4}$/
9
+
10
+ /**
11
+ * The eight groups of an IPv6 address, or `null`. An embedded IPv4 tail (`::ffff:192.0.2.1`) counts as two groups,
12
+ * and a zone id (`%eth0`) is dropped.
13
+ */
14
+ function ipv6Groups(text: string): number[] | null {
15
+ const address = text.split('%')[0] ?? ''
16
+ const halves = address.split('::')
17
+ if (halves.length > 2) {
18
+ return null
19
+ }
20
+ const groupsOf = (half: string): number[] | null => {
21
+ if (half === '') {
22
+ return []
23
+ }
24
+ const groups: number[] = []
25
+ const parts = half.split(':')
26
+ for (const [index, part] of parts.entries()) {
27
+ if (index === parts.length - 1 && IPV4.test(part)) {
28
+ const [a = 0, b = 0, c = 0, d = 0] = part.split('.').map(Number)
29
+ groups.push(a * 256 + b, c * 256 + d)
30
+ } else if (HEXTET.test(part)) {
31
+ groups.push(Number.parseInt(part, 16))
32
+ } else {
33
+ return null
34
+ }
35
+ }
36
+ return groups
37
+ }
38
+ const head = groupsOf(halves[0] ?? '')
39
+ const tail = halves.length === 2 ? groupsOf(halves[1] ?? '') : []
40
+ if (head === null || tail === null) {
41
+ return null
42
+ }
43
+ if (halves.length === 1) {
44
+ return head.length === 8 ? head : null
45
+ }
46
+ const missing = 8 - head.length - tail.length
47
+ return missing < 1 ? null : [...head, ...Array.from({ length: missing }, () => 0), ...tail]
48
+ }
49
+
50
+ /**
51
+ * The client a client-address header value counts as: an IPv4 address, or an IPv6 address's /64 (one subscriber's
52
+ * prefix, of which it may hold every address); an IPv4-mapped IPv6 address counts as its IPv4 address. Only the first
53
+ * value counts, so a caller that appends a second copy cannot change the key. `null` when the value is absent or no
54
+ * IP address.
55
+ */
56
+ export function clientAddressKey(header: string | null): string | null {
57
+ const value = (header ?? '').split(',')[0]?.trim().toLowerCase() ?? ''
58
+ if (value === '' || value.length > MAX_ADDRESS_LENGTH) {
59
+ return null
60
+ }
61
+ if (IPV4.test(value)) {
62
+ return value
63
+ }
64
+ const groups = ipv6Groups(value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value)
65
+ if (groups === null) {
66
+ return null
67
+ }
68
+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff
69
+ if (mapped) {
70
+ const [high = 0, low = 0] = groups.slice(6)
71
+ return [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.')
72
+ }
73
+ return `${groups.slice(0, 4).map((group) => group.toString(16)).join(':')}::/64`
74
+ }
@@ -4,12 +4,20 @@
4
4
  import type {
5
5
  BodyAdmission,
6
6
  Caller,
7
+ ColumnPolicyArtifact,
8
+ ColumnTestArtifact,
9
+ ConditionArtifact,
10
+ ConditionLiteralArtifact,
11
+ ConfersArtifact,
7
12
  ContractArtifact,
8
13
  CspSource,
9
14
  EndpointRow,
15
+ MemberRevealsArtifact,
10
16
  MountArtifact,
11
17
  OutputShape,
18
+ RevealsArtifact,
12
19
  RoleArtifact,
20
+ RowsTestArtifact,
13
21
  SchemaShape,
14
22
  TableActionArtifact,
15
23
  TablePolicyArtifact,
@@ -27,6 +35,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
27
35
  dimensions: artifact.dimensions,
28
36
  actions: artifact.actions,
29
37
  roles: mapValues(artifact.roles, canonicalRole),
38
+ ...(artifact.relations === undefined ? {} : { relations: artifact.relations }),
30
39
  mounts: mapValues(artifact.mounts, canonicalMount),
31
40
  files: mapValues(artifact.files, (collection) => ({
32
41
  ...collection,
@@ -65,7 +74,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
65
74
  ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
66
75
  ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
67
76
  ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
68
- ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
77
+ ...(reach.egress === undefined ? {} : { egress: typeof reach.egress === 'string' ? reach.egress : sorted(reach.egress) }),
69
78
  })),
70
79
  }),
71
80
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
@@ -74,6 +83,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
74
83
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
75
84
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
76
85
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
86
+ ...(artifact.terminal === undefined ? {} : { terminal: { identify: artifact.terminal.identify } }),
77
87
  ...(artifact.procedures === undefined
78
88
  ? {}
79
89
  : {
@@ -100,6 +110,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
100
110
  grants: sorted(role.grants),
101
111
  member: role.member === null ? null : { scope: role.member.scope, assignableBy: sorted(role.member.assignableBy) },
102
112
  ...(role.external === true ? { external: true } : {}),
113
+ ...(role.via === undefined ? {} : { via: mapValues(role.via, sorted) }),
103
114
  }
104
115
  }
105
116
 
@@ -150,7 +161,116 @@ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
150
161
  scope: table.scope.mode === 'child' ? { ...table.scope, inherit: sorted(table.scope.inherit) } : table.scope,
151
162
  insert: sorted(table.insert),
152
163
  update: sorted(table.update),
164
+ columns: mapValues(table.columns, canonicalColumn),
165
+ ...(table.when === undefined ? {} : { when: mapValues(table.when, canonicalCondition) }),
166
+ ...(table.relationWhen === undefined
167
+ ? {}
168
+ : { relationWhen: mapValues(table.relationWhen, (conditions) => mapValues(conditions, canonicalCondition)) }),
169
+ ...(table.confers === undefined ? {} : { confers: mapValues(table.confers, canonicalConfers) }),
170
+ ...(table.reveals === undefined ? {} : { reveals: mapValues(table.reveals, canonicalReveals) }),
171
+ ...(table.memberReveals === undefined ? {} : { memberReveals: mapValues(table.memberReveals, canonicalMemberReveals) }),
172
+ }
173
+ }
174
+
175
+ /** A column's list of read actions sorted; one action, and a column without its own read, as they are. */
176
+ function canonicalColumn(column: ColumnPolicyArtifact): ColumnPolicyArtifact {
177
+ return column.read === undefined || typeof column.read === 'string' ? column : { ...column, read: sorted(column.read) }
178
+ }
179
+
180
+ function canonicalConfers(confers: ConfersArtifact): ConfersArtifact {
181
+ return confers.when === undefined ? confers : { ...confers, when: canonicalCondition(confers.when) }
182
+ }
183
+
184
+ function canonicalReveals(reveals: RevealsArtifact): RevealsArtifact {
185
+ return {
186
+ ...reveals,
187
+ actions: sorted(reveals.actions),
188
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
189
+ }
190
+ }
191
+
192
+ function canonicalMemberReveals(reveals: MemberRevealsArtifact): MemberRevealsArtifact {
193
+ return {
194
+ ...reveals,
195
+ actions: sorted(reveals.actions),
196
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
197
+ }
198
+ }
199
+
200
+ /**
201
+ * A condition with its connectives' operands and its `in` / `notIn` lists sorted by their canonical JSON: AND and OR
202
+ * commute and a list is a set, so neither order changes which rows it admits.
203
+ */
204
+ export function canonicalCondition(condition: ConditionArtifact): ConditionArtifact {
205
+ if ('allOf' in condition && isConditionList(condition.allOf)) {
206
+ return { allOf: sortedConditions(condition.allOf) }
207
+ }
208
+ if ('anyOf' in condition && isConditionList(condition.anyOf)) {
209
+ return { anyOf: sortedConditions(condition.anyOf) }
210
+ }
211
+ if ('not' in condition && isCondition(condition.not)) {
212
+ return { not: canonicalCondition(condition.not) }
213
+ }
214
+ const rows = canonicalRows(condition)
215
+ if (rows !== undefined) return rows
216
+ const tests: Record<string, ColumnTestArtifact | RowsTestArtifact> = {}
217
+ for (const [path, test] of Object.entries(condition)) {
218
+ const after = isCondition(test) ? canonicalRows(test) : undefined
219
+ if (after !== undefined) {
220
+ tests[path] = after
221
+ continue
222
+ }
223
+ // A parsed artifact holds nothing else here; dropping an unknown test would widen what the condition admits.
224
+ if (!isColumnTest(test)) throw new Error(`the condition test of ${path} is not a column test`)
225
+ tests[path] = canonicalTest(test)
226
+ }
227
+ return tests
228
+ }
229
+
230
+ /** `some` or `none` with its condition canonical, or `undefined` for any other form: one beside another key is no rows test. */
231
+ function canonicalRows(condition: object): RowsTestArtifact | undefined {
232
+ if (Object.keys(condition).length !== 1) return undefined
233
+ if ('some' in condition && isConditionRecord(condition.some)) {
234
+ return { some: mapValues(condition.some, canonicalCondition) }
235
+ }
236
+ if ('none' in condition && isConditionRecord(condition.none)) {
237
+ return { none: mapValues(condition.none, canonicalCondition) }
153
238
  }
239
+ return undefined
240
+ }
241
+
242
+ function canonicalTest(test: ColumnTestArtifact): ColumnTestArtifact {
243
+ return {
244
+ ...test,
245
+ ...(test.in === undefined ? {} : { in: sortedLiterals(test.in) }),
246
+ ...(test.notIn === undefined ? {} : { notIn: sortedLiterals(test.notIn) }),
247
+ }
248
+ }
249
+
250
+ function sortedConditions(conditions: readonly ConditionArtifact[]): ConditionArtifact[] {
251
+ return conditions.map(canonicalCondition).sort((a, b) => compare(canonicalJson(a), canonicalJson(b)))
252
+ }
253
+
254
+ function sortedLiterals(values: readonly ConditionLiteralArtifact[]): ConditionLiteralArtifact[] {
255
+ return [...values].sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)))
256
+ }
257
+
258
+ function isCondition(value: unknown): value is ConditionArtifact {
259
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
260
+ }
261
+
262
+ function isConditionRecord(value: unknown): value is Readonly<Record<string, ConditionArtifact>> {
263
+ return isCondition(value) && Object.values(value).every(isCondition)
264
+ }
265
+
266
+ function isConditionList(value: unknown): value is readonly ConditionArtifact[] {
267
+ return Array.isArray(value) && value.every(isCondition)
268
+ }
269
+
270
+ const COLUMN_TEST_OPERATORS: ReadonlySet<string> = new Set(['eq', 'notEq', 'in', 'notIn', 'isNull', 'lt', 'lte', 'gt', 'gte'])
271
+
272
+ function isColumnTest(value: unknown): value is ColumnTestArtifact {
273
+ return isCondition(value) && Object.keys(value).every((operator) => COLUMN_TEST_OPERATORS.has(operator))
154
274
  }
155
275
 
156
276
  function canonicalizeEndpoint(row: EndpointRow): EndpointRow {
@@ -233,3 +353,41 @@ function sortKeys(_key: string, value: unknown): unknown {
233
353
  }
234
354
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
235
355
  }
356
+
357
+ /**
358
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
359
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
360
+ */
361
+ export function writeCanonicalJson(value: unknown, write: (piece: string) => void): void {
362
+ if (Array.isArray(value)) {
363
+ write('[')
364
+ for (const [index, item] of value.entries()) {
365
+ if (index > 0) write(',')
366
+ if (isOmitted(item)) write('null')
367
+ else writeCanonicalJson(item, write)
368
+ }
369
+ write(']')
370
+ return
371
+ }
372
+ if (typeof value === 'object' && value !== null) {
373
+ write('{')
374
+ let first = true
375
+ const rebuilt = Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
376
+ for (const [key, item] of Object.entries(rebuilt)) {
377
+ if (isOmitted(item)) continue
378
+ if (!first) write(',')
379
+ first = false
380
+ write(JSON.stringify(key))
381
+ write(':')
382
+ writeCanonicalJson(item, write)
383
+ }
384
+ write('}')
385
+ return
386
+ }
387
+ write(JSON.stringify(value) ?? 'null')
388
+ }
389
+
390
+ /** What `JSON.stringify` leaves out of an object and writes as `null` in an array. */
391
+ function isOmitted(value: unknown): boolean {
392
+ return value === undefined || typeof value === 'function' || typeof value === 'symbol'
393
+ }
@@ -0,0 +1,181 @@
1
+ // The shared encoding of a contract artifact: how a build bundles it and how Control stores a large one. Each composite
2
+ // schema shape that occurs more than once is written once, in `shapes`, and referenced by its index; a shape's null
3
+ // constraints are left out. Decoding (`@fabrika/app/contract`) restores the canonical artifact exactly, so its digest
4
+ // is the one `contractDigest` takes: the encoding is a storage form, never what a digest is taken over.
5
+
6
+ import type { ContractArtifact, OutputShape, SchemaShape } from './contract'
7
+ import { canonicalizeArtifact, canonicalJson } from './contract-canonical'
8
+
9
+ /** The `encoding` of an encoded artifact; a plain artifact has no such key. */
10
+ export const SHARED_SHAPES_ENCODING = 'shared-shapes'
11
+
12
+ /** In place of a shape: `shapes[index]` of the encoded artifact, which is always written before it is referenced. */
13
+ export interface SharedShapeReference {
14
+ readonly type: 'shared'
15
+ readonly index: number
16
+ }
17
+
18
+ /** An artifact in the shared encoding, as JSON. */
19
+ export interface EncodedArtifact {
20
+ readonly encoding: typeof SHARED_SHAPES_ENCODING
21
+ readonly shapes: readonly object[]
22
+ readonly artifact: object
23
+ }
24
+
25
+ /** The canonical artifact in the shared encoding. */
26
+ export function encodeArtifact(artifact: ContractArtifact): EncodedArtifact {
27
+ const canonical = canonicalizeArtifact(artifact)
28
+ const interner = new ShapeInterner()
29
+ mapShapes(canonical, (shape) => {
30
+ interner.node(shape).uses++
31
+ return null
32
+ })
33
+ for (const node of interner.nodes) {
34
+ for (const child of node.children) child.uses++
35
+ }
36
+ const writer = new SharedWriter(interner)
37
+ const encoded = mapShapes(canonical, (shape) => writer.write(shape))
38
+ return { encoding: SHARED_SHAPES_ENCODING, shapes: writer.shapes, artifact: encoded }
39
+ }
40
+
41
+ /** The encoded artifact as text, keys sorted: what a build bundles. */
42
+ export function encodedArtifactJson(artifact: ContractArtifact): string {
43
+ return canonicalJson(encodeArtifact(artifact))
44
+ }
45
+
46
+ /** One distinct shape: equal shapes, wherever they occur, are one node. */
47
+ interface ShapeNode {
48
+ readonly id: number
49
+ readonly shape: SchemaShape
50
+ readonly children: readonly ShapeNode[]
51
+ uses: number
52
+ }
53
+
54
+ class ShapeInterner {
55
+ readonly nodes: ShapeNode[] = []
56
+ readonly #byForm = new Map<string, ShapeNode>()
57
+ readonly #byObject = new WeakMap<SchemaShape, ShapeNode>()
58
+
59
+ node(shape: SchemaShape): ShapeNode {
60
+ const known = this.#byObject.get(shape)
61
+ if (known !== undefined) return known
62
+ const children: ShapeNode[] = []
63
+ // A node's identity is its own fields and its children's identities, so equal subtrees are found bottom up.
64
+ const form = canonicalJson(compactShape(shape, (child) => {
65
+ const node = this.node(child)
66
+ children.push(node)
67
+ return node.id
68
+ }))
69
+ let node = this.#byForm.get(form)
70
+ if (node === undefined) {
71
+ node = { id: this.nodes.length, shape, children, uses: 0 }
72
+ this.nodes.push(node)
73
+ this.#byForm.set(form, node)
74
+ }
75
+ this.#byObject.set(shape, node)
76
+ return node
77
+ }
78
+ }
79
+
80
+ class SharedWriter {
81
+ readonly shapes: object[] = []
82
+ readonly #indexes = new Map<ShapeNode, number>()
83
+ readonly #interner: ShapeInterner
84
+
85
+ constructor(interner: ShapeInterner) {
86
+ this.#interner = interner
87
+ }
88
+
89
+ write(shape: SchemaShape): object {
90
+ const node = this.#interner.node(shape)
91
+ if (node.children.length === 0 || node.uses < 2) {
92
+ return compactShape(shape, (child) => this.write(child))
93
+ }
94
+ let index = this.#indexes.get(node)
95
+ if (index === undefined) {
96
+ // Children first, so every reference points to a shape written before it.
97
+ const written = compactShape(shape, (child) => this.write(child))
98
+ index = this.shapes.length
99
+ this.shapes.push(written)
100
+ this.#indexes.set(node, index)
101
+ }
102
+ const reference: SharedShapeReference = { type: 'shared', index }
103
+ return reference
104
+ }
105
+ }
106
+
107
+ /** The shape without its null constraints, each child replaced by `child`'s answer; an object's fields in key order. */
108
+ function compactShape(shape: SchemaShape, child: (shape: SchemaShape) => unknown): object {
109
+ switch (shape.type) {
110
+ case 'string':
111
+ return {
112
+ type: 'string',
113
+ ...present('format', shape.format),
114
+ ...present('minLength', shape.minLength),
115
+ ...present('maxLength', shape.maxLength),
116
+ ...present('pattern', shape.pattern),
117
+ ...present('startsWith', shape.startsWith),
118
+ ...present('endsWith', shape.endsWith),
119
+ ...present('includes', shape.includes),
120
+ }
121
+ case 'number':
122
+ return {
123
+ type: 'number',
124
+ int: shape.int,
125
+ ...present('min', shape.min),
126
+ exclusiveMin: shape.exclusiveMin,
127
+ ...present('max', shape.max),
128
+ exclusiveMax: shape.exclusiveMax,
129
+ ...present('multipleOf', shape.multipleOf),
130
+ }
131
+ case 'array':
132
+ return { type: 'array', items: child(shape.items), ...present('minItems', shape.minItems), ...present('maxItems', shape.maxItems) }
133
+ case 'tuple':
134
+ return { type: 'tuple', items: shape.items.map(child), ...(shape.rest === null ? {} : { rest: child(shape.rest) }) }
135
+ case 'record':
136
+ return { type: 'record', key: child(shape.key), value: child(shape.value) }
137
+ case 'object':
138
+ return { type: 'object', fields: Object.fromEntries(sortedEntries(shape.fields).map(([name, field]) => [name, child(field)])) }
139
+ case 'optional':
140
+ case 'nullable':
141
+ return { type: shape.type, inner: child(shape.inner) }
142
+ case 'union':
143
+ return { type: 'union', options: shape.options.map(child) }
144
+ default:
145
+ return shape
146
+ }
147
+ }
148
+
149
+ function present(key: string, value: string | number | null): object {
150
+ return value === null ? {} : { [key]: value }
151
+ }
152
+
153
+ /** The artifact with each schema shape replaced by `map`'s answer; records are visited in key order. */
154
+ function mapShapes(artifact: ContractArtifact, map: (shape: SchemaShape) => unknown): object {
155
+ const output = (shape: OutputShape): unknown => {
156
+ if (shape.type === 'redirect') return shape
157
+ if (shape.type === 'attachment') return { ...shape, columns: shape.columns.map((column) => ({ name: column.name, shape: map(column.shape) })) }
158
+ return map(shape)
159
+ }
160
+ const endpoints = artifact.endpoints.map((row) => ({
161
+ ...row,
162
+ input: row.input === null ? null : map(row.input),
163
+ output: row.output === null ? null : output(row.output),
164
+ }))
165
+ const procedures = artifact.procedures === undefined ? undefined : Object.fromEntries(
166
+ sortedEntries(artifact.procedures).map(([id, rules]) => [id, rules.query === undefined ? rules : { ...rules, query: map(rules.query) }]),
167
+ )
168
+ const tokens = artifact.tokens === undefined ? undefined : Object.fromEntries(
169
+ sortedEntries(artifact.tokens).map(([purpose, token]) => [purpose, { ...token, claims: map(token.claims) }]),
170
+ )
171
+ return {
172
+ ...artifact,
173
+ endpoints,
174
+ ...(procedures === undefined ? {} : { procedures }),
175
+ ...(tokens === undefined ? {} : { tokens }),
176
+ }
177
+ }
178
+
179
+ function sortedEntries<T>(record: Readonly<Record<string, T>>): [string, T][] {
180
+ return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
181
+ }