@vite-hub/env 0.0.4 → 0.3.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 (57) hide show
  1. package/README.md +288 -23
  2. package/dist/access-B8lSDip4.js +54 -0
  3. package/dist/bridge-Cs9YfQWk.d.ts +447 -0
  4. package/dist/bridge-error-BhJ77age.js +66 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +354 -0
  7. package/dist/cli-BPp7rdcA.d.ts +159 -0
  8. package/dist/cli-DLpY0QAo.js +669 -0
  9. package/dist/cli.d.ts +41 -0
  10. package/dist/cli.js +2 -0
  11. package/dist/database.d.ts +47 -0
  12. package/dist/database.js +274 -0
  13. package/dist/declarations-C5XR3aKw.d.ts +58 -0
  14. package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
  15. package/dist/index.d.ts +146 -11
  16. package/dist/index.js +240 -7
  17. package/dist/internal/agent.d.ts +5 -0
  18. package/dist/internal/agent.js +22 -0
  19. package/dist/internal/connections.d.ts +18 -0
  20. package/dist/internal/connections.js +31 -0
  21. package/dist/internal/server.d.ts +3 -0
  22. package/dist/internal/server.js +2 -0
  23. package/dist/object-_dlsZ4lP.js +276 -0
  24. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  25. package/dist/operations-X1w--wds.js +30 -0
  26. package/dist/operations.d.ts +37 -0
  27. package/dist/operations.js +833 -0
  28. package/dist/runtime/public-env.d.ts +5 -0
  29. package/dist/runtime/public-env.js +8 -0
  30. package/dist/runtime/server-env.d.ts +22 -0
  31. package/dist/runtime/server-env.js +35 -0
  32. package/dist/schema-DMZ1_yhY.js +360 -0
  33. package/dist/seal.d.ts +17 -0
  34. package/dist/seal.js +52 -0
  35. package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
  36. package/dist/server-ChNL_Xc3.js +1279 -0
  37. package/dist/server-Dd8bjIKd.d.ts +145 -0
  38. package/dist/server.d.ts +3 -8
  39. package/dist/server.js +2 -3
  40. package/dist/virtual-module.d.ts +9 -5
  41. package/dist/virtual.d.ts +1 -1
  42. package/dist/vite.d.ts +79 -21
  43. package/dist/vite.js +1095 -339
  44. package/package.json +81 -28
  45. package/dist/declarations-CoMmvRqH.js +0 -159
  46. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  47. package/dist/errors-C4Xcs6Fi.js +0 -121
  48. package/dist/presets.d.ts +0 -11
  49. package/dist/presets.js +0 -25
  50. package/dist/provider.d.ts +0 -6
  51. package/dist/provider.js +0 -7
  52. package/dist/schema.d.ts +0 -16
  53. package/dist/schema.js +0 -37
  54. package/dist/secret-C2191nAa.d.ts +0 -11
  55. package/dist/secret.d.ts +0 -2
  56. package/dist/server-C16sFc1E.js +0 -303
  57. package/dist/types-CsB6DTGE.d.ts +0 -190
