-
Notifications
You must be signed in to change notification settings - Fork 758
/
Copy pathdev.ts
1294 lines (1177 loc) · 39.6 KB
/
dev.ts
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 { execSync, spawn } from "node:child_process";
import { existsSync, lstatSync, readFileSync } from "node:fs";
import { dirname, join, normalize, resolve } from "node:path";
import { watch } from "chokidar";
import * as esbuild from "esbuild";
import { unstable_dev } from "../api";
import { configFileName, readConfig } from "../config";
import { isBuildFailure } from "../deployment-bundle/build-failures";
import { shouldCheckFetch } from "../deployment-bundle/bundle";
import { esbuildAliasExternalPlugin } from "../deployment-bundle/esbuild-plugins/alias-external";
import { validateNodeCompatMode } from "../deployment-bundle/node-compat";
import { FatalError } from "../errors";
import { logger } from "../logger";
import * as metrics from "../metrics";
import { isNavigatorDefined } from "../navigator-user-agent";
import { getBasePath } from "../paths";
import * as shellquote from "../utils/shell-quote";
import { printWranglerBanner } from "../wrangler-banner";
import { buildFunctions } from "./buildFunctions";
import { ROUTES_SPEC_VERSION, SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
import { FunctionsNoRoutesError, getFunctionsNoRoutesWarning } from "./errors";
import {
buildRawWorker,
checkRawWorker,
produceWorkerBundleForWorkerJSDirectory,
} from "./functions/buildWorker";
import { validateRoutes } from "./functions/routes-validation";
import { CLEANUP, CLEANUP_CALLBACKS, debounce, getPagesTmpDir } from "./utils";
import type { Config } from "../config";
import type {
DurableObjectBindings,
EnvironmentNonInheritable,
} from "../config/environment";
import type { CfModule } from "../deployment-bundle/worker";
import type { AdditionalDevProps } from "../dev";
import type {
CommonYargsArgv,
StrictYargsOptionsToInterface,
} from "../yargs-types";
import type { RoutesJSONSpec } from "./functions/routes-transformation";
/*
* DURABLE_OBJECTS_BINDING_REGEXP matches strings like:
* - "binding=className"
* - "BINDING=MyClass"
* - "BINDING=MyClass@service-name"
* Every DO needs a binding (the JS reference) and the exported class name it refers to.
* Optionally, users can also provide a service name if they want to reference a DO from another dev session over the dev registry.
*/
const DURABLE_OBJECTS_BINDING_REGEXP = new RegExp(
/^(?<binding>[^=]+)=(?<className>[^@\s]+)(@(?<scriptName>.*)$)?$/
);
/* BINDING_REGEXP matches strings like:
* - "binding"
* - "BINDING"
* - "BINDING=ref"
* This is used to capture both the binding name (how the binding is used in JS) as well as the reference if provided.
* In the case of a D1 database, that's the database ID.
* This is useful to people who want to reference the same database in multiple bindings, or a Worker and Pages project dev session want to reference the same database.
*/
const BINDING_REGEXP = new RegExp(/^(?<binding>[^=]+)(?:=(?<ref>[^\s]+))?$/);
/* SERVICE_BINDING_REGEXP matches strings like:
* - "binding=service"
* - "binding=service@environment"
* - "binding=service#entrypoint"
* This is used to capture both the binding name (how the binding is used in JS) alongside the name of the service it needs to bind to.
* Additionally it can also accept an environment which indicates what environment the service has to be running for.
* Additionally it can also accept an entrypoint which indicates what named entrypoint of the service to use, if not the default.
*/
const SERVICE_BINDING_REGEXP = new RegExp(
/^(?<binding>[^=]+)=(?<service>[^@#\s]+)(@(?<environment>.*)$)?(#(?<entrypoint>.*))?$/
);
const DEFAULT_IP = process.platform === "win32" ? "127.0.0.1" : "localhost";
const DEFAULT_PAGES_LOCAL_PORT = 8788;
const DEFAULT_SCRIPT_PATH = "_worker.js";
export function Options(yargs: CommonYargsArgv) {
return yargs
.positional("directory", {
type: "string",
demandOption: undefined,
description: "The directory of static assets to serve",
})
.positional("command", {
type: "string",
demandOption: undefined,
description: "The proxy command to run [deprecated]", // no official way to deprecate a positional argument
})
.options({
local: {
type: "boolean",
default: true,
description: "Run on my machine",
deprecated: true,
hidden: true,
},
"compatibility-date": {
describe: "Date to use for compatibility checks",
type: "string",
},
"compatibility-flags": {
describe: "Flags to use for compatibility checks",
alias: "compatibility-flag",
type: "string",
array: true,
},
ip: {
type: "string",
// 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`).
description: "The IP address to listen on",
},
port: {
type: "number",
description: "The port to listen on (serve from)",
},
"inspector-port": {
type: "number",
describe: "Port for devtools to connect to",
},
proxy: {
type: "number",
description: "The port to proxy (where the static assets are served)",
deprecated: true,
},
"script-path": {
type: "string",
description:
"The location of the single Worker script if not using functions [default: _worker.js]",
// hacking in a fake default message here so we can detect when user is setting this and show a deprecation message
deprecated: true,
},
bundle: {
type: "boolean",
default: undefined,
hidden: true,
},
"no-bundle": {
type: "boolean",
default: false,
description: "Whether to run bundling on `_worker.js`",
},
binding: {
type: "array",
description: "Bind variable/secret (KEY=VALUE)",
alias: "b",
},
kv: {
type: "array",
description: "KV namespace to bind (--kv KV_BINDING)",
alias: "k",
},
d1: {
type: "array",
description: "D1 database to bind (--d1 D1_BINDING)",
},
do: {
type: "array",
description:
"Durable Object to bind (--do DO_BINDING=CLASS_NAME@SCRIPT_NAME)",
alias: "o",
},
r2: {
type: "array",
description: "R2 bucket to bind (--r2 R2_BINDING)",
},
ai: {
type: "string",
description: "AI to bind (--ai AI_BINDING)",
},
"version-metadata": {
type: "string",
description:
"Worker Version metadata (--version-metadata VERSION_METADATA_BINDING)",
},
service: {
type: "array",
description: "Service to bind (--service SERVICE=SCRIPT_NAME)",
alia: "s",
},
"live-reload": {
type: "boolean",
default: false,
description: "Auto reload HTML pages when change is detected",
},
"local-protocol": {
describe: "Protocol to listen to requests on, defaults to http.",
choices: ["http", "https"] as const,
},
"https-key-path": {
describe: "Path to a custom certificate key",
type: "string",
requiresArg: true,
},
"https-cert-path": {
describe: "Path to a custom certificate",
type: "string",
requiresArg: true,
},
"persist-to": {
describe:
"Specify directory to use for local persistence (defaults to .wrangler/state)",
type: "string",
requiresArg: true,
},
"node-compat": {
describe: "Enable Node.js compatibility",
default: false,
type: "boolean",
hidden: true,
},
"experimental-local": {
describe: "Run on my machine using the Cloudflare Workers runtime",
type: "boolean",
deprecated: true,
hidden: true,
},
config: {
describe:
"Pages does not support custom paths for the Wrangler configuration file",
type: "string",
hidden: true,
},
"log-level": {
choices: ["debug", "info", "log", "warn", "error", "none"] as const,
describe: "Specify logging level",
},
"show-interactive-dev-session": {
describe:
"Show interactive dev session (defaults to true if the terminal supports interactivity)",
type: "boolean",
},
"experimental-vectorize-bind-to-prod": {
type: "boolean",
describe:
"Bind to production Vectorize indexes in local development mode",
default: false,
},
});
}
type PagesDevArguments = StrictYargsOptionsToInterface<typeof Options>;
export const Handler = async (args: PagesDevArguments) => {
if (args.logLevel) {
logger.loggerLevel = args.logLevel;
}
await printWranglerBanner();
if (args.experimentalLocal) {
logger.warn(
"--experimental-local is no longer required and will be removed in a future version.\n`wrangler pages dev` now uses the local Cloudflare Workers runtime by default."
);
}
if (args.config) {
throw new FatalError(
"Pages does not support custom paths for the Wrangler configuration file",
1
);
}
if (args.env) {
throw new FatalError(
"Pages does not support targeting an environment with the --env flag. Use the --branch flag to target your production or preview branch",
1
);
}
if (args.scriptPath !== undefined) {
logger.warn(
`\`--script-path\` is deprecated and will be removed in a future version of Wrangler.\nThe Worker script should be named \`_worker.js\` and located in the build output directory of your project (specified with \`wrangler pages dev <directory>\`).`
);
}
// for `dev` we always use the top-level config, which means we need
// to read the config file with `env` set to `undefined`
const config = readConfig(
{ ...args, env: undefined },
{ useRedirectIfAvailable: true }
);
const resolvedDirectory = args.directory ?? config.pages_build_output_dir;
const [_pages, _dev, ...remaining] = args._;
const command = remaining;
let proxyPort: number | undefined;
let directory = resolvedDirectory;
if (directory !== undefined && command.length > 0) {
throw new FatalError(
"Specify either a directory OR a proxy command, not both.",
1
);
} else if (directory === undefined) {
proxyPort = await spawnProxyProcess({
port: args.proxy,
command,
});
if (proxyPort === undefined) {
return undefined;
}
} else {
directory = resolve(directory);
}
const {
compatibilityDate,
compatibilityFlags,
ip,
port,
inspectorPort,
localProtocol,
} = resolvePagesDevServerSettings(config, args);
const {
vars,
kv_namespaces,
do_bindings,
d1_databases,
r2_buckets,
services,
ai,
} = getBindingsFromArgs(args);
let scriptReadyResolve: () => void;
const scriptReadyPromise = new Promise<void>(
(promiseResolve) => (scriptReadyResolve = promiseResolve)
);
const singleWorkerScriptPath = args.scriptPath ?? DEFAULT_SCRIPT_PATH;
const workerScriptPath =
directory !== undefined
? join(directory, singleWorkerScriptPath)
: resolve(singleWorkerScriptPath);
const usingWorkerDirectory =
existsSync(workerScriptPath) && lstatSync(workerScriptPath).isDirectory();
const usingWorkerScript = existsSync(workerScriptPath);
// TODO: Here lies a known bug. If you specify both `--bundle` and `--no-bundle`, this behavior is undefined and you will get unexpected results.
// There is no sane way to get the true value out of yargs, so here we are.
const enableBundling = args.bundle ?? !args.noBundle;
const functionsDirectory = "./functions";
let usingFunctions = !usingWorkerScript && existsSync(functionsDirectory);
let scriptPath = "";
const nodejsCompatMode = validateNodeCompatMode(
args.compatibilityDate ?? config.compatibility_date,
args.compatibilityFlags ?? config.compatibility_flags ?? [],
{
nodeCompat: args.nodeCompat,
noBundle: args.noBundle ?? config.no_bundle,
}
);
const defineNavigatorUserAgent = isNavigatorDefined(
compatibilityDate,
compatibilityFlags
);
const checkFetch = shouldCheckFetch(compatibilityDate, compatibilityFlags);
let modules: CfModule[] = [];
if (usingWorkerDirectory) {
const runBuild = async () => {
const bundleResult = await produceWorkerBundleForWorkerJSDirectory({
workerJSDirectory: workerScriptPath,
bundle: enableBundling,
buildOutputDirectory: directory ?? ".",
nodejsCompatMode,
defineNavigatorUserAgent,
checkFetch,
sourceMaps: config?.upload_source_maps ?? false,
});
modules = bundleResult.modules;
scriptPath = bundleResult.resolvedEntryPointPath;
};
await runBuild().then(() => scriptReadyResolve());
watch([workerScriptPath], {
persistent: true,
ignoreInitial: true,
}).on("all", async () => {
try {
await runBuild();
} catch (e) {
if (isBuildFailure(e)) {
logger.warn("Error building worker script:", e.message);
return;
}
throw e;
}
});
} else if (usingWorkerScript) {
/*
* Delegate watching for file changes to chokidar entirely. This gives
* us a bit more flexibility and control as opposed to esbuild watch
* mode, and keeps things consistent with the Functions implementation
*/
// always watch _worker.js
const watcher = watch([workerScriptPath], {
persistent: true,
ignoreInitial: true,
});
let watchedBundleDependencies: string[] = [];
scriptPath = workerScriptPath;
let runBuild = async () => {
await checkRawWorker(workerScriptPath, nodejsCompatMode, () =>
scriptReadyResolve()
);
};
if (enableBundling) {
// We want to actually run the `_worker.js` script through the bundler
// So update the final path to the script that will be uploaded and
// change the `runBuild()` function to bundle the `_worker.js`.
scriptPath = join(
getPagesTmpDir(),
`./bundledWorker-${Math.random()}.mjs`
);
runBuild = async () => {
const workerScriptDirectory = dirname(workerScriptPath);
let currentBundleDependencies: string[] = [];
const bundle = await buildRawWorker({
workerScriptPath: usingWorkerDirectory
? join(workerScriptPath, "index.js")
: workerScriptPath,
outfile: scriptPath,
directory: directory ?? ".",
nodejsCompatMode,
local: true,
sourcemap: true,
watch: false,
onEnd: () => scriptReadyResolve(),
defineNavigatorUserAgent,
checkFetch,
});
/*
* EXCLUDE:
* - "_worker.js" because we're already watching it
* - everything in "./.wrangler", as it's mostly cache and
* temporary files
* - anything outside of the current working directory, since we
* are expecting `wrangler pages dev` to be run from the Pages
* project root folder
*/
const bundleDependencies = Object.keys(bundle.dependencies)
.map((dep) => resolve(workerScriptDirectory, dep))
.filter(
(resolvedDep) =>
!resolvedDep.includes(normalize(singleWorkerScriptPath)) &&
!resolvedDep.includes(normalize("/.wrangler/")) &&
resolvedDep.includes(resolve(process.cwd()))
);
// handle non-JS module dependencies, such as wasm/html/binary imports
const bundleModules = bundle.modules
.filter((module) => !!module.filePath)
.map((module) =>
resolve(workerScriptDirectory, module.filePath as string)
);
/*
*`bundle.dependencies` and `bundle.modules` combined, will always
* provide us with the most up-to-date list of dependencies we need
* to watch, since they reflect the latest built Worker bundle.
* Therefore, we can safely unwatch all dependencies we have been
* watching so far, and add all the new ones.
*/
currentBundleDependencies = [...bundleDependencies, ...bundleModules];
if (watchedBundleDependencies.length) {
watcher.unwatch(watchedBundleDependencies);
}
watcher.add(currentBundleDependencies);
watchedBundleDependencies = [...currentBundleDependencies];
};
}
/*
* Improve developer experience by debouncing the re-building
* of the Worker script, in case file changes are trigerred
* at a high rate (for example if code editor runs auto-saves
* at very short intervals)
*
* "Debouncing ensures that exactly one signal is sent for an
* event that may be happening several times — or even several
* hundreds of times over an extended period. As long as the
* events are occurring fast enough to happen at least once in
* every detection period, the signal will not be sent!"
* (http://unscriptable.com/2009/03/20/debouncing-javascript-methods/)
*/
const debouncedRunBuild = debounce(async () => {
try {
await runBuild();
} catch (e) {
/*
* don't break developer flow in watch mode by throwing an error
* here. Many times errors will be just the result of unfinished
* typing. Instead, log the error, point out we are still serving
* the last successfully built Worker, and allow developers to
* write their code to completion
*/
logger.warn(
`Failed to build ${singleWorkerScriptPath}. Continuing to serve the last successfully built version of the Worker.`
);
}
}, 50);
try {
await runBuild();
watcher.on("all", async (eventName, path) => {
logger.debug(`🌀 "${eventName}" event detected at ${path}.`);
// Skip re-building the Worker if "_worker.js" was deleted.
// This is necessary for Pages projects + Frameworks, where
// the file was potentially deleted as part of a build process,
// which will add the updated file back.
// see https://github.com/cloudflare/workers-sdk/issues/3886
if (eventName === "unlink") {
return;
}
debouncedRunBuild();
});
} catch (e: unknown) {
/*
* fail early if we encounter errors while attempting to build the
* Worker. These flag underlying issues in the _worker.js code, and
* should be addressed before starting the dev process
*/
throw new FatalError(`Failed to build ${singleWorkerScriptPath}.`);
}
} else if (usingFunctions) {
// Try to use Functions
scriptPath = join(
getPagesTmpDir(),
`./functionsWorker-${Math.random()}.mjs`
);
const routesModule = join(
getPagesTmpDir(),
`./functionsRoutes-${Math.random()}.mjs`
);
logger.debug(`Compiling worker to "${scriptPath}"...`);
const onEnd = () => scriptReadyResolve();
/*
* Pages Functions projects cannot rely on esbuild's watch mode alone.
* That's because the watch mode that's built into esbuild is designed
* specifically for only triggering a rebuild when esbuild's build inputs
* are changed (see https://github.com/evanw/esbuild/issues/3705). With
* Functions, we would actually want to trigger a rebuild every time a new
* file is added to the "/functions" directory.
*
* One solution would be to use an esbuild plugin, and "teach" esbuild to
* watch the "/functions" directory. But it's more complicated than that.
* When we build Functions, one of the steps is to generate the routes
* based on the file tree (see `generateConfigFileFromTree`). These routes
* are then injected into the esbuild entrypoint (see
* `templates/pages-template-worker.ts`). Delegating the "/functions" dir
* watching to an esbuild plugin, would mean delegating the routes generation
* to that plugin as well. This gets very hairy very quickly.
*
* Another solution, is to use a combination of dependencies watching, via
* esbuild, and file system watching, via chokidar. The downside of this
* approach is that a lot of syncing between the two watch modes must be put
* in place, in order to avoid triggering building Functions multiple times
* over one single change (like for example renaming file that's part of the
* dependency graph)
*
* Another solution, which is the one we opted for here, is to delegate file
* watching entirely to a file system watcher, chokidar in this case. While
* not entirely downside-free
* - we still rely on esbuild to provide us with the dependency graph
* - we need some logic in place to pre-process and filter the dependencies
* we pass to chokidar
* - we need to keep track of which dependencies are being watched
* this solution keeps all things watch mode in one place, makes things easier
* to read, reason about and maintain, separates Pages <-> esbuild concerns
* better, and gives all the flexibility we needed.
*/
// always watch the "/functions" directory
const watcher = watch([functionsDirectory], {
persistent: true,
ignoreInitial: true,
});
let watchedBundleDependencies: string[] = [];
const buildFn = async () => {
let currentBundleDependencies: string[] = [];
const bundle = await buildFunctions({
outfile: scriptPath,
functionsDirectory,
sourcemap: true,
watch: false,
onEnd,
buildOutputDirectory: directory,
nodejsCompatMode,
local: true,
routesModule,
defineNavigatorUserAgent,
checkFetch,
});
/*
* EXCLUDE:
* - the "/functions" directory because we're already watching it
* - everything in "./.wrangler", as it's mostly cache and
* temporary files
* - any bundle dependencies we are already watching
* - anything outside of the current working directory, since we
* are expecting `wrangler pages dev` to be run from the Pages
* project root folder
*/
const bundleDependencies = Object.keys(bundle.dependencies)
.map((dep) => resolve(functionsDirectory, dep))
.filter(
(resolvedDep) =>
!resolvedDep.includes(normalize("/functions/")) &&
!resolvedDep.includes(normalize("/.wrangler/")) &&
resolvedDep.includes(resolve(process.cwd()))
);
// handle non-JS module dependencies, such as wasm/html/binary imports
const bundleModules = bundle.modules
.filter((module) => !!module.filePath)
.map((module) =>
resolve(functionsDirectory, module.filePath as string)
);
/*
*`bundle.dependencies` and `bundle.modules` will always contain the
* latest dependency list of the current bundle. If we are currently
* watching any dependency files not in that list, we should remove
* them, as they are no longer relevant to the compiled Functions.
*/
currentBundleDependencies = [...bundleDependencies, ...bundleModules];
if (watchedBundleDependencies.length) {
watcher.unwatch(watchedBundleDependencies);
}
watcher.add(currentBundleDependencies);
watchedBundleDependencies = [...currentBundleDependencies];
metrics.sendMetricsEvent("build pages functions");
};
/*
* Improve developer experience by debouncing the re-building
* of Functions.
*
* "Debouncing ensures that exactly one signal is sent for an
* event that may be happening several times — or even several
* hundreds of times over an extended period. As long as the
* events are occurring fast enough to happen at least once in
* every detection period, the signal will not be sent!"
* (http://unscriptable.com/2009/03/20/debouncing-javascript-methods/)
*
* This handles use cases such as bulk file/directory changes
* (such as copy/pasting multiple files/directories), where
* chokidar will trigger a change event per each changed file/
* directory. In such use cases, we want to ensure that we
* re-build Functions once, as opposed to once per change event.
*/
const debouncedBuildFn = debounce(async () => {
try {
await buildFn();
} catch (e) {
if (e instanceof FunctionsNoRoutesError) {
logger.warn(
`${getFunctionsNoRoutesWarning(functionsDirectory)}. Continuing to serve the last successfully built version of Functions.`
);
} else {
/*
* don't break developer flow in watch mode by throwing an error
* here. Many times errors will be just the result of unfinished
* typing. Instead, log the error, point out we are still serving
* the last successfully built Functions, and allow developers to
* write their code to completion
*/
logger.warn(
`Failed to build Functions at ${functionsDirectory}. Continuing to serve the last successfully built version of Functions.`
);
}
}
}, 50);
try {
await buildFn();
// If Functions found routes, continue using Functions
watcher.on("all", async (eventName, path) => {
logger.debug(`🌀 "${eventName}" event detected at ${path}.`);
debouncedBuildFn();
});
} catch (e: unknown) {
// If there are no Functions, then Pages will only serve assets.
if (e instanceof FunctionsNoRoutesError) {
logger.error(
getFunctionsNoRoutesWarning(functionsDirectory, "skipping")
);
// Resolve anyway and run without Functions
onEnd();
usingFunctions = false;
} else {
/*
* do not start the `pages dev` session if we encounter errors
* while attempting to build Functions. These flag underlying
* issues in the Functions code, and should be addressed before
*/
throw new FatalError(
`Failed to build Functions at ${functionsDirectory}.`
);
}
}
}
// Depending on the result of building Functions, we may not actually be using
// Functions even if the directory exists.
if (!usingFunctions && !usingWorkerScript) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
scriptReadyResolve!();
logger.log("No Functions. Shimming...");
scriptPath = resolve(getBasePath(), "templates/pages-shim.ts");
}
await scriptReadyPromise;
if (scriptPath === "") {
// Failed to get a script with or without Functions,
// something really bad must have happened.
throw new Error(
"Failed to start wrangler pages dev due to an unknown error"
);
}
let scriptEntrypoint = scriptPath;
// custom _routes.json apply only to Functions or Advanced Mode Pages projects
if (
directory &&
(usingFunctions || usingWorkerScript || usingWorkerDirectory)
) {
const routesJSONPath = join(directory, "_routes.json");
if (existsSync(routesJSONPath)) {
let routesJSONContents: string;
const runBuild = async (
entrypointFile: string,
outfile: string,
routes: string
) => {
await esbuild.build({
entryPoints: [
resolve(getBasePath(), "templates/pages-dev-pipeline.ts"),
],
bundle: true,
sourcemap: true,
format: "esm",
plugins: [
esbuildAliasExternalPlugin({
__ENTRY_POINT__: entrypointFile,
"./pages-dev-util": resolve(
getBasePath(),
"templates/pages-dev-util.ts"
),
}),
],
outfile,
define: {
__ROUTES__: routes,
},
});
};
try {
// always run the routes validation first. If _routes.json is invalid we
// want to throw accordingly and exit.
routesJSONContents = readFileSync(routesJSONPath, "utf-8");
validateRoutes(JSON.parse(routesJSONContents), directory);
scriptEntrypoint = join(
getPagesTmpDir(),
`${Math.random().toString(36).slice(2)}.js`
);
await runBuild(scriptPath, scriptEntrypoint, routesJSONContents);
} catch (err) {
if (err instanceof FatalError) {
throw err;
} else {
throw new FatalError(
`Could not validate _routes.json at ${directory}: ${err}`,
1
);
}
}
watch([routesJSONPath], {
persistent: true,
ignoreInitial: true,
}).on("all", async (event) => {
try {
if (event === "unlink") {
return;
}
/**
* Watch for _routes.json file changes and validate file each time.
* If file is valid proceed to running the build.
*/
routesJSONContents = readFileSync(routesJSONPath, "utf-8");
validateRoutes(JSON.parse(routesJSONContents), directory as string);
await runBuild(scriptPath, scriptEntrypoint, routesJSONContents);
} catch (err) {
/**
* If _routes.json is invalid, don't exit but instead fallback to a sensible default
* and continue to serve the assets. At the same time make sure we warn users that we
* we detected an invalid file and that we'll be using a default.
* This basically equates to serving a Functions or _worker.js project as is,
* without applying any additional routing rules on top.
*/
const error =
err instanceof FatalError
? err
: `Could not validate _routes.json at ${directory}: ${err}`;
const defaultRoutesJSONSpec: RoutesJSONSpec = {
version: ROUTES_SPEC_VERSION,
include: ["/*"],
exclude: [],
};
logger.error(error);
logger.warn(
`Ignoring provided _routes.json file, and falling back to the following default routes configuration:\n` +
`${JSON.stringify(defaultRoutesJSONSpec, null, 2)}`
);
routesJSONContents = JSON.stringify(defaultRoutesJSONSpec);
await runBuild(scriptPath, scriptEntrypoint, routesJSONContents);
}
});
}
}
const { stop, waitUntilExit } = await unstable_dev(scriptEntrypoint, {
env: undefined,
ip,
port,
inspectorPort,
localProtocol,
httpsKeyPath: args.httpsKeyPath,
httpsCertPath: args.httpsCertPath,
compatibilityDate,
compatibilityFlags,
nodeCompat: nodejsCompatMode === "legacy",
vars,
kv: kv_namespaces,
durableObjects: do_bindings,
r2: r2_buckets,
services,
ai,
rules: usingWorkerDirectory
? [
{
type: "ESModule",
globs: ["**/*.js", "**/*.mjs"],
},
]
: undefined,
bundle: enableBundling,
persistTo: args.persistTo,
inspect: undefined,
logLevel: args.logLevel,
experimental: {
processEntrypoint: true,
additionalModules: modules,
d1Databases: d1_databases,
disableExperimentalWarning: true,
enablePagesAssetsServiceBinding: {
proxyPort,
directory,
},
liveReload: args.liveReload,
forceLocal: true,
showInteractiveDevSession: args.showInteractiveDevSession,
testMode: false,
watch: true,
enableIpc: true,
},
});
metrics.sendMetricsEvent("run pages dev");
CLEANUP_CALLBACKS.push(stop);
process.on("exit", CLEANUP);
process.on("SIGINT", CLEANUP);
process.on("SIGTERM", CLEANUP);
await waitUntilExit();
CLEANUP();
process.exit(0);
};
function isWindows() {
return process.platform === "win32";
}
async function sleep(ms: number) {
await new Promise((promiseResolve) => setTimeout(promiseResolve, ms));
}
function getPids(pid: number) {
const pids: number[] = [pid];
let command: string, regExp: RegExp;
if (isWindows()) {
command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
regExp = new RegExp(/(\d+)/);
} else {
command = `pgrep -P ${pid}`;
regExp = new RegExp(/(\d+)/);
}
try {
const newPids = (
execSync(command)
.toString()
.split("\n")
.map((line) => line.match(regExp))
.filter((line) => line !== null) as RegExpExecArray[]
).map((match) => parseInt(match[1]));
pids.push(...newPids.map(getPids).flat());
} catch {}
return pids;
}
function getPort(pid: number) {
let command: string, regExp: RegExp;
if (isWindows()) {
command = process.env.SYSTEMROOT + "\\system32\\netstat.exe -nao";
regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
} else {
command = "lsof -nPi";
regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
}
try {
const matches = execSync(command)
.toString()
.split("\n")
.map((line) => line.match(regExp))
.filter((line) => line !== null) as RegExpExecArray[];
const match = matches[0];
if (match) {
return parseInt(match[1]);
}
} catch (thrown) {
logger.error(
`Error scanning for ports of process with PID ${pid}: ${thrown}`
);
}
}
async function spawnProxyProcess({
port,
command,
}: {
port?: number;
command: (string | number)[];
}): Promise<undefined | number> {
if (command.length > 0 || port !== undefined) {
logger.warn(
`Specifying a \`-- <command>\` or \`--proxy\` is deprecated and will be removed in a future version of Wrangler.\nBuild your application to a directory and run the \`wrangler pages dev <directory>\` instead.\nThis results in a more faithful emulation of production behavior.`
);
}
if (port !== undefined) {