-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindex.ts
More file actions
2859 lines (2609 loc) · 93.7 KB
/
index.ts
File metadata and controls
2859 lines (2609 loc) · 93.7 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 crypto from "node:crypto";
import { Abortable } from "node:events";
import fs from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import http from "node:http";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { Duplex, Transform, Writable } from "node:stream";
import { ReadableStream } from "node:stream/web";
import util from "node:util";
import zlib from "node:zlib";
import { checkMacOSVersion } from "@cloudflare/cli";
import { removeDir, removeDirSync } from "@cloudflare/workers-utils";
import exitHook from "exit-hook";
import { $ as colors$, green } from "kleur/colors";
import stoppable from "stoppable";
import {
Dispatcher,
getGlobalDispatcher,
Pool,
Response as UndiciResponse,
} from "undici";
import SCRIPT_MINIFLARE_SHARED from "worker:shared/index";
import SCRIPT_MINIFLARE_ZOD from "worker:shared/zod";
import { WebSocketServer } from "ws";
import { z } from "zod";
import { fallbackCf, setupCf } from "./cf";
import {
coupleWebSocket,
DispatchFetch,
DispatchFetchDispatcher,
fetch,
getAccessibleHosts,
getEntrySocketHttpOptions,
Headers,
Request,
RequestInit,
Response,
} from "./http";
import {
BROWSER_RENDERING_PLUGIN_NAME,
D1_PLUGIN_NAME,
DURABLE_OBJECTS_PLUGIN_NAME,
DurableObjectClassNames,
getDirectSocketName,
getGlobalServices,
getPersistPath,
HELLO_WORLD_PLUGIN_NAME,
HOST_CAPNP_CONNECT,
IMAGES_PLUGIN_NAME,
KV_PLUGIN_NAME,
launchBrowser,
loadExternalPlugins,
normaliseDurableObject,
Plugin,
PLUGIN_ENTRIES,
Plugins,
PluginServicesOptions,
ProxyClient,
ProxyNodeBinding,
QueueConsumers,
QueueProducers,
QUEUES_PLUGIN_NAME,
QueuesError,
R2_PLUGIN_NAME,
ReplaceWorkersTypes,
SECRET_STORE_PLUGIN_NAME,
SERVICE_ENTRY,
SharedOptions,
SOCKET_ENTRY,
SOCKET_ENTRY_LOCAL,
WorkerOptions,
WrappedBindingNames,
} from "./plugins";
import { RPC_PROXY_SERVICE_NAME } from "./plugins/assets/constants";
import {
CUSTOM_SERVICE_KNOWN_OUTBOUND,
CustomServiceKind,
getUserServiceName,
handlePrettyErrorRequest,
JsonErrorSchema,
maybeWrappedModuleToWorkerName,
NameSourceOptions,
reviveError,
ServiceDesignatorSchema,
} from "./plugins/core";
import { InspectorProxyController } from "./plugins/core/inspector-proxy";
import { HyperdriveProxyController } from "./plugins/hyperdrive/hyperdrive-proxy";
import { imagesLocalFetcher } from "./plugins/images/fetcher";
import {
Config,
Extension,
HttpOptions_Style,
kInspectorSocket,
Runtime,
RuntimeOptions,
serializeConfig,
Service,
Socket,
SocketIdentifier,
SocketPorts,
Worker_Binding,
Worker_Module,
} from "./runtime";
import {
_isCyclic,
isFileNotFoundError,
Log,
MiniflareCoreError,
NoOpLog,
OptionalZodTypeOf,
parseWithRootPath,
stripAnsi,
} from "./shared";
import { DevRegistry, getWorkerRegistry } from "./shared/dev-registry";
import {
createInboundDoProxyService,
createOutboundDoProxyService,
createProxyFallbackService,
getHttpProxyOptions,
getOutboundDoProxyClassName,
getProtocol,
getProxyFallbackServiceSocketName,
INBOUND_DO_PROXY_SERVICE_NAME,
INBOUND_DO_PROXY_SERVICE_PATH,
normaliseServiceDesignator,
OUTBOUND_DO_PROXY_SERVICE_NAME,
} from "./shared/external-service";
import { isCompressedByCloudflareFL } from "./shared/mime-types";
import {
CacheHeaders,
CoreBindings,
CoreHeaders,
LogLevel,
Mutex,
SharedHeaders,
SiteBindings,
} from "./workers";
import { ADMIN_API } from "./workers/secrets-store/constants";
import { formatZodError } from "./zod-format";
import type { WorkerDefinition } from "./shared/dev-registry-types";
import type {
CacheStorage,
D1Database,
DurableObjectNamespace,
Fetcher,
ImagesBinding,
KVNamespace,
KVNamespaceListKey,
Queue,
R2Bucket,
} from "@cloudflare/workers-types/experimental";
import type { Process } from "@puppeteer/browsers";
const DEFAULT_HOST = "127.0.0.1";
function getURLSafeHost(host: string) {
return net.isIPv6(host) ? `[${host}]` : host;
}
function maybeGetLocallyAccessibleHost(
h: string
): "localhost" | "127.0.0.1" | "[::1]" | undefined {
if (h === "localhost") return "localhost";
if (h === "127.0.0.1" || h === "*" || h === "0.0.0.0" || h === "::") {
return "127.0.0.1";
}
if (h === "::1") return "[::1]";
}
function getServerPort(server: http.Server) {
const address = server.address();
// Note address would be string with unix socket
assert(address !== null && typeof address === "object");
return address.port;
}
// ===== `Miniflare` User Options =====
export type MiniflareOptions = SharedOptions &
(WorkerOptions | { workers: WorkerOptions[] });
// ===== `Miniflare` Validated Options =====
type PluginWorkerOptions = {
[Key in keyof Plugins]: z.infer<Plugins[Key]["options"]>;
};
type PluginSharedOptions = {
[Key in keyof Plugins]: OptionalZodTypeOf<Plugins[Key]["sharedOptions"]>;
};
function hasMultipleWorkers(opts: unknown): opts is { workers: unknown[] } {
return (
typeof opts === "object" &&
opts !== null &&
"workers" in opts &&
Array.isArray(opts.workers)
);
}
export function getRootPath(opts: unknown): string {
// `opts` will be validated properly with Zod, this is just a quick check/
// extract for the `rootPath` option since it's required for parsing
if (
typeof opts === "object" &&
opts !== null &&
"rootPath" in opts &&
typeof opts.rootPath === "string"
) {
return opts.rootPath;
} else {
return ""; // Default to cwd
}
}
function validateOptions(
opts: unknown
): [PluginSharedOptions, PluginWorkerOptions[]] {
// Normalise options into shared and worker-specific
const sharedOpts = opts;
const multipleWorkers = hasMultipleWorkers(opts);
const workerOpts = multipleWorkers ? opts.workers : [opts];
if (workerOpts.length === 0) {
throw new MiniflareCoreError("ERR_NO_WORKERS", "No workers defined");
}
// Initialise return values
const pluginSharedOpts = {} as PluginSharedOptions;
const pluginWorkerOpts = Array.from(Array(workerOpts.length)).map(
() => ({}) as PluginWorkerOptions
);
// If we haven't defined multiple workers, shared options and worker options
// are the same, but we only want to resolve the `rootPath` once. Otherwise,
// if specified a relative `rootPath` (e.g. "./dir"), we end up with a root
// path of `$PWD/dir/dir` when resolving other options.
const sharedRootPath = multipleWorkers ? getRootPath(sharedOpts) : "";
const workerRootPaths = workerOpts.map((opts) =>
path.resolve(sharedRootPath, getRootPath(opts))
);
// Validate all options
try {
for (const [key, plugin] of PLUGIN_ENTRIES) {
// @ts-expect-error types of individual plugin options are unknown
pluginSharedOpts[key] =
plugin.sharedOptions === undefined
? undefined
: parseWithRootPath(sharedRootPath, plugin.sharedOptions, sharedOpts);
for (let i = 0; i < workerOpts.length; i++) {
// Make sure paths are correct in validation errors
const optionsPath = multipleWorkers ? ["workers", i] : undefined;
// @ts-expect-error types of individual plugin options are unknown
pluginWorkerOpts[i][key] = parseWithRootPath(
workerRootPaths[i],
plugin.options,
workerOpts[i],
{ path: optionsPath }
);
}
}
} catch (e) {
if (e instanceof z.ZodError) {
let formatted: string | undefined;
try {
formatted = formatZodError(e, opts);
} catch (formatError) {
// If formatting failed for some reason, we'd like to know, so log a
// bunch of debugging information, including the full validation error
// so users at least know what was wrong.
const title = "[Miniflare] Validation Error Format Failure";
const message = [
"### Input",
"```",
util.inspect(opts, { depth: null }),
"```",
"",
"### Validation Error",
"```",
e.stack,
"```",
"",
"### Format Error",
"```",
typeof formatError === "object" &&
formatError !== null &&
"stack" in formatError &&
typeof formatError.stack === "string"
? formatError.stack
: String(formatError),
"```",
].join("\n");
const githubIssueUrl = new URL(
"https://github.com/cloudflare/miniflare/issues/new"
);
githubIssueUrl.searchParams.set("title", title);
githubIssueUrl.searchParams.set("body", message);
formatted = [
"Unable to format validation error.",
"Please open the following URL in your browser to create a GitHub issue:",
githubIssueUrl,
"",
message,
"",
].join("\n");
}
const error = new MiniflareCoreError(
"ERR_VALIDATION",
`Unexpected options passed to \`new Miniflare()\` constructor:\n${formatted}`
);
// Add the `cause` as a getter, so it isn't logged automatically with the
// error, but can still be accessed if needed
Object.defineProperty(error, "cause", { get: () => e });
throw error;
}
throw e;
}
// Validate names unique
const names = new Set<string>();
for (const opts of pluginWorkerOpts) {
const name = opts.core.name ?? "";
if (names.has(name)) {
throw new MiniflareCoreError(
"ERR_DUPLICATE_NAME",
name === ""
? "Multiple workers defined without a `name`"
: `Multiple workers defined with the same \`name\`: "${name}"`
);
}
names.add(name);
}
return [pluginSharedOpts, pluginWorkerOpts];
}
// When creating user worker services, we need to know which Durable Objects
// they export. Rather than parsing JavaScript to search for class exports
// (which would have to be recursive because of `export * from ...`), we collect
// all Durable Object bindings, noting that bindings may be defined for objects
// in other services.
function getDurableObjectClassNames(
allWorkerOpts: PluginWorkerOptions[]
): DurableObjectClassNames {
const serviceClassNames: DurableObjectClassNames = new Map();
const allDurableObjects = allWorkerOpts
.flatMap((workerOpts) => {
const workerServiceName = getUserServiceName(workerOpts.core.name);
return [
...Object.values(workerOpts.do.durableObjects ?? {}),
...(workerOpts.do.additionalUnboundDurableObjects ?? []),
].map((workerDODesignator) => {
const doInfo = normaliseDurableObject(workerDODesignator);
if (doInfo.serviceName === undefined) {
// Fallback to current worker service if name not defined
doInfo.serviceName = workerServiceName;
}
return {
doInfo,
workerRawName: workerOpts.core.name,
};
});
})
// We sort the list of durable objects because we want the durable objects without a scriptName or a scriptName
// that matches the raw worker's name (meaning that they are defined within their worker) to be processed first
.sort(({ doInfo, workerRawName }) =>
doInfo.scriptName === undefined || doInfo.scriptName === workerRawName
? -1
: 0
)
.map(({ doInfo }) => doInfo);
for (const doInfo of allDurableObjects) {
const { className, serviceName, container, ...doConfigs } = doInfo;
// We know that the service name is always defined (since if it is not we do default it to the current worker service)
assert(serviceName);
// Get or create `Map` mapping class name to optional unsafe unique key
let classNames = serviceClassNames.get(serviceName);
if (classNames === undefined) {
classNames = new Map();
serviceClassNames.set(serviceName, classNames);
}
if (classNames.has(className)) {
// If we've already seen this class in this service, make sure the
// unsafe unique keys and unsafe prevent eviction values match
const existingInfo = classNames.get(className);
const isDoUnacceptableDiff = (
field: Extract<
keyof typeof doConfigs,
"enableSql" | "unsafeUniqueKey" | "unsafePreventEviction"
>
) => {
if (!existingInfo) {
return false;
}
const same = existingInfo[field] === doConfigs[field];
if (same) {
return false;
}
const oneIsUndefined =
existingInfo[field] === undefined || doConfigs[field] === undefined;
// If one of the configurations is `undefined` (either the current one or the existing one) then there we
// want to consider this as an acceptable difference since we might be in a potentially valid situation in
// which worker A defines a DO with a config, while worker B simply uses the DO from worker A but without
// providing the configuration (thus leaving it `undefined`) (this for example is exactly what Wrangler does
// with the implicitly defined `enableSql` flag)
if (oneIsUndefined) {
return false;
}
return true;
};
if (isDoUnacceptableDiff("enableSql")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_STORAGE_BACKEND",
`Different storage backends defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.enableSql
)} and ${JSON.stringify(existingInfo?.enableSql)}`
);
}
if (isDoUnacceptableDiff("unsafeUniqueKey")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_UNIQUE_KEYS",
`Multiple unsafe unique keys defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.unsafeUniqueKey
)} and ${JSON.stringify(existingInfo?.unsafeUniqueKey)}`
);
}
if (isDoUnacceptableDiff("unsafePreventEviction")) {
throw new MiniflareCoreError(
"ERR_DIFFERENT_PREVENT_EVICTION",
`Multiple unsafe prevent eviction values defined for Durable Object "${className}" in "${serviceName}": ${JSON.stringify(
doConfigs.unsafePreventEviction
)} and ${JSON.stringify(existingInfo?.unsafePreventEviction)}`
);
}
} else {
// Otherwise, just add it
classNames.set(className, {
enableSql: doConfigs.enableSql,
unsafeUniqueKey: doConfigs.unsafeUniqueKey,
unsafePreventEviction: doConfigs.unsafePreventEviction,
container,
});
}
}
return serviceClassNames;
}
/**
* This collects all external service bindings from all workers and overrides
* it to point to the dev registry proxy. A fallback service will be created
* for each of the external service in case the external service is not available.
*/
function getExternalServiceEntrypoints(
allWorkerOpts: PluginWorkerOptions[],
proxyAddress: string
) {
const externalServices = new Map<
string,
{
classNames: Set<string>;
entrypoints: Set<string | undefined>;
}
>();
const allWorkerNames = allWorkerOpts.map((opts) => opts.core.name);
const getEntrypoints = (name: string) => {
let externalService = externalServices.get(name);
if (!externalService) {
externalService = {
classNames: new Set(),
entrypoints: new Set(),
};
externalServices.set(name, externalService);
}
return externalService;
};
for (const workerOpts of allWorkerOpts) {
// Override service bindings if they point to a worker that doesn't exist
if (workerOpts.core.serviceBindings) {
for (const [name, service] of Object.entries(
workerOpts.core.serviceBindings
)) {
const { serviceName, entrypoint, remoteProxyConnectionString } =
normaliseServiceDesignator(service);
if (
// Skip if it is a remote service
remoteProxyConnectionString === undefined &&
// Skip if the service is bound to another Worker defined in the Miniflare config
serviceName &&
!allWorkerNames.includes(serviceName)
) {
// This is a service binding to a worker that doesn't exist
// Override it to connect to the dev registry proxy
workerOpts.core.serviceBindings[name] = {
external: {
address: proxyAddress,
http: getHttpProxyOptions(serviceName, entrypoint),
},
};
const entrypoints = getEntrypoints(serviceName);
entrypoints.entrypoints.add(entrypoint);
}
}
}
if (workerOpts.do.durableObjects) {
for (const [bindingName, designator] of Object.entries(
workerOpts.do.durableObjects
)) {
const {
className,
scriptName,
unsafePreventEviction,
enableSql: useSQLite,
remoteProxyConnectionString,
} = normaliseDurableObject(designator);
if (
// Skip if it is a remote durable object
remoteProxyConnectionString === undefined &&
// Skip if the durable object is bound to a Worker that exists in the current Miniflare config
scriptName &&
!allWorkerNames.includes(scriptName)
) {
// Point it to the outbound do proxy service instead
workerOpts.do.durableObjects[bindingName] = {
className: getOutboundDoProxyClassName(scriptName, className),
scriptName: OUTBOUND_DO_PROXY_SERVICE_NAME,
useSQLite,
// Matches the unique key Miniflare will generate for this object in
// the target session. We need to do this so workerd generates the
// same IDs it would if this were part of the same process. workerd
// doesn't allow IDs from Durable Objects with different unique keys
// to be used with each other.
unsafeUniqueKey: `${scriptName}-${className}`,
unsafePreventEviction,
};
const entrypoints = getEntrypoints(scriptName);
entrypoints.classNames.add(className);
}
}
}
if (workerOpts.core.tails) {
for (let i = 0; i < workerOpts.core.tails.length; i++) {
const {
serviceName = workerOpts.core.name,
entrypoint,
remoteProxyConnectionString,
} = normaliseServiceDesignator(workerOpts.core.tails[i]);
if (
// Skip if it is a remote service
remoteProxyConnectionString === undefined &&
// Skip if the service is bound to the existing workers
serviceName &&
!allWorkerNames.includes(serviceName)
) {
// This is a tail worker that doesn't exist
// Override it to connect to the dev registry proxy
workerOpts.core.tails[i] = {
external: {
address: proxyAddress,
http: getHttpProxyOptions(serviceName, entrypoint),
},
};
const entrypoints = getEntrypoints(serviceName);
entrypoints.entrypoints.add(entrypoint);
}
}
}
}
return externalServices;
}
function invalidWrappedAsBound(name: string, bindingType: string): never {
const stringName = JSON.stringify(name);
throw new MiniflareCoreError(
"ERR_INVALID_WRAPPED",
`Cannot use ${stringName} for wrapped binding because it is bound to with ${bindingType} bindings.\nEnsure other workers don't define ${bindingType} bindings to ${stringName}.`
);
}
function getWrappedBindingNames(
allWorkerOpts: PluginWorkerOptions[],
durableObjectClassNames: DurableObjectClassNames
): WrappedBindingNames {
// Build set of all worker names bound to as wrapped bindings.
// Also check these "workers" aren't bound to as services/Durable Objects.
// We won't add them as regular workers so these bindings would fail.
const wrappedBindingWorkerNames = new Set<string>();
for (const workerOpts of allWorkerOpts) {
for (const designator of Object.values(
workerOpts.core.wrappedBindings ?? {}
)) {
const scriptName =
typeof designator === "object" ? designator.scriptName : designator;
if (durableObjectClassNames.has(getUserServiceName(scriptName))) {
invalidWrappedAsBound(scriptName, "Durable Object");
}
wrappedBindingWorkerNames.add(scriptName);
}
}
// Need to collect all wrapped bindings before checking service bindings
for (const workerOpts of allWorkerOpts) {
for (const designator of Object.values(
workerOpts.core.serviceBindings ?? {}
)) {
if (typeof designator !== "string") continue;
if (wrappedBindingWorkerNames.has(designator)) {
invalidWrappedAsBound(designator, "service");
}
}
}
return wrappedBindingWorkerNames;
}
function getQueueProducers(
allWorkerOpts: PluginWorkerOptions[]
): QueueProducers {
const queueProducers: QueueProducers = new Map();
for (const workerOpts of allWorkerOpts) {
const workerName = workerOpts.core.name ?? "";
let workerProducers = workerOpts.queues.queueProducers;
if (workerProducers !== undefined) {
// De-sugar array consumer options to record mapping to empty options
if (Array.isArray(workerProducers)) {
// queueProducers: ["MY_QUEUE"]
workerProducers = Object.fromEntries(
workerProducers.map((bindingName) => [
bindingName,
{ queueName: bindingName },
])
);
}
type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][];
type ProducersIterable = Entries<typeof workerProducers>;
const producersIterable = Object.entries(
workerProducers
) as ProducersIterable;
for (const [bindingName, opts] of producersIterable) {
if (typeof opts === "string") {
// queueProducers: { "MY_QUEUE": "my-queue" }
queueProducers.set(bindingName, { workerName, queueName: opts });
} else {
// queueProducers: { QUEUE: { queueName: "QUEUE", ... } }
queueProducers.set(bindingName, { workerName, ...opts });
}
}
}
}
return queueProducers;
}
function getQueueConsumers(
allWorkerOpts: PluginWorkerOptions[]
): QueueConsumers {
const queueConsumers: QueueConsumers = new Map();
for (const workerOpts of allWorkerOpts) {
const workerName = workerOpts.core.name ?? "";
let workerConsumers = workerOpts.queues.queueConsumers;
if (workerConsumers !== undefined) {
// De-sugar array consumer options to record mapping to empty options
if (Array.isArray(workerConsumers)) {
workerConsumers = Object.fromEntries(
workerConsumers.map((queueName) => [queueName, {}])
);
}
for (const [queueName, opts] of Object.entries(workerConsumers)) {
// Validate that each queue has at most one consumer...
const existingConsumer = queueConsumers.get(queueName);
if (existingConsumer !== undefined) {
throw new QueuesError(
"ERR_MULTIPLE_CONSUMERS",
`Multiple consumers defined for queue "${queueName}": "${existingConsumer.workerName}" and "${workerName}"`
);
}
// ...then store the consumer
queueConsumers.set(queueName, { workerName, ...opts });
}
}
}
for (const [queueName, consumer] of queueConsumers) {
// Check the dead letter queue isn't configured to be the queue itself
// (NOTE: Queues *does* permit DLQ cycles between multiple queues,
// i.e. if Q2 is DLQ for Q1, but Q1 is DLQ for Q2)
if (consumer.deadLetterQueue === queueName) {
throw new QueuesError(
"ERR_DEAD_LETTER_QUEUE_CYCLE",
`Dead letter queue for queue "${queueName}" cannot be itself`
);
}
}
return queueConsumers;
}
// Collects all routes from all worker services
function getWorkerRoutes(
allWorkerOpts: PluginWorkerOptions[],
wrappedBindingNames: Set<string>
): Map<string, string[]> {
const allRoutes = new Map<string, string[]>();
for (const workerOpts of allWorkerOpts) {
const name = workerOpts.core.name ?? "";
if (wrappedBindingNames.has(name)) continue; // Wrapped bindings un-routable
assert(!allRoutes.has(name)); // Validated unique names earlier
allRoutes.set(name, workerOpts.core.routes ?? []);
}
return allRoutes;
}
// Get the name of a binding in the `ProxyServer`'s `env`
function getProxyBindingName(plugin: string, worker: string, binding: string) {
return [
CoreBindings.DURABLE_OBJECT_NAMESPACE_PROXY,
plugin,
worker,
binding,
].join(":");
}
// Get whether a binding will need a proxy to be supported in Node (i.e. is
// the implementation of this binding in `workerd`?). If this returns `false`,
// there's no need to bind the binding to the `ProxyServer`.
function isNativeTargetBinding(binding: Worker_Binding) {
return !(
"json" in binding ||
"wasmModule" in binding ||
"text" in binding ||
"data" in binding
);
}
// Converts a regular worker binding to binding suitable for the `ProxyServer`.
function buildProxyBinding(
plugin: string,
worker: string,
binding: Worker_Binding
): Worker_Binding {
assert(binding.name !== undefined);
const name = getProxyBindingName(plugin, worker, binding.name);
const proxyBinding = { ...binding, name };
// If this is a Durable Object namespace binding to the current worker,
// make sure it continues to point to that worker when bound elsewhere
if (
"durableObjectNamespace" in proxyBinding &&
proxyBinding.durableObjectNamespace !== undefined
) {
proxyBinding.durableObjectNamespace.serviceName ??=
getUserServiceName(worker);
}
return proxyBinding;
}
// Gets an array of proxy bindings for internal Durable Objects, only used in
// testing for accessing internal methods
function getInternalDurableObjectProxyBindings(
plugin: string,
service: Service
): Worker_Binding[] | undefined {
if (!("worker" in service)) return;
assert(service.worker !== undefined);
const serviceName = service.name;
assert(serviceName !== undefined);
return service.worker.durableObjectNamespaces?.map(({ className }) => {
assert(className !== undefined);
return {
name: getProxyBindingName(`${plugin}-internal`, serviceName, className),
durableObjectNamespace: { serviceName, className },
};
});
}
type StoppableServer = http.Server & stoppable.WithStop;
const restrictedUndiciHeaders = [
// From Miniflare 2:
// https://github.com/cloudflare/miniflare/blob/9c135599dc21fe69080ada17fce6153692793bf1/packages/core/src/standards/http.ts#L129-L132
"transfer-encoding",
"connection",
"keep-alive",
"expect",
];
const restrictedWebSocketUpgradeHeaders = [
"upgrade",
"connection",
"sec-websocket-accept",
];
export function _transformsForContentEncodingAndContentType(
encoding: string | undefined,
type: string | undefined | null
): Transform[] {
const encoders: Transform[] = [];
if (!encoding) return encoders;
// if cloudflare's FL does not compress this mime-type, then don't compress locally either
if (!isCompressedByCloudflareFL(type)) return encoders;
// Reverse of https://github.com/nodejs/undici/blob/48d9578f431cbbd6e74f77455ba92184f57096cf/lib/fetch/index.js#L1660
const codings = encoding
.toLowerCase()
.split(",")
.map((x) => x.trim());
for (const coding of codings) {
if (/(x-)?gzip/.test(coding)) {
encoders.push(zlib.createGzip());
} else if (/(x-)?deflate/.test(coding)) {
encoders.push(zlib.createDeflate());
} else if (coding === "br") {
encoders.push(zlib.createBrotliCompress());
} else {
// Unknown encoding, don't do any encoding at all
encoders.length = 0;
break;
}
}
return encoders;
}
function safeReadableStreamFrom(iterable: AsyncIterable<Uint8Array>) {
// Adapted from `undici`, catches errors from `next()` to avoid unhandled
// rejections from aborted request body streams:
// https://github.com/nodejs/undici/blob/dfaec78f7a29f07bb043f9006ed0ceb0d5220b55/lib/core/util.js#L369-L392
let iterator: AsyncIterator<Uint8Array>;
return new ReadableStream<Uint8Array>({
async start() {
iterator = iterable[Symbol.asyncIterator]();
},
// @ts-expect-error `pull` may return anything
async pull(controller): Promise<boolean> {
try {
const { done, value } = await iterator.next();
if (done) {
queueMicrotask(() => controller.close());
} else {
const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
controller.enqueue(new Uint8Array(buf));
}
} catch {
queueMicrotask(() => controller.close());
}
// @ts-expect-error `pull` may return anything
return controller.desiredSize > 0;
},
async cancel() {
await iterator.return?.();
},
});
}
function extractCustomService(customService: string) {
const slashIndex = customService.indexOf("/");
// TODO: technically may want to keep old versions around so can always
// recover this in case of setOptions()?
const workerIndex = parseInt(customService.substring(0, slashIndex));
const serviceKind = customService[slashIndex + 1] as CustomServiceKind;
const serviceName = customService.substring(slashIndex + 2);
return { workerIndex, serviceKind, serviceName };
}
function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.stack || error.message;
}
if (typeof error === "string") {
return error;
}
try {
return JSON.stringify(error);
} catch {
return "Unknown error";
}
}
// Maps `Miniflare` instances to stack traces for their construction. Used to identify un-`dispose()`d instances.
let maybeInstanceRegistry:
| Map<Miniflare, string /* constructionStack */>
| undefined;
/** @internal */
export function _initialiseInstanceRegistry() {
return (maybeInstanceRegistry = new Map());
}
export class Miniflare {
#previousSharedOpts?: PluginSharedOptions;
#previousWorkerOpts?: PluginWorkerOptions[];
#sharedOpts: PluginSharedOptions;
#workerOpts: PluginWorkerOptions[];
#log: Log;
/**
* externalPlugins is a list of external plugins that have been loaded
* after being referenced by an unsafe binding
*/
#externalPlugins: Map<string, Plugin<z.ZodTypeAny>> = new Map();
// key is the browser session ID, value is the browser process
#browserProcesses: Map<string, Process> = new Map();
readonly #runtime?: Runtime;
readonly #removeExitHook?: () => void;
#runtimeEntryURL?: URL;
#socketPorts?: SocketPorts;
#runtimeDispatcher?: Dispatcher;
#proxyClient?: ProxyClient;
#structuredWorkerdLogs: boolean;
#cfObject?: Record<string, any> = {};
// Path to temporary directory for use as scratch space/"in-memory" Durable
// Object storage. Note this may not exist, it's up to the consumers to
// create this if needed. Deleted on `dispose()`.
readonly #tmpPath: string;
// Mutual exclusion lock for runtime operations (i.e. initialisation and
// updating config). This essentially puts initialisation and future updates
// in a queue, ensuring they're performed in calling order.
readonly #runtimeMutex: Mutex;
// Store `#init()` `Promise`, so we can propagate initialisation errors in
// `ready`. We would have no way of catching these otherwise.
// eslint-disable-next-line no-unused-private-class-members — oxlint is wrong here, this variable _is_ used
readonly #initPromise: Promise<void>;
// Aborted when dispose() is called
readonly #disposeController: AbortController;
#loopbackServer?: StoppableServer;
#loopbackHost?: string;
readonly #liveReloadServer: WebSocketServer;
readonly #webSocketServer: WebSocketServer;
readonly #webSocketExtraHeaders: WeakMap<http.IncomingMessage, Headers>;
readonly #devRegistry: DevRegistry;
#maybeInspectorProxyController?: InspectorProxyController;
#previousRuntimeInspectorPort?: number;
#hyperdriveProxyController: HyperdriveProxyController =
new HyperdriveProxyController();
constructor(opts: MiniflareOptions) {
// Split and validate options
const [sharedOpts, workerOpts] = validateOptions(opts);
checkMacOSVersion({ shouldThrow: true });
this.#sharedOpts = sharedOpts;
this.#workerOpts = workerOpts;
const workerNamesToProxy = this.#workerNamesToProxy();
const enableInspectorProxy = workerNamesToProxy.size > 0;
if (enableInspectorProxy) {
if (this.#sharedOpts.core.inspectorPort === undefined) {
throw new MiniflareCoreError(
"ERR_MISSING_INSPECTOR_PROXY_PORT",
"inspector proxy requested but without an inspectorPort specified"
);
}
}
// Add to registry after initial options validation, before any servers/
// child processes are started
if (maybeInstanceRegistry !== undefined) {
const object = { name: "Miniflare", stack: "" };
Error.captureStackTrace(object, Miniflare);
maybeInstanceRegistry.set(this, object.stack);
}
this.#log = this.#sharedOpts.core.log ?? new NoOpLog();
this.#structuredWorkerdLogs =
this.#sharedOpts.core.structuredWorkerdLogs ??
// If there is a `handleStructuredLogs` set then `structuredWorkerdLogs` defaults
// to `true`, otherwise it defaults to `false`
(this.#sharedOpts.core.handleStructuredLogs ? true : false);
// If we're in a JavaScript Debug terminal, Miniflare will send the inspector ports directly to VSCode for registration