@@ -0,0 +1,5 @@
1
+ import { B as PublicEnv } from "../bridge-Cs9YfQWk.js";
2
+ //#region src/runtime/public-env.d.ts
3
+ /** Reads the declared Public Env. Its values are fixed when the app builds. */
4
+ export declare function usePublicEnv(): PublicEnv;
5
+ //#endregion
@@ -0,0 +1,8 @@
1
+ import { t as envErrorDiagnostics } from "../error-diagnostics-B8RFjQ1V.js";
2
+ //#region src/runtime/public-env.ts
3
+ /** Reads the declared Public Env. Its values are fixed when the app builds. */
4
+ function usePublicEnv() {
5
+ throw envErrorDiagnostics.ENV_NOT_GENERATED({ accessor: "usePublicEnv" });
6
+ }
7
+ //#endregion
8
+ export { usePublicEnv };
@@ -0,0 +1,22 @@
1
+ import { G as ServerEnvInspection, H as ServerEnv, U as ServerEnvDescription, V as ReadonlyServerEnv, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
2
+ import { ViteHubContext } from "@vite-hub/runtime";
3
+ //#region src/runtime/server-env.d.ts
4
+ interface ServerEnvLoadOptions {
5
+ access?: EnvAccessContext;
6
+ signal?: AbortSignal;
7
+ }
8
+ /** Reads the declared Server Env. A missing required value throws `ENV_REQUIRED_MISSING`. */
9
+ export declare function useServerEnv(_event?: ViteHubContext): ServerEnv;
10
+ /** Loads one immutable Server Env snapshot, including provider-backed values. */
11
+ export declare function loadServerEnv(_event?: ViteHubContext, _options?: ServerEnvLoadOptions): Promise<ReadonlyServerEnv>;
12
+ /** Runs `callback` with a loaded Server Env snapshot. */
13
+ export declare function runWithServerEnv<T>(_event: ViteHubContext | undefined, _callback: (env: ReadonlyServerEnv) => T | Promise<T>, _options?: ServerEnvLoadOptions): Promise<T>;
14
+ /** Inspects the status of each Server Env value without returning values. */
15
+ export declare function inspectServerEnv(_event?: ViteHubContext, _options?: ServerEnvLoadOptions): Promise<ServerEnvInspection>;
16
+ /** Lists the Server Env declarations without reading host values or calling providers. */
17
+ export declare function describeServerEnv(): ServerEnvDescription;
18
+ /** Derives a purpose-specific secret from `VITEHUB_SECRET`. */
19
+ export declare function deriveSecret(_purpose: string, _event?: ViteHubContext): Promise<string>;
20
+ /** Answers the Env bridge requests of the Console. */
21
+ export declare function manageServerEnv(_request: Request): Promise<Response>;
22
+ //#endregion
@@ -0,0 +1,35 @@
1
+ import { t as envErrorDiagnostics } from "../error-diagnostics-B8RFjQ1V.js";
2
+ //#region src/runtime/server-env.ts
3
+ function notGenerated(accessor) {
4
+ throw envErrorDiagnostics.ENV_NOT_GENERATED({ accessor });
5
+ }
6
+ /** Reads the declared Server Env. A missing required value throws `ENV_REQUIRED_MISSING`. */
7
+ function useServerEnv(_event) {
8
+ return notGenerated("useServerEnv");
9
+ }
10
+ /** Loads one immutable Server Env snapshot, including provider-backed values. */
11
+ async function loadServerEnv(_event, _options) {
12
+ return notGenerated("loadServerEnv");
13
+ }
14
+ /** Runs `callback` with a loaded Server Env snapshot. */
15
+ async function runWithServerEnv(_event, _callback, _options) {
16
+ return notGenerated("runWithServerEnv");
17
+ }
18
+ /** Inspects the status of each Server Env value without returning values. */
19
+ async function inspectServerEnv(_event, _options) {
20
+ return notGenerated("inspectServerEnv");
21
+ }
22
+ /** Lists the Server Env declarations without reading host values or calling providers. */
23
+ function describeServerEnv() {
24
+ return notGenerated("describeServerEnv");
25
+ }
26
+ /** Derives a purpose-specific secret from `VITEHUB_SECRET`. */
27
+ async function deriveSecret(_purpose, _event) {
28
+ return notGenerated("deriveSecret");
29
+ }
30
+ /** Answers the Env bridge requests of the Console. */
31
+ async function manageServerEnv(_request) {
32
+ return notGenerated("manageServerEnv");
33
+ }
34
+ //#endregion
35
+ export { deriveSecret, describeServerEnv, inspectServerEnv, loadServerEnv, manageServerEnv, runWithServerEnv, useServerEnv };
@@ -0,0 +1,360 @@
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-B8RFjQ1V.js";
2
+ import { A as envValueTypeName, F as stringValueSchema, M as parseEnvValue, N as readJsonInput, j as listItemKinds } from "./server-ChNL_Xc3.js";
3
+ //#region src/internal/runtime-type.ts
4
+ function isRuntimeRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ //#endregion
8
+ //#region src/core/declarations.ts
9
+ const runtimeSchemaProperty = "__vitehubRuntimeSchema";
10
+ const runtimeSchemaToken = getRuntimeSchemaToken();
11
+ const runtimeSchemaParsers = /* @__PURE__ */ new WeakMap();
12
+ const runtimeSchemas = /* @__PURE__ */ new WeakMap();
13
+ function createRuntimeValueSchema(valueSchema) {
14
+ const safeParse = (input) => {
15
+ const result = parseEnvValue(valueSchema, input);
16
+ return result.success ? result : {
17
+ error: envErrorDiagnostics.ENV_R0001({ message: result.message }),
18
+ success: false
19
+ };
20
+ };
21
+ runtimeSchemaParsers.set(safeParse, valueSchema);
22
+ return {
23
+ [runtimeSchemaProperty]: runtimeSchemaToken,
24
+ safeParse
25
+ };
26
+ }
27
+ const defaultStringSchema = createRuntimeValueSchema(stringValueSchema);
28
+ const booleanSchema = createRuntimeValueSchema(Object.freeze({ kind: "boolean" }));
29
+ const numberSchema = createRuntimeValueSchema(Object.freeze({ kind: "number" }));
30
+ function source(name, options = {}) {
31
+ const names = Array.isArray(name) ? name : [name];
32
+ if (!names.length || names.some((value) => typeof value !== "string" || !value.trim())) throw envErrorDiagnostics.ENV_R0002({ message: "env.source() requires one or more non-empty env variable names." });
33
+ const normalized = names.map((value) => value.trim());
34
+ return {
35
+ kind: "env",
36
+ label: `env:${normalized.join("|")}`,
37
+ name: normalized[0],
38
+ ...options.canonical === false ? { canonical: false } : {},
39
+ ...normalized.length > 1 ? { names: normalized } : {},
40
+ serializable: true
41
+ };
42
+ }
43
+ function custom(label, resolver) {
44
+ return {
45
+ kind: "custom",
46
+ label,
47
+ resolver,
48
+ serializable: false
49
+ };
50
+ }
51
+ function gitBranch() {
52
+ return {
53
+ kind: "git-branch",
54
+ label: "git:branch",
55
+ serializable: true
56
+ };
57
+ }
58
+ function gitCommit(options = {}) {
59
+ return {
60
+ kind: "git-commit",
61
+ label: "git:commit",
62
+ serializable: true,
63
+ short: options.short
64
+ };
65
+ }
66
+ function gitTag() {
67
+ return {
68
+ kind: "git-tag",
69
+ label: "git:tag",
70
+ serializable: true
71
+ };
72
+ }
73
+ function buildTimestamp() {
74
+ return {
75
+ kind: "build-timestamp",
76
+ label: "build:timestamp",
77
+ serializable: true
78
+ };
79
+ }
80
+ function packageJson(path) {
81
+ return {
82
+ kind: "package-json",
83
+ label: `package.json:${path}`,
84
+ path,
85
+ serializable: true
86
+ };
87
+ }
88
+ function provider(provider, key) {
89
+ if (typeof provider !== "string" || !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(provider.trim())) throw envErrorDiagnostics.ENV_R0003({ message: "env.provider() requires a provider name that starts with a letter and contains only letters, numbers, underscores, or hyphens." });
90
+ if (typeof key !== "string" || !key.trim() || key.length > 512) throw envErrorDiagnostics.ENV_R0004({ message: "env.provider() requires a non-empty provider key." });
91
+ return {
92
+ key: key.trim(),
93
+ kind: "provider",
94
+ label: "provider",
95
+ provider: provider.trim(),
96
+ serializable: true
97
+ };
98
+ }
99
+ function schemaFrom(module, exportName = "default") {
100
+ if (typeof module !== "string" || !module.trim()) throw envErrorDiagnostics.ENV_R0029({ message: "env.schemaFrom() requires a non-empty module specifier." });
101
+ if (typeof exportName !== "string" || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(exportName)) throw envErrorDiagnostics.ENV_R0029({ message: "env.schemaFrom() requires an export name that is a JavaScript identifier." });
102
+ return Object.freeze({
103
+ kind: "schema-module",
104
+ module: module.trim(),
105
+ export: exportName
106
+ });
107
+ }
108
+ /** Return the module reference of a declaration whose schema comes from `env.schemaFrom()`. */
109
+ function schemaModuleReference(schema) {
110
+ try {
111
+ if (!isRuntimeRecord(schema) || schema.kind !== "schema-module") return void 0;
112
+ return typeof schema.module === "string" && typeof schema.export === "string" ? {
113
+ kind: "schema-module",
114
+ module: schema.module,
115
+ export: schema.export,
116
+ ...schema.input === "json" ? { input: "json" } : {}
117
+ } : void 0;
118
+ } catch {
119
+ return;
120
+ }
121
+ }
122
+ function variable(options = {}) {
123
+ const snapshot = readDeclarationOptions(options);
124
+ return createDeclaration(snapshot, snapshot.schema ?? defaultStringSchema, snapshot.type);
125
+ }
126
+ function typedVariable(schema, options) {
127
+ const snapshot = readDeclarationOptions(options);
128
+ const valueSchema = runtimeSchemaParsers.get(schema.safeParse);
129
+ return createDeclaration(snapshot, schema, valueSchema && envValueTypeName(valueSchema));
130
+ }
131
+ /** Create an internal built-in declaration whose parser survives runtime serialization. */
132
+ function descriptorVariable(valueSchema, options) {
133
+ return typedVariable(createRuntimeValueSchema(valueSchema), options);
134
+ }
135
+ function booleanVariable(options = {}) {
136
+ return typedVariable(booleanSchema, options);
137
+ }
138
+ function numberVariable(options = {}) {
139
+ return typedVariable(numberSchema, options);
140
+ }
141
+ function enumVariable(values, options = {}) {
142
+ if (!Array.isArray(values) || !values.length || values.some((value) => typeof value !== "string" || !value) || new Set(values).size !== values.length) throw envErrorDiagnostics.ENV_R0022({ message: "env.enum() requires one or more unique non-empty strings." });
143
+ return typedVariable(createRuntimeValueSchema(Object.freeze({
144
+ kind: "enum",
145
+ values: Object.freeze([...values])
146
+ })), options);
147
+ }
148
+ function listVariable(itemOrOptions, options) {
149
+ if (!isDeclaration(itemOrOptions)) {
150
+ if (options !== void 0) throw envErrorDiagnostics.ENV_LIST_ITEM_INVALID({ message: "env.list() takes the item parser first, for example env.list(env.number(), { default: [1] })." });
151
+ return typedVariable(createRuntimeValueSchema(Object.freeze({ kind: "list" })), itemOrOptions ?? {});
152
+ }
153
+ const items = runtimeValueSchema(itemOrOptions);
154
+ if (!items || !listItemKinds.has(items.kind) || itemOrOptions.source !== void 0 || itemOrOptions.default !== void 0 || itemOrOptions.secret || !itemOrOptions.required || itemOrOptions.mode !== "runtime") throw envErrorDiagnostics.ENV_LIST_ITEM_INVALID({ message: "env.list() takes an item parser without options: env(), env.boolean(), env.number(), or env.enum([...]). Put the options on the list, for example env.list(env.number(), { default: [1] })." });
155
+ return typedVariable(createRuntimeValueSchema(Object.freeze({
156
+ items,
157
+ kind: "list"
158
+ })), options ?? {});
159
+ }
160
+ function jsonVariable(schemaOrOptions, options) {
161
+ const reference = schemaModuleReference(schemaOrOptions);
162
+ if (reference) return createDeclaration(readDeclarationOptions(options ?? {}), Object.freeze({
163
+ ...reference,
164
+ input: "json"
165
+ }), void 0);
166
+ if (isStandardSchemaLike(schemaOrOptions)) {
167
+ const snapshot = readDeclarationOptions(options ?? {});
168
+ if (snapshot.mode !== "build") throw envErrorDiagnostics.ENV_JSON_SCHEMA_INVALID({ message: "env.json() in env.server runs in the server build, so it cannot take a schema object from the config. Export the schema from a module and pass env.schemaFrom(), for example env.json(env.schemaFrom('./server/env.schema.ts', 'settings')). A schema object works only with mode: 'build'." });
169
+ return createDeclaration(snapshot, jsonStandardSchema(schemaOrOptions), void 0);
170
+ }
171
+ if (isSchemaModule(schemaOrOptions) || options !== void 0 || isRuntimeRecord(schemaOrOptions) && ("kind" in schemaOrOptions || "~standard" in schemaOrOptions)) throw envErrorDiagnostics.ENV_JSON_SCHEMA_INVALID({ message: "env.json() takes env.schemaFrom(), a Standard Schema, or only options." });
172
+ return typedVariable(createRuntimeValueSchema(Object.freeze({ kind: "json" })), schemaOrOptions ?? {});
173
+ }
174
+ /** Wrap a build-time Standard Schema so that it gets the parsed JSON value. */
175
+ function jsonStandardSchema(schema) {
176
+ const validate = schema["~standard"].validate;
177
+ return { "~standard": { validate: (value) => {
178
+ const json = readJsonInput(value);
179
+ return json.success ? validate(json.data) : { issues: [{ message: json.message }] };
180
+ } } };
181
+ }
182
+ function isSchemaModule(value) {
183
+ return schemaModuleReference(value) !== void 0;
184
+ }
185
+ function isStandardSchemaLike(value) {
186
+ try {
187
+ if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
188
+ const standard = Reflect.get(value, "~standard");
189
+ return isRuntimeRecord(standard) && typeof standard.validate === "function";
190
+ } catch {
191
+ return false;
192
+ }
193
+ }
194
+ function isDeclaration(value) {
195
+ try {
196
+ return isRuntimeRecord(value) && value.kind === "env-variable";
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ function isInspectableRecord(value) {
202
+ try {
203
+ if (!isRuntimeRecord(value)) return false;
204
+ Reflect.ownKeys(value);
205
+ return true;
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
210
+ function readDeclarationOptions(options) {
211
+ if (!isInspectableRecord(options)) throw envErrorDiagnostics.ENV_R0005({ message: "env() only accepts a single options object." });
212
+ let snapshot;
213
+ let required;
214
+ try {
215
+ required = Reflect.get(options, "required");
216
+ snapshot = {
217
+ default: options.default,
218
+ mode: options.mode,
219
+ optional: options.optional === true,
220
+ schema: options.schema,
221
+ secret: options.secret,
222
+ source: options.source,
223
+ type: options.type
224
+ };
225
+ } catch {
226
+ throw envErrorDiagnostics.ENV_R0005({ message: "env() only accepts a single options object." });
227
+ }
228
+ if (required !== void 0) throw envErrorDiagnostics.ENV_R0006({ message: "env() does not accept required. A value is required by default. Use optional: true for a value that can be missing." });
229
+ if (snapshot.optional && snapshot.default !== void 0) throw envErrorDiagnostics.ENV_R0006({ message: "env() cannot use both optional and default. A default makes the value always present." });
230
+ return snapshot;
231
+ }
232
+ function createDeclaration(options, schema, type) {
233
+ const required = !options.optional;
234
+ const source = typeof options.source === "function" ? custom("custom", options.source) : options.source;
235
+ const declaration = {
236
+ default: options.default,
237
+ kind: "env-variable",
238
+ mode: options.mode ?? "runtime",
239
+ required,
240
+ schema,
241
+ secret: options.secret ?? false,
242
+ source,
243
+ type
244
+ };
245
+ if (isRuntimeValueSchema(schema)) {
246
+ runtimeSchemas.set(declaration, schema);
247
+ Object.defineProperty(declaration, runtimeSchemaProperty, {
248
+ enumerable: true,
249
+ value: runtimeSchemaToken
250
+ });
251
+ }
252
+ return declaration;
253
+ }
254
+ const env = Object.assign(variable, {
255
+ boolean: booleanVariable,
256
+ buildTimestamp,
257
+ custom,
258
+ enum: enumVariable,
259
+ gitBranch,
260
+ gitCommit,
261
+ gitTag,
262
+ json: jsonVariable,
263
+ list: listVariable,
264
+ number: numberVariable,
265
+ packageJson,
266
+ provider,
267
+ schemaFrom,
268
+ source
269
+ });
270
+ /** Return the serializable value schema of a declaration created by `env()`, `env.boolean()`, `env.number()`, or `env.enum()`. */
271
+ function runtimeValueSchema(declaration) {
272
+ const schema = declaration.schema;
273
+ if (runtimeSchemas.get(declaration) === schema && isRuntimeValueSchema(schema)) return runtimeSchemaParsers.get(schema.safeParse);
274
+ try {
275
+ if (Object.getOwnPropertyDescriptor(declaration, runtimeSchemaProperty)?.value !== runtimeSchemaToken || !isRuntimeRecord(schema)) return void 0;
276
+ if (Object.getOwnPropertyDescriptor(schema, runtimeSchemaProperty)?.value !== runtimeSchemaToken || !hasOnlyRuntimeSchemaKeys(schema)) return void 0;
277
+ const safeParse = Object.getOwnPropertyDescriptor(schema, "safeParse")?.value;
278
+ return typeof safeParse === "function" ? runtimeSchemaParsers.get(safeParse) : void 0;
279
+ } catch {
280
+ return;
281
+ }
282
+ }
283
+ function isRuntimeValueSchema(schema) {
284
+ try {
285
+ return isRuntimeRecord(schema) && typeof schema.safeParse === "function" && runtimeSchemaParsers.has(schema.safeParse);
286
+ } catch {
287
+ return false;
288
+ }
289
+ }
290
+ function getRuntimeSchemaToken() {
291
+ const tokenKey = Symbol.for("vitehub.env.runtimeSchemaToken");
292
+ const globalScope = globalThis;
293
+ globalScope[tokenKey] ??= `schema:${Math.random().toString(36).slice(2)}`;
294
+ return globalScope[tokenKey];
295
+ }
296
+ function hasOnlyRuntimeSchemaKeys(schema) {
297
+ if ("~standard" in schema || "parse" in schema) return false;
298
+ const keys = Reflect.ownKeys(schema);
299
+ const safeParse = Object.getOwnPropertyDescriptor(schema, "safeParse");
300
+ return keys.length === 2 && keys.includes(runtimeSchemaProperty) && keys.includes("safeParse") && typeof safeParse?.value === "function";
301
+ }
302
+ //#endregion
303
+ //#region src/schema.ts
304
+ function parseSchema(schema, value, label) {
305
+ if (isSchemaModuleReference(schema)) throw envErrorDiagnostics.ENV_R0029({ message: `[vitehub] ${label} uses env.schemaFrom(), which only env.server supports. Pass the schema object itself.` });
306
+ if (isStandardSchema(schema)) {
307
+ const result = schema["~standard"].validate(value);
308
+ if (isPromiseLike(result)) throw envErrorDiagnostics.ENV_R0014({ message: `[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.` });
309
+ if ("issues" in result && result.issues && result.issues.length > 0) throw envErrorDiagnostics.ENV_R0015({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
310
+ if (!("value" in result)) throw envErrorDiagnostics.ENV_R0016({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
311
+ return result.value;
312
+ }
313
+ if (isZodLike(schema) && hasSchemaMethod(schema, "safeParse") && typeof schema.safeParse === "function") {
314
+ const result = schema.safeParse(value);
315
+ if (!result.success) throw envErrorDiagnostics.ENV_R0017({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.error)}` });
316
+ return result.data;
317
+ }
318
+ if (isZodLike(schema) && hasSchemaMethod(schema, "parse") && typeof schema.parse === "function") try {
319
+ return schema.parse(value);
320
+ } catch (error) {
321
+ throw envErrorDiagnostics.ENV_R0018({ message: `[vitehub] Invalid ${label}: ${formatIssues(error)}` });
322
+ }
323
+ return value;
324
+ }
325
+ function isSchemaModuleReference(schema) {
326
+ return typeof schema === "object" && schema !== null && !Array.isArray(schema) && schema.kind === "schema-module";
327
+ }
328
+ function isPromiseLike(value) {
329
+ return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
330
+ }
331
+ function isStandardSchema(schema) {
332
+ return isZodLike(schema) && hasSchemaMethod(schema, "~standard") && typeof schema["~standard"]?.validate === "function";
333
+ }
334
+ function isZodLike(schema) {
335
+ return typeof schema === "object" && schema !== null;
336
+ }
337
+ function hasSchemaMethod(schema, method) {
338
+ return Object.hasOwn(schema, method) || isZodSchemaMethod(schema, method);
339
+ }
340
+ function isZodSchemaMethod(schema, method) {
341
+ if (!Object.hasOwn(schema, "_zod")) return false;
342
+ const metadata = schema._zod;
343
+ if (!metadata) return false;
344
+ const constructor = metadata?.constr;
345
+ return hasSetValue(metadata?.traits, "ZodType") && Object.hasOwn(metadata, "constr") && typeof constructor === "function" && Object.getPrototypeOf(schema) === constructor.prototype && Object.hasOwn(constructor.prototype, method);
346
+ }
347
+ function hasSetValue(value, entry) {
348
+ try {
349
+ return Set.prototype.has.call(value, entry);
350
+ } catch {
351
+ return false;
352
+ }
353
+ }
354
+ function formatIssues(issues) {
355
+ if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
356
+ if (issues instanceof Error) return issues.message;
357
+ return typeof issues === "string" ? issues : JSON.stringify(issues);
358
+ }
359
+ //#endregion
360
+ export { schemaModuleReference as a, runtimeValueSchema as i, descriptorVariable as n, env as r, parseSchema as t };
package/dist/seal.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ //#region src/seal.d.ts
2
+ /** Stored sealed value format: `hex(iv):hex(ciphertext)`. */
3
+ export declare const sealedPayloadPattern: RegExp;
4
+ /** An imported AES-GCM key. */
5
+ export type SealKey = Awaited<ReturnType<typeof crypto.subtle.importKey>>;
6
+ /** Imports a 32-byte AES-GCM key for `sealWithKey` and `unsealWithKey`. */
7
+ export declare function importSealKey(key: Uint8Array): Promise<SealKey>;
8
+ /** Returns a stable public identifier for a raw key: the first 8 bytes of its SHA-256 digest, in hex. */
9
+ export declare function sealKeyId(key: Uint8Array): Promise<string>;
10
+ /**
11
+ * Encrypts `plaintext` with AES-GCM under a key that the caller owns, and binds it to `additionalData`.
12
+ * To seal an app value with a key derived from `VITEHUB_SECRET`, use `seal()` from `@vite-hub/env`.
13
+ */
14
+ export declare function sealWithKey(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, plaintext: string): Promise<string>;
15
+ /** Decrypts a value from `sealWithKey`. Fails when the key or `additionalData` differs. */
16
+ export declare function unsealWithKey(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, payload: string): Promise<string>;
17
+ //#endregion
package/dist/seal.js ADDED
@@ -0,0 +1,52 @@
1
+ import { ViteHubError } from "@vite-hub/runtime";
2
+ //#region src/seal.ts
3
+ /** Stored sealed value format: `hex(iv):hex(ciphertext)`. */
4
+ const sealedPayloadPattern = /^[a-f0-9]{24}:(?:[a-f0-9]{2}){16,}$/;
5
+ function sealError() {
6
+ return new ViteHubError("SEAL_INVALID", "Invalid sealed value or key.");
7
+ }
8
+ function hex(value) {
9
+ return Array.from(value, (byte) => byte.toString(16).padStart(2, "0")).join("");
10
+ }
11
+ function bytes(value) {
12
+ if (!/^(?:[a-f0-9]{2})+$/.test(value)) throw sealError();
13
+ return Uint8Array.from(value.match(/../g), (byte) => Number.parseInt(byte, 16));
14
+ }
15
+ /** Imports a 32-byte AES-GCM key for `sealWithKey` and `unsealWithKey`. */
16
+ function importSealKey(key) {
17
+ if (key.byteLength !== 32) throw sealError();
18
+ return crypto.subtle.importKey("raw", new Uint8Array(key), "AES-GCM", false, ["encrypt", "decrypt"]);
19
+ }
20
+ /** Returns a stable public identifier for a raw key: the first 8 bytes of its SHA-256 digest, in hex. */
21
+ async function sealKeyId(key) {
22
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(key));
23
+ return hex(new Uint8Array(digest).slice(0, 8));
24
+ }
25
+ /**
26
+ * Encrypts `plaintext` with AES-GCM under a key that the caller owns, and binds it to `additionalData`.
27
+ * To seal an app value with a key derived from `VITEHUB_SECRET`, use `seal()` from `@vite-hub/env`.
28
+ */
29
+ async function sealWithKey(key, additionalData, plaintext) {
30
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
31
+ const encrypted = await crypto.subtle.encrypt({
32
+ name: "AES-GCM",
33
+ iv,
34
+ additionalData
35
+ }, key, new TextEncoder().encode(plaintext));
36
+ return `${hex(iv)}:${hex(new Uint8Array(encrypted))}`;
37
+ }
38
+ /** Decrypts a value from `sealWithKey`. Fails when the key or `additionalData` differs. */
39
+ async function unsealWithKey(key, additionalData, payload) {
40
+ if (!sealedPayloadPattern.test(payload)) throw sealError();
41
+ const [iv, ciphertext] = payload.split(":");
42
+ const value = await crypto.subtle.decrypt({
43
+ name: "AES-GCM",
44
+ iv: bytes(iv),
45
+ additionalData
46
+ }, key, bytes(ciphertext)).catch(() => {
47
+ throw sealError();
48
+ });
49
+ return new TextDecoder("utf-8", { ignoreBOM: true }).decode(value);
50
+ }
51
+ //#endregion
52
+ export { importSealKey, sealKeyId, sealWithKey, sealedPayloadPattern, unsealWithKey };
@@ -23,4 +23,4 @@ Object.defineProperty(SecretEnv.prototype, Symbol.for("nodejs.util.inspect.custo
23
23
  return redactedSecret;
24
24
  } });
25
25
  //#endregion
26
- export { SecretEnv };
26
+ export { SecretEnv as t };