alchemy 0.3.0 → 0.4.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.
Files changed (154) hide show
  1. package/README.md +8 -3
  2. package/lib/ai/astro-file.js +7 -24
  3. package/lib/ai/client.d.ts +7 -0
  4. package/lib/ai/client.js +45 -0
  5. package/lib/ai/css-file.js +7 -24
  6. package/lib/ai/data.d.ts +26 -21
  7. package/lib/ai/data.js +33 -22
  8. package/lib/ai/document.d.ts +76 -5
  9. package/lib/ai/document.js +112 -56
  10. package/lib/ai/html-file.js +7 -24
  11. package/lib/ai/json-file.js +11 -32
  12. package/lib/ai/typescript-file.d.ts +1 -2
  13. package/lib/ai/typescript-file.js +8 -39
  14. package/lib/ai/vue-file.js +7 -24
  15. package/lib/ai/yaml-file.js +12 -48
  16. package/lib/alchemy.d.ts +5 -0
  17. package/lib/alchemy.js +61 -3
  18. package/lib/apply.js +18 -11
  19. package/lib/aws/account-id.d.ts +4 -1
  20. package/lib/aws/account-id.js +1 -1
  21. package/lib/aws/credentials.d.ts +5 -0
  22. package/lib/aws/credentials.js +0 -0
  23. package/lib/aws/oidc/oidc-provider.js +2 -2
  24. package/lib/aws/role.js +35 -23
  25. package/lib/cloudflare/account-api-token.d.ts +168 -0
  26. package/lib/cloudflare/account-api-token.js +179 -0
  27. package/lib/cloudflare/account-id.d.ts +1 -0
  28. package/lib/cloudflare/account-id.js +0 -0
  29. package/lib/cloudflare/api.d.ts +38 -1
  30. package/lib/cloudflare/api.js +55 -4
  31. package/lib/cloudflare/bucket.d.ts +118 -3
  32. package/lib/cloudflare/bucket.js +269 -89
  33. package/lib/cloudflare/custom-domain.d.ts +75 -0
  34. package/lib/cloudflare/custom-domain.js +154 -0
  35. package/lib/cloudflare/{dns.js → dns-records.js} +14 -1
  36. package/lib/cloudflare/generate-asset-manifest.js +1 -1
  37. package/lib/cloudflare/index.d.ts +5 -1
  38. package/lib/cloudflare/index.js +5 -1
  39. package/lib/cloudflare/permission-groups.d.ts +78 -0
  40. package/lib/cloudflare/permission-groups.js +48 -0
  41. package/lib/cloudflare/r2-rest-state-store.d.ts +2 -1
  42. package/lib/cloudflare/r2-rest-state-store.js +3 -2
  43. package/lib/cloudflare/static-site-router.js +16 -7
  44. package/lib/cloudflare/static-site.d.ts +17 -18
  45. package/lib/cloudflare/static-site.js +19 -7
  46. package/lib/cloudflare/upload-asset-manifest.js +4 -2
  47. package/lib/{util/encrypt.d.ts → encrypt.d.ts} +1 -1
  48. package/lib/{util/encrypt.js → encrypt.js} +1 -1
  49. package/lib/fs/copy-file.d.ts +54 -0
  50. package/lib/fs/copy-file.js +63 -0
  51. package/lib/fs/file-system-state-store.js +1 -1
  52. package/lib/fs/file.d.ts +31 -0
  53. package/lib/fs/file.js +30 -5
  54. package/lib/fs/index.d.ts +6 -0
  55. package/lib/fs/index.js +6 -0
  56. package/lib/fs/static-astro-file.d.ts +34 -0
  57. package/lib/fs/static-astro-file.js +39 -0
  58. package/lib/fs/static-css-file.d.ts +24 -0
  59. package/lib/fs/static-css-file.js +29 -0
  60. package/lib/fs/static-html-file.d.ts +31 -0
  61. package/lib/fs/static-html-file.js +36 -0
  62. package/lib/fs/static-json-file.d.ts +2 -2
  63. package/lib/fs/static-json-file.js +3 -2
  64. package/lib/fs/static-text-file.d.ts +1 -1
  65. package/lib/fs/static-text-file.js +3 -2
  66. package/lib/fs/static-typescript-file.d.ts +2 -2
  67. package/lib/fs/static-typescript-file.js +3 -2
  68. package/lib/fs/static-vue-file.d.ts +28 -0
  69. package/lib/fs/static-vue-file.js +33 -0
  70. package/lib/fs/static-yaml-file.d.ts +11 -8
  71. package/lib/fs/static-yaml-file.js +3 -2
  72. package/lib/internal/{providers.d.ts → docs/providers.d.ts} +14 -4
  73. package/lib/internal/docs/providers.js +196 -0
  74. package/lib/secret.d.ts +3 -0
  75. package/lib/secret.js +13 -0
  76. package/lib/{util/serde.d.ts → serde.d.ts} +1 -1
  77. package/lib/{util/serde.js → serde.js} +12 -4
  78. package/lib/test/bun.js +3 -2
  79. package/lib/util/sha256.d.ts +1 -0
  80. package/lib/util/sha256.js +4 -0
  81. package/lib/web/vitepress/config.d.ts +11 -0
  82. package/lib/web/vitepress/config.js +32 -0
  83. package/lib/web/vitepress/home-page.d.ts +5 -3
  84. package/lib/web/vitepress/home-page.js +48 -35
  85. package/lib/web/vitepress/index.d.ts +2 -0
  86. package/lib/web/vitepress/index.js +2 -0
  87. package/lib/web/vitepress/process-front-matter-files.d.ts +18 -0
  88. package/lib/web/vitepress/process-front-matter-files.js +68 -0
  89. package/lib/web/vitepress/vitepress.d.ts +5 -4
  90. package/lib/web/vitepress/vitepress.js +20 -36
  91. package/package.json +8 -4
  92. package/src/ai/astro-file.ts +11 -30
  93. package/src/ai/client.ts +59 -0
  94. package/src/ai/css-file.ts +11 -30
  95. package/src/ai/data.ts +50 -25
  96. package/src/ai/document.ts +171 -66
  97. package/src/ai/html-file.ts +11 -30
  98. package/src/ai/json-file.ts +13 -37
  99. package/src/ai/typescript-file.ts +14 -48
  100. package/src/ai/vue-file.ts +11 -30
  101. package/src/ai/yaml-file.ts +13 -53
  102. package/src/alchemy.ts +74 -9
  103. package/src/apply.ts +27 -26
  104. package/src/aws/account-id.ts +6 -2
  105. package/src/aws/credentials.ts +6 -0
  106. package/src/aws/oidc/oidc-provider.ts +17 -17
  107. package/src/aws/role.ts +68 -54
  108. package/src/cloudflare/account-api-token.ts +365 -0
  109. package/src/cloudflare/account-id.ts +0 -0
  110. package/src/cloudflare/api.ts +88 -17
  111. package/src/cloudflare/bucket.ts +493 -133
  112. package/src/cloudflare/custom-domain.ts +318 -0
  113. package/src/cloudflare/{dns.ts → dns-records.ts} +36 -22
  114. package/src/cloudflare/generate-asset-manifest.ts +4 -4
  115. package/src/cloudflare/index.ts +5 -1
  116. package/src/cloudflare/permission-groups.ts +137 -0
  117. package/src/cloudflare/r2-rest-state-store.ts +14 -13
  118. package/src/cloudflare/static-site-router.ts +18 -8
  119. package/src/cloudflare/static-site.ts +27 -35
  120. package/src/cloudflare/upload-asset-manifest.ts +6 -4
  121. package/src/cloudflare/worker.ts +44 -43
  122. package/src/dns/import-dns.ts +4 -4
  123. package/src/{util/encrypt.ts → encrypt.ts} +7 -10
  124. package/src/fs/copy-file.ts +115 -0
  125. package/src/fs/file-system-state-store.ts +5 -5
  126. package/src/fs/file.ts +64 -9
  127. package/src/fs/index.ts +6 -0
  128. package/src/fs/static-astro-file.ts +45 -0
  129. package/src/fs/static-css-file.ts +35 -0
  130. package/src/fs/static-html-file.ts +42 -0
  131. package/src/fs/static-json-file.ts +4 -3
  132. package/src/fs/static-text-file.ts +5 -2
  133. package/src/fs/static-typescript-file.ts +4 -3
  134. package/src/fs/static-vue-file.ts +39 -0
  135. package/src/fs/static-yaml-file.ts +13 -9
  136. package/src/internal/docs/providers.ts +281 -0
  137. package/src/secret.ts +16 -0
  138. package/src/{util/serde.ts → serde.ts} +16 -10
  139. package/src/test/bun.ts +8 -7
  140. package/src/util/sha256.ts +5 -0
  141. package/src/web/vitepress/config.ts +50 -0
  142. package/src/web/vitepress/home-page.ts +54 -42
  143. package/src/web/vitepress/index.ts +2 -0
  144. package/src/web/vitepress/process-front-matter-files.ts +98 -0
  145. package/src/web/vitepress/vitepress.ts +34 -50
  146. package/lib/internal/getting-started.d.ts +0 -10
  147. package/lib/internal/getting-started.js +0 -94
  148. package/lib/internal/project.d.ts +0 -13
  149. package/lib/internal/project.js +0 -101
  150. package/lib/internal/providers.js +0 -148
  151. package/src/internal/getting-started.ts +0 -107
  152. package/src/internal/project.ts +0 -119
  153. package/src/internal/providers.ts +0 -209
  154. /package/lib/cloudflare/{dns.d.ts → dns-records.d.ts} +0 -0
