wrangler 0.0.0-e2f9bb2 → 0.0.0-e305903a

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 (258) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +30 -4
  3. package/bin/wrangler.js +154 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1437 -21
  6. package/package.json +185 -148
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +56 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4121 -3114
  13. package/src/__tests__/dev.test.tsx +1331 -738
  14. package/src/__tests__/dialogs.test.tsx +40 -0
  15. package/src/__tests__/generate.test.ts +91 -0
  16. package/src/__tests__/guess-worker-format.test.ts +68 -68
  17. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  18. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  19. package/src/__tests__/helpers/mock-bin.ts +20 -20
  20. package/src/__tests__/helpers/mock-cfetch.ts +199 -94
  21. package/src/__tests__/helpers/mock-console.ts +58 -39
  22. package/src/__tests__/helpers/mock-dialogs.ts +115 -51
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  24. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  25. package/src/__tests__/helpers/mock-istty.ts +65 -18
  26. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  27. package/src/__tests__/helpers/mock-kv.ts +26 -26
  28. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  29. package/src/__tests__/helpers/mock-process.ts +39 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  31. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  32. package/src/__tests__/helpers/msw/handlers/index.ts +13 -0
  33. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  34. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  35. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  36. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  37. package/src/__tests__/helpers/msw/index.ts +4 -0
  38. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  39. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  40. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  41. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  42. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  43. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  44. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  45. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  46. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  47. package/src/__tests__/https-options.test.ts +142 -109
  48. package/src/__tests__/index.test.ts +231 -231
  49. package/src/__tests__/init.test.ts +2689 -1014
  50. package/src/__tests__/jest.setup.ts +147 -30
  51. package/src/__tests__/kv.test.ts +1311 -1094
  52. package/src/__tests__/logger.test.ts +100 -74
  53. package/src/__tests__/metrics.test.ts +450 -0
  54. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  55. package/src/__tests__/middleware.test.ts +726 -0
  56. package/src/__tests__/package-manager.test.ts +312 -165
  57. package/src/__tests__/pages.test.ts +1988 -322
  58. package/src/__tests__/parse.test.ts +253 -245
  59. package/src/__tests__/paths.test.ts +39 -0
  60. package/src/__tests__/publish.test.ts +6955 -4743
  61. package/src/__tests__/pubsub.test.ts +367 -0
  62. package/src/__tests__/r2.test.ts +363 -206
  63. package/src/__tests__/route.test.ts +18 -18
  64. package/src/__tests__/secret.test.ts +624 -426
  65. package/src/__tests__/tail.test.ts +650 -565
  66. package/src/__tests__/test-old-node-version.js +31 -0
  67. package/src/__tests__/user.test.ts +140 -116
  68. package/src/__tests__/validate-dev-props.test.ts +56 -0
  69. package/src/__tests__/version.test.ts +35 -0
  70. package/src/__tests__/whoami.test.tsx +259 -91
  71. package/src/__tests__/worker-namespace.test.ts +319 -0
  72. package/src/abort.d.ts +3 -0
  73. package/src/api/dev.ts +206 -0
  74. package/src/api/index.ts +2 -0
  75. package/src/bundle-reporter.tsx +29 -0
  76. package/src/bundle.ts +721 -134
  77. package/src/cfetch/index.ts +83 -66
  78. package/src/cfetch/internal.ts +267 -90
  79. package/src/cli.ts +23 -7
  80. package/src/config/config.ts +236 -195
  81. package/src/config/diagnostics.ts +61 -61
  82. package/src/config/environment.ts +450 -339
  83. package/src/config/index.ts +258 -38
  84. package/src/config/validation-helpers.ts +379 -357
  85. package/src/config/validation.ts +1769 -1263
  86. package/src/config-cache.ts +81 -41
  87. package/src/create-worker-preview.ts +232 -132
  88. package/src/create-worker-upload-form.ts +285 -224
  89. package/src/d1/backups.tsx +212 -0
  90. package/src/d1/create.tsx +54 -0
  91. package/src/d1/delete.tsx +56 -0
  92. package/src/d1/execute.tsx +294 -0
  93. package/src/d1/formatTimeAgo.ts +14 -0
  94. package/src/d1/index.ts +75 -0
  95. package/src/d1/list.tsx +48 -0
  96. package/src/d1/options.ts +12 -0
  97. package/src/d1/types.tsx +14 -0
  98. package/src/d1/utils.ts +39 -0
  99. package/src/dev/dev-vars.ts +13 -13
  100. package/src/dev/dev.tsx +500 -353
  101. package/src/dev/get-local-persistence-path.tsx +31 -0
  102. package/src/dev/local.tsx +628 -290
  103. package/src/dev/remote.tsx +397 -197
  104. package/src/dev/start-server.ts +443 -0
  105. package/src/dev/use-esbuild.ts +173 -94
  106. package/src/dev/validate-dev-props.ts +31 -0
  107. package/src/dev-registry.tsx +190 -0
  108. package/src/dev.tsx +869 -0
  109. package/src/dialogs.tsx +134 -63
  110. package/src/dispatch-namespace.ts +206 -0
  111. package/src/durable.ts +102 -0
  112. package/src/entry.ts +248 -186
  113. package/src/environment-variables.ts +38 -23
  114. package/src/errors.ts +6 -6
  115. package/src/faye-websocket.d.ts +6 -0
  116. package/src/generate.ts +131 -0
  117. package/src/git-client.ts +42 -0
  118. package/src/global-wrangler-config-path.ts +26 -0
  119. package/src/https-options.ts +84 -80
  120. package/src/index.tsx +2288 -2534
  121. package/src/init.ts +967 -0
  122. package/src/inspect.ts +686 -562
  123. package/src/intl-polyfill.d.ts +123 -123
  124. package/src/is-ci.ts +14 -0
  125. package/src/is-interactive.ts +12 -0
  126. package/src/kv.ts +353 -242
  127. package/src/logger.ts +53 -39
  128. package/src/metrics/index.ts +5 -0
  129. package/src/metrics/metrics-config.ts +239 -0
  130. package/src/metrics/metrics-dispatcher.ts +96 -0
  131. package/src/metrics/metrics-usage-headers.ts +24 -0
  132. package/src/metrics/send-event.ts +93 -0
  133. package/src/miniflare-cli/assets.ts +215 -0
  134. package/src/miniflare-cli/index.ts +200 -33
  135. package/src/miniflare-cli/request-context.ts +18 -18
  136. package/src/module-collection.ts +212 -212
  137. package/src/open-in-browser.ts +5 -14
  138. package/src/package-manager.ts +182 -90
  139. package/src/pages/build.tsx +238 -0
  140. package/src/pages/constants.ts +16 -0
  141. package/src/pages/deployments.tsx +106 -0
  142. package/src/pages/dev.tsx +684 -0
  143. package/src/pages/errors.ts +66 -0
  144. package/src/pages/functions/buildPlugin.ts +110 -0
  145. package/src/pages/functions/buildWorker.ts +156 -0
  146. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  147. package/src/pages/functions/filepath-routing.ts +189 -0
  148. package/src/pages/functions/identifiers.ts +78 -0
  149. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  150. package/src/pages/functions/routes-consolidation.ts +73 -0
  151. package/src/pages/functions/routes-transformation.test.ts +282 -0
  152. package/src/pages/functions/routes-transformation.ts +115 -0
  153. package/src/pages/functions/routes-validation.test.ts +403 -0
  154. package/src/pages/functions/routes-validation.ts +202 -0
  155. package/src/pages/functions/routes.ts +151 -0
  156. package/src/pages/functions.tsx +82 -0
  157. package/src/pages/hash.tsx +13 -0
  158. package/src/pages/index.tsx +94 -0
  159. package/src/pages/projects.tsx +169 -0
  160. package/src/pages/publish.tsx +419 -0
  161. package/src/pages/types.ts +49 -0
  162. package/src/pages/upload.tsx +398 -0
  163. package/src/pages/utils.ts +12 -0
  164. package/src/parse.ts +223 -120
  165. package/src/paths.ts +53 -8
  166. package/src/preview.ts +31 -0
  167. package/src/proxy.ts +435 -383
  168. package/src/publish.ts +837 -441
  169. package/src/pubsub/index.ts +286 -0
  170. package/src/pubsub/pubsub-commands.tsx +623 -0
  171. package/src/r2.ts +100 -19
  172. package/src/selfsigned.d.ts +23 -23
  173. package/src/sites.tsx +279 -200
  174. package/src/tail/filters.ts +108 -110
  175. package/src/tail/index.ts +234 -218
  176. package/src/tail/printing.ts +86 -46
  177. package/src/update-check.ts +11 -11
  178. package/src/user/choose-account.tsx +69 -0
  179. package/src/user/env-vars.ts +46 -0
  180. package/src/user/generate-auth-url.ts +33 -0
  181. package/src/user/generate-random-state.ts +16 -0
  182. package/src/user/index.ts +3 -0
  183. package/src/user/user.tsx +1192 -0
  184. package/src/whoami.tsx +141 -42
  185. package/src/worker.ts +163 -101
  186. package/src/zones.ts +167 -0
  187. package/templates/checked-fetch.js +17 -0
  188. package/templates/d1-beta-facade.js +174 -0
  189. package/templates/experimental-local-cache-stubs.js +27 -0
  190. package/templates/first-party-worker-module-facade.ts +18 -0
  191. package/templates/format-dev-errors.ts +32 -0
  192. package/templates/init-tests/test-jest-new-worker.js +25 -0
  193. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  194. package/templates/middleware/common.ts +62 -0
  195. package/templates/middleware/loader-modules.ts +84 -0
  196. package/templates/middleware/loader-sw.ts +213 -0
  197. package/templates/middleware/middleware-pretty-error.ts +40 -0
  198. package/templates/middleware/middleware-scheduled.ts +15 -0
  199. package/templates/new-worker-scheduled.js +17 -0
  200. package/templates/new-worker-scheduled.ts +32 -0
  201. package/templates/new-worker.js +3 -3
  202. package/templates/new-worker.ts +18 -3
  203. package/templates/no-op-worker.js +10 -0
  204. package/templates/pages-dev-pipeline.ts +35 -0
  205. package/templates/pages-shim.ts +9 -0
  206. package/templates/pages-template-plugin.ts +167 -0
  207. package/templates/pages-template-worker.ts +172 -0
  208. package/templates/serve-static-assets.ts +63 -0
  209. package/templates/service-bindings-module-facade.js +54 -0
  210. package/templates/service-bindings-sw-facade.js +42 -0
  211. package/templates/tsconfig.json +95 -95
  212. package/wrangler-dist/cli.d.ts +841 -0
  213. package/wrangler-dist/cli.js +120834 -70331
  214. package/pages/functions/buildPlugin.ts +0 -92
  215. package/pages/functions/buildWorker.ts +0 -138
  216. package/pages/functions/filepath-routing.ts +0 -189
  217. package/pages/functions/identifiers.ts +0 -78
  218. package/pages/functions/routes.ts +0 -156
  219. package/pages/functions/template-plugin.ts +0 -146
  220. package/pages/functions/template-worker.ts +0 -143
  221. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  222. package/src/miniflare-cli/enum-keys.ts +0 -17
  223. package/src/pages.tsx +0 -1866
  224. package/src/user.tsx +0 -1193
  225. package/templates/static-asset-facade.js +0 -47
  226. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  227. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  228. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  229. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  230. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  231. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  232. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  233. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  234. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  235. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  236. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  237. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  238. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  239. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  240. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  241. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  242. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  243. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  244. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  245. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  246. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  247. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  248. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  249. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  250. package/vendor/wrangler-mime/LICENSE +0 -21
  251. package/vendor/wrangler-mime/Mime.js +0 -97
  252. package/vendor/wrangler-mime/README.md +0 -187
  253. package/vendor/wrangler-mime/cli.js +0 -46
  254. package/vendor/wrangler-mime/index.js +0 -4
  255. package/vendor/wrangler-mime/lite.js +0 -4
  256. package/vendor/wrangler-mime/package.json +0 -52
  257. package/vendor/wrangler-mime/types/other.js +0 -1
  258. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -0,0 +1,213 @@
