@vite-hub/runtime 0.0.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +278 -41
- package/dist/durability.d.ts +107 -0
- package/dist/durability.js +168 -0
- package/dist/error-diagnostics-BKICpwZp.js +85 -0
- package/dist/error-diagnostics-BsJr9VdW.d.ts +15 -0
- package/dist/errors-BEomN3fX.js +190 -0
- package/dist/execution-budget-BPXbISEt.d.ts +56 -0
- package/dist/index-Bcl-Hr-a.d.ts +678 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.js +5 -1159
- package/dist/internal/drain.d.ts +17 -0
- package/dist/internal/drain.js +75 -0
- package/dist/internal/execution-budget.d.ts +10 -0
- package/dist/internal/execution-budget.js +17 -0
- package/dist/internal/grant.d.ts +36 -0
- package/dist/internal/grant.js +44 -0
- package/dist/internal/h3.d.ts +42 -0
- package/dist/internal/h3.js +181 -0
- package/dist/internal/node.d.ts +33 -0
- package/dist/{node.js → internal/node.js} +12 -9
- package/dist/internal/public-url.d.ts +2 -0
- package/dist/internal/public-url.js +2 -0
- package/dist/internal/run-scope.d.ts +11 -0
- package/dist/internal/run-scope.js +30 -0
- package/dist/internal/runtime-type.d.ts +26 -0
- package/dist/internal/runtime-type.js +3 -0
- package/dist/internal/shutdown.d.ts +84 -0
- package/dist/internal/shutdown.js +202 -0
- package/dist/internal/test-mode-setup.d.ts +7 -0
- package/dist/internal/test-mode-setup.js +114 -0
- package/dist/internal/test-mode.d.ts +32 -0
- package/dist/internal/test-mode.js +9 -0
- package/dist/operations.d.ts +167 -0
- package/dist/operations.js +406 -0
- package/dist/public-url-1WeOw54Z.d.ts +34 -0
- package/dist/public-url-B6x0HMgY.js +140 -0
- package/dist/request-context-CP9NhgLL.js +2274 -0
- package/dist/runtime-type-BftydMAf.js +88 -0
- package/package.json +92 -17
- package/dist/drain.d.ts +0 -1
- package/dist/drain.js +0 -52
- package/dist/index-tBKyUP1T.d.ts +0 -314
- package/dist/node.d.ts +0 -35
- package/dist/runtime-type-ovvOd6m5.js +0 -37
|
@@ -0,0 +1,2274 @@
|
|
|
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";
|
|
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
|
|
43
|
+
//#region src/internal/trace-attributes.ts
|
|
44
|
+
const contentAttributeKeys = /* @__PURE__ */ new Set([
|
|
45
|
+
"args",
|
|
46
|
+
"body",
|
|
47
|
+
"content",
|
|
48
|
+
"data",
|
|
49
|
+
"input",
|
|
50
|
+
"message",
|
|
51
|
+
"messages",
|
|
52
|
+
"output",
|
|
53
|
+
"payload",
|
|
54
|
+
"progress",
|
|
55
|
+
"prompt",
|
|
56
|
+
"raw",
|
|
57
|
+
"request",
|
|
58
|
+
"response",
|
|
59
|
+
"result",
|
|
60
|
+
"text",
|
|
61
|
+
"title"
|
|
62
|
+
]);
|
|
63
|
+
const canonicalAttributeKeys = /* @__PURE__ */ new Set([
|
|
64
|
+
"vitehub.activity.owner",
|
|
65
|
+
"vitehub.activity.phase",
|
|
66
|
+
"vitehub.payload.summary",
|
|
67
|
+
"vitehub.payload.value",
|
|
68
|
+
"vitehub.payload.visibility"
|
|
69
|
+
]);
|
|
70
|
+
function isTraceContentAttributeKey(key) {
|
|
71
|
+
if (key === "error.message") return false;
|
|
72
|
+
if (contentAttributeKeys.has(key)) return true;
|
|
73
|
+
return key.split(".").some((part, index) => index > 0 && contentAttributeKeys.has(part));
|
|
74
|
+
}
|
|
75
|
+
function ownProperties(value) {
|
|
76
|
+
if (!isRuntimeObject(value)) return [];
|
|
77
|
+
return Reflect.ownKeys(value).flatMap((key) => {
|
|
78
|
+
if (typeof key !== "string") return [];
|
|
79
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
80
|
+
return descriptor?.enumerable ? [[key, descriptor]] : [];
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
function mapArray(value, map) {
|
|
84
|
+
const length = Object.getOwnPropertyDescriptor(value, "length").value;
|
|
85
|
+
const next = [];
|
|
86
|
+
next.length = length;
|
|
87
|
+
for (let index = 0; index < length; index += 1) {
|
|
88
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, index);
|
|
89
|
+
if (descriptor && "value" in descriptor) next[index] = map(descriptor.value);
|
|
90
|
+
}
|
|
91
|
+
return next;
|
|
92
|
+
}
|
|
93
|
+
function metadataValue(value, seen) {
|
|
94
|
+
if (!value || typeof value !== "object") return value;
|
|
95
|
+
if (seen.has(value)) return "[Circular]";
|
|
96
|
+
seen.add(value);
|
|
97
|
+
try {
|
|
98
|
+
if (Array.isArray(value)) return mapArray(value, (child) => metadataValue(child, seen));
|
|
99
|
+
return projectProperties(ownProperties(value), "metadata", seen);
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
} finally {
|
|
103
|
+
seen.delete(value);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function projectProperties(properties, content, seen) {
|
|
107
|
+
const omitted = [];
|
|
108
|
+
const next = Object.fromEntries(properties.flatMap(([key, descriptor]) => {
|
|
109
|
+
if (content === "metadata" && isTraceContentAttributeKey(key)) {
|
|
110
|
+
omitted.push(key);
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
if (!("value" in descriptor)) return [];
|
|
114
|
+
return [[key, content === "metadata" ? metadataValue(descriptor.value, seen) : descriptor.value]];
|
|
115
|
+
}));
|
|
116
|
+
if (omitted.length) next["content.omitted"] = omitted;
|
|
117
|
+
return next;
|
|
118
|
+
}
|
|
119
|
+
/** Project ordinary attributes; canonical activity and payload fields belong to the event. */
|
|
120
|
+
function normalizeTraceAttributes(attributes, content) {
|
|
121
|
+
let properties;
|
|
122
|
+
try {
|
|
123
|
+
properties = ownProperties(attributes || {}).filter(([key]) => !canonicalAttributeKeys.has(key));
|
|
124
|
+
} catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const source = projectProperties(properties, "content", /* @__PURE__ */ new WeakSet());
|
|
128
|
+
try {
|
|
129
|
+
if (Array.isArray(source["content.omitted"])) {
|
|
130
|
+
const omitted = mapArray(source["content.omitted"], (value) => value).filter((key) => typeof key === "string" && !canonicalAttributeKeys.has(key));
|
|
131
|
+
if (omitted.length) source["content.omitted"] = omitted;
|
|
132
|
+
else delete source["content.omitted"];
|
|
133
|
+
}
|
|
134
|
+
} catch {
|
|
135
|
+
delete source["content.omitted"];
|
|
136
|
+
}
|
|
137
|
+
if (content === "metadata") {
|
|
138
|
+
const accessors = properties.filter(([key, descriptor]) => !("value" in descriptor) && isTraceContentAttributeKey(key));
|
|
139
|
+
if (accessors.length) {
|
|
140
|
+
const omitted = new Set(Array.isArray(source["content.omitted"]) ? source["content.omitted"] : []);
|
|
141
|
+
for (const [key] of accessors) omitted.add(key);
|
|
142
|
+
source["content.omitted"] = [...omitted];
|
|
143
|
+
}
|
|
144
|
+
const next = projectProperties(ownProperties(source), content, /* @__PURE__ */ new WeakSet());
|
|
145
|
+
return Object.keys(next).length ? next : void 0;
|
|
146
|
+
}
|
|
147
|
+
return Object.keys(source).length ? source : void 0;
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
|
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
|
|
155
|
+
});
|
|
156
|
+
}
|
|
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";
|
|
160
|
+
}
|
|
161
|
+
function createBudgetNode(parent) {
|
|
162
|
+
const node = {
|
|
163
|
+
cleanups: /* @__PURE__ */ new Set(),
|
|
164
|
+
children: /* @__PURE__ */ new Set(),
|
|
165
|
+
...parent ? { parent } : {},
|
|
166
|
+
disposed: parent?.disposed ?? false
|
|
167
|
+
};
|
|
168
|
+
if (!parent?.disposed) parent?.children.add(node);
|
|
169
|
+
return node;
|
|
170
|
+
}
|
|
171
|
+
function registerBudgetCleanup(node, cleanup) {
|
|
172
|
+
if (node.disposed) {
|
|
173
|
+
cleanup();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
node.cleanups.add(cleanup);
|
|
177
|
+
}
|
|
178
|
+
function disposeBudgetNode(node) {
|
|
179
|
+
if (node.disposed) return;
|
|
180
|
+
node.disposed = true;
|
|
181
|
+
for (const child of [...node.children]) disposeBudgetNode(child);
|
|
182
|
+
node.children.clear();
|
|
183
|
+
for (const cleanup of [...node.cleanups]) cleanup();
|
|
184
|
+
node.cleanups.clear();
|
|
185
|
+
node.parent?.children.delete(node);
|
|
186
|
+
}
|
|
187
|
+
/** Listen once and release the listener when the budget aborts, is exhausted elsewhere, or is disposed. */
|
|
188
|
+
function listenUntilReleased(signal, onAbort, node, releaseSignals) {
|
|
189
|
+
if (node.disposed) return;
|
|
190
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
191
|
+
const release = () => signal.removeEventListener("abort", onAbort);
|
|
192
|
+
for (const releaseSignal of releaseSignals) {
|
|
193
|
+
if (releaseSignal === signal) continue;
|
|
194
|
+
releaseSignal.addEventListener("abort", release, { once: true });
|
|
195
|
+
registerBudgetCleanup(node, () => releaseSignal.removeEventListener("abort", release));
|
|
196
|
+
}
|
|
197
|
+
registerBudgetCleanup(node, release);
|
|
198
|
+
}
|
|
199
|
+
function createExecutionBudget(options = {}) {
|
|
200
|
+
const limits = normalizeLimits(options);
|
|
201
|
+
const controller = new AbortController();
|
|
202
|
+
const state = {
|
|
203
|
+
controller,
|
|
204
|
+
sharedController: new AbortController(),
|
|
205
|
+
limits,
|
|
206
|
+
usage: {
|
|
207
|
+
inputBytes: 0,
|
|
208
|
+
outputBytes: 0,
|
|
209
|
+
retries: 0,
|
|
210
|
+
toolCalls: 0
|
|
211
|
+
},
|
|
212
|
+
node: createBudgetNode()
|
|
213
|
+
};
|
|
214
|
+
const abortFromExternal = () => controller.abort(options.signal?.reason);
|
|
215
|
+
if (options.signal) {
|
|
216
|
+
if (options.signal.aborted) abortFromExternal();
|
|
217
|
+
else listenUntilReleased(options.signal, abortFromExternal, state.node, [controller.signal, state.sharedController.signal]);
|
|
218
|
+
}
|
|
219
|
+
if (limits.deadlineAt !== void 0) scheduleDeadline(controller, limits.deadlineAt, state.node, state.sharedController.signal);
|
|
220
|
+
return createBudget(state, limits, controller, state.node, options.signal);
|
|
221
|
+
}
|
|
222
|
+
function scheduleDeadline(controller, deadlineAt, node, sharedSignal) {
|
|
223
|
+
if (node.disposed) return;
|
|
224
|
+
let timer;
|
|
225
|
+
const schedule = () => {
|
|
226
|
+
if (node.disposed || controller.signal.aborted) return;
|
|
227
|
+
const remaining = deadlineAt - Date.now();
|
|
228
|
+
if (remaining <= 0) controller.abort(new DOMException("Execution budget timed out: deadline exceeded.", "TimeoutError"));
|
|
229
|
+
else {
|
|
230
|
+
timer = setTimeout(schedule, Math.min(remaining, 2147483647));
|
|
231
|
+
if (typeof timer === "object" && timer !== null && "unref" in timer && typeof timer.unref === "function") timer.unref();
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
const clear = () => clearTimeout(timer);
|
|
235
|
+
controller.signal.addEventListener("abort", clear, { once: true });
|
|
236
|
+
sharedSignal.addEventListener("abort", clear, { once: true });
|
|
237
|
+
registerBudgetCleanup(node, () => {
|
|
238
|
+
clear();
|
|
239
|
+
controller.signal.removeEventListener("abort", clear);
|
|
240
|
+
sharedSignal.removeEventListener("abort", clear);
|
|
241
|
+
});
|
|
242
|
+
schedule();
|
|
243
|
+
}
|
|
244
|
+
function createBudget(state, limits, controller, node, externalSignal, deadlineController = controller) {
|
|
245
|
+
function assertAvailable(counter, amount) {
|
|
246
|
+
const stateReason = state.controller.signal.reason;
|
|
247
|
+
const controllerReason = controller.signal.reason;
|
|
248
|
+
const sharedReason = state.sharedController.signal.reason;
|
|
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();
|
|
252
|
+
if (state.sharedController.signal.aborted) {
|
|
253
|
+
if (isExecutionBudgetExceededError(sharedReason)) throw sharedReason;
|
|
254
|
+
state.sharedController.signal.throwIfAborted();
|
|
255
|
+
}
|
|
256
|
+
if (!node.disposed && limits.deadlineAt !== void 0 && Date.now() >= limits.deadlineAt) {
|
|
257
|
+
deadlineController.abort(new DOMException("Execution budget timed out: deadline exceeded.", "TimeoutError"));
|
|
258
|
+
deadlineController.signal.throwIfAborted();
|
|
259
|
+
}
|
|
260
|
+
if (!Number.isFinite(amount) || amount < 0) throw runtimeErrorDiagnostics.RUNTIME_EXECUTION_BUDGET_AMOUNT_INVALID({ counter });
|
|
261
|
+
const next = state.usage[counter] + amount;
|
|
262
|
+
const limit = limitFor(counter, limits);
|
|
263
|
+
if (limit !== void 0 && next > limit) {
|
|
264
|
+
const error = executionBudgetExceededError(counter, limit);
|
|
265
|
+
state.sharedController.abort(error);
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
if (isExecutionBudgetExceededError(stateReason)) throw stateReason;
|
|
269
|
+
if (isExecutionBudgetExceededError(controllerReason)) throw controllerReason;
|
|
270
|
+
}
|
|
271
|
+
function consume(counter, amount = 1) {
|
|
272
|
+
assertAvailable(counter, amount);
|
|
273
|
+
state.usage[counter] += amount;
|
|
274
|
+
}
|
|
275
|
+
return {
|
|
276
|
+
signal: AbortSignal.any([controller.signal, state.sharedController.signal]),
|
|
277
|
+
cancel(reason) {
|
|
278
|
+
controller.abort(reason);
|
|
279
|
+
},
|
|
280
|
+
dispose() {
|
|
281
|
+
disposeBudgetNode(node);
|
|
282
|
+
},
|
|
283
|
+
child(options = {}) {
|
|
284
|
+
const childLimits = normalizeLimits(options);
|
|
285
|
+
const childController = new AbortController();
|
|
286
|
+
const childNode = createBudgetNode(node);
|
|
287
|
+
const abortChild = (reason) => childController.abort(reason);
|
|
288
|
+
const releaseSignals = [childController.signal, state.sharedController.signal];
|
|
289
|
+
if (state.sharedController.signal.aborted) abortChild(state.sharedController.signal.reason);
|
|
290
|
+
else if (controller.signal.aborted) abortChild(controller.signal.reason);
|
|
291
|
+
else {
|
|
292
|
+
listenUntilReleased(controller.signal, () => abortChild(controller.signal.reason), childNode, releaseSignals);
|
|
293
|
+
listenUntilReleased(state.sharedController.signal, () => abortChild(state.sharedController.signal.reason), childNode, releaseSignals);
|
|
294
|
+
}
|
|
295
|
+
if (options.signal) {
|
|
296
|
+
if (options.signal.aborted) abortChild(options.signal.reason);
|
|
297
|
+
else if (!childController.signal.aborted) listenUntilReleased(options.signal, () => abortChild(options.signal?.reason), childNode, releaseSignals);
|
|
298
|
+
}
|
|
299
|
+
const deadlineAt = minDefined(limits.deadlineAt, childLimits.deadlineAt);
|
|
300
|
+
const childDeadlineController = deadlineAt === limits.deadlineAt ? deadlineController : childController;
|
|
301
|
+
if (deadlineAt !== void 0) scheduleDeadline(childController, deadlineAt, childNode, state.sharedController.signal);
|
|
302
|
+
return createBudget(state, {
|
|
303
|
+
deadlineAt,
|
|
304
|
+
maxInputBytes: minDefined(limits.maxInputBytes, childLimits.maxInputBytes),
|
|
305
|
+
maxOutputBytes: minDefined(limits.maxOutputBytes, childLimits.maxOutputBytes),
|
|
306
|
+
maxRetries: minDefined(limits.maxRetries, childLimits.maxRetries),
|
|
307
|
+
maxToolCalls: minDefined(limits.maxToolCalls, childLimits.maxToolCalls)
|
|
308
|
+
}, childController, childNode, options.signal, childDeadlineController);
|
|
309
|
+
},
|
|
310
|
+
consume(counter, amount = 1) {
|
|
311
|
+
consume(counter, amount);
|
|
312
|
+
},
|
|
313
|
+
recordInputBytes(amount) {
|
|
314
|
+
assertAvailable("inputBytes", amount);
|
|
315
|
+
state.usage.inputBytes += amount;
|
|
316
|
+
},
|
|
317
|
+
recordOutputBytes(amount) {
|
|
318
|
+
assertAvailable("outputBytes", amount);
|
|
319
|
+
state.usage.outputBytes += amount;
|
|
320
|
+
},
|
|
321
|
+
recordRetry() {
|
|
322
|
+
assertAvailable("retries", 1);
|
|
323
|
+
state.usage.retries += 1;
|
|
324
|
+
},
|
|
325
|
+
recordToolCall(inputBytes = 0) {
|
|
326
|
+
assertAvailable("toolCalls", 1);
|
|
327
|
+
if (inputBytes !== 0) assertAvailable("inputBytes", inputBytes);
|
|
328
|
+
state.usage.toolCalls += 1;
|
|
329
|
+
if (inputBytes !== 0) state.usage.inputBytes += inputBytes;
|
|
330
|
+
},
|
|
331
|
+
snapshot() {
|
|
332
|
+
const remainingTime = limits.deadlineAt === void 0 ? void 0 : Math.max(0, limits.deadlineAt - Date.now());
|
|
333
|
+
return {
|
|
334
|
+
cancelled: state.controller.signal.aborted || controller.signal.aborted || state.sharedController.signal.aborted,
|
|
335
|
+
...limits.deadlineAt === void 0 ? {} : { deadlineAt: limits.deadlineAt },
|
|
336
|
+
limits: { ...limits },
|
|
337
|
+
remaining: {
|
|
338
|
+
...limits.maxInputBytes === void 0 ? {} : { inputBytes: Math.max(0, limits.maxInputBytes - state.usage.inputBytes) },
|
|
339
|
+
...limits.maxOutputBytes === void 0 ? {} : { outputBytes: Math.max(0, limits.maxOutputBytes - state.usage.outputBytes) },
|
|
340
|
+
...limits.maxRetries === void 0 ? {} : { retries: Math.max(0, limits.maxRetries - state.usage.retries) },
|
|
341
|
+
...limits.maxToolCalls === void 0 ? {} : { toolCalls: Math.max(0, limits.maxToolCalls - state.usage.toolCalls) },
|
|
342
|
+
...remainingTime === void 0 ? {} : { timeMs: remainingTime }
|
|
343
|
+
},
|
|
344
|
+
usage: { ...state.usage }
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
function limitFor(counter, limits) {
|
|
350
|
+
if (counter === "inputBytes") return limits.maxInputBytes;
|
|
351
|
+
if (counter === "outputBytes") return limits.maxOutputBytes;
|
|
352
|
+
if (counter === "retries") return limits.maxRetries;
|
|
353
|
+
return limits.maxToolCalls;
|
|
354
|
+
}
|
|
355
|
+
function minDefined(left, right) {
|
|
356
|
+
if (left === void 0) return right;
|
|
357
|
+
if (right === void 0) return left;
|
|
358
|
+
return Math.min(left, right);
|
|
359
|
+
}
|
|
360
|
+
function normalizeLimits(options) {
|
|
361
|
+
const normalize = (value) => {
|
|
362
|
+
if (value === void 0) return void 0;
|
|
363
|
+
if (!Number.isFinite(value) || value < 0) throw runtimeErrorDiagnostics.RUNTIME_EXECUTION_BUDGET_LIMIT_INVALID();
|
|
364
|
+
return Math.floor(value);
|
|
365
|
+
};
|
|
366
|
+
return {
|
|
367
|
+
deadlineAt: normalize(options.deadlineAt),
|
|
368
|
+
maxInputBytes: normalize(options.maxInputBytes),
|
|
369
|
+
maxOutputBytes: normalize(options.maxOutputBytes),
|
|
370
|
+
maxRetries: normalize(options.maxRetries),
|
|
371
|
+
maxToolCalls: normalize(options.maxToolCalls)
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/diagnostics.ts
|
|
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
|
+
*/
|
|
380
|
+
function isRuntimeDiagnostic(error) {
|
|
381
|
+
if (!isRuntimeObject(error)) return false;
|
|
382
|
+
try {
|
|
383
|
+
const nativeIsError = Reflect.get(Error, "isError");
|
|
384
|
+
if (!(typeof nativeIsError === "function" ? nativeIsError(error) === true : error instanceof Error || !(Symbol.toStringTag in error) && Object.prototype.toString.call(error) === "[object Error]")) return false;
|
|
385
|
+
const message = Reflect.get(error, "message");
|
|
386
|
+
const code = Reflect.get(error, "code");
|
|
387
|
+
const name = Reflect.get(error, "name");
|
|
388
|
+
const why = Reflect.get(error, "why");
|
|
389
|
+
const fix = Reflect.get(error, "fix");
|
|
390
|
+
const docs = Reflect.get(error, "docs");
|
|
391
|
+
const sources = Reflect.get(error, "sources");
|
|
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";
|
|
393
|
+
} catch {
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
function boundedString(value, state) {
|
|
398
|
+
if (typeof value !== "string") return;
|
|
399
|
+
const maximum = Math.min(state.maxStringLength, state.remainingStringLength);
|
|
400
|
+
if (maximum <= 0) return;
|
|
401
|
+
if (value.length <= maximum) {
|
|
402
|
+
state.remainingStringLength -= value.length;
|
|
403
|
+
return value;
|
|
404
|
+
}
|
|
405
|
+
const suffix = `… [${value.length - maximum} chars omitted]`;
|
|
406
|
+
const bounded = maximum > suffix.length ? `${value.slice(0, maximum - suffix.length)}${suffix}` : value.slice(0, maximum);
|
|
407
|
+
state.remainingStringLength -= bounded.length;
|
|
408
|
+
return bounded;
|
|
409
|
+
}
|
|
410
|
+
function safeString(value) {
|
|
411
|
+
try {
|
|
412
|
+
return String(value);
|
|
413
|
+
} catch {
|
|
414
|
+
return "Unknown error";
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
function readProperty(value, key) {
|
|
418
|
+
if (!isRuntimeObject(value)) return void 0;
|
|
419
|
+
try {
|
|
420
|
+
return value[key];
|
|
421
|
+
} catch {
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function scalarProperty(value, key, state) {
|
|
426
|
+
const property = readProperty(value, key);
|
|
427
|
+
if (typeof property === "string") return boundedString(property, state);
|
|
428
|
+
return typeof property === "number" && Number.isFinite(property) ? property : void 0;
|
|
429
|
+
}
|
|
430
|
+
function errorChildren(value, maximum) {
|
|
431
|
+
try {
|
|
432
|
+
if (!Array.isArray(value)) return;
|
|
433
|
+
const length = Math.min(value.length, maximum);
|
|
434
|
+
return Array.from({ length }, (_item, index) => readProperty(value, index));
|
|
435
|
+
} catch {
|
|
436
|
+
return [];
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
function normalizeDetailValue(value, state, depth) {
|
|
440
|
+
if (state.remainingNodes <= 0) return;
|
|
441
|
+
state.remainingNodes -= 1;
|
|
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);
|
|
445
|
+
if (depth > state.maxDepth) return boundedString("[Detail depth exceeded]", state);
|
|
446
|
+
if (Array.isArray(value)) return value.flatMap((item) => {
|
|
447
|
+
const normalized = normalizeDetailValue(item, state, depth + 1);
|
|
448
|
+
return normalized === void 0 ? [] : [normalized];
|
|
449
|
+
});
|
|
450
|
+
if (!isRuntimeObject(value)) return;
|
|
451
|
+
const normalized = {};
|
|
452
|
+
let keys;
|
|
453
|
+
try {
|
|
454
|
+
keys = Object.keys(value);
|
|
455
|
+
} catch {
|
|
456
|
+
return normalized;
|
|
457
|
+
}
|
|
458
|
+
for (const key of keys) {
|
|
459
|
+
const normalizedKey = boundedString(key, state);
|
|
460
|
+
if (!normalizedKey) break;
|
|
461
|
+
const child = normalizeDetailValue(readProperty(value, key), state, depth + 1);
|
|
462
|
+
if (child !== void 0) normalized[normalizedKey] = child;
|
|
463
|
+
}
|
|
464
|
+
return normalized;
|
|
465
|
+
}
|
|
466
|
+
function normalizeDetails(details, state, depth) {
|
|
467
|
+
const normalized = normalizeDetailValue(details, state, depth);
|
|
468
|
+
if (!isRuntimeObject(normalized) || Array.isArray(normalized)) return;
|
|
469
|
+
return normalized;
|
|
470
|
+
}
|
|
471
|
+
function normalizeError(value, state, depth) {
|
|
472
|
+
if (state.remainingNodes <= 0) return;
|
|
473
|
+
state.remainingNodes -= 1;
|
|
474
|
+
if (typeof value === "string") return { message: boundedString(value, state) || "Error" };
|
|
475
|
+
if (!value || typeof value !== "object") return { message: boundedString(safeString(value), state) || "Error" };
|
|
476
|
+
if (state.ancestors.has(value)) return { message: boundedString("[Circular error cause]", state) || "Error" };
|
|
477
|
+
if (depth > state.maxDepth) return { message: boundedString("[Error cause depth exceeded]", state) || "Error" };
|
|
478
|
+
state.ancestors.add(value);
|
|
479
|
+
try {
|
|
480
|
+
const publicError = getViteHubErrorShape(value);
|
|
481
|
+
const why = readProperty(value, "why");
|
|
482
|
+
const message = boundedString(readProperty(value, "message"), state) || boundedString(why, state) || boundedString(safeString(value), state) || "Error";
|
|
483
|
+
const name = boundedString(readProperty(value, "name"), state) || boundedString(readProperty(readProperty(value, "constructor") || {}, "name"), state);
|
|
484
|
+
const result = {
|
|
485
|
+
message,
|
|
486
|
+
...name ? { name } : {}
|
|
487
|
+
};
|
|
488
|
+
const code = publicError?.code ? boundedString(publicError.code, state) : scalarProperty(value, "code", state) ?? (typeof why === "string" ? boundedString(name, state) : void 0);
|
|
489
|
+
const fix = boundedString(readProperty(value, "fix"), state);
|
|
490
|
+
const docs = boundedString(readProperty(value, "docs"), state);
|
|
491
|
+
const requestId = publicError?.requestId ? boundedString(publicError.requestId, state) : boundedString(readProperty(value, "requestId"), state);
|
|
492
|
+
const status = scalarProperty(value, "status", state);
|
|
493
|
+
const statusCode = scalarProperty(value, "statusCode", state);
|
|
494
|
+
const stack = state.includeStack ? boundedString(readProperty(value, "stack"), state) : void 0;
|
|
495
|
+
if (code !== void 0) result.code = code;
|
|
496
|
+
if (fix) result.fix = fix;
|
|
497
|
+
if (docs) result.docs = docs;
|
|
498
|
+
if (requestId) result.requestId = requestId;
|
|
499
|
+
if (stack) result.stack = stack;
|
|
500
|
+
if (status !== void 0) result.status = status;
|
|
501
|
+
if (statusCode !== void 0) result.statusCode = statusCode;
|
|
502
|
+
const cause = readProperty(value, "cause");
|
|
503
|
+
const normalizedCause = cause === void 0 ? void 0 : normalizeError(cause, state, depth + 1);
|
|
504
|
+
if (normalizedCause) result.cause = normalizedCause;
|
|
505
|
+
const normalizedErrors = errorChildren(readProperty(value, "errors"), state.remainingNodes)?.flatMap((error) => {
|
|
506
|
+
const normalized = normalizeError(error, state, depth + 1);
|
|
507
|
+
return normalized ? [normalized] : [];
|
|
508
|
+
});
|
|
509
|
+
if (normalizedErrors?.length) result.errors = normalizedErrors;
|
|
510
|
+
const details = publicError?.details ? normalizeDetails(publicError.details, state, depth + 1) : void 0;
|
|
511
|
+
if (details) result.details = details;
|
|
512
|
+
const sources = errorChildren(readProperty(value, "sources"), state.remainingNodes)?.flatMap((source) => {
|
|
513
|
+
state.remainingNodes -= 1;
|
|
514
|
+
const normalized = boundedString(source, state);
|
|
515
|
+
return normalized ? [normalized] : [];
|
|
516
|
+
});
|
|
517
|
+
if (sources?.length) result.sources = sources;
|
|
518
|
+
return result;
|
|
519
|
+
} finally {
|
|
520
|
+
state.ancestors.delete(value);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
/** Formats bounded developer diagnostics without exposing causes or stacks. */
|
|
524
|
+
function formatRuntimeDiagnosticError(error) {
|
|
525
|
+
const normalized = normalizeRuntimeDiagnosticError(error);
|
|
526
|
+
if (normalized.code === void 0 && !normalized.fix && !normalized.docs && !normalized.sources?.length) return normalized.message;
|
|
527
|
+
return formatDiagnostic(new Diagnostic({
|
|
528
|
+
code: normalized.code === void 0 ? normalized.name || "Error" : String(normalized.code),
|
|
529
|
+
docs: normalized.docs,
|
|
530
|
+
fix: normalized.fix,
|
|
531
|
+
sources: normalized.sources ? [...normalized.sources] : void 0,
|
|
532
|
+
why: normalized.message
|
|
533
|
+
}));
|
|
534
|
+
}
|
|
535
|
+
function normalizeRuntimeDiagnosticError(error, options = {}) {
|
|
536
|
+
const maxDepth = options.maxDepth ?? 4;
|
|
537
|
+
const maxErrors = options.maxErrors ?? 8;
|
|
538
|
+
const maxStringLength = options.maxStringLength ?? 4096;
|
|
539
|
+
if (!Number.isInteger(maxDepth) || maxDepth < 0) throw runtimeErrorDiagnostics.RUNTIME_R0001({ message: "[vitehub:runtime] Diagnostic error maxDepth must be a non-negative integer." });
|
|
540
|
+
if (!Number.isInteger(maxErrors) || maxErrors < 1) throw runtimeErrorDiagnostics.RUNTIME_R0002({ message: "[vitehub:runtime] Diagnostic error maxErrors must be a positive integer." });
|
|
541
|
+
if (!Number.isInteger(maxStringLength) || maxStringLength < 64) throw runtimeErrorDiagnostics.RUNTIME_R0003({ message: "[vitehub:runtime] Diagnostic error maxStringLength must be an integer of at least 64." });
|
|
542
|
+
return normalizeError(error, {
|
|
543
|
+
ancestors: /* @__PURE__ */ new Set(),
|
|
544
|
+
includeStack: options.includeStack === true,
|
|
545
|
+
maxDepth,
|
|
546
|
+
maxStringLength,
|
|
547
|
+
remainingNodes: maxErrors + 1,
|
|
548
|
+
remainingStringLength: maxStringLength * (maxErrors + 1)
|
|
549
|
+
}, 0);
|
|
550
|
+
}
|
|
551
|
+
//#endregion
|
|
552
|
+
//#region src/result.ts
|
|
553
|
+
/**
|
|
554
|
+
* Prepares a recognized diagnostic for a result, keeping its metadata in memory.
|
|
555
|
+
* Reuses mutable diagnostics; copies diagnostics whose name or serializer cannot be replaced.
|
|
556
|
+
* Sets name to code to match the result contract, including diagnostics renamed by their owner.
|
|
557
|
+
* The caller owns code allowlisting and the public text. JSON includes only the public fields.
|
|
558
|
+
*/
|
|
559
|
+
function toResultError(error) {
|
|
560
|
+
const canReplace = (key) => {
|
|
561
|
+
const descriptor = Object.getOwnPropertyDescriptor(error, key);
|
|
562
|
+
return descriptor ? descriptor.configurable === true : Object.isExtensible(error);
|
|
563
|
+
};
|
|
564
|
+
const result = canReplace("name") && canReplace("toJSON") ? error : new Diagnostic({
|
|
565
|
+
code: error.code,
|
|
566
|
+
why: error.why,
|
|
567
|
+
fix: error.fix,
|
|
568
|
+
docs: error.docs,
|
|
569
|
+
cause: error.cause,
|
|
570
|
+
data: error.data,
|
|
571
|
+
sources: error.sources
|
|
572
|
+
});
|
|
573
|
+
if (result !== error) result.stack = error.stack;
|
|
574
|
+
Object.defineProperty(result, "name", {
|
|
575
|
+
configurable: true,
|
|
576
|
+
value: result.code,
|
|
577
|
+
writable: true
|
|
578
|
+
});
|
|
579
|
+
Object.defineProperty(result, "toJSON", {
|
|
580
|
+
configurable: true,
|
|
581
|
+
value: () => ({
|
|
582
|
+
code: result.code,
|
|
583
|
+
docs: result.docs,
|
|
584
|
+
fix: result.fix,
|
|
585
|
+
name: result.name,
|
|
586
|
+
why: result.why
|
|
587
|
+
})
|
|
588
|
+
});
|
|
589
|
+
return result;
|
|
590
|
+
}
|
|
591
|
+
function defineErrors(options) {
|
|
592
|
+
const diagnostics = defineDiagnostics({
|
|
593
|
+
codes: options.codes,
|
|
594
|
+
docsBase: options.docs
|
|
595
|
+
});
|
|
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
|
+
}
|
|
602
|
+
return catalog;
|
|
603
|
+
}
|
|
604
|
+
//#endregion
|
|
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."
|
|
616
|
+
}
|
|
617
|
+
}
|
|
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))
|
|
652
|
+
};
|
|
653
|
+
return held;
|
|
654
|
+
}
|
|
655
|
+
return {
|
|
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
|
+
});
|
|
671
|
+
},
|
|
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;
|
|
709
|
+
},
|
|
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;
|
|
715
|
+
},
|
|
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 };
|
|
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);
|
|
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
|
+
});
|
|
845
|
+
}
|
|
846
|
+
//#endregion
|
|
847
|
+
//#region src/response.ts
|
|
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");
|
|
857
|
+
function streamBody(read) {
|
|
858
|
+
let reader;
|
|
859
|
+
const cleanup = async (reason, cancel = false) => {
|
|
860
|
+
const current = reader;
|
|
861
|
+
reader = void 0;
|
|
862
|
+
if (!current) return;
|
|
863
|
+
try {
|
|
864
|
+
if (cancel) await current.cancel(reason);
|
|
865
|
+
} finally {
|
|
866
|
+
current.releaseLock();
|
|
867
|
+
}
|
|
868
|
+
};
|
|
869
|
+
return new ReadableStream({
|
|
870
|
+
async pull(controller) {
|
|
871
|
+
reader ??= read().getReader();
|
|
872
|
+
try {
|
|
873
|
+
const chunk = await reader.read();
|
|
874
|
+
if (chunk.done) {
|
|
875
|
+
await cleanup();
|
|
876
|
+
controller.close();
|
|
877
|
+
} else controller.enqueue(chunk.value);
|
|
878
|
+
} catch (error) {
|
|
879
|
+
await cleanup(error, true);
|
|
880
|
+
throw error;
|
|
881
|
+
}
|
|
882
|
+
},
|
|
883
|
+
async cancel(reason) {
|
|
884
|
+
await cleanup(reason, true);
|
|
885
|
+
}
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
function getBlobMethods(value) {
|
|
889
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return void 0;
|
|
890
|
+
try {
|
|
891
|
+
if (typeof blobTypeGetter !== "function" || typeof blobStreamMethod !== "function") return void 0;
|
|
892
|
+
const type = String(Reflect.apply(blobTypeGetter, value, []));
|
|
893
|
+
const body = () => streamBody(() => Reflect.apply(blobStreamMethod, value, []));
|
|
894
|
+
return {
|
|
895
|
+
type,
|
|
896
|
+
body
|
|
897
|
+
};
|
|
898
|
+
} catch {
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
const arrayBufferByteLengthGetter = /* @__PURE__ */ prototypeGetter(ArrayBuffer, "byteLength");
|
|
903
|
+
function isArrayBufferValue(value) {
|
|
904
|
+
if (!isRuntimeObject(value)) return false;
|
|
905
|
+
try {
|
|
906
|
+
if (typeof arrayBufferByteLengthGetter !== "function") return false;
|
|
907
|
+
arrayBufferByteLengthGetter.call(value);
|
|
908
|
+
return true;
|
|
909
|
+
} catch {
|
|
910
|
+
return false;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
/** Normalize a primitive value into the native Web Response contract. */
|
|
914
|
+
function toResponse(value) {
|
|
915
|
+
if (isResponse(value)) return value;
|
|
916
|
+
if (value === void 0) return new Response(null, { status: 204 });
|
|
917
|
+
if (typeof value === "string" || value instanceof Blob || isArrayBufferValue(value) || ArrayBuffer.isView(value)) return new Response(value);
|
|
918
|
+
const blobMethods = getBlobMethods(value);
|
|
919
|
+
if (blobMethods) return new Response(blobMethods.body(), blobMethods.type ? { headers: { "content-type": blobMethods.type } } : void 0);
|
|
920
|
+
return new Response(JSON.stringify(value), { headers: { "content-type": "application/json; charset=utf-8" } });
|
|
921
|
+
}
|
|
922
|
+
/** Recognize Responses created by another realm from their standard tag and surface. */
|
|
923
|
+
function isResponse(value) {
|
|
924
|
+
if (value instanceof Response) return true;
|
|
925
|
+
if (!isRuntimeObject(value)) return false;
|
|
926
|
+
try {
|
|
927
|
+
if (Object.prototype.toString.call(value) !== "[object Response]") return false;
|
|
928
|
+
const headers = Object.getOwnPropertyDescriptor(Response.prototype, "headers")?.get?.call(value);
|
|
929
|
+
if (!headers) return false;
|
|
930
|
+
Array.from(Headers.prototype.entries.call(headers));
|
|
931
|
+
return true;
|
|
932
|
+
} catch {
|
|
933
|
+
return false;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
/** Convert a native Response into a JSON-safe record. The body is fully buffered. */
|
|
937
|
+
async function serializeResponse(response) {
|
|
938
|
+
const isNull = response.body === null;
|
|
939
|
+
return {
|
|
940
|
+
body: {
|
|
941
|
+
data: bytesToBase64(new Uint8Array(await response.arrayBuffer())),
|
|
942
|
+
isNull,
|
|
943
|
+
encoding: "base64",
|
|
944
|
+
mediaType: response.headers.get("content-type") || "application/octet-stream"
|
|
945
|
+
},
|
|
946
|
+
headers: Array.from(response.headers, ([name, value]) => [name, value]),
|
|
947
|
+
status: response.status,
|
|
948
|
+
statusText: response.statusText,
|
|
949
|
+
...response.type === "opaqueredirect" ? { url: response.url } : {},
|
|
950
|
+
...response.type === "error" || response.type === "opaque" || response.type === "opaqueredirect" ? { type: response.type } : {}
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
/** Reconstruct a native Response from a durable response record. */
|
|
954
|
+
function deserializeResponse(value) {
|
|
955
|
+
if (!isSerializedResponse(value)) throw runtimeErrorDiagnostics.RUNTIME_SERIALIZED_RESPONSE_INVALID();
|
|
956
|
+
if (value.type !== void 0) return createStatusZeroResponse(value.type, value.url);
|
|
957
|
+
const bytes = base64ToBytes(value.body.data);
|
|
958
|
+
const body = value.body.isNull === true || [
|
|
959
|
+
204,
|
|
960
|
+
205,
|
|
961
|
+
304
|
|
962
|
+
].includes(value.status) && bytes.length === 0 ? null : bytes;
|
|
963
|
+
return new Response(body, {
|
|
964
|
+
headers: value.headers.map(([name, headerValue]) => [name, headerValue]),
|
|
965
|
+
status: value.status,
|
|
966
|
+
statusText: value.statusText
|
|
967
|
+
});
|
|
968
|
+
}
|
|
969
|
+
function isSerializedResponse(value) {
|
|
970
|
+
if (!isRuntimeObject(value)) return false;
|
|
971
|
+
const record = value;
|
|
972
|
+
if (!isRuntimeObject(record.body)) return false;
|
|
973
|
+
const body = record.body;
|
|
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;
|
|
976
|
+
if (body.isNull === true && body.data !== "") return false;
|
|
977
|
+
if (record.url !== void 0 && typeof record.url !== "string") return false;
|
|
978
|
+
if (record.type !== void 0 && record.type !== "error" && record.type !== "opaque" && record.type !== "opaqueredirect") return false;
|
|
979
|
+
if (record.type !== void 0) {
|
|
980
|
+
if (record.type !== "opaqueredirect" && record.url !== void 0) return false;
|
|
981
|
+
return record.status === 0 && record.statusText === "" && Array.isArray(record.headers) && record.headers.length === 0 && body.isNull === true && body.data === "";
|
|
982
|
+
}
|
|
983
|
+
if (record.url !== void 0) 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;
|
|
986
|
+
if ([
|
|
987
|
+
204,
|
|
988
|
+
205,
|
|
989
|
+
304
|
|
990
|
+
].includes(record.status) && (/[^\t\n\f\r ]/.test(body.data) || body.isNull === false)) return false;
|
|
991
|
+
const headers = record.headers;
|
|
992
|
+
if (!isBase64(body.data)) return false;
|
|
993
|
+
try {
|
|
994
|
+
new Response(null, {
|
|
995
|
+
headers: headers.map(([name, headerValue]) => [name, headerValue]),
|
|
996
|
+
status: record.status,
|
|
997
|
+
statusText: record.statusText
|
|
998
|
+
});
|
|
999
|
+
} catch {
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
return true;
|
|
1003
|
+
}
|
|
1004
|
+
function isSerializedHeaderEntry(value) {
|
|
1005
|
+
return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "string";
|
|
1006
|
+
}
|
|
1007
|
+
function isSerializedHeaderEntries(value) {
|
|
1008
|
+
if (!Array.isArray(value)) return false;
|
|
1009
|
+
for (let index = 0; index < value.length; index++) if (!isSerializedHeaderEntry(value[index])) return false;
|
|
1010
|
+
return true;
|
|
1011
|
+
}
|
|
1012
|
+
function isBase64(value) {
|
|
1013
|
+
const compact = value.replace(/[\t\n\f\r ]/g, "");
|
|
1014
|
+
const unpadded = compact.length % 4 === 0 ? compact.replace(/={1,2}$/, "") : compact;
|
|
1015
|
+
return unpadded.length % 4 !== 1 && !/[^A-Za-z0-9+/]/.test(unpadded);
|
|
1016
|
+
}
|
|
1017
|
+
function bytesToBase64(bytes) {
|
|
1018
|
+
if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
|
1019
|
+
let binary = "";
|
|
1020
|
+
for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
|
|
1021
|
+
return btoa(binary);
|
|
1022
|
+
}
|
|
1023
|
+
function base64ToBytes(value) {
|
|
1024
|
+
if (typeof Buffer !== "undefined") return Buffer.from(value, "base64");
|
|
1025
|
+
const binary = atob(value);
|
|
1026
|
+
const bytes = new Uint8Array(binary.length);
|
|
1027
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
1028
|
+
return bytes;
|
|
1029
|
+
}
|
|
1030
|
+
function createStatusZeroResponse(type, url = "") {
|
|
1031
|
+
const response = Response.error();
|
|
1032
|
+
if (type !== "error") Object.defineProperties(response, {
|
|
1033
|
+
type: {
|
|
1034
|
+
value: type,
|
|
1035
|
+
enumerable: true
|
|
1036
|
+
},
|
|
1037
|
+
url: {
|
|
1038
|
+
value: type === "opaqueredirect" ? url : "",
|
|
1039
|
+
enumerable: true
|
|
1040
|
+
},
|
|
1041
|
+
clone: { value: () => createStatusZeroResponse(type, url) }
|
|
1042
|
+
});
|
|
1043
|
+
return response;
|
|
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
|
+
}
|
|
1125
|
+
//#endregion
|
|
1126
|
+
//#region src/index.ts
|
|
1127
|
+
function captureWebAssemblyModule() {
|
|
1128
|
+
const namespace = Object.getOwnPropertyDescriptor(globalThis, "WebAssembly")?.value;
|
|
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();
|
|
1136
|
+
const noExecutionAuthority = /* @__PURE__ */ Object.freeze({
|
|
1137
|
+
credentials: "none",
|
|
1138
|
+
environment: "none",
|
|
1139
|
+
filesystem: /* @__PURE__ */ Object.freeze({
|
|
1140
|
+
access: "none",
|
|
1141
|
+
scope: "none"
|
|
1142
|
+
}),
|
|
1143
|
+
isolation: "none",
|
|
1144
|
+
network: "none",
|
|
1145
|
+
processes: "none"
|
|
1146
|
+
});
|
|
1147
|
+
const unknownExecutionAuthority = /* @__PURE__ */ Object.freeze({
|
|
1148
|
+
credentials: "unknown",
|
|
1149
|
+
environment: "unknown",
|
|
1150
|
+
filesystem: /* @__PURE__ */ Object.freeze({
|
|
1151
|
+
access: "unknown",
|
|
1152
|
+
scope: "unknown"
|
|
1153
|
+
}),
|
|
1154
|
+
isolation: "unknown",
|
|
1155
|
+
network: "unknown",
|
|
1156
|
+
processes: "unknown"
|
|
1157
|
+
});
|
|
1158
|
+
function isExecutionAuthority(value) {
|
|
1159
|
+
return inspectExecutionAuthority(value) !== void 0;
|
|
1160
|
+
}
|
|
1161
|
+
function inspectExecutionAuthority(value) {
|
|
1162
|
+
try {
|
|
1163
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1164
|
+
const authority = value;
|
|
1165
|
+
const filesystem = authority.filesystem;
|
|
1166
|
+
if (!filesystem || typeof filesystem !== "object" || Array.isArray(filesystem)) return void 0;
|
|
1167
|
+
const files = filesystem;
|
|
1168
|
+
const credentials = authority.credentials;
|
|
1169
|
+
const environment = authority.environment;
|
|
1170
|
+
const access = files.access;
|
|
1171
|
+
const scope = files.scope;
|
|
1172
|
+
const isolation = authority.isolation;
|
|
1173
|
+
const network = authority.network;
|
|
1174
|
+
const processes = authority.processes;
|
|
1175
|
+
if (!(typeof credentials === "string" && [
|
|
1176
|
+
"ambient",
|
|
1177
|
+
"none",
|
|
1178
|
+
"provisioned",
|
|
1179
|
+
"unknown"
|
|
1180
|
+
].includes(credentials) && typeof environment === "string" && [
|
|
1181
|
+
"ambient",
|
|
1182
|
+
"none",
|
|
1183
|
+
"selected",
|
|
1184
|
+
"unknown"
|
|
1185
|
+
].includes(environment) && typeof access === "string" && [
|
|
1186
|
+
"none",
|
|
1187
|
+
"read-only",
|
|
1188
|
+
"read-write",
|
|
1189
|
+
"unknown"
|
|
1190
|
+
].includes(access) && typeof scope === "string" && [
|
|
1191
|
+
"host",
|
|
1192
|
+
"none",
|
|
1193
|
+
"sandbox",
|
|
1194
|
+
"unknown",
|
|
1195
|
+
"workspace"
|
|
1196
|
+
].includes(scope) && typeof isolation === "string" && [
|
|
1197
|
+
"container",
|
|
1198
|
+
"microvm",
|
|
1199
|
+
"none",
|
|
1200
|
+
"process",
|
|
1201
|
+
"unknown"
|
|
1202
|
+
].includes(isolation) && typeof network === "string" && [
|
|
1203
|
+
"none",
|
|
1204
|
+
"restricted",
|
|
1205
|
+
"unrestricted",
|
|
1206
|
+
"unknown"
|
|
1207
|
+
].includes(network) && typeof processes === "string" && [
|
|
1208
|
+
"arbitrary",
|
|
1209
|
+
"none",
|
|
1210
|
+
"restricted",
|
|
1211
|
+
"unknown"
|
|
1212
|
+
].includes(processes))) return void 0;
|
|
1213
|
+
return {
|
|
1214
|
+
authority: {
|
|
1215
|
+
credentials,
|
|
1216
|
+
environment,
|
|
1217
|
+
filesystem: {
|
|
1218
|
+
access,
|
|
1219
|
+
scope
|
|
1220
|
+
},
|
|
1221
|
+
isolation,
|
|
1222
|
+
network,
|
|
1223
|
+
processes
|
|
1224
|
+
},
|
|
1225
|
+
filesystem
|
|
1226
|
+
};
|
|
1227
|
+
} catch {
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
const canonicalExecutionAuthorities = /* @__PURE__ */ new WeakSet([noExecutionAuthority, unknownExecutionAuthority]);
|
|
1232
|
+
function normalizeExecutionAuthority(value) {
|
|
1233
|
+
if (isRuntimeObject(value) && canonicalExecutionAuthorities.has(value)) return value;
|
|
1234
|
+
const inspected = inspectExecutionAuthority(value);
|
|
1235
|
+
if (!inspected) throw runtimeErrorDiagnostics.RUNTIME_R0007({ message: "[vitehub] Invalid execution authority descriptor." });
|
|
1236
|
+
const authority = Object.freeze({
|
|
1237
|
+
...inspected.authority,
|
|
1238
|
+
filesystem: Object.freeze({ ...inspected.authority.filesystem })
|
|
1239
|
+
});
|
|
1240
|
+
canonicalExecutionAuthorities.add(authority);
|
|
1241
|
+
return authority;
|
|
1242
|
+
}
|
|
1243
|
+
function timestamp(value) {
|
|
1244
|
+
if (value instanceof Date) return value.toISOString();
|
|
1245
|
+
if (typeof value === "string") return value;
|
|
1246
|
+
if (isRuntimeObject(value)) try {
|
|
1247
|
+
return Reflect.apply(Date.prototype.toISOString, value, []);
|
|
1248
|
+
} catch (error) {
|
|
1249
|
+
if (!(error instanceof TypeError)) throw error;
|
|
1250
|
+
}
|
|
1251
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
1252
|
+
}
|
|
1253
|
+
function normalizedTraceActivity(activity) {
|
|
1254
|
+
if (!activity || typeof activity !== "object") return;
|
|
1255
|
+
try {
|
|
1256
|
+
if (Array.isArray(activity)) return;
|
|
1257
|
+
const owner = Object.getOwnPropertyDescriptor(activity, "owner");
|
|
1258
|
+
const phase = Object.getOwnPropertyDescriptor(activity, "phase");
|
|
1259
|
+
if (!owner || !("value" in owner) || !phase || !("value" in phase)) return;
|
|
1260
|
+
if (owner.value !== "agent" && owner.value !== "vitehub") return;
|
|
1261
|
+
if (![
|
|
1262
|
+
"delivery",
|
|
1263
|
+
"execution",
|
|
1264
|
+
"setup",
|
|
1265
|
+
"teardown"
|
|
1266
|
+
].includes(phase.value)) return;
|
|
1267
|
+
return {
|
|
1268
|
+
owner: owner.value,
|
|
1269
|
+
phase: phase.value
|
|
1270
|
+
};
|
|
1271
|
+
} catch {
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
function reflectedMapEntries(value) {
|
|
1276
|
+
if (!value || typeof value !== "object") return;
|
|
1277
|
+
try {
|
|
1278
|
+
return Array.from(Map.prototype.entries.call(value));
|
|
1279
|
+
} catch {
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
function reflectedSetValues(value) {
|
|
1284
|
+
if (!value || typeof value !== "object") return;
|
|
1285
|
+
try {
|
|
1286
|
+
return Array.from(Set.prototype.values.call(value));
|
|
1287
|
+
} catch {
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
function isCryptoKey(value) {
|
|
1292
|
+
if (!value || typeof value !== "object") return false;
|
|
1293
|
+
const CryptoKeyConstructor = Object.getOwnPropertyDescriptor(globalThis, "CryptoKey")?.value;
|
|
1294
|
+
return typeof CryptoKeyConstructor === "function" && value instanceof CryptoKeyConstructor;
|
|
1295
|
+
}
|
|
1296
|
+
function isWebAssemblyModule(value) {
|
|
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;
|
|
1301
|
+
try {
|
|
1302
|
+
if (typeof exports !== "function") return false;
|
|
1303
|
+
Reflect.apply(exports, constructor, [value]);
|
|
1304
|
+
return true;
|
|
1305
|
+
} catch {
|
|
1306
|
+
return false;
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
function captureFunctionToString() {
|
|
1310
|
+
return Function.prototype.toString;
|
|
1311
|
+
}
|
|
1312
|
+
const intrinsicFunctionToString = /* @__PURE__ */ captureFunctionToString();
|
|
1313
|
+
function checkNativeFunctionToString() {
|
|
1314
|
+
try {
|
|
1315
|
+
if (Object.prototype.hasOwnProperty.call(intrinsicFunctionToString, "prototype")) return false;
|
|
1316
|
+
if (intrinsicFunctionToString.name !== "toString" || intrinsicFunctionToString.length !== 1) return false;
|
|
1317
|
+
if (intrinsicFunctionToString.call(intrinsicFunctionToString).replace(/\s+/g, " ") !== "function toString() { [native code] }") return false;
|
|
1318
|
+
function probe() {
|
|
1319
|
+
return 1;
|
|
1320
|
+
}
|
|
1321
|
+
if (intrinsicFunctionToString.call(probe) !== "function probe() { return 1 }") return false;
|
|
1322
|
+
const namedProbes = [
|
|
1323
|
+
function ArrayBuffer() {},
|
|
1324
|
+
function SharedArrayBuffer() {},
|
|
1325
|
+
function DataView() {},
|
|
1326
|
+
function Memory() {}
|
|
1327
|
+
];
|
|
1328
|
+
for (const namedProbe of namedProbes) if (intrinsicFunctionToString.call(namedProbe).includes("[native code]")) return false;
|
|
1329
|
+
const getterProbe = Object.getOwnPropertyDescriptor({ get byteLength() {
|
|
1330
|
+
return 0;
|
|
1331
|
+
} }, "byteLength")?.get;
|
|
1332
|
+
if (!getterProbe || intrinsicFunctionToString.call(getterProbe).includes("[native code]")) return false;
|
|
1333
|
+
try {
|
|
1334
|
+
intrinsicFunctionToString.call(null);
|
|
1335
|
+
return false;
|
|
1336
|
+
} catch {
|
|
1337
|
+
return true;
|
|
1338
|
+
}
|
|
1339
|
+
} catch {
|
|
1340
|
+
return false;
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
const nativeFunctionToString = /* @__PURE__ */ checkNativeFunctionToString();
|
|
1344
|
+
function isNativeBufferOperation(value, name) {
|
|
1345
|
+
if (!nativeFunctionToString || typeof value !== "function") return false;
|
|
1346
|
+
try {
|
|
1347
|
+
return intrinsicFunctionToString.call(value).replace(/\s+/g, " ") === `function ${name}() { [native code] }`;
|
|
1348
|
+
} catch {
|
|
1349
|
+
return false;
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
function captureSharedBufferByteLength() {
|
|
1353
|
+
try {
|
|
1354
|
+
let sample;
|
|
1355
|
+
const constructor = Object.getOwnPropertyDescriptor(globalThis, "SharedArrayBuffer")?.value;
|
|
1356
|
+
if (isNativeBufferOperation(constructor, "SharedArrayBuffer")) sample = Reflect.construct(constructor, [0]);
|
|
1357
|
+
else {
|
|
1358
|
+
const namespace = Object.getOwnPropertyDescriptor(globalThis, "WebAssembly")?.value;
|
|
1359
|
+
if (!isRuntimeObject(namespace)) return;
|
|
1360
|
+
const memoryConstructor = Object.getOwnPropertyDescriptor(namespace, "Memory")?.value;
|
|
1361
|
+
if (!isNativeBufferOperation(memoryConstructor, "Memory")) return;
|
|
1362
|
+
const memory = Reflect.construct(memoryConstructor, [{
|
|
1363
|
+
initial: 0,
|
|
1364
|
+
maximum: 1,
|
|
1365
|
+
shared: true
|
|
1366
|
+
}]);
|
|
1367
|
+
const memoryBuffer = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(memory), "buffer")?.get;
|
|
1368
|
+
if (!isNativeBufferOperation(memoryBuffer, "get buffer")) return;
|
|
1369
|
+
sample = memoryBuffer.call(memory);
|
|
1370
|
+
}
|
|
1371
|
+
if (!isRuntimeObject(sample)) return;
|
|
1372
|
+
const getter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(sample), "byteLength")?.get;
|
|
1373
|
+
if (!isNativeBufferOperation(getter, "get byteLength")) return;
|
|
1374
|
+
if (getter.call(sample) !== 0) return;
|
|
1375
|
+
const receiverProbes = [{}, Object.create(null)];
|
|
1376
|
+
for (const receiver of receiverProbes) try {
|
|
1377
|
+
getter.call(receiver);
|
|
1378
|
+
return;
|
|
1379
|
+
} catch {}
|
|
1380
|
+
return getter;
|
|
1381
|
+
} catch {
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
function captureOrdinaryBufferOperations() {
|
|
1386
|
+
try {
|
|
1387
|
+
const arrayBuffer = Object.getOwnPropertyDescriptor(globalThis, "ArrayBuffer")?.value;
|
|
1388
|
+
const dataView = Object.getOwnPropertyDescriptor(globalThis, "DataView")?.value;
|
|
1389
|
+
if (!isNativeBufferOperation(arrayBuffer, "ArrayBuffer") || !isNativeBufferOperation(dataView, "DataView")) return;
|
|
1390
|
+
const sample = Reflect.construct(arrayBuffer, [0]);
|
|
1391
|
+
const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(sample), "byteLength")?.get;
|
|
1392
|
+
if (!isNativeBufferOperation(byteLength, "get byteLength") || byteLength.call(sample) !== 0) return;
|
|
1393
|
+
Reflect.construct(dataView, [
|
|
1394
|
+
sample,
|
|
1395
|
+
0,
|
|
1396
|
+
0
|
|
1397
|
+
]);
|
|
1398
|
+
try {
|
|
1399
|
+
Reflect.construct(dataView, [
|
|
1400
|
+
{},
|
|
1401
|
+
0,
|
|
1402
|
+
0
|
|
1403
|
+
]);
|
|
1404
|
+
return;
|
|
1405
|
+
} catch {
|
|
1406
|
+
return {
|
|
1407
|
+
byteLength,
|
|
1408
|
+
dataView
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
} catch {
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
const sharedBufferByteLength = /* @__PURE__ */ captureSharedBufferByteLength();
|
|
1416
|
+
const ordinaryBufferOperations = /* @__PURE__ */ captureOrdinaryBufferOperations();
|
|
1417
|
+
function isSharedArrayBuffer(value) {
|
|
1418
|
+
if (!value || typeof value !== "object") return false;
|
|
1419
|
+
if (sharedBufferByteLength) try {
|
|
1420
|
+
if (ordinaryBufferOperations) Reflect.construct(ordinaryBufferOperations.dataView, [
|
|
1421
|
+
value,
|
|
1422
|
+
0,
|
|
1423
|
+
0
|
|
1424
|
+
]);
|
|
1425
|
+
return typeof sharedBufferByteLength.call(value) === "number";
|
|
1426
|
+
} catch {
|
|
1427
|
+
return false;
|
|
1428
|
+
}
|
|
1429
|
+
if (!ordinaryBufferOperations) try {
|
|
1430
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1431
|
+
if (prototype === Object.prototype) return false;
|
|
1432
|
+
const tag = Object.getOwnPropertyDescriptor(prototype, Symbol.toStringTag)?.value;
|
|
1433
|
+
const byteLength = Object.getOwnPropertyDescriptor(prototype, "byteLength")?.get;
|
|
1434
|
+
return tag === "SharedArrayBuffer" && typeof byteLength === "function";
|
|
1435
|
+
} catch {
|
|
1436
|
+
return true;
|
|
1437
|
+
}
|
|
1438
|
+
try {
|
|
1439
|
+
Reflect.construct(ordinaryBufferOperations.dataView, [
|
|
1440
|
+
value,
|
|
1441
|
+
0,
|
|
1442
|
+
0
|
|
1443
|
+
]);
|
|
1444
|
+
try {
|
|
1445
|
+
ordinaryBufferOperations.byteLength.call(value);
|
|
1446
|
+
return false;
|
|
1447
|
+
} catch {
|
|
1448
|
+
return true;
|
|
1449
|
+
}
|
|
1450
|
+
} catch {
|
|
1451
|
+
return false;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
function containsSharedArrayBuffer(value, seen = /* @__PURE__ */ new Set()) {
|
|
1455
|
+
if (!value || typeof value !== "object") return false;
|
|
1456
|
+
if (isSharedArrayBuffer(value)) return true;
|
|
1457
|
+
const WebAssemblyMemory = globalThis.WebAssembly?.Memory;
|
|
1458
|
+
if (WebAssemblyMemory && value instanceof WebAssemblyMemory) return isSharedArrayBuffer(value.buffer);
|
|
1459
|
+
if (seen.has(value)) return false;
|
|
1460
|
+
seen.add(value);
|
|
1461
|
+
if (ArrayBuffer.isView(value)) return containsSharedArrayBuffer(value.buffer, seen);
|
|
1462
|
+
const mapEntries = reflectedMapEntries(value);
|
|
1463
|
+
if (mapEntries) return mapEntries.some(([key, entry]) => containsSharedArrayBuffer(key, seen) || containsSharedArrayBuffer(entry, seen));
|
|
1464
|
+
const setValues = reflectedSetValues(value);
|
|
1465
|
+
if (setValues) return setValues.some((entry) => containsSharedArrayBuffer(entry, seen));
|
|
1466
|
+
return Reflect.ownKeys(value).some((key) => {
|
|
1467
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1468
|
+
return descriptor !== void 0 && "value" in descriptor && containsSharedArrayBuffer(descriptor.value, seen);
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
function reflectedRegExpState(value) {
|
|
1472
|
+
if (!value || typeof value !== "object") return;
|
|
1473
|
+
try {
|
|
1474
|
+
const source = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get?.call(value);
|
|
1475
|
+
const flags = Object.getOwnPropertyDescriptor(RegExp.prototype, "flags")?.get?.call(value);
|
|
1476
|
+
const lastIndex = Reflect.get(value, "lastIndex");
|
|
1477
|
+
if (typeof source !== "string" || typeof flags !== "string" || typeof lastIndex !== "number") return;
|
|
1478
|
+
return {
|
|
1479
|
+
flags,
|
|
1480
|
+
lastIndex,
|
|
1481
|
+
source
|
|
1482
|
+
};
|
|
1483
|
+
} catch {
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
function reflectedArrayBufferViewState(value) {
|
|
1488
|
+
if (!ArrayBuffer.isView(value)) return;
|
|
1489
|
+
try {
|
|
1490
|
+
const bufferConstructor = Object.getOwnPropertyDescriptor(globalThis, "Buffer")?.value ?? globalThis.Buffer;
|
|
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;
|
|
1493
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
1494
|
+
if (isNodeBuffer) {
|
|
1495
|
+
const byteLength = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength")?.get?.call(value);
|
|
1496
|
+
return typeof byteLength === "number" ? {
|
|
1497
|
+
byteLength,
|
|
1498
|
+
kind: "Buffer"
|
|
1499
|
+
} : void 0;
|
|
1500
|
+
}
|
|
1501
|
+
const typedArrayTag = Object.getOwnPropertyDescriptor(typedArrayPrototype, Symbol.toStringTag)?.get?.call(value);
|
|
1502
|
+
if (typeof typedArrayTag === "string") {
|
|
1503
|
+
const byteLength = Object.getOwnPropertyDescriptor(typedArrayPrototype, "byteLength")?.get?.call(value);
|
|
1504
|
+
return typeof byteLength === "number" ? {
|
|
1505
|
+
byteLength,
|
|
1506
|
+
kind: typedArrayTag
|
|
1507
|
+
} : void 0;
|
|
1508
|
+
}
|
|
1509
|
+
const dataViewByteLength = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength")?.get?.call(value);
|
|
1510
|
+
return typeof dataViewByteLength === "number" ? {
|
|
1511
|
+
byteLength: dataViewByteLength,
|
|
1512
|
+
kind: "DataView"
|
|
1513
|
+
} : void 0;
|
|
1514
|
+
} catch {
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
function reflectedBlobState(value) {
|
|
1519
|
+
const BlobConstructor = globalThis.Blob;
|
|
1520
|
+
if (typeof BlobConstructor !== "function" || !(value instanceof BlobConstructor)) return;
|
|
1521
|
+
try {
|
|
1522
|
+
const FileConstructor = globalThis.File;
|
|
1523
|
+
const file = typeof FileConstructor === "function" && value instanceof FileConstructor ? value : void 0;
|
|
1524
|
+
const intrinsic = file ? new FileConstructor([], "") : new BlobConstructor([]);
|
|
1525
|
+
const size = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "size")?.get?.call(value);
|
|
1526
|
+
const type = Object.getOwnPropertyDescriptor(BlobConstructor.prototype, "type")?.get?.call(value);
|
|
1527
|
+
if (typeof size !== "number" || typeof type !== "string") return;
|
|
1528
|
+
const state = {
|
|
1529
|
+
intrinsicSymbols: new Set(Reflect.ownKeys(intrinsic).filter((key) => typeof key === "symbol" && Object.getOwnPropertyDescriptor(intrinsic, key)?.enumerable === true)),
|
|
1530
|
+
size,
|
|
1531
|
+
type
|
|
1532
|
+
};
|
|
1533
|
+
if (file) {
|
|
1534
|
+
const lastModified = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "lastModified")?.get?.call(file);
|
|
1535
|
+
const name = Object.getOwnPropertyDescriptor(FileConstructor.prototype, "name")?.get?.call(file);
|
|
1536
|
+
if (typeof lastModified !== "number" || typeof name !== "string") return;
|
|
1537
|
+
state.lastModified = lastModified;
|
|
1538
|
+
state.name = name;
|
|
1539
|
+
}
|
|
1540
|
+
return state;
|
|
1541
|
+
} catch {
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
function containsUnsafeStructuredCloneState(value, seen = /* @__PURE__ */ new Set()) {
|
|
1546
|
+
if (!value || typeof value !== "object" || seen.has(value)) return false;
|
|
1547
|
+
if (isCryptoKey(value) || isWebAssemblyModule(value)) return true;
|
|
1548
|
+
seen.add(value);
|
|
1549
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
1550
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1551
|
+
if (!descriptor?.enumerable) continue;
|
|
1552
|
+
if (!("value" in descriptor) || containsUnsafeStructuredCloneState(descriptor.value, seen)) return true;
|
|
1553
|
+
}
|
|
1554
|
+
for (const key of ["cause", "errors"]) {
|
|
1555
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1556
|
+
if (descriptor && (!("value" in descriptor) || containsUnsafeStructuredCloneState(descriptor.value, seen))) return true;
|
|
1557
|
+
}
|
|
1558
|
+
const mapEntries = reflectedMapEntries(value);
|
|
1559
|
+
if (mapEntries) {
|
|
1560
|
+
for (const [key, entry] of mapEntries) if (containsUnsafeStructuredCloneState(key, seen) || containsUnsafeStructuredCloneState(entry, seen)) return true;
|
|
1561
|
+
} else {
|
|
1562
|
+
const setValues = reflectedSetValues(value);
|
|
1563
|
+
if (setValues) {
|
|
1564
|
+
for (const entry of setValues) if (containsUnsafeStructuredCloneState(entry, seen)) return true;
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
return false;
|
|
1568
|
+
}
|
|
1569
|
+
function preservesEnumerableFields(source, snapshot, seen = /* @__PURE__ */ new Map()) {
|
|
1570
|
+
if (!source || typeof source !== "object") return true;
|
|
1571
|
+
if (!snapshot || typeof snapshot !== "object") return false;
|
|
1572
|
+
if (seen.has(source)) return seen.get(source) === snapshot;
|
|
1573
|
+
seen.set(source, snapshot);
|
|
1574
|
+
const sourceView = reflectedArrayBufferViewState(source);
|
|
1575
|
+
if (sourceView) {
|
|
1576
|
+
const snapshotView = reflectedArrayBufferViewState(snapshot);
|
|
1577
|
+
if (!snapshotView || sourceView.kind !== snapshotView.kind || sourceView.byteLength !== snapshotView.byteLength) return false;
|
|
1578
|
+
}
|
|
1579
|
+
if (source instanceof Date && (!(snapshot instanceof Date) || !Object.is(source.getTime(), snapshot.getTime()))) return false;
|
|
1580
|
+
const sourceRegExp = reflectedRegExpState(source);
|
|
1581
|
+
if (sourceRegExp) {
|
|
1582
|
+
const snapshotRegExp = reflectedRegExpState(snapshot);
|
|
1583
|
+
if (!snapshotRegExp || sourceRegExp.source !== snapshotRegExp.source || sourceRegExp.flags !== snapshotRegExp.flags || sourceRegExp.lastIndex !== snapshotRegExp.lastIndex) return false;
|
|
1584
|
+
}
|
|
1585
|
+
const sourceBlob = reflectedBlobState(source);
|
|
1586
|
+
if (sourceBlob) {
|
|
1587
|
+
const snapshotBlob = reflectedBlobState(snapshot);
|
|
1588
|
+
if (!snapshotBlob || sourceBlob.size !== snapshotBlob.size || sourceBlob.type !== snapshotBlob.type || sourceBlob.name !== snapshotBlob.name || sourceBlob.lastModified !== snapshotBlob.lastModified) return false;
|
|
1589
|
+
}
|
|
1590
|
+
const sourceAggregateErrors = Object.getOwnPropertyDescriptor(source, "errors");
|
|
1591
|
+
if (sourceAggregateErrors && "value" in sourceAggregateErrors) {
|
|
1592
|
+
const snapshotAggregateErrors = Object.getOwnPropertyDescriptor(snapshot, "errors");
|
|
1593
|
+
if (!snapshotAggregateErrors || !("value" in snapshotAggregateErrors) || !preservesEnumerableFields(sourceAggregateErrors.value, snapshotAggregateErrors.value, seen)) return false;
|
|
1594
|
+
}
|
|
1595
|
+
if (source instanceof AggregateError) {
|
|
1596
|
+
if (!(snapshot instanceof AggregateError) || source.name !== snapshot.name || source.message !== snapshot.message || !preservesEnumerableFields(source.errors, snapshot.errors, seen) || !preservesEnumerableFields(source.cause, snapshot.cause, seen)) return false;
|
|
1597
|
+
} else if (source instanceof DOMException) {
|
|
1598
|
+
if (!(snapshot instanceof DOMException) || source.name !== snapshot.name || source.message !== snapshot.message || source.code !== snapshot.code) return false;
|
|
1599
|
+
} else if (source instanceof Error) {
|
|
1600
|
+
if (!(snapshot instanceof Error) || source.name !== snapshot.name || source.message !== snapshot.message || !preservesEnumerableFields(source.cause, snapshot.cause, seen)) return false;
|
|
1601
|
+
}
|
|
1602
|
+
for (const key of Reflect.ownKeys(source)) {
|
|
1603
|
+
const sourceDescriptor = Object.getOwnPropertyDescriptor(source, key);
|
|
1604
|
+
if (!sourceDescriptor?.enumerable) continue;
|
|
1605
|
+
if (typeof key === "symbol") {
|
|
1606
|
+
if (sourceBlob?.intrinsicSymbols.has(key)) continue;
|
|
1607
|
+
return false;
|
|
1608
|
+
}
|
|
1609
|
+
if (!("value" in sourceDescriptor)) return false;
|
|
1610
|
+
const snapshotDescriptor = Object.getOwnPropertyDescriptor(snapshot, key);
|
|
1611
|
+
if (!snapshotDescriptor || !("value" in snapshotDescriptor)) return false;
|
|
1612
|
+
if (!preservesEnumerableFields(sourceDescriptor.value, snapshotDescriptor.value, seen)) return false;
|
|
1613
|
+
}
|
|
1614
|
+
const sourceMapEntries = reflectedMapEntries(source);
|
|
1615
|
+
if (sourceMapEntries) {
|
|
1616
|
+
const snapshotEntries = reflectedMapEntries(snapshot);
|
|
1617
|
+
if (!snapshotEntries || sourceMapEntries.length !== snapshotEntries.length) return false;
|
|
1618
|
+
return sourceMapEntries.every(([key, value], index) => {
|
|
1619
|
+
const snapshotEntry = snapshotEntries[index];
|
|
1620
|
+
return snapshotEntry !== void 0 && preservesEnumerableFields(key, snapshotEntry[0], seen) && preservesEnumerableFields(value, snapshotEntry[1], seen);
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
const sourceSetValues = reflectedSetValues(source);
|
|
1624
|
+
if (sourceSetValues) {
|
|
1625
|
+
const snapshotValues = reflectedSetValues(snapshot);
|
|
1626
|
+
if (!snapshotValues || sourceSetValues.length !== snapshotValues.length) return false;
|
|
1627
|
+
return sourceSetValues.every((value, index) => preservesEnumerableFields(value, snapshotValues[index], seen));
|
|
1628
|
+
}
|
|
1629
|
+
return true;
|
|
1630
|
+
}
|
|
1631
|
+
function normalizedTracePayload(payload) {
|
|
1632
|
+
if (payload === void 0) return;
|
|
1633
|
+
if (!payload || typeof payload !== "object") return { visibility: "private" };
|
|
1634
|
+
try {
|
|
1635
|
+
if (Array.isArray(payload)) return { visibility: "private" };
|
|
1636
|
+
const visibility = Object.getOwnPropertyDescriptor(payload, "visibility");
|
|
1637
|
+
if (!visibility || !("value" in visibility)) return { visibility: "private" };
|
|
1638
|
+
if (visibility.value === "public") {
|
|
1639
|
+
const value = Object.getOwnPropertyDescriptor(payload, "value");
|
|
1640
|
+
if (value && "value" in value && !containsUnsafeStructuredCloneState(value.value)) {
|
|
1641
|
+
const snapshot = structuredClone(value.value);
|
|
1642
|
+
if (preservesEnumerableFields(value.value, snapshot) && !containsSharedArrayBuffer(snapshot)) return {
|
|
1643
|
+
value: snapshot,
|
|
1644
|
+
visibility: "public"
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
if (visibility.value === "summary") {
|
|
1649
|
+
const summary = Object.getOwnPropertyDescriptor(payload, "summary");
|
|
1650
|
+
if (summary && "value" in summary && typeof summary.value === "string") return {
|
|
1651
|
+
summary: summary.value,
|
|
1652
|
+
visibility: "summary"
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
if (visibility.value === "redacted") return { visibility: "redacted" };
|
|
1656
|
+
} catch {
|
|
1657
|
+
return { visibility: "private" };
|
|
1658
|
+
}
|
|
1659
|
+
return { visibility: "private" };
|
|
1660
|
+
}
|
|
1661
|
+
function traceEventAttributes(event, content, normalized = false) {
|
|
1662
|
+
const activity = normalized ? event.activity : normalizedTraceActivity(event.activity);
|
|
1663
|
+
const payload = normalized ? event.payload : normalizedTracePayload(event.payload);
|
|
1664
|
+
const next = { ...normalizeTraceAttributes(event.attributes, content) };
|
|
1665
|
+
if (activity) {
|
|
1666
|
+
next["vitehub.activity.owner"] = activity.owner;
|
|
1667
|
+
next["vitehub.activity.phase"] = activity.phase;
|
|
1668
|
+
}
|
|
1669
|
+
if (payload) {
|
|
1670
|
+
next["vitehub.payload.visibility"] = payload.visibility;
|
|
1671
|
+
if (payload.visibility === "public") next["vitehub.payload.value"] = payload.value;
|
|
1672
|
+
if (payload.visibility === "summary") next["vitehub.payload.summary"] = payload.summary;
|
|
1673
|
+
}
|
|
1674
|
+
return Object.keys(next).length ? next : void 0;
|
|
1675
|
+
}
|
|
1676
|
+
function aggregateTraceAttributes(attributes) {
|
|
1677
|
+
if (!attributes) return void 0;
|
|
1678
|
+
const next = { ...attributes };
|
|
1679
|
+
delete next["vitehub.activity.owner"];
|
|
1680
|
+
delete next["vitehub.activity.phase"];
|
|
1681
|
+
delete next["vitehub.payload.summary"];
|
|
1682
|
+
delete next["vitehub.payload.value"];
|
|
1683
|
+
delete next["vitehub.payload.visibility"];
|
|
1684
|
+
return Object.keys(next).length ? next : void 0;
|
|
1685
|
+
}
|
|
1686
|
+
function stepTraceAttributes(attributes) {
|
|
1687
|
+
if (!attributes) return void 0;
|
|
1688
|
+
const next = { ...attributes };
|
|
1689
|
+
delete next["vitehub.activity.owner"];
|
|
1690
|
+
delete next["vitehub.activity.phase"];
|
|
1691
|
+
return Object.keys(next).length ? next : void 0;
|
|
1692
|
+
}
|
|
1693
|
+
function normalizeTraceEvent(event, sequence, content) {
|
|
1694
|
+
const { activity: rawActivity, attributes: _attributes, payload: rawPayload, ...rest } = event;
|
|
1695
|
+
const activity = normalizedTraceActivity(rawActivity);
|
|
1696
|
+
const payload = normalizedTracePayload(rawPayload);
|
|
1697
|
+
const attributes = traceEventAttributes({
|
|
1698
|
+
activity,
|
|
1699
|
+
attributes: event.attributes,
|
|
1700
|
+
payload
|
|
1701
|
+
}, content, true);
|
|
1702
|
+
return {
|
|
1703
|
+
...rest,
|
|
1704
|
+
...activity ? { activity } : {},
|
|
1705
|
+
...attributes ? { attributes } : {},
|
|
1706
|
+
...payload ? { payload } : {},
|
|
1707
|
+
sequence,
|
|
1708
|
+
timestamp: timestamp(event.timestamp)
|
|
1709
|
+
};
|
|
1710
|
+
}
|
|
1711
|
+
async function emitTraceEvent(context, event) {
|
|
1712
|
+
return await context.traceLog?.append({
|
|
1713
|
+
...event,
|
|
1714
|
+
trace: event.trace || context.trace
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
function createTraceEventLog(options = {}) {
|
|
1718
|
+
const content = options.content || "metadata";
|
|
1719
|
+
const entries = [];
|
|
1720
|
+
const cloneAttributes = (attributes) => {
|
|
1721
|
+
if (!attributes) return void 0;
|
|
1722
|
+
return { ...attributes };
|
|
1723
|
+
};
|
|
1724
|
+
const cloneEntry = (entry) => {
|
|
1725
|
+
const publicValue = entry.attributes?.["vitehub.payload.value"];
|
|
1726
|
+
const cloneable = structuredClone({
|
|
1727
|
+
activity: entry.activity,
|
|
1728
|
+
payload: entry.payload,
|
|
1729
|
+
publicValue
|
|
1730
|
+
});
|
|
1731
|
+
const attributes = cloneAttributes(entry.attributes);
|
|
1732
|
+
if (attributes && "vitehub.payload.value" in attributes) attributes["vitehub.payload.value"] = cloneable.publicValue;
|
|
1733
|
+
return {
|
|
1734
|
+
...entry,
|
|
1735
|
+
...cloneable.activity ? { activity: cloneable.activity } : {},
|
|
1736
|
+
...attributes ? { attributes } : {},
|
|
1737
|
+
...cloneable.payload ? { payload: cloneable.payload } : {}
|
|
1738
|
+
};
|
|
1739
|
+
};
|
|
1740
|
+
return {
|
|
1741
|
+
async append(event) {
|
|
1742
|
+
const entry = normalizeTraceEvent(event, entries.length + 1, content);
|
|
1743
|
+
entries.push(entry);
|
|
1744
|
+
await options.onEntry?.(cloneEntry(entry));
|
|
1745
|
+
return cloneEntry(entry);
|
|
1746
|
+
},
|
|
1747
|
+
entries() {
|
|
1748
|
+
return entries.map(cloneEntry);
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
}
|
|
1752
|
+
function millis(value) {
|
|
1753
|
+
const parsed = Date.parse(value);
|
|
1754
|
+
return Number.isFinite(parsed) ? parsed : 0;
|
|
1755
|
+
}
|
|
1756
|
+
function durationMs(startTime, endTime) {
|
|
1757
|
+
if (!endTime) return void 0;
|
|
1758
|
+
const duration = millis(endTime) - millis(startTime);
|
|
1759
|
+
return Number.isFinite(duration) && duration >= 0 ? duration : void 0;
|
|
1760
|
+
}
|
|
1761
|
+
function firstString(...values) {
|
|
1762
|
+
return values.find((value) => typeof value === "string" && value.length > 0);
|
|
1763
|
+
}
|
|
1764
|
+
function runId(event) {
|
|
1765
|
+
return firstString(event.attributes?.["agent.run.id"], event.attributes?.["run.id"], event.attributes?.runId, event.trace?.id) || "default";
|
|
1766
|
+
}
|
|
1767
|
+
function stepId(event) {
|
|
1768
|
+
return firstString(event.attributes?.["step.id"], event.attributes?.["tool.id"], event.attributes?.["approval.id"], event.attributes?.["model.call.id"]);
|
|
1769
|
+
}
|
|
1770
|
+
function stepStatus(event) {
|
|
1771
|
+
return event.type === "error" || /\.(?:cancelled|error|failed)$/.test(event.name) ? "failed" : /\.(?:output|progress|request|start|started|summary|updated)$/.test(event.name) ? "running" : "completed";
|
|
1772
|
+
}
|
|
1773
|
+
function isTraceRunFinish(event) {
|
|
1774
|
+
return event.name === "agent.invocation.cancelled" || event.name === "agent.invocation.finish" || event.name === "run.finish";
|
|
1775
|
+
}
|
|
1776
|
+
function isTraceRunError(event) {
|
|
1777
|
+
return event.name === "agent.invocation.error" || event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] !== true || event.name === "run.error";
|
|
1778
|
+
}
|
|
1779
|
+
function isTraceRunTerminal(event) {
|
|
1780
|
+
return isTraceRunFinish(event) || isTraceRunError(event);
|
|
1781
|
+
}
|
|
1782
|
+
function isTraceRunFailureEvidence(event) {
|
|
1783
|
+
return event.name === "run.error" || event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] !== true;
|
|
1784
|
+
}
|
|
1785
|
+
function deriveTraceRuns(events) {
|
|
1786
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1787
|
+
for (const event of events) {
|
|
1788
|
+
const id = runId(event);
|
|
1789
|
+
const group = groups.get(id);
|
|
1790
|
+
if (group) group.push(event);
|
|
1791
|
+
else groups.set(id, [event]);
|
|
1792
|
+
}
|
|
1793
|
+
return [...groups.entries()].map(([id, group]) => {
|
|
1794
|
+
const sorted = group.sort((a, b) => a.sequence - b.sequence);
|
|
1795
|
+
const first = sorted[0];
|
|
1796
|
+
const steps = /* @__PURE__ */ new Map();
|
|
1797
|
+
for (const event of sorted) {
|
|
1798
|
+
const id = stepId(event);
|
|
1799
|
+
if (!id) continue;
|
|
1800
|
+
const existing = steps.get(id);
|
|
1801
|
+
const status = stepStatus(event);
|
|
1802
|
+
if (!existing) {
|
|
1803
|
+
steps.set(id, {
|
|
1804
|
+
attributes: stepTraceAttributes(event.attributes),
|
|
1805
|
+
endTime: status === "running" ? void 0 : event.timestamp,
|
|
1806
|
+
events: [event],
|
|
1807
|
+
id,
|
|
1808
|
+
name: event.name.replace(/\.(start|started|progress|finish|completed|failed|cancelled|end|error|request|decision|recorded)$/, ""),
|
|
1809
|
+
startTime: event.timestamp,
|
|
1810
|
+
status,
|
|
1811
|
+
type: event.type
|
|
1812
|
+
});
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
existing.events.push(event);
|
|
1816
|
+
const attributes = { ...existing.attributes };
|
|
1817
|
+
if (event.attributes?.["vitehub.payload.visibility"] !== void 0) {
|
|
1818
|
+
delete attributes["vitehub.payload.summary"];
|
|
1819
|
+
delete attributes["vitehub.payload.value"];
|
|
1820
|
+
delete attributes["vitehub.payload.visibility"];
|
|
1821
|
+
}
|
|
1822
|
+
existing.attributes = stepTraceAttributes({
|
|
1823
|
+
...attributes,
|
|
1824
|
+
...event.attributes
|
|
1825
|
+
});
|
|
1826
|
+
if (status !== "running") {
|
|
1827
|
+
existing.endTime = event.timestamp;
|
|
1828
|
+
existing.status = status;
|
|
1829
|
+
existing.durationMs = durationMs(existing.startTime, existing.endTime);
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
const terminal = sorted.slice().reverse().find(isTraceRunTerminal);
|
|
1833
|
+
const status = sorted.some(isTraceRunFailureEvidence) || terminal && isTraceRunError(terminal) ? "failed" : terminal?.name === "agent.invocation.cancelled" ? "cancelled" : terminal ? "completed" : "running";
|
|
1834
|
+
const endTime = status === "running" ? void 0 : terminal?.timestamp;
|
|
1835
|
+
return {
|
|
1836
|
+
durationMs: durationMs(first.timestamp, endTime),
|
|
1837
|
+
endTime,
|
|
1838
|
+
events: sorted,
|
|
1839
|
+
id,
|
|
1840
|
+
startTime: first.timestamp,
|
|
1841
|
+
status,
|
|
1842
|
+
steps: [...steps.values()]
|
|
1843
|
+
};
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
function traceRunTraceId(run) {
|
|
1847
|
+
return firstString(...run.events.map((event) => event.trace?.id), run.id) || run.id;
|
|
1848
|
+
}
|
|
1849
|
+
function traceRunParentId(run) {
|
|
1850
|
+
return firstString(...run.events.map((event) => event.trace?.parentId));
|
|
1851
|
+
}
|
|
1852
|
+
function traceRunSpanId(run) {
|
|
1853
|
+
return firstString(...run.events.map((event) => event.attributes?.["agent.invocation.id"]), run.id) || run.id;
|
|
1854
|
+
}
|
|
1855
|
+
function isOpenTelemetryId(value, length) {
|
|
1856
|
+
return value.length === length && /^[0-9a-f]+$/.test(value);
|
|
1857
|
+
}
|
|
1858
|
+
function openTelemetryId(value, length) {
|
|
1859
|
+
const normalized = value.toLowerCase();
|
|
1860
|
+
if (isOpenTelemetryId(normalized, length)) return normalized;
|
|
1861
|
+
let output = "";
|
|
1862
|
+
for (let seed = 0; output.length < length; seed += 1) {
|
|
1863
|
+
let hash = 2166136261;
|
|
1864
|
+
const input = `${value}:${seed}`;
|
|
1865
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
1866
|
+
hash ^= input.charCodeAt(index);
|
|
1867
|
+
hash = Math.imul(hash, 16777619);
|
|
1868
|
+
}
|
|
1869
|
+
output += (hash >>> 0).toString(16).padStart(8, "0");
|
|
1870
|
+
}
|
|
1871
|
+
const id = output.slice(0, length);
|
|
1872
|
+
return /^0+$/.test(id) ? `1${id.slice(1)}` : id;
|
|
1873
|
+
}
|
|
1874
|
+
function traceEventsToOpenTelemetryLogRecords(events, options = {}) {
|
|
1875
|
+
return deriveTraceRuns([...events]).flatMap((run) => {
|
|
1876
|
+
const spanId = openTelemetryId(traceRunSpanId(run), 16);
|
|
1877
|
+
const traceId = openTelemetryId(traceRunTraceId(run), 32);
|
|
1878
|
+
return run.events.map((event) => {
|
|
1879
|
+
const id = stepId(event);
|
|
1880
|
+
const attributes = traceEventAttributes(event, options.content === "metadata" ? "metadata" : "content");
|
|
1881
|
+
const warning = event.name === "agent.stream.error" && event.attributes?.["error.recoverable"] === true;
|
|
1882
|
+
const error = !warning && (event.type === "error" || /\.(?:cancelled|error|failed)$/.test(event.name));
|
|
1883
|
+
return {
|
|
1884
|
+
attributes: {
|
|
1885
|
+
...attributes,
|
|
1886
|
+
"vitehub.event.sequence": event.sequence,
|
|
1887
|
+
"vitehub.event.type": event.type,
|
|
1888
|
+
"vitehub.run.id": run.id,
|
|
1889
|
+
...id ? { "vitehub.step.id": id } : {}
|
|
1890
|
+
},
|
|
1891
|
+
eventName: event.name,
|
|
1892
|
+
...warning ? {
|
|
1893
|
+
severityNumber: 13,
|
|
1894
|
+
severityText: "WARN"
|
|
1895
|
+
} : error ? {
|
|
1896
|
+
severityNumber: 17,
|
|
1897
|
+
severityText: "ERROR"
|
|
1898
|
+
} : {},
|
|
1899
|
+
spanId: id ? openTelemetryId(`${spanId}:${id}`, 16) : spanId,
|
|
1900
|
+
time: event.timestamp,
|
|
1901
|
+
traceId
|
|
1902
|
+
};
|
|
1903
|
+
});
|
|
1904
|
+
});
|
|
1905
|
+
}
|
|
1906
|
+
function traceEventsToOpenTelemetrySpans(events, options = {}) {
|
|
1907
|
+
const maxEntries = 1024;
|
|
1908
|
+
const firstEntries = maxEntries / 2;
|
|
1909
|
+
const tailEntries = maxEntries / 2;
|
|
1910
|
+
const entriesByRun = /* @__PURE__ */ new Map();
|
|
1911
|
+
for (const entry of events) {
|
|
1912
|
+
const id = runId(entry);
|
|
1913
|
+
let run = entriesByRun.get(id);
|
|
1914
|
+
if (!run) {
|
|
1915
|
+
run = {
|
|
1916
|
+
count: 0,
|
|
1917
|
+
first: [],
|
|
1918
|
+
tail: Array.from({ length: tailEntries })
|
|
1919
|
+
};
|
|
1920
|
+
entriesByRun.set(id, run);
|
|
1921
|
+
}
|
|
1922
|
+
const indexed = {
|
|
1923
|
+
entry,
|
|
1924
|
+
index: run.count
|
|
1925
|
+
};
|
|
1926
|
+
if (run.count < firstEntries) run.first.push(indexed);
|
|
1927
|
+
else run.tail[(run.count - firstEntries) % tailEntries] = indexed;
|
|
1928
|
+
if (isTraceRunFailureEvidence(entry)) run.failure = indexed;
|
|
1929
|
+
if (isTraceRunTerminal(entry)) run.terminal = indexed;
|
|
1930
|
+
run.count += 1;
|
|
1931
|
+
}
|
|
1932
|
+
return deriveTraceRuns([...entriesByRun.values()].flatMap((run) => {
|
|
1933
|
+
const tail = run.tail.filter((entry) => entry !== void 0).sort((left, right) => left.index - right.index);
|
|
1934
|
+
const evidence = [run.failure, run.terminal].filter((entry) => entry !== void 0);
|
|
1935
|
+
const indexed = run.count <= maxEntries ? [...run.first, ...tail] : [
|
|
1936
|
+
...run.first,
|
|
1937
|
+
...tail.slice(evidence.length),
|
|
1938
|
+
...evidence
|
|
1939
|
+
];
|
|
1940
|
+
const entries = [...new Map(indexed.map((value) => [value.index, value])).values()].sort((left, right) => left.index - right.index).map((value) => value.entry);
|
|
1941
|
+
if (run.count <= maxEntries) return entries;
|
|
1942
|
+
return entries.map((entry, index) => index === 0 ? {
|
|
1943
|
+
...entry,
|
|
1944
|
+
attributes: {
|
|
1945
|
+
...entry.attributes,
|
|
1946
|
+
"vitehub.trace.originalEventCount": run.count,
|
|
1947
|
+
"vitehub.trace.truncated": true
|
|
1948
|
+
}
|
|
1949
|
+
} : entry);
|
|
1950
|
+
}).map((entry) => ({
|
|
1951
|
+
...entry,
|
|
1952
|
+
attributes: traceEventAttributes(entry, options.content === "metadata" ? "metadata" : "content")
|
|
1953
|
+
}))).flatMap((run) => {
|
|
1954
|
+
const rawParentSpanId = traceRunParentId(run);
|
|
1955
|
+
const rawTraceId = traceRunTraceId(run);
|
|
1956
|
+
const parentSpanId = rawParentSpanId ? openTelemetryId(rawParentSpanId, 16) : void 0;
|
|
1957
|
+
const spanId = openTelemetryId(traceRunSpanId(run), 16);
|
|
1958
|
+
const traceId = openTelemetryId(rawTraceId, 32);
|
|
1959
|
+
const attributes = aggregateTraceAttributes(Object.assign({}, ...run.events.filter((event) => !stepId(event)).map((event) => event.attributes || {})));
|
|
1960
|
+
const spanEvents = (events) => events.map((event) => ({
|
|
1961
|
+
...event.attributes ? { attributes: event.attributes } : {},
|
|
1962
|
+
name: event.name,
|
|
1963
|
+
time: event.timestamp
|
|
1964
|
+
}));
|
|
1965
|
+
const errorMessage = firstString(...run.events.slice().reverse().map((event) => event.attributes?.["error.message"]));
|
|
1966
|
+
return [{
|
|
1967
|
+
attributes: {
|
|
1968
|
+
...attributes,
|
|
1969
|
+
"vitehub.run.id": run.id,
|
|
1970
|
+
...rawParentSpanId ? { "vitehub.trace.parentId": rawParentSpanId } : {},
|
|
1971
|
+
"vitehub.trace.id": rawTraceId
|
|
1972
|
+
},
|
|
1973
|
+
endTime: run.endTime,
|
|
1974
|
+
events: spanEvents(run.events.filter((event) => !stepId(event))),
|
|
1975
|
+
name: "vitehub.run",
|
|
1976
|
+
...parentSpanId ? { parentSpanId } : {},
|
|
1977
|
+
spanId,
|
|
1978
|
+
startTime: run.startTime,
|
|
1979
|
+
status: {
|
|
1980
|
+
code: run.status === "failed" ? "ERROR" : run.status === "completed" ? "OK" : "UNSET",
|
|
1981
|
+
...run.status === "failed" && errorMessage ? { message: errorMessage } : {}
|
|
1982
|
+
},
|
|
1983
|
+
traceId
|
|
1984
|
+
}, ...run.steps.map((step) => ({
|
|
1985
|
+
attributes: {
|
|
1986
|
+
...aggregateTraceAttributes(step.attributes),
|
|
1987
|
+
"vitehub.run.id": run.id,
|
|
1988
|
+
"vitehub.step.id": step.id
|
|
1989
|
+
},
|
|
1990
|
+
endTime: step.endTime || run.endTime,
|
|
1991
|
+
events: spanEvents(step.events),
|
|
1992
|
+
name: step.name,
|
|
1993
|
+
parentSpanId: spanId,
|
|
1994
|
+
spanId: openTelemetryId(`${spanId}:${step.id}`, 16),
|
|
1995
|
+
startTime: step.startTime,
|
|
1996
|
+
status: {
|
|
1997
|
+
code: step.status === "failed" || !step.endTime && run.status === "failed" ? "ERROR" : step.endTime || run.status === "completed" ? "OK" : "UNSET",
|
|
1998
|
+
...typeof step.attributes?.["error.message"] === "string" ? { message: step.attributes["error.message"] } : {}
|
|
1999
|
+
},
|
|
2000
|
+
traceId
|
|
2001
|
+
}))];
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
function createExecutionContext(context) {
|
|
2005
|
+
const capabilities = context.capabilities ?? {};
|
|
2006
|
+
const runtimeConfig = context.runtimeConfig ?? {};
|
|
2007
|
+
return {
|
|
2008
|
+
...context,
|
|
2009
|
+
capabilities,
|
|
2010
|
+
runtimeConfig
|
|
2011
|
+
};
|
|
2012
|
+
}
|
|
2013
|
+
/** Create one operation's context. Without a host waitUntil, drain work before returning. */
|
|
2014
|
+
function createRuntimeContext(input) {
|
|
2015
|
+
const values = /* @__PURE__ */ new Map();
|
|
2016
|
+
const memo = input.memo ?? ((key, create) => {
|
|
2017
|
+
if (!values.has(key)) values.set(key, create());
|
|
2018
|
+
return values.get(key);
|
|
2019
|
+
});
|
|
2020
|
+
const controller = createRuntimeWaitUntilController({ forward: input.waitUntil?.bind(input) });
|
|
2021
|
+
return createExecutionContext({
|
|
2022
|
+
...input,
|
|
2023
|
+
...controller,
|
|
2024
|
+
memo
|
|
2025
|
+
});
|
|
2026
|
+
}
|
|
2027
|
+
function defineCapability(kind, value, options = {}) {
|
|
2028
|
+
const handle = {
|
|
2029
|
+
kind,
|
|
2030
|
+
name: options.name,
|
|
2031
|
+
value
|
|
2032
|
+
};
|
|
2033
|
+
capabilityHandles.add(handle);
|
|
2034
|
+
return handle;
|
|
2035
|
+
}
|
|
2036
|
+
function createRuntimeWaitUntilController(options = {}) {
|
|
2037
|
+
const pending = [];
|
|
2038
|
+
let flushing;
|
|
2039
|
+
return {
|
|
2040
|
+
flushWaitUntil() {
|
|
2041
|
+
flushing ??= Promise.resolve().then(async () => {
|
|
2042
|
+
try {
|
|
2043
|
+
let error;
|
|
2044
|
+
let failed = false;
|
|
2045
|
+
while (pending.length > 0) await Promise.all(pending.splice(0).map(async (task) => {
|
|
2046
|
+
try {
|
|
2047
|
+
await task;
|
|
2048
|
+
} catch (reason) {
|
|
2049
|
+
if (failed) return;
|
|
2050
|
+
error = reason;
|
|
2051
|
+
failed = true;
|
|
2052
|
+
}
|
|
2053
|
+
}));
|
|
2054
|
+
if (failed) throw error;
|
|
2055
|
+
} finally {
|
|
2056
|
+
flushing = void 0;
|
|
2057
|
+
}
|
|
2058
|
+
});
|
|
2059
|
+
return flushing;
|
|
2060
|
+
},
|
|
2061
|
+
waitUntil(task) {
|
|
2062
|
+
task.catch(() => {});
|
|
2063
|
+
pending.push(task);
|
|
2064
|
+
options.forward?.(task);
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
}
|
|
2068
|
+
const capabilityHandles = /* @__PURE__ */ new WeakSet();
|
|
2069
|
+
function isProxy(value) {
|
|
2070
|
+
try {
|
|
2071
|
+
const getBuiltinModule = globalThis.process?.getBuiltinModule;
|
|
2072
|
+
const detector = getBuiltinModule?.("node:util")?.types?.isProxy;
|
|
2073
|
+
return detector ? detector(value) : void 0;
|
|
2074
|
+
} catch {
|
|
2075
|
+
return;
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
function isCapabilityHandle(value) {
|
|
2079
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2080
|
+
if (capabilityHandles.has(value)) return true;
|
|
2081
|
+
if (isProxy(value) === true) return false;
|
|
2082
|
+
try {
|
|
2083
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
2084
|
+
const kind = descriptors.kind;
|
|
2085
|
+
const implementation = descriptors.value;
|
|
2086
|
+
if (!kind || !Object.hasOwn(kind, "value") || typeof kind.value !== "string" || !implementation || !Object.hasOwn(implementation, "value")) return false;
|
|
2087
|
+
if (Object.getPrototypeOf(value) === null) return false;
|
|
2088
|
+
let prototype = Object.getPrototypeOf(value);
|
|
2089
|
+
while (prototype !== null) {
|
|
2090
|
+
if (Object.getOwnPropertyDescriptor(prototype, "kind") || Object.getOwnPropertyDescriptor(prototype, "value")) return false;
|
|
2091
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
2092
|
+
}
|
|
2093
|
+
return true;
|
|
2094
|
+
} catch {
|
|
2095
|
+
return false;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
function hasCapability(context, name) {
|
|
2099
|
+
return !!context.capabilities && Object.hasOwn(context.capabilities, name);
|
|
2100
|
+
}
|
|
2101
|
+
function getCapability(context, name) {
|
|
2102
|
+
const value = hasCapability(context, name) ? context.capabilities?.[name] : void 0;
|
|
2103
|
+
if (value === void 0) throw new ViteHubError("CAPABILITY_NOT_FOUND", `[vitehub:runtime] Capability "${name}" was not found.`, { details: { capability: name } });
|
|
2104
|
+
if (isCapabilityHandle(value)) return value;
|
|
2105
|
+
return defineCapability(name, value, { name });
|
|
2106
|
+
}
|
|
2107
|
+
function isResolvable(value) {
|
|
2108
|
+
return typeof value === "object" && value !== null && "resolve" in value && typeof value.resolve === "function";
|
|
2109
|
+
}
|
|
2110
|
+
async function resolveRuntimeValue(value, context) {
|
|
2111
|
+
if (isResolvable(value)) return await value.resolve(context);
|
|
2112
|
+
if (typeof value === "function") return await value(context);
|
|
2113
|
+
return value;
|
|
2114
|
+
}
|
|
2115
|
+
async function resolveCapabilityPolicy(policy, context) {
|
|
2116
|
+
if (!policy) return "allow";
|
|
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);
|
|
2272
|
+
}
|
|
2273
|
+
//#endregion
|
|
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 };
|