arkenv 0.7.3 → 0.7.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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  </a>
5
5
  <br />
6
6
  <a href="https://github.com/yamcodes/arkenv/actions/workflows/tests.yml?query=branch%3Amain"><img alt="Tests Status" src="https://github.com/yamcodes/arkenv/actions/workflows/tests.yml/badge.svg?event=push&branch=main"></a>
7
- <img alt="npm bundle size" src="https://img.shields.io/bundlephobia/minzip/arkenv">
7
+ <a href="https://bundlephobia.com/package/arkenv"><img alt="npm bundle size" src="https://img.shields.io/bundlephobia/minzip/arkenv"></a>
8
8
  <a href="https://www.typescriptlang.org/"><img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-3178C6?style=flat&logo=typescript&logoColor=white"></a>
9
9
  <a href="https://arktype.io/"><img alt="Powered By ArkType" src="https://custom-icon-badges.demolab.com/badge/ArkType-0d1526?logo=arktype2&logoColor=e9eef9"></a>
10
10
  <a href="https://nodejs.org/en"><img alt="Node.js" src="https://img.shields.io/badge/Node.js-339933?style=flat&logo=node.js&logoColor=white"></a>
@@ -110,7 +110,7 @@ bun add arkenv arktype
110
110
  ## Requirements
111
111
 
