wrangler 0.0.0-bfbb0be → 0.0.0-bfbe49d0

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 (161) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +99 -114
  3. package/package.json +194 -155
  4. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  5. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  6. package/templates/__tests__/tsconfig.json +8 -0
  7. package/templates/checked-fetch.js +30 -0
  8. package/templates/facade.d.ts +17 -0
  9. package/templates/gitignore +1 -0
  10. package/templates/init-tests/test-jest-new-worker.js +23 -0
  11. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  12. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  13. package/templates/middleware/common.ts +67 -0
  14. package/templates/middleware/loader-modules.ts +137 -0
  15. package/templates/middleware/loader-sw.ts +228 -0
  16. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  17. package/templates/middleware/middleware-d1-beta.ts +244 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  20. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  21. package/templates/middleware/middleware-pretty-error.ts +40 -0
  22. package/templates/middleware/middleware-scheduled.ts +15 -0
  23. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  24. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +8 -8
  30. package/templates/pages-dev-pipeline.ts +31 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +159 -124
  34. package/templates/pages-template-worker.ts +161 -124
  35. package/templates/tsconfig-sanity.ts +11 -0
  36. package/templates/tsconfig.init.json +105 -0
  37. package/templates/tsconfig.json +6 -103
  38. package/wrangler-dist/cli.d.ts +1732 -0
  39. package/wrangler-dist/cli.js +112895 -89619
  40. package/wrangler-dist/wasm-sync.wasm +0 -0
  41. package/import_meta_url.js +0 -3
  42. package/miniflare-config-stubs/.env.empty +0 -0
  43. package/miniflare-config-stubs/package.empty.json +0 -1
  44. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  45. package/miniflare-dist/index.mjs +0 -4886
  46. package/src/__tests__/config-cache.test.ts +0 -36
  47. package/src/__tests__/configuration.test.ts +0 -3548
  48. package/src/__tests__/dev.test.tsx +0 -1055
  49. package/src/__tests__/guess-worker-format.test.ts +0 -85
  50. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  51. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  52. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  53. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  54. package/src/__tests__/helpers/mock-bin.ts +0 -36
  55. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  56. package/src/__tests__/helpers/mock-console.ts +0 -97
  57. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  58. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  59. package/src/__tests__/helpers/mock-istty.ts +0 -32
  60. package/src/__tests__/helpers/mock-kv.ts +0 -33
  61. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  62. package/src/__tests__/helpers/mock-process.ts +0 -39
  63. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  64. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  65. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  66. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  67. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  68. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  69. package/src/__tests__/https-options.test.ts +0 -130
  70. package/src/__tests__/index.test.ts +0 -258
  71. package/src/__tests__/init.test.ts +0 -1992
  72. package/src/__tests__/jest.setup.ts +0 -107
  73. package/src/__tests__/kv.test.ts +0 -1619
  74. package/src/__tests__/logger.test.ts +0 -141
  75. package/src/__tests__/package-manager.test.ts +0 -353
  76. package/src/__tests__/pages.test.ts +0 -1242
  77. package/src/__tests__/parse.test.ts +0 -330
  78. package/src/__tests__/publish.test.ts +0 -6188
  79. package/src/__tests__/r2.test.ts +0 -233
  80. package/src/__tests__/route.test.ts +0 -45
  81. package/src/__tests__/secret.test.ts +0 -486
  82. package/src/__tests__/tail.test.ts +0 -690
  83. package/src/__tests__/user.test.ts +0 -132
  84. package/src/__tests__/whoami.test.tsx +0 -139
  85. package/src/abort.d.ts +0 -3
  86. package/src/bundle-reporter.tsx +0 -29
  87. package/src/bundle.ts +0 -204
  88. package/src/cfetch/index.ts +0 -121
  89. package/src/cfetch/internal.ts +0 -142
  90. package/src/cli.ts +0 -13
  91. package/src/config/README.md +0 -107
  92. package/src/config/config.ts +0 -243
  93. package/src/config/diagnostics.ts +0 -80
  94. package/src/config/environment.ts +0 -420
  95. package/src/config/index.ts +0 -225
  96. package/src/config/validation-helpers.ts +0 -584
  97. package/src/config/validation.ts +0 -1580
  98. package/src/config-cache.ts +0 -44
  99. package/src/create-worker-preview.ts +0 -185
  100. package/src/create-worker-upload-form.ts +0 -254
  101. package/src/dev/dev-vars.ts +0 -36
  102. package/src/dev/dev.tsx +0 -399
  103. package/src/dev/local.tsx +0 -321
  104. package/src/dev/remote.tsx +0 -282
  105. package/src/dev/use-esbuild.ts +0 -112
  106. package/src/dialogs.tsx +0 -135
  107. package/src/durable.ts +0 -102
  108. package/src/entry.ts +0 -328
  109. package/src/environment-variables.ts +0 -35
  110. package/src/errors.ts +0 -11
  111. package/src/git-client.ts +0 -42
  112. package/src/https-options.ts +0 -123
  113. package/src/index.tsx +0 -2908
  114. package/src/inspect.ts +0 -662
  115. package/src/intl-polyfill.d.ts +0 -139
  116. package/src/kv.ts +0 -408
  117. package/src/logger.ts +0 -73
  118. package/src/miniflare-cli/README.md +0 -30
  119. package/src/miniflare-cli/enum-keys.ts +0 -17
  120. package/src/miniflare-cli/index.ts +0 -41
  121. package/src/miniflare-cli/request-context.ts +0 -40
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -17
  124. package/src/package-manager.ts +0 -174
  125. package/src/pages/build.tsx +0 -202
  126. package/src/pages/constants.ts +0 -7
  127. package/src/pages/deployments.tsx +0 -101
  128. package/src/pages/dev.tsx +0 -948
  129. package/src/pages/functions/buildPlugin.ts +0 -105
  130. package/src/pages/functions/buildWorker.ts +0 -151
  131. package/src/pages/functions/filepath-routing.test.ts +0 -234
  132. package/src/pages/functions/filepath-routing.ts +0 -189
  133. package/src/pages/functions/identifiers.ts +0 -78
  134. package/src/pages/functions/routes.ts +0 -151
  135. package/src/pages/index.tsx +0 -84
  136. package/src/pages/projects.tsx +0 -157
  137. package/src/pages/publish.tsx +0 -325
  138. package/src/pages/types.ts +0 -40
  139. package/src/pages/upload.tsx +0 -363
  140. package/src/pages/utils.ts +0 -12
  141. package/src/parse.ts +0 -222
  142. package/src/paths.ts +0 -26
  143. package/src/proxy.ts +0 -476
  144. package/src/publish.ts +0 -739
  145. package/src/r2.ts +0 -50
  146. package/src/selfsigned.d.ts +0 -29
  147. package/src/sites.tsx +0 -372
  148. package/src/tail/filters.ts +0 -279
  149. package/src/tail/index.ts +0 -299
  150. package/src/tail/printing.ts +0 -67
  151. package/src/update-check.ts +0 -19
  152. package/src/user/choose-account.tsx +0 -60
  153. package/src/user/env-vars.ts +0 -17
  154. package/src/user/generate-auth-url.ts +0 -33
  155. package/src/user/generate-random-state.ts +0 -16
  156. package/src/user/index.ts +0 -3
  157. package/src/user/user.tsx +0 -1133
  158. package/src/whoami.tsx +0 -71
  159. package/src/worker.ts +0 -181
  160. package/src/zones.ts +0 -73
  161. package/templates/static-asset-facade.js +0 -43
