@vite-hub/runtime 0.5.1 → 0.6.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.
@@ -0,0 +1,57 @@
1
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
2
+ function hostFromNitroPreset(value) {
3
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
4
+ if (!normalized) return;
5
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
6
+ if (normalized.startsWith("deno")) return "deno";
7
+ if (normalized.startsWith("netlify")) return "netlify";
8
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
9
+ if (normalized.startsWith("vercel")) return "vercel";
10
+ }
11
+ const providerHosts = [
12
+ ["WORKERS_CI", "cloudflare"],
13
+ ["NETLIFY", "netlify"],
14
+ ["NOW_BUILDER", "vercel"],
15
+ ["VERCEL", "vercel"],
16
+ ["VERCEL_ENV", "vercel"],
17
+ ["DENO_DEPLOY", "deno"],
18
+ ["DENO_DEPLOYMENT_ID", "deno"]
19
+ ];
20
+ /**
21
+ * Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
22
+ * The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
23
+ * `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
24
+ * `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
25
+ */
26
+ function detectHost$1(env = process.env) {
27
+ for (const name of [
28
+ "VITEHUB_HOST",
29
+ "NITRO_PRESET",
30
+ "SERVER_PRESET"
31
+ ]) {
32
+ const host = hostFromNitroPreset(env[name]);
33
+ if (host) return host;
34
+ }
35
+ return providerHosts.find(([name]) => env[name]?.trim())?.[1];
36
+ }
37
+ // src/internal/detect-host.ts
38
+ /**
39
+ * Returns the host that this code builds or runs on, or `undefined` when nothing names one.
40
+ * It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
41
+ * (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
42
+ * `vitehub()` uses the same detection when `host` is omitted.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { detectHost } from "vite-hub/runtime"
47
+ *
48
+ * const host = detectHost() ?? "node"
49
+ * ```
50
+ */
51
+ function detectHost(env = processEnv()) {
52
+ return detectHost$1(env) ?? (globalThis.navigator?.userAgent === "Cloudflare-Workers" ? "cloudflare" : void 0);
53
+ }
54
+ function processEnv() {
55
+ return globalThis.process?.env ?? {};
56
+ }
57
+ export { detectHost as t };
@@ -0,0 +1,17 @@
1
+ /** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
2
+ type ViteHubHost = "cloudflare" | "deno" | "netlify" | "node" | "vercel";
3
+ /**
4
+ * Returns the host that this code builds or runs on, or `undefined` when nothing names one.
5
+ * It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
6
+ * (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
7
+ * `vitehub()` uses the same detection when `host` is omitted.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { detectHost } from "vite-hub/runtime"
12
+ *
13
+ * const host = detectHost() ?? "node"
14
+ * ```
15
+ */
16
+ declare function detectHost(env?: Record<string, string | undefined>): ViteHubHost | undefined;
17
+ export { ViteHubHost as n, detectHost as t };
@@ -1,5 +1,3 @@
1
- /** The origin of the hosted Console. */
2
- declare const hostedConsoleOrigin = "https://console.vitehub.dev";
3
1
  /**
4
2
  * The Console path of a link, such as `/agents/bot/invocations/abc?tab=trace`, or `undefined` when the value is not a
5
3
  * Console path. A Console path starts with one `/`. Absolute URLs, protocol-relative URLs, and backslashes are not
@@ -19,10 +17,11 @@ declare function normalizeConsoleProjectUrl(projectUrl: string): string | undefi
19
17
  *
20
18
  * `projectUrl` is the app origin with its application mount, such as `https://app.example.com/portal`. `path` is the
21
19
  * Console path, such as `/agents/bot/invocations/abc`. The hosted Console switches to the project when this browser
22
- * linked it, or asks the person to link it first. The URL holds no secret.
20
+ * linked it, or asks the person to link it first. The URL holds no secret. `consoleOrigin` defaults to the Console of
21
+ * `vitehub({ console: { url } })`, else `https://console.vitehub.dev`.
23
22
  *
24
23
  * Throws `RUNTIME_CONSOLE_PROJECT_URL_INVALID` when `projectUrl` is not `https:` (or `http:` on a loopback host), and
25
24
  * `RUNTIME_CONSOLE_PATH_INVALID` when `path` is not a Console path.
26
25
  */
27
26
  declare function hostedConsoleUrl(projectUrl: string, path: string, consoleOrigin?: string): string;
