@niscorp/prism 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunkDOCK3CEK_cjs = require('./chunk-DOCK3CEK.cjs');
4
- var chunkL23ZLSDQ_cjs = require('./chunk-L23ZLSDQ.cjs');
3
+ var chunkNBU7EBGN_cjs = require('./chunk-NBU7EBGN.cjs');
4
+ var chunkVXU22DMV_cjs = require('./chunk-VXU22DMV.cjs');
5
5
  var strata = require('@niscorp/strata');
6
6
  var dayjs = require('dayjs');
7
7
  var utc = require('dayjs/plugin/utc.js');
@@ -32,16 +32,16 @@ var explainOne = (issue, prefix) => {
32
32
  var valueAt = (value, path) => path.reduce((at, key) => typeof at === "object" && at !== null ? Reflect.get(at, key) : void 0, value);
33
33
  var opOf = (value, path) => {
34
34
  const last = path[path.length - 1];
35
- if (typeof last === "string" && last.startsWith("$") && chunkL23ZLSDQ_cjs.formOf(last) === void 0) return void 0;
35
+ if (typeof last === "string" && last.startsWith("$") && chunkVXU22DMV_cjs.formOf(last) === void 0) return void 0;
36
36
  const here = valueAt(value, path);
37
37
  if (typeof here === "object" && here !== null && !Array.isArray(here)) {
38
- const ops = Object.keys(here).filter((key) => chunkL23ZLSDQ_cjs.formOf(key) !== void 0);
38
+ const ops = Object.keys(here).filter((key) => chunkVXU22DMV_cjs.formOf(key) !== void 0);
39
39
  if (ops.length === 1) return ops[0];
40
40
  }
41
41
  for (const back of [1, 2]) {
42
42
  const i = path.length - back;
43
43
  const key = path[i];
44
- if (typeof key !== "string" || chunkL23ZLSDQ_cjs.formOf(key) === void 0) continue;
44
+ if (typeof key !== "string" || chunkVXU22DMV_cjs.formOf(key) === void 0) continue;
45
45
  const holder = valueAt(value, path.slice(0, i));
46
46
  if (typeof holder === "object" && holder !== null && Object.keys(holder).length === 1) return key;
47
47
  }
@@ -49,7 +49,7 @@ var opOf = (value, path) => {
49
49
  };
50
50
  var withForm = (explained, value) => {
51
51
  const op = opOf(value, explained.path);
52
- const form = op === void 0 ? void 0 : chunkL23ZLSDQ_cjs.formOf(op);
52
+ const form = op === void 0 ? void 0 : chunkVXU22DMV_cjs.formOf(op);
53
53
  return form === void 0 ? explained : { ...explained, message: `${explained.message.replace(/\.$/, "")}. Form: ${form}` };
54
54
  };
55
55
  var explainIssues = (issues, value) => issues.flatMap((i) => explainOne(i, [])).map((explained) => withForm(explained, value));
@@ -109,7 +109,7 @@ var rewriteMin = (node, recurse) => ({
109
109
  $case: {
110
110
  branches: [
111
111
  { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
112
- { when: { $lt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
112
+ { when: { $lt: [{ $coalesce: [{ $var: "__x" }, { $var: "__acc" }] }, { $var: "__acc" }] }, then: { $var: "__x" } }
113
113
  ],
114
114
  else: { $var: "__acc" }
115
115
  }
@@ -126,7 +126,7 @@ var rewriteMax = (node, recurse) => ({
126
126
  $case: {
127
127
  branches: [
128
128
  { when: { $eq: [{ $var: "__acc" }, null] }, then: { $var: "__x" } },
129
- { when: { $gt: [{ $var: "__x" }, { $var: "__acc" }] }, then: { $var: "__x" } }
129
+ { when: { $gt: [{ $coalesce: [{ $var: "__x" }, { $var: "__acc" }] }, { $var: "__acc" }] }, then: { $var: "__x" } }
130
130
  ],
131
131
  else: { $var: "__acc" }
132
132
  }
@@ -180,24 +180,24 @@ var desugar = (node) => {
180
180
  if (node === null || node === void 0) return node;
181
181
  if (typeof node !== "object") return node;
182
182
  if (Array.isArray(node)) return node.map(desugar);
183
- if (chunkL23ZLSDQ_cjs.isWithNode(node)) {
183
+ if (chunkVXU22DMV_cjs.isWithNode(node)) {
184
184
  const bindings = {};
185
185
  for (const [name, expr] of Object.entries(node.$with.let)) bindings[name] = desugar(expr);
186
186
  return { $with: { let: bindings, value: desugar(node.$with.value) } };
187
187
  }
188
- if (chunkL23ZLSDQ_cjs.isRenameKeysNode(node)) return { $renameKeys: { ...node.$renameKeys, from: desugar(node.$renameKeys.from) } };
189
- if (chunkL23ZLSDQ_cjs.isConstNode(node)) return node;
190
- if (chunkL23ZLSDQ_cjs.isSumNode(node)) return rewriteSum(node, desugar);
191
- if (chunkL23ZLSDQ_cjs.isAvgNode(node)) return rewriteAvg(node, desugar);
192
- if (chunkL23ZLSDQ_cjs.isCountNode(node)) return rewriteCount(node, desugar);
193
- if (chunkL23ZLSDQ_cjs.isMinNode(node)) return rewriteMin(node, desugar);
194
- if (chunkL23ZLSDQ_cjs.isMaxNode(node)) return rewriteMax(node, desugar);
195
- if (chunkL23ZLSDQ_cjs.isPluckNode(node)) return rewritePluck(node, desugar);
196
- if (chunkL23ZLSDQ_cjs.isTakeNode(node)) return rewriteTake(node, desugar);
197
- if (chunkL23ZLSDQ_cjs.isDropNode(node)) return rewriteDrop(node, desugar);
198
- if (chunkL23ZLSDQ_cjs.isMatchNode(node)) return rewriteMatch(node, desugar);
199
- if (chunkL23ZLSDQ_cjs.isFlatMapNode(node)) return rewriteFlatMap(node, desugar);
200
- if (chunkL23ZLSDQ_cjs.isJsonObject(node)) {
188
+ if (chunkVXU22DMV_cjs.isRenameKeysNode(node)) return { $renameKeys: { ...node.$renameKeys, from: desugar(node.$renameKeys.from) } };
189
+ if (chunkVXU22DMV_cjs.isConstNode(node)) return node;
190
+ if (chunkVXU22DMV_cjs.isSumNode(node)) return rewriteSum(node, desugar);
191
+ if (chunkVXU22DMV_cjs.isAvgNode(node)) return rewriteAvg(node, desugar);
192
+ if (chunkVXU22DMV_cjs.isCountNode(node)) return rewriteCount(node, desugar);
193
+ if (chunkVXU22DMV_cjs.isMinNode(node)) return rewriteMin(node, desugar);
194
+ if (chunkVXU22DMV_cjs.isMaxNode(node)) return rewriteMax(node, desugar);
195
+ if (chunkVXU22DMV_cjs.isPluckNode(node)) return rewritePluck(node, desugar);
196
+ if (chunkVXU22DMV_cjs.isTakeNode(node)) return rewriteTake(node, desugar);
197
+ if (chunkVXU22DMV_cjs.isDropNode(node)) return rewriteDrop(node, desugar);
198
+ if (chunkVXU22DMV_cjs.isMatchNode(node)) return rewriteMatch(node, desugar);
199
+ if (chunkVXU22DMV_cjs.isFlatMapNode(node)) return rewriteFlatMap(node, desugar);
200
+ if (chunkVXU22DMV_cjs.isJsonObject(node)) {
201
201
  const result = {};
202
202
  for (const [key, value] of Object.entries(node)) {
203
203
  result[key] = desugar(value);
@@ -212,11 +212,11 @@ var DEFAULT_LIMITS = { maxSteps: 1e6, maxStringLength: 1e6, maxValues: 1e6 };
212
212
  var createBudget = (limits) => ({ limits: { ...DEFAULT_LIMITS, ...limits }, steps: 0, sizes: /* @__PURE__ */ new WeakMap() });
213
213
  var refuse = (what, limit, node) => {
214
214
  const message = `Evaluation stopped: ${what} (limit ${limit}).`;
215
- if (typeof node === "object" && node !== null) return chunkL23ZLSDQ_cjs.failAt(message, chunkL23ZLSDQ_cjs.ErrorCode.BUDGET, { details: { limit } }, { node, form: false });
216
- throw new chunkL23ZLSDQ_cjs.PrismError(message, chunkL23ZLSDQ_cjs.ErrorCode.BUDGET, { details: { limit } });
215
+ if (typeof node === "object" && node !== null) return chunkVXU22DMV_cjs.failAt(message, chunkVXU22DMV_cjs.ErrorCode.BUDGET, { details: { limit } }, { node, form: false });
216
+ throw new chunkVXU22DMV_cjs.PrismError(message, chunkVXU22DMV_cjs.ErrorCode.BUDGET, { details: { limit } });
217
217
  };
218
- var spendStep = (budget, node) => {
219
- budget.steps += 1;
218
+ var spendSteps = (budget, node, steps = 1) => {
219
+ budget.steps += steps;
220
220
  if (budget.steps > budget.limits.maxSteps) refuse("it evaluated too many nodes", budget.limits.maxSteps, node);
221
221
  };
222
222
  var sizeOf = (value, budget) => {
@@ -231,6 +231,8 @@ var sizeOf = (value, budget) => {
231
231
  budget.sizes.set(value, size);
232
232
  return size;
233
233
  };
234
+ var STACK_OVERFLOW = /call stack/i;
235
+ var stackRefusal = (error) => error instanceof RangeError && STACK_OVERFLOW.test(error.message) ? new chunkVXU22DMV_cjs.PrismError("Evaluation stopped: a value nests deeper than the call stack reaches, or refers back to itself.", chunkVXU22DMV_cjs.ErrorCode.BUDGET) : error;
234
236
  var measureString = (value, budget, node) => {
235
237
  if (typeof value === "string" && value.length > budget.limits.maxStringLength) refuse(`a string of ${value.length} characters`, budget.limits.maxStringLength, node);
236
238
  };
@@ -247,15 +249,15 @@ var SEGMENTS_KEY = "__segments";
247
249
  var isSegmentsArray = (value) => Array.isArray(value);
248
250
  var opRef = (node, context, _evaluate) => {
249
251
  const attached = Reflect.get(node, SEGMENTS_KEY);
250
- const segments = isSegmentsArray(attached) ? attached : chunkL23ZLSDQ_cjs.parseJsonPathCached(node.$ref);
251
- const resolved = chunkL23ZLSDQ_cjs.getByPath(context.source, segments);
252
+ const segments = isSegmentsArray(attached) ? attached : chunkVXU22DMV_cjs.parseJsonPathCached(node.$ref);
253
+ const resolved = chunkVXU22DMV_cjs.getByPath(context.source, segments);
252
254
  if (resolved === void 0) {
253
255
  const steps = segments.map((s) => s.type === "key" ? s.key : s.index);
254
- return chunkL23ZLSDQ_cjs.failAt("Path not found.", chunkL23ZLSDQ_cjs.ErrorCode.MISSING_PATH, { op: "$ref", path: node.$ref }, {
256
+ return chunkVXU22DMV_cjs.failAt("Path not found.", chunkVXU22DMV_cjs.ErrorCode.MISSING_PATH, { op: "$ref", path: node.$ref }, {
255
257
  node,
256
258
  op: "$ref",
257
259
  form: false,
258
- detail: () => `$ref ${JSON.stringify(node.$ref)} ${chunkL23ZLSDQ_cjs.whereStopped(context.source, steps, (count) => chunkL23ZLSDQ_cjs.jsonPathUpTo(segments, count))}`
260
+ detail: () => `$ref ${JSON.stringify(node.$ref)} ${chunkVXU22DMV_cjs.whereStopped(context.source, steps, (count) => chunkVXU22DMV_cjs.jsonPathUpTo(segments, count))}`
259
261
  });
260
262
  }
261
263
  return resolved;
@@ -264,16 +266,21 @@ var copyOf = (value) => {
264
266
  if (value === null || typeof value !== "object") return value;
265
267
  if (Array.isArray(value)) return value.map(copyOf);
266
268
  const copy = {};
267
- for (const [key, inner] of Object.entries(value)) copy[key] = copyOf(inner);
269
+ for (const [key, inner] of Object.entries(value)) chunkVXU22DMV_cjs.writeOwnKey(copy, key, copyOf(inner));
268
270
  return copy;
269
271
  };
270
- var opConst = (node, context, _evaluate) => context.kept === true ? copyOf(node.$const) : node.$const;
272
+ var COST_KEY = "__cost";
273
+ var opConst = (node, context, _evaluate) => {
274
+ const cost = Reflect.get(node, COST_KEY);
275
+ if (typeof cost === "number" && context.budget !== void 0) spendSteps(context.budget, node, cost);
276
+ return context.kept === true ? copyOf(node.$const) : node.$const;
277
+ };
271
278
  var opVar = (node, context, _evaluate) => {
272
- const value = context.vars[node.$var];
279
+ const value = chunkVXU22DMV_cjs.readOwnKey(context.vars, node.$var);
273
280
  if (value === void 0) {
274
281
  const names = Object.keys(context.vars).filter((name) => !name.startsWith("__"));
275
282
  const scope = names.length === 0 ? "No variable is in scope here." : `In scope: ${names.join(", ")}.`;
276
- return chunkL23ZLSDQ_cjs.failAt(`Variable not found: ${node.$var}. ${scope}`, chunkL23ZLSDQ_cjs.ErrorCode.VAR_NOT_FOUND, { op: "$var", path: node.$var }, { node, op: "$var", form: false });
283
+ return chunkVXU22DMV_cjs.failAt(`Variable not found: ${node.$var}. ${scope}`, chunkVXU22DMV_cjs.ErrorCode.VAR_NOT_FOUND, { op: "$var", path: node.$var }, { node, op: "$var", form: false });
277
284
  }
278
285
  return value;
279
286
  };
@@ -283,8 +290,9 @@ var getStopped = (node, root, count, context, evaluate2) => {
283
290
  const evaluated = typeof segment === "object" && segment !== null ? evaluate2(segment, unbudgeted) : segment;
284
291
  return typeof evaluated === "number" ? evaluated : String(evaluated);
285
292
  });
286
- return `$get.path ${JSON.stringify(steps)} ${chunkL23ZLSDQ_cjs.whereStopped(root, steps, (upTo) => upTo === 0 ? "from" : JSON.stringify(steps.slice(0, upTo)), true)}`;
293
+ return `$get.path ${JSON.stringify(steps)} ${chunkVXU22DMV_cjs.whereStopped(root, steps, (upTo) => upTo === 0 ? "from" : JSON.stringify(steps.slice(0, upTo)), true)}`;
287
294
  };
295
+ var absentAt = (current2) => current2 === null || current2 === void 0 ? { details: { absent: true } } : {};
288
296
  var opGet = (node, context, evaluate2) => {
289
297
  const { from, path, fallback } = node.$get;
290
298
  const root = evaluate2(from, context);
@@ -293,27 +301,27 @@ var opGet = (node, context, evaluate2) => {
293
301
  const segment = path[i];
294
302
  const evaluated = typeof segment === "object" && segment !== null ? evaluate2(segment, context) : segment;
295
303
  if (typeof evaluated === "number") {
296
- if (!chunkL23ZLSDQ_cjs.isJsonArray(current2)) {
304
+ if (!chunkVXU22DMV_cjs.isJsonArray(current2)) {
297
305
  if (fallback !== void 0) return evaluate2(fallback, context);
298
- return chunkL23ZLSDQ_cjs.failAt(getStopped(node, root, i + 1, context, evaluate2), chunkL23ZLSDQ_cjs.ErrorCode.TYPE, { op: "$get" }, { node, op: "$get", field: "path", form: true });
306
+ return chunkVXU22DMV_cjs.failAt(getStopped(node, root, i + 1, context, evaluate2), chunkVXU22DMV_cjs.ErrorCode.TYPE, { op: "$get", ...absentAt(current2) }, { node, op: "$get", field: "path", form: true });
299
307
  }
300
308
  current2 = current2[evaluated];
301
309
  } else {
302
310
  const key = String(evaluated);
303
- if (chunkL23ZLSDQ_cjs.isJsonArray(current2) && chunkL23ZLSDQ_cjs.INDEX_TEXT.test(key)) {
311
+ if (chunkVXU22DMV_cjs.isJsonArray(current2) && chunkVXU22DMV_cjs.INDEX_TEXT.test(key)) {
304
312
  current2 = current2[Number(key)];
305
313
  continue;
306
314
  }
307
- if (!chunkL23ZLSDQ_cjs.isJsonObject(current2)) {
315
+ if (!chunkVXU22DMV_cjs.isJsonObject(current2)) {
308
316
  if (fallback !== void 0) return evaluate2(fallback, context);
309
- return chunkL23ZLSDQ_cjs.failAt(getStopped(node, root, i + 1, context, evaluate2), chunkL23ZLSDQ_cjs.ErrorCode.TYPE, { op: "$get" }, { node, op: "$get", field: "path", form: true });
317
+ return chunkVXU22DMV_cjs.failAt(getStopped(node, root, i + 1, context, evaluate2), chunkVXU22DMV_cjs.ErrorCode.TYPE, { op: "$get", ...absentAt(current2) }, { node, op: "$get", field: "path", form: true });
310
318
  }
311
- current2 = current2[key];
319
+ current2 = chunkVXU22DMV_cjs.readOwnKey(current2, key);
312
320
  }
313
321
  }
314
322
  if (current2 === void 0) {
315
323
  if (fallback !== void 0) return evaluate2(fallback, context);
316
- return chunkL23ZLSDQ_cjs.failAt("Path not found.", chunkL23ZLSDQ_cjs.ErrorCode.MISSING_PATH, { op: "$get" }, { node, op: "$get", field: "path", form: true, detail: () => getStopped(node, root, path.length, context, evaluate2) });
324
+ return chunkVXU22DMV_cjs.failAt("Path not found.", chunkVXU22DMV_cjs.ErrorCode.MISSING_PATH, { op: "$get" }, { node, op: "$get", field: "path", form: true, detail: () => getStopped(node, root, path.length, context, evaluate2) });
317
325
  }
318
326
  return current2;
319
327
  };
@@ -321,8 +329,9 @@ var opWith = (node, context, evaluate2) => {
321
329
  const { let: declarations, value } = node.$with;
322
330
  const extendedVars = { ...context.vars };
323
331
  for (const [name, expr] of Object.entries(declarations)) {
324
- extendedVars[name] = evaluate2(expr, context);
325
- measure(extendedVars[name] ?? null, context.budget, node);
332
+ const bound = evaluate2(expr, context);
333
+ chunkVXU22DMV_cjs.writeOwnKey(extendedVars, name, bound);
334
+ measure(bound, context.budget, node);
326
335
  }
327
336
  return evaluate2(value, { ...context, vars: extendedVars });
328
337
  };
@@ -346,19 +355,19 @@ var loopScope = (context) => {
346
355
  };
347
356
 
348
357
  // src/ops/refuse.ts
349
- var writtenNote = (written) => chunkL23ZLSDQ_cjs.isPlainObject(written) ? ` That object was written in the program as ${chunkL23ZLSDQ_cjs.clip(JSON.stringify(written), 60)}, and an object without a "$" key builds an object; put the node itself there.` : "";
358
+ var writtenNote = (written) => chunkVXU22DMV_cjs.isPlainObject(written) ? ` That object was written in the program as ${chunkVXU22DMV_cjs.clip(JSON.stringify(written), 60)}, and an object without a "$" key builds an object; put the node itself there.` : "";
350
359
  var TEXT_LIKE = "text, a number, true, false or null";
351
360
  var isTextLike = (value) => value === null || typeof value !== "object";
352
- var refuseType = ({ node, op, field, needs, got, written, contextOp }) => chunkL23ZLSDQ_cjs.failAt(
353
- `${field === void 0 ? op : `${op}.${field}`} needs ${needs}, but got ${chunkL23ZLSDQ_cjs.describeValue(got)}.${writtenNote(written)}`,
354
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
361
+ var refuseType = ({ node, op, field, needs, got, written, contextOp }) => chunkVXU22DMV_cjs.failAt(
362
+ `${field === void 0 ? op : `${op}.${field}`} needs ${needs}, but got ${chunkVXU22DMV_cjs.describeValue(got)}.${writtenNote(written)}`,
363
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
355
364
  { op: contextOp ?? op },
356
365
  { node, op, ...field === void 0 ? {} : { field }, form: true }
357
366
  );
358
367
 
359
368
  // src/ops/array.ops.ts
360
369
  var requireArray = (value, node, op, field, written) => {
361
- if (!chunkL23ZLSDQ_cjs.isJsonArray(value))
370
+ if (!chunkVXU22DMV_cjs.isJsonArray(value))
362
371
  return refuseType({ node, op, ...field === void 0 ? {} : { field }, needs: "a list", got: value, written, contextOp: field === void 0 ? op : `${op}.${field}` });
363
372
  return value;
364
373
  };
@@ -368,7 +377,7 @@ var opMap = (node, context, evaluate2) => {
368
377
  const result = [];
369
378
  const { scope, vars } = loopScope(context);
370
379
  for (const item of input) {
371
- vars[as] = item;
380
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
372
381
  result.push(evaluate2(body, scope));
373
382
  }
374
383
  return result;
@@ -379,7 +388,7 @@ var opFilter = (node, context, evaluate2) => {
379
388
  const result = [];
380
389
  const { scope, vars } = loopScope(context);
381
390
  for (const item of input) {
382
- vars[as] = item;
391
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
383
392
  const condition = evaluate2(when, scope);
384
393
  if (condition) result.push(item);
385
394
  }
@@ -391,25 +400,38 @@ var opReduce = (node, context, evaluate2) => {
391
400
  let accumulator = evaluate2(init, context);
392
401
  const { scope, vars } = loopScope(context);
393
402
  for (const item of input) {
394
- vars[as] = item;
395
- vars[accName] = accumulator;
403
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
404
+ chunkVXU22DMV_cjs.writeOwnKey(vars, accName, accumulator);
396
405
  accumulator = evaluate2(body, scope);
397
406
  measure(accumulator, context.budget, node);
398
407
  }
399
408
  return accumulator;
400
409
  };
410
+ var isLowHalf = (text, at) => {
411
+ const code = text.charCodeAt(at);
412
+ const before = text.charCodeAt(at - 1);
413
+ return code >= 56320 && code <= 57343 && before >= 55296 && before <= 56319;
414
+ };
415
+ var unitAt = (text, index) => index < 0 ? Math.max(text.length + index, 0) : Math.min(index, text.length);
416
+ var sliceText = (text, start, end) => {
417
+ let from = unitAt(text, start ?? 0);
418
+ let to = end === void 0 ? text.length : unitAt(text, end);
419
+ if (from > 0 && from < text.length && isLowHalf(text, from)) from += 1;
420
+ if (to > 0 && to < text.length && isLowHalf(text, to)) to -= 1;
421
+ return from < to ? text.slice(from, to) : "";
422
+ };
401
423
  var opSlice = (node, context, evaluate2) => {
402
424
  const { from, start, end } = node.$slice;
403
425
  const input = evaluate2(from, context);
404
- if (typeof input === "string") return input.slice(start, end);
405
- if (chunkL23ZLSDQ_cjs.isJsonArray(input)) return input.slice(start, end);
426
+ if (typeof input === "string") return sliceText(input, start, end);
427
+ if (chunkVXU22DMV_cjs.isJsonArray(input)) return input.slice(start, end);
406
428
  return refuseType({ node, op: "$slice", field: "from", needs: "a list or text", got: input, written: from, contextOp: "$slice" });
407
429
  };
408
430
  var opFlatten = (node, context, evaluate2) => {
409
431
  const input = requireArray(evaluate2(node.$flatten, context), node, "$flatten", void 0, node.$flatten);
410
432
  const result = [];
411
433
  for (const item of input) {
412
- if (chunkL23ZLSDQ_cjs.isJsonArray(item)) result.push(...item);
434
+ if (chunkVXU22DMV_cjs.isJsonArray(item)) result.push(...item);
413
435
  else result.push(item);
414
436
  }
415
437
  return result;
@@ -429,9 +451,9 @@ var opUnique = (node, context, evaluate2) => {
429
451
  };
430
452
  var sortKey = (key, node) => {
431
453
  if (key !== null && typeof key === "object") {
432
- return chunkL23ZLSDQ_cjs.failAt(
433
- `$sortBy.by answered ${chunkL23ZLSDQ_cjs.describeValue(key)}; a sort key is a string or a number. To sort by two keys, sort by the second and then by the first: the sort keeps the order of equal items.`,
434
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
454
+ return chunkVXU22DMV_cjs.failAt(
455
+ `$sortBy.by answered ${chunkVXU22DMV_cjs.describeValue(key)}; a sort key is a string or a number. To sort by two keys, sort by the second and then by the first: the sort keeps the order of equal items.`,
456
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
435
457
  { op: "$sortBy" },
436
458
  { node, op: "$sortBy", field: "by", form: true }
437
459
  );
@@ -445,7 +467,7 @@ var opSortBy = (node, context, evaluate2) => {
445
467
  const input = requireArray(evaluate2(over, context), node, "$sortBy", "over", over);
446
468
  const { scope, vars } = loopScope(context);
447
469
  const keyed = input.map((item) => {
448
- vars[as] = item;
470
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
449
471
  return { item, key: sortKey(evaluate2(by, scope), node) };
450
472
  });
451
473
  keyed.sort((a, b) => {
@@ -464,32 +486,33 @@ var requireNumbers = (node, pair, context, evaluate2, op) => {
464
486
  const b = evaluate2(pair[1], context);
465
487
  if (typeof a !== "number" || typeof b !== "number") {
466
488
  const wrong = typeof a === "number" ? 1 : 0;
467
- return chunkL23ZLSDQ_cjs.failAt(
468
- `${op} needs two numbers, but got ${chunkL23ZLSDQ_cjs.describeValue(a)} and ${chunkL23ZLSDQ_cjs.describeValue(b)}.${writtenNote(pair[wrong])}`,
469
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
489
+ return chunkVXU22DMV_cjs.failAt(
490
+ `${op} needs two numbers, but got ${chunkVXU22DMV_cjs.describeValue(a)} and ${chunkVXU22DMV_cjs.describeValue(b)}.${writtenNote(pair[wrong])}`,
491
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
470
492
  { op },
471
493
  { node, op, field: String(wrong), form: true }
472
494
  );
473
495
  }
474
496
  return [a, b];
475
497
  };
476
- var refuseZero = (node, op) => chunkL23ZLSDQ_cjs.failAt(`Division by zero: the second value of ${op} is 0.`, chunkL23ZLSDQ_cjs.ErrorCode.DIVISION_BY_ZERO, { op }, { node, op, field: "1", form: false });
498
+ var refuseZero = (node, op) => chunkVXU22DMV_cjs.failAt(`Division by zero: the second value of ${op} is 0.`, chunkVXU22DMV_cjs.ErrorCode.DIVISION_BY_ZERO, { op }, { node, op, field: "1", form: false });
499
+ var finite = (result, node, op) => Number.isFinite(result) ? result : chunkVXU22DMV_cjs.failAt(`${op} gave ${result}, which is not a JSON number.`, chunkVXU22DMV_cjs.ErrorCode.TYPE, { op }, { node, op, form: false });
477
500
  var opAdd = (node, context, evaluate2) => {
478
501
  const [a, b] = requireNumbers(node, node.$add, context, evaluate2, "$add");
479
- return a + b;
502
+ return finite(a + b, node, "$add");
480
503
  };
481
504
  var opSub = (node, context, evaluate2) => {
482
505
  const [a, b] = requireNumbers(node, node.$sub, context, evaluate2, "$sub");
483
- return a - b;
506
+ return finite(a - b, node, "$sub");
484
507
  };
485
508
  var opMul = (node, context, evaluate2) => {
486
509
  const [a, b] = requireNumbers(node, node.$mul, context, evaluate2, "$mul");
487
- return a * b;
510
+ return finite(a * b, node, "$mul");
488
511
  };
489
512
  var opDiv = (node, context, evaluate2) => {
490
513
  const [a, b] = requireNumbers(node, node.$div, context, evaluate2, "$div");
491
514
  if (b === 0) return refuseZero(node, "$div");
492
- return a / b;
515
+ return finite(a / b, node, "$div");
493
516
  };
494
517
  var opMod = (node, context, evaluate2) => {
495
518
  const [a, b] = requireNumbers(node, node.$mod, context, evaluate2, "$mod");
@@ -499,12 +522,17 @@ var opMod = (node, context, evaluate2) => {
499
522
  return remainder < 0 !== b < 0 ? remainder + b : remainder;
500
523
  };
501
524
  var ROUNDING = { nearest: Math.round, floor: Math.floor, ceil: Math.ceil };
525
+ var shifted = (value, digits) => {
526
+ const [mantissa, exponent = "0"] = String(value).split("e");
527
+ return Number(`${mantissa}e${Number(exponent) + digits}`);
528
+ };
502
529
  var opRound = (node, context, evaluate2) => {
503
530
  const value = evaluate2(node.$round.value, context);
504
531
  if (typeof value !== "number") return refuseType({ node, op: "$round", field: "value", needs: "a number", got: value, written: node.$round.value });
505
532
  const digits = node.$round.digits ?? 0;
506
- const factor = Math.pow(10, digits);
507
- return ROUNDING[node.$round.mode ?? "nearest"](value * factor) / factor;
533
+ const moved = shifted(value, digits);
534
+ if (!Number.isFinite(moved)) return value;
535
+ return shifted(ROUNDING[node.$round.mode ?? "nearest"](moved), -digits);
508
536
  };
509
537
  var NUMERIC_TEXT = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
510
538
  var opToNumber = (node, context, evaluate2) => {
@@ -526,9 +554,9 @@ var opJoin = (node, context, evaluate2) => {
526
554
  if (!Array.isArray(list)) return refuseType({ node, op: "$join", field: "parts", needs: "a list", got: list, written: parts });
527
555
  const wrong = list.findIndex((part) => !isTextLike(part));
528
556
  if (wrong !== -1)
529
- return chunkL23ZLSDQ_cjs.failAt(
530
- `$join.parts needs items that are ${TEXT_LIKE}, but item ${wrong} is ${chunkL23ZLSDQ_cjs.describeValue(list[wrong])}.${Array.isArray(parts) ? writtenNote(parts[wrong]) : ""}`,
531
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
557
+ return chunkVXU22DMV_cjs.failAt(
558
+ `$join.parts needs items that are ${TEXT_LIKE}, but item ${wrong} is ${chunkVXU22DMV_cjs.describeValue(list[wrong])}.${Array.isArray(parts) ? writtenNote(parts[wrong]) : ""}`,
559
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
532
560
  { op: "$join" },
533
561
  { node, op: "$join", field: "parts", form: true }
534
562
  );
@@ -543,31 +571,33 @@ var opToString = (node, context, evaluate2) => {
543
571
  var opInterpolate = (node, context, evaluate2) => {
544
572
  const { template, values: valuesNode } = node.$interpolate;
545
573
  const values = evaluate2(valuesNode, context);
546
- if (!chunkL23ZLSDQ_cjs.isJsonObject(values)) return refuseType({ node, op: "$interpolate", field: "values", needs: "an object", got: values, written: valuesNode });
547
- return template.replace(/\{\{(\w+)\}\}/g, (_match, key) => {
548
- const value = values[key] ?? "";
574
+ if (!chunkVXU22DMV_cjs.isJsonObject(values)) return refuseType({ node, op: "$interpolate", field: "values", needs: "an object", got: values, written: valuesNode });
575
+ return template.replace(/\{\{([\p{L}\p{M}\p{N}_]+)\}\}/gu, (_match, key) => {
576
+ const value = chunkVXU22DMV_cjs.readOwnKey(values, key) ?? "";
549
577
  if (!isTextLike(value))
550
- return chunkL23ZLSDQ_cjs.failAt(
551
- `$interpolate.values needs ${TEXT_LIKE} for {{${key}}}, but "${key}" is ${chunkL23ZLSDQ_cjs.describeValue(value)}.`,
552
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
578
+ return chunkVXU22DMV_cjs.failAt(
579
+ `$interpolate.values needs ${TEXT_LIKE} for {{${key}}}, but "${key}" is ${chunkVXU22DMV_cjs.describeValue(value)}.`,
580
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
553
581
  { op: "$interpolate" },
554
582
  { node, op: "$interpolate", field: "values", form: true }
555
583
  );
556
584
  return String(value);
557
585
  });
558
586
  };
559
- var fillOne = (value) => {
587
+ var fillOne = (value, budget, node) => {
560
588
  if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
561
589
  const { phrase, slots } = value;
562
- if (typeof phrase !== "string" || !chunkL23ZLSDQ_cjs.isJsonObject(slots)) return value;
563
- return phrase.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (hole, name) => {
564
- const slot = slots[name];
590
+ if (typeof phrase !== "string" || !chunkVXU22DMV_cjs.isJsonObject(slots)) return value;
591
+ const filled = phrase.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (hole, name) => {
592
+ const slot = chunkVXU22DMV_cjs.readOwnKey(slots, name);
565
593
  if (slot === void 0 || slot === null) return hole;
566
- const filled = fillOne(slot);
567
- return typeof filled === "object" ? hole : String(filled);
594
+ const inner = fillOne(slot, budget, node);
595
+ return typeof inner === "object" ? hole : String(inner);
568
596
  });
597
+ if (budget !== void 0) measureString(filled, budget, node);
598
+ return filled;
569
599
  };
570
- var opFill = (node, context, evaluate2) => fillOne(evaluate2(node.$fill, context));
600
+ var opFill = (node, context, evaluate2) => fillOne(evaluate2(node.$fill, context), context.budget, node);
571
601
  var opTrim = (node, context, evaluate2) => {
572
602
  const value = evaluate2(node.$trim, context);
573
603
  if (typeof value !== "string") return refuseType({ node, op: "$trim", needs: "text", got: value, written: node.$trim });
@@ -586,13 +616,14 @@ var opUpper = (node, context, evaluate2) => {
586
616
  var opSplit = (node, context, evaluate2) => {
587
617
  const value = evaluate2(node.$split.value, context);
588
618
  if (typeof value !== "string") return refuseType({ node, op: "$split", field: "value", needs: "text", got: value, written: node.$split.value });
589
- return value.split(node.$split.sep);
619
+ return node.$split.sep === "" ? Array.from(value) : value.split(node.$split.sep);
590
620
  };
591
621
  var opReplace = (node, context, evaluate2) => {
592
622
  const value = evaluate2(node.$replace.value, context);
593
623
  if (typeof value !== "string") return refuseType({ node, op: "$replace", field: "value", needs: "text", got: value, written: node.$replace.value });
594
624
  const { search, replacement, all } = node.$replace;
595
- return all === true ? value.replaceAll(search, replacement) : value.replace(search, replacement);
625
+ const written = () => replacement;
626
+ return all === true ? value.replaceAll(search, written) : value.replace(search, written);
596
627
  };
597
628
 
598
629
  // src/ops/predicate.ops.ts
@@ -612,9 +643,9 @@ var compareOp = (node, pair, context, evaluate2, op, test) => {
612
643
  const cmp = compare(a, b);
613
644
  if (cmp === void 0) {
614
645
  const wrong = typeof a === "number" || typeof a === "string" ? 1 : 0;
615
- return chunkL23ZLSDQ_cjs.failAt(
616
- `${op} needs two numbers or two texts, but got ${chunkL23ZLSDQ_cjs.describeValue(a)} and ${chunkL23ZLSDQ_cjs.describeValue(b)}.${writtenNote(pair[wrong])}`,
617
- chunkL23ZLSDQ_cjs.ErrorCode.TYPE,
646
+ return chunkVXU22DMV_cjs.failAt(
647
+ `${op} needs two numbers or two texts, but got ${chunkVXU22DMV_cjs.describeValue(a)} and ${chunkVXU22DMV_cjs.describeValue(b)}.${writtenNote(pair[wrong])}`,
648
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
618
649
  { op },
619
650
  { node, op, field: String(wrong), form: true }
620
651
  );
@@ -629,8 +660,8 @@ var opEmpty = (node, context, evaluate2) => {
629
660
  const value = evaluate2(node.$empty, context);
630
661
  if (value === null || value === void 0) return true;
631
662
  if (typeof value === "string") return value.length === 0;
632
- if (chunkL23ZLSDQ_cjs.isJsonArray(value)) return value.length === 0;
633
- if (chunkL23ZLSDQ_cjs.isJsonObject(value)) return Object.keys(value).length === 0;
663
+ if (chunkVXU22DMV_cjs.isJsonArray(value)) return value.length === 0;
664
+ if (chunkVXU22DMV_cjs.isJsonObject(value)) return Object.keys(value).length === 0;
634
665
  return false;
635
666
  };
636
667
  var opStartsWith = (node, context, evaluate2) => {
@@ -680,8 +711,9 @@ var opMerge = (node, context, evaluate2) => {
680
711
  for (let index = 0; index < node.$merge.length; index++) {
681
712
  const part = node.$merge[index];
682
713
  const evaluated = evaluate2(part, context);
683
- if (!chunkL23ZLSDQ_cjs.isJsonObject(evaluated)) return refuseType({ node, op: "$merge", field: String(index), needs: "an object", got: evaluated, written: part, contextOp: "$merge" });
684
- Object.assign(result, evaluated);
714
+ if (!chunkVXU22DMV_cjs.isJsonObject(evaluated)) return refuseType({ node, op: "$merge", field: String(index), needs: "an object", got: evaluated, written: part, contextOp: "$merge" });
715
+ if (Object.hasOwn(evaluated, "__proto__")) for (const [key, value] of Object.entries(evaluated)) chunkVXU22DMV_cjs.writeOwnKey(result, key, value);
716
+ else Object.assign(result, evaluated);
685
717
  }
686
718
  return result;
687
719
  };
@@ -702,36 +734,37 @@ var opCase = (node, context, evaluate2) => {
702
734
  };
703
735
  var opEntriesOf = (node, context, evaluate2) => {
704
736
  const value = evaluate2(node.$entriesOf, context);
705
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$entriesOf", needs: "an object", got: value, written: node.$entriesOf });
737
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$entriesOf", needs: "an object", got: value, written: node.$entriesOf });
706
738
  return Object.entries(value).map(([k, v]) => [k, v]);
707
739
  };
708
740
  var opKeyBy = (node, context, evaluate2) => {
709
741
  const { over, as, key: keyExpr } = node.$keyBy;
710
742
  const input = evaluate2(over, context);
711
- if (!chunkL23ZLSDQ_cjs.isJsonArray(input)) return refuseType({ node, op: "$keyBy", field: "over", needs: "a list", got: input, written: over, contextOp: "$keyBy" });
743
+ if (!chunkVXU22DMV_cjs.isJsonArray(input)) return refuseType({ node, op: "$keyBy", field: "over", needs: "a list", got: input, written: over, contextOp: "$keyBy" });
712
744
  const result = {};
713
745
  const { scope, vars } = loopScope(context);
714
746
  for (const item of input) {
715
- vars[as] = item;
747
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
716
748
  const key = evaluate2(keyExpr, scope);
717
749
  if (!isTextLike(key)) return refuseType({ node, op: "$keyBy", field: "key", needs: TEXT_LIKE, got: key, written: keyExpr, contextOp: "$keyBy" });
718
- result[String(key)] = item;
750
+ chunkVXU22DMV_cjs.writeOwnKey(result, String(key), item);
719
751
  }
720
752
  return result;
721
753
  };
722
754
  var opGroupBy = (node, context, evaluate2) => {
723
755
  const { over, as, key: keyExpr } = node.$groupBy;
724
756
  const input = evaluate2(over, context);
725
- if (!chunkL23ZLSDQ_cjs.isJsonArray(input)) return refuseType({ node, op: "$groupBy", field: "over", needs: "a list", got: input, written: over, contextOp: "$groupBy" });
757
+ if (!chunkVXU22DMV_cjs.isJsonArray(input)) return refuseType({ node, op: "$groupBy", field: "over", needs: "a list", got: input, written: over, contextOp: "$groupBy" });
726
758
  const result = {};
727
759
  const { scope, vars } = loopScope(context);
728
760
  for (const item of input) {
729
- vars[as] = item;
761
+ chunkVXU22DMV_cjs.writeOwnKey(vars, as, item);
730
762
  const value = evaluate2(keyExpr, scope);
731
763
  if (!isTextLike(value)) return refuseType({ node, op: "$groupBy", field: "key", needs: TEXT_LIKE, got: value, written: keyExpr, contextOp: "$groupBy" });
732
764
  const key = String(value);
733
- if (!result[key]) result[key] = [];
734
- result[key].push(item);
765
+ const group = chunkVXU22DMV_cjs.readOwnKey(result, key);
766
+ if (group === void 0) chunkVXU22DMV_cjs.writeOwnKey(result, key, [item]);
767
+ else group.push(item);
735
768
  }
736
769
  return result;
737
770
  };
@@ -739,67 +772,70 @@ var opGroupBy = (node, context, evaluate2) => {
739
772
  // src/ops/object.ops.ts
740
773
  var opKeys = (node, context, evaluate2) => {
741
774
  const value = evaluate2(node.$keys, context);
742
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$keys", needs: "an object", got: value, written: node.$keys });
775
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$keys", needs: "an object", got: value, written: node.$keys });
743
776
  return Object.keys(value);
744
777
  };
745
778
  var opValues = (node, context, evaluate2) => {
746
779
  const value = evaluate2(node.$values, context);
747
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$values", needs: "an object", got: value, written: node.$values });
780
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$values", needs: "an object", got: value, written: node.$values });
748
781
  return Object.values(value);
749
782
  };
750
783
  var opFromEntries = (node, context, evaluate2) => {
751
784
  const value = evaluate2(node.$fromEntries, context);
752
- if (!chunkL23ZLSDQ_cjs.isJsonArray(value)) return refuseType({ node, op: "$fromEntries", needs: "a list of [key, value] pairs", got: value, written: node.$fromEntries });
785
+ if (!chunkVXU22DMV_cjs.isJsonArray(value)) return refuseType({ node, op: "$fromEntries", needs: "a list of [key, value] pairs", got: value, written: node.$fromEntries });
753
786
  const result = {};
754
787
  for (let index = 0; index < value.length; index++) {
755
788
  const entry = value[index];
756
- if (!chunkL23ZLSDQ_cjs.isJsonArray(entry) || entry.length < 2)
757
- return chunkL23ZLSDQ_cjs.failAt(`$fromEntries needs a list of [key, value] pairs, but item ${index} is ${chunkL23ZLSDQ_cjs.describeValue(entry)}.`, chunkL23ZLSDQ_cjs.ErrorCode.TYPE, { op: "$fromEntries" }, { node, op: "$fromEntries", form: true });
758
- result[String(entry[0])] = entry[1];
789
+ if (!chunkVXU22DMV_cjs.isJsonArray(entry) || entry.length < 2)
790
+ return chunkVXU22DMV_cjs.failAt(`$fromEntries needs a list of [key, value] pairs, but item ${index} is ${chunkVXU22DMV_cjs.describeValue(entry)}.`, chunkVXU22DMV_cjs.ErrorCode.TYPE, { op: "$fromEntries" }, { node, op: "$fromEntries", form: true });
791
+ chunkVXU22DMV_cjs.writeOwnKey(result, String(entry[0]), entry[1] ?? null);
759
792
  }
760
793
  return result;
761
794
  };
762
795
  var opPick = (node, context, evaluate2) => {
763
796
  const value = evaluate2(node.$pick.from, context);
764
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$pick", field: "from", needs: "an object", got: value, written: node.$pick.from, contextOp: "$pick" });
797
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$pick", field: "from", needs: "an object", got: value, written: node.$pick.from, contextOp: "$pick" });
765
798
  const result = {};
766
799
  for (const key of node.$pick.keys) {
767
- if (key in value) result[key] = value[key];
800
+ const picked = chunkVXU22DMV_cjs.readOwnKey(value, key);
801
+ if (picked !== void 0) chunkVXU22DMV_cjs.writeOwnKey(result, key, picked);
768
802
  }
769
803
  return result;
770
804
  };
771
805
  var opOmit = (node, context, evaluate2) => {
772
806
  const value = evaluate2(node.$omit.from, context);
773
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$omit", field: "from", needs: "an object", got: value, written: node.$omit.from, contextOp: "$omit" });
807
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$omit", field: "from", needs: "an object", got: value, written: node.$omit.from, contextOp: "$omit" });
774
808
  const keysToOmit = new Set(node.$omit.keys);
775
809
  const result = {};
776
810
  for (const [k, v] of Object.entries(value)) {
777
- if (!keysToOmit.has(k)) result[k] = v;
811
+ if (!keysToOmit.has(k)) chunkVXU22DMV_cjs.writeOwnKey(result, k, v);
778
812
  }
779
813
  return result;
780
814
  };
781
815
  var opType = (node, context, evaluate2) => {
782
816
  const value = evaluate2(node.$type, context);
783
817
  if (value === null) return "null";
784
- if (chunkL23ZLSDQ_cjs.isJsonArray(value)) return "array";
818
+ if (chunkVXU22DMV_cjs.isJsonArray(value)) return "array";
785
819
  return typeof value;
786
820
  };
787
821
  var opLength = (node, context, evaluate2) => {
788
822
  const value = evaluate2(node.$length, context);
789
823
  if (typeof value === "string") return value.length;
790
- if (chunkL23ZLSDQ_cjs.isJsonArray(value)) return value.length;
824
+ if (chunkVXU22DMV_cjs.isJsonArray(value)) return value.length;
791
825
  return refuseType({ node, op: "$length", needs: "a list or text", got: value, written: node.$length });
792
826
  };
793
827
 
794
828
  // src/ops/transform.ops.ts
829
+ var asIndex = (at, segment) => typeof segment === "string" && chunkVXU22DMV_cjs.isJsonArray(at) && chunkVXU22DMV_cjs.INDEX_TEXT.test(segment) ? Number(segment) : segment;
795
830
  var has = (value, path) => {
796
831
  let at = value;
797
- for (const segment of path) {
832
+ for (const written of path) {
833
+ const segment = asIndex(at, written);
798
834
  if (typeof segment === "number") {
799
- if (!chunkL23ZLSDQ_cjs.isJsonArray(at) || segment >= at.length) return false;
835
+ if (!chunkVXU22DMV_cjs.isJsonArray(at) || segment >= at.length) return false;
800
836
  at = at[segment] ?? null;
801
837
  } else {
802
- if (!chunkL23ZLSDQ_cjs.isJsonObject(at) || !Object.prototype.hasOwnProperty.call(at, segment)) return false;
838
+ if (!chunkVXU22DMV_cjs.isJsonObject(at) || !Object.prototype.hasOwnProperty.call(at, segment)) return false;
803
839
  at = at[segment] ?? null;
804
840
  }
805
841
  }
@@ -808,36 +844,45 @@ var has = (value, path) => {
808
844
  var opHas = (node, context, evaluate2) => has(evaluate2(node.$has.from, context), node.$has.path);
809
845
  var opRenameKeys = (node, context, evaluate2) => {
810
846
  const value = evaluate2(node.$renameKeys.from, context);
811
- if (!chunkL23ZLSDQ_cjs.isJsonObject(value)) return refuseType({ node, op: "$renameKeys", field: "from", needs: "an object", got: value, written: node.$renameKeys.from, contextOp: "$renameKeys" });
847
+ if (!chunkVXU22DMV_cjs.isJsonObject(value)) return refuseType({ node, op: "$renameKeys", field: "from", needs: "an object", got: value, written: node.$renameKeys.from, contextOp: "$renameKeys" });
812
848
  const { map } = node.$renameKeys;
813
849
  const renamedTo = new Set(Object.entries(map).filter(([from]) => Object.prototype.hasOwnProperty.call(value, from)).map(([, to]) => to));
814
850
  const result = {};
815
851
  for (const [key, v] of Object.entries(value)) {
816
- const target = map[key];
817
- if (target !== void 0) result[target] = v;
818
- else if (!renamedTo.has(key)) result[key] = v;
852
+ const target = chunkVXU22DMV_cjs.readOwnKey(map, key);
853
+ if (target !== void 0) chunkVXU22DMV_cjs.writeOwnKey(result, target, v);
854
+ else if (!renamedTo.has(key)) chunkVXU22DMV_cjs.writeOwnKey(result, key, v);
819
855
  }
820
856
  return result;
821
857
  };
822
858
  var current = (value, path) => {
823
859
  let at = value;
824
- for (const segment of path) {
825
- if (typeof segment === "number") at = chunkL23ZLSDQ_cjs.isJsonArray(at) ? at[segment] ?? null : null;
826
- else at = chunkL23ZLSDQ_cjs.isJsonObject(at) ? at[segment] ?? null : null;
860
+ for (const written of path) {
861
+ const segment = asIndex(at, written);
862
+ if (typeof segment === "number") at = chunkVXU22DMV_cjs.isJsonArray(at) ? at[segment] ?? null : null;
863
+ else at = chunkVXU22DMV_cjs.isJsonObject(at) ? chunkVXU22DMV_cjs.readOwnKey(at, segment) ?? null : null;
827
864
  }
828
865
  return at;
829
866
  };
830
867
  var setIn = (value, path, next, full, node) => {
831
- const [head, ...rest] = path;
832
- if (head === void 0) return next;
868
+ const [written, ...rest] = path;
869
+ if (written === void 0) return next;
870
+ const head = asIndex(value, written);
833
871
  if (typeof head === "number") {
834
- if (!chunkL23ZLSDQ_cjs.isJsonArray(value) || head >= value.length) {
835
- return chunkL23ZLSDQ_cjs.failAt(`No array item at ${full.join(".")}: the value there is ${chunkL23ZLSDQ_cjs.describeValue(value)}.`, chunkL23ZLSDQ_cjs.ErrorCode.MISSING_PATH, { op: "$update", path: full.join(".") }, { node, op: "$update", field: "path", form: false });
872
+ if (!chunkVXU22DMV_cjs.isJsonArray(value) || head >= value.length) {
873
+ return chunkVXU22DMV_cjs.failAt(`No array item at ${full.join(".")}: the value there is ${chunkVXU22DMV_cjs.describeValue(value)}.`, chunkVXU22DMV_cjs.ErrorCode.MISSING_PATH, { op: "$update", path: full.join(".") }, { node, op: "$update", field: "path", form: false });
836
874
  }
837
875
  return value.map((item, i) => i === head ? setIn(item, rest, next, full, node) : item);
838
876
  }
839
- const base = chunkL23ZLSDQ_cjs.isJsonObject(value) ? value : {};
840
- return { ...base, [head]: setIn(base[head] ?? null, rest, next, full, node) };
877
+ if (value !== null && !chunkVXU22DMV_cjs.isJsonObject(value))
878
+ return chunkVXU22DMV_cjs.failAt(
879
+ `No key ${JSON.stringify(head)} at ${full.join(".")}: the value there is ${chunkVXU22DMV_cjs.describeValue(value)}, and $update does not replace it.`,
880
+ chunkVXU22DMV_cjs.ErrorCode.TYPE,
881
+ { op: "$update", path: full.join(".") },
882
+ { node, op: "$update", field: "path", form: false }
883
+ );
884
+ const base = chunkVXU22DMV_cjs.isJsonObject(value) ? value : {};
885
+ return { ...base, [head]: setIn(chunkVXU22DMV_cjs.readOwnKey(base, head) ?? null, rest, next, full, node) };
841
886
  };
842
887
  var opUpdate = (node, context, evaluate2) => {
843
888
  const { from, path, value, as } = node.$update;
@@ -846,7 +891,7 @@ var opUpdate = (node, context, evaluate2) => {
846
891
  return setIn(source, path, next, path, node);
847
892
  };
848
893
  var opAssert = (node, context, evaluate2) => {
849
- if (!evaluate2(node.$assert.when, context)) throw new chunkL23ZLSDQ_cjs.PrismError(node.$assert.message, chunkL23ZLSDQ_cjs.ErrorCode.ASSERT, { op: "$assert" });
894
+ if (!evaluate2(node.$assert.when, context)) throw new chunkVXU22DMV_cjs.PrismError(node.$assert.message, chunkVXU22DMV_cjs.ErrorCode.ASSERT, { op: "$assert" });
850
895
  return evaluate2(node.$assert.value, context);
851
896
  };
852
897
  var opWalk = (node, context, evaluate2) => {
@@ -859,8 +904,8 @@ var opWalk = (node, context, evaluate2) => {
859
904
  return { matched: false, value };
860
905
  };
861
906
  const children = (value, visit) => {
862
- if (chunkL23ZLSDQ_cjs.isJsonArray(value)) return value.map(visit);
863
- if (chunkL23ZLSDQ_cjs.isJsonObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, visit(v)]));
907
+ if (chunkVXU22DMV_cjs.isJsonArray(value)) return value.map(visit);
908
+ if (chunkVXU22DMV_cjs.isJsonObject(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, visit(v)]));
864
909
  return value;
865
910
  };
866
911
  const post = (value) => rewrite(children(value, post)).value;
@@ -870,15 +915,19 @@ var opWalk = (node, context, evaluate2) => {
870
915
  dayjs__default.default.extend(utc__default.default);
871
916
  var DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
872
917
  var isDateOnly = (value) => typeof value === "string" && DATE_ONLY.test(value);
918
+ var notAheadOfTime = (context) => {
919
+ if (context.folding === true) throw new Error("answered where it runs");
920
+ };
873
921
  var parseDate = (value, node, op, field, written, contextOp) => {
874
922
  if (typeof value !== "string" && typeof value !== "number")
875
923
  return refuseType({ node, op, field, needs: "a date, as text or a number", got: value, written, contextOp });
876
924
  const d = isDateOnly(value) ? dayjs__default.default.utc(value) : dayjs__default.default(value);
877
925
  if (!d.isValid())
878
- return chunkL23ZLSDQ_cjs.failAt(`Invalid date for ${contextOp}: ${chunkL23ZLSDQ_cjs.clip(String(value), 60)}`, chunkL23ZLSDQ_cjs.ErrorCode.DATE_INVALID, { op: contextOp }, { node, op, field, form: false });
926
+ return chunkVXU22DMV_cjs.failAt(`Invalid date for ${contextOp}: ${chunkVXU22DMV_cjs.clip(String(value), 60)}`, chunkVXU22DMV_cjs.ErrorCode.DATE_INVALID, { op: contextOp }, { node, op, field, form: false });
879
927
  return d;
880
928
  };
881
929
  var opDate = (node, context, evaluate2) => {
930
+ notAheadOfTime(context);
882
931
  const value = evaluate2(node.$date.value, context);
883
932
  const d = parseDate(value, node, "$date", "value", node.$date.value, "$date");
884
933
  const instance = node.$date.utc ? d.utc() : d;
@@ -886,12 +935,14 @@ var opDate = (node, context, evaluate2) => {
886
935
  return instance.toISOString();
887
936
  };
888
937
  var opDateAdd = (node, context, evaluate2) => {
938
+ notAheadOfTime(context);
889
939
  const value = evaluate2(node.$dateAdd.date, context);
890
940
  const d = parseDate(value, node, "$dateAdd", "date", node.$dateAdd.date, "$dateAdd");
891
941
  const moved = d.add(node.$dateAdd.amount, node.$dateAdd.unit);
892
942
  return isDateOnly(value) ? moved.format("YYYY-MM-DD") : moved.toISOString();
893
943
  };
894
944
  var opDateDiff = (node, context, evaluate2) => {
945
+ notAheadOfTime(context);
895
946
  const from = evaluate2(node.$dateDiff.from, context);
896
947
  const to = evaluate2(node.$dateDiff.to, context);
897
948
  const fromDate = parseDate(from, node, "$dateDiff", "from", node.$dateDiff.from, "$dateDiff.from");
@@ -902,6 +953,24 @@ var opDateDiff = (node, context, evaluate2) => {
902
953
  // src/ops/intl.ops.ts
903
954
  var DATE_FORMATTERS = /* @__PURE__ */ new Map();
904
955
  var NUMBER_FORMATTERS = /* @__PURE__ */ new Map();
956
+ var MINOR_DIGITS = /* @__PURE__ */ new Map();
957
+ var MAX_CACHED_FORMATTERS = 1e3;
958
+ var cached = (cache, key, make) => {
959
+ const known = cache.get(key);
960
+ if (known !== void 0) return known;
961
+ const made = make();
962
+ if (cache.size >= MAX_CACHED_FORMATTERS) cache.clear();
963
+ cache.set(key, made);
964
+ return made;
965
+ };
966
+ var built = (make, node, op) => {
967
+ try {
968
+ return make();
969
+ } catch (error) {
970
+ if (!(error instanceof RangeError || error instanceof TypeError)) throw error;
971
+ return chunkVXU22DMV_cjs.failAt(`${op}: Intl refused its options: ${error.message}`, chunkVXU22DMV_cjs.ErrorCode.SCHEMA, { op }, { node, op, form: true });
972
+ }
973
+ };
905
974
  var DATE_ONLY2 = /^\d{4}-\d{2}-\d{2}$/;
906
975
  var localeOf = (value, node, op, written) => {
907
976
  if (typeof value !== "string" || value.trim() === "")
@@ -940,11 +1009,13 @@ var fallbackOf = (raw, context, evaluate2) => {
940
1009
  return resolved === null || resolved === void 0 ? "" : resolved;
941
1010
  };
942
1011
  var numberOf = (value, node, op, written) => {
943
- const parsed = typeof value === "number" ? value : Number(value);
1012
+ const text = typeof value === "string" ? value.trim() : void 0;
1013
+ const parsed = typeof value === "number" ? value : text !== void 0 && NUMERIC_TEXT.test(text) ? Number(text) : Number.NaN;
944
1014
  if (!Number.isFinite(parsed)) return refuseType({ node, op, field: "value", needs: "a number or numeric text", got: value, written, contextOp: op });
945
1015
  return parsed;
946
1016
  };
947
1017
  var opLocaleDate = (node, context, evaluate2) => {
1018
+ notAheadOfTime(context);
948
1019
  const spec = node.$localeDate;
949
1020
  const value = evaluate2(spec.value, context);
950
1021
  if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
@@ -953,35 +1024,29 @@ var opLocaleDate = (node, context, evaluate2) => {
953
1024
  const dateOnly = typeof value === "string" && DATE_ONLY2.test(value);
954
1025
  const parsed = typeof value === "number" ? new Date(value) : new Date(String(value));
955
1026
  if (Number.isNaN(parsed.getTime()))
956
- return chunkL23ZLSDQ_cjs.failAt(`Invalid date for $localeDate: ${chunkL23ZLSDQ_cjs.clip(String(value), 60)}`, chunkL23ZLSDQ_cjs.ErrorCode.DATE_INVALID, { op: "$localeDate" }, { node, op: "$localeDate", field: "value", form: false });
1027
+ return chunkVXU22DMV_cjs.failAt(`Invalid date for $localeDate: ${chunkVXU22DMV_cjs.clip(String(value), 60)}`, chunkVXU22DMV_cjs.ErrorCode.DATE_INVALID, { op: "$localeDate" }, { node, op: "$localeDate", field: "value", form: false });
957
1028
  const zone = zoneOf(writtenZone, node, context, evaluate2);
958
1029
  const timeZone = zone ?? (dateOnly ? "UTC" : void 0);
959
1030
  const options = {
960
1031
  ...authored,
961
1032
  ...timeZone === void 0 ? {} : { timeZone }
962
1033
  };
963
- const key = `${locale}\0${JSON.stringify(options)}`;
964
- let formatter = DATE_FORMATTERS.get(key);
965
- if (formatter === void 0) {
966
- formatter = new Intl.DateTimeFormat(readableLocale(locale, node, "$localeDate", spec.locale), options);
967
- DATE_FORMATTERS.set(key, formatter);
968
- }
1034
+ const formatter = cached(
1035
+ DATE_FORMATTERS,
1036
+ `${locale}\0${JSON.stringify(options)}`,
1037
+ () => built(() => new Intl.DateTimeFormat(readableLocale(locale, node, "$localeDate", spec.locale), options), node, "$localeDate")
1038
+ );
969
1039
  return formatter.format(parsed);
970
1040
  };
971
- var minorUnitDivisor = (locale, currency) => {
972
- const key = `divisor\0${locale}\0${currency}`;
973
- let formatter = NUMBER_FORMATTERS.get(key);
974
- if (formatter === void 0) {
975
- try {
976
- formatter = new Intl.NumberFormat(locale, { style: "currency", currency });
977
- } catch {
978
- return 100;
979
- }
980
- NUMBER_FORMATTERS.set(key, formatter);
1041
+ var minorDigits = (currency) => cached(MINOR_DIGITS, currency, () => {
1042
+ try {
1043
+ return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2;
1044
+ } catch {
1045
+ return 2;
981
1046
  }
982
- return 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2);
983
- };
1047
+ });
984
1048
  var opLocaleMoney = (node, context, evaluate2) => {
1049
+ notAheadOfTime(context);
985
1050
  const spec = node.$localeMoney;
986
1051
  const value = evaluate2(spec.value, context);
987
1052
  if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
@@ -991,25 +1056,23 @@ var opLocaleMoney = (node, context, evaluate2) => {
991
1056
  return refuseType({ node, op: "$localeMoney", field: "currency", needs: 'an ISO-4217 currency code such as "EUR"', got: rawCurrency, written: spec.currency, contextOp: "$localeMoney" });
992
1057
  const currency = rawCurrency.toUpperCase();
993
1058
  const amount = numberOf(value, node, "$localeMoney", spec.value);
994
- const major = spec.minorUnits === false ? amount : amount / minorUnitDivisor(locale, currency);
1059
+ const digits = minorDigits(currency);
1060
+ const major = spec.minorUnits === false ? amount : amount / 10 ** digits;
995
1061
  const options = {
996
1062
  style: "currency",
997
1063
  currency,
998
1064
  ...spec.digits === void 0 ? {} : { minimumFractionDigits: spec.digits, maximumFractionDigits: spec.digits }
999
1065
  };
1000
- const key = `${locale}\0${JSON.stringify(options)}`;
1001
- let formatter = NUMBER_FORMATTERS.get(key);
1002
- if (formatter === void 0) {
1003
- try {
1004
- formatter = new Intl.NumberFormat(locale, options);
1005
- } catch {
1006
- return `${currency} ${major.toFixed(spec.digits ?? 2)}`;
1007
- }
1008
- NUMBER_FORMATTERS.set(key, formatter);
1066
+ let formatter;
1067
+ try {
1068
+ formatter = cached(NUMBER_FORMATTERS, `${locale}\0${JSON.stringify(options)}`, () => new Intl.NumberFormat(locale, options));
1069
+ } catch {
1070
+ return `${currency} ${major.toFixed(spec.digits ?? digits)}`;
1009
1071
  }
1010
1072
  return formatter.format(major);
1011
1073
  };
1012
1074
  var opLocaleNumber = (node, context, evaluate2) => {
1075
+ notAheadOfTime(context);
1013
1076
  const spec = node.$localeNumber;
1014
1077
  const value = evaluate2(spec.value, context);
1015
1078
  if (isBlank(value)) return fallbackOf(spec.fallback, context, evaluate2);
@@ -1020,18 +1083,16 @@ var opLocaleNumber = (node, context, evaluate2) => {
1020
1083
  ...spec.minDigits === void 0 ? {} : { minimumFractionDigits: spec.minDigits },
1021
1084
  ...spec.compact === true ? { notation: "compact" } : {}
1022
1085
  };
1023
- const key = `${locale}\0${JSON.stringify(options)}`;
1024
- let formatter = NUMBER_FORMATTERS.get(key);
1025
- if (formatter === void 0) {
1026
- formatter = new Intl.NumberFormat(readableLocale(locale, node, "$localeNumber", spec.locale), options);
1027
- NUMBER_FORMATTERS.set(key, formatter);
1028
- }
1086
+ const formatter = cached(
1087
+ NUMBER_FORMATTERS,
1088
+ `${locale}\0${JSON.stringify(options)}`,
1089
+ () => built(() => new Intl.NumberFormat(readableLocale(locale, node, "$localeNumber", spec.locale), options), node, "$localeNumber")
1090
+ );
1029
1091
  return formatter.format(numberOf(value, node, "$localeNumber", spec.value));
1030
1092
  };
1031
1093
 
1032
1094
  // src/engine/optimize.ts
1033
1095
  var HANDLER_KEY = "__op";
1034
- var SEGMENTS_KEY2 = "__segments";
1035
1096
  var eraseOp = (op) => op;
1036
1097
  var attachNonEnumerable = (target, key, value) => {
1037
1098
  Object.defineProperty(target, key, {
@@ -1047,71 +1108,71 @@ var freezeConstant = (value) => {
1047
1108
  for (const inner of Object.values(value)) freezeConstant(inner);
1048
1109
  };
1049
1110
  var resolveHandler = (node) => {
1050
- if (chunkL23ZLSDQ_cjs.isRefNode(node)) return eraseOp(opRef);
1051
- if (chunkL23ZLSDQ_cjs.isConstNode(node)) return eraseOp(opConst);
1052
- if (chunkL23ZLSDQ_cjs.isVarNode(node)) return eraseOp(opVar);
1053
- if (chunkL23ZLSDQ_cjs.isGetNode(node)) return eraseOp(opGet);
1054
- if (chunkL23ZLSDQ_cjs.isWithNode(node)) return eraseOp(opWith);
1055
- if (chunkL23ZLSDQ_cjs.isMapNode(node)) return eraseOp(opMap);
1056
- if (chunkL23ZLSDQ_cjs.isFilterNode(node)) return eraseOp(opFilter);
1057
- if (chunkL23ZLSDQ_cjs.isReduceNode(node)) return eraseOp(opReduce);
1058
- if (chunkL23ZLSDQ_cjs.isSliceNode(node)) return eraseOp(opSlice);
1059
- if (chunkL23ZLSDQ_cjs.isFlattenNode(node)) return eraseOp(opFlatten);
1060
- if (chunkL23ZLSDQ_cjs.isUniqueNode(node)) return eraseOp(opUnique);
1061
- if (chunkL23ZLSDQ_cjs.isSortByNode(node)) return eraseOp(opSortBy);
1062
- if (chunkL23ZLSDQ_cjs.isAddNode(node)) return eraseOp(opAdd);
1063
- if (chunkL23ZLSDQ_cjs.isSubNode(node)) return eraseOp(opSub);
1064
- if (chunkL23ZLSDQ_cjs.isMulNode(node)) return eraseOp(opMul);
1065
- if (chunkL23ZLSDQ_cjs.isDivNode(node)) return eraseOp(opDiv);
1066
- if (chunkL23ZLSDQ_cjs.isRoundNode(node)) return eraseOp(opRound);
1067
- if (chunkL23ZLSDQ_cjs.isModNode(node)) return eraseOp(opMod);
1068
- if (chunkL23ZLSDQ_cjs.isToNumberNode(node)) return eraseOp(opToNumber);
1069
- if (chunkL23ZLSDQ_cjs.isJoinNode(node)) return eraseOp(opJoin);
1070
- if (chunkL23ZLSDQ_cjs.isToStringNode(node)) return eraseOp(opToString);
1071
- if (chunkL23ZLSDQ_cjs.isInterpolateNode(node)) return eraseOp(opInterpolate);
1072
- if (chunkL23ZLSDQ_cjs.isFillNode(node)) return eraseOp(opFill);
1073
- if (chunkL23ZLSDQ_cjs.isTrimNode(node)) return eraseOp(opTrim);
1074
- if (chunkL23ZLSDQ_cjs.isLowerNode(node)) return eraseOp(opLower);
1075
- if (chunkL23ZLSDQ_cjs.isUpperNode(node)) return eraseOp(opUpper);
1076
- if (chunkL23ZLSDQ_cjs.isSplitNode(node)) return eraseOp(opSplit);
1077
- if (chunkL23ZLSDQ_cjs.isReplaceNode(node)) return eraseOp(opReplace);
1078
- if (chunkL23ZLSDQ_cjs.isEqNode(node)) return eraseOp(opEq);
1079
- if (chunkL23ZLSDQ_cjs.isNeqNode(node)) return eraseOp(opNeq);
1080
- if (chunkL23ZLSDQ_cjs.isGtNode(node)) return eraseOp(opGt);
1081
- if (chunkL23ZLSDQ_cjs.isGteNode(node)) return eraseOp(opGte);
1082
- if (chunkL23ZLSDQ_cjs.isLtNode(node)) return eraseOp(opLt);
1083
- if (chunkL23ZLSDQ_cjs.isLteNode(node)) return eraseOp(opLte);
1084
- if (chunkL23ZLSDQ_cjs.isEmptyNode(node)) return eraseOp(opEmpty);
1085
- if (chunkL23ZLSDQ_cjs.isStartsWithNode(node)) return eraseOp(opStartsWith);
1086
- if (chunkL23ZLSDQ_cjs.isEndsWithNode(node)) return eraseOp(opEndsWith);
1087
- if (chunkL23ZLSDQ_cjs.isContainsNode(node)) return eraseOp(opContains);
1088
- if (chunkL23ZLSDQ_cjs.isNotNode(node)) return eraseOp(opNot);
1089
- if (chunkL23ZLSDQ_cjs.isAndNode(node)) return eraseOp(opAnd);
1090
- if (chunkL23ZLSDQ_cjs.isOrNode(node)) return eraseOp(opOr);
1091
- if (chunkL23ZLSDQ_cjs.isMergeNode(node)) return eraseOp(opMerge);
1092
- if (chunkL23ZLSDQ_cjs.isCoalesceNode(node)) return eraseOp(opCoalesce);
1093
- if (chunkL23ZLSDQ_cjs.isCaseNode(node)) return eraseOp(opCase);
1094
- if (chunkL23ZLSDQ_cjs.isEntriesOfNode(node)) return eraseOp(opEntriesOf);
1095
- if (chunkL23ZLSDQ_cjs.isKeyByNode(node)) return eraseOp(opKeyBy);
1096
- if (chunkL23ZLSDQ_cjs.isGroupByNode(node)) return eraseOp(opGroupBy);
1097
- if (chunkL23ZLSDQ_cjs.isKeysNode(node)) return eraseOp(opKeys);
1098
- if (chunkL23ZLSDQ_cjs.isValuesNode(node)) return eraseOp(opValues);
1099
- if (chunkL23ZLSDQ_cjs.isFromEntriesNode(node)) return eraseOp(opFromEntries);
1100
- if (chunkL23ZLSDQ_cjs.isPickNode(node)) return eraseOp(opPick);
1101
- if (chunkL23ZLSDQ_cjs.isOmitNode(node)) return eraseOp(opOmit);
1102
- if (chunkL23ZLSDQ_cjs.isTypeNode(node)) return eraseOp(opType);
1103
- if (chunkL23ZLSDQ_cjs.isLengthNode(node)) return eraseOp(opLength);
1104
- if (chunkL23ZLSDQ_cjs.isHasNode(node)) return eraseOp(opHas);
1105
- if (chunkL23ZLSDQ_cjs.isRenameKeysNode(node)) return eraseOp(opRenameKeys);
1106
- if (chunkL23ZLSDQ_cjs.isUpdateNode(node)) return eraseOp(opUpdate);
1107
- if (chunkL23ZLSDQ_cjs.isAssertNode(node)) return eraseOp(opAssert);
1108
- if (chunkL23ZLSDQ_cjs.isWalkNode(node)) return eraseOp(opWalk);
1109
- if (chunkL23ZLSDQ_cjs.isDateNode(node)) return eraseOp(opDate);
1110
- if (chunkL23ZLSDQ_cjs.isDateAddNode(node)) return eraseOp(opDateAdd);
1111
- if (chunkL23ZLSDQ_cjs.isDateDiffNode(node)) return eraseOp(opDateDiff);
1112
- if (chunkL23ZLSDQ_cjs.isLocaleDateNode(node)) return eraseOp(opLocaleDate);
1113
- if (chunkL23ZLSDQ_cjs.isLocaleMoneyNode(node)) return eraseOp(opLocaleMoney);
1114
- if (chunkL23ZLSDQ_cjs.isLocaleNumberNode(node)) return eraseOp(opLocaleNumber);
1111
+ if (chunkVXU22DMV_cjs.isRefNode(node)) return eraseOp(opRef);
1112
+ if (chunkVXU22DMV_cjs.isConstNode(node)) return eraseOp(opConst);
1113
+ if (chunkVXU22DMV_cjs.isVarNode(node)) return eraseOp(opVar);
1114
+ if (chunkVXU22DMV_cjs.isGetNode(node)) return eraseOp(opGet);
1115
+ if (chunkVXU22DMV_cjs.isWithNode(node)) return eraseOp(opWith);
1116
+ if (chunkVXU22DMV_cjs.isMapNode(node)) return eraseOp(opMap);
1117
+ if (chunkVXU22DMV_cjs.isFilterNode(node)) return eraseOp(opFilter);
1118
+ if (chunkVXU22DMV_cjs.isReduceNode(node)) return eraseOp(opReduce);
1119
+ if (chunkVXU22DMV_cjs.isSliceNode(node)) return eraseOp(opSlice);
1120
+ if (chunkVXU22DMV_cjs.isFlattenNode(node)) return eraseOp(opFlatten);
1121
+ if (chunkVXU22DMV_cjs.isUniqueNode(node)) return eraseOp(opUnique);
1122
+ if (chunkVXU22DMV_cjs.isSortByNode(node)) return eraseOp(opSortBy);
1123
+ if (chunkVXU22DMV_cjs.isAddNode(node)) return eraseOp(opAdd);
1124
+ if (chunkVXU22DMV_cjs.isSubNode(node)) return eraseOp(opSub);
1125
+ if (chunkVXU22DMV_cjs.isMulNode(node)) return eraseOp(opMul);
1126
+ if (chunkVXU22DMV_cjs.isDivNode(node)) return eraseOp(opDiv);
1127
+ if (chunkVXU22DMV_cjs.isRoundNode(node)) return eraseOp(opRound);
1128
+ if (chunkVXU22DMV_cjs.isModNode(node)) return eraseOp(opMod);
1129
+ if (chunkVXU22DMV_cjs.isToNumberNode(node)) return eraseOp(opToNumber);
1130
+ if (chunkVXU22DMV_cjs.isJoinNode(node)) return eraseOp(opJoin);
1131
+ if (chunkVXU22DMV_cjs.isToStringNode(node)) return eraseOp(opToString);
1132
+ if (chunkVXU22DMV_cjs.isInterpolateNode(node)) return eraseOp(opInterpolate);
1133
+ if (chunkVXU22DMV_cjs.isFillNode(node)) return eraseOp(opFill);
1134
+ if (chunkVXU22DMV_cjs.isTrimNode(node)) return eraseOp(opTrim);
1135
+ if (chunkVXU22DMV_cjs.isLowerNode(node)) return eraseOp(opLower);
1136
+ if (chunkVXU22DMV_cjs.isUpperNode(node)) return eraseOp(opUpper);
1137
+ if (chunkVXU22DMV_cjs.isSplitNode(node)) return eraseOp(opSplit);
1138
+ if (chunkVXU22DMV_cjs.isReplaceNode(node)) return eraseOp(opReplace);
1139
+ if (chunkVXU22DMV_cjs.isEqNode(node)) return eraseOp(opEq);
1140
+ if (chunkVXU22DMV_cjs.isNeqNode(node)) return eraseOp(opNeq);
1141
+ if (chunkVXU22DMV_cjs.isGtNode(node)) return eraseOp(opGt);
1142
+ if (chunkVXU22DMV_cjs.isGteNode(node)) return eraseOp(opGte);
1143
+ if (chunkVXU22DMV_cjs.isLtNode(node)) return eraseOp(opLt);
1144
+ if (chunkVXU22DMV_cjs.isLteNode(node)) return eraseOp(opLte);
1145
+ if (chunkVXU22DMV_cjs.isEmptyNode(node)) return eraseOp(opEmpty);
1146
+ if (chunkVXU22DMV_cjs.isStartsWithNode(node)) return eraseOp(opStartsWith);
1147
+ if (chunkVXU22DMV_cjs.isEndsWithNode(node)) return eraseOp(opEndsWith);
1148
+ if (chunkVXU22DMV_cjs.isContainsNode(node)) return eraseOp(opContains);
1149
+ if (chunkVXU22DMV_cjs.isNotNode(node)) return eraseOp(opNot);
1150
+ if (chunkVXU22DMV_cjs.isAndNode(node)) return eraseOp(opAnd);
1151
+ if (chunkVXU22DMV_cjs.isOrNode(node)) return eraseOp(opOr);
1152
+ if (chunkVXU22DMV_cjs.isMergeNode(node)) return eraseOp(opMerge);
1153
+ if (chunkVXU22DMV_cjs.isCoalesceNode(node)) return eraseOp(opCoalesce);
1154
+ if (chunkVXU22DMV_cjs.isCaseNode(node)) return eraseOp(opCase);
1155
+ if (chunkVXU22DMV_cjs.isEntriesOfNode(node)) return eraseOp(opEntriesOf);
1156
+ if (chunkVXU22DMV_cjs.isKeyByNode(node)) return eraseOp(opKeyBy);
1157
+ if (chunkVXU22DMV_cjs.isGroupByNode(node)) return eraseOp(opGroupBy);
1158
+ if (chunkVXU22DMV_cjs.isKeysNode(node)) return eraseOp(opKeys);
1159
+ if (chunkVXU22DMV_cjs.isValuesNode(node)) return eraseOp(opValues);
1160
+ if (chunkVXU22DMV_cjs.isFromEntriesNode(node)) return eraseOp(opFromEntries);
1161
+ if (chunkVXU22DMV_cjs.isPickNode(node)) return eraseOp(opPick);
1162
+ if (chunkVXU22DMV_cjs.isOmitNode(node)) return eraseOp(opOmit);
1163
+ if (chunkVXU22DMV_cjs.isTypeNode(node)) return eraseOp(opType);
1164
+ if (chunkVXU22DMV_cjs.isLengthNode(node)) return eraseOp(opLength);
1165
+ if (chunkVXU22DMV_cjs.isHasNode(node)) return eraseOp(opHas);
1166
+ if (chunkVXU22DMV_cjs.isRenameKeysNode(node)) return eraseOp(opRenameKeys);
1167
+ if (chunkVXU22DMV_cjs.isUpdateNode(node)) return eraseOp(opUpdate);
1168
+ if (chunkVXU22DMV_cjs.isAssertNode(node)) return eraseOp(opAssert);
1169
+ if (chunkVXU22DMV_cjs.isWalkNode(node)) return eraseOp(opWalk);
1170
+ if (chunkVXU22DMV_cjs.isDateNode(node)) return eraseOp(opDate);
1171
+ if (chunkVXU22DMV_cjs.isDateAddNode(node)) return eraseOp(opDateAdd);
1172
+ if (chunkVXU22DMV_cjs.isDateDiffNode(node)) return eraseOp(opDateDiff);
1173
+ if (chunkVXU22DMV_cjs.isLocaleDateNode(node)) return eraseOp(opLocaleDate);
1174
+ if (chunkVXU22DMV_cjs.isLocaleMoneyNode(node)) return eraseOp(opLocaleMoney);
1175
+ if (chunkVXU22DMV_cjs.isLocaleNumberNode(node)) return eraseOp(opLocaleNumber);
1115
1176
  return void 0;
1116
1177
  };
1117
1178
  var isFoldableLiteral = (node) => {
@@ -1119,21 +1180,21 @@ var isFoldableLiteral = (node) => {
1119
1180
  const t = typeof node;
1120
1181
  if (t === "string" || t === "number" || t === "boolean") return true;
1121
1182
  if (Array.isArray(node)) return node.every(isFoldableLiteral);
1122
- if (!chunkL23ZLSDQ_cjs.isJsonObject(node)) return false;
1123
- if (chunkL23ZLSDQ_cjs.isConstNode(node)) return isFoldableLiteral(node.$const);
1183
+ if (!chunkVXU22DMV_cjs.isJsonObject(node)) return false;
1184
+ if (chunkVXU22DMV_cjs.isConstNode(node)) return isFoldableLiteral(node.$const);
1124
1185
  if (Object.keys(node).some((k) => k.startsWith("$"))) return false;
1125
1186
  return Object.values(node).every(isFoldableLiteral);
1126
1187
  };
1127
- var optimizeNode = (node, stats, evaluate2) => {
1188
+ var optimizeNode = (node, stats, evaluate2, options) => {
1128
1189
  if (node === null || node === void 0) return node;
1129
1190
  if (typeof node !== "object") return node;
1130
1191
  if (Array.isArray(node)) {
1131
1192
  const out = [];
1132
- for (const child of node) out.push(optimizeNode(child, stats, evaluate2));
1193
+ for (const child of node) out.push(optimizeNode(child, stats, evaluate2, options));
1133
1194
  return out;
1134
1195
  }
1135
- if (!chunkL23ZLSDQ_cjs.isJsonObject(node)) return node;
1136
- if (chunkL23ZLSDQ_cjs.isConstNode(node)) {
1196
+ if (!chunkVXU22DMV_cjs.isJsonObject(node)) return node;
1197
+ if (chunkVXU22DMV_cjs.isConstNode(node)) {
1137
1198
  const literal = { ...node };
1138
1199
  freezeConstant(literal["$const"]);
1139
1200
  attachNonEnumerable(literal, HANDLER_KEY, eraseOp(opConst));
@@ -1142,21 +1203,21 @@ var optimizeNode = (node, stats, evaluate2) => {
1142
1203
  }
1143
1204
  const optimizeValues = (record) => {
1144
1205
  const out = {};
1145
- for (const key of Object.keys(record)) out[key] = optimizeNode(record[key], stats, evaluate2);
1206
+ for (const key of Object.keys(record)) out[key] = optimizeNode(record[key], stats, evaluate2, options);
1146
1207
  return out;
1147
1208
  };
1148
1209
  let optimized;
1149
- if (chunkL23ZLSDQ_cjs.isWithNode(node)) {
1150
- optimized = { $with: { let: optimizeValues(node.$with.let), value: optimizeNode(node.$with.value, stats, evaluate2) } };
1151
- } else if (chunkL23ZLSDQ_cjs.isRenameKeysNode(node)) {
1152
- optimized = { $renameKeys: { ...node.$renameKeys, from: optimizeNode(node.$renameKeys.from, stats, evaluate2) } };
1210
+ if (chunkVXU22DMV_cjs.isWithNode(node)) {
1211
+ optimized = { $with: { let: optimizeValues(node.$with.let), value: optimizeNode(node.$with.value, stats, evaluate2, options) } };
1212
+ } else if (chunkVXU22DMV_cjs.isRenameKeysNode(node)) {
1213
+ optimized = { $renameKeys: { ...node.$renameKeys, from: optimizeNode(node.$renameKeys.from, stats, evaluate2, options) } };
1153
1214
  } else {
1154
1215
  optimized = optimizeValues(node);
1155
1216
  }
1156
- if (chunkL23ZLSDQ_cjs.isRefNode(optimized)) {
1157
- const segments = chunkL23ZLSDQ_cjs.parseJsonPath(optimized.$ref);
1217
+ if (chunkVXU22DMV_cjs.isRefNode(optimized)) {
1218
+ const segments = chunkVXU22DMV_cjs.parseJsonPath(optimized.$ref);
1158
1219
  if (segments.length > 0) {
1159
- attachNonEnumerable(optimized, SEGMENTS_KEY2, segments);
1220
+ attachNonEnumerable(optimized, SEGMENTS_KEY, segments);
1160
1221
  stats.refsInlined += 1;
1161
1222
  }
1162
1223
  }
@@ -1165,18 +1226,19 @@ var optimizeNode = (node, stats, evaluate2) => {
1165
1226
  attachNonEnumerable(optimized, HANDLER_KEY, handler);
1166
1227
  stats.handlersAttached += 1;
1167
1228
  }
1168
- if (handler !== void 0 && !chunkL23ZLSDQ_cjs.isConstNode(optimized) && !chunkL23ZLSDQ_cjs.isRefNode(optimized) && !chunkL23ZLSDQ_cjs.isVarNode(optimized)) {
1229
+ if (handler !== void 0 && !chunkVXU22DMV_cjs.isConstNode(optimized) && !chunkVXU22DMV_cjs.isRefNode(optimized) && !chunkVXU22DMV_cjs.isVarNode(optimized)) {
1169
1230
  const allFoldable = Object.entries(optimized).every(([key, value]) => {
1170
- if (key === HANDLER_KEY || key === SEGMENTS_KEY2) return true;
1231
+ if (key === HANDLER_KEY || key === SEGMENTS_KEY) return true;
1171
1232
  return isFoldableLiteral(value);
1172
1233
  });
1173
1234
  if (allFoldable) {
1174
- const emptyCtx = { source: {}, vars: {}, budget: createBudget() };
1235
+ const emptyCtx = { source: {}, vars: {}, budget: createBudget(), folding: true };
1175
1236
  try {
1176
1237
  const folded = handler(optimized, emptyCtx, evaluate2);
1177
1238
  const replacement = { $const: folded };
1178
1239
  freezeConstant(folded);
1179
1240
  attachNonEnumerable(replacement, HANDLER_KEY, eraseOp(opConst));
1241
+ if (options.recordFoldCost === true) attachNonEnumerable(replacement, COST_KEY, emptyCtx.budget?.steps ?? 0);
1180
1242
  stats.constantsFolded += 1;
1181
1243
  return replacement;
1182
1244
  } catch {
@@ -1185,9 +1247,9 @@ var optimizeNode = (node, stats, evaluate2) => {
1185
1247
  }
1186
1248
  return optimized;
1187
1249
  };
1188
- var optimize = (node, evaluate2) => {
1250
+ var optimize = (node, evaluate2, options = {}) => {
1189
1251
  const stats = { refsInlined: 0, handlersAttached: 0, constantsFolded: 0 };
1190
- const result = optimizeNode(node, stats, evaluate2);
1252
+ const result = optimizeNode(node, stats, evaluate2, options);
1191
1253
  return { node: result, stats };
1192
1254
  };
1193
1255
  var annotateNode = (node) => {
@@ -1195,20 +1257,20 @@ var annotateNode = (node) => {
1195
1257
  for (const child of node) annotateNode(child);
1196
1258
  return;
1197
1259
  }
1198
- if (!chunkL23ZLSDQ_cjs.isJsonObject(node)) return;
1199
- if (chunkL23ZLSDQ_cjs.isWithNode(node)) {
1260
+ if (!chunkVXU22DMV_cjs.isJsonObject(node)) return;
1261
+ if (chunkVXU22DMV_cjs.isWithNode(node)) {
1200
1262
  for (const value of Object.values(node.$with.let)) annotateNode(value);
1201
1263
  annotateNode(node.$with.value);
1202
- } else if (chunkL23ZLSDQ_cjs.isRenameKeysNode(node)) {
1264
+ } else if (chunkVXU22DMV_cjs.isRenameKeysNode(node)) {
1203
1265
  annotateNode(node.$renameKeys.from);
1204
- } else if (!chunkL23ZLSDQ_cjs.isConstNode(node)) {
1266
+ } else if (!chunkVXU22DMV_cjs.isConstNode(node)) {
1205
1267
  for (const value of Object.values(node)) annotateNode(value);
1206
1268
  } else {
1207
1269
  freezeConstant(node.$const);
1208
1270
  }
1209
- if (chunkL23ZLSDQ_cjs.isRefNode(node)) {
1210
- const segments = chunkL23ZLSDQ_cjs.parseJsonPath(node.$ref);
1211
- if (segments.length > 0) attachNonEnumerable(node, SEGMENTS_KEY2, segments);
1271
+ if (chunkVXU22DMV_cjs.isRefNode(node)) {
1272
+ const segments = chunkVXU22DMV_cjs.parseJsonPath(node.$ref);
1273
+ if (segments.length > 0) attachNonEnumerable(node, SEGMENTS_KEY, segments);
1212
1274
  }
1213
1275
  const handler = resolveHandler(node);
1214
1276
  if (handler !== void 0) attachNonEnumerable(node, HANDLER_KEY, handler);
@@ -1231,7 +1293,7 @@ var findPath = (tree, matches) => {
1231
1293
  return walk2(tree) ? at : void 0;
1232
1294
  };
1233
1295
  var soleOpOf = (node) => {
1234
- if (!chunkL23ZLSDQ_cjs.isJsonObject(node)) return void 0;
1296
+ if (!chunkVXU22DMV_cjs.isJsonObject(node)) return void 0;
1235
1297
  const keys = Object.keys(node);
1236
1298
  return keys.length === 1 && keys[0] !== void 0 && keys[0].startsWith("$") ? keys[0] : void 0;
1237
1299
  };
@@ -1251,12 +1313,12 @@ var authorPosition = (authored, treePath) => {
1251
1313
  continue;
1252
1314
  }
1253
1315
  const op = soleOpOf(node);
1254
- if (op === void 0 || !chunkL23ZLSDQ_cjs.isJsonObject(node)) return void 0;
1316
+ if (op === void 0 || !chunkVXU22DMV_cjs.isJsonObject(node)) return void 0;
1255
1317
  const fields = node[op];
1256
- const names = chunkL23ZLSDQ_cjs.isJsonObject(fields) ? Object.keys(fields) : [];
1318
+ const names = chunkVXU22DMV_cjs.isJsonObject(fields) ? Object.keys(fields) : [];
1257
1319
  const rewritten = desugar({ [op]: Object.fromEntries(names.map((name) => [name, `${MARK}${name}`])) });
1258
1320
  const landed = names.map((name) => ({ name, at: findPath(rewritten, (value) => value === `${MARK}${name}`) })).find(({ at }) => at !== void 0 && at.every((segment, i) => rest[i] === segment));
1259
- if (landed?.at === void 0 || !chunkL23ZLSDQ_cjs.isJsonObject(fields)) return { path: [...path, op], sugar: op };
1321
+ if (landed?.at === void 0 || !chunkVXU22DMV_cjs.isJsonObject(fields)) return { path: [...path, op], sugar: op };
1260
1322
  path.push(op, landed.name);
1261
1323
  node = fields[landed.name];
1262
1324
  rest = rest.slice(landed.at.length);
@@ -1266,8 +1328,8 @@ var authorPosition = (authored, treePath) => {
1266
1328
  };
1267
1329
  var pathText = (path) => path.length === 0 ? "(root)" : path.join(".");
1268
1330
  var placeError = (error, tree, authored) => {
1269
- if (!(error instanceof chunkL23ZLSDQ_cjs.PrismError)) return;
1270
- const origin = chunkL23ZLSDQ_cjs.takeOrigin(error);
1331
+ if (!(error instanceof chunkVXU22DMV_cjs.PrismError)) return;
1332
+ const origin = chunkVXU22DMV_cjs.takeOrigin(error);
1271
1333
  if (origin === void 0) return;
1272
1334
  const parts = [error.message];
1273
1335
  if (origin.detail !== void 0) parts.push(origin.detail());
@@ -1283,18 +1345,17 @@ var placeError = (error, tree, authored) => {
1283
1345
  formOp = position.sugar;
1284
1346
  }
1285
1347
  }
1286
- const form = origin.form && formOp !== void 0 ? chunkL23ZLSDQ_cjs.formOf(formOp) : void 0;
1348
+ const form = origin.form && formOp !== void 0 ? chunkVXU22DMV_cjs.formOf(formOp) : void 0;
1287
1349
  if (form !== void 0) parts.push(`Form: ${form}`);
1288
1350
  error.message = parts.join(" ");
1289
1351
  };
1290
1352
 
1291
1353
  // src/engine/evaluate.ts
1292
- var HANDLER_KEY2 = "__op";
1293
1354
  var isAttachedFn = (value) => typeof value === "function";
1294
1355
  var evaluateNode = (node, context) => {
1295
1356
  const { budget } = context;
1296
1357
  if (budget === void 0) return evaluateUnbudgeted(node, context);
1297
- spendStep(budget, node);
1358
+ spendSteps(budget, node);
1298
1359
  const out = evaluateUnbudgeted(node, context);
1299
1360
  measureString(out, budget, node);
1300
1361
  return out;
@@ -1305,134 +1366,79 @@ var evaluateUnbudgeted = (node, context) => {
1305
1366
  if (Array.isArray(node)) return node.map((n) => evaluateNode(n, context));
1306
1367
  if (typeof node !== "object") return null;
1307
1368
  const obj = node;
1308
- const attached = obj[HANDLER_KEY2];
1369
+ const attached = obj[HANDLER_KEY];
1309
1370
  if (isAttachedFn(attached)) return attached(obj, context, evaluateNode);
1310
- if (chunkL23ZLSDQ_cjs.isPlainObject(obj)) {
1371
+ if (chunkVXU22DMV_cjs.isPlainObject(obj)) {
1311
1372
  const result = {};
1312
- if (!(chunkL23ZLSDQ_cjs.OPTIONAL_FIELDS_KEY in obj)) {
1313
- for (const key of Object.keys(obj)) result[key] = evaluateNode(obj[key], context);
1373
+ if (!(chunkVXU22DMV_cjs.OPTIONAL_FIELDS_KEY in obj)) {
1374
+ for (const key of Object.keys(obj)) chunkVXU22DMV_cjs.writeOwnKey(result, key, evaluateNode(obj[key], context));
1314
1375
  return result;
1315
1376
  }
1316
1377
  const optionalFields = new Set(
1317
- Array.isArray(obj[chunkL23ZLSDQ_cjs.OPTIONAL_FIELDS_KEY]) ? obj[chunkL23ZLSDQ_cjs.OPTIONAL_FIELDS_KEY] : []
1378
+ Array.isArray(obj[chunkVXU22DMV_cjs.OPTIONAL_FIELDS_KEY]) ? obj[chunkVXU22DMV_cjs.OPTIONAL_FIELDS_KEY] : []
1318
1379
  );
1319
1380
  for (const [key, value] of Object.entries(obj)) {
1320
- if (key === chunkL23ZLSDQ_cjs.OPTIONAL_FIELDS_KEY) continue;
1381
+ if (key === chunkVXU22DMV_cjs.OPTIONAL_FIELDS_KEY) continue;
1321
1382
  const isOptional = optionalFields.has(key);
1322
1383
  try {
1323
1384
  const evaluated = evaluateNode(value, context);
1324
1385
  if (isOptional && (evaluated === null || evaluated === void 0)) continue;
1325
- result[key] = evaluated;
1386
+ chunkVXU22DMV_cjs.writeOwnKey(result, key, evaluated);
1326
1387
  } catch (error) {
1327
- if (isOptional && error instanceof chunkL23ZLSDQ_cjs.PrismError && error.code === chunkL23ZLSDQ_cjs.ErrorCode.MISSING_PATH) continue;
1388
+ if (isOptional && error instanceof chunkVXU22DMV_cjs.PrismError && (error.code === chunkVXU22DMV_cjs.ErrorCode.MISSING_PATH || error.context?.details?.["absent"] === true)) continue;
1328
1389
  throw error;
1329
1390
  }
1330
1391
  }
1331
1392
  return result;
1332
1393
  }
1333
- if (chunkL23ZLSDQ_cjs.isRefNode(obj)) return opRef(obj, context);
1334
- if (chunkL23ZLSDQ_cjs.isConstNode(obj)) return opConst(obj, context);
1335
- if (chunkL23ZLSDQ_cjs.isVarNode(obj)) return opVar(obj, context);
1336
- if (chunkL23ZLSDQ_cjs.isGetNode(obj)) return opGet(obj, context, evaluateNode);
1337
- if (chunkL23ZLSDQ_cjs.isWithNode(obj)) return opWith(obj, context, evaluateNode);
1338
- if (chunkL23ZLSDQ_cjs.isMapNode(obj)) return opMap(obj, context, evaluateNode);
1339
- if (chunkL23ZLSDQ_cjs.isFilterNode(obj)) return opFilter(obj, context, evaluateNode);
1340
- if (chunkL23ZLSDQ_cjs.isReduceNode(obj)) return opReduce(obj, context, evaluateNode);
1341
- if (chunkL23ZLSDQ_cjs.isSliceNode(obj)) return opSlice(obj, context, evaluateNode);
1342
- if (chunkL23ZLSDQ_cjs.isFlattenNode(obj)) return opFlatten(obj, context, evaluateNode);
1343
- if (chunkL23ZLSDQ_cjs.isUniqueNode(obj)) return opUnique(obj, context, evaluateNode);
1344
- if (chunkL23ZLSDQ_cjs.isSortByNode(obj)) return opSortBy(obj, context, evaluateNode);
1345
- if (chunkL23ZLSDQ_cjs.isAddNode(obj)) return opAdd(obj, context, evaluateNode);
1346
- if (chunkL23ZLSDQ_cjs.isSubNode(obj)) return opSub(obj, context, evaluateNode);
1347
- if (chunkL23ZLSDQ_cjs.isMulNode(obj)) return opMul(obj, context, evaluateNode);
1348
- if (chunkL23ZLSDQ_cjs.isDivNode(obj)) return opDiv(obj, context, evaluateNode);
1349
- if (chunkL23ZLSDQ_cjs.isRoundNode(obj)) return opRound(obj, context, evaluateNode);
1350
- if (chunkL23ZLSDQ_cjs.isModNode(obj)) return opMod(obj, context, evaluateNode);
1351
- if (chunkL23ZLSDQ_cjs.isToNumberNode(obj)) return opToNumber(obj, context, evaluateNode);
1352
- if (chunkL23ZLSDQ_cjs.isJoinNode(obj)) return opJoin(obj, context, evaluateNode);
1353
- if (chunkL23ZLSDQ_cjs.isToStringNode(obj)) return opToString(obj, context, evaluateNode);
1354
- if (chunkL23ZLSDQ_cjs.isInterpolateNode(obj)) return opInterpolate(obj, context, evaluateNode);
1355
- if (chunkL23ZLSDQ_cjs.isFillNode(obj)) return opFill(obj, context, evaluateNode);
1356
- if (chunkL23ZLSDQ_cjs.isTrimNode(obj)) return opTrim(obj, context, evaluateNode);
1357
- if (chunkL23ZLSDQ_cjs.isLowerNode(obj)) return opLower(obj, context, evaluateNode);
1358
- if (chunkL23ZLSDQ_cjs.isUpperNode(obj)) return opUpper(obj, context, evaluateNode);
1359
- if (chunkL23ZLSDQ_cjs.isSplitNode(obj)) return opSplit(obj, context, evaluateNode);
1360
- if (chunkL23ZLSDQ_cjs.isReplaceNode(obj)) return opReplace(obj, context, evaluateNode);
1361
- if (chunkL23ZLSDQ_cjs.isEqNode(obj)) return opEq(obj, context, evaluateNode);
1362
- if (chunkL23ZLSDQ_cjs.isNeqNode(obj)) return opNeq(obj, context, evaluateNode);
1363
- if (chunkL23ZLSDQ_cjs.isGtNode(obj)) return opGt(obj, context, evaluateNode);
1364
- if (chunkL23ZLSDQ_cjs.isGteNode(obj)) return opGte(obj, context, evaluateNode);
1365
- if (chunkL23ZLSDQ_cjs.isLtNode(obj)) return opLt(obj, context, evaluateNode);
1366
- if (chunkL23ZLSDQ_cjs.isLteNode(obj)) return opLte(obj, context, evaluateNode);
1367
- if (chunkL23ZLSDQ_cjs.isEmptyNode(obj)) return opEmpty(obj, context, evaluateNode);
1368
- if (chunkL23ZLSDQ_cjs.isStartsWithNode(obj)) return opStartsWith(obj, context, evaluateNode);
1369
- if (chunkL23ZLSDQ_cjs.isEndsWithNode(obj)) return opEndsWith(obj, context, evaluateNode);
1370
- if (chunkL23ZLSDQ_cjs.isContainsNode(obj)) return opContains(obj, context, evaluateNode);
1371
- if (chunkL23ZLSDQ_cjs.isNotNode(obj)) return opNot(obj, context, evaluateNode);
1372
- if (chunkL23ZLSDQ_cjs.isAndNode(obj)) return opAnd(obj, context, evaluateNode);
1373
- if (chunkL23ZLSDQ_cjs.isOrNode(obj)) return opOr(obj, context, evaluateNode);
1374
- if (chunkL23ZLSDQ_cjs.isMergeNode(obj)) return opMerge(obj, context, evaluateNode);
1375
- if (chunkL23ZLSDQ_cjs.isCoalesceNode(obj)) return opCoalesce(obj, context, evaluateNode);
1376
- if (chunkL23ZLSDQ_cjs.isCaseNode(obj)) return opCase(obj, context, evaluateNode);
1377
- if (chunkL23ZLSDQ_cjs.isEntriesOfNode(obj)) return opEntriesOf(obj, context, evaluateNode);
1378
- if (chunkL23ZLSDQ_cjs.isKeyByNode(obj)) return opKeyBy(obj, context, evaluateNode);
1379
- if (chunkL23ZLSDQ_cjs.isGroupByNode(obj)) return opGroupBy(obj, context, evaluateNode);
1380
- if (chunkL23ZLSDQ_cjs.isKeysNode(obj)) return opKeys(obj, context, evaluateNode);
1381
- if (chunkL23ZLSDQ_cjs.isValuesNode(obj)) return opValues(obj, context, evaluateNode);
1382
- if (chunkL23ZLSDQ_cjs.isFromEntriesNode(obj)) return opFromEntries(obj, context, evaluateNode);
1383
- if (chunkL23ZLSDQ_cjs.isPickNode(obj)) return opPick(obj, context, evaluateNode);
1384
- if (chunkL23ZLSDQ_cjs.isOmitNode(obj)) return opOmit(obj, context, evaluateNode);
1385
- if (chunkL23ZLSDQ_cjs.isTypeNode(obj)) return opType(obj, context, evaluateNode);
1386
- if (chunkL23ZLSDQ_cjs.isLengthNode(obj)) return opLength(obj, context, evaluateNode);
1387
- if (chunkL23ZLSDQ_cjs.isHasNode(obj)) return opHas(obj, context, evaluateNode);
1388
- if (chunkL23ZLSDQ_cjs.isRenameKeysNode(obj)) return opRenameKeys(obj, context, evaluateNode);
1389
- if (chunkL23ZLSDQ_cjs.isUpdateNode(obj)) return opUpdate(obj, context, evaluateNode);
1390
- if (chunkL23ZLSDQ_cjs.isAssertNode(obj)) return opAssert(obj, context, evaluateNode);
1391
- if (chunkL23ZLSDQ_cjs.isWalkNode(obj)) return opWalk(obj, context, evaluateNode);
1392
- if (chunkL23ZLSDQ_cjs.isDateNode(obj)) return opDate(obj, context, evaluateNode);
1393
- if (chunkL23ZLSDQ_cjs.isDateAddNode(obj)) return opDateAdd(obj, context, evaluateNode);
1394
- if (chunkL23ZLSDQ_cjs.isDateDiffNode(obj)) return opDateDiff(obj, context, evaluateNode);
1395
- if (chunkL23ZLSDQ_cjs.isLocaleDateNode(obj)) return opLocaleDate(obj, context, evaluateNode);
1396
- if (chunkL23ZLSDQ_cjs.isLocaleMoneyNode(obj)) return opLocaleMoney(obj, context, evaluateNode);
1397
- if (chunkL23ZLSDQ_cjs.isLocaleNumberNode(obj)) return opLocaleNumber(obj, context, evaluateNode);
1394
+ const handler = resolveHandler(obj);
1395
+ if (handler !== void 0) return handler(obj, context, evaluateNode);
1398
1396
  const unknownKeys = Object.keys(obj).filter((k) => k.startsWith("$"));
1399
1397
  const preview = JSON.stringify(obj).slice(0, 100);
1400
- return chunkL23ZLSDQ_cjs.failAt(
1401
- `No op answers this node: ${chunkL23ZLSDQ_cjs.clip(JSON.stringify(obj), 100)} (keys: ${unknownKeys.join(", ")}). The tree did not go through the schema.`,
1402
- chunkL23ZLSDQ_cjs.ErrorCode.NODE_SHAPE,
1398
+ return chunkVXU22DMV_cjs.failAt(
1399
+ `No op answers this node: ${chunkVXU22DMV_cjs.clip(JSON.stringify(obj), 100)} (keys: ${unknownKeys.join(", ")}). The tree did not go through the schema.`,
1400
+ chunkVXU22DMV_cjs.ErrorCode.NODE_SHAPE,
1403
1401
  { details: { keys: unknownKeys, preview } },
1404
1402
  { node: obj, form: false }
1405
1403
  );
1406
1404
  };
1407
- var notJson = (value, at) => {
1405
+ var notJson = (value, at, ancestors = /* @__PURE__ */ new Map()) => {
1408
1406
  if (value === null || typeof value === "string" || typeof value === "boolean") return void 0;
1409
1407
  if (typeof value === "number") return Number.isFinite(value) ? void 0 : `${at} is ${value}`;
1408
+ if (typeof value !== "object") return `${at} is ${value === void 0 ? "undefined" : `a ${typeof value}`}`;
1409
+ const loop = ancestors.get(value);
1410
+ if (loop !== void 0) return `${at} refers back to ${loop}`;
1411
+ ancestors.set(value, at);
1412
+ const found = notJsonInside(value, at, ancestors);
1413
+ ancestors.delete(value);
1414
+ return found;
1415
+ };
1416
+ var notJsonInside = (value, at, ancestors) => {
1410
1417
  if (Array.isArray(value)) {
1411
1418
  for (const index of Object.keys(value)) {
1412
- const found = notJson(value[Number(index)], `${at}[${index}]`);
1419
+ const found = notJson(value[Number(index)], `${at}[${index}]`, ancestors);
1413
1420
  if (found !== void 0) return found;
1414
1421
  }
1415
1422
  return void 0;
1416
1423
  }
1417
- if (typeof value !== "object") return `${at} is ${value === void 0 ? "undefined" : `a ${typeof value}`}`;
1418
1424
  const proto = Object.getPrototypeOf(value);
1419
1425
  if (proto !== Object.prototype && proto !== null) {
1420
1426
  const tag = Object.prototype.toString.call(value).slice(8, -1);
1421
1427
  return `${at} is ${tag === "Object" ? "an instance of a class" : `a ${tag}`}`;
1422
1428
  }
1423
1429
  for (const [key, inner] of Object.entries(value)) {
1424
- const found = notJson(inner, `${at}.${key}`);
1430
+ const found = notJson(inner, `${at}.${key}`, ancestors);
1425
1431
  if (found !== void 0) return found;
1426
1432
  }
1427
1433
  return void 0;
1428
1434
  };
1429
1435
  var checked = (config) => {
1430
- if (strata.exceedsDepth(config)) throw new chunkL23ZLSDQ_cjs.PrismError(`Invalid config: ${strata.depthRefusal()}`, chunkL23ZLSDQ_cjs.ErrorCode.SCHEMA, { details: { issues: [{ path: "root", message: strata.depthRefusal() }] } });
1431
- const parsed = chunkL23ZLSDQ_cjs.ConfigSchema.safeParse(config);
1436
+ if (strata.exceedsDepth(config)) throw new chunkVXU22DMV_cjs.PrismError(`Invalid config: ${strata.depthRefusal()}`, chunkVXU22DMV_cjs.ErrorCode.SCHEMA, { details: { issues: [{ path: "root", message: strata.depthRefusal() }] } });
1437
+ const parsed = chunkVXU22DMV_cjs.ConfigSchema.safeParse(config);
1432
1438
  if (!parsed.success) {
1433
1439
  const explained = explainIssues(parsed.error.issues, config);
1434
1440
  const issues = explained.map((i) => ({ path: i.path.join(".") || "root", message: i.message }));
1435
- throw new chunkL23ZLSDQ_cjs.PrismError(`Invalid config: ${issuesText(explained)}`, chunkL23ZLSDQ_cjs.ErrorCode.SCHEMA, { details: { issues } });
1441
+ throw new chunkVXU22DMV_cjs.PrismError(`Invalid config: ${issuesText(explained)}`, chunkVXU22DMV_cjs.ErrorCode.SCHEMA, { details: { issues } });
1436
1442
  }
1437
1443
  return desugar(parsed.data);
1438
1444
  };
@@ -1448,10 +1454,10 @@ var run = (tree, source, limits, kept, authored) => {
1448
1454
  }
1449
1455
  };
1450
1456
  var keptTrees = /* @__PURE__ */ new WeakMap();
1451
- var evaluate = (config, source, options) => {
1457
+ var evaluateOnce = (config, source, options) => {
1452
1458
  if (options?.check === "always") {
1453
1459
  const wrong = notJson(source, "source");
1454
- if (wrong !== void 0) throw new chunkL23ZLSDQ_cjs.PrismError(`The source must be plain JSON: ${wrong}.`, chunkL23ZLSDQ_cjs.ErrorCode.TYPE);
1460
+ if (wrong !== void 0) throw new chunkVXU22DMV_cjs.PrismError(`The source must be plain JSON: ${wrong}.`, chunkVXU22DMV_cjs.ErrorCode.TYPE);
1455
1461
  return run(checked(config), source, options.limits, false, config);
1456
1462
  }
1457
1463
  const input = source;
@@ -1461,11 +1467,18 @@ var evaluate = (config, source, options) => {
1461
1467
  kept = { tree: checked(config), optimized: false };
1462
1468
  keptTrees.set(config, kept);
1463
1469
  } else if (!kept.optimized) {
1464
- kept.tree = optimize(kept.tree, evaluateNode).node;
1470
+ kept.tree = optimize(kept.tree, evaluateNode, { recordFoldCost: true }).node;
1465
1471
  kept.optimized = true;
1466
1472
  }
1467
1473
  return run(kept.tree, input, options?.limits, true, config);
1468
1474
  };
1475
+ var evaluate = (config, source, options) => {
1476
+ try {
1477
+ return evaluateOnce(config, source, options);
1478
+ } catch (error) {
1479
+ throw stackRefusal(error);
1480
+ }
1481
+ };
1469
1482
  var evaluateSafe = (config, source, options) => {
1470
1483
  try {
1471
1484
  return { ok: true, data: evaluate(config, source, options) };
@@ -1486,7 +1499,7 @@ var walk = (node, stats, depth) => {
1486
1499
  for (const child of node) walk(child, stats, depth + 1);
1487
1500
  return;
1488
1501
  }
1489
- if (!chunkL23ZLSDQ_cjs.isJsonObject(node)) return;
1502
+ if (!chunkVXU22DMV_cjs.isJsonObject(node)) return;
1490
1503
  for (const key of Object.keys(node)) {
1491
1504
  if (key.startsWith("$")) {
1492
1505
  stats.opCount[key] = (stats.opCount[key] ?? 0) + 1;
@@ -1506,10 +1519,10 @@ var hashSha256 = async (data) => {
1506
1519
  return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
1507
1520
  };
1508
1521
  var compile = async (config, options) => {
1509
- if (strata.exceedsDepth(config)) throw new chunkL23ZLSDQ_cjs.PrismError(`Invalid config: ${strata.depthRefusal()}`, chunkL23ZLSDQ_cjs.ErrorCode.SCHEMA);
1510
- const parsed = chunkL23ZLSDQ_cjs.ConfigSchema.safeParse(config);
1522
+ if (strata.exceedsDepth(config)) throw new chunkVXU22DMV_cjs.PrismError(`Invalid config: ${strata.depthRefusal()}`, chunkVXU22DMV_cjs.ErrorCode.SCHEMA);
1523
+ const parsed = chunkVXU22DMV_cjs.ConfigSchema.safeParse(config);
1511
1524
  if (!parsed.success) {
1512
- throw new chunkL23ZLSDQ_cjs.PrismError(`Invalid config: ${issuesText(explainIssues(parsed.error.issues, config))}`, chunkL23ZLSDQ_cjs.ErrorCode.SCHEMA);
1525
+ throw new chunkVXU22DMV_cjs.PrismError(`Invalid config: ${issuesText(explainIssues(parsed.error.issues, config))}`, chunkVXU22DMV_cjs.ErrorCode.SCHEMA);
1513
1526
  }
1514
1527
  const desugared = desugar(parsed.data);
1515
1528
  const { node: core, stats: optimizations } = optimize(desugared, evaluateNode);
@@ -1562,12 +1575,12 @@ var execute = (ir, source, limits) => {
1562
1575
  return result;
1563
1576
  } catch (error) {
1564
1577
  placeError(error, core);
1565
- throw error;
1578
+ throw stackRefusal(error);
1566
1579
  }
1567
1580
  };
1568
1581
  var validate = (config) => {
1569
1582
  if (strata.exceedsDepth(config)) return { ok: false, issues: [{ path: [], message: strata.depthRefusal() }] };
1570
- const parsed = chunkL23ZLSDQ_cjs.ConfigSchema.safeParse(config);
1583
+ const parsed = chunkVXU22DMV_cjs.ConfigSchema.safeParse(config);
1571
1584
  if (!parsed.success) {
1572
1585
  return {
1573
1586
  ok: false,
@@ -1579,39 +1592,39 @@ var validate = (config) => {
1579
1592
 
1580
1593
  Object.defineProperty(exports, "MAPPING_OPS", {
1581
1594
  enumerable: true,
1582
- get: function () { return chunkDOCK3CEK_cjs.MAPPING_OPS; }
1595
+ get: function () { return chunkNBU7EBGN_cjs.MAPPING_OPS; }
1583
1596
  });
1584
1597
  Object.defineProperty(exports, "getConfigJsonSchema", {
1585
1598
  enumerable: true,
1586
- get: function () { return chunkDOCK3CEK_cjs.getConfigJsonSchema; }
1599
+ get: function () { return chunkNBU7EBGN_cjs.getConfigJsonSchema; }
1587
1600
  });
1588
1601
  Object.defineProperty(exports, "getNodeJsonSchema", {
1589
1602
  enumerable: true,
1590
- get: function () { return chunkDOCK3CEK_cjs.getNodeJsonSchema; }
1603
+ get: function () { return chunkNBU7EBGN_cjs.getNodeJsonSchema; }
1591
1604
  });
1592
1605
  Object.defineProperty(exports, "getProfileJsonSchema", {
1593
1606
  enumerable: true,
1594
- get: function () { return chunkDOCK3CEK_cjs.getProfileJsonSchema; }
1607
+ get: function () { return chunkNBU7EBGN_cjs.getProfileJsonSchema; }
1595
1608
  });
1596
1609
  Object.defineProperty(exports, "ConfigSchema", {
1597
1610
  enumerable: true,
1598
- get: function () { return chunkL23ZLSDQ_cjs.ConfigSchema; }
1611
+ get: function () { return chunkVXU22DMV_cjs.ConfigSchema; }
1599
1612
  });
1600
1613
  Object.defineProperty(exports, "ErrorCode", {
1601
1614
  enumerable: true,
1602
- get: function () { return chunkL23ZLSDQ_cjs.ErrorCode; }
1615
+ get: function () { return chunkVXU22DMV_cjs.ErrorCode; }
1603
1616
  });
1604
1617
  Object.defineProperty(exports, "NodeSchema", {
1605
1618
  enumerable: true,
1606
- get: function () { return chunkL23ZLSDQ_cjs.NodeSchema; }
1619
+ get: function () { return chunkVXU22DMV_cjs.NodeSchema; }
1607
1620
  });
1608
1621
  Object.defineProperty(exports, "OP_KEYS", {
1609
1622
  enumerable: true,
1610
- get: function () { return chunkL23ZLSDQ_cjs.OP_KEYS; }
1623
+ get: function () { return chunkVXU22DMV_cjs.OP_KEYS; }
1611
1624
  });
1612
1625
  Object.defineProperty(exports, "PrismError", {
1613
1626
  enumerable: true,
1614
- get: function () { return chunkL23ZLSDQ_cjs.PrismError; }
1627
+ get: function () { return chunkVXU22DMV_cjs.PrismError; }
1615
1628
  });
1616
1629
  exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
1617
1630
  exports.compile = compile;