@@ -1,155 +1,190 @@
1
1
  import { match } from "path-to-regexp";
2
2
 
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
3
6
  type HTTPMethod =
4
- | "HEAD"
5
- | "OPTIONS"
6
- | "GET"
7
- | "POST"
8
- | "PUT"
9
- | "PATCH"
10
- | "DELETE";
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
11
14
 
12
15
  /* TODO: Grab these from @cloudflare/workers-types instead */
13
16
  type Params<P extends string = string> = Record<P, string | string[]>;
14
17
 
15
18
  type EventContext<Env, P extends string, Data> = {
16
- request: Request;
17
- functionPath: string;
18
- waitUntil: (promise: Promise<unknown>) => void;
19
- next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
20
- env: Env & { ASSETS: { fetch: typeof fetch } };
21
- params: Params<P>;
22
- data: Data;
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ passThroughOnException: () => void;
23
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
24
+ env: Env & { ASSETS: { fetch: typeof fetch } };
25
+ params: Params<P>;
26
+ data: Data;
23
27
  };
24
28
 
25
29
  type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
26
- request: Request;
27
- functionPath: string;
28
- waitUntil: (promise: Promise<unknown>) => void;
29
- next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
30
- env: Env & { ASSETS: { fetch: typeof fetch } };
31
- params: Params<P>;
32
- data: Data;
33
- pluginArgs: PluginArgs;
30
+ request: Request;
31
+ functionPath: string;
32
+ waitUntil: (promise: Promise<unknown>) => void;
33
+ passThroughOnException: () => void;
34
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
35
+ env: Env & { ASSETS: { fetch: typeof fetch } };
36
+ params: Params<P>;
37
+ data: Data;
38
+ pluginArgs: PluginArgs;
34
39
  };
