wrangler 0.0.0-e151223 → 0.0.0-e1b8ac4

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 (156) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4886 -0
  6. package/package.json +57 -28
  7. package/pages/functions/buildPlugin.ts +105 -0
  8. package/pages/functions/buildWorker.ts +93 -4
  9. package/pages/functions/filepath-routing.test.ts +223 -36
  10. package/pages/functions/filepath-routing.ts +78 -120
  11. package/pages/functions/routes.ts +13 -17
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +24 -17
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3548 -0
  16. package/src/__tests__/dev.test.tsx +1049 -65
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  19. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  20. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  21. package/src/__tests__/helpers/mock-bin.ts +36 -0
  22. package/src/__tests__/helpers/mock-cfetch.ts +48 -10
  23. package/src/__tests__/helpers/mock-console.ts +39 -8
  24. package/src/__tests__/helpers/mock-dialogs.ts +99 -11
  25. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  26. package/src/__tests__/helpers/mock-istty.ts +27 -0
  27. package/src/__tests__/helpers/mock-kv.ts +9 -16
  28. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  29. package/src/__tests__/helpers/mock-process.ts +24 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +160 -309
  38. package/src/__tests__/init.test.ts +1992 -0
  39. package/src/__tests__/jest.setup.ts +79 -6
  40. package/src/__tests__/kv.test.ts +651 -280
  41. package/src/__tests__/logger.test.ts +141 -0
  42. package/src/__tests__/package-manager.test.ts +353 -0
  43. package/src/__tests__/pages.test.ts +754 -0
  44. package/src/__tests__/parse.test.ts +330 -0
  45. package/src/__tests__/publish.test.ts +5671 -959
  46. package/src/__tests__/r2.test.ts +233 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +362 -91
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +132 -0
  51. package/src/__tests__/whoami.test.tsx +60 -7
  52. package/src/abort.d.ts +3 -0
  53. package/src/bundle.ts +204 -0
  54. package/src/cfetch/index.ts +28 -18
  55. package/src/cfetch/internal.ts +99 -29
  56. package/src/cli.ts +6 -2
  57. package/src/config/README.md +107 -0
  58. package/src/config/config.ts +243 -0
  59. package/src/config/diagnostics.ts +80 -0
  60. package/src/config/environment.ts +420 -0
  61. package/src/config/index.ts +225 -0
  62. package/src/config/validation-helpers.ts +584 -0
  63. package/src/config/validation.ts +1580 -0
  64. package/src/config-cache.ts +45 -0
  65. package/src/create-worker-preview.ts +185 -0
  66. package/src/create-worker-upload-form.ts +254 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +399 -0
  69. package/src/dev/local.tsx +321 -0
  70. package/src/dev/remote.tsx +242 -0
  71. package/src/dev/use-esbuild.ts +112 -0
  72. package/src/dialogs.tsx +64 -6
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +322 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/generate-auth-url.ts +33 -0
  78. package/src/generate-random-state.ts +16 -0
  79. package/src/https-options.ts +123 -0
  80. package/src/index.tsx +1835 -988
  81. package/src/inspect.ts +80 -14
  82. package/src/intl-polyfill.d.ts +139 -0
  83. package/src/{kv.tsx → kv.ts} +199 -67
  84. package/src/logger.ts +73 -0
  85. package/src/miniflare-cli/README.md +30 -0
  86. package/src/miniflare-cli/enum-keys.ts +17 -0
  87. package/src/miniflare-cli/index.ts +41 -0
  88. package/src/miniflare-cli/request-context.ts +40 -0
  89. package/src/module-collection.ts +226 -31
  90. package/src/open-in-browser.ts +17 -0
  91. package/src/package-manager.ts +174 -0
  92. package/src/pages.tsx +1132 -84
  93. package/src/parse.ts +222 -0
  94. package/src/proxy.ts +176 -70
  95. package/src/publish.ts +624 -308
  96. package/src/r2.ts +50 -0
  97. package/src/selfsigned.d.ts +29 -0
  98. package/src/sites.tsx +185 -57
  99. package/src/tail/filters.ts +279 -0
  100. package/src/tail/index.ts +299 -0
  101. package/src/tail/printing.ts +67 -0
  102. package/src/update-check.ts +19 -0
  103. package/src/user.tsx +349 -166
  104. package/src/whoami.tsx +5 -3
  105. package/src/{api/worker.ts → worker.ts} +65 -39
  106. package/src/zones.ts +73 -0
  107. package/templates/gitignore +171 -0
  108. package/templates/new-worker-scheduled.js +17 -0
  109. package/templates/new-worker-scheduled.ts +32 -0
  110. package/templates/new-worker.js +15 -0
  111. package/templates/new-worker.ts +30 -0
  112. package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
  113. package/templates/tsconfig.json +105 -0
  114. package/wrangler-dist/cli.js +76649 -75066
  115. package/src/__tests__/helpers/mock-user.ts +0 -27
  116. package/src/__tests__/logout.test.ts +0 -50
  117. package/src/api/form_data.ts +0 -134
  118. package/src/api/preview.ts +0 -128
  119. package/src/config.ts +0 -641
  120. package/src/dev.tsx +0 -834
  121. package/src/npm-installer.ts +0 -20
  122. package/src/tail.tsx +0 -73
  123. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  124. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  125. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  126. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  127. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  128. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  129. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  130. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  131. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  132. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  133. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  134. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  135. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  136. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  137. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  138. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  139. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  140. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  141. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  142. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  143. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  144. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  145. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  146. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  147. package/vendor/wrangler-mime/LICENSE +0 -21
  148. package/vendor/wrangler-mime/Mime.js +0 -97
  149. package/vendor/wrangler-mime/README.md +0 -187
  150. package/vendor/wrangler-mime/cli.js +0 -46
  151. package/vendor/wrangler-mime/index.js +0 -4
  152. package/vendor/wrangler-mime/lite.js +0 -4
  153. package/vendor/wrangler-mime/package.json +0 -52
  154. package/vendor/wrangler-mime/types/other.js +0 -1
  155. package/vendor/wrangler-mime/types/standard.js +0 -1
  156. package/wrangler-dist/cli.js.map +0 -7
