wrangler 0.0.0-e0d2f35 → 0.0.0-e101451a2

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 (132) hide show
  1. package/README.md +44 -25
  2. package/bin/wrangler.js +88 -31
  3. package/config-schema.json +3354 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +148 -94
  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 +19 -0
  11. package/templates/gitignore +170 -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 +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  27. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  28. package/templates/modules-watch-stub.js +4 -0
  29. package/templates/new-worker-scheduled.js +17 -0
  30. package/templates/new-worker-scheduled.ts +32 -0
  31. package/templates/new-worker.js +15 -0
  32. package/templates/new-worker.ts +33 -0
  33. package/templates/no-op-worker.js +10 -0
  34. package/templates/pages-dev-pipeline.ts +33 -0
  35. package/templates/pages-dev-util.ts +55 -0
  36. package/templates/pages-shim.ts +9 -0
  37. package/templates/pages-template-plugin.ts +190 -0
  38. package/templates/pages-template-worker.ts +198 -0
  39. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  40. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  41. package/templates/strip-cf-connecting-ip-header.js +13 -0
  42. package/templates/tsconfig-sanity.ts +11 -0
  43. package/templates/tsconfig.init.json +22 -0
  44. package/templates/tsconfig.json +15 -0
  45. package/templates/tsconfig.tsbuildinfo +1 -0
  46. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  47. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  48. package/wrangler-dist/ProxyWorker.js +241 -0
  49. package/wrangler-dist/ProxyWorker.js.map +6 -0
  50. package/wrangler-dist/cli.d.ts +26860 -0
  51. package/wrangler-dist/cli.js +152497 -118904
  52. package/import_meta_url.js +0 -3
  53. package/miniflare-config-stubs/.env.empty +0 -0
  54. package/miniflare-config-stubs/package.empty.json +0 -1
  55. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -39
  58. package/pages/functions/filepath-routing.ts +0 -228
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -158
  61. package/pages/functions/template-worker.ts +0 -136
  62. package/src/__tests__/clipboardy-mock.js +0 -4
  63. package/src/__tests__/dev.test.tsx +0 -71
  64. package/src/__tests__/index.test.ts +0 -424
  65. package/src/__tests__/jest.setup.ts +0 -29
  66. package/src/__tests__/kv.test.ts +0 -1224
  67. package/src/__tests__/logout.test.ts +0 -64
  68. package/src/__tests__/mock-cfetch.ts +0 -173
  69. package/src/__tests__/mock-console.ts +0 -34
  70. package/src/__tests__/mock-dialogs.ts +0 -65
  71. package/src/__tests__/mock-kv.ts +0 -40
  72. package/src/__tests__/mock-user.ts +0 -27
  73. package/src/__tests__/publish.test.ts +0 -1206
  74. package/src/__tests__/run-in-tmp.ts +0 -29
  75. package/src/__tests__/run-wrangler.ts +0 -8
  76. package/src/__tests__/secret.test.ts +0 -206
  77. package/src/__tests__/whoami.test.tsx +0 -101
  78. package/src/api/form_data.ts +0 -135
  79. package/src/api/preview.ts +0 -128
  80. package/src/api/worker.ts +0 -155
  81. package/src/cfetch/index.ts +0 -111
  82. package/src/cfetch/internal.ts +0 -71
  83. package/src/cli.ts +0 -9
  84. package/src/config.ts +0 -641
  85. package/src/dev.tsx +0 -830
  86. package/src/dialogs.tsx +0 -77
  87. package/src/index.tsx +0 -2078
  88. package/src/inspect.ts +0 -595
  89. package/src/kv.tsx +0 -276
  90. package/src/module-collection.ts +0 -63
  91. package/src/pages.tsx +0 -1043
  92. package/src/proxy.ts +0 -370
  93. package/src/publish.ts +0 -410
  94. package/src/sites.tsx +0 -240
  95. package/src/tail.tsx +0 -73
  96. package/src/user.tsx +0 -1019
  97. package/src/whoami.tsx +0 -69
  98. package/static-asset-facade.js +0 -47
  99. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  100. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  101. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  102. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  103. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  104. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  105. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  106. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  107. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  108. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  109. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  110. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  111. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  112. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  113. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  114. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  115. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  116. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  117. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  118. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  119. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  120. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  121. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  122. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  123. package/vendor/wrangler-mime/LICENSE +0 -21
  124. package/vendor/wrangler-mime/Mime.js +0 -97
  125. package/vendor/wrangler-mime/README.md +0 -187
  126. package/vendor/wrangler-mime/cli.js +0 -46
  127. package/vendor/wrangler-mime/index.js +0 -4
  128. package/vendor/wrangler-mime/lite.js +0 -4
  129. package/vendor/wrangler-mime/package.json +0 -52
  130. package/vendor/wrangler-mime/types/other.js +0 -1
  131. package/vendor/wrangler-mime/types/standard.js +0 -1
  132. package/wrangler-dist/cli.js.map +0 -7
