@niscorp/prism 0.2.0 → 0.2.2

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 (43) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/DESIGN.md +2 -1
  3. package/DOCS.md +29 -0
  4. package/README.md +49 -3
  5. package/dist/agent.cjs +4 -756
  6. package/dist/agent.cjs.map +1 -1
  7. package/dist/agent.js +2 -2
  8. package/dist/chunk-26VYDHHC.cjs +784 -0
  9. package/dist/chunk-26VYDHHC.cjs.map +1 -0
  10. package/dist/{chunk-BRIXDNJQ.js → chunk-O3OJAQWA.js} +3 -3
  11. package/dist/chunk-O3OJAQWA.js.map +1 -0
  12. package/dist/chunk-V426VIRI.cjs +1168 -0
  13. package/dist/chunk-V426VIRI.cjs.map +1 -0
  14. package/dist/{chunk-3GAYBBNH.js → chunk-VC4PRB4H.js} +21 -4
  15. package/dist/chunk-VC4PRB4H.js.map +1 -0
  16. package/dist/chunk-W32JXP33.cjs +147 -0
  17. package/dist/chunk-W32JXP33.cjs.map +1 -0
  18. package/dist/{chunk-3PYQITGE.js → chunk-XRK55NPE.js} +3 -3
  19. package/dist/{chunk-3PYQITGE.js.map → chunk-XRK55NPE.js.map} +1 -1
  20. package/dist/examples/index.cjs +1543 -0
  21. package/dist/examples/index.cjs.map +1 -0
  22. package/dist/examples/index.d.cts +26 -0
  23. package/dist/examples/index.d.ts +26 -0
  24. package/dist/examples/index.js +1540 -0
  25. package/dist/examples/index.js.map +1 -0
  26. package/dist/index.cjs +190 -2048
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +5 -82
  29. package/dist/index.d.ts +5 -82
  30. package/dist/index.js +5 -5
  31. package/dist/migrations/index.cjs +7 -1775
  32. package/dist/migrations/index.cjs.map +1 -1
  33. package/dist/migrations/index.d.cts +3 -2
  34. package/dist/migrations/index.d.ts +3 -2
  35. package/dist/migrations/index.js +3 -18
  36. package/dist/migrations/index.js.map +1 -1
  37. package/dist/profiles-C6r-x-Vj.d.cts +83 -0
  38. package/dist/profiles-C6r-x-Vj.d.ts +83 -0
  39. package/dist/transform-DcVcOBzQ.d.cts +3 -0
  40. package/dist/transform-DcVcOBzQ.d.ts +3 -0
  41. package/package.json +19 -8
  42. package/dist/chunk-3GAYBBNH.js.map +0 -1
  43. package/dist/chunk-BRIXDNJQ.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,1779 +1,15 @@
1
1
  'use strict';
2
2
 
3
- var zod = require('zod');
3
+ var chunkW32JXP33_cjs = require('./chunk-W32JXP33.cjs');
4
+ var chunkV426VIRI_cjs = require('./chunk-V426VIRI.cjs');
5
+ var chunk26VYDHHC_cjs = require('./chunk-26VYDHHC.cjs');
4
6
  var strata = require('@niscorp/strata');