28
- export { normalizeConsoleProjectUrl as i, hostedConsoleUrl as n, normalizeConsolePath as r, hostedConsoleOrigin as t };
27
+ export { normalizeConsolePath as n, normalizeConsoleProjectUrl as r, hostedConsoleUrl as t };
@@ -0,0 +1,71 @@
1
+ import { t as runtimeErrorDiagnostics } from "./error-diagnostics-Dj98U7ch.js";
2
+ import { c as configuredConsoleOrigin } from "./public-url-TlEVxNNh.js";
3
+ // src/hosted-console.ts
4
+ const loopbackHosts = /* @__PURE__ */ new Set([
5
+ "localhost",
6
+ "127.0.0.1",
7
+ "[::1]"
8
+ ]);
9
+ const pathBase = "https://console.invalid";
10
+ /**
11
+ * The Console path of a link, such as `/agents/bot/invocations/abc?tab=trace`, or `undefined` when the value is not a
12
+ * Console path. A Console path starts with one `/`. Absolute URLs, protocol-relative URLs, and backslashes are not
13
+ * Console paths, so a link cannot send the browser to another site. A path that starts with `/_vitehub`, as on a
14
+ * Console that the app serves, loses that prefix.
15
+ */
16
+ function normalizeConsolePath(path) {
17
+ if (!path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return void 0;
18
+ let url;
19
+ try {
20
+ url = new URL(path, pathBase);
21
+ } catch {
22
+ return;
23
+ }
24
+ if (url.origin !== pathBase) return void 0;
25
+ const pathname = url.pathname.replace(/^\/_vitehub(?=\/|$)/, "") || "/";
26
+ if (pathname.startsWith("//")) return void 0;
27
+ return `${pathname}${url.search}${url.hash}`;
28
+ }
29
+ /**
30
+ * The project URL of a link: the app origin and its application mount, such as `https://app.example.com/portal`, or
31
+ * `undefined` when the URL cannot be a project. A project URL is `https:`, or `http:` on a loopback host, and has no
32
+ * user name or password.
33
+ */
34
+ function normalizeConsoleProjectUrl(projectUrl) {
35
+ let url;
36
+ try {
37
+ url = new URL(projectUrl);
38
+ } catch {
39
+ return;
40
+ }
41
+ if (url.username || url.password) return void 0;
42
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopbackHosts.has(url.hostname))) return void 0;
43
+ const mount = url.pathname.search(/\/_vitehub(?=\/|$)/);
44
+ const base = (mount === -1 ? url.pathname : url.pathname.slice(0, mount)).replace(/\/+$/, "");
45
+ return `${url.origin}${base}`;
46
+ }
47
+ /**
48
+ * The hosted Console URL that opens one page of a project, such as
49
+ * `https://console.vitehub.dev/open?project=https%3A%2F%2Fapp.example.com&path=%2Fkv`.
50
+ *
51
+ * `projectUrl` is the app origin with its application mount, such as `https://app.example.com/portal`. `path` is the
52
+ * Console path, such as `/agents/bot/invocations/abc`. The hosted Console switches to the project when this browser
53
+ * linked it, or asks the person to link it first. The URL holds no secret. `consoleOrigin` defaults to the Console of
54
+ * `vitehub({ console: { url } })`, else `https://console.vitehub.dev`.
55
+ *
56
+ * Throws `RUNTIME_CONSOLE_PROJECT_URL_INVALID` when `projectUrl` is not `https:` (or `http:` on a loopback host), and
57
+ * `RUNTIME_CONSOLE_PATH_INVALID` when `path` is not a Console path.
58
+ */
59
+ function hostedConsoleUrl(projectUrl, path, consoleOrigin = configuredConsoleOrigin()) {
60
+ const project = normalizeConsoleProjectUrl(projectUrl);
61
+ if (!project) throw runtimeErrorDiagnostics.RUNTIME_CONSOLE_PROJECT_URL_INVALID({ value: projectUrl });
62
+ const consolePath = normalizeConsolePath(path);
63
+ if (!consolePath) throw runtimeErrorDiagnostics.RUNTIME_CONSOLE_PATH_INVALID({ value: path });
64
+ const url = new URL("/open", consoleOrigin);
65
+ url.search = new URLSearchParams({
66
+ project,
67
+ path: consolePath
68
+ }).toString();
69
+ return url.href;
70
+ }
71
+ export { normalizeConsolePath as n, normalizeConsoleProjectUrl as r, hostedConsoleUrl as t };
@@ -299,8 +299,6 @@ declare function sendPreparedResponse(request: Request, response: Response): Res
299
299
  */
300
300
  declare function getRuntimeContext(value: Request | ViteHubContext): RequestRuntimeContext;
301
301
  declare function getRuntimeContext<const TOptions extends RuntimeContextOptions>(value: Request | ViteHubContext, options: TOptions): RequestRuntimeContext<TOptions>;