@@ -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
 
@@ -134,7 +134,7 @@ export const ImportDnsRecords = Resource(
134
134
  async function (
135
135
  this: Context<ImportDnsRecords>,
136
136
  id: string,
137
- props: ImportDnsRecordsProps,
137
+ props: ImportDnsRecordsProps
138
138
  ): Promise<ImportDnsRecords> {
139
139
  // For delete phase, just return destroyed state since this is a read-only resource
140
140
  if (this.phase === "delete") {
@@ -152,7 +152,7 @@ export const ImportDnsRecords = Resource(
152
152
  headers: {
153
153
  accept: "application/dns-json",
154
154
  },
155
- },
155
+ }
156
156
  );
157
157
 
158
158
  if (!res.ok) {
@@ -197,7 +197,7 @@ export const ImportDnsRecords = Resource(
197
197
  } catch (error) {
198
198
  console.warn(
199
199
  `Failed to fetch ${type} records for ${props.domain}:`,
200
- error,
200
+ error
201
201
  );
202
202
  }
203
203
  }
@@ -209,5 +209,5 @@ export const ImportDnsRecords = Resource(
209
209
  records: allRecords,
210
210
  importedAt: Date.now(),
211
211
  });
212
- },
212
+ }
213
213
  );
@@ -7,17 +7,14 @@ import sodium from "libsodium-wrappers";
7
7
  * @param key - The encryption key
