@flusys/nestjs-shared 9.1.1 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +119 -18
  2. package/classes/api-controller.class.d.ts +1 -0
  3. package/classes/api-service.class.d.ts +7 -2
  4. package/classes/hybrid-cache.class.d.ts +17 -4
  5. package/constants/index.d.ts +1 -0
  6. package/constants/permissions.d.ts +9 -0
  7. package/fesm/183.js +7 -7
  8. package/fesm/47.js +1520 -0
  9. package/fesm/470.js +333 -382
  10. package/fesm/667.js +17 -17
  11. package/fesm/681.js +326 -129
  12. package/fesm/{948.js → 997.js} +45 -23
  13. package/fesm/chunks/123.js +17 -9
  14. package/fesm/chunks/37.js +5 -5
  15. package/fesm/classes/index.js +4 -3
  16. package/fesm/constants/index.js +18 -7
  17. package/fesm/decorators/index.js +120 -39
  18. package/fesm/dtos/index.js +1 -1
  19. package/fesm/entities/index.js +8 -8
  20. package/fesm/enums/index.js +2 -2
  21. package/fesm/exceptions/index.js +12 -12
  22. package/fesm/guards/index.js +201 -68
  23. package/fesm/index.js +95 -42
  24. package/fesm/interceptors/index.js +290 -590
  25. package/fesm/interfaces/index.js +97 -8
  26. package/fesm/middlewares/index.js +4 -4
  27. package/fesm/modules/index.js +2 -2
  28. package/fesm/pipes/index.js +8 -8
  29. package/fesm/utils/index.js +150 -478
  30. package/interceptors/idempotency.interceptor.d.ts +14 -2
  31. package/interceptors/slug.interceptor.d.ts +1 -0
  32. package/interfaces/expression.interface.d.ts +45 -0
  33. package/interfaces/index.d.ts +1 -0
  34. package/interfaces/permission-action-registry.interface.d.ts +1 -0
  35. package/interfaces/permission.interface.d.ts +1 -0
  36. package/modules/shared-permission-cache/shared-permission-cache.service.d.ts +3 -1
  37. package/modules/utils/utils.service.d.ts +6 -6
  38. package/package.json +3 -2
  39. package/utils/date-time.util.d.ts +0 -1
  40. package/utils/event-pattern.util.d.ts +1 -0
  41. package/utils/expression.util.d.ts +35 -0
  42. package/utils/index.d.ts +2 -0
  43. package/utils/permission-cache-key.util.d.ts +3 -0
  44. package/utils/query-helpers.util.d.ts +2 -2
  45. package/utils/safe-regex.util.d.ts +10 -0
  46. package/fesm/270.js +0 -659
