@cloudflare/deploy-helpers 0.27.1 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,113 +1,102 @@
1
- import { createRequire } from 'node:module';
2
- import { fromMimeType } from './chunk-DSGVRFIS.mjs';
3
- import { __name } from './chunk-U6NEESU5.mjs';
4
- import { randomUUID } from 'node:crypto';
5
- import { readFile } from 'node:fs/promises';
6
- import { setTimeout, clearTimeout } from 'node:timers';
7
- import { gzipSync } from 'node:zlib';
8
- import { UserError } from '@cloudflare/workers-utils';
9
- import { Miniflare, convertV4MiniflareOptions } from 'miniflare';
10
- import { Response } from 'undici';
11
- import { WebSocket } from 'ws';
12
-
13
- createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));
14
- var STARTUP_PROFILE_TIMEOUT_MS = 1e4;
15
- var MODULE_TYPE_TO_MINIFLARE_TYPE = {
16
- esm: "ESModule",
17
- commonjs: "CommonJS",
18
- "compiled-wasm": "CompiledWasm",
19
- buffer: "Data",
20
- text: "Text",
21
- python: "PythonModule",
22
- "python-requirement": "PythonRequirement"
1
+ import "./rolldown-runtime-BMUeFane.mjs";
2
+ import { n as fromMimeType } from "./create-worker-upload-form-BlSu1EfR.mjs";
3
+ import { UserError } from "@cloudflare/workers-utils";
4
+ import { Response } from "undici";
5
+ import { readFile } from "node:fs/promises";
6
+ import { gzipSync } from "node:zlib";
7
+ import { randomUUID } from "node:crypto";
8
+ import { clearTimeout, setTimeout } from "node:timers";
9
+ import { Miniflare, convertV4MiniflareOptions } from "miniflare";
10
+ import { WebSocket } from "ws";
11
+ //#region src/startup-profile.ts
12
+ const STARTUP_PROFILE_TIMEOUT_MS = 1e4;
13
+ const MODULE_TYPE_TO_MINIFLARE_TYPE = {
14
+ esm: "ESModule",
15
+ commonjs: "CommonJS",
16
+ "compiled-wasm": "CompiledWasm",
17
+ buffer: "Data",
18
+ text: "Text",
19
+ python: "PythonModule",
20
+ "python-requirement": "PythonRequirement"
23
21
  };
22
+ /**
23
+ * Parses a multipart Worker upload from disk, or returns an existing upload.
24
+ *
25
+ * @param workerBundle - A serialized upload path or an already parsed upload.
26
+ * @returns The parsed multipart Worker upload.
27
+ */
24
28
  async function parseWorkerBundle(workerBundle) {
25
- if (typeof workerBundle !== "string") {
26
- return workerBundle;
27
- }
28
- const bundle = await readFile(workerBundle);
29
- const firstLine = bundle.findIndex((value) => value === 10);
30
- const boundary = Uint8Array.prototype.slice.call(bundle, 2, firstLine).toString();
31
- const response = new Response(bundle, {
32
- headers: {
33
- "Content-Type": `multipart/form-data; boundary=${boundary}`
34
- }
35
- });
36
- return await response.formData();
29
+ if (typeof workerBundle !== "string") return workerBundle;
30
+ const bundle = await readFile(workerBundle);
31
+ const firstLine = bundle.findIndex((value) => value === 10);
32
+ const boundary = Uint8Array.prototype.slice.call(bundle, 2, firstLine).toString();
33
+ return await new Response(bundle, { headers: { "Content-Type": `multipart/form-data; boundary=${boundary}` } }).formData();
37
34
  }
38
- __name(parseWorkerBundle, "parseWorkerBundle");
35
+ /**
36
+ * Measures the uncompressed and gzip-compressed size of a Worker upload.
37
+ * Source maps and metadata are excluded from both measurements.
38
+ *
39
+ * @param workerBundle - A parsed multipart Worker upload.
40
+ * @returns Raw and compressed byte counts.
41
+ */
39
42
  async function getBundleSize(workerBundle) {
40
- const modules = [];
41
- for (const entry of workerBundle.values()) {
42
- if (entry instanceof Blob && entry.type !== "application/source-map") {
43
- modules.push(entry);
44
- }
45
- }
46
- const bundle = new Blob(modules);
47
- return {
48
- size: bundle.size,
49
- gzipSize: gzipSync(await bundle.arrayBuffer()).byteLength
50
- };
43
+ const modules = [];
44
+ for (const entry of workerBundle.values()) if (entry instanceof Blob && entry.type !== "application/source-map") modules.push(entry);
45
+ const bundle = new Blob(modules);
46
+ return {
47
+ size: bundle.size,
48
+ gzipSize: gzipSync(await bundle.arrayBuffer()).byteLength
49
+ };
51
50
  }
52
- __name(getBundleSize, "getBundleSize");
51
+ /**
52
+ * Summarizes the timing samples in a Worker startup CPU profile.
53
+ *
54
+ * @param profile - A Chrome DevTools Protocol CPU profile.
55
+ * @returns Aggregate startup, active, idle, and garbage-collection timings.
56
+ */
53
57
  function summarizeStartupProfile(profile) {
54
- const nodes = new Map(profile.nodes.map((node) => [node.id, node]));
55
- const samples = profile.samples ?? [];
56
- const timeDeltas = profile.timeDeltas ?? [];
57
- let sampledTime = 0;
58
- let idleTime = 0;
59
- let garbageCollectionTime = 0;
60
- for (const [index, timeDelta] of timeDeltas.entries()) {
61
- sampledTime += timeDelta;
62
- const functionName = nodes.get(samples[index] ?? 0)?.callFrame.functionName;
63
- if (functionName === "(idle)") {
64
- idleTime += timeDelta;
65
- } else if (functionName === "(garbage collector)") {
66
- garbageCollectionTime += timeDelta;
67
- }
68
- }
69
- return {
70
- profileWindow: profile.endTime - profile.startTime,
71
- sampledTime,
72
- activeTime: sampledTime - idleTime,
73
- garbageCollectionTime,
74
- idleTime,
75
- sampleCount: samples.length
76
- };
58
+ const nodes = new Map(profile.nodes.map((node) => [node.id, node]));
59
+ const samples = profile.samples ?? [];
60
+ const timeDeltas = profile.timeDeltas ?? [];
61
+ let sampledTime = 0;
62
+ let idleTime = 0;
63
+ let garbageCollectionTime = 0;
64
+ for (const [index, timeDelta] of timeDeltas.entries()) {
65
+ sampledTime += timeDelta;
66
+ const functionName = nodes.get(samples[index] ?? 0)?.callFrame.functionName;
67
+ if (functionName === "(idle)") idleTime += timeDelta;
68
+ else if (functionName === "(garbage collector)") garbageCollectionTime += timeDelta;
69
+ }
70
+ return {
71
+ profileWindow: profile.endTime - profile.startTime,
72
+ sampledTime,
73
+ activeTime: sampledTime - idleTime,
74
+ garbageCollectionTime,
75
+ idleTime,
76
+ sampleCount: samples.length
77
+ };
77
78
  }
78
- __name(summarizeStartupProfile, "summarizeStartupProfile");
79
+ /**
80
+ * Runs a Worker upload locally and records its module-evaluation CPU profile.
81
+ *
82
+ * @param workerBundle - A serialized upload path or a parsed multipart upload.
83
+ * @returns A Chrome DevTools Protocol CPU profile.
84
+ */
79
85
  async function analyseBundle(workerBundle) {
80
- const parsedWorkerBundle = await parseWorkerBundle(workerBundle);
81
- const metadata = JSON.parse(
82
- parsedWorkerBundle.get("metadata")
83
- );
84
- if (typeof metadata.main_module !== "string") {
85
- throw new UserError(
86
- "Startup profiling does not support service-worker format Workers. Refer to https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ for migration guidance.",
87
- {
88
- telemetryMessage: "startup profiling service worker format unsupported"
89
- }
90
- );
91
- }
92
- const convertedBindings = await convertWorkerBundleBindings(
93
- parsedWorkerBundle,
94
- metadata.bindings
95
- );
96
- const mf = new Miniflare(
97
- convertV4MiniflareOptions({
98
- name: "profiler",
99
- compatibilityDate: typeof metadata.compatibility_date === "string" ? metadata.compatibility_date : void 0,
100
- compatibilityFlags: Array.isArray(metadata.compatibility_flags) ? metadata.compatibility_flags : void 0,
101
- ...convertedBindings.options,
102
- modulesRoot: "/",
103
- modules: [
104
- {
105
- type: "ESModule",
106
- // Keep the profiler entrypoint separate from all user module names.
107
- path: randomUUID(),
108
- contents: (
109
- /* javascript */
110
- `
86
+ const parsedWorkerBundle = await parseWorkerBundle(workerBundle);
87
+ const metadata = JSON.parse(parsedWorkerBundle.get("metadata"));
88
+ if (typeof metadata.main_module !== "string") throw new UserError("Startup profiling does not support service-worker format Workers. Refer to https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/ for migration guidance.", { telemetryMessage: "startup profiling service worker format unsupported" });
89
+ const convertedBindings = await convertWorkerBundleBindings(parsedWorkerBundle, metadata.bindings);
90
+ const mf = new Miniflare(convertV4MiniflareOptions({
91
+ name: "profiler",
92
+ compatibilityDate: typeof metadata.compatibility_date === "string" ? metadata.compatibility_date : void 0,
93
+ compatibilityFlags: Array.isArray(metadata.compatibility_flags) ? metadata.compatibility_flags : void 0,
94
+ ...convertedBindings.options,
95
+ modulesRoot: "/",
96
+ modules: [{
97
+ type: "ESModule",
98
+ path: randomUUID(),
99
+ contents: `
111
100
  async function startup() {
112
101
  await import(${JSON.stringify(metadata.main_module)});
113
102
  }
@@ -118,539 +107,432 @@ async function analyseBundle(workerBundle) {
118
107
  }
119
108
  }
120
109
  `
121
- )
122
- },
123
- ...await convertWorkerBundleToModules(parsedWorkerBundle)
124
- ],
125
- inspectorPort: 0,
126
- handleStructuredLogs: /* @__PURE__ */ __name(() => void 0, "handleStructuredLogs")
127
- })
128
- );
129
- const abortController = new AbortController();
130
- const timeout = setTimeout(() => {
131
- abortController.abort(
132
- new UserError(
133
- `Worker startup profiling timed out after ${STARTUP_PROFILE_TIMEOUT_MS / 1e3} seconds.`,
134
- { telemetryMessage: "startup profiling timed out" }
135
- )
136
- );
137
- }, STARTUP_PROFILE_TIMEOUT_MS);
138
- let ws;
139
- const onInspectorError = /* @__PURE__ */ __name((error) => abortController.abort(
140
- error instanceof Error ? error : new Error(`Worker startup profiler inspector error: ${String(error)}`)
141
- ), "onInspectorError");
142
- const onInspectorClose = /* @__PURE__ */ __name(() => abortController.abort(
143
- new Error("The Worker startup profiler inspector connection closed.")
144
- ), "onInspectorClose");
145
- try {
146
- await waitForPromise(mf.ready, abortController.signal);
147
- const inspectorUrl = await waitForPromise(
148
- mf.getInspectorURL(),
149
- abortController.signal
150
- );
151
- ws = new WebSocket(new URL("/core:user:profiler", inspectorUrl.href));
152
- ws.on("error", onInspectorError);
153
- ws.on("close", onInspectorClose);
154
- await waitForInspectorOpen(ws, abortController.signal);
155
- await sendInspectorCommand(
156
- ws,
157
- 1,
158
- "Profiler.enable",
159
- abortController.signal
160
- );
161
- await sendInspectorCommand(ws, 2, "Profiler.start", abortController.signal);
162
- const response = await waitForPromise(
163
- mf.dispatchFetch("https://example.com", {
164
- signal: abortController.signal
165
- }),
166
- abortController.signal
167
- );
168
- await waitForPromise(response.text(), abortController.signal);
169
- if (!response.ok && convertedBindings.unsupportedBindings.length > 0) {
170
- const unsupportedBindings = ` The upload contains bindings that cannot be reproduced locally during startup profiling: ${convertedBindings.unsupportedBindings.map(
171
- (binding) => `${JSON.stringify(binding.name)} (${JSON.stringify(binding.type)})`
172
- ).join(", ")}.`;
173
- throw new UserError(
174
- `Worker startup profiling failed during module evaluation (status ${response.status}).${unsupportedBindings}`,
175
- {
176
- telemetryMessage: "startup profiling module evaluation failed"
177
- }
178
- );
179
- }
180
- const stopResult = await sendInspectorCommand(ws, 3, "Profiler.stop", abortController.signal);
181
- if (stopResult?.profile === void 0) {
182
- throw new Error("Inspector command Profiler.stop returned no profile.");
183
- }
184
- return stopResult.profile;
185
- } finally {
186
- try {
187
- await mf.dispose();
188
- } finally {
189
- try {
190
- if (ws !== void 0) {
191
- ws.off("error", onInspectorError);
192
- ws.off("close", onInspectorClose);
193
- if (ws.readyState !== WebSocket.CLOSED) {
194
- ws.once("error", () => void 0);
195
- ws.terminate();
196
- }
197
- }
198
- } finally {
199
- clearTimeout(timeout);
200
- }
201
- }
202
- }
110
+ }, ...await convertWorkerBundleToModules(parsedWorkerBundle)],
111
+ inspectorPort: 0,
112
+ handleStructuredLogs: () => void 0
113
+ }));
114
+ const abortController = new AbortController();
115
+ const timeout = setTimeout(() => {
116
+ abortController.abort(new UserError(`Worker startup profiling timed out after ${STARTUP_PROFILE_TIMEOUT_MS / 1e3} seconds.`, { telemetryMessage: "startup profiling timed out" }));
117
+ }, STARTUP_PROFILE_TIMEOUT_MS);
118
+ let ws;
119
+ const onInspectorError = (error) => abortController.abort(error instanceof Error ? error : /* @__PURE__ */ new Error(`Worker startup profiler inspector error: ${String(error)}`));
120
+ const onInspectorClose = () => abortController.abort(/* @__PURE__ */ new Error("The Worker startup profiler inspector connection closed."));
121
+ try {
122
+ await waitForPromise(mf.ready, abortController.signal);
123
+ const inspectorUrl = await waitForPromise(mf.getInspectorURL(), abortController.signal);
124
+ ws = new WebSocket(new URL("/core:user:profiler", inspectorUrl.href));
125
+ ws.on("error", onInspectorError);
126
+ ws.on("close", onInspectorClose);
127
+ await waitForInspectorOpen(ws, abortController.signal);
128
+ await sendInspectorCommand(ws, 1, "Profiler.enable", abortController.signal);
129
+ await sendInspectorCommand(ws, 2, "Profiler.start", abortController.signal);
130
+ const response = await waitForPromise(mf.dispatchFetch("https://example.com", { signal: abortController.signal }), abortController.signal);
131
+ await waitForPromise(response.text(), abortController.signal);
132
+ if (!response.ok && convertedBindings.unsupportedBindings.length > 0) {
133
+ const unsupportedBindings = ` The upload contains bindings that cannot be reproduced locally during startup profiling: ${convertedBindings.unsupportedBindings.map((binding) => `${JSON.stringify(binding.name)} (${JSON.stringify(binding.type)})`).join(", ")}.`;
134
+ throw new UserError(`Worker startup profiling failed during module evaluation (status ${response.status}).${unsupportedBindings}`, { telemetryMessage: "startup profiling module evaluation failed" });
135
+ }
136
+ const stopResult = await sendInspectorCommand(ws, 3, "Profiler.stop", abortController.signal);
137
+ if (stopResult?.profile === void 0) throw new Error("Inspector command Profiler.stop returned no profile.");
138
+ return stopResult.profile;
139
+ } finally {
140
+ try {
141
+ await mf.dispose();
142
+ } finally {
143
+ try {
144
+ if (ws !== void 0) {
145
+ ws.off("error", onInspectorError);
146
+ ws.off("close", onInspectorClose);
147
+ if (ws.readyState !== WebSocket.CLOSED) {
148
+ ws.once("error", () => void 0);
149
+ ws.terminate();
150
+ }
151
+ }
152
+ } finally {
153
+ clearTimeout(timeout);
154
+ }
155
+ }
156
+ }
203
157
  }
204
- __name(analyseBundle, "analyseBundle");
205
158
  async function convertWorkerBundleBindings(workerBundle, bindings) {
206
- const agentMemory = {};
207
- let ai;
208
- const aiSearchInstances = {};
209
- const aiSearchNamespaces = {};
210
- const analyticsEngineDatasets = {};
211
- const artifacts = {};
212
- const miniflareBindings = {};
213
- let browserRendering;
214
- const dataBlobBindings = {};
215
- const d1Databases = {};
216
- const dispatchNamespaces = {};
217
- const sendEmailBindings = [];
218
- const flagship = {};
219
- const helloWorld = {};
220
- let images;
221
- const kvNamespaces = {};
222
- let media;
223
- const mtlsCertificates = {};
224
- const pipelines = {};
225
- const k2 = {};
226
- const queueProducers = {};
227
- const r2Buckets = {};
228
- const ratelimits = {};
229
- const secretsStoreSecrets = {};
230
- const serviceBindings = {};
231
- let stream;
232
- const vectorize = {};
233
- let versionMetadata;
234
- const vpcNetworks = {};
235
- const vpcServices = {};
236
- const workerLoaders = {};
237
- const unsupportedBindings = [];
238
- for (const value of Array.isArray(bindings) ? bindings : []) {
239
- if (!isNamedWorkerBinding(value)) {
240
- unsupportedBindings.push({ name: "<unknown>", type: "unknown" });
241
- continue;
242
- }
243
- const binding = value;
244
- if (isRawWorkerBinding(binding)) {
245
- serviceBindings[binding.name] = createOfflineFetcherBinding();
246
- continue;
247
- }
248
- switch (binding.type) {
249
- case "plain_text":
250
- case "secret_text":
251
- miniflareBindings[binding.name] = binding.text;
252
- break;
253
- case "json":
254
- miniflareBindings[binding.name] = binding.json;
255
- break;
256
- case "text_blob":
257
- miniflareBindings[binding.name] = await getTextBindingPart(
258
- workerBundle,
259
- binding
260
- );
261
- break;
262
- case "data_blob":
263
- dataBlobBindings[binding.name] = await getBinaryBindingPart(
264
- workerBundle,
265
- binding
266
- );
267
- break;
268
- case "kv_namespace":
269
- kvNamespaces[binding.name] = { id: binding.namespace_id };
270
- break;
271
- case "d1":
272
- d1Databases[binding.name] = { id: binding.id };
273
- break;
274
- case "r2_bucket":
275
- r2Buckets[binding.name] = { id: binding.bucket_name };
276
- break;
277
- case "queue":
278
- queueProducers[binding.name] = {
279
- queueName: binding.queue_name,
280
- deliveryDelay: binding.delivery_delay
281
- };
282
- break;
283
- case "service":
284
- serviceBindings[binding.name] = createOfflineFetcherBinding();
285
- unsupportedBindings.push(binding);
286
- break;
287
- case "assets":
288
- serviceBindings[binding.name] = createOfflineFetcherBinding();
289
- break;
290
- case "browser":
291
- browserRendering = { binding: binding.name };
292
- break;
293
- case "ai":
294
- ai = { binding: binding.name };
295
- break;
296
- case "images":
297
- images = { binding: binding.name };
298
- break;
299
- case "stream":
300
- stream = { binding: binding.name };
301
- break;
302
- case "version_metadata":
303
- versionMetadata = binding.name;
304
- break;
305
- case "ai_search_namespace":
306
- aiSearchNamespaces[binding.name] = {
307
- namespace: binding.namespace
308
- };
309
- break;
310
- case "ai_search":
311
- aiSearchInstances[binding.name] = {
312
- instance_name: binding.instance_name
313
- };
314
- break;
315
- case "agent_memory":
316
- agentMemory[binding.name] = { namespace: binding.namespace };
317
- break;
318
- case "media":
319
- media = { binding: binding.name };
320
- break;
321
- case "send_email": {
322
- const shared = {
323
- name: binding.name,
324
- allowed_sender_addresses: binding.allowed_sender_addresses
325
- };
326
- if (binding.destination_address !== void 0) {
327
- sendEmailBindings.push({
328
- ...shared,
329
- destination_address: binding.destination_address
330
- });
331
- } else if (binding.allowed_destination_addresses !== void 0) {
332
- sendEmailBindings.push({
333
- ...shared,
334
- allowed_destination_addresses: binding.allowed_destination_addresses
335
- });
336
- } else {
337
- sendEmailBindings.push(shared);
338
- }
339
- break;
340
- }
341
- case "durable_object_namespace":
342
- case "workflow":
343
- unsupportedBindings.push(binding);
344
- break;
345
- case "vectorize":
346
- vectorize[binding.name] = { index_name: binding.index_name };
347
- break;
348
- case "analytics_engine":
349
- analyticsEngineDatasets[binding.name] = {
350
- dataset: binding.dataset ?? "dataset"
351
- };
352
- break;
353
- case "dispatch_namespace":
354
- dispatchNamespaces[binding.name] = {
355
- namespace: binding.namespace
356
- };
357
- break;
358
- case "mtls_certificate":
359
- mtlsCertificates[binding.name] = {
360
- certificate_id: binding.certificate_id
361
- };
362
- break;
363
- case "pipelines":
364
- if (binding.stream !== void 0) {
365
- pipelines[binding.name] = { stream: binding.stream };
366
- } else if (binding.pipeline !== void 0) {
367
- pipelines[binding.name] = { pipeline: binding.pipeline };
368
- } else {
369
- unsupportedBindings.push(binding);
370
- }
371
- break;
372
- case "k2":
373
- k2[binding.name] = { stream: binding.stream };
374
- break;
375
- case "secrets_store_secret":
376
- secretsStoreSecrets[binding.name] = {
377
- store_id: binding.store_id,
378
- secret_name: binding.secret_name
379
- };
380
- break;
381
- case "artifacts":
382
- artifacts[binding.name] = { namespace: binding.namespace };
383
- break;
384
- case "unsafe_hello_world":
385
- helloWorld[binding.name] = {
386
- enable_timer: binding.enable_timer
387
- };
388
- break;
389
- case "flagship":
390
- flagship[binding.name] = { app_id: binding.app_id };
391
- break;
392
- case "ratelimit":
393
- ratelimits[binding.name] = {
394
- namespace_id: binding.namespace_id,
395
- simple: binding.simple
396
- };
397
- break;
398
- case "vpc_service":
399
- vpcServices[binding.name] = { service_id: binding.service_id };
400
- break;
401
- case "vpc_network":
402
- if (binding.tunnel_id !== void 0) {
403
- vpcNetworks[binding.name] = { tunnel_id: binding.tunnel_id };
404
- } else if (binding.network_id !== void 0) {
405
- vpcNetworks[binding.name] = { network_id: binding.network_id };
406
- } else {
407
- unsupportedBindings.push(binding);
408
- }
409
- break;
410
- case "worker_loader":
411
- workerLoaders[binding.name] = {};
412
- break;
413
- case "inherit":
414
- unsupportedBindings.push(binding);
415
- break;
416
- case "wasm_module":
417
- unsupportedBindings.push(binding);
418
- break;
419
- case "hyperdrive":
420
- unsupportedBindings.push(binding);
421
- break;
422
- case "logfwdr":
423
- unsupportedBindings.push(binding);
424
- break;
425
- case "analytics":
426
- unsupportedBindings.push(binding);
427
- break;
428
- default: {
429
- const unknownBinding = binding;
430
- unsupportedBindings.push(unknownBinding);
431
- }
432
- }
433
- }
434
- return {
435
- options: {
436
- agentMemory,
437
- ai,
438
- aiSearchInstances,
439
- aiSearchNamespaces,
440
- analyticsEngineDatasets,
441
- artifacts,
442
- bindings: miniflareBindings,
443
- browserRendering,
444
- dataBlobBindings,
445
- d1Databases,
446
- dispatchNamespaces,
447
- email: { send_email: sendEmailBindings },
448
- flagship,
449
- helloWorld,
450
- images,
451
- kvNamespaces,
452
- media,
453
- mtlsCertificates,
454
- pipelines,
455
- k2,
456
- queueProducers,
457
- r2Buckets,
458
- ratelimits,
459
- secretsStoreSecrets,
460
- serviceBindings,
461
- stream,
462
- vectorize,
463
- versionMetadata,
464
- vpcNetworks,
465
- vpcServices,
466
- workerLoaders
467
- },
468
- unsupportedBindings
469
- };
159
+ const agentMemory = {};
160
+ let ai;
161
+ const aiSearchInstances = {};
162
+ const aiSearchNamespaces = {};
163
+ const analyticsEngineDatasets = {};
164
+ const artifacts = {};
165
+ const miniflareBindings = {};
166
+ let browserRendering;
167
+ const dataBlobBindings = {};
168
+ const d1Databases = {};
169
+ const dispatchNamespaces = {};
170
+ const sendEmailBindings = [];
171
+ const flagship = {};
172
+ const helloWorld = {};
173
+ let images;
174
+ const kvNamespaces = {};
175
+ let media;
176
+ const mtlsCertificates = {};
177
+ const pipelines = {};
178
+ const k2 = {};
179
+ const queueProducers = {};
180
+ const r2Buckets = {};
181
+ const ratelimits = {};
182
+ const secretsStoreSecrets = {};
183
+ const serviceBindings = {};
184
+ let stream;
185
+ const vectorize = {};
186
+ let versionMetadata;
187
+ const vpcNetworks = {};
188
+ const vpcServices = {};
189
+ const workerLoaders = {};
190
+ const unsupportedBindings = [];
191
+ for (const value of Array.isArray(bindings) ? bindings : []) {
192
+ if (!isNamedWorkerBinding(value)) {
193
+ unsupportedBindings.push({
194
+ name: "<unknown>",
195
+ type: "unknown"
196
+ });
197
+ continue;
198
+ }
199
+ const binding = value;
200
+ if (isRawWorkerBinding(binding)) {
201
+ serviceBindings[binding.name] = createOfflineFetcherBinding();
202
+ continue;
203
+ }
204
+ switch (binding.type) {
205
+ case "plain_text":
206
+ case "secret_text":
207
+ miniflareBindings[binding.name] = binding.text;
208
+ break;
209
+ case "json":
210
+ miniflareBindings[binding.name] = binding.json;
211
+ break;
212
+ case "text_blob":
213
+ miniflareBindings[binding.name] = await getTextBindingPart(workerBundle, binding);
214
+ break;
215
+ case "data_blob":
216
+ dataBlobBindings[binding.name] = await getBinaryBindingPart(workerBundle, binding);
217
+ break;
218
+ case "kv_namespace":
219
+ kvNamespaces[binding.name] = { id: binding.namespace_id };
220
+ break;
221
+ case "d1":
222
+ d1Databases[binding.name] = { id: binding.id };
223
+ break;
224
+ case "r2_bucket":
225
+ r2Buckets[binding.name] = { id: binding.bucket_name };
226
+ break;
227
+ case "queue":
228
+ queueProducers[binding.name] = {
229
+ queueName: binding.queue_name,
230
+ deliveryDelay: binding.delivery_delay
231
+ };
232
+ break;
233
+ case "service":
234
+ serviceBindings[binding.name] = createOfflineFetcherBinding();
235
+ unsupportedBindings.push(binding);
236
+ break;
237
+ case "assets":
238
+ serviceBindings[binding.name] = createOfflineFetcherBinding();
239
+ break;
240
+ case "browser":
241
+ browserRendering = { binding: binding.name };
242
+ break;
243
+ case "ai":
244
+ ai = { binding: binding.name };
245
+ break;
246
+ case "images":
247
+ images = { binding: binding.name };
248
+ break;
249
+ case "stream":
250
+ stream = { binding: binding.name };
251
+ break;
252
+ case "version_metadata":
253
+ versionMetadata = binding.name;
254
+ break;
255
+ case "ai_search_namespace":
256
+ aiSearchNamespaces[binding.name] = { namespace: binding.namespace };
257
+ break;
258
+ case "ai_search":
259
+ aiSearchInstances[binding.name] = { instance_name: binding.instance_name };
260
+ break;
261
+ case "agent_memory":
262
+ agentMemory[binding.name] = { namespace: binding.namespace };
263
+ break;
264
+ case "media":
265
+ media = { binding: binding.name };
266
+ break;
267
+ case "send_email": {
268
+ const shared = {
269
+ name: binding.name,
270
+ allowed_sender_addresses: binding.allowed_sender_addresses
271
+ };
272
+ if (binding.destination_address !== void 0) sendEmailBindings.push({
273
+ ...shared,
274
+ destination_address: binding.destination_address
275
+ });
276
+ else if (binding.allowed_destination_addresses !== void 0) sendEmailBindings.push({
277
+ ...shared,
278
+ allowed_destination_addresses: binding.allowed_destination_addresses
279
+ });
280
+ else sendEmailBindings.push(shared);
281
+ break;
282
+ }
283
+ case "durable_object_namespace":
284
+ case "workflow":
285
+ unsupportedBindings.push(binding);
286
+ break;
287
+ case "vectorize":
288
+ vectorize[binding.name] = { index_name: binding.index_name };
289
+ break;
290
+ case "analytics_engine":
291
+ analyticsEngineDatasets[binding.name] = { dataset: binding.dataset ?? "dataset" };
292
+ break;
293
+ case "dispatch_namespace":
294
+ dispatchNamespaces[binding.name] = { namespace: binding.namespace };
295
+ break;
296
+ case "mtls_certificate":
297
+ mtlsCertificates[binding.name] = { certificate_id: binding.certificate_id };
298
+ break;
299
+ case "pipelines":
300
+ if (binding.stream !== void 0) pipelines[binding.name] = { stream: binding.stream };
301
+ else if (binding.pipeline !== void 0) pipelines[binding.name] = { pipeline: binding.pipeline };
302
+ else unsupportedBindings.push(binding);
303
+ break;
304
+ case "k2":
305
+ k2[binding.name] = { stream: binding.stream };
306
+ break;
307
+ case "secrets_store_secret":
308
+ secretsStoreSecrets[binding.name] = {
309
+ store_id: binding.store_id,
310
+ secret_name: binding.secret_name
311
+ };
312
+ break;
313
+ case "artifacts":
314
+ artifacts[binding.name] = { namespace: binding.namespace };
315
+ break;
316
+ case "unsafe_hello_world":
317
+ helloWorld[binding.name] = { enable_timer: binding.enable_timer };
318
+ break;
319
+ case "flagship":
320
+ flagship[binding.name] = { app_id: binding.app_id };
321
+ break;
322
+ case "ratelimit":
323
+ ratelimits[binding.name] = {
324
+ namespace_id: binding.namespace_id,
325
+ simple: binding.simple
326
+ };
327
+ break;
328
+ case "vpc_service":
329
+ vpcServices[binding.name] = { service_id: binding.service_id };
330
+ break;
331
+ case "vpc_network":
332
+ if (binding.tunnel_id !== void 0) vpcNetworks[binding.name] = { tunnel_id: binding.tunnel_id };
333
+ else if (binding.network_id !== void 0) vpcNetworks[binding.name] = { network_id: binding.network_id };
334
+ else unsupportedBindings.push(binding);
335
+ break;
336
+ case "worker_loader":
337
+ workerLoaders[binding.name] = {};
338
+ break;
339
+ case "inherit":
340
+ unsupportedBindings.push(binding);
341
+ break;
342
+ case "wasm_module":
343
+ unsupportedBindings.push(binding);
344
+ break;
345
+ case "hyperdrive":
346
+ unsupportedBindings.push(binding);
347
+ break;
348
+ case "logfwdr":
349
+ unsupportedBindings.push(binding);
350
+ break;
351
+ case "analytics":
352
+ unsupportedBindings.push(binding);
353
+ break;
354
+ default: {
355
+ const unknownBinding = binding;
356
+ unsupportedBindings.push(unknownBinding);
357
+ }
358
+ }
359
+ }
360
+ return {
361
+ options: {
362
+ agentMemory,
363
+ ai,
364
+ aiSearchInstances,
365
+ aiSearchNamespaces,
366
+ analyticsEngineDatasets,
367
+ artifacts,
368
+ bindings: miniflareBindings,
369
+ browserRendering,
370
+ dataBlobBindings,
371
+ d1Databases,
372
+ dispatchNamespaces,
373
+ email: { send_email: sendEmailBindings },
374
+ flagship,
375
+ helloWorld,
376
+ images,
377
+ kvNamespaces,
378
+ media,
379
+ mtlsCertificates,
380
+ pipelines,
381
+ k2,
382
+ queueProducers,
383
+ r2Buckets,
384
+ ratelimits,
385
+ secretsStoreSecrets,
386
+ serviceBindings,
387
+ stream,
388
+ vectorize,
389
+ versionMetadata,
390
+ vpcNetworks,
391
+ vpcServices,
392
+ workerLoaders
393
+ },
394
+ unsupportedBindings
395
+ };
470
396
  }
471
- __name(convertWorkerBundleBindings, "convertWorkerBundleBindings");
472
397
  function isRawWorkerBinding(binding) {
473
- switch (binding.type) {
474
- case "browser":
475
- case "ai":
476
- case "images":
477
- case "kv_namespace":
478
- case "workflow":
479
- case "queue":
480
- case "r2_bucket":
481
- case "d1":
482
- case "vectorize":
483
- return binding.raw === true;
484
- default:
485
- return false;
486
- }
398
+ switch (binding.type) {
399
+ case "browser":
400
+ case "ai":
401
+ case "images":
402
+ case "kv_namespace":
403
+ case "workflow":
404
+ case "queue":
405
+ case "r2_bucket":
406
+ case "d1":
407
+ case "vectorize": return binding.raw === true;
408
+ default: return false;
409
+ }
487
410
  }
488
- __name(isRawWorkerBinding, "isRawWorkerBinding");
489
411
  function isNamedWorkerBinding(value) {
490
- return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && "type" in value && typeof value.type === "string";
412
+ return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && "type" in value && typeof value.type === "string";
491
413
  }
492
- __name(isNamedWorkerBinding, "isNamedWorkerBinding");
493
414
  function createOfflineFetcherBinding() {
494
- return () => new Response("Binding calls are unavailable during startup profiling.", {
495
- status: 503
496
- });
415
+ return () => new Response("Binding calls are unavailable during startup profiling.", { status: 503 });
497
416
  }
498
- __name(createOfflineFetcherBinding, "createOfflineFetcherBinding");
499
417
  async function getBinaryBindingPart(workerBundle, binding) {
500
- const part = getBindingPart(workerBundle, binding);
501
- return part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : new TextEncoder().encode(part);
418
+ const part = getBindingPart(workerBundle, binding);
419
+ return part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : new TextEncoder().encode(part);
502
420
  }
503
- __name(getBinaryBindingPart, "getBinaryBindingPart");
504
421
  async function getTextBindingPart(workerBundle, binding) {
505
- const part = getBindingPart(workerBundle, binding);
506
- return part instanceof Blob ? await part.text() : part;
422
+ const part = getBindingPart(workerBundle, binding);
423
+ return part instanceof Blob ? await part.text() : part;
507
424
  }
508
- __name(getTextBindingPart, "getTextBindingPart");
509
425
  function getBindingPart(workerBundle, binding) {
510
- const part = workerBundle.get(binding.part);
511
- if (part === null) {
512
- throw new UserError(
513
- `Startup profiling could not find multipart part ${JSON.stringify(binding.part)} for binding ${JSON.stringify(binding.name)}.`,
514
- { telemetryMessage: "startup profiling binding part missing" }
515
- );
516
- }
517
- return part;
426
+ const part = workerBundle.get(binding.part);
427
+ if (part === null) throw new UserError(`Startup profiling could not find multipart part ${JSON.stringify(binding.part)} for binding ${JSON.stringify(binding.name)}.`, { telemetryMessage: "startup profiling binding part missing" });
428
+ return part;
518
429
  }
519
- __name(getBindingPart, "getBindingPart");
520
430
  async function waitForPromise(promise, signal) {
521
- if (signal.aborted) {
522
- throw signal.reason;
523
- }
524
- return await new Promise((resolve, reject) => {
525
- const onAbort = /* @__PURE__ */ __name(() => reject(signal.reason), "onAbort");
526
- signal.addEventListener("abort", onAbort, { once: true });
527
- void promise.then(resolve, reject).finally(() => {
528
- signal.removeEventListener("abort", onAbort);
529
- });
530
- });
431
+ if (signal.aborted) throw signal.reason;
432
+ return await new Promise((resolve, reject) => {
433
+ const onAbort = () => reject(signal.reason);
434
+ signal.addEventListener("abort", onAbort, { once: true });
435
+ promise.then(resolve, reject).finally(() => {
436
+ signal.removeEventListener("abort", onAbort);
437
+ });
438
+ });
531
439
  }
532
- __name(waitForPromise, "waitForPromise");
533
440
  async function waitForInspectorOpen(ws, signal) {
534
- if (signal.aborted) {
535
- throw signal.reason;
536
- }
537
- return await new Promise((resolve, reject) => {
538
- const cleanup = /* @__PURE__ */ __name(() => {
539
- ws.off("open", onOpen);
540
- ws.off("error", onError);
541
- ws.off("close", onClose);
542
- signal.removeEventListener("abort", onAbort);
543
- }, "cleanup");
544
- const onOpen = /* @__PURE__ */ __name(() => {
545
- cleanup();
546
- resolve();
547
- }, "onOpen");
548
- const onError = /* @__PURE__ */ __name((error) => {
549
- cleanup();
550
- reject(error);
551
- }, "onError");
552
- const onClose = /* @__PURE__ */ __name(() => {
553
- cleanup();
554
- reject(
555
- new Error("The Worker startup profiler inspector connection closed.")
556
- );
557
- }, "onClose");
558
- const onAbort = /* @__PURE__ */ __name(() => {
559
- cleanup();
560
- reject(signal.reason);
561
- }, "onAbort");
562
- ws.once("open", onOpen);
563
- ws.once("error", onError);
564
- ws.once("close", onClose);
565
- signal.addEventListener("abort", onAbort, { once: true });
566
- });
441
+ if (signal.aborted) throw signal.reason;
442
+ return await new Promise((resolve, reject) => {
443
+ const cleanup = () => {
444
+ ws.off("open", onOpen);
445
+ ws.off("error", onError);
446
+ ws.off("close", onClose);
447
+ signal.removeEventListener("abort", onAbort);
448
+ };
449
+ const onOpen = () => {
450
+ cleanup();
451
+ resolve();
452
+ };
453
+ const onError = (error) => {
454
+ cleanup();
455
+ reject(error);
456
+ };
457
+ const onClose = () => {
458
+ cleanup();
459
+ reject(/* @__PURE__ */ new Error("The Worker startup profiler inspector connection closed."));
460
+ };
461
+ const onAbort = () => {
462
+ cleanup();
463
+ reject(signal.reason);
464
+ };
465
+ ws.once("open", onOpen);
466
+ ws.once("error", onError);
467
+ ws.once("close", onClose);
468
+ signal.addEventListener("abort", onAbort, { once: true });
469
+ });
567
470
  }
568
- __name(waitForInspectorOpen, "waitForInspectorOpen");
569
471
  async function sendInspectorCommand(ws, id, method, signal) {
570
- if (signal.aborted) {
571
- throw signal.reason;
572
- }
573
- return await new Promise((resolve, reject) => {
574
- const cleanup = /* @__PURE__ */ __name(() => {
575
- ws.off("message", onMessage);
576
- signal.removeEventListener("abort", onAbort);
577
- }, "cleanup");
578
- const onMessage = /* @__PURE__ */ __name((rawData) => {
579
- let message;
580
- try {
581
- message = JSON.parse(rawData.toString());
582
- } catch (error) {
583
- cleanup();
584
- reject(error);
585
- return;
586
- }
587
- if (message.id !== id) {
588
- return;
589
- }
590
- cleanup();
591
- if (message.error != null) {
592
- reject(
593
- new Error(
594
- `Inspector command ${method} failed: ${message.error.message ?? `error ${message.error.code ?? "unknown"}`}`
595
- )
596
- );
597
- return;
598
- }
599
- resolve(message.result);
600
- }, "onMessage");
601
- const onAbort = /* @__PURE__ */ __name(() => {
602
- cleanup();
603
- reject(signal.reason);
604
- }, "onAbort");
605
- ws.on("message", onMessage);
606
- signal.addEventListener("abort", onAbort, { once: true });
607
- try {
608
- ws.send(JSON.stringify({ id, method, params: {} }), (error) => {
609
- if (error) {
610
- cleanup();
611
- reject(error);
612
- }
613
- });
614
- } catch (error) {
615
- cleanup();
616
- reject(error);
617
- }
618
- });
472
+ if (signal.aborted) throw signal.reason;
473
+ return await new Promise((resolve, reject) => {
474
+ const cleanup = () => {
475
+ ws.off("message", onMessage);
476
+ signal.removeEventListener("abort", onAbort);
477
+ };
478
+ const onMessage = (rawData) => {
479
+ let message;
480
+ try {
481
+ message = JSON.parse(rawData.toString());
482
+ } catch (error) {
483
+ cleanup();
484
+ reject(error);
485
+ return;
486
+ }
487
+ if (message.id !== id) return;
488
+ cleanup();
489
+ if (message.error != null) {
490
+ reject(/* @__PURE__ */ new Error(`Inspector command ${method} failed: ${message.error.message ?? `error ${message.error.code ?? "unknown"}`}`));
491
+ return;
492
+ }
493
+ resolve(message.result);
494
+ };
495
+ const onAbort = () => {
496
+ cleanup();
497
+ reject(signal.reason);
498
+ };
499
+ ws.on("message", onMessage);
500
+ signal.addEventListener("abort", onAbort, { once: true });
501
+ try {
502
+ ws.send(JSON.stringify({
503
+ id,
504
+ method,
505
+ params: {}
506
+ }), (error) => {
507
+ if (error) {
508
+ cleanup();
509
+ reject(error);
510
+ }
511
+ });
512
+ } catch (error) {
513
+ cleanup();
514
+ reject(error);
515
+ }
516
+ });
619
517
  }
620
- __name(sendInspectorCommand, "sendInspectorCommand");
621
518
  async function getEntryValue(entry) {
622
- if (entry instanceof Blob) {
623
- return new Uint8Array(await entry.arrayBuffer());
624
- }
625
- return entry;
519
+ if (entry instanceof Blob) return new Uint8Array(await entry.arrayBuffer());
520
+ return entry;
626
521
  }
627
- __name(getEntryValue, "getEntryValue");
628
522
  function getModuleType(entry) {
629
- if (entry instanceof Blob) {
630
- try {
631
- return MODULE_TYPE_TO_MINIFLARE_TYPE[fromMimeType(entry.type)];
632
- } catch {
633
- throw new Error(
634
- `Unable to determine module type for ${entry.type} mime type`
635
- );
636
- }
637
- }
638
- return "Text";
523
+ if (entry instanceof Blob) try {
524
+ return MODULE_TYPE_TO_MINIFLARE_TYPE[fromMimeType(entry.type)];
525
+ } catch {
526
+ throw new Error(`Unable to determine module type for ${entry.type} mime type`);
527
+ }
528
+ return "Text";
639
529
  }
640
- __name(getModuleType, "getModuleType");
641
530
  async function convertWorkerBundleToModules(workerBundle) {
642
- return await Promise.all(
643
- [...workerBundle.entries()].filter(
644
- (module) => module[1] instanceof Blob && module[1].type !== "application/source-map"
645
- ).map(
646
- async ([modulePath, entry]) => ({
647
- type: getModuleType(entry),
648
- path: modulePath,
649
- contents: await getEntryValue(entry)
650
- })
651
- )
652
- );
531
+ return await Promise.all([...workerBundle.entries()].filter((module) => module[1] instanceof Blob && module[1].type !== "application/source-map").map(async ([modulePath, entry]) => ({
532
+ type: getModuleType(entry),
533
+ path: modulePath,
534
+ contents: await getEntryValue(entry)
535
+ })));
653
536
  }
654
- __name(convertWorkerBundleToModules, "convertWorkerBundleToModules");
655
-
537
+ //#endregion
656
538
  export { analyseBundle, getBundleSize, parseWorkerBundle, summarizeStartupProfile };