wrangler 0.0.0-ece06ea → 0.0.0-edc4b53

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 (41) hide show
  1. package/package.json +24 -15
  2. package/pages/functions/buildWorker.ts +62 -0
  3. package/pages/functions/filepath-routing.test.ts +39 -0
  4. package/pages/functions/filepath-routing.ts +221 -0
  5. package/pages/functions/identifiers.ts +78 -0
  6. package/pages/functions/routes.ts +158 -0
  7. package/pages/functions/template-worker.ts +144 -0
  8. package/src/__tests__/dev.test.tsx +66 -0
  9. package/src/__tests__/index.test.ts +254 -120
  10. package/src/__tests__/jest.setup.ts +22 -0
  11. package/src/__tests__/kv.test.ts +1106 -0
  12. package/src/__tests__/mock-cfetch.ts +171 -0
  13. package/src/__tests__/mock-dialogs.ts +65 -0
  14. package/src/__tests__/run-in-tmp.ts +19 -0
  15. package/src/__tests__/run-wrangler.ts +32 -0
  16. package/src/api/form_data.ts +71 -98
  17. package/src/api/preview.ts +29 -24
  18. package/src/api/worker.ts +38 -44
  19. package/src/cfetch/index.ts +102 -0
  20. package/src/cfetch/internal.ts +65 -0
  21. package/src/cli.ts +6 -7
  22. package/src/config.ts +476 -113
  23. package/src/dev.tsx +291 -256
  24. package/src/dialogs.tsx +4 -12
  25. package/src/index.tsx +381 -252
  26. package/src/inspect.ts +524 -0
  27. package/src/kv.tsx +110 -45
  28. package/src/module-collection.ts +64 -0
  29. package/src/pages.tsx +900 -213
  30. package/src/proxy.ts +294 -0
  31. package/src/publish.ts +67 -63
  32. package/src/sites.tsx +10 -7
  33. package/src/tail.tsx +5 -3
  34. package/src/user.tsx +31 -33
  35. package/wrangler-dist/cli.js +43444 -56347
  36. package/wrangler-dist/cli.js.map +3 -3
  37. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  38. package/src/__tests__/mock-cfetch.js +0 -46
  39. package/src/api/inspect.ts +0 -441
  40. package/src/cfetch.ts +0 -72
  41. package/src/util/fetch.ts +0 -74
