@mono-lit/utility 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE.md +54 -0
  2. package/README.md +156 -2
  3. package/dist/app-roots-BJsIxzjk.d.ts +91 -0
  4. package/dist/app-roots-CvJnmXcs.js +128 -0
  5. package/dist/config-node-UzJrXg0Z.js +76 -0
  6. package/dist/config-node.d.ts +977 -0
  7. package/dist/config-node.js +7 -0
  8. package/dist/config.d.ts +2 -0
  9. package/dist/config.js +3 -0
  10. package/dist/create-config-D3m6xTaQ.d.ts +733 -0
  11. package/dist/create-config-DdL3Fh6T.js +357 -0
  12. package/dist/fetching.d.ts +239 -0
  13. package/dist/fetching.js +867 -0
  14. package/dist/generate-CJ7MtcDd.js +291 -0
  15. package/dist/index-C2hZeNkq.d.ts +365 -0
  16. package/dist/index-ClrZbU7n.d.ts +518 -0
  17. package/dist/index.d.ts +29 -0
  18. package/dist/index.js +939 -0
  19. package/dist/merge-file-C5nzi_MY.d.ts +122 -0
  20. package/dist/merge-file-CtyKTu5L.js +133 -0
  21. package/dist/mock-db-5mJTObSC.js +1282 -0
  22. package/dist/mock-db.d.ts +2 -0
  23. package/dist/mock-db.js +4 -0
  24. package/dist/mono-alias-DNDm-jB_.js +508 -0
  25. package/dist/mono-clone.mjs +958 -0
  26. package/dist/mono-db.d.ts +1 -0
  27. package/dist/mono-db.js +151 -0
  28. package/dist/mono-env.mjs +231 -0
  29. package/dist/mono-git.mjs +798 -0
  30. package/dist/mono-link-YlOQ2PVS.js +488 -0
  31. package/dist/mono-prepare.d.ts +1 -0
  32. package/dist/mono-prepare.js +27 -0
  33. package/dist/mono-skills.d.ts +1 -0
  34. package/dist/mono-skills.js +830 -0
  35. package/dist/mono-tsconfig-D2qRL9_R.js +204 -0
  36. package/dist/mono.mjs +34 -0
  37. package/dist/nuxt-layers-DP1m7f1-.js +176 -0
  38. package/dist/nuxt-layers.d.ts +34 -0
  39. package/dist/nuxt-layers.js +3 -0
  40. package/dist/nuxt-runtime.d.ts +18 -0
  41. package/dist/nuxt-runtime.js +102 -0
  42. package/dist/nuxt.d.ts +386 -0
  43. package/dist/nuxt.js +590 -0
  44. package/dist/runtime-C_IWNrAG.js +5817 -0
  45. package/dist/runtime.d.ts +2583 -0
  46. package/dist/runtime.js +4 -0
  47. package/dist/session-Bk985AIM.js +1721 -0
  48. package/dist/types-B6FdB7LJ.d.ts +57 -0
  49. package/dist/universal-B2eD9xho.d.ts +97 -0
  50. package/dist/universal-BNTo_83u.js +599 -0
  51. package/dist/virtual-mono-apps.d.ts +16 -0
  52. package/dist/vite.d.ts +940 -0
  53. package/dist/vite.js +1132 -0
  54. package/package.json +141 -3
