@vite-hub/env 0.0.4 → 0.1.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 +125 -5
  2. package/dist/access-B3qzBHye.js +54 -0
  3. package/dist/auth.d.ts +32 -0
  4. package/dist/auth.js +44 -0
  5. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  6. package/dist/bridge-error-CFuU5zIz.js +65 -0
  7. package/dist/bridge.d.ts +2 -0
  8. package/dist/bridge.js +192 -0
  9. package/dist/cli-CMQPQbii.js +487 -0
  10. package/dist/cli-DEwcUIe0.d.ts +81 -0
  11. package/dist/cli.d.ts +41 -0
  12. package/dist/cli.js +2 -0
  13. package/dist/database.d.ts +21 -0
  14. package/dist/database.js +183 -0
  15. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  16. package/dist/declarations-DAVgctKD.js +236 -0
  17. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  18. package/dist/http.d.ts +2 -0
  19. package/dist/http.js +122 -0
  20. package/dist/index.d.ts +6 -6
  21. package/dist/index.js +4 -4
  22. package/dist/internal/agent.d.ts +5 -0
  23. package/dist/internal/agent.js +22 -0
  24. package/dist/internal/connections.d.ts +18 -0
  25. package/dist/internal/connections.js +31 -0
  26. package/dist/presets.d.ts +15 -6
  27. package/dist/presets.js +21 -2
  28. package/dist/provider.d.ts +3 -4
  29. package/dist/provider.js +2 -1
  30. package/dist/schema.d.ts +5 -6
  31. package/dist/schema.js +26 -8
  32. package/dist/seal.d.ts +14 -0
  33. package/dist/seal.js +49 -0
  34. package/dist/server-DufVswRJ.js +670 -0
  35. package/dist/server.d.ts +23 -6
  36. package/dist/server.js +2 -3
  37. package/dist/values-D_r6V774.js +148 -0
  38. package/dist/virtual-module.d.ts +7 -3
  39. package/dist/virtual.d.ts +1 -1
  40. package/dist/vite.d.ts +27 -14
  41. package/dist/vite.js +840 -273
  42. package/package.json +81 -17
  43. package/dist/declarations-CoMmvRqH.js +0 -159
  44. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  45. package/dist/errors-C4Xcs6Fi.js +0 -121
  46. package/dist/server-C16sFc1E.js +0 -303
  47. package/dist/types-CsB6DTGE.d.ts +0 -190