302
- /** The host that ViteHub builds for: the `host` option of `vitehub()` and the value of `VITEHUB_HOST`. */
303
- type ViteHubHost = "cloudflare" | "deno" | "netlify" | "node" | "vercel";
304
302
  declare global {
305
303
  namespace Cloudflare {
306
304
  interface Env {}
@@ -308,20 +306,6 @@ declare global {
308
306
  }
309
307
  /** The codes that `getHostBinding()` returns. */
310
308
  type HostBindingErrorCode = "RUNTIME_HOST_BINDING_NOT_FOUND" | "RUNTIME_HOST_BINDINGS_UNAVAILABLE";
311
- /**
312
- * Returns the host that this code builds or runs on, or `undefined` when nothing names one.
313
- * It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
314
- * (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
315
- * `vitehub()` uses the same detection when `host` is omitted.
316
- *
317
- * @example
318
- * ```ts
319
- * import { detectHost } from "vite-hub/runtime"
320
- *
321
- * const host = detectHost() ?? "node"
322
- * ```
323
- */
324
- declare function detectHost(env?: Record<string, string | undefined>): ViteHubHost | undefined;
325
309
  /**
326
310
  * Reads one raw binding of the host, such as an R2 bucket, a Durable Object namespace, or a variable of a Cloudflare
327
311
  * Worker. Use it for host features that no ViteHub primitive covers. It works in request handlers, Schedules, Queues,
@@ -342,4 +326,4 @@ declare function detectHost(env?: Record<string, string | undefined>): ViteHubHo
342
326
  */
343
327
  declare function getHostBinding<TName extends keyof Cloudflare.Env & string>(name: TName, event?: object): Result<Cloudflare.Env[TName], HostBindingErrorCode>;
344
328
  declare function getHostBinding<T = unknown>(name: string, event?: object): Result<T, HostBindingErrorCode>;
345
- export { ResultError as $, formatRuntimeDiagnosticError as A, LeaseErrorCode as B, RuntimeDiagnosticReporter as C, RuntimeResourceSnapshot as D, RuntimeResourceScope as E, parseDuration as F, LeaseStore as G, LeaseRecord as H, getInstanceId as I, DefineErrorsOptions as J, createMemoryLeaseStore as K, instanceIdEnv as L, normalizeRuntimeDiagnosticError as M, Duration as N, RuntimeResourceSupport as O, DurationUnit as P, Result as Q, Lease as R, RuntimeDiagnosticLevel as S, RuntimeResourceObservation as T, LeaseSqlClient as U, LeaseOperation as V, LeaseSqlParam as W, ErrorCodes as X, ErrorCatalog as Y, ErrorHandle as Z, getViteHubErrorShape as _, RequestRuntimeContext as a, RuntimeDiagnosticErrorOptions as b, getRuntimeContext as c, sendPreparedResponse as d, defineErrors as et, ViteHubError as f, ViteHubErrorShape as g, ViteHubErrorOptions as h, ViteHubHost as i, isRuntimeDiagnostic as j, RuntimeResourceUnit as k, getStandardContext as l, ViteHubErrorDetails as m, detectHost as n, RuntimeContextOptions as o, ViteHubErrorDetail as p, createSqlLeaseStore as q, getHostBinding as r, RuntimeName as s, HostBindingErrorCode as t, toResultError as tt, installRequestStandardContext as u, isViteHubError as v, RuntimeResourceInspector as w, RuntimeDiagnosticEvent as x, RuntimeDiagnosticError as y, LeaseAcquireOptions as z };
329
+ export { toResultError as $, normalizeRuntimeDiagnosticError as A, LeaseRecord as B, RuntimeResourceObservation as C, RuntimeResourceUnit as D, RuntimeResourceSupport as E, instanceIdEnv as F, createSqlLeaseStore as G, LeaseSqlParam as H, Lease as I, ErrorCodes as J, DefineErrorsOptions as K, LeaseAcquireOptions as L, DurationUnit as M, parseDuration as N, formatRuntimeDiagnosticError as O, getInstanceId as P, defineErrors as Q, LeaseErrorCode as R, RuntimeResourceInspector as S, RuntimeResourceSnapshot as T, LeaseStore as U, LeaseSqlClient as V, createMemoryLeaseStore as W, Result as X, ErrorHandle as Y, ResultError as Z, RuntimeDiagnosticError as _, RuntimeName as a, RuntimeDiagnosticLevel as b, installRequestStandardContext as c, ViteHubErrorDetail as d, ViteHubErrorDetails as f, isViteHubError as g, getViteHubErrorShape as h, RuntimeContextOptions as i, Duration as j, isRuntimeDiagnostic as k, sendPreparedResponse as l, ViteHubErrorShape as m, getHostBinding as n, getRuntimeContext as o, ViteHubErrorOptions as p, ErrorCatalog as q, RequestRuntimeContext as r, getStandardContext as s, HostBindingErrorCode as t, ViteHubError as u, RuntimeDiagnosticErrorOptions as v, RuntimeResourceScope as w, RuntimeDiagnosticReporter as x, RuntimeDiagnosticEvent as y, LeaseOperation as z };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { A as RuntimeWaitUntil, B as TraceEventLogOptions, C as PolicyDecision, D as RuntimeCapabilityHandle, E as RuntimeCapabilities, F as TraceContext, G as TraceStepStatus, H as TracePayloadVisibility, I as TraceEvent, J as createRuntimeContext, K as TraceStepView, L as TraceEventContentPolicy, M as TraceActivityContext, N as TraceActivityOwner, O as RuntimeContextInput, P as TraceActivityPhase, Q as deriveTraceRuns, R as TraceEventLog, S as PolicyContext, T as RunLifecycleHooks, U as TraceRunStatus, V as TraceEventPayload, W as TraceRunView, X as createTraceEventLog, Z as defineCapability, _ as MaybeResolvable, a as AnonymousAccessAuthorizationContext, at as normalizeExecutionAuthority, b as OpenTelemetrySpanView, c as ApprovalRequest, d as CapabilityHandle, dt as ViteHubContext, et as getCapability, f as CapabilityPolicy, ft as ViteHubRuntime, g as MaybePromise, h as ExecutionContext, i as AccessAuthorizeResult, it as noExecutionAuthority, j as RuntimeWaitUntilController, k as RuntimeHostContext, l as ApprovalState, m as ExecutionAuthority, n as AccessAuthorize, nt as isExecutionAuthority, o as AnonymousAccessAuthorize, ot as resolveCapabilityPolicy, p as CreatedRuntimeContext, pt as ViteHubStandardProps, q as createExecutionContext, r as AccessAuthorizeOption, s as ApprovalDecision, t as AccessAuthorizationContext, tt as hasCapability, u as CapabilityDefinition, ut as unknownExecutionAuthority, v as OpenTelemetryLogRecordView, w as Resolvable, x as OpenTelemetrySpanViewOptions, y as OpenTelemetrySpanEventView, z as TraceEventLogEntry } from "./core-auTkK4iZ.js";
2
- import { $ as ResultError, A as formatRuntimeDiagnosticError, B as LeaseErrorCode, C as RuntimeDiagnosticReporter, D as RuntimeResourceSnapshot, E as RuntimeResourceScope, F as parseDuration, G as LeaseStore, H as LeaseRecord, I as getInstanceId, J as DefineErrorsOptions, K as createMemoryLeaseStore, L as instanceIdEnv, M as normalizeRuntimeDiagnosticError, N as Duration, O as RuntimeResourceSupport, P as DurationUnit, Q as Result, R as Lease, S as RuntimeDiagnosticLevel, T as RuntimeResourceObservation, U as LeaseSqlClient, V as LeaseOperation, W as LeaseSqlParam, X as ErrorCodes, Y as ErrorCatalog, Z as ErrorHandle, _ as getViteHubErrorShape, a as RequestRuntimeContext, b as RuntimeDiagnosticErrorOptions, c as getRuntimeContext, et as defineErrors, f as ViteHubError, g as ViteHubErrorShape, h as ViteHubErrorOptions, i as ViteHubHost, j as isRuntimeDiagnostic, k as RuntimeResourceUnit, l as getStandardContext, m as ViteHubErrorDetails, n as detectHost, o as RuntimeContextOptions, p as ViteHubErrorDetail, q as createSqlLeaseStore, r as getHostBinding, s as RuntimeName, t as HostBindingErrorCode, tt as toResultError, v as isViteHubError, w as RuntimeResourceInspector, x as RuntimeDiagnosticEvent, y as RuntimeDiagnosticError, z as LeaseAcquireOptions } from "./index-hFKl7B_y.js";
3
- import { n as hostedConsoleUrl } from "./hosted-console-DTh9zwNz.js";
4
- import { o as resolvePublicUrl, t as PublicUrlConfig } from "./public-url-B4p8EOqr.js";
2
+ import { $ as toResultError, A as normalizeRuntimeDiagnosticError, B as LeaseRecord, C as RuntimeResourceObservation, D as RuntimeResourceUnit, E as RuntimeResourceSupport, F as instanceIdEnv, G as createSqlLeaseStore, H as LeaseSqlParam, I as Lease, J as ErrorCodes, K as DefineErrorsOptions, L as LeaseAcquireOptions, M as DurationUnit, N as parseDuration, O as formatRuntimeDiagnosticError, P as getInstanceId, Q as defineErrors, R as LeaseErrorCode, S as RuntimeResourceInspector, T as RuntimeResourceSnapshot, U as LeaseStore, V as LeaseSqlClient, W as createMemoryLeaseStore, X as Result, Y as ErrorHandle, Z as ResultError, _ as RuntimeDiagnosticError, a as RuntimeName, b as RuntimeDiagnosticLevel, d as ViteHubErrorDetail, f as ViteHubErrorDetails, g as isViteHubError, h as getViteHubErrorShape, i as RuntimeContextOptions, j as Duration, k as isRuntimeDiagnostic, m as ViteHubErrorShape, n as getHostBinding, o as getRuntimeContext, p as ViteHubErrorOptions, q as ErrorCatalog, r as RequestRuntimeContext, s as getStandardContext, t as HostBindingErrorCode, u as ViteHubError, v as RuntimeDiagnosticErrorOptions, w as RuntimeResourceScope, x as RuntimeDiagnosticReporter, y as RuntimeDiagnosticEvent, z as LeaseOperation } from "./index-fSQ1ELEy.js";
3
+ import { t as hostedConsoleUrl } from "./hosted-console-DInG3Xl9.js";
4
+ import { o as resolvePublicUrl, t as PublicUrlConfig } from "./public-url-CaVJ4vFF.js";
5
5
  import { a as ExecutionBudgetOptions, i as ExecutionBudgetLimits, n as ExecutionBudgetCounter, o as ExecutionBudgetSnapshot, r as ExecutionBudgetExceededError, s as ExecutionBudgetUsage, t as ExecutionBudget } from "./execution-budget-Bv7h0-5V.js";
6
6
  import { o as toResponse, t as SerializedResponse } from "./response-ClQ9ZSS_.js";
7
+ import { n as ViteHubHost, t as detectHost } from "./detect-host-uTgoQ9i4.js";
7
8
  export { type AccessAuthorizationContext, type AccessAuthorize, type AccessAuthorizeOption, type AccessAuthorizeResult, type AnonymousAccessAuthorizationContext, type AnonymousAccessAuthorize, type ApprovalDecision, type ApprovalRequest, type ApprovalState, type CapabilityDefinition, type CapabilityHandle, type CapabilityPolicy, type CreatedRuntimeContext, type DefineErrorsOptions, type Duration, type DurationUnit, type ErrorCatalog, type ErrorCodes, type ErrorHandle, type ExecutionAuthority, type ExecutionBudget, type ExecutionBudgetCounter, type ExecutionBudgetExceededError, type ExecutionBudgetLimits, type ExecutionBudgetOptions, type ExecutionBudgetSnapshot, type ExecutionBudgetUsage, type ExecutionContext, type HostBindingErrorCode, type Lease, type LeaseAcquireOptions, type LeaseErrorCode, type LeaseOperation, type LeaseRecord, type LeaseSqlClient, type LeaseSqlParam, type LeaseStore, type MaybePromise, type MaybeResolvable, type OpenTelemetryLogRecordView, type OpenTelemetrySpanEventView, type OpenTelemetrySpanView, type OpenTelemetrySpanViewOptions, type PolicyContext, type PolicyDecision, type PublicUrlConfig, type RequestRuntimeContext, type Resolvable, type Result, type ResultError, type RunLifecycleHooks, type RuntimeCapabilities, type RuntimeCapabilityHandle, type RuntimeContextInput, type RuntimeContextOptions, type RuntimeDiagnosticError, type RuntimeDiagnosticErrorOptions, type RuntimeDiagnosticEvent, type RuntimeDiagnosticLevel, type RuntimeDiagnosticReporter, type RuntimeHostContext, type RuntimeName, type RuntimeResourceInspector, type RuntimeResourceObservation, type RuntimeResourceScope, type RuntimeResourceSnapshot, type RuntimeResourceSupport, type RuntimeResourceUnit, type RuntimeWaitUntil, type RuntimeWaitUntilController, type SerializedResponse, type TraceActivityContext, type TraceActivityOwner, type TraceActivityPhase, type TraceContext, type TraceEvent, type TraceEventContentPolicy, type TraceEventLog, type TraceEventLogEntry, type TraceEventLogOptions, type TraceEventPayload, type TracePayloadVisibility, type TraceRunStatus, type TraceRunView, type TraceStepStatus, type TraceStepView, type ViteHubContext, ViteHubError, type ViteHubErrorDetail, type ViteHubErrorDetails, type ViteHubErrorOptions, type ViteHubErrorShape, type ViteHubHost, type ViteHubRuntime, type ViteHubStandardProps, createExecutionContext, createMemoryLeaseStore, createRuntimeContext, createSqlLeaseStore, createTraceEventLog, defineCapability, defineErrors, deriveTraceRuns, detectHost, formatRuntimeDiagnosticError, getCapability, getHostBinding, getInstanceId, getRuntimeContext, getStandardContext, getViteHubErrorShape, hasCapability, hostedConsoleUrl, instanceIdEnv, isExecutionAuthority, isRuntimeDiagnostic, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, parseDuration, resolveCapabilityPolicy, resolvePublicUrl, toResponse, toResultError, unknownExecutionAuthority };
package/dist/index.js CHANGED
@@ -1,6 +1,8 @@
1
- import { _ as instanceIdEnv, d as parseDuration, f as createMemoryLeaseStore, g as getInstanceId, h as toResultError, i as getStandardContext, l as detectHost, m as defineErrors, p as createSqlLeaseStore, r as getRuntimeContext, u as getHostBinding } from "./request-context-Ci5FjuUY.js";
1
+ import { d as createMemoryLeaseStore, f as createSqlLeaseStore, g as instanceIdEnv, h as getInstanceId, i as getStandardContext, l as getHostBinding, m as toResultError, p as defineErrors, r as getRuntimeContext, u as parseDuration } from "./request-context-Dcf59Qh4.js";
2
2
  import { n as getViteHubErrorShape, r as isViteHubError, t as ViteHubError } from "./errors-D2ixvqv3.js";
3
3
  import { a as defineCapability, c as getCapability, f as noExecutionAuthority, i as createTraceEventLog, l as hasCapability, m as resolveCapabilityPolicy, n as createRuntimeContext, o as deriveTraceRuns, p as normalizeExecutionAuthority, t as createExecutionContext, u as isExecutionAuthority, v as unknownExecutionAuthority } from "./core-Crv8CV_r.js";
4
4
  import { a as toResponse, c as normalizeRuntimeDiagnosticError, o as formatRuntimeDiagnosticError, s as isRuntimeDiagnostic } from "./response-DEyMvEBF.js";
5
- import { a as resolvePublicUrl, l as hostedConsoleUrl } from "./public-url-DDh_BHz3.js";
5
+ import { a as resolvePublicUrl } from "./public-url-TlEVxNNh.js";
6
+ import { t as hostedConsoleUrl } from "./hosted-console-nLc1pL9J.js";
7
+ import { t as detectHost } from "./detect-host-Du9saPsM.js";
6
8
  export { ViteHubError, createExecutionContext, createMemoryLeaseStore, createRuntimeContext, createSqlLeaseStore, createTraceEventLog, defineCapability, defineErrors, deriveTraceRuns, detectHost, formatRuntimeDiagnosticError, getCapability, getHostBinding, getInstanceId, getRuntimeContext, getStandardContext, getViteHubErrorShape, hasCapability, hostedConsoleUrl, instanceIdEnv, isExecutionAuthority, isRuntimeDiagnostic, isViteHubError, noExecutionAuthority, normalizeExecutionAuthority, normalizeRuntimeDiagnosticError, parseDuration, resolveCapabilityPolicy, resolvePublicUrl, toResponse, toResultError, unknownExecutionAuthority };
@@ -1,5 +1,12 @@
1
- import { i as normalizeConsoleProjectUrl, r as normalizeConsolePath, t as hostedConsoleOrigin } from "../hosted-console-DTh9zwNz.js";
2
- import { r as consoleInvocationUrl } from "../public-url-B4p8EOqr.js";
1
+ import { n as normalizeConsolePath, r as normalizeConsoleProjectUrl, t as hostedConsoleUrl } from "../hosted-console-DInG3Xl9.js";
2
+ import { r as consoleInvocationUrl } from "../public-url-CaVJ4vFF.js";
3
+ /** The origin of the hosted Console. */
4
+ export declare const hostedConsoleOrigin = "https://console.vitehub.dev";
5
+ /**
6
+ * The origin of the ViteHub Console that opens this app: `vitehub({ console: { url } })` of a self-hosted Console, else
7
+ * the hosted Console.
8
+ */
9
+ export declare function configuredConsoleOrigin(): string;
3
10
  export declare function encodeRouteSegment(value: string): string;
4
11
  export declare function decodeRouteSegment(segment: string): string | undefined;
5
- export { consoleInvocationUrl, hostedConsoleOrigin, normalizeConsolePath, normalizeConsoleProjectUrl };
12
+ export { consoleInvocationUrl, hostedConsoleUrl, normalizeConsolePath, normalizeConsoleProjectUrl };
@@ -1 +1,3 @@
1
- export { n as consoleInvocationUrl, o as decodeRouteSegment, s as encodeRouteSegment, c as hostedConsoleOrigin, u as normalizeConsolePath, d as normalizeConsoleProjectUrl } from "../public-url-DDh_BHz3.js";
1
+ import { n as normalizeConsolePath, r as normalizeConsoleProjectUrl, t as hostedConsoleUrl } from "../hosted-console-nLc1pL9J.js";
2
+ import { c as configuredConsoleOrigin, l as hostedConsoleOrigin, n as consoleInvocationUrl, o as decodeRouteSegment, s as encodeRouteSegment } from "../public-url-TlEVxNNh.js";
3
+ export { configuredConsoleOrigin, consoleInvocationUrl, decodeRouteSegment, encodeRouteSegment, hostedConsoleOrigin, hostedConsoleUrl, normalizeConsolePath, normalizeConsoleProjectUrl };
@@ -0,0 +1,2 @@
1
+ import { t as detectHost } from "../detect-host-uTgoQ9i4.js";
2
+ export { detectHost };
@@ -0,0 +1 @@
1
+ export { t as detectHost } from "../detect-host-Du9saPsM.js";
@@ -1,4 +1,4 @@
1
- import { a as RequestRuntimeContext, d as sendPreparedResponse, o as RuntimeContextOptions, u as installRequestStandardContext } from "../index-hFKl7B_y.js";
1
+ import { c as installRequestStandardContext, i as RuntimeContextOptions, l as sendPreparedResponse, r as RequestRuntimeContext } from "../index-fSQ1ELEy.js";
2
2
  import { dt as ViteHubContext, ft as ViteHubRuntime, pt as ViteHubStandardProps } from "../core-auTkK4iZ.js";
3
3
  import { EventHandlerRequest } from "h3";
4
4
  declare module "h3" {
@@ -1,4 +1,4 @@
1
- import { S as ownValue, a as installRequestStandardContext, b as getCloudflareEnv, c as sendPreparedResponse, i as getStandardContext$1, n as firstAddress, o as isHostRequest, s as requestAddressPaths, t as createStandardRuntimeContext, v as activeEnvStorageKey, x as ownObject, y as cloudflareOwners } from "../request-context-Ci5FjuUY.js";
1
+ import { _ as activeEnvStorageKey, a as installRequestStandardContext, b as ownObject, c as sendPreparedResponse, i as getStandardContext$1, n as firstAddress, o as isHostRequest, s as requestAddressPaths, t as createStandardRuntimeContext, v as cloudflareOwners, x as ownValue, y as getCloudflareEnv } from "../request-context-Dcf59Qh4.js";
2
2
  import { t as runtimeErrorDiagnostics } from "../error-diagnostics-Dj98U7ch.js";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  // ../internal/dist/runtime/cloudflare-env.js
@@ -1,4 +1,4 @@
1
- import { w as RuntimeResourceInspector } from "../index-hFKl7B_y.js";
1
+ import { S as RuntimeResourceInspector } from "../index-fSQ1ELEy.js";
2
2
  type ReadText = (path: string, options?: {
3
3
  signal?: AbortSignal;
4
4
  }) => Promise<string>;
@@ -1,2 +1,2 @@
1
- import { a as resetPublicUrlAgentNames, i as registerPublicUrlAgentName, n as configuredPublicOrigins } from "../public-url-B4p8EOqr.js";
1
+ import { a as resetPublicUrlAgentNames, i as registerPublicUrlAgentName, n as configuredPublicOrigins } from "../public-url-CaVJ4vFF.js";
2
2
  export { configuredPublicOrigins, registerPublicUrlAgentName, resetPublicUrlAgentNames };
@@ -1 +1 @@
1
- export { t as configuredPublicOrigins, r as registerPublicUrlAgentName, i as resetPublicUrlAgentNames } from "../public-url-DDh_BHz3.js";
1
+ export { t as configuredPublicOrigins, r as registerPublicUrlAgentName, i as resetPublicUrlAgentNames } from "../public-url-TlEVxNNh.js";
@@ -1,4 +1,4 @@
1
1
  import { $ as emitTraceEvent, ct as traceEventsToOpenTelemetryLogRecords, lt as traceEventsToOpenTelemetrySpans } from "../core-auTkK4iZ.js";
2
- import "../index-hFKl7B_y.js";
2
+ import "../index-fSQ1ELEy.js";
3
3
  export declare function isTraceContentAttributeKey(key: string): boolean;
4
4
  export { emitTraceEvent, traceEventsToOpenTelemetryLogRecords, traceEventsToOpenTelemetrySpans };
@@ -32,6 +32,7 @@ declare function resolvePublicUrl(options?: {
32
32
  * Build the hosted Console URL that opens one Agent invocation, such as
33
33
  * `https://console.vitehub.dev/open?project=https%3A%2F%2Fapp.example.com&path=%2Fagents%2Fbot%2Finvocations%2Fid`.
34
34
  * `origin` must not include the application base path. The hosted Console checks the project URL when it opens the link.
35
+ * A self-hosted Console of `vitehub({ console: { url } })` replaces the hosted origin.
35
36
  */
36
37
  declare function consoleInvocationUrl(origin: string, agentName: string, invocationId: string): string;
37
38
  export { resetPublicUrlAgentNames as a, registerPublicUrlAgentName as i, configuredPublicOrigins as n, resolvePublicUrl as o, consoleInvocationUrl as r, PublicUrlConfig as t };
@@ -1,72 +1,12 @@
1
- import { t as runtimeErrorDiagnostics } from "./error-diagnostics-Dj98U7ch.js";
2
- // src/hosted-console.ts
1
+ // src/hosted-console-origin.ts
3
2
  /** The origin of the hosted Console. */
4
3
  const hostedConsoleOrigin = "https://console.vitehub.dev";
5
- const loopbackHosts = /* @__PURE__ */ new Set([
6
- "localhost",
7
- "127.0.0.1",
8
- "[::1]"
9
- ]);
10
- const pathBase = "https://console.invalid";
11
4
  /**
12
- * The Console path of a link, such as `/agents/bot/invocations/abc?tab=trace`, or `undefined` when the value is not a
13
- * Console path. A Console path starts with one `/`. Absolute URLs, protocol-relative URLs, and backslashes are not
14
- * Console paths, so a link cannot send the browser to another site. A path that starts with `/_vitehub`, as on a
15
- * Console that the app serves, loses that prefix.
5
+ * The origin of the ViteHub Console that opens this app: `vitehub({ console: { url } })` of a self-hosted Console, else
6
+ * the hosted Console.
16
7
  */
17
- function normalizeConsolePath(path) {
18
- if (!path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return void 0;
19
- let url;
20
- try {
21
- url = new URL(path, pathBase);
22
- } catch {
23
- return;
24
- }
25
- if (url.origin !== pathBase) return void 0;
26
- const pathname = url.pathname.replace(/^\/_vitehub(?=\/|$)/, "") || "/";
27
- if (pathname.startsWith("//")) return void 0;
28
- return `${pathname}${url.search}${url.hash}`;
29
- }
30
- /**
31
- * The project URL of a link: the app origin and its application mount, such as `https://app.example.com/portal`, or
32
- * `undefined` when the URL cannot be a project. A project URL is `https:`, or `http:` on a loopback host, and has no
33
- * user name or password.
34
- */
35
- function normalizeConsoleProjectUrl(projectUrl) {
36
- let url;
37
- try {
38
- url = new URL(projectUrl);
39
- } catch {
40
- return;
41
- }
42
- if (url.username || url.password) return void 0;
43
- if (url.protocol !== "https:" && !(url.protocol === "http:" && loopbackHosts.has(url.hostname))) return void 0;
44
- const mount = url.pathname.search(/\/_vitehub(?=\/|$)/);
45
- const base = (mount === -1 ? url.pathname : url.pathname.slice(0, mount)).replace(/\/+$/, "");
46
- return `${url.origin}${base}`;
47
- }
48
- /**
49
- * The hosted Console URL that opens one page of a project, such as
50
- * `https://console.vitehub.dev/open?project=https%3A%2F%2Fapp.example.com&path=%2Fkv`.
51
- *
52
- * `projectUrl` is the app origin with its application mount, such as `https://app.example.com/portal`. `path` is the
53
- * Console path, such as `/agents/bot/invocations/abc`. The hosted Console switches to the project when this browser
54
- * linked it, or asks the person to link it first. The URL holds no secret.
55
- *
56
- * Throws `RUNTIME_CONSOLE_PROJECT_URL_INVALID` when `projectUrl` is not `https:` (or `http:` on a loopback host), and
57
- * `RUNTIME_CONSOLE_PATH_INVALID` when `path` is not a Console path.
58
- */
59
- function hostedConsoleUrl(projectUrl, path, consoleOrigin = hostedConsoleOrigin) {
60
- const project = normalizeConsoleProjectUrl(projectUrl);
61
- if (!project) throw runtimeErrorDiagnostics.RUNTIME_CONSOLE_PROJECT_URL_INVALID({ value: projectUrl });
62
- const consolePath = normalizeConsolePath(path);
63
- if (!consolePath) throw runtimeErrorDiagnostics.RUNTIME_CONSOLE_PATH_INVALID({ value: path });
64
- const url = new URL("/open", consoleOrigin);
65
- url.search = new URLSearchParams({
66
- project,
67
- path: consolePath
68
- }).toString();
69
- return url.href;
8
+ function configuredConsoleOrigin() {
9
+ return typeof __VITEHUB_CONSOLE_URL__ === "string" ? __VITEHUB_CONSOLE_URL__ : hostedConsoleOrigin;
70
10
  }
71
11
  // src/route-segment.ts
72
12
  const plainSegment = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -136,10 +76,11 @@ function resolvePublicUrl(options = {}) {
136
76
  * Build the hosted Console URL that opens one Agent invocation, such as
137
77
  * `https://console.vitehub.dev/open?project=https%3A%2F%2Fapp.example.com&path=%2Fagents%2Fbot%2Finvocations%2Fid`.
138
78
  * `origin` must not include the application base path. The hosted Console checks the project URL when it opens the link.
79
+ * A self-hosted Console of `vitehub({ console: { url } })` replaces the hosted origin.
139
80
  */
140
81
  function consoleInvocationUrl(origin, agentName, invocationId) {
141
82
  const project = `${new URL(origin).origin}${applicationBasePath()}`;
142
83
  const path = `/agents/${encodeRouteSegment(agentName)}/invocations/${encodeURIComponent(invocationId)}`;
143
- return `${hostedConsoleOrigin}/open?project=${encodeURIComponent(project)}&path=${encodeURIComponent(path)}`;
84
+ return `${configuredConsoleOrigin()}/open?project=${encodeURIComponent(project)}&path=${encodeURIComponent(path)}`;
144
85
  }
145
- export { resolvePublicUrl as a, hostedConsoleOrigin as c, normalizeConsoleProjectUrl as d, resetPublicUrlAgentNames as i, hostedConsoleUrl as l, consoleInvocationUrl as n, decodeRouteSegment as o, registerPublicUrlAgentName as r, encodeRouteSegment as s, configuredPublicOrigins as t, normalizeConsolePath as u };
86
+ export { resolvePublicUrl as a, configuredConsoleOrigin as c, resetPublicUrlAgentNames as i, hostedConsoleOrigin as l, consoleInvocationUrl as n, decodeRouteSegment as o, registerPublicUrlAgentName as r, encodeRouteSegment as s, configuredPublicOrigins as t };
@@ -450,42 +450,6 @@ function parseDuration(value, option, round, legacyUnit = "ms") {
450
450
  unit: legacyUnitName
451
451
  });
452
452
  }
453
- /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
454
- function hostFromNitroPreset(value) {
455
- const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
456
- if (!normalized) return;
457
- if (normalized.startsWith("cloudflare")) return "cloudflare";
458
- if (normalized.startsWith("deno")) return "deno";
459
- if (normalized.startsWith("netlify")) return "netlify";
460
- if (normalized === "node" || normalized.startsWith("node-")) return "node";
461
- if (normalized.startsWith("vercel")) return "vercel";
462
- }
463
- const providerHosts = [
464
- ["WORKERS_CI", "cloudflare"],
465
- ["NETLIFY", "netlify"],
466
- ["NOW_BUILDER", "vercel"],
467
- ["VERCEL", "vercel"],
468
- ["VERCEL_ENV", "vercel"],
469
- ["DENO_DEPLOY", "deno"],
470
- ["DENO_DEPLOYMENT_ID", "deno"]
471
- ];
472
- /**
473
- * Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
474
- * The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
475
- * `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
476
- * `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
477
- */
478
- function detectHost$1(env = process.env) {
479
- for (const name of [
480
- "VITEHUB_HOST",
481
- "NITRO_PRESET",
482
- "SERVER_PRESET"
483
- ]) {
484
- const host = hostFromNitroPreset(env[name]);
485
- if (host) return host;
486
- }
487
- return providerHosts.find(([name]) => env[name]?.trim())?.[1];
488
- }
489
453
  // src/host.ts
490
454
  const hostBindingErrors = /*#__PURE__*/ defineErrors({
491
455
  docs: "https://vitehub.dev/docs/runtime/diagnostics",
@@ -500,25 +464,6 @@ const hostBindingErrors = /*#__PURE__*/ defineErrors({
500
464
  }
501
465
  }
502
466
  });
503
- /**
504
- * Returns the host that this code builds or runs on, or `undefined` when nothing names one.
505
- * It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
506
- * (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
507
- * `vitehub()` uses the same detection when `host` is omitted.
508
- *
509
- * @example
510
- * ```ts
511
- * import { detectHost } from "vite-hub/runtime"
512
- *
513
- * const host = detectHost() ?? "node"
514
- * ```
515
- */
516
- function detectHost(env = processEnv()) {
517
- return detectHost$1(env) ?? (globalThis.navigator?.userAgent === "Cloudflare-Workers" ? "cloudflare" : void 0);
518
- }
519
- function processEnv() {
520
- return globalThis.process?.env ?? {};
521
- }
522
467
  function getHostBinding(name, event) {
523
468
  const env = (event && hostBindingsOf(event)) ?? getActiveCloudflareEnv();
524
469
  if (!env) return [hostBindingErrors.RUNTIME_HOST_BINDINGS_UNAVAILABLE({ name }), void 0];
@@ -677,4 +622,4 @@ function createStandardRuntimeContext(event, standard, options) {
677
622
  function getRuntimeContext(value, options = {}) {
678
623
  return createStandardRuntimeContext(value, getStandardContext(value), options);
679
624
  }
680
- export { ownValue as S, instanceIdEnv as _, installRequestStandardContext as a, getCloudflareEnv as b, sendPreparedResponse as c, parseDuration as d, createMemoryLeaseStore as f, getInstanceId as g, toResultError as h, getStandardContext as i, detectHost as l, defineErrors as m, firstAddress as n, isHostRequest as o, createSqlLeaseStore as p, getRuntimeContext as r, requestAddressPaths as s, createStandardRuntimeContext as t, getHostBinding as u, activeEnvStorageKey as v, ownObject as x, cloudflareOwners as y };
625
+ export { activeEnvStorageKey as _, installRequestStandardContext as a, ownObject as b, sendPreparedResponse as c, createMemoryLeaseStore as d, createSqlLeaseStore as f, instanceIdEnv as g, getInstanceId as h, getStandardContext as i, getHostBinding as l, toResultError as m, firstAddress as n, isHostRequest as o, defineErrors as p, getRuntimeContext as r, requestAddressPaths as s, createStandardRuntimeContext as t, parseDuration as u, cloudflareOwners as v, ownValue as x, getCloudflareEnv as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/runtime",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "Shared runtime context, capability, policy, approval, and tracing primitives for ViteHub.",
5
5
  "keywords": [
6
6
  "approvals",
@@ -47,6 +47,11 @@
47
47
  "import": "./dist/internal/context.js",
48
48
  "default": "./dist/internal/context.js"
49
49
  },
50
+ "./internal/detect-host": {
51
+ "types": "./dist/internal/detect-host.d.ts",
52
+ "import": "./dist/internal/detect-host.js",
53
+ "default": "./dist/internal/detect-host.js"
54
+ },
50
55
  "./internal/drain": {
51
56
  "types": "./dist/internal/drain.d.ts",
52
57
  "import": "./dist/internal/drain.js",