@vite-hub/runtime 0.1.0 → 0.3.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 (44) hide show
  1. package/README.md +151 -117
  2. package/dist/durability.d.ts +107 -0
  3. package/dist/durability.js +168 -0
  4. package/dist/error-diagnostics-BKICpwZp.js +85 -0
  5. package/dist/error-diagnostics-BsJr9VdW.d.ts +15 -0
  6. package/dist/{errors-CbqHQTvn.js → errors-BEomN3fX.js} +1 -1
  7. package/dist/{execution-budget-D8SwJE8_.d.ts → execution-budget-BPXbISEt.d.ts} +9 -6
  8. package/dist/index-Bcl-Hr-a.d.ts +678 -0
  9. package/dist/index.d.ts +5 -4
  10. package/dist/index.js +5 -4
  11. package/dist/internal/drain.d.ts +17 -0
  12. package/dist/internal/drain.js +75 -0
  13. package/dist/internal/execution-budget.d.ts +1 -1
  14. package/dist/internal/grant.js +2 -2
  15. package/dist/internal/h3.d.ts +42 -0
  16. package/dist/internal/h3.js +181 -0
  17. package/dist/{node.d.ts → internal/node.d.ts} +2 -2
  18. package/dist/{node.js → internal/node.js} +4 -4
  19. package/dist/internal/public-url.d.ts +2 -0
  20. package/dist/internal/public-url.js +2 -0
  21. package/dist/internal/run-scope.d.ts +11 -0
  22. package/dist/internal/run-scope.js +30 -0
  23. package/dist/internal/runtime-type.d.ts +9 -2
  24. package/dist/internal/runtime-type.js +3 -2
  25. package/dist/{shutdown.d.ts → internal/shutdown.d.ts} +1 -1
  26. package/dist/{shutdown.js → internal/shutdown.js} +1 -1
  27. package/dist/internal/test-mode-setup.d.ts +7 -0
  28. package/dist/internal/test-mode-setup.js +114 -0
  29. package/dist/internal/test-mode.d.ts +32 -0
  30. package/dist/internal/test-mode.js +9 -0
  31. package/dist/operations.d.ts +167 -0
  32. package/dist/operations.js +406 -0
  33. package/dist/public-url-1WeOw54Z.d.ts +34 -0
  34. package/dist/public-url-B6x0HMgY.js +140 -0
  35. package/dist/{src-jy-gyPPu.js → request-context-CP9NhgLL.js} +635 -551
  36. package/dist/runtime-type-BftydMAf.js +88 -0
  37. package/package.json +61 -26
  38. package/dist/drain.d.ts +0 -1
  39. package/dist/drain.js +0 -69
  40. package/dist/error-diagnostics-Bkym4e6y.d.ts +0 -12
  41. package/dist/h3.d.ts +0 -49
  42. package/dist/h3.js +0 -404
  43. package/dist/index-Rl4DbP8B.d.ts +0 -574
  44. package/dist/runtime-type-CgfU6SWl.js +0 -52
@@ -1,6 +1,45 @@
1
- import { i as runtimeErrorDiagnostics, n as hasRuntimeType, r as isRuntimeObject } from "./runtime-type-CgfU6SWl.js";
2
- import { n as getViteHubErrorShape, t as ViteHubError } from "./errors-CbqHQTvn.js";
1
+ import { t as runtimeErrorDiagnostics } from "./error-diagnostics-BKICpwZp.js";
2
+ import { r as isRuntimeObject } from "./runtime-type-BftydMAf.js";
3
+ import { n as getViteHubErrorShape, t as ViteHubError } from "./errors-BEomN3fX.js";
3
4
  import { Diagnostic, defineDiagnostics, formatDiagnostic } from "nostics";
