wrangler 0.0.0-e9ab55a → 0.0.0-e9fae558

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 (115) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +117 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -125
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/new-worker-scheduled.js +17 -0
  27. package/templates/new-worker-scheduled.ts +32 -0
  28. package/templates/new-worker.js +15 -0
  29. package/templates/new-worker.ts +33 -0
  30. package/templates/no-op-worker.js +10 -0
  31. package/templates/pages-dev-pipeline.ts +31 -0
  32. package/templates/pages-dev-util.ts +55 -0
  33. package/templates/pages-shim.ts +9 -0
  34. package/templates/pages-template-plugin.ts +190 -0
  35. package/templates/pages-template-worker.ts +198 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +8 -0
  39. package/wrangler-dist/cli.d.ts +1732 -0
  40. package/wrangler-dist/cli.js +141470 -110893
  41. package/wrangler-dist/wasm-sync.wasm +0 -0
  42. package/import_meta_url.js +0 -3
  43. package/miniflare-config-stubs/.env.empty +0 -0
  44. package/miniflare-config-stubs/package.empty.json +0 -1
  45. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  46. package/pages/functions/buildWorker.ts +0 -62
  47. package/pages/functions/filepath-routing.test.ts +0 -39
  48. package/pages/functions/filepath-routing.ts +0 -228
  49. package/pages/functions/identifiers.ts +0 -78
  50. package/pages/functions/routes.ts +0 -158
  51. package/pages/functions/template-worker.ts +0 -136
  52. package/src/__tests__/clipboardy-mock.js +0 -4
  53. package/src/__tests__/dev.test.tsx +0 -67
  54. package/src/__tests__/index.test.ts +0 -287
  55. package/src/__tests__/jest.setup.ts +0 -22
  56. package/src/__tests__/kv.test.ts +0 -1126
  57. package/src/__tests__/mock-cfetch.ts +0 -171
  58. package/src/__tests__/mock-dialogs.ts +0 -65
  59. package/src/__tests__/publish.test.ts +0 -102
  60. package/src/__tests__/run-in-tmp.ts +0 -19
  61. package/src/__tests__/run-wrangler.ts +0 -32
  62. package/src/api/form_data.ts +0 -131
  63. package/src/api/preview.ts +0 -128
  64. package/src/api/worker.ts +0 -155
  65. package/src/cfetch/index.ts +0 -102
  66. package/src/cfetch/internal.ts +0 -69
  67. package/src/cli.ts +0 -9
  68. package/src/config.ts +0 -646
  69. package/src/dev.tsx +0 -784
  70. package/src/dialogs.tsx +0 -77
  71. package/src/index.tsx +0 -1928
  72. package/src/inspect.ts +0 -543
  73. package/src/kv.tsx +0 -276
  74. package/src/module-collection.ts +0 -64
  75. package/src/pages.tsx +0 -1040
  76. package/src/proxy.ts +0 -302
  77. package/src/publish.ts +0 -382
  78. package/src/sites.tsx +0 -118
  79. package/src/tail.tsx +0 -73
  80. package/src/user.tsx +0 -1027
  81. package/static-asset-facade.js +0 -47
  82. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  83. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  84. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  85. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  86. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  87. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  88. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  89. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  90. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  91. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  92. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  93. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  94. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  95. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  96. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  97. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  98. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  99. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  100. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  101. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  102. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  103. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  104. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  105. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  106. package/vendor/wrangler-mime/LICENSE +0 -21
  107. package/vendor/wrangler-mime/Mime.js +0 -97
  108. package/vendor/wrangler-mime/README.md +0 -187
  109. package/vendor/wrangler-mime/cli.js +0 -46
  110. package/vendor/wrangler-mime/index.js +0 -4
  111. package/vendor/wrangler-mime/lite.js +0 -4
  112. package/vendor/wrangler-mime/package.json +0 -52
  113. package/vendor/wrangler-mime/types/other.js +0 -1
  114. package/vendor/wrangler-mime/types/standard.js +0 -1
  115. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,228 @@