35
40
 
36
41
  declare type PagesFunction<
37
- Env = unknown,
38
- P extends string = string,
39
- Data extends Record<string, unknown> = Record<string, unknown>
42
+ Env = unknown,
43
+ P extends string = string,
44
+ Data extends Record<string, unknown> = Record<string, unknown>
40
45
  > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
41
46
 
42
47
  declare type PagesPluginFunction<
43
- Env = unknown,
44
- P extends string = string,
45
- Data extends Record<string, unknown> = Record<string, unknown>,
46
- PluginArgs = unknown
48
+ Env = unknown,
49
+ P extends string = string,
50
+ Data extends Record<string, unknown> = Record<string, unknown>,
51
+ PluginArgs = unknown
47
52
  > = (
48
- context: EventPluginContext<Env, P, Data, PluginArgs>
53
+ context: EventPluginContext<Env, P, Data, PluginArgs>
49
54
  ) => Response | Promise<Response>;
50
55
  /* end @cloudflare/workers-types */
51
56
 
52
57
  type RouteHandler = {
53
- routePath: string;
54
- mountPath: string;
55
- method?: HTTPMethod;
56
- modules: PagesFunction[];
57
- middlewares: PagesFunction[];
58
+ routePath: string;
59
+ mountPath: string;
60
+ method?: HTTPMethod;
61
+ modules: PagesFunction[];
62
+ middlewares: PagesFunction[];
58
63
  };
59
64
 
60
65
  // inject `routes` via ESBuild
61
66
  declare const routes: RouteHandler[];
62
67
 
