@grupodiariodaregiao/bunstone 0.0.27

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 (49) hide show
  1. package/README.md +91 -0
  2. package/bin/cli.ts +182 -0
  3. package/dist/index.d.ts +36 -0
  4. package/dist/index.js +4316 -0
  5. package/dist/lib/adapters/cache-adapter.d.ts +19 -0
  6. package/dist/lib/adapters/form-data.d.ts +4 -0
  7. package/dist/lib/adapters/upload-adapter.d.ts +22 -0
  8. package/dist/lib/app-startup.d.ts +76 -0
  9. package/dist/lib/components/layout.d.ts +8 -0
  10. package/dist/lib/constants/index.d.ts +1 -0
  11. package/dist/lib/controller.d.ts +14 -0
  12. package/dist/lib/cqrs/command-bus.d.ts +19 -0
  13. package/dist/lib/cqrs/cqrs-module.d.ts +2 -0
  14. package/dist/lib/cqrs/decorators/command-handler.decorator.d.ts +7 -0
  15. package/dist/lib/cqrs/decorators/event-handler.decorator.d.ts +7 -0
  16. package/dist/lib/cqrs/decorators/query-handler.decorator.d.ts +7 -0
  17. package/dist/lib/cqrs/decorators/saga.decorator.d.ts +7 -0
  18. package/dist/lib/cqrs/event-bus.d.ts +38 -0
  19. package/dist/lib/cqrs/interfaces/command.interface.d.ts +5 -0
  20. package/dist/lib/cqrs/interfaces/event.interface.d.ts +5 -0
  21. package/dist/lib/cqrs/interfaces/query.interface.d.ts +5 -0
  22. package/dist/lib/cqrs/query-bus.d.ts +19 -0
  23. package/dist/lib/database/sql-module.d.ts +25 -0
  24. package/dist/lib/guard.d.ts +8 -0
  25. package/dist/lib/http-exceptions.d.ts +73 -0
  26. package/dist/lib/http-methods.d.ts +36 -0
  27. package/dist/lib/http-params.d.ts +28 -0
  28. package/dist/lib/injectable.d.ts +12 -0
  29. package/dist/lib/interfaces/class-constructor.d.ts +6 -0
  30. package/dist/lib/interfaces/guard-contract.d.ts +7 -0
  31. package/dist/lib/jwt/jwt-module.d.ts +13 -0
  32. package/dist/lib/jwt.d.ts +5 -0
  33. package/dist/lib/module.d.ts +18 -0
  34. package/dist/lib/openapi.d.ts +52 -0
  35. package/dist/lib/render.d.ts +7 -0
  36. package/dist/lib/schedule/cron/cron.d.ts +7 -0
  37. package/dist/lib/schedule/cron/mappers/map-providers-with-cron.d.ts +8 -0
  38. package/dist/lib/schedule/timeout/mappers/map-providers-with-timeouts.d.ts +9 -0
  39. package/dist/lib/schedule/timeout/timeout.d.ts +7 -0
  40. package/dist/lib/types/http-request.d.ts +13 -0
  41. package/dist/lib/types/module-config.d.ts +14 -0
  42. package/dist/lib/types/options.d.ts +24 -0
  43. package/dist/lib/utils/colors.d.ts +36 -0
  44. package/dist/lib/utils/dependency-injection.d.ts +25 -0
  45. package/dist/lib/utils/is-class.d.ts +1 -0
  46. package/dist/lib/utils/is-zod-schema.d.ts +2 -0
  47. package/dist/lib/utils/logger.d.ts +38 -0
  48. package/dist/lib/utils/map-providers.d.ts +14 -0
  49. package/package.json +47 -0
