@cloudflare/vite-plugin 2.0.0-beta.v.7 → 2.0.0-beta.v.9
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 +34 -0
- package/dist/index.d.mts +13 -4
- package/dist/index.mjs +297 -397
- package/dist/{package-mniAsqT4.mjs → package--jIwlDD7.mjs} +1 -2
- package/package.json +12 -13
package/dist/index.mjs
CHANGED
|
@@ -23,12 +23,12 @@ import childProcess, { execFile, execFileSync, spawn, spawnSync } from "node:chi
|
|
|
23
23
|
import * as timersPromises from "node:timers/promises";
|
|
24
24
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
25
25
|
import os$1 from "os";
|
|
26
|
-
import { CoreHeaders, CorePaths, DeferredPromise, Log, LogLevel, Miniflare, MiniflareCoreError, Mutex, Request as Request$1, Response as Response$1, buildPublicUrl, convertV4MiniflareOptions, coupleWebSocket, getDefaultDevRegistryPath, getNodeCompat, getWorkerRegistry, kUnsafeEphemeralUniqueKey, parseForwardedProto, parseModuleFallbackRequest } from "miniflare";
|
|
26
|
+
import { CoreHeaders, CorePaths, DeferredPromise, Log, LogLevel, Miniflare, MiniflareCoreError, Mutex, Request as Request$1, Response as Response$1, buildPublicUrl, convertV4MiniflareOptions, coupleWebSocket, getDefaultDevRegistryPath, getNodeCompat, getWorkerRegistry, kUnsafeEphemeralUniqueKey, parseForwardedProto, parseModuleFallbackRequest, resolveLocalBindings } from "miniflare";
|
|
27
27
|
import * as vite from "vite";
|
|
28
28
|
import { normalizePath, version } from "vite";
|
|
29
29
|
import P from "node:readline";
|
|
30
30
|
import { DEFAULT_WORKER_DIRECTORY_NAME, cleanBuildOutputDir, getWorkerAssetsDir, getWorkerBundleDir, normalizeDirectoryName, readBuildOutput, writeContainerConfig, writeRootConfig, writeWorkerConfig } from "@cloudflare/build-output-utils";
|
|
31
|
-
import { InputWorkerSchema, convertToWranglerConfig, generateTypes, loadAndParseConfig } from "@cloudflare/config";
|
|
31
|
+
import { InputConfigSchema, InputWorkerSchema, convertToWranglerConfig, generateTypes, loadAndParseConfig } from "@cloudflare/config";
|
|
32
32
|
import { RUNTIME_TYPES_MARKER, generateRuntimeTypes } from "@cloudflare/runtime-types";
|
|
33
33
|
import { getCloudflarePreset, nonPrefixedNodeModules } from "@cloudflare/unenv-preset";
|
|
34
34
|
import v8 from "node:v8";
|
|
@@ -685,7 +685,7 @@ __export(util_exports$1, {
|
|
|
685
685
|
hide: () => hide$1,
|
|
686
686
|
installLazyProp: () => installLazyProp$1,
|
|
687
687
|
isObject: () => isObject$3,
|
|
688
|
-
isPlainObject: () => isPlainObject$
|
|
688
|
+
isPlainObject: () => isPlainObject$1,
|
|
689
689
|
issue: () => issue$1,
|
|
690
690
|
joinValues: () => joinValues$1,
|
|
691
691
|
jsonStringifyReplacer: () => jsonStringifyReplacer$1,
|
|
@@ -931,7 +931,7 @@ var allowsEval$1 = /* @__PURE__ */ cached$1(() => {
|
|
|
931
931
|
return false;
|
|
932
932
|
}
|
|
933
933
|
});
|
|
934
|
-
function isPlainObject$
|
|
934
|
+
function isPlainObject$1(o) {
|
|
935
935
|
if (isObject$3(o) === false) return false;
|
|
936
936
|
const ctor = o.constructor;
|
|
937
937
|
if (ctor === void 0) return true;
|
|
@@ -941,9 +941,9 @@ function isPlainObject$2(o) {
|
|
|
941
941
|
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
|
|
942
942
|
return true;
|
|
943
943
|
}
|
|
944
|
-
__name$3(isPlainObject$
|
|
944
|
+
__name$3(isPlainObject$1, "isPlainObject");
|
|
945
945
|
function shallowClone$1(o) {
|
|
946
|
-
if (isPlainObject$
|
|
946
|
+
if (isPlainObject$1(o)) return { ...o };
|
|
947
947
|
if (Array.isArray(o)) return [...o];
|
|
948
948
|
if (o instanceof Map) return new Map(o);
|
|
949
949
|
if (o instanceof Set) return new Set(o);
|
|
@@ -1110,7 +1110,7 @@ function omit$1(schema, mask) {
|
|
|
1110
1110
|
}
|
|
1111
1111
|
__name$3(omit$1, "omit");
|
|
1112
1112
|
function extend$1(schema, shape) {
|
|
1113
|
-
if (!isPlainObject$
|
|
1113
|
+
if (!isPlainObject$1(shape)) throw new Error("Invalid input to extend: expected a plain object");
|
|
1114
1114
|
const checks = schema._zod.def.checks;
|
|
1115
1115
|
if (checks && checks.length > 0) {
|
|
1116
1116
|
const existingShape = sourceShape$1(schema);
|
|
@@ -1127,7 +1127,7 @@ function extended$1(schema, shape) {
|
|
|
1127
1127
|
}
|
|
1128
1128
|
__name$3(extended$1, "extended");
|
|
1129
1129
|
function safeExtend$1(schema, shape) {
|
|
1130
|
-
if (!isPlainObject$
|
|
1130
|
+
if (!isPlainObject$1(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
1131
1131
|
return clone$1(schema, mergeDefs$1(schema._zod.def, { shape: extended$1(schema, shape) }));
|
|
1132
1132
|
}
|
|
1133
1133
|
__name$3(safeExtend$1, "safeExtend");
|
|
@@ -3892,7 +3892,7 @@ function mergeValues$1(a, b) {
|
|
|
3892
3892
|
valid: true,
|
|
3893
3893
|
data: a
|
|
3894
3894
|
};
|
|
3895
|
-
if (isPlainObject$
|
|
3895
|
+
if (isPlainObject$1(a) && isPlainObject$1(b)) {
|
|
3896
3896
|
const bKeys = Object.keys(b);
|
|
3897
3897
|
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
3898
3898
|
const newObj = {
|
|
@@ -4098,7 +4098,7 @@ var $ZodRecord$1 = /* @__PURE__ */ $constructor$1("$ZodRecord", (inst, def) => {
|
|
|
4098
4098
|
memo2?.attach(inst);
|
|
4099
4099
|
inst._zod.parse = (payload, ctx) => {
|
|
4100
4100
|
const input2 = payload.value;
|
|
4101
|
-
if (!isPlainObject$
|
|
4101
|
+
if (!isPlainObject$1(input2)) {
|
|
4102
4102
|
payload.issues.push({
|
|
4103
4103
|
expected: "record",
|
|
4104
4104
|
code: "invalid_type",
|
|
@@ -13891,7 +13891,7 @@ function generateIntersectionCheck(doc, ctx, schema, accessor) {
|
|
|
13891
13891
|
__name$3(generateIntersectionCheck, "generateIntersectionCheck");
|
|
13892
13892
|
function generateRecordCheck(doc, ctx, schema, accessor) {
|
|
13893
13893
|
const def = schema._zod.def;
|
|
13894
|
-
const isPlainObjectConst = addConstant(ctx, isPlainObject$
|
|
13894
|
+
const isPlainObjectConst = addConstant(ctx, isPlainObject$1);
|
|
13895
13895
|
doc.write(`if (!${isPlainObjectConst}(${accessor})) return INVALID;`);
|
|
13896
13896
|
const outputVar = newVar(ctx);
|
|
13897
13897
|
const kVar = newVar(ctx);
|
|
@@ -18706,7 +18706,7 @@ function convertBaseSchema(schema, ctx) {
|
|
|
18706
18706
|
const patterns = patternKeys.map((p$2) => new RegExp(p$2));
|
|
18707
18707
|
const basePatternSchema = zodSchema;
|
|
18708
18708
|
zodSchema = zodSchema.check((payload) => {
|
|
18709
|
-
if (!isPlainObject$
|
|
18709
|
+
if (!isPlainObject$1(payload.value)) return;
|
|
18710
18710
|
const unrecognized = [];
|
|
18711
18711
|
for (const key of Object.keys(payload.value)) {
|
|
18712
18712
|
if (propertyKeys.includes(key)) continue;
|
|
@@ -19209,7 +19209,7 @@ function createFatalError(message, isJson, options) {
|
|
|
19209
19209
|
__name$3(createFatalError, "createFatalError");
|
|
19210
19210
|
|
|
19211
19211
|
//#endregion
|
|
19212
|
-
//#region ../workers-utils/dist/chunk-
|
|
19212
|
+
//#region ../workers-utils/dist/chunk-AAQI36FL.mjs
|
|
19213
19213
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
19214
19214
|
function hasKnownExportType(entry) {
|
|
19215
19215
|
const type = entry?.type;
|
|
@@ -19320,7 +19320,7 @@ function validateDurableObjectContainerApplications(config$3, containers = getDu
|
|
|
19320
19320
|
const maybeBoundDO = config$3.durable_objects.bindings.find((durableObject) => durableObject.class_name === container.class_name);
|
|
19321
19321
|
const useSQLite = allDOs.get(container.class_name);
|
|
19322
19322
|
if (useSQLite === void 0 && maybeBoundDO === void 0) throw new UserError(`The container class_name ${container.class_name} does not match any durable object class_name defined in your ${configFileName2}. Note that the durable object must be defined in the same script as the container.`, { telemetryMessage: "no DO defined that matches container class_name" });
|
|
19323
|
-
if (maybeBoundDO?.script_name !== void 0) throw new UserError(`The container ${container.name} is referencing the durable object ${container.class_name}, which appears to be defined on the ${maybeBoundDO.script_name} Worker instead (via the 'script_name' field). You cannot configure a container on a Durable Object that is defined in another Worker.`, { telemetryMessage: "container class_name refers to an external durable object" });
|
|
19323
|
+
if (maybeBoundDO?.script_name !== void 0 && maybeBoundDO.script_name !== config$3.name) throw new UserError(`The container ${container.name} is referencing the durable object ${container.class_name}, which appears to be defined on the ${maybeBoundDO.script_name} Worker instead (via the 'script_name' field). You cannot configure a container on a Durable Object that is defined in another Worker.`, { telemetryMessage: "container class_name refers to an external durable object" });
|
|
19324
19324
|
if (useSQLite === false) throw new UserError(`The container ${container.name} references Durable Object class ${container.class_name}, which uses the legacy KV storage backend. Durable Object-managed Containers require SQLite-backed Durable Objects.`, { telemetryMessage: "durable object container class uses legacy storage" });
|
|
19325
19325
|
}
|
|
19326
19326
|
}
|
|
@@ -50616,7 +50616,7 @@ function mapWorkerMetadataBindings(bindings) {
|
|
|
50616
50616
|
}, {});
|
|
50617
50617
|
}
|
|
50618
50618
|
__name$3(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
|
|
50619
|
-
var DEFAULT_COMPAT_DATE = "2026-
|
|
50619
|
+
var DEFAULT_COMPAT_DATE = "2026-11-01";
|
|
50620
50620
|
function constructWranglerConfig(config$3) {
|
|
50621
50621
|
const mappedBindings = mapWorkerMetadataBindings(config$3.bindings);
|
|
50622
50622
|
const durableObjectClassNames = config$3.bindings.filter((binding) => binding.type === "durable_object_namespace" && binding.script_name === config$3.name).map((durableObject) => durableObject.class_name);
|
|
@@ -55585,7 +55585,7 @@ const allowsEval = /* @__PURE__ */ cached(() => {
|
|
|
55585
55585
|
return false;
|
|
55586
55586
|
}
|
|
55587
55587
|
});
|
|
55588
|
-
function isPlainObject
|
|
55588
|
+
function isPlainObject(o) {
|
|
55589
55589
|
if (isObject$2(o) === false) return false;
|
|
55590
55590
|
const ctor = o.constructor;
|
|
55591
55591
|
if (ctor === void 0) return true;
|
|
@@ -55596,7 +55596,7 @@ function isPlainObject$1(o) {
|
|
|
55596
55596
|
return true;
|
|
55597
55597
|
}
|
|
55598
55598
|
function shallowClone(o) {
|
|
55599
|
-
if (isPlainObject
|
|
55599
|
+
if (isPlainObject(o)) return { ...o };
|
|
55600
55600
|
if (Array.isArray(o)) return [...o];
|
|
55601
55601
|
if (o instanceof Map) return new Map(o);
|
|
55602
55602
|
if (o instanceof Set) return new Set(o);
|
|
@@ -55684,7 +55684,7 @@ function omit(schema, mask) {
|
|
|
55684
55684
|
}));
|
|
55685
55685
|
}
|
|
55686
55686
|
function extend(schema, shape) {
|
|
55687
|
-
if (!isPlainObject
|
|
55687
|
+
if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
|
|
55688
55688
|
const checks = schema._zod.def.checks;
|
|
55689
55689
|
if (checks && checks.length > 0) {
|
|
55690
55690
|
const existingShape = sourceShape(schema);
|
|
@@ -55699,7 +55699,7 @@ function extended(schema, shape) {
|
|
|
55699
55699
|
return newShape;
|
|
55700
55700
|
}
|
|
55701
55701
|
function safeExtend(schema, shape) {
|
|
55702
|
-
if (!isPlainObject
|
|
55702
|
+
if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
|
|
55703
55703
|
return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
|
|
55704
55704
|
}
|
|
55705
55705
|
function merge(a, b) {
|
|
@@ -57766,7 +57766,7 @@ function mergeValues(a, b) {
|
|
|
57766
57766
|
valid: true,
|
|
57767
57767
|
data: a
|
|
57768
57768
|
};
|
|
57769
|
-
if (isPlainObject
|
|
57769
|
+
if (isPlainObject(a) && isPlainObject(b)) {
|
|
57770
57770
|
const bKeys = Object.keys(b);
|
|
57771
57771
|
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
|
|
57772
57772
|
const newObj = {
|
|
@@ -57859,7 +57859,7 @@ const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
|
|
|
57859
57859
|
memo$2?.attach(inst);
|
|
57860
57860
|
inst._zod.parse = (payload, ctx) => {
|
|
57861
57861
|
const input$1 = payload.value;
|
|
57862
|
-
if (!isPlainObject
|
|
57862
|
+
if (!isPlainObject(input$1)) {
|
|
57863
57863
|
payload.issues.push({
|
|
57864
57864
|
expected: "record",
|
|
57865
57865
|
code: "invalid_type",
|
|
@@ -66006,7 +66006,7 @@ var __name$1 = (target$1, value) => __defProp$2(target$1, "name", {
|
|
|
66006
66006
|
});
|
|
66007
66007
|
|
|
66008
66008
|
//#endregion
|
|
66009
|
-
//#region ../workers-auth/dist/chunk-
|
|
66009
|
+
//#region ../workers-auth/dist/chunk-SOBRPAPT.mjs
|
|
66010
66010
|
var import_undici$2 = require_undici();
|
|
66011
66011
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
66012
66012
|
var hasWarnedAboutDeprecatedV1ApiToken = false;
|
|
@@ -66688,14 +66688,18 @@ var ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
|
|
|
66688
66688
|
}
|
|
66689
66689
|
};
|
|
66690
66690
|
function formatOAuthErrorMessage(code, description, uri) {
|
|
66691
|
-
let message = `OAuth error: ${code}`;
|
|
66691
|
+
let message = `OAuth error: ${escapeOAuthErrorText(code)}`;
|
|
66692
66692
|
if (description) message += `
|
|
66693
|
-
${description}`;
|
|
66693
|
+
${escapeOAuthErrorText(description)}`;
|
|
66694
66694
|
if (uri) message += `
|
|
66695
|
-
See: ${uri}`;
|
|
66695
|
+
See: ${escapeOAuthErrorText(uri)}`;
|
|
66696
66696
|
return message;
|
|
66697
66697
|
}
|
|
66698
66698
|
__name$1(formatOAuthErrorMessage, "formatOAuthErrorMessage");
|
|
66699
|
+
function escapeOAuthErrorText(value) {
|
|
66700
|
+
return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
66701
|
+
}
|
|
66702
|
+
__name$1(escapeOAuthErrorText, "escapeOAuthErrorText");
|
|
66699
66703
|
function toErrorClass(rawError, description, uri) {
|
|
66700
66704
|
const message = formatOAuthErrorMessage(rawError, description, uri);
|
|
66701
66705
|
let error$3;
|
|
@@ -66748,13 +66752,14 @@ function toErrorClass(rawError, description, uri) {
|
|
|
66748
66752
|
__name$1(toErrorClass, "toErrorClass");
|
|
66749
66753
|
var TOKEN_REQUEST_TIMEOUT_MS = 3e4;
|
|
66750
66754
|
function isReturningFromAuthServer(query, state, logger$2) {
|
|
66751
|
-
|
|
66752
|
-
|
|
66753
|
-
if (!code) return false;
|
|
66754
|
-
if (query.state !== state.stateQueryParam) {
|
|
66755
|
+
const stateQueryParam = query.state;
|
|
66756
|
+
if (!state.stateQueryParam || stateQueryParam !== state.stateQueryParam) {
|
|
66755
66757
|
logger$2.warn("Received query string parameter doesn't match the one sent! Possible malicious activity somewhere.");
|
|
66756
66758
|
throw new ErrorInvalidReturnedStateParam("", { telemetryMessage: "user oauth invalid returned state" });
|
|
66757
66759
|
}
|
|
66760
|
+
if (query.error) throw toErrorClass(Array.isArray(query.error) ? query.error[0] : query.error, Array.isArray(query.error_description) ? query.error_description[0] : query.error_description, Array.isArray(query.error_uri) ? query.error_uri[0] : query.error_uri);
|
|
66761
|
+
const code = query.code;
|
|
66762
|
+
if (!code) return false;
|
|
66758
66763
|
assert(!Array.isArray(code));
|
|
66759
66764
|
state.authorizationCode = code;
|
|
66760
66765
|
state.hasAuthCodeBeenExchangedForAccessToken = false;
|
|
@@ -66969,6 +66974,10 @@ async function getOauthToken(options, state, ctx, generators) {
|
|
|
66969
66974
|
try {
|
|
66970
66975
|
hasAuthCode = isReturningFromAuthServer(query, state, ctx.logger);
|
|
66971
66976
|
} catch (err) {
|
|
66977
|
+
if (err instanceof ErrorInvalidReturnedStateParam) {
|
|
66978
|
+
renderErrorPage({ description: "This callback does not match the pending login. Return to the authorization page to continue." });
|
|
66979
|
+
return;
|
|
66980
|
+
}
|
|
66972
66981
|
if (err instanceof ErrorAccessDenied) {
|
|
66973
66982
|
res.writeHead(307, { Location: options.denied.url });
|
|
66974
66983
|
res.end(() => {
|
|
@@ -68512,7 +68521,7 @@ var AuthenticationError = class extends UserError {
|
|
|
68512
68521
|
};
|
|
68513
68522
|
|
|
68514
68523
|
//#endregion
|
|
68515
|
-
//#region ../workers-auth/dist/chunk-
|
|
68524
|
+
//#region ../workers-auth/dist/chunk-YWQXTXOY.mjs
|
|
68516
68525
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
68517
68526
|
function createPreferences(getConfigPath) {
|
|
68518
68527
|
function getUserPreferencesPath() {
|
|
@@ -70102,6 +70111,7 @@ var CF_CLIENT_REGISTERED_SCOPES = [
|
|
|
70102
70111
|
"trust-and-safety.write",
|
|
70103
70112
|
"url-scanner.read",
|
|
70104
70113
|
"url-scanner.write",
|
|
70114
|
+
"user-api-tokens.write",
|
|
70105
70115
|
"user-details.read",
|
|
70106
70116
|
"user-details.write",
|
|
70107
70117
|
"vectorize.read",
|
|
@@ -70297,32 +70307,26 @@ function createAuth(profileDir, logger$2) {
|
|
|
70297
70307
|
return auth;
|
|
70298
70308
|
}
|
|
70299
70309
|
/**
|
|
70300
|
-
* Get the cf
|
|
70301
|
-
*
|
|
70302
|
-
* Hooks are cached because `maybeStartOrUpdateRemoteProxySession()` restarts
|
|
70303
|
-
* the session whenever it receives a different hook.
|
|
70310
|
+
* Get the cf credentials for remote bindings sessions.
|
|
70304
70311
|
*
|
|
70305
|
-
* @param hooks - Hook cache that persists across Vite server restarts.
|
|
70306
70312
|
* @param profileDir - Directory used to resolve the cf auth profile.
|
|
70307
70313
|
* @param accountId - The configured account ID, if any.
|
|
70308
70314
|
* @param logger - Logger for the auth flow.
|
|
70309
|
-
* @returns A hook resolving the account ID and API token
|
|
70315
|
+
* @returns A hook resolving the account ID and API token, with a key
|
|
70316
|
+
* identifying those credentials.
|
|
70310
70317
|
*/
|
|
70311
|
-
function getRemoteBindingsAuth(
|
|
70312
|
-
|
|
70313
|
-
|
|
70314
|
-
|
|
70315
|
-
let auth;
|
|
70316
|
-
hook = async () => {
|
|
70318
|
+
function getRemoteBindingsAuth(profileDir, accountId, logger$2) {
|
|
70319
|
+
let auth;
|
|
70320
|
+
return {
|
|
70321
|
+
hook: async () => {
|
|
70317
70322
|
auth ??= createAuth(profileDir, logger$2);
|
|
70318
70323
|
return {
|
|
70319
70324
|
accountId: await auth.requireAuth(accountId ? { account_id: accountId } : {}),
|
|
70320
70325
|
apiToken: auth.requireApiToken()
|
|
70321
70326
|
};
|
|
70322
|
-
}
|
|
70323
|
-
|
|
70324
|
-
}
|
|
70325
|
-
return hook;
|
|
70327
|
+
},
|
|
70328
|
+
key: JSON.stringify([profileDir, accountId])
|
|
70329
|
+
};
|
|
70326
70330
|
}
|
|
70327
70331
|
/** Adapt Vite's logger to the shared Cloudflare API logger interface. */
|
|
70328
70332
|
function createLogger(logger$2) {
|
|
@@ -71070,10 +71074,6 @@ var PluginContext = class {
|
|
|
71070
71074
|
}
|
|
71071
71075
|
return this.#sharedContext.workerNameToExportTypesMap;
|
|
71072
71076
|
}
|
|
71073
|
-
get remoteBindingsAuthHooks() {
|
|
71074
|
-
this.#sharedContext.remoteBindingsAuthHooks ??= /* @__PURE__ */ new Map();
|
|
71075
|
-
return this.#sharedContext.remoteBindingsAuthHooks;
|
|
71076
|
-
}
|
|
71077
71077
|
beginRestartingDevServer() {
|
|
71078
71078
|
this.#sharedContext.restartingDevServerCount++;
|
|
71079
71079
|
}
|
|
@@ -78820,47 +78820,6 @@ const formatInvalidRoutes = (invalidRules) => {
|
|
|
78820
78820
|
return `Invalid routes in \`run_worker_first\`:\n` + invalidRules.join("\n");
|
|
78821
78821
|
};
|
|
78822
78822
|
|
|
78823
|
-
//#endregion
|
|
78824
|
-
//#region ../../node_modules/.pnpm/defu@6.1.4/node_modules/defu/dist/defu.mjs
|
|
78825
|
-
function isPlainObject(value) {
|
|
78826
|
-
if (value === null || typeof value !== "object") return false;
|
|
78827
|
-
const prototype = Object.getPrototypeOf(value);
|
|
78828
|
-
if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) return false;
|
|
78829
|
-
if (Symbol.iterator in value) return false;
|
|
78830
|
-
if (Symbol.toStringTag in value) return Object.prototype.toString.call(value) === "[object Module]";
|
|
78831
|
-
return true;
|
|
78832
|
-
}
|
|
78833
|
-
function _defu(baseObject, defaults, namespace = ".", merger) {
|
|
78834
|
-
if (!isPlainObject(defaults)) return _defu(baseObject, {}, namespace, merger);
|
|
78835
|
-
const object$2 = Object.assign({}, defaults);
|
|
78836
|
-
for (const key in baseObject) {
|
|
78837
|
-
if (key === "__proto__" || key === "constructor") continue;
|
|
78838
|
-
const value = baseObject[key];
|
|
78839
|
-
if (value === null || value === void 0) continue;
|
|
78840
|
-
if (merger && merger(object$2, key, value, namespace)) continue;
|
|
78841
|
-
if (Array.isArray(value) && Array.isArray(object$2[key])) object$2[key] = [...value, ...object$2[key]];
|
|
78842
|
-
else if (isPlainObject(value) && isPlainObject(object$2[key])) object$2[key] = _defu(value, object$2[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
|
|
78843
|
-
else object$2[key] = value;
|
|
78844
|
-
}
|
|
78845
|
-
return object$2;
|
|
78846
|
-
}
|
|
78847
|
-
function createDefu(merger) {
|
|
78848
|
-
return (...arguments_) => arguments_.reduce((p$2, c$1) => _defu(p$2, c$1, "", merger), {});
|
|
78849
|
-
}
|
|
78850
|
-
const defu = createDefu();
|
|
78851
|
-
const defuFn = createDefu((object$2, key, currentValue) => {
|
|
78852
|
-
if (object$2[key] !== void 0 && typeof currentValue === "function") {
|
|
78853
|
-
object$2[key] = currentValue(object$2[key]);
|
|
78854
|
-
return true;
|
|
78855
|
-
}
|
|
78856
|
-
});
|
|
78857
|
-
const defuArrayFn = createDefu((object$2, key, currentValue) => {
|
|
78858
|
-
if (Array.isArray(object$2[key]) && typeof currentValue === "function") {
|
|
78859
|
-
object$2[key] = currentValue(object$2[key]);
|
|
78860
|
-
return true;
|
|
78861
|
-
}
|
|
78862
|
-
});
|
|
78863
|
-
|
|
78864
78823
|
//#endregion
|
|
78865
78824
|
//#region src/build-output.ts
|
|
78866
78825
|
/** Build Output directory used for the dedicated prerender Worker. */
|
|
@@ -85528,14 +85487,6 @@ function createDefaultWorkerConfig(name) {
|
|
|
85528
85487
|
compatibilityDate: DEFAULT_COMPAT_DATE
|
|
85529
85488
|
};
|
|
85530
85489
|
}
|
|
85531
|
-
/** Resolves the entry Worker config. */
|
|
85532
|
-
function resolveEntryWorkerConfig(options) {
|
|
85533
|
-
const configResult = typeof options.configCustomizer === "function" ? options.configCustomizer(options.workerConfig) : options.configCustomizer;
|
|
85534
|
-
return resolveWorkerType({
|
|
85535
|
-
config: InputWorkerSchema.parse(configResult ? defu(configResult, options.workerConfig) : options.workerConfig),
|
|
85536
|
-
isEntryWorker: true
|
|
85537
|
-
});
|
|
85538
|
-
}
|
|
85539
85490
|
/** Resolves an auxiliary or prerender Worker config. */
|
|
85540
85491
|
function resolveNonEntryWorkerConfig(options) {
|
|
85541
85492
|
const inputConfig = typeof options.config === "function" ? options.config({ entryWorkerConfig: options.entryWorkerConfig }) : options.config;
|
|
@@ -85609,18 +85560,24 @@ async function resolvePluginConfig(pluginConfig, userConfig, viteEnv) {
|
|
|
85609
85560
|
mode,
|
|
85610
85561
|
types: types$5
|
|
85611
85562
|
});
|
|
85612
|
-
const settings = {
|
|
85613
|
-
accountId: loadedConfig?.parsedConfig.accountId,
|
|
85614
|
-
complianceRegion: loadedConfig?.parsedConfig.complianceRegion
|
|
85615
|
-
};
|
|
85616
|
-
const containers = loadedConfig?.parsedConfig.containers ?? [];
|
|
85617
85563
|
if (loadedConfig) {
|
|
85618
85564
|
configPaths.add(loadedConfig.configPath);
|
|
85619
85565
|
for (const dep of loadedConfig.dependencies) configPaths.add(dep);
|
|
85620
85566
|
}
|
|
85621
|
-
const
|
|
85622
|
-
|
|
85623
|
-
|
|
85567
|
+
const inputConfig = loadedConfig?.parsedConfig ?? {
|
|
85568
|
+
worker: createDefaultWorkerConfig(getWorkerNameFromProject(root)),
|
|
85569
|
+
containers: []
|
|
85570
|
+
};
|
|
85571
|
+
const customizedConfig = pluginConfig.config ? InputConfigSchema.parse(pluginConfig.config(inputConfig)) : inputConfig;
|
|
85572
|
+
if (customizedConfig.worker === void 0) throw new Error("The customized configuration must define a `worker`.");
|
|
85573
|
+
const settings = {
|
|
85574
|
+
accountId: customizedConfig.accountId,
|
|
85575
|
+
complianceRegion: customizedConfig.complianceRegion
|
|
85576
|
+
};
|
|
85577
|
+
const containers = customizedConfig.containers;
|
|
85578
|
+
const entryWorkerResolvedConfig = resolveWorkerType({
|
|
85579
|
+
config: customizedConfig.worker,
|
|
85580
|
+
isEntryWorker: true
|
|
85624
85581
|
});
|
|
85625
85582
|
const environmentNameToWorkerMap = /* @__PURE__ */ new Map();
|
|
85626
85583
|
const environmentNameToChildEnvironmentNamesMap = /* @__PURE__ */ new Map();
|
|
@@ -89077,7 +89034,7 @@ __name(createWorkerUploadForm, "createWorkerUploadForm");
|
|
|
89077
89034
|
//#endregion
|
|
89078
89035
|
//#region ../remote-bindings/dist/index.mjs
|
|
89079
89036
|
var import_undici = require_undici();
|
|
89080
|
-
var version$1 = "0.0.
|
|
89037
|
+
var version$1 = "0.0.57";
|
|
89081
89038
|
var NoDefaultValueProvided = class extends UserError {
|
|
89082
89039
|
constructor() {
|
|
89083
89040
|
super("This command cannot be run in a non-interactive context", { telemetryMessage: "remote bindings prompt default missing" });
|
|
@@ -89127,6 +89084,212 @@ function getRemoteBindingsAuthHook(auth, accountId, profileDir, logger$1$1) {
|
|
|
89127
89084
|
apiToken: remoteBindingsAuth.requireApiToken()
|
|
89128
89085
|
});
|
|
89129
89086
|
}
|
|
89087
|
+
/**
|
|
89088
|
+
* Convert native config bindings to the transport shape consumed by the
|
|
89089
|
+
* remote-bindings session API. Local-only bindings are intentionally omitted.
|
|
89090
|
+
*/
|
|
89091
|
+
function getRemoteBindings(config$3) {
|
|
89092
|
+
const bindings = {};
|
|
89093
|
+
for (const [name, binding] of Object.entries(config$3.env ?? {})) switch (binding.type) {
|
|
89094
|
+
case "agent-memory":
|
|
89095
|
+
bindings[name] = {
|
|
89096
|
+
type: "agent_memory",
|
|
89097
|
+
namespace: binding.namespace,
|
|
89098
|
+
remote: binding.dev?.remote
|
|
89099
|
+
};
|
|
89100
|
+
break;
|
|
89101
|
+
case "ai":
|
|
89102
|
+
bindings[name] = {
|
|
89103
|
+
type: "ai",
|
|
89104
|
+
remote: binding.dev?.remote
|
|
89105
|
+
};
|
|
89106
|
+
break;
|
|
89107
|
+
case "analytics":
|
|
89108
|
+
bindings[name] = {
|
|
89109
|
+
type: "analytics",
|
|
89110
|
+
remote: binding.dev?.remote
|
|
89111
|
+
};
|
|
89112
|
+
break;
|
|
89113
|
+
case "analytics-engine-dataset":
|
|
89114
|
+
bindings[name] = {
|
|
89115
|
+
type: "analytics_engine",
|
|
89116
|
+
dataset: binding.name,
|
|
89117
|
+
remote: binding.dev?.remote
|
|
89118
|
+
};
|
|
89119
|
+
break;
|
|
89120
|
+
case "ai-search":
|
|
89121
|
+
bindings[name] = {
|
|
89122
|
+
type: "ai_search",
|
|
89123
|
+
instance_name: binding.name,
|
|
89124
|
+
remote: binding.dev?.remote
|
|
89125
|
+
};
|
|
89126
|
+
break;
|
|
89127
|
+
case "ai-search-namespace":
|
|
89128
|
+
bindings[name] = {
|
|
89129
|
+
type: "ai_search_namespace",
|
|
89130
|
+
namespace: binding.namespace,
|
|
89131
|
+
remote: binding.dev?.remote
|
|
89132
|
+
};
|
|
89133
|
+
break;
|
|
89134
|
+
case "artifacts":
|
|
89135
|
+
bindings[name] = {
|
|
89136
|
+
type: "artifacts",
|
|
89137
|
+
namespace: binding.namespace,
|
|
89138
|
+
remote: binding.dev?.remote
|
|
89139
|
+
};
|
|
89140
|
+
break;
|
|
89141
|
+
case "browser":
|
|
89142
|
+
bindings[name] = {
|
|
89143
|
+
type: "browser",
|
|
89144
|
+
remote: binding.dev?.remote
|
|
89145
|
+
};
|
|
89146
|
+
break;
|
|
89147
|
+
case "d1":
|
|
89148
|
+
bindings[name] = {
|
|
89149
|
+
type: "d1",
|
|
89150
|
+
database_id: binding.id,
|
|
89151
|
+
database_name: binding.name,
|
|
89152
|
+
remote: binding.dev?.remote
|
|
89153
|
+
};
|
|
89154
|
+
break;
|
|
89155
|
+
case "dispatch-namespace":
|
|
89156
|
+
bindings[name] = {
|
|
89157
|
+
type: "dispatch_namespace",
|
|
89158
|
+
namespace: binding.namespace,
|
|
89159
|
+
outbound: binding.outbound ? {
|
|
89160
|
+
service: binding.outbound.worker,
|
|
89161
|
+
parameters: binding.outbound.parameters
|
|
89162
|
+
} : void 0,
|
|
89163
|
+
remote: binding.dev?.remote
|
|
89164
|
+
};
|
|
89165
|
+
break;
|
|
89166
|
+
case "flagship":
|
|
89167
|
+
bindings[name] = {
|
|
89168
|
+
type: "flagship",
|
|
89169
|
+
app_id: binding.id,
|
|
89170
|
+
remote: binding.dev?.remote
|
|
89171
|
+
};
|
|
89172
|
+
break;
|
|
89173
|
+
case "hyperdrive":
|
|
89174
|
+
bindings[name] = {
|
|
89175
|
+
type: "hyperdrive",
|
|
89176
|
+
id: binding.id,
|
|
89177
|
+
remote: binding.dev?.remote
|
|
89178
|
+
};
|
|
89179
|
+
break;
|
|
89180
|
+
case "images":
|
|
89181
|
+
bindings[name] = {
|
|
89182
|
+
type: "images",
|
|
89183
|
+
remote: binding.dev?.remote
|
|
89184
|
+
};
|
|
89185
|
+
break;
|
|
89186
|
+
case "kv":
|
|
89187
|
+
bindings[name] = {
|
|
89188
|
+
type: "kv_namespace",
|
|
89189
|
+
id: binding.id,
|
|
89190
|
+
remote: binding.dev?.remote
|
|
89191
|
+
};
|
|
89192
|
+
break;
|
|
89193
|
+
case "media":
|
|
89194
|
+
bindings[name] = {
|
|
89195
|
+
type: "media",
|
|
89196
|
+
remote: binding.dev?.remote
|
|
89197
|
+
};
|
|
89198
|
+
break;
|
|
89199
|
+
case "mtls-certificate":
|
|
89200
|
+
bindings[name] = {
|
|
89201
|
+
type: "mtls_certificate",
|
|
89202
|
+
certificate_id: binding.id,
|
|
89203
|
+
remote: binding.dev?.remote
|
|
89204
|
+
};
|
|
89205
|
+
break;
|
|
89206
|
+
case "pipeline":
|
|
89207
|
+
bindings[name] = {
|
|
89208
|
+
type: "pipeline",
|
|
89209
|
+
stream: binding.name,
|
|
89210
|
+
remote: binding.dev?.remote
|
|
89211
|
+
};
|
|
89212
|
+
break;
|
|
89213
|
+
case "k2":
|
|
89214
|
+
bindings[name] = {
|
|
89215
|
+
type: "k2",
|
|
89216
|
+
stream: binding.stream,
|
|
89217
|
+
remote: binding.dev?.remote
|
|
89218
|
+
};
|
|
89219
|
+
break;
|
|
89220
|
+
case "queue":
|
|
89221
|
+
bindings[name] = {
|
|
89222
|
+
type: "queue",
|
|
89223
|
+
queue_name: binding.name,
|
|
89224
|
+
delivery_delay: binding.deliveryDelay,
|
|
89225
|
+
remote: binding.dev?.remote
|
|
89226
|
+
};
|
|
89227
|
+
break;
|
|
89228
|
+
case "r2":
|
|
89229
|
+
bindings[name] = {
|
|
89230
|
+
type: "r2_bucket",
|
|
89231
|
+
bucket_name: binding.name,
|
|
89232
|
+
jurisdiction: binding.jurisdiction,
|
|
89233
|
+
remote: binding.dev?.remote
|
|
89234
|
+
};
|
|
89235
|
+
break;
|
|
89236
|
+
case "send-email": {
|
|
89237
|
+
const shared = {
|
|
89238
|
+
type: "send_email",
|
|
89239
|
+
allowed_sender_addresses: binding.allowedSenderAddresses,
|
|
89240
|
+
remote: binding.dev?.remote
|
|
89241
|
+
};
|
|
89242
|
+
if (binding.destinationAddress !== void 0) bindings[name] = {
|
|
89243
|
+
...shared,
|
|
89244
|
+
destination_address: binding.destinationAddress
|
|
89245
|
+
};
|
|
89246
|
+
else if (binding.allowedDestinationAddresses !== void 0) bindings[name] = {
|
|
89247
|
+
...shared,
|
|
89248
|
+
allowed_destination_addresses: binding.allowedDestinationAddresses
|
|
89249
|
+
};
|
|
89250
|
+
else bindings[name] = shared;
|
|
89251
|
+
break;
|
|
89252
|
+
}
|
|
89253
|
+
case "stream":
|
|
89254
|
+
bindings[name] = {
|
|
89255
|
+
type: "stream",
|
|
89256
|
+
remote: binding.dev?.remote
|
|
89257
|
+
};
|
|
89258
|
+
break;
|
|
89259
|
+
case "vectorize":
|
|
89260
|
+
bindings[name] = {
|
|
89261
|
+
type: "vectorize",
|
|
89262
|
+
index_name: binding.name,
|
|
89263
|
+
remote: binding.dev?.remote
|
|
89264
|
+
};
|
|
89265
|
+
break;
|
|
89266
|
+
case "vpc-network":
|
|
89267
|
+
bindings[name] = {
|
|
89268
|
+
type: "vpc_network",
|
|
89269
|
+
tunnel_id: binding.tunnelId,
|
|
89270
|
+
network_id: binding.networkId,
|
|
89271
|
+
remote: binding.dev?.remote
|
|
89272
|
+
};
|
|
89273
|
+
break;
|
|
89274
|
+
case "vpc-service":
|
|
89275
|
+
bindings[name] = {
|
|
89276
|
+
type: "vpc_service",
|
|
89277
|
+
service_id: binding.id,
|
|
89278
|
+
remote: binding.dev?.remote
|
|
89279
|
+
};
|
|
89280
|
+
break;
|
|
89281
|
+
case "worker":
|
|
89282
|
+
bindings[name] = {
|
|
89283
|
+
type: "service",
|
|
89284
|
+
service: binding.worker,
|
|
89285
|
+
entrypoint: binding.exportName,
|
|
89286
|
+
props: binding.props,
|
|
89287
|
+
remote: binding.dev?.remote
|
|
89288
|
+
};
|
|
89289
|
+
break;
|
|
89290
|
+
}
|
|
89291
|
+
return bindings;
|
|
89292
|
+
}
|
|
89130
89293
|
var ProxyServerWorker_default = "// ../../node_modules/.pnpm/capnweb@0.12.0/node_modules/capnweb/dist/index-workers.js\nimport * as cfw from \"cloudflare:workers\";\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol(\"workers-module\");\nglobalThis[WORKERS_MODULE_SYMBOL] = cfw;\nif (!Symbol.dispose) Symbol.dispose = /* @__PURE__ */ Symbol.for(\"dispose\");\nif (!Symbol.asyncDispose) Symbol.asyncDispose = /* @__PURE__ */ Symbol.for(\"asyncDispose\");\nif (!Promise.withResolvers) Promise.withResolvers = function() {\n let resolve;\n let reject;\n return {\n promise: new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve,\n reject\n };\n};\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget$1 = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nvar BUFFER_PROTOTYPE = typeof Buffer !== \"undefined\" ? Buffer.prototype : void 0;\nfunction typeForRpc(value) {\n switch (typeof value) {\n case \"boolean\":\n case \"number\":\n case \"string\":\n return \"primitive\";\n case \"undefined\":\n return \"undefined\";\n case \"object\":\n case \"function\":\n break;\n case \"bigint\":\n return \"bigint\";\n default:\n return \"unsupported\";\n }\n if (value === null) return \"primitive\";\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return \"object\";\n case Function.prototype:\n case AsyncFunction.prototype:\n return \"function\";\n case Array.prototype:\n return \"array\";\n case Date.prototype:\n return \"date\";\n case Uint8Array.prototype:\n case BUFFER_PROTOTYPE:\n case ArrayBuffer.prototype:\n case DataView.prototype:\n case Int8Array.prototype:\n case Uint8ClampedArray.prototype:\n case Int16Array.prototype:\n case Uint16Array.prototype:\n case Int32Array.prototype:\n case Uint32Array.prototype:\n case BigInt64Array.prototype:\n case BigUint64Array.prototype:\n case Float32Array.prototype:\n case Float64Array.prototype:\n return \"bytes\";\n case WritableStream.prototype:\n return \"writable\";\n case ReadableStream.prototype:\n return \"readable\";\n case URL.prototype:\n return \"url\";\n case Headers.prototype:\n return \"headers\";\n case Request.prototype:\n return \"request\";\n case Response.prototype:\n return \"response\";\n case Blob.prototype:\n return \"blob\";\n case RpcStub$1.prototype:\n return \"stub\";\n case RpcPromise$1.prototype:\n return \"rpc-promise\";\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) return \"rpc-target\";\n else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) return \"rpc-thenable\";\n }\n if (value instanceof RpcTarget$1) return \"rpc-target\";\n if (value instanceof Error) return \"error\";\n return \"unsupported\";\n }\n}\nfunction mapNotLoaded() {\n throw new Error(\"RPC map() implementation was not loaded.\");\n}\nvar mapImpl = {\n applyMap: mapNotLoaded,\n sendMap: mapNotLoaded\n};\nfunction streamNotLoaded() {\n throw new Error(\"Stream implementation was not loaded.\");\n}\nvar streamImpl = {\n createWritableStreamHook: streamNotLoaded,\n createWritableStreamFromHook: streamNotLoaded,\n createReadableStreamHook: streamNotLoaded\n};\nvar StubHook = class {\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled;\n try {\n pulled = hook.pull();\n } catch (err) {\n hook.dispose();\n throw err;\n }\n let promise;\n if (pulled instanceof Promise) promise = pulled.then((p) => {\n p.dispose();\n });\n else {\n pulled.dispose();\n promise = Promise.resolve();\n }\n return { promise };\n }\n};\nvar ErrorStubHook = class extends StubHook {\n error;\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n args.dispose();\n return this;\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(/* @__PURE__ */ new Error(\"Attempted to use RPC stub after it has been disposed.\"));\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol(\"realStub\");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise$1(doCall(stub.hook, stub.pathIfPromise || [], RpcPayload.fromAppParams(argumentsList)), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) return stub;\n else if (prop in RpcPromise$1.prototype) return stub[prop];\n else if (typeof prop === \"string\") return new RpcPromise$1(stub.hook, stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]);\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n else return;\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) return true;\n else if (prop in RpcPromise$1.prototype) return prop in stub;\n else if (typeof prop === \"string\") return true;\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return true;\n else return false;\n },\n construct(target, args) {\n throw new Error(\"An RPC stub cannot be used as a constructor.\");\n },\n defineProperty(target, property, attributes) {\n throw new Error(\"Can't define properties on RPC stubs.\");\n },\n deleteProperty(target, p) {\n throw new Error(\"Can't delete properties on RPC stubs.\");\n },\n getOwnPropertyDescriptor(target, p) {\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error(\"Can't assign properties on RPC stubs.\");\n },\n setPrototypeOf(target, v) {\n throw new Error(\"Can't override prototype of RPC stubs.\");\n }\n};\nvar RpcStub$1 = class RpcStub$12 extends RpcTarget$1 {\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget$1 || value instanceof Function) hook = TargetStubHook.create(value, void 0);\n else hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n if (pathIfPromise) throw new TypeError(\"RpcStub constructor expected one argument, received two.\");\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) return new RpcStub$12(target.hook.get(target.pathIfPromise));\n else return new RpcStub$12(target.hook.dup());\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return \"[object RpcStub]\";\n }\n};\nvar RpcPromise$1 = class extends RpcStub$1 {\n constructor(hook, pathIfPromise) {\n if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);\n else {\n if (pathIfPromise !== void 0) throw new TypeError(\"RpcPromise constructor expected one argument, received two.\");\n let kind = typeForRpc(hook);\n if (kind === \"rpc-promise\") {\n let raw = unwrapStubAndPath(hook);\n if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);\n else {\n let adopted = raw.hook;\n raw.hook = DISPOSED_HOOK;\n super(adopted, []);\n }\n } else if (kind === \"rpc-thenable\") super(TargetStubHook.create(hook, void 0), []);\n else {\n let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));\n promiseHook.ignoreUnhandledRejections();\n super(promiseHook, []);\n }\n }\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return \"[object RpcPromise]\";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return hook.get(pathIfPromise);\n else return hook;\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) return hook.get(pathIfPromise);\n else return hook.dup();\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return;\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);\n return (await hook.pull()).deliverResolve();\n}\nvar RpcPayload = class RpcPayload2 {\n value;\n source;\n hooks;\n promises;\n static fromAppParams(value) {\n return new RpcPayload2(value, \"params\");\n }\n static fromAppReturn(value) {\n return new RpcPayload2(value, \"return\");\n }\n static fromArray(array) {\n let hooks = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let hook of payload.hooks) hooks.push(hook);\n for (let promise of payload.promises) {\n if (promise.parent === payload) promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new RpcPayload2(resultArray, \"owned\", hooks, promises);\n }\n static forEvaluate(hooks, promises) {\n return new RpcPayload2(null, \"owned\", hooks, promises);\n }\n static deepCopyFrom(value, oldParent, owner) {\n let result = new RpcPayload2(null, \"owned\", [], []);\n result.value = result.deepCopy(value, oldParent, \"value\", result, true, owner);\n return result;\n }\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n rpcTargets;\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === \"params\") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === \"function\") target = dupable.dup();\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(target);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw RpcTargets\");\n }\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createWritableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createWritableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw WritableStreams\");\n }\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createReadableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createReadableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw ReadableStreams\");\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n return value;\n case \"primitive\":\n case \"bigint\":\n case \"date\":\n case \"bytes\":\n case \"blob\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return value;\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n return result;\n }\n case \"object\": {\n let result = {};\n let object = value;\n for (let i in object) result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n return result;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook;\n if (dupStubs) hook = unwrapStubAndDup(stub);\n else hook = unwrapStubTakingOwnership(stub);\n if (stub instanceof RpcPromise$1) {\n let promise = new RpcPromise$1(hook, []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook;\n if (owner) hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n else hook = TargetStubHook.create(target, oldParent);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n case \"rpc-thenable\": {\n let target = value;\n let promise;\n if (owner) promise = new RpcPromise$1(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n else promise = new RpcPromise$1(TargetStubHook.create(target, oldParent), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n }\n case \"writable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createWritableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"readable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"headers\":\n return new Headers(value);\n case \"request\": {\n let req = value;\n if (req.body) this.deepCopy(req.body, req, \"body\", req, dupStubs, owner);\n return new Request(req);\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.deepCopy(resp.body, resp, \"body\", resp, dupStubs, owner);\n return new Response(resp.body, resp);\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n ensureDeepCopied() {\n if (this.source !== \"owned\") {\n let dupStubs = this.source === \"params\";\n this.hooks = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, \"value\", this, dupStubs, this);\n } catch (err) {\n this.hooks = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = \"owned\";\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in deep-copy?\");\n this.rpcTargets = void 0;\n }\n }\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise$1) RpcPayload2.deliverRpcPromiseTo(this.value, parent, property, promises);\n else {\n parent[property] = this.value;\n for (let record of this.promises) RpcPayload2.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) throw new Error(\"property promises should have been resolved earlier\");\n let inner = hook.pull();\n if (inner instanceof RpcPayload2) inner.deliverTo(parent, property, promises);\n else promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) return Promise.all(subPromises);\n }));\n }\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise$1) return RpcPayload2.fromAppReturn(result);\n else return RpcPayload2.fromAppReturn(await result);\n } finally {\n this.dispose();\n }\n }\n async deliverStreamWrite(writer) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let chunk = this.value[0];\n if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {\n if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n await writer.write(chunk);\n return RpcPayload2.fromAppReturn(void 0);\n }\n await writer.write(chunk);\n this.dispose();\n return RpcPayload2.fromAppReturn(void 0);\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) Object.defineProperty(result, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === \"owned\") {\n this.hooks.forEach((hook) => hook.dispose());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === \"return\") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in disposeImpl()?\");\n }\n this.source = \"owned\";\n this.hooks = [];\n this.promises = [];\n }\n disposeImpl(value, parent) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.disposeImpl(object[i], object);\n return;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let hook = unwrapStubNoProperties(value);\n if (hook) hook.dispose();\n return;\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else disposeRpcTarget(target);\n return;\n }\n case \"rpc-thenable\":\n return;\n case \"headers\":\n return;\n case \"request\": {\n let req = value;\n if (req.body) this.disposeImpl(req.body, req);\n return;\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.disposeImpl(resp.body, resp);\n return;\n }\n case \"writable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createWritableStreamHook(stream);\n hook.dispose();\n return;\n }\n case \"readable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createReadableStreamHook(stream);\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach((promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections());\n } else this.ignoreUnhandledRejectionsImpl(this.value);\n }\n ignoreUnhandledRejectionsImpl(value) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"undefined\":\n case \"function\":\n case \"rpc-target\":\n case \"writable\":\n case \"readable\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);\n return;\n }\n case \"stub\":\n case \"rpc-promise\":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case \"rpc-thenable\":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n switch (typeForRpc(value)) {\n case \"object\":\n case \"function\":\n if (Object.hasOwn(value, part)) value = value[part];\n else value = void 0;\n break;\n case \"array\":\n if (Number.isInteger(part) && part >= 0) value = value[part];\n else value = void 0;\n break;\n case \"rpc-target\":\n case \"rpc-thenable\":\n if (Object.hasOwn(value, part)) throw new TypeError(`Attempted to access property '${part}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);\n else value = value[part];\n owner = null;\n break;\n case \"stub\":\n case \"rpc-promise\": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i)\n };\n }\n case \"writable\":\n value = void 0;\n break;\n case \"readable\":\n value = void 0;\n break;\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n value = void 0;\n break;\n case \"undefined\":\n value = value[part];\n break;\n case \"unsupported\":\n if (i === 0) throw new TypeError(`RPC stub points at a non-serializable type.`);\n else {\n let prefix = path.slice(0, i).join(\".\");\n let remainder = path.slice(0, i).join(\".\");\n throw new TypeError(`'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`);\n }\n default:\n throw new TypeError(\"unreachable\");\n }\n }\n if (value instanceof RpcPromise$1) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise || []\n };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);\n if (typeof followResult.value != \"function\") {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(\".\")}' is not a function.`));\n }\n return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {\n return new PayloadStubHook(payload);\n }));\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n for (let cap of captures) cap.dispose();\n throw err;\n }\n if (followResult.hook) return followResult.hook.map(followResult.remainingPath, captures, instructions);\n return mapImpl.applyMap(followResult.value, followResult.parent, followResult.owner, captures, instructions);\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n if (value instanceof Object && \"then\" in value) return this.dup();\n throw new Error(\"Can't dup an RpcTarget stub as a promise.\");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) return followResult.hook.get(followResult.remainingPath);\n return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class PayloadStubHook2 extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n getPayload() {\n if (this.payload) return this.payload;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n let payload = this.getPayload();\n return {\n value: payload.value,\n owner: payload\n };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new PayloadStubHook2(RpcPayload.deepCopyFrom(thisPayload.value, void 0, thisPayload));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) this.payload.ignoreUnhandledRejections();\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub$1) this.payload.value.onRpcBroken(callback);\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n}\nvar TargetStubHook = class TargetStubHook2 extends ValueStubHook {\n static create(value, parent) {\n if (typeof value !== \"function\") parent = void 0;\n return new TargetStubHook2(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) this.refcount = { count: 1 };\n }\n target;\n parent;\n refcount;\n getTarget() {\n if (this.target) return this.target;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n return {\n value: this.getTarget(),\n owner: null\n };\n }\n dup() {\n return new TargetStubHook2(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if (\"then\" in target) return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n else return Promise.reject(/* @__PURE__ */ new Error(\"Tried to resolve a non-promise stub.\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) disposeRpcTarget(this.target);\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n let target = this.target;\n if (target && \"then\" in target) Promise.resolve(target).then(() => {\n }, callback);\n }\n};\nvar PromiseStubHook = class PromiseStubHook2 extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new PromiseStubHook2(this.promise.then((hook) => hook.call(path, args), (err) => {\n args.dispose();\n throw err;\n }));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {\n args.dispose();\n throw err;\n }) };\n }\n map(path, captures, instructions) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.map(path, captures, instructions), (err) => {\n for (let cap of captures) cap.dispose();\n throw err;\n }));\n }\n get(path) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) return this.resolution.dup();\n else return new PromiseStubHook2(this.promise.then((hook) => hook.dup()));\n }\n pull() {\n if (this.resolution) return this.resolution.pull();\n else return this.promise.then((hook) => hook.pull());\n }\n ignoreUnhandledRejections() {\n if (this.resolution) this.resolution.ignoreUnhandledRejections();\n else this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n dispose() {\n this.promise.then((hook) => hook.dispose(), () => {\n });\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n};\nvar DEFAULT_LIMITS = {\n maxBigIntDigits: 16384,\n maxDepth: 256,\n maxMessageSize: 32 * 1024 * 1024\n};\nvar NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\nvar BYTE_CONTAINER_TYPE_NAMES = [\n \"ArrayBuffer\",\n \"DataView\",\n \"Int8Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"Int16Array\",\n \"Uint16Array\",\n \"Int32Array\",\n \"Uint32Array\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Float32Array\",\n \"Float64Array\"\n];\nfunction isValidByteContainerName(value) {\n return BYTE_CONTAINER_TYPE_NAMES.includes(value);\n}\nvar TYPED_ARRAY_ELEMENT_SIZE = {\n ArrayBuffer: void 0,\n DataView: void 0,\n Int8Array: void 0,\n Uint8Array: void 0,\n Uint8ClampedArray: void 0,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n BigInt64Array: 8,\n BigUint64Array: 8,\n Float32Array: 4,\n Float64Array: 8\n};\nvar BYTE_CONTAINER_PROTOTYPES = {\n ArrayBuffer: ArrayBuffer.prototype,\n DataView: DataView.prototype,\n Int8Array: Int8Array.prototype,\n Uint8ClampedArray: Uint8ClampedArray.prototype,\n Int16Array: Int16Array.prototype,\n Uint16Array: Uint16Array.prototype,\n Int32Array: Int32Array.prototype,\n Uint32Array: Uint32Array.prototype,\n BigInt64Array: BigInt64Array.prototype,\n BigUint64Array: BigUint64Array.prototype,\n Float32Array: Float32Array.prototype,\n Float64Array: Float64Array.prototype\n};\nvar BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();\nfor (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);\nfunction swapByteOrder(bytes, elementSize) {\n if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);\n let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {\n case 2:\n view.setUint16(offset, view.getUint16(offset, false), true);\n break;\n case 4:\n view.setUint32(offset, view.getUint32(offset, false), true);\n break;\n case 8:\n view.setBigUint64(offset, view.getBigUint64(offset, false), true);\n break;\n }\n}\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n exportPromise(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n getImport(hook) {\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot create pipes without an RPC session.\");\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nasync function streamToBlob(stream, type) {\n let b = await new Response(stream).blob();\n return b.type === type ? b : b.slice(0, b.size, type);\n}\nvar ERROR_TYPES = {\n __proto__: null,\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n};\nvar Devaluator = class Devaluator2 {\n exporter;\n source;\n encodingLevel;\n constructor(exporter, source, encodingLevel) {\n this.exporter = exporter;\n this.source = source;\n this.encodingLevel = encodingLevel;\n }\n static devaluate(value, parent, exporter = NULL_EXPORTER, source, encodingLevel = \"string\") {\n let devaluator = new Devaluator2(exporter, source, encodingLevel);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 256) throw new Error(\"Serialization exceeded maximum allowed depth. (Does the message contain cycles?)\");\n switch (typeForRpc(value)) {\n case \"unsupported\": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = \"Cannot serialize value: (couldn't stringify value)\";\n }\n throw new TypeError(msg);\n }\n case \"primitive\":\n if (typeof value === \"number\" && !isFinite(value)) {\n if (this.encodingLevel === \"structuredClonable\") return value;\n if (value === Infinity) return [\"inf\"];\n else if (value === -Infinity) return [\"-inf\"];\n else return [\"nan\"];\n } else return value;\n case \"object\": {\n let object = value;\n let result = {};\n for (let key in object) result[key] = this.devaluateImpl(object[key], object, depth + 1);\n return result;\n }\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);\n return [result];\n }\n case \"bigint\":\n if (this.encodingLevel === \"structuredClonable\") return value;\n return [\"bigint\", value.toString()];\n case \"date\": {\n if (this.encodingLevel === \"structuredClonable\") return value;\n const time = value.getTime();\n return [\"date\", Number.isNaN(time) ? null : time];\n }\n case \"bytes\": {\n let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));\n let bytes;\n if (alternateTypeName === \"ArrayBuffer\") bytes = new Uint8Array(value);\n else if (alternateTypeName === void 0) bytes = value;\n else {\n let view = value;\n bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];\n if (!NATIVE_LITTLE_ENDIAN && elementSize) {\n bytes = bytes.slice();\n swapByteOrder(bytes, elementSize);\n }\n }\n if (this.encodingLevel === \"structuredClonable\" || this.encodingLevel === \"jsonCompatibleWithBytes\") return alternateTypeName === void 0 ? [\"bytes\", bytes] : [\n \"bytes\",\n bytes,\n alternateTypeName\n ];\n let b64;\n if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });\n else if (typeof Buffer !== \"undefined\") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString(\"base64\");\n else {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);\n b64 = btoa(binary);\n }\n b64 = b64.replace(/=+$/, \"\");\n return alternateTypeName === void 0 ? [\"bytes\", b64] : [\n \"bytes\",\n b64,\n alternateTypeName\n ];\n }\n case \"url\":\n return [\"url\", value.href];\n case \"headers\":\n return [\"headers\", [...value]];\n case \"request\": {\n let req = value;\n let init = {};\n if (req.method !== \"GET\") init.method = req.method;\n let headers = [...req.headers];\n if (headers.length > 0) init.headers = headers;\n if (req.body) {\n init.body = this.devaluateImpl(req.body, req, depth + 1);\n init.duplex = req.duplex || \"half\";\n } else if (req.body === void 0 && ![\n \"GET\",\n \"HEAD\",\n \"OPTIONS\",\n \"TRACE\",\n \"DELETE\"\n ].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({ async start(controller) {\n try {\n controller.enqueue(new Uint8Array(await bodyPromise));\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n } });\n let hook = streamImpl.createReadableStreamHook(readable);\n init.body = [\"readable\", this.exporter.createPipe(readable, hook)];\n init.duplex = req.duplex || \"half\";\n }\n if (req.cache && req.cache !== \"default\") init.cache = req.cache;\n if (req.redirect !== \"follow\") init.redirect = req.redirect;\n if (req.integrity) init.integrity = req.integrity;\n if (req.mode && req.mode !== \"cors\") init.mode = req.mode;\n if (req.credentials && req.credentials !== \"same-origin\") init.credentials = req.credentials;\n if (req.referrer && req.referrer !== \"about:client\") init.referrer = req.referrer;\n if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;\n if (req.keepalive) init.keepalive = req.keepalive;\n let cfReq = req;\n if (cfReq.cf) init.cf = cfReq.cf;\n if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== \"automatic\") init.encodeResponseBody = cfReq.encodeResponseBody;\n return [\n \"request\",\n req.url,\n init\n ];\n }\n case \"response\": {\n let resp = value;\n let body = this.devaluateImpl(resp.body, resp, depth + 1);\n let init = {};\n if (resp.status !== 200) init.status = resp.status;\n if (resp.statusText) init.statusText = resp.statusText;\n let headers = [...resp.headers];\n if (headers.length > 0) init.headers = headers;\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== \"automatic\") init.encodeBody = cfResp.encodeBody;\n if (cfResp.webSocket) throw new TypeError(\"Can't serialize a Response containing a webSocket.\");\n return [\n \"response\",\n body,\n init\n ];\n }\n case \"blob\": {\n let blob = value;\n let readable = blob.stream();\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n return [\n \"blob\",\n blob.type,\n [\"readable\", importId]\n ];\n }\n case \"error\": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) e = rewritten;\n let anyE = e;\n let props;\n let captureProp = (key, val) => {\n let exportsBefore = this.exports?.length ?? 0;\n try {\n let encoded = this.devaluateImpl(val, e, depth + 1);\n if (!props) props = {};\n props[key] = encoded;\n } catch (err) {\n if (this.exports && this.exports.length > exportsBefore) {\n let tail = this.exports.splice(exportsBefore);\n try {\n this.exporter.unexport(tail);\n } catch (err2) {\n }\n }\n }\n };\n for (let key of Object.keys(e)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n captureProp(key, anyE[key]);\n }\n if (\"cause\" in e) captureProp(\"cause\", anyE.cause);\n if (e instanceof AggregateError) captureProp(\"errors\", e.errors);\n let result = [\n \"error\",\n e.name,\n e.message\n ];\n if (props) {\n result.push(rewritten && rewritten.stack ? rewritten.stack : null);\n result.push(props);\n } else if (rewritten && rewritten.stack) result.push(rewritten.stack);\n return result;\n }\n case \"undefined\":\n if (this.encodingLevel === \"structuredClonable\") return;\n return [\"undefined\"];\n case \"stub\":\n case \"rpc-promise\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [\n \"pipeline\",\n importId,\n pathIfPromise\n ];\n else return [\"pipeline\", importId];\n else return [\"import\", importId];\n if (pathIfPromise) hook = hook.get(pathIfPromise);\n else hook = hook.dup();\n return this.devaluateHook(pathIfPromise ? \"promise\" : \"export\", hook);\n }\n case \"function\":\n case \"rpc-target\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"export\", hook);\n }\n case \"rpc-thenable\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"promise\", hook);\n }\n case \"writable\": {\n if (!this.source) throw new Error(\"Can't serialize WritableStream in this context.\");\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook(\"writable\", hook);\n }\n case \"readable\": {\n if (!this.source) throw new Error(\"Can't serialize ReadableStream in this context.\");\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n return [\"readable\", this.exporter.createPipe(ws, hook)];\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === \"promise\" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n importPromise(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n getExport(idx) {\n }\n getPipeReadable(exportId) {\n throw new Error(\"Cannot retrieve pipe readable without an RPC session.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {\n let bytes = new Uint8Array(arrayBuffer);\n let result = new Request(request, { body: bytes });\n return new PayloadStubHook(RpcPayload.fromAppReturn(result));\n })), []);\n}\nfunction streamToBlobPromise(stream, type) {\n return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {\n return new PayloadStubHook(RpcPayload.fromAppReturn(blob));\n })), []);\n}\nvar Evaluator = class Evaluator2 {\n importer;\n encodingLevel;\n limits;\n constructor(importer, encodingLevel = \"string\") {\n this.importer = importer;\n this.encodingLevel = encodingLevel;\n this.limits = importer.getLimits();\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n return this.evaluateWithDepth(value, 0);\n }\n evaluateWithDepth(value, depth) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, \"value\", depth);\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property, depth) {\n let maxDepth = this.limits.maxDepth;\n if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);\n if (this.encodingLevel === \"structuredClonable\") {\n if (value instanceof Date || typeof value === \"bigint\") return value;\n }\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);\n return result;\n } else switch (value[0]) {\n case \"bigint\":\n if (typeof value[1] == \"string\") {\n let digits = value[1];\n let maxBigIntDigits = this.limits.maxBigIntDigits;\n if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);\n return BigInt(digits);\n }\n break;\n case \"date\":\n if (value[1] === null) return /* @__PURE__ */ new Date(NaN);\n if (typeof value[1] == \"number\") return new Date(value[1]);\n break;\n case \"bytes\": {\n let bytes;\n if (value[1] instanceof Uint8Array) bytes = value[1];\n else if (typeof value[1] == \"string\") if (typeof Buffer !== \"undefined\") bytes = Buffer.from(value[1], \"base64\");\n else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);\n else {\n let bs = atob(value[1]);\n let len = bs.length;\n bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);\n }\n else break;\n if (value.length === 2) return bytes;\n if (typeof value[2] !== \"string\") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);\n if (!isValidByteContainerName(value[2])) {\n let marker2 = value[2].slice(0, 64);\n throw new TypeError(`Unknown bytes type marker: ${marker2}`);\n }\n let marker = value[2];\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];\n if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);\n let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);\n switch (marker) {\n case \"ArrayBuffer\":\n return buffer;\n case \"DataView\":\n return new DataView(buffer);\n case \"Int8Array\":\n return new Int8Array(buffer);\n case \"Uint8Array\":\n return new Uint8Array(buffer);\n case \"Uint8ClampedArray\":\n return new Uint8ClampedArray(buffer);\n case \"Int16Array\":\n return new Int16Array(buffer);\n case \"Uint16Array\":\n return new Uint16Array(buffer);\n case \"Int32Array\":\n return new Int32Array(buffer);\n case \"Uint32Array\":\n return new Uint32Array(buffer);\n case \"BigInt64Array\":\n return new BigInt64Array(buffer);\n case \"BigUint64Array\":\n return new BigUint64Array(buffer);\n case \"Float32Array\":\n return new Float32Array(buffer);\n case \"Float64Array\":\n return new Float64Array(buffer);\n default:\n }\n }\n case \"error\":\n if (value.length >= 3 && typeof value[1] === \"string\" && typeof value[2] === \"string\") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = cls === AggregateError ? new cls([], value[2]) : new cls(value[2]);\n if (typeof value[3] === \"string\") result.stack = value[3];\n if (value.length >= 5) {\n let props = value[4];\n if (!props || typeof props !== \"object\" || Array.isArray(props)) break;\n let anyResult = result;\n let propsObj = props;\n for (let key of Object.keys(propsObj)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(propsObj[key], result, key, depth + 1);\n continue;\n }\n anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);\n }\n }\n return result;\n }\n break;\n case \"undefined\":\n if (value.length === 1) return;\n break;\n case \"inf\":\n return Infinity;\n case \"-inf\":\n return -Infinity;\n case \"nan\":\n return NaN;\n case \"url\":\n if (value.length === 2 && typeof value[1] === \"string\") return new URL(value[1]);\n break;\n case \"headers\":\n if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);\n break;\n case \"request\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let url = value[1];\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.body) {\n init.body = this.evaluateImpl(init.body, init, \"body\", depth + 1);\n if (init.body === null || typeof init.body === \"string\" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) {\n } else throw new TypeError(\"Request body must be of type ReadableStream.\");\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, \"signal\", depth + 1);\n if (!(init.signal instanceof AbortSignal)) throw new TypeError(\"Request siganl must be of type AbortSignal.\");\n }\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n let result = new Request(url, init);\n if (init.body instanceof ReadableStream && result.body === void 0) {\n let promise = fixBrokenRequestBody(result, init.body);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else return result;\n }\n case \"response\": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property, depth + 1);\n if (body === null || typeof body === \"string\" || body instanceof Uint8Array || body instanceof ReadableStream) {\n } else throw new TypeError(\"Response body must be of type ReadableStream.\");\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.webSocket) throw new TypeError(\"Can't deserialize a Response containing a webSocket.\");\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n return new Response(body, init);\n }\n case \"blob\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let contentType = value[1];\n let content = this.evaluateImpl(value[2], parent, property, depth + 1);\n if (!(content instanceof ReadableStream)) throw new TypeError(\"Blob content must be serialized as a ReadableStream.\");\n let promise = streamToBlobPromise(content, contentType);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"import\":\n case \"pipeline\": {\n if (value.length < 2 || value.length > 4) break;\n if (typeof value[1] != \"number\") break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let isPromise = value[0] == \"pipeline\";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise$1(hook2, []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise$1(hook2, []);\n }\n };\n if (value.length == 2) if (isPromise) return addStub(hook.get([]));\n else return addStub(hook.dup());\n let path = value[2];\n if (!(path instanceof Array)) break;\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n if (value.length == 3) return addStub(hook.get(path));\n let args = value[3];\n if (!(args instanceof Array)) break;\n args = new Evaluator2(this.importer).evaluateWithDepth([args], depth);\n return addStub(hook.call(path, args));\n }\n case \"remap\": {\n if (value.length !== 5 || typeof value[1] !== \"number\" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let path = value[2];\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n let captures = value[3].map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== \"import\" && cap[0] !== \"export\" || typeof cap[1] !== \"number\") throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n if (cap[0] === \"export\") return this.importer.importStub(cap[1]);\n else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) throw new Error(`no such entry on exports table: ${cap[1]}`);\n return exp.dup();\n }\n });\n let instructions = value[4];\n let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"export\":\n case \"promise\":\n if (typeof value[1] == \"number\") if (value[0] == \"promise\") {\n let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n break;\n case \"writable\":\n if (typeof value[1] == \"number\") {\n let hook = this.importer.importStub(value[1]);\n let stream = streamImpl.createWritableStreamFromHook(hook);\n this.hooks.push(hook);\n return stream;\n }\n break;\n case \"readable\":\n if (typeof value[1] == \"number\") {\n let stream = this.importer.getPipeReadable(value[1]);\n let hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(result[key], result, key, depth + 1);\n delete result[key];\n } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);\n return result;\n } else return value;\n }\n};\nvar ESTIMATED_OBJECT_OVERHEAD = 16;\nvar ESTIMATED_ENTRY_OVERHEAD = 8;\nvar ESTIMATED_BINARY_OVERHEAD = 16;\nvar MAX_ESTIMATE_DEPTH = 64;\nfunction estimateStringSize(value) {\n return 2 + value.length * 3;\n}\nfunction estimateEncodedSize(value, seen, depth = 0) {\n if (depth >= MAX_ESTIMATE_DEPTH) return ESTIMATED_ENTRY_OVERHEAD;\n switch (typeof value) {\n case \"string\":\n return estimateStringSize(value);\n case \"number\":\n return 16;\n case \"bigint\":\n return 16;\n case \"boolean\":\n return 8;\n case \"undefined\":\n return 16;\n case \"object\": {\n if (value === null) return 8;\n if (ArrayBuffer.isView(value)) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;\n if (value instanceof Date) return 16;\n seen ??= /* @__PURE__ */ new WeakSet();\n if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;\n seen.add(value);\n if (value instanceof Array) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD;\n for (let item of value) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateEncodedSize(item, seen, depth + 1);\n return size2;\n }\n if (value instanceof Error) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.name) + estimateStringSize(value.message) + estimateStringSize(value.stack ?? \"\");\n for (let key of Object.keys(value)) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size2;\n }\n let size = ESTIMATED_OBJECT_OVERHEAD;\n for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size;\n }\n default:\n return 16;\n }\n}\nvar ImportTableEntry = class {\n session;\n importId;\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) this.activePull = Promise.withResolvers();\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) delete this.session.onBrokenCallbacks[endIndex];\n else delete this.session.onBrokenCallbacks[i];\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) this.resolution.dispose();\n else {\n this.abort(/* @__PURE__ */ new Error(\"RPC was canceled because the RpcPromise was disposed.\"));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class RpcImportHook2 extends StubHook {\n isPromise;\n entry;\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) return this.entry;\n else throw new Error(\"This RpcImportHook was already disposed.\");\n }\n getEntryTakingOwnership(disposeOwned) {\n try {\n return this.getEntry();\n } catch (err) {\n disposeOwned();\n throw err;\n }\n }\n call(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.call(path, args);\n else return entry.session.sendCall(entry.importId, path, args);\n }\n stream(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.stream(path, args);\n else return entry.session.sendStream(entry.importId, path, args);\n }\n map(path, captures, instructions) {\n let entry = this.getEntryTakingOwnership(() => {\n for (let cap of captures) cap.dispose();\n });\n if (entry.resolution) return entry.resolution.map(path, captures, instructions);\n else return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) return entry.resolution.get(path);\n else return entry.session.sendCall(entry.importId, path);\n }\n dup() {\n return new RpcImportHook2(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) throw new Error(\"Can't pull this hook because it's not a promise hook.\");\n if (entry.resolution) return entry.resolution.pull();\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) entry.dispose();\n }\n }\n onBroken(callback) {\n if (this.entry) this.entry.onBroken(callback);\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n transport;\n options;\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n nextExportId = -1;\n onBatchDone;\n pullCount = 0;\n onBrokenCallbacks = [];\n encodingLevel;\n limits;\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n let level = \"string\";\n if (\"encodingLevel\" in transport) {\n let raw = transport.encodingLevel;\n if (raw !== void 0) {\n if (raw !== \"string\" && raw !== \"jsonCompatible\" && raw !== \"jsonCompatibleWithBytes\" && raw !== \"structuredClonable\") throw new TypeError(`Unknown transport encodingLevel: ${String(raw)}`);\n level = raw;\n }\n }\n this.encodingLevel = level;\n this.limits = {\n ...DEFAULT_LIMITS,\n ...options.limits\n };\n this.exports.push({\n hook: mainHook,\n refcount: 1\n });\n this.imports.push(new ImportTableEntry(this, 0, false));\n this.readLoop().catch((err) => this.abort(err));\n }\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(/* @__PURE__ */ new Error(\"RPC session was shut down by disposing the main stub\"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) this.releaseExport(id, 1);\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) throw new Error(`no such export ID: ${exportId}`);\n if (entry.refcount < refcount) throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) return this.options.onSendError(error);\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) throw new Error(`no such export ID: ${exportId}`);\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub$1) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n let autoRelease = exp.autoRelease;\n ++this.pullCount;\n exp.pull = resolve().then((payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);\n this.send([\n \"resolve\",\n exportId,\n value\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }, (error) => {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }).catch((error) => {\n try {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) this.onBatchDone.resolve();\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;\n else return;\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(false, entry);\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) return new ErrorStubHook(/* @__PURE__ */ new Error(\"Bug in RPC system: The peer sent a promise reusing an existing export ID.\"));\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(true, entry);\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n getPipeReadable(exportId) {\n let entry = this.exports[exportId];\n if (!entry || !entry.pipeReadable) throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\n }\n getLimits() {\n return this.limits;\n }\n createPipe(readable, readableHook) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pipe\"]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, false);\n this.imports.push(entry);\n let hook = new RpcImportHook(false, entry);\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n send(msg) {\n if (this.abortReason !== void 0) return 0;\n if (this.encodingLevel === \"string\") {\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n try {\n let sent = this.transport.send(msgText);\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => this.abort(err, false));\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n }\n return msgText.length;\n } else try {\n let size = this.transport.send(msg);\n if (typeof size === \"number\") return size;\n let thenable = size;\n if (thenable && typeof thenable.then === \"function\") Promise.resolve(thenable).catch((err) => this.abort(err, false));\n return;\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n return;\n }\n }\n sendCall(id, path, args) {\n if (this.abortReason) {\n args?.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n if (args) {\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n }\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendStream(id, path, args) {\n if (this.abortReason) {\n args.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n let msg = [\"stream\", value];\n let size = this.send(msg);\n if (size === void 0) size = estimateEncodedSize(msg);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, true);\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n return {\n promise: entry.awaitResolution().then((p) => {\n p.dispose();\n delete this.imports[importId];\n }, (err) => {\n delete this.imports[importId];\n throw err;\n }),\n size\n };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) cap.dispose();\n throw this.abortReason;\n }\n let value = [\n \"remap\",\n id,\n path,\n captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) return [\"import\", importId];\n else return [\"export\", this.exportStub(hook)];\n }),\n instructions\n ];\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pull\", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send([\n \"release\",\n id,\n remoteRefcount\n ]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop?.(error);\n this.cancelReadLoop = void 0;\n if (trySendAbortMessage) try {\n let abortMsg = [\"abort\", Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)];\n if (this.encodingLevel === \"string\") {\n let sent = this.transport.send(JSON.stringify(abortMsg));\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => {\n });\n } else {\n let result = this.transport.send(abortMsg);\n if (result && typeof result.then === \"function\") Promise.resolve(result).catch((err) => {\n });\n }\n } catch (err) {\n }\n if (error === void 0) error = \"undefined\";\n this.abortReason = error;\n if (this.onBatchDone) this.onBatchDone.reject(error);\n if (this.transport.abort) try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.onBrokenCallbacks) try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.imports) this.imports[i].abort(error);\n for (let i in this.exports) this.exports[i].hook.dispose();\n }\n async readLoop() {\n while (!this.abortReason) {\n let readCanceled = Promise.withResolvers();\n this.cancelReadLoop = readCanceled.reject;\n let raw;\n try {\n raw = await Promise.race([this.transport.receive(), readCanceled.promise]);\n } finally {\n if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;\n }\n if (this.encodingLevel === \"string\" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);\n if (this.abortReason) break;\n let msg = this.encodingLevel === \"string\" ? JSON.parse(raw) : raw;\n if (msg instanceof Array) switch (msg[0]) {\n case \"push\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n this.exports.push({\n hook,\n refcount: 1\n });\n continue;\n }\n break;\n case \"stream\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({\n hook,\n refcount: 1,\n autoRelease: true\n });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n case \"pipe\": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({\n hook,\n refcount: 1,\n pipeReadable: readable\n });\n continue;\n }\n case \"pull\": {\n let exportId = msg[1];\n if (typeof exportId == \"number\") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case \"resolve\":\n case \"reject\": {\n let importId = msg[1];\n if (typeof importId == \"number\" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) if (msg[0] == \"resolve\") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));\n else {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n else if (msg[0] == \"resolve\") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();\n continue;\n }\n break;\n }\n case \"release\": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == \"number\" && typeof refcount == \"number\") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case \"abort\": {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload.value, false);\n break;\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) throw this.abortReason;\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = {\n resolve,\n reject\n };\n await promise;\n }\n }\n getStats() {\n let result = {\n imports: 0,\n exports: 0\n };\n for (let i in this.imports) ++result.imports;\n for (let i in this.exports) ++result.exports;\n return result;\n }\n};\nvar RpcSession$1 = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n else mainHook = new ErrorStubHook(/* @__PURE__ */ new Error(\"This connection has no main object.\"));\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub$1(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nfunction newWebSocketRpcSession$1(webSocket, localMain, options) {\n if (typeof webSocket === \"string\") webSocket = new WebSocket(webSocket);\n return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") return new Response(\"This endpoint only accepts WebSocket requests.\", { status: 400 });\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession$1(server, localMain, options);\n return new Response(null, {\n status: 101,\n webSocket: pair[1]\n });\n}\nvar WebSocketTransport = class {\n constructor(webSocket) {\n this.#webSocket = webSocket;\n webSocket.binaryType = \"arraybuffer\";\n if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener(\"open\", (event) => {\n try {\n for (let message of this.#sendQueue) webSocket.send(message);\n } catch (err) {\n this.#receivedError(err);\n }\n this.#sendQueue = void 0;\n });\n }\n webSocket.addEventListener(\"message\", (event) => {\n if (this.#error) {\n } else if (typeof event.data === \"string\" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else this.#receiveQueue.push(event.data);\n else this.#receivedError(/* @__PURE__ */ new TypeError(\"Received unexpected message type from WebSocket.\"));\n });\n webSocket.addEventListener(\"close\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener(\"error\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n send(message) {\n if (this.#sendQueue === void 0) this.#webSocket.send(message);\n else this.#sendQueue.push(message);\n }\n receive() {\n if (this.#receiveQueue.length > 0) return Promise.resolve(this.#receiveQueue.shift());\n else if (this.#error) return Promise.reject(this.#error);\n else return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) message = reason.message;\n else message = `${reason}`;\n let reasonBytes = new TextEncoder().encode(message);\n if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });\n this.#webSocket.close(3e3, message);\n if (!this.#error) this.#error = reason;\n }\n #receivedError(reason) {\n if (!this.#error) {\n this.#error = reason;\n if (this.#receiveRejecter) {\n this.#receiveRejecter(reason);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n }\n }\n }\n};\nvar BatchServerTransport = class {\n constructor(batch) {\n this.#batchToReceive = batch;\n }\n #batchToSend = [];\n #batchToReceive;\n #allReceived = Promise.withResolvers();\n send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) return msg;\n else {\n this.#allReceived.resolve();\n return new Promise((r) => {\n });\n }\n }\n abort(reason) {\n this.#allReceived.reject(reason);\n }\n whenAllReceived() {\n return this.#allReceived.promise;\n }\n getResponseBody() {\n return this.#batchToSend.join(\"\\n\");\n }\n};\nasync function newHttpBatchRpcResponse(request, localMain, options) {\n if (request.method !== \"POST\") return new Response(\"This endpoint only accepts POST requests.\", { status: 405 });\n let body = await request.text();\n let transport = new BatchServerTransport(body === \"\" ? [] : body.split(\"\\n\"));\n let rpc = new RpcSession$1(transport, localMain, options);\n await transport.whenAllReceived();\n await rpc.drain();\n return new Response(transport.getResponseBody());\n}\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n else this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push([\n \"remap\",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => [\"import\", cap]),\n this.instructions\n ]);\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path,\n devalued\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) return hook.idx;\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else this.context.captures.push(hook);\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n exportStub(hook) {\n throw new Error(\"Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.\");\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot send ReadableStream inside a mapper function.\");\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise$1(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error(\"RPC map() callbacks cannot be async.\");\n }\n return new RpcPromise$1(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\"Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.\");\n}\nvar MapVariableHook = class extends StubHook {\n mapper;\n idx;\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) return this;\n else if (currentMapBuilder) return currentMapBuilder.pushGet(this, path);\n else throwMapperBuilderUseError();\n }\n call(path, args) {\n args.dispose();\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n captures;\n variables;\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n dispose() {\n for (let variable of this.variables) variable.dispose();\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) throw new Error(\"Invalid empty mapper function.\");\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub$1) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) variable.dispose();\n }\n }\n importStub(idx) {\n throw new Error(\"A mapper function cannot refer to exports.\");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) return this.captures[-idx - 1];\n else return this.variables[idx];\n }\n getPipeReadable(exportId) {\n throw new Error(\"A mapper function cannot use pipe readables.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise$1) throw new Error(\"applyMap() can't be called on RpcPromise\");\n else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n } catch (err) {\n for (let payload of payloads) payload.dispose();\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) result = RpcPayload.fromAppReturn(input);\n else result = applyMapToElement(input, parent, owner, captures, instructions);\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) cap.dispose();\n }\n};\nvar WritableStreamStubHook = class WritableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new WritableStreamStubHook2({\n refcount: 1,\n writer: stream.getWriter(),\n closed: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n getState() {\n if (this.state) return this.state;\n else throw new Error(\"Attempted to use a WritableStreamStubHook after it was disposed.\");\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== \"string\") throw new Error(\"WritableStream stub only supports direct method calls\");\n const method = path[0];\n if (method !== \"write\" && method !== \"close\" && method !== \"abort\") throw new Error(`Unknown WritableStream method: ${method}`);\n if (method === \"close\" || method === \"abort\") state.closed = true;\n return new PromiseStubHook((method === \"write\" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a WritableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a WritableStream stub\"));\n }\n dup() {\n return new WritableStreamStubHook2(this.getState(), this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a WritableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.closed) state.writer.abort(/* @__PURE__ */ new Error(\"WritableStream RPC stub was disposed without calling close()\")).catch(() => {\n });\n state.writer.releaseLock();\n }\n }\n }\n onBroken(callback) {\n }\n};\nvar INITIAL_WINDOW = 256 * 1024;\nvar MAX_WINDOW = 1024 * 1024 * 1024;\nvar MIN_WINDOW = 64 * 1024;\nvar STARTUP_GROWTH_FACTOR = 2;\nvar STEADY_GROWTH_FACTOR = 1.25;\nvar DECAY_FACTOR = 0.9;\nvar STARTUP_EXIT_ROUNDS = 3;\nvar FlowController = class {\n now;\n window = INITIAL_WINDOW;\n bytesInFlight = 0;\n inStartupPhase = true;\n delivered = 0;\n deliveredTime = 0;\n firstAckTime = 0;\n firstAckDelivered = 0;\n minRtt = Infinity;\n roundsWithoutIncrease = 0;\n lastRoundWindow = 0;\n roundStartTime = 0;\n constructor(now) {\n this.now = now;\n }\n onSend(size) {\n this.bytesInFlight += size;\n let token = {\n sentTime: this.now(),\n size,\n deliveredAtSend: this.delivered,\n deliveredTimeAtSend: this.deliveredTime,\n windowAtSend: this.window,\n windowFullAtSend: this.bytesInFlight >= this.window\n };\n return {\n token,\n shouldBlock: token.windowFullAtSend\n };\n }\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n onAck(token) {\n let ackTime = this.now();\n this.delivered += token.size;\n this.deliveredTime = ackTime;\n this.bytesInFlight -= token.size;\n let rtt = ackTime - token.sentTime;\n this.minRtt = Math.min(this.minRtt, rtt);\n if (this.firstAckTime === 0) {\n this.firstAckTime = ackTime;\n this.firstAckDelivered = this.delivered;\n } else {\n let baseTime;\n let baseDelivered;\n if (token.deliveredTimeAtSend === 0) {\n baseTime = this.firstAckTime;\n baseDelivered = this.firstAckDelivered;\n } else {\n baseTime = token.deliveredTimeAtSend;\n baseDelivered = token.deliveredAtSend;\n }\n let interval = ackTime - baseTime;\n let bandwidth = (this.delivered - baseDelivered) / interval;\n let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;\n let newWindow = bandwidth * this.minRtt * growthFactor;\n newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);\n if (token.windowFullAtSend) newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n else newWindow = Math.max(newWindow, this.window);\n this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);\n if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {\n if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) this.roundsWithoutIncrease = 0;\n else if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) this.inStartupPhase = false;\n this.roundStartTime = ackTime;\n this.lastRoundWindow = this.window;\n }\n }\n return this.bytesInFlight < this.window;\n }\n};\nfunction createWritableStreamFromHook(hook) {\n let pendingError = void 0;\n let hookDisposed = false;\n let fc = new FlowController(() => performance.now());\n let windowResolve;\n let windowReject;\n const disposeHook = () => {\n if (!hookDisposed) {\n hookDisposed = true;\n hook.dispose();\n }\n };\n return new WritableStream({\n write(chunk, controller) {\n if (pendingError !== void 0) throw pendingError;\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream([\"write\"], payload);\n if (size === void 0) return promise.catch((err) => {\n if (pendingError === void 0) pendingError = err;\n throw err;\n });\n else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n if (fc.onAck(token) && windowResolve) {\n windowResolve();\n windowResolve = void 0;\n windowReject = void 0;\n }\n }, (err) => {\n fc.onError(token);\n if (pendingError === void 0) {\n pendingError = err;\n controller.error(err);\n disposeHook();\n }\n if (windowReject) {\n windowReject(err);\n windowResolve = void 0;\n windowReject = void 0;\n }\n });\n if (shouldBlock) return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\n }\n },\n async close() {\n if (pendingError !== void 0) {\n disposeHook();\n throw pendingError;\n }\n const { promise } = hook.stream([\"close\"], RpcPayload.fromAppParams([]));\n try {\n await promise;\n } catch (err) {\n throw pendingError ?? err;\n } finally {\n disposeHook();\n }\n },\n abort(reason) {\n if (pendingError !== void 0) return;\n pendingError = reason ?? /* @__PURE__ */ new Error(\"WritableStream was aborted\");\n if (windowReject) {\n windowReject(pendingError);\n windowResolve = void 0;\n windowReject = void 0;\n }\n const { promise } = hook.stream([\"abort\"], RpcPayload.fromAppParams([reason]));\n promise.then(() => disposeHook(), () => disposeHook());\n }\n });\n}\nvar ReadableStreamStubHook = class ReadableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new ReadableStreamStubHook2({\n refcount: 1,\n stream,\n canceled: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot call methods on a ReadableStream stub\"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a ReadableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a ReadableStream stub\"));\n }\n dup() {\n let state = this.state;\n if (!state) throw new Error(\"Attempted to dup a ReadableStreamStubHook after it was disposed.\");\n return new ReadableStreamStubHook2(state, this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a ReadableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.canceled) {\n state.canceled = true;\n if (!state.stream.locked) state.stream.cancel(/* @__PURE__ */ new Error(\"ReadableStream RPC stub was disposed without being consumed\")).catch(() => {\n });\n }\n }\n }\n }\n onBroken(callback) {\n }\n};\nstreamImpl.createWritableStreamHook = WritableStreamStubHook.create;\nstreamImpl.createWritableStreamFromHook = createWritableStreamFromHook;\nstreamImpl.createReadableStreamHook = ReadableStreamStubHook.create;\nasync function newWorkersRpcResponse(request, localMain, options) {\n if (request.method === \"POST\") {\n let response = await newHttpBatchRpcResponse(request, localMain, options);\n response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n return response;\n } else if (request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\") return newWorkersWebSocketRpcResponse(request, localMain, options);\n else return new Response(\"This endpoint only accepts POST or WebSocket requests.\", { status: 400 });\n}\n\n// templates/remoteBindings/ProxyServerWorker.ts\nimport { EmailMessage } from \"cloudflare:email\";\nvar BindingNotFoundError = class extends Error {\n constructor(name) {\n super(`Binding ${name ? `\"${name}\"` : \"\"} not found`);\n }\n};\nfunction getExposedJSRPCBinding(request, env) {\n const url = new URL(request.url);\n const bindingName = url.searchParams.get(\"MF-Binding\");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n if (targetBinding.constructor.name === \"Hyperdrive\") {\n const hyperdrive = targetBinding;\n return {\n getConnectionString() {\n return hyperdrive.connectionString;\n },\n connect() {\n const socket = hyperdrive.connect();\n return { readable: socket.readable, writable: socket.writable };\n }\n };\n }\n if (targetBinding.constructor.name === \"AnalyticsEngine\") {\n const dataset = targetBinding;\n return {\n writeDataPoint(event) {\n dataset.writeDataPoint(event);\n }\n };\n }\n if (targetBinding.constructor.name === \"SendEmail\") {\n return {\n async send(e) {\n if (\"EmailMessage::raw\" in e) {\n const message = new EmailMessage(\n e.from,\n e.to,\n e[\"EmailMessage::raw\"]\n );\n return targetBinding.send(message);\n } else {\n return targetBinding.send(e);\n }\n }\n };\n }\n const dispatchNamespaceOptions = url.searchParams.get(\n \"MF-Dispatch-Namespace-Options\"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction getExposedFetcher(request, env) {\n const bindingName = request.headers.get(\"MF-Binding\");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n const dispatchNamespaceOptions = request.headers.get(\n \"MF-Dispatch-Namespace-Options\"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction isJSRPCBinding(request) {\n const url = new URL(request.url);\n return request.headers.has(\"Upgrade\") && url.searchParams.has(\"MF-Binding\");\n}\nfunction isConnectBinding(request) {\n return request.headers.get(\"Upgrade\") === \"websocket\" && request.headers.has(\"MF-Connect-Address\");\n}\nfunction handleConnect(request, env) {\n const address = request.headers.get(\"MF-Connect-Address\");\n if (address === null) {\n return new Response(\"Missing MF-Connect-Address header\", { status: 400 });\n }\n const fetcher = getExposedFetcher(request, env);\n const { 0: client, 1: server } = new WebSocketPair();\n server.accept();\n const socket = fetcher.connect(address);\n pipeSocketOverWebSocket(socket, server).catch(() => {\n });\n return new Response(null, { status: 101, webSocket: client });\n}\nfunction truncateCloseReason(reason) {\n const bytes = new TextEncoder().encode(reason);\n if (bytes.length <= 123) {\n return reason;\n }\n let end = 123;\n while (end > 0 && ((bytes[end] ?? 0) & 192) === 128) {\n end--;\n }\n return new TextDecoder().decode(bytes.subarray(0, end));\n}\nasync function pipeSocketOverWebSocket(socket, ws) {\n const writer = socket.writable.getWriter();\n const reader = socket.readable.getReader();\n let wsClosed = false;\n function closeWebSocket(code, reason) {\n if (wsClosed) {\n return;\n }\n wsClosed = true;\n try {\n ws.close(\n code,\n reason === void 0 ? void 0 : truncateCloseReason(reason)\n );\n } catch {\n }\n }\n let writeChain = Promise.resolve();\n let writerClosed = false;\n function closeWriter() {\n if (writerClosed) {\n return Promise.resolve();\n }\n writerClosed = true;\n return writeChain.then(() => writer.close());\n }\n let resolveFromWs;\n let rejectFromWs;\n const fromWebSocket = new Promise((resolve, reject) => {\n resolveFromWs = resolve;\n rejectFromWs = reject;\n });\n ws.addEventListener(\"message\", (event) => {\n const chunk = typeof event.data === \"string\" ? new TextEncoder().encode(event.data) : new Uint8Array(event.data);\n writeChain = writeChain.then(() => writer.write(chunk)).catch((error) => {\n closeWebSocket(\n 1011,\n error?.message ?? \"socket write failed\"\n );\n reader.cancel().catch(() => {\n });\n rejectFromWs(error);\n });\n });\n ws.addEventListener(\"close\", (event) => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n if (event.code === 1011) {\n rejectFromWs(\n new Error(event.reason || \"Remote tunnel closed with an error\")\n );\n return;\n }\n closeWriter().then(resolveFromWs, rejectFromWs);\n });\n ws.addEventListener(\"error\", () => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n rejectFromWs(new Error(\"Tunnel WebSocket errored\"));\n });\n const toWebSocket = (async () => {\n try {\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n if (wsClosed) {\n break;\n }\n ws.send(\n value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength\n )\n );\n }\n closeWebSocket(1e3);\n } catch (error) {\n closeWebSocket(1011, error?.message ?? \"socket read failed\");\n throw error;\n } finally {\n reader.releaseLock();\n closeWriter().then(resolveFromWs, rejectFromWs);\n }\n })();\n await Promise.all([toWebSocket, fromWebSocket]);\n}\nvar ProxyServerWorker_default = {\n async fetch(request, env) {\n try {\n if (isConnectBinding(request)) {\n return handleConnect(request, env);\n } else if (isJSRPCBinding(request)) {\n return await newWorkersRpcResponse(\n request,\n getExposedJSRPCBinding(request, env)\n );\n } else {\n const fetcher = getExposedFetcher(request, env);\n const originalHeaders = new Headers();\n for (const [name, value] of request.headers) {\n if (name.startsWith(\"mf-header-\")) {\n originalHeaders.set(name.slice(\"mf-header-\".length), value);\n } else if (name === \"upgrade\") {\n originalHeaders.set(name, value);\n }\n }\n return await fetcher.fetch(\n request.headers.get(\"MF-URL\") ?? \"http://example.com\",\n new Request(request, {\n redirect: \"manual\",\n headers: originalHeaders\n })\n );\n }\n } catch (e) {\n if (e instanceof BindingNotFoundError) {\n return new Response(e.message, { status: 400 });\n }\n return new Response(e.message, { status: 500 });\n }\n }\n};\nexport {\n ProxyServerWorker_default as default\n};\n";
|
|
89131
89294
|
let logger;
|
|
89132
89295
|
function initLogger(value) {
|
|
@@ -89990,9 +90153,10 @@ function pickRemoteBindings(bindings) {
|
|
|
89990
90153
|
}
|
|
89991
90154
|
/** Potentially starts or updates a remote proxy session. */
|
|
89992
90155
|
async function maybeStartOrUpdateRemoteProxySession(workerConfigObject, preExistingRemoteProxySessionData, auth, context, startSession = startRemoteProxySession) {
|
|
89993
|
-
const
|
|
90156
|
+
const { hook, key } = auth !== void 0 && "hook" in auth ? auth : { hook: auth };
|
|
90157
|
+
const remoteBindings = pickRemoteBindings(workerConfigObject.target === "cf" ? getRemoteBindings({ env: workerConfigObject.env }) : workerConfigObject.bindings);
|
|
89994
90158
|
if (Object.keys(remoteBindings).length === 0 && !preExistingRemoteProxySessionData?.session) return null;
|
|
89995
|
-
const authSameAsBefore = deepStrictEqual(
|
|
90159
|
+
const authSameAsBefore = key !== void 0 || preExistingRemoteProxySessionData?.authKey !== void 0 ? key === preExistingRemoteProxySessionData?.authKey : deepStrictEqual(hook, preExistingRemoteProxySessionData?.auth);
|
|
89996
90160
|
let remoteProxySession = preExistingRemoteProxySessionData?.session;
|
|
89997
90161
|
if (!authSameAsBefore) {
|
|
89998
90162
|
if (preExistingRemoteProxySessionData?.session) await preExistingRemoteProxySessionData.session.dispose();
|
|
@@ -90000,7 +90164,7 @@ async function maybeStartOrUpdateRemoteProxySession(workerConfigObject, preExist
|
|
|
90000
90164
|
workerName: workerConfigObject.name,
|
|
90001
90165
|
complianceRegion: workerConfigObject.complianceRegion,
|
|
90002
90166
|
cliDisplayName: context.cliDisplayName,
|
|
90003
|
-
auth: getRemoteBindingsAuthHook(
|
|
90167
|
+
auth: getRemoteBindingsAuthHook(hook, workerConfigObject.account_id, workerConfigObject.profileDir, context.logger),
|
|
90004
90168
|
logger: context.logger
|
|
90005
90169
|
});
|
|
90006
90170
|
} else if (!deepStrictEqual(remoteBindings, preExistingRemoteProxySessionData?.remoteBindings)) if (!remoteProxySession) {
|
|
@@ -90008,7 +90172,7 @@ async function maybeStartOrUpdateRemoteProxySession(workerConfigObject, preExist
|
|
|
90008
90172
|
workerName: workerConfigObject.name,
|
|
90009
90173
|
complianceRegion: workerConfigObject.complianceRegion,
|
|
90010
90174
|
cliDisplayName: context.cliDisplayName,
|
|
90011
|
-
auth: getRemoteBindingsAuthHook(
|
|
90175
|
+
auth: getRemoteBindingsAuthHook(hook, workerConfigObject.account_id, workerConfigObject.profileDir, context.logger),
|
|
90012
90176
|
logger: context.logger
|
|
90013
90177
|
});
|
|
90014
90178
|
} else await remoteProxySession.updateBindings(remoteBindings);
|
|
@@ -90017,7 +90181,8 @@ async function maybeStartOrUpdateRemoteProxySession(workerConfigObject, preExist
|
|
|
90017
90181
|
return {
|
|
90018
90182
|
session: remoteProxySession,
|
|
90019
90183
|
remoteBindings,
|
|
90020
|
-
auth
|
|
90184
|
+
auth: hook,
|
|
90185
|
+
authKey: key
|
|
90021
90186
|
};
|
|
90022
90187
|
}
|
|
90023
90188
|
function deepStrictEqual(source, target$1) {
|
|
@@ -90029,270 +90194,6 @@ function deepStrictEqual(source, target$1) {
|
|
|
90029
90194
|
}
|
|
90030
90195
|
}
|
|
90031
90196
|
|
|
90032
|
-
//#endregion
|
|
90033
|
-
//#region src/local-env.ts
|
|
90034
|
-
/**
|
|
90035
|
-
* Resolves local binding values from the loaded local env. This replaces
|
|
90036
|
-
* declared secret placeholders with text bindings and applies Hyperdrive
|
|
90037
|
-
* connection-string overrides. Missing secrets are omitted so Miniflare
|
|
90038
|
-
* doesn't receive an unresolved deployment-only placeholder.
|
|
90039
|
-
*
|
|
90040
|
-
* @param configuredBindings The Worker's configured bindings.
|
|
90041
|
-
* @param localEnv Values resolved from `.env` files and the process environment.
|
|
90042
|
-
* @param devVars Values from the selected `.dev.vars` file, which are used exclusively when provided.
|
|
90043
|
-
* @param remoteBindings Whether remote binding sessions are enabled.
|
|
90044
|
-
* @returns The complete bindings and any secrets missing a local value.
|
|
90045
|
-
*/
|
|
90046
|
-
function resolveLocalBindings(configuredBindings, localEnv, devVars, remoteBindings = true) {
|
|
90047
|
-
const bindings = {};
|
|
90048
|
-
const missingSecrets = [];
|
|
90049
|
-
const localValues = devVars ?? localEnv;
|
|
90050
|
-
for (const [name, binding] of Object.entries(configuredBindings ?? {})) {
|
|
90051
|
-
if (binding.type === "hyperdrive") {
|
|
90052
|
-
if (binding.dev?.remote && remoteBindings) {
|
|
90053
|
-
bindings[name] = {
|
|
90054
|
-
...binding,
|
|
90055
|
-
dev: binding.dev
|
|
90056
|
-
};
|
|
90057
|
-
continue;
|
|
90058
|
-
}
|
|
90059
|
-
const connectionString = localEnv[`CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_${name}`] || binding.dev?.connectionString;
|
|
90060
|
-
if (connectionString === void 0) throw new Error(`Hyperdrive binding "${name}" must define dev.connectionString for local development.`);
|
|
90061
|
-
bindings[name] = {
|
|
90062
|
-
...binding,
|
|
90063
|
-
dev: {
|
|
90064
|
-
...binding.dev,
|
|
90065
|
-
connectionString
|
|
90066
|
-
}
|
|
90067
|
-
};
|
|
90068
|
-
continue;
|
|
90069
|
-
}
|
|
90070
|
-
if (binding.type === "secret") {
|
|
90071
|
-
const localValue = localValues[name];
|
|
90072
|
-
if (localValue !== void 0) bindings[name] = {
|
|
90073
|
-
type: "text",
|
|
90074
|
-
value: localValue
|
|
90075
|
-
};
|
|
90076
|
-
else missingSecrets.push(name);
|
|
90077
|
-
continue;
|
|
90078
|
-
}
|
|
90079
|
-
bindings[name] = binding;
|
|
90080
|
-
}
|
|
90081
|
-
return {
|
|
90082
|
-
bindings,
|
|
90083
|
-
missingSecrets
|
|
90084
|
-
};
|
|
90085
|
-
}
|
|
90086
|
-
|
|
90087
|
-
//#endregion
|
|
90088
|
-
//#region src/remote-bindings.ts
|
|
90089
|
-
/**
|
|
90090
|
-
* Convert native config bindings to the transport shape consumed by the
|
|
90091
|
-
* remote-bindings session API. Local-only bindings are intentionally omitted.
|
|
90092
|
-
*/
|
|
90093
|
-
function getRemoteBindings(config$3) {
|
|
90094
|
-
const bindings = {};
|
|
90095
|
-
for (const [name, binding] of Object.entries(config$3.env ?? {})) switch (binding.type) {
|
|
90096
|
-
case "agent-memory":
|
|
90097
|
-
bindings[name] = {
|
|
90098
|
-
type: "agent_memory",
|
|
90099
|
-
namespace: binding.namespace,
|
|
90100
|
-
remote: binding.dev?.remote
|
|
90101
|
-
};
|
|
90102
|
-
break;
|
|
90103
|
-
case "ai":
|
|
90104
|
-
bindings[name] = {
|
|
90105
|
-
type: "ai",
|
|
90106
|
-
remote: binding.dev?.remote
|
|
90107
|
-
};
|
|
90108
|
-
break;
|
|
90109
|
-
case "analytics":
|
|
90110
|
-
bindings[name] = {
|
|
90111
|
-
type: "analytics",
|
|
90112
|
-
remote: binding.dev?.remote
|
|
90113
|
-
};
|
|
90114
|
-
break;
|
|
90115
|
-
case "analytics-engine-dataset":
|
|
90116
|
-
bindings[name] = {
|
|
90117
|
-
type: "analytics_engine",
|
|
90118
|
-
dataset: binding.name,
|
|
90119
|
-
remote: binding.dev?.remote
|
|
90120
|
-
};
|
|
90121
|
-
break;
|
|
90122
|
-
case "ai-search":
|
|
90123
|
-
bindings[name] = {
|
|
90124
|
-
type: "ai_search",
|
|
90125
|
-
instance_name: binding.name,
|
|
90126
|
-
remote: binding.dev?.remote
|
|
90127
|
-
};
|
|
90128
|
-
break;
|
|
90129
|
-
case "ai-search-namespace":
|
|
90130
|
-
bindings[name] = {
|
|
90131
|
-
type: "ai_search_namespace",
|
|
90132
|
-
namespace: binding.namespace,
|
|
90133
|
-
remote: binding.dev?.remote
|
|
90134
|
-
};
|
|
90135
|
-
break;
|
|
90136
|
-
case "artifacts":
|
|
90137
|
-
bindings[name] = {
|
|
90138
|
-
type: "artifacts",
|
|
90139
|
-
namespace: binding.namespace,
|
|
90140
|
-
remote: binding.dev?.remote
|
|
90141
|
-
};
|
|
90142
|
-
break;
|
|
90143
|
-
case "browser":
|
|
90144
|
-
bindings[name] = {
|
|
90145
|
-
type: "browser",
|
|
90146
|
-
remote: binding.dev?.remote
|
|
90147
|
-
};
|
|
90148
|
-
break;
|
|
90149
|
-
case "d1":
|
|
90150
|
-
bindings[name] = {
|
|
90151
|
-
type: "d1",
|
|
90152
|
-
database_id: binding.id,
|
|
90153
|
-
database_name: binding.name,
|
|
90154
|
-
remote: binding.dev?.remote
|
|
90155
|
-
};
|
|
90156
|
-
break;
|
|
90157
|
-
case "dispatch-namespace":
|
|
90158
|
-
bindings[name] = {
|
|
90159
|
-
type: "dispatch_namespace",
|
|
90160
|
-
namespace: binding.namespace,
|
|
90161
|
-
outbound: binding.outbound ? {
|
|
90162
|
-
service: binding.outbound.worker,
|
|
90163
|
-
parameters: binding.outbound.parameters
|
|
90164
|
-
} : void 0,
|
|
90165
|
-
remote: binding.dev?.remote
|
|
90166
|
-
};
|
|
90167
|
-
break;
|
|
90168
|
-
case "flagship":
|
|
90169
|
-
bindings[name] = {
|
|
90170
|
-
type: "flagship",
|
|
90171
|
-
app_id: binding.id,
|
|
90172
|
-
remote: binding.dev?.remote
|
|
90173
|
-
};
|
|
90174
|
-
break;
|
|
90175
|
-
case "hyperdrive":
|
|
90176
|
-
bindings[name] = {
|
|
90177
|
-
type: "hyperdrive",
|
|
90178
|
-
id: binding.id,
|
|
90179
|
-
remote: binding.dev?.remote
|
|
90180
|
-
};
|
|
90181
|
-
break;
|
|
90182
|
-
case "images":
|
|
90183
|
-
bindings[name] = {
|
|
90184
|
-
type: "images",
|
|
90185
|
-
remote: binding.dev?.remote
|
|
90186
|
-
};
|
|
90187
|
-
break;
|
|
90188
|
-
case "kv":
|
|
90189
|
-
bindings[name] = {
|
|
90190
|
-
type: "kv_namespace",
|
|
90191
|
-
id: binding.id,
|
|
90192
|
-
remote: binding.dev?.remote
|
|
90193
|
-
};
|
|
90194
|
-
break;
|
|
90195
|
-
case "media":
|
|
90196
|
-
bindings[name] = {
|
|
90197
|
-
type: "media",
|
|
90198
|
-
remote: binding.dev?.remote
|
|
90199
|
-
};
|
|
90200
|
-
break;
|
|
90201
|
-
case "mtls-certificate":
|
|
90202
|
-
bindings[name] = {
|
|
90203
|
-
type: "mtls_certificate",
|
|
90204
|
-
certificate_id: binding.id,
|
|
90205
|
-
remote: binding.dev?.remote
|
|
90206
|
-
};
|
|
90207
|
-
break;
|
|
90208
|
-
case "pipeline":
|
|
90209
|
-
bindings[name] = {
|
|
90210
|
-
type: "pipeline",
|
|
90211
|
-
stream: binding.name,
|
|
90212
|
-
remote: binding.dev?.remote
|
|
90213
|
-
};
|
|
90214
|
-
break;
|
|
90215
|
-
case "k2":
|
|
90216
|
-
bindings[name] = {
|
|
90217
|
-
type: "k2",
|
|
90218
|
-
stream: binding.stream,
|
|
90219
|
-
remote: binding.dev?.remote
|
|
90220
|
-
};
|
|
90221
|
-
break;
|
|
90222
|
-
case "queue":
|
|
90223
|
-
bindings[name] = {
|
|
90224
|
-
type: "queue",
|
|
90225
|
-
queue_name: binding.name,
|
|
90226
|
-
delivery_delay: binding.deliveryDelay,
|
|
90227
|
-
remote: binding.dev?.remote
|
|
90228
|
-
};
|
|
90229
|
-
break;
|
|
90230
|
-
case "r2":
|
|
90231
|
-
bindings[name] = {
|
|
90232
|
-
type: "r2_bucket",
|
|
90233
|
-
bucket_name: binding.name,
|
|
90234
|
-
jurisdiction: binding.jurisdiction,
|
|
90235
|
-
remote: binding.dev?.remote
|
|
90236
|
-
};
|
|
90237
|
-
break;
|
|
90238
|
-
case "send-email": {
|
|
90239
|
-
const shared = {
|
|
90240
|
-
type: "send_email",
|
|
90241
|
-
allowed_sender_addresses: binding.allowedSenderAddresses,
|
|
90242
|
-
remote: binding.dev?.remote
|
|
90243
|
-
};
|
|
90244
|
-
if (binding.destinationAddress !== void 0) bindings[name] = {
|
|
90245
|
-
...shared,
|
|
90246
|
-
destination_address: binding.destinationAddress
|
|
90247
|
-
};
|
|
90248
|
-
else if (binding.allowedDestinationAddresses !== void 0) bindings[name] = {
|
|
90249
|
-
...shared,
|
|
90250
|
-
allowed_destination_addresses: binding.allowedDestinationAddresses
|
|
90251
|
-
};
|
|
90252
|
-
else bindings[name] = shared;
|
|
90253
|
-
break;
|
|
90254
|
-
}
|
|
90255
|
-
case "stream":
|
|
90256
|
-
bindings[name] = {
|
|
90257
|
-
type: "stream",
|
|
90258
|
-
remote: binding.dev?.remote
|
|
90259
|
-
};
|
|
90260
|
-
break;
|
|
90261
|
-
case "vectorize":
|
|
90262
|
-
bindings[name] = {
|
|
90263
|
-
type: "vectorize",
|
|
90264
|
-
index_name: binding.name,
|
|
90265
|
-
remote: binding.dev?.remote
|
|
90266
|
-
};
|
|
90267
|
-
break;
|
|
90268
|
-
case "vpc-network":
|
|
90269
|
-
bindings[name] = {
|
|
90270
|
-
type: "vpc_network",
|
|
90271
|
-
tunnel_id: binding.tunnelId,
|
|
90272
|
-
network_id: binding.networkId,
|
|
90273
|
-
remote: binding.dev?.remote
|
|
90274
|
-
};
|
|
90275
|
-
break;
|
|
90276
|
-
case "vpc-service":
|
|
90277
|
-
bindings[name] = {
|
|
90278
|
-
type: "vpc_service",
|
|
90279
|
-
service_id: binding.id,
|
|
90280
|
-
remote: binding.dev?.remote
|
|
90281
|
-
};
|
|
90282
|
-
break;
|
|
90283
|
-
case "worker":
|
|
90284
|
-
bindings[name] = {
|
|
90285
|
-
type: "service",
|
|
90286
|
-
service: binding.worker,
|
|
90287
|
-
entrypoint: binding.exportName,
|
|
90288
|
-
props: binding.props,
|
|
90289
|
-
remote: binding.dev?.remote
|
|
90290
|
-
};
|
|
90291
|
-
break;
|
|
90292
|
-
}
|
|
90293
|
-
return bindings;
|
|
90294
|
-
}
|
|
90295
|
-
|
|
90296
90197
|
//#endregion
|
|
90297
90198
|
//#region src/update-check.ts
|
|
90298
90199
|
let updateCheckPromise;
|
|
@@ -90409,8 +90310,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
|
|
|
90409
90310
|
const inputInspectorPort = await getInputInspectorPort(ctx, viteDevServer);
|
|
90410
90311
|
const { resolvedPluginConfig, resolvedViteConfig, entryWorkerConfig } = ctx;
|
|
90411
90312
|
const assetsConfig = getAssetsConfig(resolvedPluginConfig, entryWorkerConfig, resolvedViteConfig);
|
|
90412
|
-
const resolvedLocalBindingsByWorkerName = resolveLocalBindingsByWorkerName(ctx.allWorkerConfigs, resolvedPluginConfig.localEnv, resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings);
|
|
90413
|
-
warnForMissingSecrets(resolvedLocalBindingsByWorkerName, resolvedViteConfig.mode, viteDevServer.config.logger);
|
|
90313
|
+
const resolvedLocalBindingsByWorkerName = resolveLocalBindingsByWorkerName(ctx.allWorkerConfigs, resolvedPluginConfig.localEnv, resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings, resolvedViteConfig.mode, viteDevServer.config.logger);
|
|
90414
90314
|
const [routerWorkerManifest, assetWorkerManifest, viteProxyWorkerManifest] = await Promise.all([
|
|
90415
90315
|
getInternalWorkerManifest(ROUTER_WORKER_PATH),
|
|
90416
90316
|
getInternalWorkerManifest(ASSET_WORKER_PATH),
|
|
@@ -90544,16 +90444,16 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
|
|
|
90544
90444
|
}
|
|
90545
90445
|
const containerEngine = containerPlansByWorkerName.size === 0 ? void 0 : resolveDockerHost(getDockerPath());
|
|
90546
90446
|
const userWorkers = resolvedPluginConfig.type === "workers" ? await Promise.all([...resolvedPluginConfig.environmentNameToWorkerMap].map(async ([environmentName, worker]) => {
|
|
90547
|
-
const bindings = getRemoteBindings(worker.config);
|
|
90548
90447
|
const preExistingRemoteProxySession = remoteProxySessionsDataMap.get(worker.config.name);
|
|
90549
90448
|
const settings = resolvedPluginConfig.settings;
|
|
90550
90449
|
const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await maybeStartOrUpdateRemoteProxySession({
|
|
90551
90450
|
name: worker.config.name,
|
|
90552
|
-
|
|
90451
|
+
target: "cf",
|
|
90452
|
+
env: worker.config.env,
|
|
90553
90453
|
complianceRegion: toApiComplianceRegion(settings.complianceRegion),
|
|
90554
90454
|
account_id: settings.accountId,
|
|
90555
90455
|
profileDir: resolvedViteConfig.root
|
|
90556
|
-
}, preExistingRemoteProxySession ?? null, getRemoteBindingsAuth(
|
|
90456
|
+
}, preExistingRemoteProxySession ?? null, getRemoteBindingsAuth(resolvedViteConfig.root, settings.accountId, createLogger(viteDevServer.config.logger)), {
|
|
90557
90457
|
cliDisplayName: resolvedPluginConfig.cliDisplayName,
|
|
90558
90458
|
logger: createRemoteBindingsLogger(viteDevServer.config.logger)
|
|
90559
90459
|
});
|
|
@@ -90569,7 +90469,7 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
|
|
|
90569
90469
|
const { entrypoint: _entrypoint, assets: _assets,...config$3 } = worker.config;
|
|
90570
90470
|
const resolvedLocalBindings = resolvedLocalBindingsByWorkerName.get(worker.config.name);
|
|
90571
90471
|
assert(resolvedLocalBindings);
|
|
90572
|
-
const env$3 = { ...resolvedLocalBindings
|
|
90472
|
+
const env$3 = { ...resolvedLocalBindings };
|
|
90573
90473
|
for (const [name, binding] of Object.entries(env$3)) if (binding.type === "assets") env$3[name] = {
|
|
90574
90474
|
type: "node-handler",
|
|
90575
90475
|
handler: (req, res) => {
|
|
@@ -90702,8 +90602,7 @@ async function getMiniflareManifest(bundle) {
|
|
|
90702
90602
|
async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
|
|
90703
90603
|
const inputInspectorPort = await getInputInspectorPort(ctx, vitePreviewServer);
|
|
90704
90604
|
const { resolvedPluginConfig, resolvedViteConfig } = ctx;
|
|
90705
|
-
const resolvedLocalBindingsByWorkerName = resolveLocalBindingsByWorkerName(ctx.allWorkerConfigs, resolvedPluginConfig.localEnv, resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings);
|
|
90706
|
-
warnForMissingSecrets(resolvedLocalBindingsByWorkerName, resolvedViteConfig.mode, vitePreviewServer.config.logger);
|
|
90605
|
+
const resolvedLocalBindingsByWorkerName = resolveLocalBindingsByWorkerName(ctx.allWorkerConfigs, resolvedPluginConfig.localEnv, resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings, resolvedViteConfig.mode, vitePreviewServer.config.logger);
|
|
90707
90606
|
const containerPlansByWorkerName = /* @__PURE__ */ new Map();
|
|
90708
90607
|
const containerOptions = [];
|
|
90709
90608
|
for (const previewWorker of resolvedPluginConfig.workers) {
|
|
@@ -90719,15 +90618,15 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
|
|
|
90719
90618
|
const containerEngine = containerPlansByWorkerName.size === 0 ? void 0 : resolveDockerHost(getDockerPath());
|
|
90720
90619
|
const workers = await Promise.all(resolvedPluginConfig.workers.map(async (previewWorker) => {
|
|
90721
90620
|
const workerConfig = previewWorker.config;
|
|
90722
|
-
const bindings = getRemoteBindings(workerConfig);
|
|
90723
90621
|
const preExistingRemoteProxySessionData = remoteProxySessionsDataMap.get(workerConfig.name);
|
|
90724
90622
|
const remoteProxySessionData = !resolvedPluginConfig.remoteBindings ? null : await maybeStartOrUpdateRemoteProxySession({
|
|
90725
90623
|
name: workerConfig.name,
|
|
90726
|
-
|
|
90624
|
+
target: "cf",
|
|
90625
|
+
env: workerConfig.env,
|
|
90727
90626
|
complianceRegion: toApiComplianceRegion(resolvedPluginConfig.settings.complianceRegion),
|
|
90728
90627
|
account_id: resolvedPluginConfig.settings.accountId,
|
|
90729
90628
|
profileDir: resolvedViteConfig.root
|
|
90730
|
-
}, preExistingRemoteProxySessionData ?? null, getRemoteBindingsAuth(
|
|
90629
|
+
}, preExistingRemoteProxySessionData ?? null, getRemoteBindingsAuth(resolvedViteConfig.root, resolvedPluginConfig.settings.accountId, createLogger(vitePreviewServer.config.logger)), {
|
|
90731
90630
|
cliDisplayName: resolvedPluginConfig.cliDisplayName,
|
|
90732
90631
|
logger: createRemoteBindingsLogger(vitePreviewServer.config.logger)
|
|
90733
90632
|
});
|
|
@@ -90735,7 +90634,7 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
|
|
|
90735
90634
|
const { manifest: _manifest, assets, exports: exports$1,...config$3 } = workerConfig;
|
|
90736
90635
|
const resolvedLocalBindings = resolvedLocalBindingsByWorkerName.get(workerConfig.name);
|
|
90737
90636
|
assert(resolvedLocalBindings);
|
|
90738
|
-
const env$3 = { ...resolvedLocalBindings
|
|
90637
|
+
const env$3 = { ...resolvedLocalBindings };
|
|
90739
90638
|
const workerExports = createMiniflareExports({
|
|
90740
90639
|
exports: exports$1,
|
|
90741
90640
|
containerRuntimeOptions: containerPlansByWorkerName.get(workerConfig.name)?.containerRuntimeOptions
|
|
@@ -90805,17 +90704,18 @@ function createMiniflareExports(options) {
|
|
|
90805
90704
|
} else workerExports[name] = workerExport;
|
|
90806
90705
|
return workerExports;
|
|
90807
90706
|
}
|
|
90808
|
-
function resolveLocalBindingsByWorkerName(workerConfigs, localEnv, devVars, remoteBindings) {
|
|
90707
|
+
function resolveLocalBindingsByWorkerName(workerConfigs, localEnv, devVars, remoteBindings, mode, logger$2) {
|
|
90809
90708
|
const resolvedLocalBindingsByWorkerName = /* @__PURE__ */ new Map();
|
|
90810
|
-
for (const config$3 of workerConfigs) resolvedLocalBindingsByWorkerName.set(config$3.name, resolveLocalBindings(config$3.env,
|
|
90709
|
+
for (const config$3 of workerConfigs) resolvedLocalBindingsByWorkerName.set(config$3.name, resolveLocalBindings(config$3.env, {
|
|
90710
|
+
workerName: config$3.name,
|
|
90711
|
+
localEnv: localEnv.values,
|
|
90712
|
+
devVars,
|
|
90713
|
+
mode,
|
|
90714
|
+
remoteBindings,
|
|
90715
|
+
logger: logger$2
|
|
90716
|
+
}));
|
|
90811
90717
|
return resolvedLocalBindingsByWorkerName;
|
|
90812
90718
|
}
|
|
90813
|
-
function warnForMissingSecrets(resolvedLocalBindingsByWorkerName, mode, logger$2) {
|
|
90814
|
-
for (const [workerName, { missingSecrets }] of resolvedLocalBindingsByWorkerName) {
|
|
90815
|
-
if (missingSecrets.length === 0) continue;
|
|
90816
|
-
logger$2.warn(`Missing required secrets for Worker "${workerName}": ${missingSecrets.join(", ")}. Add them to one of \`.dev.vars.${mode}\`, \`.dev.vars\`, \`.env.${mode}.local\`, \`.env.${mode}\`, \`.env.local\`, or \`.env\`. Alternatively, set them as environment variables.`);
|
|
90817
|
-
}
|
|
90818
|
-
}
|
|
90819
90719
|
/**
|
|
90820
90720
|
* A Miniflare logger that forwards messages onto a Vite logger.
|
|
90821
90721
|
*/
|