wrangler 0.0.0-e043479 → 0.0.0-e0a0509

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 (96) hide show
  1. package/README.md +27 -14
  2. package/bin/wrangler.js +13 -1
  3. package/miniflare-dist/index.mjs +4886 -0
  4. package/package.json +38 -25
  5. package/pages/functions/buildPlugin.ts +92 -0
  6. package/pages/functions/buildWorker.ts +80 -4
  7. package/pages/functions/filepath-routing.test.ts +136 -25
  8. package/pages/functions/filepath-routing.ts +14 -3
  9. package/pages/functions/routes.ts +6 -1
  10. package/pages/functions/template-plugin.ts +146 -0
  11. package/pages/functions/template-worker.ts +21 -8
  12. package/src/__tests__/config-cache.test.ts +36 -0
  13. package/src/__tests__/configuration.test.ts +1294 -355
  14. package/src/__tests__/dev.test.tsx +592 -12
  15. package/src/__tests__/guess-worker-format.test.ts +37 -18
  16. package/src/__tests__/helpers/mock-account-id.ts +4 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +8 -4
  18. package/src/__tests__/helpers/mock-console.ts +20 -3
  19. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +27 -0
  22. package/src/__tests__/helpers/mock-kv.ts +9 -16
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  24. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  25. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  26. package/src/__tests__/https-options.test.ts +130 -0
  27. package/src/__tests__/index.test.ts +129 -753
  28. package/src/__tests__/init.test.ts +1516 -0
  29. package/src/__tests__/jest.setup.ts +13 -5
  30. package/src/__tests__/kv.test.ts +208 -174
  31. package/src/__tests__/logger.test.ts +115 -0
  32. package/src/__tests__/pages.test.ts +327 -0
  33. package/src/__tests__/parse.test.ts +4 -0
  34. package/src/__tests__/publish.test.ts +3313 -505
  35. package/src/__tests__/r2.test.ts +38 -26
  36. package/src/__tests__/route.test.ts +45 -0
  37. package/src/__tests__/secret.test.ts +55 -34
  38. package/src/__tests__/tail.test.ts +146 -20
  39. package/src/__tests__/user.test.ts +131 -0
  40. package/src/__tests__/whoami.test.tsx +26 -7
  41. package/src/bundle.ts +43 -7
  42. package/src/cfetch/internal.ts +9 -5
  43. package/src/cli.ts +5 -11
  44. package/src/config/README.md +7 -7
  45. package/src/config/config.ts +69 -105
  46. package/src/config/environment.ts +93 -4
  47. package/src/config/index.ts +15 -4
  48. package/src/config/validation-helpers.ts +228 -23
  49. package/src/config/validation.ts +559 -154
  50. package/src/config-cache.ts +45 -0
  51. package/src/{api/preview.ts → create-worker-preview.ts} +41 -13
  52. package/src/{api/form_data.ts → create-worker-upload-form.ts} +33 -10
  53. package/src/dev/dev-vars.ts +36 -0
  54. package/src/dev/dev.tsx +418 -0
  55. package/src/dev/local.tsx +312 -0
  56. package/src/dev/remote.tsx +213 -0
  57. package/src/dev/use-esbuild.ts +118 -0
  58. package/src/dialogs.tsx +16 -6
  59. package/src/entry.ts +222 -12
  60. package/src/environment-variables.ts +3 -1
  61. package/src/errors.ts +11 -0
  62. package/src/https-options.ts +123 -0
  63. package/src/index.tsx +878 -482
  64. package/src/inspect.ts +25 -11
  65. package/src/intl-polyfill.d.ts +139 -0
  66. package/src/{kv.tsx → kv.ts} +7 -27
  67. package/src/logger.ts +66 -0
  68. package/src/miniflare-cli/README.md +30 -0
  69. package/src/miniflare-cli/enum-keys.ts +17 -0
  70. package/src/miniflare-cli/index.ts +41 -0
  71. package/src/miniflare-cli/request-context.ts +40 -0
  72. package/src/module-collection.ts +94 -6
  73. package/src/open-in-browser.ts +18 -5
  74. package/src/package-manager.ts +9 -8
  75. package/src/pages.tsx +892 -62
  76. package/src/parse.ts +4 -2
  77. package/src/proxy.ts +128 -55
  78. package/src/publish.ts +305 -199
  79. package/src/selfsigned.d.ts +29 -0
  80. package/src/sites.tsx +88 -33
  81. package/src/tail/index.ts +2 -2
  82. package/src/tail/printing.ts +13 -8
  83. package/src/update-check.ts +19 -0
  84. package/src/user.tsx +244 -104
  85. package/src/whoami.tsx +2 -1
  86. package/src/{api/worker.ts → worker.ts} +15 -29
  87. package/templates/gitignore +171 -0
  88. package/templates/static-asset-facade.js +1 -1
  89. package/wrangler-dist/cli.js +23568 -50489
  90. package/src/__tests__/helpers/mock-user.ts +0 -27
  91. package/src/__tests__/logout.test.ts +0 -50
  92. package/src/__tests__/sentry.test.ts +0 -146
  93. package/src/dev.tsx +0 -960
  94. package/src/guess-worker-format.ts +0 -68
  95. package/src/reporting.ts +0 -115
  96. package/wrangler-dist/cli.js.map +0 -7
