@fabrika/auth-core 0.9.0-dev.4 → 0.9.0-dev.41

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 (55) 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 +168 -2
  5. package/src/contract-encoding.ts +181 -0
  6. package/src/contract.ts +212 -12
  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 +23 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +10 -0
  14. package/src/locale.ts +13 -1
  15. package/src/managed-environment.ts +147 -0
  16. package/src/membership.ts +12 -4
  17. package/src/oauth.ts +11 -0
  18. package/src/ops.ts +1933 -0
  19. package/src/permissions.ts +42 -0
  20. package/src/public-egress.ts +168 -0
  21. package/src/requirement.ts +5 -2
  22. package/src/rpc.ts +8 -8
  23. package/src/scope-values.ts +123 -0
  24. package/src/sha256.ts +52 -14
  25. package/src/terminal.ts +105 -0
  26. package/src/token.ts +170 -19
  27. package/src/types.ts +68 -2
  28. package/src/wire.ts +7 -0
  29. package/types/src/canonical-path.d.ts +6 -0
  30. package/types/src/client-address.d.ts +7 -0
  31. package/types/src/contract-canonical.d.ts +11 -1
  32. package/types/src/contract-encoding.d.ts +18 -0
  33. package/types/src/contract.d.ts +197 -11
  34. package/types/src/dev-environment.d.ts +5 -0
  35. package/types/src/egress.d.ts +27 -0
  36. package/types/src/endpoint-digest.d.ts +5 -0
  37. package/types/src/framework-release.d.ts +25 -0
  38. package/types/src/framework-variables.d.ts +12 -1
  39. package/types/src/iam-mail.d.ts +92 -0
  40. package/types/src/index.d.ts +10 -0
  41. package/types/src/locale.d.ts +11 -1
  42. package/types/src/managed-environment.d.ts +32 -0
  43. package/types/src/membership.d.ts +8 -3
  44. package/types/src/oauth.d.ts +7 -0
  45. package/types/src/ops.d.ts +657 -0
  46. package/types/src/permissions.d.ts +12 -0
  47. package/types/src/public-egress.d.ts +31 -0
  48. package/types/src/requirement.d.ts +2 -2
  49. package/types/src/rpc.d.ts +5 -5
  50. package/types/src/scope-values.d.ts +61 -0
  51. package/types/src/sha256.d.ts +10 -0
  52. package/types/src/terminal.d.ts +72 -0
  53. package/types/src/token.d.ts +69 -12
  54. package/types/src/types.d.ts +47 -2
  55. 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.4",
3
+ "version": "0.9.0-dev.41",
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,
@@ -24,9 +32,14 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
24
32
  return {
25
33
  format: artifact.format,
26
34
  app: artifact.app,
27
- dimensions: artifact.dimensions,
35
+ dimensions: mapValues(
36
+ artifact.dimensions,
37
+ (dimension) =>
38
+ dimension.values === undefined ? dimension : { ...dimension, values: [...dimension.values].sort((a, b) => compare(a.value, b.value)) },
39
+ ),
28
40
  actions: artifact.actions,
29
41
  roles: mapValues(artifact.roles, canonicalRole),
42
+ ...(artifact.relations === undefined ? {} : { relations: artifact.relations }),
30
43
  mounts: mapValues(artifact.mounts, canonicalMount),
31
44
  files: mapValues(artifact.files, (collection) => ({
32
45
  ...collection,
@@ -65,7 +78,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
65
78
  ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
66
79
  ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
67
80
  ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
68
- ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
81
+ ...(reach.egress === undefined ? {} : { egress: typeof reach.egress === 'string' ? reach.egress : sorted(reach.egress) }),
69
82
  })),
70
83
  }),
71
84
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
@@ -74,6 +87,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
74
87
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
75
88
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
76
89
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
90
+ ...(artifact.terminal === undefined ? {} : { terminal: { identify: artifact.terminal.identify } }),
77
91
  ...(artifact.procedures === undefined
78
92
  ? {}
79
93
  : {
@@ -100,6 +114,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
100
114
  grants: sorted(role.grants),
101
115
  member: role.member === null ? null : { scope: role.member.scope, assignableBy: sorted(role.member.assignableBy) },
102
116
  ...(role.external === true ? { external: true } : {}),
117
+ ...(role.via === undefined ? {} : { via: mapValues(role.via, sorted) }),
103
118
  }
104
119
  }
