wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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 (209) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -127
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3950 -0
  10. package/src/__tests__/dev.test.tsx +1199 -67
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +36 -18
  14. package/src/__tests__/helpers/mock-bin.ts +36 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +118 -80
  16. package/src/__tests__/helpers/mock-console.ts +70 -29
  17. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  18. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  19. package/src/__tests__/helpers/mock-istty.ts +74 -0
  20. package/src/__tests__/helpers/mock-kv.ts +28 -35
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  22. package/src/__tests__/helpers/mock-process.ts +39 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  26. package/src/__tests__/helpers/run-wrangler.ts +8 -6
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +163 -0
  30. package/src/__tests__/index.test.ts +255 -399
  31. package/src/__tests__/init.test.ts +1992 -0
  32. package/src/__tests__/jest.setup.ts +102 -16
  33. package/src/__tests__/kv.test.ts +1400 -878
  34. package/src/__tests__/logger.test.ts +141 -0
  35. package/src/__tests__/metrics.test.ts +445 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1261 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6633 -1184
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +484 -202
  44. package/src/__tests__/tail.test.ts +698 -0
  45. package/src/__tests__/test-old-node-version.js +31 -0
  46. package/src/__tests__/user.test.ts +143 -0
  47. package/src/__tests__/version.test.ts +35 -0
  48. package/src/__tests__/whoami.test.tsx +219 -75
  49. package/src/__tests__/worker-namespace.test.ts +327 -0
  50. package/src/abort.d.ts +3 -0
  51. package/src/api/dev.ts +86 -0
  52. package/src/api/index.ts +1 -0
  53. package/src/bundle-reporter.tsx +29 -0
  54. package/src/bundle.ts +236 -0
  55. package/src/cfetch/index.ts +86 -76
  56. package/src/cfetch/internal.ts +122 -45
  57. package/src/cli.ts +24 -6
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +251 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +453 -0
  62. package/src/config/index.ts +238 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1754 -0
  65. package/src/config-cache.ts +84 -0
  66. package/src/create-worker-preview.ts +255 -0
  67. package/src/create-worker-upload-form.ts +263 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +452 -0
  70. package/src/dev/local.tsx +373 -0
  71. package/src/dev/remote.tsx +386 -0
  72. package/src/dev/use-esbuild.ts +150 -0
  73. package/src/dev.tsx +579 -820
  74. package/src/dialogs.tsx +115 -57
  75. package/src/durable.ts +102 -0
  76. package/src/entry.ts +328 -0
  77. package/src/environment-variables.ts +35 -0
  78. package/src/errors.ts +11 -0
  79. package/src/faye-websocket.d.ts +6 -0
  80. package/src/generate.ts +33 -0
  81. package/src/git-client.ts +42 -0
  82. package/src/global-wrangler-config-path.ts +26 -0
  83. package/src/https-options.ts +127 -0
  84. package/src/index.tsx +1969 -2024
  85. package/src/init.ts +549 -0
  86. package/src/inspect.ts +603 -537
  87. package/src/intl-polyfill.d.ts +139 -0
  88. package/src/is-interactive.ts +12 -0
  89. package/src/kv.ts +430 -0
  90. package/src/logger.ts +73 -0
  91. package/src/metrics/index.ts +4 -0
  92. package/src/metrics/is-ci.ts +14 -0
  93. package/src/metrics/metrics-config.ts +239 -0
  94. package/src/metrics/metrics-dispatcher.ts +95 -0
  95. package/src/metrics/send-event.ts +92 -0
  96. package/src/miniflare-cli/README.md +30 -0
  97. package/src/miniflare-cli/assets.ts +543 -0
  98. package/src/miniflare-cli/enum-keys.ts +17 -0
  99. package/src/miniflare-cli/index.ts +85 -0
  100. package/src/miniflare-cli/request-context.ts +40 -0
  101. package/src/module-collection.ts +244 -49
  102. package/src/open-in-browser.ts +17 -0
  103. package/src/package-manager.ts +219 -0
  104. package/src/pages/build.tsx +204 -0
  105. package/src/pages/constants.ts +7 -0
  106. package/src/pages/deployments.tsx +106 -0
  107. package/src/pages/dev.tsx +401 -0
  108. package/src/pages/functions/buildPlugin.ts +105 -0
  109. package/src/pages/functions/buildWorker.ts +151 -0
  110. package/src/pages/functions/filepath-routing.test.ts +234 -0
  111. package/src/pages/functions/filepath-routing.ts +189 -0
  112. package/src/pages/functions/identifiers.ts +78 -0
  113. package/src/pages/functions/routes.ts +151 -0
  114. package/src/pages/index.tsx +84 -0
  115. package/src/pages/projects.tsx +163 -0
  116. package/src/pages/publish.tsx +338 -0
  117. package/src/pages/types.ts +40 -0
  118. package/src/pages/upload.tsx +396 -0
  119. package/src/pages/utils.ts +12 -0
  120. package/src/parse.ts +286 -0
  121. package/src/paths.ts +6 -6
  122. package/src/preview.ts +31 -0
  123. package/src/proxy.ts +417 -311
  124. package/src/publish.ts +774 -391
  125. package/src/pubsub/index.ts +286 -0
  126. package/src/pubsub/pubsub-commands.tsx +623 -0
  127. package/src/r2.ts +50 -0
  128. package/src/selfsigned.d.ts +29 -0
  129. package/src/sites.tsx +291 -159
  130. package/src/tail/filters.ts +279 -0
  131. package/src/tail/index.ts +299 -0
  132. package/src/tail/printing.ts +67 -0
  133. package/src/update-check.ts +19 -0
  134. package/src/user/choose-account.tsx +69 -0
  135. package/src/user/env-vars.ts +46 -0
  136. package/src/user/generate-auth-url.ts +33 -0
  137. package/src/user/generate-random-state.ts +16 -0
  138. package/src/user/index.ts +3 -0
  139. package/src/user/user.tsx +1171 -0
  140. package/src/whoami.tsx +63 -41
  141. package/src/worker-namespace.ts +206 -0
  142. package/src/worker.ts +191 -0
  143. package/src/zones.ts +76 -0
  144. package/templates/checked-fetch.js +17 -0
  145. package/templates/gitignore +171 -0
  146. package/templates/new-worker-scheduled.js +17 -0
  147. package/templates/new-worker-scheduled.ts +32 -0
  148. package/templates/new-worker.js +15 -0
  149. package/templates/new-worker.ts +30 -0
  150. package/templates/no-op-worker.js +10 -0
  151. package/templates/pages-shim.ts +9 -0
  152. package/templates/pages-template-plugin.ts +155 -0
  153. package/templates/pages-template-worker.ts +161 -0
  154. package/templates/static-asset-facade.js +49 -0
  155. package/templates/tsconfig.json +105 -0
  156. package/wrangler-dist/cli.d.ts +327 -0
  157. package/wrangler-dist/cli.js +78107 -79324
  158. package/pages/functions/buildWorker.ts +0 -62
  159. package/pages/functions/filepath-routing.test.ts +0 -47
  160. package/pages/functions/filepath-routing.ts +0 -231
  161. package/pages/functions/identifiers.ts +0 -78
  162. package/pages/functions/routes.ts +0 -160
  163. package/pages/functions/template-worker.ts +0 -136
  164. package/src/__tests__/helpers/mock-user.ts +0 -27
  165. package/src/__tests__/logout.test.ts +0 -50
  166. package/src/api/form_data.ts +0 -134
  167. package/src/api/preview.ts +0 -128
  168. package/src/api/worker.ts +0 -155
  169. package/src/config.ts +0 -641
  170. package/src/kv.tsx +0 -276
  171. package/src/npm-installer.ts +0 -20
  172. package/src/pages.tsx +0 -1045
  173. package/src/tail.tsx +0 -73
  174. package/src/user.tsx +0 -1019
  175. package/static-asset-facade.js +0 -47
  176. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  177. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  178. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  179. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  180. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  181. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  182. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  183. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  184. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  185. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  186. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  190. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  191. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  192. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  193. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  194. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  195. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  196. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  197. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  198. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  199. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  200. package/vendor/wrangler-mime/LICENSE +0 -21
  201. package/vendor/wrangler-mime/Mime.js +0 -97
  202. package/vendor/wrangler-mime/README.md +0 -187
  203. package/vendor/wrangler-mime/cli.js +0 -46
  204. package/vendor/wrangler-mime/index.js +0 -4
  205. package/vendor/wrangler-mime/lite.js +0 -4
  206. package/vendor/wrangler-mime/package.json +0 -52
  207. package/vendor/wrangler-mime/types/other.js +0 -1
  208. package/vendor/wrangler-mime/types/standard.js +0 -1
  209. package/wrangler-dist/cli.js.map +0 -7
