@hyperscale0/udl 1.0.0-rc.1 → 1.0.123

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 (234) hide show
  1. package/CHANGELOG.md +5 -211
  2. package/LICENSE.md +356 -0
  3. package/NOTICE.md +8 -0
  4. package/README.md +14 -106
  5. package/dist/canonical.d.ts.map +1 -1
  6. package/dist/canonical.js +1 -29
  7. package/dist/canonical.js.map +1 -1
  8. package/dist/diagnostics.d.ts +13 -165
  9. package/dist/diagnostics.d.ts.map +1 -1
  10. package/dist/diagnostics.js +33 -157
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/field-value.d.ts +5 -0
  13. package/dist/field-value.d.ts.map +1 -0
  14. package/dist/field-value.js +85 -0
  15. package/dist/field-value.js.map +1 -0
  16. package/dist/finance.d.ts +10 -53
  17. package/dist/finance.d.ts.map +1 -1
  18. package/dist/finance.js +252 -536
  19. package/dist/finance.js.map +1 -1
  20. package/dist/index.d.ts +9 -13
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +9 -9
  23. package/dist/index.js.map +1 -1
  24. package/dist/json.d.ts +2 -0
  25. package/dist/json.d.ts.map +1 -0
  26. package/dist/json.js +30 -0
  27. package/dist/json.js.map +1 -0
  28. package/dist/limits.d.ts +3 -28
  29. package/dist/limits.d.ts.map +1 -1
  30. package/dist/limits.js +5 -31
  31. package/dist/limits.js.map +1 -1
  32. package/dist/object-contract.d.ts +140 -0
  33. package/dist/object-contract.d.ts.map +1 -0
  34. package/dist/object-contract.js +314 -0
  35. package/dist/object-contract.js.map +1 -0
  36. package/dist/object-semantics-schema.d.ts +5710 -0
  37. package/dist/object-semantics-schema.d.ts.map +1 -0
  38. package/dist/object-semantics-schema.js +119 -0
  39. package/dist/object-semantics-schema.js.map +1 -0
  40. package/dist/object-semantics.d.ts +6 -0
  41. package/dist/object-semantics.d.ts.map +1 -0
  42. package/dist/object-semantics.js +279 -0
  43. package/dist/object-semantics.js.map +1 -0
  44. package/dist/object-structures.d.ts +4 -0
  45. package/dist/object-structures.d.ts.map +1 -0
  46. package/dist/object-structures.js +134 -0
  47. package/dist/object-structures.js.map +1 -0
  48. package/dist/reporting-validation.d.ts +8 -0
  49. package/dist/reporting-validation.d.ts.map +1 -0
  50. package/dist/reporting-validation.js +252 -0
  51. package/dist/reporting-validation.js.map +1 -0
  52. package/dist/reporting.d.ts +477 -0
  53. package/dist/reporting.d.ts.map +1 -0
  54. package/dist/reporting.js +169 -0
  55. package/dist/reporting.js.map +1 -0
  56. package/dist/schema.d.ts +5572 -2710
  57. package/dist/schema.d.ts.map +1 -1
  58. package/dist/schema.js +444 -1121
  59. package/dist/schema.js.map +1 -1
  60. package/dist/validation.d.ts +10 -73
  61. package/dist/validation.d.ts.map +1 -1
  62. package/dist/validation.js +1109 -2569
  63. package/dist/validation.js.map +1 -1
  64. package/docs/assets/brand/manifest.json +30 -0
  65. package/docs/assets/brand/udl-horizontal-white.svg +1 -0
  66. package/docs/assets/brand/udl-horizontal.svg +1 -0
  67. package/docs/assets/brand/udl-stacked-white.svg +1 -0
  68. package/docs/assets/brand/udl-stacked.svg +1 -0
  69. package/docs/assets/udl.svg +11 -0
  70. package/package.json +13 -22
  71. package/spec/README.md +300 -172
  72. package/spec/cars.udl.json +249 -0
  73. package/spec/udl.schema.json +3066 -2242
  74. package/src/canonical.ts +1 -35
  75. package/src/diagnostics.ts +76 -209
  76. package/src/field-value.ts +87 -0
  77. package/src/finance.ts +327 -832
  78. package/src/index.ts +18 -95
  79. package/src/json.ts +34 -0
  80. package/src/limits.ts +5 -31
  81. package/src/object-contract.ts +559 -0
  82. package/src/object-semantics-schema.ts +148 -0
  83. package/src/object-semantics.ts +378 -0
  84. package/src/object-structures.ts +255 -0
  85. package/src/reporting-validation.ts +383 -0
  86. package/src/reporting.ts +178 -0
  87. package/src/schema.ts +510 -1277
  88. package/src/validation.ts +1630 -4545
  89. package/LICENSE +0 -661
  90. package/LICENSING.md +0 -51
  91. package/TRADEMARKS.md +0 -35
  92. package/conformance/README.md +0 -82
  93. package/conformance/evolution/action-contract.expected.json +0 -10
  94. package/conformance/evolution/action-contract.live.udl +0 -44
  95. package/conformance/evolution/action-contract.next.udl +0 -45
  96. package/conformance/evolution/product-identity.expected.json +0 -10
  97. package/conformance/evolution/product-identity.live.udl +0 -55
  98. package/conformance/evolution/product-identity.next.udl +0 -55
  99. package/conformance/evolution/version-required.expected.json +0 -10
  100. package/conformance/evolution/version-required.live.udl +0 -55
  101. package/conformance/evolution/version-required.next.udl +0 -58
  102. package/conformance/invalid/action-without-transition.expected.json +0 -10
  103. package/conformance/invalid/action-without-transition.udl +0 -60
  104. package/conformance/invalid/agent-description-too-long.expected.json +0 -10
  105. package/conformance/invalid/agent-description-too-long.udl +0 -57
  106. package/conformance/invalid/blank-title.expected.json +0 -10
  107. package/conformance/invalid/blank-title.udl +0 -54
  108. package/conformance/invalid/composition-dial-duplicate-key.expected.json +0 -10
  109. package/conformance/invalid/composition-dial-duplicate-key.udl +0 -73
  110. package/conformance/invalid/depth-budget.expected.json +0 -10
  111. package/conformance/invalid/depth-budget.udl +0 -49
  112. package/conformance/invalid/duplicate-subject.expected.json +0 -10
  113. package/conformance/invalid/duplicate-subject.udl +0 -230
  114. package/conformance/invalid/forged-effects.expected.json +0 -10
  115. package/conformance/invalid/forged-effects.udl +0 -76
  116. package/conformance/invalid/format-version.expected.json +0 -10
  117. package/conformance/invalid/format-version.udl +0 -54
  118. package/conformance/invalid/instrument-id-not-snake-case.expected.json +0 -10
  119. package/conformance/invalid/instrument-id-not-snake-case.udl +0 -54
  120. package/conformance/invalid/invalid-aggregate-gate-shape.expected.json +0 -10
  121. package/conformance/invalid/invalid-aggregate-gate-shape.udl +0 -1819
  122. package/conformance/invalid/invalid-check-duration.expected.json +0 -10
  123. package/conformance/invalid/invalid-check-duration.udl +0 -219
  124. package/conformance/invalid/invalid-dial-anchor.expected.json +0 -10
  125. package/conformance/invalid/invalid-dial-anchor.udl +0 -219
  126. package/conformance/invalid/invalid-exception-parent-ref.expected.json +0 -10
  127. package/conformance/invalid/invalid-exception-parent-ref.udl +0 -2487
  128. package/conformance/invalid/invalid-exposure-shape.expected.json +0 -10
  129. package/conformance/invalid/invalid-exposure-shape.udl +0 -1819
  130. package/conformance/invalid/invalid-remainder.expected.json +0 -10
  131. package/conformance/invalid/invalid-remainder.udl +0 -220
  132. package/conformance/invalid/invalid-schema-keyword.expected.json +0 -10
  133. package/conformance/invalid/invalid-schema-keyword.udl +0 -220
  134. package/conformance/invalid/invalid-utf8.expected.json +0 -10
  135. package/conformance/invalid/invalid-utf8.udl +0 -1
  136. package/conformance/invalid/malformed-json.expected.json +0 -10
  137. package/conformance/invalid/malformed-json.udl +0 -1
  138. package/conformance/invalid/missing-create-action.expected.json +0 -10
  139. package/conformance/invalid/missing-create-action.udl +0 -48
  140. package/conformance/invalid/missing-exception-amount-field.expected.json +0 -10
  141. package/conformance/invalid/missing-exception-amount-field.udl +0 -2487
  142. package/conformance/invalid/missing-exception-contract.expected.json +0 -14
  143. package/conformance/invalid/missing-exception-contract.udl +0 -2523
  144. package/conformance/invalid/missing-exception-reason-field.expected.json +0 -10
  145. package/conformance/invalid/missing-exception-reason-field.udl +0 -2487
  146. package/conformance/invalid/not-an-object.expected.json +0 -10
  147. package/conformance/invalid/not-an-object.udl +0 -1
  148. package/conformance/invalid/payout-reconcile-not-a-bank-debit.expected.json +0 -10
  149. package/conformance/invalid/payout-reconcile-not-a-bank-debit.udl +0 -259
  150. package/conformance/invalid/quote-freeze-set-incomplete.expected.json +0 -10
  151. package/conformance/invalid/quote-freeze-set-incomplete.udl +0 -261
  152. package/conformance/invalid/quote-named-reference-gate.expected.json +0 -10
  153. package/conformance/invalid/quote-named-reference-gate.udl +0 -50
  154. package/conformance/invalid/reconcile-named-reference-gate.expected.json +0 -10
  155. package/conformance/invalid/reconcile-named-reference-gate.udl +0 -50
  156. package/conformance/invalid/unknown-key.expected.json +0 -10
  157. package/conformance/invalid/unknown-key.udl +0 -55
  158. package/conformance/invalid/unknown-reference-gate-field.expected.json +0 -10
  159. package/conformance/invalid/unknown-reference-gate-field.udl +0 -1819
  160. package/conformance/invalid/unknown-required-field.expected.json +0 -10
  161. package/conformance/invalid/unknown-required-field.udl +0 -220
  162. package/conformance/invalid/unreachable-state.expected.json +0 -10
  163. package/conformance/invalid/unreachable-state.udl +0 -55
  164. package/conformance/invalid/wrong-exception-amount-field.expected.json +0 -10
  165. package/conformance/invalid/wrong-exception-amount-field.udl +0 -2487
  166. package/conformance/invalid/wrong-exception-reason-field.expected.json +0 -10
  167. package/conformance/invalid/wrong-exception-reason-field.udl +0 -2487
  168. package/conformance/valid/agent-description.expected.json +0 -6
  169. package/conformance/valid/agent-description.udl +0 -66
  170. package/conformance/valid/cards.expected.json +0 -6
  171. package/conformance/valid/cards.udl +0 -1579
  172. package/conformance/valid/commerce-escrow.expected.json +0 -6
  173. package/conformance/valid/commerce-escrow.udl +0 -1512
  174. package/conformance/valid/compiled-crowdfunding.expected.json +0 -6
  175. package/conformance/valid/compiled-crowdfunding.udl +0 -1843
  176. package/conformance/valid/compiled-watch-club.expected.json +0 -6
  177. package/conformance/valid/compiled-watch-club.udl +0 -2486
  178. package/conformance/valid/complete-contract.expected.json +0 -6
  179. package/conformance/valid/complete-contract.udl +0 -218
  180. package/conformance/valid/effect-signatures.expected.json +0 -6
  181. package/conformance/valid/effect-signatures.udl +0 -75
  182. package/conformance/valid/hand-edited.expected.json +0 -6
  183. package/conformance/valid/hand-edited.udl +0 -1
  184. package/conformance/valid/insured-car-marketplace.expected.json +0 -6
  185. package/conformance/valid/insured-car-marketplace.udl +0 -1050
  186. package/conformance/valid/insured-travel.expected.json +0 -6
  187. package/conformance/valid/insured-travel.udl +0 -3469
  188. package/conformance/valid/minimal.expected.json +0 -6
  189. package/conformance/valid/minimal.udl +0 -54
  190. package/conformance/valid/protection.expected.json +0 -6
  191. package/conformance/valid/protection.udl +0 -1551
  192. package/conformance/valid/string-escaping.expected.json +0 -6
  193. package/conformance/valid/string-escaping.udl +0 -54
  194. package/dist/check-profiles.d.ts +0 -57
  195. package/dist/check-profiles.d.ts.map +0 -1
  196. package/dist/check-profiles.js +0 -62
  197. package/dist/check-profiles.js.map +0 -1
  198. package/dist/cli.d.ts +0 -3
  199. package/dist/cli.d.ts.map +0 -1
  200. package/dist/cli.js +0 -184
  201. package/dist/cli.js.map +0 -1
  202. package/dist/effects.d.ts +0 -41
  203. package/dist/effects.d.ts.map +0 -1
  204. package/dist/effects.js +0 -110
  205. package/dist/effects.js.map +0 -1
  206. package/dist/evolution.d.ts +0 -120
  207. package/dist/evolution.d.ts.map +0 -1
  208. package/dist/evolution.js +0 -567
  209. package/dist/evolution.js.map +0 -1
  210. package/dist/parser.d.ts +0 -4
  211. package/dist/parser.d.ts.map +0 -1
  212. package/dist/parser.js +0 -44
  213. package/dist/parser.js.map +0 -1
  214. package/docs/README.md +0 -14
  215. package/docs/guide/01-a-document.md +0 -37
  216. package/docs/guide/02-money-steps.md +0 -23
  217. package/docs/guide/03-laws.md +0 -18
  218. package/docs/guide/04-fees-and-remainder.md +0 -15
  219. package/docs/guide/05-checks-updates-dials.md +0 -7
  220. package/docs/guide/06-effects.md +0 -11
  221. package/docs/guide/07-evolution.md +0 -11
  222. package/docs/guide/08-implementing.md +0 -13
  223. package/docs/llms-full.txt +0 -1241
  224. package/docs/llms.txt +0 -14
  225. package/docs/reference/canonical.md +0 -16
  226. package/docs/reference/clauses.md +0 -986
  227. package/docs/reference/cli.md +0 -22
  228. package/docs/reference/diagnostics.md +0 -32
  229. package/skills/udl/SKILL.md +0 -28
  230. package/src/check-profiles.ts +0 -80
  231. package/src/cli.ts +0 -196
  232. package/src/effects.ts +0 -163
  233. package/src/evolution.ts +0 -965
  234. package/src/parser.ts +0 -58
