alchemy 0.1.12 → 0.1.13

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.
Files changed (103) hide show
  1. package/lib/$.d.ts +12 -0
  2. package/lib/$.d.ts.map +1 -0
  3. package/lib/$.js +42 -0
  4. package/lib/$.js.map +1 -0
  5. package/lib/alchemize.d.ts.map +1 -1
  6. package/lib/alchemize.js +7 -0
  7. package/lib/alchemize.js.map +1 -1
  8. package/lib/apply.d.ts +2 -2
  9. package/lib/apply.d.ts.map +1 -1
  10. package/lib/apply.js +1 -1
  11. package/lib/apply.js.map +1 -1
  12. package/lib/cloudflare/api.d.ts +4 -0
  13. package/lib/cloudflare/api.d.ts.map +1 -1
  14. package/lib/cloudflare/api.js +6 -0
  15. package/lib/cloudflare/api.js.map +1 -1
  16. package/lib/cloudflare/bindings.d.ts +14 -4
  17. package/lib/cloudflare/bindings.d.ts.map +1 -1
  18. package/lib/cloudflare/bindings.js +0 -5
  19. package/lib/cloudflare/bindings.js.map +1 -1
  20. package/lib/cloudflare/durable-object-namespace.d.ts +23 -0
  21. package/lib/cloudflare/durable-object-namespace.d.ts.map +1 -0
  22. package/lib/cloudflare/durable-object-namespace.js +26 -0
  23. package/lib/cloudflare/durable-object-namespace.js.map +1 -0
  24. package/lib/cloudflare/index.d.ts +1 -0
  25. package/lib/cloudflare/index.d.ts.map +1 -1
  26. package/lib/cloudflare/index.js +1 -0
  27. package/lib/cloudflare/index.js.map +1 -1
  28. package/lib/cloudflare/kv-namespace.js +1 -1
  29. package/lib/cloudflare/kv-namespace.js.map +1 -1
  30. package/lib/cloudflare/static-site-router.d.ts +11 -2
  31. package/lib/cloudflare/static-site-router.d.ts.map +1 -1
  32. package/lib/cloudflare/static-site-router.js +98 -76
  33. package/lib/cloudflare/static-site-router.js.map +1 -1
  34. package/lib/cloudflare/static-site.d.ts +15 -15
  35. package/lib/cloudflare/static-site.d.ts.map +1 -1
  36. package/lib/cloudflare/static-site.js +41 -25
  37. package/lib/cloudflare/static-site.js.map +1 -1
  38. package/lib/cloudflare/worker-metadata.d.ts +130 -0
  39. package/lib/cloudflare/worker-metadata.d.ts.map +1 -0
  40. package/lib/cloudflare/worker-metadata.js +2 -0
  41. package/lib/cloudflare/worker-metadata.js.map +1 -0
  42. package/lib/cloudflare/worker-migration.d.ts +110 -0
  43. package/lib/cloudflare/worker-migration.d.ts.map +1 -0
  44. package/lib/cloudflare/worker-migration.js +11 -0
  45. package/lib/cloudflare/worker-migration.js.map +1 -0
  46. package/lib/cloudflare/worker.d.ts +29 -11
  47. package/lib/cloudflare/worker.d.ts.map +1 -1
  48. package/lib/cloudflare/worker.js +316 -322
  49. package/lib/cloudflare/worker.js.map +1 -1
  50. package/lib/destroy.d.ts +1 -1
  51. package/lib/destroy.d.ts.map +1 -1
  52. package/lib/destroy.js +2 -1
  53. package/lib/destroy.js.map +1 -1
  54. package/lib/esbuild.d.ts +1 -1
  55. package/lib/esbuild.d.ts.map +1 -1
  56. package/lib/esbuild.js +3 -1
  57. package/lib/esbuild.js.map +1 -1
  58. package/lib/global.d.ts +0 -2
  59. package/lib/global.d.ts.map +1 -1
  60. package/lib/global.js +0 -2
  61. package/lib/global.js.map +1 -1
  62. package/lib/index.d.ts +2 -0
  63. package/lib/index.d.ts.map +1 -1
  64. package/lib/index.js +2 -0
  65. package/lib/index.js.map +1 -1
  66. package/lib/output.d.ts +4 -3
  67. package/lib/output.d.ts.map +1 -1
  68. package/lib/output.js +10 -3
  69. package/lib/output.js.map +1 -1
  70. package/lib/print.d.ts +7 -0
  71. package/lib/print.d.ts.map +1 -0
  72. package/lib/print.js +10 -0
  73. package/lib/print.js.map +1 -0
  74. package/lib/resource.d.ts +8 -4
  75. package/lib/resource.d.ts.map +1 -1
  76. package/lib/resource.js +125 -91
  77. package/lib/resource.js.map +1 -1
  78. package/lib/scope.d.ts +3 -0
  79. package/lib/scope.d.ts.map +1 -1
  80. package/lib/scope.js +4 -12
  81. package/lib/scope.js.map +1 -1
  82. package/package.json +3 -2
  83. package/src/$.ts +69 -0
  84. package/src/alchemize.ts +12 -0
  85. package/src/apply.ts +4 -4
  86. package/src/cloudflare/api.ts +6 -0
  87. package/src/cloudflare/bindings.ts +37 -26
  88. package/src/cloudflare/durable-object-namespace.ts +43 -0
  89. package/src/cloudflare/index.ts +1 -0
  90. package/src/cloudflare/kv-namespace.ts +1 -1
  91. package/src/cloudflare/static-site-router.ts +124 -82
  92. package/src/cloudflare/static-site.ts +63 -47
  93. package/src/cloudflare/worker-metadata.ts +154 -0
  94. package/src/cloudflare/worker-migration.ts +145 -0
  95. package/src/cloudflare/worker.ts +526 -428
  96. package/src/destroy.ts +2 -2
  97. package/src/esbuild.ts +3 -0
  98. package/src/global.ts +0 -3
  99. package/src/index.ts +2 -1
  100. package/src/output.ts +24 -8
  101. package/src/print.ts +18 -0
  102. package/src/resource.ts +156 -115
  103. package/src/scope.ts +7 -12
