@cloudflare/config 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,10 @@
1
- import { a as bindings, i as triggers, n as resolveWorkerDefinition, r as exports$1, t as defineWorker } from "./public-mmLmXmLK.mjs";
1
+ import { a as triggers, i as exports$1, n as defineWorker, o as bindings, r as resolveExportDefinition, t as defineSettings } from "./public-D2QZv1n6.mjs";
2
2
  import * as nodeModule from "node:module";
3
- import * as fsp from "node:fs/promises";
4
- import * as path from "node:path";
3
+ import * as z from "zod";
4
+ import { existsSync, readFileSync, statSync } from "node:fs";
5
5
  import path2__default, { dirname, isAbsolute, join, resolve } from "node:path";
6
- import fs2, { existsSync, readFileSync, statSync } from "node:fs";
7
6
  import { fileURLToPath, pathToFileURL } from "node:url";
8
7
  import { AsyncLocalStorage } from "node:async_hooks";
9
- import * as z from "zod";
10
8
 
11
9
  //#region rolldown:runtime
12
10
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -15,156 +13,652 @@ var __commonJS = (cb, mod) => function() {
15
13
  };
16
14
 
17
15
  //#endregion
18
- //#region ../workers-utils/dist/chunk-Q72B4Q5Z.mjs
19
- var __defProp = Object.defineProperty;
20
- var __name = (target, value) => __defProp(target, "name", {
21
- value,
22
- configurable: true
16
+ //#region src/schema.ts
17
+ const AssetsSchema = z.strictObject({
18
+ htmlHandling: z.enum([
19
+ "auto-trailing-slash",
20
+ "drop-trailing-slash",
21
+ "force-trailing-slash",
22
+ "none"
23
+ ]).optional(),
24
+ notFoundHandling: z.enum([
25
+ "single-page-application",
26
+ "404-page",
27
+ "none"
28
+ ]).optional(),
29
+ runWorkerFirst: z.union([z.array(z.string()), z.boolean()]).optional()
23
30
  });
24
-
25
- //#endregion
26
- //#region ../workers-utils/dist/chunk-53IMCORZ.mjs
27
- function isDirectory(path$1) {
28
- return fs2.statSync(path$1, { throwIfNoEntry: false })?.isDirectory() ?? false;
29
- }
30
- __name(isDirectory, "isDirectory");
31
- function removeDir(dirPath, { fireAndForget = false } = {}) {
32
- const result = fs2.promises.rm(dirPath, {
33
- recursive: true,
34
- force: true,
35
- maxRetries: 5,
36
- retryDelay: 100
37
- });
38
- if (fireAndForget) result.catch(() => {});
39
- else return result;
40
- }
41
- __name(removeDir, "removeDir");
42
- function removeDirSync(dirPath) {
43
- fs2.rmSync(dirPath, {
44
- recursive: true,
45
- force: true,
46
- maxRetries: 5,
47
- retryDelay: 100
48
- });
49
- }
50
- __name(removeDirSync, "removeDirSync");
51
-
52
- //#endregion
53
- //#region ../workers-utils/dist/chunk-Y3JVLYM6.mjs
54
- function partitionExports(exports$2) {
55
- const partitioned = {
56
- "durable-object": {},
57
- worker: {}
58
- };
59
- if (exports$2 === void 0) return partitioned;
60
- for (const [name, entry] of Object.entries(exports$2)) partitioned[entry.type][name] = entry;
61
- return partitioned;
62
- }
63
- __name(partitionExports, "partitionExports");
64
- var UserError = class extends Error {
65
- static {
66
- __name(this, "UserError");
67
- }
68
- telemetryMessage;
69
- constructor(message, options) {
70
- super(message, options);
71
- Object.setPrototypeOf(this, new.target.prototype);
72
- this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
73
- }
74
- };
75
- var DeprecationError = class extends UserError {
76
- static {
77
- __name(this, "DeprecationError");
78
- }
79
- constructor(message, options) {
80
- super(`Deprecation:
81
- ${message}`, options);
82
- }
83
- };
84
- var FatalError = class extends UserError {
85
- static {
86
- __name(this, "FatalError");
87
- }
88
- code;
89
- constructor(message, options) {
90
- super(message, options);
91
- this.code = options.code;
31
+ const KnownBindingSchema = z.discriminatedUnion("type", [
32
+ z.strictObject({
33
+ type: z.literal("agent-memory"),
34
+ namespace: z.string(),
35
+ remote: z.boolean().optional()
36
+ }),
37
+ z.strictObject({
38
+ type: z.literal("ai"),
39
+ remote: z.boolean().optional()
40
+ }),
41
+ z.strictObject({
42
+ type: z.literal("ai-search"),
43
+ name: z.string(),
44
+ remote: z.boolean().optional()
45
+ }),
46
+ z.strictObject({
47
+ type: z.literal("ai-search-namespace"),
48
+ namespace: z.string(),
49
+ remote: z.boolean().optional()
50
+ }),
51
+ z.strictObject({
52
+ type: z.literal("analytics-engine-dataset"),
53
+ name: z.string().optional()
54
+ }),
55
+ z.strictObject({
56
+ type: z.literal("artifacts"),
57
+ namespace: z.string(),
58
+ remote: z.boolean().optional()
59
+ }),
60
+ z.strictObject({ type: z.literal("assets") }),
61
+ z.strictObject({
62
+ type: z.literal("browser"),
63
+ remote: z.boolean().optional()
64
+ }),
65
+ z.strictObject({
66
+ type: z.literal("d1"),
67
+ name: z.string().optional(),
68
+ id: z.string().optional(),
69
+ remote: z.boolean().optional()
70
+ }),
71
+ z.strictObject({
72
+ type: z.literal("dispatch-namespace"),
73
+ namespace: z.string().optional(),
74
+ outbound: z.strictObject({
75
+ workerName: z.string(),
76
+ parameters: z.array(z.string()).optional()
77
+ }).optional(),
78
+ remote: z.boolean().optional()
79
+ }),
80
+ z.strictObject({
81
+ type: z.literal("durable-object"),
82
+ workerName: z.string(),
83
+ exportName: z.string()
84
+ }),
85
+ z.strictObject({
86
+ type: z.literal("flagship"),
87
+ id: z.string().optional(),
88
+ remote: z.boolean().optional()
89
+ }),
90
+ z.strictObject({
91
+ type: z.literal("hyperdrive"),
92
+ id: z.string(),
93
+ localConnectionString: z.string().optional()
94
+ }),
95
+ z.strictObject({
96
+ type: z.literal("images"),
97
+ remote: z.boolean().optional()
98
+ }),
99
+ z.strictObject({
100
+ type: z.literal("json"),
101
+ value: z.json()
102
+ }),
103
+ z.strictObject({
104
+ type: z.literal("kv"),
105
+ id: z.string().optional(),
106
+ remote: z.boolean().optional()
107
+ }),
108
+ z.strictObject({
109
+ type: z.literal("logfwdr"),
110
+ destination: z.string()
111
+ }),
112
+ z.strictObject({
113
+ type: z.literal("media"),
114
+ remote: z.boolean().optional()
115
+ }),
116
+ z.strictObject({
117
+ type: z.literal("mtls-certificate"),
118
+ id: z.string(),
119
+ remote: z.boolean().optional()
120
+ }),
121
+ z.strictObject({
122
+ type: z.literal("pipeline"),
123
+ name: z.string(),
124
+ remote: z.boolean().optional()
125
+ }),
126
+ z.strictObject({
127
+ type: z.literal("queue"),
128
+ name: z.string().optional(),
129
+ deliveryDelay: z.number().optional(),
130
+ remote: z.boolean().optional()
131
+ }),
132
+ z.strictObject({
133
+ type: z.literal("rate-limit"),
134
+ namespace: z.string(),
135
+ simple: z.strictObject({
136
+ limit: z.number(),
137
+ period: z.union([z.literal(10), z.literal(60)])
138
+ })
139
+ }),
140
+ z.strictObject({
141
+ type: z.literal("r2"),
142
+ name: z.string().optional(),
143
+ jurisdiction: z.string().optional(),
144
+ remote: z.boolean().optional()
145
+ }),
146
+ z.strictObject({ type: z.literal("secret") }),
147
+ z.strictObject({
148
+ type: z.literal("secrets-store-secret"),
149
+ storeId: z.string(),
150
+ secretName: z.string()
151
+ }),
152
+ z.strictObject({
153
+ type: z.literal("send-email"),
154
+ destinationAddress: z.string().optional(),
155
+ allowedDestinationAddresses: z.array(z.string()).optional(),
156
+ allowedSenderAddresses: z.array(z.string()).optional(),
157
+ remote: z.boolean().optional()
158
+ }),
159
+ z.strictObject({
160
+ type: z.literal("stream"),
161
+ remote: z.boolean().optional()
162
+ }),
163
+ z.strictObject({
164
+ type: z.literal("text"),
165
+ value: z.string()
166
+ }),
167
+ z.strictObject({
168
+ type: z.literal("vectorize"),
169
+ name: z.string(),
170
+ remote: z.boolean().optional()
171
+ }),
172
+ z.strictObject({ type: z.literal("version-metadata") }),
173
+ z.strictObject({
174
+ type: z.literal("vpc-service"),
175
+ id: z.string(),
176
+ remote: z.boolean().optional()
177
+ }),
178
+ z.strictObject({
179
+ type: z.literal("vpc-network"),
180
+ tunnelId: z.string().optional(),
181
+ networkId: z.string().optional(),
182
+ remote: z.boolean().optional()
183
+ }).superRefine((value, ctx) => {
184
+ const hasTunnel = value.tunnelId !== void 0;
185
+ if (hasTunnel === (value.networkId !== void 0)) ctx.addIssue({
186
+ code: "custom",
187
+ message: hasTunnel ? `"vpc-network" bindings must specify exactly one of "tunnelId" or "networkId", not both` : `"vpc-network" bindings must specify either "tunnelId" or "networkId"`
188
+ });
189
+ }),
190
+ z.strictObject({
191
+ type: z.literal("web-search"),
192
+ remote: z.boolean().optional()
193
+ }),
194
+ z.strictObject({
195
+ type: z.literal("worker"),
196
+ workerName: z.string(),
197
+ exportName: z.string().optional(),
198
+ props: z.record(z.string(), z.unknown()).optional(),
199
+ remote: z.boolean().optional()
200
+ }),
201
+ z.strictObject({ type: z.literal("worker-loader") })
202
+ ]);
203
+ const UnsafeBindingSchema = z.looseObject({
204
+ type: z.templateLiteral(["unsafe:", z.string().min(1)]),
205
+ dev: z.strictObject({
206
+ plugin: z.strictObject({
207
+ package: z.string(),
208
+ name: z.string()
209
+ }),
210
+ options: z.record(z.string(), z.unknown()).optional()
211
+ }).optional()
212
+ });
213
+ const BindingSchema = z.unknown().transform((value, ctx) => {
214
+ const result = (typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && value.type.startsWith("unsafe:") ? UnsafeBindingSchema : KnownBindingSchema).safeParse(value);
215
+ if (!result.success) {
216
+ ctx.issues.push(...result.error.issues);
217
+ return z.NEVER;
92
218
  }
93
- };
94
- var CommandLineArgsError = class extends UserError {
95
- static {
96
- __name(this, "CommandLineArgsError");
97
- }
98
- };
99
- var JsonFriendlyFatalError = class extends FatalError {
100
- static {
101
- __name(this, "JsonFriendlyFatalError");
102
- }
103
- };
104
- var MissingConfigError = class extends Error {
105
- static {
106
- __name(this, "MissingConfigError");
107
- }
108
- telemetryMessage;
109
- constructor(key) {
110
- super(`Missing config value for ${key}`);
111
- this.telemetryMessage = `Missing config value for ${key}`;
112
- }
113
- };
114
- function createFatalError(message, isJson, options) {
115
- if (isJson) return new JsonFriendlyFatalError(JSON.stringify(message), options);
116
- return new FatalError(`${message}`, options);
219
+ return result.data;
220
+ });
221
+ function isParsedUnsafeBinding(binding) {
222
+ return binding.type.startsWith("unsafe:");
117
223
  }
118
- __name(createFatalError, "createFatalError");
119
- function createScanner(text, ignoreTrivia = false) {
120
- const len = text.length;
121
- let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
122
- function scanHexDigits(count, exact) {
123
- let digits = 0;
124
- let value2 = 0;
125
- while (digits < count || !exact) {
126
- let ch = text.charCodeAt(pos);
127
- if (ch >= 48 && ch <= 57) value2 = value2 * 16 + ch - 48;
128
- else if (ch >= 65 && ch <= 70) value2 = value2 * 16 + ch - 65 + 10;
129
- else if (ch >= 97 && ch <= 102) value2 = value2 * 16 + ch - 97 + 10;
130
- else break;
131
- pos++;
132
- digits++;
224
+ const CacheSchema = z.strictObject({
225
+ enabled: z.boolean(),
226
+ crossVersionCache: z.boolean().optional()
227
+ });
228
+ /**
229
+ * Binding types that can only be defined once per worker.
230
+ */
231
+ const SINGLETON_BINDING_TYPES = new Set([
232
+ "ai",
233
+ "assets",
234
+ "browser",
235
+ "images",
236
+ "media",
237
+ "stream",
238
+ "version-metadata",
239
+ "web-search"
240
+ ]);
241
+ const listFormatter = new Intl.ListFormat("en-US");
242
+ const EnvSchema = z.record(z.string(), BindingSchema).superRefine((env, ctx) => {
243
+ const seen = /* @__PURE__ */ new Set();
244
+ const duplicates = /* @__PURE__ */ new Set();
245
+ for (const binding of Object.values(env)) {
246
+ const type = binding.type;
247
+ if (SINGLETON_BINDING_TYPES.has(type)) {
248
+ if (seen.has(type)) duplicates.add(type);
249
+ seen.add(type);
133
250
  }
134
- if (digits < count) value2 = -1;
135
- return value2;
136
251
  }
137
- __name(scanHexDigits, "scanHexDigits");
138
- function setPosition(newPosition) {
139
- pos = newPosition;
140
- value = "";
141
- tokenOffset = 0;
142
- token = 16;
143
- scanError = 0;
252
+ if (duplicates.size > 0) ctx.addIssue({
253
+ code: "custom",
254
+ message: `${listFormatter.format([...duplicates].sort())} bindings can only be defined once`
255
+ });
256
+ }).optional();
257
+ const ExportSchema = z.union([
258
+ z.strictObject({
259
+ type: z.literal("durable-object"),
260
+ state: z.literal("created").optional(),
261
+ storage: z.enum(["sqlite", "legacy-kv"])
262
+ }),
263
+ z.strictObject({
264
+ type: z.literal("durable-object"),
265
+ state: z.literal("deleted")
266
+ }),
267
+ z.strictObject({
268
+ type: z.literal("durable-object"),
269
+ state: z.literal("renamed"),
270
+ renamedTo: z.string()
271
+ }),
272
+ z.strictObject({
273
+ type: z.literal("durable-object"),
274
+ state: z.literal("transferred"),
275
+ transferredTo: z.string()
276
+ }),
277
+ z.strictObject({
278
+ type: z.literal("durable-object"),
279
+ state: z.literal("expecting-transfer"),
280
+ storage: z.enum(["sqlite", "legacy-kv"]),
281
+ transferFrom: z.string()
282
+ }),
283
+ z.strictObject({
284
+ type: z.literal("worker"),
285
+ cache: z.strictObject({ enabled: z.boolean() }).optional()
286
+ })
287
+ ]);
288
+ const LimitsSchema = z.strictObject({
289
+ cpuMs: z.number().optional(),
290
+ subrequests: z.number().optional()
291
+ });
292
+ const ObservabilitySchema = z.strictObject({
293
+ enabled: z.boolean().optional(),
294
+ headSamplingRate: z.number().optional(),
295
+ logs: z.strictObject({
296
+ enabled: z.boolean().optional(),
297
+ headSamplingRate: z.number().optional(),
298
+ invocationLogs: z.boolean().optional(),
299
+ persist: z.boolean().optional(),
300
+ destinations: z.array(z.string()).optional()
301
+ }).optional(),
302
+ traces: z.strictObject({
303
+ enabled: z.boolean().optional(),
304
+ headSamplingRate: z.number().optional(),
305
+ persist: z.boolean().optional(),
306
+ destinations: z.array(z.string()).optional()
307
+ }).optional()
308
+ });
309
+ const PlacementSchema = z.union([
310
+ z.strictObject({
311
+ mode: z.enum(["off", "smart"]),
312
+ hint: z.string().optional()
313
+ }),
314
+ z.strictObject({
315
+ mode: z.literal("targeted").optional(),
316
+ region: z.string()
317
+ }),
318
+ z.strictObject({
319
+ mode: z.literal("targeted").optional(),
320
+ host: z.string()
321
+ }),
322
+ z.strictObject({
323
+ mode: z.literal("targeted").optional(),
324
+ hostname: z.string()
325
+ })
326
+ ]);
327
+ const TailConsumerSchema = z.strictObject({
328
+ workerName: z.string(),
329
+ streaming: z.boolean().optional()
330
+ });
331
+ const TriggerSchema = z.discriminatedUnion("type", [
332
+ z.strictObject({
333
+ type: z.literal("email"),
334
+ addresses: z.array(z.string())
335
+ }),
336
+ z.strictObject({
337
+ type: z.literal("fetch"),
338
+ pattern: z.string(),
339
+ zone: z.string().optional()
340
+ }),
341
+ z.strictObject({
342
+ type: z.literal("queue"),
343
+ name: z.string(),
344
+ deadLetterQueue: z.string().optional(),
345
+ maxBatchSize: z.number().optional(),
346
+ maxBatchTimeout: z.number().optional(),
347
+ maxConcurrency: z.number().nullable().optional(),
348
+ maxRetries: z.number().optional(),
349
+ retryDelay: z.number().optional(),
350
+ visibilityTimeoutMs: z.number().optional()
351
+ }),
352
+ z.strictObject({
353
+ type: z.literal("scheduled"),
354
+ schedule: z.string()
355
+ })
356
+ ]);
357
+ const UnsafeSchema = z.strictObject({
358
+ metadata: z.record(z.string(), z.unknown()).optional(),
359
+ capnp: z.union([z.strictObject({
360
+ basePath: z.string(),
361
+ sourceSchemas: z.array(z.string()),
362
+ compiledSchema: z.never().optional()
363
+ }), z.strictObject({
364
+ basePath: z.never().optional(),
365
+ sourceSchemas: z.never().optional(),
366
+ compiledSchema: z.string()
367
+ })]).optional()
368
+ });
369
+ /**
370
+ * Base Worker schema — the set of fields shared between the input
371
+ * (user-authored) and output (on-disk) Worker configs.
372
+ */
373
+ const BaseWorkerSchema = z.strictObject({
374
+ type: z.literal("worker"),
375
+ name: z.string(),
376
+ compatibilityDate: z.string(),
377
+ compatibilityFlags: z.array(z.string()).optional(),
378
+ assets: AssetsSchema.optional(),
379
+ domains: z.array(z.string()).optional(),
380
+ triggers: z.array(TriggerSchema).optional(),
381
+ tailConsumers: z.array(TailConsumerSchema).optional(),
382
+ cache: CacheSchema.optional(),
383
+ placement: PlacementSchema.optional(),
384
+ limits: LimitsSchema.optional(),
385
+ logpush: z.boolean().optional(),
386
+ observability: ObservabilitySchema.optional(),
387
+ workersDev: z.boolean().optional(),
388
+ previewUrls: z.boolean().optional(),
389
+ firstPartyWorker: z.boolean().optional(),
390
+ unsafe: UnsafeSchema.optional(),
391
+ env: EnvSchema,
392
+ exports: z.record(z.string(), ExportSchema).optional()
393
+ });
394
+ /**
395
+ * Input Worker schema — the shape that user-authored `cloudflare.config.ts`
396
+ * files are validated against. Adds an optional `entrypoint` field to the
397
+ * base schema.
398
+ */
399
+ const InputWorkerSchema = BaseWorkerSchema.extend({ entrypoint: z.union([z.string(), z.strictObject({ default: z.string() })]).transform((value) => typeof value === "string" ? value : value.default).optional() });
400
+ /**
401
+ * Settings schema — validates the named `settings` export of a
402
+ * `cloudflare.config.ts`. Holds account/deployment settings shared by the other exports.
403
+ */
404
+ const SettingsSchema = z.strictObject({
405
+ type: z.literal("settings"),
406
+ accountId: z.string().optional(),
407
+ complianceRegion: z.enum(["public", "fedramp-high"]).optional()
408
+ });
409
+ /**
410
+ * Discriminated union of the config kinds a single export may resolve to.
411
+ */
412
+ const ConfigExportSchema = z.discriminatedUnion("type", [InputWorkerSchema, SettingsSchema]);
413
+ const SETTINGS_EXPORT_NAME = "settings";
414
+ /**
415
+ * Schema for the resolved config exports, keyed by export
416
+ * name. Each value is discriminated on its `type` field. Reserves the
417
+ * `settings` export name exclusively for settings configs: a `settings`
418
+ * config must live on the `settings` export, and the `settings` export
419
+ * may only hold a `settings` config.
420
+ */
421
+ const ConfigExportsSchema = z.record(z.string(), ConfigExportSchema).check((ctx) => {
422
+ for (const [key, value] of Object.entries(ctx.value)) {
423
+ const isSettingsName = key === SETTINGS_EXPORT_NAME;
424
+ const isSettingsType = value.type === "settings";
425
+ if (isSettingsType && !isSettingsName) ctx.issues.push({
426
+ code: "custom",
427
+ input: value,
428
+ path: [key],
429
+ message: `A \`settings\` config is only allowed on the \`${SETTINGS_EXPORT_NAME}\` export; found one on the \`${key}\` export.`
430
+ });
431
+ else if (isSettingsName && !isSettingsType) ctx.issues.push({
432
+ code: "custom",
433
+ input: value,
434
+ path: [key],
435
+ message: `The \`${SETTINGS_EXPORT_NAME}\` export is reserved for a \`settings\` config; found a \`${value.type}\` config.`
436
+ });
144
437
  }
145
- __name(setPosition, "setPosition");
146
- function scanNumber() {
147
- let start = pos;
148
- if (text.charCodeAt(pos) === 48) pos++;
149
- else {
150
- pos++;
151
- while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
152
- }
153
- if (pos < text.length && text.charCodeAt(pos) === 46) {
154
- pos++;
155
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
156
- pos++;
157
- while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
158
- } else {
159
- scanError = 3;
160
- return text.substring(start, pos);
161
- }
162
- }
163
- let end = pos;
164
- if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
165
- pos++;
166
- if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
167
- if (pos < text.length && isDigit(text.charCodeAt(pos))) {
438
+ });
439
+ const ModuleTypeSchema = z.enum([
440
+ "esm",
441
+ "cjs",
442
+ "python",
443
+ "python-requirement",
444
+ "wasm",
445
+ "text",
446
+ "data",
447
+ "json",
448
+ "sourcemap"
449
+ ]);
450
+ const ManifestSchema = z.strictObject({
451
+ mainModule: z.string(),
452
+ modules: z.record(z.string(), z.strictObject({ type: ModuleTypeSchema }))
453
+ });
454
+ /**
455
+ * Output Worker schema — the shape of the Worker's `config.json` in the
456
+ * Build Output Specification. Adds an optional `manifest` field to the
457
+ * base schema.
458
+ */
459
+ const OutputWorkerSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional() });
460
+
461
+ //#endregion
462
+ //#region ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js
463
+ var require_dist = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js": ((exports) => {
464
+ Object.defineProperty(exports, "__esModule", { value: true });
465
+ exports.dedent = void 0;
466
+ function dedent$2(templ) {
467
+ var values = [];
468
+ for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
469
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
470
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
471
+ var indentLengths = strings.reduce(function(arr, str) {
472
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
473
+ if (matches) return arr.concat(matches.map(function(match) {
474
+ var _a, _b;
475
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
476
+ }));
477
+ return arr;
478
+ }, []);
479
+ if (indentLengths.length) {
480
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
481
+ strings = strings.map(function(str) {
482
+ return str.replace(pattern_1, "\n");
483
+ });
484
+ }
485
+ strings[0] = strings[0].replace(/^\r?\n/, "");
486
+ var string = strings[0];
487
+ values.forEach(function(value, i) {
488
+ var endentations = string.match(/(?:^|\n)( *)$/);
489
+ var endentation = endentations ? endentations[1] : "";
490
+ var indentedValue = value;
491
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i$1) {
492
+ return i$1 === 0 ? str : "" + endentation + str;
493
+ }).join("\n");
494
+ string += indentedValue + strings[i + 1];
495
+ });
496
+ return string;
497
+ }
498
+ exports.dedent = dedent$2;
499
+ }) });
500
+
501
+ //#endregion
502
+ //#region src/generate.ts
503
+ var import_dist = require_dist();
504
+ /**
505
+ * Generate the content for worker-configuration.d.ts
506
+ *
507
+ * @example
508
+ * ```typescript
509
+ * import { generateTypes } from "@cloudflare/config";
510
+ * import { writeFileSync } from "node:fs";
511
+ *
512
+ * const content = generateTypes({
513
+ * configPath: "./cloudflare.config.ts",
514
+ * });
515
+ *
516
+ * writeFileSync("worker-configuration.d.ts", content);
517
+ * ```
518
+ */
519
+ function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
520
+ return import_dist.dedent`
521
+ /* eslint-disable */
522
+ // Generated by @cloudflare/config
523
+ type __WorkerConfig = import("${packageName}").UnwrapConfig<typeof import("${configPath.replace(/\.(ts|js|mts|mjs)$/, "")}").default>;
524
+ type __Env = import("${packageName}").InferEnv<__WorkerConfig>;
525
+
526
+ declare namespace Cloudflare {
527
+ interface GlobalProps {
528
+ mainModule: import("${packageName}").InferMainModule<__WorkerConfig>;
529
+ durableNamespaces: import("${packageName}").InferDurableNamespaces<__WorkerConfig>;
530
+ }
531
+ interface Env extends __Env {}
532
+ }
533
+ interface Env extends Cloudflare.Env {}
534
+
535
+ `;
536
+ }
537
+
538
+ //#endregion
539
+ //#region ../workers-utils/dist/chunk-Q72B4Q5Z.mjs
540
+ var __defProp = Object.defineProperty;
541
+ var __name = (target, value) => __defProp(target, "name", {
542
+ value,
543
+ configurable: true
544
+ });
545
+
546
+ //#endregion
547
+ //#region ../workers-utils/dist/chunk-3K53PSCY.mjs
548
+ function partitionExports(exports$2) {
549
+ const partitioned = {
550
+ "durable-object": {},
551
+ worker: {}
552
+ };
553
+ if (exports$2 === void 0) return partitioned;
554
+ for (const [name, entry] of Object.entries(exports$2)) partitioned[entry.type][name] = entry;
555
+ return partitioned;
556
+ }
557
+ __name(partitionExports, "partitionExports");
558
+ var UserError = class extends Error {
559
+ static {
560
+ __name(this, "UserError");
561
+ }
562
+ telemetryMessage;
563
+ constructor(message, options) {
564
+ super(message, options);
565
+ Object.setPrototypeOf(this, new.target.prototype);
566
+ this.telemetryMessage = typeof options?.telemetryMessage === "string" ? options.telemetryMessage : options?.telemetryMessage ? message : void 0;
567
+ }
568
+ };
569
+ var DeprecationError = class extends UserError {
570
+ static {
571
+ __name(this, "DeprecationError");
572
+ }
573
+ constructor(message, options) {
574
+ super(`Deprecation:
575
+ ${message}`, options);
576
+ }
577
+ };
578
+ var FatalError = class extends UserError {
579
+ static {
580
+ __name(this, "FatalError");
581
+ }
582
+ code;
583
+ constructor(message, options) {
584
+ super(message, options);
585
+ this.code = options.code;
586
+ }
587
+ };
588
+ var CommandLineArgsError = class extends UserError {
589
+ static {
590
+ __name(this, "CommandLineArgsError");
591
+ }
592
+ };
593
+ var JsonFriendlyFatalError = class extends FatalError {
594
+ static {
595
+ __name(this, "JsonFriendlyFatalError");
596
+ }
597
+ };
598
+ var MissingConfigError = class extends Error {
599
+ static {
600
+ __name(this, "MissingConfigError");
601
+ }
602
+ telemetryMessage;
603
+ constructor(key) {
604
+ super(`Missing config value for ${key}`);
605
+ this.telemetryMessage = `Missing config value for ${key}`;
606
+ }
607
+ };
608
+ function createFatalError(message, isJson, options) {
609
+ if (isJson) return new JsonFriendlyFatalError(JSON.stringify(message), options);
610
+ return new FatalError(`${message}`, options);
611
+ }
612
+ __name(createFatalError, "createFatalError");
613
+ function createScanner(text, ignoreTrivia = false) {
614
+ const len = text.length;
615
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
616
+ function scanHexDigits(count, exact) {
617
+ let digits = 0;
618
+ let value2 = 0;
619
+ while (digits < count || !exact) {
620
+ let ch = text.charCodeAt(pos);
621
+ if (ch >= 48 && ch <= 57) value2 = value2 * 16 + ch - 48;
622
+ else if (ch >= 65 && ch <= 70) value2 = value2 * 16 + ch - 65 + 10;
623
+ else if (ch >= 97 && ch <= 102) value2 = value2 * 16 + ch - 97 + 10;
624
+ else break;
625
+ pos++;
626
+ digits++;
627
+ }
628
+ if (digits < count) value2 = -1;
629
+ return value2;
630
+ }
631
+ __name(scanHexDigits, "scanHexDigits");
632
+ function setPosition(newPosition) {
633
+ pos = newPosition;
634
+ value = "";
635
+ tokenOffset = 0;
636
+ token = 16;
637
+ scanError = 0;
638
+ }
639
+ __name(setPosition, "setPosition");
640
+ function scanNumber() {
641
+ let start = pos;
642
+ if (text.charCodeAt(pos) === 48) pos++;
643
+ else {
644
+ pos++;
645
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
646
+ }
647
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
648
+ pos++;
649
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
650
+ pos++;
651
+ while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
652
+ } else {
653
+ scanError = 3;
654
+ return text.substring(start, pos);
655
+ }
656
+ }
657
+ let end = pos;
658
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
659
+ pos++;
660
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) pos++;
661
+ if (pos < text.length && isDigit(text.charCodeAt(pos))) {
168
662
  pos++;
169
663
  while (pos < text.length && isDigit(text.charCodeAt(pos))) pos++;
170
664
  end = pos;
@@ -2060,10 +2554,16 @@ var APIError = class extends ParseError {
2060
2554
  * endpoint-specific structured error payloads.
2061
2555
  */
2062
2556
  meta;
2063
- constructor({ status,...rest }) {
2557
+ /**
2558
+ * Optional number of milliseconds the API asked us to wait before retrying,
2559
+ * derived from the response's `Retry-After` header (if present).
2560
+ */
2561
+ retryAfterMs;
2562
+ constructor({ status, retryAfterMs,...rest }) {
2064
2563
  super(rest);
2065
2564
  this.name = this.constructor.name;
2066
2565
  this.#status = status;
2566
+ this.retryAfterMs = retryAfterMs;
2067
2567
  }
2068
2568
  get status() {
2069
2569
  return this.#status;
@@ -2293,774 +2793,218 @@ var UNSUPPORTED_BOMS = [
2293
2793
  {
2294
2794
  buffer: Buffer.from([
2295
2795
  0,
2296
- 0,
2297
- 254,
2298
- 255
2299
- ]),
2300
- encoding: "UTF-32 BE"
2301
- },
2302
- {
2303
- buffer: Buffer.from([
2304
- 255,
2305
- 254,
2306
- 0,
2307
- 0
2308
- ]),
2309
- encoding: "UTF-32 LE"
2310
- },
2311
- {
2312
- buffer: Buffer.from([254, 255]),
2313
- encoding: "UTF-16 BE"
2314
- },
2315
- {
2316
- buffer: Buffer.from([255, 254]),
2317
- encoding: "UTF-16 LE"
2318
- }
2319
- ];
2320
- function removeBOMAndValidate(buffer, file2) {
2321
- for (const bom of UNSUPPORTED_BOMS) if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) throw new ParseError({
2322
- text: `Configuration file contains ${bom.encoding} byte order marker`,
2323
- notes: [{ text: `The file "${file2}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.` }],
2324
- location: {
2325
- file: file2,
2326
- line: 1,
2327
- column: 0
2328
- },
2329
- telemetryMessage: `${bom.encoding} BOM detected`
2330
- });
2331
- const content = buffer.toString("utf-8");
2332
- if (content.charCodeAt(0) === 65279) return content.slice(1);
2333
- return content;
2334
- }
2335
- __name(removeBOMAndValidate, "removeBOMAndValidate");
2336
- var INHERIT_SYMBOL = Symbol.for("inherit_binding");
2337
- var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
2338
- function absolute(input, root) {
2339
- return isAbsolute(input) ? input : resolve(root || ".", input);
2340
- }
2341
- __name(absolute, "absolute");
2342
- function up(base, options) {
2343
- let { last, cwd } = options || {};
2344
- let tmp = absolute(base, cwd);
2345
- let root = absolute(last || "/", cwd);
2346
- let prev, arr = [];
2347
- while (prev !== root) {
2348
- arr.push(tmp);
2349
- tmp = dirname(prev = tmp);
2350
- if (tmp === prev) break;
2351
- }
2352
- return arr;
2353
- }
2354
- __name(up, "up");
2355
- function file(name, options) {
2356
- let dir2, tmp;
2357
- for (dir2 of up(options && options.cwd || "", options)) try {
2358
- tmp = join(dir2, name);
2359
- if (statSync(tmp).isFile()) return tmp;
2360
- } catch {}
2361
- }
2362
- __name(file, "file");
2363
- function dir(name, options) {
2364
- let dir2, tmp;
2365
- for (dir2 of up(options && options.cwd || "", options)) try {
2366
- tmp = join(dir2, name);
2367
- if (statSync(tmp).isDirectory()) return tmp;
2368
- } catch {}
2369
- }
2370
- __name(dir, "dir");
2371
- function dedent$2(templ) {
2372
- var values = [];
2373
- for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
2374
- var strings = Array.from(typeof templ === "string" ? [templ] : templ);
2375
- strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
2376
- var indentLengths = strings.reduce(function(arr, str) {
2377
- var matches = str.match(/\n([\t ]+|(?!\s).)/g);
2378
- if (matches) return arr.concat(matches.map(function(match) {
2379
- var _a, _b;
2380
- return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2381
- }));
2382
- return arr;
2383
- }, []);
2384
- if (indentLengths.length) {
2385
- var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
2386
- strings = strings.map(function(str) {
2387
- return str.replace(pattern_1, "\n");
2388
- });
2389
- }
2390
- strings[0] = strings[0].replace(/^\r?\n/, "");
2391
- var string = strings[0];
2392
- values.forEach(function(value, i) {
2393
- var endentations = string.match(/(?:^|\n)( *)$/);
2394
- var endentation = endentations ? endentations[1] : "";
2395
- var indentedValue = value;
2396
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i2) {
2397
- return i2 === 0 ? str : "" + endentation + str;
2398
- }).join("\n");
2399
- string += indentedValue + strings[i + 1];
2400
- });
2401
- return string;
2402
- }
2403
- __name(dedent$2, "dedent");
2404
- var esm_default = dedent$2;
2405
- function resolveWranglerConfigPath({ config, script }, options) {
2406
- if (config !== void 0) return {
2407
- userConfigPath: config,
2408
- configPath: config,
2409
- deployConfigPath: void 0,
2410
- redirected: false
2411
- };
2412
- return findWranglerConfig(script !== void 0 ? path2__default.dirname(script) : process.cwd(), options);
2413
- }
2414
- __name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
2415
- function findWranglerConfig(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
2416
- const userConfigPath = file(`wrangler.json`, { cwd: referencePath }) ?? file(`wrangler.jsonc`, { cwd: referencePath }) ?? file(`wrangler.toml`, { cwd: referencePath });
2417
- if (!useRedirectIfAvailable) return {
2418
- userConfigPath,
2419
- configPath: userConfigPath,
2420
- deployConfigPath: void 0,
2421
- redirected: false
2422
- };
2423
- const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig(referencePath, userConfigPath);
2424
- return {
2425
- userConfigPath,
2426
- configPath,
2427
- deployConfigPath,
2428
- redirected
2429
- };
2430
- }
2431
- __name(findWranglerConfig, "findWranglerConfig");
2432
- function findRedirectedWranglerConfig(cwd, userConfigPath) {
2433
- const deployConfigPath = file(PATH_TO_DEPLOY_CONFIG, { cwd });
2434
- if (deployConfigPath === void 0) return {
2435
- configPath: userConfigPath,
2436
- deployConfigPath,
2437
- redirected: false
2438
- };
2439
- let redirectedConfigPath;
2440
- const deployConfigFile = readFileSync$1(deployConfigPath);
2441
- try {
2442
- const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
2443
- redirectedConfigPath = deployConfig.configPath && path2__default.resolve(path2__default.dirname(deployConfigPath), deployConfig.configPath);
2444
- } catch (e) {
2445
- throw new UserError(`Failed to parse the deploy configuration file at ${path2__default.relative(".", deployConfigPath)}`, {
2446
- cause: e,
2447
- telemetryMessage: false
2448
- });
2449
- }
2450
- if (!redirectedConfigPath) throw new UserError(esm_default`
2451
- A deploy configuration file was found at "${path2__default.relative(".", deployConfigPath)}".
2452
- But this is not valid - the required "configPath" property was not found.
2453
- Instead this file contains:
2454
- \`\`\`
2455
- ${deployConfigFile}
2456
- \`\`\`
2457
- `, { telemetryMessage: false });
2458
- if (!existsSync(redirectedConfigPath)) throw new UserError(esm_default`
2459
- There is a deploy configuration at "${path2__default.relative(".", deployConfigPath)}".
2460
- But the redirected configuration path it points to, "${path2__default.relative(".", redirectedConfigPath)}", does not exist.
2461
- `, { telemetryMessage: false });
2462
- if (userConfigPath) {
2463
- if (path2__default.join(path2__default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
2464
- Found both a user configuration file at "${path2__default.relative(".", userConfigPath)}"
2465
- and a deploy configuration file at "${path2__default.relative(".", deployConfigPath)}".
2466
- But these do not share the same base path so it is not clear which should be used.
2467
- `, { telemetryMessage: false });
2468
- }
2469
- return {
2470
- configPath: redirectedConfigPath,
2471
- deployConfigPath,
2472
- redirected: true
2473
- };
2474
- }
2475
- __name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
2476
- function isRedirectedConfig(config) {
2477
- return config.configPath !== void 0 && config.configPath !== config.userConfigPath;
2478
- }
2479
- __name(isRedirectedConfig, "isRedirectedConfig");
2480
- function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
2481
- return isRedirectedConfig({
2482
- configPath,
2483
- userConfigPath
2484
- });
2485
- }
2486
- __name(isRedirectedRawConfig, "isRedirectedRawConfig");
2487
- function configFormat(configPath) {
2488
- if (configPath?.endsWith("toml")) return "toml";
2489
- if (configPath?.endsWith("jsonc")) return "jsonc";
2490
- if (configPath?.endsWith("json")) return "json";
2491
- return "none";
2492
- }
2493
- __name(configFormat, "configFormat");
2494
- function configFileName(configPath) {
2495
- switch (configFormat(configPath)) {
2496
- case "toml": return "wrangler.toml";
2497
- case "json": return "wrangler.json";
2498
- case "jsonc": return "wrangler.jsonc";
2499
- default: return "Wrangler configuration";
2500
- }
2501
- }
2502
- __name(configFileName, "configFileName");
2503
- function formatConfigSnippet(snippet, configPath, formatted = true) {
2504
- if (configFormat(configPath) === "toml") return dist_default.stringify(snippet);
2505
- else return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
2506
- }
2507
- __name(formatConfigSnippet, "formatConfigSnippet");
2508
-
2509
- //#endregion
2510
- //#region src/build-output.ts
2511
- /**
2512
- * Initial draft version of the Build Output API.
2513
- *
2514
- * Will move to `v1` when the spec stabilises.
2515
- */
2516
- const BUILD_OUTPUT_VERSION = "v0";
2517
- /**
2518
- * Project-relative root.
2519
- */
2520
- const BUILD_OUTPUT_ROOT = ".cloudflare/output";
2521
- /**
2522
- * Filename of the per-Worker config.
2523
- */
2524
- const WORKER_CONFIG_FILENAME = "worker.config.json";
2525
- /**
2526
- * Absolute path to the Build Output API root for the current project.
2527
- */
2528
- function getBuildOutputDir(root) {
2529
- return path.resolve(root, BUILD_OUTPUT_ROOT);
2530
- }
2531
- /**
2532
- * Clean the build output directory.
2533
- */
2534
- async function cleanBuildOutputDir(root) {
2535
- await removeDir(getBuildOutputDir(root));
2536
- }
2537
- /**
2538
- * Absolute path to the Workers output directory.
2539
- */
2540
- function getWorkersDir(root) {
2541
- return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, "workers");
2542
- }
2543
- /**
2544
- * Absolute path to the config file for a given Worker.
2545
- */
2546
- function getWorkerConfigPath(root, workerName) {
2547
- return path.join(getWorkersDir(root), workerName, WORKER_CONFIG_FILENAME);
2548
- }
2549
- /**
2550
- * Absolute path to the bundle directory for a given Worker.
2551
- */
2552
- function getWorkerBundleDir(root, workerName) {
2553
- return path.join(getWorkersDir(root), workerName, "bundle");
2554
- }
2555
- /**
2556
- * Absolute path to the assets directory for a given Worker.
2557
- */
2558
- function getWorkerAssetsDir(root, workerName) {
2559
- return path.join(getWorkersDir(root), workerName, "assets");
2560
- }
2561
- /**
2562
- * Write the output `worker.config.json` for a given Worker to the Build
2563
- * Output API tree.
2564
- *
2565
- * - Workers mode: `manifest` is provided (bundle/ present on disk).
2566
- * - Assets-only mode: `manifest` is omitted (no bundle/ directory).
2567
- */
2568
- async function writeOutputWorkerConfig(root, parsedConfig, manifest) {
2569
- const { entrypoint: _entrypoint,...rest } = parsedConfig;
2570
- const outputConfig = {
2571
- ...rest,
2572
- manifest
2573
- };
2574
- const workerOutputDir = path.join(getWorkersDir(root), outputConfig.name);
2575
- await fsp.mkdir(workerOutputDir, { recursive: true });
2576
- const configPath = getWorkerConfigPath(root, outputConfig.name);
2577
- await fsp.writeFile(configPath, JSON.stringify(outputConfig));
2578
- }
2579
-
2580
- //#endregion
2581
- //#region src/schema.ts
2582
- const AssetsSchema = z.strictObject({
2583
- htmlHandling: z.enum([
2584
- "auto-trailing-slash",
2585
- "drop-trailing-slash",
2586
- "force-trailing-slash",
2587
- "none"
2588
- ]).optional(),
2589
- notFoundHandling: z.enum([
2590
- "single-page-application",
2591
- "404-page",
2592
- "none"
2593
- ]).optional(),
2594
- runWorkerFirst: z.union([z.array(z.string()), z.boolean()]).optional()
2595
- });
2596
- const KnownBindingSchema = z.discriminatedUnion("type", [
2597
- z.strictObject({
2598
- type: z.literal("agent-memory"),
2599
- namespace: z.string(),
2600
- remote: z.boolean().optional()
2601
- }),
2602
- z.strictObject({
2603
- type: z.literal("ai"),
2604
- remote: z.boolean().optional()
2605
- }),
2606
- z.strictObject({
2607
- type: z.literal("ai-search"),
2608
- name: z.string(),
2609
- remote: z.boolean().optional()
2610
- }),
2611
- z.strictObject({
2612
- type: z.literal("ai-search-namespace"),
2613
- namespace: z.string(),
2614
- remote: z.boolean().optional()
2615
- }),
2616
- z.strictObject({
2617
- type: z.literal("analytics-engine-dataset"),
2618
- name: z.string().optional()
2619
- }),
2620
- z.strictObject({
2621
- type: z.literal("artifacts"),
2622
- namespace: z.string(),
2623
- remote: z.boolean().optional()
2624
- }),
2625
- z.strictObject({ type: z.literal("assets") }),
2626
- z.strictObject({
2627
- type: z.literal("browser"),
2628
- remote: z.boolean().optional()
2629
- }),
2630
- z.strictObject({
2631
- type: z.literal("d1"),
2632
- name: z.string().optional(),
2633
- id: z.string().optional(),
2634
- remote: z.boolean().optional()
2635
- }),
2636
- z.strictObject({
2637
- type: z.literal("dispatch-namespace"),
2638
- namespace: z.string(),
2639
- outbound: z.strictObject({
2640
- workerName: z.string(),
2641
- parameters: z.array(z.string()).optional()
2642
- }).optional(),
2643
- remote: z.boolean().optional()
2644
- }),
2645
- z.strictObject({
2646
- type: z.literal("durable-object"),
2647
- workerName: z.string(),
2648
- exportName: z.string()
2649
- }),
2650
- z.strictObject({
2651
- type: z.literal("flagship"),
2652
- id: z.string(),
2653
- remote: z.boolean().optional()
2654
- }),
2655
- z.strictObject({
2656
- type: z.literal("hyperdrive"),
2657
- id: z.string(),
2658
- localConnectionString: z.string().optional()
2659
- }),
2660
- z.strictObject({
2661
- type: z.literal("images"),
2662
- remote: z.boolean().optional()
2663
- }),
2664
- z.strictObject({
2665
- type: z.literal("json"),
2666
- value: z.json()
2667
- }),
2668
- z.strictObject({
2669
- type: z.literal("kv"),
2670
- id: z.string().optional(),
2671
- remote: z.boolean().optional()
2672
- }),
2673
- z.strictObject({
2674
- type: z.literal("logfwdr"),
2675
- destination: z.string()
2676
- }),
2677
- z.strictObject({
2678
- type: z.literal("media"),
2679
- remote: z.boolean().optional()
2680
- }),
2681
- z.strictObject({
2682
- type: z.literal("mtls-certificate"),
2683
- id: z.string(),
2684
- remote: z.boolean().optional()
2685
- }),
2686
- z.strictObject({
2687
- type: z.literal("pipeline"),
2688
- name: z.string(),
2689
- remote: z.boolean().optional()
2690
- }),
2691
- z.strictObject({
2692
- type: z.literal("queue"),
2693
- name: z.string(),
2694
- deliveryDelay: z.number().optional(),
2695
- remote: z.boolean().optional()
2696
- }),
2697
- z.strictObject({
2698
- type: z.literal("rate-limit"),
2699
- namespace: z.string(),
2700
- simple: z.strictObject({
2701
- limit: z.number(),
2702
- period: z.union([z.literal(10), z.literal(60)])
2703
- })
2704
- }),
2705
- z.strictObject({
2706
- type: z.literal("r2"),
2707
- name: z.string().optional(),
2708
- jurisdiction: z.string().optional(),
2709
- remote: z.boolean().optional()
2710
- }),
2711
- z.strictObject({ type: z.literal("secret") }),
2712
- z.strictObject({
2713
- type: z.literal("secrets-store-secret"),
2714
- storeId: z.string(),
2715
- secretName: z.string()
2716
- }),
2717
- z.strictObject({
2718
- type: z.literal("send-email"),
2719
- destinationAddress: z.string().optional(),
2720
- allowedDestinationAddresses: z.array(z.string()).optional(),
2721
- allowedSenderAddresses: z.array(z.string()).optional(),
2722
- remote: z.boolean().optional()
2723
- }),
2724
- z.strictObject({
2725
- type: z.literal("stream"),
2726
- remote: z.boolean().optional()
2727
- }),
2728
- z.strictObject({
2729
- type: z.literal("text"),
2730
- value: z.string()
2731
- }),
2732
- z.strictObject({
2733
- type: z.literal("vectorize"),
2734
- name: z.string(),
2735
- remote: z.boolean().optional()
2736
- }),
2737
- z.strictObject({ type: z.literal("version-metadata") }),
2738
- z.strictObject({
2739
- type: z.literal("vpc-service"),
2740
- id: z.string(),
2741
- remote: z.boolean().optional()
2742
- }),
2743
- z.strictObject({
2744
- type: z.literal("vpc-network"),
2745
- tunnelId: z.string().optional(),
2746
- networkId: z.string().optional(),
2747
- remote: z.boolean().optional()
2748
- }).superRefine((value, ctx) => {
2749
- const hasTunnel = value.tunnelId !== void 0;
2750
- if (hasTunnel === (value.networkId !== void 0)) ctx.addIssue({
2751
- code: "custom",
2752
- message: hasTunnel ? `"vpc-network" bindings must specify exactly one of "tunnelId" or "networkId", not both` : `"vpc-network" bindings must specify either "tunnelId" or "networkId"`
2753
- });
2754
- }),
2755
- z.strictObject({
2756
- type: z.literal("web-search"),
2757
- remote: z.boolean().optional()
2758
- }),
2759
- z.strictObject({
2760
- type: z.literal("worker"),
2761
- workerName: z.string(),
2762
- exportName: z.string().optional(),
2763
- props: z.record(z.string(), z.unknown()).optional(),
2764
- remote: z.boolean().optional()
2765
- }),
2766
- z.strictObject({ type: z.literal("worker-loader") })
2767
- ]);
2768
- const UnsafeBindingSchema = z.looseObject({
2769
- type: z.templateLiteral(["unsafe:", z.string().min(1)]),
2770
- dev: z.strictObject({
2771
- plugin: z.strictObject({
2772
- package: z.string(),
2773
- name: z.string()
2774
- }),
2775
- options: z.record(z.string(), z.unknown()).optional()
2776
- }).optional()
2777
- });
2778
- const BindingSchema = z.unknown().transform((value, ctx) => {
2779
- const result = (typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && value.type.startsWith("unsafe:") ? UnsafeBindingSchema : KnownBindingSchema).safeParse(value);
2780
- if (!result.success) {
2781
- ctx.issues.push(...result.error.issues);
2782
- return z.NEVER;
2783
- }
2784
- return result.data;
2785
- });
2786
- function isParsedUnsafeBinding(binding) {
2787
- return binding.type.startsWith("unsafe:");
2788
- }
2789
- const CacheSchema = z.strictObject({
2790
- enabled: z.boolean(),
2791
- crossVersionCache: z.boolean().optional()
2792
- });
2793
- /**
2794
- * Binding types that can only be defined once per worker.
2795
- */
2796
- const SINGLETON_BINDING_TYPES = new Set([
2797
- "ai",
2798
- "assets",
2799
- "browser",
2800
- "images",
2801
- "media",
2802
- "stream",
2803
- "version-metadata",
2804
- "web-search"
2805
- ]);
2806
- const listFormatter = new Intl.ListFormat("en-US");
2807
- const EnvSchema = z.record(z.string(), BindingSchema).superRefine((env, ctx) => {
2808
- const seen = /* @__PURE__ */ new Set();
2809
- const duplicates = /* @__PURE__ */ new Set();
2810
- for (const binding of Object.values(env)) {
2811
- const type = binding.type;
2812
- if (SINGLETON_BINDING_TYPES.has(type)) {
2813
- if (seen.has(type)) duplicates.add(type);
2814
- seen.add(type);
2815
- }
2816
- }
2817
- if (duplicates.size > 0) ctx.addIssue({
2818
- code: "custom",
2819
- message: `${listFormatter.format([...duplicates].sort())} bindings can only be defined once`
2820
- });
2821
- }).optional();
2822
- const ExportSchema = z.union([
2823
- z.strictObject({
2824
- type: z.literal("durable-object"),
2825
- state: z.literal("created").optional(),
2826
- storage: z.enum(["sqlite", "legacy-kv"])
2827
- }),
2828
- z.strictObject({
2829
- type: z.literal("durable-object"),
2830
- state: z.literal("deleted")
2831
- }),
2832
- z.strictObject({
2833
- type: z.literal("durable-object"),
2834
- state: z.literal("renamed"),
2835
- renamedTo: z.string()
2836
- }),
2837
- z.strictObject({
2838
- type: z.literal("durable-object"),
2839
- state: z.literal("transferred"),
2840
- transferredTo: z.string()
2841
- }),
2842
- z.strictObject({
2843
- type: z.literal("durable-object"),
2844
- state: z.literal("expecting-transfer"),
2845
- storage: z.enum(["sqlite", "legacy-kv"]),
2846
- transferFrom: z.string()
2847
- }),
2848
- z.strictObject({
2849
- type: z.literal("worker"),
2850
- cache: z.strictObject({ enabled: z.boolean() }).optional()
2851
- })
2852
- ]);
2853
- const LimitsSchema = z.strictObject({
2854
- cpuMs: z.number().optional(),
2855
- subrequests: z.number().optional()
2856
- });
2857
- const ObservabilitySchema = z.strictObject({
2858
- enabled: z.boolean().optional(),
2859
- headSamplingRate: z.number().optional(),
2860
- logs: z.strictObject({
2861
- enabled: z.boolean().optional(),
2862
- headSamplingRate: z.number().optional(),
2863
- invocationLogs: z.boolean().optional(),
2864
- persist: z.boolean().optional(),
2865
- destinations: z.array(z.string()).optional()
2866
- }).optional(),
2867
- traces: z.strictObject({
2868
- enabled: z.boolean().optional(),
2869
- headSamplingRate: z.number().optional(),
2870
- persist: z.boolean().optional(),
2871
- destinations: z.array(z.string()).optional()
2872
- }).optional()
2873
- });
2874
- const PlacementSchema = z.union([
2875
- z.strictObject({
2876
- mode: z.enum(["off", "smart"]),
2877
- hint: z.string().optional()
2878
- }),
2879
- z.strictObject({
2880
- mode: z.literal("targeted").optional(),
2881
- region: z.string()
2882
- }),
2883
- z.strictObject({
2884
- mode: z.literal("targeted").optional(),
2885
- host: z.string()
2886
- }),
2887
- z.strictObject({
2888
- mode: z.literal("targeted").optional(),
2889
- hostname: z.string()
2890
- })
2891
- ]);
2892
- const TailConsumerSchema = z.strictObject({
2893
- workerName: z.string(),
2894
- streaming: z.boolean().optional()
2895
- });
2896
- const TriggerSchema = z.discriminatedUnion("type", [
2897
- z.strictObject({
2898
- type: z.literal("email"),
2899
- addresses: z.array(z.string())
2900
- }),
2901
- z.strictObject({
2902
- type: z.literal("fetch"),
2903
- pattern: z.string(),
2904
- zone: z.string().optional()
2905
- }),
2906
- z.strictObject({
2907
- type: z.literal("queue"),
2908
- name: z.string(),
2909
- deadLetterQueue: z.string().optional(),
2910
- maxBatchSize: z.number().optional(),
2911
- maxBatchTimeout: z.number().optional(),
2912
- maxConcurrency: z.number().nullable().optional(),
2913
- maxRetries: z.number().optional(),
2914
- retryDelay: z.number().optional(),
2915
- visibilityTimeoutMs: z.number().optional()
2916
- }),
2917
- z.strictObject({
2918
- type: z.literal("scheduled"),
2919
- schedule: z.string()
2920
- })
2921
- ]);
2922
- const UnsafeSchema = z.strictObject({
2923
- metadata: z.record(z.string(), z.unknown()).optional(),
2924
- capnp: z.union([z.strictObject({
2925
- basePath: z.string(),
2926
- sourceSchemas: z.array(z.string()),
2927
- compiledSchema: z.never().optional()
2928
- }), z.strictObject({
2929
- basePath: z.never().optional(),
2930
- sourceSchemas: z.never().optional(),
2931
- compiledSchema: z.string()
2932
- })]).optional()
2933
- });
2934
- /**
2935
- * Base Worker schema — the set of fields shared between the input
2936
- * (user-authored) and output (on-disk) Worker configs.
2937
- */
2938
- const BaseWorkerSchema = z.strictObject({
2939
- name: z.string(),
2940
- accountId: z.string().optional(),
2941
- compatibilityDate: z.string(),
2942
- compatibilityFlags: z.array(z.string()).optional(),
2943
- assets: AssetsSchema.optional(),
2944
- domains: z.array(z.string()).optional(),
2945
- triggers: z.array(TriggerSchema).optional(),
2946
- tailConsumers: z.array(TailConsumerSchema).optional(),
2947
- cache: CacheSchema.optional(),
2948
- placement: PlacementSchema.optional(),
2949
- limits: LimitsSchema.optional(),
2950
- logpush: z.boolean().optional(),
2951
- observability: ObservabilitySchema.optional(),
2952
- workersDev: z.boolean().optional(),
2953
- previewUrls: z.boolean().optional(),
2954
- complianceRegion: z.enum(["public", "fedramp-high"]).optional(),
2955
- firstPartyWorker: z.boolean().optional(),
2956
- unsafe: UnsafeSchema.optional(),
2957
- env: EnvSchema,
2958
- exports: z.record(z.string(), ExportSchema).optional()
2959
- });
2960
- /**
2961
- * Input Worker schema — the shape that user-authored `cloudflare.config.ts`
2962
- * files are validated against. Adds an optional `entrypoint` field to the
2963
- * base schema.
2964
- */
2965
- const InputWorkerSchema = BaseWorkerSchema.extend({ entrypoint: z.union([z.string(), z.strictObject({ default: z.string() })]).transform((value) => typeof value === "string" ? value : value.default).optional() });
2966
- const ModuleTypeSchema = z.enum([
2967
- "esm",
2968
- "cjs",
2969
- "python",
2970
- "python-requirement",
2971
- "wasm",
2972
- "text",
2973
- "data",
2974
- "json",
2975
- "sourcemap"
2976
- ]);
2977
- const ManifestSchema = z.strictObject({
2978
- mainModule: z.string(),
2979
- modules: z.record(z.string(), z.strictObject({ type: ModuleTypeSchema }))
2980
- });
2981
- /**
2982
- * Output Worker schema — the shape of `worker.config.json` in the
2983
- * Build Output API. Adds an optional `manifest` field to the
2984
- * base schema.
2985
- */
2986
- const OutputWorkerSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional() });
2987
-
2988
- //#endregion
2989
- //#region ../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js
2990
- var require_dist = /* @__PURE__ */ __commonJS({ "../../node_modules/.pnpm/ts-dedent@2.2.0/node_modules/ts-dedent/dist/index.js": ((exports) => {
2991
- Object.defineProperty(exports, "__esModule", { value: true });
2992
- exports.dedent = void 0;
2993
- function dedent$1(templ) {
2994
- var values = [];
2995
- for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
2996
- var strings = Array.from(typeof templ === "string" ? [templ] : templ);
2997
- strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
2998
- var indentLengths = strings.reduce(function(arr, str) {
2999
- var matches = str.match(/\n([\t ]+|(?!\s).)/g);
3000
- if (matches) return arr.concat(matches.map(function(match) {
3001
- var _a, _b;
3002
- return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
3003
- }));
3004
- return arr;
3005
- }, []);
3006
- if (indentLengths.length) {
3007
- var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
3008
- strings = strings.map(function(str) {
3009
- return str.replace(pattern_1, "\n");
3010
- });
3011
- }
3012
- strings[0] = strings[0].replace(/^\r?\n/, "");
3013
- var string = strings[0];
3014
- values.forEach(function(value, i) {
3015
- var endentations = string.match(/(?:^|\n)( *)$/);
3016
- var endentation = endentations ? endentations[1] : "";
3017
- var indentedValue = value;
3018
- if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i$1) {
3019
- return i$1 === 0 ? str : "" + endentation + str;
3020
- }).join("\n");
3021
- string += indentedValue + strings[i + 1];
2796
+ 0,
2797
+ 254,
2798
+ 255
2799
+ ]),
2800
+ encoding: "UTF-32 BE"
2801
+ },
2802
+ {
2803
+ buffer: Buffer.from([
2804
+ 255,
2805
+ 254,
2806
+ 0,
2807
+ 0
2808
+ ]),
2809
+ encoding: "UTF-32 LE"
2810
+ },
2811
+ {
2812
+ buffer: Buffer.from([254, 255]),
2813
+ encoding: "UTF-16 BE"
2814
+ },
2815
+ {
2816
+ buffer: Buffer.from([255, 254]),
2817
+ encoding: "UTF-16 LE"
2818
+ }
2819
+ ];
2820
+ function removeBOMAndValidate(buffer, file2) {
2821
+ for (const bom of UNSUPPORTED_BOMS) if (buffer.length >= bom.buffer.length && buffer.subarray(0, bom.buffer.length).equals(bom.buffer)) throw new ParseError({
2822
+ text: `Configuration file contains ${bom.encoding} byte order marker`,
2823
+ notes: [{ text: `The file "${file2}" appears to be encoded as ${bom.encoding}. Please save the file as UTF-8 without BOM.` }],
2824
+ location: {
2825
+ file: file2,
2826
+ line: 1,
2827
+ column: 0
2828
+ },
2829
+ telemetryMessage: `${bom.encoding} BOM detected`
2830
+ });
2831
+ const content = buffer.toString("utf-8");
2832
+ if (content.charCodeAt(0) === 65279) return content.slice(1);
2833
+ return content;
2834
+ }
2835
+ __name(removeBOMAndValidate, "removeBOMAndValidate");
2836
+ var INHERIT_SYMBOL = Symbol.for("inherit_binding");
2837
+ var PATH_TO_DEPLOY_CONFIG = ".wrangler/deploy/config.json";
2838
+ function absolute(input, root) {
2839
+ return isAbsolute(input) ? input : resolve(root || ".", input);
2840
+ }
2841
+ __name(absolute, "absolute");
2842
+ function up(base, options) {
2843
+ let { last, cwd } = options || {};
2844
+ let tmp = absolute(base, cwd);
2845
+ let root = absolute(last || "/", cwd);
2846
+ let prev, arr = [];
2847
+ while (prev !== root) {
2848
+ arr.push(tmp);
2849
+ tmp = dirname(prev = tmp);
2850
+ if (tmp === prev) break;
2851
+ }
2852
+ return arr;
2853
+ }
2854
+ __name(up, "up");
2855
+ function file(name, options) {
2856
+ let dir2, tmp;
2857
+ for (dir2 of up(options && options.cwd || "", options)) try {
2858
+ tmp = join(dir2, name);
2859
+ if (statSync(tmp).isFile()) return tmp;
2860
+ } catch {}
2861
+ }
2862
+ __name(file, "file");
2863
+ function dir(name, options) {
2864
+ let dir2, tmp;
2865
+ for (dir2 of up(options && options.cwd || "", options)) try {
2866
+ tmp = join(dir2, name);
2867
+ if (statSync(tmp).isDirectory()) return tmp;
2868
+ } catch {}
2869
+ }
2870
+ __name(dir, "dir");
2871
+ function dedent(templ) {
2872
+ var values = [];
2873
+ for (var _i = 1; _i < arguments.length; _i++) values[_i - 1] = arguments[_i];
2874
+ var strings = Array.from(typeof templ === "string" ? [templ] : templ);
2875
+ strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, "");
2876
+ var indentLengths = strings.reduce(function(arr, str) {
2877
+ var matches = str.match(/\n([\t ]+|(?!\s).)/g);
2878
+ if (matches) return arr.concat(matches.map(function(match) {
2879
+ var _a, _b;
2880
+ return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
2881
+ }));
2882
+ return arr;
2883
+ }, []);
2884
+ if (indentLengths.length) {
2885
+ var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g");
2886
+ strings = strings.map(function(str) {
2887
+ return str.replace(pattern_1, "\n");
3022
2888
  });
3023
- return string;
3024
2889
  }
3025
- exports.dedent = dedent$1;
3026
- }) });
3027
-
3028
- //#endregion
3029
- //#region src/generate.ts
3030
- var import_dist = require_dist();
3031
- /**
3032
- * Generate the content for worker-configuration.d.ts
3033
- *
3034
- * @example
3035
- * ```typescript
3036
- * import { generateTypes } from "@cloudflare/config";
3037
- * import { writeFileSync } from "node:fs";
3038
- *
3039
- * const content = generateTypes({
3040
- * configPath: "./cloudflare.config.ts",
3041
- * });
3042
- *
3043
- * writeFileSync("worker-configuration.d.ts", content);
3044
- * ```
3045
- */
3046
- function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
3047
- return import_dist.dedent`
3048
- /* eslint-disable */
3049
- // Generated by @cloudflare/config
3050
- type __WorkerConfig = import("${packageName}").UnwrapConfig<typeof import("${configPath.replace(/\.(ts|js|mts|mjs)$/, "")}").default>;
3051
- type __Env = import("${packageName}").InferEnv<__WorkerConfig>;
3052
-
3053
- declare namespace Cloudflare {
3054
- interface GlobalProps {
3055
- mainModule: import("${packageName}").InferMainModule<__WorkerConfig>;
3056
- durableNamespaces: import("${packageName}").InferDurableNamespaces<__WorkerConfig>;
3057
- }
3058
- interface Env extends __Env {}
3059
- }
3060
- interface Env extends Cloudflare.Env {}
3061
-
3062
- `;
2890
+ strings[0] = strings[0].replace(/^\r?\n/, "");
2891
+ var string = strings[0];
2892
+ values.forEach(function(value, i) {
2893
+ var endentations = string.match(/(?:^|\n)( *)$/);
2894
+ var endentation = endentations ? endentations[1] : "";
2895
+ var indentedValue = value;
2896
+ if (typeof value === "string" && value.includes("\n")) indentedValue = String(value).split("\n").map(function(str, i2) {
2897
+ return i2 === 0 ? str : "" + endentation + str;
2898
+ }).join("\n");
2899
+ string += indentedValue + strings[i + 1];
2900
+ });
2901
+ return string;
2902
+ }
2903
+ __name(dedent, "dedent");
2904
+ var esm_default = dedent;
2905
+ function resolveWranglerConfigPath({ config, script }, options) {
2906
+ if (config !== void 0) return {
2907
+ userConfigPath: config,
2908
+ configPath: config,
2909
+ deployConfigPath: void 0,
2910
+ redirected: false
2911
+ };
2912
+ return findWranglerConfig(script !== void 0 ? path2__default.dirname(script) : process.cwd(), options);
2913
+ }
2914
+ __name(resolveWranglerConfigPath, "resolveWranglerConfigPath");
2915
+ function findWranglerConfig(referencePath = process.cwd(), { useRedirectIfAvailable = false } = {}) {
2916
+ const userConfigPath = file(`wrangler.json`, { cwd: referencePath }) ?? file(`wrangler.jsonc`, { cwd: referencePath }) ?? file(`wrangler.toml`, { cwd: referencePath });
2917
+ if (!useRedirectIfAvailable) return {
2918
+ userConfigPath,
2919
+ configPath: userConfigPath,
2920
+ deployConfigPath: void 0,
2921
+ redirected: false
2922
+ };
2923
+ const { configPath, deployConfigPath, redirected } = findRedirectedWranglerConfig(referencePath, userConfigPath);
2924
+ return {
2925
+ userConfigPath,
2926
+ configPath,
2927
+ deployConfigPath,
2928
+ redirected
2929
+ };
2930
+ }
2931
+ __name(findWranglerConfig, "findWranglerConfig");
2932
+ function findRedirectedWranglerConfig(cwd, userConfigPath) {
2933
+ const deployConfigPath = file(PATH_TO_DEPLOY_CONFIG, { cwd });
2934
+ if (deployConfigPath === void 0) return {
2935
+ configPath: userConfigPath,
2936
+ deployConfigPath,
2937
+ redirected: false
2938
+ };
2939
+ let redirectedConfigPath;
2940
+ const deployConfigFile = readFileSync$1(deployConfigPath);
2941
+ try {
2942
+ const deployConfig = parseJSONC(deployConfigFile, deployConfigPath);
2943
+ redirectedConfigPath = deployConfig.configPath && path2__default.resolve(path2__default.dirname(deployConfigPath), deployConfig.configPath);
2944
+ } catch (e) {
2945
+ throw new UserError(`Failed to parse the deploy configuration file at ${path2__default.relative(".", deployConfigPath)}`, {
2946
+ cause: e,
2947
+ telemetryMessage: false
2948
+ });
2949
+ }
2950
+ if (!redirectedConfigPath) throw new UserError(esm_default`
2951
+ A deploy configuration file was found at "${path2__default.relative(".", deployConfigPath)}".
2952
+ But this is not valid - the required "configPath" property was not found.
2953
+ Instead this file contains:
2954
+ \`\`\`
2955
+ ${deployConfigFile}
2956
+ \`\`\`
2957
+ `, { telemetryMessage: false });
2958
+ if (!existsSync(redirectedConfigPath)) throw new UserError(esm_default`
2959
+ There is a deploy configuration at "${path2__default.relative(".", deployConfigPath)}".
2960
+ But the redirected configuration path it points to, "${path2__default.relative(".", redirectedConfigPath)}", does not exist.
2961
+ `, { telemetryMessage: false });
2962
+ if (userConfigPath) {
2963
+ if (path2__default.join(path2__default.dirname(userConfigPath), PATH_TO_DEPLOY_CONFIG) !== deployConfigPath) throw new UserError(esm_default`
2964
+ Found both a user configuration file at "${path2__default.relative(".", userConfigPath)}"
2965
+ and a deploy configuration file at "${path2__default.relative(".", deployConfigPath)}".
2966
+ But these do not share the same base path so it is not clear which should be used.
2967
+ `, { telemetryMessage: false });
2968
+ }
2969
+ return {
2970
+ configPath: redirectedConfigPath,
2971
+ deployConfigPath,
2972
+ redirected: true
2973
+ };
2974
+ }
2975
+ __name(findRedirectedWranglerConfig, "findRedirectedWranglerConfig");
2976
+ function isRedirectedConfig(config) {
2977
+ return config.configPath !== void 0 && config.configPath !== config.userConfigPath;
2978
+ }
2979
+ __name(isRedirectedConfig, "isRedirectedConfig");
2980
+ function isRedirectedRawConfig(rawConfig, configPath, userConfigPath) {
2981
+ return isRedirectedConfig({
2982
+ configPath,
2983
+ userConfigPath
2984
+ });
2985
+ }
2986
+ __name(isRedirectedRawConfig, "isRedirectedRawConfig");
2987
+ function configFormat(configPath) {
2988
+ if (configPath?.endsWith("toml")) return "toml";
2989
+ if (configPath?.endsWith("jsonc")) return "jsonc";
2990
+ if (configPath?.endsWith("json")) return "json";
2991
+ return "none";
2992
+ }
2993
+ __name(configFormat, "configFormat");
2994
+ function configFileName(configPath) {
2995
+ switch (configFormat(configPath)) {
2996
+ case "toml": return "wrangler.toml";
2997
+ case "json": return "wrangler.json";
2998
+ case "jsonc": return "wrangler.jsonc";
2999
+ default: return "Wrangler configuration";
3000
+ }
3001
+ }
3002
+ __name(configFileName, "configFileName");
3003
+ function formatConfigSnippet(snippet, configPath, formatted = true) {
3004
+ if (configFormat(configPath) === "toml") return dist_default.stringify(snippet);
3005
+ else return formatted ? JSON.stringify(snippet, null, 2) : JSON.stringify(snippet);
3063
3006
  }
3007
+ __name(formatConfigSnippet, "formatConfigSnippet");
3064
3008
 
3065
3009
  //#endregion
3066
3010
  //#region src/convert.ts
@@ -3070,29 +3014,38 @@ function generateTypes({ configPath, packageName = "@cloudflare/config" }) {
3070
3014
  * The caller is responsible for unwrapping any function/promise wrapper around
3071
3015
  * the config and validating it against `InputWorkerSchema` before passing it in.
3072
3016
  *
3073
- * @param config The parsed (post-validation) config.
3017
+ * @param workerConfig The parsed (post-validation) Worker config.
3018
+ * @param settingsConfig The optional parsed settings config, whose fields
3019
+ * are merged onto the result.
3074
3020
  * @returns The corresponding Wrangler `RawConfig`.
3075
3021
  */
3076
- function convertToWranglerConfig(config) {
3022
+ function convertToWranglerConfig(workerConfig, settingsConfig) {
3077
3023
  const result = {};
3078
- convertTopLevel(config, result);
3079
- convertBindingsAndAssets(config, result);
3080
- convertExports(config, result);
3081
- convertDomains(config, result);
3082
- convertTriggers(config, result);
3083
- convertTailConsumers(config, result);
3024
+ convertTopLevel(workerConfig, result);
3025
+ convertBindingsAndAssets(workerConfig, result);
3026
+ convertExports(workerConfig, result);
3027
+ convertDomains(workerConfig, result);
3028
+ convertTriggers(workerConfig, result);
3029
+ convertTailConsumers(workerConfig, result);
3030
+ if (settingsConfig !== void 0) convertSettings(settingsConfig, result);
3084
3031
  return result;
3085
3032
  }
3033
+ /**
3034
+ * Merge a parsed settings config's fields (`account_id`, `compliance_region`)
3035
+ * onto an existing Wrangler `RawConfig`.
3036
+ */
3037
+ function convertSettings(settings, result) {
3038
+ if (settings.accountId !== void 0) result.account_id = settings.accountId;
3039
+ if (settings.complianceRegion !== void 0) result.compliance_region = settings.complianceRegion === "fedramp-high" ? "fedramp_high" : "public";
3040
+ }
3086
3041
  function convertTopLevel(config, result) {
3087
3042
  if (config.name !== void 0) result.name = config.name;
3088
3043
  if (typeof config.entrypoint === "string") result.main = config.entrypoint;
3089
- if (config.accountId !== void 0) result.account_id = config.accountId;
3090
3044
  if (config.compatibilityDate !== void 0) result.compatibility_date = config.compatibilityDate;
3091
3045
  if (config.compatibilityFlags !== void 0) result.compatibility_flags = config.compatibilityFlags;
3092
3046
  if (config.workersDev !== void 0) result.workers_dev = config.workersDev;
3093
3047
  if (config.previewUrls !== void 0) result.preview_urls = config.previewUrls;
3094
3048
  if (config.logpush !== void 0) result.logpush = config.logpush;
3095
- if (config.complianceRegion !== void 0) result.compliance_region = config.complianceRegion === "fedramp-high" ? "fedramp_high" : "public";
3096
3049
  if (config.firstPartyWorker !== void 0) result.first_party_worker = config.firstPartyWorker;
3097
3050
  if (config.placement !== void 0) result.placement = config.placement;
3098
3051
  if (config.limits !== void 0) {
@@ -3524,9 +3477,10 @@ function convertTriggers(config, result) {
3524
3477
  const crons = [];
3525
3478
  const routes = result.routes ? [...result.routes] : [];
3526
3479
  const queueConsumers = result.queues?.consumers ? [...result.queues.consumers] : [];
3527
- const addresses = result.addresses ? [...result.addresses] : [];
3480
+ let addresses;
3528
3481
  for (const trigger of triggers$1) switch (trigger.type) {
3529
3482
  case "email":
3483
+ addresses ??= [];
3530
3484
  addresses.push(...trigger.addresses);
3531
3485
  break;
3532
3486
  case "scheduled":
@@ -3562,7 +3516,7 @@ function convertTriggers(config, result) {
3562
3516
  ...result.queues ?? {},
3563
3517
  consumers: queueConsumers
3564
3518
  };
3565
- if (addresses.length) result.addresses = addresses;
3519
+ if (addresses !== void 0) result.addresses = addresses;
3566
3520
  }
3567
3521
  function convertDomains(config, result) {
3568
3522
  if (!config.domains || config.domains.length === 0) return;
@@ -3614,20 +3568,29 @@ const depsStore = new AsyncLocalStorage();
3614
3568
  /**
3615
3569
  * Dynamically import a worker config file from disk.
3616
3570
  *
3617
- * Returns the module's default export, plus the set of file paths
3618
- * imported during resolution. Callers are responsible for unwrapping
3619
- * function/promise wrappers around the returned value and validating it
3620
- * against `InputWorkerSchema`.
3571
+ * Returns all of the module's exports (keyed by export name, including
3572
+ * `default`), plus the set of file paths imported during resolution. Callers
3573
+ * are responsible for unwrapping function/promise/definition wrappers around
3574
+ * each export and validating them.
3621
3575
  *
3622
3576
  * @param configPath Filesystem path to the config file. Relative paths are
3623
3577
  * resolved against `process.cwd()`.
3578
+ * @param options.include When provided, only exports whose names are listed
3579
+ * survive into the returned `exports` map. Filtering happens before any
3580
+ * resolution or validation.
3624
3581
  */
3625
- async function loadConfig(configPath) {
3582
+ async function loadConfig(configPath, options) {
3626
3583
  registerConfigHooks();
3627
3584
  const url = pathToFileURL(configPath).href;
3628
3585
  const dependencies = /* @__PURE__ */ new Set();
3586
+ const mod = await depsStore.run(dependencies, () => import(url, { with: { [CF_ATTR]: CF_NO_CACHE_VALUE } }));
3587
+ const exports$2 = {};
3588
+ for (const [name, value] of Object.entries(mod)) {
3589
+ if (options?.include && !options.include.includes(name)) continue;
3590
+ exports$2[name] = value;
3591
+ }
3629
3592
  return {
3630
- config: (await depsStore.run(dependencies, () => import(url, { with: { [CF_ATTR]: CF_NO_CACHE_VALUE } }))).default,
3593
+ exports: exports$2,
3631
3594
  dependencies
3632
3595
  };
3633
3596
  }
@@ -3713,4 +3676,19 @@ function cleanupImportAttributes(context) {
3713
3676
  }
3714
3677
 
3715
3678
  //#endregion
3716
- export { BUILD_OUTPUT_ROOT, BUILD_OUTPUT_VERSION, InputWorkerSchema, ModuleTypeSchema, OutputWorkerSchema, WORKER_CONFIG_FILENAME, bindings, cleanBuildOutputDir, convertToWranglerConfig, defineWorker, exports$1 as exports, generateTypes, getWorkerAssetsDir, getWorkerBundleDir, getWorkerConfigPath, getWorkersDir, loadConfig, registerConfigHooks, resolveWorkerDefinition, triggers, writeOutputWorkerConfig };
3679
+ //#region src/config-loader.ts
3680
+ /**
3681
+ * Load a `cloudflare.config.ts`, resolve all exports, and validate against {@link ConfigExportsSchema}.
3682
+ */
3683
+ async function loadAndValidateConfig(configPath, ctx, options) {
3684
+ const { exports: exports$2, dependencies } = await loadConfig(configPath, options);
3685
+ const resolved = {};
3686
+ for (const [name, value] of Object.entries(exports$2)) resolved[name] = await resolveExportDefinition(value, ctx);
3687
+ return {
3688
+ result: ConfigExportsSchema.safeParse(resolved),
3689
+ dependencies
3690
+ };
3691
+ }
3692
+
3693
+ //#endregion
3694
+ export { ConfigExportsSchema, InputWorkerSchema, ModuleTypeSchema, OutputWorkerSchema, SettingsSchema, bindings, convertToWranglerConfig, defineSettings, defineWorker, exports$1 as exports, generateTypes, loadAndValidateConfig, loadConfig, registerConfigHooks, resolveExportDefinition, triggers };