package/fesm/47.js ADDED
@@ -0,0 +1,1520 @@
1
+ import { RE2JS } from "re2js";
2
+ export const __rspack_esm_id = 47;
3
+ export const __rspack_esm_ids = [47];
4
+ export const __webpack_modules__ = {
5
+ 6079(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
6
+ const EXPRESSION_ARITHMETIC_OPS = [
7
+ 'sum',
8
+ 'subtract',
9
+ 'multiply',
10
+ 'divide',
11
+ 'modulo',
12
+ 'power',
13
+ 'average',
14
+ 'min',
15
+ 'max'
16
+ ];
17
+ const EXPRESSION_COMPARISONS = [
18
+ 'equals',
19
+ 'not_equals',
20
+ 'greater_than',
21
+ 'less_than',
22
+ 'greater_or_equal',
23
+ 'less_or_equal',
24
+ 'contains',
25
+ 'not_contains',
26
+ 'starts_with',
27
+ 'ends_with',
28
+ 'in',
29
+ 'not_in',
30
+ 'is_empty',
31
+ 'is_not_empty',
32
+ 'is_true',
33
+ 'is_false',
34
+ 'matches',
35
+ 'not_matches'
36
+ ];
37
+ /** Comparisons that only look at the left side. */ const UNARY_EXPRESSION_COMPARISONS = [
38
+ 'is_empty',
39
+ 'is_not_empty',
40
+ 'is_true',
41
+ 'is_false'
42
+ ];
43
+ const EXPRESSION_DURATION_UNITS = [
44
+ 'second',
45
+ 'minute',
46
+ 'hour',
47
+ 'day',
48
+ 'week',
49
+ 'month',
50
+ 'year'
51
+ ];
52
+ const EXPRESSION_DATE_PARTS = [
53
+ 'year',
54
+ 'month',
55
+ 'day',
56
+ 'weekday',
57
+ 'hour',
58
+ 'minute'
59
+ ];
60
+
61
+ __webpack_require__.d(__webpack_exports__, {
62
+ }, {
63
+ Me: EXPRESSION_COMPARISONS,
64
+ Vq: EXPRESSION_DATE_PARTS,
65
+ YH: EXPRESSION_DURATION_UNITS,
66
+ dL: EXPRESSION_ARITHMETIC_OPS,
67
+ kA: UNARY_EXPRESSION_COMPARISONS
68
+ });
69
+
70
+
71
+ },
72
+ 4578(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
73
+
74
+ // EXPORTS
75
+ __webpack_require__.d(__webpack_exports__, {
76
+ s8: () => (/* reexport */ permission_cache_key_util/* .DEFAULT_COMPANY_PERMISSION_KEY_FORMAT */.s8),
77
+ q6: () => (/* reexport */ permission_cache_key_util/* .DEFAULT_USER_PERMISSION_KEY_FORMAT */.q6),
78
+ Dd: () => (/* reexport */ EXPRESSION_FUNCTIONS),
79
+ wj: () => (/* reexport */ EXPRESSION_LIMITS),
80
+ tj: () => (/* reexport */ ExpressionError),
81
+ Df: () => (/* reexport */ (/* inlined export .MAX_PERMISSION_LOGIC_CODES */50)),
82
+ kW: () => (/* reexport */ (/* inlined export .MAX_PERMISSION_LOGIC_DEPTH */5)),
83
+ ZA: () => (/* reexport */ SAFE_REGEX_LIMITS),
84
+ f7: () => (/* reexport */ applyBranchFilter),
85
+ wf: () => (/* reexport */ applyCompanyFilter),
86
+ P: () => (/* reexport */ assertValidConditionGroup),
87
+ bh: () => (/* reexport */ assertValidExpression),
88
+ kQ: () => (/* reexport */ buildCompanyWhereCondition),
89
+ fJ: () => (/* reexport */ buildCookieOptions),
90
+ oV: () => (/* reexport */ buildFrontendUrl),
91
+ nt: () => (/* reexport */ permission_cache_key_util/* .buildPermissionCacheKey */.nt),
92
+ qW: () => (/* reexport */ cache_tenant_util/* .cacheTenantId */.q),
93
+ Sf: () => (/* reexport */ collectBranchAncestorIds),
94
+ qY: () => (/* reexport */ collectBranchDescendantIds),
95
+ Yc: () => (/* reexport */ compileSafeRegex),
96
+ ZD: () => (/* reexport */ escapeHtml),
97
+ qo: () => (/* reexport */ escapeHtmlVariables),
98
+ Sb: () => (/* reexport */ evaluateConditionGroup),
99
+ O4: () => (/* reexport */ evaluateExpression),
100
+ Ng: () => (/* reexport */ permission_match_util/* .evaluatePermissionLogic */.Ng),
101
+ HK: () => (/* reexport */ expressionToNumber),
102
+ zj: () => (/* reexport */ expressionToText),
103
+ hX: () => (/* reexport */ extractFrontendUrl),
104
+ Sd: () => (/* reexport */ formatInTimezone),
105
+ sN: () => (/* reexport */ generateSecureToken),
106
+ z9: () => (/* reexport */ string_util/* .generateSlug */.z),
107
+ oo: () => (/* reexport */ string_util/* .generateUniqueSlug */.o),
108
+ gN: () => (/* reexport */ getBranchPath),
109
+ f: () => (/* reexport */ hasCompanyId),
110
+ QK: () => (/* reexport */ hashToken),
111
+ xp: () => (/* reexport */ permission_cache_key_util/* .invalidatePermissionCache */.xp),
112
+ QU: () => (/* reexport */ isBranchWithin),
113
+ wh: () => (/* reexport */ isBrowserRequest),
114
+ _d: () => (/* reexport */ isExpired),
115
+ tX: () => (/* reexport */ isExpressionError),
116
+ _c: () => (/* reexport */ event_pattern_util/* .isMultiWildcard */._c),
117
+ Gd: () => (/* reexport */ event_pattern_util/* .isSensitiveKey */.Gd),
118
+ lk: () => (/* reexport */ optional_module_util/* .loadOptionalModule */.l),
119
+ CQ: () => (/* reexport */ permission_match_util/* .loadPermissionCodes */.CQ),
120
+ vf: () => (/* reexport */ localToUtc),
121
+ qe: () => (/* reexport */ event_pattern_util/* .matchEventPattern */.qe),
122
+ xY: () => (/* reexport */ permission_match_util/* .matchesPermission */.xY),
123
+ RG: () => (/* reexport */ messageRef),
124
+ Ty: () => (/* reexport */ normalizeBranchIds),
125
+ Ju: () => (/* reexport */ parseDurationToMs),
126
+ MO: () => (/* reexport */ permission_match_util/* .permissionLogicCodes */.MO),
127
+ HU: () => (/* reexport */ permission_match_util/* .permissionLogicProblem */.HU),
128
+ Rw: () => (/* reexport */ permission_cache_key_util/* .resolvePermissionCacheKey */.Rw),
129
+ _X: () => (/* reexport */ safeRegexProblem),
130
+ IN: () => (/* reexport */ event_pattern_util/* .sanitizeEventPayload */.IN),
131
+ v4: () => (/* reexport */ utcToLocal),
132
+ bE: () => (/* reexport */ validateCompanyOwnership),
133
+ o0: () => (/* reexport */ withSavepoint)
134
+ });
135
+
136
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/branch-hierarchy.util.ts
137
+ /** Each id once, in input order, without empty values. */ function normalizeBranchIds(ids) {
138
+ const list = Array.isArray(ids) ? ids : [
139
+ ids
140
+ ];
141
+ return [
142
+ ...new Set(list.filter((id)=>typeof id === 'string' && id !== ''))
143
+ ];
144
+ }
145
+ function depthLimit(maxDepth) {
146
+ return typeof maxDepth === 'number' && Number.isFinite(maxDepth) && maxDepth >= 0 ? Math.floor(maxDepth) : Infinity;
147
+ }
148
+ /** The first node per id wins, so duplicates never change the answer. */ function indexNodes(nodes) {
149
+ const byId = new Map();
150
+ for (const node of nodes)if (node?.id && !byId.has(node.id)) byId.set(node.id, node);
151
+ return byId;
152
+ }
153
+ function childrenIndex(nodes) {
154
+ const children = new Map();
155
+ for (const node of nodes){
156
+ if (!node.parentId || node.parentId === node.id) continue;
157
+ const siblings = children.get(node.parentId);
158
+ if (siblings) siblings.push(node.id);
159
+ else children.set(node.parentId, [
160
+ node.id
161
+ ]);
162
+ }
163
+ return children;
164
+ }
165
+ /**
166
+ * Every branch under `rootIds`, level by level (children, then grandchildren, ...), from a flat
167
+ * `{ id, parentId }` list. With `includeSelf` the given ids come first - kept even when they are not in
168
+ * `nodes`, so a caller never loses a branch it asked about. Safe against duplicates and parent cycles.
169
+ */ function collectBranchDescendantIds(nodes, rootIds, { includeSelf = false, maxDepth } = {}) {
170
+ const roots = normalizeBranchIds(rootIds);
171
+ const limit = depthLimit(maxDepth);
172
+ const children = childrenIndex(indexNodes(nodes).values());
173
+ const visited = new Set(roots);
174
+ const descendants = [];
175
+ let level = roots;
176
+ for(let depth = 1; depth <= limit && level.length; depth++){
177
+ const next = [];
178
+ for (const parentId of level){
179
+ for (const id of children.get(parentId) ?? []){
180
+ if (visited.has(id)) continue;
181
+ visited.add(id);
182
+ descendants.push(id);
183
+ next.push(id);
184
+ }
185
+ }
186
+ level = next;
187
+ }
188
+ return includeSelf ? [
189
+ ...roots,
190
+ ...descendants
191
+ ] : descendants;
192
+ }
193
+ /**
194
+ * The parent chain of `branchId`, nearest parent first, up to the root. Only branches in `nodes` are
195
+ * returned - the walk stops at a parent that is missing (e.g. soft-deleted). With `includeSelf` the
196
+ * branch itself comes first even when it is not in `nodes`. Safe against parent cycles.
197
+ */ function collectBranchAncestorIds(nodes, branchId, { includeSelf = false, maxDepth } = {}) {
198
+ if (!branchId) return [];
199
+ const byId = indexNodes(nodes);
200
+ const limit = depthLimit(maxDepth);
201
+ const ancestors = includeSelf ? [
202
+ branchId
203
+ ] : [];
204
+ const visited = new Set([
205
+ branchId
206
+ ]);
207
+ let parentId = byId.get(branchId)?.parentId;
208
+ for(let depth = 1; depth <= limit && parentId && byId.has(parentId) && !visited.has(parentId); depth++){
209
+ visited.add(parentId);
210
+ ancestors.push(parentId);
211
+ parentId = byId.get(parentId)?.parentId;
212
+ }
213
+ return ancestors;
214
+ }
215
+ /** True when `branchId` is `ancestorId` itself or sits anywhere under it. */ function isBranchWithin(nodes, branchId, ancestorId) {
216
+ if (!branchId || !ancestorId) return false;
217
+ return branchId === ancestorId || collectBranchAncestorIds(nodes, branchId).includes(ancestorId);
218
+ }
219
+ /**
220
+ * The nodes from the top-most known ancestor down to `branchId` itself (e.g. for "HQ / East / East 1").
221
+ * Empty when `branchId` is not in `nodes`.
222
+ */ function getBranchPath(nodes, branchId) {
223
+ if (!branchId) return [];
224
+ const byId = indexNodes(nodes);
225
+ if (!byId.has(branchId)) return [];
226
+ return collectBranchAncestorIds(nodes, branchId, {
227
+ includeSelf: true
228
+ }).map((id)=>byId.get(id)).toReversed();
229
+ }
230
+
231
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/cache-tenant.util.ts
232
+ var cache_tenant_util = __webpack_require__(8154);
233
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/date-time.util.ts
234
+ function getOffsetMinutes(utcDate, timezone) {
235
+ const extract = (tz)=>{
236
+ const parts = new Intl.DateTimeFormat('en-US', {
237
+ timeZone: tz,
238
+ year: 'numeric',
239
+ month: '2-digit',
240
+ day: '2-digit',
241
+ hour: '2-digit',
242
+ minute: '2-digit',
243
+ second: '2-digit',
244
+ hour12: false
245
+ }).formatToParts(utcDate);
246
+ const p = Object.fromEntries(parts.filter((x)=>x.type !== 'literal').map((x)=>[
247
+ x.type,
248
+ parseInt(x.value)
249
+ ]));
250
+ return Date.UTC(p['year'], p['month'] - 1, p['day'], p['hour'], p['minute'], p['second']);
251
+ };
252
+ return (extract(timezone) - extract('UTC')) / 60_000;
253
+ }
254
+ function localToUtc(dateStr, timeStr, timezone) {
255
+ const [year, month, day] = dateStr.split('-').map(Number);
256
+ const [hours, minutes] = timeStr.split(':').map(Number);
257
+ const approx = new Date(Date.UTC(year, month - 1, day, hours, minutes, 0));
258
+ const offset = getOffsetMinutes(approx, timezone);
259
+ const utcDate = new Date(approx.getTime() - offset * 60_000);
260
+ // DST boundary guard: re-check offset after adjustment
261
+ const finalOffset = getOffsetMinutes(utcDate, timezone);
262
+ return finalOffset !== offset ? new Date(approx.getTime() - finalOffset * 60_000) : utcDate;
263
+ }
264
+ function utcToLocal(utcDate, timezone) {
265
+ const d = typeof utcDate === 'string' ? new Date(utcDate) : utcDate;
266
+ const parts = new Intl.DateTimeFormat('en-CA', {
267
+ timeZone: timezone,
268
+ year: 'numeric',
269
+ month: '2-digit',
270
+ day: '2-digit',
271
+ hour: '2-digit',
272
+ minute: '2-digit',
273
+ hour12: false
274
+ }).formatToParts(d);
275
+ const p = Object.fromEntries(parts.filter((x)=>x.type !== 'literal').map((x)=>[
276
+ x.type,
277
+ x.value
278
+ ]));
279
+ // en-CA formats midnight hour as '24' — normalize to '00'
280
+ const hour = p['hour'] === '24' ? '00' : p['hour'];
281
+ return {
282
+ date: `${p['year']}-${p['month']}-${p['day']}`,
283
+ time: `${hour}:${p['minute']}`,
284
+ display: new Intl.DateTimeFormat('en-US', {
285
+ timeZone: timezone,
286
+ dateStyle: 'medium',
287
+ timeStyle: 'short'
288
+ }).format(d)
289
+ };
290
+ }
291
+ function formatInTimezone(utcDate, timezone, options = {
292
+ dateStyle: 'medium',
293
+ timeStyle: 'short'
294
+ }) {
295
+ const d = typeof utcDate === 'string' ? new Date(utcDate) : utcDate;
296
+ return new Intl.DateTimeFormat('en-US', {
297
+ ...options,
298
+ timeZone: timezone
299
+ }).format(d);
300
+ }
301
+
302
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/event-pattern.util.ts
303
+ var event_pattern_util = __webpack_require__(8456);
304
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/interfaces/expression.interface.ts
305
+ var expression_interface = __webpack_require__(6079);
306
+ ;// CONCATENATED MODULE: external "re2js"
307
+
308
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/safe-regex.util.ts
309
+
310
+ const SAFE_REGEX_LIMITS = {
311
+ MAX_PATTERN_LENGTH: 500,
312
+ MAX_INPUT_LENGTH: 10_000,
313
+ /** Largest `{n,m}` count, also for the product of nested counts. */ MAX_REPEAT: 100,
314
+ /** How much larger counted repeats may make the unrolled pattern than the pattern itself. */ MAX_REPEAT_EXPANSION: 300
315
+ };
316
+ const MAX_CACHED_PATTERNS = 200;
317
+ const compiled = new Map();
318
+ const tooComplex = new Map();
319
+ function remember(cache, pattern, make) {
320
+ if (cache.has(pattern)) return cache.get(pattern);
321
+ const value = make(pattern);
322
+ if (cache.size >= MAX_CACHED_PATTERNS) cache.delete(cache.keys().next().value);
323
+ cache.set(pattern, value);
324
+ return value;
325
+ }
326
+ /** Why an author-written pattern cannot be used, or null when it compiles within the limits. */ function safeRegexProblem(pattern) {
327
+ if (pattern.length > SAFE_REGEX_LIMITS.MAX_PATTERN_LENGTH) return 'too_long';
328
+ if (remember(tooComplex, pattern, isTooComplex)) return 'too_complex';
329
+ try {
330
+ compileSafeRegex(pattern);
331
+ return null;
332
+ } catch {
333
+ return 'invalid';
334
+ }
335
+ }
336
+ /** RE2 (linear-time) compile with a small cache. Call `safeRegexProblem` first for author input. */ function compileSafeRegex(pattern) {
337
+ return remember(compiled, pattern, (p)=>RE2JS.compile(p));
338
+ }
339
+ const newFrame = ()=>({
340
+ size: 0,
341
+ last: 0,
342
+ lastProduct: 1,
343
+ maxProduct: 1
344
+ });
345
+ /**
346
+ * RE2 unrolls counted repeats (`x{2,50}` becomes 50 copies of x), so match time grows with the
347
+ * product of nested counts. Rejects a count above MAX_REPEAT, nested counts whose product
348
+ * is above it, and a pattern whose unrolled size grows by more than MAX_REPEAT_EXPANSION.
349
+ * `*`, `+` and `?` do not unroll and stay allowed, nested or not.
350
+ */ function isTooComplex(pattern) {
351
+ const { MAX_REPEAT, MAX_REPEAT_EXPANSION } = SAFE_REGEX_LIMITS;
352
+ const stack = [
353
+ newFrame()
354
+ ];
355
+ const top = ()=>stack[stack.length - 1];
356
+ let atoms = 0;
357
+ const atom = (size, product)=>{
358
+ const frame = top();
359
+ frame.size += size;
360
+ frame.last = size;
361
+ frame.lastProduct = product;
362
+ frame.maxProduct = Math.max(frame.maxProduct, product);
363
+ };
364
+ let i = 0;
365
+ while(i < pattern.length){
366
+ const c = pattern[i];
367
+ if (c === '\\') {
368
+ const next = pattern[i + 1];
369
+ i += 2;
370
+ if ((next === 'p' || next === 'P' || next === 'x') && pattern[i] === '{') i = closing(pattern, i, '}');
371
+ atoms++;
372
+ atom(1, 1);
373
+ } else if (c === '[') {
374
+ i = classEnd(pattern, i);
375
+ atoms++;
376
+ atom(1, 1);
377
+ } else if (c === '(') {
378
+ i++;
379
+ if (pattern[i] === '?') {
380
+ const flagsOnly = /^\?[a-zA-Z-]*\)/.exec(pattern.slice(i));
381
+ if (flagsOnly) {
382
+ i += flagsOnly[0].length;
383
+ continue;
384
+ }
385
+ const marker = /^\?(?:P?<[^>]*>|[a-zA-Z-]*:)/.exec(pattern.slice(i));
386
+ i += marker ? marker[0].length : 1;
387
+ }
388
+ stack.push(newFrame());
389
+ } else if (c === ')') {
390
+ i++;
391
+ if (stack.length === 1) continue;
392
+ const group = stack.pop();
393
+ atom(group.size, group.maxProduct);
394
+ } else if (c === '|') {
395
+ i++;
396
+ top().last = 0;
397
+ top().lastProduct = 1;
398
+ } else if (c === '{') {
399
+ const repeat = /^\{(\d+)(,(\d*))?\}\??/.exec(pattern.slice(i));
400
+ if (!repeat) {
401
+ i++;
402
+ atoms++;
403
+ atom(1, 1);
404
+ continue;
405
+ }
406
+ i += repeat[0].length;
407
+ const min = Number(repeat[1]);
408
+ const max = repeat[2] === undefined ? min : repeat[3] ? Number(repeat[3]) : min + 1;
409
+ if (min > MAX_REPEAT || max > MAX_REPEAT) return true;
410
+ const frame = top();
411
+ const product = frame.lastProduct * Math.max(max, 1);
412
+ if (product > MAX_REPEAT) return true;
413
+ const extra = frame.last * (Math.max(max, 1) - 1);
414
+ frame.size += extra;
415
+ frame.last += extra;
416
+ frame.lastProduct = product;
417
+ frame.maxProduct = Math.max(frame.maxProduct, product);
418
+ } else {
419
+ i++;
420
+ if (c !== '*' && c !== '+' && c !== '?') {
421
+ atoms++;
422
+ atom(1, 1);
423
+ }
424
+ }
425
+ }
426
+ while(stack.length > 1){
427
+ const group = stack.pop();
428
+ atom(group.size, group.maxProduct);
429
+ }
430
+ return stack[0].size - atoms > MAX_REPEAT_EXPANSION;
431
+ }
432
+ function closing(pattern, from, char) {
433
+ const end = pattern.indexOf(char, from);
434
+ return end < 0 ? pattern.length : end + 1;
435
+ }
436
+ function classEnd(pattern, start) {
437
+ let j = start + 1;
438
+ if (pattern[j] === '^') j++;
439
+ if (pattern[j] === ']') j++;
440
+ while(j < pattern.length && pattern[j] !== ']'){
441
+ if (pattern[j] === '\\') j += 2;
442
+ else if (pattern.startsWith('[:', j)) j = closing(pattern, j + 2, ']');
443
+ else j++;
444
+ }
445
+ return j + 1;
446
+ }
447
+
448
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/expression.util.ts
449
+
450
+
451
+ const EXPRESSION_LIMITS = {
452
+ MAX_DEPTH: 16,
453
+ MAX_NODES: 500,
454
+ MAX_TEMPLATE_LENGTH: 4000,
455
+ MAX_TEXT_LENGTH: 100_000,
456
+ MAX_PAD_LENGTH: 1000
457
+ };
458
+ /** Plain error so each caller maps `code` to its own message key. */ class ExpressionError extends Error {
459
+ code;
460
+ variables;
461
+ constructor(code, variables = {}){
462
+ super(`${code} ${JSON.stringify(variables)}`), this.code = code, this.variables = variables;
463
+ this.name = 'ExpressionError';
464
+ }
465
+ }
466
+ /** By name, not instanceof: the class may come from another bundle. */ function isExpressionError(error) {
467
+ return error instanceof Error && error.name === 'ExpressionError' && 'code' in error;
468
+ }
469
+ const TEMPLATE_PLACEHOLDER = /\{\{\s*([\w.-]+)\s*\}\}/g;
470
+ const DAY_MS = 86_400_000;
471
+ const FIXED_UNIT_MS = {
472
+ second: 1000,
473
+ minute: 60_000,
474
+ hour: 3_600_000,
475
+ day: DAY_MS,
476
+ week: 7 * DAY_MS
477
+ };
478
+ // ── Value coercion ──────────────────────────────────────────────────────────────────────
479
+ const isBlank = (value)=>value === null || value === undefined || typeof value === 'string' && value.trim() === '';
480
+ /** Text of any value; null for null/undefined. Lists are joined with ", ". */ function expressionToText(value) {
481
+ if (value === null || value === undefined) return null;
482
+ if (typeof value === 'string') return value;
483
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
484
+ if (value instanceof Date) return value.toISOString();
485
+ if (Array.isArray(value)) return value.map((item)=>expressionToText(item) ?? '').join(', ');
486
+ return JSON.stringify(value);
487
+ }
488
+ /** Number of a value; null when blank, throws for text that is not a number. */ function expressionToNumber(value) {
489
+ if (isBlank(value)) return null;
490
+ if (typeof value === 'number') {
491
+ if (!Number.isFinite(value)) throw new ExpressionError('expected_number', {
492
+ value: String(value)
493
+ });
494
+ return value;
495
+ }
496
+ if (typeof value === 'boolean') return value ? 1 : 0;
497
+ if (typeof value === 'string') {
498
+ const n = Number(value.trim());
499
+ if (Number.isFinite(n)) return n;
500
+ }
501
+ throw new ExpressionError('expected_number', {
502
+ value: expressionToText(value) ?? ''
503
+ });
504
+ }
505
+ function tryNumber(value) {
506
+ try {
507
+ return expressionToNumber(value);
508
+ } catch {
509
+ return null;
510
+ }
511
+ }
512
+ function toTime(value) {
513
+ if (isBlank(value)) return null;
514
+ const time = value instanceof Date ? value.getTime() : typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(value) : Number.NaN;
515
+ if (!Number.isFinite(time)) throw new ExpressionError('expected_date', {
516
+ value: expressionToText(value) ?? ''
517
+ });
518
+ return time;
519
+ }
520
+ function toInteger(value, fallback) {
521
+ const n = expressionToNumber(value);
522
+ return n === null ? fallback : Math.trunc(n);
523
+ }
524
+ function toUnit(value) {
525
+ if (typeof value === 'string' && expression_interface/* .EXPRESSION_DURATION_UNITS.includes */.YH.includes(value)) return value;
526
+ throw new ExpressionError('invalid_unit', {
527
+ unit: String(value),
528
+ units: expression_interface/* .EXPRESSION_DURATION_UNITS.join */.YH.join(', ')
529
+ });
530
+ }
531
+ function limitText(text) {
532
+ if (text.length > EXPRESSION_LIMITS.MAX_TEXT_LENGTH) throw new ExpressionError('text_too_long', {
533
+ max: EXPRESSION_LIMITS.MAX_TEXT_LENGTH
534
+ });
535
+ return text;
536
+ }
537
+ const textFn = (map)=>([value])=>{
538
+ const text = expressionToText(value);
539
+ return text === null ? null : map(text);
540
+ };
541
+ const numberFn = (map)=>([value])=>{
542
+ const n = expressionToNumber(value);
543
+ return n === null ? null : map(n);
544
+ };
545
+ // ── Regex (RE2, linear time) ────────────────────────────────────────────────────────────
546
+ function regexProblemError(pattern) {
547
+ switch(safeRegexProblem(pattern)){
548
+ case 'too_long':
549
+ return new ExpressionError('regex_too_long', {
550
+ max: SAFE_REGEX_LIMITS.MAX_PATTERN_LENGTH
551
+ });
552
+ case 'too_complex':
553
+ return new ExpressionError('regex_too_complex', {
554
+ max: SAFE_REGEX_LIMITS.MAX_REPEAT
555
+ });
556
+ case 'invalid':
557
+ return new ExpressionError('regex_invalid', {
558
+ pattern
559
+ });
560
+ default:
561
+ return null;
562
+ }
563
+ }
564
+ function prepareRegex(input, pattern) {
565
+ const source = expressionToText(pattern) ?? '';
566
+ const problem = regexProblemError(source);
567
+ if (problem) throw problem;
568
+ const text = expressionToText(input);
569
+ if (text === null) return null;
570
+ if (text.length > SAFE_REGEX_LIMITS.MAX_INPUT_LENGTH) throw new ExpressionError('regex_input_too_long', {
571
+ max: SAFE_REGEX_LIMITS.MAX_INPUT_LENGTH
572
+ });
573
+ return {
574
+ regex: compileSafeRegex(source),
575
+ text
576
+ };
577
+ }
578
+ function regexTest(input, pattern) {
579
+ const prepared = prepareRegex(input, pattern);
580
+ return prepared ? prepared.regex.matcher(prepared.text).find() : false;
581
+ }
582
+ // ── Dates ───────────────────────────────────────────────────────────────────────────────
583
+ function addMonths(time, months) {
584
+ const date = new Date(time);
585
+ const day = date.getUTCDate();
586
+ date.setUTCDate(1);
587
+ date.setUTCMonth(date.getUTCMonth() + months);
588
+ const lastDay = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate();
589
+ date.setUTCDate(Math.min(day, lastDay));
590
+ return date.getTime();
591
+ }
592
+ /** Whole calendar months from `from` to `to`; negative when `to` is earlier, always `-monthsBetween(to, from)`. */ function monthsBetween(from, to) {
593
+ if (to < from) return -monthsBetween(to, from);
594
+ const a = new Date(from);
595
+ const b = new Date(to);
596
+ let months = (b.getUTCFullYear() - a.getUTCFullYear()) * 12 + (b.getUTCMonth() - a.getUTCMonth());
597
+ if (addMonths(from, months) > to) months--;
598
+ return months;
599
+ }
600
+ function dateDiff(a, b, unit) {
601
+ const to = toTime(a);
602
+ const from = toTime(b);
603
+ const resolved = toUnit(unit);
604
+ if (to === null || from === null) return null;
605
+ const diff = resolved === 'month' ? monthsBetween(from, to) : resolved === 'year' ? Math.trunc(monthsBetween(from, to) / 12) : Math.trunc((to - from) / FIXED_UNIT_MS[resolved]);
606
+ return diff + 0;
607
+ }
608
+ function addDuration(value, amount, unit) {
609
+ const time = toTime(value);
610
+ const n = expressionToNumber(amount) ?? 0;
611
+ const resolved = toUnit(unit);
612
+ if (time === null) return null;
613
+ if (resolved === 'month' || resolved === 'year') return new Date(addMonths(time, Math.trunc(n) * (resolved === 'year' ? 12 : 1))).toISOString();
614
+ return new Date(time + n * FIXED_UNIT_MS[resolved]).toISOString();
615
+ }
616
+ function datePart(value, part) {
617
+ if (typeof part !== 'string' || !expression_interface/* .EXPRESSION_DATE_PARTS.includes */.Vq.includes(part)) {
618
+ throw new ExpressionError('invalid_date_part', {
619
+ part: String(part),
620
+ parts: expression_interface/* .EXPRESSION_DATE_PARTS.join */.Vq.join(', ')
621
+ });
622
+ }
623
+ const time = toTime(value);
624
+ if (time === null) return null;
625
+ const date = new Date(time);
626
+ const parts = {
627
+ year: date.getUTCFullYear(),
628
+ month: date.getUTCMonth() + 1,
629
+ day: date.getUTCDate(),
630
+ weekday: date.getUTCDay(),
631
+ hour: date.getUTCHours(),
632
+ minute: date.getUTCMinutes()
633
+ };
634
+ return parts[part];
635
+ }
636
+ // ── Built-in functions ──────────────────────────────────────────────────────────────────
637
+ const EXPRESSION_FUNCTIONS = {
638
+ LOWER: {
639
+ minArgs: 1,
640
+ maxArgs: 1,
641
+ call: textFn((t)=>t.toLowerCase())
642
+ },
643
+ UPPER: {
644
+ minArgs: 1,
645
+ maxArgs: 1,
646
+ call: textFn((t)=>t.toUpperCase())
647
+ },
648
+ TRIM: {
649
+ minArgs: 1,
650
+ maxArgs: 1,
651
+ call: textFn((t)=>t.trim())
652
+ },
653
+ CAPITALIZE: {
654
+ minArgs: 1,
655
+ maxArgs: 1,
656
+ call: textFn((t)=>t.toLowerCase().replace(/(^|\s)(\S)/g, (_, space, c)=>space + c.toUpperCase()))
657
+ },
658
+ LENGTH: {
659
+ minArgs: 1,
660
+ maxArgs: 1,
661
+ call: ([value])=>Array.isArray(value) ? value.length : expressionToText(value)?.length ?? 0
662
+ },
663
+ SUBSTRING: {
664
+ minArgs: 2,
665
+ maxArgs: 3,
666
+ call: ([value, start, length])=>{
667
+ const text = expressionToText(value);
668
+ if (text === null) return null;
669
+ const from = Math.max(toInteger(start, 1), 1) - 1;
670
+ return isBlank(length) ? text.slice(from) : text.slice(from, from + Math.max(toInteger(length, 0), 0));
671
+ }
672
+ },
673
+ LEFT: {
674
+ minArgs: 2,
675
+ maxArgs: 2,
676
+ call: ([value, count])=>{
677
+ const text = expressionToText(value);
678
+ return text === null ? null : text.slice(0, Math.max(toInteger(count, 0), 0));
679
+ }
680
+ },
681
+ RIGHT: {
682
+ minArgs: 2,
683
+ maxArgs: 2,
684
+ call: ([value, count])=>{
685
+ const text = expressionToText(value);
686
+ const n = Math.max(toInteger(count, 0), 0);
687
+ return text === null ? null : n === 0 ? '' : text.slice(-n);
688
+ }
689
+ },
690
+ REPLACE: {
691
+ minArgs: 3,
692
+ maxArgs: 3,
693
+ call: ([value, search, replacement])=>{
694
+ const text = expressionToText(value);
695
+ if (text === null) return null;
696
+ const needle = expressionToText(search) ?? '';
697
+ const insert = expressionToText(replacement) ?? '';
698
+ return needle ? limitText(text.replaceAll(needle, ()=>insert)) : text;
699
+ }
700
+ },
701
+ SPLIT_PART: {
702
+ minArgs: 3,
703
+ maxArgs: 3,
704
+ call: ([value, separator, position])=>{
705
+ const text = expressionToText(value);
706
+ const sep = expressionToText(separator);
707
+ if (text === null || !sep) return null;
708
+ const parts = text.split(sep);
709
+ const n = toInteger(position, 1);
710
+ const part = n === 0 ? undefined : parts[n > 0 ? n - 1 : parts.length + n];
711
+ return part === undefined ? null : part.trim();
712
+ }
713
+ },
714
+ PAD_START: {
715
+ minArgs: 2,
716
+ maxArgs: 3,
717
+ call: ([value, length, fill])=>{
718
+ const text = expressionToText(value) ?? '';
719
+ const target = Math.min(Math.max(toInteger(length, 0), 0), EXPRESSION_LIMITS.MAX_PAD_LENGTH);
720
+ return text.padStart(target, expressionToText(fill) || ' ');
721
+ }
722
+ },
723
+ REGEX_EXTRACT: {
724
+ minArgs: 2,
725
+ maxArgs: 3,
726
+ regexArgs: [
727
+ 1
728
+ ],
729
+ call: ([value, pattern, group])=>{
730
+ const prepared = prepareRegex(value, pattern);
731
+ if (!prepared) return null;
732
+ const count = prepared.regex.groupCount();
733
+ const index = isBlank(group) ? count > 0 ? 1 : 0 : toInteger(group, 0);
734
+ if (index < 0 || index > count) return null;
735
+ const matcher = prepared.regex.matcher(prepared.text);
736
+ return matcher.find() ? matcher.group(index) ?? null : null;
737
+ }
738
+ },
739
+ REGEX_REPLACE: {
740
+ minArgs: 3,
741
+ maxArgs: 3,
742
+ regexArgs: [
743
+ 1
744
+ ],
745
+ call: ([value, pattern, replacement])=>{
746
+ const prepared = prepareRegex(value, pattern);
747
+ return prepared ? limitText(prepared.regex.matcher(prepared.text).replaceAll(expressionToText(replacement) ?? '')) : null;
748
+ }
749
+ },
750
+ REGEX_TEST: {
751
+ minArgs: 2,
752
+ maxArgs: 2,
753
+ regexArgs: [
754
+ 1
755
+ ],
756
+ call: ([value, pattern])=>regexTest(value, pattern)
757
+ },
758
+ TO_TEXT: {
759
+ minArgs: 1,
760
+ maxArgs: 1,
761
+ call: ([value])=>expressionToText(value)
762
+ },
763
+ JOIN: {
764
+ minArgs: 1,
765
+ maxArgs: 2,
766
+ call: ([value, separator])=>{
767
+ const items = Array.isArray(value) ? value : isBlank(value) ? [] : [
768
+ value
769
+ ];
770
+ const sep = separator === null || separator === undefined || separator === '' ? ', ' : expressionToText(separator);
771
+ return limitText(items.map((item)=>expressionToText(item) ?? '').filter(Boolean).join(sep));
772
+ }
773
+ },
774
+ ROUND: {
775
+ minArgs: 1,
776
+ maxArgs: 2,
777
+ call: ([value, digits])=>{
778
+ const n = expressionToNumber(value);
779
+ if (n === null) return null;
780
+ const factor = 10 ** Math.min(Math.max(toInteger(digits, 0), 0), 10);
781
+ return Math.round(n * factor) / factor;
782
+ }
783
+ },
784
+ FLOOR: {
785
+ minArgs: 1,
786
+ maxArgs: 1,
787
+ call: numberFn(Math.floor)
788
+ },
789
+ CEIL: {
790
+ minArgs: 1,
791
+ maxArgs: 1,
792
+ call: numberFn(Math.ceil)
793
+ },
794
+ ABS: {
795
+ minArgs: 1,
796
+ maxArgs: 1,
797
+ call: numberFn(Math.abs)
798
+ },
799
+ TO_NUMBER: {
800
+ minArgs: 1,
801
+ maxArgs: 1,
802
+ call: ([value])=>tryNumber(value)
803
+ },
804
+ NOW: {
805
+ minArgs: 0,
806
+ maxArgs: 0,
807
+ call: (_, ctx)=>(ctx.now?.() ?? new Date()).toISOString()
808
+ },
809
+ TODAY: {
810
+ minArgs: 0,
811
+ maxArgs: 0,
812
+ call: (_, ctx)=>(ctx.now?.() ?? new Date()).toISOString().slice(0, 10)
813
+ },
814
+ DATE_DIFF: {
815
+ minArgs: 3,
816
+ maxArgs: 3,
817
+ call: ([a, b, unit])=>dateDiff(a, b, unit)
818
+ },
819
+ ADD_DURATION: {
820
+ minArgs: 3,
821
+ maxArgs: 3,
822
+ call: ([value, amount, unit])=>addDuration(value, amount, unit)
823
+ },
824
+ DATE_PART: {
825
+ minArgs: 2,
826
+ maxArgs: 2,
827
+ call: ([value, part])=>datePart(value, part)
828
+ },
829
+ COALESCE: {
830
+ minArgs: 1,
831
+ call: (args)=>args.find((value)=>!isBlank(value)) ?? null
832
+ }
833
+ };
834
+ function findFunction(name) {
835
+ return Object.hasOwn(EXPRESSION_FUNCTIONS, name) ? EXPRESSION_FUNCTIONS[name] : undefined;
836
+ }
837
+ // ── Comparisons ─────────────────────────────────────────────────────────────────────────
838
+ function looseEquals(a, b) {
839
+ if (isBlank(a) || isBlank(b)) return isBlank(a) && isBlank(b);
840
+ const na = typeof a === 'boolean' || typeof b === 'boolean' ? null : tryNumber(a);
841
+ const nb = na === null ? null : tryNumber(b);
842
+ if (na !== null && nb !== null) return na === nb;
843
+ return expressionToText(a) === expressionToText(b);
844
+ }
845
+ function compareOrdered(a, b) {
846
+ if (isBlank(a) || isBlank(b)) return null;
847
+ const na = tryNumber(a);
848
+ const nb = tryNumber(b);
849
+ if (na !== null && nb !== null) return na - nb;
850
+ const ta = typeof a === 'string' ? Date.parse(a) : Number.NaN;
851
+ const tb = typeof b === 'string' ? Date.parse(b) : Number.NaN;
852
+ if (Number.isFinite(ta) && Number.isFinite(tb)) return ta - tb;
853
+ return (expressionToText(a) ?? '').localeCompare(expressionToText(b) ?? '');
854
+ }
855
+ function toList(value) {
856
+ if (Array.isArray(value)) return value;
857
+ if (isBlank(value)) return [];
858
+ if (typeof value === 'string') return value.split(',').map((item)=>item.trim());
859
+ return [
860
+ value
861
+ ];
862
+ }
863
+ function contains(container, item) {
864
+ if (Array.isArray(container)) return container.some((entry)=>looseEquals(entry, item));
865
+ const text = expressionToText(container);
866
+ const needle = expressionToText(item);
867
+ return text !== null && needle !== null && text.includes(needle);
868
+ }
869
+ function isEmpty(value) {
870
+ return isBlank(value) || Array.isArray(value) && value.length === 0;
871
+ }
872
+ function isTrue(value) {
873
+ return value === true || value === 1 || typeof value === 'string' && [
874
+ 'true',
875
+ '1',
876
+ 'yes'
877
+ ].includes(value.trim().toLowerCase());
878
+ }
879
+ function compare(comparison, left, right) {
880
+ switch(comparison){
881
+ case 'equals':
882
+ return looseEquals(left, right);
883
+ case 'not_equals':
884
+ return !looseEquals(left, right);
885
+ case 'greater_than':
886
+ case 'less_than':
887
+ case 'greater_or_equal':
888
+ case 'less_or_equal':
889
+ {
890
+ const d = compareOrdered(left, right);
891
+ if (d === null) return false;
892
+ return comparison === 'greater_than' ? d > 0 : comparison === 'less_than' ? d < 0 : comparison === 'greater_or_equal' ? d >= 0 : d <= 0;
893
+ }
894
+ case 'contains':
895
+ return contains(left, right);
896
+ case 'not_contains':
897
+ return !contains(left, right);
898
+ case 'starts_with':
899
+ return (expressionToText(left) ?? '').startsWith(expressionToText(right) ?? '');
900
+ case 'ends_with':
901
+ return (expressionToText(left) ?? '').endsWith(expressionToText(right) ?? '');
902
+ case 'in':
903
+ return toList(right).some((item)=>Array.isArray(left) ? contains(left, item) : looseEquals(left, item));
904
+ case 'not_in':
905
+ return !toList(right).some((item)=>Array.isArray(left) ? contains(left, item) : looseEquals(left, item));
906
+ case 'is_empty':
907
+ return isEmpty(left);
908
+ case 'is_not_empty':
909
+ return !isEmpty(left);
910
+ case 'is_true':
911
+ return isTrue(left);
912
+ case 'is_false':
913
+ return !isTrue(left);
914
+ case 'matches':
915
+ return regexTest(left, right);
916
+ case 'not_matches':
917
+ return !regexTest(left, right);
918
+ }
919
+ }
920
+ function enter(depth, budget) {
921
+ if (depth > EXPRESSION_LIMITS.MAX_DEPTH) throw new ExpressionError('too_deep', {
922
+ max: EXPRESSION_LIMITS.MAX_DEPTH
923
+ });
924
+ if (++budget.nodes > EXPRESSION_LIMITS.MAX_NODES) throw new ExpressionError('too_many_nodes', {
925
+ max: EXPRESSION_LIMITS.MAX_NODES
926
+ });
927
+ }
928
+ /** Overflow (`10 ** 400`) and undefined results (`(-8) ** 0.5`) are errors, never Infinity / NaN. */ function applyArithmetic(op, values) {
929
+ const result = arithmeticResult(op, values);
930
+ if (result !== null && !Number.isFinite(result)) throw new ExpressionError('expected_number', {
931
+ value: String(result)
932
+ });
933
+ return result;
934
+ }
935
+ function arithmeticResult(op, values) {
936
+ if (values.length === 0) return null;
937
+ const [first, ...rest] = values;
938
+ switch(op){
939
+ case 'sum':
940
+ return values.reduce((a, b)=>a + b, 0);
941
+ case 'subtract':
942
+ return rest.reduce((a, b)=>a - b, first);
943
+ case 'multiply':
944
+ return values.reduce((a, b)=>a * b, 1);
945
+ case 'divide':
946
+ case 'modulo':
947
+ return rest.reduce((a, b)=>{
948
+ if (b === 0) throw new ExpressionError('division_by_zero');
949
+ return op === 'divide' ? a / b : a % b;
950
+ }, first);
951
+ case 'power':
952
+ return rest.reduce((a, b)=>a ** b, first);
953
+ case 'average':
954
+ return values.reduce((a, b)=>a + b, 0) / values.length;
955
+ case 'min':
956
+ return Math.min(...values);
957
+ case 'max':
958
+ return Math.max(...values);
959
+ }
960
+ }
961
+ function renderTemplate(template, ctx) {
962
+ if (template.length > EXPRESSION_LIMITS.MAX_TEMPLATE_LENGTH) throw new ExpressionError('template_too_long', {
963
+ max: EXPRESSION_LIMITS.MAX_TEMPLATE_LENGTH
964
+ });
965
+ return limitText(template.replace(TEMPLATE_PLACEHOLDER, (_, ref)=>expressionToText(ctx.resolveRef(ref)) ?? ''));
966
+ }
967
+ function evaluate(expression, ctx, depth, budget) {
968
+ enter(depth, budget);
969
+ switch(expression?.type){
970
+ case 'literal':
971
+ return expression.value;
972
+ case 'field_ref':
973
+ return ctx.resolveRef(expression.ref);
974
+ case 'arithmetic':
975
+ {
976
+ // Blank operands count as 0 so an unanswered optional field does not void the total.
977
+ const values = expression.operands.map((operand)=>expressionToNumber(evaluate(operand, ctx, depth + 1, budget)) ?? 0);
978
+ return applyArithmetic(expression.op, values);
979
+ }
980
+ case 'concat':
981
+ {
982
+ const parts = expression.parts.map((part)=>expressionToText(evaluate(part, ctx, depth + 1, budget)) ?? '');
983
+ return limitText(expression.separator ? parts.filter((part)=>part !== '').join(expression.separator) : parts.join(''));
984
+ }
985
+ case 'template':
986
+ return renderTemplate(expression.template, ctx);
987
+ case 'function':
988
+ {
989
+ const fn = findFunction(expression.name);
990
+ if (!fn) throw new ExpressionError('unknown_function', {
991
+ name: String(expression.name)
992
+ });
993
+ return fn.call(expression.args.map((arg)=>evaluate(arg, ctx, depth + 1, budget)), ctx);
994
+ }
995
+ case 'if':
996
+ return evaluateGroup(expression.condition, ctx, depth + 1, budget) ? evaluate(expression.whenTrue, ctx, depth + 1, budget) : expression.whenFalse ? evaluate(expression.whenFalse, ctx, depth + 1, budget) : null;
997
+ default:
998
+ throw new ExpressionError('invalid_node', {
999
+ type: String(expression?.type)
1000
+ });
1001
+ }
1002
+ }
1003
+ const isGroup = (node)=>'conditions' in node;
1004
+ function evaluateGroup(group, ctx, depth, budget) {
1005
+ enter(depth, budget);
1006
+ const test = (node)=>{
1007
+ if (isGroup(node)) return evaluateGroup(node, ctx, depth + 1, budget);
1008
+ if (!expression_interface/* .EXPRESSION_COMPARISONS.includes */.Me.includes(node.comparison)) {
1009
+ throw new ExpressionError('unknown_comparison', {
1010
+ comparison: String(node.comparison)
1011
+ });
1012
+ }
1013
+ const left = evaluate(node.left, ctx, depth + 1, budget);
1014
+ const right = node.right ? evaluate(node.right, ctx, depth + 1, budget) : undefined;
1015
+ return compare(node.comparison, left, right);
1016
+ };
1017
+ return group.operator === 'OR' ? group.conditions.some(test) : group.conditions.every(test);
1018
+ }
1019
+ function evaluateExpression(expression, ctx) {
1020
+ return evaluate(expression, ctx, 0, {
1021
+ nodes: 0
1022
+ });
1023
+ }
1024
+ /** An empty group is true. */ function evaluateConditionGroup(group, ctx) {
1025
+ return evaluateGroup(group, ctx, 0, {
1026
+ nodes: 0
1027
+ });
1028
+ }
1029
+ // ── Save-time validation ────────────────────────────────────────────────────────────────
1030
+ const isObject = (value)=>typeof value === 'object' && value !== null && !Array.isArray(value);
1031
+ function invalid(type) {
1032
+ return new ExpressionError('invalid_node', {
1033
+ type: String(type)
1034
+ });
1035
+ }
1036
+ function checkRef(ref, options) {
1037
+ if (typeof ref !== 'string' || !ref) throw new ExpressionError('unknown_ref', {
1038
+ ref: String(ref ?? '')
1039
+ });
1040
+ if (options.isKnownRef && !options.isKnownRef(ref)) throw new ExpressionError('unknown_ref', {
1041
+ ref
1042
+ });
1043
+ }
1044
+ function checkLiteralRegex(node) {
1045
+ if (isObject(node) && node['type'] === 'literal') {
1046
+ const problem = regexProblemError(expressionToText(node['value']) ?? '');
1047
+ if (problem) throw problem;
1048
+ }
1049
+ }
1050
+ function validateNode(node, options, depth, budget) {
1051
+ enter(depth, budget);
1052
+ if (!isObject(node)) throw invalid(node);
1053
+ const each = (items, min)=>{
1054
+ if (!Array.isArray(items) || items.length < min) throw invalid(node['type']);
1055
+ for (const item of items)validateNode(item, options, depth + 1, budget);
1056
+ };
1057
+ switch(node['type']){
1058
+ case 'literal':
1059
+ {
1060
+ const value = node['value'];
1061
+ if (value !== null && ![
1062
+ 'string',
1063
+ 'number',
1064
+ 'boolean'
1065
+ ].includes(typeof value)) throw invalid('literal');
1066
+ return;
1067
+ }
1068
+ case 'field_ref':
1069
+ return checkRef(node['ref'], options);
1070
+ case 'arithmetic':
1071
+ if (!expression_interface/* .EXPRESSION_ARITHMETIC_OPS.includes */.dL.includes(node['op'])) throw invalid('arithmetic');
1072
+ return each(node['operands'], 1);
1073
+ case 'concat':
1074
+ if (node['separator'] !== undefined && typeof node['separator'] !== 'string') throw invalid('concat');
1075
+ return each(node['parts'], 1);
1076
+ case 'template':
1077
+ {
1078
+ const template = node['template'];
1079
+ if (typeof template !== 'string') throw invalid('template');
1080
+ if (template.length > EXPRESSION_LIMITS.MAX_TEMPLATE_LENGTH) throw new ExpressionError('template_too_long', {
1081
+ max: EXPRESSION_LIMITS.MAX_TEMPLATE_LENGTH
1082
+ });
1083
+ for (const match of template.matchAll(TEMPLATE_PLACEHOLDER))checkRef(match[1], options);
1084
+ return;
1085
+ }
1086
+ case 'function':
1087
+ {
1088
+ const name = String(node['name']);
1089
+ const fn = findFunction(name);
1090
+ if (!fn) throw new ExpressionError('unknown_function', {
1091
+ name
1092
+ });
1093
+ const args = node['args'];
1094
+ if (!Array.isArray(args)) throw invalid('function');
1095
+ if (args.length < fn.minArgs || fn.maxArgs !== undefined && args.length > fn.maxArgs) {
1096
+ throw new ExpressionError('wrong_arg_count', {
1097
+ name,
1098
+ min: fn.minArgs,
1099
+ max: fn.maxArgs ?? 'any'
1100
+ });
1101
+ }
1102
+ for (const index of fn.regexArgs ?? [])checkLiteralRegex(args[index]);
1103
+ return each(args, 0);
1104
+ }
1105
+ case 'if':
1106
+ validateGroup(node['condition'], options, depth + 1, budget);
1107
+ validateNode(node['whenTrue'], options, depth + 1, budget);
1108
+ if (node['whenFalse'] !== undefined) validateNode(node['whenFalse'], options, depth + 1, budget);
1109
+ return;
1110
+ default:
1111
+ throw invalid(node['type']);
1112
+ }
1113
+ }
1114
+ function validateGroup(group, options, depth, budget) {
1115
+ enter(depth, budget);
1116
+ if (!isObject(group) || group['operator'] !== 'AND' && group['operator'] !== 'OR' || !Array.isArray(group['conditions'])) throw invalid('condition');
1117
+ for (const node of group['conditions']){
1118
+ if (isObject(node) && 'conditions' in node) {
1119
+ validateGroup(node, options, depth + 1, budget);
1120
+ continue;
1121
+ }
1122
+ if (!isObject(node)) throw invalid('condition');
1123
+ const comparison = node['comparison'];
1124
+ if (!expression_interface/* .EXPRESSION_COMPARISONS.includes */.Me.includes(comparison)) {
1125
+ throw new ExpressionError('unknown_comparison', {
1126
+ comparison: String(comparison)
1127
+ });
1128
+ }
1129
+ validateNode(node['left'], options, depth + 1, budget);
1130
+ if (!expression_interface/* .UNARY_EXPRESSION_COMPARISONS.includes */.kA.includes(comparison)) {
1131
+ validateNode(node['right'], options, depth + 1, budget);
1132
+ if (comparison === 'matches' || comparison === 'not_matches') checkLiteralRegex(node['right']);
1133
+ }
1134
+ }
1135
+ }
1136
+ /** Throws an ExpressionError for the first problem: shape, unknown function / reference, arity, limits, bad literal regex. */ function assertValidExpression(expression, options = {}) {
1137
+ validateNode(expression, options, 0, {
1138
+ nodes: 0
1139
+ });
1140
+ }
1141
+ function assertValidConditionGroup(group, options = {}) {
1142
+ validateGroup(group, options, 0, {
1143
+ nodes: 0
1144
+ });
1145
+ }
1146
+
1147
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/html-sanitizer.util.ts
1148
+ /**
1149
+ * HTML Sanitizer Utilities
1150
+ *
1151
+ * Provides functions for escaping HTML content to prevent XSS attacks.
1152
+ * Use these utilities when interpolating user-provided variables into HTML content.
1153
+ */ /**
1154
+ * HTML entity mapping for escaping special characters
1155
+ */ const HTML_ESCAPE_MAP = {
1156
+ '&': '&amp;',
1157
+ '<': '&lt;',
1158
+ '>': '&gt;',
1159
+ '"': '&quot;',
1160
+ "'": '&#x27;',
1161
+ '/': '&#x2F;',
1162
+ '`': '&#x60;',
1163
+ '=': '&#x3D;'
1164
+ };
1165
+ /**
1166
+ * Regex pattern matching characters that need HTML escaping
1167
+ */ const HTML_ESCAPE_REGEX = /[&<>"'`=/]/g;
1168
+ /**
1169
+ * Escapes HTML special characters to prevent XSS attacks.
1170
+ *
1171
+ * @param str - The string to escape
1172
+ * @returns The escaped string safe for HTML insertion
1173
+ *
1174
+ * @example
1175
+ * ```typescript
1176
+ * escapeHtml('<script>alert("xss")</script>')
1177
+ * // Returns: '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
1178
+ * ```
1179
+ */ function escapeHtml(str) {
1180
+ if (!str || typeof str !== 'string') {
1181
+ return str ?? '';
1182
+ }
1183
+ return str.replace(HTML_ESCAPE_REGEX, (char)=>HTML_ESCAPE_MAP[char]);
1184
+ }
1185
+ /**
1186
+ * Escapes all string values in a variables object for safe HTML interpolation.
1187
+ * Non-string values are converted to strings and escaped.
1188
+ *
1189
+ * @param variables - Object containing template variables
1190
+ * @returns New object with all string values HTML-escaped
1191
+ *
1192
+ * @example
1193
+ * ```typescript
1194
+ * escapeHtmlVariables({ name: '<script>xss</script>', count: 5 })
1195
+ * // Returns: { name: '&lt;script&gt;xss&lt;/script&gt;', count: '5' }
1196
+ * ```
1197
+ */ function escapeHtmlVariables(variables) {
1198
+ if (!variables || typeof variables !== 'object') {
1199
+ return {};
1200
+ }
1201
+ const escaped = {};
1202
+ for (const [key, value] of Object.entries(variables)){
1203
+ if (value === null || value === undefined) {
1204
+ escaped[key] = '';
1205
+ } else if (typeof value === 'string') {
1206
+ escaped[key] = escapeHtml(value);
1207
+ } else if (typeof value === 'object') {
1208
+ // For objects/arrays, stringify and escape
1209
+ escaped[key] = escapeHtml(JSON.stringify(value));
1210
+ } else {
1211
+ // For numbers, booleans, etc., convert to string (no escaping needed)
1212
+ escaped[key] = String(value);
1213
+ }
1214
+ }
1215
+ return escaped;
1216
+ }
1217
+
1218
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/message-ref.util.ts
1219
+ function messageRef(messageKey, messageVariables) {
1220
+ return messageVariables ? {
1221
+ messageKey,
1222
+ messageVariables
1223
+ } : {
1224
+ messageKey
1225
+ };
1226
+ }
1227
+
1228
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/optional-module.util.ts
1229
+ var optional_module_util = __webpack_require__(8368);
1230
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/permission-cache-key.util.ts
1231
+ var permission_cache_key_util = __webpack_require__(3199);
1232
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/permission-match.util.ts
1233
+ var permission_match_util = __webpack_require__(788);
1234
+ // EXTERNAL MODULE: external "@nestjs/common"
1235
+ var common_ = __webpack_require__(6157);
1236
+ // EXTERNAL MODULE: external "typeorm"
1237
+ var external_typeorm_ = __webpack_require__(7158);
1238
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/constants/index.ts
1239
+ var constants = __webpack_require__(6043);
1240
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/query-helpers.util.ts
1241
+
1242
+
1243
+
1244
+
1245
+ /**
1246
+ * Restricts a query to the user's company when the company feature is on. A logged-in user without a
1247
+ * company matches nothing (never every company's rows); no user at all is a system call and is left
1248
+ * unfiltered.
1249
+ *
1250
+ * @example
1251
+ * ```typescript
1252
+ * applyCompanyFilter(query, {
1253
+ * isCompanyFeatureEnabled: this.config.isCompanyFeatureEnabled(),
1254
+ * entityAlias: 'file_manager',
1255
+ * }, user);
1256
+ * ```
1257
+ */ function applyCompanyFilter(query, config, user) {
1258
+ if (!config.isCompanyFeatureEnabled || !user) return query;
1259
+ if (!user.companyId) return query.andWhere('1 = 0');
1260
+ return query.andWhere(`${config.entityAlias}.${config.columnName ?? 'companyId'} = :companyId`, {
1261
+ companyId: user.companyId
1262
+ });
1263
+ }
1264
+ /**
1265
+ * Restrict a query to rows of the given branches - typically a branch plus the granted branches under
1266
+ * it from `BRANCH_HIERARCHY_RESOLVER.getGrantedDescendantIds(userId, id, { includeSelf: true })`. Empty
1267
+ * ids are dropped; with none left only unassigned rows (if asked for) match, never everything.
1268
+ */ function applyBranchFilter(query, config, branchIds) {
1269
+ const ids = normalizeBranchIds(branchIds);
1270
+ const column = `${config.entityAlias}.${config.columnName ?? 'branchId'}`;
1271
+ if (!ids.length) return query.andWhere(config.includeUnassigned ? `${column} IS NULL` : '1 = 0');
1272
+ const inList = `${column} IN (:...branchFilterIds)`;
1273
+ return query.andWhere(config.includeUnassigned ? `(${inList} OR ${column} IS NULL)` : inList, {
1274
+ branchFilterIds: ids
1275
+ });
1276
+ }
1277
+ /**
1278
+ * Adds the user's company to a find `where` when the company feature is on - `In([])` (matches
1279
+ * nothing) for a logged-in user without a company; no user at all is a system call and is unchanged.
1280
+ *
1281
+ * @example
1282
+ * ```typescript
1283
+ * const where = buildCompanyWhereCondition({ id: dto.id }, this.config.isCompanyFeatureEnabled(), user);
1284
+ * ```
1285
+ */ function buildCompanyWhereCondition(baseWhere, isCompanyFeatureEnabled, user) {
1286
+ if (!isCompanyFeatureEnabled || !user) return baseWhere;
1287
+ return {
1288
+ ...baseWhere,
1289
+ companyId: user.companyId ? user.companyId : (0,external_typeorm_.In)([])
1290
+ };
1291
+ }
1292
+ /**
1293
+ * Type guard to check if entity has companyId property
1294
+ */ function hasCompanyId(entity) {
1295
+ return entity !== null && typeof entity === 'object' && 'companyId' in entity;
1296
+ }
1297
+ /**
1298
+ * Throws when the company feature is on and `entity` belongs to a company other than the user's - a
1299
+ * logged-in user without a company may only use company-less rows. No user at all is a system call.
1300
+ *
1301
+ * @example
1302
+ * ```typescript
1303
+ * validateCompanyOwnership(config, user, this.config.isCompanyFeatureEnabled(), 'Email configuration');
1304
+ * ```
1305
+ */ function validateCompanyOwnership(entity, user, isCompanyFeatureEnabled, entityName) {
1306
+ if (!isCompanyFeatureEnabled || !user || !hasCompanyId(entity)) return;
1307
+ if (entity.companyId && entity.companyId !== user.companyId) {
1308
+ throw new common_.BadRequestException({
1309
+ message: `${entityName} belongs to another company`,
1310
+ messageKey: constants/* .AUTH_MESSAGES.ENTITY_BELOG_ANOTHER_COMPANY */.mK.ENTITY_BELOG_ANOTHER_COMPANY,
1311
+ messageVariables: {
1312
+ entity: entityName
1313
+ }
1314
+ });
1315
+ }
1316
+ }
1317
+ /**
1318
+ * Runs `fn` inside a savepoint of an already-open transaction. A failure rolls back only what
1319
+ * `fn` did, so the caller can swallow the error and keep using the transaction - without it,
1320
+ * PostgreSQL aborts the whole transaction after any failed statement.
1321
+ */ async function withSavepoint(queryRunner, fn) {
1322
+ await queryRunner.startTransaction();
1323
+ try {
1324
+ const result = await fn();
1325
+ await queryRunner.commitTransaction();
1326
+ return result;
1327
+ } catch (error) {
1328
+ await queryRunner.rollbackTransaction();
1329
+ throw error;
1330
+ }
1331
+ }
1332
+
1333
+ // EXTERNAL MODULE: external "@flusys/nestjs-core/config"
1334
+ var config_ = __webpack_require__(8307);
1335
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/request.util.ts
1336
+
1337
+
1338
+
1339
+ /** Time unit multipliers in milliseconds */ const TIME_UNIT_MS = {
1340
+ s: 1000,
1341
+ m: 60 * 1000,
1342
+ h: 60 * 60 * 1000,
1343
+ d: 24 * 60 * 60 * 1000,
1344
+ w: 7 * 24 * 60 * 60 * 1000
1345
+ };
1346
+ const IPV4_HOST = /^\d{1,3}(\.\d{1,3}){3}$/;
1347
+ /** Second-level labels used under two-letter country codes (`co.uk`, `com.au`, `ac.jp`, ...). */ const COUNTRY_SECOND_LEVEL = new Set([
1348
+ 'co',
1349
+ 'com',
1350
+ 'net',
1351
+ 'org',
1352
+ 'gov',
1353
+ 'edu',
1354
+ 'ac',
1355
+ 'or',
1356
+ 'ne',
1357
+ 'go',
1358
+ 'ltd',
1359
+ 'plc',
1360
+ 'mil',
1361
+ 'nic',
1362
+ 'sch',
1363
+ 'gen'
1364
+ ]);
1365
+ /**
1366
+ * The registrable domain to share the auth cookies across subdomains (`app.example.com` -> `.example.com`,
1367
+ * `app.example.co.uk` -> `.example.co.uk`), or undefined for a host-only cookie: IP addresses, localhost and
1368
+ * hosts that already are the registrable domain - a cookie scoped to `.1.10` or `.co.uk` is rejected by browsers.
1369
+ */ function sharedCookieDomain(hostname) {
1370
+ const host = hostname.toLowerCase().replace(/\.$/, '');
1371
+ if (!host || host.includes(':') || IPV4_HOST.test(host) || host.includes('localhost')) return undefined;
1372
+ const labels = host.split('.');
1373
+ const last = labels[labels.length - 1];
1374
+ const secondLast = labels[labels.length - 2];
1375
+ const keep = labels.length >= 3 && last.length === 2 && COUNTRY_SECOND_LEVEL.has(secondLast) ? 3 : 2;
1376
+ return labels.length > keep ? '.' + labels.slice(-keep).join('.') : undefined;
1377
+ }
1378
+ /** Get normalized client type from request header */ function getClientType(req) {
1379
+ const clientType = req.headers[constants/* .CLIENT_TYPE_HEADER */.xw];
1380
+ return clientType ? clientType.toLowerCase() : null;
1381
+ }
1382
+ /**
1383
+ * Detect if request is from a browser client.
1384
+ * Uses x-client-type header first, then falls back to user-agent detection.
1385
+ */ function isBrowserRequest(req) {
1386
+ const clientType = getClientType(req);
1387
+ if (clientType) {
1388
+ return clientType === 'browser' || clientType === 'web';
1389
+ }
1390
+ const accept = req.headers['accept'] || '';
1391
+ if (accept.includes('text/html')) return true;
1392
+ const userAgent = req.headers['user-agent'] || '';
1393
+ const browserPatterns = /mozilla|chrome|safari|firefox|edge|opera|msie/i;
1394
+ return browserPatterns.test(userAgent) && !userAgent.includes('Postman');
1395
+ }
1396
+ /**
1397
+ * Build secure cookie options based on request context.
1398
+ * Handles HTTPS detection for TLS-terminating proxies.
1399
+ */ function buildCookieOptions(req) {
1400
+ const hostname = req.hostname || '';
1401
+ const origin = req.headers.origin || '';
1402
+ const isProduction = config_.envConfig.isProduction();
1403
+ const forwardedProto = req.headers['x-forwarded-proto'];
1404
+ const isHttps = isProduction || forwardedProto === 'https' || origin.startsWith('https://') || req.secure;
1405
+ const domain = sharedCookieDomain(hostname);
1406
+ return {
1407
+ secure: isHttps,
1408
+ sameSite: isHttps ? 'strict' : 'lax',
1409
+ ...domain && {
1410
+ domain
1411
+ }
1412
+ };
1413
+ }
1414
+ /**
1415
+ * Parse duration string to milliseconds.
1416
+ * @example '7d' → 604800000, '24h' → 86400000, '30m' → 1800000
1417
+ */ function parseDurationToMs(duration, defaultMs = TIME_UNIT_MS.w) {
1418
+ const match = duration.match(/^(\d+)(s|m|h|d|w)$/);
1419
+ if (!match) return defaultMs;
1420
+ const value = parseInt(match[1], 10);
1421
+ const unit = match[2];
1422
+ return value * (TIME_UNIT_MS[unit] ?? TIME_UNIT_MS.d);
1423
+ }
1424
+ /**
1425
+ * Determine the frontend base URL for auth-related links.
1426
+ * Matches the request's Origin/Referer against configured allowed origins.
1427
+ * Never trusts the request's Host header - it is client-controlled and would
1428
+ * let an attacker redirect password-reset/verification links to their own domain.
1429
+ */ function extractFrontendUrl(req) {
1430
+ const allowedOrigins = config_.envConfig.getOrigins();
1431
+ const origin = (req.get('origin') ?? req.get('referer') ?? '').trim();
1432
+ if (origin && allowedOrigins.length) {
1433
+ const matched = allowedOrigins.find((u)=>origin.startsWith(u));
1434
+ if (matched) {
1435
+ return matched;
1436
+ }
1437
+ }
1438
+ if (allowedOrigins.length) {
1439
+ return allowedOrigins[0];
1440
+ }
1441
+ throw new common_.BadRequestException({
1442
+ message: 'Unable to determine frontend URL from request',
1443
+ messageKey: constants/* .ERROR_MESSAGES.VALIDATION */.UU.VALIDATION
1444
+ });
1445
+ }
1446
+ function buildFrontendUrl(req, path) {
1447
+ const baseUrl = extractFrontendUrl(req);
1448
+ return `${baseUrl}${path}`;
1449
+ }
1450
+
1451
+ // EXTERNAL MODULE: ./projects/nestjs-shared/src/utils/string.util.ts
1452
+ var string_util = __webpack_require__(3366);
1453
+ // EXTERNAL MODULE: external "crypto"
1454
+ var external_crypto_ = __webpack_require__(7823);
1455
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/token.util.ts
1456
+
1457
+ /** 32 random bytes as hex, suitable for a password-reset/OTP/access-style token */ function generateSecureToken() {
1458
+ return external_crypto_.randomBytes(32).toString('hex');
1459
+ }
1460
+ /** SHA-256 hash of a token, for storing/comparing tokens without keeping the raw value */ function hashToken(value) {
1461
+ return external_crypto_.createHash('sha256').update(value).digest('hex');
1462
+ }
1463
+ function isExpired(expiresAt) {
1464
+ return expiresAt < new Date();
1465
+ }
1466
+
1467
+ ;// CONCATENATED MODULE: ./projects/nestjs-shared/src/utils/index.ts
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+
1477
+
1478
+
1479
+
1480
+
1481
+
1482
+
1483
+
1484
+
1485
+ },
1486
+ 8368(__unused_rspack_module, __webpack_exports__, __webpack_require__) {
1487
+ /**
1488
+ * Loads an optional peer dependency at runtime.
1489
+ *
1490
+ * The specifier has to stay invisible to the bundler. A plain `import(name)`
1491
+ * looks dynamic in source but webpack rewrites it into a context module rooted
1492
+ * at this directory - one that can only ever resolve files sitting next to this
1493
+ * one - so `amqplib` and `kafkajs` fail to load in the bundled app no matter how
1494
+ * correctly they are installed. Both lookups below are assembled at runtime,
1495
+ * where no bundler can rewrite them.
1496
+ *
1497
+ * `require` is used first because it is what the CommonJS builds actually run
1498
+ * on; native ESM has no `require`, and there `import()` is the only way in.
1499
+ */ async function loadOptionalModule(name) {
1500
+ const runtimeRequire = resolveRuntimeRequire();
1501
+ if (runtimeRequire) return runtimeRequire(name);
1502
+ const runtimeImport = new Function('specifier', 'return import(specifier);');
1503
+ return runtimeImport(name);
1504
+ }
1505
+ /** Undefined under native ESM and inside a bundle that shadows nothing back */ function resolveRuntimeRequire() {
1506
+ try {
1507
+ return eval('typeof require === "function" ? require : undefined');
1508
+ } catch {
1509
+ return undefined;
1510
+ }
1511
+ }
1512
+
1513
+ __webpack_require__.d(__webpack_exports__, {
1514
+ l: () => (loadOptionalModule)
1515
+ });
1516
+
1517
+
1518
+ },
1519
+
1520
+ };