@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,867 @@
1
+ import { S as monoConfig, T as monoStatePatch, a as createUniqueFetcher, c as tryCatchDatasource, f as createStaticDatasource, i as createFetcher, l as useFetchOData, o as loadChuckStore, s as promiseWrapper, u as useNormalFetch, w as monoState } from "./runtime-C_IWNrAG.js";
2
+ import { t as monoCookie } from "./universal-BNTo_83u.js";
3
+ import { i as matchMockRoute } from "./generate-CJ7MtcDd.js";
4
+ import { c as executeQuery, f as parseQuery, l as parseExpand, n as monoMockDb, r as resetMonoMockDb } from "./mock-db-5mJTObSC.js";
5
+ import * as monoDevextremeModule from "@mono-lit/devextreme";
6
+ import { CustomStore, DataSource, ODataStore } from "@mono-lit/devextreme";
7
+
8
+ //#region pkg/mock-db/devextreme.ts
9
+ /** DevExtreme filter expr -> OData $filter text. */
10
+ function filterToOData(filter) {
11
+ if (!Array.isArray(filter) || !filter.length) return void 0;
12
+ if (filter.length === 1 && typeof filter[0] === "string") return filter[0];
13
+ if (Array.isArray(filter[0])) {
14
+ const parts = [];
15
+ for (const item of filter) if (Array.isArray(item)) {
16
+ const inner = filterToOData(item);
17
+ if (inner) parts.push(`(${inner})`);
18
+ } else if (typeof item === "string") parts.push(item.toLowerCase() === "or" ? "or" : "and");
19
+ return parts.join(" ") || void 0;
20
+ }
21
+ if (filter[0] === "!" && Array.isArray(filter[1])) {
22
+ const inner = filterToOData(filter[1]);
23
+ return inner ? `not (${inner})` : void 0;
24
+ }
25
+ const [field, operator, value] = filter;
26
+ if (typeof field !== "string") return void 0;
27
+ const literal = typeof value === "number" || typeof value === "boolean" ? String(value) : `'${String(value ?? "").replace(/'/g, "''")}'`;
28
+ switch (String(operator)) {
29
+ case "=": return `${field} eq ${literal}`;
30
+ case "<>": return `${field} ne ${literal}`;
31
+ case ">": return `${field} gt ${literal}`;
32
+ case ">=": return `${field} ge ${literal}`;
33
+ case "<": return `${field} lt ${literal}`;
34
+ case "<=": return `${field} le ${literal}`;
35
+ case "contains": return `contains(${field},${literal})`;
36
+ case "notcontains": return `not contains(${field},${literal})`;
37
+ case "startswith": return `startswith(${field},${literal})`;
38
+ case "endswith": return `endswith(${field},${literal})`;
39
+ default: return `${field} eq ${literal}`;
40
+ }
41
+ }
42
+ /** DevExtreme `sort` -> our orderby rules. */
43
+ function sortToOrderBy(sort) {
44
+ if (!sort) return void 0;
45
+ return (Array.isArray(sort) ? sort : [sort]).map((rule) => {
46
+ if (typeof rule === "string") return {
47
+ field: rule,
48
+ desc: false
49
+ };
50
+ if (rule?.selector) return {
51
+ field: String(rule.selector),
52
+ desc: Boolean(rule.desc)
53
+ };
54
+ return null;
55
+ }).filter(Boolean);
56
+ }
57
+ /** Case-insensitive field read, matching the rest of the engine. */
58
+ function readField(row, name) {
59
+ if (name in row) return row[name];
60
+ const lower = String(name).toLowerCase();
61
+ const hit = Object.keys(row).find((key) => key.toLowerCase() === lower);
62
+ return hit ? row[hit] : void 0;
63
+ }
64
+ /** DevExtreme `group` loadOption -> selectors. Accepts string | {selector} | array. */
65
+ function groupSelectors(group) {
66
+ if (!group) return [];
67
+ return (Array.isArray(group) ? group : [group]).map((rule) => {
68
+ if (typeof rule === "string") return {
69
+ selector: rule,
70
+ desc: false
71
+ };
72
+ if (rule?.selector) return {
73
+ selector: String(rule.selector),
74
+ desc: Boolean(rule.desc)
75
+ };
76
+ return null;
77
+ }).filter(Boolean);
78
+ }
79
+ /** One summary value over a bucket of rows. */
80
+ function computeSummary(rows, spec) {
81
+ const type = String(spec.summaryType ?? "count").toLowerCase();
82
+ if (type === "count") return rows.length;
83
+ const values = rows.map((row) => readField(row, String(spec.selector))).filter((value) => value !== void 0 && value !== null).map(Number).filter((value) => !Number.isNaN(value));
84
+ if (!values.length) return type === "sum" ? 0 : null;
85
+ switch (type) {
86
+ case "sum": return values.reduce((total, value) => total + value, 0);
87
+ case "avg": return values.reduce((total, value) => total + value, 0) / values.length;
88
+ case "min": return Math.min(...values);
89
+ case "max": return Math.max(...values);
90
+ default: return null;
91
+ }
92
+ }
93
+ /**
94
+ * Build DevExtreme's grouped result: `[{ key, items, count, summary }]`.
95
+ *
96
+ * A grid asks for grouping through `loadOptions.group`, NOT through OData `$apply`,
97
+ * and it expects this exact shape back. Returning a flat array instead makes the
98
+ * group panel render nothing while the rows still look fine — silently wrong.
99
+ *
100
+ * `groupInterval`/`isExpanded: false` collapse to `items: null` + a count, which is
101
+ * how the grid lazy-loads group contents.
102
+ */
103
+ function groupRows(rows, selectors, options = {}) {
104
+ if (!selectors.length) return [];
105
+ const [current, ...rest] = selectors;
106
+ const buckets = /* @__PURE__ */ new Map();
107
+ for (const row of rows) {
108
+ const key = readField(row, current.selector) ?? null;
109
+ const id = JSON.stringify(key);
110
+ const bucket = buckets.get(id);
111
+ if (bucket) bucket.items.push(row);
112
+ else buckets.set(id, {
113
+ key,
114
+ items: [row]
115
+ });
116
+ }
117
+ const groups = [...buckets.values()].map(({ key, items }) => {
118
+ const summary = options.groupSummary?.length ? options.groupSummary.map((spec) => computeSummary(items, spec)) : void 0;
119
+ return {
120
+ key,
121
+ items: rest.length ? groupRows(items, rest, options) : options.expanded === false ? null : items,
122
+ count: items.length,
123
+ ...summary ? { summary } : {}
124
+ };
125
+ });
126
+ groups.sort((a, b) => {
127
+ const left = a.key;
128
+ const right = b.key;
129
+ if (left === right) return 0;
130
+ if (left == null) return -1;
131
+ if (right == null) return 1;
132
+ const cmp = typeof left === "number" && typeof right === "number" ? left - right : String(left).localeCompare(String(right));
133
+ return current.desc ? -cmp : cmp;
134
+ });
135
+ return groups;
136
+ }
137
+ /** Translate DevExtreme loadOptions into our query shape. */
138
+ function loadOptionsToQuery(loadOptions) {
139
+ const query = {};
140
+ const filter = filterToOData(loadOptions?.filter);
141
+ if (filter) query.filter = filter;
142
+ const orderby = sortToOrderBy(loadOptions?.sort);
143
+ if (orderby?.length) query.orderby = orderby;
144
+ if (typeof loadOptions?.skip === "number") query.skip = loadOptions.skip;
145
+ if (typeof loadOptions?.take === "number") query.top = loadOptions.take;
146
+ if (query.top == null && loadOptions?.paginate !== false && typeof loadOptions?.pageSize === "number") query.top = loadOptions.pageSize;
147
+ if (Array.isArray(loadOptions?.select) && loadOptions.select.length) query.select = loadOptions.select.map(String);
148
+ if (loadOptions?.expand != null && (!Array.isArray(loadOptions.expand) || loadOptions.expand.length)) query.expand = parseExpand(loadOptions.expand);
149
+ if (loadOptions?.requireTotalCount) query.count = true;
150
+ return query;
151
+ }
152
+ /**
153
+ * A DevExtreme `DataSource` over a `CustomStore` that answers from IndexedDB
154
+ * through the same OData engine the fetch path uses — so a grid gets real
155
+ * server-style paging/filtering/sorting instead of a silent full table.
156
+ */
157
+ function createMockDataSource({ mock, baseUrl, entity, DataSource, CustomStore, options }) {
158
+ const readAll = async () => {
159
+ const payload = (await mock.request({
160
+ url: `${baseUrl}/${entity.name}`,
161
+ method: "GET",
162
+ params: {}
163
+ })).data;
164
+ return Array.isArray(payload?.value) ? payload.value : payload ?? [];
165
+ };
166
+ const store = new CustomStore({
167
+ key: entity.primaryKey,
168
+ loadMode: "processed",
169
+ async load(loadOptions) {
170
+ const query = loadOptionsToQuery(loadOptions);
171
+ const rows = await readAll();
172
+ const schema = mock.schemas.find((candidate) => candidate.baseUrl === baseUrl);
173
+ const related = {};
174
+ if (query.expand?.length || query.filter) {
175
+ const seen = /* @__PURE__ */ new Set();
176
+ const queue = [entity.name];
177
+ while (queue.length) {
178
+ const current = queue.shift();
179
+ if (seen.has(current)) continue;
180
+ seen.add(current);
181
+ const currentEntity = schema?.entities[current];
182
+ if (!currentEntity) continue;
183
+ for (const field of currentEntity.relations) {
184
+ const target = field.relation.targetEntity;
185
+ if (!related[target]) {
186
+ const payload = (await mock.request({
187
+ url: `${baseUrl}/${target}`,
188
+ method: "GET",
189
+ params: {}
190
+ })).data;
191
+ related[target] = Array.isArray(payload?.value) ? payload.value : payload ?? [];
192
+ }
193
+ queue.push(target);
194
+ }
195
+ }
196
+ }
197
+ const result = executeQuery(rows, query, {
198
+ entity,
199
+ readEntity: (name) => related[name] ?? [],
200
+ entityOf: (name) => schema?.entities[name]
201
+ });
202
+ const selectors = groupSelectors(loadOptions?.group);
203
+ if (selectors.length) {
204
+ const groups = groupRows(result.rows, selectors, {
205
+ groupSummary: loadOptions?.groupSummary,
206
+ expanded: loadOptions?.group?.[0]?.isExpanded
207
+ });
208
+ if (loadOptions?.requireTotalCount || loadOptions?.requireGroupCount) return {
209
+ data: groups,
210
+ totalCount: result.total,
211
+ groupCount: groups.length,
212
+ ...loadOptions?.totalSummary?.length ? { summary: loadOptions.totalSummary.map((spec) => computeSummary(result.rows, spec)) } : {}
213
+ };
214
+ return groups;
215
+ }
216
+ if (loadOptions?.requireTotalCount) return {
217
+ data: result.rows,
218
+ totalCount: result.total,
219
+ ...loadOptions?.totalSummary?.length ? { summary: loadOptions.totalSummary.map((spec) => computeSummary(result.rows, spec)) } : {}
220
+ };
221
+ return result.rows;
222
+ },
223
+ async byKey(key) {
224
+ return (await mock.request({
225
+ url: `${baseUrl}/${entity.name}(${key})`,
226
+ method: "GET"
227
+ })).data;
228
+ },
229
+ async insert(values) {
230
+ const response = await mock.request({
231
+ url: `${baseUrl}/${entity.name}`,
232
+ method: "POST",
233
+ payload: values
234
+ });
235
+ if (response.error) throw new Error(response.error.message);
236
+ return response.data;
237
+ },
238
+ async update(key, values) {
239
+ const response = await mock.request({
240
+ url: `${baseUrl}/${entity.name}(${key})`,
241
+ method: "PUT",
242
+ payload: values
243
+ });
244
+ if (response.error) throw new Error(response.error.message);
245
+ return response.data;
246
+ },
247
+ async remove(key) {
248
+ const response = await mock.request({
249
+ url: `${baseUrl}/${entity.name}(${key})`,
250
+ method: "DELETE"
251
+ });
252
+ if (response.error) throw new Error(response.error.message);
253
+ }
254
+ });
255
+ const { key: _key, ...dataSourceOptions } = options ?? {};
256
+ return new DataSource({
257
+ ...dataSourceOptions,
258
+ store,
259
+ key: entity.primaryKey
260
+ });
261
+ }
262
+
263
+ //#endregion
264
+ //#region pkg/wrapper-fetching.ts
265
+ function tanstackRunner() {
266
+ try {
267
+ const runner = Reflect.get(monoDevextremeModule, "tanstackRun");
268
+ return typeof runner === "function" ? runner : void 0;
269
+ } catch {
270
+ return;
271
+ }
272
+ }
273
+ /** A non-2xx `fetchNormal` result, thrown so TanStack neither caches it nor skips its retry policy. */
274
+ var FailedFetchResult = class {
275
+ result;
276
+ constructor(result) {
277
+ this.result = result;
278
+ }
279
+ get statusCode() {
280
+ return this.result.statusCode;
281
+ }
282
+ };
283
+ let runtimeOptions = {};
284
+ const wrapperDefaults = {
285
+ notif: false,
286
+ selfProxy: "",
287
+ method: "GET",
288
+ type: "datasource",
289
+ allowZero: false,
290
+ cache: false
291
+ };
292
+ function configureFetching(options = {}) {
293
+ runtimeOptions = {
294
+ ...runtimeOptions,
295
+ ...options
296
+ };
297
+ }
298
+ function resetFetchingConfig() {
299
+ runtimeOptions = {};
300
+ }
301
+ function getFetchingConfig() {
302
+ const config = monoConfig();
303
+ if (!config) throw new Error("[@mono-lit/utility/fetching] mono config is missing. Make sure you call app.use(createMono(monoConfig)) before using fetching helpers.");
304
+ if (!config.fetching) throw new Error("[@mono-lit/utility/fetching] config.fetching is missing in mono.config.ts.");
305
+ return config.fetching;
306
+ }
307
+ /**
308
+ * Map the shared `fetching.source` ctors to the capitalized shape the core fetch layer
309
+ * expects. Never throws — any missing ctor is left `undefined` and the core fetch layer
310
+ * fills it from its built-in DevExtreme classes.
311
+ */
312
+ function mapSharedSource(shared) {
313
+ return {
314
+ DataSource: shared?.dataSource || DataSource,
315
+ ODataStore: shared?.oDataStore || ODataStore,
316
+ CustomStore: shared?.customStore || CustomStore
317
+ };
318
+ }
319
+ /**
320
+ * Resolve the source for a named odata entry: the shared `fetching.source`
321
+ * ctors plus this entry's own `oDataService` (which differs per API).
322
+ */
323
+ function mapEntrySource(entry, shared) {
324
+ return {
325
+ ...mapSharedSource(shared),
326
+ OdataService: entry.oDataService
327
+ };
328
+ }
329
+ /**
330
+ * Merge a base source with an override, letting `override` win — but only on
331
+ * its *defined* keys, so a partial inline source can't clobber a shared ctor
332
+ * with `undefined`. Returns whichever side is present when the other is absent.
333
+ */
334
+ function mergeSource(base, override) {
335
+ if (!base) return override;
336
+ if (!override) return base;
337
+ const out = { ...base };
338
+ for (const key of Object.keys(override)) if (override[key] !== void 0) out[key] = override[key];
339
+ return out;
340
+ }
341
+ /**
342
+ * The shared OData source ctors: the `@mono-lit/devextreme` defaults baked into
343
+ * `mapSharedSource`, with any `fetching.source` overrides on top. Tolerant of a
344
+ * missing/uninitialized config (`monoConfig()` returns `undefined` → pure
345
+ * defaults), so fully-manual (baseUrl-only) calls still get real constructors.
346
+ *
347
+ * Never returns `undefined`: the core fetch layer does NOT fall back to its own DevExtreme
348
+ * classes (it `import type`s them and calls `new source.ODataStore(...)` with no
349
+ * fallback), so a fully-absent source would crash with "ods is not a constructor".
350
+ */
351
+ function getSharedSource() {
352
+ return mapSharedSource(monoConfig()?.fetching?.source);
353
+ }
354
+ /**
355
+ * True for a url that is effectively missing. Guards against the common
356
+ * `url: String(import.meta.env.SOME_VAR)` pattern: when the env var is undefined
357
+ * at the moment Vite starts, `String(undefined)` yields the *truthy* literal
358
+ * `"undefined"`, which would otherwise sail past a plain `!entry.url` check and
359
+ * make the fetcher silently request `undefined/<path>` with no error.
360
+ */
361
+ function isMissingUrl(url) {
362
+ if (!url) return true;
363
+ const trimmed = String(url).trim();
364
+ return trimmed === "" || trimmed === "undefined" || trimmed === "null";
365
+ }
366
+ /**
367
+ * The page-wide mock, or null when the app declares no `mockIndexedDB`.
368
+ * Cached inside `monoMockDb()`, so this is cheap to call per request.
369
+ *
370
+ * `monoConfig()` returns a DEEPLY READONLY view of the reactive mono config,
371
+ * so `schema[...].seed` arrives as `readonly T[]` and will not assign to the
372
+ * mutable engine types. Widen it here instead of threading `readonly` through the
373
+ * whole mock-db surface: nothing downstream mutates the config — `generateSeed`
374
+ * copies every seed row (`entity.seed.map(row => ({ ...row }))`) precisely so the
375
+ * config object can never be written through.
376
+ */
377
+ function getMockDb() {
378
+ const config = monoConfig()?.mockIndexedDB;
379
+ return monoMockDb(config);
380
+ }
381
+ /**
382
+ * Resolve a call to a mock route, if it is one.
383
+ *
384
+ * Checks BOTH the entry's base url and the call's own `url`, because either can
385
+ * carry the schema's base-url (`fetching.api.x.url = 'my-mock'` + `url: '/users'`,
386
+ * or a plain `url: '/my-mock/users'`).
387
+ *
388
+ * Deliberately tolerant of a missing/`"undefined"` entry url: an app running
389
+ * purely on the mock has no real backend to point at, so this must resolve
390
+ * BEFORE `resolveApiEntry`'s `isMissingUrl` throws.
391
+ */
392
+ function resolveMockRoute(configBaseUrl, url) {
393
+ const mock = getMockDb();
394
+ if (!mock) return null;
395
+ const entryUrl = (() => {
396
+ if (!configBaseUrl) return "";
397
+ const entry = monoConfig()?.fetching?.api?.[configBaseUrl];
398
+ return typeof entry?.url === "string" ? entry.url : "";
399
+ })();
400
+ for (const candidate of [
401
+ joinUrl(entryUrl, url),
402
+ url,
403
+ entryUrl
404
+ ]) {
405
+ if (!candidate) continue;
406
+ const route = matchMockRoute(mock.schemas, candidate);
407
+ if (route) return {
408
+ mock,
409
+ route,
410
+ url: candidate
411
+ };
412
+ }
413
+ return null;
414
+ }
415
+ function joinUrl(base, path) {
416
+ const left = String(base ?? "").replace(/\/+$/, "");
417
+ const right = String(path ?? "").replace(/^\/+/, "");
418
+ if (!left) return right;
419
+ if (!right) return left;
420
+ return `${left}/${right}`;
421
+ }
422
+ /**
423
+ * Serve a fetch call from IndexedDB, shaped exactly like the core fetch layer result so
424
+ * callers cannot tell the difference.
425
+ *
426
+ * `datasource`/`fakedatasource` hand back a real DevExtreme DataSource (over a
427
+ * CustomStore), so grids keep their server-style paging/filtering.
428
+ */
429
+ async function serveFromMock(hit, call) {
430
+ const { mock, route, url } = hit;
431
+ const wantsDataSource = String(call.type ?? "").toLowerCase().includes("datasource");
432
+ /**
433
+ * The query, from BOTH sources the caller can use:
434
+ * - `options` — the core's DataSourceOptions (select/filter/sort/expand/pageSize).
435
+ * the core applies these even for `type: 'data'` (it builds a DataSource from them
436
+ * and `.load()`s it), so ignoring them here would make the mock return every
437
+ * row while production returned a filtered set.
438
+ * - `params` — raw `$`-params. Explicit, so they win on conflict.
439
+ */
440
+ const query = {
441
+ ...call.options ? loadOptionsToQuery(call.options) : {},
442
+ ...call.params ? parseQuery(call.params) : {}
443
+ };
444
+ if (wantsDataSource) {
445
+ const shared = getSharedSource();
446
+ const dataSource = createMockDataSource({
447
+ mock,
448
+ baseUrl: route.schema.baseUrl,
449
+ entity: route.entity,
450
+ DataSource: shared.DataSource,
451
+ CustomStore: shared.CustomStore,
452
+ options: call.options
453
+ });
454
+ const method = String(call.method ?? "GET").toUpperCase();
455
+ if (method !== "GET") {
456
+ const response = await mock.request({
457
+ url,
458
+ method,
459
+ query,
460
+ key: call.payload?.keyValue,
461
+ payload: call.payload?.data ?? call.payload
462
+ });
463
+ return {
464
+ data: response.data,
465
+ dataSource,
466
+ statusCode: response.statusCode,
467
+ error: response.error
468
+ };
469
+ }
470
+ return {
471
+ data: null,
472
+ dataSource,
473
+ statusCode: 200,
474
+ error: null
475
+ };
476
+ }
477
+ const response = await mock.request({
478
+ url,
479
+ method: call.method,
480
+ query,
481
+ key: call.payload?.keyValue,
482
+ payload: call.payload?.data ?? call.payload
483
+ });
484
+ const payload = response.data;
485
+ return {
486
+ data: payload && Array.isArray(payload.value) ? payload.value : payload,
487
+ dataSource: null,
488
+ statusCode: response.statusCode,
489
+ error: response.error
490
+ };
491
+ }
492
+ /**
493
+ * Look up a named entry in `fetching.api` and resolve its url (+ source for odata).
494
+ */
495
+ function resolveApiEntry(name) {
496
+ const fetching = getFetchingConfig();
497
+ const entry = fetching.api?.[name];
498
+ if (!entry) throw new Error(`[@mono-lit/utility/fetching] fetching.api["${name}"] is not defined in mono.config.ts.`);
499
+ if (isMissingUrl(entry.url)) throw new Error(`[@mono-lit/utility/fetching] fetching.api["${name}"].url is missing (got ${JSON.stringify(entry.url)}). The backing env var was likely undefined when Vite started — check that mono-env loaded the right .env file (including any synced under .mono/apps/) and restart the dev server.`);
500
+ return {
501
+ type: entry.type,
502
+ url: entry.url,
503
+ source: entry.type === "odata" ? mapEntrySource(entry, fetching.source) : void 0
504
+ };
505
+ }
506
+ function getRestBaseUrl(configBaseUrl, explicitBaseUrl) {
507
+ const url = (configBaseUrl ? resolveApiEntry(configBaseUrl).url : "") || explicitBaseUrl || runtimeOptions.restBaseUrl;
508
+ if (!url) throw new Error("[@mono-lit/utility/fetching] no base url. Pass `configBaseUrl: \"<entryName>\"` or `baseUrl`.");
509
+ return url;
510
+ }
511
+ function getODataBaseUrl(configBaseUrl, explicitBaseUrl) {
512
+ const url = (configBaseUrl ? resolveApiEntry(configBaseUrl).url : "") || explicitBaseUrl || runtimeOptions.odataBaseUrl;
513
+ if (!url) throw new Error("[@mono-lit/utility/fetching] no odata base url. Pass `configBaseUrl: \"<entryName>\"` or `baseUrl`.");
514
+ return url;
515
+ }
516
+ /**
517
+ * Resolve the OData source ctors. Never throws — when nothing is configured it
518
+ * returns `undefined` and the core fetch layer falls back to its built-in DevExtreme
519
+ * classes.
520
+ *
521
+ * With `configBaseUrl`, the named entry's resolved source wins (already the
522
+ * shared `fetching.source` ctors merged with that entry's `oDataService`).
523
+ * Without it, the shared `fetching.source` is the base, with any inline
524
+ * per-call `source` overriding it per defined field.
525
+ */
526
+ function getODataSource(configBaseUrl, inlineSource) {
527
+ if (configBaseUrl) return resolveApiEntry(configBaseUrl).source;
528
+ return mergeSource(getSharedSource(), inlineSource);
529
+ }
530
+ /** The `split` flag a cookie declares in the top-level `cookie[]` array. */
531
+ function cookieSplit(name) {
532
+ if (!name) return false;
533
+ return Boolean(monoConfig()?.cookie?.find((c) => c.name === name)?.split);
534
+ }
535
+ /**
536
+ * Read a token cookie.
537
+ *
538
+ * The LIVE cookie wins over the hydrated state, and state is patched when they differ.
539
+ * That order is load-bearing: a token refresh writes the new value straight to
540
+ * `document.cookie` and touches nothing else. Reading the hydrated state first — which
541
+ * is what this used to do — meant that after the very first refresh we kept sending the
542
+ * OLD token forever, so the refresh "worked" once and then everything 401'd.
543
+ *
544
+ * State remains the fallback for SSR, where `monoCookie()` resolves from the h3 event.
545
+ */
546
+ function readCookieValue(name) {
547
+ const state = monoState();
548
+ try {
549
+ const live = monoCookie?.().get(name, cookieSplit(name)) ?? void 0;
550
+ if (live) {
551
+ if (state.cookie?.[name] !== live) monoStatePatch({ cookie: { [name]: live } });
552
+ return live;
553
+ }
554
+ } catch {}
555
+ return state.cookie?.[name];
556
+ }
557
+ /**
558
+ * Which cookie goes on which request.
559
+ *
560
+ * The object form of `use` names cookies directly. The legacy string form
561
+ * (`'token'` / `'tokenRefresh'`) selects between the deprecated `auth.token` /
562
+ * `auth.tokenRefresh` names, and still works — the hosts continue to use it, and a
563
+ * remote's `auth` deep-merges onto the host's, so both shapes can appear at once.
564
+ */
565
+ function resolveAuthCookies() {
566
+ const auth = monoConfig()?.fetching?.auth;
567
+ if (!auth) return {};
568
+ const use = auth.use;
569
+ if (use && typeof use === "object") return {
570
+ apiCookie: use.apiRequest ?? auth.tokenRefresh,
571
+ refreshCookie: use.refreshTokenRequest ?? auth.token
572
+ };
573
+ return {
574
+ apiCookie: use === "token" ? auth.token : auth.tokenRefresh ?? auth.token,
575
+ refreshCookie: auth.token
576
+ };
577
+ }
578
+ /**
579
+ * The core's `ConfigType`, built from our cookie names.
580
+ *
581
+ * The mapping looks inverted. It is not — the core hardcodes both sides:
582
+ * - it sends `jwtRefreshName` on ordinary API requests (getRequestToken)
583
+ * - it sends `jwtName` as the Bearer ON the refresh call (refetchRefreshToken)
584
+ *
585
+ * So `use.apiRequest` -> `jwtRefreshName`, and `use.refreshTokenRequest` -> `jwtName`.
586
+ * Please don't "fix" this.
587
+ */
588
+ function getMonoTokenConfig() {
589
+ const { apiCookie, refreshCookie } = resolveAuthCookies();
590
+ if (!apiCookie && !refreshCookie) return void 0;
591
+ return {
592
+ jwtName: refreshCookie ?? "",
593
+ jwtRefreshName: apiCookie ?? ""
594
+ };
595
+ }
596
+ /**
597
+ * The refresh request, in the shape the core and `src/token` expect (`MonoFetchCookieOptions`).
598
+ *
599
+ * Returns `undefined` when the app declares no `requestRefreshTokenRequest`, which
600
+ * leaves the core's refresh machinery dormant — the behaviour mono had before this existed.
601
+ */
602
+ function getRefreshRequestOptions(configBaseUrl) {
603
+ const refresh = (monoConfig()?.fetching?.auth)?.requestRefreshTokenRequest;
604
+ if (!refresh?.fetchParams?.url) return void 0;
605
+ const { apiCookie } = resolveAuthCookies();
606
+ const name = refresh.name ?? apiCookie;
607
+ if (!refresh.path?.milis && !refresh.path?.days) console.warn("[@mono-lit/utility/fetching] auth.requestRefreshTokenRequest.path has neither `milis` nor `days`. That is the cookie lifetime — without it the refreshed token is never stored, and the refresh will appear to succeed while changing nothing.");
608
+ const options = refresh.fetchParams.options ?? {};
609
+ return {
610
+ name,
611
+ path: refresh.path,
612
+ splitCookie: refresh.splitCookie ?? cookieSplit(name),
613
+ fetchParams: {
614
+ url: refresh.fetchParams.url,
615
+ options: {
616
+ ...options,
617
+ baseUrl: options.baseUrl ?? refreshBaseUrl(configBaseUrl)
618
+ }
619
+ }
620
+ };
621
+ }
622
+ /**
623
+ * Where `/Auth/RefreshToken` lives when the app doesn't say.
624
+ *
625
+ * A refresh endpoint is a REST route, so the base of the call that TRIGGERED the refresh
626
+ * is the wrong default whenever that call was OData: it would POST the refresh at the
627
+ * `/odata` root and 404 on every attempt, with a config that looks entirely reasonable.
628
+ * Prefer a `restful` entry — the triggering one if it is REST, else the first declared.
629
+ */
630
+ function refreshBaseUrl(configBaseUrl) {
631
+ const api = monoConfig()?.fetching?.api ?? {};
632
+ const own = configBaseUrl ? api[configBaseUrl] : void 0;
633
+ if (own?.type === "restful" && own.url) return own.url;
634
+ return Object.values(api).find((e) => e?.type === "restful" && e?.url)?.url ?? runtimeOptions.restBaseUrl;
635
+ }
636
+ /**
637
+ * Everything the core needs to refresh a token on its own: the cookie names, the refresh
638
+ * request, and what to do when it can't be saved. Spread into every core call.
639
+ */
640
+ function authArgs(configBaseUrl) {
641
+ const auth = monoConfig()?.fetching?.auth;
642
+ return {
643
+ config: getMonoTokenConfig(),
644
+ tokenOptions: getRefreshRequestOptions(configBaseUrl),
645
+ expiredBehaviour: auth?.expiredBehaviour,
646
+ unauthCall: runtimeOptions.unauthCall
647
+ };
648
+ }
649
+ /**
650
+ * The token that goes on this call.
651
+ *
652
+ * Hand the core the RAW cookie value, untouched: the core decides whether a passed token is
653
+ * "the cookie" or "the caller's own" by byte-equality with the live cookie, and only a
654
+ * cookie-derived token keeps following the cookie across refreshes for the life of a
655
+ * DataSource. Anything that transforms the value here turns every store into one that
656
+ * sends the token it was built with forever.
657
+ */
658
+ function getRequestToken(manualToken) {
659
+ if (manualToken) return manualToken;
660
+ if (runtimeOptions.token) return runtimeOptions.token;
661
+ if (!monoConfig()?.fetching) return;
662
+ const { apiCookie, refreshCookie } = resolveAuthCookies();
663
+ const chosenName = apiCookie ?? "MONO_tokenRefresh";
664
+ const fallbackName = refreshCookie ?? "MONO_token";
665
+ let value = readCookieValue(chosenName);
666
+ if (!value && fallbackName && fallbackName !== chosenName) value = readCookieValue(fallbackName);
667
+ if (!value && (apiCookie || refreshCookie)) {
668
+ const state = monoState();
669
+ console.warn("[@mono-lit/utility/fetching] request token is empty", {
670
+ apiCookie,
671
+ refreshCookie,
672
+ configuredCookies: monoConfig()?.cookie?.map((c) => c.name) ?? [],
673
+ availableCookieKeys: Object.keys(state.cookie ?? {}),
674
+ cookieState: state.cookie
675
+ });
676
+ }
677
+ return value;
678
+ }
679
+ function resolveNotif(enabled) {
680
+ if (!enabled) return false;
681
+ return runtimeOptions.notif || false;
682
+ }
683
+ function mergeHeaders(baseHeaders, overrideHeaders) {
684
+ return {
685
+ ...baseHeaders ?? {},
686
+ ...overrideHeaders ?? {}
687
+ };
688
+ }
689
+ function getGlobalHeaders() {
690
+ return (monoConfig()?.fetching)?.headers ?? {};
691
+ }
692
+ /**
693
+ * Optional helper if you want to manually refresh state before fetching.
694
+ *
695
+ * Usually unnecessary if createMono(monoConfig) already runs once.
696
+ */
697
+ function getFetchingRuntime(configBaseUrl) {
698
+ const safe = (fn) => {
699
+ try {
700
+ return fn();
701
+ } catch {
702
+ return;
703
+ }
704
+ };
705
+ return {
706
+ config: getFetchingConfig(),
707
+ restBaseUrl: safe(() => getRestBaseUrl(configBaseUrl)),
708
+ odataBaseUrl: safe(() => getODataBaseUrl(configBaseUrl)),
709
+ source: safe(() => getODataSource(configBaseUrl)),
710
+ token: getRequestToken()
711
+ };
712
+ }
713
+ const useCreateFetcher = (base) => {
714
+ const { configBaseUrl, ...rest } = base;
715
+ const mockRoute = resolveMockRoute(configBaseUrl, base.url);
716
+ if (mockRoute) return { async response(option) {
717
+ return await serveFromMock(mockRoute, {
718
+ type: option?.type ?? base.type ?? "datasource",
719
+ method: option?.method ?? base.method,
720
+ params: option?.params ?? base.params,
721
+ payload: option?.payload ?? base.payload,
722
+ options: option?.options ?? base.options
723
+ });
724
+ } };
725
+ return createFetcher({
726
+ ...authArgs(configBaseUrl),
727
+ ...rest,
728
+ token: getRequestToken(base.token),
729
+ notif: resolveNotif(Boolean(base.notif)),
730
+ baseUrl: getODataBaseUrl(configBaseUrl, base.baseUrl),
731
+ source: getODataSource(configBaseUrl, base.source)
732
+ });
733
+ };
734
+ function useTryCatchDatasource(opt) {
735
+ return tryCatchDatasource({
736
+ ...opt,
737
+ notif: runtimeOptions.notif || false
738
+ });
739
+ }
740
+ const createStaticDataSource = async (opt) => {
741
+ return await createStaticDatasource(opt);
742
+ };
743
+ const useMyFetchOData = async ({ url, options, type = wrapperDefaults.type, params, notif = wrapperDefaults.notif, headers, selfProxy = wrapperDefaults.selfProxy, method = wrapperDefaults.method, force, allowZero = wrapperDefaults.allowZero, cache = wrapperDefaults.cache, override, baseUrl, configBaseUrl, source, token, payload = {
744
+ data: null,
745
+ keyValue: null,
746
+ keyName: "",
747
+ keyType: ""
748
+ }, ...rest }) => {
749
+ const mockRoute = resolveMockRoute(configBaseUrl, url);
750
+ if (mockRoute) return await serveFromMock(mockRoute, {
751
+ type,
752
+ method,
753
+ params,
754
+ payload,
755
+ options
756
+ });
757
+ return await useFetchOData({
758
+ ...authArgs(configBaseUrl),
759
+ ...rest,
760
+ source: getODataSource(configBaseUrl, source),
761
+ url,
762
+ options,
763
+ override,
764
+ cache,
765
+ type,
766
+ force,
767
+ token: getRequestToken(token),
768
+ notif: resolveNotif(Boolean(notif)),
769
+ allowZero,
770
+ params,
771
+ headers: mergeHeaders(getGlobalHeaders(), headers),
772
+ selfProxy,
773
+ method,
774
+ baseUrl: getODataBaseUrl(configBaseUrl, baseUrl),
775
+ payload
776
+ });
777
+ };
778
+ const useFetchOdataUnique = async ({ url, options, type = wrapperDefaults.type, params, notif = wrapperDefaults.notif, headers, selfProxy = wrapperDefaults.selfProxy, method = wrapperDefaults.method, force, allowZero = wrapperDefaults.allowZero, cache = wrapperDefaults.cache, override, baseUrl, configBaseUrl, source, token, unique, payload = {
779
+ data: null,
780
+ keyValue: null,
781
+ keyName: "",
782
+ keyType: ""
783
+ }, ...rest }) => {
784
+ return await createUniqueFetcher({
785
+ ...authArgs(configBaseUrl),
786
+ ...rest,
787
+ source: getODataSource(configBaseUrl, source),
788
+ url,
789
+ unique,
790
+ options,
791
+ override,
792
+ cache,
793
+ type,
794
+ force,
795
+ token: getRequestToken(token),
796
+ notif: resolveNotif(Boolean(notif)),
797
+ allowZero,
798
+ params,
799
+ headers: mergeHeaders(getGlobalHeaders(), headers),
800
+ selfProxy,
801
+ method,
802
+ baseUrl: getODataBaseUrl(configBaseUrl, baseUrl),
803
+ payload
804
+ });
805
+ };
806
+ async function useMyFetch(url, opt) {
807
+ const { configBaseUrl, ...rest } = opt;
808
+ const mockRoute = resolveMockRoute(configBaseUrl, url);
809
+ if (mockRoute) {
810
+ const response = await mockRoute.mock.request({
811
+ url: mockRoute.url,
812
+ method: opt?.method,
813
+ params: opt?.params,
814
+ payload: opt?.body ?? opt?.payload
815
+ });
816
+ const payload = response.data;
817
+ const data = payload && Array.isArray(payload.value) ? payload.value : payload;
818
+ return {
819
+ statusCode: response.statusCode,
820
+ data: data ?? null,
821
+ message: response.error?.message ?? null,
822
+ all: response.data
823
+ };
824
+ }
825
+ const { config, tokenOptions, expiredBehaviour, unauthCall } = authArgs(configBaseUrl);
826
+ const { config: _ownConfig, tanstack, ...restOptions } = rest;
827
+ const send = (signal) => useNormalFetch(url, {
828
+ ...signal ? { signal } : {},
829
+ tokenOptions,
830
+ expiredBehaviour,
831
+ unauthCall,
832
+ ...restOptions,
833
+ token: getRequestToken(opt.token),
834
+ baseUrl: getRestBaseUrl(configBaseUrl, opt.baseUrl),
835
+ notif: resolveNotif(Boolean(opt?.notif)),
836
+ headers: mergeHeaders(getGlobalHeaders(), opt.headers)
837
+ }, _ownConfig ?? config);
838
+ const runner = tanstack ? tanstackRunner() : void 0;
839
+ if (!runner) return await send();
840
+ const method = String(restOptions.method ?? "GET").toUpperCase();
841
+ try {
842
+ return await runner({
843
+ kind: method === "GET" ? "query" : "mutation",
844
+ key: [
845
+ "mono-fetch",
846
+ method,
847
+ getRestBaseUrl(configBaseUrl, opt.baseUrl) + url,
848
+ restOptions.body ?? null
849
+ ],
850
+ tanstack,
851
+ task: async (signal) => {
852
+ const result = await send(signal);
853
+ if (!result || result.statusCode === 0 || result.statusCode >= 400) throw new FailedFetchResult(result);
854
+ return result;
855
+ }
856
+ });
857
+ } catch (error) {
858
+ if (error instanceof FailedFetchResult) return error.result;
859
+ throw error;
860
+ }
861
+ }
862
+ const loadChuckStores = async (opt) => {
863
+ return await loadChuckStore(opt);
864
+ };
865
+
866
+ //#endregion
867
+ export { createFetcher, configureFetching as monoConfigureFetching, useCreateFetcher as monoCreateFetcher, useMyFetch as monoFetch, useMyFetchOData as monoFetchOdata, useMyFetchOData as monoOdataFetch, useFetchOdataUnique as monoFetchOdataUnique, useFetchOdataUnique as monoOdataFetchUnique, getFetchingRuntime as monoFetchingRuntime, loadChuckStores as monoLoadChuckStores, monoMockDb, getODataBaseUrl as monoOdataBaseUrl, getODataSource as monoOdataSource, getRequestToken as monoRequestToken, resetFetchingConfig as monoResetFetchingConfig, getRestBaseUrl as monoRestBaseUrl, createStaticDataSource as monoStaticDataSource, useTryCatchDatasource as monoTryCatchDatasource, promiseWrapper, resetMonoMockDb };