63
68
  function* executeRequest(request: Request, relativePathname: string) {
64
- // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
65
- for (const route of [...routes].reverse()) {
66
- if (route.method && route.method !== request.method) {
67
- continue;
68
- }
69
-
70
- const routeMatcher = match(route.routePath, { end: false });
71
- const mountMatcher = match(route.mountPath, { end: false });
72
- const matchResult = routeMatcher(relativePathname);
73
- const mountMatchResult = mountMatcher(relativePathname);
74
- if (matchResult && mountMatchResult) {
75
- for (const handler of route.middlewares.flat()) {
76
- yield {
77
- handler,
78
- params: matchResult.params as Params,
79
- path: mountMatchResult.path,
80
- };
81
- }
82
- }
83
- }
84
-
85
- // Then look for the first exact route match and execute its "modules"
86
- for (const route of routes) {
87
- if (route.method && route.method !== request.method) {
88
- continue;
89
- }
90
-
91
- const routeMatcher = match(route.routePath, { end: true });
92
- const mountMatcher = match(route.mountPath, { end: false });
93
- const matchResult = routeMatcher(relativePathname);
94
- const mountMatchResult = mountMatcher(relativePathname);
95
- if (matchResult && mountMatchResult && route.modules.length) {
96
- for (const handler of route.modules.flat()) {
97
- yield {
98
- handler,
99
- params: matchResult.params as Params,
100
- path: matchResult.path,
101
- };
102
- }
103
- break;
104
- }
105
- }
69
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
70
+ for (const route of [...routes].reverse()) {
71
+ if (route.method && route.method !== request.method) {
72
+ continue;
73
+ }
74
+
75
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
76
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
77
+ end: false,
78
+ });
79
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
80
+ end: false,
81
+ });
82
+ const matchResult = routeMatcher(relativePathname);
83
+ const mountMatchResult = mountMatcher(relativePathname);
84
+ if (matchResult && mountMatchResult) {
85
+ for (const handler of route.middlewares.flat()) {
86
+ yield {
87
+ handler,
88
+ params: matchResult.params as Params,
89
+ path: mountMatchResult.path,
90
+ };
91
+ }
92
+ }
93
+ }
94
+
95
+ // Then look for the first exact route match and execute its "modules"
96
+ for (const route of routes) {
97
+ if (route.method && route.method !== request.method) {
98
+ continue;
99
+ }
100
+
101
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
102
+ end: true,
103
+ });
104
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
105
+ end: false,
106
+ });
107
+ const matchResult = routeMatcher(relativePathname);
108
+ const mountMatchResult = mountMatcher(relativePathname);
109
+ if (matchResult && mountMatchResult && route.modules.length) {
110
+ for (const handler of route.modules.flat()) {
111
+ yield {
112
+ handler,
113
+ params: matchResult.params as Params,
114
+ path: matchResult.path,
115
+ };
116
+ }
117
+ break;
118
+ }
119
+ }
106
120
  }
107
121
 