@@ -0,0 +1,144 @@
1
+ import { match } from "path-to-regexp";
2
+ import type { HTTPMethod } from "./routes";
3
+
4
+ /* TODO: Grab these from @cloudflare/workers-types instead */
5
+ type Params<P extends string = string> = Record<P, string | string[]>;
6
+
7
+ type EventContext<Env, P extends string, Data> = {
8
+ request: Request;
9
+ waitUntil: (promise: Promise<unknown>) => void;
10
+ next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
11
+ env: Env & { ASSETS: { fetch: typeof fetch } };
12
+ params: Params<P>;
13
+ data: Data;
14
+ };
15
+
16
+ declare type PagesFunction<
17
+ Env = unknown,
18
+ P extends string = string,
19
+ Data extends Record<string, unknown> = Record<string, unknown>
20
+ > = (context: EventContext<Env, P, Data>) => Response | Promise<Response>;
21
+ /* end @cloudflare/workers-types */
22
+
23
+ type RouteHandler = {
24
+ routePath: string;
25
+ methods: HTTPMethod[];
26
+ modules: PagesFunction[];
27
+ middlewares: PagesFunction[];
28
+ };
29
+
30
+ // inject `routes` via ESBuild
31
+ declare const routes: RouteHandler[];
32
+ // define `__FALLBACK_SERVICE__` via ESBuild
33
+ declare const __FALLBACK_SERVICE__: string;
34
+
35
+ // expect an ASSETS fetcher binding pointing to the asset-server stage
36
+ type Env = {
37
+ [name: string]: unknown;
38
+ ASSETS: { fetch(url: string, init: RequestInit): Promise<Response> };
39
+ };
40
+
41
+ type WorkerContext = {
42
+ waitUntil: (promise: Promise<unknown>) => void;
43
+ };
44
+
45
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- `env` can be used by __FALLBACK_SERVICE_FETCH__
46
+ function* executeRequest(request: Request, env: Env) {
47
+ const requestPath = new URL(request.url).pathname;
48
+
49
+ // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
50
+ for (const route of [...routes].reverse()) {
51
+ if (
52
+ route.methods.length &&
53
+ !route.methods.includes(request.method as HTTPMethod)
54
+ ) {
55
+ continue;
56
+ }
57
+
58
+ const routeMatcher = match(route.routePath, { end: false });
59
+ const matchResult = routeMatcher(requestPath);
60
+ if (matchResult) {
61
+ for (const handler of route.middlewares.flat()) {
62
+ yield {
63
+ handler,
64
+ params: matchResult.params as Params,
65
+ };
66
+ }
67
+ }
68
+ }
69
+
70
+ // Then look for the first exact route match and execute its "modules"
71
+ for (const route of routes) {
72
+ if (
73
+ route.methods.length &&
74
+ !route.methods.includes(request.method as HTTPMethod)
75
+ ) {
76
+ continue;
77
+ }
78
+
79
+ const routeMatcher = match(route.routePath, { end: true });
80
+ const matchResult = routeMatcher(requestPath);
81
+ if (matchResult && route.modules.length) {
82
+ for (const handler of route.modules.flat()) {
83
+ yield {
84
+ handler,
85
+ params: matchResult.params as Params,
86
+ };
87
+ }
88
+ break;
89
+ }
90
+ }
91
+
92
+ // Finally, yield to the fallback service (`env.ASSETS.fetch` in Pages' case)
93
+ return {
94
+ handler: () =>
95
+ __FALLBACK_SERVICE__
96
+ ? // @ts-expect-error expecting __FALLBACK_SERVICE__ to be the name of a service binding, so fetch should be defined
97
+ env[__FALLBACK_SERVICE__].fetch(request)
98
+ : fetch(request),
99
+ params: {} as Params,
100
+ };
101
+ }
102
+
103
+ export default {
104
+ async fetch(request: Request, env: Env, workerContext: WorkerContext) {
105
+ const handlerIterator = executeRequest(request, env);
106
+ const data = {}; // arbitrary data the user can set between functions
107
+ const next = async (input?: RequestInfo, init?: RequestInit) => {
108
+ if (input !== undefined) {
109
+ request = new Request(input, init);
110
+ }
111
+
112
+ const { value } = handlerIterator.next();
113
+ if (value) {
114
+ const { handler, params } = value;
115
+ const context: EventContext<
116
+ unknown,
117
+ string,
118
+ Record<string, unknown>
119
+ > = {
120
+ request: new Request(request.clone()),
121
+ next,
122
+ params,
123
+ data,
124
+ env,
125
+ waitUntil: workerContext.waitUntil.bind(workerContext),
126
+ };
127
+
128
+ const response = await handler(context);
129
+
130
+ // https://fetch.spec.whatwg.org/#null-body-status
131
+ return new Response(
132
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
133
+ response
134
+ );
135
+ }
136
+ };
137
+
138
+ try {
139
+ return next();
140
+ } catch (err) {
141
+ return new Response("Internal Error", { status: 500 });
142
+ }
143
+ },
144
+ };
@@ -0,0 +1,66 @@
1
+ import { render } from "ink-testing-library";
2
+ import patchConsole from "patch-console";
3
+ import React from "react";
4
+ import Dev from "../dev";
5
+ import type { DevProps } from "../dev";
6
+
7
+ describe("Dev component", () => {
8
+ let restoreConsole;
9
+ beforeEach(() => (restoreConsole = patchConsole(() => {})));
10
+ afterEach(() => restoreConsole());
11
+
12
+ it("should throw if format is service-worker and there is a public directory", () => {
13
+ const { lastFrame } = renderDev({
14
+ format: "service-worker",
15
+ accountId: "some-account-id",
16
+ public: "some/public/path",
17
+ });
18
+ expect(lastFrame()).toMatchInlineSnapshot(`
19
+ "Something went wrong:
20
+ You cannot use the service worker format with a \`public\` directory."
21
+ `);
22
+ });
23
+ });
24
+
25
+ /**
26
+ * Helper function to make it easier to setup and render the `Dev` component.
27
+ *
28
+ * All the `Dev` props are optional here, with sensible defaults for testing.
29
+ */
30
+ function renderDev({
31
+ name,
32
+ entry = "some/entry.ts",
33
+ port,
34
+ format,
35
+ accountId,
36
+ initialMode = "remote",
37
+ jsxFactory,
38
+ jsxFragment,
39
+ bindings = {},
40
+ public: publicDir,
41
+ site,
42
+ compatibilityDate,
43
+ compatibilityFlags,
44
+ usageModel,
45
+ buildCommand = {},
46
+ }: Partial<DevProps>) {
47
+ return render(
48
+ <Dev
49
+ name={name}
50
+ entry={entry}
51
+ port={port}
52
+ buildCommand={buildCommand}
53
+ format={format}
54
+ initialMode={initialMode}
55
+ jsxFactory={jsxFactory}
56
+ jsxFragment={jsxFragment}
57
+ accountId={accountId}
58
+ site={site}
59
+ public={publicDir}
60
+ compatibilityDate={compatibilityDate}
61
+ compatibilityFlags={compatibilityFlags}
62
+ usageModel={usageModel}
63
+ bindings={bindings}
64
+ />
65
+ );
66
+ }
@@ -1,153 +1,287 @@
1
- import * as fs from "node:fs";
2
1
  import * as fsp from "node:fs/promises";