@@ -1,136 +0,0 @@
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 FetchEnv = {
37
- [name: string]: { fetch: typeof fetch };
38
- ASSETS: { fetch: typeof fetch };
39
- };
40
-
41
- type WorkerContext = {
42
- waitUntil: (promise: Promise<unknown>) => void;
43
- };
44
-
45
- function* executeRequest(request: Request, _env: FetchEnv) {
46
- const requestPath = new URL(request.url).pathname;
47
-
48
- // First, iterate through the routes (backwards) and execute "middlewares" on partial route matches
49
- for (const route of [...routes].reverse()) {
50
- if (
51
- route.methods.length &&
52
- !route.methods.includes(request.method as HTTPMethod)
53
- ) {
54
- continue;
55
- }
56
-
57
- const routeMatcher = match(route.routePath, { end: false });
58
- const matchResult = routeMatcher(requestPath);
59
- if (matchResult) {
60
- for (const handler of route.middlewares.flat()) {
61
- yield {
62
- handler,
63
- params: matchResult.params as Params,
64
- };
65
- }
66
- }
67
- }
68
-
69
- // Then look for the first exact route match and execute its "modules"
70
- for (const route of routes) {
71
- if (
72
- route.methods.length &&
73
- !route.methods.includes(request.method as HTTPMethod)
74
- ) {
75
- continue;
76
- }
77
-
78
- const routeMatcher = match(route.routePath, { end: true });
79
- const matchResult = routeMatcher(requestPath);
80
- if (matchResult && route.modules.length) {
81
- for (const handler of route.modules.flat()) {
82
- yield {
83
- handler,
84
- params: matchResult.params as Params,
85
- };
86
- }
87
- break;
88
- }
89
- }
90
- }
91
-
92
- export default {
93
- async fetch(request: Request, env: FetchEnv, workerContext: WorkerContext) {
94
- const handlerIterator = executeRequest(request, env);
95
- const data = {}; // arbitrary data the user can set between functions
96
- const next = async (input?: RequestInfo, init?: RequestInit) => {
97
- if (input !== undefined) {
98
- request = new Request(input, init);
99
- }
100
-
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 = {
106
- request: new Request(request.clone()),
107
- next,
108
- params,
109
- data,
110
- env,
111
- waitUntil: workerContext.waitUntil.bind(workerContext),
112
- };
113
-
114
- const response = await handler(context);
115
-
116
- // https://fetch.spec.whatwg.org/#null-body-status
117
- return new Response(
118
- [101, 204, 205, 304].includes(response.status) ? null : response.body,
119
- response
120
- );
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
- }
128
- };
129
-
130
- try {
131
- return next();
132
- } catch (err) {
133
- return new Response("Internal Error", { status: 500 });
134
- }
135
- },
136
- };
@@ -1,4 +0,0 @@
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,71 +0,0 @@
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()?.split("\n").slice(0, 2).join("\n"))
19
- .toMatchInlineSnapshot(`
20
- "Something went wrong:
21
- Error: You cannot use the service worker format with a \`public\` directory."
22
- `);
23
- });
24
- });
25
-
26
- /**
27
- * Helper function to make it easier to setup and render the `Dev` component.
28
- *
29
- * All the `Dev` props are optional here, with sensible defaults for testing.
30
- */
31
- function renderDev({
32
- name,
33
- entry = "some/entry.ts",
34
- port,
35
- format,
36
- accountId,
37
- initialMode = "remote",
38
- jsxFactory,
39
- jsxFragment,
40
- bindings = {},
41
- public: publicDir,
42
- assetPaths,
43
- compatibilityDate,
44
- compatibilityFlags,
45
- usageModel,
46
- buildCommand = {},
47
- enableLocalPersistence = false,
48
- env = undefined,
49
- }: Partial<DevProps>) {
50
- return render(
51
- <Dev
52
- name={name}
53
- entry={entry}
54
- env={env}
55
- port={port}
56
- buildCommand={buildCommand}
57
- format={format}
58
- initialMode={initialMode}
59
- jsxFactory={jsxFactory}
60
- jsxFragment={jsxFragment}
61
- accountId={accountId}
62
- assetPaths={assetPaths}
63
- public={publicDir}
64
- compatibilityDate={compatibilityDate}
65
- compatibilityFlags={compatibilityFlags}
66
- usageModel={usageModel}
67
- bindings={bindings}
68
- enableLocalPersistence={enableLocalPersistence}
69
- />
70
- );
71
- }
@@ -1,424 +0,0 @@
1
- import * as fsp from "node:fs/promises";
2
- import * as TOML from "@iarna/toml";
3
- import { mockConfirm } from "./mock-dialogs";
4
- import { runWrangler } from "./run-wrangler";
5
- import { runInTempDir } from "./run-in-tmp";
6
- import { mockConsoleMethods } from "./mock-console";
7
- import * as fs from "node:fs";
8
-
9
- describe("wrangler", () => {
10
- runInTempDir();
11
-
12
- const std = mockConsoleMethods();
13
-
14
- describe("no command", () => {
15
- it("should display a list of available commands", async () => {
16
- await runWrangler();
17
-
18
- expect(std.out).toMatchInlineSnapshot(`
19
- "wrangler
20
-
21
- Commands:
22
- wrangler init [name] 📥 Create a wrangler.toml configuration file
23
- wrangler whoami 🕵️ Retrieve your user info and test your auth config
24
- wrangler dev <filename> 👂 Start a local server for developing your worker
25
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
26
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
27
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
28
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
29
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
30
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
31
- wrangler pages ⚡️ Configure Cloudflare Pages
32
-
33
- Flags:
34
- -c, --config Path to .toml configuration file [string]
35
- -h, --help Show help [boolean]
36
- -v, --version Show version number [boolean]
37
-
38
- Options:
39
- -l, --local Run on my machine [boolean] [default: false]"
40
- `);
41
-
42
- expect(std.err).toMatchInlineSnapshot(`""`);
43
- });
44
- });
45
-
46
- describe("invalid command", () => {
47
- it("should display an error", async () => {
48
- let err: Error | undefined;
49
- try {
50
- await runWrangler("invalid-command");
51
- } catch (e) {
52
- err = e;
53
- } finally {
54
- expect(err?.message).toBe(`Unknown command: invalid-command.`);
55
- }
56
-
57
- expect(std.out).toMatchInlineSnapshot(`""`);
58
- expect(std.err).toMatchInlineSnapshot(`
59
- "wrangler
60
-
61
- Commands:
62
- wrangler init [name] 📥 Create a wrangler.toml configuration file
63
- wrangler whoami 🕵️ Retrieve your user info and test your auth config
64
- wrangler dev <filename> 👂 Start a local server for developing your worker
65
- wrangler publish [script] 🆙 Publish your Worker to Cloudflare.
66
- wrangler tail [name] 🦚 Starts a log tailing session for a deployed Worker.
67
- wrangler secret 🤫 Generate a secret that can be referenced in the worker script
68
- wrangler kv:namespace 🗂️ Interact with your Workers KV Namespaces
69
- wrangler kv:key 🔑 Individually manage Workers KV key-value pairs
70
- wrangler kv:bulk 💪 Interact with multiple Workers KV key-value pairs at once
71
- wrangler pages ⚡️ Configure Cloudflare Pages
72
-
73
- Flags:
74
- -c, --config Path to .toml configuration file [string]
75
- -h, --help Show help [boolean]
76
- -v, --version Show version number [boolean]
77
-
78
- Options:
79
- -l, --local Run on my machine [boolean] [default: false]
80
-
81
- Unknown command: invalid-command."
82
- `);
83
- });
84
- });
85
-
86
- describe("init", () => {
87
- it("should create a wrangler.toml", async () => {
88
- mockConfirm({
89
- text: "No package.json found. Would you like to create one?",
90
- result: false,
91
- });
92
- await runWrangler("init");
93
- const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
94
- expect(typeof parsed.compatibility_date).toBe("string");
95
- expect(fs.existsSync("./package.json")).toBe(false);
96
- expect(fs.existsSync("./tsconfig.json")).toBe(false);
97
- });
98
-
99
- it("should display warning when wrangler.toml already exists, and exit if user does not want to carry on", async () => {
100
- fs.writeFileSync(
101
- "./wrangler.toml",
102
- 'compatibility_date="something-else"', // use a fake value to make sure the file is not overwritten
103
- "utf-8"
104
- );
105
- mockConfirm({
106
- text: "Do you want to continue initializing this project?",
107
- result: false,
108
- });
109
- await runWrangler("init");
110
- expect(std.warn).toContain("wrangler.toml file already exists!");
111
- const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
112
- expect(parsed.compatibility_date).toBe("something-else");
113
- });
114
-
115
- it("should display warning when wrangler.toml already exists, but continue if user does want to carry on", async () => {
116
- fs.writeFileSync(
117
- "./wrangler.toml",
118
- `compatibility_date="something-else"`,
119
- "utf-8"
120
- );
121
- mockConfirm(
122
- {
123
- text: "Do you want to continue initializing this project?",
124
- result: true,
125
- },
126
- {
127
- text: "No package.json found. Would you like to create one?",
128
- result: false,
129
- }
130
- );
131
- await runWrangler("init");
132
- expect(std.warn).toContain("wrangler.toml file already exists!");
133
- const parsed = TOML.parse(await fsp.readFile("./wrangler.toml", "utf-8"));
134
- expect(parsed.compatibility_date).toBe("something-else");
135
- });
136
-
137
- it("should create a package.json if none is found and user confirms", async () => {
138
- mockConfirm(
139
- {
140
- text: "No package.json found. Would you like to create one?",
141
- result: true,
142
- },
143
- {
144
- text: "Would you like to use typescript?",
145
- result: false,
146
- }
147
- );
148
- await runWrangler("init");
149
- expect(fs.existsSync("./package.json")).toBe(true);
150
- const packageJson = JSON.parse(
151
- fs.readFileSync("./package.json", "utf-8")
152
- );
153
- expect(packageJson.name).toEqual("worker"); // TODO: should we infer the name from the directory?
154
- expect(packageJson.version).toEqual("0.0.1");
155
- expect(packageJson.devDependencies).toEqual({
156
- wrangler: expect.any(String),
157
- });
158
- expect(fs.existsSync("./tsconfig.json")).toBe(false);
159
- });
160
-
161
- it("should not touch an existing package.json in the same directory", async () => {
162
- mockConfirm(
163
- {
164
- text: "Would you like to install wrangler into your package.json?",
165
- result: false,
166
- },
167
- {
168
- text: "Would you like to use typescript?",
169
- result: false,
170
- }
171
- );
172
-
173
- fs.writeFileSync(
174
- "./package.json",
175
- JSON.stringify({ name: "test", version: "1.0.0" }),
176
- "utf-8"
177
- );
178
-
179
- await runWrangler("init");
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");
185
- });
186
-
187
- it("should offer to install wrangler into an existing package.json", async () => {
188
- mockConfirm(
189
- {
190
- text: "Would you like to install wrangler into your package.json?",
191
- result: true,
192
- },
193
- {
194
- text: "Would you like to use typescript?",
195
- result: false,
196
- }
197
- );
198
-
199
- fs.writeFileSync(
200
- "./package.json",
201
- JSON.stringify({ name: "test", version: "1.0.0" }),
202
- "utf-8"
203
- );
204
-
205
- await runWrangler("init");
206
- const packageJson = JSON.parse(
207
- fs.readFileSync("./package.json", "utf-8")
208
- );
209
- expect(packageJson.name).toEqual("test");
210
- expect(packageJson.version).toEqual("1.0.0");
211
- expect(packageJson.devDependencies).toEqual({
212
- wrangler: expect.any(String),
213
- });
214
- });
215
-
216
- it("should not touch an existing package.json in an ancestor directory", async () => {
217
- mockConfirm(
218
- {
219
- text: "Would you like to install wrangler into your package.json?",
220
- result: false,
221
- },
222
- {
223
- text: "Would you like to use typescript?",
224
- result: false,
225
- }
226
- );
227
-
228
- fs.writeFileSync(
229
- "./package.json",
230
- JSON.stringify({ name: "test", version: "1.0.0" }),
231
- "utf-8"
232
- );
233
-
234
- fs.mkdirSync("./sub-1/sub-2", { recursive: true });
235
- process.chdir("./sub-1/sub-2");
236
-
237
- await runWrangler("init");
238
- expect(fs.existsSync("./package.json")).toBe(false);
239
- expect(fs.existsSync("../../package.json")).toBe(true);
240
-
241
- const packageJson = JSON.parse(
242
- fs.readFileSync("../../package.json", "utf-8")
243
- );
244
- expect(packageJson).toMatchInlineSnapshot(`
245
- Object {
246
- "name": "test",
247
- "version": "1.0.0",
248
- }
249
- `);
250
- });
251
-
252
- it("should create a tsconfig.json and install `workers-types` if none is found and user confirms", async () => {
253
- mockConfirm(
254
- {
255
- text: "No package.json found. Would you like to create one?",
256
- result: true,
257
- },
258
- {
259
- text: "Would you like to use typescript?",
260
- result: true,
261
- }
262
- );
263
- await runWrangler("init");
264
- expect(fs.existsSync("./tsconfig.json")).toBe(true);
265
- const tsconfigJson = JSON.parse(
266
- fs.readFileSync("./tsconfig.json", "utf-8")
267
- );
268
- expect(tsconfigJson.compilerOptions.types).toEqual([
269
- "@cloudflare/workers-types",
270
- ]);
271
- const packageJson = JSON.parse(
272
- fs.readFileSync("./package.json", "utf-8")
273
- );
274
- expect(packageJson.devDependencies).toEqual({
275
- "@cloudflare/workers-types": expect.any(String),
276
- wrangler: expect.any(String),
277
- });
278
- });
279
-
280
- it("should not touch an existing tsconfig.json in the same directory", async () => {
281
- fs.writeFileSync(
282
- "./package.json",
283
- JSON.stringify({
284
- name: "test",
285
- version: "1.0.0",
286
- devDependencies: {
287
- wrangler: "0.0.0",
288
- "@cloudflare/workers-types": "0.0.0",
289
- },
290
- }),
291
- "utf-8"
292
- );
293
- fs.writeFileSync(
294
- "./tsconfig.json",
295
- JSON.stringify({ compilerOptions: {} }),
296
- "utf-8"
297
- );
298
-
299
- await runWrangler("init");
300
- const tsconfigJson = JSON.parse(
301
- fs.readFileSync("./tsconfig.json", "utf-8")
302
- );
303
- expect(tsconfigJson.compilerOptions).toEqual({});
304
- });
305
-
306
- it("should offer to install type definitions in an existing typescript project", async () => {
307
- mockConfirm(
308
- {
309
- text: "Would you like to install wrangler into your package.json?",
310
- result: false,
311
- },
312
- {
313
- text: "Would you like to install the type definitions for Workers into your package.json?",
314
- result: true,
315
- }
316
- );
317
- fs.writeFileSync(
318
- "./package.json",
319
- JSON.stringify({
320
- name: "test",
321
- version: "1.0.0",
322
- }),
323
- "utf-8"
324
- );
325
- fs.writeFileSync(
326
- "./tsconfig.json",
327
- JSON.stringify({ compilerOptions: {} }),
328
- "utf-8"
329
- );
330
-
331
- await runWrangler("init");
332
- const tsconfigJson = JSON.parse(
333
- fs.readFileSync("./tsconfig.json", "utf-8")
334
- );
335
- // unchanged tsconfig
336
- expect(tsconfigJson.compilerOptions).toEqual({});
337
- const packageJson = JSON.parse(
338
- fs.readFileSync("./package.json", "utf-8")
339
- );
340
- expect(packageJson.devDependencies).toEqual({
341
- "@cloudflare/workers-types": expect.any(String),
342
- });
343
- });
344
-
345
- it("should not touch an existing tsconfig.json in an ancestor directory", async () => {
346
- fs.writeFileSync(
347
- "./package.json",
348
- JSON.stringify({
349
- name: "test",
350
- version: "1.0.0",
351
- devDependencies: {
352
- wrangler: "0.0.0",
353
- "@cloudflare/workers-types": "0.0.0",
354
- },
355
- }),
356
- "utf-8"
357
- );
358
- fs.writeFileSync(
359
- "./tsconfig.json",
360
- JSON.stringify({ compilerOptions: {} }),
361
- "utf-8"
362
- );
363
-
364
- fs.mkdirSync("./sub-1/sub-2", { recursive: true });
365
- process.chdir("./sub-1/sub-2");
366
-
367
- await runWrangler("init");
368
- expect(fs.existsSync("./tsconfig.json")).toBe(false);
369
- expect(fs.existsSync("../../tsconfig.json")).toBe(true);
370
-
371
- const tsconfigJson = JSON.parse(
372
- fs.readFileSync("../../tsconfig.json", "utf-8")
373
- );
374
- expect(tsconfigJson.compilerOptions).toEqual({});
375
- });
376
-
377
- it("should error if `--type` is used", async () => {
378
- let err: undefined | Error;
379
- try {
380
- await runWrangler("init --type");
381
- } catch (e) {
382
- err = e;
383
- } finally {
384
- expect(err?.message).toBe(`The --type option is no longer supported.`);
385
- }
386
- });
387
-
388
- it("should error if `--type javascript` is used", async () => {
389
- let err: undefined | Error;
390
- try {
391
- await runWrangler("init --type javascript");
392
- } catch (e) {
393
- err = e;
394
- } finally {
395
- expect(err?.message).toBe(`The --type option is no longer supported.`);
396
- }
397
- });
398
-
399
- it("should error if `--type rust` is used", async () => {
400
- let err: undefined | Error;
401
- try {
402
- await runWrangler("init --type rust");
403
- } catch (e) {
404
- err = e;
405
- } finally {
406
- expect(err?.message).toBe(`The --type option is no longer supported.`);
407
- }
408
- });
409
-
410
- it("should error if `--type webpack` is used", async () => {
411
- let err: undefined | Error;
412
- try {
413
- await runWrangler("init --type webpack");
414
- } catch (e) {
415
- err = e;
416
- } finally {
417
- expect(err?.message).toBe(
418
- `The --type option is no longer supported.
419
- If you wish to use webpack then you will need to create a custom build.`
420
- );
421
- }
422
- });
423
- });
424
- });
@@ -1,29 +0,0 @@
1
- import { mockFetchInternal } from "./mock-cfetch";
2
- import { confirm, prompt } from "../dialogs";
3
- import { fetchInternal } from "../cfetch/internal";
4
- import fetchMock from "jest-fetch-mock";
5
-
6
- jest.mock("node-fetch", () => jest.requireActual("jest-fetch-mock"));
7
- fetchMock.doMock(() => {
8
- // Any un-mocked fetches should throw
9
- throw new Error("Unexpected fetch request");
10
- });
11
-
12
- jest.mock("../cfetch/internal");
13
- (fetchInternal as jest.Mock).mockImplementation(mockFetchInternal);
14
-
15
- jest.mock("../dialogs");
16
-
17
- // By default (if not configured by mockConfirm()) calls to `confirm()` should throw.
18
- (confirm as jest.Mock).mockImplementation(() => {
19
- throw new Error(
20
- "Unexpected call to `confirm()`. You should use `mockConfirm()` to mock calls to `confirm()` with expectations. Search the codebase for `mockConfirm` to learn more."
21
- );
22
- });
23
-
24
- // By default (if not configured by mockPrompt()) calls to `prompt()` should throw.
25
- (prompt as jest.Mock).mockImplementation(() => {
26
- throw new Error(
27
- "Unexpected call to `prompt()`. You should use `mockPrompt()` to mock calls to `prompt()` with expectations. Search the codebase for `mockPrompt` to learn more."
28
- );
29
- });