@vite-hub/env 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +3 -3
  2. package/dist/{access-B8lSDip4.js → access-DIErLk3w.js} +2 -3
  3. package/dist/{bridge-Cs9YfQWk.d.ts → bridge-BWwIooe0.d.ts} +0 -12
  4. package/dist/{bridge-error-BhJ77age.js → bridge-error-DEqzARPJ.js} +1 -3
  5. package/dist/bridge.d.ts +1 -1
  6. package/dist/bridge.js +9 -10
  7. package/dist/{cli-BPp7rdcA.d.ts → cli-B-LW6l_J.d.ts} +1 -6
  8. package/dist/cli-CAlHK5nn.js +1354 -0
  9. package/dist/cli.d.ts +3 -6
  10. package/dist/cli.js +1 -2
  11. package/dist/database.d.ts +2 -4
  12. package/dist/database.js +2 -5
  13. package/dist/{declarations-C5XR3aKw.d.ts → declarations-DNjO52_s.d.ts} +1 -21
  14. package/dist/{schema-C_a0WZyd.js → declarations-meg4Rmgd.js} +43 -105
  15. package/dist/{object-C7Jt4ez2.js → error-diagnostics-5BceFRdD.js} +57 -14
  16. package/dist/{error-diagnostics-DsDPsST_.js → error-diagnostics-BFzFaXcH.js} +2 -4
  17. package/dist/index.d.ts +3 -13
  18. package/dist/index.js +8 -12
  19. package/dist/internal/agent.d.ts +2 -4
  20. package/dist/internal/agent.js +3 -4
  21. package/dist/internal/connections.d.ts +2 -4
  22. package/dist/internal/connections.js +3 -4
  23. package/dist/internal/server.d.ts +2 -2
  24. package/dist/internal/server.js +1 -2
  25. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  26. package/dist/{operations-B1PFpKzy.js → operations-BftegDMd.js} +2 -3
  27. package/dist/operations.d.ts +2 -6
  28. package/dist/operations.js +7 -41
  29. package/dist/runtime/public-env.d.ts +2 -4
  30. package/dist/runtime/public-env.js +2 -3
  31. package/dist/runtime/server-env.d.ts +2 -3
  32. package/dist/runtime/server-env.js +2 -3
  33. package/dist/seal.d.ts +1 -3
  34. package/dist/seal.js +1 -2
  35. package/dist/{secret-DJd-fy5T.js → secret-VhbE53Vm.js} +1 -2
  36. package/dist/{server-CgKAEAE6.d.ts → server-CPEywepM.d.ts} +1 -12
  37. package/dist/{server-B9-8r6MZ.js → server-pTqnkM7n.js} +213 -168
  38. package/dist/server.d.ts +2 -2
  39. package/dist/server.js +1 -2
  40. package/dist/vite.d.ts +5 -17
  41. package/dist/vite.js +20 -37
  42. package/package.json +11 -10
  43. package/dist/cli-C51D6V-M.js +0 -669
@@ -1,13 +1,196 @@
1
- import { t as envErrorDiagnostics } from "./error-diagnostics-DsDPsST_.js";
2
- import { t as SecretEnv } from "./secret-DJd-fy5T.js";
3
- import { r as internalErrorDiagnostics, t as isRecord } from "./object-C7Jt4ez2.js";
1
+ import { a as isRecordOrFunction, i as isRecord, r as standardResultIssues, t as internalErrorDiagnostics } from "./error-diagnostics-5BceFRdD.js";
2
+ import { t as envErrorDiagnostics } from "./error-diagnostics-BFzFaXcH.js";
3
+ import { t as SecretEnv } from "./secret-VhbE53Vm.js";
4
4
  import { defineDiagnostics } from "nostics";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
5
  import { ViteHubError, defineErrors, isViteHubError, parseDuration } from "@vite-hub/runtime";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
8
8
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
9
9
  import * as v from "valibot";
