-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathvalidation.ts
More file actions
5266 lines (4860 loc) · 131 KB
/
validation.ts
File metadata and controls
5266 lines (4860 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from "node:assert";
import fs from "node:fs";
import path from "node:path";
import { isValidWorkflowName } from "@cloudflare/workflows-shared/src/lib/validators";
import { dedent } from "ts-dedent";
import { getCloudflareEnv } from "../environment-variables/misc-variables";
import { UserError } from "../errors";
import { isDirectory } from "../fs-helpers";
import { isRedirectedRawConfig } from "./config-helpers";
import { Diagnostics } from "./diagnostics";
import {
all,
appendEnvName,
deprecated,
experimental,
getBindingNames,
hasProperty,
inheritable,
inheritableInWranglerEnvironments,
isBoolean,
isMutuallyExclusiveWith,
isOneOf,
isOptionalProperty,
isRequiredProperty,
isString,
isStringArray,
isValidDateTimeStringFormat,
isValidName,
notInheritable,
validateAdditionalProperties,
validateAtLeastOnePropertyRequired,
validateOptionalProperty,
validateOptionalTypedArray,
validateRequiredProperty,
validateTypedArray,
validateUniqueNameProperty,
} from "./validation-helpers";
import { configFileName, formatConfigSnippet } from ".";
import type { Binding } from "../types";
import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
import type {
Assets,
CacheOptions,
DispatchNamespaceOutbound,
Environment,
Observability,
RawEnvironment,
Rule,
StreamingTailConsumer,
TailConsumer,
} from "./environment";
import type { TypeofType, ValidatorFn } from "./validation-helpers";
/**
* R2 bucket names must:
* - contain lower case letters, numbers, and `-`
* - start and end with with a lower case letter or number
* - be between 6 and 63 characters long
*
* See https://developers.cloudflare.com/r2/buckets/create-buckets/#bucket-level-operations
*/
export function isValidR2BucketName(name: string | undefined): name is string {
return (
typeof name === "string" && /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(name)
);
}
export const bucketFormatMessage = `Bucket names must begin and end with an alphanumeric character, only contain lowercase letters, numbers, and hyphens, and be between 3 and 63 characters long.`;
/**
* Config field names for bindings (e.g., "kv_namespaces", "d1_databases").
* These are the keys used in Wrangler's config file
*/
export type ConfigBindingFieldName =
| "data_blobs"
| "durable_objects"
| "kv_namespaces"
| "send_email"
| "queues"
| "d1_databases"
| "vectorize"
| "hyperdrive"
| "r2_buckets"
| "logfwdr"
| "services"
| "analytics_engine_datasets"
| "text_blobs"
| "browser"
| "ai"
| "images"
| "media"
| "version_metadata"
| "unsafe"
| "vars"
| "wasm_modules"
| "dispatch_namespaces"
| "mtls_certificates"
| "workflows"
| "pipelines"
| "secrets_store_secrets"
| "ratelimits"
| "assets"
| "unsafe_hello_world"
| "worker_loaders"
| "vpc_services"
| "vpc_networks";
/**
* @deprecated new code should use getBindingTypeFriendlyName() instead
*/
export const friendlyBindingNames: Record<ConfigBindingFieldName, string> = {
data_blobs: "Data Blob",
durable_objects: "Durable Object",
kv_namespaces: "KV Namespace",
send_email: "Send Email",
queues: "Queue",
d1_databases: "D1 Database",
vectorize: "Vectorize Index",
hyperdrive: "Hyperdrive Config",
r2_buckets: "R2 Bucket",
logfwdr: "logfwdr",
services: "Worker",
analytics_engine_datasets: "Analytics Engine Dataset",
text_blobs: "Text Blob",
browser: "Browser",
ai: "AI",
images: "Images",
media: "Media",
version_metadata: "Worker Version Metadata",
unsafe: "Unsafe Metadata",
vars: "Environment Variable",
wasm_modules: "Wasm Module",
dispatch_namespaces: "Dispatch Namespace",
mtls_certificates: "mTLS Certificate",
workflows: "Workflow",
pipelines: "Pipeline",
secrets_store_secrets: "Secrets Store Secret",
ratelimits: "Rate Limit",
assets: "Assets",
unsafe_hello_world: "Hello World",
worker_loaders: "Worker Loader",
vpc_services: "VPC Service",
vpc_networks: "VPC Network",
} as const;
/**
* Friendly names for binding types (keyed by Binding["type"] discriminator).
* These are mostly (but not always) non-plural versions of friendlyBindingNames
*/
const bindingTypeFriendlyNames: Record<Binding["type"], string> = {
// The 3 binding types below are all rendered as "Environment Variable" to preserve existing behaviour (friendlyBindingNames.vars)
plain_text: "Environment Variable",
secret_text: "Environment Variable",
json: "Environment Variable",
kv_namespace: "KV Namespace",
send_email: "Send Email",
wasm_module: "Wasm Module",
text_blob: "Text Blob",
browser: "Browser",
ai: "AI",
images: "Images",
version_metadata: "Worker Version Metadata",
data_blob: "Data Blob",
durable_object_namespace: "Durable Object",
workflow: "Workflow",
queue: "Queue",
r2_bucket: "R2 Bucket",
d1: "D1 Database",
vectorize: "Vectorize Index",
hyperdrive: "Hyperdrive Config",
service: "Worker",
fetcher: "Service Binding",
analytics_engine: "Analytics Engine Dataset",
dispatch_namespace: "Dispatch Namespace",
mtls_certificate: "mTLS Certificate",
pipeline: "Pipeline",
secrets_store_secret: "Secrets Store Secret",
logfwdr: "logfwdr",
unsafe_hello_world: "Hello World",
ratelimit: "Rate Limit",
worker_loader: "Worker Loader",
vpc_service: "VPC Service",
vpc_network: "VPC Network",
media: "Media",
assets: "Assets",
inherit: "Inherited",
} as const;
/**
* Get a friendly name for a binding type, handling unsafe bindings
*/
export function getBindingTypeFriendlyName(
bindingType: Binding["type"]
): string {
if (bindingType in bindingTypeFriendlyNames) {
return bindingTypeFriendlyNames[bindingType];
}
if (bindingType.startsWith("unsafe_")) {
return "Unsafe Metadata";
}
return bindingType;
}
export type NormalizeAndValidateConfigArgs = {
name?: string;
env?: string;
"legacy-env"?: boolean;
// This is not relevant in dev. It's only purpose is loosening Worker name validation when deploying to a dispatch namespace
"dispatch-namespace"?: string;
remote?: boolean;
localProtocol?: string;
upstreamProtocol?: string;
script?: string;
enableContainers?: boolean;
generateTypes?: boolean;
};
const ENGLISH = new Intl.ListFormat("en-US");
const ALLOWED_INSTANCE_TYPES = [
"lite",
"basic",
"standard-1",
"standard-2",
"standard-3",
"standard-4",
"dev", // legacy
"standard", // legacy
];
export function isPagesConfig(rawConfig: RawConfig): boolean {
return rawConfig.pages_build_output_dir !== undefined;
}
/**
* Validate the given `rawConfig` object that was loaded from `configPath`.
*
* The configuration is normalized, which includes using default values for missing field,
* and copying over inheritable fields into named environments.
*
* Any errors or warnings from the validation are available in the returned `diagnostics` object.
*
* @param rawConfig The config loaded from `configPath`
* @param configPath The path to the config file
* @param userConfigPath
* @param args
* @param preserveOriginalMain
* @returns The normalized `config` and `diagnostics` message
*/
export function normalizeAndValidateConfig(
rawConfig: RawConfig,
configPath: string | undefined,
userConfigPath: string | undefined,
args: NormalizeAndValidateConfigArgs,
preserveOriginalMain = false
): {
config: Config;
diagnostics: Diagnostics;
} {
const diagnostics = new Diagnostics(
`Processing ${
configPath ? path.relative(process.cwd(), configPath) : "wrangler"
} configuration:`
);
validateOptionalProperty(
diagnostics,
"",
"legacy_env",
rawConfig.legacy_env,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"send_metrics",
rawConfig.send_metrics,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"keep_vars",
rawConfig.keep_vars,
"boolean"
);
validateOptionalProperty(
diagnostics,
"",
"pages_build_output_dir",
rawConfig.pages_build_output_dir,
"string"
);
// Support explicit JSON schema setting
validateOptionalProperty(
diagnostics,
"",
"$schema",
rawConfig.$schema,
"string"
);
/**
* Legacy env refers to wrangler environments, which are not actually legacy in any way.
* This is opposed to service environments, which are deprecated.
* Unfortunately legacy-env is a public facing arg and config option, so we have to leave the name.
* However we can change the internal handling to be less confusing.
*/
const useServiceEnvironments = !(
args["legacy-env"] ??
rawConfig.legacy_env ??
true
);
if (useServiceEnvironments) {
diagnostics.warnings.push(
"Service environments are deprecated, and will be removed in the future. DO NOT USE IN PRODUCTION."
);
}
const isDispatchNamespace =
typeof args["dispatch-namespace"] === "string" &&
args["dispatch-namespace"].trim() !== "";
const topLevelEnv = normalizeAndValidateEnvironment(
diagnostics,
configPath,
rawConfig,
isDispatchNamespace,
preserveOriginalMain
);
const isRedirectedConfig = isRedirectedRawConfig(
rawConfig,
configPath,
userConfigPath
);
const definedEnvironments = Object.keys(rawConfig.env ?? {});
if (isRedirectedConfig && definedEnvironments.length > 0) {
diagnostics.errors.push(
dedent`
Redirected configurations cannot include environments but the following have been found:\n${definedEnvironments
.map((env) => ` - ${env}`)
.join("\n")}
Such configurations are generated by tools, meaning that one of the tools
your application is using is generating the incorrect configuration.
Report this issue to the tool's author so that this can be fixed there.
`
);
}
// The environment can come from the CLI args (i.e. `--env`) or from the `CLOUDFLARE_ENV` environment variable.
const envName = args.env ?? getCloudflareEnv();
assert(envName === undefined || typeof envName === "string");
let activeEnv = topLevelEnv;
if (envName) {
if (isRedirectedConfig) {
// Check that if we are loading a redirected config, any specified environment must match the target environment
// from the original user config.
// Note: we don't error for pages commands where the environment is always set (to either "preview" or "production")
if (
!isPagesConfig(rawConfig) &&
rawConfig.targetEnvironment &&
rawConfig.targetEnvironment !== envName
) {
const via =
args.env !== undefined
? "via the `--env/-e` CLI argument"
: "via the CLOUDFLARE_ENV environment variable";
// We are throwing here rather than just adding to the diagnostics because this is a hard error
// and we'd like to collect Sentry data on when and how often this is happening.
throw new Error(dedent`
You have specified the environment "${envName}" ${via}.
This does not match the target environment "${rawConfig.targetEnvironment}" that was used when building the application.
Perhaps you need to re-run the custom build of the project with "${envName}" as the selected environment?
`);
}
} else {
const envDiagnostics = new Diagnostics(
`"env.${envName}" environment configuration`
);
const rawEnv = rawConfig.env?.[envName];
/**
* If an environment name was specified, and we found corresponding configuration
* for it in the config file, we will use that corresponding environment. If the
* environment name was specified, but no configuration for it was found, we will:
*
* - default to the top-level environment for Pages. For Pages, Wrangler does not
* require both of supported named environments ("preview" or "production") to be
* explicitly defined in the config file. If either`[env.production]` or
* `[env.preview]` is left unspecified, we will use the top-level environment when
* targeting that named Pages environment.
*
* - create a fake active environment with the specified `envName` for Workers.
* This is done to cover any legacy environment cases, where the `envName` is used.
*/
if (rawEnv !== undefined) {
activeEnv = normalizeAndValidateEnvironment(
envDiagnostics,
configPath,
rawEnv,
isDispatchNamespace,
preserveOriginalMain,
envName,
topLevelEnv,
useServiceEnvironments,
rawConfig
);
diagnostics.addChild(envDiagnostics);
} else if (!isPagesConfig(rawConfig)) {
activeEnv = normalizeAndValidateEnvironment(
envDiagnostics,
configPath,
topLevelEnv, // in this case reuse the topLevelEnv to ensure that nonInherited fields are not removed
isDispatchNamespace,
preserveOriginalMain,
envName,
topLevelEnv,
useServiceEnvironments,
rawConfig
);
const envNames = rawConfig.env
? `The available configured environment names are: ${JSON.stringify(
Object.keys(rawConfig.env)
)}\n`
: "";
const message =
`No environment found in configuration with name "${envName}".\n` +
`Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
`${envNames}\n` +
`Consider adding an environment configuration section to the ${configFileName(configPath)} file:\n` +
"```\n[env." +
envName +
"]\n```\n";
if (envNames.length > 0) {
diagnostics.errors.push(message);
} else {
// Only warn (rather than error) if there are not actually any environments configured in the Wrangler configuration file.
diagnostics.warnings.push(message);
}
}
}
}
// Process the top-level default environment configuration.
const config: Config = {
configPath,
userConfigPath,
topLevelName: isRedirectedConfig ? rawConfig.topLevelName : rawConfig.name,
definedEnvironments: isRedirectedConfig
? rawConfig.definedEnvironments
: definedEnvironments,
targetEnvironment: isRedirectedConfig
? rawConfig.targetEnvironment
: envName,
pages_build_output_dir: normalizeAndValidatePagesBuildOutputDir(
configPath,
rawConfig.pages_build_output_dir
),
/** Legacy_env is wrangler environments, as opposed to service environments. Wrangler environments is not legacy. */
legacy_env: !useServiceEnvironments,
send_metrics: rawConfig.send_metrics,
keep_vars: rawConfig.keep_vars,
...activeEnv,
dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}, args),
site: normalizeAndValidateSite(
diagnostics,
configPath,
rawConfig,
activeEnv.main
),
alias: normalizeAndValidateAliases(diagnostics, configPath, rawConfig),
wasm_modules: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"wasm_modules",
rawConfig.wasm_modules
),
text_blobs: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"text_blobs",
rawConfig.text_blobs
),
data_blobs: normalizeAndValidateModulePaths(
diagnostics,
configPath,
"data_blobs",
rawConfig.data_blobs
),
};
validateBindingsHaveUniqueNames(diagnostics, config);
validateAdditionalProperties(
diagnostics,
"top-level",
Object.keys(rawConfig),
[...Object.keys(config), "env", "$schema"]
);
applyPythonConfig(config, args);
return { config, diagnostics };
}
/**
* Modifies the provided config to support python workers, if the entrypoint is a .py file
*/
function applyPythonConfig(
config: Config,
args: NormalizeAndValidateConfigArgs
) {
const mainModule = args.script ?? config.main;
if (typeof mainModule === "string" && mainModule.endsWith(".py")) {
// Workers with a python entrypoint should have bundling turned off, since all of Wrangler's bundling is JS/TS specific
config.no_bundle = true;
// Workers with a python entrypoint need module rules for "*.py". Add one automatically as a DX nicety
if (!config.rules.some((rule) => rule.type === "PythonModule")) {
config.rules.push({ type: "PythonModule", globs: ["**/*.py"] });
}
if (!config.compatibility_flags.includes("python_workers")) {
throw new UserError(
"The `python_workers` compatibility flag is required to use Python."
);
}
}
}
/**
* Validate the `build` configuration and return the normalized values.
*/
function normalizeAndValidateBuild(
diagnostics: Diagnostics,
rawEnv: RawEnvironment,
rawBuild: Config["build"],
configPath: string | undefined
): Config["build"] {
const { command, cwd, watch_dir = "./src", ...rest } = rawBuild;
validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
validateOptionalProperty(diagnostics, "build", "command", command, "string");
validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
if (Array.isArray(watch_dir)) {
validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
} else {
validateOptionalProperty(
diagnostics,
"build",
"watch_dir",
watch_dir,
"string"
);
}
return {
command,
watch_dir:
// - `watch_dir` only matters when `command` is defined, so we apply
// a default only when `command` is defined
// - `configPath` will always be defined since `build` can only
// be configured in the Wrangler configuration file, but who knows, that may
// change in the future, so we do a check anyway
command && configPath
? Array.isArray(watch_dir)
? watch_dir.map((dir) =>
path.relative(
process.cwd(),
path.join(path.dirname(configPath), `${dir}`)
)
)
: path.relative(
process.cwd(),
path.join(path.dirname(configPath), `${watch_dir}`)
)
: watch_dir,
cwd,
};
}
/**
* Validate the `main` field and return the normalized values.
*/
function normalizeAndValidateMainField(
configPath: string | undefined,
rawMain: string | undefined
): string | undefined {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawMain !== undefined) {
if (typeof rawMain === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawMain);
} else {
return rawMain;
}
} else {
return;
}
}
/**
* Validate the `base_dir` field and return the normalized values.
*/
function normalizeAndValidateBaseDirField(
configPath: string | undefined,
rawDir: string | undefined
): string | undefined {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawDir !== undefined) {
if (typeof rawDir === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawDir);
} else {
return rawDir;
}
} else {
return;
}
}
/**
* Validate the `pages_build_output_dir` field and return the normalized values.
*/
function normalizeAndValidatePagesBuildOutputDir(
configPath: string | undefined,
rawPagesDir: string | undefined
): string | undefined {
const configDir = path.dirname(configPath ?? "wrangler.toml");
if (rawPagesDir !== undefined) {
if (typeof rawPagesDir === "string") {
const directory = path.resolve(configDir);
return path.resolve(directory, rawPagesDir);
} else {
return rawPagesDir;
}
} else {
return;
}
}
/**
* Validate the `dev` configuration and return the normalized values.
*/
function normalizeAndValidateDev(
diagnostics: Diagnostics,
rawDev: RawDevConfig,
args: NormalizeAndValidateConfigArgs
): DevConfig {
assert(typeof args === "object" && args !== null && !Array.isArray(args));
const {
localProtocol: localProtocolArg,
upstreamProtocol: upstreamProtocolArg,
remote: remoteArg,
enableContainers: enableContainersArg,
generateTypes: generateTypesArg,
} = args;
assert(
localProtocolArg === undefined ||
localProtocolArg === "http" ||
localProtocolArg === "https"
);
assert(
upstreamProtocolArg === undefined ||
upstreamProtocolArg === "http" ||
upstreamProtocolArg === "https"
);
assert(remoteArg === undefined || typeof remoteArg === "boolean");
assert(
enableContainersArg === undefined ||
typeof enableContainersArg === "boolean"
);
assert(
generateTypesArg === undefined || typeof generateTypesArg === "boolean"
);
const {
// On Windows, when specifying `localhost` as the socket hostname, `workerd`
// will only listen on the IPv4 loopback `127.0.0.1`, not the IPv6 `::1`:
// https://github.com/cloudflare/workerd/issues/1408
// On Node 17+, `fetch()` will only try to fetch the IPv6 address.
// For now, on Windows, we default to listening on IPv4 only and using
// `127.0.0.1` when sending control requests to `workerd` (e.g. with the
// `ProxyController`).
ip = process.platform === "win32" ? "127.0.0.1" : "localhost",
port,
inspector_port,
inspector_ip,
local_protocol = localProtocolArg ?? "http",
// In remote mode upstream_protocol must be https, otherwise it defaults to local_protocol.
upstream_protocol = upstreamProtocolArg ?? remoteArg
? "https"
: local_protocol,
host,
enable_containers = enableContainersArg ?? true,
container_engine,
generate_types = generateTypesArg ?? false,
...rest
} = rawDev;
validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
validateOptionalProperty(diagnostics, "dev", "port", port, "number");
validateOptionalProperty(
diagnostics,
"dev",
"inspector_port",
inspector_port,
"number"
);
validateOptionalProperty(
diagnostics,
"dev",
"inspector_ip",
inspector_ip,
"string"
);
validateOptionalProperty(
diagnostics,
"dev",
"local_protocol",
local_protocol,
"string",
["http", "https"]
);
validateOptionalProperty(
diagnostics,
"dev",
"upstream_protocol",
upstream_protocol,
"string",
["http", "https"]
);
validateOptionalProperty(diagnostics, "dev", "host", host, "string");
validateOptionalProperty(
diagnostics,
"dev",
"enable_containers",
enable_containers,
"boolean"
);
validateOptionalProperty(
diagnostics,
"dev",
"container_engine",
container_engine,
"string"
);
validateOptionalProperty(
diagnostics,
"dev",
"generate_types",
generate_types,
"boolean"
);
return {
ip,
port,
inspector_port,
inspector_ip,
local_protocol,
upstream_protocol,
host,
enable_containers,
container_engine,
generate_types,
};
}
function normalizeAndValidateAssets(
diagnostics: Diagnostics,
topLevelEnv: Environment | undefined,
rawEnv: RawEnvironment
): Config["assets"] {
return inheritable(
diagnostics,
topLevelEnv,
rawEnv,
"assets",
validateAssetsConfig,
undefined
);
}
/**
* Validate the `site` configuration and return the normalized values.
*/
function normalizeAndValidateSite(
diagnostics: Diagnostics,
configPath: string | undefined,
rawConfig: RawConfig,
mainEntryPoint: string | undefined
): Config["site"] {
if (rawConfig?.site !== undefined) {
const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
"entry-point",
]);
validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
validateTypedArray(diagnostics, "sites.include", include, "string");
validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
validateOptionalProperty(
diagnostics,
"site",
"entry-point",
rawConfig.site["entry-point"],
"string"
);
deprecated(
diagnostics,
rawConfig,
`site.entry-point`,
`Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:\n` +
`\`\`\`\n` +
`main = "${path.join(
String(rawConfig.site["entry-point"]) || "workers-site",
path.extname(String(rawConfig.site["entry-point"]) || "workers-site")
? ""
: "index.js"
)}"\n` +
`\`\`\``,
false,
undefined,
"warning"
);
let siteEntryPoint = rawConfig.site["entry-point"];
if (!mainEntryPoint && !siteEntryPoint) {
// this means that we're defaulting to "workers-site"
// so let's add the deprecation warning
diagnostics.warnings.push(
`Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.\n` +
`Add the top level \`main\` field to your configuration file:\n` +
`\`\`\`\n` +
`main = "workers-site/index.js"\n` +
`\`\`\``
);
siteEntryPoint = "workers-site";
} else if (mainEntryPoint && siteEntryPoint) {
diagnostics.errors.push(
`Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.\n` +
`They serve the same purpose: to point to the entry-point of your worker.\n` +
`Delete the deprecated \`site.entry-point\` field from your config.`
);
}
if (configPath && siteEntryPoint) {
// rewrite the path to be relative to the working directory
siteEntryPoint = path.relative(
process.cwd(),
path.join(path.dirname(configPath), siteEntryPoint)
);
}
return {
bucket,
"entry-point": siteEntryPoint,
include,
exclude,
};
}
return undefined;
}
/**
* Validate the `alias` configuration
*/
function normalizeAndValidateAliases(
diagnostics: Diagnostics,
configPath: string | undefined,
rawConfig: RawConfig
): Config["alias"] {
if (rawConfig?.alias === undefined) {
return undefined;
}
if (
["string", "boolean", "number"].includes(typeof rawConfig?.alias) ||
typeof rawConfig?.alias !== "object"
) {
diagnostics.errors.push(
`Expected alias to be an object, but got ${typeof rawConfig?.alias}`
);
return undefined;
}
let isValid = true;
for (const [key, value] of Object.entries(rawConfig?.alias)) {
if (typeof value !== "string") {
diagnostics.errors.push(
`Expected alias["${key}"] to be a string, but got ${typeof value}`
);
isValid = false;
}
}
if (isValid) {
return rawConfig.alias;
}
return;
}
/**
* Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
*/
function normalizeAndValidateModulePaths(
diagnostics: Diagnostics,
configPath: string | undefined,
field: "wasm_modules" | "text_blobs" | "data_blobs",
rawMapping: Record<string, string> | undefined
): Record<string, string> | undefined {
if (rawMapping === undefined) {
return undefined;
}
const mapping: Record<string, string> = {};
// Rewrite paths to be relative to the cwd, rather than the config path.
for (const [name, filePath] of Object.entries(rawMapping)) {
if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
if (configPath) {
mapping[name] = configPath
? path.relative(
process.cwd(),
path.join(path.dirname(configPath), filePath)
)
: filePath;
}
}
}
return mapping;
}
/**
* Check whether a value has the shape of a route, which can be a string
* or an object that looks like {pattern: string, zone_id: string }
*/
function isValidRouteValue(item: unknown): boolean {
if (!item) {
return false;
}
if (typeof item === "string") {
return true;
}
if (typeof item === "object") {
if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
return false;
}
const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
const hasZoneId =
hasProperty(item, "zone_id") && typeof item.zone_id === "string";
const hasZoneName =
hasProperty(item, "zone_name") && typeof item.zone_name === "string";
const hasCustomDomainFlag =
hasProperty(item, "custom_domain") &&
typeof item.custom_domain === "boolean";
if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
return true;
} else if (
otherKeys === 1 &&
(hasZoneId || hasZoneName || hasCustomDomainFlag)
) {
return true;
}
}
return false;
}
/**
* If account_id has been passed as an empty string, normalise it to undefined.
* This is to workaround older Wrangler v1-era templates that have account_id = '',
* which isn't a valid value anyway
*/
function mutateEmptyStringAccountIDValue(
diagnostics: Diagnostics,
rawEnv: RawEnvironment
) {
if (rawEnv.account_id === "") {
diagnostics.warnings.push(
`The "account_id" field in your configuration is an empty string and will be ignored.\n` +