wrangler 0.0.0-d0bad35 → 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.
Files changed (42) hide show
  1. package/package.json +7 -14
  2. package/pages/functions/buildWorker.ts +10 -30
  3. package/pages/functions/filepath-routing.test.ts +1 -8
  4. package/pages/functions/filepath-routing.ts +20 -25
  5. package/pages/functions/identifiers.ts +1 -1
  6. package/pages/functions/routes.ts +9 -11
  7. package/pages/functions/template-worker.ts +22 -25
  8. package/src/__tests__/index.test.ts +164 -197
  9. package/src/__tests__/jest.setup.ts +0 -12
  10. package/src/__tests__/mock-cfetch.js +42 -0
  11. package/src/api/form_data.ts +76 -66
  12. package/src/api/inspect.ts +430 -0
  13. package/src/api/preview.ts +4 -4
  14. package/src/api/worker.ts +44 -38
  15. package/src/cfetch.ts +72 -0
  16. package/src/cli.ts +7 -6
  17. package/src/config.ts +110 -629
  18. package/src/dev.tsx +290 -203
  19. package/src/dialogs.tsx +2 -2
  20. package/src/index.tsx +429 -602
  21. package/src/kv.tsx +41 -102
  22. package/src/pages.tsx +228 -361
  23. package/src/proxy.ts +72 -270
  24. package/src/publish.ts +92 -133
  25. package/src/sites.tsx +41 -169
  26. package/src/tail.tsx +3 -5
  27. package/src/user.tsx +74 -64
  28. package/wrangler-dist/cli.js +40834 -34167
  29. package/wrangler-dist/cli.js.map +3 -3
  30. package/src/__tests__/dev.test.tsx +0 -67
  31. package/src/__tests__/kv.test.ts +0 -1246
  32. package/src/__tests__/logout.test.ts +0 -64
  33. package/src/__tests__/mock-cfetch.ts +0 -173
  34. package/src/__tests__/mock-console.ts +0 -34
  35. package/src/__tests__/publish.test.ts +0 -916
  36. package/src/__tests__/run-in-tmp.ts +0 -29
  37. package/src/__tests__/run-wrangler.ts +0 -8
  38. package/src/__tests__/whoami.test.tsx +0 -127
  39. package/src/cfetch/index.ts +0 -110
  40. package/src/cfetch/internal.ts +0 -71
  41. package/src/inspect.ts +0 -590
  42. package/src/whoami.tsx +0 -69
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-d0bad35",
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": {
@@ -37,10 +37,9 @@
37
37
  ],
38
38
  "dependencies": {
39
39
  "esbuild": "0.14.1",
40
- "miniflare": "2.2.0",
40
+ "miniflare": "2.0.0-rc.4",
41
41
  "path-to-regexp": "^6.2.0",
42
- "semiver": "^1.1.0",
43
- "xxhash-addon": "^1.4.0"
42
+ "semiver": "^1.1.0"
44
43
  },
45
44
  "optionalDependencies": {
46
45
  "fsevents": "~2.3.2"
@@ -48,8 +47,8 @@
48
47
  "devDependencies": {
49
48
  "@babel/types": "^7.16.0",
50
49
  "@iarna/toml": "^2.2.5",
51
- "@types/estree": "^0.0.50",
52
50
  "@types/mime": "^2.0.3",
51
+ "@types/estree": "^0.0.50",
53
52
  "@types/react": "^17.0.37",
54
53
  "@types/serve-static": "^1.13.10",
55
54
  "@types/signal-exit": "^3.0.1",
@@ -60,21 +59,17 @@
60
59
  "chokidar": "^3.5.2",
61
60
  "clipboardy": "^3.0.0",
62
61
  "command-exists": "^1.2.9",
63
- "devtools-protocol": "^0.0.955664",
64
62
  "execa": "^6.0.0",
65
63
  "faye-websocket": "^0.11.4",
66
64
  "finalhandler": "^1.1.2",
67
65
  "find-up": "^6.2.0",
68
66
  "formdata-node": "^4.3.1",
69
- "ignore": "^5.2.0",
70
67
  "ink": "^3.2.0",
71
68
  "ink-select-input": "^4.2.1",
72
69
  "ink-table": "^3.0.0",
73
- "ink-testing-library": "^2.1.0",
74
70
  "ink-text-input": "^4.0.2",
75
- "jest-fetch-mock": "^3.0.3",
76
71
  "mime": "^3.0.0",
77
- "node-fetch": "3.1.1",
72
+ "node-fetch": "^3.1.0",
78
73
  "open": "^8.4.0",
79
74
  "react": "^17.0.2",
80
75
  "react-error-boundary": "^3.1.4",
@@ -100,15 +95,13 @@
100
95
  "bundle": "node -r esbuild-register scripts/bundle.ts",
101
96
  "build": "npm run clean && npm run bundle",
102
97
  "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
103
- "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true",
104
- "test-watch": "npm run test -- --runInBand --testTimeout=50000 --watch"
98
+ "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
105
99
  },
106
100
  "engines": {
107
101
  "node": ">=16.7.0"
108
102
  },
109
103
  "jest": {
110
104
  "restoreMocks": true,
111
- "testTimeout": 30000,
112
105
  "testRegex": ".*.(test|spec)\\.[jt]sx?$",
113
106
  "transformIgnorePatterns": [
114
107
  "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream)"
@@ -128,4 +121,4 @@
128
121
  "<rootDir>/src/__tests__/jest.setup.ts"
129
122
  ]
130
123
  }
131
- }
124
+ }
@@ -1,14 +1,20 @@
1
1
  import path from "path";