10
- //#region src/core/json-value.ts
10
+ // src/core/errors.ts
11
+ const envErrorMessages = {
12
+ ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
13
+ ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
14
+ ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
15
+ ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
16
+ ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
17
+ };
18
+ const envSourceIdentifierSet = /* @__PURE__ */ new Set([
19
+ "custom",
20
+ "env",
21
+ "git:branch",
22
+ "git:commit",
23
+ "git:tag",
24
+ "package.json",
25
+ "provider"
26
+ ]);
27
+ function createEnvError(options, message = envErrorMessages[options.code]) {
28
+ const { code, cause, details } = options;
29
+ return new ViteHubError(code, message, {
30
+ ...cause === void 0 ? {} : { cause },
31
+ ...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
32
+ });
33
+ }
34
+ function invalidEnvDeclaration(path, diagnostic, cause) {
35
+ return createEnvError({
36
+ cause: envErrorDiagnostics.ENV_R0008({
37
+ message: diagnostic,
38
+ ...cause === void 0 ? {} : { cause }
39
+ }),
40
+ code: "ENV_DECLARATION_INVALID",
41
+ details: optionalPath(path)
42
+ });
43
+ }
44
+ function asyncServerEnvRequired(path) {
45
+ return createEnvError({
46
+ cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
47
+ code: "ENV_ASYNC_REQUIRED",
48
+ details: optionalPath(path)
49
+ });
50
+ }
51
+ /**
52
+ * The message and details name the declaration path and the variables that can supply it, so the operator
53
+ * knows what to set. Names are not secret; the value never appears because there is none.
54
+ */
55
+ function missingRequiredEnv(source, diagnostic, path, names = []) {
56
+ const pathDetails = optionalPath(path);
57
+ const variables = names.filter(isEnvVariableName).slice(0, 8);
58
+ const subject = pathDetails.path ? `Required Env value ${pathDetails.path} is missing.` : "Required Env value is missing.";
59
+ const supply = variables.length ? ` Set ${variables.join(" or ")}.` : "";
60
+ return createEnvError({
61
+ cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
62
+ code: "ENV_REQUIRED_MISSING",
63
+ details: {
64
+ ...variables.length ? { names: variables } : {},
65
+ ...pathDetails,
66
+ source: publicSourceIdentifier(source)
67
+ }
68
+ }, `[vitehub] ${subject}${supply}`);
69
+ }
70
+ function isEnvVariableName(name) {
71
+ return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
72
+ }
73
+ function invalidRuntimeEnvValue(source, diagnostic, path) {
74
+ return createEnvError({
75
+ cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
76
+ code: "ENV_RUNTIME_VALUE_INVALID",
77
+ details: {
78
+ ...optionalPath(path),
79
+ source: publicSourceIdentifier(source)
80
+ }
81
+ });
82
+ }
83
+ function envSourceFailed(source, cause) {
84
+ return createEnvError({
85
+ cause,
86
+ code: "ENV_SOURCE_FAILED",
87
+ details: { source: publicSourceIdentifier(source) }
88
+ });
89
+ }
90
+ function isAbortError(value) {
91
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
92
+ try {
93
+ return value.name === "AbortError";
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ function publicSourceIdentifier(source) {
99
+ if (envSourceIdentifierSet.has(source)) return source;
100
+ if (source.startsWith("env:")) return "env";
101
+ if (source.startsWith("package.json:")) return "package.json";
102
+ return "custom";
103
+ }
104
+ function optionalPath(path) {
105
+ const normalized = safePath(path);
106
+ return normalized ? { path: normalized } : {};
107
+ }
108
+ function safePath(path) {
109
+ if (typeof path !== "string" || path.length > 256) return void 0;
110
+ return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
111
+ }
112
+ // src/schema.ts
113
+ function parseSchema(schema, value, label) {
114
+ if (isSchemaModuleReference(schema)) throw envErrorDiagnostics.ENV_R0029({ message: `[vitehub] ${label} uses env.schemaFrom(), which only env.server supports. Pass the schema object itself.` });
115
+ const validate = readStandardValidate(schema, label);
116
+ if (validate) {
117
+ const result = validate(value);
118
+ if (isPromiseLike$1(result)) throw envErrorDiagnostics.ENV_R0014({ message: `[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.` });
119
+ const issues = standardResultIssues(result);
120
+ if (issues) throw envErrorDiagnostics.ENV_R0015({ message: `[vitehub] Invalid ${label}: ${formatStandardIssues(issues)}` });
121
+ if (!hasResultValue(result)) throw envErrorDiagnostics.ENV_R0016({ message: `[vitehub] Invalid ${label}: the schema returned no value.` });
122
+ return result.value;
123
+ }
124
+ if (isZodLike(schema) && hasSchemaMethod(schema, "safeParse") && typeof schema.safeParse === "function") {
125
+ const result = schema.safeParse(value);
126
+ if (!result.success) throw envErrorDiagnostics.ENV_R0017({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.error)}` });
127
+ return result.data;
128
+ }
129
+ if (isZodLike(schema) && hasSchemaMethod(schema, "parse") && typeof schema.parse === "function") try {
130
+ return schema.parse(value);
131
+ } catch (error) {
132
+ throw envErrorDiagnostics.ENV_R0018({ message: `[vitehub] Invalid ${label}: ${formatIssues(error)}` });
133
+ }
134
+ return value;
135
+ }
136
+ function readStandardValidate(schema, label) {
137
+ if (!isRecordOrFunction(schema)) return void 0;
138
+ try {
139
+ const standard = Reflect.get(schema, "~standard");
140
+ if (!isRecordOrFunction(standard)) return void 0;
141
+ const validate = Reflect.get(standard, "validate");
142
+ if (typeof validate !== "function") return void 0;
143
+ return (input) => Reflect.apply(validate, standard, [input]);
144
+ } catch (error) {
145
+ throw invalidEnvDeclaration(label, `${label} has a schema that threw while ViteHub read its \`~standard\` validator.`, error);
146
+ }
147
+ }
148
+ function isSchemaModuleReference(schema) {
149
+ return typeof schema === "object" && schema !== null && !Array.isArray(schema) && schema.kind === "schema-module";
150
+ }
151
+ function isPromiseLike$1(value) {
152
+ return isRecordOrFunction(value) && typeof value.then === "function";
153
+ }
154
+ function hasResultValue(result) {
155
+ return isRecordOrFunction(result) && "value" in result;
156
+ }
157
+ function formatStandardIssues(issues) {
158
+ return issues.map((issue) => {
159
+ if (typeof issue === "string") return issue;
160
+ const message = isRecordOrFunction(issue) && typeof issue.message === "string" ? issue.message : "Invalid value.";
161
+ const segments = isRecordOrFunction(issue) && Array.isArray(issue.path) ? Array.from(issue.path, issuePathKey).filter((segment) => typeof segment === "string" || typeof segment === "number") : [];
162
+ return segments.length ? `${segments.join(".")}: ${message}` : message;
163
+ }).join("; ");
164
+ }
165
+ function issuePathKey(segment) {
166
+ return isRecordOrFunction(segment) ? segment.key : segment;
167
+ }
168
+ function isZodLike(schema) {
169
+ return typeof schema === "object" && schema !== null;
170
+ }
171
+ function hasSchemaMethod(schema, method) {
172
+ return Object.hasOwn(schema, method) || isZodSchemaMethod(schema, method);
173
+ }
174
+ function isZodSchemaMethod(schema, method) {
175
+ if (!Object.hasOwn(schema, "_zod")) return false;
176
+ const metadata = schema._zod;
177
+ if (!metadata) return false;
178
+ const constructor = metadata?.constr;
179
+ return hasSetValue(metadata?.traits, "ZodType") && Object.hasOwn(metadata, "constr") && typeof constructor === "function" && Object.getPrototypeOf(schema) === constructor.prototype && Object.hasOwn(constructor.prototype, method);
180
+ }
181
+ function hasSetValue(value, entry) {
182
+ try {
183
+ return Set.prototype.has.call(value, entry);
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ function formatIssues(issues) {
189
+ if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
190
+ if (issues instanceof Error) return issues.message;
191
+ return typeof issues === "string" ? issues : JSON.stringify(issues);
192
+ }
193
+ // src/core/json-value.ts
11
194
  /** JSON values accepted at the environment boundary, without prototype or internal keys. */
12
195
  function isEnvSchemaValue(value, depth = 0) {
13
196
  if (depth > 64) return false;
@@ -22,8 +205,7 @@ function isEnvSchemaValue(value, depth = 0) {
22
205
  "__envSchemaUnset"
23
206
  ].includes(key) && isEnvSchemaValue(item, depth + 1));
24
207
  }
25
- //#endregion
26
- //#region src/core/values.ts
208
+ // src/core/values.ts
27
209
  const stringValueSchema = Object.freeze({ kind: "string" });
28
210
  /** Parse one host, provider, or default value with a serializable Server Env value schema. */
29
211
  function parseEnvValue(schema, input) {
@@ -191,8 +373,7 @@ function schemaContainsEnum(schema) {
191
373
  default: return false;
192
374
  }
193
375
  }
194
- //#endregion
195
- //#region ../internal/src/runtime/cloudflare-env-lookup.ts
376
+ // ../internal/src/runtime/cloudflare-env-lookup.ts
196
377
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
197
378
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
198
379
  let activeEnv;
@@ -206,15 +387,13 @@ function getActiveCloudflareEnv() {
206
387
  const host = globalThis;
207
388
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
208
389
  }
209
- //#endregion
210
- //#region ../internal/src/runtime/cloudflare-env.ts
390
+ // ../internal/src/runtime/cloudflare-env.ts
211
391
  const runtimeGlobal = globalThis;
212
392
  const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
213
393
  function runWithActiveCloudflareEnv(env, callback) {
214
394
  return activeEnvStorage.run({ env }, callback);
215
395
  }
216
- //#endregion
217
- //#region ../internal/src/secret.ts
396
+ // ../internal/src/secret.ts
218
397
  const secretEncoder = new TextEncoder();
219
398
  /**
220
399
  * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
@@ -336,111 +515,7 @@ async function verifyViteHubStripeSignature(secret, header, body, options = {})
336
515
  for (const signature of signatures) verified = isViteHubSecretEqual(signature, expected) || verified;
337
516
  return verified;
338
517
  }
339
- //#endregion
340
- //#region src/core/errors.ts
341
- const envErrorMessages = {
342
- ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
343
- ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
344
- ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
345
- ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
346
- ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
347
- };
348
- const envSourceIdentifierSet = /* @__PURE__ */ new Set([
349
- "custom",
350
- "env",
351
- "git:branch",
352
- "git:commit",
353
- "git:tag",
354
- "package.json",
355
- "provider"
356
- ]);
357
- function createEnvError(options, message = envErrorMessages[options.code]) {
358
- const { code, cause, details } = options;
359
- return new ViteHubError(code, message, {
360
- ...cause === void 0 ? {} : { cause },
361
- ...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
362
- });
363
- }
364
- function invalidEnvDeclaration(path, diagnostic, cause) {
365
- return createEnvError({
366
- cause: envErrorDiagnostics.ENV_R0008({
367
- message: diagnostic,
368
- ...cause === void 0 ? {} : { cause }
369
- }),
370
- code: "ENV_DECLARATION_INVALID",
371
- details: optionalPath(path)
372
- });
373
- }
374
- function asyncServerEnvRequired(path) {
375
- return createEnvError({
376
- cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
377
- code: "ENV_ASYNC_REQUIRED",
378
- details: optionalPath(path)
379
- });
380
- }
381
- /**
382
- * The message and details name the declaration path and the variables that can supply it, so the operator
383
- * knows what to set. Names are not secret; the value never appears because there is none.
384
- */
385
- function missingRequiredEnv(source, diagnostic, path, names = []) {
386
- const pathDetails = optionalPath(path);
387
- const variables = names.filter(isEnvVariableName).slice(0, 8);
388
- const subject = pathDetails.path ? `Required Env value ${pathDetails.path} is missing.` : "Required Env value is missing.";
389
- const supply = variables.length ? ` Set ${variables.join(" or ")}.` : "";
390
- return createEnvError({
391
- cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
392
- code: "ENV_REQUIRED_MISSING",
393
- details: {
394
- ...variables.length ? { names: variables } : {},
395
- ...pathDetails,
396
- source: publicSourceIdentifier(source)
397
- }
398
- }, `[vitehub] ${subject}${supply}`);
399
- }
400
- function isEnvVariableName(name) {
401
- return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
402
- }
403
- function invalidRuntimeEnvValue(source, diagnostic, path) {
404
- return createEnvError({
405
- cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
406
- code: "ENV_RUNTIME_VALUE_INVALID",
407
- details: {
408
- ...optionalPath(path),
409
- source: publicSourceIdentifier(source)
410
- }
411
- });
412
- }
413
- function envSourceFailed(source, cause) {
414
- return createEnvError({
415
- cause,
416
- code: "ENV_SOURCE_FAILED",
417
- details: { source: publicSourceIdentifier(source) }
418
- });
419
- }
420
- function isAbortError(value) {
421
- if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
422
- try {
423
- return value.name === "AbortError";
424
- } catch {
425
- return false;
426
- }
427
- }
428
- function publicSourceIdentifier(source) {
429
- if (envSourceIdentifierSet.has(source)) return source;
430
- if (source.startsWith("env:")) return "env";
431
- if (source.startsWith("package.json:")) return "package.json";
432
- return "custom";
433
- }
434
- function optionalPath(path) {
435
- const normalized = safePath(path);
436
- return normalized ? { path: normalized } : {};
437
- }
438
- function safePath(path) {
439
- if (typeof path !== "string" || path.length > 256) return void 0;
440
- return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
441
- }
442
- //#endregion
443
- //#region src/internal/runtime-env.ts
518
+ // src/internal/runtime-env.ts
444
519
  function processEnv() {
445
520
  return typeof process === "object" && process && process.env ? process.env : {};
446
521
  }
@@ -473,8 +548,7 @@ function standardSource(event) {
473
548
  if ("~standard" in event) return event;
474
549
  return event instanceof Request ? event : event.req;
475
550
  }
476
- //#endregion
477
- //#region src/core/registry.ts
551
+ // src/core/registry.ts
478
552
  const envEntrySchema = v.object({
479
553
  required: v.boolean(),
480
554
  secret: v.boolean(),
@@ -513,8 +587,7 @@ function* runtimeRegistryEntries(value, path = "env.server") {
513
587
  if (!isRecord(value)) return;
514
588
  for (const [key, child] of Object.entries(value)) yield* runtimeRegistryEntries(child, `${path}.${key.includes(".") ? "!" : ""}${key}`);
515
589
  }
516
- //#endregion
517
- //#region ../internal/src/invariant.ts
590
+ // ../internal/src/invariant.ts
518
591
  const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
519
592
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
520
593
  codes: { INTERNAL_INVARIANT_FAILED: {
@@ -533,8 +606,10 @@ function invariantError(what) {
533
606
  function invariant(condition, what) {
534
607
  if (!condition) throw invariantError(what);
535
608
  }
536
- //#endregion
537
- //#region src/seal-uses.ts
609
+ // src/seal-uses.ts
610
+ function isSealUseCount(value) {
611
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
612
+ }
538
613
  const table = "vitehub_env_seal_uses";
539
614
  const ready = /* @__PURE__ */ new WeakMap();
540
615
  function checkId(id) {
@@ -555,7 +630,6 @@ function initialize(db) {
555
630
  }
556
631
  /** Keeps `uses` for a new id. The row holds no part of the value. */
557
632
  async function createSealUses(db, id, uses, expiresAt) {
558
- invariant(Number.isSafeInteger(uses) && uses >= 1, "`uses` must be a positive integer");
559
633
  await initialize(db);
560
634
  const now = Date.now();
561
635
  await db.all(`DELETE FROM ${table} WHERE expires_at IS NOT NULL AND expires_at <= ${now}`);
@@ -574,8 +648,7 @@ async function deleteSealUses(db, id) {
574
648
  await initialize(db);
575
649
  await db.all(`DELETE FROM ${table} WHERE id = '${checkId(id)}'`);
576
650
  }
577
- //#endregion
578
- //#region src/seal-value.ts
651
+ // src/seal-value.ts
579
652
  const sealErrors = /*#__PURE__*/ defineErrors({
580
653
  docs: "https://vitehub.dev/docs/env/diagnostics",
581
654
  codes: {
@@ -646,10 +719,6 @@ function rootSecret(secret) {
646
719
  if (typeof value !== "string" || value.length < 32) argumentError(`\`secret\` must be a string of at least 32 characters, or a non-empty list of them.`);
647
720
  return value;
648
721
  }
649
- /**
650
- * The root secrets in order: the one that seals first, then the old ones that `unseal()` also tries. `undefined` is
651
- * `VITEHUB_SECRET` (or the development secret). Only `unseal()` passes `previous`, to add `VITEHUB_SECRET_PREVIOUS`.
652
- */
653
722
  function rootSecrets(options, previous) {
654
723
  const { secret } = options;
655
724
  if (secret === void 0) return previous ? [void 0, ...previousSecrets(options.event)] : [void 0];
@@ -700,7 +769,7 @@ function createSealing(derive) {
700
769
  const ttl = typeof options.ttl === "string" ? parseDuration(options.ttl) / 1e3 : options.ttl;
701
770
  if (ttl !== void 0 && (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0)) argumentError("`ttl` must be a positive number of seconds or a duration such as \"15m\".");
702
771
  const { uses, db } = options;
703
- if (uses !== void 0 && (typeof uses !== "number" || !Number.isSafeInteger(uses) || uses < 1)) argumentError("`uses` must be a positive integer.");
772
+ if (uses !== void 0 && !isSealUseCount(uses)) argumentError("`uses` must be a positive integer.");
704
773
  const usesDb = uses === void 0 ? void 0 : usesDatabase(db, "`uses` needs a `db`, such as `db` from `vite-hub/database`, that every instance of the app shares.");
705
774
  checkJsonValue(value);
706
775
  let json;
@@ -790,8 +859,7 @@ function seal(purpose, value, options) {
790
859
  function unseal(purpose, sealed, options) {
791
860
  return sealing.unseal(purpose, sealed, options);
792
861
  }
793
- //#endregion
794
- //#region src/server.ts
862
+ // src/server.ts
795
863
  /**
796
864
  * Run `callback` with `env` as the active Cloudflare bindings. Server Env reads them when a call gets no request
797
865
  * event, such as for the module bindings of `cloudflare:workers` outside a request.
@@ -818,7 +886,6 @@ async function deriveSecret(purpose, options = {}, development = {}) {
818
886
  }
819
887
  return await deriveViteHubSecret(root, purpose);
820
888
  }
821
- /** An empty variable counts as missing, so it never shadows a later name or satisfies a required value. */
822
889
  function hasRuntimeName(env, name) {
823
890
  return Object.hasOwn(env, name) && env[name] !== void 0 && env[name] !== "";
824
891
  }
@@ -830,7 +897,6 @@ function readRuntimeSource(entry, env) {
830
897
  };
831
898
  return { found: false };
832
899
  }
833
- /** Report which kind of name supplied the value, and whether a shadowed conventional name holds another value. */
834
900
  function runtimeSourceOrigin(entry, env, source) {
835
901
  const canonical = entry.source.canonical;
836
902
  if (!source.found || canonical === void 0 || canonical === false) return {};
@@ -840,7 +906,6 @@ function runtimeSourceOrigin(entry, env, source) {
840
906
  via: "canonical"
841
907
  } : { via: "canonical" };
842
908
  }
843
- /** Server Env resolves every declaration together, so the message must say why reading another value fails. */
844
909
  function missingRuntimeValueMessage(entry, path) {
845
910
  const supply = entry.source.kind === "env" ? `Set ${(entry.source.names || [entry.source.name]).join(" or ")}` : "Return it from the provider";
846
911
  return `${path} is required and has no value. Server Env checks every declared value together, so this fails even when code reads only another value. ${entry.secret ? `${supply} or declare it with optional: true.` : `${supply}, give it a default, or declare it with optional: true.`}`;
@@ -855,20 +920,15 @@ function bindServerEnvSchemas(registry, modules) {
855
920
  if (!(isRuntimeEnvEntry(entry) || isRuntimeProviderEntry(entry)) || !entry.schemaModule) continue;
856
921
  const reference = entry.schemaModule;
857
922
  const module = Object.hasOwn(modules, reference.module) ? modules[reference.module] : void 0;
858
- const schema = module && Object.hasOwn(module, reference.export) ? module[reference.export] : void 0;
859
- if (!isBoundStandardSchema(schema)) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(${JSON.stringify(reference.module)}, ${JSON.stringify(reference.export)}), but that export is not a Standard Schema.`);
860
- boundSchemas.set(entry, schema);
923
+ const validate = readStandardValidate(module && Object.hasOwn(module, reference.export) ? module[reference.export] : void 0, path);
924
+ if (!validate) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(${JSON.stringify(reference.module)}, ${JSON.stringify(reference.export)}), but that export is not a Standard Schema.`);
925
+ boundSchemas.set(entry, validate);
861
926
  }
862
927
  }
863
- function isBoundStandardSchema(value) {
864
- if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
865
- const standard = value["~standard"];
866
- return typeof standard === "object" && standard !== null && typeof standard.validate === "function";
867
- }
868
928
  function parseRuntimeValue(entry, value, path) {
869
929
  if (!entry.schemaModule) return parseEnvValue(entry.schema ?? stringValueSchema, value);
870
- const schema = boundSchemas.get(entry);
871
- if (!schema) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), but no schema module was loaded for it. Only env.server declarations of hubEnv() support env.schemaFrom().`);
930
+ const validate = boundSchemas.get(entry);
931
+ if (!validate) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), but no schema module was loaded for it. Only env.server declarations of hubEnv() support env.schemaFrom().`);
872
932
  let input = value;
873
933
  if (entry.schemaModule.input === "json") {
874
934
  const json = readJsonInput(value);
@@ -877,7 +937,7 @@ function parseRuntimeValue(entry, value, path) {
877
937
  }
878
938
  let result;
879
939
  try {
880
- result = schema["~standard"].validate(input);
940
+ result = validate(input);
881
941
  } catch (error) {
882
942
  return {
883
943
  message: `The schema threw: ${error instanceof Error ? error.message : String(error)}`,
@@ -891,12 +951,12 @@ function parseRuntimeValue(entry, value, path) {
891
951
  success: false
892
952
  };
893
953
  }
894
- const issues = isRecord(result) ? result.issues : void 0;
895
- if (Array.isArray(issues) && issues.length) return {
896
- message: formatSchemaIssues(issues),
954
+ const issues = standardResultIssues(result);
955
+ if (issues) return {
956
+ message: formatStandardIssues(issues),
897
957
  success: false
898
958
  };
899
- if (!isRecord(result) || !("value" in result)) return {
959
+ if (!hasResultValue(result)) return {
900
960
  message: "The schema returned no value.",
901
961
  success: false
902
962
  };
@@ -908,13 +968,6 @@ function parseRuntimeValue(entry, value, path) {
908
968
  function isPromiseLike(value) {
909
969
  return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
910
970
  }
911
- function formatSchemaIssues(issues) {
912
- return issues.map((issue) => {
913
- const message = isRecord(issue) && typeof issue.message === "string" ? issue.message : "Invalid value.";
914
- const segments = isRecord(issue) && Array.isArray(issue.path) ? issue.path.map((segment) => isRecord(segment) ? segment.key : segment).filter((segment) => typeof segment === "string" || typeof segment === "number") : [];
915
- return segments.length ? `${segments.join(".")}: ${message}` : message;
916
- }).join("; ");
917
- }
918
971
  function resolvedRuntimeValue(entry, value, found, path, snapshot = false) {
919
972
  const resolved = found ? value : entry.default;
920
973
  if (typeof resolved === "undefined") {
@@ -950,10 +1003,6 @@ function resolveRegistryValue(value, env, path) {
950
1003
  }
951
1004
  return output;
952
1005
  }
953
- /**
954
- * Copy the namespace records of a resolved registry, so a caller that changes its result does not change the cached
955
- * one. resolveRegistryValue() creates each namespace without a prototype, and provider getters keep their descriptor.
956
- */
957
1006
  function copyNamespaces(value) {
958
1007
  const descriptors = Object.getOwnPropertyDescriptors(value);
959
1008
  for (const descriptor of Object.values(descriptors)) if (isNamespace(descriptor.value)) descriptor.value = copyNamespaces(descriptor.value);
@@ -1123,7 +1172,6 @@ function inspectionPath(path) {
1123
1172
  return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? { path } : {};
1124
1173
  }
1125
1174
  const hostVariableName = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
1126
- /** The host variable names an env declaration reads, in read order. Never values. */
1127
1175
  function inspectionNames(entry) {
1128
1176
  const names = (entry.source.names || [entry.source.name]).filter((name) => hostVariableName.test(name));
1129
1177
  return names.length ? { names } : {};
@@ -1184,7 +1232,6 @@ async function inspectRegistryEntry(value, env, options, loads, path, entries) {
1184
1232
  }
1185
1233
  const registryEnvNames = /* @__PURE__ */ new WeakMap();
1186
1234
  const resolvedServerEnvs = /* @__PURE__ */ new WeakMap();
1187
- /** The env names a registry reads, or null when it declares an array, list, JSON value, or object, since each call returns its own copy. */
1188
1235
  function reusableEnvNames(registry) {
1189
1236
  const known = registryEnvNames.get(registry);
1190
1237
  if (known !== void 0) return known;
@@ -1200,7 +1247,6 @@ function reusableEnvNames(registry) {
1200
1247
  registryEnvNames.set(registry, names);
1201
1248
  return names;
1202
1249
  }
1203
- /** The values of every name the registry reads, as one string. Undefined when the result must not be reused. */
1204
1250
  function serverEnvKey(registry, event) {
1205
1251
  const names = reusableEnvNames(registry);
1206
1252
  if (!names || getViteHubTestMode()) return void 0;
@@ -1286,5 +1332,4 @@ async function inspectServerEnv(registry, event, options = {}) {
1286
1332
  if (options.signal?.aborted) throw abortReason(options.signal);
1287
1333
  return Object.freeze({ entries: Object.freeze(entries.map((entry) => Object.freeze(entry))) });
1288
1334
  }
1289
- //#endregion
1290
- export { envValueTypeName as A, deriveViteHubSecret as C, verifyViteHubHmacSignature as D, readViteHubSecret as E, stringValueSchema as F, isEnvSchemaValue as I, parseEnvValue as M, readJsonInput as N, verifyViteHubStripeSignature as O, schemaContainsEnum as P, missingRequiredEnv as S, isViteHubBearerSecretEqual as T, runtimeEnv as _, isBlockingServerEnvEntry as a, invalidEnvDeclaration as b, runWithCloudflareEnv as c, unseal as d, invariant as f, runtimeRegistryEntries as g, isRuntimeProviderEntry as h, inspectServerEnv as i, listItemKinds as j, viteHubHmacSha256 as k, createSealing as l, isRuntimeLiteralEntry as m, deriveSecret as n, loadServerEnv as o, isRuntimeEnvEntry as p, describeServerEnv as r, resolveServerEnv as s, bindServerEnvSchemas as t, seal as u, standardSource as v, githubHmacSignatureFormat as w, isAbortError as x, envSourceFailed as y };
1335
+ export { schemaContainsEnum as A, verifyViteHubHmacSignature as C, listItemKinds as D, envValueTypeName as E, envSourceFailed as F, invalidEnvDeclaration as I, isAbortError as L, isEnvSchemaValue as M, parseSchema as N, parseEnvValue as O, readStandardValidate as P, missingRequiredEnv as R, readViteHubSecret as S, viteHubHmacSha256 as T, runtimeEnv as _, isBlockingServerEnvEntry as a, githubHmacSignatureFormat as b, runWithCloudflareEnv as c, unseal as d, invariant as f, runtimeRegistryEntries as g, isRuntimeProviderEntry as h, inspectServerEnv as i, stringValueSchema as j, readJsonInput as k, createSealing as l, isRuntimeLiteralEntry as m, deriveSecret as n, loadServerEnv as o, isRuntimeEnvEntry as p, describeServerEnv as r, resolveServerEnv as s, bindServerEnvSchemas as t, seal as u, standardSource as v, verifyViteHubStripeSignature as w, isViteHubBearerSecretEqual as x, deriveViteHubSecret as y };
package/dist/server.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "./bridge-Cs9YfQWk.js";
2
- import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-CgKAEAE6.js";
1
+ import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "./bridge-BWwIooe0.js";
2
+ import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-CPEywepM.js";
3
3
  export { DeriveSecretOptions, type EnvAccessContext, type SealOptions, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type ViteHubContext, bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
package/dist/server.js CHANGED
@@ -1,2 +1 @@
1
- import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "./server-B9-8r6MZ.js";
2
- export { bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
1
+ export { t as bindServerEnvSchemas, l as createSealing, n as deriveSecret, r as describeServerEnv, i as inspectServerEnv, a as isBlockingServerEnvEntry, o as loadServerEnv, s as resolveServerEnv, c as runWithCloudflareEnv, u as seal, d as unseal } from "./server-pTqnkM7n.js";
package/dist/vite.d.ts CHANGED
@@ -1,13 +1,10 @@
1
- import { A as EnvRuntimeRegistry, b as EnvDeclarations, k as EnvRuntimeConfigOptions, w as EnvOptions } from "./bridge-Cs9YfQWk.js";
2
- import { n as ViteHubCliContributor } from "./cli-BPp7rdcA.js";
3
- import { t as env } from "./declarations-C5XR3aKw.js";
4
- import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
1
+ import { t as env } from "./declarations-DNjO52_s.js";
2
+ import { A as EnvRuntimeRegistry, b as EnvDeclarations, k as EnvRuntimeConfigOptions, w as EnvOptions } from "./bridge-BWwIooe0.js";
3
+ import { n as ViteHubCliContributor } from "./cli-B-LW6l_J.js";
4
+ import { n as OperationContributionEntry } from "./operation-definition-CqZkx1Rm.js";
5
5
  import { Plugin, UserConfig } from "vite";
6
- //#region ../internal/src/deployment.d.ts
7
6
  /** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
8
7
  type ViteHubHost = "cloudflare" | "deno" | "netlify" | "node" | "vercel";
9
- //#endregion
10
- //#region ../internal/src/build/deployment-plan-output.d.ts
11
8
  /**
12
9
  * One set of host variables that the deployed app reads, as `deployment.json` lists it: a Server Env declaration, or
13
10
  * a variable that a primitive reads itself, such as `VITEHUB_SECRET` or `BLOB_READ_WRITE_TOKEN`.
@@ -37,12 +34,8 @@ interface DeploymentEnvContext {
37
34
  * Return names only, never values.
38
35
  */
39
36
  type DeploymentEnvContribution = (context: DeploymentEnvContext) => readonly DeploymentEnvEntry[];
40
- //#endregion
41
- //#region ../internal/src/build/vite.d.ts
42
37
  declare const VITEHUB_ENV_PUBLIC_ID: "#vitehub/env/public";
43
38
  declare const VITEHUB_ENV_SERVER_ID: "#vitehub/env/server";
44
- //#endregion
45
- //#region src/core/resolve.d.ts
46
39
  interface RuntimeRegistryOptions {
47
40
  path?: string;
48
41
  prefix?: string | false;
@@ -50,8 +43,6 @@ interface RuntimeRegistryOptions {
50
43
  schemaModules?: boolean;
51
44
  }
52
45
  declare function createRuntimeRegistry(declarations: EnvRuntimeConfigOptions | undefined, options?: RuntimeRegistryOptions): EnvRuntimeRegistry;
53
- //#endregion
54
- //#region src/env-schema/importer.d.ts
55
46
  interface EnvSchemaOptions {
56
47
  prefix?: string;
57
48
  /** Exact schema key to output path. Only Server Env supports nested paths. */
@@ -59,8 +50,6 @@ interface EnvSchemaOptions {
59
50
  }
60
51
  /** Import a committed env-spec-v1 contract. Reads schema metadata, never developer env files. */
61
52
  export declare function envSchema(file: string | URL, options?: EnvSchemaOptions): EnvDeclarations;
62
- //#endregion
63
- //#region src/vite.d.ts
64
53
  export declare const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
65
54
  export declare const ENV_PUBLIC_ID: typeof VITEHUB_ENV_PUBLIC_ID;
66
55
  export declare const ENV_SERVER_ID: typeof VITEHUB_ENV_SERVER_ID;
@@ -78,7 +67,7 @@ export interface EnvVitePluginAPI {
78
67
  }
79
68
  export type EnvVitePlugin = Plugin & {
80
69
  api: EnvVitePluginAPI;
81
- /** Contributes `vitehub env inspect`, `vitehub env check`, and the `env.inspect` operation. */
70
+ /** Contributes `vitehub env list`, `vitehub env check`, and the `env.inspect` operation. */
82
71
  vitehub: {
83
72
  cli: () => ViteHubCliContributor;
84
73
  operations: readonly OperationContributionEntry[];
@@ -97,5 +86,4 @@ export declare function createEnvTypeScriptPaths(options?: EnvGeneratedPathOptio
97
86
  */
98
87
  export declare function createEnvTypes(config: EnvDeclarations | undefined, options?: Pick<EnvOptions, "prefix" | "runtimeImports" | "projectRoot">): string;
99
88
  export declare function hubEnv(options?: EnvOptions): EnvVitePlugin;
100
- //#endregion
101
89
  export { type EnvSchemaOptions, createRuntimeRegistry as createRuntimeEnvRegistry, env };