wrangler 0.0.0-ece06ea → 0.0.0-ed4f2ef

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 (109) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +12 -3
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +49 -22
  6. package/pages/functions/buildWorker.ts +62 -0
  7. package/pages/functions/filepath-routing.test.ts +223 -0
  8. package/pages/functions/filepath-routing.ts +181 -0
  9. package/pages/functions/identifiers.ts +78 -0
  10. package/pages/functions/routes.ts +151 -0
  11. package/pages/functions/template-worker.ts +130 -0
  12. package/src/__tests__/configuration.test.ts +2874 -0
  13. package/src/__tests__/dev.test.tsx +588 -0
  14. package/src/__tests__/guess-worker-format.test.ts +83 -0
  15. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  16. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  17. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  18. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  19. package/src/__tests__/helpers/mock-bin.ts +36 -0
  20. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  21. package/src/__tests__/helpers/mock-console.ts +70 -0
  22. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  23. package/src/__tests__/helpers/mock-kv.ts +33 -0
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +178 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  27. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  28. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +127 -0
  31. package/src/__tests__/index.test.ts +953 -119
  32. package/src/__tests__/jest.setup.ts +74 -0
  33. package/src/__tests__/kv.test.ts +1380 -0
  34. package/src/__tests__/package-manager.test.ts +206 -0
  35. package/src/__tests__/pages.test.ts +180 -0
  36. package/src/__tests__/parse.test.ts +322 -0
  37. package/src/__tests__/publish.test.ts +3946 -0
  38. package/src/__tests__/r2.test.ts +198 -0
  39. package/src/__tests__/route.test.ts +45 -0
  40. package/src/__tests__/secret.test.ts +425 -0
  41. package/src/__tests__/sentry.test.ts +146 -0
  42. package/src/__tests__/tail.test.ts +638 -0
  43. package/src/__tests__/user.test.ts +83 -0
  44. package/src/__tests__/whoami.test.tsx +95 -0
  45. package/src/bundle.ts +155 -0
  46. package/src/cfetch/index.ts +104 -0
  47. package/src/cfetch/internal.ts +139 -0
  48. package/src/cli.ts +18 -7
  49. package/src/config/README.md +107 -0
  50. package/src/config/config.ts +229 -0
  51. package/src/config/diagnostics.ts +80 -0
  52. package/src/config/environment.ts +371 -0
  53. package/src/config/index.ts +62 -0
  54. package/src/config/validation-helpers.ts +557 -0
  55. package/src/config/validation.ts +1240 -0
  56. package/src/create-worker-preview.ts +173 -0
  57. package/src/create-worker-upload-form.ts +240 -0
  58. package/src/dev/dev.tsx +413 -0
  59. package/src/dev/local.tsx +287 -0
  60. package/src/dev/remote.tsx +209 -0
  61. package/src/dev/use-esbuild.ts +109 -0
  62. package/src/dialogs.tsx +6 -14
  63. package/src/entry.ts +256 -0
  64. package/src/environment-variables.ts +33 -0
  65. package/src/errors.ts +11 -0
  66. package/src/https-options.ts +122 -0
  67. package/src/index.tsx +1503 -959
  68. package/src/inspect.ts +624 -0
  69. package/src/intl-polyfill.d.ts +139 -0
  70. package/src/kv.ts +319 -0
  71. package/src/miniflare-cli/README.md +30 -0
  72. package/src/miniflare-cli/enum-keys.ts +17 -0
  73. package/src/miniflare-cli/index.ts +38 -0
  74. package/src/module-collection.ts +257 -0
  75. package/src/open-in-browser.ts +25 -0
  76. package/src/package-manager.ts +126 -0
  77. package/src/pages.tsx +1074 -212
  78. package/src/parse.ts +183 -0
  79. package/src/paths.ts +26 -0
  80. package/src/proxy.ts +455 -0
  81. package/src/publish.ts +326 -295
  82. package/src/r2.ts +50 -0
  83. package/src/reporting.ts +131 -0
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +224 -59
  86. package/src/tail/filters.ts +279 -0
  87. package/src/tail/index.ts +299 -0
  88. package/src/tail/printing.ts +62 -0
  89. package/src/user.tsx +340 -203
  90. package/src/whoami.tsx +69 -0
  91. package/src/worker.ts +172 -0
  92. package/templates/new-worker.js +15 -0
  93. package/templates/new-worker.ts +15 -0
  94. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  95. package/templates/tsconfig.json +105 -0
  96. package/wrangler-dist/cli.js +136988 -131174
  97. package/wrangler-dist/cli.js.map +3 -3
  98. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  99. package/src/__tests__/mock-cfetch.js +0 -46
  100. package/src/api/form_data.ts +0 -158
  101. package/src/api/inspect.ts +0 -441
  102. package/src/api/preview.ts +0 -123
  103. package/src/api/worker.ts +0 -161
  104. package/src/cfetch.ts +0 -72
  105. package/src/config.ts +0 -124
  106. package/src/dev.tsx +0 -736
  107. package/src/kv.tsx +0 -211
  108. package/src/tail.tsx +0 -71
  109. package/src/util/fetch.ts +0 -74
