@kaanbiryol/crate-server 0.0.0-stage → 0.17.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -2
  3. package/THIRD_PARTY_NOTICES.md +3664 -0
  4. package/assets/coordinator.mjs +116 -0
  5. package/assets/credential-revocation.mjs +18 -0
  6. package/assets/database-upgrade-rules.mjs +42 -0
  7. package/assets/migrations/README.md +19 -0
  8. package/assets/qrcode.mjs +1638 -0
  9. package/assets/schema.sql +368 -0
  10. package/assets/server-release.json +6 -0
  11. package/assets/worker-runtime.json +12 -0
  12. package/assets/worker.mjs +1458 -0
  13. package/npm-shrinkwrap.json +939 -0
  14. package/package.json +38 -4
  15. package/scripts/assets.mjs +33 -0
  16. package/scripts/commands/data.mjs +80 -0
  17. package/scripts/commands/devices.mjs +100 -0
  18. package/scripts/commands/doctor.mjs +127 -0
  19. package/scripts/commands/service.mjs +19 -0
  20. package/scripts/commands/setup.mjs +194 -0
  21. package/scripts/commands/start.mjs +171 -0
  22. package/scripts/commands/status.mjs +49 -0
  23. package/scripts/commands/update.mjs +138 -0
  24. package/scripts/crate-server.mjs +11 -0
  25. package/scripts/deployment-fingerprint.mjs +13 -0
  26. package/scripts/local-server-alerts.mjs +53 -0
  27. package/scripts/local-server-backup-schedule.mjs +153 -0
  28. package/scripts/local-server-backup.mjs +275 -0
  29. package/scripts/local-server-cloudflared.mjs +93 -0
  30. package/scripts/local-server-control.mjs +150 -0
  31. package/scripts/local-server-devices.mjs +71 -0
  32. package/scripts/local-server-host-status.mjs +72 -0
  33. package/scripts/local-server-http.mjs +120 -0
  34. package/scripts/local-server-install.mjs +22 -0
  35. package/scripts/local-server-lifecycle.mjs +54 -0
  36. package/scripts/local-server-lock.mjs +217 -0
  37. package/scripts/local-server-migrations.mjs +43 -0
  38. package/scripts/local-server-options.mjs +134 -0
  39. package/scripts/local-server-pairing.mjs +47 -0
  40. package/scripts/local-server-process.mjs +77 -0
  41. package/scripts/local-server-qr.mjs +34 -0
  42. package/scripts/local-server-quick.mjs +116 -0
  43. package/scripts/local-server-readiness.mjs +48 -0
  44. package/scripts/local-server-runtime.mjs +460 -0
  45. package/scripts/local-server-service.mjs +209 -0
  46. package/scripts/local-server-style.mjs +12 -0
  47. package/scripts/local-server-tailscale.mjs +122 -0
  48. package/scripts/local-server-tunnel.mjs +212 -0
  49. package/scripts/local-server-watchdog.mjs +37 -0
  50. package/scripts/local-server-wizard.mjs +100 -0
  51. package/scripts/local-server.mjs +100 -0
  52. package/vendor/miniflare/LICENSE +25 -0
  53. package/vendor/miniflare/dist/local-explorer-ui/assets/ArrowClockwise.es-Cs0EHtoR.js +1 -0
  54. package/vendor/miniflare/dist/local-explorer-ui/assets/Breadcrumbs-BlzUUgNz.js +1 -0
  55. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretDown.es-r8EMGhHM.js +1 -0
  56. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretLeft.es-CCxvlwgr.js +1 -0
  57. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretRight.es-CWeeOO8C.js +1 -0
  58. package/vendor/miniflare/dist/local-explorer-ui/assets/CaretUpDown.es-Bp73BWZN.js +1 -0
  59. package/vendor/miniflare/dist/local-explorer-ui/assets/Check.es-B3dV_aVM.js +1 -0
  60. package/vendor/miniflare/dist/local-explorer-ui/assets/Copy.es-DUyM7PbX.js +1 -0
  61. package/vendor/miniflare/dist/local-explorer-ui/assets/CopyButton-DdMFsAgv.js +1 -0
  62. package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersContext-CtoQyHCH.js +1 -0
  63. package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersPage-BC2FvZf5.js +1 -0
  64. package/vendor/miniflare/dist/local-explorer-ui/assets/DotsThree.es-B9u_qIrH.js +1 -0
  65. package/vendor/miniflare/dist/local-explorer-ui/assets/Download.es-v8YTKdZh.js +1 -0
  66. package/vendor/miniflare/dist/local-explorer-ui/assets/List.es-GlowdvL8.js +1 -0
  67. package/vendor/miniflare/dist/local-explorer-ui/assets/ListBullets.es-DrJsrtCL.js +1 -0
  68. package/vendor/miniflare/dist/local-explorer-ui/assets/MagnifyingGlass.es-BzOo3pru.js +1 -0
  69. package/vendor/miniflare/dist/local-explorer-ui/assets/PaperPlaneTilt.es-DTLdWOnM.js +1 -0
  70. package/vendor/miniflare/dist/local-explorer-ui/assets/Paperclip.es-6Ysj3lly.js +1 -0
  71. package/vendor/miniflare/dist/local-explorer-ui/assets/Pencil.es-CDpuGAys.js +1 -0
  72. package/vendor/miniflare/dist/local-explorer-ui/assets/Plus.es-xOjOjCs5.js +1 -0
  73. package/vendor/miniflare/dist/local-explorer-ui/assets/ResourceError-DNadec0F.js +1 -0
  74. package/vendor/miniflare/dist/local-explorer-ui/assets/Spinner.es-oqUPe-aY.js +1 -0
  75. package/vendor/miniflare/dist/local-explorer-ui/assets/TableSelect-DgjN53ZF.js +25 -0
  76. package/vendor/miniflare/dist/local-explorer-ui/assets/Trash.es-DTqwcb2_.js +1 -0
  77. package/vendor/miniflare/dist/local-explorer-ui/assets/Warning.es-CLa-n7LD.js +1 -0
  78. package/vendor/miniflare/dist/local-explorer-ui/assets/X.es-BiJFnG31.js +1 -0
  79. package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-Cow8QNw6.js +1 -0
  80. package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-TnuOHwOA.js +5 -0
  81. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Cow8QNw6.js +1 -0
  82. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DMGTgdaZ.js +1 -0
  83. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Daanvg3W.js +1 -0
  84. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DqCj-aYZ.js +1 -0
  85. package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-uYCS7veQ.js +1 -0
  86. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cb6ggQGG.js +1 -0
  87. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cow8QNw6.js +1 -0
  88. package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Daanvg3W.js +1 -0
  89. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-BW1__nAw.js +1 -0
  90. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Cow8QNw6.js +1 -0
  91. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DCj9M_Uf.js +1 -0
  92. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DMGTgdaZ.js +1 -0
  93. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Daanvg3W.js +1 -0
  94. package/vendor/miniflare/dist/local-explorer-ui/assets/_className-uYCS7veQ.js +1 -0
  95. package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-BEh2sOY5.js +1 -0
  96. package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-Cow8QNw6.js +1 -0
  97. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Cow8QNw6.js +1 -0
  98. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-CxJm9jpK.js +1 -0
  99. package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Daanvg3W.js +1 -0
  100. package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-Cow8QNw6.js +1 -0
  101. package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-HT9g0tMq.js +1 -0
  102. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Cow8QNw6.js +1 -0
  103. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Daanvg3W.js +1 -0
  104. package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-DdmD-NV1.js +1 -0
  105. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Cow8QNw6.js +1 -0
  106. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-DMGTgdaZ.js +1 -0
  107. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Daanvg3W.js +1 -0
  108. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-WgIBBs_w.js +1 -0
  109. package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-uYCS7veQ.js +1 -0
  110. package/vendor/miniflare/dist/local-explorer-ui/assets/ad-hoc-B9HL0oNk.js +1 -0
  111. package/vendor/miniflare/dist/local-explorer-ui/assets/async-t2_zA-v_.js +1 -0
  112. package/vendor/miniflare/dist/local-explorer-ui/assets/button-cdxnqcgzwko8ooha-CjoTKpgy.js +1 -0
  113. package/vendor/miniflare/dist/local-explorer-ui/assets/checkbox-kt1uojk2f9e0d0h1-D923QL-G.js +1 -0
  114. package/vendor/miniflare/dist/local-explorer-ui/assets/clipboard-text-vcbvmtne4zjk4b18-CEoJIuMe.js +1 -0
  115. package/vendor/miniflare/dist/local-explorer-ui/assets/configured-BGeRrlYf.js +1 -0
  116. package/vendor/miniflare/dist/local-explorer-ui/assets/cron-triggers-ZP5ClwAa.js +1 -0
  117. package/vendor/miniflare/dist/local-explorer-ui/assets/dialog-oqh8l3l3zutpibxx-nho54TMC.js +1 -0
  118. package/vendor/miniflare/dist/local-explorer-ui/assets/dropdown-ncwhcd912vmone8k-BAT0p_ep.js +1 -0
  119. package/vendor/miniflare/dist/local-explorer-ui/assets/email-B-IveBKB.js +1 -0
  120. package/vendor/miniflare/dist/local-explorer-ui/assets/events-ClnoiyGH.js +1 -0
  121. package/vendor/miniflare/dist/local-explorer-ui/assets/events-Cow8QNw6.js +1 -0
  122. package/vendor/miniflare/dist/local-explorer-ui/assets/field-krp6z6vfbkrvufz2-DsLUBjzS.js +1 -0
  123. package/vendor/miniflare/dist/local-explorer-ui/assets/format-CjQ0gyEW.js +1 -0
  124. package/vendor/miniflare/dist/local-explorer-ui/assets/helpers-Bz2sloWm.js +1 -0
  125. package/vendor/miniflare/dist/local-explorer-ui/assets/index-BHW_FKpE.js +30 -0
  126. package/vendor/miniflare/dist/local-explorer-ui/assets/index-CiXL10aq.css +2 -0
  127. package/vendor/miniflare/dist/local-explorer-ui/assets/input-area-no30c09udyjxshu5-T786oEMj.js +1 -0
  128. package/vendor/miniflare/dist/local-explorer-ui/assets/input-group-lxdd09p60cf27pe1-BqVz8A4J.js +1 -0
  129. package/vendor/miniflare/dist/local-explorer-ui/assets/input-h48k3uagzrgb98au-BF-hE08e.js +1 -0
  130. package/vendor/miniflare/dist/local-explorer-ui/assets/label-latndvb1ngem7we8-mWoel0Kk.js +1 -0
  131. package/vendor/miniflare/dist/local-explorer-ui/assets/link-DadJAPnd.js +1 -0
  132. package/vendor/miniflare/dist/local-explorer-ui/assets/link-provider-mn2voeohon7cj9o4-CNosc_Ni.js +13 -0
  133. package/vendor/miniflare/dist/local-explorer-ui/assets/matchContext-C1eKDtty.js +1 -0
  134. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Cow8QNw6.js +1 -0
  135. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-DDwO6NT7.js +1 -0
  136. package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Daanvg3W.js +1 -0
  137. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CC1mP6Xo.js +15 -0
  138. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CX-6-j6d.js +1 -0
  139. package/vendor/miniflare/dist/local-explorer-ui/assets/observability-Cow8QNw6.js +1 -0
  140. package/vendor/miniflare/dist/local-explorer-ui/assets/react-BZY8YNV6.js +1 -0
  141. package/vendor/miniflare/dist/local-explorer-ui/assets/redirect-CckYXsV1.js +1 -0
  142. package/vendor/miniflare/dist/local-explorer-ui/assets/routes-BlOyav-b.js +1 -0
  143. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-CVthjHxr.js +2 -0
  144. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-Cow8QNw6.js +1 -0
  145. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-DMGTgdaZ.js +1 -0
  146. package/vendor/miniflare/dist/local-explorer-ui/assets/routing-uYCS7veQ.js +1 -0
  147. package/vendor/miniflare/dist/local-explorer-ui/assets/select-kva5ru5f673kah1m-DQuxH2_G.js +1 -0
  148. package/vendor/miniflare/dist/local-explorer-ui/assets/sending-BPjb3S3Y.js +1 -0
  149. package/vendor/miniflare/dist/local-explorer-ui/assets/sending-Cow8QNw6.js +1 -0
  150. package/vendor/miniflare/dist/local-explorer-ui/assets/switch-ihaydbzem62bey4p-C9M-MPNS.js +1 -0
  151. package/vendor/miniflare/dist/local-explorer-ui/assets/table-inweecadl3her7pd-UWLv9e8D.js +1 -0
  152. package/vendor/miniflare/dist/local-explorer-ui/assets/text-nmyi1rkwdj37f30f-BLzIhmEO.js +1 -0
  153. package/vendor/miniflare/dist/local-explorer-ui/assets/types-DTx0hLYz.js +1 -0
  154. package/vendor/miniflare/dist/local-explorer-ui/assets/useCursorPaginatedList-BGUINn38.js +1 -0
  155. package/vendor/miniflare/dist/local-explorer-ui/assets/useRouterState-BLq6Ai_6.js +1 -0
  156. package/vendor/miniflare/dist/local-explorer-ui/favicon.svg +3 -0
  157. package/vendor/miniflare/dist/local-explorer-ui/index.html +27 -0
  158. package/vendor/miniflare/dist/src/index.d.ts +14183 -0
  159. package/vendor/miniflare/dist/src/index.js +123738 -0
  160. package/vendor/miniflare/dist/src/mdream_edge_bg.wasm +0 -0
  161. package/vendor/miniflare/dist/src/plugins/artifacts/git-sidecar.js +21071 -0
  162. package/vendor/miniflare/dist/src/workers/access/access-identity.worker.js +10 -0
  163. package/vendor/miniflare/dist/src/workers/analytics-engine/analytics-engine.worker.js +21 -0
  164. package/vendor/miniflare/dist/src/workers/analytics-engine/remote.worker.js +2578 -0
  165. package/vendor/miniflare/dist/src/workers/artifacts/binding.worker.js +903 -0
  166. package/vendor/miniflare/dist/src/workers/artifacts/wrapped-binding.worker.js +52 -0
  167. package/vendor/miniflare/dist/src/workers/assets/assets-kv.worker.js +27 -0
  168. package/vendor/miniflare/dist/src/workers/assets/assets.worker.js +1525 -0
  169. package/vendor/miniflare/dist/src/workers/assets/router.worker.js +1883 -0
  170. package/vendor/miniflare/dist/src/workers/assets/rpc-proxy.worker.js +55 -0
  171. package/vendor/miniflare/dist/src/workers/browser-rendering/binding.worker.js +453 -0
  172. package/vendor/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js +18 -0
  173. package/vendor/miniflare/dist/src/workers/cache/cache-entry.worker.js +24 -0
  174. package/vendor/miniflare/dist/src/workers/cache/cache.worker.js +652 -0
  175. package/vendor/miniflare/dist/src/workers/core/dev-control.worker.js +52 -0
  176. package/vendor/miniflare/dist/src/workers/core/dev-registry-proxy.worker.js +371 -0
  177. package/vendor/miniflare/dist/src/workers/core/do-wrapper.worker.js +67 -0
  178. package/vendor/miniflare/dist/src/workers/core/entry.worker.js +5516 -0
  179. package/vendor/miniflare/dist/src/workers/core/outbound.worker.js +147 -0
  180. package/vendor/miniflare/dist/src/workers/d1/database.worker.js +298 -0
  181. package/vendor/miniflare/dist/src/workers/d1/entry.worker.js +143 -0
  182. package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2574 -0
  183. package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +11 -0
  184. package/vendor/miniflare/dist/src/workers/email/email-store.worker.js +606 -0
  185. package/vendor/miniflare/dist/src/workers/email/email.worker.js +26 -0
  186. package/vendor/miniflare/dist/src/workers/email/send_email.worker.js +3703 -0
  187. package/vendor/miniflare/dist/src/workers/flagship/binding.worker.js +394 -0
  188. package/vendor/miniflare/dist/src/workers/flagship/object.worker.js +349 -0
  189. package/vendor/miniflare/dist/src/workers/hello-world/binding.worker.js +18 -0
  190. package/vendor/miniflare/dist/src/workers/hello-world/object.worker.js +13 -0
  191. package/vendor/miniflare/dist/src/workers/images/images.worker.js +450 -0
  192. package/vendor/miniflare/dist/src/workers/k2/binding.worker.js +2583 -0
  193. package/vendor/miniflare/dist/src/workers/kv/namespace.worker.js +323 -0
  194. package/vendor/miniflare/dist/src/workers/kv/sites.worker.js +148 -0
  195. package/vendor/miniflare/dist/src/workers/local-explorer/explorer.worker.js +17275 -0
  196. package/vendor/miniflare/dist/src/workers/observability/collector.worker.js +725 -0
  197. package/vendor/miniflare/dist/src/workers/pipelines/pipeline.worker.js +9 -0
  198. package/vendor/miniflare/dist/src/workers/queues/broker.worker.js +391 -0
  199. package/vendor/miniflare/dist/src/workers/r2/bucket.worker.js +1171 -0
  200. package/vendor/miniflare/dist/src/workers/r2/public.worker.js +1319 -0
  201. package/vendor/miniflare/dist/src/workers/r2/s3/index.worker.js +11128 -0
  202. package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit-object.worker.js +55 -0
  203. package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js +69 -0
  204. package/vendor/miniflare/dist/src/workers/secrets-store/secret.worker.js +64 -0
  205. package/vendor/miniflare/dist/src/workers/shared/index.worker.js +730 -0
  206. package/vendor/miniflare/dist/src/workers/shared/object-entry.worker.js +33 -0
  207. package/vendor/miniflare/dist/src/workers/shared/remote-proxy-client.worker.js +2698 -0
  208. package/vendor/miniflare/dist/src/workers/shared/zod.worker.js +15459 -0
  209. package/vendor/miniflare/dist/src/workers/stream/binding.worker.js +282 -0
  210. package/vendor/miniflare/dist/src/workers/stream/object.worker.js +479 -0
  211. package/vendor/miniflare/dist/src/workers/workflows/binding.worker.js +5137 -0
  212. package/vendor/miniflare/dist/src/workers/workflows/wrapped-binding.worker.js +111 -0
  213. package/vendor/miniflare/package.json +135 -0
