@inixiative/infra 0.1.2 → 0.2.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 (77) hide show
  1. package/README.md +6 -6
  2. package/dist/chunk-423X4M6P.cjs +2 -0
  3. package/dist/chunk-423X4M6P.cjs.map +1 -0
  4. package/dist/chunk-6YFRXV5B.js +2 -0
  5. package/dist/chunk-6YFRXV5B.js.map +1 -0
  6. package/dist/chunk-H4ZXR6Y4.cjs +3 -0
  7. package/dist/chunk-H4ZXR6Y4.cjs.map +1 -0
  8. package/dist/chunk-ISKFVF5B.cjs +3 -0
  9. package/dist/chunk-ISKFVF5B.cjs.map +1 -0
  10. package/dist/chunk-KW7XSHOO.js +3 -0
  11. package/dist/chunk-KW7XSHOO.js.map +1 -0
  12. package/dist/chunk-MFNST5XH.js +2 -0
  13. package/dist/chunk-MFNST5XH.js.map +1 -0
  14. package/dist/chunk-OHSNNHGO.cjs +3 -0
  15. package/dist/chunk-OHSNNHGO.cjs.map +1 -0
  16. package/dist/chunk-OMMAWGLG.cjs +2 -0
  17. package/dist/chunk-OMMAWGLG.cjs.map +1 -0
  18. package/dist/chunk-T6SYJK5Z.js +3 -0
  19. package/dist/chunk-T6SYJK5Z.js.map +1 -0
  20. package/dist/chunk-XW67L4CL.js +3 -0
  21. package/dist/chunk-XW67L4CL.js.map +1 -0
  22. package/dist/chunk-YBCARCMZ.js +3 -0
  23. package/dist/chunk-YBCARCMZ.js.map +1 -0
  24. package/dist/{chunk-XGIX6QNV.cjs → chunk-ZRQKCHRA.cjs} +3 -3
  25. package/dist/chunk-ZRQKCHRA.cjs.map +1 -0
  26. package/dist/{contracts-isQ6Kn09.d.cts → contracts-1rYdsPEB.d.cts} +28 -28
  27. package/dist/{contracts-isQ6Kn09.d.ts → contracts-1rYdsPEB.d.ts} +28 -28
  28. package/dist/firecracker/index.cjs +1 -1
  29. package/dist/firecracker/index.d.cts +4 -4
  30. package/dist/firecracker/index.d.ts +4 -4
  31. package/dist/firecracker/index.js +1 -1
  32. package/dist/fly/index.cjs +1 -1
  33. package/dist/fly/index.d.cts +5 -5
  34. package/dist/fly/index.d.ts +5 -5
  35. package/dist/fly/index.js +1 -1
  36. package/dist/index.cjs +1 -1
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +10 -10
  39. package/dist/index.d.ts +10 -10
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/lifecycle/index.cjs +1 -1
  43. package/dist/lifecycle/index.d.cts +21 -22
  44. package/dist/lifecycle/index.d.ts +21 -22
  45. package/dist/lifecycle/index.js +1 -1
  46. package/dist/railway/index.cjs +1 -1
  47. package/dist/railway/index.d.cts +4 -4
  48. package/dist/railway/index.d.ts +4 -4
  49. package/dist/railway/index.js +1 -1
  50. package/dist/render/index.cjs +1 -1
  51. package/dist/render/index.d.cts +4 -4
  52. package/dist/render/index.d.ts +4 -4
  53. package/dist/render/index.js +1 -1
  54. package/package.json +3 -3
  55. package/dist/chunk-3V67V3N2.cjs +0 -3
  56. package/dist/chunk-3V67V3N2.cjs.map +0 -1
  57. package/dist/chunk-5UNXCQEH.js +0 -3
  58. package/dist/chunk-5UNXCQEH.js.map +0 -1
  59. package/dist/chunk-HONV2KPY.js +0 -3
  60. package/dist/chunk-HONV2KPY.js.map +0 -1
  61. package/dist/chunk-I3A224H4.js +0 -3
  62. package/dist/chunk-I3A224H4.js.map +0 -1
  63. package/dist/chunk-MO2YI2GE.cjs +0 -2
  64. package/dist/chunk-MO2YI2GE.cjs.map +0 -1
  65. package/dist/chunk-MP4O62RE.cjs +0 -3
  66. package/dist/chunk-MP4O62RE.cjs.map +0 -1
  67. package/dist/chunk-MXJ4EW3I.js +0 -3
  68. package/dist/chunk-MXJ4EW3I.js.map +0 -1
  69. package/dist/chunk-SLMYHBFB.cjs +0 -3
  70. package/dist/chunk-SLMYHBFB.cjs.map +0 -1
  71. package/dist/chunk-U5EA4FJI.cjs +0 -2
  72. package/dist/chunk-U5EA4FJI.cjs.map +0 -1
  73. package/dist/chunk-UZUGSMDK.js +0 -2
  74. package/dist/chunk-UZUGSMDK.js.map +0 -1
  75. package/dist/chunk-W5SAM2DK.js +0 -2
  76. package/dist/chunk-W5SAM2DK.js.map +0 -1
  77. package/dist/chunk-XGIX6QNV.cjs.map +0 -1
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
1
  # `@inixiative/infra`
2
2
 
3
- Standalone MIT infrastructure and hosting drivers plus workload lifecycle, wind-down, staggered wake, and monthly cost projection — zero runtime dependencies, pure TypeScript over standard Web `fetch` and `node:http` APIs.
3
+ Standalone MIT infrastructure and hosting drivers plus infrastructure resource lifecycle, wind-down, staggered wake, and monthly cost projection — zero runtime dependencies, pure TypeScript over standard Web `fetch` and `node:http` APIs.
4
4
 
5
5
  ## What lives here
6
6
 
7
- - **Core contracts (`src/core/`)**: `sendInfraRequest` (with `redirect: 'error'`, redacted error excerpts, and `node:http` Unix-socket fallback), `InfraError` (`retryable` + `unreachable`), `INFRA_PROVIDERS` capability registry (`railway`, `render`, `fly`, `firecracker`, plus planned descriptors for `aws`, `gcp`, `azure`), `WorkloadDriver`, and `ArchiveHostingDriver`.
8
- - **Railway (`src/railway/`)**: `sendRailwayGraphql`, paginated project/service/volume/domain/GitHub/bucket/deploy GraphQL helpers, `railwayArchiveDriver`, and `railwayWorkloadDriver`.
9
- - **Render (`src/render/`)**: `sendRenderRequest`, `fetchRenderOwners`, shared plan-tier table (`starter` through `pro_ultra`), `renderArchiveDriver`, and `renderWorkloadDriver`.
10
- - **Fly.io Machines (`src/fly/`)**: `sendFlyRequest` and `flyWorkloadDriver` (Firecracker microVMs with explicit `<= 2048 MB` suspend cap enforcement, suspend/wake wait polling, HTTP health checks, and reconciled event-timeline usage).
11
- - **Firecracker (`src/firecracker/`)**: `sendFirecrackerRequest` and `firecrackerWorkloadDriver` over Unix domain socket or HTTP control plane (boot config, `track_dirty_pages` snapshot create/load, pause/resume, state-checked destroy).
7
+ - **Core contracts (`src/core/`)**: `sendInfraRequest` (with `redirect: 'error'`, redacted error excerpts, and `node:http` Unix-socket fallback), `InfraError` (`retryable` + `unreachable`), `INFRA_PROVIDERS` capability registry (`railway`, `render`, `fly`, `firecracker`, plus planned descriptors for `aws`, `gcp`, `azure`), `InfrastructureResourceDriver`, and `ArchiveHostingDriver`.
8
+ - **Railway (`src/railway/`)**: `sendRailwayGraphql`, paginated project/service/volume/domain/GitHub/bucket/deploy GraphQL helpers, `railwayArchiveDriver`, and `railwayInfrastructureResourceDriver`.
9
+ - **Render (`src/render/`)**: `sendRenderRequest`, `fetchRenderOwners`, shared plan-tier table (`starter` through `pro_ultra`), `renderArchiveDriver`, and `renderInfrastructureResourceDriver`.
10
+ - **Fly.io Machines (`src/fly/`)**: `sendFlyRequest` and `flyInfrastructureResourceDriver` (Firecracker microVMs with explicit `<= 2048 MB` suspend cap enforcement, suspend/wake wait polling, HTTP health checks, and reconciled event-timeline usage).
11
+ - **Firecracker (`src/firecracker/`)**: `sendFirecrackerRequest` and `firecrackerInfrastructureResourceDriver` over Unix domain socket or HTTP control plane (boot config, `track_dirty_pages` snapshot create/load, pause/resume, state-checked destroy).
12
12
  - **Lifecycle engine (`src/lifecycle/`)**: deterministic zero-I/O state evaluation for generic profiles (`warm-interactive`, `warm-pool`, `batch-worker`, `ephemeral-session`, `always-on`), thundering-herd prevention (`planStaggeredWakes`), and raw COGS + managed-markup projection (`projectHostingMonthlyCost`).
13
13
 