105
120
 
@@ -150,7 +165,120 @@ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
150
165
  scope: table.scope.mode === 'child' ? { ...table.scope, inherit: sorted(table.scope.inherit) } : table.scope,
151
166
  insert: sorted(table.insert),
152
167
  update: sorted(table.update),
168
+ columns: mapValues(table.columns, canonicalColumn),
169
+ ...(table.when === undefined ? {} : { when: mapValues(table.when, canonicalCondition) }),
170
+ ...(table.relationWhen === undefined
171
+ ? {}
172
+ : { relationWhen: mapValues(table.relationWhen, (conditions) => mapValues(conditions, canonicalCondition)) }),
173
+ ...(table.confers === undefined ? {} : { confers: mapValues(table.confers, canonicalConfers) }),
174
+ ...(table.reveals === undefined ? {} : { reveals: mapValues(table.reveals, canonicalReveals) }),
175
+ ...(table.memberReveals === undefined ? {} : { memberReveals: mapValues(table.memberReveals, canonicalMemberReveals) }),
176
+ }
177
+ }
178
+
179
+ /** A column's lists of read and write actions sorted; one action, and an absent one, as they are. */
180
+ function canonicalColumn(column: ColumnPolicyArtifact): ColumnPolicyArtifact {
181
+ return {
182
+ ...column,
183
+ ...(column.read === undefined || typeof column.read === 'string' ? {} : { read: sorted(column.read) }),
184
+ ...(column.write === undefined || typeof column.write === 'string' ? {} : { write: sorted(column.write) }),
185
+ }
186
+ }
187
+
188
+ function canonicalConfers(confers: ConfersArtifact): ConfersArtifact {
189
+ return confers.when === undefined ? confers : { ...confers, when: canonicalCondition(confers.when) }
190
+ }
191
+
192
+ function canonicalReveals(reveals: RevealsArtifact): RevealsArtifact {
193
+ return {
194
+ ...reveals,
195
+ actions: sorted(reveals.actions),
196
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
197
+ }
198
+ }
199
+
200
+ function canonicalMemberReveals(reveals: MemberRevealsArtifact): MemberRevealsArtifact {
201
+ return {
202
+ ...reveals,
203
+ actions: sorted(reveals.actions),
204
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
205
+ }
206
+ }
207
+
208
+ /**
209
+ * A condition with its connectives' operands and its `in` / `notIn` lists sorted by their canonical JSON: AND and OR
210
+ * commute and a list is a set, so neither order changes which rows it admits.
211
+ */
212
+ export function canonicalCondition(condition: ConditionArtifact): ConditionArtifact {
213
+ if ('allOf' in condition && isConditionList(condition.allOf)) {
214
+ return { allOf: sortedConditions(condition.allOf) }
215
+ }
216
+ if ('anyOf' in condition && isConditionList(condition.anyOf)) {
217
+ return { anyOf: sortedConditions(condition.anyOf) }
218
+ }
219
+ if ('not' in condition && isCondition(condition.not)) {
220
+ return { not: canonicalCondition(condition.not) }
221
+ }
222
+ const rows = canonicalRows(condition)
223
+ if (rows !== undefined) return rows
224
+ const tests: Record<string, ColumnTestArtifact | RowsTestArtifact> = {}
225
+ for (const [path, test] of Object.entries(condition)) {
226
+ const after = isCondition(test) ? canonicalRows(test) : undefined
227
+ if (after !== undefined) {
228
+ tests[path] = after
229
+ continue
230
+ }
231
+ // A parsed artifact holds nothing else here; dropping an unknown test would widen what the condition admits.
232
+ if (!isColumnTest(test)) throw new Error(`the condition test of ${path} is not a column test`)
233
+ tests[path] = canonicalTest(test)
234
+ }
235
+ return tests
236
+ }
237
+
238
+ /** `some` or `none` with its condition canonical, or `undefined` for any other form: one beside another key is no rows test. */
239
+ function canonicalRows(condition: object): RowsTestArtifact | undefined {
240
+ if (Object.keys(condition).length !== 1) return undefined
241
+ if ('some' in condition && isConditionRecord(condition.some)) {
242
+ return { some: mapValues(condition.some, canonicalCondition) }
153
243
  }
244
+ if ('none' in condition && isConditionRecord(condition.none)) {
245
+ return { none: mapValues(condition.none, canonicalCondition) }
246
+ }
247
+ return undefined
248
+ }
249
+
250
+ function canonicalTest(test: ColumnTestArtifact): ColumnTestArtifact {
251
+ return {
252
+ ...test,
253
+ ...(test.in === undefined ? {} : { in: sortedLiterals(test.in) }),
254
+ ...(test.notIn === undefined ? {} : { notIn: sortedLiterals(test.notIn) }),
255
+ }
256
+ }
257
+
258
+ function sortedConditions(conditions: readonly ConditionArtifact[]): ConditionArtifact[] {
259
+ return conditions.map(canonicalCondition).sort((a, b) => compare(canonicalJson(a), canonicalJson(b)))
260
+ }
261
+
262
+ function sortedLiterals(values: readonly ConditionLiteralArtifact[]): ConditionLiteralArtifact[] {
263
+ return [...values].sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)))
264
+ }
265
+
266
+ function isCondition(value: unknown): value is ConditionArtifact {
267
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
268
+ }
269
+
270
+ function isConditionRecord(value: unknown): value is Readonly<Record<string, ConditionArtifact>> {
271
+ return isCondition(value) && Object.values(value).every(isCondition)
272
+ }
273
+
274
+ function isConditionList(value: unknown): value is readonly ConditionArtifact[] {
275
+ return Array.isArray(value) && value.every(isCondition)
276
+ }
277
+
278
+ const COLUMN_TEST_OPERATORS: ReadonlySet<string> = new Set(['eq', 'notEq', 'in', 'notIn', 'isNull', 'lt', 'lte', 'gt', 'gte'])
279
+
280
+ function isColumnTest(value: unknown): value is ColumnTestArtifact {
281
+ return isCondition(value) && Object.keys(value).every((operator) => COLUMN_TEST_OPERATORS.has(operator))
154
282
  }