@@ -0,0 +1,22 @@
1
+ import { t as envBridgeError } from "../bridge-error-CFuU5zIz.js";
2
+ import { r as grantEnvAccess } from "../access-B3qzBHye.js";
3
+ import { readAgentEnvIdentity, readAgentEnvParents } from "@vite-hub/agent/env-identity";
4
+ //#region src/internal/agent.ts
5
+ /** Mint only for an identity registered by Agent Definition resolution. Names and copies are untrusted. */
6
+ function agentEnvAccess(agent, attribution = {}) {
7
+ const name = readAgentEnvIdentity(agent);
8
+ if (name === void 0) throw envBridgeError("untrusted");
9
+ return grantEnvAccess({
10
+ actor: {
11
+ kind: "agent",
12
+ id: name
13
+ },
14
+ traceId: attribution.traceId,
15
+ invocationId: attribution.invocationId
16
+ }, {
17
+ kind: "agent",
18
+ parents: readAgentEnvParents(agent)
19
+ });
20
+ }
21
+ //#endregion
22
+ export { agentEnvAccess };
@@ -0,0 +1,18 @@
1
+ import { a as EnvActor, o as EnvBridge, t as EnvAccessContext } from "../bridge-CdNdTN1V.js";
2
+ //#region src/internal/connections.d.ts
3
+ /**
4
+ * Internal to `@vite-hub/connections`. Call it only after the Connection access policy allows the call.
5
+ * The context works on one bridge, for one Connection token key and one permission.
6
+ */
7
+ export declare function connectionEnvAccess(bridge: EnvBridge, input: {
8
+ actor: EnvActor;
9
+ name: string;
10
+ permission: "activity" | "replace" | "use";
11
+ traceId?: string;
12
+ invocationId?: string;
13
+ }): EnvAccessContext;
14
+ /** Return the actor of a context that Env created. Other values fail with `ENV_BRIDGE_UNTRUSTED`. */
15
+ export declare function envAccessActor(context: EnvAccessContext): EnvActor;
16
+ /** The registered Agents that the Agent of a context extends, nearest first. Other contexts fail with `ENV_BRIDGE_UNTRUSTED`. */
17
+ export declare function envAccessAgentParents(context: EnvAccessContext): string[];
18
+ //#endregion
@@ -0,0 +1,31 @@
1
+ import { t as envBridgeError } from "../bridge-error-CFuU5zIz.js";
2
+ import { r as grantEnvAccess, t as envAccessAuthority } from "../access-B3qzBHye.js";
3
+ //#region src/internal/connections.ts
4
+ /**
5
+ * Internal to `@vite-hub/connections`. Call it only after the Connection access policy allows the call.
6
+ * The context works on one bridge, for one Connection token key and one permission.
7
+ */
8
+ function connectionEnvAccess(bridge, input) {
9
+ return grantEnvAccess(input, {
10
+ kind: "key",
11
+ bridge,
12
+ key: `connection/${input.name}`,
13
+ permissions: [input.permission]
14
+ });
15
+ }
16
+ /** Return the actor of a context that Env created. Other values fail with `ENV_BRIDGE_UNTRUSTED`. */
17
+ function envAccessActor(context) {
18
+ if (envAccessAuthority(context).kind !== "agent") throw envBridgeError("untrusted");
19
+ return {
20
+ id: context.actor.id,
21
+ kind: context.actor.kind
22
+ };
23
+ }
24
+ /** The registered Agents that the Agent of a context extends, nearest first. Other contexts fail with `ENV_BRIDGE_UNTRUSTED`. */
25
+ function envAccessAgentParents(context) {
26
+ const authority = envAccessAuthority(context);
27
+ if (authority.kind !== "agent") throw envBridgeError("untrusted");
28
+ return [...authority.parents ?? []];
29
+ }
30
+ //#endregion
31
+ export { connectionEnvAccess, envAccessActor, envAccessAgentParents };
package/dist/presets.d.ts CHANGED
@@ -1,11 +1,20 @@
1
- import { d as EnvRuntimeConfigOptions } from "./types-CsB6DTGE.js";
2
-
1
+ import { w as EnvRuntimeConfigOptions } from "./bridge-CdNdTN1V.js";
3
2
  //#region src/presets.d.ts
4
- interface OpenWorkflowEnvOptions {
3
+ export interface OpenWorkflowEnvOptions {
5
4
  namespaceId?: string;
6
5
  schema?: string;
7
6
  workerConcurrency?: string;
8
7
  }
9
- declare function openWorkflowEnv(options?: OpenWorkflowEnvOptions): EnvRuntimeConfigOptions;
10
- //#endregion
11
- export { OpenWorkflowEnvOptions, openWorkflowEnv };
8
+ export declare function openWorkflowEnv(options?: OpenWorkflowEnvOptions): EnvRuntimeConfigOptions;
9
+ export interface TypesafeEnvOptions {
10
+ /** Default model when `TYPESAFE_DEFAULT_MODEL` is not set. Default: `jev-latest`. */
11
+ model?: string;
12
+ }
13
+ /**
14
+ * Declares the Server Env of the `typesafe()` AI gateway from `vite-hub/gateways`: Secret `apiKey`
15
+ * (`TYPESAFE_API_KEY`) and `model` (`TYPESAFE_DEFAULT_MODEL`). `defineAgent({ driver: { ask } })`, `llmGate()`, and
16
+ * `llmRoute()` use `typesafe()` when they get no other gateway. The values are optional here: Jev diagnoses a
17
+ * missing key when it runs, so an application without AI still starts.
18
+ */
19
+ export declare function typesafeEnv(options?: TypesafeEnvOptions): EnvRuntimeConfigOptions;
20
+ //#endregion
package/dist/presets.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as env } from "./declarations-CoMmvRqH.js";
1
+ import { n as env } from "./declarations-DAVgctKD.js";
2
2
  //#region src/presets.ts
3
3
  function openWorkflowEnv(options = {}) {
4
4
  return {
@@ -21,5 +21,24 @@ function openWorkflowEnv(options = {}) {
21
21
  })
22
22
  };
23
23
  }
