wrangler 0.0.0-cf88928 → 0.0.0-d12d8d1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-cf88928",
3
+ "version": "0.0.0-d12d8d1",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
6
  "bin": {
@@ -45,24 +45,30 @@
45
45
  "fsevents": "~2.3.2"
46
46
  },
47
47
  "devDependencies": {
48
+ "@babel/types": "^7.16.0",
48
49
  "@iarna/toml": "^2.2.5",
50
+ "@types/mime": "^2.0.3",
51
+ "@types/estree": "^0.0.50",
49
52
  "@types/react": "^17.0.37",
53
+ "@types/serve-static": "^1.13.10",
50
54
  "@types/signal-exit": "^3.0.1",
51
55
  "@types/ws": "^8.2.1",
52
56
  "@types/yargs": "^17.0.7",
53
57
  "acorn": "^8.6.0",
58
+ "acorn-walk": "^8.2.0",
54
59
  "chokidar": "^3.5.2",
55
60
  "clipboardy": "^3.0.0",
56
61
  "command-exists": "^1.2.9",
57
62
  "execa": "^6.0.0",
63
+ "faye-websocket": "^0.11.4",
58
64
  "finalhandler": "^1.1.2",
59
65
  "find-up": "^6.2.0",
60
66
  "formdata-node": "^4.3.1",
61
- "http-proxy": "^1.18.1",
62
67
  "ink": "^3.2.0",
63
68
  "ink-select-input": "^4.2.1",
64
69
  "ink-table": "^3.0.0",
65
70
  "ink-text-input": "^4.0.2",
71
+ "mime": "^3.0.0",
66
72
  "node-fetch": "^3.1.0",
67
73
  "open": "^8.4.0",
68
74
  "react": "^17.0.2",
@@ -77,7 +83,7 @@
77
83
  "files": [
78
84
  "src",
79
85
  "bin",
80
- "lib",
86
+ "pages",
81
87
  "miniflare-config-stubs",
82
88
  "wrangler-dist",
83
89
  "static-asset-facade.js",
@@ -1,12 +1,19 @@
1
1
  import path from "path";
2
2
  import { build } from "esbuild";
3
3
  import { fileURLToPath } from "url";
4
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
4
+
5
+ let sanitizedDirname;
6
+ try {
7
+ sanitizedDirname = path.dirname(fileURLToPath(import.meta.url));
8
+ } catch {
9
+ sanitizedDirname = __dirname;
10
+ }
5
11
 
6
12
  type Options = {
7
13
  routesModule: string;
8
14
  outfile: string;
9
15
  minify?: boolean;
16
+ sourcemap?: boolean;
10
17
  watch?: boolean;
11
18
  };
12
19
 
@@ -14,12 +21,13 @@ export function buildWorker({
14
21
  routesModule,
15
22
  outfile = "bundle.js",
16
23
  minify = false,
24
+ sourcemap = false,
17
25
  watch = false,
18
26
  }: Options) {
19
27
  console.log(`Compiling worker to "${outfile}"`);
20
28
  return build({
21
29
  entryPoints: [
22
- path.resolve(__dirname, "../lib/functions/template-worker.ts"),
30
+ path.resolve(sanitizedDirname, "../pages/functions/template-worker.ts"),
23
31
  ],
24
32
  inject: [routesModule],
25
33
  bundle: true,
@@ -27,6 +35,7 @@ export function buildWorker({
27
35
  target: "esnext",
28
36
  outfile,
29
37
  minify,
38
+ sourcemap,
30
39
  watch,
31
40
  allowOverwrite: true,
32
41
  });
@@ -0,0 +1,32 @@
1
+ import { compareRoutes } from "./filepath-routing";
2
+
3
+ describe("compareRoutes()", () => {
4
+ test("routes with fewer segments come after those with more segments", () => {
5
+ expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
6
+ });
7
+
8
+ test("routes with wildcard segments come after those without", () => {
9
+ expect(compareRoutes("/:foo*", "/foo")).toBe(1);
10
+ expect(compareRoutes("/:foo*", "/:foo")).toBe(1);
11
+ });
12
+
13
+ test("routes with dynamic segments come after those without", () => {
14
+ expect(compareRoutes("/:foo", "/foo")).toBe(1);
15
+ });
16
+
17
+ test("routes with dynamic segments occuring earlier come after those with dynamic segments in later positions", () => {
18
+ expect(compareRoutes("/foo/:id/bar", "/foo/bar/:id")).toBe(1);
19
+ });
20
+
21
+ test("routes with no HTTP method come after those specifying a method", () => {
22
+ expect(compareRoutes("/foo", "GET /foo")).toBe(1);
23
+ });
24
+
25
+ test("two equal routes are sorted according to their original position in the list", () => {
26
+ expect(compareRoutes("GET /foo", "GET /foo")).toBe(0);
27
+ });
28
+
29
+ test("it returns -1 if the first argument should appear first in the list", () => {
30
+ expect(compareRoutes("GET /foo", "/foo")).toBe(-1);
31
+ });
32
+ });
@@ -0,0 +1,223 @@
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 } from "./routes";
7
+ import type { Identifier } from "estree";
8
+ import type { ExportNamedDeclaration } from "@babel/types";
9
+
10
+ type Arguments = {
11
+ baseDir: string;
12
+ baseURL: string;
13
+ };
14
+
15
+ export async function generateConfigFromFileTree({
16
+ baseDir,
17
+ baseURL,
18
+ }: Arguments) {
19
+ let routeEntries: [
20
+ string,
21
+ { [key in "module" | "middleware"]?: string[] }
22
+ ][] = [] as any;
23
+
24
+ if (!baseURL.startsWith("/")) {
25
+ baseURL = `/${baseURL}`;
26
+ }
27
+
28
+ if (baseURL.endsWith("/")) {
29
+ baseURL = baseURL.slice(0, -1);
30
+ }
31
+
32
+ await forEachFile(baseDir, async (filepath) => {
33
+ const ext = path.extname(filepath);
34
+ if (/\.(mjs|js|ts)/.test(ext)) {
35
+ // transform the code to ensure we're working with vanilla JS + ESM
36
+ const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
37
+ loader: ext === ".ts" ? "ts" : "js",
38
+ });
39
+
40
+ // parse each file into an AST and search for module exports that match "onRequest" and friends
41
+ const ast = acorn.parse(code, {
42
+ ecmaVersion: "latest",
43
+ sourceType: "module",
44
+ });
45
+ acornWalk.simple(ast, {
46
+ ExportNamedDeclaration(_node) {
47
+ const node: ExportNamedDeclaration = _node as any;
48
+
49
+ // this is an array because multiple things can be exported from a single statement
50
+ // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
51
+ const exportNames: string[] = [];
52
+
53
+ if (node.declaration) {
54
+ const declaration = node.declaration;
55
+
56
+ // `export async function onRequest() {...}`
57
+ if (declaration.type === "FunctionDeclaration") {
58
+ exportNames.push(declaration.id.name);
59
+ }
60
+
61
+ // `export const onRequestGet = () => {}, onRequestPost = () => {}`
62
+ if (declaration.type === "VariableDeclaration") {
63
+ exportNames.push(
64
+ ...declaration.declarations.map(
65
+ (variableDeclarator) =>
66
+ (variableDeclarator.id as unknown as Identifier).name
67
+ )
68
+ );
69
+ }
70
+ }
71
+
72
+ // `export {foo, bar}`
73
+ if (node.specifiers.length) {
74
+ exportNames.push(
75
+ ...node.specifiers.map(
76
+ (exportSpecifier) =>
77
+ (exportSpecifier.exported as unknown as Identifier).name
78
+ )
79
+ );
80
+ }
81
+
82
+ for (const exportName of exportNames) {
83
+ const [match, method] =
84
+ exportName.match(
85
+ /^onRequest(Get|Post|Put|Patch|Delete|Options|Head)?$/
86
+ ) ?? [];
87
+
88
+ if (match) {
89
+ const basename = path.basename(filepath).slice(0, -ext.length);
90
+
91
+ const isIndexFile = basename === "index";
92
+ // TODO: deprecate _middleware_ in favor of _middleware
93
+ const isMiddlewareFile =
94
+ basename === "_middleware" || basename === "_middleware_";
95
+
96
+ let routePath = path
97
+ .relative(baseDir, filepath)
98
+ .slice(0, -ext.length);
99
+
100
+ if (isIndexFile || isMiddlewareFile) {
101
+ routePath = path.dirname(routePath);
102
+ }
103
+
104
+ if (routePath === ".") {
105
+ routePath = "";
106
+ }
107
+
108
+ routePath = `${baseURL}/${routePath}`;
109
+
110
+ routePath = routePath.replace(/\[\[(.+)]]/g, ":$1*"); // transform [[id]] => :id*
111
+ routePath = routePath.replace(/\[(.+)]/g, ":$1"); // transform [id] => :id
112
+
113
+ if (method) {
114
+ routePath = `${method.toUpperCase()} ${routePath}`;
115
+ }
116
+
117
+ routeEntries.push([
118
+ routePath,
119
+ {
120
+ [isMiddlewareFile ? "middleware" : "module"]: [
121
+ `${path.relative(baseDir, filepath)}:${exportName}`,
122
+ ],
123
+ },
124
+ ]);
125
+ }
126
+ }
127
+ },
128
+ });
129
+ }
130
+ });
131
+
132
+ // Combine together any routes (index routes) which contain both a module and a middleware
133
+ routeEntries = routeEntries.reduce(
134
+ (acc: typeof routeEntries, [routePath, routeHandler]) => {
135
+ const existingRouteEntry = acc.find(
136
+ (routeEntry) => routeEntry[0] === routePath
137
+ );
138
+ if (existingRouteEntry !== undefined) {
139
+ existingRouteEntry[1] = {
140
+ ...existingRouteEntry[1],
141
+ ...routeHandler,
142
+ };
143
+ } else {
144
+ acc.push([routePath, routeHandler]);
145
+ }
146
+ return acc;
147
+ },
148
+ []
149
+ );
150
+
151
+ routeEntries.sort(([pathA], [pathB]) => compareRoutes(pathA, pathB));
152
+
153
+ return { routes: Object.fromEntries(routeEntries) } as Config;
154
+ }
155
+
156
+ // Ensure routes are produced in order of precedence so that
157
+ // more specific routes aren't occluded from matching due to
158
+ // less specific routes appearing first in the route list.
159
+ export function compareRoutes(a: string, b: string) {
160
+ function parseRoutePath(routePath: string) {
161
+ let [method, path] = routePath.split(" ");
162
+ if (!path) {
163
+ path = method;
164
+ method = null;
165
+ }
166
+
167
+ const segments = path.slice(1).split("/");
168
+ return [method, segments];
169
+ }
170
+
171
+ const [methodA, segmentsA] = parseRoutePath(a);
172
+ const [methodB, segmentsB] = parseRoutePath(b);
173
+
174
+ // sort routes with fewer segments after those with more segments
175
+ if (segmentsA.length !== segmentsB.length) {
176
+ return segmentsB.length - segmentsA.length;
177
+ }
178
+
179
+ for (let i = 0; i < segmentsA.length; i++) {
180
+ const isWildcardA = segmentsA[i].includes("*");
181
+ const isWildcardB = segmentsB[i].includes("*");
182
+ const isParamA = segmentsA[i].includes(":");
183
+ const isParamB = segmentsB[i].includes(":");
184
+
185
+ // sort wildcard segments after non-wildcard segments
186
+ if (isWildcardA && !isWildcardB) return 1;
187
+ if (!isWildcardA && isWildcardB) return -1;
188
+
189
+ // sort dynamic param segments after non-param segments
190
+ if (isParamA && !isParamB) return 1;
191
+ if (!isParamA && isParamB) return -1;
192
+ }
193
+
194
+ // sort routes that specify an HTTP before those that don't
195
+ if (methodA && !methodB) return -1;
196
+ if (!methodA && methodB) return 1;
197
+
198
+ // all else equal, just sort them lexicographically
199
+ return a.localeCompare(b);
200
+ }
201
+
202
+ async function forEachFile<T>(
203
+ baseDir: string,
204
+ fn: (filepath: string) => T | Promise<T>
205
+ ) {
206
+ const searchPaths = [baseDir];
207
+ const returnValues: T[] = [];
208
+
209
+ while (searchPaths.length) {
210
+ const cwd = searchPaths.shift();
211
+ const dir = await fs.readdir(cwd, { withFileTypes: true });
212
+ for (const entry of dir) {
213
+ const pathname = path.join(cwd, entry.name);
214
+ if (entry.isDirectory()) {
215
+ searchPaths.push(pathname);
216
+ } else if (entry.isFile()) {
217
+ returnValues.push(await fn(pathname));
218
+ }
219
+ }
220
+ }
221
+
222
+ return returnValues;
223
+ }
@@ -0,0 +1,78 @@
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 isValidIdentifer = (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
+ );
@@ -0,0 +1,156 @@
1
+ import path from "path";
2
+ import fs from "fs/promises";
3
+ import { isValidIdentifer, 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.includes(maybeHTTPMethod as any);
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?: any;
31
+ };
32
+
33
+ export type RoutesConfig = {
34
+ [route: string]: {
35
+ middleware?: string | string[];
36
+ module?: string | string[];
37
+ };
38
+ };
39
+
40
+ type ImportMap = Map<
41
+ string,
42
+ {
43
+ filepath: string;
44
+ name: string;
45
+ identifier: string;
46
+ }
47
+ >;
48
+
49
+ type Arguments = {
50
+ config: Config;
51
+ outfile: string;
52
+ srcDir: string;
53
+ };
54
+
55
+ export async function writeRoutesModule({
56
+ config,
57
+ srcDir,
58
+ outfile = "_routes.js",
59
+ }: Arguments) {
60
+ const { importMap, routes } = parseConfig(config, srcDir);
61
+ const routesModule = generateRoutesModule(importMap, routes);
62
+
63
+ await fs.writeFile(outfile, routesModule);
64
+
65
+ return outfile;
66
+ }
67
+
68
+ export function parseConfig(config: Config, baseDir: string) {
69
+ const routes: RoutesCollection = [];
70
+ const importMap: ImportMap = new Map();
71
+ const identifierCount = new Map<string, number>(); // to keep track of identifier collisions
72
+
73
+ function parseModuleIdentifiers(paths: string | string[] | undefined) {
74
+ if (typeof paths === "undefined") {
75
+ paths = [];
76
+ }
77
+
78
+ if (typeof paths === "string") {
79
+ paths = [paths];
80
+ }
81
+
82
+ return paths.map((modulePath) => {
83
+ const [filepath, name = "default"] = modulePath.split(":");
84
+ let { identifier } = importMap.get(modulePath) ?? {};
85
+
86
+ const resolvedPath = path.resolve(baseDir, filepath);
87
+
88
+ // ensure the filepath isn't attempting to resolve to anything outside of the project
89
+ if (path.relative(baseDir, resolvedPath).startsWith("..")) {
90
+ throw new Error(`Invalid module path "${filepath}"`);
91
+ }
92
+
93
+ // ensure the module name (if provided) is a valid identifier to guard against injection attacks
94
+ if (name !== "default" && !isValidIdentifer(name)) {
95
+ throw new Error(`Invalid module identifier "${name}"`);
96
+ }
97
+
98
+ if (!identifier) {
99
+ identifier = normalizeIdentifier(`__${filepath}_${name}`);
100
+
101
+ let count = identifierCount.get(identifier) ?? 0;
102
+ identifierCount.set(identifier, ++count);
103
+
104
+ if (count > 1) {
105
+ identifier += `_${count}`;
106
+ }
107
+
108
+ importMap.set(modulePath, { filepath: resolvedPath, name, identifier });
109
+ }
110
+
111
+ return identifier;
112
+ });
113
+ }
114
+
115
+ for (const [route, props] of Object.entries(config.routes)) {
116
+ let [_methods, routePath] = route.split(" ");
117
+ if (!routePath) {
118
+ routePath = _methods;
119
+ _methods = "";
120
+ }
121
+
122
+ routes.push({
123
+ routePath,
124
+ methods: _methods.split("|").filter(isHTTPMethod),
125
+ middlewares: parseModuleIdentifiers(props.middleware),
126
+ modules: parseModuleIdentifiers(props.module),
127
+ });
128
+ }
129
+
130
+ return { routes, importMap };
131
+ }
132
+
133
+ export function generateRoutesModule(
134
+ importMap: ImportMap,
135
+ routes: RoutesCollection
136
+ ) {
137
+ return `${[...importMap.values()]
138
+ .map(
139
+ ({ filepath, name, identifier }) =>
140
+ `import { ${name} as ${identifier} } from ${JSON.stringify(filepath)}`
141
+ )
142
+ .join("\n")}
143
+
144
+ export const routes = [
145
+ ${routes
146
+ .map(
147
+ (route) => ` {
148
+ routePath: "${route.routePath}",
149
+ methods: ${JSON.stringify(route.methods)},
150
+ middlewares: [${route.middlewares.join(", ")}],
151
+ modules: [${route.modules.join(", ")}],
152
+ },`
153
+ )
154
+ .join("\n")}
155
+ ]`;
156
+ }
@@ -1,5 +1,5 @@
1
1
  import { match } from "path-to-regexp";
2
- import { HTTPMethod } from "./routes";
2
+ import type { HTTPMethod } from "./routes";
3
3
 
4
4
  /* TODO: Grab these from @cloudflare/workers-types instead */
5
5
  type Params<P extends string = any> = Record<P, string | string[]>;