@logtape/config 1.4.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2024–2025 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ @logtape/config
2
+ ===============
3
+
4
+ [![JSR][JSR badge]][JSR]
5
+ [![npm][npm badge]][npm]
6
+
7
+ This package provides functionality to configure [LogTape] from plain objects,
8
+ such as those loaded from JSON or YAML files.
9
+
10
+ [JSR]: https://jsr.io/@logtape/config
11
+ [JSR badge]: https://jsr.io/badges/@logtape/config
12
+ [npm]: https://www.npmjs.com/package/@logtape/config
13
+ [npm badge]: https://img.shields.io/npm/v/@logtape/config?logo=npm
14
+ [LogTape]: https://logtape.org/
15
+
16
+
17
+ Installation
18
+ ------------
19
+
20
+ The package is available on [JSR] and [npm]:
21
+
22
+ ~~~~ sh
23
+ deno add jsr:@logtape/config
24
+ npm add @logtape/config
25
+ pnpm add @logtape/config
26
+ yarn add @logtape/config
27
+ bun add @logtape/config
28
+ ~~~~
29
+
30
+
31
+ Usage
32
+ -----
33
+
34
+ You can configure LogTape using a plain object:
35
+
36
+ ~~~~ typescript
37
+ import { configureFromObject } from "@logtape/config";
38
+ import { readFile } from "node:fs/promises";
39
+
40
+ const config = JSON.parse(await readFile("./logtape.json", "utf-8"));
41
+ await configureFromObject(config);
42
+ ~~~~
43
+
44
+ For more details, see the [Configuration from objects] section in the LogTape
45
+ manual.
46
+
47
+ [Configuration from objects]: https://logtape.org/manual/config#configuration-from-objects
@@ -0,0 +1,30 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ Object.defineProperty(exports, '__toESM', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return __toESM;
29
+ }
30
+ });
@@ -0,0 +1,80 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_types = require('./types.cjs');
3
+ const require_loader = require('./loader.cjs');
4
+ const require_shorthands = require('./shorthands.cjs');
5
+ const __logtape_logtape = require_rolldown_runtime.__toESM(require("@logtape/logtape"));
6
+
7
+ //#region src/config.ts
8
+ /**
9
+ * Configures LogTape from a plain object.
10
+ *
11
+ * @param config Configuration object (typically loaded from JSON/YAML/TOML)
12
+ * @param options Configuration options
13
+ * @throws {ConfigError} If configuration is invalid and onInvalidConfig is "throw"
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { configureFromObject } from "@logtape/config";
18
+ * import { readFile } from "fs/promises";
19
+ *
20
+ * const config = JSON.parse(await readFile("./logtape.json", "utf-8"));
21
+ * await configureFromObject(config);
22
+ * ```
23
+ * @since 1.4.0
24
+ */
25
+ async function configureFromObject(config, options) {
26
+ const shorthands = require_shorthands.mergeShorthands(require_shorthands.DEFAULT_SHORTHANDS, options?.shorthands);
27
+ const onInvalidConfig = options?.onInvalidConfig ?? "throw";
28
+ const warnings = [];
29
+ const sinks = {};
30
+ if (config.sinks) for (const [name, sinkConfig] of Object.entries(config.sinks)) try {
31
+ sinks[name] = await require_loader.createSink(sinkConfig, shorthands);
32
+ } catch (e) {
33
+ if (onInvalidConfig === "throw") throw e;
34
+ warnings.push(`Failed to create sink '${name}': ${e}`);
35
+ }
36
+ const filters = {};
37
+ if (config.filters) for (const [name, filterConfig] of Object.entries(config.filters)) try {
38
+ filters[name] = await require_loader.createFilter(filterConfig, shorthands);
39
+ } catch (e) {
40
+ if (onInvalidConfig === "throw") throw e;
41
+ warnings.push(`Failed to create filter '${name}': ${e}`);
42
+ }
43
+ const logTapeConfig = {
44
+ sinks,
45
+ filters,
46
+ loggers: []
47
+ };
48
+ if (config.loggers) for (const loggerConfig of config.loggers) {
49
+ const validSinks = [];
50
+ if (loggerConfig.sinks) for (const sinkName of loggerConfig.sinks) if (sinkName in sinks) validSinks.push(sinkName);
51
+ else {
52
+ const msg = `Logger '${Array.isArray(loggerConfig.category) ? loggerConfig.category.join(".") : loggerConfig.category}' references unknown or failed sink '${sinkName}'`;
53
+ if (onInvalidConfig === "throw") throw new require_types.ConfigError(msg);
54
+ warnings.push(msg);
55
+ }
56
+ const validFilters = [];
57
+ if (loggerConfig.filters) for (const filterName of loggerConfig.filters) if (filterName in filters) validFilters.push(filterName);
58
+ else {
59
+ const msg = `Logger '${Array.isArray(loggerConfig.category) ? loggerConfig.category.join(".") : loggerConfig.category}' references unknown or failed filter '${filterName}'`;
60
+ if (onInvalidConfig === "throw") throw new require_types.ConfigError(msg);
61
+ warnings.push(msg);
62
+ }
63
+ logTapeConfig.loggers.push({
64
+ category: loggerConfig.category,
65
+ sinks: validSinks.length > 0 ? validSinks : void 0,
66
+ filters: validFilters.length > 0 ? validFilters : void 0,
67
+ lowestLevel: loggerConfig.lowestLevel,
68
+ parentSinks: loggerConfig.parentSinks
69
+ });
70
+ }
71
+ if (config.reset) logTapeConfig.reset = true;
72
+ await (0, __logtape_logtape.configure)(logTapeConfig);
73
+ if (warnings.length > 0) {
74
+ const metaLogger = (0, __logtape_logtape.getLogger)(["logtape", "meta"]);
75
+ for (const warning of warnings) metaLogger.warn(warning);
76
+ }
77
+ }
78
+
79
+ //#endregion
80
+ exports.configureFromObject = configureFromObject;
@@ -0,0 +1,26 @@
1
+ import { ConfigureOptions, LogTapeConfig } from "./types.cjs";
2
+
3
+ //#region src/config.d.ts
4
+
5
+ /**
6
+ * Configures LogTape from a plain object.
7
+ *
8
+ * @param config Configuration object (typically loaded from JSON/YAML/TOML)
9
+ * @param options Configuration options
10
+ * @throws {ConfigError} If configuration is invalid and onInvalidConfig is "throw"
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { configureFromObject } from "@logtape/config";
15
+ * import { readFile } from "fs/promises";
16
+ *
17
+ * const config = JSON.parse(await readFile("./logtape.json", "utf-8"));
18
+ * await configureFromObject(config);
19
+ * ```
20
+ * @since 1.4.0
21
+ */
22
+ declare function configureFromObject(config: LogTapeConfig, options?: ConfigureOptions): Promise<void>;
23
+ //# sourceMappingURL=config.d.ts.map
24
+ //#endregion
25
+ export { configureFromObject };
26
+ //# sourceMappingURL=config.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.cts","names":[],"sources":["../src/config.ts"],"sourcesContent":[],"mappings":";;;;;;AAwBA;;;;;AAGU;;;;;;;;;;iBAHY,mBAAA,SACZ,yBACE,mBACT"}
@@ -0,0 +1,26 @@
1
+ import { ConfigureOptions, LogTapeConfig } from "./types.js";
2
+
3
+ //#region src/config.d.ts
4
+
5
+ /**
6
+ * Configures LogTape from a plain object.
7
+ *
8
+ * @param config Configuration object (typically loaded from JSON/YAML/TOML)
9
+ * @param options Configuration options
10
+ * @throws {ConfigError} If configuration is invalid and onInvalidConfig is "throw"
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { configureFromObject } from "@logtape/config";
15
+ * import { readFile } from "fs/promises";
16
+ *
17
+ * const config = JSON.parse(await readFile("./logtape.json", "utf-8"));
18
+ * await configureFromObject(config);
19
+ * ```
20
+ * @since 1.4.0
21
+ */
22
+ declare function configureFromObject(config: LogTapeConfig, options?: ConfigureOptions): Promise<void>;
23
+ //# sourceMappingURL=config.d.ts.map
24
+ //#endregion
25
+ export { configureFromObject };
26
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","names":[],"sources":["../src/config.ts"],"sourcesContent":[],"mappings":";;;;;;AAwBA;;;;;AAGU;;;;;;;;;;iBAHY,mBAAA,SACZ,yBACE,mBACT"}
package/dist/config.js ADDED
@@ -0,0 +1,80 @@
1
+ import { ConfigError } from "./types.js";
2
+ import { createFilter, createSink } from "./loader.js";
3
+ import { DEFAULT_SHORTHANDS, mergeShorthands } from "./shorthands.js";
4
+ import { configure, getLogger } from "@logtape/logtape";
5
+
6
+ //#region src/config.ts
7
+ /**
8
+ * Configures LogTape from a plain object.
9
+ *
10
+ * @param config Configuration object (typically loaded from JSON/YAML/TOML)
11
+ * @param options Configuration options
12
+ * @throws {ConfigError} If configuration is invalid and onInvalidConfig is "throw"
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { configureFromObject } from "@logtape/config";
17
+ * import { readFile } from "fs/promises";
18
+ *
19
+ * const config = JSON.parse(await readFile("./logtape.json", "utf-8"));
20
+ * await configureFromObject(config);
21
+ * ```
22
+ * @since 1.4.0
23
+ */
24
+ async function configureFromObject(config, options) {
25
+ const shorthands = mergeShorthands(DEFAULT_SHORTHANDS, options?.shorthands);
26
+ const onInvalidConfig = options?.onInvalidConfig ?? "throw";
27
+ const warnings = [];
28
+ const sinks = {};
29
+ if (config.sinks) for (const [name, sinkConfig] of Object.entries(config.sinks)) try {
30
+ sinks[name] = await createSink(sinkConfig, shorthands);
31
+ } catch (e) {
32
+ if (onInvalidConfig === "throw") throw e;
33
+ warnings.push(`Failed to create sink '${name}': ${e}`);
34
+ }
35
+ const filters = {};
36
+ if (config.filters) for (const [name, filterConfig] of Object.entries(config.filters)) try {
37
+ filters[name] = await createFilter(filterConfig, shorthands);
38
+ } catch (e) {
39
+ if (onInvalidConfig === "throw") throw e;
40
+ warnings.push(`Failed to create filter '${name}': ${e}`);
41
+ }
42
+ const logTapeConfig = {
43
+ sinks,
44
+ filters,
45
+ loggers: []
46
+ };
47
+ if (config.loggers) for (const loggerConfig of config.loggers) {
48
+ const validSinks = [];
49
+ if (loggerConfig.sinks) for (const sinkName of loggerConfig.sinks) if (sinkName in sinks) validSinks.push(sinkName);
50
+ else {
51
+ const msg = `Logger '${Array.isArray(loggerConfig.category) ? loggerConfig.category.join(".") : loggerConfig.category}' references unknown or failed sink '${sinkName}'`;
52
+ if (onInvalidConfig === "throw") throw new ConfigError(msg);
53
+ warnings.push(msg);
54
+ }
55
+ const validFilters = [];
56
+ if (loggerConfig.filters) for (const filterName of loggerConfig.filters) if (filterName in filters) validFilters.push(filterName);
57
+ else {
58
+ const msg = `Logger '${Array.isArray(loggerConfig.category) ? loggerConfig.category.join(".") : loggerConfig.category}' references unknown or failed filter '${filterName}'`;
59
+ if (onInvalidConfig === "throw") throw new ConfigError(msg);
60
+ warnings.push(msg);
61
+ }
62
+ logTapeConfig.loggers.push({
63
+ category: loggerConfig.category,
64
+ sinks: validSinks.length > 0 ? validSinks : void 0,
65
+ filters: validFilters.length > 0 ? validFilters : void 0,
66
+ lowestLevel: loggerConfig.lowestLevel,
67
+ parentSinks: loggerConfig.parentSinks
68
+ });
69
+ }
70
+ if (config.reset) logTapeConfig.reset = true;
71
+ await configure(logTapeConfig);
72
+ if (warnings.length > 0) {
73
+ const metaLogger = getLogger(["logtape", "meta"]);
74
+ for (const warning of warnings) metaLogger.warn(warning);
75
+ }
76
+ }
77
+
78
+ //#endregion
79
+ export { configureFromObject };
80
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","names":["config: LogTapeConfig","options?: ConfigureOptions","warnings: string[]","sinks: Record<string, Sink>","filters: Record<string, Filter>","logTapeConfig: Config<string, string>","validSinks: string[]","validFilters: string[]"],"sources":["../src/config.ts"],"sourcesContent":["import { configure, getLogger } from \"@logtape/logtape\";\nimport type { Config, Filter, Sink } from \"@logtape/logtape\";\nimport { createFilter, createSink } from \"./loader.ts\";\nimport { DEFAULT_SHORTHANDS, mergeShorthands } from \"./shorthands.ts\";\nimport { ConfigError } from \"./types.ts\";\nimport type { ConfigureOptions, LogTapeConfig } from \"./types.ts\";\n\n/**\n * Configures LogTape from a plain object.\n *\n * @param config Configuration object (typically loaded from JSON/YAML/TOML)\n * @param options Configuration options\n * @throws {ConfigError} If configuration is invalid and onInvalidConfig is \"throw\"\n *\n * @example\n * ```typescript\n * import { configureFromObject } from \"@logtape/config\";\n * import { readFile } from \"fs/promises\";\n *\n * const config = JSON.parse(await readFile(\"./logtape.json\", \"utf-8\"));\n * await configureFromObject(config);\n * ```\n * @since 1.4.0\n */\nexport async function configureFromObject(\n config: LogTapeConfig,\n options?: ConfigureOptions,\n): Promise<void> {\n const shorthands = mergeShorthands(\n DEFAULT_SHORTHANDS,\n options?.shorthands,\n );\n const onInvalidConfig = options?.onInvalidConfig ?? \"throw\";\n const warnings: string[] = [];\n\n // 1. Create sinks\n const sinks: Record<string, Sink> = {};\n if (config.sinks) {\n for (const [name, sinkConfig] of Object.entries(config.sinks)) {\n try {\n sinks[name] = await createSink(sinkConfig, shorthands);\n } catch (e) {\n if (onInvalidConfig === \"throw\") {\n throw e;\n }\n warnings.push(`Failed to create sink '${name}': ${e}`);\n }\n }\n }\n\n // 2. Create filters\n const filters: Record<string, Filter> = {};\n if (config.filters) {\n for (const [name, filterConfig] of Object.entries(config.filters)) {\n try {\n filters[name] = await createFilter(filterConfig, shorthands);\n } catch (e) {\n if (onInvalidConfig === \"throw\") {\n throw e;\n }\n warnings.push(`Failed to create filter '${name}': ${e}`);\n }\n }\n }\n\n // 3. Configure logtape\n const logTapeConfig: Config<string, string> = {\n sinks,\n filters,\n loggers: [],\n };\n\n if (config.loggers) {\n for (const loggerConfig of config.loggers) {\n // Validate sink references\n const validSinks: string[] = [];\n if (loggerConfig.sinks) {\n for (const sinkName of loggerConfig.sinks) {\n if (sinkName in sinks) {\n validSinks.push(sinkName);\n } else {\n const msg = `Logger '${\n Array.isArray(loggerConfig.category)\n ? loggerConfig.category.join(\".\")\n : loggerConfig.category\n }' references unknown or failed sink '${sinkName}'`;\n if (onInvalidConfig === \"throw\") {\n throw new ConfigError(msg);\n }\n warnings.push(msg);\n }\n }\n }\n\n // Validate filter references\n const validFilters: string[] = [];\n if (loggerConfig.filters) {\n for (const filterName of loggerConfig.filters) {\n if (filterName in filters) {\n validFilters.push(filterName);\n } else {\n const msg = `Logger '${\n Array.isArray(loggerConfig.category)\n ? loggerConfig.category.join(\".\")\n : loggerConfig.category\n }' references unknown or failed filter '${filterName}'`;\n if (onInvalidConfig === \"throw\") {\n throw new ConfigError(msg);\n }\n warnings.push(msg);\n }\n }\n }\n\n logTapeConfig.loggers.push({\n category: loggerConfig.category,\n sinks: validSinks.length > 0 ? validSinks : undefined,\n filters: validFilters.length > 0 ? validFilters : undefined,\n lowestLevel: loggerConfig.lowestLevel,\n parentSinks: loggerConfig.parentSinks,\n });\n }\n }\n\n if (config.reset) {\n logTapeConfig.reset = true;\n }\n\n await configure(logTapeConfig);\n\n // 4. Log warnings to meta logger\n if (warnings.length > 0) {\n const metaLogger = getLogger([\"logtape\", \"meta\"]);\n for (const warning of warnings) {\n metaLogger.warn(warning);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwBA,eAAsB,oBACpBA,QACAC,SACe;CACf,MAAM,aAAa,gBACjB,oBACA,SAAS,WACV;CACD,MAAM,kBAAkB,SAAS,mBAAmB;CACpD,MAAMC,WAAqB,CAAE;CAG7B,MAAMC,QAA8B,CAAE;AACtC,KAAI,OAAO,MACT,MAAK,MAAM,CAAC,MAAM,WAAW,IAAI,OAAO,QAAQ,OAAO,MAAM,CAC3D,KAAI;AACF,QAAM,QAAQ,MAAM,WAAW,YAAY,WAAW;CACvD,SAAQ,GAAG;AACV,MAAI,oBAAoB,QACtB,OAAM;AAER,WAAS,MAAM,yBAAyB,KAAK,KAAK,EAAE,EAAE;CACvD;CAKL,MAAMC,UAAkC,CAAE;AAC1C,KAAI,OAAO,QACT,MAAK,MAAM,CAAC,MAAM,aAAa,IAAI,OAAO,QAAQ,OAAO,QAAQ,CAC/D,KAAI;AACF,UAAQ,QAAQ,MAAM,aAAa,cAAc,WAAW;CAC7D,SAAQ,GAAG;AACV,MAAI,oBAAoB,QACtB,OAAM;AAER,WAAS,MAAM,2BAA2B,KAAK,KAAK,EAAE,EAAE;CACzD;CAKL,MAAMC,gBAAwC;EAC5C;EACA;EACA,SAAS,CAAE;CACZ;AAED,KAAI,OAAO,QACT,MAAK,MAAM,gBAAgB,OAAO,SAAS;EAEzC,MAAMC,aAAuB,CAAE;AAC/B,MAAI,aAAa,MACf,MAAK,MAAM,YAAY,aAAa,MAClC,KAAI,YAAY,MACd,YAAW,KAAK,SAAS;OACpB;GACL,MAAM,OAAO,UACX,MAAM,QAAQ,aAAa,SAAS,GAChC,aAAa,SAAS,KAAK,IAAI,GAC/B,aAAa,SAClB,uCAAuC,SAAS;AACjD,OAAI,oBAAoB,QACtB,OAAM,IAAI,YAAY;AAExB,YAAS,KAAK,IAAI;EACnB;EAKL,MAAMC,eAAyB,CAAE;AACjC,MAAI,aAAa,QACf,MAAK,MAAM,cAAc,aAAa,QACpC,KAAI,cAAc,QAChB,cAAa,KAAK,WAAW;OACxB;GACL,MAAM,OAAO,UACX,MAAM,QAAQ,aAAa,SAAS,GAChC,aAAa,SAAS,KAAK,IAAI,GAC/B,aAAa,SAClB,yCAAyC,WAAW;AACrD,OAAI,oBAAoB,QACtB,OAAM,IAAI,YAAY;AAExB,YAAS,KAAK,IAAI;EACnB;AAIL,gBAAc,QAAQ,KAAK;GACzB,UAAU,aAAa;GACvB,OAAO,WAAW,SAAS,IAAI;GAC/B,SAAS,aAAa,SAAS,IAAI;GACnC,aAAa,aAAa;GAC1B,aAAa,aAAa;EAC3B,EAAC;CACH;AAGH,KAAI,OAAO,MACT,eAAc,QAAQ;AAGxB,OAAM,UAAU,cAAc;AAG9B,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,aAAa,UAAU,CAAC,WAAW,MAAO,EAAC;AACjD,OAAK,MAAM,WAAW,SACpB,YAAW,KAAK,QAAQ;CAE3B;AACF"}
package/dist/env.cjs ADDED
@@ -0,0 +1,35 @@
1
+
2
+ //#region src/env.ts
3
+ /**
4
+ * Expands environment variables in a configuration object.
5
+ *
6
+ * @param config Configuration object
7
+ * @param options Expansion options
8
+ * @returns Configuration with expanded environment variables
9
+ * @since 1.4.0
10
+ */
11
+ function expandEnvVars(config, options) {
12
+ const pattern = options?.pattern ?? /\$\{([^}:]+)(?::([^}]+))?\}/g;
13
+ function replace(value) {
14
+ return value.replace(pattern, (_, key, defaultValue) => {
15
+ let val;
16
+ if (typeof globalThis.process?.env === "object") val = globalThis.process.env[key];
17
+ else if (typeof Deno !== "undefined") val = Deno.env.get(key);
18
+ return val ?? defaultValue ?? "";
19
+ });
20
+ }
21
+ function walk(obj) {
22
+ if (typeof obj === "string") return replace(obj);
23
+ if (Array.isArray(obj)) return obj.map(walk);
24
+ if (obj !== null && typeof obj === "object") {
25
+ const result = {};
26
+ for (const [key, value] of Object.entries(obj)) result[key] = walk(value);
27
+ return result;
28
+ }
29
+ return obj;
30
+ }
31
+ return walk(config);
32
+ }
33
+
34
+ //#endregion
35
+ exports.expandEnvVars = expandEnvVars;
package/dist/env.d.cts ADDED
@@ -0,0 +1,17 @@
1
+ import { EnvExpansionOptions } from "./types.cjs";
2
+
3
+ //#region src/env.d.ts
4
+
5
+ /**
6
+ * Expands environment variables in a configuration object.
7
+ *
8
+ * @param config Configuration object
9
+ * @param options Expansion options
10
+ * @returns Configuration with expanded environment variables
11
+ * @since 1.4.0
12
+ */
13
+ declare function expandEnvVars<T extends object>(config: T, options?: EnvExpansionOptions): T;
14
+ //# sourceMappingURL=env.d.ts.map
15
+ //#endregion
16
+ export { expandEnvVars };
17
+ //# sourceMappingURL=env.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.cts","names":[],"sources":["../src/env.ts"],"sourcesContent":[],"mappings":";;;;;;AAUA;;;;;AAGI;iBAHY,wCACN,aACE,sBACT"}
package/dist/env.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { EnvExpansionOptions } from "./types.js";
2
+
3
+ //#region src/env.d.ts
4
+
5
+ /**
6
+ * Expands environment variables in a configuration object.
7
+ *
8
+ * @param config Configuration object
9
+ * @param options Expansion options
10
+ * @returns Configuration with expanded environment variables
11
+ * @since 1.4.0
12
+ */
13
+ declare function expandEnvVars<T extends object>(config: T, options?: EnvExpansionOptions): T;
14
+ //# sourceMappingURL=env.d.ts.map
15
+ //#endregion
16
+ export { expandEnvVars };
17
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","names":[],"sources":["../src/env.ts"],"sourcesContent":[],"mappings":";;;;;;AAUA;;;;;AAGI;iBAHY,wCACN,aACE,sBACT"}
package/dist/env.js ADDED
@@ -0,0 +1,35 @@
1
+ //#region src/env.ts
2
+ /**
3
+ * Expands environment variables in a configuration object.
4
+ *
5
+ * @param config Configuration object
6
+ * @param options Expansion options
7
+ * @returns Configuration with expanded environment variables
8
+ * @since 1.4.0
9
+ */
10
+ function expandEnvVars(config, options) {
11
+ const pattern = options?.pattern ?? /\$\{([^}:]+)(?::([^}]+))?\}/g;
12
+ function replace(value) {
13
+ return value.replace(pattern, (_, key, defaultValue) => {
14
+ let val;
15
+ if (typeof globalThis.process?.env === "object") val = globalThis.process.env[key];
16
+ else if (typeof Deno !== "undefined") val = Deno.env.get(key);
17
+ return val ?? defaultValue ?? "";
18
+ });
19
+ }
20
+ function walk(obj) {
21
+ if (typeof obj === "string") return replace(obj);
22
+ if (Array.isArray(obj)) return obj.map(walk);
23
+ if (obj !== null && typeof obj === "object") {
24
+ const result = {};
25
+ for (const [key, value] of Object.entries(obj)) result[key] = walk(value);
26
+ return result;
27
+ }
28
+ return obj;
29
+ }
30
+ return walk(config);
31
+ }
32
+
33
+ //#endregion
34
+ export { expandEnvVars };
35
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","names":["config: T","options?: EnvExpansionOptions","value: string","val: string | undefined","obj: unknown","result: Record<string, unknown>"],"sources":["../src/env.ts"],"sourcesContent":["import type { EnvExpansionOptions } from \"./types.ts\";\n\n/**\n * Expands environment variables in a configuration object.\n *\n * @param config Configuration object\n * @param options Expansion options\n * @returns Configuration with expanded environment variables\n * @since 1.4.0\n */\nexport function expandEnvVars<T extends object>(\n config: T,\n options?: EnvExpansionOptions,\n): T {\n const pattern = options?.pattern ?? /\\$\\{([^}:]+)(?::([^}]+))?\\}/g;\n\n function replace(value: string): string {\n return value.replace(pattern, (_, key, defaultValue) => {\n let val: string | undefined;\n // deno-lint-ignore no-explicit-any\n if (typeof (globalThis as any).process?.env === \"object\") {\n // Node.js / Bun\n // deno-lint-ignore no-explicit-any\n val = (globalThis as any).process.env[key];\n } else if (typeof Deno !== \"undefined\") {\n // Deno\n val = Deno.env.get(key);\n }\n\n return val ?? defaultValue ?? \"\";\n });\n }\n\n function walk(obj: unknown): unknown {\n if (typeof obj === \"string\") {\n return replace(obj);\n }\n if (Array.isArray(obj)) {\n return obj.map(walk);\n }\n if (obj !== null && typeof obj === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = walk(value);\n }\n return result;\n }\n return obj;\n }\n\n return walk(config) as T;\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,cACdA,QACAC,SACG;CACH,MAAM,UAAU,SAAS,WAAW;CAEpC,SAAS,QAAQC,OAAuB;AACtC,SAAO,MAAM,QAAQ,SAAS,CAAC,GAAG,KAAK,iBAAiB;GACtD,IAAIC;AAEJ,cAAY,WAAmB,SAAS,QAAQ,SAG9C,OAAO,WAAmB,QAAQ,IAAI;mBACtB,SAAS,YAEzB,OAAM,KAAK,IAAI,IAAI,IAAI;AAGzB,UAAO,OAAO,gBAAgB;EAC/B,EAAC;CACH;CAED,SAAS,KAAKC,KAAuB;AACnC,aAAW,QAAQ,SACjB,QAAO,QAAQ,IAAI;AAErB,MAAI,MAAM,QAAQ,IAAI,CACpB,QAAO,IAAI,IAAI,KAAK;AAEtB,MAAI,QAAQ,eAAe,QAAQ,UAAU;GAC3C,MAAMC,SAAkC,CAAE;AAC1C,QAAK,MAAM,CAAC,KAAK,MAAM,IAAI,OAAO,QAAQ,IAAI,CAC5C,QAAO,OAAO,KAAK,MAAM;AAE3B,UAAO;EACR;AACD,SAAO;CACR;AAED,QAAO,KAAK,OAAO;AACpB"}
@@ -0,0 +1,94 @@
1
+ const require_parser = require('./parser.cjs');
2
+ const require_types = require('./types.cjs');
3
+
4
+ //#region src/loader.ts
5
+ /**
6
+ * Loads a module and extracts the specified export.
7
+ *
8
+ * @param parsed Parsed module reference
9
+ * @param shorthands Shorthand registry for resolving shorthands
10
+ * @param type Type of shorthand (sinks, filters, formatters)
11
+ * @returns The loaded module export
12
+ * @since 1.4.0
13
+ */
14
+ async function loadModuleExport(parsed, shorthands, type) {
15
+ if (parsed.isShorthand) {
16
+ const registry = shorthands[type];
17
+ const resolved = registry ? registry[parsed.shorthandName] : void 0;
18
+ if (!resolved) throw new require_types.ConfigError(`Unknown ${type.slice(0, -1)} shorthand: #${parsed.shorthandName}`);
19
+ const resolvedParsed = require_parser.parseModuleReference(resolved);
20
+ return loadModuleExport(resolvedParsed, shorthands, type);
21
+ }
22
+ if (!parsed.modulePath) throw new require_types.ConfigError("Module path is missing");
23
+ let mod;
24
+ try {
25
+ mod = await import(parsed.modulePath);
26
+ } catch (e) {
27
+ throw new require_types.ConfigError(`Failed to load module ${parsed.modulePath}: ${e}`);
28
+ }
29
+ const exportName = parsed.exportName ?? "default";
30
+ const exported = mod[exportName];
31
+ if (exported === void 0) throw new require_types.ConfigError(`Module ${parsed.modulePath} does not have export '${exportName}'`);
32
+ return exported;
33
+ }
34
+ /**
35
+ * Creates a sink from configuration.
36
+ *
37
+ * @param config Sink configuration
38
+ * @param shorthands Shorthand registry
39
+ * @returns The created sink
40
+ * @since 1.4.0
41
+ */
42
+ async function createSink(config, shorthands) {
43
+ const parsed = require_parser.parseModuleReference(config.type);
44
+ const factory = await loadModuleExport(parsed, shorthands, "sinks");
45
+ let sink;
46
+ if (parsed.isFactory) {
47
+ if (typeof factory !== "function") throw new require_types.ConfigError(`Export ${parsed.exportName} in ${parsed.modulePath} is not a function, but invoked as factory`);
48
+ const options = { ...config };
49
+ delete options.type;
50
+ if (options.formatter) if (typeof options.formatter === "string") {
51
+ const fmtParsed = require_parser.parseModuleReference(options.formatter);
52
+ const fmtFactory = await loadModuleExport(fmtParsed, shorthands, "formatters");
53
+ if (fmtParsed.isFactory) {
54
+ if (typeof fmtFactory !== "function") throw new require_types.ConfigError(`Formatter ${options.formatter} is not a function`);
55
+ options.formatter = fmtFactory({});
56
+ } else options.formatter = fmtFactory;
57
+ } else {
58
+ const fmtConfig = options.formatter;
59
+ const fmtParsed = require_parser.parseModuleReference(fmtConfig.type);
60
+ const fmtFactory = await loadModuleExport(fmtParsed, shorthands, "formatters");
61
+ if (fmtParsed.isFactory) {
62
+ if (typeof fmtFactory !== "function") throw new require_types.ConfigError(`Formatter ${fmtConfig.type} is not a function`);
63
+ const fmtOptions = { ...fmtConfig };
64
+ delete fmtOptions.type;
65
+ options.formatter = fmtFactory(fmtOptions);
66
+ } else options.formatter = fmtFactory;
67
+ }
68
+ sink = factory(options);
69
+ } else sink = factory;
70
+ return sink;
71
+ }
72
+ /**
73
+ * Creates a filter from configuration.
74
+ *
75
+ * @param config Filter configuration
76
+ * @param shorthands Shorthand registry
77
+ * @returns The created filter
78
+ * @since 1.4.0
79
+ */
80
+ async function createFilter(config, shorthands) {
81
+ const parsed = require_parser.parseModuleReference(config.type);
82
+ const factory = await loadModuleExport(parsed, shorthands, "filters");
83
+ if (parsed.isFactory) {
84
+ if (typeof factory !== "function") throw new require_types.ConfigError(`Export ${parsed.exportName} in ${parsed.modulePath} is not a function, but invoked as factory`);
85
+ const options = { ...config };
86
+ delete options.type;
87
+ return factory(options);
88
+ }
89
+ return factory;
90
+ }
91
+
92
+ //#endregion
93
+ exports.createFilter = createFilter;
94
+ exports.createSink = createSink;
package/dist/loader.js ADDED
@@ -0,0 +1,94 @@
1
+ import { parseModuleReference } from "./parser.js";
2
+ import { ConfigError } from "./types.js";
3
+
4
+ //#region src/loader.ts
5
+ /**
6
+ * Loads a module and extracts the specified export.
7
+ *
8
+ * @param parsed Parsed module reference
9
+ * @param shorthands Shorthand registry for resolving shorthands
10
+ * @param type Type of shorthand (sinks, filters, formatters)
11
+ * @returns The loaded module export
12
+ * @since 1.4.0
13
+ */
14
+ async function loadModuleExport(parsed, shorthands, type) {
15
+ if (parsed.isShorthand) {
16
+ const registry = shorthands[type];
17
+ const resolved = registry ? registry[parsed.shorthandName] : void 0;
18
+ if (!resolved) throw new ConfigError(`Unknown ${type.slice(0, -1)} shorthand: #${parsed.shorthandName}`);
19
+ const resolvedParsed = parseModuleReference(resolved);
20
+ return loadModuleExport(resolvedParsed, shorthands, type);
21
+ }
22
+ if (!parsed.modulePath) throw new ConfigError("Module path is missing");
23
+ let mod;
24
+ try {
25
+ mod = await import(parsed.modulePath);
26
+ } catch (e) {
27
+ throw new ConfigError(`Failed to load module ${parsed.modulePath}: ${e}`);
28
+ }
29
+ const exportName = parsed.exportName ?? "default";
30
+ const exported = mod[exportName];
31
+ if (exported === void 0) throw new ConfigError(`Module ${parsed.modulePath} does not have export '${exportName}'`);
32
+ return exported;
33
+ }
34
+ /**
35
+ * Creates a sink from configuration.
36
+ *
37
+ * @param config Sink configuration
38
+ * @param shorthands Shorthand registry
39
+ * @returns The created sink
40
+ * @since 1.4.0
41
+ */
42
+ async function createSink(config, shorthands) {
43
+ const parsed = parseModuleReference(config.type);
44
+ const factory = await loadModuleExport(parsed, shorthands, "sinks");
45
+ let sink;
46
+ if (parsed.isFactory) {
47
+ if (typeof factory !== "function") throw new ConfigError(`Export ${parsed.exportName} in ${parsed.modulePath} is not a function, but invoked as factory`);
48
+ const options = { ...config };
49
+ delete options.type;
50
+ if (options.formatter) if (typeof options.formatter === "string") {
51
+ const fmtParsed = parseModuleReference(options.formatter);
52
+ const fmtFactory = await loadModuleExport(fmtParsed, shorthands, "formatters");
53
+ if (fmtParsed.isFactory) {
54
+ if (typeof fmtFactory !== "function") throw new ConfigError(`Formatter ${options.formatter} is not a function`);
55
+ options.formatter = fmtFactory({});
56
+ } else options.formatter = fmtFactory;
57
+ } else {
58
+ const fmtConfig = options.formatter;
59
+ const fmtParsed = parseModuleReference(fmtConfig.type);
60
+ const fmtFactory = await loadModuleExport(fmtParsed, shorthands, "formatters");
61
+ if (fmtParsed.isFactory) {
62
+ if (typeof fmtFactory !== "function") throw new ConfigError(`Formatter ${fmtConfig.type} is not a function`);
63
+ const fmtOptions = { ...fmtConfig };
64
+ delete fmtOptions.type;
65
+ options.formatter = fmtFactory(fmtOptions);
66
+ } else options.formatter = fmtFactory;
67
+ }
68
+ sink = factory(options);
69
+ } else sink = factory;
70
+ return sink;
71
+ }
72
+ /**
73
+ * Creates a filter from configuration.
74
+ *
75
+ * @param config Filter configuration
76
+ * @param shorthands Shorthand registry
77
+ * @returns The created filter
78
+ * @since 1.4.0
79
+ */
80
+ async function createFilter(config, shorthands) {
81
+ const parsed = parseModuleReference(config.type);
82
+ const factory = await loadModuleExport(parsed, shorthands, "filters");
83
+ if (parsed.isFactory) {
84
+ if (typeof factory !== "function") throw new ConfigError(`Export ${parsed.exportName} in ${parsed.modulePath} is not a function, but invoked as factory`);
85
+ const options = { ...config };
86
+ delete options.type;
87
+ return factory(options);
88
+ }
89
+ return factory;
90
+ }
91
+
92
+ //#endregion
93
+ export { createFilter, createSink };
94
+ //# sourceMappingURL=loader.js.map