wrangler 0.0.0-e452a35 → 0.0.0-e4716cc87

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 (188) hide show
  1. package/README.md +42 -36
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +3305 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +126 -96
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +2 -3
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  27. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  28. package/templates/modules-watch-stub.js +4 -0
  29. package/templates/new-worker-scheduled.js +17 -0
  30. package/templates/new-worker-scheduled.ts +32 -0
  31. package/templates/new-worker.js +3 -3
  32. package/templates/new-worker.ts +19 -16
  33. package/templates/no-op-worker.js +10 -0
  34. package/templates/pages-dev-pipeline.ts +32 -0
  35. package/templates/pages-dev-util.ts +55 -0
  36. package/templates/pages-shim.ts +9 -0
  37. package/templates/pages-template-plugin.ts +190 -0
  38. package/templates/pages-template-worker.ts +198 -0
  39. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  40. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  41. package/templates/tsconfig-sanity.ts +11 -0
  42. package/templates/tsconfig.init.json +22 -0
  43. package/templates/tsconfig.json +6 -103
  44. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  45. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  46. package/wrangler-dist/ProxyWorker.js +241 -0
  47. package/wrangler-dist/ProxyWorker.js.map +6 -0
  48. package/wrangler-dist/cli.d.ts +26714 -0
  49. package/wrangler-dist/cli.js +169011 -114287
  50. package/Cloudflare_CA.pem +0 -18
  51. package/import_meta_url.js +0 -3
  52. package/miniflare-config-stubs/.env.empty +0 -0
  53. package/miniflare-config-stubs/package.empty.json +0 -1
  54. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  55. package/miniflare-dist/index.mjs +0 -4886
  56. package/pages/functions/buildPlugin.ts +0 -105
  57. package/pages/functions/buildWorker.ts +0 -151
  58. package/pages/functions/filepath-routing.test.ts +0 -234
  59. package/pages/functions/filepath-routing.ts +0 -189
  60. package/pages/functions/identifiers.ts +0 -78
  61. package/pages/functions/routes.ts +0 -156
  62. package/pages/functions/template-plugin.ts +0 -147
  63. package/pages/functions/template-worker.ts +0 -143
  64. package/src/__tests__/config-cache.test.ts +0 -36
  65. package/src/__tests__/configuration.test.ts +0 -3332
  66. package/src/__tests__/dev.test.tsx +0 -899
  67. package/src/__tests__/guess-worker-format.test.ts +0 -85
  68. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  69. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  70. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  71. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  72. package/src/__tests__/helpers/mock-bin.ts +0 -36
  73. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  74. package/src/__tests__/helpers/mock-console.ts +0 -87
  75. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  76. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  77. package/src/__tests__/helpers/mock-istty.ts +0 -27
  78. package/src/__tests__/helpers/mock-kv.ts +0 -33
  79. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  80. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  81. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  82. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  83. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  84. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  85. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  86. package/src/__tests__/https-options.test.ts +0 -130
  87. package/src/__tests__/index.test.ts +0 -256
  88. package/src/__tests__/init.test.ts +0 -1557
  89. package/src/__tests__/jest.setup.ts +0 -77
  90. package/src/__tests__/kv.test.ts +0 -1481
  91. package/src/__tests__/logger.test.ts +0 -115
  92. package/src/__tests__/package-manager.test.ts +0 -206
  93. package/src/__tests__/pages.test.ts +0 -657
  94. package/src/__tests__/parse.test.ts +0 -330
  95. package/src/__tests__/publish.test.ts +0 -5468
  96. package/src/__tests__/r2.test.ts +0 -233
  97. package/src/__tests__/route.test.ts +0 -45
  98. package/src/__tests__/secret.test.ts +0 -481
  99. package/src/__tests__/tail.test.ts +0 -690
  100. package/src/__tests__/user.test.ts +0 -131
  101. package/src/__tests__/whoami.test.tsx +0 -105
  102. package/src/abort.d.ts +0 -3
  103. package/src/bundle.ts +0 -200
  104. package/src/cfetch/index.ts +0 -121
  105. package/src/cfetch/internal.ts +0 -139
  106. package/src/cli.ts +0 -13
  107. package/src/config/README.md +0 -107
  108. package/src/config/config.ts +0 -234
  109. package/src/config/diagnostics.ts +0 -80
  110. package/src/config/environment.ts +0 -420
  111. package/src/config/index.ts +0 -225
  112. package/src/config/validation-helpers.ts +0 -575
  113. package/src/config/validation.ts +0 -1530
  114. package/src/config-cache.ts +0 -45
  115. package/src/create-worker-preview.ts +0 -185
  116. package/src/create-worker-upload-form.ts +0 -254
  117. package/src/dev/dev-vars.ts +0 -36
  118. package/src/dev/dev.tsx +0 -422
  119. package/src/dev/local.tsx +0 -318
  120. package/src/dev/remote.tsx +0 -227
  121. package/src/dev/use-esbuild.ts +0 -118
  122. package/src/dialogs.tsx +0 -87
  123. package/src/durable.ts +0 -102
  124. package/src/entry.ts +0 -322
  125. package/src/environment-variables.ts +0 -35
  126. package/src/errors.ts +0 -11
  127. package/src/https-options.ts +0 -123
  128. package/src/index.tsx +0 -2789
  129. package/src/inspect.ts +0 -662
  130. package/src/intl-polyfill.d.ts +0 -139
  131. package/src/kv.ts +0 -408
  132. package/src/logger.ts +0 -66
  133. package/src/miniflare-cli/README.md +0 -30
  134. package/src/miniflare-cli/enum-keys.ts +0 -17
  135. package/src/miniflare-cli/index.ts +0 -41
  136. package/src/miniflare-cli/request-context.ts +0 -40
  137. package/src/module-collection.ts +0 -258
  138. package/src/open-in-browser.ts +0 -19
  139. package/src/package-manager.ts +0 -127
  140. package/src/pages.tsx +0 -2027
  141. package/src/parse.ts +0 -202
  142. package/src/paths.ts +0 -26
  143. package/src/proxy.ts +0 -465
  144. package/src/publish.ts +0 -583
  145. package/src/r2.ts +0 -50
  146. package/src/selfsigned.d.ts +0 -29
  147. package/src/sites.tsx +0 -295
  148. package/src/tail/filters.ts +0 -279
  149. package/src/tail/index.ts +0 -299
  150. package/src/tail/printing.ts +0 -67
  151. package/src/update-check.ts +0 -19
  152. package/src/user.tsx +0 -1203
  153. package/src/whoami.tsx +0 -70
  154. package/src/worker.ts +0 -180
  155. package/templates/static-asset-facade.js +0 -47
  156. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  157. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  158. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  159. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  160. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  161. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  162. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  163. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  168. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  169. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  170. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  171. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  172. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  173. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  174. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  175. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  176. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  177. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  178. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  179. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  180. package/vendor/wrangler-mime/LICENSE +0 -21
  181. package/vendor/wrangler-mime/Mime.js +0 -97
  182. package/vendor/wrangler-mime/README.md +0 -187
  183. package/vendor/wrangler-mime/cli.js +0 -46
  184. package/vendor/wrangler-mime/index.js +0 -4
  185. package/vendor/wrangler-mime/lite.js +0 -4
  186. package/vendor/wrangler-mime/package.json +0 -52
  187. package/vendor/wrangler-mime/types/other.js +0 -1
  188. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -1,40 +0,0 @@
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,258 +0,0 @@
1
- import crypto from "node:crypto";
2
- import { readFile } from "node:fs/promises";
3
- import path from "node:path";
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";
8
- import type esbuild from "esbuild";
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
-
18
- // This is a combination of an esbuild plugin and a mutable array
19
- // that we use to collect module references from source code.
20
- // There will be modules that _shouldn't_ be inlined directly into
21
- // the bundle. (eg. wasm modules, some text files, etc). We can include
22
- // those files as modules in the multi part worker form upload. This
23
- // plugin+array is used to collect references to these modules, reference
24
- // them correctly in the bundle, and add them to the form upload.
25
-
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
- }): {
42
- modules: CfModule[];
43
- plugin: esbuild.Plugin;
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
-
95
- const modules: CfModule[] = [];
96
- return {
97
- modules,
98
- plugin: {
99
- name: "wrangler-module-collector",
100
- setup(build) {
101
- build.onStart(() => {
102
- // reset the module collection array
103
- modules.splice(0);
104
- });
105
-
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
110
-
111
- const rulesMatchers = rules.flatMap((rule) => {
112
- return rule.globs.map((glob) => {
113
- const regex = globToRegExp(glob);
114
- return {
115
- regex,
116
- rule,
117
- };
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
- });
255
- },
256
- },
257
- };
258
- }
@@ -1,19 +0,0 @@
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 errorMessage = `Failed to open ${url} in a browser`;
14
-
15
- const childProcess = await open(url);
16
- childProcess.on("error", () => {
17
- logger.warn(errorMessage);
18
- });
19
- }
@@ -1,127 +0,0 @@
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";
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] = await Promise.all([supportsYarn(), supportsNpm()]);
15
- const hasYarnLock = existsSync(join(cwd, "yarn.lock"));
16
- const hasNpmLock = existsSync(join(cwd, "package-lock.json"));
17
-
18
- if (hasNpmLock) {
19
- if (hasNpm) {
20
- logger.log(
21
- "Using npm as package manager, as there is already a package-lock.json file."
22
- );
23
- return { ...NpmPackageManager, cwd };
24
- } else if (hasYarn) {
25
- logger.log("Using yarn as package manager.");
26
- logger.warn(
27
- "There is already a package-lock.json file but could not find npm on the PATH."
28
- );
29
- return { ...YarnPackageManager, cwd };
30
- }
31
- } else if (hasYarnLock) {
32
- if (hasYarn) {
33
- logger.log(
34
- "Using yarn as package manager, as there is already a yarn.lock file."
35
- );
36
- return { ...YarnPackageManager, cwd };
37
- } else if (hasNpm) {
38
- logger.log("Using npm as package manager.");
39
- logger.warn(
40
- "There is already a yarn.lock file but could not find yarn on the PATH."
41
- );
42
- return { ...NpmPackageManager, cwd };
43
- }
44
- }
45
-
46
- if (hasNpm) {
47
- logger.log("Using npm as package manager.");
48
- return { ...NpmPackageManager, cwd };
49
- } else if (hasYarn) {
50
- logger.log("Using yarn as package manager.");
51
- return { ...YarnPackageManager, cwd };
52
- } else {
53
- throw new Error(
54
- "Unable to find a package manager. Supported managers are: npm and yarn."
55
- );
56
- }
57
- }
58
-
59
- /**
60
- * Get the name of the given `packageManager`.
61
- */
62
- export function getPackageManagerName(packageManager: PackageManager): string {
63
- return packageManager.type ?? "unknown";
64
- }
65
-
66
- /**
67
- * Manage packages using npm
68
- */
69
- const NpmPackageManager: PackageManager = {
70
- cwd: process.cwd(),
71
- type: "npm",
72
- /** Add and install a new devDependency into the local package.json. */
73
- async addDevDeps(...packages: string[]): Promise<void> {
74
- await execa("npm", ["install", ...packages, "--save-dev"], {
75
- stdio: "inherit",
76
- cwd: this.cwd,
77
- });
78
- },
79
-
80
- /** Install all the dependencies in the local package.json. */
81
- async install(): Promise<void> {
82
- await execa("npm", ["install"], {
83
- stdio: "inherit",
84
- cwd: this.cwd,
85
- });
86
- },
87
- };
88
-
89
- /**
90
- * Manage packages using yarn
91
- */
92
- const YarnPackageManager: PackageManager = {
93
- cwd: process.cwd(),
94
- type: "yarn",
95
- /** Add and install a new devDependency into the local package.json. */
96
- async addDevDeps(...packages: string[]): Promise<void> {
97
- await execa("yarn", ["add", ...packages, "--dev"], {
98
- stdio: "inherit",
99
- cwd: this.cwd,
100
- });
101
- },
102
-
103
- /** Install all the dependencies in the local package.json. */
104
- async install(): Promise<void> {
105
- await execa("yarn", ["install"], {
106
- stdio: "inherit",
107
- cwd: this.cwd,
108
- });
109
- },
110
- };
111
-
112
- async function supports(name: string): Promise<boolean> {
113
- try {
114
- execaCommandSync(`${name} --version`, { stdio: "ignore" });
115
- return true;
116
- } catch {
117
- return false;
118
- }
119
- }
120
-
121
- function supportsYarn(): Promise<boolean> {
122
- return supports("yarn");
123
- }
124
-
125
- function supportsNpm(): Promise<boolean> {
126
- return supports("npm");
127
- }