1
+ import {
2
+ Awaitable,
3
+ Dispatcher,
4
+ IncomingRequest,
5
+ Middleware,
6
+ __facade_invoke__,
7
+ __facade_register__,
8
+ __facade_registerInternal__,
9
+ } from "./common";
10
+ export { __facade_register__, __facade_registerInternal__ };
11
+
12
+ // Miniflare 2's `EventTarget` follows the spec and doesn't allow exceptions to
13
+ // be caught by `dispatchEvent`. Instead it has a custom `ThrowingEventTarget`
14
+ // class that rethrows errors from event listeners in `dispatchEvent`.
15
+ // We'd like errors to be propagated to the top-level `addEventListener`, so
16
+ // we'd like to use `ThrowingEventTarget`. Unfortunately, `ThrowingEventTarget`
17
+ // isn't exposed on the global scope, but `WorkerGlobalScope` (which extends
18
+ // `ThrowingEventTarget`) is. Therefore, we get at it in this nasty way.
19
+ let __FACADE_EVENT_TARGET__: EventTarget;
20
+ if ((globalThis as any).MINIFLARE) {
21
+ __FACADE_EVENT_TARGET__ = new (Object.getPrototypeOf(WorkerGlobalScope))();
22
+ } else {
23
+ __FACADE_EVENT_TARGET__ = new EventTarget();
24
+ }
25
+
26
+ function __facade_isSpecialEvent__(
27
+ type: string
28
+ ): type is "fetch" | "scheduled" {
29
+ return type === "fetch" || type === "scheduled";
30
+ }
31
+ const __facade__originalAddEventListener__ = globalThis.addEventListener;
32
+ const __facade__originalRemoveEventListener__ = globalThis.removeEventListener;
33
+ const __facade__originalDispatchEvent__ = globalThis.dispatchEvent;
34
+
35
+ globalThis.addEventListener = function (type, listener, options) {
36
+ if (__facade_isSpecialEvent__(type)) {
37
+ __FACADE_EVENT_TARGET__.addEventListener(
38
+ type,
39
+ listener as EventListenerOrEventListenerObject,
40
+ options
41
+ );
42
+ } else {
43
+ __facade__originalAddEventListener__(type, listener, options);
44
+ }
45
+ };
46
+ globalThis.removeEventListener = function (type, listener, options) {
47
+ if (__facade_isSpecialEvent__(type)) {
48
+ __FACADE_EVENT_TARGET__.removeEventListener(
49
+ type,
50
+ listener as EventListenerOrEventListenerObject,
51
+ options
52
+ );
53
+ } else {
54
+ __facade__originalRemoveEventListener__(type, listener, options);
55
+ }
56
+ };
57
+ globalThis.dispatchEvent = function (event) {
58
+ if (__facade_isSpecialEvent__(event.type)) {
59
+ return __FACADE_EVENT_TARGET__.dispatchEvent(event);
60
+ } else {
61
+ return __facade__originalDispatchEvent__(event);
62
+ }
63
+ };
64
+
65
+ declare global {
66
+ var addMiddleware: typeof __facade_register__;
67
+ var addMiddlewareInternal: typeof __facade_registerInternal__;
68
+ }
69
+ globalThis.addMiddleware = __facade_register__;
70
+ globalThis.addMiddlewareInternal = __facade_registerInternal__;
71
+
72
+ const __facade_waitUntil__ = Symbol("__facade_waitUntil__");
73
+ const __facade_response__ = Symbol("__facade_response__");
74
+ const __facade_dispatched__ = Symbol("__facade_dispatched__");
75
+
76
+ class __Facade_ExtendableEvent__ extends Event {
77
+ [__facade_waitUntil__]: Awaitable<unknown>[] = [];
78
+
79
+ waitUntil(promise: Awaitable<any>) {
80
+ if (!(this instanceof __Facade_ExtendableEvent__)) {
81
+ throw new TypeError("Illegal invocation");
82
+ }
83
+ this[__facade_waitUntil__].push(promise);
84
+ }
85
+ }
86
+
87
+ interface FetchEventInit extends EventInit {
88
+ request: Request;
89
+ passThroughOnException: FetchEvent["passThroughOnException"];
90
+ }
91
+
92
+ class __Facade_FetchEvent__ extends __Facade_ExtendableEvent__ {
93
+ #request: Request;
94
+ #passThroughOnException: FetchEvent["passThroughOnException"];
95
+ [__facade_response__]?: Awaitable<Response>;
96
+ [__facade_dispatched__] = false;
97
+
98
+ constructor(type: "fetch", init: FetchEventInit) {
99
+ super(type);
100
+ this.#request = init.request;
101
+ this.#passThroughOnException = init.passThroughOnException;
102
+ }
103
+
104
+ get request() {
105
+ return this.#request;
106
+ }
107
+
108
+ respondWith(response: Awaitable<Response>) {
109
+ if (!(this instanceof __Facade_FetchEvent__)) {
110
+ throw new TypeError("Illegal invocation");
111
+ }
112
+ if (this[__facade_response__] !== undefined) {
113
+ throw new DOMException(
114
+ "FetchEvent.respondWith() has already been called; it can only be called once.",
115
+ "InvalidStateError"
116
+ );
117
+ }
118
+ if (this[__facade_dispatched__]) {
119
+ throw new DOMException(
120
+ "Too late to call FetchEvent.respondWith(). It must be called synchronously in the event handler.",
121
+ "InvalidStateError"
122
+ );
123
+ }
124
+ this.stopImmediatePropagation();
125
+ this[__facade_response__] = response;
126
+ }
127
+
128
+ passThroughOnException() {
129
+ if (!(this instanceof __Facade_FetchEvent__)) {
130
+ throw new TypeError("Illegal invocation");
131
+ }
132
+ // Need to call native method immediately in case uncaught error thrown
133
+ this.#passThroughOnException();
134
+ }
135
+ }
136
+
137
+ interface ScheduledEventInit extends EventInit {
138
+ scheduledTime: number;
139
+ cron: string;
140
+ noRetry: ScheduledEvent["noRetry"];
141
+ }
142
+
143
+ class __Facade_ScheduledEvent__ extends __Facade_ExtendableEvent__ {
144
+ #scheduledTime: number;
145
+ #cron: string;
146
+ #noRetry: ScheduledEvent["noRetry"];
147
+
148
+ constructor(type: "scheduled", init: ScheduledEventInit) {
149
+ super(type);
150
+ this.#scheduledTime = init.scheduledTime;
151
+ this.#cron = init.cron;
152
+ this.#noRetry = init.noRetry;
153
+ }
154
+
155
+ get scheduledTime() {
156
+ return this.#scheduledTime;
157
+ }
158
+
159
+ get cron() {
160
+ return this.#cron;
161
+ }
162
+
163
+ noRetry() {
164
+ if (!(this instanceof __Facade_ScheduledEvent__)) {
165
+ throw new TypeError("Illegal invocation");
166
+ }
167
+ // Need to call native method immediately in case uncaught error thrown
168
+ this.#noRetry();
169
+ }
170
+ }
171
+
172
+ __facade__originalAddEventListener__("fetch", (event) => {
173
+ const ctx: ExecutionContext = {
174
+ waitUntil: event.waitUntil.bind(event),
175
+ passThroughOnException: event.passThroughOnException.bind(event),
176
+ };
177
+
178
+ const __facade_sw_dispatch__: Dispatcher = function (type, init) {
179
+ if (type === "scheduled") {
180
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
181
+ scheduledTime: Date.now(),
182
+ cron: init.cron ?? "",
183
+ noRetry() {},
184
+ });
185
+
186
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
187
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
188
+ }
189
+ };
190
+
191
+ const __facade_sw_fetch__: Middleware = function (request, _env, ctx) {
192
+ const facadeEvent = new __Facade_FetchEvent__("fetch", {
193
+ request,
194
+ passThroughOnException: ctx.passThroughOnException,
195
+ });
196
+
197
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
198
+ facadeEvent[__facade_dispatched__] = true;
199
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
200
+
201
+ const response = facadeEvent[__facade_response__];
202
+ if (response === undefined) {
203
+ throw new Error("No response!"); // TODO: proper error message
204
+ }
205
+ return response;
206
+ };
207
+
208
+ event.respondWith(
209
+ __facade_invoke__(
210
+ event.request as IncomingRequest,
211
+ globalThis,
212
+ ctx,
213
+ __facade_sw_dispatch__,
214
+ __facade_sw_fetch__
215
+ )
216
+ );
217
+ });
218
+
219
+ __facade__originalAddEventListener__("scheduled", (event) => {
220
+ const facadeEvent = new __Facade_ScheduledEvent__("scheduled", {
221
+ scheduledTime: event.scheduledTime,
222
+ cron: event.cron,
223
+ noRetry: event.noRetry.bind(event),
224
+ });
225
+
226
+ __FACADE_EVENT_TARGET__.dispatchEvent(facadeEvent);
227
+ event.waitUntil(Promise.all(facadeEvent[__facade_waitUntil__]));
228
+ });
@@ -0,0 +1,3 @@
1
+ declare module "config:middleware/d1-beta" {
2
+ export const D1_IMPORTS: string[];
3
+ }
@@ -0,0 +1,33 @@
1
+ import type { Middleware } from "./common";
2
+
3
+ interface JsonError {
4
+ message?: string;
5
+ name?: string;
6
+ stack?: string;
7
+ cause?: JsonError;
8
+ }
9
+
10
+ function reduceError(e: any): JsonError {
11
+ return {
12
+ name: e?.name,
13
+ message: e?.message ?? String(e),
14
+ stack: e?.stack,
15
+ cause: e?.cause === undefined ? undefined : reduceError(e.cause),
16
+ };
17
+ }
18
+
19
+ // See comment in `bundle.ts` for details on why this is needed
20
+ const jsonError: Middleware = async (request, env, _ctx, middlewareCtx) => {
21
+ try {
22
+ return await middlewareCtx.next(request, env);
23
+ } catch (e: any) {
24
+ const error = reduceError(e);
25
+ return Response.json(error, {
26
+ status: 500,
27
+ headers: { "MF-Experimental-Error-Stack": "true" },
28
+ });
29
+ }
30
+ };
31
+
32
+ export default jsonError;
33
+ export const wrap = undefined;
@@ -0,0 +1,4 @@
1
+ declare module "config:middleware/multiworker-dev" {
2
+ import type { WorkerRegistry } from "../../src/dev-registry";
3
+ export const workers: WorkerRegistry;
4
+ }
@@ -0,0 +1,59 @@
1
+ // @ts-nocheck
2
+ /// <reference path="middleware-multiworker-dev.d.ts"/>
3
+
4
+ import { workers } from "config:middleware/multiworker-dev";
5
+ import type { WorkerRegistry } from "../../src/dev-registry";
6
+
7
+ export function wrap(env: Record<string, unknown>) {
8
+ const facadeEnv = { ...env };
9
+ // For every Worker definition that's available,
10
+ // create a fetcher for it on the facade env.
11
+ // for const [name, binding] of env
12
+ // if Workers[name]
13
+ // const details = Workers[name];
14
+
15
+ for (const [name, details] of Object.entries(workers as WorkerRegistry)) {
16
+ if (details) {
17
+ facadeEnv[name] = {
18
+ async fetch(...reqArgs: Parameters<Fetcher["fetch"]>) {
19
+ const reqFromArgs = new Request(...reqArgs);
20
+ if (details.headers) {
21
+ for (const [key, value] of Object.entries(details.headers)) {
22
+ // In remote mode, you need to add a couple of headers
23
+ // to make sure it's talking to the 'dev' preview session
24
+ // (much like wrangler dev already does via proxy.ts)
25
+ reqFromArgs.headers.set(key, value);
26
+ }
27
+ return (env[name] as Fetcher).fetch(reqFromArgs);
28
+ }
29
+
30
+ const url = new URL(reqFromArgs.url);
31
+ if (details.protocol !== undefined) {
32
+ url.protocol = details.protocol;
33
+ }
34
+ if (details.host !== undefined) {
35
+ url.host = details.host;
36
+ }
37
+ if (details.port !== undefined) {
38
+ url.port = details.port.toString();
39
+ }
40
+
41
+ const request = new Request(url.toString(), reqFromArgs);
42
+ return fetch(request);
43
+ },
44
+ };
45
+ } else {
46
+ // This means there's no dev binding available.
47
+ // Let's use whatever's available, or put a shim with a message.
48
+ facadeEnv[name] = facadeEnv[name] || {
49
+ async fetch() {
50
+ return new Response(
51
+ `You should start up wrangler dev --local on the ${name} worker`,
52
+ { status: 404 }
53
+ );
54
+ },
55
+ };
56
+ }
57
+ }
58
+ return facadeEnv;
59
+ }
@@ -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,6 @@
1
+ declare module "config:middleware/serve-static-assets" {
2
+ import type { CacheControl } from "@cloudflare/kv-asset-handler";
3
+
4
+ export const spaMode: boolean;
5
+ export const cacheControl: Partial<CacheControl>;
6
+ }
@@ -0,0 +1,56 @@
1
+ /// <reference path="middleware-serve-static-assets.d.ts"/>
2
+
3
+ import {
4
+ getAssetFromKV,
5
+ NotFoundError,
6
+ MethodNotAllowedError,
7
+ serveSinglePageApp,
8
+ } from "@cloudflare/kv-asset-handler";
9
+ import type { Options } from "@cloudflare/kv-asset-handler";
10
+ import { spaMode, cacheControl } from "config:middleware/serve-static-assets";
11
+ import type * as kvAssetHandler from "@cloudflare/kv-asset-handler";
12
+ import manifest from "__STATIC_CONTENT_MANIFEST";
13
+ const ASSET_MANIFEST = JSON.parse(manifest);
14
+
15
+ import type { Middleware } from "./common";
16
+
17
+ const staticAssets: Middleware = async (request, env, _ctx, middlewareCtx) => {
18
+ let options: Partial<Options> = {
19
+ ASSET_MANIFEST,
20
+ ASSET_NAMESPACE: env.__STATIC_CONTENT,
21
+ cacheControl: cacheControl,
22
+ mapRequestToAsset: spaMode ? serveSinglePageApp : undefined,
23
+ };
24
+
25
+ try {
26
+ const page = await (getAssetFromKV as typeof kvAssetHandler.getAssetFromKV)(
27
+ {
28
+ request,
29
+ waitUntil(promise) {
30
+ return _ctx.waitUntil(promise);
31
+ },
32
+ },
33
+ options
34
+ );
35
+
36
+ // allow headers to be altered
37
+ const response = new Response(page.body, page);
38
+
39
+ response.headers.set("X-XSS-Protection", "1; mode=block");
40
+ response.headers.set("X-Content-Type-Options", "nosniff");
41
+ response.headers.set("X-Frame-Options", "DENY");
42
+ response.headers.set("Referrer-Policy", "unsafe-url");
43
+ response.headers.set("Feature-Policy", "none");
44
+
45
+ return response;
46
+ } catch (e) {
47
+ if (e instanceof NotFoundError || e instanceof MethodNotAllowedError) {
48
+ // if a known error is thrown then serve from actual worker
49
+ return await middlewareCtx.next(request, env);
50
+ }
51
+ // otherwise it's a real error, so throw it
52
+ throw e;
53
+ }
54
+ };
55
+
56
+ export default staticAssets;
@@ -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 deploy --name my-worker` to deploy 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
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first worker.
3
+ *
4
+ * - Run `npx wrangler dev src/index.js` in your terminal to start a development server
5
+ * - Open a browser tab at http://localhost:8787/ to see your worker in action
6
+ * - Run `npx wrangler publish src/index.js --name my-worker` to publish your worker
7
+ *
8
+ * Learn more at https://developers.cloudflare.com/workers/
9
+ */
10
+
11
+ export default {
12
+ async fetch(request, env, ctx) {
13
+ return new Response("Hello World!");
14
+ },
15
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Welcome to Cloudflare Workers! This is your first worker.
3
+ *
4
+ * - Run `wrangler dev src/index.ts` in your terminal to start a development server
5
+ * - Open a browser tab at http://localhost:8787/ to see your worker in action
6
+ * - Run `wrangler deploy src/index.ts --name my-worker` to deploy your worker
7
+ *
8
+ * Learn more at https://developers.cloudflare.com/workers/
9
+ */
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
+ // Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/
22
+ // MY_SERVICE: Fetcher;
23
+ }
24
+
25
+ export default {
26
+ async fetch(
27
+ request: Request,
28
+ env: Env,
29
+ ctx: ExecutionContext
30
+ ): Promise<Response> {
31
+ return new Response("Hello World!");
32
+ },
33
+ };
@@ -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,31 @@
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
+ import { isRoutingRuleMatch } from "./pages-dev-util";
6
+
7
+ // @ts-ignore routes are injected
8
+ const routes = __ROUTES__;
9
+
10
+ export default <ExportedHandler<{ ASSETS: Fetcher }>>{
11
+ fetch(request, env, context) {
12
+ const { pathname } = new URL(request.url);
13
+
14
+ for (const exclude of routes.exclude) {
15
+ if (isRoutingRuleMatch(pathname, exclude)) {
16
+ return env.ASSETS.fetch(request);
17
+ }
18
+ }
19
+
20
+ for (const include of routes.include) {
21
+ if (isRoutingRuleMatch(pathname, include)) {
22
+ if (worker.fetch === undefined) {
23
+ throw new TypeError("Entry point missing `fetch` handler");
24
+ }
25
+ return worker.fetch(request, env, context);
26
+ }
27
+ }
28
+
29
+ return env.ASSETS.fetch(request);
30
+ },
31
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @param pathname A pathname string, such as `/foo` or `/foo/bar`
3
+ * @param routingRule The routing rule, such as `/foo/*`
4
+ * @returns True if pathname matches the routing rule
5
+ *
6
+ * / -> /
7
+ * /* -> /*
8
+ * /foo -> /foo
9
+ * /foo* -> /foo, /foo-bar, /foo/*
10
+ * /foo/* -> /foo, /foo/bar
11
+ */
12
+ export function isRoutingRuleMatch(
13
+ pathname: string,
14
+ routingRule: string
15
+ ): boolean {
16
+ // sanity checks
17
+ if (!pathname) {
18
+ throw new Error("Pathname is undefined.");
19
+ }
20
+ if (!routingRule) {
21
+ throw new Error("Routing rule is undefined.");
22
+ }
23
+
24
+ const ruleRegExp = transformRoutingRuleToRegExp(routingRule);
25
+ return pathname.match(ruleRegExp) !== null;
26
+ }
27
+
28
+ function transformRoutingRuleToRegExp(rule: string): RegExp {
29
+ let transformedRule;
30
+
31
+ if (rule === "/" || rule === "/*") {
32
+ transformedRule = rule;
33
+ } else if (rule.endsWith("/*")) {
34
+ // make `/*` an optional group so we can match both /foo/* and /foo
35
+ // /foo/* => /foo(/*)?
36
+ transformedRule = `${rule.substring(0, rule.length - 2)}(/*)?`;
37
+ } else if (rule.endsWith("/")) {
38
+ // make `/` an optional group so we can match both /foo/ and /foo
39
+ // /foo/ => /foo(/)?
40
+ transformedRule = `${rule.substring(0, rule.length - 1)}(/)?`;
41
+ } else if (rule.endsWith("*")) {
42
+ transformedRule = rule;
43
+ } else {
44
+ transformedRule = `${rule}(/)?`;
45
+ }
46
+
47
+ // /foo* => /foo.* => ^/foo.*$
48
+ // /*.* => /*\.* => /.*\..* => ^/.*\..*$
49
+ transformedRule = `^${transformedRule
50
+ .replaceAll(/\./g, "\\.")
51
+ .replaceAll(/\*/g, ".*")}$`;
52
+
53
+ // ^/foo.*$ => /^\/foo.*$/
54
+ return new RegExp(transformedRule);
55
+ }
@@ -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 <ExportedHandler<{ ASSETS: Fetcher }>>{
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
+ };