package/src/entry.ts CHANGED
@@ -1,44 +1,209 @@
1
+ import assert from "node:assert";
1
2
  import { existsSync } from "node:fs";
2
3
  import path from "node:path";
4
+ import * as esbuild from "esbuild";
5
+ import { execaCommand } from "execa";
6
+ import { logger } from "./logger";
3
7
  import type { Config } from "./config";
8
+ import type { CfScriptFormat } from "./worker";
9
+ import type { Metafile } from "esbuild";
4
10
 
5
11
  /**
6
12
  * An entry point for the Worker.
7
13
  *
8
14
  * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
9
15
  */
10
- export type Entry = { file: string; directory: string };
16
+ export type Entry = { file: string; directory: string; format: CfScriptFormat };
11
17
 
12
18
  /**
13
19
  * Compute the entry-point for the Worker.
14
20
  */
15
- export function getEntry(
21
+ export async function getEntry(
22
+ args: { script?: string; format?: CfScriptFormat | undefined },
16
23
  config: Config,
17
- command: string,
18
- script?: string
19
- ): Entry {
24
+ command: "dev" | "publish"
25
+ ): Promise<Entry> {
20
26
  let file: string;
21
27
  let directory = process.cwd();
22
- if (script) {
28
+ if (args.script) {
23
29
  // If the script name comes from the command line it is relative to the current working directory.
24
- file = path.resolve(script);
30
+ file = path.resolve(args.script);
25
31
  } else if (config.main === undefined) {
26
- throw new Error(
27
- `Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command} path/to/script\`) or the \`main\` config field.`
28
- );
32
+ if (config.site?.["entry-point"]) {
33
+ directory = path.resolve(path.dirname(config.configPath ?? "."));
34
+ file = path.extname(config.site?.["entry-point"])
35
+ ? path.resolve(config.site?.["entry-point"])
36
+ : // site.entry-point could be a directory
37
+ path.resolve(config.site?.["entry-point"], "index.js");
38
+ } else {
39
+ throw new Error(
40
+ `Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command} path/to/script\`) or the \`main\` config field.`
41
+ );
42
+ }
29
43
  } else {
30
44
  directory = path.resolve(path.dirname(config.configPath ?? "."));
31
45
  file = path.resolve(directory, config.main);
32
46
  }
33
47
 
34
- if (!config.build?.command && fileExists(file) === false) {
48
+ await runCustomBuild(file, config.build);
49
+
50
+ if (fileExists(file) === false) {
35
51
  throw new Error(
36
52
  `Could not resolve "${path.relative(process.cwd(), file)}".`
37
53
  );
38
54
  }
39
- return { file, directory };
55
+ const format = await guessWorkerFormat(
56
+ file,
57
+ directory,
58
+ args.format ?? config.build?.upload?.format,
59
+ config.tsconfig
60
+ );
61
+
62
+ const { localBindings, remoteBindings } =
63
+ partitionDurableObjectBindings(config);
64
+
65
+ if (command === "dev" && remoteBindings.length > 0) {
66
+ logger.warn(
67
+ "WARNING: You have Durable Object bindings that are not defined locally in the worker being developed.\n" +
68
+ "Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\n" +
69
+ "Remote Durable Objects that are affected:\n" +
70
+ remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
71
+ );
72
+ }
73
+
74
+ if (format === "service-worker" && localBindings.length > 0) {
75
+ const errorMessage =
76
+ "You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
77
+ const addScriptName =
78
+ "You can use Durable Objects defined in other Workers by specifying a `script_name` in your wrangler.toml, where `script_name` is the name of the Worker that implements that Durable Object. For example:";
79
+ const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
80
+ const migrateText =
81
+ "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
82
+ const migrateUrl =
83
+ "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
84
+ throw new Error(
85
+ `${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
86
+ );
87
+ }
88
+
89
+ return { file, directory, format };
90
+ }
91
+
92
+ export async function runCustomBuild(
93
+ expectedEntry: string,
94
+ build: Config["build"]
95
+ ) {
96
+ if (build?.command) {
97
+ // TODO: add a deprecation message here?
98
+ logger.log("Running custom build:", build.command);
99
+ await execaCommand(build.command, {
100
+ shell: true,
101
+ // we keep these two as "inherit" so that
102
+ // logs are still visible.
103
+ stdout: "inherit",
104
+ stderr: "inherit",
105
+ ...(build.cwd && { cwd: build.cwd }),
106
+ });
107
+
108
+ if (fileExists(expectedEntry) === false) {
109
+ throw new Error(
110
+ `Could not resolve "${path.relative(
111
+ process.cwd(),
112
+ expectedEntry
113
+ )}" after running custom build: ${build.command}`
114
+ );
115
+ }
116
+ }
117
+ }
118
+
119
+ /**
120
+ * A function to "guess" the type of worker.
121
+ * We do this by running a lightweight build of the actual script,
122
+ * and looking at the metafile generated by esbuild. If it has a default
123
+ * export (or really, any exports), that means it's a "modules" worker.
124
+ * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
125
+ * well in practice.
126
+ */
127
+ export default async function guessWorkerFormat(
128
+ entryFile: string,
129
+ entryWorkingDirectory: string,
130
+ hint: CfScriptFormat | undefined,
131
+ tsconfig?: string | undefined
132
+ ): Promise<CfScriptFormat> {
133
+ const result = await esbuild.build({
134
+ entryPoints: [entryFile],
135
+ absWorkingDir: entryWorkingDirectory,
136
+ metafile: true,
137
+ bundle: false,
138
+ format: "esm",
139
+ target: "es2020",
140
+ write: false,
141
+ loader: {
142
+ ".js": "jsx",
143
+ ".mjs": "jsx",
144
+ ".cjs": "jsx",
145
+ },
146
+ ...(tsconfig && { tsconfig }),
147
+ });
148
+ // result.metafile is defined because of the `metafile: true` option above.
149
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
150
+ const metafile = result.metafile!;
151
+ const entryPoints = Object.entries(metafile.outputs).filter(
152
+ ([_path, output]) => output.entryPoint !== undefined
153
+ );
154
+ assert(
155
+ entryPoints.length > 0,
156
+ `Cannot find entry-point "${entryFile}" in generated bundle.` +
157
+ listEntryPoints(entryPoints)
158
+ );
159
+ assert(
160
+ entryPoints.length < 2,
161
+ "More than one entry-point found for generated bundle." +
162
+ listEntryPoints(entryPoints)
163
+ );
164
+
165
+ let guessedWorkerFormat: CfScriptFormat;
166
+ const scriptExports = entryPoints[0][1].exports;
167
+ if (scriptExports.length > 0) {
168
+ if (scriptExports.includes("default")) {
169
+ guessedWorkerFormat = "modules";
170
+ } else {
171
+ logger.warn(
172
+ `The entrypoint ${path.relative(
173
+ process.cwd(),
174
+ entryFile
175
+ )} has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using "service-worker" format...`
176
+ );
177
+ guessedWorkerFormat = "service-worker";
178
+ }
179
+ } else {
180
+ guessedWorkerFormat = "service-worker";
181
+ }
182
+
183
+ if (hint) {
184
+ if (hint !== guessedWorkerFormat) {
185
+ if (hint === "service-worker") {
186
+ throw new Error(
187
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have a `default` export like a module worker. Please pass `--format modules`, or simply remove the configuration."
188
+ );
189
+ } else {
190
+ throw new Error(
191
+ "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
192
+ );
193
+ }
194
+ }
195
+ }
196
+ return guessedWorkerFormat;
40
197
  }