@@ -0,0 +1,1282 @@
1
+ import { i as matchMockRoute, n as generateSeed, s as parseMockSchema } from "./generate-CJ7MtcDd.js";
2
+
3
+ //#region pkg/mock-db/split.ts
4
+ /**
5
+ * Split `input` on `separator`, but only at nesting depth 0 and outside quotes.
6
+ *
7
+ * @example
8
+ * splitTopLevel("A($select=x,y),B", ',') -> ["A($select=x,y)", "B"]
9
+ */
10
+ function splitTopLevel(input, separator = ",") {
11
+ const parts = [];
12
+ let depth = 0;
13
+ let current = "";
14
+ let quote = null;
15
+ for (const char of String(input ?? "")) {
16
+ if (quote) {
17
+ current += char;
18
+ if (char === quote) quote = null;
19
+ continue;
20
+ }
21
+ if (char === "'" || char === "\"") {
22
+ quote = char;
23
+ current += char;
24
+ continue;
25
+ }
26
+ if (char === "(") depth++;
27
+ if (char === ")") depth--;
28
+ if (char === separator && depth === 0) {
29
+ parts.push(current.trim());
30
+ current = "";
31
+ continue;
32
+ }
33
+ current += char;
34
+ }
35
+ if (current.trim()) parts.push(current.trim());
36
+ return parts;
37
+ }
38
+ /** The body between the outermost parens of `name(...)`, or null if it isn't one. */
39
+ function readCall(segment, name) {
40
+ const trimmed = segment.trim();
41
+ if (!trimmed.toLowerCase().startsWith(`${name.toLowerCase()}(`)) return null;
42
+ if (!trimmed.endsWith(")")) throw new Error(`unbalanced parentheses in "${segment}"`);
43
+ return trimmed.slice(name.length + 1, -1);
44
+ }
45
+
46
+ //#endregion
47
+ //#region pkg/mock-db/apply.ts
48
+ /** Split the pipeline on `/`, but only at depth 0 so `groupby((A),aggregate(...))` stays whole. */
49
+ function splitSegments(input) {
50
+ return splitTopLevel(input, "/");
51
+ }
52
+ const METHODS = [
53
+ "sum",
54
+ "average",
55
+ "min",
56
+ "max",
57
+ "count",
58
+ "countdistinct"
59
+ ];
60
+ /** `Price with sum as Total` | `$count as Rows`. */
61
+ function parseAggregateSpec(input) {
62
+ const text = input.trim();
63
+ const countMatch = /^\$count\s+as\s+([A-Za-z0-9_$]+)$/i.exec(text);
64
+ if (countMatch) return {
65
+ method: "count",
66
+ alias: countMatch[1]
67
+ };
68
+ const match = /^([A-Za-z0-9_$/]+)\s+with\s+([A-Za-z]+)\s+as\s+([A-Za-z0-9_$]+)$/i.exec(text);
69
+ if (!match) throw new Error(`$apply: cannot parse aggregate "${text}" — expected "Field with sum as Alias" or "$count as Alias"`);
70
+ const method = match[2].toLowerCase();
71
+ if (!METHODS.includes(method)) throw new Error(`$apply: unsupported aggregate method "${match[2]}" (expected ${METHODS.join(" | ")})`);
72
+ return {
73
+ field: match[1],
74
+ method,
75
+ alias: match[3]
76
+ };
77
+ }
78
+ function parseApply(input) {
79
+ return splitSegments(input).map((segment) => {
80
+ if (/^identity$/i.test(segment)) return { kind: "identity" };
81
+ const filterBody = readCall(segment, "filter");
82
+ if (filterBody != null) return {
83
+ kind: "filter",
84
+ expression: filterBody
85
+ };
86
+ const aggregateBody = readCall(segment, "aggregate");
87
+ if (aggregateBody != null) return {
88
+ kind: "aggregate",
89
+ aggregates: splitTopLevel(aggregateBody).map(parseAggregateSpec)
90
+ };
91
+ const groupBody = readCall(segment, "groupby");
92
+ if (groupBody != null) {
93
+ const args = splitTopLevel(groupBody);
94
+ const fieldList = (args[0] ?? "").trim();
95
+ if (!fieldList.startsWith("(") || !fieldList.endsWith(")")) throw new Error(`$apply: groupby needs a parenthesised property list, e.g. groupby((Category))`);
96
+ const fields = splitTopLevel(fieldList.slice(1, -1)).map((field) => field.trim()).filter(Boolean);
97
+ if (!fields.length) throw new Error("$apply: groupby needs at least one property");
98
+ let aggregates = [];
99
+ const rest = args.slice(1).join(",").trim();
100
+ if (rest) {
101
+ const inner = readCall(rest, "aggregate");
102
+ if (inner == null) throw new Error(`$apply: only aggregate(...) is supported inside groupby, got "${rest}"`);
103
+ aggregates = splitTopLevel(inner).map(parseAggregateSpec);
104
+ }
105
+ return {
106
+ kind: "groupby",
107
+ fields,
108
+ aggregates
109
+ };
110
+ }
111
+ throw new Error(`$apply: unsupported transformation "${segment}" (supported: filter, groupby, aggregate, identity)`);
112
+ });
113
+ }
114
+ /** Case-insensitive flat read — the fallback when no path-aware reader is injected. */
115
+ function readField$1(row, name) {
116
+ if (name in row) return row[name];
117
+ const lower = name.toLowerCase();
118
+ const hit = Object.keys(row).find((key) => key.toLowerCase() === lower);
119
+ return hit ? row[hit] : void 0;
120
+ }
121
+ function computeAggregate(rows, spec, read) {
122
+ if (spec.method === "count") return rows.length;
123
+ const values = rows.map((row) => read(row, spec.field)).filter((value) => value !== void 0 && value !== null);
124
+ if (spec.method === "countdistinct") return new Set(values.map((value) => JSON.stringify(value))).size;
125
+ const numbers = values.map(Number).filter((value) => !Number.isNaN(value));
126
+ if (!numbers.length) return spec.method === "sum" ? 0 : null;
127
+ switch (spec.method) {
128
+ case "sum": return numbers.reduce((total, value) => total + value, 0);
129
+ case "average": return numbers.reduce((total, value) => total + value, 0) / numbers.length;
130
+ case "min": return Math.min(...numbers);
131
+ case "max": return Math.max(...numbers);
132
+ default: return null;
133
+ }
134
+ }
135
+ /** Stable group key for a set of fields (each may be a navigation path). */
136
+ function groupKeyOf(row, fields, read) {
137
+ return JSON.stringify(fields.map((field) => read(row, field) ?? null));
138
+ }
139
+ /** Run the pipeline. Each transform's output feeds the next. */
140
+ function applyTransforms(rows, transforms, compileFilter, readValue = readField$1) {
141
+ const read = readValue;
142
+ let current = [...rows];
143
+ for (const transform of transforms) switch (transform.kind) {
144
+ case "identity": break;
145
+ case "filter": {
146
+ const predicate = compileFilter(transform.expression);
147
+ current = current.filter(predicate);
148
+ break;
149
+ }
150
+ case "aggregate": {
151
+ const single = {};
152
+ for (const spec of transform.aggregates) single[spec.alias] = computeAggregate(current, spec, read);
153
+ current = [single];
154
+ break;
155
+ }
156
+ case "groupby": {
157
+ const groups = /* @__PURE__ */ new Map();
158
+ for (const row of current) {
159
+ const key = groupKeyOf(row, transform.fields, read);
160
+ const bucket = groups.get(key);
161
+ if (bucket) bucket.push(row);
162
+ else groups.set(key, [row]);
163
+ }
164
+ current = [...groups.values()].map((bucket) => {
165
+ const out = {};
166
+ for (const field of transform.fields) out[field] = read(bucket[0], field) ?? null;
167
+ for (const spec of transform.aggregates) out[spec.alias] = computeAggregate(bucket, spec, read);
168
+ return out;
169
+ });
170
+ break;
171
+ }
172
+ }
173
+ return current;
174
+ }
175
+
176
+ //#endregion
177
+ //#region pkg/mock-db/odata.ts
178
+ const OPERATORS = new Set([
179
+ "eq",
180
+ "ne",
181
+ "gt",
182
+ "ge",
183
+ "lt",
184
+ "le",
185
+ "and",
186
+ "or",
187
+ "not",
188
+ "in"
189
+ ]);
190
+ function tokenize(input) {
191
+ const tokens = [];
192
+ const source = String(input ?? "");
193
+ let i = 0;
194
+ while (i < source.length) {
195
+ const char = source[i];
196
+ if (/\s/.test(char)) {
197
+ i++;
198
+ continue;
199
+ }
200
+ if (char === "(" || char === ")") {
201
+ tokens.push({
202
+ type: "paren",
203
+ value: char
204
+ });
205
+ i++;
206
+ continue;
207
+ }
208
+ if (char === "/") {
209
+ tokens.push({
210
+ type: "path",
211
+ value: char
212
+ });
213
+ i++;
214
+ continue;
215
+ }
216
+ if (char === ":") {
217
+ tokens.push({
218
+ type: "colon",
219
+ value: char
220
+ });
221
+ i++;
222
+ continue;
223
+ }
224
+ if (char === ",") {
225
+ tokens.push({
226
+ type: "comma",
227
+ value: char
228
+ });
229
+ i++;
230
+ continue;
231
+ }
232
+ if (char === "'" || char === "\"") {
233
+ const quote = char;
234
+ let value = "";
235
+ i++;
236
+ while (i < source.length) {
237
+ if (source[i] === quote) {
238
+ if (source[i + 1] === quote) {
239
+ value += quote;
240
+ i += 2;
241
+ continue;
242
+ }
243
+ break;
244
+ }
245
+ value += source[i];
246
+ i++;
247
+ }
248
+ if (source[i] !== quote) throw new Error(`$filter: unterminated string near "${value}"`);
249
+ i++;
250
+ tokens.push({
251
+ type: "string",
252
+ value
253
+ });
254
+ continue;
255
+ }
256
+ if (/[0-9]/.test(char) || char === "-" && /[0-9]/.test(source[i + 1] ?? "")) {
257
+ const iso = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})?)?/.exec(source.slice(i));
258
+ if (iso) {
259
+ tokens.push({
260
+ type: "date",
261
+ value: iso[0]
262
+ });
263
+ i += iso[0].length;
264
+ continue;
265
+ }
266
+ let value = "";
267
+ if (char === "-") {
268
+ value += "-";
269
+ i++;
270
+ }
271
+ while (i < source.length && /[0-9.]/.test(source[i])) {
272
+ value += source[i];
273
+ i++;
274
+ }
275
+ tokens.push({
276
+ type: "number",
277
+ value
278
+ });
279
+ continue;
280
+ }
281
+ if (/[A-Za-z_$]/.test(char)) {
282
+ let value = "";
283
+ while (i < source.length && /[A-Za-z0-9_$.]/.test(source[i])) {
284
+ value += source[i];
285
+ i++;
286
+ }
287
+ const lower = value.toLowerCase();
288
+ tokens.push({
289
+ type: OPERATORS.has(lower) ? "op" : "ident",
290
+ value: OPERATORS.has(lower) ? lower : value
291
+ });
292
+ continue;
293
+ }
294
+ throw new Error(`$filter: unexpected character "${char}" at ${i}`);
295
+ }
296
+ tokens.push({
297
+ type: "eof",
298
+ value: ""
299
+ });
300
+ return tokens;
301
+ }
302
+ /**
303
+ * Recursive descent, lowest precedence first:
304
+ * or -> and -> not -> comparison -> primary
305
+ * so `a eq 1 and b eq 2 or c eq 3` parses as `((a eq 1 and b eq 2) or c eq 3)`.
306
+ */
307
+ function parseFilter(input) {
308
+ const tokens = tokenize(input);
309
+ let pos = 0;
310
+ const peek = () => tokens[pos];
311
+ const next = () => tokens[pos++];
312
+ function expect(type, value) {
313
+ const token = next();
314
+ if (token.type !== type || value !== void 0 && token.value !== value) throw new Error(`$filter: expected ${value ?? type} but found "${token.value || "end of input"}"`);
315
+ return token;
316
+ }
317
+ function parseOr() {
318
+ let left = parseAnd();
319
+ while (peek().type === "op" && peek().value === "or") {
320
+ next();
321
+ left = {
322
+ kind: "logical",
323
+ op: "or",
324
+ left,
325
+ right: parseAnd()
326
+ };
327
+ }
328
+ return left;
329
+ }
330
+ function parseAnd() {
331
+ let left = parseNot();
332
+ while (peek().type === "op" && peek().value === "and") {
333
+ next();
334
+ left = {
335
+ kind: "logical",
336
+ op: "and",
337
+ left,
338
+ right: parseNot()
339
+ };
340
+ }
341
+ return left;
342
+ }
343
+ function parseNot() {
344
+ if (peek().type === "op" && peek().value === "not") {
345
+ next();
346
+ return {
347
+ kind: "not",
348
+ operand: parseNot()
349
+ };
350
+ }
351
+ return parseComparison();
352
+ }
353
+ function parseComparison() {
354
+ const left = parsePrimary();
355
+ const token = peek();
356
+ if (token.type === "op" && [
357
+ "eq",
358
+ "ne",
359
+ "gt",
360
+ "ge",
361
+ "lt",
362
+ "le"
363
+ ].includes(token.value)) {
364
+ next();
365
+ const right = parsePrimary();
366
+ return {
367
+ kind: "compare",
368
+ op: token.value,
369
+ left,
370
+ right
371
+ };
372
+ }
373
+ if (token.type === "op" && token.value === "in") {
374
+ next();
375
+ expect("paren", "(");
376
+ const values = [];
377
+ if (!(peek().type === "paren" && peek().value === ")")) {
378
+ values.push(parsePrimary());
379
+ while (peek().type === "comma") {
380
+ next();
381
+ values.push(parsePrimary());
382
+ }
383
+ }
384
+ expect("paren", ")");
385
+ return {
386
+ kind: "in",
387
+ left,
388
+ values
389
+ };
390
+ }
391
+ return left;
392
+ }
393
+ function parsePrimary() {
394
+ const token = peek();
395
+ if (token.type === "paren" && token.value === "(") {
396
+ next();
397
+ const inner = parseOr();
398
+ if (peek().type === "comma") throw new Error("$filter: a value list \"(a,b,c)\" cannot be the left operand. The OData v4 form is \"Field in (1,2,3)\", not \"(1,2,3) in 'Field'\".");
399
+ expect("paren", ")");
400
+ return inner;
401
+ }
402
+ if (token.type === "string") {
403
+ next();
404
+ return {
405
+ kind: "literal",
406
+ value: token.value
407
+ };
408
+ }
409
+ if (token.type === "number") {
410
+ next();
411
+ return {
412
+ kind: "literal",
413
+ value: Number(token.value)
414
+ };
415
+ }
416
+ if (token.type === "date") {
417
+ next();
418
+ return {
419
+ kind: "literal",
420
+ value: token.value
421
+ };
422
+ }
423
+ if (token.type === "ident") {
424
+ next();
425
+ if (peek().type === "paren" && peek().value === "(") {
426
+ next();
427
+ const args = [];
428
+ if (!(peek().type === "paren" && peek().value === ")")) {
429
+ args.push(parseOr());
430
+ while (peek().type === "comma") {
431
+ next();
432
+ args.push(parseOr());
433
+ }
434
+ }
435
+ expect("paren", ")");
436
+ return {
437
+ kind: "call",
438
+ name: token.value.toLowerCase(),
439
+ args
440
+ };
441
+ }
442
+ if (peek().type === "path") {
443
+ const segments = [token.value];
444
+ while (peek().type === "path") {
445
+ next();
446
+ const segment = next();
447
+ if (segment.type !== "ident") throw new Error(`$filter: expected a property after "/" but found "${segment.value}"`);
448
+ segments.push(segment.value);
449
+ }
450
+ const last = segments[segments.length - 1].toLowerCase();
451
+ if ((last === "any" || last === "all") && peek().type === "paren" && peek().value === "(") {
452
+ next();
453
+ if (peek().type === "paren" && peek().value === ")") {
454
+ next();
455
+ return {
456
+ kind: "lambda",
457
+ op: last,
458
+ nav: segments.slice(0, -1),
459
+ variable: "",
460
+ predicate: {
461
+ kind: "literal",
462
+ value: true
463
+ }
464
+ };
465
+ }
466
+ const variable = next();
467
+ if (variable.type !== "ident" || peek().type !== "colon") throw new Error(`$filter: ${last}() needs a range variable — the form is "${segments.slice(0, -1).join("/") || "Nav"}/${last}(d: d/Field eq 1)". Found "${variable.value}${peek().value}".`);
468
+ expect("colon");
469
+ const predicate = parseOr();
470
+ expect("paren", ")");
471
+ return {
472
+ kind: "lambda",
473
+ op: last,
474
+ nav: segments.slice(0, -1),
475
+ variable: variable.value,
476
+ predicate
477
+ };
478
+ }
479
+ return {
480
+ kind: "path",
481
+ segments
482
+ };
483
+ }
484
+ const lower = token.value.toLowerCase();
485
+ if (lower === "true") return {
486
+ kind: "literal",
487
+ value: true
488
+ };
489
+ if (lower === "false") return {
490
+ kind: "literal",
491
+ value: false
492
+ };
493
+ if (lower === "null") return {
494
+ kind: "literal",
495
+ value: null
496
+ };
497
+ return {
498
+ kind: "field",
499
+ name: token.value
500
+ };
501
+ }
502
+ throw new Error(`$filter: unexpected "${token.value || "end of input"}"`);
503
+ }
504
+ const ast = parseOr();
505
+ if (peek().type !== "eof") throw new Error(`$filter: unexpected trailing "${peek().value}"`);
506
+ return ast;
507
+ }
508
+ /** Case-insensitive field lookup, so `name` matches a `Name` column. */
509
+ function readField(row, name) {
510
+ if (name in row) return row[name];
511
+ const lower = name.toLowerCase();
512
+ const hit = Object.keys(row).find((key) => key.toLowerCase() === lower);
513
+ return hit ? row[hit] : void 0;
514
+ }
515
+ /** An ISO-ish date string, or a Date. */
516
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}|$)/;
517
+ function asTimestamp(value) {
518
+ if (value instanceof Date) return value.getTime();
519
+ if (typeof value === "string" && ISO_DATE.test(value)) {
520
+ const time = Date.parse(value);
521
+ return Number.isNaN(time) ? null : time;
522
+ }
523
+ return null;
524
+ }
525
+ function compareValues(op, left, right) {
526
+ if (left == null || right == null) {
527
+ if (op === "eq") return left == null && right == null;
528
+ if (op === "ne") return !(left == null && right == null);
529
+ return false;
530
+ }
531
+ const leftTime = asTimestamp(left);
532
+ const rightTime = asTimestamp(right);
533
+ if (leftTime != null && rightTime != null) switch (op) {
534
+ case "eq": return leftTime === rightTime;
535
+ case "ne": return leftTime !== rightTime;
536
+ case "gt": return leftTime > rightTime;
537
+ case "ge": return leftTime >= rightTime;
538
+ case "lt": return leftTime < rightTime;
539
+ case "le": return leftTime <= rightTime;
540
+ default: return false;
541
+ }
542
+ const numeric = typeof left === "number" || typeof right === "number";
543
+ const a = numeric ? Number(left) : String(left);
544
+ const b = numeric ? Number(right) : String(right);
545
+ switch (op) {
546
+ case "eq": return a === b;
547
+ case "ne": return a !== b;
548
+ case "gt": return a > b;
549
+ case "ge": return a >= b;
550
+ case "lt": return a < b;
551
+ case "le": return a <= b;
552
+ default: return false;
553
+ }
554
+ }
555
+ /**
556
+ * Resolve `A/B` against a row: a materialised value if the row already carries one
557
+ * (an `$expand`ed relation), otherwise the declared relation, joined on demand.
558
+ */
559
+ function resolvePath(segments, row, context) {
560
+ const head = segments[0];
561
+ const bound = context.scope?.[head];
562
+ let current = bound !== void 0 ? bound : void 0;
563
+ let rest = bound !== void 0 ? segments.slice(1) : segments;
564
+ let entity = bound !== void 0 ? void 0 : context.entity;
565
+ if (current === void 0) current = row;
566
+ for (const segment of rest) {
567
+ if (current == null) return void 0;
568
+ if (segment === "$count") return Array.isArray(current) ? current.length : current == null ? 0 : 1;
569
+ const direct = Array.isArray(current) ? void 0 : readField(current, segment);
570
+ if (direct !== void 0) {
571
+ current = direct;
572
+ entity = void 0;
573
+ continue;
574
+ }
575
+ const field = entity?.relations.find((candidate) => candidate.name.toLowerCase() === segment.toLowerCase());
576
+ if (!field?.relation || !context.readEntity) return void 0;
577
+ const relation = field.relation;
578
+ const localValue = readField(current, relation.localField);
579
+ const matches = context.readEntity(relation.targetEntity).filter((target) => keyEquals(readField(target, relation.targetKey), localValue));
580
+ current = relation.kind === "array" ? matches : matches[0] ?? null;
581
+ entity = void 0;
582
+ }
583
+ return current;
584
+ }
585
+ function evaluateNode(node, row, context) {
586
+ switch (node.kind) {
587
+ case "literal": return node.value;
588
+ case "field": {
589
+ const bound = context.scope?.[node.name];
590
+ if (bound !== void 0) return bound;
591
+ return readField(row, node.name);
592
+ }
593
+ case "path": return resolvePath(node.segments, row, context);
594
+ case "lambda": {
595
+ const collection = node.nav.length ? resolvePath(node.nav, row, context) : row;
596
+ const items = Array.isArray(collection) ? collection : collection == null ? [] : [collection];
597
+ const test = (item) => Boolean(evaluateNode(node.predicate, row, {
598
+ ...context,
599
+ scope: {
600
+ ...context.scope ?? {},
601
+ [node.variable]: item
602
+ }
603
+ }));
604
+ return node.op === "any" ? items.some(test) : items.every(test);
605
+ }
606
+ case "in": {
607
+ const left = evaluateNode(node.left, row, context);
608
+ return node.values.some((value) => compareValues("eq", left, evaluateNode(value, row, context)));
609
+ }
610
+ case "not": return !evaluateNode(node.operand, row, context);
611
+ case "logical": {
612
+ const left = Boolean(evaluateNode(node.left, row, context));
613
+ if (node.op === "and") return left && Boolean(evaluateNode(node.right, row, context));
614
+ return left || Boolean(evaluateNode(node.right, row, context));
615
+ }
616
+ case "compare": return compareValues(node.op, evaluateNode(node.left, row, context), evaluateNode(node.right, row, context));
617
+ case "call": {
618
+ const args = node.args.map((arg) => evaluateNode(arg, row, context));
619
+ const text = (value) => String(value ?? "");
620
+ switch (node.name) {
621
+ case "contains": return text(args[0]).toLowerCase().includes(text(args[1]).toLowerCase());
622
+ case "startswith": return text(args[0]).toLowerCase().startsWith(text(args[1]).toLowerCase());
623
+ case "endswith": return text(args[0]).toLowerCase().endsWith(text(args[1]).toLowerCase());
624
+ case "tolower": return text(args[0]).toLowerCase();
625
+ case "toupper": return text(args[0]).toUpperCase();
626
+ case "trim": return text(args[0]).trim();
627
+ case "length": return text(args[0]).length;
628
+ case "concat": return args.map(text).join("");
629
+ case "indexof": return text(args[0]).indexOf(text(args[1]));
630
+ case "year":
631
+ case "month":
632
+ case "day":
633
+ case "hour":
634
+ case "minute":
635
+ case "second": {
636
+ const time = asTimestamp(args[0]);
637
+ if (time == null) return null;
638
+ const date = new Date(time);
639
+ switch (node.name) {
640
+ case "year": return date.getUTCFullYear();
641
+ case "month": return date.getUTCMonth() + 1;
642
+ case "day": return date.getUTCDate();
643
+ case "hour": return date.getUTCHours();
644
+ case "minute": return date.getUTCMinutes();
645
+ default: return date.getUTCSeconds();
646
+ }
647
+ }
648
+ case "now": return (/* @__PURE__ */ new Date()).toISOString();
649
+ case "substring": return args.length > 2 ? text(args[0]).substr(Number(args[1]), Number(args[2])) : text(args[0]).substring(Number(args[1]));
650
+ case "substringof": return text(args[1]).toLowerCase().includes(text(args[0]).toLowerCase());
651
+ default: throw new Error(`$filter: unsupported function "${node.name}()"`);
652
+ }
653
+ }
654
+ }
655
+ }
656
+ function evaluateFilter(node, row, context = {}) {
657
+ return Boolean(evaluateNode(node, row, context));
658
+ }
659
+ /** A bare name, an already-parsed item, or a string carrying nested options. */
660
+ function normalizeExpand(input) {
661
+ return input.flatMap((item) => typeof item === "string" ? parseExpand(item) : [item]);
662
+ }
663
+ /** `Field desc, Other` -> orderby rules. */
664
+ function parseOrderBy(input) {
665
+ return splitTopLevel(input, ",").map((part) => part.trim()).filter(Boolean).map((part) => {
666
+ const [field, direction] = part.split(/\s+/);
667
+ return {
668
+ field,
669
+ desc: String(direction ?? "").toLowerCase() === "desc"
670
+ };
671
+ });
672
+ }
673
+ /**
674
+ * Parse an `$expand` value into a tree.
675
+ *
676
+ * Tolerates everything the real app emits: embedded newlines/tabs, spaces after
677
+ * commas (`Feature($select=Id, Nama)`), a stray trailing `;`
678
+ * (`BudgetAlokasi($select=…;)`), and a single string holding several comma-separated
679
+ * expands.
680
+ */
681
+ function parseExpand(input) {
682
+ return splitTopLevel(Array.isArray(input) ? input.join(",") : String(input ?? ""), ",").map((part) => part.trim()).filter(Boolean).map((part) => {
683
+ const open = part.indexOf("(");
684
+ if (open < 0) return { name: part.trim() };
685
+ const name = part.slice(0, open).trim();
686
+ const body = part.slice(open + 1, part.lastIndexOf(")"));
687
+ const item = { name };
688
+ for (const option of splitTopLevel(body, ";")) {
689
+ const at = option.indexOf("=");
690
+ if (at < 0) continue;
691
+ const key = option.slice(0, at).trim().toLowerCase();
692
+ const value = option.slice(at + 1).trim();
693
+ if (!value) continue;
694
+ switch (key) {
695
+ case "$select":
696
+ item.select = splitTopLevel(value, ",").map((s) => s.trim()).filter(Boolean);
697
+ break;
698
+ case "$filter":
699
+ item.filter = value;
700
+ break;
701
+ case "$orderby":
702
+ item.orderby = parseOrderBy(value);
703
+ break;
704
+ case "$top":
705
+ item.top = Number(value);
706
+ break;
707
+ case "$skip":
708
+ item.skip = Number(value);
709
+ break;
710
+ case "$expand":
711
+ item.expand = parseExpand(value);
712
+ break;
713
+ default: break;
714
+ }
715
+ }
716
+ return item;
717
+ });
718
+ }
719
+ /** Read OData options off a query string or a param object (DevExtreme sends both shapes). */
720
+ function parseQuery(input) {
721
+ const params = /* @__PURE__ */ new Map();
722
+ if (typeof input === "string") {
723
+ const search = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
724
+ for (const [key, value] of new URLSearchParams(search)) params.set(key.toLowerCase(), value);
725
+ } else for (const [key, value] of Object.entries(input ?? {})) if (value !== void 0 && value !== null) params.set(key.toLowerCase(), String(value));
726
+ const query = {};
727
+ const apply = params.get("$apply");
728
+ if (apply) query.apply = apply;
729
+ const filter = params.get("$filter");
730
+ if (filter) query.filter = filter;
731
+ const select = params.get("$select");
732
+ if (select) query.select = select.split(",").map((s) => s.trim()).filter(Boolean);
733
+ const expand = params.get("$expand");
734
+ if (expand) query.expand = parseExpand(expand);
735
+ const orderby = params.get("$orderby");
736
+ if (orderby) query.orderby = parseOrderBy(orderby);
737
+ const top = params.get("$top");
738
+ if (top != null && top !== "") query.top = Number(top);
739
+ const skip = params.get("$skip");
740
+ if (skip != null && skip !== "") query.skip = Number(skip);
741
+ if (String(params.get("$count") ?? "").toLowerCase() === "true") query.count = true;
742
+ return query;
743
+ }
744
+ /**
745
+ * Run a query over an entity's rows.
746
+ *
747
+ * Order matters and is the usual source of off-by-one bugs: filter first, take
748
+ * the count from the FILTERED set, then page, then expand, then select. Counting
749
+ * before filtering (or after paging) is the classic way to break a grid's pager.
750
+ */
751
+ function executeQuery(rows, query, context) {
752
+ let out = [...rows];
753
+ const filterContext = context ? {
754
+ entity: context.entity,
755
+ readEntity: context.readEntity
756
+ } : {};
757
+ if (query.apply) out = applyTransforms(out, parseApply(query.apply), (expression) => {
758
+ const ast = parseFilter(expression);
759
+ return (row) => evaluateFilter(ast, row, filterContext);
760
+ }, (row, field) => field.includes("/") ? resolvePath(field.split("/"), row, filterContext) : readField(row, field));
761
+ if (query.filter) {
762
+ const ast = parseFilter(query.filter);
763
+ out = out.filter((row) => evaluateFilter(ast, row, filterContext));
764
+ }
765
+ const total = out.length;
766
+ if (query.orderby?.length) {
767
+ const rules = query.orderby;
768
+ out.sort((a, b) => {
769
+ for (const rule of rules) {
770
+ const left = readField(a, rule.field);
771
+ const right = readField(b, rule.field);
772
+ if (left === right) continue;
773
+ if (left == null) return rule.desc ? 1 : -1;
774
+ if (right == null) return rule.desc ? -1 : 1;
775
+ const cmp = typeof left === "number" && typeof right === "number" ? left - right : String(left).localeCompare(String(right));
776
+ if (cmp !== 0) return rule.desc ? -cmp : cmp;
777
+ }
778
+ return 0;
779
+ });
780
+ }
781
+ const skip = Number(query.skip ?? 0);
782
+ if (skip > 0) out = out.slice(skip);
783
+ if (query.top != null && !Number.isNaN(query.top)) out = out.slice(0, query.top);
784
+ if (query.expand?.length && context) {
785
+ const items = normalizeExpand(query.expand);
786
+ out = out.map((row) => expandRow(row, items, context));
787
+ }
788
+ if (query.select?.length) {
789
+ const fields = query.select;
790
+ out = out.map((row) => {
791
+ const picked = {};
792
+ for (const field of fields) {
793
+ const value = readField(row, field);
794
+ if (value !== void 0) picked[field] = value;
795
+ }
796
+ return picked;
797
+ });
798
+ }
799
+ return {
800
+ rows: out,
801
+ total
802
+ };
803
+ }
804
+ /**
805
+ * Are two relation keys the same row?
806
+ *
807
+ * Strictly equal, or equal as strings — so a `"1"` foreign key still joins a `1`
808
+ * primary key. That mismatch is the common case, not an exotic one: JSON seed
809
+ * files, url path segments and select-box values all hand back string keys while
810
+ * the primary key is numeric. A strict `===` join returned `null`/`[]` for those
811
+ * with no error at all, which is the worst way to be wrong.
812
+ *
813
+ * Compared as STRINGS, never coerced to numbers: `Number('007') === Number('7')`
814
+ * would join two genuinely different keys.
815
+ *
816
+ * A null/undefined key joins NOTHING — otherwise `undefined === undefined` makes a
817
+ * row with a missing FK match every target row with a missing key.
818
+ */
819
+ function keyEquals(a, b) {
820
+ if (a == null || b == null) return false;
821
+ return a === b || String(a) === String(b);
822
+ }
823
+ /** Materialise the requested relations for one row, honouring each item's nested options. */
824
+ function expandRow(row, expand, context) {
825
+ const out = { ...row };
826
+ for (const item of expand) {
827
+ const field = context.entity.relations.find((candidate) => candidate.name.toLowerCase() === item.name.toLowerCase());
828
+ if (!field?.relation) continue;
829
+ const relation = field.relation;
830
+ const targetRows = context.readEntity(relation.targetEntity);
831
+ const localValue = readField(row, relation.localField);
832
+ let matches = targetRows.filter((target) => keyEquals(readField(target, relation.targetKey), localValue));
833
+ if (item.filter || item.orderby?.length || item.top != null || item.skip != null || item.select?.length || item.expand?.length) {
834
+ const targetEntity = context.entityOf?.(relation.targetEntity);
835
+ matches = executeQuery(matches, {
836
+ filter: item.filter,
837
+ orderby: item.orderby,
838
+ top: item.top,
839
+ skip: item.skip,
840
+ select: item.select,
841
+ expand: item.expand
842
+ }, targetEntity ? {
843
+ entity: targetEntity,
844
+ readEntity: context.readEntity,
845
+ entityOf: context.entityOf
846
+ } : void 0).rows;
847
+ }
848
+ out[field.name] = relation.kind === "array" ? matches : matches[0] ?? null;
849
+ }
850
+ return out;
851
+ }
852
+ /** `Entity(1)` / `Entity('abc')` -> the key, or null for a collection request. */
853
+ function parseKeySegment(segment) {
854
+ const match = /\(([^)]*)\)\s*$/.exec(String(segment ?? ""));
855
+ if (!match) return null;
856
+ let key = match[1].trim();
857
+ if (!key) return null;
858
+ const quoted = /^'(.*)'$/.exec(key) ?? /^"(.*)"$/.exec(key);
859
+ if (quoted) return decodeURIComponent(quoted[1]);
860
+ const asNumber = Number(key);
861
+ return Number.isNaN(asNumber) ? decodeURIComponent(key) : asNumber;
862
+ }
863
+ /** The `{ value, @odata.count }` envelope DevExtreme's ODataStore expects. */
864
+ function toODataEnvelope(result, count) {
865
+ return {
866
+ ...count ? { "@odata.count": result.total } : {},
867
+ value: result.rows
868
+ };
869
+ }
870
+
871
+ //#endregion
872
+ //#region pkg/mock-db/store.ts
873
+ /** Storage keys are namespaced by base-url so two apps can't collide. */
874
+ function storeName(baseUrl, entity) {
875
+ return `${baseUrl}::${entity}`;
876
+ }
877
+ function isIndexedDbAvailable() {
878
+ return typeof indexedDB !== "undefined";
879
+ }
880
+ function promisify(request) {
881
+ return new Promise((resolve, reject) => {
882
+ request.onsuccess = () => resolve(request.result);
883
+ request.onerror = () => reject(request.error);
884
+ });
885
+ }
886
+ /**
887
+ * Make a value safe for IndexedDB.
888
+ *
889
+ * IndexedDB persists with the STRUCTURED CLONE algorithm, which throws
890
+ * `DataCloneError` on Proxies — and a Vue `reactive()`/`ref()` object IS a Proxy.
891
+ * Apps hand store state straight to a POST all the time, so without this the very
892
+ * first realistic write blows up with an error that says nothing about Vue.
893
+ *
894
+ * structuredClone() is tried first (keeps Date, Map, Set); the JSON round-trip is
895
+ * the fallback that flattens a proxy — its `get` traps make stringify work fine.
896
+ */
897
+ function toPlain(value) {
898
+ try {
899
+ return structuredClone(value);
900
+ } catch {
901
+ return JSON.parse(JSON.stringify(value));
902
+ }
903
+ }
904
+ /**
905
+ * Open (and upgrade) the database. Every entity across every base-url becomes an
906
+ * object store keyed on its declared primary key, with an index per foreign key.
907
+ *
908
+ * `version` comes from the config: bumping it triggers `onupgradeneeded`, which
909
+ * drops and recreates the stores — i.e. a schema change WIPES the user's data.
910
+ * That's correct for a mock, but it is destructive and therefore logged.
911
+ */
912
+ async function openMockDb(dbName, version, schemas) {
913
+ if (!isIndexedDbAvailable()) throw new Error("[@mono-lit/utility/mock-db] IndexedDB is unavailable. The mock backend is browser-only — it cannot run during SSR/prerender. Mark the page client-only (Nuxt: `routeRules: { '/your-page': { ssr: false } }`).");
914
+ return new Promise((resolve, reject) => {
915
+ const request = indexedDB.open(dbName, version);
916
+ request.onupgradeneeded = () => {
917
+ const db = request.result;
918
+ for (const schema of schemas) for (const entity of Object.values(schema.entities)) {
919
+ const name = storeName(schema.baseUrl, entity.name);
920
+ if (db.objectStoreNames.contains(name)) db.deleteObjectStore(name);
921
+ const store = db.createObjectStore(name, { keyPath: entity.primaryKey });
922
+ for (const field of entity.columns) if (field.foreign) store.createIndex(field.name, field.name, { unique: false });
923
+ }
924
+ console.warn(`[@mono-lit/utility/mock-db] "${dbName}" upgraded to v${version} — stores were recreated and existing mock data discarded.`);
925
+ };
926
+ request.onsuccess = () => resolve(request.result);
927
+ request.onerror = () => reject(request.error);
928
+ request.onblocked = () => reject(/* @__PURE__ */ new Error(`[@mono-lit/utility/mock-db] "${dbName}" upgrade blocked — close other tabs and reload.`));
929
+ });
930
+ }
931
+ function createMockStore(db) {
932
+ function transaction(name, mode) {
933
+ return db.transaction(name, mode).objectStore(name);
934
+ }
935
+ return {
936
+ async read(baseUrl, entity) {
937
+ const name = storeName(baseUrl, entity);
938
+ if (!db.objectStoreNames.contains(name)) return [];
939
+ return await promisify(transaction(name, "readonly").getAll()) ?? [];
940
+ },
941
+ async write(baseUrl, entity, rows) {
942
+ const name = storeName(baseUrl, entity);
943
+ if (!db.objectStoreNames.contains(name)) return;
944
+ const tx = db.transaction(name, "readwrite");
945
+ const store = tx.objectStore(name);
946
+ store.clear();
947
+ for (const row of rows) store.put(toPlain(row));
948
+ await new Promise((resolve, reject) => {
949
+ tx.oncomplete = () => resolve();
950
+ tx.onerror = () => reject(tx.error);
951
+ tx.onabort = () => reject(tx.error);
952
+ });
953
+ },
954
+ async insert(baseUrl, entity, row) {
955
+ const name = storeName(baseUrl, entity);
956
+ const store = transaction(name, "readwrite");
957
+ const keyPath = String(store.keyPath);
958
+ const record = toPlain({ ...row });
959
+ if (record[keyPath] == null) record[keyPath] = (await promisify(transaction(name, "readonly").getAll()) ?? []).reduce((highest, current) => {
960
+ const value = Number(current?.[keyPath]);
961
+ return Number.isFinite(value) && value > highest ? value : highest;
962
+ }, 0) + 1;
963
+ await promisify(transaction(name, "readwrite").put(record));
964
+ return record;
965
+ },
966
+ async update(baseUrl, entity, key, changes, options) {
967
+ const name = storeName(baseUrl, entity);
968
+ const existing = await promisify(transaction(name, "readonly").get(key));
969
+ if (!existing) return null;
970
+ const store = transaction(name, "readwrite");
971
+ const keyPath = String(store.keyPath);
972
+ const next = toPlain({
973
+ ...options?.merge ?? true ? existing : {},
974
+ ...changes,
975
+ [keyPath]: existing[keyPath]
976
+ });
977
+ await promisify(store.put(next));
978
+ return next;
979
+ },
980
+ async remove(baseUrl, entity, key) {
981
+ const name = storeName(baseUrl, entity);
982
+ if (!await promisify(transaction(name, "readonly").get(key))) return false;
983
+ await promisify(transaction(name, "readwrite").delete(key));
984
+ return true;
985
+ },
986
+ async clear() {
987
+ for (const name of Array.from(db.objectStoreNames)) await promisify(transaction(name, "readwrite").clear());
988
+ },
989
+ close() {
990
+ db.close();
991
+ }
992
+ };
993
+ }
994
+
995
+ //#endregion
996
+ //#region pkg/mock-db/index.ts
997
+ const DEFAULTS = {
998
+ dbName: "mono-mock",
999
+ version: 1,
1000
+ seedCount: 10,
1001
+ seedRandom: 1
1002
+ };
1003
+ let instance = null;
1004
+ /**
1005
+ * Build the runtime for a config. Idempotent per page — `monoMockDb()` caches it,
1006
+ * so the schema is parsed and IndexedDB opened once.
1007
+ */
1008
+ function createMockDb(config) {
1009
+ const dbName = config.dbName ?? DEFAULTS.dbName;
1010
+ const version = config.version ?? DEFAULTS.version;
1011
+ const seedCount = config.seedCount ?? DEFAULTS.seedCount;
1012
+ const seedRandom = config.seedRandom ?? DEFAULTS.seedRandom;
1013
+ const { schemas, errors } = parseMockSchema(config);
1014
+ if (errors.length) for (const error of errors) console.error(`[@mono-lit/utility/mock-db] schema error in "${error.baseUrl}" -> ${error.entity}${error.field ? `.${error.field}` : ""}: ${error.message}`);
1015
+ let store = null;
1016
+ /**
1017
+ * Split a write payload into the row's own columns and any nested child
1018
+ * collections (an OData **deep insert**).
1019
+ *
1020
+ * The app POSTs a header with its details inline:
1021
+ * { Nama, CompanyId, BudgetAlokasi: [ {...}, {...} ] }
1022
+ * A real OData service creates those children as rows in their OWN entity set.
1023
+ * Storing the array as a blob column instead means a later
1024
+ * `GET /DTO_BudgetAlokasi` returns nothing while production returns the children —
1025
+ * so the mock would quietly disagree with the backend.
1026
+ */
1027
+ function splitDeepInsert(entity, payload) {
1028
+ const own = {};
1029
+ const children = [];
1030
+ for (const [key, value] of Object.entries(payload)) {
1031
+ const field = entity.relations.find((candidate) => candidate.name.toLowerCase() === key.toLowerCase());
1032
+ if (field?.relation?.kind === "array" && Array.isArray(value)) {
1033
+ children.push({
1034
+ relation: field.relation,
1035
+ rows: value
1036
+ });
1037
+ continue;
1038
+ }
1039
+ own[key] = value;
1040
+ }
1041
+ return {
1042
+ own,
1043
+ children
1044
+ };
1045
+ }
1046
+ /** Insert the nested rows into their own entity set, pointing them at the parent. */
1047
+ async function writeChildren(schema, entity, parent, children) {
1048
+ if (!store || !children.length) return;
1049
+ for (const { relation, rows } of children) {
1050
+ const target = schema.entities[relation.targetEntity];
1051
+ if (!target) continue;
1052
+ const parentValue = parent[relation.localField];
1053
+ for (const child of rows) await store.insert(schema.baseUrl, target.name, {
1054
+ ...child,
1055
+ [relation.targetKey]: parentValue
1056
+ });
1057
+ }
1058
+ }
1059
+ async function hydrate(force = false) {
1060
+ if (!isIndexedDbAvailable()) return;
1061
+ store = createMockStore(await openMockDb(dbName, version, schemas));
1062
+ for (const schema of schemas) {
1063
+ const seed = generateSeed(schema, {
1064
+ count: seedCount,
1065
+ random: seedRandom
1066
+ });
1067
+ for (const [entityName, rows] of Object.entries(seed)) {
1068
+ if ((force ? [] : await store.read(schema.baseUrl, entityName)).length) continue;
1069
+ await store.write(schema.baseUrl, entityName, rows);
1070
+ }
1071
+ }
1072
+ }
1073
+ const ready = hydrate().catch((error) => {
1074
+ console.error("[@mono-lit/utility/mock-db] failed to open IndexedDB:", error);
1075
+ });
1076
+ async function readEntityRows(baseUrl, entity) {
1077
+ if (!store) return [];
1078
+ return store.read(baseUrl, entity);
1079
+ }
1080
+ async function request(input) {
1081
+ await ready;
1082
+ const fail = (statusCode, message) => ({
1083
+ data: null,
1084
+ statusCode,
1085
+ error: {
1086
+ message,
1087
+ stack: "",
1088
+ response: null
1089
+ }
1090
+ });
1091
+ if (!store) return fail(503, "[@mono-lit/utility/mock-db] IndexedDB is not available");
1092
+ const route = matchMockRoute(schemas, input.url);
1093
+ if (!route) return fail(404, `[@mono-lit/utility/mock-db] no mock entity for "${input.url}"`);
1094
+ const { schema, entity, rest } = route;
1095
+ const method = String(input.method ?? "GET").toUpperCase();
1096
+ const segments = rest.split("/");
1097
+ const inlineKey = parseKeySegment(segments[0] ?? "");
1098
+ const pathKey = segments[1] != null && segments[1] !== "" ? decodeURIComponent(segments[1]) : null;
1099
+ const urlKey = inlineKey ?? (pathKey != null ? coerceKey(pathKey) : null);
1100
+ const body = normalizePayload(input.payload);
1101
+ const row = body.ok ? body.row : {};
1102
+ const rawKey = urlKey ?? (input.key != null ? coerceKey(String(input.key)) : null) ?? row[entity.primaryKey] ?? null;
1103
+ try {
1104
+ if (method === "GET") {
1105
+ const query = input.query ?? parseQuery(input.params ?? extractQuery(input.url));
1106
+ const rows = await readEntityRows(schema.baseUrl, entity.name);
1107
+ if (rawKey != null) {
1108
+ const match = rows.find((row) => row[entity.primaryKey] === rawKey);
1109
+ if (!match) return fail(404, `[@mono-lit/utility/mock-db] ${entity.name}(${rawKey}) not found`);
1110
+ return {
1111
+ data: match,
1112
+ statusCode: 200,
1113
+ error: null
1114
+ };
1115
+ }
1116
+ const needsRelations = Boolean(query.expand?.length) || Boolean(query.filter);
1117
+ const related = {};
1118
+ if (needsRelations) {
1119
+ const seen = /* @__PURE__ */ new Set();
1120
+ const queue = [entity.name];
1121
+ while (queue.length) {
1122
+ const current = queue.shift();
1123
+ if (seen.has(current)) continue;
1124
+ seen.add(current);
1125
+ const currentEntity = schema.entities[current];
1126
+ if (!currentEntity) continue;
1127
+ for (const field of currentEntity.relations) {
1128
+ const target = field.relation.targetEntity;
1129
+ if (!related[target]) related[target] = await readEntityRows(schema.baseUrl, target);
1130
+ queue.push(target);
1131
+ }
1132
+ }
1133
+ }
1134
+ return {
1135
+ data: toODataEnvelope(executeQuery(rows, query, {
1136
+ entity,
1137
+ readEntity: (name) => related[name] ?? [],
1138
+ entityOf: (name) => schema.entities[name]
1139
+ }), Boolean(query.count)),
1140
+ statusCode: 200,
1141
+ error: null
1142
+ };
1143
+ }
1144
+ if (!body.ok && method !== "GET" && method !== "DELETE") return fail(400, `[@mono-lit/utility/mock-db] ${method} ${body.message}`);
1145
+ if (method === "POST") {
1146
+ const { own, children } = splitDeepInsert(entity, row);
1147
+ const created = await store.insert(schema.baseUrl, entity.name, own);
1148
+ await writeChildren(schema, entity, created, children);
1149
+ return {
1150
+ data: created,
1151
+ statusCode: 201,
1152
+ error: null
1153
+ };
1154
+ }
1155
+ if (method === "PUT" || method === "PATCH") {
1156
+ if (rawKey == null) return fail(400, `[@mono-lit/utility/mock-db] ${method} needs a key — put it in the url ("${entity.name}(1)") or send it as payload.keyValue.`);
1157
+ const { own, children } = splitDeepInsert(entity, row);
1158
+ const updated = await store.update(schema.baseUrl, entity.name, rawKey, own, { merge: method === "PATCH" });
1159
+ if (!updated) return fail(404, `[@mono-lit/utility/mock-db] ${entity.name}(${rawKey}) not found`);
1160
+ await writeChildren(schema, entity, updated, children);
1161
+ return {
1162
+ data: updated,
1163
+ statusCode: 200,
1164
+ error: null
1165
+ };
1166
+ }
1167
+ if (method === "DELETE") {
1168
+ if (rawKey == null) return fail(400, `[@mono-lit/utility/mock-db] DELETE needs a key — put it in the url ("${entity.name}(1)") or send it as payload.keyValue.`);
1169
+ if (!await store.remove(schema.baseUrl, entity.name, rawKey)) return fail(404, `[@mono-lit/utility/mock-db] ${entity.name}(${rawKey}) not found`);
1170
+ return {
1171
+ data: null,
1172
+ statusCode: 200,
1173
+ error: null
1174
+ };
1175
+ }
1176
+ return fail(405, `[@mono-lit/utility/mock-db] ${method} is not supported`);
1177
+ } catch (error) {
1178
+ return fail(500, error?.message ?? String(error));
1179
+ }
1180
+ }
1181
+ return {
1182
+ ready,
1183
+ schemas,
1184
+ matches(url) {
1185
+ return Boolean(matchMockRoute(schemas, url));
1186
+ },
1187
+ request,
1188
+ async reset() {
1189
+ await ready;
1190
+ if (!store) return;
1191
+ await store.clear();
1192
+ await hydrate(true);
1193
+ },
1194
+ async export() {
1195
+ await ready;
1196
+ const out = {};
1197
+ if (!store) return out;
1198
+ for (const schema of schemas) {
1199
+ out[schema.baseUrl] = {};
1200
+ for (const entity of Object.values(schema.entities)) out[schema.baseUrl][entity.name] = await store.read(schema.baseUrl, entity.name);
1201
+ }
1202
+ return out;
1203
+ },
1204
+ async import(data) {
1205
+ await ready;
1206
+ if (!store) return;
1207
+ for (const [baseUrl, tables] of Object.entries(data ?? {})) for (const [entityName, rows] of Object.entries(tables ?? {})) await store.write(baseUrl, entityName, rows);
1208
+ }
1209
+ };
1210
+ }
1211
+ /**
1212
+ * Coerce a request body into a storable row, or explain why it isn't one.
1213
+ *
1214
+ * REST callers reach us through `monoFetch`, whose options are `RequestInit` — so
1215
+ * `body` is normally `JSON.stringify(obj)`, a STRING. Handing that to the store
1216
+ * spreads it character-by-character into `{"0":"{","1":"\"",…}` and writes that
1217
+ * garbage row with a 201. Normalising here (rather than only in the wrapper) means
1218
+ * no caller can corrupt the store, whichever entry point it came through.
1219
+ */
1220
+ function normalizePayload(payload) {
1221
+ let value = payload;
1222
+ if (typeof value === "string") {
1223
+ const text = value.trim();
1224
+ if (!text) return {
1225
+ ok: true,
1226
+ row: {}
1227
+ };
1228
+ try {
1229
+ value = JSON.parse(text);
1230
+ } catch {
1231
+ return {
1232
+ ok: false,
1233
+ message: "body is a string but not valid JSON"
1234
+ };
1235
+ }
1236
+ }
1237
+ if (value == null) return {
1238
+ ok: true,
1239
+ row: {}
1240
+ };
1241
+ if (typeof value !== "object" || Array.isArray(value)) return {
1242
+ ok: false,
1243
+ message: `body must be an object, received ${Array.isArray(value) ? "an array" : typeof value}`
1244
+ };
1245
+ const tag = Object.prototype.toString.call(value);
1246
+ if (tag !== "[object Object]") return {
1247
+ ok: false,
1248
+ message: `body must be a plain object, received ${tag.slice(8, -1)}`
1249
+ };
1250
+ return {
1251
+ ok: true,
1252
+ row: value
1253
+ };
1254
+ }
1255
+ /** `?a=1` off a url, so a caller can pass the whole url instead of params. */
1256
+ function extractQuery(url) {
1257
+ const at = String(url ?? "").indexOf("?");
1258
+ return at >= 0 ? url.slice(at + 1) : "";
1259
+ }
1260
+ /** Path keys arrive as strings; primary keys are usually numbers. */
1261
+ function coerceKey(value) {
1262
+ const asNumber = Number(value);
1263
+ return Number.isNaN(asNumber) || value.trim() === "" ? value : asNumber;
1264
+ }
1265
+ /**
1266
+ * The page-wide mock backend, built from `mono.config.ts` `mockIndexedDB`.
1267
+ * Returns null when the app declares no mock — every caller must treat that as
1268
+ * "go to the network".
1269
+ */
1270
+ function monoMockDb(config) {
1271
+ if (instance) return instance;
1272
+ if (!config?.schema || !Object.keys(config.schema).length) return null;
1273
+ instance = createMockDb(config);
1274
+ return instance;
1275
+ }
1276
+ /** Test seam — drops the cached instance. */
1277
+ function resetMonoMockDb() {
1278
+ instance = null;
1279
+ }
1280
+
1281
+ //#endregion
1282
+ export { isIndexedDbAvailable as a, executeQuery as c, parseKeySegment as d, parseQuery as f, parseApply as g, applyTransforms as h, createMockStore as i, parseExpand as l, tokenize as m, monoMockDb as n, openMockDb as o, toODataEnvelope as p, resetMonoMockDb as r, evaluateFilter as s, createMockDb as t, parseFilter as u };