1
+ import { Awaitable, Dispatcher, Middleware, __facade_invoke__ } from "./common";
2
+ export { __facade_register__, __facade_registerInternal__ } from "./common";
3
+
4
+ // Miniflare's `EventTarget` follows the spec and doesn't allow exceptions to
5
+ // be caught by `dispatchEvent`. Instead it has a custom`ThrowingEventTarget`
6
+ // class that rethrows errors from event listeners in `dispatchEvent`.
7
+ // We'd like errors to be propagated to the top-level `addEventListener`, so
8
+ // we'd like to use `ThrowingEventTarget`. Unfortunately, `ThrowingEventTarget`
9
+ // isn't exposed on the global scope, but `WorkerGlobalScope` (which extends
10
+ // `ThrowingEventTarget`) is. Therefore, we get at it in this nasty way.
11
+ let __FACADE_EVENT_TARGET__: EventTarget;
12
+ if ((globalThis as any).MINIFLARE) {
13
+ __FACADE_EVENT_TARGET__ = new (Object.getPrototypeOf(WorkerGlobalScope))();
14
+ } else {
15
+ __FACADE_EVENT_TARGET__ = new EventTarget();
16
+ }
17
+
18
+ declare global {
19
+ var __facade_addEventListener__: (
20
+ type: string,
21
+ listener: EventListenerOrEventListenerObject,
22
+ options?: EventTargetAddEventListenerOptions | boolean
23
+ ) => void;
24
+ var __facade_removeEventListener__: (
25
+ type: string,
26
+ listener: EventListenerOrEventListenerObject,
27
+ options?: EventTargetEventListenerOptions | boolean
28
+ ) => void;
29
+ var __facade_dispatchEvent__: (event: Event) => void;
30
+ }
31
+
32
+ function __facade_isSpecialEvent__(type: string) {
33
+ return type === "fetch" || type === "scheduled";
34
+ }
35
+ globalThis.__facade_addEventListener__ = function (type, listener, options) {
36
+ if (__facade_isSpecialEvent__(type)) {
37
+ __FACADE_EVENT_TARGET__.addEventListener(type, listener, options);
38
+ } else {
39
+ globalThis.addEventListener(type as any, listener, options);
40
+ }
41
+ };
42
+ globalThis.__facade_removeEventListener__ = function (type, listener, options) {
43
+ if (__facade_isSpecialEvent__(type)) {
44
+ __FACADE_EVENT_TARGET__.removeEventListener(type, listener, options);
45
+ } else {
46
+ globalThis.removeEventListener(type as any, listener, options);
47
+ }
48
+ };
49
+ globalThis.__facade_dispatchEvent__ = function (event) {
50
+ if (__facade_isSpecialEvent__(event.type)) {
51
+ __FACADE_EVENT_TARGET__.dispatchEvent(event);
52
+ } else {
53
+ globalThis.dispatchEvent(event as any);
54
+ }
55
+ };
56
+
57
+ const __facade_waitUntil__ = Symbol("__facade_waitUntil__");
58
+ const __facade_response__ = Symbol("__facade_response__");
59
+ const __facade_dispatched__ = Symbol("__facade_dispatched__");
60
+
61
+ class __Facade_ExtendableEvent__ extends Event {
62
+ [__facade_waitUntil__]: Awaitable<unknown>[] = [];
63
+
64
+ waitUntil(promise: Awaitable<any>) {
65
+ if (!(this instanceof __Facade_ExtendableEvent__)) {
66
+ throw new TypeError("Illegal invocation");
67
+ }
68
+ this[__facade_waitUntil__].push(promise);
69
+ }
70
+ }
71
+
72
+ interface FetchEventInit extends EventInit {
73
+ request: Request;
74
+ passThroughOnException: FetchEvent["passThroughOnException"];
75
+ }
76
+
77
+ class __Facade_FetchEvent__ extends __Facade_ExtendableEvent__ {
78
+ #request: Request;
79
+ #passThroughOnException: FetchEvent["passThroughOnException"];
80
+ [__facade_response__]?: Awaitable<Response>;
81
+ [__facade_dispatched__] = false;
82
+
83
+ constructor(type: "fetch", init: FetchEventInit) {
84
+ super(type);
85
+ this.#request = init.request;
86
+ this.#passThroughOnException = init.passThroughOnException;
87
+ }
88
+
89
+ get request() {
90
+ return this.#request;
91
+ }
92
+
93
+ respondWith(response: Awaitable<Response>) {
94
+ if (!(this instanceof __Facade_FetchEvent__)) {
95
+ throw new TypeError("Illegal invocation");
96
+ }
97
+ if (this[__facade_response__] !== undefined) {
98
+ throw new DOMException(
99
+ "FetchEvent.respondWith() has already been called; it can only be called once.",
100
+ "InvalidStateError"
101
+ );
102
+ }
103
+ if (this[__facade_dispatched__]) {
104
+ throw new DOMException(
105
+ "Too late to call FetchEvent.respondWith(). It must be called synchronously in the event handler.",
106
+ "InvalidStateError"
107
+ );
108
+ }
109
+ this.stopImmediatePropagation();
110
+ this[__facade_response__] = response;
111
+ }
112
+
113
+ passThroughOnException() {
114
+ if (!(this instanceof __Facade_FetchEvent__)) {
115
+ throw new TypeError("Illegal invocation");
116
+ }
117
+ // Need to call native method immediately in case uncaught error thrown
118
+ this.#passThroughOnException();
119
+ }
120
+ }
121
+
122
+ interface ScheduledEventInit extends EventInit {
123
+ scheduledTime: number;
124
+ cron: string;
125
+ noRetry: ScheduledEvent["noRetry"];
126
+ }
127
+
128
+ class __Facade_ScheduledEvent__ extends __Facade_ExtendableEvent__ {
129
+ #scheduledTime: number;
130
+ #cron: string;
131
+ #noRetry: ScheduledEvent["noRetry"];
132
+
133
+ constructor(type: "scheduled", init: ScheduledEventInit) {
134
+ super(type);
135
+ this.#scheduledTime = init.scheduledTime;
136
+ this.#cron = init.cron;
137
+ this.#noRetry = init.noRetry;
138
+ }
139
+
140
+ get scheduledTime() {
141
+ return this.#scheduledTime;
142
+ }
143
+
144
+ get cron() {
145
+ return this.#cron;
146
+ }
147
+
148
+ noRetry() {
149
+ if (!(this instanceof __Facade_ScheduledEvent__)) {
150
+ throw new TypeError("Illegal invocation");
151
+ }
152
+ // Need to call native method immediately in case uncaught error thrown
153
+ this.#noRetry();
154
+ }
155
+ }
156
+
157
+ globalThis.addEventListener("fetch", (event) => {
158
+ const ctx: ExecutionContext = {
159
+ waitUntil: event.waitUntil.bind(event),
160
+ passThroughOnException: event.passThroughOnException.bind(event),
161
+ };
162
+
163
+ const __facade_sw_dispatch__: Dispatcher = function (type, init) {
164
+ if (type === "scheduled") {
165
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
166
+ scheduledTime: Date.now(),
167
+ cron: init.cron ?? "",
168
+ noRetry() {},
169
+ });
170
+
171
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
172
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
173
+ }
174
+ };
175
+
176
+ const __facade_sw_fetch__: Middleware = function (request, _env, ctx) {
177
+ const facadeEvent = new __Facade_FetchEvent__("fetch", {
178
+ request,
179
+ passThroughOnException: ctx.passThroughOnException,
180
+ });
181
+
182
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
183
+ facadeEvent[__facade_dispatched__] = true;
184
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
185
+
186
+ const response = facadeEvent[__facade_response__];
187
+ if (response === undefined) {
188
+ throw new Error("No response!"); // TODO: proper error message
189
+ }
190
+ return response;
191
+ };
192
+
193
+ event.respondWith(
194
+ __facade_invoke__(
195
+ event.request,
196
+ globalThis,
197
+ ctx,
198
+ __facade_sw_dispatch__,
199
+ __facade_sw_fetch__
200
+ )
201
+ );
202
+ });
203
+
204
+ globalThis.addEventListener("scheduled", (event) => {
205
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
206
+ scheduledTime: event.scheduledTime,
207
+ cron: event.cron,
208
+ noRetry: event.noRetry.bind(event),
209
+ });
210
+
211
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
212
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
213
+ });
@@ -0,0 +1,40 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ // A middleware has to be a function of type Middleware
4
+ const prettyError: Middleware = async (request, env, _ctx, middlewareCtx) => {
5
+ try {
6
+ const response = await middlewareCtx.next(request, env);
7
+ return response;
8
+ } catch (e: any) {
9
+ const html = `
10
+ <!DOCTYPE html>
11
+ <html lang="en">
12
+ <head>
13
+ <meta charset="UTF-8">
14
+ <meta http-equiv="X-UA-Compatible" content="IE=edge">
15
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
16
+ <title>Error 🚨</title>
17
+ <style>
18
+ pre {
19
+ margin: 16px auto;
20
+ max-width: 600px;
21
+ background-color: #eeeeee;
22
+ border-radius: 4px;
23
+ padding: 16px;
24
+ }
25
+ </style>
26
+ </head>
27
+ <body>
28
+ <pre>${e.stack}</pre>
29
+ </body>
30
+ </html>
31
+ `;
32
+
33
+ return new Response(html, {
34
+ status: 500,
35
+ headers: { "Content-Type": "text/html;charset=utf-8" },
36
+ });
37
+ }
38
+ };
39
+
40
+ export default prettyError;
@@ -0,0 +1,15 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ // A middleware has to be a function of type Middleware
4
+ const scheduled: Middleware = async (request, env, _ctx, middlewareCtx) => {
5
+ const url = new URL(request.url);
6
+ if (url.pathname === "/__scheduled") {
7
+ const cron = url.searchParams.get("cron") ?? "";
8
+ await middlewareCtx.dispatch("scheduled", { cron });
9
+
10
+ return new Response("Ran scheduled event");
11
+ }
12
+ return middlewareCtx.next(request, env);
13
+ };
14
+
15
+ export default scheduled;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first scheduled worker.
3
+ *
4
+ * - Run `wrangler dev --local` in your terminal to start a development server
5
+ * - Run `curl "http://localhost:8787/cdn-cgi/mf/scheduled"` to trigger the scheduled event
6
+ * - Go back to the console to see what your worker has logged
7
+ * - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
8
+ * - Run `wrangler publish --name my-worker` to publish your worker
9
+ *
10
+ * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
11
+ */
12
+
13
+ export default {
14
+ async scheduled(controller, env, ctx) {
15
+ console.log(`Hello World!`);
16
+ },
17
+ };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first scheduled worker.
3
+ *
4
+ * - Run `wrangler dev --local` in your terminal to start a development server
5
+ * - Run `curl "http://localhost:8787/cdn-cgi/mf/scheduled"` to trigger the scheduled event
6
+ * - Go back to the console to see what your worker has logged
7
+ * - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
8
+ * - Run `wrangler publish --name my-worker` to publish your worker
9
+ *
10
+ * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
11
+ */
12
+
13
+ export interface Env {
14
+ // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
15
+ // MY_KV_NAMESPACE: KVNamespace;
16
+ //
17
+ // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
18
+ // MY_DURABLE_OBJECT: DurableObjectNamespace;
19
+ //
20
+ // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
21
+ // MY_BUCKET: R2Bucket;
22
+ }
23
+
24
+ export default {
25
+ async scheduled(
26
+ controller: ScheduledController,
27
+ env: Env,
28
+ ctx: ExecutionContext
29
+ ): Promise<void> {
30
+ console.log(`Hello World!`);
31
+ },
32
+ };
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  export default {
12
- async fetch(request) {
13
- return new Response("Hello World!");
14
- },
12
+ async fetch(request) {
13
+ return new Response("Hello World!");
14
+ },
15
15
  };
