wrangler 0.0.0-e3cab74 → 0.0.0-e3e3243

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 (66) hide show
  1. package/README.md +1 -1
  2. package/bin/wrangler.js +10 -1
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +10 -7
  6. package/pages/functions/filepath-routing.test.ts +125 -25
  7. package/pages/functions/filepath-routing.ts +6 -3
  8. package/src/__tests__/configuration.test.ts +959 -324
  9. package/src/__tests__/dev.test.tsx +512 -84
  10. package/src/__tests__/guess-worker-format.test.ts +19 -17
  11. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  12. package/src/__tests__/helpers/mock-cfetch.ts +3 -3
  13. package/src/__tests__/helpers/mock-console.ts +17 -9
  14. package/src/__tests__/helpers/mock-kv.ts +9 -16
  15. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  16. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  17. package/src/__tests__/https-options.test.ts +127 -0
  18. package/src/__tests__/index.test.ts +128 -11
  19. package/src/__tests__/jest.setup.ts +16 -4
  20. package/src/__tests__/kv.test.ts +364 -125
  21. package/src/__tests__/logout.test.ts +15 -13
  22. package/src/__tests__/pages.test.ts +82 -0
  23. package/src/__tests__/publish.test.ts +1838 -735
  24. package/src/__tests__/r2.test.ts +4 -4
  25. package/src/__tests__/route.test.ts +45 -0
  26. package/src/__tests__/secret.test.ts +167 -68
  27. package/src/__tests__/tail.test.ts +2 -4
  28. package/src/__tests__/whoami.test.tsx +21 -7
  29. package/src/bundle.ts +27 -5
  30. package/src/cfetch/internal.ts +11 -5
  31. package/src/config/README.md +6 -6
  32. package/src/config/config.ts +54 -101
  33. package/src/config/environment.ts +67 -1
  34. package/src/config/index.ts +13 -3
  35. package/src/config/validation-helpers.ts +207 -23
  36. package/src/config/validation.ts +344 -129
  37. package/src/{api/preview.ts → create-worker-preview.ts} +39 -20
  38. package/src/{api/form_data.ts → create-worker-upload-form.ts} +1 -1
  39. package/src/dev/dev.tsx +392 -0
  40. package/src/dev/local.tsx +232 -0
  41. package/src/dev/remote.tsx +203 -0
  42. package/src/dev/use-esbuild.ts +104 -0
  43. package/src/entry.ts +192 -9
  44. package/src/https-options.ts +122 -0
  45. package/src/index.tsx +577 -515
  46. package/src/inspect.ts +9 -1
  47. package/src/intl-polyfill.d.ts +139 -0
  48. package/src/{kv.tsx → kv.ts} +97 -53
  49. package/src/miniflare-cli/README.md +30 -0
  50. package/src/miniflare-cli/enum-keys.ts +17 -0
  51. package/src/miniflare-cli/index.ts +37 -0
  52. package/src/module-collection.ts +90 -2
  53. package/src/open-in-browser.ts +14 -2
  54. package/src/pages.tsx +26 -10
  55. package/src/proxy.ts +104 -40
  56. package/src/publish.ts +53 -71
  57. package/src/reporting.ts +25 -9
  58. package/src/selfsigned.d.ts +29 -0
  59. package/src/sites.tsx +68 -29
  60. package/src/user.tsx +163 -85
  61. package/src/{api/worker.ts → worker.ts} +1 -24
  62. package/wrangler-dist/cli.js +5933 -3842
  63. package/wrangler-dist/cli.js.map +3 -3
  64. package/src/__tests__/helpers/mock-user.ts +0 -27
  65. package/src/dev.tsx +0 -961
  66. package/src/guess-worker-format.ts +0 -68
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 { waitForPortToBeAvailable } from "./proxy";
8
9
  import type Protocol from "devtools-protocol";
9
10
  import type { IncomingMessage, Server, ServerResponse } from "node:http";