108
- export default function (pluginArgs) {
109
- const onRequest: PagesPluginFunction = async (workerContext) => {
110
- let { request } = workerContext;
111
- const { env, next, data } = workerContext;
112
-
113
- const url = new URL(request.url);
114
- const relativePathname = `/${
115
- url.pathname.split(workerContext.functionPath)[1] || ""
116
- }`.replace(/^\/\//, "/");
117
-
118
- const handlerIterator = executeRequest(request, relativePathname);
119
- const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
120
- if (input !== undefined) {
121
- request = new Request(input, init);
122
- }
123
-
124
- const result = handlerIterator.next();
125
- // Note we can't use `!result.done` because this doesn't narrow to the correct type
126
- if (result.done === false) {
127
- const { handler, params, path } = result.value;
128
- const context = {
129
- request,
130
- functionPath: workerContext.functionPath + path,
131
- next: pluginNext,
132
- params,
133
- data,
134
- pluginArgs,
135
- env,
136
- waitUntil: workerContext.waitUntil.bind(workerContext),
137
- };
138
-
139
- const response = await handler(context);
140
-
141
- // https://fetch.spec.whatwg.org/#null-body-status
142
- return new Response(
143
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
144
- { ...response, headers: new Headers(response.headers) }
145
- );
146
- } else {
147
- return next();
148
- }
149
- };
150
-
151
- return pluginNext();
152
- };
153
-
154
- return onRequest;
122
+ export default function (pluginArgs: unknown) {
123
+ const onRequest: PagesPluginFunction = async (workerContext) => {
124
+ let { request } = workerContext;
125
+ const { env, next } = workerContext;
126
+ let { data } = workerContext;
127
+
128
+ const url = new URL(request.url);
129
+ // TODO: Replace this with something actually legible.
130
+ const relativePathname = `/${
131
+ url.pathname.replace(workerContext.functionPath, "") || ""
132
+ }`.replace(/^\/\//, "/");
133
+
134
+ const handlerIterator = executeRequest(request, relativePathname);
135
+ const pluginNext = async (input?: RequestInfo, init?: RequestInit) => {
136
+ if (input !== undefined) {
137
+ let url = input;
138
+ if (typeof input === "string") {
139
+ url = new URL(input, request.url).toString();
140
+ }
141
+ request = new Request(url, init);
142
+ }
143
+
144
+ const result = handlerIterator.next();
145
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
146
+ if (result.done === false) {
147
+ const { handler, params, path } = result.value;
148
+ const context = {
149
+ request: new Request(request.clone()),
150
+ functionPath: workerContext.functionPath + path,
151
+ next: pluginNext,
152
+ params,
153
+ get data() {
154
+ return data;
155
+ },
156
+ set data(value) {
157
+ if (typeof value !== "object" || value === null) {
158
+ throw new Error("context.data must be an object");
159
+ }
160
+ // user has overriden context.data, so we need to merge it with the existing data
161
+ data = value;
162
+ },
163
+ pluginArgs,
164
+ env,
165
+ waitUntil: workerContext.waitUntil.bind(workerContext),
166
+ passThroughOnException:
167
+ workerContext.passThroughOnException.bind(workerContext),
168
+ };
169
+
170
+ const response = await handler(context);
171
+
172
+ return cloneResponse(response);
173
+ } else {
174
+ return next(request);
175
+ }
176
+ };
177
+
178
+ return pluginNext();
179
+ };
180
+
181
+ return onRequest;
155
182
  }
183
+
184
+ // This makes a Response mutable
185
+ const cloneResponse = (response: Response) =>
186
+ // https://fetch.spec.whatwg.org/#null-body-status
187
+ new Response(
188
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
189
+ response
190
+ );
@@ -1,40 +1,44 @@
1
1
  import { match } from "path-to-regexp";
2
2
 
3
+ //note: this explicitly does not include the * character, as pages requires this
4
+ const escapeRegex = /[.+?^${}()|[\]\\]/g;
5
+
3
6
  type HTTPMethod =
4
- | "HEAD"
5
- | "OPTIONS"
6
- | "GET"
7
- | "POST"
8
- | "PUT"
9
- | "PATCH"
10
- | "DELETE";
7
+ | "HEAD"
8
+ | "OPTIONS"
9
+ | "GET"
10
+ | "POST"
11
+ | "PUT"
12
+ | "PATCH"
13
+ | "DELETE";
11
14
 
12
15
  /* TODO: Grab these from @cloudflare/workers-types instead */
13
16
  type Params<P extends string = string> = Record<P, string | string[]>;
14
17
 
15
18
  type EventContext<Env, P extends string, Data> = {
16
- request: Request;
17
- functionPath: string;
18
- waitUntil: (promise: Promise<unknown>) => void;
19
- next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
20
- env: Env & { ASSETS: { fetch: typeof fetch } };
21
- params: Params<P>;
22
- data: Data;
19
+ request: Request;
20
+ functionPath: string;
21
+ waitUntil: (promise: Promise<unknown>) => void;
22
+ passThroughOnException: () => void;
23
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
24
+ env: Env & { ASSETS: { fetch: typeof fetch } };
25
+ params: Params<P>;
26
+ data: Data;
23
27
  };
24
28
 
25
29
  declare type PagesFunction<
26
- Env = unknown,
27
- P extends string = string,
28
- Data extends Record<string, unknown> = Record<string, unknown>
30
+ Env = unknown,
31
+ P extends string = string,
32
+ Data extends Record<string, unknown> = Record<string, unknown>
29
33
  > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
30
34
  /* end @cloudflare/workers-types */
31
35
 
32
36
  type RouteHandler = {
33
- routePath: string;
34
- mountPath: string;
35
- method?: HTTPMethod;
36
- modules: PagesFunction[];
37
- middlewares: PagesFunction[];
37
+ routePath: string;
38
+ mountPath: string;
39
+ method?: HTTPMethod;
40
+ modules: PagesFunction[];
41
+ middlewares: PagesFunction[];
38
42
  };
39
43
 
40
44
  // inject `routes` via ESBuild
@@ -44,118 +48,151 @@ declare const __FALLBACK_SERVICE__: string;
44
48
 
45
49
  // expect an ASSETS fetcher binding pointing to the asset-server stage
46
50
  type FetchEnv = {
47
- [name: string]: { fetch: typeof fetch };
48
- ASSETS: { fetch: typeof fetch };
51
+ [name: string]: { fetch: typeof fetch };
52
+ ASSETS: { fetch: typeof fetch };
49
53
  };
50
54
 
51
55
  type WorkerContext = {
52
- waitUntil: (promise: Promise<unknown>) => void;
56
+ waitUntil: (promise: Promise<unknown>) => void;
57
+ passThroughOnException: () => void;
53
58
  };
54
59
 
55
60
  function* executeRequest(request: Request) {
56
- const requestPath = new URL(request.url).pathname;
57
-
58
- // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
59
- for (const route of [...routes].reverse()) {
60
- if (route.method && route.method !== request.method) {
61
- continue;
62
- }
63
-
64
- const routeMatcher = match(route.routePath, { end: false });
65
- const mountMatcher = match(route.mountPath, { end: false });
66
- const matchResult = routeMatcher(requestPath);
67
- const mountMatchResult = mountMatcher(requestPath);
68
- if (matchResult && mountMatchResult) {
69
- for (const handler of route.middlewares.flat()) {
70
- yield {
71
- handler,
72
- params: matchResult.params as Params,
73
- path: mountMatchResult.path,
74
- };
75
- }
76
- }
77
- }
78
-
79
- // Then look for the first exact route match and execute its "modules"
80
- for (const route of routes) {
81
- if (route.method && route.method !== request.method) {
82
- continue;
83
- }
84
-
85
- const routeMatcher = match(route.routePath, { end: true });
86
- const mountMatcher = match(route.mountPath, { end: false });
87
- const matchResult = routeMatcher(requestPath);
88
- const mountMatchResult = mountMatcher(requestPath);
89
- if (matchResult && mountMatchResult && route.modules.length) {
90
- for (const handler of route.modules.flat()) {
91
- yield {
92
- handler,
93
- params: matchResult.params as Params,
94
- path: matchResult.path,
95
- };
96
- }
97
- break;
98
- }
99
- }
61
+ const requestPath = new URL(request.url).pathname;
62
+
63
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
64
+ for (const route of [...routes].reverse()) {
65
+ if (route.method && route.method !== request.method) {
66
+ continue;
67
+ }
68
+
69
+ // replaces with "\\$&", this prepends a backslash to the matched string, e.g. "[" becomes "\["
70
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
71
+ end: false,
72
+ });
73
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
74
+ end: false,
75
+ });
76
+ const matchResult = routeMatcher(requestPath);
77
+ const mountMatchResult = mountMatcher(requestPath);
78
+ if (matchResult && mountMatchResult) {
79
+ for (const handler of route.middlewares.flat()) {
80
+ yield {
81
+ handler,
82
+ params: matchResult.params as Params,
83
+ path: mountMatchResult.path,
84
+ };
85
+ }
86
+ }
87
+ }
88
+
89
+ // Then look for the first exact route match and execute its "modules"
90
+ for (const route of routes) {
91
+ if (route.method && route.method !== request.method) {
92
+ continue;
93
+ }
94
+ const routeMatcher = match(route.routePath.replace(escapeRegex, "\\$&"), {
95
+ end: true,
96
+ });
97
+ const mountMatcher = match(route.mountPath.replace(escapeRegex, "\\$&"), {
98
+ end: false,
99
+ });
100
+ const matchResult = routeMatcher(requestPath);
101
+ const mountMatchResult = mountMatcher(requestPath);
102
+ if (matchResult && mountMatchResult && route.modules.length) {
103
+ for (const handler of route.modules.flat()) {
104
+ yield {
105
+ handler,
106
+ params: matchResult.params as Params,
107
+ path: matchResult.path,
108
+ };
109
+ }
110
+ break;
111
+ }
112
+ }
100
113
  }