@@ -2,9 +2,12 @@ import * as fs from "fs/promises";
2
2
  import { apply } from "../apply";
3
3
  import { Bundle, type BundleProps } from "../esbuild";
4
4
  import { type Context, Resource } from "../resource";
5
- import { createCloudflareApi } from "./api";
6
- import type { WorkerBinding } from "./bindings";
7
-
5
+ import { type CloudflareApi, createCloudflareApi } from "./api";
6
+ import type { WorkerBinding, WorkerBindingSpec } from "./bindings";
7
+ import type { DurableObjectNamespace } from "./durable-object-namespace";
8
+ import { isDurableObjectNamespace } from "./durable-object-namespace";
9
+ import type { WorkerScriptMetadata } from "./worker-metadata";
10
+ import type { SingleStepMigration } from "./worker-migration";
8
11
  /**
9
12
  * Properties for creating or updating a Worker
10
13
  */
@@ -22,17 +25,11 @@ export interface WorkerProps {
22
25
  */
23
26
  entrypoint?: string;
24
27
 
25
- /**
26
- * Reference to a pre-configured Bundle resource
27
- * One of script, entryPoint, or bundle must be provided
28
- */
29
- bundle?: Bundle;
30
-
31
28
  /**
32
29
  * Bundle options when using entryPoint
33
30
  * Ignored if bundle is provided
34
31
  */
35
- bundleOptions?: Omit<BundleProps, "entryPoint">;
32
+ bundle?: Omit<BundleProps, "entryPoint">;
36
33
 
37
34
  /**
38
35
  * Module format for the worker script
@@ -60,10 +57,12 @@ export interface WorkerProps {
60
57
  bindings?: WorkerBinding[];
61
58
 
62
59
  /**
63
- * Whether the worker should be deployed to production
64
- * @default true
60
+ * Environment variables to attach to the worker
61
+ * These will be converted to plain_text bindings
65
62
  */
66
- production?: boolean;
63
+ env?: {
64
+ [key: string]: string;
65
+ };
67
66
 
68
67
  /**
69
68
  * Whether to enable a workers.dev URL for this worker
@@ -71,6 +70,24 @@ export interface WorkerProps {
71
70
  * @default false
72
71
  */
73
72
  url?: boolean;
73
+
74
+ /**
75
+ * Observability configuration for the worker
76
+ * Controls whether worker logs are enabled
77
+ * @default { enabled: true }
78
+ */
79
+ observability?: {
80
+ /**
81
+ * Whether to enable worker logs
82
+ * @default true
83
+ */
84
+ enabled?: boolean;
85
+ };
86
+
87
+ /**
88
+ * Migrations to apply to the worker
89
+ */
90
+ migrations?: SingleStepMigration;
74
91
  }
75
92
 
76
93
  /**
@@ -97,472 +114,553 @@ export interface WorkerOutput extends Omit<WorkerProps, "url"> {
97
114
  * Format: {name}.{subdomain}.workers.dev
98
115
  */
99
116
  url?: string;
117
+
118
+ /**
119
+ * The bindings that were created
120
+ */
121
+ bindings: WorkerBinding[];
100
122
  }
101
123
 