24
+ /**
25
+ * Declares the Server Env of the `typesafe()` AI gateway from `vite-hub/gateways`: Secret `apiKey`
26
+ * (`TYPESAFE_API_KEY`) and `model` (`TYPESAFE_DEFAULT_MODEL`). `defineAgent({ driver: { ask } })`, `llmGate()`, and
27
+ * `llmRoute()` use `typesafe()` when they get no other gateway. The values are optional here: Jev diagnoses a
28
+ * missing key when it runs, so an application without AI still starts.
29
+ */
30
+ function typesafeEnv(options = {}) {
31
+ return {
32
+ apiKey: env({
33
+ optional: true,
34
+ secret: true,
35
+ source: env.source("TYPESAFE_API_KEY")
36
+ }),
37
+ model: env({
38
+ default: options.model || "jev-latest",
39
+ source: env.source("TYPESAFE_DEFAULT_MODEL")
40
+ })
41
+ };
42
+ }
24
43
  //#endregion
25
- export { openWorkflowEnv };
44
+ export { openWorkflowEnv, typesafeEnv };
@@ -1,6 +1,5 @@
1
- import { c as EnvProviderContext, l as EnvProviderValues, s as EnvProvider } from "./types-CsB6DTGE.js";
2
-
1
+ import { S as EnvProviderValues, b as EnvProvider, x as EnvProviderContext } from "./bridge-CdNdTN1V.js";
3
2
  //#region src/provider.d.ts
4
- declare function defineEnvProvider<TEnv extends Record<string, unknown> = Record<string, unknown>, const TProvider extends EnvProvider<TEnv> = EnvProvider<TEnv>>(provider: TProvider): TProvider;
3
+ export declare function defineEnvProvider<TEnv extends Record<string, unknown> = Record<string, unknown>, const TProvider extends EnvProvider<TEnv> = EnvProvider<TEnv>>(provider: TProvider): TProvider;
5
4
  //#endregion
6
- export { type EnvProvider, type EnvProviderContext, type EnvProviderValues, defineEnvProvider };
5
+ export type { EnvProvider, EnvProviderContext, EnvProviderValues };
package/dist/provider.js CHANGED
@@ -1,6 +1,7 @@
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
1
2
  //#region src/provider.ts
2
3
  function defineEnvProvider(provider) {
3
- if (typeof provider !== "object" || provider === null || Array.isArray(provider) || typeof provider.read !== "function") throw new TypeError("[vitehub] defineEnvProvider() requires a provider with a read({ env, keys, signal }) method.");
4
+ if (typeof provider !== "object" || provider === null || Array.isArray(provider) || typeof provider.read !== "function") throw envErrorDiagnostics.ENV_R0013({ message: "[vitehub] defineEnvProvider() requires a provider with a read({ env, keys, signal }) method." });
4
5
  return provider;
5
6
  }
6
7
  //#endregion
package/dist/schema.d.ts CHANGED
@@ -1,16 +1,15 @@
1
1
  //#region src/schema.d.ts
2
- interface StandardSchemaResultSuccess<T = unknown> {
2
+ export interface StandardSchemaResultSuccess<T = unknown> {
3
3
  issues?: undefined;
4
4
  value: T;
5
5
  }
6
- interface StandardSchemaResultFailure {
6
+ export interface StandardSchemaResultFailure {
7
7
  issues: readonly unknown[];
8
8
  }
9
- interface StandardSchemaV1<T = unknown> {
9
+ export interface StandardSchemaV1<T = unknown> {
10
10
  "~standard": {
11
11
  validate: (input: unknown) => StandardSchemaResultSuccess<T> | StandardSchemaResultFailure | Promise<StandardSchemaResultSuccess<T> | StandardSchemaResultFailure>;
12
12
  };
13
13
  }
14
- declare function parseSchema(schema: unknown, value: unknown, label: string): unknown;
15
- //#endregion
16
- export { StandardSchemaResultFailure, StandardSchemaResultSuccess, StandardSchemaV1, parseSchema };
14
+ export declare function parseSchema(schema: unknown, value: unknown, label: string): unknown;
15
+ //#endregion
package/dist/schema.js CHANGED
@@ -1,21 +1,22 @@
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
1
2
  //#region src/schema.ts
2
3
  function parseSchema(schema, value, label) {
3
4
  if (isStandardSchema(schema)) {
4
5
  const result = schema["~standard"].validate(value);
5
- if (isPromiseLike(result)) throw new Error(`[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.`);
6
- if ("issues" in result && result.issues && result.issues.length > 0) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
7
- if (!("value" in result)) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.issues)}`);
6
+ if (isPromiseLike(result)) throw envErrorDiagnostics.ENV_R0014({ message: `[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.` });
7
+ if ("issues" in result && result.issues && result.issues.length > 0) throw envErrorDiagnostics.ENV_R0015({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
8
+ if (!("value" in result)) throw envErrorDiagnostics.ENV_R0016({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.issues)}` });
8
9
  return result.value;
9
10
  }
10
- if (isZodLike(schema) && typeof schema.safeParse === "function") {
11
+ if (isZodLike(schema) && hasSchemaMethod(schema, "safeParse") && typeof schema.safeParse === "function") {
11
12
  const result = schema.safeParse(value);
12
- if (!result.success) throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(result.error)}`);
13
+ if (!result.success) throw envErrorDiagnostics.ENV_R0017({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.error)}` });
13
14
  return result.data;