@@ -1,62 +0,0 @@
1
- import path from "node:path";
2
- import { build } from "esbuild";
3
-
4
- type Options = {
5
- routesModule: string;
6
- outfile: string;
7
- minify?: boolean;
8
- sourcemap?: boolean;
9
- fallbackService?: string;
10
- watch?: boolean;
11
- onEnd?: () => void;
12
- };
13
-
14
- export function buildWorker({
15
- routesModule,
16
- outfile = "bundle.js",
17
- minify = false,
18
- sourcemap = false,
19
- fallbackService = "ASSETS",
20
- watch = false,
21
- onEnd = () => {},
22
- }: Options) {
23
- return build({
24
- entryPoints: [
25
- path.resolve(__dirname, "../pages/functions/template-worker.ts"),
26
- ],
27
- inject: [routesModule],
28
- bundle: true,
29
- format: "esm",
30
- target: "esnext",
31
- outfile,
32
- minify,
33
- sourcemap,
34
- watch,
35
- allowOverwrite: true,
36
- define: {
37
- __FALLBACK_SERVICE__: JSON.stringify(fallbackService),
38
- },
39
- plugins: [
40
- {
41
- name: "wrangler notifier and monitor",
42
- setup(pluginBuild) {
43
- pluginBuild.onEnd((result) => {
44
- if (result.errors.length > 0) {
45
- console.error(
46
- `${result.errors.length} error(s) and ${result.warnings.length} warning(s) when compiling Worker.`
47
- );
48
- } else if (result.warnings.length > 0) {
49
- console.warn(
50
- `${result.warnings.length} warning(s) when compiling Worker.`
51
- );
52
- onEnd();
53
- } else {
54
- console.log("Compiled Worker successfully.");
55
- onEnd();
56
- }
57
- });
58
- },
59
- },
60
- ],
61
- });
62
- }
@@ -1,47 +0,0 @@
1
- import { toUrlPath } from "../../src/paths";
2
- import { compareRoutes } from "./filepath-routing";
3
-
4
- describe("compareRoutes()", () => {
5
- const url = toUrlPath;
6
- test("routes / last", () => {
7
- expect(compareRoutes([url("/")], [url("/foo")])).toBeGreaterThanOrEqual(1);
8
- expect(compareRoutes([url("/")], [url("/:foo")])).toBeGreaterThanOrEqual(1);
9
- expect(compareRoutes([url("/")], [url("/:foo*")])).toBeGreaterThanOrEqual(
10
- 1
11
- );
12
- });
13
-
14
- test("routes with fewer segments come after those with more segments", () => {
15
- expect(
16
- compareRoutes([url("/foo")], [url("/foo/bar")])
17
- ).toBeGreaterThanOrEqual(1);
18
- expect(
19
- compareRoutes([url("/foo")], [url("/foo/bar/cat")])
20
- ).toBeGreaterThanOrEqual(1);
21
- });
22
-
23
- test("routes with wildcard segments come after those without", () => {
24
- expect(compareRoutes([url("/:foo*")], [url("/foo")])).toBe(1);
25
- expect(compareRoutes([url("/:foo*")], [url("/:foo")])).toBe(1);
26
- });
27
-
28
- test("routes with dynamic segments come after those without", () => {
29
- expect(compareRoutes([url("/:foo")], [url("/foo")])).toBe(1);
30
- });
31
-
32
- test("routes with dynamic segments occurring earlier come after those with dynamic segments in later positions", () => {
33
- expect(compareRoutes([url("/foo/:id/bar")], [url("/foo/bar/:id")])).toBe(1);
34
- });
35
-
36
- test("routes with no HTTP method come after those specifying a method", () => {
37
- expect(compareRoutes([url("/foo")], [url("/foo"), "GET"])).toBe(1);
38
- });
39
-
40
- test("two equal routes are sorted according to their original position in the list", () => {
41
- expect(compareRoutes([url("/foo"), "GET"], [url("/foo"), "GET"])).toBe(0);
42
- });
43
-
44
- test("it returns -1 if the first argument should appear first in the list", () => {
45
- expect(compareRoutes([url("/foo"), "GET"], [url("/foo")])).toBe(-1);
46
- });
47
- });
@@ -1,231 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import * as acorn from "acorn";
4
- import * as acornWalk from "acorn-walk";
5
- import { transform } from "esbuild";
6
- import { toUrlPath } from "../../src/paths";
7
- import type { UrlPath } from "../../src/paths";
8
- import type { Config, RouteConfig } from "./routes";
9
- import type { ExportNamedDeclaration, Identifier } from "estree";
10
-
11
- type Arguments = {
12
- baseDir: string;
13
- baseURL: UrlPath;
14
- };
15
-
16
- type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS" | "HEAD";
17
- type RouteKey = [UrlPath, Method] | [UrlPath, undefined] | [UrlPath];
18
-
19
- export async function generateConfigFromFileTree({
20
- baseDir,
21
- baseURL,
22
- }: Arguments) {
23
- let routeEntries: [RouteKey, RouteConfig][] = [];
24
-
25
- if (!baseURL.startsWith("/")) {
26
- baseURL = `/${baseURL}` as UrlPath;
27
- }
28
-
29
- if (baseURL.endsWith("/")) {
30
- baseURL = baseURL.slice(0, -1) as UrlPath;
31
- }
32
-
33
- await forEachFile(baseDir, async (filepath) => {
34
- const ext = path.extname(filepath);
35
- if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
36
- // transform the code to ensure we're working with vanilla JS + ESM
37
- const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
38
- loader: ext === ".ts" ? "ts" : "js",
39
- });
40
-
41
- // parse each file into an AST and search for module exports that match "onRequest" and friends
42
- const ast = acorn.parse(code, {
43
- ecmaVersion: "latest",
44
- sourceType: "module",
45
- });
46
- acornWalk.simple(ast, {
47
- ExportNamedDeclaration(_node: unknown) {
48
- // This dynamic cast assumes that the AST generated by acornWalk will generate nodes that
49
- // are compatible with the eslint AST nodes.
50
- const node = _node as ExportNamedDeclaration;
51
-
52
- // this is an array because multiple things can be exported from a single statement
53
- // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
54
- const exportNames: string[] = [];
55
-
56
- if (node.declaration) {
57
- const declaration = node.declaration;
58
-
59
- // `export async function onRequest() {...}`
60
- if (declaration.type === "FunctionDeclaration" && declaration.id) {
61
- exportNames.push(declaration.id.name);
62
- }
63
-
64
- // `export const onRequestGet = () => {}, onRequestPost = () => {}`
65
- if (declaration.type === "VariableDeclaration") {
66
- exportNames.push(
67
- ...declaration.declarations.map(
68
- (variableDeclarator) =>
69
- (variableDeclarator.id as unknown as Identifier).name
70
- )
71
- );
72
- }
73
- }
74
-
75
- // `export {foo, bar}`
76
- if (node.specifiers.length) {
77
- exportNames.push(
78
- ...node.specifiers.map(
79
- (exportSpecifier) =>
80
- (exportSpecifier.exported as unknown as Identifier).name
81
- )
82
- );
83
- }
84
-
85
- for (const exportName of exportNames) {
86
- const [match, method] =
87
- exportName.match(
88
- /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
89
- ) ?? [];
90
-
91
- if (match) {
92
- const basename = path.basename(filepath).slice(0, -ext.length);
93
-
94
- const isIndexFile = basename === "index";
95
- // TODO: deprecate _middleware_ in favor of _middleware
96
- const isMiddlewareFile =
97
- basename === "_middleware" || basename === "_middleware_";
98
-
99
- let routePath = path
100
- .relative(baseDir, filepath)
101
- .slice(0, -ext.length);
102
-
103
- if (isIndexFile || isMiddlewareFile) {
104
- routePath = path.dirname(routePath);
105
- }
106
-
107
- if (routePath === ".") {
108
- routePath = "";
109
- }
110
-
111
- routePath = `${baseURL}/${routePath}`;
112
-
113
- routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
114
- routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
115
-
116
- const routeUrlPath = toUrlPath(routePath);
117
- const routeKey: RouteKey = [
118
- routeUrlPath,
119
- method ? (method.toUpperCase() as Method) : undefined,
120
- ];
121
-
122
- routeEntries.push([
123
- routeKey,
124
- {
125
- [isMiddlewareFile ? "middleware" : "module"]: [
126
- `${path.relative(baseDir, filepath)}:${exportName}`,
127
- ],
128
- },
129
- ]);
130
- }
131
- }
132
- },
133
- });
134
- }
135
- });
136
-
137
- // Combine together any routes (index routes) which contain both a module and a middleware
138
- routeEntries = routeEntries.reduce(
139
- (acc: typeof routeEntries, [routePath, routeHandler]) => {
140
- const existingRouteEntry = acc.find(
141
- (routeEntry) => routeEntry[0] === routePath
142
- );
143
- if (existingRouteEntry !== undefined) {
144
- existingRouteEntry[1] = {
145
- ...existingRouteEntry[1],
146
- ...routeHandler,
147
- };
148
- } else {
149
- acc.push([routePath, routeHandler]);
150
- }
151
- return acc;
152
- },
153
- []
154
- );
155
-
156
- routeEntries.sort(([a], [b]) => compareRoutes(a, b));
157
-
158
- return { routes: Object.fromEntries(routeEntries) } as Config;
159
- }
160
-
161
- // Ensure routes are produced in order of precedence so that
162
- // more specific routes aren't occluded from matching due to
163
- // less specific routes appearing first in the route list.
164
- export function compareRoutes(
165
- [routePathA, methodA]: RouteKey,
166
- [routePathB, methodB]: RouteKey
167
- ) {
168
- function parseRoutePath(routePath: UrlPath): string[] {
169
- return routePath.slice(1).split("/").filter(Boolean);
170
- }
171
-
172
- const segmentsA = parseRoutePath(routePathA);
173
- const segmentsB = parseRoutePath(routePathB);
174
-
175
- // sort routes with fewer segments after those with more segments
176
- if (segmentsA.length !== segmentsB.length) {
177
- return segmentsB.length - segmentsA.length;
178
- }
179
-
180
- for (let i = 0; i < segmentsA.length; i++) {
181
- const isWildcardA = segmentsA[i].includes("*");
182
- const isWildcardB = segmentsB[i].includes("*");
183
- const isParamA = segmentsA[i].includes(":");
184
- const isParamB = segmentsB[i].includes(":");
185
-
186
- // sort wildcard segments after non-wildcard segments
187
- if (isWildcardA && !isWildcardB) return 1;
188
- if (!isWildcardA && isWildcardB) return -1;
189
-
190
- // sort dynamic param segments after non-param segments
191
- if (isParamA && !isParamB) return 1;
192
- if (!isParamA && isParamB) return -1;
193
- }
194
-
195
- // sort routes that specify an HTTP before those that don't
196
- if (methodA && !methodB) return -1;
197
- if (!methodA && methodB) return 1;
198
-
199
- // all else equal, just sort the paths lexicographically
200
- return routePathA.localeCompare(routePathB);
201
- }
202
-
203
- async function forEachFile<T>(
204
- baseDir: string,
205
- fn: (filepath: string) => T | Promise<T>
206
- ) {
207
- const searchPaths = [baseDir];
208
- const returnValues: T[] = [];
209
-
210
- while (isNotEmpty(searchPaths)) {
211
- const cwd = searchPaths.shift();
212
- const dir = await fs.readdir(cwd, { withFileTypes: true });
213
- for (const entry of dir) {
214
- const pathname = path.join(cwd, entry.name);
215
- if (entry.isDirectory()) {
216
- searchPaths.push(pathname);
217
- } else if (entry.isFile()) {
218
- returnValues.push(await fn(pathname));
219
- }
220
- }
221
- }
222
-
223
- return returnValues;
224
- }
225
-
226
- interface NonEmptyArray<T> extends Array<T> {
227
- shift(): T;
228
- }
229
- function isNotEmpty<T>(array: T[]): array is NonEmptyArray<T> {
230
- return array.length > 0;
231
- }
@@ -1,78 +0,0 @@
1
- export const RESERVED_KEYWORDS = [
2
- "do",
3
- "if",
4
- "in",
5
- "for",
6
- "let",
7
- "new",
8
- "try",
9
- "var",
10
- "case",
11
- "else",
12
- "enum",
13
- "eval",
14
- "null",
15
- "this",
16
- "true",
17
- "void",
18
- "with",
19
- "await",
20
- "break",
21
- "catch",
22
- "class",
23
- "const",
24
- "false",
25
- "super",
26
- "throw",
27
- "while",
28
- "yield",
29
- "delete",
30
- "export",
31
- "import",
32
- "public",
33
- "return",
34
- "static",
35
- "switch",
36
- "typeof",
37
- "default",
38
- "extends",
39
- "finally",
40
- "package",
41
- "private",
42
- "continue",
43
- "debugger",
44
- "function",
45
- "arguments",
46
- "interface",
47
- "protected",
48
- "implements",
49
- "instanceof",
50
- "NaN",
51
- "Infinity",
52
- "undefined",
53
- ];
54
-
55
- export const reservedKeywordRegex = new RegExp(
56
- `^${RESERVED_KEYWORDS.join("|")}$`
57
- );
58
-
59
- export const identifierStartRegex = /[$_\p{ID_Start}]/u;
60
-
61
- export const identifierPartRegex = /[$_\u200C\u200D\p{ID_Continue}]/u;
62
-
63
- export const identifierNameRegex =
64
- /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u;
65
-
66
- export const validIdentifierRegex = new RegExp(
67
- `(?!(${reservedKeywordRegex.source})$)${identifierNameRegex.source}`,
68
- "u"
69
- );
70
-
71
- export const isValidIdentifier = (identifier: string) =>
72
- validIdentifierRegex.test(identifier);
73
-
74
- export const normalizeIdentifier = (identifier: string) =>
75
- identifier.replace(
76
- /(?:^[^$_\p{ID_Start}])|[^$_\u200C\u200D\p{ID_Continue}]/gu,
77
- "_"
78
- );
@@ -1,160 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { toUrlPath } from "../../src/paths";
4
- import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
5
- import type { UrlPath } from "../../src/paths";
6
-
7
- export const HTTP_METHODS = [
8
- "HEAD",
9
- "OPTIONS",
10
- "GET",
11
- "POST",
12
- "PUT",
13
- "PATCH",
14
- "DELETE",
15
- ] as const;
16
- export type HTTPMethod = typeof HTTP_METHODS[number];
17
- export function isHTTPMethod(
18
- maybeHTTPMethod: string
19
- ): maybeHTTPMethod is HTTPMethod {
20
- return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
21
- }
22
-
23
- export type RoutesCollection = Array<{
24
- routePath: UrlPath;
25
- methods: HTTPMethod[];
26
- modules: string[];
27
- middlewares: string[];
28
- }>;
29
-
30
- export type Config = {
31
- routes?: RoutesConfig;
32
- schedules?: unknown;
33
- };
34
-
35
- export type RoutesConfig = {
36
- [route: UrlPath]: RouteConfig;
37
- };
38
-
39
- export type RouteConfig = {
40
- middleware?: string | string[];
41
- module?: string | string[];
42
- };
43
-
44
- type ImportMap = Map<
45
- string,
46
- {
47
- filepath: string;
48
- name: string;
49
- identifier: string;
50
- }
51
- >;
52
-
53
- type Arguments = {
54
- config: Config;
55
- outfile: string;
56
- srcDir: string;
57
- };
58
-
59
- export async function writeRoutesModule({
60
- config,
61
- srcDir,
62
- outfile = "_routes.js",
63
- }: Arguments) {
64
- const { importMap, routes } = parseConfig(config, srcDir);
65
- const routesModule = generateRoutesModule(importMap, routes);
66
-
67
- await fs.writeFile(outfile, routesModule);
68
-
69
- return outfile;
70
- }
71
-
72
- export function parseConfig(config: Config, baseDir: string) {
73
- const routes: RoutesCollection = [];
74
- const importMap: ImportMap = new Map();
75
- const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
76
-
77
- function parseModuleIdentifiers(paths: string | string[] | undefined) {
78
- if (typeof paths === "undefined") {
79
- paths = [];
80
- }
81
-
82
- if (typeof paths === "string") {
83
- paths = [paths];
84
- }
85
-
86
- return paths.map((modulePath) => {
87
- const [filepath, name = "default"] = modulePath.split(":");
88
- let { identifier } = importMap.get(modulePath) ?? {};
89
-
90
- const resolvedPath = path.resolve(baseDir, filepath);
91
-
92
- // ensure the filepath isn't attempting to resolve to anything outside of the project
93
- if (path.relative(baseDir, resolvedPath).startsWith("..")) {
94
- throw new Error(`Invalid module path "${filepath}"`);
95
- }
96
-
97
- // ensure the module name (if provided) is a valid identifier to guard against injection attacks
98
- if (name !== "default" && !isValidIdentifier(name)) {
99
- throw new Error(`Invalid module identifier "${name}"`);
100
- }
101
-
102
- if (!identifier) {
103
- identifier = normalizeIdentifier(`__${filepath}_${name}`);
104
-
105
- let count = identifierCount.get(identifier) ?? 0;
106
- identifierCount.set(identifier, ++count);
107
-
108
- if (count > 1) {
109
- identifier += `_${count}`;
110
- }
111
-
112
- importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
113
- }
114
-
115
- return identifier;
116
- });
117
- }
118
-
119
- for (const [route, props] of Object.entries(config.routes ?? {})) {
120
- let [_methods, routePath] = route.split(" ");
121
- if (!routePath) {
122
- routePath = _methods;
123
- _methods = "";
124
- }
125
-
126
- routes.push({
127
- routePath: toUrlPath(routePath),
128
- methods: _methods.split("|").filter(isHTTPMethod),
129
- middlewares: parseModuleIdentifiers(props.middleware),
130
- modules: parseModuleIdentifiers(props.module),
131
- });
132
- }
133
-
134
- return { routes, importMap };
135
- }
136
-
137
- export function generateRoutesModule(
138
- importMap: ImportMap,
139
- routes: RoutesCollection
140
- ) {
141
- return `${[...importMap.values()]
142
- .map(
143
- ({ filepath, name, identifier }) =>
144
- `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
145
- )
146
- .join("\n")}
147
-
148
- export const routes = [
149
- ${routes
150
- .map(
151
- (route) => ` {
152
- routePath: "${route.routePath}",
153
- methods: ${JSON.stringify(route.methods)},
154
- middlewares: [${route.middlewares.join(", ")}],
155
- modules: [${route.modules.join(", ")}],
156
- },`
157
- )
158
- .join("\n")}
159
- ]`;
160
- }