@vite-env/core 0.2.2 → 0.4.0

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.
Files changed (47) hide show
  1. package/README.md +3 -1
  2. package/dist/config.cjs +1 -1
  3. package/dist/config.d.cts +1 -1
  4. package/dist/config.d.mts +1 -1
  5. package/dist/dts-BgHTl6hC.cjs +114 -0
  6. package/dist/dts-BgHTl6hC.cjs.map +1 -0
  7. package/dist/dts.cjs +2 -1
  8. package/dist/dts.d.cts +10 -5
  9. package/dist/dts.d.mts +10 -5
  10. package/dist/dts.mjs +31 -23
  11. package/dist/dts.mjs.map +1 -1
  12. package/dist/format.cjs +88 -0
  13. package/dist/format.cjs.map +1 -1
  14. package/dist/format.d.cts +42 -1
  15. package/dist/format.d.mts +42 -1
  16. package/dist/format.mjs +83 -1
  17. package/dist/format.mjs.map +1 -1
  18. package/dist/index.cjs +2 -8
  19. package/dist/index.d.cts +3 -3
  20. package/dist/index.d.mts +3 -3
  21. package/dist/index.mjs +2 -2
  22. package/dist/leak.cjs.map +1 -1
  23. package/dist/leak.d.cts +2 -2
  24. package/dist/leak.d.mts +2 -2
  25. package/dist/leak.mjs.map +1 -1
  26. package/dist/plugin.cjs +131 -17
  27. package/dist/plugin.cjs.map +1 -1
  28. package/dist/plugin.d.cts +22 -0
  29. package/dist/plugin.d.mts +22 -0
  30. package/dist/plugin.mjs +131 -18
  31. package/dist/plugin.mjs.map +1 -1
  32. package/dist/schema.cjs +1 -1
  33. package/dist/schema.d.cts +1 -1
  34. package/dist/schema.d.mts +1 -1
  35. package/dist/standard.cjs +46 -0
  36. package/dist/standard.cjs.map +1 -0
  37. package/dist/standard.d.cts +11 -0
  38. package/dist/standard.d.mts +11 -0
  39. package/dist/standard.mjs +43 -0
  40. package/dist/standard.mjs.map +1 -0
  41. package/dist/types-1okexcwM.d.cts +43 -0
  42. package/dist/types-DuWT_251.d.mts +43 -0
  43. package/package.json +19 -2
  44. package/dist/dts-DF71HNdJ.cjs +0 -100
  45. package/dist/dts-DF71HNdJ.cjs.map +0 -1
  46. package/dist/types-CluiDKAQ.d.mts +0 -22
  47. package/dist/types-DqTMuWwc.d.cts +0 -22
package/README.md CHANGED
@@ -7,6 +7,7 @@ The `env.ts` layer for Vite — define once, validate everywhere, import with ty
7
7
  - Typed virtual modules (`virtual:env/client`, `virtual:env/server`)
8
8
  - Server/client split with build-time leak detection
9
9
  - Auto-coercion via Zod v4 (`z.stringbool()`, `z.coerce.number()`)
10
+ - Standard Schema support — use Valibot, ArkType, or any compliant validator
10
11
  - Auto `.d.ts` generation
11
12
  - Vite 8 / Rolldown native
12
13
 
@@ -21,7 +22,8 @@ pnpm add @vite-env/core zod
21
22
  **1. Define your schema** — `env.ts`
22
23
 
