@cloudflare/vite-plugin 1.66.0 → 1.68.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
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { a as __toESM$1, i as __require$2, n as __export, r as __name$4, t as __commonJS$1 } from "./chunk-U6NEESU5-
|
|
1
|
+
import { a as __toESM$1, i as __require$2, n as __export, r as __name$4, t as __commonJS$1 } from "./chunk-U6NEESU5-WjWnfQLn.mjs";
|
|
2
2
|
import { builtinModules, createRequire } from "node:module";
|
|
3
|
+
import assert from "node:assert";
|
|
3
4
|
import * as fs from "node:fs";
|
|
4
5
|
import fs2, { accessSync, appendFileSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
5
6
|
import * as path from "node:path";
|
|
6
7
|
import path__default, { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
7
|
-
import assert from "node:assert";
|
|
8
8
|
import os, { arch, release, tmpdir } from "node:os";
|
|
9
9
|
import * as util from "node:util";
|
|
10
|
-
import { TextEncoder as TextEncoder$1, format, inspect, isDeepStrictEqual, promisify, stripVTControlCharacters, styleText } from "node:util";
|
|
10
|
+
import { TextDecoder as TextDecoder$1, TextEncoder as TextEncoder$1, format, inspect, isDeepStrictEqual, promisify, stripVTControlCharacters, styleText } from "node:util";
|
|
11
11
|
import process5, { exit, stdin, stdout } from "node:process";
|
|
12
12
|
import tty from "node:tty";
|
|
13
13
|
import url, { URL as URL$1, URLSearchParams as URLSearchParams$1, fileURLToPath, pathToFileURL } from "node:url";
|
|
@@ -21,7 +21,7 @@ import fs4, { constants as constants$1, mkdir, readFile, writeFile } from "node:
|
|
|
21
21
|
import childProcess, { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
22
22
|
import * as timersPromises from "node:timers/promises";
|
|
23
23
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
24
|
-
import { CoreHeaders, CorePaths, DeferredPromise, Log, LogLevel, Miniflare, MiniflareCoreError, Mutex, Request as Request$1, Response as Response$1, buildPublicUrl, convertV4MiniflareOptions, coupleWebSocket, getDefaultDevRegistryPath,
|
|
24
|
+
import { CoreHeaders, CorePaths, DeferredPromise, Log, LogLevel, Miniflare, MiniflareCoreError, Mutex, Request as Request$1, Response as Response$1, buildPublicUrl, convertV4MiniflareOptions, coupleWebSocket, getDefaultDevRegistryPath, getWorkerRegistry, kUnsafeEphemeralUniqueKey, parseForwardedProto, parseModuleFallbackRequest } from "miniflare";
|
|
25
25
|
import * as wrangler from "wrangler";
|
|
26
26
|
import * as vite from "vite";
|
|
27
27
|
import { normalizePath, version } from "vite";
|
|
@@ -65,7 +65,81 @@ var __toESM$2 = (mod$1, isNodeMode, target$1) => (target$1 = mod$1 != null ? __c
|
|
|
65
65
|
var __require$3 = /* @__PURE__ */ createRequire(import.meta.url);
|
|
66
66
|
|
|
67
67
|
//#endregion
|
|
68
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
68
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-2Q77CKVU.mjs
|
|
69
|
+
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
70
|
+
function isCompatDate(str) {
|
|
71
|
+
return /^\d{4}-\d{2}-\d{2}$/.test(str);
|
|
72
|
+
}
|
|
73
|
+
__name$4(isCompatDate, "isCompatDate");
|
|
74
|
+
function formatCompatibilityDate(date$2) {
|
|
75
|
+
const compatDate = date$2.toISOString().slice(0, 10);
|
|
76
|
+
assert(isCompatDate(compatDate));
|
|
77
|
+
return compatDate;
|
|
78
|
+
}
|
|
79
|
+
__name$4(formatCompatibilityDate, "formatCompatibilityDate");
|
|
80
|
+
function getTodaysCompatDate() {
|
|
81
|
+
return formatCompatibilityDate(/* @__PURE__ */ new Date());
|
|
82
|
+
}
|
|
83
|
+
__name$4(getTodaysCompatDate, "getTodaysCompatDate");
|
|
84
|
+
var NODEJS_COMPAT_DEFAULT_ON_DATE = "2026-08-04";
|
|
85
|
+
function isNodejsCompatDefaultOn(compatibilityDate) {
|
|
86
|
+
return compatibilityDate !== void 0 && compatibilityDate >= NODEJS_COMPAT_DEFAULT_ON_DATE;
|
|
87
|
+
}
|
|
88
|
+
__name$4(isNodejsCompatDefaultOn, "isNodejsCompatDefaultOn");
|
|
89
|
+
var NODEJS_COMPAT_V2_SWITCH_OVER_DATE = "2024-09-23";
|
|
90
|
+
function resolveNodejsCompat(compatibilityDate, compatibilityFlags) {
|
|
91
|
+
const isDefaultOn = isNodejsCompatDefaultOn(compatibilityDate);
|
|
92
|
+
const isNodejsCompatEnabled = compatibilityFlags.includes("nodejs_compat") || isDefaultOn && !compatibilityFlags.includes("no_nodejs_compat");
|
|
93
|
+
return {
|
|
94
|
+
isNodejsCompatEnabled,
|
|
95
|
+
isNodejsCompatV2Enabled: compatibilityFlags.includes("nodejs_compat_v2") || !compatibilityFlags.includes("no_nodejs_compat_v2") && (isDefaultOn || isNodejsCompatEnabled && compatibilityDate >= NODEJS_COMPAT_V2_SWITCH_OVER_DATE)
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
__name$4(resolveNodejsCompat, "resolveNodejsCompat");
|
|
99
|
+
function stripRedundantNodejsCompatFlags(compatibilityDate, compatibilityFlags) {
|
|
100
|
+
if (!isNodejsCompatDefaultOn(compatibilityDate)) return compatibilityFlags;
|
|
101
|
+
const redundantFlags = ["nodejs_compat", "nodejs_compat_v2"].filter((flag) => !compatibilityFlags.includes(`no_${flag}`));
|
|
102
|
+
return compatibilityFlags.filter((flag) => !redundantFlags.includes(flag));
|
|
103
|
+
}
|
|
104
|
+
__name$4(stripRedundantNodejsCompatFlags, "stripRedundantNodejsCompatFlags");
|
|
105
|
+
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-NDNWG7VN.mjs
|
|
108
|
+
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
109
|
+
function getNodeCompat(compatibilityDate = "2000-01-01", compatibilityFlags) {
|
|
110
|
+
const { hasNodejsAlsFlag, hasNodejsCompatFlag, hasNoNodejsCompatFlag, hasNodejsCompatV2Flag, hasNoNodejsCompatV2Flag, hasExperimentalNodejsCompatV2Flag } = parseNodeCompatibilityFlags(compatibilityFlags);
|
|
111
|
+
const { isNodejsCompatEnabled, isNodejsCompatV2Enabled } = resolveNodejsCompat(compatibilityDate, compatibilityFlags);
|
|
112
|
+
let mode = null;
|
|
113
|
+
if (isNodejsCompatV2Enabled) mode = "v2";
|
|
114
|
+
else if (isNodejsCompatEnabled) mode = "v1";
|
|
115
|
+
else if (hasNodejsAlsFlag) mode = "als";
|
|
116
|
+
return {
|
|
117
|
+
mode,
|
|
118
|
+
isNodejsCompatEnabled,
|
|
119
|
+
isNodejsCompatV2Enabled,
|
|
120
|
+
hasNodejsAlsFlag,
|
|
121
|
+
hasNodejsCompatFlag,
|
|
122
|
+
hasNoNodejsCompatFlag,
|
|
123
|
+
hasNodejsCompatV2Flag,
|
|
124
|
+
hasNoNodejsCompatV2Flag,
|
|
125
|
+
hasExperimentalNodejsCompatV2Flag
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
__name$4(getNodeCompat, "getNodeCompat");
|
|
129
|
+
function parseNodeCompatibilityFlags(compatibilityFlags) {
|
|
130
|
+
return {
|
|
131
|
+
hasNodejsAlsFlag: compatibilityFlags.includes("nodejs_als"),
|
|
132
|
+
hasNodejsCompatFlag: compatibilityFlags.includes("nodejs_compat"),
|
|
133
|
+
hasNoNodejsCompatFlag: compatibilityFlags.includes("no_nodejs_compat"),
|
|
134
|
+
hasNodejsCompatV2Flag: compatibilityFlags.includes("nodejs_compat_v2"),
|
|
135
|
+
hasNoNodejsCompatV2Flag: compatibilityFlags.includes("no_nodejs_compat_v2"),
|
|
136
|
+
hasExperimentalNodejsCompatV2Flag: compatibilityFlags.includes("experimental:nodejs_compat_v2")
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
__name$4(parseNodeCompatibilityFlags, "parseNodeCompatibilityFlags");
|
|
140
|
+
|
|
141
|
+
//#endregion
|
|
142
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-XEBMRQST.mjs
|
|
69
143
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
70
144
|
var external_exports$1 = {};
|
|
71
145
|
__export(external_exports$1, {
|
|
@@ -12954,8 +13028,8 @@ function generateMultipleOfCheck(doc, ctx, def, accessor) {
|
|
|
12954
13028
|
}
|
|
12955
13029
|
__name$4(generateMultipleOfCheck, "generateMultipleOfCheck");
|
|
12956
13030
|
function generateNumberFormatCheck(doc, def, accessor) {
|
|
12957
|
-
const format$
|
|
12958
|
-
switch (format$
|
|
13031
|
+
const format$3 = def.format;
|
|
13032
|
+
switch (format$3) {
|
|
12959
13033
|
case "safeint":
|
|
12960
13034
|
doc.write(`if (!Number.isSafeInteger(${accessor})) return INVALID;`);
|
|
12961
13035
|
break;
|
|
@@ -12971,21 +13045,21 @@ function generateNumberFormatCheck(doc, def, accessor) {
|
|
|
12971
13045
|
case "float64":
|
|
12972
13046
|
doc.write(`if (!Number.isFinite(${accessor})) return INVALID;`);
|
|
12973
13047
|
break;
|
|
12974
|
-
default: throw new ZodCompileUnsupportedError(`number format ${format$
|
|
13048
|
+
default: throw new ZodCompileUnsupportedError(`number format ${format$3}`);
|
|
12975
13049
|
}
|
|
12976
13050
|
}
|
|
12977
13051
|
__name$4(generateNumberFormatCheck, "generateNumberFormatCheck");
|
|
12978
13052
|
function generateBigIntFormatCheck(doc, def, accessor) {
|
|
12979
|
-
const format$
|
|
12980
|
-
if (!format$
|
|
12981
|
-
switch (format$
|
|
13053
|
+
const format$3 = def.format;
|
|
13054
|
+
if (!format$3) return;
|
|
13055
|
+
switch (format$3) {
|
|
12982
13056
|
case "int64":
|
|
12983
13057
|
doc.write(`if (${accessor} < -9223372036854775808n || ${accessor} > 9223372036854775807n) return INVALID;`);
|
|
12984
13058
|
break;
|
|
12985
13059
|
case "uint64":
|
|
12986
13060
|
doc.write(`if (${accessor} < 0n || ${accessor} > 18446744073709551615n) return INVALID;`);
|
|
12987
13061
|
break;
|
|
12988
|
-
default: throw new ZodCompileUnsupportedError(`bigint format ${format$
|
|
13062
|
+
default: throw new ZodCompileUnsupportedError(`bigint format ${format$3}`);
|
|
12989
13063
|
}
|
|
12990
13064
|
}
|
|
12991
13065
|
__name$4(generateBigIntFormatCheck, "generateBigIntFormatCheck");
|
|
@@ -13162,8 +13236,8 @@ function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) {
|
|
|
13162
13236
|
doc.write(`if (!${patternConst}.test(${accessor})) return INVALID;`);
|
|
13163
13237
|
return accessor;
|
|
13164
13238
|
}
|
|
13165
|
-
const format$
|
|
13166
|
-
switch (format$
|
|
13239
|
+
const format$3 = def.format;
|
|
13240
|
+
switch (format$3) {
|
|
13167
13241
|
case "regex": throw new ZodCompileUnsupportedError("regex format without a pattern");
|
|
13168
13242
|
case "lowercase":
|
|
13169
13243
|
doc.write(`if (${accessor} !== ${accessor}.toLowerCase()) return INVALID;`);
|
|
@@ -13184,7 +13258,7 @@ function generateStringFormatCheck(doc, ctx, def, accessor, needsValue = true) {
|
|
|
13184
13258
|
doc.write(`if (${accessor}.slice(-${suffix.length}) !== ${esc$1(suffix)}) return INVALID;`);
|
|
13185
13259
|
break;
|
|
13186
13260
|
}
|
|
13187
|
-
default: throw new ZodCompileUnsupportedError(`string format ${format$
|
|
13261
|
+
default: throw new ZodCompileUnsupportedError(`string format ${format$3}`);
|
|
13188
13262
|
}
|
|
13189
13263
|
return accessor;
|
|
13190
13264
|
}
|
|
@@ -15320,12 +15394,12 @@ function _stringbool(Classes, _params) {
|
|
|
15320
15394
|
}
|
|
15321
15395
|
__name$4(_stringbool, "_stringbool");
|
|
15322
15396
|
/* @__NO_SIDE_EFFECTS__ */
|
|
15323
|
-
function _stringFormat(Class2, format$
|
|
15397
|
+
function _stringFormat(Class2, format$3, fnOrRegex, _params = {}) {
|
|
15324
15398
|
const params = normalizeParams$1(_params);
|
|
15325
15399
|
const def = {
|
|
15326
15400
|
check: "string_format",
|
|
15327
15401
|
type: "string",
|
|
15328
|
-
format: format$
|
|
15402
|
+
format: format$3,
|
|
15329
15403
|
fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
|
|
15330
15404
|
...params
|
|
15331
15405
|
};
|
|
@@ -15783,9 +15857,9 @@ var addPattern$1 = /* @__PURE__ */ __name$4((agg, pattern) => {
|
|
|
15783
15857
|
var intersectMime$1 = /* @__PURE__ */ __name$4((agg, mime) => {
|
|
15784
15858
|
agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
|
|
15785
15859
|
}, "intersectMime");
|
|
15786
|
-
var setFormat$1 = /* @__PURE__ */ __name$4((agg, format$
|
|
15787
|
-
agg.format = format$
|
|
15788
|
-
if (format$
|
|
15860
|
+
var setFormat$1 = /* @__PURE__ */ __name$4((agg, format$3) => {
|
|
15861
|
+
agg.format = format$3;
|
|
15862
|
+
if (format$3.includes("int")) agg.isInt = true;
|
|
15789
15863
|
}, "setFormat");
|
|
15790
15864
|
var minContributor$1 = /* @__PURE__ */ __name$4((agg, def) => narrowMin$1(agg, "minimum", def.minimum), "minContributor");
|
|
15791
15865
|
var maxContributor$1 = /* @__PURE__ */ __name$4((agg, def) => narrowMax$1(agg, "maximum", def.maximum), "maxContributor");
|
|
@@ -15847,13 +15921,13 @@ var exactPattern$1 = /* @__PURE__ */ __name$4((p$2) => exactPatterns$1.get(p$2)
|
|
|
15847
15921
|
var stringProcessor$1 = /* @__PURE__ */ __name$4((schema, ctx, _json, _params) => {
|
|
15848
15922
|
const json2 = _json;
|
|
15849
15923
|
json2.type = "string";
|
|
15850
|
-
const { minimum, maximum, format: format$
|
|
15924
|
+
const { minimum, maximum, format: format$3, patterns, contentEncoding, laxFormat } = aggregateChecks$1(schema);
|
|
15851
15925
|
if (typeof minimum === "number") json2.minLength = minimum;
|
|
15852
15926
|
if (typeof maximum === "number") json2.maxLength = maximum;
|
|
15853
|
-
if (format$
|
|
15854
|
-
json2.format = formatMap$1[format$
|
|
15927
|
+
if (format$3) {
|
|
15928
|
+
json2.format = formatMap$1[format$3] ?? format$3;
|
|
15855
15929
|
if (json2.format === "") delete json2.format;
|
|
15856
|
-
if (format$
|
|
15930
|
+
if (format$3 === "time" || laxFormat) delete json2.format;
|
|
15857
15931
|
}
|
|
15858
15932
|
if (contentEncoding) json2.contentEncoding = contentEncoding;
|
|
15859
15933
|
if (patterns && patterns.size > 0) {
|
|
@@ -16159,7 +16233,7 @@ function stringifyKeyNames$1(bySchema, json2, visited) {
|
|
|
16159
16233
|
const numericType = !types$4.includes("string") && types$4.some((t$5) => t$5 === "number" || t$5 === "integer");
|
|
16160
16234
|
const values = json2.enum ?? (json2.const !== void 0 ? [json2.const] : void 0);
|
|
16161
16235
|
if (!numericType && !values?.some((v) => typeof v === "number")) return json2;
|
|
16162
|
-
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format: format$
|
|
16236
|
+
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format: format$3, id,...rest } = json2;
|
|
16163
16237
|
if (rest.enum) rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
|
|
16164
16238
|
else if (typeof rest.const === "number") rest.const = String(rest.const);
|
|
16165
16239
|
if (!numericType) return rest;
|
|
@@ -17287,8 +17361,8 @@ var ZodCustomStringFormat = /* @__PURE__ */ $constructor$1("ZodCustomStringForma
|
|
|
17287
17361
|
$ZodCustomStringFormat.init(inst, def);
|
|
17288
17362
|
ZodStringFormat$1.init(inst, def);
|
|
17289
17363
|
});
|
|
17290
|
-
function stringFormat(format$
|
|
17291
|
-
return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format$
|
|
17364
|
+
function stringFormat(format$3, fnOrRegex, _params = {}) {
|
|
17365
|
+
return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format$3, fnOrRegex, _params);
|
|
17292
17366
|
}
|
|
17293
17367
|
__name$4(stringFormat, "stringFormat");
|
|
17294
17368
|
function hostname2(_params) {
|
|
@@ -17304,10 +17378,10 @@ function currencyCode2(_params) {
|
|
|
17304
17378
|
}
|
|
17305
17379
|
__name$4(currencyCode2, "currencyCode");
|
|
17306
17380
|
function hash(alg, params) {
|
|
17307
|
-
const format$
|
|
17308
|
-
const regex$1 = regexes_exports$1[format$
|
|
17309
|
-
if (!regex$1) throw new Error(`Unrecognized hash format: ${format$
|
|
17310
|
-
return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format$
|
|
17381
|
+
const format$3 = `${alg}_${params?.enc ?? "hex"}`;
|
|
17382
|
+
const regex$1 = regexes_exports$1[format$3];
|
|
17383
|
+
if (!regex$1) throw new Error(`Unrecognized hash format: ${format$3}`);
|
|
17384
|
+
return /* @__PURE__ */ _stringFormat(ZodCustomStringFormat, format$3, regex$1, params);
|
|
17311
17385
|
}
|
|
17312
17386
|
__name$4(hash, "hash");
|
|
17313
17387
|
var ZodNumber$1 = /* @__PURE__ */ $constructor$1("ZodNumber", (inst, def) => {
|
|
@@ -18622,33 +18696,33 @@ function convertBaseSchema(schema, ctx) {
|
|
|
18622
18696
|
case "string": {
|
|
18623
18697
|
let stringSchema = z.string();
|
|
18624
18698
|
if (schema.format) {
|
|
18625
|
-
const format$
|
|
18626
|
-
if (format$
|
|
18627
|
-
else if (format$
|
|
18628
|
-
else if (format$
|
|
18629
|
-
else if (format$
|
|
18630
|
-
else if (format$
|
|
18631
|
-
else if (format$
|
|
18632
|
-
else if (format$
|
|
18633
|
-
else if (format$
|
|
18634
|
-
else if (format$
|
|
18635
|
-
else if (format$
|
|
18636
|
-
else if (format$
|
|
18637
|
-
else if (format$
|
|
18638
|
-
else if (format$
|
|
18639
|
-
else if (format$
|
|
18640
|
-
else if (format$
|
|
18641
|
-
else if (format$
|
|
18642
|
-
else if (format$
|
|
18643
|
-
else if (format$
|
|
18644
|
-
else if (format$
|
|
18645
|
-
else if (format$
|
|
18646
|
-
else if (format$
|
|
18647
|
-
else if (format$
|
|
18648
|
-
else if (format$
|
|
18649
|
-
else if (format$
|
|
18650
|
-
else if (format$
|
|
18651
|
-
else if (format$
|
|
18699
|
+
const format$3 = schema.format;
|
|
18700
|
+
if (format$3 === "email") stringSchema = stringSchema.check(z.email());
|
|
18701
|
+
else if (format$3 === "uri" || format$3 === "uri-reference") stringSchema = stringSchema.check(z.url());
|
|
18702
|
+
else if (format$3 === "uuid" || format$3 === "guid") stringSchema = stringSchema.check(z.uuid());
|
|
18703
|
+
else if (format$3 === "date-time") stringSchema = stringSchema.check(z.iso.datetime({ offset: true }));
|
|
18704
|
+
else if (format$3 === "date") stringSchema = stringSchema.check(z.iso.date());
|
|
18705
|
+
else if (format$3 === "time") stringSchema = stringSchema.check(z.regex(fullTime));
|
|
18706
|
+
else if (format$3 === "duration") stringSchema = stringSchema.check(z.iso.duration());
|
|
18707
|
+
else if (format$3 === "hostname") stringSchema = stringSchema.check(z.hostname());
|
|
18708
|
+
else if (format$3 === "ipv4") stringSchema = stringSchema.check(z.ipv4());
|
|
18709
|
+
else if (format$3 === "ipv6") stringSchema = stringSchema.check(z.ipv6());
|
|
18710
|
+
else if (format$3 === "mac") stringSchema = stringSchema.check(z.mac());
|
|
18711
|
+
else if (format$3 === "cidr") stringSchema = stringSchema.check(z.cidrv4());
|
|
18712
|
+
else if (format$3 === "cidr-v6") stringSchema = stringSchema.check(z.cidrv6());
|
|
18713
|
+
else if (format$3 === "base64") stringSchema = stringSchema.check(z.base64());
|
|
18714
|
+
else if (format$3 === "base64url") stringSchema = stringSchema.check(z.base64url());
|
|
18715
|
+
else if (format$3 === "e164") stringSchema = stringSchema.check(z.e164());
|
|
18716
|
+
else if (format$3 === "credit_card") stringSchema = stringSchema.check(z.creditCard());
|
|
18717
|
+
else if (format$3 === "iban") stringSchema = stringSchema.check(z.iban());
|
|
18718
|
+
else if (format$3 === "jwt") stringSchema = stringSchema.check(z.jwt());
|
|
18719
|
+
else if (format$3 === "emoji") stringSchema = stringSchema.check(z.emoji());
|
|
18720
|
+
else if (format$3 === "nanoid") stringSchema = stringSchema.check(z.nanoid());
|
|
18721
|
+
else if (format$3 === "cuid") stringSchema = stringSchema.check(z.cuid());
|
|
18722
|
+
else if (format$3 === "cuid2") stringSchema = stringSchema.check(z.cuid2());
|
|
18723
|
+
else if (format$3 === "ulid") stringSchema = stringSchema.check(z.ulid());
|
|
18724
|
+
else if (format$3 === "xid") stringSchema = stringSchema.check(z.xid());
|
|
18725
|
+
else if (format$3 === "ksuid") stringSchema = stringSchema.check(z.ksuid());
|
|
18652
18726
|
}
|
|
18653
18727
|
if (typeof schema.minLength === "number") stringSchema = stringSchema.min(schema.minLength);
|
|
18654
18728
|
if (typeof schema.maxLength === "number") stringSchema = stringSchema.max(schema.maxLength);
|
|
@@ -19114,7 +19188,7 @@ function formatZodError(error62) {
|
|
|
19114
19188
|
__name$4(formatZodError, "formatZodError");
|
|
19115
19189
|
|
|
19116
19190
|
//#endregion
|
|
19117
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
19191
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-M3RITKR3.mjs
|
|
19118
19192
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
19119
19193
|
function dedent$1(templ) {
|
|
19120
19194
|
var values = [];
|
|
@@ -19152,7 +19226,7 @@ __name$4(dedent$1, "dedent");
|
|
|
19152
19226
|
var esm_default$1 = dedent$1;
|
|
19153
19227
|
|
|
19154
19228
|
//#endregion
|
|
19155
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
19229
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-OWPFSLY6.mjs
|
|
19156
19230
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
19157
19231
|
var UserError = class extends Error {
|
|
19158
19232
|
static {
|
|
@@ -19211,7 +19285,7 @@ function createFatalError(message, isJson, options) {
|
|
|
19211
19285
|
__name$4(createFatalError, "createFatalError");
|
|
19212
19286
|
|
|
19213
19287
|
//#endregion
|
|
19214
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
19288
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-AAQI36FL.mjs
|
|
19215
19289
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
19216
19290
|
function hasKnownExportType(entry) {
|
|
19217
19291
|
const type = entry?.type;
|
|
@@ -19322,7 +19396,7 @@ function validateDurableObjectContainerApplications(config$2, containers = getDu
|
|
|
19322
19396
|
const maybeBoundDO = config$2.durable_objects.bindings.find((durableObject) => durableObject.class_name === container.class_name);
|
|
19323
19397
|
const useSQLite = allDOs.get(container.class_name);
|
|
19324
19398
|
if (useSQLite === void 0 && maybeBoundDO === void 0) throw new UserError(`The container class_name ${container.class_name} does not match any durable object class_name defined in your ${configFileName2}. Note that the durable object must be defined in the same script as the container.`, { telemetryMessage: "no DO defined that matches container class_name" });
|
|
19325
|
-
if (maybeBoundDO?.script_name !== void 0) throw new UserError(`The container ${container.name} is referencing the durable object ${container.class_name}, which appears to be defined on the ${maybeBoundDO.script_name} Worker instead (via the 'script_name' field). You cannot configure a container on a Durable Object that is defined in another Worker.`, { telemetryMessage: "container class_name refers to an external durable object" });
|
|
19399
|
+
if (maybeBoundDO?.script_name !== void 0 && maybeBoundDO.script_name !== config$2.name) throw new UserError(`The container ${container.name} is referencing the durable object ${container.class_name}, which appears to be defined on the ${maybeBoundDO.script_name} Worker instead (via the 'script_name' field). You cannot configure a container on a Durable Object that is defined in another Worker.`, { telemetryMessage: "container class_name refers to an external durable object" });
|
|
19326
19400
|
if (useSQLite === false) throw new UserError(`The container ${container.name} references Durable Object class ${container.class_name}, which uses the legacy KV storage backend. Durable Object-managed Containers require SQLite-backed Durable Objects.`, { telemetryMessage: "durable object container class uses legacy storage" });
|
|
19327
19401
|
}
|
|
19328
19402
|
}
|
|
@@ -19710,7 +19784,7 @@ var CharacterCodes;
|
|
|
19710
19784
|
CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
|
|
19711
19785
|
CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
|
|
19712
19786
|
})(CharacterCodes || (CharacterCodes = {}));
|
|
19713
|
-
function format$
|
|
19787
|
+
function format$2(documentText, range, options) {
|
|
19714
19788
|
let initialIndentLevel;
|
|
19715
19789
|
let formatText;
|
|
19716
19790
|
let formatTextStart;
|
|
@@ -19844,7 +19918,7 @@ function format$3(documentText, range, options) {
|
|
|
19844
19918
|
}
|
|
19845
19919
|
return editOperations;
|
|
19846
19920
|
}
|
|
19847
|
-
__name$4(format$
|
|
19921
|
+
__name$4(format$2, "format");
|
|
19848
19922
|
function repeat(s, count) {
|
|
19849
19923
|
let result = "";
|
|
19850
19924
|
for (let i$1 = 0; i$1 < count; i$1++) result += s;
|
|
@@ -20400,7 +20474,7 @@ function withFormatting(text, edit, options) {
|
|
|
20400
20474
|
while (begin > 0 && !isEOL(newText, begin - 1)) begin--;
|
|
20401
20475
|
while (end < newText.length && !isEOL(newText, end)) end++;
|
|
20402
20476
|
}
|
|
20403
|
-
const edits = format$
|
|
20477
|
+
const edits = format$2(newText, {
|
|
20404
20478
|
offset: begin,
|
|
20405
20479
|
length: end - begin
|
|
20406
20480
|
}, {
|
|
@@ -20499,7 +20573,7 @@ function printParseErrorCode(code) {
|
|
|
20499
20573
|
}
|
|
20500
20574
|
__name$4(printParseErrorCode, "printParseErrorCode");
|
|
20501
20575
|
function format2(documentText, range, options) {
|
|
20502
|
-
return format$
|
|
20576
|
+
return format$2(documentText, range, options);
|
|
20503
20577
|
}
|
|
20504
20578
|
__name$4(format2, "format");
|
|
20505
20579
|
function modify(text, path3, value, options) {
|
|
@@ -21298,10 +21372,10 @@ var APIError = class extends ParseError {
|
|
|
21298
21372
|
* derived from the response's `Retry-After` header (if present).
|
|
21299
21373
|
*/
|
|
21300
21374
|
retryAfterMs;
|
|
21301
|
-
constructor({ status: status$
|
|
21375
|
+
constructor({ status: status$1, retryAfterMs,...rest }) {
|
|
21302
21376
|
super(rest);
|
|
21303
21377
|
this.name = this.constructor.name;
|
|
21304
|
-
this.#status = status$
|
|
21378
|
+
this.#status = status$1;
|
|
21305
21379
|
this.retryAfterMs = retryAfterMs;
|
|
21306
21380
|
}
|
|
21307
21381
|
get status() {
|
|
@@ -21726,7 +21800,7 @@ function formatConfigSnippet(snippet, configPath, formatted = true) {
|
|
|
21726
21800
|
__name$4(formatConfigSnippet, "formatConfigSnippet");
|
|
21727
21801
|
|
|
21728
21802
|
//#endregion
|
|
21729
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
21803
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-QSRIB43D.mjs
|
|
21730
21804
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
21731
21805
|
function getBooleanEnvironmentVariableFactory(options) {
|
|
21732
21806
|
return () => {
|
|
@@ -21771,7 +21845,7 @@ var getDockerPath$1 = getEnvironmentVariableFactory({
|
|
|
21771
21845
|
});
|
|
21772
21846
|
|
|
21773
21847
|
//#endregion
|
|
21774
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
21848
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-MIA26B4M.mjs
|
|
21775
21849
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
21776
21850
|
function isDirectory(path$2) {
|
|
21777
21851
|
return fs2.statSync(path$2, { throwIfNoEntry: false })?.isDirectory() ?? false;
|
|
@@ -21799,7 +21873,7 @@ function removeDirSync$1(dirPath) {
|
|
|
21799
21873
|
__name$4(removeDirSync$1, "removeDirSync");
|
|
21800
21874
|
|
|
21801
21875
|
//#endregion
|
|
21802
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
21876
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-MV2OJK3L.mjs
|
|
21803
21877
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
21804
21878
|
function isWindows() {
|
|
21805
21879
|
return /^win/i.test(process.platform);
|
|
@@ -21931,7 +22005,7 @@ function getGlobalWranglerCachePath() {
|
|
|
21931
22005
|
__name$4(getGlobalWranglerCachePath, "getGlobalWranglerCachePath");
|
|
21932
22006
|
|
|
21933
22007
|
//#endregion
|
|
21934
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
22008
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/chunk-FR75DWDU.mjs
|
|
21935
22009
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
21936
22010
|
var getC3CommandFromEnv = getEnvironmentVariableFactory({
|
|
21937
22011
|
variableName: "WRANGLER_C3_COMMAND",
|
|
@@ -22064,7 +22138,7 @@ var getCloudflaredPathFromEnv = getEnvironmentVariableFactory({ variableName: "C
|
|
|
22064
22138
|
const ANSI_BACKGROUND_OFFSET$1 = 10;
|
|
22065
22139
|
const wrapAnsi16$1 = (offset = 0) => (code) => `\u001B[${code + offset}m`;
|
|
22066
22140
|
const wrapAnsi256$1 = (offset = 0) => (code) => `\u001B[${38 + offset};5;${code}m`;
|
|
22067
|
-
const wrapAnsi16m$1 = (offset = 0) => (red$
|
|
22141
|
+
const wrapAnsi16m$1 = (offset = 0) => (red$1, green$1, blue$1) => `\u001B[${38 + offset};2;${red$1};${green$1};${blue$1}m`;
|
|
22068
22142
|
const styles$2 = {
|
|
22069
22143
|
modifier: {
|
|
22070
22144
|
reset: [0, 0],
|
|
@@ -22152,13 +22226,13 @@ function assembleStyles$1() {
|
|
|
22152
22226
|
styles$2.bgColor.ansi16m = wrapAnsi16m$1(ANSI_BACKGROUND_OFFSET$1);
|
|
22153
22227
|
Object.defineProperties(styles$2, {
|
|
22154
22228
|
rgbToAnsi256: {
|
|
22155
|
-
value(red$
|
|
22156
|
-
if (red$
|
|
22157
|
-
if (red$
|
|
22158
|
-
if (red$
|
|
22159
|
-
return Math.round((red$
|
|
22229
|
+
value(red$1, green$1, blue$1) {
|
|
22230
|
+
if (red$1 === green$1 && green$1 === blue$1) {
|
|
22231
|
+
if (red$1 < 8) return 16;
|
|
22232
|
+
if (red$1 > 248) return 231;
|
|
22233
|
+
return Math.round((red$1 - 8) / 247 * 24) + 232;
|
|
22160
22234
|
}
|
|
22161
|
-
return 16 + 36 * Math.round(red$
|
|
22235
|
+
return 16 + 36 * Math.round(red$1 / 255 * 5) + 6 * Math.round(green$1 / 255 * 5) + Math.round(blue$1 / 255 * 5);
|
|
22162
22236
|
},
|
|
22163
22237
|
enumerable: false
|
|
22164
22238
|
},
|
|
@@ -22189,30 +22263,30 @@ function assembleStyles$1() {
|
|
|
22189
22263
|
value(code) {
|
|
22190
22264
|
if (code < 8) return 30 + code;
|
|
22191
22265
|
if (code < 16) return 90 + (code - 8);
|
|
22192
|
-
let red$
|
|
22193
|
-
let green$
|
|
22194
|
-
let blue$
|
|
22266
|
+
let red$1;
|
|
22267
|
+
let green$1;
|
|
22268
|
+
let blue$1;
|
|
22195
22269
|
if (code >= 232) {
|
|
22196
|
-
red$
|
|
22197
|
-
green$
|
|
22198
|
-
blue$
|
|
22270
|
+
red$1 = ((code - 232) * 10 + 8) / 255;
|
|
22271
|
+
green$1 = red$1;
|
|
22272
|
+
blue$1 = red$1;
|
|
22199
22273
|
} else {
|
|
22200
22274
|
code -= 16;
|
|
22201
22275
|
const remainder = code % 36;
|
|
22202
|
-
red$
|
|
22203
|
-
green$
|
|
22204
|
-
blue$
|
|
22276
|
+
red$1 = Math.floor(code / 36) / 5;
|
|
22277
|
+
green$1 = Math.floor(remainder / 6) / 5;
|
|
22278
|
+
blue$1 = remainder % 6 / 5;
|
|
22205
22279
|
}
|
|
22206
|
-
const value = Math.max(red$
|
|
22280
|
+
const value = Math.max(red$1, green$1, blue$1) * 2;
|
|
22207
22281
|
if (value === 0) return 30;
|
|
22208
|
-
let result = 30 + (Math.round(blue$
|
|
22282
|
+
let result = 30 + (Math.round(blue$1) << 2 | Math.round(green$1) << 1 | Math.round(red$1));
|
|
22209
22283
|
if (value === 2) result += 60;
|
|
22210
22284
|
return result;
|
|
22211
22285
|
},
|
|
22212
22286
|
enumerable: false
|
|
22213
22287
|
},
|
|
22214
22288
|
rgbToAnsi: {
|
|
22215
|
-
value: (red$
|
|
22289
|
+
value: (red$1, green$1, blue$1) => styles$2.ansi256ToAnsi(styles$2.rgbToAnsi256(red$1, green$1, blue$1)),
|
|
22216
22290
|
enumerable: false
|
|
22217
22291
|
},
|
|
22218
22292
|
hexToAnsi: {
|
|
@@ -31520,9 +31594,9 @@ var require_socks5_client = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.
|
|
|
31520
31594
|
handleAuthResponse() {
|
|
31521
31595
|
if (this.buffer.length < 2) return;
|
|
31522
31596
|
const version$5 = this.buffer[0];
|
|
31523
|
-
const status$
|
|
31597
|
+
const status$1 = this.buffer[1];
|
|
31524
31598
|
if (version$5 !== 1) throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version$5}`, "UND_ERR_SOCKS5_AUTH_VERSION");
|
|
31525
|
-
if (status$
|
|
31599
|
+
if (status$1 !== 0) throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
|
|
31526
31600
|
this.buffer = this.buffer.subarray(2);
|
|
31527
31601
|
debug$6("authentication successful");
|
|
31528
31602
|
this.markAuthenticated();
|
|
@@ -39483,19 +39557,19 @@ var require_response = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/
|
|
|
39483
39557
|
});
|
|
39484
39558
|
return responseObject;
|
|
39485
39559
|
}
|
|
39486
|
-
static redirect(url$2, status$
|
|
39560
|
+
static redirect(url$2, status$1 = 302) {
|
|
39487
39561
|
webidl$10.argumentLengthCheck(arguments, 1, "Response.redirect");
|
|
39488
39562
|
url$2 = webidl$10.converters.USVString(url$2);
|
|
39489
|
-
status$
|
|
39563
|
+
status$1 = webidl$10.converters["unsigned short"](status$1);
|
|
39490
39564
|
let parsedURL;
|
|
39491
39565
|
try {
|
|
39492
39566
|
parsedURL = new URL(url$2, relevantRealm.settingsObject.baseUrl);
|
|
39493
39567
|
} catch (err) {
|
|
39494
39568
|
throw new TypeError(`Failed to parse URL from ${url$2}`, { cause: err });
|
|
39495
39569
|
}
|
|
39496
|
-
if (!redirectStatusSet$1.has(status$
|
|
39570
|
+
if (!redirectStatusSet$1.has(status$1)) throw new RangeError(`Invalid status code ${status$1}`);
|
|
39497
39571
|
const responseObject = fromInnerResponse$2(makeResponse$1({}), "immutable");
|
|
39498
|
-
responseObject.#state.status = status$
|
|
39572
|
+
responseObject.#state.status = status$1;
|
|
39499
39573
|
const value = isomorphicEncode$1(URLSerializer$3(parsedURL));
|
|
39500
39574
|
responseObject.#state.headersList.append("location", value, true);
|
|
39501
39575
|
return responseObject;
|
|
@@ -41073,9 +41147,9 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41073
41147
|
})();
|
|
41074
41148
|
}
|
|
41075
41149
|
try {
|
|
41076
|
-
const { body, status: status$
|
|
41150
|
+
const { body, status: status$1, statusText, headersList, socket } = await dispatch({ body: requestBody });
|
|
41077
41151
|
if (socket) response = makeResponse({
|
|
41078
|
-
status: status$
|
|
41152
|
+
status: status$1,
|
|
41079
41153
|
statusText,
|
|
41080
41154
|
headersList,
|
|
41081
41155
|
socket
|
|
@@ -41084,7 +41158,7 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41084
41158
|
const iterator = body[Symbol.asyncIterator]();
|
|
41085
41159
|
fetchParams.controller.next = () => iterator.next();
|
|
41086
41160
|
response = makeResponse({
|
|
41087
|
-
status: status$
|
|
41161
|
+
status: status$1,
|
|
41088
41162
|
statusText,
|
|
41089
41163
|
headersList
|
|
41090
41164
|
});
|
|
@@ -41188,8 +41262,8 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41188
41262
|
onResponseStarted() {
|
|
41189
41263
|
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
|
|
41190
41264
|
},
|
|
41191
|
-
onHeaders(status$
|
|
41192
|
-
if (status$
|
|
41265
|
+
onHeaders(status$1, rawHeaders, resume$1, statusText) {
|
|
41266
|
+
if (status$1 < 200) return false;
|
|
41193
41267
|
const headersList = new HeadersList();
|
|
41194
41268
|
for (let i$1 = 0; i$1 < rawHeaders.length; i$1 += 2) {
|
|
41195
41269
|
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i$1]);
|
|
@@ -41197,9 +41271,9 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41197
41271
|
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i$1 + 1])) for (const val of value) headersList.append(nameStr, val.toString("latin1"), true);
|
|
41198
41272
|
else headersList.append(nameStr, value.toString("latin1"), true);
|
|
41199
41273
|
}
|
|
41200
|
-
const willFollow = headersList.get("location", true) && request$2.redirect === "follow" && redirectStatusSet.has(status$
|
|
41274
|
+
const willFollow = headersList.get("location", true) && request$2.redirect === "follow" && redirectStatusSet.has(status$1);
|
|
41201
41275
|
const decoders = [];
|
|
41202
|
-
if (request$2.method !== "HEAD" && request$2.method !== "CONNECT" && !nullBodyStatus.includes(status$
|
|
41276
|
+
if (request$2.method !== "HEAD" && request$2.method !== "CONNECT" && !nullBodyStatus.includes(status$1) && !willFollow) {
|
|
41203
41277
|
const contentEncoding = headersList.get("content-encoding", true);
|
|
41204
41278
|
/** @type {string[]} */
|
|
41205
41279
|
const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : [];
|
|
@@ -41235,7 +41309,7 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41235
41309
|
this.body = new Readable({ read: resume$1 });
|
|
41236
41310
|
const onError$1 = this.onError.bind(this);
|
|
41237
41311
|
resolve$4({
|
|
41238
|
-
status: status$
|
|
41312
|
+
status: status$1,
|
|
41239
41313
|
statusText,
|
|
41240
41314
|
headersList,
|
|
41241
41315
|
body: decoders.length ? pipeline$1(this.body, ...decoders, (err) => {
|
|
@@ -41261,8 +41335,8 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41261
41335
|
fetchParams.controller.terminate(error$3);
|
|
41262
41336
|
reject(error$3);
|
|
41263
41337
|
},
|
|
41264
|
-
onRequestUpgrade(_controller, status$
|
|
41265
|
-
if (socket.session != null && status$
|
|
41338
|
+
onRequestUpgrade(_controller, status$1, headers, socket) {
|
|
41339
|
+
if (socket.session != null && status$1 !== 200 || socket.session == null && status$1 !== 101) return false;
|
|
41266
41340
|
const headersList = new HeadersList();
|
|
41267
41341
|
for (const [name, value] of Object.entries(headers)) {
|
|
41268
41342
|
if (value == null) continue;
|
|
@@ -41271,15 +41345,15 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41271
41345
|
else headersList.append(headerName, String(value), true);
|
|
41272
41346
|
}
|
|
41273
41347
|
resolve$4({
|
|
41274
|
-
status: status$
|
|
41275
|
-
statusText: STATUS_CODES[status$
|
|
41348
|
+
status: status$1,
|
|
41349
|
+
statusText: STATUS_CODES[status$1],
|
|
41276
41350
|
headersList,
|
|
41277
41351
|
socket
|
|
41278
41352
|
});
|
|
41279
41353
|
return true;
|
|
41280
41354
|
},
|
|
41281
|
-
onUpgrade(status$
|
|
41282
|
-
if (socket.session != null && status$
|
|
41355
|
+
onUpgrade(status$1, rawHeaders, socket) {
|
|
41356
|
+
if (socket.session != null && status$1 !== 200 || socket.session == null && status$1 !== 101) return false;
|
|
41283
41357
|
const headersList = new HeadersList();
|
|
41284
41358
|
for (let i$1 = 0; i$1 < rawHeaders.length; i$1 += 2) {
|
|
41285
41359
|
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i$1]);
|
|
@@ -41288,8 +41362,8 @@ var require_fetch = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/und
|
|
|
41288
41362
|
else headersList.append(nameStr, value.toString("latin1"), true);
|
|
41289
41363
|
}
|
|
41290
41364
|
resolve$4({
|
|
41291
|
-
status: status$
|
|
41292
|
-
statusText: STATUS_CODES[status$
|
|
41365
|
+
status: status$1,
|
|
41366
|
+
statusText: STATUS_CODES[status$1],
|
|
41293
41367
|
headersList,
|
|
41294
41368
|
socket
|
|
41295
41369
|
});
|
|
@@ -45401,7 +45475,7 @@ var require_undici = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/un
|
|
|
45401
45475
|
}) });
|
|
45402
45476
|
|
|
45403
45477
|
//#endregion
|
|
45404
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.
|
|
45478
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-utils@0.51.1_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@22.1_c9b039e4a760058050f2dc3711b5575a/node_modules/@cloudflare/workers-utils/dist/index.mjs
|
|
45405
45479
|
var import_undici$3 = require_undici();
|
|
45406
45480
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
45407
45481
|
var require_vendors$1 = __commonJS$1({ "../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json"(exports$1, module$1) {
|
|
@@ -45815,8 +45889,8 @@ var require_command_exists$2 = __commonJS$1({ "../../node_modules/.pnpm/command-
|
|
|
45815
45889
|
var commandExistsUnix$1 = /* @__PURE__ */ __name$4(function(commandName, cleanedCommandName, callback$1) {
|
|
45816
45890
|
fileNotExists$1(commandName, function(isFile) {
|
|
45817
45891
|
if (!isFile) {
|
|
45818
|
-
exec$3("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }", function(error$3, stdout$
|
|
45819
|
-
callback$1(null, !!stdout$
|
|
45892
|
+
exec$3("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }", function(error$3, stdout$2, stderr$1) {
|
|
45893
|
+
callback$1(null, !!stdout$2);
|
|
45820
45894
|
});
|
|
45821
45895
|
return;
|
|
45822
45896
|
}
|
|
@@ -49092,7 +49166,12 @@ var validateAnalyticsEngineBinding = /* @__PURE__ */ __name$4((diagnostics, fiel
|
|
|
49092
49166
|
diagnostics.errors.push(`"${field}" bindings should, optionally, have a string "dataset" field but got ${JSON.stringify(value)}.`);
|
|
49093
49167
|
isValid = false;
|
|
49094
49168
|
}
|
|
49095
|
-
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
|
|
49169
|
+
validateAdditionalProperties(diagnostics, field, Object.keys(value), [
|
|
49170
|
+
"binding",
|
|
49171
|
+
"dataset",
|
|
49172
|
+
"remote"
|
|
49173
|
+
]);
|
|
49174
|
+
if (!isRemoteValid(value, field, diagnostics)) isValid = false;
|
|
49096
49175
|
return isValid;
|
|
49097
49176
|
}, "validateAnalyticsEngineBinding");
|
|
49098
49177
|
var validateWorkerNamespaceBinding = /* @__PURE__ */ __name$4((diagnostics, field, value) => {
|
|
@@ -50174,7 +50253,6 @@ var BINDING_LOCAL_SUPPORT = {
|
|
|
50174
50253
|
unsafe_hello_world: "local-only",
|
|
50175
50254
|
durable_object_namespace: "local-only",
|
|
50176
50255
|
fetcher: "local-only",
|
|
50177
|
-
analytics_engine: "local-only",
|
|
50178
50256
|
secrets_store_secret: "local-only",
|
|
50179
50257
|
ratelimit: "local-only",
|
|
50180
50258
|
worker_loader: "local-only",
|
|
@@ -50191,6 +50269,7 @@ var BINDING_LOCAL_SUPPORT = {
|
|
|
50191
50269
|
service: "local-and-remote",
|
|
50192
50270
|
queue: "local-and-remote",
|
|
50193
50271
|
flagship: "local-and-remote",
|
|
50272
|
+
analytics_engine: "local-and-remote",
|
|
50194
50273
|
vectorize: "remote",
|
|
50195
50274
|
mtls_certificate: "remote",
|
|
50196
50275
|
dispatch_namespace: "remote",
|
|
@@ -50613,7 +50692,7 @@ function mapWorkerMetadataBindings(bindings) {
|
|
|
50613
50692
|
}, {});
|
|
50614
50693
|
}
|
|
50615
50694
|
__name$4(mapWorkerMetadataBindings, "mapWorkerMetadataBindings");
|
|
50616
|
-
var DEFAULT_COMPAT_DATE = "2026-
|
|
50695
|
+
var DEFAULT_COMPAT_DATE = "2026-11-03";
|
|
50617
50696
|
function constructWranglerConfig(config$2) {
|
|
50618
50697
|
const mappedBindings = mapWorkerMetadataBindings(config$2.bindings);
|
|
50619
50698
|
const durableObjectClassNames = config$2.bindings.filter((binding) => binding.type === "durable_object_namespace" && binding.script_name === config$2.name).map((durableObject) => durableObject.class_name);
|
|
@@ -50983,8 +51062,8 @@ function getBindings(config$2, options) {
|
|
|
50983
51062
|
});
|
|
50984
51063
|
}
|
|
50985
51064
|
__name$4(getBindings, "getBindings");
|
|
50986
|
-
var { dim: dim$
|
|
50987
|
-
var brandColor$
|
|
51065
|
+
var { dim: dim$1, white: white$1 } = source_default;
|
|
51066
|
+
var brandColor$1 = source_default.hex("#BD5B08");
|
|
50988
51067
|
var isConnectedStatusExplained = false;
|
|
50989
51068
|
function printBindings(bindings, options) {
|
|
50990
51069
|
const { containers = [], log: log$2, streamingTailConsumers = [], tailConsumers = [] } = options;
|
|
@@ -51262,12 +51341,12 @@ function printBindings(bindings, options) {
|
|
|
51262
51341
|
mode
|
|
51263
51342
|
};
|
|
51264
51343
|
}));
|
|
51265
|
-
if (analytics_engine_datasets.length > 0) output$1.push(...analytics_engine_datasets.map(({ binding, dataset }) => {
|
|
51344
|
+
if (analytics_engine_datasets.length > 0) output$1.push(...analytics_engine_datasets.map(({ binding, dataset, remote }) => {
|
|
51266
51345
|
return {
|
|
51267
51346
|
name: binding,
|
|
51268
51347
|
type: getBindingTypeFriendlyName("analytics_engine"),
|
|
51269
51348
|
value: dataset ?? binding,
|
|
51270
|
-
mode: getMode({ isSimulatedLocally:
|
|
51349
|
+
mode: getMode({ isSimulatedLocally: context.remoteBindingsDisabled || !remote })
|
|
51271
51350
|
};
|
|
51272
51351
|
}));
|
|
51273
51352
|
if (text_blobs.length > 0) output$1.push(...text_blobs.map(({ binding, source }) => ({
|
|
@@ -51418,13 +51497,13 @@ function printBindings(bindings, options) {
|
|
|
51418
51497
|
const shouldWrap = bindingLength + columnGapSpaces + maxTypeLength + columnGapSpaces + maxModeLength >= process.stdout.columns;
|
|
51419
51498
|
log$2(title2);
|
|
51420
51499
|
const columnGap = shouldWrap ? " ".repeat(columnGapSpacesWrapped) : " ".repeat(columnGapSpaces);
|
|
51421
|
-
log$2(`${padEndAnsi(dim$
|
|
51500
|
+
log$2(`${padEndAnsi(dim$1(headings.binding), shouldWrap ? bindingPrefix.length + maxNameLength : bindingLength)}${columnGap}${padEndAnsi(dim$1(headings.resource), maxTypeLength)}${columnGap}${hasMode ? dim$1(headings.mode) : ""}`);
|
|
51422
51501
|
for (const binding of output$1) {
|
|
51423
|
-
const bindingValue = dim$
|
|
51424
|
-
const bindingString = padEndAnsi(`${white$
|
|
51502
|
+
const bindingValue = dim$1(typeof binding.value === "symbol" ? source_default.italic("inherited") : binding.value ?? "");
|
|
51503
|
+
const bindingString = padEndAnsi(`${white$1(`env.${binding.name}`)}${binding.value && !shouldWrap ? ` (${bindingValue})` : ""}`, shouldWrap ? bindingPrefix.length + maxNameLength : bindingLength);
|
|
51425
51504
|
const suffix = shouldWrap ? binding.value ? `
|
|
51426
51505
|
${bindingValue}` : "" : "";
|
|
51427
|
-
log$2(`${bindingString}${columnGap}${brandColor$
|
|
51506
|
+
log$2(`${bindingString}${columnGap}${brandColor$1(binding.type.padEnd(maxTypeLength))}${columnGap}${hasMode ? binding.mode : ""}${suffix}`);
|
|
51428
51507
|
}
|
|
51429
51508
|
log$2("");
|
|
51430
51509
|
}
|
|
@@ -51460,7 +51539,7 @@ ${containers.map((container) => container.scheduling_policy === "durable_object"
|
|
|
51460
51539
|
log$2(JSON.stringify(context.unsafeMetadata, null, 2));
|
|
51461
51540
|
}
|
|
51462
51541
|
if (hasConnectionStatus && !isConnectedStatusExplained) {
|
|
51463
|
-
log$2(dim$
|
|
51542
|
+
log$2(dim$1(`
|
|
51464
51543
|
Service bindings, Durable Object bindings, and Tail consumers connect to other Wrangler or Vite dev processes running locally, with their connection status indicated by ${source_default.green("[connected]")} or ${source_default.red("[not connected]")}. For more details, refer to https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/#local-development
|
|
51465
51544
|
`));
|
|
51466
51545
|
isConnectedStatusExplained = true;
|
|
@@ -51474,12 +51553,12 @@ __name$4(padEndAnsi, "padEndAnsi");
|
|
|
51474
51553
|
function createGetMode({ isProvisioning = false, isLocalDev = false }) {
|
|
51475
51554
|
return /* @__PURE__ */ __name$4(function bindingMode({ isSimulatedLocally, connected } = {}) {
|
|
51476
51555
|
if (isProvisioning || !isLocalDev) return;
|
|
51477
|
-
if (isSimulatedLocally === void 0) return dim$
|
|
51556
|
+
if (isSimulatedLocally === void 0) return dim$1("not supported");
|
|
51478
51557
|
return `${isSimulatedLocally ? source_default.blue("local") : source_default.yellow("remote")}${connected === void 0 ? "" : connected ? source_default.green(" [connected]") : source_default.red(" [not connected]")}`;
|
|
51479
51558
|
}, "bindingMode");
|
|
51480
51559
|
}
|
|
51481
51560
|
__name$4(createGetMode, "createGetMode");
|
|
51482
|
-
var import_ci_info$
|
|
51561
|
+
var import_ci_info$1 = __toESM$1(require_ci_info$1());
|
|
51483
51562
|
function isTtyInteractive() {
|
|
51484
51563
|
try {
|
|
51485
51564
|
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
@@ -51489,16 +51568,16 @@ function isTtyInteractive() {
|
|
|
51489
51568
|
}
|
|
51490
51569
|
__name$4(isTtyInteractive, "isTtyInteractive");
|
|
51491
51570
|
function isInteractive$1() {
|
|
51492
|
-
if (import_ci_info$
|
|
51571
|
+
if (import_ci_info$1.default.CLOUDFLARE_PAGES || import_ci_info$1.default.CLOUDFLARE_WORKERS) return false;
|
|
51493
51572
|
return isTtyInteractive();
|
|
51494
51573
|
}
|
|
51495
51574
|
__name$4(isInteractive$1, "isInteractive");
|
|
51496
51575
|
function isNonInteractiveOrCI() {
|
|
51497
|
-
return !isInteractive$1() || import_ci_info$
|
|
51576
|
+
return !isInteractive$1() || import_ci_info$1.default.isCI;
|
|
51498
51577
|
}
|
|
51499
51578
|
__name$4(isNonInteractiveOrCI, "isNonInteractiveOrCI");
|
|
51500
51579
|
function isCI() {
|
|
51501
|
-
return import_ci_info$
|
|
51580
|
+
return import_ci_info$1.default.isCI;
|
|
51502
51581
|
}
|
|
51503
51582
|
__name$4(isCI, "isCI");
|
|
51504
51583
|
var arrayFormatter = new Intl.ListFormat("en-US", {
|
|
@@ -51868,9 +51947,9 @@ async function fetchInternalBase(complianceConfig, resource, init = {}, userAgen
|
|
|
51868
51947
|
}
|
|
51869
51948
|
__name$4(fetchInternalBase, "fetchInternalBase");
|
|
51870
51949
|
async function fetchResultBase(complianceConfig, resource, init = {}, userAgent, logger$2, queryParams, abortSignal, credentials) {
|
|
51871
|
-
const { response: json$1, status: status$
|
|
51950
|
+
const { response: json$1, status: status$1, retryAfterMs } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$2, queryParams, abortSignal, credentials);
|
|
51872
51951
|
if (json$1.success) return json$1.result;
|
|
51873
|
-
else throwFetchError(resource, json$1, status$
|
|
51952
|
+
else throwFetchError(resource, json$1, status$1, retryAfterMs);
|
|
51874
51953
|
}
|
|
51875
51954
|
__name$4(fetchResultBase, "fetchResultBase");
|
|
51876
51955
|
async function fetchListResultBase(complianceConfig, resource, init = {}, userAgent, logger$2, queryParams, credentials) {
|
|
@@ -51882,12 +51961,12 @@ async function fetchListResultBase(complianceConfig, resource, init = {}, userAg
|
|
|
51882
51961
|
queryParams = new URLSearchParams$1(queryParams);
|
|
51883
51962
|
queryParams.set("cursor", cursor$1);
|
|
51884
51963
|
}
|
|
51885
|
-
const { response: json$1, status: status$
|
|
51964
|
+
const { response: json$1, status: status$1, retryAfterMs } = await fetchInternalBase(complianceConfig, resource, init, userAgent, logger$2, queryParams, void 0, credentials);
|
|
51886
51965
|
if (json$1.success) {
|
|
51887
51966
|
results.push(...json$1.result);
|
|
51888
51967
|
if (hasCursor(json$1.result_info)) cursor$1 = json$1.result_info?.cursor;
|
|
51889
51968
|
else getMoreResults = false;
|
|
51890
|
-
} else throwFetchError(resource, json$1, status$
|
|
51969
|
+
} else throwFetchError(resource, json$1, status$1, retryAfterMs);
|
|
51891
51970
|
}
|
|
51892
51971
|
return results;
|
|
51893
51972
|
}
|
|
@@ -51974,7 +52053,7 @@ function escapeCharacter(character) {
|
|
|
51974
52053
|
}).join("");
|
|
51975
52054
|
}
|
|
51976
52055
|
__name$4(escapeCharacter, "escapeCharacter");
|
|
51977
|
-
function throwFetchError(resource, response, status$
|
|
52056
|
+
function throwFetchError(resource, response, status$1, retryAfterMs) {
|
|
51978
52057
|
const errors$1 = response.errors ?? [];
|
|
51979
52058
|
for (const error2$1 of errors$1) maybeThrowFriendlyError(error2$1);
|
|
51980
52059
|
const notes = [...errors$1.map((err) => ({ text: renderError(err) })), ...response.messages?.map((msg) => ({ text: typeof msg === "string" ? msg : msg.message ?? String(msg) })) ?? []];
|
|
@@ -51987,7 +52066,7 @@ function throwFetchError(resource, response, status$2, retryAfterMs) {
|
|
|
51987
52066
|
const error$3 = new APIError({
|
|
51988
52067
|
text: `A request to the Cloudflare API (${resource}) failed.`,
|
|
51989
52068
|
notes,
|
|
51990
|
-
status: status$
|
|
52069
|
+
status: status$1,
|
|
51991
52070
|
retryAfterMs,
|
|
51992
52071
|
telemetryMessage: false
|
|
51993
52072
|
});
|
|
@@ -51999,7 +52078,7 @@ function throwFetchError(resource, response, status$2, retryAfterMs) {
|
|
|
51999
52078
|
throw error$3;
|
|
52000
52079
|
}
|
|
52001
52080
|
__name$4(throwFetchError, "throwFetchError");
|
|
52002
|
-
function throwWAFBlockError(headers, method, resource, status$
|
|
52081
|
+
function throwWAFBlockError(headers, method, resource, status$1, statusText, retryAfterMs) {
|
|
52003
52082
|
const rayId = extractWAFBlockRayId(headers);
|
|
52004
52083
|
throw new APIError({
|
|
52005
52084
|
text: "The Cloudflare API responded with a WAF block page instead of the expected JSON response",
|
|
@@ -52007,9 +52086,9 @@ function throwWAFBlockError(headers, method, resource, status$2, statusText, ret
|
|
|
52007
52086
|
{ text: "Cloudflare's firewall (WAF) blocked this API request. This is usually a false positive." },
|
|
52008
52087
|
...rayId ? [{ text: `Cloudflare Ray ID: ${rayId}` }] : [],
|
|
52009
52088
|
{ text: rayId ? "If the issue persists, please open a Cloudflare Support ticket and include the Ray ID above." : "If the issue persists, please open a Cloudflare Support ticket. You can find the Cloudflare Ray ID on the block page in your browser." },
|
|
52010
|
-
{ text: `${method} ${resource} -> ${status$
|
|
52089
|
+
{ text: `${method} ${resource} -> ${status$1} ${statusText}` }
|
|
52011
52090
|
],
|
|
52012
|
-
status: status$
|
|
52091
|
+
status: status$1,
|
|
52013
52092
|
retryAfterMs,
|
|
52014
52093
|
telemetryMessage: false
|
|
52015
52094
|
});
|
|
@@ -52796,7 +52875,7 @@ function compareVersions(a, b) {
|
|
|
52796
52875
|
__name$4(compareVersions, "compareVersions");
|
|
52797
52876
|
async function openInBrowser(url$2, logger$2) {
|
|
52798
52877
|
try {
|
|
52799
|
-
const { default: open$3 } = await import("./open-PCXX3ZDZ-
|
|
52878
|
+
const { default: open$3 } = await import("./open-PCXX3ZDZ-EfkqB6zS.mjs");
|
|
52800
52879
|
(await open$3(url$2)).on("error", (err) => {
|
|
52801
52880
|
handleBrowserOpenError(url$2, err, logger$2);
|
|
52802
52881
|
});
|
|
@@ -53030,6 +53109,280 @@ function leadingMigrationNumber(relativePath) {
|
|
|
53030
53109
|
return parseInt(firstSegment.split("_")[0], 10);
|
|
53031
53110
|
}
|
|
53032
53111
|
__name$4(leadingMigrationNumber, "leadingMigrationNumber");
|
|
53112
|
+
function trimSqlQuery(sql) {
|
|
53113
|
+
if (!mayContainTransaction(sql)) return sql;
|
|
53114
|
+
const trimmedSql = sql.replace("BEGIN TRANSACTION;", "").replace("COMMIT;", "");
|
|
53115
|
+
if (mayContainTransaction(trimmedSql)) throw new UserError("Wrangler could not process the provided SQL file, as it contains several transactions.\nD1 runs your SQL in a transaction for you.\nPlease export an SQL file from your SQLite database and try again.", { telemetryMessage: "d1 execute sql file contains multiple transactions" });
|
|
53116
|
+
return trimmedSql;
|
|
53117
|
+
}
|
|
53118
|
+
__name$4(trimSqlQuery, "trimSqlQuery");
|
|
53119
|
+
function mayContainTransaction(sql) {
|
|
53120
|
+
return sql.includes("BEGIN TRANSACTION");
|
|
53121
|
+
}
|
|
53122
|
+
__name$4(mayContainTransaction, "mayContainTransaction");
|
|
53123
|
+
function mayContainMultipleStatements(sql) {
|
|
53124
|
+
const trimmed = sql.trimEnd();
|
|
53125
|
+
const semiColonIndex = trimmed.indexOf(";");
|
|
53126
|
+
return semiColonIndex !== -1 && semiColonIndex !== trimmed.length - 1;
|
|
53127
|
+
}
|
|
53128
|
+
__name$4(mayContainMultipleStatements, "mayContainMultipleStatements");
|
|
53129
|
+
function splitSqlQuery(sql) {
|
|
53130
|
+
const trimmedSql = trimSqlQuery(sql);
|
|
53131
|
+
if (!mayContainMultipleStatements(trimmedSql)) return [trimmedSql];
|
|
53132
|
+
const split = splitSqlIntoStatements(trimmedSql);
|
|
53133
|
+
if (split.length === 0) return [trimmedSql];
|
|
53134
|
+
else return split;
|
|
53135
|
+
}
|
|
53136
|
+
__name$4(splitSqlQuery, "splitSqlQuery");
|
|
53137
|
+
function normalizeSqlLineEndings(sql) {
|
|
53138
|
+
let normalized = "";
|
|
53139
|
+
let quoteEnd;
|
|
53140
|
+
let inLineComment = false;
|
|
53141
|
+
let inBlockComment = false;
|
|
53142
|
+
for (let index = 0; index < sql.length; index++) {
|
|
53143
|
+
const char = sql[index];
|
|
53144
|
+
const nextChar = sql[index + 1];
|
|
53145
|
+
if (quoteEnd !== void 0) {
|
|
53146
|
+
normalized += char;
|
|
53147
|
+
if (char === quoteEnd) if (nextChar === quoteEnd) {
|
|
53148
|
+
normalized += nextChar;
|
|
53149
|
+
index++;
|
|
53150
|
+
} else quoteEnd = void 0;
|
|
53151
|
+
continue;
|
|
53152
|
+
}
|
|
53153
|
+
if (inLineComment) {
|
|
53154
|
+
if (char === "\r" && nextChar === "\n") {
|
|
53155
|
+
normalized += "\n";
|
|
53156
|
+
index++;
|
|
53157
|
+
inLineComment = false;
|
|
53158
|
+
} else {
|
|
53159
|
+
normalized += char;
|
|
53160
|
+
inLineComment = char !== "\n";
|
|
53161
|
+
}
|
|
53162
|
+
continue;
|
|
53163
|
+
}
|
|
53164
|
+
if (inBlockComment) {
|
|
53165
|
+
if (char === "\r" && nextChar === "\n") {
|
|
53166
|
+
normalized += "\n";
|
|
53167
|
+
index++;
|
|
53168
|
+
} else {
|
|
53169
|
+
normalized += char;
|
|
53170
|
+
if (char === "*" && nextChar === "/") {
|
|
53171
|
+
normalized += nextChar;
|
|
53172
|
+
index++;
|
|
53173
|
+
inBlockComment = false;
|
|
53174
|
+
}
|
|
53175
|
+
}
|
|
53176
|
+
continue;
|
|
53177
|
+
}
|
|
53178
|
+
if (char === "-" && nextChar === "-") {
|
|
53179
|
+
normalized += "--";
|
|
53180
|
+
index++;
|
|
53181
|
+
inLineComment = true;
|
|
53182
|
+
continue;
|
|
53183
|
+
}
|
|
53184
|
+
if (char === "/" && nextChar === "*") {
|
|
53185
|
+
normalized += "/*";
|
|
53186
|
+
index++;
|
|
53187
|
+
inBlockComment = true;
|
|
53188
|
+
continue;
|
|
53189
|
+
}
|
|
53190
|
+
if (char === "'" || char === "\"" || char === "`") {
|
|
53191
|
+
normalized += char;
|
|
53192
|
+
quoteEnd = char;
|
|
53193
|
+
continue;
|
|
53194
|
+
}
|
|
53195
|
+
if (char === "[") {
|
|
53196
|
+
normalized += char;
|
|
53197
|
+
quoteEnd = "]";
|
|
53198
|
+
continue;
|
|
53199
|
+
}
|
|
53200
|
+
if (char === "\r" && nextChar === "\n") {
|
|
53201
|
+
normalized += "\n";
|
|
53202
|
+
index++;
|
|
53203
|
+
continue;
|
|
53204
|
+
}
|
|
53205
|
+
normalized += char;
|
|
53206
|
+
}
|
|
53207
|
+
return normalized;
|
|
53208
|
+
}
|
|
53209
|
+
__name$4(normalizeSqlLineEndings, "normalizeSqlLineEndings");
|
|
53210
|
+
function splitSqlIntoStatements(sql) {
|
|
53211
|
+
const statements = [];
|
|
53212
|
+
let start = 0;
|
|
53213
|
+
while (start < sql.length) {
|
|
53214
|
+
const { end, hasUsefulToken } = findCompleteStatementEnd(sql, start);
|
|
53215
|
+
if (end === void 0) {
|
|
53216
|
+
if (hasUsefulToken) statements.push(sql.slice(start).trim());
|
|
53217
|
+
break;
|
|
53218
|
+
}
|
|
53219
|
+
const statement = sql.slice(start, end - 1).trim();
|
|
53220
|
+
if (hasUsefulToken && statement.length > 0) statements.push(statement);
|
|
53221
|
+
start = end;
|
|
53222
|
+
}
|
|
53223
|
+
return statements;
|
|
53224
|
+
}
|
|
53225
|
+
__name$4(splitSqlIntoStatements, "splitSqlIntoStatements");
|
|
53226
|
+
var transitions = {
|
|
53227
|
+
INVALID: {
|
|
53228
|
+
tkSEMI: "START",
|
|
53229
|
+
tkWS: "INVALID",
|
|
53230
|
+
tkOTHER: "NORMAL",
|
|
53231
|
+
tkEXPLAIN: "EXPLAIN",
|
|
53232
|
+
tkCREATE: "CREATE",
|
|
53233
|
+
tkTEMP: "NORMAL",
|
|
53234
|
+
tkTRIGGER: "NORMAL",
|
|
53235
|
+
tkEND: "NORMAL"
|
|
53236
|
+
},
|
|
53237
|
+
START: {
|
|
53238
|
+
tkSEMI: "START",
|
|
53239
|
+
tkWS: "START",
|
|
53240
|
+
tkOTHER: "NORMAL",
|
|
53241
|
+
tkEXPLAIN: "EXPLAIN",
|
|
53242
|
+
tkCREATE: "CREATE",
|
|
53243
|
+
tkTEMP: "NORMAL",
|
|
53244
|
+
tkTRIGGER: "NORMAL",
|
|
53245
|
+
tkEND: "NORMAL"
|
|
53246
|
+
},
|
|
53247
|
+
NORMAL: {
|
|
53248
|
+
tkSEMI: "START",
|
|
53249
|
+
tkWS: "NORMAL",
|
|
53250
|
+
tkOTHER: "NORMAL",
|
|
53251
|
+
tkEXPLAIN: "NORMAL",
|
|
53252
|
+
tkCREATE: "NORMAL",
|
|
53253
|
+
tkTEMP: "NORMAL",
|
|
53254
|
+
tkTRIGGER: "NORMAL",
|
|
53255
|
+
tkEND: "NORMAL"
|
|
53256
|
+
},
|
|
53257
|
+
EXPLAIN: {
|
|
53258
|
+
tkSEMI: "START",
|
|
53259
|
+
tkWS: "EXPLAIN",
|
|
53260
|
+
tkOTHER: "EXPLAIN",
|
|
53261
|
+
tkEXPLAIN: "NORMAL",
|
|
53262
|
+
tkCREATE: "CREATE",
|
|
53263
|
+
tkTEMP: "NORMAL",
|
|
53264
|
+
tkTRIGGER: "NORMAL",
|
|
53265
|
+
tkEND: "NORMAL"
|
|
53266
|
+
},
|
|
53267
|
+
CREATE: {
|
|
53268
|
+
tkSEMI: "START",
|
|
53269
|
+
tkWS: "CREATE",
|
|
53270
|
+
tkOTHER: "NORMAL",
|
|
53271
|
+
tkEXPLAIN: "NORMAL",
|
|
53272
|
+
tkCREATE: "NORMAL",
|
|
53273
|
+
tkTEMP: "CREATE",
|
|
53274
|
+
tkTRIGGER: "TRIGGER",
|
|
53275
|
+
tkEND: "NORMAL"
|
|
53276
|
+
},
|
|
53277
|
+
TRIGGER: {
|
|
53278
|
+
tkSEMI: "SEMI",
|
|
53279
|
+
tkWS: "TRIGGER",
|
|
53280
|
+
tkOTHER: "TRIGGER",
|
|
53281
|
+
tkEXPLAIN: "TRIGGER",
|
|
53282
|
+
tkCREATE: "TRIGGER",
|
|
53283
|
+
tkTEMP: "TRIGGER",
|
|
53284
|
+
tkTRIGGER: "TRIGGER",
|
|
53285
|
+
tkEND: "TRIGGER"
|
|
53286
|
+
},
|
|
53287
|
+
SEMI: {
|
|
53288
|
+
tkSEMI: "SEMI",
|
|
53289
|
+
tkWS: "SEMI",
|
|
53290
|
+
tkOTHER: "TRIGGER",
|
|
53291
|
+
tkEXPLAIN: "TRIGGER",
|
|
53292
|
+
tkCREATE: "TRIGGER",
|
|
53293
|
+
tkTEMP: "TRIGGER",
|
|
53294
|
+
tkTRIGGER: "TRIGGER",
|
|
53295
|
+
tkEND: "END"
|
|
53296
|
+
},
|
|
53297
|
+
END: {
|
|
53298
|
+
tkSEMI: "START",
|
|
53299
|
+
tkWS: "END",
|
|
53300
|
+
tkOTHER: "TRIGGER",
|
|
53301
|
+
tkEXPLAIN: "TRIGGER",
|
|
53302
|
+
tkCREATE: "TRIGGER",
|
|
53303
|
+
tkTEMP: "TRIGGER",
|
|
53304
|
+
tkTRIGGER: "TRIGGER",
|
|
53305
|
+
tkEND: "TRIGGER"
|
|
53306
|
+
}
|
|
53307
|
+
};
|
|
53308
|
+
function findCompleteStatementEnd(sql, start) {
|
|
53309
|
+
let state = "INVALID";
|
|
53310
|
+
let hasUsefulToken = false;
|
|
53311
|
+
for (let index = start; index < sql.length; index++) {
|
|
53312
|
+
const char = sql[index];
|
|
53313
|
+
let token;
|
|
53314
|
+
if (char === ";") token = "tkSEMI";
|
|
53315
|
+
else if (char === " " || char === "\r" || char === " " || char === "\n" || char === "\f") token = "tkWS";
|
|
53316
|
+
else if (char === "/" && sql[index + 1] === "*") {
|
|
53317
|
+
const end = sql.indexOf("*/", index + 2);
|
|
53318
|
+
if (end === -1) return {
|
|
53319
|
+
end: void 0,
|
|
53320
|
+
hasUsefulToken
|
|
53321
|
+
};
|
|
53322
|
+
index = end + 1;
|
|
53323
|
+
token = "tkWS";
|
|
53324
|
+
} else if (char === "-" && sql[index + 1] === "-") {
|
|
53325
|
+
const end = sql.indexOf("\n", index + 2);
|
|
53326
|
+
if (end === -1) return {
|
|
53327
|
+
end: void 0,
|
|
53328
|
+
hasUsefulToken
|
|
53329
|
+
};
|
|
53330
|
+
index = end;
|
|
53331
|
+
token = "tkWS";
|
|
53332
|
+
} else if (char === "[") {
|
|
53333
|
+
const end = sql.indexOf("]", index + 1);
|
|
53334
|
+
if (end === -1) return {
|
|
53335
|
+
end: void 0,
|
|
53336
|
+
hasUsefulToken: true
|
|
53337
|
+
};
|
|
53338
|
+
index = end;
|
|
53339
|
+
token = "tkOTHER";
|
|
53340
|
+
} else if (char === "'" || char === "\"" || char === "`") {
|
|
53341
|
+
const end = sql.indexOf(char, index + 1);
|
|
53342
|
+
if (end === -1) return {
|
|
53343
|
+
end: void 0,
|
|
53344
|
+
hasUsefulToken: true
|
|
53345
|
+
};
|
|
53346
|
+
index = end;
|
|
53347
|
+
token = "tkOTHER";
|
|
53348
|
+
} else if (isIdentifierChar$1(char)) {
|
|
53349
|
+
const identifierStart = index;
|
|
53350
|
+
while (index + 1 < sql.length && isIdentifierChar$1(sql[index + 1])) index++;
|
|
53351
|
+
token = classifyIdentifier(sql.slice(identifierStart, index + 1));
|
|
53352
|
+
} else token = "tkOTHER";
|
|
53353
|
+
hasUsefulToken ||= token !== "tkSEMI" && token !== "tkWS";
|
|
53354
|
+
state = getNextState(state, token);
|
|
53355
|
+
if (state === "START") return {
|
|
53356
|
+
end: index + 1,
|
|
53357
|
+
hasUsefulToken
|
|
53358
|
+
};
|
|
53359
|
+
}
|
|
53360
|
+
return {
|
|
53361
|
+
end: void 0,
|
|
53362
|
+
hasUsefulToken
|
|
53363
|
+
};
|
|
53364
|
+
}
|
|
53365
|
+
__name$4(findCompleteStatementEnd, "findCompleteStatementEnd");
|
|
53366
|
+
function getNextState(state, token) {
|
|
53367
|
+
return transitions[state][token];
|
|
53368
|
+
}
|
|
53369
|
+
__name$4(getNextState, "getNextState");
|
|
53370
|
+
function isIdentifierChar$1(char) {
|
|
53371
|
+
return /[A-Za-z0-9_$\u0080-\uffff]/.test(char);
|
|
53372
|
+
}
|
|
53373
|
+
__name$4(isIdentifierChar$1, "isIdentifierChar");
|
|
53374
|
+
function classifyIdentifier(identifier) {
|
|
53375
|
+
switch (identifier.toLowerCase()) {
|
|
53376
|
+
case "explain": return "tkEXPLAIN";
|
|
53377
|
+
case "create": return "tkCREATE";
|
|
53378
|
+
case "temp":
|
|
53379
|
+
case "temporary": return "tkTEMP";
|
|
53380
|
+
case "trigger": return "tkTRIGGER";
|
|
53381
|
+
case "end": return "tkEND";
|
|
53382
|
+
default: return "tkOTHER";
|
|
53383
|
+
}
|
|
53384
|
+
}
|
|
53385
|
+
__name$4(classifyIdentifier, "classifyIdentifier");
|
|
53033
53386
|
|
|
53034
53387
|
//#endregion
|
|
53035
53388
|
//#region ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js
|
|
@@ -56956,6 +57309,7 @@ function createCancellableRequestBody(req) {
|
|
|
56956
57309
|
}
|
|
56957
57310
|
});
|
|
56958
57311
|
}
|
|
57312
|
+
/** Convert a Vite request for the local runtime, preserving signed S3 headers. */
|
|
56959
57313
|
function toMiniflareRequest(request$2) {
|
|
56960
57314
|
const host = request$2.headers.get("Host") ?? new URL(request$2.url).host;
|
|
56961
57315
|
const xForwardedHost = request$2.headers.get("X-Forwarded-Host");
|
|
@@ -56963,9 +57317,11 @@ function toMiniflareRequest(request$2) {
|
|
|
56963
57317
|
request$2.headers.set(CoreHeaders.PROXY_SHARED_SECRET, PROXY_SHARED_SECRET);
|
|
56964
57318
|
const secFetchMode = request$2.headers.get("Sec-Fetch-Mode");
|
|
56965
57319
|
if (secFetchMode) request$2.headers.set(CoreHeaders.SEC_FETCH_MODE, secFetchMode);
|
|
57320
|
+
const pathname = new URL(request$2.url).pathname;
|
|
57321
|
+
const isLocalS3Request = pathname === "/cdn-cgi/local/r2/s3" || pathname.startsWith("/cdn-cgi/local/r2/s3/");
|
|
56966
57322
|
return new Request$1(request$2.url, {
|
|
56967
57323
|
method: request$2.method,
|
|
56968
|
-
headers: [["accept-encoding", "identity"], ...request$2.headers],
|
|
57324
|
+
headers: isLocalS3Request ? [...request$2.headers] : [["accept-encoding", "identity"], ...request$2.headers],
|
|
56969
57325
|
body: request$2.body,
|
|
56970
57326
|
duplex: "half",
|
|
56971
57327
|
signal: request$2.signal
|
|
@@ -62800,8 +63156,8 @@ function isErrorStackTraceLimitWritable() {
|
|
|
62800
63156
|
* @returns {T}
|
|
62801
63157
|
*/
|
|
62802
63158
|
function hideStackFrames(wrappedFunction) {
|
|
62803
|
-
const hidden$
|
|
62804
|
-
Object.defineProperty(wrappedFunction, "name", { value: hidden$
|
|
63159
|
+
const hidden$1 = nodeInternalPrefix + wrappedFunction.name;
|
|
63160
|
+
Object.defineProperty(wrappedFunction, "name", { value: hidden$1 });
|
|
62805
63161
|
return wrappedFunction;
|
|
62806
63162
|
}
|
|
62807
63163
|
const captureLargerStackTrace = hideStackFrames(
|
|
@@ -63021,8 +63377,8 @@ function getFileProtocolModuleFormat(url$2, _context, ignoreErrors) {
|
|
|
63021
63377
|
if (packageType === "none" || packageType === "commonjs") return "commonjs";
|
|
63022
63378
|
return "module";
|
|
63023
63379
|
}
|
|
63024
|
-
const format$
|
|
63025
|
-
if (format$
|
|
63380
|
+
const format$3 = extensionFormatMap[value];
|
|
63381
|
+
if (format$3) return format$3;
|
|
63026
63382
|
if (ignoreErrors) return;
|
|
63027
63383
|
throw new ERR_UNKNOWN_FILE_EXTENSION(value, fileURLToPath(url$2));
|
|
63028
63384
|
}
|
|
@@ -66331,8 +66687,8 @@ function parseRedirects(input$1, { htmlHandling = void 0, maxStaticRules = MAX_S
|
|
|
66331
66687
|
continue;
|
|
66332
66688
|
}
|
|
66333
66689
|
const to = toResult[0];
|
|
66334
|
-
const status$
|
|
66335
|
-
if (isNaN(status$
|
|
66690
|
+
const status$1 = Number(str_status);
|
|
66691
|
+
if (isNaN(status$1) || !PERMITTED_STATUS_CODES.has(status$1)) {
|
|
66336
66692
|
invalid.push({
|
|
66337
66693
|
line,
|
|
66338
66694
|
lineNumber: i$1 + 1,
|
|
@@ -66360,7 +66716,7 @@ function parseRedirects(input$1, { htmlHandling = void 0, maxStaticRules = MAX_S
|
|
|
66360
66716
|
continue;
|
|
66361
66717
|
}
|
|
66362
66718
|
seen_paths.add(from);
|
|
66363
|
-
if (status$
|
|
66719
|
+
if (status$1 === 200) {
|
|
66364
66720
|
if (urlHasHost(to)) {
|
|
66365
66721
|
invalid.push({
|
|
66366
66722
|
line,
|
|
@@ -66373,7 +66729,7 @@ function parseRedirects(input$1, { htmlHandling = void 0, maxStaticRules = MAX_S
|
|
|
66373
66729
|
rules.push({
|
|
66374
66730
|
from,
|
|
66375
66731
|
to,
|
|
66376
|
-
status: status$
|
|
66732
|
+
status: status$1,
|
|
66377
66733
|
lineNumber: i$1 + 1
|
|
66378
66734
|
});
|
|
66379
66735
|
}
|
|
@@ -67989,6 +68345,34 @@ function maybeGetFile(filePath) {
|
|
|
67989
68345
|
if (!thrownIsDoesNotExistError(e)) throw e;
|
|
67990
68346
|
}
|
|
67991
68347
|
}
|
|
68348
|
+
/** An ignore file whose encoding cannot be used to match asset paths. */
|
|
68349
|
+
var InvalidAssetsIgnoreError = class extends Error {
|
|
68350
|
+
constructor(filePath) {
|
|
68351
|
+
super(`The .assetsignore file at "${filePath}" must be UTF-8 encoded and must not contain null characters. Save the file as UTF-8 and try again.`);
|
|
68352
|
+
this.name = "InvalidAssetsIgnoreError";
|
|
68353
|
+
}
|
|
68354
|
+
};
|
|
68355
|
+
/**
|
|
68356
|
+
* Read ignore patterns without silently replacing undecodable characters.
|
|
68357
|
+
* @param filePath Path to the asset ignore file.
|
|
68358
|
+
* @returns Valid UTF-8 patterns, or undefined when the file does not exist.
|
|
68359
|
+
*/
|
|
68360
|
+
function readAssetsIgnoreFile(filePath) {
|
|
68361
|
+
let contents;
|
|
68362
|
+
try {
|
|
68363
|
+
contents = readFileSync(filePath);
|
|
68364
|
+
} catch (error$3) {
|
|
68365
|
+
if (thrownIsDoesNotExistError(error$3)) return;
|
|
68366
|
+
throw error$3;
|
|
68367
|
+
}
|
|
68368
|
+
try {
|
|
68369
|
+
const text = new TextDecoder$1("utf-8", { fatal: true }).decode(contents);
|
|
68370
|
+
if (text.includes("\0")) throw new Error("Ignore patterns contain a null character.");
|
|
68371
|
+
return text;
|
|
68372
|
+
} catch {
|
|
68373
|
+
throw new InvalidAssetsIgnoreError(filePath);
|
|
68374
|
+
}
|
|
68375
|
+
}
|
|
67992
68376
|
|
|
67993
68377
|
//#endregion
|
|
67994
68378
|
//#region ../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/v4/core/util.js
|
|
@@ -72204,9 +72588,9 @@ const addPattern = (agg, pattern) => {
|
|
|
72204
72588
|
const intersectMime = (agg, mime) => {
|
|
72205
72589
|
agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
|
|
72206
72590
|
};
|
|
72207
|
-
const setFormat = (agg, format$
|
|
72208
|
-
agg.format = format$
|
|
72209
|
-
if (format$
|
|
72591
|
+
const setFormat = (agg, format$3) => {
|
|
72592
|
+
agg.format = format$3;
|
|
72593
|
+
if (format$3.includes("int")) agg.isInt = true;
|
|
72210
72594
|
};
|
|
72211
72595
|
const minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
|
|
72212
72596
|
const maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
|
|
@@ -72267,13 +72651,13 @@ const exactPattern = (p$2) => exactPatterns.get(p$2) ?? p$2;
|
|
|
72267
72651
|
const stringProcessor = (schema, ctx, _json, _params) => {
|
|
72268
72652
|
const json$1 = _json;
|
|
72269
72653
|
json$1.type = "string";
|
|
72270
|
-
const { minimum, maximum, format: format$
|
|
72654
|
+
const { minimum, maximum, format: format$3, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
|
|
72271
72655
|
if (typeof minimum === "number") json$1.minLength = minimum;
|
|
72272
72656
|
if (typeof maximum === "number") json$1.maxLength = maximum;
|
|
72273
|
-
if (format$
|
|
72274
|
-
json$1.format = formatMap[format$
|
|
72657
|
+
if (format$3) {
|
|
72658
|
+
json$1.format = formatMap[format$3] ?? format$3;
|
|
72275
72659
|
if (json$1.format === "") delete json$1.format;
|
|
72276
|
-
if (format$
|
|
72660
|
+
if (format$3 === "time" || laxFormat) delete json$1.format;
|
|
72277
72661
|
}
|
|
72278
72662
|
if (contentEncoding) json$1.contentEncoding = contentEncoding;
|
|
72279
72663
|
if (patterns && patterns.size > 0) {
|
|
@@ -72483,7 +72867,7 @@ function stringifyKeyNames(bySchema, json$1, visited) {
|
|
|
72483
72867
|
const numericType = !types$4.includes("string") && types$4.some((t$5) => t$5 === "number" || t$5 === "integer");
|
|
72484
72868
|
const values = json$1.enum ?? (json$1.const !== void 0 ? [json$1.const] : void 0);
|
|
72485
72869
|
if (!numericType && !values?.some((v) => typeof v === "number")) return json$1;
|
|
72486
|
-
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format: format$
|
|
72870
|
+
const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format: format$3, id,...rest } = json$1;
|
|
72487
72871
|
if (rest.enum) rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
|
|
72488
72872
|
else if (typeof rest.const === "number") rest.const = String(rest.const);
|
|
72489
72873
|
if (!numericType) return rest;
|
|
@@ -73879,8 +74263,8 @@ var CloudflareDevEnvironment = class extends vite.DevEnvironment {
|
|
|
73879
74263
|
await this.depsOptimizer?.init();
|
|
73880
74264
|
const response = await miniflare.dispatchFetch(new URL(GET_EXPORT_TYPES_PATH, UNKNOWN_HOST), { headers: { [CoreHeaders.ROUTE_OVERRIDE]: workerConfig.name } });
|
|
73881
74265
|
if (!response.ok) {
|
|
73882
|
-
const status$
|
|
73883
|
-
throw new Error(`Failed to fetch export types for Worker "${workerConfig.name}" (${status$
|
|
74266
|
+
const status$1 = [response.status, response.statusText].filter(Boolean).join(" ");
|
|
74267
|
+
throw new Error(`Failed to fetch export types for Worker "${workerConfig.name}" (${status$1}): ${await response.text()}`);
|
|
73884
74268
|
}
|
|
73885
74269
|
return await response.json();
|
|
73886
74270
|
}
|
|
@@ -73907,7 +74291,7 @@ const defaultConditions = [
|
|
|
73907
74291
|
"browser"
|
|
73908
74292
|
];
|
|
73909
74293
|
const target = isRolldown ? "es2026" : "es2024";
|
|
73910
|
-
const
|
|
74294
|
+
const defaultCssTarget = "es2024";
|
|
73911
74295
|
const esbuildSupported = { using: true };
|
|
73912
74296
|
const resolveExtensions = [
|
|
73913
74297
|
".mjs",
|
|
@@ -73929,6 +74313,15 @@ const resolveExtensions = [
|
|
|
73929
74313
|
function getWorkerSourcemap(userConfig, environmentName, workerConfig) {
|
|
73930
74314
|
return userConfig.environments?.[environmentName]?.build?.sourcemap ?? userConfig.build?.sourcemap ?? workerConfig.upload_source_maps ?? true;
|
|
73931
74315
|
}
|
|
74316
|
+
/**
|
|
74317
|
+
* Vite merges the array-valued `build.cssTarget` returned from `configEnvironment`
|
|
74318
|
+
* with the user's value by appending, and Lightning CSS then takes the lowest
|
|
74319
|
+
* version per browser. A plugin default would therefore lower the user's pinned
|
|
74320
|
+
* targets, so only provide the default when the user has not set one.
|
|
74321
|
+
*/
|
|
74322
|
+
function getWorkerCssTarget(userConfig, environmentName) {
|
|
74323
|
+
return (userConfig.environments?.[environmentName]?.build?.cssTarget ?? userConfig.build?.cssTarget) === void 0 ? defaultCssTarget : void 0;
|
|
74324
|
+
}
|
|
73932
74325
|
function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, environmentName, isEntryWorker, isParentEnvironment, hasNodeJsCompat: hasNodeJsCompat$1 }) {
|
|
73933
74326
|
const rollupOptions = isParentEnvironment ? {
|
|
73934
74327
|
input: { [MAIN_ENTRY_NAME]: VIRTUAL_WORKER_ENTRY },
|
|
@@ -73951,7 +74344,7 @@ function createCloudflareEnvironmentOptions({ workerConfig, userConfig, mode, en
|
|
|
73951
74344
|
return new vite.BuildEnvironment(name, config$2);
|
|
73952
74345
|
},
|
|
73953
74346
|
target,
|
|
73954
|
-
cssTarget,
|
|
74347
|
+
cssTarget: getWorkerCssTarget(userConfig, environmentName),
|
|
73955
74348
|
emitAssets: true,
|
|
73956
74349
|
manifest: isEntryWorker,
|
|
73957
74350
|
outDir: getOutputDirectory(userConfig, environmentName),
|
|
@@ -74446,7 +74839,7 @@ const generateStaticRoutingRuleMatcher = (rules) => ({ request: request$2 }) =>
|
|
|
74446
74839
|
};
|
|
74447
74840
|
|
|
74448
74841
|
//#endregion
|
|
74449
|
-
//#region ../../node_modules/.pnpm/@cloudflare+build-output-utils@0.9.
|
|
74842
|
+
//#region ../../node_modules/.pnpm/@cloudflare+build-output-utils@0.9.9/node_modules/@cloudflare/build-output-utils/dist/index.mjs
|
|
74450
74843
|
/**
|
|
74451
74844
|
* Initial draft version of the Build Output Specification.
|
|
74452
74845
|
*
|
|
@@ -74558,29 +74951,29 @@ async function writeContainerConfig({ root, config: config$2, directoryName }) {
|
|
|
74558
74951
|
}
|
|
74559
74952
|
|
|
74560
74953
|
//#endregion
|
|
74561
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
74562
|
-
const { white
|
|
74563
|
-
const brandColor
|
|
74564
|
-
const black
|
|
74565
|
-
const blue
|
|
74566
|
-
const bgBlue
|
|
74567
|
-
const red
|
|
74568
|
-
const bgRed
|
|
74569
|
-
const green
|
|
74570
|
-
const bgGreen
|
|
74571
|
-
const yellow
|
|
74572
|
-
const bgYellow
|
|
74954
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/colors.mjs
|
|
74955
|
+
const { white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default;
|
|
74956
|
+
const brandColor = source_default.hex("#BD5B08");
|
|
74957
|
+
const black = source_default.hex("#111");
|
|
74958
|
+
const blue = source_default.hex("#0E838F");
|
|
74959
|
+
const bgBlue = black.bgHex("#0E838F");
|
|
74960
|
+
const red = source_default.hex("#AB2526");
|
|
74961
|
+
const bgRed = black.bgHex("#AB2526");
|
|
74962
|
+
const green = source_default.hex("#218529");
|
|
74963
|
+
const bgGreen = black.bgHex("#218529");
|
|
74964
|
+
const yellow = source_default.hex("#7F7322");
|
|
74965
|
+
const bgYellow = black.bgHex("#7F7322");
|
|
74573
74966
|
|
|
74574
74967
|
//#endregion
|
|
74575
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
74968
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/streams.mjs
|
|
74576
74969
|
/**
|
|
74577
74970
|
* This file simply re-exports the process's writeable streams
|
|
74578
74971
|
* The intention is to provide a boundary to mock in tests
|
|
74579
74972
|
* Anywhere in this package that writes to stdout/stderr,
|
|
74580
74973
|
* should use this module to get references to them.
|
|
74581
74974
|
*/
|
|
74582
|
-
const stdout$
|
|
74583
|
-
const stderr
|
|
74975
|
+
const stdout$1 = process.stdout;
|
|
74976
|
+
const stderr = process.stderr;
|
|
74584
74977
|
|
|
74585
74978
|
//#endregion
|
|
74586
74979
|
//#region ../../node_modules/.pnpm/ci-info@4.4.0/node_modules/ci-info/vendors.json
|
|
@@ -74960,11 +75353,11 @@ var require_ci_info = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pnpm/c
|
|
|
74960
75353
|
}) });
|
|
74961
75354
|
|
|
74962
75355
|
//#endregion
|
|
74963
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
74964
|
-
var import_ci_info
|
|
75356
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/check-macos-version.mjs
|
|
75357
|
+
var import_ci_info = /* @__PURE__ */ __toESM$2(require_ci_info(), 1);
|
|
74965
75358
|
|
|
74966
75359
|
//#endregion
|
|
74967
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
75360
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/cursor.mjs
|
|
74968
75361
|
function showCursor(show, stream$2 = process5.stderr) {
|
|
74969
75362
|
if (!stream$2.isTTY) return;
|
|
74970
75363
|
if (show) stream$2.write("\x1B[?25h");
|
|
@@ -74972,8 +75365,8 @@ function showCursor(show, stream$2 = process5.stderr) {
|
|
|
74972
75365
|
}
|
|
74973
75366
|
|
|
74974
75367
|
//#endregion
|
|
74975
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
74976
|
-
const shapes
|
|
75368
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/index.mjs
|
|
75369
|
+
const shapes = {
|
|
74977
75370
|
diamond: "◇",
|
|
74978
75371
|
dash: "─",
|
|
74979
75372
|
radioInactive: "○",
|
|
@@ -74994,17 +75387,17 @@ const shapes$1 = {
|
|
|
74994
75387
|
br: "╯"
|
|
74995
75388
|
}
|
|
74996
75389
|
};
|
|
74997
|
-
const status
|
|
74998
|
-
error: bgRed
|
|
74999
|
-
warning: bgYellow
|
|
75000
|
-
info: bgBlue
|
|
75001
|
-
success: bgGreen
|
|
75002
|
-
cancel: white
|
|
75390
|
+
const status = {
|
|
75391
|
+
error: bgRed(` ERROR `),
|
|
75392
|
+
warning: bgYellow(` WARNING `),
|
|
75393
|
+
info: bgBlue(` INFO `),
|
|
75394
|
+
success: bgGreen(` SUCCESS `),
|
|
75395
|
+
cancel: white.bgRed(` X `)
|
|
75003
75396
|
};
|
|
75004
|
-
const space
|
|
75005
|
-
return hidden
|
|
75397
|
+
const space = (n$1 = 1) => {
|
|
75398
|
+
return hidden(" ".repeat(n$1));
|
|
75006
75399
|
};
|
|
75007
|
-
const LOGGER_LEVELS
|
|
75400
|
+
const LOGGER_LEVELS = {
|
|
75008
75401
|
none: -1,
|
|
75009
75402
|
error: 0,
|
|
75010
75403
|
warn: 1,
|
|
@@ -75012,48 +75405,83 @@ const LOGGER_LEVELS$1 = {
|
|
|
75012
75405
|
log: 3,
|
|
75013
75406
|
debug: 4
|
|
75014
75407
|
};
|
|
75015
|
-
let currentLogLevel
|
|
75016
|
-
function getLogLevel
|
|
75017
|
-
return currentLogLevel
|
|
75408
|
+
let currentLogLevel = "log";
|
|
75409
|
+
function getLogLevel() {
|
|
75410
|
+
return currentLogLevel;
|
|
75018
75411
|
}
|
|
75019
|
-
const logRaw
|
|
75020
|
-
if (LOGGER_LEVELS
|
|
75412
|
+
const logRaw = (msg) => {
|
|
75413
|
+
if (LOGGER_LEVELS[getLogLevel()] >= LOGGER_LEVELS.log) stdout$1.write(`${msg}\n`);
|
|
75021
75414
|
};
|
|
75022
75415
|
const log$1 = (msg) => {
|
|
75023
|
-
logRaw
|
|
75416
|
+
logRaw(msg.split("\n").map((ln) => `${gray(shapes.bar)}${ln.length > 0 ? " " + white(ln) : ""}`).join("\n"));
|
|
75024
75417
|
};
|
|
75025
|
-
const newline
|
|
75418
|
+
const newline = () => {
|
|
75026
75419
|
log$1("");
|
|
75027
75420
|
};
|
|
75028
|
-
const format$
|
|
75029
|
-
const formattedLines = (multiline ? msg.split("\n") : [msg]).map((line, i$1) => (i$1 === 0 ? firstLinePrefix : linePrefix) + space
|
|
75421
|
+
const format$1 = (msg, { linePrefix = gray(shapes.bar), firstLinePrefix = linePrefix, newlineBefore = false, newlineAfter = false, formatLine = (line) => white(line), multiline = true } = {}) => {
|
|
75422
|
+
const formattedLines = (multiline ? msg.split("\n") : [msg]).map((line, i$1) => (i$1 === 0 ? firstLinePrefix : linePrefix) + space() + formatLine(line));
|
|
75030
75423
|
if (newlineBefore) formattedLines.unshift(linePrefix);
|
|
75031
75424
|
if (newlineAfter) formattedLines.push(linePrefix);
|
|
75032
75425
|
return formattedLines.join("\n");
|
|
75033
75426
|
};
|
|
75034
75427
|
const updateStatus = (msg, printNewLine = true) => {
|
|
75035
|
-
logRaw
|
|
75036
|
-
firstLinePrefix: gray
|
|
75037
|
-
linePrefix: gray
|
|
75428
|
+
logRaw(format$1(msg, {
|
|
75429
|
+
firstLinePrefix: gray(shapes.leftT),
|
|
75430
|
+
linePrefix: gray(shapes.bar),
|
|
75038
75431
|
newlineAfter: printNewLine
|
|
75039
75432
|
}));
|
|
75040
75433
|
};
|
|
75041
75434
|
const startSection = (heading, subheading, printNewLine = true) => {
|
|
75042
|
-
logRaw
|
|
75043
|
-
if (printNewLine) newline
|
|
75435
|
+
logRaw(`${gray(shapes.corners.tl)} ${brandColor(heading)} ${subheading ? dim(subheading) : ""}`);
|
|
75436
|
+
if (printNewLine) newline();
|
|
75044
75437
|
};
|
|
75045
75438
|
const endSection = (heading, subheading) => {
|
|
75046
|
-
logRaw
|
|
75439
|
+
logRaw(`${gray(shapes.corners.bl)} ${brandColor(heading)} ${subheading ? dim(subheading) : ""}\n`);
|
|
75440
|
+
};
|
|
75441
|
+
const cancel = (msg, { shape = shapes.corners.bl, multiline = false } = {}) => {
|
|
75442
|
+
logRaw(format$1(msg, {
|
|
75443
|
+
firstLinePrefix: `${gray(shape)} ${status.cancel}`,
|
|
75444
|
+
linePrefix: gray(shapes.bar),
|
|
75445
|
+
newlineBefore: true,
|
|
75446
|
+
formatLine: (line) => dim(line),
|
|
75447
|
+
multiline
|
|
75448
|
+
}));
|
|
75047
75449
|
};
|
|
75048
|
-
const success = (msg, { shape = shapes
|
|
75049
|
-
logRaw
|
|
75050
|
-
firstLinePrefix: gray
|
|
75051
|
-
linePrefix: gray
|
|
75450
|
+
const success = (msg, { shape = shapes.corners.bl, multiline = false } = {}) => {
|
|
75451
|
+
logRaw(format$1(msg, {
|
|
75452
|
+
firstLinePrefix: gray(shape) + space() + status.success,
|
|
75453
|
+
linePrefix: gray(shapes.bar),
|
|
75052
75454
|
newlineBefore: true,
|
|
75053
|
-
formatLine: (line) => dim
|
|
75455
|
+
formatLine: (line) => dim(line),
|
|
75054
75456
|
multiline
|
|
75055
75457
|
}));
|
|
75056
75458
|
};
|
|
75459
|
+
const stripAnsi = (str) => {
|
|
75460
|
+
const pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
|
|
75461
|
+
const regex$1 = RegExp(pattern, "g");
|
|
75462
|
+
return str.replace(linkRegex, "$2").replace(regex$1, "");
|
|
75463
|
+
};
|
|
75464
|
+
const linkRegex = /\u001B\]8;;(?<url>.+)\u001B\\(?<label>.+)\u001B\]8;;\u001B\\/g;
|
|
75465
|
+
const crash = (msg, extra) => {
|
|
75466
|
+
error(msg, extra);
|
|
75467
|
+
exit(1);
|
|
75468
|
+
};
|
|
75469
|
+
const error = (msg, extra, corner = shapes.corners.bl) => {
|
|
75470
|
+
const currentLevel = getLogLevel();
|
|
75471
|
+
if (msg && LOGGER_LEVELS[currentLevel] >= LOGGER_LEVELS.error) stderr.write(`${gray(corner)} ${status.error} ${dim(msg)}\n${extra ? space() + extra + "\n" : ""}`);
|
|
75472
|
+
};
|
|
75473
|
+
|
|
75474
|
+
//#endregion
|
|
75475
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/error.mjs
|
|
75476
|
+
/**
|
|
75477
|
+
* Error thrown when an operation is cancelled
|
|
75478
|
+
*/
|
|
75479
|
+
var CancelError$1 = class extends Error {
|
|
75480
|
+
constructor(message, signal) {
|
|
75481
|
+
super(message);
|
|
75482
|
+
this.signal = signal;
|
|
75483
|
+
}
|
|
75484
|
+
};
|
|
75057
75485
|
|
|
75058
75486
|
//#endregion
|
|
75059
75487
|
//#region ../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/utils.js
|
|
@@ -75778,6 +76206,49 @@ var at = class extends p {
|
|
|
75778
76206
|
}
|
|
75779
76207
|
};
|
|
75780
76208
|
|
|
76209
|
+
//#endregion
|
|
76210
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/select-list.mjs
|
|
76211
|
+
var SelectRefreshablePrompt = class extends p {
|
|
76212
|
+
options;
|
|
76213
|
+
cursor = 0;
|
|
76214
|
+
get _value() {
|
|
76215
|
+
return this.options[this.cursor];
|
|
76216
|
+
}
|
|
76217
|
+
changeValue() {
|
|
76218
|
+
this.value = this._value.value;
|
|
76219
|
+
}
|
|
76220
|
+
constructor(opts) {
|
|
76221
|
+
super(opts, false);
|
|
76222
|
+
this.options = opts.options;
|
|
76223
|
+
this.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);
|
|
76224
|
+
if (this.cursor === -1) this.cursor = 0;
|
|
76225
|
+
this.changeValue();
|
|
76226
|
+
this.on("key", (c$1) => {
|
|
76227
|
+
if (c$1 !== "r") return;
|
|
76228
|
+
opts.onRefresh().then((newOptions) => {
|
|
76229
|
+
this.options = [...newOptions];
|
|
76230
|
+
this.cursor = 0;
|
|
76231
|
+
this.changeValue();
|
|
76232
|
+
const that = this;
|
|
76233
|
+
if ("render" in that && typeof that.render === "function") that.render();
|
|
76234
|
+
}).catch(() => {});
|
|
76235
|
+
});
|
|
76236
|
+
this.on("cursor", (key) => {
|
|
76237
|
+
switch (key) {
|
|
76238
|
+
case "left":
|
|
76239
|
+
case "up":
|
|
76240
|
+
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
|
|
76241
|
+
break;
|
|
76242
|
+
case "down":
|
|
76243
|
+
case "right":
|
|
76244
|
+
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
|
|
76245
|
+
break;
|
|
76246
|
+
}
|
|
76247
|
+
this.changeValue();
|
|
76248
|
+
});
|
|
76249
|
+
}
|
|
76250
|
+
};
|
|
76251
|
+
|
|
75781
76252
|
//#endregion
|
|
75782
76253
|
//#region ../../node_modules/.pnpm/ansi-escapes@5.0.0/node_modules/ansi-escapes/index.js
|
|
75783
76254
|
const ESC = "\x1B[";
|
|
@@ -76097,7 +76568,7 @@ function ansiRegex({ onlyFirst = false } = {}) {
|
|
|
76097
76568
|
//#endregion
|
|
76098
76569
|
//#region ../../node_modules/.pnpm/strip-ansi@7.2.0/node_modules/strip-ansi/index.js
|
|
76099
76570
|
const regex = ansiRegex();
|
|
76100
|
-
function stripAnsi$
|
|
76571
|
+
function stripAnsi$1(string$2) {
|
|
76101
76572
|
if (typeof string$2 !== "string") throw new TypeError(`Expected a \`string\`, got \`${typeof string$2}\``);
|
|
76102
76573
|
if (!string$2.includes("\x1B") && !string$2.includes("")) return string$2;
|
|
76103
76574
|
return string$2.replace(regex, "");
|
|
@@ -76178,7 +76649,7 @@ function stringWidth(string$2, options = {}) {
|
|
|
76178
76649
|
ambiguousIsNarrow: true,
|
|
76179
76650
|
...options
|
|
76180
76651
|
};
|
|
76181
|
-
string$2 = stripAnsi$
|
|
76652
|
+
string$2 = stripAnsi$1(string$2);
|
|
76182
76653
|
if (string$2.length === 0) return 0;
|
|
76183
76654
|
string$2 = string$2.replace((0, import_emoji_regex.default)(), " ");
|
|
76184
76655
|
const ambiguousCharacterWidth = options.ambiguousIsNarrow ? 1 : 2;
|
|
@@ -76206,7 +76677,7 @@ function stringWidth(string$2, options = {}) {
|
|
|
76206
76677
|
const ANSI_BACKGROUND_OFFSET = 10;
|
|
76207
76678
|
const wrapAnsi16 = (offset = 0) => (code) => `\u001B[${code + offset}m`;
|
|
76208
76679
|
const wrapAnsi256 = (offset = 0) => (code) => `\u001B[${38 + offset};5;${code}m`;
|
|
76209
|
-
const wrapAnsi16m = (offset = 0) => (red$
|
|
76680
|
+
const wrapAnsi16m = (offset = 0) => (red$1, green$1, blue$1) => `\u001B[${38 + offset};2;${red$1};${green$1};${blue$1}m`;
|
|
76210
76681
|
const styles = {
|
|
76211
76682
|
modifier: {
|
|
76212
76683
|
reset: [0, 0],
|
|
@@ -76294,13 +76765,13 @@ function assembleStyles() {
|
|
|
76294
76765
|
styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
|
|
76295
76766
|
Object.defineProperties(styles, {
|
|
76296
76767
|
rgbToAnsi256: {
|
|
76297
|
-
value: (red$
|
|
76298
|
-
if (red$
|
|
76299
|
-
if (red$
|
|
76300
|
-
if (red$
|
|
76301
|
-
return Math.round((red$
|
|
76768
|
+
value: (red$1, green$1, blue$1) => {
|
|
76769
|
+
if (red$1 === green$1 && green$1 === blue$1) {
|
|
76770
|
+
if (red$1 < 8) return 16;
|
|
76771
|
+
if (red$1 > 248) return 231;
|
|
76772
|
+
return Math.round((red$1 - 8) / 247 * 24) + 232;
|
|
76302
76773
|
}
|
|
76303
|
-
return 16 + 36 * Math.round(red$
|
|
76774
|
+
return 16 + 36 * Math.round(red$1 / 255 * 5) + 6 * Math.round(green$1 / 255 * 5) + Math.round(blue$1 / 255 * 5);
|
|
76304
76775
|
},
|
|
76305
76776
|
enumerable: false
|
|
76306
76777
|
},
|
|
@@ -76331,30 +76802,30 @@ function assembleStyles() {
|
|
|
76331
76802
|
value: (code) => {
|
|
76332
76803
|
if (code < 8) return 30 + code;
|
|
76333
76804
|
if (code < 16) return 90 + (code - 8);
|
|
76334
|
-
let red$
|
|
76335
|
-
let green$
|
|
76336
|
-
let blue$
|
|
76805
|
+
let red$1;
|
|
76806
|
+
let green$1;
|
|
76807
|
+
let blue$1;
|
|
76337
76808
|
if (code >= 232) {
|
|
76338
|
-
red$
|
|
76339
|
-
green$
|
|
76340
|
-
blue$
|
|
76809
|
+
red$1 = ((code - 232) * 10 + 8) / 255;
|
|
76810
|
+
green$1 = red$1;
|
|
76811
|
+
blue$1 = red$1;
|
|
76341
76812
|
} else {
|
|
76342
76813
|
code -= 16;
|
|
76343
76814
|
const remainder = code % 36;
|
|
76344
|
-
red$
|
|
76345
|
-
green$
|
|
76346
|
-
blue$
|
|
76815
|
+
red$1 = Math.floor(code / 36) / 5;
|
|
76816
|
+
green$1 = Math.floor(remainder / 6) / 5;
|
|
76817
|
+
blue$1 = remainder % 6 / 5;
|
|
76347
76818
|
}
|
|
76348
|
-
const value = Math.max(red$
|
|
76819
|
+
const value = Math.max(red$1, green$1, blue$1) * 2;
|
|
76349
76820
|
if (value === 0) return 30;
|
|
76350
|
-
let result = 30 + (Math.round(blue$
|
|
76821
|
+
let result = 30 + (Math.round(blue$1) << 2 | Math.round(green$1) << 1 | Math.round(red$1));
|
|
76351
76822
|
if (value === 2) result += 60;
|
|
76352
76823
|
return result;
|
|
76353
76824
|
},
|
|
76354
76825
|
enumerable: false
|
|
76355
76826
|
},
|
|
76356
76827
|
rgbToAnsi: {
|
|
76357
|
-
value: (red$
|
|
76828
|
+
value: (red$1, green$1, blue$1) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red$1, green$1, blue$1)),
|
|
76358
76829
|
enumerable: false
|
|
76359
76830
|
},
|
|
76360
76831
|
hexToAnsi: {
|
|
@@ -76383,7 +76854,7 @@ const wrapWord = (rows, word, columns) => {
|
|
|
76383
76854
|
const characters = [...word];
|
|
76384
76855
|
let isInsideEscape = false;
|
|
76385
76856
|
let isInsideLinkEscape = false;
|
|
76386
|
-
let visible = stringWidth(stripAnsi$
|
|
76857
|
+
let visible = stringWidth(stripAnsi$1(rows[rows.length - 1]));
|
|
76387
76858
|
for (const [index, character] of characters.entries()) {
|
|
76388
76859
|
const characterLength = stringWidth(character);
|
|
76389
76860
|
if (visible + characterLength <= columns) rows[rows.length - 1] += character;
|
|
@@ -76574,7 +77045,7 @@ const fitToTerminalHeight = (stream$2, text) => {
|
|
|
76574
77045
|
const lines = text.split("\n");
|
|
76575
77046
|
const toRemove = lines.length - terminalHeight;
|
|
76576
77047
|
if (toRemove <= 0) return text;
|
|
76577
|
-
return sliceAnsi(text, stripAnsi$
|
|
77048
|
+
return sliceAnsi(text, stripAnsi$1(lines.slice(0, toRemove).join("\n")).length + 1);
|
|
76578
77049
|
};
|
|
76579
77050
|
function createLogUpdate(stream$2, { showCursor: showCursor$1 = false } = {}) {
|
|
76580
77051
|
let previousLineCount = 0;
|
|
@@ -76610,15 +77081,321 @@ function createLogUpdate(stream$2, { showCursor: showCursor$1 = false } = {}) {
|
|
|
76610
77081
|
};
|
|
76611
77082
|
return render;
|
|
76612
77083
|
}
|
|
76613
|
-
const logUpdate$
|
|
77084
|
+
const logUpdate$1 = createLogUpdate(process5.stdout);
|
|
76614
77085
|
const logUpdateStderr = createLogUpdate(process5.stderr);
|
|
76615
77086
|
|
|
76616
77087
|
//#endregion
|
|
76617
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.
|
|
76618
|
-
const logUpdate
|
|
76619
|
-
const grayBar
|
|
76620
|
-
const blCorner
|
|
76621
|
-
const leftT
|
|
77088
|
+
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.3.3_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_1015a3e98971606dde907233c81fa8ee/node_modules/@cloudflare/cli-shared-helpers/dist/interactive.mjs
|
|
77089
|
+
const logUpdate = createLogUpdate(stdout$1);
|
|
77090
|
+
const grayBar = gray(shapes.bar);
|
|
77091
|
+
const blCorner = gray(shapes.corners.bl);
|
|
77092
|
+
const leftT = gray(shapes.leftT);
|
|
77093
|
+
function acceptDefault(promptConfig, renderers, initialValue) {
|
|
77094
|
+
const error$3 = promptConfig.validate?.(initialValue);
|
|
77095
|
+
if (error$3) {
|
|
77096
|
+
const errorMessage = error$3 instanceof Error ? error$3.message : error$3;
|
|
77097
|
+
if (promptConfig.throwOnError) throw new Error(errorMessage);
|
|
77098
|
+
else crash(errorMessage);
|
|
77099
|
+
}
|
|
77100
|
+
logRaw(renderers.submit({ value: initialValue }).join("\n"));
|
|
77101
|
+
return initialValue;
|
|
77102
|
+
}
|
|
77103
|
+
const inputPrompt = async (promptConfig) => {
|
|
77104
|
+
const renderers = {
|
|
77105
|
+
...getRenderers(promptConfig),
|
|
77106
|
+
...promptConfig.renderers
|
|
77107
|
+
};
|
|
77108
|
+
let prompt;
|
|
77109
|
+
const dispatchRender = (props, p$2) => {
|
|
77110
|
+
let state = props.state;
|
|
77111
|
+
if (state === "initial" && promptConfig.initialErrorMessage) {
|
|
77112
|
+
state = "error";
|
|
77113
|
+
props.error = promptConfig.initialErrorMessage;
|
|
77114
|
+
}
|
|
77115
|
+
return renderers[state](props, p$2).join("\n");
|
|
77116
|
+
};
|
|
77117
|
+
if (promptConfig.type === "select") {
|
|
77118
|
+
const initialValue = String(promptConfig.defaultValue);
|
|
77119
|
+
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
77120
|
+
prompt = new nt({
|
|
77121
|
+
...promptConfig,
|
|
77122
|
+
options: promptConfig.options.filter((o) => !o.hidden),
|
|
77123
|
+
initialValue,
|
|
77124
|
+
render() {
|
|
77125
|
+
return dispatchRender(this, prompt);
|
|
77126
|
+
}
|
|
77127
|
+
});
|
|
77128
|
+
} else if (promptConfig.type === "confirm") {
|
|
77129
|
+
const initialValue = Boolean(promptConfig.defaultValue);
|
|
77130
|
+
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
77131
|
+
prompt = new Q({
|
|
77132
|
+
...promptConfig,
|
|
77133
|
+
initialValue,
|
|
77134
|
+
active: promptConfig.activeText || "",
|
|
77135
|
+
inactive: promptConfig.inactiveText || "",
|
|
77136
|
+
render() {
|
|
77137
|
+
return dispatchRender(this, prompt);
|
|
77138
|
+
}
|
|
77139
|
+
});
|
|
77140
|
+
} else if (promptConfig.type == "multiselect") {
|
|
77141
|
+
let initialValues;
|
|
77142
|
+
if (Array.isArray(promptConfig.defaultValue)) initialValues = promptConfig.defaultValue;
|
|
77143
|
+
else if (promptConfig.defaultValue !== void 0) initialValues = [String(promptConfig.defaultValue)];
|
|
77144
|
+
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValues);
|
|
77145
|
+
prompt = new it({
|
|
77146
|
+
...promptConfig,
|
|
77147
|
+
options: promptConfig.options,
|
|
77148
|
+
initialValues,
|
|
77149
|
+
render() {
|
|
77150
|
+
return dispatchRender(this, prompt);
|
|
77151
|
+
}
|
|
77152
|
+
});
|
|
77153
|
+
} else if (promptConfig.type === "list") {
|
|
77154
|
+
const initialValue = String(promptConfig.defaultValue);
|
|
77155
|
+
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
77156
|
+
prompt = new SelectRefreshablePrompt({
|
|
77157
|
+
...promptConfig,
|
|
77158
|
+
onRefresh: promptConfig.onRefresh ?? (() => Promise.resolve(promptConfig.options)),
|
|
77159
|
+
initialValue,
|
|
77160
|
+
render() {
|
|
77161
|
+
return dispatchRender(this, prompt);
|
|
77162
|
+
}
|
|
77163
|
+
});
|
|
77164
|
+
} else {
|
|
77165
|
+
const initialValue = promptConfig.initialValue ?? String(promptConfig.defaultValue ?? "");
|
|
77166
|
+
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
77167
|
+
prompt = new at({
|
|
77168
|
+
...promptConfig,
|
|
77169
|
+
initialValue: promptConfig.initialValue,
|
|
77170
|
+
defaultValue: String(promptConfig.defaultValue ?? ""),
|
|
77171
|
+
render() {
|
|
77172
|
+
return dispatchRender(this, prompt);
|
|
77173
|
+
}
|
|
77174
|
+
});
|
|
77175
|
+
}
|
|
77176
|
+
const input$1 = await prompt.prompt();
|
|
77177
|
+
if (q(input$1)) if (promptConfig.throwOnError) throw new CancelError$1("Operation cancelled");
|
|
77178
|
+
else {
|
|
77179
|
+
cancel("Operation cancelled");
|
|
77180
|
+
process.exit(0);
|
|
77181
|
+
}
|
|
77182
|
+
return input$1;
|
|
77183
|
+
};
|
|
77184
|
+
const renderSubmit = (config$2, value) => {
|
|
77185
|
+
const { question, label } = config$2;
|
|
77186
|
+
if (config$2.type !== "confirm" && !value) return [`${leftT} ${question} ${dim("(skipped)")}`, `${grayBar}`];
|
|
77187
|
+
const content = config$2.type === "confirm" ? `${grayBar} ${brandColor(value)} ${dim(label)}` : `${grayBar} ${brandColor(label)} ${dim(value)}`;
|
|
77188
|
+
return [
|
|
77189
|
+
`${leftT} ${question}`,
|
|
77190
|
+
content,
|
|
77191
|
+
`${grayBar}`
|
|
77192
|
+
];
|
|
77193
|
+
};
|
|
77194
|
+
const getRenderers = (config$2) => {
|
|
77195
|
+
switch (config$2.type) {
|
|
77196
|
+
case "select": return getSelectRenderers(config$2);
|
|
77197
|
+
case "confirm": return getConfirmRenderers(config$2);
|
|
77198
|
+
case "text": return getTextRenderers(config$2);
|
|
77199
|
+
case "multiselect": return getSelectRenderers(config$2);
|
|
77200
|
+
case "list": return getSelectListRenderers(config$2);
|
|
77201
|
+
}
|
|
77202
|
+
};
|
|
77203
|
+
const getTextRenderers = (config$2) => {
|
|
77204
|
+
const { question } = config$2;
|
|
77205
|
+
const helpText = config$2.helpText ?? "";
|
|
77206
|
+
const format$3 = config$2.format ?? ((val) => String(val));
|
|
77207
|
+
const defaultValue = config$2.defaultValue?.toString() ?? "";
|
|
77208
|
+
const activeRenderer = (props) => {
|
|
77209
|
+
const { userInputWithCursor } = props;
|
|
77210
|
+
return [
|
|
77211
|
+
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
77212
|
+
`${space(2)}${format$3(userInputWithCursor || dim(defaultValue))}`,
|
|
77213
|
+
``
|
|
77214
|
+
];
|
|
77215
|
+
};
|
|
77216
|
+
return {
|
|
77217
|
+
initial: () => [
|
|
77218
|
+
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
77219
|
+
`${space(2)}${gray(format$3(defaultValue))}`,
|
|
77220
|
+
``
|
|
77221
|
+
],
|
|
77222
|
+
active: activeRenderer,
|
|
77223
|
+
error: ({ value, error: error$3 }) => [
|
|
77224
|
+
`${leftT} ${status.error} ${dim(error$3)}`,
|
|
77225
|
+
`${grayBar}`,
|
|
77226
|
+
`${blCorner} ${question} ${dim(helpText)}`,
|
|
77227
|
+
`${space(2)}${format$3(value)}`,
|
|
77228
|
+
``
|
|
77229
|
+
],
|
|
77230
|
+
submit: ({ value }) => renderSubmit(config$2, format$3(value ?? "")),
|
|
77231
|
+
cancel: activeRenderer
|
|
77232
|
+
};
|
|
77233
|
+
};
|
|
77234
|
+
const getSelectRenderers = (config$2) => {
|
|
77235
|
+
const { options, question, helpText: _helpText } = config$2;
|
|
77236
|
+
const helpText = _helpText ?? "";
|
|
77237
|
+
const maxItemsPerPage = config$2.maxItemsPerPage ?? 32;
|
|
77238
|
+
const defaultRenderer = ({ cursor: cursor$1 = 0, value }) => {
|
|
77239
|
+
const renderOption = (opt, i$1) => {
|
|
77240
|
+
const { label: optionLabel, value: optionValue } = opt;
|
|
77241
|
+
const active = i$1 === cursor$1;
|
|
77242
|
+
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
|
|
77243
|
+
const color = isInListOfValues || active ? blue : white;
|
|
77244
|
+
const text = active ? color.underline(optionLabel) : color(optionLabel);
|
|
77245
|
+
const sublabel = opt.sublabel ? color.grey(opt.sublabel) : "";
|
|
77246
|
+
const indicator = isInListOfValues || active && !Array.isArray(value) ? color(opt.activeIcon ?? shapes.radioActive) : color(opt.inactiveIcon ?? shapes.radioInactive);
|
|
77247
|
+
return `${space(2)}${indicator} ${text} ${sublabel}`;
|
|
77248
|
+
};
|
|
77249
|
+
const renderOptionCondition = (_, i$1) => {
|
|
77250
|
+
if (options.length <= maxItemsPerPage) return true;
|
|
77251
|
+
if (i$1 < cursor$1) return options.length - i$1 <= maxItemsPerPage;
|
|
77252
|
+
return cursor$1 + maxItemsPerPage > i$1;
|
|
77253
|
+
};
|
|
77254
|
+
const visibleOptions = options.filter((o) => !o.hidden);
|
|
77255
|
+
const activeOption = visibleOptions.at(cursor$1);
|
|
77256
|
+
const lines = [
|
|
77257
|
+
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
77258
|
+
`${cursor$1 > 0 && options.length > maxItemsPerPage ? `${space(2)}${dim("...")}\n` : ""}${visibleOptions.map(renderOption).filter(renderOptionCondition).join(`\n`)}${cursor$1 + maxItemsPerPage < options.length && options.length > maxItemsPerPage ? `\n${space(2)}${dim("...")}` : ""}`,
|
|
77259
|
+
``
|
|
77260
|
+
];
|
|
77261
|
+
if (activeOption?.description) {
|
|
77262
|
+
const wordSegmenter = new Intl.Segmenter("en", { granularity: "word" });
|
|
77263
|
+
const padding = space(2);
|
|
77264
|
+
const availableWidth = process.stdout.columns - stripAnsi(padding).length * 2;
|
|
77265
|
+
const description = stripAnsi(activeOption.description);
|
|
77266
|
+
const descriptionLines = [];
|
|
77267
|
+
let descriptionLineNumber = 0;
|
|
77268
|
+
for (const data$1 of wordSegmenter.segment(description)) {
|
|
77269
|
+
let line = descriptionLines[descriptionLineNumber] ?? "";
|
|
77270
|
+
if (line.length + data$1.segment.length > availableWidth) {
|
|
77271
|
+
descriptionLineNumber++;
|
|
77272
|
+
line = "";
|
|
77273
|
+
if (data$1.segment.match(/^\s+$/)) continue;
|
|
77274
|
+
}
|
|
77275
|
+
descriptionLines[descriptionLineNumber] = line + data$1.segment;
|
|
77276
|
+
}
|
|
77277
|
+
lines.push(dim(descriptionLines.map((line) => padding + line + padding).join("\n")), ``);
|
|
77278
|
+
}
|
|
77279
|
+
return lines;
|
|
77280
|
+
};
|
|
77281
|
+
return {
|
|
77282
|
+
initial: defaultRenderer,
|
|
77283
|
+
active: defaultRenderer,
|
|
77284
|
+
confirm: defaultRenderer,
|
|
77285
|
+
error: (opts, prompt) => {
|
|
77286
|
+
return [
|
|
77287
|
+
`${leftT} ${status.error} ${dim(opts.error)}`,
|
|
77288
|
+
`${grayBar}`,
|
|
77289
|
+
...defaultRenderer(opts, prompt)
|
|
77290
|
+
];
|
|
77291
|
+
},
|
|
77292
|
+
submit: ({ value }) => {
|
|
77293
|
+
if (Array.isArray(value)) return renderSubmit(config$2, options.filter((o) => value.includes(o.value)).map((o) => o.label).join(", "));
|
|
77294
|
+
return renderSubmit(config$2, options.find((o) => o.value === value)?.label);
|
|
77295
|
+
},
|
|
77296
|
+
cancel: defaultRenderer
|
|
77297
|
+
};
|
|
77298
|
+
};
|
|
77299
|
+
const getSelectListRenderers = (config$2) => {
|
|
77300
|
+
const { question, helpText: _helpText } = config$2;
|
|
77301
|
+
let options = config$2.options;
|
|
77302
|
+
const helpText = _helpText ?? "";
|
|
77303
|
+
const { rows } = stdout$1;
|
|
77304
|
+
const defaultRenderer = ({ cursor: cursor$1, value }, prompt) => {
|
|
77305
|
+
if (prompt instanceof SelectRefreshablePrompt) options = prompt.options;
|
|
77306
|
+
cursor$1 = cursor$1 ?? 0;
|
|
77307
|
+
let smallCursor = 0;
|
|
77308
|
+
const renderOption = (opt, i$1) => {
|
|
77309
|
+
const { label: optionLabel, value: optionValueAny } = opt;
|
|
77310
|
+
const optionValue = optionValueAny.toString();
|
|
77311
|
+
const active = i$1 === smallCursor;
|
|
77312
|
+
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
|
|
77313
|
+
const color = isInListOfValues || active ? blue : white;
|
|
77314
|
+
const text = active ? color.underline(optionLabel) : color(optionLabel);
|
|
77315
|
+
const indicator = isInListOfValues || active && !Array.isArray(value) ? color(shapes.radioActive) : color(shapes.radioInactive);
|
|
77316
|
+
const indicatorMargin = 2;
|
|
77317
|
+
const detailBulletpointMargin = indicatorMargin + 4;
|
|
77318
|
+
return [`${space(indicatorMargin)}${indicator} ${text}`, ...opt.details.map((detail, j$1) => `${space(detailBulletpointMargin)}${j$1 === opt.details.length - 1 ? gray(shapes.corners.bl) : grayBar} ${detail}`)];
|
|
77319
|
+
};
|
|
77320
|
+
const pages = [];
|
|
77321
|
+
let current = {
|
|
77322
|
+
size: 0,
|
|
77323
|
+
options: []
|
|
77324
|
+
};
|
|
77325
|
+
const VERTICAL_MARGIN = 6;
|
|
77326
|
+
for (const option of options) {
|
|
77327
|
+
const optionHeight = option.details.length + 1;
|
|
77328
|
+
if (current.size + optionHeight > rows - VERTICAL_MARGIN) {
|
|
77329
|
+
pages.push(current.options);
|
|
77330
|
+
current = {
|
|
77331
|
+
size: optionHeight,
|
|
77332
|
+
options: [option]
|
|
77333
|
+
};
|
|
77334
|
+
continue;
|
|
77335
|
+
}
|
|
77336
|
+
current.size += optionHeight;
|
|
77337
|
+
current.options.push(option);
|
|
77338
|
+
}
|
|
77339
|
+
if (current.size !== 0) pages.push(current.options);
|
|
77340
|
+
let isFirstPage = true;
|
|
77341
|
+
let isLastPage = false;
|
|
77342
|
+
let page = [];
|
|
77343
|
+
let len = 0;
|
|
77344
|
+
for (let i$1 = 0; i$1 < pages.length; i$1++) {
|
|
77345
|
+
const pageIter = pages[i$1];
|
|
77346
|
+
if (cursor$1 >= len && pageIter.length + len > cursor$1) {
|
|
77347
|
+
isFirstPage = i$1 === 0;
|
|
77348
|
+
isLastPage = i$1 === pages.length - 1;
|
|
77349
|
+
page = pageIter;
|
|
77350
|
+
smallCursor = cursor$1 - len;
|
|
77351
|
+
break;
|
|
77352
|
+
}
|
|
77353
|
+
len += pageIter.length;
|
|
77354
|
+
}
|
|
77355
|
+
return [
|
|
77356
|
+
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
77357
|
+
...!isFirstPage ? [`${space(2)}${dim("...")}`] : [],
|
|
77358
|
+
...page.map(renderOption).reduce((prev, now) => [...prev, ...now], []),
|
|
77359
|
+
...!isLastPage ? [`${space(2)}${dim("...")}`] : []
|
|
77360
|
+
];
|
|
77361
|
+
};
|
|
77362
|
+
return {
|
|
77363
|
+
initial: defaultRenderer,
|
|
77364
|
+
active: defaultRenderer,
|
|
77365
|
+
confirm: defaultRenderer,
|
|
77366
|
+
error: (opts, prompt) => {
|
|
77367
|
+
return [
|
|
77368
|
+
`${leftT} ${status.error} ${dim(opts.error)}`,
|
|
77369
|
+
`${grayBar}`,
|
|
77370
|
+
...defaultRenderer(opts, prompt)
|
|
77371
|
+
];
|
|
77372
|
+
},
|
|
77373
|
+
submit: ({ value }) => {
|
|
77374
|
+
if (Array.isArray(value)) return renderSubmit(config$2, options.filter((o) => value.includes(o.value)).map((o) => o.value).join(", "));
|
|
77375
|
+
return renderSubmit(config$2, options.find((o) => o.value === value)?.value);
|
|
77376
|
+
},
|
|
77377
|
+
cancel: defaultRenderer
|
|
77378
|
+
};
|
|
77379
|
+
};
|
|
77380
|
+
const getConfirmRenderers = (config$2) => {
|
|
77381
|
+
const { activeText, inactiveText, question, helpText: _helpText } = config$2;
|
|
77382
|
+
const helpText = _helpText ?? "";
|
|
77383
|
+
const active = activeText || "Yes";
|
|
77384
|
+
const inactive = inactiveText || "No";
|
|
77385
|
+
const defaultRenderer = ({ value }) => {
|
|
77386
|
+
const yesColor = value ? blue.underline : dim;
|
|
77387
|
+
const noColor = value ? dim : blue.underline;
|
|
77388
|
+
return [`${blCorner} ${bold(question)} ${dim(helpText)}`, `${space(2)}${yesColor(active)} / ${noColor(inactive)}`];
|
|
77389
|
+
};
|
|
77390
|
+
return {
|
|
77391
|
+
initial: defaultRenderer,
|
|
77392
|
+
active: defaultRenderer,
|
|
77393
|
+
confirm: defaultRenderer,
|
|
77394
|
+
error: defaultRenderer,
|
|
77395
|
+
submit: ({ value }) => renderSubmit(config$2, value ? "yes" : "no"),
|
|
77396
|
+
cancel: defaultRenderer
|
|
77397
|
+
};
|
|
77398
|
+
};
|
|
76622
77399
|
const spinnerFrames = {
|
|
76623
77400
|
clockwise: [
|
|
76624
77401
|
"┤",
|
|
@@ -76652,7 +77429,7 @@ const ellipsisFrames = [
|
|
|
76652
77429
|
" .",
|
|
76653
77430
|
""
|
|
76654
77431
|
];
|
|
76655
|
-
const spinner = (frames = spinnerFrames.clockwise, color = brandColor
|
|
77432
|
+
const spinner = (frames = spinnerFrames.clockwise, color = brandColor) => {
|
|
76656
77433
|
const frameRate = 120;
|
|
76657
77434
|
let loop = null;
|
|
76658
77435
|
let startMsg;
|
|
@@ -76666,7 +77443,7 @@ const spinner = (frames = spinnerFrames.clockwise, color = brandColor$1) => {
|
|
|
76666
77443
|
helpText ||= ``;
|
|
76667
77444
|
currentMsg = msg;
|
|
76668
77445
|
startMsg = currentMsg;
|
|
76669
|
-
if (helpText !== void 0 && helpText.length > 0) startMsg += ` ${dim
|
|
77446
|
+
if (helpText !== void 0 && helpText.length > 0) startMsg += ` ${dim(helpText)}`;
|
|
76670
77447
|
if (isInteractive()) {
|
|
76671
77448
|
let index = 0;
|
|
76672
77449
|
clearLoop();
|
|
@@ -76674,25 +77451,25 @@ const spinner = (frames = spinnerFrames.clockwise, color = brandColor$1) => {
|
|
|
76674
77451
|
index++;
|
|
76675
77452
|
const spinnerFrame = frames[index % frames.length];
|
|
76676
77453
|
const ellipsisFrame = ellipsisFrames[index % ellipsisFrames.length];
|
|
76677
|
-
if (msg) logUpdate
|
|
77454
|
+
if (msg) logUpdate(`${color(spinnerFrame)} ${currentMsg} ${ellipsisFrame}`);
|
|
76678
77455
|
}, frameRate);
|
|
76679
|
-
} else logRaw
|
|
77456
|
+
} else logRaw(`${leftT} ${startMsg}`);
|
|
76680
77457
|
},
|
|
76681
77458
|
update(msg) {
|
|
76682
77459
|
currentMsg = msg;
|
|
76683
77460
|
},
|
|
76684
77461
|
stop(msg) {
|
|
76685
77462
|
if (isInteractive()) {
|
|
76686
|
-
logUpdate
|
|
77463
|
+
logUpdate.clear();
|
|
76687
77464
|
if (msg) {
|
|
76688
|
-
logUpdate
|
|
76689
|
-
logUpdate
|
|
76690
|
-
newline
|
|
77465
|
+
logUpdate(`${leftT} ${startMsg}\n${grayBar} ${msg}`);
|
|
77466
|
+
logUpdate.done();
|
|
77467
|
+
newline();
|
|
76691
77468
|
}
|
|
76692
77469
|
clearLoop();
|
|
76693
77470
|
} else {
|
|
76694
|
-
if (msg !== void 0) logRaw
|
|
76695
|
-
newline
|
|
77471
|
+
if (msg !== void 0) logRaw(`${grayBar} ${msg}`);
|
|
77472
|
+
newline();
|
|
76696
77473
|
}
|
|
76697
77474
|
}
|
|
76698
77475
|
};
|
|
@@ -76709,7 +77486,7 @@ function isInteractive() {
|
|
|
76709
77486
|
}
|
|
76710
77487
|
|
|
76711
77488
|
//#endregion
|
|
76712
|
-
//#region ../../node_modules/.pnpm/@cloudflare+containers-shared@0.23.
|
|
77489
|
+
//#region ../../node_modules/.pnpm/@cloudflare+containers-shared@0.23.8_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_d690da596d2700e963e98016f35645cb/node_modules/@cloudflare/containers-shared/dist/index.mjs
|
|
76713
77490
|
const require$1$1 = createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
76714
77491
|
var __create = Object.create;
|
|
76715
77492
|
var __defProp$2 = Object.defineProperty;
|
|
@@ -78600,7 +79377,7 @@ var require_extension = __commonJS({ "../../node_modules/.pnpm/ws@8.21.0/node_mo
|
|
|
78600
79377
|
return offers;
|
|
78601
79378
|
}
|
|
78602
79379
|
__name$2(parse$14, "parse");
|
|
78603
|
-
function format$
|
|
79380
|
+
function format$3(extensions) {
|
|
78604
79381
|
return Object.keys(extensions).map((extension2) => {
|
|
78605
79382
|
let configurations = extensions[extension2];
|
|
78606
79383
|
if (!Array.isArray(configurations)) configurations = [configurations];
|
|
@@ -78613,9 +79390,9 @@ var require_extension = __commonJS({ "../../node_modules/.pnpm/ws@8.21.0/node_mo
|
|
|
78613
79390
|
}).join(", ");
|
|
78614
79391
|
}).join(", ");
|
|
78615
79392
|
}
|
|
78616
|
-
__name$2(format$
|
|
79393
|
+
__name$2(format$3, "format");
|
|
78617
79394
|
module$1.exports = {
|
|
78618
|
-
format: format$
|
|
79395
|
+
format: format$3,
|
|
78619
79396
|
parse: parse$14
|
|
78620
79397
|
};
|
|
78621
79398
|
} });
|
|
@@ -78634,7 +79411,7 @@ var require_websocket = __commonJS({ "../../node_modules/.pnpm/ws@8.21.0/node_mo
|
|
|
78634
79411
|
var { isBlob: isBlob2 } = require_validation();
|
|
78635
79412
|
var { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER: EMPTY_BUFFER$1, GUID, kForOnEventAttribute, kListener: kListener$1, kStatusCode, kWebSocket, NOOP } = require_constants$1();
|
|
78636
79413
|
var { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
|
|
78637
|
-
var { format: format$
|
|
79414
|
+
var { format: format$3, parse: parse$14 } = require_extension();
|
|
78638
79415
|
var { toBuffer: toBuffer$1 } = require_buffer_util();
|
|
78639
79416
|
var kAborted = Symbol("kAborted");
|
|
78640
79417
|
var protocolVersions = [8, 13];
|
|
@@ -79141,7 +79918,7 @@ var require_websocket = __commonJS({ "../../node_modules/.pnpm/ws@8.21.0/node_mo
|
|
|
79141
79918
|
isServer: false,
|
|
79142
79919
|
maxPayload: opts.maxPayload
|
|
79143
79920
|
});
|
|
79144
|
-
opts.headers["Sec-WebSocket-Extensions"] = format$
|
|
79921
|
+
opts.headers["Sec-WebSocket-Extensions"] = format$3({ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer() });
|
|
79145
79922
|
}
|
|
79146
79923
|
if (protocols.length) {
|
|
79147
79924
|
for (const protocol of protocols) {
|
|
@@ -79921,7 +80698,7 @@ var ApiError = class extends Error {
|
|
|
79921
80698
|
this.request = request2;
|
|
79922
80699
|
}
|
|
79923
80700
|
};
|
|
79924
|
-
var CancelError
|
|
80701
|
+
var CancelError = class extends Error {
|
|
79925
80702
|
static {
|
|
79926
80703
|
__name$2(this, "CancelError");
|
|
79927
80704
|
}
|
|
@@ -79994,7 +80771,7 @@ var CancelablePromise = class {
|
|
|
79994
80771
|
return;
|
|
79995
80772
|
}
|
|
79996
80773
|
this.#cancelHandlers.length = 0;
|
|
79997
|
-
this.#reject?.(new CancelError
|
|
80774
|
+
this.#reject?.(new CancelError("Request aborted"));
|
|
79998
80775
|
}
|
|
79999
80776
|
get isCancelled() {
|
|
80000
80777
|
return this.#isCancelled;
|
|
@@ -81936,8 +82713,8 @@ async function getDockerSecurityOptions(dockerPath, dockerHost) {
|
|
|
81936
82713
|
], {
|
|
81937
82714
|
encoding: "utf8",
|
|
81938
82715
|
timeout: 5e3
|
|
81939
|
-
}, (error$3, stdout$
|
|
81940
|
-
if (error$3 === null) resolve2(stdout$
|
|
82716
|
+
}, (error$3, stdout$2) => {
|
|
82717
|
+
if (error$3 === null) resolve2(stdout$2);
|
|
81941
82718
|
else reject(error$3);
|
|
81942
82719
|
});
|
|
81943
82720
|
});
|
|
@@ -82238,13 +83015,13 @@ async function dockerImageInspect(dockerPath, options) {
|
|
|
82238
83015
|
"pipe",
|
|
82239
83016
|
"pipe"
|
|
82240
83017
|
] });
|
|
82241
|
-
let stdout$
|
|
82242
|
-
let stderr$
|
|
82243
|
-
proc.stdout.on("data", (chunk) => stdout$
|
|
82244
|
-
proc.stderr.on("data", (chunk) => stderr$
|
|
83018
|
+
let stdout$2 = "";
|
|
83019
|
+
let stderr$1 = "";
|
|
83020
|
+
proc.stdout.on("data", (chunk) => stdout$2 += chunk);
|
|
83021
|
+
proc.stderr.on("data", (chunk) => stderr$1 += chunk);
|
|
82245
83022
|
proc.on("close", (code) => {
|
|
82246
|
-
if (code !== 0) return reject(new UserError(`failed inspecting image locally: ${stderr$
|
|
82247
|
-
resolve2(stdout$
|
|
83023
|
+
if (code !== 0) return reject(new UserError(`failed inspecting image locally: ${stderr$1.trim()}`, { telemetryMessage: false }));
|
|
83024
|
+
resolve2(stdout$2.trim());
|
|
82248
83025
|
});
|
|
82249
83026
|
proc.on("error", (err) => reject(err));
|
|
82250
83027
|
});
|
|
@@ -82386,10 +83163,11 @@ function isDockerfileContainerConfig(container) {
|
|
|
82386
83163
|
}
|
|
82387
83164
|
__name$2(isDockerfileContainerConfig, "isDockerfileContainerConfig");
|
|
82388
83165
|
async function constructBuildCommand(options) {
|
|
83166
|
+
const imageOutput = process.env.WRANGLER_CONTAINER_IMAGE_COMPRESSION === "zstd" ? "type=docker,oci-mediatypes=true,compression=zstd,compression-level=3,force-compression=true" : void 0;
|
|
82389
83167
|
const platform$1 = options.platform ?? "linux/amd64";
|
|
82390
83168
|
const buildCmd = [
|
|
82391
83169
|
"build",
|
|
82392
|
-
"--load",
|
|
83170
|
+
...imageOutput ? ["--output", imageOutput] : ["--load"],
|
|
82393
83171
|
"-t",
|
|
82394
83172
|
options.tag,
|
|
82395
83173
|
"--platform",
|
|
@@ -82409,6 +83187,13 @@ async function constructBuildCommand(options) {
|
|
|
82409
83187
|
}
|
|
82410
83188
|
__name$2(constructBuildCommand, "constructBuildCommand");
|
|
82411
83189
|
async function startContainerBuild({ build: build$8, pathToDocker, verifyDockerIsRunning }) {
|
|
83190
|
+
if (process.env.WRANGLER_CONTAINER_IMAGE_COMPRESSION === "zstd") {
|
|
83191
|
+
if (!runDockerCmdWithOutput(pathToDocker, [
|
|
83192
|
+
"info",
|
|
83193
|
+
"--format",
|
|
83194
|
+
"{{json .DriverStatus}}"
|
|
83195
|
+
]).includes("io.containerd.snapshotter.v1")) throw new UserError("Zstd compression requires Docker's containerd image store. Enable the containerd image store or unset WRANGLER_CONTAINER_IMAGE_COMPRESSION.", { telemetryMessage: false });
|
|
83196
|
+
}
|
|
82412
83197
|
const { buildCmd, dockerfile } = await constructBuildCommand(build$8);
|
|
82413
83198
|
return await dockerBuild(pathToDocker, {
|
|
82414
83199
|
buildCmd,
|
|
@@ -83084,7 +83869,7 @@ var Diff = class {
|
|
|
83084
83869
|
`;
|
|
83085
83870
|
});
|
|
83086
83871
|
context.length = 0;
|
|
83087
|
-
for (const l of result.value.split("\n")) if (l) output$1 += `${result.added ? green
|
|
83872
|
+
for (const l of result.value.split("\n")) if (l) output$1 += `${result.added ? green("+") : red("-")} ${l}
|
|
83088
83873
|
`;
|
|
83089
83874
|
state = "diff";
|
|
83090
83875
|
} else {
|
|
@@ -83454,7 +84239,7 @@ async function apply(args, containerConfig, config$2, accountId) {
|
|
|
83454
84239
|
startSection("Deploy a container application", "deploy changes to your application");
|
|
83455
84240
|
let prevApp = (await promiseSpinner(ApplicationsService.listApplications(), { message: "Loading applications" })).find((app) => app.name === containerConfig.name);
|
|
83456
84241
|
const imageRef = "remoteDigest" in args.imageRef ? args.imageRef.remoteDigest : args.imageRef.newTag;
|
|
83457
|
-
log$1(dim
|
|
84242
|
+
log$1(dim("Container application changes\n"));
|
|
83458
84243
|
let migratedLegacyObservability = false;
|
|
83459
84244
|
if (prevApp !== void 0) {
|
|
83460
84245
|
if (!prevApp.durable_objects?.namespace_id) throw new FatalError("The previous deploy of this container application was not associated with a durable object", { telemetryMessage: "containers deploy previous durable object missing" });
|
|
@@ -83468,7 +84253,7 @@ async function apply(args, containerConfig, config$2, accountId) {
|
|
|
83468
84253
|
application: { observability: migrationObservability },
|
|
83469
84254
|
id: prevApp.id,
|
|
83470
84255
|
name: prevApp.name,
|
|
83471
|
-
successMessage: `Migrated observability configuration for ${brandColor
|
|
84256
|
+
successMessage: `Migrated observability configuration for ${brandColor(prevApp.name)} (Application ID: ${prevApp.id})`
|
|
83472
84257
|
});
|
|
83473
84258
|
prevApp = migrateLegacyObservabilityState(prevApp, migrationObservability);
|
|
83474
84259
|
migratedLegacyObservability = true;
|
|
@@ -83488,18 +84273,18 @@ async function apply(args, containerConfig, config$2, accountId) {
|
|
|
83488
84273
|
const diff$2 = new Diff(formatContainerSnippetForDisplay(normalisedPrevApp, config$2.configPath), formatContainerSnippetForDisplay(nowContainer, config$2.configPath));
|
|
83489
84274
|
if (diff$2.changes === 0) {
|
|
83490
84275
|
if (migratedLegacyObservability) {
|
|
83491
|
-
newline
|
|
84276
|
+
newline();
|
|
83492
84277
|
endSection("Applied changes");
|
|
83493
84278
|
return;
|
|
83494
84279
|
}
|
|
83495
|
-
updateStatus(`no changes ${brandColor
|
|
84280
|
+
updateStatus(`no changes ${brandColor(prevApp.name)}`);
|
|
83496
84281
|
endSection("No changes to be made");
|
|
83497
84282
|
return;
|
|
83498
84283
|
}
|
|
83499
|
-
updateStatus(`${brandColor
|
|
83500
|
-
newline
|
|
84284
|
+
updateStatus(`${brandColor.underline("EDIT")} ${prevApp.name}`, false);
|
|
84285
|
+
newline();
|
|
83501
84286
|
diff$2.print();
|
|
83502
|
-
newline
|
|
84287
|
+
newline();
|
|
83503
84288
|
if (containerConfig.rollout_kind !== "none") await doAction({
|
|
83504
84289
|
action: "modify",
|
|
83505
84290
|
application: modifyReq,
|
|
@@ -83512,18 +84297,18 @@ async function apply(args, containerConfig, config$2, accountId) {
|
|
|
83512
84297
|
});
|
|
83513
84298
|
else {
|
|
83514
84299
|
log$1("Skipping application rollout");
|
|
83515
|
-
newline
|
|
84300
|
+
newline();
|
|
83516
84301
|
}
|
|
83517
84302
|
} else {
|
|
83518
|
-
updateStatus(bold
|
|
84303
|
+
updateStatus(bold.underline(green.underline("NEW")) + ` ${appConfig.name}`);
|
|
83519
84304
|
formatContainerSnippetForDisplay(appConfig, config$2.configPath).trimEnd().split("\n").forEach((el) => log$1(` ${el}`));
|
|
83520
|
-
newline
|
|
84305
|
+
newline();
|
|
83521
84306
|
await doAction({
|
|
83522
84307
|
action: "create",
|
|
83523
84308
|
application: appConfig
|
|
83524
84309
|
});
|
|
83525
84310
|
}
|
|
83526
|
-
newline
|
|
84311
|
+
newline();
|
|
83527
84312
|
endSection("Applied changes");
|
|
83528
84313
|
}
|
|
83529
84314
|
__name$2(apply, "apply");
|
|
@@ -83541,7 +84326,7 @@ function formatError(err) {
|
|
|
83541
84326
|
if (maybeError.error !== void 0) {
|
|
83542
84327
|
const message = [];
|
|
83543
84328
|
message.push(`${maybeError.error}`);
|
|
83544
|
-
if (maybeError.details !== void 0 && typeof maybeError.details === "object") for (const key in maybeError.details) message.push(`${brandColor
|
|
84329
|
+
if (maybeError.details !== void 0 && typeof maybeError.details === "object") for (const key in maybeError.details) message.push(`${brandColor(key)} ${maybeError.details[key]}`);
|
|
83545
84330
|
return message.join("\n");
|
|
83546
84331
|
}
|
|
83547
84332
|
} catch {}
|
|
@@ -83561,7 +84346,7 @@ ${formatError(err)}`, { telemetryMessage: "containers deploy create misconfigura
|
|
|
83561
84346
|
throw new UserError(`Error creating application:
|
|
83562
84347
|
${formatError(err)}`, { telemetryMessage: "containers deploy create request failed" });
|
|
83563
84348
|
}
|
|
83564
|
-
success(`Created application ${brandColor
|
|
84349
|
+
success(`Created application ${brandColor(action.application.name)} (Application ID: ${application.id})`, { shape: shapes.bar });
|
|
83565
84350
|
}
|
|
83566
84351
|
if (action.action === "modify") {
|
|
83567
84352
|
try {
|
|
@@ -83593,7 +84378,7 @@ ${err.message}`, { telemetryMessage: "containers deploy rollout unexpected error
|
|
|
83593
84378
|
throw new UserError(`Error rolling out application "${action.name}":
|
|
83594
84379
|
${formatError(err)}`, { telemetryMessage: "containers deploy rollout request failed" });
|
|
83595
84380
|
}
|
|
83596
|
-
success(action.successMessage ?? `Modified application ${brandColor
|
|
84381
|
+
success(action.successMessage ?? `Modified application ${brandColor(action.name)} (Application ID: ${action.id})`, { shape: shapes.bar });
|
|
83597
84382
|
}
|
|
83598
84383
|
}, "doAction");
|
|
83599
84384
|
function cleanApplicationFromAPI(prev, currentConfig, accountId, observabilityWriteTarget, complianceConfig) {
|
|
@@ -83898,7 +84683,7 @@ async function sshCommand(sshArgs, userAgent) {
|
|
|
83898
84683
|
child.on("error", reject);
|
|
83899
84684
|
child.on("exit", (code) => {
|
|
83900
84685
|
if (code !== 255) resolve2(void 0);
|
|
83901
|
-
else reject(new Error(["SSH exited unsuccessfully. Is the container running?", `${bold
|
|
84686
|
+
else reject(new Error(["SSH exited unsuccessfully. Is the container running?", `${bold("NOTE:")} SSH does not automatically wake a container or count as activity to keep a container alive`].join("\n")));
|
|
83902
84687
|
});
|
|
83903
84688
|
});
|
|
83904
84689
|
showCursor(true);
|
|
@@ -84314,482 +85099,7 @@ function getDockerPath() {
|
|
|
84314
85099
|
}
|
|
84315
85100
|
|
|
84316
85101
|
//#endregion
|
|
84317
|
-
//#region ../../node_modules/.pnpm/@cloudflare+
|
|
84318
|
-
const { white, gray, dim, hidden, bold, cyanBright, bgCyan } = source_default;
|
|
84319
|
-
const brandColor = source_default.hex("#BD5B08");
|
|
84320
|
-
const black = source_default.hex("#111");
|
|
84321
|
-
const blue = source_default.hex("#0E838F");
|
|
84322
|
-
const bgBlue = black.bgHex("#0E838F");
|
|
84323
|
-
const red = source_default.hex("#AB2526");
|
|
84324
|
-
const bgRed = black.bgHex("#AB2526");
|
|
84325
|
-
const green = source_default.hex("#218529");
|
|
84326
|
-
const bgGreen = black.bgHex("#218529");
|
|
84327
|
-
const yellow = source_default.hex("#7F7322");
|
|
84328
|
-
const bgYellow = black.bgHex("#7F7322");
|
|
84329
|
-
|
|
84330
|
-
//#endregion
|
|
84331
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/error.mjs
|
|
84332
|
-
/**
|
|
84333
|
-
* Error thrown when an operation is cancelled
|
|
84334
|
-
*/
|
|
84335
|
-
var CancelError = class extends Error {
|
|
84336
|
-
constructor(message, signal) {
|
|
84337
|
-
super(message);
|
|
84338
|
-
this.signal = signal;
|
|
84339
|
-
}
|
|
84340
|
-
};
|
|
84341
|
-
|
|
84342
|
-
//#endregion
|
|
84343
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/select-list.mjs
|
|
84344
|
-
var SelectRefreshablePrompt = class extends p {
|
|
84345
|
-
options;
|
|
84346
|
-
cursor = 0;
|
|
84347
|
-
get _value() {
|
|
84348
|
-
return this.options[this.cursor];
|
|
84349
|
-
}
|
|
84350
|
-
changeValue() {
|
|
84351
|
-
this.value = this._value.value;
|
|
84352
|
-
}
|
|
84353
|
-
constructor(opts) {
|
|
84354
|
-
super(opts, false);
|
|
84355
|
-
this.options = opts.options;
|
|
84356
|
-
this.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);
|
|
84357
|
-
if (this.cursor === -1) this.cursor = 0;
|
|
84358
|
-
this.changeValue();
|
|
84359
|
-
this.on("key", (c$1) => {
|
|
84360
|
-
if (c$1 !== "r") return;
|
|
84361
|
-
opts.onRefresh().then((newOptions) => {
|
|
84362
|
-
this.options = [...newOptions];
|
|
84363
|
-
this.cursor = 0;
|
|
84364
|
-
this.changeValue();
|
|
84365
|
-
const that = this;
|
|
84366
|
-
if ("render" in that && typeof that.render === "function") that.render();
|
|
84367
|
-
}).catch(() => {});
|
|
84368
|
-
});
|
|
84369
|
-
this.on("cursor", (key) => {
|
|
84370
|
-
switch (key) {
|
|
84371
|
-
case "left":
|
|
84372
|
-
case "up":
|
|
84373
|
-
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
|
|
84374
|
-
break;
|
|
84375
|
-
case "down":
|
|
84376
|
-
case "right":
|
|
84377
|
-
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
|
|
84378
|
-
break;
|
|
84379
|
-
}
|
|
84380
|
-
this.changeValue();
|
|
84381
|
-
});
|
|
84382
|
-
}
|
|
84383
|
-
};
|
|
84384
|
-
|
|
84385
|
-
//#endregion
|
|
84386
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/streams.mjs
|
|
84387
|
-
/**
|
|
84388
|
-
* This file simply re-exports the process's writeable streams
|
|
84389
|
-
* The intention is to provide a boundary to mock in tests
|
|
84390
|
-
* Anywhere in this package that writes to stdout/stderr,
|
|
84391
|
-
* should use this module to get references to them.
|
|
84392
|
-
*/
|
|
84393
|
-
const stdout$1 = process.stdout;
|
|
84394
|
-
const stderr = process.stderr;
|
|
84395
|
-
|
|
84396
|
-
//#endregion
|
|
84397
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/check-macos-version.mjs
|
|
84398
|
-
var import_ci_info = /* @__PURE__ */ __toESM$2(require_ci_info(), 1);
|
|
84399
|
-
|
|
84400
|
-
//#endregion
|
|
84401
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/index.mjs
|
|
84402
|
-
const shapes = {
|
|
84403
|
-
diamond: "◇",
|
|
84404
|
-
dash: "─",
|
|
84405
|
-
radioInactive: "○",
|
|
84406
|
-
radioActive: "●",
|
|
84407
|
-
backActive: "◀",
|
|
84408
|
-
backInactive: "◁",
|
|
84409
|
-
bar: "│",
|
|
84410
|
-
leftT: "├",
|
|
84411
|
-
rigthT: "┤",
|
|
84412
|
-
arrows: {
|
|
84413
|
-
left: "‹",
|
|
84414
|
-
right: "›"
|
|
84415
|
-
},
|
|
84416
|
-
corners: {
|
|
84417
|
-
tl: "╭",
|
|
84418
|
-
bl: "╰",
|
|
84419
|
-
tr: "╮",
|
|
84420
|
-
br: "╯"
|
|
84421
|
-
}
|
|
84422
|
-
};
|
|
84423
|
-
const status = {
|
|
84424
|
-
error: bgRed(` ERROR `),
|
|
84425
|
-
warning: bgYellow(` WARNING `),
|
|
84426
|
-
info: bgBlue(` INFO `),
|
|
84427
|
-
success: bgGreen(` SUCCESS `),
|
|
84428
|
-
cancel: white.bgRed(` X `)
|
|
84429
|
-
};
|
|
84430
|
-
const space = (n$1 = 1) => {
|
|
84431
|
-
return hidden(" ".repeat(n$1));
|
|
84432
|
-
};
|
|
84433
|
-
const LOGGER_LEVELS = {
|
|
84434
|
-
none: -1,
|
|
84435
|
-
error: 0,
|
|
84436
|
-
warn: 1,
|
|
84437
|
-
info: 2,
|
|
84438
|
-
log: 3,
|
|
84439
|
-
debug: 4
|
|
84440
|
-
};
|
|
84441
|
-
let currentLogLevel = "log";
|
|
84442
|
-
function getLogLevel() {
|
|
84443
|
-
return currentLogLevel;
|
|
84444
|
-
}
|
|
84445
|
-
const logRaw = (msg) => {
|
|
84446
|
-
if (LOGGER_LEVELS[getLogLevel()] >= LOGGER_LEVELS.log) stdout$1.write(`${msg}\n`);
|
|
84447
|
-
};
|
|
84448
|
-
const format$1 = (msg, { linePrefix = gray(shapes.bar), firstLinePrefix = linePrefix, newlineBefore = false, newlineAfter = false, formatLine = (line) => white(line), multiline = true } = {}) => {
|
|
84449
|
-
const formattedLines = (multiline ? msg.split("\n") : [msg]).map((line, i$1) => (i$1 === 0 ? firstLinePrefix : linePrefix) + space() + formatLine(line));
|
|
84450
|
-
if (newlineBefore) formattedLines.unshift(linePrefix);
|
|
84451
|
-
if (newlineAfter) formattedLines.push(linePrefix);
|
|
84452
|
-
return formattedLines.join("\n");
|
|
84453
|
-
};
|
|
84454
|
-
const cancel = (msg, { shape = shapes.corners.bl, multiline = false } = {}) => {
|
|
84455
|
-
logRaw(format$1(msg, {
|
|
84456
|
-
firstLinePrefix: `${gray(shape)} ${status.cancel}`,
|
|
84457
|
-
linePrefix: gray(shapes.bar),
|
|
84458
|
-
newlineBefore: true,
|
|
84459
|
-
formatLine: (line) => dim(line),
|
|
84460
|
-
multiline
|
|
84461
|
-
}));
|
|
84462
|
-
};
|
|
84463
|
-
const stripAnsi = (str) => {
|
|
84464
|
-
const pattern = ["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))"].join("|");
|
|
84465
|
-
const regex$1 = RegExp(pattern, "g");
|
|
84466
|
-
return str.replace(linkRegex, "$2").replace(regex$1, "");
|
|
84467
|
-
};
|
|
84468
|
-
const linkRegex = /\u001B\]8;;(?<url>.+)\u001B\\(?<label>.+)\u001B\]8;;\u001B\\/g;
|
|
84469
|
-
const crash = (msg, extra) => {
|
|
84470
|
-
error(msg, extra);
|
|
84471
|
-
exit(1);
|
|
84472
|
-
};
|
|
84473
|
-
const error = (msg, extra, corner = shapes.corners.bl) => {
|
|
84474
|
-
const currentLevel = getLogLevel();
|
|
84475
|
-
if (msg && LOGGER_LEVELS[currentLevel] >= LOGGER_LEVELS.error) stderr.write(`${gray(corner)} ${status.error} ${dim(msg)}\n${extra ? space() + extra + "\n" : ""}`);
|
|
84476
|
-
};
|
|
84477
|
-
|
|
84478
|
-
//#endregion
|
|
84479
|
-
//#region ../../node_modules/.pnpm/@cloudflare+cli-shared-helpers@0.2.7_vitest@5.0.4_@opentelemetry+api@1.9.1_@types+node@_6654add0bd975deffde8872e8da63d3e/node_modules/@cloudflare/cli-shared-helpers/dist/interactive.mjs
|
|
84480
|
-
const logUpdate = createLogUpdate(stdout$1);
|
|
84481
|
-
const grayBar = gray(shapes.bar);
|
|
84482
|
-
const blCorner = gray(shapes.corners.bl);
|
|
84483
|
-
const leftT = gray(shapes.leftT);
|
|
84484
|
-
function acceptDefault(promptConfig, renderers, initialValue) {
|
|
84485
|
-
const error$3 = promptConfig.validate?.(initialValue);
|
|
84486
|
-
if (error$3) {
|
|
84487
|
-
const errorMessage = error$3 instanceof Error ? error$3.message : error$3;
|
|
84488
|
-
if (promptConfig.throwOnError) throw new Error(errorMessage);
|
|
84489
|
-
else crash(errorMessage);
|
|
84490
|
-
}
|
|
84491
|
-
logRaw(renderers.submit({ value: initialValue }).join("\n"));
|
|
84492
|
-
return initialValue;
|
|
84493
|
-
}
|
|
84494
|
-
const inputPrompt = async (promptConfig) => {
|
|
84495
|
-
const renderers = {
|
|
84496
|
-
...getRenderers(promptConfig),
|
|
84497
|
-
...promptConfig.renderers
|
|
84498
|
-
};
|
|
84499
|
-
let prompt;
|
|
84500
|
-
const dispatchRender = (props, p$2) => {
|
|
84501
|
-
let state = props.state;
|
|
84502
|
-
if (state === "initial" && promptConfig.initialErrorMessage) {
|
|
84503
|
-
state = "error";
|
|
84504
|
-
props.error = promptConfig.initialErrorMessage;
|
|
84505
|
-
}
|
|
84506
|
-
return renderers[state](props, p$2).join("\n");
|
|
84507
|
-
};
|
|
84508
|
-
if (promptConfig.type === "select") {
|
|
84509
|
-
const initialValue = String(promptConfig.defaultValue);
|
|
84510
|
-
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
84511
|
-
prompt = new nt({
|
|
84512
|
-
...promptConfig,
|
|
84513
|
-
options: promptConfig.options.filter((o) => !o.hidden),
|
|
84514
|
-
initialValue,
|
|
84515
|
-
render() {
|
|
84516
|
-
return dispatchRender(this, prompt);
|
|
84517
|
-
}
|
|
84518
|
-
});
|
|
84519
|
-
} else if (promptConfig.type === "confirm") {
|
|
84520
|
-
const initialValue = Boolean(promptConfig.defaultValue);
|
|
84521
|
-
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
84522
|
-
prompt = new Q({
|
|
84523
|
-
...promptConfig,
|
|
84524
|
-
initialValue,
|
|
84525
|
-
active: promptConfig.activeText || "",
|
|
84526
|
-
inactive: promptConfig.inactiveText || "",
|
|
84527
|
-
render() {
|
|
84528
|
-
return dispatchRender(this, prompt);
|
|
84529
|
-
}
|
|
84530
|
-
});
|
|
84531
|
-
} else if (promptConfig.type == "multiselect") {
|
|
84532
|
-
let initialValues;
|
|
84533
|
-
if (Array.isArray(promptConfig.defaultValue)) initialValues = promptConfig.defaultValue;
|
|
84534
|
-
else if (promptConfig.defaultValue !== void 0) initialValues = [String(promptConfig.defaultValue)];
|
|
84535
|
-
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValues);
|
|
84536
|
-
prompt = new it({
|
|
84537
|
-
...promptConfig,
|
|
84538
|
-
options: promptConfig.options,
|
|
84539
|
-
initialValues,
|
|
84540
|
-
render() {
|
|
84541
|
-
return dispatchRender(this, prompt);
|
|
84542
|
-
}
|
|
84543
|
-
});
|
|
84544
|
-
} else if (promptConfig.type === "list") {
|
|
84545
|
-
const initialValue = String(promptConfig.defaultValue);
|
|
84546
|
-
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
84547
|
-
prompt = new SelectRefreshablePrompt({
|
|
84548
|
-
...promptConfig,
|
|
84549
|
-
onRefresh: promptConfig.onRefresh ?? (() => Promise.resolve(promptConfig.options)),
|
|
84550
|
-
initialValue,
|
|
84551
|
-
render() {
|
|
84552
|
-
return dispatchRender(this, prompt);
|
|
84553
|
-
}
|
|
84554
|
-
});
|
|
84555
|
-
} else {
|
|
84556
|
-
const initialValue = promptConfig.initialValue ?? String(promptConfig.defaultValue ?? "");
|
|
84557
|
-
if (promptConfig.acceptDefault) return acceptDefault(promptConfig, renderers, initialValue);
|
|
84558
|
-
prompt = new at({
|
|
84559
|
-
...promptConfig,
|
|
84560
|
-
initialValue: promptConfig.initialValue,
|
|
84561
|
-
defaultValue: String(promptConfig.defaultValue ?? ""),
|
|
84562
|
-
render() {
|
|
84563
|
-
return dispatchRender(this, prompt);
|
|
84564
|
-
}
|
|
84565
|
-
});
|
|
84566
|
-
}
|
|
84567
|
-
const input$1 = await prompt.prompt();
|
|
84568
|
-
if (q(input$1)) if (promptConfig.throwOnError) throw new CancelError("Operation cancelled");
|
|
84569
|
-
else {
|
|
84570
|
-
cancel("Operation cancelled");
|
|
84571
|
-
process.exit(0);
|
|
84572
|
-
}
|
|
84573
|
-
return input$1;
|
|
84574
|
-
};
|
|
84575
|
-
const renderSubmit = (config$2, value) => {
|
|
84576
|
-
const { question, label } = config$2;
|
|
84577
|
-
if (config$2.type !== "confirm" && !value) return [`${leftT} ${question} ${dim("(skipped)")}`, `${grayBar}`];
|
|
84578
|
-
const content = config$2.type === "confirm" ? `${grayBar} ${brandColor(value)} ${dim(label)}` : `${grayBar} ${brandColor(label)} ${dim(value)}`;
|
|
84579
|
-
return [
|
|
84580
|
-
`${leftT} ${question}`,
|
|
84581
|
-
content,
|
|
84582
|
-
`${grayBar}`
|
|
84583
|
-
];
|
|
84584
|
-
};
|
|
84585
|
-
const getRenderers = (config$2) => {
|
|
84586
|
-
switch (config$2.type) {
|
|
84587
|
-
case "select": return getSelectRenderers(config$2);
|
|
84588
|
-
case "confirm": return getConfirmRenderers(config$2);
|
|
84589
|
-
case "text": return getTextRenderers(config$2);
|
|
84590
|
-
case "multiselect": return getSelectRenderers(config$2);
|
|
84591
|
-
case "list": return getSelectListRenderers(config$2);
|
|
84592
|
-
}
|
|
84593
|
-
};
|
|
84594
|
-
const getTextRenderers = (config$2) => {
|
|
84595
|
-
const { question } = config$2;
|
|
84596
|
-
const helpText = config$2.helpText ?? "";
|
|
84597
|
-
const format$4 = config$2.format ?? ((val) => String(val));
|
|
84598
|
-
const defaultValue = config$2.defaultValue?.toString() ?? "";
|
|
84599
|
-
const activeRenderer = (props) => {
|
|
84600
|
-
const { userInputWithCursor } = props;
|
|
84601
|
-
return [
|
|
84602
|
-
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
84603
|
-
`${space(2)}${format$4(userInputWithCursor || dim(defaultValue))}`,
|
|
84604
|
-
``
|
|
84605
|
-
];
|
|
84606
|
-
};
|
|
84607
|
-
return {
|
|
84608
|
-
initial: () => [
|
|
84609
|
-
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
84610
|
-
`${space(2)}${gray(format$4(defaultValue))}`,
|
|
84611
|
-
``
|
|
84612
|
-
],
|
|
84613
|
-
active: activeRenderer,
|
|
84614
|
-
error: ({ value, error: error$3 }) => [
|
|
84615
|
-
`${leftT} ${status.error} ${dim(error$3)}`,
|
|
84616
|
-
`${grayBar}`,
|
|
84617
|
-
`${blCorner} ${question} ${dim(helpText)}`,
|
|
84618
|
-
`${space(2)}${format$4(value)}`,
|
|
84619
|
-
``
|
|
84620
|
-
],
|
|
84621
|
-
submit: ({ value }) => renderSubmit(config$2, format$4(value ?? "")),
|
|
84622
|
-
cancel: activeRenderer
|
|
84623
|
-
};
|
|
84624
|
-
};
|
|
84625
|
-
const getSelectRenderers = (config$2) => {
|
|
84626
|
-
const { options, question, helpText: _helpText } = config$2;
|
|
84627
|
-
const helpText = _helpText ?? "";
|
|
84628
|
-
const maxItemsPerPage = config$2.maxItemsPerPage ?? 32;
|
|
84629
|
-
const defaultRenderer = ({ cursor: cursor$1 = 0, value }) => {
|
|
84630
|
-
const renderOption = (opt, i$1) => {
|
|
84631
|
-
const { label: optionLabel, value: optionValue } = opt;
|
|
84632
|
-
const active = i$1 === cursor$1;
|
|
84633
|
-
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
|
|
84634
|
-
const color = isInListOfValues || active ? blue : white;
|
|
84635
|
-
const text = active ? color.underline(optionLabel) : color(optionLabel);
|
|
84636
|
-
const sublabel = opt.sublabel ? color.grey(opt.sublabel) : "";
|
|
84637
|
-
const indicator = isInListOfValues || active && !Array.isArray(value) ? color(opt.activeIcon ?? shapes.radioActive) : color(opt.inactiveIcon ?? shapes.radioInactive);
|
|
84638
|
-
return `${space(2)}${indicator} ${text} ${sublabel}`;
|
|
84639
|
-
};
|
|
84640
|
-
const renderOptionCondition = (_, i$1) => {
|
|
84641
|
-
if (options.length <= maxItemsPerPage) return true;
|
|
84642
|
-
if (i$1 < cursor$1) return options.length - i$1 <= maxItemsPerPage;
|
|
84643
|
-
return cursor$1 + maxItemsPerPage > i$1;
|
|
84644
|
-
};
|
|
84645
|
-
const visibleOptions = options.filter((o) => !o.hidden);
|
|
84646
|
-
const activeOption = visibleOptions.at(cursor$1);
|
|
84647
|
-
const lines = [
|
|
84648
|
-
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
84649
|
-
`${cursor$1 > 0 && options.length > maxItemsPerPage ? `${space(2)}${dim("...")}\n` : ""}${visibleOptions.map(renderOption).filter(renderOptionCondition).join(`\n`)}${cursor$1 + maxItemsPerPage < options.length && options.length > maxItemsPerPage ? `\n${space(2)}${dim("...")}` : ""}`,
|
|
84650
|
-
``
|
|
84651
|
-
];
|
|
84652
|
-
if (activeOption?.description) {
|
|
84653
|
-
const wordSegmenter = new Intl.Segmenter("en", { granularity: "word" });
|
|
84654
|
-
const padding = space(2);
|
|
84655
|
-
const availableWidth = process.stdout.columns - stripAnsi(padding).length * 2;
|
|
84656
|
-
const description = stripAnsi(activeOption.description);
|
|
84657
|
-
const descriptionLines = [];
|
|
84658
|
-
let descriptionLineNumber = 0;
|
|
84659
|
-
for (const data$1 of wordSegmenter.segment(description)) {
|
|
84660
|
-
let line = descriptionLines[descriptionLineNumber] ?? "";
|
|
84661
|
-
if (line.length + data$1.segment.length > availableWidth) {
|
|
84662
|
-
descriptionLineNumber++;
|
|
84663
|
-
line = "";
|
|
84664
|
-
if (data$1.segment.match(/^\s+$/)) continue;
|
|
84665
|
-
}
|
|
84666
|
-
descriptionLines[descriptionLineNumber] = line + data$1.segment;
|
|
84667
|
-
}
|
|
84668
|
-
lines.push(dim(descriptionLines.map((line) => padding + line + padding).join("\n")), ``);
|
|
84669
|
-
}
|
|
84670
|
-
return lines;
|
|
84671
|
-
};
|
|
84672
|
-
return {
|
|
84673
|
-
initial: defaultRenderer,
|
|
84674
|
-
active: defaultRenderer,
|
|
84675
|
-
confirm: defaultRenderer,
|
|
84676
|
-
error: (opts, prompt) => {
|
|
84677
|
-
return [
|
|
84678
|
-
`${leftT} ${status.error} ${dim(opts.error)}`,
|
|
84679
|
-
`${grayBar}`,
|
|
84680
|
-
...defaultRenderer(opts, prompt)
|
|
84681
|
-
];
|
|
84682
|
-
},
|
|
84683
|
-
submit: ({ value }) => {
|
|
84684
|
-
if (Array.isArray(value)) return renderSubmit(config$2, options.filter((o) => value.includes(o.value)).map((o) => o.label).join(", "));
|
|
84685
|
-
return renderSubmit(config$2, options.find((o) => o.value === value)?.label);
|
|
84686
|
-
},
|
|
84687
|
-
cancel: defaultRenderer
|
|
84688
|
-
};
|
|
84689
|
-
};
|
|
84690
|
-
const getSelectListRenderers = (config$2) => {
|
|
84691
|
-
const { question, helpText: _helpText } = config$2;
|
|
84692
|
-
let options = config$2.options;
|
|
84693
|
-
const helpText = _helpText ?? "";
|
|
84694
|
-
const { rows } = stdout$1;
|
|
84695
|
-
const defaultRenderer = ({ cursor: cursor$1, value }, prompt) => {
|
|
84696
|
-
if (prompt instanceof SelectRefreshablePrompt) options = prompt.options;
|
|
84697
|
-
cursor$1 = cursor$1 ?? 0;
|
|
84698
|
-
let smallCursor = 0;
|
|
84699
|
-
const renderOption = (opt, i$1) => {
|
|
84700
|
-
const { label: optionLabel, value: optionValueAny } = opt;
|
|
84701
|
-
const optionValue = optionValueAny.toString();
|
|
84702
|
-
const active = i$1 === smallCursor;
|
|
84703
|
-
const isInListOfValues = Array.isArray(value) && value.includes(optionValue);
|
|
84704
|
-
const color = isInListOfValues || active ? blue : white;
|
|
84705
|
-
const text = active ? color.underline(optionLabel) : color(optionLabel);
|
|
84706
|
-
const indicator = isInListOfValues || active && !Array.isArray(value) ? color(shapes.radioActive) : color(shapes.radioInactive);
|
|
84707
|
-
const indicatorMargin = 2;
|
|
84708
|
-
const detailBulletpointMargin = indicatorMargin + 4;
|
|
84709
|
-
return [`${space(indicatorMargin)}${indicator} ${text}`, ...opt.details.map((detail, j$1) => `${space(detailBulletpointMargin)}${j$1 === opt.details.length - 1 ? gray(shapes.corners.bl) : grayBar} ${detail}`)];
|
|
84710
|
-
};
|
|
84711
|
-
const pages = [];
|
|
84712
|
-
let current = {
|
|
84713
|
-
size: 0,
|
|
84714
|
-
options: []
|
|
84715
|
-
};
|
|
84716
|
-
const VERTICAL_MARGIN = 6;
|
|
84717
|
-
for (const option of options) {
|
|
84718
|
-
const optionHeight = option.details.length + 1;
|
|
84719
|
-
if (current.size + optionHeight > rows - VERTICAL_MARGIN) {
|
|
84720
|
-
pages.push(current.options);
|
|
84721
|
-
current = {
|
|
84722
|
-
size: optionHeight,
|
|
84723
|
-
options: [option]
|
|
84724
|
-
};
|
|
84725
|
-
continue;
|
|
84726
|
-
}
|
|
84727
|
-
current.size += optionHeight;
|
|
84728
|
-
current.options.push(option);
|
|
84729
|
-
}
|
|
84730
|
-
if (current.size !== 0) pages.push(current.options);
|
|
84731
|
-
let isFirstPage = true;
|
|
84732
|
-
let isLastPage = false;
|
|
84733
|
-
let page = [];
|
|
84734
|
-
let len = 0;
|
|
84735
|
-
for (let i$1 = 0; i$1 < pages.length; i$1++) {
|
|
84736
|
-
const pageIter = pages[i$1];
|
|
84737
|
-
if (cursor$1 >= len && pageIter.length + len > cursor$1) {
|
|
84738
|
-
isFirstPage = i$1 === 0;
|
|
84739
|
-
isLastPage = i$1 === pages.length - 1;
|
|
84740
|
-
page = pageIter;
|
|
84741
|
-
smallCursor = cursor$1 - len;
|
|
84742
|
-
break;
|
|
84743
|
-
}
|
|
84744
|
-
len += pageIter.length;
|
|
84745
|
-
}
|
|
84746
|
-
return [
|
|
84747
|
-
`${blCorner} ${bold(question)} ${dim(helpText)}`,
|
|
84748
|
-
...!isFirstPage ? [`${space(2)}${dim("...")}`] : [],
|
|
84749
|
-
...page.map(renderOption).reduce((prev, now) => [...prev, ...now], []),
|
|
84750
|
-
...!isLastPage ? [`${space(2)}${dim("...")}`] : []
|
|
84751
|
-
];
|
|
84752
|
-
};
|
|
84753
|
-
return {
|
|
84754
|
-
initial: defaultRenderer,
|
|
84755
|
-
active: defaultRenderer,
|
|
84756
|
-
confirm: defaultRenderer,
|
|
84757
|
-
error: (opts, prompt) => {
|
|
84758
|
-
return [
|
|
84759
|
-
`${leftT} ${status.error} ${dim(opts.error)}`,
|
|
84760
|
-
`${grayBar}`,
|
|
84761
|
-
...defaultRenderer(opts, prompt)
|
|
84762
|
-
];
|
|
84763
|
-
},
|
|
84764
|
-
submit: ({ value }) => {
|
|
84765
|
-
if (Array.isArray(value)) return renderSubmit(config$2, options.filter((o) => value.includes(o.value)).map((o) => o.value).join(", "));
|
|
84766
|
-
return renderSubmit(config$2, options.find((o) => o.value === value)?.value);
|
|
84767
|
-
},
|
|
84768
|
-
cancel: defaultRenderer
|
|
84769
|
-
};
|
|
84770
|
-
};
|
|
84771
|
-
const getConfirmRenderers = (config$2) => {
|
|
84772
|
-
const { activeText, inactiveText, question, helpText: _helpText } = config$2;
|
|
84773
|
-
const helpText = _helpText ?? "";
|
|
84774
|
-
const active = activeText || "Yes";
|
|
84775
|
-
const inactive = inactiveText || "No";
|
|
84776
|
-
const defaultRenderer = ({ value }) => {
|
|
84777
|
-
const yesColor = value ? blue.underline : dim;
|
|
84778
|
-
const noColor = value ? dim : blue.underline;
|
|
84779
|
-
return [`${blCorner} ${bold(question)} ${dim(helpText)}`, `${space(2)}${yesColor(active)} / ${noColor(inactive)}`];
|
|
84780
|
-
};
|
|
84781
|
-
return {
|
|
84782
|
-
initial: defaultRenderer,
|
|
84783
|
-
active: defaultRenderer,
|
|
84784
|
-
confirm: defaultRenderer,
|
|
84785
|
-
error: defaultRenderer,
|
|
84786
|
-
submit: ({ value }) => renderSubmit(config$2, value ? "yes" : "no"),
|
|
84787
|
-
cancel: defaultRenderer
|
|
84788
|
-
};
|
|
84789
|
-
};
|
|
84790
|
-
|
|
84791
|
-
//#endregion
|
|
84792
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.1_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_201177df6d19f48647452d3f410e1adc/node_modules/@cloudflare/workers-auth/dist/chunk-VAZEJK55.mjs
|
|
85102
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.6_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_d34e447d1a00c49a218f49ca1f431b88/node_modules/@cloudflare/workers-auth/dist/chunk-VAZEJK55.mjs
|
|
84793
85103
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
84794
85104
|
var __defProp$1 = Object.defineProperty;
|
|
84795
85105
|
var __name$1 = (target$1, value) => __defProp$1(target$1, "name", {
|
|
@@ -84798,7 +85108,7 @@ var __name$1 = (target$1, value) => __defProp$1(target$1, "name", {
|
|
|
84798
85108
|
});
|
|
84799
85109
|
|
|
84800
85110
|
//#endregion
|
|
84801
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.
|
|
85111
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.6_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_d34e447d1a00c49a218f49ca1f431b88/node_modules/@cloudflare/workers-auth/dist/chunk-SOBRPAPT.mjs
|
|
84802
85112
|
var import_undici$2 = require_undici();
|
|
84803
85113
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
84804
85114
|
var hasWarnedAboutDeprecatedV1ApiToken = false;
|
|
@@ -84932,14 +85242,14 @@ async function domainUsesAccess(domain$1, logger$2, previewToken) {
|
|
|
84932
85242
|
logger$2.debug("Access switch not cached for:", domain$1);
|
|
84933
85243
|
try {
|
|
84934
85244
|
const controller = new AbortController();
|
|
84935
|
-
const cancel$
|
|
85245
|
+
const cancel$1 = setTimeout(() => {
|
|
84936
85246
|
controller.abort();
|
|
84937
85247
|
}, 1e3);
|
|
84938
85248
|
const output$1 = await (0, import_undici$2.fetch)(buildProbeUrl(domain$1, previewToken), {
|
|
84939
85249
|
redirect: "manual",
|
|
84940
85250
|
signal: controller.signal
|
|
84941
85251
|
});
|
|
84942
|
-
clearTimeout(cancel$
|
|
85252
|
+
clearTimeout(cancel$1);
|
|
84943
85253
|
const usesAccess = !!(output$1.status === 302 && output$1.headers.get("location")?.includes("cloudflareaccess.com"));
|
|
84944
85254
|
if (usesAccess || !previewToken) {
|
|
84945
85255
|
logger$2.debug("Caching access switch for:", domain$1);
|
|
@@ -85480,14 +85790,18 @@ var ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
|
|
|
85480
85790
|
}
|
|
85481
85791
|
};
|
|
85482
85792
|
function formatOAuthErrorMessage(code, description, uri) {
|
|
85483
|
-
let message = `OAuth error: ${code}`;
|
|
85793
|
+
let message = `OAuth error: ${escapeOAuthErrorText(code)}`;
|
|
85484
85794
|
if (description) message += `
|
|
85485
|
-
${description}`;
|
|
85795
|
+
${escapeOAuthErrorText(description)}`;
|
|
85486
85796
|
if (uri) message += `
|
|
85487
|
-
See: ${uri}`;
|
|
85797
|
+
See: ${escapeOAuthErrorText(uri)}`;
|
|
85488
85798
|
return message;
|
|
85489
85799
|
}
|
|
85490
85800
|
__name$1(formatOAuthErrorMessage, "formatOAuthErrorMessage");
|
|
85801
|
+
function escapeOAuthErrorText(value) {
|
|
85802
|
+
return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
85803
|
+
}
|
|
85804
|
+
__name$1(escapeOAuthErrorText, "escapeOAuthErrorText");
|
|
85491
85805
|
function toErrorClass(rawError, description, uri) {
|
|
85492
85806
|
const message = formatOAuthErrorMessage(rawError, description, uri);
|
|
85493
85807
|
let error$3;
|
|
@@ -85540,13 +85854,14 @@ function toErrorClass(rawError, description, uri) {
|
|
|
85540
85854
|
__name$1(toErrorClass, "toErrorClass");
|
|
85541
85855
|
var TOKEN_REQUEST_TIMEOUT_MS = 3e4;
|
|
85542
85856
|
function isReturningFromAuthServer(query, state, logger$2) {
|
|
85543
|
-
|
|
85544
|
-
|
|
85545
|
-
if (!code) return false;
|
|
85546
|
-
if (query.state !== state.stateQueryParam) {
|
|
85857
|
+
const stateQueryParam = query.state;
|
|
85858
|
+
if (!state.stateQueryParam || stateQueryParam !== state.stateQueryParam) {
|
|
85547
85859
|
logger$2.warn("Received query string parameter doesn't match the one sent! Possible malicious activity somewhere.");
|
|
85548
85860
|
throw new ErrorInvalidReturnedStateParam("", { telemetryMessage: "user oauth invalid returned state" });
|
|
85549
85861
|
}
|
|
85862
|
+
if (query.error) throw toErrorClass(Array.isArray(query.error) ? query.error[0] : query.error, Array.isArray(query.error_description) ? query.error_description[0] : query.error_description, Array.isArray(query.error_uri) ? query.error_uri[0] : query.error_uri);
|
|
85863
|
+
const code = query.code;
|
|
85864
|
+
if (!code) return false;
|
|
85550
85865
|
assert(!Array.isArray(code));
|
|
85551
85866
|
state.authorizationCode = code;
|
|
85552
85867
|
state.hasAuthCodeBeenExchangedForAccessToken = false;
|
|
@@ -85761,6 +86076,10 @@ async function getOauthToken(options, state, ctx, generators) {
|
|
|
85761
86076
|
try {
|
|
85762
86077
|
hasAuthCode = isReturningFromAuthServer(query, state, ctx.logger);
|
|
85763
86078
|
} catch (err) {
|
|
86079
|
+
if (err instanceof ErrorInvalidReturnedStateParam) {
|
|
86080
|
+
renderErrorPage({ description: "This callback does not match the pending login. Return to the authorization page to continue." });
|
|
86081
|
+
return;
|
|
86082
|
+
}
|
|
85764
86083
|
if (err instanceof ErrorAccessDenied) {
|
|
85765
86084
|
res.writeHead(307, { Location: options.denied.url });
|
|
85766
86085
|
res.end(() => {
|
|
@@ -85837,13 +86156,13 @@ function getPositiveNumberMember(body, key) {
|
|
|
85837
86156
|
}
|
|
85838
86157
|
__name$1(getPositiveNumberMember, "getPositiveNumberMember");
|
|
85839
86158
|
function describeUnusableResponse(response, body) {
|
|
85840
|
-
const status$
|
|
86159
|
+
const status$1 = `HTTP ${response.status} ${response.statusText}`.trim();
|
|
85841
86160
|
const description = getStringMember(body, "error_description");
|
|
85842
|
-
return description ? `${status$
|
|
86161
|
+
return description ? `${status$1}: ${description}` : status$1;
|
|
85843
86162
|
}
|
|
85844
86163
|
__name$1(describeUnusableResponse, "describeUnusableResponse");
|
|
85845
|
-
function isRetryableStatus(status$
|
|
85846
|
-
return status$
|
|
86164
|
+
function isRetryableStatus(status$1) {
|
|
86165
|
+
return status$1 >= 500 || status$1 === 429;
|
|
85847
86166
|
}
|
|
85848
86167
|
__name$1(isRetryableStatus, "isRetryableStatus");
|
|
85849
86168
|
function asDeviceAuthorizationResponse(body) {
|
|
@@ -86545,12 +86864,12 @@ var FILE_FORMATS = {
|
|
|
86545
86864
|
stringify: /* @__PURE__ */ __name$1((value) => JSON.stringify(value, null, " "), "stringify")
|
|
86546
86865
|
}
|
|
86547
86866
|
};
|
|
86548
|
-
function parseFile(format$
|
|
86549
|
-
return FILE_FORMATS[format$
|
|
86867
|
+
function parseFile(format$3, raw) {
|
|
86868
|
+
return FILE_FORMATS[format$3].parse(raw);
|
|
86550
86869
|
}
|
|
86551
86870
|
__name$1(parseFile, "parseFile");
|
|
86552
|
-
function stringifyFile(format$
|
|
86553
|
-
return FILE_FORMATS[format$
|
|
86871
|
+
function stringifyFile(format$3, value) {
|
|
86872
|
+
return FILE_FORMATS[format$3].stringify(value);
|
|
86554
86873
|
}
|
|
86555
86874
|
__name$1(stringifyFile, "stringifyFile");
|
|
86556
86875
|
var USER_AUTH_CONFIG_PATH = "config";
|
|
@@ -86576,10 +86895,10 @@ var FileCredentialStore = class {
|
|
|
86576
86895
|
* @param format on-disk file format (defaults to TOML for wrangler's
|
|
86577
86896
|
* historical layout; cf and other CLIs pass JSON).
|
|
86578
86897
|
*/
|
|
86579
|
-
constructor(configPath, profile, format$
|
|
86898
|
+
constructor(configPath, profile, format$3 = "toml") {
|
|
86580
86899
|
this.configPath = configPath;
|
|
86581
86900
|
this.profile = profile;
|
|
86582
|
-
this.format = format$
|
|
86901
|
+
this.format = format$3;
|
|
86583
86902
|
}
|
|
86584
86903
|
static {
|
|
86585
86904
|
__name$1(this, "FileCredentialStore");
|
|
@@ -86675,12 +86994,12 @@ var EncryptedFileCredentialStore = class {
|
|
|
86675
86994
|
* @param format on-disk format of the plaintext sibling file and the
|
|
86676
86995
|
* encrypted payload (defaults to TOML for wrangler).
|
|
86677
86996
|
*/
|
|
86678
|
-
constructor(configPath, keyProvider, onPlaintextMigration, profile, format$
|
|
86997
|
+
constructor(configPath, keyProvider, onPlaintextMigration, profile, format$3 = "toml") {
|
|
86679
86998
|
this.configPath = configPath;
|
|
86680
86999
|
this.keyProvider = keyProvider;
|
|
86681
87000
|
this.onPlaintextMigration = onPlaintextMigration;
|
|
86682
87001
|
this.profile = profile;
|
|
86683
|
-
this.format = format$
|
|
87002
|
+
this.format = format$3;
|
|
86684
87003
|
}
|
|
86685
87004
|
static {
|
|
86686
87005
|
__name$1(this, "EncryptedFileCredentialStore");
|
|
@@ -87304,7 +87623,7 @@ var AuthenticationError = class extends UserError {
|
|
|
87304
87623
|
};
|
|
87305
87624
|
|
|
87306
87625
|
//#endregion
|
|
87307
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.
|
|
87626
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.6_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_d34e447d1a00c49a218f49ca1f431b88/node_modules/@cloudflare/workers-auth/dist/chunk-YWQXTXOY.mjs
|
|
87308
87627
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
87309
87628
|
function createPreferences(getConfigPath) {
|
|
87310
87629
|
function getUserPreferencesPath() {
|
|
@@ -87949,14 +88268,14 @@ function formatDistanceToNowStrict(date$2, options) {
|
|
|
87949
88268
|
return formatDistanceStrict(date$2, constructNow(date$2), options);
|
|
87950
88269
|
}
|
|
87951
88270
|
__name$1(formatDistanceToNowStrict, "formatDistanceToNowStrict");
|
|
87952
|
-
function createFileStorage(format$
|
|
88271
|
+
function createFileStorage(format$3, getPath) {
|
|
87953
88272
|
return {
|
|
87954
88273
|
read: /* @__PURE__ */ __name$1(() => {
|
|
87955
88274
|
const filePath = getPath();
|
|
87956
88275
|
if (!existsSync(filePath)) return;
|
|
87957
88276
|
const contents = readFileSync$1(filePath);
|
|
87958
88277
|
try {
|
|
87959
|
-
return parseFile(format$
|
|
88278
|
+
return parseFile(format$3, contents);
|
|
87960
88279
|
} catch {
|
|
87961
88280
|
return;
|
|
87962
88281
|
}
|
|
@@ -87964,7 +88283,7 @@ function createFileStorage(format$4, getPath) {
|
|
|
87964
88283
|
write(config$2) {
|
|
87965
88284
|
const configPath = getPath();
|
|
87966
88285
|
mkdirSync(path__default.dirname(configPath), { recursive: true });
|
|
87967
|
-
writeFileSync(configPath, stringifyFile(format$
|
|
88286
|
+
writeFileSync(configPath, stringifyFile(format$3, config$2), {
|
|
87968
88287
|
encoding: "utf-8",
|
|
87969
88288
|
mode: 384
|
|
87970
88289
|
});
|
|
@@ -88154,12 +88473,12 @@ Run \`${descriptor.commands.whoami}\` to check your current authentication statu
|
|
|
88154
88473
|
while (getMoreResults) {
|
|
88155
88474
|
queryParams = new URLSearchParams$1(queryParams);
|
|
88156
88475
|
queryParams.set("page", String(page));
|
|
88157
|
-
const { response: json$1, status: status$
|
|
88476
|
+
const { response: json$1, status: status$1 } = await fetchInternalBase(complianceConfig, resource, {}, ctx.userAgent, logger$2, queryParams, void 0, credentials);
|
|
88158
88477
|
if (json$1.success) {
|
|
88159
88478
|
results.push(...json$1.result);
|
|
88160
88479
|
if (hasMorePages(json$1.result_info)) page = page + 1;
|
|
88161
88480
|
else getMoreResults = false;
|
|
88162
|
-
} else throwFetchError(resource, json$1, status$
|
|
88481
|
+
} else throwFetchError(resource, json$1, status$1);
|
|
88163
88482
|
}
|
|
88164
88483
|
return results;
|
|
88165
88484
|
}
|
|
@@ -88276,10 +88595,10 @@ __name$1(createCloudflareAuth, "createCloudflareAuth");
|
|
|
88276
88595
|
var DIRECTORY_BINDINGS_FILE = "profiles/directory-bindings.json";
|
|
88277
88596
|
var ENCRYPTED_PROFILE_CONFIG_EXTENSION = ".enc";
|
|
88278
88597
|
function createCloudflareProfileStore(ctx) {
|
|
88279
|
-
const { logger: logger$2, getConfigPath, keyringServiceName, format: format$
|
|
88280
|
-
const plaintextExtension = `.${format$
|
|
88598
|
+
const { logger: logger$2, getConfigPath, keyringServiceName, format: format$3 } = ctx;
|
|
88599
|
+
const plaintextExtension = `.${format$3}`;
|
|
88281
88600
|
function plaintextPath(profile) {
|
|
88282
|
-
return getAuthConfigFilePath$2(getConfigPath(), profile, format$
|
|
88601
|
+
return getAuthConfigFilePath$2(getConfigPath(), profile, format$3);
|
|
88283
88602
|
}
|
|
88284
88603
|
__name$1(plaintextPath, "plaintextPath");
|
|
88285
88604
|
function encryptedPath(profile) {
|
|
@@ -88307,9 +88626,9 @@ function createCloudflareProfileStore(ctx) {
|
|
|
88307
88626
|
serviceName: keyringServiceName,
|
|
88308
88627
|
configPath: getConfigPath(),
|
|
88309
88628
|
profile,
|
|
88310
|
-
format: format$
|
|
88629
|
+
format: format$3
|
|
88311
88630
|
});
|
|
88312
|
-
createFileStorage(format$
|
|
88631
|
+
createFileStorage(format$3, () => plaintextPath(profile)).clear();
|
|
88313
88632
|
if (encryptedFileExisted && !backendAvailable) logger$2.warn(`Removed the credential files for profile "${profile}", but the keyring backend was not reachable on this host so its keyring entry could not be cleared. Clear it manually if it persists.`);
|
|
88314
88633
|
}
|
|
88315
88634
|
};
|
|
@@ -88338,7 +88657,7 @@ function createCloudflareProfileStore(ctx) {
|
|
|
88338
88657
|
}
|
|
88339
88658
|
__name$1(createCloudflareProfileStore, "createCloudflareProfileStore");
|
|
88340
88659
|
function createKeyringPreference(deps) {
|
|
88341
|
-
const { loginCommand, createProfileCommand, keyringServiceName, getConfigPath, format: format$
|
|
88660
|
+
const { loginCommand, createProfileCommand, keyringServiceName, getConfigPath, format: format$3, preferences } = deps;
|
|
88342
88661
|
const { readUserPreferences: readUserPreferences$2, updateUserPreferences: updateUserPreferences$2 } = preferences;
|
|
88343
88662
|
function describeProfile(profile) {
|
|
88344
88663
|
return profile ?? "default";
|
|
@@ -88351,7 +88670,7 @@ function createKeyringPreference(deps) {
|
|
|
88351
88670
|
logger: logger$2,
|
|
88352
88671
|
getConfigPath,
|
|
88353
88672
|
keyringServiceName,
|
|
88354
|
-
format: format$
|
|
88673
|
+
format: format$3
|
|
88355
88674
|
});
|
|
88356
88675
|
for (const name of profileStore.configs.list()) {
|
|
88357
88676
|
try {
|
|
@@ -88374,7 +88693,7 @@ function createKeyringPreference(deps) {
|
|
|
88374
88693
|
serviceName: keyringServiceName,
|
|
88375
88694
|
configPath: getConfigPath(),
|
|
88376
88695
|
profile,
|
|
88377
|
-
format: format$
|
|
88696
|
+
format: format$3
|
|
88378
88697
|
});
|
|
88379
88698
|
cleared.push(describeProfile(profile));
|
|
88380
88699
|
if (!backendAvailable) unreachable.push(describeProfile(profile));
|
|
@@ -88411,9 +88730,9 @@ function createKeyringPreference(deps) {
|
|
|
88411
88730
|
}
|
|
88412
88731
|
__name$1(createKeyringPreference, "createKeyringPreference");
|
|
88413
88732
|
function createAuthConfigFileHelpers(deps) {
|
|
88414
|
-
const { getConfigPath, format: format$
|
|
88733
|
+
const { getConfigPath, format: format$3 } = deps;
|
|
88415
88734
|
function getAuthConfigFilePath2(profile) {
|
|
88416
|
-
return getAuthConfigFilePath$2(getConfigPath(), profile, format$
|
|
88735
|
+
return getAuthConfigFilePath$2(getConfigPath(), profile, format$3);
|
|
88417
88736
|
}
|
|
88418
88737
|
__name$1(getAuthConfigFilePath2, "getAuthConfigFilePath");
|
|
88419
88738
|
function getEncryptedAuthConfigFilePath2(profile) {
|
|
@@ -88421,7 +88740,7 @@ function createAuthConfigFileHelpers(deps) {
|
|
|
88421
88740
|
}
|
|
88422
88741
|
__name$1(getEncryptedAuthConfigFilePath2, "getEncryptedAuthConfigFilePath");
|
|
88423
88742
|
function defaultAuthConfigStorage$2(profile) {
|
|
88424
|
-
return createFileStorage(format$
|
|
88743
|
+
return createFileStorage(format$3, () => getAuthConfigFilePath2(profile));
|
|
88425
88744
|
}
|
|
88426
88745
|
__name$1(defaultAuthConfigStorage$2, "defaultAuthConfigStorage");
|
|
88427
88746
|
function writeAuthConfigFile$2(config$2, profile) {
|
|
@@ -88443,7 +88762,7 @@ function createAuthConfigFileHelpers(deps) {
|
|
|
88443
88762
|
__name$1(createAuthConfigFileHelpers, "createAuthConfigFileHelpers");
|
|
88444
88763
|
|
|
88445
88764
|
//#endregion
|
|
88446
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.
|
|
88765
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.6_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_d34e447d1a00c49a218f49ca1f431b88/node_modules/@cloudflare/workers-auth/dist/cf/index.mjs
|
|
88447
88766
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
88448
88767
|
var CF_KEYRING_SERVICE_NAME = "cloudflare";
|
|
88449
88768
|
var CF_CLI_NAME = "cf";
|
|
@@ -88894,6 +89213,7 @@ var CF_CLIENT_REGISTERED_SCOPES = [
|
|
|
88894
89213
|
"trust-and-safety.write",
|
|
88895
89214
|
"url-scanner.read",
|
|
88896
89215
|
"url-scanner.write",
|
|
89216
|
+
"user-api-tokens.write",
|
|
88897
89217
|
"user-details.read",
|
|
88898
89218
|
"user-details.write",
|
|
88899
89219
|
"vectorize.read",
|
|
@@ -89045,7 +89365,7 @@ function setKeyringPreference$1(enabled, ctx) {
|
|
|
89045
89365
|
__name$1(setKeyringPreference$1, "setKeyringPreference");
|
|
89046
89366
|
|
|
89047
89367
|
//#endregion
|
|
89048
|
-
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.
|
|
89368
|
+
//#region ../../node_modules/.pnpm/@cloudflare+workers-auth@0.15.6_msw@2.14.6_@types+node@22.15.17_typescript@5.8.3__vites_d34e447d1a00c49a218f49ca1f431b88/node_modules/@cloudflare/workers-auth/dist/wrangler/index.mjs
|
|
89049
89369
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
89050
89370
|
var DefaultScopes = {
|
|
89051
89371
|
"k2.read": "See K2 stream configurations and bind existing streams to Workers.",
|
|
@@ -89171,7 +89491,7 @@ function setKeyringPreference(enabled, ctx) {
|
|
|
89171
89491
|
__name$1(setKeyringPreference, "setKeyringPreference");
|
|
89172
89492
|
|
|
89173
89493
|
//#endregion
|
|
89174
|
-
//#region ../../node_modules/.pnpm/@cloudflare+deploy-helpers@0.
|
|
89494
|
+
//#region ../../node_modules/.pnpm/@cloudflare+deploy-helpers@0.25.0_@types+node@22.15.17_vitest@5.0.4_@opentelemetry+api@_f19aaff9d416abecc773a4c7d1252537/node_modules/@cloudflare/deploy-helpers/dist/chunk-U6NEESU5.mjs
|
|
89175
89495
|
const require$1 = createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
89176
89496
|
var __defProp = Object.defineProperty;
|
|
89177
89497
|
var __name = (target$1, value) => __defProp(target$1, "name", {
|
|
@@ -89219,8 +89539,8 @@ var require_command_exists$1 = /* @__PURE__ */ __commonJS$2({ "../../node_module
|
|
|
89219
89539
|
var commandExistsUnix = function(commandName, cleanedCommandName, callback$1) {
|
|
89220
89540
|
fileNotExists(commandName, function(isFile) {
|
|
89221
89541
|
if (!isFile) {
|
|
89222
|
-
exec("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }", function(error$3, stdout$
|
|
89223
|
-
callback$1(null, !!stdout$
|
|
89542
|
+
exec("command -v " + cleanedCommandName + " 2>/dev/null && { echo >&1 " + cleanedCommandName + "; exit 0; }", function(error$3, stdout$2, stderr$1) {
|
|
89543
|
+
callback$1(null, !!stdout$2);
|
|
89224
89544
|
});
|
|
89225
89545
|
return;
|
|
89226
89546
|
}
|
|
@@ -89293,7 +89613,7 @@ var require_command_exists = /* @__PURE__ */ __commonJS$2({ "../../node_modules/
|
|
|
89293
89613
|
}) });
|
|
89294
89614
|
|
|
89295
89615
|
//#endregion
|
|
89296
|
-
//#region ../../node_modules/.pnpm/@cloudflare+deploy-helpers@0.
|
|
89616
|
+
//#region ../../node_modules/.pnpm/@cloudflare+deploy-helpers@0.25.0_@types+node@22.15.17_vitest@5.0.4_@opentelemetry+api@_f19aaff9d416abecc773a4c7d1252537/node_modules/@cloudflare/deploy-helpers/dist/chunk-DSGVRFIS.mjs
|
|
89297
89617
|
var import_undici$1 = require_undici();
|
|
89298
89618
|
var import_command_exists = require_command_exists();
|
|
89299
89619
|
createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
|
|
@@ -89914,7 +90234,7 @@ function getRemoteBindingsAuthHook(auth, accountId, profileDir, logger$1$1) {
|
|
|
89914
90234
|
apiToken: remoteBindingsAuth.requireApiToken()
|
|
89915
90235
|
});
|
|
89916
90236
|
}
|
|
89917
|
-
var ProxyServerWorker_default = "// ../../node_modules/.pnpm/capnweb@0.12.0/node_modules/capnweb/dist/index-workers.js\nimport * as cfw from \"cloudflare:workers\";\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol(\"workers-module\");\nglobalThis[WORKERS_MODULE_SYMBOL] = cfw;\nif (!Symbol.dispose) Symbol.dispose = /* @__PURE__ */ Symbol.for(\"dispose\");\nif (!Symbol.asyncDispose) Symbol.asyncDispose = /* @__PURE__ */ Symbol.for(\"asyncDispose\");\nif (!Promise.withResolvers) Promise.withResolvers = function() {\n let resolve;\n let reject;\n return {\n promise: new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve,\n reject\n };\n};\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget$1 = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nvar BUFFER_PROTOTYPE = typeof Buffer !== \"undefined\" ? Buffer.prototype : void 0;\nfunction typeForRpc(value) {\n switch (typeof value) {\n case \"boolean\":\n case \"number\":\n case \"string\":\n return \"primitive\";\n case \"undefined\":\n return \"undefined\";\n case \"object\":\n case \"function\":\n break;\n case \"bigint\":\n return \"bigint\";\n default:\n return \"unsupported\";\n }\n if (value === null) return \"primitive\";\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return \"object\";\n case Function.prototype:\n case AsyncFunction.prototype:\n return \"function\";\n case Array.prototype:\n return \"array\";\n case Date.prototype:\n return \"date\";\n case Uint8Array.prototype:\n case BUFFER_PROTOTYPE:\n case ArrayBuffer.prototype:\n case DataView.prototype:\n case Int8Array.prototype:\n case Uint8ClampedArray.prototype:\n case Int16Array.prototype:\n case Uint16Array.prototype:\n case Int32Array.prototype:\n case Uint32Array.prototype:\n case BigInt64Array.prototype:\n case BigUint64Array.prototype:\n case Float32Array.prototype:\n case Float64Array.prototype:\n return \"bytes\";\n case WritableStream.prototype:\n return \"writable\";\n case ReadableStream.prototype:\n return \"readable\";\n case URL.prototype:\n return \"url\";\n case Headers.prototype:\n return \"headers\";\n case Request.prototype:\n return \"request\";\n case Response.prototype:\n return \"response\";\n case Blob.prototype:\n return \"blob\";\n case RpcStub$1.prototype:\n return \"stub\";\n case RpcPromise$1.prototype:\n return \"rpc-promise\";\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) return \"rpc-target\";\n else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) return \"rpc-thenable\";\n }\n if (value instanceof RpcTarget$1) return \"rpc-target\";\n if (value instanceof Error) return \"error\";\n return \"unsupported\";\n }\n}\nfunction mapNotLoaded() {\n throw new Error(\"RPC map() implementation was not loaded.\");\n}\nvar mapImpl = {\n applyMap: mapNotLoaded,\n sendMap: mapNotLoaded\n};\nfunction streamNotLoaded() {\n throw new Error(\"Stream implementation was not loaded.\");\n}\nvar streamImpl = {\n createWritableStreamHook: streamNotLoaded,\n createWritableStreamFromHook: streamNotLoaded,\n createReadableStreamHook: streamNotLoaded\n};\nvar StubHook = class {\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled;\n try {\n pulled = hook.pull();\n } catch (err) {\n hook.dispose();\n throw err;\n }\n let promise;\n if (pulled instanceof Promise) promise = pulled.then((p) => {\n p.dispose();\n });\n else {\n pulled.dispose();\n promise = Promise.resolve();\n }\n return { promise };\n }\n};\nvar ErrorStubHook = class extends StubHook {\n error;\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n args.dispose();\n return this;\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(/* @__PURE__ */ new Error(\"Attempted to use RPC stub after it has been disposed.\"));\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol(\"realStub\");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise$1(doCall(stub.hook, stub.pathIfPromise || [], RpcPayload.fromAppParams(argumentsList)), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) return stub;\n else if (prop in RpcPromise$1.prototype) return stub[prop];\n else if (typeof prop === \"string\") return new RpcPromise$1(stub.hook, stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]);\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n else return;\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) return true;\n else if (prop in RpcPromise$1.prototype) return prop in stub;\n else if (typeof prop === \"string\") return true;\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return true;\n else return false;\n },\n construct(target, args) {\n throw new Error(\"An RPC stub cannot be used as a constructor.\");\n },\n defineProperty(target, property, attributes) {\n throw new Error(\"Can't define properties on RPC stubs.\");\n },\n deleteProperty(target, p) {\n throw new Error(\"Can't delete properties on RPC stubs.\");\n },\n getOwnPropertyDescriptor(target, p) {\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error(\"Can't assign properties on RPC stubs.\");\n },\n setPrototypeOf(target, v) {\n throw new Error(\"Can't override prototype of RPC stubs.\");\n }\n};\nvar RpcStub$1 = class RpcStub$12 extends RpcTarget$1 {\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget$1 || value instanceof Function) hook = TargetStubHook.create(value, void 0);\n else hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n if (pathIfPromise) throw new TypeError(\"RpcStub constructor expected one argument, received two.\");\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) return new RpcStub$12(target.hook.get(target.pathIfPromise));\n else return new RpcStub$12(target.hook.dup());\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return \"[object RpcStub]\";\n }\n};\nvar RpcPromise$1 = class extends RpcStub$1 {\n constructor(hook, pathIfPromise) {\n if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);\n else {\n if (pathIfPromise !== void 0) throw new TypeError(\"RpcPromise constructor expected one argument, received two.\");\n let kind = typeForRpc(hook);\n if (kind === \"rpc-promise\") {\n let raw = unwrapStubAndPath(hook);\n if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);\n else {\n let adopted = raw.hook;\n raw.hook = DISPOSED_HOOK;\n super(adopted, []);\n }\n } else if (kind === \"rpc-thenable\") super(TargetStubHook.create(hook, void 0), []);\n else {\n let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));\n promiseHook.ignoreUnhandledRejections();\n super(promiseHook, []);\n }\n }\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return \"[object RpcPromise]\";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return hook.get(pathIfPromise);\n else return hook;\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) return hook.get(pathIfPromise);\n else return hook.dup();\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return;\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);\n return (await hook.pull()).deliverResolve();\n}\nvar RpcPayload = class RpcPayload2 {\n value;\n source;\n hooks;\n promises;\n static fromAppParams(value) {\n return new RpcPayload2(value, \"params\");\n }\n static fromAppReturn(value) {\n return new RpcPayload2(value, \"return\");\n }\n static fromArray(array) {\n let hooks = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let hook of payload.hooks) hooks.push(hook);\n for (let promise of payload.promises) {\n if (promise.parent === payload) promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new RpcPayload2(resultArray, \"owned\", hooks, promises);\n }\n static forEvaluate(hooks, promises) {\n return new RpcPayload2(null, \"owned\", hooks, promises);\n }\n static deepCopyFrom(value, oldParent, owner) {\n let result = new RpcPayload2(null, \"owned\", [], []);\n result.value = result.deepCopy(value, oldParent, \"value\", result, true, owner);\n return result;\n }\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n rpcTargets;\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === \"params\") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === \"function\") target = dupable.dup();\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(target);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw RpcTargets\");\n }\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createWritableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createWritableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw WritableStreams\");\n }\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createReadableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createReadableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw ReadableStreams\");\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n return value;\n case \"primitive\":\n case \"bigint\":\n case \"date\":\n case \"bytes\":\n case \"blob\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return value;\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n return result;\n }\n case \"object\": {\n let result = {};\n let object = value;\n for (let i in object) result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n return result;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook;\n if (dupStubs) hook = unwrapStubAndDup(stub);\n else hook = unwrapStubTakingOwnership(stub);\n if (stub instanceof RpcPromise$1) {\n let promise = new RpcPromise$1(hook, []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook;\n if (owner) hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n else hook = TargetStubHook.create(target, oldParent);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n case \"rpc-thenable\": {\n let target = value;\n let promise;\n if (owner) promise = new RpcPromise$1(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n else promise = new RpcPromise$1(TargetStubHook.create(target, oldParent), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n }\n case \"writable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createWritableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"readable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"headers\":\n return new Headers(value);\n case \"request\": {\n let req = value;\n if (req.body) this.deepCopy(req.body, req, \"body\", req, dupStubs, owner);\n return new Request(req);\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.deepCopy(resp.body, resp, \"body\", resp, dupStubs, owner);\n return new Response(resp.body, resp);\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n ensureDeepCopied() {\n if (this.source !== \"owned\") {\n let dupStubs = this.source === \"params\";\n this.hooks = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, \"value\", this, dupStubs, this);\n } catch (err) {\n this.hooks = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = \"owned\";\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in deep-copy?\");\n this.rpcTargets = void 0;\n }\n }\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise$1) RpcPayload2.deliverRpcPromiseTo(this.value, parent, property, promises);\n else {\n parent[property] = this.value;\n for (let record of this.promises) RpcPayload2.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) throw new Error(\"property promises should have been resolved earlier\");\n let inner = hook.pull();\n if (inner instanceof RpcPayload2) inner.deliverTo(parent, property, promises);\n else promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) return Promise.all(subPromises);\n }));\n }\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise$1) return RpcPayload2.fromAppReturn(result);\n else return RpcPayload2.fromAppReturn(await result);\n } finally {\n this.dispose();\n }\n }\n async deliverStreamWrite(writer) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let chunk = this.value[0];\n if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {\n if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n await writer.write(chunk);\n return RpcPayload2.fromAppReturn(void 0);\n }\n await writer.write(chunk);\n this.dispose();\n return RpcPayload2.fromAppReturn(void 0);\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) Object.defineProperty(result, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === \"owned\") {\n this.hooks.forEach((hook) => hook.dispose());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === \"return\") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in disposeImpl()?\");\n }\n this.source = \"owned\";\n this.hooks = [];\n this.promises = [];\n }\n disposeImpl(value, parent) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.disposeImpl(object[i], object);\n return;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let hook = unwrapStubNoProperties(value);\n if (hook) hook.dispose();\n return;\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else disposeRpcTarget(target);\n return;\n }\n case \"rpc-thenable\":\n return;\n case \"headers\":\n return;\n case \"request\": {\n let req = value;\n if (req.body) this.disposeImpl(req.body, req);\n return;\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.disposeImpl(resp.body, resp);\n return;\n }\n case \"writable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createWritableStreamHook(stream);\n hook.dispose();\n return;\n }\n case \"readable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createReadableStreamHook(stream);\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach((promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections());\n } else this.ignoreUnhandledRejectionsImpl(this.value);\n }\n ignoreUnhandledRejectionsImpl(value) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"undefined\":\n case \"function\":\n case \"rpc-target\":\n case \"writable\":\n case \"readable\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);\n return;\n }\n case \"stub\":\n case \"rpc-promise\":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case \"rpc-thenable\":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n switch (typeForRpc(value)) {\n case \"object\":\n case \"function\":\n if (Object.hasOwn(value, part)) value = value[part];\n else value = void 0;\n break;\n case \"array\":\n if (Number.isInteger(part) && part >= 0) value = value[part];\n else value = void 0;\n break;\n case \"rpc-target\":\n case \"rpc-thenable\":\n if (Object.hasOwn(value, part)) throw new TypeError(`Attempted to access property '${part}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);\n else value = value[part];\n owner = null;\n break;\n case \"stub\":\n case \"rpc-promise\": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i)\n };\n }\n case \"writable\":\n value = void 0;\n break;\n case \"readable\":\n value = void 0;\n break;\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n value = void 0;\n break;\n case \"undefined\":\n value = value[part];\n break;\n case \"unsupported\":\n if (i === 0) throw new TypeError(`RPC stub points at a non-serializable type.`);\n else {\n let prefix = path.slice(0, i).join(\".\");\n let remainder = path.slice(0, i).join(\".\");\n throw new TypeError(`'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`);\n }\n default:\n throw new TypeError(\"unreachable\");\n }\n }\n if (value instanceof RpcPromise$1) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise || []\n };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);\n if (typeof followResult.value != \"function\") {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(\".\")}' is not a function.`));\n }\n return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {\n return new PayloadStubHook(payload);\n }));\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n for (let cap of captures) cap.dispose();\n throw err;\n }\n if (followResult.hook) return followResult.hook.map(followResult.remainingPath, captures, instructions);\n return mapImpl.applyMap(followResult.value, followResult.parent, followResult.owner, captures, instructions);\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n if (value instanceof Object && \"then\" in value) return this.dup();\n throw new Error(\"Can't dup an RpcTarget stub as a promise.\");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) return followResult.hook.get(followResult.remainingPath);\n return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class PayloadStubHook2 extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n getPayload() {\n if (this.payload) return this.payload;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n let payload = this.getPayload();\n return {\n value: payload.value,\n owner: payload\n };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new PayloadStubHook2(RpcPayload.deepCopyFrom(thisPayload.value, void 0, thisPayload));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) this.payload.ignoreUnhandledRejections();\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub$1) this.payload.value.onRpcBroken(callback);\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n}\nvar TargetStubHook = class TargetStubHook2 extends ValueStubHook {\n static create(value, parent) {\n if (typeof value !== \"function\") parent = void 0;\n return new TargetStubHook2(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) this.refcount = { count: 1 };\n }\n target;\n parent;\n refcount;\n getTarget() {\n if (this.target) return this.target;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n return {\n value: this.getTarget(),\n owner: null\n };\n }\n dup() {\n return new TargetStubHook2(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if (\"then\" in target) return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n else return Promise.reject(/* @__PURE__ */ new Error(\"Tried to resolve a non-promise stub.\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) disposeRpcTarget(this.target);\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n let target = this.target;\n if (target && \"then\" in target) Promise.resolve(target).then(() => {\n }, callback);\n }\n};\nvar PromiseStubHook = class PromiseStubHook2 extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new PromiseStubHook2(this.promise.then((hook) => hook.call(path, args), (err) => {\n args.dispose();\n throw err;\n }));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {\n args.dispose();\n throw err;\n }) };\n }\n map(path, captures, instructions) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.map(path, captures, instructions), (err) => {\n for (let cap of captures) cap.dispose();\n throw err;\n }));\n }\n get(path) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) return this.resolution.dup();\n else return new PromiseStubHook2(this.promise.then((hook) => hook.dup()));\n }\n pull() {\n if (this.resolution) return this.resolution.pull();\n else return this.promise.then((hook) => hook.pull());\n }\n ignoreUnhandledRejections() {\n if (this.resolution) this.resolution.ignoreUnhandledRejections();\n else this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n dispose() {\n this.promise.then((hook) => hook.dispose(), () => {\n });\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n};\nvar DEFAULT_LIMITS = {\n maxBigIntDigits: 16384,\n maxDepth: 256,\n maxMessageSize: 32 * 1024 * 1024\n};\nvar NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\nvar BYTE_CONTAINER_TYPE_NAMES = [\n \"ArrayBuffer\",\n \"DataView\",\n \"Int8Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"Int16Array\",\n \"Uint16Array\",\n \"Int32Array\",\n \"Uint32Array\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Float32Array\",\n \"Float64Array\"\n];\nfunction isValidByteContainerName(value) {\n return BYTE_CONTAINER_TYPE_NAMES.includes(value);\n}\nvar TYPED_ARRAY_ELEMENT_SIZE = {\n ArrayBuffer: void 0,\n DataView: void 0,\n Int8Array: void 0,\n Uint8Array: void 0,\n Uint8ClampedArray: void 0,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n BigInt64Array: 8,\n BigUint64Array: 8,\n Float32Array: 4,\n Float64Array: 8\n};\nvar BYTE_CONTAINER_PROTOTYPES = {\n ArrayBuffer: ArrayBuffer.prototype,\n DataView: DataView.prototype,\n Int8Array: Int8Array.prototype,\n Uint8ClampedArray: Uint8ClampedArray.prototype,\n Int16Array: Int16Array.prototype,\n Uint16Array: Uint16Array.prototype,\n Int32Array: Int32Array.prototype,\n Uint32Array: Uint32Array.prototype,\n BigInt64Array: BigInt64Array.prototype,\n BigUint64Array: BigUint64Array.prototype,\n Float32Array: Float32Array.prototype,\n Float64Array: Float64Array.prototype\n};\nvar BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();\nfor (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);\nfunction swapByteOrder(bytes, elementSize) {\n if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);\n let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {\n case 2:\n view.setUint16(offset, view.getUint16(offset, false), true);\n break;\n case 4:\n view.setUint32(offset, view.getUint32(offset, false), true);\n break;\n case 8:\n view.setBigUint64(offset, view.getBigUint64(offset, false), true);\n break;\n }\n}\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n exportPromise(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n getImport(hook) {\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot create pipes without an RPC session.\");\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nasync function streamToBlob(stream, type) {\n let b = await new Response(stream).blob();\n return b.type === type ? b : b.slice(0, b.size, type);\n}\nvar ERROR_TYPES = {\n __proto__: null,\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n};\nvar Devaluator = class Devaluator2 {\n exporter;\n source;\n encodingLevel;\n constructor(exporter, source, encodingLevel) {\n this.exporter = exporter;\n this.source = source;\n this.encodingLevel = encodingLevel;\n }\n static devaluate(value, parent, exporter = NULL_EXPORTER, source, encodingLevel = \"string\") {\n let devaluator = new Devaluator2(exporter, source, encodingLevel);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 256) throw new Error(\"Serialization exceeded maximum allowed depth. (Does the message contain cycles?)\");\n switch (typeForRpc(value)) {\n case \"unsupported\": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = \"Cannot serialize value: (couldn't stringify value)\";\n }\n throw new TypeError(msg);\n }\n case \"primitive\":\n if (typeof value === \"number\" && !isFinite(value)) {\n if (this.encodingLevel === \"structuredClonable\") return value;\n if (value === Infinity) return [\"inf\"];\n else if (value === -Infinity) return [\"-inf\"];\n else return [\"nan\"];\n } else return value;\n case \"object\": {\n let object = value;\n let result = {};\n for (let key in object) result[key] = this.devaluateImpl(object[key], object, depth + 1);\n return result;\n }\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);\n return [result];\n }\n case \"bigint\":\n if (this.encodingLevel === \"structuredClonable\") return value;\n return [\"bigint\", value.toString()];\n case \"date\": {\n if (this.encodingLevel === \"structuredClonable\") return value;\n const time = value.getTime();\n return [\"date\", Number.isNaN(time) ? null : time];\n }\n case \"bytes\": {\n let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));\n let bytes;\n if (alternateTypeName === \"ArrayBuffer\") bytes = new Uint8Array(value);\n else if (alternateTypeName === void 0) bytes = value;\n else {\n let view = value;\n bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];\n if (!NATIVE_LITTLE_ENDIAN && elementSize) {\n bytes = bytes.slice();\n swapByteOrder(bytes, elementSize);\n }\n }\n if (this.encodingLevel === \"structuredClonable\" || this.encodingLevel === \"jsonCompatibleWithBytes\") return alternateTypeName === void 0 ? [\"bytes\", bytes] : [\n \"bytes\",\n bytes,\n alternateTypeName\n ];\n let b64;\n if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });\n else if (typeof Buffer !== \"undefined\") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString(\"base64\");\n else {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);\n b64 = btoa(binary);\n }\n b64 = b64.replace(/=+$/, \"\");\n return alternateTypeName === void 0 ? [\"bytes\", b64] : [\n \"bytes\",\n b64,\n alternateTypeName\n ];\n }\n case \"url\":\n return [\"url\", value.href];\n case \"headers\":\n return [\"headers\", [...value]];\n case \"request\": {\n let req = value;\n let init = {};\n if (req.method !== \"GET\") init.method = req.method;\n let headers = [...req.headers];\n if (headers.length > 0) init.headers = headers;\n if (req.body) {\n init.body = this.devaluateImpl(req.body, req, depth + 1);\n init.duplex = req.duplex || \"half\";\n } else if (req.body === void 0 && ![\n \"GET\",\n \"HEAD\",\n \"OPTIONS\",\n \"TRACE\",\n \"DELETE\"\n ].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({ async start(controller) {\n try {\n controller.enqueue(new Uint8Array(await bodyPromise));\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n } });\n let hook = streamImpl.createReadableStreamHook(readable);\n init.body = [\"readable\", this.exporter.createPipe(readable, hook)];\n init.duplex = req.duplex || \"half\";\n }\n if (req.cache && req.cache !== \"default\") init.cache = req.cache;\n if (req.redirect !== \"follow\") init.redirect = req.redirect;\n if (req.integrity) init.integrity = req.integrity;\n if (req.mode && req.mode !== \"cors\") init.mode = req.mode;\n if (req.credentials && req.credentials !== \"same-origin\") init.credentials = req.credentials;\n if (req.referrer && req.referrer !== \"about:client\") init.referrer = req.referrer;\n if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;\n if (req.keepalive) init.keepalive = req.keepalive;\n let cfReq = req;\n if (cfReq.cf) init.cf = cfReq.cf;\n if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== \"automatic\") init.encodeResponseBody = cfReq.encodeResponseBody;\n return [\n \"request\",\n req.url,\n init\n ];\n }\n case \"response\": {\n let resp = value;\n let body = this.devaluateImpl(resp.body, resp, depth + 1);\n let init = {};\n if (resp.status !== 200) init.status = resp.status;\n if (resp.statusText) init.statusText = resp.statusText;\n let headers = [...resp.headers];\n if (headers.length > 0) init.headers = headers;\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== \"automatic\") init.encodeBody = cfResp.encodeBody;\n if (cfResp.webSocket) throw new TypeError(\"Can't serialize a Response containing a webSocket.\");\n return [\n \"response\",\n body,\n init\n ];\n }\n case \"blob\": {\n let blob = value;\n let readable = blob.stream();\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n return [\n \"blob\",\n blob.type,\n [\"readable\", importId]\n ];\n }\n case \"error\": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) e = rewritten;\n let anyE = e;\n let props;\n let captureProp = (key, val) => {\n let exportsBefore = this.exports?.length ?? 0;\n try {\n let encoded = this.devaluateImpl(val, e, depth + 1);\n if (!props) props = {};\n props[key] = encoded;\n } catch (err) {\n if (this.exports && this.exports.length > exportsBefore) {\n let tail = this.exports.splice(exportsBefore);\n try {\n this.exporter.unexport(tail);\n } catch (err2) {\n }\n }\n }\n };\n for (let key of Object.keys(e)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n captureProp(key, anyE[key]);\n }\n if (\"cause\" in e) captureProp(\"cause\", anyE.cause);\n if (e instanceof AggregateError) captureProp(\"errors\", e.errors);\n let result = [\n \"error\",\n e.name,\n e.message\n ];\n if (props) {\n result.push(rewritten && rewritten.stack ? rewritten.stack : null);\n result.push(props);\n } else if (rewritten && rewritten.stack) result.push(rewritten.stack);\n return result;\n }\n case \"undefined\":\n if (this.encodingLevel === \"structuredClonable\") return;\n return [\"undefined\"];\n case \"stub\":\n case \"rpc-promise\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [\n \"pipeline\",\n importId,\n pathIfPromise\n ];\n else return [\"pipeline\", importId];\n else return [\"import\", importId];\n if (pathIfPromise) hook = hook.get(pathIfPromise);\n else hook = hook.dup();\n return this.devaluateHook(pathIfPromise ? \"promise\" : \"export\", hook);\n }\n case \"function\":\n case \"rpc-target\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"export\", hook);\n }\n case \"rpc-thenable\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"promise\", hook);\n }\n case \"writable\": {\n if (!this.source) throw new Error(\"Can't serialize WritableStream in this context.\");\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook(\"writable\", hook);\n }\n case \"readable\": {\n if (!this.source) throw new Error(\"Can't serialize ReadableStream in this context.\");\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n return [\"readable\", this.exporter.createPipe(ws, hook)];\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === \"promise\" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n importPromise(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n getExport(idx) {\n }\n getPipeReadable(exportId) {\n throw new Error(\"Cannot retrieve pipe readable without an RPC session.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {\n let bytes = new Uint8Array(arrayBuffer);\n let result = new Request(request, { body: bytes });\n return new PayloadStubHook(RpcPayload.fromAppReturn(result));\n })), []);\n}\nfunction streamToBlobPromise(stream, type) {\n return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {\n return new PayloadStubHook(RpcPayload.fromAppReturn(blob));\n })), []);\n}\nvar Evaluator = class Evaluator2 {\n importer;\n encodingLevel;\n limits;\n constructor(importer, encodingLevel = \"string\") {\n this.importer = importer;\n this.encodingLevel = encodingLevel;\n this.limits = importer.getLimits();\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n return this.evaluateWithDepth(value, 0);\n }\n evaluateWithDepth(value, depth) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, \"value\", depth);\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property, depth) {\n let maxDepth = this.limits.maxDepth;\n if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);\n if (this.encodingLevel === \"structuredClonable\") {\n if (value instanceof Date || typeof value === \"bigint\") return value;\n }\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);\n return result;\n } else switch (value[0]) {\n case \"bigint\":\n if (typeof value[1] == \"string\") {\n let digits = value[1];\n let maxBigIntDigits = this.limits.maxBigIntDigits;\n if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);\n return BigInt(digits);\n }\n break;\n case \"date\":\n if (value[1] === null) return /* @__PURE__ */ new Date(NaN);\n if (typeof value[1] == \"number\") return new Date(value[1]);\n break;\n case \"bytes\": {\n let bytes;\n if (value[1] instanceof Uint8Array) bytes = value[1];\n else if (typeof value[1] == \"string\") if (typeof Buffer !== \"undefined\") bytes = Buffer.from(value[1], \"base64\");\n else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);\n else {\n let bs = atob(value[1]);\n let len = bs.length;\n bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);\n }\n else break;\n if (value.length === 2) return bytes;\n if (typeof value[2] !== \"string\") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);\n if (!isValidByteContainerName(value[2])) {\n let marker2 = value[2].slice(0, 64);\n throw new TypeError(`Unknown bytes type marker: ${marker2}`);\n }\n let marker = value[2];\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];\n if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);\n let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);\n switch (marker) {\n case \"ArrayBuffer\":\n return buffer;\n case \"DataView\":\n return new DataView(buffer);\n case \"Int8Array\":\n return new Int8Array(buffer);\n case \"Uint8Array\":\n return new Uint8Array(buffer);\n case \"Uint8ClampedArray\":\n return new Uint8ClampedArray(buffer);\n case \"Int16Array\":\n return new Int16Array(buffer);\n case \"Uint16Array\":\n return new Uint16Array(buffer);\n case \"Int32Array\":\n return new Int32Array(buffer);\n case \"Uint32Array\":\n return new Uint32Array(buffer);\n case \"BigInt64Array\":\n return new BigInt64Array(buffer);\n case \"BigUint64Array\":\n return new BigUint64Array(buffer);\n case \"Float32Array\":\n return new Float32Array(buffer);\n case \"Float64Array\":\n return new Float64Array(buffer);\n default:\n }\n }\n case \"error\":\n if (value.length >= 3 && typeof value[1] === \"string\" && typeof value[2] === \"string\") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = cls === AggregateError ? new cls([], value[2]) : new cls(value[2]);\n if (typeof value[3] === \"string\") result.stack = value[3];\n if (value.length >= 5) {\n let props = value[4];\n if (!props || typeof props !== \"object\" || Array.isArray(props)) break;\n let anyResult = result;\n let propsObj = props;\n for (let key of Object.keys(propsObj)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(propsObj[key], result, key, depth + 1);\n continue;\n }\n anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);\n }\n }\n return result;\n }\n break;\n case \"undefined\":\n if (value.length === 1) return;\n break;\n case \"inf\":\n return Infinity;\n case \"-inf\":\n return -Infinity;\n case \"nan\":\n return NaN;\n case \"url\":\n if (value.length === 2 && typeof value[1] === \"string\") return new URL(value[1]);\n break;\n case \"headers\":\n if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);\n break;\n case \"request\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let url = value[1];\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.body) {\n init.body = this.evaluateImpl(init.body, init, \"body\", depth + 1);\n if (init.body === null || typeof init.body === \"string\" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) {\n } else throw new TypeError(\"Request body must be of type ReadableStream.\");\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, \"signal\", depth + 1);\n if (!(init.signal instanceof AbortSignal)) throw new TypeError(\"Request siganl must be of type AbortSignal.\");\n }\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n let result = new Request(url, init);\n if (init.body instanceof ReadableStream && result.body === void 0) {\n let promise = fixBrokenRequestBody(result, init.body);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else return result;\n }\n case \"response\": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property, depth + 1);\n if (body === null || typeof body === \"string\" || body instanceof Uint8Array || body instanceof ReadableStream) {\n } else throw new TypeError(\"Response body must be of type ReadableStream.\");\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.webSocket) throw new TypeError(\"Can't deserialize a Response containing a webSocket.\");\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n return new Response(body, init);\n }\n case \"blob\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let contentType = value[1];\n let content = this.evaluateImpl(value[2], parent, property, depth + 1);\n if (!(content instanceof ReadableStream)) throw new TypeError(\"Blob content must be serialized as a ReadableStream.\");\n let promise = streamToBlobPromise(content, contentType);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"import\":\n case \"pipeline\": {\n if (value.length < 2 || value.length > 4) break;\n if (typeof value[1] != \"number\") break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let isPromise = value[0] == \"pipeline\";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise$1(hook2, []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise$1(hook2, []);\n }\n };\n if (value.length == 2) if (isPromise) return addStub(hook.get([]));\n else return addStub(hook.dup());\n let path = value[2];\n if (!(path instanceof Array)) break;\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n if (value.length == 3) return addStub(hook.get(path));\n let args = value[3];\n if (!(args instanceof Array)) break;\n args = new Evaluator2(this.importer).evaluateWithDepth([args], depth);\n return addStub(hook.call(path, args));\n }\n case \"remap\": {\n if (value.length !== 5 || typeof value[1] !== \"number\" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let path = value[2];\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n let captures = value[3].map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== \"import\" && cap[0] !== \"export\" || typeof cap[1] !== \"number\") throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n if (cap[0] === \"export\") return this.importer.importStub(cap[1]);\n else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) throw new Error(`no such entry on exports table: ${cap[1]}`);\n return exp.dup();\n }\n });\n let instructions = value[4];\n let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"export\":\n case \"promise\":\n if (typeof value[1] == \"number\") if (value[0] == \"promise\") {\n let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n break;\n case \"writable\":\n if (typeof value[1] == \"number\") {\n let hook = this.importer.importStub(value[1]);\n let stream = streamImpl.createWritableStreamFromHook(hook);\n this.hooks.push(hook);\n return stream;\n }\n break;\n case \"readable\":\n if (typeof value[1] == \"number\") {\n let stream = this.importer.getPipeReadable(value[1]);\n let hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(result[key], result, key, depth + 1);\n delete result[key];\n } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);\n return result;\n } else return value;\n }\n};\nvar ESTIMATED_OBJECT_OVERHEAD = 16;\nvar ESTIMATED_ENTRY_OVERHEAD = 8;\nvar ESTIMATED_BINARY_OVERHEAD = 16;\nvar MAX_ESTIMATE_DEPTH = 64;\nfunction estimateStringSize(value) {\n return 2 + value.length * 3;\n}\nfunction estimateEncodedSize(value, seen, depth = 0) {\n if (depth >= MAX_ESTIMATE_DEPTH) return ESTIMATED_ENTRY_OVERHEAD;\n switch (typeof value) {\n case \"string\":\n return estimateStringSize(value);\n case \"number\":\n return 16;\n case \"bigint\":\n return 16;\n case \"boolean\":\n return 8;\n case \"undefined\":\n return 16;\n case \"object\": {\n if (value === null) return 8;\n if (ArrayBuffer.isView(value)) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;\n if (value instanceof Date) return 16;\n seen ??= /* @__PURE__ */ new WeakSet();\n if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;\n seen.add(value);\n if (value instanceof Array) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD;\n for (let item of value) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateEncodedSize(item, seen, depth + 1);\n return size2;\n }\n if (value instanceof Error) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.name) + estimateStringSize(value.message) + estimateStringSize(value.stack ?? \"\");\n for (let key of Object.keys(value)) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size2;\n }\n let size = ESTIMATED_OBJECT_OVERHEAD;\n for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size;\n }\n default:\n return 16;\n }\n}\nvar ImportTableEntry = class {\n session;\n importId;\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) this.activePull = Promise.withResolvers();\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) delete this.session.onBrokenCallbacks[endIndex];\n else delete this.session.onBrokenCallbacks[i];\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) this.resolution.dispose();\n else {\n this.abort(/* @__PURE__ */ new Error(\"RPC was canceled because the RpcPromise was disposed.\"));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class RpcImportHook2 extends StubHook {\n isPromise;\n entry;\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) return this.entry;\n else throw new Error(\"This RpcImportHook was already disposed.\");\n }\n getEntryTakingOwnership(disposeOwned) {\n try {\n return this.getEntry();\n } catch (err) {\n disposeOwned();\n throw err;\n }\n }\n call(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.call(path, args);\n else return entry.session.sendCall(entry.importId, path, args);\n }\n stream(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.stream(path, args);\n else return entry.session.sendStream(entry.importId, path, args);\n }\n map(path, captures, instructions) {\n let entry = this.getEntryTakingOwnership(() => {\n for (let cap of captures) cap.dispose();\n });\n if (entry.resolution) return entry.resolution.map(path, captures, instructions);\n else return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) return entry.resolution.get(path);\n else return entry.session.sendCall(entry.importId, path);\n }\n dup() {\n return new RpcImportHook2(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) throw new Error(\"Can't pull this hook because it's not a promise hook.\");\n if (entry.resolution) return entry.resolution.pull();\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) entry.dispose();\n }\n }\n onBroken(callback) {\n if (this.entry) this.entry.onBroken(callback);\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n transport;\n options;\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n nextExportId = -1;\n onBatchDone;\n pullCount = 0;\n onBrokenCallbacks = [];\n encodingLevel;\n limits;\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n let level = \"string\";\n if (\"encodingLevel\" in transport) {\n let raw = transport.encodingLevel;\n if (raw !== void 0) {\n if (raw !== \"string\" && raw !== \"jsonCompatible\" && raw !== \"jsonCompatibleWithBytes\" && raw !== \"structuredClonable\") throw new TypeError(`Unknown transport encodingLevel: ${String(raw)}`);\n level = raw;\n }\n }\n this.encodingLevel = level;\n this.limits = {\n ...DEFAULT_LIMITS,\n ...options.limits\n };\n this.exports.push({\n hook: mainHook,\n refcount: 1\n });\n this.imports.push(new ImportTableEntry(this, 0, false));\n this.readLoop().catch((err) => this.abort(err));\n }\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(/* @__PURE__ */ new Error(\"RPC session was shut down by disposing the main stub\"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) this.releaseExport(id, 1);\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) throw new Error(`no such export ID: ${exportId}`);\n if (entry.refcount < refcount) throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) return this.options.onSendError(error);\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) throw new Error(`no such export ID: ${exportId}`);\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub$1) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n let autoRelease = exp.autoRelease;\n ++this.pullCount;\n exp.pull = resolve().then((payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);\n this.send([\n \"resolve\",\n exportId,\n value\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }, (error) => {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }).catch((error) => {\n try {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) this.onBatchDone.resolve();\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;\n else return;\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(false, entry);\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) return new ErrorStubHook(/* @__PURE__ */ new Error(\"Bug in RPC system: The peer sent a promise reusing an existing export ID.\"));\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(true, entry);\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n getPipeReadable(exportId) {\n let entry = this.exports[exportId];\n if (!entry || !entry.pipeReadable) throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\n }\n getLimits() {\n return this.limits;\n }\n createPipe(readable, readableHook) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pipe\"]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, false);\n this.imports.push(entry);\n let hook = new RpcImportHook(false, entry);\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n send(msg) {\n if (this.abortReason !== void 0) return 0;\n if (this.encodingLevel === \"string\") {\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n try {\n let sent = this.transport.send(msgText);\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => this.abort(err, false));\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n }\n return msgText.length;\n } else try {\n let size = this.transport.send(msg);\n if (typeof size === \"number\") return size;\n let thenable = size;\n if (thenable && typeof thenable.then === \"function\") Promise.resolve(thenable).catch((err) => this.abort(err, false));\n return;\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n return;\n }\n }\n sendCall(id, path, args) {\n if (this.abortReason) {\n args?.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n if (args) {\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n }\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendStream(id, path, args) {\n if (this.abortReason) {\n args.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n let msg = [\"stream\", value];\n let size = this.send(msg);\n if (size === void 0) size = estimateEncodedSize(msg);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, true);\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n return {\n promise: entry.awaitResolution().then((p) => {\n p.dispose();\n delete this.imports[importId];\n }, (err) => {\n delete this.imports[importId];\n throw err;\n }),\n size\n };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) cap.dispose();\n throw this.abortReason;\n }\n let value = [\n \"remap\",\n id,\n path,\n captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) return [\"import\", importId];\n else return [\"export\", this.exportStub(hook)];\n }),\n instructions\n ];\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pull\", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send([\n \"release\",\n id,\n remoteRefcount\n ]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop?.(error);\n this.cancelReadLoop = void 0;\n if (trySendAbortMessage) try {\n let abortMsg = [\"abort\", Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)];\n if (this.encodingLevel === \"string\") {\n let sent = this.transport.send(JSON.stringify(abortMsg));\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => {\n });\n } else {\n let result = this.transport.send(abortMsg);\n if (result && typeof result.then === \"function\") Promise.resolve(result).catch((err) => {\n });\n }\n } catch (err) {\n }\n if (error === void 0) error = \"undefined\";\n this.abortReason = error;\n if (this.onBatchDone) this.onBatchDone.reject(error);\n if (this.transport.abort) try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.onBrokenCallbacks) try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.imports) this.imports[i].abort(error);\n for (let i in this.exports) this.exports[i].hook.dispose();\n }\n async readLoop() {\n while (!this.abortReason) {\n let readCanceled = Promise.withResolvers();\n this.cancelReadLoop = readCanceled.reject;\n let raw;\n try {\n raw = await Promise.race([this.transport.receive(), readCanceled.promise]);\n } finally {\n if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;\n }\n if (this.encodingLevel === \"string\" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);\n if (this.abortReason) break;\n let msg = this.encodingLevel === \"string\" ? JSON.parse(raw) : raw;\n if (msg instanceof Array) switch (msg[0]) {\n case \"push\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n this.exports.push({\n hook,\n refcount: 1\n });\n continue;\n }\n break;\n case \"stream\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({\n hook,\n refcount: 1,\n autoRelease: true\n });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n case \"pipe\": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({\n hook,\n refcount: 1,\n pipeReadable: readable\n });\n continue;\n }\n case \"pull\": {\n let exportId = msg[1];\n if (typeof exportId == \"number\") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case \"resolve\":\n case \"reject\": {\n let importId = msg[1];\n if (typeof importId == \"number\" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) if (msg[0] == \"resolve\") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));\n else {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n else if (msg[0] == \"resolve\") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();\n continue;\n }\n break;\n }\n case \"release\": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == \"number\" && typeof refcount == \"number\") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case \"abort\": {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload.value, false);\n break;\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) throw this.abortReason;\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = {\n resolve,\n reject\n };\n await promise;\n }\n }\n getStats() {\n let result = {\n imports: 0,\n exports: 0\n };\n for (let i in this.imports) ++result.imports;\n for (let i in this.exports) ++result.exports;\n return result;\n }\n};\nvar RpcSession$1 = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n else mainHook = new ErrorStubHook(/* @__PURE__ */ new Error(\"This connection has no main object.\"));\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub$1(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nfunction newWebSocketRpcSession$1(webSocket, localMain, options) {\n if (typeof webSocket === \"string\") webSocket = new WebSocket(webSocket);\n return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") return new Response(\"This endpoint only accepts WebSocket requests.\", { status: 400 });\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession$1(server, localMain, options);\n return new Response(null, {\n status: 101,\n webSocket: pair[1]\n });\n}\nvar WebSocketTransport = class {\n constructor(webSocket) {\n this.#webSocket = webSocket;\n webSocket.binaryType = \"arraybuffer\";\n if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener(\"open\", (event) => {\n try {\n for (let message of this.#sendQueue) webSocket.send(message);\n } catch (err) {\n this.#receivedError(err);\n }\n this.#sendQueue = void 0;\n });\n }\n webSocket.addEventListener(\"message\", (event) => {\n if (this.#error) {\n } else if (typeof event.data === \"string\" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else this.#receiveQueue.push(event.data);\n else this.#receivedError(/* @__PURE__ */ new TypeError(\"Received unexpected message type from WebSocket.\"));\n });\n webSocket.addEventListener(\"close\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener(\"error\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n send(message) {\n if (this.#sendQueue === void 0) this.#webSocket.send(message);\n else this.#sendQueue.push(message);\n }\n receive() {\n if (this.#receiveQueue.length > 0) return Promise.resolve(this.#receiveQueue.shift());\n else if (this.#error) return Promise.reject(this.#error);\n else return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) message = reason.message;\n else message = `${reason}`;\n let reasonBytes = new TextEncoder().encode(message);\n if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });\n this.#webSocket.close(3e3, message);\n if (!this.#error) this.#error = reason;\n }\n #receivedError(reason) {\n if (!this.#error) {\n this.#error = reason;\n if (this.#receiveRejecter) {\n this.#receiveRejecter(reason);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n }\n }\n }\n};\nvar BatchServerTransport = class {\n constructor(batch) {\n this.#batchToReceive = batch;\n }\n #batchToSend = [];\n #batchToReceive;\n #allReceived = Promise.withResolvers();\n send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) return msg;\n else {\n this.#allReceived.resolve();\n return new Promise((r) => {\n });\n }\n }\n abort(reason) {\n this.#allReceived.reject(reason);\n }\n whenAllReceived() {\n return this.#allReceived.promise;\n }\n getResponseBody() {\n return this.#batchToSend.join(\"\\n\");\n }\n};\nasync function newHttpBatchRpcResponse(request, localMain, options) {\n if (request.method !== \"POST\") return new Response(\"This endpoint only accepts POST requests.\", { status: 405 });\n let body = await request.text();\n let transport = new BatchServerTransport(body === \"\" ? [] : body.split(\"\\n\"));\n let rpc = new RpcSession$1(transport, localMain, options);\n await transport.whenAllReceived();\n await rpc.drain();\n return new Response(transport.getResponseBody());\n}\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n else this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push([\n \"remap\",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => [\"import\", cap]),\n this.instructions\n ]);\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path,\n devalued\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) return hook.idx;\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else this.context.captures.push(hook);\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n exportStub(hook) {\n throw new Error(\"Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.\");\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot send ReadableStream inside a mapper function.\");\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise$1(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error(\"RPC map() callbacks cannot be async.\");\n }\n return new RpcPromise$1(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\"Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.\");\n}\nvar MapVariableHook = class extends StubHook {\n mapper;\n idx;\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) return this;\n else if (currentMapBuilder) return currentMapBuilder.pushGet(this, path);\n else throwMapperBuilderUseError();\n }\n call(path, args) {\n args.dispose();\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n captures;\n variables;\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n dispose() {\n for (let variable of this.variables) variable.dispose();\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) throw new Error(\"Invalid empty mapper function.\");\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub$1) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) variable.dispose();\n }\n }\n importStub(idx) {\n throw new Error(\"A mapper function cannot refer to exports.\");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) return this.captures[-idx - 1];\n else return this.variables[idx];\n }\n getPipeReadable(exportId) {\n throw new Error(\"A mapper function cannot use pipe readables.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise$1) throw new Error(\"applyMap() can't be called on RpcPromise\");\n else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n } catch (err) {\n for (let payload of payloads) payload.dispose();\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) result = RpcPayload.fromAppReturn(input);\n else result = applyMapToElement(input, parent, owner, captures, instructions);\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) cap.dispose();\n }\n};\nvar WritableStreamStubHook = class WritableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new WritableStreamStubHook2({\n refcount: 1,\n writer: stream.getWriter(),\n closed: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n getState() {\n if (this.state) return this.state;\n else throw new Error(\"Attempted to use a WritableStreamStubHook after it was disposed.\");\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== \"string\") throw new Error(\"WritableStream stub only supports direct method calls\");\n const method = path[0];\n if (method !== \"write\" && method !== \"close\" && method !== \"abort\") throw new Error(`Unknown WritableStream method: ${method}`);\n if (method === \"close\" || method === \"abort\") state.closed = true;\n return new PromiseStubHook((method === \"write\" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a WritableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a WritableStream stub\"));\n }\n dup() {\n return new WritableStreamStubHook2(this.getState(), this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a WritableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.closed) state.writer.abort(/* @__PURE__ */ new Error(\"WritableStream RPC stub was disposed without calling close()\")).catch(() => {\n });\n state.writer.releaseLock();\n }\n }\n }\n onBroken(callback) {\n }\n};\nvar INITIAL_WINDOW = 256 * 1024;\nvar MAX_WINDOW = 1024 * 1024 * 1024;\nvar MIN_WINDOW = 64 * 1024;\nvar STARTUP_GROWTH_FACTOR = 2;\nvar STEADY_GROWTH_FACTOR = 1.25;\nvar DECAY_FACTOR = 0.9;\nvar STARTUP_EXIT_ROUNDS = 3;\nvar FlowController = class {\n now;\n window = INITIAL_WINDOW;\n bytesInFlight = 0;\n inStartupPhase = true;\n delivered = 0;\n deliveredTime = 0;\n firstAckTime = 0;\n firstAckDelivered = 0;\n minRtt = Infinity;\n roundsWithoutIncrease = 0;\n lastRoundWindow = 0;\n roundStartTime = 0;\n constructor(now) {\n this.now = now;\n }\n onSend(size) {\n this.bytesInFlight += size;\n let token = {\n sentTime: this.now(),\n size,\n deliveredAtSend: this.delivered,\n deliveredTimeAtSend: this.deliveredTime,\n windowAtSend: this.window,\n windowFullAtSend: this.bytesInFlight >= this.window\n };\n return {\n token,\n shouldBlock: token.windowFullAtSend\n };\n }\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n onAck(token) {\n let ackTime = this.now();\n this.delivered += token.size;\n this.deliveredTime = ackTime;\n this.bytesInFlight -= token.size;\n let rtt = ackTime - token.sentTime;\n this.minRtt = Math.min(this.minRtt, rtt);\n if (this.firstAckTime === 0) {\n this.firstAckTime = ackTime;\n this.firstAckDelivered = this.delivered;\n } else {\n let baseTime;\n let baseDelivered;\n if (token.deliveredTimeAtSend === 0) {\n baseTime = this.firstAckTime;\n baseDelivered = this.firstAckDelivered;\n } else {\n baseTime = token.deliveredTimeAtSend;\n baseDelivered = token.deliveredAtSend;\n }\n let interval = ackTime - baseTime;\n let bandwidth = (this.delivered - baseDelivered) / interval;\n let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;\n let newWindow = bandwidth * this.minRtt * growthFactor;\n newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);\n if (token.windowFullAtSend) newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n else newWindow = Math.max(newWindow, this.window);\n this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);\n if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {\n if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) this.roundsWithoutIncrease = 0;\n else if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) this.inStartupPhase = false;\n this.roundStartTime = ackTime;\n this.lastRoundWindow = this.window;\n }\n }\n return this.bytesInFlight < this.window;\n }\n};\nfunction createWritableStreamFromHook(hook) {\n let pendingError = void 0;\n let hookDisposed = false;\n let fc = new FlowController(() => performance.now());\n let windowResolve;\n let windowReject;\n const disposeHook = () => {\n if (!hookDisposed) {\n hookDisposed = true;\n hook.dispose();\n }\n };\n return new WritableStream({\n write(chunk, controller) {\n if (pendingError !== void 0) throw pendingError;\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream([\"write\"], payload);\n if (size === void 0) return promise.catch((err) => {\n if (pendingError === void 0) pendingError = err;\n throw err;\n });\n else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n if (fc.onAck(token) && windowResolve) {\n windowResolve();\n windowResolve = void 0;\n windowReject = void 0;\n }\n }, (err) => {\n fc.onError(token);\n if (pendingError === void 0) {\n pendingError = err;\n controller.error(err);\n disposeHook();\n }\n if (windowReject) {\n windowReject(err);\n windowResolve = void 0;\n windowReject = void 0;\n }\n });\n if (shouldBlock) return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\n }\n },\n async close() {\n if (pendingError !== void 0) {\n disposeHook();\n throw pendingError;\n }\n const { promise } = hook.stream([\"close\"], RpcPayload.fromAppParams([]));\n try {\n await promise;\n } catch (err) {\n throw pendingError ?? err;\n } finally {\n disposeHook();\n }\n },\n abort(reason) {\n if (pendingError !== void 0) return;\n pendingError = reason ?? /* @__PURE__ */ new Error(\"WritableStream was aborted\");\n if (windowReject) {\n windowReject(pendingError);\n windowResolve = void 0;\n windowReject = void 0;\n }\n const { promise } = hook.stream([\"abort\"], RpcPayload.fromAppParams([reason]));\n promise.then(() => disposeHook(), () => disposeHook());\n }\n });\n}\nvar ReadableStreamStubHook = class ReadableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new ReadableStreamStubHook2({\n refcount: 1,\n stream,\n canceled: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot call methods on a ReadableStream stub\"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a ReadableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a ReadableStream stub\"));\n }\n dup() {\n let state = this.state;\n if (!state) throw new Error(\"Attempted to dup a ReadableStreamStubHook after it was disposed.\");\n return new ReadableStreamStubHook2(state, this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a ReadableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.canceled) {\n state.canceled = true;\n if (!state.stream.locked) state.stream.cancel(/* @__PURE__ */ new Error(\"ReadableStream RPC stub was disposed without being consumed\")).catch(() => {\n });\n }\n }\n }\n }\n onBroken(callback) {\n }\n};\nstreamImpl.createWritableStreamHook = WritableStreamStubHook.create;\nstreamImpl.createWritableStreamFromHook = createWritableStreamFromHook;\nstreamImpl.createReadableStreamHook = ReadableStreamStubHook.create;\nasync function newWorkersRpcResponse(request, localMain, options) {\n if (request.method === \"POST\") {\n let response = await newHttpBatchRpcResponse(request, localMain, options);\n response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n return response;\n } else if (request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\") return newWorkersWebSocketRpcResponse(request, localMain, options);\n else return new Response(\"This endpoint only accepts POST or WebSocket requests.\", { status: 400 });\n}\n\n// templates/remoteBindings/ProxyServerWorker.ts\nimport { EmailMessage } from \"cloudflare:email\";\nvar BindingNotFoundError = class extends Error {\n constructor(name) {\n super(`Binding ${name ? `\"${name}\"` : \"\"} not found`);\n }\n};\nfunction getExposedJSRPCBinding(request, env) {\n const url = new URL(request.url);\n const bindingName = url.searchParams.get(\"MF-Binding\");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n if (targetBinding.constructor.name === \"Hyperdrive\") {\n const hyperdrive = targetBinding;\n return {\n getConnectionString() {\n return hyperdrive.connectionString;\n },\n connect() {\n const socket = hyperdrive.connect();\n return { readable: socket.readable, writable: socket.writable };\n }\n };\n }\n if (targetBinding.constructor.name === \"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";
|
|
90237
|
+
var ProxyServerWorker_default = "// ../../node_modules/.pnpm/capnweb@0.12.0/node_modules/capnweb/dist/index-workers.js\nimport * as cfw from \"cloudflare:workers\";\nvar WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol(\"workers-module\");\nglobalThis[WORKERS_MODULE_SYMBOL] = cfw;\nif (!Symbol.dispose) Symbol.dispose = /* @__PURE__ */ Symbol.for(\"dispose\");\nif (!Symbol.asyncDispose) Symbol.asyncDispose = /* @__PURE__ */ Symbol.for(\"asyncDispose\");\nif (!Promise.withResolvers) Promise.withResolvers = function() {\n let resolve;\n let reject;\n return {\n promise: new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n }),\n resolve,\n reject\n };\n};\nvar workersModule = globalThis[WORKERS_MODULE_SYMBOL];\nvar RpcTarget$1 = workersModule ? workersModule.RpcTarget : class {\n};\nvar AsyncFunction = (async function() {\n}).constructor;\nvar BUFFER_PROTOTYPE = typeof Buffer !== \"undefined\" ? Buffer.prototype : void 0;\nfunction typeForRpc(value) {\n switch (typeof value) {\n case \"boolean\":\n case \"number\":\n case \"string\":\n return \"primitive\";\n case \"undefined\":\n return \"undefined\";\n case \"object\":\n case \"function\":\n break;\n case \"bigint\":\n return \"bigint\";\n default:\n return \"unsupported\";\n }\n if (value === null) return \"primitive\";\n let prototype = Object.getPrototypeOf(value);\n switch (prototype) {\n case Object.prototype:\n return \"object\";\n case Function.prototype:\n case AsyncFunction.prototype:\n return \"function\";\n case Array.prototype:\n return \"array\";\n case Date.prototype:\n return \"date\";\n case Uint8Array.prototype:\n case BUFFER_PROTOTYPE:\n case ArrayBuffer.prototype:\n case DataView.prototype:\n case Int8Array.prototype:\n case Uint8ClampedArray.prototype:\n case Int16Array.prototype:\n case Uint16Array.prototype:\n case Int32Array.prototype:\n case Uint32Array.prototype:\n case BigInt64Array.prototype:\n case BigUint64Array.prototype:\n case Float32Array.prototype:\n case Float64Array.prototype:\n return \"bytes\";\n case WritableStream.prototype:\n return \"writable\";\n case ReadableStream.prototype:\n return \"readable\";\n case URL.prototype:\n return \"url\";\n case Headers.prototype:\n return \"headers\";\n case Request.prototype:\n return \"request\";\n case Response.prototype:\n return \"response\";\n case Blob.prototype:\n return \"blob\";\n case RpcStub$1.prototype:\n return \"stub\";\n case RpcPromise$1.prototype:\n return \"rpc-promise\";\n default:\n if (workersModule) {\n if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) return \"rpc-target\";\n else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) return \"rpc-thenable\";\n }\n if (value instanceof RpcTarget$1) return \"rpc-target\";\n if (value instanceof Error) return \"error\";\n return \"unsupported\";\n }\n}\nfunction mapNotLoaded() {\n throw new Error(\"RPC map() implementation was not loaded.\");\n}\nvar mapImpl = {\n applyMap: mapNotLoaded,\n sendMap: mapNotLoaded\n};\nfunction streamNotLoaded() {\n throw new Error(\"Stream implementation was not loaded.\");\n}\nvar streamImpl = {\n createWritableStreamHook: streamNotLoaded,\n createWritableStreamFromHook: streamNotLoaded,\n createReadableStreamHook: streamNotLoaded\n};\nvar StubHook = class {\n stream(path, args) {\n let hook = this.call(path, args);\n let pulled;\n try {\n pulled = hook.pull();\n } catch (err) {\n hook.dispose();\n throw err;\n }\n let promise;\n if (pulled instanceof Promise) promise = pulled.then((p) => {\n p.dispose();\n });\n else {\n pulled.dispose();\n promise = Promise.resolve();\n }\n return { promise };\n }\n};\nvar ErrorStubHook = class extends StubHook {\n error;\n constructor(error) {\n super();\n this.error = error;\n }\n call(path, args) {\n args.dispose();\n return this;\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return this;\n }\n get(path) {\n return this;\n }\n dup() {\n return this;\n }\n pull() {\n return Promise.reject(this.error);\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n }\n onBroken(callback) {\n try {\n callback(this.error);\n } catch (err) {\n Promise.resolve(err);\n }\n }\n};\nvar DISPOSED_HOOK = new ErrorStubHook(/* @__PURE__ */ new Error(\"Attempted to use RPC stub after it has been disposed.\"));\nvar doCall = (hook, path, params) => {\n return hook.call(path, params);\n};\nfunction withCallInterceptor(interceptor, callback) {\n let oldValue = doCall;\n doCall = interceptor;\n try {\n return callback();\n } finally {\n doCall = oldValue;\n }\n}\nvar RAW_STUB = /* @__PURE__ */ Symbol(\"realStub\");\nvar PROXY_HANDLERS = {\n apply(target, thisArg, argumentsList) {\n let stub = target.raw;\n return new RpcPromise$1(doCall(stub.hook, stub.pathIfPromise || [], RpcPayload.fromAppParams(argumentsList)), []);\n },\n get(target, prop, receiver) {\n let stub = target.raw;\n if (prop === RAW_STUB) return stub;\n else if (prop in RpcPromise$1.prototype) return stub[prop];\n else if (typeof prop === \"string\") return new RpcPromise$1(stub.hook, stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]);\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return () => {\n stub.hook.dispose();\n stub.hook = DISPOSED_HOOK;\n };\n else return;\n },\n has(target, prop) {\n let stub = target.raw;\n if (prop === RAW_STUB) return true;\n else if (prop in RpcPromise$1.prototype) return prop in stub;\n else if (typeof prop === \"string\") return true;\n else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return true;\n else return false;\n },\n construct(target, args) {\n throw new Error(\"An RPC stub cannot be used as a constructor.\");\n },\n defineProperty(target, property, attributes) {\n throw new Error(\"Can't define properties on RPC stubs.\");\n },\n deleteProperty(target, p) {\n throw new Error(\"Can't delete properties on RPC stubs.\");\n },\n getOwnPropertyDescriptor(target, p) {\n },\n getPrototypeOf(target) {\n return Object.getPrototypeOf(target.raw);\n },\n isExtensible(target) {\n return false;\n },\n ownKeys(target) {\n return [];\n },\n preventExtensions(target) {\n return true;\n },\n set(target, p, newValue, receiver) {\n throw new Error(\"Can't assign properties on RPC stubs.\");\n },\n setPrototypeOf(target, v) {\n throw new Error(\"Can't override prototype of RPC stubs.\");\n }\n};\nvar RpcStub$1 = class RpcStub$12 extends RpcTarget$1 {\n constructor(hook, pathIfPromise) {\n super();\n if (!(hook instanceof StubHook)) {\n let value = hook;\n if (value instanceof RpcTarget$1 || value instanceof Function) hook = TargetStubHook.create(value, void 0);\n else hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));\n if (pathIfPromise) throw new TypeError(\"RpcStub constructor expected one argument, received two.\");\n }\n this.hook = hook;\n this.pathIfPromise = pathIfPromise;\n let func = () => {\n };\n func.raw = this;\n return new Proxy(func, PROXY_HANDLERS);\n }\n hook;\n pathIfPromise;\n dup() {\n let target = this[RAW_STUB];\n if (target.pathIfPromise) return new RpcStub$12(target.hook.get(target.pathIfPromise));\n else return new RpcStub$12(target.hook.dup());\n }\n onRpcBroken(callback) {\n this[RAW_STUB].hook.onBroken(callback);\n }\n map(func) {\n let { hook, pathIfPromise } = this[RAW_STUB];\n return mapImpl.sendMap(hook, pathIfPromise || [], func);\n }\n toString() {\n return \"[object RpcStub]\";\n }\n};\nvar RpcPromise$1 = class extends RpcStub$1 {\n constructor(hook, pathIfPromise) {\n if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);\n else {\n if (pathIfPromise !== void 0) throw new TypeError(\"RpcPromise constructor expected one argument, received two.\");\n let kind = typeForRpc(hook);\n if (kind === \"rpc-promise\") {\n let raw = unwrapStubAndPath(hook);\n if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);\n else {\n let adopted = raw.hook;\n raw.hook = DISPOSED_HOOK;\n super(adopted, []);\n }\n } else if (kind === \"rpc-thenable\") super(TargetStubHook.create(hook, void 0), []);\n else {\n let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));\n promiseHook.ignoreUnhandledRejections();\n super(promiseHook, []);\n }\n }\n }\n then(onfulfilled, onrejected) {\n return pullPromise(this).then(...arguments);\n }\n catch(onrejected) {\n return pullPromise(this).catch(...arguments);\n }\n finally(onfinally) {\n return pullPromise(this).finally(...arguments);\n }\n toString() {\n return \"[object RpcPromise]\";\n }\n};\nfunction unwrapStubTakingOwnership(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return hook.get(pathIfPromise);\n else return hook;\n}\nfunction unwrapStubAndDup(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise) return hook.get(pathIfPromise);\n else return hook.dup();\n}\nfunction unwrapStubNoProperties(stub) {\n let { hook, pathIfPromise } = stub[RAW_STUB];\n if (pathIfPromise && pathIfPromise.length > 0) return;\n return hook;\n}\nfunction unwrapStubOrParent(stub) {\n return stub[RAW_STUB].hook;\n}\nfunction unwrapStubAndPath(stub) {\n return stub[RAW_STUB];\n}\nasync function pullPromise(promise) {\n let { hook, pathIfPromise } = promise[RAW_STUB];\n if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);\n return (await hook.pull()).deliverResolve();\n}\nvar RpcPayload = class RpcPayload2 {\n value;\n source;\n hooks;\n promises;\n static fromAppParams(value) {\n return new RpcPayload2(value, \"params\");\n }\n static fromAppReturn(value) {\n return new RpcPayload2(value, \"return\");\n }\n static fromArray(array) {\n let hooks = [];\n let promises = [];\n let resultArray = [];\n for (let payload of array) {\n payload.ensureDeepCopied();\n for (let hook of payload.hooks) hooks.push(hook);\n for (let promise of payload.promises) {\n if (promise.parent === payload) promise = {\n parent: resultArray,\n property: resultArray.length,\n promise: promise.promise\n };\n promises.push(promise);\n }\n resultArray.push(payload.value);\n }\n return new RpcPayload2(resultArray, \"owned\", hooks, promises);\n }\n static forEvaluate(hooks, promises) {\n return new RpcPayload2(null, \"owned\", hooks, promises);\n }\n static deepCopyFrom(value, oldParent, owner) {\n let result = new RpcPayload2(null, \"owned\", [], []);\n result.value = result.deepCopy(value, oldParent, \"value\", result, true, owner);\n return result;\n }\n constructor(value, source, hooks, promises) {\n this.value = value;\n this.source = source;\n this.hooks = hooks;\n this.promises = promises;\n }\n rpcTargets;\n getHookForRpcTarget(target, parent, dupStubs = true) {\n if (this.source === \"params\") {\n if (dupStubs) {\n let dupable = target;\n if (typeof dupable.dup === \"function\") target = dupable.dup();\n }\n return TargetStubHook.create(target, parent);\n } else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(target);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(target);\n return hook;\n }\n else {\n hook = TargetStubHook.create(target, parent);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(target, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw RpcTargets\");\n }\n getHookForWritableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createWritableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createWritableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw WritableStreams\");\n }\n getHookForReadableStream(stream, parent, dupStubs = true) {\n if (this.source === \"params\") return streamImpl.createReadableStreamHook(stream);\n else if (this.source === \"return\") {\n let hook = this.rpcTargets?.get(stream);\n if (hook) if (dupStubs) return hook.dup();\n else {\n this.rpcTargets?.delete(stream);\n return hook;\n }\n else {\n hook = streamImpl.createReadableStreamHook(stream);\n if (dupStubs) {\n if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();\n this.rpcTargets.set(stream, hook);\n return hook.dup();\n } else return hook;\n }\n } else throw new Error(\"owned payload shouldn't contain raw ReadableStreams\");\n }\n deepCopy(value, oldParent, property, parent, dupStubs, owner) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n return value;\n case \"primitive\":\n case \"bigint\":\n case \"date\":\n case \"bytes\":\n case \"blob\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return value;\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);\n return result;\n }\n case \"object\": {\n let result = {};\n let object = value;\n for (let i in object) result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);\n return result;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let stub = value;\n let hook;\n if (dupStubs) hook = unwrapStubAndDup(stub);\n else hook = unwrapStubTakingOwnership(stub);\n if (stub instanceof RpcPromise$1) {\n let promise = new RpcPromise$1(hook, []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook;\n if (owner) hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);\n else hook = TargetStubHook.create(target, oldParent);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n case \"rpc-thenable\": {\n let target = value;\n let promise;\n if (owner) promise = new RpcPromise$1(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);\n else promise = new RpcPromise$1(TargetStubHook.create(target, oldParent), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n }\n case \"writable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createWritableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"readable\": {\n let stream = value;\n let hook;\n if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);\n else hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n case \"headers\":\n return new Headers(value);\n case \"request\": {\n let req = value;\n if (req.body) this.deepCopy(req.body, req, \"body\", req, dupStubs, owner);\n return new Request(req);\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.deepCopy(resp.body, resp, \"body\", resp, dupStubs, owner);\n return new Response(resp.body, resp);\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n ensureDeepCopied() {\n if (this.source !== \"owned\") {\n let dupStubs = this.source === \"params\";\n this.hooks = [];\n this.promises = [];\n try {\n this.value = this.deepCopy(this.value, void 0, \"value\", this, dupStubs, this);\n } catch (err) {\n this.hooks = void 0;\n this.promises = void 0;\n throw err;\n }\n this.source = \"owned\";\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in deep-copy?\");\n this.rpcTargets = void 0;\n }\n }\n deliverTo(parent, property, promises) {\n this.ensureDeepCopied();\n if (this.value instanceof RpcPromise$1) RpcPayload2.deliverRpcPromiseTo(this.value, parent, property, promises);\n else {\n parent[property] = this.value;\n for (let record of this.promises) RpcPayload2.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);\n }\n }\n static deliverRpcPromiseTo(promise, parent, property, promises) {\n let hook = unwrapStubNoProperties(promise);\n if (!hook) throw new Error(\"property promises should have been resolved earlier\");\n let inner = hook.pull();\n if (inner instanceof RpcPayload2) inner.deliverTo(parent, property, promises);\n else promises.push(inner.then((payload) => {\n let subPromises = [];\n payload.deliverTo(parent, property, subPromises);\n if (subPromises.length > 0) return Promise.all(subPromises);\n }));\n }\n async deliverCall(func, thisArg) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = Function.prototype.apply.call(func, thisArg, this.value);\n if (result instanceof RpcPromise$1) return RpcPayload2.fromAppReturn(result);\n else return RpcPayload2.fromAppReturn(await result);\n } finally {\n this.dispose();\n }\n }\n async deliverStreamWrite(writer) {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let chunk = this.value[0];\n if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {\n if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n await writer.write(chunk);\n return RpcPayload2.fromAppReturn(void 0);\n }\n await writer.write(chunk);\n this.dispose();\n return RpcPayload2.fromAppReturn(void 0);\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n async deliverResolve() {\n try {\n let promises = [];\n this.deliverTo(this, \"value\", promises);\n if (promises.length > 0) await Promise.all(promises);\n let result = this.value;\n if (result instanceof Object) {\n if (!(Symbol.dispose in result)) Object.defineProperty(result, Symbol.dispose, {\n value: () => this.dispose(),\n writable: true,\n enumerable: false,\n configurable: true\n });\n }\n return result;\n } catch (err) {\n this.dispose();\n throw err;\n }\n }\n dispose() {\n if (this.source === \"owned\") {\n this.hooks.forEach((hook) => hook.dispose());\n this.promises.forEach((promise) => promise.promise[Symbol.dispose]());\n } else if (this.source === \"return\") {\n this.disposeImpl(this.value, void 0);\n if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error(\"Not all rpcTargets were accounted for in disposeImpl()?\");\n }\n this.source = \"owned\";\n this.hooks = [];\n this.promises = [];\n }\n disposeImpl(value, parent) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"url\":\n case \"error\":\n case \"undefined\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.disposeImpl(object[i], object);\n return;\n }\n case \"stub\":\n case \"rpc-promise\": {\n let hook = unwrapStubNoProperties(value);\n if (hook) hook.dispose();\n return;\n }\n case \"function\":\n case \"rpc-target\": {\n let target = value;\n let hook = this.rpcTargets?.get(target);\n if (hook) {\n hook.dispose();\n this.rpcTargets.delete(target);\n } else disposeRpcTarget(target);\n return;\n }\n case \"rpc-thenable\":\n return;\n case \"headers\":\n return;\n case \"request\": {\n let req = value;\n if (req.body) this.disposeImpl(req.body, req);\n return;\n }\n case \"response\": {\n let resp = value;\n if (resp.body) this.disposeImpl(resp.body, resp);\n return;\n }\n case \"writable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createWritableStreamHook(stream);\n hook.dispose();\n return;\n }\n case \"readable\": {\n let stream = value;\n let hook = this.rpcTargets?.get(stream);\n if (hook) this.rpcTargets.delete(stream);\n else hook = streamImpl.createReadableStreamHook(stream);\n hook.dispose();\n return;\n }\n default:\n return;\n }\n }\n ignoreUnhandledRejections() {\n if (this.hooks) {\n this.hooks.forEach((hook) => {\n hook.ignoreUnhandledRejections();\n });\n this.promises.forEach((promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections());\n } else this.ignoreUnhandledRejectionsImpl(this.value);\n }\n ignoreUnhandledRejectionsImpl(value) {\n switch (typeForRpc(value)) {\n case \"unsupported\":\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"undefined\":\n case \"function\":\n case \"rpc-target\":\n case \"writable\":\n case \"readable\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n return;\n case \"array\": {\n let array = value;\n let len = array.length;\n for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);\n return;\n }\n case \"object\": {\n let object = value;\n for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);\n return;\n }\n case \"stub\":\n case \"rpc-promise\":\n unwrapStubOrParent(value).ignoreUnhandledRejections();\n return;\n case \"rpc-thenable\":\n value.then((_) => {\n }, (_) => {\n });\n return;\n default:\n return;\n }\n }\n};\nfunction followPath(value, parent, path, owner) {\n for (let i = 0; i < path.length; i++) {\n parent = value;\n let part = path[i];\n if (part in Object.prototype) {\n value = void 0;\n continue;\n }\n switch (typeForRpc(value)) {\n case \"object\":\n case \"function\":\n if (Object.hasOwn(value, part)) value = value[part];\n else value = void 0;\n break;\n case \"array\":\n if (Number.isInteger(part) && part >= 0) value = value[part];\n else value = void 0;\n break;\n case \"rpc-target\":\n case \"rpc-thenable\":\n if (Object.hasOwn(value, part)) throw new TypeError(`Attempted to access property '${part}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);\n else value = value[part];\n owner = null;\n break;\n case \"stub\":\n case \"rpc-promise\": {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i)\n };\n }\n case \"writable\":\n value = void 0;\n break;\n case \"readable\":\n value = void 0;\n break;\n case \"primitive\":\n case \"bigint\":\n case \"bytes\":\n case \"blob\":\n case \"date\":\n case \"error\":\n case \"url\":\n case \"headers\":\n case \"request\":\n case \"response\":\n value = void 0;\n break;\n case \"undefined\":\n value = value[part];\n break;\n case \"unsupported\":\n if (i === 0) throw new TypeError(`RPC stub points at a non-serializable type.`);\n else {\n let prefix = path.slice(0, i).join(\".\");\n let remainder = path.slice(0, i).join(\".\");\n throw new TypeError(`'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`);\n }\n default:\n throw new TypeError(\"unreachable\");\n }\n }\n if (value instanceof RpcPromise$1) {\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n return {\n hook,\n remainingPath: pathIfPromise || []\n };\n }\n return {\n value,\n parent,\n owner\n };\n}\nvar ValueStubHook = class extends StubHook {\n call(path, args) {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);\n if (typeof followResult.value != \"function\") {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(\".\")}' is not a function.`));\n }\n return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {\n return new PayloadStubHook(payload);\n }));\n }\n map(path, captures, instructions) {\n try {\n let followResult;\n try {\n let { value, owner } = this.getValue();\n followResult = followPath(value, void 0, path, owner);\n } catch (err) {\n for (let cap of captures) cap.dispose();\n throw err;\n }\n if (followResult.hook) return followResult.hook.map(followResult.remainingPath, captures, instructions);\n return mapImpl.applyMap(followResult.value, followResult.parent, followResult.owner, captures, instructions);\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n get(path) {\n try {\n let { value, owner } = this.getValue();\n if (path.length === 0 && owner === null) {\n if (value instanceof Object && \"then\" in value) return this.dup();\n throw new Error(\"Can't dup an RpcTarget stub as a promise.\");\n }\n let followResult = followPath(value, void 0, path, owner);\n if (followResult.hook) return followResult.hook.get(followResult.remainingPath);\n return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));\n } catch (err) {\n return new ErrorStubHook(err);\n }\n }\n};\nvar PayloadStubHook = class PayloadStubHook2 extends ValueStubHook {\n constructor(payload) {\n super();\n this.payload = payload;\n }\n payload;\n getPayload() {\n if (this.payload) return this.payload;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n let payload = this.getPayload();\n return {\n value: payload.value,\n owner: payload\n };\n }\n dup() {\n let thisPayload = this.getPayload();\n return new PayloadStubHook2(RpcPayload.deepCopyFrom(thisPayload.value, void 0, thisPayload));\n }\n pull() {\n return this.getPayload();\n }\n ignoreUnhandledRejections() {\n if (this.payload) this.payload.ignoreUnhandledRejections();\n }\n dispose() {\n if (this.payload) {\n this.payload.dispose();\n this.payload = void 0;\n }\n }\n onBroken(callback) {\n if (this.payload) {\n if (this.payload.value instanceof RpcStub$1) this.payload.value.onRpcBroken(callback);\n }\n }\n};\nfunction disposeRpcTarget(target) {\n if (Symbol.dispose in target) try {\n target[Symbol.dispose]();\n } catch (err) {\n Promise.reject(err);\n }\n}\nvar TargetStubHook = class TargetStubHook2 extends ValueStubHook {\n static create(value, parent) {\n if (typeof value !== \"function\") parent = void 0;\n return new TargetStubHook2(value, parent);\n }\n constructor(target, parent, dupFrom) {\n super();\n this.target = target;\n this.parent = parent;\n if (dupFrom) {\n if (dupFrom.refcount) {\n this.refcount = dupFrom.refcount;\n ++this.refcount.count;\n }\n } else if (Symbol.dispose in target) this.refcount = { count: 1 };\n }\n target;\n parent;\n refcount;\n getTarget() {\n if (this.target) return this.target;\n else throw new Error(\"Attempted to use an RPC StubHook after it was disposed.\");\n }\n getValue() {\n return {\n value: this.getTarget(),\n owner: null\n };\n }\n dup() {\n return new TargetStubHook2(this.getTarget(), this.parent, this);\n }\n pull() {\n let target = this.getTarget();\n if (\"then\" in target) return Promise.resolve(target).then((resolution) => {\n return RpcPayload.fromAppReturn(resolution);\n });\n else return Promise.reject(/* @__PURE__ */ new Error(\"Tried to resolve a non-promise stub.\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n if (this.target) {\n if (this.refcount) {\n if (--this.refcount.count == 0) disposeRpcTarget(this.target);\n }\n this.target = void 0;\n }\n }\n onBroken(callback) {\n let target = this.target;\n if (target && \"then\" in target) Promise.resolve(target).then(() => {\n }, callback);\n }\n};\nvar PromiseStubHook = class PromiseStubHook2 extends StubHook {\n promise;\n resolution;\n constructor(promise) {\n super();\n this.promise = promise.then((res) => {\n this.resolution = res;\n return res;\n });\n }\n call(path, args) {\n args.ensureDeepCopied();\n return new PromiseStubHook2(this.promise.then((hook) => hook.call(path, args), (err) => {\n args.dispose();\n throw err;\n }));\n }\n stream(path, args) {\n args.ensureDeepCopied();\n return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {\n args.dispose();\n throw err;\n }) };\n }\n map(path, captures, instructions) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.map(path, captures, instructions), (err) => {\n for (let cap of captures) cap.dispose();\n throw err;\n }));\n }\n get(path) {\n return new PromiseStubHook2(this.promise.then((hook) => hook.get(path)));\n }\n dup() {\n if (this.resolution) return this.resolution.dup();\n else return new PromiseStubHook2(this.promise.then((hook) => hook.dup()));\n }\n pull() {\n if (this.resolution) return this.resolution.pull();\n else return this.promise.then((hook) => hook.pull());\n }\n ignoreUnhandledRejections() {\n if (this.resolution) this.resolution.ignoreUnhandledRejections();\n else this.promise.then((res) => {\n res.ignoreUnhandledRejections();\n }, (err) => {\n });\n }\n dispose() {\n this.promise.then((hook) => hook.dispose(), () => {\n });\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else this.promise.then((hook) => {\n hook.onBroken(callback);\n }, callback);\n }\n};\nvar DEFAULT_LIMITS = {\n maxBigIntDigits: 16384,\n maxDepth: 256,\n maxMessageSize: 32 * 1024 * 1024\n};\nvar NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\nvar BYTE_CONTAINER_TYPE_NAMES = [\n \"ArrayBuffer\",\n \"DataView\",\n \"Int8Array\",\n \"Uint8Array\",\n \"Uint8ClampedArray\",\n \"Int16Array\",\n \"Uint16Array\",\n \"Int32Array\",\n \"Uint32Array\",\n \"BigInt64Array\",\n \"BigUint64Array\",\n \"Float32Array\",\n \"Float64Array\"\n];\nfunction isValidByteContainerName(value) {\n return BYTE_CONTAINER_TYPE_NAMES.includes(value);\n}\nvar TYPED_ARRAY_ELEMENT_SIZE = {\n ArrayBuffer: void 0,\n DataView: void 0,\n Int8Array: void 0,\n Uint8Array: void 0,\n Uint8ClampedArray: void 0,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n BigInt64Array: 8,\n BigUint64Array: 8,\n Float32Array: 4,\n Float64Array: 8\n};\nvar BYTE_CONTAINER_PROTOTYPES = {\n ArrayBuffer: ArrayBuffer.prototype,\n DataView: DataView.prototype,\n Int8Array: Int8Array.prototype,\n Uint8ClampedArray: Uint8ClampedArray.prototype,\n Int16Array: Int16Array.prototype,\n Uint16Array: Uint16Array.prototype,\n Int32Array: Int32Array.prototype,\n Uint32Array: Uint32Array.prototype,\n BigInt64Array: BigInt64Array.prototype,\n BigUint64Array: BigUint64Array.prototype,\n Float32Array: Float32Array.prototype,\n Float64Array: Float64Array.prototype\n};\nvar BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();\nfor (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);\nfunction swapByteOrder(bytes, elementSize) {\n if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);\n let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {\n case 2:\n view.setUint16(offset, view.getUint16(offset, false), true);\n break;\n case 4:\n view.setUint32(offset, view.getUint32(offset, false), true);\n break;\n case 8:\n view.setBigUint64(offset, view.getBigUint64(offset, false), true);\n break;\n }\n}\nvar NullExporter = class {\n exportStub(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n exportPromise(stub) {\n throw new Error(\"Cannot serialize RPC stubs without an RPC session.\");\n }\n getImport(hook) {\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot create pipes without an RPC session.\");\n }\n onSendError(error) {\n }\n};\nvar NULL_EXPORTER = new NullExporter();\nasync function streamToBlob(stream, type) {\n let b = await new Response(stream).blob();\n return b.type === type ? b : b.slice(0, b.size, type);\n}\nvar ERROR_TYPES = {\n __proto__: null,\n Error,\n EvalError,\n RangeError,\n ReferenceError,\n SyntaxError,\n TypeError,\n URIError,\n AggregateError\n};\nvar Devaluator = class Devaluator2 {\n exporter;\n source;\n encodingLevel;\n constructor(exporter, source, encodingLevel) {\n this.exporter = exporter;\n this.source = source;\n this.encodingLevel = encodingLevel;\n }\n static devaluate(value, parent, exporter = NULL_EXPORTER, source, encodingLevel = \"string\") {\n let devaluator = new Devaluator2(exporter, source, encodingLevel);\n try {\n return devaluator.devaluateImpl(value, parent, 0);\n } catch (err) {\n if (devaluator.exports) try {\n exporter.unexport(devaluator.exports);\n } catch (err2) {\n }\n throw err;\n }\n }\n exports;\n devaluateImpl(value, parent, depth) {\n if (depth >= 256) throw new Error(\"Serialization exceeded maximum allowed depth. (Does the message contain cycles?)\");\n switch (typeForRpc(value)) {\n case \"unsupported\": {\n let msg;\n try {\n msg = `Cannot serialize value: ${value}`;\n } catch (err) {\n msg = \"Cannot serialize value: (couldn't stringify value)\";\n }\n throw new TypeError(msg);\n }\n case \"primitive\":\n if (typeof value === \"number\" && !isFinite(value)) {\n if (this.encodingLevel === \"structuredClonable\") return value;\n if (value === Infinity) return [\"inf\"];\n else if (value === -Infinity) return [\"-inf\"];\n else return [\"nan\"];\n } else return value;\n case \"object\": {\n let object = value;\n let result = {};\n for (let key in object) result[key] = this.devaluateImpl(object[key], object, depth + 1);\n return result;\n }\n case \"array\": {\n let array = value;\n let len = array.length;\n let result = new Array(len);\n for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);\n return [result];\n }\n case \"bigint\":\n if (this.encodingLevel === \"structuredClonable\") return value;\n return [\"bigint\", value.toString()];\n case \"date\": {\n if (this.encodingLevel === \"structuredClonable\") return value;\n const time = value.getTime();\n return [\"date\", Number.isNaN(time) ? null : time];\n }\n case \"bytes\": {\n let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));\n let bytes;\n if (alternateTypeName === \"ArrayBuffer\") bytes = new Uint8Array(value);\n else if (alternateTypeName === void 0) bytes = value;\n else {\n let view = value;\n bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];\n if (!NATIVE_LITTLE_ENDIAN && elementSize) {\n bytes = bytes.slice();\n swapByteOrder(bytes, elementSize);\n }\n }\n if (this.encodingLevel === \"structuredClonable\" || this.encodingLevel === \"jsonCompatibleWithBytes\") return alternateTypeName === void 0 ? [\"bytes\", bytes] : [\n \"bytes\",\n bytes,\n alternateTypeName\n ];\n let b64;\n if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });\n else if (typeof Buffer !== \"undefined\") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString(\"base64\");\n else {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);\n b64 = btoa(binary);\n }\n b64 = b64.replace(/=+$/, \"\");\n return alternateTypeName === void 0 ? [\"bytes\", b64] : [\n \"bytes\",\n b64,\n alternateTypeName\n ];\n }\n case \"url\":\n return [\"url\", value.href];\n case \"headers\":\n return [\"headers\", [...value]];\n case \"request\": {\n let req = value;\n let init = {};\n if (req.method !== \"GET\") init.method = req.method;\n let headers = [...req.headers];\n if (headers.length > 0) init.headers = headers;\n if (req.body) {\n init.body = this.devaluateImpl(req.body, req, depth + 1);\n init.duplex = req.duplex || \"half\";\n } else if (req.body === void 0 && ![\n \"GET\",\n \"HEAD\",\n \"OPTIONS\",\n \"TRACE\",\n \"DELETE\"\n ].includes(req.method)) {\n let bodyPromise = req.arrayBuffer();\n let readable = new ReadableStream({ async start(controller) {\n try {\n controller.enqueue(new Uint8Array(await bodyPromise));\n controller.close();\n } catch (err) {\n controller.error(err);\n }\n } });\n let hook = streamImpl.createReadableStreamHook(readable);\n init.body = [\"readable\", this.exporter.createPipe(readable, hook)];\n init.duplex = req.duplex || \"half\";\n }\n if (req.cache && req.cache !== \"default\") init.cache = req.cache;\n if (req.redirect !== \"follow\") init.redirect = req.redirect;\n if (req.integrity) init.integrity = req.integrity;\n if (req.mode && req.mode !== \"cors\") init.mode = req.mode;\n if (req.credentials && req.credentials !== \"same-origin\") init.credentials = req.credentials;\n if (req.referrer && req.referrer !== \"about:client\") init.referrer = req.referrer;\n if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;\n if (req.keepalive) init.keepalive = req.keepalive;\n let cfReq = req;\n if (cfReq.cf) init.cf = cfReq.cf;\n if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== \"automatic\") init.encodeResponseBody = cfReq.encodeResponseBody;\n return [\n \"request\",\n req.url,\n init\n ];\n }\n case \"response\": {\n let resp = value;\n let body = this.devaluateImpl(resp.body, resp, depth + 1);\n let init = {};\n if (resp.status !== 200) init.status = resp.status;\n if (resp.statusText) init.statusText = resp.statusText;\n let headers = [...resp.headers];\n if (headers.length > 0) init.headers = headers;\n let cfResp = resp;\n if (cfResp.cf) init.cf = cfResp.cf;\n if (cfResp.encodeBody && cfResp.encodeBody !== \"automatic\") init.encodeBody = cfResp.encodeBody;\n if (cfResp.webSocket) throw new TypeError(\"Can't serialize a Response containing a webSocket.\");\n return [\n \"response\",\n body,\n init\n ];\n }\n case \"blob\": {\n let blob = value;\n let readable = blob.stream();\n let hook = streamImpl.createReadableStreamHook(readable);\n let importId = this.exporter.createPipe(readable, hook);\n return [\n \"blob\",\n blob.type,\n [\"readable\", importId]\n ];\n }\n case \"error\": {\n let e = value;\n let rewritten = this.exporter.onSendError(e);\n if (rewritten) e = rewritten;\n let anyE = e;\n let props;\n let captureProp = (key, val) => {\n let exportsBefore = this.exports?.length ?? 0;\n try {\n let encoded = this.devaluateImpl(val, e, depth + 1);\n if (!props) props = {};\n props[key] = encoded;\n } catch (err) {\n if (this.exports && this.exports.length > exportsBefore) {\n let tail = this.exports.splice(exportsBefore);\n try {\n this.exporter.unexport(tail);\n } catch (err2) {\n }\n }\n }\n };\n for (let key of Object.keys(e)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n captureProp(key, anyE[key]);\n }\n if (\"cause\" in e) captureProp(\"cause\", anyE.cause);\n if (e instanceof AggregateError) captureProp(\"errors\", e.errors);\n let result = [\n \"error\",\n e.name,\n e.message\n ];\n if (props) {\n result.push(rewritten && rewritten.stack ? rewritten.stack : null);\n result.push(props);\n } else if (rewritten && rewritten.stack) result.push(rewritten.stack);\n return result;\n }\n case \"undefined\":\n if (this.encodingLevel === \"structuredClonable\") return;\n return [\"undefined\"];\n case \"stub\":\n case \"rpc-promise\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let { hook, pathIfPromise } = unwrapStubAndPath(value);\n let importId = this.exporter.getImport(hook);\n if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [\n \"pipeline\",\n importId,\n pathIfPromise\n ];\n else return [\"pipeline\", importId];\n else return [\"import\", importId];\n if (pathIfPromise) hook = hook.get(pathIfPromise);\n else hook = hook.dup();\n return this.devaluateHook(pathIfPromise ? \"promise\" : \"export\", hook);\n }\n case \"function\":\n case \"rpc-target\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"export\", hook);\n }\n case \"rpc-thenable\": {\n if (!this.source) throw new Error(\"Can't serialize RPC stubs in this context.\");\n let hook = this.source.getHookForRpcTarget(value, parent);\n return this.devaluateHook(\"promise\", hook);\n }\n case \"writable\": {\n if (!this.source) throw new Error(\"Can't serialize WritableStream in this context.\");\n let hook = this.source.getHookForWritableStream(value, parent);\n return this.devaluateHook(\"writable\", hook);\n }\n case \"readable\": {\n if (!this.source) throw new Error(\"Can't serialize ReadableStream in this context.\");\n let ws = value;\n let hook = this.source.getHookForReadableStream(ws, parent);\n return [\"readable\", this.exporter.createPipe(ws, hook)];\n }\n default:\n throw new Error(\"unreachable\");\n }\n }\n devaluateHook(type, hook) {\n if (!this.exports) this.exports = [];\n let exportId = type === \"promise\" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);\n this.exports.push(exportId);\n return [type, exportId];\n }\n};\nvar NullImporter = class {\n importStub(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n importPromise(idx) {\n throw new Error(\"Cannot deserialize RPC stubs without an RPC session.\");\n }\n getExport(idx) {\n }\n getPipeReadable(exportId) {\n throw new Error(\"Cannot retrieve pipe readable without an RPC session.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nvar NULL_IMPORTER = new NullImporter();\nfunction fixBrokenRequestBody(request, body) {\n return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {\n let bytes = new Uint8Array(arrayBuffer);\n let result = new Request(request, { body: bytes });\n return new PayloadStubHook(RpcPayload.fromAppReturn(result));\n })), []);\n}\nfunction streamToBlobPromise(stream, type) {\n return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {\n return new PayloadStubHook(RpcPayload.fromAppReturn(blob));\n })), []);\n}\nvar Evaluator = class Evaluator2 {\n importer;\n encodingLevel;\n limits;\n constructor(importer, encodingLevel = \"string\") {\n this.importer = importer;\n this.encodingLevel = encodingLevel;\n this.limits = importer.getLimits();\n }\n hooks = [];\n promises = [];\n evaluate(value) {\n return this.evaluateWithDepth(value, 0);\n }\n evaluateWithDepth(value, depth) {\n let payload = RpcPayload.forEvaluate(this.hooks, this.promises);\n try {\n payload.value = this.evaluateImpl(value, payload, \"value\", depth);\n return payload;\n } catch (err) {\n payload.dispose();\n throw err;\n }\n }\n evaluateCopy(value) {\n return this.evaluate(structuredClone(value));\n }\n evaluateImpl(value, parent, property, depth) {\n let maxDepth = this.limits.maxDepth;\n if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);\n if (this.encodingLevel === \"structuredClonable\") {\n if (value instanceof Date || typeof value === \"bigint\") return value;\n }\n if (value instanceof Array) {\n if (value.length == 1 && value[0] instanceof Array) {\n let result = value[0];\n for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);\n return result;\n } else switch (value[0]) {\n case \"bigint\":\n if (typeof value[1] == \"string\") {\n let digits = value[1];\n let maxBigIntDigits = this.limits.maxBigIntDigits;\n if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);\n return BigInt(digits);\n }\n break;\n case \"date\":\n if (value[1] === null) return /* @__PURE__ */ new Date(NaN);\n if (typeof value[1] == \"number\") return new Date(value[1]);\n break;\n case \"bytes\": {\n let bytes;\n if (value[1] instanceof Uint8Array) bytes = value[1];\n else if (typeof value[1] == \"string\") if (typeof Buffer !== \"undefined\") bytes = Buffer.from(value[1], \"base64\");\n else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);\n else {\n let bs = atob(value[1]);\n let len = bs.length;\n bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);\n }\n else break;\n if (value.length === 2) return bytes;\n if (typeof value[2] !== \"string\") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);\n if (!isValidByteContainerName(value[2])) {\n let marker2 = value[2].slice(0, 64);\n throw new TypeError(`Unknown bytes type marker: ${marker2}`);\n }\n let marker = value[2];\n let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];\n if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);\n let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);\n if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);\n switch (marker) {\n case \"ArrayBuffer\":\n return buffer;\n case \"DataView\":\n return new DataView(buffer);\n case \"Int8Array\":\n return new Int8Array(buffer);\n case \"Uint8Array\":\n return new Uint8Array(buffer);\n case \"Uint8ClampedArray\":\n return new Uint8ClampedArray(buffer);\n case \"Int16Array\":\n return new Int16Array(buffer);\n case \"Uint16Array\":\n return new Uint16Array(buffer);\n case \"Int32Array\":\n return new Int32Array(buffer);\n case \"Uint32Array\":\n return new Uint32Array(buffer);\n case \"BigInt64Array\":\n return new BigInt64Array(buffer);\n case \"BigUint64Array\":\n return new BigUint64Array(buffer);\n case \"Float32Array\":\n return new Float32Array(buffer);\n case \"Float64Array\":\n return new Float64Array(buffer);\n default:\n }\n }\n case \"error\":\n if (value.length >= 3 && typeof value[1] === \"string\" && typeof value[2] === \"string\") {\n let cls = ERROR_TYPES[value[1]] || Error;\n let result = cls === AggregateError ? new cls([], value[2]) : new cls(value[2]);\n if (typeof value[3] === \"string\") result.stack = value[3];\n if (value.length >= 5) {\n let props = value[4];\n if (!props || typeof props !== \"object\" || Array.isArray(props)) break;\n let anyResult = result;\n let propsObj = props;\n for (let key of Object.keys(propsObj)) {\n if (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(propsObj[key], result, key, depth + 1);\n continue;\n }\n anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);\n }\n }\n return result;\n }\n break;\n case \"undefined\":\n if (value.length === 1) return;\n break;\n case \"inf\":\n return Infinity;\n case \"-inf\":\n return -Infinity;\n case \"nan\":\n return NaN;\n case \"url\":\n if (value.length === 2 && typeof value[1] === \"string\") return new URL(value[1]);\n break;\n case \"headers\":\n if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);\n break;\n case \"request\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let url = value[1];\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.body) {\n init.body = this.evaluateImpl(init.body, init, \"body\", depth + 1);\n if (init.body === null || typeof init.body === \"string\" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) {\n } else throw new TypeError(\"Request body must be of type ReadableStream.\");\n }\n if (init.signal) {\n init.signal = this.evaluateImpl(init.signal, init, \"signal\", depth + 1);\n if (!(init.signal instanceof AbortSignal)) throw new TypeError(\"Request siganl must be of type AbortSignal.\");\n }\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n let result = new Request(url, init);\n if (init.body instanceof ReadableStream && result.body === void 0) {\n let promise = fixBrokenRequestBody(result, init.body);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else return result;\n }\n case \"response\": {\n if (value.length !== 3) break;\n let body = this.evaluateImpl(value[1], parent, property, depth + 1);\n if (body === null || typeof body === \"string\" || body instanceof Uint8Array || body instanceof ReadableStream) {\n } else throw new TypeError(\"Response body must be of type ReadableStream.\");\n let init = value[2];\n if (typeof init !== \"object\" || init === null) break;\n if (init.webSocket) throw new TypeError(\"Can't deserialize a Response containing a webSocket.\");\n if (init.headers && !(init.headers instanceof Array)) throw new TypeError(\"Request headers must be serialized as an array of pairs.\");\n return new Response(body, init);\n }\n case \"blob\": {\n if (value.length !== 3 || typeof value[1] !== \"string\") break;\n let contentType = value[1];\n let content = this.evaluateImpl(value[2], parent, property, depth + 1);\n if (!(content instanceof ReadableStream)) throw new TypeError(\"Blob content must be serialized as a ReadableStream.\");\n let promise = streamToBlobPromise(content, contentType);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"import\":\n case \"pipeline\": {\n if (value.length < 2 || value.length > 4) break;\n if (typeof value[1] != \"number\") break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let isPromise = value[0] == \"pipeline\";\n let addStub = (hook2) => {\n if (isPromise) {\n let promise = new RpcPromise$1(hook2, []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n } else {\n this.hooks.push(hook2);\n return new RpcPromise$1(hook2, []);\n }\n };\n if (value.length == 2) if (isPromise) return addStub(hook.get([]));\n else return addStub(hook.dup());\n let path = value[2];\n if (!(path instanceof Array)) break;\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n if (value.length == 3) return addStub(hook.get(path));\n let args = value[3];\n if (!(args instanceof Array)) break;\n args = new Evaluator2(this.importer).evaluateWithDepth([args], depth);\n return addStub(hook.call(path, args));\n }\n case \"remap\": {\n if (value.length !== 5 || typeof value[1] !== \"number\" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) break;\n let hook = this.importer.getExport(value[1]);\n if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);\n let path = value[2];\n if (!path.every((part) => {\n return typeof part == \"string\" || typeof part == \"number\";\n })) break;\n let captures = value[3].map((cap) => {\n if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== \"import\" && cap[0] !== \"export\" || typeof cap[1] !== \"number\") throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);\n if (cap[0] === \"export\") return this.importer.importStub(cap[1]);\n else {\n let exp = this.importer.getExport(cap[1]);\n if (!exp) throw new Error(`no such entry on exports table: ${cap[1]}`);\n return exp.dup();\n }\n });\n let instructions = value[4];\n let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);\n this.promises.push({\n promise,\n parent,\n property\n });\n return promise;\n }\n case \"export\":\n case \"promise\":\n if (typeof value[1] == \"number\") if (value[0] == \"promise\") {\n let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);\n this.promises.push({\n parent,\n property,\n promise\n });\n return promise;\n } else {\n let hook = this.importer.importStub(value[1]);\n this.hooks.push(hook);\n return new RpcStub$1(hook);\n }\n break;\n case \"writable\":\n if (typeof value[1] == \"number\") {\n let hook = this.importer.importStub(value[1]);\n let stream = streamImpl.createWritableStreamFromHook(hook);\n this.hooks.push(hook);\n return stream;\n }\n break;\n case \"readable\":\n if (typeof value[1] == \"number\") {\n let stream = this.importer.getPipeReadable(value[1]);\n let hook = streamImpl.createReadableStreamHook(stream);\n this.hooks.push(hook);\n return stream;\n }\n break;\n }\n throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);\n } else if (value instanceof Object) {\n let result = value;\n for (let key in result) if (key in Object.prototype || key === \"toJSON\") {\n this.evaluateImpl(result[key], result, key, depth + 1);\n delete result[key];\n } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);\n return result;\n } else return value;\n }\n};\nvar ESTIMATED_OBJECT_OVERHEAD = 16;\nvar ESTIMATED_ENTRY_OVERHEAD = 8;\nvar ESTIMATED_BINARY_OVERHEAD = 16;\nvar MAX_ESTIMATE_DEPTH = 64;\nfunction estimateStringSize(value) {\n return 2 + value.length * 3;\n}\nfunction estimateEncodedSize(value, seen, depth = 0) {\n if (depth >= MAX_ESTIMATE_DEPTH) return ESTIMATED_ENTRY_OVERHEAD;\n switch (typeof value) {\n case \"string\":\n return estimateStringSize(value);\n case \"number\":\n return 16;\n case \"bigint\":\n return 16;\n case \"boolean\":\n return 8;\n case \"undefined\":\n return 16;\n case \"object\": {\n if (value === null) return 8;\n if (ArrayBuffer.isView(value)) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;\n if (value instanceof Date) return 16;\n seen ??= /* @__PURE__ */ new WeakSet();\n if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;\n seen.add(value);\n if (value instanceof Array) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD;\n for (let item of value) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateEncodedSize(item, seen, depth + 1);\n return size2;\n }\n if (value instanceof Error) {\n let size2 = ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.name) + estimateStringSize(value.message) + estimateStringSize(value.stack ?? \"\");\n for (let key of Object.keys(value)) size2 += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size2;\n }\n let size = ESTIMATED_OBJECT_OVERHEAD;\n for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);\n return size;\n }\n default:\n return 16;\n }\n}\nvar ImportTableEntry = class {\n session;\n importId;\n constructor(session, importId, pulling) {\n this.session = session;\n this.importId = importId;\n if (pulling) this.activePull = Promise.withResolvers();\n }\n localRefcount = 0;\n remoteRefcount = 1;\n activePull;\n resolution;\n onBrokenRegistrations;\n resolve(resolution) {\n if (this.localRefcount == 0) {\n resolution.dispose();\n return;\n }\n this.resolution = resolution;\n this.sendRelease();\n if (this.onBrokenRegistrations) {\n for (let i of this.onBrokenRegistrations) {\n let callback = this.session.onBrokenCallbacks[i];\n let endIndex = this.session.onBrokenCallbacks.length;\n resolution.onBroken(callback);\n if (this.session.onBrokenCallbacks[endIndex] === callback) delete this.session.onBrokenCallbacks[endIndex];\n else delete this.session.onBrokenCallbacks[i];\n }\n this.onBrokenRegistrations = void 0;\n }\n if (this.activePull) {\n this.activePull.resolve();\n this.activePull = void 0;\n }\n }\n async awaitResolution() {\n if (!this.activePull) {\n this.session.sendPull(this.importId);\n this.activePull = Promise.withResolvers();\n }\n await this.activePull.promise;\n return this.resolution.pull();\n }\n dispose() {\n if (this.resolution) this.resolution.dispose();\n else {\n this.abort(/* @__PURE__ */ new Error(\"RPC was canceled because the RpcPromise was disposed.\"));\n this.sendRelease();\n }\n }\n abort(error) {\n if (!this.resolution) {\n this.resolution = new ErrorStubHook(error);\n if (this.activePull) {\n this.activePull.reject(error);\n this.activePull = void 0;\n }\n this.onBrokenRegistrations = void 0;\n }\n }\n onBroken(callback) {\n if (this.resolution) this.resolution.onBroken(callback);\n else {\n let index = this.session.onBrokenCallbacks.length;\n this.session.onBrokenCallbacks.push(callback);\n if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];\n this.onBrokenRegistrations.push(index);\n }\n }\n sendRelease() {\n if (this.remoteRefcount > 0) {\n this.session.sendRelease(this.importId, this.remoteRefcount);\n this.remoteRefcount = 0;\n }\n }\n};\nvar RpcImportHook = class RpcImportHook2 extends StubHook {\n isPromise;\n entry;\n constructor(isPromise, entry) {\n super();\n this.isPromise = isPromise;\n ++entry.localRefcount;\n this.entry = entry;\n }\n collectPath(path) {\n return this;\n }\n getEntry() {\n if (this.entry) return this.entry;\n else throw new Error(\"This RpcImportHook was already disposed.\");\n }\n getEntryTakingOwnership(disposeOwned) {\n try {\n return this.getEntry();\n } catch (err) {\n disposeOwned();\n throw err;\n }\n }\n call(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.call(path, args);\n else return entry.session.sendCall(entry.importId, path, args);\n }\n stream(path, args) {\n let entry = this.getEntryTakingOwnership(() => args.dispose());\n if (entry.resolution) return entry.resolution.stream(path, args);\n else return entry.session.sendStream(entry.importId, path, args);\n }\n map(path, captures, instructions) {\n let entry = this.getEntryTakingOwnership(() => {\n for (let cap of captures) cap.dispose();\n });\n if (entry.resolution) return entry.resolution.map(path, captures, instructions);\n else return entry.session.sendMap(entry.importId, path, captures, instructions);\n }\n get(path) {\n let entry = this.getEntry();\n if (entry.resolution) return entry.resolution.get(path);\n else return entry.session.sendCall(entry.importId, path);\n }\n dup() {\n return new RpcImportHook2(false, this.getEntry());\n }\n pull() {\n let entry = this.getEntry();\n if (!this.isPromise) throw new Error(\"Can't pull this hook because it's not a promise hook.\");\n if (entry.resolution) return entry.resolution.pull();\n return entry.awaitResolution();\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let entry = this.entry;\n this.entry = void 0;\n if (entry) {\n if (--entry.localRefcount === 0) entry.dispose();\n }\n }\n onBroken(callback) {\n if (this.entry) this.entry.onBroken(callback);\n }\n};\nvar RpcMainHook = class extends RpcImportHook {\n session;\n constructor(entry) {\n super(false, entry);\n this.session = entry.session;\n }\n dispose() {\n if (this.session) {\n let session = this.session;\n this.session = void 0;\n session.shutdown();\n }\n }\n};\nvar RpcSessionImpl = class {\n transport;\n options;\n exports = [];\n reverseExports = /* @__PURE__ */ new Map();\n imports = [];\n abortReason;\n cancelReadLoop;\n nextExportId = -1;\n onBatchDone;\n pullCount = 0;\n onBrokenCallbacks = [];\n encodingLevel;\n limits;\n constructor(transport, mainHook, options) {\n this.transport = transport;\n this.options = options;\n let level = \"string\";\n if (\"encodingLevel\" in transport) {\n let raw = transport.encodingLevel;\n if (raw !== void 0) {\n if (raw !== \"string\" && raw !== \"jsonCompatible\" && raw !== \"jsonCompatibleWithBytes\" && raw !== \"structuredClonable\") throw new TypeError(`Unknown transport encodingLevel: ${String(raw)}`);\n level = raw;\n }\n }\n this.encodingLevel = level;\n this.limits = {\n ...DEFAULT_LIMITS,\n ...options.limits\n };\n this.exports.push({\n hook: mainHook,\n refcount: 1\n });\n this.imports.push(new ImportTableEntry(this, 0, false));\n this.readLoop().catch((err) => this.abort(err));\n }\n getMainImport() {\n return new RpcMainHook(this.imports[0]);\n }\n shutdown() {\n this.abort(/* @__PURE__ */ new Error(\"RPC session was shut down by disposing the main stub\"), false);\n }\n exportStub(hook) {\n if (this.abortReason) throw this.abortReason;\n let existingExportId = this.reverseExports.get(hook);\n if (existingExportId !== void 0) {\n ++this.exports[existingExportId].refcount;\n return existingExportId;\n } else {\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n return exportId;\n }\n }\n exportPromise(hook) {\n if (this.abortReason) throw this.abortReason;\n let exportId = this.nextExportId--;\n this.exports[exportId] = {\n hook,\n refcount: 1\n };\n this.reverseExports.set(hook, exportId);\n this.ensureResolvingExport(exportId);\n return exportId;\n }\n unexport(ids) {\n for (let id of ids) this.releaseExport(id, 1);\n }\n releaseExport(exportId, refcount) {\n let entry = this.exports[exportId];\n if (!entry) throw new Error(`no such export ID: ${exportId}`);\n if (entry.refcount < refcount) throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);\n entry.refcount -= refcount;\n if (entry.refcount === 0) {\n delete this.exports[exportId];\n this.reverseExports.delete(entry.hook);\n entry.hook.dispose();\n }\n }\n onSendError(error) {\n if (this.options.onSendError) return this.options.onSendError(error);\n }\n ensureResolvingExport(exportId) {\n let exp = this.exports[exportId];\n if (!exp) throw new Error(`no such export ID: ${exportId}`);\n if (!exp.pull) {\n let resolve = async () => {\n let hook = exp.hook;\n for (; ; ) {\n let payload = await hook.pull();\n if (payload.value instanceof RpcStub$1) {\n let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);\n if (pathIfPromise && pathIfPromise.length == 0) {\n if (this.getImport(hook) === void 0) {\n hook = inner;\n continue;\n }\n }\n }\n return payload;\n }\n };\n let autoRelease = exp.autoRelease;\n ++this.pullCount;\n exp.pull = resolve().then((payload) => {\n let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);\n this.send([\n \"resolve\",\n exportId,\n value\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }, (error) => {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n }).catch((error) => {\n try {\n this.send([\n \"reject\",\n exportId,\n Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)\n ]);\n if (autoRelease) this.releaseExport(exportId, 1);\n } catch (error2) {\n this.abort(error2);\n }\n }).finally(() => {\n if (--this.pullCount === 0) {\n if (this.onBatchDone) this.onBatchDone.resolve();\n }\n });\n }\n }\n getImport(hook) {\n if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;\n else return;\n }\n importStub(idx) {\n if (this.abortReason) throw this.abortReason;\n let entry = this.imports[idx];\n if (!entry) {\n entry = new ImportTableEntry(this, idx, false);\n this.imports[idx] = entry;\n }\n return new RpcImportHook(false, entry);\n }\n importPromise(idx) {\n if (this.abortReason) throw this.abortReason;\n if (this.imports[idx]) return new ErrorStubHook(/* @__PURE__ */ new Error(\"Bug in RPC system: The peer sent a promise reusing an existing export ID.\"));\n let entry = new ImportTableEntry(this, idx, true);\n this.imports[idx] = entry;\n return new RpcImportHook(true, entry);\n }\n getExport(idx) {\n return this.exports[idx]?.hook;\n }\n getPipeReadable(exportId) {\n let entry = this.exports[exportId];\n if (!entry || !entry.pipeReadable) throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);\n let readable = entry.pipeReadable;\n entry.pipeReadable = void 0;\n return readable;\n }\n getLimits() {\n return this.limits;\n }\n createPipe(readable, readableHook) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pipe\"]);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, false);\n this.imports.push(entry);\n let hook = new RpcImportHook(false, entry);\n let writable = streamImpl.createWritableStreamFromHook(hook);\n readable.pipeTo(writable).catch(() => {\n }).finally(() => readableHook.dispose());\n return importId;\n }\n send(msg) {\n if (this.abortReason !== void 0) return 0;\n if (this.encodingLevel === \"string\") {\n let msgText;\n try {\n msgText = JSON.stringify(msg);\n } catch (err) {\n try {\n this.abort(err);\n } catch (err2) {\n }\n throw err;\n }\n try {\n let sent = this.transport.send(msgText);\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => this.abort(err, false));\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n }\n return msgText.length;\n } else try {\n let size = this.transport.send(msg);\n if (typeof size === \"number\") return size;\n let thenable = size;\n if (thenable && typeof thenable.then === \"function\") Promise.resolve(thenable).catch((err) => this.abort(err, false));\n return;\n } catch (err) {\n queueMicrotask(() => this.abort(err, false));\n return;\n }\n }\n sendCall(id, path, args) {\n if (this.abortReason) {\n args?.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n if (args) {\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n }\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendStream(id, path, args) {\n if (this.abortReason) {\n args.dispose();\n throw this.abortReason;\n }\n let value = [\n \"pipeline\",\n id,\n path\n ];\n let devalue;\n try {\n devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);\n } catch (err) {\n args.dispose();\n throw err;\n }\n value.push(devalue[0]);\n let msg = [\"stream\", value];\n let size = this.send(msg);\n if (size === void 0) size = estimateEncodedSize(msg);\n let importId = this.imports.length;\n let entry = new ImportTableEntry(this, importId, true);\n entry.remoteRefcount = 0;\n entry.localRefcount = 1;\n this.imports.push(entry);\n return {\n promise: entry.awaitResolution().then((p) => {\n p.dispose();\n delete this.imports[importId];\n }, (err) => {\n delete this.imports[importId];\n throw err;\n }),\n size\n };\n }\n sendMap(id, path, captures, instructions) {\n if (this.abortReason) {\n for (let cap of captures) cap.dispose();\n throw this.abortReason;\n }\n let value = [\n \"remap\",\n id,\n path,\n captures.map((hook) => {\n let importId = this.getImport(hook);\n if (importId !== void 0) return [\"import\", importId];\n else return [\"export\", this.exportStub(hook)];\n }),\n instructions\n ];\n this.send([\"push\", value]);\n let entry = new ImportTableEntry(this, this.imports.length, false);\n this.imports.push(entry);\n return new RpcImportHook(true, entry);\n }\n sendPull(id) {\n if (this.abortReason) throw this.abortReason;\n this.send([\"pull\", id]);\n }\n sendRelease(id, remoteRefcount) {\n if (this.abortReason) return;\n this.send([\n \"release\",\n id,\n remoteRefcount\n ]);\n delete this.imports[id];\n }\n abort(error, trySendAbortMessage = true) {\n if (this.abortReason !== void 0) return;\n this.cancelReadLoop?.(error);\n this.cancelReadLoop = void 0;\n if (trySendAbortMessage) try {\n let abortMsg = [\"abort\", Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)];\n if (this.encodingLevel === \"string\") {\n let sent = this.transport.send(JSON.stringify(abortMsg));\n if (sent !== void 0 && typeof sent.catch === \"function\") sent.catch((err) => {\n });\n } else {\n let result = this.transport.send(abortMsg);\n if (result && typeof result.then === \"function\") Promise.resolve(result).catch((err) => {\n });\n }\n } catch (err) {\n }\n if (error === void 0) error = \"undefined\";\n this.abortReason = error;\n if (this.onBatchDone) this.onBatchDone.reject(error);\n if (this.transport.abort) try {\n this.transport.abort(error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.onBrokenCallbacks) try {\n this.onBrokenCallbacks[i](error);\n } catch (err) {\n Promise.resolve(err);\n }\n for (let i in this.imports) this.imports[i].abort(error);\n for (let i in this.exports) this.exports[i].hook.dispose();\n }\n async readLoop() {\n while (!this.abortReason) {\n let readCanceled = Promise.withResolvers();\n this.cancelReadLoop = readCanceled.reject;\n let raw;\n try {\n raw = await Promise.race([this.transport.receive(), readCanceled.promise]);\n } finally {\n if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;\n }\n if (this.encodingLevel === \"string\" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);\n if (this.abortReason) break;\n let msg = this.encodingLevel === \"string\" ? JSON.parse(raw) : raw;\n if (msg instanceof Array) switch (msg[0]) {\n case \"push\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n this.exports.push({\n hook,\n refcount: 1\n });\n continue;\n }\n break;\n case \"stream\":\n if (msg.length > 1) {\n let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));\n hook.ignoreUnhandledRejections();\n let exportId = this.exports.length;\n this.exports.push({\n hook,\n refcount: 1,\n autoRelease: true\n });\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n case \"pipe\": {\n let { readable, writable } = new TransformStream();\n let hook = streamImpl.createWritableStreamHook(writable);\n this.exports.push({\n hook,\n refcount: 1,\n pipeReadable: readable\n });\n continue;\n }\n case \"pull\": {\n let exportId = msg[1];\n if (typeof exportId == \"number\") {\n this.ensureResolvingExport(exportId);\n continue;\n }\n break;\n }\n case \"resolve\":\n case \"reject\": {\n let importId = msg[1];\n if (typeof importId == \"number\" && msg.length > 2) {\n let imp = this.imports[importId];\n if (imp) if (msg[0] == \"resolve\") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));\n else {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);\n payload.dispose();\n imp.resolve(new ErrorStubHook(payload.value));\n }\n else if (msg[0] == \"resolve\") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();\n continue;\n }\n break;\n }\n case \"release\": {\n let exportId = msg[1];\n let refcount = msg[2];\n if (typeof exportId == \"number\" && typeof refcount == \"number\") {\n this.releaseExport(exportId, refcount);\n continue;\n }\n break;\n }\n case \"abort\": {\n let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);\n payload.dispose();\n this.abort(payload.value, false);\n break;\n }\n }\n throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);\n }\n }\n async drain() {\n if (this.abortReason) throw this.abortReason;\n if (this.pullCount > 0) {\n let { promise, resolve, reject } = Promise.withResolvers();\n this.onBatchDone = {\n resolve,\n reject\n };\n await promise;\n }\n }\n getStats() {\n let result = {\n imports: 0,\n exports: 0\n };\n for (let i in this.imports) ++result.imports;\n for (let i in this.exports) ++result.exports;\n return result;\n }\n};\nvar RpcSession$1 = class {\n #session;\n #mainStub;\n constructor(transport, localMain, options = {}) {\n let mainHook;\n if (localMain) mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));\n else mainHook = new ErrorStubHook(/* @__PURE__ */ new Error(\"This connection has no main object.\"));\n this.#session = new RpcSessionImpl(transport, mainHook, options);\n this.#mainStub = new RpcStub$1(this.#session.getMainImport());\n }\n getRemoteMain() {\n return this.#mainStub;\n }\n getStats() {\n return this.#session.getStats();\n }\n drain() {\n return this.#session.drain();\n }\n};\nfunction newWebSocketRpcSession$1(webSocket, localMain, options) {\n if (typeof webSocket === \"string\") webSocket = new WebSocket(webSocket);\n return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();\n}\nfunction newWorkersWebSocketRpcResponse(request, localMain, options) {\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") return new Response(\"This endpoint only accepts WebSocket requests.\", { status: 400 });\n let pair = new WebSocketPair();\n let server = pair[0];\n server.accept();\n newWebSocketRpcSession$1(server, localMain, options);\n return new Response(null, {\n status: 101,\n webSocket: pair[1]\n });\n}\nvar WebSocketTransport = class {\n constructor(webSocket) {\n this.#webSocket = webSocket;\n webSocket.binaryType = \"arraybuffer\";\n if (webSocket.readyState === WebSocket.CONNECTING) {\n this.#sendQueue = [];\n webSocket.addEventListener(\"open\", (event) => {\n try {\n for (let message of this.#sendQueue) webSocket.send(message);\n } catch (err) {\n this.#receivedError(err);\n }\n this.#sendQueue = void 0;\n });\n }\n webSocket.addEventListener(\"message\", (event) => {\n if (this.#error) {\n } else if (typeof event.data === \"string\" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {\n this.#receiveResolver(event.data);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n } else this.#receiveQueue.push(event.data);\n else this.#receivedError(/* @__PURE__ */ new TypeError(\"Received unexpected message type from WebSocket.\"));\n });\n webSocket.addEventListener(\"close\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));\n });\n webSocket.addEventListener(\"error\", (event) => {\n this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));\n });\n }\n #webSocket;\n #sendQueue;\n #receiveResolver;\n #receiveRejecter;\n #receiveQueue = [];\n #error;\n send(message) {\n if (this.#sendQueue === void 0) this.#webSocket.send(message);\n else this.#sendQueue.push(message);\n }\n receive() {\n if (this.#receiveQueue.length > 0) return Promise.resolve(this.#receiveQueue.shift());\n else if (this.#error) return Promise.reject(this.#error);\n else return new Promise((resolve, reject) => {\n this.#receiveResolver = resolve;\n this.#receiveRejecter = reject;\n });\n }\n abort(reason) {\n let message;\n if (reason instanceof Error) message = reason.message;\n else message = `${reason}`;\n let reasonBytes = new TextEncoder().encode(message);\n if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });\n this.#webSocket.close(3e3, message);\n if (!this.#error) this.#error = reason;\n }\n #receivedError(reason) {\n if (!this.#error) {\n this.#error = reason;\n if (this.#receiveRejecter) {\n this.#receiveRejecter(reason);\n this.#receiveResolver = void 0;\n this.#receiveRejecter = void 0;\n }\n }\n }\n};\nvar BatchServerTransport = class {\n constructor(batch) {\n this.#batchToReceive = batch;\n }\n #batchToSend = [];\n #batchToReceive;\n #allReceived = Promise.withResolvers();\n send(message) {\n this.#batchToSend.push(message);\n }\n async receive() {\n let msg = this.#batchToReceive.shift();\n if (msg !== void 0) return msg;\n else {\n this.#allReceived.resolve();\n return new Promise((r) => {\n });\n }\n }\n abort(reason) {\n this.#allReceived.reject(reason);\n }\n whenAllReceived() {\n return this.#allReceived.promise;\n }\n getResponseBody() {\n return this.#batchToSend.join(\"\\n\");\n }\n};\nasync function newHttpBatchRpcResponse(request, localMain, options) {\n if (request.method !== \"POST\") return new Response(\"This endpoint only accepts POST requests.\", { status: 405 });\n let body = await request.text();\n let transport = new BatchServerTransport(body === \"\" ? [] : body.split(\"\\n\"));\n let rpc = new RpcSession$1(transport, localMain, options);\n await transport.whenAllReceived();\n await rpc.drain();\n return new Response(transport.getResponseBody());\n}\nvar currentMapBuilder;\nvar MapBuilder = class {\n context;\n captureMap = /* @__PURE__ */ new Map();\n instructions = [];\n constructor(subject, path) {\n if (currentMapBuilder) this.context = {\n parent: currentMapBuilder,\n captures: [],\n subject: currentMapBuilder.capture(subject),\n path\n };\n else this.context = {\n parent: void 0,\n captures: [],\n subject,\n path\n };\n currentMapBuilder = this;\n }\n unregister() {\n currentMapBuilder = this.context.parent;\n }\n makeInput() {\n return new MapVariableHook(this, 0);\n }\n makeOutput(result) {\n let devalued;\n try {\n devalued = Devaluator.devaluate(result.value, void 0, this, result);\n } finally {\n result.dispose();\n }\n this.instructions.push(devalued);\n if (this.context.parent) {\n this.context.parent.instructions.push([\n \"remap\",\n this.context.subject,\n this.context.path,\n this.context.captures.map((cap) => [\"import\", cap]),\n this.instructions\n ]);\n return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);\n } else return this.context.subject.map(this.context.path, this.context.captures, this.instructions);\n }\n pushCall(hook, path, params) {\n let devalued = Devaluator.devaluate(params.value, void 0, this, params);\n devalued = devalued[0];\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path,\n devalued\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n pushGet(hook, path) {\n let subject = this.capture(hook.dup());\n this.instructions.push([\n \"pipeline\",\n subject,\n path\n ]);\n return new MapVariableHook(this, this.instructions.length);\n }\n capture(hook) {\n if (hook instanceof MapVariableHook && hook.mapper === this) return hook.idx;\n let result = this.captureMap.get(hook);\n if (result === void 0) {\n if (this.context.parent) {\n let parentIdx = this.context.parent.capture(hook);\n this.context.captures.push(parentIdx);\n } else this.context.captures.push(hook);\n result = -this.context.captures.length;\n this.captureMap.set(hook, result);\n }\n return result;\n }\n exportStub(hook) {\n throw new Error(\"Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.\");\n }\n exportPromise(hook) {\n return this.exportStub(hook);\n }\n getImport(hook) {\n return this.capture(hook);\n }\n unexport(ids) {\n }\n createPipe(readable) {\n throw new Error(\"Cannot send ReadableStream inside a mapper function.\");\n }\n onSendError(error) {\n }\n};\nmapImpl.sendMap = (hook, path, func) => {\n let builder = new MapBuilder(hook, path);\n let result;\n try {\n result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {\n return func(new RpcPromise$1(builder.makeInput(), []));\n }));\n } finally {\n builder.unregister();\n }\n if (result instanceof Promise) {\n result.catch((err) => {\n });\n throw new Error(\"RPC map() callbacks cannot be async.\");\n }\n return new RpcPromise$1(builder.makeOutput(result), []);\n};\nfunction throwMapperBuilderUseError() {\n throw new Error(\"Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.\");\n}\nvar MapVariableHook = class extends StubHook {\n mapper;\n idx;\n constructor(mapper, idx) {\n super();\n this.mapper = mapper;\n this.idx = idx;\n }\n dup() {\n return this;\n }\n dispose() {\n }\n get(path) {\n if (path.length == 0) return this;\n else if (currentMapBuilder) return currentMapBuilder.pushGet(this, path);\n else throwMapperBuilderUseError();\n }\n call(path, args) {\n args.dispose();\n throwMapperBuilderUseError();\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n throwMapperBuilderUseError();\n }\n pull() {\n throwMapperBuilderUseError();\n }\n ignoreUnhandledRejections() {\n }\n onBroken(callback) {\n throwMapperBuilderUseError();\n }\n};\nvar MapApplicator = class {\n captures;\n variables;\n constructor(captures, input) {\n this.captures = captures;\n this.variables = [input];\n }\n dispose() {\n for (let variable of this.variables) variable.dispose();\n }\n apply(instructions) {\n try {\n if (instructions.length < 1) throw new Error(\"Invalid empty mapper function.\");\n for (let instruction of instructions.slice(0, -1)) {\n let payload = new Evaluator(this).evaluateCopy(instruction);\n if (payload.value instanceof RpcStub$1) {\n let hook = unwrapStubNoProperties(payload.value);\n if (hook) {\n this.variables.push(hook);\n continue;\n }\n }\n this.variables.push(new PayloadStubHook(payload));\n }\n return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);\n } finally {\n for (let variable of this.variables) variable.dispose();\n }\n }\n importStub(idx) {\n throw new Error(\"A mapper function cannot refer to exports.\");\n }\n importPromise(idx) {\n return this.importStub(idx);\n }\n getExport(idx) {\n if (idx < 0) return this.captures[-idx - 1];\n else return this.variables[idx];\n }\n getPipeReadable(exportId) {\n throw new Error(\"A mapper function cannot use pipe readables.\");\n }\n getLimits() {\n return DEFAULT_LIMITS;\n }\n};\nfunction applyMapToElement(input, parent, owner, captures, instructions) {\n let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));\n try {\n return mapper.apply(instructions);\n } finally {\n mapper.dispose();\n }\n}\nmapImpl.applyMap = (input, parent, owner, captures, instructions) => {\n try {\n let result;\n if (input instanceof RpcPromise$1) throw new Error(\"applyMap() can't be called on RpcPromise\");\n else if (input instanceof Array) {\n let payloads = [];\n try {\n for (let elem of input) payloads.push(applyMapToElement(elem, input, owner, captures, instructions));\n } catch (err) {\n for (let payload of payloads) payload.dispose();\n throw err;\n }\n result = RpcPayload.fromArray(payloads);\n } else if (input === null || input === void 0) result = RpcPayload.fromAppReturn(input);\n else result = applyMapToElement(input, parent, owner, captures, instructions);\n return new PayloadStubHook(result);\n } finally {\n for (let cap of captures) cap.dispose();\n }\n};\nvar WritableStreamStubHook = class WritableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new WritableStreamStubHook2({\n refcount: 1,\n writer: stream.getWriter(),\n closed: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n getState() {\n if (this.state) return this.state;\n else throw new Error(\"Attempted to use a WritableStreamStubHook after it was disposed.\");\n }\n call(path, args) {\n try {\n let state = this.getState();\n if (path.length !== 1 || typeof path[0] !== \"string\") throw new Error(\"WritableStream stub only supports direct method calls\");\n const method = path[0];\n if (method !== \"write\" && method !== \"close\" && method !== \"abort\") throw new Error(`Unknown WritableStream method: ${method}`);\n if (method === \"close\" || method === \"abort\") state.closed = true;\n return new PromiseStubHook((method === \"write\" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));\n } catch (err) {\n args.dispose();\n return new ErrorStubHook(err);\n }\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a WritableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a WritableStream stub\"));\n }\n dup() {\n return new WritableStreamStubHook2(this.getState(), this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a WritableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.closed) state.writer.abort(/* @__PURE__ */ new Error(\"WritableStream RPC stub was disposed without calling close()\")).catch(() => {\n });\n state.writer.releaseLock();\n }\n }\n }\n onBroken(callback) {\n }\n};\nvar INITIAL_WINDOW = 256 * 1024;\nvar MAX_WINDOW = 1024 * 1024 * 1024;\nvar MIN_WINDOW = 64 * 1024;\nvar STARTUP_GROWTH_FACTOR = 2;\nvar STEADY_GROWTH_FACTOR = 1.25;\nvar DECAY_FACTOR = 0.9;\nvar STARTUP_EXIT_ROUNDS = 3;\nvar FlowController = class {\n now;\n window = INITIAL_WINDOW;\n bytesInFlight = 0;\n inStartupPhase = true;\n delivered = 0;\n deliveredTime = 0;\n firstAckTime = 0;\n firstAckDelivered = 0;\n minRtt = Infinity;\n roundsWithoutIncrease = 0;\n lastRoundWindow = 0;\n roundStartTime = 0;\n constructor(now) {\n this.now = now;\n }\n onSend(size) {\n this.bytesInFlight += size;\n let token = {\n sentTime: this.now(),\n size,\n deliveredAtSend: this.delivered,\n deliveredTimeAtSend: this.deliveredTime,\n windowAtSend: this.window,\n windowFullAtSend: this.bytesInFlight >= this.window\n };\n return {\n token,\n shouldBlock: token.windowFullAtSend\n };\n }\n onError(token) {\n this.bytesInFlight -= token.size;\n }\n onAck(token) {\n let ackTime = this.now();\n this.delivered += token.size;\n this.deliveredTime = ackTime;\n this.bytesInFlight -= token.size;\n let rtt = ackTime - token.sentTime;\n this.minRtt = Math.min(this.minRtt, rtt);\n if (this.firstAckTime === 0) {\n this.firstAckTime = ackTime;\n this.firstAckDelivered = this.delivered;\n } else {\n let baseTime;\n let baseDelivered;\n if (token.deliveredTimeAtSend === 0) {\n baseTime = this.firstAckTime;\n baseDelivered = this.firstAckDelivered;\n } else {\n baseTime = token.deliveredTimeAtSend;\n baseDelivered = token.deliveredAtSend;\n }\n let interval = ackTime - baseTime;\n let bandwidth = (this.delivered - baseDelivered) / interval;\n let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;\n let newWindow = bandwidth * this.minRtt * growthFactor;\n newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);\n if (token.windowFullAtSend) newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);\n else newWindow = Math.max(newWindow, this.window);\n this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);\n if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {\n if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) this.roundsWithoutIncrease = 0;\n else if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) this.inStartupPhase = false;\n this.roundStartTime = ackTime;\n this.lastRoundWindow = this.window;\n }\n }\n return this.bytesInFlight < this.window;\n }\n};\nfunction createWritableStreamFromHook(hook) {\n let pendingError = void 0;\n let hookDisposed = false;\n let fc = new FlowController(() => performance.now());\n let windowResolve;\n let windowReject;\n const disposeHook = () => {\n if (!hookDisposed) {\n hookDisposed = true;\n hook.dispose();\n }\n };\n return new WritableStream({\n write(chunk, controller) {\n if (pendingError !== void 0) throw pendingError;\n const payload = RpcPayload.fromAppParams([chunk]);\n const { promise, size } = hook.stream([\"write\"], payload);\n if (size === void 0) return promise.catch((err) => {\n if (pendingError === void 0) pendingError = err;\n throw err;\n });\n else {\n let { token, shouldBlock } = fc.onSend(size);\n promise.then(() => {\n if (fc.onAck(token) && windowResolve) {\n windowResolve();\n windowResolve = void 0;\n windowReject = void 0;\n }\n }, (err) => {\n fc.onError(token);\n if (pendingError === void 0) {\n pendingError = err;\n controller.error(err);\n disposeHook();\n }\n if (windowReject) {\n windowReject(err);\n windowResolve = void 0;\n windowReject = void 0;\n }\n });\n if (shouldBlock) return new Promise((resolve, reject) => {\n windowResolve = resolve;\n windowReject = reject;\n });\n }\n },\n async close() {\n if (pendingError !== void 0) {\n disposeHook();\n throw pendingError;\n }\n const { promise } = hook.stream([\"close\"], RpcPayload.fromAppParams([]));\n try {\n await promise;\n } catch (err) {\n throw pendingError ?? err;\n } finally {\n disposeHook();\n }\n },\n abort(reason) {\n if (pendingError !== void 0) return;\n pendingError = reason ?? /* @__PURE__ */ new Error(\"WritableStream was aborted\");\n if (windowReject) {\n windowReject(pendingError);\n windowResolve = void 0;\n windowReject = void 0;\n }\n const { promise } = hook.stream([\"abort\"], RpcPayload.fromAppParams([reason]));\n promise.then(() => disposeHook(), () => disposeHook());\n }\n });\n}\nvar ReadableStreamStubHook = class ReadableStreamStubHook2 extends StubHook {\n state;\n static create(stream) {\n return new ReadableStreamStubHook2({\n refcount: 1,\n stream,\n canceled: false\n });\n }\n constructor(state, dupFrom) {\n super();\n this.state = state;\n if (dupFrom) ++state.refcount;\n }\n call(path, args) {\n args.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot call methods on a ReadableStream stub\"));\n }\n map(path, captures, instructions) {\n for (let cap of captures) cap.dispose();\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot use map() on a ReadableStream\"));\n }\n get(path) {\n return new ErrorStubHook(/* @__PURE__ */ new Error(\"Cannot access properties on a ReadableStream stub\"));\n }\n dup() {\n let state = this.state;\n if (!state) throw new Error(\"Attempted to dup a ReadableStreamStubHook after it was disposed.\");\n return new ReadableStreamStubHook2(state, this);\n }\n pull() {\n return Promise.reject(/* @__PURE__ */ new Error(\"Cannot pull a ReadableStream stub\"));\n }\n ignoreUnhandledRejections() {\n }\n dispose() {\n let state = this.state;\n this.state = void 0;\n if (state) {\n if (--state.refcount === 0) {\n if (!state.canceled) {\n state.canceled = true;\n if (!state.stream.locked) state.stream.cancel(/* @__PURE__ */ new Error(\"ReadableStream RPC stub was disposed without being consumed\")).catch(() => {\n });\n }\n }\n }\n }\n onBroken(callback) {\n }\n};\nstreamImpl.createWritableStreamHook = WritableStreamStubHook.create;\nstreamImpl.createWritableStreamFromHook = createWritableStreamFromHook;\nstreamImpl.createReadableStreamHook = ReadableStreamStubHook.create;\nasync function newWorkersRpcResponse(request, localMain, options) {\n if (request.method === \"POST\") {\n let response = await newHttpBatchRpcResponse(request, localMain, options);\n response.headers.set(\"Access-Control-Allow-Origin\", \"*\");\n return response;\n } else if (request.headers.get(\"Upgrade\")?.toLowerCase() === \"websocket\") return newWorkersWebSocketRpcResponse(request, localMain, options);\n else return new Response(\"This endpoint only accepts POST or WebSocket requests.\", { status: 400 });\n}\n\n// templates/remoteBindings/ProxyServerWorker.ts\nimport { EmailMessage } from \"cloudflare:email\";\nvar BindingNotFoundError = class extends Error {\n constructor(name) {\n super(`Binding ${name ? `\"${name}\"` : \"\"} not found`);\n }\n};\nfunction getExposedJSRPCBinding(request, env) {\n const url = new URL(request.url);\n const bindingName = url.searchParams.get(\"MF-Binding\");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n if (targetBinding.constructor.name === \"Hyperdrive\") {\n const hyperdrive = targetBinding;\n return {\n getConnectionString() {\n return hyperdrive.connectionString;\n },\n connect() {\n const socket = hyperdrive.connect();\n return { readable: socket.readable, writable: socket.writable };\n }\n };\n }\n if (targetBinding.constructor.name === \"AnalyticsEngine\") {\n const dataset = targetBinding;\n return {\n writeDataPoint(event) {\n dataset.writeDataPoint(event);\n }\n };\n }\n if (targetBinding.constructor.name === \"SendEmail\") {\n return {\n async send(e) {\n if (\"EmailMessage::raw\" in e) {\n const message = new EmailMessage(\n e.from,\n e.to,\n e[\"EmailMessage::raw\"]\n );\n return targetBinding.send(message);\n } else {\n return targetBinding.send(e);\n }\n }\n };\n }\n const dispatchNamespaceOptions = url.searchParams.get(\n \"MF-Dispatch-Namespace-Options\"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction getExposedFetcher(request, env) {\n const bindingName = request.headers.get(\"MF-Binding\");\n if (!bindingName) {\n throw new BindingNotFoundError();\n }\n const targetBinding = env[bindingName];\n if (!targetBinding) {\n throw new BindingNotFoundError(bindingName);\n }\n const dispatchNamespaceOptions = request.headers.get(\n \"MF-Dispatch-Namespace-Options\"\n );\n if (dispatchNamespaceOptions) {\n const { name, args, options } = JSON.parse(dispatchNamespaceOptions);\n return targetBinding.get(name, args, options);\n }\n return targetBinding;\n}\nfunction isJSRPCBinding(request) {\n const url = new URL(request.url);\n return request.headers.has(\"Upgrade\") && url.searchParams.has(\"MF-Binding\");\n}\nfunction isConnectBinding(request) {\n return request.headers.get(\"Upgrade\") === \"websocket\" && request.headers.has(\"MF-Connect-Address\");\n}\nfunction handleConnect(request, env) {\n const address = request.headers.get(\"MF-Connect-Address\");\n if (address === null) {\n return new Response(\"Missing MF-Connect-Address header\", { status: 400 });\n }\n const fetcher = getExposedFetcher(request, env);\n const { 0: client, 1: server } = new WebSocketPair();\n server.accept();\n const socket = fetcher.connect(address);\n pipeSocketOverWebSocket(socket, server).catch(() => {\n });\n return new Response(null, { status: 101, webSocket: client });\n}\nfunction truncateCloseReason(reason) {\n const bytes = new TextEncoder().encode(reason);\n if (bytes.length <= 123) {\n return reason;\n }\n let end = 123;\n while (end > 0 && ((bytes[end] ?? 0) & 192) === 128) {\n end--;\n }\n return new TextDecoder().decode(bytes.subarray(0, end));\n}\nasync function pipeSocketOverWebSocket(socket, ws) {\n const writer = socket.writable.getWriter();\n const reader = socket.readable.getReader();\n let wsClosed = false;\n function closeWebSocket(code, reason) {\n if (wsClosed) {\n return;\n }\n wsClosed = true;\n try {\n ws.close(\n code,\n reason === void 0 ? void 0 : truncateCloseReason(reason)\n );\n } catch {\n }\n }\n let writeChain = Promise.resolve();\n let writerClosed = false;\n function closeWriter() {\n if (writerClosed) {\n return Promise.resolve();\n }\n writerClosed = true;\n return writeChain.then(() => writer.close());\n }\n let resolveFromWs;\n let rejectFromWs;\n const fromWebSocket = new Promise((resolve, reject) => {\n resolveFromWs = resolve;\n rejectFromWs = reject;\n });\n ws.addEventListener(\"message\", (event) => {\n const chunk = typeof event.data === \"string\" ? new TextEncoder().encode(event.data) : new Uint8Array(event.data);\n writeChain = writeChain.then(() => writer.write(chunk)).catch((error) => {\n closeWebSocket(\n 1011,\n error?.message ?? \"socket write failed\"\n );\n reader.cancel().catch(() => {\n });\n rejectFromWs(error);\n });\n });\n ws.addEventListener(\"close\", (event) => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n if (event.code === 1011) {\n rejectFromWs(\n new Error(event.reason || \"Remote tunnel closed with an error\")\n );\n return;\n }\n closeWriter().then(resolveFromWs, rejectFromWs);\n });\n ws.addEventListener(\"error\", () => {\n wsClosed = true;\n reader.cancel().catch(() => {\n });\n rejectFromWs(new Error(\"Tunnel WebSocket errored\"));\n });\n const toWebSocket = (async () => {\n try {\n for (; ; ) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n if (wsClosed) {\n break;\n }\n ws.send(\n value.buffer.slice(\n value.byteOffset,\n value.byteOffset + value.byteLength\n )\n );\n }\n closeWebSocket(1e3);\n } catch (error) {\n closeWebSocket(1011, error?.message ?? \"socket read failed\");\n throw error;\n } finally {\n reader.releaseLock();\n closeWriter().then(resolveFromWs, rejectFromWs);\n }\n })();\n await Promise.all([toWebSocket, fromWebSocket]);\n}\nvar ProxyServerWorker_default = {\n async fetch(request, env) {\n try {\n if (isConnectBinding(request)) {\n return handleConnect(request, env);\n } else if (isJSRPCBinding(request)) {\n return await newWorkersRpcResponse(\n request,\n getExposedJSRPCBinding(request, env)\n );\n } else {\n const fetcher = getExposedFetcher(request, env);\n const originalHeaders = new Headers();\n for (const [name, value] of request.headers) {\n if (name.startsWith(\"mf-header-\")) {\n originalHeaders.set(name.slice(\"mf-header-\".length), value);\n } else if (name === \"upgrade\") {\n originalHeaders.set(name, value);\n }\n }\n return await fetcher.fetch(\n request.headers.get(\"MF-URL\") ?? \"http://example.com\",\n new Request(request, {\n redirect: \"manual\",\n headers: originalHeaders\n })\n );\n }\n } catch (e) {\n if (e instanceof BindingNotFoundError) {\n return new Response(e.message, { status: 400 });\n }\n return new Response(e.message, { status: 500 });\n }\n }\n};\nexport {\n ProxyServerWorker_default as default\n};\n";
|
|
89918
90238
|
let logger;
|
|
89919
90239
|
function initLogger(value) {
|
|
89920
90240
|
logger = value;
|
|
@@ -93038,11 +93358,11 @@ var require_picomatch$1 = /* @__PURE__ */ __commonJS$2({ "../../node_modules/.pn
|
|
|
93038
93358
|
output: ""
|
|
93039
93359
|
};
|
|
93040
93360
|
const opts = options || {};
|
|
93041
|
-
const format$
|
|
93361
|
+
const format$3 = opts.format || (posix$1 ? utils$1.toPosixSlashes : null);
|
|
93042
93362
|
let match = input$1 === glob;
|
|
93043
|
-
let output$1 = match && format$
|
|
93363
|
+
let output$1 = match && format$3 ? format$3(input$1) : input$1;
|
|
93044
93364
|
if (match === false) {
|
|
93045
|
-
output$1 = format$
|
|
93365
|
+
output$1 = format$3 ? format$3(input$1) : input$1;
|
|
93046
93366
|
match = output$1 === glob;
|
|
93047
93367
|
}
|
|
93048
93368
|
if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$2.matchBase(input$1, regex$1, options, posix$1);
|
|
@@ -93437,8 +93757,8 @@ function buildCrawler(options, patterns) {
|
|
|
93437
93757
|
const matcher = (0, import_picomatch.default)(processed.match, matchOptions);
|
|
93438
93758
|
const ignore$1 = (0, import_picomatch.default)(processed.ignore, matchOptions);
|
|
93439
93759
|
const partialMatcher = getPartialMatcher(processed.match, matchOptions);
|
|
93440
|
-
const format$
|
|
93441
|
-
const excludeFormatter = absolute$1 ? format$
|
|
93760
|
+
const format$3 = buildFormat(cwd, root, absolute$1);
|
|
93761
|
+
const excludeFormatter = absolute$1 ? format$3 : buildFormat(cwd, root, true);
|
|
93442
93762
|
const excludePredicate = (_, p$2) => {
|
|
93443
93763
|
const relativePath = excludeFormatter(p$2, true);
|
|
93444
93764
|
return relativePath !== "." && !partialMatcher(relativePath) || ignore$1(relativePath);
|
|
@@ -93447,12 +93767,12 @@ function buildCrawler(options, patterns) {
|
|
|
93447
93767
|
if (options.deep !== void 0) maxDepth = Math.round(options.deep - props.depthOffset);
|
|
93448
93768
|
const crawler = new Builder({
|
|
93449
93769
|
filters: [debug$7 ? (p$2, isDirectory$2) => {
|
|
93450
|
-
const path$2 = format$
|
|
93770
|
+
const path$2 = format$3(p$2, isDirectory$2);
|
|
93451
93771
|
const matches = matcher(path$2) && !ignore$1(path$2);
|
|
93452
93772
|
if (matches) log(`matched ${path$2}`);
|
|
93453
93773
|
return matches;
|
|
93454
93774
|
} : (p$2, isDirectory$2) => {
|
|
93455
|
-
const path$2 = format$
|
|
93775
|
+
const path$2 = format$3(p$2, isDirectory$2);
|
|
93456
93776
|
return matcher(path$2) && !ignore$1(path$2);
|
|
93457
93777
|
}],
|
|
93458
93778
|
exclude: debug$7 ? (_, p$2) => {
|
|
@@ -93985,7 +94305,7 @@ function getStructuredLogsLogger(logger$2) {
|
|
|
93985
94305
|
/**
|
|
93986
94306
|
* Handles 'upgrade' requests to the Vite HTTP server and forwards WebSocket events between the client and Worker environments.
|
|
93987
94307
|
*/
|
|
93988
|
-
function handleWebSocket(httpServer, miniflare, entryWorkerName) {
|
|
94308
|
+
function handleWebSocket(httpServer, miniflare, entryWorkerName, viteWebSocketEnabled = true) {
|
|
93989
94309
|
const nodeWebSocket = new WebSocketServer({ noServer: true });
|
|
93990
94310
|
const workerResponseHeaders = /* @__PURE__ */ new WeakMap();
|
|
93991
94311
|
nodeWebSocket.on("headers", (responseHeaders, request$2) => {
|
|
@@ -94003,7 +94323,10 @@ function handleWebSocket(httpServer, miniflare, entryWorkerName) {
|
|
|
94003
94323
|
const isViteRequest = request$2.headers["sec-websocket-protocol"]?.startsWith("vite");
|
|
94004
94324
|
const isDevToolsRequest = url$2.pathname === "/__devtools/__ws";
|
|
94005
94325
|
const isSandboxRequest = hasSandboxOrigin(url$2.origin);
|
|
94006
|
-
if ((isViteRequest || isDevToolsRequest) && !isSandboxRequest)
|
|
94326
|
+
if ((isViteRequest || isDevToolsRequest) && !isSandboxRequest) {
|
|
94327
|
+
if (isViteRequest && !viteWebSocketEnabled) socket.destroy();
|
|
94328
|
+
return;
|
|
94329
|
+
}
|
|
94007
94330
|
const headers = createHeadersForIncomingMessage(request$2);
|
|
94008
94331
|
if (entryWorkerName) headers.set(CoreHeaders.ROUTE_OVERRIDE, entryWorkerName);
|
|
94009
94332
|
const response = await miniflare.dispatchFetch(url$2, {
|
|
@@ -94129,7 +94452,7 @@ const devPlugin = createPlugin("dev", (ctx) => {
|
|
|
94129
94452
|
const entryWorkerConfig = ctx.entryWorkerConfig;
|
|
94130
94453
|
assert(entryWorkerConfig, `No entry Worker config`);
|
|
94131
94454
|
const entryWorkerName = entryWorkerConfig.name;
|
|
94132
|
-
if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName);
|
|
94455
|
+
if (viteDevServer.httpServer) handleWebSocket(viteDevServer.httpServer, ctx.miniflare, entryWorkerName, viteDevServer.config.server.ws !== false);
|
|
94133
94456
|
const staticRouting = entryWorkerConfig.assets?.run_worker_first === true ? { user_worker: ["/*"] } : ctx.resolvedPluginConfig.staticRouting;
|
|
94134
94457
|
if (staticRouting) {
|
|
94135
94458
|
const excludeRulesMatcher = generateStaticRoutingRuleMatcher(staticRouting.asset_worker ?? []);
|
|
@@ -94327,7 +94650,7 @@ const outputConfigPlugin = createPlugin("output-config", (ctx) => {
|
|
|
94327
94650
|
}
|
|
94328
94651
|
} else if (this.environment.name === "client") {
|
|
94329
94652
|
const filesToAssetsIgnore = ["wrangler.json", ".dev.vars"];
|
|
94330
|
-
const existingAssetsIgnoreContent = ctx.resolvedViteConfig.publicDir.length > 0 ? readAssetsIgnoreFile(path.join(ctx.resolvedViteConfig.publicDir, ".assetsignore")) : "";
|
|
94653
|
+
const existingAssetsIgnoreContent = ctx.resolvedViteConfig.publicDir.length > 0 ? readAssetsIgnoreFile$1(path.join(ctx.resolvedViteConfig.publicDir, ".assetsignore")) : "";
|
|
94331
94654
|
this.emitFile({
|
|
94332
94655
|
type: "asset",
|
|
94333
94656
|
fileName: ".assetsignore",
|
|
@@ -94406,8 +94729,8 @@ function rewriteMigrationsPattern(migrationsPattern, fromMigrationsDir, toMigrat
|
|
|
94406
94729
|
const suffix = normalizedDir === "." ? normalizedPattern : path.posix.relative(normalizedDir, normalizedPattern);
|
|
94407
94730
|
return vite.normalizePath(path.posix.normalize(toMigrationsDir === "." ? suffix : `${toMigrationsDir}/${suffix}`));
|
|
94408
94731
|
}
|
|
94409
|
-
function readAssetsIgnoreFile(assetsIgnorePath) {
|
|
94410
|
-
const content =
|
|
94732
|
+
function readAssetsIgnoreFile$1(assetsIgnorePath) {
|
|
94733
|
+
const content = readAssetsIgnoreFile(assetsIgnorePath) ?? "";
|
|
94411
94734
|
if (content.length === 0) return "";
|
|
94412
94735
|
return content.at(-1) === "\n" ? content : `${content}\n`;
|
|
94413
94736
|
}
|
|
@@ -94655,14 +94978,14 @@ const canAccessPowerShell = async () => {
|
|
|
94655
94978
|
};
|
|
94656
94979
|
const wslDefaultBrowser = async () => {
|
|
94657
94980
|
const psPath = await powerShellPath();
|
|
94658
|
-
const { stdout: stdout$
|
|
94659
|
-
return stdout$
|
|
94981
|
+
const { stdout: stdout$2 } = await executePowerShell(String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`, { powerShellPath: psPath });
|
|
94982
|
+
return stdout$2.trim();
|
|
94660
94983
|
};
|
|
94661
94984
|
const convertWslPathToWindows = async (path$2) => {
|
|
94662
94985
|
if (/^[a-z]+:\/\//i.test(path$2)) return path$2;
|
|
94663
94986
|
try {
|
|
94664
|
-
const { stdout: stdout$
|
|
94665
|
-
return stdout$
|
|
94987
|
+
const { stdout: stdout$2 } = await execFile$1("wslpath", ["-aw", path$2], { encoding: "utf8" });
|
|
94988
|
+
return stdout$2.trim();
|
|
94666
94989
|
} catch {
|
|
94667
94990
|
return path$2;
|
|
94668
94991
|
}
|
|
@@ -94696,12 +95019,12 @@ function defineLazyProperty(object$2, propertyName, valueGetter) {
|
|
|
94696
95019
|
const execFileAsync$3 = promisify(execFile);
|
|
94697
95020
|
async function defaultBrowserId() {
|
|
94698
95021
|
if (process5.platform !== "darwin") throw new Error("macOS only");
|
|
94699
|
-
const { stdout: stdout$
|
|
95022
|
+
const { stdout: stdout$2 } = await execFileAsync$3("defaults", [
|
|
94700
95023
|
"read",
|
|
94701
95024
|
"com.apple.LaunchServices/com.apple.launchservices.secure",
|
|
94702
95025
|
"LSHandlers"
|
|
94703
95026
|
]);
|
|
94704
|
-
const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout$
|
|
95027
|
+
const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout$2)?.groups.id ?? "com.apple.Safari";
|
|
94705
95028
|
if (browserId === "com.apple.safari") return "com.apple.Safari";
|
|
94706
95029
|
return browserId;
|
|
94707
95030
|
}
|
|
@@ -94714,12 +95037,12 @@ async function runAppleScript(script, { humanReadableOutput = true, signal } = {
|
|
|
94714
95037
|
const outputArguments = humanReadableOutput ? [] : ["-ss"];
|
|
94715
95038
|
const execOptions = {};
|
|
94716
95039
|
if (signal) execOptions.signal = signal;
|
|
94717
|
-
const { stdout: stdout$
|
|
95040
|
+
const { stdout: stdout$2 } = await execFileAsync$2("osascript", [
|
|
94718
95041
|
"-e",
|
|
94719
95042
|
script,
|
|
94720
95043
|
outputArguments
|
|
94721
95044
|
], execOptions);
|
|
94722
|
-
return stdout$
|
|
95045
|
+
return stdout$2.trim();
|
|
94723
95046
|
}
|
|
94724
95047
|
|
|
94725
95048
|
//#endregion
|
|
@@ -94800,14 +95123,14 @@ const windowsBrowserProgIds = {
|
|
|
94800
95123
|
const _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
|
|
94801
95124
|
var UnknownBrowserError = class extends Error {};
|
|
94802
95125
|
async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
|
|
94803
|
-
const { stdout: stdout$
|
|
95126
|
+
const { stdout: stdout$2 } = await _execFileAsync("reg", [
|
|
94804
95127
|
"QUERY",
|
|
94805
95128
|
" HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
|
|
94806
95129
|
"/v",
|
|
94807
95130
|
"ProgId"
|
|
94808
95131
|
]);
|
|
94809
|
-
const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout$
|
|
94810
|
-
if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout$
|
|
95132
|
+
const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout$2);
|
|
95133
|
+
if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout$2)}`);
|
|
94811
95134
|
const { id } = match.groups;
|
|
94812
95135
|
const browser = windowsBrowserProgIds[id];
|
|
94813
95136
|
if (!browser) throw new UnknownBrowserError(`Unknown browser ID: ${id}`);
|
|
@@ -94827,12 +95150,12 @@ async function defaultBrowser() {
|
|
|
94827
95150
|
};
|
|
94828
95151
|
}
|
|
94829
95152
|
if (process5.platform === "linux") {
|
|
94830
|
-
const { stdout: stdout$
|
|
95153
|
+
const { stdout: stdout$2 } = await execFileAsync("xdg-mime", [
|
|
94831
95154
|
"query",
|
|
94832
95155
|
"default",
|
|
94833
95156
|
"x-scheme-handler/http"
|
|
94834
95157
|
]);
|
|
94835
|
-
const id = stdout$
|
|
95158
|
+
const id = stdout$2.trim();
|
|
94836
95159
|
return {
|
|
94837
95160
|
name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
|
|
94838
95161
|
id
|