miniflare 0.0.0-020b04921
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +858 -0
- package/bootstrap.js +11 -0
- package/dist/src/index.d.ts +4408 -0
- package/dist/src/index.js +10391 -0
- package/dist/src/index.js.map +6 -0
- package/dist/src/workers/assets/assets-kv.worker.js +28 -0
- package/dist/src/workers/assets/assets-kv.worker.js.map +6 -0
- package/dist/src/workers/assets/assets.worker.js +9275 -0
- package/dist/src/workers/assets/assets.worker.js.map +6 -0
- package/dist/src/workers/assets/router.worker.js +8755 -0
- package/dist/src/workers/assets/router.worker.js.map +6 -0
- package/dist/src/workers/cache/cache-entry-noop.worker.js +19 -0
- package/dist/src/workers/cache/cache-entry-noop.worker.js.map +6 -0
- package/dist/src/workers/cache/cache-entry.worker.js +28 -0
- package/dist/src/workers/cache/cache-entry.worker.js.map +6 -0
- package/dist/src/workers/cache/cache.worker.js +656 -0
- package/dist/src/workers/cache/cache.worker.js.map +6 -0
- package/dist/src/workers/core/entry.worker.js +1040 -0
- package/dist/src/workers/core/entry.worker.js.map +6 -0
- package/dist/src/workers/d1/database.worker.js +350 -0
- package/dist/src/workers/d1/database.worker.js.map +6 -0
- package/dist/src/workers/kv/namespace.worker.js +258 -0
- package/dist/src/workers/kv/namespace.worker.js.map +6 -0
- package/dist/src/workers/kv/sites.worker.js +147 -0
- package/dist/src/workers/kv/sites.worker.js.map +6 -0
- package/dist/src/workers/queues/broker.worker.js +294 -0
- package/dist/src/workers/queues/broker.worker.js.map +6 -0
- package/dist/src/workers/r2/bucket.worker.js +1157 -0
- package/dist/src/workers/r2/bucket.worker.js.map +6 -0
- package/dist/src/workers/ratelimit/ratelimit.worker.js +54 -0
- package/dist/src/workers/ratelimit/ratelimit.worker.js.map +6 -0
- package/dist/src/workers/shared/index.worker.js +706 -0
- package/dist/src/workers/shared/index.worker.js.map +6 -0
- package/dist/src/workers/shared/object-entry.worker.js +21 -0
- package/dist/src/workers/shared/object-entry.worker.js.map +6 -0
- package/dist/src/workers/shared/zod.worker.js +2719 -0
- package/dist/src/workers/shared/zod.worker.js.map +6 -0
- package/package.json +108 -0
|
@@ -0,0 +1,1040 @@
|
|
|
1
|
+
// ../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs
|
|
2
|
+
var FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY = !0;
|
|
3
|
+
typeof process < "u" && ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {}, isTTY = process.stdout && process.stdout.isTTY);
|
|
4
|
+
var $ = {
|
|
5
|
+
enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== "dumb" && (FORCE_COLOR != null && FORCE_COLOR !== "0" || isTTY)
|
|
6
|
+
};
|
|
7
|
+
function init(x, y) {
|
|
8
|
+
let rgx = new RegExp(`\\x1b\\[${y}m`, "g"), open = `\x1B[${x}m`, close = `\x1B[${y}m`;
|
|
9
|
+
return function(txt) {
|
|
10
|
+
return !$.enabled || txt == null ? txt : open + (~("" + txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
var reset = init(0, 0), bold = init(1, 22), dim = init(2, 22), italic = init(3, 23), underline = init(4, 24), inverse = init(7, 27), hidden = init(8, 28), strikethrough = init(9, 29), black = init(30, 39), red = init(31, 39), green = init(32, 39), yellow = init(33, 39), blue = init(34, 39), magenta = init(35, 39), cyan = init(36, 39), white = init(37, 39), gray = init(90, 39), grey = init(90, 39), bgBlack = init(40, 49), bgRed = init(41, 49), bgGreen = init(42, 49), bgYellow = init(43, 49), bgBlue = init(44, 49), bgMagenta = init(45, 49), bgCyan = init(46, 49), bgWhite = init(47, 49);
|
|
14
|
+
|
|
15
|
+
// src/workers/core/entry.worker.ts
|
|
16
|
+
import { HttpError, LogLevel, SharedHeaders } from "miniflare:shared";
|
|
17
|
+
|
|
18
|
+
// src/shared/mime-types.ts
|
|
19
|
+
var compressedByCloudflareFL = /* @__PURE__ */ new Set([
|
|
20
|
+
// list copied from https://developers.cloudflare.com/speed/optimization/content/brotli/content-compression/#:~:text=If%20supported%20by%20visitors%E2%80%99%20web%20browsers%2C%20Cloudflare%20will%20return%20Gzip%20or%20Brotli%2Dencoded%20responses%20for%20the%20following%20content%20types%3A
|
|
21
|
+
"text/html",
|
|
22
|
+
"text/richtext",
|
|
23
|
+
"text/plain",
|
|
24
|
+
"text/css",
|
|
25
|
+
"text/x-script",
|
|
26
|
+
"text/x-component",
|
|
27
|
+
"text/x-java-source",
|
|
28
|
+
"text/x-markdown",
|
|
29
|
+
"application/javascript",
|
|
30
|
+
"application/x-javascript",
|
|
31
|
+
"text/javascript",
|
|
32
|
+
"text/js",
|
|
33
|
+
"image/x-icon",
|
|
34
|
+
"image/vnd.microsoft.icon",
|
|
35
|
+
"application/x-perl",
|
|
36
|
+
"application/x-httpd-cgi",
|
|
37
|
+
"text/xml",
|
|
38
|
+
"application/xml",
|
|
39
|
+
"application/rss+xml",
|
|
40
|
+
"application/vnd.api+json",
|
|
41
|
+
"application/x-protobuf",
|
|
42
|
+
"application/json",
|
|
43
|
+
"multipart/bag",
|
|
44
|
+
"multipart/mixed",
|
|
45
|
+
"application/xhtml+xml",
|
|
46
|
+
"font/ttf",
|
|
47
|
+
"font/otf",
|
|
48
|
+
"font/x-woff",
|
|
49
|
+
"image/svg+xml",
|
|
50
|
+
"application/vnd.ms-fontobject",
|
|
51
|
+
"application/ttf",
|
|
52
|
+
"application/x-ttf",
|
|
53
|
+
"application/otf",
|
|
54
|
+
"application/x-otf",
|
|
55
|
+
"application/truetype",
|
|
56
|
+
"application/opentype",
|
|
57
|
+
"application/x-opentype",
|
|
58
|
+
"application/font-woff",
|
|
59
|
+
"application/eot",
|
|
60
|
+
"application/font",
|
|
61
|
+
"application/font-sfnt",
|
|
62
|
+
"application/wasm",
|
|
63
|
+
"application/javascript-binast",
|
|
64
|
+
"application/manifest+json",
|
|
65
|
+
"application/ld+json",
|
|
66
|
+
"application/graphql+json",
|
|
67
|
+
"application/geo+json"
|
|
68
|
+
]);
|
|
69
|
+
function isCompressedByCloudflareFL(contentTypeHeader) {
|
|
70
|
+
if (!contentTypeHeader)
|
|
71
|
+
return !0;
|
|
72
|
+
let [contentType] = contentTypeHeader.split(";");
|
|
73
|
+
return compressedByCloudflareFL.has(contentType);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// src/workers/core/constants.ts
|
|
77
|
+
var CoreHeaders = {
|
|
78
|
+
CUSTOM_SERVICE: "MF-Custom-Service",
|
|
79
|
+
ORIGINAL_URL: "MF-Original-URL",
|
|
80
|
+
PROXY_SHARED_SECRET: "MF-Proxy-Shared-Secret",
|
|
81
|
+
DISABLE_PRETTY_ERROR: "MF-Disable-Pretty-Error",
|
|
82
|
+
ERROR_STACK: "MF-Experimental-Error-Stack",
|
|
83
|
+
ROUTE_OVERRIDE: "MF-Route-Override",
|
|
84
|
+
CF_BLOB: "MF-CF-Blob",
|
|
85
|
+
// API Proxy
|
|
86
|
+
OP_SECRET: "MF-Op-Secret",
|
|
87
|
+
OP: "MF-Op",
|
|
88
|
+
OP_TARGET: "MF-Op-Target",
|
|
89
|
+
OP_KEY: "MF-Op-Key",
|
|
90
|
+
OP_SYNC: "MF-Op-Sync",
|
|
91
|
+
OP_STRINGIFIED_SIZE: "MF-Op-Stringified-Size",
|
|
92
|
+
OP_RESULT_TYPE: "MF-Op-Result-Type"
|
|
93
|
+
}, CoreBindings = {
|
|
94
|
+
SERVICE_LOOPBACK: "MINIFLARE_LOOPBACK",
|
|
95
|
+
SERVICE_USER_ROUTE_PREFIX: "MINIFLARE_USER_ROUTE_",
|
|
96
|
+
SERVICE_USER_FALLBACK: "MINIFLARE_USER_FALLBACK",
|
|
97
|
+
TEXT_CUSTOM_SERVICE: "MINIFLARE_CUSTOM_SERVICE",
|
|
98
|
+
TEXT_UPSTREAM_URL: "MINIFLARE_UPSTREAM_URL",
|
|
99
|
+
JSON_CF_BLOB: "CF_BLOB",
|
|
100
|
+
JSON_ROUTES: "MINIFLARE_ROUTES",
|
|
101
|
+
JSON_LOG_LEVEL: "MINIFLARE_LOG_LEVEL",
|
|
102
|
+
DATA_LIVE_RELOAD_SCRIPT: "MINIFLARE_LIVE_RELOAD_SCRIPT",
|
|
103
|
+
DURABLE_OBJECT_NAMESPACE_PROXY: "MINIFLARE_PROXY",
|
|
104
|
+
DATA_PROXY_SECRET: "MINIFLARE_PROXY_SECRET",
|
|
105
|
+
DATA_PROXY_SHARED_SECRET: "MINIFLARE_PROXY_SHARED_SECRET"
|
|
106
|
+
}, ProxyOps = {
|
|
107
|
+
// Get the target or a property of the target
|
|
108
|
+
GET: "GET",
|
|
109
|
+
// Get the descriptor for a property of the target
|
|
110
|
+
GET_OWN_DESCRIPTOR: "GET_OWN_DESCRIPTOR",
|
|
111
|
+
// Get the target's own property names
|
|
112
|
+
GET_OWN_KEYS: "GET_OWN_KEYS",
|
|
113
|
+
// Call a method on the target
|
|
114
|
+
CALL: "CALL",
|
|
115
|
+
// Remove the strong reference to the target on the "heap", allowing it to be
|
|
116
|
+
// garbage collected
|
|
117
|
+
FREE: "FREE"
|
|
118
|
+
}, ProxyAddresses = {
|
|
119
|
+
GLOBAL: 0,
|
|
120
|
+
// globalThis
|
|
121
|
+
ENV: 1,
|
|
122
|
+
// env
|
|
123
|
+
USER_START: 2
|
|
124
|
+
};
|
|
125
|
+
function isFetcherFetch(targetName, key) {
|
|
126
|
+
return (targetName === "Fetcher" || targetName === "DurableObject" || targetName === "WorkerRpc") && key === "fetch";
|
|
127
|
+
}
|
|
128
|
+
function isR2ObjectWriteHttpMetadata(targetName, key) {
|
|
129
|
+
return (targetName === "HeadResult" || targetName === "GetResult") && key === "writeHttpMetadata";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/workers/core/http.ts
|
|
133
|
+
var STATUS_CODES = {
|
|
134
|
+
100: "Continue",
|
|
135
|
+
101: "Switching Protocols",
|
|
136
|
+
102: "Processing",
|
|
137
|
+
103: "Early Hints",
|
|
138
|
+
200: "OK",
|
|
139
|
+
201: "Created",
|
|
140
|
+
202: "Accepted",
|
|
141
|
+
203: "Non-Authoritative Information",
|
|
142
|
+
204: "No Content",
|
|
143
|
+
205: "Reset Content",
|
|
144
|
+
206: "Partial Content",
|
|
145
|
+
207: "Multi-Status",
|
|
146
|
+
208: "Already Reported",
|
|
147
|
+
226: "IM Used",
|
|
148
|
+
300: "Multiple Choices",
|
|
149
|
+
301: "Moved Permanently",
|
|
150
|
+
302: "Found",
|
|
151
|
+
303: "See Other",
|
|
152
|
+
304: "Not Modified",
|
|
153
|
+
305: "Use Proxy",
|
|
154
|
+
307: "Temporary Redirect",
|
|
155
|
+
308: "Permanent Redirect",
|
|
156
|
+
400: "Bad Request",
|
|
157
|
+
401: "Unauthorized",
|
|
158
|
+
402: "Payment Required",
|
|
159
|
+
403: "Forbidden",
|
|
160
|
+
404: "Not Found",
|
|
161
|
+
405: "Method Not Allowed",
|
|
162
|
+
406: "Not Acceptable",
|
|
163
|
+
407: "Proxy Authentication Required",
|
|
164
|
+
408: "Request Timeout",
|
|
165
|
+
409: "Conflict",
|
|
166
|
+
410: "Gone",
|
|
167
|
+
411: "Length Required",
|
|
168
|
+
412: "Precondition Failed",
|
|
169
|
+
413: "Payload Too Large",
|
|
170
|
+
414: "URI Too Long",
|
|
171
|
+
415: "Unsupported Media Type",
|
|
172
|
+
416: "Range Not Satisfiable",
|
|
173
|
+
417: "Expectation Failed",
|
|
174
|
+
418: "I'm a Teapot",
|
|
175
|
+
421: "Misdirected Request",
|
|
176
|
+
422: "Unprocessable Entity",
|
|
177
|
+
423: "Locked",
|
|
178
|
+
424: "Failed Dependency",
|
|
179
|
+
425: "Too Early",
|
|
180
|
+
426: "Upgrade Required",
|
|
181
|
+
428: "Precondition Required",
|
|
182
|
+
429: "Too Many Requests",
|
|
183
|
+
431: "Request Header Fields Too Large",
|
|
184
|
+
451: "Unavailable For Legal Reasons",
|
|
185
|
+
500: "Internal Server Error",
|
|
186
|
+
501: "Not Implemented",
|
|
187
|
+
502: "Bad Gateway",
|
|
188
|
+
503: "Service Unavailable",
|
|
189
|
+
504: "Gateway Timeout",
|
|
190
|
+
505: "HTTP Version Not Supported",
|
|
191
|
+
506: "Variant Also Negotiates",
|
|
192
|
+
507: "Insufficient Storage",
|
|
193
|
+
508: "Loop Detected",
|
|
194
|
+
509: "Bandwidth Limit Exceeded",
|
|
195
|
+
510: "Not Extended",
|
|
196
|
+
511: "Network Authentication Required"
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
// src/workers/core/routing.ts
|
|
200
|
+
function matchRoutes(routes, url) {
|
|
201
|
+
for (let route of routes) {
|
|
202
|
+
if (route.protocol && route.protocol !== url.protocol)
|
|
203
|
+
continue;
|
|
204
|
+
if (route.allowHostnamePrefix) {
|
|
205
|
+
if (!url.hostname.endsWith(route.hostname))
|
|
206
|
+
continue;
|
|
207
|
+
} else if (url.hostname !== route.hostname)
|
|
208
|
+
continue;
|
|
209
|
+
let path = url.pathname + url.search;
|
|
210
|
+
if (route.allowPathSuffix) {
|
|
211
|
+
if (!path.startsWith(route.path))
|
|
212
|
+
continue;
|
|
213
|
+
} else if (path !== route.path)
|
|
214
|
+
continue;
|
|
215
|
+
return route.target;
|
|
216
|
+
}
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// src/workers/core/proxy.worker.ts
|
|
221
|
+
import assert2 from "node:assert";
|
|
222
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
223
|
+
|
|
224
|
+
// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/utils.js
|
|
225
|
+
var DevalueError = class extends Error {
|
|
226
|
+
/**
|
|
227
|
+
* @param {string} message
|
|
228
|
+
* @param {string[]} keys
|
|
229
|
+
*/
|
|
230
|
+
constructor(message, keys) {
|
|
231
|
+
super(message), this.name = "DevalueError", this.path = keys.join("");
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
function is_primitive(thing) {
|
|
235
|
+
return Object(thing) !== thing;
|
|
236
|
+
}
|
|
237
|
+
var object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(
|
|
238
|
+
Object.prototype
|
|
239
|
+
).sort().join("\0");
|
|
240
|
+
function is_plain_object(thing) {
|
|
241
|
+
let proto = Object.getPrototypeOf(thing);
|
|
242
|
+
return proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
|
|
243
|
+
}
|
|
244
|
+
function get_type(thing) {
|
|
245
|
+
return Object.prototype.toString.call(thing).slice(8, -1);
|
|
246
|
+
}
|
|
247
|
+
function get_escaped_char(char) {
|
|
248
|
+
switch (char) {
|
|
249
|
+
case '"':
|
|
250
|
+
return '\\"';
|
|
251
|
+
case "<":
|
|
252
|
+
return "\\u003C";
|
|
253
|
+
case "\\":
|
|
254
|
+
return "\\\\";
|
|
255
|
+
case `
|
|
256
|
+
`:
|
|
257
|
+
return "\\n";
|
|
258
|
+
case "\r":
|
|
259
|
+
return "\\r";
|
|
260
|
+
case " ":
|
|
261
|
+
return "\\t";
|
|
262
|
+
case "\b":
|
|
263
|
+
return "\\b";
|
|
264
|
+
case "\f":
|
|
265
|
+
return "\\f";
|
|
266
|
+
case "\u2028":
|
|
267
|
+
return "\\u2028";
|
|
268
|
+
case "\u2029":
|
|
269
|
+
return "\\u2029";
|
|
270
|
+
default:
|
|
271
|
+
return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function stringify_string(str) {
|
|
275
|
+
let result = "", last_pos = 0, len = str.length;
|
|
276
|
+
for (let i = 0; i < len; i += 1) {
|
|
277
|
+
let char = str[i], replacement = get_escaped_char(char);
|
|
278
|
+
replacement && (result += str.slice(last_pos, i) + replacement, last_pos = i + 1);
|
|
279
|
+
}
|
|
280
|
+
return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/parse.js
|
|
284
|
+
function parse(serialized, revivers) {
|
|
285
|
+
return unflatten(JSON.parse(serialized), revivers);
|
|
286
|
+
}
|
|
287
|
+
function unflatten(parsed, revivers) {
|
|
288
|
+
if (typeof parsed == "number")
|
|
289
|
+
return hydrate(parsed, !0);
|
|
290
|
+
if (!Array.isArray(parsed) || parsed.length === 0)
|
|
291
|
+
throw new Error("Invalid input");
|
|
292
|
+
let values = (
|
|
293
|
+
/** @type {any[]} */
|
|
294
|
+
parsed
|
|
295
|
+
), hydrated = Array(values.length);
|
|
296
|
+
function hydrate(index, standalone = !1) {
|
|
297
|
+
if (index === -1)
|
|
298
|
+
return;
|
|
299
|
+
if (index === -3)
|
|
300
|
+
return NaN;
|
|
301
|
+
if (index === -4)
|
|
302
|
+
return 1 / 0;
|
|
303
|
+
if (index === -5)
|
|
304
|
+
return -1 / 0;
|
|
305
|
+
if (index === -6)
|
|
306
|
+
return -0;
|
|
307
|
+
if (standalone)
|
|
308
|
+
throw new Error("Invalid input");
|
|
309
|
+
if (index in hydrated)
|
|
310
|
+
return hydrated[index];
|
|
311
|
+
let value = values[index];
|
|
312
|
+
if (!value || typeof value != "object")
|
|
313
|
+
hydrated[index] = value;
|
|
314
|
+
else if (Array.isArray(value))
|
|
315
|
+
if (typeof value[0] == "string") {
|
|
316
|
+
let type = value[0], reviver = revivers?.[type];
|
|
317
|
+
if (reviver)
|
|
318
|
+
return hydrated[index] = reviver(hydrate(value[1]));
|
|
319
|
+
switch (type) {
|
|
320
|
+
case "Date":
|
|
321
|
+
hydrated[index] = new Date(value[1]);
|
|
322
|
+
break;
|
|
323
|
+
case "Set":
|
|
324
|
+
let set = /* @__PURE__ */ new Set();
|
|
325
|
+
hydrated[index] = set;
|
|
326
|
+
for (let i = 1; i < value.length; i += 1)
|
|
327
|
+
set.add(hydrate(value[i]));
|
|
328
|
+
break;
|
|
329
|
+
case "Map":
|
|
330
|
+
let map = /* @__PURE__ */ new Map();
|
|
331
|
+
hydrated[index] = map;
|
|
332
|
+
for (let i = 1; i < value.length; i += 2)
|
|
333
|
+
map.set(hydrate(value[i]), hydrate(value[i + 1]));
|
|
334
|
+
break;
|
|
335
|
+
case "RegExp":
|
|
336
|
+
hydrated[index] = new RegExp(value[1], value[2]);
|
|
337
|
+
break;
|
|
338
|
+
case "Object":
|
|
339
|
+
hydrated[index] = Object(value[1]);
|
|
340
|
+
break;
|
|
341
|
+
case "BigInt":
|
|
342
|
+
hydrated[index] = BigInt(value[1]);
|
|
343
|
+
break;
|
|
344
|
+
case "null":
|
|
345
|
+
let obj = /* @__PURE__ */ Object.create(null);
|
|
346
|
+
hydrated[index] = obj;
|
|
347
|
+
for (let i = 1; i < value.length; i += 2)
|
|
348
|
+
obj[value[i]] = hydrate(value[i + 1]);
|
|
349
|
+
break;
|
|
350
|
+
default:
|
|
351
|
+
throw new Error(`Unknown type ${type}`);
|
|
352
|
+
}
|
|
353
|
+
} else {
|
|
354
|
+
let array = new Array(value.length);
|
|
355
|
+
hydrated[index] = array;
|
|
356
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
357
|
+
let n = value[i];
|
|
358
|
+
n !== -2 && (array[i] = hydrate(n));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
let object = {};
|
|
363
|
+
hydrated[index] = object;
|
|
364
|
+
for (let key in value) {
|
|
365
|
+
let n = value[key];
|
|
366
|
+
object[key] = hydrate(n);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return hydrated[index];
|
|
370
|
+
}
|
|
371
|
+
return hydrate(0);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// ../../node_modules/.pnpm/devalue@4.3.2/node_modules/devalue/src/stringify.js
|
|
375
|
+
function stringify(value, reducers) {
|
|
376
|
+
let stringified = [], indexes = /* @__PURE__ */ new Map(), custom = [];
|
|
377
|
+
for (let key in reducers)
|
|
378
|
+
custom.push({ key, fn: reducers[key] });
|
|
379
|
+
let keys = [], p = 0;
|
|
380
|
+
function flatten(thing) {
|
|
381
|
+
if (typeof thing == "function")
|
|
382
|
+
throw new DevalueError("Cannot stringify a function", keys);
|
|
383
|
+
if (indexes.has(thing))
|
|
384
|
+
return indexes.get(thing);
|
|
385
|
+
if (thing === void 0)
|
|
386
|
+
return -1;
|
|
387
|
+
if (Number.isNaN(thing))
|
|
388
|
+
return -3;
|
|
389
|
+
if (thing === 1 / 0)
|
|
390
|
+
return -4;
|
|
391
|
+
if (thing === -1 / 0)
|
|
392
|
+
return -5;
|
|
393
|
+
if (thing === 0 && 1 / thing < 0)
|
|
394
|
+
return -6;
|
|
395
|
+
let index2 = p++;
|
|
396
|
+
indexes.set(thing, index2);
|
|
397
|
+
for (let { key, fn } of custom) {
|
|
398
|
+
let value2 = fn(thing);
|
|
399
|
+
if (value2)
|
|
400
|
+
return stringified[index2] = `["${key}",${flatten(value2)}]`, index2;
|
|
401
|
+
}
|
|
402
|
+
let str = "";
|
|
403
|
+
if (is_primitive(thing))
|
|
404
|
+
str = stringify_primitive(thing);
|
|
405
|
+
else
|
|
406
|
+
switch (get_type(thing)) {
|
|
407
|
+
case "Number":
|
|
408
|
+
case "String":
|
|
409
|
+
case "Boolean":
|
|
410
|
+
str = `["Object",${stringify_primitive(thing)}]`;
|
|
411
|
+
break;
|
|
412
|
+
case "BigInt":
|
|
413
|
+
str = `["BigInt",${thing}]`;
|
|
414
|
+
break;
|
|
415
|
+
case "Date":
|
|
416
|
+
str = `["Date","${thing.toISOString()}"]`;
|
|
417
|
+
break;
|
|
418
|
+
case "RegExp":
|
|
419
|
+
let { source, flags } = thing;
|
|
420
|
+
str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`;
|
|
421
|
+
break;
|
|
422
|
+
case "Array":
|
|
423
|
+
str = "[";
|
|
424
|
+
for (let i = 0; i < thing.length; i += 1)
|
|
425
|
+
i > 0 && (str += ","), i in thing ? (keys.push(`[${i}]`), str += flatten(thing[i]), keys.pop()) : str += -2;
|
|
426
|
+
str += "]";
|
|
427
|
+
break;
|
|
428
|
+
case "Set":
|
|
429
|
+
str = '["Set"';
|
|
430
|
+
for (let value2 of thing)
|
|
431
|
+
str += `,${flatten(value2)}`;
|
|
432
|
+
str += "]";
|
|
433
|
+
break;
|
|
434
|
+
case "Map":
|
|
435
|
+
str = '["Map"';
|
|
436
|
+
for (let [key, value2] of thing)
|
|
437
|
+
keys.push(
|
|
438
|
+
`.get(${is_primitive(key) ? stringify_primitive(key) : "..."})`
|
|
439
|
+
), str += `,${flatten(key)},${flatten(value2)}`;
|
|
440
|
+
str += "]";
|
|
441
|
+
break;
|
|
442
|
+
default:
|
|
443
|
+
if (!is_plain_object(thing))
|
|
444
|
+
throw new DevalueError(
|
|
445
|
+
"Cannot stringify arbitrary non-POJOs",
|
|
446
|
+
keys
|
|
447
|
+
);
|
|
448
|
+
if (Object.getOwnPropertySymbols(thing).length > 0)
|
|
449
|
+
throw new DevalueError(
|
|
450
|
+
"Cannot stringify POJOs with symbolic keys",
|
|
451
|
+
keys
|
|
452
|
+
);
|
|
453
|
+
if (Object.getPrototypeOf(thing) === null) {
|
|
454
|
+
str = '["null"';
|
|
455
|
+
for (let key in thing)
|
|
456
|
+
keys.push(`.${key}`), str += `,${stringify_string(key)},${flatten(thing[key])}`, keys.pop();
|
|
457
|
+
str += "]";
|
|
458
|
+
} else {
|
|
459
|
+
str = "{";
|
|
460
|
+
let started = !1;
|
|
461
|
+
for (let key in thing)
|
|
462
|
+
started && (str += ","), started = !0, keys.push(`.${key}`), str += `${stringify_string(key)}:${flatten(thing[key])}`, keys.pop();
|
|
463
|
+
str += "}";
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
return stringified[index2] = str, index2;
|
|
467
|
+
}
|
|
468
|
+
let index = flatten(value);
|
|
469
|
+
return index < 0 ? `${index}` : `[${stringified.join(",")}]`;
|
|
470
|
+
}
|
|
471
|
+
function stringify_primitive(thing) {
|
|
472
|
+
let type = typeof thing;
|
|
473
|
+
return type === "string" ? stringify_string(thing) : thing instanceof String ? stringify_string(thing.toString()) : thing === void 0 ? (-1).toString() : thing === 0 && 1 / thing < 0 ? (-6).toString() : type === "bigint" ? `["BigInt","${thing}"]` : String(thing);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// src/workers/core/proxy.worker.ts
|
|
477
|
+
import { readPrefix, reduceError } from "miniflare:shared";
|
|
478
|
+
|
|
479
|
+
// src/workers/core/devalue.ts
|
|
480
|
+
import assert from "node:assert";
|
|
481
|
+
import { Buffer } from "node:buffer";
|
|
482
|
+
var ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS = [
|
|
483
|
+
DataView,
|
|
484
|
+
Int8Array,
|
|
485
|
+
Uint8Array,
|
|
486
|
+
Uint8ClampedArray,
|
|
487
|
+
Int16Array,
|
|
488
|
+
Uint16Array,
|
|
489
|
+
Int32Array,
|
|
490
|
+
Uint32Array,
|
|
491
|
+
Float32Array,
|
|
492
|
+
Float64Array,
|
|
493
|
+
BigInt64Array,
|
|
494
|
+
BigUint64Array
|
|
495
|
+
], ALLOWED_ERROR_CONSTRUCTORS = [
|
|
496
|
+
EvalError,
|
|
497
|
+
RangeError,
|
|
498
|
+
ReferenceError,
|
|
499
|
+
SyntaxError,
|
|
500
|
+
TypeError,
|
|
501
|
+
URIError,
|
|
502
|
+
Error
|
|
503
|
+
// `Error` last so more specific error subclasses preferred
|
|
504
|
+
], structuredSerializableReducers = {
|
|
505
|
+
ArrayBuffer(value) {
|
|
506
|
+
if (value instanceof ArrayBuffer)
|
|
507
|
+
return [Buffer.from(value).toString("base64")];
|
|
508
|
+
},
|
|
509
|
+
ArrayBufferView(value) {
|
|
510
|
+
if (ArrayBuffer.isView(value))
|
|
511
|
+
return [
|
|
512
|
+
value.constructor.name,
|
|
513
|
+
value.buffer,
|
|
514
|
+
value.byteOffset,
|
|
515
|
+
value.byteLength
|
|
516
|
+
];
|
|
517
|
+
},
|
|
518
|
+
Error(value) {
|
|
519
|
+
for (let ctor of ALLOWED_ERROR_CONSTRUCTORS)
|
|
520
|
+
if (value instanceof ctor && value.name === ctor.name)
|
|
521
|
+
return [value.name, value.message, value.stack, value.cause];
|
|
522
|
+
if (value instanceof Error)
|
|
523
|
+
return ["Error", value.message, value.stack, value.cause];
|
|
524
|
+
}
|
|
525
|
+
}, structuredSerializableRevivers = {
|
|
526
|
+
ArrayBuffer(value) {
|
|
527
|
+
assert(Array.isArray(value));
|
|
528
|
+
let [encoded] = value;
|
|
529
|
+
assert(typeof encoded == "string");
|
|
530
|
+
let view = Buffer.from(encoded, "base64");
|
|
531
|
+
return view.buffer.slice(
|
|
532
|
+
view.byteOffset,
|
|
533
|
+
view.byteOffset + view.byteLength
|
|
534
|
+
);
|
|
535
|
+
},
|
|
536
|
+
ArrayBufferView(value) {
|
|
537
|
+
assert(Array.isArray(value));
|
|
538
|
+
let [name, buffer, byteOffset, byteLength] = value;
|
|
539
|
+
assert(typeof name == "string"), assert(buffer instanceof ArrayBuffer), assert(typeof byteOffset == "number"), assert(typeof byteLength == "number");
|
|
540
|
+
let ctor = globalThis[name];
|
|
541
|
+
assert(ALLOWED_ARRAY_BUFFER_VIEW_CONSTRUCTORS.includes(ctor));
|
|
542
|
+
let length = byteLength;
|
|
543
|
+
return "BYTES_PER_ELEMENT" in ctor && (length /= ctor.BYTES_PER_ELEMENT), new ctor(buffer, byteOffset, length);
|
|
544
|
+
},
|
|
545
|
+
Error(value) {
|
|
546
|
+
assert(Array.isArray(value));
|
|
547
|
+
let [name, message, stack, cause] = value;
|
|
548
|
+
assert(typeof name == "string"), assert(typeof message == "string"), assert(stack === void 0 || typeof stack == "string");
|
|
549
|
+
let ctor = globalThis[name];
|
|
550
|
+
assert(ALLOWED_ERROR_CONSTRUCTORS.includes(ctor));
|
|
551
|
+
let error = new ctor(message, { cause });
|
|
552
|
+
return error.stack = stack, error;
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
function createHTTPReducers(impl) {
|
|
556
|
+
return {
|
|
557
|
+
Headers(val) {
|
|
558
|
+
if (val instanceof impl.Headers)
|
|
559
|
+
return Object.fromEntries(val);
|
|
560
|
+
},
|
|
561
|
+
Request(val) {
|
|
562
|
+
if (val instanceof impl.Request)
|
|
563
|
+
return [val.method, val.url, val.headers, val.cf, val.body];
|
|
564
|
+
},
|
|
565
|
+
Response(val) {
|
|
566
|
+
if (val instanceof impl.Response)
|
|
567
|
+
return [val.status, val.statusText, val.headers, val.cf, val.body];
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function createHTTPRevivers(impl) {
|
|
572
|
+
return {
|
|
573
|
+
Headers(value) {
|
|
574
|
+
return assert(typeof value == "object" && value !== null), new impl.Headers(value);
|
|
575
|
+
},
|
|
576
|
+
Request(value) {
|
|
577
|
+
assert(Array.isArray(value));
|
|
578
|
+
let [method, url, headers, cf, body] = value;
|
|
579
|
+
return assert(typeof method == "string"), assert(typeof url == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Request(url, {
|
|
580
|
+
method,
|
|
581
|
+
headers,
|
|
582
|
+
cf,
|
|
583
|
+
// @ts-expect-error `duplex` is not required by `workerd` yet
|
|
584
|
+
duplex: body === null ? void 0 : "half",
|
|
585
|
+
body
|
|
586
|
+
});
|
|
587
|
+
},
|
|
588
|
+
Response(value) {
|
|
589
|
+
assert(Array.isArray(value));
|
|
590
|
+
let [status, statusText, headers, cf, body] = value;
|
|
591
|
+
return assert(typeof status == "number"), assert(typeof statusText == "string"), assert(headers instanceof impl.Headers), assert(body === null || impl.isReadableStream(body)), new impl.Response(body, {
|
|
592
|
+
status,
|
|
593
|
+
statusText,
|
|
594
|
+
headers,
|
|
595
|
+
cf
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
function stringifyWithStreams(impl, value, reducers, allowUnbufferedStream) {
|
|
601
|
+
let unbufferedStream, bufferPromises = [], streamReducers = {
|
|
602
|
+
ReadableStream(value2) {
|
|
603
|
+
if (impl.isReadableStream(value2))
|
|
604
|
+
return allowUnbufferedStream && unbufferedStream === void 0 ? unbufferedStream = value2 : bufferPromises.push(impl.bufferReadableStream(value2)), !0;
|
|
605
|
+
},
|
|
606
|
+
Blob(value2) {
|
|
607
|
+
if (value2 instanceof impl.Blob)
|
|
608
|
+
return bufferPromises.push(value2.arrayBuffer()), !0;
|
|
609
|
+
},
|
|
610
|
+
...reducers
|
|
611
|
+
};
|
|
612
|
+
typeof value == "function" && (value = new __MiniflareFunctionWrapper(
|
|
613
|
+
value
|
|
614
|
+
));
|
|
615
|
+
let stringifiedValue = stringify(value, streamReducers);
|
|
616
|
+
return bufferPromises.length === 0 ? { value: stringifiedValue, unbufferedStream } : Promise.all(bufferPromises).then((streamBuffers) => (streamReducers.ReadableStream = function(value2) {
|
|
617
|
+
if (impl.isReadableStream(value2))
|
|
618
|
+
return value2 === unbufferedStream ? !0 : streamBuffers.shift();
|
|
619
|
+
}, streamReducers.Blob = function(value2) {
|
|
620
|
+
if (value2 instanceof impl.Blob) {
|
|
621
|
+
let array = [streamBuffers.shift(), value2.type];
|
|
622
|
+
return value2 instanceof impl.File && array.push(value2.name, value2.lastModified), array;
|
|
623
|
+
}
|
|
624
|
+
}, { value: stringify(value, streamReducers), unbufferedStream }));
|
|
625
|
+
}
|
|
626
|
+
var __MiniflareFunctionWrapper = class {
|
|
627
|
+
constructor(fnWithProps) {
|
|
628
|
+
return new Proxy(this, {
|
|
629
|
+
get: (_, key) => key === "__miniflareWrappedFunction" ? fnWithProps : fnWithProps[key]
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
};
|
|
633
|
+
function parseWithReadableStreams(impl, stringified, revivers) {
|
|
634
|
+
let streamRevivers = {
|
|
635
|
+
ReadableStream(value) {
|
|
636
|
+
return value === !0 ? (assert(stringified.unbufferedStream !== void 0), stringified.unbufferedStream) : (assert(value instanceof ArrayBuffer), impl.unbufferReadableStream(value));
|
|
637
|
+
},
|
|
638
|
+
Blob(value) {
|
|
639
|
+
if (assert(Array.isArray(value)), value.length === 2) {
|
|
640
|
+
let [buffer, type] = value;
|
|
641
|
+
assert(buffer instanceof ArrayBuffer), assert(typeof type == "string");
|
|
642
|
+
let opts = {};
|
|
643
|
+
return type !== "" && (opts.type = type), new impl.Blob([buffer], opts);
|
|
644
|
+
} else {
|
|
645
|
+
assert(value.length === 4);
|
|
646
|
+
let [buffer, type, name, lastModified] = value;
|
|
647
|
+
assert(buffer instanceof ArrayBuffer), assert(typeof type == "string"), assert(typeof name == "string"), assert(typeof lastModified == "number");
|
|
648
|
+
let opts = { lastModified };
|
|
649
|
+
return type !== "" && (opts.type = type), new impl.File([buffer], name, opts);
|
|
650
|
+
}
|
|
651
|
+
},
|
|
652
|
+
...revivers
|
|
653
|
+
};
|
|
654
|
+
return parse(stringified.value, streamRevivers);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// src/workers/core/proxy.worker.ts
|
|
658
|
+
var ENCODER = new TextEncoder(), DECODER = new TextDecoder(), ALLOWED_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"], WORKERS_PLATFORM_IMPL = {
|
|
659
|
+
Blob,
|
|
660
|
+
File,
|
|
661
|
+
Headers,
|
|
662
|
+
Request,
|
|
663
|
+
Response,
|
|
664
|
+
isReadableStream(value) {
|
|
665
|
+
return value instanceof ReadableStream;
|
|
666
|
+
},
|
|
667
|
+
bufferReadableStream(stream) {
|
|
668
|
+
return new Response(stream).arrayBuffer();
|
|
669
|
+
},
|
|
670
|
+
unbufferReadableStream(buffer) {
|
|
671
|
+
let body = new Response(buffer).body;
|
|
672
|
+
return assert2(body !== null), body;
|
|
673
|
+
}
|
|
674
|
+
}, objectProtoNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
|
|
675
|
+
function isPlainObject(value) {
|
|
676
|
+
let proto = Object.getPrototypeOf(value);
|
|
677
|
+
return value?.constructor?.name === "RpcStub" || isObject(value) && objectContainsFunctions(value) ? !1 : proto === Object.prototype || proto === null || Object.getOwnPropertyNames(proto).sort().join("\0") === objectProtoNames;
|
|
678
|
+
}
|
|
679
|
+
function objectContainsFunctions(obj) {
|
|
680
|
+
let propertyNames = Object.getOwnPropertyNames(obj), propertySymbols = Object.getOwnPropertySymbols(obj), properties = [...propertyNames, ...propertySymbols];
|
|
681
|
+
for (let property of properties) {
|
|
682
|
+
let entry = obj[property];
|
|
683
|
+
if (typeof entry == "function" || isObject(entry) && objectContainsFunctions(entry))
|
|
684
|
+
return !0;
|
|
685
|
+
}
|
|
686
|
+
return !1;
|
|
687
|
+
}
|
|
688
|
+
function isObject(value) {
|
|
689
|
+
return !!value && typeof value == "object";
|
|
690
|
+
}
|
|
691
|
+
function getType(value) {
|
|
692
|
+
return Object.prototype.toString.call(value).slice(8, -1);
|
|
693
|
+
}
|
|
694
|
+
function isInternal(value) {
|
|
695
|
+
return isObject(value) && value[Symbol.for("cloudflare:internal-class")];
|
|
696
|
+
}
|
|
697
|
+
var ProxyServer = class {
|
|
698
|
+
constructor(_state, env) {
|
|
699
|
+
this.env = env;
|
|
700
|
+
this.heap.set(ProxyAddresses.GLOBAL, globalThis), this.heap.set(ProxyAddresses.ENV, env);
|
|
701
|
+
}
|
|
702
|
+
nextHeapAddress = ProxyAddresses.USER_START;
|
|
703
|
+
heap = /* @__PURE__ */ new Map();
|
|
704
|
+
reducers = {
|
|
705
|
+
...structuredSerializableReducers,
|
|
706
|
+
...createHTTPReducers(WORKERS_PLATFORM_IMPL),
|
|
707
|
+
// Corresponding revivers in `ProxyClient`
|
|
708
|
+
// `Native` reducer *MUST* be applied last
|
|
709
|
+
Native: (value) => {
|
|
710
|
+
let type = getType(value);
|
|
711
|
+
if ((type === "Object" || isInternal(value)) && !isPlainObject(value) || type === "Promise") {
|
|
712
|
+
let address = this.nextHeapAddress++;
|
|
713
|
+
this.heap.set(address, value), assert2(value !== null);
|
|
714
|
+
let name = value?.constructor.name, isFunction = value instanceof __MiniflareFunctionWrapper;
|
|
715
|
+
return [address, name, isFunction];
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
revivers = {
|
|
720
|
+
...structuredSerializableRevivers,
|
|
721
|
+
...createHTTPRevivers(WORKERS_PLATFORM_IMPL),
|
|
722
|
+
// Corresponding reducers in `ProxyClient`
|
|
723
|
+
Native: (value) => {
|
|
724
|
+
assert2(Array.isArray(value));
|
|
725
|
+
let [address] = value;
|
|
726
|
+
assert2(typeof address == "number");
|
|
727
|
+
let heapValue = this.heap.get(address);
|
|
728
|
+
return assert2(heapValue !== void 0), heapValue instanceof Promise && this.heap.delete(address), heapValue;
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
nativeReviver = { Native: this.revivers.Native };
|
|
732
|
+
async fetch(request) {
|
|
733
|
+
try {
|
|
734
|
+
return await this.#fetch(request);
|
|
735
|
+
} catch (e) {
|
|
736
|
+
let error = reduceError(e);
|
|
737
|
+
return Response.json(error, {
|
|
738
|
+
status: 500,
|
|
739
|
+
headers: { [CoreHeaders.ERROR_STACK]: "true" }
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
async #fetch(request) {
|
|
744
|
+
let hostHeader = request.headers.get("Host");
|
|
745
|
+
if (hostHeader == null)
|
|
746
|
+
return new Response(null, { status: 400 });
|
|
747
|
+
try {
|
|
748
|
+
let host = new URL(`http://${hostHeader}`);
|
|
749
|
+
if (!ALLOWED_HOSTNAMES.includes(host.hostname))
|
|
750
|
+
return new Response(null, { status: 401 });
|
|
751
|
+
} catch {
|
|
752
|
+
return new Response(null, { status: 400 });
|
|
753
|
+
}
|
|
754
|
+
let secretHex = request.headers.get(CoreHeaders.OP_SECRET);
|
|
755
|
+
if (secretHex == null)
|
|
756
|
+
return new Response(null, { status: 401 });
|
|
757
|
+
let expectedSecret = this.env[CoreBindings.DATA_PROXY_SECRET], secretBuffer = Buffer2.from(secretHex, "hex");
|
|
758
|
+
if (secretBuffer.byteLength !== expectedSecret.byteLength || !crypto.subtle.timingSafeEqual(secretBuffer, expectedSecret))
|
|
759
|
+
return new Response(null, { status: 401 });
|
|
760
|
+
let opHeader = request.headers.get(CoreHeaders.OP), targetHeader = request.headers.get(CoreHeaders.OP_TARGET), keyHeader = request.headers.get(CoreHeaders.OP_KEY), allowAsync = request.headers.get(CoreHeaders.OP_SYNC) === null, argsSizeHeader = request.headers.get(CoreHeaders.OP_STRINGIFIED_SIZE), contentLengthHeader = request.headers.get("Content-Length");
|
|
761
|
+
if (targetHeader === null)
|
|
762
|
+
return new Response(null, { status: 400 });
|
|
763
|
+
if (opHeader === ProxyOps.FREE) {
|
|
764
|
+
for (let targetValue of targetHeader.split(",")) {
|
|
765
|
+
let targetAddress = parseInt(targetValue);
|
|
766
|
+
assert2(!Number.isNaN(targetAddress)), this.heap.delete(targetAddress);
|
|
767
|
+
}
|
|
768
|
+
return new Response(null, { status: 204 });
|
|
769
|
+
}
|
|
770
|
+
let target = parse(
|
|
771
|
+
targetHeader,
|
|
772
|
+
this.nativeReviver
|
|
773
|
+
), targetName = target.constructor.name, status = 200, result, unbufferedRest;
|
|
774
|
+
if (opHeader === ProxyOps.GET) {
|
|
775
|
+
if (result = keyHeader === null ? target : target[keyHeader], result?.constructor.name === "RpcProperty" && (result = await result), typeof result == "function")
|
|
776
|
+
return new Response(null, {
|
|
777
|
+
status: 204,
|
|
778
|
+
headers: { [CoreHeaders.OP_RESULT_TYPE]: "Function" }
|
|
779
|
+
});
|
|
780
|
+
} else if (opHeader === ProxyOps.GET_OWN_DESCRIPTOR) {
|
|
781
|
+
if (keyHeader === null)
|
|
782
|
+
return new Response(null, { status: 400 });
|
|
783
|
+
let descriptor = Object.getOwnPropertyDescriptor(target, keyHeader);
|
|
784
|
+
descriptor !== void 0 && (result = {
|
|
785
|
+
configurable: descriptor.configurable,
|
|
786
|
+
enumerable: descriptor.enumerable,
|
|
787
|
+
writable: descriptor.writable
|
|
788
|
+
});
|
|
789
|
+
} else if (opHeader === ProxyOps.GET_OWN_KEYS)
|
|
790
|
+
result = Object.getOwnPropertyNames(target);
|
|
791
|
+
else if (opHeader === ProxyOps.CALL) {
|
|
792
|
+
assert2(keyHeader !== null);
|
|
793
|
+
let func = target[keyHeader];
|
|
794
|
+
if (assert2(typeof func == "function"), isFetcherFetch(targetName, keyHeader)) {
|
|
795
|
+
let originalUrl = request.headers.get(CoreHeaders.ORIGINAL_URL), url = new URL(originalUrl ?? request.url);
|
|
796
|
+
return request = new Request(url, request), request.headers.delete(CoreHeaders.OP_SECRET), request.headers.delete(CoreHeaders.OP), request.headers.delete(CoreHeaders.OP_TARGET), request.headers.delete(CoreHeaders.OP_KEY), request.headers.delete(CoreHeaders.ORIGINAL_URL), request.headers.delete(CoreHeaders.DISABLE_PRETTY_ERROR), func.call(target, request);
|
|
797
|
+
}
|
|
798
|
+
let args;
|
|
799
|
+
if (argsSizeHeader === null || argsSizeHeader === contentLengthHeader)
|
|
800
|
+
args = parseWithReadableStreams(
|
|
801
|
+
WORKERS_PLATFORM_IMPL,
|
|
802
|
+
{ value: await request.text() },
|
|
803
|
+
this.revivers
|
|
804
|
+
);
|
|
805
|
+
else {
|
|
806
|
+
let argsSize = parseInt(argsSizeHeader);
|
|
807
|
+
assert2(!Number.isNaN(argsSize)), assert2(request.body !== null);
|
|
808
|
+
let [encodedArgs, rest] = await readPrefix(request.body, argsSize);
|
|
809
|
+
unbufferedRest = rest;
|
|
810
|
+
let stringifiedArgs = DECODER.decode(encodedArgs);
|
|
811
|
+
args = parseWithReadableStreams(
|
|
812
|
+
WORKERS_PLATFORM_IMPL,
|
|
813
|
+
{ value: stringifiedArgs, unbufferedStream: rest },
|
|
814
|
+
this.revivers
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
assert2(Array.isArray(args));
|
|
818
|
+
try {
|
|
819
|
+
["RpcProperty", "RpcStub"].includes(func.constructor.name) ? result = await func(...args) : result = func.apply(target, args), isR2ObjectWriteHttpMetadata(targetName, keyHeader) && (result = args[0]);
|
|
820
|
+
} catch (e) {
|
|
821
|
+
status = 500, result = e;
|
|
822
|
+
}
|
|
823
|
+
} else
|
|
824
|
+
return new Response(null, { status: 404 });
|
|
825
|
+
let headers = new Headers();
|
|
826
|
+
if (allowAsync && result instanceof Promise) {
|
|
827
|
+
try {
|
|
828
|
+
result = await result;
|
|
829
|
+
} catch (e) {
|
|
830
|
+
status = 500, result = e;
|
|
831
|
+
}
|
|
832
|
+
headers.append(CoreHeaders.OP_RESULT_TYPE, "Promise");
|
|
833
|
+
}
|
|
834
|
+
if (unbufferedRest !== void 0 && !unbufferedRest.locked)
|
|
835
|
+
try {
|
|
836
|
+
await unbufferedRest.pipeTo(new WritableStream());
|
|
837
|
+
} catch {
|
|
838
|
+
}
|
|
839
|
+
if (result instanceof ReadableStream)
|
|
840
|
+
return headers.append(CoreHeaders.OP_RESULT_TYPE, "ReadableStream"), new Response(result, { status, headers });
|
|
841
|
+
{
|
|
842
|
+
let stringified = await stringifyWithStreams(
|
|
843
|
+
WORKERS_PLATFORM_IMPL,
|
|
844
|
+
result,
|
|
845
|
+
this.reducers,
|
|
846
|
+
/* allowUnbufferedStream */
|
|
847
|
+
allowAsync
|
|
848
|
+
);
|
|
849
|
+
if (stringified.unbufferedStream === void 0)
|
|
850
|
+
return new Response(stringified.value, { status, headers });
|
|
851
|
+
{
|
|
852
|
+
let body = new IdentityTransformStream(), encodedValue = ENCODER.encode(stringified.value), encodedSize = encodedValue.byteLength.toString();
|
|
853
|
+
return headers.set(CoreHeaders.OP_STRINGIFIED_SIZE, encodedSize), this.#writeWithUnbufferedStream(
|
|
854
|
+
body.writable,
|
|
855
|
+
encodedValue,
|
|
856
|
+
stringified.unbufferedStream
|
|
857
|
+
), new Response(body.readable, { status, headers });
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
async #writeWithUnbufferedStream(writable, encodedValue, unbufferedStream) {
|
|
862
|
+
let writer = writable.getWriter();
|
|
863
|
+
await writer.write(encodedValue), writer.releaseLock(), await unbufferedStream.pipeTo(writable);
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
|
|
867
|
+
// src/workers/core/entry.worker.ts
|
|
868
|
+
var encoder = new TextEncoder();
|
|
869
|
+
function getUserRequest(request, env) {
|
|
870
|
+
let originalUrl = request.headers.get(CoreHeaders.ORIGINAL_URL), url = new URL(originalUrl ?? request.url), rewriteHeadersFromOriginalUrl = !1, proxySharedSecret = request.headers.get(
|
|
871
|
+
CoreHeaders.PROXY_SHARED_SECRET
|
|
872
|
+
);
|
|
873
|
+
if (proxySharedSecret) {
|
|
874
|
+
let secretFromHeader = encoder.encode(proxySharedSecret), configuredSecret = env[CoreBindings.DATA_PROXY_SHARED_SECRET];
|
|
875
|
+
if (secretFromHeader.byteLength === configuredSecret?.byteLength && crypto.subtle.timingSafeEqual(secretFromHeader, configuredSecret))
|
|
876
|
+
rewriteHeadersFromOriginalUrl = !0;
|
|
877
|
+
else
|
|
878
|
+
throw new HttpError(
|
|
879
|
+
400,
|
|
880
|
+
`Disallowed header in request: ${CoreHeaders.PROXY_SHARED_SECRET}=${proxySharedSecret}`
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
let upstreamUrl = env[CoreBindings.TEXT_UPSTREAM_URL];
|
|
884
|
+
if (upstreamUrl !== void 0) {
|
|
885
|
+
let path = url.pathname + url.search;
|
|
886
|
+
path.startsWith("/") && (path = `./${path.substring(1)}`), url = new URL(path, upstreamUrl), rewriteHeadersFromOriginalUrl = !0;
|
|
887
|
+
}
|
|
888
|
+
if (request = new Request(url, request), request.cf === void 0) {
|
|
889
|
+
let cf = {
|
|
890
|
+
...env[CoreBindings.JSON_CF_BLOB],
|
|
891
|
+
// Defaulting to empty string to preserve undefined `Accept-Encoding`
|
|
892
|
+
// through Wrangler's proxy worker.
|
|
893
|
+
clientAcceptEncoding: request.headers.get("Accept-Encoding") ?? ""
|
|
894
|
+
};
|
|
895
|
+
request = new Request(request, { cf });
|
|
896
|
+
}
|
|
897
|
+
return request.headers.set("Accept-Encoding", "br, gzip"), rewriteHeadersFromOriginalUrl && request.headers.set("Host", url.host), request.headers.delete(CoreHeaders.PROXY_SHARED_SECRET), request.headers.delete(CoreHeaders.ORIGINAL_URL), request.headers.delete(CoreHeaders.DISABLE_PRETTY_ERROR), request;
|
|
898
|
+
}
|
|
899
|
+
function getTargetService(request, url, env) {
|
|
900
|
+
let service = env[CoreBindings.SERVICE_USER_FALLBACK], override = request.headers.get(CoreHeaders.ROUTE_OVERRIDE);
|
|
901
|
+
request.headers.delete(CoreHeaders.ROUTE_OVERRIDE);
|
|
902
|
+
let route = override ?? matchRoutes(env[CoreBindings.JSON_ROUTES], url);
|
|
903
|
+
return route !== null && (service = env[`${CoreBindings.SERVICE_USER_ROUTE_PREFIX}${route}`]), service;
|
|
904
|
+
}
|
|
905
|
+
function maybePrettifyError(request, response, env) {
|
|
906
|
+
return response.status !== 500 || response.headers.get(CoreHeaders.ERROR_STACK) === null ? response : env[CoreBindings.SERVICE_LOOPBACK].fetch(
|
|
907
|
+
"http://localhost/core/error",
|
|
908
|
+
{
|
|
909
|
+
method: "POST",
|
|
910
|
+
headers: request.headers,
|
|
911
|
+
body: response.body,
|
|
912
|
+
cf: { prettyErrorOriginalUrl: request.url }
|
|
913
|
+
}
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
function maybeInjectLiveReload(response, env, ctx) {
|
|
917
|
+
let liveReloadScript = env[CoreBindings.DATA_LIVE_RELOAD_SCRIPT];
|
|
918
|
+
if (liveReloadScript === void 0 || !response.headers.get("Content-Type")?.toLowerCase().includes("text/html"))
|
|
919
|
+
return response;
|
|
920
|
+
let headers = new Headers(response.headers), contentLength = parseInt(headers.get("content-length"));
|
|
921
|
+
isNaN(contentLength) || headers.set(
|
|
922
|
+
"content-length",
|
|
923
|
+
String(contentLength + liveReloadScript.byteLength)
|
|
924
|
+
);
|
|
925
|
+
let { readable, writable } = new IdentityTransformStream();
|
|
926
|
+
return ctx.waitUntil(
|
|
927
|
+
(async () => {
|
|
928
|
+
await response.body?.pipeTo(writable, { preventClose: !0 });
|
|
929
|
+
let writer = writable.getWriter();
|
|
930
|
+
await writer.write(liveReloadScript), await writer.close();
|
|
931
|
+
})()
|
|
932
|
+
), new Response(readable, {
|
|
933
|
+
status: response.status,
|
|
934
|
+
statusText: response.statusText,
|
|
935
|
+
headers
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
var acceptEncodingElement = /^(?<coding>[a-z]+|\*)(?:\s*;\s*q=(?<weight>\d+(?:.\d+)?))?$/;
|
|
939
|
+
function maybeParseAcceptEncodingElement(element) {
|
|
940
|
+
let match = acceptEncodingElement.exec(element);
|
|
941
|
+
if (match?.groups != null)
|
|
942
|
+
return {
|
|
943
|
+
coding: match.groups.coding,
|
|
944
|
+
weight: match.groups.weight === void 0 ? 1 : parseFloat(match.groups.weight)
|
|
945
|
+
};
|
|
946
|
+
}
|
|
947
|
+
function parseAcceptEncoding(header) {
|
|
948
|
+
let encodings = [];
|
|
949
|
+
for (let element of header.split(",")) {
|
|
950
|
+
let maybeEncoding = maybeParseAcceptEncodingElement(element.trim());
|
|
951
|
+
maybeEncoding !== void 0 && encodings.push(maybeEncoding);
|
|
952
|
+
}
|
|
953
|
+
return encodings.sort((a, b) => b.weight - a.weight);
|
|
954
|
+
}
|
|
955
|
+
function ensureAcceptableEncoding(clientAcceptEncoding, response) {
|
|
956
|
+
if (clientAcceptEncoding === null)
|
|
957
|
+
return response;
|
|
958
|
+
let encodings = parseAcceptEncoding(clientAcceptEncoding);
|
|
959
|
+
if (encodings.length === 0)
|
|
960
|
+
return response;
|
|
961
|
+
let contentEncoding = response.headers.get("Content-Encoding"), contentType = response.headers.get("Content-Type");
|
|
962
|
+
if (!isCompressedByCloudflareFL(contentType) || contentEncoding !== null && contentEncoding !== "gzip" && contentEncoding !== "br")
|
|
963
|
+
return response;
|
|
964
|
+
let desiredEncoding, identityDisallowed = !1;
|
|
965
|
+
for (let encoding of encodings)
|
|
966
|
+
if (encoding.weight === 0)
|
|
967
|
+
(encoding.coding === "identity" || encoding.coding === "*") && (identityDisallowed = !0);
|
|
968
|
+
else if (encoding.coding === "gzip" || encoding.coding === "br") {
|
|
969
|
+
desiredEncoding = encoding.coding;
|
|
970
|
+
break;
|
|
971
|
+
} else if (encoding.coding === "identity")
|
|
972
|
+
break;
|
|
973
|
+
return desiredEncoding === void 0 ? identityDisallowed ? new Response("Unsupported Media Type", {
|
|
974
|
+
status: 415,
|
|
975
|
+
headers: { "Accept-Encoding": "br, gzip" }
|
|
976
|
+
}) : (contentEncoding === null || (response = new Response(response.body, response), response.headers.delete("Content-Encoding")), response) : (contentEncoding === desiredEncoding || (response = new Response(response.body, response), response.headers.set("Content-Encoding", desiredEncoding)), response);
|
|
977
|
+
}
|
|
978
|
+
function colourFromHTTPStatus(status) {
|
|
979
|
+
return 200 <= status && status < 300 ? green : 400 <= status && status < 500 ? yellow : 500 <= status ? red : blue;
|
|
980
|
+
}
|
|
981
|
+
function maybeLogRequest(req, res, env, ctx, startTime) {
|
|
982
|
+
if (env[CoreBindings.JSON_LOG_LEVEL] < LogLevel.INFO)
|
|
983
|
+
return;
|
|
984
|
+
let url = new URL(req.url), statusText = (res.statusText.trim() || STATUS_CODES[res.status]) ?? "", lines = [
|
|
985
|
+
`${bold(req.method)} ${url.pathname} `,
|
|
986
|
+
colourFromHTTPStatus(res.status)(`${bold(res.status)} ${statusText} `),
|
|
987
|
+
grey(`(${Date.now() - startTime}ms)`)
|
|
988
|
+
], message = reset(lines.join(""));
|
|
989
|
+
ctx.waitUntil(
|
|
990
|
+
env[CoreBindings.SERVICE_LOOPBACK].fetch("http://localhost/core/log", {
|
|
991
|
+
method: "POST",
|
|
992
|
+
headers: { [SharedHeaders.LOG_LEVEL]: LogLevel.INFO.toString() },
|
|
993
|
+
body: message
|
|
994
|
+
})
|
|
995
|
+
);
|
|
996
|
+
}
|
|
997
|
+
function handleProxy(request, env) {
|
|
998
|
+
let ns = env[CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY], id = ns.idFromName("");
|
|
999
|
+
return ns.get(id).fetch(request);
|
|
1000
|
+
}
|
|
1001
|
+
async function handleScheduled(params, service) {
|
|
1002
|
+
let time = params.get("time"), scheduledTime = time ? new Date(parseInt(time)) : void 0, cron = params.get("cron") ?? void 0, result = await service.scheduled({
|
|
1003
|
+
scheduledTime,
|
|
1004
|
+
cron
|
|
1005
|
+
});
|
|
1006
|
+
return new Response(result.outcome, {
|
|
1007
|
+
status: result.outcome === "ok" ? 200 : 500
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
var entry_worker_default = {
|
|
1011
|
+
async fetch(request, env, ctx) {
|
|
1012
|
+
let startTime = Date.now();
|
|
1013
|
+
if (request.headers.get(CoreHeaders.OP) !== null)
|
|
1014
|
+
return handleProxy(request, env);
|
|
1015
|
+
let disablePrettyErrorPage = request.headers.get(CoreHeaders.DISABLE_PRETTY_ERROR) !== null, clientAcceptEncoding = request.headers.get("Accept-Encoding");
|
|
1016
|
+
try {
|
|
1017
|
+
request = getUserRequest(request, env);
|
|
1018
|
+
} catch (e) {
|
|
1019
|
+
if (e instanceof HttpError)
|
|
1020
|
+
return e.toResponse();
|
|
1021
|
+
throw e;
|
|
1022
|
+
}
|
|
1023
|
+
let url = new URL(request.url), service = getTargetService(request, url, env);
|
|
1024
|
+
if (service === void 0)
|
|
1025
|
+
return new Response("No entrypoint worker found", { status: 404 });
|
|
1026
|
+
try {
|
|
1027
|
+
if (url.pathname === "/cdn-cgi/mf/scheduled")
|
|
1028
|
+
return await handleScheduled(url.searchParams, service);
|
|
1029
|
+
let response = await service.fetch(request);
|
|
1030
|
+
return disablePrettyErrorPage || (response = await maybePrettifyError(request, response, env)), response = maybeInjectLiveReload(response, env, ctx), response = ensureAcceptableEncoding(clientAcceptEncoding, response), maybeLogRequest(request, response, env, ctx, startTime), response;
|
|
1031
|
+
} catch (e) {
|
|
1032
|
+
return new Response(e?.stack ?? String(e), { status: 500 });
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
export {
|
|
1037
|
+
ProxyServer,
|
|
1038
|
+
entry_worker_default as default
|
|
1039
|
+
};
|
|
1040
|
+
//# sourceMappingURL=entry.worker.js.map
|