155
283
 
156
284
  function canonicalizeEndpoint(row: EndpointRow): EndpointRow {
@@ -233,3 +361,41 @@ function sortKeys(_key: string, value: unknown): unknown {
233
361
  }
234
362
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
235
363
  }
364
+
365
+ /**
366
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
367
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
368
+ */
369
+ export function writeCanonicalJson(value: unknown, write: (piece: string) => void): void {
370
+ if (Array.isArray(value)) {
371
+ write('[')
372
+ for (const [index, item] of value.entries()) {
373
+ if (index > 0) write(',')
374
+ if (isOmitted(item)) write('null')
375
+ else writeCanonicalJson(item, write)
376
+ }
377
+ write(']')
378
+ return
379
+ }
380
+ if (typeof value === 'object' && value !== null) {
381
+ write('{')
382
+ let first = true
383
+ const rebuilt = Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
384
+ for (const [key, item] of Object.entries(rebuilt)) {
385
+ if (isOmitted(item)) continue
386
+ if (!first) write(',')
387
+ first = false
388
+ write(JSON.stringify(key))
389
+ write(':')
390
+ writeCanonicalJson(item, write)
391
+ }
392
+ write('}')
393
+ return
394
+ }
395
+ write(JSON.stringify(value) ?? 'null')
396
+ }
397
+
398
+ /** What `JSON.stringify` leaves out of an object and writes as `null` in an array. */
399
+ function isOmitted(value: unknown): boolean {
400
+ return value === undefined || typeof value === 'function' || typeof value === 'symbol'
401
+ }
@@ -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
+ }