@vite-hub/runtime 0.4.1 → 0.5.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/dist/core-BfUEli_0.d.ts +304 -0
- package/dist/core-DpLK9dQt.js +1105 -0
- package/dist/durability.d.ts +2 -2
- package/dist/durability.js +4 -1
- package/dist/hosted-console-ZfMo5MW4.d.ts +30 -0
- package/dist/index-DsisbCNa.d.ts +364 -0
- package/dist/index.d.ts +7 -5
- package/dist/index.js +5 -4
- package/dist/internal/console.d.ts +7 -0
- package/dist/internal/console.js +2 -0
- package/dist/internal/context.d.ts +2 -0
- package/dist/internal/context.js +2 -0
- package/dist/internal/error-diagnostics.d.ts +2 -0
- package/dist/internal/error-diagnostics.js +2 -0
- package/dist/internal/execution-budget.d.ts +3 -2
- package/dist/internal/execution-budget.js +226 -1
- package/dist/internal/grant.js +1 -1
- package/dist/internal/h3.d.ts +2 -2
- package/dist/internal/h3.js +1 -7
- package/dist/internal/node.d.ts +1 -1
- package/dist/internal/public-url.d.ts +2 -2
- package/dist/internal/public-url.js +2 -2
- package/dist/internal/response.d.ts +2 -0
- package/dist/internal/response.js +2 -0
- package/dist/internal/run-failed.js +0 -1
- package/dist/internal/runtime-type.js +1 -1
- package/dist/internal/shutdown.js +17 -19
- package/dist/internal/test-mode-setup.js +0 -4
- package/dist/internal/trace.d.ts +6 -0
- package/dist/internal/trace.js +2 -0
- package/dist/operations.d.ts +8 -2
- package/dist/operations.js +6 -2
- package/dist/{public-url-1WeOw54Z.d.ts → public-url-BCFhTiTM.d.ts} +6 -1
- package/dist/{public-url-ByAmAjbP.js → public-url-DizC8CFs.js} +25 -17
- package/dist/request-context-Dmsliqan.js +687 -0
- package/dist/response-Be5M4WIn.js +432 -0
- package/dist/response-iONbTI0E.d.ts +33 -0
- package/dist/{runtime-type-BftydMAf.js → runtime-type-CHYQYwDx.js} +0 -7
- package/package.json +26 -1
- package/dist/index-C1DoYfCf.d.ts +0 -733
- package/dist/request-context-uRQpodgl.js +0 -2433
|
@@ -0,0 +1,687 @@
|
|
|
1
|
+
import { t as runtimeErrorDiagnostics } from "./error-diagnostics-BM9W4pBg.js";
|
|
2
|
+
import { n as createRuntimeContext } from "./core-DpLK9dQt.js";
|
|
3
|
+
import { s as isRuntimeDiagnostic } from "./response-Be5M4WIn.js";
|
|
4
|
+
import { Diagnostic, defineDiagnostics } 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/instance.ts
|
|
44
|
+
/** The environment variable that names this server instance. */
|
|
45
|
+
const instanceIdEnv = "VITEHUB_INSTANCE_ID";
|
|
46
|
+
const generatedKey = Symbol.for("vitehub.runtime.instance-id");
|
|
47
|
+
function generatedInstanceId() {
|
|
48
|
+
let host = "";
|
|
49
|
+
try {
|
|
50
|
+
host = globalThis.process?.getBuiltinModule?.("node:os")?.hostname() ?? "";
|
|
51
|
+
} catch {}
|
|
52
|
+
const pid = globalThis.process?.pid;
|
|
53
|
+
const suffix = globalThis.crypto.randomUUID().slice(0, 8);
|
|
54
|
+
return [
|
|
55
|
+
host,
|
|
56
|
+
pid,
|
|
57
|
+
suffix
|
|
58
|
+
].filter((part) => part !== void 0 && part !== "").join(":");
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The owner label of this server instance: `VITEHUB_INSTANCE_ID` when it is set, else `<hostname>:<pid>:<random>`, made
|
|
62
|
+
* once for each process. Leases record it as their `owner`, and Agent Invocation claims start with it, so you can see
|
|
63
|
+
* which instance holds a key or runs an Invocation. Give each instance its own value, such as the pod or machine name.
|
|
64
|
+
*/
|
|
65
|
+
function getInstanceId() {
|
|
66
|
+
const configured = globalThis.process?.env?.[instanceIdEnv]?.trim();
|
|
67
|
+
if (configured) return configured;
|
|
68
|
+
const state = globalThis;
|
|
69
|
+
return state[generatedKey] ??= generatedInstanceId();
|
|
70
|
+
}
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/result.ts
|
|
73
|
+
const resultErrorBrand = Symbol.for("vitehub.runtime.resultError");
|
|
74
|
+
/**
|
|
75
|
+
* Prepares a recognized diagnostic for a result, keeping its metadata in memory.
|
|
76
|
+
* Reuses mutable diagnostics; copies diagnostics whose name or serializer cannot be replaced.
|
|
77
|
+
* Sets name to code to match the result contract, including diagnostics renamed by their owner.
|
|
78
|
+
* The caller owns code allowlisting and the public text. JSON includes only the public fields.
|
|
79
|
+
*/
|
|
80
|
+
function toResultError(error) {
|
|
81
|
+
const canReplace = (key) => {
|
|
82
|
+
const descriptor = Object.getOwnPropertyDescriptor(error, key);
|
|
83
|
+
return descriptor ? descriptor.configurable === true : Object.isExtensible(error);
|
|
84
|
+
};
|
|
85
|
+
const result = canReplace("name") && canReplace("toJSON") && (Object.hasOwn(error, resultErrorBrand) || Object.isExtensible(error)) ? error : new Diagnostic({
|
|
86
|
+
code: error.code,
|
|
87
|
+
why: error.why,
|
|
88
|
+
fix: error.fix,
|
|
89
|
+
docs: error.docs,
|
|
90
|
+
cause: error.cause,
|
|
91
|
+
data: error.data,
|
|
92
|
+
sources: error.sources
|
|
93
|
+
});
|
|
94
|
+
if (result !== error) {
|
|
95
|
+
result.stack = error.stack;
|
|
96
|
+
const status = Reflect.get(error, "status");
|
|
97
|
+
if (typeof status === "number") Object.defineProperty(result, "status", {
|
|
98
|
+
configurable: true,
|
|
99
|
+
value: status
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
Object.defineProperty(result, "name", {
|
|
103
|
+
configurable: true,
|
|
104
|
+
value: result.code,
|
|
105
|
+
writable: true
|
|
106
|
+
});
|
|
107
|
+
Object.defineProperty(result, resultErrorBrand, { value: true });
|
|
108
|
+
Object.defineProperty(result, "toJSON", {
|
|
109
|
+
configurable: true,
|
|
110
|
+
value: () => ({
|
|
111
|
+
code: result.code,
|
|
112
|
+
docs: result.docs,
|
|
113
|
+
fix: result.fix,
|
|
114
|
+
name: result.name,
|
|
115
|
+
why: result.why
|
|
116
|
+
})
|
|
117
|
+
});
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
function defineErrors(options) {
|
|
121
|
+
const diagnostics = defineDiagnostics({
|
|
122
|
+
codes: options.codes,
|
|
123
|
+
docsBase: options.docs
|
|
124
|
+
});
|
|
125
|
+
const codes = new Set(Object.keys(options.codes));
|
|
126
|
+
const catalog = Object.defineProperty({}, "is", { value: (error) => isRuntimeDiagnostic(error) && codes.has(error.code) });
|
|
127
|
+
for (const code of codes) {
|
|
128
|
+
const create = diagnostics[code];
|
|
129
|
+
const status = options.codes[code]?.status;
|
|
130
|
+
catalog[code] = Object.assign((params) => {
|
|
131
|
+
const error = toResultError(create(params));
|
|
132
|
+
if (status !== void 0) Object.defineProperty(error, "status", {
|
|
133
|
+
configurable: true,
|
|
134
|
+
enumerable: false,
|
|
135
|
+
value: status
|
|
136
|
+
});
|
|
137
|
+
return error;
|
|
138
|
+
}, { is: (error) => isRuntimeDiagnostic(error) && error.code === code });
|
|
139
|
+
}
|
|
140
|
+
return catalog;
|
|
141
|
+
}
|
|
142
|
+
//#endregion
|
|
143
|
+
//#region src/lease.ts
|
|
144
|
+
const leaseErrorDiagnostics = /*#__PURE__*/ defineErrors({
|
|
145
|
+
docs: "https://vitehub.dev/docs/runtime/diagnostics",
|
|
146
|
+
codes: {
|
|
147
|
+
RUNTIME_LEASE_INVALID_TTL: {
|
|
148
|
+
why: "`ttl` must be a positive number of seconds.",
|
|
149
|
+
fix: "Pass the TTL in seconds, for example `leases.acquire('report:daily', { ttl: 30 })`."
|
|
150
|
+
},
|
|
151
|
+
RUNTIME_LEASE_FAILED: {
|
|
152
|
+
why: ({ key, operation }) => `The lease store could not ${operation} the lease ${JSON.stringify(key)}.`,
|
|
153
|
+
fix: "Read `error.cause` for the store error. Retry when the store is available again."
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
const sweepIntervalMs = 6e4;
|
|
158
|
+
function toTtlMs(ttl) {
|
|
159
|
+
if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0) return void 0;
|
|
160
|
+
const ms = Math.ceil(ttl * 1e3);
|
|
161
|
+
return Number.isSafeInteger(ms) ? ms : void 0;
|
|
162
|
+
}
|
|
163
|
+
async function attempt(operation, key, run) {
|
|
164
|
+
try {
|
|
165
|
+
return [void 0, await run()];
|
|
166
|
+
} catch (cause) {
|
|
167
|
+
return [leaseErrorDiagnostics.RUNTIME_LEASE_FAILED({
|
|
168
|
+
cause,
|
|
169
|
+
key,
|
|
170
|
+
operation
|
|
171
|
+
}), void 0];
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function createLeaseStore(backend) {
|
|
175
|
+
function lease(record, defaultTtlMs) {
|
|
176
|
+
const held = {
|
|
177
|
+
...record,
|
|
178
|
+
async renew(options) {
|
|
179
|
+
const ttlMs = options?.ttl === void 0 ? defaultTtlMs : toTtlMs(options.ttl);
|
|
180
|
+
if (ttlMs === void 0) return [leaseErrorDiagnostics.RUNTIME_LEASE_INVALID_TTL(), void 0];
|
|
181
|
+
return attempt("renew", held.key, async () => {
|
|
182
|
+
const expiresAt = await backend.renew(held.key, held.id, ttlMs);
|
|
183
|
+
if (expiresAt === void 0) return false;
|
|
184
|
+
held.expiresAt = new Date(expiresAt);
|
|
185
|
+
return true;
|
|
186
|
+
});
|
|
187
|
+
},
|
|
188
|
+
release: () => attempt("release", held.key, () => backend.release(held.key, held.id))
|
|
189
|
+
};
|
|
190
|
+
return held;
|
|
191
|
+
}
|
|
192
|
+
return {
|
|
193
|
+
async acquire(key, options) {
|
|
194
|
+
const ttlMs = toTtlMs(options?.ttl);
|
|
195
|
+
if (ttlMs === void 0) return [leaseErrorDiagnostics.RUNTIME_LEASE_INVALID_TTL(), void 0];
|
|
196
|
+
const id = crypto.randomUUID();
|
|
197
|
+
const owner = options.owner ?? getInstanceId();
|
|
198
|
+
return attempt("acquire", key, async () => {
|
|
199
|
+
const expiresAt = await backend.acquire(key, id, owner, ttlMs);
|
|
200
|
+
if (expiresAt === void 0) return null;
|
|
201
|
+
return lease({
|
|
202
|
+
key,
|
|
203
|
+
id,
|
|
204
|
+
...owner === void 0 ? {} : { owner },
|
|
205
|
+
expiresAt: new Date(expiresAt)
|
|
206
|
+
}, ttlMs);
|
|
207
|
+
});
|
|
208
|
+
},
|
|
209
|
+
get: (key) => attempt("get", key, async () => {
|
|
210
|
+
const record = await backend.get(key);
|
|
211
|
+
return record ? {
|
|
212
|
+
key,
|
|
213
|
+
id: record.id,
|
|
214
|
+
...record.owner === void 0 ? {} : { owner: record.owner },
|
|
215
|
+
expiresAt: new Date(record.expiresAt)
|
|
216
|
+
} : null;
|
|
217
|
+
})
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Leases in the memory of this process. Use it for one instance and for tests. Several instances need a shared store,
|
|
222
|
+
* such as `createSqlLeaseStore()`.
|
|
223
|
+
*/
|
|
224
|
+
function createMemoryLeaseStore() {
|
|
225
|
+
const leases = /* @__PURE__ */ new Map();
|
|
226
|
+
let sweptAt = 0;
|
|
227
|
+
const live = (key, now) => {
|
|
228
|
+
const entry = leases.get(key);
|
|
229
|
+
return entry && entry.expiresAt > now ? entry : void 0;
|
|
230
|
+
};
|
|
231
|
+
return createLeaseStore({
|
|
232
|
+
async acquire(key, id, owner, ttlMs) {
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
if (now - sweptAt >= sweepIntervalMs) {
|
|
235
|
+
sweptAt = now;
|
|
236
|
+
for (const [held, entry] of leases) if (entry.expiresAt <= now) leases.delete(held);
|
|
237
|
+
}
|
|
238
|
+
if (live(key, now)) return void 0;
|
|
239
|
+
const expiresAt = now + ttlMs;
|
|
240
|
+
leases.set(key, {
|
|
241
|
+
id,
|
|
242
|
+
...owner === void 0 ? {} : { owner },
|
|
243
|
+
expiresAt
|
|
244
|
+
});
|
|
245
|
+
return expiresAt;
|
|
246
|
+
},
|
|
247
|
+
async renew(key, id, ttlMs) {
|
|
248
|
+
const entry = leases.get(key);
|
|
249
|
+
if (entry?.id !== id) return void 0;
|
|
250
|
+
entry.expiresAt = Date.now() + ttlMs;
|
|
251
|
+
return entry.expiresAt;
|
|
252
|
+
},
|
|
253
|
+
async release(key, id) {
|
|
254
|
+
if (leases.get(key)?.id !== id) return false;
|
|
255
|
+
return leases.delete(key);
|
|
256
|
+
},
|
|
257
|
+
async get(key) {
|
|
258
|
+
const entry = live(key, Date.now());
|
|
259
|
+
return entry && { ...entry };
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
const busyRetryMs = 5e3;
|
|
264
|
+
async function retryBusy(run) {
|
|
265
|
+
const deadline = Date.now() + busyRetryMs;
|
|
266
|
+
for (let delay = 2;; delay = Math.min(delay * 2, 50)) try {
|
|
267
|
+
return await run();
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (!isBusy(error) || Date.now() + delay > deadline) throw error;
|
|
270
|
+
await new Promise((resolve) => setTimeout(resolve, delay * (.5 + Math.random())));
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function isBusy(error) {
|
|
274
|
+
if (!(error instanceof Error)) return false;
|
|
275
|
+
const code = Reflect.get(error, "code");
|
|
276
|
+
return typeof code === "string" && code.startsWith("SQLITE_BUSY") || /SQLITE_BUSY|database is locked/i.test(error.message) || isBusy(error.cause);
|
|
277
|
+
}
|
|
278
|
+
/** The table of `createSqlLeaseStore()`. The store creates it when it is missing. */
|
|
279
|
+
const leaseTable = "vitehub_leases";
|
|
280
|
+
/**
|
|
281
|
+
* Leases in a SQL table, shared by every process that uses the same Database. Each operation is one statement, so
|
|
282
|
+
* two processes that acquire a key at the same time get one winner. Expiry uses the clock of the Database, not the
|
|
283
|
+
* clocks of the hosts. Works on Postgres and on SQLite 3.35 or later, such as libSQL.
|
|
284
|
+
*/
|
|
285
|
+
function createSqlLeaseStore(client) {
|
|
286
|
+
const now = client.dialect === "postgresql" ? "(extract(epoch from clock_timestamp()) * 1000)::bigint" : "cast((julianday('now') - 2440587.5) * 86400000 as integer)";
|
|
287
|
+
const query = (sql, params) => {
|
|
288
|
+
if (client.dialect === "sqlite") return retryBusy(() => client.query(sql, params));
|
|
289
|
+
let index = 0;
|
|
290
|
+
return client.query(sql.replace(/\?/g, () => `$${++index}`), params);
|
|
291
|
+
};
|
|
292
|
+
const table = leaseTable;
|
|
293
|
+
const columns = `("key" text primary key, id text not null, owner text, expires_at bigint not null)`;
|
|
294
|
+
const index = `create index if not exists ${table}_expires_at on ${table} (expires_at)`;
|
|
295
|
+
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];
|
|
296
|
+
let ready;
|
|
297
|
+
let sweptAt = 0;
|
|
298
|
+
const tableExists = () => query(`select 1 from ${table} limit 0`, []).then(() => true, () => false);
|
|
299
|
+
function ensureTable() {
|
|
300
|
+
ready ??= (async () => {
|
|
301
|
+
if (await tableExists()) return;
|
|
302
|
+
for (const statement of create) await query(statement, []);
|
|
303
|
+
})();
|
|
304
|
+
ready.catch(() => {
|
|
305
|
+
ready = void 0;
|
|
306
|
+
});
|
|
307
|
+
return ready;
|
|
308
|
+
}
|
|
309
|
+
async function run(statement) {
|
|
310
|
+
await ensureTable();
|
|
311
|
+
try {
|
|
312
|
+
return await statement();
|
|
313
|
+
} catch (error) {
|
|
314
|
+
if (await tableExists()) throw error;
|
|
315
|
+
ready = void 0;
|
|
316
|
+
await ensureTable().catch(() => {
|
|
317
|
+
throw error;
|
|
318
|
+
});
|
|
319
|
+
return await statement();
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
const end = (value) => Number(value);
|
|
323
|
+
return createLeaseStore({
|
|
324
|
+
async acquire(key, id, owner, ttlMs) {
|
|
325
|
+
if (Date.now() - sweptAt >= sweepIntervalMs) {
|
|
326
|
+
sweptAt = Date.now();
|
|
327
|
+
await run(() => query(`delete from ${table} where expires_at <= ${now}`, []));
|
|
328
|
+
}
|
|
329
|
+
const [row] = await run(() => query(`insert into ${table} ("key", id, owner, expires_at) values (?, ?, ?, ${now} + cast(? as bigint))
|
|
330
|
+
on conflict ("key") do update set id = excluded.id, owner = excluded.owner, expires_at = ${now} + cast(? as bigint)
|
|
331
|
+
where ${table}.expires_at <= ${now} or ${table}.id = excluded.id
|
|
332
|
+
returning id, expires_at`, [
|
|
333
|
+
key,
|
|
334
|
+
id,
|
|
335
|
+
owner ?? null,
|
|
336
|
+
ttlMs,
|
|
337
|
+
ttlMs
|
|
338
|
+
]));
|
|
339
|
+
return row?.id === id ? end(row.expires_at) : void 0;
|
|
340
|
+
},
|
|
341
|
+
async renew(key, id, ttlMs) {
|
|
342
|
+
const [row] = await run(() => client.dialect === "postgresql" ? query(`with held as (select "key", id from ${table} where "key" = ? and id = ? for update)
|
|
343
|
+
update ${table} set expires_at = ${now} + cast(? as bigint) from held
|
|
344
|
+
where ${table}."key" = held."key" and ${table}.id = held.id returning ${table}.expires_at`, [
|
|
345
|
+
key,
|
|
346
|
+
id,
|
|
347
|
+
ttlMs
|
|
348
|
+
]) : query(`update ${table} set expires_at = ${now} + cast(? as bigint) where "key" = ? and id = ? returning expires_at`, [
|
|
349
|
+
ttlMs,
|
|
350
|
+
key,
|
|
351
|
+
id
|
|
352
|
+
]));
|
|
353
|
+
return row ? end(row.expires_at) : void 0;
|
|
354
|
+
},
|
|
355
|
+
async release(key, id) {
|
|
356
|
+
return (await run(() => query(`delete from ${table} where "key" = ? and id = ? returning id`, [key, id]))).length > 0;
|
|
357
|
+
},
|
|
358
|
+
async get(key) {
|
|
359
|
+
const [row] = await run(() => query(`select id, owner, expires_at from ${table} where "key" = ? and expires_at > ${now}`, [key]));
|
|
360
|
+
if (!row) return void 0;
|
|
361
|
+
return {
|
|
362
|
+
id: String(row.id),
|
|
363
|
+
...typeof row.owner === "string" ? { owner: row.owner } : {},
|
|
364
|
+
expiresAt: end(row.expires_at)
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
//#endregion
|
|
370
|
+
//#region src/duration.ts
|
|
371
|
+
const second = 1e3;
|
|
372
|
+
const minute = 60 * second;
|
|
373
|
+
const hour = 60 * minute;
|
|
374
|
+
const day = 24 * hour;
|
|
375
|
+
const week = 7 * day;
|
|
376
|
+
const units = {
|
|
377
|
+
ms: 1,
|
|
378
|
+
millisecond: 1,
|
|
379
|
+
milliseconds: 1,
|
|
380
|
+
s: second,
|
|
381
|
+
sec: second,
|
|
382
|
+
secs: second,
|
|
383
|
+
second,
|
|
384
|
+
seconds: second,
|
|
385
|
+
m: minute,
|
|
386
|
+
min: minute,
|
|
387
|
+
mins: minute,
|
|
388
|
+
minute,
|
|
389
|
+
minutes: minute,
|
|
390
|
+
h: hour,
|
|
391
|
+
hr: hour,
|
|
392
|
+
hrs: hour,
|
|
393
|
+
hour,
|
|
394
|
+
hours: hour,
|
|
395
|
+
d: day,
|
|
396
|
+
day,
|
|
397
|
+
days: day,
|
|
398
|
+
w: week,
|
|
399
|
+
week,
|
|
400
|
+
weeks: week
|
|
401
|
+
};
|
|
402
|
+
const pattern = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/i;
|
|
403
|
+
function suggest(milliseconds) {
|
|
404
|
+
for (const [unit, size] of [
|
|
405
|
+
["w", week],
|
|
406
|
+
["d", day],
|
|
407
|
+
["h", hour],
|
|
408
|
+
["m", minute],
|
|
409
|
+
["s", second]
|
|
410
|
+
]) if (milliseconds >= size && milliseconds % size === 0) return `"${milliseconds / size}${unit}"`;
|
|
411
|
+
return `"${milliseconds}ms"`;
|
|
412
|
+
}
|
|
413
|
+
function describe(value) {
|
|
414
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
415
|
+
if (typeof value === "object" && value !== null) return "an object";
|
|
416
|
+
return typeof value === "function" || typeof value === "symbol" ? `a ${typeof value}` : String(value);
|
|
417
|
+
}
|
|
418
|
+
function toMilliseconds(amount, size, round) {
|
|
419
|
+
const [whole, fraction = ""] = amount.split(".");
|
|
420
|
+
const scaled = BigInt(`${whole}${fraction}`) * BigInt(size);
|
|
421
|
+
if (fraction.length === 0) return Number(scaled);
|
|
422
|
+
if (round === "ceil") {
|
|
423
|
+
const divisor = 10n ** BigInt(fraction.length);
|
|
424
|
+
return Number((scaled + divisor - 1n) / divisor);
|
|
425
|
+
}
|
|
426
|
+
return Number(`${scaled}e-${fraction.length}`);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Reads a {@link Duration} such as `"30s"`, `"5m"`, or `"1 day"` and returns its milliseconds. A number, a negative
|
|
430
|
+
* value, an unknown unit, or a value too large for a number throws `RUNTIME_DURATION_INVALID`. Pass `option`, such as
|
|
431
|
+
* `"debounce"`, so the error names the option. Pass `"ceil"` to round up to whole milliseconds before converting
|
|
432
|
+
* to a number. For a number, the fix shows the same time as a string. Pass `"s"` as `legacyUnit` when the option took a
|
|
433
|
+
* number of seconds before, so `60` gets the fix `"1m"` and not `"60ms"`. It changes only the fix text.
|
|
434
|
+
*
|
|
435
|
+
* ```ts
|
|
436
|
+
* parseDuration("90s") // 90000
|
|
437
|
+
* parseDuration("1 day") // 86400000
|
|
438
|
+
* ```
|
|
439
|
+
*/
|
|
440
|
+
function parseDuration(value, option, round, legacyUnit = "ms") {
|
|
441
|
+
const [, amount, suffix] = (typeof value === "string" ? pattern.exec(value.trim()) : null) ?? [];
|
|
442
|
+
const unit = suffix?.toLowerCase();
|
|
443
|
+
const size = unit !== void 0 && Object.hasOwn(units, unit) ? units[unit] : void 0;
|
|
444
|
+
const milliseconds = amount === void 0 || size === void 0 ? NaN : toMilliseconds(amount, size, round);
|
|
445
|
+
if (Number.isFinite(milliseconds)) return milliseconds;
|
|
446
|
+
const received = value;
|
|
447
|
+
const legacy = typeof received === "number" && received >= 0 ? received * (legacyUnit === "s" ? second : 1) : NaN;
|
|
448
|
+
const suggestion = Number.isFinite(legacy) ? suggest(legacy) : void 0;
|
|
449
|
+
const legacyUnitName = legacyUnit === "s" ? "seconds" : "milliseconds";
|
|
450
|
+
throw runtimeErrorDiagnostics.RUNTIME_DURATION_INVALID({
|
|
451
|
+
option,
|
|
452
|
+
value: describe(received),
|
|
453
|
+
suggestion,
|
|
454
|
+
unit: legacyUnitName
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
/** Maps a host name or a Nitro preset name, such as `cloudflare-module` or `node-server`, to its ViteHub host. */
|
|
458
|
+
function hostFromNitroPreset(value) {
|
|
459
|
+
const normalized = value?.trim().toLowerCase().replaceAll("_", "-");
|
|
460
|
+
if (!normalized) return;
|
|
461
|
+
if (normalized.startsWith("cloudflare")) return "cloudflare";
|
|
462
|
+
if (normalized.startsWith("deno")) return "deno";
|
|
463
|
+
if (normalized.startsWith("netlify")) return "netlify";
|
|
464
|
+
if (normalized === "node" || normalized.startsWith("node-")) return "node";
|
|
465
|
+
if (normalized.startsWith("vercel")) return "vercel";
|
|
466
|
+
}
|
|
467
|
+
const providerHosts = [
|
|
468
|
+
["WORKERS_CI", "cloudflare"],
|
|
469
|
+
["NETLIFY", "netlify"],
|
|
470
|
+
["NOW_BUILDER", "vercel"],
|
|
471
|
+
["VERCEL", "vercel"],
|
|
472
|
+
["VERCEL_ENV", "vercel"],
|
|
473
|
+
["DENO_DEPLOY", "deno"],
|
|
474
|
+
["DENO_DEPLOYMENT_ID", "deno"]
|
|
475
|
+
];
|
|
476
|
+
/**
|
|
477
|
+
* Returns the ViteHub host that this process builds or runs on, or `undefined` when no variable names a host.
|
|
478
|
+
* The order is `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the provider variables:
|
|
479
|
+
* `WORKERS_CI` (Cloudflare Workers Builds), `NETLIFY`, `NOW_BUILDER`, `VERCEL` or `VERCEL_ENV`, then `DENO_DEPLOY` or `DENO_DEPLOYMENT_ID`.
|
|
480
|
+
* `vitehub()` uses this result when `host` is omitted, and `"node"` when it is `undefined`.
|
|
481
|
+
*/
|
|
482
|
+
function detectHost$1(env = process.env) {
|
|
483
|
+
for (const name of [
|
|
484
|
+
"VITEHUB_HOST",
|
|
485
|
+
"NITRO_PRESET",
|
|
486
|
+
"SERVER_PRESET"
|
|
487
|
+
]) {
|
|
488
|
+
const host = hostFromNitroPreset(env[name]);
|
|
489
|
+
if (host) return host;
|
|
490
|
+
}
|
|
491
|
+
return providerHosts.find(([name]) => env[name]?.trim())?.[1];
|
|
492
|
+
}
|
|
493
|
+
//#endregion
|
|
494
|
+
//#region src/host.ts
|
|
495
|
+
const hostBindingErrors = /*#__PURE__*/ defineErrors({
|
|
496
|
+
docs: "https://vitehub.dev/docs/runtime/diagnostics",
|
|
497
|
+
codes: {
|
|
498
|
+
RUNTIME_HOST_BINDINGS_UNAVAILABLE: {
|
|
499
|
+
why: ({ name }) => `This code runs without host bindings, so the binding "${name}" is not available. Only Cloudflare Workers give bindings.`,
|
|
500
|
+
fix: "Build with `host: \"cloudflare\"`, or handle the error to use another source in this runtime, for example in `vite dev` on Node."
|
|
501
|
+
},
|
|
502
|
+
RUNTIME_HOST_BINDING_NOT_FOUND: {
|
|
503
|
+
why: ({ name }) => `The Worker has no binding named "${name}".`,
|
|
504
|
+
fix: "Declare the binding in the Wrangler config of the app, then run `wrangler types` to update `Cloudflare.Env`."
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
/**
|
|
509
|
+
* Returns the host that this code builds or runs on, or `undefined` when nothing names one.
|
|
510
|
+
* It reads `VITEHUB_HOST`, `NITRO_PRESET`, `SERVER_PRESET`, then the build variables of Cloudflare Workers Builds
|
|
511
|
+
* (`WORKERS_CI`), Netlify, Vercel, and Deno Deploy. Inside a Cloudflare Worker, it returns `"cloudflare"`.
|
|
512
|
+
* `vitehub()` uses the same detection when `host` is omitted.
|
|
513
|
+
*
|
|
514
|
+
* @example
|
|
515
|
+
* ```ts
|
|
516
|
+
* import { detectHost } from "vite-hub/runtime"
|
|
517
|
+
*
|
|
518
|
+
* const host = detectHost() ?? "node"
|
|
519
|
+
* ```
|
|
520
|
+
*/
|
|
521
|
+
function detectHost(env = processEnv()) {
|
|
522
|
+
return detectHost$1(env) ?? (globalThis.navigator?.userAgent === "Cloudflare-Workers" ? "cloudflare" : void 0);
|
|
523
|
+
}
|
|
524
|
+
function processEnv() {
|
|
525
|
+
return globalThis.process?.env ?? {};
|
|
526
|
+
}
|
|
527
|
+
function getHostBinding(name, event) {
|
|
528
|
+
const env = (event && hostBindingsOf(event)) ?? getActiveCloudflareEnv();
|
|
529
|
+
if (!env) return [hostBindingErrors.RUNTIME_HOST_BINDINGS_UNAVAILABLE({ name }), void 0];
|
|
530
|
+
const binding = Object.hasOwn(env, name) ? env[name] : void 0;
|
|
531
|
+
if (binding === void 0) return [hostBindingErrors.RUNTIME_HOST_BINDING_NOT_FOUND({ name }), void 0];
|
|
532
|
+
return [void 0, binding];
|
|
533
|
+
}
|
|
534
|
+
function hostBindingsOf(event) {
|
|
535
|
+
return event["~standard"]?.runtime?.cloudflare?.env ?? getCloudflareEnv(event, { fallback: false });
|
|
536
|
+
}
|
|
537
|
+
//#endregion
|
|
538
|
+
//#region src/request-context.ts
|
|
539
|
+
function isObjectLike(value) {
|
|
540
|
+
return value !== null && (typeof value === "object" || typeof value === "function");
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Return true for a web Request. Hosts pass their own Request classes, such as a Request from another realm, so
|
|
544
|
+
* check the fields that ViteHub reads when the prototype does not match. srvx's Node request inherits from
|
|
545
|
+
* Request, and the prototype check does not run its lazy `url` and `headers` getters.
|
|
546
|
+
*/
|
|
547
|
+
function isHostRequest(value) {
|
|
548
|
+
if (value instanceof Request) return true;
|
|
549
|
+
if (!isObjectLike(value)) return false;
|
|
550
|
+
const headers = Reflect.get(value, "headers");
|
|
551
|
+
return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
|
|
552
|
+
}
|
|
553
|
+
function readPath(value, path) {
|
|
554
|
+
let current = value;
|
|
555
|
+
for (const key of path) current = isObjectLike(current) ? Reflect.get(current, key) : void 0;
|
|
556
|
+
return current;
|
|
557
|
+
}
|
|
558
|
+
/** The first non-empty string at one of `paths`. ViteHub never reads forwarding headers here. */
|
|
559
|
+
function firstAddress(value, paths) {
|
|
560
|
+
for (const path of paths) {
|
|
561
|
+
const address = readPath(value, path);
|
|
562
|
+
if (typeof address === "string" && address) return address;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* The places where hosts put the peer address of a request, in the order of H3's `getRequestIP()`: a host adapter
|
|
567
|
+
* sets `context.clientAddress`, and srvx sets `ip` and keeps the Node request in `runtime.node`.
|
|
568
|
+
*/
|
|
569
|
+
const requestAddressPaths = [
|
|
570
|
+
["context", "clientAddress"],
|
|
571
|
+
["ip"],
|
|
572
|
+
[
|
|
573
|
+
"runtime",
|
|
574
|
+
"node",
|
|
575
|
+
"req",
|
|
576
|
+
"socket",
|
|
577
|
+
"remoteAddress"
|
|
578
|
+
]
|
|
579
|
+
];
|
|
580
|
+
var RequestStandardProps = class {
|
|
581
|
+
vendor = "fetch";
|
|
582
|
+
req;
|
|
583
|
+
res = { headers: new Headers() };
|
|
584
|
+
#runtime;
|
|
585
|
+
constructor(request) {
|
|
586
|
+
this.req = request;
|
|
587
|
+
}
|
|
588
|
+
get runtime() {
|
|
589
|
+
if (this.#runtime) return this.#runtime;
|
|
590
|
+
const cloudflare = readPath(this.req, ["runtime", "cloudflare"]);
|
|
591
|
+
const env = readPath(cloudflare, ["env"]);
|
|
592
|
+
const context = readPath(cloudflare, ["context"]);
|
|
593
|
+
const clientAddress = firstAddress(this.req, requestAddressPaths);
|
|
594
|
+
return this.#runtime = {
|
|
595
|
+
...isObjectLike(env) || isObjectLike(context) ? { cloudflare: {
|
|
596
|
+
...isObjectLike(env) ? { env } : {},
|
|
597
|
+
...isObjectLike(context) ? { context } : {}
|
|
598
|
+
} } : {},
|
|
599
|
+
...clientAddress ? { clientAddress } : {}
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
get waitUntil() {
|
|
603
|
+
for (const owner of [this.req, readPath(this.req, [
|
|
604
|
+
"runtime",
|
|
605
|
+
"cloudflare",
|
|
606
|
+
"context"
|
|
607
|
+
])]) {
|
|
608
|
+
const waitUntil = readPath(owner, ["waitUntil"]);
|
|
609
|
+
if (typeof waitUntil === "function") return waitUntil.bind(owner);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
const requestStandardContexts = /* @__PURE__ */ new WeakMap();
|
|
614
|
+
/** Keep one Standard Context per Request, even when it cannot be extended. A value set by the host stays. */
|
|
615
|
+
function installRequestStandardContext(request, standard) {
|
|
616
|
+
if ("~standard" in request) return request["~standard"];
|
|
617
|
+
const props = standard ?? requestStandardContexts.get(request) ?? new RequestStandardProps(request);
|
|
618
|
+
if (Object.isExtensible(request)) Object.defineProperty(request, "~standard", {
|
|
619
|
+
configurable: true,
|
|
620
|
+
enumerable: false,
|
|
621
|
+
value: props
|
|
622
|
+
});
|
|
623
|
+
else requestStandardContexts.set(request, props);
|
|
624
|
+
return props;
|
|
625
|
+
}
|
|
626
|
+
/**
|
|
627
|
+
* Return the Standard Context of a web Request or of a request event. In a Fetchable server entry, pass the
|
|
628
|
+
* Request: `getStandardContext(request)`. In a ViteHub app, Nitro sets `~standard` on each event and on its
|
|
629
|
+
* Request, so ViteHub keeps the response headers that primitives set. Throws `RUNTIME_R0015` for an event without
|
|
630
|
+
* Standard Context.
|
|
631
|
+
*/
|
|
632
|
+
function getStandardContext(value) {
|
|
633
|
+
if (isObjectLike(value) && "~standard" in value) return value["~standard"];
|
|
634
|
+
if (isHostRequest(value)) return installRequestStandardContext(value);
|
|
635
|
+
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." });
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Adds the prepared response of a plain Fetch host to the Response that a ViteHub route returns, as H3 adds it in a
|
|
639
|
+
* ViteHub app: `set-cookie` values join the ones of the Response, and other headers replace them. The headers move,
|
|
640
|
+
* so a host that also copies `res.headers` does not send them twice. With another vendor, such as H3, the host adds
|
|
641
|
+
* the prepared response, and `response` comes back as it is.
|
|
642
|
+
*/
|
|
643
|
+
function sendPreparedResponse(request, response) {
|
|
644
|
+
const standard = getStandardContext(request);
|
|
645
|
+
const prepared = standard.res.headers;
|
|
646
|
+
if (standard.vendor !== "fetch" || !prepared || prepared.keys().next().done) return response;
|
|
647
|
+
const headers = new Headers(response.headers);
|
|
648
|
+
for (const [name, value] of prepared) if (name === "set-cookie") headers.append(name, value);
|
|
649
|
+
else headers.set(name, value);
|
|
650
|
+
for (const name of Array.from(prepared.keys())) prepared.delete(name);
|
|
651
|
+
return new Response(response.body, {
|
|
652
|
+
headers,
|
|
653
|
+
status: response.status,
|
|
654
|
+
statusText: response.statusText
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
function detectRuntime(cloudflare) {
|
|
658
|
+
if (cloudflare) return "cloudflare-agents";
|
|
659
|
+
if ("Deno" in globalThis) return "deno";
|
|
660
|
+
if (typeof process !== "undefined") {
|
|
661
|
+
if (process.env.VERCEL) return "vercel";
|
|
662
|
+
if (process.env.NODE_ENV === "development") return "vite";
|
|
663
|
+
}
|
|
664
|
+
return "unknown";
|
|
665
|
+
}
|
|
666
|
+
/** Create the runtime context of one request from its Standard Context. The H3 entry shares this function. */
|
|
667
|
+
function createStandardRuntimeContext(event, standard, options) {
|
|
668
|
+
const request = options.request ?? standard?.req;
|
|
669
|
+
if (!request) throw runtimeErrorDiagnostics.RUNTIME_R0015({ message: "[vitehub] The event has no request, so ViteHub cannot create a runtime context." });
|
|
670
|
+
const waitUntil = options.waitUntil?.bind(options) ?? options.vercel?.waitUntil?.bind(options.vercel) ?? standard?.waitUntil;
|
|
671
|
+
const cloudflare = options.cloudflare ?? standard?.runtime?.cloudflare;
|
|
672
|
+
const runtime = options.runtime ?? detectRuntime(!!cloudflare);
|
|
673
|
+
return createRuntimeContext({
|
|
674
|
+
request,
|
|
675
|
+
...options,
|
|
676
|
+
...cloudflare ? { cloudflare } : {},
|
|
677
|
+
event,
|
|
678
|
+
runtime,
|
|
679
|
+
...runtime === "vercel" && waitUntil ? { vercel: { waitUntil } } : {},
|
|
680
|
+
...waitUntil ? { waitUntil } : {}
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
function getRuntimeContext(value, options = {}) {
|
|
684
|
+
return createStandardRuntimeContext(value, getStandardContext(value), options);
|
|
685
|
+
}
|
|
686
|
+
//#endregion
|
|
687
|
+
export { ownValue as S, instanceIdEnv as _, installRequestStandardContext as a, getCloudflareEnv as b, sendPreparedResponse as c, parseDuration as d, createMemoryLeaseStore as f, getInstanceId as g, toResultError as h, getStandardContext as i, detectHost as l, defineErrors as m, firstAddress as n, isHostRequest as o, createSqlLeaseStore as p, getRuntimeContext as r, requestAddressPaths as s, createStandardRuntimeContext as t, getHostBinding as u, activeEnvStorageKey as v, ownObject as x, cloudflareOwners as y };
|