alchemy 0.3.0 → 0.3.1

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 (107) hide show
  1. package/lib/ai/approve.d.ts +99 -0
  2. package/lib/ai/approve.js +76 -0
  3. package/lib/ai/astro-file.js +7 -24
  4. package/lib/ai/client.d.ts +7 -0
  5. package/lib/ai/client.js +45 -0
  6. package/lib/ai/css-file.js +7 -24
  7. package/lib/ai/data.d.ts +26 -21
  8. package/lib/ai/data.js +33 -22
  9. package/lib/ai/document.d.ts +64 -4
  10. package/lib/ai/document.js +102 -55
  11. package/lib/ai/html-file.js +7 -24
  12. package/lib/ai/index.d.ts +2 -0
  13. package/lib/ai/index.js +2 -0
  14. package/lib/ai/json-file.js +11 -32
  15. package/lib/ai/review.d.ts +122 -0
  16. package/lib/ai/review.js +101 -0
  17. package/lib/ai/typescript-file.d.ts +1 -2
  18. package/lib/ai/typescript-file.js +8 -39
  19. package/lib/ai/vue-file.js +7 -24
  20. package/lib/ai/yaml-file.js +12 -48
  21. package/lib/alchemy.js +17 -2
  22. package/lib/apply.js +1 -1
  23. package/lib/cloudflare/generate-asset-manifest.js +1 -1
  24. package/lib/cloudflare/static-site-router.js +16 -7
  25. package/lib/cloudflare/static-site.js +3 -0
  26. package/lib/cloudflare/upload-asset-manifest.js +4 -2
  27. package/lib/fs/copy-file.d.ts +54 -0
  28. package/lib/fs/copy-file.js +63 -0
  29. package/lib/fs/file.d.ts +13 -0
  30. package/lib/fs/file.js +24 -5
  31. package/lib/fs/index.d.ts +6 -0
  32. package/lib/fs/index.js +6 -0
  33. package/lib/fs/static-astro-file.d.ts +34 -0
  34. package/lib/fs/static-astro-file.js +39 -0
  35. package/lib/fs/static-css-file.d.ts +24 -0
  36. package/lib/fs/static-css-file.js +29 -0
  37. package/lib/fs/static-html-file.d.ts +31 -0
  38. package/lib/fs/static-html-file.js +36 -0
  39. package/lib/fs/static-json-file.d.ts +2 -2
  40. package/lib/fs/static-json-file.js +3 -2
  41. package/lib/fs/static-text-file.d.ts +1 -1
  42. package/lib/fs/static-text-file.js +3 -2
  43. package/lib/fs/static-typescript-file.d.ts +2 -2
  44. package/lib/fs/static-typescript-file.js +3 -2
  45. package/lib/fs/static-vue-file.d.ts +28 -0
  46. package/lib/fs/static-vue-file.js +33 -0
  47. package/lib/fs/static-yaml-file.d.ts +11 -8
  48. package/lib/fs/static-yaml-file.js +3 -2
  49. package/lib/internal/getting-started.d.ts +15 -4
  50. package/lib/internal/getting-started.js +34 -41
  51. package/lib/internal/index.d.ts +3 -0
  52. package/lib/internal/index.js +3 -0
  53. package/lib/internal/providers.d.ts +7 -3
  54. package/lib/internal/providers.js +42 -18
  55. package/lib/internal/tutorial.d.ts +104 -0
  56. package/lib/internal/tutorial.js +251 -0
  57. package/lib/web/vitepress/config.d.ts +10 -0
  58. package/lib/web/vitepress/config.js +31 -0
  59. package/lib/web/vitepress/home-page.d.ts +5 -3
  60. package/lib/web/vitepress/home-page.js +48 -35
  61. package/lib/web/vitepress/index.d.ts +1 -0
  62. package/lib/web/vitepress/index.js +1 -0
  63. package/lib/web/vitepress/vitepress.d.ts +5 -4
  64. package/lib/web/vitepress/vitepress.js +17 -34
  65. package/package.json +1 -1
  66. package/src/ai/approve.ts +163 -0
  67. package/src/ai/astro-file.ts +11 -30
  68. package/src/ai/client.ts +59 -0
  69. package/src/ai/css-file.ts +11 -30
  70. package/src/ai/data.ts +50 -25
  71. package/src/ai/document.ts +146 -65
  72. package/src/ai/html-file.ts +11 -30
  73. package/src/ai/index.ts +2 -0
  74. package/src/ai/json-file.ts +13 -37
  75. package/src/ai/review.ts +213 -0
  76. package/src/ai/typescript-file.ts +14 -48
  77. package/src/ai/vue-file.ts +11 -30
  78. package/src/ai/yaml-file.ts +13 -53
  79. package/src/alchemy.ts +18 -7
  80. package/src/apply.ts +8 -8
  81. package/src/cloudflare/generate-asset-manifest.ts +4 -4
  82. package/src/cloudflare/static-site-router.ts +18 -8
  83. package/src/cloudflare/static-site.ts +11 -7
  84. package/src/cloudflare/upload-asset-manifest.ts +6 -4
  85. package/src/cloudflare/worker.ts +44 -43
  86. package/src/fs/copy-file.ts +115 -0
  87. package/src/fs/file.ts +35 -9
  88. package/src/fs/index.ts +6 -0
  89. package/src/fs/static-astro-file.ts +45 -0
  90. package/src/fs/static-css-file.ts +35 -0
  91. package/src/fs/static-html-file.ts +42 -0
  92. package/src/fs/static-json-file.ts +4 -3
  93. package/src/fs/static-text-file.ts +5 -2
  94. package/src/fs/static-typescript-file.ts +4 -3
  95. package/src/fs/static-vue-file.ts +39 -0
  96. package/src/fs/static-yaml-file.ts +13 -9
  97. package/src/internal/getting-started.ts +51 -43
  98. package/src/internal/index.ts +3 -0
  99. package/src/internal/providers.ts +59 -27
  100. package/src/internal/tutorial.ts +392 -0
  101. package/src/web/vitepress/config.ts +48 -0
  102. package/src/web/vitepress/home-page.ts +54 -42
  103. package/src/web/vitepress/index.ts +1 -0
  104. package/src/web/vitepress/vitepress.ts +31 -48
  105. package/lib/internal/project.d.ts +0 -13
  106. package/lib/internal/project.js +0 -101
  107. package/src/internal/project.ts +0 -119