101
114
 
102
115
  export default {
103
- async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
104
- const handlerIterator = executeRequest(request);
105
- const data = {}; // arbitrary data the user can set between functions
106
- const next = async (input?: RequestInfo, init?: RequestInit) => {
107
- if (input !== undefined) {
108
- let url = input;
109
- if (typeof input === "string") {
110
- url = new URL(input, request.url).toString();
111
- }
112
- request = new Request(url, init);
113
- }
114
-
115
- const result = handlerIterator.next();
116
- // Note we can't use `!result.done` because this doesn't narrow to the correct type
117
- if (result.done === false) {
118
- const { handler, params, path } = result.value;
119
- const context = {
120
- request: new Request(request.clone()),
121
- functionPath: path,
122
- next,
123
- params,
124
- data,
125
- env,
126
- waitUntil: workerContext.waitUntil.bind(workerContext),
127
- };
128
-
129
- const response = await handler(context);
130
-
131
- if (!(response instanceof Response)) {
132
- throw new Error("Your Pages function should return a Response");
133
- }
134
-
135
- return cloneResponse(response);
136
- } else if (__FALLBACK_SERVICE__) {
137
- // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
138
- const response = await env[__FALLBACK_SERVICE__].fetch(request);
139
- return cloneResponse(response);
140
- } else {
141
- // There was not fallback service so actually make the request to the origin.
142
- const response = await fetch(request);
143
- return cloneResponse(response);
144
- }
145
- };
146
-
147
- try {
148
- return next();
149
- } catch (err) {
150
- return new Response("Internal Error", { status: 500 });
151
- }
152
- },
116
+ async fetch(
117
+ originalRequest: Request,
118
+ env: FetchEnv,
119
+ workerContext: WorkerContext
120
+ ) {
121
+ let request = originalRequest;
122
+ const handlerIterator = executeRequest(request);
123
+ let data = {}; // arbitrary data the user can set between functions
124
+ let isFailOpen = false;
125
+
126
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
127
+ if (input !== undefined) {
128
+ let url = input;
129
+ if (typeof input === "string") {
130
+ url = new URL(input, request.url).toString();
131
+ }
132
+ request = new Request(url, init);
133
+ }
134
+
135
+ const result = handlerIterator.next();
136
+ // Note we can't use `!result.done` because this doesn't narrow to the correct type
137
+ if (result.done === false) {
138
+ const { handler, params, path } = result.value;
139
+ const context = {
140
+ request: new Request(request.clone()),
141
+ functionPath: path,
142
+ next,
143
+ params,
144
+ get data() {
145
+ return data;
146
+ },
147
+ set data(value) {
148
+ if (typeof value !== "object" || value === null) {
149
+ throw new Error("context.data must be an object");
150
+ }
151
+ // user has overriden context.data, so we need to merge it with the existing data
152
+ data = value;
153
+ },
154
+ env,
155
+ waitUntil: workerContext.waitUntil.bind(workerContext),
156
+ passThroughOnException: () => {
157
+ isFailOpen = true;
158
+ },
159
+ };
160
+
161
+ const response = await handler(context);
162
+
163
+ if (!(response instanceof Response)) {
164
+ throw new Error("Your Pages function should return a Response");
165
+ }
166
+
167
+ return cloneResponse(response);
168
+ } else if (__FALLBACK_SERVICE__) {
169
+ // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
170
+ const response = await env[__FALLBACK_SERVICE__].fetch(request);
171
+ return cloneResponse(response);
172
+ } else {
173
+ // There was not fallback service so actually make the request to the origin.
174
+ const response = await fetch(request);
175
+ return cloneResponse(response);
176
+ }
177
+ };
178
+
179
+ try {
180
+ return await next();
181
+ } catch (error) {
182
+ if (isFailOpen) {
183
+ const response = await env[__FALLBACK_SERVICE__].fetch(request);
184
+ return cloneResponse(response);
185
+ }
186
+
187
+ throw error;
188
+ }
189
+ },
153
190
  };
154
191
 
155
192
  // This makes a Response mutable
156
193
  const cloneResponse = (response: Response) =>
157
- // https://fetch.spec.whatwg.org/#null-body-status
158
- new Response(
159
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
160
- response
161
- );
194
+ // https://fetch.spec.whatwg.org/#null-body-status
195
+ new Response(
196
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
197
+ response
198
+ );
@@ -0,0 +1,11 @@
1
+ // @ts-nocheck `@types/node` should NOT be included
2
+ Buffer.from("test");
3
+
4
+ // @ts-expect-error `@types/jest` should NOT be included
5
+ test("test");
6
+
7
+ // `@cloudflare/workers-types` should be included
8
+ const _handler: ExportedHandler = {};
9
+ new HTMLRewriter();
10
+
11
+ export {};