23
24
  ```ts
24
- import { defineEnv, z } from '@vite-env/core'
25
+ import { defineEnv } from '@vite-env/core'
26
+ import { z } from 'zod'
25
27
 
26
28
  export default defineEnv({
27
29
  server: {
package/dist/config.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- require("./dts-DF71HNdJ.cjs");
2
+ require("./dts-BgHTl6hC.cjs");
3
3
  let jiti = require("jiti");
4
4
  //#region src/config.ts
5
5
  async function loadEnvConfig(configPath) {
package/dist/config.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as EnvDefinition } from "./types-DqTMuWwc.cjs";
1
+ import { n as EnvDefinition } from "./types-1okexcwM.cjs";
2
2
 
3
3
  //#region src/config.d.ts
4
4
  declare function loadEnvConfig(configPath: string): Promise<EnvDefinition>;
package/dist/config.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as EnvDefinition } from "./types-CluiDKAQ.mjs";
1
+ import { n as EnvDefinition } from "./types-DuWT_251.mjs";
2
2
 
3
3
  //#region src/config.d.ts
4
4
  declare function loadEnvConfig(configPath: string): Promise<EnvDefinition>;
@@ -0,0 +1,114 @@
1
+ //#region \0rolldown/runtime.js
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
+ //#endregion
23
+ let node_path = require("node:path");
24
+ node_path = __toESM(node_path);
25
+ let node_fs_promises = require("node:fs/promises");
26
+ node_fs_promises = __toESM(node_fs_promises);
27
+ //#region src/dts.ts
28
+ /**
29
+ * Writes vite-env.d.ts for Zod definitions.
30
+ * Uses instanceof checks to infer TypeScript types from Zod schemas.
31
+ * Zod is loaded dynamically so this module can be imported without zod installed.
32
+ */
33
+ async function generateDts(def, root) {
34
+ const { z } = await import("zod");
35
+ await writeDts(root, zodShapeToTsFields(z, { ...def.client }), zodShapeToTsFields(z, {
36
+ ...def.server,
37
+ ...def.client
38
+ }));
39
+ }
40
+ /**
41
+ * Writes vite-env.d.ts for Standard Schema definitions.
42
+ * All fields are typed as `string` — Standard Schema has no runtime type introspection.
43
+ */
44
+ async function generateStandardDts(def, root) {
45
+ const clientKeys = Object.keys(def.client ?? {});
46
+ const serverKeys = [...Object.keys(def.server ?? {}), ...clientKeys];
47
+ await writeDts(root, keysToTsFields(clientKeys), keysToTsFields(serverKeys), "(Standard Schema)");
48
+ }
49
+ async function writeDts(root, clientFields, serverFields, tag = "") {
50
+ const dts = `${tag ? `// Auto-generated by @vite-env/core ${tag}\n// Do not edit manually — re-generated on every dev server start and build\n// Tip: for richer types, use defineEnv() with Zod instead of defineStandardEnv()` : `// Auto-generated by @vite-env/core\n// Do not edit manually — re-generated on every dev server start and build`}
51
+
52
+ declare module 'virtual:env/client' {
53
+ const env: {
54
+ ${clientFields}
55
+ }
56
+ export { env }
57
+ export default env
58
+ }
59
+
60
+ declare module 'virtual:env/server' {
61
+ const env: {
62
+ ${serverFields}
63
+ }
64
+ export { env }
65
+ export default env
66
+ }
67
+ `;
68
+ const filePath = node_path.default.join(root, "vite-env.d.ts");
69
+ try {
70
+ await node_fs_promises.default.writeFile(filePath, dts, "utf-8");
71
+ } catch (e) {
72
+ throw new Error(`[vite-env] Failed to write vite-env.d.ts to ${root}. Check file permissions.`, { cause: e });
73
+ }
74
+ }
75
+ function keysToTsFields(keys) {
76
+ return keys.map((key) => ` readonly ${key}: string`).join("\n");
77
+ }
78
+ function zodShapeToTsFields(z, shape) {
79
+ return Object.entries(shape).map(([key, schema]) => {
80
+ const tsType = zodToTs(z, schema);
81
+ return ` readonly ${key}${schema instanceof z.ZodOptional ? "?" : ""}: ${tsType}`;
82
+ }).join("\n");
83
+ }
84
+ function zodToTs(z, schema) {
85
+ if (schema instanceof z.ZodOptional) return zodToTs(z, schema.unwrap());
86
+ if (schema instanceof z.ZodDefault) return zodToTs(z, schema.def.innerType);
87
+ if (schema instanceof z.ZodString) return "string";
88
+ if (schema instanceof z.ZodNumber) return "number";
89
+ if (schema instanceof z.ZodBoolean) return "boolean";
90
+ if (schema instanceof z.ZodEnum) return schema.options.map((o) => `'${o}'`).join(" | ");
91
+ if (schema instanceof z.ZodPipe) return zodToTs(z, schema.def.out);
92
+ return "string";
93
+ }
94
+ //#endregion
95
+ Object.defineProperty(exports, "__toESM", {
96
+ enumerable: true,
97
+ get: function() {
98
+ return __toESM;
99
+ }
100
+ });
101
+ Object.defineProperty(exports, "generateDts", {
102
+ enumerable: true,
103
+ get: function() {
104
+ return generateDts;
105
+ }
106
+ });
107
+ Object.defineProperty(exports, "generateStandardDts", {
108
+ enumerable: true,
109
+ get: function() {
110
+ return generateStandardDts;
111
+ }
112
+ });
113
+
114
+ //# sourceMappingURL=dts-BgHTl6hC.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dts-BgHTl6hC.cjs","names":["path","fs"],"sources":["../src/dts.ts"],"sourcesContent":["// @env node\nimport type { EnvDefinition, StandardEnvDefinition } from './types'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\n\n/**\n * Writes vite-env.d.ts for Zod definitions.\n * Uses instanceof checks to infer TypeScript types from Zod schemas.\n * Zod is loaded dynamically so this module can be imported without zod installed.\n */\nexport async function generateDts(\n def: EnvDefinition,\n root: string,\n): Promise<void> {\n const { z } = await import('zod')\n\n const clientFields = zodShapeToTsFields(z, { ...def.client })\n const serverFields = zodShapeToTsFields(z, { ...def.server, ...def.client })\n\n await writeDts(root, clientFields, serverFields)\n}\n\n/**\n * Writes vite-env.d.ts for Standard Schema definitions.\n * All fields are typed as `string` — Standard Schema has no runtime type introspection.\n */\nexport async function generateStandardDts(\n def: StandardEnvDefinition,\n root: string,\n): Promise<void> {\n const clientKeys = Object.keys(def.client ?? {})\n const serverKeys = [...Object.keys(def.server ?? {}), ...clientKeys]\n\n const clientFields = keysToTsFields(clientKeys)\n const serverFields = keysToTsFields(serverKeys)\n\n await writeDts(root, clientFields, serverFields, '(Standard Schema)')\n}\n\nasync function writeDts(\n root: string,\n clientFields: string,\n serverFields: string,\n tag = '',\n): Promise<void> {\n const header = tag\n ? `// Auto-generated by @vite-env/core ${tag}\\n// Do not edit manually — re-generated on every dev server start and build\\n// Tip: for richer types, use defineEnv() with Zod instead of defineStandardEnv()`\n : `// Auto-generated by @vite-env/core\\n// Do not edit manually — re-generated on every dev server start and build`\n\n const dts = `${header}\n\ndeclare module 'virtual:env/client' {\n const env: {\n${clientFields}\n }\n export { env }\n export default env\n}\n\ndeclare module 'virtual:env/server' {\n const env: {\n${serverFields}\n }\n export { env }\n export default env\n}\n`\n\n const filePath = path.join(root, 'vite-env.d.ts')\n try {\n await fs.writeFile(filePath, dts, 'utf-8')\n }\n catch (e) {\n throw new Error(\n `[vite-env] Failed to write vite-env.d.ts to ${root}. Check file permissions.`,\n { cause: e },\n )\n }\n}\n\nfunction keysToTsFields(keys: string[]): string {\n return keys\n .map(key => ` readonly ${key}: string`)\n .join('\\n')\n}\n\nfunction zodShapeToTsFields(z: any, shape: Record<string, unknown>): string {\n return Object.entries(shape)\n .map(([key, schema]) => {\n const tsType = zodToTs(z, schema)\n const optional = schema instanceof z.ZodOptional\n return ` readonly ${key}${optional ? '?' : ''}: ${tsType}`\n })\n .join('\\n')\n}\n\nfunction zodToTs(z: any, schema: any): string {\n if (schema instanceof z.ZodOptional)\n return zodToTs(z, schema.unwrap())\n if (schema instanceof z.ZodDefault)\n return zodToTs(z, schema.def.innerType)\n if (schema instanceof z.ZodString)\n return 'string'\n if (schema instanceof z.ZodNumber)\n return 'number'\n if (schema instanceof z.ZodBoolean)\n return 'boolean'\n if (schema instanceof z.ZodEnum)\n return (schema.options as string[]).map(o => `'${o}'`).join(' | ')\n if (schema instanceof z.ZodPipe)\n return zodToTs(z, schema.def.out)\n return 'string'\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,eAAsB,YACpB,KACA,MACe;CACf,MAAM,EAAE,MAAM,MAAM,OAAO;AAK3B,OAAM,SAAS,MAHM,mBAAmB,GAAG,EAAE,GAAG,IAAI,QAAQ,CAAC,EACxC,mBAAmB,GAAG;EAAE,GAAG,IAAI;EAAQ,GAAG,IAAI;EAAQ,CAAC,CAE5B;;;;;;AAOlD,eAAsB,oBACpB,KACA,MACe;CACf,MAAM,aAAa,OAAO,KAAK,IAAI,UAAU,EAAE,CAAC;CAChD,MAAM,aAAa,CAA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AAG,OAAO,IAAI,IAAI;AACnC,QAAO"}
package/dist/dts.cjs CHANGED
@@ -1,3 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_dts = require("./dts-DF71HNdJ.cjs");
2
+ const require_dts = require("./dts-BgHTl6hC.cjs");
3
3
  exports.generateDts = require_dts.generateDts;