112
112
  - TypeScript >= 5.1 and [anything else required by ArkType](https://arktype.io/docs/intro/setup#installation)
113
- - Tested on [Node.js 22 LTS](https://github.com/yamcodes/arkenv/tree/main/examples/basic), [Bun 1.2](https://github.com/yamcodes/arkenv/tree/main/examples/with-bun), and [Vite from **2.9.18** to **7.x**](https://github.com/yamcodes/arkenv/tree/main/examples/with-vite-react-ts). Older versions may work but are not officially supported
113
+ - Tested on [Node.js **LTS** and **Current**](https://github.com/yamcodes/arkenv/tree/main/examples/basic), [Bun 1.2](https://github.com/yamcodes/arkenv/tree/main/examples/with-bun), and [Vite from **2.9.18** to **7.x**](https://github.com/yamcodes/arkenv/tree/main/examples/with-vite-react-ts). Older versions may work but are not officially supported
114
114
 
115
115
  ## Plugins
116
116
 
package/dist/index.cjs CHANGED
@@ -1,137 +1,4 @@
1
- Object.defineProperty(exports, '__esModule', { value: true });
2
- //#region rolldown:runtime
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
-
24
- //#endregion
25
- let arktype = require("arktype");
26
- arktype = __toESM(arktype);
27
- let node_util = require("node:util");
28
- node_util = __toESM(node_util);
29
-
30
- //#region src/utils.ts
31
- /**
32
- * Indent a string by a given amount
33
- * @param str - The string to indent
34
- * @param amt - The amount to indent by, defaults to 2
35
- * @param options - {@link IndentOptions}
36
- * @returns The indented string
37
- */
38
- const indent = (str, amt = 2, { dontDetectNewlines = false } = {}) => {
39
- if (!dontDetectNewlines) return str.split("\n").map((line) => `${" ".repeat(amt)}${line}`).join("\n");
40
- return `${" ".repeat(amt)}${str}`;
41
- };
42
-
43
- //#endregion
44
- //#region src/errors.ts
45
- /**
46
- * Format the errors returned by ArkType to be more readable
47
- * @param errors - The errors returned by ArkType
48
- * @returns A string of the formatted errors
49
- */
50
- const formatErrors = (errors) => Object.entries(errors.byPath).map(([path, error]) => {
51
- const messageWithoutPath = error.message.startsWith(path) ? error.message.slice(path.length) : error.message;
52
- const valueMatch = messageWithoutPath.match(/\(was "([^"]+)"\)/);
53
- const formattedMessage = valueMatch ? messageWithoutPath.replace(`(was "${valueMatch[1]}")`, `(was ${(0, node_util.styleText)("cyan", `"${valueMatch[1]}"`)})`) : messageWithoutPath;
54
- return `${(0, node_util.styleText)("yellow", path)}${formattedMessage}`;
55
- }).join("\n");
56
- var ArkEnvError = class extends Error {
57
- constructor(errors, message = "Errors found while validating environment variables") {
58
- super(`${(0, node_util.styleText)("red", message)}\n${indent(formatErrors(errors))}\n`);
59
- this.name = "ArkEnvError";
60
- }
61
- };
62
-
63
- //#endregion
64
- //#region src/types.ts
65
- /**
66
- * A `string` that can be parsed into a number between 0 and 65535
67
- */
68
- const port = (0, arktype.type)("string", "=>", (data, ctx) => {
69
- const asNumber = Number.parseInt(data, 10);
70
- if (!Number.isInteger(asNumber) || !(0 <= asNumber && asNumber <= 65535)) ctx.mustBe("an integer between 0 and 65535");
71
- return asNumber;
72
- });
73
- /**
74
- * An IP address or `"localhost"`
75
- */
76
- const host = (0, arktype.type)("string.ip | 'localhost'");
77
- /**
78
- * A boolean that accepts string values and converts them to boolean
79
- * Accepts "true" or "false" strings and converts them to actual boolean values
80
- */
81
- const boolean = (0, arktype.type)("'true' | 'false' | true | false", "=>", (str) => str === "true" || str === true);
82
-
83
- //#endregion
84
- //#region src/scope.ts
85
- /**
86
- * The root scope for the ArkEnv library, containing extensions to the ArkType scopes with ArkEnv-specific types like `string.host` and `number.port`.
87
- */
88
- const $ = (0, arktype.scope)({
89
- string: arktype.type.module({
90
- ...arktype.type.keywords.string,
91
- host
92
- }),
93
- number: arktype.type.module({
94
- ...arktype.type.keywords.number,
95
- port
96
- }),
97
- boolean
98
- });
99
-
100
- //#endregion
101
- //#region src/create-env.ts
102
- /**
103
- * TODO: If possible, find a better type than "const T extends Record<string, unknown>",
104
- * and be as close as possible to the type accepted by ArkType's `type`.
105
- */
106
- /**
107
- * Create an environment variables object from a schema and an environment
108
- * @param def - The environment variable schema
109
- * @param env - The environment variables to validate, defaults to `process.env`
110
- * @returns The validated environment variable schema
111
- * @throws An {@link ArkEnvError | error} if the environment variables are invalid.
112
- */
113
- function createEnv(def, env = process.env) {
114
- const validatedEnv = $.type.raw(def)(env);
115
- if (validatedEnv instanceof arktype.type.errors) throw new ArkEnvError(validatedEnv);
116
- return validatedEnv;
117
- }
118
-
119
- //#endregion
120
- //#region src/type.ts
121
- const type = $.type;
122
-
123
- //#endregion
124
- //#region src/index.ts
125
- /**
126
- * `arkenv`'s main export, an alias for {@link createEnv}
127
- *
128
- * {@link https://arkenv.js.org | ArkEnv} is a typesafe environment variables parser powered by {@link https://arktype.io | ArkType}, TypeScript's 1:1 validator.
129
- */
130
- const arkenv = createEnv;
131
- var src_default = arkenv;
132
-
133
- //#endregion
134
- exports.ArkEnvError = ArkEnvError;
135
- exports.createEnv = createEnv;
136
- exports.default = src_default;
137
- exports.type = type;
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`arktype`);c=s(c);const l={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`},u=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null,d=()=>!!(!u()||process.env.NO_COLOR!==void 0||process.env.CI!==void 0||process.stdout&&!process.stdout.isTTY),f=(e,t)=>u()&&!d()?`${l[e]}${t}${l.reset}`:t,p=(e,t=2,{dontDetectNewlines:n=!1}={})=>n?`${` `.repeat(t)}${e}`:e.split(`
2
+ `).map(e=>`${` `.repeat(t)}${e}`).join(`
3
+ `),m=e=>Object.entries(e.byPath).map(([e,t])=>{let n=t.message.startsWith(e)?t.message.slice(e.length):t.message,r=n.match(/\(was "([^"]+)"\)/),i=r?n.replace(`(was "${r[1]}")`,`(was ${f(`cyan`,`"${r[1]}"`)})`):n;return`${f(`yellow`,e)}${i}`}).join(`
4
+ `);var h=class extends Error{constructor(e,t=`Errors found while validating environment variables`){super(`${f(`red`,t)}\n${p(m(e))}\n`),this.name=`ArkEnvError`}};const g=(0,c.type)(`string`,`=>`,(e,t)=>{let n=Number.parseInt(e,10);return(!Number.isInteger(n)||!(0<=n&&n<=65535))&&t.mustBe(`an integer between 0 and 65535`),n}),_=(0,c.type)(`string.ip | 'localhost'`),v=(0,c.type)(`'true' | 'false' | true | false`,`=>`,e=>e===`true`||e===!0),y=(0,c.scope)({string:c.type.module({...c.type.keywords.string,host:_}),number:c.type.module({...c.type.keywords.number,port:g}),boolean:v});function b(e,t=process.env){let n=y.type.raw(e)(t);if(n instanceof c.type.errors)throw new h(n);return n}const x=y.type,S=b;var C=S;exports.ArkEnvError=h,exports.createEnv=b,exports.default=C,exports.type=x;
package/dist/index.d.cts CHANGED
@@ -184,4 +184,5 @@ declare class ArkEnvError extends Error {
184
184
  */
185
185
  declare const arkenv: typeof createEnv;
186
186
  //#endregion
187
- export { ArkEnvError, type EnvSchema, createEnv, arkenv as default, type };
187
+ export { ArkEnvError, type EnvSchema, createEnv, arkenv as default, type };
188
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/scope.ts","../src/create-env.ts","../src/type.ts","../src/errors.ts","../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;cAQa,aAAC;;;;IAUZ,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;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IAAjB,QAAQ,EAAA,MAAA;IAAG,IAAA,EAAA,MAAA;;;;ICrBD,IAAa,EAAA,MAAA;;;;;;;;AFMb,cGqBA,WAAA,SAAoB,KAAA,CHX/B;sBGaQ;;;;;;;;;AHvBV,cICM,MJSJ,EAAA,OITU,SJSV"}
package/dist/index.d.ts CHANGED
@@ -184,4 +184,5 @@ declare class ArkEnvError extends Error {
184
184
  */
185
185
  declare const arkenv: typeof createEnv;
186
186
  //#endregion
187
- export { ArkEnvError, type EnvSchema, createEnv, arkenv as default, type };
187
+ export { ArkEnvError, type EnvSchema, createEnv, arkenv as default, type };
188
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/scope.ts","../src/create-env.ts","../src/type.ts","../src/errors.ts","../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;cAQa,aAAC;;;;IAUZ,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAVY,qBAAA,yDAAA;MAAA,cAAA,EAAA,MAAA;;;;ICJT,KAAA,qBAAqB,CAAM;MAEpB,IAAS,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,qCAAA,CAAA,MAAA,CAAA;MAAsB,YAAA,EAAA,MAAA;IAAa,CAAA,GAAA;MAAtB,cAAA,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,qCAAA,CAAA,MAAA,CAAA;IAAQ,CAAA,CAAA;IAc1B,GAAA,qBAAS,+CAAA;MAAiB,cAAA,EAAA,MAAA;IAC1B,CAAA,CAAA;IAAV,IAAA,qBAAA,gDAAA;MACA,cAAA,EAAA,MAAA;IACoB,CAAA,CAAA;IAAW,cAAA,EAAA,MAAA;IAAjB,IAAA,EAAA,MAAA;EAAjB,CAAA,CAAA;EAAW,MAAA,qBAAA,CAAA;;;;ICrBD,OAAa,EAAA,MAAA;;;;;;;;;;;KDErB,kBAAA,GAAqB;KAEd,iBAAiB,MAAA,CAAK,SAAS,aAAa;;;;ADExD;;;;;;;;iBCYgB,0BAA0B,8BACpC,UAAU,UACV,qBACH,OAAA,CAAQ,IAAI,MAAA,CAAK,MAAM,WAAW;;;cCrBxB,gCAAI;;;;;;;IFgBf,CAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAVY,EAAA,MAAA;IAAA,MAAA,EAAA,MAAA;;;;ICJT,CAAA,GAAA;MAEO,cAAS,EAAA,CAAA,EAAA,EAAA,MAAA,EAAA,qCAAA,CAAA,MAAA,CAAA;IAAsB,CAAA,CAAA;IAAa,GAAA,qBAAA,+CAAA;MAAtB,cAAA,EAAA,MAAA;IAAQ,CAAA,CAAA;IAc1B,IAAA,qBAAS,gDAAA;MAAiB,cAAA,EAAA,MAAA;IAC1B,CAAA,CAAA;IAAV,cAAA,EAAA,MAAA;IACA,IAAA,EAAA,MAAA;EACoB,CAAA,CAAA;EAAW,MAAA,qBAAA,CAAA;IAAjB,GAAA,EAAA,MAAA;IAAjB,QAAQ,EAAA,MAAA;IAAG,IAAA,EAAA,MAAA;;;;ICrBD,IAAa,EAAA,MAAA;;;;;;;;AFMb,cGqBA,WAAA,SAAoB,KAAA,CHX/B;sBGaQ;;;;;;;;;AHvBV,cICM,MJSJ,EAAA,OITU,SJSV"}
package/dist/index.js CHANGED
@@ -1,108 +1,5 @@
1
- import { scope, type as type$1 } from "arktype";
2
- import { styleText } from "node:util";
3
-
4
- //#region src/utils.ts
5
- /**
6
- * Indent a string by a given amount
7
- * @param str - The string to indent
8
- * @param amt - The amount to indent by, defaults to 2
9
- * @param options - {@link IndentOptions}
10
- * @returns The indented string
11
- */
12
- const indent = (str, amt = 2, { dontDetectNewlines = false } = {}) => {
13
- if (!dontDetectNewlines) return str.split("\n").map((line) => `${" ".repeat(amt)}${line}`).join("\n");
14
- return `${" ".repeat(amt)}${str}`;
15
- };
16
-
17
- //#endregion
18
- //#region src/errors.ts
19
- /**
20
- * Format the errors returned by ArkType to be more readable
21
- * @param errors - The errors returned by ArkType
22
- * @returns A string of the formatted errors
23
- */
24
- const formatErrors = (errors) => Object.entries(errors.byPath).map(([path, error]) => {
25
- const messageWithoutPath = error.message.startsWith(path) ? error.message.slice(path.length) : error.message;
26
- const valueMatch = messageWithoutPath.match(/\(was "([^"]+)"\)/);
27
- const formattedMessage = valueMatch ? messageWithoutPath.replace(`(was "${valueMatch[1]}")`, `(was ${styleText("cyan", `"${valueMatch[1]}"`)})`) : messageWithoutPath;
28
- return `${styleText("yellow", path)}${formattedMessage}`;
29
- }).join("\n");
30
- var ArkEnvError = class extends Error {
31
- constructor(errors, message = "Errors found while validating environment variables") {
32
- super(`${styleText("red", message)}\n${indent(formatErrors(errors))}\n`);
33
- this.name = "ArkEnvError";
34
- }
35
- };
36
-
37
- //#endregion
38
- //#region src/types.ts
39
- /**
40
- * A `string` that can be parsed into a number between 0 and 65535
41
- */
42
- const port = type$1("string", "=>", (data, ctx) => {
43
- const asNumber = Number.parseInt(data, 10);
44
- if (!Number.isInteger(asNumber) || !(0 <= asNumber && asNumber <= 65535)) ctx.mustBe("an integer between 0 and 65535");
45
- return asNumber;
46
- });
47
- /**
48
- * An IP address or `"localhost"`
49
- */
50
- const host = type$1("string.ip | 'localhost'");
51
- /**
52
- * A boolean that accepts string values and converts them to boolean
53
- * Accepts "true" or "false" strings and converts them to actual boolean values
54
- */
55
- const boolean = type$1("'true' | 'false' | true | false", "=>", (str) => str === "true" || str === true);
56
-
57
- //#endregion
58
- //#region src/scope.ts
59
- /**
60
- * The root scope for the ArkEnv library, containing extensions to the ArkType scopes with ArkEnv-specific types like `string.host` and `number.port`.
61
- */
62
- const $ = scope({
63
- string: type$1.module({
64
- ...type$1.keywords.string,
65
- host
66
- }),
67
- number: type$1.module({
68
- ...type$1.keywords.number,
69
- port
70
- }),
71
- boolean
72
- });
73
-
74
- //#endregion
75
- //#region src/create-env.ts
76
- /**
77
- * TODO: If possible, find a better type than "const T extends Record<string, unknown>",
78
- * and be as close as possible to the type accepted by ArkType's `type`.
79
- */
80
- /**
81
- * Create an environment variables object from a schema and an environment
82
- * @param def - The environment variable schema
83
- * @param env - The environment variables to validate, defaults to `process.env`
84
- * @returns The validated environment variable schema
85
- * @throws An {@link ArkEnvError | error} if the environment variables are invalid.
86
- */
87
- function createEnv(def, env = process.env) {
88
- const validatedEnv = $.type.raw(def)(env);
89
- if (validatedEnv instanceof type$1.errors) throw new ArkEnvError(validatedEnv);
90
- return validatedEnv;
91
- }
92
-
93
- //#endregion
94
- //#region src/type.ts
95
- const type = $.type;
96
-
97
- //#endregion
98
- //#region src/index.ts
99
- /**
100
- * `arkenv`'s main export, an alias for {@link createEnv}
101
- *
102
- * {@link https://arkenv.js.org | ArkEnv} is a typesafe environment variables parser powered by {@link https://arktype.io | ArkType}, TypeScript's 1:1 validator.
103
- */
104
- const arkenv = createEnv;
105
- var src_default = arkenv;
106
-
107
- //#endregion
108
- export { ArkEnvError, createEnv, src_default as default, type };
1
+ import{scope as e,type as t}from"arktype";const n={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`},r=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null,i=()=>!!(!r()||process.env.NO_COLOR!==void 0||process.env.CI!==void 0||process.stdout&&!process.stdout.isTTY),a=(e,t)=>r()&&!i()?`${n[e]}${t}${n.reset}`:t,o=(e,t=2,{dontDetectNewlines:n=!1}={})=>n?`${` `.repeat(t)}${e}`:e.split(`
2
+ `).map(e=>`${` `.repeat(t)}${e}`).join(`
3
+ `),s=e=>Object.entries(e.byPath).map(([e,t])=>{let n=t.message.startsWith(e)?t.message.slice(e.length):t.message,r=n.match(/\(was "([^"]+)"\)/),i=r?n.replace(`(was "${r[1]}")`,`(was ${a(`cyan`,`"${r[1]}"`)})`):n;return`${a(`yellow`,e)}${i}`}).join(`
4
+ `);var c=class extends Error{constructor(e,t=`Errors found while validating environment variables`){super(`${a(`red`,t)}\n${o(s(e))}\n`),this.name=`ArkEnvError`}};const l=t(`string`,`=>`,(e,t)=>{let n=Number.parseInt(e,10);return(!Number.isInteger(n)||!(0<=n&&n<=65535))&&t.mustBe(`an integer between 0 and 65535`),n}),u=t(`string.ip | 'localhost'`),d=t(`'true' | 'false' | true | false`,`=>`,e=>e===`true`||e===!0),f=e({string:t.module({...t.keywords.string,host:u}),number:t.module({...t.keywords.number,port:l}),boolean:d});function p(e,n=process.env){let r=f.type.raw(e)(n);if(r instanceof t.errors)throw new c(r);return r}const m=f.type;var h=p;export{c as ArkEnvError,p as createEnv,h as default,m as type};
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["type","type","type"],"sources":["../src/lib/style-text.ts","../src/utils.ts","../src/errors.ts","../src/types.ts","../src/scope.ts","../src/create-env.ts","../src/type.ts","../src/index.ts"],"sourcesContent":["/**\n * Cross-platform text styling utility\n * Uses ANSI colors in Node environments, plain text in browsers\n * Respects NO_COLOR, CI environment variables, and TTY detection\n */\n\n// ANSI color codes for Node environments\nconst colors = {\n\tred: \"\\x1b[31m\",\n\tyellow: \"\\x1b[33m\",\n\tcyan: \"\\x1b[36m\",\n\treset: \"\\x1b[0m\",\n} as const;\n\n/**\n * Check if we're in a Node environment (not browser)\n * Checked dynamically to allow for testing with mocked globals\n */\nconst isNode = (): boolean =>\n\ttypeof process !== \"undefined\" &&\n\tprocess.versions != null &&\n\tprocess.versions.node != null;\n\n/**\n * Check if colors should be disabled based on environment\n * Respects NO_COLOR, CI environment variables, and TTY detection\n */\nconst shouldDisableColors = (): boolean => {\n\tif (!isNode()) return true;\n\n\t// Respect NO_COLOR environment variable (https://no-color.org/)\n\tif (process.env.NO_COLOR !== undefined) return true;\n\n\t// Disable colors in CI environments by default\n\tif (process.env.CI !== undefined) return true;\n\n\t// Disable colors if not writing to a TTY\n\tif (process.stdout && !process.stdout.isTTY) return true;\n\n\treturn false;\n};\n\n/**\n * Style text with color. Uses ANSI codes in Node, plain text in browsers.\n * @param color - The color to apply\n * @param text - The text to style\n * @returns Styled text in Node (if colors enabled), plain text otherwise\n */\nexport const styleText = (\n\tcolor: \"red\" | \"yellow\" | \"cyan\",\n\ttext: string,\n): string => {\n\t// Use ANSI colors only in Node environments with colors enabled\n\tif (isNode() && !shouldDisableColors()) {\n\t\treturn `${colors[color]}${text}${colors.reset}`;\n\t}\n\t// Fall back to plain text in browsers or when colors are disabled\n\treturn text;\n};\n","/**\n * Options for the `indent` function\n */\ntype IndentOptions = {\n\t/**\n\t * Whether to detect newlines and indent each line individually, defaults to false (indenting the whole string)\n\t */\n\tdontDetectNewlines?: boolean;\n};\n\n/**\n * Indent a string by a given amount\n * @param str - The string to indent\n * @param amt - The amount to indent by, defaults to 2\n * @param options - {@link IndentOptions}\n * @returns The indented string\n */\nexport const indent = (\n\tstr: string,\n\tamt = 2,\n\t{ dontDetectNewlines = false }: IndentOptions = {},\n) => {\n\tconst detectNewlines = !dontDetectNewlines;\n\tif (detectNewlines) {\n\t\treturn str\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => `${\" \".repeat(amt)}${line}`)\n\t\t\t.join(\"\\n\");\n\t}\n\n\treturn `${\" \".repeat(amt)}${str}`;\n};\n","import type { ArkErrors } from \"arktype\";\nimport { styleText } from \"./lib/style-text\";\nimport { indent } from \"./utils\";\n\n/**\n * Format the errors returned by ArkType to be more readable\n * @param errors - The errors returned by ArkType\n * @returns A string of the formatted errors\n */\nexport const formatErrors = (errors: ArkErrors): string =>\n\tObject.entries(errors.byPath)\n\t\t.map(([path, error]) => {\n\t\t\tconst messageWithoutPath = error.message.startsWith(path)\n\t\t\t\t? error.message.slice(path.length)\n\t\t\t\t: error.message;\n\n\t\t\t// Extract the value in parentheses if it exists\n\t\t\tconst valueMatch = messageWithoutPath.match(/\\(was \"([^\"]+)\"\\)/);\n\t\t\tconst formattedMessage = valueMatch\n\t\t\t\t? messageWithoutPath.replace(\n\t\t\t\t\t\t`(was \"${valueMatch[1]}\")`,\n\t\t\t\t\t\t`(was ${styleText(\"cyan\", `\"${valueMatch[1]}\"`)})`,\n\t\t\t\t\t)\n\t\t\t\t: messageWithoutPath;\n\n\t\t\treturn `${styleText(\"yellow\", path)}${formattedMessage}`;\n\t\t})\n\t\t.join(\"\\n\");\n\nexport class ArkEnvError extends Error {\n\tconstructor(\n\t\terrors: ArkErrors,\n\t\tmessage = \"Errors found while validating environment variables\",\n\t) {\n\t\tsuper(`${styleText(\"red\", message)}\\n${indent(formatErrors(errors))}\\n`);\n\t\tthis.name = \"ArkEnvError\";\n\t}\n}\n","import { type } from \"arktype\";\n\n/**\n * A `string` that can be parsed into a number between 0 and 65535\n */\nexport const port = type(\"string\", \"=>\", (data, ctx) => {\n\tconst asNumber = Number.parseInt(data, 10);\n\tconst isInteger = Number.isInteger(asNumber);\n\tconst isBetween = 0 <= asNumber && asNumber <= 65535;\n\tif (!isInteger || !isBetween) {\n\t\tctx.mustBe(\"an integer between 0 and 65535\");\n\t}\n\treturn asNumber;\n});\n\n/**\n * An IP address or `\"localhost\"`\n */\nexport const host = type(\"string.ip | 'localhost'\");\n\n/**\n * A boolean that accepts string values and converts them to boolean\n * Accepts \"true\" or \"false\" strings and converts them to actual boolean values\n */\nexport const boolean = type(\n\t\"'true' | 'false' | true | false\",\n\t\"=>\",\n\t(str) => str === \"true\" || str === true,\n);\n","import { scope, type } from \"arktype\";\nimport { boolean, host, port } from \"./types\";\n\n// For an explanation of the `$` variable naming convention, see: https://discord.com/channels/957797212103016458/1414659167008063588/1414670282756587581\n\n/**\n * The root scope for the ArkEnv library, containing extensions to the ArkType scopes with ArkEnv-specific types like `string.host` and `number.port`.\n */\nexport const $ = scope({\n\tstring: type.module({\n\t\t...type.keywords.string,\n\t\thost,\n\t}),\n\tnumber: type.module({\n\t\t...type.keywords.number,\n\t\tport,\n\t}),\n\tboolean,\n});\n","import { type distill, type } from \"arktype\";\nimport { ArkEnvError } from \"./errors\";\nimport { $ } from \"./scope\";\n\ntype RuntimeEnvironment = Record<string, string | undefined>;\n\nexport type EnvSchema<def> = type.validate<def, (typeof $)[\"t\"]>;\n\n/**\n * TODO: If possible, find a better type than \"const T extends Record<string, unknown>\",\n * and be as close as possible to the type accepted by ArkType's `type`.\n */\n\n/**\n * Create an environment variables object from a schema and an environment\n * @param def - The environment variable schema\n * @param env - The environment variables to validate, defaults to `process.env`\n * @returns The validated environment variable schema\n * @throws An {@link ArkEnvError | error} if the environment variables are invalid.\n */\nexport function createEnv<const T extends Record<string, unknown>>(\n\tdef: EnvSchema<T>,\n\tenv: RuntimeEnvironment = process.env,\n): distill.Out<type.infer<T, (typeof $)[\"t\"]>> {\n\tconst schema = $.type.raw(def);\n\n\tconst validatedEnv = schema(env);\n\n\tif (validatedEnv instanceof type.errors) {\n\t\tthrow new ArkEnvError(validatedEnv);\n\t}\n\n\treturn validatedEnv;\n}\n","import { $ } from \"./scope\";\n\nexport const type = $.type;\n","export type { EnvSchema } from \"./create-env\";\n\nimport { createEnv } from \"./create-env\";\n\n/**\n * `arkenv`'s main export, an alias for {@link createEnv}\n *\n * {@link https://arkenv.js.org | ArkEnv} is a typesafe environment variables parser powered by {@link https://arktype.io | ArkType}, TypeScript's 1:1 validator.\n */\nconst arkenv = createEnv;\nexport default arkenv;\nexport { type } from \"./type\";\nexport { createEnv };\nexport { ArkEnvError } from \"./errors\";\n"],"mappings":"0CAOA,MAAM,EAAS,CACd,IAAK,WACL,OAAQ,WACR,KAAM,WACN,MAAO,UACP,CAMK,MACL,OAAO,QAAY,KACnB,QAAQ,UAAY,MACpB,QAAQ,SAAS,MAAQ,KAMpB,MAUL,GATI,CAAC,GAAQ,EAGT,QAAQ,IAAI,WAAa,IAAA,IAGzB,QAAQ,IAAI,KAAO,IAAA,IAGnB,QAAQ,QAAU,CAAC,QAAQ,OAAO,OAW1B,GACZ,EACA,IAGI,GAAQ,EAAI,CAAC,GAAqB,CAC9B,GAAG,EAAO,KAAS,IAAO,EAAO,QAGlC,ECxCK,GACZ,EACA,EAAM,EACN,CAAE,qBAAqB,IAAyB,EA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AAI,EAAI,CAEF,EAAI,CAEhC,GAAI,aAAwBC,EAAK,OAChC,MAAM,IAAI,EAAY,EAAa,CAGpC,OAAO,EC9BR,MAAa,EAAO,EAAE,KCQtB,IAAA,EADe"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arkenv",
3
3
  "type": "module",
4
- "version": "0.7.3",
4
+ "version": "0.7.5",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -31,17 +31,29 @@
31
31
  "bugs": "https://github.com/yamcodes/arkenv/labels/arkenv",
32
32
  "author": "Yam Borodetsky <yam@yam.codes>",
33
33
  "devDependencies": {
34
- "@ark/schema": "^0.49.0",
35
- "@types/node": "24.6.2",
36
- "tsdown": "^0.15.6",
37
- "typescript": "^5.9.3",
38
- "vitest": "^3.2.4"
34
+ "@ark/schema": "0.53.0",
35
+ "@size-limit/esbuild-why": "11.2.0",
36
+ "@size-limit/preset-small-lib": "11.2.0",
37
+ "@types/node": "24.10.0",
38
+ "arktype": "2.1.25",
39
+ "size-limit": "11.2.0",
40
+ "tsdown": "0.15.12",
41
+ "typescript": "5.9.3",
42
+ "vitest": "4.0.8"
39
43
  },
40
44
  "peerDependencies": {
41
45
  "arktype": "^2.1.22"
42
46
  },
47
+ "size-limit": [
48
+ {
49
+ "path": "dist/index.js",
50
+ "limit": "2 kB",
51
+ "import": "*"
52
+ }
53
+ ],
43
54
  "scripts": {
44
55
  "build": "tsdown",
56
+ "size": "size-limit",
45
57
  "test:once": "pnpm test",
46
58
  "typecheck": "tsc --noEmit",
47
59
  "clean": "rimraf dist node_modules",