@depup/miniflare 4.20260317.0-depup.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.
Files changed (91) hide show
  1. package/README.md +31 -0
  2. package/bootstrap.js +11 -0
  3. package/changes.json +10 -0
  4. package/dist/local-explorer-ui/assets/Breadcrumbs-7hjI0sYt.js +1 -0
  5. package/dist/local-explorer-ui/assets/TableSelect-_bi6l6Iv.js +25 -0
  6. package/dist/local-explorer-ui/assets/_className-gSkjniQn.js +1 -0
  7. package/dist/local-explorer-ui/assets/_databaseId-DWcfgBis.js +1 -0
  8. package/dist/local-explorer-ui/assets/_namespaceId-8ViM8VDL.js +1 -0
  9. package/dist/local-explorer-ui/assets/_objectId-X6x-JUph.js +1 -0
  10. package/dist/local-explorer-ui/assets/dropdown-DFeFcKfn-BCd_NRZS.js +1 -0
  11. package/dist/local-explorer-ui/assets/index-BFNDwiew.js +42 -0
  12. package/dist/local-explorer-ui/assets/index-CLSFsgi0.js +1 -0
  13. package/dist/local-explorer-ui/assets/index-KG4JeHCX.js +1 -0
  14. package/dist/local-explorer-ui/assets/index-mgoUmSld.css +1 -0
  15. package/dist/local-explorer-ui/assets/table-BUmvaBj8-v-EIZgOz.js +1 -0
  16. package/dist/local-explorer-ui/favicon.svg +3 -0
  17. package/dist/local-explorer-ui/index.html +14 -0
  18. package/dist/src/index.d.ts +8703 -0
  19. package/dist/src/index.js +83666 -0
  20. package/dist/src/index.js.map +6 -0
  21. package/dist/src/shared/dev-registry.worker.js +69801 -0
  22. package/dist/src/shared/dev-registry.worker.js.map +6 -0
  23. package/dist/src/workers/analytics-engine/analytics-engine.worker.js +15 -0
  24. package/dist/src/workers/analytics-engine/analytics-engine.worker.js.map +6 -0
  25. package/dist/src/workers/assets/assets-kv.worker.js +28 -0
  26. package/dist/src/workers/assets/assets-kv.worker.js.map +6 -0
  27. package/dist/src/workers/assets/assets.worker.js +9014 -0
  28. package/dist/src/workers/assets/assets.worker.js.map +6 -0
  29. package/dist/src/workers/assets/router.worker.js +9625 -0
  30. package/dist/src/workers/assets/router.worker.js.map +6 -0
  31. package/dist/src/workers/assets/rpc-proxy.worker.js +29 -0
  32. package/dist/src/workers/assets/rpc-proxy.worker.js.map +6 -0
  33. package/dist/src/workers/browser-rendering/binding.worker.js +129 -0
  34. package/dist/src/workers/browser-rendering/binding.worker.js.map +6 -0
  35. package/dist/src/workers/cache/cache-entry-noop.worker.js +19 -0
  36. package/dist/src/workers/cache/cache-entry-noop.worker.js.map +6 -0
  37. package/dist/src/workers/cache/cache-entry.worker.js +28 -0
  38. package/dist/src/workers/cache/cache-entry.worker.js.map +6 -0
  39. package/dist/src/workers/cache/cache.worker.js +653 -0
  40. package/dist/src/workers/cache/cache.worker.js.map +6 -0
  41. package/dist/src/workers/core/do-wrapper.worker.js +43 -0
  42. package/dist/src/workers/core/do-wrapper.worker.js.map +6 -0
  43. package/dist/src/workers/core/entry.worker.js +4633 -0
  44. package/dist/src/workers/core/entry.worker.js.map +6 -0
  45. package/dist/src/workers/core/strip-cf-connecting-ip.worker.js +11 -0
  46. package/dist/src/workers/core/strip-cf-connecting-ip.worker.js.map +6 -0
  47. package/dist/src/workers/d1/database.worker.js +219 -0
  48. package/dist/src/workers/d1/database.worker.js.map +6 -0
  49. package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2271 -0
  50. package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js.map +6 -0
  51. package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +12 -0
  52. package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js.map +6 -0
  53. package/dist/src/workers/email/email.worker.js +23 -0
  54. package/dist/src/workers/email/email.worker.js.map +6 -0
  55. package/dist/src/workers/email/send_email.worker.js +3294 -0
  56. package/dist/src/workers/email/send_email.worker.js.map +6 -0
  57. package/dist/src/workers/hello-world/binding.worker.js +19 -0
  58. package/dist/src/workers/hello-world/binding.worker.js.map +6 -0
  59. package/dist/src/workers/hello-world/object.worker.js +14 -0
  60. package/dist/src/workers/hello-world/object.worker.js.map +6 -0
  61. package/dist/src/workers/images/images.worker.js +155 -0
  62. package/dist/src/workers/images/images.worker.js.map +6 -0
  63. package/dist/src/workers/kv/namespace.worker.js +322 -0
  64. package/dist/src/workers/kv/namespace.worker.js.map +6 -0
  65. package/dist/src/workers/kv/sites.worker.js +146 -0
  66. package/dist/src/workers/kv/sites.worker.js.map +6 -0
  67. package/dist/src/workers/local-explorer/explorer.worker.js +5245 -0
  68. package/dist/src/workers/local-explorer/explorer.worker.js.map +6 -0
  69. package/dist/src/workers/pipelines/pipeline.worker.js +10 -0
  70. package/dist/src/workers/pipelines/pipeline.worker.js.map +6 -0
  71. package/dist/src/workers/queues/broker.worker.js +289 -0
  72. package/dist/src/workers/queues/broker.worker.js.map +6 -0
  73. package/dist/src/workers/r2/bucket.worker.js +1134 -0
  74. package/dist/src/workers/r2/bucket.worker.js.map +6 -0
  75. package/dist/src/workers/ratelimit/ratelimit.worker.js +54 -0
  76. package/dist/src/workers/ratelimit/ratelimit.worker.js.map +6 -0
  77. package/dist/src/workers/secrets-store/secret.worker.js +65 -0
  78. package/dist/src/workers/secrets-store/secret.worker.js.map +6 -0
  79. package/dist/src/workers/shared/index.worker.js +693 -0
  80. package/dist/src/workers/shared/index.worker.js.map +6 -0
  81. package/dist/src/workers/shared/object-entry.worker.js +21 -0
  82. package/dist/src/workers/shared/object-entry.worker.js.map +6 -0
  83. package/dist/src/workers/shared/remote-proxy-client.worker.js +2271 -0
  84. package/dist/src/workers/shared/remote-proxy-client.worker.js.map +6 -0
  85. package/dist/src/workers/shared/zod.worker.js +2954 -0
  86. package/dist/src/workers/shared/zod.worker.js.map +6 -0
  87. package/dist/src/workers/workflows/binding.worker.js +2422 -0
  88. package/dist/src/workers/workflows/binding.worker.js.map +6 -0
  89. package/dist/src/workers/workflows/wrapped-binding.worker.js +71 -0
  90. package/dist/src/workers/workflows/wrapped-binding.worker.js.map +6 -0
  91. package/package.json +139 -0