4
+ exports.generateStandardDts = require_dts.generateStandardDts;
package/dist/dts.d.cts CHANGED
@@ -1,12 +1,17 @@
1
- import { t as EnvDefinition } from "./types-DqTMuWwc.cjs";
1
+ import { a as StandardEnvDefinition, n as EnvDefinition } from "./types-1okexcwM.cjs";
2
2
 
3
3
  //#region src/dts.d.ts
4
4
  /**
5
- * Writes vite-env.d.ts to project root.
6
- * Declares virtual:env/client and virtual:env/server module types.
7
- * Users never need to manually augment ImportMetaEnv again.
5
+ * Writes vite-env.d.ts for Zod definitions.
6
+ * Uses instanceof checks to infer TypeScript types from Zod schemas.
7
+ * Zod is loaded dynamically so this module can be imported without zod installed.
8
8
  */
9
9
  declare function generateDts(def: EnvDefinition, root: string): Promise<void>;
10
+ /**
11
+ * Writes vite-env.d.ts for Standard Schema definitions.
12
+ * All fields are typed as `string` — Standard Schema has no runtime type introspection.
13
+ */
14
+ declare function generateStandardDts(def: StandardEnvDefinition, root: string): Promise<void>;
10
15
  //#endregion
11
- export { generateDts };
16
+ export { generateDts, generateStandardDts };
12
17
  //# sourceMappingURL=dts.d.cts.map
package/dist/dts.d.mts CHANGED
@@ -1,12 +1,17 @@
1
- import { t as EnvDefinition } from "./types-CluiDKAQ.mjs";
1
+ import { a as StandardEnvDefinition, n as EnvDefinition } from "./types-DuWT_251.mjs";
2
2
 
3
3
  //#region src/dts.d.ts
4
4
  /**
5
- * Writes vite-env.d.ts to project root.
6
- * Declares virtual:env/client and virtual:env/server module types.
7
- * Users never need to manually augment ImportMetaEnv again.
5
+ * Writes vite-env.d.ts for Zod definitions.
6
+ * Uses instanceof checks to infer TypeScript types from Zod schemas.
7
+ * Zod is loaded dynamically so this module can be imported without zod installed.
8
8
  */
9
9
  declare function generateDts(def: EnvDefinition, root: string): Promise<void>;
10
+ /**
11
+ * Writes vite-env.d.ts for Standard Schema definitions.
12
+ * All fields are typed as `string` — Standard Schema has no runtime type introspection.
13
+ */
14
+ declare function generateStandardDts(def: StandardEnvDefinition, root: string): Promise<void>;
10
15
  //#endregion
11
- export { generateDts };
16
+ export { generateDts, generateStandardDts };
12
17
  //# sourceMappingURL=dts.d.mts.map
package/dist/dts.mjs CHANGED
@@ -1,24 +1,33 @@
1
- import { z } from "zod";
2
1
  import path from "node:path";
3
2
  import fs from "node:fs/promises";
4
3
  //#region src/dts.ts
5
4
  /**
6
- * Writes vite-env.d.ts to project root.
7
- * Declares virtual:env/client and virtual:env/server module types.
8
- * Users never need to manually augment ImportMetaEnv again.
5
+ * Writes vite-env.d.ts for Zod definitions.
6
+ * Uses instanceof checks to infer TypeScript types from Zod schemas.
7
+ * Zod is loaded dynamically so this module can be imported without zod installed.
9
8
  */
