@cloudflare/vite-plugin 1.46.0 → 1.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +180 -75
- package/dist/index.mjs.map +1 -1
- package/dist/{package-Cjez0K_t.mjs → package-CkWRIieu.mjs} +2 -2
- package/dist/{package-Cjez0K_t.mjs.map → package-CkWRIieu.mjs.map} +1 -1
- package/dist/workers/runner-worker/index.js +11 -5
- package/dist/workers/runner-worker/module-runner.js +20 -16
- package/package.json +13 -13
package/dist/index.mjs
CHANGED
|
@@ -1486,7 +1486,7 @@ async function assertWranglerVersion() {
|
|
|
1486
1486
|
* The default compatibility date to use when the user omits one.
|
|
1487
1487
|
* This value is injected at build time and remains fixed for each release.
|
|
1488
1488
|
*/
|
|
1489
|
-
const DEFAULT_COMPAT_DATE = "2026-07-
|
|
1489
|
+
const DEFAULT_COMPAT_DATE = "2026-07-28";
|
|
1490
1490
|
|
|
1491
1491
|
//#endregion
|
|
1492
1492
|
//#region src/build-output-env.ts
|
|
@@ -2038,7 +2038,7 @@ function getGlobalWranglerCachePath() {
|
|
|
2038
2038
|
__name$3(getGlobalWranglerCachePath, "getGlobalWranglerCachePath");
|
|
2039
2039
|
|
|
2040
2040
|
//#endregion
|
|
2041
|
-
//#region ../workers-utils/dist/chunk-
|
|
2041
|
+
//#region ../workers-utils/dist/chunk-3K53PSCY.mjs
|
|
2042
2042
|
function partitionExports$1(exports$2) {
|
|
2043
2043
|
const partitioned = {
|
|
2044
2044
|
"durable-object": {},
|
|
@@ -4048,10 +4048,16 @@ var APIError = class extends ParseError {
|
|
|
4048
4048
|
* endpoint-specific structured error payloads.
|
|
4049
4049
|
*/
|
|
4050
4050
|
meta;
|
|
4051
|
-
|
|
4051
|
+
/**
|
|
4052
|
+
* Optional number of milliseconds the API asked us to wait before retrying,
|
|
4053
|
+
* derived from the response's `Retry-After` header (if present).
|
|
4054
|
+
*/
|
|
4055
|
+
retryAfterMs;
|
|
4056
|
+
constructor({ status: status$1, retryAfterMs,...rest }) {
|
|
4052
4057
|
super(rest);
|
|
4053
4058
|
this.name = this.constructor.name;
|
|
4054
4059
|
this.#status = status$1;
|
|
4060
|
+
this.retryAfterMs = retryAfterMs;
|
|
4055
4061
|
}
|
|
4056
4062
|
get status() {
|
|
4057
4063
|
return this.#status;
|
|
@@ -41608,6 +41614,10 @@ var getLocalExplorerEnabledFromEnv = getBooleanEnvironmentVariableFactory({
|
|
|
41608
41614
|
variableName: "X_LOCAL_EXPLORER",
|
|
41609
41615
|
defaultValue: true
|
|
41610
41616
|
});
|
|
41617
|
+
var getLocalObservabilityEnabledFromEnv = getBooleanEnvironmentVariableFactory({
|
|
41618
|
+
variableName: "X_LOCAL_OBSERVABILITY",
|
|
41619
|
+
defaultValue: false
|
|
41620
|
+
});
|
|
41611
41621
|
var getBrowserRenderingHeadfulFromEnv = getBooleanEnvironmentVariableFactory({
|
|
41612
41622
|
variableName: "X_BROWSER_HEADFUL",
|
|
41613
41623
|
defaultValue: false
|
|
@@ -41978,12 +41988,13 @@ function isPagesConfig(rawConfig) {
|
|
|
41978
41988
|
__name$3(isPagesConfig, "isPagesConfig");
|
|
41979
41989
|
function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args, preserveOriginalMain = false) {
|
|
41980
41990
|
const diagnostics = new Diagnostics(`Processing ${configPath ? path2__default.relative(process.cwd(), configPath) : "wrangler"} configuration:`);
|
|
41991
|
+
const isRedirectedConfig2 = isRedirectedRawConfig$1(rawConfig, configPath, userConfigPath);
|
|
41981
41992
|
if ("legacy_env" in rawConfig) {
|
|
41982
|
-
diagnostics.errors.push(dedent$1`
|
|
41983
|
-
|
|
41984
|
-
|
|
41985
|
-
|
|
41986
|
-
|
|
41993
|
+
if (!isRedirectedConfig2) diagnostics.errors.push(dedent$1`
|
|
41994
|
+
The "legacy_env" field is no longer supported, so please remove it from your configuration file.
|
|
41995
|
+
Service environments have been removed, and each environment is now deployed as its own Worker named "<name>-<environment>". This matches the behaviour of "legacy_env = true", which was the default, so removing the field will not change how your Worker is deployed.
|
|
41996
|
+
Refer to https://developers.cloudflare.com/workers/wrangler/environments/ for more information.
|
|
41997
|
+
`);
|
|
41987
41998
|
delete rawConfig.legacy_env;
|
|
41988
41999
|
}
|
|
41989
42000
|
validateOptionalProperty(diagnostics, "", "send_metrics", rawConfig.send_metrics, "boolean");
|
|
@@ -42000,7 +42011,6 @@ function normalizeAndValidateConfig(rawConfig, configPath, userConfigPath, args,
|
|
|
42000
42011
|
validateOptionalProperty(diagnostics, "", "$schema", rawConfig.$schema, "string");
|
|
42001
42012
|
const isDispatchNamespace = typeof args["dispatch-namespace"] === "string" && args["dispatch-namespace"].trim() !== "";
|
|
42002
42013
|
const topLevelEnv = normalizeAndValidateEnvironment(diagnostics, configPath, rawConfig, isDispatchNamespace, preserveOriginalMain);
|
|
42003
|
-
const isRedirectedConfig2 = isRedirectedRawConfig$1(rawConfig, configPath, userConfigPath);
|
|
42004
42014
|
const definedEnvironments = Object.keys(rawConfig.env ?? {});
|
|
42005
42015
|
if (isRedirectedConfig2 && definedEnvironments.length > 0) diagnostics.errors.push(dedent$1`
|
|
42006
42016
|
Redirected configurations cannot include environments but the following have been found:\n${definedEnvironments.map((env$3) => ` - ${env$3}`).join("\n")}
|
|
@@ -43309,12 +43319,30 @@ var validateR2Binding = /* @__PURE__ */ __name$3((diagnostics, field, value) =>
|
|
|
43309
43319
|
isValid$1 = false;
|
|
43310
43320
|
}
|
|
43311
43321
|
if (!isRemoteValid(value, field, diagnostics)) isValid$1 = false;
|
|
43322
|
+
if (hasProperty(value, "local_dev")) {
|
|
43323
|
+
const localDev = value.local_dev;
|
|
43324
|
+
if (typeof localDev !== "object" || localDev === null) {
|
|
43325
|
+
diagnostics.errors.push(`"${field}" bindings should, optionally, have an object "local_dev" field but got ${JSON.stringify(value)}.`);
|
|
43326
|
+
isValid$1 = false;
|
|
43327
|
+
} else {
|
|
43328
|
+
experimental(diagnostics, { local_dev: localDev }, "local_dev.experimental_s3_credentials");
|
|
43329
|
+
if (hasProperty(localDev, "experimental_s3_credentials")) {
|
|
43330
|
+
const credentials = localDev.experimental_s3_credentials;
|
|
43331
|
+
if (typeof credentials !== "object" || credentials === null || !isRequiredProperty(credentials, "accessKeyId", "string") || !isRequiredProperty(credentials, "secretAccessKey", "string")) {
|
|
43332
|
+
diagnostics.errors.push(`"${field}" bindings should, optionally, have a "local_dev.experimental_s3_credentials" field with string "accessKeyId" and "secretAccessKey" fields, but got ${JSON.stringify(value)}.`);
|
|
43333
|
+
isValid$1 = false;
|
|
43334
|
+
}
|
|
43335
|
+
}
|
|
43336
|
+
validateAdditionalProperties(diagnostics, `${field}.local_dev`, Object.keys(localDev), ["experimental_s3_credentials"]);
|
|
43337
|
+
}
|
|
43338
|
+
}
|
|
43312
43339
|
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
|
|
43313
43340
|
"binding",
|
|
43314
43341
|
"bucket_name",
|
|
43315
43342
|
"preview_bucket_name",
|
|
43316
43343
|
"jurisdiction",
|
|
43317
|
-
"remote"
|
|
43344
|
+
"remote",
|
|
43345
|
+
"local_dev"
|
|
43318
43346
|
]);
|
|
43319
43347
|
return isValid$1;
|
|
43320
43348
|
}, "validateR2Binding");
|
|
@@ -45459,6 +45487,7 @@ async function fetchInternalBase(complianceConfig, resource, init = {}, userAgen
|
|
|
45459
45487
|
logHeaders(response.headers, logger$1);
|
|
45460
45488
|
logger$1.debugWithSanitization?.("RESPONSE:", jsonText);
|
|
45461
45489
|
logger$1.debug("-- END CF API RESPONSE");
|
|
45490
|
+
const retryAfterMs = parseRetryAfterMs(response.headers);
|
|
45462
45491
|
if (!jsonText && (response.status === 204 || response.status === 205)) return {
|
|
45463
45492
|
response: {
|
|
45464
45493
|
result: {},
|
|
@@ -45466,13 +45495,15 @@ async function fetchInternalBase(complianceConfig, resource, init = {}, userAgen
|
|
|
45466
45495
|
errors: [],
|
|
45467
45496
|
messages: []
|
|
45468
45497
|
},
|
|
45469
|
-
status: response.status
|
|
45498
|
+
status: response.status,
|
|
45499
|
+
retryAfterMs
|
|
45470
45500
|
};
|
|
45471
|
-
if (isWAFBlockResponse(response.headers)) throwWAFBlockError(response.headers, method, resource, response.status, response.statusText);
|
|
45501
|
+
if (isWAFBlockResponse(response.headers)) throwWAFBlockError(response.headers, method, resource, response.status, response.statusText, retryAfterMs);
|
|
45472
45502
|
try {
|
|
45473
45503
|
return {
|
|
45474
45504
|
response: parseJSON(jsonText),
|
|
45475
|
-
status: response.status
|
|
45505
|
+
status: response.status,
|
|
45506
|
+
retryAfterMs
|
|
45476
45507
|
};
|
|
45477
45508
|
} catch {
|
|
45478
45509
|
const rayId = extractWAFBlockRayId(response.headers);
|
|
@@ -45484,15 +45515,16 @@ async function fetchInternalBase(complianceConfig, resource, init = {}, userAgen
|
|
|
45484
45515
|
...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : []
|
|
45485
45516
|
],
|
|
45486
45517
|
status: response.status,
|
|
45518
|
+
retryAfterMs,
|
|
45487
45519
|
telemetryMessage: false
|
|
45488
45520
|
});
|
|
45489
45521
|
}
|
|
45490
45522
|
}
|
|
45491
45523
|
__name$3(fetchInternalBase, "fetchInternalBase");
|
|
45492
45524
|
async function fetchResultBase(complianceConfig, resource, init = {}, userAgent, logger$1, queryParams, abortSignal, credentials) {
|
|
45493
|
-
const { response: json2, status: status$1 } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$1, queryParams, abortSignal, credentials);
|
|
45525
|
+
const { response: json2, status: status$1, retryAfterMs } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$1, queryParams, abortSignal, credentials);
|
|
45494
45526
|
if (json2.success) return json2.result;
|
|
45495
|
-
else throwFetchError(resource, json2, status$1);
|
|
45527
|
+
else throwFetchError(resource, json2, status$1, retryAfterMs);
|
|
45496
45528
|
}
|
|
45497
45529
|
__name$3(fetchResultBase, "fetchResultBase");
|
|
45498
45530
|
async function fetchListResultBase(complianceConfig, resource, init = {}, userAgent, logger$1, queryParams, credentials) {
|
|
@@ -45504,12 +45536,12 @@ async function fetchListResultBase(complianceConfig, resource, init = {}, userAg
|
|
|
45504
45536
|
queryParams = new URLSearchParams$1(queryParams);
|
|
45505
45537
|
queryParams.set("cursor", cursor$1);
|
|
45506
45538
|
}
|
|
45507
|
-
const { response: json2, status: status$1 } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$1, queryParams, void 0, credentials);
|
|
45539
|
+
const { response: json2, status: status$1, retryAfterMs } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$1, queryParams, void 0, credentials);
|
|
45508
45540
|
if (json2.success) {
|
|
45509
45541
|
results.push(...json2.result);
|
|
45510
45542
|
if (hasCursor(json2.result_info)) cursor$1 = json2.result_info?.cursor;
|
|
45511
45543
|
else getMoreResults = false;
|
|
45512
|
-
} else throwFetchError(resource, json2, status$1);
|
|
45544
|
+
} else throwFetchError(resource, json2, status$1, retryAfterMs);
|
|
45513
45545
|
}
|
|
45514
45546
|
return results;
|
|
45515
45547
|
}
|
|
@@ -45524,6 +45556,17 @@ function isWAFBlockResponse(headers) {
|
|
|
45524
45556
|
return headers.get("cf-mitigated") === "challenge";
|
|
45525
45557
|
}
|
|
45526
45558
|
__name$3(isWAFBlockResponse, "isWAFBlockResponse");
|
|
45559
|
+
function parseRetryAfterValue(retryAfter) {
|
|
45560
|
+
if (!retryAfter) return;
|
|
45561
|
+
if (/^\d+$/.test(retryAfter.trim())) return Number(retryAfter) * 1e3;
|
|
45562
|
+
const retryAfterDate = new Date(retryAfter);
|
|
45563
|
+
if (!Number.isNaN(retryAfterDate.getTime())) return Math.max(0, retryAfterDate.getTime() - Date.now());
|
|
45564
|
+
}
|
|
45565
|
+
__name$3(parseRetryAfterValue, "parseRetryAfterValue");
|
|
45566
|
+
function parseRetryAfterMs(headers) {
|
|
45567
|
+
return parseRetryAfterValue(headers.get("Retry-After"));
|
|
45568
|
+
}
|
|
45569
|
+
__name$3(parseRetryAfterMs, "parseRetryAfterMs");
|
|
45527
45570
|
function extractWAFBlockRayId(headers) {
|
|
45528
45571
|
return headers.get("cf-ray") ?? void 0;
|
|
45529
45572
|
}
|
|
@@ -45585,7 +45628,7 @@ function escapeCharacter(character) {
|
|
|
45585
45628
|
}).join("");
|
|
45586
45629
|
}
|
|
45587
45630
|
__name$3(escapeCharacter, "escapeCharacter");
|
|
45588
|
-
function throwFetchError(resource, response, status$1) {
|
|
45631
|
+
function throwFetchError(resource, response, status$1, retryAfterMs) {
|
|
45589
45632
|
const errors$1 = response.errors ?? [];
|
|
45590
45633
|
for (const error52 of errors$1) maybeThrowFriendlyError(error52);
|
|
45591
45634
|
const notes = [...errors$1.map((err) => ({ text: renderError(err) })), ...response.messages?.map((msg) => ({ text: typeof msg === "string" ? msg : msg.message ?? String(msg) })) ?? []];
|
|
@@ -45594,10 +45637,12 @@ function throwFetchError(resource, response, status$1) {
|
|
|
45594
45637
|
const fallbackMessage = typeof raw.error === "string" ? `${raw.error}${raw.code ? ` [code: ${raw.code}]` : ""}` : void 0;
|
|
45595
45638
|
if (fallbackMessage) notes.push({ text: fallbackMessage });
|
|
45596
45639
|
}
|
|
45640
|
+
if (retryAfterMs !== void 0) notes.push({ text: `The API responded with a "Retry-After" header indicating you should wait ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying.` });
|
|
45597
45641
|
const error51 = new APIError({
|
|
45598
45642
|
text: `A request to the Cloudflare API (${resource}) failed.`,
|
|
45599
45643
|
notes,
|
|
45600
45644
|
status: status$1,
|
|
45645
|
+
retryAfterMs,
|
|
45601
45646
|
telemetryMessage: false
|
|
45602
45647
|
});
|
|
45603
45648
|
const code = errors$1[0]?.code;
|
|
@@ -45608,7 +45653,7 @@ function throwFetchError(resource, response, status$1) {
|
|
|
45608
45653
|
throw error51;
|
|
45609
45654
|
}
|
|
45610
45655
|
__name$3(throwFetchError, "throwFetchError");
|
|
45611
|
-
function throwWAFBlockError(headers, method, resource, status$1, statusText) {
|
|
45656
|
+
function throwWAFBlockError(headers, method, resource, status$1, statusText, retryAfterMs) {
|
|
45612
45657
|
const rayId = extractWAFBlockRayId(headers);
|
|
45613
45658
|
throw new APIError({
|
|
45614
45659
|
text: "The Cloudflare API responded with a WAF block page instead of the expected JSON response",
|
|
@@ -45619,6 +45664,7 @@ function throwWAFBlockError(headers, method, resource, status$1, statusText) {
|
|
|
45619
45664
|
{ text: `${method} ${resource} -> ${status$1} ${statusText}` }
|
|
45620
45665
|
],
|
|
45621
45666
|
status: status$1,
|
|
45667
|
+
retryAfterMs,
|
|
45622
45668
|
telemetryMessage: false
|
|
45623
45669
|
});
|
|
45624
45670
|
}
|
|
@@ -45696,18 +45742,28 @@ ${url2}`);
|
|
|
45696
45742
|
}
|
|
45697
45743
|
__name$3(handleBrowserOpenError, "handleBrowserOpenError");
|
|
45698
45744
|
var MAX_ATTEMPTS = 3;
|
|
45745
|
+
var MAX_RETRY_AFTER_MS = 6e4;
|
|
45699
45746
|
async function retryOnAPIFailure(action, logger$1, backoff = 0, attempts = MAX_ATTEMPTS, abortSignal) {
|
|
45700
45747
|
try {
|
|
45701
45748
|
return await action();
|
|
45702
45749
|
} catch (err) {
|
|
45703
45750
|
if (err instanceof APIError) {
|
|
45704
|
-
if (!err.isRetryable()) throw err;
|
|
45751
|
+
if (!err.isRetryable() && err.status !== 429) throw err;
|
|
45705
45752
|
} else if (err instanceof DOMException && err.name === "TimeoutError");
|
|
45706
45753
|
else if (!(err instanceof TypeError)) throw err;
|
|
45707
|
-
|
|
45708
|
-
|
|
45754
|
+
const retryAfterMs = err instanceof APIError ? err.retryAfterMs : void 0;
|
|
45755
|
+
if (retryAfterMs !== void 0 && retryAfterMs > MAX_RETRY_AFTER_MS) throw err;
|
|
45709
45756
|
if (attempts <= 1) throw err;
|
|
45710
|
-
|
|
45757
|
+
const jitter = Math.random() * 1e3;
|
|
45758
|
+
let wait = backoff;
|
|
45759
|
+
if (retryAfterMs !== void 0) wait = retryAfterMs + jitter;
|
|
45760
|
+
else if (err instanceof APIError && err.status === 429) wait = Math.max(backoff, 1e3) + jitter;
|
|
45761
|
+
if (retryAfterMs !== void 0) logger$1.info(`Received a "Retry-After" header from the Cloudflare API. Waiting ${Math.ceil(retryAfterMs / 1e3)} second(s) before retrying...`);
|
|
45762
|
+
else {
|
|
45763
|
+
logger$1.debug(`Retrying API call after error...`);
|
|
45764
|
+
logger$1.debug(err);
|
|
45765
|
+
}
|
|
45766
|
+
await setTimeout$1(wait, void 0, { signal: abortSignal });
|
|
45711
45767
|
return retryOnAPIFailure(action, logger$1, backoff + 1e3, attempts - 1, abortSignal);
|
|
45712
45768
|
}
|
|
45713
45769
|
}
|
|
@@ -47950,13 +48006,18 @@ const tunnelPlugin = createPlugin("tunnel", (ctx) => {
|
|
|
47950
48006
|
tunnelManager?.dispose();
|
|
47951
48007
|
}
|
|
47952
48008
|
return {
|
|
47953
|
-
buildEnd() {
|
|
47954
|
-
if (!ctx.isRestartingDevServer) stopTunnel();
|
|
47955
|
-
},
|
|
47956
48009
|
configureServer(server) {
|
|
47957
48010
|
assertIsNotPreview(ctx);
|
|
47958
48011
|
tunnelManager ??= new TunnelManager(server.config.logger);
|
|
47959
48012
|
patchPrintUrls(server);
|
|
48013
|
+
const closeServer = server.close.bind(server);
|
|
48014
|
+
server.close = async () => {
|
|
48015
|
+
try {
|
|
48016
|
+
await closeServer();
|
|
48017
|
+
} finally {
|
|
48018
|
+
if (!ctx.isRestartingDevServer) stopTunnel();
|
|
48019
|
+
}
|
|
48020
|
+
};
|
|
47960
48021
|
if (!ctx.resolvedPluginConfig.tunnel.autoStart) return;
|
|
47961
48022
|
const serverListen = server.listen.bind(server);
|
|
47962
48023
|
server.listen = async (...args) => {
|
|
@@ -47979,11 +48040,10 @@ const tunnelPlugin = createPlugin("tunnel", (ctx) => {
|
|
|
47979
48040
|
if (ctx.resolvedPluginConfig.tunnel.autoStart) await setupPreviewTunnel(server, ctx, tunnelManager);
|
|
47980
48041
|
const closePreviewServer = server.close.bind(server);
|
|
47981
48042
|
server.close = async () => {
|
|
47982
|
-
const closePromise = closePreviewServer();
|
|
47983
48043
|
try {
|
|
47984
|
-
|
|
48044
|
+
await closePreviewServer();
|
|
47985
48045
|
} finally {
|
|
47986
|
-
|
|
48046
|
+
stopTunnel();
|
|
47987
48047
|
}
|
|
47988
48048
|
};
|
|
47989
48049
|
}
|
|
@@ -54836,10 +54896,16 @@ var ParseError$1 = class extends UserError$1 {
|
|
|
54836
54896
|
* endpoint-specific structured error payloads.
|
|
54837
54897
|
*/
|
|
54838
54898
|
meta;
|
|
54839
|
-
|
|
54899
|
+
/**
|
|
54900
|
+
* Optional number of milliseconds the API asked us to wait before retrying,
|
|
54901
|
+
* derived from the response's `Retry-After` header (if present).
|
|
54902
|
+
*/
|
|
54903
|
+
retryAfterMs;
|
|
54904
|
+
constructor({ status: status$1, retryAfterMs,...rest }) {
|
|
54840
54905
|
super(rest);
|
|
54841
54906
|
this.name = this.constructor.name;
|
|
54842
54907
|
this.#status = status$1;
|
|
54908
|
+
this.retryAfterMs = retryAfterMs;
|
|
54843
54909
|
}
|
|
54844
54910
|
get status() {
|
|
54845
54911
|
return this.#status;
|
|
@@ -75574,7 +75640,7 @@ var __name$1 = (target$1, value) => __defProp$1(target$1, "name", {
|
|
|
75574
75640
|
});
|
|
75575
75641
|
|
|
75576
75642
|
//#endregion
|
|
75577
|
-
//#region ../workers-auth/dist/chunk-
|
|
75643
|
+
//#region ../workers-auth/dist/chunk-5WRJ2ZUV.mjs
|
|
75578
75644
|
var import_undici$2 = require_undici();
|
|
75579
75645
|
var hasWarnedAboutDeprecatedV1ApiToken = false;
|
|
75580
75646
|
function readStoredAuthState(options) {
|
|
@@ -76681,7 +76747,7 @@ function createProfileStore(args) {
|
|
|
76681
76747
|
const boundProfile = currentBindings[normalizedDir];
|
|
76682
76748
|
if (boundProfile === void 0) {
|
|
76683
76749
|
const parentBinding = getProfileForDirectoryFromBindings(normalizedDir, currentBindings);
|
|
76684
|
-
if (parentBinding) throw new UserError(`No profile is directly bound to "${formatDirectoryForUserError(normalizedDir)}". The active profile "${parentBinding.profile}" is bound at "${formatDirectoryForUserError(parentBinding.dir)}". Run
|
|
76750
|
+
if (parentBinding) throw new UserError(`No profile is directly bound to "${formatDirectoryForUserError(normalizedDir)}". The active profile "${parentBinding.profile}" is bound at "${formatDirectoryForUserError(parentBinding.dir)}". Run the deactivate command from that directory instead.`, { telemetryMessage: "auth deactivate wrong directory" });
|
|
76685
76751
|
throw new UserError(`No profile is bound to "${formatDirectoryForUserError(normalizedDir)}". Nothing to deactivate.`, { telemetryMessage: "auth deactivate no binding" });
|
|
76686
76752
|
}
|
|
76687
76753
|
delete currentBindings[normalizedDir];
|
|
@@ -76743,7 +76809,7 @@ function createProfileStore(args) {
|
|
|
76743
76809
|
}
|
|
76744
76810
|
__name$1(createProfileStore, "createProfileStore");
|
|
76745
76811
|
function validateProfileName(name) {
|
|
76746
|
-
if (RESERVED_PROFILE_NAMES.includes(name.toLowerCase())) throw new UserError(`"${name}" is a reserved profile name. Use
|
|
76812
|
+
if (RESERVED_PROFILE_NAMES.includes(name.toLowerCase())) throw new UserError(`"${name}" is a reserved profile name. Use the login and logout commands to manage the default profile, which applies as a global fallback.`, { telemetryMessage: "auth profile reserved name" });
|
|
76747
76813
|
if (!/^[a-zA-Z0-9_-]+$/.test(name)) throw new UserError(`Invalid profile name "${name}". Profile names may only contain alphanumeric characters, hyphens, and underscores.`, { telemetryMessage: "auth profile invalid name" });
|
|
76748
76814
|
}
|
|
76749
76815
|
__name$1(validateProfileName, "validateProfileName");
|
|
@@ -78215,7 +78281,7 @@ function scrubEncryptedCredentials(options) {
|
|
|
78215
78281
|
__name$1(scrubEncryptedCredentials, "scrubEncryptedCredentials");
|
|
78216
78282
|
|
|
78217
78283
|
//#endregion
|
|
78218
|
-
//#region ../workers-auth/dist/chunk-
|
|
78284
|
+
//#region ../workers-auth/dist/chunk-7PS36DJW.mjs
|
|
78219
78285
|
function createPreferences(getConfigPath) {
|
|
78220
78286
|
function getUserPreferencesPath() {
|
|
78221
78287
|
return path2__default.resolve(getConfigPath(), "preferences.json");
|
|
@@ -79482,7 +79548,8 @@ var CF_CLI = {
|
|
|
79482
79548
|
cliName: CF_CLI_NAME,
|
|
79483
79549
|
commands: {
|
|
79484
79550
|
login: "cf auth login",
|
|
79485
|
-
whoami: "cf auth whoami"
|
|
79551
|
+
whoami: "cf auth whoami",
|
|
79552
|
+
createProfile: "cf auth create"
|
|
79486
79553
|
},
|
|
79487
79554
|
keyringServiceName: CF_KEYRING_SERVICE_NAME,
|
|
79488
79555
|
clientId: getClientIdFromEnv$1,
|
|
@@ -80634,7 +80701,7 @@ __name(createWorkerUploadForm, "createWorkerUploadForm");
|
|
|
80634
80701
|
//#endregion
|
|
80635
80702
|
//#region ../remote-bindings/dist/index.mjs
|
|
80636
80703
|
var import_undici = require_undici();
|
|
80637
|
-
var version$2 = "0.0.
|
|
80704
|
+
var version$2 = "0.0.3";
|
|
80638
80705
|
var NoDefaultValueProvided = class extends UserError {
|
|
80639
80706
|
constructor() {
|
|
80640
80707
|
super("This command cannot be run in a non-interactive context", { telemetryMessage: "remote bindings prompt default missing" });
|
|
@@ -80684,7 +80751,7 @@ function getRemoteBindingsAuthHook(auth, accountId, profileDir, logger$1) {
|
|
|
80684
80751
|
apiToken: remoteBindingsAuth.requireApiToken()
|
|
80685
80752
|
});
|
|
80686
80753
|
}
|
|
80687
|
-
var ProxyServerWorker_default = "// ../../node_modules/.pnpm/capnweb@0.5.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) {\n Symbol.dispose = /* @__PURE__ */ Symbol.for(\"dispose\");\n}\nif (!Symbol.asyncDispose) {\n Symbol.asyncDispose = /* @__PURE__ */ Symbol.for(\"asyncDispose\");\n}\nif (!Promise.withResolvers) {\n Promise.withResolvers = function() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n };\n}\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\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) {\n return \"primitive\";\n }\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 return \"bytes\";\n case WritableStream.prototype:\n return \"writable\";\n case ReadableStream.prototype:\n return \"readable\";\n case Headers.prototype:\n return \"headers\";\n case Request.prototype:\n return \"request\";\n case Response.prototype:\n return \"response\";\n // TODO: All other structured clone types.\n case RpcStub.prototype:\n return \"stub\";\n case RpcPromise.prototype:\n return \"rpc-promise\";\n // TODO: Promise<T> or thenable\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) {\n return \"rpc-target\";\n } else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) {\n return \"rpc-thenable\";\n }\n }\n if (value instanceof RpcTarget) {\n return \"rpc-target\";\n }\n if (value instanceof Error) {\n return \"error\";\n }\n return \"unsupported\";\n }\n}\nfunction mapNotLoaded() {\n throw new Error(\"RPC map() implementation was not loaded.\");\n}\nvar mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };\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 // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:\n // - promise: A Promise<void> for the completion of the call.\n // - size: If the call was remote, the byte size of the serialized message. For local calls,\n // undefined is returned, indicating the caller should await the promise to serialize writes\n // (no overlapping).\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled = hook.pull();\n let promise;\n if (pulled instanceof Promise) {\n 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 constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n return this;\n }\n map(path, captures, instructions) {\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(\n new Error(\"Attempted to use RPC stub after it has been disposed.\")\n);\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(doCall(\n stub.hook,\n stub.pathIfPromise || [],\n RpcPayload.fromAppParams(argumentsList)\n ), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return stub;\n } else if (prop in RpcPromise.prototype) {\n return stub[prop];\n } else if (typeof prop === \"string\") {\n return new RpcPromise(\n stub.hook,\n stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]\n );\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n } else {\n return void 0;\n }\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return true;\n } else if (prop in RpcPromise.prototype) {\n return prop in stub;\n } else if (typeof prop === \"string\") {\n return true;\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return true;\n } else {\n return false;\n }\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 return void 0;\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 = class _RpcStub extends RpcTarget {\n // Although `hook` and `path` are declared `public` here, they are effectively hidden by the\n // proxy.\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget || value instanceof Function) {\n hook = TargetStubHook.create(value, void 0);\n } else {\n hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n }\n if (pathIfPromise) {\n throw new TypeError(\"RpcStub constructor expected one argument, received two.\");\n }\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) {\n return new _RpcStub(target.hook.get(target.pathIfPromise));\n } else {\n return new _RpcStub(target.hook.dup());\n }\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 = class extends RpcStub {\n // TODO: Support passing target value or promise to constructor.\n constructor(hook, pathIfPromise) {\n super(hook, pathIfPromise);\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) {\n return hook.get(pathIfPromise);\n } else {\n return hook;\n }\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) {\n return hook.get(pathIfPromise);\n } else {\n return hook.dup();\n }\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return void 0;\n }\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) {\n hook = hook.get(pathIfPromise);\n }\n let payload = await hook.pull();\n return payload.deliverResolve();\n}\nvar RpcPayload = class _RpcPayload {\n // Private constructor; use factory functions above to construct.\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n // Create a payload from a value passed as params to an RPC from the app.\n //\n // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify\n // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not\n // to have the sender and recipient end up sharing the same mutable object. `value` will not be\n // touched again after the call returns synchronously (returns a promise) -- by that point,\n // the value has either been copied or serialized to the wire.\n static fromAppParams(value) {\n return new _RpcPayload(value, \"params\");\n }\n // Create a payload from a value return from an RPC implementation by the app.\n //\n // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and\n // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It\n // will still avoid modifying `value` and will make a deep copy if it is delivered locally.\n static fromAppReturn(value) {\n return new _RpcPayload(value, \"return\");\n }\n // Combine an array of payloads into a single payload whose value is an array. Ownership of all\n // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the\n // inputs should not be. (In case of exception, nothing is disposed, though.)\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) {\n hooks.push(hook);\n }\n for (let promise of payload.promises) {\n if (promise.parent === payload) {\n promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n }\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new _RpcPayload(resultArray, \"owned\", hooks, promises);\n }\n // Create a payload from a value parsed off the wire using Evaluator.evaluate().\n //\n // A payload is constructed with a null value and the given hooks and promises arrays. The value\n // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected\n // to be extended with stubs found during parsing. (This weird usage model is necessary so that\n // if the root value turns out to be a promise, its `parent` in `promises` can be the payload\n // object itself.)\n //\n // When done, the payload takes ownership of the final value and all the stubs within. It may\n // modify the value in preparation for delivery, and may deliver the value directly to the app\n // without copying.\n static forEvaluate(hooks, promises) {\n return new _RpcPayload(null, \"owned\", hooks, promises);\n }\n // Deep-copy the given value, including dup()ing all stubs.\n //\n // If `value` is a function, it should be bound to `oldParent` as its `this`.\n //\n // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure\n // RpcTargets found within don't get duplicate stubs.\n static deepCopyFrom(value, oldParent, owner) {\n let result = new _RpcPayload(null, \"owned\", [], []);\n result.value = result.deepCopy(\n value,\n oldParent,\n \"value\",\n result,\n /*dupStubs=*/\n true,\n owner\n );\n return result;\n }\n // For `source === \"return\"` payloads only, this tracks any StubHooks created around RpcTargets\n // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for\n // return, so that we can make sure they are not disposed before the pipeline ends.\n //\n // This is initialized on first use.\n rpcTargets;\n // Get the StubHook representing the given RpcTarget found inside this payload.\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === \"params\") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === \"function\") {\n target = dupable.dup();\n }\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw RpcTargets\");\n }\n }\n // Get the StubHook representing the given WritableStream found inside this payload.\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") {\n return streamImpl.createWritableStreamHook(stream);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw WritableStreams\");\n }\n }\n // Get the StubHook representing the given ReadableStream found inside this payload.\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") {\n return streamImpl.createReadableStreamHook(stream);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw ReadableStreams\");\n }\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n return value;\n case \"primitive\":\n case \"bigint\":\n case \"date\":\n case \"bytes\":\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++) {\n result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n }\n return result;\n }\n case \"object\": {\n let result = {};\n let object = value;\n for (let i in object) {\n result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n }\n return result;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook;\n if (dupStubs) {\n hook = unwrapStubAndDup(stub);\n } else {\n hook = unwrapStubTakingOwnership(stub);\n }\n if (stub instanceof RpcPromise) {\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook;\n if (owner) {\n hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n } else {\n hook = TargetStubHook.create(target, oldParent);\n }\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n case \"rpc-thenable\": {\n let target = value;\n let promise;\n if (owner) {\n promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n } else {\n promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);\n }\n this.promises.push({ parent, property, promise });\n return promise;\n }\n case \"writable\": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case \"readable\": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\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) {\n this.deepCopy(req.body, req, \"body\", req, dupStubs, owner);\n }\n return new Request(req);\n }\n case \"response\": {\n let resp = value;\n if (resp.body) {\n this.deepCopy(resp.body, resp, \"body\", resp, dupStubs, owner);\n }\n return new Response(resp.body, resp);\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n // Ensures that if the value originally came from an unowned source, we have replaced it with a\n // deep copy.\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) {\n throw new Error(\"Not all rpcTargets were accounted for in deep-copy?\");\n }\n this.rpcTargets = void 0;\n }\n }\n // Resolve all promises in this payload and then assign the final value into `parent[property]`.\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise) {\n _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);\n } else {\n parent[property] = this.value;\n for (let record of this.promises) {\n _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) {\n throw new Error(\"property promises should have been resolved earlier\");\n }\n let inner = hook.pull();\n if (inner instanceof _RpcPayload) {\n inner.deliverTo(parent, property, promises);\n } else {\n promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) {\n return Promise.all(subPromises);\n }\n }));\n }\n }\n // Call the given function with the payload as an argument. The call is made synchronously if\n // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,\n // they are awaited and substituted before calling the function. The result of the call is\n // wrapped into another payload.\n //\n // The payload is automatically disposed after the call completes. The caller should not call\n // dispose().\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise) {\n return _RpcPayload.fromAppReturn(result);\n } else {\n return _RpcPayload.fromAppReturn(await result);\n }\n } finally {\n this.dispose();\n }\n }\n // Produce a promise for this payload for return to the application. Any RpcPromises in the\n // payload are awaited and substituted with their results first.\n //\n // The returned object will have a disposer which disposes the payload. The caller should not\n // separately dispose it.\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) {\n Object.defineProperty(result, Symbol.dispose, {\n // NOTE: Using `this.dispose.bind(this)` here causes Playwright's build of\n // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,\n // with the error:\n // TypeError: Symbol(Symbol.dispose) is not a function\n // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,\n // so maybe it was a short-lived V8 bug or something. To be safe, though, we use\n // `() => this.dispose()`, which seems to always work.\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\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) {\n throw new Error(\"Not all rpcTargets were accounted for in disposeImpl()?\");\n }\n } else ;\n this.source = \"owned\";\n this.hooks = [];\n this.promises = [];\n }\n // Recursive dispose, called only when `source` is \"return\".\n disposeImpl(value, parent) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"date\":\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++) {\n this.disposeImpl(array[i], array);\n }\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) {\n this.disposeImpl(object[i], object);\n }\n return;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook = unwrapStubNoProperties(stub);\n if (hook) {\n hook.dispose();\n }\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 {\n disposeRpcTarget(target);\n }\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) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n case \"readable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n // Ignore unhandled rejections in all promises in this payload -- that is, all promises that\n // *would* be awaited if this payload were to be delivered. See the similarly-named method of\n // StubHook for explanation.\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach(\n (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()\n );\n } else {\n this.ignoreUnhandledRejectionsImpl(this.value);\n }\n }\n ignoreUnhandledRejectionsImpl(value) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"date\":\n case \"error\":\n case \"undefined\":\n case \"function\":\n case \"rpc-target\":\n case \"writable\":\n case \"readable\":\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++) {\n this.ignoreUnhandledRejectionsImpl(array[i]);\n }\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) {\n this.ignoreUnhandledRejectionsImpl(object[i]);\n }\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 let kind = typeForRpc(value);\n switch (kind) {\n case \"object\":\n case \"function\":\n if (Object.hasOwn(value, part)) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case \"array\":\n if (Number.isInteger(part) && part >= 0) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case \"rpc-target\":\n case \"rpc-thenable\": {\n if (Object.hasOwn(value, part)) {\n throw new TypeError(\n `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 );\n } else {\n value = value[part];\n }\n owner = null;\n break;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };\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 \"date\":\n case \"error\":\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) {\n 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(\n `'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`\n );\n }\n }\n default:\n throw new TypeError(\"unreachable\");\n }\n }\n if (value instanceof RpcPromise) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise || [] };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n try {\n let { value, owner } = this.getValue();\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.call(followResult.remainingPath, args);\n }\n if (typeof followResult.value != \"function\") {\n throw new TypeError(`'${path.join(\".\")}' is not a function.`);\n }\n let promise = args.deliverCall(followResult.value, followResult.parent);\n return new PromiseStubHook(promise.then((payload) => {\n return new PayloadStubHook(payload);\n }));\n } catch (err) {\n return new ErrorStubHook(err);\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 ;\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (followResult.hook) {\n return followResult.hook.map(followResult.remainingPath, captures, instructions);\n }\n return mapImpl.applyMap(\n followResult.value,\n followResult.parent,\n followResult.owner,\n captures,\n instructions\n );\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 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) {\n return followResult.hook.get(followResult.remainingPath);\n }\n return new PayloadStubHook(RpcPayload.deepCopyFrom(\n followResult.value,\n followResult.parent,\n followResult.owner\n ));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class _PayloadStubHook extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n // cleared when disposed\n getPayload() {\n if (this.payload) {\n return this.payload;\n } else {\n throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n }\n getValue() {\n let payload = this.getPayload();\n return { value: payload.value, owner: payload };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new _PayloadStubHook(RpcPayload.deepCopyFrom(\n thisPayload.value,\n void 0,\n thisPayload\n ));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) {\n this.payload.ignoreUnhandledRejections();\n }\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) {\n this.payload.value.onRpcBroken(callback);\n }\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) {\n try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n }\n}\nvar TargetStubHook = class _TargetStubHook extends ValueStubHook {\n // Constructs a TargetStubHook that is not duplicated from an existing hook.\n //\n // If `value` is a function, `parent` is bound as its \"this\".\n static create(value, parent) {\n if (typeof value !== \"function\") {\n parent = void 0;\n }\n return new _TargetStubHook(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) {\n this.refcount = { count: 1 };\n }\n }\n target;\n // cleared when disposed\n parent;\n // `this` parameter when calling `target`\n refcount;\n // undefined if not needed (because target has no disposer)\n getTarget() {\n if (this.target) {\n return this.target;\n } else {\n throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n }\n getValue() {\n return { value: this.getTarget(), owner: null };\n }\n dup() {\n return new _TargetStubHook(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if (\"then\" in target) {\n return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n } else {\n return Promise.reject(new Error(\"Tried to resolve a non-promise stub.\"));\n }\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) {\n disposeRpcTarget(this.target);\n }\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n }\n};\nvar PromiseStubHook = class _PromiseStubHook 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 _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n let promise = this.promise.then((hook) => {\n let result = hook.stream(path, args);\n return result.promise;\n });\n return { promise };\n }\n map(path, captures, instructions) {\n return new _PromiseStubHook(this.promise.then(\n (hook) => hook.map(path, captures, instructions),\n (err) => {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n ));\n }\n get(path) {\n return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) {\n return this.resolution.dup();\n } else {\n return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));\n }\n }\n pull() {\n if (this.resolution) {\n return this.resolution.pull();\n } else {\n return this.promise.then((hook) => hook.pull());\n }\n }\n ignoreUnhandledRejections() {\n if (this.resolution) {\n this.resolution.ignoreUnhandledRejections();\n } else {\n this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.promise.then((hook) => {\n hook.dispose();\n }, (err) => {\n });\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\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 return void 0;\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();\nvar ERROR_TYPES = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n // TODO: DOMError? Others?\n};\nvar Devaluator = class _Devaluator {\n constructor(exporter, source) {\n this.exporter = exporter;\n this.source = source;\n }\n // Devaluate the given value.\n // * value: The value to devaluate.\n // * parent: The value's parent object, which would be used as `this` if the value were called\n // as a function.\n // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.\n // * source: The RpcPayload which contains the value, and therefore owns stubs within.\n //\n // Returns: The devaluated value, ready to be JSON-serialized.\n static devaluate(value, parent, exporter = NULL_EXPORTER, source) {\n let devaluator = new _Devaluator(exporter, source);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) {\n try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 64) {\n throw new Error(\n \"Serialization exceeded maximum allowed depth. (Does the message contain cycles?)\"\n );\n }\n let kind = typeForRpc(value);\n switch (kind) {\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 (value === Infinity) {\n return [\"inf\"];\n } else if (value === -Infinity) {\n return [\"-inf\"];\n } else {\n return [\"nan\"];\n }\n } else {\n return value;\n }\n case \"object\": {\n let object = value;\n let result = {};\n for (let key in object) {\n result[key] = this.devaluateImpl(object[key], object, depth + 1);\n }\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++) {\n result[i] = this.devaluateImpl(array[i], array, depth + 1);\n }\n return [result];\n }\n case \"bigint\":\n return [\"bigint\", value.toString()];\n case \"date\":\n return [\"date\", value.getTime()];\n case \"bytes\": {\n let bytes = value;\n if (bytes.toBase64) {\n return [\"bytes\", bytes.toBase64({ omitPadding: true })];\n } else {\n return [\n \"bytes\",\n btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, \"\"))\n ];\n }\n }\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) {\n init.headers = headers;\n }\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 && ![\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\", \"DELETE\"].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({\n 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 });\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n init.body = [\"readable\", importId];\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\") {\n init.credentials = req.credentials;\n }\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\") {\n init.encodeResponseBody = cfReq.encodeResponseBody;\n }\n return [\"request\", req.url, init];\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) {\n init.headers = headers;\n }\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== \"automatic\") {\n init.encodeBody = cfResp.encodeBody;\n }\n if (cfResp.webSocket) {\n throw new TypeError(\"Can't serialize a Response containing a webSocket.\");\n }\n return [\"response\", body, init];\n }\n case \"error\": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) {\n e = rewritten;\n }\n let result = [\"error\", e.name, e.message];\n if (rewritten && rewritten.stack) {\n result.push(rewritten.stack);\n }\n return result;\n }\n case \"undefined\":\n return [\"undefined\"];\n case \"stub\":\n case \"rpc-promise\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) {\n if (pathIfPromise) {\n if (pathIfPromise.length > 0) {\n return [\"pipeline\", importId, pathIfPromise];\n } else {\n return [\"pipeline\", importId];\n }\n } else {\n return [\"import\", importId];\n }\n }\n if (pathIfPromise) {\n hook = hook.get(pathIfPromise);\n } else {\n hook = hook.dup();\n }\n return this.devaluateHook(pathIfPromise ? \"promise\" : \"export\", hook);\n }\n case \"function\":\n case \"rpc-target\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"export\", hook);\n }\n case \"rpc-thenable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"promise\", hook);\n }\n case \"writable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize WritableStream in this context.\");\n }\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook(\"writable\", hook);\n }\n case \"readable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize ReadableStream in this context.\");\n }\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n let importId = this.exporter.createPipe(ws, hook);\n return [\"readable\", importId];\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 return void 0;\n }\n getPipeReadable(exportId) {\n throw new Error(\"Cannot retrieve pipe readable without an RPC session.\");\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n let promise = 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 return new RpcPromise(new PromiseStubHook(promise), []);\n}\nvar Evaluator = class _Evaluator {\n constructor(importer) {\n this.importer = importer;\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, \"value\");\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n // Evaluate the value without destroying it.\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property) {\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++) {\n result[i] = this.evaluateImpl(result[i], result, i);\n }\n return result;\n } else switch (value[0]) {\n case \"bigint\":\n if (typeof value[1] == \"string\") {\n return BigInt(value[1]);\n }\n break;\n case \"date\":\n if (typeof value[1] == \"number\") {\n return new Date(value[1]);\n }\n break;\n case \"bytes\": {\n let b64 = Uint8Array;\n if (typeof value[1] == \"string\") {\n if (b64.fromBase64) {\n return b64.fromBase64(value[1]);\n } else {\n let bs = atob(value[1]);\n let len = bs.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = bs.charCodeAt(i);\n }\n return bytes;\n }\n }\n break;\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 = new cls(value[2]);\n if (typeof value[3] === \"string\") {\n result.stack = value[3];\n }\n return result;\n }\n break;\n case \"undefined\":\n if (value.length === 1) {\n return void 0;\n }\n break;\n case \"inf\":\n return Infinity;\n case \"-inf\":\n return -Infinity;\n case \"nan\":\n return NaN;\n case \"headers\":\n if (value.length === 2 && value[1] instanceof Array) {\n return new Headers(value[1]);\n }\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\");\n if (init.body === null || typeof init.body === \"string\" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) ;\n else {\n throw new TypeError(\"Request body must be of type ReadableStream.\");\n }\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, \"signal\");\n if (!(init.signal instanceof AbortSignal)) {\n throw new TypeError(\"Request siganl must be of type AbortSignal.\");\n }\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n }\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({ promise, parent, property });\n return promise;\n } else {\n return result;\n }\n }\n case \"response\": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property);\n if (body === null || typeof body === \"string\" || body instanceof Uint8Array || body instanceof ReadableStream) ;\n else {\n throw new TypeError(\"Response body must be of type ReadableStream.\");\n }\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.webSocket) {\n throw new TypeError(\"Can't deserialize a Response containing a webSocket.\");\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n }\n return new Response(body, init);\n }\n case \"import\":\n case \"pipeline\": {\n if (value.length < 2 || value.length > 4) {\n break;\n }\n if (typeof value[1] != \"number\") {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let isPromise = value[0] == \"pipeline\";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise(hook2, []);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise(hook2, []);\n }\n };\n if (value.length == 2) {\n if (isPromise) {\n return addStub(hook.get([]));\n } else {\n return addStub(hook.dup());\n }\n }\n let path = value[2];\n if (!(path instanceof Array)) {\n break;\n }\n if (!path.every(\n (part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n }\n )) {\n break;\n }\n if (value.length == 3) {\n return addStub(hook.get(path));\n }\n let args = value[3];\n if (!(args instanceof Array)) {\n break;\n }\n let subEval = new _Evaluator(this.importer);\n args = subEval.evaluate([args]);\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)) {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let path = value[2];\n if (!path.every(\n (part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n }\n )) {\n break;\n }\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\") {\n throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n }\n if (cap[0] === \"export\") {\n return this.importer.importStub(cap[1]);\n } else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) {\n throw new Error(`no such entry on exports table: ${cap[1]}`);\n }\n return exp.dup();\n }\n });\n let instructions = value[4];\n let resultHook = hook.map(path, captures, instructions);\n let promise = new RpcPromise(resultHook, []);\n this.promises.push({ promise, parent, property });\n return promise;\n }\n case \"export\":\n case \"promise\":\n if (typeof value[1] == \"number\") {\n if (value[0] == \"promise\") {\n let hook = this.importer.importPromise(value[1]);\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\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) {\n if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(result[key], result, key);\n delete result[key];\n } else {\n result[key] = this.evaluateImpl(result[key], result, key);\n }\n }\n return result;\n } else {\n return value;\n }\n }\n};\nvar ImportTableEntry = class {\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) {\n this.activePull = Promise.withResolvers();\n }\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on\n // this import. Initialized on first use (so `undefined` is the same as an empty list).\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) {\n delete this.session.onBrokenCallbacks[endIndex];\n } else {\n delete this.session.onBrokenCallbacks[i];\n }\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) {\n this.resolution.dispose();\n } else {\n this.abort(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) {\n 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 _RpcImportHook extends StubHook {\n // undefined when we're disposed\n // `pulling` is true if we already expect that this import is going to be resolved later, and\n // null if this import is not allowed to be pulled (i.e. it's a stub not a promise).\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n entry;\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) {\n return this.entry;\n } else {\n throw new Error(\"This RpcImportHook was already disposed.\");\n }\n }\n // -------------------------------------------------------------------------------------\n // implements StubHook\n call(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.call(path, args);\n } else {\n return entry.session.sendCall(entry.importId, path, args);\n }\n }\n stream(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.stream(path, args);\n } else {\n return entry.session.sendStream(entry.importId, path, args);\n }\n }\n map(path, captures, instructions) {\n let entry;\n try {\n entry = this.getEntry();\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (entry.resolution) {\n return entry.resolution.map(path, captures, instructions);\n } else {\n return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.get(path);\n } else {\n return entry.session.sendCall(entry.importId, path);\n }\n }\n dup() {\n return new _RpcImportHook(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) {\n throw new Error(\"Can't pull this hook because it's not a promise hook.\");\n }\n if (entry.resolution) {\n return entry.resolution.pull();\n }\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) {\n entry.dispose();\n }\n }\n }\n onBroken(callback) {\n if (this.entry) {\n this.entry.onBroken(callback);\n }\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 constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n this.exports.push({ hook: mainHook, refcount: 1 });\n this.imports.push(new ImportTableEntry(this, 0, false));\n let rejectFunc;\n let abortPromise = new Promise((resolve, reject) => {\n rejectFunc = reject;\n });\n this.cancelReadLoop = rejectFunc;\n this.readLoop(abortPromise).catch((err) => this.abort(err));\n }\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n // We assign positive numbers to imports we initiate, and negative numbers to exports we\n // initiate. So the next import ID is just `imports.length`, but the next export ID needs\n // to be tracked explicitly.\n nextExportId = -1;\n // If set, call this when all incoming calls are complete.\n onBatchDone;\n // How many promises is our peer expecting us to resolve?\n pullCount = 0;\n // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but\n // may be deleted from the middle (hence leaving the array sparse).\n onBrokenCallbacks = [];\n // Should only be called once immediately after construction.\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(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] = { hook, refcount: 1 };\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] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) {\n this.releaseExport(id, 1);\n }\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (entry.refcount < refcount) {\n throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n }\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) {\n return this.options.onSendError(error);\n }\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) {\n throw new Error(`no such export ID: ${exportId}`);\n }\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) {\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(\n (payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload);\n this.send([\"resolve\", exportId, value]);\n if (autoRelease) this.releaseExport(exportId, 1);\n },\n (error) => {\n this.send([\"reject\", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }\n ).catch(\n (error) => {\n try {\n this.send([\"reject\", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }\n ).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) {\n this.onBatchDone.resolve();\n }\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) {\n return hook.entry.importId;\n } else {\n return void 0;\n }\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(\n /*isPromise=*/\n false,\n entry\n );\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) {\n return new ErrorStubHook(new Error(\n \"Bug in RPC system: The peer sent a promise reusing an existing export ID.\"\n ));\n }\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\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) {\n throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n }\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\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(\n /*isPromise=*/\n false,\n entry\n );\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n // Serializes and sends a message. Returns the byte length of the serialized message.\n send(msg) {\n if (this.abortReason !== void 0) {\n return 0;\n }\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 this.transport.send(msgText).catch((err) => this.abort(err, false));\n return msgText.length;\n }\n sendCall(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = [\"pipeline\", id, path];\n if (args) {\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\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(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendStream(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = [\"pipeline\", id, path];\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n let size = this.send([\"stream\", value]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(\n this,\n importId,\n /*pulling=*/\n true\n );\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n let promise = entry.awaitResolution().then(\n (p) => {\n p.dispose();\n delete this.imports[importId];\n },\n (err) => {\n delete this.imports[importId];\n throw err;\n }\n );\n return { promise, size };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw this.abortReason;\n }\n let devaluedCaptures = captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) {\n return [\"import\", importId];\n } else {\n return [\"export\", this.exportStub(hook)];\n }\n });\n let value = [\"remap\", id, path, devaluedCaptures, instructions];\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\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([\"release\", id, remoteRefcount]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop(error);\n if (trySendAbortMessage) {\n try {\n this.transport.send(JSON.stringify([\"abort\", Devaluator.devaluate(error, void 0, this)])).catch((err) => {\n });\n } catch (err) {\n }\n }\n if (error === void 0) {\n error = \"undefined\";\n }\n this.abortReason = error;\n if (this.onBatchDone) {\n this.onBatchDone.reject(error);\n }\n if (this.transport.abort) {\n try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.onBrokenCallbacks) {\n try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.imports) {\n this.imports[i].abort(error);\n }\n for (let i in this.exports) {\n this.exports[i].hook.dispose();\n }\n }\n async readLoop(abortPromise) {\n while (!this.abortReason) {\n let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));\n if (this.abortReason) break;\n if (msg instanceof Array) {\n switch (msg[0]) {\n case \"push\":\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n this.exports.push({ hook, refcount: 1 });\n continue;\n }\n break;\n case \"stream\": {\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({ hook, refcount: 1, autoRelease: true });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case \"pipe\": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({ hook, refcount: 1, pipeReadable: readable });\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 // [\"resolve\", ExportId, Expression]\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) {\n if (msg[0] == \"resolve\") {\n imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));\n } else {\n let payload = new Evaluator(this).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n } else {\n if (msg[0] == \"resolve\") {\n new Evaluator(this).evaluate(msg[2]).dispose();\n }\n }\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).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload, false);\n break;\n }\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) {\n throw this.abortReason;\n }\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = { resolve, reject };\n await promise;\n }\n }\n getStats() {\n let result = { imports: 0, exports: 0 };\n for (let i in this.imports) {\n ++result.imports;\n }\n for (let i in this.exports) {\n ++result.exports;\n }\n return result;\n }\n};\nvar RpcSession = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) {\n mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n } else {\n mainHook = new ErrorStubHook(new Error(\"This connection has no main object.\"));\n }\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub(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(webSocket, localMain, options) {\n if (typeof webSocket === \"string\") {\n webSocket = new WebSocket(webSocket);\n }\n let transport = new WebSocketTransport(webSocket);\n let rpc = new RpcSession(transport, localMain, options);\n return rpc.getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n return new Response(\"This endpoint only accepts WebSocket requests.\", { status: 400 });\n }\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession(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 if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener(\"open\", (event) => {\n try {\n for (let message of this.#sendQueue) {\n webSocket.send(message);\n }\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\") {\n if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else {\n this.#receiveQueue.push(event.data);\n }\n } else {\n this.#receivedError(new TypeError(\"Received non-string message from WebSocket.\"));\n }\n });\n webSocket.addEventListener(\"close\", (event) => {\n this.#receivedError(new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener(\"error\", (event) => {\n this.#receivedError(new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n // only if not opened yet\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n async send(message) {\n if (this.#sendQueue === void 0) {\n this.#webSocket.send(message);\n } else {\n this.#sendQueue.push(message);\n }\n }\n async receive() {\n if (this.#receiveQueue.length > 0) {\n return this.#receiveQueue.shift();\n } else if (this.#error) {\n throw this.#error;\n } else {\n return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) {\n message = reason.message;\n } else {\n message = `${reason}`;\n }\n this.#webSocket.close(3e3, message);\n if (!this.#error) {\n this.#error = reason;\n }\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 async send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) {\n 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\") {\n return new Response(\"This endpoint only accepts POST requests.\", { status: 405 });\n }\n let body = await request.text();\n let batch = body === \"\" ? [] : body.split(\"\\n\");\n let transport = new BatchServerTransport(batch);\n let rpc = new RpcSession(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) {\n this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n } else {\n this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\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 [\n \"remap\",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => [\"import\", cap]),\n this.instructions\n ]\n );\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else {\n return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\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([\"pipeline\", subject, path, devalued]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push([\"pipeline\", subject, path]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) {\n return hook.idx;\n }\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 {\n this.context.captures.push(hook);\n }\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n // ---------------------------------------------------------------------------\n // implements Exporter\n exportStub(hook) {\n throw new Error(\n \"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 }\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(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(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\n \"Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.\"\n );\n}\nvar MapVariableHook = class extends StubHook {\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n // We don't have anything we actually need to dispose, so dup() can just return the same hook.\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) {\n return this;\n } else if (currentMapBuilder) {\n return currentMapBuilder.pushGet(this, path);\n } else {\n throwMapperBuilderUseError();\n }\n }\n // Other methods should never be called.\n call(path, args) {\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n variables;\n dispose() {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) {\n throw new Error(\"Invalid empty mapper function.\");\n }\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub) {\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) {\n variable.dispose();\n }\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) {\n return this.captures[-idx - 1];\n } else {\n return this.variables[idx];\n }\n }\n getPipeReadable(exportId) {\n throw new Error(\"A mapper function cannot use pipe readables.\");\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));\n let mapper = new MapApplicator(captures, inputHook);\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) {\n 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) {\n payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n }\n } catch (err) {\n for (let payload of payloads) {\n payload.dispose();\n }\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) {\n result = RpcPayload.fromAppReturn(input);\n } else {\n result = applyMapToElement(input, parent, owner, captures, instructions);\n }\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) {\n cap.dispose();\n }\n }\n};\nvar WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.\n static create(stream) {\n let writer = stream.getWriter();\n return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n getState() {\n if (this.state) {\n return this.state;\n } else {\n throw new Error(\"Attempted to use a WritableStreamStubHook after it was disposed.\");\n }\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== \"string\") {\n throw new Error(\"WritableStream stub only supports direct method calls\");\n }\n const method = path[0];\n if (method !== \"write\" && method !== \"close\" && method !== \"abort\") {\n args.dispose();\n throw new Error(`Unknown WritableStream method: ${method}`);\n }\n if (method === \"close\" || method === \"abort\") {\n state.closed = true;\n }\n let func = state.writer[method];\n let promise = args.deliverCall(func, state.writer);\n return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error(\"Cannot use map() on a WritableStream\"));\n }\n get(path) {\n return new ErrorStubHook(new Error(\"Cannot access properties on a WritableStream stub\"));\n }\n dup() {\n let state = this.getState();\n return new _WritableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(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) {\n state.writer.abort(new Error(\"WritableStream RPC stub was disposed without calling close()\")).catch(() => {\n });\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 constructor(now) {\n this.now = now;\n }\n // The current window size in bytes. The sender blocks when bytesInFlight >= window.\n window = INITIAL_WINDOW;\n // Total bytes currently in flight (sent but not yet acked).\n bytesInFlight = 0;\n // Whether we're still in the startup phase.\n inStartupPhase = true;\n // ----- BDP estimation state (private) -----\n // Total bytes acked so far.\n delivered = 0;\n // Time of most recent ack.\n deliveredTime = 0;\n // Time when the very first ack was received.\n firstAckTime = 0;\n firstAckDelivered = 0;\n // Global minimum RTT observed (milliseconds).\n minRtt = Infinity;\n // For startup exit: count of consecutive RTT rounds where the window didn't meaningfully grow.\n roundsWithoutIncrease = 0;\n // Window size at the start of the current round, for startup exit detection.\n lastRoundWindow = 0;\n // Time when the current round started.\n roundStartTime = 0;\n // Called when a write of `size` bytes is about to be sent. Returns a token that must be\n // passed to onAck() when the ack arrives, and whether the sender should block (window full).\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 { token, shouldBlock: token.windowFullAtSend };\n }\n // Called when a previously-sent write fails. Restores bytesInFlight without updating\n // any BDP estimates.\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n // Called when an ack is received for a previously-sent write. Updates BDP estimates and\n // the window. Returns whether a blocked sender should now unblock.\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 bytes = this.delivered - baseDelivered;\n let bandwidth = bytes / 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) {\n newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n } else {\n newWindow = Math.max(newWindow, this.window);\n }\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) {\n this.roundsWithoutIncrease = 0;\n } else {\n if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {\n this.inStartupPhase = false;\n }\n }\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) {\n throw pendingError;\n }\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream([\"write\"], payload);\n if (size === void 0) {\n return promise.catch((err) => {\n if (pendingError === void 0) {\n pendingError = err;\n }\n throw err;\n });\n } else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n let hasCapacity = fc.onAck(token);\n if (hasCapacity && 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) {\n return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\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) {\n return;\n }\n pendingError = reason ?? 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 _ReadableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new ReadableStreamStubHook.\n static create(stream) {\n return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(new Error(\"Cannot call methods on a ReadableStream stub\"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error(\"Cannot use map() on a ReadableStream\"));\n }\n get(path) {\n return new ErrorStubHook(new Error(\"Cannot access properties on a ReadableStream stub\"));\n }\n dup() {\n let state = this.state;\n if (!state) {\n throw new Error(\"Attempted to dup a ReadableStreamStubHook after it was disposed.\");\n }\n return new _ReadableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(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) {\n state.stream.cancel(\n new Error(\"ReadableStream RPC stub was disposed without being consumed\")\n ).catch(() => {\n });\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) {\n if (request.method === \"POST\") {\n let response = await newHttpBatchRpcResponse(request, localMain);\n response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n return response;\n } else if (request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\") {\n return newWorkersWebSocketRpcResponse(request, localMain);\n } else {\n return new Response(\"This endpoint only accepts POST or WebSocket requests.\", { status: 400 });\n }\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 === \"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}\nvar ProxyServerWorker_default = {\n async fetch(request, env) {\n try {\n 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";
|
|
80754
|
+
var ProxyServerWorker_default = "// ../../node_modules/.pnpm/capnweb@0.5.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) {\n Symbol.dispose = /* @__PURE__ */ Symbol.for(\"dispose\");\n}\nif (!Symbol.asyncDispose) {\n Symbol.asyncDispose = /* @__PURE__ */ Symbol.for(\"asyncDispose\");\n}\nif (!Promise.withResolvers) {\n Promise.withResolvers = function() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve, reject };\n };\n}\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\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) {\n return \"primitive\";\n }\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 return \"bytes\";\n case WritableStream.prototype:\n return \"writable\";\n case ReadableStream.prototype:\n return \"readable\";\n case Headers.prototype:\n return \"headers\";\n case Request.prototype:\n return \"request\";\n case Response.prototype:\n return \"response\";\n // TODO: All other structured clone types.\n case RpcStub.prototype:\n return \"stub\";\n case RpcPromise.prototype:\n return \"rpc-promise\";\n // TODO: Promise<T> or thenable\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) {\n return \"rpc-target\";\n } else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) {\n return \"rpc-thenable\";\n }\n }\n if (value instanceof RpcTarget) {\n return \"rpc-target\";\n }\n if (value instanceof Error) {\n return \"error\";\n }\n return \"unsupported\";\n }\n}\nfunction mapNotLoaded() {\n throw new Error(\"RPC map() implementation was not loaded.\");\n}\nvar mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };\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 // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:\n // - promise: A Promise<void> for the completion of the call.\n // - size: If the call was remote, the byte size of the serialized message. For local calls,\n // undefined is returned, indicating the caller should await the promise to serialize writes\n // (no overlapping).\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled = hook.pull();\n let promise;\n if (pulled instanceof Promise) {\n 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 constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n return this;\n }\n map(path, captures, instructions) {\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(\n new Error(\"Attempted to use RPC stub after it has been disposed.\")\n);\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(doCall(\n stub.hook,\n stub.pathIfPromise || [],\n RpcPayload.fromAppParams(argumentsList)\n ), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return stub;\n } else if (prop in RpcPromise.prototype) {\n return stub[prop];\n } else if (typeof prop === \"string\") {\n return new RpcPromise(\n stub.hook,\n stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]\n );\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n } else {\n return void 0;\n }\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) {\n return true;\n } else if (prop in RpcPromise.prototype) {\n return prop in stub;\n } else if (typeof prop === \"string\") {\n return true;\n } else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) {\n return true;\n } else {\n return false;\n }\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 return void 0;\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 = class _RpcStub extends RpcTarget {\n // Although `hook` and `path` are declared `public` here, they are effectively hidden by the\n // proxy.\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget || value instanceof Function) {\n hook = TargetStubHook.create(value, void 0);\n } else {\n hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n }\n if (pathIfPromise) {\n throw new TypeError(\"RpcStub constructor expected one argument, received two.\");\n }\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) {\n return new _RpcStub(target.hook.get(target.pathIfPromise));\n } else {\n return new _RpcStub(target.hook.dup());\n }\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 = class extends RpcStub {\n // TODO: Support passing target value or promise to constructor.\n constructor(hook, pathIfPromise) {\n super(hook, pathIfPromise);\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) {\n return hook.get(pathIfPromise);\n } else {\n return hook;\n }\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) {\n return hook.get(pathIfPromise);\n } else {\n return hook.dup();\n }\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) {\n return void 0;\n }\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) {\n hook = hook.get(pathIfPromise);\n }\n let payload = await hook.pull();\n return payload.deliverResolve();\n}\nvar RpcPayload = class _RpcPayload {\n // Private constructor; use factory functions above to construct.\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n // Create a payload from a value passed as params to an RPC from the app.\n //\n // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify\n // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not\n // to have the sender and recipient end up sharing the same mutable object. `value` will not be\n // touched again after the call returns synchronously (returns a promise) -- by that point,\n // the value has either been copied or serialized to the wire.\n static fromAppParams(value) {\n return new _RpcPayload(value, \"params\");\n }\n // Create a payload from a value return from an RPC implementation by the app.\n //\n // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and\n // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It\n // will still avoid modifying `value` and will make a deep copy if it is delivered locally.\n static fromAppReturn(value) {\n return new _RpcPayload(value, \"return\");\n }\n // Combine an array of payloads into a single payload whose value is an array. Ownership of all\n // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the\n // inputs should not be. (In case of exception, nothing is disposed, though.)\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) {\n hooks.push(hook);\n }\n for (let promise of payload.promises) {\n if (promise.parent === payload) {\n promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n }\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new _RpcPayload(resultArray, \"owned\", hooks, promises);\n }\n // Create a payload from a value parsed off the wire using Evaluator.evaluate().\n //\n // A payload is constructed with a null value and the given hooks and promises arrays. The value\n // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected\n // to be extended with stubs found during parsing. (This weird usage model is necessary so that\n // if the root value turns out to be a promise, its `parent` in `promises` can be the payload\n // object itself.)\n //\n // When done, the payload takes ownership of the final value and all the stubs within. It may\n // modify the value in preparation for delivery, and may deliver the value directly to the app\n // without copying.\n static forEvaluate(hooks, promises) {\n return new _RpcPayload(null, \"owned\", hooks, promises);\n }\n // Deep-copy the given value, including dup()ing all stubs.\n //\n // If `value` is a function, it should be bound to `oldParent` as its `this`.\n //\n // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure\n // RpcTargets found within don't get duplicate stubs.\n static deepCopyFrom(value, oldParent, owner) {\n let result = new _RpcPayload(null, \"owned\", [], []);\n result.value = result.deepCopy(\n value,\n oldParent,\n \"value\",\n result,\n /*dupStubs=*/\n true,\n owner\n );\n return result;\n }\n // For `source === \"return\"` payloads only, this tracks any StubHooks created around RpcTargets\n // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for\n // return, so that we can make sure they are not disposed before the pipeline ends.\n //\n // This is initialized on first use.\n rpcTargets;\n // Get the StubHook representing the given RpcTarget found inside this payload.\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === \"params\") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === \"function\") {\n target = dupable.dup();\n }\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw RpcTargets\");\n }\n }\n // Get the StubHook representing the given WritableStream found inside this payload.\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") {\n return streamImpl.createWritableStreamHook(stream);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw WritableStreams\");\n }\n }\n // Get the StubHook representing the given ReadableStream found inside this payload.\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") {\n return streamImpl.createReadableStreamHook(stream);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n if (dupStubs) {\n 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) {\n this.rpcTargets = /* @__PURE__ */ new Map();\n }\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else {\n return hook;\n }\n }\n } else {\n throw new Error(\"owned payload shouldn't contain raw ReadableStreams\");\n }\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n return value;\n case \"primitive\":\n case \"bigint\":\n case \"date\":\n case \"bytes\":\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++) {\n result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n }\n return result;\n }\n case \"object\": {\n let result = {};\n let object = value;\n for (let i in object) {\n result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n }\n return result;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook;\n if (dupStubs) {\n hook = unwrapStubAndDup(stub);\n } else {\n hook = unwrapStubTakingOwnership(stub);\n }\n if (stub instanceof RpcPromise) {\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook;\n if (owner) {\n hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n } else {\n hook = TargetStubHook.create(target, oldParent);\n }\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\n case \"rpc-thenable\": {\n let target = value;\n let promise;\n if (owner) {\n promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n } else {\n promise = new RpcPromise(TargetStubHook.create(target, oldParent), []);\n }\n this.promises.push({ parent, property, promise });\n return promise;\n }\n case \"writable\": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n this.hooks.push(hook);\n return stream;\n }\n case \"readable\": {\n let stream = value;\n let hook;\n if (owner) {\n hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\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) {\n this.deepCopy(req.body, req, \"body\", req, dupStubs, owner);\n }\n return new Request(req);\n }\n case \"response\": {\n let resp = value;\n if (resp.body) {\n this.deepCopy(resp.body, resp, \"body\", resp, dupStubs, owner);\n }\n return new Response(resp.body, resp);\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n // Ensures that if the value originally came from an unowned source, we have replaced it with a\n // deep copy.\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) {\n throw new Error(\"Not all rpcTargets were accounted for in deep-copy?\");\n }\n this.rpcTargets = void 0;\n }\n }\n // Resolve all promises in this payload and then assign the final value into `parent[property]`.\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise) {\n _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);\n } else {\n parent[property] = this.value;\n for (let record of this.promises) {\n _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) {\n throw new Error(\"property promises should have been resolved earlier\");\n }\n let inner = hook.pull();\n if (inner instanceof _RpcPayload) {\n inner.deliverTo(parent, property, promises);\n } else {\n promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) {\n return Promise.all(subPromises);\n }\n }));\n }\n }\n // Call the given function with the payload as an argument. The call is made synchronously if\n // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,\n // they are awaited and substituted before calling the function. The result of the call is\n // wrapped into another payload.\n //\n // The payload is automatically disposed after the call completes. The caller should not call\n // dispose().\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise) {\n return _RpcPayload.fromAppReturn(result);\n } else {\n return _RpcPayload.fromAppReturn(await result);\n }\n } finally {\n this.dispose();\n }\n }\n // Produce a promise for this payload for return to the application. Any RpcPromises in the\n // payload are awaited and substituted with their results first.\n //\n // The returned object will have a disposer which disposes the payload. The caller should not\n // separately dispose it.\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) {\n await Promise.all(promises);\n }\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) {\n Object.defineProperty(result, Symbol.dispose, {\n // NOTE: Using `this.dispose.bind(this)` here causes Playwright's build of\n // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,\n // with the error:\n // TypeError: Symbol(Symbol.dispose) is not a function\n // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,\n // so maybe it was a short-lived V8 bug or something. To be safe, though, we use\n // `() => this.dispose()`, which seems to always work.\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\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) {\n throw new Error(\"Not all rpcTargets were accounted for in disposeImpl()?\");\n }\n } else ;\n this.source = \"owned\";\n this.hooks = [];\n this.promises = [];\n }\n // Recursive dispose, called only when `source` is \"return\".\n disposeImpl(value, parent) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"date\":\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++) {\n this.disposeImpl(array[i], array);\n }\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) {\n this.disposeImpl(object[i], object);\n }\n return;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook = unwrapStubNoProperties(stub);\n if (hook) {\n hook.dispose();\n }\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 {\n disposeRpcTarget(target);\n }\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) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createWritableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n case \"readable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) {\n this.rpcTargets.delete(stream);\n } else {\n hook = streamImpl.createReadableStreamHook(stream);\n }\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n // Ignore unhandled rejections in all promises in this payload -- that is, all promises that\n // *would* be awaited if this payload were to be delivered. See the similarly-named method of\n // StubHook for explanation.\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach(\n (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()\n );\n } else {\n this.ignoreUnhandledRejectionsImpl(this.value);\n }\n }\n ignoreUnhandledRejectionsImpl(value) {\n let kind = typeForRpc(value);\n switch (kind) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"date\":\n case \"error\":\n case \"undefined\":\n case \"function\":\n case \"rpc-target\":\n case \"writable\":\n case \"readable\":\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++) {\n this.ignoreUnhandledRejectionsImpl(array[i]);\n }\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) {\n this.ignoreUnhandledRejectionsImpl(object[i]);\n }\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 let kind = typeForRpc(value);\n switch (kind) {\n case \"object\":\n case \"function\":\n if (Object.hasOwn(value, part)) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case \"array\":\n if (Number.isInteger(part) && part >= 0) {\n value = value[part];\n } else {\n value = void 0;\n }\n break;\n case \"rpc-target\":\n case \"rpc-thenable\": {\n if (Object.hasOwn(value, part)) {\n throw new TypeError(\n `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 );\n } else {\n value = value[part];\n }\n owner = null;\n break;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };\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 \"date\":\n case \"error\":\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) {\n 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(\n `'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`\n );\n }\n }\n default:\n throw new TypeError(\"unreachable\");\n }\n }\n if (value instanceof RpcPromise) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return { hook, remainingPath: pathIfPromise || [] };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n try {\n let { value, owner } = this.getValue();\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) {\n return followResult.hook.call(followResult.remainingPath, args);\n }\n if (typeof followResult.value != \"function\") {\n throw new TypeError(`'${path.join(\".\")}' is not a function.`);\n }\n let promise = args.deliverCall(followResult.value, followResult.parent);\n return new PromiseStubHook(promise.then((payload) => {\n return new PayloadStubHook(payload);\n }));\n } catch (err) {\n return new ErrorStubHook(err);\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 ;\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (followResult.hook) {\n return followResult.hook.map(followResult.remainingPath, captures, instructions);\n }\n return mapImpl.applyMap(\n followResult.value,\n followResult.parent,\n followResult.owner,\n captures,\n instructions\n );\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 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) {\n return followResult.hook.get(followResult.remainingPath);\n }\n return new PayloadStubHook(RpcPayload.deepCopyFrom(\n followResult.value,\n followResult.parent,\n followResult.owner\n ));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class _PayloadStubHook extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n // cleared when disposed\n getPayload() {\n if (this.payload) {\n return this.payload;\n } else {\n throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n }\n getValue() {\n let payload = this.getPayload();\n return { value: payload.value, owner: payload };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new _PayloadStubHook(RpcPayload.deepCopyFrom(\n thisPayload.value,\n void 0,\n thisPayload\n ));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) {\n this.payload.ignoreUnhandledRejections();\n }\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) {\n this.payload.value.onRpcBroken(callback);\n }\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) {\n try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n }\n}\nvar TargetStubHook = class _TargetStubHook extends ValueStubHook {\n // Constructs a TargetStubHook that is not duplicated from an existing hook.\n //\n // If `value` is a function, `parent` is bound as its \"this\".\n static create(value, parent) {\n if (typeof value !== \"function\") {\n parent = void 0;\n }\n return new _TargetStubHook(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) {\n this.refcount = { count: 1 };\n }\n }\n target;\n // cleared when disposed\n parent;\n // `this` parameter when calling `target`\n refcount;\n // undefined if not needed (because target has no disposer)\n getTarget() {\n if (this.target) {\n return this.target;\n } else {\n throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n }\n getValue() {\n return { value: this.getTarget(), owner: null };\n }\n dup() {\n return new _TargetStubHook(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if (\"then\" in target) {\n return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n } else {\n return Promise.reject(new Error(\"Tried to resolve a non-promise stub.\"));\n }\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) {\n disposeRpcTarget(this.target);\n }\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n }\n};\nvar PromiseStubHook = class _PromiseStubHook 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 _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n let promise = this.promise.then((hook) => {\n let result = hook.stream(path, args);\n return result.promise;\n });\n return { promise };\n }\n map(path, captures, instructions) {\n return new _PromiseStubHook(this.promise.then(\n (hook) => hook.map(path, captures, instructions),\n (err) => {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n ));\n }\n get(path) {\n return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) {\n return this.resolution.dup();\n } else {\n return new _PromiseStubHook(this.promise.then((hook) => hook.dup()));\n }\n }\n pull() {\n if (this.resolution) {\n return this.resolution.pull();\n } else {\n return this.promise.then((hook) => hook.pull());\n }\n }\n ignoreUnhandledRejections() {\n if (this.resolution) {\n this.resolution.ignoreUnhandledRejections();\n } else {\n this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n }\n dispose() {\n if (this.resolution) {\n this.resolution.dispose();\n } else {\n this.promise.then((hook) => {\n hook.dispose();\n }, (err) => {\n });\n }\n }\n onBroken(callback) {\n if (this.resolution) {\n this.resolution.onBroken(callback);\n } else {\n this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\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 return void 0;\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();\nvar ERROR_TYPES = {\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n // TODO: DOMError? Others?\n};\nvar Devaluator = class _Devaluator {\n constructor(exporter, source) {\n this.exporter = exporter;\n this.source = source;\n }\n // Devaluate the given value.\n // * value: The value to devaluate.\n // * parent: The value's parent object, which would be used as `this` if the value were called\n // as a function.\n // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.\n // * source: The RpcPayload which contains the value, and therefore owns stubs within.\n //\n // Returns: The devaluated value, ready to be JSON-serialized.\n static devaluate(value, parent, exporter = NULL_EXPORTER, source) {\n let devaluator = new _Devaluator(exporter, source);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) {\n try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 64) {\n throw new Error(\n \"Serialization exceeded maximum allowed depth. (Does the message contain cycles?)\"\n );\n }\n let kind = typeForRpc(value);\n switch (kind) {\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 (value === Infinity) {\n return [\"inf\"];\n } else if (value === -Infinity) {\n return [\"-inf\"];\n } else {\n return [\"nan\"];\n }\n } else {\n return value;\n }\n case \"object\": {\n let object = value;\n let result = {};\n for (let key in object) {\n result[key] = this.devaluateImpl(object[key], object, depth + 1);\n }\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++) {\n result[i] = this.devaluateImpl(array[i], array, depth + 1);\n }\n return [result];\n }\n case \"bigint\":\n return [\"bigint\", value.toString()];\n case \"date\":\n return [\"date\", value.getTime()];\n case \"bytes\": {\n let bytes = value;\n if (bytes.toBase64) {\n return [\"bytes\", bytes.toBase64({ omitPadding: true })];\n } else {\n return [\n \"bytes\",\n btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, \"\"))\n ];\n }\n }\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) {\n init.headers = headers;\n }\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 && ![\"GET\", \"HEAD\", \"OPTIONS\", \"TRACE\", \"DELETE\"].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({\n 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 });\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n init.body = [\"readable\", importId];\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\") {\n init.credentials = req.credentials;\n }\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\") {\n init.encodeResponseBody = cfReq.encodeResponseBody;\n }\n return [\"request\", req.url, init];\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) {\n init.headers = headers;\n }\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== \"automatic\") {\n init.encodeBody = cfResp.encodeBody;\n }\n if (cfResp.webSocket) {\n throw new TypeError(\"Can't serialize a Response containing a webSocket.\");\n }\n return [\"response\", body, init];\n }\n case \"error\": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) {\n e = rewritten;\n }\n let result = [\"error\", e.name, e.message];\n if (rewritten && rewritten.stack) {\n result.push(rewritten.stack);\n }\n return result;\n }\n case \"undefined\":\n return [\"undefined\"];\n case \"stub\":\n case \"rpc-promise\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) {\n if (pathIfPromise) {\n if (pathIfPromise.length > 0) {\n return [\"pipeline\", importId, pathIfPromise];\n } else {\n return [\"pipeline\", importId];\n }\n } else {\n return [\"import\", importId];\n }\n }\n if (pathIfPromise) {\n hook = hook.get(pathIfPromise);\n } else {\n hook = hook.dup();\n }\n return this.devaluateHook(pathIfPromise ? \"promise\" : \"export\", hook);\n }\n case \"function\":\n case \"rpc-target\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"export\", hook);\n }\n case \"rpc-thenable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize RPC stubs in this context.\");\n }\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"promise\", hook);\n }\n case \"writable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize WritableStream in this context.\");\n }\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook(\"writable\", hook);\n }\n case \"readable\": {\n if (!this.source) {\n throw new Error(\"Can't serialize ReadableStream in this context.\");\n }\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n let importId = this.exporter.createPipe(ws, hook);\n return [\"readable\", importId];\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 return void 0;\n }\n getPipeReadable(exportId) {\n throw new Error(\"Cannot retrieve pipe readable without an RPC session.\");\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n let promise = 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 return new RpcPromise(new PromiseStubHook(promise), []);\n}\nvar Evaluator = class _Evaluator {\n constructor(importer) {\n this.importer = importer;\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, \"value\");\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n // Evaluate the value without destroying it.\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property) {\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++) {\n result[i] = this.evaluateImpl(result[i], result, i);\n }\n return result;\n } else switch (value[0]) {\n case \"bigint\":\n if (typeof value[1] == \"string\") {\n return BigInt(value[1]);\n }\n break;\n case \"date\":\n if (typeof value[1] == \"number\") {\n return new Date(value[1]);\n }\n break;\n case \"bytes\": {\n let b64 = Uint8Array;\n if (typeof value[1] == \"string\") {\n if (b64.fromBase64) {\n return b64.fromBase64(value[1]);\n } else {\n let bs = atob(value[1]);\n let len = bs.length;\n let bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = bs.charCodeAt(i);\n }\n return bytes;\n }\n }\n break;\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 = new cls(value[2]);\n if (typeof value[3] === \"string\") {\n result.stack = value[3];\n }\n return result;\n }\n break;\n case \"undefined\":\n if (value.length === 1) {\n return void 0;\n }\n break;\n case \"inf\":\n return Infinity;\n case \"-inf\":\n return -Infinity;\n case \"nan\":\n return NaN;\n case \"headers\":\n if (value.length === 2 && value[1] instanceof Array) {\n return new Headers(value[1]);\n }\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\");\n if (init.body === null || typeof init.body === \"string\" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) ;\n else {\n throw new TypeError(\"Request body must be of type ReadableStream.\");\n }\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, \"signal\");\n if (!(init.signal instanceof AbortSignal)) {\n throw new TypeError(\"Request siganl must be of type AbortSignal.\");\n }\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n }\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({ promise, parent, property });\n return promise;\n } else {\n return result;\n }\n }\n case \"response\": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property);\n if (body === null || typeof body === \"string\" || body instanceof Uint8Array || body instanceof ReadableStream) ;\n else {\n throw new TypeError(\"Response body must be of type ReadableStream.\");\n }\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.webSocket) {\n throw new TypeError(\"Can't deserialize a Response containing a webSocket.\");\n }\n if (init.headers && !(init.headers instanceof Array)) {\n throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n }\n return new Response(body, init);\n }\n case \"import\":\n case \"pipeline\": {\n if (value.length < 2 || value.length > 4) {\n break;\n }\n if (typeof value[1] != \"number\") {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let isPromise = value[0] == \"pipeline\";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise(hook2, []);\n this.promises.push({ promise, parent, property });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise(hook2, []);\n }\n };\n if (value.length == 2) {\n if (isPromise) {\n return addStub(hook.get([]));\n } else {\n return addStub(hook.dup());\n }\n }\n let path = value[2];\n if (!(path instanceof Array)) {\n break;\n }\n if (!path.every(\n (part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n }\n )) {\n break;\n }\n if (value.length == 3) {\n return addStub(hook.get(path));\n }\n let args = value[3];\n if (!(args instanceof Array)) {\n break;\n }\n let subEval = new _Evaluator(this.importer);\n args = subEval.evaluate([args]);\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)) {\n break;\n }\n let hook = this.importer.getExport(value[1]);\n if (!hook) {\n throw new Error(`no such entry on exports table: ${value[1]}`);\n }\n let path = value[2];\n if (!path.every(\n (part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n }\n )) {\n break;\n }\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\") {\n throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n }\n if (cap[0] === \"export\") {\n return this.importer.importStub(cap[1]);\n } else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) {\n throw new Error(`no such entry on exports table: ${cap[1]}`);\n }\n return exp.dup();\n }\n });\n let instructions = value[4];\n let resultHook = hook.map(path, captures, instructions);\n let promise = new RpcPromise(resultHook, []);\n this.promises.push({ promise, parent, property });\n return promise;\n }\n case \"export\":\n case \"promise\":\n if (typeof value[1] == \"number\") {\n if (value[0] == \"promise\") {\n let hook = this.importer.importPromise(value[1]);\n let promise = new RpcPromise(hook, []);\n this.promises.push({ parent, property, promise });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub(hook);\n }\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) {\n if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(result[key], result, key);\n delete result[key];\n } else {\n result[key] = this.evaluateImpl(result[key], result, key);\n }\n }\n return result;\n } else {\n return value;\n }\n }\n};\nvar ImportTableEntry = class {\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) {\n this.activePull = Promise.withResolvers();\n }\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on\n // this import. Initialized on first use (so `undefined` is the same as an empty list).\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) {\n delete this.session.onBrokenCallbacks[endIndex];\n } else {\n delete this.session.onBrokenCallbacks[i];\n }\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) {\n this.resolution.dispose();\n } else {\n this.abort(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) {\n 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 _RpcImportHook extends StubHook {\n // undefined when we're disposed\n // `pulling` is true if we already expect that this import is going to be resolved later, and\n // null if this import is not allowed to be pulled (i.e. it's a stub not a promise).\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n entry;\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) {\n return this.entry;\n } else {\n throw new Error(\"This RpcImportHook was already disposed.\");\n }\n }\n // -------------------------------------------------------------------------------------\n // implements StubHook\n call(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.call(path, args);\n } else {\n return entry.session.sendCall(entry.importId, path, args);\n }\n }\n stream(path, args) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.stream(path, args);\n } else {\n return entry.session.sendStream(entry.importId, path, args);\n }\n }\n map(path, captures, instructions) {\n let entry;\n try {\n entry = this.getEntry();\n } catch (err) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw err;\n }\n if (entry.resolution) {\n return entry.resolution.map(path, captures, instructions);\n } else {\n return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) {\n return entry.resolution.get(path);\n } else {\n return entry.session.sendCall(entry.importId, path);\n }\n }\n dup() {\n return new _RpcImportHook(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) {\n throw new Error(\"Can't pull this hook because it's not a promise hook.\");\n }\n if (entry.resolution) {\n return entry.resolution.pull();\n }\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) {\n entry.dispose();\n }\n }\n }\n onBroken(callback) {\n if (this.entry) {\n this.entry.onBroken(callback);\n }\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 constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n this.exports.push({ hook: mainHook, refcount: 1 });\n this.imports.push(new ImportTableEntry(this, 0, false));\n let rejectFunc;\n let abortPromise = new Promise((resolve, reject) => {\n rejectFunc = reject;\n });\n this.cancelReadLoop = rejectFunc;\n this.readLoop(abortPromise).catch((err) => this.abort(err));\n }\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n // We assign positive numbers to imports we initiate, and negative numbers to exports we\n // initiate. So the next import ID is just `imports.length`, but the next export ID needs\n // to be tracked explicitly.\n nextExportId = -1;\n // If set, call this when all incoming calls are complete.\n onBatchDone;\n // How many promises is our peer expecting us to resolve?\n pullCount = 0;\n // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but\n // may be deleted from the middle (hence leaving the array sparse).\n onBrokenCallbacks = [];\n // Should only be called once immediately after construction.\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(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] = { hook, refcount: 1 };\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] = { hook, refcount: 1 };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) {\n this.releaseExport(id, 1);\n }\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) {\n throw new Error(`no such export ID: ${exportId}`);\n }\n if (entry.refcount < refcount) {\n throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n }\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) {\n return this.options.onSendError(error);\n }\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) {\n throw new Error(`no such export ID: ${exportId}`);\n }\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) {\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(\n (payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload);\n this.send([\"resolve\", exportId, value]);\n if (autoRelease) this.releaseExport(exportId, 1);\n },\n (error) => {\n this.send([\"reject\", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }\n ).catch(\n (error) => {\n try {\n this.send([\"reject\", exportId, Devaluator.devaluate(error, void 0, this)]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }\n ).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) {\n this.onBatchDone.resolve();\n }\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) {\n return hook.entry.importId;\n } else {\n return void 0;\n }\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(\n /*isPromise=*/\n false,\n entry\n );\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) {\n return new ErrorStubHook(new Error(\n \"Bug in RPC system: The peer sent a promise reusing an existing export ID.\"\n ));\n }\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\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) {\n throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n }\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\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(\n /*isPromise=*/\n false,\n entry\n );\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n // Serializes and sends a message. Returns the byte length of the serialized message.\n send(msg) {\n if (this.abortReason !== void 0) {\n return 0;\n }\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 this.transport.send(msgText).catch((err) => this.abort(err, false));\n return msgText.length;\n }\n sendCall(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = [\"pipeline\", id, path];\n if (args) {\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\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(\n /*isPromise=*/\n true,\n entry\n );\n }\n sendStream(id, path, args) {\n if (this.abortReason) throw this.abortReason;\n let value = [\"pipeline\", id, path];\n let devalue = Devaluator.devaluate(args.value, void 0, this, args);\n value.push(devalue[0]);\n let size = this.send([\"stream\", value]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(\n this,\n importId,\n /*pulling=*/\n true\n );\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n let promise = entry.awaitResolution().then(\n (p) => {\n p.dispose();\n delete this.imports[importId];\n },\n (err) => {\n delete this.imports[importId];\n throw err;\n }\n );\n return { promise, size };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) {\n cap.dispose();\n }\n throw this.abortReason;\n }\n let devaluedCaptures = captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) {\n return [\"import\", importId];\n } else {\n return [\"export\", this.exportStub(hook)];\n }\n });\n let value = [\"remap\", id, path, devaluedCaptures, instructions];\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(\n /*isPromise=*/\n true,\n entry\n );\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([\"release\", id, remoteRefcount]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop(error);\n if (trySendAbortMessage) {\n try {\n this.transport.send(JSON.stringify([\"abort\", Devaluator.devaluate(error, void 0, this)])).catch((err) => {\n });\n } catch (err) {\n }\n }\n if (error === void 0) {\n error = \"undefined\";\n }\n this.abortReason = error;\n if (this.onBatchDone) {\n this.onBatchDone.reject(error);\n }\n if (this.transport.abort) {\n try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.onBrokenCallbacks) {\n try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n for (let i in this.imports) {\n this.imports[i].abort(error);\n }\n for (let i in this.exports) {\n this.exports[i].hook.dispose();\n }\n }\n async readLoop(abortPromise) {\n while (!this.abortReason) {\n let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));\n if (this.abortReason) break;\n if (msg instanceof Array) {\n switch (msg[0]) {\n case \"push\":\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n this.exports.push({ hook, refcount: 1 });\n continue;\n }\n break;\n case \"stream\": {\n if (msg.length > 1) {\n let payload = new Evaluator(this).evaluate(msg[1]);\n let hook = new PayloadStubHook(payload);\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({ hook, refcount: 1, autoRelease: true });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case \"pipe\": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({ hook, refcount: 1, pipeReadable: readable });\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 // [\"resolve\", ExportId, Expression]\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) {\n if (msg[0] == \"resolve\") {\n imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));\n } else {\n let payload = new Evaluator(this).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n } else {\n if (msg[0] == \"resolve\") {\n new Evaluator(this).evaluate(msg[2]).dispose();\n }\n }\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).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload, false);\n break;\n }\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) {\n throw this.abortReason;\n }\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = { resolve, reject };\n await promise;\n }\n }\n getStats() {\n let result = { imports: 0, exports: 0 };\n for (let i in this.imports) {\n ++result.imports;\n }\n for (let i in this.exports) {\n ++result.exports;\n }\n return result;\n }\n};\nvar RpcSession = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) {\n mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n } else {\n mainHook = new ErrorStubHook(new Error(\"This connection has no main object.\"));\n }\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub(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(webSocket, localMain, options) {\n if (typeof webSocket === \"string\") {\n webSocket = new WebSocket(webSocket);\n }\n let transport = new WebSocketTransport(webSocket);\n let rpc = new RpcSession(transport, localMain, options);\n return rpc.getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n return new Response(\"This endpoint only accepts WebSocket requests.\", { status: 400 });\n }\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession(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 if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener(\"open\", (event) => {\n try {\n for (let message of this.#sendQueue) {\n webSocket.send(message);\n }\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\") {\n if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else {\n this.#receiveQueue.push(event.data);\n }\n } else {\n this.#receivedError(new TypeError(\"Received non-string message from WebSocket.\"));\n }\n });\n webSocket.addEventListener(\"close\", (event) => {\n this.#receivedError(new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener(\"error\", (event) => {\n this.#receivedError(new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n // only if not opened yet\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n async send(message) {\n if (this.#sendQueue === void 0) {\n this.#webSocket.send(message);\n } else {\n this.#sendQueue.push(message);\n }\n }\n async receive() {\n if (this.#receiveQueue.length > 0) {\n return this.#receiveQueue.shift();\n } else if (this.#error) {\n throw this.#error;\n } else {\n return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) {\n message = reason.message;\n } else {\n message = `${reason}`;\n }\n this.#webSocket.close(3e3, message);\n if (!this.#error) {\n this.#error = reason;\n }\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 async send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) {\n 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\") {\n return new Response(\"This endpoint only accepts POST requests.\", { status: 405 });\n }\n let body = await request.text();\n let batch = body === \"\" ? [] : body.split(\"\\n\");\n let transport = new BatchServerTransport(batch);\n let rpc = new RpcSession(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) {\n this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n } else {\n this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\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 [\n \"remap\",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => [\"import\", cap]),\n this.instructions\n ]\n );\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else {\n return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\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([\"pipeline\", subject, path, devalued]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push([\"pipeline\", subject, path]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) {\n return hook.idx;\n }\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 {\n this.context.captures.push(hook);\n }\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n // ---------------------------------------------------------------------------\n // implements Exporter\n exportStub(hook) {\n throw new Error(\n \"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 }\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(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(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\n \"Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.\"\n );\n}\nvar MapVariableHook = class extends StubHook {\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n // We don't have anything we actually need to dispose, so dup() can just return the same hook.\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) {\n return this;\n } else if (currentMapBuilder) {\n return currentMapBuilder.pushGet(this, path);\n } else {\n throwMapperBuilderUseError();\n }\n }\n // Other methods should never be called.\n call(path, args) {\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n variables;\n dispose() {\n for (let variable of this.variables) {\n variable.dispose();\n }\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) {\n throw new Error(\"Invalid empty mapper function.\");\n }\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub) {\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) {\n variable.dispose();\n }\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) {\n return this.captures[-idx - 1];\n } else {\n return this.variables[idx];\n }\n }\n getPipeReadable(exportId) {\n throw new Error(\"A mapper function cannot use pipe readables.\");\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));\n let mapper = new MapApplicator(captures, inputHook);\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) {\n 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) {\n payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n }\n } catch (err) {\n for (let payload of payloads) {\n payload.dispose();\n }\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) {\n result = RpcPayload.fromAppReturn(input);\n } else {\n result = applyMapToElement(input, parent, owner, captures, instructions);\n }\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) {\n cap.dispose();\n }\n }\n};\nvar WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.\n static create(stream) {\n let writer = stream.getWriter();\n return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n getState() {\n if (this.state) {\n return this.state;\n } else {\n throw new Error(\"Attempted to use a WritableStreamStubHook after it was disposed.\");\n }\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== \"string\") {\n throw new Error(\"WritableStream stub only supports direct method calls\");\n }\n const method = path[0];\n if (method !== \"write\" && method !== \"close\" && method !== \"abort\") {\n args.dispose();\n throw new Error(`Unknown WritableStream method: ${method}`);\n }\n if (method === \"close\" || method === \"abort\") {\n state.closed = true;\n }\n let func = state.writer[method];\n let promise = args.deliverCall(func, state.writer);\n return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error(\"Cannot use map() on a WritableStream\"));\n }\n get(path) {\n return new ErrorStubHook(new Error(\"Cannot access properties on a WritableStream stub\"));\n }\n dup() {\n let state = this.getState();\n return new _WritableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(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) {\n state.writer.abort(new Error(\"WritableStream RPC stub was disposed without calling close()\")).catch(() => {\n });\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 constructor(now) {\n this.now = now;\n }\n // The current window size in bytes. The sender blocks when bytesInFlight >= window.\n window = INITIAL_WINDOW;\n // Total bytes currently in flight (sent but not yet acked).\n bytesInFlight = 0;\n // Whether we're still in the startup phase.\n inStartupPhase = true;\n // ----- BDP estimation state (private) -----\n // Total bytes acked so far.\n delivered = 0;\n // Time of most recent ack.\n deliveredTime = 0;\n // Time when the very first ack was received.\n firstAckTime = 0;\n firstAckDelivered = 0;\n // Global minimum RTT observed (milliseconds).\n minRtt = Infinity;\n // For startup exit: count of consecutive RTT rounds where the window didn't meaningfully grow.\n roundsWithoutIncrease = 0;\n // Window size at the start of the current round, for startup exit detection.\n lastRoundWindow = 0;\n // Time when the current round started.\n roundStartTime = 0;\n // Called when a write of `size` bytes is about to be sent. Returns a token that must be\n // passed to onAck() when the ack arrives, and whether the sender should block (window full).\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 { token, shouldBlock: token.windowFullAtSend };\n }\n // Called when a previously-sent write fails. Restores bytesInFlight without updating\n // any BDP estimates.\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n // Called when an ack is received for a previously-sent write. Updates BDP estimates and\n // the window. Returns whether a blocked sender should now unblock.\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 bytes = this.delivered - baseDelivered;\n let bandwidth = bytes / 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) {\n newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n } else {\n newWindow = Math.max(newWindow, this.window);\n }\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) {\n this.roundsWithoutIncrease = 0;\n } else {\n if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {\n this.inStartupPhase = false;\n }\n }\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) {\n throw pendingError;\n }\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream([\"write\"], payload);\n if (size === void 0) {\n return promise.catch((err) => {\n if (pendingError === void 0) {\n pendingError = err;\n }\n throw err;\n });\n } else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n let hasCapacity = fc.onAck(token);\n if (hasCapacity && 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) {\n return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\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) {\n return;\n }\n pendingError = reason ?? 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 _ReadableStreamStubHook extends StubHook {\n state;\n // undefined when disposed\n // Creates a new ReadableStreamStubHook.\n static create(stream) {\n return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) {\n ++state.refcount;\n }\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(new Error(\"Cannot call methods on a ReadableStream stub\"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) {\n cap.dispose();\n }\n return new ErrorStubHook(new Error(\"Cannot use map() on a ReadableStream\"));\n }\n get(path) {\n return new ErrorStubHook(new Error(\"Cannot access properties on a ReadableStream stub\"));\n }\n dup() {\n let state = this.state;\n if (!state) {\n throw new Error(\"Attempted to dup a ReadableStreamStubHook after it was disposed.\");\n }\n return new _ReadableStreamStubHook(state, this);\n }\n pull() {\n return Promise.reject(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) {\n state.stream.cancel(\n new Error(\"ReadableStream RPC stub was disposed without being consumed\")\n ).catch(() => {\n });\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) {\n if (request.method === \"POST\") {\n let response = await newHttpBatchRpcResponse(request, localMain);\n response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n return response;\n } else if (request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\") {\n return newWorkersWebSocketRpcResponse(request, localMain);\n } else {\n return new Response(\"This endpoint only accepts POST or WebSocket requests.\", { status: 400 });\n }\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 === \"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";
|
|
80688
80755
|
let logger;
|
|
80689
80756
|
function initLogger(value) {
|
|
80690
80757
|
logger = value;
|
|
@@ -81035,11 +81102,11 @@ function isAbortError(err) {
|
|
|
81035
81102
|
var RemoteSessionAuthenticationError = class extends UserError {
|
|
81036
81103
|
/**
|
|
81037
81104
|
* @param cause - The original error that triggered the authentication
|
|
81038
|
-
* failure (e.g. an {@link APIError} with code 9106 or
|
|
81105
|
+
* failure (e.g. an {@link APIError} with code 9106, 10000, or 10405).
|
|
81039
81106
|
*/
|
|
81040
81107
|
constructor(cause) {
|
|
81041
81108
|
const envAuth = getAuthFromEnv();
|
|
81042
|
-
let errorMessage = "
|
|
81109
|
+
let errorMessage = "This Worker uses bindings that need to run remotely, even when developing locally, but the remote session could not be authenticated.\n";
|
|
81043
81110
|
if (envAuth !== void 0) {
|
|
81044
81111
|
const method = "apiToken" in envAuth ? "a custom API token (`CLOUDFLARE_API_TOKEN`)" : "a Global API Key (`CLOUDFLARE_API_KEY`)";
|
|
81045
81112
|
errorMessage += `It looks like you are authenticating via ${method} set in an environment variable.\nThe token may be invalid or lack the required permissions for this operation.
|
|
@@ -81112,7 +81179,8 @@ function createRemoteWorkerInit(props) {
|
|
|
81112
81179
|
function handleUserFriendlyError(error$2, accountId) {
|
|
81113
81180
|
if (error$2 instanceof APIError) switch (error$2.code) {
|
|
81114
81181
|
case 9106:
|
|
81115
|
-
case 1e4:
|
|
81182
|
+
case 1e4:
|
|
81183
|
+
case 10405: throw new RemoteSessionAuthenticationError(error$2);
|
|
81116
81184
|
case 10063: {
|
|
81117
81185
|
const onboardingLink = accountId ? `https://dash.cloudflare.com/${accountId}/workers/onboarding` : "https://dash.cloudflare.com/?to=/:account/workers/onboarding";
|
|
81118
81186
|
logger.error(`You need to register a workers.dev subdomain before running the dev command in remote mode. You can either enable local mode by pressing l, or register a workers.dev subdomain here: ${onboardingLink}`);
|
|
@@ -81409,6 +81477,7 @@ function findRemoteSessionAuthError(error$2) {
|
|
|
81409
81477
|
if (error$2 instanceof Error) return findRemoteSessionAuthError(error$2.cause);
|
|
81410
81478
|
}
|
|
81411
81479
|
async function startRemoteProxySession(bindings$1, options) {
|
|
81480
|
+
for (const [name, binding] of Object.entries(bindings$1 ?? {})) if (binding.type === "flagship" && binding.app_id === void 0) throw new UserError(`Flagship binding "${name}" has no \`app_id\` and has not been created, but needs to run remotely. Run \`wrangler flagship apps create\` to create an app.`, { telemetryMessage: "flagship remote binding missing app_id" });
|
|
81412
81481
|
options.logger.log(source_default.dim("⎔ Establishing remote connection..."));
|
|
81413
81482
|
initLogger(getInternalLogger(options.logger));
|
|
81414
81483
|
const rawBindings = toRawBindings(bindings$1);
|
|
@@ -84318,15 +84387,31 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
|
|
|
84318
84387
|
},
|
|
84319
84388
|
__VITE_FETCH_HTML__: async (request$2) => {
|
|
84320
84389
|
const { pathname } = new URL(request$2.url);
|
|
84321
|
-
const { root, publicDir } = resolvedViteConfig;
|
|
84322
|
-
const isInPublicDir = pathname.startsWith(PUBLIC_DIR_PREFIX);
|
|
84323
|
-
const resolvedPath = isInPublicDir ? path2.join(publicDir, pathname.slice(20)) : path2.join(root, pathname);
|
|
84324
84390
|
try {
|
|
84391
|
+
const { root, publicDir } = resolvedViteConfig;
|
|
84392
|
+
if (pathname.startsWith(PUBLIC_DIR_PREFIX)) {
|
|
84393
|
+
const resolvedPath$1 = path2.join(publicDir, pathname.slice(20));
|
|
84394
|
+
return new Response$1(await fsp.readFile(resolvedPath$1, "utf-8"), { headers: { "Content-Type": "text/html" } });
|
|
84395
|
+
}
|
|
84396
|
+
const bundledDev = viteDevServer.environments.client.bundledDev;
|
|
84397
|
+
if (bundledDev) {
|
|
84398
|
+
await bundledDev.triggerBundleRegenerationIfStale();
|
|
84399
|
+
const key = pathname.slice(1);
|
|
84400
|
+
let file$3 = bundledDev.memoryFiles.get(key);
|
|
84401
|
+
const deadline = Date.now() + 1e4;
|
|
84402
|
+
while (!file$3 && Date.now() < deadline) {
|
|
84403
|
+
await timersPromises.setTimeout(10);
|
|
84404
|
+
file$3 = bundledDev.memoryFiles.get(key);
|
|
84405
|
+
}
|
|
84406
|
+
if (!file$3) throw new Error(`No bundled file for "${pathname}" after waiting for bundle regeneration.`);
|
|
84407
|
+
return new Response$1(typeof file$3.source === "string" ? file$3.source : Buffer.from(file$3.source), { headers: { "Content-Type": "text/html" } });
|
|
84408
|
+
}
|
|
84409
|
+
const resolvedPath = path2.join(root, pathname);
|
|
84325
84410
|
let html = await fsp.readFile(resolvedPath, "utf-8");
|
|
84326
|
-
|
|
84411
|
+
html = await viteDevServer.transformIndexHtml(resolvedPath, html);
|
|
84327
84412
|
return new Response$1(html, { headers: { "Content-Type": "text/html" } });
|
|
84328
|
-
} catch {
|
|
84329
|
-
throw new Error(`Unexpected error. Failed to load "${pathname}"
|
|
84413
|
+
} catch (error$2) {
|
|
84414
|
+
throw new Error(`Unexpected error. Failed to load "${pathname}".`, { cause: error$2 });
|
|
84330
84415
|
}
|
|
84331
84416
|
}
|
|
84332
84417
|
}
|
|
@@ -84456,8 +84541,13 @@ async function getDevMiniflareOptions(ctx, viteDevServer) {
|
|
|
84456
84541
|
unsafeDevRegistryPath: getDefaultDevRegistryPath(),
|
|
84457
84542
|
unsafeTriggerHandlers: true,
|
|
84458
84543
|
unsafeLocalExplorer: getLocalExplorerEnabledFromEnv(),
|
|
84544
|
+
unsafeObservability: getLocalObservabilityEnabledFromEnv(),
|
|
84459
84545
|
telemetry: { enabled: false },
|
|
84460
84546
|
handleStructuredLogs: getStructuredLogsLogger(logger$1),
|
|
84547
|
+
async unsafeHandleRuntimeRestart() {
|
|
84548
|
+
debuglog("workerd restarted after a crash; restarting the Vite dev server");
|
|
84549
|
+
await viteDevServer.restart();
|
|
84550
|
+
},
|
|
84461
84551
|
defaultPersistRoot: getPersistenceRoot(resolvedViteConfig.root, resolvedPluginConfig.persistState),
|
|
84462
84552
|
defaultProjectTmpPath: path2.resolve(resolvedViteConfig.root, ".wrangler/tmp"),
|
|
84463
84553
|
workers: [
|
|
@@ -84611,6 +84701,7 @@ async function getPreviewMiniflareOptions(ctx, vitePreviewServer) {
|
|
|
84611
84701
|
unsafeDevRegistryPath: getDefaultDevRegistryPath(),
|
|
84612
84702
|
unsafeTriggerHandlers: true,
|
|
84613
84703
|
unsafeLocalExplorer: getLocalExplorerEnabledFromEnv(),
|
|
84704
|
+
unsafeObservability: getLocalObservabilityEnabledFromEnv(),
|
|
84614
84705
|
telemetry: { enabled: false },
|
|
84615
84706
|
handleStructuredLogs: getStructuredLogsLogger(logger$1),
|
|
84616
84707
|
defaultPersistRoot: getPersistenceRoot(resolvedViteConfig.root, resolvedPluginConfig.persistState),
|
|
@@ -84688,29 +84779,34 @@ function handleWebSocket(httpServer, miniflare, entryWorkerName) {
|
|
|
84688
84779
|
});
|
|
84689
84780
|
httpServer.on("upgrade", async (request$2, socket, head) => {
|
|
84690
84781
|
socket.on("error", () => socket.destroy());
|
|
84691
|
-
|
|
84692
|
-
|
|
84693
|
-
|
|
84694
|
-
|
|
84695
|
-
|
|
84696
|
-
|
|
84697
|
-
|
|
84698
|
-
|
|
84699
|
-
|
|
84700
|
-
|
|
84701
|
-
|
|
84702
|
-
|
|
84703
|
-
|
|
84704
|
-
|
|
84705
|
-
|
|
84782
|
+
try {
|
|
84783
|
+
const rawHost = request$2.headers.host ?? UNKNOWN_HOST;
|
|
84784
|
+
const protocol = getForwardedProto(request$2) ?? "http:";
|
|
84785
|
+
const base = /^https?:\/\//i.test(rawHost) ? rawHost : `${protocol}//${rawHost}`;
|
|
84786
|
+
const url$2 = new URL(request$2.url ?? "", base);
|
|
84787
|
+
const isViteRequest = request$2.headers["sec-websocket-protocol"]?.startsWith("vite");
|
|
84788
|
+
const isSandboxRequest = hasSandboxOrigin(url$2.origin);
|
|
84789
|
+
if (isViteRequest && !isSandboxRequest) return;
|
|
84790
|
+
const headers = createHeaders(request$2);
|
|
84791
|
+
if (entryWorkerName) headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
|
|
84792
|
+
const response = await miniflare.dispatchFetch(url$2, {
|
|
84793
|
+
headers,
|
|
84794
|
+
method: request$2.method
|
|
84795
|
+
});
|
|
84796
|
+
const workerWebSocket = response.webSocket;
|
|
84797
|
+
if (!workerWebSocket) {
|
|
84798
|
+
socket.destroy();
|
|
84799
|
+
return;
|
|
84800
|
+
}
|
|
84801
|
+
workerResponseHeaders.set(request$2, response.headers);
|
|
84802
|
+
nodeWebSocket.handleUpgrade(request$2, socket, head, async (clientWebSocket) => {
|
|
84803
|
+
coupleWebSocket(clientWebSocket, workerWebSocket);
|
|
84804
|
+
nodeWebSocket.emit("connection", clientWebSocket, request$2);
|
|
84805
|
+
});
|
|
84806
|
+
} catch {
|
|
84807
|
+
workerResponseHeaders.delete(request$2);
|
|
84706
84808
|
socket.destroy();
|
|
84707
|
-
return;
|
|
84708
84809
|
}
|
|
84709
|
-
workerResponseHeaders.set(request$2, response.headers);
|
|
84710
|
-
nodeWebSocket.handleUpgrade(request$2, socket, head, async (clientWebSocket) => {
|
|
84711
|
-
coupleWebSocket(clientWebSocket, workerWebSocket);
|
|
84712
|
-
nodeWebSocket.emit("connection", clientWebSocket, request$2);
|
|
84713
|
-
});
|
|
84714
84810
|
});
|
|
84715
84811
|
}
|
|
84716
84812
|
/**
|
|
@@ -84764,20 +84860,29 @@ process.on("exit", () => {
|
|
|
84764
84860
|
const devPlugin = createPlugin("dev", (ctx) => {
|
|
84765
84861
|
let containerImageTags = /* @__PURE__ */ new Set();
|
|
84766
84862
|
return {
|
|
84767
|
-
|
|
84768
|
-
if (ctx.resolvedViteConfig.command === "serve" && containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
|
|
84769
|
-
debuglog("buildEnd:", ctx.isRestartingDevServer ? "restarted" : "disposing");
|
|
84770
|
-
if (!ctx.isRestartingDevServer) try {
|
|
84771
|
-
await ctx.disposeMiniflare();
|
|
84772
|
-
} catch (error$2) {
|
|
84773
|
-
debuglog("Failed to dispose Miniflare instance:", error$2);
|
|
84774
|
-
}
|
|
84863
|
+
buildEnd() {
|
|
84864
|
+
if (ctx.resolvedViteConfig.command === "serve" && ctx.isRestartingDevServer && containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
|
|
84775
84865
|
},
|
|
84776
84866
|
async configureServer(viteDevServer) {
|
|
84777
84867
|
assertIsNotPreview(ctx);
|
|
84778
84868
|
const initialOptions = await getDevMiniflareOptions(ctx, viteDevServer);
|
|
84779
84869
|
let containerTagToOptionsMap = initialOptions.containerTagToOptionsMap;
|
|
84780
84870
|
await ctx.startOrUpdateMiniflare(initialOptions.miniflareOptions);
|
|
84871
|
+
const closeServer = viteDevServer.close.bind(viteDevServer);
|
|
84872
|
+
viteDevServer.close = async () => {
|
|
84873
|
+
try {
|
|
84874
|
+
await closeServer();
|
|
84875
|
+
} finally {
|
|
84876
|
+
if (!ctx.isRestartingDevServer) {
|
|
84877
|
+
if (containerImageTags.size) cleanupContainers(getDockerPath(), containerImageTags);
|
|
84878
|
+
try {
|
|
84879
|
+
await ctx.disposeMiniflare();
|
|
84880
|
+
} catch (error$2) {
|
|
84881
|
+
debuglog("Failed to dispose Miniflare instance:", error$2);
|
|
84882
|
+
}
|
|
84883
|
+
}
|
|
84884
|
+
}
|
|
84885
|
+
};
|
|
84781
84886
|
if (viteDevServer.httpServer) viteDevServer.httpServer.on("listening", () => {
|
|
84782
84887
|
const addr = viteDevServer.httpServer?.address();
|
|
84783
84888
|
if (typeof addr === "object" && addr !== null) {
|