5
- var dayjs = require('dayjs');
6
- var utc = require('dayjs/plugin/utc.js');
7
-
8
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
-
10
- var dayjs__default = /*#__PURE__*/_interopDefault(dayjs);
11
- var utc__default = /*#__PURE__*/_interopDefault(utc);
12
-
13
- // src/utils/issues.ts
14
- var segmentsOf = (path) => path.map((p) => typeof p === "number" ? p : String(p));
15
- var explainOne = (issue, prefix) => {
16
- const here = [...prefix, ...segmentsOf(issue.path)];
17
- if (issue.code === "invalid_key") return [{ path: here, message: issue.issues[0]?.message ?? issue.message }];
18
- if (issue.code !== "invalid_union" || issue.errors.length === 0) return [{ path: here, message: issue.message }];
19
- let best = [];
20
- let bestDepth = -1;
21
- for (const branch of issue.errors) {
22
- const explained = branch.flatMap((i) => explainOne(i, here));
23
- const depth = Math.max(...explained.map((e) => e.path.length));
24
- if (depth > bestDepth || depth === bestDepth && explained.length < best.length) {
25
- best = explained;
26
- bestDepth = depth;
27
- }
28
- }
29
- return bestDepth <= here.length ? [{ path: here, message: "Not a Prism node: no op matches, and it is not a plain value." }] : best;
30
- };
31
- var explainIssues = (issues) => issues.flatMap((i) => explainOne(i, []));
32
- var JsonPrimitiveSchema = zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean(), zod.z.null()]).describe("JSON primitive: string | number | boolean | null");
33
- var JsonValueSchema = zod.z.lazy(
34
- () => zod.z.union([JsonPrimitiveSchema, zod.z.array(JsonValueSchema), zod.z.record(zod.z.string(), JsonValueSchema)])
35
- ).describe("Any JSON value: primitive, array, or object");
36
- zod.z.record(zod.z.string(), JsonValueSchema).describe("JSON object mapping string keys to JSON values");
37
- var _NodeSchema = zod.z.any();
38
- var setNodeSchema = (schema) => {
39
- _NodeSchema = schema;
40
- };
41
- var node = () => _NodeSchema;
42
- var RefNodeSchema = zod.z.object({
43
- $ref: zod.z.string().regex(/^\$(\..*)?$/).describe('JSONPath from the source root: "$" is the whole source; "$.user.name", "$.items[0].sku" reach into it. Only reads from source data, not variables. For variables use $var, for navigating into variables use $get.')
44
- }).strict().describe("Read a value from the source data by static JSONPath. Use $ref for source access, $var for variables, $get for navigating into variables or dynamic paths.");
45
- var ConstNodeSchema = zod.z.object({
46
- $const: JsonValueSchema.describe("Any JSON value to return as-is.")
47
- }).strict().describe("Return a literal JSON value unchanged.");
48
- var VarNodeSchema = zod.z.object({
49
- $var: zod.z.string().min(1).describe("Variable name bound by $with, $map, $filter, $reduce, or $sortBy.")
50
- }).strict().describe("Read a scoped variable by name. Variables are created by $with (let bindings), $map/$filter/$reduce/$sortBy (loop element). Returns the whole variable \u2014 use $get to navigate into it.");
51
- var GetNodeSchema = zod.z.object({
52
- $get: zod.z.object({
53
- from: zod.z.lazy(node).describe("Source value to navigate into."),
54
- path: zod.z.array(zod.z.union([zod.z.string(), zod.z.number(), zod.z.lazy(node)])).min(1).describe("Path segments: string keys, numeric indices, or node expressions."),
55
- fallback: zod.z.lazy(node).optional().describe("Fallback value when path is missing.")
56
- }).strict()
57
- }).strict().describe('Navigate into a value by path. Use to access fields on variables: {$get: {from: {$var: "item"}, path: ["name"]}}. Also supports dynamic path segments (nodes as segments) and fallback values. Prefer $ref for simple source access.');
58
- var WithNodeSchema = zod.z.object({
59
- $with: zod.z.object({
60
- let: zod.z.record(zod.z.string(), zod.z.lazy(node)).describe("Variable bindings: name \u2192 expression evaluated in current scope."),
61
- value: zod.z.lazy(node).describe("Expression evaluated with the declared variables in scope.")
62
- }).strict()
63
- }).strict().describe("Bind variables in a scoped block: { $with: { let: { x: ... }, value: ... } }");
64
- var _NodeSchema2 = zod.z.any();
65
- var setNodeSchema2 = (schema) => {
66
- _NodeSchema2 = schema;
67
- };
68
- var node2 = () => _NodeSchema2;
69
- var MapNodeSchema = zod.z.object({
70
- $map: zod.z.object({
71
- over: zod.z.lazy(node2).describe("Array to iterate over."),
72
- as: zod.z.string().min(1).describe("Variable name for the current element."),
73
- body: zod.z.lazy(node2).describe("Expression evaluated for each element.")
74
- }).strict()
75
- }).strict().describe("Map over an array, transforming each element.");
76
- var FilterNodeSchema = zod.z.object({
77
- $filter: zod.z.object({
78
- over: zod.z.lazy(node2).describe("Array to filter."),
79
- as: zod.z.string().min(1).describe("Variable name for the current element."),
80
- when: zod.z.lazy(node2).describe("Condition \u2014 keeps element when truthy.")
81
- }).strict()
82
- }).strict().describe("Filter an array, keeping elements where condition is truthy.");
83
- var ReduceNodeSchema = zod.z.object({
84
- $reduce: zod.z.object({
85
- over: zod.z.lazy(node2).describe("Array to reduce."),
86
- as: zod.z.string().min(1).describe("Variable name for the current element."),
87
- acc: zod.z.string().min(1).optional().default("acc").describe('Accumulator variable name. Default: "acc".'),
88
- init: zod.z.lazy(node2).describe("Initial accumulator value."),
89
- body: zod.z.lazy(node2).describe("Expression evaluated for each element with both element and accumulator in scope.")
90
- }).strict()
91
- }).strict().describe("Reduce an array to a single value using an accumulator.");
92
- var SliceNodeSchema = zod.z.object({
93
- $slice: zod.z.object({
94
- from: zod.z.lazy(node2).describe("Array or string to slice."),
95
- start: zod.z.number().int().optional().describe("Start index (inclusive). Default: 0."),
96
- end: zod.z.number().int().optional().describe("End index (exclusive). Default: length.")
97
- }).strict()
98
- }).strict().describe("Slice an array or string by start/end indices.");
99
- var FlattenNodeSchema = zod.z.object({
100
- $flatten: zod.z.lazy(node2).describe("Array of arrays to flatten one level.")
101
- }).strict().describe("Flatten a nested array by one level.");
102
- var UniqueNodeSchema = zod.z.object({
103
- $unique: zod.z.lazy(node2).describe("Array to deduplicate.")
104
- }).strict().describe("Remove duplicate values from an array (compared by JSON.stringify).");
105
- var SortByNodeSchema = zod.z.object({
106
- $sortBy: zod.z.object({
107
- over: zod.z.lazy(node2).describe("Array to sort."),
108
- as: zod.z.string().min(1).describe("Variable name for the current element."),
109
- by: zod.z.lazy(node2).describe("Expression to compute the sort key."),
110
- dir: zod.z.enum(["asc", "desc"]).optional().default("asc").describe('Sort direction. Default: "asc".')
111
- }).strict()
112
- }).strict().describe("Sort an array by a computed key.");
113
- var _NodeSchema3 = zod.z.any();
114
- var setNodeSchema3 = (schema) => {
115
- _NodeSchema3 = schema;
116
- };
117
- var node3 = () => _NodeSchema3;
118
- var pairOf = (desc) => zod.z.tuple([zod.z.lazy(node3), zod.z.lazy(node3)]).describe(desc);
119
- var AddNodeSchema = zod.z.object({ $add: pairOf("Two numeric operands to add.") }).strict().describe("Add two numbers.");
120
- var SubNodeSchema = zod.z.object({ $sub: pairOf("Two numeric operands to subtract (a - b).") }).strict().describe("Subtract second number from first.");
121
- var MulNodeSchema = zod.z.object({ $mul: pairOf("Two numeric operands to multiply.") }).strict().describe("Multiply two numbers.");
122
- var DivNodeSchema = zod.z.object({ $div: pairOf("Two numeric operands to divide (a / b). Throws on division by zero.") }).strict().describe("Divide first number by second. Throws E_DIVISION_BY_ZERO if divisor is 0.");
123
- var RoundNodeSchema = zod.z.object({
124
- $round: zod.z.object({
125
- value: zod.z.lazy(node3).describe("Numeric value to round."),
126
- digits: zod.z.number().int().nonnegative().optional().default(0).describe("Decimal places. Default: 0.")
127
- }).strict()
128
- }).strict().describe("Round a number to N decimal places.");
129
- var _NodeSchema4 = zod.z.any();
130
- var setNodeSchema4 = (schema) => {
131
- _NodeSchema4 = schema;
132
- };
133
- var node4 = () => _NodeSchema4;
134
- var JoinNodeSchema = zod.z.object({
135
- $join: zod.z.object({
136
- parts: zod.z.lazy(node4).describe("Values to concatenate (coerced to string): a literal list of nodes, or any node that evaluates to an array \u2014 a mapped list, a $var."),
137
- sep: zod.z.string().optional().default("").describe('Separator between parts. Default: "".')
138
- }).strict()
139
- }).strict().describe("Concatenate values into a string with an optional separator.");
140
- var ToStringNodeSchema = zod.z.object({ $toString: zod.z.lazy(node4).describe("Value to stringify via String().") }).strict().describe("Convert a value to its string representation.");
141
- var InterpolateNodeSchema = zod.z.object({
142
- $interpolate: zod.z.object({
143
- template: zod.z.string().describe("Template with {{key}} placeholders."),
144
- values: zod.z.lazy(node4).describe("Object whose keys replace {{key}} placeholders.")
145
- }).strict()
146
- }).strict().describe("Replace {{key}} placeholders in a template with values from an object.");
147
- var FillNodeSchema = zod.z.object({
148
- $fill: zod.z.lazy(node4).describe("A pattern value `{ phrase, slots }` \u2014 filled with its own slots, source language. Non-patterns pass through.")
149
- }).strict().describe('Fill a counted phrase: `{ phrase: "{n} of {total}", slots: { n: 1, total: 12 } }` \u2192 "1 of 12".');
150
- var TrimNodeSchema = zod.z.object({ $trim: zod.z.lazy(node4).describe("String to trim whitespace from.") }).strict().describe("Trim leading and trailing whitespace from a string.");
151
- var LowerNodeSchema = zod.z.object({ $lower: zod.z.lazy(node4).describe("String to lowercase.") }).strict().describe("Convert a string to lowercase.");
152
- var UpperNodeSchema = zod.z.object({ $upper: zod.z.lazy(node4).describe("String to uppercase.") }).strict().describe("Convert a string to uppercase.");
153
- var SplitNodeSchema = zod.z.object({
154
- $split: zod.z.object({
155
- value: zod.z.lazy(node4).describe("String to split."),
156
- sep: zod.z.string().describe("Separator to split on.")
157
- }).strict()
158
- }).strict().describe("Split a string into an array by separator.");
159
- var ReplaceNodeSchema = zod.z.object({
160
- $replace: zod.z.object({
161
- value: zod.z.lazy(node4).describe("String to search in."),
162
- search: zod.z.string().describe("Substring to find."),
163
- replacement: zod.z.string().describe("Replacement string.")
164
- }).strict()
165
- }).strict().describe("Replace the first occurrence of a substring.");
166
- var _NodeSchema5 = zod.z.any();
167
- var setNodeSchema5 = (schema) => {
168
- _NodeSchema5 = schema;
169
- };
170
- var node5 = () => _NodeSchema5;
171
- var pairOf2 = (desc) => zod.z.tuple([zod.z.lazy(node5), zod.z.lazy(node5)]).describe(desc);
172
- var EqNodeSchema = zod.z.object({ $eq: pairOf2("Two values to compare for deep equality.") }).strict().describe("Deep equality comparison (JSON.stringify-based). Returns true or false.");
173
- var NeqNodeSchema = zod.z.object({ $neq: pairOf2("Two values to compare for inequality.") }).strict().describe("Deep inequality comparison. Returns true or false.");
174
- var GtNodeSchema = zod.z.object({ $gt: pairOf2("Two values: returns true if first > second (numbers or strings).") }).strict().describe("Greater than comparison for numbers or strings.");
175
- var GteNodeSchema = zod.z.object({ $gte: pairOf2("Two values: returns true if first >= second.") }).strict().describe("Greater than or equal comparison.");
176
- var LtNodeSchema = zod.z.object({ $lt: pairOf2("Two values: returns true if first < second.") }).strict().describe("Less than comparison.");
177
- var LteNodeSchema = zod.z.object({ $lte: pairOf2("Two values: returns true if first <= second.") }).strict().describe("Less than or equal comparison.");
178
- var EmptyNodeSchema = zod.z.object({ $empty: zod.z.lazy(node5).describe('Value to check for emptiness (null, "", [], {}).') }).strict().describe("Returns true if value is null, empty string, empty array, or empty object.");
179
- var StartsWithNodeSchema = zod.z.object({
180
- $startsWith: zod.z.object({
181
- value: zod.z.lazy(node5).describe("String to check."),
182
- prefix: zod.z.lazy(node5).describe("Expected prefix.")
183
- }).strict()
184
- }).strict().describe("Returns true if string starts with prefix.");
185
- var EndsWithNodeSchema = zod.z.object({
186
- $endsWith: zod.z.object({
187
- value: zod.z.lazy(node5).describe("String to check."),
188
- suffix: zod.z.lazy(node5).describe("Expected suffix.")
189
- }).strict()
190
- }).strict().describe("Returns true if string ends with suffix.");
191
- var ContainsNodeSchema = zod.z.object({
192
- $contains: zod.z.object({
193
- value: zod.z.lazy(node5).describe("String to search in."),
194
- search: zod.z.lazy(node5).describe("Substring to find.")
195
- }).strict()
196
- }).strict().describe("Returns true if string contains the search substring.");
197
- var _NodeSchema6 = zod.z.any();
198
- var setNodeSchema6 = (schema) => {
199
- _NodeSchema6 = schema;
200
- };
201
- var node6 = () => _NodeSchema6;
202
- var NotNodeSchema = zod.z.object({ $not: zod.z.lazy(node6).describe("Value to negate (truthy \u2192 false, falsy \u2192 true).") }).strict().describe("Boolean negation of a truthy/falsy value.");
203
- var AndNodeSchema = zod.z.object({
204
- $and: zod.z.array(zod.z.lazy(node6)).min(1).describe("Values to AND. Short-circuits: returns last truthy or first falsy.")
205
- }).strict().describe("Short-circuit logical AND.");
206
- var OrNodeSchema = zod.z.object({
207
- $or: zod.z.array(zod.z.lazy(node6)).min(1).describe("Values to OR. Short-circuits: returns first truthy or last falsy.")
208
- }).strict().describe("Short-circuit logical OR.");
209
- var _NodeSchema7 = zod.z.any();
210
- var setNodeSchema7 = (schema) => {
211
- _NodeSchema7 = schema;
212
- };
213
- var node7 = () => _NodeSchema7;
214
- var MergeNodeSchema = zod.z.object({
215
- $merge: zod.z.array(zod.z.lazy(node7)).min(1).describe("Objects to shallow-merge (left to right, later wins).")
216
- }).strict().describe("Shallow merge multiple objects. Later values overwrite earlier ones.");
217
- var CoalesceNodeSchema = zod.z.object({
218
- $coalesce: zod.z.array(zod.z.lazy(node7)).min(1).describe("Values to try in order. Returns first non-null/non-undefined.")
219
- }).strict().describe("Return the first non-null, non-undefined value.");
220
- var CaseNodeSchema = zod.z.object({
221
- $case: zod.z.object({
222
- branches: zod.z.array(
223
- zod.z.object({
224
- when: zod.z.lazy(node7).describe("Condition to evaluate."),
225
- then: zod.z.lazy(node7).describe("Value to return if condition is truthy.")
226
- }).strict()
227
- ).min(1).describe("Ordered list of when/then branches."),
228
- else: zod.z.lazy(node7).optional().describe("Fallback value if no branch matches. Default: null.")
229
- }).strict()
230
- }).strict().describe("Conditional branching: evaluates branches in order, returns first match or else.");
231
- var EntriesOfNodeSchema = zod.z.object({ $entriesOf: zod.z.lazy(node7).describe("Object to convert to [key, value][] entries.") }).strict().describe("Convert an object to an array of [key, value] pairs.");
232
- var KeyByNodeSchema = zod.z.object({
233
- $keyBy: zod.z.object({
234
- over: zod.z.lazy(node7).describe("Array to group."),
235
- as: zod.z.string().min(1).describe("Variable name for the current element."),
236
- key: zod.z.lazy(node7).describe("Expression to compute the key (last wins on collision).")
237
- }).strict()
238
- }).strict().describe("Convert an array to an object keyed by a computed value. Last element wins on key collision.");
239
- var GroupByNodeSchema = zod.z.object({
240
- $groupBy: zod.z.object({
241
- over: zod.z.lazy(node7).describe("Array to group."),
242
- as: zod.z.string().min(1).describe("Variable name for the current element."),
243
- key: zod.z.lazy(node7).describe("Expression to compute the group key.")
244
- }).strict()
245
- }).strict().describe("Group array elements into an object of arrays by computed key.");
246
- var _NodeSchema8 = zod.z.any();
247
- var setNodeSchema8 = (schema) => {
248
- _NodeSchema8 = schema;
249
- };
250
- var node8 = () => _NodeSchema8;
251
- var KeysNodeSchema = zod.z.object({ $keys: zod.z.lazy(node8).describe("Object to extract keys from.") }).strict().describe("Return the keys of an object as a string array.");
252
- var ValuesNodeSchema = zod.z.object({ $values: zod.z.lazy(node8).describe("Object to extract values from.") }).strict().describe("Return the values of an object as an array.");
253
- var FromEntriesNodeSchema = zod.z.object({
254
- $fromEntries: zod.z.lazy(node8).describe("Array of [key, value] pairs to convert to an object.")
255
- }).strict().describe("Convert [key, value][] entries into an object.");
256
- var PickNodeSchema = zod.z.object({
257
- $pick: zod.z.object({
258
- from: zod.z.lazy(node8).describe("Source object."),
259
- keys: zod.z.array(zod.z.string()).min(1).describe("Keys to keep.")
260
- }).strict()
261
- }).strict().describe("Pick specific keys from an object, discarding the rest.");
262
- var OmitNodeSchema = zod.z.object({
263
- $omit: zod.z.object({
264
- from: zod.z.lazy(node8).describe("Source object."),
265
- keys: zod.z.array(zod.z.string()).min(1).describe("Keys to remove.")
266
- }).strict()
267
- }).strict().describe("Remove specific keys from an object, keeping the rest.");
268
- var TypeNodeSchema = zod.z.object({ $type: zod.z.lazy(node8).describe("Value to get the type of.") }).strict().describe('Returns the type as a string: "string", "number", "boolean", "null", "array", or "object".');
269
- var LengthNodeSchema = zod.z.object({ $length: zod.z.lazy(node8).describe("Array or string to measure.") }).strict().describe("Return the length of an array or string.");
270
- var _NodeSchema9 = zod.z.any();
271
- var setNodeSchema9 = (schema) => {
272
- _NodeSchema9 = schema;
273
- };
274
- var node9 = () => _NodeSchema9;
275
- var TimeUnit = zod.z.enum(["year", "month", "day", "hour", "minute", "second"]).describe("Time unit for date arithmetic.");
276
- var DateNodeSchema = zod.z.object({
277
- $date: zod.z.object({
278
- value: zod.z.lazy(node9).describe("Date value (ISO string or timestamp)."),
279
- format: zod.z.string().optional().describe("Output format string (dayjs format). Default: ISO 8601."),
280
- utc: zod.z.boolean().optional().default(false).describe("Format in UTC. Default: false.")
281
- }).strict()
282
- }).strict().describe("Format a date value.");
283
- var DateAddNodeSchema = zod.z.object({
284
- $dateAdd: zod.z.object({
285
- date: zod.z.lazy(node9).describe("Base date (ISO string or timestamp)."),
286
- amount: zod.z.number().describe("Amount to add (can be negative)."),
287
- unit: TimeUnit
288
- }).strict()
289
- }).strict().describe("Add a duration to a date. Returns ISO string.");
290
- var DateDiffNodeSchema = zod.z.object({
291
- $dateDiff: zod.z.object({
292
- from: zod.z.lazy(node9).describe("Start date."),
293
- to: zod.z.lazy(node9).describe("End date."),
294
- unit: TimeUnit
295
- }).strict()
296
- }).strict().describe("Calculate difference between two dates. Returns a number.");
297
- var _NodeSchema10 = zod.z.any();
298
- var setNodeSchema10 = (schema) => {
299
- _NodeSchema10 = schema;
300
- };
301
- var node10 = () => _NodeSchema10;
302
- var localeField = zod.z.lazy(node10).describe('BCP-47 locale tag ("de-AT", "en-GB"). Required \u2014 a default renders plausible nonsense for everybody it is wrong for.');
303
- var fallbackField = zod.z.lazy(node10).optional().describe('Rendered when the value is null/undefined/empty. Default: "".');
304
- var DateStyle = zod.z.enum(["full", "long", "medium", "short"]);
305
- var IntlDateOptionsSchema = zod.z.object({
306
- dateStyle: DateStyle.optional().describe("Whole-date preset. Mutually exclusive with the field-by-field options below."),
307
- timeStyle: DateStyle.optional().describe("Whole-time preset. Mutually exclusive with the field-by-field options below."),
308
- weekday: zod.z.enum(["long", "short", "narrow"]).optional(),
309
- year: zod.z.enum(["numeric", "2-digit"]).optional(),
310
- month: zod.z.enum(["numeric", "2-digit", "long", "short", "narrow"]).optional(),
311
- day: zod.z.enum(["numeric", "2-digit"]).optional(),
312
- hour: zod.z.enum(["numeric", "2-digit"]).optional(),
313
- minute: zod.z.enum(["numeric", "2-digit"]).optional(),
314
- second: zod.z.enum(["numeric", "2-digit"]).optional(),
315
- hour12: zod.z.boolean().optional().describe("Force 12/24-hour. Omit to take the locale's own convention \u2014 which is the point of asking for a locale."),
316
- timeZone: zod.z.string().optional().describe('IANA zone. Omit and a DATE-only value ("2026-03-14") is read as UTC, which is what stops it rendering as the 13th west of Greenwich.')
317
- }).strict();
318
- var LocaleDateNodeSchema = zod.z.object({
319
- $localeDate: zod.z.object({
320
- value: zod.z.lazy(node10).describe("ISO string, DATE-only string, or epoch milliseconds."),
321
- locale: localeField,
322
- options: IntlDateOptionsSchema.optional().describe('Defaults to { dateStyle: "medium" }.'),
323
- fallback: fallbackField
324
- }).strict()
325
- }).strict().describe("Format a date for a human reading in a given locale (Intl.DateTimeFormat).");
326
- var LocaleMoneyNodeSchema = zod.z.object({
327
- $localeMoney: zod.z.object({
328
- value: zod.z.lazy(node10).describe("The amount. Minor units (cents) unless `minorUnits` is false."),
329
- currency: zod.z.lazy(node10).describe('ISO-4217 code \u2014 "EUR", "CHF". Required: an amount without one is a number, not money.'),
330
- locale: localeField,
331
- minorUnits: zod.z.boolean().optional().describe(
332
- "Value is in the currency's minor unit. Default true. The divisor comes from the CURRENCY, not a hardcoded 100 \u2014 JPY has no minor unit and dividing it would be a hundredfold error."
333
- ),
334
- digits: zod.z.number().int().min(0).max(20).optional().describe("Fraction digits. Default: the currency's own (2 for EUR, 0 for JPY)."),
335
- fallback: fallbackField
336
- }).strict()
337
- }).strict().describe("Format an amount as money in a given locale (Intl.NumberFormat, style currency).");
338
- var LocaleNumberNodeSchema = zod.z.object({
339
- $localeNumber: zod.z.object({
340
- value: zod.z.lazy(node10).describe("The number to format."),
341
- locale: localeField,
342
- style: zod.z.enum(["decimal", "percent"]).optional().describe('Default "decimal". "percent" multiplies by 100 \u2014 pass 0.42, not 42.'),
343
- digits: zod.z.number().int().min(0).max(20).optional().describe("Maximum fraction digits. Default: the locale's own."),
344
- minDigits: zod.z.number().int().min(0).max(20).optional().describe("Minimum fraction digits \u2014 for a column that should not ragged-edge."),
345
- compact: zod.z.boolean().optional().describe('Short form \u2014 "1.2K", "1,2 Tsd.". For a headline figure, never for money owed.'),
346
- fallback: fallbackField
347
- }).strict()
348
- }).strict().describe("Format a number in a given locale (Intl.NumberFormat).");
349
- var _NodeSchema11 = zod.z.any();
350
- var setNodeSchema11 = (schema) => {
351
- _NodeSchema11 = schema;
352
- };
353
- var node11 = () => _NodeSchema11;
354
- var overOnly = (desc) => zod.z.object({ over: zod.z.lazy(node11).describe(desc) }).strict();
355
- var SumNodeSchema = zod.z.object({ $sum: overOnly("Array of numbers to sum.") }).strict().describe("Sugar: sum all elements in an array. Desugars to $reduce + $add.");
356
- var AvgNodeSchema = zod.z.object({ $avg: overOnly("Array of numbers to average.") }).strict().describe("Sugar: average all elements in an array. Desugars to $div($sum, $count).");
357
- var CountNodeSchema = zod.z.object({ $count: overOnly("Array to count elements of.") }).strict().describe("Sugar: count elements in an array. Desugars to $reduce.");
358
- var MinNodeSchema = zod.z.object({ $min: overOnly("Array of numbers to find minimum.") }).strict().describe("Sugar: find minimum value in an array. Desugars to $reduce + $lt.");
359
- var MaxNodeSchema = zod.z.object({ $max: overOnly("Array of numbers to find maximum.") }).strict().describe("Sugar: find maximum value in an array. Desugars to $reduce + $gt.");
360
- var PluckNodeSchema = zod.z.object({
361
- $pluck: zod.z.object({
362
- over: zod.z.lazy(node11).describe("Array of objects to extract from."),
363
- key: zod.z.string().min(1).describe("Key to extract from each object.")
364
- }).strict()
365
- }).strict().describe("Sugar: extract a single field from each element. Desugars to $map + $get.");
366
- var TakeNodeSchema = zod.z.object({
367
- $take: zod.z.object({
368
- from: zod.z.lazy(node11).describe("Array to take from."),
369
- count: zod.z.number().int().nonnegative().describe("Number of elements to take from the start.")
370
- }).strict()
371
- }).strict().describe("Sugar: take first N elements. Desugars to $slice.");
372
- var DropNodeSchema = zod.z.object({
373
- $drop: zod.z.object({
374
- from: zod.z.lazy(node11).describe("Array to drop from."),
375
- count: zod.z.number().int().nonnegative().describe("Number of elements to skip from the start.")
376
- }).strict()
377
- }).strict().describe("Sugar: skip first N elements. Desugars to $slice.");
378
- var MatchNodeSchema = zod.z.object({
379
- $match: zod.z.object({
380
- over: zod.z.lazy(node11).describe("Array to search within."),
381
- as: zod.z.string().min(1).describe("Variable name for the current element."),
382
- search: zod.z.lazy(node11).describe("String to search for (uses $contains).")
383
- }).strict()
384
- }).strict().describe("Sugar: filter array by string containment. Desugars to $filter + $contains.");
385
- var FlatMapNodeSchema = zod.z.object({
386
- $flatMap: zod.z.object({
387
- over: zod.z.lazy(node11).describe("Array to flat-map over."),
388
- as: zod.z.string().min(1).describe("Variable name for the current element."),
389
- body: zod.z.lazy(node11).describe("Expression that returns an array for each element.")
390
- }).strict()
391
- }).strict().describe("Sugar: map then flatten one level. Desugars to $map + $flatten.");
392
- var _NodeSchema12 = zod.z.any();
393
- var setNodeSchema12 = (schema) => {
394
- _NodeSchema12 = schema;
395
- };
396
- var node12 = () => _NodeSchema12;
397
- var PathSchema = zod.z.array(zod.z.union([zod.z.string(), zod.z.number().int().nonnegative()])).min(1).describe("Literal path segments: object keys (strings) and array indexes (numbers).");
398
- var HasNodeSchema = zod.z.object({
399
- $has: zod.z.object({
400
- from: zod.z.lazy(node12).describe("The value to look into."),
401
- path: PathSchema
402
- }).strict()
403
- }).strict().describe("True when the whole path exists \u2014 a key present with a null value counts; a missing one does not.");
404
- var RenameKeysNodeSchema = zod.z.object({
405
- $renameKeys: zod.z.object({
406
- from: zod.z.lazy(node12).describe("The object whose keys to rename."),
407
- map: zod.z.record(zod.z.string(), zod.z.string()).describe("Old key \u2192 new key. Keys not listed, and listed keys that are absent, are left alone.")
408
- }).strict()
409
- }).strict().describe(
410
- "The object with keys renamed IN PLACE \u2014 each renamed key keeps its position. If a new name is already a key of the object, that entry is replaced by the renamed one."
411
- );
412
- var UpdateNodeSchema = zod.z.object({
413
- $update: zod.z.object({
414
- from: zod.z.lazy(node12).describe("The value to copy with one path changed."),
415
- path: PathSchema,
416
- value: zod.z.lazy(node12).describe("The new value at `path`. The value currently there (null when absent) is bound as `$var` `as`."),
417
- as: zod.z.string().min(1).optional().describe('The variable name the current value is bound to (default "current").')
418
- }).strict()
419
- }).strict().describe(
420
- "A copy of `from` with the value at `path` replaced and everything else identical. Missing objects along a string path are created; an index that does not exist is an error."
421
- );
422
- var AssertNodeSchema = zod.z.object({
423
- $assert: zod.z.object({
424
- when: zod.z.lazy(node12).describe("Must be truthy."),
425
- message: zod.z.string().min(1).describe("What went wrong, for a person \u2014 the whole error text."),
426
- value: zod.z.lazy(node12).describe("Returned when `when` holds.")
427
- }).strict()
428
- }).strict().describe("Fail with `message` (E_ASSERT) unless `when` is truthy; otherwise evaluate to `value`. How a migration refuses a shape it cannot handle.");
429
- var WalkNodeSchema = zod.z.object({
430
- $walk: zod.z.object({
431
- over: zod.z.lazy(node12).describe("The tree to rewrite \u2014 any JSON value."),
432
- as: zod.z.string().min(1).describe("The variable each visited node is bound to."),
433
- rules: zod.z.array(
434
- zod.z.object({
435
- when: zod.z.lazy(node12).describe("Evaluated with the node bound to `as`; the first truthy rule wins."),
436
- then: zod.z.lazy(node12).describe("The node's replacement.")
437
- }).strict()
438
- ).min(1).describe("Tried in order at every node. No rule matches: the node is kept."),
439
- order: zod.z.enum(["post", "pre"]).optional().describe(
440
- "post (default): a node's children are rewritten first, and its rules see the rewritten children. pre: rules see the node as it was, then the walk descends into whatever they returned."
441
- )
442
- }).strict()
443
- }).strict().describe(
444
- "Rewrite every node of a tree \u2014 objects, arrays and leaves, at any depth \u2014 by rules. Structural: it always terminates, and a replacement is never walked again at its own level."
445
- );
446
-
447
- // src/schemas/node.schema.ts
448
- var OP_KEYS = [
449
- "$ref",
450
- "$const",
451
- "$var",
452
- "$get",
453
- "$with",
454
- "$map",
455
- "$filter",
456
- "$reduce",
457
- "$slice",
458
- "$flatten",
459
- "$unique",
460
- "$sortBy",
461
- "$add",
462
- "$sub",
463
- "$mul",
464
- "$div",
465
- "$round",
466
- "$fill",
467
- "$join",
468
- "$toString",
469
- "$interpolate",
470
- "$trim",
471
- "$lower",
472
- "$upper",
473
- "$split",
474
- "$replace",
475
- "$eq",
476
- "$neq",
477
- "$gt",
478
- "$gte",
479
- "$lt",
480
- "$lte",
481
- "$empty",
482
- "$startsWith",
483
- "$endsWith",
484
- "$contains",
485
- "$not",
486
- "$and",
487
- "$or",
488
- "$merge",
489
- "$coalesce",
490
- "$case",
491
- "$entriesOf",
492
- "$keyBy",
493
- "$groupBy",
494
- "$keys",
495
- "$values",
496
- "$fromEntries",
497
- "$pick",
498
- "$omit",
499
- "$type",
500
- "$length",
501
- "$date",
502
- "$dateAdd",
503
- "$dateDiff",
504
- "$localeDate",
505
- "$localeMoney",
506
- "$localeNumber",
507
- "$sum",
508
- "$avg",
509
- "$count",
510
- "$min",
511
- "$max",
512
- "$pluck",
513
- "$take",
514
- "$drop",
515
- "$match",
516
- "$flatMap",
517
- "$has",
518
- "$renameKeys",
519
- "$update",
520
- "$assert",
521
- "$walk"
522
- ];
523
- var OPTIONAL_FIELDS_KEY = "__optional";
524
- var TEMPLATE_KEY = /^(?!\$)/;
525
- var isOpKey = (key) => OP_KEYS.some((op) => op === key);
526
- var templateKeyRefusal = (key) => isOpKey(key) ? "An op name cannot be a plain object key. Use the op itself." : 'Not a Prism op. A key that starts with "$" names an op; data with such a key goes in $const.';
527
- var hasValidOptionalMeta = (obj) => {
528
- const meta = obj[OPTIONAL_FIELDS_KEY];
529
- if (meta === void 0) return true;
530
- if (!Array.isArray(meta)) return false;
531
- return meta.every((f) => typeof f === "string" && f.length > 0);
532
- };
533
- var NodeSchema = zod.z.lazy(
534
- () => zod.z.union([
535
- // Core
536
- RefNodeSchema,
537
- ConstNodeSchema,
538
- VarNodeSchema,
539
- GetNodeSchema,
540
- WithNodeSchema,
541
- // Array
542
- MapNodeSchema,
543
- FilterNodeSchema,
544
- ReduceNodeSchema,
545
- SliceNodeSchema,
546
- FlattenNodeSchema,
547
- UniqueNodeSchema,
548
- SortByNodeSchema,
549
- // Math
550
- AddNodeSchema,
551
- SubNodeSchema,
552
- MulNodeSchema,
553
- DivNodeSchema,
554
- RoundNodeSchema,
555
- // String
556
- FillNodeSchema,
557
- JoinNodeSchema,
558
- ToStringNodeSchema,
559
- InterpolateNodeSchema,
560
- TrimNodeSchema,
561
- LowerNodeSchema,
562
- UpperNodeSchema,
563
- SplitNodeSchema,
564
- ReplaceNodeSchema,
565
- // Predicates
566
- EqNodeSchema,
567
- NeqNodeSchema,
568
- GtNodeSchema,
569
- GteNodeSchema,
570
- LtNodeSchema,
571
- LteNodeSchema,
572
- EmptyNodeSchema,
573
- StartsWithNodeSchema,
574
- EndsWithNodeSchema,
575
- ContainsNodeSchema,
576
- // Logic
577
- NotNodeSchema,
578
- AndNodeSchema,
579
- OrNodeSchema,
580
- // Structure
581
- MergeNodeSchema,
582
- CoalesceNodeSchema,
583
- CaseNodeSchema,
584
- EntriesOfNodeSchema,
585
- KeyByNodeSchema,
586
- GroupByNodeSchema,
587
- // Object
588
- KeysNodeSchema,
589
- ValuesNodeSchema,
590
- FromEntriesNodeSchema,
591
- PickNodeSchema,
592
- OmitNodeSchema,
593
- TypeNodeSchema,
594
- LengthNodeSchema,
595
- // Time
596
- DateNodeSchema,
597
- DateAddNodeSchema,
598
- DateDiffNodeSchema,
599
- // Locale-aware formatting
600
- LocaleDateNodeSchema,
601
- LocaleMoneyNodeSchema,
602
- LocaleNumberNodeSchema,
603
- // Sugar
604
- SumNodeSchema,
605
- AvgNodeSchema,
606
- CountNodeSchema,
607
- MinNodeSchema,
608
- MaxNodeSchema,
609
- PluckNodeSchema,
610
- TakeNodeSchema,
611
- DropNodeSchema,
612
- MatchNodeSchema,
613
- FlatMapNodeSchema,
614
- // Transform (rewriting a document)
615
- HasNodeSchema,
616
- RenameKeysNodeSchema,
617
- UpdateNodeSchema,
618
- AssertNodeSchema,
619
- WalkNodeSchema,
620
- // Primitives
621
- JsonPrimitiveSchema,
622
- // Arrays of nodes
623
- zod.z.array(zod.z.lazy(() => NodeSchema)),
624
- // Plain objects (no `$` keys, recursive values)
625
- // A `$` key is not a template key. Said in the KEY schema, not a
626
- // refinement: a refinement leaves this branch structurally matched, and
627
- // zod then reports its complaint instead of the union's — so a typo inside
628
- // a real op (`{ $get: { pathh } }`) read as "plain object must not contain
629
- // $ op keys" at the root. As a key pattern it is also plain JSON Schema
630
- // (`propertyNames`), which the grammar snapshot and agent prompts read.
631
- zod.z.record(zod.z.string().regex(TEMPLATE_KEY, { error: (issue) => templateKeyRefusal(issue.input) }), zod.z.lazy(() => NodeSchema)).refine((o) => hasValidOptionalMeta(o), { message: "__optional must be an array of non-empty field name strings." })
632
- ]).describe("A Prism node: an op, a plain JSON value, an array of nodes, or a plain object template.")
633
- );
634
- setNodeSchema(NodeSchema);
635
- setNodeSchema2(NodeSchema);
636
- setNodeSchema3(NodeSchema);
637
- setNodeSchema4(NodeSchema);
638
- setNodeSchema5(NodeSchema);
639
- setNodeSchema6(NodeSchema);
640
- setNodeSchema7(NodeSchema);
641
- setNodeSchema8(NodeSchema);
642
- setNodeSchema9(NodeSchema);
643
- setNodeSchema10(NodeSchema);
644
- setNodeSchema11(NodeSchema);
645
- setNodeSchema12(NodeSchema);
646
-
647
- // src/schemas/config.schema.ts
648
- var ConfigSchema = NodeSchema.describe(
649
- "A Prism config: the top-level transformation definition. Can be any valid node."
650
- );
651
-
652
- // src/errors.ts
653
- var ErrorCode = {
654
- SCHEMA: "E_SCHEMA",
655
- MISSING_PATH: "E_MISSING_PATH",
656
- TYPE: "E_TYPE",
657
- DIVISION_BY_ZERO: "E_DIVISION_BY_ZERO",
658
- DATE_INVALID: "E_DATE_INVALID",
659
- VAR_NOT_FOUND: "E_VAR_NOT_FOUND",
660
- NODE_SHAPE: "E_NODE_SHAPE",
661
- // A config's own `$assert` refused its input.
662
- ASSERT: "E_ASSERT",
663
- // An evaluation past its budget (engine/budget.ts).
664
- BUDGET: "E_BUDGET"
665
- };
666
- var PrismError = class extends Error {
667
- code;
668
- context;
669
- constructor(message, code, context) {
670
- super(message);
671
- this.name = "PrismError";
672
- this.code = code;
673
- this.context = context;
674
- }
675
- };
676
-
677
- // src/schemas/guards.ts
678
- var hasKey = (value, key) => typeof value === "object" && value !== null && !Array.isArray(value) && key in value;
679
- var isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
680
- var isJsonArray = (value) => Array.isArray(value);
681
- var isRefNode = (v) => hasKey(v, "$ref");
682
- var isConstNode = (v) => hasKey(v, "$const");
683
- var isVarNode = (v) => hasKey(v, "$var");
684
- var isGetNode = (v) => hasKey(v, "$get");
685
- var isWithNode = (v) => hasKey(v, "$with");
686
- var isMapNode = (v) => hasKey(v, "$map");
687
- var isFilterNode = (v) => hasKey(v, "$filter");
688
- var isReduceNode = (v) => hasKey(v, "$reduce");
689
- var isSliceNode = (v) => hasKey(v, "$slice");
690
- var isFlattenNode = (v) => hasKey(v, "$flatten");
691
- var isUniqueNode = (v) => hasKey(v, "$unique");
692
- var isSortByNode = (v) => hasKey(v, "$sortBy");
693
- var isAddNode = (v) => hasKey(v, "$add");
694
- var isSubNode = (v) => hasKey(v, "$sub");
695
- var isMulNode = (v) => hasKey(v, "$mul");
696
- var isDivNode = (v) => hasKey(v, "$div");
697
- var isRoundNode = (v) => hasKey(v, "$round");
698
- var isJoinNode = (v) => hasKey(v, "$join");
699
- var isToStringNode = (v) => hasKey(v, "$toString");
700
- var isInterpolateNode = (v) => hasKey(v, "$interpolate");
701
- var isFillNode = (v) => hasKey(v, "$fill");
702
- var isTrimNode = (v) => hasKey(v, "$trim");
703
- var isLowerNode = (v) => hasKey(v, "$lower");
704
- var isUpperNode = (v) => hasKey(v, "$upper");
705
- var isSplitNode = (v) => hasKey(v, "$split");
706
- var isReplaceNode = (v) => hasKey(v, "$replace");
707
- var isEqNode = (v) => hasKey(v, "$eq");
708
- var isNeqNode = (v) => hasKey(v, "$neq");
709
- var isGtNode = (v) => hasKey(v, "$gt");
710
- var isGteNode = (v) => hasKey(v, "$gte");
711
- var isLtNode = (v) => hasKey(v, "$lt");
712
- var isLteNode = (v) => hasKey(v, "$lte");
713
- var isEmptyNode = (v) => hasKey(v, "$empty");
714
- var isStartsWithNode = (v) => hasKey(v, "$startsWith");
715
- var isEndsWithNode = (v) => hasKey(v, "$endsWith");
716
- var isContainsNode = (v) => hasKey(v, "$contains");
717
- var isNotNode = (v) => hasKey(v, "$not");
718
- var isAndNode = (v) => hasKey(v, "$and");
719
- var isOrNode = (v) => hasKey(v, "$or");
720
- var isMergeNode = (v) => hasKey(v, "$merge");
721
- var isCoalesceNode = (v) => hasKey(v, "$coalesce");
722
- var isCaseNode = (v) => hasKey(v, "$case");
723
- var isEntriesOfNode = (v) => hasKey(v, "$entriesOf");
724
- var isKeyByNode = (v) => hasKey(v, "$keyBy");
725
- var isGroupByNode = (v) => hasKey(v, "$groupBy");
726
- var isKeysNode = (v) => hasKey(v, "$keys");
727
- var isValuesNode = (v) => hasKey(v, "$values");
728
- var isFromEntriesNode = (v) => hasKey(v, "$fromEntries");
729
- var isPickNode = (v) => hasKey(v, "$pick");
730
- var isOmitNode = (v) => hasKey(v, "$omit");
731
- var isHasNode = (v) => hasKey(v, "$has");
732
- var isRenameKeysNode = (v) => hasKey(v, "$renameKeys");
733
- var isUpdateNode = (v) => hasKey(v, "$update");
734
- var isAssertNode = (v) => hasKey(v, "$assert");
735
- var isWalkNode = (v) => hasKey(v, "$walk");
736
- var isTypeNode = (v) => hasKey(v, "$type");
737
- var isLengthNode = (v) => hasKey(v, "$length");
738
- var isDateNode = (v) => hasKey(v, "$date");
739
- var isDateAddNode = (v) => hasKey(v, "$dateAdd");
740
- var isDateDiffNode = (v) => hasKey(v, "$dateDiff");
741
- var isLocaleDateNode = (v) => hasKey(v, "$localeDate");
742
- var isLocaleMoneyNode = (v) => hasKey(v, "$localeMoney");
743
- var isLocaleNumberNode = (v) => hasKey(v, "$localeNumber");
744
- var isSumNode = (v) => hasKey(v, "$sum");
745
- var isAvgNode = (v) => hasKey(v, "$avg");
746
- var isCountNode = (v) => hasKey(v, "$count");
747
- var isMinNode = (v) => hasKey(v, "$min");
748
- var isMaxNode = (v) => hasKey(v, "$max");
749
- var isPluckNode = (v) => hasKey(v, "$pluck");
750
- var isTakeNode = (v) => hasKey(v, "$take");
751
- var isDropNode = (v) => hasKey(v, "$drop");
752
- var isMatchNode = (v) => hasKey(v, "$match");
753
- var isFlatMapNode = (v) => hasKey(v, "$flatMap");
754
- var isPlainObject = (value) => isJsonObject(value) && !Object.keys(value).some((k) => k.startsWith("$"));
755
-
756
- // src/sugar/rewriters.ts
757
- var rewriteSum = (node13, recurse) => ({
758
- $reduce: {
759
- over: recurse(node13.$sum.over),
760
- as: "__x",
761
- acc: "__acc",
762
- init: { $const: 0 },
763
- body: { $add: [{ $var: "__acc" }, { $var: "__x" }] }
764
- }
765
- });
766
- var rewriteCount = (node13, recurse) => ({
767
- $reduce: {
768
- over: recurse(node13.$count.over),
769
- as: "__x",
770
- acc: "__acc",
771
- init: { $const: 0 },
772
- body: { $add: [{ $var: "__acc" }, { $const: 1 }] }
773
- }
774
- });
775
- var rewriteAvg = (node13, recurse) => {
776
- const over = recurse(node13.$avg.over);
777
- return {
778
- $div: [
779
- {
780
- $reduce: {
781
- over,
782
- as: "__x",
783
- acc: "__acc",
784
- init: { $const: 0 },
785
- body: { $add: [{ $var: "__acc" }, { $var: "__x" }] }
786
- }
787
- },
788
- {
789
- $reduce: {
790
- over,
791
- as: "__x",
792
- acc: "__acc",
793
- init: { $const: 0 },
794
- body: { $add: [{ $var: "__acc" }, { $const: 1 }] }
795
- }
796
- }
797
- ]
798
- };
799
- };
800
- var rewriteMin = (node13, recurse) => ({
801
- $reduce: {
802
- over: recurse(node13.$min.over),
803
- as: "__x",
804
- acc: "__acc",
805
- init: { $const: null },
806
- body: {
807
- $case: {
808
- branches: [
809
- { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
810
- { when: { $lt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
811
- ],
812
- else: { $var: "__acc" }
813
- }
814
- }
815
- }
816
- });
817
- var rewriteMax = (node13, recurse) => ({
818
- $reduce: {
819
- over: recurse(node13.$max.over),
820
- as: "__x",
821
- acc: "__acc",
822
- init: { $const: null },
823
- body: {
824
- $case: {
825
- branches: [
826
- { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
827
- { when: { $gt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
828
- ],
829
- else: { $var: "__acc" }
830
- }
831
- }
832
- }
833
- });
834
- var rewritePluck = (node13, recurse) => ({
835
- $map: {
836
- over: recurse(node13.$pluck.over),
837
- as: "__item",
838
- body: { $get: { from: { $var: "__item" }, path: [node13.$pluck.key] } }
839
- }
840
- });
841
- var rewriteTake = (node13, recurse) => ({
842
- $slice: {
843
- from: recurse(node13.$take.from),
844
- start: 0,
845
- end: node13.$take.count
846
- }
847
- });
848
- var rewriteDrop = (node13, recurse) => ({
849
- $slice: {
850
- from: recurse(node13.$drop.from),
851
- start: node13.$drop.count
852
- }
853
- });
854
- var rewriteMatch = (node13, recurse) => ({
855
- $filter: {
856
- over: recurse(node13.$match.over),
857
- as: node13.$match.as,
858
- when: {
859
- $contains: {
860
- value: { $var: node13.$match.as },
861
- search: recurse(node13.$match.search)
862
- }
863
- }
864
- }
865
- });
866
- var rewriteFlatMap = (node13, recurse) => ({
867
- $flatten: {
868
- $map: {
869
- over: recurse(node13.$flatMap.over),
870
- as: node13.$flatMap.as,
871
- body: recurse(node13.$flatMap.body)
872
- }
873
- }
874
- });
875
-
876
- // src/sugar/desugar.ts
877
- var desugar = (node13) => {
878
- if (node13 === null || node13 === void 0) return node13;
879
- if (typeof node13 !== "object") return node13;
880
- if (Array.isArray(node13)) return node13.map(desugar);
881
- if (isSumNode(node13)) return rewriteSum(node13, desugar);
882
- if (isAvgNode(node13)) return rewriteAvg(node13, desugar);
883
- if (isCountNode(node13)) return rewriteCount(node13, desugar);
884
- if (isMinNode(node13)) return rewriteMin(node13, desugar);
885
- if (isMaxNode(node13)) return rewriteMax(node13, desugar);
886
- if (isPluckNode(node13)) return rewritePluck(node13, desugar);
887
- if (isTakeNode(node13)) return rewriteTake(node13, desugar);
888
- if (isDropNode(node13)) return rewriteDrop(node13, desugar);
889
- if (isMatchNode(node13)) return rewriteMatch(node13, desugar);
890
- if (isFlatMapNode(node13)) return rewriteFlatMap(node13, desugar);
891
- if (isJsonObject(node13)) {
892
- const result = {};
893
- for (const [key, value] of Object.entries(node13)) {
894
- result[key] = desugar(value);
895
- }
896
- return result;
897
- }
898
- return node13;
899
- };
900
-
901
- // src/engine/budget.ts
902
- var DEFAULT_LIMITS = { maxSteps: 1e6, maxStringLength: 1e6, maxValues: 1e6 };
903
- var createBudget = (limits) => ({ limits: { ...DEFAULT_LIMITS, ...limits }, steps: 0, sizes: /* @__PURE__ */ new WeakMap() });
904
- var refuse = (what, limit) => {
905
- throw new PrismError(`Evaluation stopped: ${what} (limit ${limit})`, ErrorCode.BUDGET, { details: { limit } });
906
- };
907
- var spendStep = (budget) => {
908
- budget.steps += 1;
909
- if (budget.steps > budget.limits.maxSteps) refuse("it evaluated too many nodes", budget.limits.maxSteps);
910
- };
911
- var sizeOf = (value, budget) => {
912
- if (value === null || typeof value !== "object") return 1;
913
- const known = budget.sizes.get(value);
914
- if (known !== void 0) return known;
915
- let size = 1;
916
- for (const inner of Array.isArray(value) ? value : Object.values(value)) {
917
- size += sizeOf(inner, budget);
918
- if (size > budget.limits.maxValues) break;
919
- }
920
- budget.sizes.set(value, size);
921
- return size;
922
- };
923
- var measureString = (value, budget) => {
924
- if (typeof value === "string" && value.length > budget.limits.maxStringLength) refuse(`a string of ${value.length} characters`, budget.limits.maxStringLength);
925
- };
926
- var measure = (value, budget) => {
927
- if (budget === void 0) return;
928
- measureString(value, budget);
929
- if (value !== null && typeof value === "object" && sizeOf(value, budget) > budget.limits.maxValues) {
930
- refuse("a result holding too many values", budget.limits.maxValues);
931
- }
932
- };
933
-
934
- // src/utils/jsonpath.ts
935
- var parseJsonPath = (path) => {
936
- if (!path.startsWith("$.")) return [];
937
- const segments = [];
938
- let cursor = 2;
939
- let currentKey = "";
940
- const pushKey = () => {
941
- if (currentKey.length > 0) {
942
- segments.push({ type: "key", key: currentKey });
943
- currentKey = "";
944
- }
945
- };
946
- while (cursor < path.length) {
947
- const char = path[cursor];
948
- if (char === ".") {
949
- pushKey();
950
- cursor++;
951
- continue;
952
- }
953
- if (char === "[") {
954
- pushKey();
955
- cursor++;
956
- let numBuf = "";
957
- while (cursor < path.length && path[cursor] !== "]") {
958
- numBuf += path[cursor];
959
- cursor++;
960
- }
961
- if (path[cursor] !== "]") return [];
962
- cursor++;
963
- const index = Number(numBuf);
964
- if (!Number.isInteger(index) || index < 0) return [];
965
- segments.push({ type: "index", index });
966
- continue;
967
- }
968
- currentKey += char;
969
- cursor++;
970
- }
971
- pushKey();
972
- return segments;
973
- };
974
- var cache = /* @__PURE__ */ new Map();
975
- var parseJsonPathCached = (path) => {
976
- const cached = cache.get(path);
977
- if (cached) return cached;
978
- const parsed = parseJsonPath(path);
979
- cache.set(path, parsed);
980
- return parsed;
981
- };
982
- var primeJsonPathCache = (paths) => {
983
- for (const p of paths) {
984
- if (!cache.has(p)) cache.set(p, parseJsonPath(p));
985
- }
986
- };
987
- var getByPath = (root, segments) => {
988
- let current2 = root;
989
- for (const segment of segments) {
990
- if (segment.type === "key") {
991
- if (!isJsonObject(current2)) return void 0;
992
- current2 = current2[segment.key];
993
- } else {
994
- if (!isJsonArray(current2)) return void 0;
995
- current2 = current2[segment.index];
996
- }
997
- }
998
- return current2;
999
- };
1000
-
1001
- // src/ops/core.ops.ts
1002
- var SEGMENTS_KEY = "__segments";
1003
- var isSegmentsArray = (value) => Array.isArray(value);
1004
- var opRef = (node13, context, _evaluate) => {
1005
- const attached = Reflect.get(node13, SEGMENTS_KEY);
1006
- const segments = isSegmentsArray(attached) ? attached : parseJsonPathCached(node13.$ref);
1007
- const resolved = getByPath(context.source, segments);
1008
- if (resolved === void 0)
1009
- throw new PrismError("Path not found", ErrorCode.MISSING_PATH, { op: "$ref", path: node13.$ref });
1010
- return resolved;
1011
- };
1012
- var opConst = (node13, _context, _evaluate) => node13.$const;
1013
- var opVar = (node13, context, _evaluate) => {
1014
- const value = context.vars[node13.$var];
1015
- if (value === void 0)
1016
- throw new PrismError(`Variable not found: ${node13.$var}`, ErrorCode.VAR_NOT_FOUND, { op: "$var", path: node13.$var });
1017
- return value;
1018
- };
1019
- var opGet = (node13, context, evaluate2) => {
1020
- const { from, path, fallback } = node13.$get;
1021
- let current2 = evaluate2(from, context);
1022
- for (const segment of path) {
1023
- const evaluated = typeof segment === "object" && segment !== null ? evaluate2(segment, context) : segment;
1024
- if (typeof evaluated === "number") {
1025
- if (!isJsonArray(current2)) {
1026
- if (fallback !== void 0) return evaluate2(fallback, context);
1027
- throw new PrismError("Expected array for index access", ErrorCode.TYPE, { op: "$get" });
1028
- }
1029
- current2 = current2[evaluated];
1030
- } else {
1031
- const key = String(evaluated);
1032
- if (!isJsonObject(current2)) {
1033
- if (fallback !== void 0) return evaluate2(fallback, context);
1034
- throw new PrismError("Expected object for key access", ErrorCode.TYPE, { op: "$get" });
1035
- }
1036
- current2 = current2[key];
1037
- }
1038
- }
1039
- if (current2 === void 0) {
1040
- if (fallback !== void 0) return evaluate2(fallback, context);
1041
- throw new PrismError("Path not found", ErrorCode.MISSING_PATH, { op: "$get" });
1042
- }
1043
- return current2;
1044
- };
1045
- var opWith = (node13, context, evaluate2) => {
1046
- const { let: declarations, value } = node13.$with;
1047
- const extendedVars = { ...context.vars };
1048
- for (const [name, expr] of Object.entries(declarations)) {
1049
- extendedVars[name] = evaluate2(expr, context);
1050
- measure(extendedVars[name] ?? null, context.budget);
1051
- }
1052
- return evaluate2(value, { ...context, vars: extendedVars });
1053
- };
1054
-
1055
- // src/utils/compare.ts
1056
- var jsonEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1057
- var compare = (a, b) => {
1058
- if (typeof a === "number" && typeof b === "number") return a - b;
1059
- if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
1060
- return void 0;
1061
- };
1062
-
1063
- // src/ops/array.ops.ts
1064
- var requireArray = (value, op) => {
1065
- if (!isJsonArray(value))
1066
- throw new PrismError(`Expected array for ${op}`, ErrorCode.TYPE, { op });
1067
- return value;
1068
- };
1069
- var opMap = (node13, context, evaluate2) => {
1070
- const { over, as, body } = node13.$map;
1071
- const input = requireArray(evaluate2(over, context), "$map.over");
1072
- const result = [];
1073
- for (const item of input) {
1074
- result.push(evaluate2(body, { ...context, vars: { ...context.vars, [as]: item } }));
1075
- }
1076
- return result;
1077
- };
1078
- var opFilter = (node13, context, evaluate2) => {
1079
- const { over, as, when } = node13.$filter;
1080
- const input = requireArray(evaluate2(over, context), "$filter.over");
1081
- const result = [];
1082
- for (const item of input) {
1083
- const condition = evaluate2(when, { ...context, vars: { ...context.vars, [as]: item } });
1084
- if (condition) result.push(item);
1085
- }
1086
- return result;
1087
- };
1088
- var opReduce = (node13, context, evaluate2) => {
1089
- const { over, as, acc: accName = "acc", init, body } = node13.$reduce;
1090
- const input = requireArray(evaluate2(over, context), "$reduce.over");
1091
- let accumulator = evaluate2(init, context);
1092
- for (const item of input) {
1093
- accumulator = evaluate2(body, {
1094
- ...context,
1095
- vars: { ...context.vars, [as]: item, [accName]: accumulator }
1096
- });
1097
- measure(accumulator, context.budget);
1098
- }
1099
- return accumulator;
1100
- };
1101
- var opSlice = (node13, context, evaluate2) => {
1102
- const { from, start, end } = node13.$slice;
1103
- const input = evaluate2(from, context);
1104
- if (typeof input === "string") return input.slice(start, end);
1105
- if (isJsonArray(input)) return input.slice(start, end);
1106
- throw new PrismError("Expected array or string for $slice", ErrorCode.TYPE, { op: "$slice" });
1107
- };
1108
- var opFlatten = (node13, context, evaluate2) => {
1109
- const input = requireArray(evaluate2(node13.$flatten, context), "$flatten");
1110
- const result = [];
1111
- for (const item of input) {
1112
- if (isJsonArray(item)) result.push(...item);
1113
- else result.push(item);
1114
- }
1115
- return result;
1116
- };
1117
- var opUnique = (node13, context, evaluate2) => {
1118
- const input = requireArray(evaluate2(node13.$unique, context), "$unique");
1119
- const seen = /* @__PURE__ */ new Set();
1120
- const result = [];
1121
- for (const item of input) {
1122
- const key = JSON.stringify(item);
1123
- if (!seen.has(key)) {
1124
- seen.add(key);
1125
- result.push(item);
1126
- }
1127
- }
1128
- return result;
1129
- };
1130
- var opSortBy = (node13, context, evaluate2) => {
1131
- const { over, as, by, dir = "asc" } = node13.$sortBy;
1132
- const input = requireArray(evaluate2(over, context), "$sortBy.over");
1133
- const keyed = input.map((item) => ({
1134
- item,
1135
- key: evaluate2(by, { ...context, vars: { ...context.vars, [as]: item } })
1136
- }));
1137
- keyed.sort((a, b) => {
1138
- const cmp = compare(a.key, b.key);
1139
- if (cmp === void 0) return 0;
1140
- return dir === "desc" ? -cmp : cmp;
1141
- });
1142
- return keyed.map((k) => k.item);
1143
- };
1144
-
1145
- // src/ops/math.ops.ts
1146
- var requireNumbers = (node13, context, evaluate2, op) => {
1147
- const a = evaluate2(node13[0], context);
1148
- const b = evaluate2(node13[1], context);
1149
- if (typeof a !== "number" || typeof b !== "number")
1150
- throw new PrismError(`Expected numbers for ${op}`, ErrorCode.TYPE, { op });
1151
- return [a, b];
1152
- };
1153
- var opAdd = (node13, context, evaluate2) => {
1154
- const [a, b] = requireNumbers(node13.$add, context, evaluate2, "$add");
1155
- return a + b;
1156
- };
1157
- var opSub = (node13, context, evaluate2) => {
1158
- const [a, b] = requireNumbers(node13.$sub, context, evaluate2, "$sub");
1159
- return a - b;
1160
- };
1161
- var opMul = (node13, context, evaluate2) => {
1162
- const [a, b] = requireNumbers(node13.$mul, context, evaluate2, "$mul");
1163
- return a * b;
1164
- };
1165
- var opDiv = (node13, context, evaluate2) => {
1166
- const [a, b] = requireNumbers(node13.$div, context, evaluate2, "$div");
1167
- if (b === 0) throw new PrismError("Division by zero", ErrorCode.DIVISION_BY_ZERO, { op: "$div" });
1168
- return a / b;
1169
- };
1170
- var opRound = (node13, context, evaluate2) => {
1171
- const value = evaluate2(node13.$round.value, context);
1172
- if (typeof value !== "number")
1173
- throw new PrismError("Expected number for $round", ErrorCode.TYPE, { op: "$round" });
1174
- const digits = node13.$round.digits ?? 0;
1175
- const factor = Math.pow(10, digits);
1176
- return Math.round(value * factor) / factor;
1177
- };
1178
-
1179
- // src/ops/string.ops.ts
1180
- var opJoin = (node13, context, evaluate2) => {
1181
- const { parts, sep = "" } = node13.$join;
1182
- const list = evaluate2(parts, context);
1183
- if (!Array.isArray(list)) throw new PrismError("Expected $join.parts to evaluate to an array", ErrorCode.TYPE, { op: "$join" });
1184
- return list.map((p) => String(p ?? "")).join(sep);
1185
- };
1186
- var opToString = (node13, context, evaluate2) => {
1187
- const value = evaluate2(node13.$toString, context);
1188
- if (value === null) return "null";
1189
- if (typeof value === "object") return JSON.stringify(value);
1190
- return String(value);
1191
- };
1192
- var opInterpolate = (node13, context, evaluate2) => {
1193
- const { template, values: valuesNode } = node13.$interpolate;
1194
- const values = evaluate2(valuesNode, context);
1195
- if (!isJsonObject(values))
1196
- throw new PrismError("Expected object for $interpolate.values", ErrorCode.TYPE, { op: "$interpolate" });
1197
- return template.replace(
1198
- /\{\{(\w+)\}\}/g,
1199
- (_match, key) => String(values[key] ?? "")
1200
- );
1201
- };
1202
- var fillOne = (value) => {
1203
- if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
1204
- const { phrase, slots } = value;
1205
- if (typeof phrase !== "string" || !isJsonObject(slots)) return value;
1206
- return phrase.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (hole, name) => {
1207
- const slot = slots[name];
1208
- if (slot === void 0 || slot === null) return hole;
1209
- const filled = fillOne(slot);
1210
- return typeof filled === "object" ? hole : String(filled);
1211
- });
1212
- };
1213
- var opFill = (node13, context, evaluate2) => fillOne(evaluate2(node13.$fill, context));
1214
- var opTrim = (node13, context, evaluate2) => {
1215
- const value = evaluate2(node13.$trim, context);
1216
- if (typeof value !== "string")
1217
- throw new PrismError("Expected string for $trim", ErrorCode.TYPE, { op: "$trim" });
1218
- return value.trim();
1219
- };
1220
- var opLower = (node13, context, evaluate2) => {
1221
- const value = evaluate2(node13.$lower, context);
1222
- if (typeof value !== "string")
1223
- throw new PrismError("Expected string for $lower", ErrorCode.TYPE, { op: "$lower" });
1224
- return value.toLowerCase();
1225
- };
1226
- var opUpper = (node13, context, evaluate2) => {
1227
- const value = evaluate2(node13.$upper, context);
1228
- if (typeof value !== "string")
1229
- throw new PrismError("Expected string for $upper", ErrorCode.TYPE, { op: "$upper" });
1230
- return value.toUpperCase();
1231
- };
1232
- var opSplit = (node13, context, evaluate2) => {
1233
- const value = evaluate2(node13.$split.value, context);
1234
- if (typeof value !== "string")
1235
- throw new PrismError("Expected string for $split", ErrorCode.TYPE, { op: "$split" });
1236
- return value.split(node13.$split.sep);
1237
- };
1238
- var opReplace = (node13, context, evaluate2) => {
1239
- const value = evaluate2(node13.$replace.value, context);
1240
- if (typeof value !== "string")
1241
- throw new PrismError("Expected string for $replace", ErrorCode.TYPE, { op: "$replace" });
1242
- return value.replace(node13.$replace.search, node13.$replace.replacement);
1243
- };
1244
-
1245
- // src/ops/predicate.ops.ts
1246
- var opEq = (node13, context, evaluate2) => {
1247
- const a = evaluate2(node13.$eq[0], context);
1248
- const b = evaluate2(node13.$eq[1], context);
1249
- return jsonEqual(a, b);
1250
- };
1251
- var opNeq = (node13, context, evaluate2) => {
1252
- const a = evaluate2(node13.$neq[0], context);
1253
- const b = evaluate2(node13.$neq[1], context);
1254
- return !jsonEqual(a, b);
1255
- };
1256
- var compareOp = (pair, context, evaluate2, op, test) => {
1257
- const a = evaluate2(pair[0], context);
1258
- const b = evaluate2(pair[1], context);
1259
- const cmp = compare(a, b);
1260
- if (cmp === void 0)
1261
- throw new PrismError(`Cannot compare values for ${op}`, ErrorCode.TYPE, { op });
1262
- return test(cmp);
1263
- };
1264
- var opGt = (node13, ctx, ev) => compareOp(node13.$gt, ctx, ev, "$gt", (c) => c > 0);
1265
- var opGte = (node13, ctx, ev) => compareOp(node13.$gte, ctx, ev, "$gte", (c) => c >= 0);
1266
- var opLt = (node13, ctx, ev) => compareOp(node13.$lt, ctx, ev, "$lt", (c) => c < 0);
1267
- var opLte = (node13, ctx, ev) => compareOp(node13.$lte, ctx, ev, "$lte", (c) => c <= 0);
1268
- var opEmpty = (node13, context, evaluate2) => {
1269
- const value = evaluate2(node13.$empty, context);
1270
- if (value === null || value === void 0) return true;
1271
- if (typeof value === "string") return value.length === 0;
1272
- if (isJsonArray(value)) return value.length === 0;
1273
- if (isJsonObject(value)) return Object.keys(value).length === 0;
1274
- return false;
1275
- };
1276
- var opStartsWith = (node13, context, evaluate2) => {
1277
- const value = evaluate2(node13.$startsWith.value, context);
1278
- const prefix = evaluate2(node13.$startsWith.prefix, context);
1279
- if (typeof value !== "string" || typeof prefix !== "string")
1280
- throw new PrismError("Expected strings for $startsWith", ErrorCode.TYPE, { op: "$startsWith" });
1281
- return value.startsWith(prefix);
1282
- };
1283
- var opEndsWith = (node13, context, evaluate2) => {
1284
- const value = evaluate2(node13.$endsWith.value, context);
1285
- const suffix = evaluate2(node13.$endsWith.suffix, context);
1286
- if (typeof value !== "string" || typeof suffix !== "string")
1287
- throw new PrismError("Expected strings for $endsWith", ErrorCode.TYPE, { op: "$endsWith" });
1288
- return value.endsWith(suffix);
1289
- };
1290
- var opContains = (node13, context, evaluate2) => {
1291
- const value = evaluate2(node13.$contains.value, context);
1292
- const search = evaluate2(node13.$contains.search, context);
1293
- if (typeof value !== "string" || typeof search !== "string")
1294
- throw new PrismError("Expected strings for $contains", ErrorCode.TYPE, { op: "$contains" });
1295
- return value.includes(search);
1296
- };
1297
-
1298
- // src/ops/logic.ops.ts
1299
- var opNot = (node13, context, evaluate2) => !evaluate2(node13.$not, context);
1300
- var opAnd = (node13, context, evaluate2) => {
1301
- let last = true;
1302
- for (const operand of node13.$and) {
1303
- last = evaluate2(operand, context);
1304
- if (!last) return last;
1305
- }
1306
- return last;
1307
- };
1308
- var opOr = (node13, context, evaluate2) => {
1309
- let last = false;
1310
- for (const operand of node13.$or) {
1311
- last = evaluate2(operand, context);
1312
- if (last) return last;
1313
- }
1314
- return last;
1315
- };
1316
-
1317
- // src/ops/structure.ops.ts
1318
- var opMerge = (node13, context, evaluate2) => {
1319
- const result = {};
1320
- for (const part of node13.$merge) {
1321
- const evaluated = evaluate2(part, context);
1322
- if (!isJsonObject(evaluated))
1323
- throw new PrismError("Expected object for $merge element", ErrorCode.TYPE, { op: "$merge" });
1324
- Object.assign(result, evaluated);
1325
- }
1326
- return result;
1327
- };
1328
- var opCoalesce = (node13, context, evaluate2) => {
1329
- for (const candidate of node13.$coalesce) {
1330
- const value = evaluate2(candidate, context);
1331
- if (value !== null && value !== void 0) return value;
1332
- }
1333
- return null;
1334
- };
1335
- var opCase = (node13, context, evaluate2) => {
1336
- for (const branch of node13.$case.branches) {
1337
- const condition = evaluate2(branch.when, context);
1338
- if (condition) return evaluate2(branch.then, context);
1339
- }
1340
- if (node13.$case.else !== void 0) return evaluate2(node13.$case.else, context);
1341
- return null;
1342
- };
1343
- var opEntriesOf = (node13, context, evaluate2) => {
1344
- const value = evaluate2(node13.$entriesOf, context);
1345
- if (!isJsonObject(value))
1346
- throw new PrismError("Expected object for $entriesOf", ErrorCode.TYPE, { op: "$entriesOf" });
1347
- return Object.entries(value).map(([k, v]) => [k, v]);
1348
- };
1349
- var opKeyBy = (node13, context, evaluate2) => {
1350
- const { over, as, key: keyExpr } = node13.$keyBy;
1351
- const input = evaluate2(over, context);
1352
- if (!isJsonArray(input))
1353
- throw new PrismError("Expected array for $keyBy.over", ErrorCode.TYPE, { op: "$keyBy" });
1354
- const result = {};
1355
- for (const item of input) {
1356
- const key = evaluate2(keyExpr, { ...context, vars: { ...context.vars, [as]: item } });
1357
- result[String(key)] = item;
1358
- }
1359
- return result;
1360
- };
1361
- var opGroupBy = (node13, context, evaluate2) => {
1362
- const { over, as, key: keyExpr } = node13.$groupBy;
1363
- const input = evaluate2(over, context);
1364
- if (!isJsonArray(input))
1365
- throw new PrismError("Expected array for $groupBy.over", ErrorCode.TYPE, { op: "$groupBy" });
1366
- const result = {};
1367
- for (const item of input) {
1368
- const key = String(evaluate2(keyExpr, { ...context, vars: { ...context.vars, [as]: item } }));
1369
- if (!result[key]) result[key] = [];
1370
- result[key].push(item);
1371
- }
1372
- return result;
1373
- };
1374
-
1375
- // src/ops/object.ops.ts
1376
- var opKeys = (node13, context, evaluate2) => {
1377
- const value = evaluate2(node13.$keys, context);
1378
- if (!isJsonObject(value))
1379
- throw new PrismError("Expected object for $keys", ErrorCode.TYPE, { op: "$keys" });
1380
- return Object.keys(value);
1381
- };
1382
- var opValues = (node13, context, evaluate2) => {
1383
- const value = evaluate2(node13.$values, context);
1384
- if (!isJsonObject(value))
1385
- throw new PrismError("Expected object for $values", ErrorCode.TYPE, { op: "$values" });
1386
- return Object.values(value);
1387
- };
1388
- var opFromEntries = (node13, context, evaluate2) => {
1389
- const value = evaluate2(node13.$fromEntries, context);
1390
- if (!isJsonArray(value))
1391
- throw new PrismError("Expected array for $fromEntries", ErrorCode.TYPE, { op: "$fromEntries" });
1392
- const result = {};
1393
- for (const entry of value) {
1394
- if (!isJsonArray(entry) || entry.length < 2)
1395
- throw new PrismError("Expected [key, value] pairs for $fromEntries", ErrorCode.TYPE, { op: "$fromEntries" });
1396
- result[String(entry[0])] = entry[1];
1397
- }
1398
- return result;
1399
- };
1400
- var opPick = (node13, context, evaluate2) => {
1401
- const value = evaluate2(node13.$pick.from, context);
1402
- if (!isJsonObject(value))
1403
- throw new PrismError("Expected object for $pick", ErrorCode.TYPE, { op: "$pick" });
1404
- const result = {};
1405
- for (const key of node13.$pick.keys) {
1406
- if (key in value) result[key] = value[key];
1407
- }
1408
- return result;
1409
- };
1410
- var opOmit = (node13, context, evaluate2) => {
1411
- const value = evaluate2(node13.$omit.from, context);
1412
- if (!isJsonObject(value))
1413
- throw new PrismError("Expected object for $omit", ErrorCode.TYPE, { op: "$omit" });
1414
- const keysToOmit = new Set(node13.$omit.keys);
1415
- const result = {};
1416
- for (const [k, v] of Object.entries(value)) {
1417
- if (!keysToOmit.has(k)) result[k] = v;
1418
- }
1419
- return result;
1420
- };
1421
- var opType = (node13, context, evaluate2) => {
1422
- const value = evaluate2(node13.$type, context);
1423
- if (value === null) return "null";
1424
- if (isJsonArray(value)) return "array";
1425
- return typeof value;
1426
- };
1427
- var opLength = (node13, context, evaluate2) => {
1428
- const value = evaluate2(node13.$length, context);
1429
- if (typeof value === "string") return value.length;
1430
- if (isJsonArray(value)) return value.length;
1431
- throw new PrismError("Expected array or string for $length", ErrorCode.TYPE, { op: "$length" });
1432
- };
1433
-
1434
- // src/ops/transform.ops.ts
1435
- var has = (value, path) => {
1436
- let at = value;
1437
- for (const segment of path) {
1438
- if (typeof segment === "number") {
1439
- if (!isJsonArray(at) || segment >= at.length) return false;
1440
- at = at[segment] ?? null;
1441
- } else {
1442
- if (!isJsonObject(at) || !Object.prototype.hasOwnProperty.call(at, segment)) return false;
1443
- at = at[segment] ?? null;
1444
- }
1445
- }
1446
- return true;
1447
- };
1448
- var opHas = (node13, context, evaluate2) => has(evaluate2(node13.$has.from, context), node13.$has.path);
1449
- var opRenameKeys = (node13, context, evaluate2) => {
1450
- const value = evaluate2(node13.$renameKeys.from, context);
1451
- if (!isJsonObject(value)) throw new PrismError("Expected object for $renameKeys", ErrorCode.TYPE, { op: "$renameKeys" });
1452
- const { map } = node13.$renameKeys;
1453
- const renamedTo = new Set(Object.entries(map).filter(([from]) => Object.prototype.hasOwnProperty.call(value, from)).map(([, to]) => to));
1454
- const result = {};
1455
- for (const [key, v] of Object.entries(value)) {
1456
- const target = map[key];
1457
- if (target !== void 0) result[target] = v;
1458
- else if (!renamedTo.has(key)) result[key] = v;
1459
- }
1460
- return result;
1461
- };
1462
- var current = (value, path) => {
1463
- let at = value;
1464
- for (const segment of path) {
1465
- if (typeof segment === "number") at = isJsonArray(at) ? at[segment] ?? null : null;
1466
- else at = isJsonObject(at) ? at[segment] ?? null : null;
1467
- }
1468
- return at;
1469
- };
1470
- var setIn = (value, path, next, full) => {
1471
- const [head, ...rest] = path;
1472
- if (head === void 0) return next;
1473
- if (typeof head === "number") {
1474
- if (!isJsonArray(value) || head >= value.length) {
1475
- throw new PrismError(`No array item at ${full.join(".")}`, ErrorCode.MISSING_PATH, { op: "$update", path: full.join(".") });
1476
- }
1477
- return value.map((item, i) => i === head ? setIn(item, rest, next, full) : item);
1478
- }
1479
- const base = isJsonObject(value) ? value : {};
1480
- return { ...base, [head]: setIn(base[head] ?? null, rest, next, full) };
1481
- };
1482
- var opUpdate = (node13, context, evaluate2) => {
1483
- const { from, path, value, as } = node13.$update;
1484
- const source = evaluate2(from, context);
1485
- const next = evaluate2(value, { ...context, vars: { ...context.vars, [as ?? "current"]: current(source, path) } });
1486
- return setIn(source, path, next, path);
1487
- };
1488
- var opAssert = (node13, context, evaluate2) => {
1489
- if (!evaluate2(node13.$assert.when, context)) throw new PrismError(node13.$assert.message, ErrorCode.ASSERT, { op: "$assert" });
1490
- return evaluate2(node13.$assert.value, context);
1491
- };
1492
- var opWalk = (node13, context, evaluate2) => {
1493
- const { over, as, rules, order } = node13.$walk;
1494
- const rewrite = (value) => {
1495
- const scope = { ...context, vars: { ...context.vars, [as]: value } };
1496
- for (const rule of rules) {
1497
- if (evaluate2(rule.when, scope)) return { matched: true, value: evaluate2(rule.then, scope) };
1498
- }
1499
- return { matched: false, value };
1500
- };
1501
- const children = (value, visit) => {
1502
- if (isJsonArray(value)) return value.map(visit);
1503
- if (isJsonObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, visit(v)]));
1504
- return value;
1505
- };
1506
- const post = (value) => rewrite(children(value, post)).value;
1507
- const pre = (value) => children(rewrite(value).value, pre);
1508
- return (order ?? "post") === "pre" ? pre(evaluate2(over, context)) : post(evaluate2(over, context));
1509
- };
1510
- dayjs__default.default.extend(utc__default.default);
1511
- var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
1512
- var isDateOnly = (value) => typeof value === "string" && DATE_ONLY.test(value);
1513
- var parseDate = (value, op) => {
1514
- if (typeof value !== "string" && typeof value !== "number")
1515
- throw new PrismError(`Expected string or number for ${op}`, ErrorCode.TYPE, { op });
1516
- const d = isDateOnly(value) ? dayjs__default.default.utc(value) : dayjs__default.default(value);
1517
- if (!d.isValid())
1518
- throw new PrismError(`Invalid date for ${op}: ${String(value)}`, ErrorCode.DATE_INVALID, { op });
1519
- return d;
1520
- };
1521
- var opDate = (node13, context, evaluate2) => {
1522
- const value = evaluate2(node13.$date.value, context);
1523
- const d = parseDate(value, "$date");
1524
- const instance = node13.$date.utc ? d.utc() : d;
1525
- if (node13.$date.format) return instance.format(node13.$date.format);
1526
- return instance.toISOString();
1527
- };
1528
- var opDateAdd = (node13, context, evaluate2) => {
1529
- const value = evaluate2(node13.$dateAdd.date, context);
1530
- const d = parseDate(value, "$dateAdd");
1531
- const moved = d.add(node13.$dateAdd.amount, node13.$dateAdd.unit);
1532
- return isDateOnly(value) ? moved.format("YYYY-MM-DD") : moved.toISOString();
1533
- };
1534
- var opDateDiff = (node13, context, evaluate2) => {
1535
- const from = evaluate2(node13.$dateDiff.from, context);
1536
- const to = evaluate2(node13.$dateDiff.to, context);
1537
- const fromDate = parseDate(from, "$dateDiff.from");
1538
- const toDate = parseDate(to, "$dateDiff.to");
1539
- return toDate.diff(fromDate, node13.$dateDiff.unit);
1540
- };
1541
-
1542
- // src/ops/intl.ops.ts
1543
- var DATE_FORMATTERS = /* @__PURE__ */ new Map();
1544
- var NUMBER_FORMATTERS = /* @__PURE__ */ new Map();
1545
- var DATE_ONLY2 = /^\d{4}-\d{2}-\d{2}$/;
1546
- var localeOf = (value, op) => {
1547
- if (typeof value !== "string" || value.trim() === "")
1548
- throw new PrismError(`${op} needs a locale tag (e.g. "de-AT")`, ErrorCode.TYPE, { op });
1549
- return value;
1550
- };
1551
- var isBlank = (value) => value === null || value === void 0 || value === "";
1552
- var fallbackOf = (raw, context, evaluate2) => {
1553
- if (raw === void 0) return "";
1554
- const resolved = evaluate2(raw, context);
1555
- return resolved === null || resolved === void 0 ? "" : resolved;
1556
- };
1557
- var numberOf = (value, op) => {
1558
- const parsed = typeof value === "number" ? value : Number(value);
1559
- if (!Number.isFinite(parsed)) throw new PrismError(`${op} expected a number, got ${JSON.stringify(value)}`, ErrorCode.TYPE, { op });
1560
- return parsed;
1561
- };
1562
- var opLocaleDate = (node13, context, evaluate2) => {
1563
- const spec = node13.$localeDate;
1564
- const value = evaluate2(spec.value, context);
1565
- if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
1566
- const locale = localeOf(evaluate2(spec.locale, context), "$localeDate");
1567
- const authored = spec.options ?? { dateStyle: "medium" };
1568
- const dateOnly = typeof value === "string" && DATE_ONLY2.test(value);
1569
- const options = {
1570
- ...authored,
1571
- ...authored.timeZone === void 0 && dateOnly ? { timeZone: "UTC" } : {}
1572
- };
1573
- const parsed = typeof value === "number" ? new Date(value) : new Date(String(value));
1574
- if (Number.isNaN(parsed.getTime()))
1575
- throw new PrismError(`Invalid date for $localeDate: ${String(value)}`, ErrorCode.DATE_INVALID, { op: "$localeDate" });
1576
- const key = `${locale}\0${JSON.stringify(options)}`;
1577
- let formatter = DATE_FORMATTERS.get(key);
1578
- if (formatter === void 0) {
1579
- formatter = new Intl.DateTimeFormat(locale, options);
1580
- DATE_FORMATTERS.set(key, formatter);
1581
- }
1582
- return formatter.format(parsed);
1583
- };
1584
- var minorUnitDivisor = (locale, currency) => {
1585
- const key = `divisor\0${locale}\0${currency}`;
1586
- let formatter = NUMBER_FORMATTERS.get(key);
1587
- if (formatter === void 0) {
1588
- try {
1589
- formatter = new Intl.NumberFormat(locale, { style: "currency", currency });
1590
- } catch {
1591
- return 100;
1592
- }
1593
- NUMBER_FORMATTERS.set(key, formatter);
1594
- }
1595
- return 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2);
1596
- };
1597
- var opLocaleMoney = (node13, context, evaluate2) => {
1598
- const spec = node13.$localeMoney;
1599
- const value = evaluate2(spec.value, context);
1600
- if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
1601
- const locale = localeOf(evaluate2(spec.locale, context), "$localeMoney");
1602
- const rawCurrency = evaluate2(spec.currency, context);
1603
- if (typeof rawCurrency !== "string" || rawCurrency.trim() === "")
1604
- throw new PrismError("$localeMoney needs an ISO-4217 currency code", ErrorCode.TYPE, { op: "$localeMoney" });
1605
- const currency = rawCurrency.toUpperCase();
1606
- const amount = numberOf(value, "$localeMoney");
1607
- const major = spec.minorUnits === false ? amount : amount / minorUnitDivisor(locale, currency);
1608
- const options = {
1609
- style: "currency",
1610
- currency,
1611
- ...spec.digits === void 0 ? {} : { minimumFractionDigits: spec.digits, maximumFractionDigits: spec.digits }
1612
- };
1613
- const key = `${locale}\0${JSON.stringify(options)}`;
1614
- let formatter = NUMBER_FORMATTERS.get(key);
1615
- if (formatter === void 0) {
1616
- try {
1617
- formatter = new Intl.NumberFormat(locale, options);
1618
- } catch {
1619
- return `${currency} ${major.toFixed(spec.digits ?? 2)}`;
1620
- }
1621
- NUMBER_FORMATTERS.set(key, formatter);
1622
- }
1623
- return formatter.format(major);
1624
- };
1625
- var opLocaleNumber = (node13, context, evaluate2) => {
1626
- const spec = node13.$localeNumber;
1627
- const value = evaluate2(spec.value, context);
1628
- if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
1629
- const locale = localeOf(evaluate2(spec.locale, context), "$localeNumber");
1630
- const options = {
1631
- style: spec.style ?? "decimal",
1632
- ...spec.digits === void 0 ? {} : { maximumFractionDigits: spec.digits },
1633
- ...spec.minDigits === void 0 ? {} : { minimumFractionDigits: spec.minDigits },
1634
- ...spec.compact === true ? { notation: "compact" } : {}
1635
- };
1636
- const key = `${locale}\0${JSON.stringify(options)}`;
1637
- let formatter = NUMBER_FORMATTERS.get(key);
1638
- if (formatter === void 0) {
1639
- formatter = new Intl.NumberFormat(locale, options);
1640
- NUMBER_FORMATTERS.set(key, formatter);
1641
- }
1642
- return formatter.format(numberOf(value, "$localeNumber"));
1643
- };
1644
-
1645
- // src/engine/evaluate.ts
1646
- var HANDLER_KEY = "__op";
1647
- var isAttachedFn = (value) => typeof value === "function";
1648
- var evaluateNode = (node13, context) => {
1649
- const { budget } = context;
1650
- if (budget === void 0) return evaluateUnbudgeted(node13, context);
1651
- spendStep(budget);
1652
- const out = evaluateUnbudgeted(node13, context);
1653
- measureString(out, budget);
1654
- return out;
1655
- };
1656
- var evaluateUnbudgeted = (node13, context) => {
1657
- if (node13 === null || node13 === void 0) return null;
1658
- if (typeof node13 === "string" || typeof node13 === "number" || typeof node13 === "boolean") return node13;
1659
- if (Array.isArray(node13)) return node13.map((n) => evaluateNode(n, context));
1660
- if (typeof node13 !== "object") return null;
1661
- const obj = node13;
1662
- const attached = obj[HANDLER_KEY];
1663
- if (isAttachedFn(attached)) return attached(obj, context, evaluateNode);
1664
- if (isRefNode(obj)) return opRef(obj, context);
1665
- if (isConstNode(obj)) return opConst(obj);
1666
- if (isVarNode(obj)) return opVar(obj, context);
1667
- if (isGetNode(obj)) return opGet(obj, context, evaluateNode);
1668
- if (isWithNode(obj)) return opWith(obj, context, evaluateNode);
1669
- if (isMapNode(obj)) return opMap(obj, context, evaluateNode);
1670
- if (isFilterNode(obj)) return opFilter(obj, context, evaluateNode);
1671
- if (isReduceNode(obj)) return opReduce(obj, context, evaluateNode);
1672
- if (isSliceNode(obj)) return opSlice(obj, context, evaluateNode);
1673
- if (isFlattenNode(obj)) return opFlatten(obj, context, evaluateNode);
1674
- if (isUniqueNode(obj)) return opUnique(obj, context, evaluateNode);
1675
- if (isSortByNode(obj)) return opSortBy(obj, context, evaluateNode);
1676
- if (isAddNode(obj)) return opAdd(obj, context, evaluateNode);
1677
- if (isSubNode(obj)) return opSub(obj, context, evaluateNode);
1678
- if (isMulNode(obj)) return opMul(obj, context, evaluateNode);
1679
- if (isDivNode(obj)) return opDiv(obj, context, evaluateNode);
1680
- if (isRoundNode(obj)) return opRound(obj, context, evaluateNode);
1681
- if (isJoinNode(obj)) return opJoin(obj, context, evaluateNode);
1682
- if (isToStringNode(obj)) return opToString(obj, context, evaluateNode);
1683
- if (isInterpolateNode(obj)) return opInterpolate(obj, context, evaluateNode);
1684
- if (isFillNode(obj)) return opFill(obj, context, evaluateNode);
1685
- if (isTrimNode(obj)) return opTrim(obj, context, evaluateNode);
1686
- if (isLowerNode(obj)) return opLower(obj, context, evaluateNode);
1687
- if (isUpperNode(obj)) return opUpper(obj, context, evaluateNode);
1688
- if (isSplitNode(obj)) return opSplit(obj, context, evaluateNode);
1689
- if (isReplaceNode(obj)) return opReplace(obj, context, evaluateNode);
1690
- if (isEqNode(obj)) return opEq(obj, context, evaluateNode);
1691
- if (isNeqNode(obj)) return opNeq(obj, context, evaluateNode);
1692
- if (isGtNode(obj)) return opGt(obj, context, evaluateNode);
1693
- if (isGteNode(obj)) return opGte(obj, context, evaluateNode);
1694
- if (isLtNode(obj)) return opLt(obj, context, evaluateNode);
1695
- if (isLteNode(obj)) return opLte(obj, context, evaluateNode);
1696
- if (isEmptyNode(obj)) return opEmpty(obj, context, evaluateNode);
1697
- if (isStartsWithNode(obj)) return opStartsWith(obj, context, evaluateNode);
1698
- if (isEndsWithNode(obj)) return opEndsWith(obj, context, evaluateNode);
1699
- if (isContainsNode(obj)) return opContains(obj, context, evaluateNode);
1700
- if (isNotNode(obj)) return opNot(obj, context, evaluateNode);
1701
- if (isAndNode(obj)) return opAnd(obj, context, evaluateNode);
1702
- if (isOrNode(obj)) return opOr(obj, context, evaluateNode);
1703
- if (isMergeNode(obj)) return opMerge(obj, context, evaluateNode);
1704
- if (isCoalesceNode(obj)) return opCoalesce(obj, context, evaluateNode);
1705
- if (isCaseNode(obj)) return opCase(obj, context, evaluateNode);
1706
- if (isEntriesOfNode(obj)) return opEntriesOf(obj, context, evaluateNode);
1707
- if (isKeyByNode(obj)) return opKeyBy(obj, context, evaluateNode);
1708
- if (isGroupByNode(obj)) return opGroupBy(obj, context, evaluateNode);
1709
- if (isKeysNode(obj)) return opKeys(obj, context, evaluateNode);
1710
- if (isValuesNode(obj)) return opValues(obj, context, evaluateNode);
1711
- if (isFromEntriesNode(obj)) return opFromEntries(obj, context, evaluateNode);
1712
- if (isPickNode(obj)) return opPick(obj, context, evaluateNode);
1713
- if (isOmitNode(obj)) return opOmit(obj, context, evaluateNode);
1714
- if (isTypeNode(obj)) return opType(obj, context, evaluateNode);
1715
- if (isLengthNode(obj)) return opLength(obj, context, evaluateNode);
1716
- if (isHasNode(obj)) return opHas(obj, context, evaluateNode);
1717
- if (isRenameKeysNode(obj)) return opRenameKeys(obj, context, evaluateNode);
1718
- if (isUpdateNode(obj)) return opUpdate(obj, context, evaluateNode);
1719
- if (isAssertNode(obj)) return opAssert(obj, context, evaluateNode);
1720
- if (isWalkNode(obj)) return opWalk(obj, context, evaluateNode);
1721
- if (isDateNode(obj)) return opDate(obj, context, evaluateNode);
1722
- if (isDateAddNode(obj)) return opDateAdd(obj, context, evaluateNode);
1723
- if (isDateDiffNode(obj)) return opDateDiff(obj, context, evaluateNode);
1724
- if (isLocaleDateNode(obj)) return opLocaleDate(obj, context, evaluateNode);
1725
- if (isLocaleMoneyNode(obj)) return opLocaleMoney(obj, context, evaluateNode);
1726
- if (isLocaleNumberNode(obj)) return opLocaleNumber(obj, context, evaluateNode);
1727
- if (isPlainObject(obj)) {
1728
- const optionalFields = new Set(
1729
- Array.isArray(obj[OPTIONAL_FIELDS_KEY]) ? obj[OPTIONAL_FIELDS_KEY] : []
1730
- );
1731
- const result = {};
1732
- for (const [key, value] of Object.entries(obj)) {
1733
- if (key === OPTIONAL_FIELDS_KEY) continue;
1734
- const isOptional = optionalFields.has(key);
1735
- try {
1736
- const evaluated = evaluateNode(value, context);
1737
- if (isOptional && (evaluated === null || evaluated === void 0)) continue;
1738
- result[key] = evaluated;
1739
- } catch (error) {
1740
- if (isOptional && error instanceof PrismError && error.code === ErrorCode.MISSING_PATH) continue;
1741
- throw error;
1742
- }
1743
- }
1744
- return result;
1745
- }
1746
- const unknownKeys = Object.keys(obj).filter((k) => k.startsWith("$"));
1747
- throw new PrismError("Unsupported node shape", ErrorCode.NODE_SHAPE, {
1748
- details: { keys: unknownKeys, preview: JSON.stringify(obj).slice(0, 100) }
1749
- });
1750
- };
1751
- var evaluate = (config, source, limits) => {
1752
- if (strata.exceedsDepth(config)) throw new PrismError("Invalid config", ErrorCode.SCHEMA, { details: { issues: [{ path: "root", message: strata.depthRefusal() }] } });
1753
- const parsed = ConfigSchema.safeParse(config);
1754
- if (!parsed.success) {
1755
- const issues = explainIssues(parsed.error.issues).map((i) => ({ path: i.path.join(".") || "root", message: i.message }));
1756
- throw new PrismError("Invalid config", ErrorCode.SCHEMA, { details: { issues } });
1757
- }
1758
- const desugared = desugar(parsed.data);
1759
- const budget = createBudget(limits);
1760
- const result = evaluateNode(desugared, { source, vars: {}, budget });
1761
- measure(result, budget);
1762
- return result;
1763
- };
1764
- var evaluateSafe = (config, source, limits) => {
1765
- try {
1766
- return { ok: true, data: evaluate(config, source, limits) };
1767
- } catch (error) {
1768
- return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };
1769
- }
1770
- };
1771
7
 
1772
8
  // src/engine/optimize.ts
1773
- var HANDLER_KEY2 = "__op";
1774
- var SEGMENTS_KEY2 = "__segments";
1775
- var eraseOp = (op) => (node13, context, evaluate2) => {
1776
- return op.call(void 0, node13, context, evaluate2);
9
+ var HANDLER_KEY = "__op";
10
+ var SEGMENTS_KEY = "__segments";
11
+ var eraseOp = (op) => (node, context, evaluate2) => {
12
+ return op.call(void 0, node, context, evaluate2);
1777
13
  };
1778
14
  var attachNonEnumerable = (target, key, value) => {
1779
15
  Object.defineProperty(target, key, {
@@ -1783,126 +19,126 @@ var attachNonEnumerable = (target, key, value) => {
1783
19
  configurable: true
1784
20
  });
1785
21
  };
1786
- var isPlainObject2 = (value) => isJsonObject(value);
1787
- var resolveHandler = (node13) => {
1788
- if (isRefNode(node13)) return eraseOp(opRef);
1789
- if (isConstNode(node13)) return eraseOp(opConst);
1790
- if (isVarNode(node13)) return eraseOp(opVar);
1791
- if (isGetNode(node13)) return eraseOp(opGet);
1792
- if (isWithNode(node13)) return eraseOp(opWith);
1793
- if (isMapNode(node13)) return eraseOp(opMap);
1794
- if (isFilterNode(node13)) return eraseOp(opFilter);
1795
- if (isReduceNode(node13)) return eraseOp(opReduce);
1796
- if (isSliceNode(node13)) return eraseOp(opSlice);
1797
- if (isFlattenNode(node13)) return eraseOp(opFlatten);
1798
- if (isUniqueNode(node13)) return eraseOp(opUnique);
1799
- if (isSortByNode(node13)) return eraseOp(opSortBy);
1800
- if (isAddNode(node13)) return eraseOp(opAdd);
1801
- if (isSubNode(node13)) return eraseOp(opSub);
1802
- if (isMulNode(node13)) return eraseOp(opMul);
1803
- if (isDivNode(node13)) return eraseOp(opDiv);
1804
- if (isRoundNode(node13)) return eraseOp(opRound);
1805
- if (isJoinNode(node13)) return eraseOp(opJoin);
1806
- if (isToStringNode(node13)) return eraseOp(opToString);
1807
- if (isInterpolateNode(node13)) return eraseOp(opInterpolate);
1808
- if (isFillNode(node13)) return eraseOp(opFill);
1809
- if (isTrimNode(node13)) return eraseOp(opTrim);
1810
- if (isLowerNode(node13)) return eraseOp(opLower);
1811
- if (isUpperNode(node13)) return eraseOp(opUpper);
1812
- if (isSplitNode(node13)) return eraseOp(opSplit);
1813
- if (isReplaceNode(node13)) return eraseOp(opReplace);
1814
- if (isEqNode(node13)) return eraseOp(opEq);
1815
- if (isNeqNode(node13)) return eraseOp(opNeq);
1816
- if (isGtNode(node13)) return eraseOp(opGt);
1817
- if (isGteNode(node13)) return eraseOp(opGte);
1818
- if (isLtNode(node13)) return eraseOp(opLt);
1819
- if (isLteNode(node13)) return eraseOp(opLte);
1820
- if (isEmptyNode(node13)) return eraseOp(opEmpty);
1821
- if (isStartsWithNode(node13)) return eraseOp(opStartsWith);
1822
- if (isEndsWithNode(node13)) return eraseOp(opEndsWith);
1823
- if (isContainsNode(node13)) return eraseOp(opContains);
1824
- if (isNotNode(node13)) return eraseOp(opNot);
1825
- if (isAndNode(node13)) return eraseOp(opAnd);
1826
- if (isOrNode(node13)) return eraseOp(opOr);
1827
- if (isMergeNode(node13)) return eraseOp(opMerge);
1828
- if (isCoalesceNode(node13)) return eraseOp(opCoalesce);
1829
- if (isCaseNode(node13)) return eraseOp(opCase);
1830
- if (isEntriesOfNode(node13)) return eraseOp(opEntriesOf);
1831
- if (isKeyByNode(node13)) return eraseOp(opKeyBy);
1832
- if (isGroupByNode(node13)) return eraseOp(opGroupBy);
1833
- if (isKeysNode(node13)) return eraseOp(opKeys);
1834
- if (isValuesNode(node13)) return eraseOp(opValues);
1835
- if (isFromEntriesNode(node13)) return eraseOp(opFromEntries);
1836
- if (isPickNode(node13)) return eraseOp(opPick);
1837
- if (isOmitNode(node13)) return eraseOp(opOmit);
1838
- if (isTypeNode(node13)) return eraseOp(opType);
1839
- if (isLengthNode(node13)) return eraseOp(opLength);
1840
- if (isHasNode(node13)) return eraseOp(opHas);
1841
- if (isRenameKeysNode(node13)) return eraseOp(opRenameKeys);
1842
- if (isUpdateNode(node13)) return eraseOp(opUpdate);
1843
- if (isAssertNode(node13)) return eraseOp(opAssert);
1844
- if (isWalkNode(node13)) return eraseOp(opWalk);
1845
- if (isDateNode(node13)) return eraseOp(opDate);
1846
- if (isDateAddNode(node13)) return eraseOp(opDateAdd);
1847
- if (isDateDiffNode(node13)) return eraseOp(opDateDiff);
1848
- if (isLocaleDateNode(node13)) return eraseOp(opLocaleDate);
1849
- if (isLocaleMoneyNode(node13)) return eraseOp(opLocaleMoney);
1850
- if (isLocaleNumberNode(node13)) return eraseOp(opLocaleNumber);
22
+ var isPlainObject = (value) => chunk26VYDHHC_cjs.isJsonObject(value);
23
+ var resolveHandler = (node) => {
24
+ if (chunk26VYDHHC_cjs.isRefNode(node)) return eraseOp(chunkV426VIRI_cjs.opRef);
25
+ if (chunk26VYDHHC_cjs.isConstNode(node)) return eraseOp(chunkV426VIRI_cjs.opConst);
26
+ if (chunk26VYDHHC_cjs.isVarNode(node)) return eraseOp(chunkV426VIRI_cjs.opVar);
27
+ if (chunk26VYDHHC_cjs.isGetNode(node)) return eraseOp(chunkV426VIRI_cjs.opGet);
28
+ if (chunk26VYDHHC_cjs.isWithNode(node)) return eraseOp(chunkV426VIRI_cjs.opWith);
29
+ if (chunk26VYDHHC_cjs.isMapNode(node)) return eraseOp(chunkV426VIRI_cjs.opMap);
30
+ if (chunk26VYDHHC_cjs.isFilterNode(node)) return eraseOp(chunkV426VIRI_cjs.opFilter);
31
+ if (chunk26VYDHHC_cjs.isReduceNode(node)) return eraseOp(chunkV426VIRI_cjs.opReduce);
32
+ if (chunk26VYDHHC_cjs.isSliceNode(node)) return eraseOp(chunkV426VIRI_cjs.opSlice);
33
+ if (chunk26VYDHHC_cjs.isFlattenNode(node)) return eraseOp(chunkV426VIRI_cjs.opFlatten);
34
+ if (chunk26VYDHHC_cjs.isUniqueNode(node)) return eraseOp(chunkV426VIRI_cjs.opUnique);
35
+ if (chunk26VYDHHC_cjs.isSortByNode(node)) return eraseOp(chunkV426VIRI_cjs.opSortBy);
36
+ if (chunk26VYDHHC_cjs.isAddNode(node)) return eraseOp(chunkV426VIRI_cjs.opAdd);
37
+ if (chunk26VYDHHC_cjs.isSubNode(node)) return eraseOp(chunkV426VIRI_cjs.opSub);
38
+ if (chunk26VYDHHC_cjs.isMulNode(node)) return eraseOp(chunkV426VIRI_cjs.opMul);
39
+ if (chunk26VYDHHC_cjs.isDivNode(node)) return eraseOp(chunkV426VIRI_cjs.opDiv);
40
+ if (chunk26VYDHHC_cjs.isRoundNode(node)) return eraseOp(chunkV426VIRI_cjs.opRound);
41
+ if (chunk26VYDHHC_cjs.isJoinNode(node)) return eraseOp(chunkV426VIRI_cjs.opJoin);
42
+ if (chunk26VYDHHC_cjs.isToStringNode(node)) return eraseOp(chunkV426VIRI_cjs.opToString);
43
+ if (chunk26VYDHHC_cjs.isInterpolateNode(node)) return eraseOp(chunkV426VIRI_cjs.opInterpolate);
44
+ if (chunk26VYDHHC_cjs.isFillNode(node)) return eraseOp(chunkV426VIRI_cjs.opFill);
45
+ if (chunk26VYDHHC_cjs.isTrimNode(node)) return eraseOp(chunkV426VIRI_cjs.opTrim);
46
+ if (chunk26VYDHHC_cjs.isLowerNode(node)) return eraseOp(chunkV426VIRI_cjs.opLower);
47
+ if (chunk26VYDHHC_cjs.isUpperNode(node)) return eraseOp(chunkV426VIRI_cjs.opUpper);
48
+ if (chunk26VYDHHC_cjs.isSplitNode(node)) return eraseOp(chunkV426VIRI_cjs.opSplit);
49
+ if (chunk26VYDHHC_cjs.isReplaceNode(node)) return eraseOp(chunkV426VIRI_cjs.opReplace);
50
+ if (chunk26VYDHHC_cjs.isEqNode(node)) return eraseOp(chunkV426VIRI_cjs.opEq);
51
+ if (chunk26VYDHHC_cjs.isNeqNode(node)) return eraseOp(chunkV426VIRI_cjs.opNeq);
52
+ if (chunk26VYDHHC_cjs.isGtNode(node)) return eraseOp(chunkV426VIRI_cjs.opGt);
53
+ if (chunk26VYDHHC_cjs.isGteNode(node)) return eraseOp(chunkV426VIRI_cjs.opGte);
54
+ if (chunk26VYDHHC_cjs.isLtNode(node)) return eraseOp(chunkV426VIRI_cjs.opLt);
55
+ if (chunk26VYDHHC_cjs.isLteNode(node)) return eraseOp(chunkV426VIRI_cjs.opLte);
56
+ if (chunk26VYDHHC_cjs.isEmptyNode(node)) return eraseOp(chunkV426VIRI_cjs.opEmpty);
57
+ if (chunk26VYDHHC_cjs.isStartsWithNode(node)) return eraseOp(chunkV426VIRI_cjs.opStartsWith);
58
+ if (chunk26VYDHHC_cjs.isEndsWithNode(node)) return eraseOp(chunkV426VIRI_cjs.opEndsWith);
59
+ if (chunk26VYDHHC_cjs.isContainsNode(node)) return eraseOp(chunkV426VIRI_cjs.opContains);
60
+ if (chunk26VYDHHC_cjs.isNotNode(node)) return eraseOp(chunkV426VIRI_cjs.opNot);
61
+ if (chunk26VYDHHC_cjs.isAndNode(node)) return eraseOp(chunkV426VIRI_cjs.opAnd);
62
+ if (chunk26VYDHHC_cjs.isOrNode(node)) return eraseOp(chunkV426VIRI_cjs.opOr);
63
+ if (chunk26VYDHHC_cjs.isMergeNode(node)) return eraseOp(chunkV426VIRI_cjs.opMerge);
64
+ if (chunk26VYDHHC_cjs.isCoalesceNode(node)) return eraseOp(chunkV426VIRI_cjs.opCoalesce);
65
+ if (chunk26VYDHHC_cjs.isCaseNode(node)) return eraseOp(chunkV426VIRI_cjs.opCase);
66
+ if (chunk26VYDHHC_cjs.isEntriesOfNode(node)) return eraseOp(chunkV426VIRI_cjs.opEntriesOf);
67
+ if (chunk26VYDHHC_cjs.isKeyByNode(node)) return eraseOp(chunkV426VIRI_cjs.opKeyBy);
68
+ if (chunk26VYDHHC_cjs.isGroupByNode(node)) return eraseOp(chunkV426VIRI_cjs.opGroupBy);
69
+ if (chunk26VYDHHC_cjs.isKeysNode(node)) return eraseOp(chunkV426VIRI_cjs.opKeys);
70
+ if (chunk26VYDHHC_cjs.isValuesNode(node)) return eraseOp(chunkV426VIRI_cjs.opValues);
71
+ if (chunk26VYDHHC_cjs.isFromEntriesNode(node)) return eraseOp(chunkV426VIRI_cjs.opFromEntries);
72
+ if (chunk26VYDHHC_cjs.isPickNode(node)) return eraseOp(chunkV426VIRI_cjs.opPick);
73
+ if (chunk26VYDHHC_cjs.isOmitNode(node)) return eraseOp(chunkV426VIRI_cjs.opOmit);
74
+ if (chunk26VYDHHC_cjs.isTypeNode(node)) return eraseOp(chunkV426VIRI_cjs.opType);
75
+ if (chunk26VYDHHC_cjs.isLengthNode(node)) return eraseOp(chunkV426VIRI_cjs.opLength);
76
+ if (chunk26VYDHHC_cjs.isHasNode(node)) return eraseOp(chunkV426VIRI_cjs.opHas);
77
+ if (chunk26VYDHHC_cjs.isRenameKeysNode(node)) return eraseOp(chunkV426VIRI_cjs.opRenameKeys);
78
+ if (chunk26VYDHHC_cjs.isUpdateNode(node)) return eraseOp(chunkV426VIRI_cjs.opUpdate);
79
+ if (chunk26VYDHHC_cjs.isAssertNode(node)) return eraseOp(chunkV426VIRI_cjs.opAssert);
80
+ if (chunk26VYDHHC_cjs.isWalkNode(node)) return eraseOp(chunkV426VIRI_cjs.opWalk);
81
+ if (chunk26VYDHHC_cjs.isDateNode(node)) return eraseOp(chunkV426VIRI_cjs.opDate);
82
+ if (chunk26VYDHHC_cjs.isDateAddNode(node)) return eraseOp(chunkV426VIRI_cjs.opDateAdd);
83
+ if (chunk26VYDHHC_cjs.isDateDiffNode(node)) return eraseOp(chunkV426VIRI_cjs.opDateDiff);
84
+ if (chunk26VYDHHC_cjs.isLocaleDateNode(node)) return eraseOp(chunkV426VIRI_cjs.opLocaleDate);
85
+ if (chunk26VYDHHC_cjs.isLocaleMoneyNode(node)) return eraseOp(chunkV426VIRI_cjs.opLocaleMoney);
86
+ if (chunk26VYDHHC_cjs.isLocaleNumberNode(node)) return eraseOp(chunkV426VIRI_cjs.opLocaleNumber);
1851
87
  return void 0;
1852
88
  };
1853
- var isFoldableLiteral = (node13) => {
1854
- if (node13 === null || node13 === void 0) return true;
1855
- const t = typeof node13;
89
+ var isFoldableLiteral = (node) => {
90
+ if (node === null || node === void 0) return true;
91
+ const t = typeof node;
1856
92
  if (t === "string" || t === "number" || t === "boolean") return true;
1857
- if (Array.isArray(node13)) return node13.every(isFoldableLiteral);
1858
- if (!isPlainObject2(node13)) return false;
1859
- if (isConstNode(node13)) return isFoldableLiteral(node13.$const);
1860
- if (Object.keys(node13).some((k) => k.startsWith("$"))) return false;
1861
- return Object.values(node13).every(isFoldableLiteral);
1862
- };
1863
- var optimizeNode = (node13, stats, evaluate2) => {
1864
- if (node13 === null || node13 === void 0) return node13;
1865
- if (typeof node13 !== "object") return node13;
1866
- if (Array.isArray(node13)) {
93
+ if (Array.isArray(node)) return node.every(isFoldableLiteral);
94
+ if (!isPlainObject(node)) return false;
95
+ if (chunk26VYDHHC_cjs.isConstNode(node)) return isFoldableLiteral(node.$const);
96
+ if (Object.keys(node).some((k) => k.startsWith("$"))) return false;
97
+ return Object.values(node).every(isFoldableLiteral);
98
+ };
99
+ var optimizeNode = (node, stats, evaluate2) => {
100
+ if (node === null || node === void 0) return node;
101
+ if (typeof node !== "object") return node;
102
+ if (Array.isArray(node)) {
1867
103
  const out = [];
1868
- for (const child of node13) out.push(optimizeNode(child, stats, evaluate2));
104
+ for (const child of node) out.push(optimizeNode(child, stats, evaluate2));
1869
105
  return out;
1870
106
  }
1871
- if (!isPlainObject2(node13)) return node13;
1872
- if (isConstNode(node13)) {
1873
- const literal = { ...node13 };
1874
- attachNonEnumerable(literal, HANDLER_KEY2, eraseOp(opConst));
107
+ if (!isPlainObject(node)) return node;
108
+ if (chunk26VYDHHC_cjs.isConstNode(node)) {
109
+ const literal = { ...node };
110
+ attachNonEnumerable(literal, HANDLER_KEY, eraseOp(chunkV426VIRI_cjs.opConst));
1875
111
  stats.handlersAttached += 1;
1876
112
  return literal;
1877
113
  }
1878
- const keys = Object.keys(node13);
114
+ const keys = Object.keys(node);
1879
115
  const optimized = {};
1880
116
  for (const key of keys) {
1881
- optimized[key] = optimizeNode(node13[key], stats, evaluate2);
117
+ optimized[key] = optimizeNode(node[key], stats, evaluate2);
1882
118
  }
1883
- if (isRefNode(optimized)) {
1884
- const segments = parseJsonPath(optimized.$ref);
119
+ if (chunk26VYDHHC_cjs.isRefNode(optimized)) {
120
+ const segments = chunkV426VIRI_cjs.parseJsonPath(optimized.$ref);
1885
121
  if (segments.length > 0) {
1886
- attachNonEnumerable(optimized, SEGMENTS_KEY2, segments);
122
+ attachNonEnumerable(optimized, SEGMENTS_KEY, segments);
1887
123
  stats.refsInlined += 1;
1888
124
  }
1889
125
  }
1890
126
  const handler = resolveHandler(optimized);
1891
127
  if (handler !== void 0) {
1892
- attachNonEnumerable(optimized, HANDLER_KEY2, handler);
128
+ attachNonEnumerable(optimized, HANDLER_KEY, handler);
1893
129
  stats.handlersAttached += 1;
1894
130
  }
1895
- if (handler !== void 0 && !isConstNode(optimized) && !isRefNode(optimized) && !isVarNode(optimized)) {
131
+ if (handler !== void 0 && !chunk26VYDHHC_cjs.isConstNode(optimized) && !chunk26VYDHHC_cjs.isRefNode(optimized) && !chunk26VYDHHC_cjs.isVarNode(optimized)) {
1896
132
  const allFoldable = Object.entries(optimized).every(([key, value]) => {
1897
- if (key === HANDLER_KEY2 || key === SEGMENTS_KEY2) return true;
133
+ if (key === HANDLER_KEY || key === SEGMENTS_KEY) return true;
1898
134
  return isFoldableLiteral(value);
1899
135
  });
1900
136
  if (allFoldable) {
1901
- const emptyCtx = { source: {}, vars: {}, budget: createBudget() };
137
+ const emptyCtx = { source: {}, vars: {}, budget: chunkV426VIRI_cjs.createBudget() };
1902
138
  try {
1903
139
  const folded = handler(optimized, emptyCtx, evaluate2);
1904
140
  const replacement = { $const: folded };
1905
- attachNonEnumerable(replacement, HANDLER_KEY2, eraseOp(opConst));
141
+ attachNonEnumerable(replacement, HANDLER_KEY, eraseOp(chunkV426VIRI_cjs.opConst));
1906
142
  stats.constantsFolded += 1;
1907
143
  return replacement;
1908
144
  } catch {
@@ -1911,54 +147,54 @@ var optimizeNode = (node13, stats, evaluate2) => {
1911
147
  }
1912
148
  return optimized;
1913
149
  };
1914
- var optimize = (node13, evaluate2) => {
150
+ var optimize = (node, evaluate2) => {
1915
151
  const stats = { refsInlined: 0, handlersAttached: 0, constantsFolded: 0 };
1916
- const result = optimizeNode(node13, stats, evaluate2);
152
+ const result = optimizeNode(node, stats, evaluate2);
1917
153
  return { node: result, stats };
1918
154
  };
1919
- var annotateNode = (node13) => {
1920
- if (Array.isArray(node13)) {
1921
- for (const child of node13) annotateNode(child);
155
+ var annotateNode = (node) => {
156
+ if (Array.isArray(node)) {
157
+ for (const child of node) annotateNode(child);
1922
158
  return;
1923
159
  }
1924
- if (!isPlainObject2(node13)) return;
1925
- if (!isConstNode(node13)) {
1926
- for (const value of Object.values(node13)) annotateNode(value);
160
+ if (!isPlainObject(node)) return;
161
+ if (!chunk26VYDHHC_cjs.isConstNode(node)) {
162
+ for (const value of Object.values(node)) annotateNode(value);
1927
163
  }
1928
- if (isRefNode(node13)) {
1929
- const segments = parseJsonPath(node13.$ref);
1930
- if (segments.length > 0) attachNonEnumerable(node13, SEGMENTS_KEY2, segments);
164
+ if (chunk26VYDHHC_cjs.isRefNode(node)) {
165
+ const segments = chunkV426VIRI_cjs.parseJsonPath(node.$ref);
166
+ if (segments.length > 0) attachNonEnumerable(node, SEGMENTS_KEY, segments);
1931
167
  }
1932
- const handler = resolveHandler(node13);
1933
- if (handler !== void 0) attachNonEnumerable(node13, HANDLER_KEY2, handler);
168
+ const handler = resolveHandler(node);
169
+ if (handler !== void 0) attachNonEnumerable(node, HANDLER_KEY, handler);
1934
170
  };
1935
171
  var rehydrate = (core) => annotateNode(core);
1936
172
 
1937
173
  // src/engine/compile.ts
1938
- var walk = (node13, stats, depth) => {
174
+ var walk = (node, stats, depth) => {
1939
175
  stats.nodeCount++;
1940
176
  if (depth > stats.maxDepth) stats.maxDepth = depth;
1941
- if (node13 === null || node13 === void 0) return;
1942
- if (typeof node13 === "string") {
1943
- stats.strings.add(node13);
177
+ if (node === null || node === void 0) return;
178
+ if (typeof node === "string") {
179
+ stats.strings.add(node);
1944
180
  return;
1945
181
  }
1946
- if (typeof node13 === "number" || typeof node13 === "boolean") return;
1947
- if (Array.isArray(node13)) {
1948
- for (const child of node13) walk(child, stats, depth + 1);
182
+ if (typeof node === "number" || typeof node === "boolean") return;
183
+ if (Array.isArray(node)) {
184
+ for (const child of node) walk(child, stats, depth + 1);
1949
185
  return;
1950
186
  }
1951
- if (!isJsonObject(node13)) return;
1952
- for (const key of Object.keys(node13)) {
187
+ if (!chunk26VYDHHC_cjs.isJsonObject(node)) return;
188
+ for (const key of Object.keys(node)) {
1953
189
  if (key.startsWith("$")) {
1954
190
  stats.opCount[key] = (stats.opCount[key] ?? 0) + 1;
1955
191
  }
1956
192
  }
1957
- if ("$ref" in node13 && typeof node13["$ref"] === "string") {
1958
- stats.paths.add(node13["$ref"]);
1959
- stats.strings.add(node13["$ref"]);
193
+ if ("$ref" in node && typeof node["$ref"] === "string") {
194
+ stats.paths.add(node["$ref"]);
195
+ stats.strings.add(node["$ref"]);
1960
196
  }
1961
- for (const value of Object.values(node13)) {
197
+ for (const value of Object.values(node)) {
1962
198
  walk(value, stats, depth + 1);
1963
199
  }
1964
200
  };
@@ -1968,14 +204,14 @@ var hashSha256 = async (data) => {
1968
204
  return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
1969
205
  };
1970
206
  var compile = async (config, options) => {
1971
- if (strata.exceedsDepth(config)) throw new PrismError(`Invalid config: ${strata.depthRefusal()}`, ErrorCode.SCHEMA);
1972
- const parsed = ConfigSchema.safeParse(config);
207
+ if (strata.exceedsDepth(config)) throw new chunkV426VIRI_cjs.PrismError(`Invalid config: ${strata.depthRefusal()}`, chunkV426VIRI_cjs.ErrorCode.SCHEMA);
208
+ const parsed = chunk26VYDHHC_cjs.ConfigSchema.safeParse(config);
1973
209
  if (!parsed.success) {
1974
- const issues = explainIssues(parsed.error.issues).map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
1975
- throw new PrismError(`Invalid config: ${issues}`, ErrorCode.SCHEMA);
210
+ const issues = chunkV426VIRI_cjs.explainIssues(parsed.error.issues).map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
211
+ throw new chunkV426VIRI_cjs.PrismError(`Invalid config: ${issues}`, chunkV426VIRI_cjs.ErrorCode.SCHEMA);
1976
212
  }
1977
- const desugared = desugar(parsed.data);
1978
- const { node: core, stats: optimizations } = optimize(desugared, evaluateNode);
213
+ const desugared = chunkV426VIRI_cjs.desugar(parsed.data);
214
+ const { node: core, stats: optimizations } = optimize(desugared, chunkV426VIRI_cjs.evaluateNode);
1979
215
  const stats = {
1980
216
  nodeCount: 0,
1981
217
  maxDepth: 0,
@@ -2014,180 +250,86 @@ var compile = async (config, options) => {
2014
250
  var hydrated = /* @__PURE__ */ new WeakSet();
2015
251
  var execute = (ir, source, limits) => {
2016
252
  if (ir.tables.paths.length > 0) {
2017
- primeJsonPathCache(ir.tables.paths);
253
+ chunkV426VIRI_cjs.primeJsonPathCache(ir.tables.paths);
2018
254
  }
2019
255
  const { core } = ir;
2020
256
  if (typeof core === "object" && core !== null && !hydrated.has(core)) {
2021
257
  rehydrate(core);
2022
258
  hydrated.add(core);
2023
259
  }
2024
- const budget = createBudget(limits);
2025
- const result = evaluateNode(core, { source, vars: {}, budget });
2026
- measure(result, budget);
260
+ const budget = chunkV426VIRI_cjs.createBudget(limits);
261
+ const result = chunkV426VIRI_cjs.evaluateNode(core, { source, vars: {}, budget });
262
+ chunkV426VIRI_cjs.measure(result, budget);
2027
263
  return result;
2028
264
  };
2029
265
  var validate = (config) => {
2030
266
  if (strata.exceedsDepth(config)) return { ok: false, issues: [{ path: [], message: strata.depthRefusal() }] };
2031
- const parsed = ConfigSchema.safeParse(config);
267
+ const parsed = chunk26VYDHHC_cjs.ConfigSchema.safeParse(config);
2032
268
  if (!parsed.success) {
2033
269
  return {
2034
270
  ok: false,
2035
271
  // The branch the config meant, with its full path — not the root union's
2036
272
  // "Invalid input" (see utils/issues).
2037
- issues: explainIssues(parsed.error.issues)
273
+ issues: chunkV426VIRI_cjs.explainIssues(parsed.error.issues)
2038
274
  };
2039
275
  }
2040
276
  return { ok: true, data: parsed.data };
2041
277
  };
2042
- var getNodeJsonSchema = (target = "draft-2020-12") => zod.z.toJSONSchema(NodeSchema, { target });
2043
- var getConfigJsonSchema = (target = "draft-2020-12") => zod.z.toJSONSchema(ConfigSchema, { target });
2044
- var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2045
- var unwrapRef = (value) => {
2046
- const allOf = isObject(value) ? value["allOf"] : void 0;
2047
- const only = Array.isArray(allOf) && allOf.length === 1 ? allOf[0] : void 0;
2048
- return isObject(only) && "$ref" in only ? only : value;
2049
- };
2050
- var refTarget = (ref) => {
2051
- if (typeof ref !== "string") return void 0;
2052
- const match = /^#\/([^/]+)\/([^/]+)$/.exec(ref);
2053
- return match?.[1] !== void 0 && match[2] !== void 0 ? [match[1], match[2]] : void 0;
2054
- };
2055
- var resolve = (root, ref) => {
2056
- const target = refTarget(ref);
2057
- if (target === void 0) return void 0;
2058
- const container = root[target[0]];
2059
- const def = isObject(container) ? container[target[1]] : void 0;
2060
- return isObject(def) ? def : void 0;
2061
- };
2062
- var opOf = (root, written) => {
2063
- const alternative = unwrapRef(written);
2064
- const node13 = isObject(alternative) && "$ref" in alternative ? resolve(root, alternative["$ref"]) : alternative;
2065
- const properties = isObject(node13) ? node13["properties"] : void 0;
2066
- const key = isObject(properties) ? Object.keys(properties)[0] : void 0;
2067
- return key !== void 0 && key.startsWith("$") ? key : void 0;
2068
- };
2069
- var refsIn = (value, found) => {
2070
- if (Array.isArray(value)) {
2071
- for (const item of value) refsIn(item, found);
2072
- return;
2073
- }
2074
- if (!isObject(value)) return;
2075
- for (const [key, child] of Object.entries(value)) {
2076
- if (key === "$ref" && typeof child === "string") found.add(child);
2077
- else refsIn(child, found);
2078
- }
2079
- };
2080
- var getProfileJsonSchema = (ops, target = "draft-2020-12") => narrowConfigJsonSchema(getConfigJsonSchema(target), ops);
2081
- var narrowConfigJsonSchema = (full, ops) => {
2082
- if (!isObject(full)) throw new Error("prism: the config JSON Schema is not an object");
2083
- const root = structuredClone(full);
2084
- const top = unwrapRef(root);
2085
- const node13 = resolve(root, isObject(top) ? top["$ref"] : void 0);
2086
- const alternatives = node13?.["anyOf"];
2087
- if (node13 === void 0 || !Array.isArray(alternatives)) throw new Error("prism: the config JSON Schema has no node union to narrow");
2088
- const keep = new Set(ops);
2089
- node13["anyOf"] = alternatives.filter((alternative) => {
2090
- const op = opOf(root, alternative);
2091
- return op === void 0 || keep.has(op);
2092
- });
2093
- const reached = /* @__PURE__ */ new Set();
2094
- const pending = [];
2095
- const visit = (value) => {
2096
- const found = /* @__PURE__ */ new Set();
2097
- refsIn(value, found);
2098
- for (const ref of found) {
2099
- if (reached.has(ref)) continue;
2100
- reached.add(ref);
2101
- pending.push(ref);
2102
- }
2103
- };
2104
- visit({ ...root, $defs: void 0, definitions: void 0 });
2105
- for (let ref = pending.pop(); ref !== void 0; ref = pending.pop()) visit(resolve(root, ref));
2106
- for (const container of ["$defs", "definitions"]) {
2107
- const defs = root[container];
2108
- if (!isObject(defs)) continue;
2109
- for (const name of Object.keys(defs)) if (!reached.has(`#/${container}/${name}`)) delete defs[name];
2110
- }
2111
- return root;
2112
- };
2113
278
 
2114
- // src/schemas/profiles.ts
2115
- var MAPPING_OPS = [
2116
- // reading the source
2117
- "$ref",
2118
- "$const",
2119
- "$var",
2120
- "$get",
2121
- "$with",
2122
- // arrays
2123
- "$map",
2124
- "$filter",
2125
- "$reduce",
2126
- "$slice",
2127
- "$unique",
2128
- "$sortBy",
2129
- "$take",
2130
- "$pluck",
2131
- // numbers and aggregates
2132
- "$add",
2133
- "$sub",
2134
- "$mul",
2135
- "$div",
2136
- "$round",
2137
- "$sum",
2138
- "$avg",
2139
- "$count",
2140
- "$min",
2141
- "$max",
2142
- // strings
2143
- "$join",
2144
- "$toString",
2145
- "$interpolate",
2146
- "$trim",
2147
- "$lower",
2148
- "$upper",
2149
- "$split",
2150
- // conditions
2151
- "$eq",
2152
- "$neq",
2153
- "$gt",
2154
- "$gte",
2155
- "$lt",
2156
- "$lte",
2157
- "$empty",
2158
- "$contains",
2159
- "$not",
2160
- "$and",
2161
- "$or",
2162
- // structure
2163
- "$merge",
2164
- "$coalesce",
2165
- "$case",
2166
- "$groupBy",
2167
- "$pick",
2168
- "$omit",
2169
- "$length",
2170
- // dates and locale formatting
2171
- "$date",
2172
- "$dateDiff",
2173
- "$localeDate",
2174
- "$localeMoney",
2175
- "$localeNumber"
2176
- ];
2177
-
2178
- exports.ConfigSchema = ConfigSchema;
2179
- exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
2180
- exports.ErrorCode = ErrorCode;
2181
- exports.MAPPING_OPS = MAPPING_OPS;
2182
- exports.NodeSchema = NodeSchema;
2183
- exports.PrismError = PrismError;
279
+ Object.defineProperty(exports, "MAPPING_OPS", {
280
+ enumerable: true,
281
+ get: function () { return chunkW32JXP33_cjs.MAPPING_OPS; }
282
+ });
283
+ Object.defineProperty(exports, "getConfigJsonSchema", {
284
+ enumerable: true,
285
+ get: function () { return chunkW32JXP33_cjs.getConfigJsonSchema; }
286
+ });
287
+ Object.defineProperty(exports, "getNodeJsonSchema", {
288
+ enumerable: true,
289
+ get: function () { return chunkW32JXP33_cjs.getNodeJsonSchema; }
290
+ });
291
+ Object.defineProperty(exports, "getProfileJsonSchema", {
292
+ enumerable: true,
293
+ get: function () { return chunkW32JXP33_cjs.getProfileJsonSchema; }
294
+ });
295
+ Object.defineProperty(exports, "DEFAULT_LIMITS", {
296
+ enumerable: true,
297
+ get: function () { return chunkV426VIRI_cjs.DEFAULT_LIMITS; }
298
+ });
299
+ Object.defineProperty(exports, "ErrorCode", {
300
+ enumerable: true,
301
+ get: function () { return chunkV426VIRI_cjs.ErrorCode; }
302
+ });
303
+ Object.defineProperty(exports, "PrismError", {
304
+ enumerable: true,
305
+ get: function () { return chunkV426VIRI_cjs.PrismError; }
306
+ });
307
+ Object.defineProperty(exports, "evaluate", {
308
+ enumerable: true,
309
+ get: function () { return chunkV426VIRI_cjs.evaluate; }
310
+ });
311
+ Object.defineProperty(exports, "evaluateSafe", {
312
+ enumerable: true,
313
+ get: function () { return chunkV426VIRI_cjs.evaluateSafe; }
314
+ });
315
+ Object.defineProperty(exports, "prismTransform", {
316
+ enumerable: true,
317
+ get: function () { return chunkV426VIRI_cjs.prismTransform; }
318
+ });
319
+ Object.defineProperty(exports, "ConfigSchema", {
320
+ enumerable: true,
321
+ get: function () { return chunk26VYDHHC_cjs.ConfigSchema; }
322
+ });
323
+ Object.defineProperty(exports, "NodeSchema", {
324
+ enumerable: true,
325
+ get: function () { return chunk26VYDHHC_cjs.NodeSchema; }
326
+ });
327
+ Object.defineProperty(exports, "OP_KEYS", {
328
+ enumerable: true,
329
+ get: function () { return chunk26VYDHHC_cjs.OP_KEYS; }
330
+ });
2184
331
  exports.compile = compile;
2185
- exports.evaluate = evaluate;
2186
- exports.evaluateSafe = evaluateSafe;
2187
332
  exports.execute = execute;
2188
- exports.getConfigJsonSchema = getConfigJsonSchema;
2189
- exports.getNodeJsonSchema = getNodeJsonSchema;
2190
- exports.getProfileJsonSchema = getProfileJsonSchema;
2191
333
  exports.validate = validate;
2192
334
  //# sourceMappingURL=index.cjs.map
2193
335
  //# sourceMappingURL=index.cjs.map