102
124
  export class Worker extends Resource(
103
125
  "cloudflare::Worker",
126
+ {
127
+ alwaysUpdate: true,
128
+ },
104
129
  async (ctx: Context<WorkerOutput>, props: WorkerProps) => {
105
130
  // Create Cloudflare API client with automatic account discovery
106
131
  const api = await createCloudflareApi();
107
132
 
108
- // Validate that a name is provided
109
- if (!props.name) {
110
- throw new Error("Worker name is required - must be explicitly specified");
111
- }
112
-
113
133
  // Use the provided name
114
134
  const workerName = props.name;
115
135
 
116
136
  // Validate input - we need either script, entryPoint, or bundle
117
- if (!props.script && !props.entrypoint && !props.bundle) {
118
- throw new Error("One of script, entryPoint, or bundle must be provided");
119
- }
120
-
121
- // For create operations, check if a worker with the same name already exists
122
- if (ctx.event === "create") {
123
- const checkExistsResponse = await api.get(
124
- `/accounts/${api.accountId}/workers/scripts/${workerName}`,
125
- );
126
-
127
- if (checkExistsResponse.ok) {
128
- throw new Error(
129
- `Worker with name '${workerName}' already exists. Please use a unique name.`,
130
- );
131
- } else if (checkExistsResponse.status !== 404) {
132
- // If it's neither a success nor a 404, it's an unexpected error
133
- const errorData: any = await checkExistsResponse.json().catch(() => ({
134
- errors: [{ message: checkExistsResponse.statusText }],
135
- }));
136
- throw new Error(
137
- `Error checking if worker exists: ${errorData.errors?.[0]?.message || checkExistsResponse.statusText}`,
138
- );
139
- }
140
- // If it's a 404, that means the worker doesn't exist yet, which is what we want
137
+ if (!props.script && !props.entrypoint) {
138
+ throw new Error("One of script or entryPoint must be provided");
141
139
  }
142
140
 
143
141
  if (ctx.event === "delete") {
144
- // Delete worker
145
- const deleteResponse = await api.delete(
146
- `/accounts/${api.accountId}/workers/scripts/${workerName}`,
147
- );
142
+ return deleteWorker(ctx, api, workerName);
143
+ } else if (ctx.event === "create") {
144
+ await assertWorkerDoesNotExist(ctx, api, workerName);
145
+ }
148
146
 
149
- // Check for success (2xx status code)
150
- if (!deleteResponse.ok && deleteResponse.status !== 404) {
151
- const errorData: any = await deleteResponse
152
- .json()
153
- .catch(() => ({ errors: [{ message: deleteResponse.statusText }] }));
154
- console.error(
155
- "Error deleting worker:",
156
- errorData.errors?.[0]?.message || deleteResponse.statusText,
157
- );
158
- }
147
+ const oldBindings = await ctx.get<WorkerBinding[]>("bindings");
148
+
149
+ const scriptMetadata = await prepareWorkerMetadata(ctx, oldBindings, props);
150
+
151
+ // Get the script content - either from props.script, or by bundling
152
+ const scriptContent =
153
+ props.script ?? (await bundleWorkerScript(ctx, props));
154
+
155
+ // Upload the worker script
156
+ await putWorker(ctx, api, workerName, scriptContent, scriptMetadata);
157
+
158
+ // TODO: it is less than ideal that this can fail, resulting in state problem
159
+ await ctx.set("bindings", props.bindings);
160
+
161
+ // Handle routes if requested
162
+ await setupRoutes(api, workerName, props.routes || []);
163
+
164
+ // Handle worker URL if requested
165
+ const workerUrl = await configureURL(
166
+ ctx,
167
+ api,
168
+ workerName,
169
+ props.url ?? false,
170
+ );
171
+
172
+ // Get current timestamp
173
+ const now = Date.now();
174
+
175
+ // Construct the output
176
+ const output: WorkerOutput = {
177
+ id: workerName,
178
+ name: workerName,
179
+ script: scriptContent,
180
+ format: props.format || "esm", // Include format in the output
181
+ routes: props.routes || [],
182
+ bindings: props.bindings || [],
183
+ env: props.env,
184
+ observability: scriptMetadata.observability,
185
+ createdAt: now,
186
+ updatedAt: now,
187
+ url: workerUrl,
188
+ };
189
+
190
+ return output;
191
+ },
192
+ ) {}
159
193
 
160
- // Also remove any associated routes if they exist
161
- if (ctx.output?.routes && ctx.output.routes.length > 0 && api.zoneId) {
162
- // First get existing routes to find their IDs
163
- const routesResponse = await api.get(
164
- `/zones/${api.zoneId}/workers/routes`,
194
+ async function deleteWorker(
195
+ ctx: Context<WorkerOutput>,
196
+ api: CloudflareApi,
197
+ workerName: string,
198
+ ) {
199
+ // Delete worker
200
+ const deleteResponse = await api.delete(
201
+ `/accounts/${api.accountId}/workers/scripts/${workerName}`,
202
+ );
203
+
204
+ // Check for success (2xx status code)
205
+ if (!deleteResponse.ok && deleteResponse.status !== 404) {
206
+ const errorData: any = await deleteResponse
207
+ .json()
208
+ .catch(() => ({ errors: [{ message: deleteResponse.statusText }] }));
209
+ console.error(
210
+ "Error deleting worker:",
211
+ errorData.errors?.[0]?.message || deleteResponse.statusText,
212
+ );
213
+ }
214
+
215
+ // Also remove any associated routes if they exist
216
+ if (ctx.output?.routes && ctx.output.routes.length > 0 && api.zoneId) {
217
+ // First get existing routes to find their IDs
218
+ const routesResponse = await api.get(`/zones/${api.zoneId}/workers/routes`);
219
+
220
+ if (!routesResponse.ok) {
221
+ throw new Error(
222
+ `Could not fetch routes for cleanup: ${routesResponse.status} ${routesResponse.statusText}`,
223
+ );
224
+ }
225
+ const routesData: any = await routesResponse.json();
226
+ const existingRoutes = routesData.result || [];
227
+
228
+ for (const route of existingRoutes) {
229
+ if (ctx.output.routes.includes(route.pattern)) {
230
+ // Delete the route
231
+ const routeDeleteResponse = await api.delete(
232
+ `/zones/${api.zoneId}/workers/routes/${route.id}`,
165
233
  );
166
234
 
167
- if (routesResponse.ok) {
168
- const routesData: any = await routesResponse.json();
169
- const existingRoutes = routesData.result || [];
170
-
171
- for (const route of existingRoutes) {
172
- if (ctx.output.routes.includes(route.pattern)) {
173
- // Delete the route
174
- const routeDeleteResponse = await api.delete(
175
- `/zones/${api.zoneId}/workers/routes/${route.id}`,
176
- );
177
-
178
- if (!routeDeleteResponse.ok) {
179
- console.warn(
180
- `Failed to delete route ${route.pattern}: ${routeDeleteResponse.status} ${routeDeleteResponse.statusText}`,
181
- );
182
- }
183
- }
184
- }
185
- } else {
235
+ if (!routeDeleteResponse.ok) {
186
236
  console.warn(
187
- "Could not fetch routes for cleanup:",
188
- routesResponse.status,
189
- routesResponse.statusText,
237
+ `Failed to delete route ${route.pattern}: ${routeDeleteResponse.status} ${routeDeleteResponse.statusText}`,
190
238
  );
191
239
  }
192
240
  }
241
+ }
242
+ }
243
+
244
+ // Disable the URL if it was enabled
245
+ if (ctx.output?.url) {
246
+ try {
247
+ await api.post(
248
+ `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
249
+ JSON.stringify({ enabled: false }),
250
+ {
251
+ headers: { "Content-Type": "application/json" },
252
+ },
253
+ );
254
+ } catch (error) {
255
+ console.warn("Failed to disable worker URL during deletion:", error);
256
+ }
257
+ }
193
258
 
194
- // Disable the URL if it was enabled
195
- if (ctx.output?.url) {
196
- try {
197
- await api.post(
198
- `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
199
- JSON.stringify({ enabled: false }),
200
- {
201
- headers: { "Content-Type": "application/json" },
202
- },
203
- );
204
- } catch (error) {
205
- console.warn("Failed to disable worker URL during deletion:", error);
206
- }
207
- }
208
-
209
- // Return minimal output for deleted state
210
- return {
211
- ...props,
212
- id: "",
213
- createdAt: 0,
214
- updatedAt: 0,
215
- url: undefined,
216
- };
217
- } else {
218
- // Get the script content - either from props.script, or by bundling
219
- let scriptContent: string;
220
-
221
- if (props.script) {
222
- // Use the provided script
223
- scriptContent = props.script;
224
- } else if (props.bundle) {
225
- // Use a pre-configured Bundle resource
226
- const bundleOutput = await apply(props.bundle);
227
- scriptContent = await fs.readFile(bundleOutput.path, "utf-8");
228
- } else if (props.entrypoint) {
229
- // Create and use a Bundle resource with worker-optimized configuration
230
- const defaultBundleOptions: Omit<BundleProps, "entryPoint"> = {
231
- format: props.format === "cjs" ? "cjs" : "esm", // Use the specified format or default to ESM
232
- target: "es2020",
233
- platform: "browser",
234
- minify: true,
235
- options: {
236
- keepNames: true, // Important for Durable Object classes
237
- },
238
- };
239
-
240
- // Merge with user-provided options
241
- const bundleOptions = {
242
- ...defaultBundleOptions,
243
- ...(props.bundleOptions || {}),
244
- };
245
-
246
- // Create the bundle
247
- const bundle = new Bundle("bundle", {
248
- entryPoint: props.entrypoint,
249
- ...bundleOptions,
250
- });
259
+ // Return minimal output for deleted state
260
+ return;
261
+ }
251
262
 
252
- // Get the bundled content
253
- const bundleOutput = await apply(bundle);
254
- try {
255
- scriptContent = await fs.readFile(bundleOutput.path, "utf-8");
256
- } catch (error) {
257
- console.error("Error reading bundle:", error);
258
- throw new Error("Error reading bundle");
259
- }
260
- } else {
261
- throw new Error("No script source provided"); // Shouldn't reach here due to earlier validation
262
- }
263
- // Prepare metadata with bindings
264
- const metadata: any = {
265
- bindings: [],
266
- };
263
+ async function putWorker(
264
+ ctx: Context<WorkerOutput>,
265
+ api: CloudflareApi,
266
+ workerName: string,
267
+ scriptContent: string,
268
+ scriptMetadata: WorkerMetadata,
269
+ ) {
270
+ const scriptName = scriptMetadata.main_module ?? scriptMetadata.body_part!;
271
+
272
+ // Create FormData for the upload
273
+ const formData = new FormData();
274
+
275
+ // Add the actual script content as a named file part
276
+ formData.append(
277
+ scriptName,
278
+ new Blob([scriptContent], {
279
+ type: scriptMetadata.main_module
280
+ ? "application/javascript+module"
281
+ : "application/javascript",
282
+ }),
283
+ scriptName,
284
+ );
285
+
286
+ console.log("Script Metadata:", JSON.stringify(scriptMetadata, null, 2));
287
+
288
+ // Add metadata as JSON
289
+ formData.append(
290
+ "metadata",
291
+ new Blob([JSON.stringify(scriptMetadata)], {
292
+ type: "application/json",
293
+ }),
294
+ );
295
+
296
+ // Upload worker script with bindings
297
+ const uploadResponse = await api.put(
298
+ `/accounts/${api.accountId}/workers/scripts/${workerName}`,
299
+ formData,
300
+ {
301
+ headers: {
302
+ "Content-Type": "multipart/form-data",
303
+ },
304
+ },
305
+ );
306
+
307
+ // Check if the upload was successful
308
+ if (!uploadResponse.ok) {
309
+ const errorData: any = await uploadResponse
310
+ .json()
311
+ .catch(() => ({ errors: [{ message: uploadResponse.statusText }] }));
312
+ throw new Error(
313
+ `Error uploading worker script '${workerName}': ${errorData.errors?.[0]?.message || uploadResponse.statusText}`,
314
+ );
315
+ }
316
+
317
+ return formData;
318
+ }
267
319
 
268
- // Convert bindings to the format expected by the API
269
- if (props.bindings && props.bindings.length > 0) {
270
- for (const binding of props.bindings) {
271
- const bindingData: any = {
272
- name: binding.name,
273
- type: binding.type,
274
- };
275
-
276
- // Map binding properties to the API format based on binding type
277
- switch (binding.type) {
278
- case "kv_namespace":
279
- bindingData.namespace_id = (binding as any).namespace_id;
280
- break;
281
- case "durable_object_namespace":
282
- bindingData.class_name = (binding as any).class_name;
283
- if ((binding as any).namespace_id) {
284
- bindingData.namespace_id = (binding as any).namespace_id;
285
- }
286
- if ((binding as any).script_name) {
287
- bindingData.script_name = (binding as any).script_name;
288
- }
289
- if ((binding as any).environment) {
290
- bindingData.environment = (binding as any).environment;
291
- }
292
- break;
293
- case "secret_text":
294
- bindingData.text = (binding as any).text;
295
- break;
296
- case "r2_bucket":
297
- bindingData.bucket_name = (binding as any).bucket_name;
298
- break;
299
- case "analytics_engine":
300
- bindingData.dataset = (binding as any).dataset;
301
- break;
302
- case "service":
303
- bindingData.service = (binding as any).service;
304
- if ((binding as any).environment) {
305
- bindingData.environment = (binding as any).environment;
306
- }
307
- if ((binding as any).namespace) {
308
- bindingData.namespace = (binding as any).namespace;
309
- }
310
- break;
311
- case "d1":
312
- bindingData.id = (binding as any).id;
313
- break;
314
- case "queue":
315
- bindingData.queue_name = (binding as any).queue_name;
316
- break;
317
- case "json":
318
- bindingData.json = (binding as any).json;
319
- break;
320
- case "hyperdrive":
321
- bindingData.id = (binding as any).id;
322
- break;
323
- case "vectorize":
324
- bindingData.index_name = (binding as any).index_name;
325
- break;
326
- case "dispatch_namespace":
327
- bindingData.namespace = (binding as any).namespace;
328
- if ((binding as any).outbound) {
329
- bindingData.outbound = (binding as any).outbound;
330
- }
331
- break;
332
- case "mtls_certificate":
333
- bindingData.certificate_id = (binding as any).certificate_id;
334
- break;
335
- case "plain_text":
336
- bindingData.text = (binding as any).text;
337
- break;
338
- case "wasm_module":
339
- bindingData.module = (binding as any).module;
340
- break;
341
- case "tail_consumer":
342
- bindingData.service = (binding as any).service;
343
- break;
344
- }
320
+ interface WorkerMetadata {
321
+ bindings: WorkerBinding[];
322
+ observability: {
323
+ enabled: boolean;
324
+ };
325
+ migrations?: SingleStepMigration;
326
+ main_module?: string;
327
+ body_part?: string;
328
+ tags?: string[];
329
+ }
345
330
 
346
- metadata.bindings.push(bindingData);
331
+ async function prepareWorkerMetadata(
332
+ ctx: Context<WorkerOutput>,
333
+ oldBindings: WorkerBinding[] | undefined,
334
+ props: WorkerProps,
335
+ ): Promise<WorkerMetadata> {
336
+ // Prepare metadata with bindings
337
+ const meta: WorkerMetadata = {
338
+ bindings: [] as WorkerBinding[],
339
+ observability: {
340
+ enabled: props.observability?.enabled !== false,
341
+ },
342
+ tags: [`alchemy:id:${ctx.resourceFQN}`],
343
+ migrations: {
344
+ new_classes: props.migrations?.new_classes ?? [],
345
+ deleted_classes: props.migrations?.deleted_classes ?? [],
346
+ renamed_classes: props.migrations?.renamed_classes ?? [],
347
+ transferred_classes: props.migrations?.transferred_classes ?? [],
348
+ new_sqlite_classes: props.migrations?.new_sqlite_classes ?? [],
349
+ },
350
+ };
351
+
352
+ // Convert bindings to the format expected by the API
353
+ for (const binding of props.bindings ?? []) {
354
+ // Create a copy of the binding to avoid modifying the original
355
+ const bindingData = { ...binding };
356
+
357
+ if (isDurableObjectNamespace(bindingData)) {
358
+ const stableId = bindingData.id;
359
+ const className = bindingData.className;
360
+
361
+ meta.bindings.push({
362
+ type: "durable_object_namespace",
363
+ name: bindingData.bindingName,
364
+ class_name: className,
365
+ script_name: bindingData.scriptName,
366
+ environment: bindingData.environment,
367
+ namespace_id: bindingData.namespaceId,
368
+ });
369
+
370
+ const oldBinding: DurableObjectNamespace | undefined = oldBindings
371
+ ?.filter(isDurableObjectNamespace)
372
+ ?.find((b) => b.id === stableId);
373
+
374
+ if (!oldBinding) {
375
+ if (bindingData.sqlite) {
376
+ meta.migrations!.new_sqlite_classes!.push(className);
377
+ } else {
378
+ meta.migrations!.new_classes!.push(className);
347
379
  }
380
+ } else if (oldBinding.className !== className) {
381
+ meta.migrations!.renamed_classes!.push({
382
+ from: oldBinding.className,
383
+ to: className,
384
+ });
348
385
  }
386
+ } else {
387
+ // For all other binding types, use as-is
388
+ meta.bindings.push(bindingData as WorkerBindingSpec);
389
+ }
390
+ }
391
+
392
+ // Convert env variables to plain_text bindings
393
+ if (props.env) {
394
+ for (const [key, value] of Object.entries(props.env)) {
395
+ meta.bindings.push({
396
+ name: key,
397
+ type: "plain_text",
398
+ text: value,
399
+ });
400
+ }
401
+ }
402
+
403
+ // Determine if we're using ESM or service worker format
404
+ const isEsModule = props.format !== "cjs"; // Default to ESM unless CJS is specified
405
+ const scriptName = isEsModule ? "worker.js" : "script";
406
+
407
+ if (isEsModule) {
408
+ // For ES modules format
409
+ meta.main_module = scriptName;
410
+ } else {
411
+ // For service worker format (CJS)
412
+ meta.body_part = scriptName;
413
+ }
414
+ return meta;
415
+ }
349
416
 
350
- // Create FormData for the upload
351
- const formData = new FormData();
352
-
353
- // Determine if we're using ESM or service worker format
354
- const isEsModule = props.format !== "cjs"; // Default to ESM unless CJS is specified
355
- const scriptName = isEsModule ? "worker.js" : "script";
356
- const contentType = isEsModule
357
- ? "application/javascript+module"
358
- : "application/javascript";
359
-
360
- // Prepare metadata
361
- const updatedMetadata = {
362
- ...metadata,
363
- };
364
-
365
- // Add Durable Object migrations if there are any DO bindings
366
- const durableObjectBindings = props.bindings?.filter(
367
- (binding) =>
368
- binding.type === "durable_object_namespace" &&
369
- // Only include self-referencing DOs (ones defined in this script)
370
- (binding as any).script_name === props.name,
417
+ async function assertWorkerDoesNotExist(
418
+ ctx: Context<WorkerOutput>,
419
+ api: CloudflareApi,
420
+ workerName: string,
421
+ ) {
422
+ const response = await api.get(
423
+ `/accounts/${api.accountId}/workers/scripts/${workerName}`,
424
+ );
425
+ if (response.status === 404) {
426
+ return true;
427
+ }
428
+ if (response.status === 200) {
429
+ const metadata = await getWorkerScriptMetadata(api, workerName);
430
+
431
+ if (!metadata) {
432
+ throw new Error(
433
+ `Worker exists but failed to fetch metadata: ${response.status} ${response.statusText}`,
371
434
  );
435
+ }
372
436
 
373
- if (durableObjectBindings && durableObjectBindings.length > 0) {
374
- // Add migrations metadata for Durable Objects
375
- updatedMetadata.migrations = {
376
- new_classes: durableObjectBindings.map(
377
- (binding) => (binding as any).class_name, // Just the class name as a string
378
- ),
379
- deleted_classes: [],
380
- renamed_classes: [],
381
- // Version 2 migrations
382
- new_sqlite_classes: [],
383
- updated_sqlite_classes: [],
384
- renamed_sqlite_classes: [],
385
- };
386
- }
437
+ if (
438
+ metadata.default_environment?.script.tags.includes(
439
+ `alchemy:id:${ctx.resourceFQN}`,
440
+ )
441
+ ) {
442
+ return true;
443
+ }
387
444
 
388
- if (isEsModule) {
389
- // For ES modules format
390
- updatedMetadata.main_module = scriptName;
391
- } else {
392
- // For service worker format (CJS)
393
- updatedMetadata.body_part = scriptName;
394
- }
445
+ throw new Error(
446
+ `Worker with name '${workerName}' already exists. Please use a unique name.`,
447
+ );
448
+ } else {
449
+ throw new Error(
450
+ `Error checking if worker exists: ${response.status} ${response.statusText}`,
451
+ );
452
+ }
453
+ }
395
454
 
396
- // Add the actual script content as a named file part
397
- formData.append(
398
- scriptName,
399
- new Blob([scriptContent], { type: contentType }),
400
- scriptName,
401
- );
455
+ async function bundleWorkerScript(
456
+ ctx: Context<WorkerOutput>,
457
+ props: WorkerProps,
458
+ ) {
459
+ // Get the script content - either from props.script, or by bundling
460
+
461
+ // Create and use a Bundle resource with worker-optimized configuration
462
+ const defaultBundleOptions: Omit<BundleProps, "entryPoint"> = {
463
+ format: props.format === "cjs" ? "cjs" : "esm", // Use the specified format or default to ESM
464
+ target: "es2020",
465
+ platform: "browser",
466
+ minify: true,
467
+ options: {
468
+ keepNames: true, // Important for Durable Object classes
469
+ },
470
+ };
471
+
472
+ // Merge with user-provided options
473
+ const bundleOptions = {
474
+ ...defaultBundleOptions,
475
+ ...(props.bundle || {}),
476
+ };
477
+
478
+ // Create the bundle
479
+ const bundle = new Bundle("bundle", {
480
+ entryPoint: props.entrypoint!,
481
+ ...bundleOptions,
482
+ external: [...(bundleOptions.external ?? []), "cloudflare:workers"],
483
+ });
484
+
485
+ // Get the bundled content
486
+ const bundleOutput = await apply(bundle, {
487
+ quiet: ctx.quiet,
488
+ });
489
+ try {
490
+ return await fs.readFile(bundleOutput.path, "utf-8");
491
+ } catch (error) {
492
+ console.error("Error reading bundle:", error);
493
+ throw new Error("Error reading bundle");
494
+ }
495
+ }
402
496
 
403
- // Add metadata as JSON
404
- formData.append(
405
- "metadata",
406
- new Blob([JSON.stringify(updatedMetadata)], {
407
- type: "application/json",
408
- }),
497
+ async function setupRoutes(
498
+ api: CloudflareApi,
499
+ workerName: string,
500
+ routes: string[],
501
+ ) {
502
+ // Set up routes if provided
503
+ if (routes && routes.length > 0 && api.zoneId) {
504
+ // First get existing routes
505
+ const routesResponse = await api.get(`/zones/${api.zoneId}/workers/routes`);
506
+
507
+ if (!routesResponse.ok) {
508
+ throw new Error(
509
+ `Could not fetch routes: ${routesResponse.status} ${routesResponse.statusText}`,
409
510
  );
511
+ }
512
+ const routesData: any = await routesResponse.json();
513
+ const existingRoutes = routesData.result || [];
410
514
 
411
- // Upload worker script with bindings
412
- const uploadResponse = await api.put(
413
- `/accounts/${api.accountId}/workers/scripts/${workerName}`,
414
- formData,
515
+ // For each desired route
516
+ for (const pattern of routes) {
517
+ const existingRoute = existingRoutes.find(
518
+ (r: any) => r.pattern === pattern,
415
519
  );
416
520
 
417
- // Check if the upload was successful
418
- if (!uploadResponse.ok) {
419
- const errorData: any = await uploadResponse
420
- .json()
421
- .catch(() => ({ errors: [{ message: uploadResponse.statusText }] }));
422
- throw new Error(
423
- `Error uploading worker script: ${errorData.errors?.[0]?.message || uploadResponse.statusText}`,
424
- );
425
- }
426
-
427
- // Set up routes if provided
428
- if (props.routes && props.routes.length > 0 && api.zoneId) {
429
- // First get existing routes
430
- const routesResponse = await api.get(
431
- `/zones/${api.zoneId}/workers/routes`,
432
- );
433
-
434
- if (routesResponse.ok) {
435
- const routesData: any = await routesResponse.json();
436
- const existingRoutes = routesData.result || [];
437
-
438
- // For each desired route
439
- for (const pattern of props.routes) {
440
- const existingRoute = existingRoutes.find(
441
- (r: any) => r.pattern === pattern,
442
- );
443
-
444
- if (existingRoute) {
445
- // Update if script name doesn't match
446
- if (existingRoute.script !== workerName) {
447
- const updateRouteResponse = await api.put(
448
- `/zones/${api.zoneId}/workers/routes/${existingRoute.id}`,
449
- {
450
- pattern,
451
- script: workerName,
452
- },
453
- );
454
-
455
- if (!updateRouteResponse.ok) {
456
- console.warn(
457
- `Failed to update route ${pattern}: ${updateRouteResponse.status} ${updateRouteResponse.statusText}`,
458
- );
459
- }
460
- }
461
- } else {
462
- // Create new route
463
- const createRouteResponse = await api.post(
464
- `/zones/${api.zoneId}/workers/routes`,
465
- {
466
- pattern,
467
- script: workerName,
468
- },
469
- );
470
-
471
- if (!createRouteResponse.ok) {
472
- console.warn(
473
- `Failed to create route ${pattern}: ${createRouteResponse.status} ${createRouteResponse.statusText}`,
474
- );
475
- }
476
- }
477
- }
478
- } else {
479
- console.warn(
480
- "Could not fetch routes:",
481
- routesResponse.status,
482
- routesResponse.statusText,
483
- );
484
- }
485
- }
486
-
487
- // Handle worker URL if requested
488
- let workerUrl;
489
- if (props.url) {
490
- try {
491
- // Enable the workers.dev subdomain for this worker
492
- await api.post(
493
- `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
494
- { enabled: true, previews_enabled: true },
521
+ if (existingRoute) {
522
+ // Update if script name doesn't match
523
+ if (existingRoute.script !== workerName) {
524
+ const updateRouteResponse = await api.put(
525
+ `/zones/${api.zoneId}/workers/routes/${existingRoute.id}`,
495
526
  {
496
- headers: { "Content-Type": "application/json" },
527
+ pattern,
528
+ script: workerName,
497
529
  },
498
530
  );
499
531
 
500
- // Get the account's workers.dev subdomain
501
- const subdomainResponse = await api.get(
502
- `/accounts/${api.accountId}/workers/subdomain`,
503
- );
504
-
505
- if (subdomainResponse.ok) {
506
- const subdomainData: {
507
- result: {
508
- subdomain: string;
509
- };
510
- } = await subdomainResponse.json();
511
- const subdomain = subdomainData.result?.subdomain;
512
-
513
- if (subdomain) {
514
- workerUrl = `${workerName}.${subdomain}.workers.dev`;
515
-
516
- // Add a delay when the subdomain is first created.
517
- // This is to prevent an issue where a negative cache-hit
518
- // causes the subdomain to be unavailable for 30 seconds.
519
- if (ctx.event === "create" || !ctx.output?.url) {
520
- await new Promise((resolve) => setTimeout(resolve, 3000));
521
- }
522
- }
523
- } else {
532
+ if (!updateRouteResponse.ok) {
524
533
  console.warn(
525
- "Could not fetch workers.dev subdomain:",
526
- subdomainResponse.status,
527
- subdomainResponse.statusText,
534
+ `Failed to update route ${pattern}: ${updateRouteResponse.status} ${updateRouteResponse.statusText}`,
528
535
  );
529
536
  }
530
- } catch (error) {
531
- console.warn("Failed to enable worker URL:", error);
532
537
  }
533
- } else if (props.url === false && ctx.output?.url) {
534
- // Explicitly disable URL if it was previously enabled
535
- try {
536
- await api.post(
537
- `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
538
- JSON.stringify({ enabled: false }),
539
- {
540
- headers: { "Content-Type": "application/json" },
541
- },
538
+ } else {
539
+ // Create new route
540
+ const createRouteResponse = await api.post(
541
+ `/zones/${api.zoneId}/workers/routes`,
542
+ {
543
+ pattern,
544
+ script: workerName,
545
+ },
546
+ );
547
+
548
+ if (!createRouteResponse.ok) {
549
+ throw new Error(
550
+ `Failed to create route ${pattern}: ${createRouteResponse.status} ${createRouteResponse.statusText}`,
542
551
  );
543
- } catch (error) {
544
- console.warn("Failed to disable worker URL:", error);
545
552
  }
546
553
  }
554
+ }
555
+ }
556
+ }
547
557
 
548
- // Get current timestamp
549
- const now = Date.now();
550
-
551
- // Construct the output
552
- const output: WorkerOutput = {
553
- id: workerName,
554
- name: workerName,
555
- script: scriptContent,
556
- format: props.format || "esm", // Include format in the output
557
- routes: props.routes || [],
558
- bindings: props.bindings || [],
559
- production: props.production !== false,
560
- createdAt: now,
561
- updatedAt: now,
562
- url: workerUrl,
558
+ async function configureURL(
559
+ ctx: Context<WorkerOutput>,
560
+ api: CloudflareApi,
561
+ workerName: string,
562
+ url: boolean,
563
+ ) {
564
+ let workerUrl;
565
+ if (url) {
566
+ // Enable the workers.dev subdomain for this worker
567
+ await api.post(
568
+ `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
569
+ { enabled: true, previews_enabled: true },
570
+ {
571
+ headers: { "Content-Type": "application/json" },
572
+ },
573
+ );
574
+
575
+ // Get the account's workers.dev subdomain
576
+ const subdomainResponse = await api.get(
577
+ `/accounts/${api.accountId}/workers/subdomain`,
578
+ );
579
+
580
+ if (!subdomainResponse.ok) {
581
+ throw new Error(
582
+ `Could not fetch workers.dev subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`,
583
+ );
584
+ }
585
+ const subdomainData: {
586
+ result: {
587
+ subdomain: string;
563
588
  };
589
+ } = await subdomainResponse.json();
590
+ const subdomain = subdomainData.result?.subdomain;
591
+
592
+ if (subdomain) {
593
+ workerUrl = `https://${workerName}.${subdomain}.workers.dev`;
564
594
 
565
- return output;
595
+ // Add a delay when the subdomain is first created.
596
+ // This is to prevent an issue where a negative cache-hit
597
+ // causes the subdomain to be unavailable for 30 seconds.
598
+ if (ctx.event === "create" || !ctx.output?.url) {
599
+ await new Promise((resolve) => setTimeout(resolve, 3000));
600
+ }
566
601
  }
567
- },
568
- ) {}
602
+ } else if (url === false && ctx.output?.url) {
603
+ // Explicitly disable URL if it was previously enabled
604
+ const response = await api.post(
605
+ `/accounts/${api.accountId}/workers/scripts/${workerName}/subdomain`,
606
+ JSON.stringify({ enabled: false }),
607
+ {
608
+ headers: { "Content-Type": "application/json" },
609
+ },
610
+ );
611
+ if (!response.ok) {
612
+ throw new Error(
613
+ `Failed to disable worker URL: ${response.status} ${response.statusText}`,
614
+ );
615
+ }
616
+ }
617
+ return workerUrl;
618
+ }
619
+
620
+ async function getWorkerScriptMetadata(
621
+ api: CloudflareApi,
622
+ workerName: string,
623
+ ): Promise<WorkerScriptMetadata | undefined> {
624
+ const response = await api.get(
625
+ `/accounts/${api.accountId}/workers/services/${workerName}`,
626
+ );
627
+ if (response.status === 404) {
628
+ return undefined;
629
+ }
630
+ if (!response.ok) {
631
+ throw new Error(
632
+ `Error getting worker script metadata: ${response.status} ${response.statusText}`,
633
+ );
634
+ }
635
+ return ((await response.json()) as any).result as WorkerScriptMetadata;
636
+ }
637
+
638
+ async function getWorkerBindings(
639
+ api: CloudflareApi,
640
+ workerName: string,
641
+ environment = "production",
642
+ ) {
643
+ const response = await api.get(
644
+ `/accounts/${api.accountId}/workers/services/${workerName}/environments/${environment}/bindings`,
645
+ {
646
+ headers: {
647
+ Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
648
+ "Content-Type": "application/json",
649
+ },
650
+ },
651
+ );
652
+
653
+ if (response.status === 404) {
654
+ return undefined;
655
+ }
656
+
657
+ if (!response.ok) {
658
+ throw new Error(
659
+ `Failed to fetch bindings: ${response.status} ${response.statusText}`,
660
+ );
661
+ }
662
+
663
+ const data: any = await response.json();
664
+
665
+ return data.result;
666
+ }