10
9
  async function generateDts(def, root) {
11
- const clientKeys = { ...def.client };
12
- const serverKeys = {
10
+ const { z } = await import("zod");
11
+ await writeDts(root, zodShapeToTsFields(z, { ...def.client }), zodShapeToTsFields(z, {
13
12
  ...def.server,
14
13
  ...def.client
15
- };
16
- const dts = `// Auto-generated by @vite-env/core
17
- // Do not edit manually — re-generated on every dev server start and build
14
+ }));
15
+ }
16
+ /**
17
+ * Writes vite-env.d.ts for Standard Schema definitions.
18
+ * All fields are typed as `string` — Standard Schema has no runtime type introspection.
19
+ */
20
+ async function generateStandardDts(def, root) {
21
+ const clientKeys = Object.keys(def.client ?? {});
22
+ const serverKeys = [...Object.keys(def.server ?? {}), ...clientKeys];
23
+ await writeDts(root, keysToTsFields(clientKeys), keysToTsFields(serverKeys), "(Standard Schema)");
24
+ }
25
+ async function writeDts(root, clientFields, serverFields, tag = "") {
26
+ const dts = `${tag ? `// Auto-generated by @vite-env/core ${tag}\n// Do not edit manually — re-generated on every dev server start and build\n// Tip: for richer types, use defineEnv() with Zod instead of defineStandardEnv()` : `// Auto-generated by @vite-env/core\n// Do not edit manually — re-generated on every dev server start and build`}
18
27
 
19
28
  declare module 'virtual:env/client' {
20
29
  const env: {
21
- ${zodShapeToTsFields(clientKeys)}
30
+ ${clientFields}
22
31
  }
23
32
  export { env }
24
33
  export default env
@@ -26,7 +35,7 @@ ${zodShapeToTsFields(clientKeys)}
26
35
 
27
36
  declare module 'virtual:env/server' {
28
37
  const env: {
29
- ${zodShapeToTsFields(serverKeys)}
38
+ ${serverFields}
30
39
  }
31
40
  export { env }
32
41
  export default env
@@ -39,27 +48,26 @@ ${zodShapeToTsFields(serverKeys)}
39
48
  throw new Error(`[vite-env] Failed to write vite-env.d.ts to ${root}. Check file permissions.`, { cause: e });
40
49
  }
41
50
  }
42
- function zodShapeToTsFields(shape) {
51
+ function keysToTsFields(keys) {
52
+ return keys.map((key) => ` readonly ${key}: string`).join("\n");
53
+ }
54
+ function zodShapeToTsFields(z, shape) {
43
55
  return Object.entries(shape).map(([key, schema]) => {
44
- const s = schema;
45
- const tsType = zodToTs(s);
46
- return ` readonly ${key}${isOptional(s) ? "?" : ""}: ${tsType}`;
56
+ const tsType = zodToTs(z, schema);
57
+ return ` readonly ${key}${schema instanceof z.ZodOptional ? "?" : ""}: ${tsType}`;
47
58
  }).join("\n");
48
59
  }
49
- function zodToTs(schema) {
50
- if (schema instanceof z.ZodOptional) return zodToTs(schema.unwrap());
51
- if (schema instanceof z.ZodDefault) return zodToTs(schema.def.innerType);
60
+ function zodToTs(z, schema) {
61
+ if (schema instanceof z.ZodOptional) return zodToTs(z, schema.unwrap());
62
+ if (schema instanceof z.ZodDefault) return zodToTs(z, schema.def.innerType);
52
63
  if (schema instanceof z.ZodString) return "string";
53
64
  if (schema instanceof z.ZodNumber) return "number";
54
65
  if (schema instanceof z.ZodBoolean) return "boolean";
55
66
  if (schema instanceof z.ZodEnum) return schema.options.map((o) => `'${o}'`).join(" | ");
56
- if (schema instanceof z.ZodPipe) return zodToTs(schema.def.out);
67
+ if (schema instanceof z.ZodPipe) return zodToTs(z, schema.def.out);
57
68
  return "string";
58
69
  }
59
- function isOptional(schema) {
60
- return schema instanceof z.ZodOptional;
61
- }
62
70
  //#endregion
63
- export { generateDts };
71
+ export { generateDts, generateStandardDts };
64
72
 
65
73
  //# sourceMappingURL=dts.mjs.map
package/dist/dts.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dts.mjs","names":[],"sources":["../src/dts.ts"],"sourcesContent":["// @env node\nimport type { EnvDefinition } from './types'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport { z } from 'zod'\n\n/**\n * Writes vite-env.d.ts to project root.\n * Declares virtual:env/client and virtual:env/server module types.\n * Users never need to manually augment ImportMetaEnv again.\n */\nexport async function generateDts(\n def: EnvDefinition,\n root: string,\n): Promise<void> {\n const clientKeys = {\n ...def.client,\n }\n const serverKeys = {\n ...def.server,\n ...def.client,\n }\n\n const clientFields = zodShapeToTsFields(clientKeys)\n const serverFields = zodShapeToTsFields(serverKeys)\n\n const dts = `// Auto-generated by @vite-env/core\n// Do not edit manually — re-generated on every dev server start and build\n\ndeclare module 'virtual:env/client' {\n const env: {\n${clientFields}\n }\n export { env }\n export default env\n}\n\ndeclare module 'virtual:env/server' {\n const env: {\n${serverFields}\n }\n export { env }\n export default env\n}\n`\n\n const filePath = path.join(root, 'vite-env.d.ts')\n try {\n await fs.writeFile(filePath, dts, 'utf-8')\n }\n catch (e) {\n throw new Error(\n `[vite-env] Failed to write vite-env.d.ts to ${root}. Check file permissions.`,\n { cause: e },\n )\n }\n}\n\nfunction zodShapeToTsFields(shape: z.ZodRawShape): string {\n return Object.entries(shape)\n .map(([key, schema]) => {\n // Zod v4: ZodRawShape values are $ZodType, cast to ZodTypeAny for instanceof checks\n const s = schema as z.ZodTypeAny\n const tsType = zodToTs(s)\n const optional = isOptional(s)\n return ` readonly ${key}${optional ? '?' : ''}: ${tsType}`\n })\n .join('\\n')\n}\n\nfunction zodToTs(schema: z.ZodTypeAny): string {\n if (schema instanceof z.ZodOptional)\n return zodToTs(schema.unwrap() as unknown as z.ZodTypeAny)\n if (schema instanceof z.ZodDefault)\n return zodToTs(schema.def.innerType as unknown as z.ZodTypeAny)\n if (schema instanceof z.ZodString)\n return 'string'\n if (schema instanceof z.ZodNumber)\n return 'number'\n if (schema instanceof z.ZodBoolean)\n return 'boolean'\n if (schema instanceof z.ZodEnum)\n return (schema.options as string[]).map(o => `'${o}'`).join(' | ')\n if (schema instanceof z.ZodPipe)\n return zodToTs(schema.def.out as unknown as z.ZodTypeAny)\n return 'string'\n}\n\nfunction isOptional(schema: z.ZodTypeAny): boolean {\n return schema instanceof z.ZodOptional\n}\n"],"mappings":";;;;;;;;;AAWA,eAAsB,YACpB,KACA,MACe;CACf,MAAM,aAAa,EACjB,GAAG,IAAI,QACR;CACD,MAAM,aAAa;EACjB,GAAG,IAAI;EACP,GAAG,IAAI;EACR;CAKD,MAAM,MAAM;;;;;EAHS,mBAAmB,WAAW,CAQtC;;;;;;;;EAPQ,mBAAmB,WAAW,CAetC;;;;;;CAOb,MAAM,WAAW,KAAK,KAAK,MAAM,gBAAgB;AACjD,KAAI;AACF,QAAM,GAAG,UAAU,UAAU,KAAK,QAAQ;UAErC,GAAG;AACR,QAAM,IAAI,MACR,+CAA+C,KAAK,4BACpD,EAAE,OAAO,GAAG,CACb;;;AAIL,SAAS,mBAAmB,OAA8B;AACxD,QAAO,OAAO,QAAQ,MAAM,CACzB,KAAK,CAAC,KAAK,YAAY;EAEtB,MAAM,IAAI;EACV,MAAM,SAAS,QAAQ,EAAE;AAEzB,SAAO,gBAAgB,MADN,WAAW,EAAE,GACU,MAAM,GAAG,IAAI;GACrD,CACD,KAAK,KAAK;;AAGf,SAAS,QAAQ,QAA8B;AAC7C,KAAI,kBAAkB,EAAE,YACtB,QAAO,QAAQ,OAAO,QAAQ,CAA4B;AAC5D,KAAI,kBAAkB,EAAE,WACtB,QAAO,QAAQ,OAAO,IAAI,UAAqC;AACjE,KAAI,kBAAkB,EAAE,UACtB,QAAO;AACT,KAAI,kBAAkB,EAAE,UACtB,QAAO;AACT,KAAI,kBAAkB,EAAE,WACtB,QAAO;AACT,KAAI,kBAAkB,EAAE,QACtB,QAAQ,OAAO,QAAqB,KAAI,MAAK,IAAI,EAAE,GAAG,CAAC,KAAK,MAAM;AACpE,KAAI,kBAAkB,EAAE,QACtB,QAAO,QAAQ,OAAO,IAAI,IAA+B;AAC3D,QAAO;;AAGT,SAAS,WAAW,QAA+B;AACjD,QAAO,kBAAkB,EAAE"}
1
+ {"version":3,"file":"dts.mjs","names":[],"sources":["../src/dts.ts"],"sourcesContent":["// @env node\nimport type { EnvDefinition, StandardEnvDefinition } from './types'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\n\n/**\n * Writes vite-env.d.ts for Zod definitions.\n * Uses instanceof checks to infer TypeScript types from Zod schemas.\n * Zod is loaded dynamically so this module can be imported without zod installed.\n */\nexport async function generateDts(\n def: EnvDefinition,\n root: string,\n): Promise<void> {\n const { z } = await import('zod')\n\n const clientFields = zodShapeToTsFields(z, { ...def.client })\n const serverFields = zodShapeToTsFields(z, { ...def.server, ...def.client })\n\n await writeDts(root, clientFields, serverFields)\n}\n\n/**\n * Writes vite-env.d.ts for Standard Schema definitions.\n * All fields are typed as `string` — Standard Schema has no runtime type introspection.\n */\nexport async function generateStandardDts(\n def: StandardEnvDefinition,\n root: string,\n): Promise<void> {\n const clientKeys = Object.keys(def.client ?? {})\n const serverKeys = [...Object.keys(def.server ?? {}), ...clientKeys]\n\n const clientFields = keysToTsFields(clientKeys)\n const serverFields = keysToTsFields(serverKeys)\n\n await writeDts(root, clientFields, serverFields, '(Standard Schema)')\n}\n\nasync function writeDts(\n root: string,\n clientFields: string,\n serverFields: string,\n tag = '',\n): Promise<void> {\n const header = tag\n ? `// Auto-generated by @vite-env/core ${tag}\\n// Do not edit manually — re-generated on every dev server start and build\\n// Tip: for richer types, use defineEnv() with Zod instead of defineStandardEnv()`\n : `// Auto-generated by @vite-env/core\\n// Do not edit manually — re-generated on every dev server start and build`\n\n const dts = `${header}\n\ndeclare module 'virtual:env/client' {\n const env: {\n${clientFields}\n }\n export { env }\n export default env\n}\n\ndeclare module 'virtual:env/server' {\n const env: {\n${serverFields}\n }\n export { env }\n export default env\n}\n`\n\n const filePath = path.join(root, 'vite-env.d.ts')\n try {\n await fs.writeFile(filePath, dts, 'utf-8')\n }\n catch (e) {\n throw new Error(\n `[vite-env] Failed to write vite-env.d.ts to ${root}. Check file permissions.`,\n { cause: e },\n )\n }\n}\n\nfunction keysToTsFields(keys: string[]): string {\n return keys\n .map(key => ` readonly ${key}: string`)\n .join('\\n')\n}\n\nfunction zodShapeToTsFields(z: any, shape: Record<string, unknown>): string {\n return Object.entries(shape)\n .map(([key, schema]) => {\n const tsType = zodToTs(z, schema)\n const optional = schema instanceof z.ZodOptional\n return ` readonly ${key}${optional ? '?' : ''}: ${tsType}`\n })\n .join('\\n')\n}\n\nfunction zodToTs(z: any, schema: any): string {\n if (schema instanceof z.ZodOptional)\n return zodToTs(z, schema.unwrap())\n if (schema instanceof z.ZodDefault)\n return zodToTs(z, schema.def.innerType)\n if (schema instanceof z.ZodString)\n return 'string'\n if (schema instanceof z.ZodNumber)\n return 'number'\n if (schema instanceof z.ZodBoolean)\n return 'boolean'\n if (schema instanceof z.ZodEnum)\n return (schema.options as string[]).map(o => `'${o}'`).join(' | ')\n if (schema instanceof z.ZodPipe)\n return zodToTs(z, schema.def.out)\n return 'string'\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,YACpB,KACA,MACe;CACf,MAAM,EAAE,MAAM,MAAM,OAAO;AAK3B,OAAM,SAAS,MAHM,mBAAmB,GAAG,EAAE,GAAG,IAAI,QAAQ,CAAC,EACxC,mBAAmB,GAAG;EAAE,GAAG,IAAI;EAAQ,GAAG,IAAI;EAAQ,CAAC,CAE5B;;;;;;AAOlD,eAAsB,oBACpB,KACA,MACe;CACf,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AAM;AACpE,KAAI,kBAAkB,EAAE,QACtB,QAAO,QAAQ,GAAG,OAAO,IAAI,IAAI;AACnC,QAAO"}
package/dist/format.cjs CHANGED
@@ -5,7 +5,95 @@ function formatZodError(issues) {
5
5
  return ` \x1B[31m✗\x1B[0m ${(issue.path.length > 0 ? issue.path.join(".") : "(root)").padEnd(28)} ${issue.message}`;
6
6
  }).join("\n");
7
7
  }
8
+ function formatStandardSchemaError(issues) {
9
+ return issues.map((issue) => {
10
+ return ` \x1B[31m✗\x1B[0m ${(issue.path.length > 0 ? issue.path.map((seg) => typeof seg === "object" && seg !== null && "key" in seg ? String(seg.key) : String(seg)).join(".") : "(root)").padEnd(28)} ${issue.message}`;
11
+ }).join("\n");
12
+ }
13
+ const YELLOW = "\x1B[33m";
14
+ const BOLD_YELLOW = "\x1B[1;33m";
15
+ const CYAN = "\x1B[36m";
16
+ const RESET = "\x1B[0m";
17
+ const BOX_WIDTH = 66;
18
+ const CONTENT_AREA = BOX_WIDTH - 4;
19
+ /** Maximum visible character length for an importer path inside the warning box. */
20
+ const IMPORTER_MAX_LEN = CONTENT_AREA - 10;
21
+ /**
22
+ * Truncates an importer path to fit within maxLen visible characters.
23
+ * Adds a leading '…' when truncation occurs so the rightmost (most specific) part is preserved.
24
+ */
25
+ function truncateImporter(importerPath, maxLen) {
26
+ if (importerPath.length <= maxLen) return importerPath;
27
+ return `\u2026${importerPath.slice(-(maxLen - 1))}`;
28
+ }
29
+ function boxTop() {
30
+ return `${YELLOW}\u250C${"─".repeat(BOX_WIDTH - 2)}\u2510${RESET}`;
31
+ }
32
+ function boxBottom() {
33
+ return `${YELLOW}\u2514${"─".repeat(BOX_WIDTH - 2)}\u2518${RESET}`;
34
+ }
35
+ function boxLine(visibleText, renderedText = visibleText) {
36
+ return `${YELLOW}\u2502${RESET} ${renderedText}${" ".repeat(Math.max(0, CONTENT_AREA - visibleText.length))}${YELLOW}\u2502${RESET}`;
37
+ }
38
+ /**
39
+ * Renders the colored terminal warning box for 'warn' mode.
40
+ * Every line is exactly 66 characters wide (visible chars, excluding ANSI codes),
41
+ * assuming Vite environment names are short (≤19 chars). Longer names will extend
42
+ * the line beyond 66 chars without crashing — Math.max(0) prevents negative padding.
43
+ * Use in logger.warn() calls — not in log files.
44
+ */
45
+ function formatGuardWarning(fail) {
46
+ const importerDisplay = fail.importer === void 0 ? "(unknown)" : truncateImporter(fail.importer, 52);
47
+ return [
48
+ boxTop(),
49
+ boxLine("[vite-env] DEPRECATION WARNING", `${BOLD_YELLOW}[vite-env] DEPRECATION WARNING${RESET}`),
50
+ boxLine(""),
51
+ boxLine(`virtual:env/server was imported from the "${fail.envName}"`),
52
+ boxLine("environment. This will be a hard build error in 1.0.0."),
53
+ boxLine(""),
54
+ boxLine("To enforce now: onClientAccessOfServerModule: 'error'", `To enforce now: ${CYAN}onClientAccessOfServerModule: 'error'${RESET}`),
55
+ boxLine("To silence: onClientAccessOfServerModule: 'stub'", `To silence: ${CYAN}onClientAccessOfServerModule: 'stub'${RESET}`),
56
+ boxLine(""),
57
+ boxLine(`Found in: ${importerDisplay}`),
58
+ boxBottom()
59
+ ].join("\n");
60
+ }
61
+ /**
62
+ * Renders the plain-text hard error message thrown in 'error' mode.
63
+ * No ANSI — thrown as an Error message, not printed via logger.
64
+ */
65
+ function formatHardError(fail) {
66
+ const importerLine = fail.importer ?? "(unknown)";
67
+ return [
68
+ `[vite-env] virtual:env/server is not available in the "${fail.envName}" environment.`,
69
+ ``,
70
+ ` Server-only modules cannot be imported from client code.`,
71
+ ` Add this environment to serverEnvironments if intentional:`,
72
+ ``,
73
+ ` ViteEnv({ serverEnvironments: ['ssr', '${fail.envName}'] })`,
74
+ ``,
75
+ ` Or change enforcement:`,
76
+ ``,
77
+ ` ViteEnv({ onClientAccessOfServerModule: 'stub' })`,
78
+ ``,
79
+ ` Imported from: ${importerLine}`
80
+ ].join("\n");
81
+ }
82
+ /**
83
+ * Renders a single ANSI-free log entry for vite-env-warnings.log.
84
+ * Uses the same (unknown) convention as formatGuardWarning for missing importers.
85
+ */
86
+ function formatGuardLogEntry(fail, timestamp) {
87
+ const importerLine = fail.importer ?? "(unknown)";
88
+ return [`[${timestamp}] virtual:env/server accessed from "${fail.envName}" environment`, ` Importer: ${importerLine}`].join("\n");
89
+ }
8
90
  //#endregion
91
+ exports.IMPORTER_MAX_LEN = IMPORTER_MAX_LEN;
92
+ exports.formatGuardLogEntry = formatGuardLogEntry;
93
+ exports.formatGuardWarning = formatGuardWarning;
94
+ exports.formatHardError = formatHardError;
95
+ exports.formatStandardSchemaError = formatStandardSchemaError;
9
96
  exports.formatZodError = formatZodError;
97
+ exports.truncateImporter = truncateImporter;
10
98
 
11
99
  //# sourceMappingURL=format.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import type { core } from 'zod'\n\nexport function formatZodError(issues: core.$ZodIssue[]): string {\n return issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join('.') : '(root)'\n return ` \\x1B[31m✗\\x1B[0m ${path.padEnd(28)} ${issue.message}`\n })\n .join('\\n')\n}\n"],"mappings":";;AAEA,SAAgB,eAAe,QAAkC;AAC/D,QAAO,OACJ,KAAK,UAAU;AAEd,SAAO,uBADM,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,KAAK,IAAI,GAAG,UAC1B,OAAO,GAAG,CAAC,GAAG,MAAM;GACtD,CACD,KAAK,KAAK"}
1
+ {"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import type { core } from 'zod'\nimport type { GuardFail } from './guard'\nimport type { StandardValidationIssue } from './types'\n\nexport function formatZodError(issues: core.$ZodIssue[]): string {\n return issues\n .map((issue) => {\n const path = issue.path.length > 0 ? issue.path.join('.') : '(root)'\n return ` \\x1B[31m✗\\x1B[0m ${path.padEnd(28)} ${issue.message}`\n })\n .join('\\n')\n}\n\nexport function formatStandardSchemaError(issues: StandardValidationIssue[]): string {\n return issues\n .map((issue) => {\n const path = issue.path.length > 0\n ? issue.path.map(seg => typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg)).join('.')\n : '(root)'\n return ` \\x1B[31m✗\\x1B[0m ${path.padEnd(28)} ${issue.message}`\n })\n .join('\\n')\n}\n\nconst YELLOW = '\\x1B[33m'\nconst BOLD_YELLOW = '\\x1B[1;33m'\nconst CYAN = '\\x1B[36m'\nconst RESET = '\\x1B[0m'\n\nconst BOX_WIDTH = 66\n// 1 left border + 2 left spaces + content + 1 right border = BOX_WIDTH\n// content area = BOX_WIDTH - 4\nconst CONTENT_AREA = BOX_WIDTH - 4\n\n/** Maximum visible character length for an importer path inside the warning box. */\nexport const IMPORTER_MAX_LEN = CONTENT_AREA - 'Found in: '.length\n\n/**\n * Truncates an importer path to fit within maxLen visible characters.\n * Adds a leading '…' when truncation occurs so the rightmost (most specific) part is preserved.\n */\nexport function truncateImporter(importerPath: string, maxLen: number): string {\n if (importerPath.length <= maxLen)\n return importerPath\n return `\\u2026${importerPath.slice(-(maxLen - 1))}`\n}\n\nfunction boxTop(): string {\n return `${YELLOW}\\u250C${'─'.repeat(BOX_WIDTH - 2)}\\u2510${RESET}`\n}\n\nfunction boxBottom(): string {\n return `${YELLOW}\\u2514${'─'.repeat(BOX_WIDTH - 2)}\\u2518${RESET}`\n}\n\nfunction boxLine(visibleText: string, renderedText = visibleText): string {\n const rightPad = ' '.repeat(Math.max(0, CONTENT_AREA - visibleText.length))\n return `${YELLOW}\\u2502${RESET} ${renderedText}${rightPad}${YELLOW}\\u2502${RESET}`\n}\n\n/**\n * Renders the colored terminal warning box for 'warn' mode.\n * Every line is exactly 66 characters wide (visible chars, excluding ANSI codes),\n * assuming Vite environment names are short (≤19 chars). Longer names will extend\n * the line beyond 66 chars without crashing — Math.max(0) prevents negative padding.\n * Use in logger.warn() calls — not in log files.\n */\nexport function formatGuardWarning(fail: GuardFail): string {\n const importerDisplay = fail.importer === undefined\n ? '(unknown)'\n : truncateImporter(fail.importer, IMPORTER_MAX_LEN)\n\n const warnTitle = 'To enforce now: onClientAccessOfServerModule: \\'error\\''\n const stubTitle = 'To silence: onClientAccessOfServerModule: \\'stub\\''\n\n return [\n boxTop(),\n boxLine(\n '[vite-env] DEPRECATION WARNING',\n `${BOLD_YELLOW}[vite-env] DEPRECATION WARNING${RESET}`,\n ),\n boxLine(''),\n boxLine(`virtual:env/server was imported from the \"${fail.envName}\"`),\n boxLine('environment. This will be a hard build error in 1.0.0.'),\n boxLine(''),\n boxLine(warnTitle, `To enforce now: ${CYAN}onClientAccessOfServerModule: 'error'${RESET}`),\n boxLine(stubTitle, `To silence: ${CYAN}onClientAccessOfServerModule: 'stub'${RESET}`),\n boxLine(''),\n boxLine(`Found in: ${importerDisplay}`),\n boxBottom(),\n ].join('\\n')\n}\n\n/**\n * Renders the plain-text hard error message thrown in 'error' mode.\n * No ANSI — thrown as an Error message, not printed via logger.\n */\nexport function formatHardError(fail: GuardFail): string {\n const importerLine = fail.importer ?? '(unknown)'\n return [\n `[vite-env] virtual:env/server is not available in the \"${fail.envName}\" environment.`,\n ``,\n ` Server-only modules cannot be imported from client code.`,\n ` Add this environment to serverEnvironments if intentional:`,\n ``,\n ` ViteEnv({ serverEnvironments: ['ssr', '${fail.envName}'] })`,\n ``,\n ` Or change enforcement:`,\n ``,\n ` ViteEnv({ onClientAccessOfServerModule: 'stub' })`,\n ``,\n ` Imported from: ${importerLine}`,\n ].join('\\n')\n}\n\n/**\n * Renders a single ANSI-free log entry for vite-env-warnings.log.\n * Uses the same (unknown) convention as formatGuardWarning for missing importers.\n */\nexport function formatGuardLogEntry(fail: GuardFail, timestamp: string): string {\n const importerLine = fail.importer ?? '(unknown)'\n return [\n `[${timestamp}] virtual:env/server accessed from \"${fail.envName}\" environment`,\n ` Importer: ${importerLine}`,\n ].join('\\n')\n}\n"],"mappings":";;AAIA,SAAgB,eAAe,QAAkC;AAC/D,QAAO,OACJ,KAAK,UAAU;AAEd,SAAO,uBADM,MAAM,KAAK,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,6CAA6C,KAAK,QAAQ,GAAG;EACrE,QAAQ,yDAAyD;EACjE,QAAQ,GAAG;EACX,QAbgB,0DAaG,oBAAoB,KAAK,uCAAuC,QAAQ;EAC3F,QAbgB,yDAaG,oBAAoB,KAAK,sCAAsC,QAAQ;EAC1F,QAAQ,GAAG;EACX,QAAQ,aAAa,kBAAkB;EACvC,WAAW;EACZ,CAAC,KAAK,KAAK;;;;;;AAOd,SAAgB,gBAAgB,MAAyB;CACvD,MAAM,eAAe,KAAK,YAAY;AACtC,QAAO;EACL,0DAA0D,KAAK,QAAQ;EACvE;EACA;EACA;EACA;EACA,8CAA8C,KAAK,QAAQ;EAC3D;EACA;EACA;EACA;EACA;EACA,oBAAoB;EACrB,CAAC,KAAK,KAAK;;;;;;AAOd,SAAgB,oBAAoB,MAAiB,WAA2B;CAC9E,MAAM,eAAe,KAAK,YAAY;AACtC,QAAO,CACL,IAAI,UAAU,sCAAsC,KAAK,QAAQ,gBACjE,eAAe,eAChB,CAAC,KAAK,KAAK"}
package/dist/format.d.cts CHANGED
@@ -1,7 +1,48 @@
1
+ import { o as StandardValidationIssue } from "./types-1okexcwM.cjs";
1
2
  import { core } from "zod";
2
3
 
4
+ //#region src/guard.d.ts
5
+ type GuardMode = 'error' | 'stub' | 'warn';
6
+ type GuardResult = {
7
+ allowed: true;
8
+ } | {
9
+ allowed: false;
10
+ mode: GuardMode;
11
+ envName: string;
12
+ importer: string | undefined;
13
+ };
14
+ type GuardFail = Extract<GuardResult, {
15
+ allowed: false;
16
+ }>;
17
+ //#endregion
3
18
  //#region src/format.d.ts
4
19
  declare function formatZodError(issues: core.$ZodIssue[]): string;
20
+ declare function formatStandardSchemaError(issues: StandardValidationIssue[]): string;
21
+ /** Maximum visible character length for an importer path inside the warning box. */
22
+ declare const IMPORTER_MAX_LEN: number;
23
+ /**
24
+ * Truncates an importer path to fit within maxLen visible characters.
25
+ * Adds a leading '…' when truncation occurs so the rightmost (most specific) part is preserved.
26
+ */
27
+ declare function truncateImporter(importerPath: string, maxLen: number): string;
28
+ /**
29
+ * Renders the colored terminal warning box for 'warn' mode.
30
+ * Every line is exactly 66 characters wide (visible chars, excluding ANSI codes),
31
+ * assuming Vite environment names are short (≤19 chars). Longer names will extend
32
+ * the line beyond 66 chars without crashing — Math.max(0) prevents negative padding.
33
+ * Use in logger.warn() calls — not in log files.
34
+ */
35
+ declare function formatGuardWarning(fail: GuardFail): string;
36
+ /**
37
+ * Renders the plain-text hard error message thrown in 'error' mode.
38
+ * No ANSI — thrown as an Error message, not printed via logger.
39
+ */
40
+ declare function formatHardError(fail: GuardFail): string;
41
+ /**
42
+ * Renders a single ANSI-free log entry for vite-env-warnings.log.
43
+ * Uses the same (unknown) convention as formatGuardWarning for missing importers.
44
+ */
45
+ declare function formatGuardLogEntry(fail: GuardFail, timestamp: string): string;
5
46
  //#endregion
6
- export { formatZodError };
47
+ export { IMPORTER_MAX_LEN, formatGuardLogEntry, formatGuardWarning, formatHardError, formatStandardSchemaError, formatZodError, truncateImporter };
7
48
  //# sourceMappingURL=format.d.cts.map
package/dist/format.d.mts CHANGED
@@ -1,7 +1,48 @@
1
+ import { o as StandardValidationIssue } from "./types-DuWT_251.mjs";
1
2
  import { core } from "zod";
2
3
 
4
+ //#region src/guard.d.ts
5
+ type GuardMode = 'error' | 'stub' | 'warn';
6
+ type GuardResult = {
7
+ allowed: true;
8
+ } | {
9
+ allowed: false;
10
+ mode: GuardMode;
11
+ envName: string;
12
+ importer: string | undefined;
13
+ };
14
+ type GuardFail = Extract<GuardResult, {
15
+ allowed: false;
16
+ }>;
17
+ //#endregion
3
18
  //#region src/format.d.ts
4
19
  declare function formatZodError(issues: core.$ZodIssue[]): string;
20
+ declare function formatStandardSchemaError(issues: StandardValidationIssue[]): string;
21
+ /** Maximum visible character length for an importer path inside the warning box. */
22
+ declare const IMPORTER_MAX_LEN: number;
23
+ /**
24
+ * Truncates an importer path to fit within maxLen visible characters.
25
+ * Adds a leading '…' when truncation occurs so the rightmost (most specific) part is preserved.
26
+ */
27
+ declare function truncateImporter(importerPath: string, maxLen: number): string;
28
+ /**
29
+ * Renders the colored terminal warning box for 'warn' mode.
30
+ * Every line is exactly 66 characters wide (visible chars, excluding ANSI codes),
31
+ * assuming Vite environment names are short (≤19 chars). Longer names will extend
32
+ * the line beyond 66 chars without crashing — Math.max(0) prevents negative padding.
33
+ * Use in logger.warn() calls — not in log files.
34
+ */
35
+ declare function formatGuardWarning(fail: GuardFail): string;
36
+ /**
37
+ * Renders the plain-text hard error message thrown in 'error' mode.
38
+ * No ANSI — thrown as an Error message, not printed via logger.
39
+ */
40
+ declare function formatHardError(fail: GuardFail): string;
41
+ /**
42
+ * Renders a single ANSI-free log entry for vite-env-warnings.log.
43
+ * Uses the same (unknown) convention as formatGuardWarning for missing importers.
44
+ */
45
+ declare function formatGuardLogEntry(fail: GuardFail, timestamp: string): string;
5
46
  //#endregion
6
- export { formatZodError };
47
+ export { IMPORTER_MAX_LEN, formatGuardLogEntry, formatGuardWarning, formatHardError, formatStandardSchemaError, formatZodError, truncateImporter };
7
48
  //# sourceMappingURL=format.d.mts.map
package/dist/format.mjs CHANGED
@@ -4,7 +4,89 @@ function formatZodError(issues) {
4
4
  return ` \x1B[31m✗\x1B[0m ${(issue.path.length > 0 ? issue.path.join(".") : "(root)").padEnd(28)} ${issue.message}`;
5
5
  }).join("\n");
6
6
  }
7
+ function formatStandardSchemaError(issues) {
8
+ return issues.map((issue) => {
9
+ return ` \x1B[31m✗\x1B[0m ${(issue.path.length > 0 ? issue.path.map((seg) => typeof seg === "object" && seg !== null && "key" in seg ? String(seg.key) : String(seg)).join(".") : "(root)").padEnd(28)} ${issue.message}`;
10
+ }).join("\n");
11
+ }
12
+ const YELLOW = "\x1B[33m";
13
+ const BOLD_YELLOW = "\x1B[1;33m";
14
+ const CYAN = "\x1B[36m";
15
+ const RESET = "\x1B[0m";
16
+ const BOX_WIDTH = 66;
17
+ const CONTENT_AREA = BOX_WIDTH - 4;
18
+ /** Maximum visible character length for an importer path inside the warning box. */
19
+ const IMPORTER_MAX_LEN = CONTENT_AREA - 10;
20
+ /**
21
+ * Truncates an importer path to fit within maxLen visible characters.
22
+ * Adds a leading '…' when truncation occurs so the rightmost (most specific) part is preserved.
23
+ */
24
+ function truncateImporter(importerPath, maxLen) {
25
+ if (importerPath.length <= maxLen) return importerPath;
26
+ return `\u2026${importerPath.slice(-(maxLen - 1))}`;
27
+ }
28
+ function boxTop() {
29
+ return `${YELLOW}\u250C${"─".repeat(BOX_WIDTH - 2)}\u2510${RESET}`;
30
+ }
31
+ function boxBottom() {
32
+ return `${YELLOW}\u2514${"─".repeat(BOX_WIDTH - 2)}\u2518${RESET}`;
33
+ }
34
+ function boxLine(visibleText, renderedText = visibleText) {
35
+ return `${YELLOW}\u2502${RESET} ${renderedText}${" ".repeat(Math.max(0, CONTENT_AREA - visibleText.length))}${YELLOW}\u2502${RESET}`;
36
+ }
37
+ /**
38
+ * Renders the colored terminal warning box for 'warn' mode.
39
+ * Every line is exactly 66 characters wide (visible chars, excluding ANSI codes),
40
+ * assuming Vite environment names are short (≤19 chars). Longer names will extend
41
+ * the line beyond 66 chars without crashing — Math.max(0) prevents negative padding.
42
+ * Use in logger.warn() calls — not in log files.
43
+ */
44
+ function formatGuardWarning(fail) {
45
+ const importerDisplay = fail.importer === void 0 ? "(unknown)" : truncateImporter(fail.importer, 52);
46
+ return [
47
+ boxTop(),
48
+ boxLine("[vite-env] DEPRECATION WARNING", `${BOLD_YELLOW}[vite-env] DEPRECATION WARNING${RESET}`),
49
+ boxLine(""),
50
+ boxLine(`virtual:env/server was imported from the "${fail.envName}"`),
51
+ boxLine("environment. This will be a hard build error in 1.0.0."),
52
+ boxLine(""),
53
+ boxLine("To enforce now: onClientAccessOfServerModule: 'error'", `To enforce now: ${CYAN}onClientAccessOfServerModule: 'error'${RESET}`),
54
+ boxLine("To silence: onClientAccessOfServerModule: 'stub'", `To silence: ${CYAN}onClientAccessOfServerModule: 'stub'${RESET}`),
55
+ boxLine(""),
56
+ boxLine(`Found in: ${importerDisplay}`),
57
+ boxBottom()
58
+ ].join("\n");
59
+ }
60
+ /**
61
+ * Renders the plain-text hard error message thrown in 'error' mode.
62
+ * No ANSI — thrown as an Error message, not printed via logger.
63
+ */
64
+ function formatHardError(fail) {
65
+ const importerLine = fail.importer ?? "(unknown)";
66
+ return [
67
+ `[vite-env] virtual:env/server is not available in the "${fail.envName}" environment.`,
68
+ ``,
69
+ ` Server-only modules cannot be imported from client code.`,
70
+ ` Add this environment to serverEnvironments if intentional:`,
71
+ ``,
72
+ ` ViteEnv({ serverEnvironments: ['ssr', '${fail.envName}'] })`,
73
+ ``,
74
+ ` Or change enforcement:`,
75
+ ``,
76
+ ` ViteEnv({ onClientAccessOfServerModule: 'stub' })`,
77
+ ``,
78
+ ` Imported from: ${importerLine}`
79
+ ].join("\n");
80
+ }
81
+ /**
82
+ * Renders a single ANSI-free log entry for vite-env-warnings.log.
83
+ * Uses the same (unknown) convention as formatGuardWarning for missing importers.
84
+ */
85
+ function formatGuardLogEntry(fail, timestamp) {
86
+ const importerLine = fail.importer ?? "(unknown)";
87
+ return [`[${timestamp}] virtual:env/server accessed from "${fail.envName}" environment`, ` Importer: ${importerLine}`].join("\n");
88
+ }
7
89
  //#endregion
8
- export { formatZodError };
90
+ export { IMPORTER_MAX_LEN, formatGuardLogEntry, formatGuardWarning, formatHardError, formatStandardSchemaError, formatZodError, truncateImporter };
9
91
 
10
92
  //# sourceMappingURL=format.mjs.map