2
2
  import { build } from "esbuild";
3
+ import { fileURLToPath } from "url";
4
+
5
+ let sanitizedDirname;
6
+ try {
7
+ sanitizedDirname = path.dirname(fileURLToPath(import.meta.url));
8
+ } catch {
9
+ sanitizedDirname = __dirname;
10
+ }
3
11
 
4
12
  type Options = {
5
13
  routesModule: string;
6
14
  outfile: string;
7
15
  minify?: boolean;
8
16
  sourcemap?: boolean;
9
- fallbackService?: string;
10
17
  watch?: boolean;
11
- onEnd?: () => void;
12
18
  };
13
19
 
14
20
  export function buildWorker({
@@ -16,13 +22,12 @@ export function buildWorker({
16
22
  outfile = "bundle.js",
17
23
  minify = false,
18
24
  sourcemap = false,
19
- fallbackService = "ASSETS",
20
25
  watch = false,
21
- onEnd = () => {},
22
26
  }: Options) {
27
+ console.log(`Compiling worker to "${outfile}"`);
23
28
  return build({
24
29
  entryPoints: [
25
- path.resolve(__dirname, "../pages/functions/template-worker.ts"),
30
+ path.resolve(sanitizedDirname, "../pages/functions/template-worker.ts"),
26
31
  ],
27
32
  inject: [routesModule],
28
33
  bundle: true,
@@ -33,30 +38,5 @@ export function buildWorker({
33
38
  sourcemap,
34
39
  watch,
35
40
  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
41
  });
62
42
  }
@@ -1,15 +1,8 @@
1
1
  import { compareRoutes } from "./filepath-routing";
2
2
 
3
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
4
  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);
5
+ expect(compareRoutes("/foo", "/foo/bar")).toBe(1);
13
6
  });
14
7
 
15
8
  test("routes with wildcard segments come after those without", () => {
@@ -3,8 +3,9 @@ import fs from "fs/promises";
3
3
  import { transform } from "esbuild";
4
4
  import * as acorn from "acorn";
5
5
  import * as acornWalk from "acorn-walk";
6
- import type { Config, RouteConfig } from "./routes";
7
- import type { ExportNamedDeclaration, Identifier } from "estree";
6
+ import type { Config } from "./routes";
7
+ import type { Identifier } from "estree";
8
+ import type { ExportNamedDeclaration } from "@babel/types";
8
9
 
9
10
  type Arguments = {
10
11
  baseDir: string;
@@ -15,7 +16,10 @@ export async function generateConfigFromFileTree({
15
16
  baseDir,
16
17
  baseURL,
17
18
  }: Arguments) {
18
- let routeEntries: [string, RouteConfig][] = [];
19
+ let routeEntries: [
20
+ string,
21
+ { [key in "module" | "middleware"]?: string[] }
22
+ ][] = [] as any;
19
23
 
20
24
  if (!baseURL.startsWith("/")) {
21
25
  baseURL = `/${baseURL}`;
@@ -27,7 +31,7 @@ export async function generateConfigFromFileTree({
27
31
 
28
32
  await forEachFile(baseDir, async (filepath) => {
29
33
  const ext = path.extname(filepath);
30
- if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
34
+ if (/\.(mjs|js|ts)/.test(ext)) {
31
35
  // transform the code to ensure we're working with vanilla JS + ESM
32
36
  const { code } = await transform(await fs.readFile(filepath, "utf-8"), {
33
37
  loader: ext === ".ts" ? "ts" : "js",
@@ -39,10 +43,8 @@ export async function generateConfigFromFileTree({
39
43
  sourceType: "module",
40
44
  });
41
45
  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
+ ExportNamedDeclaration(_node) {
47
+ const node: ExportNamedDeclaration = _node as any;
46
48
 
47
49
  // this is an array because multiple things can be exported from a single statement
48
50
  // i.e. `export {foo, bar}` or `export const foo = "f", bar = "b"`
@@ -52,7 +54,7 @@ export async function generateConfigFromFileTree({
52
54
  const declaration = node.declaration;
53
55
 
54
56
  // `export async function onRequest() {...}`
55
- if (declaration.type === "FunctionDeclaration" && declaration.id) {
57
+ if (declaration.type === "FunctionDeclaration") {
56
58
  exportNames.push(declaration.id.name);
57
59
  }
58
60
 
@@ -155,14 +157,14 @@ export async function generateConfigFromFileTree({
155
157
  // more specific routes aren't occluded from matching due to
156
158
  // less specific routes appearing first in the route list.
157
159
  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);
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("/");
166
168
  return [method, segments];
167
169
  }
168
170
 
@@ -204,7 +206,7 @@ async function forEachFile<T>(
204
206
  const searchPaths = [baseDir];
205
207
  const returnValues: T[] = [];
206
208
 
207
- while (isNotEmpty(searchPaths)) {
209
+ while (searchPaths.length) {
208
210
  const cwd = searchPaths.shift();
209
211
  const dir = await fs.readdir(cwd, { withFileTypes: true });
210
212
  for (const entry of dir) {
@@ -219,10 +221,3 @@ async function forEachFile<T>(
219
221
 
220
222
  return returnValues;
221
223
  }
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
- }
@@ -68,7 +68,7 @@ export const validIdentifierRegex = new RegExp(
68
68
  "u"
69
69
  );
70
70
 
71
- export const isValidIdentifier = (identifier: string) =>
71
+ export const isValidIdentifer = (identifier: string) =>
72
72
  validIdentifierRegex.test(identifier);
73
73
 
74
74
  export const normalizeIdentifier = (identifier: string) =>
@@ -1,6 +1,6 @@
1
1
  import path from "path";
2
2
  import fs from "fs/promises";
3
- import { isValidIdentifier, normalizeIdentifier } from "./identifiers";
3
+ import { isValidIdentifer, normalizeIdentifier } from "./identifiers";
4
4
 
5
5
  export const HTTP_METHODS = [
6
6
  "HEAD",
@@ -15,7 +15,7 @@ export type HTTPMethod = typeof HTTP_METHODS[number];
15
15
  export function isHTTPMethod(
16
16
  maybeHTTPMethod: string
17
17
  ): maybeHTTPMethod is HTTPMethod {
18
- return (HTTP_METHODS as readonly string[]).includes(maybeHTTPMethod);
18
+ return HTTP_METHODS.includes(maybeHTTPMethod as any);
19
19
  }
20
20
 
21
21
  export type RoutesCollection = Array<{
@@ -27,16 +27,14 @@ export type RoutesCollection = Array<{
27
27
 
28
28
  export type Config = {
29
29
  routes?: RoutesConfig;
30
- schedules?: unknown;
30
+ schedules?: any;
31
31
  };
32
32
 
33
33
  export type RoutesConfig = {
34
- [route: string]: RouteConfig;
35
- };
36
-
37
- export type RouteConfig = {
38
- middleware?: string | string[];
39
- module?: string | string[];
34
+ [route: string]: {
35
+ middleware?: string | string[];
36
+ module?: string | string[];
37
+ };
40
38
  };
41
39
 
42
40
  type ImportMap = Map<
@@ -93,7 +91,7 @@ export function parseConfig(config: Config, baseDir: string) {
93
91
  }
94
92
 
95
93
  // ensure the module name (if provided) is a valid identifier to guard against injection attacks
96
- if (name !== "default" && !isValidIdentifier(name)) {
94
+ if (name !== "default" && !isValidIdentifer(name)) {
97
95
  throw new Error(`Invalid module identifier "${name}"`);
98
96
  }
99
97
 
@@ -114,7 +112,7 @@ export function parseConfig(config: Config, baseDir: string) {
114
112
  });
115
113
  }
116
114
 
117
- for (const [route, props] of Object.entries(config.routes ?? {})) {
115
+ for (const [route, props] of Object.entries(config.routes)) {
118
116
  let [_methods, routePath] = route.split(" ");
119
117
  if (!routePath) {
120
118
  routePath = _methods;
@@ -2,11 +2,11 @@ import { match } from "path-to-regexp";
2
2
  import type { HTTPMethod } from "./routes";
3
3
 
4
4
  /* TODO: Grab these from @cloudflare/workers-types instead */
5
- type Params<P extends string = string> = Record<P, string | string[]>;
5
+ type Params<P extends string = any> = Record<P, string | string[]>;
6
6
 
7
7
  type EventContext<Env, P extends string, Data> = {
8
8
  request: Request;
9
- waitUntil: (promise: Promise<unknown>) => void;
9
+ waitUntil: (promise: Promise<any>) => void;
10
10
  next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
11
  env: Env & { ASSETS: { fetch: typeof fetch } };
12
12
  params: Params<P>;
@@ -15,9 +15,9 @@ type EventContext<Env, P extends string, Data> = {
15
15
 
16
16
  declare type PagesFunction<
17
17
  Env = unknown,
18
- P extends string = string,
18
+ Params extends string = any,
19
19
  Data extends Record<string, unknown> = Record<string, unknown>
20
- > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
20
+ > = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;
21
21
  /* end @cloudflare/workers-types */
22
22
 
23
23
  type RouteHandler = {
@@ -29,24 +29,22 @@ type RouteHandler = {
29
29
 
30
30
  // inject `routes` via ESBuild
31
31
  declare const routes: RouteHandler[];
32
- // define `__FALLBACK_SERVICE__` via ESBuild
33
- declare const __FALLBACK_SERVICE__: string;
34
32
 
35
33
  // expect an ASSETS fetcher binding pointing to the asset-server stage
36
- type FetchEnv = {
37
- [name: string]: { fetch: typeof fetch };
38
- ASSETS: { fetch: typeof fetch };
34
+ type Env = {
35
+ [name: string]: any;
36
+ ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
39
37
  };
40
38
 
41
39
  type WorkerContext = {
42
- waitUntil: (promise: Promise<unknown>) => void;
40
+ waitUntil: (promise: Promise<any>) => void;
43
41
  };
44
42
 
45
- function* executeRequest(request: Request, _env: FetchEnv) {
43
+ function* executeRequest(request: Request, env: Env) {
46
44
  const requestPath = new URL(request.url).pathname;
47
45
 
48
- // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
49
- for (const route of [...routes].reverse()) {
46
+ // First, iterate through the routes and execute "middlewares" on partial route matches
47
+ for (const route of routes) {
50
48
  if (
51
49
  route.methods.length &&
52
50
  !route.methods.includes(request.method as HTTPMethod)
@@ -87,10 +85,16 @@ function* executeRequest(request: Request, _env: FetchEnv) {
87
85
  break;
88
86
  }
89
87
  }
88
+
89
+ // Finally, yield to the asset-server
90
+ return {
91
+ handler: () => env.ASSETS.fetch(request.url, request),
92
+ params: {} as Params,
93
+ };
90
94
  }
91
95
 
92
96
  export default {
93
- async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
97
+ async fetch(request: Request, env: Env, workerContext: WorkerContext) {
94
98
  const handlerIterator = executeRequest(request, env);
95
99
  const data = {}; // arbitrary data the user can set between functions
96
100
  const next = async (input?: RequestInfo, init?: RequestInit) => {
@@ -98,11 +102,10 @@ export default {
98
102
  request = new Request(input, init);
99
103
  }
100
104
 
101
- const result = handlerIterator.next();
102
- // Note we can't use `!result.done` because this doesn't narrow to the correct type
103
- if (result.done == false) {
104
- const { handler, params } = result.value;
105
- const context = {
105
+ const { value } = handlerIterator.next();
106
+ if (value) {
107
+ const { handler, params } = value;
108
+ const context: EventContext<unknown, any, any> = {
106
109
  request: new Request(request.clone()),
107
110
  next,
108
111
  params,
@@ -118,12 +121,6 @@ export default {
118
121
  [101, 204, 205, 304].includes(response.status) ? null : response.body,
119
122
  response
120
123
  );
121
- } else if (__FALLBACK_SERVICE__) {
122
- // There are no more handlers so finish with the fallback service (`env.ASSETS.fetch` in Pages' case)
123
- return env[__FALLBACK_SERVICE__].fetch(request);
124
- } else {
125
- // There was not fallback service so actually make the request to the origin.
126
- return fetch(request);
127
124
  }
128
125
  };
129
126