-
Notifications
You must be signed in to change notification settings - Fork 774
/
Copy pathindex.ts
339 lines (304 loc) · 9.73 KB
/
index.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
import { kCurrentWorker, Miniflare } from "miniflare";
import { getAssetsOptions } from "../../../assets";
import { readConfig } from "../../../config";
import { DEFAULT_MODULE_RULES } from "../../../deployment-bundle/rules";
import { getBindings } from "../../../dev";
import { getBoundRegisteredWorkers } from "../../../dev-registry";
import { getClassNamesWhichUseSQLite } from "../../../dev/class-names-sqlite";
import { getVarsForDev } from "../../../dev/dev-vars";
import {
buildAssetOptions,
buildMiniflareBindingOptions,
buildSitesOptions,
} from "../../../dev/miniflare";
import { run } from "../../../experimental-flags";
import { getLegacyAssetPaths, getSiteAssetPaths } from "../../../sites";
import { CacheStorage } from "./caches";
import { ExecutionContext } from "./executionContext";
import { getServiceBindings } from "./services";
import type { Config, RawConfig, RawEnvironment } from "../../../config";
import type { IncomingRequestCfProperties } from "@cloudflare/workers-types/experimental";
import type { MiniflareOptions, ModuleRule, WorkerOptions } from "miniflare";
export { readConfig as unstable_readConfig };
export type {
Config as Unstable_Config,
RawConfig as Unstable_RawConfig,
RawEnvironment as Unstable_RawEnvironment,
};
/**
* Options for the `getPlatformProxy` utility
*/
export type GetPlatformProxyOptions = {
/**
* The name of the environment to use
*/
environment?: string;
/**
* The path to the config file to use.
* If no path is specified the default behavior is to search from the
* current directory up the filesystem for a Wrangler configuration file to use.
*
* Note: this field is optional but if a path is specified it must
* point to a valid file on the filesystem
*/
configPath?: string;
/**
* Indicates if and where to persist the bindings data, if not present or `true` it defaults to the same location
* used by wrangler v3: `.wrangler/state/v3` (so that the same data can be easily used by the caller and wrangler).
* If `false` is specified no data is persisted on the filesystem.
*/
persist?: boolean | { path: string };
};
/**
* Result of the `getPlatformProxy` utility
*/
export type PlatformProxy<
Env = Record<string, unknown>,
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
> = {
/**
* Environment object containing the various Cloudflare bindings
*/
env: Env;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
cf: CfProperties;
/**
* Mock of the context object that Workers received in their request handler, all the object's methods are no-op
*/
ctx: ExecutionContext;
/**
* Caches object emulating the Workers Cache runtime API
*/
caches: CacheStorage;
/**
* Function used to dispose of the child process providing the bindings implementation
*/
dispose: () => Promise<void>;
};
/**
* By reading from a Wrangler configuration file this function generates proxy objects that can be
* used to simulate the interaction with the Cloudflare platform during local development
* in a Node.js environment
*
* @param options The various options that can tweak this function's behavior
* @returns An Object containing the generated proxies alongside other related utilities
*/
export async function getPlatformProxy<
Env = Record<string, unknown>,
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
>(
options: GetPlatformProxyOptions = {}
): Promise<PlatformProxy<Env, CfProperties>> {
const env = options.environment;
const rawConfig = readConfig({
config: options.configPath,
env,
});
const miniflareOptions = await run(
{
MULTIWORKER: false,
RESOURCES_PROVISION: false,
},
() => getMiniflareOptionsFromConfig(rawConfig, env, options)
);
const mf = new Miniflare({
script: "",
modules: true,
...(miniflareOptions as Record<string, unknown>),
});
const bindings: Env = await mf.getBindings();
const vars = getVarsForDev(rawConfig, env);
const cf = await mf.getCf();
deepFreeze(cf);
return {
env: {
...vars,
...bindings,
},
cf: cf as CfProperties,
ctx: new ExecutionContext(),
caches: new CacheStorage(),
dispose: () => mf.dispose(),
};
}
async function getMiniflareOptionsFromConfig(
rawConfig: Config,
env: string | undefined,
options: GetPlatformProxyOptions
): Promise<Partial<MiniflareOptions>> {
const bindings = getBindings(rawConfig, env, true, {});
const workerDefinitions = await getBoundRegisteredWorkers({
name: rawConfig.name,
services: bindings.services,
durableObjects: rawConfig["durable_objects"],
});
const { bindingOptions, externalWorkers } = buildMiniflareBindingOptions({
name: undefined,
bindings,
workerDefinitions,
queueConsumers: undefined,
services: rawConfig.services,
serviceBindings: {},
migrations: rawConfig.migrations,
});
const persistOptions = getMiniflarePersistOptions(options.persist);
const serviceBindings = await getServiceBindings(bindings.services);
const miniflareOptions: MiniflareOptions = {
workers: [
{
script: "",
modules: true,
...bindingOptions,
serviceBindings: {
...serviceBindings,
...bindingOptions.serviceBindings,
},
},
...externalWorkers,
],
...persistOptions,
};
return miniflareOptions;
}
/**
* Get the persist option properties to pass to miniflare
*
* @param persist The user provided persistence option
* @returns an object containing the properties to pass to miniflare
*/
function getMiniflarePersistOptions(
persist: GetPlatformProxyOptions["persist"]
): Pick<
MiniflareOptions,
| "kvPersist"
| "durableObjectsPersist"
| "r2Persist"
| "d1Persist"
| "workflowsPersist"
> {
if (persist === false) {
// the user explicitly asked for no persistance
return {
kvPersist: false,
durableObjectsPersist: false,
r2Persist: false,
d1Persist: false,
workflowsPersist: false,
};
}
const defaultPersistPath = ".wrangler/state/v3";
const persistPath =
typeof persist === "object" ? persist.path : defaultPersistPath;
return {
kvPersist: `${persistPath}/kv`,
durableObjectsPersist: `${persistPath}/do`,
r2Persist: `${persistPath}/r2`,
d1Persist: `${persistPath}/d1`,
workflowsPersist: `${persistPath}/workflows`,
};
}
function deepFreeze<T extends Record<string | number | symbol, unknown>>(
obj: T
): void {
Object.freeze(obj);
Object.entries(obj).forEach(([, prop]) => {
if (prop !== null && typeof prop === "object" && !Object.isFrozen(prop)) {
deepFreeze(prop as Record<string | number | symbol, unknown>);
}
});
}
export type SourcelessWorkerOptions = Omit<
WorkerOptions,
"script" | "scriptPath" | "modules" | "modulesRoot"
> & { modulesRules?: ModuleRule[] };
export interface Unstable_MiniflareWorkerOptions {
workerOptions: SourcelessWorkerOptions;
define: Record<string, string>;
main?: string;
}
export function unstable_getMiniflareWorkerOptions(
configPath: string,
env?: string
): Unstable_MiniflareWorkerOptions;
export function unstable_getMiniflareWorkerOptions(
config: Config
): Unstable_MiniflareWorkerOptions;
export function unstable_getMiniflareWorkerOptions(
configOrConfigPath: string | Config,
env?: string
): Unstable_MiniflareWorkerOptions {
const config =
typeof configOrConfigPath === "string"
? readConfig({ config: configOrConfigPath, env })
: configOrConfigPath;
const modulesRules: ModuleRule[] = config.rules
.concat(DEFAULT_MODULE_RULES)
.map((rule) => ({
type: rule.type,
include: rule.globs,
fallthrough: rule.fallthrough,
}));
const bindings = getBindings(config, env, true, {});
const { bindingOptions } = buildMiniflareBindingOptions({
name: undefined,
bindings,
workerDefinitions: undefined,
queueConsumers: config.queues.consumers,
services: [],
serviceBindings: {},
migrations: config.migrations,
});
// This function is currently only exported for the Workers Vitest pool.
// In tests, we don't want to rely on the dev registry, as we can't guarantee
// which sessions will be running. Instead, we rewrite `serviceBindings` and
// `durableObjects` to use more traditional Miniflare config expecting the
// user to define workers with the required names in the `workers` array.
// These will run the same `workerd` processes as tests.
if (bindings.services !== undefined) {
bindingOptions.serviceBindings = Object.fromEntries(
bindings.services.map((binding) => {
const name =
binding.service === config.name ? kCurrentWorker : binding.service;
return [binding.binding, { name, entrypoint: binding.entrypoint }];
})
);
}
if (bindings.durable_objects !== undefined) {
type DurableObjectDefinition = NonNullable<
typeof bindingOptions.durableObjects
>[string];
const classNameToUseSQLite = getClassNamesWhichUseSQLite(config.migrations);
bindingOptions.durableObjects = Object.fromEntries(
bindings.durable_objects.bindings.map((binding) => {
const useSQLite = classNameToUseSQLite.get(binding.class_name);
return [
binding.name,
{
className: binding.class_name,
scriptName: binding.script_name,
useSQLite,
} satisfies DurableObjectDefinition,
];
})
);
}
const legacyAssetPaths = config.legacy_assets
? getLegacyAssetPaths(config, undefined)
: getSiteAssetPaths(config);
const sitesOptions = buildSitesOptions({ legacyAssetPaths });
const processedAssetOptions = getAssetsOptions({ assets: undefined }, config);
const assetOptions = processedAssetOptions
? buildAssetOptions({ assets: processedAssetOptions })
: {};
const workerOptions: SourcelessWorkerOptions = {
compatibilityDate: config.compatibility_date,
compatibilityFlags: config.compatibility_flags,
modulesRules,
...bindingOptions,
...sitesOptions,
...assetOptions,
};
return { workerOptions, define: config.define, main: config.main };
}