5
+ //#region ../internal/dist/runtime/cloudflare-env-lookup.js
6
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
7
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
8
+ let activeEnv;
9
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
10
+ function getScopedCloudflareEnv() {
11
+ return globalThis[activeEnvStorageKey]?.getStore();
12
+ }
13
+ function getActiveCloudflareEnv() {
14
+ const scoped = getScopedCloudflareEnv();
15
+ if (scoped) return scoped.env;
16
+ const host = globalThis;
17
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
18
+ }
19
+ function ownValue(value, key) {
20
+ if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
21
+ return Reflect.get(value, key);
22
+ }
23
+ function ownObject(value) {
24
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
25
+ }
26
+ /** The objects where H3 and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
27
+ function cloudflareOwners(target) {
28
+ const context = ownObject(ownValue(target, "context"));
29
+ const platform = ownObject(ownValue(context, "_platform"));
30
+ const req = ownObject(ownValue(target, "req"));
31
+ return [
32
+ ownObject(ownValue(context, "cloudflare")),
33
+ ownObject(ownValue(platform, "cloudflare")),
34
+ ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"))
35
+ ];
36
+ }
37
+ function getCloudflareEnv(event, options = {}) {
38
+ const target = ownObject(event);
39
+ for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
40
+ return options.fallback === false ? void 0 : getActiveCloudflareEnv();
41
+ }
42
+ //#endregion
4
43
  //#region src/internal/trace-attributes.ts
5
44
  const contentAttributeKeys = /* @__PURE__ */ new Set([
6
45
  "args",
@@ -36,7 +75,7 @@ function isTraceContentAttributeKey(key) {
36
75
  function ownProperties(value) {
37
76
  if (!isRuntimeObject(value)) return [];
38
77
  return Reflect.ownKeys(value).flatMap((key) => {
39
- if (!hasRuntimeType(key, "string")) return [];
78
+ if (typeof key !== "string") return [];
40
79
  const descriptor = Object.getOwnPropertyDescriptor(value, key);
41
80
  return descriptor?.enumerable ? [[key, descriptor]] : [];
42
81
  });
@@ -52,7 +91,7 @@ function mapArray(value, map) {
52
91
  return next;
53
92
  }
54
93
  function metadataValue(value, seen) {
55
- if (!value || !hasRuntimeType(value, "object")) return value;
94
+ if (!value || typeof value !== "object") return value;
56
95
  if (seen.has(value)) return "[Circular]";
57
96
  seen.add(value);
58
97
  try {
@@ -88,7 +127,7 @@ function normalizeTraceAttributes(attributes, content) {
88
127
  const source = projectProperties(properties, "content", /* @__PURE__ */ new WeakSet());
89
128
  try {
90
129
  if (Array.isArray(source["content.omitted"])) {
91
- const omitted = mapArray(source["content.omitted"], (value) => value).filter((key) => hasRuntimeType(key, "string") && !canonicalAttributeKeys.has(key));
130
+ const omitted = mapArray(source["content.omitted"], (value) => value).filter((key) => typeof key === "string" && !canonicalAttributeKeys.has(key));
92
131
  if (omitted.length) source["content.omitted"] = omitted;
93
132
  else delete source["content.omitted"];
94
133
  }
@@ -108,296 +147,17 @@ function normalizeTraceAttributes(attributes, content) {
108
147
  return Object.keys(source).length ? source : void 0;
109
148
  }
110
149
  //#endregion
111
- //#region src/preflight.ts
112
- const preflightDiagnostics = defineDiagnostics({
113
- docsBase: () => "https://vitehub.dev/docs/reference/errors-diagnostics#runtime-preflight",
114
- codes: {
115
- RUNTIME_R0012: {
116
- why: ({ checkId, kind }) => `Runtime preflight could not find ${kind} capability "${checkId}".`,
117
- fix: "Provide the capability in the execution environment, or mark this check optional when the Agent can continue without it.",
118
- data: (params) => params
119
- },
120
- RUNTIME_R0013: {
121
- why: ({ checkId, kind }) => `Runtime preflight could not verify ${kind} capability "${checkId}".`,
122
- fix: "Inspect the check reason and verify the capability from the same runtime that starts the Agent.",
123
- data: (params) => params
124
- }
125
- }
126
- });
127
- const maxReasonLength = 256;
128
- const maxDetailCount = 12;
129
- const maxCheckIdLength = 128;
130
- const maxCheckKindLength = 64;
131
- function normalizeReason(value) {
132
- if (!hasRuntimeType(value, "string")) return;
133
- return value.slice(0, maxReasonLength).trim() || void 0;
134
- }
135
- function normalizeThrownReason(value) {
136
- try {
137
- if (value instanceof Error) return normalizeReason(value.message);
138
- if (value !== null && hasRuntimeType(value, "object")) {
139
- const message = Object.getOwnPropertyDescriptor(value, "message");
140
- if (message && "value" in message) return normalizeReason(message.value);
141
- }
142
- return normalizeReason(value);
143
- } catch {
144
- return;
145
- }
146
- }
147
- function normalizeDetails$1(value) {
148
- if (value === null || !hasRuntimeType(value, "object") || Array.isArray(value)) return;
149
- const details = {};
150
- let count = 0;
151
- for (const key in value) {
152
- if (count++ >= maxDetailCount) break;
153
- if (!key || key.length > 64) continue;
154
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
155
- if (!descriptor || !("value" in descriptor)) continue;
156
- const child = descriptor.value;
157
- if (child === null || hasRuntimeType(child, "string") || hasRuntimeType(child, "boolean") || hasRuntimeType(child, "number") && Number.isFinite(child)) Object.defineProperty(details, key, {
158
- value: hasRuntimeType(child, "string") ? child.slice(0, maxReasonLength) : child,
159
- enumerable: true
160
- });
161
- }
162
- return Object.keys(details).length ? details : void 0;
163
- }
164
- function normalizeResult(value) {
165
- if (value === true) return { state: "available" };
166
- if (value === false) return { state: "missing" };
167
- if (value === "available" || value === "missing" || value === "unknown") return { state: value };
168
- if (value !== null && hasRuntimeType(value, "object") && !Array.isArray(value)) {
169
- const result = value;
170
- const rawState = result.state;
171
- let validState = false;
172
- let state = "unknown";
173
- if (rawState === "available" || rawState === "missing" || rawState === "unknown") {
174
- validState = true;
175
- state = rawState;
176
- }
177
- const normalized = { state };
178
- const details = normalizeDetails$1(result.details);
179
- if (details) normalized.details = details;
180
- const reason = normalizeReason(result.reason);
181
- if (reason) normalized.reason = reason;
182
- else if (!validState) normalized.reason = "The preflight check returned an invalid result.";
183
- return normalized;
184
- }
185
- return {
186
- state: "unknown",
187
- reason: "The preflight check returned an invalid result."
188
- };
189
- }
190
- function timeoutSignal(parent, timeoutMs) {
191
- const controller = new AbortController();
192
- const abort = () => controller.abort(parent.reason);
193
- const expire = () => controller.abort(/* @__PURE__ */ new Error("The preflight check timed out."));
194
- if (parent.aborted) abort();
195
- else parent.addEventListener("abort", abort, { once: true });
196
- const deadline = Date.now() + timeoutMs;
197
- const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("Runtime preflight check timed out.")), timeoutMs);
198
- const cancel = () => {
199
- clearTimeout(timer);
200
- parent.removeEventListener("abort", abort);
201
- };
202
- return {
203
- signal: controller.signal,
204
- deadline,
205
- cancel,
206
- expire
207
- };
208
- }
209
- async function resolveCheck(check, signal, deadline, expire) {
210
- let removeAbortListener;
211
- const aborted = new Promise((_, reject) => {
212
- const rejectAbort = () => reject(signal.reason || /* @__PURE__ */ new Error("Runtime preflight check was aborted."));
213
- if (signal.aborted) rejectAbort();
214
- else {
215
- signal.addEventListener("abort", rejectAbort, { once: true });
216
- removeAbortListener = () => signal.removeEventListener("abort", rejectAbort);
217
- }
218
- });
219
- const operation = Promise.resolve().then(() => {
220
- if (signal.aborted) throw signal.reason || /* @__PURE__ */ new Error("Runtime preflight check was aborted.");
221
- if (Date.now() >= deadline) {
222
- expire();
223
- return {
224
- state: "unknown",
225
- reason: "The preflight check timed out."
226
- };
227
- }
228
- const value = check.check({ signal });
229
- if (Date.now() >= deadline) {
230
- expire();
231
- Promise.resolve(value).catch(() => void 0);
232
- return {
233
- state: "unknown",
234
- reason: "The preflight check timed out."
235
- };
236
- }
237
- return value;
150
+ //#region src/execution-budget.ts
151
+ function executionBudgetExceededError(counter, limit) {
152
+ return Object.assign(runtimeErrorDiagnostics.RUNTIME_EXECUTION_BUDGET_EXCEEDED({ counter }), {
153
+ counter,
154
+ limit
238
155
  });
239
- operation.catch(() => void 0);
240
- try {
241
- const result = normalizeResult(await Promise.race([operation, aborted]));
242
- if (Date.now() >= deadline) {
243
- expire();
244
- return {
245
- state: "unknown",
246
- reason: "The preflight check timed out."
247
- };
248
- }
249
- return result;
250
- } finally {
251
- removeAbortListener?.();
252
- }
253
156
  }
254
- function diagnosticFor(check, state, reason) {
255
- if (state === "available") return;
256
- const params = {
257
- checkId: check.id,
258
- kind: check.kind,
259
- required: check.required === true,
260
- state
261
- };
262
- if (reason) params.reason = reason;
263
- return state === "missing" ? preflightDiagnostics.RUNTIME_R0012(params) : preflightDiagnostics.RUNTIME_R0013(params);
157
+ /** Whether `error` is the error of an execution budget that ran out. */
158
+ function isExecutionBudgetExceededError(error) {
159
+ return error instanceof Error && Reflect.get(error, "code") === "RUNTIME_EXECUTION_BUDGET_EXCEEDED";
264
160
  }
265
- function snapshotRuntimePreflightCheck(value) {
266
- if (value === null || !hasRuntimeType(value, "object")) return;
267
- try {
268
- const id = Reflect.get(value, "id");
269
- const kind = Reflect.get(value, "kind");
270
- const check = Reflect.get(value, "check");
271
- const required = Reflect.get(value, "required");
272
- if (!hasRuntimeType(id, "string") || !hasRuntimeType(kind, "string") || !hasRuntimeType(check, "function")) return;
273
- return {
274
- id,
275
- kind,
276
- check,
277
- required: required === true
278
- };
279
- } catch {
280
- return;
281
- }
282
- }
283
- function validateOptions(options) {
284
- if (!options || !Array.isArray(options.checks)) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: "[vitehub] Runtime preflight checks must be an array." });
285
- const timeoutMs = options.timeoutMs ?? 250;
286
- if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 1e4) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: "[vitehub] Runtime preflight timeoutMs must be between 1 and 10000." });
287
- const maxChecks = options.maxChecks ?? 32;
288
- if (!Number.isSafeInteger(maxChecks) || maxChecks < 1 || maxChecks > 128) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: "[vitehub] Runtime preflight maxChecks must be between 1 and 128." });
289
- if (options.checks.length > maxChecks) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: `[vitehub] Runtime preflight checks exceed maxChecks (${maxChecks}).` });
290
- const checks = [];
291
- const ids = /* @__PURE__ */ new Set();
292
- for (const value of options.checks) {
293
- const check = snapshotRuntimePreflightCheck(value);
294
- if (!check || !check.id.trim() || !check.kind.trim()) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: "[vitehub] Runtime preflight checks require an id, kind, and check function." });
295
- if (check.id.length > maxCheckIdLength) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: `[vitehub] Runtime preflight check id must be at most ${maxCheckIdLength} characters.` });
296
- if (check.kind.length > maxCheckKindLength) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: `[vitehub] Runtime preflight check kind must be at most ${maxCheckKindLength} characters.` });
297
- if (ids.has(check.id)) throw runtimeErrorDiagnostics.RUNTIME_R0014({ message: `[vitehub] Runtime preflight check "${check.id}" is duplicated.` });
298
- ids.add(check.id);
299
- checks.push(check);
300
- }
301
- return {
302
- checks,
303
- timeoutMs,
304
- maxChecks
305
- };
306
- }
307
- /**
308
- * Start bounded capability checks without making them part of the invocation's critical path.
309
- * Checks run in parallel and settle to a manifest; failures are represented as diagnostics.
310
- */
311
- function startRuntimePreflight(options) {
312
- const normalized = validateOptions(options);
313
- const signal = options.signal;
314
- const onDiagnostic = options.onDiagnostic;
315
- const controller = new AbortController();
316
- const abort = () => controller.abort(signal?.reason);
317
- if (signal?.aborted) abort();
318
- else signal?.addEventListener("abort", abort, { once: true });
319
- let settled = false;
320
- const startedAt = Date.now();
321
- return {
322
- manifest: Promise.resolve().then(async () => {
323
- const results = await Promise.all(normalized.checks.map(async (check) => {
324
- const bounded = timeoutSignal(controller.signal, normalized.timeoutMs);
325
- let result;
326
- try {
327
- result = await resolveCheck(check, bounded.signal, bounded.deadline, bounded.expire);
328
- if (bounded.signal.aborted && !controller.signal.aborted) result = {
329
- state: "unknown",
330
- reason: "The preflight check timed out."
331
- };
332
- } catch (error) {
333
- result = {
334
- state: "unknown",
335
- reason: normalizeThrownReason(error) || "The preflight check failed."
336
- };
337
- } finally {
338
- bounded.cancel();
339
- }
340
- const diagnostic = diagnosticFor(check, result.state, result.reason);
341
- const issue = diagnostic ? {
342
- check,
343
- state: result.state,
344
- diagnostic
345
- } : void 0;
346
- const summary = {
347
- id: check.id,
348
- kind: check.kind,
349
- required: check.required === true,
350
- state: result.state
351
- };
352
- if (result.details) summary.details = result.details;
353
- if (result.reason) summary.reason = result.reason;
354
- if (diagnostic) summary.diagnostic = diagnostic.toJSON();
355
- return {
356
- issue,
357
- summary
358
- };
359
- }));
360
- const summaries = results.map((result) => result.summary);
361
- const capabilities = Object.fromEntries(summaries.map((summary) => [summary.id, summary.state]));
362
- const manifest = {
363
- version: 1,
364
- checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
365
- durationMs: Math.max(0, Date.now() - startedAt),
366
- checks: summaries,
367
- capabilities,
368
- diagnostics: summaries.flatMap((summary) => summary.diagnostic ? [summary.diagnostic] : [])
369
- };
370
- if (onDiagnostic) {
371
- const issues = results.flatMap(({ issue }) => issue ? [issue] : []);
372
- setTimeout(() => {
373
- for (const issue of issues) Promise.resolve().then(() => onDiagnostic(issue)).catch(() => void 0);
374
- }, 0);
375
- }
376
- return manifest;
377
- }).finally(() => {
378
- settled = true;
379
- signal?.removeEventListener("abort", abort);
380
- }),
381
- cancel() {
382
- if (!settled) controller.abort(/* @__PURE__ */ new Error("Runtime preflight cancelled."));
383
- }
384
- };
385
- }
386
- async function runRuntimePreflight(options) {
387
- return await startRuntimePreflight(options).manifest;
388
- }
389
- //#endregion
390
- //#region src/execution-budget.ts
391
- var ExecutionBudgetExceededError = class extends Error {
392
- counter;
393
- limit;
394
- constructor(counter, limit) {
395
- super(`[vitehub] Execution budget exhausted${counter === "deadline" ? " at the deadline" : ` for ${counter}`}.`);
396
- this.name = "ExecutionBudgetExceededError";
397
- this.counter = counter;
398
- this.limit = limit;
399
- }
400
- };
401
161
  function createBudgetNode(parent) {
402
162
  const node = {
403
163
  cleanups: /* @__PURE__ */ new Set(),
@@ -486,27 +246,27 @@ function createBudget(state, limits, controller, node, externalSignal, deadlineC
486
246
  const stateReason = state.controller.signal.reason;
487
247
  const controllerReason = controller.signal.reason;
488
248
  const sharedReason = state.sharedController.signal.reason;
489
- if (state.controller.signal.aborted && !(stateReason instanceof ExecutionBudgetExceededError)) state.controller.signal.throwIfAborted();
490
- if (controller.signal.aborted && !(controllerReason instanceof ExecutionBudgetExceededError)) controller.signal.throwIfAborted();
491
- if (!node.disposed && externalSignal?.aborted && !(externalSignal.reason instanceof ExecutionBudgetExceededError)) externalSignal.throwIfAborted();
249
+ if (state.controller.signal.aborted && !isExecutionBudgetExceededError(stateReason)) state.controller.signal.throwIfAborted();
250
+ if (controller.signal.aborted && !isExecutionBudgetExceededError(controllerReason)) controller.signal.throwIfAborted();
251
+ if (!node.disposed && externalSignal?.aborted && !isExecutionBudgetExceededError(externalSignal.reason)) externalSignal.throwIfAborted();
492
252
  if (state.sharedController.signal.aborted) {
493
- if (sharedReason instanceof ExecutionBudgetExceededError) throw sharedReason;
253
+ if (isExecutionBudgetExceededError(sharedReason)) throw sharedReason;
494
254
  state.sharedController.signal.throwIfAborted();
495
255
  }
496
256
  if (!node.disposed && limits.deadlineAt !== void 0 && Date.now() >= limits.deadlineAt) {
497
257
  deadlineController.abort(new DOMException("Execution budget timed out: deadline exceeded.", "TimeoutError"));
498
258
  deadlineController.signal.throwIfAborted();
499
259
  }
500
- if (!Number.isFinite(amount) || amount < 0) throw new RangeError(`[vitehub] Execution budget ${counter} amount must be a finite non-negative number.`);
260
+ if (!Number.isFinite(amount) || amount < 0) throw runtimeErrorDiagnostics.RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID({ counter });
501
261
  const next = state.usage[counter] + amount;
502
262
  const limit = limitFor(counter, limits);
503
263
  if (limit !== void 0 && next > limit) {
504
- const error = new ExecutionBudgetExceededError(counter, limit);
264
+ const error = executionBudgetExceededError(counter, limit);
505
265
  state.sharedController.abort(error);
506
266
  throw error;
507
267
  }
508
- if (stateReason instanceof ExecutionBudgetExceededError) throw stateReason;
509
- if (controllerReason instanceof ExecutionBudgetExceededError) throw controllerReason;
268
+ if (isExecutionBudgetExceededError(stateReason)) throw stateReason;
269
+ if (isExecutionBudgetExceededError(controllerReason)) throw controllerReason;
510
270
  }
511
271
  function consume(counter, amount = 1) {
512
272
  assertAvailable(counter, amount);
@@ -600,7 +360,7 @@ function minDefined(left, right) {
600
360
  function normalizeLimits(options) {
601
361
  const normalize = (value) => {
602
362
  if (value === void 0) return void 0;
603
- if (!Number.isFinite(value) || value < 0) throw new RangeError("[vitehub] Execution budget limits must be finite non-negative numbers.");
363
+ if (!Number.isFinite(value) || value < 0) throw runtimeErrorDiagnostics.RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID();
604
364
  return Math.floor(value);
605
365
  };
606
366
  return {
@@ -612,77 +372,16 @@ function normalizeLimits(options) {
612
372
  };
613
373
  }
614
374
  //#endregion
615
- //#region src/route-segment.ts
616
- const plainSegment = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
617
- function encodeRouteSegment(value) {
618
- if (plainSegment.test(value)) return value;
619
- let encoded = "~";
620
- for (let index = 0; index < value.length; index++) encoded += value.charCodeAt(index).toString(16).padStart(4, "0");
621
- return encoded;
622
- }
623
- function decodeRouteSegment(segment) {
624
- if (plainSegment.test(segment)) return segment;
625
- if (!/^~(?:[0-9a-f]{4})+$/.test(segment)) return;
626
- let value = "";
627
- for (let index = 1; index < segment.length; index += 4) value += String.fromCharCode(Number.parseInt(segment.slice(index, index + 4), 16));
628
- return encodeRouteSegment(value) === segment ? value : void 0;
629
- }
630
- //#endregion
631
- //#region src/public-url.ts
632
- const publicUrlAgentNames = /* @__PURE__ */ new Map();
633
- /** Replace aliases when a generated Agent registry is installed. */
634
- function resetPublicUrlAgentNames() {
635
- publicUrlAgentNames.clear();
636
- }
637
- /** Associate an evaluated Agent name with the identity used by build-time URL configuration. */
638
- function registerPublicUrlAgentName(name, discoveredName) {
639
- const previous = publicUrlAgentNames.get(name);
640
- publicUrlAgentNames.set(name, previous === void 0 || previous === discoveredName ? discoveredName : null);
641
- }
642
- function publicUrlConfig() {
643
- return typeof __VITEHUB_PUBLIC_URL__ === "undefined" ? {} : __VITEHUB_PUBLIC_URL__;
644
- }
645
- function applicationBasePath() {
646
- const segments = (typeof __VITEHUB_APP_BASE_URL__ === "undefined" ? "/" : __VITEHUB_APP_BASE_URL__).split("/").filter(Boolean);
647
- return segments.length ? `/${segments.join("/")}` : "";
648
- }
649
- function configuredAgentUrl(config, name) {
650
- return config.agents && Object.hasOwn(config.agents, name) ? config.agents[name] : void 0;
651
- }
652
- function isInternalRequestHost(hostname) {
653
- const host = hostname.toLowerCase();
654
- if (host === "internal") return true;
655
- if (host.endsWith(".internal") || host.endsWith(".svc")) return true;
656
- const octets = host.split(".").map(Number);
657
- if (octets.length !== 4 || octets.some((octet) => !Number.isInteger(octet) || octet < 0 || octet > 255)) return false;
658
- return octets[0] === 10 || octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31 || octets[0] === 192 && octets[1] === 168;
659
- }
660
- function resolvePublicUrl(options = {}) {
661
- const config = publicUrlConfig();
662
- const discoveredName = options.agentName ? publicUrlAgentNames.get(options.agentName) : void 0;
663
- const agentUrl = options.agentName ? configuredAgentUrl(config, options.agentName) ?? (discoveredName ? configuredAgentUrl(config, discoveredName) : void 0) : void 0;
664
- if (config.url) return config.url;
665
- if (!options.request) return agentUrl;
666
- const request = new URL(options.request.url);
667
- const configuredAgents = Object.values(config.agents ?? {});
668
- const requestHostUrl = configuredAgents.find((url) => new URL(url).host === request.host);
669
- if (requestHostUrl) return requestHostUrl;
670
- if (isInternalRequestHost(request.hostname)) return agentUrl ?? (configuredAgents.length === 1 ? configuredAgents[0] : request.origin);
671
- return request.origin;
672
- }
673
- /** Build the Console URL of one Agent invocation. `origin` must not include the application base path. */
674
- function consoleInvocationUrl(origin, agentName, invocationId) {
675
- const path = `${applicationBasePath()}/_vitehub/agents/${encodeRouteSegment(agentName)}/invocations/${encodeURIComponent(invocationId)}`;
676
- return new URL(path, origin).href;
677
- }
678
- //#endregion
679
375
  //#region src/diagnostics.ts
680
- /** Recognizes a live Nostics error across bundled copies. This does not make its fields safe for public responses. */
376
+ /**
377
+ * Recognizes a live Nostics error across bundled copies. This does not make its fields safe for public responses.
378
+ * nostics' own check matches only its own copy (https://github.com/vercel-labs/nostics/pull/40).
379
+ */
681
380
  function isRuntimeDiagnostic(error) {
682
381
  if (!isRuntimeObject(error)) return false;
683
382
  try {
684
383
  const nativeIsError = Reflect.get(Error, "isError");
685
- if (!(hasRuntimeType(nativeIsError, "function") ? nativeIsError(error) === true : error instanceof Error || !(Symbol.toStringTag in error) && Object.prototype.toString.call(error) === "[object Error]")) return false;
384
+ if (!(typeof nativeIsError === "function" ? nativeIsError(error) === true : error instanceof Error || !(Symbol.toStringTag in error) && Object.prototype.toString.call(error) === "[object Error]")) return false;
686
385
  const message = Reflect.get(error, "message");
687
386
  const code = Reflect.get(error, "code");
688
387
  const name = Reflect.get(error, "name");
@@ -690,13 +389,13 @@ function isRuntimeDiagnostic(error) {
690
389
  const fix = Reflect.get(error, "fix");
691
390
  const docs = Reflect.get(error, "docs");
692
391
  const sources = Reflect.get(error, "sources");
693
- return hasRuntimeType(code, "string") && code.length > 0 && hasRuntimeType(name, "string") && hasRuntimeType(message, "string") && why === message && (fix === void 0 || hasRuntimeType(fix, "string")) && (docs === void 0 || hasRuntimeType(docs, "string")) && (sources === void 0 || Array.isArray(sources) && sources.every((source) => hasRuntimeType(source, "string"))) && hasRuntimeType(Reflect.get(error, "toJSON"), "function");
392
+ return typeof code === "string" && code.length > 0 && typeof name === "string" && typeof message === "string" && why === message && (fix === void 0 || typeof fix === "string") && (docs === void 0 || typeof docs === "string") && (sources === void 0 || Array.isArray(sources) && sources.every((source) => typeof source === "string")) && typeof Reflect.get(error, "toJSON") === "function";
694
393
  } catch {
695
394
  return false;
696
395
  }
697
396
  }
698
397
  function boundedString(value, state) {
699
- if (!hasRuntimeType(value, "string")) return;
398
+ if (typeof value !== "string") return;
700
399
  const maximum = Math.min(state.maxStringLength, state.remainingStringLength);
701
400
  if (maximum <= 0) return;
702
401
  if (value.length <= maximum) {
@@ -725,8 +424,8 @@ function readProperty(value, key) {
725
424
  }
726
425
  function scalarProperty(value, key, state) {
727
426
  const property = readProperty(value, key);
728
- if (hasRuntimeType(property, "string")) return boundedString(property, state);
729
- return hasRuntimeType(property, "number") && Number.isFinite(property) ? property : void 0;
427
+ if (typeof property === "string") return boundedString(property, state);
428
+ return typeof property === "number" && Number.isFinite(property) ? property : void 0;
730
429
  }
731
430
  function errorChildren(value, maximum) {
732
431
  try {
@@ -740,9 +439,9 @@ function errorChildren(value, maximum) {
740
439
  function normalizeDetailValue(value, state, depth) {
741
440
  if (state.remainingNodes <= 0) return;
742
441
  state.remainingNodes -= 1;
743
- if (value === null || hasRuntimeType(value, "boolean")) return value;
744
- if (hasRuntimeType(value, "number")) return Number.isFinite(value) ? value : void 0;
745
- if (hasRuntimeType(value, "string")) return boundedString(value, state);
442
+ if (value === null || typeof value === "boolean") return value;
443
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
444
+ if (typeof value === "string") return boundedString(value, state);
746
445
  if (depth > state.maxDepth) return boundedString("[Detail depth exceeded]", state);
747
446
  if (Array.isArray(value)) return value.flatMap((item) => {
748
447
  const normalized = normalizeDetailValue(item, state, depth + 1);
@@ -772,8 +471,8 @@ function normalizeDetails(details, state, depth) {
772
471
  function normalizeError(value, state, depth) {
773
472
  if (state.remainingNodes <= 0) return;
774
473
  state.remainingNodes -= 1;
775
- if (hasRuntimeType(value, "string")) return { message: boundedString(value, state) || "Error" };
776
- if (!value || !hasRuntimeType(value, "object")) return { message: boundedString(safeString(value), state) || "Error" };
474
+ if (typeof value === "string") return { message: boundedString(value, state) || "Error" };
475
+ if (!value || typeof value !== "object") return { message: boundedString(safeString(value), state) || "Error" };
777
476
  if (state.ancestors.has(value)) return { message: boundedString("[Circular error cause]", state) || "Error" };
778
477
  if (depth > state.maxDepth) return { message: boundedString("[Error cause depth exceeded]", state) || "Error" };
779
478
  state.ancestors.add(value);
@@ -786,7 +485,7 @@ function normalizeError(value, state, depth) {
786
485
  message,
787
486
  ...name ? { name } : {}
788
487
  };
789
- const code = publicError?.code ? boundedString(publicError.code, state) : scalarProperty(value, "code", state) ?? (hasRuntimeType(why, "string") ? boundedString(name, state) : void 0);
488
+ const code = publicError?.code ? boundedString(publicError.code, state) : scalarProperty(value, "code", state) ?? (typeof why === "string" ? boundedString(name, state) : void 0);
790
489
  const fix = boundedString(readProperty(value, "fix"), state);
791
490
  const docs = boundedString(readProperty(value, "docs"), state);
792
491
  const requestId = publicError?.requestId ? boundedString(publicError.requestId, state) : boundedString(readProperty(value, "requestId"), state);
@@ -889,130 +588,272 @@ function toResultError(error) {
889
588
  });
890
589
  return result;
891
590
  }
892
- /**
893
- * Defines the error catalog of a package with Nostics.
894
- * Return runtime errors as `[error, undefined]`. Throw definition and config errors.
895
- */
896
591
  function defineErrors(options) {
897
592
  const diagnostics = defineDiagnostics({
898
593
  codes: options.codes,
899
- docsBase: (code) => `${options.docs}#${String(code).toLowerCase()}`
594
+ docsBase: options.docs
900
595
  });
901
- const catalog = {};
902
- for (const [code, create] of Object.entries(diagnostics)) catalog[code] = (params) => toResultError(create(params));
596
+ const codes = new Set(Object.keys(options.codes));
597
+ const catalog = Object.defineProperty({}, "is", { value: (error) => isRuntimeDiagnostic(error) && codes.has(error.code) });
598
+ for (const code of codes) {
599
+ const create = diagnostics[code];
600
+ catalog[code] = Object.assign((params) => toResultError(create(params)), { is: (error) => isRuntimeDiagnostic(error) && error.code === code });
601
+ }
903
602
  return catalog;
904
603
  }
905
604
  //#endregion
906
- //#region src/work.ts
907
- function createWorkTracker(options) {
908
- const retryMs = options.retryMs ?? 9e5;
909
- const maxRetryMs = options.maxRetryMs ?? 216e5;
910
- if (!Number.isFinite(retryMs) || retryMs <= 0 || !Number.isFinite(maxRetryMs) || maxRetryMs < retryMs) throw new TypeError("Work retry intervals must be positive and maxRetryMs must be at least retryMs.");
911
- const now = options.now ?? Date.now;
912
- const active = /* @__PURE__ */ new Set();
913
- const fallback = /* @__PURE__ */ new Map();
914
- function checkpoint(value) {
915
- if (!isRuntimeObject(value)) return;
916
- try {
917
- for (const key of Reflect.ownKeys(value)) {
918
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
919
- if (!descriptor || !Object.prototype.hasOwnProperty.call(descriptor, "value") || isRuntimeObject(descriptor.value)) return;
920
- }
921
- structuredClone(value);
922
- const read = (key) => {
923
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
924
- return descriptor && Object.prototype.hasOwnProperty.call(descriptor, "value") ? descriptor.value : void 0;
925
- };
926
- const version = read("version");
927
- const fingerprint = read("fingerprint");
928
- const disposition = read("disposition");
929
- const attempt = read("attempt");
930
- const retryAt = read("retryAt");
931
- if (version !== 1 || !hasRuntimeType(fingerprint, "string") || !hasRuntimeType(attempt, "number") || !Number.isSafeInteger(attempt) || attempt < 0) return;
932
- if (disposition === "park") return {
933
- version,
934
- fingerprint,
935
- disposition,
936
- attempt
937
- };
938
- if (disposition === "retry" && hasRuntimeType(retryAt, "number") && Number.isFinite(retryAt)) return {
939
- version,
940
- fingerprint,
941
- disposition,
942
- attempt,
943
- retryAt
944
- };
945
- } catch {
946
- return;
605
+ //#region src/lease.ts
606
+ const leaseErrorDiagnostics = /*#__PURE__*/ defineErrors({
607
+ docs: "https://vitehub.dev/docs/development/diagnostics",
608
+ codes: {
609
+ RUNTIME_LEASE_INVALID_TTL: {
610
+ why: "`ttl` must be a positive number of seconds.",
611
+ fix: "Pass the TTL in seconds, for example `leases.acquire('report:daily', { ttl: 30 })`."
612
+ },
613
+ RUNTIME_LEASE_FAILED: {
614
+ why: ({ key, operation }) => `The lease store could not ${operation} the lease ${JSON.stringify(key)}.`,
615
+ fix: "Read `error.cause` for the store error. Retry when the store is available again."
947
616
  }
948
617
  }
949
- async function read(key) {
950
- return fallback.get(key) ?? checkpoint(await options.store.get(key));
951
- }
952
- function eligible(state, fingerprint) {
953
- return !state || state.fingerprint !== fingerprint || state.disposition === "retry" && state.retryAt <= now();
954
- }
955
- async function write(key, state) {
956
- fallback.set(key, state);
957
- await options.store.set(key, state);
958
- fallback.delete(key);
959
- }
960
- function retry(fingerprint, previous) {
961
- const attempt = previous?.fingerprint === fingerprint ? previous.attempt + 1 : 1;
962
- return {
963
- version: 1,
964
- fingerprint,
965
- disposition: "retry",
966
- attempt,
967
- retryAt: now() + Math.min(retryMs * 2 ** Math.min(attempt - 1, 30), maxRetryMs)
618
+ });
619
+ /** Expired leases mean nothing, so stores delete them at most once per this interval. */
620
+ const sweepIntervalMs = 6e4;
621
+ function toTtlMs(ttl) {
622
+ if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0) return void 0;
623
+ const ms = Math.ceil(ttl * 1e3);
624
+ return Number.isSafeInteger(ms) ? ms : void 0;
625
+ }
626
+ async function attempt(operation, key, run) {
627
+ try {
628
+ return [void 0, await run()];
629
+ } catch (cause) {
630
+ return [leaseErrorDiagnostics.RUNTIME_LEASE_FAILED({
631
+ cause,
632
+ key,
633
+ operation
634
+ }), void 0];
635
+ }
636
+ }
637
+ function createLeaseStore(backend) {
638
+ function lease(record, defaultTtlMs) {
639
+ const held = {
640
+ ...record,
641
+ async renew(options) {
642
+ const ttlMs = options?.ttl === void 0 ? defaultTtlMs : toTtlMs(options.ttl);
643
+ if (ttlMs === void 0) return [leaseErrorDiagnostics.RUNTIME_LEASE_INVALID_TTL(), void 0];
644
+ return attempt("renew", held.key, async () => {
645
+ const expiresAt = await backend.renew(held.key, held.id, ttlMs);
646
+ if (expiresAt === void 0) return false;
647
+ held.expiresAt = new Date(expiresAt);
648
+ return true;
649
+ });
650
+ },
651
+ release: () => attempt("release", held.key, () => backend.release(held.key, held.id))
968
652
  };
653
+ return held;
969
654
  }
970
655
  return {
971
- get active() {
972
- return active.size;
656
+ async acquire(key, options) {
657
+ const ttlMs = toTtlMs(options?.ttl);
658
+ if (ttlMs === void 0) return [leaseErrorDiagnostics.RUNTIME_LEASE_INVALID_TTL(), void 0];
659
+ const id = crypto.randomUUID();
660
+ const owner = options.owner;
661
+ return attempt("acquire", key, async () => {
662
+ const expiresAt = await backend.acquire(key, id, owner, ttlMs);
663
+ if (expiresAt === void 0) return null;
664
+ return lease({
665
+ key,
666
+ id,
667
+ ...owner === void 0 ? {} : { owner },
668
+ expiresAt: new Date(expiresAt)
669
+ }, ttlMs);
670
+ });
973
671
  },
974
- has(key) {
975
- return active.has(key);
672
+ get: (key) => attempt("get", key, async () => {
673
+ const record = await backend.get(key);
674
+ return record ? {
675
+ key,
676
+ id: record.id,
677
+ ...record.owner === void 0 ? {} : { owner: record.owner },
678
+ expiresAt: new Date(record.expiresAt)
679
+ } : null;
680
+ })
681
+ };
682
+ }
683
+ /**
684
+ * Leases in the memory of this process. Use it for one instance and for tests. Several instances need a shared store,
685
+ * such as `createSqlLeaseStore()`.
686
+ */
687
+ function createMemoryLeaseStore() {
688
+ const leases = /* @__PURE__ */ new Map();
689
+ let sweptAt = 0;
690
+ const live = (key, now) => {
691
+ const entry = leases.get(key);
692
+ return entry && entry.expiresAt > now ? entry : void 0;
693
+ };
694
+ return createLeaseStore({
695
+ async acquire(key, id, owner, ttlMs) {
696
+ const now = Date.now();
697
+ if (now - sweptAt >= sweepIntervalMs) {
698
+ sweptAt = now;
699
+ for (const [held, entry] of leases) if (entry.expiresAt <= now) leases.delete(held);
700
+ }
701
+ if (live(key, now)) return void 0;
702
+ const expiresAt = now + ttlMs;
703
+ leases.set(key, {
704
+ id,
705
+ ...owner === void 0 ? {} : { owner },
706
+ expiresAt
707
+ });
708
+ return expiresAt;
976
709
  },
977
- async eligible(key, fingerprint) {
978
- return !active.has(key) && eligible(await read(key), fingerprint);
710
+ async renew(key, id, ttlMs) {
711
+ const entry = leases.get(key);
712
+ if (entry?.id !== id) return void 0;
713
+ entry.expiresAt = Date.now() + ttlMs;
714
+ return entry.expiresAt;
979
715
  },
980
- async run(key, fingerprint, run) {
981
- if (active.has(key)) return false;
982
- active.add(key);
983
- try {
984
- const previous = await read(key);
985
- if (!eligible(previous, fingerprint)) return false;
986
- let current = fingerprint;
987
- try {
988
- const result = await run();
989
- if (result.disposition !== "park" && result.disposition !== "retry") throw new TypeError("Work must return a park or retry disposition.");
990
- current = result.fingerprint ?? fingerprint;
991
- await write(key, result.disposition === "retry" ? retry(current, previous) : {
992
- version: 1,
993
- fingerprint: current,
994
- disposition: "park",
995
- attempt: 0
996
- });
997
- return true;
998
- } catch (error) {
999
- try {
1000
- await write(key, retry(current, previous));
1001
- } catch (checkpointError) {
1002
- throw new AggregateError([error, checkpointError], "Work failed and its retry checkpoint could not be persisted.");
1003
- }
1004
- throw error;
1005
- }
1006
- } finally {
1007
- active.delete(key);
1008
- }
716
+ async release(key, id) {
717
+ if (leases.get(key)?.id !== id) return false;
718
+ return leases.delete(key);
719
+ },
720
+ async get(key) {
721
+ const entry = live(key, Date.now());
722
+ return entry && { ...entry };
1009
723
  }
724
+ });
725
+ }
726
+ /** How long a SQLite statement retries while another connection holds the write lock. */
727
+ const busyRetryMs = 5e3;
728
+ /**
729
+ * Runs a SQLite statement again while it fails with `SQLITE_BUSY`, which SQLite allows for a statement outside a
730
+ * transaction. It waits without blocking the event loop, unlike `PRAGMA busy_timeout` on a synchronous client.
731
+ */
732
+ async function retryBusy(run) {
733
+ const deadline = Date.now() + busyRetryMs;
734
+ for (let delay = 2;; delay = Math.min(delay * 2, 50)) try {
735
+ return await run();
736
+ } catch (error) {
737
+ if (!isBusy(error) || Date.now() + delay > deadline) throw error;
738
+ await new Promise((resolve) => setTimeout(resolve, delay * (.5 + Math.random())));
739
+ }
740
+ }
741
+ /**
742
+ * libSQL and better-sqlite3 set `code` to `SQLITE_BUSY`. Other drivers only say so in the message. Drizzle puts the
743
+ * driver error in `cause`.
744
+ */
745
+ function isBusy(error) {
746
+ if (!(error instanceof Error)) return false;
747
+ const code = Reflect.get(error, "code");
748
+ return typeof code === "string" && code.startsWith("SQLITE_BUSY") || /SQLITE_BUSY|database is locked/i.test(error.message) || isBusy(error.cause);
749
+ }
750
+ /** The table of `createSqlLeaseStore()`. The store creates it when it is missing. */
751
+ const leaseTable = "vitehub_leases";
752
+ /**
753
+ * Leases in a SQL table, shared by every process that uses the same Database. Each operation is one statement, so
754
+ * two processes that acquire a key at the same time get one winner. Expiry uses the clock of the Database, not the
755
+ * clocks of the hosts. Works on Postgres and on SQLite 3.35 or later, such as libSQL.
756
+ */
757
+ function createSqlLeaseStore(client) {
758
+ const now = client.dialect === "postgresql" ? "(extract(epoch from clock_timestamp()) * 1000)::bigint" : "cast((julianday('now') - 2440587.5) * 86400000 as integer)";
759
+ /** Runs SQL written with `?` placeholders, which become `$1`, `$2`, ... on Postgres. */
760
+ const query = (sql, params) => {
761
+ if (client.dialect === "sqlite") return retryBusy(() => client.query(sql, params));
762
+ let index = 0;
763
+ return client.query(sql.replace(/\?/g, () => `$${++index}`), params);
1010
764
  };
765
+ const table = leaseTable;
766
+ const columns = `("key" text primary key, id text not null, owner text, expires_at bigint not null)`;
767
+ const index = `create index if not exists ${table}_expires_at on ${table} (expires_at)`;
768
+ const create = client.dialect === "postgresql" ? [`do $$ begin perform pg_advisory_xact_lock(hashtext('${table}')); create table if not exists ${table} ${columns}; ${index}; end $$`] : [`create table if not exists ${table} ${columns}`, index];
769
+ let ready;
770
+ let sweptAt = 0;
771
+ const tableExists = () => query(`select 1 from ${table} limit 0`, []).then(() => true, () => false);
772
+ function ensureTable() {
773
+ ready ??= (async () => {
774
+ if (await tableExists()) return;
775
+ for (const statement of create) await query(statement, []);
776
+ })();
777
+ ready.catch(() => {
778
+ ready = void 0;
779
+ });
780
+ return ready;
781
+ }
782
+ /**
783
+ * Runs one lease statement. A test reset can give the same client an empty database, so a statement that fails
784
+ * because the table is gone creates it again and runs once more. Every other failure throws.
785
+ */
786
+ async function run(statement) {
787
+ await ensureTable();
788
+ try {
789
+ return await statement();
790
+ } catch (error) {
791
+ if (await tableExists()) throw error;
792
+ ready = void 0;
793
+ await ensureTable().catch(() => {
794
+ throw error;
795
+ });
796
+ return await statement();
797
+ }
798
+ }
799
+ const end = (value) => Number(value);
800
+ return createLeaseStore({
801
+ async acquire(key, id, owner, ttlMs) {
802
+ if (Date.now() - sweptAt >= sweepIntervalMs) {
803
+ sweptAt = Date.now();
804
+ await run(() => query(`delete from ${table} where expires_at <= ${now}`, []));
805
+ }
806
+ const [row] = await run(() => query(`insert into ${table} ("key", id, owner, expires_at) values (?, ?, ?, ${now} + cast(? as bigint))
807
+ on conflict ("key") do update set id = excluded.id, owner = excluded.owner, expires_at = ${now} + cast(? as bigint)
808
+ where ${table}.expires_at <= ${now} or ${table}.id = excluded.id
809
+ returning id, expires_at`, [
810
+ key,
811
+ id,
812
+ owner ?? null,
813
+ ttlMs,
814
+ ttlMs
815
+ ]));
816
+ return row?.id === id ? end(row.expires_at) : void 0;
817
+ },
818
+ async renew(key, id, ttlMs) {
819
+ const [row] = await run(() => client.dialect === "postgresql" ? query(`with held as (select "key", id from ${table} where "key" = ? and id = ? for update)
820
+ update ${table} set expires_at = ${now} + cast(? as bigint) from held
821
+ where ${table}."key" = held."key" and ${table}.id = held.id returning ${table}.expires_at`, [
822
+ key,
823
+ id,
824
+ ttlMs
825
+ ]) : query(`update ${table} set expires_at = ${now} + cast(? as bigint) where "key" = ? and id = ? returning expires_at`, [
826
+ ttlMs,
827
+ key,
828
+ id
829
+ ]));
830
+ return row ? end(row.expires_at) : void 0;
831
+ },
832
+ async release(key, id) {
833
+ return (await run(() => query(`delete from ${table} where "key" = ? and id = ? returning id`, [key, id]))).length > 0;
834
+ },
835
+ async get(key) {
836
+ const [row] = await run(() => query(`select id, owner, expires_at from ${table} where "key" = ? and expires_at > ${now}`, [key]));
837
+ if (!row) return void 0;
838
+ return {
839
+ id: String(row.id),
840
+ ...typeof row.owner === "string" ? { owner: row.owner } : {},
841
+ expiresAt: end(row.expires_at)
842
+ };
843
+ }
844
+ });
1011
845
  }
1012
846
  //#endregion
1013
847
  //#region src/response.ts
1014
- const blobTypeGetter = Object.getOwnPropertyDescriptor(Blob.prototype, "type")?.get;
1015
- const blobStreamMethod = Object.getOwnPropertyDescriptor(Blob.prototype, "stream")?.value;
848
+ function prototypeGetter(constructor, key) {
849
+ return Object.getOwnPropertyDescriptor(constructor.prototype, key)?.get;
850
+ }
851
+ function prototypeMethod(constructor, key) {
852
+ const value = Object.getOwnPropertyDescriptor(constructor.prototype, key)?.value;
853
+ return typeof value === "function" ? value : void 0;
854
+ }
855
+ const blobTypeGetter = /* @__PURE__ */ prototypeGetter(Blob, "type");
856
+ const blobStreamMethod = /* @__PURE__ */ prototypeMethod(Blob, "stream");
1016
857
  function streamBody(read) {
1017
858
  let reader;
1018
859
  const cleanup = async (reason, cancel = false) => {
@@ -1058,7 +899,7 @@ function getBlobMethods(value) {
1058
899
  return;
1059
900
  }
1060
901
  }
1061
- const arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength")?.get;
902
+ const arrayBufferByteLengthGetter = /* @__PURE__ */ prototypeGetter(ArrayBuffer, "byteLength");
1062
903
  function isArrayBufferValue(value) {
1063
904
  if (!isRuntimeObject(value)) return false;
1064
905
  try {
@@ -1073,7 +914,7 @@ function isArrayBufferValue(value) {
1073
914
  function toResponse(value) {
1074
915
  if (isResponse(value)) return value;
1075
916
  if (value === void 0) return new Response(null, { status: 204 });
1076
- if (hasRuntimeType(value, "string") || value instanceof Blob || isArrayBufferValue(value) || ArrayBuffer.isView(value)) return new Response(value);
917
+ if (typeof value === "string" || value instanceof Blob || isArrayBufferValue(value) || ArrayBuffer.isView(value)) return new Response(value);
1077
918
  const blobMethods = getBlobMethods(value);
1078
919
  if (blobMethods) return new Response(blobMethods.body(), blobMethods.type ? { headers: { "content-type": blobMethods.type } } : void 0);
1079
920
  return new Response(JSON.stringify(value), { headers: { "content-type": "application/json; charset=utf-8" } });
@@ -1111,7 +952,7 @@ async function serializeResponse(response) {
1111
952
  }
1112
953
  /** Reconstruct a native Response from a durable response record. */
1113
954
  function deserializeResponse(value) {
1114
- if (!isSerializedResponse(value)) throw new TypeError("Invalid serialized Response");
955
+ if (!isSerializedResponse(value)) throw runtimeErrorDiagnostics.RUNTIME_SERIALIZED_RESPONSE_INVALID();
1115
956
  if (value.type !== void 0) return createStatusZeroResponse(value.type, value.url);
1116
957
  const bytes = base64ToBytes(value.body.data);
1117
958
  const body = value.body.isNull === true || [
@@ -1130,18 +971,18 @@ function isSerializedResponse(value) {
1130
971
  const record = value;
1131
972
  if (!isRuntimeObject(record.body)) return false;
1132
973
  const body = record.body;
1133
- if (!hasRuntimeType(body.data, "string") || body.encoding !== "base64" || !hasRuntimeType(body.mediaType, "string")) return false;
1134
- if (body.isNull !== void 0 && !hasRuntimeType(body.isNull, "boolean")) return false;
974
+ if (typeof body.data !== "string" || body.encoding !== "base64" || typeof body.mediaType !== "string") return false;
975
+ if (body.isNull !== void 0 && typeof body.isNull !== "boolean") return false;
1135
976
  if (body.isNull === true && body.data !== "") return false;
1136
- if (record.url !== void 0 && !hasRuntimeType(record.url, "string")) return false;
977
+ if (record.url !== void 0 && typeof record.url !== "string") return false;
1137
978
  if (record.type !== void 0 && record.type !== "error" && record.type !== "opaque" && record.type !== "opaqueredirect") return false;
1138
979
  if (record.type !== void 0) {
1139
980
  if (record.type !== "opaqueredirect" && record.url !== void 0) return false;
1140
981
  return record.status === 0 && record.statusText === "" && Array.isArray(record.headers) && record.headers.length === 0 && body.isNull === true && body.data === "";
1141
982
  }
1142
983
  if (record.url !== void 0) return false;
1143
- if (!hasRuntimeType(record.status, "number") || !Number.isInteger(record.status) || record.status < 200 || record.status > 599) return false;
1144
- if (!hasRuntimeType(record.statusText, "string") || !isSerializedHeaderEntries(record.headers)) return false;
984
+ if (typeof record.status !== "number" || !Number.isInteger(record.status) || record.status < 200 || record.status > 599) return false;
985
+ if (typeof record.statusText !== "string" || !isSerializedHeaderEntries(record.headers)) return false;
1145
986
  if ([
1146
987
  204,
1147
988
  205,
@@ -1161,7 +1002,7 @@ function isSerializedResponse(value) {
1161
1002
  return true;
1162
1003
  }
1163
1004
  function isSerializedHeaderEntry(value) {
1164
- return Array.isArray(value) && value.length === 2 && hasRuntimeType(value[0], "string") && hasRuntimeType(value[1], "string");
1005
+ return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "string";
1165
1006
  }
1166
1007
  function isSerializedHeaderEntries(value) {
1167
1008
  if (!Array.isArray(value)) return false;
@@ -1201,13 +1042,97 @@ function createStatusZeroResponse(type, url = "") {
1201
1042
  });
1202
1043
  return response;
1203
1044
  }
1045
+ /** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
1046
+ function hostFromNitroPreset(value) {
1047
+ const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
1048
+ if (!normalized) return;
1049
+ if (normalized.startsWith("cloudflare")) return "cloudflare";
1050
+ if (normalized.startsWith("deno")) return "deno";
1051
+ if (normalized.startsWith("netlify")) return "netlify";
1052
+ if (normalized === "node" || normalized.startsWith("node-")) return "node";
1053
+ if (normalized.startsWith("vercel")) return "vercel";
1054
+ }
1055
+ const providerHosts = [
1056
+ ["WORKERS_CI", "cloudflare"],
1057
+ ["NETLIFY", "netlify"],
1058
+ ["NOW_BUILDER", "vercel"],
1059
+ ["VERCEL", "vercel"],
1060
+ ["VERCEL_ENV", "vercel"],
1061
+ ["DENO_DEPLOY", "deno"],
1062
+ ["DENO_DEPLOYMENT_ID", "deno"]
1063
+ ];
1064
+ /**
1065
+ * Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
1066
+ * The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
1067
+ * `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
1068
+ * `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
1069
+ */
1070
+ function detectHost$1(env = process.env) {
1071
+ for (const name of [
1072
+ "VITEHUB_HOST",
1073
+ "NITRO_PRESET",
1074
+ "SERVER_PRESET"
1075
+ ]) {
1076
+ const host = hostFromNitroPreset(env[name]);
1077
+ if (host) return host;
1078
+ }
1079
+ return providerHosts.find(([name]) => env[name]?.trim())?.[1];
1080
+ }
1081
+ //#endregion
1082
+ //#region src/host.ts
1083
+ const hostBindingErrors = /*#__PURE__*/ defineErrors({
1084
+ docs: "https://vitehub.dev/docs/development/diagnostics",
1085
+ codes: {
1086
+ RUNTIME_HOST_BINDINGS_UNAVAILABLE: {
1087
+ why: ({ name }) => `This code runs without host bindings, so the binding "${name}" is not available. Only Cloudflare Workers give bindings.`,
1088
+ fix: "Build with `host: \"cloudflare\"`, or handle the error to use another source in this runtime, for example in `vite dev` on Node."
1089
+ },
1090
+ RUNTIME_HOST_BINDING_NOT_FOUND: {
1091
+ why: ({ name }) => `The Worker has no binding named "${name}".`,
1092
+ fix: "Declare the binding in the Wrangler config of the app, then run `wrangler types` to update `Cloudflare.Env`."
1093
+ }
1094
+ }
1095
+ });
1096
+ /**
1097
+ * Returns the host that this code builds or runs on, or `undefined` when nothing names one.
1098
+ * It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
1099
+ * (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
1100
+ * `vitehub()` uses the same detection when `host` is omitted.
1101
+ *
1102
+ * @example
1103
+ * ```ts
1104
+ * import { detectHost } from "vite-hub/runtime"
1105
+ *
1106
+ * const host = detectHost() ?? "node"
1107
+ * ```
1108
+ */
1109
+ function detectHost(env = processEnv()) {
1110
+ return detectHost$1(env) ?? (globalThis.navigator?.userAgent === "Cloudflare-Workers" ? "cloudflare" : void 0);
1111
+ }
1112
+ function processEnv() {
1113
+ return globalThis.process?.env ?? {};
1114
+ }
1115
+ function getHostBinding(name, event) {
1116
+ const env = (event && hostBindingsOf(event)) ?? getActiveCloudflareEnv();
1117
+ if (!env) return [hostBindingErrors.RUNTIME_HOST_BINDINGS_UNAVAILABLE({ name }), void 0];
1118
+ const binding = Object.hasOwn(env, name) ? env[name] : void 0;
1119
+ if (binding === void 0) return [hostBindingErrors.RUNTIME_HOST_BINDING_NOT_FOUND({ name }), void 0];
1120
+ return [void 0, binding];
1121
+ }
1122
+ function hostBindingsOf(event) {
1123
+ return event["~standard"]?.runtime?.cloudflare?.env ?? getCloudflareEnv(event, { fallback: false });
1124
+ }
1204
1125
  //#endregion
1205
1126
  //#region src/index.ts
1206
- const webAssemblyModuleConstructor = (() => {
1127
+ function captureWebAssemblyModule() {
1207
1128
  const namespace = Object.getOwnPropertyDescriptor(globalThis, "WebAssembly")?.value;
1208
- return hasRuntimeType(namespace, "object") ? Object.getOwnPropertyDescriptor(namespace, "Module")?.value : void 0;
1209
- })();
1210
- const webAssemblyModuleExports = hasRuntimeType(webAssemblyModuleConstructor, "function") ? Object.getOwnPropertyDescriptor(webAssemblyModuleConstructor, "exports")?.value : void 0;
1129
+ const constructor = typeof namespace === "object" ? Object.getOwnPropertyDescriptor(namespace, "Module")?.value : void 0;
1130
+ return {
1131
+ constructor,
1132
+ exports: typeof constructor === "function" ? Object.getOwnPropertyDescriptor(constructor, "exports")?.value : void 0
1133
+ };
1134
+ }
1135
+ const webAssemblyModule = /* @__PURE__ */ captureWebAssemblyModule();
1211
1136
  const noExecutionAuthority = /* @__PURE__ */ Object.freeze({
1212
1137
  credentials: "none",
1213
1138
  environment: "none",
@@ -1235,10 +1160,10 @@ function isExecutionAuthority(value) {
1235
1160
  }
1236
1161
  function inspectExecutionAuthority(value) {
1237
1162
  try {
1238
- if (!value || !hasRuntimeType(value, "object") || Array.isArray(value)) return void 0;
1163
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1239
1164
  const authority = value;
1240
1165
  const filesystem = authority.filesystem;
1241
- if (!filesystem || !hasRuntimeType(filesystem, "object") || Array.isArray(filesystem)) return void 0;
1166
+ if (!filesystem || typeof filesystem !== "object" || Array.isArray(filesystem)) return void 0;
1242
1167
  const files = filesystem;
1243
1168
  const credentials = authority.credentials;
1244
1169
  const environment = authority.environment;
@@ -1247,39 +1172,39 @@ function inspectExecutionAuthority(value) {
1247
1172
  const isolation = authority.isolation;
1248
1173
  const network = authority.network;
1249
1174
  const processes = authority.processes;
1250
- if (!(hasRuntimeType(credentials, "string") && [
1175
+ if (!(typeof credentials === "string" && [
1251
1176
  "ambient",
1252
1177
  "none",
1253
1178
  "provisioned",
1254
1179
  "unknown"
1255
- ].includes(credentials) && hasRuntimeType(environment, "string") && [
1180
+ ].includes(credentials) && typeof environment === "string" && [
1256
1181
  "ambient",
1257
1182
  "none",
1258
1183
  "selected",
1259
1184
  "unknown"
1260
- ].includes(environment) && hasRuntimeType(access, "string") && [
1185
+ ].includes(environment) && typeof access === "string" && [
1261
1186
  "none",
1262
1187
  "read-only",
1263
1188
  "read-write",
1264
1189
  "unknown"
1265
- ].includes(access) && hasRuntimeType(scope, "string") && [
1190
+ ].includes(access) && typeof scope === "string" && [
1266
1191
  "host",
1267
1192
  "none",
1268
1193
  "sandbox",
1269
1194
  "unknown",
1270
1195
  "workspace"
1271
- ].includes(scope) && hasRuntimeType(isolation, "string") && [
1196
+ ].includes(scope) && typeof isolation === "string" && [
1272
1197
  "container",
1273
1198
  "microvm",
1274
1199
  "none",
1275
1200
  "process",
1276
1201
  "unknown"
1277
- ].includes(isolation) && hasRuntimeType(network, "string") && [
1202
+ ].includes(isolation) && typeof network === "string" && [
1278
1203
  "none",
1279
1204
  "restricted",
1280
1205
  "unrestricted",
1281
1206
  "unknown"
1282
- ].includes(network) && hasRuntimeType(processes, "string") && [
1207
+ ].includes(network) && typeof processes === "string" && [
1283
1208
  "arbitrary",
1284
1209
  "none",
1285
1210
  "restricted",
@@ -1317,7 +1242,7 @@ function normalizeExecutionAuthority(value) {
1317
1242
  }
1318
1243
  function timestamp(value) {
1319
1244
  if (value instanceof Date) return value.toISOString();
1320
- if (hasRuntimeType(value, "string")) return value;
1245
+ if (typeof value === "string") return value;
1321
1246
  if (isRuntimeObject(value)) try {
1322
1247
  return Reflect.apply(Date.prototype.toISOString, value, []);
1323
1248
  } catch (error) {
@@ -1326,7 +1251,7 @@ function timestamp(value) {
1326
1251
  return (/* @__PURE__ */ new Date()).toISOString();
1327
1252
  }
1328
1253
  function normalizedTraceActivity(activity) {
1329
- if (!activity || !hasRuntimeType(activity, "object")) return;
1254
+ if (!activity || typeof activity !== "object") return;
1330
1255
  try {
1331
1256
  if (Array.isArray(activity)) return;
1332
1257
  const owner = Object.getOwnPropertyDescriptor(activity, "owner");
@@ -1348,7 +1273,7 @@ function normalizedTraceActivity(activity) {
1348
1273
  }
1349
1274
  }
1350
1275
  function reflectedMapEntries(value) {
1351
- if (!value || !hasRuntimeType(value, "object")) return;
1276
+ if (!value || typeof value !== "object") return;
1352
1277
  try {
1353
1278
  return Array.from(Map.prototype.entries.call(value));
1354
1279
  } catch {
@@ -1356,7 +1281,7 @@ function reflectedMapEntries(value) {
1356
1281
  }
1357
1282
  }
1358
1283
  function reflectedSetValues(value) {
1359
- if (!value || !hasRuntimeType(value, "object")) return;
1284
+ if (!value || typeof value !== "object") return;
1360
1285
  try {
1361
1286
  return Array.from(Set.prototype.values.call(value));
1362
1287
  } catch {
@@ -1364,24 +1289,28 @@ function reflectedSetValues(value) {
1364
1289
  }
1365
1290
  }
1366
1291
  function isCryptoKey(value) {
1367
- if (!value || !hasRuntimeType(value, "object")) return false;
1292
+ if (!value || typeof value !== "object") return false;
1368
1293
  const CryptoKeyConstructor = Object.getOwnPropertyDescriptor(globalThis, "CryptoKey")?.value;
1369
- return hasRuntimeType(CryptoKeyConstructor, "function") && value instanceof CryptoKeyConstructor;
1294
+ return typeof CryptoKeyConstructor === "function" && value instanceof CryptoKeyConstructor;
1370
1295
  }
1371
1296
  function isWebAssemblyModule(value) {
1372
- if (!value || !hasRuntimeType(value, "object")) return false;
1373
- if (!hasRuntimeType(webAssemblyModuleConstructor, "function")) return false;
1374
- if (value instanceof webAssemblyModuleConstructor) return true;
1297
+ if (!value || typeof value !== "object") return false;
1298
+ const { constructor, exports } = webAssemblyModule;
1299
+ if (typeof constructor !== "function") return false;
1300
+ if (value instanceof constructor) return true;
1375
1301
  try {
1376
- if (!hasRuntimeType(webAssemblyModuleExports, "function")) return false;
1377
- Reflect.apply(webAssemblyModuleExports, webAssemblyModuleConstructor, [value]);
1302
+ if (typeof exports !== "function") return false;
1303
+ Reflect.apply(exports, constructor, [value]);
1378
1304
  return true;
1379
1305
  } catch {
1380
1306
  return false;
1381
1307
  }
1382
1308
  }
1383
- const intrinsicFunctionToString = Function.prototype.toString;
1384
- const nativeFunctionToString = (() => {
1309
+ function captureFunctionToString() {
1310
+ return Function.prototype.toString;
1311
+ }
1312
+ const intrinsicFunctionToString = /* @__PURE__ */ captureFunctionToString();
1313
+ function checkNativeFunctionToString() {
1385
1314
  try {
1386
1315
  if (Object.prototype.hasOwnProperty.call(intrinsicFunctionToString, "prototype")) return false;
1387
1316
  if (intrinsicFunctionToString.name !== "toString" || intrinsicFunctionToString.length !== 1) return false;
@@ -1410,9 +1339,10 @@ const nativeFunctionToString = (() => {
1410
1339
  } catch {
1411
1340
  return false;
1412
1341
  }
1413
- })();
1342
+ }
1343
+ const nativeFunctionToString = /* @__PURE__ */ checkNativeFunctionToString();
1414
1344
  function isNativeBufferOperation(value, name) {
1415
- if (!nativeFunctionToString || !hasRuntimeType(value, "function")) return false;
1345
+ if (!nativeFunctionToString || typeof value !== "function") return false;
1416
1346
  try {
1417
1347
  return intrinsicFunctionToString.call(value).replace(/\s+/g, " ") === `function ${name}() { [native code] }`;
1418
1348
  } catch {
@@ -1482,17 +1412,17 @@ function captureOrdinaryBufferOperations() {
1482
1412
  return;
1483
1413
  }
1484
1414
  }
1485
- const sharedBufferByteLength = captureSharedBufferByteLength();
1486
- const ordinaryBufferOperations = captureOrdinaryBufferOperations();
1415
+ const sharedBufferByteLength = /* @__PURE__ */ captureSharedBufferByteLength();
1416
+ const ordinaryBufferOperations = /* @__PURE__ */ captureOrdinaryBufferOperations();
1487
1417
  function isSharedArrayBuffer(value) {
1488
- if (!value || !hasRuntimeType(value, "object")) return false;
1418
+ if (!value || typeof value !== "object") return false;
1489
1419
  if (sharedBufferByteLength) try {
1490
1420
  if (ordinaryBufferOperations) Reflect.construct(ordinaryBufferOperations.dataView, [
1491
1421
  value,
1492
1422
  0,
1493
1423
  0
1494
1424
  ]);
1495
- return hasRuntimeType(sharedBufferByteLength.call(value), "number");
1425
+ return typeof sharedBufferByteLength.call(value) === "number";
1496
1426
  } catch {
1497
1427
  return false;
1498
1428
  }
@@ -1501,7 +1431,7 @@ function isSharedArrayBuffer(value) {
1501
1431
  if (prototype === Object.prototype) return false;
1502
1432
  const tag = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag)?.value;
1503
1433
  const byteLength = Object.getOwnPropertyDescriptor(prototype, "byteLength")?.get;
1504
- return tag === "SharedArrayBuffer" && hasRuntimeType(byteLength, "function");
1434
+ return tag === "SharedArrayBuffer" && typeof byteLength === "function";
1505
1435
  } catch {
1506
1436
  return true;
1507
1437
  }
@@ -1522,7 +1452,7 @@ function isSharedArrayBuffer(value) {
1522
1452
  }
1523
1453
  }
1524
1454
  function containsSharedArrayBuffer(value, seen = /* @__PURE__ */ new Set()) {
1525
- if (!value || !hasRuntimeType(value, "object")) return false;
1455
+ if (!value || typeof value !== "object") return false;
1526
1456
  if (isSharedArrayBuffer(value)) return true;
1527
1457
  const WebAssemblyMemory = globalThis.WebAssembly?.Memory;
1528
1458
  if (WebAssemblyMemory && value instanceof WebAssemblyMemory) return isSharedArrayBuffer(value.buffer);
@@ -1539,12 +1469,12 @@ function containsSharedArrayBuffer(value, seen = /* @__PURE__ */ new Set()) {
1539
1469
  });
1540
1470
  }
1541
1471
  function reflectedRegExpState(value) {
1542
- if (!value || !hasRuntimeType(value, "object")) return;
1472
+ if (!value || typeof value !== "object") return;
1543
1473
  try {
1544
1474
  const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get?.call(value);
1545
1475
  const flags = Object.getOwnPropertyDescriptor(RegExp.prototype, "flags")?.get?.call(value);
1546
1476
  const lastIndex = Reflect.get(value, "lastIndex");
1547
- if (!hasRuntimeType(source, "string") || !hasRuntimeType(flags, "string") || !hasRuntimeType(lastIndex, "number")) return;
1477
+ if (typeof source !== "string" || typeof flags !== "string" || typeof lastIndex !== "number") return;
1548
1478
  return {
1549
1479
  flags,
1550
1480
  lastIndex,
@@ -1558,26 +1488,26 @@ function reflectedArrayBufferViewState(value) {
1558
1488
  if (!ArrayBuffer.isView(value)) return;
1559
1489
  try {
1560
1490
  const bufferConstructor = Object.getOwnPropertyDescriptor(globalThis, "Buffer")?.value ?? globalThis.Buffer;
1561
- const isBuffer = hasRuntimeType(bufferConstructor, "function") ? Object.getOwnPropertyDescriptor(bufferConstructor, "isBuffer")?.value : void 0;
1562
- const isNodeBuffer = hasRuntimeType(isBuffer, "function") && Reflect.apply(isBuffer, bufferConstructor, [value]) === true;
1491
+ const isBuffer = typeof bufferConstructor === "function" ? Object.getOwnPropertyDescriptor(bufferConstructor, "isBuffer")?.value : void 0;
1492
+ const isNodeBuffer = typeof isBuffer === "function" && Reflect.apply(isBuffer, bufferConstructor, [value]) === true;
1563
1493
  const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
1564
1494
  if (isNodeBuffer) {
1565
1495
  const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength")?.get?.call(value);
1566
- return hasRuntimeType(byteLength, "number") ? {
1496
+ return typeof byteLength === "number" ? {
1567
1497
  byteLength,
1568
1498
  kind: "Buffer"
1569
1499
  } : void 0;
1570
1500
  }
1571
1501
  const typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get?.call(value);
1572
- if (hasRuntimeType(typedArrayTag, "string")) {
1502
+ if (typeof typedArrayTag === "string") {
1573
1503
  const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")?.get?.call(value);
1574
- return hasRuntimeType(byteLength, "number") ? {
1504
+ return typeof byteLength === "number" ? {
1575
1505
  byteLength,
1576
1506
  kind: typedArrayTag
1577
1507
  } : void 0;
1578
1508
  }
1579
1509
  const dataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get?.call(value);
1580
- return hasRuntimeType(dataViewByteLength, "number") ? {
1510
+ return typeof dataViewByteLength === "number" ? {
1581
1511
  byteLength: dataViewByteLength,
1582
1512
  kind: "DataView"
1583
1513
  } : void 0;
@@ -1587,23 +1517,23 @@ function reflectedArrayBufferViewState(value) {
1587
1517
  }
1588
1518
  function reflectedBlobState(value) {
1589
1519
  const BlobConstructor = globalThis.Blob;
1590
- if (!hasRuntimeType(BlobConstructor, "function") || !(value instanceof BlobConstructor)) return;
1520
+ if (typeof BlobConstructor !== "function" || !(value instanceof BlobConstructor)) return;
1591
1521
  try {
1592
1522
  const FileConstructor = globalThis.File;
1593
- const file = hasRuntimeType(FileConstructor, "function") && value instanceof FileConstructor ? value : void 0;
1523
+ const file = typeof FileConstructor === "function" && value instanceof FileConstructor ? value : void 0;
1594
1524
  const intrinsic = file ? new FileConstructor([], "") : new BlobConstructor([]);
1595
1525
  const size = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "size")?.get?.call(value);
1596
1526
  const type = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "type")?.get?.call(value);
1597
- if (!hasRuntimeType(size, "number") || !hasRuntimeType(type, "string")) return;
1527
+ if (typeof size !== "number" || typeof type !== "string") return;
1598
1528
  const state = {
1599
- intrinsicSymbols: new Set(Reflect.ownKeys(intrinsic).filter((key) => hasRuntimeType(key, "symbol") && Object.getOwnPropertyDescriptor(intrinsic, key)?.enumerable === true)),
1529
+ intrinsicSymbols: new Set(Reflect.ownKeys(intrinsic).filter((key) => typeof key === "symbol" && Object.getOwnPropertyDescriptor(intrinsic, key)?.enumerable === true)),
1600
1530
  size,
1601
1531
  type
1602
1532
  };
1603
1533
  if (file) {
1604
1534
  const lastModified = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "lastModified")?.get?.call(file);
1605
1535
  const name = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "name")?.get?.call(file);
1606
- if (!hasRuntimeType(lastModified, "number") || !hasRuntimeType(name, "string")) return;
1536
+ if (typeof lastModified !== "number" || typeof name !== "string") return;
1607
1537
  state.lastModified = lastModified;
1608
1538
  state.name = name;
1609
1539
  }
@@ -1613,7 +1543,7 @@ function reflectedBlobState(value) {
1613
1543
  }
1614
1544
  }
1615
1545
  function containsUnsafeStructuredCloneState(value, seen = /* @__PURE__ */ new Set()) {
1616
- if (!value || !hasRuntimeType(value, "object") || seen.has(value)) return false;
1546
+ if (!value || typeof value !== "object" || seen.has(value)) return false;
1617
1547
  if (isCryptoKey(value) || isWebAssemblyModule(value)) return true;
1618
1548
  seen.add(value);
1619
1549
  for (const key of Reflect.ownKeys(value)) {
@@ -1637,8 +1567,8 @@ function containsUnsafeStructuredCloneState(value, seen = /* @__PURE__ */ new Se
1637
1567
  return false;
1638
1568
  }
1639
1569
  function preservesEnumerableFields(source, snapshot, seen = /* @__PURE__ */ new Map()) {
1640
- if (!source || !hasRuntimeType(source, "object")) return true;
1641
- if (!snapshot || !hasRuntimeType(snapshot, "object")) return false;
1570
+ if (!source || typeof source !== "object") return true;
1571
+ if (!snapshot || typeof snapshot !== "object") return false;
1642
1572
  if (seen.has(source)) return seen.get(source) === snapshot;
1643
1573
  seen.set(source, snapshot);
1644
1574
  const sourceView = reflectedArrayBufferViewState(source);
@@ -1672,7 +1602,7 @@ function preservesEnumerableFields(source, snapshot, seen = /* @__PURE__ */ new
1672
1602
  for (const key of Reflect.ownKeys(source)) {
1673
1603
  const sourceDescriptor = Object.getOwnPropertyDescriptor(source, key);
1674
1604
  if (!sourceDescriptor?.enumerable) continue;
1675
- if (hasRuntimeType(key, "symbol")) {
1605
+ if (typeof key === "symbol") {
1676
1606
  if (sourceBlob?.intrinsicSymbols.has(key)) continue;
1677
1607
  return false;
1678
1608
  }
@@ -1700,7 +1630,7 @@ function preservesEnumerableFields(source, snapshot, seen = /* @__PURE__ */ new
1700
1630
  }
1701
1631
  function normalizedTracePayload(payload) {
1702
1632
  if (payload === void 0) return;
1703
- if (!payload || !hasRuntimeType(payload, "object")) return { visibility: "private" };
1633
+ if (!payload || typeof payload !== "object") return { visibility: "private" };
1704
1634
  try {
1705
1635
  if (Array.isArray(payload)) return { visibility: "private" };
1706
1636
  const visibility = Object.getOwnPropertyDescriptor(payload, "visibility");
@@ -1717,7 +1647,7 @@ function normalizedTracePayload(payload) {
1717
1647
  }
1718
1648
  if (visibility.value === "summary") {
1719
1649
  const summary = Object.getOwnPropertyDescriptor(payload, "summary");
1720
- if (summary && "value" in summary && hasRuntimeType(summary.value, "string")) return {
1650
+ if (summary && "value" in summary && typeof summary.value === "string") return {
1721
1651
  summary: summary.value,
1722
1652
  visibility: "summary"
1723
1653
  };
@@ -1829,7 +1759,7 @@ function durationMs(startTime, endTime) {
1829
1759
  return Number.isFinite(duration) && duration >= 0 ? duration : void 0;
1830
1760
  }
1831
1761
  function firstString(...values) {
1832
- return values.find((value) => hasRuntimeType(value, "string") && value.length > 0);
1762
+ return values.find((value) => typeof value === "string" && value.length > 0);
1833
1763
  }
1834
1764
  function runId(event) {
1835
1765
  return firstString(event.attributes?.["agent.run.id"], event.attributes?.["run.id"], event.attributes?.runId, event.trace?.id) || "default";
@@ -2065,7 +1995,7 @@ function traceEventsToOpenTelemetrySpans(events, options = {}) {
2065
1995
  startTime: step.startTime,
2066
1996
  status: {
2067
1997
  code: step.status === "failed" || !step.endTime && run.status === "failed" ? "ERROR" : step.endTime || run.status === "completed" ? "OK" : "UNSET",
2068
- ...hasRuntimeType(step.attributes?.["error.message"], "string") ? { message: step.attributes["error.message"] } : {}
1998
+ ...typeof step.attributes?.["error.message"] === "string" ? { message: step.attributes["error.message"] } : {}
2069
1999
  },
2070
2000
  traceId
2071
2001
  }))];
@@ -2146,14 +2076,14 @@ function isProxy(value) {
2146
2076
  }
2147
2077
  }
2148
2078
  function isCapabilityHandle(value) {
2149
- if (!hasRuntimeType(value, "object") || value === null) return false;
2079
+ if (typeof value !== "object" || value === null) return false;
2150
2080
  if (capabilityHandles.has(value)) return true;
2151
2081
  if (isProxy(value) === true) return false;
2152
2082
  try {
2153
2083
  const descriptors = Object.getOwnPropertyDescriptors(value);
2154
2084
  const kind = descriptors.kind;
2155
2085
  const implementation = descriptors.value;
2156
- if (!kind || !Object.hasOwn(kind, "value") || !hasRuntimeType(kind.value, "string") || !implementation || !Object.hasOwn(implementation, "value")) return false;
2086
+ if (!kind || !Object.hasOwn(kind, "value") || typeof kind.value !== "string" || !implementation || !Object.hasOwn(implementation, "value")) return false;
2157
2087
  if (Object.getPrototypeOf(value) === null) return false;
2158
2088
  let prototype = Object.getPrototypeOf(value);
2159
2089
  while (prototype !== null) {
@@ -2175,16 +2105,170 @@ function getCapability(context, name) {
2175
2105
  return defineCapability(name, value, { name });
2176
2106
  }
2177
2107
  function isResolvable(value) {
2178
- return hasRuntimeType(value, "object") && value !== null && "resolve" in value && hasRuntimeType(value.resolve, "function");
2108
+ return typeof value === "object" && value !== null && "resolve" in value && typeof value.resolve === "function";
2179
2109
  }
2180
2110
  async function resolveRuntimeValue(value, context) {
2181
2111
  if (isResolvable(value)) return await value.resolve(context);
2182
- if (hasRuntimeType(value, "function")) return await value(context);
2112
+ if (typeof value === "function") return await value(context);
2183
2113
  return value;
2184
2114
  }
2185
2115
  async function resolveCapabilityPolicy(policy, context) {
2186
2116
  if (!policy) return "allow";
2187
- return hasRuntimeType(policy, "function") ? await policy(context) : policy;
2117
+ return typeof policy === "function" ? await policy(context) : policy;
2118
+ }
2119
+ //#endregion
2120
+ //#region src/request-context.ts
2121
+ function isObjectLike(value) {
2122
+ return value !== null && (typeof value === "object" || typeof value === "function");
2123
+ }
2124
+ /**
2125
+ * Return true for a web Request. Hosts pass their own Request classes, such as a Request from another realm, so
2126
+ * check the fields that ViteHub reads when the prototype does not match. srvx's Node request inherits from
2127
+ * Request, and the prototype check does not run its lazy `url` and `headers` getters.
2128
+ */
2129
+ function isHostRequest(value) {
2130
+ if (value instanceof Request) return true;
2131
+ if (!isObjectLike(value)) return false;
2132
+ const headers = Reflect.get(value, "headers");
2133
+ return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
2134
+ }
2135
+ function readPath(value, path) {
2136
+ let current = value;
2137
+ for (const key of path) current = isObjectLike(current) ? Reflect.get(current, key) : void 0;
2138
+ return current;
2139
+ }
2140
+ /** The first non-empty string at one of `paths`. ViteHub never reads forwarding headers here. */
2141
+ function firstAddress(value, paths) {
2142
+ for (const path of paths) {
2143
+ const address = readPath(value, path);
2144
+ if (typeof address === "string" && address) return address;
2145
+ }
2146
+ }
2147
+ /**
2148
+ * The places where hosts put the peer address of a request, in the order of H3's `getRequestIP()`: a host adapter
2149
+ * sets `context.clientAddress`, and srvx sets `ip` and keeps the Node request in `runtime.node`.
2150
+ */
2151
+ const requestAddressPaths = [
2152
+ ["context", "clientAddress"],
2153
+ ["ip"],
2154
+ [
2155
+ "runtime",
2156
+ "node",
2157
+ "req",
2158
+ "socket",
2159
+ "remoteAddress"
2160
+ ]
2161
+ ];
2162
+ /**
2163
+ * The `~standard` properties of a Request that no framework wraps, such as the Request of a Fetchable server
2164
+ * entry. srvx and Nitro put the host data on the Request: `runtime.cloudflare`, `waitUntil`, and `ip`.
2165
+ * Nothing reads `res` for you. Copy `res.status` and `res.headers` to the Response that you return.
2166
+ */
2167
+ var RequestStandardProps = class {
2168
+ vendor = "fetch";
2169
+ req;
2170
+ res = { headers: new Headers() };
2171
+ #runtime;
2172
+ constructor(request) {
2173
+ this.req = request;
2174
+ }
2175
+ get runtime() {
2176
+ if (this.#runtime) return this.#runtime;
2177
+ const cloudflare = readPath(this.req, ["runtime", "cloudflare"]);
2178
+ const env = readPath(cloudflare, ["env"]);
2179
+ const context = readPath(cloudflare, ["context"]);
2180
+ const clientAddress = firstAddress(this.req, requestAddressPaths);
2181
+ return this.#runtime = {
2182
+ ...isObjectLike(env) || isObjectLike(context) ? { cloudflare: {
2183
+ ...isObjectLike(env) ? { env } : {},
2184
+ ...isObjectLike(context) ? { context } : {}
2185
+ } } : {},
2186
+ ...clientAddress ? { clientAddress } : {}
2187
+ };
2188
+ }
2189
+ get waitUntil() {
2190
+ for (const owner of [this.req, readPath(this.req, [
2191
+ "runtime",
2192
+ "cloudflare",
2193
+ "context"
2194
+ ])]) {
2195
+ const waitUntil = readPath(owner, ["waitUntil"]);
2196
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
2197
+ }
2198
+ }
2199
+ };
2200
+ const requestStandardContexts = /* @__PURE__ */ new WeakMap();
2201
+ /** Keep one Standard Context per Request, even when it cannot be extended. A value set by the host stays. */
2202
+ function installRequestStandardContext(request, standard) {
2203
+ if ("~standard" in request) return request["~standard"];
2204
+ const props = standard ?? requestStandardContexts.get(request) ?? new RequestStandardProps(request);
2205
+ if (Object.isExtensible(request)) Object.defineProperty(request, "~standard", {
2206
+ configurable: true,
2207
+ enumerable: false,
2208
+ value: props
2209
+ });
2210
+ else requestStandardContexts.set(request, props);
2211
+ return props;
2212
+ }
2213
+ /**
2214
+ * Return the Standard Context of a web Request or of a request event. In a Fetchable server entry, pass the
2215
+ * Request: `getStandardContext(request)`. In a ViteHub app, Nitro sets `~standard` on each event and on its
2216
+ * Request, so ViteHub keeps the response headers that primitives set. Throws `RUNTIME_R0015` for an event without
2217
+ * Standard Context.
2218
+ */
2219
+ function getStandardContext(value) {
2220
+ if (isObjectLike(value) && "~standard" in value) return value["~standard"];
2221
+ if (isHostRequest(value)) return installRequestStandardContext(value);
2222
+ throw runtimeErrorDiagnostics.RUNTIME_R0015({ message: "[vitehub] The value is not a Request and has no `~standard`. Pass the Request of a Fetchable handler or the event of a route in a ViteHub app." });
2223
+ }
2224
+ /**
2225
+ * Adds the prepared response of a plain Fetch host to the Response that a ViteHub route returns, as H3 adds it in a
2226
+ * ViteHub app: `set-cookie` values join the ones of the Response, and other headers replace them. The headers move,
2227
+ * so a host that also copies `res.headers` does not send them twice. With another vendor, such as H3, the host adds
2228
+ * the prepared response, and `response` comes back as it is.
2229
+ */
2230
+ function sendPreparedResponse(request, response) {
2231
+ const standard = getStandardContext(request);
2232
+ const prepared = standard.res.headers;
2233
+ if (standard.vendor !== "fetch" || !prepared || prepared.keys().next().done) return response;
2234
+ const headers = new Headers(response.headers);
2235
+ for (const [name, value] of prepared) if (name === "set-cookie") headers.append(name, value);
2236
+ else headers.set(name, value);
2237
+ for (const name of Array.from(prepared.keys())) prepared.delete(name);
2238
+ return new Response(response.body, {
2239
+ headers,
2240
+ status: response.status,
2241
+ statusText: response.statusText
2242
+ });
2243
+ }
2244
+ function detectRuntime(cloudflare) {
2245
+ if (cloudflare) return "cloudflare-agents";
2246
+ if ("Deno" in globalThis) return "deno";
2247
+ if (typeof process !== "undefined") {
2248
+ if (process.env.VERCEL) return "vercel";
2249
+ if (process.env.NODE_ENV === "development") return "vite";
2250
+ }
2251
+ return "unknown";
2252
+ }
2253
+ /** Create the runtime context of one request from its Standard Context. The H3 entry shares this function. */
2254
+ function createStandardRuntimeContext(event, standard, options) {
2255
+ const request = options.request ?? standard?.req;
2256
+ if (!request) throw runtimeErrorDiagnostics.RUNTIME_R0015({ message: "[vitehub] The event has no request, so ViteHub cannot create a runtime context." });
2257
+ const waitUntil = options.waitUntil?.bind(options) ?? options.vercel?.waitUntil?.bind(options.vercel) ?? standard?.waitUntil;
2258
+ const cloudflare = options.cloudflare ?? standard?.runtime?.cloudflare;
2259
+ const runtime = options.runtime ?? detectRuntime(!!cloudflare);
2260
+ return createRuntimeContext({
2261
+ request,
2262
+ ...options,
2263
+ ...cloudflare ? { cloudflare } : {},
2264
+ event,
2265
+ runtime,
2266
+ ...runtime === "vercel" && waitUntil ? { vercel: { waitUntil } } : {},
2267
+ ...waitUntil ? { waitUntil } : {}
2268
+ });
2269
+ }
2270
+ function getRuntimeContext(value, options = {}) {
2271
+ return createStandardRuntimeContext(value, getStandardContext(value), options);
2188
2272
  }
2189
2273
  //#endregion
2190
- export { registerPublicUrlAgentName as A, createWorkTracker as C, isRuntimeDiagnostic as D, formatRuntimeDiagnosticError as E, ExecutionBudgetExceededError as F, createExecutionBudget as I, runRuntimePreflight as L, resolvePublicUrl as M, decodeRouteSegment as N, normalizeRuntimeDiagnosticError as O, encodeRouteSegment as P, startRuntimePreflight as R, toResponse as S, toResultError as T, traceEventsToOpenTelemetrySpans as _, defineCapability as a, isSerializedResponse as b, getCapability as c, isResolvable as d, noExecutionAuthority as f, traceEventsToOpenTelemetryLogRecords as g, resolveRuntimeValue as h, createTraceEventLog as i, resetPublicUrlAgentNames as j, consoleInvocationUrl as k, hasCapability as l, resolveCapabilityPolicy as m, createRuntimeContext as n, deriveTraceRuns as o, normalizeExecutionAuthority as p, createRuntimeWaitUntilController as r, emitTraceEvent as s, createExecutionContext as t, isExecutionAuthority as u, unknownExecutionAuthority as v, defineErrors as w, serializeResponse as x, deserializeResponse as y, isTraceContentAttributeKey as z };
2274
+ export { isResponse as A, isRuntimeDiagnostic as B, resolveRuntimeValue as C, detectHost as D, unknownExecutionAuthority as E, createSqlLeaseStore as F, activeEnvStorageKey as G, createExecutionBudget as H, leaseTable as I, ownObject as J, cloudflareOwners as K, defineErrors as L, serializeResponse as M, toResponse as N, getHostBinding as O, createMemoryLeaseStore as P, toResultError as R, resolveCapabilityPolicy as S, traceEventsToOpenTelemetrySpans as T, isExecutionBudgetExceededError as U, normalizeRuntimeDiagnosticError as V, isTraceContentAttributeKey as W, ownValue as Y, hasCapability as _, installRequestStandardContext as a, noExecutionAuthority as b, sendPreparedResponse as c, createRuntimeWaitUntilController as d, createTraceEventLog as f, getCapability as g, emitTraceEvent as h, getStandardContext as i, isSerializedResponse as j, deserializeResponse as k, createExecutionContext as l, deriveTraceRuns as m, firstAddress as n, isHostRequest as o, defineCapability as p, getCloudflareEnv as q, getRuntimeContext as r, requestAddressPaths as s, createStandardRuntimeContext as t, createRuntimeContext as u, isExecutionAuthority as v, traceEventsToOpenTelemetryLogRecords as w, normalizeExecutionAuthority as x, isResolvable as y, formatRuntimeDiagnosticError as z };