package/src/evolution.ts DELETED
@@ -1,965 +0,0 @@
1
- import { UDL_LIMITS } from "./limits.js";
2
- import { deriveUdlActionEffects } from "./effects.js";
3
- import type {
4
- UdlAggregate,
5
- UdlDocument,
6
- UdlInstrument,
7
- UdlAction,
8
- } from "./schema.js";
9
- import { udlClauseVocabulary } from "./schema.js";
10
- import { UdlError } from "./validation.js";
11
- import { issue, type UdlIssue } from "./diagnostics.js";
12
-
13
- export interface EvolutionFieldSnapshot {
14
- readonly required: boolean;
15
- readonly schema: unknown;
16
- }
17
-
18
- export interface EvolutionStepSnapshot {
19
- readonly bind: unknown;
20
- readonly capture: unknown;
21
- readonly operation: string;
22
- }
23
-
24
- export interface EvolutionMoveSnapshot extends EvolutionStepSnapshot {
25
- readonly key: string;
26
- }
27
-
28
- export interface EvolutionActionSnapshot {
29
- /** Missing on snapshots written before receipt-input capture existed. */
30
- readonly captureInput?: unknown;
31
- readonly deadline: unknown;
32
- readonly decision: unknown;
33
- /** Missing on snapshots written before UDL completeness. */
34
- readonly principal?: string | null;
35
- /** Missing on snapshots written before quote-commit existed. */
36
- readonly commit?: string | null;
37
- /** Missing on snapshots written before UDL completeness. */
38
- readonly remainder?: unknown;
39
- /** Missing on snapshots written before UDL completeness. */
40
- readonly requiresChecks?: unknown;
41
- /** Missing on snapshots written before UDL completeness. */
42
- readonly sandboxFailurePoint?: string | null;
43
- /** Missing on snapshots written before UDL completeness. */
44
- readonly updates?: readonly string[];
45
- /** Missing on snapshots written before weighted distribution existed. */
46
- readonly distribute?: unknown;
47
- readonly due: unknown;
48
- readonly earnable: boolean;
49
- /** Missing on snapshots written before derived effect rows entered UDL. */
50
- readonly effects?: unknown;
51
- readonly eventName: string | null;
52
- readonly input: Readonly<Record<string, EvolutionFieldSnapshot>> | null;
53
- /**
54
- * Every top-level input schema keyword EXCEPT properties/required (those are
55
- * diffed field by field). additionalProperties, string and array bounds,
56
- * numeric bounds, enum, const, pattern, and format change what callers may
57
- * send, so they are frozen once live.
58
- */
59
- readonly inputConstraints: unknown;
60
- /** Missing on snapshots written before payout intents existed. */
61
- readonly payout?: unknown;
62
- readonly port: unknown;
63
- /** Missing on snapshots written before public action metadata existed. */
64
- readonly publicAction?: string | null;
65
- readonly requiresAggregate: unknown;
66
- readonly requiresDrainedAccount: unknown;
67
- /** Missing on snapshots written before exposure gates entered open UDL. */
68
- readonly requiresExposure?: unknown;
69
- readonly requiresRefs: unknown;
70
- /** Missing on snapshots written before reconcile expectations existed. */
71
- readonly reconcile?: unknown;
72
- readonly setsAt: unknown;
73
- /** Missing on snapshots written before signed child sums existed. */
74
- readonly signedSum?: unknown;
75
- readonly moves: readonly EvolutionMoveSnapshot[];
76
- readonly steps: readonly EvolutionStepSnapshot[];
77
- }
78
-
79
- export interface EvolutionTransitionSnapshot {
80
- readonly from: readonly string[];
81
- readonly to: string;
82
- }
83
-
84
- /** The complete serializable algebra protected by append-only evolution. */
85
- export interface InstrumentEvolutionSnapshot {
86
- /** Missing on snapshots written before UDL carried authored action order. */
87
- readonly actionOrder?: readonly string[];
88
- readonly aggregateInvariants: readonly string[];
89
- /** Missing on snapshots written before UDL completeness. */
90
- readonly callerParkedStates?: Readonly<Record<string, string>>;
91
- readonly derivedAmounts: readonly string[];
92
- /** Missing on snapshots written before UDL completeness. */
93
- readonly dials?: unknown;
94
- readonly distinctParties?: true;
95
- /** Missing on snapshots written before unified fee rules entered UDL. */
96
- readonly feeRules?: unknown;
97
- readonly fields: Readonly<Record<string, EvolutionFieldSnapshot>>;
98
- readonly id: string;
99
- readonly idPrefix: string;
100
- readonly initial: string;
101
- /** Missing on snapshots written before UDL completeness. */
102
- readonly nav?: readonly string[];
103
- readonly parties: Readonly<Record<string, string>>;
104
- readonly partitions: readonly string[];
105
- readonly states: readonly string[];
106
- readonly subjects: readonly string[];
107
- /** Missing on snapshots written before UDL completeness. */
108
- readonly subjectExtensible?: boolean;
109
- /** Missing on snapshots written before UDL completeness. */
110
- readonly surfaceVisibility?: string | null;
111
- /** Missing on snapshots written before UDL completeness. */
112
- readonly templateId?: string | null;
113
- readonly transitions: Readonly<Record<string, EvolutionTransitionSnapshot>>;
114
- /** Every quote-commit pair, keyed by quoting action. */
115
- readonly quotes: unknown;
116
- readonly updateFields: readonly string[];
117
- /** Missing on snapshots written before UDL completeness. */
118
- readonly updateExamples?: unknown;
119
- readonly updateStates: readonly string[];
120
- readonly actions: Readonly<Record<string, EvolutionActionSnapshot>>;
121
- }
122
-
123
- /** Project an open .udl instrument into the evolution engine's exact semantic shape. */
124
- export function snapshotUdlInstrument(
125
- instrument: UdlInstrument,
126
- ): InstrumentEvolutionSnapshot {
127
- const required = new Set(instrument.required);
128
- return {
129
- actionOrder: [...instrument.actionOrder],
130
- aggregateInvariants: (instrument.aggregateInvariants ?? []).map(
131
- aggregateInvariantKey,
132
- ),
133
- callerParkedStates: instrument.callerParkedStates ?? {},
134
- derivedAmounts: (instrument.derivedAmounts ?? []).map(
135
- (amount) =>
136
- `${amount.field}=floor(${amount.sourceField}*${amount.rule.bps}/10000)`,
137
- ),
138
- dials: instrument.dials ?? [],
139
- ...(instrument.distinctParties ? { distinctParties: true as const } : {}),
140
- ...(instrument.feeRules
141
- ? {
142
- feeRules: instrument.feeRules.map((fee) => ({
143
- ...fee,
144
- rule:
145
- fee.rule.kind === "tiered"
146
- ? {
147
- ...fee.rule,
148
- tiers: fee.rule.tiers.map((tier) => ({
149
- ...tier,
150
- rule: { ...tier.rule },
151
- })),
152
- }
153
- : { ...fee.rule },
154
- })),
155
- }
156
- : {}),
157
- fields: Object.fromEntries(
158
- Object.entries(instrument.fields).map(([field, schema]) => [
159
- field,
160
- { required: required.has(field), schema },
161
- ]),
162
- ),
163
- id: instrument.id,
164
- idPrefix: instrument.idPrefix,
165
- initial: instrument.lifecycle.initial,
166
- nav: instrument.nav ?? [],
167
- parties: compactStringRecord(instrument.parties),
168
- partitions: (instrument.partitions ?? []).map(
169
- (partition) =>
170
- `${partition.totalField} = ${[...partition.pieceFields].sort().join(" + ")}`,
171
- ),
172
- states: [...instrument.lifecycle.states],
173
- subjects: instrument.subject ? [...instrument.subject.kinds] : [],
174
- subjectExtensible: instrument.subject?.extensible ?? false,
175
- surfaceVisibility: instrument.surfaceVisibility ?? null,
176
- templateId: instrument.templateId ?? null,
177
- transitions: Object.fromEntries(
178
- Object.entries(instrument.lifecycle.transitions).map(
179
- ([action, transition]) => [
180
- action,
181
- { from: [...transition.from], to: transition.to },
182
- ],
183
- ),
184
- ),
185
- quotes: Object.fromEntries(
186
- Object.entries(instrument.actions)
187
- .filter(([, action]) => action.quote)
188
- .map(([name, action]) => [name, action.quote]),
189
- ),
190
- updateFields: instrument.update?.fields ?? [],
191
- updateExamples: instrument.update?.examples ?? null,
192
- updateStates: instrument.update?.states ?? [],
193
- actions: Object.fromEntries(
194
- instrument.actionOrder.map((action) => [
195
- action,
196
- snapshotUdlAction(instrument.actions[action]!),
197
- ]),
198
- ),
199
- };
200
- }
201
-
202
- /**
203
- * Compare two product definitions under the append-only evolution law.
204
- *
205
- * Both documents must already have passed `validateUdl`. The diff walks
206
- * straight into `stableStringify`, so an unvalidated document with a cycle in
207
- * it throws a RangeError out of here where the validator would have returned a
208
- * clean `resource_limit` issue: parse first, then diff.
209
- */
210
- export function diffValidatedUdlEvolution(
211
- previous: UdlDocument,
212
- next: UdlDocument,
213
- ): readonly UdlIssue[] {
214
- return diffValidatedUdlEvolutionMessages(previous, next).map((message) => {
215
- const instrumentId = /^([^:]+): /.exec(message)?.[1];
216
- const instrumentIndex = previous.instruments.findIndex(
217
- (instrument) => instrument.id === instrumentId,
218
- );
219
- const base =
220
- instrumentIndex < 0
221
- ? "$.instruments"
222
- : `$.instruments[${instrumentIndex}]`;
223
- return evolutionIssue(message, base);
224
- });
225
- }
226
-
227
- function diffValidatedUdlEvolutionMessages(
228
- previous: UdlDocument,
229
- next: UdlDocument,
230
- ): readonly string[] {
231
- const violations: string[] = [];
232
- if (previous.product !== next.product) {
233
- violations.push(
234
- `product id changed from ${previous.product} to ${next.product}`,
235
- );
236
- }
237
- if (next.version < previous.version) {
238
- violations.push(
239
- `product version moved backward from ${previous.version} to ${next.version}`,
240
- );
241
- }
242
-
243
- let semanticChange = false;
244
- const previousSubjects = new Map(
245
- previous.subjects.map((subject) => [subject.kind, subject] as const),
246
- );
247
- const nextSubjects = new Map(
248
- next.subjects.map((subject) => [subject.kind, subject] as const),
249
- );
250
- for (const [kind, subject] of previousSubjects) {
251
- const current = nextSubjects.get(kind);
252
- if (!current) {
253
- semanticChange = true;
254
- violations.push(`subject kind ${kind} was removed or renamed`);
255
- } else if (stableStringify(subject) !== stableStringify(current)) {
256
- semanticChange = true;
257
- violations.push(`subject kind ${kind} changed after becoming live`);
258
- }
259
- }
260
- for (const kind of nextSubjects.keys()) {
261
- if (!previousSubjects.has(kind)) semanticChange = true;
262
- }
263
-
264
- const previousInstruments = new Map(
265
- previous.instruments.map(
266
- (instrument) =>
267
- [instrument.id, snapshotUdlInstrument(instrument)] as const,
268
- ),
269
- );
270
- const nextInstruments = new Map(
271
- next.instruments.map(
272
- (instrument) =>
273
- [instrument.id, snapshotUdlInstrument(instrument)] as const,
274
- ),
275
- );
276
- for (const [id, instrument] of previousInstruments) {
277
- const current = nextInstruments.get(id);
278
- if (!current) {
279
- semanticChange = true;
280
- violations.push(`${id}: live instrument was removed from the product`);
281
- continue;
282
- }
283
- if (stableStringify(instrument) !== stableStringify(current)) {
284
- semanticChange = true;
285
- }
286
- violations.push(...diffInstrumentEvolutionMessages(instrument, current));
287
- }
288
- for (const id of nextInstruments.keys()) {
289
- if (!previousInstruments.has(id)) semanticChange = true;
290
- }
291
-
292
- if (semanticChange && next.version <= previous.version) {
293
- violations.push(
294
- `product definition changed without increasing version ${previous.version}`,
295
- );
296
- }
297
- return violations;
298
- }
299
-
300
- /** Diff one instrument snapshot. An empty result means the change is additive. */
301
- export function diffInstrumentEvolution(
302
- previous: InstrumentEvolutionSnapshot,
303
- next: InstrumentEvolutionSnapshot,
304
- ): readonly UdlIssue[] {
305
- return diffInstrumentEvolutionMessages(previous, next).map((message) =>
306
- evolutionIssue(message, "$.instruments"),
307
- );
308
- }
309
-
310
- function diffInstrumentEvolutionMessages(
311
- previous: InstrumentEvolutionSnapshot,
312
- next: InstrumentEvolutionSnapshot,
313
- ): readonly string[] {
314
- if (previous.id !== next.id) {
315
- return [`instrument id changed from ${previous.id} to ${next.id}`];
316
- }
317
- const violations: string[] = [];
318
- if (previous.idPrefix !== next.idPrefix) {
319
- violations.push(
320
- `instance id prefix changed from ${previous.idPrefix} to ${next.idPrefix}`,
321
- );
322
- }
323
- if (previous.initial !== next.initial) {
324
- violations.push(
325
- `initial lifecycle state changed from ${previous.initial} to ${next.initial}`,
326
- );
327
- }
328
-
329
- violations.push(
330
- ...removedSetEntries(
331
- previous.states,
332
- next.states,
333
- (state) => `lifecycle state ${state} was removed or renamed`,
334
- ),
335
- );
336
- for (const [action, transition] of Object.entries(previous.transitions)) {
337
- const current = next.transitions[action];
338
- if (!current) {
339
- violations.push(`transition for action ${action} was removed or renamed`);
340
- continue;
341
- }
342
- if (transition.to !== current.to) {
343
- violations.push(
344
- `transition for action ${action} changed its target state from ${transition.to} to ${current.to}`,
345
- );
346
- }
347
- violations.push(
348
- ...removedSetEntries(
349
- transition.from,
350
- current.from,
351
- (state) =>
352
- `transition for action ${action} no longer fires from state ${state}`,
353
- ),
354
- );
355
- }
356
-
357
- violations.push(...diffFields(previous.fields, next.fields));
358
- if (Boolean(previous.distinctParties) !== Boolean(next.distinctParties)) {
359
- violations.push("distinct-party admission changed after becoming live");
360
- }
361
- if (previous.actionOrder) {
362
- const previousActions = new Set(previous.actionOrder);
363
- const retainedActionOrder = (next.actionOrder ?? []).filter((action) =>
364
- previousActions.has(action),
365
- );
366
- if (
367
- stableStringify(previous.actionOrder) !==
368
- stableStringify(retainedActionOrder)
369
- ) {
370
- violations.push("instrument action order changed after becoming live");
371
- }
372
- }
373
- violations.push(...diffActions(previous.actions, next.actions));
374
- violations.push(...diffParties(previous.parties, next.parties));
375
- violations.push(...diffAggregates(previous, next));
376
- if (
377
- stableStringify(Object.keys(previous.callerParkedStates ?? {}).sort()) !==
378
- stableStringify(Object.keys(next.callerParkedStates ?? {}).sort())
379
- ) {
380
- violations.push("caller-parked state annotations changed");
381
- }
382
- if (
383
- stableStringify(previous.dials ?? []) !== stableStringify(next.dials ?? [])
384
- ) {
385
- violations.push("instrument dials changed after becoming live");
386
- }
387
- if (
388
- (previous.surfaceVisibility ?? null) !== (next.surfaceVisibility ?? null)
389
- ) {
390
- violations.push(
391
- "instrument surface visibility changed after becoming live",
392
- );
393
- }
394
- if ((previous.templateId ?? null) !== (next.templateId ?? null)) {
395
- violations.push(
396
- "instrument archetype template changed after becoming live",
397
- );
398
- }
399
- if (previous.subjectExtensible && !next.subjectExtensible) {
400
- violations.push("tenant-defined subject kinds are no longer accepted");
401
- }
402
- if (
403
- stableStringify(previous.derivedAmounts ?? []) !==
404
- stableStringify(next.derivedAmounts ?? [])
405
- ) {
406
- violations.push(
407
- "derived amount rules changed; derived money arithmetic is frozen once live",
408
- );
409
- }
410
- if (
411
- stableStringify(previous.feeRules ?? []) !==
412
- stableStringify(next.feeRules ?? [])
413
- ) {
414
- violations.push(
415
- "feeRules changed; fee calculation and settlement funding are frozen once live",
416
- );
417
- }
418
- violations.push(
419
- ...removedSetEntries(
420
- previous.partitions,
421
- next.partitions,
422
- (law) => `partition law [${law}] was removed`,
423
- ),
424
- ...next.partitions
425
- .filter((law) => !previous.partitions.includes(law))
426
- .map(
427
- (law) =>
428
- `partition law [${law}] was added, which can reject existing callers`,
429
- ),
430
- );
431
- violations.push(...diffQuotes(previous.quotes, next.quotes));
432
- violations.push(
433
- ...removedSetEntries(
434
- previous.subjects,
435
- next.subjects,
436
- (kind) => `subject kind ${kind} was removed, rejecting linked instances`,
437
- ),
438
- ...removedSetEntries(
439
- previous.updateFields,
440
- next.updateFields,
441
- (field) => `update policy no longer permits field ${field}`,
442
- ),
443
- ...removedSetEntries(
444
- previous.updateStates,
445
- next.updateStates,
446
- (state) => `update policy no longer permits state ${state}`,
447
- ),
448
- );
449
- return violations.map((violation) => `${next.id}: ${violation}`);
450
- }
451
-
452
- function evolutionIssue(message: string, instrumentBase: string): UdlIssue {
453
- if (message.startsWith("product id changed"))
454
- return issue("UDL7001", "$.product", message);
455
- if (message.startsWith("product version moved backward"))
456
- return issue("UDL7001", "$.version", message);
457
- if (message.startsWith("product definition changed"))
458
- return issue("UDL7002", "$.version", message);
459
- if (message.startsWith("subject kind "))
460
- return issue("UDL7001", "$.subjects", message);
461
-
462
- const instrumentMatch = /^([^:]+): (.*)$/.exec(message);
463
- const detail = instrumentMatch?.[2] ?? message;
464
- const transitionAction = /^transition for action ([a-z][a-z0-9_]*)/.exec(
465
- detail,
466
- )?.[1];
467
- if (transitionAction)
468
- return issue(
469
- "UDL7001",
470
- `${instrumentBase}.lifecycle.transitions.${transitionAction}`,
471
- message,
472
- );
473
- const action = /^action ([a-z][a-z0-9_]*)/.exec(detail)?.[1];
474
- if (action)
475
- return issue("UDL7001", `${instrumentBase}.actions.${action}`, message);
476
- if (detail.includes("instrument id"))
477
- return issue("UDL7001", instrumentBase, message);
478
- if (
479
- detail.includes("id prefix") ||
480
- detail.includes("lifecycle") ||
481
- detail.includes("transition") ||
482
- detail.includes("initial") ||
483
- detail.includes("live instrument was removed")
484
- )
485
- return issue("UDL7001", `${instrumentBase}.lifecycle`, message);
486
- if (detail.startsWith("field "))
487
- return issue("UDL7001", `${instrumentBase}.fields`, message);
488
- if (
489
- detail.includes("move") ||
490
- detail.includes("payout") ||
491
- detail.includes("fee") ||
492
- detail.includes("quote") ||
493
- detail.includes("derived amount") ||
494
- detail.includes("partition") ||
495
- detail.includes("distribution") ||
496
- detail.includes("signed child sum") ||
497
- detail.includes("earnable")
498
- )
499
- return issue("UDL7001", `${instrumentBase}.actions`, message);
500
- if (
501
- detail.includes("gate") ||
502
- detail.includes("check prerequisite") ||
503
- detail.includes("reconcile expectation") ||
504
- detail.includes("drained-account") ||
505
- detail.includes("exposure") ||
506
- detail.includes("aggregate")
507
- )
508
- return issue("UDL7001", `${instrumentBase}.actions`, message);
509
- if (
510
- detail.startsWith("action ") ||
511
- detail.includes("action order") ||
512
- detail.includes("step count")
513
- )
514
- return issue("UDL7001", `${instrumentBase}.actions`, message);
515
- return issue("UDL7001", instrumentBase, message);
516
- }
517
-
518
- function snapshotUdlAction(definition: UdlAction): EvolutionActionSnapshot {
519
- return {
520
- captureInput: definition.captureInput ?? null,
521
- commit: definition.commit ?? null,
522
- deadline: definition.deadline ?? null,
523
- decision: definition.decision ?? null,
524
- principal: definition.principal ?? null,
525
- remainder: definition.remainder ?? null,
526
- requiresChecks: definition.requiresChecks ?? [],
527
- sandboxFailurePoint: definition.sandboxFailurePoint ?? null,
528
- updates: definition.updates ?? [],
529
- distribute: definition.distribute ?? null,
530
- due: definition.due ?? null,
531
- earnable: definition.earnable ?? false,
532
- effects:
533
- definition.effects ??
534
- deriveUdlActionEffects(definition, udlClauseVocabulary),
535
- eventName: definition.eventName ?? null,
536
- input: definition.input ? snapshotJsonSchemaFields(definition.input) : null,
537
- inputConstraints: definition.input
538
- ? snapshotJsonSchemaConstraints(definition.input)
539
- : null,
540
- payout: definition.payout ?? null,
541
- port: definition.port ?? null,
542
- publicAction: definition.publicAction ?? null,
543
- setsAt: definition.setsAt ?? null,
544
- signedSum: definition.signedSum ?? null,
545
- moves: definition.moves.map((move) => ({
546
- bind: move.bind,
547
- capture: move.capture ?? {},
548
- key: move.key,
549
- operation: move.operation,
550
- })),
551
- requiresAggregate: definition.requiresAggregate ?? [],
552
- requiresDrainedAccount: definition.requiresDrainedAccount ?? null,
553
- requiresExposure: definition.requiresExposure ?? [],
554
- requiresRefs: definition.requiresRefs ?? [],
555
- reconcile: definition.reconcile ?? null,
556
- steps: definition.steps.map((step) => ({
557
- bind: step.bind,
558
- capture: step.capture ?? {},
559
- operation: step.operation,
560
- })),
561
- };
562
- }
563
-
564
- function snapshotJsonSchemaFields(
565
- schema: Readonly<Record<string, unknown>>,
566
- ): Readonly<Record<string, EvolutionFieldSnapshot>> {
567
- const properties = recordValue(schema.properties);
568
- const required = new Set(
569
- Array.isArray(schema.required)
570
- ? schema.required.filter(
571
- (value): value is string => typeof value === "string",
572
- )
573
- : [],
574
- );
575
- return Object.fromEntries(
576
- Object.entries(properties).map(([field, fieldSchema]) => [
577
- field,
578
- { required: required.has(field), schema: fieldSchema },
579
- ]),
580
- );
581
- }
582
-
583
- function snapshotJsonSchemaConstraints(
584
- schema: Readonly<Record<string, unknown>>,
585
- ): Readonly<Record<string, unknown>> {
586
- const {
587
- properties: _properties,
588
- required: _required,
589
- ...constraints
590
- } = schema;
591
- return constraints;
592
- }
593
-
594
- function diffFields(
595
- previous: Readonly<Record<string, EvolutionFieldSnapshot>>,
596
- next: Readonly<Record<string, EvolutionFieldSnapshot>>,
597
- ): string[] {
598
- const violations: string[] = [];
599
- for (const [field, descriptor] of Object.entries(previous)) {
600
- const current = next[field];
601
- if (!current) {
602
- violations.push(`field ${field} was removed or renamed`);
603
- continue;
604
- }
605
- if (!descriptor.required && current.required) {
606
- violations.push(`field ${field} became required, tightening the schema`);
607
- }
608
- if (
609
- stableStringify(descriptor.schema) !== stableStringify(current.schema)
610
- ) {
611
- violations.push(
612
- `field ${field} schema changed; a live field schema is frozen`,
613
- );
614
- }
615
- }
616
- for (const [field, descriptor] of Object.entries(next)) {
617
- if (!previous[field] && descriptor.required) {
618
- violations.push(
619
- `field ${field} was added as required, which rejects existing instances (only optional fields are additive)`,
620
- );
621
- }
622
- }
623
- return violations;
624
- }
625
-
626
- function diffActions(
627
- previous: Readonly<Record<string, EvolutionActionSnapshot>>,
628
- next: Readonly<Record<string, EvolutionActionSnapshot>>,
629
- ): string[] {
630
- const violations: string[] = [];
631
- for (const [action, descriptor] of Object.entries(previous)) {
632
- const current = next[action];
633
- if (!current) {
634
- violations.push(`action ${action} was removed or renamed`);
635
- continue;
636
- }
637
- if (descriptor.moves.length !== current.moves.length) {
638
- violations.push(
639
- `action ${action} changed its move count from ${descriptor.moves.length} to ${current.moves.length}; money movement is frozen once live`,
640
- );
641
- } else {
642
- descriptor.moves.forEach((move, index) => {
643
- const nextMove = current.moves[index] as EvolutionMoveSnapshot;
644
- if (stableStringify(move) !== stableStringify(nextMove)) {
645
- violations.push(
646
- `action ${action} changed move ${move.key} at index ${index}; money movement is frozen once live`,
647
- );
648
- }
649
- });
650
- }
651
- if (descriptor.steps.length !== current.steps.length) {
652
- violations.push(
653
- `action ${action} changed its step count from ${descriptor.steps.length} to ${current.steps.length}; a live action's steps are frozen`,
654
- );
655
- } else {
656
- descriptor.steps.forEach((step, index) => {
657
- const nextStep = current.steps[index] as EvolutionStepSnapshot;
658
- if (stableStringify(step) === stableStringify(nextStep)) return;
659
- violations.push(
660
- `action ${action} changed step ${index} (${step.operation}); a live action's steps are frozen`,
661
- );
662
- });
663
- }
664
- violations.push(
665
- ...diffInput(action, descriptor.input ?? {}, current.input ?? {}),
666
- );
667
- // A action gaining its first input is additive (per-field checks still catch
668
- // added-as-required); once an input is live, its schema envelope is frozen.
669
- if (
670
- descriptor.input !== null &&
671
- stableStringify(descriptor.inputConstraints) !==
672
- stableStringify(current.inputConstraints)
673
- ) {
674
- violations.push(
675
- `action ${action} changed its input schema beyond declared fields; a live action input is frozen`,
676
- );
677
- }
678
- if (
679
- stableStringify(descriptor.requiresRefs) !==
680
- stableStringify(current.requiresRefs)
681
- ) {
682
- violations.push(`action ${action} changed its cross-instrument gates`);
683
- }
684
- if (
685
- stableStringify(descriptor.requiresAggregate) !==
686
- stableStringify(current.requiresAggregate)
687
- ) {
688
- violations.push(`action ${action} changed its aggregate admission gates`);
689
- }
690
- if (
691
- stableStringify(descriptor.requiresDrainedAccount) !==
692
- stableStringify(current.requiresDrainedAccount)
693
- ) {
694
- violations.push(`action ${action} changed its drained-account gate`);
695
- }
696
- if (
697
- descriptor.requiresExposure !== undefined &&
698
- stableStringify(descriptor.requiresExposure) !==
699
- stableStringify(current.requiresExposure)
700
- ) {
701
- violations.push(`action ${action} changed its exposure admission gates`);
702
- }
703
- if (
704
- descriptor.reconcile !== undefined &&
705
- stableStringify(descriptor.reconcile) !==
706
- stableStringify(current.reconcile)
707
- ) {
708
- violations.push(`action ${action} changed its reconcile expectations`);
709
- }
710
- if (
711
- stableStringify(descriptor.payout ?? null) !==
712
- stableStringify(current.payout ?? null)
713
- ) {
714
- violations.push(`action ${action} changed its payout intent`);
715
- }
716
- if (descriptor.earnable !== current.earnable) {
717
- violations.push(`action ${action} changed its earnable flag`);
718
- }
719
- if (
720
- descriptor.effects !== undefined &&
721
- stableStringify(descriptor.effects) !== stableStringify(current.effects)
722
- ) {
723
- violations.push(`action ${action} changed its derived effects`);
724
- }
725
- if (descriptor.eventName !== current.eventName) {
726
- violations.push(`action ${action} changed its event name`);
727
- }
728
- if (stableStringify(descriptor.due) !== stableStringify(current.due)) {
729
- violations.push(`action ${action} changed its due condition`);
730
- }
731
- if (
732
- stableStringify(descriptor.deadline) !== stableStringify(current.deadline)
733
- ) {
734
- violations.push(`action ${action} changed its admission deadline`);
735
- }
736
- if (
737
- stableStringify(descriptor.decision) !== stableStringify(current.decision)
738
- ) {
739
- violations.push(`action ${action} changed its provider decision`);
740
- }
741
- if ((descriptor.principal ?? null) !== (current.principal ?? null)) {
742
- violations.push(`action ${action} changed its caller principal`);
743
- }
744
- if (
745
- stableStringify(descriptor.remainder ?? null) !==
746
- stableStringify(current.remainder ?? null)
747
- ) {
748
- violations.push(`action ${action} changed its remainder rule`);
749
- }
750
- if (
751
- stableStringify(descriptor.requiresChecks ?? []) !==
752
- stableStringify(current.requiresChecks ?? [])
753
- ) {
754
- violations.push(`action ${action} changed its check prerequisites`);
755
- }
756
- if (
757
- (descriptor.sandboxFailurePoint ?? null) !==
758
- (current.sandboxFailurePoint ?? null)
759
- ) {
760
- violations.push(`action ${action} changed its sandbox failure point`);
761
- }
762
- if (
763
- stableStringify(descriptor.updates ?? []) !==
764
- stableStringify(current.updates ?? [])
765
- ) {
766
- violations.push(`action ${action} changed its field updates`);
767
- }
768
- if (
769
- stableStringify(descriptor.distribute) !==
770
- stableStringify(current.distribute)
771
- ) {
772
- violations.push(
773
- `action ${action} changed its distribution rule; money distribution is frozen once live`,
774
- );
775
- }
776
- if (
777
- descriptor.captureInput !== undefined &&
778
- stableStringify(descriptor.captureInput) !==
779
- stableStringify(current.captureInput)
780
- ) {
781
- violations.push(`action ${action} changed its captured receipt input`);
782
- }
783
- if (stableStringify(descriptor.port) !== stableStringify(current.port)) {
784
- violations.push(`action ${action} changed its decision port`);
785
- }
786
- if (
787
- descriptor.publicAction != null &&
788
- descriptor.publicAction !== current.publicAction
789
- ) {
790
- violations.push(`action ${action} changed its public action`);
791
- }
792
- if (
793
- stableStringify(descriptor.setsAt) !== stableStringify(current.setsAt)
794
- ) {
795
- violations.push(`action ${action} changed its computed timestamp`);
796
- }
797
- if (
798
- descriptor.signedSum !== undefined &&
799
- stableStringify(descriptor.signedSum) !==
800
- stableStringify(current.signedSum)
801
- ) {
802
- violations.push(`action ${action} changed its signed child sum`);
803
- }
804
- }
805
- for (const [action, descriptor] of Object.entries(next)) {
806
- if (previous[action] || descriptor.payout == null) continue;
807
- violations.push(
808
- `action ${action} added a payout intent; external money movement is frozen once live`,
809
- );
810
- }
811
- return violations;
812
- }
813
-
814
- function diffInput(
815
- action: string,
816
- previous: Readonly<Record<string, EvolutionFieldSnapshot>>,
817
- next: Readonly<Record<string, EvolutionFieldSnapshot>>,
818
- ): string[] {
819
- const violations: string[] = [];
820
- for (const [field, descriptor] of Object.entries(previous)) {
821
- const current = next[field];
822
- if (!current) {
823
- // Compiled action inputs are strict objects, so a removed field starts
824
- // rejecting every caller that still sends it -- same law as instrument fields.
825
- violations.push(
826
- `action ${action} input field ${field} was removed or renamed`,
827
- );
828
- continue;
829
- }
830
- if (!descriptor.required && current.required) {
831
- violations.push(
832
- `action ${action} input field ${field} became required, tightening the action input`,
833
- );
834
- }
835
- if (
836
- stableStringify(descriptor.schema) !== stableStringify(current.schema)
837
- ) {
838
- violations.push(
839
- `action ${action} input field ${field} schema changed; a live action input schema is frozen`,
840
- );
841
- }
842
- }
843
- for (const [field, descriptor] of Object.entries(next)) {
844
- if (!previous[field] && descriptor.required) {
845
- violations.push(
846
- `action ${action} input field ${field} was added as required, tightening the action input`,
847
- );
848
- }
849
- }
850
- return violations;
851
- }
852
-
853
- function diffParties(
854
- previous: Readonly<Record<string, string>>,
855
- next: Readonly<Record<string, string>>,
856
- ): string[] {
857
- const violations: string[] = [];
858
- for (const [role, field] of Object.entries(previous)) {
859
- const current = next[role];
860
- if (!current) violations.push(`party role ${role} was removed or renamed`);
861
- else if (current !== field) {
862
- violations.push(
863
- `party role ${role} moved from field ${field} to ${current}`,
864
- );
865
- }
866
- }
867
- return violations;
868
- }
869
-
870
- function diffAggregates(
871
- previous: InstrumentEvolutionSnapshot,
872
- next: InstrumentEvolutionSnapshot,
873
- ): string[] {
874
- return [
875
- ...removedSetEntries(
876
- previous.aggregateInvariants,
877
- next.aggregateInvariants,
878
- (key) => `aggregate invariant [${key}] was removed`,
879
- ),
880
- ...next.aggregateInvariants
881
- .filter((key) => !previous.aggregateInvariants.includes(key))
882
- .map(
883
- (key) =>
884
- `aggregate invariant [${key}] was added, which can reject existing instances`,
885
- ),
886
- ];
887
- }
888
-
889
- function diffQuotes(previous: unknown, next: unknown): string[] {
890
- if (previous === null || previous === undefined) return [];
891
- if (next === null || next === undefined) return ["quote policy was removed"];
892
- return stableStringify(previous) === stableStringify(next)
893
- ? []
894
- : [
895
- "quote policy changed; the charge schedule, the frozen fields, and the refund destination are frozen once live",
896
- ];
897
- }
898
-
899
- function aggregateInvariantKey(invariant: UdlAggregate): string {
900
- const measure =
901
- "childField" in invariant
902
- ? invariant.childField
903
- : `count${invariant.window ? `[${invariant.window.field} per ${invariant.window.days}d]` : ""}`;
904
- return `${invariant.childInstrumentId}.${measure} within ${invariant.parentField} via ${invariant.childRefField} while ${[...invariant.childStatuses].sort().join(",")}`;
905
- }
906
-
907
- function removedSetEntries(
908
- previous: readonly string[],
909
- next: readonly string[],
910
- message: (entry: string) => string,
911
- ): string[] {
912
- const current = new Set(next);
913
- return previous.filter((entry) => !current.has(entry)).map(message);
914
- }
915
-
916
- function compactStringRecord(
917
- value: Readonly<Record<string, string | undefined>> | undefined,
918
- ): Readonly<Record<string, string>> {
919
- return Object.fromEntries(
920
- Object.entries(value ?? {}).filter(
921
- (entry): entry is [string, string] => typeof entry[1] === "string",
922
- ),
923
- );
924
- }
925
-
926
- function recordValue(value: unknown): Readonly<Record<string, unknown>> {
927
- return value !== null && typeof value === "object" && !Array.isArray(value)
928
- ? (value as Readonly<Record<string, unknown>>)
929
- : {};
930
- }
931
-
932
- /**
933
- * The comparison key every diff above is written against. It recurses, so it
934
- * carries the same depth budget the validator applies to a document: a
935
- * snapshot is never deeper than the document it came from, and the deepest
936
- * conformance document reaches 12 of the 24 levels. A cycle is infinite depth
937
- * and lands here rather than exhausting the call stack.
938
- */
939
- function stableStringify(value: unknown, depth = 1): string {
940
- if (depth > UDL_LIMITS.maxDepth) {
941
- throw new UdlError([
942
- issue(
943
- "UDL1004",
944
- "$",
945
- `UDL nesting exceeds ${UDL_LIMITS.maxDepth} levels`,
946
- ),
947
- ]);
948
- }
949
- if (value === null || typeof value !== "object") {
950
- return JSON.stringify(value) ?? "null";
951
- }
952
- if (Array.isArray(value)) {
953
- // An arrow, not a bare reference: `map` would pass the index as the depth.
954
- return `[${value.map((item) => stableStringify(item, depth + 1)).join(",")}]`;
955
- }
956
- const entries = Object.entries(value as Record<string, unknown>)
957
- .filter(([, entry]) => entry !== undefined)
958
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
959
- return `{${entries
960
- .map(
961
- ([key, entry]) =>
962
- `${JSON.stringify(key)}:${stableStringify(entry, depth + 1)}`,
963
- )
964
- .join(",")}}`;
965
- }