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.
- package/dist/api/audits/index.d.ts +418 -338
- package/dist/api/audits/index.d.ts.map +1 -0
- package/dist/api/files/index.d.ts +81 -1
- package/dist/api/files/index.d.ts.map +1 -0
- package/dist/api/jobs/index.d.ts +107 -27
- package/dist/api/jobs/index.d.ts.map +1 -0
- package/dist/api/notifications/index.d.ts +21 -1
- package/dist/api/notifications/index.d.ts.map +1 -0
- package/dist/api/parameters/index.d.ts +455 -8
- package/dist/api/parameters/index.d.ts.map +1 -0
- package/dist/api/users/index.d.ts +844 -840
- package/dist/api/users/index.d.ts.map +1 -0
- package/dist/api/verifications/index.d.ts.map +1 -0
- package/dist/batch/index.d.ts.map +1 -0
- package/dist/bucket/index.d.ts.map +1 -0
- package/dist/cache/core/index.d.ts.map +1 -0
- package/dist/cache/redis/index.d.ts.map +1 -0
- package/dist/cli/index.d.ts +254 -59
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +499 -127
- package/dist/cli/index.js.map +1 -1
- package/dist/command/index.d.ts +217 -10
- package/dist/command/index.d.ts.map +1 -0
- package/dist/command/index.js +350 -74
- package/dist/command/index.js.map +1 -1
- package/dist/core/index.browser.js +1334 -1318
- package/dist/core/index.browser.js.map +1 -1
- package/dist/core/index.d.ts +76 -72
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +1337 -1321
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.native.js +1337 -1321
- package/dist/core/index.native.js.map +1 -1
- package/dist/datetime/index.d.ts.map +1 -0
- package/dist/email/index.d.ts.map +1 -0
- package/dist/fake/index.d.ts.map +1 -0
- package/dist/file/index.d.ts.map +1 -0
- package/dist/file/index.js.map +1 -1
- package/dist/lock/core/index.d.ts.map +1 -0
- package/dist/lock/redis/index.d.ts.map +1 -0
- package/dist/logger/index.d.ts +1 -0
- package/dist/logger/index.d.ts.map +1 -0
- package/dist/mcp/index.d.ts +820 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +978 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/orm/index.d.ts +234 -107
- package/dist/orm/index.d.ts.map +1 -0
- package/dist/orm/index.js +376 -316
- package/dist/orm/index.js.map +1 -1
- package/dist/queue/core/index.d.ts +4 -4
- package/dist/queue/core/index.d.ts.map +1 -0
- package/dist/queue/redis/index.d.ts.map +1 -0
- package/dist/queue/redis/index.js +2 -4
- package/dist/queue/redis/index.js.map +1 -1
- package/dist/redis/index.d.ts +400 -29
- package/dist/redis/index.d.ts.map +1 -0
- package/dist/redis/index.js +412 -21
- package/dist/redis/index.js.map +1 -1
- package/dist/retry/index.d.ts.map +1 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/scheduler/index.d.ts +6 -6
- package/dist/scheduler/index.d.ts.map +1 -0
- package/dist/security/index.d.ts +28 -28
- package/dist/security/index.d.ts.map +1 -0
- package/dist/server/auth/index.d.ts +155 -155
- package/dist/server/auth/index.d.ts.map +1 -0
- package/dist/server/cache/index.d.ts.map +1 -0
- package/dist/server/compress/index.d.ts.map +1 -0
- package/dist/server/cookies/index.d.ts.map +1 -0
- package/dist/server/core/index.d.ts +0 -1
- package/dist/server/core/index.d.ts.map +1 -0
- package/dist/server/core/index.js.map +1 -1
- package/dist/server/cors/index.d.ts.map +1 -0
- package/dist/server/health/index.d.ts +17 -17
- package/dist/server/health/index.d.ts.map +1 -0
- package/dist/server/helmet/index.d.ts +4 -1
- package/dist/server/helmet/index.d.ts.map +1 -0
- package/dist/server/links/index.d.ts +33 -33
- package/dist/server/links/index.d.ts.map +1 -0
- package/dist/server/metrics/index.d.ts.map +1 -0
- package/dist/server/multipart/index.d.ts.map +1 -0
- package/dist/server/multipart/index.js.map +1 -1
- package/dist/server/proxy/index.d.ts.map +1 -0
- package/dist/server/proxy/index.js.map +1 -1
- package/dist/server/rate-limit/index.d.ts.map +1 -0
- package/dist/server/security/index.d.ts +9 -9
- package/dist/server/security/index.d.ts.map +1 -0
- package/dist/server/static/index.d.ts.map +1 -0
- package/dist/server/swagger/index.d.ts.map +1 -0
- package/dist/sms/index.d.ts.map +1 -0
- package/dist/thread/index.d.ts.map +1 -0
- package/dist/topic/core/index.d.ts.map +1 -0
- package/dist/topic/redis/index.d.ts.map +1 -0
- package/dist/topic/redis/index.js +3 -3
- package/dist/topic/redis/index.js.map +1 -1
- package/dist/vite/index.d.ts +10 -2
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +45 -20
- package/dist/vite/index.js.map +1 -1
- package/dist/websocket/index.d.ts.map +1 -0
- package/package.json +9 -4
- package/src/cli/apps/AlephaCli.ts +10 -3
- package/src/cli/apps/AlephaPackageBuilderCli.ts +15 -8
- package/src/cli/assets/mainTs.ts +9 -10
- package/src/cli/atoms/changelogOptions.ts +45 -0
- package/src/cli/commands/ChangelogCommands.ts +259 -0
- package/src/cli/commands/DeployCommands.ts +118 -0
- package/src/cli/commands/DrizzleCommands.ts +230 -10
- package/src/cli/commands/ViteCommands.ts +47 -23
- package/src/cli/defineConfig.ts +15 -0
- package/src/cli/index.ts +3 -0
- package/src/cli/services/AlephaCliUtils.ts +10 -154
- package/src/cli/services/GitMessageParser.ts +77 -0
- package/src/command/helpers/EnvUtils.ts +37 -0
- package/src/command/index.ts +3 -1
- package/src/command/primitives/$command.ts +172 -6
- package/src/command/providers/CliProvider.ts +499 -95
- package/src/core/Alepha.ts +1 -1
- package/src/core/providers/SchemaValidator.ts +23 -1
- package/src/file/providers/NodeFileSystemProvider.ts +3 -1
- package/src/mcp/errors/McpError.ts +72 -0
- package/src/mcp/helpers/jsonrpc.ts +163 -0
- package/src/mcp/index.ts +132 -0
- package/src/mcp/interfaces/McpTypes.ts +248 -0
- package/src/mcp/primitives/$prompt.ts +188 -0
- package/src/mcp/primitives/$resource.ts +171 -0
- package/src/mcp/primitives/$tool.ts +285 -0
- package/src/mcp/providers/McpServerProvider.ts +382 -0
- package/src/mcp/transports/SseMcpTransport.ts +172 -0
- package/src/mcp/transports/StdioMcpTransport.ts +126 -0
- package/src/orm/index.ts +20 -4
- package/src/orm/interfaces/PgQueryWhere.ts +1 -26
- package/src/orm/providers/drivers/BunPostgresProvider.ts +225 -0
- package/src/orm/providers/drivers/BunSqliteProvider.ts +180 -0
- package/src/orm/providers/drivers/CloudflareD1Provider.ts +164 -0
- package/src/orm/providers/drivers/DatabaseProvider.ts +25 -0
- package/src/orm/providers/drivers/NodePostgresProvider.ts +0 -25
- package/src/orm/providers/drivers/NodeSqliteProvider.ts +3 -1
- package/src/orm/services/QueryManager.ts +10 -125
- package/src/queue/redis/providers/RedisQueueProvider.ts +2 -7
- package/src/redis/index.ts +65 -3
- package/src/redis/providers/BunRedisProvider.ts +304 -0
- package/src/redis/providers/BunRedisSubscriberProvider.ts +94 -0
- package/src/redis/providers/NodeRedisProvider.ts +280 -0
- package/src/redis/providers/NodeRedisSubscriberProvider.ts +94 -0
- package/src/redis/providers/RedisProvider.ts +134 -140
- package/src/redis/providers/RedisSubscriberProvider.ts +58 -49
- package/src/server/core/providers/BunHttpServerProvider.ts +0 -3
- package/src/server/core/providers/ServerBodyParserProvider.ts +3 -1
- package/src/server/core/providers/ServerProvider.ts +7 -4
- package/src/server/multipart/providers/ServerMultipartProvider.ts +3 -1
- package/src/server/proxy/providers/ServerProxyProvider.ts +1 -1
- package/src/topic/redis/providers/RedisTopicProvider.ts +3 -3
- package/src/vite/plugins/viteAlephaBuild.ts +8 -2
- package/src/vite/plugins/viteAlephaDev.ts +6 -2
- package/src/vite/tasks/buildServer.ts +2 -1
- package/src/vite/tasks/generateCloudflare.ts +43 -15
- package/src/vite/tasks/runAlepha.ts +1 -0
- 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/
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
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
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
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
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
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
|
-
|
|
544
|
+
throw new AlephaError(`Locale not found: ${locale}`);
|
|
474
545
|
}
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
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
|
-
*
|
|
558
|
+
* Default maximum length for strings.
|
|
505
559
|
*
|
|
506
|
-
*
|
|
507
|
-
*
|
|
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
|
-
|
|
510
|
-
this.codecs.set(name, codec);
|
|
511
|
-
}
|
|
566
|
+
static DEFAULT_STRING_MAX_LENGTH = 255;
|
|
512
567
|
/**
|
|
513
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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
|
-
*
|
|
647
|
+
* Create a schema for an object.
|
|
648
|
+
* By default, additional properties are not allowed.
|
|
546
649
|
*
|
|
547
|
-
*
|
|
650
|
+
* @example
|
|
651
|
+
* ```ts
|
|
652
|
+
* const userSchema = t.object({
|
|
653
|
+
* id: t.integer(),
|
|
654
|
+
* name: t.string(),
|
|
655
|
+
* });
|
|
656
|
+
* ```
|
|
548
657
|
*/
|
|
549
|
-
|
|
550
|
-
return
|
|
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
|
-
*
|
|
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
|
-
|
|
562
|
-
|
|
563
|
-
|
|
670
|
+
array(schema, options) {
|
|
671
|
+
return Type.Array(schema, {
|
|
672
|
+
maxItems: TypeProvider.DEFAULT_ARRAY_MAX_ITEMS,
|
|
673
|
+
...options
|
|
674
|
+
});
|
|
564
675
|
}
|
|
565
|
-
|
|
566
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
572
|
-
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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
|
-
*
|
|
704
|
+
* Create a schema for a JSON object.
|
|
705
|
+
* This is a record with string keys and any values.
|
|
587
706
|
*/
|
|
588
|
-
|
|
589
|
-
|
|
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
|
-
|
|
619
|
-
|
|
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
|
-
|
|
661
|
-
|
|
716
|
+
/**
|
|
717
|
+
* Create a schema for a number.
|
|
718
|
+
*/
|
|
719
|
+
number(options) {
|
|
720
|
+
return Type.Number({ ...options });
|
|
662
721
|
}
|
|
663
|
-
|
|
664
|
-
|
|
722
|
+
/**
|
|
723
|
+
* Create a schema for an integer.
|
|
724
|
+
*/
|
|
725
|
+
integer(options) {
|
|
726
|
+
return Type.Integer({ ...options });
|
|
665
727
|
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
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
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
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
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
}
|
|
701
|
-
return this;
|
|
751
|
+
/**
|
|
752
|
+
* Make a schema optional.
|
|
753
|
+
*/
|
|
754
|
+
optional(schema) {
|
|
755
|
+
return Type.Optional(schema);
|
|
702
756
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
return
|
|
757
|
+
/**
|
|
758
|
+
* Make a schema nullable.
|
|
759
|
+
*/
|
|
760
|
+
nullable(schema, options) {
|
|
761
|
+
return Type.Union([Type.Null(), schema], options);
|
|
708
762
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
}
|
|
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
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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
|
-
*
|
|
788
|
+
* Create a schema for a URL represented as a string.
|
|
730
789
|
*/
|
|
731
|
-
|
|
732
|
-
return
|
|
790
|
+
url(options) {
|
|
791
|
+
return this.string({
|
|
792
|
+
...options,
|
|
793
|
+
format: "url"
|
|
794
|
+
});
|
|
733
795
|
}
|
|
734
796
|
/**
|
|
735
|
-
*
|
|
797
|
+
* Create a schema for binary data represented as a base64 string.
|
|
736
798
|
*/
|
|
737
|
-
|
|
738
|
-
return this.
|
|
799
|
+
binary(options) {
|
|
800
|
+
return this.string({
|
|
801
|
+
...options,
|
|
802
|
+
format: "binary"
|
|
803
|
+
});
|
|
739
804
|
}
|
|
740
805
|
/**
|
|
741
|
-
*
|
|
806
|
+
* Create a schema for uuid.
|
|
742
807
|
*/
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
808
|
+
uuid(options) {
|
|
809
|
+
return this.string({
|
|
810
|
+
...options,
|
|
811
|
+
format: "uuid"
|
|
812
|
+
});
|
|
747
813
|
}
|
|
748
814
|
/**
|
|
749
|
-
*
|
|
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
|
-
|
|
752
|
-
|
|
753
|
-
|
|
821
|
+
file(options) {
|
|
822
|
+
return Type.Unsafe(Type.Any({
|
|
823
|
+
[OPTIONS]: options,
|
|
824
|
+
format: "binary"
|
|
825
|
+
}));
|
|
754
826
|
}
|
|
755
827
|
/**
|
|
756
|
-
*
|
|
828
|
+
* @experimental
|
|
757
829
|
*/
|
|
758
|
-
|
|
759
|
-
return
|
|
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/
|
|
765
|
-
|
|
766
|
-
|
|
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
|
-
*
|
|
931
|
+
* Validate the value against the provided schema.
|
|
891
932
|
*
|
|
892
|
-
*
|
|
893
|
-
|
|
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
|
|
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
|
-
|
|
898
|
-
if (
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
if (
|
|
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
|
-
|
|
906
|
-
|
|
907
|
-
const
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
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
|
|
980
|
+
return value;
|
|
920
981
|
}
|
|
921
982
|
/**
|
|
922
|
-
*
|
|
923
|
-
* Pass to true when #start() is called.
|
|
983
|
+
* Used by `beforeParse` to determine if a schema allows null values.
|
|
924
984
|
*/
|
|
925
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
1030
|
+
register(name, codec) {
|
|
1031
|
+
this.codecs.set(name, codec);
|
|
1032
|
+
}
|
|
930
1033
|
/**
|
|
931
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
1046
|
+
* Encode data using the specified codec and output format.
|
|
936
1047
|
*/
|
|
937
|
-
|
|
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
|
-
*
|
|
1057
|
+
* Decode data using the specified codec.
|
|
940
1058
|
*/
|
|
941
|
-
|
|
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
|
-
*
|
|
944
|
-
*
|
|
1066
|
+
* Validate decoded data against the schema.
|
|
1067
|
+
*
|
|
1068
|
+
* This is automatically called before encoding or after decoding.
|
|
945
1069
|
*/
|
|
946
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
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
|
-
*
|
|
1090
|
+
* Registers a hook for the specified event.
|
|
996
1091
|
*/
|
|
997
|
-
|
|
998
|
-
|
|
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
|
-
*
|
|
1107
|
+
* Emits the specified event with the given payload.
|
|
1002
1108
|
*/
|
|
1003
|
-
|
|
1004
|
-
|
|
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
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
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
|
-
|
|
1014
|
-
this.
|
|
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
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
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
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
1041
|
-
return this.
|
|
1252
|
+
has(key) {
|
|
1253
|
+
return key in this.store;
|
|
1042
1254
|
}
|
|
1043
1255
|
/**
|
|
1044
|
-
*
|
|
1256
|
+
* Delete a key from the state (set to undefined)
|
|
1045
1257
|
*/
|
|
1046
|
-
|
|
1047
|
-
return this.
|
|
1258
|
+
del(key) {
|
|
1259
|
+
return this.set(key, void 0);
|
|
1048
1260
|
}
|
|
1049
1261
|
/**
|
|
1050
|
-
*
|
|
1262
|
+
* Push a value to an array in the state
|
|
1051
1263
|
*/
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
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
|
-
*
|
|
1270
|
+
* Clear all state
|
|
1058
1271
|
*/
|
|
1059
|
-
|
|
1060
|
-
|
|
1272
|
+
clear() {
|
|
1273
|
+
this.store = {};
|
|
1274
|
+
return this;
|
|
1061
1275
|
}
|
|
1062
1276
|
/**
|
|
1063
|
-
*
|
|
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
|
-
|
|
1333
|
-
|
|
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/
|
|
1285
|
+
//#region ../../src/core/Alepha.ts
|
|
1382
1286
|
/**
|
|
1383
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1393
|
-
*
|
|
1394
|
-
*
|
|
1395
|
-
*
|
|
1396
|
-
*
|
|
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
|
|
1401
|
-
*
|
|
1402
|
-
* //
|
|
1403
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1409
|
-
*
|
|
1410
|
-
*
|
|
1411
|
-
*
|
|
1412
|
-
*
|
|
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
|
-
*
|
|
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
|
-
*
|
|
1419
|
-
*
|
|
1420
|
-
*
|
|
1421
|
-
*
|
|
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
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
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
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
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
|
-
*
|
|
1533
|
-
*
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
*
|
|
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
|
-
|
|
1458
|
+
ready = false;
|
|
1541
1459
|
/**
|
|
1542
|
-
*
|
|
1460
|
+
* A promise that resolves when the App has started.
|
|
1543
1461
|
*/
|
|
1544
|
-
|
|
1462
|
+
starting;
|
|
1545
1463
|
/**
|
|
1546
|
-
*
|
|
1547
|
-
* It
|
|
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
|
-
|
|
1467
|
+
pendingInstantiations = [];
|
|
1555
1468
|
/**
|
|
1556
|
-
*
|
|
1557
|
-
*
|
|
1558
|
-
|
|
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
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
1484
|
+
substitutions = /* @__PURE__ */ new Map();
|
|
1568
1485
|
/**
|
|
1569
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
*
|
|
1622
|
-
* By default, additional properties are not allowed.
|
|
1494
|
+
* Node.js feature that allows to store context across asynchronous calls.
|
|
1623
1495
|
*
|
|
1624
|
-
*
|
|
1625
|
-
*
|
|
1626
|
-
*
|
|
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
|
-
|
|
1633
|
-
return Type.Object(properties, {
|
|
1634
|
-
additionalProperties: false,
|
|
1635
|
-
...options
|
|
1636
|
-
});
|
|
1637
|
-
}
|
|
1500
|
+
context;
|
|
1638
1501
|
/**
|
|
1639
|
-
*
|
|
1640
|
-
|
|
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
|
-
*
|
|
1512
|
+
* Supports multiple codec formats (JSON, Protobuf, etc.) with a unified interface.
|
|
1643
1513
|
*/
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1514
|
+
codec;
|
|
1515
|
+
/**
|
|
1516
|
+
* Get logger instance.
|
|
1517
|
+
*/
|
|
1518
|
+
get log() {
|
|
1519
|
+
return this.store.get("alepha.logger");
|
|
1649
1520
|
}
|
|
1650
1521
|
/**
|
|
1651
|
-
*
|
|
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
|
-
|
|
1657
|
-
return
|
|
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
|
-
*
|
|
1661
|
-
* For internal strings without length limits, consider using `t.string()` instead.
|
|
1539
|
+
* True when start() is called.
|
|
1662
1540
|
*
|
|
1663
|
-
*
|
|
1541
|
+
* -> No more services can be added, it's over, bye!
|
|
1664
1542
|
*/
|
|
1665
|
-
|
|
1666
|
-
|
|
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
|
-
*
|
|
1679
|
-
*
|
|
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
|
-
|
|
1682
|
-
return
|
|
1553
|
+
isConfigured() {
|
|
1554
|
+
return this.configured;
|
|
1683
1555
|
}
|
|
1684
1556
|
/**
|
|
1685
|
-
*
|
|
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
|
-
|
|
1688
|
-
return
|
|
1561
|
+
isStarted() {
|
|
1562
|
+
return this.started;
|
|
1689
1563
|
}
|
|
1690
1564
|
/**
|
|
1691
|
-
*
|
|
1565
|
+
* True if the App is ready. It means that Alepha is started AND ready() hook has beed called.
|
|
1692
1566
|
*/
|
|
1693
|
-
|
|
1694
|
-
return
|
|
1567
|
+
isReady() {
|
|
1568
|
+
return this.ready;
|
|
1695
1569
|
}
|
|
1696
1570
|
/**
|
|
1697
|
-
*
|
|
1571
|
+
* True if the App is running in a Continuous Integration environment.
|
|
1698
1572
|
*/
|
|
1699
|
-
|
|
1700
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
1717
|
-
return
|
|
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
|
-
*
|
|
1584
|
+
* Returns whether the App is running in Vite dev mode.
|
|
1727
1585
|
*/
|
|
1728
|
-
|
|
1729
|
-
|
|
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
|
-
*
|
|
1594
|
+
* Returns whether the App is running in a serverless environment.
|
|
1733
1595
|
*/
|
|
1734
|
-
|
|
1735
|
-
|
|
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
|
-
*
|
|
1739
|
-
|
|
1740
|
-
|
|
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
|
-
|
|
1745
|
-
return
|
|
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
|
-
*
|
|
1753
|
-
*
|
|
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
|
-
|
|
1756
|
-
return
|
|
1757
|
-
...options,
|
|
1758
|
-
format: "bigint"
|
|
1759
|
-
});
|
|
1615
|
+
isProduction() {
|
|
1616
|
+
return this.env.NODE_ENV === "production";
|
|
1760
1617
|
}
|
|
1761
1618
|
/**
|
|
1762
|
-
*
|
|
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
|
-
|
|
1765
|
-
|
|
1766
|
-
...
|
|
1767
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
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
|
-
*
|
|
1683
|
+
* Check if entry is registered in the container.
|
|
1781
1684
|
*/
|
|
1782
|
-
|
|
1783
|
-
return
|
|
1784
|
-
|
|
1785
|
-
|
|
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
|
-
*
|
|
1703
|
+
* Registers the specified service in the container.
|
|
1790
1704
|
*
|
|
1791
|
-
*
|
|
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
|
-
*
|
|
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
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
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
|
-
*
|
|
1750
|
+
* Get an instance of the specified service from the container.
|
|
1751
|
+
*
|
|
1752
|
+
* @see {@link InjectOptions} for the available options.
|
|
1803
1753
|
*/
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
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
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
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
|
-
*
|
|
1844
|
-
*
|
|
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
|
-
|
|
1847
|
-
return this.
|
|
1848
|
-
|
|
1849
|
-
|
|
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
|
-
*
|
|
1854
|
-
*
|
|
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
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
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
|
-
*
|
|
1851
|
+
* Get all primitives of the specified type.
|
|
1871
1852
|
*/
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
}
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
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
|
-
|
|
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
|
/**
|