41
198
 
199
+ function listEntryPoints(
200
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
201
+ ): string {
202
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
203
+ }
204
+
205
+ type ValueOf<T> = T[keyof T];
206
+
42
207
  /**
43
208
  * Returns true if the given `filePath` exists as-is,
44
209
  * or if some version of it (by appending a common extension) exists.
@@ -55,3 +220,48 @@ export function fileExists(filePath: string): boolean {
55
220
  }
56
221
  return false;
57
222
  }
223
+
224
+ type DurableObjectBindings = Config["durable_objects"]["bindings"];
225
+
226
+ /**
227
+ * Groups the durable object bindings into two lists:
228
+ * those that are defined locally and those that refer to a durable object defined in another script.
229
+ */
230
+ function partitionDurableObjectBindings(config: Config): {
231
+ localBindings: DurableObjectBindings;
232
+ remoteBindings: DurableObjectBindings;
233
+ } {
234
+ const localBindings: DurableObjectBindings = [];
235
+ const remoteBindings: DurableObjectBindings = [];
236
+ for (const binding of config.durable_objects.bindings) {
237
+ if (binding.script_name === undefined) {
238
+ localBindings.push(binding);
239
+ } else {
240
+ remoteBindings.push(binding);
241
+ }
242
+ }
243
+ return { localBindings, remoteBindings };
244
+ }
245
+
246
+ /**
247
+ * Generates some help text based on the Durable Object bindings in a given
248
+ * config indicating how the user can add a `script_name` field to bind an
249
+ * externally defined Durable Object.
250
+ */
251
+ function generateAddScriptNameExamples(
252
+ localBindings: DurableObjectBindings
253
+ ): string {
254
+ function exampleScriptName(binding_name: string): string {
255
+ return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
256
+ }
257
+
258
+ return localBindings
259
+ .map(({ name, class_name }) => {
260
+ const script_name = exampleScriptName(name);
261
+ const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
262
+ const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
263
+
264
+ return `${currentBinding} ==> ${fixedBinding}`;
265
+ })
266
+ .join("\n");
267
+ }
@@ -1,3 +1,5 @@
1
+ import { logger } from "./logger";
2
+
1
3
  /**
2
4
  * Create a function used to access an environment variable.
3
5
  *
@@ -21,7 +23,7 @@ export function getEnvironmentVariableFactory({
21
23
  if (!hasWarned) {
22
24
  // Only show the warning once.
23
25
  hasWarned = true;
24
- console.warn(
26
+ logger.warn(
25
27
  `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
26
28
  );
27
29
  }
package/src/errors.ts ADDED
@@ -0,0 +1,11 @@
1
+ export class DeprecationError extends Error {
2
+ constructor(message: string) {
3
+ super(`Deprecation:\n${message}`);
4
+ }
5
+ }
6
+
7
+ export class FatalError extends Error {
8
+ constructor(message?: string, readonly code?: number) {
9
+ super(message);
10
+ }
11
+ }
@@ -0,0 +1,123 @@
1
+ import * as fs from "node:fs";
2
+ import { homedir, networkInterfaces } from "node:os";
3
+ import * as path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { logger } from "./logger";
6
+ import type { Attributes, Options } from "selfsigned";
7
+
8
+ // Most of this file has been borrowed from the implementation in Miniflare.
9
+ // See https://github.com/cloudflare/miniflare/blob/870b401ef5/packages/http-server/src/plugin.ts#L313-L397
10
+ // Thanks @mrbbot.
11
+ const CERT_EXPIRY_DAYS = 30;
12
+ const ONE_DAY_IN_MS = 86400000;
13
+
14
+ /**
15
+ * Get the options (i.e. SSL certificates) for running an HTTPS server.
16
+ *
17
+ * The certificates are self-signed and generated locally, and cached in the `CERT_ROOT` directory.
18
+ */
19
+ export async function getHttpsOptions() {
20
+ const certDirectory = path.join(homedir(), ".wrangler/local-cert");
21
+ const keyPath = path.join(certDirectory, "key.pem");
22
+ const certPath = path.join(certDirectory, "cert.pem");
23
+
24
+ const regenerate =
25
+ !fs.existsSync(keyPath) ||
26
+ !fs.existsSync(certPath) ||
27
+ hasCertificateExpired(keyPath, certPath);
28
+
29
+ if (regenerate) {
30
+ logger.log("Generating new self-signed certificate...");
31
+ const { key, cert } = await generateCertificate();
32
+ try {
33
+ // Write certificate files so we can reuse them later.
34
+ fs.mkdirSync(certDirectory, { recursive: true });
35
+ fs.writeFileSync(keyPath, key, "utf8");
36
+ fs.writeFileSync(certPath, cert, "utf8");
37
+ } catch (e) {
38
+ const message = e instanceof Error ? e.message : `${e}`;
39
+ logger.warn(
40
+ `Unable to cache generated self-signed certificate in ${certDirectory}.\n${message}`
41
+ );
42
+ }
43
+ return { key, cert };
44
+ } else {
45
+ return {
46
+ key: fs.readFileSync(keyPath, "utf8"),
47
+ cert: fs.readFileSync(certPath, "utf8"),
48
+ };
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Determine if the certificate defined in `keyPath` and `certPath` files
54
+ * have expired based on the date when they were last modified.
55
+ */
56
+ function hasCertificateExpired(keyPath: string, certPath: string): boolean {
57
+ const keyStat = fs.statSync(keyPath);
58
+ const certStat = fs.statSync(certPath);
59
+ const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
60
+ return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
61
+ }
62
+
63
+ /**
64
+ * Generate a new self-signed certificate and cache it in `CERT_ROOT` directory.
65
+ */
66
+ async function generateCertificate() {
67
+ // `selfsigned` imports `node-forge`, which is a pretty big library.
68
+ // To reduce startup time, only load this dynamically when needed.
69
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
70
+ const generate: typeof import("selfsigned").generate = promisify(
71
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
72
+ require("selfsigned").generate
73
+ );
74
+
75
+ const certAttrs: Attributes = [{ name: "commonName", value: "localhost" }];
76
+
77
+ const certOptions: Options = {
78
+ algorithm: "sha256",
79
+ days: CERT_EXPIRY_DAYS,
80
+ keySize: 2048,
81
+ extensions: [
82
+ { name: "basicConstraints", cA: true },
83
+ {
84
+ name: "keyUsage",
85
+ keyCertSign: true,
86
+ digitalSignature: true,
87
+ nonRepudiation: true,
88
+ keyEncipherment: true,
89
+ dataEncipherment: true,
90
+ },
91
+ {
92
+ name: "extKeyUsage",
93
+ serverAuth: true,
94
+ clientAuth: true,
95
+ codeSigning: true,
96
+ timeStamping: true,
97
+ },
98
+ {
99
+ name: "subjectAltName",
100
+ altNames: [
101
+ { type: 2, value: "localhost" },
102
+ ...getAccessibleHosts().map((ip) => ({ type: 7, ip })),
103
+ ],
104
+ },
105
+ ],
106
+ };
107
+
108
+ const { private: key, cert } = await generate(certAttrs, certOptions);
109
+ return { key, cert };
110
+ }
111
+
112
+ /**
113
+ * Ask the OS for the addresses of locally accessible hosts.
114
+ */
115
+ function getAccessibleHosts(ipv4 = false): string[] {
116
+ const hosts: string[] = [];
117
+ Object.values(networkInterfaces()).forEach((net) =>
118
+ net?.forEach(({ family, address }) => {
119
+ if (!ipv4 || family === "IPv4") hosts.push(address);
120
+ })
121
+ );
122
+ return hosts;
123
+ }