@kivacore/app-utils 0.0.0 → 0.22.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 (41) hide show
  1. package/README.md +1515 -1
  2. package/dist/index.d.ts +82 -0
  3. package/dist/index.js +2304 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.native.js +4695 -0
  6. package/dist/index.native.js.map +1 -0
  7. package/dist/query.d.ts +54 -0
  8. package/dist/query.js +269 -0
  9. package/dist/query.js.map +1 -0
  10. package/dist/types-GNkXRpu4.d.ts +754 -0
  11. package/package.json +57 -3
  12. package/src/app-config-client.ts +48 -0
  13. package/src/async-each-helper.ts +98 -0
  14. package/src/brand-client.ts +80 -0
  15. package/src/data-form-client.ts +85 -0
  16. package/src/data-source-client.ts +298 -0
  17. package/src/data-source-queries.ts +149 -0
  18. package/src/data-view-client.ts +92 -0
  19. package/src/date-utils.test.ts +48 -0
  20. package/src/date-utils.ts +146 -0
  21. package/src/envelope-interceptor.ts +65 -0
  22. package/src/get-tenant-preferences.test.ts +42 -0
  23. package/src/get-tenant-preferences.ts +30 -0
  24. package/src/handlebars-async-helpers.d.ts +12 -0
  25. package/src/index.native.ts +9 -0
  26. package/src/index.ts +88 -0
  27. package/src/inventory-client.ts +725 -0
  28. package/src/jsonata-helpers.ts +545 -0
  29. package/src/number-utils.ts +305 -0
  30. package/src/php-date-formatter.d.ts +8 -0
  31. package/src/query.ts +5 -0
  32. package/src/shims/stream.ts +11 -0
  33. package/src/template-engine.test.ts +47 -0
  34. package/src/template-engine.ts +298 -0
  35. package/src/types.ts +871 -0
  36. package/src/unwrap-envelope.ts +51 -0
  37. package/src/user-app-config-client.ts +44 -0
  38. package/src/user-identity-client.ts +21 -0
  39. package/tsconfig.json +9 -0
  40. package/tsup.config.ts +71 -0
  41. package/vitest.config.mts +13 -0