8
8
  * @returns The base64-encoded encrypted value with nonce
9
9
  */
10
- export async function encryptWithKey(
11
- value: string,
12
- key: string,
13
- ): Promise<string> {
10
+ export async function encrypt(value: string, key: string): Promise<string> {
14
11
  // Initialize libsodium
15
12
  await sodium.ready;
16
13
 
17
14
  // Derive a key from the passphrase
18
15
  const cryptoKey = sodium.crypto_generichash(
19
16
  sodium.crypto_secretbox_KEYBYTES,
20
- sodium.from_string(key),
17
+ sodium.from_string(key)
21
18
  );
22
19
 
23
20
  // Generate a random nonce
@@ -27,7 +24,7 @@ export async function encryptWithKey(
27
24
  const encryptedBin = sodium.crypto_secretbox_easy(
28
25
  sodium.from_string(value),
29
26
  nonce,
30
- cryptoKey,
27
+ cryptoKey
31
28
  );
32
29
 
33
30
  // Combine nonce and ciphertext, then encode to base64
@@ -47,7 +44,7 @@ export async function encryptWithKey(
47
44
  */
48
45
  export async function decryptWithKey(
49
46
  encryptedValue: string,
50
- key: string,
47
+ key: string
51
48
  ): Promise<string> {
52
49
  // Initialize libsodium
53
50
  await sodium.ready;
@@ -55,13 +52,13 @@ export async function decryptWithKey(
55
52
  // Derive a key from the passphrase
56
53
  const cryptoKey = sodium.crypto_generichash(
57
54
  sodium.crypto_secretbox_KEYBYTES,
58
- sodium.from_string(key),
55
+ sodium.from_string(key)
59
56
  );
60
57
 
61
58
  // Decode the base64 combined value
62
59
  const combined = sodium.from_base64(
63
60
  encryptedValue,
64
- sodium.base64_variants.ORIGINAL,
61
+ sodium.base64_variants.ORIGINAL
65
62
  );
66
63
 
67
64
  // Extract nonce and ciphertext
@@ -72,7 +69,7 @@ export async function decryptWithKey(
72
69
  const decryptedBin = sodium.crypto_secretbox_open_easy(
73
70
  ciphertext,
74
71
  nonce,
75
- cryptoKey,
72
+ cryptoKey
76
73
  );
77
74
 
78
75
  return sodium.to_string(decryptedBin);
@@ -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
+ );
@@ -1,9 +1,9 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import type { Scope } from "../scope";
4
+ import { deserialize, serialize } from "../serde";
4
5
  import type { State, StateStore } from "../state";
5
6
  import { ignore } from "../util/ignore";
6
- import { deserialize, serialize } from "../util/serde";
7
7
 
8
8
  const stateRootDir = path.join(process.cwd(), ".alchemy");
9
9
 
@@ -48,7 +48,7 @@ export class FileSystemStateStore implements StateStore {
48
48
  const content = await fs.readFile(await this.getPath(key), "utf8");
49
49
  const state = (await deserialize(
50
50
  this.scope,
51
- JSON.parse(content),
51
+ JSON.parse(content)
52
52
  )) as State;
53
53
  if (state.output === undefined) {
54
54
  state.output = {} as any;
@@ -66,7 +66,7 @@ export class FileSystemStateStore implements StateStore {
66
66
  async set(key: string, value: State): Promise<void> {
67
67
  return fs.writeFile(
68
68
  await this.getPath(key),
69
- JSON.stringify(await serialize(this.scope, value), null, 2),
69
+ JSON.stringify(await serialize(this.scope, value), null, 2)
70
70
  );
71
71
  }
72
72
 
@@ -88,9 +88,9 @@ export class FileSystemStateStore implements StateStore {
88
88
  return [] as const;
89
89
  }
90
90
  return [[id, s]] as const;
91
- }),
91
+ })
92
92
  )
93
- ).flat(),
93
+ ).flat()
94
94
  );
95
95
  }
96
96