@@ -8,8 +8,23 @@
8
8
  * Learn more at https://developers.cloudflare.com/workers/
9
9
  */
10
10
 
11
+ export interface Env {
12
+ // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
13
+ // MY_KV_NAMESPACE: KVNamespace;
14
+ //
15
+ // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
16
+ // MY_DURABLE_OBJECT: DurableObjectNamespace;
17
+ //
18
+ // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
19
+ // MY_BUCKET: R2Bucket;
20
+ }
21
+
11
22
  export default {
12
- async fetch(request: Request): Promise<Response> {
13
- return new Response("Hello World!");
14
- },
23
+ async fetch(
24
+ request: Request,
25
+ env: Env,
26
+ ctx: ExecutionContext
27
+ ): Promise<Response> {
28
+ return new Response("Hello World!");
29
+ },
15
30
  };
@@ -0,0 +1,10 @@
1
+ export default {
2
+ fetch() {
3
+ return new Response("Not found", {
4
+ status: 404,
5
+ headers: {
6
+ "Content-Type": "text/html",
7
+ },
8
+ });
9
+ },
10
+ };
@@ -0,0 +1,35 @@
1
+ // @ts-ignore entry point will get replaced
2
+ import worker from "__ENTRY_POINT__";
3
+ // @ts-ignore entry point will get replaced
4
+ export * from "__ENTRY_POINT__";
5
+
6
+ const transformToRegex = (filter: string) => {
7
+ return filter.replace("*", ".*");
8
+ };
9
+
10
+ const routes = {
11
+ // @ts-ignore routes are injected
12
+ include: __ROUTES__.include.map(transformToRegex),
13
+ // @ts-ignore routes are injected
14
+ exclude: __ROUTES__.exclude.map(transformToRegex) || [],
15
+ };
16
+
17
+ export default {
18
+ fetch(request, env, context) {
19
+ const { pathname } = new URL(request.url);
20
+
21
+ for (const exclude of routes.exclude) {
22
+ if (pathname.match(exclude)) {
23
+ return env.ASSETS.fetch(request);
24
+ }
25
+ }
26
+
27
+ for (const include of routes.include) {
28
+ if (pathname.match(include)) {
29
+ return worker.fetch(request, env, context);
30
+ }
31
+ }
32
+
33
+ return env.ASSETS.fetch(request);
34
+ },
35
+ };
@@ -0,0 +1,9 @@
1
+ // This Worker is used as a default when no Pages Functions are present.
2
+ // It proxies the request directly on to the asset server binding.
3
+
4
+ export default {
5
+ async fetch(request, env, context) {
6
+ const response = await env.ASSETS.fetch(request.url, request);
7
+ return new Response(response.body, response);
8
+ },
9
+ };
@@ -0,0 +1,167 @@
1
+ import { match } from "path-to-regexp";
2
+
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
6
+ type HTTPMethod =
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
14
+
15
+ /* TODO: Grab these from @cloudflare/workers-types instead */
16
+ type Params<P extends string = string> = Record<P, string | string[]>;
17
+
18
+ type EventContext<Env, P extends string, Data> = {
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
23
+ env: Env & { ASSETS: { fetch: typeof fetch } };
24
+ params: Params<P>;
25
+ data: Data;
26
+ };
27
+
28
+ type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
29
+ request: Request;
30
+ functionPath: string;
31
+ waitUntil: (promise: Promise<unknown>) => void;
32
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
33
+ env: Env & { ASSETS: { fetch: typeof fetch } };
34
+ params: Params<P>;
35
+ data: Data;
36
+ pluginArgs: PluginArgs;
37
+ };
38
+
39
+ declare type PagesFunction<
40
+ Env = unknown,
41
+ P extends string = string,
42
+ Data extends Record<string, unknown> = Record<string, unknown>
43
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
44
+
45
+ declare type PagesPluginFunction<
46
+ Env = unknown,
47
+ P extends string = string,
48
+ Data extends Record<string, unknown> = Record<string, unknown>,
49
+ PluginArgs = unknown
50
+ > = (
51
+ context: EventPluginContext<Env, P, Data, PluginArgs>
52
+ ) => Response | Promise<Response>;
53
+ /* end @cloudflare/workers-types */
54
+
55
+ type RouteHandler = {
56
+ routePath: string;
57
+ mountPath: string;
58
+ method?: HTTPMethod;
59
+ modules: PagesFunction[];
60
+ middlewares: PagesFunction[];
61
+ };
62
+
63
+ // inject `routes` via ESBuild
64
+ declare const routes: RouteHandler[];
65
+
66
+ function* executeRequest(request: Request, relativePathname: string) {
67
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
68
+ for (const route of [...routes].reverse()) {
69
+ if (route.method && route.method !== request.method) {
70
+ continue;
71
+ }
72
+
73
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
74
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
75
+ end: false,
76
+ });
77
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
78
+ end: false,
79
+ });
80
+ const matchResult = routeMatcher(relativePathname);
81
+ const mountMatchResult = mountMatcher(relativePathname);
82
+ if (matchResult && mountMatchResult) {
83
+ for (const handler of route.middlewares.flat()) {
84
+ yield {
85
+ handler,
86
+ params: matchResult.params as Params,
87
+ path: mountMatchResult.path,
88
+ };
89
+ }
90
+ }
91
+ }
92
+
93
+ // Then look for the first exact route match and execute its "modules"
94
+ for (const route of routes) {
95
+ if (route.method && route.method !== request.method) {
96
+ continue;
97
+ }
98
+
99
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
100
+ end: true,
101
+ });
102
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
103
+ end: false,
104
+ });
105
+ const matchResult = routeMatcher(relativePathname);
106
+ const mountMatchResult = mountMatcher(relativePathname);
107
+ if (matchResult && mountMatchResult && route.modules.length) {
108
+ for (const handler of route.modules.flat()) {
109
+ yield {
110
+ handler,
111
+ params: matchResult.params as Params,
112
+ path: matchResult.path,
113
+ };
114
+ }
115
+ break;
116
+ }
117
+ }
118
+ }
119
+
120
+ export default function (pluginArgs) {
121
+ const onRequest: PagesPluginFunction = async (workerContext) => {
122
+ let { request } = workerContext;
123
+ const { env, next, data } = workerContext;
124
+
125
+ const url = new URL(request.url);
126
+ const relativePathname = `/${
127
+ url.pathname.split(workerContext.functionPath)[1] || ""
128
+ }`.replace(/^\/\//, "/");
129
+
130
+ const handlerIterator = executeRequest(request, relativePathname);
131
+ const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
132
+ if (input !== undefined) {
133
+ request = new Request(input, init);
134
+ }
135
+
136
+ const result = handlerIterator.next();
137
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
138
+ if (result.done === false) {
139
+ const { handler, params, path } = result.value;
140
+ const context = {
141
+ request,
142
+ functionPath: workerContext.functionPath + path,
143
+ next: pluginNext,
144
+ params,
145
+ data,
146
+ pluginArgs,
147
+ env,
148
+ waitUntil: workerContext.waitUntil.bind(workerContext),
149
+ };
150
+
151
+ const response = await handler(context);
152
+
153
+ // https://fetch.spec.whatwg.org/#null-body-status
154
+ return new Response(
155
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
156
+ { ...response, headers: new Headers(response.headers) }
157
+ );
158
+ } else {
159
+ return next();
160
+ }
161
+ };
162
+
163
+ return pluginNext();
164
+ };
165
+
166
+ return onRequest;
167
+ }