package/dist/index.js ADDED
@@ -0,0 +1,2304 @@
1
+ import DateFormatter from 'php-date-formatter';
2
+ import Handlebars from 'handlebars';
3
+ import jsonata from 'jsonata';
4
+ import { JSONPath } from 'jsonpath-plus';
5
+ import { endOfQuarter, endOfToday, endOfWeek, endOfMonth, endOfDay, startOfQuarter, startOfToday, startOfWeek, startOfMonth, startOfDay, differenceInBusinessDays, differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays, differenceInWeeks, differenceInMonths, differenceInYears, isPast, isEqual as isEqual$1, isBefore, isAfter, subMilliseconds, subSeconds, subMinutes, subHours, subDays, subWeeks, subMonths, subYears, addMilliseconds, addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears, formatRelative, formatISO, formatDuration, formatDistanceToNowStrict, formatDistanceToNow, formatDistanceStrict, formatDistance, format } from 'date-fns';
6
+
7
+ var __create = Object.create;
8
+ var __defProp = Object.defineProperty;
9
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
10
+ var __getOwnPropNames = Object.getOwnPropertyNames;
11
+ var __getProtoOf = Object.getPrototypeOf;
12
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
13
+ var __esm = (fn, res, err) => function __init() {
14
+ if (err) throw err[0];
15
+ try {
16
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
17
+ } catch (e) {
18
+ throw err = [e], e;
19
+ }
20
+ };
21
+ var __commonJS = (cb, mod) => function __require() {
22
+ try {
23
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
24
+ } catch (e) {
25
+ throw mod = 0, e;
26
+ }
27
+ };
28
+ var __export = (target, all) => {
29
+ for (var name in all)
30
+ __defProp(target, name, { get: all[name], enumerable: true });
31
+ };
32
+ var __copyProps = (to, from, except, desc) => {
33
+ if (from && typeof from === "object" || typeof from === "function") {
34
+ for (let key of __getOwnPropNames(from))
35
+ if (!__hasOwnProp.call(to, key) && key !== except)
36
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
37
+ }
38
+ return to;
39
+ };
40
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
41
+ // If the importer is in node compatibility mode or this is not an ESM
42
+ // file that has been converted to a CommonJS file using a Babel-
43
+ // compatible transform (i.e. "__esModule" has not been set), then set
44
+ // "default" to the CommonJS "module.exports" for node compatibility.
45
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
46
+ mod
47
+ ));
48
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
49
+
50
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/package.json
51
+ var require_package = __commonJS({
52
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/package.json"(exports, module) {
53
+ module.exports = {
54
+ name: "handlebars-async-helpers",
55
+ version: "1.0.6",
56
+ description: "Adding async function support to handlebars helpers",
57
+ main: "index.js",
58
+ scripts: {
59
+ test: "mocha --ui bdd --recursive --timeout 15000"
60
+ },
61
+ repository: "https://github.com/gastonrobledo/handlebars-async-helpers",
62
+ author: "Gaston Robledo",
63
+ license: "MIT",
64
+ peerDependencies: {
65
+ handlebars: "4.7.6"
66
+ },
67
+ devDependencies: {
68
+ handlebars: "^4.7.6",
69
+ eslint: "^8.9.0",
70
+ "eslint-config-airbnb": "^19.0.4",
71
+ "eslint-config-standard": "^12.0.0",
72
+ "eslint-plugin-import": "^2.14.0",
73
+ "eslint-plugin-node": "^8.0.0",
74
+ "eslint-plugin-promise": "^4.0.1",
75
+ "eslint-plugin-standard": "^4.0.0",
76
+ mocha: "^9.2.0",
77
+ should: "^13.2.3"
78
+ }
79
+ };
80
+ }
81
+ });
82
+
83
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/utils.js
84
+ var require_utils = __commonJS({
85
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/utils.js"(exports, module) {
86
+ function blockParams(params, ids) {
87
+ params.path = ids;
88
+ return params;
89
+ }
90
+ function extend(obj) {
91
+ for (let i = 1; i < arguments.length; i++) {
92
+ for (const key in arguments[i]) {
93
+ if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
94
+ obj[key] = arguments[i][key];
95
+ }
96
+ }
97
+ }
98
+ return obj;
99
+ }
100
+ function appendContextPath(contextPath, id) {
101
+ return (contextPath ? `${contextPath}.` : "") + id;
102
+ }
103
+ function createFrame(object) {
104
+ const frame = extend({}, object);
105
+ frame._parent = object;
106
+ return frame;
107
+ }
108
+ function isEmpty(value) {
109
+ if (!value && value !== 0) {
110
+ return true;
111
+ }
112
+ if (Array.isArray(value) && value.length === 0) {
113
+ return true;
114
+ }
115
+ return false;
116
+ }
117
+ function isPromise(value) {
118
+ return typeof value === "object" && value !== null && typeof value.then === "function";
119
+ }
120
+ module.exports = {
121
+ blockParams,
122
+ extend,
123
+ appendContextPath,
124
+ createFrame,
125
+ isEmpty,
126
+ isPromise
127
+ };
128
+ }
129
+ });
130
+
131
+ // src/shims/stream.ts
132
+ var stream_exports = {};
133
+ __export(stream_exports, {
134
+ Readable: () => Readable,
135
+ default: () => stream_default
136
+ });
137
+ var Readable, stream_default;
138
+ var init_stream = __esm({
139
+ "src/shims/stream.ts"() {
140
+ Readable = class {
141
+ };
142
+ stream_default = { Readable };
143
+ }
144
+ });
145
+
146
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/each.js
147
+ var require_each = __commonJS({
148
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/each.js"(exports, module) {
149
+ var {
150
+ appendContextPath,
151
+ createFrame,
152
+ blockParams,
153
+ isPromise
154
+ } = require_utils();
155
+ var { Readable: Readable2 } = (init_stream(), __toCommonJS(stream_exports));
156
+ module.exports = (handlebars) => {
157
+ handlebars.registerHelper("each", async function(context, options) {
158
+ if (!options) {
159
+ throw new Error("Must pass iterator to #each");
160
+ }
161
+ let { fn } = options, { inverse } = options, i = 0, ret = [], data, contextPath;
162
+ if (options.data && options.ids) {
163
+ contextPath = `${appendContextPath(options.data.contextPath, options.ids[0])}.`;
164
+ }
165
+ if (typeof context === "function") {
166
+ context = context.call(this);
167
+ }
168
+ if (options.data) {
169
+ data = createFrame(options.data);
170
+ }
171
+ async function execIteration(field, index, last) {
172
+ if (data) {
173
+ data.key = field;
174
+ data.index = index;
175
+ data.first = index === 0;
176
+ data.last = !!last;
177
+ if (contextPath) {
178
+ data.contextPath = contextPath + field;
179
+ }
180
+ }
181
+ ret.push(await fn(context[field], {
182
+ data,
183
+ blockParams: blockParams(
184
+ [context[field], field],
185
+ [contextPath + field, null]
186
+ )
187
+ }));
188
+ }
189
+ if (context && typeof context === "object") {
190
+ if (isPromise(context)) {
191
+ context = await context;
192
+ }
193
+ if (Array.isArray(context)) {
194
+ for (let j = context.length; i < j; i++) {
195
+ if (i in context) {
196
+ await execIteration(i, i, i === context.length - 1);
197
+ }
198
+ }
199
+ } else if (global.Symbol && context[global.Symbol.iterator]) {
200
+ const newContext = [], iterator = context[global.Symbol.iterator]();
201
+ for (let it = iterator.next(); !it.done; it = iterator.next()) {
202
+ newContext.push(it.value);
203
+ }
204
+ context = newContext;
205
+ for (let j = context.length; i < j; i++) {
206
+ await execIteration(i, i, i === context.length - 1);
207
+ }
208
+ } else if (context instanceof Readable2) {
209
+ const newContext = [];
210
+ await new Promise((resolve, reject) => {
211
+ context.on("data", (item) => {
212
+ newContext.push(item);
213
+ }).on("end", async () => {
214
+ context = newContext;
215
+ for (let j = context.length; i < j; i++) {
216
+ await execIteration(i, i, i === context.length - 1);
217
+ }
218
+ resolve();
219
+ }).once("error", (e) => reject(e));
220
+ });
221
+ } else {
222
+ let priorKey;
223
+ for (const key of Object.keys(context)) {
224
+ if (priorKey !== void 0) {
225
+ await execIteration(priorKey, i - 1);
226
+ }
227
+ priorKey = key;
228
+ i++;
229
+ }
230
+ if (priorKey !== void 0) {
231
+ await execIteration(priorKey, i - 1, true);
232
+ }
233
+ }
234
+ }
235
+ if (i === 0) {
236
+ ret = inverse(this);
237
+ }
238
+ return ret.join("");
239
+ });
240
+ };
241
+ }
242
+ });
243
+
244
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/if.js
245
+ var require_if = __commonJS({
246
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/if.js"(exports, module) {
247
+ var { isPromise, isEmpty } = require_utils();
248
+ module.exports = (handlebars) => {
249
+ handlebars.registerHelper("if", async function(conditional, options) {
250
+ if (arguments.length !== 2) {
251
+ throw new Error("#if requires exactly one argument");
252
+ }
253
+ if (typeof conditional === "function") {
254
+ conditional = conditional.call(this);
255
+ } else if (isPromise(conditional)) {
256
+ conditional = await conditional;
257
+ }
258
+ if (!options.hash.includeZero && !conditional || isEmpty(conditional)) {
259
+ return options.inverse(this);
260
+ } else {
261
+ return options.fn(this);
262
+ }
263
+ });
264
+ handlebars.registerHelper("unless", function(conditional, options) {
265
+ if (arguments.length !== 2) {
266
+ throw new Error("#unless requires exactly one argument");
267
+ }
268
+ return handlebars.helpers["if"].call(this, conditional, {
269
+ fn: options.inverse,
270
+ inverse: options.fn,
271
+ hash: options.hash
272
+ });
273
+ });
274
+ };
275
+ }
276
+ });
277
+
278
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/with.js
279
+ var require_with = __commonJS({
280
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/with.js"(exports, module) {
281
+ var { isPromise, isEmpty, createFrame, appendContextPath, blockParams } = require_utils();
282
+ module.exports = (handlebars) => {
283
+ handlebars.registerHelper("with", async function(context, options) {
284
+ if (arguments.length !== 2) {
285
+ throw new Error("#with requires exactly one argument");
286
+ }
287
+ if (typeof context === "function") {
288
+ context = context.call(this);
289
+ } else if (isPromise(context)) {
290
+ context = await context;
291
+ }
292
+ const { fn } = options;
293
+ if (!isEmpty(context)) {
294
+ let { data } = options;
295
+ if (options.data && options.ids) {
296
+ data = createFrame(options.data);
297
+ data.contextPath = appendContextPath(
298
+ options.data.contextPath,
299
+ options.ids[0]
300
+ );
301
+ }
302
+ return fn(context, {
303
+ data,
304
+ blockParams: blockParams([context], [data && data.contextPath])
305
+ });
306
+ }
307
+ return options.inverse(this);
308
+ });
309
+ };
310
+ }
311
+ });
312
+
313
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/index.js
314
+ var require_helpers = __commonJS({
315
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/index.js"(exports, module) {
316
+ module.exports = {
317
+ registerCoreHelpers: (handlebars) => {
318
+ require_each()(handlebars);
319
+ require_if()(handlebars);
320
+ require_with()(handlebars);
321
+ }
322
+ };
323
+ }
324
+ });
325
+
326
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/index.js
327
+ var require_handlebars_async_helpers = __commonJS({
328
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/index.js"(exports, module) {
329
+ var app = require_package();
330
+ var { registerCoreHelpers } = require_helpers();
331
+ var isPromise = (obj) => !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
332
+ function asyncHelpers2(hbs) {
333
+ const handlebars = hbs.create(), asyncCompiler = class extends hbs.JavaScriptCompiler {
334
+ constructor() {
335
+ super();
336
+ this.compiler = asyncCompiler;
337
+ }
338
+ mergeSource(varDeclarations) {
339
+ const sources = super.mergeSource(varDeclarations);
340
+ sources.prepend("return (async () => {");
341
+ sources.add(" })()");
342
+ return sources;
343
+ }
344
+ appendToBuffer(source, location, explicit) {
345
+ if (!Array.isArray(source)) {
346
+ source = [source];
347
+ }
348
+ source = this.source.wrap(source, location);
349
+ if (this.environment.isSimple) {
350
+ return ["return await ", source, ";"];
351
+ }
352
+ if (explicit) {
353
+ return ["buffer += await ", source, ";"];
354
+ }
355
+ source.appendToBuffer = true;
356
+ source.prepend("await ");
357
+ return source;
358
+ }
359
+ };
360
+ handlebars.JavaScriptCompiler = asyncCompiler;
361
+ const _compile = handlebars.compile, _template = handlebars.VM.template, _escapeExpression = handlebars.escapeExpression, escapeExpression = function(value) {
362
+ if (isPromise(value)) {
363
+ return value.then((v) => _escapeExpression(v));
364
+ }
365
+ return _escapeExpression(value);
366
+ };
367
+ function lookupProperty(containerLookupProperty) {
368
+ return function(parent, propertyName) {
369
+ if (isPromise(parent)) {
370
+ return parent.then((p) => containerLookupProperty(p, propertyName));
371
+ }
372
+ return containerLookupProperty(parent, propertyName);
373
+ };
374
+ }
375
+ handlebars.template = function(spec) {
376
+ spec.main_d = (prog, props, container, depth, data, blockParams, depths) => async (context) => {
377
+ container.escapeExpression = escapeExpression;
378
+ container.lookupProperty = lookupProperty(container.lookupProperty);
379
+ const v = spec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
380
+ return v;
381
+ };
382
+ return _template(spec, handlebars);
383
+ };
384
+ handlebars.compile = function(template, options) {
385
+ const compiled = _compile.apply(handlebars, [template, { ...options }]);
386
+ return function(context, execOptions) {
387
+ context = context || {};
388
+ return compiled.call(handlebars, context, execOptions);
389
+ };
390
+ };
391
+ handlebars.ASYNC_VERSION = app.version;
392
+ registerCoreHelpers(handlebars);
393
+ return handlebars;
394
+ }
395
+ module.exports = asyncHelpers2;
396
+ }
397
+ });
398
+
399
+ // src/unwrap-envelope.ts
400
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set([
401
+ "data",
402
+ "success",
403
+ "meta",
404
+ "error",
405
+ "message"
406
+ ]);
407
+ function unwrapEnvelope(response) {
408
+ if (response !== null && typeof response === "object" && !Array.isArray(response)) {
409
+ const keys = Object.keys(response);
410
+ const looksLikeEnvelope2 = "data" in response && keys.every((key) => ENVELOPE_KEYS.has(key));
411
+ if (looksLikeEnvelope2) {
412
+ return response.data;
413
+ }
414
+ }
415
+ return response;
416
+ }
417
+
418
+ // src/get-tenant-preferences.ts
419
+ async function getTenantPreferences(client) {
420
+ return client.get("/v1/tenant/preferences");
421
+ }
422
+ async function getTenantPreferenceSummary(client) {
423
+ const { preferences, tenant, product } = unwrapEnvelope(
424
+ await client.get("/v1/tenant/preferences", { includeEnums: false })
425
+ );
426
+ return {
427
+ preferences: preferences ? {
428
+ ...preferences,
429
+ date_format: preferences.date_format ?? preferences.dateFormat,
430
+ date_time_format: preferences.date_time_format ?? preferences.dateTimeFormat,
431
+ long_date_format: preferences.long_date_format ?? preferences.longDateFormat,
432
+ time_format: preferences.time_format ?? preferences.timeFormat,
433
+ time_zone: preferences.time_zone ?? preferences.timeZone,
434
+ thousand_separator: preferences.thousand_separator ?? preferences.thousandSeparator,
435
+ decimal_separator: preferences.decimal_separator ?? preferences.decimalSeparator,
436
+ decimal_precision: preferences.decimal_precision ?? preferences.decimalPrecision
437
+ } : null,
438
+ tenant,
439
+ product
440
+ };
441
+ }
442
+ var TIMEZONE_SUFFIX_RE = /([+-]\d{2}:\d{2}|Z)\s*$/;
443
+ function applyTimezone(date, timezone) {
444
+ return new Date(date.toLocaleString("en-US", { timeZone: timezone }));
445
+ }
446
+ function parseDate(value) {
447
+ return new Date(value);
448
+ }
449
+ function parseDatetime(value) {
450
+ const hasTimezone = TIMEZONE_SUFFIX_RE.test(value);
451
+ return hasTimezone ? new Date(value) : /* @__PURE__ */ new Date(`${value}Z`);
452
+ }
453
+ var dateNameCache = /* @__PURE__ */ new Map();
454
+ function partOf(formatter, date, type) {
455
+ return formatter.formatToParts(date).find((part) => part.type === type)?.value ?? "";
456
+ }
457
+ function getDateNames(locale) {
458
+ const tag = locale?.trim().replace(/_/g, "-");
459
+ if (!tag || /^en(-|$)/i.test(tag)) return null;
460
+ const cached = dateNameCache.get(tag);
461
+ if (cached !== void 0) return cached;
462
+ let names = null;
463
+ try {
464
+ const weekdayLong = new Intl.DateTimeFormat(tag, { weekday: "long", timeZone: "UTC" });
465
+ const weekdayShort = new Intl.DateTimeFormat(tag, { weekday: "short", timeZone: "UTC" });
466
+ const monthLong = new Intl.DateTimeFormat(tag, { day: "numeric", month: "long", timeZone: "UTC" });
467
+ const monthShort = new Intl.DateTimeFormat(tag, { day: "numeric", month: "short", timeZone: "UTC" });
468
+ const weekdays = Array.from({ length: 7 }, (_, i) => new Date(Date.UTC(2023, 0, 1 + i)));
469
+ const months = Array.from({ length: 12 }, (_, i) => new Date(Date.UTC(2023, i, 15)));
470
+ names = {
471
+ days: weekdays.map((date) => partOf(weekdayLong, date, "weekday")),
472
+ daysShort: weekdays.map((date) => partOf(weekdayShort, date, "weekday")),
473
+ months: months.map((date) => partOf(monthLong, date, "month")),
474
+ monthsShort: months.map((date) => partOf(monthShort, date, "month"))
475
+ };
476
+ } catch {
477
+ names = null;
478
+ }
479
+ dateNameCache.set(tag, names);
480
+ return names;
481
+ }
482
+ function createFormatter(locale) {
483
+ const formatter = new DateFormatter();
484
+ const names = getDateNames(locale);
485
+ if (names) {
486
+ const instance = formatter;
487
+ instance.dateSettings = { ...instance.dateSettings, ...names };
488
+ }
489
+ return formatter;
490
+ }
491
+ function createDateUtils(config) {
492
+ const { preferences, userTimezone = "UTC", locale } = config;
493
+ const formatter = createFormatter(locale);
494
+ function formatDate(date, options) {
495
+ if (!date) return null;
496
+ const format = options?.format ?? preferences.date_format ?? "Y-m-d";
497
+ const timezone = options?.timezone ?? userTimezone;
498
+ const parsed = applyTimezone(
499
+ typeof date === "string" ? parseDate(date) : date,
500
+ timezone
501
+ );
502
+ return formatter.formatDate(parsed, format);
503
+ }
504
+ function formatDateTime(date, options) {
505
+ if (!date) return null;
506
+ const format = options?.format ?? preferences.date_time_format ?? "Y-m-d H:i:s";
507
+ const timezone = options?.timezone ?? userTimezone;
508
+ const parsed = applyTimezone(
509
+ typeof date === "string" ? parseDatetime(date) : date,
510
+ timezone
511
+ );
512
+ return formatter.formatDate(parsed, format);
513
+ }
514
+ function formatDateLong(date, options) {
515
+ if (!date) return null;
516
+ const format = options?.format ?? preferences.long_date_format ?? "Y-m-d H:i:s";
517
+ const timezone = options?.timezone ?? userTimezone;
518
+ const parsed = applyTimezone(
519
+ typeof date === "string" ? parseDate(date) : date,
520
+ timezone
521
+ );
522
+ return formatter.formatDate(parsed, format);
523
+ }
524
+ function toUserTimezone(date) {
525
+ const parsed = typeof date === "string" ? parseDatetime(date) : date;
526
+ return applyTimezone(parsed, userTimezone);
527
+ }
528
+ return {
529
+ formatDate,
530
+ formatDateTime,
531
+ formatDateLong,
532
+ toUserTimezone
533
+ };
534
+ }
535
+
536
+ // src/number-utils.ts
537
+ function createNumberUtils(config) {
538
+ const { preferences } = config;
539
+ function formatNumber(value, options) {
540
+ if (value == null) return null;
541
+ const precision = options?.decimalPrecision ?? preferences.decimal_precision ?? 2;
542
+ const thousandSep = options?.thousandSeparator !== void 0 ? options.thousandSeparator : preferences.thousand_separator;
543
+ const decimalSep = options?.decimalSeparator || preferences.decimal_separator;
544
+ if (thousandSep && decimalSep) {
545
+ const formatted = parseFloat(String(value)).toFixed(precision);
546
+ const parts = formatted.split(".");
547
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);
548
+ return parts.join(decimalSep);
549
+ }
550
+ const resolvedLocale = preferences.locale?.replace("_", "-") || "en-US";
551
+ return value.toLocaleString(resolvedLocale, {
552
+ minimumFractionDigits: precision,
553
+ maximumFractionDigits: precision,
554
+ useGrouping: !!thousandSep
555
+ });
556
+ }
557
+ return { formatNumber };
558
+ }
559
+ var THOUSAND_SEP = ".";
560
+ var DECIMAL_SEP = ",";
561
+ function phpNumberFormat(value, decimals = 2) {
562
+ const num = Number(value);
563
+ if (isNaN(num)) return `0${DECIMAL_SEP}${"0".repeat(decimals)}`;
564
+ const [intPart, decPart] = num.toFixed(decimals).split(".");
565
+ return `${intPart.replace(/\B(?=(\d{3})+(?!\d))/g, THOUSAND_SEP)}${DECIMAL_SEP}${decPart}`;
566
+ }
567
+ var DIGITS_1_TR = [
568
+ "",
569
+ "B\u0130R",
570
+ "\u0130K\u0130",
571
+ "\xDC\xC7",
572
+ "D\xD6RT",
573
+ "BE\u015E",
574
+ "ALTI",
575
+ "YED\u0130",
576
+ "SEK\u0130Z",
577
+ "DOKUZ"
578
+ ];
579
+ var DIGITS_10_TR = [
580
+ "",
581
+ "ON",
582
+ "Y\u0130RM\u0130",
583
+ "OTUZ",
584
+ "KIRK",
585
+ "ELL\u0130",
586
+ "ALTMI\u015E",
587
+ "YETM\u0130\u015E",
588
+ "SEKSEN",
589
+ "DOKSAN"
590
+ ];
591
+ var DIGITS_100_TR = [
592
+ "",
593
+ "Y\xDCZ",
594
+ "\u0130K\u0130Y\xDCZ",
595
+ "\xDC\xC7Y\xDCZ",
596
+ "D\xD6RTY\xDCZ",
597
+ "BE\u015EY\xDCZ",
598
+ "ALTIY\xDCZ",
599
+ "YED\u0130Y\xDCZ",
600
+ "SEK\u0130ZY\xDCZ",
601
+ "DOKUZY\xDCZ"
602
+ ];
603
+ var SCALE_TR = [
604
+ "",
605
+ "",
606
+ "B\u0130N",
607
+ "M\u0130LYON",
608
+ "M\u0130LYAR",
609
+ "TR\u0130LYON",
610
+ "KAT\u0130R\u0130LYON",
611
+ "KENT\u0130LYON",
612
+ "SEKS\u0130LYON",
613
+ "SEPT\u0130LYON",
614
+ "OKT\u0130LYON"
615
+ ];
616
+ function toWordTR(value, useSpaces) {
617
+ const formatted = phpNumberFormat(value);
618
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
619
+ const groups = intPart.split(THOUSAND_SEP).reverse();
620
+ let integerStr = "";
621
+ groups.forEach((group, idx) => {
622
+ const padded = group.padStart(3, "0");
623
+ const d1 = parseInt(padded[0], 10);
624
+ const d2 = parseInt(padded[1], 10);
625
+ const d3 = parseInt(padded[2], 10);
626
+ const groupIndex = groups.length - idx;
627
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
628
+ integerStr += " ";
629
+ } else {
630
+ integerStr += ` ${DIGITS_100_TR[d1]} ${DIGITS_10_TR[d2]} ${DIGITS_1_TR[d3]} `;
631
+ }
632
+ integerStr += SCALE_TR[groupIndex] || "";
633
+ });
634
+ const paddedDec = decPart.padEnd(2, "0");
635
+ const decStr = `${DIGITS_10_TR[parseInt(paddedDec[0], 10)]} ${DIGITS_1_TR[parseInt(paddedDec[1], 10)]}`;
636
+ if (!useSpaces) {
637
+ integerStr = integerStr.replace(/ /g, "");
638
+ }
639
+ return [integerStr.replace(/ {2,}/g, " ").trim(), decStr.replace(/ {2,}/g, " ").trim()];
640
+ }
641
+ var DIGITS_1_EN = [
642
+ "",
643
+ "ONE",
644
+ "TWO",
645
+ "THREE",
646
+ "FOUR",
647
+ "FIVE",
648
+ "SIX",
649
+ "SEVEN",
650
+ "EIGHT",
651
+ "NINE"
652
+ ];
653
+ var DIGITS_TEEN_EN = [
654
+ "",
655
+ "ELEVEN",
656
+ "TWELVE",
657
+ "THIRTEEN",
658
+ "FOURTEEN",
659
+ "FIFTEEN",
660
+ "SIXTEEN",
661
+ "SEVENTEEN",
662
+ "EIGHTEEN",
663
+ "NINETEEN"
664
+ ];
665
+ var DIGITS_10_EN = [
666
+ "",
667
+ "TEN",
668
+ "TWENTY",
669
+ "THIRTY",
670
+ "FORTY",
671
+ "FIFTY",
672
+ "SIXTY",
673
+ "SEVENTY",
674
+ "EIGHTY",
675
+ "NINETY"
676
+ ];
677
+ var DIGITS_100_EN = [
678
+ "",
679
+ "HUNDRED",
680
+ "TWO HUNDRED",
681
+ "THREE HUNDRED",
682
+ "FOUR HUNDRED",
683
+ "FIVE HUNDRED",
684
+ "SIX HUNDRED",
685
+ "SEVEN HUNDRED",
686
+ "EIGHT HUNDRED",
687
+ "NINE HUNDRED"
688
+ ];
689
+ var SCALE_EN = [
690
+ "",
691
+ "",
692
+ "THOUSAND",
693
+ "MILLION",
694
+ "BILLION",
695
+ "TRILLION",
696
+ "QUADRILLION",
697
+ "QUINTILLION",
698
+ "SEXTILLION",
699
+ "SEPTILLION",
700
+ "OCTILLION"
701
+ ];
702
+ function toWordEN(value, useSpaces) {
703
+ const formatted = phpNumberFormat(value);
704
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
705
+ const groups = intPart.split(THOUSAND_SEP).reverse();
706
+ let integerStr = "";
707
+ groups.forEach((group, idx) => {
708
+ const padded = group.padStart(3, "0");
709
+ const d1 = parseInt(padded[0], 10);
710
+ const d2 = parseInt(padded[1], 10);
711
+ const d3 = parseInt(padded[2], 10);
712
+ const groupIndex = groups.length - idx;
713
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
714
+ integerStr += " ";
715
+ } else if (d2 === 1 && d3 >= 1) {
716
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_TEEN_EN[d3]} `;
717
+ } else {
718
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_10_EN[d2]} ${DIGITS_1_EN[d3]} `;
719
+ }
720
+ integerStr += SCALE_EN[groupIndex] || "";
721
+ });
722
+ const paddedDec = decPart.padEnd(2, "0");
723
+ const dec1 = parseInt(paddedDec[0], 10);
724
+ const dec2 = parseInt(paddedDec[1], 10);
725
+ const decStr = dec1 === 1 && dec2 >= 1 ? DIGITS_TEEN_EN[dec2] : `${DIGITS_10_EN[dec1]} ${DIGITS_1_EN[dec2]}`;
726
+ if (!useSpaces) {
727
+ integerStr = integerStr.replace(/ /g, "");
728
+ }
729
+ return [integerStr.replace(/ {2,}/g, " ").trim(), decStr.replace(/ {2,}/g, " ").trim()];
730
+ }
731
+ var WORD_CONVERTERS = {
732
+ TR: toWordTR,
733
+ EN: toWordEN
734
+ };
735
+ var CURRENCY_LABELS = {
736
+ TRY: { unit: "T\xDCRK L\u0130RASI", subunit: "KURU\u015E" },
737
+ EUR: { unit: "EURO", subunit: "CENT" },
738
+ USD: { unit: "DOLAR", subunit: "CENT" },
739
+ GBP: { unit: "STERL\u0130N", subunit: "PENNY" },
740
+ JPY: { unit: "YEN", subunit: "SEN" }
741
+ };
742
+ function formatNumberToWords(value, options) {
743
+ const lang = options?.lang ?? "TR";
744
+ const currency = options?.currency ?? "TRY";
745
+ const useSpaces = options?.useSpaces ?? false;
746
+ const num = value ?? 0;
747
+ const [intWords, decWords] = WORD_CONVERTERS[lang](num, useSpaces);
748
+ const labels = CURRENCY_LABELS[currency] ?? CURRENCY_LABELS.TRY;
749
+ let result = "";
750
+ if (intWords) {
751
+ result += `${intWords} ${labels.unit}`;
752
+ }
753
+ if (decWords) {
754
+ result += ` ${decWords} ${labels.subunit}`;
755
+ }
756
+ return result.trim();
757
+ }
758
+ function formatDurationAsTime(seconds) {
759
+ const hours = Math.floor(seconds / 3600);
760
+ const minutes = Math.floor(seconds % 3600 / 60);
761
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
762
+ }
763
+ function formatDurationAsHours(seconds, decimalPrecision = 2) {
764
+ if (!seconds) return "0";
765
+ return (seconds / 3600).toFixed(decimalPrecision);
766
+ }
767
+ function formatDurationAsWords(seconds) {
768
+ const hours = Math.floor(seconds / 3600);
769
+ const minutes = Math.floor(seconds % 3600 / 60);
770
+ let result = "";
771
+ if (hours > 0) {
772
+ result += `${hours} hr${hours !== 1 ? "s" : ""} `;
773
+ }
774
+ if (minutes > 0) {
775
+ result += `${minutes} min${minutes !== 1 ? "s" : ""}`;
776
+ }
777
+ return result.trim() || "0 mins";
778
+ }
779
+
780
+ // src/template-engine.ts
781
+ var import_handlebars_async_helpers = __toESM(require_handlebars_async_helpers());
782
+
783
+ // src/async-each-helper.ts
784
+ function isPromiseLike(value) {
785
+ return value != null && typeof value.then === "function";
786
+ }
787
+ function createAsyncEachHelper(handlebars) {
788
+ const {
789
+ appendContextPath,
790
+ blockParams,
791
+ createFrame
792
+ } = handlebars.Utils;
793
+ return async function each(rawContext, options) {
794
+ if (!options) {
795
+ throw new Error("Must pass iterator to #each");
796
+ }
797
+ const fn = options.fn;
798
+ const inverse = options.inverse;
799
+ let context = typeof rawContext === "function" ? rawContext.call(this) : rawContext;
800
+ if (isPromiseLike(context)) {
801
+ context = await context;
802
+ }
803
+ const contextPath = options.data && options.ids ? `${appendContextPath(options.data.contextPath, options.ids[0] ?? "")}.` : void 0;
804
+ const data = options.data ? createFrame(options.data) : void 0;
805
+ const parts = [];
806
+ const renderItem = async (item, key, index, last) => {
807
+ if (data) {
808
+ data.key = key;
809
+ data.index = index;
810
+ data.first = index === 0;
811
+ data.last = last;
812
+ if (contextPath) {
813
+ data.contextPath = contextPath + key;
814
+ }
815
+ }
816
+ parts.push(String(await fn(item, {
817
+ data,
818
+ blockParams: blockParams([item, key], [contextPath ? contextPath + key : void 0, null])
819
+ }) ?? ""));
820
+ };
821
+ if (context && typeof context === "object") {
822
+ if (Array.isArray(context)) {
823
+ for (let i = 0; i < context.length; i += 1) {
824
+ if (i in context) {
825
+ await renderItem(context[i], i, i, i === context.length - 1);
826
+ }
827
+ }
828
+ } else if (typeof context[Symbol.iterator] === "function") {
829
+ const items = Array.from(context);
830
+ for (let i = 0; i < items.length; i += 1) {
831
+ await renderItem(items[i], i, i, i === items.length - 1);
832
+ }
833
+ } else {
834
+ const keys = Object.keys(context);
835
+ for (let i = 0; i < keys.length; i += 1) {
836
+ const key = keys[i];
837
+ await renderItem(context[key], key, i, i === keys.length - 1);
838
+ }
839
+ }
840
+ }
841
+ if (parts.length === 0) {
842
+ return String(await inverse(this) ?? "");
843
+ }
844
+ return parts.join("");
845
+ };
846
+ }
847
+ function dateWrapper(fn) {
848
+ return ((...args) => {
849
+ if (args[0] == null || args[0] === "") return null;
850
+ if (typeof args[0] === "string") args[0] = new Date(args[0]);
851
+ return fn(...args);
852
+ });
853
+ }
854
+ function formatDecimal(...args) {
855
+ if (!args || args.length < 1) {
856
+ throw new Error("Missing required arguments.");
857
+ }
858
+ const numberValue = args[0];
859
+ if (typeof numberValue !== "number" || isNaN(numberValue) || !isFinite(numberValue)) {
860
+ throw new Error("The first argument must be a valid number.");
861
+ }
862
+ if (typeof args[1] === "string" && args[1].includes("-")) {
863
+ return new Intl.NumberFormat(args[1]).format(numberValue);
864
+ }
865
+ const decimalPrecision = args[1] ?? 2;
866
+ const decimalSeparator = args[2] || ".";
867
+ const thousandsSeparator = args[3] || (decimalSeparator === "," ? "." : ",");
868
+ if (!Number.isInteger(decimalPrecision)) {
869
+ throw new Error("Invalid decimal precision.");
870
+ }
871
+ const validSeparators = [".", ","];
872
+ if (decimalSeparator === thousandsSeparator || !validSeparators.includes(decimalSeparator) || !validSeparators.includes(thousandsSeparator)) {
873
+ throw new Error("Invalid separators.");
874
+ }
875
+ const integerPart = Math.floor(numberValue);
876
+ const decimalPart = Math.abs(numberValue - integerPart);
877
+ const integerString = integerPart.toString().replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
878
+ const decimalString = decimalPart.toFixed(decimalPrecision).slice(2);
879
+ return decimalPrecision > 0 ? `${integerString}${decimalSeparator}${decimalString}` : integerString;
880
+ }
881
+ function formatMoney(...args) {
882
+ if (!args || args.length < 1) {
883
+ throw new Error("Missing required arguments.");
884
+ }
885
+ const numberValue = args[0];
886
+ if (typeof numberValue !== "number" || isNaN(numberValue) || !isFinite(numberValue)) {
887
+ throw new Error("The first argument must be a valid number.");
888
+ }
889
+ if (typeof args[1] === "string" && args[1].includes("-")) {
890
+ return new Intl.NumberFormat(args[1], {
891
+ style: "currency",
892
+ currency: args[2]
893
+ }).format(numberValue);
894
+ }
895
+ const currency = args[4] || "$";
896
+ const currencyPosition = args[5] || "start";
897
+ if (currencyPosition !== "start" && currencyPosition !== "end") {
898
+ throw new Error("Invalid currency position. It must be 'start' or 'end'.");
899
+ }
900
+ const formattedNumber = formatDecimal(numberValue, args[1], args[2], args[3]);
901
+ return currencyPosition === "start" ? `${currency}${formattedNumber}` : `${formattedNumber}${currency}`;
902
+ }
903
+ function percentage(...args) {
904
+ const pct = args[0] / args[1] * 100;
905
+ return pct.toFixed(args[2]);
906
+ }
907
+ function truncate(...args) {
908
+ const text = args[0];
909
+ const limit = args[1];
910
+ return text.length > limit ? `${text.substring(0, limit)}...` : text;
911
+ }
912
+ function join(...args) {
913
+ return args[0].join(args[1]);
914
+ }
915
+ function formatDurationInSeconds(durationInSeconds) {
916
+ return formatDuration({
917
+ hours: Math.floor(durationInSeconds / 3600),
918
+ minutes: Math.floor(durationInSeconds % 3600 / 60),
919
+ seconds: durationInSeconds % 60
920
+ });
921
+ }
922
+ async function sha256(message) {
923
+ if (!message) return "";
924
+ const msgUint8 = new TextEncoder().encode(message);
925
+ const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
926
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
927
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
928
+ }
929
+ function ascii(str) {
930
+ if (!str) return "";
931
+ let s = str.replace(/^\s+|\s+$/g, "");
932
+ const from = "\xC1\xC4\xC2\xC0\xC3\xC5\u010C\xC7\u0106\u010E\xC9\u011A\xCB\xC8\xCA\u1EBC\u0114\u0206\u011E\xCD\xCC\xCE\xCF\u0130\u0147\xD1\xD3\xD6\xD2\xD4\xD5\xD8\u0158\u0154\u0160\u015E\u0164\xDA\u016E\xDC\xD9\xDB\xDD\u0178\u017D\xE1\xE4\xE2\xE0\xE3\xE5\u010D\xE7\u0107\u010F\xE9\u011B\xEB\xE8\xEA\u1EBD\u0115\u0207\u011F\xED\xEC\xEE\xEF\u0131\u0148\xF1\xF3\xF6\xF2\xF4\xF5\xF8\xF0\u0159\u0155\u0161\u015F\u0165\xFA\u016F\xFC\xF9\xFB\xFD\xFF\u017E\xFE\xDE\u0110\u0111\xDF\xC6a";
933
+ const to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa";
934
+ for (let i = 0; i < from.length; i++) {
935
+ s = s.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
936
+ }
937
+ return s.replace(/[^a-zA-Z0-9\s\-.@]/g, "");
938
+ }
939
+ function extractNameFromEmail(email, nameOriginal) {
940
+ const localPart = typeof email === "string" ? email.split("@")[0] : "";
941
+ function capitalize(s) {
942
+ return s.length === 0 ? "" : s.charAt(0).toLocaleUpperCase() + s.slice(1).toLowerCase();
943
+ }
944
+ function clean(s) {
945
+ return capitalize(s.replace(/[^a-zA-Z]/g, ""));
946
+ }
947
+ if (localPart) {
948
+ if (localPart.includes(".")) {
949
+ const parts = localPart.split(".");
950
+ return `${clean(parts[0])} ${clean(parts[1])}`;
951
+ }
952
+ return `${clean(localPart)} `;
953
+ }
954
+ return nameOriginal || "";
955
+ }
956
+ function slug(str, separator = "-") {
957
+ let s = str.replace(/^\s+|\s+$/g, "").toLowerCase();
958
+ const from = "\xC1\xC4\xC2\xC0\xC3\xC5\u010C\xC7\u0106\u010E\xC9\u011A\xCB\xC8\xCA\u1EBC\u0114\u0206\u011E\xCD\xCC\xCE\xCF\u0130\u0147\xD1\xD3\xD6\xD2\xD4\xD5\xD8\u0158\u0154\u0160\u015E\u0164\xDA\u016E\xDC\xD9\xDB\xDD\u0178\u017D\xE1\xE4\xE2\xE0\xE3\xE5\u010D\xE7\u0107\u010F\xE9\u011B\xEB\xE8\xEA\u1EBD\u0115\u0207\u011F\xED\xEC\xEE\xEF\u0131\u0148\xF1\xF3\xF6\xF2\xF4\xF5\xF8\xF0\u0159\u0155\u0161\u015F\u0165\xFA\u016F\xFC\xF9\xFB\xFD\xFF\u017E\xFE\xDE\u0110\u0111\xDF\xC6a\xB7/_,:;";
959
+ const to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";
960
+ for (let i = 0; i < from.length; i++) {
961
+ s = s.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
962
+ }
963
+ return s.replace(/[^a-z0-9 -]/g, "").replace(/\s+/g, separator).replace(/-+/g, separator);
964
+ }
965
+ function filterEmpty(arr) {
966
+ if (arr && arr.filter) {
967
+ return arr.filter((el) => el != null && el !== "");
968
+ }
969
+ return arr;
970
+ }
971
+ function padLeft(value, totalLength, padChar = "0") {
972
+ let s = String(value);
973
+ while (s.length < totalLength) {
974
+ s = padChar + s;
975
+ }
976
+ return s;
977
+ }
978
+ function padRight(value, totalLength, padChar = "0") {
979
+ let s = String(value);
980
+ while (s.length < totalLength) {
981
+ s = s + padChar;
982
+ }
983
+ return s;
984
+ }
985
+ function ifNull(value, alternativeValue) {
986
+ return value === null || value === void 0 ? alternativeValue : value;
987
+ }
988
+ function objectToString(objectValue) {
989
+ let result = "";
990
+ if (objectValue instanceof Object) {
991
+ for (const [key, value] of Object.entries(objectValue)) {
992
+ result = `${key}:${value}`;
993
+ }
994
+ }
995
+ return result;
996
+ }
997
+ function isEqual(a, b) {
998
+ if (a == null && b == null) return true;
999
+ if (a == null || b == null) return false;
1000
+ if (a instanceof Date || b instanceof Date) {
1001
+ const da = typeof a === "string" ? new Date(a) : a;
1002
+ const db = typeof b === "string" ? new Date(b) : b;
1003
+ return da.getTime() === db.getTime();
1004
+ }
1005
+ if (typeof a === "object" && typeof b === "object") {
1006
+ if (a.id && b.id) return a.id === b.id;
1007
+ return JSON.stringify(a) === JSON.stringify(b);
1008
+ }
1009
+ if (typeof a === "object" && a.id && (typeof b === "string" || typeof b === "number")) {
1010
+ return a.id === b;
1011
+ }
1012
+ if ((typeof a === "string" || typeof a === "number") && typeof b === "object" && b.id) {
1013
+ return a === b.id;
1014
+ }
1015
+ return a === b;
1016
+ }
1017
+ function isEqualOrContained(needle, haystack) {
1018
+ if (Array.isArray(haystack)) {
1019
+ return haystack.some((item) => isEqual(item, needle));
1020
+ }
1021
+ if (typeof needle === "object" && typeof haystack === "object" && needle?.id && haystack?.id) {
1022
+ return needle.id === haystack.id;
1023
+ }
1024
+ return isEqual(needle, haystack);
1025
+ }
1026
+ function getDbValue(value) {
1027
+ if (typeof value === "object" && value !== null) {
1028
+ if (value.id) return value.id;
1029
+ if (Array.isArray(value) && value.length > 0 && value[0]?.id) return value[0].id;
1030
+ }
1031
+ return value;
1032
+ }
1033
+ function differenceInBusinessDaysCustom(startDate, endDate, options = {}) {
1034
+ if (!startDate || !endDate) return null;
1035
+ const start = new Date(startDate);
1036
+ const end = new Date(endDate);
1037
+ const config = {
1038
+ workStartHour: 9,
1039
+ workEndHour: 18,
1040
+ lunchBreakHours: 1,
1041
+ lunchStartHour: 12.5,
1042
+ lunchEndHour: 13.5,
1043
+ includePartialDays: true,
1044
+ ...options
1045
+ };
1046
+ const workingHoursPerDay = config.workEndHour - config.workStartHour - config.lunchBreakHours;
1047
+ const businessDays = differenceInBusinessDays(end, start);
1048
+ if (!config.includePartialDays) return businessDays;
1049
+ if (businessDays > 0) {
1050
+ const startHour2 = start.getHours() + start.getMinutes() / 60;
1051
+ const endHour2 = end.getHours() + end.getMinutes() / 60;
1052
+ if ((startHour2 < config.workStartHour || startHour2 > config.workEndHour) && (endHour2 < config.workStartHour || endHour2 > config.workEndHour)) {
1053
+ return 0;
1054
+ }
1055
+ let firstDayHours = 0;
1056
+ if (startHour2 >= config.workStartHour && startHour2 <= config.workEndHour) {
1057
+ firstDayHours = config.workEndHour - startHour2;
1058
+ if (startHour2 < config.lunchStartHour) {
1059
+ firstDayHours -= config.lunchBreakHours;
1060
+ } else if (startHour2 >= config.lunchStartHour && startHour2 < config.lunchEndHour) {
1061
+ firstDayHours -= config.lunchEndHour - startHour2;
1062
+ }
1063
+ }
1064
+ let lastDayHours = 0;
1065
+ if (endHour2 >= config.workStartHour) {
1066
+ const effectiveEndHour = Math.min(endHour2, config.workEndHour);
1067
+ lastDayHours = effectiveEndHour - config.workStartHour;
1068
+ if (effectiveEndHour > config.lunchEndHour) {
1069
+ lastDayHours -= config.lunchBreakHours;
1070
+ } else if (effectiveEndHour > config.lunchStartHour && effectiveEndHour <= config.lunchEndHour) {
1071
+ lastDayHours -= effectiveEndHour - config.lunchStartHour;
1072
+ }
1073
+ }
1074
+ const adjustedBusinessDays = businessDays - 1;
1075
+ const totalExtraHours = firstDayHours + lastDayHours;
1076
+ const hourDecimal = Math.max(0, totalExtraHours) / workingHoursPerDay;
1077
+ return Math.round((adjustedBusinessDays + hourDecimal) * 1e3) / 1e3;
1078
+ }
1079
+ const startHour = start.getHours() + start.getMinutes() / 60;
1080
+ const endHour = end.getHours() + end.getMinutes() / 60;
1081
+ if (businessDays === 0) {
1082
+ const dayOfWeek = start.getDay();
1083
+ if (dayOfWeek === 0 || dayOfWeek === 6) return 0;
1084
+ }
1085
+ if (businessDays === 0 && (startHour > config.workEndHour || endHour < config.workStartHour)) {
1086
+ return 0;
1087
+ }
1088
+ let workingHours = Math.max(0, endHour - startHour);
1089
+ if (startHour < config.lunchEndHour && endHour > config.lunchStartHour) {
1090
+ const lunchOverlap = Math.min(endHour, config.lunchEndHour) - Math.max(startHour, config.lunchStartHour);
1091
+ workingHours -= Math.max(0, lunchOverlap);
1092
+ }
1093
+ return Math.round(Math.max(0, workingHours / workingHoursPerDay) * 1e3) / 1e3;
1094
+ }
1095
+ var dateFunctions = {
1096
+ formatDate: format,
1097
+ formatDistance,
1098
+ formatDistanceStrict,
1099
+ formatDistanceToNow,
1100
+ formatDistanceToNowStrict,
1101
+ formatDuration,
1102
+ formatISO,
1103
+ formatRelative,
1104
+ addYears,
1105
+ addMonths,
1106
+ addWeeks,
1107
+ addDays,
1108
+ addHours,
1109
+ addMinutes,
1110
+ addSeconds,
1111
+ addMilliseconds,
1112
+ subYears,
1113
+ subMonths,
1114
+ subWeeks,
1115
+ subDays,
1116
+ subHours,
1117
+ subMinutes,
1118
+ subSeconds,
1119
+ subMilliseconds,
1120
+ isAfter,
1121
+ isBefore,
1122
+ isDatesEqual: isEqual$1,
1123
+ isPast,
1124
+ differenceInYears,
1125
+ differenceInMonths,
1126
+ differenceInWeeks,
1127
+ differenceInDays,
1128
+ differenceInHours,
1129
+ differenceInMinutes,
1130
+ differenceInSeconds,
1131
+ differenceInBusinessDays,
1132
+ differenceInBusinessDaysCustom,
1133
+ startOfDay,
1134
+ startOfMonth,
1135
+ startOfWeek,
1136
+ startOfToday,
1137
+ startOfQuarter,
1138
+ endOfDay,
1139
+ endOfMonth,
1140
+ endOfWeek,
1141
+ endOfToday,
1142
+ endOfQuarter
1143
+ };
1144
+ for (const key of Object.keys(dateFunctions)) {
1145
+ dateFunctions[key] = dateWrapper(dateFunctions[key]);
1146
+ }
1147
+ var jsonataHelpers = {
1148
+ ...dateFunctions,
1149
+ // Format functions
1150
+ formatDecimal,
1151
+ formatMoney,
1152
+ join,
1153
+ truncate,
1154
+ percentage,
1155
+ formatDurationInSeconds,
1156
+ // String / misc
1157
+ sha256,
1158
+ ascii,
1159
+ extractNameFromEmail,
1160
+ slug,
1161
+ filterEmpty,
1162
+ startsWith: (haystack, needle) => haystack.startsWith(needle),
1163
+ endsWith: (haystack, needle) => haystack.endsWith(needle),
1164
+ includes: (haystack, needle) => {
1165
+ if (!haystack || !needle) return false;
1166
+ return haystack.includes(needle);
1167
+ },
1168
+ objectToString,
1169
+ padLeft,
1170
+ padRight,
1171
+ ifNull,
1172
+ // Equality / DB helpers
1173
+ isEqual,
1174
+ isEqualOrContained,
1175
+ isNotEqualOrContained: (needle, haystack) => !isEqualOrContained(needle, haystack),
1176
+ getDbValue
1177
+ };
1178
+
1179
+ // src/template-engine.ts
1180
+ var HTML_ENTITIES = {
1181
+ amp: "&",
1182
+ lt: "<",
1183
+ gt: ">",
1184
+ quot: '"',
1185
+ apos: "'"
1186
+ };
1187
+ function decodeHtmlEntities(str) {
1188
+ return str.replace(/&(amp|lt|gt|quot|apos);/g, (match, entity) => HTML_ENTITIES[entity] ?? match);
1189
+ }
1190
+ function removeHtmlTags(str) {
1191
+ if (str === null || str === "") return "";
1192
+ return String(str).replace(/(<([^>]+)>)/gi, "");
1193
+ }
1194
+ var FORMULA_EXPR_RE = /(\{\{formula\s)(?<formula>[^}]+)(\}\})/g;
1195
+ var IF_FORMULA_RE = /(\{\{#if\s)(?<formula>[^}]+)(\}\})/g;
1196
+ var INLINE_RE = /\{\{<([^*]+)\}\}/g;
1197
+ function preprocessTemplate(tpl) {
1198
+ let result = tpl.replace(FORMULA_EXPR_RE, (_matched, g1, g2, g3) => {
1199
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
1200
+ return `${g1}'${removeHtmlTags(escaped)}'${g3}`;
1201
+ });
1202
+ result = result.replace(IF_FORMULA_RE, (_matched, g1, g2, g3) => {
1203
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
1204
+ return `${g1} (formula '${escaped}')${g3}`;
1205
+ });
1206
+ result = result.replace(INLINE_RE, (_matched, group) => {
1207
+ return removeHtmlTags(group);
1208
+ });
1209
+ return result;
1210
+ }
1211
+ function registerHelpers(hb, dateUtils, numberUtils, bindings) {
1212
+ hb.registerHelper("repeat", async (n, block) => {
1213
+ let accum = "";
1214
+ for (let i = 0; i < n; ++i) {
1215
+ accum += block.fn(i);
1216
+ }
1217
+ return accum;
1218
+ });
1219
+ hb.registerHelper("sum", (...args) => {
1220
+ args = args.slice(0, -1);
1221
+ if (args.length >= 2 && Array.isArray(args[0]) && typeof args[1] === "string") {
1222
+ const key = args[1];
1223
+ return Handlebars.escapeExpression(
1224
+ String(args[0].reduce((total, obj) => total + (Number(obj[key]) || 0), 0))
1225
+ );
1226
+ }
1227
+ const sumValue = (val) => {
1228
+ if (Array.isArray(val)) return val.reduce((acc, item) => acc + sumValue(item), 0);
1229
+ return Number(val) || 0;
1230
+ };
1231
+ return Handlebars.escapeExpression(
1232
+ String(args.reduce((total, num) => total + sumValue(num), 0))
1233
+ );
1234
+ });
1235
+ if (dateUtils) {
1236
+ hb.registerHelper("formatDate", (input, options) => {
1237
+ const dateFormat = options.hash.format || void 0;
1238
+ const result = Handlebars.escapeExpression(
1239
+ dateUtils.formatDate(input, dateFormat ? { format: dateFormat } : void 0) ?? ""
1240
+ );
1241
+ return new Handlebars.SafeString(result);
1242
+ });
1243
+ hb.registerHelper("formatDateTime", (input) => {
1244
+ const result = Handlebars.escapeExpression(
1245
+ dateUtils.formatDateTime(input) ?? ""
1246
+ );
1247
+ return new Handlebars.SafeString(result);
1248
+ });
1249
+ }
1250
+ if (numberUtils) {
1251
+ hb.registerHelper("formatNumber", (input, options) => {
1252
+ const result = Handlebars.escapeExpression(
1253
+ numberUtils.formatNumber(input, {
1254
+ decimalPrecision: options.hash.decimalPrecision || void 0,
1255
+ decimalSeparator: options.hash.decimalSeparator || void 0,
1256
+ thousandSeparator: options.hash.thousandSeparator !== void 0 ? options.hash.thousandSeparator : void 0
1257
+ }) ?? ""
1258
+ );
1259
+ return result;
1260
+ });
1261
+ }
1262
+ hb.registerHelper("formatNumberToWords", (number, options) => {
1263
+ return formatNumberToWords(number, {
1264
+ useSpaces: options.hash.useSpaces || false,
1265
+ lang: options.hash.lang || "TR",
1266
+ currency: options.hash.currency || "TRY"
1267
+ });
1268
+ });
1269
+ hb.registerHelper("formatDurationAsTime", (input) => {
1270
+ return Handlebars.escapeExpression(formatDurationAsTime(input));
1271
+ });
1272
+ hb.registerHelper("formatDurationAsWords", (input) => {
1273
+ return Handlebars.escapeExpression(formatDurationAsWords(input));
1274
+ });
1275
+ hb.registerHelper("formatDurationAsHours", (input, options) => {
1276
+ const decimalPrecision = options.hash.decimalPrecision || 2;
1277
+ return Handlebars.escapeExpression(formatDurationAsHours(input, decimalPrecision));
1278
+ });
1279
+ hb.registerHelper("formula", async function(context, options) {
1280
+ let data;
1281
+ let opts;
1282
+ if (!options && context && context.fn) {
1283
+ opts = context;
1284
+ data = Array.isArray(opts.data.root) ? opts.data.root[opts.data.index] : opts.data.root || {};
1285
+ } else {
1286
+ opts = options;
1287
+ data = opts.data.root;
1288
+ }
1289
+ if (opts.fn) {
1290
+ const expression = await opts.fn(this);
1291
+ if (!expression) return "";
1292
+ try {
1293
+ return await jsonata(expression).evaluate(data || {}, bindings);
1294
+ } catch (err) {
1295
+ console.warn("Error during jsonata evaluation", { expression, data });
1296
+ throw err;
1297
+ }
1298
+ }
1299
+ if (typeof context === "string") {
1300
+ try {
1301
+ return await jsonata(context).evaluate(data || {}, bindings);
1302
+ } catch (err) {
1303
+ console.warn("Error during jsonata evaluation", { context, data });
1304
+ throw err;
1305
+ }
1306
+ }
1307
+ return "";
1308
+ });
1309
+ hb.registerHelper("path", (...args) => {
1310
+ const options = args[args.length - 1];
1311
+ const expression = args[0];
1312
+ const result = JSONPath({ path: expression, json: options.data.root });
1313
+ if (result == null) return "";
1314
+ const ctx = Array.isArray(result) && result.length === 1 ? result[0] : result;
1315
+ return options.fn(ctx);
1316
+ });
1317
+ hb.registerHelper("json", (context) => {
1318
+ return JSON.stringify(context, null, 2);
1319
+ });
1320
+ }
1321
+ function createTemplateEngine(config = {}) {
1322
+ const {
1323
+ dateUtils,
1324
+ numberUtils,
1325
+ extraJsonataBindings = {},
1326
+ additionalHelpers = {},
1327
+ user
1328
+ } = config;
1329
+ const allBindings = { ...jsonataHelpers, ...extraJsonataBindings };
1330
+ const hb = (0, import_handlebars_async_helpers.default)(Handlebars);
1331
+ hb.registerHelper("each", createAsyncEachHelper(hb));
1332
+ registerHelpers(hb, dateUtils, numberUtils, allBindings);
1333
+ for (const [name, fn] of Object.entries(additionalHelpers)) {
1334
+ hb.registerHelper(name, fn);
1335
+ }
1336
+ function compileTpl(templateString) {
1337
+ const preprocessed = preprocessTemplate(templateString);
1338
+ return hb.compile(preprocessed);
1339
+ }
1340
+ async function compileFormula(expression, data) {
1341
+ try {
1342
+ const metadata = {
1343
+ ...data?.metadata || {},
1344
+ user: user ?? null
1345
+ };
1346
+ return await jsonata(expression).evaluate(
1347
+ { ...data, metadata },
1348
+ allBindings
1349
+ );
1350
+ } catch (err) {
1351
+ console.warn("Error during jsonata evaluation", { expression, data });
1352
+ console.warn(err);
1353
+ return void 0;
1354
+ }
1355
+ }
1356
+ return {
1357
+ compileTpl,
1358
+ compileFormula,
1359
+ jsonataHelpers: allBindings
1360
+ };
1361
+ }
1362
+
1363
+ // src/app-config-client.ts
1364
+ function createAppConfigClient(client, appId, options) {
1365
+ const basePath = `/v1/tenant/apps/${appId}/config`;
1366
+ const inventory = options?.inventory;
1367
+ async function get() {
1368
+ if (inventory) {
1369
+ const cached = await inventory.getAppConfig(appId);
1370
+ if (cached) return cached;
1371
+ }
1372
+ return unwrapEnvelope(await client.get(basePath));
1373
+ }
1374
+ async function upsert(body) {
1375
+ const result = unwrapEnvelope(await client.put(basePath, body));
1376
+ inventory?.setAppConfig(appId, result);
1377
+ return result;
1378
+ }
1379
+ async function remove() {
1380
+ await client.delete(basePath);
1381
+ inventory?.setAppConfig(appId, null);
1382
+ }
1383
+ return { get, upsert, remove };
1384
+ }
1385
+
1386
+ // src/user-app-config-client.ts
1387
+ function createUserAppConfigClient(client, appId, options) {
1388
+ const basePath = `/v1/tenant/apps/${appId}/user-config`;
1389
+ const inventory = options?.inventory;
1390
+ async function get() {
1391
+ if (inventory) {
1392
+ const cached = await inventory.getUserAppConfig(appId);
1393
+ if (cached) return cached;
1394
+ }
1395
+ return unwrapEnvelope(await client.get(basePath));
1396
+ }
1397
+ async function upsert(body) {
1398
+ const result = unwrapEnvelope(await client.put(basePath, body));
1399
+ inventory?.setUserAppConfig(appId, result);
1400
+ return result;
1401
+ }
1402
+ async function remove() {
1403
+ await client.delete(basePath);
1404
+ inventory?.setUserAppConfig(appId, null);
1405
+ }
1406
+ return { get, upsert, remove };
1407
+ }
1408
+
1409
+ // src/data-view-client.ts
1410
+ async function resolveDataSource(inventory, appSlug, dataSourceSlug) {
1411
+ const sources = await inventory.listDataSources();
1412
+ const match = sources.find(
1413
+ (ds) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
1414
+ );
1415
+ return match ?? null;
1416
+ }
1417
+ function createDataViewClient(client, appSlug, dataSourceSlug, options) {
1418
+ const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/views`;
1419
+ const inventory = options?.inventory;
1420
+ async function list(params) {
1421
+ if (inventory) {
1422
+ const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
1423
+ if (dataSource) {
1424
+ const views = dataSource.views ?? [];
1425
+ return params?.appId ? views.filter((view) => view.tenant_app_id === params.appId) : views;
1426
+ }
1427
+ }
1428
+ return unwrapEnvelope(
1429
+ await client.get(basePath, params?.appId ? { appId: params.appId } : void 0)
1430
+ );
1431
+ }
1432
+ async function get(viewId) {
1433
+ if (inventory) {
1434
+ const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
1435
+ const match = dataSource?.views?.find((view) => view.id === viewId);
1436
+ if (match) return match;
1437
+ }
1438
+ return unwrapEnvelope(await client.get(`${basePath}/${viewId}`));
1439
+ }
1440
+ async function create(body) {
1441
+ const result = unwrapEnvelope(await client.post(basePath, body));
1442
+ inventory?.upsertDataView(result);
1443
+ return result;
1444
+ }
1445
+ async function update(viewId, body) {
1446
+ const result = unwrapEnvelope(await client.put(`${basePath}/${viewId}`, body));
1447
+ if (body.archived === true) {
1448
+ inventory?.removeDataView(viewId);
1449
+ } else {
1450
+ inventory?.upsertDataView(result);
1451
+ }
1452
+ return result;
1453
+ }
1454
+ async function remove(viewId) {
1455
+ await client.delete(`${basePath}/${viewId}`);
1456
+ inventory?.removeDataView(viewId);
1457
+ }
1458
+ return {
1459
+ list,
1460
+ get,
1461
+ create,
1462
+ update,
1463
+ remove
1464
+ };
1465
+ }
1466
+
1467
+ // src/data-form-client.ts
1468
+ async function resolveDataSource2(inventory, appSlug, dataSourceSlug) {
1469
+ const sources = await inventory.listDataSources();
1470
+ const match = sources.find(
1471
+ (ds) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
1472
+ );
1473
+ return match ?? null;
1474
+ }
1475
+ function createDataFormClient(client, appSlug, dataSourceSlug, options) {
1476
+ const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/forms`;
1477
+ const inventory = options?.inventory;
1478
+ async function list() {
1479
+ if (inventory) {
1480
+ const dataSource = await resolveDataSource2(inventory, appSlug, dataSourceSlug);
1481
+ if (dataSource) return dataSource.forms ?? [];
1482
+ }
1483
+ return unwrapEnvelope(await client.get(basePath));
1484
+ }
1485
+ async function get(formId) {
1486
+ if (inventory) {
1487
+ const dataSource = await resolveDataSource2(inventory, appSlug, dataSourceSlug);
1488
+ const match = dataSource?.forms?.find((form) => form.id === formId);
1489
+ if (match) return match;
1490
+ }
1491
+ return unwrapEnvelope(await client.get(`${basePath}/${formId}`));
1492
+ }
1493
+ async function create(body) {
1494
+ const result = unwrapEnvelope(await client.post(basePath, body));
1495
+ inventory?.upsertDataForm(result);
1496
+ return result;
1497
+ }
1498
+ async function update(formId, body) {
1499
+ const result = unwrapEnvelope(await client.put(`${basePath}/${formId}`, body));
1500
+ if (body.archived === true) {
1501
+ inventory?.removeDataForm(formId);
1502
+ } else {
1503
+ inventory?.upsertDataForm(result);
1504
+ }
1505
+ return result;
1506
+ }
1507
+ async function remove(formId) {
1508
+ await client.delete(`${basePath}/${formId}`);
1509
+ inventory?.removeDataForm(formId);
1510
+ }
1511
+ return {
1512
+ list,
1513
+ get,
1514
+ create,
1515
+ update,
1516
+ remove
1517
+ };
1518
+ }
1519
+
1520
+ // src/data-source-client.ts
1521
+ function matchesSlug(dataSource, appSlug, dataSourceSlug) {
1522
+ const ownerAppSlug = dataSource.appSlug ?? dataSource.app_slug;
1523
+ return ownerAppSlug === appSlug && dataSource.slug === dataSourceSlug;
1524
+ }
1525
+ function normalizeFieldType(type) {
1526
+ return type.startsWith("field-") ? type.slice("field-".length) : type;
1527
+ }
1528
+ function getRelationTargetId(field) {
1529
+ if (normalizeFieldType(field.type) !== "relation") return void 0;
1530
+ const target = field.relation_data_source_id ?? field.relationDataSourceId;
1531
+ return typeof target === "string" && target.length > 0 ? target : void 0;
1532
+ }
1533
+ function addRelationEdge(map, key, value) {
1534
+ const existing = map.get(key);
1535
+ if (existing) existing.add(value);
1536
+ else map.set(key, /* @__PURE__ */ new Set([value]));
1537
+ }
1538
+ function buildRelationIndex(sources) {
1539
+ const byId = /* @__PURE__ */ new Map();
1540
+ const parentsByChild = /* @__PURE__ */ new Map();
1541
+ const childrenByParent = /* @__PURE__ */ new Map();
1542
+ for (const dataSource of sources) byId.set(dataSource.id, dataSource);
1543
+ for (const dataSource of sources) {
1544
+ for (const field of dataSource.fields ?? []) {
1545
+ const parentId = getRelationTargetId(field);
1546
+ if (!parentId || parentId === dataSource.id) continue;
1547
+ addRelationEdge(parentsByChild, dataSource.id, parentId);
1548
+ addRelationEdge(childrenByParent, parentId, dataSource.id);
1549
+ }
1550
+ }
1551
+ return { byId, parentsByChild, childrenByParent };
1552
+ }
1553
+ function createDataSourceClient(client, options) {
1554
+ const basePath = "/v1/apps/data-sources";
1555
+ const inventory = options?.inventory;
1556
+ function buildQueryParams(params) {
1557
+ if (!params?.expand) return void 0;
1558
+ return { expand: params.expand };
1559
+ }
1560
+ async function listApps() {
1561
+ if (inventory) return inventory.listApps();
1562
+ return unwrapEnvelope(await client.get("/v1/apps"));
1563
+ }
1564
+ async function list(params) {
1565
+ if (inventory && !params?.expand) return inventory.listDataSources();
1566
+ return unwrapEnvelope(
1567
+ await client.get(basePath, buildQueryParams(params))
1568
+ );
1569
+ }
1570
+ async function listByAppSlug(appSlug, params) {
1571
+ if (inventory && !params?.expand) {
1572
+ const sources = await inventory.listDataSources();
1573
+ return sources.filter((ds) => (ds.appSlug ?? ds.app_slug) === appSlug);
1574
+ }
1575
+ return unwrapEnvelope(
1576
+ await client.get(`/v1/apps/${appSlug}/data-sources`, buildQueryParams(params))
1577
+ );
1578
+ }
1579
+ async function listByAppId(appId, params) {
1580
+ if (inventory && !params?.expand) {
1581
+ const sources = await inventory.listDataSources();
1582
+ return sources.filter((ds) => ds.tenant_app_id === appId);
1583
+ }
1584
+ const queryParams = { appId };
1585
+ if (params?.expand) {
1586
+ queryParams.expand = params.expand;
1587
+ }
1588
+ return unwrapEnvelope(await client.get(basePath, queryParams));
1589
+ }
1590
+ async function getById(dataSourceId, params) {
1591
+ if (inventory && !params?.expand) {
1592
+ const sources = await inventory.listDataSources();
1593
+ const match = sources.find((ds) => ds.id === dataSourceId);
1594
+ if (match) return match;
1595
+ }
1596
+ return unwrapEnvelope(
1597
+ await client.get(`${basePath}/${dataSourceId}`, buildQueryParams(params))
1598
+ );
1599
+ }
1600
+ async function getBySlug(appSlug, dataSourceSlug, params) {
1601
+ if (inventory && !params?.expand) {
1602
+ const sources = await inventory.listDataSources();
1603
+ const match = sources.find((ds) => matchesSlug(ds, appSlug, dataSourceSlug));
1604
+ if (match) return match;
1605
+ }
1606
+ return unwrapEnvelope(
1607
+ await client.get(
1608
+ `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}`,
1609
+ buildQueryParams(params)
1610
+ )
1611
+ );
1612
+ }
1613
+ async function getFields(dataSourceId) {
1614
+ if (inventory) {
1615
+ const cached = await getById(dataSourceId);
1616
+ if (cached.fields) return cached.fields;
1617
+ }
1618
+ const dataSource = await getById(dataSourceId, { expand: "fields" });
1619
+ return dataSource.fields ?? [];
1620
+ }
1621
+ async function getFieldById(dataSourceId, fieldId) {
1622
+ return (await getFields(dataSourceId)).find((field) => field.id === fieldId);
1623
+ }
1624
+ async function getFieldBySlug(dataSourceId, fieldSlug) {
1625
+ return (await getFields(dataSourceId)).find((field) => field.slug === fieldSlug);
1626
+ }
1627
+ async function getEnumsByFieldId(dataSourceId, fieldId) {
1628
+ const field = await getFieldById(dataSourceId, fieldId);
1629
+ return field?.enums ?? [];
1630
+ }
1631
+ async function getEnumById(dataSourceId, fieldId, enumId) {
1632
+ return (await getEnumsByFieldId(dataSourceId, fieldId)).find((option) => option.id === enumId);
1633
+ }
1634
+ let relationIndexSource = null;
1635
+ let relationIndex = null;
1636
+ async function loadAllDataSources() {
1637
+ if (inventory) return inventory.listDataSources();
1638
+ return unwrapEnvelope(await client.get(basePath, { expand: "fields" }));
1639
+ }
1640
+ async function getRelationIndex() {
1641
+ const sources = await loadAllDataSources();
1642
+ if (relationIndex && relationIndexSource === sources) return relationIndex;
1643
+ relationIndex = buildRelationIndex(sources);
1644
+ relationIndexSource = sources;
1645
+ return relationIndex;
1646
+ }
1647
+ async function resolveRelated(dataSourceId, edge) {
1648
+ const index = await getRelationIndex();
1649
+ const ids = index[edge].get(dataSourceId);
1650
+ if (!ids) return [];
1651
+ const out = [];
1652
+ for (const id of ids) {
1653
+ const match = index.byId.get(id);
1654
+ if (match) out.push(match);
1655
+ }
1656
+ return out;
1657
+ }
1658
+ async function listParentDataSources(dataSourceId) {
1659
+ return resolveRelated(dataSourceId, "parentsByChild");
1660
+ }
1661
+ async function listChildDataSources(dataSourceId) {
1662
+ return resolveRelated(dataSourceId, "childrenByParent");
1663
+ }
1664
+ async function listParentDataSourceFields(dataSourceId) {
1665
+ return (await listParentDataSources(dataSourceId)).flatMap((ds) => ds.fields ?? []);
1666
+ }
1667
+ async function listChildDataSourceFields(dataSourceId) {
1668
+ return (await listChildDataSources(dataSourceId)).flatMap((ds) => ds.fields ?? []);
1669
+ }
1670
+ return {
1671
+ listApps,
1672
+ list,
1673
+ listByAppSlug,
1674
+ listByAppId,
1675
+ getById,
1676
+ getBySlug,
1677
+ getFields,
1678
+ getFieldById,
1679
+ getFieldBySlug,
1680
+ getEnumsByFieldId,
1681
+ getEnumById,
1682
+ listParentDataSources,
1683
+ listChildDataSources,
1684
+ listParentDataSourceFields,
1685
+ listChildDataSourceFields
1686
+ };
1687
+ }
1688
+
1689
+ // src/inventory-client.ts
1690
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
1691
+ var DEFAULT_DATA_SOURCES_EXPAND = "views,forms,fields";
1692
+ var DEFAULT_STORAGE_KEY = "docyrus:inventory";
1693
+ var SNAPSHOT_VERSION = 1;
1694
+ var DEFAULT_LOAD_STEPS = [
1695
+ "apps",
1696
+ "data-sources",
1697
+ "users",
1698
+ "brands",
1699
+ "preferences"
1700
+ ];
1701
+ function resolveStorage(option) {
1702
+ if (!option) return null;
1703
+ if (typeof option !== "string") return option;
1704
+ try {
1705
+ const key = option === "session" ? "sessionStorage" : "localStorage";
1706
+ const store = globalThis[key];
1707
+ if (!store) return null;
1708
+ const probe = "__docyrus_inventory_probe__";
1709
+ store.setItem(probe, probe);
1710
+ store.removeItem(probe);
1711
+ return store;
1712
+ } catch {
1713
+ return null;
1714
+ }
1715
+ }
1716
+ function toIdSet(value) {
1717
+ if (value === void 0) return null;
1718
+ return new Set(Array.isArray(value) ? value : [value]);
1719
+ }
1720
+ function isNotFound(error) {
1721
+ return typeof error === "object" && error !== null && error.status === 404;
1722
+ }
1723
+ function readAppIdFromEnv() {
1724
+ let value;
1725
+ try {
1726
+ value = import.meta.env?.VITE_APP_ID;
1727
+ } catch {
1728
+ value = void 0;
1729
+ }
1730
+ if (!value && typeof process !== "undefined") {
1731
+ value = process.env?.VITE_APP_ID;
1732
+ }
1733
+ return value && value.length > 0 ? value : void 0;
1734
+ }
1735
+ function normalizeEmbeddedForm(raw, dataSourceId) {
1736
+ const isDefault = raw.is_default ?? raw.isDefault ?? false;
1737
+ const tenantDataSourceId = raw.tenant_data_source_id ?? dataSourceId;
1738
+ return {
1739
+ ...raw,
1740
+ tenant_data_source_id: tenantDataSourceId,
1741
+ is_default: isDefault,
1742
+ archived: raw.archived ?? false
1743
+ };
1744
+ }
1745
+ function normalizeEmbeddedView(raw) {
1746
+ return raw.archived === void 0 ? { ...raw, archived: false } : raw;
1747
+ }
1748
+ function normalizeDataSource(dataSource) {
1749
+ const views = Array.isArray(dataSource.views) ? dataSource.views.map(normalizeEmbeddedView) : dataSource.views;
1750
+ const forms = Array.isArray(dataSource.forms) ? dataSource.forms.map((form) => normalizeEmbeddedForm(form, dataSource.id)) : dataSource.forms;
1751
+ if (views === dataSource.views && forms === dataSource.forms) return dataSource;
1752
+ return { ...dataSource, views, forms };
1753
+ }
1754
+ function createInventoryClient(client, options) {
1755
+ const ttlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
1756
+ const dataSourcesExpand = options?.dataSourcesExpand ?? DEFAULT_DATA_SOURCES_EXPAND;
1757
+ const storage = resolveStorage(options?.storage);
1758
+ const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;
1759
+ let apps = null;
1760
+ let dataSources = null;
1761
+ let users = null;
1762
+ let brands = null;
1763
+ let preferences = null;
1764
+ const appConfigs = /* @__PURE__ */ new Map();
1765
+ const userAppConfigs = /* @__PURE__ */ new Map();
1766
+ let appsInFlight = null;
1767
+ let dataSourcesInFlight = null;
1768
+ let usersInFlight = null;
1769
+ let brandsInFlight = null;
1770
+ let preferencesInFlight = null;
1771
+ const appConfigsInFlight = /* @__PURE__ */ new Map();
1772
+ const userAppConfigsInFlight = /* @__PURE__ */ new Map();
1773
+ function persist() {
1774
+ if (!storage) return;
1775
+ const snapshot = {
1776
+ v: SNAPSHOT_VERSION,
1777
+ apps,
1778
+ dataSources,
1779
+ users,
1780
+ brands,
1781
+ preferences,
1782
+ appConfigs: [...appConfigs],
1783
+ userAppConfigs: [...userAppConfigs]
1784
+ };
1785
+ try {
1786
+ storage.setItem(storageKey, JSON.stringify(snapshot));
1787
+ } catch {
1788
+ }
1789
+ }
1790
+ function hydrate() {
1791
+ if (!storage) return;
1792
+ let raw;
1793
+ try {
1794
+ raw = storage.getItem(storageKey);
1795
+ } catch {
1796
+ return;
1797
+ }
1798
+ if (!raw) return;
1799
+ let snapshot = null;
1800
+ try {
1801
+ const parsed = JSON.parse(raw);
1802
+ if (parsed && parsed.v === SNAPSHOT_VERSION) snapshot = parsed;
1803
+ } catch {
1804
+ snapshot = null;
1805
+ }
1806
+ if (!snapshot) return;
1807
+ apps = snapshot.apps ?? null;
1808
+ dataSources = snapshot.dataSources ?? null;
1809
+ users = snapshot.users ?? null;
1810
+ brands = snapshot.brands ?? null;
1811
+ preferences = snapshot.preferences ?? null;
1812
+ for (const [id, entry] of snapshot.appConfigs ?? []) appConfigs.set(id, entry);
1813
+ for (const [id, entry] of snapshot.userAppConfigs ?? []) userAppConfigs.set(id, entry);
1814
+ }
1815
+ hydrate();
1816
+ function isFresh(entry) {
1817
+ if (!entry) return false;
1818
+ if (!Number.isFinite(ttlMs)) return true;
1819
+ return Date.now() - entry.fetchedAt < ttlMs;
1820
+ }
1821
+ async function listApps() {
1822
+ if (isFresh(apps)) return apps.data;
1823
+ if (appsInFlight) return appsInFlight;
1824
+ appsInFlight = (async () => {
1825
+ try {
1826
+ const data = unwrapEnvelope(await client.get("/v1/apps"));
1827
+ apps = { data, fetchedAt: Date.now() };
1828
+ persist();
1829
+ return data;
1830
+ } finally {
1831
+ appsInFlight = null;
1832
+ }
1833
+ })();
1834
+ return appsInFlight;
1835
+ }
1836
+ async function listDataSources() {
1837
+ if (isFresh(dataSources)) return dataSources.data;
1838
+ if (dataSourcesInFlight) return dataSourcesInFlight;
1839
+ dataSourcesInFlight = (async () => {
1840
+ try {
1841
+ const queryParams = dataSourcesExpand ? { expand: dataSourcesExpand } : void 0;
1842
+ const raw = unwrapEnvelope(
1843
+ await client.get("/v1/apps/data-sources", queryParams)
1844
+ );
1845
+ const data = raw.map(normalizeDataSource);
1846
+ dataSources = { data, fetchedAt: Date.now() };
1847
+ persist();
1848
+ return data;
1849
+ } finally {
1850
+ dataSourcesInFlight = null;
1851
+ }
1852
+ })();
1853
+ return dataSourcesInFlight;
1854
+ }
1855
+ async function listUsers() {
1856
+ if (isFresh(users)) return users.data;
1857
+ if (usersInFlight) return usersInFlight;
1858
+ usersInFlight = (async () => {
1859
+ try {
1860
+ const data = unwrapEnvelope(await client.get("/v1/users"));
1861
+ users = { data, fetchedAt: Date.now() };
1862
+ persist();
1863
+ return data;
1864
+ } finally {
1865
+ usersInFlight = null;
1866
+ }
1867
+ })();
1868
+ return usersInFlight;
1869
+ }
1870
+ async function listBrands() {
1871
+ if (isFresh(brands)) return brands.data;
1872
+ if (brandsInFlight) return brandsInFlight;
1873
+ brandsInFlight = (async () => {
1874
+ try {
1875
+ const data = unwrapEnvelope(await client.get("/v1/tenant/brands"));
1876
+ brands = { data, fetchedAt: Date.now() };
1877
+ persist();
1878
+ return data;
1879
+ } finally {
1880
+ brandsInFlight = null;
1881
+ }
1882
+ })();
1883
+ return brandsInFlight;
1884
+ }
1885
+ async function getPreferences() {
1886
+ if (isFresh(preferences)) return preferences.data;
1887
+ if (preferencesInFlight) return preferencesInFlight;
1888
+ preferencesInFlight = (async () => {
1889
+ try {
1890
+ const data = unwrapEnvelope(await client.get("/v1/tenant/preferences"));
1891
+ preferences = { data, fetchedAt: Date.now() };
1892
+ persist();
1893
+ return data;
1894
+ } finally {
1895
+ preferencesInFlight = null;
1896
+ }
1897
+ })();
1898
+ return preferencesInFlight;
1899
+ }
1900
+ async function getAppConfig(appId) {
1901
+ return getConfig(appId, appConfigs, appConfigsInFlight, `/v1/tenant/apps/${appId}/config`);
1902
+ }
1903
+ async function getUserAppConfig(appId) {
1904
+ return getConfig(appId, userAppConfigs, userAppConfigsInFlight, `/v1/tenant/apps/${appId}/user-config`);
1905
+ }
1906
+ function getConfig(appId, cache, inFlight, path) {
1907
+ const cached = cache.get(appId);
1908
+ if (isFresh(cached)) return Promise.resolve(cached.data);
1909
+ const existing = inFlight.get(appId);
1910
+ if (existing) return existing;
1911
+ const promise = (async () => {
1912
+ try {
1913
+ const data = unwrapEnvelope(await client.get(path));
1914
+ cache.set(appId, { data, fetchedAt: Date.now() });
1915
+ persist();
1916
+ return data;
1917
+ } catch (error) {
1918
+ if (isNotFound(error)) {
1919
+ cache.set(appId, { data: null, fetchedAt: Date.now() });
1920
+ persist();
1921
+ return null;
1922
+ }
1923
+ throw error;
1924
+ } finally {
1925
+ inFlight.delete(appId);
1926
+ }
1927
+ })();
1928
+ inFlight.set(appId, promise);
1929
+ return promise;
1930
+ }
1931
+ async function listDataViews(params) {
1932
+ const sources = await listDataSources();
1933
+ const appIds = toIdSet(params?.appId);
1934
+ const dataSourceIds = toIdSet(params?.dataSourceId);
1935
+ const out = [];
1936
+ for (const dataSource of sources) {
1937
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
1938
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
1939
+ if (!dataSource.views) continue;
1940
+ for (const view of dataSource.views) {
1941
+ out.push(view);
1942
+ }
1943
+ }
1944
+ return out;
1945
+ }
1946
+ async function listDataForms(params) {
1947
+ const sources = await listDataSources();
1948
+ const appIds = toIdSet(params?.appId);
1949
+ const dataSourceIds = toIdSet(params?.dataSourceId);
1950
+ const out = [];
1951
+ for (const dataSource of sources) {
1952
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
1953
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
1954
+ if (!dataSource.forms) continue;
1955
+ for (const form of dataSource.forms) {
1956
+ out.push(form);
1957
+ }
1958
+ }
1959
+ return out;
1960
+ }
1961
+ function mutateCachedDataSources(mutator) {
1962
+ if (!dataSources) return;
1963
+ const next = mutator(dataSources.data);
1964
+ if (next) {
1965
+ dataSources = { data: next, fetchedAt: dataSources.fetchedAt };
1966
+ persist();
1967
+ }
1968
+ }
1969
+ function upsertDataView(view) {
1970
+ mutateCachedDataSources((sources) => {
1971
+ const index = sources.findIndex((ds) => ds.id === view.tenant_data_source_id);
1972
+ if (index === -1) return;
1973
+ const dataSource = sources[index];
1974
+ const normalized = normalizeEmbeddedView(view);
1975
+ const existingViews = dataSource.views ?? [];
1976
+ const viewIndex = existingViews.findIndex((v) => v.id === view.id);
1977
+ const views = viewIndex === -1 ? [...existingViews, normalized] : existingViews.map((v, i) => i === viewIndex ? normalized : v);
1978
+ const next = [...sources];
1979
+ next[index] = { ...dataSource, views };
1980
+ return next;
1981
+ });
1982
+ }
1983
+ function removeDataView(viewId) {
1984
+ mutateCachedDataSources((sources) => {
1985
+ let touched = false;
1986
+ const next = sources.map((dataSource) => {
1987
+ if (!dataSource.views?.some((v) => v.id === viewId)) return dataSource;
1988
+ touched = true;
1989
+ return { ...dataSource, views: dataSource.views.filter((v) => v.id !== viewId) };
1990
+ });
1991
+ return touched ? next : void 0;
1992
+ });
1993
+ }
1994
+ function upsertDataForm(form) {
1995
+ mutateCachedDataSources((sources) => {
1996
+ const index = sources.findIndex((ds) => ds.id === form.tenant_data_source_id);
1997
+ if (index === -1) return;
1998
+ const dataSource = sources[index];
1999
+ const normalized = normalizeEmbeddedForm(form, dataSource.id);
2000
+ const existingForms = dataSource.forms ?? [];
2001
+ const formIndex = existingForms.findIndex((f) => f.id === form.id);
2002
+ const forms = formIndex === -1 ? [...existingForms, normalized] : existingForms.map((f, i) => i === formIndex ? normalized : f);
2003
+ const next = [...sources];
2004
+ next[index] = { ...dataSource, forms };
2005
+ return next;
2006
+ });
2007
+ }
2008
+ function removeDataForm(formId) {
2009
+ mutateCachedDataSources((sources) => {
2010
+ let touched = false;
2011
+ const next = sources.map((dataSource) => {
2012
+ if (!dataSource.forms?.some((f) => f.id === formId)) return dataSource;
2013
+ touched = true;
2014
+ return { ...dataSource, forms: dataSource.forms.filter((f) => f.id !== formId) };
2015
+ });
2016
+ return touched ? next : void 0;
2017
+ });
2018
+ }
2019
+ function invalidateApps() {
2020
+ apps = null;
2021
+ persist();
2022
+ }
2023
+ function invalidateDataSources() {
2024
+ dataSources = null;
2025
+ persist();
2026
+ }
2027
+ function invalidateUsers() {
2028
+ users = null;
2029
+ persist();
2030
+ }
2031
+ function invalidateBrands() {
2032
+ brands = null;
2033
+ persist();
2034
+ }
2035
+ function invalidatePreferences() {
2036
+ preferences = null;
2037
+ persist();
2038
+ }
2039
+ function invalidateAppConfig(appId) {
2040
+ if (appId === void 0) appConfigs.clear();
2041
+ else appConfigs.delete(appId);
2042
+ persist();
2043
+ }
2044
+ function invalidateUserAppConfig(appId) {
2045
+ if (appId === void 0) userAppConfigs.clear();
2046
+ else userAppConfigs.delete(appId);
2047
+ persist();
2048
+ }
2049
+ function upsertBrand(brand) {
2050
+ if (!brands) return;
2051
+ const index = brands.data.findIndex((b) => b.id === brand.id);
2052
+ const data = index === -1 ? [...brands.data, brand] : brands.data.map((b, i) => i === index ? brand : b);
2053
+ brands = { data, fetchedAt: brands.fetchedAt };
2054
+ persist();
2055
+ }
2056
+ function removeBrand(brandId) {
2057
+ if (!brands?.data.some((b) => b.id === brandId)) return;
2058
+ brands = { data: brands.data.filter((b) => b.id !== brandId), fetchedAt: brands.fetchedAt };
2059
+ persist();
2060
+ }
2061
+ function setAppConfig(appId, config) {
2062
+ appConfigs.set(appId, { data: config, fetchedAt: Date.now() });
2063
+ persist();
2064
+ }
2065
+ function setUserAppConfig(appId, config) {
2066
+ userAppConfigs.set(appId, { data: config, fetchedAt: Date.now() });
2067
+ persist();
2068
+ }
2069
+ async function refresh() {
2070
+ invalidateApps();
2071
+ invalidateDataSources();
2072
+ invalidateUsers();
2073
+ invalidateBrands();
2074
+ invalidatePreferences();
2075
+ invalidateAppConfig();
2076
+ invalidateUserAppConfig();
2077
+ await Promise.all([listApps(), listDataSources()]);
2078
+ }
2079
+ const singletonLoaders = {
2080
+ apps: { message: "Loading apps\u2026", run: listApps },
2081
+ "data-sources": { message: "Loading data sources\u2026", run: listDataSources },
2082
+ users: { message: "Loading users\u2026", run: listUsers },
2083
+ brands: { message: "Loading brands\u2026", run: listBrands },
2084
+ preferences: { message: "Loading preferences\u2026", run: getPreferences }
2085
+ };
2086
+ function mapToRecord(map) {
2087
+ const out = {};
2088
+ for (const [key, entry] of map) out[key] = entry.data;
2089
+ return out;
2090
+ }
2091
+ function buildLoadResult() {
2092
+ return {
2093
+ apps: apps?.data ?? [],
2094
+ dataSources: dataSources?.data ?? [],
2095
+ users: users?.data ?? [],
2096
+ brands: brands?.data ?? [],
2097
+ preferences: preferences?.data ?? {},
2098
+ appConfigs: mapToRecord(appConfigs),
2099
+ userAppConfigs: mapToRecord(userAppConfigs)
2100
+ };
2101
+ }
2102
+ async function load(loadOptions) {
2103
+ const onProgress = loadOptions?.onProgress;
2104
+ const force = loadOptions?.force ?? true;
2105
+ const include = loadOptions?.include ?? DEFAULT_LOAD_STEPS;
2106
+ const envAppId = readAppIdFromEnv();
2107
+ const configAppIds = loadOptions?.configAppIds ?? (envAppId ? [envAppId] : []);
2108
+ const steps = [];
2109
+ for (const id of include) {
2110
+ if (id === "app-config" || id === "user-app-config") continue;
2111
+ steps.push({ id, message: singletonLoaders[id].message, run: singletonLoaders[id].run });
2112
+ }
2113
+ for (const appId of configAppIds) {
2114
+ steps.push({
2115
+ id: "app-config",
2116
+ appId,
2117
+ message: "Loading app config\u2026",
2118
+ run: () => getAppConfig(appId)
2119
+ });
2120
+ steps.push({
2121
+ id: "user-app-config",
2122
+ appId,
2123
+ message: "Loading user app config\u2026",
2124
+ run: () => getUserAppConfig(appId)
2125
+ });
2126
+ }
2127
+ if (force) {
2128
+ if (include.includes("apps")) invalidateApps();
2129
+ if (include.includes("data-sources")) invalidateDataSources();
2130
+ if (include.includes("users")) invalidateUsers();
2131
+ if (include.includes("brands")) invalidateBrands();
2132
+ if (include.includes("preferences")) invalidatePreferences();
2133
+ for (const appId of configAppIds) {
2134
+ invalidateAppConfig(appId);
2135
+ invalidateUserAppConfig(appId);
2136
+ }
2137
+ }
2138
+ const total = steps.length;
2139
+ for (let index = 0; index < total; index++) {
2140
+ const step = steps[index];
2141
+ const current = index + 1;
2142
+ onProgress?.({
2143
+ step: step.id,
2144
+ appId: step.appId,
2145
+ message: step.message,
2146
+ current,
2147
+ total,
2148
+ ratio: index / total,
2149
+ phase: "start"
2150
+ });
2151
+ try {
2152
+ await step.run();
2153
+ } catch (error) {
2154
+ onProgress?.({
2155
+ step: step.id,
2156
+ appId: step.appId,
2157
+ message: step.message,
2158
+ current,
2159
+ total,
2160
+ ratio: index / total,
2161
+ phase: "error",
2162
+ error
2163
+ });
2164
+ throw error;
2165
+ }
2166
+ onProgress?.({
2167
+ step: step.id,
2168
+ appId: step.appId,
2169
+ message: step.message,
2170
+ current,
2171
+ total,
2172
+ ratio: current / total,
2173
+ phase: "success"
2174
+ });
2175
+ }
2176
+ onProgress?.({
2177
+ step: null,
2178
+ message: "Ready",
2179
+ current: total,
2180
+ total,
2181
+ ratio: 1,
2182
+ phase: "complete"
2183
+ });
2184
+ return buildLoadResult();
2185
+ }
2186
+ return {
2187
+ listApps,
2188
+ listDataSources,
2189
+ listUsers,
2190
+ listBrands,
2191
+ getPreferences,
2192
+ getAppConfig,
2193
+ getUserAppConfig,
2194
+ load,
2195
+ listDataViews,
2196
+ listDataForms,
2197
+ refresh,
2198
+ invalidateApps,
2199
+ invalidateDataSources,
2200
+ invalidateUsers,
2201
+ invalidateBrands,
2202
+ invalidatePreferences,
2203
+ invalidateAppConfig,
2204
+ invalidateUserAppConfig,
2205
+ upsertDataView,
2206
+ removeDataView,
2207
+ upsertDataForm,
2208
+ removeDataForm,
2209
+ upsertBrand,
2210
+ removeBrand,
2211
+ setAppConfig,
2212
+ setUserAppConfig
2213
+ };
2214
+ }
2215
+
2216
+ // src/brand-client.ts
2217
+ function createBrandClient(client, options) {
2218
+ const basePath = "/v1/tenant/brands";
2219
+ const inventory = options?.inventory;
2220
+ async function list() {
2221
+ if (inventory) return inventory.listBrands();
2222
+ return unwrapEnvelope(await client.get(basePath));
2223
+ }
2224
+ async function get(brandId) {
2225
+ if (inventory) {
2226
+ const match = (await inventory.listBrands()).find((brand) => brand.id === brandId);
2227
+ if (match) return match;
2228
+ }
2229
+ return unwrapEnvelope(await client.get(`${basePath}/${brandId}`));
2230
+ }
2231
+ async function create(body) {
2232
+ const result = unwrapEnvelope(await client.post(basePath, body));
2233
+ inventory?.upsertBrand(result);
2234
+ return result;
2235
+ }
2236
+ async function update(brandId, body) {
2237
+ const result = unwrapEnvelope(await client.patch(`${basePath}/${brandId}`, body));
2238
+ if (body.archived === true) {
2239
+ inventory?.removeBrand(brandId);
2240
+ } else {
2241
+ inventory?.upsertBrand(result);
2242
+ }
2243
+ return result;
2244
+ }
2245
+ async function remove(brandId) {
2246
+ await client.delete(`${basePath}/${brandId}`);
2247
+ inventory?.removeBrand(brandId);
2248
+ }
2249
+ async function fetchFromWebsite(brandId) {
2250
+ const result = await client.put(
2251
+ `${basePath}/${brandId}/fetchFromWebsite`
2252
+ );
2253
+ if (inventory && result?.brand) {
2254
+ const existing = (await inventory.listBrands()).find((brand) => brand.id === brandId);
2255
+ if (existing) inventory.upsertBrand({ ...existing, ...result.brand });
2256
+ }
2257
+ return result;
2258
+ }
2259
+ return {
2260
+ list,
2261
+ get,
2262
+ create,
2263
+ update,
2264
+ remove,
2265
+ fetchFromWebsite
2266
+ };
2267
+ }
2268
+
2269
+ // src/user-identity-client.ts
2270
+ function createUserIdentityClient(client) {
2271
+ const basePath = "/v1/users/me/identity";
2272
+ async function saveMicrosoft(payload) {
2273
+ await client.put(`${basePath}/microsoft`, payload);
2274
+ }
2275
+ async function saveGoogle(payload) {
2276
+ await client.put(`${basePath}/google`, payload);
2277
+ }
2278
+ return { saveMicrosoft, saveGoogle };
2279
+ }
2280
+
2281
+ // src/envelope-interceptor.ts
2282
+ var STRIPPABLE_ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "success"]);
2283
+ function looksLikeEnvelope(value) {
2284
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
2285
+ return false;
2286
+ }
2287
+ const keys = Object.keys(value);
2288
+ return "data" in value && keys.every((key) => STRIPPABLE_ENVELOPE_KEYS.has(key));
2289
+ }
2290
+ var envelopeUnwrapInterceptor = {
2291
+ response: (response) => {
2292
+ if (looksLikeEnvelope(response.data)) {
2293
+ return {
2294
+ ...response,
2295
+ data: response.data.data
2296
+ };
2297
+ }
2298
+ return response;
2299
+ }
2300
+ };
2301
+
2302
+ export { createAppConfigClient, createBrandClient, createDataFormClient, createDataSourceClient, createDataViewClient, createDateUtils, createInventoryClient, createNumberUtils, createTemplateEngine, createUserAppConfigClient, createUserIdentityClient, envelopeUnwrapInterceptor, formatDurationAsHours, formatDurationAsTime, formatDurationAsWords, formatNumberToWords, getTenantPreferenceSummary, getTenantPreferences, jsonataHelpers, unwrapEnvelope };
2303
+ //# sourceMappingURL=index.js.map
2304
+ //# sourceMappingURL=index.js.map