3
- import * as path from "node:path";
4
2
  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";
3
+ import { mockConfirm } from "./mock-dialogs";
4
+ import { runWrangler } from "./run-wrangler";
5
+ import { runInTempDir } from "./run-in-tmp";
6
+ import * as fs from "node:fs";
8
7
 
9
- jest.mock("../cfetch", () => {
10
- return jest.requireActual("./mock-cfetch");
11
- });
8
+ describe("wrangler", () => {
9
+ runInTempDir();
12
10
 
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;
44
- }
11
+ describe("no command", () => {
12
+ it("should display a list of available commands", async () => {
13
+ const { stdout, stderr } = await runWrangler();
45
14
 
46
- describe("wrangler", () => {
47
- it("should run", async () => {
48
- const { stdout } = await w(undefined, { tap: true });
49
-
50
- expect(stdout).toMatchInlineSnapshot(`
51
- "wrangler
52
-
53
- Commands:
54
- wrangler init [name] 📥 Create a wrangler.toml configuration file
55
- wrangler dev <filename> 👂 Start a local server for developing your worker
56
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
57
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
58
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
59
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
60
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
61
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
62
- wrangler pages ⚡️ Configure Cloudflare Pages
63
-
64
- Flags:
65
- --config Path to .toml configuration file [string]
66
- --help Show help [boolean]
67
- --version Show version number [boolean]
68
-
69
- Options:
70
- --local Run on my machine [boolean] [default: false]"
71
- `);
72
- });
15
+ expect(stdout).toMatchInlineSnapshot(`
16
+ "wrangler
73
17
 
74
- describe("init", () => {
75
- const ogcwd = process.cwd();
18
+ Commands:
19
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
20
+ wrangler dev <filename> 👂 Start a local server for developing your worker
21
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
22
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
23
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
24
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
25
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
26
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
27
+ wrangler pages ⚡️ Configure Cloudflare Pages
28
+
29
+ Flags:
30
+ -c, --config Path to .toml configuration file [string]
31
+ -h, --help Show help [boolean]
32
+ -v, --version Show version number [boolean]
33
+
34
+ Options:
35
+ -l, --local Run on my machine [boolean] [default: false]"
36
+ `);
76
37
 
77
- beforeEach(() => {
78
- process.chdir(path.join(__dirname, "fixtures", "init"));
38
+ expect(stderr).toMatchInlineSnapshot(`""`);
79
39
  });
40
+ });
41
+
42
+ describe("invalid command", () => {
43
+ it("should display an error", async () => {
44
+ const { error, stdout, stderr } = await runWrangler("invalid-command");
45
+
46
+ expect(stdout).toMatchInlineSnapshot(`""`);
47
+ expect(stderr).toMatchInlineSnapshot(`
48
+ "wrangler
49
+
50
+ Commands:
51
+ wrangler init [name] 📥 Create a wrangler.toml configuration file
52
+ wrangler dev <filename> 👂 Start a local server for developing your worker
53
+ wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
54
+ wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
55
+ wrangler secret 🤫 Generate a secret that can be referenced in the worker script
56
+ wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
57
+ wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
58
+ wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
59
+ wrangler pages ⚡️ Configure Cloudflare Pages
80
60
 
81
- afterEach(async () => {
82
- await fsp.rm("./wrangler.toml");
83
- process.chdir(ogcwd);
61
+ Flags:
62
+ -c, --config Path to .toml configuration file [string]
63
+ -h, --help Show help [boolean]
64
+ -v, --version Show version number [boolean]
65
+
66
+ Options:
67
+ -l, --local Run on my machine [boolean] [default: false]
68
+
69
+ Unknown command: invalid-command."
70
+ `);
71
+ expect(error).toMatchInlineSnapshot(
72
+ `[Error: Unknown command: invalid-command.]`
73
+ );
84
74
  });
75
+ });
85
76
 
77
+ describe("init", () => {
86
78
  it("should create a wrangler.toml", async () => {
87
- await w("init");
79
+ mockConfirm({
80
+ text: "No package.json found. Would you like to create one?",
81
+ result: false,
82
+ });
83
+ await runWrangler("init");
88
84
  const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
89
85
  expect(typeof parsed.compatibility_date).toBe("string");
86
+ expect(fs.existsSync("./package.json")).toBe(false);
87
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
90
88
  });
91
89
 
92
- it("should error when wrangler.toml already exists", async () => {
93
- fs.closeSync(fs.openSync("./wrangler.toml", "w"));
94
- const { stderr } = await w("init", { tap: true });
95
- expect(stderr.endsWith("wrangler.toml already exists.")).toBe(true);
90
+ it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
91
+ fs.writeFileSync("./wrangler.toml", "", "utf-8");
92
+ mockConfirm({
93
+ text: "Do you want to continue initializing this project?",
94
+ result: false,
95
+ });
96
+ const { warnings } = await runWrangler("init");
97
+ expect(warnings).toContain("wrangler.toml file already exists!");
98
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
99
+ expect(typeof parsed.compatibility_date).toBe("undefined");
96
100
  });
97
- });
98
101
 
99
- describe("kv:namespace", () => {
100
- afterAll(() => {
101
- unsetAllMocks();
102
+ it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
103
+ fs.writeFileSync("./wrangler.toml", "", "utf-8");
104
+ mockConfirm(
105
+ {
106
+ text: "Do you want to continue initializing this project?",
107
+ result: true,
108
+ },
109
+ {
110
+ text: "No package.json found. Would you like to create one?",
111
+ result: false,
112
+ }
113
+ );
114
+ const { warnings } = await runWrangler("init");
115
+ expect(warnings).toContain("wrangler.toml file already exists!");
116
+ const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
117
+ expect(typeof parsed.compatibility_date).toBe("string");
118
+ });
119
+
120
+ it("should create a package.json if none is found and user confirms", async () => {
121
+ mockConfirm(
122
+ {
123
+ text: "No package.json found. Would you like to create one?",
124
+ result: true,
125
+ },
126
+ {
127
+ text: "Would you like to use typescript?",
128
+ result: false,
129
+ }
130
+ );
131
+ await runWrangler("init");
132
+ expect(fs.existsSync("./package.json")).toBe(true);
133
+ const packageJson = JSON.parse(
134
+ fs.readFileSync("./package.json", "utf-8")
135
+ );
136
+ expect(packageJson.name).toEqual("worker"); // TODO: should we infer the name from the directory?
137
+ expect(packageJson.version).toEqual("0.0.1");
138
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
139
+ });
140
+
141
+ it("should not touch an existing package.json in the same directory", async () => {
142
+ mockConfirm({
143
+ text: "Would you like to use typescript?",
144
+ result: false,
145
+ });
146
+
147
+ fs.writeFileSync(
148
+ "./package.json",
149
+ JSON.stringify({ name: "test", version: "1.0.0" }),
150
+ "utf-8"
151
+ );
152
+
153
+ await runWrangler("init");
154
+ const packageJson = JSON.parse(
155
+ fs.readFileSync("./package.json", "utf-8")
156
+ );
157
+ expect(packageJson.name).toEqual("test");
158
+ expect(packageJson.version).toEqual("1.0.0");
102
159
  });
103
- let KVNamespaces: { title: string; id: string }[] = [];
104
- it("can create a namespace", async () => {
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" };
160
+
161
+ it("should not touch an existing package.json in an ancestor directory", async () => {
162
+ mockConfirm({
163
+ text: "Would you like to use typescript?",
164
+ result: false,
111
165
  });
112
166
 
113
- await w("kv:namespace create UnitTestNamespace");
114
- expect(
115
- KVNamespaces.find((ns) => ns.title === `worker-UnitTestNamespace`)
116
- ).toBeTruthy();
167
+ fs.writeFileSync(
168
+ "./package.json",
169
+ JSON.stringify({ name: "test", version: "1.0.0" }),
170
+ "utf-8"
171
+ );
172
+
173
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
174
+ process.chdir("./sub-1/sub-2");
175
+
176
+ await runWrangler("init");
177
+ expect(fs.existsSync("./package.json")).toBe(false);
178
+ expect(fs.existsSync("../../package.json")).toBe(true);
179
+
180
+ const packageJson = JSON.parse(
181
+ fs.readFileSync("../../package.json", "utf-8")
182
+ );
183
+ expect(packageJson.name).toEqual("test");
184
+ expect(packageJson.version).toEqual("1.0.0");
117
185
  });
118
186
 
119
- let createdNamespace: { id: string; title: string };
120
- it("can list namespaces", async () => {
121
- setMock(
122
- "/accounts/:accountId/storage/kv/namespaces\\?:qs",
123
- (uri, init) => {
124
- expect(init).toBe(undefined);
125
- return KVNamespaces;
187
+ it("should create a tsconfig.json and install `workers-types` if none is found and user confirms", async () => {
188
+ mockConfirm(
189
+ {
190
+ text: "No package.json found. Would you like to create one?",
191
+ result: true,
192
+ },
193
+ {
194
+ text: "Would you like to use typescript?",
195
+ result: true,
126
196
  }
127
197
  );
128
- const { stdout } = await w("kv:namespace list", { tap: true });
129
- const namespaces = JSON.parse(stdout);
130
- createdNamespace = namespaces.find(
131
- (ns) => ns.title === "worker-UnitTestNamespace"
198
+ await runWrangler("init");
199
+ expect(fs.existsSync("./tsconfig.json")).toBe(true);
200
+ const tsconfigJson = JSON.parse(
201
+ fs.readFileSync("./tsconfig.json", "utf-8")
202
+ );
203
+ expect(tsconfigJson.compilerOptions.types).toEqual([
204
+ "@cloudflare/workers-types",
205
+ ]);
206
+ const packageJson = JSON.parse(
207
+ fs.readFileSync("./package.json", "utf-8")
132
208
  );
133
- expect(createdNamespace.title).toBe("worker-UnitTestNamespace");
209
+ expect(packageJson.devDependencies).toEqual({
210
+ "@cloudflare/workers-types": expect.any(String),
211
+ });
134
212
  });
135
213
 
136
- it("can delete a namespace", async () => {
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
- }
214
+ it("should not touch an existing tsconfig.json in the same directory", async () => {
215
+ fs.writeFileSync(
216
+ "./package.json",
217
+ JSON.stringify({ name: "test", version: "1.0.0" }),
218
+ "utf-8"
219
+ );
220
+ fs.writeFileSync(
221
+ "./tsconfig.json",
222
+ JSON.stringify({ compilerOptions: {} }),
223
+ "utf-8"
224
+ );
225
+
226
+ await runWrangler("init");
227
+ const tsconfigJson = JSON.parse(
228
+ fs.readFileSync("./tsconfig.json", "utf-8")
229
+ );
230
+ expect(tsconfigJson.compilerOptions).toEqual({});
231
+ });
232
+
233
+ it("should not touch an existing package.json in an ancestor directory", async () => {
234
+ fs.writeFileSync(
235
+ "./package.json",
236
+ JSON.stringify({ name: "test", version: "1.0.0" }),
237
+ "utf-8"
238
+ );
239
+ fs.writeFileSync(
240
+ "./tsconfig.json",
241
+ JSON.stringify({ compilerOptions: {} }),
242
+ "utf-8"
146
243
  );
147
- await w(`kv:namespace delete --namespace-id ${namespaceIdToDelete}`);
148
- expect(KVNamespaces.find((ns) => ns.id === namespaceIdToDelete)).toBe(
149
- undefined
244
+
245
+ fs.mkdirSync("./sub-1/sub-2", { recursive: true });
246
+ process.chdir("./sub-1/sub-2");
247
+
248
+ await runWrangler("init");
249
+ expect(fs.existsSync("./tsconfig.json")).toBe(false);
250
+ expect(fs.existsSync("../../tsconfig.json")).toBe(true);
251
+
252
+ const tsconfigJson = JSON.parse(
253
+ fs.readFileSync("../../tsconfig.json", "utf-8")
254
+ );
255
+ expect(tsconfigJson.compilerOptions).toEqual({});
256
+ });
257
+
258
+ it("should error if `--type` is used", async () => {
259
+ const { error } = await runWrangler("init --type");
260
+ expect(error).toMatchInlineSnapshot(
261
+ `[Error: The --type option is no longer supported.]`
150
262
  );
151
263
  });
264
+
265
+ it("should error if `--type javascript` is used", async () => {
266
+ const { error } = await runWrangler("init --type javascript");
267
+ expect(error).toMatchInlineSnapshot(
268
+ `[Error: The --type option is no longer supported.]`
269
+ );
270
+ });
271
+
272
+ it("should error if `--type rust` is used", async () => {
273
+ const { error } = await runWrangler("init --type rust");
274
+ expect(error).toMatchInlineSnapshot(
275
+ `[Error: The --type option is no longer supported.]`
276
+ );
277
+ });
278
+
279
+ it("should error if `--type webpack` is used", async () => {
280
+ const { error } = await runWrangler("init --type webpack");
281
+ expect(error).toMatchInlineSnapshot(`
282
+ [Error: The --type option is no longer supported.
283
+ If you wish to use webpack then you will need to create a custom build.]
284
+ `);
285
+ });
152
286
  });
153
287
  });
@@ -0,0 +1,22 @@
1
+ import { mockFetchInternal } from "./mock-cfetch";
2
+ import { confirm, prompt } from "../dialogs";
3
+ import { fetchInternal } from "../cfetch/internal";
4
+
5
+ jest.mock("../cfetch/internal");
6
+ (fetchInternal as jest.Mock).mockImplementation(mockFetchInternal);
7
+
8
+ jest.mock("../dialogs");
9
+
10
+ // By default (if not configured by mockConfirm()) calls to `confirm()` should throw.
11
+ (confirm as jest.Mock).mockImplementation(() => {
12
+ throw new Error(
13
+ "Unexpected call to `confirm()`. You should use `mockConfirm()` to mock calls to `confirm()` with expectations. Search the codebase for `mockConfirm` to learn more."
14
+ );
15
+ });
16
+
17
+ // By default (if not configured by mockPrompt()) calls to `prompt()` should throw.
18
+ (prompt as jest.Mock).mockImplementation(() => {
19
+ throw new Error(
20
+ "Unexpected call to `prompt()`. You should use `mockPrompt()` to mock calls to `prompt()` with expectations. Search the codebase for `mockPrompt` to learn more."
21
+ );
22
+ });