@geekmidas/envkit 1.0.3 → 1.0.5
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/CHANGELOG.md +12 -0
- package/dist/{EnvironmentBuilder-BSuHZm0y.mjs → EnvironmentBuilder-CFen3oIg.mjs} +1 -1
- package/dist/{EnvironmentBuilder-BSuHZm0y.mjs.map → EnvironmentBuilder-CFen3oIg.mjs.map} +1 -1
- package/dist/{EnvironmentBuilder-Xuf2Dd9u.d.cts → EnvironmentBuilder-CNgcdzSR.d.cts} +1 -1
- package/dist/{EnvironmentBuilder-Xuf2Dd9u.d.cts.map → EnvironmentBuilder-CNgcdzSR.d.cts.map} +1 -1
- package/dist/{EnvironmentBuilder-Djr1VsWM.cjs → EnvironmentBuilder-DDgLJAAo.cjs} +1 -1
- package/dist/{EnvironmentBuilder-Djr1VsWM.cjs.map → EnvironmentBuilder-DDgLJAAo.cjs.map} +1 -1
- package/dist/{EnvironmentBuilder-jF-b7WQg.d.mts → EnvironmentBuilder-DHfDXJUm.d.mts} +1 -1
- package/dist/{EnvironmentBuilder-jF-b7WQg.d.mts.map → EnvironmentBuilder-DHfDXJUm.d.mts.map} +1 -1
- package/dist/{EnvironmentParser-DtOL86NU.d.cts → EnvironmentParser-BY1oCUsc.d.mts} +3 -3
- package/dist/EnvironmentParser-BY1oCUsc.d.mts.map +1 -0
- package/dist/{EnvironmentParser-DJdW7vOL.cjs → EnvironmentParser-Bzg5yXG2.cjs} +124 -4
- package/dist/EnvironmentParser-Bzg5yXG2.cjs.map +1 -0
- package/dist/{EnvironmentParser-CkLfmn4Y.d.mts → EnvironmentParser-DoooZm8n.d.cts} +3 -3
- package/dist/EnvironmentParser-DoooZm8n.d.cts.map +1 -0
- package/dist/{EnvironmentParser-zMblItla.mjs → EnvironmentParser-taAKfzT7.mjs} +112 -4
- package/dist/EnvironmentParser-taAKfzT7.mjs.map +1 -0
- package/dist/SnifferEnvironmentParser.cjs +19 -4
- package/dist/SnifferEnvironmentParser.cjs.map +1 -1
- package/dist/SnifferEnvironmentParser.d.cts +20 -3
- package/dist/SnifferEnvironmentParser.d.cts.map +1 -1
- package/dist/SnifferEnvironmentParser.d.mts +20 -3
- package/dist/SnifferEnvironmentParser.d.mts.map +1 -1
- package/dist/SnifferEnvironmentParser.mjs +19 -4
- package/dist/SnifferEnvironmentParser.mjs.map +1 -1
- package/dist/credentials.cjs +9 -3
- package/dist/credentials.cjs.map +1 -1
- package/dist/credentials.d.cts +7 -3
- package/dist/credentials.d.cts.map +1 -1
- package/dist/credentials.d.mts +7 -3
- package/dist/credentials.d.mts.map +1 -1
- package/dist/credentials.mjs +9 -3
- package/dist/credentials.mjs.map +1 -1
- package/dist/index.cjs +4 -5
- package/dist/index.d.cts +52 -4
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.mts +52 -4
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -3
- package/dist/sst.cjs +114 -6
- package/dist/sst.cjs.map +1 -1
- package/dist/sst.d.cts +184 -3
- package/dist/sst.d.cts.map +1 -1
- package/dist/sst.d.mts +184 -3
- package/dist/sst.d.mts.map +1 -1
- package/dist/sst.mjs +110 -2
- package/dist/sst.mjs.map +1 -1
- package/package.json +4 -3
- package/src/SnifferEnvironmentParser.ts +31 -3
- package/src/__tests__/SnifferEnvironmentParser.spec.ts +158 -0
- package/src/credentials.ts +16 -3
- package/tsdown.config.ts +16 -1
- package/dist/EnvironmentBuilder.cjs +0 -4
- package/dist/EnvironmentBuilder.d.cts +0 -2
- package/dist/EnvironmentBuilder.d.mts +0 -2
- package/dist/EnvironmentBuilder.mjs +0 -3
- package/dist/EnvironmentParser-CkLfmn4Y.d.mts.map +0 -1
- package/dist/EnvironmentParser-DJdW7vOL.cjs.map +0 -1
- package/dist/EnvironmentParser-DtOL86NU.d.cts.map +0 -1
- package/dist/EnvironmentParser-zMblItla.mjs.map +0 -1
- package/dist/EnvironmentParser.cjs +0 -5
- package/dist/EnvironmentParser.d.cts +0 -2
- package/dist/EnvironmentParser.d.mts +0 -2
- package/dist/EnvironmentParser.mjs +0 -4
- package/dist/SstEnvironmentBuilder-BRAcRQp2.d.mts +0 -186
- package/dist/SstEnvironmentBuilder-BRAcRQp2.d.mts.map +0 -1
- package/dist/SstEnvironmentBuilder-D-NGrp7U.cjs +0 -130
- package/dist/SstEnvironmentBuilder-D-NGrp7U.cjs.map +0 -1
- package/dist/SstEnvironmentBuilder-DOu4dVPL.mjs +0 -113
- package/dist/SstEnvironmentBuilder-DOu4dVPL.mjs.map +0 -1
- package/dist/SstEnvironmentBuilder-Dc9nOuuK.d.cts +0 -186
- package/dist/SstEnvironmentBuilder-Dc9nOuuK.d.cts.map +0 -1
- package/dist/SstEnvironmentBuilder.cjs +0 -7
- package/dist/SstEnvironmentBuilder.d.cts +0 -3
- package/dist/SstEnvironmentBuilder.d.mts +0 -3
- package/dist/SstEnvironmentBuilder.mjs +0 -4
- package/dist/formatter-BRRrxQi3.mjs +0 -111
- package/dist/formatter-BRRrxQi3.mjs.map +0 -1
- package/dist/formatter-Cox0NGxT.d.mts +0 -51
- package/dist/formatter-Cox0NGxT.d.mts.map +0 -1
- package/dist/formatter-D85aIkpd.d.cts +0 -51
- package/dist/formatter-D85aIkpd.d.cts.map +0 -1
- package/dist/formatter-HxePpSy2.cjs +0 -123
- package/dist/formatter-HxePpSy2.cjs.map +0 -1
- package/dist/formatter.cjs +0 -4
- package/dist/formatter.d.cts +0 -2
- package/dist/formatter.d.mts +0 -2
- package/dist/formatter.mjs +0 -3
package/dist/sst.mjs
CHANGED
|
@@ -1,6 +1,114 @@
|
|
|
1
|
-
import { environmentCase } from "./EnvironmentBuilder-
|
|
2
|
-
import { ResourceType, SstEnvironmentBuilder, sstResolvers } from "./SstEnvironmentBuilder-DOu4dVPL.mjs";
|
|
1
|
+
import { EnvironmentBuilder, environmentCase } from "./EnvironmentBuilder-CFen3oIg.mjs";
|
|
3
2
|
|
|
3
|
+
//#region src/SstEnvironmentBuilder.ts
|
|
4
|
+
/**
|
|
5
|
+
* Enumeration of supported SST (Serverless Stack Toolkit) resource types.
|
|
6
|
+
* Used to identify and process different AWS and SST resources.
|
|
7
|
+
*/
|
|
8
|
+
let ResourceType = /* @__PURE__ */ function(ResourceType$1) {
|
|
9
|
+
ResourceType$1["ApiGatewayV2"] = "sst.aws.ApiGatewayV2";
|
|
10
|
+
ResourceType$1["Postgres"] = "sst.aws.Postgres";
|
|
11
|
+
ResourceType$1["Function"] = "sst.aws.Function";
|
|
12
|
+
ResourceType$1["Bucket"] = "sst.aws.Bucket";
|
|
13
|
+
ResourceType$1["Vpc"] = "sst.aws.Vpc";
|
|
14
|
+
ResourceType$1["Secret"] = "sst.sst.Secret";
|
|
15
|
+
ResourceType$1["Dynamo"] = "sst.aws.Dynamo";
|
|
16
|
+
ResourceType$1["SSTSecret"] = "sst:sst:Secret";
|
|
17
|
+
ResourceType$1["SSTFunction"] = "sst:sst:Function";
|
|
18
|
+
ResourceType$1["SSTApiGatewayV2"] = "sst:aws:ApiGatewayV2";
|
|
19
|
+
ResourceType$1["SSTPostgres"] = "sst:aws:Postgres";
|
|
20
|
+
ResourceType$1["SSTBucket"] = "sst:aws:Bucket";
|
|
21
|
+
ResourceType$1["SnsTopic"] = "sst:aws:SnsTopic";
|
|
22
|
+
ResourceType$1["SSTDynamo"] = "sst:aws:Dynamo";
|
|
23
|
+
return ResourceType$1;
|
|
24
|
+
}({});
|
|
25
|
+
const secretResolver = (name, value) => ({ [name]: value.value });
|
|
26
|
+
const postgresResolver = (key, value) => ({
|
|
27
|
+
[`${key}Name`]: value.database,
|
|
28
|
+
[`${key}Host`]: value.host,
|
|
29
|
+
[`${key}Password`]: value.password,
|
|
30
|
+
[`${key}Port`]: value.port,
|
|
31
|
+
[`${key}Username`]: value.username
|
|
32
|
+
});
|
|
33
|
+
const bucketResolver = (name, value) => ({ [`${name}Name`]: value.name });
|
|
34
|
+
const topicResolver = (name, value) => ({ [`${name}Arn`]: value.arn });
|
|
35
|
+
const dynamoResolver = (name, value) => ({ [`${name}Name`]: value.name });
|
|
36
|
+
const noopResolver = () => ({});
|
|
37
|
+
/**
|
|
38
|
+
* Pre-configured resolvers for all SST resource types.
|
|
39
|
+
*/
|
|
40
|
+
const sstResolvers = {
|
|
41
|
+
[ResourceType.ApiGatewayV2]: noopResolver,
|
|
42
|
+
[ResourceType.Function]: noopResolver,
|
|
43
|
+
[ResourceType.Vpc]: noopResolver,
|
|
44
|
+
[ResourceType.Secret]: secretResolver,
|
|
45
|
+
[ResourceType.Postgres]: postgresResolver,
|
|
46
|
+
[ResourceType.Bucket]: bucketResolver,
|
|
47
|
+
[ResourceType.Dynamo]: dynamoResolver,
|
|
48
|
+
[ResourceType.SSTSecret]: secretResolver,
|
|
49
|
+
[ResourceType.SSTBucket]: bucketResolver,
|
|
50
|
+
[ResourceType.SSTFunction]: noopResolver,
|
|
51
|
+
[ResourceType.SSTPostgres]: postgresResolver,
|
|
52
|
+
[ResourceType.SSTApiGatewayV2]: noopResolver,
|
|
53
|
+
[ResourceType.SnsTopic]: topicResolver,
|
|
54
|
+
[ResourceType.SSTDynamo]: dynamoResolver
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* SST-specific environment builder with built-in resolvers for all known
|
|
58
|
+
* SST resource types.
|
|
59
|
+
*
|
|
60
|
+
* Wraps the generic EnvironmentBuilder with pre-configured SST resolvers.
|
|
61
|
+
*
|
|
62
|
+
* @template TRecord - The input record type for type inference
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* const env = new SstEnvironmentBuilder({
|
|
67
|
+
* database: { type: 'sst:aws:Postgres', host: '...', ... },
|
|
68
|
+
* apiKey: { type: 'sst:sst:Secret', value: 'secret' },
|
|
69
|
+
* appName: 'my-app',
|
|
70
|
+
* }).build();
|
|
71
|
+
*
|
|
72
|
+
* // With custom resolvers (typed based on input)
|
|
73
|
+
* const env = new SstEnvironmentBuilder(
|
|
74
|
+
* {
|
|
75
|
+
* database: postgresResource,
|
|
76
|
+
* custom: { type: 'my-custom' as const, data: 'foo' },
|
|
77
|
+
* },
|
|
78
|
+
* {
|
|
79
|
+
* // TypeScript requires 'my-custom' resolver with typed value
|
|
80
|
+
* 'my-custom': (key, value) => ({ [`${key}Data`]: value.data }),
|
|
81
|
+
* }
|
|
82
|
+
* ).build();
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
var SstEnvironmentBuilder = class {
|
|
86
|
+
builder;
|
|
87
|
+
/**
|
|
88
|
+
* Create a new SST environment builder.
|
|
89
|
+
*
|
|
90
|
+
* @param record - Object containing SST resources, custom resources, and/or string values
|
|
91
|
+
* @param additionalResolvers - Optional custom resolvers (typed based on custom types in record)
|
|
92
|
+
* @param options - Optional configuration options
|
|
93
|
+
*/
|
|
94
|
+
constructor(record, additionalResolvers, options) {
|
|
95
|
+
const mergedResolvers = additionalResolvers ? {
|
|
96
|
+
...sstResolvers,
|
|
97
|
+
...additionalResolvers
|
|
98
|
+
} : sstResolvers;
|
|
99
|
+
this.builder = new EnvironmentBuilder(record, mergedResolvers, options);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Build environment variables from the input record.
|
|
103
|
+
*
|
|
104
|
+
* @returns A record of environment variables
|
|
105
|
+
*/
|
|
106
|
+
build() {
|
|
107
|
+
return this.builder.build();
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
//#endregion
|
|
4
112
|
//#region src/sst.ts
|
|
5
113
|
/**
|
|
6
114
|
* @deprecated Use `new SstEnvironmentBuilder(record).build()` instead.
|
package/dist/sst.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sst.mjs","names":["record: Record<string, SstResource | string>"],"sources":["../src/sst.ts"],"sourcesContent":["// Re-export everything from SstEnvironmentBuilder\n\n// Re-export types from EnvironmentBuilder\nexport type {\n\tEnvironmentBuilderOptions,\n\tEnvRecord,\n\tEnvValue,\n} from './EnvironmentBuilder';\n\n// Re-export environmentCase from EnvironmentBuilder\nexport { environmentCase } from './EnvironmentBuilder';\nexport {\n\ttype ApiGatewayV2,\n\ttype Bucket,\n\ttype Dynamo,\n\ttype Function,\n\ttype Postgres,\n\ttype ResourceProcessor,\n\tResourceType,\n\ttype Secret,\n\ttype SnsTopic,\n\tSstEnvironmentBuilder,\n\ttype SstResource,\n\tsstResolvers,\n\ttype Vpc,\n} from './SstEnvironmentBuilder';\n\n// Import for deprecated function\nimport {\n\tSstEnvironmentBuilder,\n\ttype SstResource,\n} from './SstEnvironmentBuilder';\n\n/**\n * @deprecated Use `new SstEnvironmentBuilder(record).build()` instead.\n *\n * Normalizes SST resources and plain strings into environment variables.\n * Processes resources based on their type and converts names to environment case.\n *\n * @param record - Object containing resources and/or string values\n * @returns Normalized environment variables object\n *\n * @example\n * // Old usage (deprecated):\n * normalizeResourceEnv({ database: postgresResource })\n *\n * // New usage:\n * new SstEnvironmentBuilder({ database: postgresResource }).build()\n */\nexport function normalizeResourceEnv(\n\trecord: Record<string, SstResource | string>,\n): Record<string, string | number | boolean | Record<string, unknown>> {\n\treturn new SstEnvironmentBuilder(record).build();\n}\n\n// Keep Resource type as deprecated alias for backwards compatibility\n/**\n * @deprecated Use `SstResource` instead.\n */\nexport type Resource = SstResource;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,qBACfA,QACsE;AACtE,QAAO,IAAI,sBAAsB,QAAQ,OAAO;AAChD"}
|
|
1
|
+
{"version":3,"file":"sst.mjs","names":["name: string","value: SecretValue","key: string","value: PostgresValue","value: BucketValue","value: SnsTopicValue","value: DynamoValue","sstResolvers: Resolvers","record: TRecord","additionalResolvers?: CustomResolvers<TRecord>","options?: EnvironmentBuilderOptions","mergedResolvers: Resolvers","record: Record<string, SstResource | string>"],"sources":["../src/SstEnvironmentBuilder.ts","../src/sst.ts"],"sourcesContent":["import {\n\tEnvironmentBuilder,\n\ttype EnvironmentBuilderOptions,\n\ttype EnvironmentResolver,\n\ttype EnvRecord,\n\ttype InputValue,\n\ttype Resolvers,\n} from './EnvironmentBuilder';\n\n/**\n * Enumeration of supported SST (Serverless Stack Toolkit) resource types.\n * Used to identify and process different AWS and SST resources.\n */\nexport enum ResourceType {\n\t// Legacy format (dot notation)\n\tApiGatewayV2 = 'sst.aws.ApiGatewayV2',\n\tPostgres = 'sst.aws.Postgres',\n\tFunction = 'sst.aws.Function',\n\tBucket = 'sst.aws.Bucket',\n\tVpc = 'sst.aws.Vpc',\n\tSecret = 'sst.sst.Secret',\n\tDynamo = 'sst.aws.Dynamo',\n\n\t// Modern format (colon notation)\n\tSSTSecret = 'sst:sst:Secret',\n\tSSTFunction = 'sst:sst:Function',\n\tSSTApiGatewayV2 = 'sst:aws:ApiGatewayV2',\n\tSSTPostgres = 'sst:aws:Postgres',\n\tSSTBucket = 'sst:aws:Bucket',\n\tSnsTopic = 'sst:aws:SnsTopic',\n\tSSTDynamo = 'sst:aws:Dynamo',\n}\n\n/**\n * AWS API Gateway V2 resource type.\n * Represents an HTTP/WebSocket API.\n */\nexport type ApiGatewayV2 = {\n\ttype: ResourceType.ApiGatewayV2 | ResourceType.SSTApiGatewayV2;\n\turl: string;\n};\n\n/**\n * PostgreSQL database resource type.\n * Contains all connection details needed to connect to the database.\n */\nexport type Postgres = {\n\ttype: ResourceType.Postgres | ResourceType.SSTPostgres;\n\tdatabase: string;\n\thost: string;\n\tpassword: string;\n\tport: number;\n\tusername: string;\n};\n\n/**\n * AWS Lambda Function resource type.\n */\nexport type Function = {\n\ttype: ResourceType.Function | ResourceType.SSTFunction;\n\tname: string;\n};\n\n/**\n * AWS S3 Bucket resource type.\n */\nexport type Bucket = {\n\ttype: ResourceType.Bucket | ResourceType.SSTBucket;\n\tname: string;\n};\n\n/**\n * AWS VPC (Virtual Private Cloud) resource type.\n */\nexport type Vpc = {\n\ttype: ResourceType.Vpc;\n\tbastion: string;\n};\n\n/**\n * Secret resource type for storing sensitive values.\n */\nexport type Secret = {\n\ttype: ResourceType.Secret | ResourceType.SSTSecret;\n\tvalue: string;\n};\n\n/**\n * AWS SNS Topic resource type.\n */\nexport type SnsTopic = {\n\ttype: ResourceType.SnsTopic;\n\tarn: string;\n};\n\n/**\n * AWS DynamoDB Table resource type.\n */\nexport type Dynamo = {\n\ttype: ResourceType.Dynamo | ResourceType.SSTDynamo;\n\tname: string;\n};\n\n/**\n * Union type of all supported SST resource types.\n */\nexport type SstResource =\n\t| ApiGatewayV2\n\t| Postgres\n\t| Function\n\t| Bucket\n\t| Vpc\n\t| Secret\n\t| SnsTopic\n\t| Dynamo;\n\n// Value types without the `type` key (for resolver parameters)\ntype SecretValue = Omit<Secret, 'type'>;\ntype PostgresValue = Omit<Postgres, 'type'>;\ntype BucketValue = Omit<Bucket, 'type'>;\ntype SnsTopicValue = Omit<SnsTopic, 'type'>;\ntype DynamoValue = Omit<Dynamo, 'type'>;\n\n/**\n * Function type for processing a specific resource type into environment variables.\n *\n * @template K - The specific resource type (without `type` key)\n * @param name - The resource name\n * @param value - The resource value (without `type` key)\n * @returns Object mapping environment variable names to values\n */\nexport type ResourceProcessor<K> = (name: string, value: K) => EnvRecord;\n\n// SST Resource Resolvers (receive values without `type` key)\n\nconst secretResolver = (name: string, value: SecretValue) => ({\n\t[name]: value.value,\n});\n\nconst postgresResolver = (key: string, value: PostgresValue) => ({\n\t[`${key}Name`]: value.database,\n\t[`${key}Host`]: value.host,\n\t[`${key}Password`]: value.password,\n\t[`${key}Port`]: value.port,\n\t[`${key}Username`]: value.username,\n});\n\nconst bucketResolver = (name: string, value: BucketValue) => ({\n\t[`${name}Name`]: value.name,\n});\n\nconst topicResolver = (name: string, value: SnsTopicValue) => ({\n\t[`${name}Arn`]: value.arn,\n});\n\nconst dynamoResolver = (name: string, value: DynamoValue) => ({\n\t[`${name}Name`]: value.name,\n});\n\nconst noopResolver = () => ({});\n\n/**\n * Pre-configured resolvers for all SST resource types.\n */\nexport const sstResolvers: Resolvers = {\n\t// Legacy format\n\t[ResourceType.ApiGatewayV2]: noopResolver,\n\t[ResourceType.Function]: noopResolver,\n\t[ResourceType.Vpc]: noopResolver,\n\t[ResourceType.Secret]: secretResolver,\n\t[ResourceType.Postgres]: postgresResolver,\n\t[ResourceType.Bucket]: bucketResolver,\n\t[ResourceType.Dynamo]: dynamoResolver,\n\n\t// Modern format\n\t[ResourceType.SSTSecret]: secretResolver,\n\t[ResourceType.SSTBucket]: bucketResolver,\n\t[ResourceType.SSTFunction]: noopResolver,\n\t[ResourceType.SSTPostgres]: postgresResolver,\n\t[ResourceType.SSTApiGatewayV2]: noopResolver,\n\t[ResourceType.SnsTopic]: topicResolver,\n\t[ResourceType.SSTDynamo]: dynamoResolver,\n};\n\n/**\n * All known SST resource type strings.\n */\ntype SstResourceTypeString = `${ResourceType}`;\n\n/**\n * Extracts the `type` string value from an input value.\n */\ntype ExtractType<T> = T extends { type: infer U extends string } ? U : never;\n\n/**\n * Removes the `type` key from an object type.\n */\ntype OmitType<T> = T extends { type: string } ? Omit<T, 'type'> : never;\n\n/**\n * Extracts all unique `type` values from a record (excluding plain strings).\n */\ntype AllTypeValues<TRecord extends Record<string, InputValue>> = {\n\t[K in keyof TRecord]: ExtractType<TRecord[K]>;\n}[keyof TRecord];\n\n/**\n * Extracts only the custom (non-SST) type values from a record.\n */\ntype CustomTypeValues<TRecord extends Record<string, InputValue>> = Exclude<\n\tAllTypeValues<TRecord>,\n\tSstResourceTypeString\n>;\n\n/**\n * For a given type value, finds the corresponding value type (without `type` key).\n */\ntype ValueForType<\n\tTRecord extends Record<string, InputValue>,\n\tTType extends string,\n> = {\n\t[K in keyof TRecord]: TRecord[K] extends { type: TType }\n\t\t? OmitType<TRecord[K]>\n\t\t: never;\n}[keyof TRecord];\n\n/**\n * Generates typed resolvers for custom (non-SST) types in the input record.\n */\ntype CustomResolvers<TRecord extends Record<string, InputValue>> =\n\tCustomTypeValues<TRecord> extends never\n\t\t? Resolvers | undefined\n\t\t: {\n\t\t\t\t[TType in CustomTypeValues<TRecord>]: EnvironmentResolver<\n\t\t\t\t\tValueForType<TRecord, TType>\n\t\t\t\t>;\n\t\t\t};\n\n/**\n * SST-specific environment builder with built-in resolvers for all known\n * SST resource types.\n *\n * Wraps the generic EnvironmentBuilder with pre-configured SST resolvers.\n *\n * @template TRecord - The input record type for type inference\n *\n * @example\n * ```typescript\n * const env = new SstEnvironmentBuilder({\n * database: { type: 'sst:aws:Postgres', host: '...', ... },\n * apiKey: { type: 'sst:sst:Secret', value: 'secret' },\n * appName: 'my-app',\n * }).build();\n *\n * // With custom resolvers (typed based on input)\n * const env = new SstEnvironmentBuilder(\n * {\n * database: postgresResource,\n * custom: { type: 'my-custom' as const, data: 'foo' },\n * },\n * {\n * // TypeScript requires 'my-custom' resolver with typed value\n * 'my-custom': (key, value) => ({ [`${key}Data`]: value.data }),\n * }\n * ).build();\n * ```\n */\nexport class SstEnvironmentBuilder<\n\tTRecord extends Record<string, SstResource | InputValue | string>,\n> {\n\tprivate readonly builder: EnvironmentBuilder<\n\t\tRecord<string, InputValue>,\n\t\tResolvers\n\t>;\n\n\t/**\n\t * Create a new SST environment builder.\n\t *\n\t * @param record - Object containing SST resources, custom resources, and/or string values\n\t * @param additionalResolvers - Optional custom resolvers (typed based on custom types in record)\n\t * @param options - Optional configuration options\n\t */\n\tconstructor(\n\t\trecord: TRecord,\n\t\tadditionalResolvers?: CustomResolvers<TRecord>,\n\t\toptions?: EnvironmentBuilderOptions,\n\t) {\n\t\t// Merge resolvers with custom ones taking precedence\n\t\tconst mergedResolvers: Resolvers = additionalResolvers\n\t\t\t? { ...sstResolvers, ...additionalResolvers }\n\t\t\t: sstResolvers;\n\n\t\tthis.builder = new EnvironmentBuilder(\n\t\t\trecord as Record<string, InputValue>,\n\t\t\tmergedResolvers,\n\t\t\toptions,\n\t\t);\n\t}\n\n\t/**\n\t * Build environment variables from the input record.\n\t *\n\t * @returns A record of environment variables\n\t */\n\tbuild(): EnvRecord {\n\t\treturn this.builder.build();\n\t}\n}\n\nexport type {\n\tEnvironmentBuilderOptions,\n\tEnvRecord,\n\tEnvValue,\n} from './EnvironmentBuilder';\n// Re-export useful types\nexport { environmentCase } from './EnvironmentBuilder';\n","// Re-export everything from SstEnvironmentBuilder\n\n// Re-export types from EnvironmentBuilder\nexport type {\n\tEnvironmentBuilderOptions,\n\tEnvRecord,\n\tEnvValue,\n} from './EnvironmentBuilder';\n\n// Re-export environmentCase from EnvironmentBuilder\nexport { environmentCase } from './EnvironmentBuilder';\nexport {\n\ttype ApiGatewayV2,\n\ttype Bucket,\n\ttype Dynamo,\n\ttype Function,\n\ttype Postgres,\n\ttype ResourceProcessor,\n\tResourceType,\n\ttype Secret,\n\ttype SnsTopic,\n\tSstEnvironmentBuilder,\n\ttype SstResource,\n\tsstResolvers,\n\ttype Vpc,\n} from './SstEnvironmentBuilder';\n\n// Import for deprecated function\nimport {\n\tSstEnvironmentBuilder,\n\ttype SstResource,\n} from './SstEnvironmentBuilder';\n\n/**\n * @deprecated Use `new SstEnvironmentBuilder(record).build()` instead.\n *\n * Normalizes SST resources and plain strings into environment variables.\n * Processes resources based on their type and converts names to environment case.\n *\n * @param record - Object containing resources and/or string values\n * @returns Normalized environment variables object\n *\n * @example\n * // Old usage (deprecated):\n * normalizeResourceEnv({ database: postgresResource })\n *\n * // New usage:\n * new SstEnvironmentBuilder({ database: postgresResource }).build()\n */\nexport function normalizeResourceEnv(\n\trecord: Record<string, SstResource | string>,\n): Record<string, string | number | boolean | Record<string, unknown>> {\n\treturn new SstEnvironmentBuilder(record).build();\n}\n\n// Keep Resource type as deprecated alias for backwards compatibility\n/**\n * @deprecated Use `SstResource` instead.\n */\nexport type Resource = SstResource;\n"],"mappings":";;;;;;;AAaA,IAAY,wDAAL;AAEN;AACA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;;AACA;AAwGD,MAAM,iBAAiB,CAACA,MAAcC,WAAwB,GAC5D,OAAO,MAAM,MACd;AAED,MA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|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -42,8 +42,9 @@
|
|
|
42
42
|
"zod": "~4.1.13"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@types/lodash.set": "~4.3.9",
|
|
46
45
|
"@types/lodash.get": "~4.4.9",
|
|
47
|
-
"@types/lodash.
|
|
46
|
+
"@types/lodash.set": "~4.3.9",
|
|
47
|
+
"@types/lodash.snakecase": "~4.1.9",
|
|
48
|
+
"@types/node": "~22.0.0"
|
|
48
49
|
}
|
|
49
50
|
}
|
|
@@ -26,10 +26,12 @@ import {
|
|
|
26
26
|
*/
|
|
27
27
|
export class SnifferEnvironmentParser<_T extends EmptyObject = EmptyObject> {
|
|
28
28
|
private readonly accessedVars: Set<string> = new Set();
|
|
29
|
+
private readonly optionalVars: Set<string> = new Set();
|
|
29
30
|
|
|
30
31
|
/**
|
|
31
32
|
* Wraps a Zod schema to always return mock values.
|
|
32
33
|
* This ensures .parse() and .safeParse() never fail.
|
|
34
|
+
* Also detects when .optional() or .default() is called to track optional vars.
|
|
33
35
|
*/
|
|
34
36
|
private wrapSchema = (schema: z.ZodType, name: string): z.ZodType => {
|
|
35
37
|
return new Proxy(schema, {
|
|
@@ -45,6 +47,11 @@ export class SnifferEnvironmentParser<_T extends EmptyObject = EmptyObject> {
|
|
|
45
47
|
});
|
|
46
48
|
}
|
|
47
49
|
|
|
50
|
+
// Detect .optional() or .default() — mark the variable as optional
|
|
51
|
+
if (prop === 'optional' || prop === 'default') {
|
|
52
|
+
this.optionalVars.add(name);
|
|
53
|
+
}
|
|
54
|
+
|
|
48
55
|
const originalProp = target[prop as keyof typeof target];
|
|
49
56
|
if (typeof originalProp === 'function') {
|
|
50
57
|
return (...args: any[]) => {
|
|
@@ -141,9 +148,24 @@ export class SnifferEnvironmentParser<_T extends EmptyObject = EmptyObject> {
|
|
|
141
148
|
|
|
142
149
|
/**
|
|
143
150
|
* Returns all environment variable names that were accessed.
|
|
151
|
+
*
|
|
152
|
+
* @param opts.markOptional - When true, optional variables (those accessed
|
|
153
|
+
* via `.optional()` or `.default()`) are suffixed with `?` (e.g. `PORT?`).
|
|
144
154
|
*/
|
|
145
|
-
getEnvironmentVariables(): string[] {
|
|
146
|
-
|
|
155
|
+
getEnvironmentVariables(opts?: { markOptional?: boolean }): string[] {
|
|
156
|
+
const vars = Array.from(this.accessedVars).sort();
|
|
157
|
+
if (!opts?.markOptional) return vars;
|
|
158
|
+
return vars.map((name) =>
|
|
159
|
+
this.optionalVars.has(name) ? `${name}?` : name,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Returns all environment variable names that were accessed via
|
|
165
|
+
* `.optional()` or `.default()` — i.e. variables that are not required.
|
|
166
|
+
*/
|
|
167
|
+
getOptionalVariables(): string[] {
|
|
168
|
+
return Array.from(this.optionalVars).sort();
|
|
147
169
|
}
|
|
148
170
|
}
|
|
149
171
|
|
|
@@ -212,8 +234,13 @@ class SnifferConfigParser<
|
|
|
212
234
|
* Result of sniffing with fire-and-forget handling.
|
|
213
235
|
*/
|
|
214
236
|
export interface SniffResult {
|
|
215
|
-
/**
|
|
237
|
+
/** All environment variable names that were accessed during sniffing */
|
|
216
238
|
envVars: string[];
|
|
239
|
+
/**
|
|
240
|
+
* Subset of envVars that are optional (accessed via `.optional()` or
|
|
241
|
+
* `.default()`). These do not need to be present for the app to start.
|
|
242
|
+
*/
|
|
243
|
+
optionalEnvVars: string[];
|
|
217
244
|
/** Error thrown during sniffing (env vars may still be captured) */
|
|
218
245
|
error?: Error;
|
|
219
246
|
/** Unhandled promise rejections captured during sniffing */
|
|
@@ -300,6 +327,7 @@ export async function sniffWithFireAndForget(
|
|
|
300
327
|
|
|
301
328
|
return {
|
|
302
329
|
envVars: sniffer.getEnvironmentVariables(),
|
|
330
|
+
optionalEnvVars: sniffer.getOptionalVariables(),
|
|
303
331
|
error,
|
|
304
332
|
unhandledRejections,
|
|
305
333
|
};
|
|
@@ -343,6 +343,135 @@ describe('SnifferEnvironmentParser', () => {
|
|
|
343
343
|
});
|
|
344
344
|
});
|
|
345
345
|
|
|
346
|
+
describe('Optional variable tracking', () => {
|
|
347
|
+
it('should track variables accessed with .optional() as optional', () => {
|
|
348
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
349
|
+
|
|
350
|
+
sniffer.create((get) => ({
|
|
351
|
+
required: get('REQUIRED_VAR').string(),
|
|
352
|
+
optional: get('OPTIONAL_VAR').string().optional(),
|
|
353
|
+
}));
|
|
354
|
+
|
|
355
|
+
expect(sniffer.getOptionalVariables()).toEqual(['OPTIONAL_VAR']);
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
it('should track variables accessed with .default() as optional', () => {
|
|
359
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
360
|
+
|
|
361
|
+
sniffer.create((get) => ({
|
|
362
|
+
required: get('REQUIRED_VAR').string(),
|
|
363
|
+
withDefault: get('DEFAULT_VAR').string().default('fallback'),
|
|
364
|
+
}));
|
|
365
|
+
|
|
366
|
+
expect(sniffer.getOptionalVariables()).toEqual(['DEFAULT_VAR']);
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
it('should track variables with .default() after .transform() as optional', () => {
|
|
370
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
371
|
+
|
|
372
|
+
sniffer.create((get) => ({
|
|
373
|
+
port: get('PORT').string().transform(Number).default(3000),
|
|
374
|
+
}));
|
|
375
|
+
|
|
376
|
+
expect(sniffer.getOptionalVariables()).toEqual(['PORT']);
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it('should not include required variables in getOptionalVariables()', () => {
|
|
380
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
381
|
+
|
|
382
|
+
sniffer.create((get) => ({
|
|
383
|
+
required: get('DATABASE_URL').string(),
|
|
384
|
+
optional: get('LOG_LEVEL').string().optional(),
|
|
385
|
+
}));
|
|
386
|
+
|
|
387
|
+
expect(sniffer.getOptionalVariables()).toEqual(['LOG_LEVEL']);
|
|
388
|
+
expect(sniffer.getOptionalVariables()).not.toContain('DATABASE_URL');
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it('getEnvironmentVariables({ markOptional: true }) suffixes optional vars with ?', () => {
|
|
392
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
393
|
+
|
|
394
|
+
sniffer.create((get) => ({
|
|
395
|
+
required: get('DATABASE_URL').string(),
|
|
396
|
+
apiKey: get('API_KEY').string(),
|
|
397
|
+
logLevel: get('LOG_LEVEL').string().optional(),
|
|
398
|
+
port: get('PORT').string().default('3000'),
|
|
399
|
+
}));
|
|
400
|
+
|
|
401
|
+
expect(sniffer.getEnvironmentVariables({ markOptional: true })).toEqual([
|
|
402
|
+
'API_KEY',
|
|
403
|
+
'DATABASE_URL',
|
|
404
|
+
'LOG_LEVEL?',
|
|
405
|
+
'PORT?',
|
|
406
|
+
]);
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
it('getEnvironmentVariables() without option returns plain names', () => {
|
|
410
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
411
|
+
|
|
412
|
+
sniffer.create((get) => ({
|
|
413
|
+
required: get('DATABASE_URL').string(),
|
|
414
|
+
optional: get('PORT').string().default('3000'),
|
|
415
|
+
}));
|
|
416
|
+
|
|
417
|
+
expect(sniffer.getEnvironmentVariables()).toEqual([
|
|
418
|
+
'DATABASE_URL',
|
|
419
|
+
'PORT',
|
|
420
|
+
]);
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
it('getEnvironmentVariables({ markOptional: false }) returns plain names', () => {
|
|
424
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
425
|
+
|
|
426
|
+
sniffer.create((get) => ({
|
|
427
|
+
required: get('DATABASE_URL').string(),
|
|
428
|
+
optional: get('PORT').string().default('3000'),
|
|
429
|
+
}));
|
|
430
|
+
|
|
431
|
+
expect(sniffer.getEnvironmentVariables({ markOptional: false })).toEqual([
|
|
432
|
+
'DATABASE_URL',
|
|
433
|
+
'PORT',
|
|
434
|
+
]);
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
it('should return empty getOptionalVariables() when all vars are required', () => {
|
|
438
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
439
|
+
|
|
440
|
+
sniffer.create((get) => ({
|
|
441
|
+
url: get('DATABASE_URL').string(),
|
|
442
|
+
key: get('API_KEY').string(),
|
|
443
|
+
}));
|
|
444
|
+
|
|
445
|
+
expect(sniffer.getOptionalVariables()).toEqual([]);
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
it('should handle mix of optional and default across nested config', () => {
|
|
449
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
450
|
+
|
|
451
|
+
sniffer.create((get) => ({
|
|
452
|
+
database: {
|
|
453
|
+
url: get('DATABASE_URL').string(),
|
|
454
|
+
poolSize: get('DB_POOL_SIZE').string().transform(Number).default(10),
|
|
455
|
+
},
|
|
456
|
+
cache: {
|
|
457
|
+
url: get('REDIS_URL').string().optional(),
|
|
458
|
+
ttl: get('CACHE_TTL').string(),
|
|
459
|
+
},
|
|
460
|
+
}));
|
|
461
|
+
|
|
462
|
+
expect(sniffer.getOptionalVariables().sort()).toEqual([
|
|
463
|
+
'DB_POOL_SIZE',
|
|
464
|
+
'REDIS_URL',
|
|
465
|
+
]);
|
|
466
|
+
expect(sniffer.getEnvironmentVariables({ markOptional: true })).toEqual([
|
|
467
|
+
'CACHE_TTL',
|
|
468
|
+
'DATABASE_URL',
|
|
469
|
+
'DB_POOL_SIZE?',
|
|
470
|
+
'REDIS_URL?',
|
|
471
|
+
]);
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
|
|
346
475
|
describe('Edge cases', () => {
|
|
347
476
|
it('should return empty array when no variables accessed', () => {
|
|
348
477
|
const sniffer = new SnifferEnvironmentParser();
|
|
@@ -483,4 +612,33 @@ describe('sniffWithFireAndForget', () => {
|
|
|
483
612
|
expect(result.error).toBeUndefined();
|
|
484
613
|
expect(result.unhandledRejections).toEqual([]);
|
|
485
614
|
});
|
|
615
|
+
|
|
616
|
+
it('should include optionalEnvVars in result', async () => {
|
|
617
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
618
|
+
|
|
619
|
+
const result = await sniffWithFireAndForget(sniffer, () => {
|
|
620
|
+
sniffer.create((get) => ({
|
|
621
|
+
required: get('DATABASE_URL').string(),
|
|
622
|
+
optional: get('PORT').string().default('3000'),
|
|
623
|
+
alsoOptional: get('LOG_LEVEL').string().optional(),
|
|
624
|
+
}));
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
expect(result.envVars).toEqual(['DATABASE_URL', 'LOG_LEVEL', 'PORT']);
|
|
628
|
+
expect(result.optionalEnvVars).toEqual(['LOG_LEVEL', 'PORT']);
|
|
629
|
+
expect(result.error).toBeUndefined();
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
it('should return empty optionalEnvVars when all vars are required', async () => {
|
|
633
|
+
const sniffer = new SnifferEnvironmentParser();
|
|
634
|
+
|
|
635
|
+
const result = await sniffWithFireAndForget(sniffer, () => {
|
|
636
|
+
sniffer.create((get) => ({
|
|
637
|
+
url: get('DATABASE_URL').string(),
|
|
638
|
+
key: get('API_KEY').string(),
|
|
639
|
+
}));
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
expect(result.optionalEnvVars).toEqual([]);
|
|
643
|
+
});
|
|
486
644
|
});
|
package/src/credentials.ts
CHANGED
|
@@ -42,9 +42,13 @@ export function decryptCredentials(
|
|
|
42
42
|
/**
|
|
43
43
|
* Credentials object for use with EnvironmentParser.
|
|
44
44
|
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
45
|
+
* Resolution order:
|
|
46
|
+
* 1. **Dev mode (gkm dev/exec)**: Checks `globalThis.__gkm_credentials__` for
|
|
47
|
+
* credentials injected by the CLI preload script. This approach survives
|
|
48
|
+
* CJS/ESM module duplication (where mutating the export would only affect one copy).
|
|
49
|
+
* 2. **Production mode**: Decrypts build-time embedded credentials using the
|
|
50
|
+
* `GKM_MASTER_KEY` environment variable (AES-256-GCM).
|
|
51
|
+
* 3. **Fallback**: Returns empty object (allows graceful fallback to process.env).
|
|
48
52
|
*
|
|
49
53
|
* @example
|
|
50
54
|
* ```typescript
|
|
@@ -61,6 +65,15 @@ export function decryptCredentials(
|
|
|
61
65
|
* ```
|
|
62
66
|
*/
|
|
63
67
|
export const Credentials: Record<string, string> = (() => {
|
|
68
|
+
// Dev mode: check if gkm exec/dev preload injected credentials via globalThis
|
|
69
|
+
// This survives CJS/ESM module duplication where Object.assign on the
|
|
70
|
+
// export would only mutate one copy of the module's Credentials object.
|
|
71
|
+
const injected = (globalThis as Record<string, unknown>)
|
|
72
|
+
.__gkm_credentials__ as Record<string, string> | undefined;
|
|
73
|
+
if (injected) {
|
|
74
|
+
return injected;
|
|
75
|
+
}
|
|
76
|
+
|
|
64
77
|
// Development mode - no credentials embedded at build time
|
|
65
78
|
if (
|
|
66
79
|
typeof __GKM_ENCRYPTED_CREDENTIALS__ === 'undefined' ||
|
package/tsdown.config.ts
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
1
|
import { defineConfig } from 'tsdown';
|
|
2
2
|
|
|
3
|
-
export default defineConfig({
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
entry: [
|
|
5
|
+
'src/index.ts',
|
|
6
|
+
'src/sst.ts',
|
|
7
|
+
'src/SnifferEnvironmentParser.ts',
|
|
8
|
+
'src/credentials.ts',
|
|
9
|
+
],
|
|
10
|
+
clean: true,
|
|
11
|
+
outDir: 'dist',
|
|
12
|
+
format: ['cjs', 'esm'],
|
|
13
|
+
sourcemap: true,
|
|
14
|
+
dts: true,
|
|
15
|
+
outExtensions: (ctx) => ({
|
|
16
|
+
js: ctx.format === 'es' ? '.mjs' : '.cjs',
|
|
17
|
+
}),
|
|
18
|
+
});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { EnvRecord, EnvValue, EnvironmentBuilder, EnvironmentBuilderOptions, EnvironmentResolver, InputValue, Resolvers, TypedInputValue, TypedResolvers, environmentCase } from "./EnvironmentBuilder-Xuf2Dd9u.cjs";
|
|
2
|
-
export { EnvRecord, EnvValue, EnvironmentBuilder, EnvironmentBuilderOptions, EnvironmentResolver, InputValue, Resolvers, TypedInputValue, TypedResolvers, environmentCase };
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { EnvRecord, EnvValue, EnvironmentBuilder, EnvironmentBuilderOptions, EnvironmentResolver, InputValue, Resolvers, TypedInputValue, TypedResolvers, environmentCase } from "./EnvironmentBuilder-jF-b7WQg.mjs";
|
|
2
|
-
export { EnvRecord, EnvValue, EnvironmentBuilder, EnvironmentBuilderOptions, EnvironmentResolver, InputValue, Resolvers, TypedInputValue, TypedResolvers, environmentCase };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentParser-CkLfmn4Y.d.mts","names":[],"sources":["../src/EnvironmentParser.ts"],"sourcesContent":[],"mappings":";;;;;;AAWA;;;;AAS4B,cATf,YASe,CAAA,kBATgB,WAShB,CAAA,CAAA;EAAG,iBAMT,MAAA;EAAS,iBAArB,OAAA;EAAW;AA2FrB;;;;;EAiJmC,WAClB,CAAA,MAAA,EApPU,SAoPV,EAAA,OAAA,CAAA,EAnPW,GAmPX,CAAA,MAAA,CAAA;EAAU;;;AACX;EA6BJ,KAAA,CAAA,CAAA,EA3QF,WA2Qa,CA3QD,SA2QC,CAAA;EAAA;;;;;;;;;;;;;;;;EAKjB,uBAAC,CAAA,CAAA,EAAA,MAAA,EAAA;AAAC;AAWR;;;;AAEa;AAUb;;;;;AAEc;AAMd;;;;;;;;cApNa,4BAA4B;;;;;;;;;;;sBAWH;;;;;;;;;;;;;;;;;;;;;;;;yBAsId,4BACP,eAAe,UAC5B,aAAa;;;;;;;;;;;;;;;;;;;;;;KA6BL,sBAAsB,6BACrB,IAAI,EAAE,WAAW,CAAA,CAAE,YAC5B,CAAA,CAAE,MAAM,EAAE,MACV,EAAE,WAAW,0BACZ,YAAY,EAAE,MACd,EAAE;;;;;;;;;KAWK,mDACL,iBACK;;;;;;;;;KAUA,qCAAqC,qBAC3C,eACD;;;;;KAMO,WAAA,GAAc"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentParser-DJdW7vOL.cjs","names":["config: TResponse","envVars: Set<string>","errors: z.core.$ZodIssue[]","config: T","path: string[]","result: EmptyObject","z","schema: z.ZodType","name: string","issue: z.core.$ZodIssue","builder: (get: EnvFetcher) => TReturn"],"sources":["../src/EnvironmentParser.ts"],"sourcesContent":["import get from 'lodash.get';\nimport set from 'lodash.set';\nimport { z } from 'zod/v4';\nimport { formatParseError, isDevelopment } from './formatter.js';\n\n/**\n * Parses and validates configuration objects against Zod schemas.\n * Handles nested configurations and aggregates validation errors.\n *\n * @template TResponse - The shape of the configuration object\n */\nexport class ConfigParser<TResponse extends EmptyObject> {\n\t/**\n\t * Creates a new ConfigParser instance.\n\t *\n\t * @param config - The configuration object to parse\n\t * @param envVars - Set of environment variable names that were accessed\n\t */\n\tconstructor(\n\t\tprivate readonly config: TResponse,\n\t\tprivate readonly envVars: Set<string> = new Set(),\n\t) {}\n\t/**\n\t * Parses the config object and validates it against the Zod schemas\n\t * @returns The parsed config object\n\t */\n\tparse(): InferConfig<TResponse> {\n\t\tconst errors: z.core.$ZodIssue[] = [];\n\n\t\tconst parseDeep = <T>(config: T, path: string[] = []) => {\n\t\t\tconst result: EmptyObject = {};\n\n\t\t\tif (config && typeof config !== 'object') {\n\t\t\t\treturn config;\n\t\t\t}\n\n\t\t\tfor (const key in config) {\n\t\t\t\tconst schema = config[key];\n\t\t\t\tconst currentPath = [...path, key];\n\n\t\t\t\tif (schema instanceof z.ZodType) {\n\t\t\t\t\tconst parsed = schema.safeParse(undefined);\n\t\t\t\t\tif (parsed.success) {\n\t\t\t\t\t\tset(result, key, parsed.data);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If the schema is invalid, assign the error\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t...parsed.error.issues.map((issue) => ({\n\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\tpath: [...currentPath, ...(issue.path as string[])],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (schema) {\n\t\t\t\t\tset(result, key, parseDeep(schema as EmptyObject, currentPath));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t};\n\n\t\tconst parsedConfig = parseDeep(\n\t\t\tthis.config,\n\t\t) as unknown as InferConfig<TResponse>;\n\n\t\tif (errors.length > 0) {\n\t\t\tconst zodError = new z.ZodError(errors);\n\t\t\t// In development, log a formatted error message before throwing\n\t\t\tif (isDevelopment()) {\n\t\t\t\tconsole.error(formatParseError(zodError));\n\t\t\t}\n\t\t\tthrow zodError;\n\t\t}\n\n\t\treturn parsedConfig;\n\t}\n\n\t/**\n\t * Returns an array of environment variable names that were accessed during config creation.\n\t * This is useful for deployment and configuration management to know which env vars are required.\n\t *\n\t * @returns Array of environment variable names, sorted alphabetically\n\t *\n\t * @example\n\t * ```typescript\n\t * const config = envParser.create((get) => ({\n\t * dbUrl: get('DATABASE_URL').string(),\n\t * port: get('PORT').number()\n\t * }));\n\t *\n\t * config.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']\n\t * ```\n\t */\n\tgetEnvironmentVariables(): string[] {\n\t\treturn Array.from(this.envVars).sort();\n\t}\n}\n\n/**\n * Parses environment variables with type-safe validation using Zod schemas.\n * Provides a fluent API for defining environment variable schemas with automatic\n * error context enrichment.\n *\n * @template T - The type of the configuration object (typically process.env)\n *\n * @example\n * ```typescript\n * const config = new EnvironmentParser(process.env)\n * .create((get) => ({\n * port: get('PORT').string().transform(Number).default(3000),\n * database: {\n * url: get('DATABASE_URL').string().url()\n * }\n * }))\n * .parse();\n * ```\n */\nexport class EnvironmentParser<T extends EmptyObject> {\n\t/**\n\t * Set to track which environment variable names have been accessed\n\t */\n\tprivate readonly accessedVars: Set<string> = new Set();\n\n\t/**\n\t * Creates a new EnvironmentParser instance.\n\t *\n\t * @param config - The configuration object to parse (typically process.env)\n\t */\n\tconstructor(private readonly config: T) {}\n\n\t/**\n\t * Wraps a Zod schema to intercept parse/safeParse calls and enrich error messages\n\t * with environment variable context.\n\t *\n\t * @param schema - The Zod schema to wrap\n\t * @param name - The environment variable name for error context\n\t * @returns A wrapped Zod schema with enhanced error reporting\n\t */\n\tprivate wrapSchema = (schema: z.ZodType, name: string): z.ZodType => {\n\t\t// Create a proxy that intercepts all method calls on the schema\n\t\treturn new Proxy(schema, {\n\t\t\tget: (target, prop) => {\n\t\t\t\tif (prop === 'parse') {\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tconst value = get(this.config, name);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn target.parse(value);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof z.ZodError) {\n\t\t\t\t\t\t\t\t// Modify the error to include the environment variable name\n\t\t\t\t\t\t\t\tconst modifiedIssues = error.issues.map((issue) => ({\n\t\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\t\tmessage: `Environment variable \"${name}\": ${issue.message}`,\n\t\t\t\t\t\t\t\t\tpath: [name, ...issue.path],\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\tthrow new z.ZodError(modifiedIssues);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (prop === 'safeParse') {\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tconst value = get(this.config, name);\n\t\t\t\t\t\tconst result = target.safeParse(value);\n\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\t// Modify the error to include the environment variable name\n\t\t\t\t\t\t\tconst modifiedIssues = result.error.issues.map(\n\t\t\t\t\t\t\t\t(issue: z.core.$ZodIssue) => ({\n\t\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\t\tmessage: `Environment variable \"${name}\": ${issue.message}`,\n\t\t\t\t\t\t\t\t\tpath: [name, ...issue.path],\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tsuccess: false as const,\n\t\t\t\t\t\t\t\terror: new z.ZodError(modifiedIssues),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// For any method that returns a new schema (like transform, optional, etc.),\n\t\t\t\t// wrap the result as well\n\t\t\t\tconst originalProp = target[prop as keyof typeof target];\n\t\t\t\tif (typeof originalProp === 'function') {\n\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\tconst result = originalProp.apply(target, args);\n\t\t\t\t\t\t// If the result is a ZodType, wrap it too\n\t\t\t\t\t\tif (result && typeof result === 'object' && 'parse' in result) {\n\t\t\t\t\t\t\treturn this.wrapSchema(result, name);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn originalProp;\n\t\t\t},\n\t\t});\n\t};\n\n\t/**\n\t * Creates a proxied version of the Zod object that wraps all schema creators\n\t * to provide enhanced error messages with environment variable context.\n\t *\n\t * @param name - The environment variable name\n\t * @returns A proxied Zod object with wrapped schema creators\n\t */\n\tprivate getZodGetter = (name: string) => {\n\t\t// Track that this environment variable was accessed\n\t\tthis.accessedVars.add(name);\n\n\t\t// Return an object that has all Zod schemas but with our wrapper\n\t\treturn new Proxy(\n\t\t\t{ ...z },\n\t\t\t{\n\t\t\t\tget: (target, prop) => {\n\t\t\t\t\t// deno-lint-ignore ban-ts-comment\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tconst value = target[prop];\n\n\t\t\t\t\tif (typeof value === 'function') {\n\t\t\t\t\t\t// Return a wrapper around each Zod schema creator\n\t\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\t\tconst schema = value(...args);\n\t\t\t\t\t\t\treturn this.wrapSchema(schema, name);\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Handle objects like z.coerce\n\t\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\t\treturn new Proxy(value, {\n\t\t\t\t\t\t\tget: (nestedTarget, nestedProp) => {\n\t\t\t\t\t\t\t\tconst nestedValue =\n\t\t\t\t\t\t\t\t\tnestedTarget[nestedProp as keyof typeof nestedTarget];\n\t\t\t\t\t\t\t\tif (typeof nestedValue === 'function') {\n\t\t\t\t\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\t\t\t\t\tconst schema = nestedValue(...args);\n\t\t\t\t\t\t\t\t\t\treturn this.wrapSchema(schema, name);\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn nestedValue;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t};\n\n\t/**\n\t * Creates a new ConfigParser object that can be used to parse the config object\n\t *\n\t * @param builder - A function that takes a getter function and returns a config object\n\t * @returns A ConfigParser object that can be used to parse the config object\n\t */\n\tcreate<TReturn extends EmptyObject>(\n\t\tbuilder: (get: EnvFetcher) => TReturn,\n\t): ConfigParser<TReturn> {\n\t\tconst config = builder(this.getZodGetter);\n\t\treturn new ConfigParser(config, this.accessedVars);\n\t}\n\n\t/**\n\t * Returns an array of environment variable names that were accessed via the getter.\n\t * This is useful for build-time analysis to determine which env vars a service needs.\n\t *\n\t * @returns Array of environment variable names, sorted alphabetically\n\t *\n\t * @example\n\t * ```typescript\n\t * const sniffer = new EnvironmentParser({});\n\t * service.register(sniffer);\n\t * const envVars = sniffer.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']\n\t * ```\n\t */\n\tgetEnvironmentVariables(): string[] {\n\t\treturn Array.from(this.accessedVars).sort();\n\t}\n}\n\n/**\n * Infers the TypeScript type of a configuration object based on its Zod schemas.\n * Recursively processes nested objects and extracts types from Zod schemas.\n *\n * @template T - The configuration object type\n */\nexport type InferConfig<T extends EmptyObject> = {\n\t[K in keyof T]: T[K] extends z.ZodSchema\n\t\t? z.infer<T[K]>\n\t\t: T[K] extends Record<string, unknown>\n\t\t\t? InferConfig<T[K]>\n\t\t\t: T[K];\n};\n\n/**\n * Function type for fetching environment variables with Zod validation.\n * Returns a Zod object scoped to a specific environment variable.\n *\n * @template TPath - The environment variable path type\n * @param name - The environment variable name\n * @returns A Zod object for defining the schema\n */\nexport type EnvFetcher<TPath extends string = string> = (\n\tname: TPath,\n) => typeof z;\n\n/**\n * Function type for building environment configuration objects.\n * Takes an EnvFetcher and returns a configuration object with Zod schemas.\n *\n * @template TResponse - The response configuration object type\n * @param get - The environment variable fetcher function\n * @returns The configuration object with Zod schemas\n */\nexport type EnvironmentBuilder<TResponse extends EmptyObject> = (\n\tget: EnvFetcher,\n) => TResponse;\n\n/**\n * Type alias for a generic object with unknown values.\n * Used as a constraint for configuration objects.\n */\nexport type EmptyObject = Record<string | number | symbol, unknown>;\n"],"mappings":";;;;;;;;;;;;;AAWA,IAAa,eAAb,MAAyD;;;;;;;CAOxD,YACkBA,QACAC,0BAAuB,IAAI,OAC3C;EAFgB;EACA;CACd;;;;;CAKJ,QAAgC;EAC/B,MAAMC,SAA6B,CAAE;EAErC,MAAM,YAAY,CAAIC,QAAWC,OAAiB,CAAE,MAAK;GACxD,MAAMC,SAAsB,CAAE;AAE9B,OAAI,iBAAiB,WAAW,SAC/B,QAAO;AAGR,QAAK,MAAM,OAAO,QAAQ;IACzB,MAAM,SAAS,OAAO;IACtB,MAAM,cAAc,CAAC,GA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K;IACpC;AAEF,WAAO;GACP,EACD;AAGF,UAAO;EACP,EACD;CAEF;;;;;;;CAQD,OACCI,SACwB;EACxB,MAAM,SAAS,QAAQ,KAAK,aAAa;AACzC,SAAO,IAAI,aAAa,QAAQ,KAAK;CACrC;;;;;;;;;;;;;;CAeD,0BAAoC;AACnC,SAAO,MAAM,KAAK,KAAK,aAAa,CAAC,MAAM;CAC3C;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentParser-DtOL86NU.d.cts","names":[],"sources":["../src/EnvironmentParser.ts"],"sourcesContent":[],"mappings":";;;;;;AAWA;;;;AAS4B,cATf,YASe,CAAA,kBATgB,WAShB,CAAA,CAAA;EAAG,iBAMT,MAAA;EAAS,iBAArB,OAAA;EAAW;AA2FrB;;;;;EAiJmC,WAClB,CAAA,MAAA,EApPU,SAoPV,EAAA,OAAA,CAAA,EAnPW,GAmPX,CAAA,MAAA,CAAA;EAAU;;;AACX;EA6BJ,KAAA,CAAA,CAAA,EA3QF,WA2Qa,CA3QD,SA2QC,CAAA;EAAA;;;;;;;;;;;;;;;;EAKjB,uBAAC,CAAA,CAAA,EAAA,MAAA,EAAA;AAAC;AAWR;;;;AAEa;AAUb;;;;;AAEc;AAMd;;;;;;;;cApNa,4BAA4B;;;;;;;;;;;sBAWH;;;;;;;;;;;;;;;;;;;;;;;;yBAsId,4BACP,eAAe,UAC5B,aAAa;;;;;;;;;;;;;;;;;;;;;;KA6BL,sBAAsB,6BACrB,IAAI,EAAE,WAAW,CAAA,CAAE,YAC5B,CAAA,CAAE,MAAM,EAAE,MACV,EAAE,WAAW,0BACZ,YAAY,EAAE,MACd,EAAE;;;;;;;;;KAWK,mDACL,iBACK;;;;;;;;;KAUA,qCAAqC,qBAC3C,eACD;;;;;KAMO,WAAA,GAAc"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentParser-zMblItla.mjs","names":["config: TResponse","envVars: Set<string>","errors: z.core.$ZodIssue[]","config: T","path: string[]","result: EmptyObject","schema: z.ZodType","name: string","issue: z.core.$ZodIssue","builder: (get: EnvFetcher) => TReturn"],"sources":["../src/EnvironmentParser.ts"],"sourcesContent":["import get from 'lodash.get';\nimport set from 'lodash.set';\nimport { z } from 'zod/v4';\nimport { formatParseError, isDevelopment } from './formatter.js';\n\n/**\n * Parses and validates configuration objects against Zod schemas.\n * Handles nested configurations and aggregates validation errors.\n *\n * @template TResponse - The shape of the configuration object\n */\nexport class ConfigParser<TResponse extends EmptyObject> {\n\t/**\n\t * Creates a new ConfigParser instance.\n\t *\n\t * @param config - The configuration object to parse\n\t * @param envVars - Set of environment variable names that were accessed\n\t */\n\tconstructor(\n\t\tprivate readonly config: TResponse,\n\t\tprivate readonly envVars: Set<string> = new Set(),\n\t) {}\n\t/**\n\t * Parses the config object and validates it against the Zod schemas\n\t * @returns The parsed config object\n\t */\n\tparse(): InferConfig<TResponse> {\n\t\tconst errors: z.core.$ZodIssue[] = [];\n\n\t\tconst parseDeep = <T>(config: T, path: string[] = []) => {\n\t\t\tconst result: EmptyObject = {};\n\n\t\t\tif (config && typeof config !== 'object') {\n\t\t\t\treturn config;\n\t\t\t}\n\n\t\t\tfor (const key in config) {\n\t\t\t\tconst schema = config[key];\n\t\t\t\tconst currentPath = [...path, key];\n\n\t\t\t\tif (schema instanceof z.ZodType) {\n\t\t\t\t\tconst parsed = schema.safeParse(undefined);\n\t\t\t\t\tif (parsed.success) {\n\t\t\t\t\t\tset(result, key, parsed.data);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// If the schema is invalid, assign the error\n\t\t\t\t\t\terrors.push(\n\t\t\t\t\t\t\t...parsed.error.issues.map((issue) => ({\n\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\tpath: [...currentPath, ...(issue.path as string[])],\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (schema) {\n\t\t\t\t\tset(result, key, parseDeep(schema as EmptyObject, currentPath));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn result;\n\t\t};\n\n\t\tconst parsedConfig = parseDeep(\n\t\t\tthis.config,\n\t\t) as unknown as InferConfig<TResponse>;\n\n\t\tif (errors.length > 0) {\n\t\t\tconst zodError = new z.ZodError(errors);\n\t\t\t// In development, log a formatted error message before throwing\n\t\t\tif (isDevelopment()) {\n\t\t\t\tconsole.error(formatParseError(zodError));\n\t\t\t}\n\t\t\tthrow zodError;\n\t\t}\n\n\t\treturn parsedConfig;\n\t}\n\n\t/**\n\t * Returns an array of environment variable names that were accessed during config creation.\n\t * This is useful for deployment and configuration management to know which env vars are required.\n\t *\n\t * @returns Array of environment variable names, sorted alphabetically\n\t *\n\t * @example\n\t * ```typescript\n\t * const config = envParser.create((get) => ({\n\t * dbUrl: get('DATABASE_URL').string(),\n\t * port: get('PORT').number()\n\t * }));\n\t *\n\t * config.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']\n\t * ```\n\t */\n\tgetEnvironmentVariables(): string[] {\n\t\treturn Array.from(this.envVars).sort();\n\t}\n}\n\n/**\n * Parses environment variables with type-safe validation using Zod schemas.\n * Provides a fluent API for defining environment variable schemas with automatic\n * error context enrichment.\n *\n * @template T - The type of the configuration object (typically process.env)\n *\n * @example\n * ```typescript\n * const config = new EnvironmentParser(process.env)\n * .create((get) => ({\n * port: get('PORT').string().transform(Number).default(3000),\n * database: {\n * url: get('DATABASE_URL').string().url()\n * }\n * }))\n * .parse();\n * ```\n */\nexport class EnvironmentParser<T extends EmptyObject> {\n\t/**\n\t * Set to track which environment variable names have been accessed\n\t */\n\tprivate readonly accessedVars: Set<string> = new Set();\n\n\t/**\n\t * Creates a new EnvironmentParser instance.\n\t *\n\t * @param config - The configuration object to parse (typically process.env)\n\t */\n\tconstructor(private readonly config: T) {}\n\n\t/**\n\t * Wraps a Zod schema to intercept parse/safeParse calls and enrich error messages\n\t * with environment variable context.\n\t *\n\t * @param schema - The Zod schema to wrap\n\t * @param name - The environment variable name for error context\n\t * @returns A wrapped Zod schema with enhanced error reporting\n\t */\n\tprivate wrapSchema = (schema: z.ZodType, name: string): z.ZodType => {\n\t\t// Create a proxy that intercepts all method calls on the schema\n\t\treturn new Proxy(schema, {\n\t\t\tget: (target, prop) => {\n\t\t\t\tif (prop === 'parse') {\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tconst value = get(this.config, name);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn target.parse(value);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (error instanceof z.ZodError) {\n\t\t\t\t\t\t\t\t// Modify the error to include the environment variable name\n\t\t\t\t\t\t\t\tconst modifiedIssues = error.issues.map((issue) => ({\n\t\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\t\tmessage: `Environment variable \"${name}\": ${issue.message}`,\n\t\t\t\t\t\t\t\t\tpath: [name, ...issue.path],\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\tthrow new z.ZodError(modifiedIssues);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (prop === 'safeParse') {\n\t\t\t\t\treturn () => {\n\t\t\t\t\t\tconst value = get(this.config, name);\n\t\t\t\t\t\tconst result = target.safeParse(value);\n\n\t\t\t\t\t\tif (!result.success) {\n\t\t\t\t\t\t\t// Modify the error to include the environment variable name\n\t\t\t\t\t\t\tconst modifiedIssues = result.error.issues.map(\n\t\t\t\t\t\t\t\t(issue: z.core.$ZodIssue) => ({\n\t\t\t\t\t\t\t\t\t...issue,\n\t\t\t\t\t\t\t\t\tmessage: `Environment variable \"${name}\": ${issue.message}`,\n\t\t\t\t\t\t\t\t\tpath: [name, ...issue.path],\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tsuccess: false as const,\n\t\t\t\t\t\t\t\terror: new z.ZodError(modifiedIssues),\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t// For any method that returns a new schema (like transform, optional, etc.),\n\t\t\t\t// wrap the result as well\n\t\t\t\tconst originalProp = target[prop as keyof typeof target];\n\t\t\t\tif (typeof originalProp === 'function') {\n\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\tconst result = originalProp.apply(target, args);\n\t\t\t\t\t\t// If the result is a ZodType, wrap it too\n\t\t\t\t\t\tif (result && typeof result === 'object' && 'parse' in result) {\n\t\t\t\t\t\t\treturn this.wrapSchema(result, name);\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\treturn originalProp;\n\t\t\t},\n\t\t});\n\t};\n\n\t/**\n\t * Creates a proxied version of the Zod object that wraps all schema creators\n\t * to provide enhanced error messages with environment variable context.\n\t *\n\t * @param name - The environment variable name\n\t * @returns A proxied Zod object with wrapped schema creators\n\t */\n\tprivate getZodGetter = (name: string) => {\n\t\t// Track that this environment variable was accessed\n\t\tthis.accessedVars.add(name);\n\n\t\t// Return an object that has all Zod schemas but with our wrapper\n\t\treturn new Proxy(\n\t\t\t{ ...z },\n\t\t\t{\n\t\t\t\tget: (target, prop) => {\n\t\t\t\t\t// deno-lint-ignore ban-ts-comment\n\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\tconst value = target[prop];\n\n\t\t\t\t\tif (typeof value === 'function') {\n\t\t\t\t\t\t// Return a wrapper around each Zod schema creator\n\t\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\t\tconst schema = value(...args);\n\t\t\t\t\t\t\treturn this.wrapSchema(schema, name);\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\t// Handle objects like z.coerce\n\t\t\t\t\tif (value && typeof value === 'object') {\n\t\t\t\t\t\treturn new Proxy(value, {\n\t\t\t\t\t\t\tget: (nestedTarget, nestedProp) => {\n\t\t\t\t\t\t\t\tconst nestedValue =\n\t\t\t\t\t\t\t\t\tnestedTarget[nestedProp as keyof typeof nestedTarget];\n\t\t\t\t\t\t\t\tif (typeof nestedValue === 'function') {\n\t\t\t\t\t\t\t\t\treturn (...args: any[]) => {\n\t\t\t\t\t\t\t\t\t\tconst schema = nestedValue(...args);\n\t\t\t\t\t\t\t\t\t\treturn this.wrapSchema(schema, name);\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn nestedValue;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t};\n\n\t/**\n\t * Creates a new ConfigParser object that can be used to parse the config object\n\t *\n\t * @param builder - A function that takes a getter function and returns a config object\n\t * @returns A ConfigParser object that can be used to parse the config object\n\t */\n\tcreate<TReturn extends EmptyObject>(\n\t\tbuilder: (get: EnvFetcher) => TReturn,\n\t): ConfigParser<TReturn> {\n\t\tconst config = builder(this.getZodGetter);\n\t\treturn new ConfigParser(config, this.accessedVars);\n\t}\n\n\t/**\n\t * Returns an array of environment variable names that were accessed via the getter.\n\t * This is useful for build-time analysis to determine which env vars a service needs.\n\t *\n\t * @returns Array of environment variable names, sorted alphabetically\n\t *\n\t * @example\n\t * ```typescript\n\t * const sniffer = new EnvironmentParser({});\n\t * service.register(sniffer);\n\t * const envVars = sniffer.getEnvironmentVariables(); // ['DATABASE_URL', 'PORT']\n\t * ```\n\t */\n\tgetEnvironmentVariables(): string[] {\n\t\treturn Array.from(this.accessedVars).sort();\n\t}\n}\n\n/**\n * Infers the TypeScript type of a configuration object based on its Zod schemas.\n * Recursively processes nested objects and extracts types from Zod schemas.\n *\n * @template T - The configuration object type\n */\nexport type InferConfig<T extends EmptyObject> = {\n\t[K in keyof T]: T[K] extends z.ZodSchema\n\t\t? z.infer<T[K]>\n\t\t: T[K] extends Record<string, unknown>\n\t\t\t? InferConfig<T[K]>\n\t\t\t: T[K];\n};\n\n/**\n * Function type for fetching environment variables with Zod validation.\n * Returns a Zod object scoped to a specific environment variable.\n *\n * @template TPath - The environment variable path type\n * @param name - The environment variable name\n * @returns A Zod object for defining the schema\n */\nexport type EnvFetcher<TPath extends string = string> = (\n\tname: TPath,\n) => typeof z;\n\n/**\n * Function type for building environment configuration objects.\n * Takes an EnvFetcher and returns a configuration object with Zod schemas.\n *\n * @template TResponse - The response configuration object type\n * @param get - The environment variable fetcher function\n * @returns The configuration object with Zod schemas\n */\nexport type EnvironmentBuilder<TResponse extends EmptyObject> = (\n\tget: EnvFetcher,\n) => TResponse;\n\n/**\n * Type alias for a generic object with unknown values.\n * Used as a constraint for configuration objects.\n */\nexport type EmptyObject = Record<string | number | symbol, unknown>;\n"],"mappings":";;;;;;;;;;;;AAWA,IAAa,eAAb,MAAyD;;;;;;;CAOxD,YACkBA,QACAC,0BAAuB,IAAI,OAC3C;EAFgB;EACA;CACd;;;;;CAKJ,QAAgC;EAC/B,MAAMC,SAA6B,CAAE;EAErC,MAAM,YAAY,CAAIC,QAAWC,OAAiB,CAAE,MAAK;GACxD,MAAMC,SAAsB,CAAE;AAE9B,OAAI,iBAAiB,WAAW,SAC/B,QAAO;AAGR,QAAK,MAAM,OAAO,QAAQ;IACzB,MAAM,SAAS,OAAO;IACtB,MAAM,cAAc,CAAC,GAAG,MAAM,GAAI;AAElC,QAAI,kBAAkB,EAAE,SAAS;KAChC,MAAM,SAAS,OAAO,iBAAoB;AAC1C,SAAI,OAAO,QACV,KAAI,QAAQ,KAAK,OAAO,KAAK;SAG7B,QAAO,KACN,GAAG,OAAO,MAAM,OAAO,IAAI,CAAC,WAAW;MACtC,GAAG;MACH,MAAM,CAAC,GAAG,aAAa,GAAI,MAAM,IAAkB;KACnD,GAAE,CACH;IAEF,WAAU,OACV,KAAI,QAAQ,KAAK,UAAU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