14
14
  ## Naming & vocabulary
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkQREJ73ZG_cjs=require('./chunk-QREJ73ZG.cjs');var t="ghcr.io/inixiative/archive",o=4700,a="archive",s=e=>{if(!e.archiveToken)throw new chunkQREJ73ZG_cjs.a("authentication_failed","Archive server token is required");return e.archiveToken};exports.a=t;exports.b=o;exports.c=a;exports.d=s;//# sourceMappingURL=chunk-423X4M6P.cjs.map
2
+ //# sourceMappingURL=chunk-423X4M6P.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/contracts.ts"],"names":["ARCHIVE_IMAGE","ARCHIVE_PORT","ARCHIVE_DATABASE","archiveTokenOrThrow","deployment","InfraError"],"mappings":"mEAGO,IAAMA,CAAAA,CAAgB,6BAChBC,CAAAA,CAAe,IAAA,CACfC,EAAmB,SAAA,CA0KnBC,CAAAA,CAAuBC,GAA0C,CAC5E,GAAI,CAACA,CAAAA,CAAW,YAAA,CACd,MAAM,IAAIC,mBAAAA,CAAW,wBAAyB,kCAAkC,CAAA,CAElF,OAAOD,CAAAA,CAAW,YACpB","file":"chunk-423X4M6P.cjs","sourcesContent":["import { InfraError } from './infraError.ts';\nimport type { ArchiveHostingProvider, ImplementedInfraProvider } from './providers.ts';\n\nexport const ARCHIVE_IMAGE = 'ghcr.io/inixiative/archive';\nexport const ARCHIVE_PORT = 4700;\nexport const ARCHIVE_DATABASE = 'archive';\n\nexport type InfrastructureResourceCpuKind = 'shared' | 'performance';\n\nexport type InfrastructureResourceVolumeSpec = {\n readonly name: string;\n readonly mountPath: string;\n readonly sizeGb?: number;\n readonly volumeId?: string;\n readonly hostPath?: string;\n};\n\nexport type InfrastructureResourcePortSpec = {\n readonly internalPort: number;\n readonly protocol?: 'tcp' | 'udp';\n readonly publicHttps?: boolean;\n};\n\nexport type InfrastructureResourceNetworkInterfaceSpec = {\n readonly ifaceId: string;\n readonly hostDevName: string;\n readonly guestMac?: string;\n};\n\nexport type InfrastructureResourceCredentials = {\n readonly token?: string;\n readonly apiUrl?: string;\n readonly unixSocketPath?: string;\n readonly workspaceId?: string;\n readonly appName?: string;\n readonly projectId?: string;\n readonly environmentId?: string;\n};\n\nexport type InfrastructureResourceSpec = {\n readonly name: string;\n readonly image: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly memoryMb: number;\n readonly cpuKind?: InfrastructureResourceCpuKind;\n readonly vcpus: number;\n readonly region?: string;\n readonly volume?: InfrastructureResourceVolumeSpec;\n readonly egressAllowlist?: readonly string[];\n readonly labels?: Readonly<Record<string, string>>;\n readonly port?: InfrastructureResourcePortSpec;\n readonly healthcheckPath?: string;\n readonly autoDestroy?: boolean;\n readonly kernelImagePath?: string;\n readonly bootArgs?: string;\n readonly snapshotPath?: string;\n readonly memFilePath?: string;\n readonly trackDirtyPages?: boolean;\n readonly networkInterface?: InfrastructureResourceNetworkInterfaceSpec;\n};\n\nexport type InfrastructureResourceHandle = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly name?: string;\n readonly region?: string;\n readonly url?: string;\n readonly memoryMb?: number;\n readonly vcpus?: number;\n readonly projectId?: string;\n readonly environmentId?: string;\n readonly appName?: string;\n readonly snapshotPath?: string;\n readonly memFilePath?: string;\n readonly metadata?: Readonly<Record<string, string>>;\n};\n\nexport type InfrastructureResourceRuntimeState =\n | 'provisioning'\n | 'starting'\n | 'running'\n | 'suspending'\n | 'suspended'\n | 'stopping'\n | 'stopped'\n | 'destroying'\n | 'destroyed'\n | 'failed'\n | 'unknown';\n\nexport type InfrastructureResourceStatus = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly name?: string;\n readonly state: InfrastructureResourceRuntimeState;\n readonly providerState: string;\n readonly region?: string;\n readonly url?: string;\n readonly memoryMb?: number;\n readonly vcpus?: number;\n readonly createdAt?: string;\n readonly updatedAt?: string;\n readonly labels?: Readonly<Record<string, string>>;\n};\n\nexport type InfrastructureResourceUsage = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly memoryMb: number;\n readonly vcpus: number;\n readonly activeSeconds: number;\n readonly suspendedSeconds: number;\n readonly rootfsGb: number;\n readonly metered: boolean;\n readonly windowStartIso: string;\n readonly windowEndIso: string;\n};\n\nexport type InfrastructureResourceDriver = {\n readonly provider: ImplementedInfraProvider;\n readonly provisionInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n spec: InfrastructureResourceSpec,\n ) => Promise<InfrastructureResourceHandle>;\n readonly suspendInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceHandle>;\n readonly wakeInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceHandle>;\n readonly fetchInfrastructureResourceStatus: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceStatus>;\n readonly fetchInfrastructureResources?: (\n credentials: InfrastructureResourceCredentials,\n ) => Promise<InfrastructureResourceStatus[]>;\n readonly fetchInfrastructureResourceUsage: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceUsage>;\n readonly destroyInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<void>;\n};\n\nexport type ArchiveDeploymentIds = {\n readonly projectId?: string;\n readonly environmentId?: string;\n readonly databaseServiceId?: string;\n readonly serviceId?: string;\n readonly databaseId?: string;\n readonly deploymentId?: string;\n};\n\nexport type ArchiveDeployment = {\n readonly apiUrl?: string;\n readonly token: string;\n readonly workspaceId: string;\n readonly name: string;\n readonly imageVersion: string;\n readonly archiveToken?: string;\n readonly ids: ArchiveDeploymentIds;\n};\n\nexport type HostingWorkspace = {\n readonly id: string;\n readonly name: string;\n};\n\nexport type ImageDeployStatus = 'deploying' | 'live' | 'failed';\n\nexport const archiveTokenOrThrow = (deployment: ArchiveDeployment): string => {\n if (!deployment.archiveToken) {\n throw new InfraError('authentication_failed', 'Archive server token is required');\n }\n return deployment.archiveToken;\n};\n\nexport type ArchiveHostingDriver = {\n readonly provider: ArchiveHostingProvider;\n readonly fetchWorkspaces: (token: string, apiUrl?: string) => Promise<HostingWorkspace[]>;\n readonly provisionDatabase: (deployment: ArchiveDeployment) => Promise<ArchiveDeploymentIds>;\n readonly fetchDatabaseReadiness: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly provisionService: (\n deployment: ArchiveDeployment,\n ) => Promise<{ readonly ids: ArchiveDeploymentIds; readonly url: string }>;\n readonly fetchServiceReadiness: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly fetchServiceFailureStatus: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly deployImage: (deployment: ArchiveDeployment) => Promise<ArchiveDeploymentIds>;\n readonly restoreImage: (deployment: ArchiveDeployment) => Promise<void>;\n readonly fetchImageDeployStatus: (deployment: ArchiveDeployment) => Promise<ImageDeployStatus>;\n readonly destroyService: (deployment: ArchiveDeployment) => Promise<void>;\n};\n"]}
@@ -0,0 +1,2 @@
1
+ import {a as a$1}from'./chunk-S47XOR4G.js';var t="ghcr.io/inixiative/archive",o=4700,a="archive",s=e=>{if(!e.archiveToken)throw new a$1("authentication_failed","Archive server token is required");return e.archiveToken};export{t as a,o as b,a as c,s as d};//# sourceMappingURL=chunk-6YFRXV5B.js.map
2
+ //# sourceMappingURL=chunk-6YFRXV5B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/contracts.ts"],"names":["ARCHIVE_IMAGE","ARCHIVE_PORT","ARCHIVE_DATABASE","archiveTokenOrThrow","deployment","InfraError"],"mappings":"2CAGO,IAAMA,CAAAA,CAAgB,6BAChBC,CAAAA,CAAe,IAAA,CACfC,EAAmB,SAAA,CA0KnBC,CAAAA,CAAuBC,GAA0C,CAC5E,GAAI,CAACA,CAAAA,CAAW,YAAA,CACd,MAAM,IAAIC,GAAAA,CAAW,wBAAyB,kCAAkC,CAAA,CAElF,OAAOD,CAAAA,CAAW,YACpB","file":"chunk-6YFRXV5B.js","sourcesContent":["import { InfraError } from './infraError.ts';\nimport type { ArchiveHostingProvider, ImplementedInfraProvider } from './providers.ts';\n\nexport const ARCHIVE_IMAGE = 'ghcr.io/inixiative/archive';\nexport const ARCHIVE_PORT = 4700;\nexport const ARCHIVE_DATABASE = 'archive';\n\nexport type InfrastructureResourceCpuKind = 'shared' | 'performance';\n\nexport type InfrastructureResourceVolumeSpec = {\n readonly name: string;\n readonly mountPath: string;\n readonly sizeGb?: number;\n readonly volumeId?: string;\n readonly hostPath?: string;\n};\n\nexport type InfrastructureResourcePortSpec = {\n readonly internalPort: number;\n readonly protocol?: 'tcp' | 'udp';\n readonly publicHttps?: boolean;\n};\n\nexport type InfrastructureResourceNetworkInterfaceSpec = {\n readonly ifaceId: string;\n readonly hostDevName: string;\n readonly guestMac?: string;\n};\n\nexport type InfrastructureResourceCredentials = {\n readonly token?: string;\n readonly apiUrl?: string;\n readonly unixSocketPath?: string;\n readonly workspaceId?: string;\n readonly appName?: string;\n readonly projectId?: string;\n readonly environmentId?: string;\n};\n\nexport type InfrastructureResourceSpec = {\n readonly name: string;\n readonly image: string;\n readonly env?: Readonly<Record<string, string>>;\n readonly memoryMb: number;\n readonly cpuKind?: InfrastructureResourceCpuKind;\n readonly vcpus: number;\n readonly region?: string;\n readonly volume?: InfrastructureResourceVolumeSpec;\n readonly egressAllowlist?: readonly string[];\n readonly labels?: Readonly<Record<string, string>>;\n readonly port?: InfrastructureResourcePortSpec;\n readonly healthcheckPath?: string;\n readonly autoDestroy?: boolean;\n readonly kernelImagePath?: string;\n readonly bootArgs?: string;\n readonly snapshotPath?: string;\n readonly memFilePath?: string;\n readonly trackDirtyPages?: boolean;\n readonly networkInterface?: InfrastructureResourceNetworkInterfaceSpec;\n};\n\nexport type InfrastructureResourceHandle = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly name?: string;\n readonly region?: string;\n readonly url?: string;\n readonly memoryMb?: number;\n readonly vcpus?: number;\n readonly projectId?: string;\n readonly environmentId?: string;\n readonly appName?: string;\n readonly snapshotPath?: string;\n readonly memFilePath?: string;\n readonly metadata?: Readonly<Record<string, string>>;\n};\n\nexport type InfrastructureResourceRuntimeState =\n | 'provisioning'\n | 'starting'\n | 'running'\n | 'suspending'\n | 'suspended'\n | 'stopping'\n | 'stopped'\n | 'destroying'\n | 'destroyed'\n | 'failed'\n | 'unknown';\n\nexport type InfrastructureResourceStatus = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly name?: string;\n readonly state: InfrastructureResourceRuntimeState;\n readonly providerState: string;\n readonly region?: string;\n readonly url?: string;\n readonly memoryMb?: number;\n readonly vcpus?: number;\n readonly createdAt?: string;\n readonly updatedAt?: string;\n readonly labels?: Readonly<Record<string, string>>;\n};\n\nexport type InfrastructureResourceUsage = {\n readonly provider: ImplementedInfraProvider;\n readonly externalId: string;\n readonly memoryMb: number;\n readonly vcpus: number;\n readonly activeSeconds: number;\n readonly suspendedSeconds: number;\n readonly rootfsGb: number;\n readonly metered: boolean;\n readonly windowStartIso: string;\n readonly windowEndIso: string;\n};\n\nexport type InfrastructureResourceDriver = {\n readonly provider: ImplementedInfraProvider;\n readonly provisionInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n spec: InfrastructureResourceSpec,\n ) => Promise<InfrastructureResourceHandle>;\n readonly suspendInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceHandle>;\n readonly wakeInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceHandle>;\n readonly fetchInfrastructureResourceStatus: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceStatus>;\n readonly fetchInfrastructureResources?: (\n credentials: InfrastructureResourceCredentials,\n ) => Promise<InfrastructureResourceStatus[]>;\n readonly fetchInfrastructureResourceUsage: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<InfrastructureResourceUsage>;\n readonly destroyInfrastructureResource: (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ) => Promise<void>;\n};\n\nexport type ArchiveDeploymentIds = {\n readonly projectId?: string;\n readonly environmentId?: string;\n readonly databaseServiceId?: string;\n readonly serviceId?: string;\n readonly databaseId?: string;\n readonly deploymentId?: string;\n};\n\nexport type ArchiveDeployment = {\n readonly apiUrl?: string;\n readonly token: string;\n readonly workspaceId: string;\n readonly name: string;\n readonly imageVersion: string;\n readonly archiveToken?: string;\n readonly ids: ArchiveDeploymentIds;\n};\n\nexport type HostingWorkspace = {\n readonly id: string;\n readonly name: string;\n};\n\nexport type ImageDeployStatus = 'deploying' | 'live' | 'failed';\n\nexport const archiveTokenOrThrow = (deployment: ArchiveDeployment): string => {\n if (!deployment.archiveToken) {\n throw new InfraError('authentication_failed', 'Archive server token is required');\n }\n return deployment.archiveToken;\n};\n\nexport type ArchiveHostingDriver = {\n readonly provider: ArchiveHostingProvider;\n readonly fetchWorkspaces: (token: string, apiUrl?: string) => Promise<HostingWorkspace[]>;\n readonly provisionDatabase: (deployment: ArchiveDeployment) => Promise<ArchiveDeploymentIds>;\n readonly fetchDatabaseReadiness: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly provisionService: (\n deployment: ArchiveDeployment,\n ) => Promise<{ readonly ids: ArchiveDeploymentIds; readonly url: string }>;\n readonly fetchServiceReadiness: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly fetchServiceFailureStatus: (deployment: ArchiveDeployment) => Promise<boolean>;\n readonly deployImage: (deployment: ArchiveDeployment) => Promise<ArchiveDeploymentIds>;\n readonly restoreImage: (deployment: ArchiveDeployment) => Promise<void>;\n readonly fetchImageDeployStatus: (deployment: ArchiveDeployment) => Promise<ImageDeployStatus>;\n readonly destroyService: (deployment: ArchiveDeployment) => Promise<void>;\n};\n"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkOHRGTWGZ_cjs=require('./chunk-OHRGTWGZ.cjs'),chunkQREJ73ZG_cjs=require('./chunk-QREJ73ZG.cjs');var k="http://localhost",n=async(r,e,t={})=>{if(!r.unixSocketPath&&!r.apiUrl)throw new chunkQREJ73ZG_cjs.a("invalid_request","Firecracker driver requires either unixSocketPath or apiUrl",{provider:"firecracker"});let a=chunkOHRGTWGZ_cjs.b(r.apiUrl??k);return chunkOHRGTWGZ_cjs.d(`${a}${e}`,{method:t.method??"GET",token:r.token,body:t.body,timeoutMs:t.timeoutMs,unixSocketPath:r.unixSocketPath,provider:"firecracker"})};var p="/var/lib/firecracker/vmlinux",R="console=ttyS0 reboot=k panic=1 pci=off",y=/^[A-Za-z0-9._-]+$/,c=r=>({apiUrl:r.apiUrl,unixSocketPath:r.unixSocketPath,token:r.token}),i=(r,e)=>{if(!r||r==="."||r===".."||r.includes("..")||r.includes("/")||r.includes("\\")||r.includes("\0")||!y.test(r))throw new chunkQREJ73ZG_cjs.a("invalid_request",`Invalid Firecracker ${e}: must match /^[A-Za-z0-9._-]+$/ without path traversal`,{provider:"firecracker"});return r},_=r=>{if(r===void 0)return 0;let e=Number(r);return Number.isFinite(e)&&e>=0?e:0},v=r=>{switch(r){case "Running":return "running";case "Paused":return "suspended";case "Not started":return "stopped";default:return "unknown"}},h={provider:"firecracker",provisionInfrastructureResource:async(r,e)=>{let t=c(r);if(chunkQREJ73ZG_cjs.f(e.egressAllowlist,"firecracker"),i(e.name,"infrastructure resource name"),e.volume){if(e.volume.name==="rootfs")throw new chunkQREJ73ZG_cjs.a("invalid_request",'Firecracker secondary drive name cannot be "rootfs"',{provider:"firecracker"});if(i(e.volume.name,"volume name"),!e.volume.hostPath)throw new chunkQREJ73ZG_cjs.a("invalid_request","Firecracker secondary drives require an explicit volume.hostPath backing file",{provider:"firecracker"})}let a=e.trackDirtyPages??false;if(await n(t,"/machine-config",{method:"PUT",body:{vcpu_count:e.vcpus,mem_size_mib:e.memoryMb,smt:false,track_dirty_pages:a}}),await n(t,"/boot-source",{method:"PUT",body:{kernel_image_path:e.kernelImagePath??p,boot_args:e.bootArgs??R}}),await n(t,"/drives/rootfs",{method:"PUT",body:{drive_id:"rootfs",path_on_host:e.image,is_root_device:true,is_read_only:false}}),e.volume?.hostPath){let d=encodeURIComponent(e.volume.name);await n(t,`/drives/${d}`,{method:"PUT",body:{drive_id:e.volume.name,path_on_host:e.volume.hostPath,is_root_device:false,is_read_only:false}});}if(e.networkInterface){i(e.networkInterface.ifaceId,"network interface id");let d=encodeURIComponent(e.networkInterface.ifaceId);await n(t,`/network-interfaces/${d}`,{method:"PUT",body:{iface_id:e.networkInterface.ifaceId,host_dev_name:e.networkInterface.hostDevName,...e.networkInterface.guestMac?{guest_mac:e.networkInterface.guestMac}:{}}});}await n(t,"/actions",{method:"PUT",body:{action_type:"InstanceStart"}});let o=await n(t,"/");return {provider:"firecracker",externalId:i(o.id||e.name,"externalId"),name:e.name,region:e.region,memoryMb:e.memoryMb,vcpus:e.vcpus,snapshotPath:e.snapshotPath,memFilePath:e.memFilePath,metadata:{vmmVersion:o.vmm_version,trackDirtyPages:String(a)}}},suspendInfrastructureResource:async(r,e)=>{let t=c(r),a=i(e.externalId,"externalId"),o=e.snapshotPath??`/var/lib/firecracker/snapshots/${a}.snap`,u=e.memFilePath??`/var/lib/firecracker/snapshots/${a}.mem`;return await n(t,"/vm",{method:"PATCH",body:{state:"Paused"}}),await n(t,"/snapshot/create",{method:"PUT",body:{snapshot_type:"Full",snapshot_path:o,mem_file_path:u}}),{...e,snapshotPath:o,memFilePath:u}},wakeInfrastructureResource:async(r,e)=>{let t=c(r),a=await n(t,"/");if(a.state==="Not started"&&e.snapshotPath&&e.memFilePath){let o=e.metadata?.trackDirtyPages==="true";await n(t,"/snapshot/load",{method:"PUT",body:{snapshot_path:e.snapshotPath,mem_backend:{backend_path:e.memFilePath,backend_type:"File"},track_dirty_pages:o,resume_vm:true}});}else a.state==="Paused"?await n(t,"/vm",{method:"PATCH",body:{state:"Resumed"}}):a.state==="Not started"&&await n(t,"/actions",{method:"PUT",body:{action_type:"InstanceStart"}});return e},fetchInfrastructureResourceStatus:async(r,e)=>{let t=c(r),a=await n(t,"/");return {provider:"firecracker",externalId:a.id||e.externalId,state:v(a.state),providerState:a.state,region:e.region,memoryMb:e.memoryMb,vcpus:e.vcpus,updatedAt:new Date().toISOString()}},fetchInfrastructureResourceUsage:async(r,e)=>{let t=await h.fetchInfrastructureResourceStatus(r,e),a=new Date().toISOString();return {provider:"firecracker",externalId:t.externalId,memoryMb:e.memoryMb??0,vcpus:e.vcpus??0,activeSeconds:0,suspendedSeconds:0,rootfsGb:_(e.metadata?.rootfsGb),metered:false,windowStartIso:a,windowEndIso:a}},destroyInfrastructureResource:async(r,e)=>{let t=c(r);(await n(t,"/").catch(o=>{chunkQREJ73ZG_cjs.e(o);}))?.state==="Running"&&await n(t,"/actions",{method:"PUT",body:{action_type:"SendCtrlAltDel"}}).catch(chunkQREJ73ZG_cjs.e);}};
2
+ exports.a=k;exports.b=n;exports.c=h;//# sourceMappingURL=chunk-H4ZXR6Y4.cjs.map
3
+ //# sourceMappingURL=chunk-H4ZXR6Y4.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/firecracker/firecrackerRequest.ts","../src/firecracker/firecrackerInfrastructureResourceDriver.ts"],"names":["FIRECRACKER_DEFAULT_BASE_URL","sendFirecrackerRequest","transport","path","init","InfraError","baseUrl","stripTrailingSlash","sendInfraRequest","DEFAULT_KERNEL_IMAGE_PATH","DEFAULT_BOOT_ARGS","SAFE_FIRECRACKER_ID","transportFromCredentials","credentials","assertSafeFirecrackerId","value","label","parseRootfsGb","raw","parsed","mapFirecrackerState","state","firecrackerInfrastructureResourceDriver","spec","assertNoEgressAllowlist","trackDirtyPages","encodedDriveId","encodedIfaceId","info","handle","safeExternalId","snapshotPath","memFilePath","status","nowIso","_handle","error","ignoreNotFound"],"mappings":"qHAGO,IAAMA,CAAAA,CAA+B,mBAc/BC,CAAAA,CAAyB,MACpCC,EACAC,CAAAA,CACAC,CAAAA,CAA+B,EAAC,GACjB,CACf,GAAI,CAACF,CAAAA,CAAU,gBAAkB,CAACA,CAAAA,CAAU,OAC1C,MAAM,IAAIG,oBACR,iBAAA,CACA,6DAAA,CACA,CAAE,QAAA,CAAU,aAAc,CAC5B,CAAA,CAGF,IAAMC,EAAUC,mBAAAA,CAAmBL,CAAAA,CAAU,QAAUF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,CAAE,WAAA,EACxB,CACF,CAAA,CACA,gCAAA,CAAkC,MAChChB,CAAAA,CACAgB,CAAAA,GACyC,CACzC,IAAMI,CAAAA,CAAS,MAAMX,CAAAA,CAAwC,iCAAA,CAC3DT,EACAgB,CACF,CAAA,CACMK,EAAS,IAAI,IAAA,GAAO,WAAA,EAAY,CACtC,OAAO,CACL,QAAA,CAAU,cACV,UAAA,CAAYD,CAAAA,CAAO,WACnB,QAAA,CAAUJ,CAAAA,CAAO,UAAY,CAAA,CAC7B,KAAA,CAAOA,EAAO,KAAA,EAAS,CAAA,CACvB,cAAe,CAAA,CACf,gBAAA,CAAkB,EAClB,QAAA,CAAUZ,CAAAA,CAAcY,EAAO,QAAA,EAAU,QAAQ,CAAA,CACjD,OAAA,CAAS,KAAA,CACT,cAAA,CAAgBK,EAChB,YAAA,CAAcA,CAChB,CACF,CAAA,CACA,6BAAA,CAA+B,MAC7BrB,CAAAA,CACAsB,CAAAA,GACkB,CAClB,IAAMjC,CAAAA,CAAYU,EAAyBC,CAAW,CAAA,CAAA,CACzC,MAAMZ,CAAAA,CAAgDC,CAAAA,CAAW,GAAG,CAAA,CAAE,KAAA,CAChFkC,GAAU,CACTC,mBAAAA,CAAeD,CAAK,EAEtB,CACF,IAEU,KAAA,GAAU,SAAA,EACpB,MAAMnC,CAAAA,CAAuBC,CAAAA,CAAW,WAAY,CAClD,MAAA,CAAQ,MACR,IAAA,CAAM,CAAE,YAAa,gBAAiB,CACxC,CAAC,CAAA,CAAE,KAAA,CAAMmC,mBAAc,EACzB,CACF","file":"chunk-H4ZXR6Y4.cjs","sourcesContent":["import { InfraError } from '../core/infraError.ts';\nimport { sendInfraRequest, stripTrailingSlash } from '../core/infraFetch.ts';\n\nexport const FIRECRACKER_DEFAULT_BASE_URL = 'http://localhost';\n\nexport type FirecrackerTransport = {\n readonly apiUrl?: string;\n readonly unixSocketPath?: string;\n readonly token?: string;\n};\n\nexport type FirecrackerRequestInit = {\n readonly method?: 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE';\n readonly body?: unknown;\n readonly timeoutMs?: number;\n};\n\nexport const sendFirecrackerRequest = async <T>(\n transport: FirecrackerTransport,\n path: string,\n init: FirecrackerRequestInit = {},\n): Promise<T> => {\n if (!transport.unixSocketPath && !transport.apiUrl) {\n throw new InfraError(\n 'invalid_request',\n 'Firecracker driver requires either unixSocketPath or apiUrl',\n { provider: 'firecracker' },\n );\n }\n\n const baseUrl = stripTrailingSlash(transport.apiUrl ?? FIRECRACKER_DEFAULT_BASE_URL);\n return sendInfraRequest<T>(`${baseUrl}${path}`, {\n method: init.method ?? 'GET',\n token: transport.token,\n body: init.body,\n timeoutMs: init.timeoutMs,\n unixSocketPath: transport.unixSocketPath,\n provider: 'firecracker',\n });\n};\n","import type {\n InfrastructureResourceCredentials,\n InfrastructureResourceDriver,\n InfrastructureResourceHandle,\n InfrastructureResourceRuntimeState,\n InfrastructureResourceSpec,\n InfrastructureResourceStatus,\n InfrastructureResourceUsage,\n} from '../core/contracts.ts';\nimport { assertNoEgressAllowlist, InfraError, ignoreNotFound } from '../core/infraError.ts';\nimport { type FirecrackerTransport, sendFirecrackerRequest } from './firecrackerRequest.ts';\n\nconst DEFAULT_KERNEL_IMAGE_PATH = '/var/lib/firecracker/vmlinux';\nconst DEFAULT_BOOT_ARGS = 'console=ttyS0 reboot=k panic=1 pci=off';\nconst SAFE_FIRECRACKER_ID = /^[A-Za-z0-9._-]+$/;\n\ntype FirecrackerInstanceInfo = {\n readonly id: string;\n readonly state: 'Not started' | 'Running' | 'Paused' | string;\n readonly vmm_version: string;\n readonly app_name?: string;\n};\n\nconst transportFromCredentials = (\n credentials: InfrastructureResourceCredentials,\n): FirecrackerTransport => ({\n apiUrl: credentials.apiUrl,\n unixSocketPath: credentials.unixSocketPath,\n token: credentials.token,\n});\n\nconst assertSafeFirecrackerId = (value: string, label: string): string => {\n if (\n !value ||\n value === '.' ||\n value === '..' ||\n value.includes('..') ||\n value.includes('/') ||\n value.includes('\\\\') ||\n value.includes('\\0') ||\n !SAFE_FIRECRACKER_ID.test(value)\n ) {\n throw new InfraError(\n 'invalid_request',\n `Invalid Firecracker ${label}: must match /^[A-Za-z0-9._-]+$/ without path traversal`,\n { provider: 'firecracker' },\n );\n }\n return value;\n};\n\nconst parseRootfsGb = (raw: string | undefined): number => {\n if (raw === undefined) return 0;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n};\n\nconst mapFirecrackerState = (state: string): InfrastructureResourceRuntimeState => {\n switch (state) {\n case 'Running':\n return 'running';\n case 'Paused':\n return 'suspended';\n case 'Not started':\n return 'stopped';\n default:\n return 'unknown';\n }\n};\n\nexport const firecrackerInfrastructureResourceDriver: InfrastructureResourceDriver = {\n provider: 'firecracker',\n provisionInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n spec: InfrastructureResourceSpec,\n ): Promise<InfrastructureResourceHandle> => {\n const transport = transportFromCredentials(credentials);\n assertNoEgressAllowlist(spec.egressAllowlist, 'firecracker');\n assertSafeFirecrackerId(spec.name, 'infrastructure resource name');\n\n if (spec.volume) {\n if (spec.volume.name === 'rootfs') {\n throw new InfraError(\n 'invalid_request',\n 'Firecracker secondary drive name cannot be \"rootfs\"',\n { provider: 'firecracker' },\n );\n }\n assertSafeFirecrackerId(spec.volume.name, 'volume name');\n if (!spec.volume.hostPath) {\n throw new InfraError(\n 'invalid_request',\n 'Firecracker secondary drives require an explicit volume.hostPath backing file',\n { provider: 'firecracker' },\n );\n }\n }\n\n const trackDirtyPages = spec.trackDirtyPages ?? false;\n\n await sendFirecrackerRequest(transport, '/machine-config', {\n method: 'PUT',\n body: {\n vcpu_count: spec.vcpus,\n mem_size_mib: spec.memoryMb,\n smt: false,\n track_dirty_pages: trackDirtyPages,\n },\n });\n\n await sendFirecrackerRequest(transport, '/boot-source', {\n method: 'PUT',\n body: {\n kernel_image_path: spec.kernelImagePath ?? DEFAULT_KERNEL_IMAGE_PATH,\n boot_args: spec.bootArgs ?? DEFAULT_BOOT_ARGS,\n },\n });\n\n await sendFirecrackerRequest(transport, '/drives/rootfs', {\n method: 'PUT',\n body: {\n drive_id: 'rootfs',\n path_on_host: spec.image,\n is_root_device: true,\n is_read_only: false,\n },\n });\n\n if (spec.volume?.hostPath) {\n const encodedDriveId = encodeURIComponent(spec.volume.name);\n await sendFirecrackerRequest(transport, `/drives/${encodedDriveId}`, {\n method: 'PUT',\n body: {\n drive_id: spec.volume.name,\n path_on_host: spec.volume.hostPath,\n is_root_device: false,\n is_read_only: false,\n },\n });\n }\n\n if (spec.networkInterface) {\n assertSafeFirecrackerId(spec.networkInterface.ifaceId, 'network interface id');\n const encodedIfaceId = encodeURIComponent(spec.networkInterface.ifaceId);\n await sendFirecrackerRequest(transport, `/network-interfaces/${encodedIfaceId}`, {\n method: 'PUT',\n body: {\n iface_id: spec.networkInterface.ifaceId,\n host_dev_name: spec.networkInterface.hostDevName,\n ...(spec.networkInterface.guestMac ? { guest_mac: spec.networkInterface.guestMac } : {}),\n },\n });\n }\n\n await sendFirecrackerRequest(transport, '/actions', {\n method: 'PUT',\n body: { action_type: 'InstanceStart' },\n });\n\n const info = await sendFirecrackerRequest<FirecrackerInstanceInfo>(transport, '/');\n const externalId = assertSafeFirecrackerId(info.id || spec.name, 'externalId');\n\n return {\n provider: 'firecracker',\n externalId,\n name: spec.name,\n region: spec.region,\n memoryMb: spec.memoryMb,\n vcpus: spec.vcpus,\n snapshotPath: spec.snapshotPath,\n memFilePath: spec.memFilePath,\n metadata: {\n vmmVersion: info.vmm_version,\n trackDirtyPages: String(trackDirtyPages),\n },\n };\n },\n suspendInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const transport = transportFromCredentials(credentials);\n const safeExternalId = assertSafeFirecrackerId(handle.externalId, 'externalId');\n const snapshotPath =\n handle.snapshotPath ?? `/var/lib/firecracker/snapshots/${safeExternalId}.snap`;\n const memFilePath =\n handle.memFilePath ?? `/var/lib/firecracker/snapshots/${safeExternalId}.mem`;\n\n await sendFirecrackerRequest(transport, '/vm', {\n method: 'PATCH',\n body: { state: 'Paused' },\n });\n\n await sendFirecrackerRequest(transport, '/snapshot/create', {\n method: 'PUT',\n body: {\n snapshot_type: 'Full',\n snapshot_path: snapshotPath,\n mem_file_path: memFilePath,\n },\n });\n\n return {\n ...handle,\n snapshotPath,\n memFilePath,\n };\n },\n wakeInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const transport = transportFromCredentials(credentials);\n const info = await sendFirecrackerRequest<FirecrackerInstanceInfo>(transport, '/');\n\n if (info.state === 'Not started' && handle.snapshotPath && handle.memFilePath) {\n const trackDirtyPages = handle.metadata?.trackDirtyPages === 'true';\n await sendFirecrackerRequest(transport, '/snapshot/load', {\n method: 'PUT',\n body: {\n snapshot_path: handle.snapshotPath,\n mem_backend: {\n backend_path: handle.memFilePath,\n backend_type: 'File',\n },\n track_dirty_pages: trackDirtyPages,\n resume_vm: true,\n },\n });\n } else if (info.state === 'Paused') {\n await sendFirecrackerRequest(transport, '/vm', {\n method: 'PATCH',\n body: { state: 'Resumed' },\n });\n } else if (info.state === 'Not started') {\n await sendFirecrackerRequest(transport, '/actions', {\n method: 'PUT',\n body: { action_type: 'InstanceStart' },\n });\n }\n\n return handle;\n },\n fetchInfrastructureResourceStatus: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceStatus> => {\n const transport = transportFromCredentials(credentials);\n const info = await sendFirecrackerRequest<FirecrackerInstanceInfo>(transport, '/');\n\n return {\n provider: 'firecracker',\n externalId: info.id || handle.externalId,\n state: mapFirecrackerState(info.state),\n providerState: info.state,\n region: handle.region,\n memoryMb: handle.memoryMb,\n vcpus: handle.vcpus,\n updatedAt: new Date().toISOString(),\n };\n },\n fetchInfrastructureResourceUsage: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceUsage> => {\n const status = await firecrackerInfrastructureResourceDriver.fetchInfrastructureResourceStatus(\n credentials,\n handle,\n );\n const nowIso = new Date().toISOString();\n return {\n provider: 'firecracker',\n externalId: status.externalId,\n memoryMb: handle.memoryMb ?? 0,\n vcpus: handle.vcpus ?? 0,\n activeSeconds: 0,\n suspendedSeconds: 0,\n rootfsGb: parseRootfsGb(handle.metadata?.rootfsGb),\n metered: false,\n windowStartIso: nowIso,\n windowEndIso: nowIso,\n };\n },\n destroyInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n _handle: InfrastructureResourceHandle,\n ): Promise<void> => {\n const transport = transportFromCredentials(credentials);\n const info = await sendFirecrackerRequest<FirecrackerInstanceInfo>(transport, '/').catch(\n (error) => {\n ignoreNotFound(error);\n return undefined;\n },\n );\n // Firecracker only accepts SendCtrlAltDel while Running; paused/not-started VMs are reaped by host VMM teardown.\n if (info?.state !== 'Running') return;\n await sendFirecrackerRequest(transport, '/actions', {\n method: 'PUT',\n body: { action_type: 'SendCtrlAltDel' },\n }).catch(ignoreNotFound);\n },\n};\n"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkOHRGTWGZ_cjs=require('./chunk-OHRGTWGZ.cjs'),chunkQREJ73ZG_cjs=require('./chunk-QREJ73ZG.cjs');var v="https://api.machines.dev/v1",d=async(t,e,r={},n=v)=>chunkOHRGTWGZ_cjs.d(`${chunkOHRGTWGZ_cjs.b(n)}${e}`,{method:r.method??"GET",token:t,body:r.body,timeoutMs:r.timeoutMs,provider:"fly"});var y=2048,M=30,h=4e4,c=(t,e)=>{if(!t.token)throw new chunkQREJ73ZG_cjs.a("authentication_failed","Fly.io API token is required",{provider:"fly"});let r=t.appName??e;if(!r)throw new chunkQREJ73ZG_cjs.a("invalid_request","Fly.io appName is required",{provider:"fly"});return {token:t.token,appName:r}},S=t=>{switch(t){case "created":return "provisioning";case "starting":return "starting";case "started":return "running";case "suspending":return "suspending";case "suspended":return "suspended";case "stopping":return "stopping";case "stopped":return "stopped";case "destroying":return "destroying";case "destroyed":return "destroyed";default:return "unknown"}},_=t=>{if(t===void 0)return 0;let e=Number(t);return Number.isFinite(e)&&e>=0?e:0},b=(t,e,r)=>{if(t.length===0)return {activeSeconds:0,suspendedSeconds:0,metered:false,windowStartMs:r,windowEndMs:r};let n=[...t].sort((u,i)=>u.timestamp-i.timestamp),a=0,o=0;for(let u=0;u<n.length;u+=1){let i=n[u],l=n[u+1];if(l){let m=Math.max(0,l.timestamp-i.timestamp);i.status==="started"?a+=m:i.status==="suspended"&&(o+=m);}else if(i.status===e){let m=Math.max(0,r-i.timestamp);e==="started"?a+=m:e==="suspended"&&(o+=m);}}let s=n[n.length-1].timestamp;return {activeSeconds:Math.round(a/1e3),suspendedSeconds:Math.round(o/1e3),metered:true,windowStartMs:n[0].timestamp,windowEndMs:Math.max(r,s)}},w=(t,e)=>({provider:"fly",externalId:t.id,name:t.name,state:S(t.state),providerState:t.state,region:t.region,...e?.url!==void 0?{url:e.url}:{},memoryMb:t.config?.guest?.memory_mb??e?.memoryMb,vcpus:t.config?.guest?.cpus??e?.vcpus,createdAt:t.created_at,updatedAt:t.updated_at,labels:t.config?.metadata}),U={provider:"fly",provisionInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.labels?.["fly.app"]);if(chunkQREJ73ZG_cjs.f(e.egressAllowlist,"fly"),e.volume&&!e.volume.volumeId)throw new chunkQREJ73ZG_cjs.a("invalid_request","Fly.io volume mounts require volume.volumeId",{provider:"fly"});let a=encodeURIComponent(n),o=e.port?[{protocol:e.port.protocol??"tcp",internal_port:e.port.internalPort,autostart:false,autostop:"off",...e.port.publicHttps?{ports:[{port:443,handlers:["tls","http"]}]}:{}}]:void 0,s=e.healthcheckPath?{httpget:{type:"http",port:e.port?.internalPort??8080,method:"GET",path:e.healthcheckPath,interval:"15s",timeout:"5s"}}:void 0,u=await d(r,`/apps/${a}/machines`,{method:"POST",body:{name:e.name,...e.region?{region:e.region}:{},config:{image:e.image,...e.env?{env:e.env}:{},guest:{cpu_kind:e.cpuKind??"shared",cpus:e.vcpus,memory_mb:e.memoryMb},...e.volume?.volumeId?{mounts:[{volume:e.volume.volumeId,path:e.volume.mountPath}]}:{},auto_destroy:e.autoDestroy??false,...o?{services:o}:{},...s?{checks:s}:{},...e.labels?{metadata:e.labels}:{}}}},t.apiUrl),i=u.config?.guest?.memory_mb??e.memoryMb,l=u.config?.guest?.cpus??e.vcpus;return {provider:"fly",externalId:u.id,name:u.name,region:u.region,appName:n,url:e.port?.publicHttps?`https://${n}.fly.dev`:void 0,memoryMb:i,vcpus:l,metadata:u.instance_id?{instanceId:u.instance_id}:void 0}},suspendInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=e.memoryMb;if(s===void 0&&(s=(await d(r,`/apps/${a}/machines/${o}`,{},t.apiUrl)).config?.guest?.memory_mb),s!==void 0&&s>y)throw new chunkQREJ73ZG_cjs.a("invalid_request",`Fly.io Machines suspend requires memoryMb <= ${y} (got ${s} MB)`,{provider:"fly"});await d(r,`/apps/${a}/machines/${o}/suspend`,{method:"POST"},t.apiUrl);let u=new URLSearchParams({state:"suspended",timeout:String(M)});return await d(r,`/apps/${a}/machines/${o}/wait?${u}`,{timeoutMs:h},t.apiUrl),{...e,appName:n,memoryMb:s}},wakeInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId);await d(r,`/apps/${a}/machines/${o}/start`,{method:"POST"},t.apiUrl);let s=new URLSearchParams({state:"started",timeout:String(M)});return await d(r,`/apps/${a}/machines/${o}/wait?${s}`,{timeoutMs:h},t.apiUrl),{...e,appName:n}},fetchInfrastructureResourceStatus:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=await d(r,`/apps/${a}/machines/${o}`,{},t.apiUrl);return w(s,e)},fetchInfrastructureResources:async t=>{let{token:e,appName:r}=c(t),n=encodeURIComponent(r);return (await d(e,`/apps/${n}/machines`,{},t.apiUrl)).map(o=>w(o))},fetchInfrastructureResourceUsage:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=await d(r,`/apps/${a}/machines/${o}`,{},t.apiUrl),u=Date.now(),i=b(s.events??[],s.state,u);return {provider:"fly",externalId:s.id,memoryMb:s.config?.guest?.memory_mb??e.memoryMb??0,vcpus:s.config?.guest?.cpus??e.vcpus??0,activeSeconds:i.activeSeconds,suspendedSeconds:i.suspendedSeconds,rootfsGb:_(e.metadata?.rootfsGb),metered:i.metered,windowStartIso:new Date(i.windowStartMs).toISOString(),windowEndIso:new Date(i.windowEndMs).toISOString()}},destroyInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId);await d(r,`/apps/${a}/machines/${o}?force=true`,{method:"DELETE"},t.apiUrl).catch(chunkQREJ73ZG_cjs.e);}};
2
+ exports.a=v;exports.b=d;exports.c=y;exports.d=U;//# sourceMappingURL=chunk-ISKFVF5B.cjs.map
3
+ //# sourceMappingURL=chunk-ISKFVF5B.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fly/flyRequest.ts","../src/fly/flyInfrastructureResourceDriver.ts"],"names":["FLY_MACHINES_API_URL","sendFlyRequest","token","path","init","apiUrl","sendInfraRequest","stripTrailingSlash","FLY_SUSPEND_MAX_MEMORY_MB","FLY_WAIT_TIMEOUT_SECONDS","FLY_WAIT_HTTP_TIMEOUT_MS","requireFlyAuth","credentials","appFallback","InfraError","appName","mapFlyMachineState","state","parseRootfsGb","raw","parsed","accumulateFlyEventDurations","events","currentState","nowMs","ordered","left","right","activeMs","suspendedMs","index","current","nextEvent","durationMs","lastTimestamp","flyMachineToInfrastructureResourceStatus","machine","handle","flyInfrastructureResourceDriver","spec","assertNoEgressAllowlist","encodedApp","services","checks","memoryMb","vcpus","encodedId","waitQuery","durations","ignoreNotFound"],"mappings":"qHAEO,IAAMA,CAAAA,CAAuB,6BAAA,CAQvBC,CAAAA,CAAiB,MAC5BC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAuB,EAAC,CACxBC,CAAAA,CAASL,CAAAA,GAETM,mBAAAA,CAAoB,CAAA,EAAGC,mBAAAA,CAAmBF,CAAM,CAAC,CAAA,EAAGF,CAAI,CAAA,CAAA,CAAI,CAC1D,MAAA,CAAQC,CAAAA,CAAK,MAAA,EAAU,KAAA,CACvB,KAAA,CAAAF,CAAAA,CACA,IAAA,CAAME,CAAAA,CAAK,KACX,SAAA,CAAWA,CAAAA,CAAK,SAAA,CAChB,QAAA,CAAU,KACZ,CAAC,ECVI,IAAMI,CAAAA,CAA4B,IAAA,CAEnCC,CAAAA,CAA2B,EAAA,CAC3BC,CAAAA,CAA2B,GAAA,CA4B3BC,CAAAA,CAAiB,CACrBC,EACAC,CAAAA,GACyD,CACzD,GAAI,CAACD,CAAAA,CAAY,KAAA,CACf,MAAM,IAAIE,mBAAAA,CAAW,uBAAA,CAAyB,8BAAA,CAAgC,CAC5E,QAAA,CAAU,KACZ,CAAC,CAAA,CAEH,IAAMC,CAAAA,CAAUH,CAAAA,CAAY,OAAA,EAAWC,CAAAA,CACvC,GAAI,CAACE,CAAAA,CACH,MAAM,IAAID,mBAAAA,CAAW,iBAAA,CAAmB,4BAAA,CAA8B,CACpE,QAAA,CAAU,KACZ,CAAC,EAEH,OAAO,CAAE,KAAA,CAAOF,CAAAA,CAAY,KAAA,CAAO,OAAA,CAAAG,CAAQ,CAC7C,CAAA,CAEMC,CAAAA,CAAsBC,CAAAA,EAAsD,CAChF,OAAQA,CAAAA,EACN,KAAK,UACH,OAAO,cAAA,CACT,KAAK,UAAA,CACH,OAAO,UAAA,CACT,KAAK,SAAA,CACH,OAAO,SAAA,CACT,KAA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D,aAAA,CAAeW,CAAAA,CAAU,aAAA,CACzB,gBAAA,CAAkBA,CAAAA,CAAU,gBAAA,CAC5B,QAAA,CAAU9B,CAAAA,CAAcmB,EAAO,QAAA,EAAU,QAAQ,CAAA,CACjD,OAAA,CAASW,CAAAA,CAAU,OAAA,CACnB,cAAA,CAAgB,IAAI,IAAA,CAAKA,CAAAA,CAAU,aAAa,CAAA,CAAE,WAAA,EAAY,CAC9D,YAAA,CAAc,IAAI,KAAKA,CAAAA,CAAU,WAAW,CAAA,CAAE,WAAA,EAChD,CACF,CAAA,CACA,6BAAA,CAA+B,MAC7BpC,CAAAA,CACAyB,CAAAA,GACkB,CAClB,GAAM,CAAE,KAAA,CAAAnC,CAAAA,CAAO,QAAAa,CAAQ,CAAA,CAAIJ,CAAAA,CAAeC,CAAAA,CAAayB,CAAAA,CAAO,OAAO,CAAA,CAC/DI,CAAAA,CAAa,kBAAA,CAAmB1B,CAAO,CAAA,CACvC+B,CAAAA,CAAY,kBAAA,CAAmBT,CAAAA,CAAO,UAAU,CAAA,CAEtD,MAAMpC,CAAAA,CACJC,CAAAA,CACA,CAAA,MAAA,EAASuC,CAAU,CAAA,UAAA,EAAaK,CAAS,CAAA,WAAA,CAAA,CACzC,CAAE,MAAA,CAAQ,QAAS,CAAA,CACnBlC,CAAAA,CAAY,MACd,CAAA,CAAE,KAAA,CAAMqC,mBAAc,EACxB,CACF","file":"chunk-ISKFVF5B.cjs","sourcesContent":["import { sendInfraRequest, stripTrailingSlash } from '../core/infraFetch.ts';\n\nexport const FLY_MACHINES_API_URL = 'https://api.machines.dev/v1';\n\nexport type FlyRequestInit = {\n readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly body?: unknown;\n readonly timeoutMs?: number;\n};\n\nexport const sendFlyRequest = async <T>(\n token: string,\n path: string,\n init: FlyRequestInit = {},\n apiUrl = FLY_MACHINES_API_URL,\n): Promise<T> =>\n sendInfraRequest<T>(`${stripTrailingSlash(apiUrl)}${path}`, {\n method: init.method ?? 'GET',\n token,\n body: init.body,\n timeoutMs: init.timeoutMs,\n provider: 'fly',\n });\n","import type {\n InfrastructureResourceCredentials,\n InfrastructureResourceDriver,\n InfrastructureResourceHandle,\n InfrastructureResourceRuntimeState,\n InfrastructureResourceSpec,\n InfrastructureResourceStatus,\n InfrastructureResourceUsage,\n} from '../core/contracts.ts';\nimport { assertNoEgressAllowlist, InfraError, ignoreNotFound } from '../core/infraError.ts';\nimport { sendFlyRequest } from './flyRequest.ts';\n\nexport const FLY_SUSPEND_MAX_MEMORY_MB = 2048;\n\nconst FLY_WAIT_TIMEOUT_SECONDS = 30;\nconst FLY_WAIT_HTTP_TIMEOUT_MS = 40_000;\n\ntype FlyMachineEvent = {\n readonly type: string;\n readonly status: string;\n readonly timestamp: number;\n};\n\ntype FlyMachine = {\n readonly id: string;\n readonly name: string;\n readonly state: string;\n readonly region: string;\n readonly instance_id?: string;\n readonly updated_at?: string;\n readonly created_at?: string;\n readonly config?: {\n readonly image?: string;\n readonly guest?: {\n readonly cpu_kind?: string;\n readonly cpus?: number;\n readonly memory_mb?: number;\n };\n readonly metadata?: Record<string, string>;\n };\n readonly events?: readonly FlyMachineEvent[];\n};\n\nconst requireFlyAuth = (\n credentials: InfrastructureResourceCredentials,\n appFallback?: string,\n): { readonly token: string; readonly appName: string } => {\n if (!credentials.token) {\n throw new InfraError('authentication_failed', 'Fly.io API token is required', {\n provider: 'fly',\n });\n }\n const appName = credentials.appName ?? appFallback;\n if (!appName) {\n throw new InfraError('invalid_request', 'Fly.io appName is required', {\n provider: 'fly',\n });\n }\n return { token: credentials.token, appName };\n};\n\nconst mapFlyMachineState = (state: string): InfrastructureResourceRuntimeState => {\n switch (state) {\n case 'created':\n return 'provisioning';\n case 'starting':\n return 'starting';\n case 'started':\n return 'running';\n case 'suspending':\n return 'suspending';\n case 'suspended':\n return 'suspended';\n case 'stopping':\n return 'stopping';\n case 'stopped':\n return 'stopped';\n case 'destroying':\n return 'destroying';\n case 'destroyed':\n return 'destroyed';\n default:\n return 'unknown';\n }\n};\n\nconst parseRootfsGb = (raw: string | undefined): number => {\n if (raw === undefined) return 0;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n};\n\nconst accumulateFlyEventDurations = (\n events: readonly FlyMachineEvent[],\n currentState: string,\n nowMs: number,\n): {\n readonly activeSeconds: number;\n readonly suspendedSeconds: number;\n readonly metered: boolean;\n readonly windowStartMs: number;\n readonly windowEndMs: number;\n} => {\n if (events.length === 0) {\n return {\n activeSeconds: 0,\n suspendedSeconds: 0,\n metered: false,\n windowStartMs: nowMs,\n windowEndMs: nowMs,\n };\n }\n\n const ordered = [...events].sort((left, right) => left.timestamp - right.timestamp);\n let activeMs = 0;\n let suspendedMs = 0;\n\n for (let index = 0; index < ordered.length; index += 1) {\n const current = ordered[index];\n const nextEvent = ordered[index + 1];\n if (nextEvent) {\n const durationMs = Math.max(0, nextEvent.timestamp - current.timestamp);\n if (current.status === 'started') {\n activeMs += durationMs;\n } else if (current.status === 'suspended') {\n suspendedMs += durationMs;\n }\n } else if (current.status === currentState) {\n // Only extend the trailing open interval when the last event reconciles with current state.\n const durationMs = Math.max(0, nowMs - current.timestamp);\n if (currentState === 'started') {\n activeMs += durationMs;\n } else if (currentState === 'suspended') {\n suspendedMs += durationMs;\n }\n }\n }\n\n const lastTimestamp = ordered[ordered.length - 1].timestamp;\n return {\n activeSeconds: Math.round(activeMs / 1000),\n suspendedSeconds: Math.round(suspendedMs / 1000),\n metered: true,\n windowStartMs: ordered[0].timestamp,\n windowEndMs: Math.max(nowMs, lastTimestamp),\n };\n};\n\nconst flyMachineToInfrastructureResourceStatus = (\n machine: FlyMachine,\n handle?: InfrastructureResourceHandle,\n): InfrastructureResourceStatus => ({\n provider: 'fly',\n externalId: machine.id,\n name: machine.name,\n state: mapFlyMachineState(machine.state),\n providerState: machine.state,\n region: machine.region,\n ...(handle?.url !== undefined ? { url: handle.url } : {}),\n memoryMb: machine.config?.guest?.memory_mb ?? handle?.memoryMb,\n vcpus: machine.config?.guest?.cpus ?? handle?.vcpus,\n createdAt: machine.created_at,\n updatedAt: machine.updated_at,\n labels: machine.config?.metadata,\n});\n\nexport const flyInfrastructureResourceDriver: InfrastructureResourceDriver = {\n provider: 'fly',\n provisionInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n spec: InfrastructureResourceSpec,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, spec.labels?.['fly.app']);\n assertNoEgressAllowlist(spec.egressAllowlist, 'fly');\n\n if (spec.volume && !spec.volume.volumeId) {\n throw new InfraError('invalid_request', 'Fly.io volume mounts require volume.volumeId', {\n provider: 'fly',\n });\n }\n\n const encodedApp = encodeURIComponent(appName);\n\n const services = spec.port\n ? [\n {\n protocol: spec.port.protocol ?? 'tcp',\n internal_port: spec.port.internalPort,\n autostart: false,\n autostop: 'off',\n ...(spec.port.publicHttps\n ? {\n ports: [{ port: 443, handlers: ['tls', 'http'] }],\n }\n : {}),\n },\n ]\n : undefined;\n\n const checks = spec.healthcheckPath\n ? {\n httpget: {\n type: 'http',\n port: spec.port?.internalPort ?? 8080,\n method: 'GET',\n path: spec.healthcheckPath,\n interval: '15s',\n timeout: '5s',\n },\n }\n : undefined;\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines`,\n {\n method: 'POST',\n body: {\n name: spec.name,\n ...(spec.region ? { region: spec.region } : {}),\n config: {\n image: spec.image,\n ...(spec.env ? { env: spec.env } : {}),\n guest: {\n cpu_kind: spec.cpuKind ?? 'shared',\n cpus: spec.vcpus,\n memory_mb: spec.memoryMb,\n },\n ...(spec.volume?.volumeId\n ? {\n mounts: [\n {\n volume: spec.volume.volumeId,\n path: spec.volume.mountPath,\n },\n ],\n }\n : {}),\n auto_destroy: spec.autoDestroy ?? false,\n ...(services ? { services } : {}),\n ...(checks ? { checks } : {}),\n ...(spec.labels ? { metadata: spec.labels } : {}),\n },\n },\n },\n credentials.apiUrl,\n );\n\n const memoryMb = machine.config?.guest?.memory_mb ?? spec.memoryMb;\n const vcpus = machine.config?.guest?.cpus ?? spec.vcpus;\n\n return {\n provider: 'fly',\n externalId: machine.id,\n name: machine.name,\n region: machine.region,\n appName,\n url: spec.port?.publicHttps ? `https://${appName}.fly.dev` : undefined,\n memoryMb,\n vcpus,\n metadata: machine.instance_id ? { instanceId: machine.instance_id } : undefined,\n };\n },\n suspendInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n let memoryMb = handle.memoryMb;\n if (memoryMb === undefined) {\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n memoryMb = machine.config?.guest?.memory_mb;\n }\n\n if (memoryMb !== undefined && memoryMb > FLY_SUSPEND_MAX_MEMORY_MB) {\n throw new InfraError(\n 'invalid_request',\n `Fly.io Machines suspend requires memoryMb <= ${FLY_SUSPEND_MAX_MEMORY_MB} (got ${memoryMb} MB)`,\n { provider: 'fly' },\n );\n }\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/suspend`,\n { method: 'POST' },\n credentials.apiUrl,\n );\n\n const waitQuery = new URLSearchParams({\n state: 'suspended',\n timeout: String(FLY_WAIT_TIMEOUT_SECONDS),\n });\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/wait?${waitQuery}`,\n { timeoutMs: FLY_WAIT_HTTP_TIMEOUT_MS },\n credentials.apiUrl,\n );\n\n return {\n ...handle,\n appName,\n memoryMb,\n };\n },\n wakeInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/start`,\n { method: 'POST' },\n credentials.apiUrl,\n );\n\n const waitQuery = new URLSearchParams({\n state: 'started',\n timeout: String(FLY_WAIT_TIMEOUT_SECONDS),\n });\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/wait?${waitQuery}`,\n { timeoutMs: FLY_WAIT_HTTP_TIMEOUT_MS },\n credentials.apiUrl,\n );\n\n return { ...handle, appName };\n },\n fetchInfrastructureResourceStatus: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceStatus> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n\n return flyMachineToInfrastructureResourceStatus(machine, handle);\n },\n fetchInfrastructureResources: async (\n credentials: InfrastructureResourceCredentials,\n ): Promise<InfrastructureResourceStatus[]> => {\n const { token, appName } = requireFlyAuth(credentials);\n const encodedApp = encodeURIComponent(appName);\n\n const machines = await sendFlyRequest<FlyMachine[]>(\n token,\n `/apps/${encodedApp}/machines`,\n {},\n credentials.apiUrl,\n );\n\n return machines.map((machine) => flyMachineToInfrastructureResourceStatus(machine));\n },\n fetchInfrastructureResourceUsage: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceUsage> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n const nowMs = Date.now();\n const durations = accumulateFlyEventDurations(machine.events ?? [], machine.state, nowMs);\n\n return {\n provider: 'fly',\n externalId: machine.id,\n memoryMb: machine.config?.guest?.memory_mb ?? handle.memoryMb ?? 0,\n vcpus: machine.config?.guest?.cpus ?? handle.vcpus ?? 0,\n activeSeconds: durations.activeSeconds,\n suspendedSeconds: durations.suspendedSeconds,\n rootfsGb: parseRootfsGb(handle.metadata?.rootfsGb),\n metered: durations.metered,\n windowStartIso: new Date(durations.windowStartMs).toISOString(),\n windowEndIso: new Date(durations.windowEndMs).toISOString(),\n };\n },\n destroyInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<void> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}?force=true`,\n { method: 'DELETE' },\n credentials.apiUrl,\n ).catch(ignoreNotFound);\n },\n};\n"]}
@@ -0,0 +1,3 @@
1
+ import {d as d$1,b as b$1}from'./chunk-NGWNYW3U.js';import {e,a,f}from'./chunk-S47XOR4G.js';var v="https://api.machines.dev/v1",d=async(t,e,r={},n=v)=>d$1(`${b$1(n)}${e}`,{method:r.method??"GET",token:t,body:r.body,timeoutMs:r.timeoutMs,provider:"fly"});var y=2048,M=30,h=4e4,c=(t,e)=>{if(!t.token)throw new a("authentication_failed","Fly.io API token is required",{provider:"fly"});let r=t.appName??e;if(!r)throw new a("invalid_request","Fly.io appName is required",{provider:"fly"});return {token:t.token,appName:r}},S=t=>{switch(t){case "created":return "provisioning";case "starting":return "starting";case "started":return "running";case "suspending":return "suspending";case "suspended":return "suspended";case "stopping":return "stopping";case "stopped":return "stopped";case "destroying":return "destroying";case "destroyed":return "destroyed";default:return "unknown"}},_=t=>{if(t===void 0)return 0;let e=Number(t);return Number.isFinite(e)&&e>=0?e:0},b=(t,e,r)=>{if(t.length===0)return {activeSeconds:0,suspendedSeconds:0,metered:false,windowStartMs:r,windowEndMs:r};let n=[...t].sort((u,i)=>u.timestamp-i.timestamp),a=0,o=0;for(let u=0;u<n.length;u+=1){let i=n[u],l=n[u+1];if(l){let m=Math.max(0,l.timestamp-i.timestamp);i.status==="started"?a+=m:i.status==="suspended"&&(o+=m);}else if(i.status===e){let m=Math.max(0,r-i.timestamp);e==="started"?a+=m:e==="suspended"&&(o+=m);}}let s=n[n.length-1].timestamp;return {activeSeconds:Math.round(a/1e3),suspendedSeconds:Math.round(o/1e3),metered:true,windowStartMs:n[0].timestamp,windowEndMs:Math.max(r,s)}},w=(t,e)=>({provider:"fly",externalId:t.id,name:t.name,state:S(t.state),providerState:t.state,region:t.region,...e?.url!==void 0?{url:e.url}:{},memoryMb:t.config?.guest?.memory_mb??e?.memoryMb,vcpus:t.config?.guest?.cpus??e?.vcpus,createdAt:t.created_at,updatedAt:t.updated_at,labels:t.config?.metadata}),U={provider:"fly",provisionInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.labels?.["fly.app"]);if(f(e.egressAllowlist,"fly"),e.volume&&!e.volume.volumeId)throw new a("invalid_request","Fly.io volume mounts require volume.volumeId",{provider:"fly"});let a$1=encodeURIComponent(n),o=e.port?[{protocol:e.port.protocol??"tcp",internal_port:e.port.internalPort,autostart:false,autostop:"off",...e.port.publicHttps?{ports:[{port:443,handlers:["tls","http"]}]}:{}}]:void 0,s=e.healthcheckPath?{httpget:{type:"http",port:e.port?.internalPort??8080,method:"GET",path:e.healthcheckPath,interval:"15s",timeout:"5s"}}:void 0,u=await d(r,`/apps/${a$1}/machines`,{method:"POST",body:{name:e.name,...e.region?{region:e.region}:{},config:{image:e.image,...e.env?{env:e.env}:{},guest:{cpu_kind:e.cpuKind??"shared",cpus:e.vcpus,memory_mb:e.memoryMb},...e.volume?.volumeId?{mounts:[{volume:e.volume.volumeId,path:e.volume.mountPath}]}:{},auto_destroy:e.autoDestroy??false,...o?{services:o}:{},...s?{checks:s}:{},...e.labels?{metadata:e.labels}:{}}}},t.apiUrl),i=u.config?.guest?.memory_mb??e.memoryMb,l=u.config?.guest?.cpus??e.vcpus;return {provider:"fly",externalId:u.id,name:u.name,region:u.region,appName:n,url:e.port?.publicHttps?`https://${n}.fly.dev`:void 0,memoryMb:i,vcpus:l,metadata:u.instance_id?{instanceId:u.instance_id}:void 0}},suspendInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a$1=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=e.memoryMb;if(s===void 0&&(s=(await d(r,`/apps/${a$1}/machines/${o}`,{},t.apiUrl)).config?.guest?.memory_mb),s!==void 0&&s>y)throw new a("invalid_request",`Fly.io Machines suspend requires memoryMb <= ${y} (got ${s} MB)`,{provider:"fly"});await d(r,`/apps/${a$1}/machines/${o}/suspend`,{method:"POST"},t.apiUrl);let u=new URLSearchParams({state:"suspended",timeout:String(M)});return await d(r,`/apps/${a$1}/machines/${o}/wait?${u}`,{timeoutMs:h},t.apiUrl),{...e,appName:n,memoryMb:s}},wakeInfrastructureResource:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId);await d(r,`/apps/${a}/machines/${o}/start`,{method:"POST"},t.apiUrl);let s=new URLSearchParams({state:"started",timeout:String(M)});return await d(r,`/apps/${a}/machines/${o}/wait?${s}`,{timeoutMs:h},t.apiUrl),{...e,appName:n}},fetchInfrastructureResourceStatus:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=await d(r,`/apps/${a}/machines/${o}`,{},t.apiUrl);return w(s,e)},fetchInfrastructureResources:async t=>{let{token:e,appName:r}=c(t),n=encodeURIComponent(r);return (await d(e,`/apps/${n}/machines`,{},t.apiUrl)).map(o=>w(o))},fetchInfrastructureResourceUsage:async(t,e)=>{let{token:r,appName:n}=c(t,e.appName),a=encodeURIComponent(n),o=encodeURIComponent(e.externalId),s=await d(r,`/apps/${a}/machines/${o}`,{},t.apiUrl),u=Date.now(),i=b(s.events??[],s.state,u);return {provider:"fly",externalId:s.id,memoryMb:s.config?.guest?.memory_mb??e.memoryMb??0,vcpus:s.config?.guest?.cpus??e.vcpus??0,activeSeconds:i.activeSeconds,suspendedSeconds:i.suspendedSeconds,rootfsGb:_(e.metadata?.rootfsGb),metered:i.metered,windowStartIso:new Date(i.windowStartMs).toISOString(),windowEndIso:new Date(i.windowEndMs).toISOString()}},destroyInfrastructureResource:async(t,e$1)=>{let{token:r,appName:n}=c(t,e$1.appName),a=encodeURIComponent(n),o=encodeURIComponent(e$1.externalId);await d(r,`/apps/${a}/machines/${o}?force=true`,{method:"DELETE"},t.apiUrl).catch(e);}};
2
+ export{v as a,d as b,y as c,U as d};//# sourceMappingURL=chunk-KW7XSHOO.js.map
3
+ //# sourceMappingURL=chunk-KW7XSHOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fly/flyRequest.ts","../src/fly/flyInfrastructureResourceDriver.ts"],"names":["FLY_MACHINES_API_URL","sendFlyRequest","token","path","init","apiUrl","sendInfraRequest","stripTrailingSlash","FLY_SUSPEND_MAX_MEMORY_MB","FLY_WAIT_TIMEOUT_SECONDS","FLY_WAIT_HTTP_TIMEOUT_MS","requireFlyAuth","credentials","appFallback","InfraError","appName","mapFlyMachineState","state","parseRootfsGb","raw","parsed","accumulateFlyEventDurations","events","currentState","nowMs","ordered","left","right","activeMs","suspendedMs","index","current","nextEvent","durationMs","lastTimestamp","flyMachineToInfrastructureResourceStatus","machine","handle","flyInfrastructureResourceDriver","spec","assertNoEgressAllowlist","encodedApp","services","checks","memoryMb","vcpus","encodedId","waitQuery","durations","ignoreNotFound"],"mappings":"4FAEO,IAAMA,CAAAA,CAAuB,6BAAA,CAQvBC,CAAAA,CAAiB,MAC5BC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAuB,EAAC,CACxBC,CAAAA,CAASL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AE,WAAA,EAAY,CAC9D,YAAA,CAAc,IAAI,KAAKA,CAAAA,CAAU,WAAW,CAAA,CAAE,WAAA,EAChD,CACF,CAAA,CACA,6BAAA,CAA+B,MAC7BpC,CAAAA,CACAyB,GAAAA,GACkB,CAClB,GAAM,CAAE,KAAA,CAAAnC,CAAAA,CAAO,QAAAa,CAAQ,CAAA,CAAIJ,CAAAA,CAAeC,CAAAA,CAAayB,GAAAA,CAAO,OAAO,CAAA,CAC/DI,CAAAA,CAAa,kBAAA,CAAmB1B,CAAO,CAAA,CACvC+B,CAAAA,CAAY,kBAAA,CAAmBT,GAAAA,CAAO,UAAU,CAAA,CAEtD,MAAMpC,CAAAA,CACJC,CAAAA,CACA,CAAA,MAAA,EAASuC,CAAU,CAAA,UAAA,EAAaK,CAAS,CAAA,WAAA,CAAA,CACzC,CAAE,MAAA,CAAQ,QAAS,CAAA,CACnBlC,CAAAA,CAAY,MACd,CAAA,CAAE,KAAA,CAAMqC,CAAc,EACxB,CACF","file":"chunk-KW7XSHOO.js","sourcesContent":["import { sendInfraRequest, stripTrailingSlash } from '../core/infraFetch.ts';\n\nexport const FLY_MACHINES_API_URL = 'https://api.machines.dev/v1';\n\nexport type FlyRequestInit = {\n readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly body?: unknown;\n readonly timeoutMs?: number;\n};\n\nexport const sendFlyRequest = async <T>(\n token: string,\n path: string,\n init: FlyRequestInit = {},\n apiUrl = FLY_MACHINES_API_URL,\n): Promise<T> =>\n sendInfraRequest<T>(`${stripTrailingSlash(apiUrl)}${path}`, {\n method: init.method ?? 'GET',\n token,\n body: init.body,\n timeoutMs: init.timeoutMs,\n provider: 'fly',\n });\n","import type {\n InfrastructureResourceCredentials,\n InfrastructureResourceDriver,\n InfrastructureResourceHandle,\n InfrastructureResourceRuntimeState,\n InfrastructureResourceSpec,\n InfrastructureResourceStatus,\n InfrastructureResourceUsage,\n} from '../core/contracts.ts';\nimport { assertNoEgressAllowlist, InfraError, ignoreNotFound } from '../core/infraError.ts';\nimport { sendFlyRequest } from './flyRequest.ts';\n\nexport const FLY_SUSPEND_MAX_MEMORY_MB = 2048;\n\nconst FLY_WAIT_TIMEOUT_SECONDS = 30;\nconst FLY_WAIT_HTTP_TIMEOUT_MS = 40_000;\n\ntype FlyMachineEvent = {\n readonly type: string;\n readonly status: string;\n readonly timestamp: number;\n};\n\ntype FlyMachine = {\n readonly id: string;\n readonly name: string;\n readonly state: string;\n readonly region: string;\n readonly instance_id?: string;\n readonly updated_at?: string;\n readonly created_at?: string;\n readonly config?: {\n readonly image?: string;\n readonly guest?: {\n readonly cpu_kind?: string;\n readonly cpus?: number;\n readonly memory_mb?: number;\n };\n readonly metadata?: Record<string, string>;\n };\n readonly events?: readonly FlyMachineEvent[];\n};\n\nconst requireFlyAuth = (\n credentials: InfrastructureResourceCredentials,\n appFallback?: string,\n): { readonly token: string; readonly appName: string } => {\n if (!credentials.token) {\n throw new InfraError('authentication_failed', 'Fly.io API token is required', {\n provider: 'fly',\n });\n }\n const appName = credentials.appName ?? appFallback;\n if (!appName) {\n throw new InfraError('invalid_request', 'Fly.io appName is required', {\n provider: 'fly',\n });\n }\n return { token: credentials.token, appName };\n};\n\nconst mapFlyMachineState = (state: string): InfrastructureResourceRuntimeState => {\n switch (state) {\n case 'created':\n return 'provisioning';\n case 'starting':\n return 'starting';\n case 'started':\n return 'running';\n case 'suspending':\n return 'suspending';\n case 'suspended':\n return 'suspended';\n case 'stopping':\n return 'stopping';\n case 'stopped':\n return 'stopped';\n case 'destroying':\n return 'destroying';\n case 'destroyed':\n return 'destroyed';\n default:\n return 'unknown';\n }\n};\n\nconst parseRootfsGb = (raw: string | undefined): number => {\n if (raw === undefined) return 0;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;\n};\n\nconst accumulateFlyEventDurations = (\n events: readonly FlyMachineEvent[],\n currentState: string,\n nowMs: number,\n): {\n readonly activeSeconds: number;\n readonly suspendedSeconds: number;\n readonly metered: boolean;\n readonly windowStartMs: number;\n readonly windowEndMs: number;\n} => {\n if (events.length === 0) {\n return {\n activeSeconds: 0,\n suspendedSeconds: 0,\n metered: false,\n windowStartMs: nowMs,\n windowEndMs: nowMs,\n };\n }\n\n const ordered = [...events].sort((left, right) => left.timestamp - right.timestamp);\n let activeMs = 0;\n let suspendedMs = 0;\n\n for (let index = 0; index < ordered.length; index += 1) {\n const current = ordered[index];\n const nextEvent = ordered[index + 1];\n if (nextEvent) {\n const durationMs = Math.max(0, nextEvent.timestamp - current.timestamp);\n if (current.status === 'started') {\n activeMs += durationMs;\n } else if (current.status === 'suspended') {\n suspendedMs += durationMs;\n }\n } else if (current.status === currentState) {\n // Only extend the trailing open interval when the last event reconciles with current state.\n const durationMs = Math.max(0, nowMs - current.timestamp);\n if (currentState === 'started') {\n activeMs += durationMs;\n } else if (currentState === 'suspended') {\n suspendedMs += durationMs;\n }\n }\n }\n\n const lastTimestamp = ordered[ordered.length - 1].timestamp;\n return {\n activeSeconds: Math.round(activeMs / 1000),\n suspendedSeconds: Math.round(suspendedMs / 1000),\n metered: true,\n windowStartMs: ordered[0].timestamp,\n windowEndMs: Math.max(nowMs, lastTimestamp),\n };\n};\n\nconst flyMachineToInfrastructureResourceStatus = (\n machine: FlyMachine,\n handle?: InfrastructureResourceHandle,\n): InfrastructureResourceStatus => ({\n provider: 'fly',\n externalId: machine.id,\n name: machine.name,\n state: mapFlyMachineState(machine.state),\n providerState: machine.state,\n region: machine.region,\n ...(handle?.url !== undefined ? { url: handle.url } : {}),\n memoryMb: machine.config?.guest?.memory_mb ?? handle?.memoryMb,\n vcpus: machine.config?.guest?.cpus ?? handle?.vcpus,\n createdAt: machine.created_at,\n updatedAt: machine.updated_at,\n labels: machine.config?.metadata,\n});\n\nexport const flyInfrastructureResourceDriver: InfrastructureResourceDriver = {\n provider: 'fly',\n provisionInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n spec: InfrastructureResourceSpec,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, spec.labels?.['fly.app']);\n assertNoEgressAllowlist(spec.egressAllowlist, 'fly');\n\n if (spec.volume && !spec.volume.volumeId) {\n throw new InfraError('invalid_request', 'Fly.io volume mounts require volume.volumeId', {\n provider: 'fly',\n });\n }\n\n const encodedApp = encodeURIComponent(appName);\n\n const services = spec.port\n ? [\n {\n protocol: spec.port.protocol ?? 'tcp',\n internal_port: spec.port.internalPort,\n autostart: false,\n autostop: 'off',\n ...(spec.port.publicHttps\n ? {\n ports: [{ port: 443, handlers: ['tls', 'http'] }],\n }\n : {}),\n },\n ]\n : undefined;\n\n const checks = spec.healthcheckPath\n ? {\n httpget: {\n type: 'http',\n port: spec.port?.internalPort ?? 8080,\n method: 'GET',\n path: spec.healthcheckPath,\n interval: '15s',\n timeout: '5s',\n },\n }\n : undefined;\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines`,\n {\n method: 'POST',\n body: {\n name: spec.name,\n ...(spec.region ? { region: spec.region } : {}),\n config: {\n image: spec.image,\n ...(spec.env ? { env: spec.env } : {}),\n guest: {\n cpu_kind: spec.cpuKind ?? 'shared',\n cpus: spec.vcpus,\n memory_mb: spec.memoryMb,\n },\n ...(spec.volume?.volumeId\n ? {\n mounts: [\n {\n volume: spec.volume.volumeId,\n path: spec.volume.mountPath,\n },\n ],\n }\n : {}),\n auto_destroy: spec.autoDestroy ?? false,\n ...(services ? { services } : {}),\n ...(checks ? { checks } : {}),\n ...(spec.labels ? { metadata: spec.labels } : {}),\n },\n },\n },\n credentials.apiUrl,\n );\n\n const memoryMb = machine.config?.guest?.memory_mb ?? spec.memoryMb;\n const vcpus = machine.config?.guest?.cpus ?? spec.vcpus;\n\n return {\n provider: 'fly',\n externalId: machine.id,\n name: machine.name,\n region: machine.region,\n appName,\n url: spec.port?.publicHttps ? `https://${appName}.fly.dev` : undefined,\n memoryMb,\n vcpus,\n metadata: machine.instance_id ? { instanceId: machine.instance_id } : undefined,\n };\n },\n suspendInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n let memoryMb = handle.memoryMb;\n if (memoryMb === undefined) {\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n memoryMb = machine.config?.guest?.memory_mb;\n }\n\n if (memoryMb !== undefined && memoryMb > FLY_SUSPEND_MAX_MEMORY_MB) {\n throw new InfraError(\n 'invalid_request',\n `Fly.io Machines suspend requires memoryMb <= ${FLY_SUSPEND_MAX_MEMORY_MB} (got ${memoryMb} MB)`,\n { provider: 'fly' },\n );\n }\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/suspend`,\n { method: 'POST' },\n credentials.apiUrl,\n );\n\n const waitQuery = new URLSearchParams({\n state: 'suspended',\n timeout: String(FLY_WAIT_TIMEOUT_SECONDS),\n });\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/wait?${waitQuery}`,\n { timeoutMs: FLY_WAIT_HTTP_TIMEOUT_MS },\n credentials.apiUrl,\n );\n\n return {\n ...handle,\n appName,\n memoryMb,\n };\n },\n wakeInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/start`,\n { method: 'POST' },\n credentials.apiUrl,\n );\n\n const waitQuery = new URLSearchParams({\n state: 'started',\n timeout: String(FLY_WAIT_TIMEOUT_SECONDS),\n });\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}/wait?${waitQuery}`,\n { timeoutMs: FLY_WAIT_HTTP_TIMEOUT_MS },\n credentials.apiUrl,\n );\n\n return { ...handle, appName };\n },\n fetchInfrastructureResourceStatus: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceStatus> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n\n return flyMachineToInfrastructureResourceStatus(machine, handle);\n },\n fetchInfrastructureResources: async (\n credentials: InfrastructureResourceCredentials,\n ): Promise<InfrastructureResourceStatus[]> => {\n const { token, appName } = requireFlyAuth(credentials);\n const encodedApp = encodeURIComponent(appName);\n\n const machines = await sendFlyRequest<FlyMachine[]>(\n token,\n `/apps/${encodedApp}/machines`,\n {},\n credentials.apiUrl,\n );\n\n return machines.map((machine) => flyMachineToInfrastructureResourceStatus(machine));\n },\n fetchInfrastructureResourceUsage: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<InfrastructureResourceUsage> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n const nowMs = Date.now();\n const durations = accumulateFlyEventDurations(machine.events ?? [], machine.state, nowMs);\n\n return {\n provider: 'fly',\n externalId: machine.id,\n memoryMb: machine.config?.guest?.memory_mb ?? handle.memoryMb ?? 0,\n vcpus: machine.config?.guest?.cpus ?? handle.vcpus ?? 0,\n activeSeconds: durations.activeSeconds,\n suspendedSeconds: durations.suspendedSeconds,\n rootfsGb: parseRootfsGb(handle.metadata?.rootfsGb),\n metered: durations.metered,\n windowStartIso: new Date(durations.windowStartMs).toISOString(),\n windowEndIso: new Date(durations.windowEndMs).toISOString(),\n };\n },\n destroyInfrastructureResource: async (\n credentials: InfrastructureResourceCredentials,\n handle: InfrastructureResourceHandle,\n ): Promise<void> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.externalId);\n\n await sendFlyRequest(\n token,\n `/apps/${encodedApp}/machines/${encodedId}?force=true`,\n { method: 'DELETE' },\n credentials.apiUrl,\n ).catch(ignoreNotFound);\n },\n};\n"]}
@@ -0,0 +1,2 @@
1
+ import {b as b$1}from'./chunk-55HNIEAS.js';import {a}from'./chunk-S47XOR4G.js';var b=730,F=.65,N=.1,u={railway:{memoryUsdPerGbHour:.0139,vcpuUsdPerHour:.0278,storageUsdPerGbMonth:.15},fly:{sharedVcpuUsdPerMonth:.7,performanceVcpuUsdPerMonth:21,memoryUsdPerGbMonth:6,suspendedRootfsUsdPerGbMonth:.15},render:{diskUsdPerGbMonth:.25},firecracker:{amortizedMemoryUsdPerGbMonth:3.5,amortizedVcpuUsdPerMonth:4,snapshotStorageUsdPerGbMonth:.05},aws:{fargateArmVcpuUsdPerHour:.0324,fargateArmMemoryUsdPerGbHour:.0036,storageUsdPerGbMonth:.08},gcp:{vcpuUsdPerHour:.0432,memoryUsdPerGbHour:.0048,storageUsdPerGbMonth:.1},azure:{vcpuUsdPerHour:.0432,memoryUsdPerGbHour:.0048,storageUsdPerGbMonth:.1}},h=e=>Math.round(e*1e4)/1e4,v=(e,t)=>{if(!Number.isFinite(e)||e<0)throw new a("invalid_request",`${t} must be a finite number >= 0 (got ${e})`)},x=(e,t)=>{if(!Number.isFinite(e)||e<0||e>1)throw new a("invalid_request",`${t} must be a finite number in [0, 1] (got ${e})`)},D=e=>{if(v(e.memoryMb,"memoryMb"),v(e.vcpus,"vcpus"),v(e.activeHoursPerMonth,"activeHoursPerMonth"),v(e.suspendedHoursPerMonth,"suspendedHoursPerMonth"),v(e.rootfsGb,"rootfsGb"),e.activeHoursPerMonth+e.suspendedHoursPerMonth>b)throw new a("invalid_request",`activeHoursPerMonth + suspendedHoursPerMonth must be <= ${b} (got ${e.activeHoursPerMonth+e.suspendedHoursPerMonth})`);let t=e.markupMultiplier??1;if(!Number.isFinite(t)||t<1)throw new a("invalid_request",`markupMultiplier must be a finite number >= 1 (got ${t})`);e.averageMemoryUtilization!==void 0&&x(e.averageMemoryUtilization,"averageMemoryUtilization"),e.averageCpuUtilization!==void 0&&x(e.averageCpuUtilization,"averageCpuUtilization");let r=e.memoryMb/1024,n=e.activeHoursPerMonth/b,o=(e.activeHoursPerMonth+e.suspendedHoursPerMonth)/b,m=e.suspendedHoursPerMonth/b,c=0,a$1=0,s="";switch(e.provider){case "railway":{let M=e.averageMemoryUtilization??F,k=e.averageCpuUtilization??N;c=r*M*e.activeHoursPerMonth*u.railway.memoryUsdPerGbHour+e.vcpus*k*e.activeHoursPerMonth*u.railway.vcpuUsdPerHour,a$1=e.rootfsGb*o*u.railway.storageUsdPerGbMonth,s="usage-metered active RAM/vCPU per second + persistent volume storage";break}case "fly":{let M=e.cpuKind==="performance"?u.fly.performanceVcpuUsdPerMonth:u.fly.sharedVcpuUsdPerMonth;c=(e.vcpus*M+r*u.fly.memoryUsdPerGbMonth)*n,a$1=e.rootfsGb*m*u.fly.suspendedRootfsUsdPerGbMonth,s="provisioned Firecracker microVM per second while active + rootfs-only storage while suspended";break}case "render":{let M=b$1(e.memoryMb);c=M.monthlyUsd*n,a$1=e.rootfsGb*o*u.render.diskUsdPerGbMonth,s=`prorated fixed Render ${M.id} tier while unsuspended + persistent disk`;break}case "firecracker":{c=(r*u.firecracker.amortizedMemoryUsdPerGbMonth+e.vcpus*u.firecracker.amortizedVcpuUsdPerMonth)*n,a$1=(e.rootfsGb+r)*m*u.firecracker.snapshotStorageUsdPerGbMonth,s="amortized dedicated bare-metal host capacity while active + NVMe snapshot storage while suspended";break}case "aws":{c=e.vcpus*e.activeHoursPerMonth*u.aws.fargateArmVcpuUsdPerHour+r*e.activeHoursPerMonth*u.aws.fargateArmMemoryUsdPerGbHour,a$1=e.rootfsGb*o*u.aws.storageUsdPerGbMonth,s="AWS Fargate ARM provisioned vCPU/GB-hour + EBS/snapshot storage";break}case "gcp":{c=e.vcpus*e.activeHoursPerMonth*u.gcp.vcpuUsdPerHour+r*e.activeHoursPerMonth*u.gcp.memoryUsdPerGbHour,a$1=e.rootfsGb*o*u.gcp.storageUsdPerGbMonth,s="GCP provisioned vCPU/GB-hour + persistent storage";break}case "azure":{c=e.vcpus*e.activeHoursPerMonth*u.azure.vcpuUsdPerHour+r*e.activeHoursPerMonth*u.azure.memoryUsdPerGbHour,a$1=e.rootfsGb*o*u.azure.storageUsdPerGbMonth,s="Azure Container Apps provisioned vCPU/GB-hour + storage";break}}let l=h(c),p=h(a$1),d=h(l+p),f=h(d*t),_=h(f-d);return {provider:e.provider,activeComputeUsd:l,suspendedStorageUsd:p,rawMonthlyCostUsd:d,markupMultiplier:t,markedUpMonthlyCostUsd:f,marginUsd:_,pricingBasis:s}};var T=["railway","render","fly","firecracker"],ne=["aws","gcp","azure"],O=["railway","render"],U={railway:{id:"railway",name:"Railway",implemented:true,supportsArchiveHosting:true,supportsInfrastructureResourceDriver:true,isolation:"container",supportsSuspend:false,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"active_utilization_second",notes:"Usage-metered memory and CPU per second; stopped services bill nothing; no memory-snapshot suspend."},render:{id:"render",name:"Render",implemented:true,supportsArchiveHosting:true,supportsInfrastructureResourceDriver:true,isolation:"container",supportsSuspend:false,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"flat_plan_month",notes:"Managed web services and Postgres on fixed tiers; service suspend stops execution without a memory snapshot."},fly:{id:"fly",name:"Fly.io Machines",implemented:true,supportsArchiveHosting:false,supportsInfrastructureResourceDriver:true,isolation:"microvm",supportsSuspend:true,suspendMaxMemoryMb:2048,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"provisioned_second_with_suspend_storage",notes:"Firecracker microVMs with GA memory-snapshot suspend up to 2048 MB RAM and rootfs-only suspended storage billing."},firecracker:{id:"firecracker",name:"Firecracker",implemented:true,supportsArchiveHosting:false,supportsInfrastructureResourceDriver:true,isolation:"microvm",supportsSuspend:true,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"host_machine_month",notes:"Direct Firecracker VMM HTTP/Unix control plane for dedicated or bare-metal microVM hosts with full memory snapshots."},aws:{id:"aws",name:"AWS (Fargate / Lambda MicroVMs)",implemented:false,supportsArchiveHosting:false,supportsInfrastructureResourceDriver:false,isolation:"microvm",supportsSuspend:true,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"provisioned_vcpu_memory_second",notes:"Planned cloud adapter for AWS Fargate tasks and Firecracker-backed Lambda MicroVMs (8h session cap)."},gcp:{id:"gcp",name:"Google Cloud (Cloud Run / GKE Autopilot)",implemented:false,supportsArchiveHosting:false,supportsInfrastructureResourceDriver:false,isolation:"microvm",supportsSuspend:false,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"provisioned_vcpu_memory_second",notes:"Planned cloud adapter for Google Cloud Run and GKE Autopilot."},azure:{id:"azure",name:"Azure (Container Apps / ACI)",implemented:false,supportsArchiveHosting:false,supportsInfrastructureResourceDriver:false,isolation:"container",supportsSuspend:false,supportsByoAccount:true,supportsManagedAccount:true,billingUnit:"provisioned_vcpu_memory_second",notes:"Planned cloud adapter for Azure Container Apps and Container Instances."}},oe=e=>typeof e=="string"&&Object.hasOwn(U,e),se=e=>T.some(t=>t===e),ae=e=>O.some(t=>t===e),C=e=>U[e];var R=(e,t={})=>{switch(e){case "warm-interactive":return {infrastructureResourceClass:e,idleSuspendMs:48e4,idleStopMs:108e5,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:864e5,maxSuspendedMs:12096e5,softMemoryRecycleMb:1536,hardMemoryCapMb:2048,requireArchiveFlushBeforeWindDown:false,workingHoursPrewarm:t.workingHoursPrewarm,idleAction:"suspend"};case "warm-pool":return {infrastructureResourceClass:e,idleSuspendMs:t.warmRetentionMode==="extended"?36e5:3e5,idleStopMs:108e5,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:864e5,maxSuspendedMs:6048e5,softMemoryRecycleMb:1536,hardMemoryCapMb:2048,requireArchiveFlushBeforeWindDown:false,workingHoursPrewarm:t.workingHoursPrewarm,idleAction:"suspend"};case "batch-worker":return {infrastructureResourceClass:e,idleSuspendMs:3e5,idleStopMs:3e5,drainGraceMs:12e4,pendingApprovalGraceMs:0,maxLifetimeMs:144e5,maxSuspendedMs:864e5,softMemoryRecycleMb:1536,hardMemoryCapMb:2048,requireArchiveFlushBeforeWindDown:false,idleAction:"terminate"};case "ephemeral-session":return {infrastructureResourceClass:e,idleSuspendMs:9e5,idleStopMs:9e5,drainGraceMs:6e4,pendingApprovalGraceMs:18e5,maxLifetimeMs:864e5,maxSuspendedMs:6048e5,softMemoryRecycleMb:null,hardMemoryCapMb:null,requireArchiveFlushBeforeWindDown:true,idleAction:"suspend"};case "always-on":return {infrastructureResourceClass:e,idleSuspendMs:null,idleStopMs:null,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:null,maxSuspendedMs:null,softMemoryRecycleMb:null,hardMemoryCapMb:null,requireArchiveFlushBeforeWindDown:false,idleAction:"keep_warm"}}};var q=15e3,H=3e4,z=1e4,B=3e5,I=36e5,W=24*I,A=(e,t)=>{if(!Number.isFinite(e))throw new a("invalid_request",`${t} must be a finite number (got ${e})`)},S=(e,t)=>{if(!Number.isFinite(e)||e<0)throw new a("invalid_request",`${t} must be a finite number >= 0 (got ${e})`)},w=(e,t)=>{if(!Number.isInteger(e)||e<0)throw new a("invalid_request",`${t} must be an integer >= 0 (got ${e})`)},g=(e,t)=>{if(e!=null&&(!Number.isFinite(e)||e<=0))throw new a("invalid_request",`${t} must be a finite number > 0 (got ${e})`)},$=e=>{if(A(e.timezoneOffsetMinutes,"workingHoursPrewarm.timezoneOffsetMinutes"),!Number.isFinite(e.startHour)||e.startHour<0||e.startHour>=24)throw new a("invalid_request",`workingHoursPrewarm.startHour must be in [0, 24) (got ${e.startHour})`);if(!Number.isFinite(e.endHour)||e.endHour<0||e.endHour>24)throw new a("invalid_request",`workingHoursPrewarm.endHour must be in [0, 24] (got ${e.endHour})`);S(e.prewarmLeadMs,"workingHoursPrewarm.prewarmLeadMs");},V=(e,t,r)=>{A(t,"nowMs"),A(e.createdAtMs,"snapshot.createdAtMs"),A(e.lastActivityAtMs,"snapshot.lastActivityAtMs"),A(e.stateEnteredAtMs,"snapshot.stateEnteredAtMs"),w(e.inFlightTurns,"snapshot.inFlightTurns"),w(e.activeBackgroundShells,"snapshot.activeBackgroundShells"),e.pendingApprovals!==void 0&&w(e.pendingApprovals,"snapshot.pendingApprovals"),g(e.provisionedMemoryMb,"snapshot.provisionedMemoryMb"),g(e.rssMemoryMb,"snapshot.rssMemoryMb"),r.idleSuspendMs!==null&&S(r.idleSuspendMs,"policy.idleSuspendMs"),r.idleStopMs!==null&&S(r.idleStopMs,"policy.idleStopMs"),S(r.drainGraceMs,"policy.drainGraceMs"),S(r.pendingApprovalGraceMs,"policy.pendingApprovalGraceMs"),r.maxLifetimeMs!==null&&g(r.maxLifetimeMs,"policy.maxLifetimeMs"),r.maxSuspendedMs!==null&&g(r.maxSuspendedMs,"policy.maxSuspendedMs"),g(r.softMemoryRecycleMb,"policy.softMemoryRecycleMb"),g(r.hardMemoryCapMb,"policy.hardMemoryCapMb"),r.workingHoursPrewarm&&$(r.workingHoursPrewarm);},E=(e,t,r)=>{let n=t.timezoneOffsetMinutes*6e4,o=new Date(e+n+r*W),m=o.getUTCDay();if(t.weekdaysOnly&&(m===0||m===6))return null;let c=Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate())-n,a=c+t.startHour*I,s=t.endHour<=t.startHour,l=c+t.endHour*I+(s?W:0);return {prewarmStartMs:a-t.prewarmLeadMs,windowStartMs:a,windowEndMs:l}},L=(e,t)=>{for(let r of [-1,0,1]){let n=E(e,t,r);if(n&&e>=n.prewarmStartMs&&e<n.windowEndMs)return n}return null},Y=(e,t)=>{let r=null;for(let n=0;n<=8;n+=1){let o=E(e,t,n);o&&o.prewarmStartMs>e&&(r=r===null?o.prewarmStartMs:Math.min(r,o.prewarmStartMs));}return r},y=(...e)=>{let t=null;for(let r of e)r!=null&&(t=t===null?r:Math.min(t,r));return t},j=(e,t,r=R(e.infrastructureResourceClass,{warmRetentionMode:e.warmRetentionMode}))=>{V(e,t,r);let n=C(e.provider),o=e.inFlightTurns>0||e.activeBackgroundShells>0,m=(e.pendingApprovals??0)>0,c=Math.max(0,t-e.createdAtMs),a=r.maxLifetimeMs!==null&&c>=r.maxLifetimeMs,s=r.maxLifetimeMs!==null?e.createdAtMs+r.maxLifetimeMs:null;if(e.state==="destroyed")return {action:"none",reason:"infrastructure_resource_already_destroyed",nextCheckAtMs:null};if(e.state==="failed"||e.state==="orphaned")return {action:"terminate",reason:`reap_${e.state}_infrastructure_resource`,nextCheckAtMs:null};if(e.state==="provisioning"||e.state==="booting"||e.state==="suspending"||e.state==="terminating")return {action:"none",reason:`infrastructure_resource_${e.state}`,nextCheckAtMs:t+q};if(e.state==="suspended"){let d=Math.max(0,t-e.stateEnteredAtMs);if(r.maxSuspendedMs!==null&&d>=r.maxSuspendedMs)return {action:"terminate",reason:"suspended_retention_expired",nextCheckAtMs:null};if(r.workingHoursPrewarm&&L(t,r.workingHoursPrewarm))return {action:"prewarm",reason:"working_hours_prewarm_window",nextCheckAtMs:null};let f=r.maxSuspendedMs!==null?e.stateEnteredAtMs+r.maxSuspendedMs:null,_=r.workingHoursPrewarm?Y(t,r.workingHoursPrewarm):null;return {action:"none",reason:"suspended_within_retention",nextCheckAtMs:y(f,_,t+B)}}if(e.state==="draining"){let d=Math.max(0,t-e.stateEnteredAtMs),f=e.stateEnteredAtMs+r.drainGraceMs,_=Math.max(0,t-e.lastActivityAtMs);if(o)return a?d<r.drainGraceMs?{action:"none",reason:"waiting_for_in_flight_work_to_drain",nextCheckAtMs:f}:{action:"terminate",reason:"max_lifetime_exceeded_with_active_work",nextCheckAtMs:null}:{action:"none",reason:"active_work_blocks_idle_drain",nextCheckAtMs:y(s,t+H)};if(m&&!a&&r.pendingApprovalGraceMs>0&&_<r.pendingApprovalGraceMs)return {action:"none",reason:"waiting_for_pending_approval",nextCheckAtMs:y(s,e.lastActivityAtMs+r.pendingApprovalGraceMs)};if(r.requireArchiveFlushBeforeWindDown&&!e.archiveFlushed)return !a||d<r.drainGraceMs?{action:"none",reason:"waiting_for_archive_flush",nextCheckAtMs:t+z}:{action:"terminate",reason:"max_lifetime_exceeded_without_archive_flush",nextCheckAtMs:null};if(a)return {action:"terminate",reason:"max_lifetime_reached_after_drain",nextCheckAtMs:null};if(r.idleAction==="terminate")return {action:"terminate",reason:"drain_complete_ready_to_terminate",nextCheckAtMs:null};let M=e.provisionedMemoryMb??e.rssMemoryMb;return n.supportsSuspend&&n.suspendMaxMemoryMb!==void 0&&M!==void 0&&M>n.suspendMaxMemoryMb?r.hardMemoryCapMb!==null?{action:"recycle",reason:"memory_exceeds_provider_suspend_cap",nextCheckAtMs:null}:{action:"terminate",reason:"cannot_suspend_above_provider_memory_cap",nextCheckAtMs:null}:{action:"suspend",reason:n.supportsSuspend?"drain_complete_ready_to_suspend":"drain_complete_ready_to_stop",nextCheckAtMs:null}}if(a)return o||r.requireArchiveFlushBeforeWindDown&&!e.archiveFlushed?{action:"drain",reason:"max_lifetime_reached_draining",nextCheckAtMs:t+r.drainGraceMs}:{action:"terminate",reason:"max_lifetime_reached",nextCheckAtMs:null};if(r.hardMemoryCapMb!==null&&e.rssMemoryMb!==void 0&&e.rssMemoryMb>(n.suspendMaxMemoryMb!==void 0?Math.min(r.hardMemoryCapMb,n.suspendMaxMemoryMb):r.hardMemoryCapMb))return {action:"recycle",reason:"rss_exceeds_hard_cap",nextCheckAtMs:null};if(r.softMemoryRecycleMb!==null&&e.rssMemoryMb!==void 0&&e.rssMemoryMb>=r.softMemoryRecycleMb&&!o)return {action:"recycle",reason:"rss_exceeds_soft_recycle_threshold",nextCheckAtMs:null};if(e.pinnedWarm||r.idleAction==="keep_warm")return {action:"none",reason:"infrastructure_resource_pinned_warm",nextCheckAtMs:s};if(r.workingHoursPrewarm){let d=L(t,r.workingHoursPrewarm);if(d)return {action:"none",reason:"within_working_hours_window",nextCheckAtMs:y(s,d.windowEndMs)}}if(o)return {action:"none",reason:"active_work_in_progress",nextCheckAtMs:y(s,t+H)};let l=n.supportsSuspend?r.idleSuspendMs:r.idleStopMs;if(l===null)return {action:"none",reason:"no_idle_timeout_configured",nextCheckAtMs:s};let p=Math.max(0,t-e.lastActivityAtMs);if(m&&r.pendingApprovalGraceMs>0){let d=Math.max(l,r.pendingApprovalGraceMs);if(p<d)return {action:"none",reason:"waiting_for_pending_approval",nextCheckAtMs:y(s,e.lastActivityAtMs+d)}}return p>=l?{action:"drain",reason:"idle_timeout_reached",nextCheckAtMs:t+r.drainGraceMs}:{action:"none",reason:"within_idle_window",nextCheckAtMs:y(s,e.lastActivityAtMs+l)}};var K=["provisioning","booting","warm","active","draining","suspending","suspended","terminating","destroyed","failed","orphaned"],Z=["warm-interactive","warm-pool","batch-worker","ephemeral-session","always-on"];var J=1e3,G=(e,t)=>{let r=(t.priority??0)-(e.priority??0);if(r!==0)return r;let n=e.requestedAtMs-t.requestedAtMs;return n!==0?n:e.infrastructureResourceId<t.infrastructureResourceId?-1:e.infrastructureResourceId>t.infrastructureResourceId?1:0},Q=e=>{let t=new Map;for(let r of e){if(!r.infrastructureResourceId)throw new a("invalid_request","StaggeredWakeRequest.infrastructureResourceId must be non-empty");if(!Number.isFinite(r.requestedAtMs))throw new a("invalid_request",`requestedAtMs must be finite (got ${r.requestedAtMs})`);if(r.priority!==void 0&&!Number.isFinite(r.priority))throw new a("invalid_request",`priority must be finite (got ${r.priority})`);let n=t.get(r.infrastructureResourceId);(!n||G(r,n)<0)&&t.set(r.infrastructureResourceId,r);}return [...t.values()]},X=(e,t,r)=>{if(!Number.isFinite(t))throw new a("invalid_request",`nowMs must be finite (got ${t})`);if(!Number.isInteger(r.maxConcurrentWakes)||r.maxConcurrentWakes<1)throw new a("invalid_request",`maxConcurrentWakes must be an integer >= 1 (got ${r.maxConcurrentWakes})`);if(!Number.isFinite(r.minSpacingMs)||r.minSpacingMs<0)throw new a("invalid_request",`minSpacingMs must be a finite number >= 0 (got ${r.minSpacingMs})`);if(r.inFlightWakeCount!==void 0&&(!Number.isInteger(r.inFlightWakeCount)||r.inFlightWakeCount<0))throw new a("invalid_request",`inFlightWakeCount must be an integer >= 0 (got ${r.inFlightWakeCount})`);if(r.lastWakeLaunchedAtMs!==void 0&&r.lastWakeLaunchedAtMs!==null&&!Number.isFinite(r.lastWakeLaunchedAtMs))throw new a("invalid_request",`lastWakeLaunchedAtMs must be finite or null (got ${r.lastWakeLaunchedAtMs})`);let n=Q(e).sort(G),o=r.inFlightWakeCount??0,m=Math.max(0,r.maxConcurrentWakes-o),c=[],a$1=[],s=r.minSpacingMs>0?r.minSpacingMs:J,l=r.lastWakeLaunchedAtMs!==null&&r.lastWakeLaunchedAtMs!==void 0?Math.max(t,r.lastWakeLaunchedAtMs+r.minSpacingMs):t,p=0;for(let d of n){if(p>=m){let f=Math.max(l,t+s);a$1.push({request:d,earliestLaunchAtMs:f,reason:"concurrency_limit"}),l=f+s;continue}if(l>t){a$1.push({request:d,earliestLaunchAtMs:l,reason:"spacing_interval"}),p+=1,l+=r.minSpacingMs;continue}c.push(d),p+=1,r.minSpacingMs>0&&(l=t+r.minSpacingMs);}return {launchNow:c,defer:a$1}};export{T as a,ne as b,O as c,U as d,oe as e,se as f,ae as g,C as h,u as i,D as j,R as k,j as l,K as m,Z as n,X as o};//# sourceMappingURL=chunk-MFNST5XH.js.map
2
+ //# sourceMappingURL=chunk-MFNST5XH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lifecycle/costProjection.ts","../src/core/providers.ts","../src/lifecycle/lifecyclePolicy.ts","../src/lifecycle/evaluateInfrastructureResourceLifecycle.ts","../src/lifecycle/lifecycleTypes.ts","../src/lifecycle/staggeredWakes.ts"],"names":["HOURS_PER_MONTH","DEFAULT_RAILWAY_MEMORY_UTILIZATION","DEFAULT_RAILWAY_CPU_UTILIZATION","HOSTING_PRICING_RATES","roundUsd","amount","requireNonNegative","value","name","InfraError","requireUnitInterval","projectHostingMonthlyCost","input","markupMultiplier","memoryGb","activeMonthFraction","totalStoredMonthFraction","suspendedMonthFraction","activeComputeUsd","suspendedStorageUsd","pricingBasis","memUtil","cpuUtil","vcpuMonthRate","plan","renderPlanForMemoryMb","roundedActive","roundedStorage","roundedRaw","roundedMarkedUp","roundedMargin","IMPLEMENTED_INFRA_PROVIDERS","PLANNED_INFRA_PROVIDERS","ARCHIVE_HOSTING_PROVIDERS","INFRA_PROVIDERS","isInfraProvider","isImplementedInfraProvider","provider","isArchiveHostingProvider","infraProviderDescriptor","defaultInfrastructureResourceLifecyclePolicy","infrastructureResourceClass","options","TRANSITIONAL_POLL_MS","ACTIVE_WORK_POLL_MS","ARCHIVE_FLUSH_POLL_MS","SUSPENDED_POLL_MS","HOUR_MS","DAY_MS","assertFiniteNumber","assertNonNegativeFinite","assertNonNegativeInteger","assertPositiveOptional","validateWorkingHoursSchedule","schedule","validateSnapshotAndPolicy","snapshot","nowMs","policy","workingWindowForDayDelta","dayDelta","offsetMs","shifted","dayOfWeek","localMidnightUtcMs","windowStartMs","isOvernight","windowEndMs","activeWorkingWindowAt","bounds","nextWorkingHoursPrewarmAtMs","next","earliestCheckTime","candidates","earliest","candidate","evaluateInfrastructureResourceLifecycle","descriptor","hasActiveWork","hasPendingApprovals","ageMs","maxLifetimeReached","lifetimeDeadlineMs","suspendedElapsedMs","expiryAtMs","nextPrewarmAtMs","drainElapsedMs","drainDeadlineMs","idleElapsedMs","suspendMemoryMb","activeWindow","idleLimitMs","approvalLimitMs","INFRASTRUCTURE_RESOURCE_LIFECYCLE_STATES","INFRASTRUCTURE_RESOURCE_CLASSES","DEFAULT_CONCURRENCY_RETRY_FLOOR_MS","compareWakeRequests","left","right","priorityDiff","requestedDiff","deduplicateRequests","requests","byInfrastructureResourceId","request","existing","planStaggeredWakes","sorted","inFlight","availableSlots","launchNow","defer","retryStepMs","nextEligibleAtMs","scheduledWithinConcurrency","earliestLaunchAtMs"],"mappings":"+EAKA,IAAMA,CAAAA,CAAkB,GAAA,CAClBC,CAAAA,CAAqC,GAAA,CACrCC,EAAkC,EAAA,CA0B3BC,CAAAA,CAAwB,CACnC,OAAA,CAAS,CACP,kBAAA,CAAoB,KAAA,CACpB,cAAA,CAAgB,MAChB,oBAAA,CAAsB,GACxB,CAAA,CACA,GAAA,CAAK,CACH,qBAAA,CAAuB,EAAA,CACvB,0BAAA,CAA4B,GAC5B,mBAAA,CAAqB,CAAA,CACrB,4BAAA,CAA8B,GAChC,CAAA,CACA,MAAA,CAAQ,CACN,iBAAA,CAAmB,GACrB,CAAA,CACA,WAAA,CAAa,CACX,4BAAA,CAA8B,GAAA,CAC9B,wBAAA,CAA0B,CAAA,CAC1B,4BAAA,CAA8B,GAChC,CAAA,CACA,GAAA,CAAK,CACH,wBAAA,CAA0B,KAAA,CAC1B,4BAAA,CAA8B,KAAA,CAC9B,oBAAA,CAAsB,GACxB,CAAA,CACA,GAAA,CAAK,CACH,cAAA,CAAgB,KAAA,CAChB,kBAAA,CAAoB,KAAA,CACpB,oBAAA,CAAsB,EACxB,CAAA,CACA,KAAA,CAAO,CACL,cAAA,CAAgB,MAChB,kBAAA,CAAoB,KAAA,CACpB,oBAAA,CAAsB,EACxB,CACF,CAAA,CAEMC,CAAAA,CAAYC,CAAAA,EAA2B,IAAA,CAAK,KAAA,CAAMA,CAAAA,CAAS,GAAM,CAAA,CAAI,IAErEC,CAAAA,CAAqB,CAACC,CAAAA,CAAeC,CAAAA,GAAuB,CAChE,G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AAAA,CAAkBxD,CAAAA,CAAQuD,CAAW,CAAA,CACzED,GAAAA,CAAM,KAAK,CACT,OAAA,CAAAP,CAAAA,CACA,kBAAA,CAAAW,CAAAA,CACA,MAAA,CAAQ,mBACV,CAAC,EACDF,CAAAA,CAAmBE,CAAAA,CAAqBH,CAAAA,CACxC,QACF,CAEA,GAAIC,CAAAA,CAAmBxD,CAAAA,CAAO,CAC5BsD,IAAM,IAAA,CAAK,CACT,OAAA,CAAAP,CAAAA,CACA,kBAAA,CAAoBS,CAAAA,CACpB,MAAA,CAAQ,kBACV,CAAC,CAAA,CACDC,CAAAA,EAA8B,CAAA,CAC9BD,CAAAA,EAAoBvE,CAAAA,CAAQ,YAAA,CAC5B,QACF,CAEAoE,EAAU,IAAA,CAAKN,CAAO,CAAA,CACtBU,CAAAA,EAA8B,CAAA,CAC1BxE,CAAAA,CAAQ,YAAA,CAAe,CAAA,GACzBuE,EAAmBxD,CAAAA,CAAQf,CAAAA,CAAQ,YAAA,EAEvC,CAEA,OAAO,CAAE,SAAA,CAAAoE,CAAAA,CAAW,KAAA,CAAAC,GAAM,CAC5B","file":"chunk-MFNST5XH.js","sourcesContent":["import type { InfrastructureResourceCpuKind } from '../core/contracts.ts';\nimport { InfraError } from '../core/infraError.ts';\nimport type { InfraProviderId } from '../core/providers.ts';\nimport { renderPlanForMemoryMb } from '../render/renderPlans.ts';\n\nconst HOURS_PER_MONTH = 730;\nconst DEFAULT_RAILWAY_MEMORY_UTILIZATION = 0.65;\nconst DEFAULT_RAILWAY_CPU_UTILIZATION = 0.1;\n\nexport type HostingCostProjectionInput = {\n readonly provider: InfraProviderId;\n readonly memoryMb: number;\n readonly vcpus: number;\n readonly activeHoursPerMonth: number;\n readonly suspendedHoursPerMonth: number;\n readonly rootfsGb: number;\n readonly markupMultiplier?: number;\n readonly averageMemoryUtilization?: number;\n readonly averageCpuUtilization?: number;\n readonly cpuKind?: InfrastructureResourceCpuKind;\n};\n\nexport type HostingCostProjection = {\n readonly provider: InfraProviderId;\n readonly activeComputeUsd: number;\n readonly suspendedStorageUsd: number;\n readonly rawMonthlyCostUsd: number;\n readonly markupMultiplier: number;\n readonly markedUpMonthlyCostUsd: number;\n readonly marginUsd: number;\n readonly pricingBasis: string;\n};\n\nexport const HOSTING_PRICING_RATES = {\n railway: {\n memoryUsdPerGbHour: 0.0139,\n vcpuUsdPerHour: 0.0278,\n storageUsdPerGbMonth: 0.15,\n },\n fly: {\n sharedVcpuUsdPerMonth: 0.7,\n performanceVcpuUsdPerMonth: 21.0,\n memoryUsdPerGbMonth: 6.0,\n suspendedRootfsUsdPerGbMonth: 0.15,\n },\n render: {\n diskUsdPerGbMonth: 0.25,\n },\n firecracker: {\n amortizedMemoryUsdPerGbMonth: 3.5,\n amortizedVcpuUsdPerMonth: 4.0,\n snapshotStorageUsdPerGbMonth: 0.05,\n },\n aws: {\n fargateArmVcpuUsdPerHour: 0.0324,\n fargateArmMemoryUsdPerGbHour: 0.0036,\n storageUsdPerGbMonth: 0.08,\n },\n gcp: {\n vcpuUsdPerHour: 0.0432,\n memoryUsdPerGbHour: 0.0048,\n storageUsdPerGbMonth: 0.1,\n },\n azure: {\n vcpuUsdPerHour: 0.0432,\n memoryUsdPerGbHour: 0.0048,\n storageUsdPerGbMonth: 0.1,\n },\n} as const;\n\nconst roundUsd = (amount: number): number => Math.round(amount * 10_000) / 10_000;\n\nconst requireNonNegative = (value: number, name: string): void => {\n if (!Number.isFinite(value) || value < 0) {\n throw new InfraError('invalid_request', `${name} must be a finite number >= 0 (got ${value})`);\n }\n};\n\nconst requireUnitInterval = (value: number, name: string): void => {\n if (!Number.isFinite(value) || value < 0 || value > 1) {\n throw new InfraError(\n 'invalid_request',\n `${name} must be a finite number in [0, 1] (got ${value})`,\n );\n }\n};\n\nexport const projectHostingMonthlyCost = (\n input: HostingCostProjectionInput,\n): HostingCostProjection => {\n requireNonNegative(input.memoryMb, 'memoryMb');\n requireNonNegative(input.vcpus, 'vcpus');\n requireNonNegative(input.activeHoursPerMonth, 'activeHoursPerMonth');\n requireNonNegative(input.suspendedHoursPerMonth, 'suspendedHoursPerMonth');\n requireNonNegative(input.rootfsGb, 'rootfsGb');\n\n if (input.activeHoursPerMonth + input.suspendedHoursPerMonth > HOURS_PER_MONTH) {\n throw new InfraError(\n 'invalid_request',\n `activeHoursPerMonth + suspendedHoursPerMonth must be <= ${HOURS_PER_MONTH} (got ${input.activeHoursPerMonth + input.suspendedHoursPerMonth})`,\n );\n }\n\n const markupMultiplier = input.markupMultiplier ?? 1;\n if (!Number.isFinite(markupMultiplier) || markupMultiplier < 1) {\n throw new InfraError(\n 'invalid_request',\n `markupMultiplier must be a finite number >= 1 (got ${markupMultiplier})`,\n );\n }\n\n if (input.averageMemoryUtilization !== undefined) {\n requireUnitInterval(input.averageMemoryUtilization, 'averageMemoryUtilization');\n }\n if (input.averageCpuUtilization !== undefined) {\n requireUnitInterval(input.averageCpuUtilization, 'averageCpuUtilization');\n }\n\n const memoryGb = input.memoryMb / 1024;\n const activeMonthFraction = input.activeHoursPerMonth / HOURS_PER_MONTH;\n const totalStoredMonthFraction =\n (input.activeHoursPerMonth + input.suspendedHoursPerMonth) / HOURS_PER_MONTH;\n const suspendedMonthFraction = input.suspendedHoursPerMonth / HOURS_PER_MONTH;\n\n let activeComputeUsd = 0;\n let suspendedStorageUsd = 0;\n let pricingBasis = '';\n\n switch (input.provider) {\n case 'railway': {\n const memUtil = input.averageMemoryUtilization ?? DEFAULT_RAILWAY_MEMORY_UTILIZATION;\n const cpuUtil = input.averageCpuUtilization ?? DEFAULT_RAILWAY_CPU_UTILIZATION;\n activeComputeUsd =\n memoryGb *\n memUtil *\n input.activeHoursPerMonth *\n HOSTING_PRICING_RATES.railway.memoryUsdPerGbHour +\n input.vcpus *\n cpuUtil *\n input.activeHoursPerMonth *\n HOSTING_PRICING_RATES.railway.vcpuUsdPerHour;\n suspendedStorageUsd =\n input.rootfsGb *\n totalStoredMonthFraction *\n HOSTING_PRICING_RATES.railway.storageUsdPerGbMonth;\n pricingBasis = 'usage-metered active RAM/vCPU per second + persistent volume storage';\n break;\n }\n case 'fly': {\n const vcpuMonthRate =\n input.cpuKind === 'performance'\n ? HOSTING_PRICING_RATES.fly.performanceVcpuUsdPerMonth\n : HOSTING_PRICING_RATES.fly.sharedVcpuUsdPerMonth;\n const monthlyActiveRate =\n input.vcpus * vcpuMonthRate + memoryGb * HOSTING_PRICING_RATES.fly.memoryUsdPerGbMonth;\n activeComputeUsd = monthlyActiveRate * activeMonthFraction;\n suspendedStorageUsd =\n input.rootfsGb *\n suspendedMonthFraction *\n HOSTING_PRICING_RATES.fly.suspendedRootfsUsdPerGbMonth;\n pricingBasis =\n 'provisioned Firecracker microVM per second while active + rootfs-only storage while suspended';\n break;\n }\n case 'render': {\n const plan = renderPlanForMemoryMb(input.memoryMb);\n activeComputeUsd = plan.monthlyUsd * activeMonthFraction;\n suspendedStorageUsd =\n input.rootfsGb * totalStoredMonthFraction * HOSTING_PRICING_RATES.render.diskUsdPerGbMonth;\n pricingBasis = `prorated fixed Render ${plan.id} tier while unsuspended + persistent disk`;\n break;\n }\n case 'firecracker': {\n const monthlyHostShare =\n memoryGb * HOSTING_PRICING_RATES.firecracker.amortizedMemoryUsdPerGbMonth +\n input.vcpus * HOSTING_PRICING_RATES.firecracker.amortizedVcpuUsdPerMonth;\n activeComputeUsd = monthlyHostShare * activeMonthFraction;\n suspendedStorageUsd =\n (input.rootfsGb + memoryGb) *\n suspendedMonthFraction *\n HOSTING_PRICING_RATES.firecracker.snapshotStorageUsdPerGbMonth;\n pricingBasis =\n 'amortized dedicated bare-metal host capacity while active + NVMe snapshot storage while suspended';\n break;\n }\n case 'aws': {\n activeComputeUsd =\n input.vcpus *\n input.activeHoursPerMonth *\n HOSTING_PRICING_RATES.aws.fargateArmVcpuUsdPerHour +\n memoryGb *\n input.activeHoursPerMonth *\n HOSTING_PRICING_RATES.aws.fargateArmMemoryUsdPerGbHour;\n suspendedStorageUsd =\n input.rootfsGb * totalStoredMonthFraction * HOSTING_PRICING_RATES.aws.storageUsdPerGbMonth;\n pricingBasis = 'AWS Fargate ARM provisioned vCPU/GB-hour + EBS/snapshot storage';\n break;\n }\n case 'gcp': {\n activeComputeUsd =\n input.vcpus * input.activeHoursPerMonth * HOSTING_PRICING_RATES.gcp.vcpuUsdPerHour +\n memoryGb * input.activeHoursPerMonth * HOSTING_PRICING_RATES.gcp.memoryUsdPerGbHour;\n suspendedStorageUsd =\n input.rootfsGb * totalStoredMonthFraction * HOSTING_PRICING_RATES.gcp.storageUsdPerGbMonth;\n pricingBasis = 'GCP provisioned vCPU/GB-hour + persistent storage';\n break;\n }\n case 'azure': {\n activeComputeUsd =\n input.vcpus * input.activeHoursPerMonth * HOSTING_PRICING_RATES.azure.vcpuUsdPerHour +\n memoryGb * input.activeHoursPerMonth * HOSTING_PRICING_RATES.azure.memoryUsdPerGbHour;\n suspendedStorageUsd =\n input.rootfsGb *\n totalStoredMonthFraction *\n HOSTING_PRICING_RATES.azure.storageUsdPerGbMonth;\n pricingBasis = 'Azure Container Apps provisioned vCPU/GB-hour + storage';\n break;\n }\n }\n\n const roundedActive = roundUsd(activeComputeUsd);\n const roundedStorage = roundUsd(suspendedStorageUsd);\n const roundedRaw = roundUsd(roundedActive + roundedStorage);\n const roundedMarkedUp = roundUsd(roundedRaw * markupMultiplier);\n const roundedMargin = roundUsd(roundedMarkedUp - roundedRaw);\n\n return {\n provider: input.provider,\n activeComputeUsd: roundedActive,\n suspendedStorageUsd: roundedStorage,\n rawMonthlyCostUsd: roundedRaw,\n markupMultiplier,\n markedUpMonthlyCostUsd: roundedMarkedUp,\n marginUsd: roundedMargin,\n pricingBasis,\n };\n};\n","export const IMPLEMENTED_INFRA_PROVIDERS = ['railway', 'render', 'fly', 'firecracker'] as const;\nexport const PLANNED_INFRA_PROVIDERS = ['aws', 'gcp', 'azure'] as const;\nexport const ARCHIVE_HOSTING_PROVIDERS = ['railway', 'render'] as const;\n\nexport type ImplementedInfraProvider = (typeof IMPLEMENTED_INFRA_PROVIDERS)[number];\nexport type PlannedInfraProvider = (typeof PLANNED_INFRA_PROVIDERS)[number];\nexport type ArchiveHostingProvider = (typeof ARCHIVE_HOSTING_PROVIDERS)[number];\nexport type InfraProviderId = ImplementedInfraProvider | PlannedInfraProvider;\n\nexport type InfraIsolationKind = 'microvm' | 'container';\n\nexport type InfraBillingUnit =\n | 'active_utilization_second'\n | 'provisioned_second_with_suspend_storage'\n | 'flat_plan_month'\n | 'host_machine_month'\n | 'provisioned_vcpu_memory_second';\n\nexport type InfraProviderDescriptor = {\n readonly id: InfraProviderId;\n readonly name: string;\n readonly implemented: boolean;\n readonly supportsArchiveHosting: boolean;\n readonly supportsInfrastructureResourceDriver: boolean;\n readonly isolation: InfraIsolationKind;\n readonly supportsSuspend: boolean;\n readonly suspendMaxMemoryMb?: number;\n readonly supportsByoAccount: boolean;\n readonly supportsManagedAccount: boolean;\n readonly billingUnit: InfraBillingUnit;\n readonly notes: string;\n};\n\nexport const INFRA_PROVIDERS: Readonly<Record<InfraProviderId, InfraProviderDescriptor>> = {\n railway: {\n id: 'railway',\n name: 'Railway',\n implemented: true,\n supportsArchiveHosting: true,\n supportsInfrastructureResourceDriver: true,\n isolation: 'container',\n supportsSuspend: false,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'active_utilization_second',\n notes:\n 'Usage-metered memory and CPU per second; stopped services bill nothing; no memory-snapshot suspend.',\n },\n render: {\n id: 'render',\n name: 'Render',\n implemented: true,\n supportsArchiveHosting: true,\n supportsInfrastructureResourceDriver: true,\n isolation: 'container',\n supportsSuspend: false,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'flat_plan_month',\n notes:\n 'Managed web services and Postgres on fixed tiers; service suspend stops execution without a memory snapshot.',\n },\n fly: {\n id: 'fly',\n name: 'Fly.io Machines',\n implemented: true,\n supportsArchiveHosting: false,\n supportsInfrastructureResourceDriver: true,\n isolation: 'microvm',\n supportsSuspend: true,\n suspendMaxMemoryMb: 2048,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'provisioned_second_with_suspend_storage',\n notes:\n 'Firecracker microVMs with GA memory-snapshot suspend up to 2048 MB RAM and rootfs-only suspended storage billing.',\n },\n firecracker: {\n id: 'firecracker',\n name: 'Firecracker',\n implemented: true,\n supportsArchiveHosting: false,\n supportsInfrastructureResourceDriver: true,\n isolation: 'microvm',\n supportsSuspend: true,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'host_machine_month',\n notes:\n 'Direct Firecracker VMM HTTP/Unix control plane for dedicated or bare-metal microVM hosts with full memory snapshots.',\n },\n aws: {\n id: 'aws',\n name: 'AWS (Fargate / Lambda MicroVMs)',\n implemented: false,\n supportsArchiveHosting: false,\n supportsInfrastructureResourceDriver: false,\n isolation: 'microvm',\n supportsSuspend: true,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'provisioned_vcpu_memory_second',\n notes:\n 'Planned cloud adapter for AWS Fargate tasks and Firecracker-backed Lambda MicroVMs (8h session cap).',\n },\n gcp: {\n id: 'gcp',\n name: 'Google Cloud (Cloud Run / GKE Autopilot)',\n implemented: false,\n supportsArchiveHosting: false,\n supportsInfrastructureResourceDriver: false,\n isolation: 'microvm',\n supportsSuspend: false,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'provisioned_vcpu_memory_second',\n notes: 'Planned cloud adapter for Google Cloud Run and GKE Autopilot.',\n },\n azure: {\n id: 'azure',\n name: 'Azure (Container Apps / ACI)',\n implemented: false,\n supportsArchiveHosting: false,\n supportsInfrastructureResourceDriver: false,\n isolation: 'container',\n supportsSuspend: false,\n supportsByoAccount: true,\n supportsManagedAccount: true,\n billingUnit: 'provisioned_vcpu_memory_second',\n notes: 'Planned cloud adapter for Azure Container Apps and Container Instances.',\n },\n};\n\nexport const isInfraProvider = (value: string | null | undefined): value is InfraProviderId =>\n typeof value === 'string' && Object.hasOwn(INFRA_PROVIDERS, value);\n\nexport const isImplementedInfraProvider = (\n value: string | null | undefined,\n): value is ImplementedInfraProvider =>\n IMPLEMENTED_INFRA_PROVIDERS.some((provider) => provider === value);\n\nexport const isArchiveHostingProvider = (\n value: string | null | undefined,\n): value is ArchiveHostingProvider =>\n ARCHIVE_HOSTING_PROVIDERS.some((provider) => provider === value);\n\nexport const infraProviderDescriptor = (provider: InfraProviderId): InfraProviderDescriptor =>\n INFRA_PROVIDERS[provider];\n","import type {\n InfrastructureResourceClass,\n InfrastructureResourceLifecyclePolicy,\n WarmRetentionMode,\n WorkingHoursSchedule,\n} from './lifecycleTypes.ts';\n\nconst MINUTE_MS = 60_000;\nconst HOUR_MS = 60 * MINUTE_MS;\nconst DAY_MS = 24 * HOUR_MS;\n\nexport type InfrastructureResourceLifecyclePolicyOptions = {\n readonly warmRetentionMode?: WarmRetentionMode;\n readonly workingHoursPrewarm?: WorkingHoursSchedule;\n};\n\nexport const defaultInfrastructureResourceLifecyclePolicy = (\n infrastructureResourceClass: InfrastructureResourceClass,\n options: InfrastructureResourceLifecyclePolicyOptions = {},\n): InfrastructureResourceLifecyclePolicy => {\n switch (infrastructureResourceClass) {\n case 'warm-interactive':\n return {\n infrastructureResourceClass,\n idleSuspendMs: 8 * MINUTE_MS,\n idleStopMs: 3 * HOUR_MS,\n drainGraceMs: 60_000,\n pendingApprovalGraceMs: 0,\n maxLifetimeMs: 24 * HOUR_MS,\n maxSuspendedMs: 14 * DAY_MS,\n softMemoryRecycleMb: 1536,\n hardMemoryCapMb: 2048,\n requireArchiveFlushBeforeWindDown: false,\n workingHoursPrewarm: options.workingHoursPrewarm,\n idleAction: 'suspend',\n };\n case 'warm-pool':\n return {\n infrastructureResourceClass,\n idleSuspendMs: options.warmRetentionMode === 'extended' ? 60 * MINUTE_MS : 5 * MINUTE_MS,\n idleStopMs: 3 * HOUR_MS,\n drainGraceMs: 60_000,\n pendingApprovalGraceMs: 0,\n maxLifetimeMs: 24 * HOUR_MS,\n maxSuspendedMs: 7 * DAY_MS,\n softMemoryRecycleMb: 1536,\n hardMemoryCapMb: 2048,\n requireArchiveFlushBeforeWindDown: false,\n workingHoursPrewarm: options.workingHoursPrewarm,\n idleAction: 'suspend',\n };\n case 'batch-worker':\n return {\n infrastructureResourceClass,\n idleSuspendMs: 5 * MINUTE_MS,\n idleStopMs: 5 * MINUTE_MS,\n drainGraceMs: 120_000,\n pendingApprovalGraceMs: 0,\n maxLifetimeMs: 4 * HOUR_MS,\n maxSuspendedMs: 24 * HOUR_MS,\n softMemoryRecycleMb: 1536,\n hardMemoryCapMb: 2048,\n requireArchiveFlushBeforeWindDown: false,\n idleAction: 'terminate',\n };\n case 'ephemeral-session':\n return {\n infrastructureResourceClass,\n idleSuspendMs: 15 * MINUTE_MS,\n idleStopMs: 15 * MINUTE_MS,\n drainGraceMs: 60_000,\n pendingApprovalGraceMs: 30 * MINUTE_MS,\n maxLifetimeMs: 24 * HOUR_MS,\n maxSuspendedMs: 7 * DAY_MS,\n softMemoryRecycleMb: null,\n hardMemoryCapMb: null,\n requireArchiveFlushBeforeWindDown: true,\n idleAction: 'suspend',\n };\n case 'always-on':\n return {\n infrastructureResourceClass,\n idleSuspendMs: null,\n idleStopMs: null,\n drainGraceMs: 60_000,\n pendingApprovalGraceMs: 0,\n maxLifetimeMs: null,\n maxSuspendedMs: null,\n softMemoryRecycleMb: null,\n hardMemoryCapMb: null,\n requireArchiveFlushBeforeWindDown: false,\n idleAction: 'keep_warm',\n };\n }\n};\n","import { InfraError } from '../core/infraError.ts';\nimport { infraProviderDescriptor } from '../core/providers.ts';\nimport { defaultInfrastructureResourceLifecyclePolicy } from './lifecyclePolicy.ts';\nimport type {\n InfrastructureResourceLifecycleDecision,\n InfrastructureResourceLifecyclePolicy,\n InfrastructureResourceLifecycleSnapshot,\n WorkingHoursSchedule,\n} from './lifecycleTypes.ts';\n\nconst TRANSITIONAL_POLL_MS = 15_000;\nconst ACTIVE_WORK_POLL_MS = 30_000;\nconst ARCHIVE_FLUSH_POLL_MS = 10_000;\nconst SUSPENDED_POLL_MS = 300_000;\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 24 * HOUR_MS;\n\nconst assertFiniteNumber = (value: number, name: string): void => {\n if (!Number.isFinite(value)) {\n throw new InfraError('invalid_request', `${name} must be a finite number (got ${value})`);\n }\n};\n\nconst assertNonNegativeFinite = (value: number, name: string): void => {\n if (!Number.isFinite(value) || value < 0) {\n throw new InfraError('invalid_request', `${name} must be a finite number >= 0 (got ${value})`);\n }\n};\n\nconst assertNonNegativeInteger = (value: number, name: string): void => {\n if (!Number.isInteger(value) || value < 0) {\n throw new InfraError('invalid_request', `${name} must be an integer >= 0 (got ${value})`);\n }\n};\n\nconst assertPositiveOptional = (value: number | null | undefined, name: string): void => {\n if (value === null || value === undefined) return;\n if (!Number.isFinite(value) || value <= 0) {\n throw new InfraError('invalid_request', `${name} must be a finite number > 0 (got ${value})`);\n }\n};\n\nconst validateWorkingHoursSchedule = (schedule: WorkingHoursSchedule): void => {\n assertFiniteNumber(schedule.timezoneOffsetMinutes, 'workingHoursPrewarm.timezoneOffsetMinutes');\n if (!Number.isFinite(schedule.startHour) || schedule.startHour < 0 || schedule.startHour >= 24) {\n throw new InfraError(\n 'invalid_request',\n `workingHoursPrewarm.startHour must be in [0, 24) (got ${schedule.startHour})`,\n );\n }\n if (!Number.isFinite(schedule.endHour) || schedule.endHour < 0 || schedule.endHour > 24) {\n throw new InfraError(\n 'invalid_request',\n `workingHoursPrewarm.endHour must be in [0, 24] (got ${schedule.endHour})`,\n );\n }\n assertNonNegativeFinite(schedule.prewarmLeadMs, 'workingHoursPrewarm.prewarmLeadMs');\n};\n\nconst validateSnapshotAndPolicy = (\n snapshot: InfrastructureResourceLifecycleSnapshot,\n nowMs: number,\n policy: InfrastructureResourceLifecyclePolicy,\n): void => {\n assertFiniteNumber(nowMs, 'nowMs');\n assertFiniteNumber(snapshot.createdAtMs, 'snapshot.createdAtMs');\n assertFiniteNumber(snapshot.lastActivityAtMs, 'snapshot.lastActivityAtMs');\n assertFiniteNumber(snapshot.stateEnteredAtMs, 'snapshot.stateEnteredAtMs');\n assertNonNegativeInteger(snapshot.inFlightTurns, 'snapshot.inFlightTurns');\n assertNonNegativeInteger(snapshot.activeBackgroundShells, 'snapshot.activeBackgroundShells');\n if (snapshot.pendingApprovals !== undefined) {\n assertNonNegativeInteger(snapshot.pendingApprovals, 'snapshot.pendingApprovals');\n }\n assertPositiveOptional(snapshot.provisionedMemoryMb, 'snapshot.provisionedMemoryMb');\n assertPositiveOptional(snapshot.rssMemoryMb, 'snapshot.rssMemoryMb');\n\n if (policy.idleSuspendMs !== null) {\n assertNonNegativeFinite(policy.idleSuspendMs, 'policy.idleSuspendMs');\n }\n if (policy.idleStopMs !== null) {\n assertNonNegativeFinite(policy.idleStopMs, 'policy.idleStopMs');\n }\n assertNonNegativeFinite(policy.drainGraceMs, 'policy.drainGraceMs');\n assertNonNegativeFinite(policy.pendingApprovalGraceMs, 'policy.pendingApprovalGraceMs');\n if (policy.maxLifetimeMs !== null) {\n assertPositiveOptional(policy.maxLifetimeMs, 'policy.maxLifetimeMs');\n }\n if (policy.maxSuspendedMs !== null) {\n assertPositiveOptional(policy.maxSuspendedMs, 'policy.maxSuspendedMs');\n }\n assertPositiveOptional(policy.softMemoryRecycleMb, 'policy.softMemoryRecycleMb');\n assertPositiveOptional(policy.hardMemoryCapMb, 'policy.hardMemoryCapMb');\n if (policy.workingHoursPrewarm) {\n validateWorkingHoursSchedule(policy.workingHoursPrewarm);\n }\n};\n\ntype WorkingWindowBounds = {\n readonly prewarmStartMs: number;\n readonly windowStartMs: number;\n readonly windowEndMs: number;\n};\n\nconst workingWindowForDayDelta = (\n nowMs: number,\n schedule: WorkingHoursSchedule,\n dayDelta: number,\n): WorkingWindowBounds | null => {\n const offsetMs = schedule.timezoneOffsetMinutes * 60_000;\n const shifted = new Date(nowMs + offsetMs + dayDelta * DAY_MS);\n const dayOfWeek = shifted.getUTCDay();\n if (schedule.weekdaysOnly && (dayOfWeek === 0 || dayOfWeek === 6)) {\n return null;\n }\n const localMidnightUtcMs =\n Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth(), shifted.getUTCDate()) - offsetMs;\n const windowStartMs = localMidnightUtcMs + schedule.startHour * HOUR_MS;\n const isOvernight = schedule.endHour <= schedule.startHour;\n const windowEndMs = localMidnightUtcMs + schedule.endHour * HOUR_MS + (isOvernight ? DAY_MS : 0);\n const prewarmStartMs = windowStartMs - schedule.prewarmLeadMs;\n return { prewarmStartMs, windowStartMs, windowEndMs };\n};\n\nconst activeWorkingWindowAt = (\n nowMs: number,\n schedule: WorkingHoursSchedule,\n): WorkingWindowBounds | null => {\n for (const dayDelta of [-1, 0, 1]) {\n const bounds = workingWindowForDayDelta(nowMs, schedule, dayDelta);\n if (!bounds) continue;\n if (nowMs >= bounds.prewarmStartMs && nowMs < bounds.windowEndMs) {\n return bounds;\n }\n }\n return null;\n};\n\nconst nextWorkingHoursPrewarmAtMs = (\n nowMs: number,\n schedule: WorkingHoursSchedule,\n): number | null => {\n let next: number | null = null;\n for (let dayDelta = 0; dayDelta <= 8; dayDelta += 1) {\n const bounds = workingWindowForDayDelta(nowMs, schedule, dayDelta);\n if (!bounds) continue;\n if (bounds.prewarmStartMs > nowMs) {\n next = next === null ? bounds.prewarmStartMs : Math.min(next, bounds.prewarmStartMs);\n }\n }\n return next;\n};\n\nconst earliestCheckTime = (...candidates: Array<number | null | undefined>): number | null => {\n let earliest: number | null = null;\n for (const candidate of candidates) {\n if (candidate === null || candidate === undefined) continue;\n earliest = earliest === null ? candidate : Math.min(earliest, candidate);\n }\n return earliest;\n};\n\nexport const evaluateInfrastructureResourceLifecycle = (\n snapshot: InfrastructureResourceLifecycleSnapshot,\n nowMs: number,\n policy: InfrastructureResourceLifecyclePolicy = defaultInfrastructureResourceLifecyclePolicy(\n snapshot.infrastructureResourceClass,\n {\n warmRetentionMode: snapshot.warmRetentionMode,\n },\n ),\n): InfrastructureResourceLifecycleDecision => {\n validateSnapshotAndPolicy(snapshot, nowMs, policy);\n\n const descriptor = infraProviderDescriptor(snapshot.provider);\n const hasActiveWork = snapshot.inFlightTurns > 0 || snapshot.activeBackgroundShells > 0;\n const hasPendingApprovals = (snapshot.pendingApprovals ?? 0) > 0;\n const ageMs = Math.max(0, nowMs - snapshot.createdAtMs);\n const maxLifetimeReached = policy.maxLifetimeMs !== null && ageMs >= policy.maxLifetimeMs;\n const lifetimeDeadlineMs =\n policy.maxLifetimeMs !== null ? snapshot.createdAtMs + policy.maxLifetimeMs : null;\n\n if (snapshot.state === 'destroyed') {\n return {\n action: 'none',\n reason: 'infrastructure_resource_already_destroyed',\n nextCheckAtMs: null,\n };\n }\n\n if (snapshot.state === 'failed' || snapshot.state === 'orphaned') {\n return {\n action: 'terminate',\n reason: `reap_${snapshot.state}_infrastructure_resource`,\n nextCheckAtMs: null,\n };\n }\n\n if (\n snapshot.state === 'provisioning' ||\n snapshot.state === 'booting' ||\n snapshot.state === 'suspending' ||\n snapshot.state === 'terminating'\n ) {\n return {\n action: 'none',\n reason: `infrastructure_resource_${snapshot.state}`,\n nextCheckAtMs: nowMs + TRANSITIONAL_POLL_MS,\n };\n }\n\n if (snapshot.state === 'suspended') {\n const suspendedElapsedMs = Math.max(0, nowMs - snapshot.stateEnteredAtMs);\n if (policy.maxSuspendedMs !== null && suspendedElapsedMs >= policy.maxSuspendedMs) {\n return {\n action: 'terminate',\n reason: 'suspended_retention_expired',\n nextCheckAtMs: null,\n };\n }\n\n if (policy.workingHoursPrewarm) {\n if (activeWorkingWindowAt(nowMs, policy.workingHoursPrewarm)) {\n return {\n action: 'prewarm',\n reason: 'working_hours_prewarm_window',\n nextCheckAtMs: null,\n };\n }\n }\n\n const expiryAtMs =\n policy.maxSuspendedMs !== null ? snapshot.stateEnteredAtMs + policy.maxSuspendedMs : null;\n const nextPrewarmAtMs = policy.workingHoursPrewarm\n ? nextWorkingHoursPrewarmAtMs(nowMs, policy.workingHoursPrewarm)\n : null;\n return {\n action: 'none',\n reason: 'suspended_within_retention',\n nextCheckAtMs: earliestCheckTime(expiryAtMs, nextPrewarmAtMs, nowMs + SUSPENDED_POLL_MS),\n };\n }\n\n if (snapshot.state === 'draining') {\n const drainElapsedMs = Math.max(0, nowMs - snapshot.stateEnteredAtMs);\n const drainDeadlineMs = snapshot.stateEnteredAtMs + policy.drainGraceMs;\n const idleElapsedMs = Math.max(0, nowMs - snapshot.lastActivityAtMs);\n\n if (hasActiveWork) {\n if (!maxLifetimeReached) {\n return {\n action: 'none',\n reason: 'active_work_blocks_idle_drain',\n nextCheckAtMs: earliestCheckTime(lifetimeDeadlineMs, nowMs + ACTIVE_WORK_POLL_MS),\n };\n }\n if (drainElapsedMs < policy.drainGraceMs) {\n return {\n action: 'none',\n reason: 'waiting_for_in_flight_work_to_drain',\n nextCheckAtMs: drainDeadlineMs,\n };\n }\n return {\n action: 'terminate',\n reason: 'max_lifetime_exceeded_with_active_work',\n nextCheckAtMs: null,\n };\n }\n\n if (\n hasPendingApprovals &&\n !maxLifetimeReached &&\n policy.pendingApprovalGraceMs > 0 &&\n idleElapsedMs < policy.pendingApprovalGraceMs\n ) {\n return {\n action: 'none',\n reason: 'waiting_for_pending_approval',\n nextCheckAtMs: earliestCheckTime(\n lifetimeDeadlineMs,\n snapshot.lastActivityAtMs + policy.pendingApprovalGraceMs,\n ),\n };\n }\n\n if (policy.requireArchiveFlushBeforeWindDown && !snapshot.archiveFlushed) {\n if (!maxLifetimeReached || drainElapsedMs < policy.drainGraceMs) {\n return {\n action: 'none',\n reason: 'waiting_for_archive_flush',\n nextCheckAtMs: nowMs + ARCHIVE_FLUSH_POLL_MS,\n };\n }\n return {\n action: 'terminate',\n reason: 'max_lifetime_exceeded_without_archive_flush',\n nextCheckAtMs: null,\n };\n }\n\n if (maxLifetimeReached) {\n return {\n action: 'terminate',\n reason: 'max_lifetime_reached_after_drain',\n nextCheckAtMs: null,\n };\n }\n\n if (policy.idleAction === 'terminate') {\n return {\n action: 'terminate',\n reason: 'drain_complete_ready_to_terminate',\n nextCheckAtMs: null,\n };\n }\n\n const suspendMemoryMb = snapshot.provisionedMemoryMb ?? snapshot.rssMemoryMb;\n if (\n descriptor.supportsSuspend &&\n descriptor.suspendMaxMemoryMb !== undefined &&\n suspendMemoryMb !== undefined &&\n suspendMemoryMb > descriptor.suspendMaxMemoryMb\n ) {\n return policy.hardMemoryCapMb !== null\n ? {\n action: 'recycle',\n reason: 'memory_exceeds_provider_suspend_cap',\n nextCheckAtMs: null,\n }\n : {\n action: 'terminate',\n reason: 'cannot_suspend_above_provider_memory_cap',\n nextCheckAtMs: null,\n };\n }\n\n return {\n action: 'suspend',\n reason: descriptor.supportsSuspend\n ? 'drain_complete_ready_to_suspend'\n : 'drain_complete_ready_to_stop',\n nextCheckAtMs: null,\n };\n }\n\n // States: 'warm' | 'active'\n if (maxLifetimeReached) {\n if (hasActiveWork || (policy.requireArchiveFlushBeforeWindDown && !snapshot.archiveFlushed)) {\n return {\n action: 'drain',\n reason: 'max_lifetime_reached_draining',\n nextCheckAtMs: nowMs + policy.drainGraceMs,\n };\n }\n return {\n action: 'terminate',\n reason: 'max_lifetime_reached',\n nextCheckAtMs: null,\n };\n }\n\n if (\n policy.hardMemoryCapMb !== null &&\n snapshot.rssMemoryMb !== undefined &&\n snapshot.rssMemoryMb >\n (descriptor.suspendMaxMemoryMb !== undefined\n ? Math.min(policy.hardMemoryCapMb, descriptor.suspendMaxMemoryMb)\n : policy.hardMemoryCapMb)\n ) {\n return {\n action: 'recycle',\n reason: 'rss_exceeds_hard_cap',\n nextCheckAtMs: null,\n };\n }\n\n if (\n policy.softMemoryRecycleMb !== null &&\n snapshot.rssMemoryMb !== undefined &&\n snapshot.rssMemoryMb >= policy.softMemoryRecycleMb &&\n !hasActiveWork\n ) {\n return {\n action: 'recycle',\n reason: 'rss_exceeds_soft_recycle_threshold',\n nextCheckAtMs: null,\n };\n }\n\n if (snapshot.pinnedWarm || policy.idleAction === 'keep_warm') {\n return {\n action: 'none',\n reason: 'infrastructure_resource_pinned_warm',\n nextCheckAtMs: lifetimeDeadlineMs,\n };\n }\n\n if (policy.workingHoursPrewarm) {\n const activeWindow = activeWorkingWindowAt(nowMs, policy.workingHoursPrewarm);\n if (activeWindow) {\n return {\n action: 'none',\n reason: 'within_working_hours_window',\n nextCheckAtMs: earliestCheckTime(lifetimeDeadlineMs, activeWindow.windowEndMs),\n };\n }\n }\n\n if (hasActiveWork) {\n return {\n action: 'none',\n reason: 'active_work_in_progress',\n nextCheckAtMs: earliestCheckTime(lifetimeDeadlineMs, nowMs + ACTIVE_WORK_POLL_MS),\n };\n }\n\n const idleLimitMs = descriptor.supportsSuspend ? policy.idleSuspendMs : policy.idleStopMs;\n if (idleLimitMs === null) {\n return {\n action: 'none',\n reason: 'no_idle_timeout_configured',\n nextCheckAtMs: lifetimeDeadlineMs,\n };\n }\n\n const idleElapsedMs = Math.max(0, nowMs - snapshot.lastActivityAtMs);\n if (hasPendingApprovals && policy.pendingApprovalGraceMs > 0) {\n const approvalLimitMs = Math.max(idleLimitMs, policy.pendingApprovalGraceMs);\n if (idleElapsedMs < approvalLimitMs) {\n return {\n action: 'none',\n reason: 'waiting_for_pending_approval',\n nextCheckAtMs: earliestCheckTime(\n lifetimeDeadlineMs,\n snapshot.lastActivityAtMs + approvalLimitMs,\n ),\n };\n }\n }\n\n if (idleElapsedMs >= idleLimitMs) {\n return {\n action: 'drain',\n reason: 'idle_timeout_reached',\n nextCheckAtMs: nowMs + policy.drainGraceMs,\n };\n }\n\n return {\n action: 'none',\n reason: 'within_idle_window',\n nextCheckAtMs: earliestCheckTime(lifetimeDeadlineMs, snapshot.lastActivityAtMs + idleLimitMs),\n };\n};\n","import type { InfraProviderId } from '../core/providers.ts';\n\nexport const INFRASTRUCTURE_RESOURCE_LIFECYCLE_STATES = [\n 'provisioning',\n 'booting',\n 'warm',\n 'active',\n 'draining',\n 'suspending',\n 'suspended',\n 'terminating',\n 'destroyed',\n 'failed',\n 'orphaned',\n] as const;\n\nexport type InfrastructureResourceLifecycleState =\n (typeof INFRASTRUCTURE_RESOURCE_LIFECYCLE_STATES)[number];\n\nexport const INFRASTRUCTURE_RESOURCE_CLASSES = [\n 'warm-interactive',\n 'warm-pool',\n 'batch-worker',\n 'ephemeral-session',\n 'always-on',\n] as const;\n\nexport type InfrastructureResourceClass = (typeof INFRASTRUCTURE_RESOURCE_CLASSES)[number];\n\nexport type WarmRetentionMode = 'short' | 'extended';\n\nexport type WorkingHoursSchedule = {\n readonly timezoneOffsetMinutes: number;\n readonly startHour: number;\n readonly endHour: number;\n readonly weekdaysOnly: boolean;\n readonly prewarmLeadMs: number;\n};\n\nexport type InfrastructureResourceIdleAction = 'suspend' | 'terminate' | 'keep_warm';\n\nexport type InfrastructureResourceLifecyclePolicy = {\n readonly infrastructureResourceClass: InfrastructureResourceClass;\n readonly idleSuspendMs: number | null;\n readonly idleStopMs: number | null;\n readonly drainGraceMs: number;\n readonly pendingApprovalGraceMs: number;\n readonly maxLifetimeMs: number | null;\n readonly maxSuspendedMs: number | null;\n readonly softMemoryRecycleMb: number | null;\n readonly hardMemoryCapMb: number | null;\n readonly requireArchiveFlushBeforeWindDown: boolean;\n readonly workingHoursPrewarm?: WorkingHoursSchedule;\n readonly idleAction: InfrastructureResourceIdleAction;\n};\n\nexport type InfrastructureResourceLifecycleSnapshot = {\n readonly infrastructureResourceClass: InfrastructureResourceClass;\n readonly provider: InfraProviderId;\n readonly state: InfrastructureResourceLifecycleState;\n readonly createdAtMs: number;\n readonly lastActivityAtMs: number;\n readonly stateEnteredAtMs: number;\n readonly inFlightTurns: number;\n readonly activeBackgroundShells: number;\n readonly pendingApprovals?: number;\n readonly archiveFlushed: boolean;\n readonly provisionedMemoryMb?: number;\n readonly rssMemoryMb?: number;\n readonly pinnedWarm?: boolean;\n readonly warmRetentionMode?: WarmRetentionMode;\n};\n\nexport type InfrastructureResourceLifecycleAction =\n | 'none'\n | 'prewarm'\n | 'drain'\n | 'suspend'\n | 'terminate'\n | 'recycle';\n\nexport type InfrastructureResourceLifecycleDecision = {\n readonly action: InfrastructureResourceLifecycleAction;\n readonly reason: string;\n readonly nextCheckAtMs: number | null;\n};\n","import { InfraError } from '../core/infraError.ts';\n\nconst DEFAULT_CONCURRENCY_RETRY_FLOOR_MS = 1_000;\n\nexport type StaggeredWakeRequest = {\n readonly infrastructureResourceId: string;\n readonly priority?: number;\n readonly requestedAtMs: number;\n};\n\nexport type StaggeredWakeOptions = {\n readonly maxConcurrentWakes: number;\n readonly minSpacingMs: number;\n readonly inFlightWakeCount?: number;\n readonly lastWakeLaunchedAtMs?: number | null;\n};\n\nexport type DeferredWakeReason = 'concurrency_limit' | 'spacing_interval';\n\nexport type DeferredWake = {\n readonly request: StaggeredWakeRequest;\n readonly earliestLaunchAtMs: number;\n readonly reason: DeferredWakeReason;\n};\n\nexport type StaggeredWakePlan = {\n readonly launchNow: readonly StaggeredWakeRequest[];\n readonly defer: readonly DeferredWake[];\n};\n\nconst compareWakeRequests = (left: StaggeredWakeRequest, right: StaggeredWakeRequest): number => {\n const priorityDiff = (right.priority ?? 0) - (left.priority ?? 0);\n if (priorityDiff !== 0) return priorityDiff;\n const requestedDiff = left.requestedAtMs - right.requestedAtMs;\n if (requestedDiff !== 0) return requestedDiff;\n return left.infrastructureResourceId < right.infrastructureResourceId\n ? -1\n : left.infrastructureResourceId > right.infrastructureResourceId\n ? 1\n : 0;\n};\n\nconst deduplicateRequests = (requests: readonly StaggeredWakeRequest[]): StaggeredWakeRequest[] => {\n const byInfrastructureResourceId = new Map<string, StaggeredWakeRequest>();\n for (const request of requests) {\n if (!request.infrastructureResourceId) {\n throw new InfraError(\n 'invalid_request',\n 'StaggeredWakeRequest.infrastructureResourceId must be non-empty',\n );\n }\n if (!Number.isFinite(request.requestedAtMs)) {\n throw new InfraError(\n 'invalid_request',\n `requestedAtMs must be finite (got ${request.requestedAtMs})`,\n );\n }\n if (request.priority !== undefined && !Number.isFinite(request.priority)) {\n throw new InfraError('invalid_request', `priority must be finite (got ${request.priority})`);\n }\n\n const existing = byInfrastructureResourceId.get(request.infrastructureResourceId);\n if (!existing || compareWakeRequests(request, existing) < 0) {\n byInfrastructureResourceId.set(request.infrastructureResourceId, request);\n }\n }\n return [...byInfrastructureResourceId.values()];\n};\n\nexport const planStaggeredWakes = (\n requests: readonly StaggeredWakeRequest[],\n nowMs: number,\n options: StaggeredWakeOptions,\n): StaggeredWakePlan => {\n if (!Number.isFinite(nowMs)) {\n throw new InfraError('invalid_request', `nowMs must be finite (got ${nowMs})`);\n }\n if (!Number.isInteger(options.maxConcurrentWakes) || options.maxConcurrentWakes < 1) {\n throw new InfraError(\n 'invalid_request',\n `maxConcurrentWakes must be an integer >= 1 (got ${options.maxConcurrentWakes})`,\n );\n }\n if (!Number.isFinite(options.minSpacingMs) || options.minSpacingMs < 0) {\n throw new InfraError(\n 'invalid_request',\n `minSpacingMs must be a finite number >= 0 (got ${options.minSpacingMs})`,\n );\n }\n if (\n options.inFlightWakeCount !== undefined &&\n (!Number.isInteger(options.inFlightWakeCount) || options.inFlightWakeCount < 0)\n ) {\n throw new InfraError(\n 'invalid_request',\n `inFlightWakeCount must be an integer >= 0 (got ${options.inFlightWakeCount})`,\n );\n }\n if (\n options.lastWakeLaunchedAtMs !== undefined &&\n options.lastWakeLaunchedAtMs !== null &&\n !Number.isFinite(options.lastWakeLaunchedAtMs)\n ) {\n throw new InfraError(\n 'invalid_request',\n `lastWakeLaunchedAtMs must be finite or null (got ${options.lastWakeLaunchedAtMs})`,\n );\n }\n\n const sorted = deduplicateRequests(requests).sort(compareWakeRequests);\n const inFlight = options.inFlightWakeCount ?? 0;\n const availableSlots = Math.max(0, options.maxConcurrentWakes - inFlight);\n const launchNow: StaggeredWakeRequest[] = [];\n const defer: DeferredWake[] = [];\n\n const retryStepMs =\n options.minSpacingMs > 0 ? options.minSpacingMs : DEFAULT_CONCURRENCY_RETRY_FLOOR_MS;\n\n let nextEligibleAtMs =\n options.lastWakeLaunchedAtMs !== null && options.lastWakeLaunchedAtMs !== undefined\n ? Math.max(nowMs, options.lastWakeLaunchedAtMs + options.minSpacingMs)\n : nowMs;\n let scheduledWithinConcurrency = 0;\n\n for (const request of sorted) {\n if (scheduledWithinConcurrency >= availableSlots) {\n const earliestLaunchAtMs = Math.max(nextEligibleAtMs, nowMs + retryStepMs);\n defer.push({\n request,\n earliestLaunchAtMs,\n reason: 'concurrency_limit',\n });\n nextEligibleAtMs = earliestLaunchAtMs + retryStepMs;\n continue;\n }\n\n if (nextEligibleAtMs > nowMs) {\n defer.push({\n request,\n earliestLaunchAtMs: nextEligibleAtMs,\n reason: 'spacing_interval',\n });\n scheduledWithinConcurrency += 1;\n nextEligibleAtMs += options.minSpacingMs;\n continue;\n }\n\n launchNow.push(request);\n scheduledWithinConcurrency += 1;\n if (options.minSpacingMs > 0) {\n nextEligibleAtMs = nowMs + options.minSpacingMs;\n }\n }\n\n return { launchNow, defer };\n};\n"]}
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkCNAFA6FE_cjs=require('./chunk-CNAFA6FE.cjs'),chunk423X4M6P_cjs=require('./chunk-423X4M6P.cjs'),chunkOHRGTWGZ_cjs=require('./chunk-OHRGTWGZ.cjs'),chunkQREJ73ZG_cjs=require('./chunk-QREJ73ZG.cjs');var b="https://api.render.com/v1",t=async(e,r,s={},n=b)=>chunkOHRGTWGZ_cjs.d(`${chunkOHRGTWGZ_cjs.b(n)}${r}`,{method:s.method??"GET",token:e,body:s.body,provider:"render"}),I=async(e,r,s)=>{await t(e,r,{method:"DELETE"},s).catch(chunkQREJ73ZG_cjs.e);};var p="oregon",T="basic_256mb",C="starter",U=100,N=(e,r)=>new URLSearchParams({name:e,ownerId:r,limit:"20"}).toString(),E=e=>`${e.name}-db`,A=async e=>(await t(e.token,`/postgres?${N(E(e),e.workspaceId)}`,{},e.apiUrl)).find(r=>r.postgres.name===E(e))?.postgres,y=async e=>(await t(e.token,`/services?${N(e.name,e.workspaceId)}`,{},e.apiUrl)).find(r=>r.service.name===e.name)?.service,$=async(e,r)=>{let s=[],n=new Set,i;do{let v=new URLSearchParams({limit:String(U),...i?{cursor:i}:{}}),d=await t(e,`/owners?${v}`,{},r);if(!Array.isArray(d))throw new chunkQREJ73ZG_cjs.a("provider_unavailable","Render owners response was not an array",{provider:"render"});s.push(...d.map(({owner:u})=>({id:u.id,name:u.name||u.email||u.id})));let a=d.length===U?d.at(-1)?.cursor:void 0;if(a!==void 0){if(n.has(a))throw new chunkQREJ73ZG_cjs.a("provider_unavailable","Render owners pagination cursor repeated",{provider:"render"});n.add(a);}i=a;}while(i);return s},H={provider:"render",fetchWorkspaces:$,provisionDatabase:async e=>{let r=(e.ids.databaseId?{id:e.ids.databaseId}:void 0)??await A(e)??await t(e.token,"/postgres",{method:"POST",body:{name:E(e),ownerId:e.workspaceId,plan:T,version:"17",region:p,databaseName:chunk423X4M6P_cjs.c,databaseUser:chunk423X4M6P_cjs.c}},e.apiUrl);return {...e.ids,databaseId:r.id}},fetchDatabaseReadiness:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.databaseId,"Render databaseId","render")),{status:s}=await t(e.token,`/postgres/${r}`,{},e.apiUrl);if(s==="unavailable"||s==="suspended")throw new chunkQREJ73ZG_cjs.a("deploy_failed",`Render Postgres status ${s}`,{provider:"render"});return s==="available"},provisionService:async e=>{let r=(e.ids.serviceId?await t(e.token,`/services/${encodeURIComponent(e.ids.serviceId)}`,{},e.apiUrl):void 0)??await y(e),s;if(r)s=r;else {let n=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.databaseId,"Render databaseId","render"));s=(await t(e.token,"/services",{method:"POST",body:{type:"web_service",name:e.name,ownerId:e.workspaceId,image:{ownerId:e.workspaceId,imagePath:`${chunk423X4M6P_cjs.a}:${e.imageVersion}`},envVars:[{key:"ARCHIVE_SERVER_TOKEN",value:chunk423X4M6P_cjs.d(e)},{key:"PORT",value:String(chunk423X4M6P_cjs.b)},{key:"DATABASE_URL",value:(await t(e.token,`/postgres/${n}/connection-info`,{},e.apiUrl)).internalConnectionString}],serviceDetails:{runtime:"image",plan:C,region:p,healthCheckPath:"/health"}}},e.apiUrl)).service;}return {ids:{...e.ids,serviceId:s.id},url:chunkQREJ73ZG_cjs.d(s.serviceDetails?.url,"Render service url","render")}},fetchServiceReadiness:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.serviceId,"Render serviceId","render")),[s]=await t(e.token,`/services/${r}/deploys?limit=1`,{},e.apiUrl);if(!s)return false;if(chunkCNAFA6FE_cjs.c.has(s.deploy.status))throw new chunkQREJ73ZG_cjs.a("deploy_failed",`Render deploy ${s.deploy.status}`,{provider:"render"});return s.deploy.status==="live"},fetchServiceFailureStatus:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.serviceId,"Render serviceId","render")),[s]=await t(e.token,`/services/${r}/deploys?limit=1`,{},e.apiUrl);return !!(s&&chunkCNAFA6FE_cjs.c.has(s.deploy.status))},deployImage:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.serviceId,"Render serviceId","render")),s=`${chunk423X4M6P_cjs.a}:${e.imageVersion}`;await t(e.token,`/services/${r}`,{method:"PATCH",body:{image:{ownerId:e.workspaceId,imagePath:s}}},e.apiUrl);let n=await t(e.token,`/services/${r}/deploys`,{method:"POST",body:{imageUrl:s}},e.apiUrl);return {...e.ids,deploymentId:chunkQREJ73ZG_cjs.d(n?.id,"Render deploymentId","render")}},restoreImage:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.serviceId,"Render serviceId","render"));await t(e.token,`/services/${r}`,{method:"PATCH",body:{image:{ownerId:e.workspaceId,imagePath:`${chunk423X4M6P_cjs.a}:${e.imageVersion}`}}},e.apiUrl);},fetchImageDeployStatus:async e=>{let r=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.serviceId,"Render serviceId","render")),s=encodeURIComponent(chunkQREJ73ZG_cjs.d(e.ids.deploymentId,"Render deploymentId","render")),{status:n}=await t(e.token,`/services/${r}/deploys/${s}`,{},e.apiUrl);return n==="live"?"live":chunkCNAFA6FE_cjs.d.has(n)?"failed":"deploying"},destroyService:async e=>{let r=e.ids.serviceId??(await y(e))?.id;r&&await I(e.token,`/services/${encodeURIComponent(r)}`,e.apiUrl);let s=e.ids.databaseId??(await A(e))?.id;s&&await I(e.token,`/postgres/${encodeURIComponent(s)}`,e.apiUrl);}};var g=e=>{if(!e.token)throw new chunkQREJ73ZG_cjs.a("authentication_failed","Render API token is required",{provider:"render"});return e.token},L=(e,r)=>e.suspended==="suspended"?"suspended":r?r==="live"?"running":chunkCNAFA6FE_cjs.c.has(r)?"failed":r==="deactivated"?"stopped":"starting":"provisioning",O={provider:"render",provisionInfrastructureResource:async(e,r)=>{let s=g(e);if(chunkQREJ73ZG_cjs.f(r.egressAllowlist,"render"),!e.workspaceId)throw new chunkQREJ73ZG_cjs.a("invalid_request","Render infrastructure resource provisioning requires workspaceId",{provider:"render"});let n=Object.entries({...r.env??{},...r.port?{PORT:String(r.port.internalPort)}:{}}).map(([u,x])=>({key:u,value:x})),i=r.port?.publicHttps?"web_service":"background_worker",v=r.region??p,d=chunkCNAFA6FE_cjs.b(r.memoryMb).id,a=await t(s,"/services",{method:"POST",body:{type:i,name:r.name,ownerId:e.workspaceId,image:{ownerId:e.workspaceId,imagePath:r.image},envVars:n,serviceDetails:{runtime:"image",plan:d,region:v,...i==="web_service"&&r.healthcheckPath?{healthCheckPath:r.healthcheckPath}:{},...r.volume?{disk:{name:r.volume.name,mountPath:r.volume.mountPath,sizeGB:r.volume.sizeGb??10}}:{}}}},e.apiUrl);return {provider:"render",externalId:a.service.id,name:a.service.name,region:a.service.serviceDetails?.region??v,url:a.service.serviceDetails?.url,memoryMb:r.memoryMb,vcpus:r.vcpus,metadata:a.deployId?{deployId:a.deployId}:void 0}},suspendInfrastructureResource:async(e,r)=>{let s=g(e);return await t(s,`/services/${encodeURIComponent(r.externalId)}/suspend`,{method:"POST"},e.apiUrl),r},wakeInfrastructureResource:async(e,r)=>{let s=g(e);return await t(s,`/services/${encodeURIComponent(r.externalId)}/resume`,{method:"POST"},e.apiUrl),r},fetchInfrastructureResourceStatus:async(e,r)=>{let s=g(e),n=encodeURIComponent(r.externalId),i=await t(s,`/services/${n}`,{},e.apiUrl),d=(await t(s,`/services/${n}/deploys?limit=1`,{},e.apiUrl))[0]?.deploy.status;return {provider:"render",externalId:i.id,state:L(i,d),providerState:i.suspended==="suspended"?"suspended":d??"provisioning",region:i.serviceDetails?.region??r.region,url:i.serviceDetails?.url??r.url,memoryMb:r.memoryMb,vcpus:r.vcpus,updatedAt:new Date().toISOString()}},fetchInfrastructureResourceUsage:async(e,r)=>{await O.fetchInfrastructureResourceStatus(e,r);let s=new Date().toISOString();return {provider:"render",externalId:r.externalId,memoryMb:r.memoryMb??0,vcpus:r.vcpus??0,activeSeconds:0,suspendedSeconds:0,rootfsGb:0,metered:false,windowStartIso:s,windowEndIso:s}},destroyInfrastructureResource:async(e,r)=>{let s=g(e);await I(s,`/services/${encodeURIComponent(r.externalId)}`,e.apiUrl);}};
2
+ exports.a=b;exports.b=t;exports.c=I;exports.d=p;exports.e=T;exports.f=C;exports.g=$;exports.h=H;exports.i=O;//# sourceMappingURL=chunk-OHSNNHGO.cjs.map
3
+ //# sourceMappingURL=chunk-OHSNNHGO.cjs.map