@venizia/ignis-helpers 0.4.8-13 → 0.4.8-14
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/esm/common/redact.js.map +1 -1
- package/dist/esm/common/types/class.d.ts +14 -12
- package/dist/esm/common/types/class.js.map +1 -1
- package/dist/esm/common/types/const-value.d.ts +3 -3
- package/dist/esm/common/types/const-value.js.map +1 -1
- package/dist/esm/common/types/injection.d.ts +1 -1
- package/dist/esm/common/types/injection.js.map +1 -1
- package/dist/esm/common/types/utility.d.ts +0 -4
- package/dist/esm/common/types/utility.js.map +1 -1
- package/dist/esm/modules/env/app-env.d.ts +17 -8
- package/dist/esm/modules/env/app-env.js +18 -15
- package/dist/esm/modules/env/app-env.js.map +1 -1
- package/dist/esm/modules/env/common/types.d.ts +22 -6
- package/dist/esm/modules/env/common/types.js.map +1 -1
- package/dist/esm/modules/logger/base/abstract.d.ts +6 -7
- package/dist/esm/modules/logger/base/abstract.js.map +1 -1
- package/dist/esm/modules/logger/base/base.d.ts +7 -8
- package/dist/esm/modules/logger/base/base.js.map +1 -1
- package/dist/esm/modules/logger/base/console.d.ts +6 -7
- package/dist/esm/modules/logger/base/console.js.map +1 -1
- package/dist/esm/modules/logger/common/types.d.ts +7 -7
- package/dist/esm/modules/logger/common/types.js.map +1 -1
- package/dist/esm/modules/logger/factory.js.map +1 -1
- package/dist/esm/modules/logger/hf/flusher.js.map +1 -1
- package/dist/esm/modules/logger/hf/logger.d.ts +6 -7
- package/dist/esm/modules/logger/hf/logger.js.map +1 -1
- package/dist/esm/modules/logger/pino/backing.js.map +1 -1
- package/dist/esm/modules/logger/pino/destination.d.ts +1 -1
- package/dist/esm/modules/logger/pino/destination.js.map +1 -1
- package/dist/esm/modules/logger/pino/logger.d.ts +1 -2
- package/dist/esm/modules/logger/pino/logger.js.map +1 -1
- package/dist/esm/modules/logger/winston/formats.js +2 -2
- package/dist/esm/modules/logger/winston/formats.js.map +1 -1
- package/dist/esm/modules/logger/winston/logger.d.ts +1 -2
- package/dist/esm/modules/logger/winston/logger.js.map +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.d.ts +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js +1 -1
- package/dist/esm/modules/logger/winston/transports/dgram.transport.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +5 -5
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +1 -2
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +1 -2
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +5 -6
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.d.ts +2 -2
- package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +1 -1
- package/dist/esm/modules/queue/kafka/base.d.ts +1 -1
- package/dist/esm/modules/queue/kafka/base.js +13 -2
- package/dist/esm/modules/queue/kafka/base.js.map +1 -1
- package/dist/esm/modules/redis/cluster/cluster.helper.d.ts +1 -1
- package/dist/esm/modules/redis/cluster/cluster.helper.js +10 -3
- package/dist/esm/modules/redis/cluster/cluster.helper.js.map +1 -1
- package/dist/esm/modules/redis/cluster/index.d.ts +1 -0
- package/dist/esm/modules/redis/cluster/index.js +1 -0
- package/dist/esm/modules/redis/cluster/index.js.map +1 -1
- package/dist/esm/modules/redis/cluster/types.d.ts +20 -0
- package/dist/esm/modules/redis/cluster/types.js +2 -0
- package/dist/esm/modules/redis/cluster/types.js.map +1 -0
- package/dist/esm/modules/redis/common/constants.d.ts +2 -8
- package/dist/esm/modules/redis/common/constants.js +2 -5
- package/dist/esm/modules/redis/common/constants.js.map +1 -1
- package/dist/esm/modules/redis/common/types.d.ts +9 -62
- package/dist/esm/modules/redis/common/types.js.map +1 -1
- package/dist/esm/modules/redis/factory.d.ts +3 -4
- package/dist/esm/modules/redis/factory.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/constants.d.ts +14 -0
- package/dist/esm/modules/redis/sentinel/constants.js +11 -0
- package/dist/esm/modules/redis/sentinel/constants.js.map +1 -0
- package/dist/esm/modules/redis/sentinel/index.d.ts +2 -0
- package/dist/esm/modules/redis/sentinel/index.js +2 -0
- package/dist/esm/modules/redis/sentinel/index.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/sentinel.helper.d.ts +1 -1
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js +18 -9
- package/dist/esm/modules/redis/sentinel/sentinel.helper.js.map +1 -1
- package/dist/esm/modules/redis/sentinel/types.d.ts +26 -0
- package/dist/esm/modules/redis/sentinel/types.js +2 -0
- package/dist/esm/modules/redis/sentinel/types.js.map +1 -0
- package/dist/esm/modules/redis/single/index.d.ts +1 -0
- package/dist/esm/modules/redis/single/index.js +1 -0
- package/dist/esm/modules/redis/single/index.js.map +1 -1
- package/dist/esm/modules/redis/single/single.helper.d.ts +1 -1
- package/dist/esm/modules/redis/single/single.helper.js +1 -1
- package/dist/esm/modules/redis/single/single.helper.js.map +1 -1
- package/dist/esm/modules/redis/single/types.d.ts +15 -0
- package/dist/esm/modules/redis/single/types.js +2 -0
- package/dist/esm/modules/redis/single/types.js.map +1 -0
- package/dist/esm/modules/secrets/base/abstract.helper.js +6 -1
- package/dist/esm/modules/secrets/base/abstract.helper.js.map +1 -1
- package/dist/esm/modules/secrets/common/types/registration.d.ts +25 -6
- package/dist/esm/modules/secrets/common/types/registration.js.map +1 -1
- package/dist/esm/modules/secrets/dotenv/dotenv.helper.js +1 -1
- package/dist/esm/modules/secrets/dotenv/dotenv.helper.js.map +1 -1
- package/dist/esm/modules/secrets/factory.js +7 -6
- package/dist/esm/modules/secrets/factory.js.map +1 -1
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.d.ts +12 -10
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js +50 -25
- package/dist/esm/modules/secrets/hashicorp/hashicorp.helper.js.map +1 -1
- package/dist/esm/modules/storage/in-memory/helper.d.ts +2 -3
- package/dist/esm/modules/storage/in-memory/helper.js.map +1 -1
- package/dist/esm/modules/worker-thread/common/types.d.ts +2 -2
- package/dist/esm/modules/worker-thread/common/types.js.map +1 -1
- package/dist/esm/modules/worker-thread/thread/abstract.d.ts +2 -2
- package/dist/esm/modules/worker-thread/thread/abstract.js.map +1 -1
- package/dist/esm/modules/worker-thread/worker-pool.d.ts +1 -1
- package/dist/esm/modules/worker-thread/worker-pool.js.map +1 -1
- package/dist/esm/utilities/module.utility.d.ts +8 -5
- package/dist/esm/utilities/module.utility.js +5 -1
- package/dist/esm/utilities/module.utility.js.map +1 -1
- package/dist/esm/utilities/parse.utility.d.ts +34 -6
- package/dist/esm/utilities/parse.utility.js +82 -15
- package/dist/esm/utilities/parse.utility.js.map +1 -1
- package/dist/esm/utilities/performance.utility.d.ts +3 -3
- package/dist/esm/utilities/performance.utility.js.map +1 -1
- package/dist/esm/utilities/promise.utility.d.ts +1 -1
- package/dist/esm/utilities/promise.utility.js.map +1 -1
- package/package.json +3 -3
|
@@ -14,36 +14,37 @@ export class SecretsHelperFactory {
|
|
|
14
14
|
cacheTtlSeconds: opts.cacheTtlSeconds,
|
|
15
15
|
renewBeforeRatio: opts.renewBeforeRatio,
|
|
16
16
|
};
|
|
17
|
-
|
|
17
|
+
// Named before the switch: in `default` the union is exhausted and `opts` is `never`, yet an untyped JS caller can still land there.
|
|
18
|
+
const provider = opts.provider;
|
|
18
19
|
switch (opts.provider) {
|
|
19
20
|
case SecretProviders.SYSTEM_ENVS: {
|
|
20
21
|
return new SystemEnvsHelper({ identifier: opts.identifier });
|
|
21
22
|
}
|
|
22
23
|
case SecretProviders.HASHICORP_VAULT: {
|
|
23
24
|
// `client` is the injected escape: the helper never reaches for the peer, so demanding it here would defeat the escape.
|
|
24
|
-
if (!config?.client) {
|
|
25
|
+
if (!opts.config?.client) {
|
|
25
26
|
ModuleUtility.assertInstalled({
|
|
26
27
|
scope: 'HashiCorpVaultHelper',
|
|
27
28
|
modules: ['node-vault'],
|
|
28
29
|
allowRegistered: true,
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
|
-
return new HashiCorpVaultHelper({ ...config, ...shared });
|
|
32
|
+
return new HashiCorpVaultHelper({ ...opts.config, ...shared });
|
|
32
33
|
}
|
|
33
34
|
case SecretProviders.DOTENV_VAULT: {
|
|
34
35
|
// `decode` is the injected escape - same reasoning as `client` above.
|
|
35
|
-
if (!config?.decode) {
|
|
36
|
+
if (!opts.config?.decode) {
|
|
36
37
|
ModuleUtility.assertInstalled({
|
|
37
38
|
scope: 'DotenvVaultHelper',
|
|
38
39
|
modules: ['@dotenvx/dotenvx'],
|
|
39
40
|
allowRegistered: true,
|
|
40
41
|
});
|
|
41
42
|
}
|
|
42
|
-
return new DotenvVaultHelper({ ...config, ...shared });
|
|
43
|
+
return new DotenvVaultHelper({ ...opts.config, ...shared });
|
|
43
44
|
}
|
|
44
45
|
default: {
|
|
45
46
|
throw getError({
|
|
46
|
-
message: `[createSecretsHelper] Unsupported secret provider: ${
|
|
47
|
+
message: `[createSecretsHelper] Unsupported secret provider: ${provider}`,
|
|
47
48
|
});
|
|
48
49
|
}
|
|
49
50
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../src/modules/secrets/factory.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"factory.js","sourceRoot":"","sources":["../../../../src/modules/secrets/factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BA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,MAAM,EAAE,MAAM,EAAE,CAAC;oBACzB,aAAa,CAAC,eAAe,CAAC;wBAC5B,KAAK,EAAE,mBAAmB;wBAC1B,OAAO,EAAE,CAAC,kBAAkB,CAAC;wBAC7B,eAAe,EAAE,IAAI;qBACtB,CAAC,CAAC;gBACL,CAAC;gBAED,OAAO,IAAI,iBAAiB,CAAC,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC;YAC9D,CAAC;YACD,OAAO,CAAC,CAAC,CAAC;gBACR,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,sDAAsD,QAAQ,EAAE;iBAC1E,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { SecretProviders, type ISecretsHelper, type ISecretsRegistration } from './common';\nimport { DotenvVaultHelper } from './dotenv';\nimport { HashiCorpVaultHelper } from './hashicorp';\nimport { SystemEnvsHelper } from './system-envs';\n\n// node-vault / @dotenvx/dotenvx are optional peers reached only via `ModuleUtility.load`: never eagerly loaded, invisible to bundlers. Compiled apps that use a provider must ship the peer in node_modules, inject the client via options, or register it with `ModuleUtility.register`.\n// The providers are imported statically on purpose: a dynamic `import('./x')` of our own module makes bun wrap every module it reaches in a lazy initializer, and the root barrel then exports `undefined` for them.\n/** Builds the `ISecretsHelper` for a registration by its `provider`. Throws when the provider is unknown, or when the provider package is neither installed, registered, nor injected through the config. */\nexport class SecretsHelperFactory {\n static async create(\n opts: ISecretsRegistration & { identifier?: string },\n ): Promise<ISecretsHelper> {\n const shared = {\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n };\n\n // Named before the switch: in `default` the union is exhausted and `opts` is `never`, yet an untyped JS caller can still land there.\n const provider: string = opts.provider;\n\n switch (opts.provider) {\n case SecretProviders.SYSTEM_ENVS: {\n return new SystemEnvsHelper({ identifier: opts.identifier });\n }\n case SecretProviders.HASHICORP_VAULT: {\n // `client` is the injected escape: the helper never reaches for the peer, so demanding it here would defeat the escape.\n if (!opts.config?.client) {\n ModuleUtility.assertInstalled({\n scope: 'HashiCorpVaultHelper',\n modules: ['node-vault'],\n allowRegistered: true,\n });\n }\n\n return new HashiCorpVaultHelper({ ...opts.config, ...shared });\n }\n case SecretProviders.DOTENV_VAULT: {\n // `decode` is the injected escape - same reasoning as `client` above.\n if (!opts.config?.decode) {\n ModuleUtility.assertInstalled({\n scope: 'DotenvVaultHelper',\n modules: ['@dotenvx/dotenvx'],\n allowRegistered: true,\n });\n }\n\n return new DotenvVaultHelper({ ...opts.config, ...shared });\n }\n default: {\n throw getError({\n message: `[createSecretsHelper] Unsupported secret provider: ${provider}`,\n });\n }\n }\n }\n}\n"]}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import type { AnyObject, AnyType } from '../../../common/types/index.js';
|
|
2
1
|
import { AbstractSecretsHelper } from '../base/index.js';
|
|
3
2
|
import { type IClock, type ITimerAdapter } from '../common/index.js';
|
|
4
3
|
import { type TVaultAuth } from './auth.js';
|
|
4
|
+
/** What Vault answers is the body node-vault passes on: nothing is assumed of it, each key is read and narrowed where it is used. */
|
|
5
5
|
interface TVaultClient {
|
|
6
6
|
token: string;
|
|
7
|
-
read(path: string): Promise<
|
|
8
|
-
write(path: string, data:
|
|
9
|
-
approleLogin(opts:
|
|
10
|
-
kubernetesLogin?(opts:
|
|
11
|
-
tokenRenewSelf(): Promise<
|
|
12
|
-
tokenLookupSelf(): Promise<
|
|
7
|
+
read(path: string): Promise<unknown>;
|
|
8
|
+
write(path: string, data: Record<string, unknown>): Promise<unknown>;
|
|
9
|
+
approleLogin(opts: Record<string, unknown>): Promise<unknown>;
|
|
10
|
+
kubernetesLogin?(opts: Record<string, unknown>): Promise<unknown>;
|
|
11
|
+
tokenRenewSelf(): Promise<unknown>;
|
|
12
|
+
tokenLookupSelf(): Promise<unknown>;
|
|
13
13
|
}
|
|
14
14
|
/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */
|
|
15
15
|
export interface IHashiCorpVaultHelperOptions {
|
|
@@ -35,6 +35,8 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
35
35
|
constructor(opts: IHashiCorpVaultHelperOptions);
|
|
36
36
|
configure(): Promise<void>;
|
|
37
37
|
shutdown(): Promise<void>;
|
|
38
|
+
/** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */
|
|
39
|
+
private static readClientToken;
|
|
38
40
|
private requireClient;
|
|
39
41
|
/** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */
|
|
40
42
|
private login;
|
|
@@ -47,8 +49,8 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
47
49
|
}): Promise<{
|
|
48
50
|
value: Record<string, string>;
|
|
49
51
|
lease: {
|
|
50
|
-
leaseId:
|
|
51
|
-
ttlSeconds:
|
|
52
|
+
leaseId: string;
|
|
53
|
+
ttlSeconds: number;
|
|
52
54
|
renewable: boolean;
|
|
53
55
|
};
|
|
54
56
|
} | {
|
|
@@ -59,7 +61,7 @@ export declare class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
59
61
|
leaseId: string;
|
|
60
62
|
ttlSeconds: number;
|
|
61
63
|
}): Promise<{
|
|
62
|
-
ttlSeconds:
|
|
64
|
+
ttlSeconds: number;
|
|
63
65
|
} | null>;
|
|
64
66
|
protected revokeRaw(opts: {
|
|
65
67
|
leaseId: string;
|
|
@@ -4,6 +4,16 @@ import { ModuleUtility } from '../../../utilities/module.utility.js';
|
|
|
4
4
|
import { AbstractSecretsHelper } from '../base/index.js';
|
|
5
5
|
import { VaultAuthMethods } from '../common/index.js';
|
|
6
6
|
import { vaultAuthSchema } from './auth.js';
|
|
7
|
+
/** The object a Vault answer is, or an empty one: a body that is not an object reads as no keys. */
|
|
8
|
+
const toRecord = (value) => {
|
|
9
|
+
return typeof value === 'object' && value !== null
|
|
10
|
+
? Object.fromEntries(Object.entries(value))
|
|
11
|
+
: {};
|
|
12
|
+
};
|
|
13
|
+
/** The nested object under `key` of a Vault answer, or an empty one. */
|
|
14
|
+
const readRecord = (opts) => {
|
|
15
|
+
return toRecord(toRecord(opts.source)[opts.key]);
|
|
16
|
+
};
|
|
7
17
|
/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */
|
|
8
18
|
export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
9
19
|
static { this.TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1; }
|
|
@@ -32,9 +42,10 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
32
42
|
async configure() {
|
|
33
43
|
const logger = this.logger.for(this.configure.name);
|
|
34
44
|
if (!this.client) {
|
|
35
|
-
const result = await ModuleUtility.load({
|
|
36
|
-
|
|
37
|
-
|
|
45
|
+
const result = await ModuleUtility.load({
|
|
46
|
+
module: 'node-vault',
|
|
47
|
+
});
|
|
48
|
+
this.client = result.default({ endpoint: this.endpoint, apiVersion: 'v1' });
|
|
38
49
|
}
|
|
39
50
|
const { ttlSeconds, renewable } = await this.login();
|
|
40
51
|
if (renewable && ttlSeconds > 0) {
|
|
@@ -49,6 +60,14 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
49
60
|
}
|
|
50
61
|
await super.shutdown();
|
|
51
62
|
}
|
|
63
|
+
/** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */
|
|
64
|
+
static readClientToken(opts) {
|
|
65
|
+
const token = opts.auth['client_token'];
|
|
66
|
+
if (typeof token !== 'string' || !token) {
|
|
67
|
+
throw getError({ message: '[HashiCorpVaultHelper.login] Vault answered no client_token' });
|
|
68
|
+
}
|
|
69
|
+
return token;
|
|
70
|
+
}
|
|
52
71
|
requireClient() {
|
|
53
72
|
if (!this.client) {
|
|
54
73
|
throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });
|
|
@@ -61,10 +80,11 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
61
80
|
switch (this.auth.method) {
|
|
62
81
|
case VaultAuthMethods.TOKEN: {
|
|
63
82
|
client.token = this.auth.token;
|
|
64
|
-
const
|
|
83
|
+
const answer = await client.tokenLookupSelf();
|
|
84
|
+
const data = readRecord({ source: answer, key: 'data' });
|
|
65
85
|
return {
|
|
66
|
-
ttlSeconds: Number(
|
|
67
|
-
renewable: Boolean(
|
|
86
|
+
ttlSeconds: Number(data['ttl'] ?? 0),
|
|
87
|
+
renewable: Boolean(data['renewable']),
|
|
68
88
|
};
|
|
69
89
|
}
|
|
70
90
|
case VaultAuthMethods.APP_ROLE: {
|
|
@@ -72,11 +92,12 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
72
92
|
payload['role_id'] = this.auth.roleId;
|
|
73
93
|
payload['secret_id'] = this.auth.secretId;
|
|
74
94
|
payload['mount_point'] = this.auth.mountPath ?? 'approle';
|
|
75
|
-
const
|
|
76
|
-
|
|
95
|
+
const answer = await client.approleLogin(payload);
|
|
96
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
97
|
+
client.token = HashiCorpVaultHelper.readClientToken({ auth });
|
|
77
98
|
return {
|
|
78
|
-
ttlSeconds: Number(
|
|
79
|
-
renewable: Boolean(
|
|
99
|
+
ttlSeconds: Number(auth['lease_duration'] ?? 0),
|
|
100
|
+
renewable: Boolean(auth['renewable']),
|
|
80
101
|
};
|
|
81
102
|
}
|
|
82
103
|
case VaultAuthMethods.KUBERNETES: {
|
|
@@ -89,11 +110,12 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
89
110
|
const jwt = result.trimEnd();
|
|
90
111
|
const payload = { role: this.auth.role, jwt };
|
|
91
112
|
payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';
|
|
92
|
-
const
|
|
93
|
-
|
|
113
|
+
const answer = await client.kubernetesLogin(payload);
|
|
114
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
115
|
+
client.token = HashiCorpVaultHelper.readClientToken({ auth });
|
|
94
116
|
return {
|
|
95
|
-
ttlSeconds: Number(
|
|
96
|
-
renewable: Boolean(
|
|
117
|
+
ttlSeconds: Number(auth['lease_duration'] ?? 0),
|
|
118
|
+
renewable: Boolean(auth['renewable']),
|
|
97
119
|
};
|
|
98
120
|
}
|
|
99
121
|
default: {
|
|
@@ -133,9 +155,10 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
133
155
|
async handleTokenRenewal() {
|
|
134
156
|
const logger = this.logger.for(this.handleTokenRenewal.name);
|
|
135
157
|
try {
|
|
136
|
-
const
|
|
137
|
-
const
|
|
138
|
-
const
|
|
158
|
+
const answer = await this.requireClient().tokenRenewSelf();
|
|
159
|
+
const auth = readRecord({ source: answer, key: 'auth' });
|
|
160
|
+
const ttlSeconds = Number(auth['lease_duration'] ?? 0);
|
|
161
|
+
const renewable = Boolean(auth['renewable']);
|
|
139
162
|
if (renewable && ttlSeconds > 0) {
|
|
140
163
|
this.tokenRenewalRetryCount = 0;
|
|
141
164
|
this.scheduleTokenRenewal({ ttlSeconds });
|
|
@@ -160,21 +183,23 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
160
183
|
}
|
|
161
184
|
async fetchRaw(opts) {
|
|
162
185
|
const res = await this.requireClient().read(opts.path);
|
|
163
|
-
const
|
|
164
|
-
const
|
|
186
|
+
const data = readRecord({ source: res, key: 'data' });
|
|
187
|
+
const nested = data['data'];
|
|
188
|
+
const inner = nested && typeof nested === 'object' ? toRecord(nested) : data;
|
|
165
189
|
const value = {};
|
|
166
|
-
const innerEntries = Object.entries(inner
|
|
190
|
+
const innerEntries = Object.entries(inner);
|
|
167
191
|
for (const [key, raw] of innerEntries) {
|
|
168
192
|
value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);
|
|
169
193
|
}
|
|
170
|
-
const
|
|
171
|
-
|
|
194
|
+
const lease = toRecord(res);
|
|
195
|
+
const leaseId = lease['lease_id'];
|
|
196
|
+
if (typeof leaseId === 'string' && leaseId) {
|
|
172
197
|
return {
|
|
173
198
|
value,
|
|
174
199
|
lease: {
|
|
175
200
|
leaseId,
|
|
176
|
-
ttlSeconds:
|
|
177
|
-
renewable: Boolean(
|
|
201
|
+
ttlSeconds: Number(lease['lease_duration'] ?? 0),
|
|
202
|
+
renewable: Boolean(lease['renewable']),
|
|
178
203
|
},
|
|
179
204
|
};
|
|
180
205
|
}
|
|
@@ -186,7 +211,7 @@ export class HashiCorpVaultHelper extends AbstractSecretsHelper {
|
|
|
186
211
|
const payload = { increment: opts.ttlSeconds };
|
|
187
212
|
payload['lease_id'] = opts.leaseId;
|
|
188
213
|
const res = await this.requireClient().write('sys/leases/renew', payload);
|
|
189
|
-
return { ttlSeconds: res['lease_duration'] ?? opts.ttlSeconds };
|
|
214
|
+
return { ttlSeconds: Number(toRecord(res)['lease_duration'] ?? opts.ttlSeconds) };
|
|
190
215
|
}
|
|
191
216
|
catch (error) {
|
|
192
217
|
logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hashicorp.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/hashicorp/hashicorp.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAsD,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,eAAe,EAAmB,MAAM,QAAQ,CAAC;AA0B1D,uLAAuL;AACvL,MAA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AO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAES,KAAK,CAAC,SAAS,CAAC,IAAyB;QACjD,MAAM,OAAO,GAAc,EAAE,CAAC;QAC9B,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACnC,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport type { AnyObject, AnyType } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { AbstractSecretsHelper } from '../base';\nimport { VaultAuthMethods, type IClock, type ITimerAdapter, type TTimerHandle } from '../common';\nimport { vaultAuthSchema, type TVaultAuth } from './auth';\n\n// node-vault's wire contract uses snake_case (role_id, secret_id, client_token, lease_duration, ...); built/read via bracket-notation on AnyObject here so the snake_case stays confined to this boundary instead of leaking into our camelCase-only typing convention.\ninterface TVaultClient {\n token: string;\n read(path: string): Promise<AnyType>;\n write(path: string, data: AnyObject): Promise<AnyType>;\n approleLogin(opts: AnyObject): Promise<AnyType>;\n kubernetesLogin?(opts: AnyObject): Promise<AnyType>;\n tokenRenewSelf(): Promise<AnyType>;\n tokenLookupSelf(): Promise<AnyType>;\n}\n\n/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */\nexport interface IHashiCorpVaultHelperOptions {\n endpoint: string;\n auth: TVaultAuth;\n identifier?: string;\n cacheTtlSeconds?: number;\n renewBeforeRatio?: number;\n clock?: IClock;\n timers?: ITimerAdapter;\n /** Injection seam for tests; production builds the real node-vault client in configure(). */\n client?: TVaultClient;\n}\n\n/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */\nexport class HashiCorpVaultHelper extends AbstractSecretsHelper {\n private static readonly TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1;\n private static readonly TOKEN_RENEWAL_RETRY_CAP_SECONDS = 60;\n\n private readonly endpoint: string;\n private readonly auth: TVaultAuth;\n private client?: TVaultClient;\n private tokenTimer?: TTimerHandle;\n private tokenRenewalRetryCount = 0;\n\n constructor(opts: IHashiCorpVaultHelperOptions) {\n super({\n scope: HashiCorpVaultHelper.name,\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n clock: opts.clock,\n timers: opts.timers,\n });\n this.endpoint = opts.endpoint;\n\n try {\n this.auth = vaultAuthSchema.parse(opts.auth);\n } catch (error) {\n throw getError({\n message: `[HashiCorpVaultHelper] Invalid Vault auth configuration | ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n\n this.client = opts.client;\n }\n\n override async configure(): Promise<void> {\n const logger = this.logger.for(this.configure.name);\n\n if (!this.client) {\n const result = await ModuleUtility.load<AnyType>({ module: 'node-vault' });\n const factory = result.default;\n this.client = factory({ endpoint: this.endpoint, apiVersion: 'v1' }) as TVaultClient;\n }\n\n const { ttlSeconds, renewable } = await this.login();\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n\n logger.info('Vault authenticated | endpoint: %s | method: %s', this.endpoint, this.auth.method);\n }\n\n override async shutdown(): Promise<void> {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n this.tokenTimer = undefined;\n }\n\n await super.shutdown();\n }\n\n private requireClient(): TVaultClient {\n if (!this.client) {\n throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });\n }\n\n return this.client;\n }\n\n /** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */\n private async login(): Promise<{ ttlSeconds: number; renewable: boolean }> {\n const client = this.requireClient();\n\n switch (this.auth.method) {\n case VaultAuthMethods.TOKEN: {\n client.token = this.auth.token;\n const res = await client.tokenLookupSelf();\n\n return {\n ttlSeconds: Number(res?.data?.['ttl'] ?? 0),\n renewable: Boolean(res?.data?.['renewable']),\n };\n }\n case VaultAuthMethods.APP_ROLE: {\n const payload: AnyObject = {};\n payload['role_id'] = this.auth.roleId;\n payload['secret_id'] = this.auth.secretId;\n payload['mount_point'] = this.auth.mountPath ?? 'approle';\n const res = await client.approleLogin(payload);\n client.token = res.auth['client_token'];\n\n return {\n ttlSeconds: Number(res.auth['lease_duration'] ?? 0),\n renewable: Boolean(res.auth['renewable']),\n };\n }\n case VaultAuthMethods.KUBERNETES: {\n if (!client.kubernetesLogin) {\n throw getError({\n message: '[HashiCorpVaultHelper.login] node-vault client lacks kubernetesLogin',\n });\n }\n\n const result = await readFile(\n this.auth.jwtPath ?? '/var/run/secrets/kubernetes.io/serviceaccount/token',\n 'utf8',\n );\n const jwt = result.trimEnd();\n const payload: AnyObject = { role: this.auth.role, jwt };\n payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';\n const res = await client.kubernetesLogin(payload);\n client.token = res.auth['client_token'];\n\n return {\n ttlSeconds: Number(res.auth['lease_duration'] ?? 0),\n renewable: Boolean(res.auth['renewable']),\n };\n }\n default: {\n throw getError({ message: '[HashiCorpVaultHelper.login] Unsupported auth method' });\n }\n }\n }\n\n private scheduleTokenRenewal(opts: { ttlSeconds: number }): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n const delayMs = Math.max(0, opts.ttlSeconds * this.renewBeforeRatio * 1000);\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewal.name)\n .error('Token renewal handler crashed | error: %s', error);\n });\n }, delayMs);\n }\n\n /** Without a reschedule here, a transient re-auth failure lets the token expire silently with no recovery - retry with the same capped exponential backoff as lease renewal. */\n private scheduleTokenRenewalRetry(): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n this.tokenRenewalRetryCount += 1;\n const backoffSeconds = Math.min(\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_CAP_SECONDS,\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_BASE_SECONDS *\n 2 ** (this.tokenRenewalRetryCount - 1),\n );\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewalRetry.name)\n .error('Token renewal retry handler crashed | error: %s', error);\n });\n }, backoffSeconds * 1000);\n }\n\n private async handleTokenRenewal(): Promise<void> {\n const logger = this.logger.for(this.handleTokenRenewal.name);\n\n try {\n const res = await this.requireClient().tokenRenewSelf();\n const ttlSeconds = Number(res?.auth?.['lease_duration'] ?? 0);\n const renewable = Boolean(res?.auth?.['renewable']);\n\n if (renewable && ttlSeconds > 0) {\n this.tokenRenewalRetryCount = 0;\n this.scheduleTokenRenewal({ ttlSeconds });\n\n return;\n }\n\n logger.warn('Token renewal returned a non-renewable/expired token; re-authenticating');\n } catch (error) {\n logger.warn('Token renewal failed; re-authenticating | error: %s', error);\n }\n\n try {\n const { ttlSeconds, renewable } = await this.login();\n this.tokenRenewalRetryCount = 0;\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n } catch (error) {\n logger.error('Token re-authentication failed; scheduling bounded retry | error: %s', error);\n this.scheduleTokenRenewalRetry();\n }\n }\n\n protected async fetchRaw(opts: { path: string }) {\n const res = await this.requireClient().read(opts.path);\n const nested = res?.['data']?.['data'];\n const inner = nested && typeof nested === 'object' ? nested : res?.['data'];\n const value: Record<string, string> = {};\n const innerEntries = Object.entries(inner ?? {});\n\n for (const [key, raw] of innerEntries) {\n value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);\n }\n\n const leaseId = res?.['lease_id'];\n\n if (leaseId) {\n return {\n value,\n lease: {\n leaseId,\n ttlSeconds: res['lease_duration'] ?? 0,\n renewable: Boolean(res['renewable']),\n },\n };\n }\n\n return { value };\n }\n\n protected async renewRaw(opts: { leaseId: string; ttlSeconds: number }) {\n const logger = this.logger.for(this.renewRaw.name);\n\n try {\n const payload: AnyObject = { increment: opts.ttlSeconds };\n payload['lease_id'] = opts.leaseId;\n const res = await this.requireClient().write('sys/leases/renew', payload);\n\n return { ttlSeconds: res['lease_duration'] ?? opts.ttlSeconds };\n } catch (error) {\n logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);\n\n return null;\n }\n }\n\n protected async revokeRaw(opts: { leaseId: string }) {\n const payload: AnyObject = {};\n payload['lease_id'] = opts.leaseId;\n await this.requireClient().write('sys/leases/revoke', payload);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"hashicorp.helper.js","sourceRoot":"","sources":["../../../../../src/modules/secrets/hashicorp/hashicorp.helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAsD,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,eAAe,EAAmB,MAAM,QAAQ,CAAC;AAc1D,oGAAoG;AACpG,MAAM,QAAQ,GAAG,CAAC,KAAc,EAA2B,EAAE;IAC3D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAChD,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QAC3C,CAAC,CAAC,EAAE,CAAC;AACT,CAAC,CAAC;AAEF,wEAAwE;AACxE,MAAM,UAAU,GAAG,CAAC,IAAsC,EAA2B,EAAE;IACrF,OAAO,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AACnD,CAAC,CAAC;AAeF,uLAAuL;AACvL,MAAM,OAAO,oBAAqB,SA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,WAAW,CAAC,CAAC;iBACvC;aACF,CAAC;QACJ,CAAC;QAED,OAAO,EAAE,KAAK,EAAE,CAAC;IACnB,CAAC;IAES,KAAK,CAAC,QAAQ,CAAC,IAA6C;QACpE,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAEnD,IAAI,CAAC;YACH,MAAM,OAAO,GAA4B,EAAE,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC;YACxE,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;YACnC,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,kBAAkB,EAAE,OAAO,CAAC,CAAC;YAE1E,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,gBAAgB,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACpF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,IAAI,CAAC,0CAA0C,EAAE,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;YAE7E,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAES,KAAK,CAAC,SAAS,CAAC,IAAyB;QACjD,MAAM,OAAO,GAA4B,EAAE,CAAC;QAC5C,OAAO,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC;QACnC,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,mBAAmB,EAAE,OAAO,CAAC,CAAC;IACjE,CAAC","sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { getError } from '@/modules/error';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport { AbstractSecretsHelper } from '../base';\nimport { VaultAuthMethods, type IClock, type ITimerAdapter, type TTimerHandle } from '../common';\nimport { vaultAuthSchema, type TVaultAuth } from './auth';\n\n// node-vault's wire contract uses snake_case (role_id, secret_id, client_token, lease_duration, ...); built/read via bracket-notation on a record here so the snake_case stays confined to this boundary instead of leaking into our camelCase-only typing convention.\n/** What Vault answers is the body node-vault passes on: nothing is assumed of it, each key is read and narrowed where it is used. */\ninterface TVaultClient {\n token: string;\n read(path: string): Promise<unknown>;\n write(path: string, data: Record<string, unknown>): Promise<unknown>;\n approleLogin(opts: Record<string, unknown>): Promise<unknown>;\n kubernetesLogin?(opts: Record<string, unknown>): Promise<unknown>;\n tokenRenewSelf(): Promise<unknown>;\n tokenLookupSelf(): Promise<unknown>;\n}\n\n/** The object a Vault answer is, or an empty one: a body that is not an object reads as no keys. */\nconst toRecord = (value: unknown): Record<string, unknown> => {\n return typeof value === 'object' && value !== null\n ? Object.fromEntries(Object.entries(value))\n : {};\n};\n\n/** The nested object under `key` of a Vault answer, or an empty one. */\nconst readRecord = (opts: { source: unknown; key: string }): Record<string, unknown> => {\n return toRecord(toRecord(opts.source)[opts.key]);\n};\n\n/** Options for `HashiCorpVaultHelper`. `auth` is validated on construction; `client` replaces the `node-vault` client the helper would otherwise create. */\nexport interface IHashiCorpVaultHelperOptions {\n endpoint: string;\n auth: TVaultAuth;\n identifier?: string;\n cacheTtlSeconds?: number;\n renewBeforeRatio?: number;\n clock?: IClock;\n timers?: ITimerAdapter;\n /** Injection seam for tests; production builds the real node-vault client in configure(). */\n client?: TVaultClient;\n}\n\n/** Secrets provider backed by HashiCorp Vault via `node-vault`. `configure()` must run before use; it logs in and schedules renewal of the Vault token when the token is renewable. */\nexport class HashiCorpVaultHelper extends AbstractSecretsHelper {\n private static readonly TOKEN_RENEWAL_RETRY_BASE_SECONDS = 1;\n private static readonly TOKEN_RENEWAL_RETRY_CAP_SECONDS = 60;\n\n private readonly endpoint: string;\n private readonly auth: TVaultAuth;\n private client?: TVaultClient;\n private tokenTimer?: TTimerHandle;\n private tokenRenewalRetryCount = 0;\n\n constructor(opts: IHashiCorpVaultHelperOptions) {\n super({\n scope: HashiCorpVaultHelper.name,\n identifier: opts.identifier,\n cacheTtlSeconds: opts.cacheTtlSeconds,\n renewBeforeRatio: opts.renewBeforeRatio,\n clock: opts.clock,\n timers: opts.timers,\n });\n this.endpoint = opts.endpoint;\n\n try {\n this.auth = vaultAuthSchema.parse(opts.auth);\n } catch (error) {\n throw getError({\n message: `[HashiCorpVaultHelper] Invalid Vault auth configuration | ${\n error instanceof Error ? error.message : String(error)\n }`,\n });\n }\n\n this.client = opts.client;\n }\n\n override async configure(): Promise<void> {\n const logger = this.logger.for(this.configure.name);\n\n if (!this.client) {\n const result = await ModuleUtility.load<{\n default: (opts: { endpoint: string; apiVersion: string }) => TVaultClient;\n }>({\n module: 'node-vault',\n });\n this.client = result.default({ endpoint: this.endpoint, apiVersion: 'v1' });\n }\n\n const { ttlSeconds, renewable } = await this.login();\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n\n logger.info('Vault authenticated | endpoint: %s | method: %s', this.endpoint, this.auth.method);\n }\n\n override async shutdown(): Promise<void> {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n this.tokenTimer = undefined;\n }\n\n await super.shutdown();\n }\n\n /** The `client_token` of a login answer: a login that carries none is refused, where an undefined token would fail on the first read. */\n private static readClientToken(opts: { auth: Record<string, unknown> }): string {\n const token = opts.auth['client_token'];\n\n if (typeof token !== 'string' || !token) {\n throw getError({ message: '[HashiCorpVaultHelper.login] Vault answered no client_token' });\n }\n\n return token;\n }\n\n private requireClient(): TVaultClient {\n if (!this.client) {\n throw getError({ message: '[HashiCorpVaultHelper] configure() must run before use' });\n }\n\n return this.client;\n }\n\n /** Authenticates against Vault and returns the resulting token's TTL/renewability so callers can schedule self-renewal. */\n private async login(): Promise<{ ttlSeconds: number; renewable: boolean }> {\n const client = this.requireClient();\n\n switch (this.auth.method) {\n case VaultAuthMethods.TOKEN: {\n client.token = this.auth.token;\n const answer = await client.tokenLookupSelf();\n const data = readRecord({ source: answer, key: 'data' });\n\n return {\n ttlSeconds: Number(data['ttl'] ?? 0),\n renewable: Boolean(data['renewable']),\n };\n }\n case VaultAuthMethods.APP_ROLE: {\n const payload: Record<string, unknown> = {};\n payload['role_id'] = this.auth.roleId;\n payload['secret_id'] = this.auth.secretId;\n payload['mount_point'] = this.auth.mountPath ?? 'approle';\n const answer = await client.approleLogin(payload);\n const auth = readRecord({ source: answer, key: 'auth' });\n client.token = HashiCorpVaultHelper.readClientToken({ auth });\n\n return {\n ttlSeconds: Number(auth['lease_duration'] ?? 0),\n renewable: Boolean(auth['renewable']),\n };\n }\n case VaultAuthMethods.KUBERNETES: {\n if (!client.kubernetesLogin) {\n throw getError({\n message: '[HashiCorpVaultHelper.login] node-vault client lacks kubernetesLogin',\n });\n }\n\n const result = await readFile(\n this.auth.jwtPath ?? '/var/run/secrets/kubernetes.io/serviceaccount/token',\n 'utf8',\n );\n const jwt = result.trimEnd();\n const payload: Record<string, unknown> = { role: this.auth.role, jwt };\n payload['mount_point'] = this.auth.mountPath ?? 'kubernetes';\n const answer = await client.kubernetesLogin(payload);\n const auth = readRecord({ source: answer, key: 'auth' });\n client.token = HashiCorpVaultHelper.readClientToken({ auth });\n\n return {\n ttlSeconds: Number(auth['lease_duration'] ?? 0),\n renewable: Boolean(auth['renewable']),\n };\n }\n default: {\n throw getError({ message: '[HashiCorpVaultHelper.login] Unsupported auth method' });\n }\n }\n }\n\n private scheduleTokenRenewal(opts: { ttlSeconds: number }): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n const delayMs = Math.max(0, opts.ttlSeconds * this.renewBeforeRatio * 1000);\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewal.name)\n .error('Token renewal handler crashed | error: %s', error);\n });\n }, delayMs);\n }\n\n /** Without a reschedule here, a transient re-auth failure lets the token expire silently with no recovery - retry with the same capped exponential backoff as lease renewal. */\n private scheduleTokenRenewalRetry(): void {\n if (this.tokenTimer) {\n this.timers.clear(this.tokenTimer);\n }\n\n this.tokenRenewalRetryCount += 1;\n const backoffSeconds = Math.min(\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_CAP_SECONDS,\n HashiCorpVaultHelper.TOKEN_RENEWAL_RETRY_BASE_SECONDS *\n 2 ** (this.tokenRenewalRetryCount - 1),\n );\n this.tokenTimer = this.timers.set(() => {\n this.handleTokenRenewal().catch((error) => {\n this.logger\n .for(this.scheduleTokenRenewalRetry.name)\n .error('Token renewal retry handler crashed | error: %s', error);\n });\n }, backoffSeconds * 1000);\n }\n\n private async handleTokenRenewal(): Promise<void> {\n const logger = this.logger.for(this.handleTokenRenewal.name);\n\n try {\n const answer = await this.requireClient().tokenRenewSelf();\n const auth = readRecord({ source: answer, key: 'auth' });\n const ttlSeconds = Number(auth['lease_duration'] ?? 0);\n const renewable = Boolean(auth['renewable']);\n\n if (renewable && ttlSeconds > 0) {\n this.tokenRenewalRetryCount = 0;\n this.scheduleTokenRenewal({ ttlSeconds });\n\n return;\n }\n\n logger.warn('Token renewal returned a non-renewable/expired token; re-authenticating');\n } catch (error) {\n logger.warn('Token renewal failed; re-authenticating | error: %s', error);\n }\n\n try {\n const { ttlSeconds, renewable } = await this.login();\n this.tokenRenewalRetryCount = 0;\n\n if (renewable && ttlSeconds > 0) {\n this.scheduleTokenRenewal({ ttlSeconds });\n }\n } catch (error) {\n logger.error('Token re-authentication failed; scheduling bounded retry | error: %s', error);\n this.scheduleTokenRenewalRetry();\n }\n }\n\n protected async fetchRaw(opts: { path: string }) {\n const res = await this.requireClient().read(opts.path);\n const data = readRecord({ source: res, key: 'data' });\n const nested = data['data'];\n const inner = nested && typeof nested === 'object' ? toRecord(nested) : data;\n const value: Record<string, string> = {};\n const innerEntries = Object.entries(inner);\n\n for (const [key, raw] of innerEntries) {\n value[key] = typeof raw === 'string' ? raw : JSON.stringify(raw);\n }\n\n const lease = toRecord(res);\n const leaseId = lease['lease_id'];\n\n if (typeof leaseId === 'string' && leaseId) {\n return {\n value,\n lease: {\n leaseId,\n ttlSeconds: Number(lease['lease_duration'] ?? 0),\n renewable: Boolean(lease['renewable']),\n },\n };\n }\n\n return { value };\n }\n\n protected async renewRaw(opts: { leaseId: string; ttlSeconds: number }) {\n const logger = this.logger.for(this.renewRaw.name);\n\n try {\n const payload: Record<string, unknown> = { increment: opts.ttlSeconds };\n payload['lease_id'] = opts.leaseId;\n const res = await this.requireClient().write('sys/leases/renew', payload);\n\n return { ttlSeconds: Number(toRecord(res)['lease_duration'] ?? opts.ttlSeconds) };\n } catch (error) {\n logger.warn('Renew rejected | leaseId: %s | error: %s', opts.leaseId, error);\n\n return null;\n }\n }\n\n protected async revokeRaw(opts: { leaseId: string }) {\n const payload: Record<string, unknown> = {};\n payload['lease_id'] = opts.leaseId;\n await this.requireClient().write('sys/leases/revoke', payload);\n }\n}\n"]}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import { type AnyObject } from '../../../common/index.js';
|
|
2
1
|
import { BaseHelper } from '../../base.js';
|
|
3
2
|
/** An in-process keyed container, NOT an `IStorageHelper`: it stores values, not objects in a bucket. */
|
|
4
|
-
export declare class MemoryStorageHelper<T extends object =
|
|
3
|
+
export declare class MemoryStorageHelper<T extends object = Record<string, unknown>> extends BaseHelper {
|
|
5
4
|
private container;
|
|
6
5
|
constructor(opts?: {
|
|
7
6
|
scope?: string;
|
|
8
7
|
});
|
|
9
|
-
static newInstance<T extends object =
|
|
8
|
+
static newInstance<T extends object = Record<string, unknown>>(): MemoryStorageHelper<T>;
|
|
10
9
|
isBound(key: keyof T): boolean;
|
|
11
10
|
get<K extends keyof T>(key: K): T[K] | undefined;
|
|
12
11
|
set<K extends keyof T>(key: K, value: T[K]): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/in-memory/helper.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/storage/in-memory/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,yGAAyG;AACzG,MAAM,OAAO,mBAAgE,SAAQ,UAAU;IAG7F,YAAY,IAAyB;QACnC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAHpD,cAAS,GAAG,IAAI,GAAG,EAAuB,CAAC;IAInD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,OAAO,IAAI,mBAAmB,EAAK,CAAC;IACtC,CAAC;IAED,OAAO,CAAC,GAAY;QAClB,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;IAED,GAAG,CAAoB,GAAM;QAC3B,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAqB,CAAC;IACrD,CAAC;IAED,GAAG,CAAoB,GAAM,EAAE,KAAW;QACxC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,uFAAuF;IACvF,KAAK,CAAC,GAAY;QAChB,OAAO,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IACpC,CAAC;IAED,IAAI;QACF,OAAO,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;IACpC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;IAC7B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;IACzB,CAAC;IAED,gGAAgG;IAChG,YAAY;QACV,OAAO,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,SAAiC,CAAC,CAAC;IACpE,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\n\n/** An in-process keyed container, NOT an `IStorageHelper`: it stores values, not objects in a bucket. */\nexport class MemoryStorageHelper<T extends object = Record<string, unknown>> extends BaseHelper {\n private container = new Map<keyof T, T[keyof T]>();\n\n constructor(opts?: { scope?: string }) {\n super({ scope: opts?.scope ?? MemoryStorageHelper.name });\n }\n\n static newInstance<T extends object = Record<string, unknown>>() {\n return new MemoryStorageHelper<T>();\n }\n\n isBound(key: keyof T): boolean {\n return this.container.has(key);\n }\n\n get<K extends keyof T>(key: K): T[K] | undefined {\n return this.container.get(key) as T[K] | undefined;\n }\n\n set<K extends keyof T>(key: K, value: T[K]): void {\n this.container.set(key, value);\n }\n\n /** `false` when the key was not bound, so a caller can tell a removal from a no-op. */\n unset(key: keyof T): boolean {\n return this.container.delete(key);\n }\n\n keys(): Array<keyof T> {\n return [...this.container.keys()];\n }\n\n get size(): number {\n return this.container.size;\n }\n\n clear(): void {\n this.container.clear();\n }\n\n /** A COPY: handing out the live map let a caller mutate this helper's state behind its back. */\n getContainer(): Record<string, unknown> {\n return Object.fromEntries(this.container as Map<string, unknown>);\n }\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type ValueOrPromise } from '../../../common/types/index.js';
|
|
2
2
|
import { type MessagePort, type Transferable, type Worker, type WorkerOptions } from 'node:worker_threads';
|
|
3
3
|
/** A managed `Worker` and the hooks fired for its lifecycle events. */
|
|
4
4
|
export interface IWorker<MessageType> {
|
|
@@ -21,7 +21,7 @@ export interface IWorker<MessageType> {
|
|
|
21
21
|
/** Message buses held by a worker thread, keyed by name. */
|
|
22
22
|
export interface IWorkerThread {
|
|
23
23
|
buses: {
|
|
24
|
-
[workerKey: string | symbol]: IWorkerBus<
|
|
24
|
+
[workerKey: string | symbol]: IWorkerBus<never, never>;
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
27
|
/** The callbacks a bus invokes for the events of its port. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import { type ValueOrPromise } from '@/common/types';\nimport {\n type MessagePort,\n type Transferable,\n type Worker,\n type WorkerOptions,\n} from 'node:worker_threads';\n\n/** A managed `Worker` and the hooks fired for its lifecycle events. */\nexport interface IWorker<MessageType> {\n worker: Worker;\n options: WorkerOptions;\n\n onOnline(): ValueOrPromise<void>;\n onExit(opts: { code: string | number }): ValueOrPromise<void>;\n onError(opts: { error: Error }): ValueOrPromise<void>;\n onMessage(opts: { message: MessageType }): ValueOrPromise<void>;\n onMessageError(opts: { error: Error }): ValueOrPromise<void>;\n}\n\n/** Message buses held by a worker thread, keyed by name. */\nexport interface IWorkerThread {\n buses: {\n [workerKey: string | symbol]: IWorkerBus<never, never>;\n };\n}\n\n/** The callbacks a bus invokes for the events of its port. */\nexport interface IWorkerMessageBusHandler<IConsumePayload> {\n onMessage: (opts: { message: IConsumePayload }) => ValueOrPromise<void>;\n\n onClose: () => ValueOrPromise<void>;\n onError: (opts: { error: Error }) => ValueOrPromise<void>;\n onExit: (opts: { exitCode: number | string }) => ValueOrPromise<void>;\n}\n\n/** A message channel over a `MessagePort`: `handler` receives incoming messages, `postMessage` sends outgoing ones, with optional hooks around each send. */\nexport interface IWorkerBus<IConsumePayload, IPublishPayload> {\n port: MessagePort;\n handler: IWorkerMessageBusHandler<IConsumePayload>;\n\n onBeforePostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n onAfterPostMessage?(opts: { message: IPublishPayload }): ValueOrPromise<void>;\n postMessage(opts: {\n message: IPublishPayload;\n transferList: readonly Transferable[] | undefined;\n }): ValueOrPromise<void>;\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type ValueOrPromise } from '../../../common/types/index.js';
|
|
2
2
|
import { BaseHelper } from '../../base.js';
|
|
3
3
|
import { type IWorkerBus, type IWorkerThread } from '../common/index.js';
|
|
4
4
|
/** Base for the worker-side helper that holds message buses by key. */
|
|
5
5
|
export declare abstract class AbstractWorkerThreadHelper extends BaseHelper implements IWorkerThread {
|
|
6
6
|
buses: {
|
|
7
|
-
[workerKey: string | symbol]: IWorkerBus<
|
|
7
|
+
[workerKey: string | symbol]: IWorkerBus<never, never>;
|
|
8
8
|
};
|
|
9
9
|
abstract bindWorkerBus<IC, IP>(opts: {
|
|
10
10
|
key: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/abstract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAG5C,uEAAuE;AACvE,MAAM,OAAgB,0BAA2B,SAAQ,UAAU;CAWlE","sourcesContent":["import { type
|
|
1
|
+
{"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/modules/worker-thread/thread/abstract.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAG5C,uEAAuE;AACvE,MAAM,OAAgB,0BAA2B,SAAQ,UAAU;CAWlE","sourcesContent":["import { type ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '@/modules/base';\nimport { type IWorkerBus, type IWorkerThread } from '../common';\n\n/** Base for the worker-side helper that holds message buses by key. */\nexport abstract class AbstractWorkerThreadHelper extends BaseHelper implements IWorkerThread {\n buses: {\n [workerKey: string | symbol]: IWorkerBus<never, never>;\n };\n\n abstract bindWorkerBus<IC, IP>(opts: {\n key: string;\n bus: IWorkerBus<IC, IP>;\n }): ValueOrPromise<void>;\n\n abstract getWorkerBus<IC, IP>(opts: { key: string }): IWorkerBus<IC, IP>;\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { type IWorker } from './common/index.js';
|
|
|
3
3
|
/** Registry of workers by key. `register` refuses a worker once the pool holds one per CPU core, unless `ignoreMaxWarning` is set, and refuses a duplicate key; `getInstance()` returns the shared pool. */
|
|
4
4
|
export declare class WorkerPoolHelper extends BaseHelper {
|
|
5
5
|
private static instance;
|
|
6
|
-
protected registry: Map<string | symbol, IWorker<
|
|
6
|
+
protected registry: Map<string | symbol, IWorker<unknown>>;
|
|
7
7
|
private numberOfCPUs;
|
|
8
8
|
private ignoreMaxWarning;
|
|
9
9
|
constructor(opts?: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-pool.js","sourceRoot":"","sources":["../../../../src/modules/worker-thread/worker-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AAGzB,4MAA4M;AAC5M,MAAM,OAAO,gBAAiB,SAAQ,UAAU;IAO9C,YAAY,IAAqC;QAC/C,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;QAE5B,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,gBAAgB,GAAG,IAAI,EAAE,gBAAgB,IAAI,KAAK,CAAC;IAC1D,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,CAAC;YAC/B,gBAAgB,CAAC,QAAQ,GAAG,IAAI,gBAAgB,CAAC,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC,CAAC;QAChF,CAAC;QAED,OAAO,gBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI;Q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,uDAAuD,EAAE,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAE1F,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAqB;QACpC,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAErB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,IAAI,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;YAEtE,OAAO;QACT,CAAC;QAED,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;QAErC,gKAAgK;QAChK,IAAI,CAAC;YACH,MAAM,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;QACxC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,KAAK,CAAC,kDAAkD,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;aACzB,IAAI,CAAC,yDAAyD,EAAE,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC9F,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport os from 'node:os';\nimport { type IWorker } from './common';\n\n/** Registry of workers by key. `register` refuses a worker once the pool holds one per CPU core, unless `ignoreMaxWarning` is set, and refuses a duplicate key; `getInstance()` returns the shared pool. */\nexport class WorkerPoolHelper extends BaseHelper {\n private static instance: WorkerPoolHelper;\n protected registry: Map<string | symbol, IWorker<
|
|
1
|
+
{"version":3,"file":"worker-pool.js","sourceRoot":"","sources":["../../../../src/modules/worker-thread/worker-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,MAAM,SAAS,CAAC;AAGzB,4MAA4M;AAC5M,MAAM,OAAO,gBAAiB,SAAQ,UAAU;IAO9C,YAAY,IAAqC;QAC/C,KAAK,CAAC,EAAE,KAAK,EAAE,gBAAgB,CAAC,IAAI,EAAE,CAAC,CAAC;QACxC,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC;QAE5B,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,MAAM,CAAC;QAChC,IAAI,CAAC,gBAAgB,GAAG,IAAI,EAAE,gBAAgB,IAAI,KAAK,CAAC;IAC1D,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,CAAC;YAC/B,gBAAgB,CAAC,QAAQ,GAAG,IAAI,gBAAgB,CAAC,EAAE,gBAAgB,EAAE,KAAK,EAAE,CAAC,CAAC;QAChF,CAAC;QAED,OAAO,gBAAgB,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;IAC5B,CAAC;IAED,GAAG,CAAc,IAAqB;QACpC,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAqC,CAAC;IACzE,CAAC;IAED,GAAG,CAAC,IAAqB;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC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AAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,IAAI,CAAC,uDAAuD,EAAE,GAAG,CAAC,CAAC;YAEtE,OAAO;QACT,CAAC;QAED,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC;QAErC,gKAAgK;QAChK,IAAI,CAAC;YACH,MAAM,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;QACxC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;iBACzB,KAAK,CAAC,kDAAkD,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;QAC3E,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC1B,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;aACzB,IAAI,CAAC,yDAAyD,EAAE,GAAG,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC9F,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport os from 'node:os';\nimport { type IWorker } from './common';\n\n/** Registry of workers by key. `register` refuses a worker once the pool holds one per CPU core, unless `ignoreMaxWarning` is set, and refuses a duplicate key; `getInstance()` returns the shared pool. */\nexport class WorkerPoolHelper extends BaseHelper {\n private static instance: WorkerPoolHelper;\n protected registry: Map<string | symbol, IWorker<unknown>>;\n\n private numberOfCPUs: number;\n private ignoreMaxWarning: boolean;\n\n constructor(opts?: { ignoreMaxWarning?: boolean }) {\n super({ scope: WorkerPoolHelper.name });\n this.registry = new Map([]);\n\n const cpus = os.cpus();\n this.numberOfCPUs = cpus.length;\n this.ignoreMaxWarning = opts?.ignoreMaxWarning ?? false;\n }\n\n static getInstance(): WorkerPoolHelper {\n if (!WorkerPoolHelper.instance) {\n WorkerPoolHelper.instance = new WorkerPoolHelper({ ignoreMaxWarning: false });\n }\n\n return WorkerPoolHelper.instance;\n }\n\n size() {\n return this.registry.size;\n }\n\n get<MessageType>(opts: { key: string }) {\n return this.registry.get(opts.key) as IWorker<MessageType> | undefined;\n }\n\n has(opts: { key: string }) {\n return this.registry.has(opts.key);\n }\n\n register<MessageType>(opts: { key: string; worker: IWorker<MessageType> }) {\n if (!this.registry) {\n throw getError({\n message:\n '[register] Invalid worker registry instance | please init registry before register new worker!',\n });\n }\n\n if (this.registry.size >= this.numberOfCPUs && !this.ignoreMaxWarning) {\n this.logger\n .for(this.register.name)\n .warn(\n 'SKIP register worker | Pool size reached maximum number of cores | CPUs: %s | ignoreMaxWarning: %s',\n this.numberOfCPUs,\n this.ignoreMaxWarning,\n );\n\n return false;\n }\n\n const { key, worker } = opts;\n\n if (this.registry.has(key)) {\n this.logger\n .for(this.register.name)\n .error('SKIP register worker | Worker key existed in pool | key: %s', key);\n\n return false;\n }\n\n this.registry.set(key, worker);\n this.logger\n .for(this.register.name)\n .info('Successfully register worker | key: %s | poolSize: %s', key, this.registry.size);\n\n return true;\n }\n\n async unregister(opts: { key: string }) {\n const { key } = opts;\n\n if (!this.has({ key })) {\n this.logger\n .for(this.unregister.name)\n .warn('SKIP unregister worker | Worker not existed | key: %s', key);\n\n return;\n }\n\n const registered = this.get({ key });\n\n // The registry entry must go even if the thread refuses to die, otherwise the key is unusable forever and the pool never drops back below its max-workers bound\n try {\n await registered?.worker?.terminate();\n } catch (error) {\n this.logger\n .for(this.unregister.name)\n .error('Failed to terminate worker | key: %s | error: %s', key, error);\n }\n\n this.registry.delete(key);\n this.logger\n .for(this.unregister.name)\n .info('Successfully unregister worker | key: %s | poolSize: %s', key, this.registry.size);\n }\n}\n"]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import type { AnyType } from '../common/types/index.js';
|
|
2
1
|
/** Loads an optional peer without letting `Bun.build` see it: every specifier stays a parameter, so there is no literal (nor a `minify.syntax`-folded const) for the bundler to resolve. */
|
|
3
2
|
export declare class ModuleUtility {
|
|
4
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Peers handed over by the application, keyed by specifier. Checked before any filesystem lookup. The map lives in a globalThis slot because a process (or a compiled bundle) can carry two copies of this module, and a peer registered through one copy must be found by the other.
|
|
5
|
+
*
|
|
6
|
+
* The one deliberate `any` of this class: a module's shape is whatever the peer is, and `load<T>`/`loadSync<T>` hand it back as the `T` the caller names, as `import()` and `require()` do (both answer `any`).
|
|
7
|
+
*/
|
|
5
8
|
private static readonly registered;
|
|
6
9
|
private static sharedRegistry;
|
|
7
10
|
/** Called by the application once it knows its root (`configs.projectRoot` or the cwd); every peer lookup below follows it. Delegates to `ProjectRootRegistry`, which a browser Worker host reaches too through `/core` - the two must share ONE slot. */
|
|
@@ -23,7 +26,7 @@ export declare class ModuleUtility {
|
|
|
23
26
|
* module after the first.
|
|
24
27
|
*/
|
|
25
28
|
static register(opts: {
|
|
26
|
-
modules: Record<string,
|
|
29
|
+
modules: Record<string, unknown>;
|
|
27
30
|
}): void;
|
|
28
31
|
/**
|
|
29
32
|
* The file `module` resolves to from the project root under the ES module conditions (`import`), so
|
|
@@ -37,7 +40,7 @@ export declare class ModuleUtility {
|
|
|
37
40
|
* one. A module handed over with {@link register} wins; one that does not resolve from the project root is
|
|
38
41
|
* imported by name as before. Use this everywhere except a constructor, which cannot await - see {@link preload}.
|
|
39
42
|
*/
|
|
40
|
-
static load<T =
|
|
43
|
+
static load<T = unknown>(opts: {
|
|
41
44
|
module: string;
|
|
42
45
|
}): Promise<T>;
|
|
43
46
|
/**
|
|
@@ -55,7 +58,7 @@ export declare class ModuleUtility {
|
|
|
55
58
|
* the one an application's `import` holds, and `instanceof` across the two fails. `await preload(...)` at the
|
|
56
59
|
* entrypoint registers the ES module copy first, and this returns that.
|
|
57
60
|
*/
|
|
58
|
-
static loadSync<T =
|
|
61
|
+
static loadSync<T = unknown>(opts: {
|
|
59
62
|
module: string;
|
|
60
63
|
}): T;
|
|
61
64
|
/**
|
|
@@ -7,7 +7,11 @@ import { ProjectRootRegistry } from './project-root.utility.js';
|
|
|
7
7
|
const logger = LoggerFactory.getLogger(['ModuleUtility']);
|
|
8
8
|
/** Loads an optional peer without letting `Bun.build` see it: every specifier stays a parameter, so there is no literal (nor a `minify.syntax`-folded const) for the bundler to resolve. */
|
|
9
9
|
export class ModuleUtility {
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Peers handed over by the application, keyed by specifier. Checked before any filesystem lookup. The map lives in a globalThis slot because a process (or a compiled bundle) can carry two copies of this module, and a peer registered through one copy must be found by the other.
|
|
12
|
+
*
|
|
13
|
+
* The one deliberate `any` of this class: a module's shape is whatever the peer is, and `load<T>`/`loadSync<T>` hand it back as the `T` the caller names, as `import()` and `require()` do (both answer `any`).
|
|
14
|
+
*/
|
|
11
15
|
static { this.registered = ModuleUtility.sharedRegistry(); }
|
|
12
16
|
static sharedRegistry() {
|
|
13
17
|
const slot = Symbol.for('ignis:module-registry');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"module.utility.js","sourceRoot":"","sources":["../../../src/utilities/module.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE7D,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC;AAE1D,4LAA4L;AAC5L,MAAM,OAAO,aAAa;IACxB,0RAA0R;aAClQ,eAAU,GAAyB,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,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,eAAe,CAAC,IAItB;QACC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,eAAe,GAAG,KAAK,EAAE,GAAG,IAAI,CAAC;QACzD,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;QAErC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,eAAe,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnD,SAAS;YACX,CAAC;YAED,IAAI,CAAC;gBACH,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAC7B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACvE,CAAC;QACH,CAAC;IACH,CAAC","sourcesContent":["import { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { AnyType } from '@/common/types';\nimport { LoggerFactory } from '@/modules/logger';\nimport { getError } from '@/modules/error';\nimport { ProjectRootRegistry } from './project-root.utility';\n\nconst logger = LoggerFactory.getLogger(['ModuleUtility']);\n\n/** Loads an optional peer without letting `Bun.build` see it: every specifier stays a parameter, so there is no literal (nor a `minify.syntax`-folded const) for the bundler to resolve. */\nexport class ModuleUtility {\n /** Peers handed over by the application, keyed by specifier. Checked before any filesystem lookup. The map lives in a globalThis slot because a process (or a compiled bundle) can carry two copies of this module, and a peer registered through one copy must be found by the other. */\n private static readonly registered: Map<string, AnyType> = ModuleUtility.sharedRegistry();\n\n private static sharedRegistry(): Map<string, AnyType> {\n const slot = Symbol.for('ignis:module-registry');\n const shared: Map<string, AnyType> | undefined = Reflect.get(globalThis, slot);\n\n if (shared) {\n return shared;\n }\n\n const created = new Map<string, AnyType>();\n Reflect.set(globalThis, slot, created);\n\n return created;\n }\n\n /** Called by the application once it knows its root (`configs.projectRoot` or the cwd); every peer lookup below follows it. Delegates to `ProjectRootRegistry`, which a browser Worker host reaches too through `/core` - the two must share ONE slot. */\n static setProjectRoot(opts: { projectRoot: string }): void {\n ProjectRootRegistry.set(opts);\n }\n\n static getProjectRoot(): string {\n return ProjectRootRegistry.getShared() ?? process.cwd();\n }\n\n /** Resolves peers against the APP's node_modules (under the project root), not this package's own `dist/` location. */\n private static appRequire() {\n return createRequire(path.join(this.getProjectRoot(), 'node_modules'));\n }\n\n private static fail(opts: { method: string; module: string; error: unknown; scope?: string }) {\n const { method, module, error, scope } = opts;\n const reason = error instanceof Error ? error.message : String(error);\n\n logger.for(method).error(\"Failed to load '%s' | Error: %s\", module, reason);\n\n return getError({\n message: `[ModuleUtility.${method}] ${module} is required, resolved from ${this.getProjectRoot()}${\n scope ? ` for ${scope}` : ''\n }. Please install '${module}' | Error: ${reason}`,\n });\n }\n\n /**\n * Hands the framework a peer the application already holds, so no filesystem lookup is needed.\n * A `bun build --compile` binary ships without `node_modules`, which leaves runtime resolution\n * nothing to resolve against: the application imports such a peer statically - that import is\n * what gets it into the binary - and registers it here before the consuming component boots.\n *\n * Deliberately does not log. It runs at the entrypoint of exactly the deployment that has no\n * logger provider yet, where `LoggerFactory` throws - and a throw mid-loop would drop every\n * module after the first.\n */\n static register(opts: { modules: Record<string, AnyType> }): void {\n const modulesEntries = Object.entries(opts.modules);\n\n for (const [module, value] of modulesEntries) {\n this.registered.set(module, value);\n }\n }\n\n /**\n * The file `module` resolves to from the project root under the ES module conditions (`import`), so\n * the peer is the very instance an application's own `import` of it gets. `undefined` when it does not\n * resolve there or the runtime has no resolver: the caller falls back to a plain `import()`.\n */\n private static resolveEsmFile(opts: { module: string }): string | undefined {\n if (typeof Bun === 'undefined') {\n return undefined;\n }\n\n try {\n const file = Bun.resolveSync(opts.module, this.getProjectRoot());\n\n return path.isAbsolute(file) ? file : undefined;\n // eslint-disable-next-line venizia/no-silent-catch -- documented contract: an unresolvable module is `undefined` and the caller falls back to a plain `import()`\n } catch {\n return undefined;\n }\n }\n\n /**\n * Loads the module as an ES module, resolved from the project root: a peer that ships both builds\n * (`bullmq`, `socket.io-client`) is loaded as the copy the application's own `import` gets, not a second\n * one. A module handed over with {@link register} wins; one that does not resolve from the project root is\n * imported by name as before. Use this everywhere except a constructor, which cannot await - see {@link preload}.\n */\n static async load<T = AnyType>(opts: { module: string }): Promise<T> {\n const { module } = opts;\n\n if (this.registered.has(module)) {\n return this.registered.get(module) as T;\n }\n\n try {\n const file = this.resolveEsmFile({ module });\n const result = await import(file === undefined ? module : pathToFileURL(file).href);\n\n return result as T;\n } catch (error) {\n throw this.fail({ method: 'load', module, error });\n }\n }\n\n /**\n * The explicit register path for what a constructor needs: loads each module with {@link load} and\n * registers it, so the synchronous {@link loadSync} returns that ES module copy afterwards. Call it once\n * at the entrypoint, before the helpers are constructed. A module already registered is kept; every module\n * is loaded before any is registered, so one that is missing registers nothing.\n */\n static async preload(opts: { modules: Array<string> }): Promise<void> {\n const loaded: Record<string, AnyType> = {};\n\n for (const module of opts.modules) {\n // `load` answers from the registry first, so a module the application handed over comes back as itself.\n const result = await this.load({ module });\n loaded[module] = result;\n }\n\n this.register({ modules: loaded });\n }\n\n /**\n * Sync twin of {@link load}, for a constructor or any path that cannot await. It resolves with\n * `require`, so a peer that ships both builds comes back as its CommonJS copy - a second instance next to\n * the one an application's `import` holds, and `instanceof` across the two fails. `await preload(...)` at the\n * entrypoint registers the ES module copy first, and this returns that.\n */\n static loadSync<T = AnyType>(opts: { module: string }): T {\n const { module } = opts;\n\n if (this.registered.has(module)) {\n return this.registered.get(module) as T;\n }\n\n try {\n return this.appRequire()(module) as T;\n } catch (error) {\n throw this.fail({ method: 'loadSync', module, error });\n }\n }\n\n /**\n * Presence check only - throws naming what to install, without executing the module.\n *\n * `allowRegistered` must be set only where {@link load} or {@link loadSync} is what finally loads\n * the module. Where the consumer resolves the specifier itself - `pino.transport()` inside a\n * worker thread, or any caller with its own `createRequire` - the registry cannot reach it, and\n * counting a registration as installed would replace this precise error with an opaque one.\n */\n static assertInstalled(opts: {\n modules: Array<string>;\n scope?: string;\n allowRegistered?: boolean;\n }): void {\n const { modules, scope, allowRegistered = false } = opts;\n const appRequire = this.appRequire();\n\n for (const module of modules) {\n if (allowRegistered && this.registered.has(module)) {\n continue;\n }\n\n try {\n appRequire.resolve(module);\n } catch (error) {\n throw this.fail({ method: 'assertInstalled', module, error, scope });\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"module.utility.js","sourceRoot":"","sources":["../../../src/utilities/module.utility.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAE7D,MAAM,MAAM,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC;AAE1D,4LAA4L;AAC5L,MAAM,OAAO,aAAa;IACxB;;;;OAIG;aACqB,eAAU,GAAqB,aAAa,CAAC,cAAc,EAAE,CAAC;IAE9E,MAAM,CAAC,cAAc;QAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;QACjD,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAE7C,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,OAAO,GAAG,IAAI,GAAG,EAAE,C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I,eAAe,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnD,SAAS;YACX,CAAC;YAED,IAAI,CAAC;gBACH,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAC7B,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YACvE,CAAC;QACH,CAAC;IACH,CAAC","sourcesContent":["import { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { LoggerFactory } from '@/modules/logger';\nimport { getError } from '@/modules/error';\nimport { ProjectRootRegistry } from './project-root.utility';\n\nconst logger = LoggerFactory.getLogger(['ModuleUtility']);\n\n/** Loads an optional peer without letting `Bun.build` see it: every specifier stays a parameter, so there is no literal (nor a `minify.syntax`-folded const) for the bundler to resolve. */\nexport class ModuleUtility {\n /**\n * Peers handed over by the application, keyed by specifier. Checked before any filesystem lookup. The map lives in a globalThis slot because a process (or a compiled bundle) can carry two copies of this module, and a peer registered through one copy must be found by the other.\n *\n * The one deliberate `any` of this class: a module's shape is whatever the peer is, and `load<T>`/`loadSync<T>` hand it back as the `T` the caller names, as `import()` and `require()` do (both answer `any`).\n */\n private static readonly registered: Map<string, any> = ModuleUtility.sharedRegistry();\n\n private static sharedRegistry(): Map<string, any> {\n const slot = Symbol.for('ignis:module-registry');\n const shared = Reflect.get(globalThis, slot);\n\n if (shared) {\n return shared;\n }\n\n const created = new Map();\n Reflect.set(globalThis, slot, created);\n\n return created;\n }\n\n /** Called by the application once it knows its root (`configs.projectRoot` or the cwd); every peer lookup below follows it. Delegates to `ProjectRootRegistry`, which a browser Worker host reaches too through `/core` - the two must share ONE slot. */\n static setProjectRoot(opts: { projectRoot: string }): void {\n ProjectRootRegistry.set(opts);\n }\n\n static getProjectRoot(): string {\n return ProjectRootRegistry.getShared() ?? process.cwd();\n }\n\n /** Resolves peers against the APP's node_modules (under the project root), not this package's own `dist/` location. */\n private static appRequire() {\n return createRequire(path.join(this.getProjectRoot(), 'node_modules'));\n }\n\n private static fail(opts: { method: string; module: string; error: unknown; scope?: string }) {\n const { method, module, error, scope } = opts;\n const reason = error instanceof Error ? error.message : String(error);\n\n logger.for(method).error(\"Failed to load '%s' | Error: %s\", module, reason);\n\n return getError({\n message: `[ModuleUtility.${method}] ${module} is required, resolved from ${this.getProjectRoot()}${\n scope ? ` for ${scope}` : ''\n }. Please install '${module}' | Error: ${reason}`,\n });\n }\n\n /**\n * Hands the framework a peer the application already holds, so no filesystem lookup is needed.\n * A `bun build --compile` binary ships without `node_modules`, which leaves runtime resolution\n * nothing to resolve against: the application imports such a peer statically - that import is\n * what gets it into the binary - and registers it here before the consuming component boots.\n *\n * Deliberately does not log. It runs at the entrypoint of exactly the deployment that has no\n * logger provider yet, where `LoggerFactory` throws - and a throw mid-loop would drop every\n * module after the first.\n */\n static register(opts: { modules: Record<string, unknown> }): void {\n const modulesEntries = Object.entries(opts.modules);\n\n for (const [module, value] of modulesEntries) {\n this.registered.set(module, value);\n }\n }\n\n /**\n * The file `module` resolves to from the project root under the ES module conditions (`import`), so\n * the peer is the very instance an application's own `import` of it gets. `undefined` when it does not\n * resolve there or the runtime has no resolver: the caller falls back to a plain `import()`.\n */\n private static resolveEsmFile(opts: { module: string }): string | undefined {\n if (typeof Bun === 'undefined') {\n return undefined;\n }\n\n try {\n const file = Bun.resolveSync(opts.module, this.getProjectRoot());\n\n return path.isAbsolute(file) ? file : undefined;\n // eslint-disable-next-line venizia/no-silent-catch -- documented contract: an unresolvable module is `undefined` and the caller falls back to a plain `import()`\n } catch {\n return undefined;\n }\n }\n\n /**\n * Loads the module as an ES module, resolved from the project root: a peer that ships both builds\n * (`bullmq`, `socket.io-client`) is loaded as the copy the application's own `import` gets, not a second\n * one. A module handed over with {@link register} wins; one that does not resolve from the project root is\n * imported by name as before. Use this everywhere except a constructor, which cannot await - see {@link preload}.\n */\n static async load<T = unknown>(opts: { module: string }): Promise<T> {\n const { module } = opts;\n\n if (this.registered.has(module)) {\n return this.registered.get(module);\n }\n\n try {\n const file = this.resolveEsmFile({ module });\n const result = await import(file === undefined ? module : pathToFileURL(file).href);\n\n return result;\n } catch (error) {\n throw this.fail({ method: 'load', module, error });\n }\n }\n\n /**\n * The explicit register path for what a constructor needs: loads each module with {@link load} and\n * registers it, so the synchronous {@link loadSync} returns that ES module copy afterwards. Call it once\n * at the entrypoint, before the helpers are constructed. A module already registered is kept; every module\n * is loaded before any is registered, so one that is missing registers nothing.\n */\n static async preload(opts: { modules: Array<string> }): Promise<void> {\n const loaded: Record<string, unknown> = {};\n\n for (const module of opts.modules) {\n // `load` answers from the registry first, so a module the application handed over comes back as itself.\n const result = await this.load({ module });\n loaded[module] = result;\n }\n\n this.register({ modules: loaded });\n }\n\n /**\n * Sync twin of {@link load}, for a constructor or any path that cannot await. It resolves with\n * `require`, so a peer that ships both builds comes back as its CommonJS copy - a second instance next to\n * the one an application's `import` holds, and `instanceof` across the two fails. `await preload(...)` at the\n * entrypoint registers the ES module copy first, and this returns that.\n */\n static loadSync<T = unknown>(opts: { module: string }): T {\n const { module } = opts;\n\n if (this.registered.has(module)) {\n return this.registered.get(module);\n }\n\n try {\n return this.appRequire()(module);\n } catch (error) {\n throw this.fail({ method: 'loadSync', module, error });\n }\n }\n\n /**\n * Presence check only - throws naming what to install, without executing the module.\n *\n * `allowRegistered` must be set only where {@link load} or {@link loadSync} is what finally loads\n * the module. Where the consumer resolves the specifier itself - `pino.transport()` inside a\n * worker thread, or any caller with its own `createRequire` - the registry cannot reach it, and\n * counting a registration as installed would replace this precise error with an opaque one.\n */\n static assertInstalled(opts: {\n modules: Array<string>;\n scope?: string;\n allowRegistered?: boolean;\n }): void {\n const { modules, scope, allowRegistered = false } = opts;\n const appRequire = this.appRequire();\n\n for (const module of modules) {\n if (allowRegistered && this.registered.has(module)) {\n continue;\n }\n\n try {\n appRequire.resolve(module);\n } catch (error) {\n throw this.fail({ method: 'assertInstalled', module, error, scope });\n }\n }\n }\n}\n"]}
|