10
11
  import type { MessageEvent } from "ws";
@@ -153,7 +154,14 @@ export default function useInspector(props: InspectorProps) {
153
154
  * of the component lifecycle. Convenient.
154
155
  */
155
156
  useEffect(() => {
156
- server.listen(props.port);
157
+ async function startInspectorProxy() {
158
+ await waitForPortToBeAvailable(props.port, {
159
+ retryPeriod: 200,
160
+ timeout: 2000,
161
+ });
162
+ server.listen(props.port);
163
+ }
164
+ startInspectorProxy().catch((err) => console.error(err));
157
165
  return () => {
158
166
  server.close();
159
167
  // Also disconnect any open websockets/devtools connections
@@ -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,11 +1,16 @@
1
1
  import { URLSearchParams } from "node:url";
2
2
  import { fetchListResult, fetchResult, fetchKVGetValue } from "./cfetch";
3
- import type { Config, Environment } from "./config";
3
+ import type { Config } from "./config";
4
+
5
+ /** The largest number of kv items we can pass to the API in a single request. */
6
+ const API_MAX = 10000;
7
+ // The const below are halved from the API's true capacity to help avoid
8
+ // hammering it with large requests.
9
+ const BATCH_KEY_MAX = API_MAX / 2;
4
10
 
5
11
  type KvArgs = {
6
12
  binding?: string;
7
13
  "namespace-id"?: string;
8
- env?: string;
9
14
  preview?: boolean;
10
15
  };
11
16
 
@@ -90,26 +95,64 @@ export async function listNamespaceKeys(
90
95
  );
91
96
  }
92
97
 
98
+ /**
99
+ * Information about a key-value pair, including its "metadata" fields.
100
+ */
101
+ export interface KeyValue {
102
+ key: string;
103
+ value: string;
104
+ expiration?: number;
105
+ expiration_ttl?: number;
106
+ metadata?: object;
107
+ base64?: boolean;
108
+ }
109
+
110
+ const KeyValueKeys = new Set([
111
+ "key",
112
+ "value",
113
+ "expiration",
114
+ "expiration_ttl",
115
+ "metadata",
116
+ "base64",
117
+ ]);
118
+
119
+ /**
120
+ * Is the given object a valid `KeyValue` type?
121
+ */
122
+ export function isKeyValue(keyValue: object): keyValue is KeyValue {
123
+ const props = Object.keys(keyValue);
124
+ if (!props.includes("key") || !props.includes("value")) {
125
+ return false;
126
+ }
127
+ return true;
128
+ }
129
+
130
+ /**
131
+ * Get all the properties on the `keyValue` that are not expected.
132
+ */
133
+ export function unexpectedKeyValueProps(keyValue: KeyValue): string[] {
134
+ const props = Object.keys(keyValue);
135
+ return props.filter((prop) => !KeyValueKeys.has(prop));
136
+ }
137
+
93
138
  export async function putKeyValue(
94
139
  accountId: string,
95
140
  namespaceId: string,
96
- key: string,
97
- value: string,
98
- args?: { expiration?: number; expiration_ttl?: number }
141
+ keyValue: KeyValue
99
142
  ) {
100
143
  let searchParams: URLSearchParams | undefined;
101
- if (args) {
144
+ if (keyValue.expiration || keyValue.expiration_ttl) {
102
145
  searchParams = new URLSearchParams();
103
- if (args.expiration) {
104
- searchParams.set("expiration", `${args.expiration}`);
146
+ if (keyValue.expiration) {
147
+ searchParams.set("expiration", `${keyValue.expiration}`);
105
148
  }
106
- if (args.expiration_ttl) {
107
- searchParams.set("expiration_ttl", `${args.expiration_ttl}`);
149
+ if (keyValue.expiration_ttl) {
150
+ searchParams.set("expiration_ttl", `${keyValue.expiration_ttl}`);
108
151
  }
109
152
  }
110
153
  return await fetchResult(
111
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`,
112
- { method: "PUT", body: value },
154
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${keyValue.key}`,
155
+ { method: "PUT", body: keyValue.value },
113
156
  searchParams
114
157
  );
115
158
  }
@@ -125,36 +168,56 @@ export async function getKeyValue(
125
168
  export async function putBulkKeyValue(
126
169
  accountId: string,
127
170
  namespaceId: string,
128
- keyvalueStr: string
171
+ keyValues: KeyValue[],
172
+ progressCallback: (index: number, total: number) => void
129
173
  ) {
130
- return await fetchResult(
131
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
132
- {
133
- method: "PUT",
134
- body: keyvalueStr,
135
- headers: { "Content-Type": "application/json" },
174
+ for (let index = 0; index < keyValues.length; index += BATCH_KEY_MAX) {
175
+ if (progressCallback && keyValues.length > BATCH_KEY_MAX) {
176
+ progressCallback(index, keyValues.length);
136
177
  }
137
- );
178
+
179
+ await fetchResult(
180
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
181
+ {
182
+ method: "PUT",
183
+ body: JSON.stringify(keyValues.slice(index, index + BATCH_KEY_MAX)),
184
+ headers: { "Content-Type": "application/json" },
185
+ }
186
+ );
187
+ }
188
+ if (progressCallback && keyValues.length > BATCH_KEY_MAX) {
189
+ progressCallback(keyValues.length, keyValues.length);
190
+ }
138
191
  }
139
192
 
140
193
  export async function deleteBulkKeyValue(
141
194
  accountId: string,
142
195
  namespaceId: string,
143
- keyStr: string
196
+ keys: string[],
197
+ progressCallback: (index: number, total: number) => void
144
198
  ) {
145
- return await fetchResult(
146
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
147
- {
148
- method: "DELETE",
149
- body: keyStr,
150
- headers: { "Content-Type": "application/json" },
199
+ for (let index = 0; index < keys.length; index += BATCH_KEY_MAX) {
200
+ if (progressCallback && keys.length > BATCH_KEY_MAX) {
201
+ progressCallback(index, keys.length);
151
202
  }
152
- );
203
+
204
+ await fetchResult(
205
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
206
+ {
207
+ method: "DELETE",
208
+ body: JSON.stringify(keys.slice(index, index + BATCH_KEY_MAX)),
209
+ headers: { "Content-Type": "application/json" },
210
+ }
211
+ );
212
+ }
213
+ if (progressCallback && keys.length > BATCH_KEY_MAX) {
214
+ progressCallback(keys.length, keys.length);
215
+ }
153
216
  }
154
217
 
155
218
  export function getNamespaceId(
156
- { preview, binding, "namespace-id": namespaceId, env }: KvArgs,
157
- configOrEnv: Config | Environment | undefined
219
+ { preview, binding, "namespace-id": namespaceId }: KvArgs,
220
+ config: Config
158
221
  ): string {
159
222
  // nice
160
223
  if (namespaceId) {
@@ -164,45 +227,26 @@ export function getNamespaceId(
164
227
  // begin pre-flight checks
165
228
 
166
229
  // `--binding` is only valid if there's a wrangler configuration.
167
- if (binding && !configOrEnv) {
230
+ if (binding && !config) {
168
231
  throw new Error("--binding specified, but no config file was found.");
169
232
  }
170
233
 
171
234
  // there's no config. abort here
172
- if (!configOrEnv) {
235
+ if (!config) {
173
236
  throw new Error(
174
237
  "Failed to find a config file.\n" +
175
238
  "Either use --namespace-id to upload directly or create a configuration file with a binding."
176
239
  );
177
240
  }
178
241
 
179
- // they want to use an environment, actually
180
- if (env) {
181
- if (!("env" in configOrEnv) || !configOrEnv.env[env]) {
182
- throw new Error(
183
- `Failed to find environment "${env}" in configuration file!`
184
- );
185
- }
186
- return getNamespaceId(
187
- {
188
- binding,
189
- "namespace-id": namespaceId,
190
- preview,
191
- },
192
- configOrEnv.env[env]
193
- );
194
- }
195
-
196
242
  // there's no KV namespaces
197
- if (!configOrEnv.kv_namespaces || configOrEnv.kv_namespaces.length === 0) {
243
+ if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
198
244
  throw new Error(
199
245
  "No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
200
246
  );
201
247
  }
202
248
 
203
- const namespace = configOrEnv.kv_namespaces.find(
204
- (ns) => ns.binding === binding
205
- );
249
+ const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
206
250
 
207
251
  // we couldn't find a namespace with that binding
208
252
  if (!namespace) {
@@ -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,37 @@
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
+
6
+ async function main() {
7
+ const args = await yargs(hideBin(process.argv))
8
+ .help(false)
9
+ .version(false)
10
+ .option("log", {
11
+ choices: enumKeys(LogLevel),
12
+ }).argv;
13
+
14
+ const logLevel = LogLevel[args.log ?? "INFO"];
15
+ const config = {
16
+ ...JSON.parse((args._[0] as string) ?? "{}"),
17
+ log: new Log(logLevel),
18
+ };
19
+
20
+ if (logLevel > LogLevel.INFO) {
21
+ console.log("OPTIONS:\n", JSON.stringify(config, null, 2));
22
+ }
23
+
24
+ const mf = new Miniflare(config);
25
+
26
+ try {
27
+ // Start Miniflare development server
28
+ await mf.startServer();
29
+ } catch (e) {
30
+ mf.log.error(e as Error);
31
+ process.exitCode = 1;
32
+ // Unmount any mounted workers
33
+ await mf.dispose();
34
+ }
35
+ }
36
+
37
+ await main();
@@ -2,8 +2,8 @@ import crypto from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import globToRegExp from "glob-to-regexp";
5
- import type { CfModule, CfModuleType, CfScriptFormat } from "./api/worker";
6
5
  import type { Config, ConfigModuleRuleType } from "./config";
6
+ import type { CfModule, CfModuleType, CfScriptFormat } from "./worker";
7
7
  import type esbuild from "esbuild";
8
8
 
9
9
  const RuleTypeToModuleType: Record<ConfigModuleRuleType, CfModuleType> = {
@@ -28,9 +28,15 @@ export const DEFAULT_MODULE_RULES: Config["rules"] = [
28
28
  { type: "CompiledWasm", globs: ["**/*.wasm"] },
29
29
  ];
30
30
 
31
- export default function makeModuleCollector(props: {
31
+ export default function createModuleCollector(props: {
32
32
  format: CfScriptFormat;
33
33
  rules?: Config["rules"];
34
+ // a collection of "legacy" style module references, which are just file names
35
+ // we will eventually deprecate this functionality, hence the verbose greppable name
36
+ wrangler1xlegacyModuleReferences: {
37
+ rootDirectory: string;
38
+ fileNames: Set<string>;
39
+ };
34
40
  }): {
35
41
  modules: CfModule[];
36
42
  plugin: esbuild.Plugin;
@@ -41,6 +47,10 @@ export default function makeModuleCollector(props: {
41
47
  ...DEFAULT_MODULE_RULES!,
42
48
  ];
43
49
 
50
+ // First, we want to add some validations to the module rules
51
+ // We want to warn if rules are accidentally configured in such a way that
52
+ // subsequent rules will never match because `fallthrough` hasn't been set
53
+
44
54
  const completedRuleLocations: Record<string, number> = {};
45
55
  let index = 0;
46
56
  const rulesToRemove: Config["rules"] = [];
@@ -92,6 +102,84 @@ export default function makeModuleCollector(props: {
92
102
  modules.splice(0);
93
103
  });
94
104
 
105
+ // ~ start legacy module specifier support ~
106
+
107
+ // This section detects usage of "legacy" 1.x style module specifiers
108
+ // and modifies them so they "work" in wrangler v2, but with a warning
109
+
110
+ const rulesMatchers = rules.flatMap((rule) => {
111
+ return rule.globs.map((glob) => {
112
+ const regex = globToRegExp(glob);
113
+ return {
114
+ regex,
115
+ rule,
116
+ };
117
+ });
118
+ });
119
+
120
+ if (props.wrangler1xlegacyModuleReferences.fileNames.size > 0) {
121
+ build.onResolve(
122
+ {
123
+ filter: new RegExp(
124
+ "^(" +
125
+ [...props.wrangler1xlegacyModuleReferences.fileNames].join(
126
+ "|"
127
+ ) +
128
+ ")$"
129
+ ),
130
+ },
131
+ async (args: esbuild.OnResolveArgs) => {
132
+ if (
133
+ args.kind !== "import-statement" &&
134
+ args.kind !== "require-call"
135
+ ) {
136
+ return;
137
+ }
138
+ // In the future, this will simply throw an error
139
+ console.warn(
140
+ `Deprecation warning: detected a legacy module import in "./${path.relative(
141
+ process.cwd(),
142
+ args.importer
143
+ )}". This will stop working in the future. Replace references to "${
144
+ args.path
145
+ }" with "./${args.path}";`
146
+ );
147
+
148
+ // take the file and massage it to a
149
+ // transportable/manageable format
150
+ const filePath = path.join(
151
+ props.wrangler1xlegacyModuleReferences.rootDirectory,
152
+ args.path
153
+ );
154
+ const fileContent = await readFile(filePath);
155
+ const fileHash = crypto
156
+ .createHash("sha1")
157
+ .update(fileContent)
158
+ .digest("hex");
159
+ const fileName = `./${fileHash}-${path.basename(args.path)}`;
160
+
161
+ const { rule } =
162
+ rulesMatchers.find(({ regex }) => regex.test(fileName)) || {};
163
+ if (rule) {
164
+ // add the module to the array
165
+ modules.push({
166
+ name: fileName,
167
+ content: fileContent,
168
+ type: RuleTypeToModuleType[rule.type],
169
+ });
170
+ return {
171
+ path: fileName, // change the reference to the changed module
172
+ external: props.format === "modules", // mark it as external in the bundle
173
+ namespace: `wrangler-module-${rule.type}`, // just a tag, this isn't strictly necessary
174
+ watchFiles: [filePath], // we also add the file to esbuild's watch list
175
+ };
176
+ }
177
+ }
178
+ );
179
+ }
180
+
181
+ // ~ end legacy module specifier support ~
182
+
95
183
  rules?.forEach((rule) => {
96
184
  if (rule.type === "ESModule" || rule.type === "CommonJS") return; // TODO: we should treat these as js files, and use the jsx loader
97
185
 
@@ -1,12 +1,24 @@
1
1
  import open from "open";
2
+
2
3
  /**
3
4
  * An extremely simple wrapper around the open command.
4
5
  * Specifically, it adds an 'error' event handler so that when this function
5
6
  * is called in environments where we can't open the browser (e.g. github codespaces,
6
7
  * stackblitz, remote servers), it doesn't just crash the process.
8
+ *
9
+ * @param url the URL to point the browser at
10
+ * @param options open a chromium-based browser instead of the default
7
11
  */
8
- export default async function openInBrowser(url: string): Promise<void> {
9
- const childProcess = await open(url);
12
+ export default async function openInBrowser(
13
+ url: string,
14
+ { forceChromium }: { forceChromium: boolean } = { forceChromium: false }
15
+ ): Promise<void> {
16
+ const options: open.Options | undefined = forceChromium
17
+ ? {
18
+ app: [{ name: open.apps.chrome }, { name: open.apps.edge }],
19
+ }
20
+ : undefined;
21
+ const childProcess = await open(url, options);
10
22
  childProcess.on("error", () => {
11
23
  console.warn(`Failed to open ${url} in a browser`);
12
24
  });