package/src/logger.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { format } from "node:util";
2
+ import { formatMessagesSync } from "esbuild";
3
+ import { getEnvironmentVariableFactory } from "./environment-variables";
4
+
5
+ const LOGGER_LEVELS = {
6
+ error: 0,
7
+ warn: 1,
8
+ log: 2,
9
+ debug: 3,
10
+ } as const;
11
+
12
+ type LoggerLevel = keyof typeof LOGGER_LEVELS;
13
+
14
+ /** A map from LOGGER_LEVEL to the error `kind` needed by `formatMessagesSync()`. */
15
+ const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
16
+ error: "error",
17
+ warn: "warning",
18
+ log: undefined,
19
+ debug: undefined,
20
+ } as const;
21
+
22
+ const getLogLevelFromEnv = getEnvironmentVariableFactory({
23
+ variableName: "WRANGLER_LOG",
24
+ defaultValue: "log",
25
+ });
26
+
27
+ class Logger {
28
+ constructor() {}
29
+
30
+ loggerLevel: LoggerLevel = (getLogLevelFromEnv() as LoggerLevel) ?? "log";
31
+ columns = process.stdout.columns;
32
+
33
+ debug = (...args: unknown[]) => this.doLog("debug", args);
34
+ log = (...args: unknown[]) => this.doLog("log", args);
35
+ warn = (...args: unknown[]) => this.doLog("warn", args);
36
+ error = (...args: unknown[]) => this.doLog("error", args);
37
+
38
+ private doLog(messageLevel: LoggerLevel, args: unknown[]) {
39
+ if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
40
+ console[messageLevel](this.formatMessage(messageLevel, format(...args)));
41
+ }
42
+ }
43
+
44
+ private formatMessage(level: LoggerLevel, message: string): string {
45
+ const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
46
+ if (kind) {
47
+ // Format the message using the esbuild formatter.
48
+ // The first line of the message is the main `text`,
49
+ // subsequent lines are put into the `notes`.
50
+ const [firstLine, ...otherLines] = message.split("\n");
51
+ const notes =
52
+ otherLines.length > 0
53
+ ? otherLines.map((text) => ({ text }))
54
+ : undefined;
55
+ return formatMessagesSync([{ text: firstLine, notes }], {
56
+ color: true,
57
+ kind,
58
+ terminalWidth: this.columns,
59
+ })[0];
60
+ } else {
61
+ return message;
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * A drop-in replacement for `console` for outputting logging messages.
68
+ *
69
+ * Errors and Warnings will get additional formatting to highlight them to the user.
70
+ * You can also set a `logger.loggerLevel` value to one of "debug", "log", "warn" or "error",
71
+ * to filter out logging messages.
72
+ */
73
+ 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
+ };
@@ -1,21 +1,97 @@
1
1
  import crypto from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
- import type { CfModule } from "./api/worker";
4
+ import globToRegExp from "glob-to-regexp";
5
+ import { logger } from "./logger";
6
+ import type { Config, ConfigModuleRuleType } from "./config";
7
+ import type { CfModule, CfModuleType, CfScriptFormat } from "./worker";
5
8
  import type esbuild from "esbuild";
6
9
 
10
+ const RuleTypeToModuleType: Record<ConfigModuleRuleType, CfModuleType> = {
11
+ ESModule: "esm",
12
+ CommonJS: "commonjs",
13
+ CompiledWasm: "compiled-wasm",
14
+ Data: "buffer",
15
+ Text: "text",
16
+ };
17
+
7
18
  // This is a combination of an esbuild plugin and a mutable array
8
19
  // that we use to collect module references from source code.
9
20
  // There will be modules that _shouldn't_ be inlined directly into
10
21
  // the bundle. (eg. wasm modules, some text files, etc). We can include
11
- // those files as modules in the multi part forker form upload. This
22
+ // those files as modules in the multi part worker form upload. This
12
23
  // plugin+array is used to collect references to these modules, reference
13
24
  // them correctly in the bundle, and add them to the form upload.
14
25
 
15
- export default function makeModuleCollector(): {
26
+ export const DEFAULT_MODULE_RULES: Config["rules"] = [
27
+ { type: "Text", globs: ["**/*.txt", "**/*.html"] },
28
+ { type: "Data", globs: ["**/*.bin"] },
29
+ { type: "CompiledWasm", globs: ["**/*.wasm"] },
30
+ ];
31
+
32
+ export default function createModuleCollector(props: {
33
+ format: CfScriptFormat;
34
+ rules?: Config["rules"];
35
+ // a collection of "legacy" style module references, which are just file names
36
+ // we will eventually deprecate this functionality, hence the verbose greppable name
37
+ wrangler1xlegacyModuleReferences: {
38
+ rootDirectory: string;
39
+ fileNames: Set<string>;
40
+ };
41
+ }): {
16
42
  modules: CfModule[];
17
43
  plugin: esbuild.Plugin;
18
44
  } {
45
+ const rules: Config["rules"] = [
46
+ ...(props.rules || []),
47
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
48
+ ...DEFAULT_MODULE_RULES!,
49
+ ];
50
+
51
+ // First, we want to add some validations to the module rules
52
+ // We want to warn if rules are accidentally configured in such a way that
53
+ // subsequent rules will never match because `fallthrough` hasn't been set
54
+
55
+ const completedRuleLocations: Record<string, number> = {};
56
+ let index = 0;
57
+ const rulesToRemove: Config["rules"] = [];
58
+ for (const rule of rules) {
59
+ if (rule.type in completedRuleLocations) {
60
+ if (rules[completedRuleLocations[rule.type]].fallthrough !== false) {
61
+ if (index < (props.rules || []).length) {
62
+ logger.warn(
63
+ `The module rule at position ${index} (${JSON.stringify(
64
+ rule
65
+ )}) has the same type as a previous rule (at position ${
66
+ completedRuleLocations[rule.type]
67
+ }, ${JSON.stringify(
68
+ rules[completedRuleLocations[rule.type]]
69
+ )}). This rule will be ignored. To the previous rule, add \`fallthrough = true\` to allow this one to also be used, or \`fallthrough = false\` to silence this warning.`
70
+ );
71
+ } else {
72
+ logger.warn(
73
+ `The default module rule ${JSON.stringify(
74
+ rule
75
+ )} has the same type as a previous rule (at position ${
76
+ completedRuleLocations[rule.type]
77
+ }, ${JSON.stringify(
78
+ rules[completedRuleLocations[rule.type]]
79
+ )}). This rule will be ignored. To the previous rule, add \`fallthrough = true\` to allow the default one to also be used, or \`fallthrough = false\` to silence this warning.`
80
+ );
81
+ }
82
+ }
83
+
84
+ rulesToRemove.push(rule);
85
+ }
86
+ if (!(rule.type in completedRuleLocations) && rule.fallthrough !== true) {
87
+ completedRuleLocations[rule.type] = index;
88
+ }
89
+ index++;
90
+ }
91
+
92
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
93
+ rulesToRemove.forEach((rule) => rules!.splice(rules!.indexOf(rule), 1));
94
+
19
95
  const modules: CfModule[] = [];
20
96
  return {
21
97
  modules,
@@ -23,40 +99,159 @@ export default function makeModuleCollector(): {
23
99
  name: "wrangler-module-collector",
24
100
  setup(build) {
25
101
  build.onStart(() => {
26
- // reset the moduels collection
102
+ // reset the module collection array
27
103
  modules.splice(0);
28
104
  });
29
105
 
30
- build.onResolve(
31
- // filter on "known" file types,
32
- // we can expand this list later
33
- { filter: /.*\.(wasm)$/ },
34
- async (args: esbuild.OnResolveArgs) => {
35
- // take the file and massage it to a
36
- // transportable/manageable format
37
- const filePath = path.join(args.resolveDir, args.path);
38
- const fileContent = await readFile(filePath);
39
- const fileHash = crypto
40
- .createHash("sha1")
41
- .update(fileContent)
42
- .digest("hex");
43
- const fileName = `${fileHash}-${path.basename(args.path)}`;
44
-
45
- // add the module to the array
46
- modules.push({
47
- name: fileName,
48
- content: fileContent,
49
- type: "compiled-wasm",
50
- });
106
+ // ~ start legacy module specifier support ~
107
+
108
+ // This section detects usage of "legacy" 1.x style module specifiers
109
+ // and modifies them so they "work" in wrangler v2, but with a warning
51
110
 
111
+ const rulesMatchers = rules.flatMap((rule) => {
112
+ return rule.globs.map((glob) => {
113
+ const regex = globToRegExp(glob);
52
114
  return {
53
- path: fileName, // change the reference to the changed module
54
- external: true, // mark it as external in the bundle
55
- namespace: "wrangler-module-collector-ns", // just a tag, this isn't strictly necessary
56
- watchFiles: [filePath], // we also add the file to esbuild's watch list
115
+ regex,
116
+ rule,
57
117
  };
58
- }
59
- );
118
+ });
119
+ });
120
+
121
+ if (props.wrangler1xlegacyModuleReferences.fileNames.size > 0) {
122
+ build.onResolve(
123
+ {
124
+ filter: new RegExp(
125
+ "^(" +
126
+ [...props.wrangler1xlegacyModuleReferences.fileNames].join(
127
+ "|"
128
+ ) +
129
+ ")$"
130
+ ),
131
+ },
132
+ async (args: esbuild.OnResolveArgs) => {
133
+ if (
134
+ args.kind !== "import-statement" &&
135
+ args.kind !== "require-call"
136
+ ) {
137
+ return;
138
+ }
139
+ // In the future, this will simply throw an error
140
+ logger.warn(
141
+ `Deprecation: detected a legacy module import in "./${path.relative(
142
+ process.cwd(),
143
+ args.importer
144
+ )}". This will stop working in the future. Replace references to "${
145
+ args.path
146
+ }" with "./${args.path}";`
147
+ );
148
+
149
+ // take the file and massage it to a
150
+ // transportable/manageable format
151
+ const filePath = path.join(
152
+ props.wrangler1xlegacyModuleReferences.rootDirectory,
153
+ args.path
154
+ );
155
+ const fileContent = await readFile(filePath);
156
+ const fileHash = crypto
157
+ .createHash("sha1")
158
+ .update(fileContent)
159
+ .digest("hex");
160
+ const fileName = `./${fileHash}-${path.basename(args.path)}`;
161
+
162
+ const { rule } =
163
+ rulesMatchers.find(({ regex }) => regex.test(fileName)) || {};
164
+ if (rule) {
165
+ // add the module to the array
166
+ modules.push({
167
+ name: fileName,
168
+ content: fileContent,
169
+ type: RuleTypeToModuleType[rule.type],
170
+ });
171
+ return {
172
+ path: fileName, // change the reference to the changed module
173
+ external: props.format === "modules", // mark it as external in the bundle
174
+ namespace: `wrangler-module-${rule.type}`, // just a tag, this isn't strictly necessary
175
+ watchFiles: [filePath], // we also add the file to esbuild's watch list
176
+ };
177
+ }
178
+ }
179
+ );
180
+ }
181
+
182
+ // ~ end legacy module specifier support ~
183
+
184
+ rules?.forEach((rule) => {
185
+ if (rule.type === "ESModule" || rule.type === "CommonJS") return; // TODO: we should treat these as js files, and use the jsx loader
186
+
187
+ rule.globs.forEach((glob) => {
188
+ build.onResolve(
189
+ { filter: globToRegExp(glob) },
190
+ async (args: esbuild.OnResolveArgs) => {
191
+ // take the file and massage it to a
192
+ // transportable/manageable format
193
+
194
+ const filePath = path.join(args.resolveDir, args.path);
195
+ const fileContent = await readFile(filePath);
196
+ const fileHash = crypto
197
+ .createHash("sha1")
198
+ .update(fileContent)
199
+ .digest("hex");
200
+ const fileName = `./${fileHash}-${path.basename(args.path)}`;
201
+
202
+ // add the module to the array
203
+ modules.push({
204
+ name: fileName,
205
+ content: fileContent,
206
+ type: RuleTypeToModuleType[rule.type],
207
+ });
208
+
209
+ return {
210
+ path: fileName, // change the reference to the changed module
211
+ external: props.format === "modules", // mark it as external in the bundle
212
+ namespace: `wrangler-module-${rule.type}`, // just a tag, this isn't strictly necessary
213
+ watchFiles: [filePath], // we also add the file to esbuild's watch list
214
+ };
215
+ }
216
+ );
217
+
218
+ if (props.format === "service-worker") {
219
+ build.onLoad(
220
+ { filter: globToRegExp(glob) },
221
+ async (args: esbuild.OnLoadArgs) => {
222
+ return {
223
+ // We replace the the module with an identifier
224
+ // that we'll separately add to the form upload
225
+ // as part of [wasm_modules]/[text_blobs]/[data_blobs]. This identifier has to be a valid
226
+ // JS identifier, so we replace all non alphanumeric characters
227
+ // with an underscore.
228
+ contents: `export default ${args.path.replace(
229
+ /[^a-zA-Z0-9_$]/g,
230
+ "_"
231
+ )};`,
232
+ };
233
+ }
234
+ );
235
+ }
236
+ });
237
+ });
238
+
239
+ rulesToRemove.forEach((rule) => {
240
+ rule.globs.forEach((glob) => {
241
+ build.onResolve(
242
+ { filter: globToRegExp(glob) },
243
+ async (args: esbuild.OnResolveArgs) => {
244
+ throw new Error(
245
+ `The file ${
246
+ args.path
247
+ } matched a module rule in your configuration (${JSON.stringify(
248
+ rule
249
+ )}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
250
+ );
251
+ }
252
+ );
253
+ });
254
+ });
60
255
  },
61
256
  },
62
257
  };
@@ -0,0 +1,17 @@
1
+ import open from "open";
2
+ import { logger } from "./logger";
3
+
4
+ /**
5
+ * An extremely simple wrapper around the open command.
6
+ * Specifically, it adds an 'error' event handler so that when this function
7
+ * is called in environments where we can't open the browser (e.g. GitHub Codespaces,
8
+ * StackBlitz, remote servers), it doesn't just crash the process.
9
+ *
10
+ * @param url the URL to point the browser at
11
+ */
12
+ export default async function openInBrowser(url: string): Promise<void> {
13
+ const childProcess = await open(url);
14
+ childProcess.on("error", () => {
15
+ logger.warn("Failed to open");
16
+ });
17
+ }
@@ -0,0 +1,174 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { execa, execaCommandSync } from "execa";
4
+ import { logger } from "./logger";
5
+
6
+ export interface PackageManager {
7
+ cwd: string;
8
+ type: "npm" | "yarn" | "pnpm";
9
+ addDevDeps(...packages: string[]): Promise<void>;
10
+ install(): Promise<void>;
11
+ }
12
+
13
+ export async function getPackageManager(cwd: string): Promise<PackageManager> {
14
+ const [hasYarn, hasNpm, hasPnpm] = await Promise.all([
15
+ supportsYarn(),
16
+ supportsNpm(),
17
+ supportsPnpm(),
18
+ ]);
19
+ const hasYarnLock = existsSync(join(cwd, "yarn.lock"));
20
+ const hasNpmLock = existsSync(join(cwd, "package-lock.json"));
21
+ const hasPnpmLock = existsSync(join(cwd, "pnpm-lock.yaml"));
22
+
23
+ if (hasNpmLock) {
24
+ if (hasNpm) {
25
+ logger.log(
26
+ "Using npm as package manager, as there is already a package-lock.json file."
27
+ );
28
+ return { ...NpmPackageManager, cwd };
29
+ } else if (hasYarn) {
30
+ logger.log("Using yarn as package manager.");
31
+ logger.warn(
32
+ "There is already a package-lock.json file but could not find npm on the PATH."
33
+ );
34
+ return { ...YarnPackageManager, cwd };
35
+ }
36
+ } else if (hasPnpmLock) {
37
+ if (hasPnpm) {
38
+ logger.log(
39
+ "Using pnpm as package manager, as there is already a pnpm-lock.yaml file."
40
+ );
41
+ return { ...PnpmPackageManager, cwd };
42
+ } else {
43
+ logger.warn(
44
+ "There is already a pnpm-lock.yaml file but could not find pnpm on the PATH."
45
+ );
46
+ // will simply fallback to the first found of [npm, yaml, pnpm] in the next if round.
47
+ }
48
+ } else if (hasYarnLock) {
49
+ if (hasYarn) {
50
+ logger.log(
51
+ "Using yarn as package manager, as there is already a yarn.lock file."
52
+ );
53
+ return { ...YarnPackageManager, cwd };
54
+ } else if (hasNpm) {
55
+ logger.log("Using npm as package manager.");
56
+ logger.warn(
57
+ "There is already a yarn.lock file but could not find yarn on the PATH."
58
+ );
59
+ return { ...NpmPackageManager, cwd };
60
+ }
61
+ }
62
+
63
+ if (hasNpm) {
64
+ logger.log("Using npm as package manager.");
65
+ return { ...NpmPackageManager, cwd };
66
+ } else if (hasYarn) {
67
+ logger.log("Using yarn as package manager.");
68
+ return { ...YarnPackageManager, cwd };
69
+ } else if (hasPnpm) {
70
+ logger.log("Using pnpm as package manager.");
71
+ return { ...PnpmPackageManager, cwd };
72
+ } else {
73
+ throw new Error(
74
+ "Unable to find a package manager. Supported managers are: npm, yarn, and pnpm."
75
+ );
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Get the name of the given `packageManager`.
81
+ */
82
+ export function getPackageManagerName(packageManager: PackageManager): string {
83
+ return packageManager.type ?? "unknown";
84
+ }
85
+
86
+ /**
87
+ * Manage packages using npm
88
+ */
89
+ const NpmPackageManager: PackageManager = {
90
+ cwd: process.cwd(),
91
+ type: "npm",
92
+ /** Add and install a new devDependency into the local package.json. */
93
+ async addDevDeps(...packages: string[]): Promise<void> {
94
+ await execa("npm", ["install", ...packages, "--save-dev"], {
95
+ stdio: "inherit",
96
+ cwd: this.cwd,
97
+ });
98
+ },
99
+
100
+ /** Install all the dependencies in the local package.json. */
101
+ async install(): Promise<void> {
102
+ await execa("npm", ["install"], {
103
+ stdio: "inherit",
104
+ cwd: this.cwd,
105
+ });
106
+ },
107
+ };
108
+
109
+ /**
110
+ * Manage packages using pnpm
111
+ */
112
+ const PnpmPackageManager: PackageManager = {
113
+ cwd: process.cwd(),
114
+ type: "pnpm",
115
+ /** Add and install a new devDependency into the local package.json. */
116
+ async addDevDeps(...packages: string[]): Promise<void> {
117
+ await execa("pnpm", ["install", ...packages, "--save-dev"], {
118
+ stdio: "inherit",
119
+ cwd: this.cwd,
120
+ });
121
+ },
122
+
123
+ /** Install all the dependencies in the local package.json. */
124
+ async install(): Promise<void> {
125
+ await execa("pnpm", ["install"], {
126
+ stdio: "inherit",
127
+ cwd: this.cwd,
128
+ });
129
+ },
130
+ };
131
+
132
+ /**
133
+ * Manage packages using yarn
134
+ */
135
+ const YarnPackageManager: PackageManager = {
136
+ cwd: process.cwd(),
137
+ type: "yarn",
138
+ /** Add and install a new devDependency into the local package.json. */
139
+ async addDevDeps(...packages: string[]): Promise<void> {
140
+ await execa("yarn", ["add", ...packages, "--dev"], {
141
+ stdio: "inherit",
142
+ cwd: this.cwd,
143
+ });
144
+ },
145
+
146
+ /** Install all the dependencies in the local package.json. */
147
+ async install(): Promise<void> {
148
+ await execa("yarn", ["install"], {
149
+ stdio: "inherit",
150
+ cwd: this.cwd,
151
+ });
152
+ },
153
+ };
154
+
155
+ async function supports(name: string): Promise<boolean> {
156
+ try {
157
+ execaCommandSync(`${name} --version`, { stdio: "ignore" });
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ function supportsYarn(): Promise<boolean> {
165
+ return supports("yarn");
166
+ }
167
+
168
+ function supportsNpm(): Promise<boolean> {
169
+ return supports("npm");
170
+ }
171
+
172
+ function supportsPnpm(): Promise<boolean> {
173
+ return supports("pnpm");
174
+ }