alepha 0.13.8 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/dist/api/audits/index.d.ts +418 -338
  2. package/dist/api/audits/index.d.ts.map +1 -0
  3. package/dist/api/files/index.d.ts +81 -1
  4. package/dist/api/files/index.d.ts.map +1 -0
  5. package/dist/api/jobs/index.d.ts +107 -27
  6. package/dist/api/jobs/index.d.ts.map +1 -0
  7. package/dist/api/notifications/index.d.ts +21 -1
  8. package/dist/api/notifications/index.d.ts.map +1 -0
  9. package/dist/api/parameters/index.d.ts +455 -8
  10. package/dist/api/parameters/index.d.ts.map +1 -0
  11. package/dist/api/users/index.d.ts +844 -840
  12. package/dist/api/users/index.d.ts.map +1 -0
  13. package/dist/api/verifications/index.d.ts.map +1 -0
  14. package/dist/batch/index.d.ts.map +1 -0
  15. package/dist/bucket/index.d.ts.map +1 -0
  16. package/dist/cache/core/index.d.ts.map +1 -0
  17. package/dist/cache/redis/index.d.ts.map +1 -0
  18. package/dist/cli/index.d.ts +254 -59
  19. package/dist/cli/index.d.ts.map +1 -0
  20. package/dist/cli/index.js +499 -127
  21. package/dist/cli/index.js.map +1 -1
  22. package/dist/command/index.d.ts +217 -10
  23. package/dist/command/index.d.ts.map +1 -0
  24. package/dist/command/index.js +350 -74
  25. package/dist/command/index.js.map +1 -1
  26. package/dist/core/index.browser.js +1334 -1318
  27. package/dist/core/index.browser.js.map +1 -1
  28. package/dist/core/index.d.ts +76 -72
  29. package/dist/core/index.d.ts.map +1 -0
  30. package/dist/core/index.js +1337 -1321
  31. package/dist/core/index.js.map +1 -1
  32. package/dist/core/index.native.js +1337 -1321
  33. package/dist/core/index.native.js.map +1 -1
  34. package/dist/datetime/index.d.ts.map +1 -0
  35. package/dist/email/index.d.ts.map +1 -0
  36. package/dist/fake/index.d.ts.map +1 -0
  37. package/dist/file/index.d.ts.map +1 -0
  38. package/dist/file/index.js.map +1 -1
  39. package/dist/lock/core/index.d.ts.map +1 -0
  40. package/dist/lock/redis/index.d.ts.map +1 -0
  41. package/dist/logger/index.d.ts +1 -0
  42. package/dist/logger/index.d.ts.map +1 -0
  43. package/dist/mcp/index.d.ts +820 -0
  44. package/dist/mcp/index.d.ts.map +1 -0
  45. package/dist/mcp/index.js +978 -0
  46. package/dist/mcp/index.js.map +1 -0
  47. package/dist/orm/index.d.ts +234 -107
  48. package/dist/orm/index.d.ts.map +1 -0
  49. package/dist/orm/index.js +376 -316
  50. package/dist/orm/index.js.map +1 -1
  51. package/dist/queue/core/index.d.ts +4 -4
  52. package/dist/queue/core/index.d.ts.map +1 -0
  53. package/dist/queue/redis/index.d.ts.map +1 -0
  54. package/dist/queue/redis/index.js +2 -4
  55. package/dist/queue/redis/index.js.map +1 -1
  56. package/dist/redis/index.d.ts +400 -29
  57. package/dist/redis/index.d.ts.map +1 -0
  58. package/dist/redis/index.js +412 -21
  59. package/dist/redis/index.js.map +1 -1
  60. package/dist/retry/index.d.ts.map +1 -0
  61. package/dist/router/index.d.ts.map +1 -0
  62. package/dist/scheduler/index.d.ts +6 -6
  63. package/dist/scheduler/index.d.ts.map +1 -0
  64. package/dist/security/index.d.ts +28 -28
  65. package/dist/security/index.d.ts.map +1 -0
  66. package/dist/server/auth/index.d.ts +155 -155
  67. package/dist/server/auth/index.d.ts.map +1 -0
  68. package/dist/server/cache/index.d.ts.map +1 -0
  69. package/dist/server/compress/index.d.ts.map +1 -0
  70. package/dist/server/cookies/index.d.ts.map +1 -0
  71. package/dist/server/core/index.d.ts +0 -1
  72. package/dist/server/core/index.d.ts.map +1 -0
  73. package/dist/server/core/index.js.map +1 -1
  74. package/dist/server/cors/index.d.ts.map +1 -0
  75. package/dist/server/health/index.d.ts +17 -17
  76. package/dist/server/health/index.d.ts.map +1 -0
  77. package/dist/server/helmet/index.d.ts +4 -1
  78. package/dist/server/helmet/index.d.ts.map +1 -0
  79. package/dist/server/links/index.d.ts +33 -33
  80. package/dist/server/links/index.d.ts.map +1 -0
  81. package/dist/server/metrics/index.d.ts.map +1 -0
  82. package/dist/server/multipart/index.d.ts.map +1 -0
  83. package/dist/server/multipart/index.js.map +1 -1
  84. package/dist/server/proxy/index.d.ts.map +1 -0
  85. package/dist/server/proxy/index.js.map +1 -1
  86. package/dist/server/rate-limit/index.d.ts.map +1 -0
  87. package/dist/server/security/index.d.ts +9 -9
  88. package/dist/server/security/index.d.ts.map +1 -0
  89. package/dist/server/static/index.d.ts.map +1 -0
  90. package/dist/server/swagger/index.d.ts.map +1 -0
  91. package/dist/sms/index.d.ts.map +1 -0
  92. package/dist/thread/index.d.ts.map +1 -0
  93. package/dist/topic/core/index.d.ts.map +1 -0
  94. package/dist/topic/redis/index.d.ts.map +1 -0
  95. package/dist/topic/redis/index.js +3 -3
  96. package/dist/topic/redis/index.js.map +1 -1
  97. package/dist/vite/index.d.ts +10 -2
  98. package/dist/vite/index.d.ts.map +1 -0
  99. package/dist/vite/index.js +45 -20
  100. package/dist/vite/index.js.map +1 -1
  101. package/dist/websocket/index.d.ts.map +1 -0
  102. package/package.json +9 -4
  103. package/src/cli/apps/AlephaCli.ts +10 -3
  104. package/src/cli/apps/AlephaPackageBuilderCli.ts +15 -8
  105. package/src/cli/assets/mainTs.ts +9 -10
  106. package/src/cli/atoms/changelogOptions.ts +45 -0
  107. package/src/cli/commands/ChangelogCommands.ts +259 -0
  108. package/src/cli/commands/DeployCommands.ts +118 -0
  109. package/src/cli/commands/DrizzleCommands.ts +230 -10
  110. package/src/cli/commands/ViteCommands.ts +47 -23
  111. package/src/cli/defineConfig.ts +15 -0
  112. package/src/cli/index.ts +3 -0
  113. package/src/cli/services/AlephaCliUtils.ts +10 -154
  114. package/src/cli/services/GitMessageParser.ts +77 -0
  115. package/src/command/helpers/EnvUtils.ts +37 -0
  116. package/src/command/index.ts +3 -1
  117. package/src/command/primitives/$command.ts +172 -6
  118. package/src/command/providers/CliProvider.ts +499 -95
  119. package/src/core/Alepha.ts +1 -1
  120. package/src/core/providers/SchemaValidator.ts +23 -1
  121. package/src/file/providers/NodeFileSystemProvider.ts +3 -1
  122. package/src/mcp/errors/McpError.ts +72 -0
  123. package/src/mcp/helpers/jsonrpc.ts +163 -0
  124. package/src/mcp/index.ts +132 -0
  125. package/src/mcp/interfaces/McpTypes.ts +248 -0
  126. package/src/mcp/primitives/$prompt.ts +188 -0
  127. package/src/mcp/primitives/$resource.ts +171 -0
  128. package/src/mcp/primitives/$tool.ts +285 -0
  129. package/src/mcp/providers/McpServerProvider.ts +382 -0
  130. package/src/mcp/transports/SseMcpTransport.ts +172 -0
  131. package/src/mcp/transports/StdioMcpTransport.ts +126 -0
  132. package/src/orm/index.ts +20 -4
  133. package/src/orm/interfaces/PgQueryWhere.ts +1 -26
  134. package/src/orm/providers/drivers/BunPostgresProvider.ts +225 -0
  135. package/src/orm/providers/drivers/BunSqliteProvider.ts +180 -0
  136. package/src/orm/providers/drivers/CloudflareD1Provider.ts +164 -0
  137. package/src/orm/providers/drivers/DatabaseProvider.ts +25 -0
  138. package/src/orm/providers/drivers/NodePostgresProvider.ts +0 -25
  139. package/src/orm/providers/drivers/NodeSqliteProvider.ts +3 -1
  140. package/src/orm/services/QueryManager.ts +10 -125
  141. package/src/queue/redis/providers/RedisQueueProvider.ts +2 -7
  142. package/src/redis/index.ts +65 -3
  143. package/src/redis/providers/BunRedisProvider.ts +304 -0
  144. package/src/redis/providers/BunRedisSubscriberProvider.ts +94 -0
  145. package/src/redis/providers/NodeRedisProvider.ts +280 -0
  146. package/src/redis/providers/NodeRedisSubscriberProvider.ts +94 -0
  147. package/src/redis/providers/RedisProvider.ts +134 -140
  148. package/src/redis/providers/RedisSubscriberProvider.ts +58 -49
  149. package/src/server/core/providers/BunHttpServerProvider.ts +0 -3
  150. package/src/server/core/providers/ServerBodyParserProvider.ts +3 -1
  151. package/src/server/core/providers/ServerProvider.ts +7 -4
  152. package/src/server/multipart/providers/ServerMultipartProvider.ts +3 -1
  153. package/src/server/proxy/providers/ServerProxyProvider.ts +1 -1
  154. package/src/topic/redis/providers/RedisTopicProvider.ts +3 -3
  155. package/src/vite/plugins/viteAlephaBuild.ts +8 -2
  156. package/src/vite/plugins/viteAlephaDev.ts +6 -2
  157. package/src/vite/tasks/buildServer.ts +2 -1
  158. package/src/vite/tasks/generateCloudflare.ts +43 -15
  159. package/src/vite/tasks/runAlepha.ts +1 -0
  160. package/src/orm/services/PgJsonQueryManager.ts +0 -511
@@ -418,1483 +418,1556 @@ var TypeBoxError = class extends AlephaError {
418
418
  };
419
419
 
420
420
  //#endregion