package/dist/index.js ADDED
@@ -0,0 +1,4316 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __legacyDecorateClassTS = function(decorators, target, key, desc) {
20
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
22
+ r = Reflect.decorate(decorators, target, key, desc);
23
+ else
24
+ for (var i = decorators.length - 1;i >= 0; i--)
25
+ if (d = decorators[i])
26
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
27
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
28
+ };
29
+ var __legacyMetadataTS = (k, v) => {
30
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
31
+ return Reflect.metadata(k, v);
32
+ };
33
+ var __require = import.meta.require;
34
+
35
+ // node_modules/reflect-metadata/Reflect.js
36
+ var require_Reflect = __commonJS(() => {
37
+ /*! *****************************************************************************
38
+ Copyright (C) Microsoft. All rights reserved.
39
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
40
+ this file except in compliance with the License. You may obtain a copy of the
41
+ License at http://www.apache.org/licenses/LICENSE-2.0
42
+
43
+ THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
44
+ KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
45
+ WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
46
+ MERCHANTABLITY OR NON-INFRINGEMENT.
47
+
48
+ See the Apache Version 2.0 License for specific language governing permissions
49
+ and limitations under the License.
50
+ ***************************************************************************** */
51
+ var Reflect2;
52
+ (function(Reflect3) {
53
+ (function(factory) {
54
+ var root = typeof globalThis === "object" ? globalThis : typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis();
55
+ var exporter = makeExporter(Reflect3);
56
+ if (typeof root.Reflect !== "undefined") {
57
+ exporter = makeExporter(root.Reflect, exporter);
58
+ }
59
+ factory(exporter, root);
60
+ if (typeof root.Reflect === "undefined") {
61
+ root.Reflect = Reflect3;
62
+ }
63
+ function makeExporter(target, previous) {
64
+ return function(key, value) {
65
+ Object.defineProperty(target, key, { configurable: true, writable: true, value });
66
+ if (previous)
67
+ previous(key, value);
68
+ };
69
+ }
70
+ function functionThis() {
71
+ try {
72
+ return Function("return this;")();
73
+ } catch (_) {}
74
+ }
75
+ function indirectEvalThis() {
76
+ try {
77
+ return (undefined, eval)("(function() { return this; })()");
78
+ } catch (_) {}
79
+ }
80
+ function sloppyModeThis() {
81
+ return functionThis() || indirectEvalThis();
82
+ }
83
+ })(function(exporter, root) {
84
+ var hasOwn = Object.prototype.hasOwnProperty;
85
+ var supportsSymbol = typeof Symbol === "function";
86
+ var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive";
87
+ var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator";
88
+ var supportsCreate = typeof Object.create === "function";
89
+ var supportsProto = { __proto__: [] } instanceof Array;
90
+ var downLevel = !supportsCreate && !supportsProto;
91
+ var HashMap = {
92
+ create: supportsCreate ? function() {
93
+ return MakeDictionary(Object.create(null));
94
+ } : supportsProto ? function() {
95
+ return MakeDictionary({ __proto__: null });
96
+ } : function() {
97
+ return MakeDictionary({});
98
+ },
99
+ has: downLevel ? function(map, key) {
100
+ return hasOwn.call(map, key);
101
+ } : function(map, key) {
102
+ return key in map;
103
+ },
104
+ get: downLevel ? function(map, key) {
105
+ return hasOwn.call(map, key) ? map[key] : undefined;
106
+ } : function(map, key) {
107
+ return map[key];
108
+ }
109
+ };
110
+ var functionPrototype = Object.getPrototypeOf(Function);
111
+ var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill();
112
+ var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill();
113
+ var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill();
114
+ var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : undefined;
115
+ var metadataRegistry = GetOrCreateMetadataRegistry();
116
+ var metadataProvider = CreateMetadataProvider(metadataRegistry);
117
+ function decorate(decorators, target, propertyKey, attributes) {
118
+ if (!IsUndefined(propertyKey)) {
119
+ if (!IsArray(decorators))
120
+ throw new TypeError;
121
+ if (!IsObject(target))
122
+ throw new TypeError;
123
+ if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes))
124
+ throw new TypeError;
125
+ if (IsNull(attributes))
126
+ attributes = undefined;
127
+ propertyKey = ToPropertyKey(propertyKey);
128
+ return DecorateProperty(decorators, target, propertyKey, attributes);
129
+ } else {
130
+ if (!IsArray(decorators))
131
+ throw new TypeError;
132
+ if (!IsConstructor(target))
133
+ throw new TypeError;
134
+ return DecorateConstructor(decorators, target);
135
+ }
136
+ }
137
+ exporter("decorate", decorate);
138
+ function metadata(metadataKey, metadataValue) {
139
+ function decorator(target, propertyKey) {
140
+ if (!IsObject(target))
141
+ throw new TypeError;
142
+ if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey))
143
+ throw new TypeError;
144
+ OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
145
+ }
146
+ return decorator;
147
+ }
148
+ exporter("metadata", metadata);
149
+ function defineMetadata(metadataKey, metadataValue, target, propertyKey) {
150
+ if (!IsObject(target))
151
+ throw new TypeError;
152
+ if (!IsUndefined(propertyKey))
153
+ propertyKey = ToPropertyKey(propertyKey);
154
+ return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
155
+ }
156
+ exporter("defineMetadata", defineMetadata);
157
+ function hasMetadata(metadataKey, target, propertyKey) {
158
+ if (!IsObject(target))
159
+ throw new TypeError;
160
+ if (!IsUndefined(propertyKey))
161
+ propertyKey = ToPropertyKey(propertyKey);
162
+ return OrdinaryHasMetadata(metadataKey, target, propertyKey);
163
+ }
164
+ exporter("hasMetadata", hasMetadata);
165
+ function hasOwnMetadata(metadataKey, target, propertyKey) {
166
+ if (!IsObject(target))
167
+ throw new TypeError;
168
+ if (!IsUndefined(propertyKey))
169
+ propertyKey = ToPropertyKey(propertyKey);
170
+ return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey);
171
+ }
172
+ exporter("hasOwnMetadata", hasOwnMetadata);
173
+ function getMetadata(metadataKey, target, propertyKey) {
174
+ if (!IsObject(target))
175
+ throw new TypeError;
176
+ if (!IsUndefined(propertyKey))
177
+ propertyKey = ToPropertyKey(propertyKey);
178
+ return OrdinaryGetMetadata(metadataKey, target, propertyKey);
179
+ }
180
+ exporter("getMetadata", getMetadata);
181
+ function getOwnMetadata(metadataKey, target, propertyKey) {
182
+ if (!IsObject(target))
183
+ throw new TypeError;
184
+ if (!IsUndefined(propertyKey))
185
+ propertyKey = ToPropertyKey(propertyKey);
186
+ return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey);
187
+ }
188
+ exporter("getOwnMetadata", getOwnMetadata);
189
+ function getMetadataKeys(target, propertyKey) {
190
+ if (!IsObject(target))
191
+ throw new TypeError;
192
+ if (!IsUndefined(propertyKey))
193
+ propertyKey = ToPropertyKey(propertyKey);
194
+ return OrdinaryMetadataKeys(target, propertyKey);
195
+ }
196
+ exporter("getMetadataKeys", getMetadataKeys);
197
+ function getOwnMetadataKeys(target, propertyKey) {
198
+ if (!IsObject(target))
199
+ throw new TypeError;
200
+ if (!IsUndefined(propertyKey))
201
+ propertyKey = ToPropertyKey(propertyKey);
202
+ return OrdinaryOwnMetadataKeys(target, propertyKey);
203
+ }
204
+ exporter("getOwnMetadataKeys", getOwnMetadataKeys);
205
+ function deleteMetadata(metadataKey, target, propertyKey) {
206
+ if (!IsObject(target))
207
+ throw new TypeError;
208
+ if (!IsUndefined(propertyKey))
209
+ propertyKey = ToPropertyKey(propertyKey);
210
+ if (!IsObject(target))
211
+ throw new TypeError;
212
+ if (!IsUndefined(propertyKey))
213
+ propertyKey = ToPropertyKey(propertyKey);
214
+ var provider = GetMetadataProvider(target, propertyKey, false);
215
+ if (IsUndefined(provider))
216
+ return false;
217
+ return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey);
218
+ }
219
+ exporter("deleteMetadata", deleteMetadata);
220
+ function DecorateConstructor(decorators, target) {
221
+ for (var i = decorators.length - 1;i >= 0; --i) {
222
+ var decorator = decorators[i];
223
+ var decorated = decorator(target);
224
+ if (!IsUndefined(decorated) && !IsNull(decorated)) {
225
+ if (!IsConstructor(decorated))
226
+ throw new TypeError;
227
+ target = decorated;
228
+ }
229
+ }
230
+ return target;
231
+ }
232
+ function DecorateProperty(decorators, target, propertyKey, descriptor) {
233
+ for (var i = decorators.length - 1;i >= 0; --i) {
234
+ var decorator = decorators[i];
235
+ var decorated = decorator(target, propertyKey, descriptor);
236
+ if (!IsUndefined(decorated) && !IsNull(decorated)) {
237
+ if (!IsObject(decorated))
238
+ throw new TypeError;
239
+ descriptor = decorated;
240
+ }
241
+ }
242
+ return descriptor;
243
+ }
244
+ function OrdinaryHasMetadata(MetadataKey, O, P) {
245
+ var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O, P);
246
+ if (hasOwn2)
247
+ return true;
248
+ var parent = OrdinaryGetPrototypeOf(O);
249
+ if (!IsNull(parent))
250
+ return OrdinaryHasMetadata(MetadataKey, parent, P);
251
+ return false;
252
+ }
253
+ function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
254
+ var provider = GetMetadataProvider(O, P, false);
255
+ if (IsUndefined(provider))
256
+ return false;
257
+ return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P));
258
+ }
259
+ function OrdinaryGetMetadata(MetadataKey, O, P) {
260
+ var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O, P);
261
+ if (hasOwn2)
262
+ return OrdinaryGetOwnMetadata(MetadataKey, O, P);
263
+ var parent = OrdinaryGetPrototypeOf(O);
264
+ if (!IsNull(parent))
265
+ return OrdinaryGetMetadata(MetadataKey, parent, P);
266
+ return;
267
+ }
268
+ function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
269
+ var provider = GetMetadataProvider(O, P, false);
270
+ if (IsUndefined(provider))
271
+ return;
272
+ return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P);
273
+ }
274
+ function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
275
+ var provider = GetMetadataProvider(O, P, true);
276
+ provider.OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P);
277
+ }
278
+ function OrdinaryMetadataKeys(O, P) {
279
+ var ownKeys = OrdinaryOwnMetadataKeys(O, P);
280
+ var parent = OrdinaryGetPrototypeOf(O);
281
+ if (parent === null)
282
+ return ownKeys;
283
+ var parentKeys = OrdinaryMetadataKeys(parent, P);
284
+ if (parentKeys.length <= 0)
285
+ return ownKeys;
286
+ if (ownKeys.length <= 0)
287
+ return parentKeys;
288
+ var set = new _Set;
289
+ var keys = [];
290
+ for (var _i = 0, ownKeys_1 = ownKeys;_i < ownKeys_1.length; _i++) {
291
+ var key = ownKeys_1[_i];
292
+ var hasKey = set.has(key);
293
+ if (!hasKey) {
294
+ set.add(key);
295
+ keys.push(key);
296
+ }
297
+ }
298
+ for (var _a = 0, parentKeys_1 = parentKeys;_a < parentKeys_1.length; _a++) {
299
+ var key = parentKeys_1[_a];
300
+ var hasKey = set.has(key);
301
+ if (!hasKey) {
302
+ set.add(key);
303
+ keys.push(key);
304
+ }
305
+ }
306
+ return keys;
307
+ }
308
+ function OrdinaryOwnMetadataKeys(O, P) {
309
+ var provider = GetMetadataProvider(O, P, false);
310
+ if (!provider) {
311
+ return [];
312
+ }
313
+ return provider.OrdinaryOwnMetadataKeys(O, P);
314
+ }
315
+ function Type(x) {
316
+ if (x === null)
317
+ return 1;
318
+ switch (typeof x) {
319
+ case "undefined":
320
+ return 0;
321
+ case "boolean":
322
+ return 2;
323
+ case "string":
324
+ return 3;
325
+ case "symbol":
326
+ return 4;
327
+ case "number":
328
+ return 5;
329
+ case "object":
330
+ return x === null ? 1 : 6;
331
+ default:
332
+ return 6;
333
+ }
334
+ }
335
+ function IsUndefined(x) {
336
+ return x === undefined;
337
+ }
338
+ function IsNull(x) {
339
+ return x === null;
340
+ }
341
+ function IsSymbol(x) {
342
+ return typeof x === "symbol";
343
+ }
344
+ function IsObject(x) {
345
+ return typeof x === "object" ? x !== null : typeof x === "function";
346
+ }
347
+ function ToPrimitive(input, PreferredType) {
348
+ switch (Type(input)) {
349
+ case 0:
350
+ return input;
351
+ case 1:
352
+ return input;
353
+ case 2:
354
+ return input;
355
+ case 3:
356
+ return input;
357
+ case 4:
358
+ return input;
359
+ case 5:
360
+ return input;
361
+ }
362
+ var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default";
363
+ var exoticToPrim = GetMethod(input, toPrimitiveSymbol);
364
+ if (exoticToPrim !== undefined) {
365
+ var result = exoticToPrim.call(input, hint);
366
+ if (IsObject(result))
367
+ throw new TypeError;
368
+ return result;
369
+ }
370
+ return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint);
371
+ }
372
+ function OrdinaryToPrimitive(O, hint) {
373
+ if (hint === "string") {
374
+ var toString_1 = O.toString;
375
+ if (IsCallable(toString_1)) {
376
+ var result = toString_1.call(O);
377
+ if (!IsObject(result))
378
+ return result;
379
+ }
380
+ var valueOf = O.valueOf;
381
+ if (IsCallable(valueOf)) {
382
+ var result = valueOf.call(O);
383
+ if (!IsObject(result))
384
+ return result;
385
+ }
386
+ } else {
387
+ var valueOf = O.valueOf;
388
+ if (IsCallable(valueOf)) {
389
+ var result = valueOf.call(O);
390
+ if (!IsObject(result))
391
+ return result;
392
+ }
393
+ var toString_2 = O.toString;
394
+ if (IsCallable(toString_2)) {
395
+ var result = toString_2.call(O);
396
+ if (!IsObject(result))
397
+ return result;
398
+ }
399
+ }
400
+ throw new TypeError;
401
+ }
402
+ function ToBoolean(argument) {
403
+ return !!argument;
404
+ }
405
+ function ToString(argument) {
406
+ return "" + argument;
407
+ }
408
+ function ToPropertyKey(argument) {
409
+ var key = ToPrimitive(argument, 3);
410
+ if (IsSymbol(key))
411
+ return key;
412
+ return ToString(key);
413
+ }
414
+ function IsArray(argument) {
415
+ return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]";
416
+ }
417
+ function IsCallable(argument) {
418
+ return typeof argument === "function";
419
+ }
420
+ function IsConstructor(argument) {
421
+ return typeof argument === "function";
422
+ }
423
+ function IsPropertyKey(argument) {
424
+ switch (Type(argument)) {
425
+ case 3:
426
+ return true;
427
+ case 4:
428
+ return true;
429
+ default:
430
+ return false;
431
+ }
432
+ }
433
+ function SameValueZero(x, y) {
434
+ return x === y || x !== x && y !== y;
435
+ }
436
+ function GetMethod(V, P) {
437
+ var func = V[P];
438
+ if (func === undefined || func === null)
439
+ return;
440
+ if (!IsCallable(func))
441
+ throw new TypeError;
442
+ return func;
443
+ }
444
+ function GetIterator(obj) {
445
+ var method = GetMethod(obj, iteratorSymbol);
446
+ if (!IsCallable(method))
447
+ throw new TypeError;
448
+ var iterator = method.call(obj);
449
+ if (!IsObject(iterator))
450
+ throw new TypeError;
451
+ return iterator;
452
+ }
453
+ function IteratorValue(iterResult) {
454
+ return iterResult.value;
455
+ }
456
+ function IteratorStep(iterator) {
457
+ var result = iterator.next();
458
+ return result.done ? false : result;
459
+ }
460
+ function IteratorClose(iterator) {
461
+ var f = iterator["return"];
462
+ if (f)
463
+ f.call(iterator);
464
+ }
465
+ function OrdinaryGetPrototypeOf(O) {
466
+ var proto = Object.getPrototypeOf(O);
467
+ if (typeof O !== "function" || O === functionPrototype)
468
+ return proto;
469
+ if (proto !== functionPrototype)
470
+ return proto;
471
+ var prototype = O.prototype;
472
+ var prototypeProto = prototype && Object.getPrototypeOf(prototype);
473
+ if (prototypeProto == null || prototypeProto === Object.prototype)
474
+ return proto;
475
+ var constructor = prototypeProto.constructor;
476
+ if (typeof constructor !== "function")
477
+ return proto;
478
+ if (constructor === O)
479
+ return proto;
480
+ return constructor;
481
+ }
482
+ function CreateMetadataRegistry() {
483
+ var fallback;
484
+ if (!IsUndefined(registrySymbol) && typeof root.Reflect !== "undefined" && !(registrySymbol in root.Reflect) && typeof root.Reflect.defineMetadata === "function") {
485
+ fallback = CreateFallbackProvider(root.Reflect);
486
+ }
487
+ var first;
488
+ var second;
489
+ var rest;
490
+ var targetProviderMap = new _WeakMap;
491
+ var registry = {
492
+ registerProvider,
493
+ getProvider,
494
+ setProvider
495
+ };
496
+ return registry;
497
+ function registerProvider(provider) {
498
+ if (!Object.isExtensible(registry)) {
499
+ throw new Error("Cannot add provider to a frozen registry.");
500
+ }
501
+ switch (true) {
502
+ case fallback === provider:
503
+ break;
504
+ case IsUndefined(first):
505
+ first = provider;
506
+ break;
507
+ case first === provider:
508
+ break;
509
+ case IsUndefined(second):
510
+ second = provider;
511
+ break;
512
+ case second === provider:
513
+ break;
514
+ default:
515
+ if (rest === undefined)
516
+ rest = new _Set;
517
+ rest.add(provider);
518
+ break;
519
+ }
520
+ }
521
+ function getProviderNoCache(O, P) {
522
+ if (!IsUndefined(first)) {
523
+ if (first.isProviderFor(O, P))
524
+ return first;
525
+ if (!IsUndefined(second)) {
526
+ if (second.isProviderFor(O, P))
527
+ return first;
528
+ if (!IsUndefined(rest)) {
529
+ var iterator = GetIterator(rest);
530
+ while (true) {
531
+ var next = IteratorStep(iterator);
532
+ if (!next) {
533
+ return;
534
+ }
535
+ var provider = IteratorValue(next);
536
+ if (provider.isProviderFor(O, P)) {
537
+ IteratorClose(iterator);
538
+ return provider;
539
+ }
540
+ }
541
+ }
542
+ }
543
+ }
544
+ if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) {
545
+ return fallback;
546
+ }
547
+ return;
548
+ }
549
+ function getProvider(O, P) {
550
+ var providerMap = targetProviderMap.get(O);
551
+ var provider;
552
+ if (!IsUndefined(providerMap)) {
553
+ provider = providerMap.get(P);
554
+ }
555
+ if (!IsUndefined(provider)) {
556
+ return provider;
557
+ }
558
+ provider = getProviderNoCache(O, P);
559
+ if (!IsUndefined(provider)) {
560
+ if (IsUndefined(providerMap)) {
561
+ providerMap = new _Map;
562
+ targetProviderMap.set(O, providerMap);
563
+ }
564
+ providerMap.set(P, provider);
565
+ }
566
+ return provider;
567
+ }
568
+ function hasProvider(provider) {
569
+ if (IsUndefined(provider))
570
+ throw new TypeError;
571
+ return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider);
572
+ }
573
+ function setProvider(O, P, provider) {
574
+ if (!hasProvider(provider)) {
575
+ throw new Error("Metadata provider not registered.");
576
+ }
577
+ var existingProvider = getProvider(O, P);
578
+ if (existingProvider !== provider) {
579
+ if (!IsUndefined(existingProvider)) {
580
+ return false;
581
+ }
582
+ var providerMap = targetProviderMap.get(O);
583
+ if (IsUndefined(providerMap)) {
584
+ providerMap = new _Map;
585
+ targetProviderMap.set(O, providerMap);
586
+ }
587
+ providerMap.set(P, provider);
588
+ }
589
+ return true;
590
+ }
591
+ }
592
+ function GetOrCreateMetadataRegistry() {
593
+ var metadataRegistry2;
594
+ if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) {
595
+ metadataRegistry2 = root.Reflect[registrySymbol];
596
+ }
597
+ if (IsUndefined(metadataRegistry2)) {
598
+ metadataRegistry2 = CreateMetadataRegistry();
599
+ }
600
+ if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) {
601
+ Object.defineProperty(root.Reflect, registrySymbol, {
602
+ enumerable: false,
603
+ configurable: false,
604
+ writable: false,
605
+ value: metadataRegistry2
606
+ });
607
+ }
608
+ return metadataRegistry2;
609
+ }
610
+ function CreateMetadataProvider(registry) {
611
+ var metadata2 = new _WeakMap;
612
+ var provider = {
613
+ isProviderFor: function(O, P) {
614
+ var targetMetadata = metadata2.get(O);
615
+ if (IsUndefined(targetMetadata))
616
+ return false;
617
+ return targetMetadata.has(P);
618
+ },
619
+ OrdinaryDefineOwnMetadata: OrdinaryDefineOwnMetadata2,
620
+ OrdinaryHasOwnMetadata: OrdinaryHasOwnMetadata2,
621
+ OrdinaryGetOwnMetadata: OrdinaryGetOwnMetadata2,
622
+ OrdinaryOwnMetadataKeys: OrdinaryOwnMetadataKeys2,
623
+ OrdinaryDeleteMetadata
624
+ };
625
+ metadataRegistry.registerProvider(provider);
626
+ return provider;
627
+ function GetOrCreateMetadataMap(O, P, Create) {
628
+ var targetMetadata = metadata2.get(O);
629
+ var createdTargetMetadata = false;
630
+ if (IsUndefined(targetMetadata)) {
631
+ if (!Create)
632
+ return;
633
+ targetMetadata = new _Map;
634
+ metadata2.set(O, targetMetadata);
635
+ createdTargetMetadata = true;
636
+ }
637
+ var metadataMap = targetMetadata.get(P);
638
+ if (IsUndefined(metadataMap)) {
639
+ if (!Create)
640
+ return;
641
+ metadataMap = new _Map;
642
+ targetMetadata.set(P, metadataMap);
643
+ if (!registry.setProvider(O, P, provider)) {
644
+ targetMetadata.delete(P);
645
+ if (createdTargetMetadata) {
646
+ metadata2.delete(O);
647
+ }
648
+ throw new Error("Wrong provider for target.");
649
+ }
650
+ }
651
+ return metadataMap;
652
+ }
653
+ function OrdinaryHasOwnMetadata2(MetadataKey, O, P) {
654
+ var metadataMap = GetOrCreateMetadataMap(O, P, false);
655
+ if (IsUndefined(metadataMap))
656
+ return false;
657
+ return ToBoolean(metadataMap.has(MetadataKey));
658
+ }
659
+ function OrdinaryGetOwnMetadata2(MetadataKey, O, P) {
660
+ var metadataMap = GetOrCreateMetadataMap(O, P, false);
661
+ if (IsUndefined(metadataMap))
662
+ return;
663
+ return metadataMap.get(MetadataKey);
664
+ }
665
+ function OrdinaryDefineOwnMetadata2(MetadataKey, MetadataValue, O, P) {
666
+ var metadataMap = GetOrCreateMetadataMap(O, P, true);
667
+ metadataMap.set(MetadataKey, MetadataValue);
668
+ }
669
+ function OrdinaryOwnMetadataKeys2(O, P) {
670
+ var keys = [];
671
+ var metadataMap = GetOrCreateMetadataMap(O, P, false);
672
+ if (IsUndefined(metadataMap))
673
+ return keys;
674
+ var keysObj = metadataMap.keys();
675
+ var iterator = GetIterator(keysObj);
676
+ var k = 0;
677
+ while (true) {
678
+ var next = IteratorStep(iterator);
679
+ if (!next) {
680
+ keys.length = k;
681
+ return keys;
682
+ }
683
+ var nextValue = IteratorValue(next);
684
+ try {
685
+ keys[k] = nextValue;
686
+ } catch (e) {
687
+ try {
688
+ IteratorClose(iterator);
689
+ } finally {
690
+ throw e;
691
+ }
692
+ }
693
+ k++;
694
+ }
695
+ }
696
+ function OrdinaryDeleteMetadata(MetadataKey, O, P) {
697
+ var metadataMap = GetOrCreateMetadataMap(O, P, false);
698
+ if (IsUndefined(metadataMap))
699
+ return false;
700
+ if (!metadataMap.delete(MetadataKey))
701
+ return false;
702
+ if (metadataMap.size === 0) {
703
+ var targetMetadata = metadata2.get(O);
704
+ if (!IsUndefined(targetMetadata)) {
705
+ targetMetadata.delete(P);
706
+ if (targetMetadata.size === 0) {
707
+ metadata2.delete(targetMetadata);
708
+ }
709
+ }
710
+ }
711
+ return true;
712
+ }
713
+ }
714
+ function CreateFallbackProvider(reflect) {
715
+ var { defineMetadata: defineMetadata2, hasOwnMetadata: hasOwnMetadata2, getOwnMetadata: getOwnMetadata2, getOwnMetadataKeys: getOwnMetadataKeys2, deleteMetadata: deleteMetadata2 } = reflect;
716
+ var metadataOwner = new _WeakMap;
717
+ var provider = {
718
+ isProviderFor: function(O, P) {
719
+ var metadataPropertySet = metadataOwner.get(O);
720
+ if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) {
721
+ return true;
722
+ }
723
+ if (getOwnMetadataKeys2(O, P).length) {
724
+ if (IsUndefined(metadataPropertySet)) {
725
+ metadataPropertySet = new _Set;
726
+ metadataOwner.set(O, metadataPropertySet);
727
+ }
728
+ metadataPropertySet.add(P);
729
+ return true;
730
+ }
731
+ return false;
732
+ },
733
+ OrdinaryDefineOwnMetadata: defineMetadata2,
734
+ OrdinaryHasOwnMetadata: hasOwnMetadata2,
735
+ OrdinaryGetOwnMetadata: getOwnMetadata2,
736
+ OrdinaryOwnMetadataKeys: getOwnMetadataKeys2,
737
+ OrdinaryDeleteMetadata: deleteMetadata2
738
+ };
739
+ return provider;
740
+ }
741
+ function GetMetadataProvider(O, P, Create) {
742
+ var registeredProvider = metadataRegistry.getProvider(O, P);
743
+ if (!IsUndefined(registeredProvider)) {
744
+ return registeredProvider;
745
+ }
746
+ if (Create) {
747
+ if (metadataRegistry.setProvider(O, P, metadataProvider)) {
748
+ return metadataProvider;
749
+ }
750
+ throw new Error("Illegal state.");
751
+ }
752
+ return;
753
+ }
754
+ function CreateMapPolyfill() {
755
+ var cacheSentinel = {};
756
+ var arraySentinel = [];
757
+ var MapIterator = function() {
758
+ function MapIterator2(keys, values, selector) {
759
+ this._index = 0;
760
+ this._keys = keys;
761
+ this._values = values;
762
+ this._selector = selector;
763
+ }
764
+ MapIterator2.prototype["@@iterator"] = function() {
765
+ return this;
766
+ };
767
+ MapIterator2.prototype[iteratorSymbol] = function() {
768
+ return this;
769
+ };
770
+ MapIterator2.prototype.next = function() {
771
+ var index = this._index;
772
+ if (index >= 0 && index < this._keys.length) {
773
+ var result = this._selector(this._keys[index], this._values[index]);
774
+ if (index + 1 >= this._keys.length) {
775
+ this._index = -1;
776
+ this._keys = arraySentinel;
777
+ this._values = arraySentinel;
778
+ } else {
779
+ this._index++;
780
+ }
781
+ return { value: result, done: false };
782
+ }
783
+ return { value: undefined, done: true };
784
+ };
785
+ MapIterator2.prototype.throw = function(error) {
786
+ if (this._index >= 0) {
787
+ this._index = -1;
788
+ this._keys = arraySentinel;
789
+ this._values = arraySentinel;
790
+ }
791
+ throw error;
792
+ };
793
+ MapIterator2.prototype.return = function(value) {
794
+ if (this._index >= 0) {
795
+ this._index = -1;
796
+ this._keys = arraySentinel;
797
+ this._values = arraySentinel;
798
+ }
799
+ return { value, done: true };
800
+ };
801
+ return MapIterator2;
802
+ }();
803
+ var Map2 = function() {
804
+ function Map3() {
805
+ this._keys = [];
806
+ this._values = [];
807
+ this._cacheKey = cacheSentinel;
808
+ this._cacheIndex = -2;
809
+ }
810
+ Object.defineProperty(Map3.prototype, "size", {
811
+ get: function() {
812
+ return this._keys.length;
813
+ },
814
+ enumerable: true,
815
+ configurable: true
816
+ });
817
+ Map3.prototype.has = function(key) {
818
+ return this._find(key, false) >= 0;
819
+ };
820
+ Map3.prototype.get = function(key) {
821
+ var index = this._find(key, false);
822
+ return index >= 0 ? this._values[index] : undefined;
823
+ };
824
+ Map3.prototype.set = function(key, value) {
825
+ var index = this._find(key, true);
826
+ this._values[index] = value;
827
+ return this;
828
+ };
829
+ Map3.prototype.delete = function(key) {
830
+ var index = this._find(key, false);
831
+ if (index >= 0) {
832
+ var size = this._keys.length;
833
+ for (var i = index + 1;i < size; i++) {
834
+ this._keys[i - 1] = this._keys[i];
835
+ this._values[i - 1] = this._values[i];
836
+ }
837
+ this._keys.length--;
838
+ this._values.length--;
839
+ if (SameValueZero(key, this._cacheKey)) {
840
+ this._cacheKey = cacheSentinel;
841
+ this._cacheIndex = -2;
842
+ }
843
+ return true;
844
+ }
845
+ return false;
846
+ };
847
+ Map3.prototype.clear = function() {
848
+ this._keys.length = 0;
849
+ this._values.length = 0;
850
+ this._cacheKey = cacheSentinel;
851
+ this._cacheIndex = -2;
852
+ };
853
+ Map3.prototype.keys = function() {
854
+ return new MapIterator(this._keys, this._values, getKey);
855
+ };
856
+ Map3.prototype.values = function() {
857
+ return new MapIterator(this._keys, this._values, getValue);
858
+ };
859
+ Map3.prototype.entries = function() {
860
+ return new MapIterator(this._keys, this._values, getEntry);
861
+ };
862
+ Map3.prototype["@@iterator"] = function() {
863
+ return this.entries();
864
+ };
865
+ Map3.prototype[iteratorSymbol] = function() {
866
+ return this.entries();
867
+ };
868
+ Map3.prototype._find = function(key, insert) {
869
+ if (!SameValueZero(this._cacheKey, key)) {
870
+ this._cacheIndex = -1;
871
+ for (var i = 0;i < this._keys.length; i++) {
872
+ if (SameValueZero(this._keys[i], key)) {
873
+ this._cacheIndex = i;
874
+ break;
875
+ }
876
+ }
877
+ }
878
+ if (this._cacheIndex < 0 && insert) {
879
+ this._cacheIndex = this._keys.length;
880
+ this._keys.push(key);
881
+ this._values.push(undefined);
882
+ }
883
+ return this._cacheIndex;
884
+ };
885
+ return Map3;
886
+ }();
887
+ return Map2;
888
+ function getKey(key, _) {
889
+ return key;
890
+ }
891
+ function getValue(_, value) {
892
+ return value;
893
+ }
894
+ function getEntry(key, value) {
895
+ return [key, value];
896
+ }
897
+ }
898
+ function CreateSetPolyfill() {
899
+ var Set2 = function() {
900
+ function Set3() {
901
+ this._map = new _Map;
902
+ }
903
+ Object.defineProperty(Set3.prototype, "size", {
904
+ get: function() {
905
+ return this._map.size;
906
+ },
907
+ enumerable: true,
908
+ configurable: true
909
+ });
910
+ Set3.prototype.has = function(value) {
911
+ return this._map.has(value);
912
+ };
913
+ Set3.prototype.add = function(value) {
914
+ return this._map.set(value, value), this;
915
+ };
916
+ Set3.prototype.delete = function(value) {
917
+ return this._map.delete(value);
918
+ };
919
+ Set3.prototype.clear = function() {
920
+ this._map.clear();
921
+ };
922
+ Set3.prototype.keys = function() {
923
+ return this._map.keys();
924
+ };
925
+ Set3.prototype.values = function() {
926
+ return this._map.keys();
927
+ };
928
+ Set3.prototype.entries = function() {
929
+ return this._map.entries();
930
+ };
931
+ Set3.prototype["@@iterator"] = function() {
932
+ return this.keys();
933
+ };
934
+ Set3.prototype[iteratorSymbol] = function() {
935
+ return this.keys();
936
+ };
937
+ return Set3;
938
+ }();
939
+ return Set2;
940
+ }
941
+ function CreateWeakMapPolyfill() {
942
+ var UUID_SIZE = 16;
943
+ var keys = HashMap.create();
944
+ var rootKey = CreateUniqueKey();
945
+ return function() {
946
+ function WeakMap2() {
947
+ this._key = CreateUniqueKey();
948
+ }
949
+ WeakMap2.prototype.has = function(target) {
950
+ var table = GetOrCreateWeakMapTable(target, false);
951
+ return table !== undefined ? HashMap.has(table, this._key) : false;
952
+ };
953
+ WeakMap2.prototype.get = function(target) {
954
+ var table = GetOrCreateWeakMapTable(target, false);
955
+ return table !== undefined ? HashMap.get(table, this._key) : undefined;
956
+ };
957
+ WeakMap2.prototype.set = function(target, value) {
958
+ var table = GetOrCreateWeakMapTable(target, true);
959
+ table[this._key] = value;
960
+ return this;
961
+ };
962
+ WeakMap2.prototype.delete = function(target) {
963
+ var table = GetOrCreateWeakMapTable(target, false);
964
+ return table !== undefined ? delete table[this._key] : false;
965
+ };
966
+ WeakMap2.prototype.clear = function() {
967
+ this._key = CreateUniqueKey();
968
+ };
969
+ return WeakMap2;
970
+ }();
971
+ function CreateUniqueKey() {
972
+ var key;
973
+ do
974
+ key = "@@WeakMap@@" + CreateUUID();
975
+ while (HashMap.has(keys, key));
976
+ keys[key] = true;
977
+ return key;
978
+ }
979
+ function GetOrCreateWeakMapTable(target, create) {
980
+ if (!hasOwn.call(target, rootKey)) {
981
+ if (!create)
982
+ return;
983
+ Object.defineProperty(target, rootKey, { value: HashMap.create() });
984
+ }
985
+ return target[rootKey];
986
+ }
987
+ function FillRandomBytes(buffer, size) {
988
+ for (var i = 0;i < size; ++i)
989
+ buffer[i] = Math.random() * 255 | 0;
990
+ return buffer;
991
+ }
992
+ function GenRandomBytes(size) {
993
+ if (typeof Uint8Array === "function") {
994
+ var array = new Uint8Array(size);
995
+ if (typeof crypto !== "undefined") {
996
+ crypto.getRandomValues(array);
997
+ } else if (typeof msCrypto !== "undefined") {
998
+ msCrypto.getRandomValues(array);
999
+ } else {
1000
+ FillRandomBytes(array, size);
1001
+ }
1002
+ return array;
1003
+ }
1004
+ return FillRandomBytes(new Array(size), size);
1005
+ }
1006
+ function CreateUUID() {
1007
+ var data = GenRandomBytes(UUID_SIZE);
1008
+ data[6] = data[6] & 79 | 64;
1009
+ data[8] = data[8] & 191 | 128;
1010
+ var result = "";
1011
+ for (var offset = 0;offset < UUID_SIZE; ++offset) {
1012
+ var byte = data[offset];
1013
+ if (offset === 4 || offset === 6 || offset === 8)
1014
+ result += "-";
1015
+ if (byte < 16)
1016
+ result += "0";
1017
+ result += byte.toString(16).toLowerCase();
1018
+ }
1019
+ return result;
1020
+ }
1021
+ }
1022
+ function MakeDictionary(obj) {
1023
+ obj.__ = undefined;
1024
+ delete obj.__;
1025
+ return obj;
1026
+ }
1027
+ });
1028
+ })(Reflect2 || (Reflect2 = {}));
1029
+ });
1030
+
1031
+ // node_modules/node-cron/dist/esm/create-id.js
1032
+ var require_create_id = __commonJS((exports) => {
1033
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1034
+ return mod && mod.__esModule ? mod : { default: mod };
1035
+ };
1036
+ Object.defineProperty(exports, "__esModule", { value: true });
1037
+ exports.createID = createID;
1038
+ var node_crypto_1 = __importDefault(__require("crypto"));
1039
+ function createID(prefix = "", length = 16) {
1040
+ const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1041
+ const values = node_crypto_1.default.randomBytes(length);
1042
+ const id = Array.from(values, (v) => charset[v % charset.length]).join("");
1043
+ return prefix ? `${prefix}-${id}` : id;
1044
+ }
1045
+ });
1046
+
1047
+ // node_modules/node-cron/dist/esm/logger.js
1048
+ var require_logger = __commonJS((exports) => {
1049
+ Object.defineProperty(exports, "__esModule", { value: true });
1050
+ var levelColors = {
1051
+ INFO: "\x1B[36m",
1052
+ WARN: "\x1B[33m",
1053
+ ERROR: "\x1B[31m",
1054
+ DEBUG: "\x1B[35m"
1055
+ };
1056
+ var GREEN = "\x1B[32m";
1057
+ var RESET = "\x1B[0m";
1058
+ function log(level, message, extra) {
1059
+ const timestamp = new Date().toISOString();
1060
+ const color = levelColors[level] ?? "";
1061
+ const prefix = `[${timestamp}] [PID: ${process.pid}] ${GREEN}[NODE-CRON]${GREEN} ${color}[${level}]${RESET}`;
1062
+ const output = `${prefix} ${message}`;
1063
+ switch (level) {
1064
+ case "ERROR":
1065
+ console.error(output, extra ?? "");
1066
+ break;
1067
+ case "DEBUG":
1068
+ console.debug(output, extra ?? "");
1069
+ break;
1070
+ case "WARN":
1071
+ console.warn(output);
1072
+ break;
1073
+ case "INFO":
1074
+ default:
1075
+ console.info(output);
1076
+ break;
1077
+ }
1078
+ }
1079
+ var logger = {
1080
+ info(message) {
1081
+ log("INFO", message);
1082
+ },
1083
+ warn(message) {
1084
+ log("WARN", message);
1085
+ },
1086
+ error(message, err) {
1087
+ if (message instanceof Error) {
1088
+ log("ERROR", message.message, message);
1089
+ } else {
1090
+ log("ERROR", message, err);
1091
+ }
1092
+ },
1093
+ debug(message, err) {
1094
+ if (message instanceof Error) {
1095
+ log("DEBUG", message.message, message);
1096
+ } else {
1097
+ log("DEBUG", message, err);
1098
+ }
1099
+ }
1100
+ };
1101
+ exports.default = logger;
1102
+ });
1103
+
1104
+ // node_modules/node-cron/dist/esm/promise/tracked-promise.js
1105
+ var require_tracked_promise = __commonJS((exports) => {
1106
+ Object.defineProperty(exports, "__esModule", { value: true });
1107
+ exports.TrackedPromise = undefined;
1108
+
1109
+ class TrackedPromise {
1110
+ promise;
1111
+ error;
1112
+ state;
1113
+ value;
1114
+ constructor(executor) {
1115
+ this.state = "pending";
1116
+ this.promise = new Promise((resolve, reject) => {
1117
+ executor((value) => {
1118
+ this.state = "fulfilled";
1119
+ this.value = value;
1120
+ resolve(value);
1121
+ }, (error) => {
1122
+ this.state = "rejected";
1123
+ this.error = error;
1124
+ reject(error);
1125
+ });
1126
+ });
1127
+ }
1128
+ getPromise() {
1129
+ return this.promise;
1130
+ }
1131
+ getState() {
1132
+ return this.state;
1133
+ }
1134
+ isPending() {
1135
+ return this.state === "pending";
1136
+ }
1137
+ isFulfilled() {
1138
+ return this.state === "fulfilled";
1139
+ }
1140
+ isRejected() {
1141
+ return this.state === "rejected";
1142
+ }
1143
+ getValue() {
1144
+ return this.value;
1145
+ }
1146
+ getError() {
1147
+ return this.error;
1148
+ }
1149
+ then(onfulfilled, onrejected) {
1150
+ return this.promise.then(onfulfilled, onrejected);
1151
+ }
1152
+ catch(onrejected) {
1153
+ return this.promise.catch(onrejected);
1154
+ }
1155
+ finally(onfinally) {
1156
+ return this.promise.finally(onfinally);
1157
+ }
1158
+ }
1159
+ exports.TrackedPromise = TrackedPromise;
1160
+ });
1161
+
1162
+ // node_modules/node-cron/dist/esm/scheduler/runner.js
1163
+ var require_runner = __commonJS((exports) => {
1164
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1165
+ return mod && mod.__esModule ? mod : { default: mod };
1166
+ };
1167
+ Object.defineProperty(exports, "__esModule", { value: true });
1168
+ exports.Runner = undefined;
1169
+ var create_id_1 = require_create_id();
1170
+ var logger_1 = __importDefault(require_logger());
1171
+ var tracked_promise_1 = require_tracked_promise();
1172
+ function emptyOnFn() {}
1173
+ function emptyHookFn() {
1174
+ return true;
1175
+ }
1176
+ function defaultOnError(date, error) {
1177
+ logger_1.default.error("Task failed with error!", error);
1178
+ }
1179
+
1180
+ class Runner {
1181
+ timeMatcher;
1182
+ onMatch;
1183
+ noOverlap;
1184
+ maxExecutions;
1185
+ maxRandomDelay;
1186
+ runCount;
1187
+ running;
1188
+ heartBeatTimeout;
1189
+ onMissedExecution;
1190
+ onOverlap;
1191
+ onError;
1192
+ beforeRun;
1193
+ onFinished;
1194
+ onMaxExecutions;
1195
+ constructor(timeMatcher, onMatch, options) {
1196
+ this.timeMatcher = timeMatcher;
1197
+ this.onMatch = onMatch;
1198
+ this.noOverlap = options == undefined || options.noOverlap === undefined ? false : options.noOverlap;
1199
+ this.maxExecutions = options?.maxExecutions;
1200
+ this.maxRandomDelay = options?.maxRandomDelay || 0;
1201
+ this.onMissedExecution = options?.onMissedExecution || emptyOnFn;
1202
+ this.onOverlap = options?.onOverlap || emptyOnFn;
1203
+ this.onError = options?.onError || defaultOnError;
1204
+ this.onFinished = options?.onFinished || emptyHookFn;
1205
+ this.beforeRun = options?.beforeRun || emptyHookFn;
1206
+ this.onMaxExecutions = options?.onMaxExecutions || emptyOnFn;
1207
+ this.runCount = 0;
1208
+ this.running = false;
1209
+ }
1210
+ start() {
1211
+ this.running = true;
1212
+ let lastExecution;
1213
+ let expectedNextExecution;
1214
+ const scheduleNextHeartBeat = (currentDate) => {
1215
+ if (this.running) {
1216
+ clearTimeout(this.heartBeatTimeout);
1217
+ this.heartBeatTimeout = setTimeout(heartBeat, getDelay(this.timeMatcher, currentDate));
1218
+ }
1219
+ };
1220
+ const runTask = (date) => {
1221
+ return new Promise(async (resolve) => {
1222
+ const execution = {
1223
+ id: (0, create_id_1.createID)("exec"),
1224
+ reason: "scheduled"
1225
+ };
1226
+ const shouldExecute = await this.beforeRun(date, execution);
1227
+ const randomDelay = Math.floor(Math.random() * this.maxRandomDelay);
1228
+ if (shouldExecute) {
1229
+ setTimeout(async () => {
1230
+ try {
1231
+ this.runCount++;
1232
+ execution.startedAt = new Date;
1233
+ const result = await this.onMatch(date, execution);
1234
+ execution.finishedAt = new Date;
1235
+ execution.result = result;
1236
+ this.onFinished(date, execution);
1237
+ if (this.maxExecutions && this.runCount >= this.maxExecutions) {
1238
+ this.onMaxExecutions(date);
1239
+ this.stop();
1240
+ }
1241
+ } catch (error) {
1242
+ execution.finishedAt = new Date;
1243
+ execution.error = error;
1244
+ this.onError(date, error, execution);
1245
+ }
1246
+ resolve(true);
1247
+ }, randomDelay);
1248
+ }
1249
+ });
1250
+ };
1251
+ const checkAndRun = (date) => {
1252
+ return new tracked_promise_1.TrackedPromise(async (resolve, reject) => {
1253
+ try {
1254
+ if (this.timeMatcher.match(date)) {
1255
+ await runTask(date);
1256
+ }
1257
+ resolve(true);
1258
+ } catch (err) {
1259
+ reject(err);
1260
+ }
1261
+ });
1262
+ };
1263
+ const heartBeat = async () => {
1264
+ const currentDate = nowWithoutMs();
1265
+ if (expectedNextExecution && expectedNextExecution.getTime() < currentDate.getTime()) {
1266
+ while (expectedNextExecution.getTime() < currentDate.getTime()) {
1267
+ logger_1.default.warn(`missed execution at ${expectedNextExecution}! Possible blocking IO or high CPU user at the same process used by node-cron.`);
1268
+ expectedNextExecution = this.timeMatcher.getNextMatch(expectedNextExecution);
1269
+ runAsync(this.onMissedExecution, expectedNextExecution, defaultOnError);
1270
+ }
1271
+ }
1272
+ if (lastExecution && lastExecution.getState() === "pending") {
1273
+ runAsync(this.onOverlap, currentDate, defaultOnError);
1274
+ if (this.noOverlap) {
1275
+ logger_1.default.warn("task still running, new execution blocked by overlap prevention!");
1276
+ expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
1277
+ scheduleNextHeartBeat(currentDate);
1278
+ return;
1279
+ }
1280
+ }
1281
+ lastExecution = checkAndRun(currentDate);
1282
+ expectedNextExecution = this.timeMatcher.getNextMatch(currentDate);
1283
+ scheduleNextHeartBeat(currentDate);
1284
+ };
1285
+ this.heartBeatTimeout = setTimeout(() => {
1286
+ heartBeat();
1287
+ }, getDelay(this.timeMatcher, nowWithoutMs()));
1288
+ }
1289
+ nextRun() {
1290
+ return this.timeMatcher.getNextMatch(new Date);
1291
+ }
1292
+ stop() {
1293
+ this.running = false;
1294
+ if (this.heartBeatTimeout) {
1295
+ clearTimeout(this.heartBeatTimeout);
1296
+ this.heartBeatTimeout = undefined;
1297
+ }
1298
+ }
1299
+ isStarted() {
1300
+ return !!this.heartBeatTimeout && this.running;
1301
+ }
1302
+ isStopped() {
1303
+ return !this.isStarted();
1304
+ }
1305
+ async execute() {
1306
+ const date = new Date;
1307
+ const execution = {
1308
+ id: (0, create_id_1.createID)("exec"),
1309
+ reason: "invoked"
1310
+ };
1311
+ try {
1312
+ const shouldExecute = await this.beforeRun(date, execution);
1313
+ if (shouldExecute) {
1314
+ this.runCount++;
1315
+ execution.startedAt = new Date;
1316
+ const result = await this.onMatch(date, execution);
1317
+ execution.finishedAt = new Date;
1318
+ execution.result = result;
1319
+ this.onFinished(date, execution);
1320
+ }
1321
+ } catch (error) {
1322
+ execution.finishedAt = new Date;
1323
+ execution.error = error;
1324
+ this.onError(date, error, execution);
1325
+ }
1326
+ }
1327
+ }
1328
+ exports.Runner = Runner;
1329
+ async function runAsync(fn, date, onError) {
1330
+ try {
1331
+ await fn(date);
1332
+ } catch (error) {
1333
+ onError(date, error);
1334
+ }
1335
+ }
1336
+ function getDelay(timeMatcher, currentDate) {
1337
+ const maxDelay = 86400000;
1338
+ const nextRun = timeMatcher.getNextMatch(currentDate);
1339
+ const now = new Date;
1340
+ const delay = nextRun.getTime() - now.getTime();
1341
+ if (delay > maxDelay) {
1342
+ return maxDelay;
1343
+ }
1344
+ return Math.max(0, delay);
1345
+ }
1346
+ function nowWithoutMs() {
1347
+ const date = new Date;
1348
+ date.setMilliseconds(0);
1349
+ return date;
1350
+ }
1351
+ });
1352
+
1353
+ // node_modules/node-cron/dist/esm/pattern/convertion/month-names-conversion.js
1354
+ var require_month_names_conversion = __commonJS((exports) => {
1355
+ Object.defineProperty(exports, "__esModule", { value: true });
1356
+ exports.default = (() => {
1357
+ const months = [
1358
+ "january",
1359
+ "february",
1360
+ "march",
1361
+ "april",
1362
+ "may",
1363
+ "june",
1364
+ "july",
1365
+ "august",
1366
+ "september",
1367
+ "october",
1368
+ "november",
1369
+ "december"
1370
+ ];
1371
+ const shortMonths = [
1372
+ "jan",
1373
+ "feb",
1374
+ "mar",
1375
+ "apr",
1376
+ "may",
1377
+ "jun",
1378
+ "jul",
1379
+ "aug",
1380
+ "sep",
1381
+ "oct",
1382
+ "nov",
1383
+ "dec"
1384
+ ];
1385
+ function convertMonthName(expression, items) {
1386
+ for (let i = 0;i < items.length; i++) {
1387
+ expression = expression.replace(new RegExp(items[i], "gi"), i + 1);
1388
+ }
1389
+ return expression;
1390
+ }
1391
+ function interprete(monthExpression) {
1392
+ monthExpression = convertMonthName(monthExpression, months);
1393
+ monthExpression = convertMonthName(monthExpression, shortMonths);
1394
+ return monthExpression;
1395
+ }
1396
+ return interprete;
1397
+ })();
1398
+ });
1399
+
1400
+ // node_modules/node-cron/dist/esm/pattern/convertion/week-day-names-conversion.js
1401
+ var require_week_day_names_conversion = __commonJS((exports) => {
1402
+ Object.defineProperty(exports, "__esModule", { value: true });
1403
+ exports.default = (() => {
1404
+ const weekDays = [
1405
+ "sunday",
1406
+ "monday",
1407
+ "tuesday",
1408
+ "wednesday",
1409
+ "thursday",
1410
+ "friday",
1411
+ "saturday"
1412
+ ];
1413
+ const shortWeekDays = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1414
+ function convertWeekDayName(expression, items) {
1415
+ for (let i = 0;i < items.length; i++) {
1416
+ expression = expression.replace(new RegExp(items[i], "gi"), i);
1417
+ }
1418
+ return expression;
1419
+ }
1420
+ function convertWeekDays(expression) {
1421
+ expression = expression.replace("7", "0");
1422
+ expression = convertWeekDayName(expression, weekDays);
1423
+ return convertWeekDayName(expression, shortWeekDays);
1424
+ }
1425
+ return convertWeekDays;
1426
+ })();
1427
+ });
1428
+
1429
+ // node_modules/node-cron/dist/esm/pattern/convertion/asterisk-to-range-conversion.js
1430
+ var require_asterisk_to_range_conversion = __commonJS((exports) => {
1431
+ Object.defineProperty(exports, "__esModule", { value: true });
1432
+ exports.default = (() => {
1433
+ function convertAsterisk(expression, replecement) {
1434
+ if (expression.indexOf("*") !== -1) {
1435
+ return expression.replace("*", replecement);
1436
+ }
1437
+ return expression;
1438
+ }
1439
+ function convertAsterisksToRanges(expressions) {
1440
+ expressions[0] = convertAsterisk(expressions[0], "0-59");
1441
+ expressions[1] = convertAsterisk(expressions[1], "0-59");
1442
+ expressions[2] = convertAsterisk(expressions[2], "0-23");
1443
+ expressions[3] = convertAsterisk(expressions[3], "1-31");
1444
+ expressions[4] = convertAsterisk(expressions[4], "1-12");
1445
+ expressions[5] = convertAsterisk(expressions[5], "0-6");
1446
+ return expressions;
1447
+ }
1448
+ return convertAsterisksToRanges;
1449
+ })();
1450
+ });
1451
+
1452
+ // node_modules/node-cron/dist/esm/pattern/convertion/range-conversion.js
1453
+ var require_range_conversion = __commonJS((exports) => {
1454
+ Object.defineProperty(exports, "__esModule", { value: true });
1455
+ exports.default = (() => {
1456
+ function replaceWithRange(expression, text, init, end, stepTxt) {
1457
+ const step = parseInt(stepTxt);
1458
+ const numbers = [];
1459
+ let last = parseInt(end);
1460
+ let first = parseInt(init);
1461
+ if (first > last) {
1462
+ last = parseInt(init);
1463
+ first = parseInt(end);
1464
+ }
1465
+ for (let i = first;i <= last; i += step) {
1466
+ numbers.push(i);
1467
+ }
1468
+ return expression.replace(new RegExp(text, "i"), numbers.join());
1469
+ }
1470
+ function convertRange(expression) {
1471
+ const rangeRegEx = /(\d+)-(\d+)(\/(\d+)|)/;
1472
+ let match = rangeRegEx.exec(expression);
1473
+ while (match !== null && match.length > 0) {
1474
+ expression = replaceWithRange(expression, match[0], match[1], match[2], match[4] || "1");
1475
+ match = rangeRegEx.exec(expression);
1476
+ }
1477
+ return expression;
1478
+ }
1479
+ function convertAllRanges(expressions) {
1480
+ for (let i = 0;i < expressions.length; i++) {
1481
+ expressions[i] = convertRange(expressions[i]);
1482
+ }
1483
+ return expressions;
1484
+ }
1485
+ return convertAllRanges;
1486
+ })();
1487
+ });
1488
+
1489
+ // node_modules/node-cron/dist/esm/pattern/convertion/index.js
1490
+ var require_convertion = __commonJS((exports) => {
1491
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1492
+ return mod && mod.__esModule ? mod : { default: mod };
1493
+ };
1494
+ Object.defineProperty(exports, "__esModule", { value: true });
1495
+ var month_names_conversion_1 = __importDefault(require_month_names_conversion());
1496
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
1497
+ var asterisk_to_range_conversion_1 = __importDefault(require_asterisk_to_range_conversion());
1498
+ var range_conversion_1 = __importDefault(require_range_conversion());
1499
+ exports.default = (() => {
1500
+ function appendSeccondExpression(expressions) {
1501
+ if (expressions.length === 5) {
1502
+ return ["0"].concat(expressions);
1503
+ }
1504
+ return expressions;
1505
+ }
1506
+ function removeSpaces(str) {
1507
+ return str.replace(/\s{2,}/g, " ").trim();
1508
+ }
1509
+ function normalizeIntegers(expressions) {
1510
+ for (let i = 0;i < expressions.length; i++) {
1511
+ const numbers = expressions[i].split(",");
1512
+ for (let j = 0;j < numbers.length; j++) {
1513
+ numbers[j] = parseInt(numbers[j]);
1514
+ }
1515
+ expressions[i] = numbers;
1516
+ }
1517
+ return expressions;
1518
+ }
1519
+ function interprete(expression) {
1520
+ let expressions = removeSpaces(`${expression}`).split(" ");
1521
+ expressions = appendSeccondExpression(expressions);
1522
+ expressions[4] = (0, month_names_conversion_1.default)(expressions[4]);
1523
+ expressions[5] = (0, week_day_names_conversion_1.default)(expressions[5]);
1524
+ expressions = (0, asterisk_to_range_conversion_1.default)(expressions);
1525
+ expressions = (0, range_conversion_1.default)(expressions);
1526
+ expressions = normalizeIntegers(expressions);
1527
+ return expressions;
1528
+ }
1529
+ return interprete;
1530
+ })();
1531
+ });
1532
+
1533
+ // node_modules/node-cron/dist/esm/time/localized-time.js
1534
+ var require_localized_time = __commonJS((exports) => {
1535
+ Object.defineProperty(exports, "__esModule", { value: true });
1536
+ exports.LocalizedTime = undefined;
1537
+
1538
+ class LocalizedTime {
1539
+ timestamp;
1540
+ parts;
1541
+ timezone;
1542
+ constructor(date, timezone) {
1543
+ this.timestamp = date.getTime();
1544
+ this.timezone = timezone;
1545
+ this.parts = buildDateParts(date, timezone);
1546
+ }
1547
+ toDate() {
1548
+ return new Date(this.timestamp);
1549
+ }
1550
+ toISO() {
1551
+ const gmt = this.parts.gmt.replace(/^GMT/, "");
1552
+ const offset = gmt ? gmt : "Z";
1553
+ const pad = (n) => String(n).padStart(2, "0");
1554
+ return `${this.parts.year}-${pad(this.parts.month)}-${pad(this.parts.day)}` + `T${pad(this.parts.hour)}:${pad(this.parts.minute)}:${pad(this.parts.second)}` + `.${String(this.parts.milisecond).padStart(3, "0")}` + offset;
1555
+ }
1556
+ getParts() {
1557
+ return this.parts;
1558
+ }
1559
+ set(field, value) {
1560
+ this.parts[field] = value;
1561
+ const newDate = new Date(this.toISO());
1562
+ this.timestamp = newDate.getTime();
1563
+ this.parts = buildDateParts(newDate, this.timezone);
1564
+ }
1565
+ }
1566
+ exports.LocalizedTime = LocalizedTime;
1567
+ function buildDateParts(date, timezone) {
1568
+ const dftOptions = {
1569
+ year: "numeric",
1570
+ month: "2-digit",
1571
+ day: "2-digit",
1572
+ hour: "2-digit",
1573
+ minute: "2-digit",
1574
+ second: "2-digit",
1575
+ weekday: "short",
1576
+ hour12: false
1577
+ };
1578
+ if (timezone) {
1579
+ dftOptions.timeZone = timezone;
1580
+ }
1581
+ const dateFormat = new Intl.DateTimeFormat("en-US", dftOptions);
1582
+ const parts = dateFormat.formatToParts(date).filter((part) => {
1583
+ return part.type !== "literal";
1584
+ }).reduce((acc, part) => {
1585
+ acc[part.type] = part.value;
1586
+ return acc;
1587
+ }, {});
1588
+ return {
1589
+ day: parseInt(parts.day),
1590
+ month: parseInt(parts.month),
1591
+ year: parseInt(parts.year),
1592
+ hour: parts.hour === "24" ? 0 : parseInt(parts.hour),
1593
+ minute: parseInt(parts.minute),
1594
+ second: parseInt(parts.second),
1595
+ milisecond: date.getMilliseconds(),
1596
+ weekday: parts.weekday,
1597
+ gmt: getTimezoneGMT(date, timezone)
1598
+ };
1599
+ }
1600
+ function getTimezoneGMT(date, timezone) {
1601
+ const utcDate = new Date(date.toLocaleString("en-US", { timeZone: "UTC" }));
1602
+ const tzDate = new Date(date.toLocaleString("en-US", { timeZone: timezone }));
1603
+ let offsetInMinutes = (utcDate.getTime() - tzDate.getTime()) / 60000;
1604
+ const sign = offsetInMinutes <= 0 ? "+" : "-";
1605
+ offsetInMinutes = Math.abs(offsetInMinutes);
1606
+ if (offsetInMinutes === 0)
1607
+ return "Z";
1608
+ const hours = Math.floor(offsetInMinutes / 60).toString().padStart(2, "0");
1609
+ const minutes = Math.floor(offsetInMinutes % 60).toString().padStart(2, "0");
1610
+ return `GMT${sign}${hours}:${minutes}`;
1611
+ }
1612
+ });
1613
+
1614
+ // node_modules/node-cron/dist/esm/time/matcher-walker.js
1615
+ var require_matcher_walker = __commonJS((exports) => {
1616
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1617
+ return mod && mod.__esModule ? mod : { default: mod };
1618
+ };
1619
+ Object.defineProperty(exports, "__esModule", { value: true });
1620
+ exports.MatcherWalker = undefined;
1621
+ var convertion_1 = __importDefault(require_convertion());
1622
+ var localized_time_1 = require_localized_time();
1623
+ var time_matcher_1 = require_time_matcher();
1624
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
1625
+
1626
+ class MatcherWalker {
1627
+ cronExpression;
1628
+ baseDate;
1629
+ pattern;
1630
+ expressions;
1631
+ timeMatcher;
1632
+ timezone;
1633
+ constructor(cronExpression, baseDate, timezone) {
1634
+ this.cronExpression = cronExpression;
1635
+ this.baseDate = baseDate;
1636
+ this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, timezone);
1637
+ this.timezone = timezone;
1638
+ this.expressions = (0, convertion_1.default)(cronExpression);
1639
+ }
1640
+ isMatching() {
1641
+ return this.timeMatcher.match(this.baseDate);
1642
+ }
1643
+ matchNext() {
1644
+ const findNextDateIgnoringWeekday = () => {
1645
+ const baseDate = new Date(this.baseDate.getTime());
1646
+ baseDate.setMilliseconds(0);
1647
+ const localTime = new localized_time_1.LocalizedTime(baseDate, this.timezone);
1648
+ const dateParts = localTime.getParts();
1649
+ const date2 = new localized_time_1.LocalizedTime(localTime.toDate(), this.timezone);
1650
+ const seconds = this.expressions[0];
1651
+ const nextSecond = availableValue(seconds, dateParts.second);
1652
+ if (nextSecond) {
1653
+ date2.set("second", nextSecond);
1654
+ if (this.timeMatcher.match(date2.toDate())) {
1655
+ return date2;
1656
+ }
1657
+ }
1658
+ date2.set("second", seconds[0]);
1659
+ const minutes = this.expressions[1];
1660
+ const nextMinute = availableValue(minutes, dateParts.minute);
1661
+ if (nextMinute) {
1662
+ date2.set("minute", nextMinute);
1663
+ if (this.timeMatcher.match(date2.toDate())) {
1664
+ return date2;
1665
+ }
1666
+ }
1667
+ date2.set("minute", minutes[0]);
1668
+ const hours = this.expressions[2];
1669
+ const nextHour = availableValue(hours, dateParts.hour);
1670
+ if (nextHour) {
1671
+ date2.set("hour", nextHour);
1672
+ if (this.timeMatcher.match(date2.toDate())) {
1673
+ return date2;
1674
+ }
1675
+ }
1676
+ date2.set("hour", hours[0]);
1677
+ const days = this.expressions[3];
1678
+ const nextDay = availableValue(days, dateParts.day);
1679
+ if (nextDay) {
1680
+ date2.set("day", nextDay);
1681
+ if (this.timeMatcher.match(date2.toDate())) {
1682
+ return date2;
1683
+ }
1684
+ }
1685
+ date2.set("day", days[0]);
1686
+ const months = this.expressions[4];
1687
+ const nextMonth = availableValue(months, dateParts.month);
1688
+ if (nextMonth) {
1689
+ date2.set("month", nextMonth);
1690
+ if (this.timeMatcher.match(date2.toDate())) {
1691
+ return date2;
1692
+ }
1693
+ }
1694
+ date2.set("year", date2.getParts().year + 1);
1695
+ date2.set("month", months[0]);
1696
+ return date2;
1697
+ };
1698
+ const date = findNextDateIgnoringWeekday();
1699
+ const weekdays = this.expressions[5];
1700
+ let currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
1701
+ while (!(weekdays.indexOf(currentWeekday) > -1)) {
1702
+ date.set("year", date.getParts().year + 1);
1703
+ currentWeekday = parseInt((0, week_day_names_conversion_1.default)(date.getParts().weekday));
1704
+ }
1705
+ return date;
1706
+ }
1707
+ }
1708
+ exports.MatcherWalker = MatcherWalker;
1709
+ function availableValue(values, currentValue) {
1710
+ const availableValues = values.sort((a, b) => a - b).filter((s) => s > currentValue);
1711
+ if (availableValues.length > 0)
1712
+ return availableValues[0];
1713
+ return false;
1714
+ }
1715
+ });
1716
+
1717
+ // node_modules/node-cron/dist/esm/time/time-matcher.js
1718
+ var require_time_matcher = __commonJS((exports) => {
1719
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1720
+ return mod && mod.__esModule ? mod : { default: mod };
1721
+ };
1722
+ Object.defineProperty(exports, "__esModule", { value: true });
1723
+ exports.TimeMatcher = undefined;
1724
+ var index_1 = __importDefault(require_convertion());
1725
+ var week_day_names_conversion_1 = __importDefault(require_week_day_names_conversion());
1726
+ var localized_time_1 = require_localized_time();
1727
+ var matcher_walker_1 = require_matcher_walker();
1728
+ function matchValue(allowedValues, value) {
1729
+ return allowedValues.indexOf(value) !== -1;
1730
+ }
1731
+
1732
+ class TimeMatcher {
1733
+ timezone;
1734
+ pattern;
1735
+ expressions;
1736
+ constructor(pattern, timezone) {
1737
+ this.timezone = timezone;
1738
+ this.pattern = pattern;
1739
+ this.expressions = (0, index_1.default)(pattern);
1740
+ }
1741
+ match(date) {
1742
+ const localizedTime = new localized_time_1.LocalizedTime(date, this.timezone);
1743
+ const parts = localizedTime.getParts();
1744
+ const runOnSecond = matchValue(this.expressions[0], parts.second);
1745
+ const runOnMinute = matchValue(this.expressions[1], parts.minute);
1746
+ const runOnHour = matchValue(this.expressions[2], parts.hour);
1747
+ const runOnDay = matchValue(this.expressions[3], parts.day);
1748
+ const runOnMonth = matchValue(this.expressions[4], parts.month);
1749
+ const runOnWeekDay = matchValue(this.expressions[5], parseInt((0, week_day_names_conversion_1.default)(parts.weekday)));
1750
+ return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
1751
+ }
1752
+ getNextMatch(date) {
1753
+ const walker = new matcher_walker_1.MatcherWalker(this.pattern, date, this.timezone);
1754
+ const next = walker.matchNext();
1755
+ return next.toDate();
1756
+ }
1757
+ }
1758
+ exports.TimeMatcher = TimeMatcher;
1759
+ });
1760
+
1761
+ // node_modules/node-cron/dist/esm/tasks/state-machine.js
1762
+ var require_state_machine = __commonJS((exports) => {
1763
+ Object.defineProperty(exports, "__esModule", { value: true });
1764
+ exports.StateMachine = undefined;
1765
+ var allowedTransitions = {
1766
+ stopped: ["stopped", "idle", "destroyed"],
1767
+ idle: ["idle", "running", "stopped", "destroyed"],
1768
+ running: ["running", "idle", "stopped", "destroyed"],
1769
+ destroyed: ["destroyed"]
1770
+ };
1771
+
1772
+ class StateMachine {
1773
+ state;
1774
+ constructor(initial = "stopped") {
1775
+ this.state = initial;
1776
+ }
1777
+ changeState(state) {
1778
+ if (allowedTransitions[this.state].includes(state)) {
1779
+ this.state = state;
1780
+ } else {
1781
+ throw new Error(`invalid transition from ${this.state} to ${state}`);
1782
+ }
1783
+ }
1784
+ }
1785
+ exports.StateMachine = StateMachine;
1786
+ });
1787
+
1788
+ // node_modules/node-cron/dist/esm/tasks/inline-scheduled-task.js
1789
+ var require_inline_scheduled_task = __commonJS((exports) => {
1790
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1791
+ return mod && mod.__esModule ? mod : { default: mod };
1792
+ };
1793
+ Object.defineProperty(exports, "__esModule", { value: true });
1794
+ exports.InlineScheduledTask = undefined;
1795
+ var events_1 = __importDefault(__require("events"));
1796
+ var runner_1 = require_runner();
1797
+ var time_matcher_1 = require_time_matcher();
1798
+ var create_id_1 = require_create_id();
1799
+ var state_machine_1 = require_state_machine();
1800
+ var logger_1 = __importDefault(require_logger());
1801
+ var localized_time_1 = require_localized_time();
1802
+
1803
+ class TaskEmitter extends events_1.default {
1804
+ }
1805
+
1806
+ class InlineScheduledTask {
1807
+ emitter;
1808
+ cronExpression;
1809
+ timeMatcher;
1810
+ runner;
1811
+ id;
1812
+ name;
1813
+ stateMachine;
1814
+ timezone;
1815
+ constructor(cronExpression, taskFn, options) {
1816
+ this.emitter = new TaskEmitter;
1817
+ this.cronExpression = cronExpression;
1818
+ this.id = (0, create_id_1.createID)("task", 12);
1819
+ this.name = options?.name || this.id;
1820
+ this.timezone = options?.timezone;
1821
+ this.timeMatcher = new time_matcher_1.TimeMatcher(cronExpression, options?.timezone);
1822
+ this.stateMachine = new state_machine_1.StateMachine;
1823
+ const runnerOptions = {
1824
+ timezone: options?.timezone,
1825
+ noOverlap: options?.noOverlap,
1826
+ maxExecutions: options?.maxExecutions,
1827
+ maxRandomDelay: options?.maxRandomDelay,
1828
+ beforeRun: (date, execution) => {
1829
+ if (execution.reason === "scheduled") {
1830
+ this.changeState("running");
1831
+ }
1832
+ this.emitter.emit("execution:started", this.createContext(date, execution));
1833
+ return true;
1834
+ },
1835
+ onFinished: (date, execution) => {
1836
+ if (execution.reason === "scheduled") {
1837
+ this.changeState("idle");
1838
+ }
1839
+ this.emitter.emit("execution:finished", this.createContext(date, execution));
1840
+ return true;
1841
+ },
1842
+ onError: (date, error, execution) => {
1843
+ logger_1.default.error(error);
1844
+ this.emitter.emit("execution:failed", this.createContext(date, execution));
1845
+ this.changeState("idle");
1846
+ },
1847
+ onOverlap: (date) => {
1848
+ this.emitter.emit("execution:overlap", this.createContext(date));
1849
+ },
1850
+ onMissedExecution: (date) => {
1851
+ this.emitter.emit("execution:missed", this.createContext(date));
1852
+ },
1853
+ onMaxExecutions: (date) => {
1854
+ this.emitter.emit("execution:maxReached", this.createContext(date));
1855
+ this.destroy();
1856
+ }
1857
+ };
1858
+ this.runner = new runner_1.Runner(this.timeMatcher, (date, execution) => {
1859
+ return taskFn(this.createContext(date, execution));
1860
+ }, runnerOptions);
1861
+ }
1862
+ getNextRun() {
1863
+ if (this.stateMachine.state !== "stopped") {
1864
+ return this.runner.nextRun();
1865
+ }
1866
+ return null;
1867
+ }
1868
+ changeState(state) {
1869
+ if (this.runner.isStarted()) {
1870
+ this.stateMachine.changeState(state);
1871
+ }
1872
+ }
1873
+ start() {
1874
+ if (this.runner.isStopped()) {
1875
+ this.runner.start();
1876
+ this.stateMachine.changeState("idle");
1877
+ this.emitter.emit("task:started", this.createContext(new Date));
1878
+ }
1879
+ }
1880
+ stop() {
1881
+ if (this.runner.isStarted()) {
1882
+ this.runner.stop();
1883
+ this.stateMachine.changeState("stopped");
1884
+ this.emitter.emit("task:stopped", this.createContext(new Date));
1885
+ }
1886
+ }
1887
+ getStatus() {
1888
+ return this.stateMachine.state;
1889
+ }
1890
+ destroy() {
1891
+ if (this.stateMachine.state === "destroyed")
1892
+ return;
1893
+ this.stop();
1894
+ this.stateMachine.changeState("destroyed");
1895
+ this.emitter.emit("task:destroyed", this.createContext(new Date));
1896
+ }
1897
+ execute() {
1898
+ return new Promise((resolve, reject) => {
1899
+ const onFail = (context) => {
1900
+ this.off("execution:finished", onFail);
1901
+ reject(context.execution?.error);
1902
+ };
1903
+ const onFinished = (context) => {
1904
+ this.off("execution:failed", onFail);
1905
+ resolve(context.execution?.result);
1906
+ };
1907
+ this.once("execution:finished", onFinished);
1908
+ this.once("execution:failed", onFail);
1909
+ this.runner.execute();
1910
+ });
1911
+ }
1912
+ on(event, fun) {
1913
+ this.emitter.on(event, fun);
1914
+ }
1915
+ off(event, fun) {
1916
+ this.emitter.off(event, fun);
1917
+ }
1918
+ once(event, fun) {
1919
+ this.emitter.once(event, fun);
1920
+ }
1921
+ createContext(executionDate, execution) {
1922
+ const localTime = new localized_time_1.LocalizedTime(executionDate, this.timezone);
1923
+ const ctx = {
1924
+ date: localTime.toDate(),
1925
+ dateLocalIso: localTime.toISO(),
1926
+ triggeredAt: new Date,
1927
+ task: this,
1928
+ execution
1929
+ };
1930
+ return ctx;
1931
+ }
1932
+ }
1933
+ exports.InlineScheduledTask = InlineScheduledTask;
1934
+ });
1935
+
1936
+ // node_modules/node-cron/dist/esm/task-registry.js
1937
+ var require_task_registry = __commonJS((exports) => {
1938
+ Object.defineProperty(exports, "__esModule", { value: true });
1939
+ exports.TaskRegistry = undefined;
1940
+ var tasks = new Map;
1941
+
1942
+ class TaskRegistry {
1943
+ add(task) {
1944
+ if (this.has(task.id)) {
1945
+ throw Error(`task ${task.id} already registred!`);
1946
+ }
1947
+ tasks.set(task.id, task);
1948
+ task.on("task:destroyed", () => {
1949
+ this.remove(task);
1950
+ });
1951
+ }
1952
+ get(taskId) {
1953
+ return tasks.get(taskId);
1954
+ }
1955
+ remove(task) {
1956
+ if (this.has(task.id)) {
1957
+ task?.destroy();
1958
+ tasks.delete(task.id);
1959
+ }
1960
+ }
1961
+ all() {
1962
+ return tasks;
1963
+ }
1964
+ has(taskId) {
1965
+ return tasks.has(taskId);
1966
+ }
1967
+ killAll() {
1968
+ tasks.forEach((id) => this.remove(id));
1969
+ }
1970
+ }
1971
+ exports.TaskRegistry = TaskRegistry;
1972
+ });
1973
+
1974
+ // node_modules/node-cron/dist/esm/pattern/validation/pattern-validation.js
1975
+ var require_pattern_validation = __commonJS((exports) => {
1976
+ var __importDefault = exports && exports.__importDefault || function(mod) {
1977
+ return mod && mod.__esModule ? mod : { default: mod };
1978
+ };
1979
+ Object.defineProperty(exports, "__esModule", { value: true });
1980
+ var index_1 = __importDefault(require_convertion());
1981
+ var validationRegex = /^(?:\d+|\*|\*\/\d+)$/;
1982
+ function isValidExpression(expression, min, max) {
1983
+ const options = expression;
1984
+ for (const option of options) {
1985
+ const optionAsInt = parseInt(option, 10);
1986
+ if (!Number.isNaN(optionAsInt) && (optionAsInt < min || optionAsInt > max) || !validationRegex.test(option))
1987
+ return false;
1988
+ }
1989
+ return true;
1990
+ }
1991
+ function isInvalidSecond(expression) {
1992
+ return !isValidExpression(expression, 0, 59);
1993
+ }
1994
+ function isInvalidMinute(expression) {
1995
+ return !isValidExpression(expression, 0, 59);
1996
+ }
1997
+ function isInvalidHour(expression) {
1998
+ return !isValidExpression(expression, 0, 23);
1999
+ }
2000
+ function isInvalidDayOfMonth(expression) {
2001
+ return !isValidExpression(expression, 1, 31);
2002
+ }
2003
+ function isInvalidMonth(expression) {
2004
+ return !isValidExpression(expression, 1, 12);
2005
+ }
2006
+ function isInvalidWeekDay(expression) {
2007
+ return !isValidExpression(expression, 0, 7);
2008
+ }
2009
+ function validateFields(patterns, executablePatterns) {
2010
+ if (isInvalidSecond(executablePatterns[0]))
2011
+ throw new Error(`${patterns[0]} is a invalid expression for second`);
2012
+ if (isInvalidMinute(executablePatterns[1]))
2013
+ throw new Error(`${patterns[1]} is a invalid expression for minute`);
2014
+ if (isInvalidHour(executablePatterns[2]))
2015
+ throw new Error(`${patterns[2]} is a invalid expression for hour`);
2016
+ if (isInvalidDayOfMonth(executablePatterns[3]))
2017
+ throw new Error(`${patterns[3]} is a invalid expression for day of month`);
2018
+ if (isInvalidMonth(executablePatterns[4]))
2019
+ throw new Error(`${patterns[4]} is a invalid expression for month`);
2020
+ if (isInvalidWeekDay(executablePatterns[5]))
2021
+ throw new Error(`${patterns[5]} is a invalid expression for week day`);
2022
+ }
2023
+ function validate(pattern) {
2024
+ if (typeof pattern !== "string")
2025
+ throw new TypeError("pattern must be a string!");
2026
+ const patterns = pattern.split(" ");
2027
+ const executablePatterns = (0, index_1.default)(pattern);
2028
+ if (patterns.length === 5)
2029
+ patterns.unshift("0");
2030
+ validateFields(patterns, executablePatterns);
2031
+ }
2032
+ exports.default = validate;
2033
+ });
2034
+
2035
+ // node_modules/node-cron/dist/esm/tasks/background-scheduled-task/background-scheduled-task.js
2036
+ var require_background_scheduled_task = __commonJS((exports) => {
2037
+ var __dirname = "/home/filipi.oliveira@gdc.local/poc/diario-dip/node_modules/node-cron/dist/esm/tasks/background-scheduled-task";
2038
+ var __importDefault = exports && exports.__importDefault || function(mod) {
2039
+ return mod && mod.__esModule ? mod : { default: mod };
2040
+ };
2041
+ Object.defineProperty(exports, "__esModule", { value: true });
2042
+ var path_1 = __require("path");
2043
+ var child_process_1 = __require("child_process");
2044
+ var create_id_1 = require_create_id();
2045
+ var stream_1 = __require("stream");
2046
+ var state_machine_1 = require_state_machine();
2047
+ var localized_time_1 = require_localized_time();
2048
+ var logger_1 = __importDefault(require_logger());
2049
+ var time_matcher_1 = require_time_matcher();
2050
+ var daemonPath = (0, path_1.resolve)(__dirname, "daemon.js");
2051
+
2052
+ class TaskEmitter extends stream_1.EventEmitter {
2053
+ }
2054
+
2055
+ class BackgroundScheduledTask {
2056
+ emitter;
2057
+ id;
2058
+ name;
2059
+ cronExpression;
2060
+ taskPath;
2061
+ options;
2062
+ forkProcess;
2063
+ stateMachine;
2064
+ constructor(cronExpression, taskPath, options) {
2065
+ this.cronExpression = cronExpression;
2066
+ this.taskPath = taskPath;
2067
+ this.options = options;
2068
+ this.id = (0, create_id_1.createID)("task");
2069
+ this.name = options?.name || this.id;
2070
+ this.emitter = new TaskEmitter;
2071
+ this.stateMachine = new state_machine_1.StateMachine("stopped");
2072
+ this.on("task:stopped", () => {
2073
+ this.forkProcess?.kill();
2074
+ this.forkProcess = undefined;
2075
+ this.stateMachine.changeState("stopped");
2076
+ });
2077
+ this.on("task:destroyed", () => {
2078
+ this.forkProcess?.kill();
2079
+ this.forkProcess = undefined;
2080
+ this.stateMachine.changeState("destroyed");
2081
+ });
2082
+ }
2083
+ getNextRun() {
2084
+ if (this.stateMachine.state !== "stopped") {
2085
+ const timeMatcher = new time_matcher_1.TimeMatcher(this.cronExpression, this.options?.timezone);
2086
+ return timeMatcher.getNextMatch(new Date);
2087
+ }
2088
+ return null;
2089
+ }
2090
+ start() {
2091
+ return new Promise((resolve, reject) => {
2092
+ if (this.forkProcess) {
2093
+ return resolve(undefined);
2094
+ }
2095
+ const timeout = setTimeout(() => {
2096
+ reject(new Error("Start operation timed out"));
2097
+ }, 5000);
2098
+ try {
2099
+ this.forkProcess = (0, child_process_1.fork)(daemonPath);
2100
+ this.forkProcess.on("error", (err) => {
2101
+ clearTimeout(timeout);
2102
+ reject(new Error(`Error on daemon: ${err.message}`));
2103
+ });
2104
+ this.forkProcess.on("exit", (code, signal) => {
2105
+ if (code !== 0 && signal !== "SIGTERM") {
2106
+ const erro = new Error(`node-cron daemon exited with code ${code || signal}`);
2107
+ logger_1.default.error(erro);
2108
+ clearTimeout(timeout);
2109
+ reject(erro);
2110
+ }
2111
+ });
2112
+ this.forkProcess.on("message", (message) => {
2113
+ if (message.jsonError) {
2114
+ if (message.context?.execution) {
2115
+ message.context.execution.error = deserializeError(message.jsonError);
2116
+ delete message.jsonError;
2117
+ }
2118
+ }
2119
+ if (message.context?.task?.state) {
2120
+ this.stateMachine.changeState(message.context?.task?.state);
2121
+ }
2122
+ if (message.context) {
2123
+ const execution = message.context?.execution;
2124
+ delete execution?.hasError;
2125
+ const context = this.createContext(new Date(message.context.date), execution);
2126
+ this.emitter.emit(message.event, context);
2127
+ }
2128
+ });
2129
+ this.once("task:started", () => {
2130
+ this.stateMachine.changeState("idle");
2131
+ clearTimeout(timeout);
2132
+ resolve(undefined);
2133
+ });
2134
+ this.forkProcess.send({
2135
+ command: "task:start",
2136
+ path: this.taskPath,
2137
+ cron: this.cronExpression,
2138
+ options: this.options
2139
+ });
2140
+ } catch (error) {
2141
+ reject(error);
2142
+ }
2143
+ });
2144
+ }
2145
+ stop() {
2146
+ return new Promise((resolve, reject) => {
2147
+ if (!this.forkProcess) {
2148
+ return resolve(undefined);
2149
+ }
2150
+ const timeoutId = setTimeout(() => {
2151
+ clearTimeout(timeoutId);
2152
+ reject(new Error("Stop operation timed out"));
2153
+ }, 5000);
2154
+ const cleanupAndResolve = () => {
2155
+ clearTimeout(timeoutId);
2156
+ this.off("task:stopped", onStopped);
2157
+ this.forkProcess = undefined;
2158
+ resolve(undefined);
2159
+ };
2160
+ const onStopped = () => {
2161
+ cleanupAndResolve();
2162
+ };
2163
+ this.once("task:stopped", onStopped);
2164
+ this.forkProcess.send({
2165
+ command: "task:stop"
2166
+ });
2167
+ });
2168
+ }
2169
+ getStatus() {
2170
+ return this.stateMachine.state;
2171
+ }
2172
+ destroy() {
2173
+ return new Promise((resolve, reject) => {
2174
+ if (!this.forkProcess) {
2175
+ return resolve(undefined);
2176
+ }
2177
+ const timeoutId = setTimeout(() => {
2178
+ clearTimeout(timeoutId);
2179
+ reject(new Error("Destroy operation timed out"));
2180
+ }, 5000);
2181
+ const onDestroy = () => {
2182
+ clearTimeout(timeoutId);
2183
+ this.off("task:destroyed", onDestroy);
2184
+ resolve(undefined);
2185
+ };
2186
+ this.once("task:destroyed", onDestroy);
2187
+ this.forkProcess.send({
2188
+ command: "task:destroy"
2189
+ });
2190
+ });
2191
+ }
2192
+ execute() {
2193
+ return new Promise((resolve, reject) => {
2194
+ if (!this.forkProcess) {
2195
+ return reject(new Error("Cannot execute background task because it hasn't been started yet. Please initialize the task using the start() method before attempting to execute it."));
2196
+ }
2197
+ const timeoutId = setTimeout(() => {
2198
+ cleanupListeners();
2199
+ reject(new Error("Execution timeout exceeded"));
2200
+ }, 5000);
2201
+ const cleanupListeners = () => {
2202
+ clearTimeout(timeoutId);
2203
+ this.off("execution:finished", onFinished);
2204
+ this.off("execution:failed", onFail);
2205
+ };
2206
+ const onFinished = (context) => {
2207
+ cleanupListeners();
2208
+ resolve(context.execution?.result);
2209
+ };
2210
+ const onFail = (context) => {
2211
+ cleanupListeners();
2212
+ reject(context.execution?.error || new Error("Execution failed without specific error"));
2213
+ };
2214
+ this.once("execution:finished", onFinished);
2215
+ this.once("execution:failed", onFail);
2216
+ this.forkProcess.send({
2217
+ command: "task:execute"
2218
+ });
2219
+ });
2220
+ }
2221
+ on(event, fun) {
2222
+ this.emitter.on(event, fun);
2223
+ }
2224
+ off(event, fun) {
2225
+ this.emitter.off(event, fun);
2226
+ }
2227
+ once(event, fun) {
2228
+ this.emitter.once(event, fun);
2229
+ }
2230
+ createContext(executionDate, execution) {
2231
+ const localTime = new localized_time_1.LocalizedTime(executionDate, this.options?.timezone);
2232
+ const ctx = {
2233
+ date: localTime.toDate(),
2234
+ dateLocalIso: localTime.toISO(),
2235
+ triggeredAt: new Date,
2236
+ task: this,
2237
+ execution
2238
+ };
2239
+ return ctx;
2240
+ }
2241
+ }
2242
+ function deserializeError(str) {
2243
+ const data = JSON.parse(str);
2244
+ const Err = globalThis[data.name] || Error;
2245
+ const err = new Err(data.message);
2246
+ if (data.stack) {
2247
+ err.stack = data.stack;
2248
+ }
2249
+ Object.keys(data).forEach((key) => {
2250
+ if (!["name", "message", "stack"].includes(key)) {
2251
+ err[key] = data[key];
2252
+ }
2253
+ });
2254
+ return err;
2255
+ }
2256
+ exports.default = BackgroundScheduledTask;
2257
+ });
2258
+
2259
+ // node_modules/node-cron/dist/esm/node-cron.js
2260
+ var require_node_cron = __commonJS((exports) => {
2261
+ var __filename = "/home/filipi.oliveira@gdc.local/poc/diario-dip/node_modules/node-cron/dist/esm/node-cron.js";
2262
+ var __importDefault = exports && exports.__importDefault || function(mod) {
2263
+ return mod && mod.__esModule ? mod : { default: mod };
2264
+ };
2265
+ Object.defineProperty(exports, "__esModule", { value: true });
2266
+ exports.nodeCron = exports.getTask = exports.getTasks = undefined;
2267
+ exports.schedule = schedule;
2268
+ exports.createTask = createTask;
2269
+ exports.solvePath = solvePath;
2270
+ exports.validate = validate;
2271
+ var inline_scheduled_task_1 = require_inline_scheduled_task();
2272
+ var task_registry_1 = require_task_registry();
2273
+ var pattern_validation_1 = __importDefault(require_pattern_validation());
2274
+ var background_scheduled_task_1 = __importDefault(require_background_scheduled_task());
2275
+ var path_1 = __importDefault(__require("path"));
2276
+ var url_1 = __require("url");
2277
+ var registry = new task_registry_1.TaskRegistry;
2278
+ function schedule(expression, func, options) {
2279
+ const task = createTask(expression, func, options);
2280
+ task.start();
2281
+ return task;
2282
+ }
2283
+ function createTask(expression, func, options) {
2284
+ let task;
2285
+ if (func instanceof Function) {
2286
+ task = new inline_scheduled_task_1.InlineScheduledTask(expression, func, options);
2287
+ } else {
2288
+ const taskPath = solvePath(func);
2289
+ task = new background_scheduled_task_1.default(expression, taskPath, options);
2290
+ }
2291
+ registry.add(task);
2292
+ return task;
2293
+ }
2294
+ function solvePath(filePath) {
2295
+ if (path_1.default.isAbsolute(filePath))
2296
+ return (0, url_1.pathToFileURL)(filePath).href;
2297
+ if (filePath.startsWith("file://"))
2298
+ return filePath;
2299
+ const stackLines = new Error().stack?.split(`
2300
+ `);
2301
+ if (stackLines) {
2302
+ stackLines?.shift();
2303
+ const callerLine = stackLines?.find((line) => {
2304
+ return line.indexOf(__filename) === -1;
2305
+ });
2306
+ const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
2307
+ if (match) {
2308
+ const dir = `${match[5] ?? ""}${path_1.default.dirname(match[6])}`;
2309
+ return (0, url_1.pathToFileURL)(path_1.default.resolve(dir, filePath)).href;
2310
+ }
2311
+ }
2312
+ throw new Error(`Could not locate task file ${filePath}`);
2313
+ }
2314
+ function validate(expression) {
2315
+ try {
2316
+ (0, pattern_validation_1.default)(expression);
2317
+ return true;
2318
+ } catch (e) {
2319
+ return false;
2320
+ }
2321
+ }
2322
+ exports.getTasks = registry.all;
2323
+ exports.getTask = registry.get;
2324
+ exports.nodeCron = {
2325
+ schedule,
2326
+ createTask,
2327
+ validate,
2328
+ getTasks: exports.getTasks,
2329
+ getTask: exports.getTask
2330
+ };
2331
+ exports.default = exports.nodeCron;
2332
+ });
2333
+
2334
+ // index.ts
2335
+ var import_reflect_metadata21 = __toESM(require_Reflect(), 1);
2336
+
2337
+ // lib/adapters/cache-adapter.ts
2338
+ var {redis, RedisClient } = globalThis.Bun;
2339
+
2340
+ // lib/injectable.ts
2341
+ var import_reflect_metadata = __toESM(require_Reflect(), 1);
2342
+ function Injectable() {
2343
+ return function(target, context) {
2344
+ Reflect.defineMetadata("injectable", true, target);
2345
+ };
2346
+ }
2347
+
2348
+ // lib/adapters/cache-adapter.ts
2349
+ class CacheAdapter {
2350
+ client;
2351
+ constructor(config) {
2352
+ this.client = config ? new RedisClient(config.url) : redis;
2353
+ }
2354
+ async set(key, value, options) {
2355
+ assertValidKey(key);
2356
+ const payload = JSON.stringify(value);
2357
+ await this.client.set(key, payload);
2358
+ if (!options || "permanent" in options)
2359
+ return;
2360
+ const ttlSeconds = "ttlSeconds" in options ? options.ttlSeconds : options.ttl;
2361
+ if (ttlSeconds > 0) {
2362
+ await this.client.expire(key, ttlSeconds);
2363
+ }
2364
+ }
2365
+ async get(key) {
2366
+ assertValidKey(key);
2367
+ const raw = await this.client.get(key);
2368
+ if (raw === null)
2369
+ return {};
2370
+ const parsed = safeJsonParse(raw);
2371
+ if (!isRecord(parsed)) {
2372
+ throw new Error(`Cache key "${key}" does not contain a JSON object.`);
2373
+ }
2374
+ return parsed;
2375
+ }
2376
+ async exists(key) {
2377
+ assertValidKey(key);
2378
+ const result = await this.client.exists(key);
2379
+ return typeof result === "boolean" ? result : Boolean(result);
2380
+ }
2381
+ async remove(key) {
2382
+ assertValidKey(key);
2383
+ await this.client.del(key);
2384
+ }
2385
+ }
2386
+ CacheAdapter = __legacyDecorateClassTS([
2387
+ Injectable(),
2388
+ __legacyMetadataTS("design:paramtypes", [
2389
+ typeof CacheAdapterConfig === "undefined" ? Object : CacheAdapterConfig
2390
+ ])
2391
+ ], CacheAdapter);
2392
+ function assertValidKey(key) {
2393
+ const normalized = key.trim();
2394
+ if (normalized.length === 0) {
2395
+ throw new Error("Cache key cannot be empty.");
2396
+ }
2397
+ }
2398
+ function safeJsonParse(value) {
2399
+ try {
2400
+ return JSON.parse(value);
2401
+ } catch {
2402
+ throw new Error("Failed to parse cached value as JSON.");
2403
+ }
2404
+ }
2405
+ function isRecord(value) {
2406
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2407
+ }
2408
+ // lib/constants/index.ts
2409
+ var PARAM_METADATA_KEY = Symbol("paramMetadata");
2410
+
2411
+ // lib/http-params.ts
2412
+ var import_reflect_metadata2 = __toESM(require_Reflect(), 1);
2413
+
2414
+ // node_modules/zod/v4/core/core.js
2415
+ var NEVER = Object.freeze({
2416
+ status: "aborted"
2417
+ });
2418
+ function $constructor(name, initializer, params) {
2419
+ function init(inst, def) {
2420
+ if (!inst._zod) {
2421
+ Object.defineProperty(inst, "_zod", {
2422
+ value: {
2423
+ def,
2424
+ constr: _,
2425
+ traits: new Set
2426
+ },
2427
+ enumerable: false
2428
+ });
2429
+ }
2430
+ if (inst._zod.traits.has(name)) {
2431
+ return;
2432
+ }
2433
+ inst._zod.traits.add(name);
2434
+ initializer(inst, def);
2435
+ const proto = _.prototype;
2436
+ const keys = Object.keys(proto);
2437
+ for (let i = 0;i < keys.length; i++) {
2438
+ const k = keys[i];
2439
+ if (!(k in inst)) {
2440
+ inst[k] = proto[k].bind(inst);
2441
+ }
2442
+ }
2443
+ }
2444
+ const Parent = params?.Parent ?? Object;
2445
+
2446
+ class Definition extends Parent {
2447
+ }
2448
+ Object.defineProperty(Definition, "name", { value: name });
2449
+ function _(def) {
2450
+ var _a;
2451
+ const inst = params?.Parent ? new Definition : this;
2452
+ init(inst, def);
2453
+ (_a = inst._zod).deferred ?? (_a.deferred = []);
2454
+ for (const fn of inst._zod.deferred) {
2455
+ fn();
2456
+ }
2457
+ return inst;
2458
+ }
2459
+ Object.defineProperty(_, "init", { value: init });
2460
+ Object.defineProperty(_, Symbol.hasInstance, {
2461
+ value: (inst) => {
2462
+ if (params?.Parent && inst instanceof params.Parent)
2463
+ return true;
2464
+ return inst?._zod?.traits?.has(name);
2465
+ }
2466
+ });
2467
+ Object.defineProperty(_, "name", { value: name });
2468
+ return _;
2469
+ }
2470
+ var $brand = Symbol("zod_brand");
2471
+
2472
+ // node_modules/zod/v4/core/util.js
2473
+ function jsonStringifyReplacer(_, value) {
2474
+ if (typeof value === "bigint")
2475
+ return value.toString();
2476
+ return value;
2477
+ }
2478
+ function cached(getter) {
2479
+ const set = false;
2480
+ return {
2481
+ get value() {
2482
+ if (!set) {
2483
+ const value = getter();
2484
+ Object.defineProperty(this, "value", { value });
2485
+ return value;
2486
+ }
2487
+ throw new Error("cached value already set");
2488
+ }
2489
+ };
2490
+ }
2491
+ var EVALUATING = Symbol("evaluating");
2492
+ var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
2493
+ var allowsEval = cached(() => {
2494
+ if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
2495
+ return false;
2496
+ }
2497
+ try {
2498
+ const F = Function;
2499
+ new F("");
2500
+ return true;
2501
+ } catch (_) {
2502
+ return false;
2503
+ }
2504
+ });
2505
+ var propertyKeyTypes = new Set(["string", "number", "symbol"]);
2506
+ var primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
2507
+ var NUMBER_FORMAT_RANGES = {
2508
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
2509
+ int32: [-2147483648, 2147483647],
2510
+ uint32: [0, 4294967295],
2511
+ float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
2512
+ float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
2513
+ };
2514
+
2515
+ // node_modules/zod/v4/core/errors.js
2516
+ var initializer = (inst, def) => {
2517
+ inst.name = "$ZodError";
2518
+ Object.defineProperty(inst, "_zod", {
2519
+ value: inst._zod,
2520
+ enumerable: false
2521
+ });
2522
+ Object.defineProperty(inst, "issues", {
2523
+ value: def,
2524
+ enumerable: false
2525
+ });
2526
+ inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
2527
+ Object.defineProperty(inst, "toString", {
2528
+ value: () => inst.message,
2529
+ enumerable: false
2530
+ });
2531
+ };
2532
+ var $ZodError = $constructor("$ZodError", initializer);
2533
+ var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
2534
+ function flattenError(error, mapper = (issue) => issue.message) {
2535
+ const fieldErrors = {};
2536
+ const formErrors = [];
2537
+ for (const sub of error.issues) {
2538
+ if (sub.path.length > 0) {
2539
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2540
+ fieldErrors[sub.path[0]].push(mapper(sub));
2541
+ } else {
2542
+ formErrors.push(mapper(sub));
2543
+ }
2544
+ }
2545
+ return { formErrors, fieldErrors };
2546
+ }
2547
+ function formatError(error, mapper = (issue) => issue.message) {
2548
+ const fieldErrors = { _errors: [] };
2549
+ const processError = (error2) => {
2550
+ for (const issue of error2.issues) {
2551
+ if (issue.code === "invalid_union" && issue.errors.length) {
2552
+ issue.errors.map((issues) => processError({ issues }));
2553
+ } else if (issue.code === "invalid_key") {
2554
+ processError({ issues: issue.issues });
2555
+ } else if (issue.code === "invalid_element") {
2556
+ processError({ issues: issue.issues });
2557
+ } else if (issue.path.length === 0) {
2558
+ fieldErrors._errors.push(mapper(issue));
2559
+ } else {
2560
+ let curr = fieldErrors;
2561
+ let i = 0;
2562
+ while (i < issue.path.length) {
2563
+ const el = issue.path[i];
2564
+ const terminal = i === issue.path.length - 1;
2565
+ if (!terminal) {
2566
+ curr[el] = curr[el] || { _errors: [] };
2567
+ } else {
2568
+ curr[el] = curr[el] || { _errors: [] };
2569
+ curr[el]._errors.push(mapper(issue));
2570
+ }
2571
+ curr = curr[el];
2572
+ i++;
2573
+ }
2574
+ }
2575
+ }
2576
+ };
2577
+ processError(error);
2578
+ return fieldErrors;
2579
+ }
2580
+
2581
+ // node_modules/zod/v4/classic/errors.js
2582
+ var initializer2 = (inst, issues) => {
2583
+ $ZodError.init(inst, issues);
2584
+ inst.name = "ZodError";
2585
+ Object.defineProperties(inst, {
2586
+ format: {
2587
+ value: (mapper) => formatError(inst, mapper)
2588
+ },
2589
+ flatten: {
2590
+ value: (mapper) => flattenError(inst, mapper)
2591
+ },
2592
+ addIssue: {
2593
+ value: (issue) => {
2594
+ inst.issues.push(issue);
2595
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2596
+ }
2597
+ },
2598
+ addIssues: {
2599
+ value: (issues2) => {
2600
+ inst.issues.push(...issues2);
2601
+ inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
2602
+ }
2603
+ },
2604
+ isEmpty: {
2605
+ get() {
2606
+ return inst.issues.length === 0;
2607
+ }
2608
+ }
2609
+ });
2610
+ };
2611
+ var ZodError = $constructor("ZodError", initializer2);
2612
+ var ZodRealError = $constructor("ZodError", initializer2, {
2613
+ Parent: Error
2614
+ });
2615
+
2616
+ // lib/utils/is-zod-schema.ts
2617
+ var isZodSchema = (obj) => {
2618
+ return obj && typeof obj === "object" && typeof obj.parse === "function";
2619
+ };
2620
+
2621
+ // lib/http-params.ts
2622
+ var ParamType;
2623
+ ((ParamType2) => {
2624
+ ParamType2["BODY"] = "body";
2625
+ ParamType2["QUERY"] = "query";
2626
+ ParamType2["PARAM"] = "param";
2627
+ ParamType2["HEADER"] = "header";
2628
+ ParamType2["REQUEST"] = "request";
2629
+ ParamType2["FORM_DATA"] = "form-data";
2630
+ })(ParamType ||= {});
2631
+ function setParamMetadata(target, propertyKey, parameterIndex, type, key, options) {
2632
+ const existingParams = Reflect.getOwnMetadata(PARAM_METADATA_KEY, target, propertyKey) || [];
2633
+ existingParams.push({ index: parameterIndex, type, key, options });
2634
+ Reflect.defineMetadata(PARAM_METADATA_KEY, existingParams, target, propertyKey);
2635
+ }
2636
+ function Body() {
2637
+ if (arguments.length === 1) {
2638
+ const arg = arguments[0];
2639
+ if (isZodSchema(arg)) {
2640
+ return function(target, propertyKey, parameterIndex) {
2641
+ setParamMetadata(target, propertyKey, parameterIndex, "body" /* BODY */, undefined, { zodSchema: arg });
2642
+ };
2643
+ }
2644
+ }
2645
+ return function(target, propertyKey, parameterIndex) {
2646
+ setParamMetadata(target, propertyKey, parameterIndex, "body" /* BODY */);
2647
+ };
2648
+ }
2649
+ function Param() {
2650
+ let key;
2651
+ if (arguments.length === 1) {
2652
+ if (isZodSchema(arguments[0])) {
2653
+ return function(target, propertyKey, parameterIndex) {
2654
+ setParamMetadata(target, propertyKey, parameterIndex, "param" /* PARAM */, undefined, {
2655
+ zodSchema: arguments[0]
2656
+ });
2657
+ };
2658
+ }
2659
+ key = arguments[0];
2660
+ }
2661
+ return function(target, propertyKey, parameterIndex) {
2662
+ setParamMetadata(target, propertyKey, parameterIndex, "param" /* PARAM */, key);
2663
+ };
2664
+ }
2665
+ function Query() {
2666
+ let key;
2667
+ if (arguments.length === 1) {
2668
+ if (isZodSchema(arguments[0])) {
2669
+ return function(target, propertyKey, parameterIndex) {
2670
+ setParamMetadata(target, propertyKey, parameterIndex, "query" /* QUERY */, undefined, {
2671
+ zodSchema: arguments[0]
2672
+ });
2673
+ };
2674
+ }
2675
+ key = arguments[0];
2676
+ }
2677
+ return function(target, propertyKey, parameterIndex) {
2678
+ setParamMetadata(target, propertyKey, parameterIndex, "query" /* QUERY */, key);
2679
+ };
2680
+ }
2681
+ function Header(key) {
2682
+ return function(target, propertyKey, parameterIndex) {
2683
+ setParamMetadata(target, propertyKey, parameterIndex, "header" /* HEADER */, key);
2684
+ };
2685
+ }
2686
+ function Request() {
2687
+ return function(target, propertyKey, parameterIndex) {
2688
+ setParamMetadata(target, propertyKey, parameterIndex, "request" /* REQUEST */);
2689
+ };
2690
+ }
2691
+ async function processParameters(request, target, propertyKey) {
2692
+ const paramMetadata = Reflect.getOwnMetadata(PARAM_METADATA_KEY, Object.getPrototypeOf(target), propertyKey) || [];
2693
+ const paramTypes = Reflect.getMetadata("design:paramtypes", target, propertyKey) || [];
2694
+ const args = new Array(paramTypes.length);
2695
+ let cachedFormData = null;
2696
+ for (const metadata of paramMetadata) {
2697
+ const { index, type, key } = metadata;
2698
+ switch (type) {
2699
+ case "body" /* BODY */:
2700
+ try {
2701
+ args[index] = request.body;
2702
+ } catch (e) {
2703
+ args[index] = null;
2704
+ }
2705
+ break;
2706
+ case "query" /* QUERY */:
2707
+ if (key) {
2708
+ args[index] = request.query?.[key];
2709
+ } else {
2710
+ args[index] = request.query;
2711
+ }
2712
+ break;
2713
+ case "param" /* PARAM */:
2714
+ if (key === undefined) {
2715
+ args[index] = request.params;
2716
+ } else {
2717
+ args[index] = request.params?.[key];
2718
+ }
2719
+ break;
2720
+ case "header" /* HEADER */:
2721
+ args[index] = request.headers?.[key];
2722
+ break;
2723
+ case "request" /* REQUEST */:
2724
+ args[index] = request;
2725
+ break;
2726
+ case "form-data" /* FORM_DATA */:
2727
+ cachedFormData = cachedFormData || await readFormData(request);
2728
+ args[index] = extractFormDataPayload(cachedFormData, metadata.options);
2729
+ break;
2730
+ }
2731
+ try {
2732
+ if (metadata.options?.zodSchema) {
2733
+ const zodSchema = metadata.options.zodSchema;
2734
+ if (isZodSchema(zodSchema)) {
2735
+ args[index] = zodSchema.parse(args[index]);
2736
+ }
2737
+ }
2738
+ } catch (e) {
2739
+ if (e instanceof ZodError) {
2740
+ badRequest(e.issues.map((issue) => issue.message).join(", "));
2741
+ }
2742
+ }
2743
+ }
2744
+ return args;
2745
+ }
2746
+ var FORM_DATA_CACHE = Symbol.for("dip:form-data-cache");
2747
+ async function readFormData(request) {
2748
+ if (request?.[FORM_DATA_CACHE]) {
2749
+ return request[FORM_DATA_CACHE];
2750
+ }
2751
+ const existingBody = request?.body;
2752
+ const bodyAsFormData = tryResolveFromBody(existingBody);
2753
+ if (bodyAsFormData) {
2754
+ request[FORM_DATA_CACHE] = bodyAsFormData;
2755
+ return bodyAsFormData;
2756
+ }
2757
+ const requestLike = request?.request || request?.raw || request;
2758
+ if (!requestLike || typeof requestLike.formData !== "function") {
2759
+ throw new Error("FormData is not available on this request.");
2760
+ }
2761
+ let formData;
2762
+ try {
2763
+ formData = typeof requestLike.clone === "function" ? await requestLike.clone().formData() : await requestLike.formData();
2764
+ } catch (err) {
2765
+ const fallback = tryResolveFromBody(existingBody);
2766
+ if (fallback) {
2767
+ request[FORM_DATA_CACHE] = fallback;
2768
+ return fallback;
2769
+ }
2770
+ const reason = err instanceof Error ? err.message : "Body already consumed or unreadable";
2771
+ throw new Error(`Could not read multipart form data from the request. ${reason}`);
2772
+ }
2773
+ if (!(formData instanceof FormData)) {
2774
+ throw new Error("Could not read multipart form data from the request.");
2775
+ }
2776
+ request[FORM_DATA_CACHE] = formData;
2777
+ return formData;
2778
+ }
2779
+ function extractFormDataPayload(formData, options = {}) {
2780
+ const { fileField, allowedTypes, jsonField } = options;
2781
+ const files = [];
2782
+ const allowed = (allowedTypes || []).map((item) => item.toLowerCase());
2783
+ const getFiles = fileField ? formData.getAll(fileField) : Array.from(formData.values());
2784
+ for (const value of getFiles) {
2785
+ if (value instanceof File) {
2786
+ if (allowed.length > 0 && !isAllowedFileType(value, allowed)) {
2787
+ badRequest(`File type for "${value.name}" is not allowed. Allowed: ${allowed.join(", ")}`);
2788
+ }
2789
+ files.push(value);
2790
+ }
2791
+ }
2792
+ let parsedJson;
2793
+ if (jsonField) {
2794
+ const rawJson = formData.get(jsonField);
2795
+ if (typeof rawJson === "string") {
2796
+ try {
2797
+ parsedJson = JSON.parse(rawJson);
2798
+ } catch {
2799
+ badRequest(`Failed to parse JSON field "${jsonField}".`);
2800
+ }
2801
+ } else if (rawJson !== null) {
2802
+ badRequest(`JSON field "${jsonField}" must be a string value.`);
2803
+ }
2804
+ }
2805
+ return {
2806
+ files,
2807
+ json: parsedJson
2808
+ };
2809
+ }
2810
+ function isAllowedFileType(file, allowedTypes) {
2811
+ const mime = file.type?.toLowerCase?.() || "";
2812
+ const extension = file.name.split(".").pop()?.toLowerCase();
2813
+ if (mime && allowedTypes.includes(mime))
2814
+ return true;
2815
+ if (extension && allowedTypes.includes(extension))
2816
+ return true;
2817
+ return allowedTypes.length === 0;
2818
+ }
2819
+ function isFormDataLike(value) {
2820
+ return typeof value === "object" && value !== null && typeof value.get === "function" && typeof value.entries === "function";
2821
+ }
2822
+ function tryResolveFromBody(body) {
2823
+ if (!body)
2824
+ return null;
2825
+ if (isFormDataLike(body))
2826
+ return body;
2827
+ if (typeof body !== "object")
2828
+ return null;
2829
+ const formData = new globalThis.FormData;
2830
+ for (const [key, value] of Object.entries(body)) {
2831
+ if (value === undefined || value === null)
2832
+ continue;
2833
+ if (Array.isArray(value)) {
2834
+ value.forEach((item) => appendValue(formData, key, item));
2835
+ continue;
2836
+ }
2837
+ appendValue(formData, key, value);
2838
+ }
2839
+ return formData;
2840
+ }
2841
+ function appendValue(formData, key, value) {
2842
+ if (value instanceof File || value instanceof Blob) {
2843
+ formData.append(key, value);
2844
+ } else if (typeof value === "object") {
2845
+ formData.append(key, JSON.stringify(value));
2846
+ } else {
2847
+ formData.append(key, String(value));
2848
+ }
2849
+ }
2850
+ function badRequest(message) {
2851
+ throw new Response(JSON.stringify({ error: message }), {
2852
+ status: 400,
2853
+ headers: { "content-type": "application/json" }
2854
+ });
2855
+ }
2856
+
2857
+ // lib/adapters/form-data.ts
2858
+ var import_reflect_metadata3 = __toESM(require_Reflect(), 1);
2859
+ function FormData2(options = {}) {
2860
+ return function(target, propertyKey, parameterIndex) {
2861
+ const existingParams = (propertyKey === undefined ? Reflect.getOwnMetadata(PARAM_METADATA_KEY, target) : Reflect.getOwnMetadata(PARAM_METADATA_KEY, target, propertyKey)) || [];
2862
+ existingParams.push({
2863
+ index: parameterIndex,
2864
+ type: "form-data" /* FORM_DATA */,
2865
+ options
2866
+ });
2867
+ if (propertyKey === undefined) {
2868
+ Reflect.defineMetadata(PARAM_METADATA_KEY, existingParams, target);
2869
+ } else {
2870
+ Reflect.defineMetadata(PARAM_METADATA_KEY, existingParams, target, propertyKey);
2871
+ }
2872
+ };
2873
+ }
2874
+ // lib/adapters/upload-adapter.ts
2875
+ var {s3, S3Client } = globalThis.Bun;
2876
+ var import_reflect_metadata4 = __toESM(require_Reflect(), 1);
2877
+ class UploadAdatper {
2878
+ client;
2879
+ constructor(config) {
2880
+ this.client = config ? new S3Client({
2881
+ endpoint: config.endpoint,
2882
+ bucket: config.bucket,
2883
+ accessKeyId: config.accessKey,
2884
+ secretAccessKey: config.secretKey
2885
+ }) : s3;
2886
+ }
2887
+ async upload(params) {
2888
+ const key = normalizeS3Key(params.path);
2889
+ await this.client.write(key, params.body, {
2890
+ type: params.contentType,
2891
+ acl: params.acl
2892
+ });
2893
+ return toPublicBucketPath(key);
2894
+ }
2895
+ async exists(path) {
2896
+ const key = normalizeS3Key(path);
2897
+ return this.client.exists(key);
2898
+ }
2899
+ async remove(path) {
2900
+ const key = normalizeS3Key(path);
2901
+ await this.client.delete(key);
2902
+ }
2903
+ }
2904
+ UploadAdatper = __legacyDecorateClassTS([
2905
+ Injectable(),
2906
+ __legacyMetadataTS("design:paramtypes", [
2907
+ typeof MinioConfig === "undefined" ? Object : MinioConfig
2908
+ ])
2909
+ ], UploadAdatper);
2910
+ function normalizeS3Key(path) {
2911
+ const normalized = path.replaceAll("\\", "/").replace(/^\/+/, "");
2912
+ if (normalized.length === 0) {
2913
+ throw new Error("S3 object path cannot be empty.");
2914
+ }
2915
+ return normalized.replace(/\/{2,}/g, "/");
2916
+ }
2917
+ function toPublicBucketPath(key) {
2918
+ return `/${normalizeS3Key(key)}`;
2919
+ }
2920
+ // lib/app-startup.ts
2921
+ import { cors } from "@elysiajs/cors";
2922
+ import { html } from "@elysiajs/html";
2923
+ import { staticPlugin } from "@elysiajs/static";
2924
+ import jwt from "@elysiajs/jwt";
2925
+ import { swagger } from "@elysiajs/swagger";
2926
+ import Elysia from "elysia";
2927
+ import React from "react";
2928
+ import { renderToReadableStream } from "react-dom/server";
2929
+
2930
+ // lib/components/layout.tsx
2931
+ import { jsxDEV } from "react/jsx-dev-runtime";
2932
+ var Layout = ({
2933
+ title,
2934
+ children,
2935
+ data,
2936
+ bundle
2937
+ }) => {
2938
+ return /* @__PURE__ */ jsxDEV("html", {
2939
+ lang: "en",
2940
+ children: [
2941
+ /* @__PURE__ */ jsxDEV("head", {
2942
+ children: [
2943
+ /* @__PURE__ */ jsxDEV("meta", {
2944
+ charSet: "UTF-8"
2945
+ }, undefined, false, undefined, this),
2946
+ /* @__PURE__ */ jsxDEV("meta", {
2947
+ name: "viewport",
2948
+ content: "width=device-width, initial-scale=1.0"
2949
+ }, undefined, false, undefined, this),
2950
+ /* @__PURE__ */ jsxDEV("title", {
2951
+ children: title || "Bunstone App"
2952
+ }, undefined, false, undefined, this),
2953
+ /* @__PURE__ */ jsxDEV("meta", {
2954
+ name: "bunstone-version",
2955
+ content: "fix-hydration-v1"
2956
+ }, undefined, false, undefined, this),
2957
+ /* @__PURE__ */ jsxDEV("script", {
2958
+ src: "https://cdn.tailwindcss.com"
2959
+ }, undefined, false, undefined, this),
2960
+ /* @__PURE__ */ jsxDEV("script", {
2961
+ type: "importmap",
2962
+ dangerouslySetInnerHTML: {
2963
+ __html: JSON.stringify({
2964
+ imports: {
2965
+ react: "https://esm.sh/react@19",
2966
+ "react-dom": "https://esm.sh/react-dom@19",
2967
+ "react-dom/client": "https://esm.sh/react-dom@19/client",
2968
+ "react/jsx-runtime": "https://esm.sh/react@19/jsx-runtime",
2969
+ "react/jsx-dev-runtime": "https://esm.sh/react@19/jsx-dev-runtime"
2970
+ }
2971
+ })
2972
+ }
2973
+ }, undefined, false, undefined, this),
2974
+ bundle && /* @__PURE__ */ jsxDEV("script", {
2975
+ type: "module",
2976
+ src: `/public/${bundle}`
2977
+ }, undefined, false, undefined, this)
2978
+ ]
2979
+ }, undefined, true, undefined, this),
2980
+ /* @__PURE__ */ jsxDEV("body", {
2981
+ className: "bg-gray-100 text-gray-900 font-sans",
2982
+ children: [
2983
+ /* @__PURE__ */ jsxDEV("main", {
2984
+ id: "root",
2985
+ className: "container mx-auto p-4",
2986
+ children
2987
+ }, undefined, false, undefined, this),
2988
+ data && /* @__PURE__ */ jsxDEV("script", {
2989
+ id: "__BUNSTONE_DATA__",
2990
+ type: "application/json",
2991
+ dangerouslySetInnerHTML: { __html: JSON.stringify(data) }
2992
+ }, undefined, false, undefined, this)
2993
+ ]
2994
+ }, undefined, true, undefined, this)
2995
+ ]
2996
+ }, undefined, true, undefined, this);
2997
+ };
2998
+
2999
+ // lib/app-startup.ts
3000
+ var import_node_cron = __toESM(require_node_cron(), 1);
3001
+ var import_reflect_metadata12 = __toESM(require_Reflect(), 1);
3002
+ import {
3003
+ readdirSync,
3004
+ existsSync,
3005
+ mkdirSync,
3006
+ writeFileSync,
3007
+ statSync
3008
+ } from "fs";
3009
+ import { join, basename, extname, resolve } from "path";
3010
+
3011
+ // lib/http-exceptions.ts
3012
+ class HttpException extends Error {
3013
+ response;
3014
+ status;
3015
+ constructor(response, status) {
3016
+ super(typeof response === "string" ? response : JSON.stringify(response));
3017
+ this.response = response;
3018
+ this.status = status;
3019
+ Object.setPrototypeOf(this, HttpException.prototype);
3020
+ }
3021
+ getResponse() {
3022
+ return this.response;
3023
+ }
3024
+ getStatus() {
3025
+ return this.status;
3026
+ }
3027
+ }
3028
+
3029
+ class BadRequestException extends HttpException {
3030
+ constructor(response = "Bad Request") {
3031
+ super(response, 400);
3032
+ }
3033
+ }
3034
+
3035
+ class UnauthorizedException extends HttpException {
3036
+ constructor(response = "Unauthorized") {
3037
+ super(response, 401);
3038
+ }
3039
+ }
3040
+
3041
+ class ForbiddenException extends HttpException {
3042
+ constructor(response = "Forbidden") {
3043
+ super(response, 403);
3044
+ }
3045
+ }
3046
+
3047
+ class NotFoundException extends HttpException {
3048
+ constructor(response = "Not Found") {
3049
+ super(response, 404);
3050
+ }
3051
+ }
3052
+
3053
+ class ConflictException extends HttpException {
3054
+ constructor(response = "Conflict") {
3055
+ super(response, 409);
3056
+ }
3057
+ }
3058
+
3059
+ class UnprocessableEntityException extends HttpException {
3060
+ constructor(response = "Unprocessable Entity") {
3061
+ super(response, 422);
3062
+ }
3063
+ }
3064
+
3065
+ class InternalServerErrorException extends HttpException {
3066
+ constructor(response = "Internal Server Error") {
3067
+ super(response, 500);
3068
+ }
3069
+ }
3070
+
3071
+ class OkResponse extends HttpException {
3072
+ constructor(response = "OK") {
3073
+ super(response, 200);
3074
+ }
3075
+ }
3076
+
3077
+ class CreatedResponse extends HttpException {
3078
+ constructor(response = "Created") {
3079
+ super(response, 201);
3080
+ }
3081
+ }
3082
+
3083
+ class NoContentResponse extends HttpException {
3084
+ constructor() {
3085
+ super("", 204);
3086
+ }
3087
+ }
3088
+
3089
+ // lib/cqrs/decorators/command-handler.decorator.ts
3090
+ var import_reflect_metadata5 = __toESM(require_Reflect(), 1);
3091
+ var COMMAND_HANDLER_METADATA = "dip:cqrs:command-handler";
3092
+ var CommandHandler = (command) => {
3093
+ return (target, context) => {
3094
+ Reflect.defineMetadata(COMMAND_HANDLER_METADATA, command, target);
3095
+ };
3096
+ };
3097
+
3098
+ // lib/cqrs/command-bus.ts
3099
+ class CommandBus {
3100
+ handlers = new Map;
3101
+ register(handlers) {
3102
+ handlers.forEach((handler) => {
3103
+ const command = Reflect.getMetadata(COMMAND_HANDLER_METADATA, handler.constructor);
3104
+ if (command) {
3105
+ this.handlers.set(command, handler);
3106
+ }
3107
+ });
3108
+ }
3109
+ async execute(command) {
3110
+ const commandType = command.constructor;
3111
+ const handler = this.handlers.get(commandType);
3112
+ if (!handler) {
3113
+ throw new Error(`No handler found for command: ${commandType.name}`);
3114
+ }
3115
+ return handler.execute(command);
3116
+ }
3117
+ }
3118
+ CommandBus = __legacyDecorateClassTS([
3119
+ Injectable()
3120
+ ], CommandBus);
3121
+
3122
+ // lib/cqrs/decorators/query-handler.decorator.ts
3123
+ var import_reflect_metadata6 = __toESM(require_Reflect(), 1);
3124
+ var QUERY_HANDLER_METADATA = "dip:cqrs:query-handler";
3125
+ var QueryHandler = (query) => {
3126
+ return (target, context) => {
3127
+ Reflect.defineMetadata(QUERY_HANDLER_METADATA, query, target);
3128
+ };
3129
+ };
3130
+
3131
+ // lib/cqrs/query-bus.ts
3132
+ class QueryBus {
3133
+ handlers = new Map;
3134
+ register(handlers) {
3135
+ handlers.forEach((handler) => {
3136
+ const query = Reflect.getMetadata(QUERY_HANDLER_METADATA, handler.constructor);
3137
+ if (query) {
3138
+ this.handlers.set(query, handler);
3139
+ }
3140
+ });
3141
+ }
3142
+ async execute(query) {
3143
+ const queryType = query.constructor;
3144
+ const handler = this.handlers.get(queryType);
3145
+ if (!handler) {
3146
+ throw new Error(`No handler found for query: ${queryType.name}`);
3147
+ }
3148
+ return handler.execute(query);
3149
+ }
3150
+ }
3151
+ QueryBus = __legacyDecorateClassTS([
3152
+ Injectable()
3153
+ ], QueryBus);
3154
+
3155
+ // lib/cqrs/decorators/event-handler.decorator.ts
3156
+ var import_reflect_metadata7 = __toESM(require_Reflect(), 1);
3157
+ var EVENT_HANDLER_METADATA = "dip:cqrs:event-handler";
3158
+ var EventsHandler = (...events) => {
3159
+ return (target, context) => {
3160
+ Reflect.defineMetadata(EVENT_HANDLER_METADATA, events, target);
3161
+ };
3162
+ };
3163
+
3164
+ // lib/cqrs/event-bus.ts
3165
+ class EventStream {
3166
+ source;
3167
+ constructor(source) {
3168
+ this.source = source;
3169
+ }
3170
+ pipe(...operators) {
3171
+ let currentSource = this.source;
3172
+ operators.forEach((operator) => {
3173
+ const prevSource = currentSource;
3174
+ currentSource = (callback) => {
3175
+ prevSource((event) => {
3176
+ operator(event, callback);
3177
+ });
3178
+ };
3179
+ });
3180
+ return new EventStream(currentSource);
3181
+ }
3182
+ subscribe(callback) {
3183
+ this.source(callback);
3184
+ }
3185
+ }
3186
+
3187
+ class EventBus {
3188
+ handlers = new Map;
3189
+ listeners = [];
3190
+ register(handlers) {
3191
+ handlers.forEach((handler) => {
3192
+ const events = Reflect.getMetadata(EVENT_HANDLER_METADATA, handler.constructor);
3193
+ if (Array.isArray(events)) {
3194
+ events.forEach((event) => {
3195
+ if (!this.handlers.has(event)) {
3196
+ this.handlers.set(event, []);
3197
+ }
3198
+ const handlersForEvent = this.handlers.get(event);
3199
+ if (!handlersForEvent.includes(handler)) {
3200
+ handlersForEvent.push(handler);
3201
+ }
3202
+ });
3203
+ }
3204
+ });
3205
+ }
3206
+ publish(event) {
3207
+ const eventType = event.constructor;
3208
+ const handlers = this.handlers.get(eventType) || [];
3209
+ handlers.forEach((handler) => handler.handle(event));
3210
+ this.listeners.forEach((listener) => listener(event));
3211
+ }
3212
+ get stream() {
3213
+ return new EventStream((callback) => {
3214
+ this.listeners.push(callback);
3215
+ });
3216
+ }
3217
+ }
3218
+ EventBus = __legacyDecorateClassTS([
3219
+ Injectable()
3220
+ ], EventBus);
3221
+ var ofType = (...types) => {
3222
+ return (event, next) => {
3223
+ if (types.some((type) => event instanceof type)) {
3224
+ next(event);
3225
+ }
3226
+ };
3227
+ };
3228
+ var map = (fn) => {
3229
+ return (event, next) => {
3230
+ const result = fn(event);
3231
+ if (result) {
3232
+ next(result);
3233
+ }
3234
+ };
3235
+ };
3236
+
3237
+ // lib/cqrs/decorators/saga.decorator.ts
3238
+ var import_reflect_metadata8 = __toESM(require_Reflect(), 1);
3239
+ var SAGA_METADATA = "dip:cqrs:saga";
3240
+ var Saga = () => {
3241
+ return (target, propertyKey, context) => {
3242
+ if (typeof propertyKey === "object" && propertyKey !== null && "kind" in propertyKey) {
3243
+ return;
3244
+ }
3245
+ const properties = Reflect.getMetadata(SAGA_METADATA, target.constructor) || [];
3246
+ Reflect.defineMetadata(SAGA_METADATA, [...properties, propertyKey], target.constructor);
3247
+ };
3248
+ };
3249
+
3250
+ // lib/render.ts
3251
+ var import_reflect_metadata9 = __toESM(require_Reflect(), 1);
3252
+ var RENDER_METADATA = "dip:render:component";
3253
+ function Render(component) {
3254
+ return (target, propertyKey, descriptor) => {
3255
+ Reflect.defineMetadata(RENDER_METADATA, component, target, propertyKey);
3256
+ return descriptor;
3257
+ };
3258
+ }
3259
+
3260
+ // lib/openapi.ts
3261
+ var import_reflect_metadata10 = __toESM(require_Reflect(), 1);
3262
+ var API_TAGS_METADATA = "dip:openapi:tags";
3263
+ var API_OPERATION_METADATA = "dip:openapi:operation";
3264
+ var API_RESPONSE_METADATA = "dip:openapi:responses";
3265
+ var API_HEADERS_METADATA = "dip:openapi:headers";
3266
+ function ApiTags(...tags) {
3267
+ return (target, propertyKey, descriptor) => {
3268
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
3269
+ const context = propertyKey;
3270
+ if (context.kind === "class") {
3271
+ Reflect.defineMetadata(API_TAGS_METADATA, tags, target);
3272
+ } else if (context.kind === "method") {
3273
+ Reflect.defineMetadata(API_TAGS_METADATA, tags, target);
3274
+ }
3275
+ return;
3276
+ }
3277
+ if (propertyKey) {
3278
+ Reflect.defineMetadata(API_TAGS_METADATA, tags, target, propertyKey);
3279
+ } else {
3280
+ Reflect.defineMetadata(API_TAGS_METADATA, tags, target);
3281
+ }
3282
+ };
3283
+ }
3284
+ function ApiOperation(options) {
3285
+ return (target, propertyKey, descriptor) => {
3286
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
3287
+ Reflect.defineMetadata(API_OPERATION_METADATA, options, target);
3288
+ return;
3289
+ }
3290
+ Reflect.defineMetadata(API_OPERATION_METADATA, options, target, propertyKey);
3291
+ };
3292
+ }
3293
+ function ApiResponse(options) {
3294
+ return (target, propertyKey, descriptor) => {
3295
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
3296
+ const responses2 = Reflect.getMetadata(API_RESPONSE_METADATA, target) || [];
3297
+ responses2.push(options);
3298
+ Reflect.defineMetadata(API_RESPONSE_METADATA, responses2, target);
3299
+ return;
3300
+ }
3301
+ const responses = Reflect.getMetadata(API_RESPONSE_METADATA, target, propertyKey) || [];
3302
+ responses.push(options);
3303
+ Reflect.defineMetadata(API_RESPONSE_METADATA, responses, target, propertyKey);
3304
+ };
3305
+ }
3306
+ function ApiHeader(options) {
3307
+ return (target, propertyKey, descriptor) => {
3308
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
3309
+ const context = propertyKey;
3310
+ const headers2 = Reflect.getMetadata(API_HEADERS_METADATA, target) || [];
3311
+ headers2.push(options);
3312
+ Reflect.defineMetadata(API_HEADERS_METADATA, headers2, target);
3313
+ return;
3314
+ }
3315
+ const headers = (propertyKey ? Reflect.getMetadata(API_HEADERS_METADATA, target, propertyKey) : Reflect.getMetadata(API_HEADERS_METADATA, target)) || [];
3316
+ headers.push(options);
3317
+ if (propertyKey) {
3318
+ Reflect.defineMetadata(API_HEADERS_METADATA, headers, target, propertyKey);
3319
+ } else {
3320
+ Reflect.defineMetadata(API_HEADERS_METADATA, headers, target);
3321
+ }
3322
+ };
3323
+ }
3324
+ function ApiHeaders(headers) {
3325
+ return (target, propertyKey) => {
3326
+ headers.forEach((header) => {
3327
+ ApiHeader(header)(target, propertyKey);
3328
+ });
3329
+ };
3330
+ }
3331
+
3332
+ // lib/utils/dependency-injection.ts
3333
+ var import_reflect_metadata11 = __toESM(require_Reflect(), 1);
3334
+
3335
+ class GlobalRegistry {
3336
+ static globalDeps = new Map;
3337
+ static register(type, instance) {
3338
+ this.globalDeps.set(type, instance);
3339
+ }
3340
+ static get(type) {
3341
+ return this.globalDeps.get(type);
3342
+ }
3343
+ static has(type) {
3344
+ return this.globalDeps.has(type);
3345
+ }
3346
+ static getAll() {
3347
+ return this.globalDeps;
3348
+ }
3349
+ }
3350
+ function resolveDependencies(paramTypes, deps) {
3351
+ return paramTypes.map((paramType) => {
3352
+ return resolveType(paramType, deps);
3353
+ });
3354
+ }
3355
+ function resolveType(type, deps) {
3356
+ if (!type) {
3357
+ throw new Error("Cannot resolve dependency: type is undefined. This often happens due to circular dependencies or using 'import type' for a class that needs to be injected.");
3358
+ }
3359
+ if (type === Object) {
3360
+ throw new Error("Cannot resolve dependency: type is 'Object'. This usually happens when 'emitDecoratorMetadata' is enabled but the class is imported as a type or there is a circular dependency.");
3361
+ }
3362
+ if (deps.has(type)) {
3363
+ return deps.get(type);
3364
+ }
3365
+ if (GlobalRegistry.has(type)) {
3366
+ return GlobalRegistry.get(type);
3367
+ }
3368
+ if (typeof type === "function" && type.name) {
3369
+ for (const [key, value] of deps.entries()) {
3370
+ if (typeof key === "function" && key.name === type.name) {
3371
+ return value;
3372
+ }
3373
+ }
3374
+ for (const [key, value] of GlobalRegistry.getAll().entries()) {
3375
+ if (typeof key === "function" && key.name === type.name) {
3376
+ return value;
3377
+ }
3378
+ }
3379
+ }
3380
+ const isInjectable = Reflect.getMetadata("injectable", type);
3381
+ if (!isInjectable) {}
3382
+ const paramTypes = Reflect.getMetadata("design:paramtypes", type) || [];
3383
+ const childrenDep = resolveDependencies(paramTypes, deps);
3384
+ const instance = new type(...childrenDep);
3385
+ deps.set(type, instance);
3386
+ return instance;
3387
+ }
3388
+
3389
+ // lib/utils/colors.ts
3390
+ var colors = {
3391
+ red: "\x1B[31m",
3392
+ green: "\x1B[32m",
3393
+ blue: "\x1B[34m",
3394
+ purple: "\x1B[35m",
3395
+ reset: "\x1B[0m",
3396
+ yellow: "\x1B[33m",
3397
+ cyan: "\x1B[36m",
3398
+ magenta: "\x1B[35m",
3399
+ gray: "\x1B[90m",
3400
+ white: "\x1B[37m",
3401
+ brightRed: "\x1B[91m",
3402
+ brightGreen: "\x1B[92m",
3403
+ brightYellow: "\x1B[93m",
3404
+ brightBlue: "\x1B[94m",
3405
+ brightMagenta: "\x1B[95m",
3406
+ brightCyan: "\x1B[96m",
3407
+ brightWhite: "\x1B[97m",
3408
+ bgRed: "\x1B[41m",
3409
+ bgGreen: "\x1B[42m",
3410
+ bgYellow: "\x1B[43m",
3411
+ bgBlue: "\x1B[44m",
3412
+ bgMagenta: "\x1B[45m",
3413
+ bgCyan: "\x1B[46m",
3414
+ bgWhite: "\x1B[47m",
3415
+ bold: "\x1B[1m",
3416
+ dim: "\x1B[2m",
3417
+ italic: "\x1B[3m",
3418
+ underline: "\x1B[4m",
3419
+ blink: "\x1B[5m",
3420
+ reverse: "\x1B[7m",
3421
+ hidden: "\x1B[8m",
3422
+ strikethrough: "\x1B[9m"
3423
+ };
3424
+
3425
+ // lib/utils/logger.ts
3426
+ var LogLevel;
3427
+ ((LogLevel2) => {
3428
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
3429
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
3430
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
3431
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
3432
+ LogLevel2[LogLevel2["FATAL"] = 4] = "FATAL";
3433
+ })(LogLevel ||= {});
3434
+
3435
+ class Logger {
3436
+ name;
3437
+ level;
3438
+ showTimestamp;
3439
+ pretty;
3440
+ constructor(name, options = {}) {
3441
+ this.name = name;
3442
+ this.level = options.level ?? 1 /* INFO */;
3443
+ this.showTimestamp = options.timestamp ?? true;
3444
+ this.pretty = options.pretty ?? true;
3445
+ }
3446
+ getTimestamp() {
3447
+ const now = new Date;
3448
+ return now.toISOString();
3449
+ }
3450
+ formatMessage(level, color, ...args) {
3451
+ if (!this.pretty) {
3452
+ console.log(JSON.stringify({
3453
+ timestamp: this.getTimestamp(),
3454
+ level,
3455
+ name: this.name,
3456
+ message: args.map((a) => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")
3457
+ }));
3458
+ return;
3459
+ }
3460
+ let message = "";
3461
+ if (this.showTimestamp) {
3462
+ message += `${colors.gray}${this.getTimestamp()}${colors.reset} `;
3463
+ }
3464
+ message += `${color}[${level}]${colors.reset} `;
3465
+ message += `${colors.cyan}[${this.name}]${colors.reset} `;
3466
+ console.log(message, ...args);
3467
+ }
3468
+ shouldLog(level) {
3469
+ return level >= this.level;
3470
+ }
3471
+ debug(...args) {
3472
+ if (this.shouldLog(0 /* DEBUG */)) {
3473
+ this.formatMessage("DEBUG", colors.blue, ...args);
3474
+ }
3475
+ }
3476
+ info(...args) {
3477
+ if (this.shouldLog(1 /* INFO */)) {
3478
+ this.formatMessage("INFO", colors.green, ...args);
3479
+ }
3480
+ }
3481
+ log(...args) {
3482
+ this.info(...args);
3483
+ }
3484
+ warn(...args) {
3485
+ if (this.shouldLog(2 /* WARN */)) {
3486
+ this.formatMessage("WARN", colors.yellow, ...args);
3487
+ }
3488
+ }
3489
+ error(...args) {
3490
+ if (this.shouldLog(3 /* ERROR */)) {
3491
+ this.formatMessage("ERROR", colors.red, ...args);
3492
+ }
3493
+ }
3494
+ fatal(...args) {
3495
+ if (this.shouldLog(4 /* FATAL */)) {
3496
+ this.formatMessage("FATAL", colors.magenta, ...args);
3497
+ }
3498
+ }
3499
+ child(childName) {
3500
+ return new Logger(`${this.name}:${childName}`, {
3501
+ level: this.level,
3502
+ timestamp: this.showTimestamp,
3503
+ pretty: this.pretty
3504
+ });
3505
+ }
3506
+ setLevel(level) {
3507
+ this.level = level;
3508
+ }
3509
+ group(label, callback) {
3510
+ console.group(`${colors.cyan}${label}${colors.reset}`);
3511
+ callback();
3512
+ console.groupEnd();
3513
+ }
3514
+ async time(label, callback) {
3515
+ const start = performance.now();
3516
+ this.debug(`\u23F1\uFE0F Starting: ${label}`);
3517
+ try {
3518
+ const result = await callback();
3519
+ const duration = (performance.now() - start).toFixed(2);
3520
+ this.debug(`\u2705 Completed: ${label} (${duration}ms)`);
3521
+ return result;
3522
+ } catch (error) {
3523
+ const duration = (performance.now() - start).toFixed(2);
3524
+ this.error(`\u274C Failed: ${label} (${duration}ms)`, error);
3525
+ throw error;
3526
+ }
3527
+ }
3528
+ }
3529
+
3530
+ // lib/app-startup.ts
3531
+ console.log("APP STARTUP LOADED FROM:", import.meta.url);
3532
+
3533
+ class AppStartup {
3534
+ static elysia = new Elysia;
3535
+ static logger = new Logger(AppStartup.name);
3536
+ static registeredSagas = new WeakSet;
3537
+ static viewBundles = new Map;
3538
+ static create(module, options) {
3539
+ this.elysia = new Elysia;
3540
+ if (!existsSync("./public"))
3541
+ mkdirSync("./public", { recursive: true });
3542
+ this.elysia.use(html());
3543
+ this.elysia.use(staticPlugin({
3544
+ assets: "public",
3545
+ prefix: "/public"
3546
+ }));
3547
+ if (options?.viewsDir) {
3548
+ this.autoBundle(options.viewsDir).catch((err) => {
3549
+ this.logger.error(`Failed to auto-bundle views: ${err.message}`);
3550
+ });
3551
+ }
3552
+ this.elysia.error({
3553
+ HttpException
3554
+ });
3555
+ this.elysia.onError(({ code, error, set }) => {
3556
+ if (error instanceof HttpException) {
3557
+ set.status = error.getStatus();
3558
+ return error.getResponse();
3559
+ }
3560
+ return error;
3561
+ });
3562
+ if (options?.cors) {
3563
+ AppStartup.elysia.use(cors(options.cors));
3564
+ }
3565
+ if (options?.swagger) {
3566
+ AppStartup.elysia.use(swagger({
3567
+ path: options.swagger.path || "/swagger",
3568
+ documentation: options.swagger.documentation
3569
+ }));
3570
+ }
3571
+ AppStartup.registerModules(module);
3572
+ return {
3573
+ listen: this.listen,
3574
+ getElysia: () => this.elysia
3575
+ };
3576
+ }
3577
+ static async bundle(entryPath, outputName) {
3578
+ try {
3579
+ const result = await Bun.build({
3580
+ entrypoints: [entryPath],
3581
+ outdir: "./public",
3582
+ naming: outputName,
3583
+ minify: true,
3584
+ external: [
3585
+ "react",
3586
+ "react-dom",
3587
+ "react-dom/client",
3588
+ "react/jsx-runtime",
3589
+ "react/jsx-dev-runtime"
3590
+ ]
3591
+ });
3592
+ if (!result.success) {
3593
+ this.logger.error(`Bundle failed for ${outputName}: ${result.logs.map((l) => l.message).join(`
3594
+ `)}`);
3595
+ } else {
3596
+ this.logger.log(`Bundle created successfully: public/${outputName}`);
3597
+ }
3598
+ } catch (error) {
3599
+ this.logger.error(`Error during bundling ${outputName}: ${error.message}`);
3600
+ }
3601
+ }
3602
+ static async autoBundle(viewsDir) {
3603
+ if (!existsSync(viewsDir))
3604
+ return;
3605
+ if (!existsSync("./.bunstone"))
3606
+ mkdirSync("./.bunstone", { recursive: true });
3607
+ const getFilesRecursively = (dir) => {
3608
+ let results = [];
3609
+ const list = readdirSync(dir);
3610
+ for (const file of list) {
3611
+ const fullPath = join(dir, file);
3612
+ const stat = statSync(fullPath);
3613
+ if (stat && stat.isDirectory()) {
3614
+ results = results.concat(getFilesRecursively(fullPath));
3615
+ } else {
3616
+ results.push(resolve(fullPath));
3617
+ }
3618
+ }
3619
+ return results;
3620
+ };
3621
+ const viewsDirAbs = resolve(viewsDir);
3622
+ const files = getFilesRecursively(viewsDirAbs);
3623
+ this.logger.log(`Auto-bundling views from ${viewsDirAbs} (${files.length} views found)`);
3624
+ for (const absolutePath of files) {
3625
+ const file = basename(absolutePath);
3626
+ if (file.endsWith(".tsx") || file.endsWith(".jsx")) {
3627
+ const componentName = basename(file, extname(file));
3628
+ const entryPath = join(process.cwd(), ".bunstone", `${componentName}.client.tsx`);
3629
+ const entryContent = `
3630
+ import React from 'react';
3631
+ import { hydrateRoot } from 'react-dom/client';
3632
+ import * as Mod from '${absolutePath}';
3633
+
3634
+ const Component = Mod['${componentName}'] || Mod.default;
3635
+
3636
+ const dataElement = document.getElementById("__BUNSTONE_DATA__");
3637
+ const data = dataElement ? JSON.parse(dataElement.textContent || "{}") : {};
3638
+
3639
+ if (typeof document !== 'undefined' && Component) {
3640
+ const root = document.getElementById("root");
3641
+ if (root) {
3642
+ try {
3643
+ hydrateRoot(root, React.createElement(Component, data));
3644
+ console.log('[Bunstone] Hydration successful for component: ${componentName}');
3645
+ } catch (e) {
3646
+ console.error('[Bunstone] Hydration failed for component: ${componentName}', e);
3647
+ }
3648
+ } else {
3649
+ console.error('[Bunstone] Root element "root" not found for hydration.');
3650
+ }
3651
+ } else {
3652
+ console.error('[Bunstone] Component ${componentName} not found in bundle.');
3653
+ }
3654
+ `;
3655
+ writeFileSync(entryPath, entryContent);
3656
+ const bundleName = `${componentName.toLowerCase()}.bundle.js`;
3657
+ await this.bundle(entryPath, bundleName);
3658
+ this.viewBundles.set(componentName, bundleName);
3659
+ this.viewBundles.set(componentName.toLowerCase(), bundleName);
3660
+ }
3661
+ }
3662
+ }
3663
+ static listen(port) {
3664
+ AppStartup.logger.log(`App is running at http://localhost:${port}`);
3665
+ AppStartup.elysia.listen(port);
3666
+ }
3667
+ static async executeControllerMethod(context, controller, method) {
3668
+ const args = await processParameters(context, controller, method);
3669
+ const result = await controller[method](...args);
3670
+ const component = Reflect.getMetadata(RENDER_METADATA, controller, method);
3671
+ if (component) {
3672
+ context.set.headers["Content-Type"] = "text/html; charset=utf8";
3673
+ const componentName = component.name || component.displayName;
3674
+ const bundle = result?.bundle || this.viewBundles.get(componentName) || this.viewBundles.get(componentName.toLowerCase());
3675
+ this.logger.log(`Rendering component: ${componentName}, bundle found: ${bundle || "none"}`);
3676
+ if (!bundle) {
3677
+ this.logger.warn(`No client bundle found for component: ${componentName}. useEffect and other hooks will not work on the client.`);
3678
+ }
3679
+ const title = result?.title || "Bunstone App";
3680
+ const stream = await renderToReadableStream(React.createElement(Layout, { title, data: result, bundle }, React.createElement(component, result)));
3681
+ return new Response(stream, {
3682
+ headers: { "Content-Type": "text/html; charset=utf8" }
3683
+ });
3684
+ }
3685
+ if (React.isValidElement(result)) {
3686
+ const stream = await renderToReadableStream(result);
3687
+ return new Response(stream, {
3688
+ headers: { "Content-Type": "text/html; charset=utf8" }
3689
+ });
3690
+ }
3691
+ return result;
3692
+ }
3693
+ static registerModules(module) {
3694
+ const isGlobal = Reflect.getMetadata("dip:module:global", module);
3695
+ if (isGlobal) {
3696
+ const injectables = Reflect.getMetadata("dip:injectables", module);
3697
+ if (injectables) {
3698
+ for (const [key, value] of injectables.entries()) {
3699
+ GlobalRegistry.register(key, value);
3700
+ }
3701
+ }
3702
+ }
3703
+ AppStartup.startWithJWT(module);
3704
+ AppStartup.registerRoutes(module);
3705
+ AppStartup.registerTimeouts(module);
3706
+ AppStartup.registerCronJobs(module);
3707
+ AppStartup.registerCqrsHandlers(module);
3708
+ const modules = Reflect.getMetadata("dip:modules", module) || [];
3709
+ for (const mod of modules) {
3710
+ AppStartup.registerModules(mod);
3711
+ }
3712
+ }
3713
+ static registerRoutes(module) {
3714
+ const controllers = Reflect.getMetadata("dip:module:routes", module);
3715
+ if (!controllers) {
3716
+ return;
3717
+ }
3718
+ const injectables = Reflect.getMetadata("dip:injectables", module);
3719
+ for (const item of controllers.entries()) {
3720
+ const [controllerInstance, methods] = item;
3721
+ const paramsTypes = Reflect.getMetadata("design:paramtypes", controllerInstance) || [];
3722
+ const dependencies = resolveDependencies(paramsTypes, injectables);
3723
+ let controller = new controllerInstance(...dependencies);
3724
+ controller = Object.assign(controller, AppStartup.getControllerHandler(module, controllerInstance));
3725
+ for (const method of methods) {
3726
+ AppStartup.logger.log(`Registering ${method.httpMethod} route: ${method.pathname}`);
3727
+ const httpMethod = method.httpMethod.toLowerCase();
3728
+ if (!(httpMethod in AppStartup.elysia)) {
3729
+ throw new Error(`HTTP method ${method.httpMethod} is not supported.`);
3730
+ }
3731
+ const controllerTags = Reflect.getMetadata(API_TAGS_METADATA, controllerInstance) || [];
3732
+ const methodTags = Reflect.getMetadata(API_TAGS_METADATA, controllerInstance.prototype, method.methodName) || [];
3733
+ const operation = Reflect.getMetadata(API_OPERATION_METADATA, controllerInstance.prototype, method.methodName);
3734
+ const responsesMetadata = Reflect.getMetadata(API_RESPONSE_METADATA, controllerInstance.prototype, method.methodName) || [];
3735
+ const tags = [...new Set([...controllerTags, ...methodTags])];
3736
+ const responses = {};
3737
+ responsesMetadata.forEach((res) => {
3738
+ responses[res.status.toString()] = {
3739
+ description: res.description,
3740
+ content: res.type ? {
3741
+ "application/json": {
3742
+ schema: res.type
3743
+ }
3744
+ } : undefined
3745
+ };
3746
+ });
3747
+ const controllerHeaders = Reflect.getMetadata(API_HEADERS_METADATA, controllerInstance) || [];
3748
+ const methodHeaders = Reflect.getMetadata(API_HEADERS_METADATA, controllerInstance.prototype, method.methodName) || [];
3749
+ const allHeaders = [...controllerHeaders, ...methodHeaders];
3750
+ const parameters = allHeaders.map((h) => ({
3751
+ name: h.name,
3752
+ in: "header",
3753
+ description: h.description,
3754
+ required: h.required,
3755
+ schema: h.schema || { type: "string" }
3756
+ }));
3757
+ const paramsMetadata = Reflect.getMetadata(PARAM_METADATA_KEY, controllerInstance.prototype, method.methodName) || [];
3758
+ const bodySchema = paramsMetadata.find((p) => p.type === "body" /* BODY */)?.options?.zodSchema;
3759
+ const querySchema = paramsMetadata.find((p) => p.type === "query" /* QUERY */)?.options?.zodSchema;
3760
+ const paramsSchema = paramsMetadata.find((p) => p.type === "param" /* PARAM */)?.options?.zodSchema;
3761
+ AppStartup.elysia[httpMethod](method.pathname, (req) => AppStartup.executeControllerMethod(req, controller, method.methodName), {
3762
+ body: bodySchema,
3763
+ query: querySchema,
3764
+ params: paramsSchema,
3765
+ detail: {
3766
+ tags,
3767
+ summary: operation?.summary,
3768
+ description: operation?.description,
3769
+ responses,
3770
+ parameters
3771
+ },
3772
+ beforeHandle(req) {
3773
+ if (!method.guard)
3774
+ return;
3775
+ const guardInstance = new method.guard;
3776
+ const isValid = guardInstance.validate(req);
3777
+ if (isValid instanceof Promise) {
3778
+ return isValid.then((valid) => {
3779
+ if (!valid) {
3780
+ throw new Error("Unauthorized");
3781
+ }
3782
+ });
3783
+ } else {
3784
+ if (!isValid) {
3785
+ throw new Error("Unauthorized");
3786
+ }
3787
+ }
3788
+ }
3789
+ });
3790
+ }
3791
+ }
3792
+ }
3793
+ static registerTimeouts(module) {
3794
+ const providersTimeouts = Reflect.getMetadata("dip:timeouts", module);
3795
+ if (!providersTimeouts) {
3796
+ return;
3797
+ }
3798
+ for (const item of providersTimeouts.entries()) {
3799
+ const [providerInstance, timeouts] = item;
3800
+ const provider = new providerInstance;
3801
+ for (const timeout of timeouts) {
3802
+ AppStartup.logger.log(`Scheduling timeout for method: ${timeout.methodName} with delay: ${timeout.delay}ms`);
3803
+ setTimeout(() => {
3804
+ provider[timeout.methodName]();
3805
+ }, timeout.delay);
3806
+ }
3807
+ }
3808
+ }
3809
+ static registerCronJobs(module) {
3810
+ const providersCron = Reflect.getMetadata("dip:crons", module);
3811
+ if (!providersCron) {
3812
+ return;
3813
+ }
3814
+ for (const item of providersCron.entries()) {
3815
+ const [providerInstance, crons] = item;
3816
+ const provider = new providerInstance;
3817
+ for (const cron of crons) {
3818
+ AppStartup.logger.log(`Scheduling cron for method: ${cron.methodName}`);
3819
+ import_node_cron.default.schedule(cron.expression, () => {
3820
+ provider[cron.methodName]();
3821
+ });
3822
+ }
3823
+ }
3824
+ }
3825
+ static registerCqrsHandlers(module) {
3826
+ const injectables = Reflect.getMetadata("dip:injectables", module);
3827
+ if (!injectables)
3828
+ return;
3829
+ const commandBus = injectables.get(CommandBus);
3830
+ const queryBus = injectables.get(QueryBus);
3831
+ const eventBus = injectables.get(EventBus);
3832
+ const commandHandlers = [];
3833
+ const queryHandlers = [];
3834
+ const eventHandlers = [];
3835
+ const sagas = [];
3836
+ for (const instance of injectables.values()) {
3837
+ if (Reflect.hasMetadata(COMMAND_HANDLER_METADATA, instance.constructor)) {
3838
+ commandHandlers.push(instance);
3839
+ }
3840
+ if (Reflect.hasMetadata(QUERY_HANDLER_METADATA, instance.constructor)) {
3841
+ queryHandlers.push(instance);
3842
+ }
3843
+ if (Reflect.hasMetadata(EVENT_HANDLER_METADATA, instance.constructor)) {
3844
+ eventHandlers.push(instance);
3845
+ }
3846
+ if (Reflect.hasMetadata(SAGA_METADATA, instance.constructor)) {
3847
+ sagas.push(instance);
3848
+ }
3849
+ }
3850
+ if (commandBus && commandHandlers.length > 0) {
3851
+ commandBus.register(commandHandlers);
3852
+ }
3853
+ if (queryBus && queryHandlers.length > 0) {
3854
+ queryBus.register(queryHandlers);
3855
+ }
3856
+ if (eventBus && eventHandlers.length > 0) {
3857
+ eventBus.register(eventHandlers);
3858
+ }
3859
+ if (eventBus && commandBus && sagas.length > 0) {
3860
+ sagas.forEach((sagaInstance) => {
3861
+ if (AppStartup.registeredSagas.has(sagaInstance)) {
3862
+ return;
3863
+ }
3864
+ AppStartup.registeredSagas.add(sagaInstance);
3865
+ const sagaMethods = Reflect.getMetadata(SAGA_METADATA, sagaInstance.constructor);
3866
+ sagaMethods.forEach((methodName) => {
3867
+ const sagaFn = sagaInstance[methodName];
3868
+ if (typeof sagaFn === "function") {
3869
+ const stream = sagaFn.call(sagaInstance, eventBus.stream);
3870
+ if (stream && typeof stream.subscribe === "function") {
3871
+ stream.subscribe((command) => {
3872
+ if (command) {
3873
+ commandBus.execute(command).catch((err) => {
3874
+ AppStartup.logger.error(`Error executing command from Saga ${sagaInstance.constructor.name}.${methodName}:`, err);
3875
+ });
3876
+ }
3877
+ });
3878
+ }
3879
+ }
3880
+ });
3881
+ });
3882
+ }
3883
+ }
3884
+ static startWithJWT(module) {
3885
+ const modules = Reflect.getMetadata("dip:modules", module) || [];
3886
+ for (const mod of modules) {
3887
+ const hasJWT = Reflect.getMetadata("dip:module:jwt", mod);
3888
+ if (hasJWT) {
3889
+ const jwtOptions = Reflect.getMetadata("dip:module:jwt:options", mod);
3890
+ AppStartup.elysia.use(jwt(jwtOptions));
3891
+ }
3892
+ }
3893
+ }
3894
+ static getControllerHandler(module, controller) {
3895
+ const injectables = Reflect.getMetadata("dip:injectables", module);
3896
+ if (!injectables) {
3897
+ return [];
3898
+ }
3899
+ return injectables.get(controller);
3900
+ }
3901
+ }
3902
+ // lib/controller.ts
3903
+ var import_reflect_metadata13 = __toESM(require_Reflect(), 1);
3904
+ function Controller(pathname = "/") {
3905
+ if (!pathname.startsWith("/")) {
3906
+ pathname = `/${pathname}`;
3907
+ }
3908
+ return function(target) {
3909
+ Injectable()(target);
3910
+ const controllerMethods = Object.getOwnPropertyNames(target.prototype).filter((method) => method !== "constructor");
3911
+ const controllerHttpMethods = Symbol.for("dip:controller:http-methods");
3912
+ for (const controllerMethod of controllerMethods) {
3913
+ if (!target[controllerHttpMethods] || target[controllerHttpMethods].length === 0) {
3914
+ target[controllerHttpMethods] = [];
3915
+ }
3916
+ const metadata = Reflect.getMetadata("dip:http-method", target.prototype[controllerMethod]);
3917
+ if (metadata) {
3918
+ const [httpMethod, pathname2] = metadata.split(" ");
3919
+ target[controllerHttpMethods].push({
3920
+ httpMethod,
3921
+ pathname: pathname2,
3922
+ methodName: controllerMethod
3923
+ });
3924
+ }
3925
+ }
3926
+ Reflect.defineMetadata("dip:controller", "is_controller", target);
3927
+ Reflect.defineMetadata("dip:controller:pathname", pathname, target);
3928
+ };
3929
+ }
3930
+ // lib/module.ts
3931
+ var import_reflect_metadata15 = __toESM(require_Reflect(), 1);
3932
+
3933
+ // lib/utils/map-providers.ts
3934
+ function mapProvidersWithType(providers = [], type) {
3935
+ const result = new Map;
3936
+ for (const provider of providers) {
3937
+ for (const providerSymbol of Object.getOwnPropertySymbols(provider.prototype)) {
3938
+ const methods = provider.prototype[providerSymbol];
3939
+ for (const method of methods) {
3940
+ if (method.type === type) {
3941
+ if (!result.has(provider)) {
3942
+ result.set(provider, []);
3943
+ }
3944
+ result.get(provider)?.push({
3945
+ expression: method.expression,
3946
+ delay: method.delay,
3947
+ methodName: method.methodName
3948
+ });
3949
+ }
3950
+ }
3951
+ }
3952
+ }
3953
+ return result;
3954
+ }
3955
+
3956
+ // lib/schedule/cron/mappers/map-providers-with-cron.ts
3957
+ class MapProvidersWithCron {
3958
+ static execute(providers = []) {
3959
+ return mapProvidersWithType(providers, "cron");
3960
+ }
3961
+ }
3962
+
3963
+ // lib/schedule/timeout/mappers/map-providers-with-timeouts.ts
3964
+ var import_reflect_metadata14 = __toESM(require_Reflect(), 1);
3965
+ class MapProvidersWithTimeout {
3966
+ static execute(providers = []) {
3967
+ return mapProvidersWithType(providers, "timeout");
3968
+ }
3969
+ }
3970
+
3971
+ // lib/module.ts
3972
+ function Module(moduleConfig = {}) {
3973
+ moduleConfig.controllers = moduleConfig.controllers || [];
3974
+ moduleConfig.providers = moduleConfig.providers || [];
3975
+ moduleConfig.imports = moduleConfig.imports || [];
3976
+ moduleConfig.exports = moduleConfig.exports || [];
3977
+ const modules = moduleConfig.imports;
3978
+ const controllers = mapControllers(moduleConfig.controllers);
3979
+ const providersTimeouts = MapProvidersWithTimeout.execute(moduleConfig.providers);
3980
+ const providersCrons = MapProvidersWithCron.execute(moduleConfig.providers);
3981
+ const injectableProviders = mapInjectableProviders(moduleConfig);
3982
+ return function(target, context) {
3983
+ Reflect.defineMetadata("dip:module", "is_module", target);
3984
+ Reflect.defineMetadata("dip:module:global", !!moduleConfig.global, target);
3985
+ Reflect.defineMetadata("dip:module:routes", controllers, target);
3986
+ Reflect.defineMetadata("dip:timeouts", providersTimeouts, target);
3987
+ Reflect.defineMetadata("dip:modules", modules, target);
3988
+ Reflect.defineMetadata("dip:crons", providersCrons, target);
3989
+ Reflect.defineMetadata("dip:injectables", injectableProviders, target);
3990
+ };
3991
+ }
3992
+ function mapControllers(controllers = []) {
3993
+ const controllersMap = new Map;
3994
+ for (const controller of controllers) {
3995
+ controllersMap.set(controller, []);
3996
+ for (const controllerSymbol of Object.getOwnPropertySymbols(controller)) {
3997
+ const controllerPathname = Reflect.getOwnMetadata("dip:controller:pathname", controller);
3998
+ const controllerGuard = Reflect.getMetadata("dip:guard", controller);
3999
+ const controllerMethods = controller[controllerSymbol];
4000
+ controllerMethods.forEach((cm) => {
4001
+ const pathname = `${controllerPathname === "/" ? "" : controllerPathname}${cm.pathname}`;
4002
+ const methodGuard = Reflect.getMetadata("dip:guard", controller.prototype, cm.methodName);
4003
+ controllersMap.get(controller)?.push({
4004
+ httpMethod: cm.httpMethod,
4005
+ pathname,
4006
+ methodName: cm.methodName,
4007
+ guard: methodGuard || controllerGuard
4008
+ });
4009
+ });
4010
+ }
4011
+ }
4012
+ return controllersMap;
4013
+ }
4014
+ function mapInjectableProviders(moduleConfig) {
4015
+ const deps = new Map;
4016
+ (moduleConfig.imports || []).forEach((mod) => {
4017
+ const importedInjectables = Reflect.getMetadata("dip:injectables", mod);
4018
+ if (importedInjectables instanceof Map) {
4019
+ for (const [key, value] of importedInjectables.entries()) {
4020
+ deps.set(key, value);
4021
+ }
4022
+ }
4023
+ });
4024
+ (moduleConfig.providers || []).forEach((provider) => {
4025
+ resolveType(provider, deps);
4026
+ });
4027
+ return deps;
4028
+ }
4029
+
4030
+ // lib/cqrs/cqrs-module.ts
4031
+ class CqrsModule {
4032
+ }
4033
+ CqrsModule = __legacyDecorateClassTS([
4034
+ Module({
4035
+ providers: [CommandBus, QueryBus, EventBus],
4036
+ exports: [CommandBus, QueryBus, EventBus],
4037
+ global: true
4038
+ })
4039
+ ], CqrsModule);
4040
+ // lib/database/sql-module.ts
4041
+ var {SQL } = globalThis.Bun;
4042
+ class SqlService {
4043
+ async query(query, params) {
4044
+ const sql = this.getSqlInstance();
4045
+ return await sql.unsafe(query, params);
4046
+ }
4047
+ async transaction(queries) {
4048
+ const sql = this.getSqlInstance();
4049
+ await sql.begin(async (trx) => {
4050
+ for (const { query, params } of queries) {
4051
+ await trx.unsafe(query, params);
4052
+ }
4053
+ });
4054
+ }
4055
+ async bulkInsert(table, values) {
4056
+ const sql = this.getSqlInstance();
4057
+ await sql`INSERT INTO ${sql(table)} ${sql(values)}`;
4058
+ }
4059
+ getSqlInstance() {
4060
+ const sql = SqlModule.getSqlInstance();
4061
+ if (!sql) {
4062
+ throw new Error("SQL instance not initialized. Call SqlModule.register() first.");
4063
+ }
4064
+ return sql;
4065
+ }
4066
+ }
4067
+ SqlService = __legacyDecorateClassTS([
4068
+ Injectable()
4069
+ ], SqlService);
4070
+
4071
+ class SqlModule {
4072
+ static sqlInstance;
4073
+ static register(connection) {
4074
+ this.sqlInstance = new SQL({
4075
+ url: typeof connection === "string" ? connection : `${connection.provider}://${connection.username}:${connection.password}@${connection.host}:${connection.port}/${connection.database}`
4076
+ });
4077
+ return this;
4078
+ }
4079
+ static getSqlInstance() {
4080
+ return this.sqlInstance;
4081
+ }
4082
+ }
4083
+ SqlModule = __legacyDecorateClassTS([
4084
+ Module({
4085
+ providers: [SqlService],
4086
+ global: true
4087
+ })
4088
+ ], SqlModule);
4089
+ // lib/guard.ts
4090
+ var import_reflect_metadata16 = __toESM(require_Reflect(), 1);
4091
+
4092
+ // lib/utils/is-class.ts
4093
+ function isClass(fn) {
4094
+ return typeof fn === "function" && Object.getOwnPropertyDescriptor(fn, "prototype")?.writable === false;
4095
+ }
4096
+
4097
+ // lib/guard.ts
4098
+ function Guard(guard) {
4099
+ return function(target, propertyKey, descriptor) {
4100
+ if (!("validate" in guard.prototype)) {
4101
+ throw new Error(`Guard class must implement 'validate' method.`);
4102
+ }
4103
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
4104
+ const context = propertyKey;
4105
+ if (context.kind === "class") {
4106
+ Reflect.defineMetadata("dip:guard", guard, target);
4107
+ } else if (context.kind === "method") {
4108
+ Reflect.defineMetadata("dip:guard", guard, target);
4109
+ }
4110
+ return;
4111
+ }
4112
+ if (isClass(target)) {
4113
+ Reflect.defineMetadata("dip:guard", guard, target);
4114
+ }
4115
+ if (propertyKey && descriptor) {
4116
+ Reflect.defineMetadata("dip:guard", guard, target, propertyKey);
4117
+ }
4118
+ };
4119
+ }
4120
+ // lib/http-methods.ts
4121
+ var import_reflect_metadata17 = __toESM(require_Reflect(), 1);
4122
+ function HttpMethodDecorator(httpMethod, pathname = "") {
4123
+ if (!pathname.startsWith("/")) {
4124
+ pathname = `/${pathname}`;
4125
+ }
4126
+ return function(target, propertyKey, descriptor) {
4127
+ Reflect.defineMetadata("dip:http-method", `${httpMethod} ${pathname}`, descriptor.value);
4128
+ return descriptor;
4129
+ };
4130
+ }
4131
+ function Get(pathname = "") {
4132
+ return HttpMethodDecorator("GET", pathname);
4133
+ }
4134
+ function Post(pathname = "") {
4135
+ return HttpMethodDecorator("POST", pathname);
4136
+ }
4137
+ function Put(pathname = "") {
4138
+ return HttpMethodDecorator("PUT", pathname);
4139
+ }
4140
+ function Delete(pathname = "") {
4141
+ return HttpMethodDecorator("DELETE", pathname);
4142
+ }
4143
+ function Patch(pathname = "") {
4144
+ return HttpMethodDecorator("PATCH", pathname);
4145
+ }
4146
+ function Options(pathname = "") {
4147
+ return HttpMethodDecorator("OPTIONS", pathname);
4148
+ }
4149
+ function Head(pathname = "") {
4150
+ return HttpMethodDecorator("HEAD", pathname);
4151
+ }
4152
+ // lib/jwt.ts
4153
+ async function validateTokenFromRequest(req) {
4154
+ if (!req.jwt)
4155
+ throw new Error("JWT middleware is not configured.");
4156
+ if (!req.headers)
4157
+ return false;
4158
+ const [_, token] = req.headers.authorization?.split(" ") ?? [];
4159
+ if (!token) {
4160
+ return false;
4161
+ }
4162
+ const result = await req.jwt.verify(token);
4163
+ return result !== false;
4164
+ }
4165
+
4166
+ class JwtGuard {
4167
+ async validate(req) {
4168
+ return await validateTokenFromRequest(req);
4169
+ }
4170
+ }
4171
+ function Jwt() {
4172
+ return function(target, propertyKey, descriptor) {
4173
+ if (propertyKey && typeof propertyKey === "object" && "kind" in propertyKey) {
4174
+ const context = propertyKey;
4175
+ if (context.kind === "class") {
4176
+ Guard(JwtGuard)(target, context);
4177
+ } else if (context.kind === "method") {
4178
+ Guard(JwtGuard)(target, context);
4179
+ }
4180
+ return;
4181
+ }
4182
+ if (isClass(target)) {
4183
+ Guard(JwtGuard)(target);
4184
+ return;
4185
+ }
4186
+ Guard(JwtGuard)(target, propertyKey, descriptor);
4187
+ };
4188
+ }
4189
+ // lib/jwt/jwt-module.ts
4190
+ var import_reflect_metadata18 = __toESM(require_Reflect(), 1);
4191
+
4192
+ class JwtModule {
4193
+ static options;
4194
+ static register(options) {
4195
+ this.options = {
4196
+ ...options,
4197
+ alg: options.alg || "HS256",
4198
+ exp: options.exp || "7d"
4199
+ };
4200
+ Reflect.defineMetadata("dip:module:jwt", true, JwtModule);
4201
+ Reflect.defineMetadata("dip:module:jwt:options", this.options, JwtModule);
4202
+ return this;
4203
+ }
4204
+ }
4205
+ // lib/schedule/cron/cron.ts
4206
+ var import_reflect_metadata19 = __toESM(require_Reflect(), 1);
4207
+ function Cron(expression) {
4208
+ if (!expression) {
4209
+ throw new Error("Invalid cron expression.");
4210
+ }
4211
+ return function(target, propertyKey, descriptor) {
4212
+ if (typeof propertyKey === "object" && propertyKey !== null && "kind" in propertyKey) {
4213
+ const context = propertyKey;
4214
+ const methodName = context.name;
4215
+ const sym2 = Symbol.for("dip:providers:crons");
4216
+ return;
4217
+ }
4218
+ const sym = Symbol.for("dip:providers:crons");
4219
+ target[sym] = target[sym] || [];
4220
+ target[sym].push({
4221
+ expression,
4222
+ methodName: propertyKey,
4223
+ type: "cron"
4224
+ });
4225
+ Reflect.defineMetadata("dip:cron", "is_cron", target, propertyKey);
4226
+ };
4227
+ }
4228
+ // lib/schedule/timeout/timeout.ts
4229
+ var import_reflect_metadata20 = __toESM(require_Reflect(), 1);
4230
+ function Timeout(delay) {
4231
+ if (!delay || delay < 0) {
4232
+ throw new Error("Delay must be a positive number.");
4233
+ }
4234
+ return function(target, propertyKey, descriptor) {
4235
+ if (typeof propertyKey === "object" && propertyKey !== null && "kind" in propertyKey) {
4236
+ return;
4237
+ }
4238
+ const sym = Symbol.for("dip:providers:timeouts");
4239
+ target[sym] = target[sym] || [];
4240
+ target[sym].push({
4241
+ delay,
4242
+ methodName: propertyKey,
4243
+ type: "timeout"
4244
+ });
4245
+ Reflect.defineMetadata("dip:timeout", "is_timeout", target, propertyKey);
4246
+ };
4247
+ }
4248
+ export {
4249
+ processParameters,
4250
+ ofType,
4251
+ map,
4252
+ UploadAdatper,
4253
+ UnprocessableEntityException,
4254
+ UnauthorizedException,
4255
+ Timeout,
4256
+ SqlService,
4257
+ SqlModule,
4258
+ Saga,
4259
+ SAGA_METADATA,
4260
+ Request,
4261
+ Render,
4262
+ RENDER_METADATA,
4263
+ QueryHandler,
4264
+ QueryBus,
4265
+ Query,
4266
+ QUERY_HANDLER_METADATA,
4267
+ Put,
4268
+ Post,
4269
+ Patch,
4270
+ ParamType,
4271
+ Param,
4272
+ Options,
4273
+ OkResponse,
4274
+ NotFoundException,
4275
+ NoContentResponse,
4276
+ Module,
4277
+ Logger,
4278
+ LogLevel,
4279
+ Layout,
4280
+ JwtModule,
4281
+ Jwt,
4282
+ InternalServerErrorException,
4283
+ Injectable,
4284
+ HttpException,
4285
+ Header,
4286
+ Head,
4287
+ Guard,
4288
+ Get,
4289
+ FormData2 as FormData,
4290
+ ForbiddenException,
4291
+ EventsHandler,
4292
+ EventBus,
4293
+ EVENT_HANDLER_METADATA,
4294
+ Delete,
4295
+ Cron,
4296
+ CreatedResponse,
4297
+ CqrsModule,
4298
+ Controller,
4299
+ ConflictException,
4300
+ CommandHandler,
4301
+ CommandBus,
4302
+ CacheAdapter,
4303
+ COMMAND_HANDLER_METADATA,
4304
+ Body,
4305
+ BadRequestException,
4306
+ AppStartup,
4307
+ ApiTags,
4308
+ ApiResponse,
4309
+ ApiOperation,
4310
+ ApiHeaders,
4311
+ ApiHeader,
4312
+ API_TAGS_METADATA,
4313
+ API_RESPONSE_METADATA,
4314
+ API_OPERATION_METADATA,
4315
+ API_HEADERS_METADATA
4316
+ };