wrangler 0.0.0-e0d2f35 → 0.0.0-e11e1691

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 (130) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +122 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +176 -80
  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 +167 -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 +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +15 -0
  31. package/templates/new-worker.ts +33 -0
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +8 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23937 -0
  48. package/wrangler-dist/cli.js +164283 -116933
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/pages/functions/buildWorker.ts +0 -62
  55. package/pages/functions/filepath-routing.test.ts +0 -39
  56. package/pages/functions/filepath-routing.ts +0 -228
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -158
  59. package/pages/functions/template-worker.ts +0 -136
  60. package/src/__tests__/clipboardy-mock.js +0 -4
  61. package/src/__tests__/dev.test.tsx +0 -71
  62. package/src/__tests__/index.test.ts +0 -424
  63. package/src/__tests__/jest.setup.ts +0 -29
  64. package/src/__tests__/kv.test.ts +0 -1224
  65. package/src/__tests__/logout.test.ts +0 -64
  66. package/src/__tests__/mock-cfetch.ts +0 -173
  67. package/src/__tests__/mock-console.ts +0 -34
  68. package/src/__tests__/mock-dialogs.ts +0 -65
  69. package/src/__tests__/mock-kv.ts +0 -40
  70. package/src/__tests__/mock-user.ts +0 -27
  71. package/src/__tests__/publish.test.ts +0 -1206
  72. package/src/__tests__/run-in-tmp.ts +0 -29
  73. package/src/__tests__/run-wrangler.ts +0 -8
  74. package/src/__tests__/secret.test.ts +0 -206
  75. package/src/__tests__/whoami.test.tsx +0 -101
  76. package/src/api/form_data.ts +0 -135
  77. package/src/api/preview.ts +0 -128
  78. package/src/api/worker.ts +0 -155
  79. package/src/cfetch/index.ts +0 -111
  80. package/src/cfetch/internal.ts +0 -71
  81. package/src/cli.ts +0 -9
  82. package/src/config.ts +0 -641
  83. package/src/dev.tsx +0 -830
  84. package/src/dialogs.tsx +0 -77
  85. package/src/index.tsx +0 -2078
  86. package/src/inspect.ts +0 -595
  87. package/src/kv.tsx +0 -276
  88. package/src/module-collection.ts +0 -63
  89. package/src/pages.tsx +0 -1043
  90. package/src/proxy.ts +0 -370
  91. package/src/publish.ts +0 -410
  92. package/src/sites.tsx +0 -240
  93. package/src/tail.tsx +0 -73
  94. package/src/user.tsx +0 -1019
  95. package/src/whoami.tsx +0 -69
  96. package/static-asset-facade.js +0 -47
  97. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  98. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  99. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  100. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  101. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  102. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  103. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  104. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  105. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  106. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  107. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  108. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  109. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  110. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  111. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  112. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  113. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  114. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  115. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  116. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  117. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  118. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  119. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  120. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  121. package/vendor/wrangler-mime/LICENSE +0 -21
  122. package/vendor/wrangler-mime/Mime.js +0 -97
  123. package/vendor/wrangler-mime/README.md +0 -187
  124. package/vendor/wrangler-mime/cli.js +0 -46
  125. package/vendor/wrangler-mime/index.js +0 -4
  126. package/vendor/wrangler-mime/lite.js +0 -4
  127. package/vendor/wrangler-mime/package.json +0 -52
  128. package/vendor/wrangler-mime/types/other.js +0 -1
  129. package/vendor/wrangler-mime/types/standard.js +0 -1
  130. package/wrangler-dist/cli.js.map +0 -7