421
- //#region ../../src/core/providers/SchemaValidator.ts
422
- var SchemaValidator = class {
423
- cache = /* @__PURE__ */ new Map();
424
- /**
425
- * Validate the value against the provided schema.
426
- *
427
- * Validation create a new value by applying some preprocessing. (e.g., trimming text)
428
- */
429
- validate(schema, value, options = {}) {
430
- const newValue = this.beforeParse(schema, value, {
431
- trim: options.trim ?? true,
432
- nullToUndefined: options.nullToUndefined ?? true,
433
- deleteUndefined: options.deleteUndefined ?? true
421
+ //#region ../../src/core/primitives/$hook.ts
422
+ /**
423
+ * Registers a new hook.
424
+ *
425
+ * ```ts
426
+ * import { $hook } from "alepha";
427
+ *
428
+ * class MyProvider {
429
+ * onStart = $hook({
430
+ * name: "start", // or "configure", "ready", "stop", ...
431
+ * handler: async (app) => {
432
+ * // await db.connect(); ...
433
+ * }
434
+ * });
435
+ * }
436
+ * ```
437
+ *
438
+ * Hooks are used to run async functions from all registered providers/services.
439
+ *
440
+ * You can't register a hook after the App has started.
441
+ *
442
+ * It's used under the hood by the `configure`, `start`, and `stop` methods.
443
+ * Some modules also use hooks to run their own logic. (e.g. `alepha/server`).
444
+ *
445
+ * You can create your own hooks by using module augmentation:
446
+ *
447
+ * ```ts
448
+ * declare module "alepha" {
449
+ *
450
+ * interface Hooks {
451
+ * "my:custom:hook": {
452
+ * arg1: string;
453
+ * }
454
+ * }
455
+ * }
456
+ *
457
+ * await alepha.events.emit("my:custom:hook", { arg1: "value" });
458
+ * ```
459
+ *
460
+ */
461
+ const $hook = (options) => createPrimitive(HookPrimitive, options);
462
+ var HookPrimitive = class extends Primitive {
463
+ called = 0;
464
+ onInit() {
465
+ this.alepha.events.on(this.options.on, {
466
+ caller: this.config.service,
467
+ priority: this.options.priority,
468
+ callback: async (args) => {
469
+ this.called += 1;
470
+ await this.options.handler(args);
471
+ }
434
472
  });
435
- try {
436
- return this.getValidator(schema).Parse(newValue);
437
- } catch (error) {
438
- if (error.cause?.errors?.[0]) throw new TypeBoxError(error.cause.errors[0]);
439
- throw error;
440
- }
441
473
  }
442
- getValidator(schema) {
443
- if (this.cache.has(schema)) return this.cache.get(schema);
444
- const validator = Compile(schema);
445
- this.cache.set(schema, validator);
446
- return validator;
474
+ };
475
+ $hook[KIND] = HookPrimitive;
476
+
477
+ //#endregion
478
+ //#region ../../src/core/helpers/FileLike.ts
479
+ const isTypeFile = (value) => {
480
+ return value && typeof value === "object" && "format" in value && value.format === "binary";
481
+ };
482
+ const isFileLike = (value) => {
483
+ return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.name === "string" && typeof value.type === "string" && typeof value.size === "number" && typeof value.stream.bind(value) === "function";
484
+ };
485
+
486
+ //#endregion
487
+ //#region ../../src/core/providers/TypeProvider.ts
488
+ const isUUID = Format.IsUuid;
489
+ var TypeGuard = class {
490
+ isBigInt = (value) => Type.IsString(value) && "format" in value && value.format === "bigint";
491
+ isUUID = (value) => Type.IsString(value) && "format" in value && value.format === "uuid";
492
+ isObject = Type.IsObject;
493
+ isNumber = Type.IsNumber;
494
+ isString = Type.IsString;
495
+ isBoolean = Type.IsBoolean;
496
+ isAny = Type.IsAny;
497
+ isArray = Type.IsArray;
498
+ isOptional = Type.IsOptional;
499
+ isUnion = Type.IsUnion;
500
+ isInteger = Type.IsInteger;
501
+ isNull = Type.IsNull;
502
+ isUndefined = Type.IsUndefined;
503
+ isUnsafe = Type.IsUnsafe;
504
+ isRecord = Type.IsRecord;
505
+ isTuple = Type.IsTuple;
506
+ isVoid = Type.IsVoid;
507
+ isLiteral = Type.IsLiteral;
508
+ isSchema = Type.IsSchema;
509
+ isFile = isTypeFile;
510
+ isDateTime = (schema) => {
511
+ return t.schema.isString(schema) && schema.format === "date-time";
512
+ };
513
+ isDate = (schema) => {
514
+ return t.schema.isString(schema) && schema.format === "date";
515
+ };
516
+ isTime = (schema) => {
517
+ return t.schema.isString(schema) && schema.format === "time";
518
+ };
519
+ isDuration = (schema) => {
520
+ return t.schema.isString(schema) && schema.format === "duration";
521
+ };
522
+ };
523
+ var TypeProvider = class TypeProvider {
524
+ static format = Format;
525
+ static {
526
+ Format.Set("bigint", (value) => TypeProvider.isValidBigInt(value));
447
527
  }
448
- /**
449
- * Preprocess the value based on the schema before validation.
450
- *
451
- * - If the value is `null` and the schema does not allow `null`, it converts it to `undefined`.
452
- * - If the value is a string and the schema has a `~options.trim` flag, it trims whitespace from the string.
453
- */
454
- beforeParse(schema, value, options) {
455
- if (!schema) return value;
456
- if (value === null && !this.isSchemaNullable(schema) && options.nullToUndefined) return;
457
- if (Array.isArray(value)) return value.map((it) => this.beforeParse(schema.items, it, options));
458
- if (typeof value === "string" && schema.type === "string") {
459
- let str = value;
460
- if (options.trim && schema["~options"]?.trim) str = str.trim();
461
- if (schema["~options"]?.lowercase) str = str.toLowerCase();
462
- return str;
528
+ static translateError(error, locale) {
529
+ if (!locale) return error.cause.message;
530
+ for (const [key, value] of Object.entries(Locale)) {
531
+ if (key === "Set" || key === "Get" || key === "Reset") continue;
532
+ if (key === locale || key.startsWith(`${locale}_`)) return value(error.cause);
463
533
  }
464
- if (typeof value === "object" && value !== null && schema.type === "object") {
465
- const obj = {};
466
- for (const key in value) {
467
- const newValue = this.beforeParse(schema.properties?.[key], value[key], options);
468
- if (newValue === void 0 && options.deleteUndefined) continue;
469
- obj[key] = newValue;
534
+ return error.cause.message;
535
+ }
536
+ static setLocale(locale) {
537
+ for (const [key, value] of Object.entries(Locale)) {
538
+ if (key === "Set" || key === "Get" || key === "Reset") continue;
539
+ if (key === locale || key.startsWith(`${locale}_`)) {
540
+ Locale.Set(value);
541
+ return;
470
542
  }
471
- return obj;
472
543
  }
473
- return value;
544
+ throw new AlephaError(`Locale not found: ${locale}`);
474
545
  }
475
- /**
476
- * Used by `beforeParse` to determine if a schema allows null values.
477
- */
478
- isSchemaNullable = (schema) => {
479
- if (!schema) return false;
480
- if (schema.type === "null") return true;
481
- if (Array.isArray(schema.type) && schema.type.includes("null")) return true;
482
- if (schema.anyOf) return schema.anyOf.some((it) => this.isSchemaNullable(it));
483
- if (schema.oneOf) return schema.oneOf.some((it) => this.isSchemaNullable(it));
484
- if (schema.allOf) return schema.allOf.some((it) => this.isSchemaNullable(it));
485
- return false;
486
- };
487
- };
488
-
489
- //#endregion
490
- //#region ../../src/core/providers/CodecManager.ts
491
- /**
492
- * CodecManager manages multiple codec formats and provides a unified interface
493
- * for encoding and decoding data with different formats.
494
- */
495
- var CodecManager = class {
496
- codecs = /* @__PURE__ */ new Map();
497
- jsonCodec = $inject(JsonSchemaCodec);
498
- schemaValidator = $inject(SchemaValidator);
499
- default = "json";
500
- constructor() {
501
- this.register(this.default, this.jsonCodec);
546
+ static isValidBigInt(value) {
547
+ if (typeof value === "number") return Number.isInteger(value);
548
+ if (!value.trim()) return false;
549
+ if (!/^-?\d+$/.test(value)) return false;
550
+ try {
551
+ BigInt(value);
552
+ return true;
553
+ } catch {
554
+ return false;
555
+ }
502
556
  }
503
557
  /**
504
- * Register a new codec format.
558
+ * Default maximum length for strings.
505
559
  *
506
- * @param name - The name of the codec (e.g., 'json', 'protobuf')
507
- * @param codec - The codec implementation
560
+ * It can be set to a larger value:
561
+ * ```ts
562
+ * TypeProvider.DEFAULT_STRING_MAX_LENGTH = 1000000;
563
+ * TypeProvider.DEFAULT_STRING_MAX_LENGTH = undefined; // no limit (not recommended)
564
+ * ```
508
565
  */
509
- register(name, codec) {
510
- this.codecs.set(name, codec);
511
- }
566
+ static DEFAULT_STRING_MAX_LENGTH = 255;
512
567
  /**
513
- * Get a specific codec by name.
514
- *
515
- * @param name - The name of the codec
516
- * @returns The codec instance
517
- * @throws {AlephaError} If the codec is not found
568
+ * Maximum length for short strings, such as names or titles.
518
569
  */
519
- getCodec(name) {
520
- const codec = this.codecs.get(name);
521
- if (!codec) throw new AlephaError(`Codec "${name}" not found. Available codecs: ${Array.from(this.codecs.keys()).join(", ")}`);
522
- return codec;
523
- }
570
+ static DEFAULT_SHORT_STRING_MAX_LENGTH = 64;
524
571
  /**
525
- * Encode data using the specified codec and output format.
572
+ * Maximum length for long strings, such as descriptions or comments.
573
+ * It can be overridden in the string options.
574
+ *
575
+ * It can be set to a larger value:
576
+ * ```ts
577
+ * TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH = 2048;
578
+ * ```
526
579
  */
527
- encode(schema, value, options) {
528
- const codec = this.getCodec(options?.encoder ?? this.default);
529
- const as = options?.as ?? "object";
530
- if (options?.validation !== false) value = this.schemaValidator.validate(schema, value, options?.validation);
531
- if (as === "object") return value;
532
- if (as === "binary") return codec.encodeToBinary(schema, value);
533
- return codec.encodeToString(schema, value);
534
- }
580
+ static DEFAULT_LONG_STRING_MAX_LENGTH = 1024;
535
581
  /**
536
- * Decode data using the specified codec.
582
+ * Maximum length for rich strings, such as HTML or Markdown.
583
+ * This is a large value to accommodate rich text content.
584
+ * > It's also the maximum length of PG's TEXT type.
585
+ *
586
+ * It can be overridden in the string options.
587
+ *
588
+ * It can be set to a larger value:
589
+ * ```ts
590
+ * TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH = 1000000;
591
+ * ```
537
592
  */
538
- decode(schema, data, options) {
539
- const encoderName = options?.encoder ?? this.default;
540
- let value = this.getCodec(encoderName).decode(schema, data);
541
- if (options?.validation !== false) value = this.schemaValidator.validate(schema, value, options?.validation);
542
- return value;
593
+ static DEFAULT_RICH_STRING_MAX_LENGTH = 65535;
594
+ /**
595
+ * Maximum number of items in an array.
596
+ * This is a default value to prevent excessive memory usage.
597
+ * It can be overridden in the array options.
598
+ */
599
+ static DEFAULT_ARRAY_MAX_ITEMS = 1e3;
600
+ raw = Type;
601
+ any = Type.Any;
602
+ void = Type.Void;
603
+ undefined = Type.Undefined;
604
+ record = Type.Record;
605
+ union = Type.Union;
606
+ tuple = Type.Tuple;
607
+ null = Type.Null;
608
+ const = Type.Literal;
609
+ options = Type.Options;
610
+ /**
611
+ * Type guards to check the type of schema.
612
+ * This is not a runtime type check, but a compile-time type guard.
613
+ *
614
+ * @example
615
+ * ```ts
616
+ * if (t.schema.isString(schema)) {
617
+ * // schema is TString
618
+ * }
619
+ * ```
620
+ */
621
+ schema = new TypeGuard();
622
+ extend(schema, properties, options) {
623
+ return Type.Interface(Array.isArray(schema) ? schema : [schema], properties, {
624
+ additionalProperties: false,
625
+ ...options
626
+ });
627
+ }
628
+ pick(schema, keys, options) {
629
+ return Type.Pick(schema, keys, {
630
+ additionalProperties: false,
631
+ ...options
632
+ });
633
+ }
634
+ omit(schema, keys, options) {
635
+ return Type.Omit(schema, keys, {
636
+ additionalProperties: false,
637
+ ...options
638
+ });
639
+ }
640
+ partial(schema, options) {
641
+ return Type.Partial(schema, {
642
+ additionalProperties: false,
643
+ ...options
644
+ });
543
645
  }
544
646
  /**
545
- * Validate decoded data against the schema.
647
+ * Create a schema for an object.
648
+ * By default, additional properties are not allowed.
546
649
  *
547
- * This is automatically called before encoding or after decoding.
650
+ * @example
651
+ * ```ts
652
+ * const userSchema = t.object({
653
+ * id: t.integer(),
654
+ * name: t.string(),
655
+ * });
656
+ * ```
548
657
  */
549
- validate(schema, value, options) {
550
- return this.schemaValidator.validate(schema, value, options);
658
+ object(properties, options) {
659
+ return Type.Object(properties, {
660
+ additionalProperties: false,
661
+ ...options
662
+ });
551
663
  }
552
- };
553
-
554
- //#endregion
555
- //#region ../../src/core/providers/EventManager.ts
556
- var EventManager = class {
557
- logFn;
558
664
  /**
559
- * List of events that can be triggered. Powered by $hook().
665
+ * Create a schema for an array.
666
+ * By default, the maximum number of items is limited to prevent excessive memory usage.
667
+ *
668
+ * @see TypeProvider.DEFAULT_ARRAY_MAX_ITEMS
560
669
  */
561
- events = {};
562
- constructor(logFn) {
563
- this.logFn = logFn;
670
+ array(schema, options) {
671
+ return Type.Array(schema, {
672
+ maxItems: TypeProvider.DEFAULT_ARRAY_MAX_ITEMS,
673
+ ...options
674
+ });
564
675
  }
565
- get log() {
566
- return this.logFn?.();
676
+ /**
677
+ * Create a schema for a string.
678
+ * For db or input fields, consider using `t.text()` instead, which has length limits.
679
+ *
680
+ * If you need a string with specific format (e.g. email, uuid), consider using the corresponding method (e.g. `t.email()`, `t.uuid()`).
681
+ */
682
+ string(options = {}) {
683
+ return Type.String({ ...options });
567
684
  }
568
685
  /**
569
- * Registers a hook for the specified event.
686
+ * Create a schema for a string with length limits.
687
+ * For internal strings without length limits, consider using `t.string()` instead.
688
+ *
689
+ * Default size is "regular", which has a max length of 255 characters.
570
690
  */
571
- on(event, hookOrFunc) {
572
- if (!this.events[event]) this.events[event] = [];
573
- const hook = typeof hookOrFunc === "function" ? { callback: hookOrFunc } : hookOrFunc;
574
- if (hook.priority === "first") this.events[event].unshift(hook);
575
- else if (hook.priority === "last") this.events[event].push(hook);
576
- else {
577
- const index = this.events[event].findIndex((it) => it.priority === "last");
578
- if (index !== -1) this.events[event].splice(index, 0, hook);
579
- else this.events[event].push(hook);
580
- }
581
- return () => {
582
- this.events[event] = this.events[event].filter((it) => it.callback !== hook.callback);
583
- };
691
+ text(options = {}) {
692
+ const { size, ...rest } = options;
693
+ const maxLength = size === "short" ? TypeProvider.DEFAULT_SHORT_STRING_MAX_LENGTH : size === "long" ? TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH : size === "rich" ? TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH : TypeProvider.DEFAULT_STRING_MAX_LENGTH;
694
+ return Type.String({
695
+ maxLength,
696
+ "~options": {
697
+ trim: options.trim ?? true,
698
+ lowercase: options.lowercase ?? false
699
+ },
700
+ ...rest
701
+ });
584
702
  }
585
703
  /**
586
- * Emits the specified event with the given payload.
704
+ * Create a schema for a JSON object.
705
+ * This is a record with string keys and any values.
587
706
  */
588
- async emit(func, payload, options = {}) {
589
- const ctx = {};
590
- if (options.log) {
591
- ctx.now = Date.now();
592
- this.log?.trace(`${func} ...`);
593
- }
594
- let events = this.events[func] ?? [];
595
- if (options.reverse) events = events.toReversed();
596
- for (const hook of events) {
597
- const name = hook.caller?.name ?? "unknown";
598
- if (options.log) {
599
- ctx.now2 = Date.now();
600
- this.log?.trace(`${func}(${name}) ...`);
601
- }
602
- try {
603
- await hook.callback(payload);
604
- } catch (error) {
605
- if (options.catch) {
606
- this.log?.error(`${func}(${name}) ERROR`, error);
607
- continue;
608
- }
609
- if (options.log) throw new AlephaError(`Failed during '${func}()' hook for service: ${name}`, { cause: error });
610
- throw error;
611
- }
612
- if (options.log) this.log?.debug(`${func}(${name}) OK [${Date.now() - ctx.now2}ms]`);
613
- }
614
- if (options.log) this.log?.debug(`${func} OK [${Date.now() - ctx.now}ms]`);
707
+ json(options) {
708
+ return t.record(t.text(), t.any(), options);
615
709
  }
616
- };
617
-
618
- //#endregion
619
- //#region ../../src/core/primitives/$atom.ts
620
- /**
621
- * Define an atom for state management.
622
- *
623
- * Atom lets you define a piece of state with a name, schema, and default value.
624
- *
625
- * By default, Alepha state is just a simple key-value store.
626
- * Using atoms allows you to have type safety, validation, and default values for your state.
627
- *
628
- * You control how state is structured and validated.
629
- *
630
- * Features:
631
- * - Set a schema for validation
632
- * - Set a default value for initial state
633
- * - Rules, like read-only, custom validation, etc.
634
- * - Automatic getter access in services with {@link $use}
635
- * - SSR support (server state automatically serialized and hydrated on client)
636
- * - React integration (useAtom hook for automatic component re-renders)
637
- * - Middleware
638
- * - Persistence adapters (localStorage, Redis, database, file system, cookie, etc.)
639
- * - State migrations (version upgrades when schema changes)
640
- * - Documentation generation & devtools integration
641
- *
642
- * Common use cases:
643
- * - user preferences
644
- * - feature flags
645
- * - configuration options
646
- * - session data
647
- *
648
- * Atom must contain only serializable data.
649
- * Avoid storing complex objects like class instances, functions, or DOM elements.
650
- * If you need to store complex data, consider using identifiers or references instead.
651
- */
652
- const $atom = (options) => {
653
- return new Atom(options);
654
- };
655
- var Atom = class {
656
- options;
657
- get schema() {
658
- return this.options.schema;
710
+ /**
711
+ * Create a schema for a boolean.
712
+ */
713
+ boolean(options) {
714
+ return Type.Boolean({ ...options });
659
715
  }
660
- get key() {
661
- return this.options.name;
716
+ /**
717
+ * Create a schema for a number.
718
+ */
719
+ number(options) {
720
+ return Type.Number({ ...options });
662
721
  }
663
- constructor(options) {
664
- this.options = options;
722
+ /**
723
+ * Create a schema for an integer.
724
+ */
725
+ integer(options) {
726
+ return Type.Integer({ ...options });
665
727
  }
666
- };
667
- $atom[KIND] = "atom";
668
-
669
- //#endregion
670
- //#region ../../src/core/providers/StateManager.ts
671
- var StateManager = class {
672
- als = $inject(AlsProvider);
673
- events = $inject(EventManager);
674
- codec = $inject(JsonSchemaCodec);
675
- atoms = /* @__PURE__ */ new Map();
676
- store = {};
677
- constructor(store = {}) {
678
- this.store = store;
728
+ int32(options) {
729
+ return Type.Integer({
730
+ minimum: -2147483647,
731
+ maximum: 2147483647,
732
+ ...options
733
+ });
679
734
  }
680
- getAtoms(context = true) {
681
- const atoms = [];
682
- if (context && this.als?.exists()) for (const atom of this.atoms.values()) {
683
- const value = this.als.get(atom.key);
684
- if (value !== void 0) atoms.push({
685
- atom,
686
- value
687
- });
688
- }
689
- else for (const [key, atom] of this.atoms.entries()) atoms.push({
690
- atom,
691
- value: this.store[key]
735
+ /**
736
+ * Mimic a signed 64-bit integer.
737
+ *
738
+ * This is NOT a true int64, as JavaScript cannot represent all int64 values.
739
+ * It is a number that is an integer and between -9007199254740991 and 9007199254740991.
740
+ * Use `t.bigint()` for true int64 values represented as strings.
741
+ */
742
+ int64(options) {
743
+ return Type.Number({
744
+ format: "int64",
745
+ multipleOf: 1,
746
+ minimum: -9007199254740991,
747
+ maximum: 9007199254740991,
748
+ ...options
692
749
  });
693
- return atoms;
694
750
  }
695
- register(atom) {
696
- const key = atom.key;
697
- if (!this.atoms.has(key)) {
698
- this.atoms.set(key, atom);
699
- if (!(key in this.store)) this.set(key, atom.options.default, { skipContext: true });
700
- }
701
- return this;
751
+ /**
752
+ * Make a schema optional.
753
+ */
754
+ optional(schema) {
755
+ return Type.Optional(schema);
702
756
  }
703
- get(target) {
704
- if (target instanceof Atom) this.register(target);
705
- const key = target instanceof Atom ? target.key : target;
706
- const store = this.store;
707
- return this.als?.exists() ? this.als.get(key) ?? store[key] : store[key];
757
+ /**
758
+ * Make a schema nullable.
759
+ */
760
+ nullable(schema, options) {
761
+ return Type.Union([Type.Null(), schema], options);
708
762
  }
709
- set(target, value, options) {
710
- if (target instanceof Atom) this.register(target);
711
- const key = target instanceof Atom ? target.key : target;
712
- const store = this.store;
713
- const prevValue = this.get(key);
714
- if (prevValue === value) return this;
715
- if (options?.skipContext !== true && this.als?.exists()) this.als.set(key, value);
716
- else store[key] = value;
717
- if (options?.skipEvents !== true) this.events?.emit("state:mutate", {
718
- key,
719
- value,
720
- prevValue
721
- }, { catch: true }).catch(() => null);
722
- return this;
763
+ /**
764
+ * Create a schema that maps all properties of an object schema to nullable.
765
+ */
766
+ nullify = (schema, options) => Type.Mapped(Type.Identifier("K"), Type.KeyOf(schema), Type.Ref("K"), Type.Union([Type.Index(schema, Type.Ref("K")), Type.Null()]), options);
767
+ /**
768
+ * Create a schema for a string enum.
769
+ */
770
+ enum(values, options) {
771
+ return Type.Unsafe(t.text({
772
+ enum: values,
773
+ pattern: values.map((v) => `^${v}$`).join("|"),
774
+ ...options
775
+ }));
723
776
  }
724
- mut(target, mutator) {
725
- const updated = mutator(this.get(target));
726
- return this.set(target, updated);
777
+ /**
778
+ * Create a schema for a bigint represented as a string.
779
+ * This is a string that validates bigint format (e.g. "123456789").
780
+ */
781
+ bigint(options) {
782
+ return t.string({
783
+ ...options,
784
+ format: "bigint"
785
+ });
727
786
  }
728
787
  /**
729
- * Check if a key exists in the state
788
+ * Create a schema for a URL represented as a string.
730
789
  */
731
- has(key) {
732
- return key in this.store;
790
+ url(options) {
791
+ return this.string({
792
+ ...options,
793
+ format: "url"
794
+ });
733
795
  }
734
796
  /**
735
- * Delete a key from the state (set to undefined)
797
+ * Create a schema for binary data represented as a base64 string.
736
798
  */
737
- del(key) {
738
- return this.set(key, void 0);
799
+ binary(options) {
800
+ return this.string({
801
+ ...options,
802
+ format: "binary"
803
+ });
739
804
  }
740
805
  /**
741
- * Push a value to an array in the state
806
+ * Create a schema for uuid.
742
807
  */
743
- push(key, ...value) {
744
- const current = this.get(key) ?? [];
745
- if (Array.isArray(current)) this.set(key, [...current, ...value]);
746
- return this;
808
+ uuid(options) {
809
+ return this.string({
810
+ ...options,
811
+ format: "uuid"
812
+ });
747
813
  }
748
814
  /**
749
- * Clear all state
815
+ * Create a schema for a file-like object.
816
+ *
817
+ * File like mimics the File API in browsers, but is adapted to work in Node.js as well.
818
+ *
819
+ * Implementation of file-like objects is handled by "alepha/file" package.
750
820
  */
751
- clear() {
752
- this.store = {};
753
- return this;
821
+ file(options) {
822
+ return Type.Unsafe(Type.Any({
823
+ [OPTIONS]: options,
824
+ format: "binary"
825
+ }));
754
826
  }
755
827
  /**
756
- * Get all keys that exist in the state
828
+ * @experimental
757
829
  */
758
- keys() {
759
- return Object.keys(this.store);
830
+ stream() {
831
+ return Type.Unsafe(Type.Any({
832
+ format: "stream",
833
+ type: "string"
834
+ }));
835
+ }
836
+ email(options) {
837
+ return this.text({
838
+ ...options,
839
+ format: "email",
840
+ trim: true,
841
+ lowercase: true
842
+ });
843
+ }
844
+ e164(options) {
845
+ return this.text({
846
+ ...options,
847
+ description: "Phone number in E.164 format, e.g. +1234567890.",
848
+ pattern: "^\\+[1-9]\\d{1,14}$"
849
+ });
850
+ }
851
+ bcp47(options) {
852
+ return this.text({
853
+ ...options,
854
+ description: "BCP 47 language tag, e.g. en, en-US, fr, fr-CA.",
855
+ pattern: "^[a-z]{2,3}(?:-[A-Z]{2})?$"
856
+ });
857
+ }
858
+ /**
859
+ * Create a schema for short text, such as names or titles.
860
+ * Default max length is 64 characters.
861
+ */
862
+ shortText(options) {
863
+ return this.text({
864
+ size: "short",
865
+ ...options
866
+ });
867
+ }
868
+ /**
869
+ * Create a schema for long text, such as descriptions or comments.
870
+ * Default max length is 1024 characters.
871
+ */
872
+ longText(options) {
873
+ return this.text({
874
+ size: "long",
875
+ ...options
876
+ });
877
+ }
878
+ /**
879
+ * Create a schema for rich text, such as HTML or Markdown.
880
+ * Default max length is 65535 characters.
881
+ */
882
+ richText(options) {
883
+ return this.text({
884
+ size: "rich",
885
+ ...options
886
+ });
760
887
  }
888
+ /**
889
+ * Create a schema for a string enum e.g. LIKE_THIS.
890
+ */
891
+ snakeCase = (options) => this.text({
892
+ pattern: "^[A-Z_-]+$",
893
+ ...options
894
+ });
895
+ /**
896
+ * Create a schema for an object with a value and label.
897
+ */
898
+ valueLabel = (options) => this.object({
899
+ value: this.snakeCase({ description: "Machine-readable value." }),
900
+ label: this.text({ description: "Human-readable label." }),
901
+ description: this.optional(this.text({
902
+ description: "Description of the value.",
903
+ size: "long"
904
+ }))
905
+ }, options);
906
+ datetime = (options) => t.text({
907
+ ...options,
908
+ format: "date-time"
909
+ });
910
+ date = (options) => t.text({
911
+ ...options,
912
+ format: "date"
913
+ });
914
+ time = (options) => t.text({
915
+ ...options,
916
+ format: "time"
917
+ });
918
+ duration = (options) => t.text({
919
+ ...options,
920
+ format: "duration"
921
+ });
761
922
  };
923
+ const t = new TypeProvider();
762
924
 
763
925
  //#endregion
764
- //#region ../../src/core/Alepha.ts
765
- /**
766
- * Core container of the Alepha framework.
767
- *
768
- * It is responsible for managing the lifecycle of services,
769
- * handling dependency injection,
770
- * and providing a unified interface for the application.
771
- *
772
- * @example
773
- * ```ts
774
- * import { Alepha, run } from "alepha";
775
- *
776
- * class MyService {
777
- * // business logic here
778
- * }
779
- *
780
- * const alepha = Alepha.create({
781
- * // state, env, and other properties
782
- * })
783
- *
784
- * alepha.with(MyService);
785
- *
786
- * run(alepha); // trigger .start (and .stop) automatically
787
- * ```
788
- *
789
- * ### Alepha Factory
790
- *
791
- * Alepha.create() is an enhanced version of new Alepha().
792
- * - It merges `process.env` with the provided state.env when available.
793
- * - It populates the test hooks for Vitest or Jest environments when available.
794
- *
795
- * new Alepha() is fine if you don't need these helpers.
796
- *
797
- * ### Platforms & Environments
798
- *
799
- * Alepha is designed to work in various environments:
800
- * - **Browser**: Runs in the browser, using the global `window` object.
801
- * - **Serverless**: Runs in serverless environments like Vercel or Vite.
802
- * - **Test**: Runs in test environments like Jest or Vitest.
803
- * - **Production**: Runs in production environments, typically with NODE_ENV set to "production".
804
- * * You can check the current environment using the following methods:
805
- *
806
- * - `isBrowser()`: Returns true if the App is running in a browser environment.
807
- * - `isServerless()`: Returns true if the App is running in a serverless environment.
808
- * - `isTest()`: Returns true if the App is running in a test environment.
809
- * - `isProduction()`: Returns true if the App is running in a production environment.
810
- *
811
- * ### State & Environment
812
- *
813
- * The state of the Alepha container is stored in the `store` property.
814
- * Most important property is `store.env`, which contains the environment variables.
815
- *
816
- * ```ts
817
- * const alepha = Alepha.create({ env: { MY_VAR: "value" } });
818
- *
819
- * // You can access the environment variables using alepha.env
820
- * console.log(alepha.env.MY_VAR); // "value"
821
- *
822
- * // But you should use $env() primitive to get typed values from the environment.
823
- * class App {
824
- * env = $env(
825
- * t.object({
826
- * MY_VAR: t.text(),
827
- * })
828
- * );
829
- * }
830
- * ```
831
- *
832
- * ### Modules
833
- *
834
- * Modules are a way to group services together.
835
- * You can register a module using the `$module` primitive.
836
- *
837
- * ```ts
838
- * import { $module } from "alepha";
839
- *
840
- * class MyLib {}
841
- *
842
- * const myModule = $module({
843
- * name: "my.project.module",
844
- * services: [MyLib],
845
- * });
846
- * ```
847
- *
848
- * Do not use modules for small applications.
849
- *
850
- * ### Hooks
851
- *
852
- * Hooks are a way to run async functions from all registered providers/services.
853
- * You can register a hook using the `$hook` primitive.
854
- *
855
- * ```ts
856
- * import { $hook } from "alepha";
857
- *
858
- * class App {
859
- * log = $logger();
860
- * onCustomerHook = $hook({
861
- * on: "my:custom:hook",
862
- * handler: () => {
863
- * this.log?.info("App is being configured");
864
- * },
865
- * });
866
- * }
867
- *
868
- * Alepha.create()
869
- * .with(App)
870
- * .start()
871
- * .then(alepha => alepha.events.emit("my:custom:hook"));
872
- * ```
873
- *
874
- * Hooks are fully typed. You can create your own hooks by using module augmentation:
875
- *
876
- * ```ts
877
- * declare module "alepha" {
878
- * interface Hooks {
879
- * "my:custom:hook": {
880
- * arg1: string;
881
- * }
882
- * }
883
- * }
884
- * ```
885
- *
886
- * @module alepha
887
- */
888
- var Alepha = class Alepha {
926
+ //#region ../../src/core/providers/SchemaValidator.ts
927
+ var SchemaValidator = class {
928
+ cache = /* @__PURE__ */ new Map();
929
+ useEval = true;
889
930
  /**
890
- * Creates a new instance of the Alepha container with some helpers:
931
+ * Validate the value against the provided schema.
891
932
  *
892
- * - merges `process.env` with the provided state.env when available.
893
- * - populates the test hooks for Vitest or Jest environments when available.
933
+ * Validation create a new value by applying some preprocessing. (e.g., trimming text)
934
+ */
935
+ validate(schema, value, options = {}) {
936
+ const newValue = this.beforeParse(schema, value, {
937
+ trim: options.trim ?? true,
938
+ nullToUndefined: options.nullToUndefined ?? true,
939
+ deleteUndefined: options.deleteUndefined ?? true
940
+ });
941
+ try {
942
+ if (!this.useEval) return Value.Parse(schema, newValue);
943
+ return this.getValidator(schema).Parse(newValue);
944
+ } catch (error) {
945
+ if (error.cause?.errors?.[0]) throw new TypeBoxError(error.cause.errors[0]);
946
+ throw error;
947
+ }
948
+ }
949
+ getValidator(schema) {
950
+ if (this.cache.has(schema)) return this.cache.get(schema);
951
+ const validator = Compile(schema);
952
+ this.cache.set(schema, validator);
953
+ return validator;
954
+ }
955
+ /**
956
+ * Preprocess the value based on the schema before validation.
894
957
  *
895
- * If you are not interested about these helpers, you can use the constructor directly.
958
+ * - If the value is `null` and the schema does not allow `null`, it converts it to `undefined`.
959
+ * - If the value is a string and the schema has a `~options.trim` flag, it trims whitespace from the string.
896
960
  */
897
- static create(state = {}) {
898
- if (typeof process === "object" && typeof process.env === "object") {
899
- state.env = {
900
- ...state.env,
901
- ...process.env
902
- };
903
- if (process.env.NODE_ENV === "production") state.env.NODE_ENV ??= "production";
961
+ beforeParse(schema, value, options) {
962
+ if (!schema) return value;
963
+ if (value === null && !this.isSchemaNullable(schema) && options.nullToUndefined) return;
964
+ if (Array.isArray(value)) return value.map((it) => this.beforeParse(schema.items, it, options));
965
+ if (typeof value === "string" && schema.type === "string") {
966
+ let str = value;
967
+ if (options.trim && schema["~options"]?.trim) str = str.trim();
968
+ if (schema["~options"]?.lowercase) str = str.toLowerCase();
969
+ return str;
904
970
  }
905
- const alepha = new Alepha(state);
906
- if (alepha.isTest()) {
907
- const g = globalThis;
908
- const beforeAll = state["alepha.test.beforeAll"] ?? g.beforeAll;
909
- const afterAll = state["alepha.test.afterAll"] ?? g.afterAll;
910
- const afterEach = state["alepha.test.afterEach"] ?? g.afterEach;
911
- const onTestFinished = state["alepha.test.onTestFinished"] ?? g.onTestFinished;
912
- beforeAll?.(() => alepha.start());
913
- afterAll?.(() => alepha.stop());
914
- try {
915
- onTestFinished?.(() => alepha.stop());
916
- } catch (_error) {}
917
- alepha.store.set("alepha.test.beforeAll", beforeAll).set("alepha.test.afterAll", afterAll).set("alepha.test.afterEach", afterEach).set("alepha.test.onTestFinished", onTestFinished);
971
+ if (typeof value === "object" && value !== null && schema.type === "object") {
972
+ const obj = {};
973
+ for (const key in value) {
974
+ const newValue = this.beforeParse(schema.properties?.[key], value[key], options);
975
+ if (newValue === void 0 && options.deleteUndefined) continue;
976
+ obj[key] = newValue;
977
+ }
978
+ return obj;
918
979
  }
919
- return alepha;
980
+ return value;
920
981
  }
921
982
  /**
922
- * Flag indicating whether the App won't accept any further changes.
923
- * Pass to true when #start() is called.
983
+ * Used by `beforeParse` to determine if a schema allows null values.
924
984
  */
925
- locked = false;
985
+ isSchemaNullable = (schema) => {
986
+ if (!schema) return false;
987
+ if (schema.type === "null") return true;
988
+ if (Array.isArray(schema.type) && schema.type.includes("null")) return true;
989
+ if (schema.anyOf) return schema.anyOf.some((it) => this.isSchemaNullable(it));
990
+ if (schema.oneOf) return schema.oneOf.some((it) => this.isSchemaNullable(it));
991
+ if (schema.allOf) return schema.allOf.some((it) => this.isSchemaNullable(it));
992
+ return false;
993
+ };
994
+ onConfigure = $hook({
995
+ on: "configure",
996
+ handler: () => {
997
+ this.useEval = this.canEval();
998
+ }
999
+ });
1000
+ canEval() {
1001
+ try {
1002
+ Compile(t.object({ test: t.string() })).Parse({ test: "value" });
1003
+ return true;
1004
+ } catch {
1005
+ return false;
1006
+ }
1007
+ }
1008
+ };
1009
+
1010
+ //#endregion
1011
+ //#region ../../src/core/providers/CodecManager.ts
1012
+ /**
1013
+ * CodecManager manages multiple codec formats and provides a unified interface
1014
+ * for encoding and decoding data with different formats.
1015
+ */
1016
+ var CodecManager = class {
1017
+ codecs = /* @__PURE__ */ new Map();
1018
+ jsonCodec = $inject(JsonSchemaCodec);
1019
+ schemaValidator = $inject(SchemaValidator);
1020
+ default = "json";
1021
+ constructor() {
1022
+ this.register(this.default, this.jsonCodec);
1023
+ }
926
1024
  /**
927
- * True if the App has been configured.
1025
+ * Register a new codec format.
1026
+ *
1027
+ * @param name - The name of the codec (e.g., 'json', 'protobuf')
1028
+ * @param codec - The codec implementation
928
1029
  */
929
- configured = false;
1030
+ register(name, codec) {
1031
+ this.codecs.set(name, codec);
1032
+ }
930
1033
  /**
931
- * True if the App has started.
1034
+ * Get a specific codec by name.
1035
+ *
1036
+ * @param name - The name of the codec
1037
+ * @returns The codec instance
1038
+ * @throws {AlephaError} If the codec is not found
932
1039
  */
933
- started = false;
1040
+ getCodec(name) {
1041
+ const codec = this.codecs.get(name);
1042
+ if (!codec) throw new AlephaError(`Codec "${name}" not found. Available codecs: ${Array.from(this.codecs.keys()).join(", ")}`);
1043
+ return codec;
1044
+ }
934
1045
  /**
935
- * True if the App is ready.
1046
+ * Encode data using the specified codec and output format.
936
1047
  */
937
- ready = false;
1048
+ encode(schema, value, options) {
1049
+ const codec = this.getCodec(options?.encoder ?? this.default);
1050
+ const as = options?.as ?? "object";
1051
+ if (options?.validation !== false) value = this.schemaValidator.validate(schema, value, options?.validation);
1052
+ if (as === "object") return value;
1053
+ if (as === "binary") return codec.encodeToBinary(schema, value);
1054
+ return codec.encodeToString(schema, value);
1055
+ }
938
1056
  /**
939
- * A promise that resolves when the App has started.
1057
+ * Decode data using the specified codec.
940
1058
  */
941
- starting;
1059
+ decode(schema, data, options) {
1060
+ const encoderName = options?.encoder ?? this.default;
1061
+ let value = this.getCodec(encoderName).decode(schema, data);
1062
+ if (options?.validation !== false) value = this.schemaValidator.validate(schema, value, options?.validation);
1063
+ return value;
1064
+ }
942
1065
  /**
943
- * During the instantiation process, we keep a list of pending instantiations.
944
- * > It allows us to detect circular dependencies.
1066
+ * Validate decoded data against the schema.
1067
+ *
1068
+ * This is automatically called before encoding or after decoding.
945
1069
  */
946
- pendingInstantiations = [];
1070
+ validate(schema, value, options) {
1071
+ return this.schemaValidator.validate(schema, value, options);
1072
+ }
1073
+ };
1074
+
1075
+ //#endregion
1076
+ //#region ../../src/core/providers/EventManager.ts
1077
+ var EventManager = class {
1078
+ logFn;
947
1079
  /**
948
- * Cache for environment variables.
949
- * > It allows us to avoid parsing the same schema multiple times.
1080
+ * List of events that can be triggered. Powered by $hook().
950
1081
  */
951
- cacheEnv = /* @__PURE__ */ new Map();
952
- /**
953
- * List of modules that are registered in the container.
954
- *
955
- * Modules are used to group services and provide a way to register them in the container.
956
- */
957
- modules = [];
958
- /**
959
- * List of service substitutions.
960
- *
961
- * Services registered here will be replaced by the specified service when injected.
962
- */
963
- substitutions = /* @__PURE__ */ new Map();
964
- /**
965
- * Registry of primitives.
966
- */
967
- primitiveRegistry = /* @__PURE__ */ new Map();
968
- /**
969
- * List of all services + how they are provided.
970
- */
971
- registry = /* @__PURE__ */ new Map();
972
- /**
973
- * Node.js feature that allows to store context across asynchronous calls.
974
- *
975
- * This is used for logging, tracing, and other context-related features.
976
- *
977
- * Mocked for browser environments.
978
- */
979
- context;
980
- /**
981
- * Event manager to handle lifecycle events and custom events.
982
- */
983
- events;
984
- /**
985
- * State manager to store arbitrary values.
986
- */
987
- store;
988
- /**
989
- * Codec manager for encoding and decoding data with different formats.
990
- *
991
- * Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface.
992
- */
993
- codec;
1082
+ events = {};
1083
+ constructor(logFn) {
1084
+ this.logFn = logFn;
1085
+ }
1086
+ get log() {
1087
+ return this.logFn?.();
1088
+ }
994
1089
  /**
995
- * Get logger instance.
1090
+ * Registers a hook for the specified event.
996
1091
  */
997
- get log() {
998
- return this.store.get("alepha.logger");
1092
+ on(event, hookOrFunc) {
1093
+ if (!this.events[event]) this.events[event] = [];
1094
+ const hook = typeof hookOrFunc === "function" ? { callback: hookOrFunc } : hookOrFunc;
1095
+ if (hook.priority === "first") this.events[event].unshift(hook);
1096
+ else if (hook.priority === "last") this.events[event].push(hook);
1097
+ else {
1098
+ const index = this.events[event].findIndex((it) => it.priority === "last");
1099
+ if (index !== -1) this.events[event].splice(index, 0, hook);
1100
+ else this.events[event].push(hook);
1101
+ }
1102
+ return () => {
1103
+ this.events[event] = this.events[event].filter((it) => it.callback !== hook.callback);
1104
+ };
999
1105
  }
1000
1106
  /**
1001
- * The environment variables for the App.
1107
+ * Emits the specified event with the given payload.
1002
1108
  */
1003
- get env() {
1004
- return this.store.get("env") ?? {};
1109
+ async emit(func, payload, options = {}) {
1110
+ const ctx = {};
1111
+ if (options.log) {
1112
+ ctx.now = Date.now();
1113
+ this.log?.trace(`${func} ...`);
1114
+ }
1115
+ let events = this.events[func] ?? [];
1116
+ if (options.reverse) events = events.toReversed();
1117
+ for (const hook of events) {
1118
+ const name = hook.caller?.name ?? "unknown";
1119
+ if (options.log) {
1120
+ ctx.now2 = Date.now();
1121
+ this.log?.trace(`${func}(${name}) ...`);
1122
+ }
1123
+ try {
1124
+ await hook.callback(payload);
1125
+ } catch (error) {
1126
+ if (options.catch) {
1127
+ this.log?.error(`${func}(${name}) ERROR`, error);
1128
+ continue;
1129
+ }
1130
+ if (options.log) throw new AlephaError(`Failed during '${func}()' hook for service: ${name}`, { cause: error });
1131
+ throw error;
1132
+ }
1133
+ if (options.log) this.log?.debug(`${func}(${name}) OK [${Date.now() - ctx.now2}ms]`);
1134
+ }
1135
+ if (options.log) this.log?.debug(`${func} OK [${Date.now() - ctx.now}ms]`);
1005
1136
  }
1006
- constructor(state = {}) {
1007
- this.store = this.inject(StateManager, { args: [state] });
1008
- this.events = this.inject(EventManager);
1009
- this.events.logFn = () => this.log;
1010
- this.context = this.inject(AlsProvider);
1011
- this.codec = this.inject(CodecManager);
1137
+ };
1138
+
1139
+ //#endregion
1140
+ //#region ../../src/core/primitives/$atom.ts
1141
+ /**
1142
+ * Define an atom for state management.
1143
+ *
1144
+ * Atom lets you define a piece of state with a name, schema, and default value.
1145
+ *
1146
+ * By default, Alepha state is just a simple key-value store.
1147
+ * Using atoms allows you to have type safety, validation, and default values for your state.
1148
+ *
1149
+ * You control how state is structured and validated.
1150
+ *
1151
+ * Features:
1152
+ * - Set a schema for validation
1153
+ * - Set a default value for initial state
1154
+ * - Rules, like read-only, custom validation, etc.
1155
+ * - Automatic getter access in services with {@link $use}
1156
+ * - SSR support (server state automatically serialized and hydrated on client)
1157
+ * - React integration (useAtom hook for automatic component re-renders)
1158
+ * - Middleware
1159
+ * - Persistence adapters (localStorage, Redis, database, file system, cookie, etc.)
1160
+ * - State migrations (version upgrades when schema changes)
1161
+ * - Documentation generation & devtools integration
1162
+ *
1163
+ * Common use cases:
1164
+ * - user preferences
1165
+ * - feature flags
1166
+ * - configuration options
1167
+ * - session data
1168
+ *
1169
+ * Atom must contain only serializable data.
1170
+ * Avoid storing complex objects like class instances, functions, or DOM elements.
1171
+ * If you need to store complex data, consider using identifiers or references instead.
1172
+ */
1173
+ const $atom = (options) => {
1174
+ return new Atom(options);
1175
+ };
1176
+ var Atom = class {
1177
+ options;
1178
+ get schema() {
1179
+ return this.options.schema;
1012
1180
  }
1013
- set(target, value) {
1014
- this.store.set(target, value);
1181
+ get key() {
1182
+ return this.options.name;
1183
+ }
1184
+ constructor(options) {
1185
+ this.options = options;
1186
+ }
1187
+ };
1188
+ $atom[KIND] = "atom";
1189
+
1190
+ //#endregion
1191
+ //#region ../../src/core/providers/StateManager.ts
1192
+ var StateManager = class {
1193
+ als = $inject(AlsProvider);
1194
+ events = $inject(EventManager);
1195
+ codec = $inject(JsonSchemaCodec);
1196
+ atoms = /* @__PURE__ */ new Map();
1197
+ store = {};
1198
+ constructor(store = {}) {
1199
+ this.store = store;
1200
+ }
1201
+ getAtoms(context = true) {
1202
+ const atoms = [];
1203
+ if (context && this.als?.exists()) for (const atom of this.atoms.values()) {
1204
+ const value = this.als.get(atom.key);
1205
+ if (value !== void 0) atoms.push({
1206
+ atom,
1207
+ value
1208
+ });
1209
+ }
1210
+ else for (const [key, atom] of this.atoms.entries()) atoms.push({
1211
+ atom,
1212
+ value: this.store[key]
1213
+ });
1214
+ return atoms;
1215
+ }
1216
+ register(atom) {
1217
+ const key = atom.key;
1218
+ if (!this.atoms.has(key)) {
1219
+ this.atoms.set(key, atom);
1220
+ if (!(key in this.store)) this.set(key, atom.options.default, { skipContext: true });
1221
+ }
1015
1222
  return this;
1016
1223
  }
1017
- /**
1018
- * True when start() is called.
1019
- *
1020
- * -> No more services can be added, it's over, bye!
1021
- */
1022
- isLocked() {
1023
- return this.locked;
1224
+ get(target) {
1225
+ if (target instanceof Atom) this.register(target);
1226
+ const key = target instanceof Atom ? target.key : target;
1227
+ const store = this.store;
1228
+ return this.als?.exists() ? this.als.get(key) ?? store[key] : store[key];
1024
1229
  }
1025
- /**
1026
- * Returns whether the App is configured.
1027
- *
1028
- * It means that Alepha#configure() has been called.
1029
- *
1030
- * > By default, configure() is called automatically when start() is called, but you can also call it manually.
1031
- */
1032
- isConfigured() {
1033
- return this.configured;
1230
+ set(target, value, options) {
1231
+ if (target instanceof Atom) this.register(target);
1232
+ const key = target instanceof Atom ? target.key : target;
1233
+ const store = this.store;
1234
+ const prevValue = this.get(key);
1235
+ if (prevValue === value) return this;
1236
+ if (options?.skipContext !== true && this.als?.exists()) this.als.set(key, value);
1237
+ else store[key] = value;
1238
+ if (options?.skipEvents !== true) this.events?.emit("state:mutate", {
1239
+ key,
1240
+ value,
1241
+ prevValue
1242
+ }, { catch: true }).catch(() => null);
1243
+ return this;
1244
+ }
1245
+ mut(target, mutator) {
1246
+ const updated = mutator(this.get(target));
1247
+ return this.set(target, updated);
1034
1248
  }
1035
1249
  /**
1036
- * Returns whether the App has started.
1037
- *
1038
- * It means that #start() has been called but maybe not all services are ready.
1250
+ * Check if a key exists in the state
1039
1251
  */
1040
- isStarted() {
1041
- return this.started;
1252
+ has(key) {
1253
+ return key in this.store;
1042
1254
  }
1043
1255
  /**
1044
- * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
1256
+ * Delete a key from the state (set to undefined)
1045
1257
  */
1046
- isReady() {
1047
- return this.ready;
1258
+ del(key) {
1259
+ return this.set(key, void 0);
1048
1260
  }
1049
1261
  /**
1050
- * True if the App is running in a Continuous Integration environment.
1262
+ * Push a value to an array in the state
1051
1263
  */
1052
- isCI() {
1053
- if (this.env.GITHUB_ACTIONS) return true;
1054
- return !!this.env.CI;
1264
+ push(key, ...value) {
1265
+ const current = this.get(key) ?? [];
1266
+ if (Array.isArray(current)) this.set(key, [...current, ...value]);
1267
+ return this;
1055
1268
  }
1056
1269
  /**
1057
- * True if the App is running in a browser environment.
1270
+ * Clear all state
1058
1271
  */
1059
- isBrowser() {
1060
- return typeof window !== "undefined";
1272
+ clear() {
1273
+ this.store = {};
1274
+ return this;
1061
1275
  }
1062
1276
  /**
1063
- * Returns whether the App is running in Vite dev mode.
1064
- */
1065
- isViteDev() {
1066
- if (this.isBrowser()) return false;
1067
- return !!this.env.VITE_ALEPHA_DEV;
1068
- }
1069
- isBun() {
1070
- return "Bun" in globalThis;
1071
- }
1072
- /**
1073
- * Returns whether the App is running in a serverless environment.
1074
- */
1075
- isServerless() {
1076
- if (this.isBrowser()) return false;
1077
- if (this.env.VERCEL_REGION) return true;
1078
- if (typeof global === "object" && typeof global.Cloudflare === "object") return true;
1079
- return false;
1080
- }
1081
- /**
1082
- * Returns whether the App is in test mode. (Running in a test environment)
1083
- *
1084
- * > This is automatically set when running tests with Jest or Vitest.
1085
- */
1086
- isTest() {
1087
- return this.env.NODE_ENV === "test";
1088
- }
1089
- /**
1090
- * Returns whether the App is in production mode. (Running in a production environment)
1091
- *
1092
- * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.
1093
- */
1094
- isProduction() {
1095
- return this.env.NODE_ENV === "production";
1096
- }
1097
- /**
1098
- * Starts the App.
1099
- *
1100
- * - Lock any further changes to the container.
1101
- * - Run "configure" hook for all services. Primitives will be processed.
1102
- * - Run "start" hook for all services. Providers will connect/listen/...
1103
- * - Run "ready" hook for all services. This is the point where the App is ready to serve requests.
1104
- *
1105
- * @return A promise that resolves when the App has started.
1106
- */
1107
- async start() {
1108
- if (this.ready) {
1109
- this.log?.debug("App is already started, skipping...");
1110
- return this;
1111
- }
1112
- if (this.starting) {
1113
- this.log?.warn("App is already starting, waiting for it to finish...");
1114
- return this.starting.promise;
1115
- }
1116
- this.starting = Promise.withResolvers();
1117
- const now = Date.now();
1118
- this.log?.info("Starting App...");
1119
- for (const [key] of this.substitutions.entries()) this.inject(key);
1120
- const target = this.store.get("alepha.target");
1121
- if (target) {
1122
- this.registry = /* @__PURE__ */ new Map();
1123
- this.primitiveRegistry = /* @__PURE__ */ new Map();
1124
- this.with(target);
1125
- }
1126
- this.locked = true;
1127
- await this.events.emit("configure", this, { log: true });
1128
- this.configured = true;
1129
- await this.events.emit("start", this, { log: true });
1130
- this.started = true;
1131
- await this.events.emit("ready", this, { log: true });
1132
- this.log?.info(`App is now ready [${Date.now() - now}ms]`);
1133
- this.ready = true;
1134
- this.starting.resolve(this);
1135
- this.starting = void 0;
1136
- return this;
1137
- }
1138
- /**
1139
- * Stops the App.
1140
- *
1141
- * - Run "stop" hook for all services.
1142
- *
1143
- * Stop will NOT reset the container.
1144
- * Stop will NOT unlock the container.
1145
- *
1146
- * > Stop is used to gracefully shut down the application, nothing more. There is no "restart".
1147
- *
1148
- * @return A promise that resolves when the App has stopped.
1149
- */
1150
- async stop() {
1151
- if (!this.started) return;
1152
- this.log?.info("Stopping App...");
1153
- await this.events.emit("stop", this, {
1154
- reverse: true,
1155
- log: true
1156
- });
1157
- this.log?.info("App is now off");
1158
- this.started = false;
1159
- this.ready = false;
1160
- }
1161
- /**
1162
- * Check if entry is registered in the container.
1163
- */
1164
- has(entry, opts = {}) {
1165
- if (entry === Alepha) return true;
1166
- const { inStack = true, inRegistry = true, inSubstitutions = true, registry = this.registry } = opts;
1167
- const { provide } = typeof entry === "object" && "provide" in entry ? entry : { provide: entry };
1168
- if (inSubstitutions) {
1169
- if (this.substitutions.get(provide)) return true;
1170
- }
1171
- if (inRegistry) {
1172
- if (registry.get(provide)) return true;
1173
- }
1174
- if (inStack) {
1175
- const substitute = this.substitutions.get(provide)?.use;
1176
- if (substitute && this.pendingInstantiations.includes(substitute)) return true;
1177
- return this.pendingInstantiations.includes(provide);
1178
- }
1179
- return false;
1180
- }
1181
- /**
1182
- * Registers the specified service in the container.
1183
- *
1184
- * - If the service is ALREADY registered, the method does nothing.
1185
- * - If the service is NOT registered, a new instance is created and registered.
1186
- *
1187
- * Method is chainable, so you can register multiple services in a single call.
1188
- *
1189
- * > ServiceEntry allows to provide a service **substitution** feature.
1190
- *
1191
- * @example
1192
- * ```ts
1193
- * class A { value = "a"; }
1194
- * class B { value = "b"; }
1195
- * class M { a = $inject(A); }
1196
- *
1197
- * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b"
1198
- * ```
1199
- *
1200
- * > **Substitution** is an advanced feature that allows you to replace a service with another service.
1201
- * > It's useful for testing or for providing different implementations of a service.
1202
- * > If you are interested in configuring a service, use Alepha#configure() instead.
1203
- *
1204
- * @param serviceEntry - The service to register in the container.
1205
- * @return Current instance of Alepha.
1206
- */
1207
- with(serviceEntry) {
1208
- const entry = "default" in serviceEntry ? serviceEntry.default : serviceEntry;
1209
- if (this.has(entry, {
1210
- inSubstitutions: false,
1211
- inRegistry: false
1212
- })) return this;
1213
- if (typeof entry === "object") {
1214
- if (entry.provide === entry.use) {
1215
- this.inject(entry.provide);
1216
- return this;
1217
- }
1218
- if (!this.substitutions.has(entry.provide) && !this.has(entry.provide)) {
1219
- if (this.started) throw new ContainerLockedError();
1220
- if (MODULE in entry.provide && typeof entry.provide[MODULE] === "function") entry.use[MODULE] ??= entry.provide[MODULE];
1221
- this.substitutions.set(entry.provide, { use: entry.use });
1222
- } else if (!entry.optional) throw new TooLateSubstitutionError(entry.provide.name, entry.use.name);
1223
- return this;
1224
- }
1225
- this.inject(entry);
1226
- return this;
1227
- }
1228
- /**
1229
- * Get an instance of the specified service from the container.
1230
- *
1231
- * @see {@link InjectOptions} for the available options.
1232
- */
1233
- inject(service, opts = {}) {
1234
- const lifetime = opts.lifetime ?? "singleton";
1235
- const parent = opts.parent !== void 0 ? opts.parent : __alephaRef?.parent ?? Alepha;
1236
- const transient = lifetime === "transient";
1237
- const registry = lifetime === "scoped" ? this.context.get("registry") ?? this.registry : this.registry;
1238
- if (service === Alepha) return this;
1239
- if (typeof service === "string") {
1240
- for (const [key, value] of registry.entries()) if (key.name === service) return value.instance;
1241
- throw new AlephaError(`Service not found: ${service}`);
1242
- }
1243
- const substitute = this.substitutions.get(service);
1244
- if (substitute) return this.inject(substitute.use, {
1245
- parent,
1246
- lifetime
1247
- });
1248
- const index = this.pendingInstantiations.indexOf(service);
1249
- if (index !== -1 && !transient) throw new CircularDependencyError(service.name, this.pendingInstantiations.slice(0, index).map((it) => it.name));
1250
- if (!transient) {
1251
- const match = registry.get(service);
1252
- if (match) {
1253
- if (!match.parents.includes(parent) && parent !== service) match.parents.push(parent);
1254
- return match.instance;
1255
- }
1256
- if (this.started) throw new ContainerLockedError(`Container is locked. No more services can be added. ${parent?.name} -> ${service.name}`);
1257
- }
1258
- const module = service[MODULE];
1259
- if (module && typeof module === "function") this.with(module);
1260
- if (this.has(service, { registry }) && !transient) return this.inject(service, {
1261
- parent,
1262
- lifetime
1263
- });
1264
- const instance = this.new(service, opts.args);
1265
- const definition = {
1266
- parents: [parent],
1267
- instance
1268
- };
1269
- if (!transient) registry.set(service, definition);
1270
- if (instance instanceof Module) {
1271
- this.modules.push(instance);
1272
- const parent$1 = __alephaRef.parent;
1273
- __alephaRef.parent = instance.constructor;
1274
- instance.register(this);
1275
- __alephaRef.parent = parent$1;
1276
- }
1277
- return instance;
1278
- }
1279
- /**
1280
- * Applies environment variables to the provided schema and state object.
1281
- *
1282
- * It replaces also all templated $ENV inside string values.
1283
- *
1284
- * @param schema - The schema object to apply environment variables to.
1285
- * @return The schema object with environment variables applied.
1286
- */
1287
- parseEnv(schema) {
1288
- if (this.cacheEnv.has(schema)) return this.cacheEnv.get(schema);
1289
- const config = this.codec.validate(schema, this.env);
1290
- for (const key in config) if (typeof config[key] === "string") for (const env in config) config[key] = config[key].replace(new RegExp(`\\$${env}`, "gim"), config[env]);
1291
- this.cacheEnv.set(schema, config);
1292
- return config;
1293
- }
1294
- /**
1295
- * Get all environment variable schemas and their parsed values.
1296
- *
1297
- * This is useful for DevTools to display all expected environment variables.
1298
- */
1299
- getEnvSchemas() {
1300
- const result = [];
1301
- for (const [schema, values] of this.cacheEnv.entries()) result.push({
1302
- schema,
1303
- values
1304
- });
1305
- return result;
1306
- }
1307
- /**
1308
- * Dump the current dependency graph of the App.
1309
- *
1310
- * This method returns a record where the keys are the names of the services.
1311
- */
1312
- graph() {
1313
- for (const [key] of this.substitutions.entries()) if (!this.has(key)) this.inject(key);
1314
- const graph = {};
1315
- for (const [provide, { parents }] of this.registry.entries()) {
1316
- graph[provide.name] = { from: parents.filter((it) => !!it).map((it) => it.name) };
1317
- const aliases = this.substitutions.entries().filter((it) => it[1].use === provide).map((it) => it[0].name).toArray();
1318
- if (aliases.length) graph[provide.name].as = aliases;
1319
- const module = Module.of(provide);
1320
- if (module) graph[provide.name].module = module.name;
1321
- }
1322
- return graph;
1323
- }
1324
- services(base) {
1325
- const list = [];
1326
- for (const [key, value] of this.registry.entries()) if (value.instance instanceof base) list.push(value.instance);
1327
- return list;
1328
- }
1329
- /**
1330
- * Get all primitives of the specified type.
1277
+ * Get all keys that exist in the state
1331
1278
  */
1332
- primitives(factory) {
1333
- if (typeof factory === "string") {
1334
- const key1 = factory.toLowerCase().replace("$", "");
1335
- const key2 = `${key1}primitive`;
1336
- for (const [key, value] of this.primitiveRegistry.entries()) {
1337
- const name = key.name.toLowerCase();
1338
- if (name === key1 || name === key2) return value;
1339
- }
1340
- return [];
1341
- }
1342
- return this.primitiveRegistry.get(factory[KIND]) ?? [];
1343
- }
1344
- new(service, args = []) {
1345
- this.pendingInstantiations.push(service);
1346
- __alephaRef.alepha = this;
1347
- __alephaRef.service = service;
1348
- const instance = isClass(service) ? new service(...args) : service(...args) ?? {};
1349
- const obj = instance;
1350
- for (const [key, value] of Object.entries(obj)) {
1351
- if (value instanceof Primitive) this.processPrimitive(value, key);
1352
- if (typeof value === "object" && value !== null && typeof value[OPTIONS] === "object" && "getter" in value[OPTIONS]) {
1353
- const getter = value[OPTIONS].getter;
1354
- Object.defineProperty(obj, key, { get: () => this.store.get(getter) });
1355
- }
1356
- }
1357
- this.pendingInstantiations.pop();
1358
- if (this.pendingInstantiations.length === 0) __alephaRef.alepha = void 0;
1359
- __alephaRef.service = this.pendingInstantiations[this.pendingInstantiations.length - 1];
1360
- return instance;
1361
- }
1362
- processPrimitive(value, propertyKey = "") {
1363
- value.config.propertyKey = propertyKey;
1364
- value.onInit();
1365
- const kind = value.constructor;
1366
- const list = this.primitiveRegistry.get(kind) ?? [];
1367
- this.primitiveRegistry.set(kind, [...list, value]);
1368
- }
1369
- };
1370
-
1371
- //#endregion
1372
- //#region ../../src/core/errors/AppNotStartedError.ts
1373
- var AppNotStartedError = class extends AlephaError {
1374
- name = "AppNotStartedError";
1375
- constructor() {
1376
- super("App not started. Please start the app before.");
1279
+ keys() {
1280
+ return Object.keys(this.store);
1377
1281
  }
1378
1282
  };
1379
1283
 
1380
1284
  //#endregion
1381
- //#region ../../src/core/helpers/createPagination.ts
1285
+ //#region ../../src/core/Alepha.ts
1382
1286
  /**
1383
- * Create a pagination object from an array of entities.
1287
+ * Core container of the Alepha framework.
1288
+ *
1289
+ * It is responsible for managing the lifecycle of services,
1290
+ * handling dependency injection,
1291
+ * and providing a unified interface for the application.
1292
+ *
1293
+ * @example
1294
+ * ```ts
1295
+ * import { Alepha, run } from "alepha";
1296
+ *
1297
+ * class MyService {
1298
+ * // business logic here
1299
+ * }
1300
+ *
1301
+ * const alepha = Alepha.create({
1302
+ * // state, env, and other properties
1303
+ * })
1304
+ *
1305
+ * alepha.with(MyService);
1306
+ *
1307
+ * run(alepha); // trigger .start (and .stop) automatically
1308
+ * ```
1309
+ *
1310
+ * ### Alepha Factory
1311
+ *
1312
+ * Alepha.create() is an enhanced version of new Alepha().
1313
+ * - It merges `process.env` with the provided state.env when available.
1314
+ * - It populates the test hooks for Vitest or Jest environments when available.
1384
1315
  *
1385
- * This is a pure function that works with any data source (databases, APIs, caches, arrays, etc.).
1386
- * It handles the core pagination logic including:
1387
- * - Slicing the content to the requested page size
1388
- * - Calculating pagination metadata (offset, page number, etc.)
1389
- * - Determining navigation state (isFirst, isLast)
1390
- * - Including sort metadata when provided
1316
+ * new Alepha() is fine if you don't need these helpers.
1391
1317
  *
1392
- * @param entities - The entities to paginate (should include one extra item to detect if there's a next page)
1393
- * @param limit - The limit of the pagination (page size)
1394
- * @param offset - The offset of the pagination (starting position)
1395
- * @param sort - Optional sort metadata to include in response
1396
- * @returns A complete Page object with content and metadata
1318
+ * ### Platforms & Environments
1319
+ *
1320
+ * Alepha is designed to work in various environments:
1321
+ * - **Browser**: Runs in the browser, using the global `window` object.
1322
+ * - **Serverless**: Runs in serverless environments like Vercel or Vite.
1323
+ * - **Test**: Runs in test environments like Jest or Vitest.
1324
+ * - **Production**: Runs in production environments, typically with NODE_ENV set to "production".
1325
+ * * You can check the current environment using the following methods:
1326
+ *
1327
+ * - `isBrowser()`: Returns true if the App is running in a browser environment.
1328
+ * - `isServerless()`: Returns true if the App is running in a serverless environment.
1329
+ * - `isTest()`: Returns true if the App is running in a test environment.
1330
+ * - `isProduction()`: Returns true if the App is running in a production environment.
1331
+ *
1332
+ * ### State & Environment
1333
+ *
1334
+ * The state of the Alepha container is stored in the `store` property.
1335
+ * Most important property is `store.env`, which contains the environment variables.
1397
1336
  *
1398
- * @example Basic pagination
1399
1337
  * ```ts
1400
- * const users = await fetchUsers({ limit: 11, offset: 0 }); // Fetch limit + 1
1401
- * const page = createPagination(users, 10, 0);
1402
- * // page.content has max 10 items
1403
- * // page.page.isLast tells us if there are more pages
1338
+ * const alepha = Alepha.create({ env: { MY_VAR: "value" } });
1339
+ *
1340
+ * // You can access the environment variables using alepha.env
1341
+ * console.log(alepha.env.MY_VAR); // "value"
1342
+ *
1343
+ * // But you should use $env() primitive to get typed values from the environment.
1344
+ * class App {
1345
+ * env = $env(
1346
+ * t.object({
1347
+ * MY_VAR: t.text(),
1348
+ * })
1349
+ * );
1350
+ * }
1404
1351
  * ```
1405
1352
  *
1406
- * @example With sorting
1353
+ * ### Modules
1354
+ *
1355
+ * Modules are a way to group services together.
1356
+ * You can register a module using the `$module` primitive.
1357
+ *
1407
1358
  * ```ts
1408
- * const page = createPagination(
1409
- * entities,
1410
- * 10,
1411
- * 0,
1412
- * [{ column: "name", direction: "asc" }]
1413
- * );
1359
+ * import { $module } from "alepha";
1360
+ *
1361
+ * class MyLib {}
1362
+ *
1363
+ * const myModule = $module({
1364
+ * name: "my.project.module",
1365
+ * services: [MyLib],
1366
+ * });
1414
1367
  * ```
1415
1368
  *
1416
- * @example In a custom service
1369
+ * Do not use modules for small applications.
1370
+ *
1371
+ * ### Hooks
1372
+ *
1373
+ * Hooks are a way to run async functions from all registered providers/services.
1374
+ * You can register a hook using the `$hook` primitive.
1375
+ *
1417
1376
  * ```ts
1418
- * class MyService {
1419
- * async listItems(page: number, size: number) {
1420
- * const items = await this.fetchItems({ limit: size + 1, offset: page * size });
1421
- * return createPagination(items, size, page * size);
1422
- * }
1423
- * }
1377
+ * import { $hook } from "alepha";
1378
+ *
1379
+ * class App {
1380
+ * log = $logger();
1381
+ * onCustomerHook = $hook({
1382
+ * on: "my:custom:hook",
1383
+ * handler: () => {
1384
+ * this.log?.info("App is being configured");
1385
+ * },
1386
+ * });
1387
+ * }
1388
+ *
1389
+ * Alepha.create()
1390
+ * .with(App)
1391
+ * .start()
1392
+ * .then(alepha => alepha.events.emit("my:custom:hook"));
1424
1393
  * ```
1394
+ *
1395
+ * Hooks are fully typed. You can create your own hooks by using module augmentation:
1396
+ *
1397
+ * ```ts
1398
+ * declare module "alepha" {
1399
+ * interface Hooks {
1400
+ * "my:custom:hook": {
1401
+ * arg1: string;
1402
+ * }
1403
+ * }
1404
+ * }
1405
+ * ```
1406
+ *
1407
+ * @module alepha
1425
1408
  */
1426
- function createPagination(entities, limit = 10, offset = 0, sort) {
1427
- const content = entities.slice(0, limit);
1428
- const hasNext = entities.length === limit + 1;
1429
- const pageNumber = Math.floor(offset / limit);
1430
- return {
1431
- content,
1432
- page: {
1433
- number: pageNumber,
1434
- size: limit,
1435
- offset,
1436
- numberOfElements: content.length,
1437
- isEmpty: content.length === 0,
1438
- isFirst: pageNumber === 0,
1439
- isLast: !hasNext,
1440
- ...sort && sort.length > 0 ? { sort: {
1441
- sorted: true,
1442
- fields: sort.map((s) => ({
1443
- field: s.column,
1444
- direction: s.direction
1445
- }))
1446
- } } : {}
1447
- }
1448
- };
1449
- }
1450
-
1451
- //#endregion
1452
- //#region ../../src/core/helpers/FileLike.ts
1453
- const isTypeFile = (value) => {
1454
- return value && typeof value === "object" && "format" in value && value.format === "binary";
1455
- };
1456
- const isFileLike = (value) => {
1457
- return !!value && typeof value === "object" && !Array.isArray(value) && typeof value.name === "string" && typeof value.type === "string" && typeof value.size === "number" && typeof value.stream.bind(value) === "function";
1458
- };
1459
-
1460
- //#endregion
1461
- //#region ../../src/core/providers/TypeProvider.ts
1462
- const isUUID = Format.IsUuid;
1463
- var TypeGuard = class {
1464
- isBigInt = (value) => Type.IsString(value) && "format" in value && value.format === "bigint";
1465
- isUUID = (value) => Type.IsString(value) && "format" in value && value.format === "uuid";
1466
- isObject = Type.IsObject;
1467
- isNumber = Type.IsNumber;
1468
- isString = Type.IsString;
1469
- isBoolean = Type.IsBoolean;
1470
- isAny = Type.IsAny;
1471
- isArray = Type.IsArray;
1472
- isOptional = Type.IsOptional;
1473
- isUnion = Type.IsUnion;
1474
- isInteger = Type.IsInteger;
1475
- isNull = Type.IsNull;
1476
- isUndefined = Type.IsUndefined;
1477
- isUnsafe = Type.IsUnsafe;
1478
- isRecord = Type.IsRecord;
1479
- isTuple = Type.IsTuple;
1480
- isVoid = Type.IsVoid;
1481
- isLiteral = Type.IsLiteral;
1482
- isSchema = Type.IsSchema;
1483
- isFile = isTypeFile;
1484
- isDateTime = (schema) => {
1485
- return t.schema.isString(schema) && schema.format === "date-time";
1486
- };
1487
- isDate = (schema) => {
1488
- return t.schema.isString(schema) && schema.format === "date";
1489
- };
1490
- isTime = (schema) => {
1491
- return t.schema.isString(schema) && schema.format === "time";
1492
- };
1493
- isDuration = (schema) => {
1494
- return t.schema.isString(schema) && schema.format === "duration";
1495
- };
1496
- };
1497
- var TypeProvider = class TypeProvider {
1498
- static format = Format;
1499
- static {
1500
- Format.Set("bigint", (value) => TypeProvider.isValidBigInt(value));
1501
- }
1502
- static translateError(error, locale) {
1503
- if (!locale) return error.cause.message;
1504
- for (const [key, value] of Object.entries(Locale)) {
1505
- if (key === "Set" || key === "Get" || key === "Reset") continue;
1506
- if (key === locale || key.startsWith(`${locale}_`)) return value(error.cause);
1507
- }
1508
- return error.cause.message;
1509
- }
1510
- static setLocale(locale) {
1511
- for (const [key, value] of Object.entries(Locale)) {
1512
- if (key === "Set" || key === "Get" || key === "Reset") continue;
1513
- if (key === locale || key.startsWith(`${locale}_`)) {
1514
- Locale.Set(value);
1515
- return;
1516
- }
1409
+ var Alepha = class Alepha {
1410
+ /**
1411
+ * Creates a new instance of the Alepha container with some helpers:
1412
+ *
1413
+ * - merges `process.env` with the provided state.env when available.
1414
+ * - populates the test hooks for Vitest or Jest environments when available.
1415
+ *
1416
+ * If you are not interested about these helpers, you can use the constructor directly.
1417
+ */
1418
+ static create(state = {}) {
1419
+ if (typeof process === "object" && typeof process.env === "object") {
1420
+ state.env = {
1421
+ ...state.env,
1422
+ ...process.env
1423
+ };
1424
+ if (process.env.NODE_ENV === "production") state.env.NODE_ENV ??= "production";
1517
1425
  }
1518
- throw new AlephaError(`Locale not found: ${locale}`);
1519
- }
1520
- static isValidBigInt(value) {
1521
- if (typeof value === "number") return Number.isInteger(value);
1522
- if (!value.trim()) return false;
1523
- if (!/^-?\d+$/.test(value)) return false;
1524
- try {
1525
- BigInt(value);
1526
- return true;
1527
- } catch {
1528
- return false;
1426
+ const alepha = new Alepha(state);
1427
+ if (alepha.isTest()) {
1428
+ const g = globalThis;
1429
+ const beforeAll = state["alepha.test.beforeAll"] ?? g.beforeAll;
1430
+ const afterAll = state["alepha.test.afterAll"] ?? g.afterAll;
1431
+ const afterEach = state["alepha.test.afterEach"] ?? g.afterEach;
1432
+ const onTestFinished = state["alepha.test.onTestFinished"] ?? g.onTestFinished;
1433
+ beforeAll?.(() => alepha.start());
1434
+ afterAll?.(() => alepha.stop());
1435
+ try {
1436
+ onTestFinished?.(() => alepha.stop());
1437
+ } catch (_error) {}
1438
+ alepha.store.set("alepha.test.beforeAll", beforeAll).set("alepha.test.afterAll", afterAll).set("alepha.test.afterEach", afterEach).set("alepha.test.onTestFinished", onTestFinished);
1529
1439
  }
1440
+ return alepha;
1530
1441
  }
1531
1442
  /**
1532
- * Default maximum length for strings.
1533
- *
1534
- * It can be set to a larger value:
1535
- * ```ts
1536
- * TypeProvider.DEFAULT_STRING_MAX_LENGTH = 1000000;
1537
- * TypeProvider.DEFAULT_STRING_MAX_LENGTH = undefined; // no limit (not recommended)
1538
- * ```
1443
+ * Flag indicating whether the App won't accept any further changes.
1444
+ * Pass to true when #start() is called.
1445
+ */
1446
+ locked = false;
1447
+ /**
1448
+ * True if the App has been configured.
1449
+ */
1450
+ configured = false;
1451
+ /**
1452
+ * True if the App has started.
1453
+ */
1454
+ started = false;
1455
+ /**
1456
+ * True if the App is ready.
1539
1457
  */
1540
- static DEFAULT_STRING_MAX_LENGTH = 255;
1458
+ ready = false;
1541
1459
  /**
1542
- * Maximum length for short strings, such as names or titles.
1460
+ * A promise that resolves when the App has started.
1543
1461
  */
1544
- static DEFAULT_SHORT_STRING_MAX_LENGTH = 64;
1462
+ starting;
1545
1463
  /**
1546
- * Maximum length for long strings, such as descriptions or comments.
1547
- * It can be overridden in the string options.
1548
- *
1549
- * It can be set to a larger value:
1550
- * ```ts
1551
- * TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH = 2048;
1552
- * ```
1464
+ * During the instantiation process, we keep a list of pending instantiations.
1465
+ * > It allows us to detect circular dependencies.
1553
1466
  */
1554
- static DEFAULT_LONG_STRING_MAX_LENGTH = 1024;
1467
+ pendingInstantiations = [];
1555
1468
  /**
1556
- * Maximum length for rich strings, such as HTML or Markdown.
1557
- * This is a large value to accommodate rich text content.
1558
- * > It's also the maximum length of PG's TEXT type.
1469
+ * Cache for environment variables.
1470
+ * > It allows us to avoid parsing the same schema multiple times.
1471
+ */
1472
+ cacheEnv = /* @__PURE__ */ new Map();
1473
+ /**
1474
+ * List of modules that are registered in the container.
1559
1475
  *
1560
- * It can be overridden in the string options.
1476
+ * Modules are used to group services and provide a way to register them in the container.
1477
+ */
1478
+ modules = [];
1479
+ /**
1480
+ * List of service substitutions.
1561
1481
  *
1562
- * It can be set to a larger value:
1563
- * ```ts
1564
- * TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH = 1000000;
1565
- * ```
1482
+ * Services registered here will be replaced by the specified service when injected.
1566
1483
  */
1567
- static DEFAULT_RICH_STRING_MAX_LENGTH = 65535;
1484
+ substitutions = /* @__PURE__ */ new Map();
1568
1485
  /**
1569
- * Maximum number of items in an array.
1570
- * This is a default value to prevent excessive memory usage.
1571
- * It can be overridden in the array options.
1486
+ * Registry of primitives.
1572
1487
  */
1573
- static DEFAULT_ARRAY_MAX_ITEMS = 1e3;
1574
- raw = Type;
1575
- any = Type.Any;
1576
- void = Type.Void;
1577
- undefined = Type.Undefined;
1578
- record = Type.Record;
1579
- union = Type.Union;
1580
- tuple = Type.Tuple;
1581
- null = Type.Null;
1582
- const = Type.Literal;
1583
- options = Type.Options;
1488
+ primitiveRegistry = /* @__PURE__ */ new Map();
1584
1489
  /**
1585
- * Type guards to check the type of schema.
1586
- * This is not a runtime type check, but a compile-time type guard.
1587
- *
1588
- * @example
1589
- * ```ts
1590
- * if (t.schema.isString(schema)) {
1591
- * // schema is TString
1592
- * }
1593
- * ```
1490
+ * List of all services + how they are provided.
1594
1491
  */
1595
- schema = new TypeGuard();
1596
- extend(schema, properties, options) {
1597
- return Type.Interface(Array.isArray(schema) ? schema : [schema], properties, {
1598
- additionalProperties: false,
1599
- ...options
1600
- });
1601
- }
1602
- pick(schema, keys, options) {
1603
- return Type.Pick(schema, keys, {
1604
- additionalProperties: false,
1605
- ...options
1606
- });
1607
- }
1608
- omit(schema, keys, options) {
1609
- return Type.Omit(schema, keys, {
1610
- additionalProperties: false,
1611
- ...options
1612
- });
1613
- }
1614
- partial(schema, options) {
1615
- return Type.Partial(schema, {
1616
- additionalProperties: false,
1617
- ...options
1618
- });
1619
- }
1492
+ registry = /* @__PURE__ */ new Map();
1620
1493
  /**
1621
- * Create a schema for an object.
1622
- * By default, additional properties are not allowed.
1494
+ * Node.js feature that allows to store context across asynchronous calls.
1623
1495
  *
1624
- * @example
1625
- * ```ts
1626
- * const userSchema = t.object({
1627
- * id: t.integer(),
1628
- * name: t.string(),
1629
- * });
1630
- * ```
1496
+ * This is used for logging, tracing, and other context-related features.
1497
+ *
1498
+ * Mocked for browser environments.
1631
1499
  */
1632
- object(properties, options) {
1633
- return Type.Object(properties, {
1634
- additionalProperties: false,
1635
- ...options
1636
- });
1637
- }
1500
+ context;
1638
1501
  /**
1639
- * Create a schema for an array.
1640
- * By default, the maximum number of items is limited to prevent excessive memory usage.
1502
+ * Event manager to handle lifecycle events and custom events.
1503
+ */
1504
+ events;
1505
+ /**
1506
+ * State manager to store arbitrary values.
1507
+ */
1508
+ store;
1509
+ /**
1510
+ * Codec manager for encoding and decoding data with different formats.
1641
1511
  *
1642
- * @see TypeProvider.DEFAULT_ARRAY_MAX_ITEMS
1512
+ * Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface.
1643
1513
  */
1644
- array(schema, options) {
1645
- return Type.Array(schema, {
1646
- maxItems: TypeProvider.DEFAULT_ARRAY_MAX_ITEMS,
1647
- ...options
1648
- });
1514
+ codec;
1515
+ /**
1516
+ * Get logger instance.
1517
+ */
1518
+ get log() {
1519
+ return this.store.get("alepha.logger");
1649
1520
  }
1650
1521
  /**
1651
- * Create a schema for a string.
1652
- * For db or input fields, consider using `t.text()` instead, which has length limits.
1653
- *
1654
- * If you need a string with specific format (e.g. email, uuid), consider using the corresponding method (e.g. `t.email()`, `t.uuid()`).
1522
+ * The environment variables for the App.
1655
1523
  */
1656
- string(options = {}) {
1657
- return Type.String({ ...options });
1524
+ get env() {
1525
+ return this.store.get("env") ?? {};
1526
+ }
1527
+ constructor(state = {}) {
1528
+ this.store = this.inject(StateManager, { args: [state] });
1529
+ this.events = this.inject(EventManager);
1530
+ this.events.logFn = () => this.log;
1531
+ this.context = this.inject(AlsProvider);
1532
+ this.codec = this.inject(CodecManager);
1533
+ }
1534
+ set(target, value) {
1535
+ this.store.set(target, value);
1536
+ return this;
1658
1537
  }
1659
1538
  /**
1660
- * Create a schema for a string with length limits.
1661
- * For internal strings without length limits, consider using `t.string()` instead.
1539
+ * True when start() is called.
1662
1540
  *
1663
- * Default size is "regular", which has a max length of 255 characters.
1541
+ * -> No more services can be added, it's over, bye!
1664
1542
  */
1665
- text(options = {}) {
1666
- const { size, ...rest } = options;
1667
- const maxLength = size === "short" ? TypeProvider.DEFAULT_SHORT_STRING_MAX_LENGTH : size === "long" ? TypeProvider.DEFAULT_LONG_STRING_MAX_LENGTH : size === "rich" ? TypeProvider.DEFAULT_RICH_STRING_MAX_LENGTH : TypeProvider.DEFAULT_STRING_MAX_LENGTH;
1668
- return Type.String({
1669
- maxLength,
1670
- "~options": {
1671
- trim: options.trim ?? true,
1672
- lowercase: options.lowercase ?? false
1673
- },
1674
- ...rest
1675
- });
1543
+ isLocked() {
1544
+ return this.locked;
1676
1545
  }
1677
1546
  /**
1678
- * Create a schema for a JSON object.
1679
- * This is a record with string keys and any values.
1547
+ * Returns whether the App is configured.
1548
+ *
1549
+ * It means that Alepha#configure() has been called.
1550
+ *
1551
+ * > By default, configure() is called automatically when start() is called, but you can also call it manually.
1680
1552
  */
1681
- json(options) {
1682
- return t.record(t.text(), t.any(), options);
1553
+ isConfigured() {
1554
+ return this.configured;
1683
1555
  }
1684
1556
  /**
1685
- * Create a schema for a boolean.
1557
+ * Returns whether the App has started.
1558
+ *
1559
+ * It means that #start() has been called but maybe not all services are ready.
1686
1560
  */
1687
- boolean(options) {
1688
- return Type.Boolean({ ...options });
1561
+ isStarted() {
1562
+ return this.started;
1689
1563
  }
1690
1564
  /**
1691
- * Create a schema for a number.
1565
+ * True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
1692
1566
  */
1693
- number(options) {
1694
- return Type.Number({ ...options });
1567
+ isReady() {
1568
+ return this.ready;
1695
1569
  }
1696
1570
  /**
1697
- * Create a schema for an integer.
1571
+ * True if the App is running in a Continuous Integration environment.
1698
1572
  */
1699
- integer(options) {
1700
- return Type.Integer({ ...options });
1701
- }
1702
- int32(options) {
1703
- return Type.Integer({
1704
- minimum: -2147483647,
1705
- maximum: 2147483647,
1706
- ...options
1707
- });
1573
+ isCI() {
1574
+ if (this.env.GITHUB_ACTIONS) return true;
1575
+ return !!this.env.CI;
1708
1576
  }
1709
1577
  /**
1710
- * Mimic a signed 64-bit integer.
1711
- *
1712
- * This is NOT a true int64, as JavaScript cannot represent all int64 values.
1713
- * It is a number that is an integer and between -9007199254740991 and 9007199254740991.
1714
- * Use `t.bigint()` for true int64 values represented as strings.
1578
+ * True if the App is running in a browser environment.
1715
1579
  */
1716
- int64(options) {
1717
- return Type.Number({
1718
- format: "int64",
1719
- multipleOf: 1,
1720
- minimum: -9007199254740991,
1721
- maximum: 9007199254740991,
1722
- ...options
1723
- });
1580
+ isBrowser() {
1581
+ return typeof window !== "undefined";
1724
1582
  }
1725
1583
  /**
1726
- * Make a schema optional.
1584
+ * Returns whether the App is running in Vite dev mode.
1727
1585
  */
1728
- optional(schema) {
1729
- return Type.Optional(schema);
1586
+ isViteDev() {
1587
+ if (this.isBrowser()) return false;
1588
+ return !!this.env.VITE_ALEPHA_DEV;
1589
+ }
1590
+ isBun() {
1591
+ return "Bun" in globalThis;
1730
1592
  }
1731
1593
  /**
1732
- * Make a schema nullable.
1594
+ * Returns whether the App is running in a serverless environment.
1733
1595
  */
1734
- nullable(schema, options) {
1735
- return Type.Union([Type.Null(), schema], options);
1596
+ isServerless() {
1597
+ if (this.isBrowser()) return false;
1598
+ if (this.env.VERCEL_REGION) return true;
1599
+ if (typeof global === "object" && typeof global.Cloudflare === "object") return true;
1600
+ return false;
1736
1601
  }
1737
1602
  /**
1738
- * Create a schema that maps all properties of an object schema to nullable.
1739
- */
1740
- nullify = (schema, options) => Type.Mapped(Type.Identifier("K"), Type.KeyOf(schema), Type.Ref("K"), Type.Union([Type.Index(schema, Type.Ref("K")), Type.Null()]), options);
1741
- /**
1742
- * Create a schema for a string enum.
1603
+ * Returns whether the App is in test mode. (Running in a test environment)
1604
+ *
1605
+ * > This is automatically set when running tests with Jest or Vitest.
1743
1606
  */
1744
- enum(values, options) {
1745
- return Type.Unsafe(t.text({
1746
- enum: values,
1747
- pattern: values.map((v) => `^${v}$`).join("|"),
1748
- ...options
1749
- }));
1607
+ isTest() {
1608
+ return this.env.NODE_ENV === "test";
1750
1609
  }
1751
1610
  /**
1752
- * Create a schema for a bigint represented as a string.
1753
- * This is a string that validates bigint format (e.g. "123456789").
1611
+ * Returns whether the App is in production mode. (Running in a production environment)
1612
+ *
1613
+ * > This is automatically set by Vite or Vercel. However, you have to set it manually when running Docker apps.
1754
1614
  */
1755
- bigint(options) {
1756
- return t.string({
1757
- ...options,
1758
- format: "bigint"
1759
- });
1615
+ isProduction() {
1616
+ return this.env.NODE_ENV === "production";
1760
1617
  }
1761
1618
  /**
1762
- * Create a schema for a URL represented as a string.
1619
+ * Starts the App.
1620
+ *
1621
+ * - Lock any further changes to the container.
1622
+ * - Run "configure" hook for all services. Primitives will be processed.
1623
+ * - Run "start" hook for all services. Providers will connect/listen/...
1624
+ * - Run "ready" hook for all services. This is the point where the App is ready to serve requests.
1625
+ *
1626
+ * @return A promise that resolves when the App has started.
1763
1627
  */
1764
- url(options) {
1765
- return this.string({
1766
- ...options,
1767
- format: "url"
1768
- });
1628
+ async start() {
1629
+ if (this.ready) {
1630
+ this.log?.debug("App is already started, skipping...");
1631
+ return this;
1632
+ }
1633
+ if (this.starting) {
1634
+ this.log?.warn("App is already starting, waiting for it to finish...");
1635
+ return this.starting.promise;
1636
+ }
1637
+ this.starting = Promise.withResolvers();
1638
+ const now = Date.now();
1639
+ this.log?.info("Starting App...");
1640
+ for (const [key] of this.substitutions.entries()) this.inject(key);
1641
+ const target = this.store.get("alepha.target");
1642
+ if (target) {
1643
+ this.registry = /* @__PURE__ */ new Map();
1644
+ this.primitiveRegistry = /* @__PURE__ */ new Map();
1645
+ this.with(target);
1646
+ }
1647
+ this.locked = true;
1648
+ await this.events.emit("configure", this, { log: true });
1649
+ this.configured = true;
1650
+ await this.events.emit("start", this, { log: true });
1651
+ this.started = true;
1652
+ await this.events.emit("ready", this, { log: true });
1653
+ this.log?.info(`App is now ready [${Date.now() - now}ms]`);
1654
+ this.ready = true;
1655
+ this.starting.resolve(this);
1656
+ this.starting = void 0;
1657
+ return this;
1769
1658
  }
1770
1659
  /**
1771
- * Create a schema for binary data represented as a base64 string.
1660
+ * Stops the App.
1661
+ *
1662
+ * - Run "stop" hook for all services.
1663
+ *
1664
+ * Stop will NOT reset the container.
1665
+ * Stop will NOT unlock the container.
1666
+ *
1667
+ * > Stop is used to gracefully shut down the application, nothing more. There is no "restart".
1668
+ *
1669
+ * @return A promise that resolves when the App has stopped.
1772
1670
  */
1773
- binary(options) {
1774
- return this.string({
1775
- ...options,
1776
- format: "binary"
1671
+ async stop() {
1672
+ if (!this.started) return;
1673
+ this.log?.info("Stopping App...");
1674
+ await this.events.emit("stop", this, {
1675
+ reverse: true,
1676
+ log: true
1777
1677
  });
1678
+ this.log?.info("App is now off");
1679
+ this.started = false;
1680
+ this.ready = false;
1778
1681
  }
1779
1682
  /**
1780
- * Create a schema for uuid.
1683
+ * Check if entry is registered in the container.
1781
1684
  */
1782
- uuid(options) {
1783
- return this.string({
1784
- ...options,
1785
- format: "uuid"
1786
- });
1685
+ has(entry, opts = {}) {
1686
+ if (entry === Alepha) return true;
1687
+ const { inStack = true, inRegistry = true, inSubstitutions = true, registry = this.registry } = opts;
1688
+ const { provide } = typeof entry === "object" && "provide" in entry ? entry : { provide: entry };
1689
+ if (inSubstitutions) {
1690
+ if (this.substitutions.get(provide)) return true;
1691
+ }
1692
+ if (inRegistry) {
1693
+ if (registry.get(provide)) return true;
1694
+ }
1695
+ if (inStack) {
1696
+ const substitute = this.substitutions.get(provide)?.use;
1697
+ if (substitute && this.pendingInstantiations.includes(substitute)) return true;
1698
+ return this.pendingInstantiations.includes(provide);
1699
+ }
1700
+ return false;
1787
1701
  }
1788
1702
  /**
1789
- * Create a schema for a file-like object.
1703
+ * Registers the specified service in the container.
1790
1704
  *
1791
- * File like mimics the File API in browsers, but is adapted to work in Node.js as well.
1705
+ * - If the service is ALREADY registered, the method does nothing.
1706
+ * - If the service is NOT registered, a new instance is created and registered.
1792
1707
  *
1793
- * Implementation of file-like objects is handled by "alepha/file" package.
1708
+ * Method is chainable, so you can register multiple services in a single call.
1709
+ *
1710
+ * > ServiceEntry allows to provide a service **substitution** feature.
1711
+ *
1712
+ * @example
1713
+ * ```ts
1714
+ * class A { value = "a"; }
1715
+ * class B { value = "b"; }
1716
+ * class M { a = $inject(A); }
1717
+ *
1718
+ * Alepha.create().with({ provide: A, use: B }).get(M).a.value; // "b"
1719
+ * ```
1720
+ *
1721
+ * > **Substitution** is an advanced feature that allows you to replace a service with another service.
1722
+ * > It's useful for testing or for providing different implementations of a service.
1723
+ * > If you are interested in configuring a service, use Alepha#configure() instead.
1724
+ *
1725
+ * @param serviceEntry - The service to register in the container.
1726
+ * @return Current instance of Alepha.
1794
1727
  */
1795
- file(options) {
1796
- return Type.Unsafe(Type.Any({
1797
- [OPTIONS]: options,
1798
- format: "binary"
1799
- }));
1728
+ with(serviceEntry) {
1729
+ const entry = "default" in serviceEntry ? serviceEntry.default : serviceEntry;
1730
+ if (this.has(entry, {
1731
+ inSubstitutions: false,
1732
+ inRegistry: false
1733
+ })) return this;
1734
+ if (typeof entry === "object") {
1735
+ if (entry.provide === entry.use) {
1736
+ this.inject(entry.provide);
1737
+ return this;
1738
+ }
1739
+ if (!this.substitutions.has(entry.provide) && !this.has(entry.provide)) {
1740
+ if (this.started) throw new ContainerLockedError();
1741
+ if (MODULE in entry.provide && typeof entry.provide[MODULE] === "function") entry.use[MODULE] ??= entry.provide[MODULE];
1742
+ this.substitutions.set(entry.provide, { use: entry.use });
1743
+ } else if (!entry.optional) throw new TooLateSubstitutionError(entry.provide.name, entry.use.name);
1744
+ return this;
1745
+ }
1746
+ this.inject(entry);
1747
+ return this;
1800
1748
  }
1801
1749
  /**
1802
- * @experimental
1750
+ * Get an instance of the specified service from the container.
1751
+ *
1752
+ * @see {@link InjectOptions} for the available options.
1803
1753
  */
1804
- stream() {
1805
- return Type.Unsafe(Type.Any({
1806
- format: "stream",
1807
- type: "string"
1808
- }));
1809
- }
1810
- email(options) {
1811
- return this.text({
1812
- ...options,
1813
- format: "email",
1814
- trim: true,
1815
- lowercase: true
1816
- });
1817
- }
1818
- e164(options) {
1819
- return this.text({
1820
- ...options,
1821
- description: "Phone number in E.164 format, e.g. +1234567890.",
1822
- pattern: "^\\+[1-9]\\d{1,14}$"
1823
- });
1824
- }
1825
- bcp47(options) {
1826
- return this.text({
1827
- ...options,
1828
- description: "BCP 47 language tag, e.g. en, en-US, fr, fr-CA.",
1829
- pattern: "^[a-z]{2,3}(?:-[A-Z]{2})?$"
1754
+ inject(service, opts = {}) {
1755
+ const lifetime = opts.lifetime ?? "singleton";
1756
+ const parent = opts.parent !== void 0 ? opts.parent : __alephaRef?.parent ?? Alepha;
1757
+ const transient = lifetime === "transient";
1758
+ const registry = lifetime === "scoped" ? this.context.get("registry") ?? this.registry : this.registry;
1759
+ if (service === Alepha) return this;
1760
+ if (typeof service === "string") {
1761
+ for (const [key, value] of registry.entries()) if (key.name === service) return value.instance;
1762
+ throw new AlephaError(`Service not found: ${service}`);
1763
+ }
1764
+ const substitute = this.substitutions.get(service);
1765
+ if (substitute) return this.inject(substitute.use, {
1766
+ parent,
1767
+ lifetime
1830
1768
  });
1831
- }
1832
- /**
1833
- * Create a schema for short text, such as names or titles.
1834
- * Default max length is 64 characters.
1835
- */
1836
- shortText(options) {
1837
- return this.text({
1838
- size: "short",
1839
- ...options
1769
+ const index = this.pendingInstantiations.indexOf(service);
1770
+ if (index !== -1 && !transient) throw new CircularDependencyError(service.name, this.pendingInstantiations.slice(0, index).map((it) => it.name));
1771
+ if (!transient) {
1772
+ const match = registry.get(service);
1773
+ if (match) {
1774
+ if (!match.parents.includes(parent) && parent !== service) match.parents.push(parent);
1775
+ return match.instance;
1776
+ }
1777
+ if (this.started) throw new ContainerLockedError(`Container is locked. No more services can be added. ${parent?.name} -> ${service.name}`);
1778
+ }
1779
+ const module = service[MODULE];
1780
+ if (module && typeof module === "function") this.with(module);
1781
+ if (this.has(service, { registry }) && !transient) return this.inject(service, {
1782
+ parent,
1783
+ lifetime
1840
1784
  });
1785
+ const instance = this.new(service, opts.args);
1786
+ const definition = {
1787
+ parents: [parent],
1788
+ instance
1789
+ };
1790
+ if (!transient) registry.set(service, definition);
1791
+ if (instance instanceof Module) {
1792
+ this.modules.push(instance);
1793
+ const parent$1 = __alephaRef.parent;
1794
+ __alephaRef.parent = instance.constructor;
1795
+ instance.register(this);
1796
+ __alephaRef.parent = parent$1;
1797
+ }
1798
+ return instance;
1841
1799
  }
1842
1800
  /**
1843
- * Create a schema for long text, such as descriptions or comments.
1844
- * Default max length is 1024 characters.
1801
+ * Applies environment variables to the provided schema and state object.
1802
+ *
1803
+ * It replaces also all templated $ENV inside string values.
1804
+ *
1805
+ * @param schema - The schema object to apply environment variables to.
1806
+ * @return The schema object with environment variables applied.
1845
1807
  */
1846
- longText(options) {
1847
- return this.text({
1848
- size: "long",
1849
- ...options
1850
- });
1808
+ parseEnv(schema) {
1809
+ if (this.cacheEnv.has(schema)) return this.cacheEnv.get(schema);
1810
+ const config = this.codec.validate(schema, this.env);
1811
+ for (const key in config) if (typeof config[key] === "string") for (const env in config) config[key] = config[key].replace(new RegExp(`\\$${env}`, "gim"), config[env]);
1812
+ this.cacheEnv.set(schema, config);
1813
+ return config;
1851
1814
  }
1852
1815
  /**
1853
- * Create a schema for rich text, such as HTML or Markdown.
1854
- * Default max length is 65535 characters.
1816
+ * Get all environment variable schemas and their parsed values.
1817
+ *
1818
+ * This is useful for DevTools to display all expected environment variables.
1855
1819
  */
1856
- richText(options) {
1857
- return this.text({
1858
- size: "rich",
1859
- ...options
1820
+ getEnvSchemas() {
1821
+ const result = [];
1822
+ for (const [schema, values] of this.cacheEnv.entries()) result.push({
1823
+ schema,
1824
+ values
1860
1825
  });
1826
+ return result;
1861
1827
  }
1862
1828
  /**
1863
- * Create a schema for a string enum e.g. LIKE_THIS.
1829
+ * Dump the current dependency graph of the App.
1830
+ *
1831
+ * This method returns a record where the keys are the names of the services.
1864
1832
  */
1865
- snakeCase = (options) => this.text({
1866
- pattern: "^[A-Z_-]+$",
1867
- ...options
1868
- });
1833
+ graph() {
1834
+ for (const [key] of this.substitutions.entries()) if (!this.has(key)) this.inject(key);
1835
+ const graph = {};
1836
+ for (const [provide, { parents }] of this.registry.entries()) {
1837
+ graph[provide.name] = { from: parents.filter((it) => !!it).map((it) => it.name) };
1838
+ const aliases = this.substitutions.entries().filter((it) => it[1].use === provide).map((it) => it[0].name).toArray();
1839
+ if (aliases.length) graph[provide.name].as = aliases;
1840
+ const module = Module.of(provide);
1841
+ if (module) graph[provide.name].module = module.name;
1842
+ }
1843
+ return graph;
1844
+ }
1845
+ services(base) {
1846
+ const list = [];
1847
+ for (const [key, value] of this.registry.entries()) if (value.instance instanceof base) list.push(value.instance);
1848
+ return list;
1849
+ }
1869
1850
  /**
1870
- * Create a schema for an object with a value and label.
1851
+ * Get all primitives of the specified type.
1871
1852
  */
1872
- valueLabel = (options) => this.object({
1873
- value: this.snakeCase({ description: "Machine-readable value." }),
1874
- label: this.text({ description: "Human-readable label." }),
1875
- description: this.optional(this.text({
1876
- description: "Description of the value.",
1877
- size: "long"
1878
- }))
1879
- }, options);
1880
- datetime = (options) => t.text({
1881
- ...options,
1882
- format: "date-time"
1883
- });
1884
- date = (options) => t.text({
1885
- ...options,
1886
- format: "date"
1887
- });
1888
- time = (options) => t.text({
1889
- ...options,
1890
- format: "time"
1891
- });
1892
- duration = (options) => t.text({
1893
- ...options,
1894
- format: "duration"
1895
- });
1853
+ primitives(factory) {
1854
+ if (typeof factory === "string") {
1855
+ const key1 = factory.toLowerCase().replace("$", "");
1856
+ const key2 = `${key1}primitive`;
1857
+ for (const [key, value] of this.primitiveRegistry.entries()) {
1858
+ const name = key.name.toLowerCase();
1859
+ if (name === key1 || name === key2) return value;
1860
+ }
1861
+ return [];
1862
+ }
1863
+ return this.primitiveRegistry.get(factory[KIND]) ?? [];
1864
+ }
1865
+ new(service, args = []) {
1866
+ this.pendingInstantiations.push(service);
1867
+ __alephaRef.alepha = this;
1868
+ __alephaRef.service = service;
1869
+ const instance = isClass(service) ? new service(...args) : service(...args) ?? {};
1870
+ const obj = instance;
1871
+ for (const [key, value] of Object.entries(obj)) {
1872
+ if (value instanceof Primitive) this.processPrimitive(value, key);
1873
+ if (typeof value === "object" && value !== null && typeof value[OPTIONS] === "object" && "getter" in value[OPTIONS]) {
1874
+ const getter = value[OPTIONS].getter;
1875
+ Object.defineProperty(obj, key, { get: () => this.store.get(getter) });
1876
+ }
1877
+ }
1878
+ this.pendingInstantiations.pop();
1879
+ if (this.pendingInstantiations.length === 0) __alephaRef.alepha = void 0;
1880
+ __alephaRef.service = this.pendingInstantiations[this.pendingInstantiations.length - 1];
1881
+ return instance;
1882
+ }
1883
+ processPrimitive(value, propertyKey = "") {
1884
+ value.config.propertyKey = propertyKey;
1885
+ value.onInit();
1886
+ const kind = value.constructor;
1887
+ const list = this.primitiveRegistry.get(kind) ?? [];
1888
+ this.primitiveRegistry.set(kind, [...list, value]);
1889
+ }
1890
+ };
1891
+
1892
+ //#endregion
1893
+ //#region ../../src/core/errors/AppNotStartedError.ts
1894
+ var AppNotStartedError = class extends AlephaError {
1895
+ name = "AppNotStartedError";
1896
+ constructor() {
1897
+ super("App not started. Please start the app before.");
1898
+ }
1896
1899
  };
1897
- const t = new TypeProvider();
1900
+
1901
+ //#endregion
1902
+ //#region ../../src/core/helpers/createPagination.ts
1903
+ /**
1904
+ * Create a pagination object from an array of entities.
1905
+ *
1906
+ * This is a pure function that works with any data source (databases, APIs, caches, arrays, etc.).
1907
+ * It handles the core pagination logic including:
1908
+ * - Slicing the content to the requested page size
1909
+ * - Calculating pagination metadata (offset, page number, etc.)
1910
+ * - Determining navigation state (isFirst, isLast)
1911
+ * - Including sort metadata when provided
1912
+ *
1913
+ * @param entities - The entities to paginate (should include one extra item to detect if there's a next page)
1914
+ * @param limit - The limit of the pagination (page size)
1915
+ * @param offset - The offset of the pagination (starting position)
1916
+ * @param sort - Optional sort metadata to include in response
1917
+ * @returns A complete Page object with content and metadata
1918
+ *
1919
+ * @example Basic pagination
1920
+ * ```ts
1921
+ * const users = await fetchUsers({ limit: 11, offset: 0 }); // Fetch limit + 1
1922
+ * const page = createPagination(users, 10, 0);
1923
+ * // page.content has max 10 items
1924
+ * // page.page.isLast tells us if there are more pages
1925
+ * ```
1926
+ *
1927
+ * @example With sorting
1928
+ * ```ts
1929
+ * const page = createPagination(
1930
+ * entities,
1931
+ * 10,
1932
+ * 0,
1933
+ * [{ column: "name", direction: "asc" }]
1934
+ * );
1935
+ * ```
1936
+ *
1937
+ * @example In a custom service
1938
+ * ```ts
1939
+ * class MyService {
1940
+ * async listItems(page: number, size: number) {
1941
+ * const items = await this.fetchItems({ limit: size + 1, offset: page * size });
1942
+ * return createPagination(items, size, page * size);
1943
+ * }
1944
+ * }
1945
+ * ```
1946
+ */
1947
+ function createPagination(entities, limit = 10, offset = 0, sort) {
1948
+ const content = entities.slice(0, limit);
1949
+ const hasNext = entities.length === limit + 1;
1950
+ const pageNumber = Math.floor(offset / limit);
1951
+ return {
1952
+ content,
1953
+ page: {
1954
+ number: pageNumber,
1955
+ size: limit,
1956
+ offset,
1957
+ numberOfElements: content.length,
1958
+ isEmpty: content.length === 0,
1959
+ isFirst: pageNumber === 0,
1960
+ isLast: !hasNext,
1961
+ ...sort && sort.length > 0 ? { sort: {
1962
+ sorted: true,
1963
+ fields: sort.map((s) => ({
1964
+ field: s.column,
1965
+ direction: s.direction
1966
+ }))
1967
+ } } : {}
1968
+ }
1969
+ };
1970
+ }
1898
1971
 
1899
1972
  //#endregion
1900
1973
  //#region ../../src/core/helpers/jsonSchemaToTypeBox.ts
@@ -2116,63 +2189,6 @@ const $env = (type) => {
2116
2189
  return alepha.parseEnv(type);
2117
2190
  };
2118
2191
 
2119
- //#endregion
2120
- //#region ../../src/core/primitives/$hook.ts
2121
- /**
2122
- * Registers a new hook.
2123
- *
2124
- * ```ts
2125
- * import { $hook } from "alepha";
2126
- *
2127
- * class MyProvider {
2128
- * onStart = $hook({
2129
- * name: "start", // or "configure", "ready", "stop", ...
2130
- * handler: async (app) => {
2131
- * // await db.connect(); ...
2132
- * }
2133
- * });
2134
- * }
2135
- * ```
2136
- *
2137
- * Hooks are used to run async functions from all registered providers/services.
2138
- *
2139
- * You can't register a hook after the App has started.
2140
- *
2141
- * It's used under the hood by the `configure`, `start`, and `stop` methods.
2142
- * Some modules also use hooks to run their own logic. (e.g. `alepha/server`).
2143
- *
2144
- * You can create your own hooks by using module augmentation:
2145
- *
2146
- * ```ts
2147
- * declare module "alepha" {
2148
- *
2149
- * interface Hooks {
2150
- * "my:custom:hook": {
2151
- * arg1: string;
2152
- * }
2153
- * }
2154
- * }
2155
- *
2156
- * await alepha.events.emit("my:custom:hook", { arg1: "value" });
2157
- * ```
2158
- *
2159
- */
2160
- const $hook = (options) => createPrimitive(HookPrimitive, options);
2161
- var HookPrimitive = class extends Primitive {
2162
- called = 0;
2163
- onInit() {
2164
- this.alepha.events.on(this.options.on, {
2165
- caller: this.config.service,
2166
- priority: this.options.priority,
2167
- callback: async (args) => {
2168
- this.called += 1;
2169
- await this.options.handler(args);
2170
- }
2171
- });
2172
- }
2173
- };
2174
- $hook[KIND] = HookPrimitive;
2175
-
2176
2192
  //#endregion
2177
2193
  //#region ../../src/core/primitives/$use.ts
2178
2194
  /**