wrangler 0.0.0-e95bea2 → 0.0.0-e95e5a0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/bin/wrangler.js +13 -1
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +33 -25
- package/pages/functions/buildPlugin.ts +92 -0
- package/pages/functions/buildWorker.ts +80 -4
- package/pages/functions/filepath-routing.test.ts +136 -25
- package/pages/functions/filepath-routing.ts +14 -3
- package/pages/functions/routes.ts +6 -1
- package/pages/functions/template-plugin.ts +146 -0
- package/pages/functions/template-worker.ts +21 -8
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +1179 -271
- package/src/__tests__/dev.test.tsx +382 -25
- package/src/__tests__/guess-worker-format.test.ts +28 -1
- package/src/__tests__/helpers/mock-account-id.ts +4 -0
- package/src/__tests__/helpers/mock-cfetch.ts +5 -1
- package/src/__tests__/helpers/mock-console.ts +20 -3
- package/src/__tests__/helpers/mock-dialogs.ts +26 -1
- 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 +9 -16
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/run-in-tmp.ts +10 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/https-options.test.ts +5 -2
- package/src/__tests__/index.test.ts +27 -769
- package/src/__tests__/init.test.ts +1516 -0
- package/src/__tests__/jest.setup.ts +4 -4
- package/src/__tests__/kv.test.ts +172 -126
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/pages.test.ts +311 -26
- package/src/__tests__/publish.test.ts +2946 -524
- package/src/__tests__/r2.test.ts +26 -10
- package/src/__tests__/route.test.ts +4 -4
- package/src/__tests__/secret.test.ts +55 -34
- package/src/__tests__/tail.test.ts +146 -20
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +26 -7
- package/src/bundle.ts +30 -3
- package/src/cfetch/internal.ts +9 -7
- package/src/cli.ts +5 -11
- package/src/config/README.md +7 -7
- package/src/config/config.ts +33 -78
- package/src/config/environment.ts +93 -4
- package/src/config/index.ts +15 -4
- package/src/config/validation-helpers.ts +202 -15
- package/src/config/validation.ts +530 -133
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +22 -13
- package/src/create-worker-upload-form.ts +32 -9
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +136 -75
- package/src/dev/local.tsx +196 -125
- package/src/dev/remote.tsx +25 -13
- package/src/dev/use-esbuild.ts +23 -5
- package/src/dialogs.tsx +16 -6
- package/src/entry.ts +119 -11
- package/src/environment-variables.ts +3 -1
- package/src/errors.ts +11 -0
- package/src/https-options.ts +3 -2
- package/src/index.tsx +739 -400
- package/src/inspect.ts +17 -11
- package/src/intl-polyfill.d.ts +139 -0
- package/src/{kv/index.tsx → kv.ts} +8 -28
- 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 +63 -58
- package/src/open-in-browser.ts +5 -4
- package/src/package-manager.ts +9 -8
- package/src/pages.tsx +883 -62
- package/src/parse.ts +1 -1
- package/src/proxy.ts +32 -21
- package/src/publish.ts +276 -161
- package/src/sites.tsx +88 -33
- package/src/tail/index.ts +2 -2
- package/src/tail/printing.ts +13 -8
- package/src/update-check.ts +19 -0
- package/src/user.tsx +231 -103
- package/src/whoami.tsx +2 -1
- package/src/worker.ts +15 -6
- package/templates/gitignore +171 -0
- package/templates/static-asset-facade.js +1 -1
- package/wrangler-dist/cli.js +22087 -49340
- package/src/__tests__/dev2.test.tsx +0 -152
- package/src/__tests__/helpers/mock-user.ts +0 -27
- package/src/__tests__/logout.test.ts +0 -50
- package/src/__tests__/sentry.test.ts +0 -146
- package/src/reporting.ts +0 -131
- package/wrangler-dist/cli.js.map +0 -7
package/src/inspect.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { URL } from "node:url";
|
|
|
5
5
|
import { useEffect, useRef, useState } from "react";
|
|
6
6
|
import WebSocket, { WebSocketServer } from "ws";
|
|
7
7
|
import { version } from "../package.json";
|
|
8
|
+
import { logger } from "./logger";
|
|
8
9
|
import { waitForPortToBeAvailable } from "./proxy";
|
|
9
10
|
import type Protocol from "devtools-protocol";
|
|
10
11
|
import type { IncomingMessage, Server, ServerResponse } from "node:http";
|
|
@@ -42,7 +43,7 @@ interface InspectorProps {
|
|
|
42
43
|
/**
|
|
43
44
|
* The websocket URL exposed by Workers that the inspector should connect to.
|
|
44
45
|
*/
|
|
45
|
-
inspectorUrl:
|
|
46
|
+
inspectorUrl: string | undefined;
|
|
46
47
|
/**
|
|
47
48
|
* Whether console statements and exceptions should be logged to the terminal.
|
|
48
49
|
* (We don't log them in local mode because they're already getting
|
|
@@ -134,7 +135,7 @@ export default function useInspector(props: InspectorProps) {
|
|
|
134
135
|
wsServer.on("connection", (ws: WebSocket) => {
|
|
135
136
|
if (wsServer.clients.size > 1) {
|
|
136
137
|
/** We only want to have one active Devtools instance at a time. */
|
|
137
|
-
|
|
138
|
+
logger.error(
|
|
138
139
|
"Tried to open a new devtools window when a previous one was already open."
|
|
139
140
|
);
|
|
140
141
|
ws.close(1013, "Too many clients; only one can be connected at a time");
|
|
@@ -154,19 +155,26 @@ export default function useInspector(props: InspectorProps) {
|
|
|
154
155
|
* of the component lifecycle. Convenient.
|
|
155
156
|
*/
|
|
156
157
|
useEffect(() => {
|
|
158
|
+
const abortController = new AbortController();
|
|
157
159
|
async function startInspectorProxy() {
|
|
158
160
|
await waitForPortToBeAvailable(props.port, {
|
|
159
161
|
retryPeriod: 200,
|
|
160
162
|
timeout: 2000,
|
|
163
|
+
abortSignal: abortController.signal,
|
|
161
164
|
});
|
|
162
165
|
server.listen(props.port);
|
|
163
166
|
}
|
|
164
|
-
startInspectorProxy().catch((err) =>
|
|
167
|
+
startInspectorProxy().catch((err) => {
|
|
168
|
+
if ((err as { code: string }).code !== "ABORT_ERR") {
|
|
169
|
+
logger.error("Failed to start inspector:", err);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
165
172
|
return () => {
|
|
166
173
|
server.close();
|
|
167
174
|
// Also disconnect any open websockets/devtools connections
|
|
168
175
|
wsServer.clients.forEach((ws) => ws.close());
|
|
169
176
|
wsServer.close();
|
|
177
|
+
abortController.abort();
|
|
170
178
|
};
|
|
171
179
|
}, [props.port, server, wsServer]);
|
|
172
180
|
|
|
@@ -247,9 +255,7 @@ export default function useInspector(props: InspectorProps) {
|
|
|
247
255
|
const evt = JSON.parse(event.data);
|
|
248
256
|
if (evt.method === "Runtime.exceptionThrown") {
|
|
249
257
|
const params = evt.params as Protocol.Runtime.ExceptionThrownEvent;
|
|
250
|
-
|
|
251
|
-
"🚨", // cheesy, but it works
|
|
252
|
-
// maybe we could use color here too.
|
|
258
|
+
logger.error(
|
|
253
259
|
params.exceptionDetails.text,
|
|
254
260
|
params.exceptionDetails.exception?.description ?? ""
|
|
255
261
|
);
|
|
@@ -261,7 +267,7 @@ export default function useInspector(props: InspectorProps) {
|
|
|
261
267
|
}
|
|
262
268
|
} else {
|
|
263
269
|
// We should never get here, but who know is 2022...
|
|
264
|
-
|
|
270
|
+
logger.error("Unrecognised devtools event:", event);
|
|
265
271
|
}
|
|
266
272
|
});
|
|
267
273
|
}
|
|
@@ -280,7 +286,7 @@ export default function useInspector(props: InspectorProps) {
|
|
|
280
286
|
});
|
|
281
287
|
|
|
282
288
|
ws.on("unexpected-response", () => {
|
|
283
|
-
|
|
289
|
+
logger.log("Waiting for connection...");
|
|
284
290
|
/**
|
|
285
291
|
* This usually means the worker is not "ready" yet
|
|
286
292
|
* so we'll just retry the connection process
|
|
@@ -386,7 +392,7 @@ export default function useInspector(props: InspectorProps) {
|
|
|
386
392
|
* happens on the first request. Maybe we should buffer
|
|
387
393
|
* these messages too?
|
|
388
394
|
*/
|
|
389
|
-
|
|
395
|
+
logger.error(e);
|
|
390
396
|
}
|
|
391
397
|
}
|
|
392
398
|
}
|
|
@@ -611,7 +617,7 @@ function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
|
|
|
611
617
|
break;
|
|
612
618
|
}
|
|
613
619
|
} else {
|
|
614
|
-
|
|
615
|
-
|
|
620
|
+
logger.warn(`Unsupported console method: ${method}`);
|
|
621
|
+
logger.warn("console event:", evt);
|
|
616
622
|
}
|
|
617
623
|
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TODO Remove once https://github.com/microsoft/TypeScript/pull/47254 lands
|
|
3
|
+
*/
|
|
4
|
+
declare namespace Intl {
|
|
5
|
+
interface DateTimeFormatOptions {
|
|
6
|
+
formatMatcher?: "basic" | "best fit" | "best fit" | undefined;
|
|
7
|
+
dateStyle?: "full" | "long" | "medium" | "short" | undefined;
|
|
8
|
+
timeStyle?: "full" | "long" | "medium" | "short" | undefined;
|
|
9
|
+
dayPeriod?: "narrow" | "short" | "long" | undefined;
|
|
10
|
+
fractionalSecondDigits?: 0 | 1 | 2 | 3 | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ResolvedDateTimeFormatOptions {
|
|
14
|
+
formatMatcher?: "basic" | "best fit" | "best fit";
|
|
15
|
+
dateStyle?: "full" | "long" | "medium" | "short";
|
|
16
|
+
timeStyle?: "full" | "long" | "medium" | "short";
|
|
17
|
+
hourCycle?: "h11" | "h12" | "h23" | "h24";
|
|
18
|
+
dayPeriod?: "narrow" | "short" | "long";
|
|
19
|
+
fractionalSecondDigits?: 0 | 1 | 2 | 3;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface NumberFormat {
|
|
23
|
+
formatRange(startDate: number | bigint, endDate: number | bigint): string;
|
|
24
|
+
formatRangeToParts(
|
|
25
|
+
startDate: number | bigint,
|
|
26
|
+
endDate: number | bigint
|
|
27
|
+
): NumberFormatPart[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The locale matching algorithm to use.
|
|
32
|
+
*
|
|
33
|
+
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).
|
|
34
|
+
*/
|
|
35
|
+
type ListFormatLocaleMatcher = "lookup" | "best fit";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The format of output message.
|
|
39
|
+
*
|
|
40
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
|
|
41
|
+
*/
|
|
42
|
+
type ListFormatType = "conjunction" | "disjunction" | "unit";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The length of the formatted message.
|
|
46
|
+
*
|
|
47
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
|
|
48
|
+
*/
|
|
49
|
+
type ListFormatStyle = "long" | "short" | "narrow";
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter.
|
|
53
|
+
*
|
|
54
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
|
|
55
|
+
*/
|
|
56
|
+
interface ListFormatOptions {
|
|
57
|
+
/** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
|
|
58
|
+
localeMatcher?: ListFormatLocaleMatcher;
|
|
59
|
+
/** The format of output message. */
|
|
60
|
+
type?: ListFormatType;
|
|
61
|
+
/** The length of the internationalized message. */
|
|
62
|
+
style?: ListFormatStyle;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface ListFormat {
|
|
66
|
+
/**
|
|
67
|
+
* Returns a string with a language-specific representation of the list.
|
|
68
|
+
*
|
|
69
|
+
* @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
|
|
70
|
+
*
|
|
71
|
+
* @throws `TypeError` if `list` includes something other than the possible values.
|
|
72
|
+
*
|
|
73
|
+
* @returns {string} A language-specific formatted string representing the elements of the list.
|
|
74
|
+
*
|
|
75
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format).
|
|
76
|
+
*/
|
|
77
|
+
format(list: Iterable<string>): string;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
|
|
81
|
+
*
|
|
82
|
+
* @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale.
|
|
83
|
+
*
|
|
84
|
+
* @throws `TypeError` if `list` includes something other than the possible values.
|
|
85
|
+
*
|
|
86
|
+
* @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list.
|
|
87
|
+
*
|
|
88
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts).
|
|
89
|
+
*/
|
|
90
|
+
formatToParts(
|
|
91
|
+
list: Iterable<string>
|
|
92
|
+
): { type: "element" | "literal"; value: string }[];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const ListFormat: {
|
|
96
|
+
prototype: ListFormat;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Creates [Intl.ListFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that
|
|
100
|
+
* enable language-sensitive list formatting.
|
|
101
|
+
*
|
|
102
|
+
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
|
|
103
|
+
* For the general form and interpretation of the `locales` argument,
|
|
104
|
+
* see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
|
|
105
|
+
*
|
|
106
|
+
* @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters)
|
|
107
|
+
* with some or all options of `ListFormatOptions`.
|
|
108
|
+
*
|
|
109
|
+
* @returns [Intl.ListFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object.
|
|
110
|
+
*
|
|
111
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat).
|
|
112
|
+
*/
|
|
113
|
+
new (
|
|
114
|
+
locales?: BCP47LanguageTag | BCP47LanguageTag[],
|
|
115
|
+
options?: ListFormatOptions
|
|
116
|
+
): ListFormat;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Returns an array containing those of the provided locales that are
|
|
120
|
+
* supported in list formatting without having to fall back to the runtime's default locale.
|
|
121
|
+
*
|
|
122
|
+
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
|
|
123
|
+
* For the general form and interpretation of the `locales` argument,
|
|
124
|
+
* see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
|
|
125
|
+
*
|
|
126
|
+
* @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters).
|
|
127
|
+
* with some or all possible options.
|
|
128
|
+
*
|
|
129
|
+
* @returns An array of strings representing a subset of the given locale tags that are supported in list
|
|
130
|
+
* formatting without having to fall back to the runtime's default locale.
|
|
131
|
+
*
|
|
132
|
+
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf).
|
|
133
|
+
*/
|
|
134
|
+
supportedLocalesOf(
|
|
135
|
+
locales: BCP47LanguageTag | BCP47LanguageTag[],
|
|
136
|
+
options?: Pick<ListFormatOptions, "localeMatcher">
|
|
137
|
+
): BCP47LanguageTag[];
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { URLSearchParams } from "node:url";
|
|
2
|
-
import { fetchListResult, fetchResult, fetchKVGetValue } from "
|
|
3
|
-
import type { Config
|
|
2
|
+
import { fetchListResult, fetchResult, fetchKVGetValue } from "./cfetch";
|
|
3
|
+
import type { Config } from "./config";
|
|
4
4
|
|
|
5
5
|
/** The largest number of kv items we can pass to the API in a single request. */
|
|
6
6
|
const API_MAX = 10000;
|
|
@@ -11,7 +11,6 @@ const BATCH_KEY_MAX = API_MAX / 2;
|
|
|
11
11
|
type KvArgs = {
|
|
12
12
|
binding?: string;
|
|
13
13
|
"namespace-id"?: string;
|
|
14
|
-
env?: string;
|
|
15
14
|
preview?: boolean;
|
|
16
15
|
};
|
|
17
16
|
|
|
@@ -217,8 +216,8 @@ export async function deleteBulkKeyValue(
|
|
|
217
216
|
}
|
|
218
217
|
|
|
219
218
|
export function getNamespaceId(
|
|
220
|
-
{ preview, binding, "namespace-id": namespaceId
|
|
221
|
-
|
|
219
|
+
{ preview, binding, "namespace-id": namespaceId }: KvArgs,
|
|
220
|
+
config: Config
|
|
222
221
|
): string {
|
|
223
222
|
// nice
|
|
224
223
|
if (namespaceId) {
|
|
@@ -228,45 +227,26 @@ export function getNamespaceId(
|
|
|
228
227
|
// begin pre-flight checks
|
|
229
228
|
|
|
230
229
|
// `--binding` is only valid if there's a wrangler configuration.
|
|
231
|
-
if (binding && !
|
|
230
|
+
if (binding && !config) {
|
|
232
231
|
throw new Error("--binding specified, but no config file was found.");
|
|
233
232
|
}
|
|
234
233
|
|
|
235
234
|
// there's no config. abort here
|
|
236
|
-
if (!
|
|
235
|
+
if (!config) {
|
|
237
236
|
throw new Error(
|
|
238
237
|
"Failed to find a config file.\n" +
|
|
239
238
|
"Either use --namespace-id to upload directly or create a configuration file with a binding."
|
|
240
239
|
);
|
|
241
240
|
}
|
|
242
241
|
|
|
243
|
-
// they want to use an environment, actually
|
|
244
|
-
if (env) {
|
|
245
|
-
if (!("env" in configOrEnv) || !configOrEnv.env[env]) {
|
|
246
|
-
throw new Error(
|
|
247
|
-
`Failed to find environment "${env}" in configuration file!`
|
|
248
|
-
);
|
|
249
|
-
}
|
|
250
|
-
return getNamespaceId(
|
|
251
|
-
{
|
|
252
|
-
binding,
|
|
253
|
-
"namespace-id": namespaceId,
|
|
254
|
-
preview,
|
|
255
|
-
},
|
|
256
|
-
configOrEnv.env[env]
|
|
257
|
-
);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
242
|
// there's no KV namespaces
|
|
261
|
-
if (!
|
|
243
|
+
if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
|
|
262
244
|
throw new Error(
|
|
263
245
|
"No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
|
|
264
246
|
);
|
|
265
247
|
}
|
|
266
248
|
|
|
267
|
-
const namespace =
|
|
268
|
-
(ns) => ns.binding === binding
|
|
269
|
-
);
|
|
249
|
+
const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
|
|
270
250
|
|
|
271
251
|
// we couldn't find a namespace with that binding
|
|
272
252
|
if (!namespace) {
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { format } from "node:util";
|
|
2
|
+
import { formatMessagesSync } from "esbuild";
|
|
3
|
+
|
|
4
|
+
const LOGGER_LEVELS = {
|
|
5
|
+
error: 0,
|
|
6
|
+
warn: 1,
|
|
7
|
+
log: 2,
|
|
8
|
+
debug: 3,
|
|
9
|
+
} as const;
|
|
10
|
+
|
|
11
|
+
type LoggerLevel = keyof typeof LOGGER_LEVELS;
|
|
12
|
+
|
|
13
|
+
/** A map from LOGGER_LEVEL to the error `kind` needed by `formatMessagesSync()`. */
|
|
14
|
+
const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
|
|
15
|
+
error: "error",
|
|
16
|
+
warn: "warning",
|
|
17
|
+
log: undefined,
|
|
18
|
+
debug: undefined,
|
|
19
|
+
} as const;
|
|
20
|
+
|
|
21
|
+
class Logger {
|
|
22
|
+
constructor(public loggerLevel: LoggerLevel = "log") {}
|
|
23
|
+
|
|
24
|
+
columns = process.stdout.columns;
|
|
25
|
+
|
|
26
|
+
debug = (...args: unknown[]) => this.doLog("debug", args);
|
|
27
|
+
log = (...args: unknown[]) => this.doLog("log", args);
|
|
28
|
+
warn = (...args: unknown[]) => this.doLog("warn", args);
|
|
29
|
+
error = (...args: unknown[]) => this.doLog("error", args);
|
|
30
|
+
|
|
31
|
+
private doLog(messageLevel: LoggerLevel, args: unknown[]) {
|
|
32
|
+
if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
|
|
33
|
+
console[messageLevel](this.formatMessage(messageLevel, format(...args)));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private formatMessage(level: LoggerLevel, message: string): string {
|
|
38
|
+
const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
|
|
39
|
+
if (kind) {
|
|
40
|
+
// Format the message using the esbuild formatter.
|
|
41
|
+
// The first line of the message is the main `text`,
|
|
42
|
+
// subsequent lines are put into the `notes`.
|
|
43
|
+
const [firstLine, ...otherLines] = message.split("\n");
|
|
44
|
+
const notes =
|
|
45
|
+
otherLines.length > 0
|
|
46
|
+
? otherLines.map((text) => ({ text }))
|
|
47
|
+
: undefined;
|
|
48
|
+
return formatMessagesSync([{ text: firstLine, notes }], {
|
|
49
|
+
color: true,
|
|
50
|
+
kind,
|
|
51
|
+
terminalWidth: this.columns,
|
|
52
|
+
})[0];
|
|
53
|
+
} else {
|
|
54
|
+
return message;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A drop-in replacement for `console` for outputting logging messages.
|
|
61
|
+
*
|
|
62
|
+
* Errors and Warnings will get additional formatting to highlight them to the user.
|
|
63
|
+
* You can also set a `logger.loggerLevel` value to one of "debug", "log", "warn" or "error",
|
|
64
|
+
* to filter out logging messages.
|
|
65
|
+
*/
|
|
66
|
+
export const logger = new Logger();
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Custom Miniflare CLI
|
|
2
|
+
|
|
3
|
+
This directory contains a simple wrapper around the programmatic Miniflare API,
|
|
4
|
+
which Wrangler spawns when running `wrangler dev` in local mode.
|
|
5
|
+
|
|
6
|
+
## Building
|
|
7
|
+
|
|
8
|
+
This CLI is built at the same time as Wrangler by running
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
npm run -w wrangler build
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The output of the build is `miniflare-dist/index.mjs`.
|
|
15
|
+
|
|
16
|
+
## Running
|
|
17
|
+
|
|
18
|
+
The CLI expects a single command line argument which is the Miniflare options formatted as a string of JSON.
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
node --no-warnings ./packages/wrangler/miniflare-dist/index.mjs '{"watch": true, "script": ""}' --log VERBOSE
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The `--log` argument is optional and takes one of Miniflare's LogLevels: "NONE", "ERROR", "WARN", "INFO", "DEBUG", "VERBOSE".
|
|
25
|
+
It defaults to `INFO`.
|
|
26
|
+
|
|
27
|
+
## Debugging
|
|
28
|
+
|
|
29
|
+
Simply place a breakpoint in the code and run the above command in the VS Code "JavaScript Debug Terminal".
|
|
30
|
+
The code will stop at the breakpoint as expected.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type EnumKeys<Enum> = Exclude<keyof Enum, number>;
|
|
2
|
+
|
|
3
|
+
export const enumObject = <Enum extends Record<string, number | string>>(
|
|
4
|
+
e: Enum
|
|
5
|
+
) => {
|
|
6
|
+
const copy = { ...e } as { [K in EnumKeys<Enum>]: Enum[K] };
|
|
7
|
+
Object.values(e).forEach(
|
|
8
|
+
(value) => typeof value === "number" && delete copy[value]
|
|
9
|
+
);
|
|
10
|
+
return copy;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const enumKeys = <Enum extends Record<string, number | string>>(
|
|
14
|
+
e: Enum
|
|
15
|
+
) => {
|
|
16
|
+
return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
|
|
17
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Log, LogLevel, Miniflare } from "miniflare";
|
|
2
|
+
import yargs from "yargs";
|
|
3
|
+
import { hideBin } from "yargs/helpers";
|
|
4
|
+
import { enumKeys } from "./enum-keys";
|
|
5
|
+
import { getRequestContextCheckOptions } from "./request-context";
|
|
6
|
+
|
|
7
|
+
async function main() {
|
|
8
|
+
const args = await yargs(hideBin(process.argv))
|
|
9
|
+
.help(false)
|
|
10
|
+
.version(false)
|
|
11
|
+
.option("log", {
|
|
12
|
+
choices: enumKeys(LogLevel),
|
|
13
|
+
}).argv;
|
|
14
|
+
|
|
15
|
+
const logLevel = LogLevel[args.log ?? "INFO"];
|
|
16
|
+
const requestContextCheckOptions = await getRequestContextCheckOptions();
|
|
17
|
+
const config = {
|
|
18
|
+
...JSON.parse((args._[0] as string) ?? "{}"),
|
|
19
|
+
...requestContextCheckOptions,
|
|
20
|
+
log: new Log(logLevel),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
if (logLevel > LogLevel.INFO) {
|
|
24
|
+
console.log("OPTIONS:\n", JSON.stringify(config, null, 2));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const mf = new Miniflare(config);
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
// Start Miniflare development server
|
|
31
|
+
await mf.startServer();
|
|
32
|
+
await mf.startScheduler();
|
|
33
|
+
} catch (e) {
|
|
34
|
+
mf.log.error(e as Error);
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
// Unmount any mounted workers
|
|
37
|
+
await mf.dispose();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
await main();
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { MiniflareOptions } from "miniflare";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Certain runtime APIs are only available to workers during the "request context",
|
|
5
|
+
* which is any code that returns after receiving a request and before returning
|
|
6
|
+
* a response.
|
|
7
|
+
*
|
|
8
|
+
* Miniflare emulates this behavior by using an [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and
|
|
9
|
+
* [checking at runtime](https://github.com/cloudflare/miniflare/blob/master/packages/shared/src/context.ts#L21-L36)
|
|
10
|
+
* to see if you're using those APIs during the request context.
|
|
11
|
+
*
|
|
12
|
+
* In certain environments `AsyncLocalStorage` is unavailable, such as in a
|
|
13
|
+
* [webcontainer](https://github.com/stackblitz/webcontainer-core).
|
|
14
|
+
* This function figures out if we're able to run those "request context" checks
|
|
15
|
+
* and returns [a set of options](https://miniflare.dev/core/standards#global-functionality-limits)
|
|
16
|
+
* that indicate to miniflare whether to run the checks or not.
|
|
17
|
+
*/
|
|
18
|
+
export const getRequestContextCheckOptions = async (): Promise<
|
|
19
|
+
Pick<MiniflareOptions, "globalAsyncIO" | "globalTimers" | "globalRandom">
|
|
20
|
+
> => {
|
|
21
|
+
// check that there's an implementation of AsyncLocalStorage
|
|
22
|
+
let hasAsyncLocalStorage = true;
|
|
23
|
+
try {
|
|
24
|
+
// ripped from the example here https://nodejs.org/api/async_context.html#class-asynclocalstorage
|
|
25
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
26
|
+
const storage = new AsyncLocalStorage<string>();
|
|
27
|
+
|
|
28
|
+
hasAsyncLocalStorage = storage.run("some-value", () => {
|
|
29
|
+
return storage.getStore() === "some-value";
|
|
30
|
+
});
|
|
31
|
+
} catch (e) {
|
|
32
|
+
hasAsyncLocalStorage = false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
globalAsyncIO: hasAsyncLocalStorage,
|
|
37
|
+
globalRandom: hasAsyncLocalStorage,
|
|
38
|
+
globalTimers: hasAsyncLocalStorage,
|
|
39
|
+
};
|
|
40
|
+
};
|