wrangler 0.0.0-bd89b54 → 0.0.0-beta.6

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/README.md ADDED
@@ -0,0 +1,51 @@
1
+ ## 🤠 wrangler
2
+
3
+ `wrangler` is a command line tool for building [Cloudflare Workers](https://workers.cloudflare.com/).
4
+
5
+ [(Read the full stack week launch blog post.)](https://blog.cloudflare.com/wrangler-v2-beta/)
6
+
7
+ **DISCLAIMER**: This is a work in progress, and is NOT recommended for use in production. We are opening this preview for feedback from the community, and to openly share our [roadmap](https://github.com/cloudflare/wrangler2/issues/12) for the future. As such, expect APIs and documentation to change before the end of the preview.
8
+
9
+ Further, we will NOT do a general release until we are both feature complete, and have a full backward compatibility and incremental migration plan in place. For more details, follow the [parent roadmap issue](https://github.com/cloudflare/wrangler2/issues/12).
10
+
11
+ ## Quick Start
12
+
13
+ ```bash
14
+ # Make a javascript file
15
+ $ echo "export default { fetch() { return new Response('hello world') } }" > index.js
16
+ # try it out
17
+ $ npx wrangler@beta dev index.js
18
+ # and then publish it
19
+ $ npx wrangler@beta publish index.js --name my-worker
20
+ # visit https://my-worker.<your workers subdomain>.workers.dev
21
+ ```
22
+
23
+ ## Installation:
24
+
25
+ ```bash
26
+ $ npm install wrangler@beta
27
+ ```
28
+
29
+ ## Commands
30
+
31
+ ### `wrangler init [name]`
32
+
33
+ Creates a `wrangler.toml` configuration file. For more details on the configuration keys and values, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/configuration).
34
+
35
+ ### `wrangler dev [script]`
36
+
37
+ Start a local development server, with live reloading and devtools.
38
+
39
+ ### `wrangler publish [script] --name [name]`
40
+
41
+ Publish the given script to the worldwide Cloudflare network.
42
+
43
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/workers/cli-wrangler/commands).
44
+
45
+ ### `wrangler pages dev [directory] [-- command]`
46
+
47
+ Either serves a static build asset directory, or proxies itself in front of a command.
48
+
49
+ Builds and runs functions from a `./functions` directory or uses a `_worker.js` file inside the static build asset directory.
50
+
51
+ For more commands and options, refer to the [documentation](https://developers.cloudflare.com/pages/platform/functions#develop-and-preview-locally) or run `wrangler pages dev --help`.
package/bin/wrangler.js CHANGED
@@ -24,7 +24,7 @@ Consider using a Node.js version manager such as https://volta.sh/ or https://gi
24
24
  "--no-warnings",
25
25
  "--experimental-vm-modules",
26
26
  ...process.execArgv,
27
- join(__dirname, "../wrangler-dist/index_node.js"),
27
+ join(__dirname, "../wrangler-dist/cli.js"),
28
28
  ...process.argv.slice(2),
29
29
  ],
30
30
  { stdio: "inherit" }
package/package.json CHANGED
@@ -1,9 +1,12 @@
1
1
  {
2
2
  "name": "wrangler",
3
- "version": "0.0.0-bd89b54",
3
+ "version": "0.0.0-beta.6",
4
4
  "author": "wrangler@cloudflare.com",
5
5
  "description": "Command-line interface for all things Cloudflare Workers",
6
- "bin": "./bin/wrangler.js",
6
+ "bin": {
7
+ "wrangler": "./bin/wrangler.js",
8
+ "wrangler2": "./bin/wrangler.js"
9
+ },
7
10
  "license": "MIT OR Apache-2.0",
8
11
  "bugs": {
9
12
  "url": "https://github.com/cloudflare/wrangler/issues"
@@ -33,9 +36,9 @@
33
36
  "cli"
34
37
  ],
35
38
  "dependencies": {
36
- "@cloudflare/pages-functions-compiler": "0.3.4",
39
+ "@cloudflare/pages-functions-compiler": "0.3.5",
37
40
  "esbuild": "0.13.12",
38
- "miniflare": "2.0.0-rc.1",
41
+ "miniflare": "2.0.0-rc.2",
39
42
  "semiver": "^1.1.0",
40
43
  "serve": "^13.0.2"
41
44
  },
@@ -63,8 +66,9 @@
63
66
  "ink-select-input": "^4.2.0",
64
67
  "ink-table": "^3.0.0",
65
68
  "ink-text-input": "^4.0.1",
66
- "node-fetch": "github:tekwiz/node-fetch#fix/redirect-with-empty-chunked-transfer-encoding",
69
+ "node-fetch": "^3.1.0",
67
70
  "open": "^8.4.0",
71
+ "path-to-regexp": "^6.2.0",
68
72
  "react": "^17.0.2",
69
73
  "serve-static": "^1.14.1",
70
74
  "signal-exit": "^3.0.5",
@@ -86,22 +90,26 @@
86
90
  "bundle": "node -r esbuild-register scripts/bundle.ts",
87
91
  "build": "npm run clean && npm run bundle",
88
92
  "start": "npm run bundle && NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
89
- "test": "npm run build && NODE_OPTIONS=--enable-source-maps jest --silent=false"
93
+ "test": "CF_API_TOKEN=some-api-token CF_ACCOUNT_ID=some-account-id jest --silent=false --verbose=true"
90
94
  },
91
95
  "engines": {
92
- "node": ">=16.0.0"
96
+ "node": ">=16.7.0"
93
97
  },
94
98
  "jest": {
99
+ "testRegex": ".*.(test|spec)\\.[jt]sx?$",
100
+ "transformIgnorePatterns": [
101
+ "node_modules/(?!node-fetch|fetch-blob|find-up|locate-path|p-locate|p-limit|yocto-queue|path-exists|data-uri-to-buffer|formdata-polyfill)"
102
+ ],
103
+ "moduleNameMapper": {
104
+ "clipboardy": "<rootDir>/src/__tests__/clipboardy-mock.js"
105
+ },
95
106
  "transform": {
96
- "^.+\\.tsx?$": [
107
+ "^.+\\.c?(t|j)sx?$": [
97
108
  "esbuild-jest",
98
109
  {
99
- "sourcemap": true,
100
- "loaders": {
101
- ".spec.ts": "tsx"
102
- }
110
+ "sourcemap": true
103
111
  }
104
112
  ]
105
113
  }
106
114
  }
107
- }
115
+ }
@@ -0,0 +1,4 @@
1
+ // We use this mock during tests because we're having trouble
2
+ // properly compiling clipboardy for jest
3
+ // We can revisit this if and when we write tests that test
4
+ // the copying part of `dev`
@@ -1,19 +1,53 @@
1
- import execa from "execa";
2
1
  import * as fs from "node:fs";
3
2
  import * as fsp from "node:fs/promises";
4
3
  import * as path from "node:path";
5
4
  import * as TOML from "@iarna/toml";
5
+ import { main } from "../index";
6
+ // @ts-expect-error we're mocking cfetch, so of course setMock isn't a thing
7
+ import { setMock, unsetAllMocks } from "../cfetch";
6
8
 
7
- async function w(cmd: string | string[] = []) {
8
- return await execa(
9
- path.join(__dirname, "../../bin/wrangler.js"),
10
- typeof cmd === "string" ? cmd.split(" ") : cmd
11
- );
9
+ jest.mock("../cfetch", () => {
10
+ return jest.requireActual("./mock-cfetch");
11
+ });
12
+
13
+ async function w(cmd: void | string, options?: { tap: boolean }) {
14
+ const tapped = options?.tap ? tap() : undefined;
15
+ await main([...(cmd ? cmd.split(" ") : [])]);
16
+ tapped?.off();
17
+ return { stdout: tapped?.out, stderr: tapped?.err };
18
+ }
19
+
20
+ function tap() {
21
+ const oldLog = console.log;
22
+ const oldError = console.error;
23
+
24
+ const toReturn = {
25
+ off: () => {
26
+ console.log = oldLog;
27
+ console.error = oldError;
28
+ },
29
+ out: "",
30
+ err: "",
31
+ };
32
+
33
+ console.log = (...args) => {
34
+ toReturn.out += args.join("");
35
+ oldLog.apply(console, args);
36
+ // console.trace(...args); // use this if you want to find the true source of your console.log
37
+ };
38
+ console.error = (...args) => {
39
+ toReturn.err += args.join("");
40
+ oldError.apply(console, args);
41
+ };
42
+
43
+ return toReturn;
12
44
  }
13
45
 
14
46
  describe("wrangler", () => {
15
47
  it("should run", async () => {
16
- expect((await w()).stdout).toMatchInlineSnapshot(`
48
+ const { stdout } = await w(undefined, { tap: true });
49
+
50
+ expect(stdout).toMatchInlineSnapshot(`
17
51
  "wrangler
18
52
 
19
53
  Commands:
@@ -52,32 +86,46 @@ describe("wrangler", () => {
52
86
  it("should create a wrangler.toml", async () => {
53
87
  await w("init");
54
88
  const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
55
- expect(parsed.name).toBe("init");
56
89
  expect(typeof parsed.compatibility_date).toBe("string");
57
90
  });
58
91
 
59
92
  it("should error when wrangler.toml already exists", async () => {
60
93
  fs.closeSync(fs.openSync("./wrangler.toml", "w"));
61
- const { stderr } = await w("init");
94
+ const { stderr } = await w("init", { tap: true });
62
95
  expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
63
96
  });
64
-
65
- it("should create a named config", async () => {
66
- await w("init xyz");
67
- const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
68
- expect(parsed.name).toBe("xyz");
69
- });
70
97
  });
71
98
 
72
99
  describe("kv:namespace", () => {
100
+ afterAll(() => {
101
+ unsetAllMocks();
102
+ });
103
+ let KVNamespaces: { title: string; id: string }[] = [];
73
104
  it("can create a namespace", async () => {
74
- const { stdout } = await w('kv:namespace create "UnitTestNamespace"');
75
- expect(stdout.includes(`{ binding = "UnitTestNamespace",`)).toBe(true);
105
+ setMock("/accounts/:accountId/storage/kv/namespaces", (uri, init) => {
106
+ expect(init.method === "POST");
107
+ const body = JSON.parse(init.body);
108
+ expect(body.title).toBe("worker-UnitTestNamespace");
109
+ KVNamespaces.push({ title: body.title, id: "some-namespace-id" });
110
+ return { id: "some-namespace-id" };
111
+ });
112
+
113
+ await w('kv:namespace create "UnitTestNamespace"');
114
+ expect(
115
+ KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
+ ).toBeTruthy();
76
117
  });
77
118
 
78
119
  let createdNamespace: { id: string; title: string };
79
120
  it("can list namespaces", async () => {
80
- const { stdout } = await w("kv:namespace list");
121
+ setMock(
122
+ "/accounts/:accountId/storage/kv/namespaces\\?:qs",
123
+ (uri, init) => {
124
+ expect(init).toBe(undefined);
125
+ return KVNamespaces;
126
+ }
127
+ );
128
+ const { stdout } = await w("kv:namespace list", { tap: true });
81
129
  const namespaces = JSON.parse(stdout);
82
130
  createdNamespace = namespaces.find(
83
131
  (ns) => ns.title === "worker-UnitTestNamespace"
@@ -86,37 +134,20 @@ describe("wrangler", () => {
86
134
  });
87
135
 
88
136
  it("can delete a namespace", async () => {
89
- const { stdout } = await w(
90
- `kv:namespace delete --namespace-id ${createdNamespace.id}`
137
+ const namespaceIdToDelete = createdNamespace.id;
138
+ setMock(
139
+ "/accounts/:accountId/storage/kv/namespaces/:namespaceId",
140
+ (uri, init) => {
141
+ expect(init.method).toBe("DELETE");
142
+ KVNamespaces = KVNamespaces.filter(
143
+ (ns) => ns.id !== namespaceIdToDelete
144
+ );
145
+ }
146
+ );
147
+ await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
+ expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
+ undefined
91
150
  );
92
- console.log(stdout);
93
- });
94
- });
95
- describe("kv:key", () => {
96
- let namespaceId: string;
97
- beforeAll(async () => {
98
- await w('kv:namespace create "UnitTestNamespace"');
99
- namespaceId = JSON.parse((await w("kv:namespace list")).stdout).find(
100
- (ns) => ns.title === "worker-UnitTestNamespace"
101
- ).id;
102
- });
103
- afterAll(async () => {
104
- await w(`kv:namespace delete --namespace-id ${namespaceId}`);
105
151
  });
106
- it("stub", () => {});
107
- // it("can add a key", () => {});
108
- // it("can read a key", () => {});
109
- // it("can list keys", () => {});
110
- // it("can delete a key", () => {});
111
152
  });
112
-
113
- // describe("login", () => {
114
- // it("should show possible scopes", async () => {
115
- // const { stdout } = await w("login --scopes-list");
116
- // // UGH jest doesn't like wide text huh
117
- // expect(stdout).toMatchInlineSnapshot();
118
- // });
119
- // });
120
-
121
- // TODO: setup a "api server" to mock requests
122
153
  });
@@ -0,0 +1,46 @@
1
+ // This file mocks ../cfetch.ts
2
+ // so we can insert whatever responses we want from it
3
+
4
+ const pathToRegexp = require("path-to-regexp");
5
+ // TODO: add jsdoc style types here
6
+
7
+ // type MockHandler = (resource: string, init?: RequestInit) => any; // TODO: use a generic here
8
+
9
+ let mocks = [];
10
+
11
+ function mockCfetch(resource, init) {
12
+ for (const { regexp, handler } of mocks) {
13
+ if (regexp.test(resource)) {
14
+ return handler(resource, init); // should we have some kind of fallthrough system? we'll see.
15
+ }
16
+ }
17
+ throw new Error(`no mocks found for ${resource}`);
18
+ }
19
+
20
+ function setMock(resource, handler) {
21
+ const mock = {
22
+ resource,
23
+ handler,
24
+ regexp: pathToRegexp(resource),
25
+ };
26
+ mocks.push(mock);
27
+ return () => {
28
+ mocks = mocks.filter((x) => x !== mock);
29
+ };
30
+ }
31
+
32
+ function unsetAllMocks() {
33
+ mocks = [];
34
+ }
35
+
36
+ const CF_API_BASE_URL =
37
+ process.env.CF_API_BASE_URL || "https://api.cloudflare.com/client/v4";
38
+
39
+ Object.assign(module.exports, {
40
+ __esModule: true,
41
+ default: mockCfetch,
42
+ mockCfetch,
43
+ setMock,
44
+ unsetAllMocks,
45
+ CF_API_BASE_URL,
46
+ });
@@ -1,6 +1,6 @@
1
1
  import { main } from ".";
2
2
 
3
- main().catch((cause) => {
3
+ main(process.argv.slice(2)).catch((cause) => {
4
4
  const { name, message } = cause;
5
5
  if (name === "CloudflareError") {
6
6
  console.error("\x1b[31m", message);
package/src/config.ts CHANGED
@@ -64,6 +64,8 @@ type Env = {
64
64
  route?: string; // inherited
65
65
  webpack_config?: string; // inherited
66
66
  site?: Site;
67
+ jsxFactory?: string; // inherited
68
+ jsxFragment?: string; // inherited
67
69
  // we should use typescript to parse cron patterns
68
70
  triggers?: { crons: Cron[] }; // inherited
69
71
  kv_namespaces?: KVNamespace[];
@@ -83,6 +85,8 @@ export type Config = {
83
85
  // -- end mutually exclusive stuff
84
86
  // @deprecated Don't use this
85
87
  webpack_config?: string; // inherited
88
+ jsxFactory?: string; // inherited
89
+ jsxFragment?: string; // inherited
86
90
  vars?: Vars;
87
91
  kv_namespaces?: KVNamespace[];
88
92
  site?: Site; // inherited
package/src/dev.tsx CHANGED
@@ -32,9 +32,11 @@ type Props = {
32
32
  format: CfScriptFormat;
33
33
  accountId: void | string;
34
34
  initialMode: "local" | "remote";
35
- variables?: { [name: string]: CfVariable };
36
- public?: void | string;
37
- site?: void | string;
35
+ jsxFactory: void | string;
36
+ jsxFragment: void | string;
37
+ variables: { [name: string]: CfVariable };
38
+ public: void | string;
39
+ site: void | string;
38
40
  };
39
41
 
40
42
  export function Dev(props: Props): JSX.Element {
@@ -47,7 +49,13 @@ export function Dev(props: Props): JSX.Element {
47
49
  const apiToken = getAPIToken();
48
50
  const directory = useTmpDir();
49
51
 
50
- const bundle = useEsbuild(props.entry, directory, props.public);
52
+ const bundle = useEsbuild({
53
+ entry: props.entry,
54
+ destination: directory,
55
+ staticRoot: props.public,
56
+ jsxFactory: props.jsxFactory,
57
+ jsxFragment: props.jsxFragment,
58
+ });
51
59
  if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
52
60
  throw new Error(
53
61
  "You cannot use the service worker format with a `public` directory."
@@ -322,11 +330,14 @@ type EsbuildBundle = {
322
330
  exports: string[];
323
331
  };
324
332
 
325
- function useEsbuild(
326
- entry: string,
327
- destination: string | void,
328
- staticRoot: void | string
329
- ): EsbuildBundle | void {
333
+ function useEsbuild(props: {
334
+ entry: string;
335
+ destination: string | void;
336
+ staticRoot: void | string;
337
+ jsxFactory: string | void;
338
+ jsxFragment: string | void;
339
+ }): EsbuildBundle | void {
340
+ const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
330
341
  const [bundle, setBundle] = useState<EsbuildBundle>();
331
342
  useEffect(() => {
332
343
  let result: esbuild.BuildResult;
@@ -339,6 +350,11 @@ function useEsbuild(
339
350
  metafile: true,
340
351
  format: "esm",
341
352
  sourcemap: true,
353
+ loader: {
354
+ ".js": "jsx",
355
+ },
356
+ ...(jsxFactory && { jsxFactory }),
357
+ ...(jsxFragment && { jsxFragment }),
342
358
  external: ["__STATIC_CONTENT_MANIFEST"],
343
359
  // TODO: import.meta.url
344
360
  watch: {
@@ -431,6 +447,7 @@ function useWorker(props: {
431
447
  }; // TODO: cancellable?
432
448
 
433
449
  const content = await readFile(bundle.path, "utf-8");
450
+ console.log(content);
434
451
  const init: CfWorkerInit = {
435
452
  main: {
436
453
  name: name || path.basename(bundle.path),
@@ -565,15 +582,15 @@ function useTunnel(toggle: boolean) {
565
582
  // point them to a url where they can get docs to install it
566
583
  useEffect(() => {
567
584
  async function startTunnel() {
568
- try {
569
- await commandExists("cloudflared");
570
- } catch (e) {
571
- console.error(
572
- "Please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
573
- );
574
- return;
575
- }
576
585
  if (toggle) {
586
+ try {
587
+ await commandExists("cloudflared");
588
+ } catch (e) {
589
+ console.error(
590
+ "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
591
+ );
592
+ return;
593
+ }
577
594
  console.log("⎔ Starting a tunnel...");
578
595
  tunnel.current = spawn("cloudflared", [
579
596
  "tunnel",
@@ -0,0 +1,85 @@
1
+ import * as React from "react";
2
+ import { useState } from "react";
3
+ import { Box, Text, useInput, render } from "ink";
4
+ import TextInput from "ink-text-input";
5
+ type ConfirmProps = {
6
+ text: string;
7
+ onConfirm: (answer: boolean) => void | Promise<void>;
8
+ };
9
+ function Confirm(props: ConfirmProps) {
10
+ useInput((input: string) => {
11
+ if (input === "y") {
12
+ props.onConfirm(true);
13
+ } else if (input === "n") {
14
+ props.onConfirm(false);
15
+ } else {
16
+ console.log("Unrecognised input");
17
+ }
18
+ });
19
+ return (
20
+ <Box>
21
+ <Text>{props.text} (y/n) </Text>
22
+ </Box>
23
+ );
24
+ }
25
+
26
+ export function confirm(text: string): Promise<boolean> {
27
+ return new Promise((resolve) => {
28
+ const { unmount } = render(
29
+ <Confirm
30
+ text={text}
31
+ onConfirm={(answer: boolean) => {
32
+ unmount();
33
+ resolve(answer);
34
+ }}
35
+ />
36
+ );
37
+ });
38
+ }
39
+
40
+ type PromptProps = {
41
+ text: string;
42
+ type?: "text" | "password";
43
+ onSubmit: (text: string) => void;
44
+ };
45
+
46
+ export function Prompt(props: PromptProps) {
47
+ const [value, setValue] = useState("");
48
+
49
+ return (
50
+ <Box>
51
+ <Text>{props.text} </Text>
52
+ <Box>
53
+ <TextInput
54
+ mask={props.type === "password" ? "*" : undefined}
55
+ value={value}
56
+ onChange={setValue}
57
+ onSubmit={props.onSubmit}
58
+ />
59
+ </Box>
60
+ </Box>
61
+ );
62
+ }
63
+
64
+ export async function prompt(text: string, type: "text" | "password" = "text") {
65
+ return new Promise((resolve) => {
66
+ const { unmount } = render(
67
+ <Prompt
68
+ text={text}
69
+ type={type}
70
+ onSubmit={(text) => {
71
+ unmount();
72
+ resolve(text);
73
+ }}
74
+ />
75
+ );
76
+ });
77
+ }
78
+
79
+ // this one feels a little non "standard"
80
+ // export async function select(
81
+ // title: string,
82
+ // choices: { label: string; value: string }[]
83
+ // ): Promise<{ label: string; value: string }>{
84
+
85
+ // }