@@ -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
+ }
package/src/kv.ts ADDED
@@ -0,0 +1,319 @@
1
+ import { URLSearchParams } from "node:url";
2
+ import { fetchListResult, fetchResult, fetchKVGetValue } from "./cfetch";
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;
10
+
11
+ type KvArgs = {
12
+ binding?: string;
13
+ "namespace-id"?: string;
14
+ preview?: boolean;
15
+ };
16
+
17
+ /**
18
+ * Create a new namespace under the given `accountId` with the given `title`.
19
+ *
20
+ * @returns the generated id of the created namespace.
21
+ */
22
+ export async function createNamespace(
23
+ accountId: string,
24
+ title: string
25
+ ): Promise<string> {
26
+ const response = await fetchResult<{ id: string }>(
27
+ `/accounts/${accountId}/storage/kv/namespaces`,
28
+ {
29
+ method: "POST",
30
+ headers: {
31
+ "Content-Type": "application/json",
32
+ },
33
+ body: JSON.stringify({
34
+ title,
35
+ }),
36
+ }
37
+ );
38
+
39
+ return response.id;
40
+ }
41
+
42
+ /**
43
+ * The information about a namespace that is returned from `listNamespaces()`.
44
+ */
45
+ export interface KVNamespaceInfo {
46
+ id: string;
47
+ title: string;
48
+ supports_url_encoding?: boolean;
49
+ }
50
+
51
+ /**
52
+ * Fetch a list of all the namespaces under the given `accountId`.
53
+ */
54
+ export async function listNamespaces(
55
+ accountId: string
56
+ ): Promise<KVNamespaceInfo[]> {
57
+ const pageSize = 100;
58
+ let page = 1;
59
+ const results: KVNamespaceInfo[] = [];
60
+ while (results.length % pageSize === 0) {
61
+ const json = await fetchResult<KVNamespaceInfo[]>(
62
+ `/accounts/${accountId}/storage/kv/namespaces`,
63
+ {},
64
+ new URLSearchParams({
65
+ per_page: pageSize.toString(),
66
+ order: "title",
67
+ direction: "asc",
68
+ page: page.toString(),
69
+ })
70
+ );
71
+ page++;
72
+ results.push(...json);
73
+ if (json.length < pageSize) {
74
+ break;
75
+ }
76
+ }
77
+ return results;
78
+ }
79
+
80
+ export interface NamespaceKeyInfo {
81
+ name: string;
82
+ expiration?: number;
83
+ metadata?: { [key: string]: unknown };
84
+ }
85
+
86
+ export async function listNamespaceKeys(
87
+ accountId: string,
88
+ namespaceId: string,
89
+ prefix = ""
90
+ ) {
91
+ return await fetchListResult<NamespaceKeyInfo>(
92
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
93
+ {},
94
+ new URLSearchParams({ prefix })
95
+ );
96
+ }
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
+
138
+ export async function putKeyValue(
139
+ accountId: string,
140
+ namespaceId: string,
141
+ keyValue: KeyValue
142
+ ) {
143
+ let searchParams: URLSearchParams | undefined;
144
+ if (keyValue.expiration || keyValue.expiration_ttl) {
145
+ searchParams = new URLSearchParams();
146
+ if (keyValue.expiration) {
147
+ searchParams.set("expiration", `${keyValue.expiration}`);
148
+ }
149
+ if (keyValue.expiration_ttl) {
150
+ searchParams.set("expiration_ttl", `${keyValue.expiration_ttl}`);
151
+ }
152
+ }
153
+ return await fetchResult(
154
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${keyValue.key}`,
155
+ { method: "PUT", body: keyValue.value },
156
+ searchParams
157
+ );
158
+ }
159
+
160
+ export async function getKeyValue(
161
+ accountId: string,
162
+ namespaceId: string,
163
+ key: string
164
+ ): Promise<string> {
165
+ return await fetchKVGetValue(accountId, namespaceId, key);
166
+ }
167
+
168
+ export async function putBulkKeyValue(
169
+ accountId: string,
170
+ namespaceId: string,
171
+ keyValues: KeyValue[],
172
+ progressCallback: (index: number, total: number) => void
173
+ ) {
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);
177
+ }
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
+ }
191
+ }
192
+
193
+ export async function deleteBulkKeyValue(
194
+ accountId: string,
195
+ namespaceId: string,
196
+ keys: string[],
197
+ progressCallback: (index: number, total: number) => void
198
+ ) {
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);
202
+ }
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
+ }
216
+ }
217
+
218
+ export function getNamespaceId(
219
+ { preview, binding, "namespace-id": namespaceId }: KvArgs,
220
+ config: Config
221
+ ): string {
222
+ // nice
223
+ if (namespaceId) {
224
+ return namespaceId;
225
+ }
226
+
227
+ // begin pre-flight checks
228
+
229
+ // `--binding` is only valid if there's a wrangler configuration.
230
+ if (binding && !config) {
231
+ throw new Error("--binding specified, but no config file was found.");
232
+ }
233
+
234
+ // there's no config. abort here
235
+ if (!config) {
236
+ throw new Error(
237
+ "Failed to find a config file.\n" +
238
+ "Either use --namespace-id to upload directly or create a configuration file with a binding."
239
+ );
240
+ }
241
+
242
+ // there's no KV namespaces
243
+ if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
244
+ throw new Error(
245
+ "No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
246
+ );
247
+ }
248
+
249
+ const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
250
+
251
+ // we couldn't find a namespace with that binding
252
+ if (!namespace) {
253
+ throw new Error(
254
+ `A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
255
+ );
256
+ }
257
+
258
+ // end pre-flight checks
259
+
260
+ // we're in preview mode, `--preview true` or `--preview` was passed
261
+ if (preview && namespace.preview_id) {
262
+ namespaceId = namespace.preview_id;
263
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we will get errors!
264
+ return namespaceId;
265
+ } else if (preview) {
266
+ throw new Error(
267
+ `No preview ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
268
+ );
269
+ }
270
+
271
+ // either `--preview false`, or preview wasn't passed
272
+ // TODO: should we care? or should we just treat false and undefined the same
273
+ const previewIsDefined = typeof preview !== "undefined";
274
+
275
+ // --preview false was passed
276
+ if (previewIsDefined && namespace.id) {
277
+ namespaceId = namespace.id;
278
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we can get error!
279
+ return namespaceId;
280
+ } else if (previewIsDefined) {
281
+ throw new Error(
282
+ `No namespace ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
283
+ );
284
+ }
285
+
286
+ // `--preview` wasn't passed
287
+ const bindingHasOnlyOneId =
288
+ (namespace.id && !namespace.preview_id) ||
289
+ (!namespace.id && namespace.preview_id);
290
+ if (bindingHasOnlyOneId) {
291
+ namespaceId = namespace.id || namespace.preview_id;
292
+ } else {
293
+ throw new Error(
294
+ `${binding} has both a namespace ID and a preview ID. Specify "--preview" or "--preview false" to avoid writing data to the wrong namespace.`
295
+ );
296
+ }
297
+
298
+ // shouldn't happen. we should be able to prove this with strong typing.
299
+ // TODO: when we add strongly typed commands, rewrite these checks so they're exhaustive
300
+ if (!namespaceId) {
301
+ throw Error(
302
+ "Something went wrong trying to determine which namespace to upload to.\n" +
303
+ "Please create a github issue with the command you just ran along with your wrangler configuration."
304
+ );
305
+ }
306
+
307
+ return namespaceId;
308
+ }
309
+
310
+ /**
311
+ * KV namespace binding names must be valid JS identifiers.
312
+ */
313
+ export function isValidNamespaceBinding(
314
+ binding: string | undefined
315
+ ): binding is string {
316
+ return (
317
+ typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding)
318
+ );
319
+ }
@@ -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,38 @@
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
+ await mf.startScheduler();
30
+ } catch (e) {
31
+ mf.log.error(e as Error);
32
+ process.exitCode = 1;
33
+ // Unmount any mounted workers
34
+ await mf.dispose();
35
+ }
36
+ }
37
+
38
+ await main();