@@ -65,21 +65,27 @@ app.notFound(async (ctx) => {
65
65
 
66
66
  // Fetch from KV
67
67
  {
68
- const object = await env.ASSETS.getWithMetadata(filePath);
68
+ const object = await env.ASSETS.getWithMetadata(filePath, {
69
+ type: "arrayBuffer",
70
+ });
69
71
  if (object.value) {
70
72
  return await respond(200, filePath, object);
71
73
  }
72
74
  }
73
75
  {
74
76
  const guess = filePath + (filePath.endsWith("/") ? "" : "/") + "index.html";
75
- const object = await env.ASSETS.getWithMetadata(guess);
77
+ const object = await env.ASSETS.getWithMetadata(guess, {
78
+ type: "arrayBuffer",
79
+ });
76
80
  if (object.value) {
77
81
  return await respond(200, guess, object);
78
82
  }
79
83
  }
80
84
  {
81
85
  const guess = filePath + ".html";
82
- const object = await env.ASSETS.getWithMetadata(guess);
86
+ const object = await env.ASSETS.getWithMetadata(guess, {
87
+ type: "arrayBuffer",
88
+ });
83
89
  if (object.value) {
84
90
  return await respond(200, guess, object);
85
91
  }
@@ -87,12 +93,16 @@ app.notFound(async (ctx) => {
87
93
 
88
94
  // Handle error page
89
95
  if (env.ERROR_PAGE) {
90
- const object = await env.ASSETS.getWithMetadata(env.ERROR_PAGE);
96
+ const object = await env.ASSETS.getWithMetadata(env.ERROR_PAGE, {
97
+ type: "arrayBuffer",
98
+ });
91
99
  if (object.value) {
92
100
  return await respond(404, env.ERROR_PAGE, object);
93
101
  }
94
102
  } else {
95
- const object = await env.ASSETS.getWithMetadata(env.INDEX_PAGE);
103
+ const object = await env.ASSETS.getWithMetadata(env.INDEX_PAGE, {
104
+ type: "arrayBuffer",
105
+ });
96
106
  if (object.value) {
97
107
  return await respond(200, env.INDEX_PAGE, object);
98
108
  }
@@ -122,7 +132,7 @@ app.notFound(async (ctx) => {
122
132
  async function respond(
123
133
  status: number,
124
134
  filePath: string,
125
- object: KVNamespaceGetWithMetadataResult<any, any>,
135
+ object: KVNamespaceGetWithMetadataResult<any, any>
126
136
  ) {
127
137
  // build response
128
138
  const headers = new Headers();
@@ -131,8 +141,8 @@ app.notFound(async (ctx) => {
131
141
  headers.set("content-type", object.metadata.contentType);
132
142
  headers.set("cache-control", object.metadata.cacheControl);
133
143
  }
134
- // TODO: do we need base64 encoded here?
135
- // const response = new Response(base64ToArrayBuffer(object.value), {
144
+
145
+ // Create response with the raw data directly
136
146
  const response = new Response(object.value, {
137
147
  status,
138
148
  headers,
@@ -262,7 +262,7 @@ export const StaticSite = Resource(
262
262
  async function (
263
263
  this: Context<StaticSite>,
264
264
  id: string,
265
- props: StaticSiteProps,
265
+ props: StaticSiteProps
266
266
  ) {
267
267
  if (this.phase === "delete") {
268
268
  // For delete operations, we'll rely on the Worker delete to clean up
@@ -273,7 +273,7 @@ export const StaticSite = Resource(
273
273
  // Validate that a name is provided
274
274
  if (!props.name) {
275
275
  throw new Error(
276
- "StaticSite name is required - must be explicitly specified",
276
+ "StaticSite name is required - must be explicitly specified"
277
277
  );
278
278
  }
279
279
 
@@ -302,7 +302,7 @@ export const StaticSite = Resource(
302
302
 
303
303
  // Throw a more descriptive error that includes the exit code and stderr
304
304
  throw new Error(
305
- `Build command "${props.build.command}" failed with exit code ${error.code}:\n${error.stderr || error.message}`,
305
+ `Build command "${props.build.command}" failed with exit code ${error.code}:\n${error.stderr || error.message}`
306
306
  );
307
307
  }
308
308
  }
@@ -314,7 +314,7 @@ export const StaticSite = Resource(
314
314
  }
315
315
  } catch (error: any) {
316
316
  throw new Error(
317
- `Directory "${props.dir}" does not exist: ${error.message}`,
317
+ `Directory "${props.dir}" does not exist: ${error.message}`
318
318
  );
319
319
  }
320
320
 
@@ -333,6 +333,10 @@ export const StaticSite = Resource(
333
333
  generateAssetManifest(props.dir),
334
334
  ]);
335
335
 
336
+ console.log({
337
+ assetManifest,
338
+ });
339
+
336
340
  // Step 3: Upload assets to KV
337
341
  await uploadAssetManifest(api, kv.namespaceId, assetManifest);
338
342
 
@@ -356,7 +360,7 @@ export const StaticSite = Resource(
356
360
 
357
361
  // Create asset manifest banner for static site router
358
362
  const assetManifestBanner = `const __ASSET_MANIFEST__ = ${JSON.stringify(
359
- Object.fromEntries(assetManifest.map((item) => [item.key, item.hash])),
363
+ Object.fromEntries(assetManifest.map((item) => [item.key, item.hash]))
360
364
  )};\n`;
361
365
 
362
366
  const bundleOptions = {
@@ -398,7 +402,7 @@ export const StaticSite = Resource(
398
402
  Object.entries(routes).map(([key, value]) => [
399
403
  `__ROUTE_${value}`,
400
404
  key,
401
- ]),
405
+ ])
402
406
  ),
403
407
  },
404
408
  });
@@ -420,5 +424,5 @@ export const StaticSite = Resource(
420
424
  url: worker.url,
421
425
  routes,
422
426
  });
423
- },
427
+ }
424
428
  );
@@ -17,7 +17,7 @@ type UploadResult = {
17
17
  export async function uploadAssetManifest(
18
18
  api: CloudflareApi,
19
19
  namespaceId: string,
20
- manifest: AssetManifest,
20
+ manifest: AssetManifest
21
21
  ): Promise<UploadResult[]> {
22
22
  const results: UploadResult[] = [];
23
23
 
@@ -59,14 +59,16 @@ export async function uploadAssetManifest(
59
59
  const formData = new FormData();
60
60
  formData.append("metadata", JSON.stringify(metadata));
61
61
 
62
- // Add file content as 'value'
63
- const blob = new Blob([content]);
62
+ // Add file content as 'value' - Fix for binary file corruption
63
+ const blob = new Blob([new Uint8Array(content)], {
64
+ type: item.contentType,
65
+ });
64
66
  formData.append("value", blob);
65
67
 
66
68
  try {
67
69
  const response = await api.put(
68
70
  `/accounts/${api.accountId}/storage/kv/namespaces/${namespaceId}/values/${item.key}`,
69
- formData,
71
+ formData
70
72
  );
71
73
 
72
74
  const result = { item, success: response.ok, status: response.status };
@@ -16,6 +16,7 @@ import type { DurableObjectNamespace } from "./durable-object-namespace";
16
16
  import { isKVNamespace } from "./kv-namespace";
17
17
  import type { WorkerScriptMetadata } from "./worker-metadata";
18
18
  import type { SingleStepMigration } from "./worker-migration";
19
+
19
20
  /**
20
21
  * Properties for creating or updating a Worker
21
22
  */
@@ -209,7 +210,7 @@ export const Worker = Resource(
209
210
  async function <const B extends Bindings>(
210
211
  this: Context<Worker<NoInfer<B>>>,
211
212
  id: string,
212
- props: WorkerProps<B>,
213
+ props: WorkerProps<B>
213
214
  ): Promise<Worker<B>> {
214
215
  // Create Cloudflare API client with automatic account discovery
215
216
  const api = await createCloudflareApi();
@@ -234,7 +235,7 @@ export const Worker = Resource(
234
235
  const scriptMetadata = await prepareWorkerMetadata(
235
236
  this,
236
237
  oldBindings,
237
- props,
238
+ props
238
239
  );
239
240
 
240
241
  // Get the script content - either from props.script, or by bundling
@@ -254,7 +255,7 @@ export const Worker = Resource(
254
255
  this,
255
256
  api,
256
257
  workerName,
257
- props.url ?? false,
258
+ props.url ?? false
258
259
  );
259
260
 
260
261
  // Get current timestamp
@@ -277,17 +278,17 @@ export const Worker = Resource(
277
278
  // phantom property
278
279
  Env: undefined!,
279
280
  });
280
- },
281
+ }
281
282
  );
282
283
 
283
284
  async function deleteWorker<B extends Bindings>(
284
285
  ctx: Context<Worker<B>>,
285
286
  api: CloudflareApi,
286
- workerName: string,
287
+ workerName: string
287
288
  ) {
288
289
  // Delete worker
289
290
  const deleteResponse = await api.delete(
290
- `/accounts/${api.accountId}/workers/scripts/${workerName}`,
291
+ `/accounts/${api.accountId}/workers/scripts/${workerName}`
291
292
  );
292
293
 
293
294
  // Check for success (2xx status code)
@@ -297,7 +298,7 @@ async function deleteWorker<B extends Bindings>(
297
298
  .catch(() => ({ errors: [{ message: deleteResponse.statusText }] }));
298
299
  console.error(
299
300
  "Error deleting worker:",
300
- errorData.errors?.[0]?.message || deleteResponse.statusText,
301
+ errorData.errors?.[0]?.message || deleteResponse.statusText
301
302
  );
302
303
  }
303
304
 
@@ -308,7 +309,7 @@ async function deleteWorker<B extends Bindings>(
308
309
 
309
310
  if (!routesResponse.ok) {
310
311
  throw new Error(
311
- `Could not fetch routes for cleanup: ${routesResponse.status} ${routesResponse.statusText}`,
312
+ `Could not fetch routes for cleanup: ${routesResponse.status} ${routesResponse.statusText}`
312
313
  );
313
314
  }
314
315
  const routesData: any = await routesResponse.json();
@@ -318,12 +319,12 @@ async function deleteWorker<B extends Bindings>(
318
319
  if (ctx.output.routes.includes(route.pattern)) {
319
320
  // Delete the route
320
321
  const routeDeleteResponse = await api.delete(
321
- `/zones/${api.zoneId}/workers/routes/${route.id}`,
322
+ `/zones/${api.zoneId}/workers/routes/${route.id}`
322
323
  );
323
324
 
324
325
  if (!routeDeleteResponse.ok) {
325
326
  console.warn(
326
- `Failed to delete route ${route.pattern}: ${routeDeleteResponse.status} ${routeDeleteResponse.statusText}`,
327
+ `Failed to delete route ${route.pattern}: ${routeDeleteResponse.status} ${routeDeleteResponse.statusText}`
327
328
  );
328
329
  }
329
330
  }
@@ -338,7 +339,7 @@ async function deleteWorker<B extends Bindings>(
338
339
  JSON.stringify({ enabled: false }),
339
340
  {
340
341
  headers: { "Content-Type": "application/json" },
341
- },
342
+ }
342
343
  );
343
344
  } catch (error) {
344
345
  console.warn("Failed to disable worker URL during deletion:", error);
@@ -353,7 +354,7 @@ async function putWorker(
353
354
  api: CloudflareApi,
354
355
  workerName: string,
355
356
  scriptContent: string,
356
- scriptMetadata: WorkerMetadata,
357
+ scriptMetadata: WorkerMetadata
357
358
  ) {
358
359
  return withExponentialBackoff(
359
360
  async () => {
@@ -371,7 +372,7 @@ async function putWorker(
371
372
  ? "application/javascript+module"
372
373
  : "application/javascript",
373
374
  }),
374
- scriptName,
375
+ scriptName
375
376
  );
376
377
 
377
378
  // Add metadata as JSON
@@ -379,7 +380,7 @@ async function putWorker(
379
380
  "metadata",
380
381
  new Blob([JSON.stringify(scriptMetadata)], {
381
382
  type: "application/json",
382
- }),
383
+ })
383
384
  );
384
385
 
385
386
  await new Promise((resolve) => setTimeout(resolve, 1000));
@@ -392,7 +393,7 @@ async function putWorker(
392
393
  headers: {
393
394
  "Content-Type": "multipart/form-data",
394
395
  },
395
- },
396
+ }
396
397
  );
397
398
 
398
399
  // Check if the upload was successful
@@ -416,7 +417,7 @@ async function putWorker(
416
417
  },
417
418
  (err) => err instanceof NotFoundError,
418
419
  10,
419
- 100,
420
+ 100
420
421
  );
421
422
  }
422
423
 
@@ -441,7 +442,7 @@ interface WorkerMetadata {
441
442
  async function prepareWorkerMetadata<B extends Bindings>(
442
443
  ctx: Context<Worker<B>>,
443
444
  oldBindings: Bindings | undefined,
444
- props: WorkerProps,
445
+ props: WorkerProps
445
446
  ): Promise<WorkerMetadata> {
446
447
  // Prepare metadata with bindings
447
448
  const meta: WorkerMetadata = {
@@ -498,7 +499,7 @@ async function prepareWorkerMetadata<B extends Bindings>(
498
499
  });
499
500
 
500
501
  const oldBinding: DurableObjectNamespace | undefined = Object.values(
501
- oldBindings ?? {},
502
+ oldBindings ?? {}
502
503
  )
503
504
  ?.filter(isDurableObjectNamespace)
504
505
  ?.find((b) => b.id === stableId);
@@ -561,10 +562,10 @@ async function prepareWorkerMetadata<B extends Bindings>(
561
562
  async function assertWorkerDoesNotExist<B extends Bindings>(
562
563
  ctx: Context<Worker<B>>,
563
564
  api: CloudflareApi,
564
- workerName: string,
565
+ workerName: string
565
566
  ) {
566
567
  const response = await api.get(
567
- `/accounts/${api.accountId}/workers/scripts/${workerName}`,
568
+ `/accounts/${api.accountId}/workers/scripts/${workerName}`
568
569
  );
569
570
  if (response.status === 404) {
570
571
  return true;
@@ -574,24 +575,24 @@ async function assertWorkerDoesNotExist<B extends Bindings>(
574
575
 
575
576
  if (!metadata) {
576
577
  throw new Error(
577
- `Worker exists but failed to fetch metadata: ${response.status} ${response.statusText}`,
578
+ `Worker exists but failed to fetch metadata: ${response.status} ${response.statusText}`
578
579
  );
579
580
  }
580
581
 
581
582
  if (
582
583
  metadata.default_environment?.script.tags.includes(
583
- `alchemy:id:${slugify(ctx.fqn)}`,
584
+ `alchemy:id:${slugify(ctx.fqn)}`
584
585
  )
585
586
  ) {
586
587
  return true;
587
588
  }
588
589
 
589
590
  throw new Error(
590
- `Worker with name '${workerName}' already exists. Please use a unique name.`,
591
+ `Worker with name '${workerName}' already exists. Please use a unique name.`
591
592
  );
592
593
  } else {
593
594
  throw new Error(
594
- `Error checking if worker exists: ${response.status} ${response.statusText} ${await response.text()}`,
595
+ `Error checking if worker exists: ${response.status} ${response.statusText} ${await response.text()}`
595
596
  );
596
597
  }
597
598
  }
@@ -634,7 +635,7 @@ async function bundleWorkerScript<B extends Bindings>(props: WorkerProps) {
634
635
  async function setupRoutes(
635
636
  api: CloudflareApi,
636
637
  workerName: string,
637
- routes: string[],
638
+ routes: string[]
638
639
  ) {
639
640
  // Set up routes if provided
640
641
  if (routes && routes.length > 0 && api.zoneId) {
@@ -643,7 +644,7 @@ async function setupRoutes(
643
644
 
644
645
  if (!routesResponse.ok) {
645
646
  throw new Error(
646
- `Could not fetch routes: ${routesResponse.status} ${routesResponse.statusText}`,
647
+ `Could not fetch routes: ${routesResponse.status} ${routesResponse.statusText}`
647
648
  );
648
649
  }
649
650
  const routesData: any = await routesResponse.json();
@@ -652,7 +653,7 @@ async function setupRoutes(
652
653
  // For each desired route
653
654
  for (const pattern of routes) {
654
655
  const existingRoute = existingRoutes.find(
655
- (r: any) => r.pattern === pattern,
656
+ (r: any) => r.pattern === pattern
656
657
  );
657
658
 
658
659
  if (existingRoute) {
@@ -663,12 +664,12 @@ async function setupRoutes(
663
664
  {
664
665
  pattern,
665
666
  script: workerName,
666
- },
667
+ }
667
668
  );
668
669
 
669
670
  if (!updateRouteResponse.ok) {
670
671
  console.warn(
671
- `Failed to update route ${pattern}: ${updateRouteResponse.status} ${updateRouteResponse.statusText}`,
672
+ `Failed to update route ${pattern}: ${updateRouteResponse.status} ${updateRouteResponse.statusText}`
672
673
  );
673
674
  }
674
675
  }
@@ -679,12 +680,12 @@ async function setupRoutes(
679
680
  {
680
681
  pattern,
681
682
  script: workerName,
682
- },
683
+ }
683
684
  );
684
685
 
685
686
  if (!createRouteResponse.ok) {
686
687
  throw new Error(
687
- `Failed to create route ${pattern}: ${createRouteResponse.status} ${createRouteResponse.statusText}`,
688
+ `Failed to create route ${pattern}: ${createRouteResponse.status} ${createRouteResponse.statusText}`
688
689
  );
689
690
  }
690
691
  }
@@ -696,7 +697,7 @@ async function configureURL<B extends Bindings>(
696
697
  ctx: Context<Worker<B>>,
697
698
  api: CloudflareApi,
698
699
  workerName: string,
699
- url: boolean,
700
+ url: boolean
700
701
  ) {
701
702
  let workerUrl;
702
703
  if (url) {
@@ -706,17 +707,17 @@ async function configureURL<B extends Bindings>(
706
707
  { enabled: true, previews_enabled: true },
707
708
  {
708
709
  headers: { "Content-Type": "application/json" },
709
- },
710
+ }
710
711
  );
711
712
 
712
713
  // Get the account's workers.dev subdomain
713
714
  const subdomainResponse = await api.get(
714
- `/accounts/${api.accountId}/workers/subdomain`,
715
+ `/accounts/${api.accountId}/workers/subdomain`
715
716
  );
716
717
 
717
718
  if (!subdomainResponse.ok) {
718
719
  throw new Error(
719
- `Could not fetch workers.dev subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`,
720
+ `Could not fetch workers.dev subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`
720
721
  );
721
722
  }
722
723
  const subdomainData: {
@@ -743,11 +744,11 @@ async function configureURL<B extends Bindings>(
743
744
  JSON.stringify({ enabled: false }),
744
745
  {
745
746
  headers: { "Content-Type": "application/json" },
746
- },
747
+ }
747
748
  );
748
749
  if (!response.ok) {
749
750
  throw new Error(
750
- `Failed to disable worker URL: ${response.status} ${response.statusText}`,
751
+ `Failed to disable worker URL: ${response.status} ${response.statusText}`
751
752
  );
752
753
  }
753
754
  }
@@ -756,17 +757,17 @@ async function configureURL<B extends Bindings>(
756
757
 
757
758
  async function getWorkerScriptMetadata(
758
759
  api: CloudflareApi,
759
- workerName: string,
760
+ workerName: string
760
761
  ): Promise<WorkerScriptMetadata | undefined> {
761
762
  const response = await api.get(
762
- `/accounts/${api.accountId}/workers/services/${workerName}`,
763
+ `/accounts/${api.accountId}/workers/services/${workerName}`
763
764
  );
764
765
  if (response.status === 404) {
765
766
  return undefined;
766
767
  }
767
768
  if (!response.ok) {
768
769
  throw new Error(
769
- `Error getting worker script metadata: ${response.status} ${response.statusText}`,
770
+ `Error getting worker script metadata: ${response.status} ${response.statusText}`
770
771
  );
771
772
  }
772
773
  return ((await response.json()) as any).result as WorkerScriptMetadata;
@@ -775,7 +776,7 @@ async function getWorkerScriptMetadata(
775
776
  async function getWorkerBindings(
776
777
  api: CloudflareApi,
777
778
  workerName: string,
778
- environment = "production",
779
+ environment = "production"
779
780
  ) {
780
781
  const response = await api.get(
781
782
  `/accounts/${api.accountId}/workers/services/${workerName}/environments/${environment}/bindings`,
@@ -784,7 +785,7 @@ async function getWorkerBindings(
784
785
  Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
785
786
  "Content-Type": "application/json",
786
787
  },
787
- },
788
+ }
788
789
  );
789
790
 
790
791
  if (response.status === 404) {
@@ -793,7 +794,7 @@ async function getWorkerBindings(
793
794
 
794
795
  if (!response.ok) {
795
796
  throw new Error(
796
- `Failed to fetch bindings: ${response.status} ${response.statusText}`,
797
+ `Failed to fetch bindings: ${response.status} ${response.statusText}`
797
798
  );
798
799
  }
799
800
 
@@ -0,0 +1,115 @@
1
+ import fs from "node:fs";
2
+ import type { Context } from "../context";
3
+ import { Resource } from "../resource";
4
+ import { ignore } from "../util/ignore";
5
+
6
+ /**
7
+ * Properties for creating a CopyFile resource
8
+ */
9
+ export interface CopyFileProps {
10
+ /**
11
+ * Source path of the file to copy
12
+ */
13
+ src: string;
14
+
15
+ /**
16
+ * Destination path where the file should be copied to
17
+ */
18
+ dest: string;
19
+
20
+ /**
21
+ * Whether to overwrite the destination file if it already exists
22
+ * @default true
23
+ */
24
+ overwrite?: boolean;
25
+ }
26
+
27
+ /**
28
+ * Output returned after CopyFile creation/update
29
+ */
30
+ export interface CopyFile extends Resource<"fs::CopyFile">, CopyFileProps {
31
+ /**
32
+ * Time at which the object was created
33
+ */
34
+ createdAt: number;
35
+
36
+ /**
37
+ * Whether the file was successfully copied
38
+ */
39
+ copied: boolean;
40
+ }
41
+
42
+ /**
43
+ * CopyFile Resource
44
+ *
45
+ * Copies a file from a source location to a destination location.
46
+ *
47
+ * @example
48
+ * // Copy a file to a new location
49
+ * const copiedFile = await CopyFile("config-copy", {
50
+ * src: "config.json",
51
+ * dest: "backup/config.json"
52
+ * });
53
+ *
54
+ * @example
55
+ * // Copy a file without overwriting if destination exists
56
+ * const safeCopy = await CopyFile("safe-copy", {
57
+ * src: "data.json",
58
+ * dest: "backup/data.json",
59
+ * overwrite: false
60
+ * });
61
+ */
62
+ export const CopyFile = Resource(
63
+ "fs::CopyFile",
64
+ async function (
65
+ this: Context<CopyFile>,
66
+ id: string,
67
+ props: CopyFileProps
68
+ ): Promise<CopyFile> {
69
+ const { src, dest, overwrite = true } = props;
70
+
71
+ if (this.phase === "delete") {
72
+ // When deleting, remove the destination file
73
+ await ignore("ENOENT", async () => fs.promises.unlink(dest));
74
+ return this.destroy();
75
+ } else {
76
+ try {
77
+ // Check if source file exists
78
+ await fs.promises.access(src, fs.constants.F_OK);
79
+
80
+ // If this is an update and the destination has changed, delete the old file
81
+ if (
82
+ this.phase === "update" &&
83
+ this.output?.dest &&
84
+ this.output.dest !== dest
85
+ ) {
86
+ await ignore("ENOENT", async () =>
87
+ fs.promises.unlink(this.output.dest)
88
+ );
89
+ }
90
+
91
+ // Check if destination file exists
92
+ const destinationExists = await fs.promises
93
+ .access(dest, fs.constants.F_OK)
94
+ .then(() => true)
95
+ .catch(() => false);
96
+
97
+ // Copy file if destination doesn't exist or overwrite is true
98
+ if (!destinationExists || overwrite) {
99
+ await fs.promises.copyFile(src, dest);
100
+ }
101
+
102
+ return this({
103
+ src,
104
+ dest,
105
+ overwrite,
106
+ copied: true,
107
+ createdAt: Date.now(),
108
+ });
109
+ } catch (error) {
110
+ console.error(`Error copying file from ${src} to ${dest}:`, error);
111
+ throw error;
112
+ }
113
+ }
114
+ }
115
+ );
package/src/fs/file.ts CHANGED
@@ -72,8 +72,8 @@ alchemy.files = async (
72
72
  paths.map(async (path) => [
73
73
  path,
74
74
  await fs.promises.readFile(path, "utf-8"),
75
- ]),
76
- ),
75
+ ])
76
+ )
77
77
  ),
78
78
  };
79
79
  };
@@ -111,6 +111,19 @@ export interface File extends Resource<"fs::File"> {
111
111
  * path: "logs/app.log",
112
112
  * content: "application log entry"
113
113
  * });
114
+ *
115
+ * @example
116
+ * // Update file content and path
117
+ * let file = await File("config.json", {
118
+ * path: "config.json",
119
+ * content: '{ "version": "1.0.0" }'
120
+ * });
121
+ *
122
+ * // Later, update the path and content (old file will be removed)
123
+ * file = await File("config.json", {
124
+ * path: "config/config.json",
125
+ * content: '{ "version": "1.0.1" }'
126
+ * });
114
127
  */
115
128
  export const File = Resource(
116
129
  "fs::File",
@@ -120,21 +133,34 @@ export const File = Resource(
120
133
  props: {
121
134
  path: string;
122
135
  content: string;
123
- },
136
+ }
124
137
  ): Promise<File> {
125
138
  const filePath = props?.path ?? id;
139
+
126
140
  if (this.phase === "delete") {
127
141
  await ignore("ENOENT", async () => fs.promises.unlink(filePath));
128
142
  return this.destroy();
129
- } else {
130
- await fs.promises.mkdir(path.dirname(filePath), {
131
- recursive: true,
132
- });
133
- await fs.promises.writeFile(filePath, props.content);
143
+ } else if (
144
+ this.phase === "update" &&
145
+ this.output &&
146
+ this.output.path !== filePath
147
+ ) {
148
+ // If path has changed, delete the old file
149
+ console.log(
150
+ `File: Path changed from ${this.output.path} to ${filePath}, removing old file`
151
+ );
152
+ await ignore("ENOENT", async () => fs.promises.unlink(this.output.path));
134
153
  }
154
+
155
+ // Create directory and write file
156
+ await fs.promises.mkdir(path.dirname(filePath), {
157
+ recursive: true,
158
+ });
159
+ await fs.promises.writeFile(filePath, props.content);
160
+
135
161
  return this({
136
162
  path: filePath,
137
163
  content: props.content,
138
164
  });
139
- },
165
+ }
140
166
  );