@@ -0,0 +1,653 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __commonJS = (cb, mod) => function() {
7
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from == "object" || typeof from == "function")
11
+ for (let key of __getOwnPropNames(from))
12
+ !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ return to;
14
+ };
15
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
+ // If the importer is in node compatibility mode or this is not an ESM
17
+ // file that has been converted to a CommonJS file using a Babel-
18
+ // compatible transform (i.e. "__esModule" has not been set), then set
19
+ // "default" to the CommonJS "module.exports" for node compatibility.
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
21
+ mod
22
+ ));
23
+ var __decorateClass = (decorators, target, key, kind) => {
24
+ for (var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target, i = decorators.length - 1, decorator; i >= 0; i--)
25
+ (decorator = decorators[i]) && (result = (kind ? decorator(target, key, result) : decorator(result)) || result);
26
+ return kind && result && __defProp(target, key, result), result;
27
+ };
28
+
29
+ // ../../node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js
30
+ var require_http_cache_semantics = __commonJS({
31
+ "../../node_modules/.pnpm/http-cache-semantics@4.1.1/node_modules/http-cache-semantics/index.js"(exports, module) {
32
+ "use strict";
33
+ var statusCodeCacheableByDefault = /* @__PURE__ */ new Set([
34
+ 200,
35
+ 203,
36
+ 204,
37
+ 206,
38
+ 300,
39
+ 301,
40
+ 308,
41
+ 404,
42
+ 405,
43
+ 410,
44
+ 414,
45
+ 501
46
+ ]), understoodStatuses = /* @__PURE__ */ new Set([
47
+ 200,
48
+ 203,
49
+ 204,
50
+ 300,
51
+ 301,
52
+ 302,
53
+ 303,
54
+ 307,
55
+ 308,
56
+ 404,
57
+ 405,
58
+ 410,
59
+ 414,
60
+ 501
61
+ ]), errorStatusCodes = /* @__PURE__ */ new Set([
62
+ 500,
63
+ 502,
64
+ 503,
65
+ 504
66
+ ]), hopByHopHeaders = {
67
+ date: !0,
68
+ // included, because we add Age update Date
69
+ connection: !0,
70
+ "keep-alive": !0,
71
+ "proxy-authenticate": !0,
72
+ "proxy-authorization": !0,
73
+ te: !0,
74
+ trailer: !0,
75
+ "transfer-encoding": !0,
76
+ upgrade: !0
77
+ }, excludedFromRevalidationUpdate = {
78
+ // Since the old body is reused, it doesn't make sense to change properties of the body
79
+ "content-length": !0,
80
+ "content-encoding": !0,
81
+ "transfer-encoding": !0,
82
+ "content-range": !0
83
+ };
84
+ function toNumberOrZero(s) {
85
+ let n = parseInt(s, 10);
86
+ return isFinite(n) ? n : 0;
87
+ }
88
+ function isErrorResponse(response) {
89
+ return response ? errorStatusCodes.has(response.status) : !0;
90
+ }
91
+ function parseCacheControl(header) {
92
+ let cc = {};
93
+ if (!header) return cc;
94
+ let parts = header.trim().split(/,/);
95
+ for (let part of parts) {
96
+ let [k, v] = part.split(/=/, 2);
97
+ cc[k.trim()] = v === void 0 ? !0 : v.trim().replace(/^"|"$/g, "");
98
+ }
99
+ return cc;
100
+ }
101
+ function formatCacheControl(cc) {
102
+ let parts = [];
103
+ for (let k in cc) {
104
+ let v = cc[k];
105
+ parts.push(v === !0 ? k : k + "=" + v);
106
+ }
107
+ if (parts.length)
108
+ return parts.join(", ");
109
+ }
110
+ module.exports = class {
111
+ constructor(req, res, {
112
+ shared,
113
+ cacheHeuristic,
114
+ immutableMinTimeToLive,
115
+ ignoreCargoCult,
116
+ _fromObject
117
+ } = {}) {
118
+ if (_fromObject) {
119
+ this._fromObject(_fromObject);
120
+ return;
121
+ }
122
+ if (!res || !res.headers)
123
+ throw Error("Response headers missing");
124
+ this._assertRequestHasHeaders(req), this._responseTime = this.now(), this._isShared = shared !== !1, this._cacheHeuristic = cacheHeuristic !== void 0 ? cacheHeuristic : 0.1, this._immutableMinTtl = immutableMinTimeToLive !== void 0 ? immutableMinTimeToLive : 24 * 3600 * 1e3, this._status = "status" in res ? res.status : 200, this._resHeaders = res.headers, this._rescc = parseCacheControl(res.headers["cache-control"]), this._method = "method" in req ? req.method : "GET", this._url = req.url, this._host = req.headers.host, this._noAuthorization = !req.headers.authorization, this._reqHeaders = res.headers.vary ? req.headers : null, this._reqcc = parseCacheControl(req.headers["cache-control"]), ignoreCargoCult && "pre-check" in this._rescc && "post-check" in this._rescc && (delete this._rescc["pre-check"], delete this._rescc["post-check"], delete this._rescc["no-cache"], delete this._rescc["no-store"], delete this._rescc["must-revalidate"], this._resHeaders = Object.assign({}, this._resHeaders, {
125
+ "cache-control": formatCacheControl(this._rescc)
126
+ }), delete this._resHeaders.expires, delete this._resHeaders.pragma), res.headers["cache-control"] == null && /no-cache/.test(res.headers.pragma) && (this._rescc["no-cache"] = !0);
127
+ }
128
+ now() {
129
+ return Date.now();
130
+ }
131
+ storable() {
132
+ return !!(!this._reqcc["no-store"] && // A cache MUST NOT store a response to any request, unless:
133
+ // The request method is understood by the cache and defined as being cacheable, and
134
+ (this._method === "GET" || this._method === "HEAD" || this._method === "POST" && this._hasExplicitExpiration()) && // the response status code is understood by the cache, and
135
+ understoodStatuses.has(this._status) && // the "no-store" cache directive does not appear in request or response header fields, and
136
+ !this._rescc["no-store"] && // the "private" response directive does not appear in the response, if the cache is shared, and
137
+ (!this._isShared || !this._rescc.private) && // the Authorization header field does not appear in the request, if the cache is shared,
138
+ (!this._isShared || this._noAuthorization || this._allowsStoringAuthenticated()) && // the response either:
139
+ // contains an Expires header field, or
140
+ (this._resHeaders.expires || // contains a max-age response directive, or
141
+ // contains a s-maxage response directive and the cache is shared, or
142
+ // contains a public response directive.
143
+ this._rescc["max-age"] || this._isShared && this._rescc["s-maxage"] || this._rescc.public || // has a status code that is defined as cacheable by default
144
+ statusCodeCacheableByDefault.has(this._status)));
145
+ }
146
+ _hasExplicitExpiration() {
147
+ return this._isShared && this._rescc["s-maxage"] || this._rescc["max-age"] || this._resHeaders.expires;
148
+ }
149
+ _assertRequestHasHeaders(req) {
150
+ if (!req || !req.headers)
151
+ throw Error("Request headers missing");
152
+ }
153
+ satisfiesWithoutRevalidation(req) {
154
+ this._assertRequestHasHeaders(req);
155
+ let requestCC = parseCacheControl(req.headers["cache-control"]);
156
+ return requestCC["no-cache"] || /no-cache/.test(req.headers.pragma) || requestCC["max-age"] && this.age() > requestCC["max-age"] || requestCC["min-fresh"] && this.timeToLive() < 1e3 * requestCC["min-fresh"] || this.stale() && !(requestCC["max-stale"] && !this._rescc["must-revalidate"] && (requestCC["max-stale"] === !0 || requestCC["max-stale"] > this.age() - this.maxAge())) ? !1 : this._requestMatches(req, !1);
157
+ }
158
+ _requestMatches(req, allowHeadMethod) {
159
+ return (!this._url || this._url === req.url) && this._host === req.headers.host && // the request method associated with the stored response allows it to be used for the presented request, and
160
+ (!req.method || this._method === req.method || allowHeadMethod && req.method === "HEAD") && // selecting header fields nominated by the stored response (if any) match those presented, and
161
+ this._varyMatches(req);
162
+ }
163
+ _allowsStoringAuthenticated() {
164
+ return this._rescc["must-revalidate"] || this._rescc.public || this._rescc["s-maxage"];
165
+ }
166
+ _varyMatches(req) {
167
+ if (!this._resHeaders.vary)
168
+ return !0;
169
+ if (this._resHeaders.vary === "*")
170
+ return !1;
171
+ let fields = this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);
172
+ for (let name of fields)
173
+ if (req.headers[name] !== this._reqHeaders[name]) return !1;
174
+ return !0;
175
+ }
176
+ _copyWithoutHopByHopHeaders(inHeaders) {
177
+ let headers = {};
178
+ for (let name in inHeaders)
179
+ hopByHopHeaders[name] || (headers[name] = inHeaders[name]);
180
+ if (inHeaders.connection) {
181
+ let tokens = inHeaders.connection.trim().split(/\s*,\s*/);
182
+ for (let name of tokens)
183
+ delete headers[name];
184
+ }
185
+ if (headers.warning) {
186
+ let warnings = headers.warning.split(/,/).filter((warning) => !/^\s*1[0-9][0-9]/.test(warning));
187
+ warnings.length ? headers.warning = warnings.join(",").trim() : delete headers.warning;
188
+ }
189
+ return headers;
190
+ }
191
+ responseHeaders() {
192
+ let headers = this._copyWithoutHopByHopHeaders(this._resHeaders), age = this.age();
193
+ return age > 3600 * 24 && !this._hasExplicitExpiration() && this.maxAge() > 3600 * 24 && (headers.warning = (headers.warning ? `${headers.warning}, ` : "") + '113 - "rfc7234 5.5.4"'), headers.age = `${Math.round(age)}`, headers.date = new Date(this.now()).toUTCString(), headers;
194
+ }
195
+ /**
196
+ * Value of the Date response header or current time if Date was invalid
197
+ * @return timestamp
198
+ */
199
+ date() {
200
+ let serverDate = Date.parse(this._resHeaders.date);
201
+ return isFinite(serverDate) ? serverDate : this._responseTime;
202
+ }
203
+ /**
204
+ * Value of the Age header, in seconds, updated for the current time.
205
+ * May be fractional.
206
+ *
207
+ * @return Number
208
+ */
209
+ age() {
210
+ let age = this._ageValue(), residentTime = (this.now() - this._responseTime) / 1e3;
211
+ return age + residentTime;
212
+ }
213
+ _ageValue() {
214
+ return toNumberOrZero(this._resHeaders.age);
215
+ }
216
+ /**
217
+ * Value of applicable max-age (or heuristic equivalent) in seconds. This counts since response's `Date`.
218
+ *
219
+ * For an up-to-date value, see `timeToLive()`.
220
+ *
221
+ * @return Number
222
+ */
223
+ maxAge() {
224
+ if (!this.storable() || this._rescc["no-cache"] || this._isShared && this._resHeaders["set-cookie"] && !this._rescc.public && !this._rescc.immutable || this._resHeaders.vary === "*")
225
+ return 0;
226
+ if (this._isShared) {
227
+ if (this._rescc["proxy-revalidate"])
228
+ return 0;
229
+ if (this._rescc["s-maxage"])
230
+ return toNumberOrZero(this._rescc["s-maxage"]);
231
+ }
232
+ if (this._rescc["max-age"])
233
+ return toNumberOrZero(this._rescc["max-age"]);
234
+ let defaultMinTtl = this._rescc.immutable ? this._immutableMinTtl : 0, serverDate = this.date();
235
+ if (this._resHeaders.expires) {
236
+ let expires = Date.parse(this._resHeaders.expires);
237
+ return Number.isNaN(expires) || expires < serverDate ? 0 : Math.max(defaultMinTtl, (expires - serverDate) / 1e3);
238
+ }
239
+ if (this._resHeaders["last-modified"]) {
240
+ let lastModified = Date.parse(this._resHeaders["last-modified"]);
241
+ if (isFinite(lastModified) && serverDate > lastModified)
242
+ return Math.max(
243
+ defaultMinTtl,
244
+ (serverDate - lastModified) / 1e3 * this._cacheHeuristic
245
+ );
246
+ }
247
+ return defaultMinTtl;
248
+ }
249
+ timeToLive() {
250
+ let age = this.maxAge() - this.age(), staleIfErrorAge = age + toNumberOrZero(this._rescc["stale-if-error"]), staleWhileRevalidateAge = age + toNumberOrZero(this._rescc["stale-while-revalidate"]);
251
+ return Math.max(0, age, staleIfErrorAge, staleWhileRevalidateAge) * 1e3;
252
+ }
253
+ stale() {
254
+ return this.maxAge() <= this.age();
255
+ }
256
+ _useStaleIfError() {
257
+ return this.maxAge() + toNumberOrZero(this._rescc["stale-if-error"]) > this.age();
258
+ }
259
+ useStaleWhileRevalidate() {
260
+ return this.maxAge() + toNumberOrZero(this._rescc["stale-while-revalidate"]) > this.age();
261
+ }
262
+ static fromObject(obj) {
263
+ return new this(void 0, void 0, { _fromObject: obj });
264
+ }
265
+ _fromObject(obj) {
266
+ if (this._responseTime) throw Error("Reinitialized");
267
+ if (!obj || obj.v !== 1) throw Error("Invalid serialization");
268
+ this._responseTime = obj.t, this._isShared = obj.sh, this._cacheHeuristic = obj.ch, this._immutableMinTtl = obj.imm !== void 0 ? obj.imm : 24 * 3600 * 1e3, this._status = obj.st, this._resHeaders = obj.resh, this._rescc = obj.rescc, this._method = obj.m, this._url = obj.u, this._host = obj.h, this._noAuthorization = obj.a, this._reqHeaders = obj.reqh, this._reqcc = obj.reqcc;
269
+ }
270
+ toObject() {
271
+ return {
272
+ v: 1,
273
+ t: this._responseTime,
274
+ sh: this._isShared,
275
+ ch: this._cacheHeuristic,
276
+ imm: this._immutableMinTtl,
277
+ st: this._status,
278
+ resh: this._resHeaders,
279
+ rescc: this._rescc,
280
+ m: this._method,
281
+ u: this._url,
282
+ h: this._host,
283
+ a: this._noAuthorization,
284
+ reqh: this._reqHeaders,
285
+ reqcc: this._reqcc
286
+ };
287
+ }
288
+ /**
289
+ * Headers for sending to the origin server to revalidate stale response.
290
+ * Allows server to return 304 to allow reuse of the previous response.
291
+ *
292
+ * Hop by hop headers are always stripped.
293
+ * Revalidation headers may be added or removed, depending on request.
294
+ */
295
+ revalidationHeaders(incomingReq) {
296
+ this._assertRequestHasHeaders(incomingReq);
297
+ let headers = this._copyWithoutHopByHopHeaders(incomingReq.headers);
298
+ if (delete headers["if-range"], !this._requestMatches(incomingReq, !0) || !this.storable())
299
+ return delete headers["if-none-match"], delete headers["if-modified-since"], headers;
300
+ if (this._resHeaders.etag && (headers["if-none-match"] = headers["if-none-match"] ? `${headers["if-none-match"]}, ${this._resHeaders.etag}` : this._resHeaders.etag), headers["accept-ranges"] || headers["if-match"] || headers["if-unmodified-since"] || this._method && this._method != "GET") {
301
+ if (delete headers["if-modified-since"], headers["if-none-match"]) {
302
+ let etags = headers["if-none-match"].split(/,/).filter((etag) => !/^\s*W\//.test(etag));
303
+ etags.length ? headers["if-none-match"] = etags.join(",").trim() : delete headers["if-none-match"];
304
+ }
305
+ } else this._resHeaders["last-modified"] && !headers["if-modified-since"] && (headers["if-modified-since"] = this._resHeaders["last-modified"]);
306
+ return headers;
307
+ }
308
+ /**
309
+ * Creates new CachePolicy with information combined from the previews response,
310
+ * and the new revalidation response.
311
+ *
312
+ * Returns {policy, modified} where modified is a boolean indicating
313
+ * whether the response body has been modified, and old cached body can't be used.
314
+ *
315
+ * @return {Object} {policy: CachePolicy, modified: Boolean}
316
+ */
317
+ revalidatedPolicy(request, response) {
318
+ if (this._assertRequestHasHeaders(request), this._useStaleIfError() && isErrorResponse(response))
319
+ return {
320
+ modified: !1,
321
+ matches: !1,
322
+ policy: this
323
+ };
324
+ if (!response || !response.headers)
325
+ throw Error("Response headers missing");
326
+ let matches = !1;
327
+ if (response.status !== void 0 && response.status != 304 ? matches = !1 : response.headers.etag && !/^\s*W\//.test(response.headers.etag) ? matches = this._resHeaders.etag && this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag : this._resHeaders.etag && response.headers.etag ? matches = this._resHeaders.etag.replace(/^\s*W\//, "") === response.headers.etag.replace(/^\s*W\//, "") : this._resHeaders["last-modified"] ? matches = this._resHeaders["last-modified"] === response.headers["last-modified"] : !this._resHeaders.etag && !this._resHeaders["last-modified"] && !response.headers.etag && !response.headers["last-modified"] && (matches = !0), !matches)
328
+ return {
329
+ policy: new this.constructor(request, response),
330
+ // Client receiving 304 without body, even if it's invalid/mismatched has no option
331
+ // but to reuse a cached body. We don't have a good way to tell clients to do
332
+ // error recovery in such case.
333
+ modified: response.status != 304,
334
+ matches: !1
335
+ };
336
+ let headers = {};
337
+ for (let k in this._resHeaders)
338
+ headers[k] = k in response.headers && !excludedFromRevalidationUpdate[k] ? response.headers[k] : this._resHeaders[k];
339
+ let newResponse = Object.assign({}, response, {
340
+ status: this._status,
341
+ method: this._method,
342
+ headers
343
+ });
344
+ return {
345
+ policy: new this.constructor(request, newResponse, {
346
+ shared: this._isShared,
347
+ cacheHeuristic: this._cacheHeuristic,
348
+ immutableMinTimeToLive: this._immutableMinTtl
349
+ }),
350
+ modified: !1,
351
+ matches: !0
352
+ };
353
+ }
354
+ };
355
+ }
356
+ });
357
+
358
+ // src/workers/cache/cache.worker.ts
359
+ var import_http_cache_semantics = __toESM(require_http_cache_semantics());
360
+ import assert from "node:assert";
361
+ import { Buffer as Buffer2 } from "node:buffer";
362
+ import {
363
+ DeferredPromise,
364
+ DELETE,
365
+ GET,
366
+ KeyValueStorage,
367
+ LogLevel,
368
+ MiniflareDurableObject,
369
+ parseRanges,
370
+ PURGE,
371
+ PUT
372
+ } from "miniflare:shared";
373
+
374
+ // src/workers/kv/constants.ts
375
+ import { testRegExps } from "miniflare:shared";
376
+ var KVLimits = {
377
+ MIN_CACHE_TTL_SECONDS: 30,
378
+ MIN_EXPIRATION_TTL_SECONDS: 60,
379
+ MAX_LIST_KEYS: 1e3,
380
+ MAX_KEY_SIZE_BYTES: 512,
381
+ MAX_VALUE_SIZE_BYTES: 25 * 1024 * 1024,
382
+ MAX_VALUE_SIZE_TEST_BYTES: 1024,
383
+ MAX_METADATA_SIZE_BYTES: 1024,
384
+ MAX_BULK_SIZE_BYTES: 25 * 1024 * 1024
385
+ };
386
+ var SITES_NO_CACHE_PREFIX = "$__MINIFLARE_SITES__$/";
387
+ function isSitesRequest(request) {
388
+ return new URL(request.url).pathname.startsWith(`/${SITES_NO_CACHE_PREFIX}`);
389
+ }
390
+
391
+ // src/workers/cache/errors.worker.ts
392
+ import { HttpError } from "miniflare:shared";
393
+
394
+ // src/workers/cache/constants.ts
395
+ var CacheHeaders = {
396
+ NAMESPACE: "cf-cache-namespace",
397
+ STATUS: "cf-cache-status"
398
+ };
399
+
400
+ // src/workers/cache/errors.worker.ts
401
+ var CacheError = class extends HttpError {
402
+ constructor(code, message, headers = []) {
403
+ super(code, message);
404
+ this.headers = headers;
405
+ }
406
+ toResponse() {
407
+ return new Response(null, {
408
+ status: this.code,
409
+ headers: this.headers
410
+ });
411
+ }
412
+ context(info) {
413
+ return this.message += ` (${info})`, this;
414
+ }
415
+ }, StorageFailure = class extends CacheError {
416
+ constructor() {
417
+ super(413, "Cache storage failed");
418
+ }
419
+ }, PurgeFailure = class extends CacheError {
420
+ constructor() {
421
+ super(404, "Couldn't find asset to purge");
422
+ }
423
+ }, CacheMiss = class extends CacheError {
424
+ constructor() {
425
+ super(
426
+ // workerd ignores this, but it's the correct status code
427
+ 504,
428
+ "Asset not found in cache",
429
+ [[CacheHeaders.STATUS, "MISS"]]
430
+ );
431
+ }
432
+ }, RangeNotSatisfiable = class extends CacheError {
433
+ constructor(size) {
434
+ super(416, "Range not satisfiable", [
435
+ ["Content-Range", `bytes */${size}`],
436
+ [CacheHeaders.STATUS, "HIT"]
437
+ ]);
438
+ }
439
+ };
440
+
441
+ // src/workers/cache/cache.worker.ts
442
+ function getCacheKey(req) {
443
+ return req.cf?.cacheKey ? String(req.cf?.cacheKey) : req.url;
444
+ }
445
+ function getExpiration(timers, req, res) {
446
+ let reqHeaders = normaliseHeaders(req.headers);
447
+ delete reqHeaders["cache-control"];
448
+ let resHeaders = normaliseHeaders(res.headers);
449
+ resHeaders["cache-control"]?.toLowerCase().includes("private=set-cookie") && (resHeaders["cache-control"] = resHeaders["cache-control"]?.toLowerCase().replace(/private=set-cookie;?/i, ""), delete resHeaders["set-cookie"]);
450
+ let cacheReq = {
451
+ url: req.url,
452
+ // If a request gets to the Cache service, it's method will be GET. See README.md for details
453
+ method: "GET",
454
+ headers: reqHeaders
455
+ }, cacheRes = {
456
+ status: res.status,
457
+ headers: resHeaders
458
+ }, originalNow = import_http_cache_semantics.default.prototype.now;
459
+ import_http_cache_semantics.default.prototype.now = timers.now;
460
+ try {
461
+ let policy = new import_http_cache_semantics.default(cacheReq, cacheRes, { shared: !0 });
462
+ return {
463
+ // Check if the request & response is cacheable
464
+ storable: policy.storable() && !("set-cookie" in resHeaders),
465
+ expiration: policy.timeToLive(),
466
+ // Cache Policy Headers is typed as [header: string]: string | string[] | undefined
467
+ // It's safe to ignore the undefined here, which is what casting to HeadersInit does
468
+ headers: policy.responseHeaders()
469
+ };
470
+ } finally {
471
+ import_http_cache_semantics.default.prototype.now = originalNow;
472
+ }
473
+ }
474
+ function normaliseHeaders(headers) {
475
+ let result = {};
476
+ for (let [key, value] of headers) result[key.toLowerCase()] = value;
477
+ return result;
478
+ }
479
+ var etagRegexp = /^(W\/)?"(.+)"$/;
480
+ function parseETag(value) {
481
+ return etagRegexp.exec(value.trim())?.[2] ?? void 0;
482
+ }
483
+ var utcDateRegexp = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d\d (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d\d\d\d \d\d:\d\d:\d\d GMT$/;
484
+ function parseUTCDate(value) {
485
+ return utcDateRegexp.test(value) ? Date.parse(value) : NaN;
486
+ }
487
+ function getMatchResponse(reqHeaders, res) {
488
+ let reqIfNoneMatchHeader = reqHeaders.get("If-None-Match"), resETagHeader = res.headers.get("ETag");
489
+ if (reqIfNoneMatchHeader !== null && resETagHeader !== null) {
490
+ let resETag = parseETag(resETagHeader);
491
+ if (resETag !== void 0) {
492
+ if (reqIfNoneMatchHeader.trim() === "*")
493
+ return new Response(null, { status: 304, headers: res.headers });
494
+ for (let reqIfNoneMatch of reqIfNoneMatchHeader.split(","))
495
+ if (resETag === parseETag(reqIfNoneMatch))
496
+ return new Response(null, { status: 304, headers: res.headers });
497
+ }
498
+ }
499
+ let reqIfModifiedSinceHeader = reqHeaders.get("If-Modified-Since"), resLastModifiedHeader = res.headers.get("Last-Modified");
500
+ if (reqIfModifiedSinceHeader !== null && resLastModifiedHeader !== null) {
501
+ let reqIfModifiedSince = parseUTCDate(reqIfModifiedSinceHeader);
502
+ if (parseUTCDate(resLastModifiedHeader) <= reqIfModifiedSince)
503
+ return new Response(null, { status: 304, headers: res.headers });
504
+ }
505
+ if (res.ranges.length > 0)
506
+ if (res.status = 206, res.ranges.length > 1)
507
+ assert(!(res.body instanceof ReadableStream)), res.headers.set("Content-Type", res.body.multipartContentType);
508
+ else {
509
+ let { start, end } = res.ranges[0];
510
+ res.headers.set(
511
+ "Content-Range",
512
+ `bytes ${start}-${end}/${res.totalSize}`
513
+ ), res.headers.set("Content-Length", `${end - start + 1}`);
514
+ }
515
+ return res.body instanceof ReadableStream || (res.body = res.body.body), new Response(res.body, { status: res.status, headers: res.headers });
516
+ }
517
+ var CR = 13, LF = 10, STATUS_REGEXP = /^HTTP\/\d(?:\.\d)? (?<rawStatusCode>\d+) (?<statusText>.*)$/;
518
+ async function parseHttpResponse(stream) {
519
+ let buffer = Buffer2.alloc(0), blankLineIndex = -1;
520
+ for await (let chunk of stream.values({ preventCancel: !0 }))
521
+ if (buffer = Buffer2.concat([buffer, chunk]), blankLineIndex = buffer.findIndex(
522
+ (_value, index) => buffer[index] === CR && buffer[index + 1] === LF && buffer[index + 2] === CR && buffer[index + 3] === LF
523
+ ), blankLineIndex !== -1) break;
524
+ assert(blankLineIndex !== -1, "Expected to find blank line in HTTP message");
525
+ let rawStatusHeaders = buffer.subarray(0, blankLineIndex).toString(), [rawStatus, ...rawHeaders] = rawStatusHeaders.split(`\r
526
+ `), statusMatch = rawStatus.match(STATUS_REGEXP);
527
+ assert(
528
+ statusMatch?.groups != null,
529
+ `Expected first line ${JSON.stringify(rawStatus)} to be HTTP status line`
530
+ );
531
+ let { rawStatusCode, statusText } = statusMatch.groups, statusCode = parseInt(rawStatusCode), headers = rawHeaders.map((rawHeader) => {
532
+ let index = rawHeader.indexOf(":");
533
+ return [
534
+ rawHeader.substring(0, index),
535
+ rawHeader.substring(index + 1).trim()
536
+ ];
537
+ }), prefix = buffer.subarray(
538
+ blankLineIndex + 4
539
+ /* "\r\n\r\n" */
540
+ ), { readable, writable } = new IdentityTransformStream(), writer = writable.getWriter();
541
+ return writer.write(prefix).then(() => (writer.releaseLock(), stream.pipeTo(writable))).catch((e) => console.error("Error writing HTTP body:", e)), new Response(readable, { status: statusCode, statusText, headers });
542
+ }
543
+ var SizingStream = class extends TransformStream {
544
+ size;
545
+ constructor() {
546
+ let sizePromise = new DeferredPromise(), size = 0;
547
+ super({
548
+ transform(chunk, controller) {
549
+ size += chunk.byteLength, controller.enqueue(chunk);
550
+ },
551
+ flush() {
552
+ sizePromise.resolve(size);
553
+ }
554
+ }), this.size = sizePromise;
555
+ }
556
+ }, CacheObject = class extends MiniflareDurableObject {
557
+ #warnedUsage = !1;
558
+ async #maybeWarnUsage(request) {
559
+ !this.#warnedUsage && request.cf?.miniflare?.cacheWarnUsage === !0 && (this.#warnedUsage = !0, await this.logWithLevel(
560
+ LogLevel.WARN,
561
+ "Cache operations will have no impact if you deploy to a workers.dev subdomain!"
562
+ ));
563
+ }
564
+ #storage;
565
+ get storage() {
566
+ return this.#storage ??= new KeyValueStorage(this);
567
+ }
568
+ match = async (req) => {
569
+ await this.#maybeWarnUsage(req);
570
+ let cacheKey = getCacheKey(req);
571
+ if (isSitesRequest(req)) throw new CacheMiss();
572
+ let resHeaders, resRanges, cached = await this.storage.get(cacheKey, ({ size, headers }) => {
573
+ resHeaders = new Headers(headers);
574
+ let contentType = resHeaders.get("Content-Type"), rangeHeader = req.headers.get("Range");
575
+ if (rangeHeader !== null && (resRanges = parseRanges(rangeHeader, size), resRanges === void 0))
576
+ throw new RangeNotSatisfiable(size);
577
+ return {
578
+ ranges: resRanges,
579
+ contentLength: size,
580
+ contentType: contentType ?? void 0
581
+ };
582
+ });
583
+ if (cached?.metadata === void 0) throw new CacheMiss();
584
+ return assert(resHeaders !== void 0), resHeaders.set("CF-Cache-Status", "HIT"), resRanges ??= [], getMatchResponse(req.headers, {
585
+ status: cached.metadata.status,
586
+ headers: resHeaders,
587
+ ranges: resRanges,
588
+ body: cached.value,
589
+ totalSize: cached.metadata.size
590
+ });
591
+ };
592
+ put = async (req) => {
593
+ await this.#maybeWarnUsage(req);
594
+ let cacheKey = getCacheKey(req);
595
+ if (isSitesRequest(req)) throw new CacheMiss();
596
+ assert(req.body !== null);
597
+ let res = await parseHttpResponse(req.body), body = res.body;
598
+ assert(body !== null);
599
+ let { storable, expiration, headers } = getExpiration(
600
+ this.timers,
601
+ req,
602
+ res
603
+ );
604
+ if (!storable) {
605
+ try {
606
+ await body.pipeTo(new WritableStream());
607
+ } catch {
608
+ }
609
+ throw new StorageFailure();
610
+ }
611
+ let contentLength = parseInt(res.headers.get("Content-Length")), sizePromise;
612
+ if (Number.isNaN(contentLength)) {
613
+ let stream = new SizingStream();
614
+ body = body.pipeThrough(stream), sizePromise = stream.size;
615
+ } else
616
+ sizePromise = Promise.resolve(contentLength);
617
+ let metadata = sizePromise.then((size) => ({
618
+ headers: Object.entries(headers),
619
+ status: res.status,
620
+ size
621
+ }));
622
+ return await this.storage.put({
623
+ key: cacheKey,
624
+ value: body,
625
+ expiration: this.timers.now() + expiration,
626
+ metadata
627
+ }), new Response(null, { status: 204 });
628
+ };
629
+ delete = async (req) => {
630
+ await this.#maybeWarnUsage(req);
631
+ let cacheKey = getCacheKey(req);
632
+ if (!await this.storage.delete(cacheKey)) throw new PurgeFailure();
633
+ return new Response(null);
634
+ };
635
+ purgeAll = async () => {
636
+ let deletedCount = this.storage.deleteAll();
637
+ return Response.json({ deleted: deletedCount });
638
+ };
639
+ };
640
+ __decorateClass([
641
+ GET()
642
+ ], CacheObject.prototype, "match", 2), __decorateClass([
643
+ PUT()
644
+ ], CacheObject.prototype, "put", 2), __decorateClass([
645
+ PURGE()
646
+ ], CacheObject.prototype, "delete", 2), __decorateClass([
647
+ DELETE("/purge-all")
648
+ ], CacheObject.prototype, "purgeAll", 2);
649
+ export {
650
+ CacheObject,
651
+ parseHttpResponse
652
+ };
653
+ //# sourceMappingURL=cache.worker.js.map