14
15
  }
15
- if (isZodLike(schema) && typeof schema.parse === "function") try {
16
+ if (isZodLike(schema) && hasSchemaMethod(schema, "parse") && typeof schema.parse === "function") try {
16
17
  return schema.parse(value);
17
18
  } catch (error) {
18
- throw new Error(`[vitehub] Invalid ${label}: ${formatIssues(error)}`);
19
+ throw envErrorDiagnostics.ENV_R0018({ message: `[vitehub] Invalid ${label}: ${formatIssues(error)}` });
19
20
  }
20
21
  return value;
21
22
  }
@@ -23,11 +24,28 @@ function isPromiseLike(value) {
23
24
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
24
25
  }
25
26
  function isStandardSchema(schema) {
26
- return typeof schema === "object" && schema !== null && "~standard" in schema && typeof schema["~standard"]?.validate === "function";
27
+ return isZodLike(schema) && hasSchemaMethod(schema, "~standard") && typeof schema["~standard"]?.validate === "function";
27
28
  }
28
29
  function isZodLike(schema) {
29
30
  return typeof schema === "object" && schema !== null;
30
31
  }
32
+ function hasSchemaMethod(schema, method) {
33
+ return Object.hasOwn(schema, method) || isZodSchemaMethod(schema, method);
34
+ }
35
+ function isZodSchemaMethod(schema, method) {
36
+ if (!Object.hasOwn(schema, "_zod")) return false;
37
+ const metadata = schema._zod;
38
+ if (!metadata) return false;
39
+ const constructor = metadata?.constr;
40
+ return hasSetValue(metadata?.traits, "ZodType") && Object.hasOwn(metadata, "constr") && typeof constructor === "function" && Object.getPrototypeOf(schema) === constructor.prototype && Object.hasOwn(constructor.prototype, method);
41
+ }
42
+ function hasSetValue(value, entry) {
43
+ try {
44
+ return Set.prototype.has.call(value, entry);
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
31
49
  function formatIssues(issues) {
32
50
  if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
33
51
  if (issues instanceof Error) return issues.message;
package/dist/seal.d.ts ADDED
@@ -0,0 +1,14 @@
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 `seal` and `unseal`. */
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
+ /** Encrypts `plaintext` with AES-GCM and binds it to `additionalData`. */
11
+ export declare function seal(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, plaintext: string): Promise<string>;
12
+ /** Decrypts a value from `seal`. Fails when the key or `additionalData` differs. */
13
+ export declare function unseal(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, payload: string): Promise<string>;
14
+ //#endregion
package/dist/seal.js ADDED
@@ -0,0 +1,49 @@
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 `seal` and `unseal`. */
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
+ /** Encrypts `plaintext` with AES-GCM and binds it to `additionalData`. */
26
+ async function seal(key, additionalData, plaintext) {
27
+ const iv = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
28
+ const encrypted = await crypto.subtle.encrypt({
29
+ name: "AES-GCM",
30
+ iv,
31
+ additionalData
32
+ }, key, new TextEncoder().encode(plaintext));
33
+ return `${hex(iv)}:${hex(new Uint8Array(encrypted))}`;
34
+ }
35
+ /** Decrypts a value from `seal`. Fails when the key or `additionalData` differs. */
36
+ async function unseal(key, additionalData, payload) {
37
+ if (!sealedPayloadPattern.test(payload)) throw sealError();
38
+ const [iv, ciphertext] = payload.split(":");
39
+ const value = await crypto.subtle.decrypt({
40
+ name: "AES-GCM",
41
+ iv: bytes(iv),
42
+ additionalData
43
+ }, key, bytes(ciphertext)).catch(() => {
44
+ throw sealError();
45
+ });
46
+ return new TextDecoder("utf-8", { ignoreBOM: true }).decode(value);
47
+ }
48
+ //#endregion
49
+ export { importSealKey, seal, sealKeyId, sealedPayloadPattern, unseal };