@@ -0,0 +1,1525 @@
1
+ // ../workers-shared/asset-worker/src/worker.ts
2
+ import { WorkerEntrypoint } from "cloudflare:workers";
3
+
4
+ // ../workers-shared/utils/performance.ts
5
+ var PerformanceTimer = class {
6
+ constructor(performanceTimer) {
7
+ this.performanceTimer = performanceTimer;
8
+ }
9
+ now() {
10
+ return this.performanceTimer ? this.performanceTimer.timeOrigin + this.performanceTimer.now() : Date.now();
11
+ }
12
+ };
13
+
14
+ // ../workers-shared/utils/tracing.ts
15
+ function mockJaegerBindingSpan() {
16
+ return {
17
+ addLogs: () => {
18
+ },
19
+ setTags: () => {
20
+ },
21
+ end: () => {
22
+ },
23
+ isRecording: !0
24
+ };
25
+ }
26
+ function mockJaegerBinding() {
27
+ return {
28
+ enterSpan: (_, span, ...args) => span(mockJaegerBindingSpan(), ...args),
29
+ getSpanContext: () => ({
30
+ traceId: "test-trace",
31
+ spanId: "test-span",
32
+ parentSpanId: "test-parent-span",
33
+ traceFlags: 0
34
+ }),
35
+ runWithSpanContext: (_, callback, ...args) => callback(...args),
36
+ traceId: "test-trace",
37
+ spanId: "test-span",
38
+ parentSpanId: "test-parent-span",
39
+ cfTraceIdHeader: "test-trace:test-span:0"
40
+ };
41
+ }
42
+
43
+ // ../workers-shared/asset-worker/src/analytics.ts
44
+ function getRequestKind(request) {
45
+ let dest = request.headers.get("Sec-Fetch-Dest");
46
+ if (dest)
47
+ return dest === "document" || dest === "iframe" ? "navigation" : "subresource";
48
+ let { pathname } = new URL(request.url), lastSegment = pathname.slice(pathname.lastIndexOf("/") + 1), dotIndex = lastSegment.lastIndexOf(".");
49
+ return dotIndex <= 0 || lastSegment.slice(dotIndex + 1).toLowerCase() === "html" ? "navigation" : "subresource";
50
+ }
51
+ var COMPATIBILITY_FLAG_MASKS = {
52
+ assets_navigation_prefers_asset_serving: 1
53
+ // next_one: 1 << 1
54
+ // one_after_that: 1 << 2
55
+ // etc: 1 << 3
56
+ }, Analytics = class {
57
+ constructor(readyAnalytics) {
58
+ this.data = {};
59
+ this.readyAnalytics = readyAnalytics;
60
+ }
61
+ setData(newData) {
62
+ this.data = { ...this.data, ...newData };
63
+ }
64
+ getData(key) {
65
+ return this.data[key];
66
+ }
67
+ write() {
68
+ if (!this.readyAnalytics)
69
+ return;
70
+ let compatibilityFlagsBitmask = 0;
71
+ for (let compatibilityFlag of this.data.compatibilityFlags || []) {
72
+ let mask = COMPATIBILITY_FLAG_MASKS[compatibilityFlag];
73
+ mask && (compatibilityFlagsBitmask += mask);
74
+ }
75
+ this.readyAnalytics.logEvent({
76
+ version: 1,
77
+ accountId: this.data.accountId,
78
+ indexId: this.data.scriptId?.toString(),
79
+ doubles: [
80
+ this.data.requestTime ?? -1,
81
+ // double1
82
+ this.data.coloId ?? -1,
83
+ // double2
84
+ this.data.metalId ?? -1,
85
+ // double3
86
+ this.data.coloTier ?? -1,
87
+ // double4
88
+ this.data.status ?? -1,
89
+ // double5
90
+ compatibilityFlagsBitmask,
91
+ // double6
92
+ this.data.entrypoint ?? -1
93
+ // double7
94
+ ],
95
+ blobs: [
96
+ this.data.hostname?.substring(0, 256),
97
+ // blob1 - trim to 256 bytes
98
+ this.data.userAgent?.substring(0, 256),
99
+ // blob2 - trim to 256 bytes
100
+ this.data.htmlHandling,
101
+ // blob3
102
+ this.data.notFoundHandling,
103
+ // blob4
104
+ this.data.error?.substring(0, 256),
105
+ // blob5 - trim to 256 bytes
106
+ this.data.version,
107
+ // blob6
108
+ this.data.coloRegion,
109
+ // blob7
110
+ this.data.cacheStatus,
111
+ // blob8
112
+ this.data.cohort,
113
+ // blob9
114
+ this.data.servedBy,
115
+ // blob10
116
+ this.data.requestKind
117
+ // blob11
118
+ ]
119
+ });
120
+ }
121
+ };
122
+
123
+ // ../workers-shared/asset-worker/src/assets-manifest.ts
124
+ var AssetsManifest = class {
125
+ constructor(data) {
126
+ this.data = new Uint8Array(data);
127
+ }
128
+ async get(pathname) {
129
+ let pathHash = await hashPath(pathname), entry = binarySearch(this.data, pathHash);
130
+ return entry ? Uint8ToHexString(entry) : null;
131
+ }
132
+ }, hashPath = async (path) => {
133
+ let data = new TextEncoder().encode(path), hashBuffer = await crypto.subtle.digest(
134
+ "SHA-256",
135
+ data.buffer
136
+ );
137
+ return new Uint8Array(hashBuffer, 0, 16);
138
+ }, binarySearch = (manifest, pathHash) => {
139
+ if (pathHash.byteLength !== 16)
140
+ throw new TypeError(
141
+ `Search value should have a length of ${16}`
142
+ );
143
+ let numberOfEntries = (manifest.byteLength - 20) / 40;
144
+ if (numberOfEntries === 0)
145
+ return !1;
146
+ let lowIndex = 0, highIndex = numberOfEntries - 1;
147
+ for (; lowIndex <= highIndex; ) {
148
+ let middleIndex = lowIndex + highIndex >> 1, cmp = comparePathHashWithEntry(pathHash, manifest, middleIndex);
149
+ if (cmp < 0) {
150
+ highIndex = middleIndex - 1;
151
+ continue;
152
+ }
153
+ if (cmp > 0) {
154
+ lowIndex = middleIndex + 1;
155
+ continue;
156
+ }
157
+ return new Uint8Array(
158
+ manifest.buffer,
159
+ 20 + middleIndex * 40 + 16,
160
+ 16
161
+ );
162
+ }
163
+ return !1;
164
+ };
165
+ function comparePathHashWithEntry(searchValue, manifest, entryIndex) {
166
+ let pathHashOffset = 20 + entryIndex * 40 + 0;
167
+ for (let offset = 0; offset < 16; offset++, pathHashOffset++) {
168
+ let s = searchValue[offset], e = manifest[pathHashOffset];
169
+ if (s === void 0 || e === void 0)
170
+ throw new TypeError(
171
+ `Unexpected undefined value at offset ${offset} during path hash comparison`
172
+ );
173
+ if (s < e)
174
+ return -1;
175
+ if (s > e)
176
+ return 1;
177
+ }
178
+ return 0;
179
+ }
180
+ var Uint8ToHexString = (array) => [...array].map((b) => b.toString(16).padStart(2, "0")).join("");
181
+
182
+ // ../workers-shared/utils/base-path.ts
183
+ var CONTROL_CHARACTER = /[\u0000-\u001f\u007f]/;
184
+ function normalizeBasePath(value) {
185
+ if (value === "/")
186
+ return { valid: !0, value: "/" };
187
+ if (typeof value != "string")
188
+ return {
189
+ valid: !1,
190
+ error: `Expected a string but got ${typeof value}.`
191
+ };
192
+ if (value.length === 0)
193
+ return { valid: !1, error: "The value must not be empty." };
194
+ if (value.startsWith("//") || /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(value))
195
+ return {
196
+ valid: !1,
197
+ error: "The value must be a pathname, not a URL."
198
+ };
199
+ if (value.includes("\\"))
200
+ return { valid: !1, error: "The value must not contain backslashes." };
201
+ if (CONTROL_CHARACTER.test(value))
202
+ return {
203
+ valid: !1,
204
+ error: "The value must not contain control characters."
205
+ };
206
+ if (value.includes("?") || value.includes("#"))
207
+ return {
208
+ valid: !1,
209
+ error: "The value must not contain query strings or fragments."
210
+ };
211
+ if (value.includes("%"))
212
+ return {
213
+ valid: !1,
214
+ error: "The value must not contain percent-encoded sequences."
215
+ };
216
+ let normalizedSegments = [];
217
+ for (let segment of value.split("/"))
218
+ if (!(segment === "" || segment === ".")) {
219
+ if (segment === "..") {
220
+ normalizedSegments.pop();
221
+ continue;
222
+ }
223
+ normalizedSegments.push(segment);
224
+ }
225
+ return { valid: !0, value: normalizedSegments.length === 0 ? "/" : `/${normalizedSegments.join("/")}/` };
226
+ }
227
+
228
+ // ../workers-shared/asset-worker/src/compatibility-flags.ts
229
+ var SEC_FETCH_MODE_NAVIGATE_HEADER_PREFERS_ASSET_SERVING = {
230
+ enable: "assets_navigation_prefers_asset_serving",
231
+ disable: "assets_navigation_has_no_effect",
232
+ onByDefaultAfter: "2025-04-01"
233
+ }, COMPATIBILITY_FLAGS = [
234
+ SEC_FETCH_MODE_NAVIGATE_HEADER_PREFERS_ASSET_SERVING
235
+ ], resolveCompatibilityOptions = (configuration) => {
236
+ let compatibilityDate = configuration?.compatibility_date ?? "2021-11-02", resolvedCompatibilityFlags = configuration?.compatibility_flags ?? [];
237
+ for (let compatibilityFlag of COMPATIBILITY_FLAGS)
238
+ compatibilityFlag.onByDefaultAfter && compatibilityDate >= compatibilityFlag.onByDefaultAfter && !resolvedCompatibilityFlags.find(
239
+ (flag) => flag === compatibilityFlag.disable
240
+ ) && !resolvedCompatibilityFlags.find(
241
+ (flag) => flag === compatibilityFlag.enable
242
+ ) && resolvedCompatibilityFlags.push(compatibilityFlag.enable);
243
+ return {
244
+ compatibilityDate,
245
+ compatibilityFlags: resolvedCompatibilityFlags
246
+ };
247
+ }, flagIsEnabled = (configuration, compatibilityFlag) => !!configuration.compatibility_flags.find(
248
+ (flag) => flag === compatibilityFlag.enable
249
+ );
250
+
251
+ // ../workers-shared/asset-worker/src/configuration.ts
252
+ var normalizeConfiguration = (configuration) => {
253
+ let compatibilityOptions = resolveCompatibilityOptions(configuration), basePath = normalizeBasePath(configuration?.base_path ?? "/");
254
+ if (!basePath.valid)
255
+ throw new Error(`Invalid assets base_path: ${basePath.error}`);
256
+ return {
257
+ compatibility_date: compatibilityOptions.compatibilityDate,
258
+ compatibility_flags: compatibilityOptions.compatibilityFlags,
259
+ html_handling: configuration?.html_handling ?? "auto-trailing-slash",
260
+ not_found_handling: configuration?.not_found_handling ?? "none",
261
+ base_path: basePath.value,
262
+ redirects: configuration?.redirects ?? {
263
+ version: 1,
264
+ staticRules: {},
265
+ rules: {}
266
+ },
267
+ headers: configuration?.headers ?? {
268
+ version: 2,
269
+ rules: {}
270
+ },
271
+ has_static_routing: configuration?.has_static_routing ?? !1,
272
+ account_id: configuration?.account_id ?? -1,
273
+ script_id: configuration?.script_id ?? -1,
274
+ debug: configuration?.debug ?? !1
275
+ };
276
+ };
277
+
278
+ // ../workers-shared/asset-worker/src/experiment-analytics.ts
279
+ var ExperimentAnalytics = class {
280
+ constructor(readyAnalytics) {
281
+ this.data = {};
282
+ this.readyAnalytics = readyAnalytics;
283
+ }
284
+ setData(newData) {
285
+ this.data = { ...this.data, ...newData };
286
+ }
287
+ getData(key) {
288
+ return this.data[key];
289
+ }
290
+ write() {
291
+ this.readyAnalytics && this.readyAnalytics.logEvent({
292
+ version: 1,
293
+ accountId: this.data.accountId,
294
+ indexId: this.data.experimentName,
295
+ doubles: [
296
+ this.data.manifestReadTime ?? -1
297
+ // double1
298
+ ],
299
+ blobs: [
300
+ this.data.binarySearchVersion
301
+ // blob1
302
+ ]
303
+ });
304
+ }
305
+ };
306
+
307
+ // ../workers-shared/utils/responses.ts
308
+ var OkResponse = class _OkResponse extends Response {
309
+ static {
310
+ this.status = 200;
311
+ }
312
+ constructor(body, init) {
313
+ super(body, {
314
+ ...init,
315
+ status: _OkResponse.status
316
+ });
317
+ }
318
+ }, NotFoundResponse = class _NotFoundResponse extends Response {
319
+ static {
320
+ this.status = 404;
321
+ }
322
+ constructor(...[body, init]) {
323
+ super(body, {
324
+ ...init,
325
+ status: _NotFoundResponse.status,
326
+ statusText: "Not Found"
327
+ });
328
+ }
329
+ }, NoIntentResponse = class extends NotFoundResponse {
330
+ constructor() {
331
+ super();
332
+ }
333
+ }, MethodNotAllowedResponse = class _MethodNotAllowedResponse extends Response {
334
+ static {
335
+ this.status = 405;
336
+ }
337
+ constructor(...[body, init]) {
338
+ super(body, {
339
+ ...init,
340
+ status: _MethodNotAllowedResponse.status,
341
+ statusText: "Method Not Allowed"
342
+ });
343
+ }
344
+ }, InternalServerErrorResponse = class _InternalServerErrorResponse extends Response {
345
+ static {
346
+ this.status = 500;
347
+ }
348
+ constructor(_, init) {
349
+ super(null, {
350
+ ...init,
351
+ status: _InternalServerErrorResponse.status
352
+ });
353
+ }
354
+ }, NotModifiedResponse = class _NotModifiedResponse extends Response {
355
+ static {
356
+ this.status = 304;
357
+ }
358
+ constructor(...[_body, init]) {
359
+ super(null, {
360
+ ...init,
361
+ status: _NotModifiedResponse.status,
362
+ statusText: "Not Modified"
363
+ });
364
+ }
365
+ }, MovedPermanentlyResponse = class _MovedPermanentlyResponse extends Response {
366
+ static {
367
+ this.status = 301;
368
+ }
369
+ constructor(location, init) {
370
+ super(null, {
371
+ ...init,
372
+ status: _MovedPermanentlyResponse.status,
373
+ statusText: "Moved Permanently",
374
+ headers: {
375
+ ...init?.headers,
376
+ Location: location
377
+ }
378
+ });
379
+ }
380
+ }, FoundResponse = class _FoundResponse extends Response {
381
+ static {
382
+ this.status = 302;
383
+ }
384
+ constructor(location, init) {
385
+ super(null, {
386
+ ...init,
387
+ status: _FoundResponse.status,
388
+ statusText: "Found",
389
+ headers: {
390
+ ...init?.headers,
391
+ Location: location
392
+ }
393
+ });
394
+ }
395
+ }, SeeOtherResponse = class _SeeOtherResponse extends Response {
396
+ static {
397
+ this.status = 303;
398
+ }
399
+ constructor(location, init) {
400
+ super(null, {
401
+ ...init,
402
+ status: _SeeOtherResponse.status,
403
+ statusText: "See Other",
404
+ headers: {
405
+ ...init?.headers,
406
+ Location: location
407
+ }
408
+ });
409
+ }
410
+ }, TemporaryRedirectResponse = class _TemporaryRedirectResponse extends Response {
411
+ static {
412
+ this.status = 307;
413
+ }
414
+ constructor(location, init) {
415
+ super(null, {
416
+ ...init,
417
+ status: _TemporaryRedirectResponse.status,
418
+ statusText: "Temporary Redirect",
419
+ headers: {
420
+ ...init?.headers,
421
+ Location: location
422
+ }
423
+ });
424
+ }
425
+ }, PermanentRedirectResponse = class _PermanentRedirectResponse extends Response {
426
+ static {
427
+ this.status = 308;
428
+ }
429
+ constructor(location, init) {
430
+ super(null, {
431
+ ...init,
432
+ status: _PermanentRedirectResponse.status,
433
+ statusText: "Permanent Redirect",
434
+ headers: {
435
+ ...init?.headers,
436
+ Location: location
437
+ }
438
+ });
439
+ }
440
+ };
441
+
442
+ // ../workers-shared/asset-worker/src/utils/base-path.ts
443
+ function isWithinBase(publicDecodedPath, base) {
444
+ return base === "/" ? !0 : publicDecodedPath === base.slice(0, -1) || publicDecodedPath.startsWith(base);
445
+ }
446
+ function stripBasePath(publicDecodedPath, base) {
447
+ if (base === "/")
448
+ return { inPrefix: !0, assetPath: publicDecodedPath };
449
+ if (!isWithinBase(publicDecodedPath, base))
450
+ return { inPrefix: !1, assetPath: publicDecodedPath };
451
+ let stripped = publicDecodedPath.slice(base.length - 1);
452
+ return { inPrefix: !0, assetPath: stripped === "" ? "/" : stripped };
453
+ }
454
+ function addBasePath(assetRelativePath, base) {
455
+ return base === "/" ? assetRelativePath : assetRelativePath === "/" ? base : base.slice(0, -1) + assetRelativePath;
456
+ }
457
+
458
+ // ../workers-shared/asset-worker/src/constants.ts
459
+ var CACHE_CONTROL_BROWSER = "public, max-age=0, must-revalidate";
460
+
461
+ // ../workers-shared/asset-worker/src/utils/rules-engine.ts
462
+ var ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g, escapeRegex = (str) => str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&"), HOST_PLACEHOLDER_REGEX = /(?<=^https:\\\/\\\/[^/]*?):([A-Za-z]\w*)(?=\\)/g, PLACEHOLDER_REGEX = /:([A-Za-z]\w*)/g, replacer = (str, replacements) => {
463
+ for (let [replacement, value] of Object.entries(replacements))
464
+ str = str.replaceAll(`:${replacement}`, value);
465
+ return str;
466
+ };
467
+ var generateRuleRegExp = (rule) => {
468
+ rule = rule.split("*").map(escapeRegex).join("(?<splat>.*)");
469
+ let host_matches = rule.matchAll(HOST_PLACEHOLDER_REGEX);
470
+ for (let host_match of host_matches)
471
+ rule = rule.split(host_match[0]).join(`(?<${host_match[1]}>[^/.]+)`);
472
+ let path_matches = rule.matchAll(PLACEHOLDER_REGEX);
473
+ for (let path_match of path_matches)
474
+ rule = rule.split(path_match[0]).join(`(?<${path_match[1]}>[^/]+)`);
475
+ return rule = "^" + rule + "$", RegExp(rule);
476
+ }, generateRulesMatcher = (rules, replacerFn = (match) => match) => {
477
+ if (!rules)
478
+ return () => [];
479
+ let compiledRules = Object.entries(rules).map(([rule, match]) => {
480
+ let crossHost = rule.startsWith("https://");
481
+ try {
482
+ let regExp = generateRuleRegExp(rule);
483
+ return [{ crossHost, regExp }, match];
484
+ } catch {
485
+ }
486
+ }).filter((value) => value !== void 0);
487
+ return ({ request }) => {
488
+ let { pathname, hostname } = new URL(request.url);
489
+ return compiledRules.map(([{ crossHost, regExp }, match]) => {
490
+ let test = crossHost ? `https://${hostname}${pathname}` : pathname, result = regExp.exec(test);
491
+ if (result)
492
+ return replacerFn(match, result.groups || {});
493
+ }).filter((value) => value !== void 0);
494
+ };
495
+ }, staticRedirectsMatcher = (configuration, host, pathname) => {
496
+ let withHostMatch = configuration.redirects.staticRules[`https://${host}${pathname}`], withoutHostMatch = configuration.redirects.staticRules[pathname];
497
+ return withHostMatch && withoutHostMatch ? withHostMatch.lineNumber < withoutHostMatch.lineNumber ? withHostMatch : withoutHostMatch : withHostMatch || withoutHostMatch;
498
+ }, generateRedirectsMatcher = (configuration) => generateRulesMatcher(
499
+ configuration.redirects.version === REDIRECTS_VERSION ? configuration.redirects.rules : {},
500
+ ({ status, to }, replacements) => ({
501
+ status,
502
+ to: normalizeRedirectTarget(to, replacements)
503
+ })
504
+ );
505
+ function normalizeRedirectTarget(value, replacements) {
506
+ let isExternal = /^(?:\w+:\/\/|\/\/[^/\\\s?#])/.test(value.trim()), target = replacer(value, replacements).trim();
507
+ if (isExternal)
508
+ return target;
509
+ let suffixStart = target.search(/[?#]/), pathname = suffixStart === -1 ? target : target.slice(0, suffixStart), suffix = suffixStart === -1 ? "" : target.slice(suffixStart);
510
+ return pathname.replace(/[/\\]+/g, "/") + suffix;
511
+ }
512
+
513
+ // ../workers-shared/asset-worker/src/utils/headers.ts
514
+ function getAssetHeaders({ eTag, resolver }, contentType, cacheStatus, request, configuration) {
515
+ let headers = new Headers({
516
+ ETag: `"${eTag}"`
517
+ });
518
+ return contentType !== void 0 && headers.append("Content-Type", contentType), isCacheable(request) && headers.append("Cache-Control", CACHE_CONTROL_BROWSER), headers.append("CF-Cache-Status", cacheStatus), configuration.debug && resolver === "not-found" && flagIsEnabled(
519
+ configuration,
520
+ SEC_FETCH_MODE_NAVIGATE_HEADER_PREFERS_ASSET_SERVING
521
+ ) && headers.append(
522
+ "X-Mf-Additional-Response-Log",
523
+ "`Sec-Fetch-Mode: navigate` header present - using `not_found_handling` behavior"
524
+ ), headers;
525
+ }
526
+ function isCacheable(request) {
527
+ return !request.headers.has("Authorization") && !request.headers.has("Range");
528
+ }
529
+ function attachCustomHeaders(request, response, configuration, env) {
530
+ return (env.JAEGER ?? mockJaegerBinding()).enterSpan("add_headers", (span) => {
531
+ let matches = generateRulesMatcher(
532
+ configuration.headers?.version === HEADERS_VERSION ? configuration.headers.rules : {},
533
+ ({ set = {}, unset = [] }, replacements) => {
534
+ let replacedSet = {};
535
+ return Object.entries(set).forEach(([key, value]) => {
536
+ replacedSet[key] = replacer(value, replacements);
537
+ }), {
538
+ set: replacedSet,
539
+ unset
540
+ };
541
+ }
542
+ )({ request }), setMap = /* @__PURE__ */ new Set();
543
+ return matches.forEach(({ set = {}, unset = [] }) => {
544
+ unset.forEach((key) => {
545
+ response.headers.delete(key), span.addLogs({ remove_header: key });
546
+ }), Object.entries(set).forEach(([key, value]) => {
547
+ setMap.has(key.toLowerCase()) ? (response.headers.append(key, value), span.addLogs({ append_header: key })) : (response.headers.set(key, value), setMap.add(key.toLowerCase()), span.addLogs({ add_header: key }));
548
+ });
549
+ }), response;
550
+ });
551
+ }
552
+
553
+ // ../workers-shared/asset-worker/src/handler.ts
554
+ var REDIRECTS_VERSION = 1, HEADERS_VERSION = 2, getResponseOrAssetIntent = async (request, env, configuration, exists, originalDecodedPathname, analytics) => {
555
+ let url = new URL(request.url), { search } = url, base = configuration.base_path, redirectResult = handleRedirects(
556
+ env,
557
+ request,
558
+ configuration,
559
+ url.host,
560
+ url.pathname,
561
+ search
562
+ );
563
+ if (redirectResult instanceof Response)
564
+ return analytics?.setData({ servedBy: "redirect" }), redirectResult;
565
+ let { proxied, pathname } = redirectResult, effectiveDecodedPathname = proxied ? decodePath(pathname) : originalDecodedPathname, { inPrefix, assetPath } = stripBasePath(effectiveDecodedPathname, base);
566
+ if (!inPrefix)
567
+ return noIntent(
568
+ env,
569
+ analytics,
570
+ configuration,
571
+ effectiveDecodedPathname,
572
+ proxied
573
+ );
574
+ let intent = (proxied ? null : await getBaseRootIntent(
575
+ effectiveDecodedPathname,
576
+ base,
577
+ request,
578
+ configuration,
579
+ exists
580
+ )) ?? await getIntent(assetPath, request, configuration, exists);
581
+ if (!intent)
582
+ return noIntent(
583
+ env,
584
+ analytics,
585
+ configuration,
586
+ effectiveDecodedPathname,
587
+ proxied
588
+ );
589
+ let method = request.method.toUpperCase();
590
+ if (!["GET", "HEAD"].includes(method))
591
+ return analytics?.setData({ servedBy: "method-not-allowed" }), env.JAEGER.enterSpan("method_not_allowed", (span) => (span.setTags({
592
+ method,
593
+ status: MethodNotAllowedResponse.status
594
+ }), new MethodNotAllowedResponse()));
595
+ let decodedDestination = intent.redirect !== null ? addBasePath(intent.redirect, base) : effectiveDecodedPathname, encodedDestination = encodePath(decodedDestination);
596
+ return encodedDestination !== pathname && intent.asset || intent.redirect !== null ? (analytics?.setData({ servedBy: "redirect" }), env.JAEGER.enterSpan("redirect", (span) => (span.setTags({
597
+ originalPath: pathname,
598
+ location: encodedDestination !== pathname ? encodedDestination : intent.redirect ?? "<unknown>",
599
+ status: TemporaryRedirectResponse.status
600
+ }), new TemporaryRedirectResponse(encodedDestination + search)))) : intent.asset ? { ...intent.asset, resolver: intent.resolver } : (analytics?.setData({ servedBy: "error" }), env.JAEGER.enterSpan("unknown_action", (span) => (span.setTags({
601
+ pathname,
602
+ status: InternalServerErrorResponse.status
603
+ }), new InternalServerErrorResponse(new Error("Unknown action")))));
604
+ };
605
+ function noIntent(env, analytics, configuration, decodedPathname, proxied, claimProxiedRequest = !0) {
606
+ let response = proxied && claimProxiedRequest ? new NotFoundResponse() : new NoIntentResponse();
607
+ return analytics?.setData({ servedBy: "none" }), env.JAEGER.enterSpan("no_intent", (span) => (span.setTags({
608
+ decodedPathname,
609
+ configuration: JSON.stringify(configuration),
610
+ proxied,
611
+ status: response.status
612
+ }), response));
613
+ }
614
+ var resolveAssetIntentToResponse = async (assetIntent, request, env, configuration, getByETag, analytics) => {
615
+ let { pathname } = new URL(request.url), method = request.method.toUpperCase(), asset = await env.JAEGER.enterSpan("getByETag", async (span) => (span.setTags({
616
+ pathname,
617
+ eTag: assetIntent.eTag,
618
+ status: assetIntent.status
619
+ }), await getByETag(assetIntent.eTag, request))), headers = getAssetHeaders(
620
+ assetIntent,
621
+ asset.contentType,
622
+ asset.cacheStatus,
623
+ request,
624
+ configuration
625
+ );
626
+ analytics.setData({ cacheStatus: asset.cacheStatus });
627
+ let strongETag = `"${assetIntent.eTag}"`, weakETag = `W/${strongETag}`, ifNoneMatch = request.headers.get("If-None-Match") || "";
628
+ return [weakETag, strongETag].includes(ifNoneMatch) ? (analytics.setData({ servedBy: "not-modified" }), env.JAEGER.enterSpan("matched_etag", (span) => (span.setTags({
629
+ matchedEtag: ifNoneMatch,
630
+ status: NotModifiedResponse.status
631
+ }), new NotModifiedResponse(null, { headers })))) : (analytics.setData({
632
+ servedBy: servedByForResolver(assetIntent.resolver, configuration)
633
+ }), env.JAEGER.enterSpan("response", (span) => {
634
+ span.setTags({
635
+ etag: assetIntent.eTag,
636
+ status: assetIntent.status,
637
+ head: method === "HEAD"
638
+ });
639
+ let body = method === "HEAD" ? null : asset.readableStream;
640
+ switch (assetIntent.status) {
641
+ case NotFoundResponse.status:
642
+ return new NotFoundResponse(body, { headers });
643
+ case OkResponse.status:
644
+ return new OkResponse(body, { headers });
645
+ }
646
+ }));
647
+ };
648
+ function getRequestBasePath(request, base) {
649
+ let decodedPathname = decodePath(new URL(request.url).pathname);
650
+ return {
651
+ decodedPathname,
652
+ ...stripBasePath(decodedPathname, base)
653
+ };
654
+ }
655
+ var canFetch = async (request, env, configuration, exists) => {
656
+ let requestPath = getRequestBasePath(request, configuration.base_path);
657
+ return !(!requestPath.inPrefix || (configuration.has_static_routing || flagIsEnabled(
658
+ configuration,
659
+ SEC_FETCH_MODE_NAVIGATE_HEADER_PREFERS_ASSET_SERVING
660
+ ) && request.headers.get("Sec-Fetch-Mode") === "navigate" || (configuration = {
661
+ ...configuration,
662
+ not_found_handling: "none"
663
+ }), await getResponseOrAssetIntent(
664
+ request,
665
+ env,
666
+ configuration,
667
+ exists,
668
+ requestPath.decodedPathname
669
+ ) instanceof NoIntentResponse));
670
+ }, handleRequest = async (request, env, configuration, exists, getByETag, analytics) => {
671
+ let requestPath = getRequestBasePath(request, configuration.base_path);
672
+ if (!requestPath.inPrefix)
673
+ return noIntent(
674
+ env,
675
+ analytics,
676
+ configuration,
677
+ requestPath.decodedPathname,
678
+ !1
679
+ );
680
+ let responseOrAssetIntent = await getResponseOrAssetIntent(
681
+ request,
682
+ env,
683
+ configuration,
684
+ exists,
685
+ requestPath.decodedPathname,
686
+ analytics
687
+ ), response = responseOrAssetIntent instanceof Response ? responseOrAssetIntent : await resolveAssetIntentToResponse(
688
+ responseOrAssetIntent,
689
+ request,
690
+ env,
691
+ configuration,
692
+ getByETag,
693
+ analytics
694
+ );
695
+ return attachCustomHeaders(request, response, configuration, env);
696
+ };
697
+ function servedByForResolver(resolver, configuration) {
698
+ if (resolver === "html-handling")
699
+ return "asset";
700
+ switch (configuration.not_found_handling) {
701
+ case "single-page-application":
702
+ return "spa";
703
+ case "404-page":
704
+ return "404-page";
705
+ case "none":
706
+ return "none";
707
+ default:
708
+ return configuration.not_found_handling, "error";
709
+ }
710
+ }
711
+ var getIntent = async (pathname, request, configuration, exists, skipRedirects = !1) => {
712
+ switch (configuration.html_handling) {
713
+ case "auto-trailing-slash":
714
+ return htmlHandlingAutoTrailingSlash(
715
+ pathname,
716
+ request,
717
+ configuration,
718
+ exists,
719
+ skipRedirects
720
+ );
721
+ case "force-trailing-slash":
722
+ return htmlHandlingForceTrailingSlash(
723
+ pathname,
724
+ request,
725
+ configuration,
726
+ exists,
727
+ skipRedirects
728
+ );
729
+ case "drop-trailing-slash":
730
+ return htmlHandlingDropTrailingSlash(
731
+ pathname,
732
+ request,
733
+ configuration,
734
+ exists,
735
+ skipRedirects
736
+ );
737
+ case "none":
738
+ return htmlHandlingNone(pathname, request, configuration, exists);
739
+ }
740
+ };
741
+ async function getBaseRootIntent(publicDecodedPath, base, request, configuration, exists) {
742
+ let pathname;
743
+ switch (configuration.html_handling) {
744
+ case "force-trailing-slash":
745
+ case "auto-trailing-slash":
746
+ pathname = base !== "/" && publicDecodedPath === base.slice(0, -1) ? "/" : null;
747
+ break;
748
+ case "drop-trailing-slash":
749
+ pathname = base !== "/" && publicDecodedPath === base ? "" : null;
750
+ break;
751
+ case "none":
752
+ return null;
753
+ }
754
+ return pathname === null || !await exists("/index.html", request) ? null : {
755
+ asset: null,
756
+ redirect: pathname,
757
+ resolver: "html-handling"
758
+ };
759
+ }
760
+ var htmlHandlingAutoTrailingSlash = async (pathname, request, configuration, exists, skipRedirects) => {
761
+ let redirectResult = null, eTagResult = null, exactETag = await exists(pathname, request);
762
+ if (pathname.endsWith("/index")) {
763
+ if (exactETag)
764
+ return {
765
+ asset: {
766
+ eTag: exactETag,
767
+ status: OkResponse.status
768
+ },
769
+ redirect: null,
770
+ resolver: "html-handling"
771
+ };
772
+ if (redirectResult = await safeRedirect(
773
+ `${pathname}.html`,
774
+ request,
775
+ pathname.slice(0, -5),
776
+ configuration,
777
+ exists,
778
+ skipRedirects,
779
+ "html-handling"
780
+ ))
781
+ return redirectResult;
782
+ if (redirectResult = await safeRedirect(
783
+ `${pathname.slice(0, -6)}.html`,
784
+ request,
785
+ pathname.slice(0, -6),
786
+ configuration,
787
+ exists,
788
+ skipRedirects,
789
+ "html-handling"
790
+ ))
791
+ return redirectResult;
792
+ } else if (pathname.endsWith("/index.html")) {
793
+ if (redirectResult = await safeRedirect(
794
+ pathname,
795
+ request,
796
+ pathname.slice(0, -10),
797
+ configuration,
798
+ exists,
799
+ skipRedirects,
800
+ "html-handling"
801
+ ))
802
+ return redirectResult;
803
+ if (redirectResult = await safeRedirect(
804
+ `${pathname.slice(0, -11)}.html`,
805
+ request,
806
+ pathname.slice(0, -11),
807
+ configuration,
808
+ exists,
809
+ skipRedirects,
810
+ "html-handling"
811
+ ))
812
+ return redirectResult;
813
+ } else if (pathname.endsWith("/")) {
814
+ if (eTagResult = await exists(`${pathname}index.html`, request))
815
+ return {
816
+ asset: { eTag: eTagResult, status: OkResponse.status },
817
+ redirect: null,
818
+ resolver: "html-handling"
819
+ };
820
+ if (redirectResult = await safeRedirect(
821
+ `${pathname.slice(0, -1)}.html`,
822
+ request,
823
+ pathname.slice(0, -1),
824
+ configuration,
825
+ exists,
826
+ skipRedirects,
827
+ "html-handling"
828
+ ))
829
+ return redirectResult;
830
+ } else if (pathname.endsWith(".html")) {
831
+ if (redirectResult = await safeRedirect(
832
+ pathname,
833
+ request,
834
+ pathname.slice(0, -5),
835
+ configuration,
836
+ exists,
837
+ skipRedirects,
838
+ "html-handling"
839
+ ))
840
+ return redirectResult;
841
+ if (redirectResult = await safeRedirect(
842
+ `${pathname.slice(0, -5)}/index.html`,
843
+ request,
844
+ `${pathname.slice(0, -5)}/`,
845
+ configuration,
846
+ exists,
847
+ skipRedirects,
848
+ "html-handling"
849
+ ))
850
+ return redirectResult;
851
+ }
852
+ return exactETag ? {
853
+ asset: { eTag: exactETag, status: OkResponse.status },
854
+ redirect: null,
855
+ resolver: "html-handling"
856
+ } : (eTagResult = await exists(`${pathname}.html`, request)) ? {
857
+ asset: { eTag: eTagResult, status: OkResponse.status },
858
+ redirect: null,
859
+ resolver: "html-handling"
860
+ } : (redirectResult = await safeRedirect(
861
+ `${pathname}/index.html`,
862
+ request,
863
+ `${pathname}/`,
864
+ configuration,
865
+ exists,
866
+ skipRedirects,
867
+ "html-handling"
868
+ )) ? redirectResult : notFound(pathname, request, configuration, exists);
869
+ }, htmlHandlingForceTrailingSlash = async (pathname, request, configuration, exists, skipRedirects) => {
870
+ let redirectResult = null, eTagResult = null, exactETag = await exists(pathname, request);
871
+ if (pathname.endsWith("/index")) {
872
+ if (exactETag)
873
+ return {
874
+ asset: { eTag: exactETag, status: OkResponse.status },
875
+ redirect: null,
876
+ resolver: "html-handling"
877
+ };
878
+ if (redirectResult = await safeRedirect(
879
+ `${pathname}.html`,
880
+ request,
881
+ pathname.slice(0, -5),
882
+ configuration,
883
+ exists,
884
+ skipRedirects,
885
+ "html-handling"
886
+ ))
887
+ return redirectResult;
888
+ if (redirectResult = await safeRedirect(
889
+ `${pathname.slice(0, -6)}.html`,
890
+ request,
891
+ pathname.slice(0, -5),
892
+ configuration,
893
+ exists,
894
+ skipRedirects,
895
+ "html-handling"
896
+ ))
897
+ return redirectResult;
898
+ } else if (pathname.endsWith("/index.html")) {
899
+ if (redirectResult = await safeRedirect(
900
+ pathname,
901
+ request,
902
+ pathname.slice(0, -10),
903
+ configuration,
904
+ exists,
905
+ skipRedirects,
906
+ "html-handling"
907
+ ))
908
+ return redirectResult;
909
+ if (redirectResult = await safeRedirect(
910
+ `${pathname.slice(0, -11)}.html`,
911
+ request,
912
+ pathname.slice(0, -10),
913
+ configuration,
914
+ exists,
915
+ skipRedirects,
916
+ "html-handling"
917
+ ))
918
+ return redirectResult;
919
+ } else if (pathname.endsWith("/")) {
920
+ if (eTagResult = await exists(`${pathname}index.html`, request))
921
+ return {
922
+ asset: { eTag: eTagResult, status: OkResponse.status },
923
+ redirect: null,
924
+ resolver: "html-handling"
925
+ };
926
+ if (eTagResult = await exists(
927
+ `${pathname.slice(0, -1)}.html`,
928
+ request
929
+ ))
930
+ return {
931
+ asset: { eTag: eTagResult, status: OkResponse.status },
932
+ redirect: null,
933
+ resolver: "html-handling"
934
+ };
935
+ } else if (pathname.endsWith(".html")) {
936
+ if (redirectResult = await safeRedirect(
937
+ pathname,
938
+ request,
939
+ `${pathname.slice(0, -5)}/`,
940
+ configuration,
941
+ exists,
942
+ skipRedirects,
943
+ "html-handling"
944
+ ))
945
+ return redirectResult;
946
+ if (exactETag)
947
+ return {
948
+ asset: { eTag: exactETag, status: OkResponse.status },
949
+ redirect: null,
950
+ resolver: "html-handling"
951
+ };
952
+ if (redirectResult = await safeRedirect(
953
+ `${pathname.slice(0, -5)}/index.html`,
954
+ request,
955
+ `${pathname.slice(0, -5)}/`,
956
+ configuration,
957
+ exists,
958
+ skipRedirects,
959
+ "html-handling"
960
+ ))
961
+ return redirectResult;
962
+ }
963
+ return exactETag ? {
964
+ asset: { eTag: exactETag, status: OkResponse.status },
965
+ redirect: null,
966
+ resolver: "html-handling"
967
+ } : (redirectResult = await safeRedirect(
968
+ `${pathname}.html`,
969
+ request,
970
+ `${pathname}/`,
971
+ configuration,
972
+ exists,
973
+ skipRedirects,
974
+ "html-handling"
975
+ )) || (redirectResult = await safeRedirect(
976
+ `${pathname}/index.html`,
977
+ request,
978
+ `${pathname}/`,
979
+ configuration,
980
+ exists,
981
+ skipRedirects,
982
+ "html-handling"
983
+ )) ? redirectResult : notFound(pathname, request, configuration, exists);
984
+ }, htmlHandlingDropTrailingSlash = async (pathname, request, configuration, exists, skipRedirects) => {
985
+ let redirectResult = null, eTagResult = null, exactETag = await exists(pathname, request);
986
+ if (pathname.endsWith("/index")) {
987
+ if (exactETag)
988
+ return {
989
+ asset: { eTag: exactETag, status: OkResponse.status },
990
+ redirect: null,
991
+ resolver: "html-handling"
992
+ };
993
+ if (pathname === "/index") {
994
+ if (redirectResult = await safeRedirect(
995
+ "/index.html",
996
+ request,
997
+ "/",
998
+ configuration,
999
+ exists,
1000
+ skipRedirects,
1001
+ "html-handling"
1002
+ ))
1003
+ return redirectResult;
1004
+ } else {
1005
+ if (redirectResult = await safeRedirect(
1006
+ `${pathname.slice(0, -6)}.html`,
1007
+ request,
1008
+ pathname.slice(0, -6),
1009
+ configuration,
1010
+ exists,
1011
+ skipRedirects,
1012
+ "html-handling"
1013
+ ))
1014
+ return redirectResult;
1015
+ if (redirectResult = await safeRedirect(
1016
+ `${pathname}.html`,
1017
+ request,
1018
+ pathname.slice(0, -6),
1019
+ configuration,
1020
+ exists,
1021
+ skipRedirects,
1022
+ "html-handling"
1023
+ ))
1024
+ return redirectResult;
1025
+ }
1026
+ } else if (pathname.endsWith("/index.html"))
1027
+ if (pathname === "/index.html") {
1028
+ if (redirectResult = await safeRedirect(
1029
+ "/index.html",
1030
+ request,
1031
+ "/",
1032
+ configuration,
1033
+ exists,
1034
+ skipRedirects,
1035
+ "html-handling"
1036
+ ))
1037
+ return redirectResult;
1038
+ } else {
1039
+ if (redirectResult = await safeRedirect(
1040
+ pathname,
1041
+ request,
1042
+ pathname.slice(0, -11),
1043
+ configuration,
1044
+ exists,
1045
+ skipRedirects,
1046
+ "html-handling"
1047
+ ))
1048
+ return redirectResult;
1049
+ if (exactETag)
1050
+ return {
1051
+ asset: { eTag: exactETag, status: OkResponse.status },
1052
+ redirect: null,
1053
+ resolver: "html-handling"
1054
+ };
1055
+ if (redirectResult = await safeRedirect(
1056
+ `${pathname.slice(0, -11)}.html`,
1057
+ request,
1058
+ pathname.slice(0, -11),
1059
+ configuration,
1060
+ exists,
1061
+ skipRedirects,
1062
+ "html-handling"
1063
+ ))
1064
+ return redirectResult;
1065
+ }
1066
+ else if (pathname.endsWith("/"))
1067
+ if (pathname === "/") {
1068
+ if (eTagResult = await exists("/index.html", request))
1069
+ return {
1070
+ asset: { eTag: eTagResult, status: OkResponse.status },
1071
+ redirect: null,
1072
+ resolver: "html-handling"
1073
+ };
1074
+ } else {
1075
+ if (redirectResult = await safeRedirect(
1076
+ `${pathname.slice(0, -1)}.html`,
1077
+ request,
1078
+ pathname.slice(0, -1),
1079
+ configuration,
1080
+ exists,
1081
+ skipRedirects,
1082
+ "html-handling"
1083
+ ))
1084
+ return redirectResult;
1085
+ if (redirectResult = await safeRedirect(
1086
+ `${pathname.slice(0, -1)}/index.html`,
1087
+ request,
1088
+ pathname.slice(0, -1),
1089
+ configuration,
1090
+ exists,
1091
+ skipRedirects,
1092
+ "html-handling"
1093
+ ))
1094
+ return redirectResult;
1095
+ }
1096
+ else if (pathname.endsWith(".html")) {
1097
+ if (redirectResult = await safeRedirect(
1098
+ pathname,
1099
+ request,
1100
+ pathname.slice(0, -5),
1101
+ configuration,
1102
+ exists,
1103
+ skipRedirects,
1104
+ "html-handling"
1105
+ ))
1106
+ return redirectResult;
1107
+ if (redirectResult = await safeRedirect(
1108
+ `${pathname.slice(0, -5)}/index.html`,
1109
+ request,
1110
+ pathname.slice(0, -5),
1111
+ configuration,
1112
+ exists,
1113
+ skipRedirects,
1114
+ "html-handling"
1115
+ ))
1116
+ return redirectResult;
1117
+ }
1118
+ return exactETag ? {
1119
+ asset: { eTag: exactETag, status: OkResponse.status },
1120
+ redirect: null,
1121
+ resolver: "html-handling"
1122
+ } : (eTagResult = await exists(`${pathname}.html`, request)) ? {
1123
+ asset: { eTag: eTagResult, status: OkResponse.status },
1124
+ redirect: null,
1125
+ resolver: "html-handling"
1126
+ } : (eTagResult = await exists(`${pathname}/index.html`, request)) ? {
1127
+ asset: { eTag: eTagResult, status: OkResponse.status },
1128
+ redirect: null,
1129
+ resolver: "html-handling"
1130
+ } : notFound(pathname, request, configuration, exists);
1131
+ }, htmlHandlingNone = async (pathname, request, configuration, exists) => {
1132
+ let exactETag = await exists(pathname, request);
1133
+ return exactETag ? {
1134
+ asset: { eTag: exactETag, status: OkResponse.status },
1135
+ redirect: null,
1136
+ resolver: "html-handling"
1137
+ } : notFound(pathname, request, configuration, exists);
1138
+ }, notFound = async (pathname, request, configuration, exists) => {
1139
+ switch (configuration.not_found_handling) {
1140
+ case "single-page-application": {
1141
+ let eTag = await exists("/index.html", request);
1142
+ return eTag ? {
1143
+ asset: { eTag, status: OkResponse.status },
1144
+ redirect: null,
1145
+ resolver: "not-found"
1146
+ } : null;
1147
+ }
1148
+ case "404-page": {
1149
+ let cwd = pathname;
1150
+ for (; cwd; ) {
1151
+ cwd = cwd.slice(0, cwd.lastIndexOf("/"));
1152
+ let eTag = await exists(`${cwd}/404.html`, request);
1153
+ if (eTag)
1154
+ return {
1155
+ asset: { eTag, status: NotFoundResponse.status },
1156
+ redirect: null,
1157
+ resolver: "not-found"
1158
+ };
1159
+ }
1160
+ return null;
1161
+ }
1162
+ default:
1163
+ return null;
1164
+ }
1165
+ }, safeRedirect = async (file, request, destination, configuration, exists, skip, resolver) => {
1166
+ if (skip)
1167
+ return null;
1168
+ if (!await exists(destination, request)) {
1169
+ let intent = await getIntent(
1170
+ destination,
1171
+ request,
1172
+ configuration,
1173
+ exists,
1174
+ !0
1175
+ );
1176
+ if (intent?.asset && intent.asset.eTag === await exists(file, request))
1177
+ return {
1178
+ asset: null,
1179
+ redirect: destination,
1180
+ resolver
1181
+ };
1182
+ }
1183
+ return null;
1184
+ }, decodePath = (pathname) => pathname.split("/").map((x) => {
1185
+ try {
1186
+ return decodeURIComponent(x);
1187
+ } catch {
1188
+ return x;
1189
+ }
1190
+ }).join("/").replace(/\/+/g, "/"), encodePath = (pathname) => pathname.split("/").map((x) => {
1191
+ try {
1192
+ return encodeURIComponent(x);
1193
+ } catch {
1194
+ return x;
1195
+ }
1196
+ }).join("/"), handleRedirects = (env, request, configuration, host, pathname, search) => (env.JAEGER ?? mockJaegerBinding()).enterSpan("handle_redirects", (span) => {
1197
+ let redirectMatch = staticRedirectsMatcher(configuration, host, pathname) || generateRedirectsMatcher(configuration)({ request })[0], proxied = !1;
1198
+ if (redirectMatch)
1199
+ if (redirectMatch.status === 200)
1200
+ pathname = new URL(redirectMatch.to, request.url).pathname, proxied = !0, span.setTags({
1201
+ matched: !0,
1202
+ proxied: !0,
1203
+ new_path: pathname,
1204
+ status: redirectMatch.status
1205
+ });
1206
+ else {
1207
+ let { status, to } = redirectMatch, destination = new URL(to, request.url), location = destination.origin === new URL(request.url).origin ? `${destination.pathname}${destination.search || search}${destination.hash}` : `${destination.href.slice(0, destination.href.length - (destination.search.length + destination.hash.length))}${destination.search ? destination.search : search}${destination.hash}`;
1208
+ switch (span.setTags({
1209
+ matched: !0,
1210
+ destination: location,
1211
+ status
1212
+ }), status) {
1213
+ case MovedPermanentlyResponse.status:
1214
+ return new MovedPermanentlyResponse(location);
1215
+ case SeeOtherResponse.status:
1216
+ return new SeeOtherResponse(location);
1217
+ case TemporaryRedirectResponse.status:
1218
+ return new TemporaryRedirectResponse(location);
1219
+ case PermanentRedirectResponse.status:
1220
+ return new PermanentRedirectResponse(location);
1221
+ case FoundResponse.status:
1222
+ default:
1223
+ return new FoundResponse(location);
1224
+ }
1225
+ }
1226
+ else
1227
+ span.setTags({
1228
+ matched: !1
1229
+ });
1230
+ return { proxied, pathname };
1231
+ });
1232
+
1233
+ // ../workers-shared/asset-worker/src/utils/final-operations.ts
1234
+ function handleError(sentry, analytics, err) {
1235
+ try {
1236
+ let response = new InternalServerErrorResponse(err);
1237
+ return sentry && sentry.captureException(err), analytics.setData({ servedBy: "error" }), err instanceof Error && analytics.setData({ error: err.message }), response;
1238
+ } catch (e) {
1239
+ return console.error("Error handling error", e), new InternalServerErrorResponse(e);
1240
+ }
1241
+ }
1242
+ function submitMetrics(analytics, performance, startTimeMs) {
1243
+ try {
1244
+ analytics.setData({ requestTime: performance.now() - startTimeMs }), analytics.write();
1245
+ } catch (e) {
1246
+ console.error("Error submitting metrics", e);
1247
+ }
1248
+ }
1249
+
1250
+ // ../workers-shared/asset-worker/src/utils/kv.ts
1251
+ async function getAssetWithMetadataFromKV(assetsKVNamespace, assetKey, sentry, retries = 3) {
1252
+ let attempts = 0;
1253
+ for (; attempts <= retries; )
1254
+ try {
1255
+ let asset = await assetsKVNamespace.getWithMetadata(
1256
+ assetKey,
1257
+ {
1258
+ type: "stream",
1259
+ cacheTtl: 31536e3
1260
+ // 1 year
1261
+ }
1262
+ );
1263
+ if (asset.value === null) {
1264
+ let retriedAsset = await assetsKVNamespace.getWithMetadata(assetKey, {
1265
+ type: "stream",
1266
+ cacheTtl: 60
1267
+ // Minimum value allowed
1268
+ });
1269
+ return retriedAsset.value !== null && sentry && sentry.captureException(
1270
+ new Error(
1271
+ `Initial request for asset ${assetKey} failed, but subsequent request succeeded.`
1272
+ )
1273
+ ), retriedAsset;
1274
+ }
1275
+ return asset;
1276
+ } catch (err) {
1277
+ if (attempts >= retries) {
1278
+ let message = `KV GET ${assetKey} failed.`;
1279
+ throw err instanceof Error && (message = `KV GET ${assetKey} failed: ${err.message}`), new Error(message);
1280
+ }
1281
+ await new Promise(
1282
+ (resolvePromise) => setTimeout(resolvePromise, Math.pow(2, attempts++) * 1e3)
1283
+ );
1284
+ }
1285
+ }
1286
+
1287
+ // ../workers-shared/asset-worker/src/worker.ts
1288
+ async function unstableExistsImpl(env, pathname, _request) {
1289
+ let analytics = new ExperimentAnalytics(env.EXPERIMENT_ANALYTICS), performance = new PerformanceTimer(env.UNSAFE_PERFORMANCE);
1290
+ return (env.JAEGER ?? mockJaegerBinding()).enterSpan("unstable_exists", async (span) => {
1291
+ env.COLO_METADATA && env.VERSION_METADATA && env.CONFIG && analytics.setData({
1292
+ accountId: env.CONFIG.account_id,
1293
+ experimentName: "manifest-read-timing"
1294
+ });
1295
+ let startTimeMs = performance.now();
1296
+ try {
1297
+ let eTag = await new AssetsManifest(env.ASSETS_MANIFEST).get(pathname);
1298
+ return span.setTags({
1299
+ path: pathname,
1300
+ found: eTag !== null,
1301
+ etag: eTag ?? ""
1302
+ }), eTag;
1303
+ } finally {
1304
+ analytics.setData({
1305
+ manifestReadTime: performance.now() - startTimeMs
1306
+ }), analytics.write();
1307
+ }
1308
+ });
1309
+ }
1310
+ async function unstableGetByETagImpl(env, eTag, _request) {
1311
+ let performance = new PerformanceTimer(env.UNSAFE_PERFORMANCE);
1312
+ return (env.JAEGER ?? mockJaegerBinding()).enterSpan("unstable_getByETag", async (span) => {
1313
+ let startTime = performance.now(), asset = await getAssetWithMetadataFromKV(
1314
+ env.ASSETS_KV_NAMESPACE,
1315
+ eTag
1316
+ ), assetFetchTime = performance.now() - startTime;
1317
+ if (!asset || !asset.value)
1318
+ throw span.setTags({
1319
+ error: !0
1320
+ }), span.addLogs({
1321
+ error: `Requested asset ${eTag} exists in the asset manifest but not in the KV namespace.`
1322
+ }), new Error(
1323
+ `Requested asset ${eTag} exists in the asset manifest but not in the KV namespace.`
1324
+ );
1325
+ let cacheStatus = assetFetchTime <= 100 ? "HIT" : "MISS";
1326
+ return span.setTags({
1327
+ etag: eTag,
1328
+ contentType: asset.metadata?.contentType ?? "unknown",
1329
+ cacheStatus
1330
+ }), {
1331
+ readableStream: asset.value,
1332
+ contentType: asset.metadata?.contentType,
1333
+ cacheStatus
1334
+ };
1335
+ });
1336
+ }
1337
+ async function unstableGetByPathnameImpl(env, exists, getByETag, pathname, request) {
1338
+ return (env.JAEGER ?? mockJaegerBinding()).enterSpan("unstable_getByPathname", async (span) => {
1339
+ let eTag = await exists(pathname, request);
1340
+ return span.setTags({
1341
+ path: pathname,
1342
+ found: eTag !== null
1343
+ }), eTag ? getByETag(eTag, request) : null;
1344
+ });
1345
+ }
1346
+ async function runFetchRequest(request, env, ctx, exists, getByETag, cohort) {
1347
+ let sentry, analytics = new Analytics(env.ANALYTICS), performance = new PerformanceTimer(env.UNSAFE_PERFORMANCE), startTimeMs = performance.now();
1348
+ try {
1349
+ env.JAEGER ??= mockJaegerBinding(), sentry = (env.SENTRY_DSN, env.SENTRY_ACCESS_CLIENT_ID, env.SENTRY_ACCESS_CLIENT_SECRET, env.COLO_METADATA, env.VERSION_METADATA, env.CONFIG?.account_id, env.CONFIG?.script_id, void 0);
1350
+ let config = normalizeConfiguration(env.CONFIG);
1351
+ sentry?.setContext("compatibilityOptions", {
1352
+ compatibilityDate: config.compatibility_date,
1353
+ compatibilityFlags: config.compatibility_flags,
1354
+ originalCompatibilityFlags: env.CONFIG.compatibility_flags
1355
+ });
1356
+ let userAgent = request.headers.get("user-agent") ?? "UA UNKNOWN", url = new URL(request.url);
1357
+ return env.COLO_METADATA && env.VERSION_METADATA && env.CONFIG && analytics.setData({
1358
+ accountId: env.CONFIG.account_id,
1359
+ scriptId: env.CONFIG.script_id,
1360
+ coloId: env.COLO_METADATA.coloId,
1361
+ metalId: env.COLO_METADATA.metalId,
1362
+ coloTier: env.COLO_METADATA.coloTier,
1363
+ coloRegion: env.COLO_METADATA.coloRegion,
1364
+ version: env.VERSION_METADATA.tag,
1365
+ hostname: url.hostname,
1366
+ htmlHandling: config.html_handling,
1367
+ notFoundHandling: config.not_found_handling,
1368
+ compatibilityFlags: config.compatibility_flags,
1369
+ userAgent,
1370
+ entrypoint: 1 /* Inner */,
1371
+ cohort: cohort ?? "unknown",
1372
+ requestKind: getRequestKind(request)
1373
+ }), await env.JAEGER.enterSpan("handleRequest", async (span) => {
1374
+ span.setTags({
1375
+ hostname: url.hostname,
1376
+ eyeballPath: url.pathname,
1377
+ env: env.ENVIRONMENT,
1378
+ version: env.VERSION_METADATA?.id
1379
+ });
1380
+ let response = await handleRequest(
1381
+ request,
1382
+ env,
1383
+ config,
1384
+ exists,
1385
+ getByETag,
1386
+ analytics
1387
+ );
1388
+ return analytics.setData({ status: response.status }), response;
1389
+ });
1390
+ } catch (err) {
1391
+ return handleError(sentry, analytics, err);
1392
+ } finally {
1393
+ submitMetrics(analytics, performance, startTimeMs);
1394
+ }
1395
+ }
1396
+ var AssetWorkerOuter = class extends WorkerEntrypoint {
1397
+ constructor() {
1398
+ super(...arguments);
1399
+ this.resolvedCohort = void 0;
1400
+ }
1401
+ /**
1402
+ * Resolves and caches the cohort for this request. The cohort is
1403
+ * constant for the lifetime of the outer entrypoint instance, so
1404
+ * we only pay the RPC cost once even if multiple methods are called.
1405
+ */
1406
+ async getCohort() {
1407
+ return this.resolvedCohort === void 0 && (this.resolvedCohort = "ent"), this.resolvedCohort;
1408
+ }
1409
+ /**
1410
+ * Gets the inner entrypoint from ctx.exports to forward requests to.
1411
+ * When a cohort is provided, the runtime routes the inner entrypoint
1412
+ * to the version assigned to that cohort in the current deployment.
1413
+ */
1414
+ getInnerEntrypoint(_cohort) {
1415
+ let entrypoint = this.ctx.exports?.AssetWorkerInner;
1416
+ if (entrypoint === void 0)
1417
+ throw new Error(
1418
+ "AssetWorkerInner not found on ctx.exports. Ensure enable_ctx_exports compatibility flag is set and AssetWorkerInner is exported from the worker module."
1419
+ );
1420
+ return entrypoint({
1421
+ props: { traceContext: this.env.JAEGER.getSpanContext() }
1422
+ // TODO: Hardcoding temporarily for latency testing.
1423
+ // ...(cohort ? { version: { cohort } } : {}),
1424
+ });
1425
+ }
1426
+ async fetch(request) {
1427
+ this.env.JAEGER ??= mockJaegerBinding();
1428
+ let sentry, analytics = new Analytics(this.env.ANALYTICS), performance = new PerformanceTimer(this.env.UNSAFE_PERFORMANCE), startTimeMs = performance.now();
1429
+ try {
1430
+ if (this.env.COLO_METADATA && this.env.VERSION_METADATA && this.env.CONFIG) {
1431
+ let url = new URL(request.url);
1432
+ analytics.setData({
1433
+ accountId: this.env.CONFIG.account_id,
1434
+ scriptId: this.env.CONFIG.script_id,
1435
+ coloId: this.env.COLO_METADATA.coloId,
1436
+ metalId: this.env.COLO_METADATA.metalId,
1437
+ coloTier: this.env.COLO_METADATA.coloTier,
1438
+ coloRegion: this.env.COLO_METADATA.coloRegion,
1439
+ hostname: url.hostname,
1440
+ version: this.env.VERSION_METADATA.tag,
1441
+ entrypoint: 0 /* Outer */,
1442
+ requestKind: getRequestKind(request)
1443
+ });
1444
+ }
1445
+ sentry = (this.ctx, this.env.SENTRY_DSN, this.env.SENTRY_ACCESS_CLIENT_ID, this.env.SENTRY_ACCESS_CLIENT_SECRET, this.env.COLO_METADATA, this.env.VERSION_METADATA, this.env.CONFIG?.account_id, this.env.CONFIG?.script_id, void 0);
1446
+ let cohort = await this.getCohort();
1447
+ analytics.setData({ cohort: cohort ?? "unknown" });
1448
+ let response = await this.getInnerEntrypoint(cohort).fetch(request);
1449
+ return analytics.setData({ status: response.status }), response.status >= 500 && analytics.setData({
1450
+ error: "inner entrypoint error",
1451
+ servedBy: "error"
1452
+ }), response;
1453
+ } catch (err) {
1454
+ return analytics.setData({ status: 500 }), handleError(sentry, analytics, err);
1455
+ } finally {
1456
+ submitMetrics(analytics, performance, startTimeMs);
1457
+ }
1458
+ }
1459
+ async unstable_canFetch(request) {
1460
+ this.env.JAEGER ??= mockJaegerBinding();
1461
+ let cohort = await this.getCohort();
1462
+ return this.getInnerEntrypoint(cohort).unstable_canFetch(request);
1463
+ }
1464
+ async unstable_getByETag(eTag, request) {
1465
+ this.env.JAEGER ??= mockJaegerBinding();
1466
+ let cohort = await this.getCohort();
1467
+ return this.getInnerEntrypoint(cohort).unstable_getByETag(eTag, request);
1468
+ }
1469
+ async unstable_getByPathname(pathname, request) {
1470
+ this.env.JAEGER ??= mockJaegerBinding();
1471
+ let cohort = await this.getCohort();
1472
+ return this.getInnerEntrypoint(cohort).unstable_getByPathname(
1473
+ pathname,
1474
+ request
1475
+ );
1476
+ }
1477
+ async unstable_exists(pathname, request) {
1478
+ this.env.JAEGER ??= mockJaegerBinding();
1479
+ let cohort = await this.getCohort();
1480
+ return this.getInnerEntrypoint(cohort).unstable_exists(pathname, request);
1481
+ }
1482
+ }, AssetWorkerInner = class extends WorkerEntrypoint {
1483
+ async fetch(request) {
1484
+ this.env.JAEGER ??= mockJaegerBinding();
1485
+ let traceContext = this.ctx.props?.traceContext ?? null, cohort = this.ctx.version?.cohort, runRequest = () => runFetchRequest(
1486
+ request,
1487
+ this.env,
1488
+ this.ctx,
1489
+ this.unstable_exists.bind(this),
1490
+ this.unstable_getByETag.bind(this),
1491
+ cohort
1492
+ ), response = traceContext ? await this.env.JAEGER.runWithSpanContext(traceContext, runRequest) : await runRequest();
1493
+ if (response instanceof Response)
1494
+ return response;
1495
+ throw new Error("AssetWorkerInner fetch returned non-Response value.");
1496
+ }
1497
+ async unstable_canFetch(request) {
1498
+ return this.env.JAEGER ??= mockJaegerBinding(), canFetch(
1499
+ request,
1500
+ this.env,
1501
+ normalizeConfiguration(this.env.CONFIG),
1502
+ this.unstable_exists.bind(this)
1503
+ );
1504
+ }
1505
+ async unstable_getByETag(eTag, request) {
1506
+ return unstableGetByETagImpl(this.env, eTag, request);
1507
+ }
1508
+ async unstable_getByPathname(pathname, request) {
1509
+ return unstableGetByPathnameImpl(
1510
+ this.env,
1511
+ this.unstable_exists.bind(this),
1512
+ this.unstable_getByETag.bind(this),
1513
+ pathname,
1514
+ request
1515
+ );
1516
+ }
1517
+ async unstable_exists(pathname, request) {
1518
+ return unstableExistsImpl(this.env, pathname, request);
1519
+ }
1520
+ }, worker_default = AssetWorkerInner;
1521
+ export {
1522
+ AssetWorkerInner,
1523
+ AssetWorkerOuter,
1524
+ worker_default as default
1525
+ };