wrangler 0.0.0-ece06ea → 0.0.0-ed08df4
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/Cloudflare_CA.pem +18 -0
- package/README.md +27 -14
- package/bin/wrangler.js +34 -2
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +71 -36
- package/pages/functions/buildPlugin.ts +92 -0
- package/pages/functions/buildWorker.ts +138 -0
- package/pages/functions/filepath-routing.test.ts +234 -0
- package/pages/functions/filepath-routing.ts +189 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +156 -0
- package/pages/functions/template-plugin.ts +147 -0
- package/pages/functions/template-worker.ts +143 -0
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +3125 -0
- package/src/__tests__/dev.test.tsx +829 -0
- package/src/__tests__/guess-worker-format.test.ts +85 -0
- package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +48 -0
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/helpers/mock-cfetch.ts +211 -0
- package/src/__tests__/helpers/mock-console.ts +87 -0
- package/src/__tests__/helpers/mock-dialogs.ts +90 -0
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +39 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +221 -132
- package/src/__tests__/init.test.ts +1516 -0
- package/src/__tests__/jest.setup.ts +77 -0
- package/src/__tests__/kv.test.ts +1481 -0
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +327 -0
- package/src/__tests__/parse.test.ts +326 -0
- package/src/__tests__/publish.test.ts +4996 -0
- package/src/__tests__/r2.test.ts +210 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +446 -0
- package/src/__tests__/tail.test.ts +690 -0
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +105 -0
- package/src/bundle.ts +169 -0
- package/src/cfetch/index.ts +104 -0
- package/src/cfetch/internal.ts +140 -0
- package/src/cli.ts +10 -7
- package/src/config/README.md +107 -0
- package/src/config/config.ts +234 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +394 -0
- package/src/config/index.ts +63 -0
- package/src/config/validation-helpers.ts +575 -0
- package/src/config/validation.ts +1424 -0
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +175 -0
- package/src/create-worker-upload-form.ts +240 -0
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +421 -0
- package/src/dev/local.tsx +312 -0
- package/src/dev/remote.tsx +213 -0
- package/src/dev/use-esbuild.ts +118 -0
- package/src/dialogs.tsx +22 -20
- package/src/entry.ts +322 -0
- package/src/environment-variables.ts +35 -0
- package/src/errors.ts +11 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +1869 -1020
- package/src/inspect.ts +623 -0
- package/src/intl-polyfill.d.ts +139 -0
- package/src/kv.ts +344 -0
- package/src/logger.ts +66 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +258 -0
- package/src/open-in-browser.ts +26 -0
- package/src/package-manager.ts +127 -0
- package/src/pages.tsx +1756 -218
- package/src/parse.ts +185 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +449 -0
- package/src/publish.ts +377 -262
- package/src/r2.ts +50 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +237 -59
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +67 -0
- package/src/update-check.ts +19 -0
- package/src/user.tsx +395 -221
- package/src/whoami.tsx +70 -0
- package/src/worker.ts +172 -0
- package/templates/gitignore +171 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +108921 -132528
- package/src/__tests__/fixtures/init/.gitkeep +0 -0
- package/src/__tests__/mock-cfetch.js +0 -46
- package/src/api/form_data.ts +0 -158
- package/src/api/inspect.ts +0 -441
- package/src/api/preview.ts +0 -123
- package/src/api/worker.ts +0 -161
- package/src/cfetch.ts +0 -72
- package/src/config.ts +0 -124
- package/src/dev.tsx +0 -736
- package/src/kv.tsx +0 -211
- package/src/tail.tsx +0 -71
- package/src/util/fetch.ts +0 -74
- package/wrangler-dist/cli.js.map +0 -7
package/src/dialogs.tsx
CHANGED
|
@@ -1,24 +1,28 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { useState } from "react";
|
|
1
|
+
import chalk from "chalk";
|
|
3
2
|
import { Box, Text, useInput, render } from "ink";
|
|
4
3
|
import TextInput from "ink-text-input";
|
|
4
|
+
import * as React from "react";
|
|
5
|
+
import { useState } from "react";
|
|
6
|
+
import { logger } from "./logger";
|
|
5
7
|
type ConfirmProps = {
|
|
6
8
|
text: string;
|
|
7
|
-
onConfirm: (answer: boolean) => void
|
|
9
|
+
onConfirm: (answer: boolean) => void;
|
|
8
10
|
};
|
|
9
11
|
function Confirm(props: ConfirmProps) {
|
|
10
|
-
useInput((input: string) => {
|
|
11
|
-
if (input === "y") {
|
|
12
|
+
useInput((input: string, key) => {
|
|
13
|
+
if (input === "y" || key.return === true) {
|
|
12
14
|
props.onConfirm(true);
|
|
13
15
|
} else if (input === "n") {
|
|
14
16
|
props.onConfirm(false);
|
|
15
17
|
} else {
|
|
16
|
-
|
|
18
|
+
logger.warn("Unrecognised input:", input);
|
|
17
19
|
}
|
|
18
20
|
});
|
|
19
21
|
return (
|
|
20
22
|
<Box>
|
|
21
|
-
<Text>
|
|
23
|
+
<Text>
|
|
24
|
+
{props.text} ({chalk.bold("y")}/n)
|
|
25
|
+
</Text>
|
|
22
26
|
</Box>
|
|
23
27
|
);
|
|
24
28
|
}
|
|
@@ -39,12 +43,13 @@ export function confirm(text: string): Promise<boolean> {
|
|
|
39
43
|
|
|
40
44
|
type PromptProps = {
|
|
41
45
|
text: string;
|
|
46
|
+
defaultValue?: string;
|
|
42
47
|
type?: "text" | "password";
|
|
43
48
|
onSubmit: (text: string) => void;
|
|
44
49
|
};
|
|
45
50
|
|
|
46
|
-
|
|
47
|
-
const [value, setValue] = useState("");
|
|
51
|
+
function Prompt(props: PromptProps) {
|
|
52
|
+
const [value, setValue] = useState(props.defaultValue || "");
|
|
48
53
|
|
|
49
54
|
return (
|
|
50
55
|
<Box>
|
|
@@ -61,25 +66,22 @@ export function Prompt(props: PromptProps) {
|
|
|
61
66
|
);
|
|
62
67
|
}
|
|
63
68
|
|
|
64
|
-
export async function prompt(
|
|
69
|
+
export async function prompt(
|
|
70
|
+
text: string,
|
|
71
|
+
type: "text" | "password" = "text",
|
|
72
|
+
defaultValue?: string
|
|
73
|
+
): Promise<string> {
|
|
65
74
|
return new Promise((resolve) => {
|
|
66
75
|
const { unmount } = render(
|
|
67
76
|
<Prompt
|
|
68
77
|
text={text}
|
|
78
|
+
defaultValue={defaultValue}
|
|
69
79
|
type={type}
|
|
70
|
-
onSubmit={(
|
|
80
|
+
onSubmit={(inputText) => {
|
|
71
81
|
unmount();
|
|
72
|
-
resolve(
|
|
82
|
+
resolve(inputText);
|
|
73
83
|
}}
|
|
74
84
|
/>
|
|
75
85
|
);
|
|
76
86
|
});
|
|
77
87
|
}
|
|
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
|
-
// }
|
package/src/entry.ts
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import assert from "node:assert";
|
|
2
|
+
import { existsSync, statSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import * as esbuild from "esbuild";
|
|
5
|
+
import { execaCommand } from "execa";
|
|
6
|
+
import { logger } from "./logger";
|
|
7
|
+
import type { Config } from "./config";
|
|
8
|
+
import type { CfScriptFormat } from "./worker";
|
|
9
|
+
import type { Metafile } from "esbuild";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* An entry point for the Worker.
|
|
13
|
+
*
|
|
14
|
+
* It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
|
|
15
|
+
*/
|
|
16
|
+
export type Entry = { file: string; directory: string; format: CfScriptFormat };
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Compute the entry-point for the Worker.
|
|
20
|
+
*/
|
|
21
|
+
export async function getEntry(
|
|
22
|
+
args: { script?: string; format?: CfScriptFormat | undefined },
|
|
23
|
+
config: Config,
|
|
24
|
+
command: "dev" | "publish"
|
|
25
|
+
): Promise<Entry> {
|
|
26
|
+
let file: string;
|
|
27
|
+
let directory = process.cwd();
|
|
28
|
+
if (args.script) {
|
|
29
|
+
// If the script name comes from the command line it is relative to the current working directory.
|
|
30
|
+
file = path.resolve(args.script);
|
|
31
|
+
} else if (config.main === undefined) {
|
|
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
|
+
}
|
|
43
|
+
} else {
|
|
44
|
+
directory = path.resolve(path.dirname(config.configPath ?? "."));
|
|
45
|
+
file = path.resolve(directory, config.main);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const relativeFile = path.relative(directory, file) || ".";
|
|
49
|
+
await runCustomBuild(file, relativeFile, config.build);
|
|
50
|
+
|
|
51
|
+
if (fileExists(file) === false) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
getMissingEntryPointMessage(
|
|
54
|
+
`The entry-point file at "${relativeFile}" was not found.`,
|
|
55
|
+
file,
|
|
56
|
+
relativeFile
|
|
57
|
+
)
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
const format = await guessWorkerFormat(
|
|
61
|
+
file,
|
|
62
|
+
directory,
|
|
63
|
+
args.format ?? config.build?.upload?.format,
|
|
64
|
+
config.tsconfig
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const { localBindings, remoteBindings } =
|
|
68
|
+
partitionDurableObjectBindings(config);
|
|
69
|
+
|
|
70
|
+
if (command === "dev" && remoteBindings.length > 0) {
|
|
71
|
+
logger.warn(
|
|
72
|
+
"WARNING: You have Durable Object bindings that are not defined locally in the worker being developed.\n" +
|
|
73
|
+
"Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\n" +
|
|
74
|
+
"Remote Durable Objects that are affected:\n" +
|
|
75
|
+
remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (format === "service-worker" && localBindings.length > 0) {
|
|
80
|
+
const errorMessage =
|
|
81
|
+
"You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
|
|
82
|
+
const addScriptName =
|
|
83
|
+
"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:";
|
|
84
|
+
const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
|
|
85
|
+
const migrateText =
|
|
86
|
+
"Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
|
|
87
|
+
const migrateUrl =
|
|
88
|
+
"https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
|
|
89
|
+
throw new Error(
|
|
90
|
+
`${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return { file, directory, format };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function runCustomBuild(
|
|
98
|
+
expectedEntryAbsolute: string,
|
|
99
|
+
expectedEntryRelative: string,
|
|
100
|
+
build: Config["build"]
|
|
101
|
+
) {
|
|
102
|
+
if (build?.command) {
|
|
103
|
+
// TODO: add a deprecation message here?
|
|
104
|
+
logger.log("Running custom build:", build.command);
|
|
105
|
+
await execaCommand(build.command, {
|
|
106
|
+
shell: true,
|
|
107
|
+
// we keep these two as "inherit" so that
|
|
108
|
+
// logs are still visible.
|
|
109
|
+
stdout: "inherit",
|
|
110
|
+
stderr: "inherit",
|
|
111
|
+
...(build.cwd && { cwd: build.cwd }),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
if (fileExists(expectedEntryAbsolute) === false) {
|
|
115
|
+
throw new Error(
|
|
116
|
+
getMissingEntryPointMessage(
|
|
117
|
+
`The expected output file at "${expectedEntryRelative}" was not found after running custom build: ${build.command}.\n` +
|
|
118
|
+
"The `main` property in wrangler.toml should point to the file generated by the custom build.",
|
|
119
|
+
expectedEntryAbsolute,
|
|
120
|
+
expectedEntryRelative
|
|
121
|
+
)
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* A function to "guess" the type of worker.
|
|
129
|
+
* We do this by running a lightweight build of the actual script,
|
|
130
|
+
* and looking at the metafile generated by esbuild. If it has a default
|
|
131
|
+
* export (or really, any exports), that means it's a "modules" worker.
|
|
132
|
+
* Else, it's a "service-worker" worker. This seems hacky, but works remarkably
|
|
133
|
+
* well in practice.
|
|
134
|
+
*/
|
|
135
|
+
export default async function guessWorkerFormat(
|
|
136
|
+
entryFile: string,
|
|
137
|
+
entryWorkingDirectory: string,
|
|
138
|
+
hint: CfScriptFormat | undefined,
|
|
139
|
+
tsconfig?: string | undefined
|
|
140
|
+
): Promise<CfScriptFormat> {
|
|
141
|
+
const result = await esbuild.build({
|
|
142
|
+
entryPoints: [entryFile],
|
|
143
|
+
absWorkingDir: entryWorkingDirectory,
|
|
144
|
+
metafile: true,
|
|
145
|
+
bundle: false,
|
|
146
|
+
format: "esm",
|
|
147
|
+
target: "es2020",
|
|
148
|
+
write: false,
|
|
149
|
+
loader: {
|
|
150
|
+
".js": "jsx",
|
|
151
|
+
".mjs": "jsx",
|
|
152
|
+
".cjs": "jsx",
|
|
153
|
+
},
|
|
154
|
+
...(tsconfig && { tsconfig }),
|
|
155
|
+
});
|
|
156
|
+
// result.metafile is defined because of the `metafile: true` option above.
|
|
157
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
158
|
+
const metafile = result.metafile!;
|
|
159
|
+
const entryPoints = Object.entries(metafile.outputs).filter(
|
|
160
|
+
([_path, output]) => output.entryPoint !== undefined
|
|
161
|
+
);
|
|
162
|
+
assert(
|
|
163
|
+
entryPoints.length > 0,
|
|
164
|
+
`Cannot find entry-point "${entryFile}" in generated bundle.` +
|
|
165
|
+
listEntryPoints(entryPoints)
|
|
166
|
+
);
|
|
167
|
+
assert(
|
|
168
|
+
entryPoints.length < 2,
|
|
169
|
+
"More than one entry-point found for generated bundle." +
|
|
170
|
+
listEntryPoints(entryPoints)
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
let guessedWorkerFormat: CfScriptFormat;
|
|
174
|
+
const scriptExports = entryPoints[0][1].exports;
|
|
175
|
+
if (scriptExports.length > 0) {
|
|
176
|
+
if (scriptExports.includes("default")) {
|
|
177
|
+
guessedWorkerFormat = "modules";
|
|
178
|
+
} else {
|
|
179
|
+
logger.warn(
|
|
180
|
+
`The entrypoint ${path.relative(
|
|
181
|
+
process.cwd(),
|
|
182
|
+
entryFile
|
|
183
|
+
)} 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...`
|
|
184
|
+
);
|
|
185
|
+
guessedWorkerFormat = "service-worker";
|
|
186
|
+
}
|
|
187
|
+
} else {
|
|
188
|
+
guessedWorkerFormat = "service-worker";
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (hint) {
|
|
192
|
+
if (hint !== guessedWorkerFormat) {
|
|
193
|
+
if (hint === "service-worker") {
|
|
194
|
+
throw new Error(
|
|
195
|
+
"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."
|
|
196
|
+
);
|
|
197
|
+
} else {
|
|
198
|
+
throw new Error(
|
|
199
|
+
"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."
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return guessedWorkerFormat;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function listEntryPoints(
|
|
208
|
+
outputs: [string, ValueOf<Metafile["outputs"]>][]
|
|
209
|
+
): string {
|
|
210
|
+
return outputs.map(([_input, output]) => output.entryPoint).join("\n");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
type ValueOf<T> = T[keyof T];
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Returns true if the given `filePath` exists as-is,
|
|
217
|
+
* or if some version of it (by appending a common extension) exists.
|
|
218
|
+
*/
|
|
219
|
+
export function fileExists(filePath: string): boolean {
|
|
220
|
+
if (path.extname(filePath) !== "") {
|
|
221
|
+
return existsSync(filePath);
|
|
222
|
+
}
|
|
223
|
+
const base = path.join(path.dirname(filePath), path.basename(filePath));
|
|
224
|
+
for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
|
|
225
|
+
if (existsSync(base + ext)) {
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
type DurableObjectBindings = Config["durable_objects"]["bindings"];
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Groups the durable object bindings into two lists:
|
|
236
|
+
* those that are defined locally and those that refer to a durable object defined in another script.
|
|
237
|
+
*/
|
|
238
|
+
function partitionDurableObjectBindings(config: Config): {
|
|
239
|
+
localBindings: DurableObjectBindings;
|
|
240
|
+
remoteBindings: DurableObjectBindings;
|
|
241
|
+
} {
|
|
242
|
+
const localBindings: DurableObjectBindings = [];
|
|
243
|
+
const remoteBindings: DurableObjectBindings = [];
|
|
244
|
+
for (const binding of config.durable_objects.bindings) {
|
|
245
|
+
if (binding.script_name === undefined) {
|
|
246
|
+
localBindings.push(binding);
|
|
247
|
+
} else {
|
|
248
|
+
remoteBindings.push(binding);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { localBindings, remoteBindings };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Generates some help text based on the Durable Object bindings in a given
|
|
256
|
+
* config indicating how the user can add a `script_name` field to bind an
|
|
257
|
+
* externally defined Durable Object.
|
|
258
|
+
*/
|
|
259
|
+
function generateAddScriptNameExamples(
|
|
260
|
+
localBindings: DurableObjectBindings
|
|
261
|
+
): string {
|
|
262
|
+
function exampleScriptName(binding_name: string): string {
|
|
263
|
+
return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
return localBindings
|
|
267
|
+
.map(({ name, class_name }) => {
|
|
268
|
+
const script_name = exampleScriptName(name);
|
|
269
|
+
const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
|
|
270
|
+
const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
|
|
271
|
+
|
|
272
|
+
return `${currentBinding} ==> ${fixedBinding}`;
|
|
273
|
+
})
|
|
274
|
+
.join("\n");
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Generate an appropriate message for when the entry-point is missing.
|
|
279
|
+
*
|
|
280
|
+
* To be more helpful to developers, we check whether there is a suitable file
|
|
281
|
+
* nearby to the expected file path.
|
|
282
|
+
*/
|
|
283
|
+
function getMissingEntryPointMessage(
|
|
284
|
+
message: string,
|
|
285
|
+
absoluteEntryPointPath: string,
|
|
286
|
+
relativeEntryPointPath: string
|
|
287
|
+
): string {
|
|
288
|
+
if (
|
|
289
|
+
existsSync(absoluteEntryPointPath) &&
|
|
290
|
+
statSync(absoluteEntryPointPath).isDirectory()
|
|
291
|
+
) {
|
|
292
|
+
// The expected entry-point is a directory, so offer further guidance.
|
|
293
|
+
message += `\nThe provided entry-point path, "${relativeEntryPointPath}", points to a directory, rather than a file.\n`;
|
|
294
|
+
|
|
295
|
+
// Perhaps we can even guess what the correct path should be...
|
|
296
|
+
const possiblePaths: string[] = [];
|
|
297
|
+
for (const basenamePath of [
|
|
298
|
+
"worker",
|
|
299
|
+
"dist/worker",
|
|
300
|
+
"index",
|
|
301
|
+
"dist/index",
|
|
302
|
+
]) {
|
|
303
|
+
for (const extension of [".ts", ".tsx", ".js", ".jsx"]) {
|
|
304
|
+
const filePath = basenamePath + extension;
|
|
305
|
+
if (fileExists(path.resolve(absoluteEntryPointPath, filePath))) {
|
|
306
|
+
possiblePaths.push(path.join(relativeEntryPointPath, filePath));
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (possiblePaths.length > 0) {
|
|
312
|
+
message +=
|
|
313
|
+
`\nDid you mean to set the main field to${
|
|
314
|
+
possiblePaths.length > 1 ? " one of" : ""
|
|
315
|
+
}:\n` +
|
|
316
|
+
"```\n" +
|
|
317
|
+
possiblePaths.map((filePath) => `main = "./${filePath}"\n`).join("") +
|
|
318
|
+
"```";
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return message;
|
|
322
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { logger } from "./logger";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Create a function used to access an environment variable.
|
|
5
|
+
*
|
|
6
|
+
* This is not memoized to allow us to change the value at runtime, such as in testing.
|
|
7
|
+
* A warning is shown if the client is using a deprecated version - but only once.
|
|
8
|
+
*/
|
|
9
|
+
export function getEnvironmentVariableFactory({
|
|
10
|
+
variableName,
|
|
11
|
+
deprecatedName,
|
|
12
|
+
defaultValue,
|
|
13
|
+
}: {
|
|
14
|
+
variableName: string;
|
|
15
|
+
deprecatedName?: string;
|
|
16
|
+
defaultValue?: string;
|
|
17
|
+
}) {
|
|
18
|
+
let hasWarned = false;
|
|
19
|
+
return () => {
|
|
20
|
+
if (process.env[variableName]) {
|
|
21
|
+
return process.env[variableName];
|
|
22
|
+
} else if (deprecatedName && process.env[deprecatedName]) {
|
|
23
|
+
if (!hasWarned) {
|
|
24
|
+
// Only show the warning once.
|
|
25
|
+
hasWarned = true;
|
|
26
|
+
logger.warn(
|
|
27
|
+
`Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return process.env[deprecatedName];
|
|
31
|
+
} else {
|
|
32
|
+
return defaultValue;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -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
|
+
}
|