Binary file
@@ -1,3 +0,0 @@
1
- // as per https://github.com/evanw/esbuild/issues/1492
2
- // to make some libs work
3
- export const import_meta_url = require("url").pathToFileURL(__filename);
File without changes
@@ -1 +0,0 @@
1
- {}
File without changes
@@ -1,62 +0,0 @@
1
- import path from "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,39 +0,0 @@
1
- import { compareRoutes } from "./filepath-routing";
2
-
3
- describe("compareRoutes()", () => {
4
- test("routes / last", () => {
5
- expect(compareRoutes("/", "/foo")).toBeGreaterThanOrEqual(1);
6
- expect(compareRoutes("/", "/:foo")).toBeGreaterThanOrEqual(1);
7
- expect(compareRoutes("/", "/:foo*")).toBeGreaterThanOrEqual(1);
8
- });
9
-
10
- test("routes with fewer segments come after those with more segments", () => {
11
- expect(compareRoutes("/foo", "/foo/bar")).toBeGreaterThanOrEqual(1);
12
- expect(compareRoutes("/foo", "/foo/bar/cat")).toBeGreaterThanOrEqual(1);
13
- });
14
-
15
- test("routes with wildcard segments come after those without", () => {
16
- expect(compareRoutes("/:foo*", "/foo")).toBe(1);
17
- expect(compareRoutes("/:foo*", "/:foo")).toBe(1);
18
- });
19
-
20
- test("routes with dynamic segments come after those without", () => {
21
- expect(compareRoutes("/:foo", "/foo")).toBe(1);
22
- });
23
-
24
- test("routes with dynamic segments occuring earlier come after those with dynamic segments in later positions", () => {
25
- expect(compareRoutes("/foo/:id/bar", "/foo/bar/:id")).toBe(1);
26
- });
27
-
28
- test("routes with no HTTP method come after those specifying a method", () => {
29
- expect(compareRoutes("/foo", "GET /foo")).toBe(1);
30
- });
31
-
32
- test("two equal routes are sorted according to their original position in the list", () => {
33
- expect(compareRoutes("GET /foo", "GET /foo")).toBe(0);
34
- });
35
-
36
- test("it returns -1 if the first argument should appear first in the list", () => {
37
- expect(compareRoutes("GET /foo", "/foo")).toBe(-1);
38
- });
39
- });
@@ -1,228 +0,0 @@
1
- import path from "path";
2
- import fs from "fs/promises";
3
- import { transform } from "esbuild";
4
- import * as acorn from "acorn";
5
- import * as acornWalk from "acorn-walk";
6
- import type { Config, RouteConfig } from "./routes";
7
- import type { ExportNamedDeclaration, Identifier } from "estree";
8
-
9
- type Arguments = {
10
- baseDir: string;
11
- baseURL: string;
12
- };
13
-
14
- export async function generateConfigFromFileTree({
15
- baseDir,
16
- baseURL,
17
- }: Arguments) {
18
- let routeEntries: [string, RouteConfig][] = [];
19
-
20
- if (!baseURL.startsWith("/")) {
21
- baseURL = `/${baseURL}`;
22
- }
23
-
24
- if (baseURL.endsWith("/")) {
25
- baseURL = baseURL.slice(0, -1);
26
- }
27
-
28
- await forEachFile(baseDir, async (filepath) => {
29
- const ext = path.extname(filepath);
30
- if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
31
- // transform the code to ensure we're working with vanilla JS + ESM
32
- const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
33
- loader: ext === ".ts" ? "ts" : "js",
34
- });
35
-
36
- // parse each file into an AST and search for module exports that match "onRequest" and friends
37
- const ast = acorn.parse(code, {
38
- ecmaVersion: "latest",
39
- sourceType: "module",
40
- });
41
- acornWalk.simple(ast, {
42
- ExportNamedDeclaration(_node: unknown) {
43
- // This dynamic cast assumes that the AST generated by acornWalk will generate nodes that
44
- // are compatible with the eslint AST nodes.
45
- const node = _node as ExportNamedDeclaration;
46
-
47
- // this is an array because multiple things can be exported from a single statement
48
- // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
49
- const exportNames: string[] = [];
50
-
51
- if (node.declaration) {
52
- const declaration = node.declaration;
53
-
54
- // `export async function onRequest() {...}`
55
- if (declaration.type === "FunctionDeclaration" && declaration.id) {
56
- exportNames.push(declaration.id.name);
57
- }
58
-
59
- // `export const onRequestGet = () => {}, onRequestPost = () => {}`
60
- if (declaration.type === "VariableDeclaration") {
61
- exportNames.push(
62
- ...declaration.declarations.map(
63
- (variableDeclarator) =>
64
- (variableDeclarator.id as unknown as Identifier).name
65
- )
66
- );
67
- }
68
- }
69
-
70
- // `export {foo, bar}`
71
- if (node.specifiers.length) {
72
- exportNames.push(
73
- ...node.specifiers.map(
74
- (exportSpecifier) =>
75
- (exportSpecifier.exported as unknown as Identifier).name
76
- )
77
- );
78
- }
79
-
80
- for (const exportName of exportNames) {
81
- const [match, method] =
82
- exportName.match(
83
- /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
84
- ) ?? [];
85
-
86
- if (match) {
87
- const basename = path.basename(filepath).slice(0, -ext.length);
88
-
89
- const isIndexFile = basename === "index";
90
- // TODO: deprecate _middleware_ in favor of _middleware
91
- const isMiddlewareFile =
92
- basename === "_middleware" || basename === "_middleware_";
93
-
94
- let routePath = path
95
- .relative(baseDir, filepath)
96
- .slice(0, -ext.length);
97
-
98
- if (isIndexFile || isMiddlewareFile) {
99
- routePath = path.dirname(routePath);
100
- }
101
-
102
- if (routePath === ".") {
103
- routePath = "";
104
- }
105
-
106
- routePath = `${baseURL}/${routePath}`;
107
-
108
- routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
109
- routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
110
-
111
- if (method) {
112
- routePath = `${method.toUpperCase()} ${routePath}`;
113
- }
114
-
115
- routeEntries.push([
116
- routePath,
117
- {
118
- [isMiddlewareFile ? "middleware" : "module"]: [
119
- `${path.relative(baseDir, filepath)}:${exportName}`,
120
- ],
121
- },
122
- ]);
123
- }
124
- }
125
- },
126
- });
127
- }
128
- });
129
-
130
- // Combine together any routes (index routes) which contain both a module and a middleware
131
- routeEntries = routeEntries.reduce(
132
- (acc: typeof routeEntries, [routePath, routeHandler]) => {
133
- const existingRouteEntry = acc.find(
134
- (routeEntry) => routeEntry[0] === routePath
135
- );
136
- if (existingRouteEntry !== undefined) {
137
- existingRouteEntry[1] = {
138
- ...existingRouteEntry[1],
139
- ...routeHandler,
140
- };
141
- } else {
142
- acc.push([routePath, routeHandler]);
143
- }
144
- return acc;
145
- },
146
- []
147
- );
148
-
149
- routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
150
-
151
- return { routes: Object.fromEntries(routeEntries) } as Config;
152
- }
153
-
154
- // Ensure routes are produced in order of precedence so that
155
- // more specific routes aren't occluded from matching due to
156
- // less specific routes appearing first in the route list.
157
- export function compareRoutes(a: string, b: string) {
158
- function parseRoutePath(routePath: string): [string | null, string[]] {
159
- const parts = routePath.split(" ", 2);
160
- // split() will guarantee at least one element.
161
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
162
- const segmentedPath = parts.pop()!;
163
- const method = parts.pop() ?? null;
164
-
165
- const segments = segmentedPath.slice(1).split("/").filter(Boolean);
166
- return [method, segments];
167
- }
168
-
169
- const [methodA, segmentsA] = parseRoutePath(a);
170
- const [methodB, segmentsB] = parseRoutePath(b);
171
-
172
- // sort routes with fewer segments after those with more segments
173
- if (segmentsA.length !== segmentsB.length) {
174
- return segmentsB.length - segmentsA.length;
175
- }
176
-
177
- for (let i = 0; i < segmentsA.length; i++) {
178
- const isWildcardA = segmentsA[i].includes("*");
179
- const isWildcardB = segmentsB[i].includes("*");
180
- const isParamA = segmentsA[i].includes(":");
181
- const isParamB = segmentsB[i].includes(":");
182
-
183
- // sort wildcard segments after non-wildcard segments
184
- if (isWildcardA && !isWildcardB) return 1;
185
- if (!isWildcardA && isWildcardB) return -1;
186
-
187
- // sort dynamic param segments after non-param segments
188
- if (isParamA && !isParamB) return 1;
189
- if (!isParamA && isParamB) return -1;
190
- }
191
-
192
- // sort routes that specify an HTTP before those that don't
193
- if (methodA && !methodB) return -1;
194
- if (!methodA && methodB) return 1;
195
-
196
- // all else equal, just sort them lexicographically
197
- return a.localeCompare(b);
198
- }
199
-
200
- async function forEachFile<T>(
201
- baseDir: string,
202
- fn: (filepath: string) => T | Promise<T>
203
- ) {
204
- const searchPaths = [baseDir];
205
- const returnValues: T[] = [];
206
-
207
- while (isNotEmpty(searchPaths)) {
208
- const cwd = searchPaths.shift();
209
- const dir = await fs.readdir(cwd, { withFileTypes: true });
210
- for (const entry of dir) {
211
- const pathname = path.join(cwd, entry.name);
212
- if (entry.isDirectory()) {
213
- searchPaths.push(pathname);
214
- } else if (entry.isFile()) {
215
- returnValues.push(await fn(pathname));
216
- }
217
- }
218
- }
219
-
220
- return returnValues;
221
- }
222
-
223
- interface NonEmptyArray<T> extends Array<T> {
224
- shift(): T;
225
- }
226
- function isNotEmpty<T>(array: T[]): array is NonEmptyArray<T> {
227
- return array.length > 0;
228
- }
@@ -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,158 +0,0 @@
1
- import path from "path";
2
- import fs from "fs/promises";
3
- import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
4
-
5
- export const HTTP_METHODS = [
6
- "HEAD",
7
- "OPTIONS",
8
- "GET",
9
- "POST",
10
- "PUT",
11
- "PATCH",
12
- "DELETE",
13
- ] as const;
14
- export type HTTPMethod = typeof HTTP_METHODS[number];
15
- export function isHTTPMethod(
16
- maybeHTTPMethod: string
17
- ): maybeHTTPMethod is HTTPMethod {
18
- return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
19
- }
20
-
21
- export type RoutesCollection = Array<{
22
- routePath: string;
23
- methods: HTTPMethod[];
24
- modules: string[];
25
- middlewares: string[];
26
- }>;
27
-
28
- export type Config = {
29
- routes?: RoutesConfig;
30
- schedules?: unknown;
31
- };
32
-
33
- export type RoutesConfig = {
34
- [route: string]: RouteConfig;
35
- };
36
-
37
- export type RouteConfig = {
38
- middleware?: string | string[];
39
- module?: string | string[];
40
- };
41
-
42
- type ImportMap = Map<
43
- string,
44
- {
45
- filepath: string;
46
- name: string;
47
- identifier: string;
48
- }
49
- >;
50
-
51
- type Arguments = {
52
- config: Config;
53
- outfile: string;
54
- srcDir: string;
55
- };
56
-
57
- export async function writeRoutesModule({
58
- config,
59
- srcDir,
60
- outfile = "_routes.js",
61
- }: Arguments) {
62
- const { importMap, routes } = parseConfig(config, srcDir);
63
- const routesModule = generateRoutesModule(importMap, routes);
64
-
65
- await fs.writeFile(outfile, routesModule);
66
-
67
- return outfile;
68
- }
69
-
70
- export function parseConfig(config: Config, baseDir: string) {
71
- const routes: RoutesCollection = [];
72
- const importMap: ImportMap = new Map();
73
- const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
74
-
75
- function parseModuleIdentifiers(paths: string | string[] | undefined) {
76
- if (typeof paths === "undefined") {
77
- paths = [];
78
- }
79
-
80
- if (typeof paths === "string") {
81
- paths = [paths];
82
- }
83
-
84
- return paths.map((modulePath) => {
85
- const [filepath, name = "default"] = modulePath.split(":");
86
- let { identifier } = importMap.get(modulePath) ?? {};
87
-
88
- const resolvedPath = path.resolve(baseDir, filepath);
89
-
90
- // ensure the filepath isn't attempting to resolve to anything outside of the project
91
- if (path.relative(baseDir, resolvedPath).startsWith("..")) {
92
- throw new Error(`Invalid module path "${filepath}"`);
93
- }
94
-
95
- // ensure the module name (if provided) is a valid identifier to guard against injection attacks
96
- if (name !== "default" && !isValidIdentifier(name)) {
97
- throw new Error(`Invalid module identifier "${name}"`);
98
- }
99
-
100
- if (!identifier) {
101
- identifier = normalizeIdentifier(`__${filepath}_${name}`);
102
-
103
- let count = identifierCount.get(identifier) ?? 0;
104
- identifierCount.set(identifier, ++count);
105
-
106
- if (count > 1) {
107
- identifier += `_${count}`;
108
- }
109
-
110
- importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
111
- }
112
-
113
- return identifier;
114
- });
115
- }
116
-
117
- for (const [route, props] of Object.entries(config.routes ?? {})) {
118
- let [_methods, routePath] = route.split(" ");
119
- if (!routePath) {
120
- routePath = _methods;
121
- _methods = "";
122
- }
123
-
124
- routes.push({
125
- routePath,
126
- methods: _methods.split("|").filter(isHTTPMethod),
127
- middlewares: parseModuleIdentifiers(props.middleware),
128
- modules: parseModuleIdentifiers(props.module),
129
- });
130
- }
131
-
132
- return { routes, importMap };
133
- }
134
-
135
- export function generateRoutesModule(
136
- importMap: ImportMap,
137
- routes: RoutesCollection
138
- ) {
139
- return `${[...importMap.values()]
140
- .map(
141
- ({ filepath, name, identifier }) =>
142
- `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
143
- )
144
- .join("\n")}
145
-
146
- export const routes = [
147
- ${routes
148
- .map(
149
- (route) => ` {
150
- routePath: "${route.routePath}",
151
- methods: ${JSON.stringify(route.methods)},
152
- middlewares: [${route.middlewares.join(", ")}],
153
- modules: [${route.modules.join(", ")}],
154
- },`
155
- )
156
- .join("\n")}
157
- ]`;
158
- }