@inixiative/infra 0.0.0-stage → 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -2
  3. package/dist/contracts-BxHKiOwj.d.cts +169 -0
  4. package/dist/contracts-BxHKiOwj.d.ts +169 -0
  5. package/dist/firecracker/index.cjs +3 -0
  6. package/dist/firecracker/index.cjs.map +1 -0
  7. package/dist/firecracker/index.d.cts +18 -0
  8. package/dist/firecracker/index.d.ts +18 -0
  9. package/dist/firecracker/index.js +3 -0
  10. package/dist/firecracker/index.js.map +1 -0
  11. package/dist/fly/index.cjs +3 -0
  12. package/dist/fly/index.cjs.map +1 -0
  13. package/dist/fly/index.d.cts +14 -0
  14. package/dist/fly/index.d.ts +14 -0
  15. package/dist/fly/index.js +3 -0
  16. package/dist/fly/index.js.map +1 -0
  17. package/dist/index.cjs +3 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +58 -0
  20. package/dist/index.d.ts +58 -0
  21. package/dist/index.js +3 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/lifecycle/index.cjs +2 -0
  24. package/dist/lifecycle/index.cjs.map +1 -0
  25. package/dist/lifecycle/index.d.cts +145 -0
  26. package/dist/lifecycle/index.d.ts +145 -0
  27. package/dist/lifecycle/index.js +2 -0
  28. package/dist/lifecycle/index.js.map +1 -0
  29. package/dist/railway/index.cjs +3 -0
  30. package/dist/railway/index.cjs.map +1 -0
  31. package/dist/railway/index.d.cts +87 -0
  32. package/dist/railway/index.d.ts +87 -0
  33. package/dist/railway/index.js +3 -0
  34. package/dist/railway/index.js.map +1 -0
  35. package/dist/render/index.cjs +3 -0
  36. package/dist/render/index.cjs.map +1 -0
  37. package/dist/render/index.d.cts +30 -0
  38. package/dist/render/index.d.ts +30 -0
  39. package/dist/render/index.js +3 -0
  40. package/dist/render/index.js.map +1 -0
  41. package/package.json +82 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/infraError.ts","../../src/core/infraFetch.ts","../../src/firecracker/firecrackerRequest.ts","../../src/firecracker/firecrackerWorkloadDriver.ts"],"names":["RETRYABLE_INFRA_ERROR_CODES","InfraError","code","message","details","prefix","infraErrorForStatus","status","isInfraError","error","ignoreNotFound","assertNoEgressAllowlist","egressAllowlist","provider","INFRA_REQUEST_TIMEOUT_MS","MAX_ERROR_BODY_CHARS","stripTrailingSlash","url","sanitizeUrlForError","rawUrl","parsed","redactSensitiveText","text","token","sanitized","formatErrorExcerpt","trimmed","validateTimeoutMs","timeoutMs","parseJsonOrEmpty","rawBody","cause","sendUnixSocketHttpRequest","socketPath","options","parsedUrl","requestPath","response","resolve","reject","settled","deadlineTimer","settleResolve","result","settleReject","req","nodeHttpRequest","res","chunks","chunk","timeoutCause","sendInfraRequest","method","serializedBody","headers","init","rawError","FIRECRACKER_DEFAULT_BASE_URL","sendFirecrackerRequest","transport","path","baseUrl","DEFAULT_KERNEL_IMAGE_PATH","DEFAULT_BOOT_ARGS","SAFE_FIRECRACKER_ID","transportFromCredentials","credentials","assertSafeFirecrackerId","value","label","parseRootfsGb","raw","mapFirecrackerState","state","firecrackerWorkloadDriver","spec","trackDirtyPages","encodedDriveId","encodedIfaceId","info","handle","safeWorkloadId","snapshotPath","memFilePath","nowIso","_handle"],"mappings":"2BAiBA,IAAMA,CAAAA,CAA2D,IAAI,GAAA,CAAI,CACvE,cACA,cAAA,CACA,sBACF,CAAC,CAAA,CAEYC,CAAAA,CAAN,cAAyB,KAAM,CAC3B,IAAA,CACA,MAAA,CACA,QAAA,CACA,SAAA,CAET,WAAA,CAAYC,EAAsBC,CAAAA,CAAkBC,CAAAA,CAA6B,CAC/E,IAAMC,CAAAA,CAASD,CAAAA,EAAS,SAAW,CAAA,CAAA,EAAIA,CAAAA,CAAQ,QAAQ,CAAA,EAAA,CAAA,CAAO,EAAA,CAC9D,MAAMD,CAAAA,CAAU,CAAA,EAAGE,C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AAiB,CACxC,CAAC,CAAA,CAAE,KAAA,CAAMjD,CAAc,EACzB,CACF","file":"index.js","sourcesContent":["export type InfraErrorCode =\n | 'authentication_failed'\n | 'rate_limited'\n | 'not_found'\n | 'conflict'\n | 'provider_unavailable'\n | 'unreachable'\n | 'invalid_request'\n | 'deploy_failed';\n\nexport type InfraErrorDetails = {\n readonly status?: number;\n readonly provider?: string;\n readonly cause?: unknown;\n readonly retryable?: boolean;\n};\n\nconst RETRYABLE_INFRA_ERROR_CODES: ReadonlySet<InfraErrorCode> = new Set([\n 'unreachable',\n 'rate_limited',\n 'provider_unavailable',\n]);\n\nexport class InfraError extends Error {\n readonly code: InfraErrorCode;\n readonly status?: number;\n readonly provider?: string;\n readonly retryable: boolean;\n\n constructor(code: InfraErrorCode, message?: string, details?: InfraErrorDetails) {\n const prefix = details?.provider ? `[${details.provider}] ` : '';\n super(message ? `${prefix}${message}` : `${prefix}Infrastructure request failed (${code})`, {\n cause: details?.cause,\n });\n this.name = 'InfraError';\n this.code = code;\n this.status = details?.status;\n this.provider = details?.provider;\n this.retryable = details?.retryable ?? RETRYABLE_INFRA_ERROR_CODES.has(code);\n }\n}\n\nexport const infraErrorForStatus = (\n status: number,\n details?: { readonly provider?: string; readonly message?: string },\n): InfraError => {\n const code: InfraErrorCode =\n status === 401 || status === 403\n ? 'authentication_failed'\n : status === 404\n ? 'not_found'\n : status === 409\n ? 'conflict'\n : status === 429\n ? 'rate_limited'\n : status === 400 || status === 422\n ? 'invalid_request'\n : 'provider_unavailable';\n const message = details?.message\n ? `HTTP ${status}: ${details.message}`\n : `HTTP ${status} (${code})`;\n return new InfraError(code, message, { status, provider: details?.provider });\n};\n\nexport const isInfraError = (error: unknown, code?: InfraErrorCode): error is InfraError =>\n error instanceof InfraError && (code === undefined || error.code === code);\n\nexport const requireNonEmpty = (\n value: string | undefined,\n label: string,\n provider?: string,\n): string => {\n if (!value?.trim()) {\n throw new InfraError('invalid_request', `Missing required ${label}`, { provider });\n }\n return value;\n};\n\nexport const ignoreNotFound = (error: unknown): void => {\n if (!isInfraError(error, 'not_found')) throw error;\n};\n\nexport const assertNoEgressAllowlist = (\n egressAllowlist: readonly string[] | undefined,\n provider: string,\n): void => {\n if (egressAllowlist && egressAllowlist.length > 0) {\n throw new InfraError('invalid_request', 'Egress allowlist is not enforced by this driver', {\n provider,\n });\n }\n};\n","import { request as nodeHttpRequest } from 'node:http';\nimport { InfraError, infraErrorForStatus } from './infraError.ts';\n\nexport const INFRA_REQUEST_TIMEOUT_MS = 30_000;\n\nconst MAX_ERROR_BODY_CHARS = 500;\n\nexport type InfraFetchOptions = {\n readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly token?: string;\n readonly body?: unknown;\n readonly headers?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly unixSocketPath?: string;\n readonly provider?: string;\n};\n\ntype UnixRequestInit = RequestInit & { unix?: string };\n\nexport const stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nconst sanitizeUrlForError = (rawUrl: string): string => {\n try {\n const parsed = new URL(rawUrl);\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return rawUrl.split('?')[0]?.split('#')[0] ?? rawUrl;\n }\n};\n\nconst redactSensitiveText = (text: string, token?: string): string => {\n let sanitized = text.replace(/Bearer\\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [REDACTED]');\n if (token && token.length > 0) {\n sanitized = sanitized.split(token).join('[REDACTED]');\n }\n return sanitized;\n};\n\nconst formatErrorExcerpt = (text: string, token?: string): string | undefined => {\n const trimmed = redactSensitiveText(text.trim(), token);\n if (!trimmed) return undefined;\n return trimmed.length > MAX_ERROR_BODY_CHARS\n ? `${trimmed.slice(0, MAX_ERROR_BODY_CHARS)}...`\n : trimmed;\n};\n\nconst validateTimeoutMs = (timeoutMs: number | undefined, provider?: string): number => {\n if (timeoutMs === undefined) return INFRA_REQUEST_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new InfraError(\n 'invalid_request',\n `timeoutMs must be a finite positive number (got ${timeoutMs})`,\n { provider },\n );\n }\n return timeoutMs;\n};\n\nconst parseJsonOrEmpty = <T>(rawBody: string, status: number, provider?: string): T => {\n if (status === 204 || !rawBody.trim()) return undefined as T;\n try {\n return JSON.parse(rawBody) as T;\n } catch (cause) {\n throw new InfraError('provider_unavailable', 'Provider returned malformed JSON', {\n status,\n provider,\n cause,\n });\n }\n};\n\nexport const sendUnixSocketHttpRequest = async <T = unknown>(\n url: string,\n socketPath: string,\n options: {\n readonly method: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly serializedBody?: string;\n readonly timeoutMs: number;\n readonly token?: string;\n readonly provider?: string;\n },\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch (cause) {\n throw new InfraError('invalid_request', `Invalid request URL: ${sanitizeUrlForError(url)}`, {\n provider: options.provider,\n cause,\n });\n }\n\n const requestPath = `${parsedUrl.pathname}${parsedUrl.search}`;\n const response = await new Promise<{ readonly status: number; readonly body: string }>(\n (resolve, reject) => {\n let settled = false;\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\n const settleResolve = (result: { readonly status: number; readonly body: string }) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n resolve(result);\n };\n\n const settleReject = (error: InfraError) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n reject(error);\n };\n\n const req = nodeHttpRequest(\n {\n socketPath,\n method: options.method,\n path: requestPath,\n headers: {\n ...options.headers,\n ...(options.serializedBody !== undefined\n ? { 'Content-Length': String(Buffer.byteLength(options.serializedBody)) }\n : {}),\n },\n timeout: timeoutMs,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer | string) => {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n });\n res.on('end', () => {\n settleResolve({\n status: res.statusCode ?? 0,\n body: Buffer.concat(chunks).toString('utf8'),\n });\n });\n res.on('close', () => {\n if (!res.complete) {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response closed prematurely for ${sanitizeUrlForError(url)}`,\n { provider: options.provider },\n ),\n );\n }\n });\n res.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response failed for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause },\n ),\n );\n });\n },\n );\n\n deadlineTimer = setTimeout(() => {\n const timeoutCause = new Error(`Unix socket request exceeded deadline of ${timeoutMs}ms`);\n req.destroy(timeoutCause);\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request timed out for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause: timeoutCause },\n ),\n );\n }, timeoutMs);\n\n req.on('timeout', () => {\n req.destroy(new Error(`Unix socket request timed out after ${timeoutMs}ms`));\n });\n req.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request failed for ${sanitizeUrlForError(url)}`,\n {\n provider: options.provider,\n cause,\n },\n ),\n );\n });\n\n if (options.serializedBody !== undefined) {\n req.write(options.serializedBody);\n }\n req.end();\n },\n );\n\n if (response.status >= 300 && response.status < 400) {\n throw new InfraError(\n 'unreachable',\n `Unexpected redirect (${response.status}) from ${sanitizeUrlForError(url)}`,\n { status: response.status, provider: options.provider },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(response.body, options.token),\n });\n }\n\n return parseJsonOrEmpty<T>(response.body, response.status, options.provider);\n};\n\nexport const sendInfraRequest = async <T = unknown>(\n url: string,\n options: InfraFetchOptions = {},\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n const method = options.method ?? 'GET';\n const serializedBody = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),\n ...(serializedBody !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...options.headers,\n };\n\n if (options.unixSocketPath && typeof Bun === 'undefined') {\n return sendUnixSocketHttpRequest<T>(url, options.unixSocketPath, {\n method,\n headers,\n serializedBody,\n timeoutMs,\n token: options.token,\n provider: options.provider,\n });\n }\n\n const init: UnixRequestInit = {\n method,\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n headers,\n ...(serializedBody !== undefined ? { body: serializedBody } : {}),\n ...(options.unixSocketPath ? { unix: options.unixSocketPath } : {}),\n };\n\n let response: Response;\n try {\n response = await fetch(url, init);\n } catch (cause) {\n throw new InfraError('unreachable', `Request to ${sanitizeUrlForError(url)} failed`, {\n provider: options.provider,\n cause,\n });\n }\n\n if (!response.ok) {\n const rawError = await response.text().catch(() => '');\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(rawError, options.token),\n });\n }\n\n if (response.status === 204) return undefined as T;\n\n const rawBody = await response.text().catch((cause) => {\n throw new InfraError('unreachable', 'Failed to read response body', {\n status: response.status,\n provider: options.provider,\n cause,\n });\n });\n\n return parseJsonOrEmpty<T>(rawBody, response.status, options.provider);\n};\n","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 WorkloadCredentials,\n WorkloadDriver,\n WorkloadHandle,\n WorkloadRuntimeState,\n WorkloadSpec,\n WorkloadStatus,\n WorkloadUsage,\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 = (credentials: WorkloadCredentials): 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): WorkloadRuntimeState => {\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 firecrackerWorkloadDriver: WorkloadDriver = {\n provider: 'firecracker',\n provisionWorkload: async (\n credentials: WorkloadCredentials,\n spec: WorkloadSpec,\n ): Promise<WorkloadHandle> => {\n const transport = transportFromCredentials(credentials);\n assertNoEgressAllowlist(spec.egressAllowlist, 'firecracker');\n assertSafeFirecrackerId(spec.name, 'workload 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 workloadId = assertSafeFirecrackerId(info.id || spec.name, 'workloadId');\n\n return {\n provider: 'firecracker',\n workloadId,\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 suspendWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\n const transport = transportFromCredentials(credentials);\n const safeWorkloadId = assertSafeFirecrackerId(handle.workloadId, 'workloadId');\n const snapshotPath =\n handle.snapshotPath ?? `/var/lib/firecracker/snapshots/${safeWorkloadId}.snap`;\n const memFilePath =\n handle.memFilePath ?? `/var/lib/firecracker/snapshots/${safeWorkloadId}.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 wakeWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\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 fetchWorkloadStatus: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadStatus> => {\n const transport = transportFromCredentials(credentials);\n const info = await sendFirecrackerRequest<FirecrackerInstanceInfo>(transport, '/');\n\n return {\n provider: 'firecracker',\n workloadId: info.id || handle.workloadId,\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 fetchWorkloadUsage: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadUsage> => {\n const status = await firecrackerWorkloadDriver.fetchWorkloadStatus(credentials, handle);\n const nowIso = new Date().toISOString();\n return {\n provider: 'firecracker',\n workloadId: status.workloadId,\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 destroyWorkload: async (\n credentials: WorkloadCredentials,\n _handle: WorkloadHandle,\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 http=require('http');var F=new Set(["unreachable","rate_limited","provider_unavailable"]),d=class extends Error{code;status;provider;retryable;constructor(e,t,n){let s=n?.provider?`[${n.provider}] `:"";super(t?`${s}${t}`:`${s}Infrastructure request failed (${e})`,{cause:n?.cause}),this.name="InfraError",this.code=e,this.status=n?.status,this.provider=n?.provider,this.retryable=n?.retryable??F.has(e);}},w=(r,e)=>{let t=r===401||r===403?"authentication_failed":r===404?"not_found":r===409?"conflict":r===429?"rate_limited":r===400||r===422?"invalid_request":"provider_unavailable",n=e?.message?`HTTP ${r}: ${e.message}`:`HTTP ${r} (${t})`;return new d(t,n,{status:r,provider:e?.provider})},C=(r,e)=>r instanceof d&&(r.code===e);var E=r=>{if(!C(r,"not_found"))throw r},_=(r,e)=>{if(r&&r.length>0)throw new d("invalid_request","Egress allowlist is not enforced by this driver",{provider:e})};var N=3e4,I=500,S=r=>r.replace(/\/+$/,""),y=r=>{try{let e=new URL(r);return `${e.protocol}//${e.host}${e.pathname}`}catch{return r.split("?")[0]?.split("#")[0]??r}},A=(r,e)=>{let t=r.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer [REDACTED]");return e&&e.length>0&&(t=t.split(e).join("[REDACTED]")),t},R=(r,e)=>{let t=A(r.trim(),e);if(t)return t.length>I?`${t.slice(0,I)}...`:t},M=(r,e)=>{if(r===void 0)return N;if(!Number.isFinite(r)||r<=0)throw new d("invalid_request",`timeoutMs must be a finite positive number (got ${r})`,{provider:e});return r},T=(r,e,t)=>{if(!(e===204||!r.trim()))try{return JSON.parse(r)}catch(n){throw new d("provider_unavailable","Provider returned malformed JSON",{status:e,provider:t,cause:n})}},D=async(r,e,t)=>{let n=M(t.timeoutMs,t.provider),s;try{s=new URL(r);}catch(a){throw new d("invalid_request",`Invalid request URL: ${y(r)}`,{provider:t.provider,cause:a})}let i=`${s.pathname}${s.search}`,o=await new Promise((a,u)=>{let l=false,m,q=c=>{l||(l=true,m!==void 0&&clearTimeout(m),a(c));},v=c=>{l||(l=true,m!==void 0&&clearTimeout(m),u(c));},f=http.request({socketPath:e,method:t.method,path:i,headers:{...t.headers,...t.serializedBody!==void 0?{"Content-Length":String(Buffer.byteLength(t.serializedBody))}:{}},timeout:n},c=>{let k=[];c.on("data",h=>{k.push(typeof h=="string"?Buffer.from(h):h);}),c.on("end",()=>{q({status:c.statusCode??0,body:Buffer.concat(k).toString("utf8")});}),c.on("close",()=>{c.complete||v(new d("unreachable",`Unix socket response closed prematurely for ${y(r)}`,{provider:t.provider}));}),c.on("error",h=>{v(new d("unreachable",`Unix socket response failed for ${y(r)}`,{provider:t.provider,cause:h}));});});m=setTimeout(()=>{let c=new Error(`Unix socket request exceeded deadline of ${n}ms`);f.destroy(c),v(new d("unreachable",`Unix socket request timed out for ${y(r)}`,{provider:t.provider,cause:c}));},n),f.on("timeout",()=>{f.destroy(new Error(`Unix socket request timed out after ${n}ms`));}),f.on("error",c=>{v(new d("unreachable",`Unix socket request failed for ${y(r)}`,{provider:t.provider,cause:c}));}),t.serializedBody!==void 0&&f.write(t.serializedBody),f.end();});if(o.status>=300&&o.status<400)throw new d("unreachable",`Unexpected redirect (${o.status}) from ${y(r)}`,{status:o.status,provider:t.provider});if(o.status<200||o.status>=300)throw w(o.status,{provider:t.provider,message:R(o.body,t.token)});return T(o.body,o.status,t.provider)},$=async(r,e={})=>{let t=M(e.timeoutMs,e.provider),n=e.method??"GET",s=e.body!==void 0?JSON.stringify(e.body):void 0,i={Accept:"application/json",...e.token?{Authorization:`Bearer ${e.token}`}:{},...s!==void 0?{"Content-Type":"application/json"}:{},...e.headers};if(e.unixSocketPath&&typeof Bun>"u")return D(r,e.unixSocketPath,{method:n,headers:i,serializedBody:s,timeoutMs:t,token:e.token,provider:e.provider});let o={method:n,redirect:"error",signal:AbortSignal.timeout(t),headers:i,...s!==void 0?{body:s}:{},...e.unixSocketPath?{unix:e.unixSocketPath}:{}},a;try{a=await fetch(r,o);}catch(l){throw new d("unreachable",`Request to ${y(r)} failed`,{provider:e.provider,cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw w(a.status,{provider:e.provider,message:R(l,e.token)})}if(a.status===204)return;let u=await a.text().catch(l=>{throw new d("unreachable","Failed to read response body",{status:a.status,provider:e.provider,cause:l})});return T(u,a.status,e.provider)};var x="https://api.machines.dev/v1",p=async(r,e,t={},n=x)=>$(`${S(n)}${e}`,{method:t.method??"GET",token:r,body:t.body,timeoutMs:t.timeoutMs,provider:"fly"});var b=2048,U=30,P=4e4,g=(r,e)=>{if(!r.token)throw new d("authentication_failed","Fly.io API token is required",{provider:"fly"});let t=r.appName??e;if(!t)throw new d("invalid_request","Fly.io appName is required",{provider:"fly"});return {token:r.token,appName:t}},O=r=>{switch(r){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"}},H=r=>{if(r===void 0)return 0;let e=Number(r);return Number.isFinite(e)&&e>=0?e:0},B=(r,e,t)=>{if(r.length===0)return {activeSeconds:0,suspendedSeconds:0,metered:false,windowStartMs:t,windowEndMs:t};let n=[...r].sort((a,u)=>a.timestamp-u.timestamp),s=0,i=0;for(let a=0;a<n.length;a+=1){let u=n[a],l=n[a+1];if(l){let m=Math.max(0,l.timestamp-u.timestamp);u.status==="started"?s+=m:u.status==="suspended"&&(i+=m);}else if(u.status===e){let m=Math.max(0,t-u.timestamp);e==="started"?s+=m:e==="suspended"&&(i+=m);}}let o=n[n.length-1].timestamp;return {activeSeconds:Math.round(s/1e3),suspendedSeconds:Math.round(i/1e3),metered:true,windowStartMs:n[0].timestamp,windowEndMs:Math.max(t,o)}},L={provider:"fly",provisionWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.labels?.["fly.app"]);if(_(e.egressAllowlist,"fly"),e.volume&&!e.volume.volumeId)throw new d("invalid_request","Fly.io volume mounts require volume.volumeId",{provider:"fly"});let s=encodeURIComponent(n),i=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,o=e.healthcheckPath?{httpget:{type:"http",port:e.port?.internalPort??8080,method:"GET",path:e.healthcheckPath,interval:"15s",timeout:"5s"}}:void 0,a=await p(t,`/apps/${s}/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,...i?{services:i}:{},...o?{checks:o}:{},...e.labels?{metadata:e.labels}:{}}}},r.apiUrl),u=a.config?.guest?.memory_mb??e.memoryMb,l=a.config?.guest?.cpus??e.vcpus;return {provider:"fly",workloadId:a.id,name:a.name,region:a.region,appName:n,url:e.port?.publicHttps?`https://${n}.fly.dev`:void 0,memoryMb:u,vcpus:l,metadata:a.instance_id?{instanceId:a.instance_id}:void 0}},suspendWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=e.memoryMb;if(o===void 0&&(o=(await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl)).config?.guest?.memory_mb),o!==void 0&&o>b)throw new d("invalid_request",`Fly.io Machines suspend requires memoryMb <= ${b} (got ${o} MB)`,{provider:"fly"});await p(t,`/apps/${s}/machines/${i}/suspend`,{method:"POST"},r.apiUrl);let a=new URLSearchParams({state:"suspended",timeout:String(U)});return await p(t,`/apps/${s}/machines/${i}/wait?${a}`,{timeoutMs:P},r.apiUrl),{...e,appName:n,memoryMb:o}},wakeWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId);await p(t,`/apps/${s}/machines/${i}/start`,{method:"POST"},r.apiUrl);let o=new URLSearchParams({state:"started",timeout:String(U)});return await p(t,`/apps/${s}/machines/${i}/wait?${o}`,{timeoutMs:P},r.apiUrl),{...e,appName:n}},fetchWorkloadStatus:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl);return {provider:"fly",workloadId:o.id,state:O(o.state),providerState:o.state,region:o.region,url:e.url,memoryMb:o.config?.guest?.memory_mb??e.memoryMb,vcpus:o.config?.guest?.cpus??e.vcpus,updatedAt:o.updated_at}},fetchWorkloadUsage:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl),a=Date.now(),u=B(o.events??[],o.state,a);return {provider:"fly",workloadId:o.id,memoryMb:o.config?.guest?.memory_mb??e.memoryMb??0,vcpus:o.config?.guest?.cpus??e.vcpus??0,activeSeconds:u.activeSeconds,suspendedSeconds:u.suspendedSeconds,rootfsGb:H(e.metadata?.rootfsGb),metered:u.metered,windowStartIso:new Date(u.windowStartMs).toISOString(),windowEndIso:new Date(u.windowEndMs).toISOString()}},destroyWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId);await p(t,`/apps/${s}/machines/${i}?force=true`,{method:"DELETE"},r.apiUrl).catch(E);}};
2
+ exports.FLY_MACHINES_API_URL=x;exports.FLY_SUSPEND_MAX_MEMORY_MB=b;exports.flyWorkloadDriver=L;exports.sendFlyRequest=p;//# sourceMappingURL=index.cjs.map
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/infraError.ts","../../src/core/infraFetch.ts","../../src/fly/flyRequest.ts","../../src/fly/flyWorkloadDriver.ts"],"names":["RETRYABLE_INFRA_ERROR_CODES","InfraError","code","message","details","prefix","infraErrorForStatus","status","isInfraError","error","ignoreNotFound","assertNoEgressAllowlist","egressAllowlist","provider","INFRA_REQUEST_TIMEOUT_MS","MAX_ERROR_BODY_CHARS","stripTrailingSlash","url","sanitizeUrlForError","rawUrl","parsed","redactSensitiveText","text","token","sanitized","formatErrorExcerpt","trimmed","validateTimeoutMs","timeoutMs","parseJsonOrEmpty","rawBody","cause","sendUnixSocketHttpRequest","socketPath","options","parsedUrl","requestPath","response","resolve","reject","settled","deadlineTimer","settleResolve","result","settleReject","req","nodeHttpRequest","res","chunks","chunk","timeoutCause","sendInfraRequest","method","serializedBody","headers","init","rawError","FLY_MACHINES_API_URL","sendFlyRequest","path","apiUrl","FLY_SUSPEND_MAX_MEMORY_MB","FLY_WAIT_TIMEOUT_SECONDS","FLY_WAIT_HTTP_TIMEOUT_MS","requireFlyAuth","credentials","appFallback","appName","mapFlyMachineState","state","parseRootfsGb","raw","accumulateFlyEventDurations","events","currentState","nowMs","ordered","left","right","activeMs","suspendedMs","index","current","nextEvent","durationMs","lastTimestamp","flyWorkloadDriver","spec","encodedApp","services","checks","machine","memoryMb","vcpus","handle","encodedId","waitQuery","durations"],"mappings":"sCAiBA,IAAMA,CAAAA,CAA2D,IAAI,GAAA,CAAI,CACvE,aAAA,CACA,cAAA,CACA,sBACF,CAAC,CAAA,CAEYC,EAAN,cAAyB,KAAM,C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A,CACA,eAAA,CAAiB,MACfhC,CAAAA,CACA6B,CAAAA,GACkB,CAClB,GAAM,CAAE,KAAA,CAAAvE,CAAAA,CAAO,OAAA,CAAA4C,CAAQ,CAAA,CAAIH,CAAAA,CAAeC,CAAAA,CAAa6B,CAAAA,CAAO,OAAO,CAAA,CAC/DN,CAAAA,CAAa,kBAAA,CAAmBrB,CAAO,CAAA,CACvC4B,CAAAA,CAAY,kBAAA,CAAmBD,CAAAA,CAAO,UAAU,CAAA,CAEtD,MAAMpC,CAAAA,CACJnC,CAAAA,CACA,CAAA,MAAA,EAASiE,CAAU,CAAA,UAAA,EAAaO,CAAS,CAAA,WAAA,CAAA,CACzC,CAAE,MAAA,CAAQ,QAAS,CAAA,CACnB9B,CAAAA,CAAY,MACd,CAAA,CAAE,KAAA,CAAMvD,CAAc,EACxB,CACF","file":"index.cjs","sourcesContent":["export type InfraErrorCode =\n | 'authentication_failed'\n | 'rate_limited'\n | 'not_found'\n | 'conflict'\n | 'provider_unavailable'\n | 'unreachable'\n | 'invalid_request'\n | 'deploy_failed';\n\nexport type InfraErrorDetails = {\n readonly status?: number;\n readonly provider?: string;\n readonly cause?: unknown;\n readonly retryable?: boolean;\n};\n\nconst RETRYABLE_INFRA_ERROR_CODES: ReadonlySet<InfraErrorCode> = new Set([\n 'unreachable',\n 'rate_limited',\n 'provider_unavailable',\n]);\n\nexport class InfraError extends Error {\n readonly code: InfraErrorCode;\n readonly status?: number;\n readonly provider?: string;\n readonly retryable: boolean;\n\n constructor(code: InfraErrorCode, message?: string, details?: InfraErrorDetails) {\n const prefix = details?.provider ? `[${details.provider}] ` : '';\n super(message ? `${prefix}${message}` : `${prefix}Infrastructure request failed (${code})`, {\n cause: details?.cause,\n });\n this.name = 'InfraError';\n this.code = code;\n this.status = details?.status;\n this.provider = details?.provider;\n this.retryable = details?.retryable ?? RETRYABLE_INFRA_ERROR_CODES.has(code);\n }\n}\n\nexport const infraErrorForStatus = (\n status: number,\n details?: { readonly provider?: string; readonly message?: string },\n): InfraError => {\n const code: InfraErrorCode =\n status === 401 || status === 403\n ? 'authentication_failed'\n : status === 404\n ? 'not_found'\n : status === 409\n ? 'conflict'\n : status === 429\n ? 'rate_limited'\n : status === 400 || status === 422\n ? 'invalid_request'\n : 'provider_unavailable';\n const message = details?.message\n ? `HTTP ${status}: ${details.message}`\n : `HTTP ${status} (${code})`;\n return new InfraError(code, message, { status, provider: details?.provider });\n};\n\nexport const isInfraError = (error: unknown, code?: InfraErrorCode): error is InfraError =>\n error instanceof InfraError && (code === undefined || error.code === code);\n\nexport const requireNonEmpty = (\n value: string | undefined,\n label: string,\n provider?: string,\n): string => {\n if (!value?.trim()) {\n throw new InfraError('invalid_request', `Missing required ${label}`, { provider });\n }\n return value;\n};\n\nexport const ignoreNotFound = (error: unknown): void => {\n if (!isInfraError(error, 'not_found')) throw error;\n};\n\nexport const assertNoEgressAllowlist = (\n egressAllowlist: readonly string[] | undefined,\n provider: string,\n): void => {\n if (egressAllowlist && egressAllowlist.length > 0) {\n throw new InfraError('invalid_request', 'Egress allowlist is not enforced by this driver', {\n provider,\n });\n }\n};\n","import { request as nodeHttpRequest } from 'node:http';\nimport { InfraError, infraErrorForStatus } from './infraError.ts';\n\nexport const INFRA_REQUEST_TIMEOUT_MS = 30_000;\n\nconst MAX_ERROR_BODY_CHARS = 500;\n\nexport type InfraFetchOptions = {\n readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly token?: string;\n readonly body?: unknown;\n readonly headers?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly unixSocketPath?: string;\n readonly provider?: string;\n};\n\ntype UnixRequestInit = RequestInit & { unix?: string };\n\nexport const stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nconst sanitizeUrlForError = (rawUrl: string): string => {\n try {\n const parsed = new URL(rawUrl);\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return rawUrl.split('?')[0]?.split('#')[0] ?? rawUrl;\n }\n};\n\nconst redactSensitiveText = (text: string, token?: string): string => {\n let sanitized = text.replace(/Bearer\\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [REDACTED]');\n if (token && token.length > 0) {\n sanitized = sanitized.split(token).join('[REDACTED]');\n }\n return sanitized;\n};\n\nconst formatErrorExcerpt = (text: string, token?: string): string | undefined => {\n const trimmed = redactSensitiveText(text.trim(), token);\n if (!trimmed) return undefined;\n return trimmed.length > MAX_ERROR_BODY_CHARS\n ? `${trimmed.slice(0, MAX_ERROR_BODY_CHARS)}...`\n : trimmed;\n};\n\nconst validateTimeoutMs = (timeoutMs: number | undefined, provider?: string): number => {\n if (timeoutMs === undefined) return INFRA_REQUEST_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new InfraError(\n 'invalid_request',\n `timeoutMs must be a finite positive number (got ${timeoutMs})`,\n { provider },\n );\n }\n return timeoutMs;\n};\n\nconst parseJsonOrEmpty = <T>(rawBody: string, status: number, provider?: string): T => {\n if (status === 204 || !rawBody.trim()) return undefined as T;\n try {\n return JSON.parse(rawBody) as T;\n } catch (cause) {\n throw new InfraError('provider_unavailable', 'Provider returned malformed JSON', {\n status,\n provider,\n cause,\n });\n }\n};\n\nexport const sendUnixSocketHttpRequest = async <T = unknown>(\n url: string,\n socketPath: string,\n options: {\n readonly method: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly serializedBody?: string;\n readonly timeoutMs: number;\n readonly token?: string;\n readonly provider?: string;\n },\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch (cause) {\n throw new InfraError('invalid_request', `Invalid request URL: ${sanitizeUrlForError(url)}`, {\n provider: options.provider,\n cause,\n });\n }\n\n const requestPath = `${parsedUrl.pathname}${parsedUrl.search}`;\n const response = await new Promise<{ readonly status: number; readonly body: string }>(\n (resolve, reject) => {\n let settled = false;\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\n const settleResolve = (result: { readonly status: number; readonly body: string }) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n resolve(result);\n };\n\n const settleReject = (error: InfraError) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n reject(error);\n };\n\n const req = nodeHttpRequest(\n {\n socketPath,\n method: options.method,\n path: requestPath,\n headers: {\n ...options.headers,\n ...(options.serializedBody !== undefined\n ? { 'Content-Length': String(Buffer.byteLength(options.serializedBody)) }\n : {}),\n },\n timeout: timeoutMs,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer | string) => {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n });\n res.on('end', () => {\n settleResolve({\n status: res.statusCode ?? 0,\n body: Buffer.concat(chunks).toString('utf8'),\n });\n });\n res.on('close', () => {\n if (!res.complete) {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response closed prematurely for ${sanitizeUrlForError(url)}`,\n { provider: options.provider },\n ),\n );\n }\n });\n res.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response failed for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause },\n ),\n );\n });\n },\n );\n\n deadlineTimer = setTimeout(() => {\n const timeoutCause = new Error(`Unix socket request exceeded deadline of ${timeoutMs}ms`);\n req.destroy(timeoutCause);\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request timed out for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause: timeoutCause },\n ),\n );\n }, timeoutMs);\n\n req.on('timeout', () => {\n req.destroy(new Error(`Unix socket request timed out after ${timeoutMs}ms`));\n });\n req.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request failed for ${sanitizeUrlForError(url)}`,\n {\n provider: options.provider,\n cause,\n },\n ),\n );\n });\n\n if (options.serializedBody !== undefined) {\n req.write(options.serializedBody);\n }\n req.end();\n },\n );\n\n if (response.status >= 300 && response.status < 400) {\n throw new InfraError(\n 'unreachable',\n `Unexpected redirect (${response.status}) from ${sanitizeUrlForError(url)}`,\n { status: response.status, provider: options.provider },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(response.body, options.token),\n });\n }\n\n return parseJsonOrEmpty<T>(response.body, response.status, options.provider);\n};\n\nexport const sendInfraRequest = async <T = unknown>(\n url: string,\n options: InfraFetchOptions = {},\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n const method = options.method ?? 'GET';\n const serializedBody = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),\n ...(serializedBody !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...options.headers,\n };\n\n if (options.unixSocketPath && typeof Bun === 'undefined') {\n return sendUnixSocketHttpRequest<T>(url, options.unixSocketPath, {\n method,\n headers,\n serializedBody,\n timeoutMs,\n token: options.token,\n provider: options.provider,\n });\n }\n\n const init: UnixRequestInit = {\n method,\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n headers,\n ...(serializedBody !== undefined ? { body: serializedBody } : {}),\n ...(options.unixSocketPath ? { unix: options.unixSocketPath } : {}),\n };\n\n let response: Response;\n try {\n response = await fetch(url, init);\n } catch (cause) {\n throw new InfraError('unreachable', `Request to ${sanitizeUrlForError(url)} failed`, {\n provider: options.provider,\n cause,\n });\n }\n\n if (!response.ok) {\n const rawError = await response.text().catch(() => '');\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(rawError, options.token),\n });\n }\n\n if (response.status === 204) return undefined as T;\n\n const rawBody = await response.text().catch((cause) => {\n throw new InfraError('unreachable', 'Failed to read response body', {\n status: response.status,\n provider: options.provider,\n cause,\n });\n });\n\n return parseJsonOrEmpty<T>(rawBody, response.status, options.provider);\n};\n","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 WorkloadCredentials,\n WorkloadDriver,\n WorkloadHandle,\n WorkloadRuntimeState,\n WorkloadSpec,\n WorkloadStatus,\n WorkloadUsage,\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: WorkloadCredentials,\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): WorkloadRuntimeState => {\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\nexport const flyWorkloadDriver: WorkloadDriver = {\n provider: 'fly',\n provisionWorkload: async (\n credentials: WorkloadCredentials,\n spec: WorkloadSpec,\n ): Promise<WorkloadHandle> => {\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 workloadId: 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 suspendWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 wakeWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 fetchWorkloadStatus: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadStatus> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n\n return {\n provider: 'fly',\n workloadId: machine.id,\n state: mapFlyMachineState(machine.state),\n providerState: machine.state,\n region: machine.region,\n url: handle.url,\n memoryMb: machine.config?.guest?.memory_mb ?? handle.memoryMb,\n vcpus: machine.config?.guest?.cpus ?? handle.vcpus,\n updatedAt: machine.updated_at,\n };\n },\n fetchWorkloadUsage: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadUsage> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 workloadId: 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 destroyWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<void> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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,14 @@
1
+ import { W as WorkloadDriver } from '../contracts-BxHKiOwj.cjs';
2
+
3
+ declare const FLY_MACHINES_API_URL = "https://api.machines.dev/v1";
4
+ type FlyRequestInit = {
5
+ readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
6
+ readonly body?: unknown;
7
+ readonly timeoutMs?: number;
8
+ };
9
+ declare const sendFlyRequest: <T>(token: string, path: string, init?: FlyRequestInit, apiUrl?: string) => Promise<T>;
10
+
11
+ declare const FLY_SUSPEND_MAX_MEMORY_MB = 2048;
12
+ declare const flyWorkloadDriver: WorkloadDriver;
13
+
14
+ export { FLY_MACHINES_API_URL, FLY_SUSPEND_MAX_MEMORY_MB, type FlyRequestInit, flyWorkloadDriver, sendFlyRequest };
@@ -0,0 +1,14 @@
1
+ import { W as WorkloadDriver } from '../contracts-BxHKiOwj.js';
2
+
3
+ declare const FLY_MACHINES_API_URL = "https://api.machines.dev/v1";
4
+ type FlyRequestInit = {
5
+ readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
6
+ readonly body?: unknown;
7
+ readonly timeoutMs?: number;
8
+ };
9
+ declare const sendFlyRequest: <T>(token: string, path: string, init?: FlyRequestInit, apiUrl?: string) => Promise<T>;
10
+
11
+ declare const FLY_SUSPEND_MAX_MEMORY_MB = 2048;
12
+ declare const flyWorkloadDriver: WorkloadDriver;
13
+
14
+ export { FLY_MACHINES_API_URL, FLY_SUSPEND_MAX_MEMORY_MB, type FlyRequestInit, flyWorkloadDriver, sendFlyRequest };
@@ -0,0 +1,3 @@
1
+ import {request}from'http';var F=new Set(["unreachable","rate_limited","provider_unavailable"]),d=class extends Error{code;status;provider;retryable;constructor(e,t,n){let s=n?.provider?`[${n.provider}] `:"";super(t?`${s}${t}`:`${s}Infrastructure request failed (${e})`,{cause:n?.cause}),this.name="InfraError",this.code=e,this.status=n?.status,this.provider=n?.provider,this.retryable=n?.retryable??F.has(e);}},w=(r,e)=>{let t=r===401||r===403?"authentication_failed":r===404?"not_found":r===409?"conflict":r===429?"rate_limited":r===400||r===422?"invalid_request":"provider_unavailable",n=e?.message?`HTTP ${r}: ${e.message}`:`HTTP ${r} (${t})`;return new d(t,n,{status:r,provider:e?.provider})},C=(r,e)=>r instanceof d&&(r.code===e);var E=r=>{if(!C(r,"not_found"))throw r},_=(r,e)=>{if(r&&r.length>0)throw new d("invalid_request","Egress allowlist is not enforced by this driver",{provider:e})};var N=3e4,I=500,S=r=>r.replace(/\/+$/,""),y=r=>{try{let e=new URL(r);return `${e.protocol}//${e.host}${e.pathname}`}catch{return r.split("?")[0]?.split("#")[0]??r}},A=(r,e)=>{let t=r.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer [REDACTED]");return e&&e.length>0&&(t=t.split(e).join("[REDACTED]")),t},R=(r,e)=>{let t=A(r.trim(),e);if(t)return t.length>I?`${t.slice(0,I)}...`:t},M=(r,e)=>{if(r===void 0)return N;if(!Number.isFinite(r)||r<=0)throw new d("invalid_request",`timeoutMs must be a finite positive number (got ${r})`,{provider:e});return r},T=(r,e,t)=>{if(!(e===204||!r.trim()))try{return JSON.parse(r)}catch(n){throw new d("provider_unavailable","Provider returned malformed JSON",{status:e,provider:t,cause:n})}},D=async(r,e,t)=>{let n=M(t.timeoutMs,t.provider),s;try{s=new URL(r);}catch(a){throw new d("invalid_request",`Invalid request URL: ${y(r)}`,{provider:t.provider,cause:a})}let i=`${s.pathname}${s.search}`,o=await new Promise((a,u)=>{let l=false,m,q=c=>{l||(l=true,m!==void 0&&clearTimeout(m),a(c));},v=c=>{l||(l=true,m!==void 0&&clearTimeout(m),u(c));},f=request({socketPath:e,method:t.method,path:i,headers:{...t.headers,...t.serializedBody!==void 0?{"Content-Length":String(Buffer.byteLength(t.serializedBody))}:{}},timeout:n},c=>{let k=[];c.on("data",h=>{k.push(typeof h=="string"?Buffer.from(h):h);}),c.on("end",()=>{q({status:c.statusCode??0,body:Buffer.concat(k).toString("utf8")});}),c.on("close",()=>{c.complete||v(new d("unreachable",`Unix socket response closed prematurely for ${y(r)}`,{provider:t.provider}));}),c.on("error",h=>{v(new d("unreachable",`Unix socket response failed for ${y(r)}`,{provider:t.provider,cause:h}));});});m=setTimeout(()=>{let c=new Error(`Unix socket request exceeded deadline of ${n}ms`);f.destroy(c),v(new d("unreachable",`Unix socket request timed out for ${y(r)}`,{provider:t.provider,cause:c}));},n),f.on("timeout",()=>{f.destroy(new Error(`Unix socket request timed out after ${n}ms`));}),f.on("error",c=>{v(new d("unreachable",`Unix socket request failed for ${y(r)}`,{provider:t.provider,cause:c}));}),t.serializedBody!==void 0&&f.write(t.serializedBody),f.end();});if(o.status>=300&&o.status<400)throw new d("unreachable",`Unexpected redirect (${o.status}) from ${y(r)}`,{status:o.status,provider:t.provider});if(o.status<200||o.status>=300)throw w(o.status,{provider:t.provider,message:R(o.body,t.token)});return T(o.body,o.status,t.provider)},$=async(r,e={})=>{let t=M(e.timeoutMs,e.provider),n=e.method??"GET",s=e.body!==void 0?JSON.stringify(e.body):void 0,i={Accept:"application/json",...e.token?{Authorization:`Bearer ${e.token}`}:{},...s!==void 0?{"Content-Type":"application/json"}:{},...e.headers};if(e.unixSocketPath&&typeof Bun>"u")return D(r,e.unixSocketPath,{method:n,headers:i,serializedBody:s,timeoutMs:t,token:e.token,provider:e.provider});let o={method:n,redirect:"error",signal:AbortSignal.timeout(t),headers:i,...s!==void 0?{body:s}:{},...e.unixSocketPath?{unix:e.unixSocketPath}:{}},a;try{a=await fetch(r,o);}catch(l){throw new d("unreachable",`Request to ${y(r)} failed`,{provider:e.provider,cause:l})}if(!a.ok){let l=await a.text().catch(()=>"");throw w(a.status,{provider:e.provider,message:R(l,e.token)})}if(a.status===204)return;let u=await a.text().catch(l=>{throw new d("unreachable","Failed to read response body",{status:a.status,provider:e.provider,cause:l})});return T(u,a.status,e.provider)};var x="https://api.machines.dev/v1",p=async(r,e,t={},n=x)=>$(`${S(n)}${e}`,{method:t.method??"GET",token:r,body:t.body,timeoutMs:t.timeoutMs,provider:"fly"});var b=2048,U=30,P=4e4,g=(r,e)=>{if(!r.token)throw new d("authentication_failed","Fly.io API token is required",{provider:"fly"});let t=r.appName??e;if(!t)throw new d("invalid_request","Fly.io appName is required",{provider:"fly"});return {token:r.token,appName:t}},O=r=>{switch(r){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"}},H=r=>{if(r===void 0)return 0;let e=Number(r);return Number.isFinite(e)&&e>=0?e:0},B=(r,e,t)=>{if(r.length===0)return {activeSeconds:0,suspendedSeconds:0,metered:false,windowStartMs:t,windowEndMs:t};let n=[...r].sort((a,u)=>a.timestamp-u.timestamp),s=0,i=0;for(let a=0;a<n.length;a+=1){let u=n[a],l=n[a+1];if(l){let m=Math.max(0,l.timestamp-u.timestamp);u.status==="started"?s+=m:u.status==="suspended"&&(i+=m);}else if(u.status===e){let m=Math.max(0,t-u.timestamp);e==="started"?s+=m:e==="suspended"&&(i+=m);}}let o=n[n.length-1].timestamp;return {activeSeconds:Math.round(s/1e3),suspendedSeconds:Math.round(i/1e3),metered:true,windowStartMs:n[0].timestamp,windowEndMs:Math.max(t,o)}},L={provider:"fly",provisionWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.labels?.["fly.app"]);if(_(e.egressAllowlist,"fly"),e.volume&&!e.volume.volumeId)throw new d("invalid_request","Fly.io volume mounts require volume.volumeId",{provider:"fly"});let s=encodeURIComponent(n),i=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,o=e.healthcheckPath?{httpget:{type:"http",port:e.port?.internalPort??8080,method:"GET",path:e.healthcheckPath,interval:"15s",timeout:"5s"}}:void 0,a=await p(t,`/apps/${s}/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,...i?{services:i}:{},...o?{checks:o}:{},...e.labels?{metadata:e.labels}:{}}}},r.apiUrl),u=a.config?.guest?.memory_mb??e.memoryMb,l=a.config?.guest?.cpus??e.vcpus;return {provider:"fly",workloadId:a.id,name:a.name,region:a.region,appName:n,url:e.port?.publicHttps?`https://${n}.fly.dev`:void 0,memoryMb:u,vcpus:l,metadata:a.instance_id?{instanceId:a.instance_id}:void 0}},suspendWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=e.memoryMb;if(o===void 0&&(o=(await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl)).config?.guest?.memory_mb),o!==void 0&&o>b)throw new d("invalid_request",`Fly.io Machines suspend requires memoryMb <= ${b} (got ${o} MB)`,{provider:"fly"});await p(t,`/apps/${s}/machines/${i}/suspend`,{method:"POST"},r.apiUrl);let a=new URLSearchParams({state:"suspended",timeout:String(U)});return await p(t,`/apps/${s}/machines/${i}/wait?${a}`,{timeoutMs:P},r.apiUrl),{...e,appName:n,memoryMb:o}},wakeWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId);await p(t,`/apps/${s}/machines/${i}/start`,{method:"POST"},r.apiUrl);let o=new URLSearchParams({state:"started",timeout:String(U)});return await p(t,`/apps/${s}/machines/${i}/wait?${o}`,{timeoutMs:P},r.apiUrl),{...e,appName:n}},fetchWorkloadStatus:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl);return {provider:"fly",workloadId:o.id,state:O(o.state),providerState:o.state,region:o.region,url:e.url,memoryMb:o.config?.guest?.memory_mb??e.memoryMb,vcpus:o.config?.guest?.cpus??e.vcpus,updatedAt:o.updated_at}},fetchWorkloadUsage:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId),o=await p(t,`/apps/${s}/machines/${i}`,{},r.apiUrl),a=Date.now(),u=B(o.events??[],o.state,a);return {provider:"fly",workloadId:o.id,memoryMb:o.config?.guest?.memory_mb??e.memoryMb??0,vcpus:o.config?.guest?.cpus??e.vcpus??0,activeSeconds:u.activeSeconds,suspendedSeconds:u.suspendedSeconds,rootfsGb:H(e.metadata?.rootfsGb),metered:u.metered,windowStartIso:new Date(u.windowStartMs).toISOString(),windowEndIso:new Date(u.windowEndMs).toISOString()}},destroyWorkload:async(r,e)=>{let{token:t,appName:n}=g(r,e.appName),s=encodeURIComponent(n),i=encodeURIComponent(e.workloadId);await p(t,`/apps/${s}/machines/${i}?force=true`,{method:"DELETE"},r.apiUrl).catch(E);}};
2
+ export{x as FLY_MACHINES_API_URL,b as FLY_SUSPEND_MAX_MEMORY_MB,L as flyWorkloadDriver,p as sendFlyRequest};//# sourceMappingURL=index.js.map
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/infraError.ts","../../src/core/infraFetch.ts","../../src/fly/flyRequest.ts","../../src/fly/flyWorkloadDriver.ts"],"names":["RETRYABLE_INFRA_ERROR_CODES","InfraError","code","message","details","prefix","infraErrorForStatus","status","isInfraError","error","ignoreNotFound","assertNoEgressAllowlist","egressAllowlist","provider","INFRA_REQUEST_TIMEOUT_MS","MAX_ERROR_BODY_CHARS","stripTrailingSlash","url","sanitizeUrlForError","rawUrl","parsed","redactSensitiveText","text","token","sanitized","formatErrorExcerpt","trimmed","validateTimeoutMs","timeoutMs","parseJsonOrEmpty","rawBody","cause","sendUnixSocketHttpRequest","socketPath","options","parsedUrl","requestPath","response","resolve","reject","settled","deadlineTimer","settleResolve","result","settleReject","req","nodeHttpRequest","res","chunks","chunk","timeoutCause","sendInfraRequest","method","serializedBody","headers","init","rawError","FLY_MACHINES_API_URL","sendFlyRequest","path","apiUrl","FLY_SUSPEND_MAX_MEMORY_MB","FLY_WAIT_TIMEOUT_SECONDS","FLY_WAIT_HTTP_TIMEOUT_MS","requireFlyAuth","credentials","appFallback","appName","mapFlyMachineState","state","parseRootfsGb","raw","accumulateFlyEventDurations","events","currentState","nowMs","ordered","left","right","activeMs","suspendedMs","index","current","nextEvent","durationMs","lastTimestamp","flyWorkloadDriver","spec","encodedApp","services","checks","machine","memoryMb","vcpus","handle","encodedId","waitQuery","durations"],"mappings":"2BAiBA,IAAMA,CAAAA,CAA2D,IAAI,GAAA,CAAI,CACvE,aAAA,CACA,cAAA,CACA,sBACF,CAAC,CAAA,CAEYC,EAAN,cAAyB,KAAM,CAC3B,IAAA,CACA,MAAA,CACA,QAAA,CACA,SAAA,CAET,WAAA,CAAYC,CAAAA,CAAsBC,CAAAA,CAAkBC,CAAAA,CAA6B,CAC/E,IAAMC,CAAAA,CAASD,GAAS,QAAA,CAAW,CAAA,CAAA,EAAIA,CAAAA,CAAQ,QAAQ,CAAA,EAAA,CAAA,CAAO,EAAA,C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rB,CAAO,CAAA,CACvC4B,CAAAA,CAAY,kBAAA,CAAmBD,CAAAA,CAAO,UAAU,CAAA,CAEtD,MAAMpC,CAAAA,CACJnC,CAAAA,CACA,CAAA,MAAA,EAASiE,CAAU,CAAA,UAAA,EAAaO,CAAS,CAAA,WAAA,CAAA,CACzC,CAAE,MAAA,CAAQ,QAAS,CAAA,CACnB9B,CAAAA,CAAY,MACd,CAAA,CAAE,KAAA,CAAMvD,CAAc,EACxB,CACF","file":"index.js","sourcesContent":["export type InfraErrorCode =\n | 'authentication_failed'\n | 'rate_limited'\n | 'not_found'\n | 'conflict'\n | 'provider_unavailable'\n | 'unreachable'\n | 'invalid_request'\n | 'deploy_failed';\n\nexport type InfraErrorDetails = {\n readonly status?: number;\n readonly provider?: string;\n readonly cause?: unknown;\n readonly retryable?: boolean;\n};\n\nconst RETRYABLE_INFRA_ERROR_CODES: ReadonlySet<InfraErrorCode> = new Set([\n 'unreachable',\n 'rate_limited',\n 'provider_unavailable',\n]);\n\nexport class InfraError extends Error {\n readonly code: InfraErrorCode;\n readonly status?: number;\n readonly provider?: string;\n readonly retryable: boolean;\n\n constructor(code: InfraErrorCode, message?: string, details?: InfraErrorDetails) {\n const prefix = details?.provider ? `[${details.provider}] ` : '';\n super(message ? `${prefix}${message}` : `${prefix}Infrastructure request failed (${code})`, {\n cause: details?.cause,\n });\n this.name = 'InfraError';\n this.code = code;\n this.status = details?.status;\n this.provider = details?.provider;\n this.retryable = details?.retryable ?? RETRYABLE_INFRA_ERROR_CODES.has(code);\n }\n}\n\nexport const infraErrorForStatus = (\n status: number,\n details?: { readonly provider?: string; readonly message?: string },\n): InfraError => {\n const code: InfraErrorCode =\n status === 401 || status === 403\n ? 'authentication_failed'\n : status === 404\n ? 'not_found'\n : status === 409\n ? 'conflict'\n : status === 429\n ? 'rate_limited'\n : status === 400 || status === 422\n ? 'invalid_request'\n : 'provider_unavailable';\n const message = details?.message\n ? `HTTP ${status}: ${details.message}`\n : `HTTP ${status} (${code})`;\n return new InfraError(code, message, { status, provider: details?.provider });\n};\n\nexport const isInfraError = (error: unknown, code?: InfraErrorCode): error is InfraError =>\n error instanceof InfraError && (code === undefined || error.code === code);\n\nexport const requireNonEmpty = (\n value: string | undefined,\n label: string,\n provider?: string,\n): string => {\n if (!value?.trim()) {\n throw new InfraError('invalid_request', `Missing required ${label}`, { provider });\n }\n return value;\n};\n\nexport const ignoreNotFound = (error: unknown): void => {\n if (!isInfraError(error, 'not_found')) throw error;\n};\n\nexport const assertNoEgressAllowlist = (\n egressAllowlist: readonly string[] | undefined,\n provider: string,\n): void => {\n if (egressAllowlist && egressAllowlist.length > 0) {\n throw new InfraError('invalid_request', 'Egress allowlist is not enforced by this driver', {\n provider,\n });\n }\n};\n","import { request as nodeHttpRequest } from 'node:http';\nimport { InfraError, infraErrorForStatus } from './infraError.ts';\n\nexport const INFRA_REQUEST_TIMEOUT_MS = 30_000;\n\nconst MAX_ERROR_BODY_CHARS = 500;\n\nexport type InfraFetchOptions = {\n readonly method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n readonly token?: string;\n readonly body?: unknown;\n readonly headers?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly unixSocketPath?: string;\n readonly provider?: string;\n};\n\ntype UnixRequestInit = RequestInit & { unix?: string };\n\nexport const stripTrailingSlash = (url: string): string => url.replace(/\\/+$/, '');\n\nconst sanitizeUrlForError = (rawUrl: string): string => {\n try {\n const parsed = new URL(rawUrl);\n return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;\n } catch {\n return rawUrl.split('?')[0]?.split('#')[0] ?? rawUrl;\n }\n};\n\nconst redactSensitiveText = (text: string, token?: string): string => {\n let sanitized = text.replace(/Bearer\\s+[A-Za-z0-9._~+/-]+=*/gi, 'Bearer [REDACTED]');\n if (token && token.length > 0) {\n sanitized = sanitized.split(token).join('[REDACTED]');\n }\n return sanitized;\n};\n\nconst formatErrorExcerpt = (text: string, token?: string): string | undefined => {\n const trimmed = redactSensitiveText(text.trim(), token);\n if (!trimmed) return undefined;\n return trimmed.length > MAX_ERROR_BODY_CHARS\n ? `${trimmed.slice(0, MAX_ERROR_BODY_CHARS)}...`\n : trimmed;\n};\n\nconst validateTimeoutMs = (timeoutMs: number | undefined, provider?: string): number => {\n if (timeoutMs === undefined) return INFRA_REQUEST_TIMEOUT_MS;\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new InfraError(\n 'invalid_request',\n `timeoutMs must be a finite positive number (got ${timeoutMs})`,\n { provider },\n );\n }\n return timeoutMs;\n};\n\nconst parseJsonOrEmpty = <T>(rawBody: string, status: number, provider?: string): T => {\n if (status === 204 || !rawBody.trim()) return undefined as T;\n try {\n return JSON.parse(rawBody) as T;\n } catch (cause) {\n throw new InfraError('provider_unavailable', 'Provider returned malformed JSON', {\n status,\n provider,\n cause,\n });\n }\n};\n\nexport const sendUnixSocketHttpRequest = async <T = unknown>(\n url: string,\n socketPath: string,\n options: {\n readonly method: string;\n readonly headers: Readonly<Record<string, string>>;\n readonly serializedBody?: string;\n readonly timeoutMs: number;\n readonly token?: string;\n readonly provider?: string;\n },\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n\n let parsedUrl: URL;\n try {\n parsedUrl = new URL(url);\n } catch (cause) {\n throw new InfraError('invalid_request', `Invalid request URL: ${sanitizeUrlForError(url)}`, {\n provider: options.provider,\n cause,\n });\n }\n\n const requestPath = `${parsedUrl.pathname}${parsedUrl.search}`;\n const response = await new Promise<{ readonly status: number; readonly body: string }>(\n (resolve, reject) => {\n let settled = false;\n let deadlineTimer: ReturnType<typeof setTimeout> | undefined;\n\n const settleResolve = (result: { readonly status: number; readonly body: string }) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n resolve(result);\n };\n\n const settleReject = (error: InfraError) => {\n if (settled) return;\n settled = true;\n if (deadlineTimer !== undefined) clearTimeout(deadlineTimer);\n reject(error);\n };\n\n const req = nodeHttpRequest(\n {\n socketPath,\n method: options.method,\n path: requestPath,\n headers: {\n ...options.headers,\n ...(options.serializedBody !== undefined\n ? { 'Content-Length': String(Buffer.byteLength(options.serializedBody)) }\n : {}),\n },\n timeout: timeoutMs,\n },\n (res) => {\n const chunks: Buffer[] = [];\n res.on('data', (chunk: Buffer | string) => {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk) : chunk);\n });\n res.on('end', () => {\n settleResolve({\n status: res.statusCode ?? 0,\n body: Buffer.concat(chunks).toString('utf8'),\n });\n });\n res.on('close', () => {\n if (!res.complete) {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response closed prematurely for ${sanitizeUrlForError(url)}`,\n { provider: options.provider },\n ),\n );\n }\n });\n res.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket response failed for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause },\n ),\n );\n });\n },\n );\n\n deadlineTimer = setTimeout(() => {\n const timeoutCause = new Error(`Unix socket request exceeded deadline of ${timeoutMs}ms`);\n req.destroy(timeoutCause);\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request timed out for ${sanitizeUrlForError(url)}`,\n { provider: options.provider, cause: timeoutCause },\n ),\n );\n }, timeoutMs);\n\n req.on('timeout', () => {\n req.destroy(new Error(`Unix socket request timed out after ${timeoutMs}ms`));\n });\n req.on('error', (cause) => {\n settleReject(\n new InfraError(\n 'unreachable',\n `Unix socket request failed for ${sanitizeUrlForError(url)}`,\n {\n provider: options.provider,\n cause,\n },\n ),\n );\n });\n\n if (options.serializedBody !== undefined) {\n req.write(options.serializedBody);\n }\n req.end();\n },\n );\n\n if (response.status >= 300 && response.status < 400) {\n throw new InfraError(\n 'unreachable',\n `Unexpected redirect (${response.status}) from ${sanitizeUrlForError(url)}`,\n { status: response.status, provider: options.provider },\n );\n }\n\n if (response.status < 200 || response.status >= 300) {\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(response.body, options.token),\n });\n }\n\n return parseJsonOrEmpty<T>(response.body, response.status, options.provider);\n};\n\nexport const sendInfraRequest = async <T = unknown>(\n url: string,\n options: InfraFetchOptions = {},\n): Promise<T> => {\n const timeoutMs = validateTimeoutMs(options.timeoutMs, options.provider);\n const method = options.method ?? 'GET';\n const serializedBody = options.body !== undefined ? JSON.stringify(options.body) : undefined;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),\n ...(serializedBody !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...options.headers,\n };\n\n if (options.unixSocketPath && typeof Bun === 'undefined') {\n return sendUnixSocketHttpRequest<T>(url, options.unixSocketPath, {\n method,\n headers,\n serializedBody,\n timeoutMs,\n token: options.token,\n provider: options.provider,\n });\n }\n\n const init: UnixRequestInit = {\n method,\n redirect: 'error',\n signal: AbortSignal.timeout(timeoutMs),\n headers,\n ...(serializedBody !== undefined ? { body: serializedBody } : {}),\n ...(options.unixSocketPath ? { unix: options.unixSocketPath } : {}),\n };\n\n let response: Response;\n try {\n response = await fetch(url, init);\n } catch (cause) {\n throw new InfraError('unreachable', `Request to ${sanitizeUrlForError(url)} failed`, {\n provider: options.provider,\n cause,\n });\n }\n\n if (!response.ok) {\n const rawError = await response.text().catch(() => '');\n throw infraErrorForStatus(response.status, {\n provider: options.provider,\n message: formatErrorExcerpt(rawError, options.token),\n });\n }\n\n if (response.status === 204) return undefined as T;\n\n const rawBody = await response.text().catch((cause) => {\n throw new InfraError('unreachable', 'Failed to read response body', {\n status: response.status,\n provider: options.provider,\n cause,\n });\n });\n\n return parseJsonOrEmpty<T>(rawBody, response.status, options.provider);\n};\n","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 WorkloadCredentials,\n WorkloadDriver,\n WorkloadHandle,\n WorkloadRuntimeState,\n WorkloadSpec,\n WorkloadStatus,\n WorkloadUsage,\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: WorkloadCredentials,\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): WorkloadRuntimeState => {\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\nexport const flyWorkloadDriver: WorkloadDriver = {\n provider: 'fly',\n provisionWorkload: async (\n credentials: WorkloadCredentials,\n spec: WorkloadSpec,\n ): Promise<WorkloadHandle> => {\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 workloadId: 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 suspendWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 wakeWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadHandle> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 fetchWorkloadStatus: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadStatus> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\n\n const machine = await sendFlyRequest<FlyMachine>(\n token,\n `/apps/${encodedApp}/machines/${encodedId}`,\n {},\n credentials.apiUrl,\n );\n\n return {\n provider: 'fly',\n workloadId: machine.id,\n state: mapFlyMachineState(machine.state),\n providerState: machine.state,\n region: machine.region,\n url: handle.url,\n memoryMb: machine.config?.guest?.memory_mb ?? handle.memoryMb,\n vcpus: machine.config?.guest?.cpus ?? handle.vcpus,\n updatedAt: machine.updated_at,\n };\n },\n fetchWorkloadUsage: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<WorkloadUsage> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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 workloadId: 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 destroyWorkload: async (\n credentials: WorkloadCredentials,\n handle: WorkloadHandle,\n ): Promise<void> => {\n const { token, appName } = requireFlyAuth(credentials, handle.appName);\n const encodedApp = encodeURIComponent(appName);\n const encodedId = encodeURIComponent(handle.workloadId);\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"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';var http=require('http');var Er=new Set(["unreachable","rate_limited","provider_unavailable"]),d=class extends Error{code;status;provider;retryable;constructor(r,t,n){let o=n?.provider?`[${n.provider}] `:"";super(t?`${o}${t}`:`${o}Infrastructure request failed (${r})`,{cause:n?.cause}),this.name="InfraError",this.code=r,this.status=n?.status,this.provider=n?.provider,this.retryable=n?.retryable??Er.has(r);}},ue=(e,r)=>{let t=e===401||e===403?"authentication_failed":e===404?"not_found":e===409?"conflict":e===429?"rate_limited":e===400||e===422?"invalid_request":"provider_unavailable",n=r?.message?`HTTP ${e}: ${r.message}`:`HTTP ${e} (${t})`;return new d(t,n,{status:e,provider:r?.provider})},Ge=(e,r)=>e instanceof d&&(r===void 0||e.code===r),p=(e,r,t)=>{if(!e?.trim())throw new d("invalid_request",`Missing required ${r}`,{provider:t});return e},R=e=>{if(!Ge(e,"not_found"))throw e},_=(e,r)=>{if(e&&e.length>0)throw new d("invalid_request","Egress allowlist is not enforced by this driver",{provider:r})};var b="ghcr.io/inixiative/archive",N=4700,P="archive",z=e=>{if(!e.archiveToken)throw new d("authentication_failed","Archive server token is required");return e.archiveToken};var Ve=3e4,je=500,A=e=>e.replace(/\/+$/,""),U=e=>{try{let r=new URL(e);return `${r.protocol}//${r.host}${r.pathname}`}catch{return e.split("?")[0]?.split("#")[0]??e}},Dr=(e,r)=>{let t=e.replace(/Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,"Bearer [REDACTED]");return r&&r.length>0&&(t=t.split(r).join("[REDACTED]")),t},Be=(e,r)=>{let t=Dr(e.trim(),r);if(t)return t.length>je?`${t.slice(0,je)}...`:t},Ye=(e,r)=>{if(e===void 0)return Ve;if(!Number.isFinite(e)||e<=0)throw new d("invalid_request",`timeoutMs must be a finite positive number (got ${e})`,{provider:r});return e},ze=(e,r,t)=>{if(!(r===204||!e.trim()))try{return JSON.parse(e)}catch(n){throw new d("provider_unavailable","Provider returned malformed JSON",{status:r,provider:t,cause:n})}},Ke=async(e,r,t)=>{let n=Ye(t.timeoutMs,t.provider),o;try{o=new URL(e);}catch(s){throw new d("invalid_request",`Invalid request URL: ${U(e)}`,{provider:t.provider,cause:s})}let a=`${o.pathname}${o.search}`,i=await new Promise((s,c)=>{let l=false,u,v=y=>{l||(l=true,u!==void 0&&clearTimeout(u),s(y));},k=y=>{l||(l=true,u!==void 0&&clearTimeout(u),c(y));},I=http.request({socketPath:r,method:t.method,path:a,headers:{...t.headers,...t.serializedBody!==void 0?{"Content-Length":String(Buffer.byteLength(t.serializedBody))}:{}},timeout:n},y=>{let B=[];y.on("data",Y=>{B.push(typeof Y=="string"?Buffer.from(Y):Y);}),y.on("end",()=>{v({status:y.statusCode??0,body:Buffer.concat(B).toString("utf8")});}),y.on("close",()=>{y.complete||k(new d("unreachable",`Unix socket response closed prematurely for ${U(e)}`,{provider:t.provider}));}),y.on("error",Y=>{k(new d("unreachable",`Unix socket response failed for ${U(e)}`,{provider:t.provider,cause:Y}));});});u=setTimeout(()=>{let y=new Error(`Unix socket request exceeded deadline of ${n}ms`);I.destroy(y),k(new d("unreachable",`Unix socket request timed out for ${U(e)}`,{provider:t.provider,cause:y}));},n),I.on("timeout",()=>{I.destroy(new Error(`Unix socket request timed out after ${n}ms`));}),I.on("error",y=>{k(new d("unreachable",`Unix socket request failed for ${U(e)}`,{provider:t.provider,cause:y}));}),t.serializedBody!==void 0&&I.write(t.serializedBody),I.end();});if(i.status>=300&&i.status<400)throw new d("unreachable",`Unexpected redirect (${i.status}) from ${U(e)}`,{status:i.status,provider:t.provider});if(i.status<200||i.status>=300)throw ue(i.status,{provider:t.provider,message:Be(i.body,t.token)});return ze(i.body,i.status,t.provider)},E=async(e,r={})=>{let t=Ye(r.timeoutMs,r.provider),n=r.method??"GET",o=r.body!==void 0?JSON.stringify(r.body):void 0,a={Accept:"application/json",...r.token?{Authorization:`Bearer ${r.token}`}:{},...o!==void 0?{"Content-Type":"application/json"}:{},...r.headers};if(r.unixSocketPath&&typeof Bun>"u")return Ke(e,r.unixSocketPath,{method:n,headers:a,serializedBody:o,timeoutMs:t,token:r.token,provider:r.provider});let i={method:n,redirect:"error",signal:AbortSignal.timeout(t),headers:a,...o!==void 0?{body:o}:{},...r.unixSocketPath?{unix:r.unixSocketPath}:{}},s;try{s=await fetch(e,i);}catch(l){throw new d("unreachable",`Request to ${U(e)} failed`,{provider:r.provider,cause:l})}if(!s.ok){let l=await s.text().catch(()=>"");throw ue(s.status,{provider:r.provider,message:Be(l,r.token)})}if(s.status===204)return;let c=await s.text().catch(l=>{throw new d("unreachable","Failed to read response body",{status:s.status,provider:r.provider,cause:l})});return ze(c,s.status,r.provider)};var Qe=["railway","render","fly","firecracker"],Cr=["aws","gcp","azure"],Ze=["railway","render"],_e={railway:{id:"railway",name:"Railway",implemented:true,supportsArchiveHosting:true,supportsWorkloadDriver: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,supportsWorkloadDriver: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,supportsWorkloadDriver: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,supportsWorkloadDriver: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,supportsWorkloadDriver: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,supportsWorkloadDriver: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 workloads."},azure:{id:"azure",name:"Azure (Container Apps / ACI)",implemented:false,supportsArchiveHosting:false,supportsWorkloadDriver: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."}},Ur=e=>typeof e=="string"&&Object.hasOwn(_e,e),xr=e=>Qe.some(r=>r===e),Tr=e=>Ze.some(r=>r===e),be=e=>_e[e];var Pe="http://localhost",w=async(e,r,t={})=>{if(!e.unixSocketPath&&!e.apiUrl)throw new d("invalid_request","Firecracker driver requires either unixSocketPath or apiUrl",{provider:"firecracker"});let n=A(e.apiUrl??Pe);return E(`${n}${r}`,{method:t.method??"GET",token:e.token,body:t.body,timeoutMs:t.timeoutMs,unixSocketPath:e.unixSocketPath,provider:"firecracker"})};var Hr="/var/lib/firecracker/vmlinux",$r="console=ttyS0 reboot=k panic=1 pci=off",Nr=/^[A-Za-z0-9._-]+$/,K=e=>({apiUrl:e.apiUrl,unixSocketPath:e.unixSocketPath,token:e.token}),Q=(e,r)=>{if(!e||e==="."||e===".."||e.includes("..")||e.includes("/")||e.includes("\\")||e.includes("\0")||!Nr.test(e))throw new d("invalid_request",`Invalid Firecracker ${r}: must match /^[A-Za-z0-9._-]+$/ without path traversal`,{provider:"firecracker"});return e},Lr=e=>{if(e===void 0)return 0;let r=Number(e);return Number.isFinite(r)&&r>=0?r:0},Fr=e=>{switch(e){case "Running":return "running";case "Paused":return "suspended";case "Not started":return "stopped";default:return "unknown"}},Z={provider:"firecracker",provisionWorkload:async(e,r)=>{let t=K(e);if(_(r.egressAllowlist,"firecracker"),Q(r.name,"workload name"),r.volume){if(r.volume.name==="rootfs")throw new d("invalid_request",'Firecracker secondary drive name cannot be "rootfs"',{provider:"firecracker"});if(Q(r.volume.name,"volume name"),!r.volume.hostPath)throw new d("invalid_request","Firecracker secondary drives require an explicit volume.hostPath backing file",{provider:"firecracker"})}let n=r.trackDirtyPages??false;if(await w(t,"/machine-config",{method:"PUT",body:{vcpu_count:r.vcpus,mem_size_mib:r.memoryMb,smt:false,track_dirty_pages:n}}),await w(t,"/boot-source",{method:"PUT",body:{kernel_image_path:r.kernelImagePath??Hr,boot_args:r.bootArgs??$r}}),await w(t,"/drives/rootfs",{method:"PUT",body:{drive_id:"rootfs",path_on_host:r.image,is_root_device:true,is_read_only:false}}),r.volume?.hostPath){let i=encodeURIComponent(r.volume.name);await w(t,`/drives/${i}`,{method:"PUT",body:{drive_id:r.volume.name,path_on_host:r.volume.hostPath,is_root_device:false,is_read_only:false}});}if(r.networkInterface){Q(r.networkInterface.ifaceId,"network interface id");let i=encodeURIComponent(r.networkInterface.ifaceId);await w(t,`/network-interfaces/${i}`,{method:"PUT",body:{iface_id:r.networkInterface.ifaceId,host_dev_name:r.networkInterface.hostDevName,...r.networkInterface.guestMac?{guest_mac:r.networkInterface.guestMac}:{}}});}await w(t,"/actions",{method:"PUT",body:{action_type:"InstanceStart"}});let o=await w(t,"/");return {provider:"firecracker",workloadId:Q(o.id||r.name,"workloadId"),name:r.name,region:r.region,memoryMb:r.memoryMb,vcpus:r.vcpus,snapshotPath:r.snapshotPath,memFilePath:r.memFilePath,metadata:{vmmVersion:o.vmm_version,trackDirtyPages:String(n)}}},suspendWorkload:async(e,r)=>{let t=K(e),n=Q(r.workloadId,"workloadId"),o=r.snapshotPath??`/var/lib/firecracker/snapshots/${n}.snap`,a=r.memFilePath??`/var/lib/firecracker/snapshots/${n}.mem`;return await w(t,"/vm",{method:"PATCH",body:{state:"Paused"}}),await w(t,"/snapshot/create",{method:"PUT",body:{snapshot_type:"Full",snapshot_path:o,mem_file_path:a}}),{...r,snapshotPath:o,memFilePath:a}},wakeWorkload:async(e,r)=>{let t=K(e),n=await w(t,"/");if(n.state==="Not started"&&r.snapshotPath&&r.memFilePath){let o=r.metadata?.trackDirtyPages==="true";await w(t,"/snapshot/load",{method:"PUT",body:{snapshot_path:r.snapshotPath,mem_backend:{backend_path:r.memFilePath,backend_type:"File"},track_dirty_pages:o,resume_vm:true}});}else n.state==="Paused"?await w(t,"/vm",{method:"PATCH",body:{state:"Resumed"}}):n.state==="Not started"&&await w(t,"/actions",{method:"PUT",body:{action_type:"InstanceStart"}});return r},fetchWorkloadStatus:async(e,r)=>{let t=K(e),n=await w(t,"/");return {provider:"firecracker",workloadId:n.id||r.workloadId,state:Fr(n.state),providerState:n.state,region:r.region,memoryMb:r.memoryMb,vcpus:r.vcpus,updatedAt:new Date().toISOString()}},fetchWorkloadUsage:async(e,r)=>{let t=await Z.fetchWorkloadStatus(e,r),n=new Date().toISOString();return {provider:"firecracker",workloadId:t.workloadId,memoryMb:r.memoryMb??0,vcpus:r.vcpus??0,activeSeconds:0,suspendedSeconds:0,rootfsGb:Lr(r.metadata?.rootfsGb),metered:false,windowStartIso:n,windowEndIso:n}},destroyWorkload:async(e,r)=>{let t=K(e);(await w(t,"/").catch(o=>{R(o);}))?.state==="Running"&&await w(t,"/actions",{method:"PUT",body:{action_type:"SendCtrlAltDel"}}).catch(R);}};var Ae="https://api.machines.dev/v1",h=async(e,r,t={},n=Ae)=>E(`${A(n)}${r}`,{method:t.method??"GET",token:e,body:t.body,timeoutMs:t.timeoutMs,provider:"fly"});var me=2048,Je=30,Xe=4e4,L=(e,r)=>{if(!e.token)throw new d("authentication_failed","Fly.io API token is required",{provider:"fly"});let t=e.appName??r;if(!t)throw new d("invalid_request","Fly.io appName is required",{provider:"fly"});return {token:e.token,appName:t}},Or=e=>{switch(e){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"}},qr=e=>{if(e===void 0)return 0;let r=Number(e);return Number.isFinite(r)&&r>=0?r:0},Gr=(e,r,t)=>{if(e.length===0)return {activeSeconds:0,suspendedSeconds:0,metered:false,windowStartMs:t,windowEndMs:t};let n=[...e].sort((s,c)=>s.timestamp-c.timestamp),o=0,a=0;for(let s=0;s<n.length;s+=1){let c=n[s],l=n[s+1];if(l){let u=Math.max(0,l.timestamp-c.timestamp);c.status==="started"?o+=u:c.status==="suspended"&&(a+=u);}else if(c.status===r){let u=Math.max(0,t-c.timestamp);r==="started"?o+=u:r==="suspended"&&(a+=u);}}let i=n[n.length-1].timestamp;return {activeSeconds:Math.round(o/1e3),suspendedSeconds:Math.round(a/1e3),metered:true,windowStartMs:n[0].timestamp,windowEndMs:Math.max(t,i)}},pe={provider:"fly",provisionWorkload:async(e,r)=>{let{token:t,appName:n}=L(e,r.labels?.["fly.app"]);if(_(r.egressAllowlist,"fly"),r.volume&&!r.volume.volumeId)throw new d("invalid_request","Fly.io volume mounts require volume.volumeId",{provider:"fly"});let o=encodeURIComponent(n),a=r.port?[{protocol:r.port.protocol??"tcp",internal_port:r.port.internalPort,autostart:false,autostop:"off",...r.port.publicHttps?{ports:[{port:443,handlers:["tls","http"]}]}:{}}]:void 0,i=r.healthcheckPath?{httpget:{type:"http",port:r.port?.internalPort??8080,method:"GET",path:r.healthcheckPath,interval:"15s",timeout:"5s"}}:void 0,s=await h(t,`/apps/${o}/machines`,{method:"POST",body:{name:r.name,...r.region?{region:r.region}:{},config:{image:r.image,...r.env?{env:r.env}:{},guest:{cpu_kind:r.cpuKind??"shared",cpus:r.vcpus,memory_mb:r.memoryMb},...r.volume?.volumeId?{mounts:[{volume:r.volume.volumeId,path:r.volume.mountPath}]}:{},auto_destroy:r.autoDestroy??false,...a?{services:a}:{},...i?{checks:i}:{},...r.labels?{metadata:r.labels}:{}}}},e.apiUrl),c=s.config?.guest?.memory_mb??r.memoryMb,l=s.config?.guest?.cpus??r.vcpus;return {provider:"fly",workloadId:s.id,name:s.name,region:s.region,appName:n,url:r.port?.publicHttps?`https://${n}.fly.dev`:void 0,memoryMb:c,vcpus:l,metadata:s.instance_id?{instanceId:s.instance_id}:void 0}},suspendWorkload:async(e,r)=>{let{token:t,appName:n}=L(e,r.appName),o=encodeURIComponent(n),a=encodeURIComponent(r.workloadId),i=r.memoryMb;if(i===void 0&&(i=(await h(t,`/apps/${o}/machines/${a}`,{},e.apiUrl)).config?.guest?.memory_mb),i!==void 0&&i>me)throw new d("invalid_request",`Fly.io Machines suspend requires memoryMb <= ${me} (got ${i} MB)`,{provider:"fly"});await h(t,`/apps/${o}/machines/${a}/suspend`,{method:"POST"},e.apiUrl);let s=new URLSearchParams({state:"suspended",timeout:String(Je)});return await h(t,`/apps/${o}/machines/${a}/wait?${s}`,{timeoutMs:Xe},e.apiUrl),{...r,appName:n,memoryMb:i}},wakeWorkload:async(e,r)=>{let{token:t,appName:n}=L(e,r.appName),o=encodeURIComponent(n),a=encodeURIComponent(r.workloadId);await h(t,`/apps/${o}/machines/${a}/start`,{method:"POST"},e.apiUrl);let i=new URLSearchParams({state:"started",timeout:String(Je)});return await h(t,`/apps/${o}/machines/${a}/wait?${i}`,{timeoutMs:Xe},e.apiUrl),{...r,appName:n}},fetchWorkloadStatus:async(e,r)=>{let{token:t,appName:n}=L(e,r.appName),o=encodeURIComponent(n),a=encodeURIComponent(r.workloadId),i=await h(t,`/apps/${o}/machines/${a}`,{},e.apiUrl);return {provider:"fly",workloadId:i.id,state:Or(i.state),providerState:i.state,region:i.region,url:r.url,memoryMb:i.config?.guest?.memory_mb??r.memoryMb,vcpus:i.config?.guest?.cpus??r.vcpus,updatedAt:i.updated_at}},fetchWorkloadUsage:async(e,r)=>{let{token:t,appName:n}=L(e,r.appName),o=encodeURIComponent(n),a=encodeURIComponent(r.workloadId),i=await h(t,`/apps/${o}/machines/${a}`,{},e.apiUrl),s=Date.now(),c=Gr(i.events??[],i.state,s);return {provider:"fly",workloadId:i.id,memoryMb:i.config?.guest?.memory_mb??r.memoryMb??0,vcpus:i.config?.guest?.cpus??r.vcpus??0,activeSeconds:c.activeSeconds,suspendedSeconds:c.suspendedSeconds,rootfsGb:qr(r.metadata?.rootfsGb),metered:c.metered,windowStartIso:new Date(c.windowStartMs).toISOString(),windowEndIso:new Date(c.windowEndMs).toISOString()}},destroyWorkload:async(e,r)=>{let{token:t,appName:n}=L(e,r.appName),o=encodeURIComponent(n),a=encodeURIComponent(r.workloadId);await h(t,`/apps/${o}/machines/${a}?force=true`,{method:"DELETE"},e.apiUrl).catch(R);}};var Ee="https://backboard.railway.com/graphql/v2",jr=e=>{if(typeof e=="string")switch(e.toUpperCase()){case "UNAUTHENTICATED":case "FORBIDDEN":case "UNAUTHORIZED":return "authentication_failed";case "NOT_FOUND":return "not_found";case "CONFLICT":return "conflict";case "TOO_MANY_REQUESTS":case "RATE_LIMITED":return "rate_limited";case "BAD_USER_INPUT":case "GRAPHQL_VALIDATION_FAILED":return "invalid_request";default:return}},Vr=e=>{let r=e.toLowerCase();return r.includes("not authorized")||r.includes("unauthorized")?"authentication_failed":r.includes("rate limit")||r.includes("too quickly")?"rate_limited":r.includes("not found")?"not_found":r.includes("already exists")||r.includes("conflict")?"conflict":r.includes("bad user input")||r.includes("invalid")?"invalid_request":"provider_unavailable"},m=async(e,r,t={},n=Ee)=>{let o=await E(A(n),{method:"POST",token:e,body:{query:r,variables:t},provider:"railway"});if(Array.isArray(o?.errors)&&o.errors.length>0){let a=o.errors.map(u=>typeof u?.message=="string"?u.message.trim():"").filter(u=>u.length>0),i=a.length>0?a.join("; "):"Railway GraphQL error",s=o.errors.map(u=>jr(u?.extensions?.code)).find(u=>u!==void 0),c=Vr(i),l=c==="rate_limited"||c==="authentication_failed"?c:s??c;throw new d(l,i,{provider:"railway"})}if(!o?.data||typeof o.data!="object")throw new d("provider_unavailable","Railway GraphQL response omitted data",{provider:"railway"});return o.data};var ye=e=>e?.edges.map(r=>r.node)??[],W=(e,r)=>{if(e==null)throw new d("not_found",`Railway ${r} not found`,{provider:"railway"});return e},J=async e=>{let r=[],t=new Set,n=null;do{let o=await e(n);r.push(...ye(o));let a=o.pageInfo?.hasNextPage?o.pageInfo.endCursor??null:null;if(a!==null){if(t.has(a))throw new d("provider_unavailable","Railway pagination cursor repeated",{provider:"railway"});t.add(a);}n=a;}while(n!==null);return r},ge=async(e,r)=>{let{apiToken:t}=await m(e,"query { apiToken { workspaces { id name } } }",{},r);if(!Array.isArray(t?.workspaces))throw new d("provider_unavailable","Railway apiToken response omitted workspaces",{provider:"railway"});return t.workspaces.map(({id:n,name:o})=>({id:n,name:o}))},X=async(e,r,t,n)=>{let o=new Set,a=null;do{let i=await m(e,"query($workspaceId: String, $after: String) { projects(workspaceId: $workspaceId, first: 100, after: $after) { edges { node { id name environments { edges { node { id name } } } } } pageInfo { hasNextPage endCursor } } }",{workspaceId:r,after:a},n),{projects:s}=i,c=ye(s).find(u=>u.name===t);if(c)return {id:c.id,name:c.name,environments:ye(c.environments)};let l=s.pageInfo?.hasNextPage?s.pageInfo.endCursor??null:null;if(l!==null){if(o.has(l))throw new d("provider_unavailable","Railway projects pagination cursor repeated",{provider:"railway"});o.add(l);}a=l;}while(a!==null)},We=async(e,r,t,n="production",o)=>{let{projectCreate:a}=await m(e,"mutation($input: ProjectCreateInput!) { projectCreate(input: $input) { id name environments { edges { node { id name } } } } }",{input:{name:t,workspaceId:r,defaultEnvironmentName:n}},o);return {id:a.id,name:a.name,environments:ye(a.environments)}},De=async(e,r,t)=>J(async n=>{let{project:o}=await m(e,"query($id: String!, $after: String) { project(id: $id) { environments(first: 100, after: $after) { edges { node { id name } } pageInfo { hasNextPage endCursor } } } }",{id:r,after:n},t);return W(o,`project ${r}`).environments}),F=async(e,r,t,n,o)=>{if(n?.projectId&&n?.environmentId)return {projectId:n.projectId,environmentId:n.environmentId};if(n?.projectId){let s=await De(e,n.projectId,o),c=s.find(l=>l.name==="production")??s[0];return {projectId:n.projectId,environmentId:p(c?.id,"Railway environmentId","railway")}}let a=await X(e,r,t,o)??await We(e,r,t,"production",o),i=a.environments.find(s=>s.name==="production")??a.environments[0];return {projectId:a.id,environmentId:p(i?.id,"Railway environmentId","railway")}},er=async(e,r,t,n)=>{let{environmentRename:o}=await m(e,"mutation($id: String!, $name: String!) { environmentRename(id: $id, input: { name: $name }) }",{id:r,name:t},n);return o},x=async(e,r,t,n,o)=>{let i=(await J(async c=>{let{project:l}=await m(e,"query($id: String!, $after: String) { project(id: $id) { services(first: 100, after: $after) { edges { node { id name } } pageInfo { hasNextPage endCursor } } } }",{id:r,after:c},o);return W(l,`project ${r}`).services})).find(c=>c.name===n);if(i)return i.id;let{serviceCreate:s}=await m(e,"mutation($input: ServiceCreateInput!) { serviceCreate(input: $input) { id } }",{input:{projectId:r,environmentId:t,name:n}},o);return s.id},rr=async(e,r,t,n)=>{let{serviceUpdate:o}=await m(e,"mutation($id: String!, $input: ServiceUpdateInput!) { serviceUpdate(id: $id, input: $input) { id name } }",{id:r,input:{name:t}},n);return o},M=async(e,r,t,n,o)=>{let{serviceInstanceUpdate:a}=await m(e,"mutation($serviceId: String!, $environmentId: String, $input: ServiceInstanceUpdateInput!) { serviceInstanceUpdate(serviceId: $serviceId, environmentId: $environmentId, input: $input) }",{serviceId:r,environmentId:t,input:n},o);if(a===false)throw new d("provider_unavailable",`Failed to update Railway service instance ${r}`,{provider:"railway"})},tr=async(e,r,t,n)=>{let{serviceInstance:o}=await m(e,"query($serviceId: String!, $environmentId: String!) { serviceInstance(serviceId: $serviceId, environmentId: $environmentId) { id source { repo } } }",{serviceId:r,environmentId:t},n);return !!W(o,`serviceInstance ${r}`).source?.repo},nr=async(e,r,t,n,o="main",a)=>{await M(e,r,t,{source:{repo:n}},a);let{service:i}=await m(e,"query($id: String!) { service(id: $id) { projectId } }",{id:r},a),s=W(i,`service ${r}`).projectId;(await J(async u=>{let{deploymentTriggers:v}=await m(e,"query($projectId: String!, $serviceId: String!, $environmentId: String!, $after: String) { deploymentTriggers(projectId: $projectId, serviceId: $serviceId, environmentId: $environmentId, first: 100, after: $after) { edges { node { id branch repository } } pageInfo { hasNextPage endCursor } } }",{projectId:s,serviceId:r,environmentId:t,after:u},a);return v})).some(u=>u.repository===n&&u.branch===o)||await m(e,"mutation($input: DeploymentTriggerCreateInput!) { deploymentTriggerCreate(input: $input) { id } }",{input:{projectId:s,environmentId:t,serviceId:r,provider:"github",repository:n,branch:o,checkSuites:false}},a);},or=async(e,r,t)=>J(async n=>{let{project:o}=await m(e,"query($id: String!, $after: String) { project(id: $id) { volumes(first: 100, after: $after) { edges { node { id name } } pageInfo { hasNextPage endCursor } } } }",{id:r,after:n},t);return W(o,`project ${r}`).volumes}),O=async(e,r,t,n,o,a)=>{(await J(async s=>{let{environment:c}=await m(e,"query($id: String!, $projectId: String, $after: String) { environment(id: $id, projectId: $projectId) { volumeInstances(first: 100, after: $after) { edges { node { serviceId mountPath } } pageInfo { hasNextPage endCursor } } } }",{id:t,projectId:r,after:s},a);return W(c,`environment ${t}`).volumeInstances})).some(s=>s.serviceId===n&&s.mountPath===o)||await m(e,"mutation($input: VolumeCreateInput!) { volumeCreate(input: $input) { id } }",{input:{projectId:r,environmentId:t,serviceId:n,mountPath:o}},a);},ar=async(e,r,t,n)=>{let{volumeUpdate:o}=await m(e,"mutation($volumeId: String!, $input: VolumeUpdateInput!) { volumeUpdate(volumeId: $volumeId, input: $input) { id name } }",{volumeId:r,input:{name:t}},n);return o},ve=async(e,r,t,n,o)=>{let{variables:a}=await m(e,"query($projectId: String!, $environmentId: String!, $serviceId: String) { variables(projectId: $projectId, environmentId: $environmentId, serviceId: $serviceId, unrendered: true) }",{projectId:r,environmentId:t,serviceId:n},o);return a},T=async(e,r,t,n,o,a={},i)=>{await m(e,"mutation($input: VariableCollectionUpsertInput!) { variableCollectionUpsert(input: $input) }",{input:{projectId:r,environmentId:t,serviceId:n,variables:o,skipDeploys:a.skipDeploys??true}},i);},S=async(e,r,t,n)=>{let{serviceInstance:o}=await m(e,"query($serviceId: String!, $environmentId: String!) { serviceInstance(serviceId: $serviceId, environmentId: $environmentId) { latestDeployment { id status } domains { serviceDomains { domain } } source { repo } } }",{serviceId:r,environmentId:t},n),a=W(o,`serviceInstance ${r}`);return {latestDeployment:a.latestDeployment,domains:a.domains.serviceDomains.map(i=>i.domain),sourceRepo:a.source?.repo}},D=async(e,r,t,n={},o)=>{let a=n.commitSha?"mutation($serviceId: String!, $environmentId: String!, $commitSha: String) { serviceInstanceDeployV2(serviceId: $serviceId, environmentId: $environmentId, commitSha: $commitSha) }":"mutation($serviceId: String!, $environmentId: String!) { serviceInstanceDeployV2(serviceId: $serviceId, environmentId: $environmentId) }",i=n.commitSha?{serviceId:r,environmentId:t,commitSha:n.commitSha}:{serviceId:r,environmentId:t},{serviceInstanceDeployV2:s}=await m(e,a,i,o);return p(s,"Railway deploymentId","railway")},ir=async(e,r,t,n={},o)=>{let{serviceInstanceDeploy:a}=await m(e,"mutation($serviceId: String!, $environmentId: String!, $latestCommit: Boolean!) { serviceInstanceDeploy(serviceId: $serviceId, environmentId: $environmentId, latestCommit: $latestCommit) }",{serviceId:r,environmentId:t,latestCommit:n.latestCommit??true},o);if(!a)throw new d("provider_unavailable",`Failed to deploy latest commit for Railway service ${r}`,{provider:"railway"})},fe=async(e,r,t)=>{let{deployment:n}=await m(e,"query($id: String!) { deployment(id: $id) { status } }",{id:r},t);return W(n,`deployment ${r}`).status},we=async(e,r,t)=>{let{deploymentStop:n}=await m(e,"mutation($id: String!) { deploymentStop(id: $id) }",{id:r},t);return n},q=async(e,r,t,n,o)=>{let i=(await S(e,r,t,o)).domains[0];if(i)return i;let{serviceDomainCreate:s}=await m(e,"mutation($input: ServiceDomainCreateInput!) { serviceDomainCreate(input: $input) { domain } }",{input:{serviceId:r,environmentId:t,...n!==void 0?{targetPort:n}:{}}},o);return s.domain},Ce=async(e,r,t)=>{let{project:n}=await m(e,"query($id: String!) { project(id: $id) { buckets { id name } } }",{id:r},t);return W(n,`project ${r}`).buckets??[]},Ue=async(e,r,t,n)=>{let{bucketCreate:o}=await m(e,"mutation($input: BucketCreateInput!) { bucketCreate(input: $input) { id name } }",{input:{projectId:r,name:t}},n);return {id:o.id,name:o.name}},sr=async(e,r,t,n)=>{let o=(await Ce(e,r,n)).find(a=>a.name===t);return o||Ue(e,r,t,n)},dr=async(e,r,t,n,o)=>{let{bucketS3Credentials:a}=await m(e,"query($bucketId: String!, $environmentId: String!, $projectId: String!) { bucketS3Credentials(bucketId: $bucketId, environmentId: $environmentId, projectId: $projectId) { accessKeyId bucketName endpoint region secretAccessKey urlStyle } }",{bucketId:r,environmentId:t,projectId:n},o);if(!a?.bucketName||!a?.accessKeyId)throw new d("provider_unavailable","Railway bucket credentials are not ready yet",{provider:"railway"});return {bucket:a.bucketName,accessKeyId:a.accessKeyId,secretAccessKey:a.secretAccessKey,region:a.region,endpoint:a.endpoint,urlStyle:a.urlStyle}},ke=async(e,r,t)=>{await m(e,"mutation($id: String!) { serviceDelete(id: $id) }",{id:r},t).catch(R);},Ie=async(e,r,t)=>{await m(e,"mutation($id: String!) { projectScheduleDelete(id: $id) }",{id:r},t).catch(R);};var ee="archive-postgres",xe="archive",Br="pgvector/pgvector:pg17",cr="/var/lib/postgresql/data",lr=new Set(["SUCCESS","SLEEPING"]),Yr=new Set(["FAILED","CRASHED","REMOVED","SKIPPED"]),zr=()=>{let e=crypto.getRandomValues(new Uint8Array(32));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")},ur=async(e,r,t)=>{let n=await S(e.token,t,r,e.apiUrl);return n.latestDeployment||await D(e.token,t,r,{},e.apiUrl),n},he={provider:"railway",fetchWorkspaces:ge,provisionDatabase:async e=>{let{projectId:r,environmentId:t}=await F(e.token,e.workspaceId,e.name,e.ids,e.apiUrl),n=e.ids.databaseServiceId??await x(e.token,r,t,ee,e.apiUrl);return await O(e.token,r,t,n,cr,e.apiUrl),(await ve(e.token,r,t,n,e.apiUrl)).POSTGRES_PASSWORD||await T(e.token,r,t,n,{POSTGRES_USER:P,POSTGRES_DB:P,POSTGRES_PASSWORD:zr(),PGDATA:`${cr}/pgdata`},{skipDeploys:true},e.apiUrl),await M(e.token,n,t,{source:{image:Br}},e.apiUrl),await ur(e,t,n),{projectId:r,environmentId:t,databaseServiceId:n}},fetchDatabaseReadiness:async e=>{let t=(await S(e.token,p(e.ids.databaseServiceId,"archive databaseServiceId","railway"),p(e.ids.environmentId,"archive environmentId","railway"),e.apiUrl)).latestDeployment?.status;if(t==="FAILED"||t==="CRASHED")throw new d("deploy_failed",`Railway database deployment ${t}`,{provider:"railway"});return t==="SUCCESS"},provisionService:async e=>{let r=p(e.ids.projectId,"archive projectId","railway"),t=p(e.ids.environmentId,"archive environmentId","railway"),n=e.ids.serviceId??await x(e.token,r,t,xe,e.apiUrl);await T(e.token,r,t,n,{ARCHIVE_SERVER_TOKEN:z(e),PORT:String(N),DATABASE_URL:`postgresql://${P}:\${{${ee}.POSTGRES_PASSWORD}}@\${{${ee}.RAILWAY_PRIVATE_DOMAIN}}:5432/${P}`},{skipDeploys:true},e.apiUrl),await M(e.token,n,t,{source:{image:`${b}:${e.imageVersion}`},healthcheckPath:"/health"},e.apiUrl);let o=await ur(e,t,n),a=o.domains[0]??await q(e.token,n,t,N,e.apiUrl);if(o.latestDeployment?.status==="FAILED"||o.latestDeployment?.status==="CRASHED")throw new d("deploy_failed","Railway archive service deployment failed",{provider:"railway"});return {ids:{...e.ids,serviceId:n},url:`https://${a}`}},fetchServiceReadiness:async e=>{let t=(await S(e.token,p(e.ids.serviceId,"archive serviceId","railway"),p(e.ids.environmentId,"archive environmentId","railway"),e.apiUrl)).latestDeployment?.status;if(t==="FAILED"||t==="CRASHED")throw new d("deploy_failed",`Railway archive service deployment ${t}`,{provider:"railway"});return !!(t&&lr.has(t))},fetchServiceFailureStatus:async e=>{let t=(await S(e.token,p(e.ids.serviceId,"archive serviceId","railway"),p(e.ids.environmentId,"archive environmentId","railway"),e.apiUrl)).latestDeployment?.status;return t==="FAILED"||t==="CRASHED"},deployImage:async e=>{let r=p(e.ids.environmentId,"archive environmentId","railway"),t=p(e.ids.serviceId,"archive serviceId","railway");await M(e.token,t,r,{source:{image:`${b}:${e.imageVersion}`}},e.apiUrl);let n=await D(e.token,t,r,{},e.apiUrl);return {...e.ids,deploymentId:n}},restoreImage:async e=>{await M(e.token,p(e.ids.serviceId,"archive serviceId","railway"),p(e.ids.environmentId,"archive environmentId","railway"),{source:{image:`${b}:${e.imageVersion}`}},e.apiUrl);},fetchImageDeployStatus:async e=>{let r=await fe(e.token,p(e.ids.deploymentId,"archive deploymentId","railway"),e.apiUrl);return lr.has(r)?"live":Yr.has(r)?"failed":"deploying"},destroyService:async e=>{let r=e.ids.projectId??(await X(e.token,e.workspaceId,e.name,e.apiUrl))?.id;r&&await Ie(e.token,r,e.apiUrl);}};var re=e=>{if(!e.token)throw new d("authentication_failed","Railway API token is required",{provider:"railway"});return e.token},Te=(e,r)=>p(r.environmentId??e.environmentId,"Railway environmentId","railway"),Kr=e=>{switch(e){case "SUCCESS":return "running";case "SLEEPING":return "suspended";case "BUILDING":case "DEPLOYING":case "INITIALIZING":case "WAITING":return "starting";case "REMOVING":return "stopping";case "REMOVED":case "STOPPED":case void 0:return "stopped";case "FAILED":case "CRASHED":return "failed";default:return "unknown"}},te={provider:"railway",provisionWorkload:async(e,r)=>{let t=re(e);_(r.egressAllowlist,"railway");let n=e.projectId,o=e.environmentId;if(!n||!o){if(!n&&!e.workspaceId)throw new d("invalid_request","Railway workload provisioning requires either (projectId + environmentId), projectId, or workspaceId",{provider:"railway"});let l=await F(t,e.workspaceId??"",r.name,{projectId:n,environmentId:o},e.apiUrl);n=l.projectId,o=l.environmentId;}let a=await x(t,n,o,r.name,e.apiUrl);r.volume&&await O(t,n,o,a,r.volume.mountPath,e.apiUrl);let i={...r.env??{},...r.port?{PORT:String(r.port.internalPort)}:{}};Object.keys(i).length>0&&await T(t,n,o,a,i,{skipDeploys:true},e.apiUrl),await M(t,a,o,{source:{image:r.image},...r.healthcheckPath?{healthcheckPath:r.healthcheckPath}:{}},e.apiUrl);let s=await D(t,a,o,{},e.apiUrl),c;return r.port?.publicHttps&&(c=`https://${await q(t,a,o,r.port.internalPort,e.apiUrl)}`),{provider:"railway",workloadId:a,name:r.name,url:c,memoryMb:r.memoryMb,vcpus:r.vcpus,projectId:n,environmentId:o,metadata:{deploymentId:s}}},suspendWorkload:async(e,r)=>{let t=re(e),n=Te(e,r),a=(await S(t,r.workloadId,n,e.apiUrl)).latestDeployment?.id??r.metadata?.deploymentId;return a&&await we(t,a,e.apiUrl),{...r,environmentId:n,metadata:a?{...r.metadata,deploymentId:a}:r.metadata}},wakeWorkload:async(e,r)=>{let t=re(e),n=Te(e,r),o=await D(t,r.workloadId,n,{},e.apiUrl);return {...r,environmentId:n,metadata:{...r.metadata,deploymentId:o}}},fetchWorkloadStatus:async(e,r)=>{let t=re(e),n=Te(e,r),o=await S(t,r.workloadId,n,e.apiUrl),a=o.latestDeployment?.status??"STOPPED",i=o.domains[0];return {provider:"railway",workloadId:r.workloadId,state:Kr(o.latestDeployment?.status),providerState:a,region:r.region,url:i?`https://${i}`:r.url,memoryMb:r.memoryMb,vcpus:r.vcpus,updatedAt:new Date().toISOString()}},fetchWorkloadUsage:async(e,r)=>{await te.fetchWorkloadStatus(e,r);let t=new Date().toISOString();return {provider:"railway",workloadId:r.workloadId,memoryMb:r.memoryMb??0,vcpus:r.vcpus??0,activeSeconds:0,suspendedSeconds:0,rootfsGb:0,metered:false,windowStartIso:t,windowEndIso:t}},destroyWorkload:async(e,r)=>{let t=re(e);await ke(t,r.workloadId,e.apiUrl);}};var ne=[{id:"starter",maxMemoryMb:512,monthlyUsd:7},{id:"standard",maxMemoryMb:2048,monthlyUsd:25},{id:"pro",maxMemoryMb:4096,monthlyUsd:85},{id:"pro_plus",maxMemoryMb:8192,monthlyUsd:175},{id:"pro_max",maxMemoryMb:16384,monthlyUsd:225},{id:"pro_ultra",maxMemoryMb:32768,monthlyUsd:450}],G=e=>{for(let r of ne)if(e<=r.maxMemoryMb)return r;return ne[ne.length-1]},C=new Set(["build_failed","update_failed","pre_deploy_failed","canceled"]),Re=new Set([...C,"deactivated"]);var He="https://api.render.com/v1",g=async(e,r,t={},n=He)=>E(`${A(n)}${r}`,{method:t.method??"GET",token:e,body:t.body,provider:"render"}),H=async(e,r,t)=>{await g(e,r,{method:"DELETE"},t).catch(R);};var j="oregon",Ne="basic_256mb",Le="starter",mr=100,gr=(e,r)=>new URLSearchParams({name:e,ownerId:r,limit:"20"}).toString(),$e=e=>`${e.name}-db`,pr=async e=>(await g(e.token,`/postgres?${gr($e(e),e.workspaceId)}`,{},e.apiUrl)).find(r=>r.postgres.name===$e(e))?.postgres,yr=async e=>(await g(e.token,`/services?${gr(e.name,e.workspaceId)}`,{},e.apiUrl)).find(r=>r.service.name===e.name)?.service,Fe=async(e,r)=>{let t=[],n=new Set,o;do{let a=new URLSearchParams({limit:String(mr),...o?{cursor:o}:{}}),i=await g(e,`/owners?${a}`,{},r);if(!Array.isArray(i))throw new d("provider_unavailable","Render owners response was not an array",{provider:"render"});t.push(...i.map(({owner:c})=>({id:c.id,name:c.name||c.email||c.id})));let s=i.length===mr?i.at(-1)?.cursor:void 0;if(s!==void 0){if(n.has(s))throw new d("provider_unavailable","Render owners pagination cursor repeated",{provider:"render"});n.add(s);}o=s;}while(o);return t},Se={provider:"render",fetchWorkspaces:Fe,provisionDatabase:async e=>{let r=(e.ids.databaseId?{id:e.ids.databaseId}:void 0)??await pr(e)??await g(e.token,"/postgres",{method:"POST",body:{name:$e(e),ownerId:e.workspaceId,plan:Ne,version:"17",region:j,databaseName:P,databaseUser:P}},e.apiUrl);return {...e.ids,databaseId:r.id}},fetchDatabaseReadiness:async e=>{let r=encodeURIComponent(p(e.ids.databaseId,"Render databaseId","render")),{status:t}=await g(e.token,`/postgres/${r}`,{},e.apiUrl);if(t==="unavailable"||t==="suspended")throw new d("deploy_failed",`Render Postgres status ${t}`,{provider:"render"});return t==="available"},provisionService:async e=>{let r=(e.ids.serviceId?await g(e.token,`/services/${encodeURIComponent(e.ids.serviceId)}`,{},e.apiUrl):void 0)??await yr(e),t;if(r)t=r;else {let n=encodeURIComponent(p(e.ids.databaseId,"Render databaseId","render"));t=(await g(e.token,"/services",{method:"POST",body:{type:"web_service",name:e.name,ownerId:e.workspaceId,image:{ownerId:e.workspaceId,imagePath:`${b}:${e.imageVersion}`},envVars:[{key:"ARCHIVE_SERVER_TOKEN",value:z(e)},{key:"PORT",value:String(N)},{key:"DATABASE_URL",value:(await g(e.token,`/postgres/${n}/connection-info`,{},e.apiUrl)).internalConnectionString}],serviceDetails:{runtime:"image",plan:Le,region:j,healthCheckPath:"/health"}}},e.apiUrl)).service;}return {ids:{...e.ids,serviceId:t.id},url:p(t.serviceDetails?.url,"Render service url","render")}},fetchServiceReadiness:async e=>{let r=encodeURIComponent(p(e.ids.serviceId,"Render serviceId","render")),[t]=await g(e.token,`/services/${r}/deploys?limit=1`,{},e.apiUrl);if(!t)return false;if(C.has(t.deploy.status))throw new d("deploy_failed",`Render deploy ${t.deploy.status}`,{provider:"render"});return t.deploy.status==="live"},fetchServiceFailureStatus:async e=>{let r=encodeURIComponent(p(e.ids.serviceId,"Render serviceId","render")),[t]=await g(e.token,`/services/${r}/deploys?limit=1`,{},e.apiUrl);return !!(t&&C.has(t.deploy.status))},deployImage:async e=>{let r=encodeURIComponent(p(e.ids.serviceId,"Render serviceId","render")),t=`${b}:${e.imageVersion}`;await g(e.token,`/services/${r}`,{method:"PATCH",body:{image:{ownerId:e.workspaceId,imagePath:t}}},e.apiUrl);let n=await g(e.token,`/services/${r}/deploys`,{method:"POST",body:{imageUrl:t}},e.apiUrl);return {...e.ids,deploymentId:p(n?.id,"Render deploymentId","render")}},restoreImage:async e=>{let r=encodeURIComponent(p(e.ids.serviceId,"Render serviceId","render"));await g(e.token,`/services/${r}`,{method:"PATCH",body:{image:{ownerId:e.workspaceId,imagePath:`${b}:${e.imageVersion}`}}},e.apiUrl);},fetchImageDeployStatus:async e=>{let r=encodeURIComponent(p(e.ids.serviceId,"Render serviceId","render")),t=encodeURIComponent(p(e.ids.deploymentId,"Render deploymentId","render")),{status:n}=await g(e.token,`/services/${r}/deploys/${t}`,{},e.apiUrl);return n==="live"?"live":Re.has(n)?"failed":"deploying"},destroyService:async e=>{let r=e.ids.serviceId??(await yr(e))?.id;r&&await H(e.token,`/services/${encodeURIComponent(r)}`,e.apiUrl);let t=e.ids.databaseId??(await pr(e))?.id;t&&await H(e.token,`/postgres/${encodeURIComponent(t)}`,e.apiUrl);}};var oe=e=>{if(!e.token)throw new d("authentication_failed","Render API token is required",{provider:"render"});return e.token},Qr=(e,r)=>e.suspended==="suspended"?"suspended":r?r==="live"?"running":C.has(r)?"failed":r==="deactivated"?"stopped":"starting":"provisioning",ae={provider:"render",provisionWorkload:async(e,r)=>{let t=oe(e);if(_(r.egressAllowlist,"render"),!e.workspaceId)throw new d("invalid_request","Render workload provisioning requires workspaceId",{provider:"render"});let n=Object.entries({...r.env??{},...r.port?{PORT:String(r.port.internalPort)}:{}}).map(([c,l])=>({key:c,value:l})),o=r.port?.publicHttps?"web_service":"background_worker",a=r.region??j,i=G(r.memoryMb).id,s=await g(t,"/services",{method:"POST",body:{type:o,name:r.name,ownerId:e.workspaceId,image:{ownerId:e.workspaceId,imagePath:r.image},envVars:n,serviceDetails:{runtime:"image",plan:i,region:a,...o==="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",workloadId:s.service.id,name:s.service.name,region:s.service.serviceDetails?.region??a,url:s.service.serviceDetails?.url,memoryMb:r.memoryMb,vcpus:r.vcpus,metadata:s.deployId?{deployId:s.deployId}:void 0}},suspendWorkload:async(e,r)=>{let t=oe(e);return await g(t,`/services/${encodeURIComponent(r.workloadId)}/suspend`,{method:"POST"},e.apiUrl),r},wakeWorkload:async(e,r)=>{let t=oe(e);return await g(t,`/services/${encodeURIComponent(r.workloadId)}/resume`,{method:"POST"},e.apiUrl),r},fetchWorkloadStatus:async(e,r)=>{let t=oe(e),n=encodeURIComponent(r.workloadId),o=await g(t,`/services/${n}`,{},e.apiUrl),i=(await g(t,`/services/${n}/deploys?limit=1`,{},e.apiUrl))[0]?.deploy.status;return {provider:"render",workloadId:o.id,state:Qr(o,i),providerState:o.suspended==="suspended"?"suspended":i??"provisioning",region:o.serviceDetails?.region??r.region,url:o.serviceDetails?.url??r.url,memoryMb:r.memoryMb,vcpus:r.vcpus,updatedAt:new Date().toISOString()}},fetchWorkloadUsage:async(e,r)=>{await ae.fetchWorkloadStatus(e,r);let t=new Date().toISOString();return {provider:"render",workloadId:r.workloadId,memoryMb:r.memoryMb??0,vcpus:r.vcpus??0,activeSeconds:0,suspendedSeconds:0,rootfsGb:0,metered:false,windowStartIso:t,windowEndIso:t}},destroyWorkload:async(e,r)=>{let t=oe(e);await H(t,`/services/${encodeURIComponent(r.workloadId)}`,e.apiUrl);}};var vr={railway:te,render:ae,fly:pe,firecracker:Z},fr={railway:he,render:Se},Zr=e=>vr[e],Jr=e=>fr[e];var ie=730,Xr=.65,et=.1,f={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}},se=e=>Math.round(e*1e4)/1e4,de=(e,r)=>{if(!Number.isFinite(e)||e<0)throw new d("invalid_request",`${r} must be a finite number >= 0 (got ${e})`)},wr=(e,r)=>{if(!Number.isFinite(e)||e<0||e>1)throw new d("invalid_request",`${r} must be a finite number in [0, 1] (got ${e})`)},kr=e=>{if(de(e.memoryMb,"memoryMb"),de(e.vcpus,"vcpus"),de(e.activeHoursPerMonth,"activeHoursPerMonth"),de(e.suspendedHoursPerMonth,"suspendedHoursPerMonth"),de(e.rootfsGb,"rootfsGb"),e.activeHoursPerMonth+e.suspendedHoursPerMonth>ie)throw new d("invalid_request",`activeHoursPerMonth + suspendedHoursPerMonth must be <= ${ie} (got ${e.activeHoursPerMonth+e.suspendedHoursPerMonth})`);let r=e.markupMultiplier??1;if(!Number.isFinite(r)||r<1)throw new d("invalid_request",`markupMultiplier must be a finite number >= 1 (got ${r})`);e.averageMemoryUtilization!==void 0&&wr(e.averageMemoryUtilization,"averageMemoryUtilization"),e.averageCpuUtilization!==void 0&&wr(e.averageCpuUtilization,"averageCpuUtilization");let t=e.memoryMb/1024,n=e.activeHoursPerMonth/ie,o=(e.activeHoursPerMonth+e.suspendedHoursPerMonth)/ie,a=e.suspendedHoursPerMonth/ie,i=0,s=0,c="";switch(e.provider){case "railway":{let y=e.averageMemoryUtilization??Xr,B=e.averageCpuUtilization??et;i=t*y*e.activeHoursPerMonth*f.railway.memoryUsdPerGbHour+e.vcpus*B*e.activeHoursPerMonth*f.railway.vcpuUsdPerHour,s=e.rootfsGb*o*f.railway.storageUsdPerGbMonth,c="usage-metered active RAM/vCPU per second + persistent volume storage";break}case "fly":{let y=e.cpuKind==="performance"?f.fly.performanceVcpuUsdPerMonth:f.fly.sharedVcpuUsdPerMonth;i=(e.vcpus*y+t*f.fly.memoryUsdPerGbMonth)*n,s=e.rootfsGb*a*f.fly.suspendedRootfsUsdPerGbMonth,c="provisioned Firecracker microVM per second while active + rootfs-only storage while suspended";break}case "render":{let y=G(e.memoryMb);i=y.monthlyUsd*n,s=e.rootfsGb*o*f.render.diskUsdPerGbMonth,c=`prorated fixed Render ${y.id} tier while unsuspended + persistent disk`;break}case "firecracker":{i=(t*f.firecracker.amortizedMemoryUsdPerGbMonth+e.vcpus*f.firecracker.amortizedVcpuUsdPerMonth)*n,s=(e.rootfsGb+t)*a*f.firecracker.snapshotStorageUsdPerGbMonth,c="amortized dedicated bare-metal host capacity while active + NVMe snapshot storage while suspended";break}case "aws":{i=e.vcpus*e.activeHoursPerMonth*f.aws.fargateArmVcpuUsdPerHour+t*e.activeHoursPerMonth*f.aws.fargateArmMemoryUsdPerGbHour,s=e.rootfsGb*o*f.aws.storageUsdPerGbMonth,c="AWS Fargate ARM provisioned vCPU/GB-hour + EBS/snapshot storage";break}case "gcp":{i=e.vcpus*e.activeHoursPerMonth*f.gcp.vcpuUsdPerHour+t*e.activeHoursPerMonth*f.gcp.memoryUsdPerGbHour,s=e.rootfsGb*o*f.gcp.storageUsdPerGbMonth,c="GCP provisioned vCPU/GB-hour + persistent storage";break}case "azure":{i=e.vcpus*e.activeHoursPerMonth*f.azure.vcpuUsdPerHour+t*e.activeHoursPerMonth*f.azure.memoryUsdPerGbHour,s=e.rootfsGb*o*f.azure.storageUsdPerGbMonth,c="Azure Container Apps provisioned vCPU/GB-hour + storage";break}}let l=se(i),u=se(s),v=se(l+u),k=se(v*r),I=se(k-v);return {provider:e.provider,activeComputeUsd:l,suspendedStorageUsd:u,rawMonthlyCostUsd:v,markupMultiplier:r,markedUpMonthlyCostUsd:k,marginUsd:I,pricingBasis:c}};var Me=(e,r={})=>{switch(e){case "warm-interactive":return {workloadClass:e,idleSuspendMs:48e4,idleStopMs:108e5,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:864e5,maxSuspendedMs:12096e5,softMemoryRecycleMb:1536,hardMemoryCapMb:2048,requireArchiveFlushBeforeWindDown:false,workingHoursPrewarm:r.workingHoursPrewarm,idleAction:"suspend"};case "warm-pool":return {workloadClass:e,idleSuspendMs:r.warmRetentionMode==="extended"?36e5:3e5,idleStopMs:108e5,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:864e5,maxSuspendedMs:6048e5,softMemoryRecycleMb:1536,hardMemoryCapMb:2048,requireArchiveFlushBeforeWindDown:false,workingHoursPrewarm:r.workingHoursPrewarm,idleAction:"suspend"};case "batch-worker":return {workloadClass: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 {workloadClass: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 {workloadClass:e,idleSuspendMs:null,idleStopMs:null,drainGraceMs:6e4,pendingApprovalGraceMs:0,maxLifetimeMs:null,maxSuspendedMs:null,softMemoryRecycleMb:null,hardMemoryCapMb:null,requireArchiveFlushBeforeWindDown:false,idleAction:"keep_warm"}}};var rt=15e3,Ir=3e4,tt=1e4,nt=3e5,qe=36e5,hr=24*qe,ce=(e,r)=>{if(!Number.isFinite(e))throw new d("invalid_request",`${r} must be a finite number (got ${e})`)},le=(e,r)=>{if(!Number.isFinite(e)||e<0)throw new d("invalid_request",`${r} must be a finite number >= 0 (got ${e})`)},Oe=(e,r)=>{if(!Number.isInteger(e)||e<0)throw new d("invalid_request",`${r} must be an integer >= 0 (got ${e})`)},V=(e,r)=>{if(e!=null&&(!Number.isFinite(e)||e<=0))throw new d("invalid_request",`${r} must be a finite number > 0 (got ${e})`)},ot=e=>{if(ce(e.timezoneOffsetMinutes,"workingHoursPrewarm.timezoneOffsetMinutes"),!Number.isFinite(e.startHour)||e.startHour<0||e.startHour>=24)throw new d("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 d("invalid_request",`workingHoursPrewarm.endHour must be in [0, 24] (got ${e.endHour})`);le(e.prewarmLeadMs,"workingHoursPrewarm.prewarmLeadMs");},at=(e,r,t)=>{ce(r,"nowMs"),ce(e.createdAtMs,"snapshot.createdAtMs"),ce(e.lastActivityAtMs,"snapshot.lastActivityAtMs"),ce(e.stateEnteredAtMs,"snapshot.stateEnteredAtMs"),Oe(e.inFlightTurns,"snapshot.inFlightTurns"),Oe(e.activeBackgroundShells,"snapshot.activeBackgroundShells"),e.pendingApprovals!==void 0&&Oe(e.pendingApprovals,"snapshot.pendingApprovals"),V(e.provisionedMemoryMb,"snapshot.provisionedMemoryMb"),V(e.rssMemoryMb,"snapshot.rssMemoryMb"),t.idleSuspendMs!==null&&le(t.idleSuspendMs,"policy.idleSuspendMs"),t.idleStopMs!==null&&le(t.idleStopMs,"policy.idleStopMs"),le(t.drainGraceMs,"policy.drainGraceMs"),le(t.pendingApprovalGraceMs,"policy.pendingApprovalGraceMs"),t.maxLifetimeMs!==null&&V(t.maxLifetimeMs,"policy.maxLifetimeMs"),t.maxSuspendedMs!==null&&V(t.maxSuspendedMs,"policy.maxSuspendedMs"),V(t.softMemoryRecycleMb,"policy.softMemoryRecycleMb"),V(t.hardMemoryCapMb,"policy.hardMemoryCapMb"),t.workingHoursPrewarm&&ot(t.workingHoursPrewarm);},Sr=(e,r,t)=>{let n=r.timezoneOffsetMinutes*6e4,o=new Date(e+n+t*hr),a=o.getUTCDay();if(r.weekdaysOnly&&(a===0||a===6))return null;let i=Date.UTC(o.getUTCFullYear(),o.getUTCMonth(),o.getUTCDate())-n,s=i+r.startHour*qe,c=r.endHour<=r.startHour,l=i+r.endHour*qe+(c?hr:0);return {prewarmStartMs:s-r.prewarmLeadMs,windowStartMs:s,windowEndMs:l}},Rr=(e,r)=>{for(let t of [-1,0,1]){let n=Sr(e,r,t);if(n&&e>=n.prewarmStartMs&&e<n.windowEndMs)return n}return null},it=(e,r)=>{let t=null;for(let n=0;n<=8;n+=1){let o=Sr(e,r,n);o&&o.prewarmStartMs>e&&(t=t===null?o.prewarmStartMs:Math.min(t,o.prewarmStartMs));}return t},$=(...e)=>{let r=null;for(let t of e)t!=null&&(r=r===null?t:Math.min(r,t));return r},Mr=(e,r,t=Me(e.workloadClass,{warmRetentionMode:e.warmRetentionMode}))=>{at(e,r,t);let n=be(e.provider),o=e.inFlightTurns>0||e.activeBackgroundShells>0,a=(e.pendingApprovals??0)>0,i=Math.max(0,r-e.createdAtMs),s=t.maxLifetimeMs!==null&&i>=t.maxLifetimeMs,c=t.maxLifetimeMs!==null?e.createdAtMs+t.maxLifetimeMs:null;if(e.state==="destroyed")return {action:"none",reason:"workload_already_destroyed",nextCheckAtMs:null};if(e.state==="failed"||e.state==="orphaned")return {action:"terminate",reason:`reap_${e.state}_workload`,nextCheckAtMs:null};if(e.state==="provisioning"||e.state==="booting"||e.state==="suspending"||e.state==="terminating")return {action:"none",reason:`workload_${e.state}`,nextCheckAtMs:r+rt};if(e.state==="suspended"){let v=Math.max(0,r-e.stateEnteredAtMs);if(t.maxSuspendedMs!==null&&v>=t.maxSuspendedMs)return {action:"terminate",reason:"suspended_retention_expired",nextCheckAtMs:null};if(t.workingHoursPrewarm&&Rr(r,t.workingHoursPrewarm))return {action:"prewarm",reason:"working_hours_prewarm_window",nextCheckAtMs:null};let k=t.maxSuspendedMs!==null?e.stateEnteredAtMs+t.maxSuspendedMs:null,I=t.workingHoursPrewarm?it(r,t.workingHoursPrewarm):null;return {action:"none",reason:"suspended_within_retention",nextCheckAtMs:$(k,I,r+nt)}}if(e.state==="draining"){let v=Math.max(0,r-e.stateEnteredAtMs),k=e.stateEnteredAtMs+t.drainGraceMs,I=Math.max(0,r-e.lastActivityAtMs);if(o)return s?v<t.drainGraceMs?{action:"none",reason:"waiting_for_in_flight_work_to_drain",nextCheckAtMs:k}:{action:"terminate",reason:"max_lifetime_exceeded_with_active_work",nextCheckAtMs:null}:{action:"none",reason:"active_work_blocks_idle_drain",nextCheckAtMs:$(c,r+Ir)};if(a&&!s&&t.pendingApprovalGraceMs>0&&I<t.pendingApprovalGraceMs)return {action:"none",reason:"waiting_for_pending_approval",nextCheckAtMs:$(c,e.lastActivityAtMs+t.pendingApprovalGraceMs)};if(t.requireArchiveFlushBeforeWindDown&&!e.archiveFlushed)return !s||v<t.drainGraceMs?{action:"none",reason:"waiting_for_archive_flush",nextCheckAtMs:r+tt}:{action:"terminate",reason:"max_lifetime_exceeded_without_archive_flush",nextCheckAtMs:null};if(s)return {action:"terminate",reason:"max_lifetime_reached_after_drain",nextCheckAtMs:null};if(t.idleAction==="terminate")return {action:"terminate",reason:"drain_complete_ready_to_terminate",nextCheckAtMs:null};let y=e.provisionedMemoryMb??e.rssMemoryMb;return n.supportsSuspend&&n.suspendMaxMemoryMb!==void 0&&y!==void 0&&y>n.suspendMaxMemoryMb?t.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(s)return o||t.requireArchiveFlushBeforeWindDown&&!e.archiveFlushed?{action:"drain",reason:"max_lifetime_reached_draining",nextCheckAtMs:r+t.drainGraceMs}:{action:"terminate",reason:"max_lifetime_reached",nextCheckAtMs:null};if(t.hardMemoryCapMb!==null&&e.rssMemoryMb!==void 0&&e.rssMemoryMb>(n.suspendMaxMemoryMb!==void 0?Math.min(t.hardMemoryCapMb,n.suspendMaxMemoryMb):t.hardMemoryCapMb))return {action:"recycle",reason:"rss_exceeds_hard_cap",nextCheckAtMs:null};if(t.softMemoryRecycleMb!==null&&e.rssMemoryMb!==void 0&&e.rssMemoryMb>=t.softMemoryRecycleMb&&!o)return {action:"recycle",reason:"rss_exceeds_soft_recycle_threshold",nextCheckAtMs:null};if(e.pinnedWarm||t.idleAction==="keep_warm")return {action:"none",reason:"workload_pinned_warm",nextCheckAtMs:c};if(t.workingHoursPrewarm){let v=Rr(r,t.workingHoursPrewarm);if(v)return {action:"none",reason:"within_working_hours_window",nextCheckAtMs:$(c,v.windowEndMs)}}if(o)return {action:"none",reason:"active_work_in_progress",nextCheckAtMs:$(c,r+Ir)};let l=n.supportsSuspend?t.idleSuspendMs:t.idleStopMs;if(l===null)return {action:"none",reason:"no_idle_timeout_configured",nextCheckAtMs:c};let u=Math.max(0,r-e.lastActivityAtMs);if(a&&t.pendingApprovalGraceMs>0){let v=Math.max(l,t.pendingApprovalGraceMs);if(u<v)return {action:"none",reason:"waiting_for_pending_approval",nextCheckAtMs:$(c,e.lastActivityAtMs+v)}}return u>=l?{action:"drain",reason:"idle_timeout_reached",nextCheckAtMs:r+t.drainGraceMs}:{action:"none",reason:"within_idle_window",nextCheckAtMs:$(c,e.lastActivityAtMs+l)}};var _r=["provisioning","booting","warm","active","draining","suspending","suspended","terminating","destroyed","failed","orphaned"],br=["warm-interactive","warm-pool","batch-worker","ephemeral-session","always-on"];var st=1e3,Pr=(e,r)=>{let t=(r.priority??0)-(e.priority??0);if(t!==0)return t;let n=e.requestedAtMs-r.requestedAtMs;return n!==0?n:e.workloadId<r.workloadId?-1:e.workloadId>r.workloadId?1:0},dt=e=>{let r=new Map;for(let t of e){if(!t.workloadId)throw new d("invalid_request","StaggeredWakeRequest.workloadId must be non-empty");if(!Number.isFinite(t.requestedAtMs))throw new d("invalid_request",`requestedAtMs must be finite (got ${t.requestedAtMs})`);if(t.priority!==void 0&&!Number.isFinite(t.priority))throw new d("invalid_request",`priority must be finite (got ${t.priority})`);let n=r.get(t.workloadId);(!n||Pr(t,n)<0)&&r.set(t.workloadId,t);}return [...r.values()]},Ar=(e,r,t)=>{if(!Number.isFinite(r))throw new d("invalid_request",`nowMs must be finite (got ${r})`);if(!Number.isInteger(t.maxConcurrentWakes)||t.maxConcurrentWakes<1)throw new d("invalid_request",`maxConcurrentWakes must be an integer >= 1 (got ${t.maxConcurrentWakes})`);if(!Number.isFinite(t.minSpacingMs)||t.minSpacingMs<0)throw new d("invalid_request",`minSpacingMs must be a finite number >= 0 (got ${t.minSpacingMs})`);if(t.inFlightWakeCount!==void 0&&(!Number.isInteger(t.inFlightWakeCount)||t.inFlightWakeCount<0))throw new d("invalid_request",`inFlightWakeCount must be an integer >= 0 (got ${t.inFlightWakeCount})`);if(t.lastWakeLaunchedAtMs!==void 0&&t.lastWakeLaunchedAtMs!==null&&!Number.isFinite(t.lastWakeLaunchedAtMs))throw new d("invalid_request",`lastWakeLaunchedAtMs must be finite or null (got ${t.lastWakeLaunchedAtMs})`);let n=dt(e).sort(Pr),o=t.inFlightWakeCount??0,a=Math.max(0,t.maxConcurrentWakes-o),i=[],s=[],c=t.minSpacingMs>0?t.minSpacingMs:st,l=t.lastWakeLaunchedAtMs!==null&&t.lastWakeLaunchedAtMs!==void 0?Math.max(r,t.lastWakeLaunchedAtMs+t.minSpacingMs):r,u=0;for(let v of n){if(u>=a){let k=Math.max(l,r+c);s.push({request:v,earliestLaunchAtMs:k,reason:"concurrency_limit"}),l=k+c;continue}if(l>r){s.push({request:v,earliestLaunchAtMs:l,reason:"spacing_interval"}),u+=1,l+=t.minSpacingMs;continue}i.push(v),u+=1,t.minSpacingMs>0&&(l=r+t.minSpacingMs);}return {launchNow:i,defer:s}};
2
+ exports.ARCHIVE_DATABASE=P;exports.ARCHIVE_HOSTING_DRIVERS=fr;exports.ARCHIVE_HOSTING_PROVIDERS=Ze;exports.ARCHIVE_IMAGE=b;exports.ARCHIVE_PORT=N;exports.FIRECRACKER_DEFAULT_BASE_URL=Pe;exports.FLY_MACHINES_API_URL=Ae;exports.FLY_SUSPEND_MAX_MEMORY_MB=me;exports.HOSTING_PRICING_RATES=f;exports.IMPLEMENTED_INFRA_PROVIDERS=Qe;exports.INFRA_PROVIDERS=_e;exports.INFRA_REQUEST_TIMEOUT_MS=Ve;exports.InfraError=d;exports.PLANNED_INFRA_PROVIDERS=Cr;exports.RAILWAY_API_URL=Ee;exports.RAILWAY_ARCHIVE_SERVICE=xe;exports.RAILWAY_DATABASE_SERVICE=ee;exports.RENDER_API_URL=He;exports.RENDER_DATABASE_PLAN=Ne;exports.RENDER_ENDED_DEPLOY_STATUSES=Re;exports.RENDER_FAILED_DEPLOY_STATUSES=C;exports.RENDER_PLAN_TIERS=ne;exports.RENDER_REGION=j;exports.RENDER_SERVICE_PLAN=Le;exports.WORKLOAD_CLASSES=br;exports.WORKLOAD_DRIVERS=vr;exports.WORKLOAD_LIFECYCLE_STATES=_r;exports.archiveHostingDriverForProvider=Jr;exports.archiveTokenOrThrow=z;exports.assertNoEgressAllowlist=_;exports.connectRailwayServiceToGitHub=nr;exports.createRailwayBucket=Ue;exports.createRailwayProject=We;exports.defaultWorkloadLifecyclePolicy=Me;exports.deleteRailwayService=ke;exports.deleteRenderResource=H;exports.deployRailwayServiceInstance=D;exports.deployRailwayServiceLatestCommit=ir;exports.ensureRailwayBucket=sr;exports.ensureRailwayProject=F;exports.ensureRailwayService=x;exports.ensureRailwayServiceDomain=q;exports.ensureRailwayVolume=O;exports.evaluateWorkloadLifecycle=Mr;exports.fetchRailwayBucketCredentials=dr;exports.fetchRailwayDeploymentStatus=fe;exports.fetchRailwayProjectBuckets=Ce;exports.fetchRailwayProjectByName=X;exports.fetchRailwayProjectEnvironments=De;exports.fetchRailwayProjectVolumes=or;exports.fetchRailwayServiceGitHubConnectionStatus=tr;exports.fetchRailwayServiceInstance=S;exports.fetchRailwayServiceVariables=ve;exports.fetchRailwayWorkspaces=ge;exports.fetchRenderOwners=Fe;exports.firecrackerWorkloadDriver=Z;exports.flyWorkloadDriver=pe;exports.ignoreNotFound=R;exports.infraErrorForStatus=ue;exports.infraProviderDescriptor=be;exports.isArchiveHostingProvider=Tr;exports.isImplementedInfraProvider=xr;exports.isInfraError=Ge;exports.isInfraProvider=Ur;exports.planStaggeredWakes=Ar;exports.projectHostingMonthlyCost=kr;exports.railwayArchiveDriver=he;exports.railwayWorkloadDriver=te;exports.renameRailwayEnvironment=er;exports.renameRailwayService=rr;exports.renameRailwayVolume=ar;exports.renderArchiveDriver=Se;exports.renderPlanForMemoryMb=G;exports.renderWorkloadDriver=ae;exports.requireNonEmpty=p;exports.scheduleRailwayProjectDelete=Ie;exports.sendFirecrackerRequest=w;exports.sendFlyRequest=h;exports.sendInfraRequest=E;exports.sendRailwayGraphql=m;exports.sendRenderRequest=g;exports.sendUnixSocketHttpRequest=Ke;exports.stopRailwayDeployment=we;exports.stripTrailingSlash=A;exports.updateRailwayServiceInstance=M;exports.upsertRailwayServiceVariables=T;exports.workloadDriverForProvider=Zr;//# sourceMappingURL=index.cjs.map
3
+ //# sourceMappingURL=index.cjs.map