@shipstatic/ship 2.0.0-beta.0 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../node_modules/.pnpm/@shipstatic+types@2.2.0/node_modules/@shipstatic/types/dist/index.js","../src/shared/lib/md5.ts","../src/shared/lib/env.ts","../src/shared/lib/junk.ts","../src/shared/lib/path.ts","../src/shared/lib/deploy-paths.ts","../src/shared/lib/file-validation.ts","../src/shared/lib/security.ts","../src/node/core/node-files.ts","../src/node/cli/index.ts","../src/node/cli/utils.ts","../src/node/cli/formatters.ts","../src/node/cli/completion.ts","../src/node/cli/config.ts","../src/shared/base-ship.ts","../src/shared/api/http.ts","../src/shared/events.ts","../src/shared/lib/validation.ts","../src/shared/resources.ts","../src/shared/core/config.ts","../src/shared/lib/spa.ts","../src/node/index.ts","../src/node/core/config.ts","../src/shared/core/credential-schema.ts","../src/node/core/deploy-body.ts","../src/node/cli/shiprc.ts","../src/node/cli/create-client.ts","../src/node/cli/error-handling.ts"],"sourcesContent":["/**\n * @file Shared TypeScript types, constants, and utilities for the ShipStatic platform.\n * This package is the single source of truth for all shared data structures.\n */\n// =============================================================================\n// I. CORE ENTITIES\n// =============================================================================\n/**\n * Deployment status constants\n */\nexport const DeploymentStatus = {\n PENDING: 'pending',\n SUCCESS: 'success',\n FAILED: 'failed',\n DELETING: 'deleting'\n};\n// =============================================================================\n// DOMAIN TYPES\n// =============================================================================\n/**\n * Domain status constants\n *\n * - PENDING: DNS not configured\n * - PARTIAL: DNS partially configured\n * - SUCCESS: DNS fully verified\n * - PAUSED: Domain paused due to plan enforcement (billing)\n */\nexport const DomainStatus = {\n PENDING: 'pending',\n PARTIAL: 'partial',\n SUCCESS: 'success',\n PAUSED: 'paused'\n};\n// =============================================================================\n// ACCOUNT TYPES\n// =============================================================================\n/**\n * Account plan constants\n */\nexport const AccountPlan = {\n FREE: 'free',\n STANDARD: 'standard',\n SPONSORED: 'sponsored',\n ENTERPRISE: 'enterprise',\n SUSPENDED: 'suspended',\n TERMINATING: 'terminating',\n TERMINATED: 'terminated'\n};\n// =============================================================================\n// ERROR SYSTEM\n// =============================================================================\n/**\n * All possible error types in the ShipStatic platform.\n *\n * Developer-friendly key names map to stable wire-format string values.\n * Both the value and the type are exported under the same name so callers\n * can use `ErrorType.Validation` (value comparison) and `: ErrorType` (type\n * annotation) without ceremony — matching the pattern other status objects\n * (`DeploymentStatus`, `DomainStatus`, `AccountPlan`, `AuthMethod`) follow.\n */\nexport const ErrorType = {\n /** Validation failed (400). Input shape is wrong. */\n Validation: 'validation_failed',\n /** Resource not found (404). */\n NotFound: 'not_found',\n /** Authenticated but not allowed (403). User lacks permission for this action. */\n Forbidden: 'forbidden',\n /** Rate limit exceeded (429). */\n RateLimit: 'rate_limit_exceeded',\n /** Authentication required or failed (401). Missing/invalid credentials. */\n Authentication: 'authentication_failed',\n /** Business rule violation. Catch-all for 4xx state-rule errors that aren't more specific. */\n Business: 'business_logic_error',\n /** API server error (500). Generic server-side fault. */\n Api: 'internal_server_error',\n /** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */\n Network: 'network_error',\n /** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */\n Cancelled: 'operation_cancelled',\n /** File operation error. Client-side only — set by SDK during local file processing; never produced server-side. */\n File: 'file_error',\n /** Configuration error. Client-side only — set by SDK during config parsing/validation; never produced server-side. */\n Config: 'config_error',\n};\n/**\n * Error types that originate exclusively on the client (HTTP clients, SDK\n * file processing, local config parsing). These never appear on the wire\n * from the server, so `fromHttpResponse` will not trust them even if a\n * misbehaving server claims one in `body.error`.\n */\nconst CLIENT_ONLY_ERROR_TYPES = new Set([\n ErrorType.Network,\n ErrorType.Cancelled,\n ErrorType.File,\n ErrorType.Config,\n]);\n/**\n * Categorizes error types for the `isClientError` / `isNetworkError` /\n * `isAuthError` helpers. Each `Set` is typed against the wider `ErrorType`\n * union so `.has(error.type)` accepts any value from the union.\n */\nconst ERROR_CATEGORIES = {\n client: new Set([ErrorType.Business, ErrorType.Config, ErrorType.File, ErrorType.Forbidden, ErrorType.Validation]),\n network: new Set([ErrorType.Network]),\n auth: new Set([ErrorType.Authentication]),\n};\n/**\n * Error types the server can legitimately produce on the wire. Used by\n * `ShipError.fromHttpResponse` to validate the body's `error` field before\n * trusting it as `ShipError.type`. Derived by exclusion from\n * `CLIENT_ONLY_ERROR_TYPES` so adding a new server-producible type to\n * `ErrorType` is automatically picked up.\n */\nconst SERVER_PRODUCIBLE_ERROR_TYPES = new Set(Object.values(ErrorType).filter(t => !CLIENT_ONLY_ERROR_TYPES.has(t)));\n/**\n * Simple unified error class for both API and SDK\n */\nexport class ShipError extends Error {\n type;\n status;\n details;\n constructor(type, message, status, details) {\n super(message);\n this.type = type;\n this.status = status;\n this.details = details;\n this.name = 'ShipError';\n }\n /** Convert to wire format */\n toResponse() {\n // Strip authentication details when they carry an `internal` telemetry\n // tag (see `ShipError.authentication` JSDoc) — these are server-side\n // diagnostics like 'session_invalid' that must not leak to clients.\n const authDetails = this.details;\n const details = this.type === ErrorType.Authentication && authDetails?.internal\n ? undefined\n : this.details;\n return {\n error: this.type,\n message: this.message,\n status: this.status,\n details\n };\n }\n /**\n * Construct a `ShipError` from an HTTP error response.\n *\n * Best-effort body parse for `{ message, error?, details? }`. Message\n * resolution: `body.message` → `body.error` → `\"<operationName> failed with\n * status <N>\"`.\n *\n * Type resolution: trusts `body.error` when it's a known server-producible\n * `ErrorType` (preserves the wire's intent — server's\n * `ShipError.validation(...)` round-trips back to `ErrorType.Validation`\n * on the client). Falls back to status-derived (401 → Authentication,\n * 403 → Forbidden, 429 → RateLimit, else → Api) for non-API responses\n * (CDN errors, intermediaries) or malformed bodies. Client-only types\n * (`Network`, `Cancelled`, `File`, `Config`) are filtered out of the\n * trusted set — a misbehaving server claiming one of those is ignored.\n *\n * `operationName` (e.g. `\"Get account\"`) is used to compose the fallback\n * message. Defaults to `\"Request\"`. Same convention as `fromFetchError`.\n *\n * Async because it reads the response body. Returns rather than throws so\n * callers can compose; most will `throw await ShipError.fromHttpResponse(...)`.\n */\n static async fromHttpResponse(response, operationName) {\n let message;\n let details;\n let bodyType;\n try {\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n const json = await response.json();\n if (json && typeof json === 'object') {\n const obj = json;\n if (typeof obj.message === 'string')\n message = obj.message;\n else if (typeof obj.error === 'string')\n message = obj.error;\n details = obj.details;\n if (typeof obj.error === 'string' && SERVER_PRODUCIBLE_ERROR_TYPES.has(obj.error)) {\n bodyType = obj.error;\n }\n }\n }\n else {\n const text = await response.text();\n if (text)\n message = text;\n }\n }\n catch {\n // Body unreadable; fall through to operationName-derived message.\n }\n message = message || `${operationName || 'Request'} failed with status ${response.status}`;\n const type = bodyType ?? (response.status === 401 ? ErrorType.Authentication :\n response.status === 403 ? ErrorType.Forbidden :\n response.status === 429 ? ErrorType.RateLimit :\n ErrorType.Api);\n return new ShipError(type, message, response.status, details);\n }\n /**\n * Construct a `ShipError` from an error caught around a `fetch()` call.\n *\n * The mirror of `fromHttpResponse` for the *other* side of the HTTP error\n * story — the network layer failing (offline, CORS, abort) rather than the\n * server returning a non-OK response.\n *\n * Routing:\n * - Already a `ShipError` → returned as-is (caller's intent preserved)\n * - `AbortError` → `ShipError.cancelled(...)`\n * - `TypeError` whose message mentions \"fetch\" → `ShipError.network(...)`\n * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)\n * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`\n *\n * The optional `operationName` is composed into the message for context:\n * `\"Get account was cancelled\"`, `\"Get account failed: ...\"`. Defaults to\n * `\"Request\"` when omitted.\n */\n static fromFetchError(cause, operationName) {\n if (isShipError(cause))\n return cause;\n const op = operationName || 'Request';\n if (cause instanceof Error) {\n if (cause.name === 'AbortError') {\n return ShipError.cancelled(`${op} was cancelled`);\n }\n if (cause instanceof TypeError && cause.message.includes('fetch')) {\n return ShipError.network(`${op} failed: ${cause.message}`, { cause });\n }\n return new ShipError(ErrorType.Api, `${op} failed: ${cause.message}`);\n }\n return new ShipError(ErrorType.Api, `${op} failed: Unknown error`);\n }\n // Factory methods. Uniform shape `(message, details?)` with two principled\n // exceptions: `notFound` composes its message from (resource, id?), and\n // `business` / `api` accept an optional status because they're the\n // multi-status fallbacks.\n static validation(message, details) {\n return new ShipError(ErrorType.Validation, message, 400, details);\n }\n static notFound(resource, id) {\n const message = id ? `${resource} ${id} not found` : `${resource} not found`;\n return new ShipError(ErrorType.NotFound, message, 404);\n }\n static forbidden(message, details) {\n return new ShipError(ErrorType.Forbidden, message, 403, details);\n }\n static rateLimit(message = \"Too many requests\", details) {\n return new ShipError(ErrorType.RateLimit, message, 429, details);\n }\n /**\n * Construct an Authentication (401) error.\n *\n * **Telemetry pattern — `details: { internal: '<tag>' }`.** When the\n * server creates an auth error with an `internal` key in `details`\n * (e.g. `{ internal: 'session_invalid' }`), `toResponse()` strips the\n * entire `details` object before serialization. This keeps the wire\n * response a clean \"Authentication failed\" while preserving granular\n * server-side telemetry (which strategy/check failed) for logs and tests.\n *\n * Use this pattern in API auth code; do not put client-visible info under\n * `internal`. Other `details` keys round-trip normally.\n */\n static authentication(message = \"Authentication required\", details) {\n return new ShipError(ErrorType.Authentication, message, 401, details);\n }\n static business(message, status = 400, details) {\n return new ShipError(ErrorType.Business, message, status, details);\n }\n static network(message, details) {\n return new ShipError(ErrorType.Network, message, undefined, details);\n }\n static cancelled(message, details) {\n return new ShipError(ErrorType.Cancelled, message, undefined, details);\n }\n static file(message, details) {\n return new ShipError(ErrorType.File, message, undefined, details);\n }\n static config(message, details) {\n return new ShipError(ErrorType.Config, message, undefined, details);\n }\n static api(message, status = 500, details) {\n return new ShipError(ErrorType.Api, message, status, details);\n }\n // Semantic-category type guards. For specific-type checks, use\n // `error.type === ErrorType.X` directly or the generic `isType(t)`.\n isClientError() {\n return ERROR_CATEGORIES.client.has(this.type);\n }\n isNetworkError() {\n return ERROR_CATEGORIES.network.has(this.type);\n }\n isAuthError() {\n return ERROR_CATEGORIES.auth.has(this.type);\n }\n isType(errorType) {\n return this.type === errorType;\n }\n}\n/**\n * Type guard to check if an unknown value is a ShipError.\n *\n * Uses structural checking instead of instanceof to handle module duplication\n * in bundled applications where multiple copies of the ShipError class may exist.\n *\n * @example\n * if (isShipError(error)) {\n * console.log(error.status, error.message);\n * }\n */\nexport function isShipError(error) {\n return (error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'ShipError' &&\n 'status' in error);\n}\n// =============================================================================\n// EXTENSION BLOCKLIST\n// =============================================================================\n/**\n * Blocked file extensions — files that cannot be uploaded.\n *\n * We accept any file type by default and derive Content-Type from the\n * extension at serve time (via mime-db in the API worker). Unknown extensions\n * are served as `application/octet-stream` with `X-Content-Type-Options: nosniff`.\n *\n * The blocklist targets file types that pose direct security risks when hosted:\n * executables, disk images, malware vectors, dangerous scripts, and shortcuts.\n */\nexport const BLOCKED_EXTENSIONS = new Set([\n // Executables\n 'exe', 'msi', 'dll', 'scr', 'bat', 'cmd', 'com', 'pif', 'app', 'deb', 'rpm',\n // Installers\n 'pkg', 'mpkg',\n // Disk images\n 'dmg', 'iso', 'img',\n // Malware vectors\n 'cab', 'cpl', 'chm',\n // Dangerous scripts\n 'ps1', 'vbs', 'vbe', 'ws', 'wsf', 'wsc', 'wsh', 'reg',\n // Java\n 'jar', 'jnlp',\n // Mobile/browser packages\n 'apk', 'crx',\n // Shortcut/link\n 'lnk', 'inf', 'hta',\n]);\n/**\n * Check if a filename has a blocked extension.\n * Extracts the extension from the filename and checks against the blocklist.\n * Case-insensitive. Returns false for files without extensions.\n *\n * @example\n * isBlockedExtension('virus.exe') // true\n * isBlockedExtension('app.dmg') // true\n * isBlockedExtension('style.css') // false\n * isBlockedExtension('data.custom') // false\n * isBlockedExtension('README') // false\n */\nexport function isBlockedExtension(filename) {\n const dotIndex = filename.lastIndexOf('.');\n if (dotIndex === -1 || dotIndex === filename.length - 1)\n return false;\n const ext = filename.slice(dotIndex + 1).toLowerCase();\n return BLOCKED_EXTENSIONS.has(ext);\n}\n// =============================================================================\n// FILENAME CHARACTER VALIDATION\n// =============================================================================\n/**\n * Characters that are unsafe in filenames for static hosting.\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (upload splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n */\nexport const UNSAFE_FILENAME_CHARS = /[\\x00-\\x1f\\x7f#?%\\\\<>\"]/;\n/**\n * Check if a filename contains unsafe characters.\n *\n * @example\n * hasUnsafeChars('saved_resource(1).html') // false — parentheses are safe\n * hasUnsafeChars('page[slug].js') // false — brackets are safe\n * hasUnsafeChars('file#anchor.html') // true — # breaks URL resolution\n * hasUnsafeChars('file<tag>.html') // true — < is an XSS vector\n */\nexport function hasUnsafeChars(filename) {\n return UNSAFE_FILENAME_CHARS.test(filename);\n}\n// =============================================================================\n// UNBUILT PROJECT MARKERS\n// =============================================================================\n/**\n * Path segment names that indicate an unbuilt project was uploaded instead of build output.\n * Used for early detection in CLI, browser, and server validation.\n */\nexport const UNBUILT_PROJECT_MARKERS = new Set([\n 'node_modules',\n 'package.json',\n]);\n/**\n * Check if a file path contains an unbuilt project marker.\n *\n * @example\n * hasUnbuiltMarker('node_modules/react/index.js') // true\n * hasUnbuiltMarker('package.json') // true\n * hasUnbuiltMarker('dist/index.html') // false\n */\nexport function hasUnbuiltMarker(filePath) {\n const segments = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n return segments.some(s => UNBUILT_PROJECT_MARKERS.has(s));\n}\n// =============================================================================\n// CREDENTIAL SHAPES\n// =============================================================================\n// The one address for credential vocabulary: how a request is authorized\n// (AuthMethod), the shapes that distinguish populations on the wire\n// (API_KEY, DEPLOY_TOKEN, CALLER), the single dispatch over them (TokenKind,\n// classifyToken), and the delegated-access scopes (OAuthScope).\n/**\n * How a request (or recorded activity) was authorized.\n *\n * Client populations: `SESSION` (first-party cookie), `API_KEY` (`ship-`\n * key), `TOKEN` (`deploy-` deploy token), `AGENT` (anonymous public deploy —\n * no credential; the platform grants the public-account identity per\n * request), `OAUTH` (delegated access token). Server populations: `WEBHOOK`\n * (signed webhook processing), `SYSTEM` (scheduled/background jobs).\n */\nexport const AuthMethod = {\n SESSION: 'session',\n API_KEY: 'apiKey',\n TOKEN: 'token',\n AGENT: 'agent',\n OAUTH: 'oauth',\n WEBHOOK: 'webhook',\n SYSTEM: 'system'\n};\n/**\n * Shape constants for API keys (`ship-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const API_KEY = {\n /** Prefix that identifies an API key. */\n PREFIX: 'ship-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of an API key including prefix (`PREFIX.length + HEX_LENGTH = 69`). */\n TOTAL_LENGTH: 69,\n /** Number of trailing characters used to display a redacted hint (e.g. last 4). */\n HINT_LENGTH: 4,\n};\n/**\n * Shape constants for deploy tokens (`deploy-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const DEPLOY_TOKEN = {\n /** Prefix that identifies a deploy token. */\n PREFIX: 'deploy-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of a deploy token including prefix (`PREFIX.length + HEX_LENGTH = 71`). */\n TOTAL_LENGTH: 71,\n};\n/**\n * Shape constants for caller identifiers (the `X-Caller` instance-identity\n * header — rate-limit bucketing for multi-tenant orchestrators). The API\n * normalizes case and silently ignores malformed values (the header is\n * unauthenticated); clients validate at the boundary via `validateCaller`,\n * so a value the server would drop fails fast instead.\n */\nexport const CALLER = {\n /** HTTP header name. */\n HEADER: 'X-Caller',\n /** Maximum identifier length. */\n MAX_LENGTH: 128,\n /** Allowed characters: alphanumeric, dot, underscore, hyphen. */\n PATTERN: /^[a-zA-Z0-9._-]+$/,\n};\n/**\n * Token populations distinguishable by shape. The platform carries every\n * client token in one wire slot (`Authorization: Bearer <value>`) and\n * classifies by value, never by a side channel — this is the classifier.\n *\n * `API_KEY` and `DEPLOY_TOKEN` *are* `AuthMethod.API_KEY` and\n * `AuthMethod.TOKEN` — the equality is structural, so a classification flows\n * straight into an auth method and the pair can never drift. `OPAQUE` is any\n * other value — shape says nothing about it, so only a lookup can. Today the\n * server refuses every opaque bearer; the OAuth access-token population\n * resolves there when the authorization server ships.\n */\nexport const TokenKind = {\n API_KEY: AuthMethod.API_KEY,\n DEPLOY_TOKEN: AuthMethod.TOKEN,\n OPAQUE: 'opaque',\n};\n/**\n * Classify a client token by shape. The single dispatch used by both sides\n * of the wire: API auth middleware (which population is this credential?)\n * and SDK validation (which format rules apply before sending?). Sharing it\n * is what guarantees client and server can never disagree on dispatch.\n */\nexport function classifyToken(token) {\n if (token.startsWith(API_KEY.PREFIX))\n return TokenKind.API_KEY;\n if (token.startsWith(DEPLOY_TOKEN.PREFIX))\n return TokenKind.DEPLOY_TOKEN;\n return TokenKind.OPAQUE;\n}\n/**\n * OAuth scope vocabulary for delegated third-party access tokens.\n * Single source of truth used by the authorization server (advertised in\n * `scopes_supported`), the API's scope-enforcement middleware, and consent UI\n * copy. The standard `offline_access` scope (refresh tokens) is not platform\n * vocabulary and is deliberately absent — the middleware never checks it.\n *\n * Deliberately absent by design: any `tokens:*` scope, `account:write`, or\n * admin scope — a delegated app must never mint credentials, delete the\n * account, or act as admin.\n */\nexport const OAuthScope = {\n ACCOUNT_READ: 'account:read',\n DEPLOYMENTS_READ: 'deployments:read',\n DEPLOYMENTS_WRITE: 'deployments:write',\n DOMAINS_READ: 'domains:read',\n DOMAINS_WRITE: 'domains:write',\n};\n// =============================================================================\n// DEPLOYMENT CONFIGURATION CONSTANTS\n// =============================================================================\nexport const DEPLOYMENT_CONFIG_FILENAME = 'ship.json';\n/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */\nexport const SPA_DEFAULT_CONFIG = { rewrites: [{ source: '/(.*)', destination: '/index.html' }] };\n// =============================================================================\n// VALIDATION UTILITIES\n// =============================================================================\n/**\n * Shared rule for prefixed credentials: `{PREFIX}{HEX_LENGTH hex chars}`.\n * The regex derives from the shape constants, so the validators can never\n * drift from the shapes `classifyToken` dispatches on.\n */\nfunction validatePrefixedCredential(value, shape, label) {\n if (!value.startsWith(shape.PREFIX)) {\n throw ShipError.validation(`${label} must start with \"${shape.PREFIX}\"`);\n }\n if (value.length !== shape.TOTAL_LENGTH) {\n throw ShipError.validation(`${label} must be ${shape.TOTAL_LENGTH} characters total (${shape.PREFIX} + ${shape.HEX_LENGTH} hex chars)`);\n }\n const hexPart = value.slice(shape.PREFIX.length);\n if (!new RegExp(`^[a-f0-9]{${shape.HEX_LENGTH}}$`, 'i').test(hexPart)) {\n throw ShipError.validation(`${label} must contain ${shape.HEX_LENGTH} hexadecimal characters after \"${shape.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate API key format\n */\nexport function validateApiKey(apiKey) {\n validatePrefixedCredential(apiKey, API_KEY, 'API key');\n}\n/**\n * Validate deploy token format\n */\nexport function validateDeployToken(deployToken) {\n validatePrefixedCredential(deployToken, DEPLOY_TOKEN, 'Deploy token');\n}\n/**\n * Validate a client token of any population. Classifies by shape and applies\n * the matching format rules: `ship-` keys and `deploy-` deploy tokens are\n * validated strictly; opaque tokens (OAuth access tokens, future populations)\n * only need to be non-empty — their validity is the server's to decide.\n */\nexport function validateToken(token) {\n switch (classifyToken(token)) {\n case TokenKind.API_KEY:\n return validateApiKey(token);\n case TokenKind.DEPLOY_TOKEN:\n return validateDeployToken(token);\n case TokenKind.OPAQUE:\n if (!token)\n throw ShipError.validation('Token must be a non-empty string');\n }\n}\n/**\n * Validate a caller identifier against the `CALLER` shape. The server\n * silently ignores malformed values (the header is unauthenticated); clients\n * call this at configuration time so the drop never silently happens.\n */\nexport function validateCaller(caller) {\n if (!caller || caller.length > CALLER.MAX_LENGTH || !CALLER.PATTERN.test(caller)) {\n throw ShipError.validation(`Caller must be 1-${CALLER.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`);\n }\n}\n/**\n * Validate API URL format\n */\nexport function validateApiUrl(apiUrl) {\n try {\n const url = new URL(apiUrl);\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw ShipError.validation('API URL must use http:// or https:// protocol');\n }\n if (url.pathname !== '/' && url.pathname !== '') {\n throw ShipError.validation('API URL must not contain a path');\n }\n if (url.search || url.hash) {\n throw ShipError.validation('API URL must not contain query parameters or fragments');\n }\n }\n catch (error) {\n if (isShipError(error)) {\n throw error;\n }\n throw ShipError.validation('API URL must be a valid URL');\n }\n}\n/**\n * Check if a string matches the deployment identifier pattern (word-word-alphanumeric7).\n * Example: \"happy-cat-abc1234.shipstatic.com\"\n */\nexport function isDeployment(input) {\n return /^[a-z]+-[a-z]+-[a-z0-9]{7}(\\.[a-z0-9.-]+)?$/i.test(input);\n}\n// =============================================================================\n// PLATFORM CONSTANTS\n// =============================================================================\n/** Default API URL if not otherwise configured. */\nexport const DEFAULT_API = 'https://api.shipstatic.com';\n// =============================================================================\n// FILE UPLOAD TYPES\n// =============================================================================\n/**\n * File status constants for validation state tracking\n */\nexport const FileValidationStatus = {\n /** File is pending validation */\n PENDING: 'pending',\n /** File failed during processing (before validation) */\n PROCESSING_ERROR: 'processing_error',\n /** File was excluded by validation warning (not an error) */\n EXCLUDED: 'excluded',\n /** File failed validation (blocks deployment) */\n VALIDATION_FAILED: 'validation_failed',\n /** File passed validation and is ready for deployment */\n READY: 'ready',\n};\n// =============================================================================\n// DOMAIN UTILITIES\n// =============================================================================\n/**\n * Check if a domain is a platform domain (subdomain of our platform).\n * Platform domains are free and don't require DNS verification.\n *\n * @example isPlatformDomain(\"www.shipstatic.com\", \"shipstatic.com\") → true\n * @example isPlatformDomain(\"example.com\", \"shipstatic.com\") → false\n */\nexport function isPlatformDomain(domain, platformDomain) {\n return domain.endsWith(`.${platformDomain}`);\n}\n/**\n * Check if a domain is a custom domain (not a platform subdomain).\n * Custom domains are billable and require DNS verification.\n *\n * @example isCustomDomain(\"example.com\", \"shipstatic.com\") → true\n * @example isCustomDomain(\"www.shipstatic.com\", \"shipstatic.com\") → false\n */\nexport function isCustomDomain(domain, platformDomain) {\n return !isPlatformDomain(domain, platformDomain);\n}\n/**\n * Extract subdomain from a platform domain.\n * Returns null if not a platform domain.\n *\n * @example extractSubdomain(\"www.shipstatic.com\", \"shipstatic.com\") → \"www\"\n * @example extractSubdomain(\"example.com\", \"shipstatic.com\") → null\n */\nexport function extractSubdomain(domain, platformDomain) {\n if (!isPlatformDomain(domain, platformDomain)) {\n return null;\n }\n return domain.slice(0, -(platformDomain.length + 1)); // +1 for the dot\n}\n/**\n * Generate HTTPS URL for a deployment hostname.\n */\nexport function generateDeploymentUrl(deployment) {\n return `https://${deployment}`;\n}\n/**\n * Generate HTTPS URL for a domain.\n */\nexport function generateDomainUrl(domain) {\n return `https://${domain}`;\n}\n// =============================================================================\n// LABEL UTILITIES\n// =============================================================================\n/**\n * Label validation constraints shared across UI and API.\n * These rules define the single source of truth for label validation.\n */\nexport const LABEL_CONSTRAINTS = {\n /** Minimum label length in characters */\n MIN_LENGTH: 3,\n /** Maximum label length in characters (concise labels, matches Stack Overflow's original limit) */\n MAX_LENGTH: 25,\n /** Maximum number of labels allowed per resource */\n MAX_COUNT: 10,\n /** Allowed separator characters between label segments */\n SEPARATORS: '._-',\n};\n/**\n * Label validation pattern.\n * Must start and end with alphanumeric (a-z, 0-9).\n * Can contain separators (. _ -) between segments, but not consecutive.\n *\n * Valid examples: 'production', 'v1.2.3', 'api_v2', 'us-east-1'\n * Invalid examples: 'ab' (too short), '-prod' (starts with separator), 'foo--bar' (consecutive separators)\n */\nexport const LABEL_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;\n/**\n * Serialize labels array to JSON string for database storage.\n * Returns null for empty or undefined arrays.\n *\n * @example serializeLabels(['web', 'production']) → '[\"web\",\"production\"]'\n * @example serializeLabels([]) → null\n * @example serializeLabels(undefined) → null\n */\nexport function serializeLabels(labels) {\n if (!labels || labels.length === 0)\n return null;\n return JSON.stringify(labels);\n}\n/**\n * Deserialize labels from JSON string to array.\n * Always returns an array — empty array for null/empty/invalid input.\n *\n * @example deserializeLabels('[\"web\",\"production\"]') → ['web', 'production']\n * @example deserializeLabels(null) → []\n * @example deserializeLabels('') → []\n */\nexport function deserializeLabels(labelsJson) {\n if (!labelsJson)\n return [];\n try {\n const parsed = JSON.parse(labelsJson);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n}\n// =============================================================================\n// PASSWORD UTILITIES\n// =============================================================================\n/**\n * Length constraints for the optional deployment password\n * (`DeploymentUploadOptions.password`). Single source of truth shared across\n * platform consumers.\n */\nexport const PASSWORD_CONSTRAINTS = {\n /** Minimum password length in characters */\n MIN_LENGTH: 6,\n /** Maximum password length in characters */\n MAX_LENGTH: 128,\n};\n/**\n * Validate an optional deployment password and return it normalized.\n *\n * Absent (`undefined` / `null`) → returns `undefined`. Present → trim\n * leading/trailing whitespace, then validate against `PASSWORD_CONSTRAINTS`\n * length bounds (internal whitespace is significant and counts toward\n * length). Throws `ShipError.validation` on breach; returns the trimmed\n * value.\n *\n * The trim is canonical: at upload, the API hashes the trimmed value; at\n * unlock, the router trims submissions before hashing. Submission and storage\n * agree byte-for-byte. Length validation runs on the trimmed value because\n * that's the user's actual intent — and it disarms a class of invisible\n * foot-guns (trailing newlines from copy/paste, mobile auto-spacing,\n * password-manager artifacts).\n *\n * Single source of truth shared by SDK (client-side validation, return\n * ignored) and API (server-side enforcement, return threaded into config).\n * Length is part of the wire-format contract; strength rules, if added later,\n * stay server-side. See `CLAUDE.md` \"Validation: format vs policy\".\n */\nexport function validatePassword(value) {\n if (value === undefined || value === null)\n return undefined;\n if (typeof value !== 'string') {\n throw ShipError.validation('Password must be a string');\n }\n const trimmed = value.trim();\n if (trimmed.length < PASSWORD_CONSTRAINTS.MIN_LENGTH ||\n trimmed.length > PASSWORD_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(`Password must be between ${PASSWORD_CONSTRAINTS.MIN_LENGTH} and ${PASSWORD_CONSTRAINTS.MAX_LENGTH} characters`);\n }\n return trimmed;\n}\n","/**\n * @file MD5 utility for Blob, Buffer, or file path inputs.\n */\nimport { ShipError } from '@shipstatic/types';\n\nexport interface MD5Result {\n md5: string;\n}\n\nasync function md5Blob(blob: Blob): Promise<MD5Result> {\n const SparkMD5 = (await import('spark-md5')).default;\n const spark = new SparkMD5.ArrayBuffer();\n const chunkSize = 2097152; // 2 MB\n for (let start = 0; start < blob.size; start += chunkSize) {\n const end = Math.min(start + chunkSize, blob.size);\n spark.append(await blob.slice(start, end).arrayBuffer());\n }\n return { md5: spark.end() };\n}\n\nasync function md5Buffer(buffer: Buffer): Promise<MD5Result> {\n const { createHash } = await import('crypto');\n const hash = createHash('md5');\n hash.update(buffer);\n return { md5: hash.digest('hex') };\n}\n\nasync function md5Path(path: string): Promise<MD5Result> {\n const { createHash } = await import('crypto');\n const { createReadStream } = await import('fs');\n return new Promise((resolve, reject) => {\n const hash = createHash('md5');\n const stream = createReadStream(path);\n stream.on('error', err =>\n reject(ShipError.business(`Failed to read file for MD5: ${err.message}`))\n );\n stream.on('data', chunk => hash.update(chunk));\n stream.on('end', () => resolve({ md5: hash.digest('hex') }));\n });\n}\n\nexport async function calculateMD5(input: Blob | Buffer | string): Promise<MD5Result> {\n if (input instanceof Blob) return md5Blob(input);\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(input)) return md5Buffer(input);\n if (typeof input === 'string') return md5Path(input);\n throw ShipError.business('Invalid input for MD5 calculation');\n}\n","/**\n * @file Environment detection utilities for the Ship SDK.\n * Helps in determining whether the SDK is running in a Node.js, browser, or unknown environment.\n */\n\n/**\n * Represents the detected or simulated JavaScript execution environment.\n */\nexport type ExecutionEnvironment = 'browser' | 'node' | 'unknown';\n\n/** @internal Environment override for testing. */\nlet _testEnvironment: ExecutionEnvironment | null = null;\n\n/**\n * **FOR TESTING PURPOSES ONLY.**\n *\n * Allows tests to override the detected environment, forcing the SDK to behave\n * as if it's running in the specified environment.\n *\n * @param env - The environment to simulate ('node', 'browser', 'unknown'),\n * or `null` to clear the override and revert to actual environment detection.\n * @internal\n */\nexport function __setTestEnvironment(env: ExecutionEnvironment | null): void {\n _testEnvironment = env;\n}\n\n/**\n * Detects the actual JavaScript execution environment (Node.js, browser, or unknown)\n * by checking for characteristic global objects.\n * @returns The detected environment as {@link ExecutionEnvironment}.\n * @internal\n */\nfunction detectEnvironment(): ExecutionEnvironment {\n // Check for Node.js environment\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n // Check for Browser environment (including Web Workers)\n if (typeof window !== 'undefined' || typeof self !== 'undefined') {\n return 'browser';\n }\n\n return 'unknown';\n}\n\n/**\n * Gets the current effective execution environment.\n *\n * This function first checks if a test environment override is active via {@link __setTestEnvironment}.\n * If not, it detects the actual environment (Node.js, browser, or unknown).\n *\n * @returns The current execution environment: 'browser', 'node', or 'unknown'.\n * @public\n */\nexport function getENV(): ExecutionEnvironment {\n // Return test override if set\n if (_testEnvironment) {\n return _testEnvironment;\n }\n \n // Detect actual environment\n return detectEnvironment();\n}\n","/**\n * @file Utility for filtering out junk files and directories from file paths\n * \n * This module provides functionality to filter out common system junk files and directories\n * from a list of file paths. It uses the 'junk' package to identify junk filenames and\n * a custom list to filter out common junk directories.\n */\nimport { isJunk } from 'junk';\nimport { ShipError, hasUnbuiltMarker } from '@shipstatic/types';\n\n/**\n * List of directory names considered as junk\n * \n * Files within these directories (at any level in the path hierarchy) will be excluded.\n * The comparison is case-insensitive for cross-platform compatibility.\n * \n * @internal\n */\nexport const JUNK_DIRECTORIES = [\n '__MACOSX',\n '.Trashes',\n '.fseventsd',\n '.Spotlight-V100',\n] as const;\n\n/**\n * Filters an array of file paths, removing those considered junk\n *\n * Throws if any path contains an unbuilt project marker (e.g. `node_modules`, `package.json`).\n * This check runs first because the dot-file filter below would strip paths like\n * `node_modules/.pnpm/...`, destroying the evidence.\n *\n * A path is filtered out if any of these conditions are met:\n * 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)\n * 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)\n * Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)\n * 3. Any path segment exceeds 255 characters (filesystem limit)\n * 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)\n *\n * All path separators are normalized to forward slashes for consistent cross-platform behavior.\n *\n * Dot files are filtered for security — they typically contain sensitive configuration\n * (.env, .git) or are not meant to be served publicly. This matches server-side filtering.\n *\n * @param filePaths - An array of file path strings to filter\n * @param options - Optional settings\n * @param options.allowUnbuilt - When true, skip the unbuilt project marker check (for server-processed uploads)\n * @returns A new array containing only non-junk file paths\n * @throws {ShipError} If any path contains an unbuilt project marker (unless allowUnbuilt is true)\n *\n * @example\n * ```typescript\n * import { filterJunk } from '@shipstatic/ship';\n *\n * // Filter an array of file paths\n * const paths = ['index.html', '.DS_Store', '.gitattributes', '__MACOSX/file.txt', 'app.js'];\n * const clean = filterJunk(paths);\n * // Result: ['index.html', 'app.js']\n * ```\n *\n * @example\n * ```typescript\n * // Use with browser File objects\n * import { filterJunk } from '@shipstatic/ship';\n *\n * const files: File[] = [...]; // From input or drag-drop\n *\n * // Extract paths from File objects\n * const filePaths = files.map(f => f.webkitRelativePath || f.name);\n *\n * // Filter out junk paths\n * const validPaths = new Set(filterJunk(filePaths));\n *\n * // Filter the original File array\n * const validFiles = files.filter(f =>\n * validPaths.has(f.webkitRelativePath || f.name)\n * );\n * ```\n */\nexport function filterJunk(\n filePaths: string[],\n options?: { allowUnbuilt?: boolean }\n): string[] {\n if (!filePaths || filePaths.length === 0) {\n return [];\n }\n\n // Reject unbuilt projects before the dot-file filter removes evidence.\n // pnpm stores files under node_modules/.pnpm/ — the dot-file filter below\n // strips .pnpm/ paths, destroying the only signal that this is an unbuilt project.\n if (!options?.allowUnbuilt) {\n const marker = filePaths.find(p => p && hasUnbuiltMarker(p));\n if (marker) {\n throw ShipError.business(\n 'Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder'\n );\n }\n }\n\n return filePaths.filter(filePath => {\n if (!filePath) {\n return false; // Exclude null or undefined paths\n }\n\n // Normalize path separators to forward slashes and split into segments\n const parts = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n if (parts.length === 0) return true;\n\n // Check if the basename is a junk file (using junk package)\n const basename = parts[parts.length - 1];\n if (isJunk(basename)) {\n return false;\n }\n\n // Filter out dot files and directories (security: prevents .env, .git, etc.)\n // .well-known is not junk — it's a standard directory (RFC 8615)\n // Path position constraints enforced at upload (buildFileKey) and serving (isBlockedDotFile)\n for (const part of parts) {\n if (part === '.well-known') continue;\n if (part.startsWith('.') || part.length > 255) {\n return false;\n }\n }\n\n // Check if any directory segment is in our junk directories list\n const directorySegments = parts.slice(0, -1);\n for (const segment of directorySegments) {\n if (JUNK_DIRECTORIES.some(junkDir =>\n segment.toLowerCase() === junkDir.toLowerCase())) {\n return false;\n }\n }\n\n return true;\n });\n}\n","/**\n * @file Path helper utilities that work in both browser and Node.js environments.\n * Provides environment-agnostic path manipulation functions.\n */\n\n/**\n * Finds the common parent directory from an array of directory paths.\n * Simple, unified implementation for flattenDirs functionality.\n * \n * @param dirPaths - Array of directory paths (not file paths - directories containing the files)\n * @returns The common parent directory path, or empty string if none found\n */\nexport function findCommonParent(dirPaths: string[]): string {\n if (!dirPaths || dirPaths.length === 0) return '';\n \n const normalizedPaths = dirPaths\n .filter(p => p && typeof p === 'string')\n .map(p => p.replace(/\\\\/g, '/'));\n \n if (normalizedPaths.length === 0) return '';\n if (normalizedPaths.length === 1) return normalizedPaths[0];\n\n const pathSegments = normalizedPaths.map(p => p.split('/').filter(Boolean));\n const commonSegments = [];\n const minLength = Math.min(...pathSegments.map(p => p.length));\n \n for (let i = 0; i < minLength; i++) {\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n\n\n/**\n * Converts backslashes to forward slashes for cross-platform compatibility.\n * Does not remove leading slashes (preserves absolute paths).\n * @param path - The path to normalize\n * @returns Path with forward slashes\n */\nexport function normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n/**\n * Normalizes a path for web usage by converting backslashes to forward slashes\n * and removing leading slashes.\n * @param path - The path to normalize\n * @returns Normalized path suitable for web deployment\n */\nexport function normalizeWebPath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/^\\/+/, '');\n}\n\n","/**\n * @file Deploy path optimization - the core logic that makes Ship deployments clean and intuitive.\n * Automatically strips common parent directories to create clean deployment URLs.\n */\n\nimport { normalizeWebPath } from './path.js';\n\n/**\n * Represents a file ready for deployment with its optimized path\n */\nexport interface DeployFile {\n /** The clean deployment path (e.g., \"assets/style.css\") */\n path: string;\n /** Original filename */\n name: string;\n}\n\n/**\n * Core path optimization logic.\n * Transforms messy local paths into clean deployment paths.\n * \n * @example\n * Input: [\"dist/index.html\", \"dist/assets/app.js\"]\n * Output: [\"index.html\", \"assets/app.js\"]\n * \n * @param filePaths - Raw file paths from the local filesystem\n * @param options - Path processing options\n */\nexport function optimizeDeployPaths(\n filePaths: string[], \n options: { flatten?: boolean } = {}\n): DeployFile[] {\n // When flattening is disabled, keep original structure\n if (options.flatten === false) {\n return filePaths.map(path => ({\n path: normalizeWebPath(path),\n name: extractFileName(path)\n }));\n }\n\n // Find the common directory prefix to strip\n const commonPrefix = findCommonDirectory(filePaths);\n \n return filePaths.map(filePath => {\n let deployPath = normalizeWebPath(filePath);\n \n // Strip the common prefix to create clean deployment paths\n if (commonPrefix) {\n const prefixToRemove = commonPrefix.endsWith('/') ? commonPrefix : `${commonPrefix}/`;\n if (deployPath.startsWith(prefixToRemove)) {\n deployPath = deployPath.substring(prefixToRemove.length);\n }\n }\n \n // Fallback to filename if path becomes empty\n if (!deployPath) {\n deployPath = extractFileName(filePath);\n }\n \n return {\n path: deployPath,\n name: extractFileName(filePath)\n };\n });\n}\n\n/**\n * Finds the common directory shared by all file paths.\n * This is what gets stripped to create clean deployment URLs.\n * \n * @example\n * [\"dist/index.html\", \"dist/assets/app.js\"] → \"dist\"\n * [\"src/components/A.tsx\", \"src/utils/B.ts\"] → \"src\"\n * [\"file1.txt\", \"file2.txt\", \"subdir/file3.txt\"] → \"\" (no common directory)\n */\nfunction findCommonDirectory(filePaths: string[]): string {\n if (!filePaths.length) return '';\n \n // Normalize all paths first\n const normalizedPaths = filePaths.map(path => normalizeWebPath(path));\n \n // Find the common prefix among all file paths (not just directories)\n const pathSegments = normalizedPaths.map(path => path.split('/'));\n const commonSegments: string[] = [];\n const minLength = Math.min(...pathSegments.map(segments => segments.length));\n \n // Check each segment level to find the longest common prefix\n for (let i = 0; i < minLength - 1; i++) { // -1 because we don't want to include the filename\n const segment = pathSegments[0][i];\n if (pathSegments.every(segments => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n \n return commonSegments.join('/');\n}\n\n/**\n * Extracts just the filename from a file path\n */\nfunction extractFileName(path: string): string {\n return path.split(/[/\\\\]/).pop() || path;\n}","/**\n * @file File validation utilities for Ship SDK\n * Provides client-side validation for file uploads before deployment\n */\n\nimport type {\n PlatformLimits,\n FileValidationResult,\n ValidatableFile,\n ValidationIssue,\n FileValidationStatusType\n} from '@shipstatic/types';\nimport {\n FileValidationStatus as FILE_VALIDATION_STATUS,\n isBlockedExtension,\n hasUnbuiltMarker,\n hasUnsafeChars,\n} from '@shipstatic/types';\n\nexport { FILE_VALIDATION_STATUS };\n\n/**\n * Format file size to human-readable string\n */\nexport function formatFileSize(bytes: number, decimals: number = 1): string {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];\n}\n\n/**\n * Validate filename for deployment safety\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (buildFileKey splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n *\n * Additional checks: path traversal, reserved names, leading/trailing dots or spaces.\n */\nexport function validateFileName(filename: string): { valid: boolean; reason?: string } {\n if (hasUnsafeChars(filename)) {\n return { valid: false, reason: 'File name contains unsafe characters' };\n }\n\n if (filename.startsWith(' ') || filename.endsWith(' ')) {\n return { valid: false, reason: 'File name cannot start/end with spaces' };\n }\n\n if (filename.endsWith('.')) {\n return { valid: false, reason: 'File name cannot end with dots' };\n }\n\n const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\\.|$)/i;\n const nameWithoutPath = filename.split('/').pop() || filename;\n if (reservedNames.test(nameWithoutPath)) {\n return { valid: false, reason: 'File name uses a reserved system name' };\n }\n\n if (filename.includes('..')) {\n return { valid: false, reason: 'File name contains path traversal pattern' };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate files against configuration limits with severity-based reporting\n *\n * Validation categorizes issues by severity:\n * - **Errors**: Block deployment (file too large, blocked extension, etc.)\n * - **Warnings**: Exclude files but allow deployment (empty files, etc.)\n *\n * @param files - Array of files to validate\n * @param config - Validation configuration from ship.getLimits()\n * @returns Validation result with errors and warnings\n *\n * @example\n * ```typescript\n * const config = await ship.getLimits();\n * const result = validateFiles(files, config);\n *\n * if (!result.canDeploy) {\n * // Has errors - deployment blocked\n * console.error('Deployment blocked:', result.errors);\n * } else if (result.warnings.length > 0) {\n * // Has warnings - deployment proceeds, some files excluded\n * console.warn('Files excluded:', result.warnings);\n * await ship.deploy(result.validFiles);\n * } else {\n * // All files valid\n * await ship.deploy(result.validFiles);\n * }\n * ```\n */\nexport function validateFiles<T extends ValidatableFile>(\n files: T[],\n config: PlatformLimits\n): FileValidationResult<T> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n let fileStatuses: T[] = []; // Use 'let' for atomic enforcement later\n\n // Check at least 1 file required\n if (files.length === 0) {\n const issue: ValidationIssue = {\n file: '(no files)',\n message: 'At least one file must be provided'\n };\n errors.push(issue);\n\n return {\n files: [],\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Check for unbuilt project markers (node_modules/, etc.)\n for (const file of files) {\n if (hasUnbuiltMarker(file.name)) {\n errors.push({\n file: file.name,\n message: `Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder`\n });\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: 'Unbuilt project detected'\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false\n };\n }\n }\n\n // Check file count limit\n if (files.length > config.maxFilesCount) {\n const issue: ValidationIssue = {\n file: `(${files.length} files)`,\n message: `File count (${files.length}) exceeds limit of ${config.maxFilesCount}`\n };\n errors.push(issue);\n\n return {\n files: files.map(f => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: issue.message,\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Validate each file\n let totalSize = 0;\n\n for (const file of files) {\n let fileStatus: FileValidationStatusType = FILE_VALIDATION_STATUS.READY;\n let statusMessage = 'Ready for upload';\n\n // Pre-compute filename validation\n const nameValidation = file.name ? validateFileName(file.name) : { valid: false, reason: 'File name cannot be empty' };\n\n // Check for processing errors\n if (file.status === FILE_VALIDATION_STATUS.PROCESSING_ERROR) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = file.statusMessage || 'File failed during processing';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // EMPTY FILE - Warning (not error)\n else if (file.size === 0) {\n fileStatus = FILE_VALIDATION_STATUS.EXCLUDED;\n statusMessage = 'File is empty (0 bytes) and cannot be deployed due to storage limitations';\n warnings.push({\n file: file.name,\n message: statusMessage\n });\n // Skip other validations for excluded files\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n continue;\n }\n\n // Negative file size - Error\n else if (file.size < 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File size must be positive';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File name validation\n else if (!file.name || file.name.trim().length === 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name cannot be empty';\n errors.push({\n file: file.name || '(empty)',\n message: statusMessage\n });\n }\n else if (file.name.includes('\\0')) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name contains invalid characters (null byte)';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n else if (!nameValidation.valid) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = nameValidation.reason || 'Invalid file name';\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Blocked extension check\n else if (isBlockedExtension(file.name)) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File extension not allowed: \"${file.name}\"`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // File size validation\n else if (file.size > config.maxFileSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File size (${formatFileSize(file.size)}) exceeds limit of ${formatFileSize(config.maxFileSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n\n // Total size validation\n else {\n totalSize += file.size;\n if (totalSize > config.maxTotalSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `Total size would exceed limit of ${formatFileSize(config.maxTotalSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage\n });\n }\n }\n\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n }\n\n // ATOMIC ENFORCEMENT: Two-phase validation for optimal UX + atomic semantics\n // Phase 1 (above): Validate files individually to collect ALL errors\n // Phase 2 (below): Mark all files as failed if any errors exist\n //\n // Why two phases? We validate individually for better UX (users see all problems\n // at once and can fix everything in one pass), then enforce atomicity to maintain\n // deployment transaction semantics (all-or-nothing).\n if (errors.length > 0) {\n fileStatuses = fileStatuses.map(file => {\n // Keep EXCLUDED files as-is (they're warnings, not errors)\n if (file.status === FILE_VALIDATION_STATUS.EXCLUDED) {\n return file;\n }\n\n // Mark ALL other files as VALIDATION_FAILED (atomic deployment)\n return {\n ...file,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: file.status === FILE_VALIDATION_STATUS.VALIDATION_FAILED\n ? file.statusMessage // Keep original error message for the file that actually failed\n : 'Deployment failed due to validation errors in bundle'\n };\n });\n }\n\n // Build atomic result\n // validFiles is empty if ANY errors exist (all-or-nothing)\n const validFiles = errors.length === 0\n ? fileStatuses.filter(f => f.status === FILE_VALIDATION_STATUS.READY)\n : [];\n const canDeploy = errors.length === 0;\n\n return {\n files: fileStatuses,\n validFiles,\n errors,\n warnings,\n canDeploy,\n };\n}\n\n/**\n * Get only the valid files from validation results\n */\nexport function getValidFiles<T extends ValidatableFile>(files: T[]): T[] {\n return files.filter(f => f.status === FILE_VALIDATION_STATUS.READY);\n}\n\n/**\n * Check if all valid files have required properties for upload\n * (Can be extended to check for MD5, etc.)\n */\nexport function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean {\n const validFiles = getValidFiles(files);\n return validFiles.length > 0;\n}\n","/**\n * @file Shared security validation for the deploy pipeline.\n * Used by both Node.js and browser file processing pipelines.\n */\nimport { ShipError, isBlockedExtension } from '@shipstatic/types';\nimport { validateFileName } from './file-validation.js';\n\n/**\n * Validate a deploy path for security concerns.\n * Rejects paths containing path traversal patterns or null bytes.\n *\n * Checks for:\n * - Null bytes (\\0) — path injection\n * - /../ — directory traversal within path\n * - ../ at start — upward traversal\n * - /.. at end — trailing traversal\n *\n * Does NOT reject double dots in filenames (e.g., \"foo..bar.txt\" is safe).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the path contains unsafe patterns\n */\nexport function validateDeployPath(deployPath: string, sourceIdentifier: string): void {\n if (\n deployPath.includes('\\0') ||\n deployPath.includes('/../') ||\n deployPath.startsWith('../') ||\n deployPath.endsWith('/..')\n ) {\n throw ShipError.business(`Security error: Unsafe file path \"${deployPath}\" for file: ${sourceIdentifier}`);\n }\n}\n\n/**\n * Validate a deploy file's name and extension.\n * Rejects unsafe filenames (shell/URL-dangerous chars, reserved names)\n * and blocked file extensions (.exe, .msi, .dll, etc.).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the filename is unsafe or extension is blocked\n */\nexport function validateDeployFile(deployPath: string, sourceIdentifier: string): void {\n const nameCheck = validateFileName(deployPath);\n if (!nameCheck.valid) {\n throw ShipError.business(nameCheck.reason || 'Invalid file name');\n }\n\n if (isBlockedExtension(deployPath)) {\n throw ShipError.business(`File extension not allowed: \"${sourceIdentifier}\"`);\n }\n}\n","/**\n * @file Node.js-specific file utilities for the Ship SDK.\n * Provides helpers for recursively discovering, filtering, and preparing files for deploy in Node.js.\n */\nimport { getENV } from '../../shared/lib/env.js';\nimport type { PlatformLimits } from '@shipstatic/types';\nimport type { StaticFile, DeploymentOptions } from '../../shared/types.js';\nimport { calculateMD5 } from '../../shared/lib/md5.js';\nimport { filterJunk } from '../../shared/lib/junk.js';\nimport { validateDeployPath, validateDeployFile } from '../../shared/lib/security.js';\nimport { ShipError, isShipError, UNBUILT_PROJECT_MARKERS } from '@shipstatic/types';\nimport { optimizeDeployPaths } from '../../shared/lib/deploy-paths.js';\nimport { findCommonParent } from '../../shared/lib/path.js';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n\n/**\n * Recursive function to walk directory and return all file paths.\n * Includes symlink loop protection to prevent infinite recursion.\n * @param dirPath - Directory path to traverse\n * @param visited - Set of already visited real paths (for cycle detection)\n * @returns Array of absolute file paths in the directory\n */\nfunction findAllFilePaths(dirPath: string, visited: Set<string> = new Set()): string[] {\n const results: string[] = [];\n\n // Resolve the real path to detect symlink cycles\n const realPath = fs.realpathSync(dirPath);\n if (visited.has(realPath)) {\n // Already visited this directory (symlink cycle) - skip to prevent infinite loop\n return results;\n }\n visited.add(realPath);\n\n const entries = fs.readdirSync(dirPath);\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry);\n const stats = fs.statSync(fullPath);\n\n if (stats.isDirectory()) {\n const subFiles = findAllFilePaths(fullPath, visited);\n results.push(...subFiles);\n } else if (stats.isFile()) {\n results.push(fullPath);\n }\n }\n\n return results;\n}\n\n/**\n * Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.\n * Computes content paths relative to the upload root before filtering, so only the deployed\n * directory structure is evaluated — not the user's filesystem above it.\n * \n * @param paths - File or directory paths to scan and process.\n * @param options - Processing options (pathDetect, etc.).\n * @param platformLimits - Per-instance platform limits (file-size / count /\n * total-size caps) from the originating Ship's `GET /config` fetch. Passed\n * in rather than read from a module global so concurrent Ships against\n * different API URLs cannot clobber each other's caps.\n * @returns Promise resolving to an array of StaticFile objects.\n * @throws {ShipClientError} If called outside Node.js or if fs/path modules fail.\n */\nexport async function processFilesForNode(\n paths: string[],\n options: DeploymentOptions = {},\n platformLimits?: PlatformLimits\n): Promise<StaticFile[]> {\n if (getENV() !== 'node') {\n throw ShipError.business('processFilesForNode can only be called in Node.js environment.');\n }\n\n // Check input directories for unbuilt project markers before recursive walk\n for (const p of paths) {\n const absPath = path.resolve(p);\n try {\n if (fs.statSync(absPath).isDirectory()) {\n const marker = fs.readdirSync(absPath).find(e => UNBUILT_PROJECT_MARKERS.has(e));\n if (marker) {\n throw ShipError.business(`\"${marker}\" detected — deploy your build output (dist/, build/, out/), not the project folder`);\n }\n }\n } catch (e) {\n if (isShipError(e)) throw e;\n // Path errors handled in the existing flatMap below\n }\n }\n\n // 1. Discover all unique, absolute file paths from the input list\n const absolutePaths = paths.flatMap(p => {\n const absPath = path.resolve(p);\n try {\n const stats = fs.statSync(absPath);\n return stats.isDirectory() ? findAllFilePaths(absPath) : [absPath];\n } catch (error) {\n throw ShipError.file(`Path does not exist: ${p}`, { filePath: p });\n }\n });\n const uniquePaths = [...new Set(absolutePaths)];\n\n // 2. Determine base path for content paths (from INPUT paths, not discovered files)\n const inputAbsolutePaths = paths.map(p => path.resolve(p));\n const inputBasePath = findCommonParent(inputAbsolutePaths.map(p => {\n try {\n const stats = fs.statSync(p);\n return stats.isDirectory() ? p : path.dirname(p);\n } catch {\n return path.dirname(p);\n }\n }));\n\n // 3. Compute content paths (relative to upload root)\n const contentPaths = uniquePaths.map(absPath => {\n if (inputBasePath && inputBasePath.length > 0) {\n const rel = path.relative(inputBasePath, absPath);\n if (rel && typeof rel === 'string' && !rel.startsWith('..')) {\n return rel.replace(/\\\\/g, '/');\n }\n }\n return path.basename(absPath);\n });\n\n // 4. Optimize paths for deployment (strip common root, flatten)\n const deployFiles = optimizeDeployPaths(contentPaths, {\n flatten: options.pathDetect !== false\n });\n const deployPaths = deployFiles.map(f => f.path);\n\n // 5. Filter junk from deploy paths\n const filteredSet = new Set(filterJunk(deployPaths));\n if (filteredSet.size === 0) {\n return [];\n }\n\n // 6. Collect valid file pairs (absolute path for reading, deploy path for output)\n const validAbsPaths: string[] = [];\n const validDeployPaths: string[] = [];\n for (let i = 0; i < uniquePaths.length; i++) {\n if (filteredSet.has(deployPaths[i])) {\n validAbsPaths.push(uniquePaths[i]);\n validDeployPaths.push(deployPaths[i]);\n }\n }\n\n // 7. Process files into StaticFile objects\n const results: StaticFile[] = [];\n let totalSize = 0;\n if (!platformLimits) {\n throw ShipError.config(\n 'Platform limits not provided. processFilesForNode requires the limits ' +\n 'argument — pass `ship.getLimits()` result.'\n );\n }\n\n for (let i = 0; i < validAbsPaths.length; i++) {\n const filePath = validAbsPaths[i];\n const deployPath = validDeployPaths[i];\n \n try {\n // Security validation (shared with browser) — fail fast before any I/O\n validateDeployPath(deployPath, filePath);\n\n const stats = fs.statSync(filePath);\n\n // Skip empty files — R2 cannot store zero-byte objects\n if (stats.size === 0) {\n continue;\n }\n\n // Filename and extension validation (shared with browser)\n validateDeployFile(deployPath, filePath);\n\n // Validate file sizes\n if (stats.size > platformLimits.maxFileSize) {\n throw ShipError.business(`File ${filePath} is too large. Maximum allowed size is ${platformLimits.maxFileSize / (1024 * 1024)}MB.`);\n }\n totalSize += stats.size;\n if (totalSize > platformLimits.maxTotalSize) {\n throw ShipError.business(`Total deploy size is too large. Maximum allowed is ${platformLimits.maxTotalSize / (1024 * 1024)}MB.`);\n }\n\n const content = fs.readFileSync(filePath);\n const { md5 } = await calculateMD5(content);\n\n results.push({\n path: deployPath,\n content,\n size: content.length,\n md5,\n });\n } catch (error) {\n // Re-throw ShipError instances directly\n if (isShipError(error)) {\n throw error;\n }\n // Convert file system errors to ShipError with clear message\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw ShipError.file(`Failed to read file \"${filePath}\": ${errorMessage}`, { filePath });\n }\n }\n\n // Final validation\n if (results.length > platformLimits.maxFilesCount) {\n throw ShipError.business(`Too many files to deploy. Maximum allowed is ${platformLimits.maxFilesCount} files.`);\n }\n \n return results;\n}","/**\n * @file Main entry point for the Ship CLI.\n */\nimport { Command } from 'commander';\nimport { Ship } from '../index.js';\nimport { ShipError, ErrorType, validateToken, validateApiUrl, isShipError, type Deployment } from '@shipstatic/types';\nimport { readFileSync, existsSync, statSync } from 'fs';\nimport * as path from 'path';\nimport { success, error } from './utils.js';\nimport { formatOutput, type OutputContext } from './formatters.js';\nimport { installCompletion, uninstallCompletion } from './completion.js';\nimport { runConfig } from './config.js';\nimport { createClient, mergeCliConfig } from './create-client.js';\nimport { readEnvConfig } from '../core/config.js';\nimport { loadShipFile } from './shiprc.js';\nimport { getUserMessage, toShipError, formatErrorJson } from './error-handling.js';\nimport { bold, dim } from 'yoctocolors';\nimport type { GlobalOptions, DeployCommandOptions, LabelOptions, TokenCreateCommandOptions, CLIResult } from './types.js';\n\n// Load package.json for version\nfunction loadPackageJson(): { version: string } {\n const paths = [\n path.resolve(__dirname, '../package.json'),\n path.resolve(__dirname, '../../package.json')\n ];\n for (const p of paths) {\n try {\n return JSON.parse(readFileSync(p, 'utf-8'));\n } catch {}\n }\n return { version: '0.0.0' };\n}\n\nconst packageJson = loadPackageJson();\n\n\n\nconst program = new Command();\n\n// Override Commander.js error handling while preserving help/version behavior\nprogram\n .exitOverride((err) => {\n // Only override actual errors, not help/version exits\n if (err.code === 'commander.help' || err.code === 'commander.version' || err.exitCode === 0) {\n process.exit(err.exitCode || 0);\n }\n\n // --help alongside a parse error (e.g., ship deployments upload --help)\n // Show help instead of the error\n if (process.argv.includes('--help')) {\n displayHelp(processOptions(program).noColor);\n process.exit(0);\n }\n\n const globalOptions = processOptions(program);\n\n let message = err.message || 'unknown command error';\n message = message\n .replace(/^error: /, '')\n .replace(/\\n.*/, '')\n .replace(/\\.$/, '')\n .toLowerCase();\n\n error(message, globalOptions.json, globalOptions.noColor);\n\n if (!globalOptions.json) {\n displayHelp(globalOptions.noColor);\n }\n\n process.exit(err.exitCode || 1);\n })\n .configureOutput({\n writeErr: (str) => {\n if (!str.startsWith('error:')) {\n process.stderr.write(str);\n }\n },\n writeOut: (str) => process.stdout.write(str)\n });\n\n\n/**\n * Display comprehensive help information for all commands\n */\nfunction displayHelp(noColor?: boolean) {\n const applyBold = (text: string) => noColor ? text : bold(text);\n const applyDim = (text: string) => noColor ? text : dim(text);\n const icon = (emoji: string) => noColor ? '' : `${emoji} `;\n\n const output = `${applyBold('USAGE')}\n ship <path> ${icon('🚀')}Deploy static sites with simplicity\n\n${applyBold('COMMANDS')}\n ${icon('📦')}${applyBold('Deployments')}\n ship deployments list List all deployments\n ship deployments upload <path> Upload deployment from directory\n ship deployments get <deployment> Show deployment information\n ship deployments set <deployment> Set deployment labels\n ship deployments remove <deployment> Delete deployment permanently\n\n ${icon('🌎')}${applyBold('Domains')}\n ship domains list List all domains\n ship domains set <name> [deployment] Create domain, link to deployment, or update labels\n ship domains get <name> Show domain information\n ship domains validate <name> Check if domain name is valid and available\n ship domains records <name> Show required DNS records for domain setup\n ship domains dns <name> Look up DNS provider for a domain\n ship domains share <name> Get shareable DNS setup link\n ship domains verify <name> Trigger DNS verification for external domain\n ship domains remove <name> Delete domain permanently\n\n ${icon('🔑')}${applyBold('Tokens')}\n ship tokens list List all deploy tokens\n ship tokens create Create a new deploy token\n ship tokens remove <token> Delete token permanently\n\n ${icon('⚙️')}${applyBold('Setup')}\n ship config Save your token\n ship whoami Get current account information\n\n ${icon('🛠️')}${applyBold('Completion')}\n ship completion install Install shell completion script\n ship completion uninstall Uninstall shell completion script\n\n${applyBold('FLAGS')}\n --token <token> Any ship token: API key (ship-…) or deploy token (deploy-…)\n --config <file> Custom config file path\n --label <label> Set label (repeatable, replaces all existing)\n --password <password> Password-protect this deployment\n --no-path-detect Disable automatic path optimization and flattening\n --no-spa-detect Disable automatic SPA detection and configuration\n --no-color Disable colored output\n --json Output results in JSON format\n -q, --quiet Output only the resource identifier\n --version Show version information\n\n${applyBold('EXAMPLES')}\n ship ./dist\n ship domains set www.example.com happy-cat-abc1234.shipstatic.com\n ship ./dist -q | ship domains set www.example.com\n\n${applyDim('Please report any issues to https://github.com/shipstatic/ship/issues')}\n`;\n\n console.log(output);\n}\n\n/**\n * Collector function for Commander.js to accumulate repeated option values.\n * Used for --label flag that can be specified multiple times.\n */\nfunction collect(value: string, previous: string[] = []): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Merge label options from command and program levels.\n * Commander.js sometimes routes --label to program level instead of command level.\n */\nfunction mergeLabelOption(cmdOptions: LabelOptions | undefined, programOpts: LabelOptions | undefined): string[] | undefined {\n const labels = cmdOptions?.label?.length ? cmdOptions.label : programOpts?.label;\n if (!labels?.length) return undefined;\n // Filter empty strings: --label '' means \"clear all labels\"\n const filtered = labels.filter(l => l !== '');\n return filtered.length ? filtered : [];\n}\n\n/**\n * Merge password options from command and program levels.\n * Commander.js sometimes routes --password to program level instead of command level.\n *\n * An empty `--password ''` is forwarded to the SDK validator so the user\n * sees a clear length error rather than a silent drop. An empty\n * `SHIP_PASSWORD` is coerced to undefined, matching how SHIP_TOKEN\n * and SHIP_API_URL treat empty env vars (CI/Docker\n * often sets unset vars to \"\" — see core/config.ts).\n */\nfunction mergePasswordOption(\n cmdOptions: { password?: string } | undefined,\n programOpts: { password?: string } | undefined,\n): string | undefined {\n return cmdOptions?.password ?? programOpts?.password ?? (process.env.SHIP_PASSWORD || undefined);\n}\n\n/**\n * Handle unknown or missing subcommand for parent commands.\n * Shows scoped usage instead of full help — the user already knows the group.\n */\nfunction handleUnknownSubcommand(parentName: string, validSubcommands: string[]): (...args: unknown[]) => void {\n return (...args: unknown[]) => {\n const globalOptions = processOptions(program);\n\n // Get the command object (last argument) - Commander passes it as the final arg\n const commandObj = args[args.length - 1] as { args?: string[] } | undefined;\n\n // Check if an unknown subcommand was provided\n if (commandObj?.args?.length) {\n const unknownArg = commandObj.args.find((arg) => !validSubcommands.includes(arg));\n if (unknownArg) {\n error(`unknown command '${unknownArg}'`, globalOptions.json, globalOptions.noColor);\n }\n }\n\n if (!globalOptions.json) {\n console.log(`usage: ship ${parentName} <${validSubcommands.join('|')}>\\n`);\n }\n process.exit(1);\n };\n}\n\n/**\n * Process CLI options using Commander's built-in option merging.\n * Applies CLI-specific transformations (validation is done in preAction hook).\n */\nfunction processOptions(command: Command): GlobalOptions {\n const options = command.optsWithGlobals();\n\n // Convert Commander.js --no-color flag (color: false) to our convention (noColor: true)\n if (options.color === false) {\n options.noColor = true;\n }\n\n // Auto-suppress color when stdout is not a TTY (like grep --color=auto)\n // Also respect NO_COLOR convention (https://no-color.org/)\n // FORCE_COLOR overrides for CI environments that explicitly want color\n // FORCE_COLOR=0 means \"force no color\" per the convention (0=off, 1/2/3=on)\n const forceColor = !!process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0';\n if (!options.noColor && !forceColor) {\n if (!process.stdout.isTTY || process.env.NO_COLOR !== undefined) {\n options.noColor = true;\n }\n }\n\n return options as GlobalOptions;\n}\n\n/**\n * Error handler - outputs errors consistently in text or JSON format.\n * Message formatting is delegated to the error-handling module.\n */\n/**\n * The credential the CLI actually resolved (flag > env > file). The error\n * path must diagnose with the same lens the client was built with — a user\n * whose `SHIP_TOKEN` or `.shiprc` token was rejected is credentialed, and\n * the anonymous-user hint would misdiagnose their failure. A config file\n * that fails to load counts as no file credential: that failure is already\n * the error being reported.\n */\nfunction resolveCliToken(flags: { config?: string; apiUrl?: string; token?: string }): string | undefined {\n let file = {};\n try {\n file = loadShipFile(flags.config);\n } catch {}\n // Flags, env, and files only ever hold strings — provider functions exist\n // solely as constructor arguments, which the CLI never passes.\n const token = mergeCliConfig(flags, readEnvConfig(), file).token;\n return typeof token === 'string' ? token : undefined;\n}\n\nfunction handleError(\n err: unknown,\n context?: OutputContext\n) {\n const opts = processOptions(program);\n const shipError = toShipError(err);\n\n // Get user-facing message using the extracted pure function\n const message = getUserMessage(shipError, context, {\n token: resolveCliToken(program.opts())\n });\n\n // Output in appropriate format\n if (opts.json) {\n console.error(formatErrorJson(message, shipError.details) + '\\n');\n } else {\n error(message, false, opts.noColor);\n // Show help only for unknown command errors (user CLI mistake)\n if (shipError.type === ErrorType.Validation && message.includes('unknown command')) {\n displayHelp(opts.noColor);\n }\n }\n\n process.exit(1);\n}\n\n/**\n * Wrapper for CLI actions that handles errors and client creation consistently.\n * Reduces boilerplate while preserving context for error handling.\n */\nfunction withErrorHandling<T extends unknown[], R extends CLIResult>(\n handler: (client: Ship, options: GlobalOptions, ...args: T) => Promise<R>,\n context?: { operation?: string; resourceType?: string; getResourceId?: (...args: T) => string }\n) {\n return async function(this: Command, ...args: T) {\n const globalOptions = processOptions(this);\n\n // Build context once for both output and error paths\n const resolvedContext: OutputContext = context ? {\n operation: context.operation,\n resourceType: context.resourceType,\n resourceId: context.getResourceId?.(...args)\n } : {};\n\n try {\n const { config, apiUrl, token } = program.opts();\n const client = createClient({ config, apiUrl, token });\n const result = await handler(client, globalOptions, ...args);\n formatOutput(result, resolvedContext, { json: globalOptions.json, quiet: globalOptions.quiet, noColor: globalOptions.noColor });\n } catch (err) {\n handleError(err, resolvedContext);\n }\n };\n}\n\n/** Spinner instance type from yocto-spinner */\ninterface Spinner {\n start(): Spinner;\n stop(): void;\n}\n\n/**\n * Common deploy logic used by both shortcut and explicit commands.\n */\nasync function performDeploy(\n client: Ship,\n deployPath: string,\n labels: string[] | undefined,\n password: string | undefined,\n cmdOptions: DeployCommandOptions | undefined,\n globalOptions: GlobalOptions\n): Promise<Deployment> {\n if (!existsSync(deployPath)) {\n throw ShipError.file(`${deployPath} path does not exist`, { filePath: deployPath });\n }\n\n const stats = statSync(deployPath);\n if (!stats.isDirectory() && !stats.isFile()) {\n throw ShipError.file(`${deployPath} path must be a file or directory`, { filePath: deployPath });\n }\n\n const deployOptions: {\n via: string;\n labels?: string[];\n password?: string;\n pathDetect?: boolean;\n spaDetect?: boolean;\n signal?: AbortSignal;\n } = { via: process.env.SHIP_VIA || 'cli' };\n\n // Handle labels\n if (labels !== undefined) deployOptions.labels = labels;\n\n // Empty password strings flow through to the SDK validator (clear length\n // error) instead of being silently dropped.\n if (password !== undefined) deployOptions.password = password;\n\n // Handle detection flags\n if (cmdOptions?.noPathDetect !== undefined) {\n deployOptions.pathDetect = !cmdOptions.noPathDetect;\n }\n if (cmdOptions?.noSpaDetect !== undefined) {\n deployOptions.spaDetect = !cmdOptions.noSpaDetect;\n }\n\n // Cancellation support\n const abortController = new AbortController();\n deployOptions.signal = abortController.signal;\n\n // Spinner (TTY only, not JSON, not --no-color)\n let spinner: Spinner | null = null;\n if (process.stdout.isTTY && !globalOptions.json && !globalOptions.quiet && !globalOptions.noColor) {\n const { default: yoctoSpinner } = await import('yocto-spinner');\n spinner = yoctoSpinner({ text: 'uploading…' }).start();\n }\n\n const sigintHandler = () => {\n abortController.abort();\n if (spinner) spinner.stop();\n process.exit(130);\n };\n process.on('SIGINT', sigintHandler);\n\n try {\n return await client.deployments.upload(deployPath, deployOptions);\n } finally {\n process.removeListener('SIGINT', sigintHandler);\n if (spinner) spinner.stop();\n }\n}\n\n\n\nprogram\n .name('ship')\n .description('🚀 Deploy static sites with simplicity')\n .version(packageJson.version, '--version', 'Show version information')\n .option('--token <token>', 'Any ship token: API key (ship-…) or deploy token (deploy-…)')\n .option('--config <file>', 'Custom config file path')\n .option('--api-url <url>', 'API URL (for development)')\n .option('--json', 'Output results in JSON format')\n .option('-q, --quiet', 'Output only the resource identifier')\n .option('--no-color', 'Disable colored output')\n .option('--help', 'Display help for command')\n .helpOption(false); // Disable default help\n\n// Handle --help flag manually to show custom help\nprogram.hook('preAction', (thisCommand) => {\n const options = processOptions(thisCommand);\n if (options.help) {\n displayHelp(options.noColor);\n process.exit(0);\n }\n});\n\n// Validate options early - before any action is executed\nprogram.hook('preAction', (thisCommand) => {\n const options = processOptions(thisCommand);\n\n try {\n if (options.token && typeof options.token === 'string') {\n validateToken(options.token);\n }\n\n if (options.apiUrl && typeof options.apiUrl === 'string') {\n validateApiUrl(options.apiUrl);\n }\n } catch (validationError) {\n if (isShipError(validationError)) {\n error(validationError.message, options.json, options.noColor);\n process.exit(1);\n }\n throw validationError;\n }\n});\n\n// Ping command\nprogram\n .command('ping')\n .description('Check API connectivity')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.ping()));\n\n// Whoami shortcut - alias for account get\nprogram\n .command('whoami')\n .description('Get current account information')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions) => client.whoami(),\n { operation: 'get', resourceType: 'Account' }\n ));\n\n// Deployments commands\nconst deploymentsCmd = program\n .command('deployments')\n .description('Manage deployments')\n .enablePositionalOptions()\n .action(handleUnknownSubcommand('deployments', ['list', 'upload', 'get', 'set', 'remove']));\n\ndeploymentsCmd\n .command('list')\n .description('List all deployments')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.deployments.list()));\n\ndeploymentsCmd\n .command('upload <path>')\n .description('Upload deployment from file or directory')\n .passThroughOptions()\n .option('--label <label>', 'Label to add (can be repeated)', collect, [])\n .option('--password <password>', 'Password-protect this deployment')\n .option('--no-path-detect', 'Disable automatic path optimization and flattening')\n .option('--no-spa-detect', 'Disable automatic SPA detection and configuration')\n .action(withErrorHandling(\n (client: Ship, options: GlobalOptions, deployPath: string, cmdOptions: DeployCommandOptions) =>\n performDeploy(\n client,\n deployPath,\n mergeLabelOption(cmdOptions, program.opts() as LabelOptions),\n mergePasswordOption(cmdOptions, program.opts() as { password?: string }),\n cmdOptions,\n options,\n ),\n { operation: 'upload' }\n ));\n\ndeploymentsCmd\n .command('get <deployment>')\n .description('Show deployment information')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, deployment: string) => client.deployments.get(deployment),\n { operation: 'get', resourceType: 'Deployment', getResourceId: (id: string) => id }\n ));\n\ndeploymentsCmd\n .command('set <deployment>')\n .description('Set deployment labels')\n .passThroughOptions()\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(withErrorHandling(\n async (client: Ship, _options: GlobalOptions, deployment: string, cmdOptions: LabelOptions) => {\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions) || [];\n return client.deployments.set(deployment, { labels });\n },\n { operation: 'set', resourceType: 'Deployment', getResourceId: (deployment: string) => deployment }\n ));\n\ndeploymentsCmd\n .command('remove <deployment>')\n .description('Delete deployment permanently')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, deployment: string) => client.deployments.remove(deployment),\n { operation: 'remove', resourceType: 'Deployment', getResourceId: (deployment: string) => deployment }\n ));\n\n// Domains commands\nconst domainsCmd = program\n .command('domains')\n .description('Manage domains')\n .enablePositionalOptions()\n .action(handleUnknownSubcommand('domains', ['list', 'get', 'set', 'validate', 'records', 'dns', 'share', 'verify', 'remove']));\n\ndomainsCmd\n .command('list')\n .description('List all domains')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.domains.list()));\n\ndomainsCmd\n .command('get <name>')\n .description('Show domain information')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.get(name),\n { operation: 'get', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('validate <name>')\n .description('Check if domain name is valid and available')\n .action(withErrorHandling(\n async (client: Ship, _options: GlobalOptions, name: string) => {\n const result = await client.domains.validate(name);\n if (!result.valid) process.exitCode = 1;\n return result;\n },\n { operation: 'validate', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('verify <name>')\n .description('Trigger DNS verification for external domain')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.verify(name),\n { operation: 'verify', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('records <name>')\n .description('Show required DNS records for domain setup')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.records(name),\n { operation: 'records', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('dns <name>')\n .description('Look up DNS provider for a domain')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.dns(name),\n { operation: 'dns', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('share <name>')\n .description('Get shareable DNS setup link')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.share(name),\n { operation: 'share', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('set <name> [deployment]')\n .description('Create domain, link to deployment, or update labels')\n .passThroughOptions()\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(withErrorHandling(\n async (client: Ship, _options: GlobalOptions, name: string, deployment: string | undefined, cmdOptions: LabelOptions) => {\n // Read deployment from stdin when piped (e.g., ship ./dist -q | ship domains set mysite.com)\n if (!deployment && !process.stdin.isTTY) {\n deployment = await new Promise<string | undefined>(resolve => {\n let data = '';\n process.stdin.on('data', chunk => data += chunk);\n process.stdin.on('end', () => resolve(data.trim() || undefined));\n });\n }\n\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions);\n\n const setOptions: { deployment?: string; labels?: string[] } = {};\n if (deployment) setOptions.deployment = deployment;\n if (labels !== undefined) setOptions.labels = labels;\n\n // SDK returns DomainSetResult (Domain + isCreate derived from HTTP 201/200) —\n // the resource interface in @shipstatic/types declares this directly, no cast needed.\n const result = await client.domains.set(name, setOptions);\n\n // Enrich with DNS info for new external domains (pure formatter will display it)\n if (result.isCreate && name.includes('.')) {\n try {\n const [records, share] = await Promise.all([\n client.domains.records(name),\n client.domains.share(name)\n ]);\n return {\n ...result,\n _dnsRecords: records.records,\n _shareHash: share.hash\n };\n } catch {\n // Graceful degradation - return without DNS info\n }\n }\n return result;\n },\n { operation: 'set', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\ndomainsCmd\n .command('remove <name>')\n .description('Delete domain permanently')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.remove(name),\n { operation: 'remove', resourceType: 'Domain', getResourceId: (name: string) => name }\n ));\n\n// Tokens commands\nconst tokensCmd = program\n .command('tokens')\n .description('Manage deploy tokens')\n .enablePositionalOptions()\n .action(handleUnknownSubcommand('tokens', ['list', 'create', 'remove']));\n\ntokensCmd\n .command('list')\n .description('List all tokens')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.tokens.list()));\n\ntokensCmd\n .command('create')\n .description('Create a new deploy token')\n .option('--ttl <seconds>', 'Time to live in seconds (default: never expires)', parseInt)\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, cmdOptions: TokenCreateCommandOptions) => {\n const options: { ttl?: number; labels?: string[] } = {};\n if (cmdOptions?.ttl !== undefined) options.ttl = cmdOptions.ttl;\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions);\n if (labels !== undefined) options.labels = labels;\n return client.tokens.create(options);\n },\n { operation: 'create', resourceType: 'Token' }\n ));\n\ntokensCmd\n .command('remove <token>')\n .description('Delete token permanently')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions, token: string) => client.tokens.remove(token),\n { operation: 'remove', resourceType: 'Token', getResourceId: (token: string) => token }\n ));\n\n// Account commands\nconst accountCmd = program\n .command('account')\n .description('Manage account')\n .action(handleUnknownSubcommand('account', ['get']));\n\naccountCmd\n .command('get')\n .description('Show account information')\n .action(withErrorHandling(\n (client: Ship, _options: GlobalOptions) => client.whoami(),\n { operation: 'get', resourceType: 'Account' }\n ));\n\n// Completion commands\nconst completionCmd = program\n .command('completion')\n .description('Setup shell completion')\n .action(handleUnknownSubcommand('completion', ['install', 'uninstall']));\n\ncompletionCmd\n .command('install')\n .description('Install shell completion script')\n .action(() => {\n const options = processOptions(program);\n const scriptDir = path.resolve(__dirname, 'completions');\n installCompletion(scriptDir, { json: options.json, noColor: options.noColor });\n });\n\ncompletionCmd\n .command('uninstall')\n .description('Uninstall shell completion script')\n .action(() => {\n const options = processOptions(program);\n uninstallCompletion({ json: options.json, noColor: options.noColor });\n });\n\n// Config command\nprogram\n .command('config')\n .description('Save your token')\n .action(async () => {\n const options = processOptions(program);\n try {\n await runConfig({ noColor: options.noColor, json: options.json });\n } catch (err) {\n handleError(err);\n }\n });\n\n\n// Deploy shortcut as default action\nprogram\n .argument('[path]', 'Path to deploy')\n .option('--label <label>', 'Label to add (can be repeated)', collect, [])\n .option('--password <password>', 'Password-protect this deployment')\n .option('--no-path-detect', 'Disable automatic path optimization and flattening')\n .option('--no-spa-detect', 'Disable automatic SPA detection and configuration')\n .action(withErrorHandling(\n async (client: Ship, options: GlobalOptions, deployPath?: string, cmdOptions?: DeployCommandOptions) => {\n if (!deployPath) {\n displayHelp(options.noColor);\n process.exit(0);\n }\n\n // Check if the argument is a valid path by checking filesystem\n // This correctly handles paths like \"dist\", \"build\", \"public\" without slashes\n if (!existsSync(deployPath)) {\n // Path doesn't exist - could be unknown command or typo\n // Check if it looks like a command (no path separators, no extension)\n const looksLikeCommand = !deployPath.includes('/') && !deployPath.includes('\\\\') &&\n !deployPath.includes('.') && !deployPath.startsWith('~');\n if (looksLikeCommand) {\n throw ShipError.validation(`unknown command '${deployPath}'`);\n }\n // Otherwise let performDeploy handle the \"path does not exist\" error\n }\n\n return performDeploy(\n client,\n deployPath,\n mergeLabelOption(cmdOptions, program.opts() as LabelOptions),\n mergePasswordOption(cmdOptions, program.opts() as { password?: string }),\n cmdOptions,\n options,\n );\n },\n { operation: 'upload' }\n ));\n\n\n\n/**\n * Simple completion handler - no self-invocation, just static completions\n */\nfunction handleCompletion() {\n const args = process.argv;\n const isBash = args.includes('--compbash');\n const isZsh = args.includes('--compzsh');\n const isFish = args.includes('--compfish');\n\n if (!isBash && !isZsh && !isFish) return;\n\n const completions = ['ping', 'whoami', 'deployments', 'domains', 'tokens', 'account', 'config', 'completion'];\n console.log(completions.join(isFish ? '\\n' : ' '));\n process.exit(0);\n}\n\n// Handle completion requests (before any other processing)\nif (process.env.NODE_ENV !== 'test' && (process.argv.includes('--compbash') || process.argv.includes('--compzsh') || process.argv.includes('--compfish'))) {\n handleCompletion();\n}\n\n// Handle main CLI parsing\nif (process.env.NODE_ENV !== 'test') {\n try {\n program.parse(process.argv);\n } catch (err) {\n // Commander.js errors are already handled by exitOverride above\n // This catch is for safety - check if it's a Commander error\n if (err instanceof Error && 'code' in err) {\n const code = (err as Error & { code?: string }).code;\n const exitCode = (err as Error & { exitCode?: number }).exitCode;\n if (code?.startsWith('commander.')) {\n process.exit(exitCode || 1);\n }\n }\n throw err;\n }\n}","/**\n * Simple CLI utilities following \"impossible simplicity\" mantra\n */\nimport columnify from 'columnify';\nimport { bold, dim, green, red, yellow, blue, inverse, hidden } from 'yoctocolors';\n\nconst INTERNAL_FIELDS = ['isCreate', 'claim'];\n\nconst applyColor = (colorFn: (text: string) => string, text: string, noColor?: boolean): string => {\n return noColor ? text : colorFn(text);\n};\n\n// Wire messages are displayed verbatim — identifiers, paths, and acronyms\n// must survive formatting. The CLI's lowercase opening applies to the leading\n// sentence word only, and only when it's an ordinary capitalized word (never\n// \"DNS\", a quoted key, or a path).\nconst decapitalize = (msg: string): string =>\n /^[A-Z][a-z]/.test(msg) ? msg.charAt(0).toLowerCase() + msg.slice(1) : msg;\n\n/**\n * Message helper functions for consistent CLI output\n */\nexport const success = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(JSON.stringify({ success: msg }, null, 2) + '\\n');\n } else {\n console.log(`${applyColor(green, decapitalize(msg).replace(/\\.$/, ''), noColor)}\\n`);\n }\n};\n\nexport const error = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.error(JSON.stringify({ error: msg }, null, 2) + '\\n');\n } else {\n const errorPrefix = applyColor((text) => inverse(red(text)), `${applyColor(hidden, '[', noColor)}error${applyColor(hidden, ']', noColor)}`, noColor);\n const errorMsg = applyColor(red, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.error(`${errorPrefix} ${errorMsg}\\n`);\n }\n};\n\nexport const warn = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(JSON.stringify({ warning: msg }, null, 2) + '\\n');\n } else {\n const warnPrefix = applyColor((text) => inverse(yellow(text)), `${applyColor(hidden, '[', noColor)}warning${applyColor(hidden, ']', noColor)}`, noColor);\n const warnMsg = applyColor(yellow, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.log(`${warnPrefix} ${warnMsg}\\n`);\n }\n};\n\nexport const info = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(JSON.stringify({ info: msg }, null, 2) + '\\n');\n } else {\n const infoPrefix = applyColor((text) => inverse(blue(text)), `${applyColor(hidden, '[', noColor)}info${applyColor(hidden, ']', noColor)}`, noColor);\n const infoMsg = applyColor(blue, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.log(`${infoPrefix} ${infoMsg}\\n`);\n }\n};\n\n\n/**\n * Format unix timestamp to ISO 8601 string without milliseconds, or return '-' if not provided\n */\nexport const formatTimestamp = (timestamp?: number, context: 'table' | 'details' = 'details', noColor?: boolean): string => {\n if (timestamp === undefined || timestamp === null || timestamp === 0) {\n return '-';\n }\n \n const isoString = new Date(timestamp * 1000).toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n \n // Hide the T and Z characters only in table/list views for cleaner appearance\n if (context === 'table') {\n return isoString.replace(/T/, applyColor(hidden, 'T', noColor)).replace(/Z$/, applyColor(hidden, 'Z', noColor));\n }\n \n return isoString;\n};\n\n/**\n * Format value for display.\n * Handles timestamps, file sizes, and boolean configs with special formatting.\n */\nconst formatValue = (key: string, value: unknown, context: 'table' | 'details' = 'details', noColor?: boolean): string => {\n if (value === null || (Array.isArray(value) && value.length === 0)) return '-';\n if (typeof value === 'number' && (key === 'created' || key === 'activated' || key === 'expires' || key === 'linked' || key === 'grace')) {\n return formatTimestamp(value, context, noColor);\n }\n if (key === 'size' && typeof value === 'number') {\n const mb = value / (1024 * 1024);\n return mb >= 1 ? `${mb.toFixed(1)}Mb` : `${(value / 1024).toFixed(1)}Kb`;\n }\n // Boolean signal columns (config, password) render as yes/no in details.\n if (key === 'config' || key === 'password') {\n if (typeof value === 'boolean') return value ? 'yes' : 'no';\n if (typeof value === 'number') return value === 1 ? 'yes' : 'no';\n }\n return String(value);\n};\n\n/**\n * Format data as table with specified columns for easy parsing.\n * @param data - Array of objects to display as table rows\n * @param columns - Optional column order (defaults to first item's keys)\n * @param noColor - Disable colors\n * @param headerMap - Optional mapping of property names to display headers\n */\nexport const formatTable = (data: object[], columns?: string[], noColor?: boolean, headerMap?: Record<string, string>): string => {\n if (!data || data.length === 0) return '';\n\n // Get column order from first item (preserves API order) or use provided columns\n const firstItem = data[0] as Record<string, unknown>;\n const columnOrder = columns || Object.keys(firstItem).filter(key =>\n firstItem[key] !== undefined && !INTERNAL_FIELDS.includes(key)\n );\n\n // Transform data preserving column order\n const transformedData = data.map(item => {\n const record = item as Record<string, unknown>;\n const transformed: Record<string, string> = {};\n columnOrder.forEach(col => {\n if (col in record && record[col] !== undefined) {\n transformed[col] = formatValue(col, record[col], 'table', noColor);\n }\n });\n return transformed;\n });\n\n const output = columnify(transformedData, {\n columnSplitter: ' ',\n columns: columnOrder,\n config: columnOrder.reduce<Record<string, { headingTransform: (h: string) => string }>>((config, col) => {\n config[col] = {\n headingTransform: (heading: string) => applyColor(dim, headerMap?.[heading] || heading, noColor)\n };\n return config;\n }, {})\n });\n \n // Clean output: remove null bytes and ensure clean spacing\n return output\n .split('\\n')\n .map((line: string) => line\n .replace(/\\0/g, '') // Remove any null bytes\n .replace(/\\s+$/, '') // Remove trailing spaces\n )\n .join('\\n') + '\\n';\n};\n\n/**\n * Format object properties as key-value pairs with space separation for readability.\n * @param obj - Object to display as key-value pairs\n * @param noColor - Disable colors\n */\nexport const formatDetails = (obj: object, noColor?: boolean): string => {\n const entries = (Object.entries(obj) as [string, unknown][]).filter(([key, value]) => {\n if (INTERNAL_FIELDS.includes(key)) return false;\n return value !== undefined;\n });\n \n if (entries.length === 0) return '';\n \n // Transform to columnify format while preserving order\n const data = entries.map(([key, value]) => ({\n property: key + ':',\n value: formatValue(key, value, 'details', noColor)\n }));\n \n const output = columnify(data, {\n columnSplitter: ' ',\n showHeaders: false,\n config: {\n property: { \n dataTransform: (value: string) => applyColor(dim, value, noColor)\n }\n }\n });\n \n // Clean output: remove null bytes and ensure clean spacing\n return output\n .split('\\n')\n .map((line: string) => line.replace(/\\0/g, '')) // Remove any null bytes\n .join('\\n') + '\\n';\n};\n\n","/**\n * Pure formatting functions for CLI output.\n * All formatters are synchronous and have no side effects beyond console output.\n */\nimport type {\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n Domain,\n DomainListResponse,\n DomainValidateResponse,\n DomainRecordsResponse,\n DomainDnsResponse,\n Account,\n TokenCreateResponse,\n TokenListResponse\n} from '@shipstatic/types';\nimport type { EnrichedDomain, DomainShareResponse, MessageResult, CLIResult } from './types.js';\nimport { formatTable, formatDetails, success, error, info } from './utils.js';\n\nconst setupUrl = (hash: string, domain: string) => `https://setup.shipstatic.com/${hash}/${domain}`;\n\nexport interface OutputContext {\n operation?: string;\n resourceType?: string;\n resourceId?: string;\n}\n\nexport interface FormatOptions {\n json?: boolean;\n quiet?: boolean;\n noColor?: boolean;\n}\n\n/**\n * Format deployments list\n */\nexport function formatDeploymentsList(result: DeploymentListResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (result.deployments.length === 0) {\n console.log('no deployments found');\n console.log();\n return;\n }\n\n const columns = ['deployment', 'labels', 'files', 'size', 'created', 'via'];\n console.log(formatTable(result.deployments, columns, noColor));\n}\n\n/**\n * Format domains list\n */\nexport function formatDomainsList(result: DomainListResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (result.domains.length === 0) {\n console.log('no domains found');\n console.log();\n return;\n }\n\n const columns = ['domain', 'deployment', 'labels', 'linked', 'links', 'created'];\n console.log(formatTable(result.domains, columns, noColor));\n}\n\n/**\n * Format single domain result.\n * Accepts plain Domain (from get) or EnrichedDomain (from set, with DNS info).\n */\nexport function formatDomain(result: Domain | EnrichedDomain, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n // Destructure enrichment fields (undefined when result is plain Domain)\n const { _dnsRecords, _shareHash, isCreate, ...displayResult } = result as EnrichedDomain;\n\n // Show success message for set operations\n if (context.operation === 'set') {\n const verb = isCreate ? 'created' : 'updated';\n success(`${result.url} domain ${verb}`, false, noColor);\n }\n\n // Display pre-fetched DNS records (for new external domains)\n if (_dnsRecords && _dnsRecords.length > 0) {\n console.log();\n info('DNS Records to configure:', false, noColor);\n _dnsRecords.forEach((record) => {\n console.log(` ${record.type}: ${record.name} → ${record.value}`);\n });\n }\n\n // Display setup instructions link\n if (_shareHash) {\n console.log();\n info(`Setup instructions: ${setupUrl(_shareHash, result.domain)}`, false, noColor);\n }\n\n console.log(formatDetails(displayResult, noColor));\n}\n\n/**\n * Format single deployment result\n */\nexport function formatDeployment(result: Deployment | DeploymentCreateResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n // Show success message for upload operations\n if (context.operation === 'upload') {\n success(`${result.url} deployment uploaded`, false, noColor);\n }\n\n console.log(formatDetails(result, noColor));\n\n // Public deployment — claim URL + CTA after details\n const claim = (result as DeploymentCreateResponse).claim;\n if (claim) {\n const days = result.expires ? Math.round((result.expires - result.created) / 86400) : null;\n console.log(`IMPORTANT: this deployment${days ? ` expires in ${days} day${days !== 1 ? 's' : ''}` : ' will expire'}, claim it to keep permanently:\\n${claim}\\n`);\n info(`configure a free API key with 'ship config' to deploy to your own account`, false, noColor);\n }\n}\n\n/**\n * Format account/email result\n */\nexport function formatAccount(result: Account, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n console.log(formatDetails(result, noColor));\n}\n\n/**\n * Format message result (e.g., from DNS verification)\n */\nexport function formatMessage(result: MessageResult, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n if (result.message) {\n success(result.message, false, noColor);\n }\n}\n\n/**\n * Format domain validation result\n */\nexport function formatDomainValidate(result: DomainValidateResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (result.valid) {\n success(`domain is valid`, false, noColor);\n console.log();\n if (result.normalized) {\n console.log(` normalized: ${result.normalized}`);\n }\n if (result.available !== null) {\n const availabilityText = result.available ? (noColor ? 'available' : 'available ✓') : 'already taken';\n console.log(` availability: ${availabilityText}`);\n }\n console.log();\n } else {\n error(result.error || 'domain is invalid', false, noColor);\n }\n}\n\n/**\n * Format domain DNS records result\n */\nexport function formatDomainRecords(result: DomainRecordsResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (result.records.length === 0) {\n console.log('no records found');\n console.log();\n return;\n }\n\n const columns = ['type', 'name', 'value'];\n console.log(formatTable(result.records, columns, noColor));\n}\n\n/**\n * Format domain DNS provider result\n */\nexport function formatDomainDns(result: DomainDnsResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n const provider = result.dns?.provider?.name || null;\n console.log(formatDetails({ domain: result.domain, provider }, noColor));\n}\n\n/**\n * Format domain share result as setup URL\n */\nexport function formatDomainShare(result: DomainShareResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n success(setupUrl(result.hash, result.domain), false, noColor);\n}\n\n/**\n * Format tokens list\n */\nexport function formatTokensList(result: TokenListResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (result.tokens.length === 0) {\n console.log('no tokens found');\n console.log();\n return;\n }\n\n const columns = ['token', 'labels', 'created', 'expires'];\n console.log(formatTable(result.tokens, columns, noColor));\n}\n\n/**\n * Format single token result (creation response includes both token ID and secret)\n */\nexport function formatToken(result: TokenCreateResponse, context: OutputContext, options: FormatOptions): void {\n const { noColor } = options;\n\n if (context.operation === 'create' && result.token) {\n success(`token ${result.token} created`, false, noColor);\n }\n\n console.log(formatDetails(result, noColor));\n}\n\n/**\n * Main output function - routes to appropriate formatter based on result shape.\n * Handles JSON mode, removal operations, and ping results.\n */\nexport function formatOutput(\n result: CLIResult,\n context: OutputContext,\n options: FormatOptions\n): void {\n const { json, quiet, noColor } = options;\n\n // Quiet mode: output only the key identifier\n if (quiet) {\n if (result === undefined || typeof result === 'boolean') return;\n if (result !== null && typeof result === 'object') {\n if ('deployments' in result) {\n (result as DeploymentListResponse).deployments.forEach(d => console.log(d.deployment));\n } else if ('domains' in result) {\n (result as DomainListResponse).domains.forEach(d => console.log(d.domain));\n } else if ('tokens' in result) {\n (result as TokenListResponse).tokens.forEach(t => console.log(t.token));\n } else if ('records' in result) {\n (result as DomainRecordsResponse).records.forEach(r => console.log(`${r.type} ${r.name} ${r.value}`));\n } else if ('hash' in result) {\n const r = result as DomainShareResponse;\n console.log(setupUrl(r.hash, r.domain));\n } else if ('dns' in result) {\n const name = (result as DomainDnsResponse).dns?.provider?.name;\n if (name) console.log(name);\n } else if ('domain' in result) {\n console.log((result as Domain).domain);\n } else if ('deployment' in result) {\n console.log((result as Deployment).deployment);\n } else if ('secret' in result) {\n console.log((result as TokenCreateResponse).secret);\n } else if ('email' in result) {\n console.log((result as Account).email);\n } else if ('valid' in result) {\n const v = result as DomainValidateResponse;\n if (v.valid && v.normalized) console.log(v.normalized);\n } else if ('message' in result) {\n console.log((result as MessageResult).message);\n }\n }\n return;\n }\n\n // Handle void/undefined results (removal operations)\n if (result === undefined) {\n if (context.operation === 'remove' && context.resourceType && context.resourceId) {\n success(`${context.resourceId} ${context.resourceType.toLowerCase()} removed`, json, noColor);\n } else {\n success('removed successfully', json, noColor);\n }\n return;\n }\n\n // Handle ping result (boolean from client.ping())\n if (typeof result === 'boolean') {\n if (result) {\n success('api reachable', json, noColor);\n } else {\n error('api unreachable', json, noColor);\n }\n return;\n }\n\n // JSON mode: output raw JSON for all results\n if (json && result !== null && typeof result === 'object') {\n // Filter internal fields from JSON output\n const output = { ...result } as Record<string, unknown>;\n delete output._dnsRecords;\n delete output._shareHash;\n delete output.isCreate;\n console.log(JSON.stringify(output, null, 2));\n console.log();\n return;\n }\n\n // Route to specific formatter based on result shape\n // Order matters: check list types before singular types\n if (result !== null && typeof result === 'object') {\n if ('deployments' in result) {\n formatDeploymentsList(result as DeploymentListResponse, context, options);\n } else if ('domains' in result) {\n formatDomainsList(result as DomainListResponse, context, options);\n } else if ('tokens' in result) {\n formatTokensList(result as TokenListResponse, context, options);\n } else if ('records' in result) {\n formatDomainRecords(result as DomainRecordsResponse, context, options);\n } else if ('hash' in result) {\n formatDomainShare(result as DomainShareResponse, context, options);\n } else if ('dns' in result) {\n formatDomainDns(result as DomainDnsResponse, context, options);\n } else if ('domain' in result) {\n formatDomain(result as Domain, context, options);\n } else if ('deployment' in result) {\n formatDeployment(result as Deployment, context, options);\n } else if ('token' in result) {\n formatToken(result as TokenCreateResponse, context, options);\n } else if ('email' in result) {\n formatAccount(result as Account, context, options);\n } else if ('valid' in result) {\n formatDomainValidate(result as DomainValidateResponse, context, options);\n } else if ('message' in result) {\n formatMessage(result as MessageResult, context, options);\n } else {\n // Fallback\n success('success', json, noColor);\n }\n } else {\n // Fallback for non-object results\n success('success', json, noColor);\n }\n}\n","/**\n * Shell completion install/uninstall logic.\n * Handles bash, zsh, and fish shells.\n */\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { success, error, info, warn } from './utils.js';\n\nexport interface CompletionOptions {\n json?: boolean;\n noColor?: boolean;\n}\n\n/**\n * Detect current shell from environment\n */\nfunction detectShell(): 'bash' | 'zsh' | 'fish' | null {\n const shell = process.env.SHELL || '';\n if (shell.includes('bash')) return 'bash';\n if (shell.includes('zsh')) return 'zsh';\n if (shell.includes('fish')) return 'fish';\n return null;\n}\n\n/**\n * Get shell-specific paths\n */\nfunction getShellPaths(shell: 'bash' | 'zsh' | 'fish', homeDir: string) {\n switch (shell) {\n case 'bash':\n return {\n completionFile: path.join(homeDir, '.ship_completion.bash'),\n profileFile: path.join(homeDir, '.bash_profile'),\n scriptName: 'ship.bash'\n };\n case 'zsh':\n return {\n completionFile: path.join(homeDir, '.ship_completion.zsh'),\n profileFile: path.join(homeDir, '.zshrc'),\n scriptName: 'ship.zsh'\n };\n case 'fish':\n return {\n completionFile: path.join(homeDir, '.config/fish/completions/ship.fish'),\n profileFile: null, // fish doesn't need profile sourcing\n scriptName: 'ship.fish'\n };\n }\n}\n\n/**\n * Install shell completion script\n */\nexport function installCompletion(scriptDir: string, options: CompletionOptions = {}): void {\n const { json, noColor } = options;\n const shell = detectShell();\n const homeDir = os.homedir();\n\n if (!shell) {\n error(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`, json, noColor);\n return;\n }\n\n const paths = getShellPaths(shell, homeDir);\n const sourceScript = path.join(scriptDir, paths.scriptName);\n\n try {\n // Fish has a different installation pattern\n if (shell === 'fish') {\n const fishDir = path.dirname(paths.completionFile);\n if (!fs.existsSync(fishDir)) {\n fs.mkdirSync(fishDir, { recursive: true });\n }\n fs.copyFileSync(sourceScript, paths.completionFile);\n success('fish completion installed successfully', json, noColor);\n info('please restart your shell to apply the changes', json, noColor);\n return;\n }\n\n // Bash and zsh: copy script and add sourcing to profile\n fs.copyFileSync(sourceScript, paths.completionFile);\n const sourceLine = `# ship\\nsource '${paths.completionFile}'\\n# ship end`;\n\n if (paths.profileFile) {\n if (fs.existsSync(paths.profileFile)) {\n const content = fs.readFileSync(paths.profileFile, 'utf-8');\n if (!content.includes('# ship') || !content.includes('# ship end')) {\n const prefix = content.length > 0 && !content.endsWith('\\n') ? '\\n' : '';\n fs.appendFileSync(paths.profileFile, prefix + sourceLine);\n }\n } else {\n fs.writeFileSync(paths.profileFile, sourceLine);\n }\n\n success(`completion script installed for ${shell}`, json, noColor);\n warn(`run \"source ${paths.profileFile}\" or restart your shell`, json, noColor);\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n error(`could not install completion script: ${message}`, json, noColor);\n }\n}\n\n/**\n * Uninstall shell completion script\n */\nexport function uninstallCompletion(options: CompletionOptions = {}): void {\n const { json, noColor } = options;\n const shell = detectShell();\n const homeDir = os.homedir();\n\n if (!shell) {\n error(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`, json, noColor);\n return;\n }\n\n const paths = getShellPaths(shell, homeDir);\n\n try {\n // Fish: just remove the file\n if (shell === 'fish') {\n if (fs.existsSync(paths.completionFile)) {\n fs.unlinkSync(paths.completionFile);\n success('fish completion uninstalled successfully', json, noColor);\n } else {\n warn('fish completion was not installed', json, noColor);\n }\n info('please restart your shell to apply the changes', json, noColor);\n return;\n }\n\n // Bash and zsh: remove file and clean profile\n if (fs.existsSync(paths.completionFile)) {\n fs.unlinkSync(paths.completionFile);\n }\n\n if (!paths.profileFile) return;\n\n if (!fs.existsSync(paths.profileFile)) {\n error('profile file not found', json, noColor);\n return;\n }\n\n const content = fs.readFileSync(paths.profileFile, 'utf-8');\n const lines = content.split('\\n');\n\n // Remove ship block (between \"# ship\" and \"# ship end\")\n const filtered: string[] = [];\n let i = 0;\n let removed = false;\n\n while (i < lines.length) {\n if (lines[i].trim() === '# ship') {\n removed = true;\n i++;\n while (i < lines.length && lines[i].trim() !== '# ship end') i++;\n if (i < lines.length) i++; // skip \"# ship end\"\n } else {\n filtered.push(lines[i]);\n i++;\n }\n }\n\n if (removed) {\n const endsWithNewline = content.endsWith('\\n');\n const newContent = filtered.length === 0\n ? ''\n : filtered.join('\\n') + (endsWithNewline ? '\\n' : '');\n fs.writeFileSync(paths.profileFile, newContent);\n success(`completion script uninstalled for ${shell}`, json, noColor);\n warn(`run \"source ${paths.profileFile}\" or restart your shell`, json, noColor);\n } else {\n error('completion was not found in profile', json, noColor);\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n error(`could not uninstall completion script: ${message}`, json, noColor);\n }\n}\n","/**\n * @file Interactive config file creation for `ship config`.\n * Asks for a token, merges into existing ~/.shiprc, preserves all other fields.\n * Uses Node.js built-in readline/promises — zero additional dependencies.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { readFileSync, writeFileSync, existsSync, chmodSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport { DEFAULT_API, validateToken } from '@shipstatic/types';\nimport { dim, green } from 'yoctocolors';\n\n/** Path to the global config file */\nconst CONFIG_PATH = join(homedir(), '.shiprc');\n\n/**\n * Mask a token for display: ship-a1b2...c3d4. A token too short to keep a\n * useful prefix + suffix is masked entirely — never printed verbatim.\n */\nfunction maskToken(token: string): string {\n if (token.length < 13) return '...';\n return token.slice(0, 9) + '...' + token.slice(-4);\n}\n\n/**\n * Read existing config file, preserving all fields.\n * Returns empty object if file doesn't exist or is invalid.\n */\nfunction readExistingConfig(): Record<string, unknown> {\n try {\n if (!existsSync(CONFIG_PATH)) return {};\n return JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'));\n } catch {\n return {};\n }\n}\n\n/**\n * Run the interactive config flow.\n * Asks for a token, merges into existing config, writes ~/.shiprc.\n */\nexport async function runConfig(options: { noColor?: boolean; json?: boolean } = {}): Promise<void> {\n const { noColor, json } = options;\n const applyDim = (text: string) => noColor ? text : dim(text);\n const applyGreen = (text: string) => noColor ? text : green(text);\n\n // JSON mode: show current config status\n if (json) {\n const existing = readExistingConfig();\n const token = typeof existing.token === 'string' ? existing.token : undefined;\n const apiUrl = typeof existing.apiUrl === 'string' ? existing.apiUrl : undefined;\n console.log(JSON.stringify({\n path: CONFIG_PATH,\n exists: existsSync(CONFIG_PATH),\n ...(token ? { token: maskToken(token) } : {}),\n ...(apiUrl && apiUrl !== DEFAULT_API ? { apiUrl } : {}),\n }, null, 2) + '\\n');\n return;\n }\n\n const existing = readExistingConfig();\n const existingToken = typeof existing.token === 'string' ? existing.token : undefined;\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log('');\n console.log(` ${applyDim('Create a free API key at')} https://my.shipstatic.com/api-key`);\n console.log('');\n\n const prompt = existingToken\n ? ` Token (${applyDim(maskToken(existingToken))}): `\n : ' Token: ';\n\n let input: string;\n try {\n input = (await rl.question(prompt)).trim();\n } finally {\n rl.close();\n }\n\n if (input) {\n validateToken(input);\n existing.token = input;\n }\n\n // The file holds a credential: owner-only, like ~/.netrc. `mode` only\n // applies on creation, so chmod repairs files written before this rule.\n writeFileSync(CONFIG_PATH, JSON.stringify(existing, null, 2) + '\\n', { mode: 0o600 });\n chmodSync(CONFIG_PATH, 0o600);\n console.log(`\\n ${applyGreen('saved to')} ${applyDim(CONFIG_PATH)}\\n`);\n}\n","/**\n * @file Base Ship SDK class — shared functionality across environments.\n *\n * The constructor is fully synchronous: an `ApiHttp` instance is built immediately\n * with whatever credentials the caller supplied (and, in Node, env vars merged in\n * by the subclass before `super()`). The only deferred work is the one-shot\n * `GET /limits` fetch that hydrates platform limits — that's lazy and runs on\n * first API call via `ensureInitialized()`.\n *\n * Subclasses only override what genuinely differs per environment:\n * - `processInput()` — Node reads paths from disk; Browser handles `File[]`\n * - `getDeployBodyCreator()` — Node streams Buffers; Browser builds Blobs\n *\n * Everything else (the credential slot, resources, events, lazy platform-limits)\n * lives here.\n */\n\nimport { ShipError, validateToken, validateCaller } from '@shipstatic/types';\nimport type {\n Deployment,\n PlatformLimits,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource,\n StaticFile,\n} from '@shipstatic/types';\n\nimport { ApiHttp } from './api/http.js';\nimport {\n createDeploymentResource,\n createDomainResource,\n createAccountResource,\n createTokenResource,\n type DeployInput,\n} from './resources.js';\nimport type {\n ShipClientOptions,\n ShipEvents,\n DeploymentOptions,\n DeployBodyCreator,\n TokenProvider,\n} from './types.js';\n\n/**\n * Abstract base class for Ship SDK implementations.\n */\nexport abstract class Ship {\n // Resource handles, created once at construction. Each is a thin facade\n // bound to `this.http` plus the lazy-init callback.\n public readonly deployments: DeploymentResource;\n public readonly domains: DomainResource;\n public readonly account: AccountResource;\n public readonly tokens: TokenResource;\n\n // The HTTP client and merged options are private — subclasses interact\n // with the base class through the abstract methods below, never by\n // reaching into these fields. Tests bypass via `(ship as any).http = ...`.\n private readonly http: ApiHttp;\n private readonly clientOptions: ShipClientOptions;\n\n // Lazy-init plumbing for the one-shot `GET /config` fetch.\n // `platformLimits` is INSTANCE state (not a module-level singleton): two\n // Ships against different `apiUrl`s — staging + prod, multi-tenant\n // orchestrators, n8n with multiple credentials — must not clobber each\n // other's limits. Each instance owns its hydrated copy.\n // `protected` so subclasses' `processInput` can pass it down to the\n // platform-specific file-validation utilities.\n private initPromise: Promise<void> | null = null;\n protected platformLimits: PlatformLimits | null = null;\n\n // The credential slot — one platform token (any population) or a provider\n // that supplies one per request. Read dynamically on every request through\n // `getAuthHeaders`, so `setToken` takes effect without rebuilding the client.\n private credential: string | TokenProvider | null = null;\n\n constructor(options: ShipClientOptions = {}) {\n // SDK-boundary normalization: an empty-string token is absence of\n // credential intent, never a credential. Empty strings reach here from\n // shell-expansion of unset CI variables, empty form fields in browser\n // apps, and any other path that produces `''` instead of `undefined`.\n // Normalizing once at the SDK boundary covers every entry point: CLI,\n // Browser SDK, Node SDK, embedded consumers, and direct base-class use.\n options = {\n ...options,\n apiUrl: options.apiUrl || undefined,\n token: options.token || undefined,\n caller: options.caller || undefined,\n };\n this.clientOptions = options;\n\n // Caller identity is validated at the boundary like the token: a value\n // the API would silently drop (the header is unauthenticated) is a\n // configuration error here, never a quiet fallback to IP bucketing.\n if (options.caller !== undefined) {\n validateCaller(options.caller);\n }\n\n // One client, one identity. A token and a cookie session are different\n // principals — holding both is a configuration error, not a precedence\n // question.\n if (options.token && options.session) {\n throw ShipError.config('Provide either `token` or `session`, not both.');\n }\n\n // Static tokens are validated at the boundary (prefix-classified, same\n // rules the server applies); providers are invoked per request instead.\n if (typeof options.token === 'string') {\n validateToken(options.token);\n this.credential = options.token;\n } else if (options.token) {\n this.credential = options.token;\n }\n\n // Build the HTTP client once. The `getAuthHeaders` callback reads\n // `this.credential` dynamically on every request.\n this.http = new ApiHttp({\n ...options,\n getAuthHeaders: () => this.getAuthHeaders(),\n createDeployBody: this.getDeployBodyCreator(),\n });\n\n const ctx = {\n getApi: () => this.http,\n ensureInit: () => this.ensureInitialized(),\n };\n\n this.deployments = createDeploymentResource({\n ...ctx,\n processInput: (input, opts) => this.processInput(input, opts),\n clientDefaults: this.clientOptions,\n });\n this.domains = createDomainResource(ctx);\n this.account = createAccountResource(ctx);\n this.tokens = createTokenResource(ctx);\n }\n\n // Environment-specific behavior.\n protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;\n protected abstract getDeployBodyCreator(): DeployBodyCreator;\n\n /**\n * Lazy initialization — fetches platform limits (file size / count caps) once,\n * on the first API call. Subsequent calls reuse the resolved promise.\n */\n protected async ensureInitialized(): Promise<void> {\n if (!this.initPromise) {\n this.initPromise = this.fetchPlatformLimits();\n }\n return this.initPromise;\n }\n\n private async fetchPlatformLimits(): Promise<void> {\n try {\n this.platformLimits = await this.http.getLimits();\n } catch (error) {\n // Reset so the next API call can retry initialization.\n this.initPromise = null;\n throw error;\n }\n }\n\n /**\n * Ping the API server to check connectivity.\n */\n async ping(): Promise<boolean> {\n await this.ensureInitialized();\n return this.http.ping();\n }\n\n /**\n * Deploy project (convenience shortcut to `ship.deployments.upload()`).\n */\n async deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment> {\n return this.deployments.upload(input, options);\n }\n\n /**\n * Get current account information (convenience shortcut to `ship.account.get()`).\n */\n async whoami() {\n return this.account.get();\n }\n\n /**\n * Get platform limits (max file size, file count, total size).\n * Reuses the response fetched during initialization. Per-instance state —\n * does not leak between concurrent Ships against different API URLs.\n */\n async getLimits(): Promise<PlatformLimits> {\n if (this.platformLimits) return this.platformLimits;\n await this.ensureInitialized();\n return this.platformLimits!;\n }\n\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.on(event, handler);\n }\n\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.off(event, handler);\n }\n\n /**\n * Set global headers included in every request.\n * Useful for injecting custom headers (e.g. for admin impersonation).\n */\n setHeaders(headers: Record<string, string>): void {\n this.http.setGlobalHeaders(headers);\n }\n\n /**\n * Clear all custom global headers.\n */\n clearHeaders(): void {\n this.http.setGlobalHeaders({});\n }\n\n /**\n * Sets the client token — any platform token (API key, deploy token, OAuth\n * access token) or a {@link TokenProvider} invoked per request. Replaces\n * whatever credential the client held before.\n * @param token A platform token, sent verbatim, or a provider function\n */\n public setToken(token: string | TokenProvider): void {\n // One client, one identity — the constructor's token/session exclusion\n // holds for the client's whole life, not just its first moment.\n if (this.clientOptions.session) {\n throw ShipError.config('Provide either `token` or `session`, not both.');\n }\n if (typeof token === 'string') {\n if (!token) {\n throw ShipError.business('Invalid token provided. Token must be a non-empty string.');\n }\n validateToken(token);\n this.credential = token;\n return;\n }\n if (typeof token !== 'function') {\n throw ShipError.business('Invalid token provided. Token must be a non-empty string or a provider function.');\n }\n this.credential = token;\n }\n\n /**\n * Resolve the credential slot into request headers. Async because a\n * provider may mint or refresh its token per request.\n *\n * Anonymity requires proven absence of credentials: a configured provider\n * that yields nothing is an error — the request fails typed rather than\n * silently proceeding as an anonymous public deploy. Empty-string\n * normalization at the constructor is the same invariant's boundary\n * condition: `''` is absence of intent, so it never reaches this point.\n */\n private async getAuthHeaders(): Promise<Record<string, string>> {\n if (this.credential === null) return {};\n const value = typeof this.credential === 'function'\n ? await this.credential()\n : this.credential;\n if (!value) {\n throw ShipError.authentication('Token provider returned no token.');\n }\n if (typeof value !== 'string') {\n throw ShipError.authentication('Token provider returned a non-string value.');\n }\n return { Authorization: `Bearer ${value}` };\n }\n}\n","/**\n * @file HTTP client for Ship API.\n */\nimport type {\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n PingResponse,\n PlatformLimits,\n Domain,\n DomainListResponse,\n DomainDnsResponse,\n DomainRecordsResponse,\n DomainValidateResponse,\n AccountGetResponse,\n SPACheckRequest,\n SPACheckResponse,\n StaticFile,\n TokenCreateResponse,\n TokenListResponse\n} from '@shipstatic/types';\nimport type { ApiDeployOptions, DeployBodyCreator, DomainSetResult, Fetch, ShipClientOptions } from '../types.js';\nimport { ShipError, DEFAULT_API } from '@shipstatic/types';\nimport { SimpleEvents } from '../events.js';\nimport { validateLabels, validatePassword } from '../lib/validation.js';\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst ENDPOINTS = {\n DEPLOYMENTS: '/deployments',\n DOMAINS: '/domains',\n TOKENS: '/tokens',\n ACCOUNT: '/account',\n LIMITS: '/limits',\n PING: '/ping',\n SPA_CHECK: '/spa-check'\n} as const;\n\nconst DEFAULT_REQUEST_TIMEOUT = 30000;\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ApiHttpOptions extends ShipClientOptions {\n /** Resolves the credential slot per request — async so token providers can mint/refresh. */\n getAuthHeaders: () => Record<string, string> | Promise<Record<string, string>>;\n createDeployBody: DeployBodyCreator;\n}\n\ninterface RequestResult<T> {\n data: T;\n status: number;\n}\n\n// =============================================================================\n// HTTP CLIENT\n// =============================================================================\n\nexport class ApiHttp extends SimpleEvents {\n private readonly apiUrl: string;\n private readonly getAuthHeadersCallback: () => Record<string, string> | Promise<Record<string, string>>;\n private readonly session: boolean;\n private readonly caller: string | undefined;\n private readonly timeout: number;\n private readonly fetch: Fetch;\n private readonly createDeployBody: DeployBodyCreator;\n private readonly deployEndpoint: string;\n private globalHeaders: Record<string, string> = {};\n\n constructor(options: ApiHttpOptions) {\n super();\n this.apiUrl = options.apiUrl || DEFAULT_API;\n this.getAuthHeadersCallback = options.getAuthHeaders;\n this.session = options.session ?? false;\n this.caller = options.caller;\n this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;\n // Bind to globalThis when falling back to the platform `fetch` — browsers\n // require `this === window` on `window.fetch` and throw \"Illegal invocation\"\n // when it's invoked as a property of any other object.\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.createDeployBody = options.createDeployBody;\n this.deployEndpoint = options.deployEndpoint || ENDPOINTS.DEPLOYMENTS;\n }\n\n /**\n * Set global headers included in every request.\n * Priority: globalHeaders (lowest) < instance auth < per-request headers (highest)\n */\n setGlobalHeaders(headers: Record<string, string>): void {\n this.globalHeaders = headers;\n }\n\n // ===========================================================================\n // CORE REQUEST INFRASTRUCTURE\n // ===========================================================================\n\n /**\n * Execute HTTP request with timeout, events, and error handling\n */\n private async executeRequest<T>(\n url: string,\n options: RequestInit,\n operationName: string\n ): Promise<RequestResult<T>> {\n let cleanup = () => {};\n\n try {\n // Credential resolution runs inside the error boundary: a token\n // provider that throws or yields nothing fails the request through\n // the same typed path (and `error` event) as any transport failure.\n const headers = await this.mergeHeaders(options.headers as Record<string, string>);\n const timeout = this.createTimeoutSignal(options.signal);\n cleanup = timeout.cleanup;\n\n const fetchOptions: RequestInit = {\n ...options,\n headers,\n credentials: this.session && !headers.Authorization ? 'include' : undefined,\n signal: timeout.signal,\n };\n\n this.emit('request', url, fetchOptions);\n\n const response = await this.fetch(url, fetchOptions);\n cleanup();\n\n if (!response.ok) {\n throw await ShipError.fromHttpResponse(response, operationName);\n }\n\n this.emit('response', this.safeClone(response), url);\n const data = await this.parseResponse<T>(this.safeClone(response));\n return { data, status: response.status };\n } catch (error) {\n cleanup();\n // Normalize anything thrown above (credential resolution, fetch\n // failure, abort, response error) into a ShipError.\n // fromFetchError passes existing ShipErrors through unchanged.\n const shipError = ShipError.fromFetchError(error, operationName);\n this.emit('error', shipError, url);\n throw shipError;\n }\n }\n\n /**\n * Simple request - returns data only\n */\n private async request<T>(url: string, options: RequestInit, operationName: string): Promise<T> {\n const { data } = await this.executeRequest<T>(url, options, operationName);\n return data;\n }\n\n /**\n * Request with status - returns data and HTTP status code\n */\n private async requestWithStatus<T>(url: string, options: RequestInit, operationName: string): Promise<RequestResult<T>> {\n return this.executeRequest<T>(url, options, operationName);\n }\n\n // ===========================================================================\n // REQUEST HELPERS\n // ===========================================================================\n\n private async mergeHeaders(customHeaders: Record<string, string> = {}): Promise<Record<string, string>> {\n // `caller` is instance identity metadata, like the credential: the\n // rate limiter buckets by X-Caller on every write, so it rides every\n // request rather than any single operation.\n return {\n ...this.globalHeaders,\n ...(this.caller ? { 'X-Caller': this.caller } : {}),\n ...(await this.getAuthHeadersCallback()),\n ...customHeaders,\n };\n }\n\n private createTimeoutSignal(existingSignal?: AbortSignal | null): { signal: AbortSignal; cleanup: () => void } {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n if (existingSignal) {\n const abort = () => controller.abort();\n existingSignal.addEventListener('abort', abort);\n if (existingSignal.aborted) controller.abort();\n }\n\n return {\n signal: controller.signal,\n cleanup: () => clearTimeout(timeoutId)\n };\n }\n\n private safeClone(response: Response): Response {\n try {\n return response.clone();\n } catch {\n return response;\n }\n }\n\n private async parseResponse<T>(response: Response): Promise<T> {\n if (response.headers.get('Content-Length') === '0' || response.status === 204) {\n return undefined as T;\n }\n return response.json() as Promise<T>;\n }\n\n // ===========================================================================\n // PUBLIC API - DEPLOYMENTS\n // ===========================================================================\n\n async deploy(files: StaticFile[], options: ApiDeployOptions = {}): Promise<DeploymentCreateResponse> {\n if (!files.length) {\n throw ShipError.business('No files to deploy');\n }\n for (const file of files) {\n if (!file.md5) {\n throw ShipError.file(`MD5 checksum missing for file: ${file.path}`, { filePath: file.path });\n }\n }\n\n // Fast-fail on definitely-invalid input before constructing a multipart body.\n validatePassword(options.password);\n const labels = validateLabels(options.labels);\n\n const flags = (options.build || options.prerender || options.spa)\n ? { build: options.build, prerender: options.prerender, spa: options.spa }\n : undefined;\n const { body, headers: bodyHeaders } = await this.createDeployBody(files, {\n labels,\n via: options.via,\n password: options.password,\n flags,\n captcha: options.captcha,\n });\n\n return this.request<DeploymentCreateResponse>(\n `${this.apiUrl}${this.deployEndpoint}`,\n { method: 'POST', body, headers: bodyHeaders, signal: options.signal || null },\n 'Deploy'\n );\n }\n\n async listDeployments(): Promise<DeploymentListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}`, { method: 'GET' }, 'List deployments');\n }\n\n async getDeployment(id: string): Promise<Deployment> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`, { method: 'GET' }, 'Get deployment');\n }\n\n async updateDeploymentLabels(id: string, labels: string[]): Promise<Deployment> {\n const normalized = validateLabels(labels);\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ labels: normalized }) },\n 'Update deployment labels'\n );\n }\n\n async removeDeployment(id: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'Remove deployment'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - DOMAINS\n // ===========================================================================\n // All domain methods accept FQDN (Fully Qualified Domain Name) as the `name` parameter.\n // The SDK does not validate or normalize - the API handles all domain semantics.\n\n async setDomain(name: string, deployment?: string, labels?: string[]): Promise<DomainSetResult> {\n const normalized = validateLabels(labels);\n const body: { deployment?: string; labels?: string[] } = {};\n if (deployment) body.deployment = deployment;\n if (normalized !== undefined) body.labels = normalized;\n\n const { data, status } = await this.requestWithStatus<Domain>(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Set domain'\n );\n\n return { ...data, isCreate: status === 201 };\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}`, { method: 'GET' }, 'List domains');\n }\n\n async getDomain(name: string): Promise<Domain> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'GET' }, 'Get domain');\n }\n\n async removeDomain(name: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`, { method: 'DELETE' }, 'Remove domain');\n }\n\n async verifyDomain(name: string): Promise<{ message: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/verify`, { method: 'POST' }, 'Verify domain');\n }\n\n async getDomainDns(name: string): Promise<DomainDnsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/dns`, { method: 'GET' }, 'Get domain DNS');\n }\n\n async getDomainRecords(name: string): Promise<DomainRecordsResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/records`, { method: 'GET' }, 'Get domain records');\n }\n\n async getDomainShare(name: string): Promise<{ domain: string; hash: string }> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/share`, { method: 'GET' }, 'Get domain share');\n }\n\n async validateDomain(name: string): Promise<DomainValidateResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/validate`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ domain: name }) },\n 'Validate domain'\n );\n }\n\n // ===========================================================================\n // PUBLIC API - TOKENS\n // ===========================================================================\n\n async createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse> {\n const normalized = validateLabels(labels);\n const body: { ttl?: number; labels?: string[] } = {};\n if (ttl !== undefined) body.ttl = ttl;\n if (normalized !== undefined) body.labels = normalized;\n\n return this.request(\n `${this.apiUrl}${ENDPOINTS.TOKENS}`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'Create token'\n );\n }\n\n async listTokens(): Promise<TokenListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.TOKENS}`, { method: 'GET' }, 'List tokens');\n }\n\n async removeToken(token: string): Promise<void> {\n await this.request<void>(`${this.apiUrl}${ENDPOINTS.TOKENS}/${encodeURIComponent(token)}`, { method: 'DELETE' }, 'Remove token');\n }\n\n // ===========================================================================\n // PUBLIC API - ACCOUNT & CONFIG\n // ===========================================================================\n\n async getAccount(): Promise<AccountGetResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.ACCOUNT}`, { method: 'GET' }, 'Get account');\n }\n\n async getLimits(): Promise<PlatformLimits> {\n return this.request(`${this.apiUrl}${ENDPOINTS.LIMITS}`, { method: 'GET' }, 'Get limits');\n }\n\n async ping(): Promise<boolean> {\n const data = await this.request<PingResponse>(`${this.apiUrl}${ENDPOINTS.PING}`, { method: 'GET' }, 'Ping');\n return data?.success || false;\n }\n\n // ===========================================================================\n // PUBLIC API - SPA CHECK\n // ===========================================================================\n\n async checkSPA(files: StaticFile[], options: ApiDeployOptions = {}): Promise<boolean> {\n const indexFile = files.find(f => f.path === 'index.html' || f.path === '/index.html');\n if (!indexFile || indexFile.size > 100 * 1024) {\n return false;\n }\n\n let indexContent: string;\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(indexFile.content)) {\n indexContent = indexFile.content.toString('utf-8');\n } else if (typeof Blob !== 'undefined' && indexFile.content instanceof Blob) {\n indexContent = await indexFile.content.text();\n } else if (typeof File !== 'undefined' && indexFile.content instanceof File) {\n indexContent = await indexFile.content.text();\n } else {\n return false;\n }\n\n const body: SPACheckRequest = { files: files.map(f => f.path), index: indexContent };\n const response = await this.request<SPACheckResponse>(\n `${this.apiUrl}${ENDPOINTS.SPA_CHECK}`,\n { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n 'SPA check'\n );\n\n return response.isSPA;\n }\n}\n","/**\n * Event system for Ship SDK\n * Lightweight, reliable event handling with proper error boundaries\n */\n\nimport type { ShipEvents } from './types.js';\n\n/**\n * Lightweight typed event emitter.\n *\n * Public API: `on()` / `off()`. `emit()` is internal — only the SDK\n * publishes events. Throwing handlers are evicted automatically and\n * surfaced as `error` events on the next tick.\n */\nexport class SimpleEvents {\n private handlers = new Map<string, Set<Function>>();\n\n /**\n * Add event handler\n */\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n if (!this.handlers.has(event as string)) {\n this.handlers.set(event as string, new Set());\n }\n this.handlers.get(event as string)!.add(handler);\n }\n\n /**\n * Remove event handler \n */\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n const eventHandlers = this.handlers.get(event as string);\n if (eventHandlers) {\n eventHandlers.delete(handler);\n if (eventHandlers.size === 0) {\n this.handlers.delete(event as string);\n }\n }\n }\n\n /**\n * Emit event (internal use only)\n * @internal\n */\n emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void {\n const eventHandlers = this.handlers.get(event as string);\n if (!eventHandlers) return;\n\n // Snapshot handlers so a handler that mutates the set during iteration\n // (e.g. by removing itself) doesn't skip or duplicate calls.\n const handlerArray = Array.from(eventHandlers);\n\n for (const handler of handlerArray) {\n try {\n handler(...args);\n } catch (error) {\n // A throwing handler is treated as broken — drop it so we don't\n // repeatedly invoke it and re-emit the failure as an `error` event\n // for observability. Defer the re-emit so the next tick has a clean\n // call stack and we can't recurse if the error handler also throws.\n eventHandlers.delete(handler);\n\n if (event !== 'error') {\n setTimeout(() => {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit('error', err, String(event));\n }, 0);\n }\n }\n }\n }\n}","/**\n * @file Client-side input validation for SDK request boundaries.\n *\n * These validators run before request construction. Constants come from\n * `@shipstatic/types` (`LABEL_CONSTRAINTS`, `LABEL_PATTERN`) so the SDK and\n * API agree on the rules.\n */\n\nimport {\n LABEL_CONSTRAINTS,\n LABEL_PATTERN,\n ShipError,\n} from '@shipstatic/types';\n\n// Re-export the canonical password validator from `@shipstatic/types` so\n// existing SDK callers (`http.ts`) keep their `from '../lib/validation.js'`\n// import path unchanged. The types-tier definition is the single source of\n// truth — see `@shipstatic/types/CLAUDE.md` \"Validation: format vs policy\".\nexport { validatePassword } from '@shipstatic/types';\n\n/**\n * Validate and normalize an array of labels.\n *\n * Lowercases and trims each entry, enforces per-label length and pattern\n * (`LABEL_CONSTRAINTS` / `LABEL_PATTERN`), count cap, and uniqueness after\n * normalization. Returns the normalized array. An empty array is valid and\n * signals \"clear all labels\" on label-update operations.\n */\nexport function validateLabels(labels: string[]): string[];\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined;\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined {\n if (labels === undefined || labels === null) return undefined;\n if (labels.length === 0) return labels;\n\n if (labels.length > LABEL_CONSTRAINTS.MAX_COUNT) {\n throw ShipError.validation(\n `Maximum ${LABEL_CONSTRAINTS.MAX_COUNT} labels allowed`,\n );\n }\n\n const normalized = labels.map((label, i) => {\n if (typeof label !== 'string') {\n throw ShipError.validation(`Label at index ${i} must be a string`);\n }\n const cleaned = label.trim().toLowerCase();\n if (cleaned.length < LABEL_CONSTRAINTS.MIN_LENGTH) {\n throw ShipError.validation(\n `Labels must be at least ${LABEL_CONSTRAINTS.MIN_LENGTH} characters long`,\n );\n }\n if (cleaned.length > LABEL_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(\n `Labels must be no more than ${LABEL_CONSTRAINTS.MAX_LENGTH} characters long`,\n );\n }\n if (!LABEL_PATTERN.test(cleaned)) {\n throw ShipError.validation(\n `Labels must start and end with alphanumeric characters, with optional separators (${LABEL_CONSTRAINTS.SEPARATORS}) between segments`,\n );\n }\n return cleaned;\n });\n\n const unique = [...new Set(normalized)];\n if (unique.length !== normalized.length) {\n throw ShipError.validation('Duplicate labels are not allowed');\n }\n\n return unique;\n}\n","/**\n * Ship SDK resource factory functions.\n */\nimport {\n ShipError,\n type StaticFile,\n type DeployInput,\n type DeploymentResource,\n type DomainResource,\n type AccountResource,\n type TokenResource\n} from '@shipstatic/types';\n\nexport type {\n StaticFile,\n DeployInput,\n DeploymentResource,\n DomainResource,\n AccountResource,\n TokenResource\n};\nimport type { ApiHttp } from './api/http.js';\nimport type { ShipClientOptions, DeploymentOptions } from './types.js';\nimport { mergeDeployOptions } from './core/config.js';\nimport { detectAndConfigureSPA } from './lib/spa.js';\n\n/**\n * Shared context for all resource factories.\n */\nexport interface ResourceContext {\n getApi: () => ApiHttp;\n ensureInit: () => Promise<void>;\n}\n\n/**\n * Extended context for deployment resource.\n */\nexport interface DeploymentResourceContext extends ResourceContext {\n processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;\n clientDefaults?: ShipClientOptions;\n}\n\n/**\n * Upload deployment resource with all CRUD operations.\n *\n * There is no client-side auth branching: an upload from a credential-less\n * client simply carries no `Authorization` header, and the API grants the\n * public-account agent identity per request (claim URL + expiry on the\n * response). The SDK stays a transparent pipe either way.\n */\nexport function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource {\n const { getApi, ensureInit, processInput, clientDefaults } = ctx;\n\n return {\n upload: async (input: DeployInput, options: DeploymentOptions = {}) => {\n await ensureInit();\n\n const mergedOptions = clientDefaults\n ? mergeDeployOptions(options, clientDefaults)\n : options;\n\n if (!processInput) {\n throw ShipError.config('processInput function is not provided.');\n }\n\n const apiClient = getApi();\n let staticFiles = await processInput(input, mergedOptions);\n staticFiles = await detectAndConfigureSPA(staticFiles, apiClient, mergedOptions);\n\n return apiClient.deploy(staticFiles, mergedOptions);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDeployments();\n },\n\n get: async (id: string) => {\n await ensureInit();\n return getApi().getDeployment(id);\n },\n\n set: async (id: string, options: { labels: string[] }) => {\n await ensureInit();\n return getApi().updateDeploymentLabels(id, options.labels);\n },\n\n remove: async (id: string) => {\n await ensureInit();\n await getApi().removeDeployment(id);\n }\n };\n}\n\n/**\n * Create domain resource with all CRUD operations.\n *\n * @remarks\n * The `name` parameter in all methods is an FQDN (Fully Qualified Domain Name).\n * The SDK does not validate or normalize domain names - the API handles all domain semantics.\n */\nexport function createDomainResource(ctx: ResourceContext): DomainResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n // INTENTIONAL DESIGN: The API does NOT support unlinking domains (setting deployment to null).\n // Once a domain is linked to a deployment, it must always have a deployment.\n // Supported: reserve (omit deployment), link, switch deployments atomically, delete entirely.\n // Not supported: unlink after linking (creates ambiguous state with no clear use case).\n // See npm/ship/CLAUDE.md \"Domain Write Semantics\" for full rationale.\n set: async (name: string, options: { deployment?: string; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().setDomain(name, options.deployment, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDomains();\n },\n\n get: async (name: string) => {\n await ensureInit();\n return getApi().getDomain(name);\n },\n\n remove: async (name: string) => {\n await ensureInit();\n await getApi().removeDomain(name);\n },\n\n verify: async (name: string) => {\n await ensureInit();\n return getApi().verifyDomain(name);\n },\n\n validate: async (name: string) => {\n await ensureInit();\n return getApi().validateDomain(name);\n },\n\n dns: async (name: string) => {\n await ensureInit();\n return getApi().getDomainDns(name);\n },\n\n records: async (name: string) => {\n await ensureInit();\n return getApi().getDomainRecords(name);\n },\n\n share: async (name: string) => {\n await ensureInit();\n return getApi().getDomainShare(name);\n }\n };\n}\n\n/**\n * Create account resource (whoami functionality).\n */\nexport function createAccountResource(ctx: ResourceContext): AccountResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n get: async () => {\n await ensureInit();\n return getApi().getAccount();\n }\n };\n}\n\n/**\n * Create token resource for managing deploy tokens.\n */\nexport function createTokenResource(ctx: ResourceContext): TokenResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n create: async (options: { ttl?: number; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().createToken(options.ttl, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listTokens();\n },\n\n remove: async (token: string) => {\n await ensureInit();\n await getApi().removeToken(token);\n }\n };\n}\n","/**\n * @file Cross-platform configuration helpers.\n *\n * One pure helper used by the deployment resource:\n *\n * - `mergeDeployOptions(perCallOptions, clientDefaults)` — overlays\n * instance-level defaults under per-call overrides for a single deploy.\n *\n * Deploy options are pure deploy concerns (progress, timeout, concurrency).\n * Credentials, the API URL, and the caller identifier are client identity —\n * they live on the instance, never per call: one client is one principal\n * speaking for one end user against one API. Callers that need a different\n * identity construct another Ship.\n */\n\nimport type { ShipClientOptions, DeploymentOptions } from '../types.js';\n\n/**\n * Overlay client-level defaults under per-call deploy options.\n *\n * Per-call options always win — they're the explicit override for a single\n * `deployments.upload()`. Defaults fill in only when the per-call option is\n * `undefined` (an explicit `null` / empty value passes through).\n */\nexport function mergeDeployOptions(\n options: DeploymentOptions,\n clientDefaults: ShipClientOptions,\n): DeploymentOptions {\n const result: DeploymentOptions = { ...options };\n\n if (result.timeout === undefined && clientDefaults.timeout !== undefined) {\n result.timeout = clientDefaults.timeout;\n }\n if (result.maxConcurrency === undefined && clientDefaults.maxConcurrency !== undefined) {\n result.maxConcurrency = clientDefaults.maxConcurrency;\n }\n if (result.onProgress === undefined && clientDefaults.onProgress !== undefined) {\n result.onProgress = clientDefaults.onProgress;\n }\n\n return result;\n}\n","/**\n * @file SPA detection and auto-configuration utilities.\n *\n * Provides SPA detection and ship.json generation functionality\n * that can be used by both Node.js and browser environments.\n */\n\nimport { DEPLOYMENT_CONFIG_FILENAME, SPA_DEFAULT_CONFIG } from '@shipstatic/types';\nimport { calculateMD5 } from './md5.js';\nimport type { StaticFile, DeploymentOptions } from '../types.js';\nimport type { ApiHttp } from '../api/http.js';\n\n/**\n * Creates ship.json configuration for SPA projects.\n * @returns Promise resolving to StaticFile with SPA configuration\n */\nexport async function createSPAConfig(): Promise<StaticFile> {\n const configString = JSON.stringify(SPA_DEFAULT_CONFIG, null, 2);\n\n // Create content that works in both browser and Node.js environments\n let content: Buffer | Blob;\n if (typeof Buffer !== 'undefined') {\n // Node.js environment\n content = Buffer.from(configString, 'utf-8');\n } else {\n // Browser environment\n content = new Blob([configString], { type: 'application/json' });\n }\n\n const { md5 } = await calculateMD5(content);\n\n return {\n path: DEPLOYMENT_CONFIG_FILENAME,\n content,\n size: configString.length,\n md5\n };\n}\n\n/**\n * Detects SPA projects and auto-generates configuration.\n * This function can be used by both Node.js and browser environments.\n *\n * @param files - Array of StaticFiles to analyze\n * @param apiClient - HTTP client for API communication\n * @param options - Deployment options containing SPA detection settings\n * @returns Promise resolving to files array with optional SPA config added\n */\nexport async function detectAndConfigureSPA(\n files: StaticFile[],\n apiClient: ApiHttp,\n options: DeploymentOptions\n): Promise<StaticFile[]> {\n // Skip if disabled, config already exists, or server will handle detection\n if (options.spaDetect === false || options.spa || options.build || options.prerender || files.some(f => f.path === DEPLOYMENT_CONFIG_FILENAME)) {\n return files;\n }\n\n try {\n const isSPA = await apiClient.checkSPA(files, options);\n\n if (isSPA) {\n const spaConfig = await createSPAConfig();\n return [...files, spaConfig];\n }\n } catch (error) {\n // SPA detection failed, continue silently without auto-config\n }\n\n return files;\n}\n","/**\n * @file Ship SDK for Node.js environments.\n *\n * The Node-side `Ship` adds two things on top of the base class:\n * 1. Environment detection — refuses to construct outside Node.\n * 2. `SHIP_TOKEN` / `SHIP_API_URL` env-var resolution as the universal\n * \"process boundary\" credential source — the industry's one-token\n * convention. Constructor arguments win over env vars.\n *\n * The SDK does NOT read `~/.shiprc` or `package.json` `\"ship\"` keys — that's\n * the CLI's job (see `cli/shiprc.ts`). Keeping file resolution out of the SDK\n * is what lets embedded consumers (MCP, n8n, GitHub Action) safely write\n * `new Ship({})` for anonymous public deployments without inheriting the host\n * developer's personal credentials.\n */\n\nimport { Ship as BaseShip } from '../shared/base-ship.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../shared/lib/env.js';\nimport { readEnvConfig } from './core/config.js';\nimport type {\n ShipClientOptions,\n Deployment,\n DeployInput,\n DeploymentOptions,\n StaticFile,\n DeployBodyCreator,\n} from '../shared/types.js';\nimport { createDeployBody } from './core/deploy-body.js';\n\n// Export all shared functionality\nexport * from '../shared/index.js';\n\n/**\n * Ship SDK Client for Node.js environments.\n *\n * @example\n * ```typescript\n * // Authenticated — explicit token (API key, deploy token, or OAuth bearer)\n * const ship = new Ship({ token: 'ship-xxxx' });\n *\n * // Authenticated — picks up SHIP_TOKEN from env\n * const ship = new Ship({});\n *\n * // Anonymous public deploy — works when neither constructor nor env provides a token\n * const ship = new Ship({});\n * await ship.deploy('./dist');\n * ```\n */\nexport class Ship extends BaseShip {\n constructor(options: ShipClientOptions = {}) {\n if (getENV() !== 'node') {\n throw ShipError.business('Node.js Ship class can only be used in Node.js environment.');\n }\n\n // Layer env vars under constructor options. The merged result is what the\n // base class sees, so the credential and the HTTP client are fully formed\n // by the time the constructor returns — no async config phase needed.\n //\n // Truthiness (not `??`) is deliberate: an empty-string token is absence\n // (shell expansion of unset CI variables), so `token: ''` falls through\n // to `SHIP_TOKEN` instead of locking in a phantom credential. A client\n // constructed with `session: true` has chosen its identity — the ambient\n // token does not ride along.\n const env = readEnvConfig();\n super({\n ...options,\n apiUrl: options.apiUrl || env.apiUrl,\n token: options.token || (options.session ? undefined : env.token),\n });\n }\n\n /**\n * Deploy file or directory paths to ShipStatic. Convenience shortcut for\n * `ship.deployments.upload()`.\n *\n * Wrong-platform inputs (e.g. `File[]`) fail at compile time. For\n * platform-neutral code, use `ship.deployments.upload()`, which accepts\n * the wider `DeployInput` and validates at runtime — that asymmetry is\n * intentional: the convenience shortcut narrows; the resource-layer\n * contract stays platform-neutral.\n */\n async deploy(input: string | string[], options?: DeploymentOptions): Promise<Deployment> {\n return super.deploy(input, options);\n }\n\n protected async processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]> {\n // Normalize string to string[] and validate.\n const paths = typeof input === 'string' ? [input] : input;\n\n if (!Array.isArray(paths) || !paths.every(p => typeof p === 'string')) {\n throw ShipError.business('Invalid input type for Node.js environment. Expected string or string[].');\n }\n\n if (paths.length === 0) {\n throw ShipError.business('No files to deploy.');\n }\n\n const { processFilesForNode } = await import('./core/node-files.js');\n return processFilesForNode(paths, options, this.platformLimits ?? undefined);\n }\n\n protected getDeployBodyCreator(): DeployBodyCreator {\n return createDeployBody;\n }\n}\n\n// Default export (for `import Ship from '@shipstatic/ship'`)\nexport default Ship;\n\n// Node-only utilities (path-walking + MD5 over the local filesystem)\nexport { processFilesForNode } from './core/node-files.js';\n","/**\n * @file Environment variable resolution for the Node.js Ship SDK.\n *\n * The SDK has exactly one ambient credential source: process environment\n * variables. `SHIP_TOKEN` (any platform token — the value's prefix says what\n * it is) and `SHIP_API_URL` are honored as the universal \"process boundary\" —\n * the one-token idiom used across the industry (`GITHUB_TOKEN`, `NPM_TOKEN`,\n * `VERCEL_TOKEN`). Constructor arguments win over env vars.\n *\n * File-based config (`~/.shiprc`, `package.json` `\"ship\"` key) is the CLI's\n * responsibility — see `src/node/cli/shiprc.ts`. The SDK does not read files,\n * which is what lets embedded consumers (MCP, n8n, GitHub Action) construct\n * `new Ship({})` for anonymous deployments without leaking the host developer's\n * personal credentials.\n */\n\nimport { z } from 'zod';\nimport type { ShipClientOptions } from '../../shared/types.js';\nimport { ShipError } from '@shipstatic/types';\nimport { getENV } from '../../shared/lib/env.js';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\n\n// `.strict()` matches the file-config schema. The `raw` object below is\n// constructed from a fixed set of keys, so .strict() doesn't catch user\n// typos here (env vars we don't read are simply never put into `raw` in\n// the first place). What it does catch is a *contributor* error — adding\n// a new env-var read without updating `CREDENTIAL_FIELDS` produces a clear\n// validation failure rather than a silently-stripped value. Nearly free\n// (one method call), and keeps both schemas reading the same.\nconst EnvConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\n/**\n * Map a `ShipClientOptions` field name (camelCase) back to the env var that\n * supplied it (SCREAMING_SNAKE_CASE), so validation errors point users at\n * the actual variable they need to fix. Kept as an explicit table rather\n * than a regex because the set is small, fixed, and unambiguous.\n */\nconst ENV_VAR_BY_FIELD: Record<string, string> = {\n apiUrl: 'SHIP_API_URL',\n token: 'SHIP_TOKEN',\n};\n\n/**\n * Read `SHIP_*` environment variables and validate the result.\n *\n * Empty strings (CI/Docker often sets env vars to `\"\"` instead of unsetting them)\n * are normalized to `undefined` before validation, so they don't trigger zod's\n * \"min length 1\" check or accidentally override a valid constructor argument.\n *\n * Returns an empty object outside Node.js — browser/edge runtimes have no\n * `process.env` we should reach into.\n */\nexport function readEnvConfig(): Partial<ShipClientOptions> {\n if (getENV() !== 'node') return {};\n\n const raw = {\n apiUrl: process.env.SHIP_API_URL || undefined,\n token: process.env.SHIP_TOKEN || undefined,\n };\n\n try {\n return EnvConfigSchema.parse(raw);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n const field = issue.path[0] as string | undefined;\n const envVar = (field && ENV_VAR_BY_FIELD[field]) ?? 'SHIP environment configuration';\n throw ShipError.config(`Invalid ${envVar}: ${issue.message}`);\n }\n throw ShipError.config('Invalid environment configuration');\n }\n}\n","/**\n * @file Single source of truth for ambient-config field validation.\n *\n * Both the SDK env reader (`node/core/config.ts`) and the CLI file loader\n * (`node/cli/shiprc.ts`) import these — if we tighten or relax a rule,\n * both layers update together. The `token` field accepts any platform token;\n * strict prefix-classified format validation happens once, at the `Ship`\n * constructor boundary, for every source uniformly.\n *\n * Lives in its own file (not alongside `mergeDeployOptions`) because it's a\n * pure data constant: tests that mock runtime config behavior shouldn't have\n * to forward this through their mocks.\n */\n\nimport { z } from 'zod';\n\nexport const CREDENTIAL_FIELDS = {\n apiUrl: z.string().url().optional(),\n token: z.string().min(1).optional(),\n};\n","/**\n * Node.js-specific deploy body creation.\n */\nimport { ShipError } from '@shipstatic/types';\nimport type { StaticFile, DeployBody, DeployBodyContext } from '../../shared/types.js';\n\nexport async function createDeployBody(\n files: StaticFile[],\n context: DeployBodyContext = {},\n): Promise<DeployBody> {\n const { FormData, File } = await import('formdata-node');\n const { FormDataEncoder } = await import('form-data-encoder');\n\n const { labels, via, password, flags, captcha } = context;\n const formData = new FormData();\n const checksums: string[] = [];\n\n for (const file of files) {\n // 1. Validate content type\n if (!Buffer.isBuffer(file.content) && !(typeof Blob !== 'undefined' && file.content instanceof Blob)) {\n throw ShipError.file(`Unsupported file.content type for Node.js: ${file.path}`, { filePath: file.path });\n }\n\n // 2. Validate md5\n if (!file.md5) {\n throw ShipError.file(`File missing md5 checksum: ${file.path}`, { filePath: file.path });\n }\n\n // 3. Create File and append — API derives Content-Type from extension\n const fileInstance = new File([file.content], file.path, { type: 'application/octet-stream' });\n formData.append('files[]', fileInstance);\n checksums.push(file.md5);\n }\n\n formData.append('checksums', JSON.stringify(checksums));\n\n if (labels && labels.length > 0) formData.append('labels', JSON.stringify(labels));\n if (via) formData.append('via', via);\n if (password) formData.append('password', password);\n if (flags?.build) formData.append('build', 'true');\n if (flags?.prerender) formData.append('prerender', 'true');\n if (flags?.spa) formData.append('spa', 'true');\n if (captcha) formData.append('captcha', captcha);\n\n const encoder = new FormDataEncoder(formData);\n const chunks = [];\n for await (const chunk of encoder.encode()) {\n chunks.push(Buffer.from(chunk));\n }\n const body = Buffer.concat(chunks);\n\n return {\n body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,\n headers: {\n 'Content-Type': encoder.contentType,\n 'Content-Length': Buffer.byteLength(body).toString()\n }\n };\n}\n","/**\n * @file File-based configuration loader for the `ship` CLI.\n *\n * The CLI is the only place that reads `~/.shiprc` and `package.json` `\"ship\"` keys.\n * Programmatic SDK consumers never touch the filesystem — they pass options to the\n * `Ship` constructor, optionally falling back to `SHIP_*` environment variables.\n * Keeping file resolution out of the SDK is what makes embedded usage (MCP, n8n,\n * GitHub Action) safe by default: `new Ship({})` cannot accidentally pick up the\n * host developer's `~/.shiprc`.\n *\n * Search order (cosmiconfig defaults):\n * 1. `.shiprc` walking up from CWD to `$HOME`\n * 2. `package.json` `\"ship\"` key walking up from CWD\n * 3. `$HOME/.shiprc`\n *\n * The `--config <file>` CLI flag bypasses the search and loads a specific path.\n */\n\nimport { z } from 'zod';\nimport { homedir } from 'os';\nimport { cosmiconfigSync } from 'cosmiconfig';\nimport { ShipError, isShipError } from '@shipstatic/types';\nimport type { ShipClientOptions } from '../../shared/types.js';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\n\n// `.strict()` rejects unknown keys — catches typos like `apikey` (lowercase)\n// in user-authored `.shiprc` files. The env reader doesn't need this because\n// its input is exactly the two SHIP_* vars we read.\nconst FileConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\nconst MODULE_NAME = 'ship';\n\n/**\n * Load configuration from `.shiprc` / `package.json`.\n *\n * Error semantics by failure mode:\n *\n * | Mode | Behavior |\n * |------|----------|\n * | Search finds no file | Returns `{}` — file config is optional |\n * | `--config <path>` and the file does not exist | Throws — a typo'd path is a clear user error and shouldn't be hidden behind a downstream auth failure |\n * | File found but unparseable JSON / unreadable (permissions) | Throws — silent swallowing left users debugging \"wrong API key\" when the real issue was their config |\n * | File parsed but fails schema validation | Throws with the offending field path |\n *\n * @param configFile - Optional explicit path (from the CLI's `--config` flag).\n * When provided, cosmiconfig loads exactly that file instead of searching.\n * @returns Validated config, or `{}` if no file was found in the search.\n * @throws {ShipError} for explicit-path failures, parse errors, or schema violations.\n */\nexport function loadShipFile(configFile?: string): Partial<ShipClientOptions> {\n // Empty path is treated as absence — matches credential-flag handling\n // (`--token \"\"` falls through to env). A user passing `--config \"$VAR\"`\n // with `VAR` unset gets `--config \"\"`, which should not error: it should\n // fall through to the normal cosmiconfig search.\n const explicitPath = configFile || undefined;\n\n const home = homedir();\n const explorer = cosmiconfigSync(MODULE_NAME, {\n searchPlaces: [\n `.${MODULE_NAME}rc`,\n 'package.json',\n `${home}/.${MODULE_NAME}rc`,\n ],\n stopDir: home,\n });\n\n let result;\n try {\n result = explicitPath ? explorer.load(explicitPath) : explorer.search();\n } catch (error) {\n if (isShipError(error)) throw error;\n // Wrap any cosmiconfig failure (missing explicit path, bad JSON, permissions)\n // in a ShipError. Surfacing this beats a confusing \"auth failed\" later.\n const message = error instanceof Error ? error.message : String(error);\n const where = explicitPath ? ` (${explicitPath})` : '';\n throw ShipError.config(`Failed to read ship config${where}: ${message}`);\n }\n\n if (!result || !result.config) return {};\n\n try {\n return FileConfigSchema.parse(result.config);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n // Keys from retired credential vocabularies get a rename hint instead\n // of a bare rejection — the fix is one edit, so the error names it.\n if (issue.code === 'unrecognized_keys') {\n const legacy = issue.keys.filter((key) => key === 'apiKey' || key === 'deployToken');\n if (legacy.length > 0) {\n const keys = legacy.map((key) => `\"${key}\"`).join(' and ');\n throw ShipError.config(\n `Invalid config in ${result.filepath}: ${keys} ${legacy.length > 1 ? 'are' : 'is'} no longer supported — the key is now \"token\". Run \\`ship config\\` to rewrite it.`\n );\n }\n }\n const path = issue.path.length > 0 ? ` at ${issue.path.join('.')}` : '';\n throw ShipError.config(\n `Invalid config in ${result.filepath}${path}: ${issue.message}`\n );\n }\n throw ShipError.config(`Invalid config in ${result.filepath}`);\n }\n}\n","/**\n * @file Resolves CLI configuration into a `Ship` instance.\n *\n * Owns the credential precedence contract: **flag > env > file**.\n *\n * Env-over-file is the canonical CLI tooling posture: CI runners and secret\n * managers set environment variables; a stale dotfile from local dev should\n * never override them. The merge is extracted as a pure function so the\n * contract is unit-testable and a future refactor can't silently flip the\n * order.\n *\n * The SDK itself only knows about constructor args + env vars (see\n * `node/index.ts`). File resolution lives here, in the CLI layer, exactly\n * once — keeping the SDK pure is what guarantees embedded consumers like\n * MCP can't inadvertently inherit the host developer's `~/.shiprc`.\n */\n\nimport { Ship } from '../index.js';\nimport { readEnvConfig } from '../core/config.js';\nimport { loadShipFile } from './shiprc.js';\nimport type { ShipClientOptions } from '../../shared/types.js';\n\n/**\n * The subset of CLI flags that participate in config resolution.\n * Other flags (`--json`, `--quiet`, etc.) flow through Commander separately.\n */\nexport interface CliFlags {\n /** Path to a specific config file, from `--config <file>`. */\n config?: string;\n apiUrl?: string;\n token?: string;\n}\n\n/**\n * Pure precedence merge: flag > env > file, per value. There is one token\n * and one API URL — nothing to arbitrate beyond source order.\n *\n * Empty strings are treated as absence and fall through to the next source\n * (mirrors the env reader, which normalizes empty `process.env` values to\n * `undefined`). This handles CI/CD shell-expansion of unset variables —\n * `--token \"$TOKEN\"` with `TOKEN` unset becomes `--token \"\"`, which we\n * must not lock in as a credential. Without this, an empty flag would\n * silently demote an authenticated deploy to anonymous PUBLIC_ACCOUNT.\n *\n * Exported separately from `createClient` so tests can lock in the contract\n * without mocking the SDK or the filesystem.\n */\nexport function mergeCliConfig(\n flags: CliFlags,\n env: Partial<ShipClientOptions>,\n file: Partial<ShipClientOptions>,\n): ShipClientOptions {\n return {\n apiUrl: flags.apiUrl || env.apiUrl || file.apiUrl,\n token: flags.token || env.token || file.token,\n };\n}\n\n/**\n * Resolve CLI flags + env + file into a `Ship` instance, ready for command\n * action handlers. Called once per CLI invocation by `withErrorHandling`.\n *\n * Synchronous all the way down — matches the SDK's sync constructor.\n */\nexport function createClient(flags: CliFlags = {}): Ship {\n return new Ship(mergeCliConfig(flags, readEnvConfig(), loadShipFile(flags.config)));\n}\n","/**\n * @file CLI-specific error UX utilities.\n *\n * Two pure functions: `toShipError` normalizes any thrown value into a typed\n * `ShipError` for the CLI's global error boundary; `getUserMessage` translates\n * a `ShipError` into the actionable string the CLI prints. Both are pure for\n * easy unit testing.\n *\n * Distinct from `ShipError.fromFetchError` (in `@shipstatic/types`), which is\n * for HTTP fetch failures. The CLI's global handler also catches things like\n * Commander parse errors, runtime exceptions in user code, etc. — so it uses\n * `toShipError` and intentionally normalizes unknowns to `Business` (a client\n * error type) so `getUserMessage`'s `isClientError()` branch surfaces the\n * original message rather than swallowing it as a generic \"server error\".\n */\n\nimport { ShipError, isShipError } from '@shipstatic/types';\nimport type { OutputContext } from './formatters.js';\n\n/**\n * Normalize any thrown value to a `ShipError` for the CLI error boundary.\n * Pass-through for existing `ShipError`s; wraps other Errors and unknowns\n * as `Business` so their message is preserved through `getUserMessage`.\n */\nexport function toShipError(err: unknown): ShipError {\n if (isShipError(err)) {\n return err;\n }\n if (err instanceof Error) {\n return ShipError.business(err.message);\n }\n return ShipError.business(String(err ?? 'Unknown error'));\n}\n\n/**\n * CLI options relevant to error message generation.\n */\nexport interface ErrorOptions {\n /**\n * The credential the CLI resolved (flag > env > file) — not the raw\n * `--token` flag. Presence selects the \"invalid or expired\" auth message;\n * absence selects the \"how to authenticate\" one.\n */\n token?: string;\n}\n\n/**\n * Get actionable user-facing message from an error.\n * Transforms technical errors into helpful messages that tell users what to do.\n *\n * This is a pure function - given the same inputs, always returns the same output.\n * All error message logic is centralized here for easy testing and maintenance.\n */\nexport function getUserMessage(\n err: ShipError,\n context?: OutputContext,\n options?: ErrorOptions\n): string {\n // Auth errors - tell user what credentials to provide\n if (err.isAuthError()) {\n if (options?.token) {\n return 'authentication failed: invalid or expired token';\n }\n return 'authentication required: pass --token, set SHIP_TOKEN, or run ship config';\n }\n\n // Network errors - include context about what failed\n if (err.isNetworkError()) {\n const url = (err.details as { url?: string } | undefined)?.url;\n if (url) {\n return `network error: could not reach ${url}`;\n }\n return 'network error: could not reach the API. check your internet connection';\n }\n\n // Client errors (Business | Config | File | Forbidden | Validation) —\n // trust the original message; the API or local code authored it.\n if (err.isClientError()) {\n return err.message;\n }\n\n // Other 4xx (NotFound, RateLimit, anything else with a 4xx status) —\n // the API's message is user-facing; trust it.\n if (err.status && err.status >= 400 && err.status < 500) {\n return err.message;\n }\n\n // Server errors (5xx) - generic but actionable\n return 'server error: please try again or check https://status.shipstatic.com';\n}\n\n/**\n * Format error for JSON output.\n * Returns the JSON string to be output (without newline).\n */\nexport function formatErrorJson(message: string, details?: unknown): string {\n return JSON.stringify({\n error: message,\n ...(details ? { details } : {})\n }, null, 2);\n}\n"],"mappings":";skBAwTO,SAASA,EAAYC,EAAO,CAC/B,OAAQA,IAAU,MACd,OAAOA,GAAU,UACjB,SAAUA,GACVA,EAAM,OAAS,aACf,WAAYA,CACpB,CA4CO,SAASC,GAAmBC,EAAU,CACzC,IAAMC,EAAWD,EAAS,YAAY,GAAG,EACzC,GAAIC,IAAa,IAAMA,IAAaD,EAAS,OAAS,EAClD,MAAO,GACX,IAAME,EAAMF,EAAS,MAAMC,EAAW,CAAC,EAAE,YAAY,EACrD,OAAOE,GAAmB,IAAID,CAAG,CACrC,CAyBO,SAASE,GAAeJ,EAAU,CACrC,OAAOK,GAAsB,KAAKL,CAAQ,CAC9C,CAoBO,SAASM,GAAiBC,EAAU,CAEvC,OADiBA,EAAS,QAAQ,MAAO,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO,EACvD,KAAKC,GAAKC,GAAwB,IAAID,CAAC,CAAC,CAC5D,CA0FO,SAASE,GAAcC,EAAO,CACjC,OAAIA,EAAM,WAAWC,GAAQ,MAAM,EACxBC,EAAU,QAC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AM,QAAQ,IAAI,CAC5B,OAASC,EAAK,CAGZ,GAAIA,aAAe,OAAS,SAAUA,EAAK,CACzC,IAAMgG,EAAQhG,EAAkC,KAC1CiG,EAAYjG,EAAsC,SACpDgG,GAAM,WAAW,YAAY,GAC/B,QAAQ,KAAKC,GAAY,CAAC,CAE9B,CACA,MAAMjG,CACR","names":["isShipError","error","isBlockedExtension","filename","dotIndex","ext","BLOCKED_EXTENSIONS","hasUnsafeChars","UNSAFE_FILENAME_CHARS","hasUnbuiltMarker","filePath","s","UNBUILT_PROJECT_MARKERS","classifyToken","token","API_KEY","TokenKind","DEPLOY_TOKEN","validatePrefixedCredential","value","shape","label","ShipError","hexPart","validateApiKey","apiKey","validateDeployToken","deployToken","validateToken","validateCaller","caller","CALLER","validateApiUrl","apiUrl","url","validatePassword","trimmed","PASSWORD_CONSTRAINTS","ErrorType","CLIENT_ONLY_ERROR_TYPES","ERROR_CATEGORIES","SERVER_PRODUCIBLE_ERROR_TYPES","AuthMethod","DEPLOYMENT_CONFIG_FILENAME","SPA_DEFAULT_CONFIG","DEFAULT_API","LABEL_CONSTRAINTS","LABEL_PATTERN","init_dist","__esmMin","t","_ShipError","type","message","status","details","authDetails","response","operationName","bodyType","json","obj","text","cause","op","resource","id","errorType","md5Blob","blob","SparkMD5","spark","chunkSize","start","end","md5Buffer","buffer","createHash","hash","md5Path","path","createReadStream","resolve","reject","stream","err","ShipError","chunk","calculateMD5","input","init_md5","__esmMin","init_dist","detectEnvironment","getENV","_testEnvironment","init_env","__esmMin","filterJunk","filePaths","options","p","hasUnbuiltMarker","ShipError","filePath","parts","basename","part","directorySegments","segment","JUNK_DIRECTORIES","junkDir","import_junk","init_junk","__esmMin","init_dist","findCommonParent","dirPaths","normalizedPaths","p","pathSegments","commonSegments","minLength","segment","segments","normalizeWebPath","path","init_path","__esmMin","optimizeDeployPaths","filePaths","options","path","normalizeWebPath","extractFileName","commonPrefix","findCommonDirectory","filePath","deployPath","prefixToRemove","pathSegments","commonSegments","minLength","segments","segment","init_deploy_paths","__esmMin","init_path","validateFileName","filename","hasUnsafeChars","reservedNames","nameWithoutPath","init_file_validation","__esmMin","init_dist","validateDeployPath","deployPath","sourceIdentifier","ShipError","validateDeployFile","nameCheck","validateFileName","isBlockedExtension","init_security","__esmMin","init_dist","init_file_validation","node_files_exports","__export","processFilesForNode","findAllFilePaths","dirPath","visited","results","realPath","entries","entry","fullPath","stats","subFiles","paths","options","platformLimits","getENV","ShipError","p","absPath","marker","e","UNBUILT_PROJECT_MARKERS","isShipError","absolutePaths","uniquePaths","inputAbsolutePaths","inputBasePath","findCommonParent","contentPaths","rel","deployPaths","optimizeDeployPaths","f","filteredSet","filterJunk","validAbsPaths","validDeployPaths","i","totalSize","filePath","deployPath","validateDeployPath","validateDeployFile","content","md5","calculateMD5","error","errorMessage","fs","path","init_node_files","__esmMin","init_env","init_md5","init_junk","init_security","init_dist","init_deploy_paths","init_path","import_commander","init_dist","import_fs","path","import_columnify","import_yoctocolors","INTERNAL_FIELDS","applyColor","colorFn","text","noColor","decapitalize","msg","success","json","error","errorPrefix","errorMsg","warn","warnPrefix","warnMsg","info","infoPrefix","infoMsg","formatTimestamp","timestamp","context","isoString","formatValue","key","value","mb","formatTable","data","columns","headerMap","firstItem","columnOrder","transformedData","item","record","transformed","col","columnify","config","heading","line","formatDetails","obj","entries","setupUrl","hash","domain","formatDeploymentsList","result","context","options","noColor","columns","formatTable","formatDomainsList","formatDomain","_dnsRecords","_shareHash","isCreate","displayResult","verb","success","info","record","formatDetails","formatDeployment","claim","days","formatAccount","formatMessage","formatDomainValidate","availabilityText","error","formatDomainRecords","formatDomainDns","provider","formatDomainShare","formatTokensList","formatToken","formatOutput","json","quiet","d","t","name","v","output","fs","path","os","detectShell","shell","getShellPaths","homeDir","installCompletion","scriptDir","options","json","noColor","error","paths","sourceScript","fishDir","success","info","sourceLine","content","prefix","warn","e","message","uninstallCompletion","lines","filtered","i","removed","endsWithNewline","newContent","import_promises","import_fs","import_os","import_path","init_dist","import_yoctocolors","CONFIG_PATH","maskToken","token","readExistingConfig","runConfig","options","noColor","json","applyDim","text","applyGreen","existing","apiUrl","DEFAULT_API","existingToken","rl","prompt","input","validateToken","init_dist","init_dist","SimpleEvents","event","handler","eventHandlers","args","handlerArray","error","err","init_dist","validateLabels","labels","LABEL_CONSTRAINTS","ShipError","normalized","label","i","cleaned","LABEL_PATTERN","unique","ENDPOINTS","DEFAULT_REQUEST_TIMEOUT","ApiHttp","SimpleEvents","options","DEFAULT_API","headers","url","operationName","cleanup","timeout","fetchOptions","response","ShipError","error","shipError","data","customHeaders","existingSignal","controller","timeoutId","abort","files","file","validatePassword","labels","validateLabels","flags","body","bodyHeaders","id","normalized","name","deployment","status","ttl","token","indexFile","f","indexContent","init_dist","mergeDeployOptions","options","clientDefaults","result","init_dist","init_md5","createSPAConfig","configString","SPA_DEFAULT_CONFIG","content","md5","calculateMD5","DEPLOYMENT_CONFIG_FILENAME","detectAndConfigureSPA","files","apiClient","options","f","spaConfig","createDeploymentResource","ctx","getApi","ensureInit","processInput","clientDefaults","input","options","mergedOptions","mergeDeployOptions","ShipError","apiClient","staticFiles","detectAndConfigureSPA","id","createDomainResource","name","createAccountResource","createTokenResource","token","Ship","options","validateCaller","ShipError","validateToken","ApiHttp","ctx","createDeploymentResource","input","opts","createDomainResource","createAccountResource","createTokenResource","error","event","handler","headers","token","value","init_dist","init_env","import_zod","init_dist","init_env","import_zod","CREDENTIAL_FIELDS","EnvConfigSchema","CREDENTIAL_FIELDS","ENV_VAR_BY_FIELD","readEnvConfig","getENV","raw","error","issue","field","envVar","ShipError","init_dist","createDeployBody","files","context","FormData","File","FormDataEncoder","labels","via","password","flags","captcha","formData","checksums","file","ShipError","fileInstance","encoder","chunks","chunk","body","Ship","options","getENV","ShipError","env","readEnvConfig","input","paths","p","processFilesForNode","createDeployBody","import_zod","import_os","import_cosmiconfig","init_dist","FileConfigSchema","CREDENTIAL_FIELDS","MODULE_NAME","loadShipFile","configFile","explicitPath","home","explorer","result","error","isShipError","message","where","ShipError","issue","legacy","key","keys","path","mergeCliConfig","flags","env","file","createClient","Ship","readEnvConfig","loadShipFile","init_dist","toShipError","err","isShipError","ShipError","getUserMessage","context","options","url","formatErrorJson","message","details","import_yoctocolors","loadPackageJson","paths","p","packageJson","program","err","displayHelp","processOptions","globalOptions","message","error","str","noColor","applyBold","text","applyDim","icon","emoji","output","collect","value","previous","mergeLabelOption","cmdOptions","programOpts","labels","filtered","l","mergePasswordOption","handleUnknownSubcommand","parentName","validSubcommands","args","commandObj","unknownArg","arg","command","options","forceColor","resolveCliToken","flags","file","loadShipFile","token","mergeCliConfig","readEnvConfig","handleError","context","opts","shipError","toShipError","getUserMessage","formatErrorJson","ErrorType","withErrorHandling","handler","resolvedContext","config","apiUrl","client","createClient","result","formatOutput","performDeploy","deployPath","password","ShipError","stats","deployOptions","abortController","spinner","yoctoSpinner","sigintHandler","thisCommand","validateToken","validateApiUrl","validationError","isShipError","_options","deploymentsCmd","deployment","id","domainsCmd","name","resolve","data","chunk","setOptions","records","share","tokensCmd","accountCmd","completionCmd","scriptDir","installCompletion","uninstallCompletion","runConfig","handleCompletion","isBash","isZsh","isFish","code","exitCode"]}
1
+ {"version":3,"sources":["../node_modules/.pnpm/@shipstatic+types@2.2.1-beta.0/node_modules/@shipstatic/types/dist/index.js","../src/shared/lib/env.ts","../src/shared/lib/md5.ts","../src/shared/lib/path.ts","../src/shared/lib/deploy-paths.ts","../src/shared/lib/file-validation.ts","../src/shared/lib/junk.ts","../src/shared/lib/security.ts","../src/node/core/node-files.ts","../src/node/cli/index.ts","../src/node/core/config.ts","../src/shared/core/credential-schema.ts","../src/node/cli/completion.ts","../src/node/cli/utils.ts","../src/node/cli/config.ts","../src/node/index.ts","../src/shared/base-ship.ts","../src/shared/api/http.ts","../src/shared/events.ts","../src/shared/lib/validation.ts","../src/shared/resources.ts","../src/shared/core/config.ts","../src/shared/lib/spa.ts","../src/node/core/deploy-body.ts","../src/node/cli/shiprc.ts","../src/node/cli/create-client.ts","../src/node/cli/error-handling.ts","../src/node/cli/formatters.ts"],"sourcesContent":["/**\n * @file Shared TypeScript types, constants, and utilities for the ShipStatic platform.\n * This package is the single source of truth for all shared data structures.\n */\n// =============================================================================\n// I. CORE ENTITIES\n// =============================================================================\n/**\n * Deployment status constants\n */\nexport const DeploymentStatus = {\n PENDING: 'pending',\n SUCCESS: 'success',\n FAILED: 'failed',\n DELETING: 'deleting',\n};\n// =============================================================================\n// DOMAIN TYPES\n// =============================================================================\n/**\n * Domain status constants\n *\n * - PENDING: DNS not configured\n * - PARTIAL: DNS partially configured\n * - SUCCESS: DNS fully verified\n * - PAUSED: Domain paused due to plan enforcement (billing)\n */\nexport const DomainStatus = {\n PENDING: 'pending',\n PARTIAL: 'partial',\n SUCCESS: 'success',\n PAUSED: 'paused',\n};\n// =============================================================================\n// ACCOUNT TYPES\n// =============================================================================\n/**\n * Account plan constants\n */\nexport const AccountPlan = {\n FREE: 'free',\n STANDARD: 'standard',\n SPONSORED: 'sponsored',\n ENTERPRISE: 'enterprise',\n SUSPENDED: 'suspended',\n TERMINATING: 'terminating',\n TERMINATED: 'terminated',\n};\n// =============================================================================\n// ERROR SYSTEM\n// =============================================================================\n/**\n * All possible error types in the ShipStatic platform.\n *\n * Developer-friendly key names map to stable wire-format string values.\n * Both the value and the type are exported under the same name so callers\n * can use `ErrorType.Validation` (value comparison) and `: ErrorType` (type\n * annotation) without ceremony — matching the pattern other status objects\n * (`DeploymentStatus`, `DomainStatus`, `AccountPlan`, `AuthMethod`) follow.\n */\nexport const ErrorType = {\n /** Validation failed (400). Input shape is wrong. */\n Validation: 'validation_failed',\n /** Resource not found (404). */\n NotFound: 'not_found',\n /** Authenticated but not allowed (403). User lacks permission for this action. */\n Forbidden: 'forbidden',\n /** Rate limit exceeded (429). */\n RateLimit: 'rate_limit_exceeded',\n /** Authentication required or failed (401). Missing/invalid credentials. */\n Authentication: 'authentication_failed',\n /** Business rule violation. Catch-all for 4xx state-rule errors that aren't more specific. */\n Business: 'business_logic_error',\n /** API server error (500). Generic server-side fault. */\n Api: 'internal_server_error',\n /** Network/connection error. Client-side only — set by HTTP clients on fetch failure; never produced server-side. */\n Network: 'network_error',\n /** Operation was cancelled. Client-side only — set on `AbortSignal` abort; never produced server-side. */\n Cancelled: 'operation_cancelled',\n /** File operation error. Client-side only — set by SDK during local file processing; never produced server-side. */\n File: 'file_error',\n /** Configuration error. Client-side only — set by SDK during config parsing/validation; never produced server-side. */\n Config: 'config_error',\n};\n/**\n * Error types that originate exclusively on the client (HTTP clients, SDK\n * file processing, local config parsing). These never appear on the wire\n * from the server, so `fromHttpResponse` will not trust them even if a\n * misbehaving server claims one in `body.error`.\n */\nconst CLIENT_ONLY_ERROR_TYPES = new Set([\n ErrorType.Network,\n ErrorType.Cancelled,\n ErrorType.File,\n ErrorType.Config,\n]);\n/**\n * Categorizes error types for the `isClientError` / `isNetworkError` /\n * `isAuthError` helpers. Each `Set` is typed against the wider `ErrorType`\n * union so `.has(error.type)` accepts any value from the union.\n */\nconst ERROR_CATEGORIES = {\n client: new Set([\n ErrorType.Business,\n ErrorType.Config,\n ErrorType.File,\n ErrorType.Forbidden,\n ErrorType.Validation,\n ]),\n network: new Set([ErrorType.Network]),\n auth: new Set([ErrorType.Authentication]),\n};\n/**\n * Error types the server can legitimately produce on the wire. Used by\n * `ShipError.fromHttpResponse` to validate the body's `error` field before\n * trusting it as `ShipError.type`. Derived by exclusion from\n * `CLIENT_ONLY_ERROR_TYPES` so adding a new server-producible type to\n * `ErrorType` is automatically picked up.\n */\nconst SERVER_PRODUCIBLE_ERROR_TYPES = new Set(Object.values(ErrorType).filter((t) => !CLIENT_ONLY_ERROR_TYPES.has(t)));\n/**\n * Simple unified error class for both API and SDK\n */\nexport class ShipError extends Error {\n type;\n status;\n details;\n constructor(type, message, status, details) {\n super(message);\n this.type = type;\n this.status = status;\n this.details = details;\n this.name = 'ShipError';\n }\n /** Convert to wire format */\n toResponse() {\n // Strip authentication details when they carry an `internal` telemetry\n // tag (see `ShipError.authentication` JSDoc) — these are server-side\n // diagnostics like 'session_invalid' that must not leak to clients.\n const authDetails = this.details;\n const details = this.type === ErrorType.Authentication && authDetails?.internal ? undefined : this.details;\n return {\n error: this.type,\n message: this.message,\n status: this.status,\n details,\n };\n }\n /**\n * Construct a `ShipError` from an HTTP error response.\n *\n * Best-effort body parse for `{ message, error?, details? }`. Message\n * resolution: `body.message` → `body.error` → `\"<operationName> failed with\n * status <N>\"`.\n *\n * Type resolution: trusts `body.error` when it's a known server-producible\n * `ErrorType` (preserves the wire's intent — server's\n * `ShipError.validation(...)` round-trips back to `ErrorType.Validation`\n * on the client). Falls back to status-derived (401 → Authentication,\n * 403 → Forbidden, 429 → RateLimit, else → Api) for non-API responses\n * (CDN errors, intermediaries) or malformed bodies. Client-only types\n * (`Network`, `Cancelled`, `File`, `Config`) are filtered out of the\n * trusted set — a misbehaving server claiming one of those is ignored.\n *\n * `operationName` (e.g. `\"Get account\"`) is used to compose the fallback\n * message. Defaults to `\"Request\"`. Same convention as `fromFetchError`.\n *\n * Async because it reads the response body. Returns rather than throws so\n * callers can compose; most will `throw await ShipError.fromHttpResponse(...)`.\n */\n static async fromHttpResponse(response, operationName) {\n let message;\n let details;\n let bodyType;\n try {\n const contentType = response.headers.get('content-type');\n if (contentType?.includes('application/json')) {\n const json = await response.json();\n if (json && typeof json === 'object') {\n const obj = json;\n if (typeof obj.message === 'string')\n message = obj.message;\n else if (typeof obj.error === 'string')\n message = obj.error;\n details = obj.details;\n if (typeof obj.error === 'string' && SERVER_PRODUCIBLE_ERROR_TYPES.has(obj.error)) {\n bodyType = obj.error;\n }\n }\n }\n else {\n const text = await response.text();\n if (text)\n message = text;\n }\n }\n catch {\n // Body unreadable; fall through to operationName-derived message.\n }\n message = message || `${operationName || 'Request'} failed with status ${response.status}`;\n const type = bodyType ??\n (response.status === 401\n ? ErrorType.Authentication\n : response.status === 403\n ? ErrorType.Forbidden\n : response.status === 429\n ? ErrorType.RateLimit\n : ErrorType.Api);\n return new ShipError(type, message, response.status, details);\n }\n /**\n * Construct a `ShipError` from an error caught around a `fetch()` call.\n *\n * The mirror of `fromHttpResponse` for the *other* side of the HTTP error\n * story — the network layer failing (offline, CORS, abort) rather than the\n * server returning a non-OK response.\n *\n * Routing:\n * - Already a `ShipError` → returned as-is (caller's intent preserved)\n * - `AbortError` → `ShipError.cancelled(...)`\n * - `TypeError` whose message mentions \"fetch\" → `ShipError.network(...)`\n * - Any other `Error` → `ShipError(Api, ...)` (no HTTP status — fetch never reached the server)\n * - Anything else (string, undefined, etc.) → `ShipError(Api, ...)`\n *\n * The optional `operationName` is composed into the message for context:\n * `\"Get account was cancelled\"`, `\"Get account failed: ...\"`. Defaults to\n * `\"Request\"` when omitted.\n */\n static fromFetchError(cause, operationName) {\n if (isShipError(cause))\n return cause;\n const op = operationName || 'Request';\n if (cause instanceof Error) {\n if (cause.name === 'AbortError') {\n return ShipError.cancelled(`${op} was cancelled`);\n }\n if (cause instanceof TypeError && cause.message.includes('fetch')) {\n return ShipError.network(`${op} failed: ${cause.message}`, { cause });\n }\n return new ShipError(ErrorType.Api, `${op} failed: ${cause.message}`);\n }\n return new ShipError(ErrorType.Api, `${op} failed: Unknown error`);\n }\n // Factory methods. Uniform shape `(message, details?)` with two principled\n // exceptions: `notFound` composes its message from (resource, id?), and\n // `business` / `api` accept an optional status because they're the\n // multi-status fallbacks.\n static validation(message, details) {\n return new ShipError(ErrorType.Validation, message, 400, details);\n }\n static notFound(resource, id) {\n const message = id ? `${resource} ${id} not found` : `${resource} not found`;\n return new ShipError(ErrorType.NotFound, message, 404);\n }\n static forbidden(message, details) {\n return new ShipError(ErrorType.Forbidden, message, 403, details);\n }\n static rateLimit(message = 'Too many requests', details) {\n return new ShipError(ErrorType.RateLimit, message, 429, details);\n }\n /**\n * Construct an Authentication (401) error.\n *\n * **Telemetry pattern — `details: { internal: '<tag>' }`.** When the\n * server creates an auth error with an `internal` key in `details`\n * (e.g. `{ internal: 'session_invalid' }`), `toResponse()` strips the\n * entire `details` object before serialization. This keeps the wire\n * response a clean \"Authentication failed\" while preserving granular\n * server-side telemetry (which strategy/check failed) for logs and tests.\n *\n * Use this pattern in API auth code; do not put client-visible info under\n * `internal`. Other `details` keys round-trip normally.\n */\n static authentication(message = 'Authentication required', details) {\n return new ShipError(ErrorType.Authentication, message, 401, details);\n }\n static business(message, status = 400, details) {\n return new ShipError(ErrorType.Business, message, status, details);\n }\n static network(message, details) {\n return new ShipError(ErrorType.Network, message, undefined, details);\n }\n static cancelled(message, details) {\n return new ShipError(ErrorType.Cancelled, message, undefined, details);\n }\n static file(message, details) {\n return new ShipError(ErrorType.File, message, undefined, details);\n }\n static config(message, details) {\n return new ShipError(ErrorType.Config, message, undefined, details);\n }\n static api(message, status = 500, details) {\n return new ShipError(ErrorType.Api, message, status, details);\n }\n // Semantic-category type guards. For specific-type checks, use\n // `error.type === ErrorType.X` directly or the generic `isType(t)`.\n isClientError() {\n return ERROR_CATEGORIES.client.has(this.type);\n }\n isNetworkError() {\n return ERROR_CATEGORIES.network.has(this.type);\n }\n isAuthError() {\n return ERROR_CATEGORIES.auth.has(this.type);\n }\n isType(errorType) {\n return this.type === errorType;\n }\n}\n/**\n * Type guard to check if an unknown value is a ShipError.\n *\n * Uses structural checking instead of instanceof to handle module duplication\n * in bundled applications where multiple copies of the ShipError class may exist.\n *\n * @example\n * if (isShipError(error)) {\n * console.log(error.status, error.message);\n * }\n */\nexport function isShipError(error) {\n return (error !== null &&\n typeof error === 'object' &&\n 'name' in error &&\n error.name === 'ShipError' &&\n 'status' in error);\n}\n// =============================================================================\n// EXTENSION BLOCKLIST\n// =============================================================================\n/**\n * Blocked file extensions — files that cannot be uploaded.\n *\n * We accept any file type by default and derive Content-Type from the\n * extension at serve time (via mime-db in the API worker). Unknown extensions\n * are served as `application/octet-stream` with `X-Content-Type-Options: nosniff`.\n *\n * The blocklist targets file types that pose direct security risks when hosted:\n * executables, disk images, malware vectors, dangerous scripts, and shortcuts.\n */\nexport const BLOCKED_EXTENSIONS = new Set([\n // Executables\n 'exe',\n 'msi',\n 'dll',\n 'scr',\n 'bat',\n 'cmd',\n 'com',\n 'pif',\n 'app',\n 'deb',\n 'rpm',\n // Installers\n 'pkg',\n 'mpkg',\n // Disk images\n 'dmg',\n 'iso',\n 'img',\n // Malware vectors\n 'cab',\n 'cpl',\n 'chm',\n // Dangerous scripts\n 'ps1',\n 'vbs',\n 'vbe',\n 'ws',\n 'wsf',\n 'wsc',\n 'wsh',\n 'reg',\n // Java\n 'jar',\n 'jnlp',\n // Mobile/browser packages\n 'apk',\n 'crx',\n // Shortcut/link\n 'lnk',\n 'inf',\n 'hta',\n]);\n/**\n * Check if a filename has a blocked extension.\n * Extracts the extension from the filename and checks against the blocklist.\n * Case-insensitive. Returns false for files without extensions.\n *\n * @example\n * isBlockedExtension('virus.exe') // true\n * isBlockedExtension('app.dmg') // true\n * isBlockedExtension('style.css') // false\n * isBlockedExtension('data.custom') // false\n * isBlockedExtension('README') // false\n */\nexport function isBlockedExtension(filename) {\n const dotIndex = filename.lastIndexOf('.');\n if (dotIndex === -1 || dotIndex === filename.length - 1)\n return false;\n const ext = filename.slice(dotIndex + 1).toLowerCase();\n return BLOCKED_EXTENSIONS.has(ext);\n}\n// =============================================================================\n// FILENAME CHARACTER VALIDATION\n// =============================================================================\n/**\n * Characters that are unsafe in filenames for static hosting.\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (upload splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: blocking control characters is this regex's purpose\nexport const UNSAFE_FILENAME_CHARS = /[\\x00-\\x1f\\x7f#?%\\\\<>\"]/;\n/**\n * Check if a filename contains unsafe characters.\n *\n * @example\n * hasUnsafeChars('saved_resource(1).html') // false — parentheses are safe\n * hasUnsafeChars('page[slug].js') // false — brackets are safe\n * hasUnsafeChars('file#anchor.html') // true — # breaks URL resolution\n * hasUnsafeChars('file<tag>.html') // true — < is an XSS vector\n */\nexport function hasUnsafeChars(filename) {\n return UNSAFE_FILENAME_CHARS.test(filename);\n}\n// =============================================================================\n// UNBUILT PROJECT MARKERS\n// =============================================================================\n/**\n * Path segment names that indicate an unbuilt project was uploaded instead of build output.\n * Used for early detection in CLI, browser, and server validation.\n */\nexport const UNBUILT_PROJECT_MARKERS = new Set([\n 'node_modules',\n 'package.json',\n]);\n/**\n * Check if a file path contains an unbuilt project marker.\n *\n * @example\n * hasUnbuiltMarker('node_modules/react/index.js') // true\n * hasUnbuiltMarker('package.json') // true\n * hasUnbuiltMarker('dist/index.html') // false\n */\nexport function hasUnbuiltMarker(filePath) {\n const segments = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n return segments.some((s) => UNBUILT_PROJECT_MARKERS.has(s));\n}\n// =============================================================================\n// CREDENTIAL SHAPES\n// =============================================================================\n// The one address for credential vocabulary: how a request is authorized\n// (AuthMethod), the shapes that distinguish populations on the wire\n// (API_KEY, DEPLOY_TOKEN, CALLER), the single dispatch over them (TokenKind,\n// classifyToken), and the delegated-access scopes (OAuthScope).\n/**\n * How a request (or recorded activity) was authorized.\n *\n * Client populations: `SESSION` (first-party cookie), `API_KEY` (`ship-`\n * key), `TOKEN` (`deploy-` deploy token), `AGENT` (anonymous public deploy —\n * no credential; the platform grants the public-account identity per\n * request), `OAUTH` (delegated access token). Server populations: `WEBHOOK`\n * (signed webhook processing), `SYSTEM` (scheduled/background jobs).\n */\nexport const AuthMethod = {\n SESSION: 'session',\n API_KEY: 'apiKey',\n TOKEN: 'token',\n AGENT: 'agent',\n OAUTH: 'oauth',\n WEBHOOK: 'webhook',\n SYSTEM: 'system',\n};\n/**\n * Shape constants for API keys (`ship-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const API_KEY = {\n /** Prefix that identifies an API key. */\n PREFIX: 'ship-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of an API key including prefix (`PREFIX.length + HEX_LENGTH = 69`). */\n TOTAL_LENGTH: 69,\n /** Number of trailing characters used to display a redacted hint (e.g. last 4). */\n HINT_LENGTH: 4,\n};\n/**\n * Shape constants for deploy tokens (`deploy-{64 hex chars}`).\n * Single source of truth used by validation utilities and auth middleware.\n */\nexport const DEPLOY_TOKEN = {\n /** Prefix that identifies a deploy token. */\n PREFIX: 'deploy-',\n /** Number of hex characters following the prefix. */\n HEX_LENGTH: 64,\n /** Total length of a deploy token including prefix (`PREFIX.length + HEX_LENGTH = 71`). */\n TOTAL_LENGTH: 71,\n};\n/**\n * Shape constants for caller identifiers (the `X-Caller` instance-identity\n * header — rate-limit bucketing for multi-tenant orchestrators). The API\n * normalizes case and silently ignores malformed values (the header is\n * unauthenticated); clients validate at the boundary via `validateCaller`,\n * so a value the server would drop fails fast instead.\n */\nexport const CALLER = {\n /** HTTP header name. */\n HEADER: 'X-Caller',\n /** Maximum identifier length. */\n MAX_LENGTH: 128,\n /** Allowed characters: alphanumeric, dot, underscore, hyphen. */\n PATTERN: /^[a-zA-Z0-9._-]+$/,\n};\n/**\n * Token populations distinguishable by shape. The platform carries every\n * client token in one wire slot (`Authorization: Bearer <value>`) and\n * classifies by value, never by a side channel — this is the classifier.\n *\n * `API_KEY` and `DEPLOY_TOKEN` *are* `AuthMethod.API_KEY` and\n * `AuthMethod.TOKEN` — the equality is structural, so a classification flows\n * straight into an auth method and the pair can never drift. `OPAQUE` is any\n * other value — shape says nothing about it, so only a lookup can. Today the\n * server refuses every opaque bearer; the OAuth access-token population\n * resolves there when the authorization server ships.\n */\nexport const TokenKind = {\n API_KEY: AuthMethod.API_KEY,\n DEPLOY_TOKEN: AuthMethod.TOKEN,\n OPAQUE: 'opaque',\n};\n/**\n * Classify a client token by shape. The single dispatch used by both sides\n * of the wire: API auth middleware (which population is this credential?)\n * and SDK validation (which format rules apply before sending?). Sharing it\n * is what guarantees client and server can never disagree on dispatch.\n */\nexport function classifyToken(token) {\n if (token.startsWith(API_KEY.PREFIX))\n return TokenKind.API_KEY;\n if (token.startsWith(DEPLOY_TOKEN.PREFIX))\n return TokenKind.DEPLOY_TOKEN;\n return TokenKind.OPAQUE;\n}\n/**\n * OAuth scope vocabulary for delegated third-party access tokens.\n * Single source of truth used by the authorization server (advertised in\n * `scopes_supported`), the API's scope-enforcement middleware, and consent UI\n * copy. The standard `offline_access` scope (refresh tokens) is not platform\n * vocabulary and is deliberately absent — the middleware never checks it.\n *\n * Deliberately absent by design: any `tokens:*` scope, `account:write`, or\n * admin scope — a delegated app must never mint credentials, delete the\n * account, or act as admin.\n */\nexport const OAuthScope = {\n ACCOUNT_READ: 'account:read',\n DEPLOYMENTS_READ: 'deployments:read',\n DEPLOYMENTS_WRITE: 'deployments:write',\n DOMAINS_READ: 'domains:read',\n DOMAINS_WRITE: 'domains:write',\n};\n// =============================================================================\n// DEPLOYMENT CONFIGURATION CONSTANTS\n// =============================================================================\nexport const DEPLOYMENT_CONFIG_FILENAME = 'ship.json';\n/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */\nexport const SPA_DEFAULT_CONFIG = {\n rewrites: [{ source: '/(.*)', destination: '/index.html' }],\n};\n// =============================================================================\n// VALIDATION UTILITIES\n// =============================================================================\n/**\n * Shared rule for prefixed credentials: `{PREFIX}{HEX_LENGTH hex chars}`.\n * The regex derives from the shape constants, so the validators can never\n * drift from the shapes `classifyToken` dispatches on.\n */\nfunction validatePrefixedCredential(value, shape, label) {\n if (!value.startsWith(shape.PREFIX)) {\n throw ShipError.validation(`${label} must start with \"${shape.PREFIX}\"`);\n }\n if (value.length !== shape.TOTAL_LENGTH) {\n throw ShipError.validation(`${label} must be ${shape.TOTAL_LENGTH} characters total (${shape.PREFIX} + ${shape.HEX_LENGTH} hex chars)`);\n }\n const hexPart = value.slice(shape.PREFIX.length);\n if (!new RegExp(`^[a-f0-9]{${shape.HEX_LENGTH}}$`, 'i').test(hexPart)) {\n throw ShipError.validation(`${label} must contain ${shape.HEX_LENGTH} hexadecimal characters after \"${shape.PREFIX}\" prefix`);\n }\n}\n/**\n * Validate API key format\n */\nexport function validateApiKey(apiKey) {\n validatePrefixedCredential(apiKey, API_KEY, 'API key');\n}\n/**\n * Validate deploy token format\n */\nexport function validateDeployToken(deployToken) {\n validatePrefixedCredential(deployToken, DEPLOY_TOKEN, 'Deploy token');\n}\n/**\n * Validate a client token of any population. Classifies by shape and applies\n * the matching format rules: `ship-` keys and `deploy-` deploy tokens are\n * validated strictly; opaque tokens (OAuth access tokens, future populations)\n * only need to be non-empty — their validity is the server's to decide.\n */\nexport function validateToken(token) {\n switch (classifyToken(token)) {\n case TokenKind.API_KEY:\n validateApiKey(token);\n return;\n case TokenKind.DEPLOY_TOKEN:\n validateDeployToken(token);\n return;\n case TokenKind.OPAQUE:\n if (!token)\n throw ShipError.validation('Token must be a non-empty string');\n }\n}\n/**\n * Validate a caller identifier against the `CALLER` shape. The server\n * silently ignores malformed values (the header is unauthenticated); clients\n * call this at configuration time so the drop never silently happens.\n */\nexport function validateCaller(caller) {\n if (!caller || caller.length > CALLER.MAX_LENGTH || !CALLER.PATTERN.test(caller)) {\n throw ShipError.validation(`Caller must be 1-${CALLER.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`);\n }\n}\n/**\n * Validate API URL format\n */\nexport function validateApiUrl(apiUrl) {\n try {\n const url = new URL(apiUrl);\n if (!['http:', 'https:'].includes(url.protocol)) {\n throw ShipError.validation('API URL must use http:// or https:// protocol');\n }\n if (url.pathname !== '/' && url.pathname !== '') {\n throw ShipError.validation('API URL must not contain a path');\n }\n if (url.search || url.hash) {\n throw ShipError.validation('API URL must not contain query parameters or fragments');\n }\n }\n catch (error) {\n if (isShipError(error)) {\n throw error;\n }\n throw ShipError.validation('API URL must be a valid URL');\n }\n}\n/**\n * Check if a string matches the deployment identifier pattern (word-word-alphanumeric7).\n * Example: \"happy-cat-abc1234.shipstatic.com\"\n */\nexport function isDeployment(input) {\n return /^[a-z]+-[a-z]+-[a-z0-9]{7}(\\.[a-z0-9.-]+)?$/i.test(input);\n}\n// =============================================================================\n// PLATFORM CONSTANTS\n// =============================================================================\n/** Default API URL if not otherwise configured. */\nexport const DEFAULT_API = 'https://api.shipstatic.com';\n// =============================================================================\n// FILE UPLOAD TYPES\n// =============================================================================\n/**\n * File status constants for validation state tracking\n */\nexport const FileValidationStatus = {\n /** File is pending validation */\n PENDING: 'pending',\n /** File failed during processing (before validation) */\n PROCESSING_ERROR: 'processing_error',\n /** File was excluded by validation warning (not an error) */\n EXCLUDED: 'excluded',\n /** File failed validation (blocks deployment) */\n VALIDATION_FAILED: 'validation_failed',\n /** File passed validation and is ready for deployment */\n READY: 'ready',\n};\n// =============================================================================\n// DOMAIN UTILITIES\n// =============================================================================\n/**\n * Check if a domain is a platform domain (subdomain of our platform).\n * Platform domains are free and don't require DNS verification.\n *\n * @example isPlatformDomain(\"www.shipstatic.com\", \"shipstatic.com\") → true\n * @example isPlatformDomain(\"example.com\", \"shipstatic.com\") → false\n */\nexport function isPlatformDomain(domain, platformDomain) {\n return domain.endsWith(`.${platformDomain}`);\n}\n/**\n * Check if a domain is a custom domain (not a platform subdomain).\n * Custom domains are billable and require DNS verification.\n *\n * @example isCustomDomain(\"example.com\", \"shipstatic.com\") → true\n * @example isCustomDomain(\"www.shipstatic.com\", \"shipstatic.com\") → false\n */\nexport function isCustomDomain(domain, platformDomain) {\n return !isPlatformDomain(domain, platformDomain);\n}\n/**\n * Extract subdomain from a platform domain.\n * Returns null if not a platform domain.\n *\n * @example extractSubdomain(\"www.shipstatic.com\", \"shipstatic.com\") → \"www\"\n * @example extractSubdomain(\"example.com\", \"shipstatic.com\") → null\n */\nexport function extractSubdomain(domain, platformDomain) {\n if (!isPlatformDomain(domain, platformDomain)) {\n return null;\n }\n return domain.slice(0, -(platformDomain.length + 1)); // +1 for the dot\n}\n/**\n * Generate HTTPS URL for a deployment hostname.\n */\nexport function generateDeploymentUrl(deployment) {\n return `https://${deployment}`;\n}\n/**\n * Generate HTTPS URL for a domain.\n */\nexport function generateDomainUrl(domain) {\n return `https://${domain}`;\n}\n// =============================================================================\n// LABEL UTILITIES\n// =============================================================================\n/**\n * Label validation constraints shared across UI and API.\n * These rules define the single source of truth for label validation.\n */\nexport const LABEL_CONSTRAINTS = {\n /** Minimum label length in characters */\n MIN_LENGTH: 3,\n /** Maximum label length in characters (concise labels, matches Stack Overflow's original limit) */\n MAX_LENGTH: 25,\n /** Maximum number of labels allowed per resource */\n MAX_COUNT: 10,\n /** Allowed separator characters between label segments */\n SEPARATORS: '._-',\n};\n/**\n * Label validation pattern.\n * Must start and end with alphanumeric (a-z, 0-9).\n * Can contain separators (. _ -) between segments, but not consecutive.\n *\n * Valid examples: 'production', 'v1.2.3', 'api_v2', 'us-east-1'\n * Invalid examples: 'ab' (too short), '-prod' (starts with separator), 'foo--bar' (consecutive separators)\n */\nexport const LABEL_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;\n/**\n * Serialize labels array to JSON string for database storage.\n * Returns null for empty or undefined arrays.\n *\n * @example serializeLabels(['web', 'production']) → '[\"web\",\"production\"]'\n * @example serializeLabels([]) → null\n * @example serializeLabels(undefined) → null\n */\nexport function serializeLabels(labels) {\n if (!labels || labels.length === 0)\n return null;\n return JSON.stringify(labels);\n}\n/**\n * Deserialize labels from JSON string to array.\n * Always returns an array — empty array for null/empty/invalid input.\n *\n * @example deserializeLabels('[\"web\",\"production\"]') → ['web', 'production']\n * @example deserializeLabels(null) → []\n * @example deserializeLabels('') → []\n */\nexport function deserializeLabels(labelsJson) {\n if (!labelsJson)\n return [];\n try {\n const parsed = JSON.parse(labelsJson);\n return Array.isArray(parsed) ? parsed : [];\n }\n catch {\n return [];\n }\n}\n// =============================================================================\n// PASSWORD UTILITIES\n// =============================================================================\n/**\n * Length constraints for the optional deployment password\n * (`DeploymentUploadOptions.password`). Single source of truth shared across\n * platform consumers.\n */\nexport const PASSWORD_CONSTRAINTS = {\n /** Minimum password length in characters */\n MIN_LENGTH: 6,\n /** Maximum password length in characters */\n MAX_LENGTH: 128,\n};\n/**\n * Validate an optional deployment password and return it normalized.\n *\n * Absent (`undefined` / `null`) → returns `undefined`. Present → trim\n * leading/trailing whitespace, then validate against `PASSWORD_CONSTRAINTS`\n * length bounds (internal whitespace is significant and counts toward\n * length). Throws `ShipError.validation` on breach; returns the trimmed\n * value.\n *\n * The trim is canonical: at upload, the API hashes the trimmed value; at\n * unlock, the router trims submissions before hashing. Submission and storage\n * agree byte-for-byte. Length validation runs on the trimmed value because\n * that's the user's actual intent — and it disarms a class of invisible\n * foot-guns (trailing newlines from copy/paste, mobile auto-spacing,\n * password-manager artifacts).\n *\n * Single source of truth shared by SDK (client-side validation, return\n * ignored) and API (server-side enforcement, return threaded into config).\n * Length is part of the wire-format contract; strength rules, if added later,\n * stay server-side. See `CLAUDE.md` \"Validation: format vs policy\".\n */\nexport function validatePassword(value) {\n if (value === undefined || value === null)\n return undefined;\n if (typeof value !== 'string') {\n throw ShipError.validation('Password must be a string');\n }\n const trimmed = value.trim();\n if (trimmed.length < PASSWORD_CONSTRAINTS.MIN_LENGTH ||\n trimmed.length > PASSWORD_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(`Password must be between ${PASSWORD_CONSTRAINTS.MIN_LENGTH} and ${PASSWORD_CONSTRAINTS.MAX_LENGTH} characters`);\n }\n return trimmed;\n}\n","/**\n * @file Environment detection utilities for the Ship SDK.\n * Helps in determining whether the SDK is running in a Node.js, browser, or unknown environment.\n */\n\n/**\n * Represents the detected or simulated JavaScript execution environment.\n */\nexport type ExecutionEnvironment = 'browser' | 'node' | 'unknown';\n\n/** @internal Environment override for testing. */\nlet _testEnvironment: ExecutionEnvironment | null = null;\n\n/**\n * **FOR TESTING PURPOSES ONLY.**\n *\n * Allows tests to override the detected environment, forcing the SDK to behave\n * as if it's running in the specified environment.\n *\n * @param env - The environment to simulate ('node', 'browser', 'unknown'),\n * or `null` to clear the override and revert to actual environment detection.\n * @internal\n */\nexport function __setTestEnvironment(env: ExecutionEnvironment | null): void {\n _testEnvironment = env;\n}\n\n/**\n * Detects the actual JavaScript execution environment (Node.js, browser, or unknown)\n * by checking for characteristic global objects.\n * @returns The detected environment as {@link ExecutionEnvironment}.\n * @internal\n */\nfunction detectEnvironment(): ExecutionEnvironment {\n // Check for Node.js environment\n if (typeof process !== 'undefined' && process.versions && process.versions.node) {\n return 'node';\n }\n\n // Check for Browser environment (including Web Workers)\n if (typeof window !== 'undefined' || typeof self !== 'undefined') {\n return 'browser';\n }\n\n return 'unknown';\n}\n\n/**\n * Gets the current effective execution environment.\n *\n * This function first checks if a test environment override is active via {@link __setTestEnvironment}.\n * If not, it detects the actual environment (Node.js, browser, or unknown).\n *\n * @returns The current execution environment: 'browser', 'node', or 'unknown'.\n * @public\n */\nexport function getENV(): ExecutionEnvironment {\n // Return test override if set\n if (_testEnvironment) {\n return _testEnvironment;\n }\n\n // Detect actual environment\n return detectEnvironment();\n}\n","/**\n * @file MD5 utility for Blob, Buffer, or file path inputs.\n */\nimport { ShipError } from '@shipstatic/types';\n\nexport interface MD5Result {\n md5: string;\n}\n\nasync function md5Blob(blob: Blob): Promise<MD5Result> {\n const SparkMD5 = (await import('spark-md5')).default;\n const spark = new SparkMD5.ArrayBuffer();\n const chunkSize = 2097152; // 2 MB\n for (let start = 0; start < blob.size; start += chunkSize) {\n const end = Math.min(start + chunkSize, blob.size);\n spark.append(await blob.slice(start, end).arrayBuffer());\n }\n return { md5: spark.end() };\n}\n\nasync function md5Buffer(buffer: Buffer): Promise<MD5Result> {\n const { createHash } = await import('node:crypto');\n const hash = createHash('md5');\n hash.update(buffer);\n return { md5: hash.digest('hex') };\n}\n\nasync function md5Path(path: string): Promise<MD5Result> {\n const { createHash } = await import('node:crypto');\n const { createReadStream } = await import('node:fs');\n return new Promise((resolve, reject) => {\n const hash = createHash('md5');\n const stream = createReadStream(path);\n stream.on('error', (err) =>\n reject(ShipError.business(`Failed to read file for MD5: ${err.message}`)),\n );\n stream.on('data', (chunk) => hash.update(chunk));\n stream.on('end', () => resolve({ md5: hash.digest('hex') }));\n });\n}\n\nexport async function calculateMD5(input: Blob | Buffer | string): Promise<MD5Result> {\n if (input instanceof Blob) return md5Blob(input);\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(input)) return md5Buffer(input);\n if (typeof input === 'string') return md5Path(input);\n throw ShipError.business('Invalid input for MD5 calculation');\n}\n","/**\n * @file Path helper utilities that work in both browser and Node.js environments.\n * Provides environment-agnostic path manipulation functions.\n */\n\n/**\n * Finds the common parent directory from an array of directory paths.\n * Simple, unified implementation for flattenDirs functionality.\n *\n * @param dirPaths - Array of directory paths (not file paths - directories containing the files)\n * @returns The common parent directory path, or empty string if none found\n */\nexport function findCommonParent(dirPaths: string[]): string {\n if (!dirPaths || dirPaths.length === 0) return '';\n\n const normalizedPaths = dirPaths\n .filter((p) => p && typeof p === 'string')\n .map((p) => p.replace(/\\\\/g, '/'));\n\n if (normalizedPaths.length === 0) return '';\n if (normalizedPaths.length === 1) return normalizedPaths[0];\n\n const pathSegments = normalizedPaths.map((p) => p.split('/').filter(Boolean));\n const commonSegments = [];\n const minLength = Math.min(...pathSegments.map((p) => p.length));\n\n for (let i = 0; i < minLength; i++) {\n const segment = pathSegments[0][i];\n if (pathSegments.every((segments) => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n\n return commonSegments.join('/');\n}\n\n/**\n * Converts backslashes to forward slashes for cross-platform compatibility.\n * Does not remove leading slashes (preserves absolute paths).\n * @param path - The path to normalize\n * @returns Path with forward slashes\n */\nexport function normalizeSlashes(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n/**\n * Normalizes a path for web usage by converting backslashes to forward slashes\n * and removing leading slashes.\n * @param path - The path to normalize\n * @returns Normalized path suitable for web deployment\n */\nexport function normalizeWebPath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/\\/+/g, '/').replace(/^\\/+/, '');\n}\n","/**\n * @file Deploy path optimization - the core logic that makes Ship deployments clean and intuitive.\n * Automatically strips common parent directories to create clean deployment URLs.\n */\n\nimport { normalizeWebPath } from './path.js';\n\n/**\n * Represents a file ready for deployment with its optimized path\n */\nexport interface DeployFile {\n /** The clean deployment path (e.g., \"assets/style.css\") */\n path: string;\n /** Original filename */\n name: string;\n}\n\n/**\n * Core path optimization logic.\n * Transforms messy local paths into clean deployment paths.\n *\n * @example\n * Input: [\"dist/index.html\", \"dist/assets/app.js\"]\n * Output: [\"index.html\", \"assets/app.js\"]\n *\n * @param filePaths - Raw file paths from the local filesystem\n * @param options - Path processing options\n */\nexport function optimizeDeployPaths(\n filePaths: string[],\n options: { flatten?: boolean } = {},\n): DeployFile[] {\n // When flattening is disabled, keep original structure\n if (options.flatten === false) {\n return filePaths.map((path) => ({\n path: normalizeWebPath(path),\n name: extractFileName(path),\n }));\n }\n\n // Find the common directory prefix to strip\n const commonPrefix = findCommonDirectory(filePaths);\n\n return filePaths.map((filePath) => {\n let deployPath = normalizeWebPath(filePath);\n\n // Strip the common prefix to create clean deployment paths\n if (commonPrefix) {\n const prefixToRemove = commonPrefix.endsWith('/') ? commonPrefix : `${commonPrefix}/`;\n if (deployPath.startsWith(prefixToRemove)) {\n deployPath = deployPath.substring(prefixToRemove.length);\n }\n }\n\n // Fallback to filename if path becomes empty\n if (!deployPath) {\n deployPath = extractFileName(filePath);\n }\n\n return {\n path: deployPath,\n name: extractFileName(filePath),\n };\n });\n}\n\n/**\n * Finds the common directory shared by all file paths.\n * This is what gets stripped to create clean deployment URLs.\n *\n * @example\n * [\"dist/index.html\", \"dist/assets/app.js\"] → \"dist\"\n * [\"src/components/A.tsx\", \"src/utils/B.ts\"] → \"src\"\n * [\"file1.txt\", \"file2.txt\", \"subdir/file3.txt\"] → \"\" (no common directory)\n */\nfunction findCommonDirectory(filePaths: string[]): string {\n if (!filePaths.length) return '';\n\n // Normalize all paths first\n const normalizedPaths = filePaths.map((path) => normalizeWebPath(path));\n\n // Find the common prefix among all file paths (not just directories)\n const pathSegments = normalizedPaths.map((path) => path.split('/'));\n const commonSegments: string[] = [];\n const minLength = Math.min(...pathSegments.map((segments) => segments.length));\n\n // Check each segment level to find the longest common prefix\n for (let i = 0; i < minLength - 1; i++) {\n // -1 because we don't want to include the filename\n const segment = pathSegments[0][i];\n if (pathSegments.every((segments) => segments[i] === segment)) {\n commonSegments.push(segment);\n } else {\n break;\n }\n }\n\n return commonSegments.join('/');\n}\n\n/**\n * Extracts just the filename from a file path\n */\nfunction extractFileName(path: string): string {\n return path.split(/[/\\\\]/).pop() || path;\n}\n","/**\n * @file File validation utilities for Ship SDK\n * Provides client-side validation for file uploads before deployment\n */\n\nimport type {\n FileValidationResult,\n FileValidationStatusType,\n PlatformLimits,\n ValidatableFile,\n ValidationIssue,\n} from '@shipstatic/types';\nimport {\n FileValidationStatus as FILE_VALIDATION_STATUS,\n hasUnbuiltMarker,\n hasUnsafeChars,\n isBlockedExtension,\n} from '@shipstatic/types';\n\nexport { FILE_VALIDATION_STATUS };\n\n/**\n * Format file size to human-readable string\n */\nexport function formatFileSize(bytes: number, decimals: number = 1): string {\n if (bytes === 0) return '0 Bytes';\n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n return `${parseFloat((bytes / k ** i).toFixed(decimals))} ${sizes[i]}`;\n}\n\n/**\n * Validate filename for deployment safety\n *\n * Blocks only characters that genuinely break the upload→serve round-trip:\n * - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)\n * - \\ Path separator confusion (buildFileKey splits on backslash)\n * - < > \" XSS vectors with zero legitimate use in filenames\n * - \\x00-\\x1f \\x7f Control characters (header injection, display corruption)\n *\n * Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.\n *\n * Additional checks: path traversal, reserved names, leading/trailing dots or spaces.\n */\nexport function validateFileName(filename: string): { valid: boolean; reason?: string } {\n if (hasUnsafeChars(filename)) {\n return { valid: false, reason: 'File name contains unsafe characters' };\n }\n\n if (filename.startsWith(' ') || filename.endsWith(' ')) {\n return { valid: false, reason: 'File name cannot start/end with spaces' };\n }\n\n if (filename.endsWith('.')) {\n return { valid: false, reason: 'File name cannot end with dots' };\n }\n\n const reservedNames = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\\.|$)/i;\n const nameWithoutPath = filename.split('/').pop() || filename;\n if (reservedNames.test(nameWithoutPath)) {\n return { valid: false, reason: 'File name uses a reserved system name' };\n }\n\n if (filename.includes('..')) {\n return { valid: false, reason: 'File name contains path traversal pattern' };\n }\n\n return { valid: true };\n}\n\n/**\n * Validate files against configuration limits with severity-based reporting\n *\n * Validation categorizes issues by severity:\n * - **Errors**: Block deployment (file too large, blocked extension, etc.)\n * - **Warnings**: Exclude files but allow deployment (empty files, etc.)\n *\n * @param files - Array of files to validate\n * @param config - Validation configuration from ship.getLimits()\n * @returns Validation result with errors and warnings\n *\n * @example\n * ```typescript\n * const config = await ship.getLimits();\n * const result = validateFiles(files, config);\n *\n * if (!result.canDeploy) {\n * // Has errors - deployment blocked\n * console.error('Deployment blocked:', result.errors);\n * } else if (result.warnings.length > 0) {\n * // Has warnings - deployment proceeds, some files excluded\n * console.warn('Files excluded:', result.warnings);\n * await ship.deploy(result.validFiles);\n * } else {\n * // All files valid\n * await ship.deploy(result.validFiles);\n * }\n * ```\n */\nexport function validateFiles<T extends ValidatableFile>(\n files: T[],\n config: PlatformLimits,\n): FileValidationResult<T> {\n const errors: ValidationIssue[] = [];\n const warnings: ValidationIssue[] = [];\n let fileStatuses: T[] = []; // Use 'let' for atomic enforcement later\n\n // Check at least 1 file required\n if (files.length === 0) {\n const issue: ValidationIssue = {\n file: '(no files)',\n message: 'At least one file must be provided',\n };\n errors.push(issue);\n\n return {\n files: [],\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Check for unbuilt project markers (node_modules/, etc.)\n for (const file of files) {\n if (hasUnbuiltMarker(file.name)) {\n errors.push({\n file: file.name,\n message: `Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder`,\n });\n return {\n files: files.map((f) => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: 'Unbuilt project detected',\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n }\n\n // Check file count limit\n if (files.length > config.maxFilesCount) {\n const issue: ValidationIssue = {\n file: `(${files.length} files)`,\n message: `File count (${files.length}) exceeds limit of ${config.maxFilesCount}`,\n };\n errors.push(issue);\n\n return {\n files: files.map((f) => ({\n ...f,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage: issue.message,\n })),\n validFiles: [],\n errors,\n warnings: [],\n canDeploy: false,\n };\n }\n\n // Validate each file\n let totalSize = 0;\n\n for (const file of files) {\n let fileStatus: FileValidationStatusType = FILE_VALIDATION_STATUS.READY;\n let statusMessage = 'Ready for upload';\n\n // Pre-compute filename validation\n const nameValidation = file.name\n ? validateFileName(file.name)\n : { valid: false, reason: 'File name cannot be empty' };\n\n // Check for processing errors\n if (file.status === FILE_VALIDATION_STATUS.PROCESSING_ERROR) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = file.statusMessage || 'File failed during processing';\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n\n // EMPTY FILE - Warning (not error)\n else if (file.size === 0) {\n fileStatus = FILE_VALIDATION_STATUS.EXCLUDED;\n statusMessage = 'File is empty (0 bytes) and cannot be deployed due to storage limitations';\n warnings.push({\n file: file.name,\n message: statusMessage,\n });\n // Skip other validations for excluded files\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n continue;\n }\n\n // Negative file size - Error\n else if (file.size < 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File size must be positive';\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n\n // File name validation\n else if (!file.name || file.name.trim().length === 0) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name cannot be empty';\n errors.push({\n file: file.name || '(empty)',\n message: statusMessage,\n });\n } else if (file.name.includes('\\0')) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = 'File name contains invalid characters (null byte)';\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n } else if (!nameValidation.valid) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = nameValidation.reason || 'Invalid file name';\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n\n // Blocked extension check\n else if (isBlockedExtension(file.name)) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File extension not allowed: \"${file.name}\"`;\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n\n // File size validation\n else if (file.size > config.maxFileSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `File size (${formatFileSize(file.size)}) exceeds limit of ${formatFileSize(config.maxFileSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n\n // Total size validation\n else {\n totalSize += file.size;\n if (totalSize > config.maxTotalSize) {\n fileStatus = FILE_VALIDATION_STATUS.VALIDATION_FAILED;\n statusMessage = `Total size would exceed limit of ${formatFileSize(config.maxTotalSize)}`;\n errors.push({\n file: file.name,\n message: statusMessage,\n });\n }\n }\n\n fileStatuses.push({\n ...file,\n status: fileStatus,\n statusMessage,\n });\n }\n\n // ATOMIC ENFORCEMENT: Two-phase validation for optimal UX + atomic semantics\n // Phase 1 (above): Validate files individually to collect ALL errors\n // Phase 2 (below): Mark all files as failed if any errors exist\n //\n // Why two phases? We validate individually for better UX (users see all problems\n // at once and can fix everything in one pass), then enforce atomicity to maintain\n // deployment transaction semantics (all-or-nothing).\n if (errors.length > 0) {\n fileStatuses = fileStatuses.map((file) => {\n // Keep EXCLUDED files as-is (they're warnings, not errors)\n if (file.status === FILE_VALIDATION_STATUS.EXCLUDED) {\n return file;\n }\n\n // Mark ALL other files as VALIDATION_FAILED (atomic deployment)\n return {\n ...file,\n status: FILE_VALIDATION_STATUS.VALIDATION_FAILED,\n statusMessage:\n file.status === FILE_VALIDATION_STATUS.VALIDATION_FAILED\n ? file.statusMessage // Keep original error message for the file that actually failed\n : 'Deployment failed due to validation errors in bundle',\n };\n });\n }\n\n // Build atomic result\n // validFiles is empty if ANY errors exist (all-or-nothing)\n const validFiles =\n errors.length === 0\n ? fileStatuses.filter((f) => f.status === FILE_VALIDATION_STATUS.READY)\n : [];\n const canDeploy = errors.length === 0;\n\n return {\n files: fileStatuses,\n validFiles,\n errors,\n warnings,\n canDeploy,\n };\n}\n\n/**\n * Get only the valid files from validation results\n */\nexport function getValidFiles<T extends ValidatableFile>(files: T[]): T[] {\n return files.filter((f) => f.status === FILE_VALIDATION_STATUS.READY);\n}\n\n/**\n * Check if all valid files have required properties for upload\n * (Can be extended to check for MD5, etc.)\n */\nexport function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean {\n const validFiles = getValidFiles(files);\n return validFiles.length > 0;\n}\n","/**\n * @file Utility for filtering out junk files and directories from file paths\n *\n * This module provides functionality to filter out common system junk files and directories\n * from a list of file paths. It uses the 'junk' package to identify junk filenames and\n * a custom list to filter out common junk directories.\n */\n\nimport { hasUnbuiltMarker, ShipError } from '@shipstatic/types';\nimport { isJunk } from 'junk';\n\n/**\n * List of directory names considered as junk\n *\n * Files within these directories (at any level in the path hierarchy) will be excluded.\n * The comparison is case-insensitive for cross-platform compatibility.\n *\n * @internal\n */\nexport const JUNK_DIRECTORIES = ['__MACOSX', '.Trashes', '.fseventsd', '.Spotlight-V100'] as const;\n\n/**\n * Filters an array of file paths, removing those considered junk\n *\n * Throws if any path contains an unbuilt project marker (e.g. `node_modules`, `package.json`).\n * This check runs first because the dot-file filter below would strip paths like\n * `node_modules/.pnpm/...`, destroying the evidence.\n *\n * A path is filtered out if any of these conditions are met:\n * 1. The basename is identified as junk by the 'junk' package (e.g., .DS_Store, Thumbs.db)\n * 2. Any path segment starts with a dot (e.g., .env, .git, .htaccess)\n * Exception: `.well-known` is allowed (RFC 8615 — ACME, security.txt, app links)\n * 3. Any path segment exceeds 255 characters (filesystem limit)\n * 4. Any directory segment in the path matches an entry in JUNK_DIRECTORIES (case-insensitive)\n *\n * All path separators are normalized to forward slashes for consistent cross-platform behavior.\n *\n * Dot files are filtered for security — they typically contain sensitive configuration\n * (.env, .git) or are not meant to be served publicly. This matches server-side filtering.\n *\n * @param filePaths - An array of file path strings to filter\n * @param options - Optional settings\n * @param options.allowUnbuilt - When true, skip the unbuilt project marker check (for server-processed uploads)\n * @returns A new array containing only non-junk file paths\n * @throws {ShipError} If any path contains an unbuilt project marker (unless allowUnbuilt is true)\n *\n * @example\n * ```typescript\n * import { filterJunk } from '@shipstatic/ship';\n *\n * // Filter an array of file paths\n * const paths = ['index.html', '.DS_Store', '.gitattributes', '__MACOSX/file.txt', 'app.js'];\n * const clean = filterJunk(paths);\n * // Result: ['index.html', 'app.js']\n * ```\n *\n * @example\n * ```typescript\n * // Use with browser File objects\n * import { filterJunk } from '@shipstatic/ship';\n *\n * const files: File[] = [...]; // From input or drag-drop\n *\n * // Extract paths from File objects\n * const filePaths = files.map(f => f.webkitRelativePath || f.name);\n *\n * // Filter out junk paths\n * const validPaths = new Set(filterJunk(filePaths));\n *\n * // Filter the original File array\n * const validFiles = files.filter(f =>\n * validPaths.has(f.webkitRelativePath || f.name)\n * );\n * ```\n */\nexport function filterJunk(filePaths: string[], options?: { allowUnbuilt?: boolean }): string[] {\n if (!filePaths || filePaths.length === 0) {\n return [];\n }\n\n // Reject unbuilt projects before the dot-file filter removes evidence.\n // pnpm stores files under node_modules/.pnpm/ — the dot-file filter below\n // strips .pnpm/ paths, destroying the only signal that this is an unbuilt project.\n if (!options?.allowUnbuilt) {\n const marker = filePaths.find((p) => p && hasUnbuiltMarker(p));\n if (marker) {\n throw ShipError.business(\n 'Unbuilt project detected — deploy your build output (dist/, build/, out/), not the project folder',\n );\n }\n }\n\n return filePaths.filter((filePath) => {\n if (!filePath) {\n return false; // Exclude null or undefined paths\n }\n\n // Normalize path separators to forward slashes and split into segments\n const parts = filePath.replace(/\\\\/g, '/').split('/').filter(Boolean);\n if (parts.length === 0) return true;\n\n // Check if the basename is a junk file (using junk package)\n const basename = parts[parts.length - 1];\n if (isJunk(basename)) {\n return false;\n }\n\n // Filter out dot files and directories (security: prevents .env, .git, etc.)\n // .well-known is not junk — it's a standard directory (RFC 8615)\n // Path position constraints enforced at upload (buildFileKey) and serving (isBlockedDotFile)\n for (const part of parts) {\n if (part === '.well-known') continue;\n if (part.startsWith('.') || part.length > 255) {\n return false;\n }\n }\n\n // Check if any directory segment is in our junk directories list\n const directorySegments = parts.slice(0, -1);\n for (const segment of directorySegments) {\n if (JUNK_DIRECTORIES.some((junkDir) => segment.toLowerCase() === junkDir.toLowerCase())) {\n return false;\n }\n }\n\n return true;\n });\n}\n","/**\n * @file Shared security validation for the deploy pipeline.\n * Used by both Node.js and browser file processing pipelines.\n */\nimport { isBlockedExtension, ShipError } from '@shipstatic/types';\nimport { validateFileName } from './file-validation.js';\n\n/**\n * Validate a deploy path for security concerns.\n * Rejects paths containing path traversal patterns or null bytes.\n *\n * Checks for:\n * - Null bytes (\\0) — path injection\n * - /../ — directory traversal within path\n * - ../ at start — upward traversal\n * - /.. at end — trailing traversal\n *\n * Does NOT reject double dots in filenames (e.g., \"foo..bar.txt\" is safe).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the path contains unsafe patterns\n */\nexport function validateDeployPath(deployPath: string, sourceIdentifier: string): void {\n if (\n deployPath.includes('\\0') ||\n deployPath.includes('/../') ||\n deployPath.startsWith('../') ||\n deployPath.endsWith('/..')\n ) {\n throw ShipError.business(\n `Security error: Unsafe file path \"${deployPath}\" for file: ${sourceIdentifier}`,\n );\n }\n}\n\n/**\n * Validate a deploy file's name and extension.\n * Rejects unsafe filenames (shell/URL-dangerous chars, reserved names)\n * and blocked file extensions (.exe, .msi, .dll, etc.).\n *\n * @param deployPath - The deployment path to validate\n * @param sourceIdentifier - Human-readable identifier for error messages\n * @throws {ShipError} If the filename is unsafe or extension is blocked\n */\nexport function validateDeployFile(deployPath: string, sourceIdentifier: string): void {\n const nameCheck = validateFileName(deployPath);\n if (!nameCheck.valid) {\n throw ShipError.business(nameCheck.reason || 'Invalid file name');\n }\n\n if (isBlockedExtension(deployPath)) {\n throw ShipError.business(`File extension not allowed: \"${sourceIdentifier}\"`);\n }\n}\n","/**\n * @file Node.js-specific file utilities for the Ship SDK.\n * Provides helpers for recursively discovering, filtering, and preparing files for deploy in Node.js.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { PlatformLimits } from '@shipstatic/types';\nimport { isShipError, ShipError, UNBUILT_PROJECT_MARKERS } from '@shipstatic/types';\nimport { optimizeDeployPaths } from '../../shared/lib/deploy-paths.js';\nimport { getENV } from '../../shared/lib/env.js';\nimport { filterJunk } from '../../shared/lib/junk.js';\nimport { calculateMD5 } from '../../shared/lib/md5.js';\nimport { findCommonParent } from '../../shared/lib/path.js';\nimport { validateDeployFile, validateDeployPath } from '../../shared/lib/security.js';\nimport type { DeploymentOptions, StaticFile } from '../../shared/types.js';\n\n/**\n * Recursive function to walk directory and return all file paths.\n * Includes symlink loop protection to prevent infinite recursion.\n * @param dirPath - Directory path to traverse\n * @param visited - Set of already visited real paths (for cycle detection)\n * @returns Array of absolute file paths in the directory\n */\nfunction findAllFilePaths(dirPath: string, visited: Set<string> = new Set()): string[] {\n const results: string[] = [];\n\n // Resolve the real path to detect symlink cycles\n const realPath = fs.realpathSync(dirPath);\n if (visited.has(realPath)) {\n // Already visited this directory (symlink cycle) - skip to prevent infinite loop\n return results;\n }\n visited.add(realPath);\n\n const entries = fs.readdirSync(dirPath);\n\n for (const entry of entries) {\n const fullPath = path.join(dirPath, entry);\n const stats = fs.statSync(fullPath);\n\n if (stats.isDirectory()) {\n const subFiles = findAllFilePaths(fullPath, visited);\n results.push(...subFiles);\n } else if (stats.isFile()) {\n results.push(fullPath);\n }\n }\n\n return results;\n}\n\n/**\n * Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.\n * Computes content paths relative to the upload root before filtering, so only the deployed\n * directory structure is evaluated — not the user's filesystem above it.\n *\n * @param paths - File or directory paths to scan and process.\n * @param options - Processing options (pathDetect, etc.).\n * @param platformLimits - Per-instance platform limits (file-size / count /\n * total-size caps) from the originating Ship's `GET /config` fetch. Passed\n * in rather than read from a module global so concurrent Ships against\n * different API URLs cannot clobber each other's caps.\n * @returns Promise resolving to an array of StaticFile objects.\n * @throws {ShipClientError} If called outside Node.js or if fs/path modules fail.\n */\nexport async function processFilesForNode(\n paths: string[],\n options: DeploymentOptions = {},\n platformLimits?: PlatformLimits,\n): Promise<StaticFile[]> {\n if (getENV() !== 'node') {\n throw ShipError.business('processFilesForNode can only be called in Node.js environment.');\n }\n\n // Check input directories for unbuilt project markers before recursive walk\n for (const p of paths) {\n const absPath = path.resolve(p);\n try {\n if (fs.statSync(absPath).isDirectory()) {\n const marker = fs.readdirSync(absPath).find((e) => UNBUILT_PROJECT_MARKERS.has(e));\n if (marker) {\n throw ShipError.business(\n `\"${marker}\" detected — deploy your build output (dist/, build/, out/), not the project folder`,\n );\n }\n }\n } catch (e) {\n if (isShipError(e)) throw e;\n // Path errors handled in the existing flatMap below\n }\n }\n\n // 1. Discover all unique, absolute file paths from the input list\n const absolutePaths = paths.flatMap((p) => {\n const absPath = path.resolve(p);\n try {\n const stats = fs.statSync(absPath);\n return stats.isDirectory() ? findAllFilePaths(absPath) : [absPath];\n } catch (_error) {\n throw ShipError.file(`Path does not exist: ${p}`, { filePath: p });\n }\n });\n const uniquePaths = [...new Set(absolutePaths)];\n\n // 2. Determine base path for content paths (from INPUT paths, not discovered files)\n const inputAbsolutePaths = paths.map((p) => path.resolve(p));\n const inputBasePath = findCommonParent(\n inputAbsolutePaths.map((p) => {\n try {\n const stats = fs.statSync(p);\n return stats.isDirectory() ? p : path.dirname(p);\n } catch {\n return path.dirname(p);\n }\n }),\n );\n\n // 3. Compute content paths (relative to upload root)\n const contentPaths = uniquePaths.map((absPath) => {\n if (inputBasePath && inputBasePath.length > 0) {\n const rel = path.relative(inputBasePath, absPath);\n if (rel && typeof rel === 'string' && !rel.startsWith('..')) {\n return rel.replace(/\\\\/g, '/');\n }\n }\n return path.basename(absPath);\n });\n\n // 4. Optimize paths for deployment (strip common root, flatten)\n const deployFiles = optimizeDeployPaths(contentPaths, {\n flatten: options.pathDetect !== false,\n });\n const deployPaths = deployFiles.map((f) => f.path);\n\n // 5. Filter junk from deploy paths\n const filteredSet = new Set(filterJunk(deployPaths));\n if (filteredSet.size === 0) {\n return [];\n }\n\n // 6. Collect valid file pairs (absolute path for reading, deploy path for output)\n const validAbsPaths: string[] = [];\n const validDeployPaths: string[] = [];\n for (let i = 0; i < uniquePaths.length; i++) {\n if (filteredSet.has(deployPaths[i])) {\n validAbsPaths.push(uniquePaths[i]);\n validDeployPaths.push(deployPaths[i]);\n }\n }\n\n // 7. Process files into StaticFile objects\n const results: StaticFile[] = [];\n let totalSize = 0;\n if (!platformLimits) {\n throw ShipError.config(\n 'Platform limits not provided. processFilesForNode requires the limits ' +\n 'argument — pass `ship.getLimits()` result.',\n );\n }\n\n for (let i = 0; i < validAbsPaths.length; i++) {\n const filePath = validAbsPaths[i];\n const deployPath = validDeployPaths[i];\n\n try {\n // Security validation (shared with browser) — fail fast before any I/O\n validateDeployPath(deployPath, filePath);\n\n const stats = fs.statSync(filePath);\n\n // Skip empty files — R2 cannot store zero-byte objects\n if (stats.size === 0) {\n continue;\n }\n\n // Filename and extension validation (shared with browser)\n validateDeployFile(deployPath, filePath);\n\n // Validate file sizes\n if (stats.size > platformLimits.maxFileSize) {\n throw ShipError.business(\n `File ${filePath} is too large. Maximum allowed size is ${platformLimits.maxFileSize / (1024 * 1024)}MB.`,\n );\n }\n totalSize += stats.size;\n if (totalSize > platformLimits.maxTotalSize) {\n throw ShipError.business(\n `Total deploy size is too large. Maximum allowed is ${platformLimits.maxTotalSize / (1024 * 1024)}MB.`,\n );\n }\n\n const content = fs.readFileSync(filePath);\n const { md5 } = await calculateMD5(content);\n\n results.push({\n path: deployPath,\n content,\n size: content.length,\n md5,\n });\n } catch (error) {\n // Re-throw ShipError instances directly\n if (isShipError(error)) {\n throw error;\n }\n // Convert file system errors to ShipError with clear message\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw ShipError.file(`Failed to read file \"${filePath}\": ${errorMessage}`, { filePath });\n }\n }\n\n // Final validation\n if (results.length > platformLimits.maxFilesCount) {\n throw ShipError.business(\n `Too many files to deploy. Maximum allowed is ${platformLimits.maxFilesCount} files.`,\n );\n }\n\n return results;\n}\n","/**\n * @file Main entry point for the Ship CLI.\n */\n\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport * as path from 'node:path';\nimport {\n type Deployment,\n ErrorType,\n isShipError,\n ShipError,\n validateApiUrl,\n validateToken,\n} from '@shipstatic/types';\nimport { Command } from 'commander';\nimport { bold, dim } from 'yoctocolors';\nimport { readEnvConfig } from '../core/config.js';\nimport type { Ship } from '../index.js';\nimport { installCompletion, uninstallCompletion } from './completion.js';\nimport { runConfig } from './config.js';\nimport { createClient, mergeCliConfig } from './create-client.js';\nimport { formatErrorJson, getUserMessage, toShipError } from './error-handling.js';\nimport { formatOutput, type OutputContext } from './formatters.js';\nimport { loadShipFile } from './shiprc.js';\nimport type {\n CLIResult,\n DeployCommandOptions,\n GlobalOptions,\n LabelOptions,\n TokenCreateCommandOptions,\n} from './types.js';\nimport { error } from './utils.js';\n\n// Load package.json for version\nfunction loadPackageJson(): { version: string } {\n const paths = [\n path.resolve(__dirname, '../package.json'),\n path.resolve(__dirname, '../../package.json'),\n ];\n for (const p of paths) {\n try {\n return JSON.parse(readFileSync(p, 'utf-8'));\n } catch {}\n }\n return { version: '0.0.0' };\n}\n\nconst packageJson = loadPackageJson();\n\nconst program = new Command();\n\n// Override Commander.js error handling while preserving help/version behavior\nprogram\n .exitOverride((err) => {\n // Only override actual errors, not help/version exits\n if (err.code === 'commander.help' || err.code === 'commander.version' || err.exitCode === 0) {\n process.exit(err.exitCode || 0);\n }\n\n // --help alongside a parse error (e.g., ship deployments upload --help)\n // Show help instead of the error\n if (process.argv.includes('--help')) {\n displayHelp(processOptions(program).noColor);\n process.exit(0);\n }\n\n const globalOptions = processOptions(program);\n\n let message = err.message || 'unknown command error';\n message = message\n .replace(/^error: /, '')\n .replace(/\\n.*/, '')\n .replace(/\\.$/, '')\n .toLowerCase();\n\n error(message, globalOptions.json, globalOptions.noColor);\n\n if (!globalOptions.json) {\n displayHelp(globalOptions.noColor);\n }\n\n process.exit(err.exitCode || 1);\n })\n .configureOutput({\n writeErr: (str) => {\n if (!str.startsWith('error:')) {\n process.stderr.write(str);\n }\n },\n writeOut: (str) => process.stdout.write(str),\n });\n\n/**\n * Display comprehensive help information for all commands\n */\nfunction displayHelp(noColor?: boolean) {\n const applyBold = (text: string) => (noColor ? text : bold(text));\n const applyDim = (text: string) => (noColor ? text : dim(text));\n const icon = (emoji: string) => (noColor ? '' : `${emoji} `);\n\n const output = `${applyBold('USAGE')}\n ship <path> ${icon('🚀')}Deploy static sites with simplicity\n\n${applyBold('COMMANDS')}\n ${icon('📦')}${applyBold('Deployments')}\n ship deployments list List all deployments\n ship deployments upload <path> Upload deployment from directory\n ship deployments get <deployment> Show deployment information\n ship deployments set <deployment> Set deployment labels\n ship deployments remove <deployment> Delete deployment permanently\n\n ${icon('🌎')}${applyBold('Domains')}\n ship domains list List all domains\n ship domains set <name> [deployment] Create domain, link to deployment, or update labels\n ship domains get <name> Show domain information\n ship domains validate <name> Check if domain name is valid and available\n ship domains records <name> Show required DNS records for domain setup\n ship domains dns <name> Look up DNS provider for a domain\n ship domains share <name> Get shareable DNS setup link\n ship domains verify <name> Trigger DNS verification for external domain\n ship domains remove <name> Delete domain permanently\n\n ${icon('🔑')}${applyBold('Tokens')}\n ship tokens list List all deploy tokens\n ship tokens create Create a new deploy token\n ship tokens remove <token> Delete token permanently\n\n ${icon('⚙️')}${applyBold('Setup')}\n ship config Save your token\n ship whoami Get current account information\n\n ${icon('🛠️')}${applyBold('Completion')}\n ship completion install Install shell completion script\n ship completion uninstall Uninstall shell completion script\n\n${applyBold('FLAGS')}\n --token <token> Any ship token: API key (ship-…) or deploy token (deploy-…)\n --config <file> Custom config file path\n --label <label> Set label (repeatable, replaces all existing)\n --password <password> Password-protect this deployment\n --no-path-detect Disable automatic path optimization and flattening\n --no-spa-detect Disable automatic SPA detection and configuration\n --no-color Disable colored output\n --json Output results in JSON format\n -q, --quiet Output only the resource identifier\n --version Show version information\n\n${applyBold('EXAMPLES')}\n ship ./dist\n ship domains set www.example.com happy-cat-abc1234.shipstatic.com\n ship ./dist -q | ship domains set www.example.com\n\n${applyDim('Please report any issues to https://github.com/shipstatic/ship/issues')}\n`;\n\n console.log(output);\n}\n\n/**\n * Collector function for Commander.js to accumulate repeated option values.\n * Used for --label flag that can be specified multiple times.\n */\nfunction collect(value: string, previous: string[] = []): string[] {\n return previous.concat([value]);\n}\n\n/**\n * Merge label options from command and program levels.\n * Commander.js sometimes routes --label to program level instead of command level.\n */\nfunction mergeLabelOption(\n cmdOptions: LabelOptions | undefined,\n programOpts: LabelOptions | undefined,\n): string[] | undefined {\n const labels = cmdOptions?.label?.length ? cmdOptions.label : programOpts?.label;\n if (!labels?.length) return undefined;\n // Filter empty strings: --label '' means \"clear all labels\"\n const filtered = labels.filter((l) => l !== '');\n return filtered.length ? filtered : [];\n}\n\n/**\n * Merge password options from command and program levels.\n * Commander.js sometimes routes --password to program level instead of command level.\n *\n * An empty `--password ''` is forwarded to the SDK validator so the user\n * sees a clear length error rather than a silent drop. An empty\n * `SHIP_PASSWORD` is coerced to undefined, matching how SHIP_TOKEN\n * and SHIP_API_URL treat empty env vars (CI/Docker\n * often sets unset vars to \"\" — see core/config.ts).\n */\nfunction mergePasswordOption(\n cmdOptions: { password?: string } | undefined,\n programOpts: { password?: string } | undefined,\n): string | undefined {\n return cmdOptions?.password ?? programOpts?.password ?? (process.env.SHIP_PASSWORD || undefined);\n}\n\n/**\n * Handle unknown or missing subcommand for parent commands.\n * Shows scoped usage instead of full help — the user already knows the group.\n */\nfunction handleUnknownSubcommand(\n parentName: string,\n validSubcommands: string[],\n): (...args: unknown[]) => void {\n return (...args: unknown[]) => {\n const globalOptions = processOptions(program);\n\n // Get the command object (last argument) - Commander passes it as the final arg\n const commandObj = args[args.length - 1] as { args?: string[] } | undefined;\n\n // Check if an unknown subcommand was provided\n if (commandObj?.args?.length) {\n const unknownArg = commandObj.args.find((arg) => !validSubcommands.includes(arg));\n if (unknownArg) {\n error(`unknown command '${unknownArg}'`, globalOptions.json, globalOptions.noColor);\n }\n }\n\n if (!globalOptions.json) {\n console.log(`usage: ship ${parentName} <${validSubcommands.join('|')}>\\n`);\n }\n process.exit(1);\n };\n}\n\n/**\n * Process CLI options using Commander's built-in option merging.\n * Applies CLI-specific transformations (validation is done in preAction hook).\n */\nfunction processOptions(command: Command): GlobalOptions {\n const options = command.optsWithGlobals();\n\n // Convert Commander.js --no-color flag (color: false) to our convention (noColor: true)\n if (options.color === false) {\n options.noColor = true;\n }\n\n // Auto-suppress color when stdout is not a TTY (like grep --color=auto)\n // Also respect NO_COLOR convention (https://no-color.org/)\n // FORCE_COLOR overrides for CI environments that explicitly want color\n // FORCE_COLOR=0 means \"force no color\" per the convention (0=off, 1/2/3=on)\n const forceColor = !!process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0';\n if (!options.noColor && !forceColor) {\n if (!process.stdout.isTTY || process.env.NO_COLOR !== undefined) {\n options.noColor = true;\n }\n }\n\n return options as GlobalOptions;\n}\n\n/**\n * Error handler - outputs errors consistently in text or JSON format.\n * Message formatting is delegated to the error-handling module.\n */\n/**\n * The credential the CLI actually resolved (flag > env > file). The error\n * path must diagnose with the same lens the client was built with — a user\n * whose `SHIP_TOKEN` or `.shiprc` token was rejected is credentialed, and\n * the anonymous-user hint would misdiagnose their failure. A config file\n * that fails to load counts as no file credential: that failure is already\n * the error being reported.\n */\nfunction resolveCliToken(flags: {\n config?: string;\n apiUrl?: string;\n token?: string;\n}): string | undefined {\n let file = {};\n try {\n file = loadShipFile(flags.config);\n } catch {}\n // Flags, env, and files only ever hold strings — provider functions exist\n // solely as constructor arguments, which the CLI never passes.\n const token = mergeCliConfig(flags, readEnvConfig(), file).token;\n return typeof token === 'string' ? token : undefined;\n}\n\nfunction handleError(err: unknown, context?: OutputContext) {\n const opts = processOptions(program);\n const shipError = toShipError(err);\n\n // Get user-facing message using the extracted pure function\n const message = getUserMessage(shipError, context, {\n token: resolveCliToken(program.opts()),\n });\n\n // Output in appropriate format\n if (opts.json) {\n console.error(`${formatErrorJson(message, shipError.details)}\\n`);\n } else {\n error(message, false, opts.noColor);\n // Show help only for unknown command errors (user CLI mistake)\n if (shipError.type === ErrorType.Validation && message.includes('unknown command')) {\n displayHelp(opts.noColor);\n }\n }\n\n process.exit(1);\n}\n\n/**\n * Wrapper for CLI actions that handles errors and client creation consistently.\n * Reduces boilerplate while preserving context for error handling.\n */\nfunction withErrorHandling<T extends unknown[], R extends CLIResult>(\n handler: (client: Ship, options: GlobalOptions, ...args: T) => Promise<R>,\n context?: { operation?: string; resourceType?: string; getResourceId?: (...args: T) => string },\n) {\n return async function (this: Command, ...args: T) {\n const globalOptions = processOptions(this);\n\n // Build context once for both output and error paths\n const resolvedContext: OutputContext = context\n ? {\n operation: context.operation,\n resourceType: context.resourceType,\n resourceId: context.getResourceId?.(...args),\n }\n : {};\n\n try {\n const { config, apiUrl, token } = program.opts();\n const client = createClient({ config, apiUrl, token });\n const result = await handler(client, globalOptions, ...args);\n formatOutput(result, resolvedContext, {\n json: globalOptions.json,\n quiet: globalOptions.quiet,\n noColor: globalOptions.noColor,\n });\n } catch (err) {\n handleError(err, resolvedContext);\n }\n };\n}\n\n/** Spinner instance type from yocto-spinner */\ninterface Spinner {\n start(): Spinner;\n stop(): void;\n}\n\n/**\n * Common deploy logic used by both shortcut and explicit commands.\n */\nasync function performDeploy(\n client: Ship,\n deployPath: string,\n labels: string[] | undefined,\n password: string | undefined,\n cmdOptions: DeployCommandOptions | undefined,\n globalOptions: GlobalOptions,\n): Promise<Deployment> {\n if (!existsSync(deployPath)) {\n throw ShipError.file(`${deployPath} path does not exist`, { filePath: deployPath });\n }\n\n const stats = statSync(deployPath);\n if (!stats.isDirectory() && !stats.isFile()) {\n throw ShipError.file(`${deployPath} path must be a file or directory`, {\n filePath: deployPath,\n });\n }\n\n const deployOptions: {\n via: string;\n labels?: string[];\n password?: string;\n pathDetect?: boolean;\n spaDetect?: boolean;\n signal?: AbortSignal;\n } = { via: process.env.SHIP_VIA || 'cli' };\n\n // Handle labels\n if (labels !== undefined) deployOptions.labels = labels;\n\n // Empty password strings flow through to the SDK validator (clear length\n // error) instead of being silently dropped.\n if (password !== undefined) deployOptions.password = password;\n\n // Handle detection flags\n if (cmdOptions?.noPathDetect !== undefined) {\n deployOptions.pathDetect = !cmdOptions.noPathDetect;\n }\n if (cmdOptions?.noSpaDetect !== undefined) {\n deployOptions.spaDetect = !cmdOptions.noSpaDetect;\n }\n\n // Cancellation support\n const abortController = new AbortController();\n deployOptions.signal = abortController.signal;\n\n // Spinner (TTY only, not JSON, not --no-color)\n let spinner: Spinner | null = null;\n if (\n process.stdout.isTTY &&\n !globalOptions.json &&\n !globalOptions.quiet &&\n !globalOptions.noColor\n ) {\n const { default: yoctoSpinner } = await import('yocto-spinner');\n spinner = yoctoSpinner({ text: 'uploading…' }).start();\n }\n\n const sigintHandler = () => {\n abortController.abort();\n if (spinner) spinner.stop();\n process.exit(130);\n };\n process.on('SIGINT', sigintHandler);\n\n try {\n return await client.deployments.upload(deployPath, deployOptions);\n } finally {\n process.removeListener('SIGINT', sigintHandler);\n if (spinner) spinner.stop();\n }\n}\n\nprogram\n .name('ship')\n .description('🚀 Deploy static sites with simplicity')\n .version(packageJson.version, '--version', 'Show version information')\n .option('--token <token>', 'Any ship token: API key (ship-…) or deploy token (deploy-…)')\n .option('--config <file>', 'Custom config file path')\n .option('--api-url <url>', 'API URL (for development)')\n .option('--json', 'Output results in JSON format')\n .option('-q, --quiet', 'Output only the resource identifier')\n .option('--no-color', 'Disable colored output')\n .option('--help', 'Display help for command')\n .helpOption(false); // Disable default help\n\n// Handle --help flag manually to show custom help\nprogram.hook('preAction', (thisCommand) => {\n const options = processOptions(thisCommand);\n if (options.help) {\n displayHelp(options.noColor);\n process.exit(0);\n }\n});\n\n// Validate options early - before any action is executed\nprogram.hook('preAction', (thisCommand) => {\n const options = processOptions(thisCommand);\n\n try {\n if (options.token && typeof options.token === 'string') {\n validateToken(options.token);\n }\n\n if (options.apiUrl && typeof options.apiUrl === 'string') {\n validateApiUrl(options.apiUrl);\n }\n } catch (validationError) {\n if (isShipError(validationError)) {\n error(validationError.message, options.json, options.noColor);\n process.exit(1);\n }\n throw validationError;\n }\n});\n\n// Ping command\nprogram\n .command('ping')\n .description('Check API connectivity')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.ping()));\n\n// Whoami shortcut - alias for account get\nprogram\n .command('whoami')\n .description('Get current account information')\n .action(\n withErrorHandling((client: Ship, _options: GlobalOptions) => client.whoami(), {\n operation: 'get',\n resourceType: 'Account',\n }),\n );\n\n// Deployments commands\nconst deploymentsCmd = program\n .command('deployments')\n .description('Manage deployments')\n .enablePositionalOptions()\n .action(handleUnknownSubcommand('deployments', ['list', 'upload', 'get', 'set', 'remove']));\n\ndeploymentsCmd\n .command('list')\n .description('List all deployments')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.deployments.list()));\n\ndeploymentsCmd\n .command('upload <path>')\n .description('Upload deployment from file or directory')\n .passThroughOptions()\n .option('--label <label>', 'Label to add (can be repeated)', collect, [])\n .option('--password <password>', 'Password-protect this deployment')\n .option('--no-path-detect', 'Disable automatic path optimization and flattening')\n .option('--no-spa-detect', 'Disable automatic SPA detection and configuration')\n .action(\n withErrorHandling(\n (\n client: Ship,\n options: GlobalOptions,\n deployPath: string,\n cmdOptions: DeployCommandOptions,\n ) =>\n performDeploy(\n client,\n deployPath,\n mergeLabelOption(cmdOptions, program.opts() as LabelOptions),\n mergePasswordOption(cmdOptions, program.opts() as { password?: string }),\n cmdOptions,\n options,\n ),\n { operation: 'upload' },\n ),\n );\n\ndeploymentsCmd\n .command('get <deployment>')\n .description('Show deployment information')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, deployment: string) =>\n client.deployments.get(deployment),\n { operation: 'get', resourceType: 'Deployment', getResourceId: (id: string) => id },\n ),\n );\n\ndeploymentsCmd\n .command('set <deployment>')\n .description('Set deployment labels')\n .passThroughOptions()\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(\n withErrorHandling(\n async (\n client: Ship,\n _options: GlobalOptions,\n deployment: string,\n cmdOptions: LabelOptions,\n ) => {\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions) || [];\n return client.deployments.set(deployment, { labels });\n },\n {\n operation: 'set',\n resourceType: 'Deployment',\n getResourceId: (deployment: string) => deployment,\n },\n ),\n );\n\ndeploymentsCmd\n .command('remove <deployment>')\n .description('Delete deployment permanently')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, deployment: string) =>\n client.deployments.remove(deployment),\n {\n operation: 'remove',\n resourceType: 'Deployment',\n getResourceId: (deployment: string) => deployment,\n },\n ),\n );\n\n// Domains commands\nconst domainsCmd = program\n .command('domains')\n .description('Manage domains')\n .enablePositionalOptions()\n .action(\n handleUnknownSubcommand('domains', [\n 'list',\n 'get',\n 'set',\n 'validate',\n 'records',\n 'dns',\n 'share',\n 'verify',\n 'remove',\n ]),\n );\n\ndomainsCmd\n .command('list')\n .description('List all domains')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.domains.list()));\n\ndomainsCmd\n .command('get <name>')\n .description('Show domain information')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.get(name),\n { operation: 'get', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('validate <name>')\n .description('Check if domain name is valid and available')\n .action(\n withErrorHandling(\n async (client: Ship, _options: GlobalOptions, name: string) => {\n const result = await client.domains.validate(name);\n if (!result.valid) process.exitCode = 1;\n return result;\n },\n { operation: 'validate', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('verify <name>')\n .description('Trigger DNS verification for external domain')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.verify(name),\n { operation: 'verify', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('records <name>')\n .description('Show required DNS records for domain setup')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.records(name),\n { operation: 'records', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('dns <name>')\n .description('Look up DNS provider for a domain')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.dns(name),\n { operation: 'dns', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('share <name>')\n .description('Get shareable DNS setup link')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.share(name),\n { operation: 'share', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('set <name> [deployment]')\n .description('Create domain, link to deployment, or update labels')\n .passThroughOptions()\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(\n withErrorHandling(\n async (\n client: Ship,\n _options: GlobalOptions,\n name: string,\n deployment: string | undefined,\n cmdOptions: LabelOptions,\n ) => {\n // Read deployment from stdin when piped (e.g., ship ./dist -q | ship domains set mysite.com)\n if (!deployment && !process.stdin.isTTY) {\n deployment = await new Promise<string | undefined>((resolve) => {\n let data = '';\n process.stdin.on('data', (chunk) => (data += chunk));\n process.stdin.on('end', () => resolve(data.trim() || undefined));\n });\n }\n\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions);\n\n const setOptions: { deployment?: string; labels?: string[] } = {};\n if (deployment) setOptions.deployment = deployment;\n if (labels !== undefined) setOptions.labels = labels;\n\n // SDK returns DomainSetResult (Domain + isCreate derived from HTTP 201/200) —\n // the resource interface in @shipstatic/types declares this directly, no cast needed.\n const result = await client.domains.set(name, setOptions);\n\n // Enrich with DNS info for new external domains (pure formatter will display it)\n if (result.isCreate && name.includes('.')) {\n try {\n const [records, share] = await Promise.all([\n client.domains.records(name),\n client.domains.share(name),\n ]);\n return {\n ...result,\n _dnsRecords: records.records,\n _shareHash: share.hash,\n };\n } catch {\n // Graceful degradation - return without DNS info\n }\n }\n return result;\n },\n { operation: 'set', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\ndomainsCmd\n .command('remove <name>')\n .description('Delete domain permanently')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, name: string) => client.domains.remove(name),\n { operation: 'remove', resourceType: 'Domain', getResourceId: (name: string) => name },\n ),\n );\n\n// Tokens commands\nconst tokensCmd = program\n .command('tokens')\n .description('Manage deploy tokens')\n .enablePositionalOptions()\n .action(handleUnknownSubcommand('tokens', ['list', 'create', 'remove']));\n\ntokensCmd\n .command('list')\n .description('List all tokens')\n .action(withErrorHandling((client: Ship, _options: GlobalOptions) => client.tokens.list()));\n\ntokensCmd\n .command('create')\n .description('Create a new deploy token')\n .option('--ttl <seconds>', 'Time to live in seconds (default: never expires)', parseInt)\n .option('--label <label>', 'Label to set (can be repeated)', collect, [])\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, cmdOptions: TokenCreateCommandOptions) => {\n const options: { ttl?: number; labels?: string[] } = {};\n if (cmdOptions?.ttl !== undefined) options.ttl = cmdOptions.ttl;\n const labels = mergeLabelOption(cmdOptions, program.opts() as LabelOptions);\n if (labels !== undefined) options.labels = labels;\n return client.tokens.create(options);\n },\n { operation: 'create', resourceType: 'Token' },\n ),\n );\n\ntokensCmd\n .command('remove <token>')\n .description('Delete token permanently')\n .action(\n withErrorHandling(\n (client: Ship, _options: GlobalOptions, token: string) => client.tokens.remove(token),\n { operation: 'remove', resourceType: 'Token', getResourceId: (token: string) => token },\n ),\n );\n\n// Account commands\nconst accountCmd = program\n .command('account')\n .description('Manage account')\n .action(handleUnknownSubcommand('account', ['get']));\n\naccountCmd\n .command('get')\n .description('Show account information')\n .action(\n withErrorHandling((client: Ship, _options: GlobalOptions) => client.whoami(), {\n operation: 'get',\n resourceType: 'Account',\n }),\n );\n\n// Completion commands\nconst completionCmd = program\n .command('completion')\n .description('Setup shell completion')\n .action(handleUnknownSubcommand('completion', ['install', 'uninstall']));\n\ncompletionCmd\n .command('install')\n .description('Install shell completion script')\n .action(() => {\n const options = processOptions(program);\n const scriptDir = path.resolve(__dirname, 'completions');\n installCompletion(scriptDir, { json: options.json, noColor: options.noColor });\n });\n\ncompletionCmd\n .command('uninstall')\n .description('Uninstall shell completion script')\n .action(() => {\n const options = processOptions(program);\n uninstallCompletion({ json: options.json, noColor: options.noColor });\n });\n\n// Config command\nprogram\n .command('config')\n .description('Save your token')\n .action(async () => {\n const options = processOptions(program);\n try {\n await runConfig({ noColor: options.noColor, json: options.json });\n } catch (err) {\n handleError(err);\n }\n });\n\n// Deploy shortcut as default action\nprogram\n .argument('[path]', 'Path to deploy')\n .option('--label <label>', 'Label to add (can be repeated)', collect, [])\n .option('--password <password>', 'Password-protect this deployment')\n .option('--no-path-detect', 'Disable automatic path optimization and flattening')\n .option('--no-spa-detect', 'Disable automatic SPA detection and configuration')\n .action(\n withErrorHandling(\n async (\n client: Ship,\n options: GlobalOptions,\n deployPath?: string,\n cmdOptions?: DeployCommandOptions,\n ) => {\n if (!deployPath) {\n displayHelp(options.noColor);\n process.exit(0);\n }\n\n // Check if the argument is a valid path by checking filesystem\n // This correctly handles paths like \"dist\", \"build\", \"public\" without slashes\n if (!existsSync(deployPath)) {\n // Path doesn't exist - could be unknown command or typo\n // Check if it looks like a command (no path separators, no extension)\n const looksLikeCommand =\n !deployPath.includes('/') &&\n !deployPath.includes('\\\\') &&\n !deployPath.includes('.') &&\n !deployPath.startsWith('~');\n if (looksLikeCommand) {\n throw ShipError.validation(`unknown command '${deployPath}'`);\n }\n // Otherwise let performDeploy handle the \"path does not exist\" error\n }\n\n return performDeploy(\n client,\n deployPath,\n mergeLabelOption(cmdOptions, program.opts() as LabelOptions),\n mergePasswordOption(cmdOptions, program.opts() as { password?: string }),\n cmdOptions,\n options,\n );\n },\n { operation: 'upload' },\n ),\n );\n\n/**\n * Simple completion handler - no self-invocation, just static completions\n */\nfunction handleCompletion() {\n const args = process.argv;\n const isBash = args.includes('--compbash');\n const isZsh = args.includes('--compzsh');\n const isFish = args.includes('--compfish');\n\n if (!isBash && !isZsh && !isFish) return;\n\n const completions = [\n 'ping',\n 'whoami',\n 'deployments',\n 'domains',\n 'tokens',\n 'account',\n 'config',\n 'completion',\n ];\n console.log(completions.join(isFish ? '\\n' : ' '));\n process.exit(0);\n}\n\n// Handle completion requests (before any other processing)\nif (\n process.env.NODE_ENV !== 'test' &&\n (process.argv.includes('--compbash') ||\n process.argv.includes('--compzsh') ||\n process.argv.includes('--compfish'))\n) {\n handleCompletion();\n}\n\n// Handle main CLI parsing\nif (process.env.NODE_ENV !== 'test') {\n try {\n program.parse(process.argv);\n } catch (err) {\n // Commander.js errors are already handled by exitOverride above\n // This catch is for safety - check if it's a Commander error\n if (err instanceof Error && 'code' in err) {\n const code = (err as Error & { code?: string }).code;\n const exitCode = (err as Error & { exitCode?: number }).exitCode;\n if (code?.startsWith('commander.')) {\n process.exit(exitCode || 1);\n }\n }\n throw err;\n }\n}\n","/**\n * @file Environment variable resolution for the Node.js Ship SDK.\n *\n * The SDK has exactly one ambient credential source: process environment\n * variables. `SHIP_TOKEN` (any platform token — the value's prefix says what\n * it is) and `SHIP_API_URL` are honored as the universal \"process boundary\" —\n * the one-token idiom used across the industry (`GITHUB_TOKEN`, `NPM_TOKEN`,\n * `VERCEL_TOKEN`). Constructor arguments win over env vars.\n *\n * File-based config (`~/.shiprc`, `package.json` `\"ship\"` key) is the CLI's\n * responsibility — see `src/node/cli/shiprc.ts`. The SDK does not read files,\n * which is what lets embedded consumers (MCP, n8n, GitHub Action) construct\n * `new Ship({})` for anonymous deployments without leaking the host developer's\n * personal credentials.\n */\n\nimport { ShipError } from '@shipstatic/types';\nimport { z } from 'zod';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\nimport { getENV } from '../../shared/lib/env.js';\nimport type { ShipClientOptions } from '../../shared/types.js';\n\n// `.strict()` matches the file-config schema. The `raw` object below is\n// constructed from a fixed set of keys, so .strict() doesn't catch user\n// typos here (env vars we don't read are simply never put into `raw` in\n// the first place). What it does catch is a *contributor* error — adding\n// a new env-var read without updating `CREDENTIAL_FIELDS` produces a clear\n// validation failure rather than a silently-stripped value. Nearly free\n// (one method call), and keeps both schemas reading the same.\nconst EnvConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\n/**\n * Map a `ShipClientOptions` field name (camelCase) back to the env var that\n * supplied it (SCREAMING_SNAKE_CASE), so validation errors point users at\n * the actual variable they need to fix. Kept as an explicit table rather\n * than a regex because the set is small, fixed, and unambiguous.\n */\nconst ENV_VAR_BY_FIELD: Record<string, string> = {\n apiUrl: 'SHIP_API_URL',\n token: 'SHIP_TOKEN',\n};\n\n/**\n * Read `SHIP_*` environment variables and validate the result.\n *\n * Empty strings (CI/Docker often sets env vars to `\"\"` instead of unsetting them)\n * are normalized to `undefined` before validation, so they don't trigger zod's\n * \"min length 1\" check or accidentally override a valid constructor argument.\n *\n * Returns an empty object outside Node.js — browser/edge runtimes have no\n * `process.env` we should reach into.\n */\nexport function readEnvConfig(): Partial<ShipClientOptions> {\n if (getENV() !== 'node') return {};\n\n const raw = {\n apiUrl: process.env.SHIP_API_URL || undefined,\n token: process.env.SHIP_TOKEN || undefined,\n };\n\n try {\n return EnvConfigSchema.parse(raw);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n const field = issue.path[0] as string | undefined;\n const envVar = (field && ENV_VAR_BY_FIELD[field]) ?? 'SHIP environment configuration';\n throw ShipError.config(`Invalid ${envVar}: ${issue.message}`);\n }\n throw ShipError.config('Invalid environment configuration');\n }\n}\n","/**\n * @file Single source of truth for ambient-config field validation.\n *\n * Both the SDK env reader (`node/core/config.ts`) and the CLI file loader\n * (`node/cli/shiprc.ts`) import these — if we tighten or relax a rule,\n * both layers update together. The `token` field accepts any platform token;\n * strict prefix-classified format validation happens once, at the `Ship`\n * constructor boundary, for every source uniformly.\n *\n * Lives in its own file (not alongside `mergeDeployOptions`) because it's a\n * pure data constant: tests that mock runtime config behavior shouldn't have\n * to forward this through their mocks.\n */\n\nimport { z } from 'zod';\n\nexport const CREDENTIAL_FIELDS = {\n apiUrl: z.string().url().optional(),\n token: z.string().min(1).optional(),\n};\n","/**\n * Shell completion install/uninstall logic.\n * Handles bash, zsh, and fish shells.\n */\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { error, info, success, warn } from './utils.js';\n\nexport interface CompletionOptions {\n json?: boolean;\n noColor?: boolean;\n}\n\n/**\n * Detect current shell from environment\n */\nfunction detectShell(): 'bash' | 'zsh' | 'fish' | null {\n const shell = process.env.SHELL || '';\n if (shell.includes('bash')) return 'bash';\n if (shell.includes('zsh')) return 'zsh';\n if (shell.includes('fish')) return 'fish';\n return null;\n}\n\n/**\n * Get shell-specific paths\n */\nfunction getShellPaths(shell: 'bash' | 'zsh' | 'fish', homeDir: string) {\n switch (shell) {\n case 'bash':\n return {\n completionFile: path.join(homeDir, '.ship_completion.bash'),\n profileFile: path.join(homeDir, '.bash_profile'),\n scriptName: 'ship.bash',\n };\n case 'zsh':\n return {\n completionFile: path.join(homeDir, '.ship_completion.zsh'),\n profileFile: path.join(homeDir, '.zshrc'),\n scriptName: 'ship.zsh',\n };\n case 'fish':\n return {\n completionFile: path.join(homeDir, '.config/fish/completions/ship.fish'),\n profileFile: null, // fish doesn't need profile sourcing\n scriptName: 'ship.fish',\n };\n }\n}\n\n/**\n * Install shell completion script\n */\nexport function installCompletion(scriptDir: string, options: CompletionOptions = {}): void {\n const { json, noColor } = options;\n const shell = detectShell();\n const homeDir = os.homedir();\n\n if (!shell) {\n error(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`, json, noColor);\n return;\n }\n\n const paths = getShellPaths(shell, homeDir);\n const sourceScript = path.join(scriptDir, paths.scriptName);\n\n try {\n // Fish has a different installation pattern\n if (shell === 'fish') {\n const fishDir = path.dirname(paths.completionFile);\n if (!fs.existsSync(fishDir)) {\n fs.mkdirSync(fishDir, { recursive: true });\n }\n fs.copyFileSync(sourceScript, paths.completionFile);\n success('fish completion installed successfully', json, noColor);\n info('please restart your shell to apply the changes', json, noColor);\n return;\n }\n\n // Bash and zsh: copy script and add sourcing to profile\n fs.copyFileSync(sourceScript, paths.completionFile);\n const sourceLine = `# ship\\nsource '${paths.completionFile}'\\n# ship end`;\n\n if (paths.profileFile) {\n if (fs.existsSync(paths.profileFile)) {\n const content = fs.readFileSync(paths.profileFile, 'utf-8');\n if (!content.includes('# ship') || !content.includes('# ship end')) {\n const prefix = content.length > 0 && !content.endsWith('\\n') ? '\\n' : '';\n fs.appendFileSync(paths.profileFile, prefix + sourceLine);\n }\n } else {\n fs.writeFileSync(paths.profileFile, sourceLine);\n }\n\n success(`completion script installed for ${shell}`, json, noColor);\n warn(`run \"source ${paths.profileFile}\" or restart your shell`, json, noColor);\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n error(`could not install completion script: ${message}`, json, noColor);\n }\n}\n\n/**\n * Uninstall shell completion script\n */\nexport function uninstallCompletion(options: CompletionOptions = {}): void {\n const { json, noColor } = options;\n const shell = detectShell();\n const homeDir = os.homedir();\n\n if (!shell) {\n error(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`, json, noColor);\n return;\n }\n\n const paths = getShellPaths(shell, homeDir);\n\n try {\n // Fish: just remove the file\n if (shell === 'fish') {\n if (fs.existsSync(paths.completionFile)) {\n fs.unlinkSync(paths.completionFile);\n success('fish completion uninstalled successfully', json, noColor);\n } else {\n warn('fish completion was not installed', json, noColor);\n }\n info('please restart your shell to apply the changes', json, noColor);\n return;\n }\n\n // Bash and zsh: remove file and clean profile\n if (fs.existsSync(paths.completionFile)) {\n fs.unlinkSync(paths.completionFile);\n }\n\n if (!paths.profileFile) return;\n\n if (!fs.existsSync(paths.profileFile)) {\n error('profile file not found', json, noColor);\n return;\n }\n\n const content = fs.readFileSync(paths.profileFile, 'utf-8');\n const lines = content.split('\\n');\n\n // Remove ship block (between \"# ship\" and \"# ship end\")\n const filtered: string[] = [];\n let i = 0;\n let removed = false;\n\n while (i < lines.length) {\n if (lines[i].trim() === '# ship') {\n removed = true;\n i++;\n while (i < lines.length && lines[i].trim() !== '# ship end') i++;\n if (i < lines.length) i++; // skip \"# ship end\"\n } else {\n filtered.push(lines[i]);\n i++;\n }\n }\n\n if (removed) {\n const endsWithNewline = content.endsWith('\\n');\n const newContent =\n filtered.length === 0 ? '' : filtered.join('\\n') + (endsWithNewline ? '\\n' : '');\n fs.writeFileSync(paths.profileFile, newContent);\n success(`completion script uninstalled for ${shell}`, json, noColor);\n warn(`run \"source ${paths.profileFile}\" or restart your shell`, json, noColor);\n } else {\n error('completion was not found in profile', json, noColor);\n }\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n error(`could not uninstall completion script: ${message}`, json, noColor);\n }\n}\n","/**\n * Simple CLI utilities following \"impossible simplicity\" mantra\n */\nimport columnify from 'columnify';\nimport { blue, dim, green, hidden, inverse, red, yellow } from 'yoctocolors';\n\nconst INTERNAL_FIELDS = ['isCreate', 'claim'];\n\nconst applyColor = (colorFn: (text: string) => string, text: string, noColor?: boolean): string => {\n return noColor ? text : colorFn(text);\n};\n\n// Wire messages are displayed verbatim — identifiers, paths, and acronyms\n// must survive formatting. The CLI's lowercase opening applies to the leading\n// sentence word only, and only when it's an ordinary capitalized word (never\n// \"DNS\", a quoted key, or a path).\nconst decapitalize = (msg: string): string =>\n /^[A-Z][a-z]/.test(msg) ? msg.charAt(0).toLowerCase() + msg.slice(1) : msg;\n\n/**\n * Message helper functions for consistent CLI output\n */\nexport const success = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(`${JSON.stringify({ success: msg }, null, 2)}\\n`);\n } else {\n console.log(`${applyColor(green, decapitalize(msg).replace(/\\.$/, ''), noColor)}\\n`);\n }\n};\n\nexport const error = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.error(`${JSON.stringify({ error: msg }, null, 2)}\\n`);\n } else {\n const errorPrefix = applyColor(\n (text) => inverse(red(text)),\n `${applyColor(hidden, '[', noColor)}error${applyColor(hidden, ']', noColor)}`,\n noColor,\n );\n const errorMsg = applyColor(red, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.error(`${errorPrefix} ${errorMsg}\\n`);\n }\n};\n\nexport const warn = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(`${JSON.stringify({ warning: msg }, null, 2)}\\n`);\n } else {\n const warnPrefix = applyColor(\n (text) => inverse(yellow(text)),\n `${applyColor(hidden, '[', noColor)}warning${applyColor(hidden, ']', noColor)}`,\n noColor,\n );\n const warnMsg = applyColor(yellow, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.log(`${warnPrefix} ${warnMsg}\\n`);\n }\n};\n\nexport const info = (msg: string, json?: boolean, noColor?: boolean) => {\n if (json) {\n console.log(`${JSON.stringify({ info: msg }, null, 2)}\\n`);\n } else {\n const infoPrefix = applyColor(\n (text) => inverse(blue(text)),\n `${applyColor(hidden, '[', noColor)}info${applyColor(hidden, ']', noColor)}`,\n noColor,\n );\n const infoMsg = applyColor(blue, decapitalize(msg).replace(/\\.$/, ''), noColor);\n console.log(`${infoPrefix} ${infoMsg}\\n`);\n }\n};\n\n/**\n * Format unix timestamp to ISO 8601 string without milliseconds, or return '-' if not provided\n */\nexport const formatTimestamp = (\n timestamp?: number,\n context: 'table' | 'details' = 'details',\n noColor?: boolean,\n): string => {\n if (timestamp === undefined || timestamp === null || timestamp === 0) {\n return '-';\n }\n\n const isoString = new Date(timestamp * 1000).toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n\n // Hide the T and Z characters only in table/list views for cleaner appearance\n if (context === 'table') {\n return isoString\n .replace(/T/, applyColor(hidden, 'T', noColor))\n .replace(/Z$/, applyColor(hidden, 'Z', noColor));\n }\n\n return isoString;\n};\n\n/**\n * Format value for display.\n * Handles timestamps, file sizes, and boolean configs with special formatting.\n */\nconst formatValue = (\n key: string,\n value: unknown,\n context: 'table' | 'details' = 'details',\n noColor?: boolean,\n): string => {\n if (value === null || (Array.isArray(value) && value.length === 0)) return '-';\n if (\n typeof value === 'number' &&\n (key === 'created' ||\n key === 'activated' ||\n key === 'expires' ||\n key === 'linked' ||\n key === 'grace')\n ) {\n return formatTimestamp(value, context, noColor);\n }\n if (key === 'size' && typeof value === 'number') {\n const mb = value / (1024 * 1024);\n return mb >= 1 ? `${mb.toFixed(1)}Mb` : `${(value / 1024).toFixed(1)}Kb`;\n }\n // Boolean signal columns (config, password) render as yes/no in details.\n if (key === 'config' || key === 'password') {\n if (typeof value === 'boolean') return value ? 'yes' : 'no';\n if (typeof value === 'number') return value === 1 ? 'yes' : 'no';\n }\n return String(value);\n};\n\n/**\n * Format data as table with specified columns for easy parsing.\n * @param data - Array of objects to display as table rows\n * @param columns - Optional column order (defaults to first item's keys)\n * @param noColor - Disable colors\n * @param headerMap - Optional mapping of property names to display headers\n */\nexport const formatTable = (\n data: object[],\n columns?: string[],\n noColor?: boolean,\n headerMap?: Record<string, string>,\n): string => {\n if (!data || data.length === 0) return '';\n\n // Get column order from first item (preserves API order) or use provided columns\n const firstItem = data[0] as Record<string, unknown>;\n const columnOrder =\n columns ||\n Object.keys(firstItem).filter(\n (key) => firstItem[key] !== undefined && !INTERNAL_FIELDS.includes(key),\n );\n\n // Transform data preserving column order\n const transformedData = data.map((item) => {\n const record = item as Record<string, unknown>;\n const transformed: Record<string, string> = {};\n columnOrder.forEach((col) => {\n if (col in record && record[col] !== undefined) {\n transformed[col] = formatValue(col, record[col], 'table', noColor);\n }\n });\n return transformed;\n });\n\n const output = columnify(transformedData, {\n columnSplitter: ' ',\n columns: columnOrder,\n config: columnOrder.reduce<Record<string, { headingTransform: (h: string) => string }>>(\n (config, col) => {\n config[col] = {\n headingTransform: (heading: string) =>\n applyColor(dim, headerMap?.[heading] || heading, noColor),\n };\n return config;\n },\n {},\n ),\n });\n\n // Clean output: remove null bytes and ensure clean spacing\n return `${output\n .split('\\n')\n .map(\n (line: string) =>\n line\n .replace(/\\0/g, '') // Remove any null bytes\n .replace(/\\s+$/, ''), // Remove trailing spaces\n )\n .join('\\n')}\\n`;\n};\n\n/**\n * Format object properties as key-value pairs with space separation for readability.\n * @param obj - Object to display as key-value pairs\n * @param noColor - Disable colors\n */\nexport const formatDetails = (obj: object, noColor?: boolean): string => {\n const entries = (Object.entries(obj) as [string, unknown][]).filter(([key, value]) => {\n if (INTERNAL_FIELDS.includes(key)) return false;\n return value !== undefined;\n });\n\n if (entries.length === 0) return '';\n\n // Transform to columnify format while preserving order\n const data = entries.map(([key, value]) => ({\n property: `${key}:`,\n value: formatValue(key, value, 'details', noColor),\n }));\n\n const output = columnify(data, {\n columnSplitter: ' ',\n showHeaders: false,\n config: {\n property: {\n dataTransform: (value: string) => applyColor(dim, value, noColor),\n },\n },\n });\n\n // Clean output: remove null bytes and ensure clean spacing\n return `${output\n .split('\\n')\n .map((line: string) => line.replace(/\\0/g, '')) // Remove any null bytes\n .join('\\n')}\\n`;\n};\n","/**\n * @file Interactive config file creation for `ship config`.\n * Asks for a token, merges into existing ~/.shiprc, preserves all other fields.\n * Uses Node.js built-in readline/promises — zero additional dependencies.\n */\n\nimport { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\nimport { DEFAULT_API, validateToken } from '@shipstatic/types';\nimport { dim, green } from 'yoctocolors';\n\n/** Path to the global config file */\nconst CONFIG_PATH = join(homedir(), '.shiprc');\n\n/**\n * Mask a token for display: ship-a1b2...c3d4. A token too short to keep a\n * useful prefix + suffix is masked entirely — never printed verbatim.\n */\nfunction maskToken(token: string): string {\n if (token.length < 13) return '...';\n return `${token.slice(0, 9)}...${token.slice(-4)}`;\n}\n\n/**\n * Read existing config file, preserving all fields.\n * Returns empty object if file doesn't exist or is invalid.\n */\nfunction readExistingConfig(): Record<string, unknown> {\n try {\n if (!existsSync(CONFIG_PATH)) return {};\n return JSON.parse(readFileSync(CONFIG_PATH, 'utf-8'));\n } catch {\n return {};\n }\n}\n\n/**\n * Run the interactive config flow.\n * Asks for a token, merges into existing config, writes ~/.shiprc.\n */\nexport async function runConfig(\n options: { noColor?: boolean; json?: boolean } = {},\n): Promise<void> {\n const { noColor, json } = options;\n const applyDim = (text: string) => (noColor ? text : dim(text));\n const applyGreen = (text: string) => (noColor ? text : green(text));\n\n // JSON mode: show current config status\n if (json) {\n const existing = readExistingConfig();\n const token = typeof existing.token === 'string' ? existing.token : undefined;\n const apiUrl = typeof existing.apiUrl === 'string' ? existing.apiUrl : undefined;\n console.log(\n `${JSON.stringify(\n {\n path: CONFIG_PATH,\n exists: existsSync(CONFIG_PATH),\n ...(token ? { token: maskToken(token) } : {}),\n ...(apiUrl && apiUrl !== DEFAULT_API ? { apiUrl } : {}),\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n const existing = readExistingConfig();\n const existingToken = typeof existing.token === 'string' ? existing.token : undefined;\n\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n console.log('');\n console.log(` ${applyDim('Create a free API key at')} https://my.shipstatic.com/api-key`);\n console.log('');\n\n const prompt = existingToken ? ` Token (${applyDim(maskToken(existingToken))}): ` : ' Token: ';\n\n let input: string;\n try {\n input = (await rl.question(prompt)).trim();\n } finally {\n rl.close();\n }\n\n if (input) {\n validateToken(input);\n existing.token = input;\n }\n\n // The file holds a credential: owner-only, like ~/.netrc. `mode` only\n // applies on creation, so chmod repairs files written before this rule.\n writeFileSync(CONFIG_PATH, `${JSON.stringify(existing, null, 2)}\\n`, { mode: 0o600 });\n chmodSync(CONFIG_PATH, 0o600);\n console.log(`\\n ${applyGreen('saved to')} ${applyDim(CONFIG_PATH)}\\n`);\n}\n","/**\n * @file Ship SDK for Node.js environments.\n *\n * The Node-side `Ship` adds two things on top of the base class:\n * 1. Environment detection — refuses to construct outside Node.\n * 2. `SHIP_TOKEN` / `SHIP_API_URL` env-var resolution as the universal\n * \"process boundary\" credential source — the industry's one-token\n * convention. Constructor arguments win over env vars.\n *\n * The SDK does NOT read `~/.shiprc` or `package.json` `\"ship\"` keys — that's\n * the CLI's job (see `cli/shiprc.ts`). Keeping file resolution out of the SDK\n * is what lets embedded consumers (MCP, n8n, GitHub Action) safely write\n * `new Ship({})` for anonymous public deployments without inheriting the host\n * developer's personal credentials.\n */\n\nimport { ShipError } from '@shipstatic/types';\nimport { Ship as BaseShip } from '../shared/base-ship.js';\nimport { getENV } from '../shared/lib/env.js';\nimport type {\n DeployBodyCreator,\n DeployInput,\n Deployment,\n DeploymentOptions,\n ShipClientOptions,\n StaticFile,\n} from '../shared/types.js';\nimport { readEnvConfig } from './core/config.js';\nimport { createDeployBody } from './core/deploy-body.js';\n\n// Export all shared functionality\nexport * from '../shared/index.js';\n\n/**\n * Ship SDK Client for Node.js environments.\n *\n * @example\n * ```typescript\n * // Authenticated — explicit token (API key, deploy token, or OAuth bearer)\n * const ship = new Ship({ token: 'ship-xxxx' });\n *\n * // Authenticated — picks up SHIP_TOKEN from env\n * const ship = new Ship({});\n *\n * // Anonymous public deploy — works when neither constructor nor env provides a token\n * const ship = new Ship({});\n * await ship.deploy('./dist');\n * ```\n */\nexport class Ship extends BaseShip {\n constructor(options: ShipClientOptions = {}) {\n if (getENV() !== 'node') {\n throw ShipError.business('Node.js Ship class can only be used in Node.js environment.');\n }\n\n // Layer env vars under constructor options. The merged result is what the\n // base class sees, so the credential and the HTTP client are fully formed\n // by the time the constructor returns — no async config phase needed.\n //\n // Truthiness (not `??`) is deliberate: an empty-string token is absence\n // (shell expansion of unset CI variables), so `token: ''` falls through\n // to `SHIP_TOKEN` instead of locking in a phantom credential. A client\n // constructed with `session: true` has chosen its identity — the ambient\n // token does not ride along.\n const env = readEnvConfig();\n super({\n ...options,\n apiUrl: options.apiUrl || env.apiUrl,\n token: options.token || (options.session ? undefined : env.token),\n });\n }\n\n /**\n * Deploy file or directory paths to ShipStatic. Convenience shortcut for\n * `ship.deployments.upload()`.\n *\n * Wrong-platform inputs (e.g. `File[]`) fail at compile time. For\n * platform-neutral code, use `ship.deployments.upload()`, which accepts\n * the wider `DeployInput` and validates at runtime — that asymmetry is\n * intentional: the convenience shortcut narrows; the resource-layer\n * contract stays platform-neutral.\n */\n async deploy(input: string | string[], options?: DeploymentOptions): Promise<Deployment> {\n return super.deploy(input, options);\n }\n\n protected async processInput(\n input: DeployInput,\n options: DeploymentOptions,\n ): Promise<StaticFile[]> {\n // Normalize string to string[] and validate.\n const paths = typeof input === 'string' ? [input] : input;\n\n if (!Array.isArray(paths) || !paths.every((p) => typeof p === 'string')) {\n throw ShipError.business(\n 'Invalid input type for Node.js environment. Expected string or string[].',\n );\n }\n\n if (paths.length === 0) {\n throw ShipError.business('No files to deploy.');\n }\n\n const { processFilesForNode } = await import('./core/node-files.js');\n return processFilesForNode(paths, options, this.platformLimits ?? undefined);\n }\n\n protected getDeployBodyCreator(): DeployBodyCreator {\n return createDeployBody;\n }\n}\n\n// Default export (for `import Ship from '@shipstatic/ship'`)\nexport default Ship;\n\n// Node-only utilities (path-walking + MD5 over the local filesystem)\nexport { processFilesForNode } from './core/node-files.js';\n","/**\n * @file Base Ship SDK class — shared functionality across environments.\n *\n * The constructor is fully synchronous: an `ApiHttp` instance is built immediately\n * with whatever credentials the caller supplied (and, in Node, env vars merged in\n * by the subclass before `super()`). The only deferred work is the one-shot\n * `GET /limits` fetch that hydrates platform limits — that's lazy and runs on\n * first API call via `ensureInitialized()`.\n *\n * Subclasses only override what genuinely differs per environment:\n * - `processInput()` — Node reads paths from disk; Browser handles `File[]`\n * - `getDeployBodyCreator()` — Node streams Buffers; Browser builds Blobs\n *\n * Everything else (the credential slot, resources, events, lazy platform-limits)\n * lives here.\n */\n\nimport type {\n AccountResource,\n Deployment,\n DeploymentResource,\n DomainResource,\n PlatformLimits,\n StaticFile,\n TokenResource,\n} from '@shipstatic/types';\nimport { ShipError, validateCaller, validateToken } from '@shipstatic/types';\n\nimport { ApiHttp } from './api/http.js';\nimport {\n createAccountResource,\n createDeploymentResource,\n createDomainResource,\n createTokenResource,\n type DeployInput,\n} from './resources.js';\nimport type {\n DeployBodyCreator,\n DeploymentOptions,\n ShipClientOptions,\n ShipEvents,\n TokenProvider,\n} from './types.js';\n\n/**\n * Abstract base class for Ship SDK implementations.\n */\nexport abstract class Ship {\n // Resource handles, created once at construction. Each is a thin facade\n // bound to `this.http` plus the lazy-init callback.\n public readonly deployments: DeploymentResource;\n public readonly domains: DomainResource;\n public readonly account: AccountResource;\n public readonly tokens: TokenResource;\n\n // The HTTP client and merged options are private — subclasses interact\n // with the base class through the abstract methods below, never by\n // reaching into these fields. Tests bypass via `(ship as any).http = ...`.\n private readonly http: ApiHttp;\n private readonly clientOptions: ShipClientOptions;\n\n // Lazy-init plumbing for the one-shot `GET /config` fetch.\n // `platformLimits` is INSTANCE state (not a module-level singleton): two\n // Ships against different `apiUrl`s — staging + prod, multi-tenant\n // orchestrators, n8n with multiple credentials — must not clobber each\n // other's limits. Each instance owns its hydrated copy.\n // `protected` so subclasses' `processInput` can pass it down to the\n // platform-specific file-validation utilities.\n private initPromise: Promise<void> | null = null;\n protected platformLimits: PlatformLimits | null = null;\n\n // The credential slot — one platform token (any population) or a provider\n // that supplies one per request. Read dynamically on every request through\n // `getAuthHeaders`, so `setToken` takes effect without rebuilding the client.\n private credential: string | TokenProvider | null = null;\n\n constructor(options: ShipClientOptions = {}) {\n // SDK-boundary normalization: an empty-string token is absence of\n // credential intent, never a credential. Empty strings reach here from\n // shell-expansion of unset CI variables, empty form fields in browser\n // apps, and any other path that produces `''` instead of `undefined`.\n // Normalizing once at the SDK boundary covers every entry point: CLI,\n // Browser SDK, Node SDK, embedded consumers, and direct base-class use.\n options = {\n ...options,\n apiUrl: options.apiUrl || undefined,\n token: options.token || undefined,\n caller: options.caller || undefined,\n };\n this.clientOptions = options;\n\n // Caller identity is validated at the boundary like the token: a value\n // the API would silently drop (the header is unauthenticated) is a\n // configuration error here, never a quiet fallback to IP bucketing.\n if (options.caller !== undefined) {\n validateCaller(options.caller);\n }\n\n // One client, one identity. A token and a cookie session are different\n // principals — holding both is a configuration error, not a precedence\n // question.\n if (options.token && options.session) {\n throw ShipError.config('Provide either `token` or `session`, not both.');\n }\n\n // Static tokens are validated at the boundary (prefix-classified, same\n // rules the server applies); providers are invoked per request instead.\n if (typeof options.token === 'string') {\n validateToken(options.token);\n this.credential = options.token;\n } else if (options.token) {\n this.credential = options.token;\n }\n\n // Build the HTTP client once. The `getAuthHeaders` callback reads\n // `this.credential` dynamically on every request.\n this.http = new ApiHttp({\n ...options,\n getAuthHeaders: () => this.getAuthHeaders(),\n createDeployBody: this.getDeployBodyCreator(),\n });\n\n const ctx = {\n getApi: () => this.http,\n ensureInit: () => this.ensureInitialized(),\n };\n\n this.deployments = createDeploymentResource({\n ...ctx,\n processInput: (input, opts) => this.processInput(input, opts),\n clientDefaults: this.clientOptions,\n });\n this.domains = createDomainResource(ctx);\n this.account = createAccountResource(ctx);\n this.tokens = createTokenResource(ctx);\n }\n\n // Environment-specific behavior.\n protected abstract processInput(\n input: DeployInput,\n options: DeploymentOptions,\n ): Promise<StaticFile[]>;\n protected abstract getDeployBodyCreator(): DeployBodyCreator;\n\n /**\n * Lazy initialization — fetches platform limits (file size / count caps) once,\n * on the first API call. Subsequent calls reuse the resolved promise.\n */\n protected async ensureInitialized(): Promise<void> {\n if (!this.initPromise) {\n this.initPromise = this.fetchPlatformLimits();\n }\n return this.initPromise;\n }\n\n private async fetchPlatformLimits(): Promise<void> {\n try {\n this.platformLimits = await this.http.getLimits();\n } catch (error) {\n // Reset so the next API call can retry initialization.\n this.initPromise = null;\n throw error;\n }\n }\n\n /**\n * Ping the API server to check connectivity.\n */\n async ping(): Promise<boolean> {\n await this.ensureInitialized();\n return this.http.ping();\n }\n\n /**\n * Deploy project (convenience shortcut to `ship.deployments.upload()`).\n */\n async deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment> {\n return this.deployments.upload(input, options);\n }\n\n /**\n * Get current account information (convenience shortcut to `ship.account.get()`).\n */\n async whoami() {\n return this.account.get();\n }\n\n /**\n * Get platform limits (max file size, file count, total size).\n * Reuses the response fetched during initialization. Per-instance state —\n * does not leak between concurrent Ships against different API URLs.\n */\n async getLimits(): Promise<PlatformLimits> {\n if (this.platformLimits) return this.platformLimits;\n await this.ensureInitialized();\n // biome-ignore lint/style/noNonNullAssertion: ensureInitialized() hydrates platformLimits or throws\n return this.platformLimits!;\n }\n\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.on(event, handler);\n }\n\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n this.http.off(event, handler);\n }\n\n /**\n * Set global headers included in every request.\n * Useful for injecting custom headers (e.g. for admin impersonation).\n */\n setHeaders(headers: Record<string, string>): void {\n this.http.setGlobalHeaders(headers);\n }\n\n /**\n * Clear all custom global headers.\n */\n clearHeaders(): void {\n this.http.setGlobalHeaders({});\n }\n\n /**\n * Sets the client token — any platform token (API key, deploy token, OAuth\n * access token) or a {@link TokenProvider} invoked per request. Replaces\n * whatever credential the client held before.\n * @param token A platform token, sent verbatim, or a provider function\n */\n public setToken(token: string | TokenProvider): void {\n // One client, one identity — the constructor's token/session exclusion\n // holds for the client's whole life, not just its first moment.\n if (this.clientOptions.session) {\n throw ShipError.config('Provide either `token` or `session`, not both.');\n }\n if (typeof token === 'string') {\n if (!token) {\n throw ShipError.business('Invalid token provided. Token must be a non-empty string.');\n }\n validateToken(token);\n this.credential = token;\n return;\n }\n if (typeof token !== 'function') {\n throw ShipError.business(\n 'Invalid token provided. Token must be a non-empty string or a provider function.',\n );\n }\n this.credential = token;\n }\n\n /**\n * Resolve the credential slot into request headers. Async because a\n * provider may mint or refresh its token per request.\n *\n * Anonymity requires proven absence of credentials: a configured provider\n * that yields nothing is an error — the request fails typed rather than\n * silently proceeding as an anonymous public deploy. Empty-string\n * normalization at the constructor is the same invariant's boundary\n * condition: `''` is absence of intent, so it never reaches this point.\n */\n private async getAuthHeaders(): Promise<Record<string, string>> {\n if (this.credential === null) return {};\n const value = typeof this.credential === 'function' ? await this.credential() : this.credential;\n if (!value) {\n throw ShipError.authentication('Token provider returned no token.');\n }\n if (typeof value !== 'string') {\n throw ShipError.authentication('Token provider returned a non-string value.');\n }\n return { Authorization: `Bearer ${value}` };\n }\n}\n","/**\n * @file HTTP client for Ship API.\n */\nimport type {\n AccountGetResponse,\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n Domain,\n DomainDnsResponse,\n DomainListResponse,\n DomainRecordsResponse,\n DomainValidateResponse,\n PingResponse,\n PlatformLimits,\n SPACheckRequest,\n SPACheckResponse,\n StaticFile,\n TokenCreateResponse,\n TokenListResponse,\n} from '@shipstatic/types';\nimport { DEFAULT_API, ShipError } from '@shipstatic/types';\nimport { SimpleEvents } from '../events.js';\nimport { validateLabels, validatePassword } from '../lib/validation.js';\nimport type {\n ApiDeployOptions,\n DeployBodyCreator,\n DomainSetResult,\n Fetch,\n ShipClientOptions,\n} from '../types.js';\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst ENDPOINTS = {\n DEPLOYMENTS: '/deployments',\n DOMAINS: '/domains',\n TOKENS: '/tokens',\n ACCOUNT: '/account',\n LIMITS: '/limits',\n PING: '/ping',\n SPA_CHECK: '/spa-check',\n} as const;\n\nconst DEFAULT_REQUEST_TIMEOUT = 30000;\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ApiHttpOptions extends ShipClientOptions {\n /** Resolves the credential slot per request — async so token providers can mint/refresh. */\n getAuthHeaders: () => Record<string, string> | Promise<Record<string, string>>;\n createDeployBody: DeployBodyCreator;\n}\n\ninterface RequestResult<T> {\n data: T;\n status: number;\n}\n\n// =============================================================================\n// HTTP CLIENT\n// =============================================================================\n\nexport class ApiHttp extends SimpleEvents {\n private readonly apiUrl: string;\n private readonly getAuthHeadersCallback: () =>\n | Record<string, string>\n | Promise<Record<string, string>>;\n private readonly session: boolean;\n private readonly caller: string | undefined;\n private readonly timeout: number;\n private readonly fetch: Fetch;\n private readonly createDeployBody: DeployBodyCreator;\n private readonly deployEndpoint: string;\n private globalHeaders: Record<string, string> = {};\n\n constructor(options: ApiHttpOptions) {\n super();\n this.apiUrl = options.apiUrl || DEFAULT_API;\n this.getAuthHeadersCallback = options.getAuthHeaders;\n this.session = options.session ?? false;\n this.caller = options.caller;\n this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;\n // Bind to globalThis when falling back to the platform `fetch` — browsers\n // require `this === window` on `window.fetch` and throw \"Illegal invocation\"\n // when it's invoked as a property of any other object.\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.createDeployBody = options.createDeployBody;\n this.deployEndpoint = options.deployEndpoint || ENDPOINTS.DEPLOYMENTS;\n }\n\n /**\n * Set global headers included in every request.\n * Priority: globalHeaders (lowest) < instance auth < per-request headers (highest)\n */\n setGlobalHeaders(headers: Record<string, string>): void {\n this.globalHeaders = headers;\n }\n\n // ===========================================================================\n // CORE REQUEST INFRASTRUCTURE\n // ===========================================================================\n\n /**\n * Execute HTTP request with timeout, events, and error handling\n */\n private async executeRequest<T>(\n url: string,\n options: RequestInit,\n operationName: string,\n ): Promise<RequestResult<T>> {\n let cleanup = () => {};\n\n try {\n // Credential resolution runs inside the error boundary: a token\n // provider that throws or yields nothing fails the request through\n // the same typed path (and `error` event) as any transport failure.\n const headers = await this.mergeHeaders(options.headers as Record<string, string>);\n const timeout = this.createTimeoutSignal(options.signal);\n cleanup = timeout.cleanup;\n\n const fetchOptions: RequestInit = {\n ...options,\n headers,\n credentials: this.session && !headers.Authorization ? 'include' : undefined,\n signal: timeout.signal,\n };\n\n this.emit('request', url, fetchOptions);\n\n const response = await this.fetch(url, fetchOptions);\n cleanup();\n\n if (!response.ok) {\n throw await ShipError.fromHttpResponse(response, operationName);\n }\n\n this.emit('response', this.safeClone(response), url);\n const data = await this.parseResponse<T>(this.safeClone(response));\n return { data, status: response.status };\n } catch (error) {\n cleanup();\n // Normalize anything thrown above (credential resolution, fetch\n // failure, abort, response error) into a ShipError.\n // fromFetchError passes existing ShipErrors through unchanged.\n const shipError = ShipError.fromFetchError(error, operationName);\n this.emit('error', shipError, url);\n throw shipError;\n }\n }\n\n /**\n * Simple request - returns data only\n */\n private async request<T>(url: string, options: RequestInit, operationName: string): Promise<T> {\n const { data } = await this.executeRequest<T>(url, options, operationName);\n return data;\n }\n\n /**\n * Request with status - returns data and HTTP status code\n */\n private async requestWithStatus<T>(\n url: string,\n options: RequestInit,\n operationName: string,\n ): Promise<RequestResult<T>> {\n return this.executeRequest<T>(url, options, operationName);\n }\n\n // ===========================================================================\n // REQUEST HELPERS\n // ===========================================================================\n\n private async mergeHeaders(\n customHeaders: Record<string, string> = {},\n ): Promise<Record<string, string>> {\n // `caller` is instance identity metadata, like the credential: the\n // rate limiter buckets by X-Caller on every write, so it rides every\n // request rather than any single operation.\n return {\n ...this.globalHeaders,\n ...(this.caller ? { 'X-Caller': this.caller } : {}),\n ...(await this.getAuthHeadersCallback()),\n ...customHeaders,\n };\n }\n\n private createTimeoutSignal(existingSignal?: AbortSignal | null): {\n signal: AbortSignal;\n cleanup: () => void;\n } {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n if (existingSignal) {\n const abort = () => controller.abort();\n existingSignal.addEventListener('abort', abort);\n if (existingSignal.aborted) controller.abort();\n }\n\n return {\n signal: controller.signal,\n cleanup: () => clearTimeout(timeoutId),\n };\n }\n\n private safeClone(response: Response): Response {\n try {\n return response.clone();\n } catch {\n return response;\n }\n }\n\n private async parseResponse<T>(response: Response): Promise<T> {\n if (response.headers.get('Content-Length') === '0' || response.status === 204) {\n return undefined as T;\n }\n return response.json() as Promise<T>;\n }\n\n // ===========================================================================\n // PUBLIC API - DEPLOYMENTS\n // ===========================================================================\n\n async deploy(\n files: StaticFile[],\n options: ApiDeployOptions = {},\n ): Promise<DeploymentCreateResponse> {\n if (!files.length) {\n throw ShipError.business('No files to deploy');\n }\n for (const file of files) {\n if (!file.md5) {\n throw ShipError.file(`MD5 checksum missing for file: ${file.path}`, {\n filePath: file.path,\n });\n }\n }\n\n // Fast-fail on definitely-invalid input before constructing a multipart body.\n validatePassword(options.password);\n const labels = validateLabels(options.labels);\n\n const flags =\n options.build || options.prerender || options.spa\n ? { build: options.build, prerender: options.prerender, spa: options.spa }\n : undefined;\n const { body, headers: bodyHeaders } = await this.createDeployBody(files, {\n labels,\n via: options.via,\n password: options.password,\n flags,\n captcha: options.captcha,\n });\n\n return this.request<DeploymentCreateResponse>(\n `${this.apiUrl}${this.deployEndpoint}`,\n { method: 'POST', body, headers: bodyHeaders, signal: options.signal || null },\n 'Deploy',\n );\n }\n\n async listDeployments(): Promise<DeploymentListResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}`,\n { method: 'GET' },\n 'List deployments',\n );\n }\n\n async getDeployment(id: string): Promise<Deployment> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'GET' },\n 'Get deployment',\n );\n }\n\n async updateDeploymentLabels(id: string, labels: string[]): Promise<Deployment> {\n const normalized = validateLabels(labels);\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n {\n method: 'PATCH',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ labels: normalized }),\n },\n 'Update deployment labels',\n );\n }\n\n async removeDeployment(id: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.DEPLOYMENTS}/${encodeURIComponent(id)}`,\n { method: 'DELETE' },\n 'Remove deployment',\n );\n }\n\n // ===========================================================================\n // PUBLIC API - DOMAINS\n // ===========================================================================\n // All domain methods accept FQDN (Fully Qualified Domain Name) as the `name` parameter.\n // The SDK does not validate or normalize - the API handles all domain semantics.\n\n async setDomain(name: string, deployment?: string, labels?: string[]): Promise<DomainSetResult> {\n const normalized = validateLabels(labels);\n const body: { deployment?: string; labels?: string[] } = {};\n if (deployment) body.deployment = deployment;\n if (normalized !== undefined) body.labels = normalized;\n\n const { data, status } = await this.requestWithStatus<Domain>(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n },\n 'Set domain',\n );\n\n return { ...data, isCreate: status === 201 };\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.DOMAINS}`, { method: 'GET' }, 'List domains');\n }\n\n async getDomain(name: string): Promise<Domain> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n { method: 'GET' },\n 'Get domain',\n );\n }\n\n async removeDomain(name: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}`,\n { method: 'DELETE' },\n 'Remove domain',\n );\n }\n\n async verifyDomain(name: string): Promise<{ message: string }> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/verify`,\n { method: 'POST' },\n 'Verify domain',\n );\n }\n\n async getDomainDns(name: string): Promise<DomainDnsResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/dns`,\n { method: 'GET' },\n 'Get domain DNS',\n );\n }\n\n async getDomainRecords(name: string): Promise<DomainRecordsResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/records`,\n { method: 'GET' },\n 'Get domain records',\n );\n }\n\n async getDomainShare(name: string): Promise<{ domain: string; hash: string }> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/${encodeURIComponent(name)}/share`,\n { method: 'GET' },\n 'Get domain share',\n );\n }\n\n async validateDomain(name: string): Promise<DomainValidateResponse> {\n return this.request(\n `${this.apiUrl}${ENDPOINTS.DOMAINS}/validate`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ domain: name }),\n },\n 'Validate domain',\n );\n }\n\n // ===========================================================================\n // PUBLIC API - TOKENS\n // ===========================================================================\n\n async createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse> {\n const normalized = validateLabels(labels);\n const body: { ttl?: number; labels?: string[] } = {};\n if (ttl !== undefined) body.ttl = ttl;\n if (normalized !== undefined) body.labels = normalized;\n\n return this.request(\n `${this.apiUrl}${ENDPOINTS.TOKENS}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n },\n 'Create token',\n );\n }\n\n async listTokens(): Promise<TokenListResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.TOKENS}`, { method: 'GET' }, 'List tokens');\n }\n\n async removeToken(token: string): Promise<void> {\n await this.request<void>(\n `${this.apiUrl}${ENDPOINTS.TOKENS}/${encodeURIComponent(token)}`,\n { method: 'DELETE' },\n 'Remove token',\n );\n }\n\n // ===========================================================================\n // PUBLIC API - ACCOUNT & CONFIG\n // ===========================================================================\n\n async getAccount(): Promise<AccountGetResponse> {\n return this.request(`${this.apiUrl}${ENDPOINTS.ACCOUNT}`, { method: 'GET' }, 'Get account');\n }\n\n async getLimits(): Promise<PlatformLimits> {\n return this.request(`${this.apiUrl}${ENDPOINTS.LIMITS}`, { method: 'GET' }, 'Get limits');\n }\n\n async ping(): Promise<boolean> {\n const data = await this.request<PingResponse>(\n `${this.apiUrl}${ENDPOINTS.PING}`,\n { method: 'GET' },\n 'Ping',\n );\n return data?.success || false;\n }\n\n // ===========================================================================\n // PUBLIC API - SPA CHECK\n // ===========================================================================\n\n async checkSPA(files: StaticFile[], _options: ApiDeployOptions = {}): Promise<boolean> {\n const indexFile = files.find((f) => f.path === 'index.html' || f.path === '/index.html');\n if (!indexFile || indexFile.size > 100 * 1024) {\n return false;\n }\n\n let indexContent: string;\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(indexFile.content)) {\n indexContent = indexFile.content.toString('utf-8');\n } else if (typeof Blob !== 'undefined' && indexFile.content instanceof Blob) {\n indexContent = await indexFile.content.text();\n } else if (typeof File !== 'undefined' && indexFile.content instanceof File) {\n indexContent = await indexFile.content.text();\n } else {\n return false;\n }\n\n const body: SPACheckRequest = { files: files.map((f) => f.path), index: indexContent };\n const response = await this.request<SPACheckResponse>(\n `${this.apiUrl}${ENDPOINTS.SPA_CHECK}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n },\n 'SPA check',\n );\n\n return response.isSPA;\n }\n}\n","/**\n * Event system for Ship SDK\n * Lightweight, reliable event handling with proper error boundaries\n */\n\nimport type { ShipEvents } from './types.js';\n\n/**\n * Lightweight typed event emitter.\n *\n * Public API: `on()` / `off()`. `emit()` is internal — only the SDK\n * publishes events. Throwing handlers are evicted automatically and\n * surfaced as `error` events on the next tick.\n */\nexport class SimpleEvents {\n // biome-ignore lint/complexity/noBannedTypes: the registry is heterogeneous by design — per-event signatures are enforced at the on()/emit() boundary\n private handlers = new Map<string, Set<Function>>();\n\n /**\n * Add event handler\n */\n on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n if (!this.handlers.has(event as string)) {\n this.handlers.set(event as string, new Set());\n }\n this.handlers.get(event as string)?.add(handler);\n }\n\n /**\n * Remove event handler\n */\n off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void {\n const eventHandlers = this.handlers.get(event as string);\n if (eventHandlers) {\n eventHandlers.delete(handler);\n if (eventHandlers.size === 0) {\n this.handlers.delete(event as string);\n }\n }\n }\n\n /**\n * Emit event (internal use only)\n * @internal\n */\n emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void {\n const eventHandlers = this.handlers.get(event as string);\n if (!eventHandlers) return;\n\n // Snapshot handlers so a handler that mutates the set during iteration\n // (e.g. by removing itself) doesn't skip or duplicate calls.\n const handlerArray = Array.from(eventHandlers);\n\n for (const handler of handlerArray) {\n try {\n handler(...args);\n } catch (error) {\n // A throwing handler is treated as broken — drop it so we don't\n // repeatedly invoke it and re-emit the failure as an `error` event\n // for observability. Defer the re-emit so the next tick has a clean\n // call stack and we can't recurse if the error handler also throws.\n eventHandlers.delete(handler);\n\n if (event !== 'error') {\n setTimeout(() => {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit('error', err, String(event));\n }, 0);\n }\n }\n }\n }\n}\n","/**\n * @file Client-side input validation for SDK request boundaries.\n *\n * These validators run before request construction. Constants come from\n * `@shipstatic/types` (`LABEL_CONSTRAINTS`, `LABEL_PATTERN`) so the SDK and\n * API agree on the rules.\n */\n\nimport { LABEL_CONSTRAINTS, LABEL_PATTERN, ShipError } from '@shipstatic/types';\n\n// Re-export the canonical password validator from `@shipstatic/types` so\n// existing SDK callers (`http.ts`) keep their `from '../lib/validation.js'`\n// import path unchanged. The types-tier definition is the single source of\n// truth — see `@shipstatic/types/CLAUDE.md` \"Validation: format vs policy\".\nexport { validatePassword } from '@shipstatic/types';\n\n/**\n * Validate and normalize an array of labels.\n *\n * Lowercases and trims each entry, enforces per-label length and pattern\n * (`LABEL_CONSTRAINTS` / `LABEL_PATTERN`), count cap, and uniqueness after\n * normalization. Returns the normalized array. An empty array is valid and\n * signals \"clear all labels\" on label-update operations.\n */\nexport function validateLabels(labels: string[]): string[];\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined;\nexport function validateLabels(labels: string[] | undefined | null): string[] | undefined {\n if (labels === undefined || labels === null) return undefined;\n if (labels.length === 0) return labels;\n\n if (labels.length > LABEL_CONSTRAINTS.MAX_COUNT) {\n throw ShipError.validation(`Maximum ${LABEL_CONSTRAINTS.MAX_COUNT} labels allowed`);\n }\n\n const normalized = labels.map((label, i) => {\n if (typeof label !== 'string') {\n throw ShipError.validation(`Label at index ${i} must be a string`);\n }\n const cleaned = label.trim().toLowerCase();\n if (cleaned.length < LABEL_CONSTRAINTS.MIN_LENGTH) {\n throw ShipError.validation(\n `Labels must be at least ${LABEL_CONSTRAINTS.MIN_LENGTH} characters long`,\n );\n }\n if (cleaned.length > LABEL_CONSTRAINTS.MAX_LENGTH) {\n throw ShipError.validation(\n `Labels must be no more than ${LABEL_CONSTRAINTS.MAX_LENGTH} characters long`,\n );\n }\n if (!LABEL_PATTERN.test(cleaned)) {\n throw ShipError.validation(\n `Labels must start and end with alphanumeric characters, with optional separators (${LABEL_CONSTRAINTS.SEPARATORS}) between segments`,\n );\n }\n return cleaned;\n });\n\n const unique = [...new Set(normalized)];\n if (unique.length !== normalized.length) {\n throw ShipError.validation('Duplicate labels are not allowed');\n }\n\n return unique;\n}\n","/**\n * Ship SDK resource factory functions.\n */\nimport {\n type AccountResource,\n type DeployInput,\n type DeploymentResource,\n type DomainResource,\n ShipError,\n type StaticFile,\n type TokenResource,\n} from '@shipstatic/types';\n\nexport type {\n AccountResource,\n DeployInput,\n DeploymentResource,\n DomainResource,\n StaticFile,\n TokenResource,\n};\n\nimport type { ApiHttp } from './api/http.js';\nimport { mergeDeployOptions } from './core/config.js';\nimport { detectAndConfigureSPA } from './lib/spa.js';\nimport type { DeploymentOptions, ShipClientOptions } from './types.js';\n\n/**\n * Shared context for all resource factories.\n */\nexport interface ResourceContext {\n getApi: () => ApiHttp;\n ensureInit: () => Promise<void>;\n}\n\n/**\n * Extended context for deployment resource.\n */\nexport interface DeploymentResourceContext extends ResourceContext {\n processInput: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>;\n clientDefaults?: ShipClientOptions;\n}\n\n/**\n * Upload deployment resource with all CRUD operations.\n *\n * There is no client-side auth branching: an upload from a credential-less\n * client simply carries no `Authorization` header, and the API grants the\n * public-account agent identity per request (claim URL + expiry on the\n * response). The SDK stays a transparent pipe either way.\n */\nexport function createDeploymentResource(ctx: DeploymentResourceContext): DeploymentResource {\n const { getApi, ensureInit, processInput, clientDefaults } = ctx;\n\n return {\n upload: async (input: DeployInput, options: DeploymentOptions = {}) => {\n await ensureInit();\n\n const mergedOptions = clientDefaults ? mergeDeployOptions(options, clientDefaults) : options;\n\n if (!processInput) {\n throw ShipError.config('processInput function is not provided.');\n }\n\n const apiClient = getApi();\n let staticFiles = await processInput(input, mergedOptions);\n staticFiles = await detectAndConfigureSPA(staticFiles, apiClient, mergedOptions);\n\n return apiClient.deploy(staticFiles, mergedOptions);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDeployments();\n },\n\n get: async (id: string) => {\n await ensureInit();\n return getApi().getDeployment(id);\n },\n\n set: async (id: string, options: { labels: string[] }) => {\n await ensureInit();\n return getApi().updateDeploymentLabels(id, options.labels);\n },\n\n remove: async (id: string) => {\n await ensureInit();\n await getApi().removeDeployment(id);\n },\n };\n}\n\n/**\n * Create domain resource with all CRUD operations.\n *\n * @remarks\n * The `name` parameter in all methods is an FQDN (Fully Qualified Domain Name).\n * The SDK does not validate or normalize domain names - the API handles all domain semantics.\n */\nexport function createDomainResource(ctx: ResourceContext): DomainResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n // INTENTIONAL DESIGN: The API does NOT support unlinking domains (setting deployment to null).\n // Once a domain is linked to a deployment, it must always have a deployment.\n // Supported: reserve (omit deployment), link, switch deployments atomically, delete entirely.\n // Not supported: unlink after linking (creates ambiguous state with no clear use case).\n // See npm/ship/CLAUDE.md \"Domain Write Semantics\" for full rationale.\n set: async (name: string, options: { deployment?: string; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().setDomain(name, options.deployment, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listDomains();\n },\n\n get: async (name: string) => {\n await ensureInit();\n return getApi().getDomain(name);\n },\n\n remove: async (name: string) => {\n await ensureInit();\n await getApi().removeDomain(name);\n },\n\n verify: async (name: string) => {\n await ensureInit();\n return getApi().verifyDomain(name);\n },\n\n validate: async (name: string) => {\n await ensureInit();\n return getApi().validateDomain(name);\n },\n\n dns: async (name: string) => {\n await ensureInit();\n return getApi().getDomainDns(name);\n },\n\n records: async (name: string) => {\n await ensureInit();\n return getApi().getDomainRecords(name);\n },\n\n share: async (name: string) => {\n await ensureInit();\n return getApi().getDomainShare(name);\n },\n };\n}\n\n/**\n * Create account resource (whoami functionality).\n */\nexport function createAccountResource(ctx: ResourceContext): AccountResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n get: async () => {\n await ensureInit();\n return getApi().getAccount();\n },\n };\n}\n\n/**\n * Create token resource for managing deploy tokens.\n */\nexport function createTokenResource(ctx: ResourceContext): TokenResource {\n const { getApi, ensureInit } = ctx;\n\n return {\n create: async (options: { ttl?: number; labels?: string[] } = {}) => {\n await ensureInit();\n return getApi().createToken(options.ttl, options.labels);\n },\n\n list: async () => {\n await ensureInit();\n return getApi().listTokens();\n },\n\n remove: async (token: string) => {\n await ensureInit();\n await getApi().removeToken(token);\n },\n };\n}\n","/**\n * @file Cross-platform configuration helpers.\n *\n * One pure helper used by the deployment resource:\n *\n * - `mergeDeployOptions(perCallOptions, clientDefaults)` — overlays\n * instance-level defaults under per-call overrides for a single deploy.\n *\n * Deploy options are pure deploy concerns (progress, timeout, concurrency).\n * Credentials, the API URL, and the caller identifier are client identity —\n * they live on the instance, never per call: one client is one principal\n * speaking for one end user against one API. Callers that need a different\n * identity construct another Ship.\n */\n\nimport type { DeploymentOptions, ShipClientOptions } from '../types.js';\n\n/**\n * Overlay client-level defaults under per-call deploy options.\n *\n * Per-call options always win — they're the explicit override for a single\n * `deployments.upload()`. Defaults fill in only when the per-call option is\n * `undefined` (an explicit `null` / empty value passes through).\n */\nexport function mergeDeployOptions(\n options: DeploymentOptions,\n clientDefaults: ShipClientOptions,\n): DeploymentOptions {\n const result: DeploymentOptions = { ...options };\n\n if (result.timeout === undefined && clientDefaults.timeout !== undefined) {\n result.timeout = clientDefaults.timeout;\n }\n if (result.maxConcurrency === undefined && clientDefaults.maxConcurrency !== undefined) {\n result.maxConcurrency = clientDefaults.maxConcurrency;\n }\n if (result.onProgress === undefined && clientDefaults.onProgress !== undefined) {\n result.onProgress = clientDefaults.onProgress;\n }\n\n return result;\n}\n","/**\n * @file SPA detection and auto-configuration utilities.\n *\n * Provides SPA detection and ship.json generation functionality\n * that can be used by both Node.js and browser environments.\n */\n\nimport { DEPLOYMENT_CONFIG_FILENAME, SPA_DEFAULT_CONFIG } from '@shipstatic/types';\nimport type { ApiHttp } from '../api/http.js';\nimport type { DeploymentOptions, StaticFile } from '../types.js';\nimport { calculateMD5 } from './md5.js';\n\n/**\n * Creates ship.json configuration for SPA projects.\n * @returns Promise resolving to StaticFile with SPA configuration\n */\nexport async function createSPAConfig(): Promise<StaticFile> {\n const configString = JSON.stringify(SPA_DEFAULT_CONFIG, null, 2);\n\n // Create content that works in both browser and Node.js environments\n let content: Buffer | Blob;\n if (typeof Buffer !== 'undefined') {\n // Node.js environment\n content = Buffer.from(configString, 'utf-8');\n } else {\n // Browser environment\n content = new Blob([configString], { type: 'application/json' });\n }\n\n const { md5 } = await calculateMD5(content);\n\n return {\n path: DEPLOYMENT_CONFIG_FILENAME,\n content,\n size: configString.length,\n md5,\n };\n}\n\n/**\n * Detects SPA projects and auto-generates configuration.\n * This function can be used by both Node.js and browser environments.\n *\n * @param files - Array of StaticFiles to analyze\n * @param apiClient - HTTP client for API communication\n * @param options - Deployment options containing SPA detection settings\n * @returns Promise resolving to files array with optional SPA config added\n */\nexport async function detectAndConfigureSPA(\n files: StaticFile[],\n apiClient: ApiHttp,\n options: DeploymentOptions,\n): Promise<StaticFile[]> {\n // Skip if disabled, config already exists, or server will handle detection\n if (\n options.spaDetect === false ||\n options.spa ||\n options.build ||\n options.prerender ||\n files.some((f) => f.path === DEPLOYMENT_CONFIG_FILENAME)\n ) {\n return files;\n }\n\n try {\n const isSPA = await apiClient.checkSPA(files, options);\n\n if (isSPA) {\n const spaConfig = await createSPAConfig();\n return [...files, spaConfig];\n }\n } catch (_error) {\n // SPA detection failed, continue silently without auto-config\n }\n\n return files;\n}\n","/**\n * Node.js-specific deploy body creation.\n */\nimport { ShipError } from '@shipstatic/types';\nimport type { DeployBody, DeployBodyContext, StaticFile } from '../../shared/types.js';\n\nexport async function createDeployBody(\n files: StaticFile[],\n context: DeployBodyContext = {},\n): Promise<DeployBody> {\n const { FormData, File } = await import('formdata-node');\n const { FormDataEncoder } = await import('form-data-encoder');\n\n const { labels, via, password, flags, captcha } = context;\n const formData = new FormData();\n const checksums: string[] = [];\n\n for (const file of files) {\n // 1. Validate content type\n if (\n !Buffer.isBuffer(file.content) &&\n !(typeof Blob !== 'undefined' && file.content instanceof Blob)\n ) {\n throw ShipError.file(`Unsupported file.content type for Node.js: ${file.path}`, {\n filePath: file.path,\n });\n }\n\n // 2. Validate md5\n if (!file.md5) {\n throw ShipError.file(`File missing md5 checksum: ${file.path}`, { filePath: file.path });\n }\n\n // 3. Create File and append — API derives Content-Type from extension\n const fileInstance = new File([file.content], file.path, { type: 'application/octet-stream' });\n formData.append('files[]', fileInstance);\n checksums.push(file.md5);\n }\n\n formData.append('checksums', JSON.stringify(checksums));\n\n if (labels && labels.length > 0) formData.append('labels', JSON.stringify(labels));\n if (via) formData.append('via', via);\n if (password) formData.append('password', password);\n if (flags?.build) formData.append('build', 'true');\n if (flags?.prerender) formData.append('prerender', 'true');\n if (flags?.spa) formData.append('spa', 'true');\n if (captcha) formData.append('captcha', captcha);\n\n const encoder = new FormDataEncoder(formData);\n const chunks = [];\n for await (const chunk of encoder.encode()) {\n chunks.push(Buffer.from(chunk));\n }\n const body = Buffer.concat(chunks);\n\n return {\n body: body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer,\n headers: {\n 'Content-Type': encoder.contentType,\n 'Content-Length': Buffer.byteLength(body).toString(),\n },\n };\n}\n","/**\n * @file File-based configuration loader for the `ship` CLI.\n *\n * The CLI is the only place that reads `~/.shiprc` and `package.json` `\"ship\"` keys.\n * Programmatic SDK consumers never touch the filesystem — they pass options to the\n * `Ship` constructor, optionally falling back to `SHIP_*` environment variables.\n * Keeping file resolution out of the SDK is what makes embedded usage (MCP, n8n,\n * GitHub Action) safe by default: `new Ship({})` cannot accidentally pick up the\n * host developer's `~/.shiprc`.\n *\n * Search order (cosmiconfig defaults):\n * 1. `.shiprc` walking up from CWD to `$HOME`\n * 2. `package.json` `\"ship\"` key walking up from CWD\n * 3. `$HOME/.shiprc`\n *\n * The `--config <file>` CLI flag bypasses the search and loads a specific path.\n */\n\nimport { homedir } from 'node:os';\nimport { isShipError, ShipError } from '@shipstatic/types';\nimport { cosmiconfigSync } from 'cosmiconfig';\nimport { z } from 'zod';\nimport { CREDENTIAL_FIELDS } from '../../shared/core/credential-schema.js';\nimport type { ShipClientOptions } from '../../shared/types.js';\n\n// `.strict()` rejects unknown keys — catches typos like `apikey` (lowercase)\n// in user-authored `.shiprc` files. The env reader doesn't need this because\n// its input is exactly the two SHIP_* vars we read.\nconst FileConfigSchema = z.object(CREDENTIAL_FIELDS).strict();\n\nconst MODULE_NAME = 'ship';\n\n/**\n * Load configuration from `.shiprc` / `package.json`.\n *\n * Error semantics by failure mode:\n *\n * | Mode | Behavior |\n * |------|----------|\n * | Search finds no file | Returns `{}` — file config is optional |\n * | `--config <path>` and the file does not exist | Throws — a typo'd path is a clear user error and shouldn't be hidden behind a downstream auth failure |\n * | File found but unparseable JSON / unreadable (permissions) | Throws — silent swallowing left users debugging \"wrong API key\" when the real issue was their config |\n * | File parsed but fails schema validation | Throws with the offending field path |\n *\n * @param configFile - Optional explicit path (from the CLI's `--config` flag).\n * When provided, cosmiconfig loads exactly that file instead of searching.\n * @returns Validated config, or `{}` if no file was found in the search.\n * @throws {ShipError} for explicit-path failures, parse errors, or schema violations.\n */\nexport function loadShipFile(configFile?: string): Partial<ShipClientOptions> {\n // Empty path is treated as absence — matches credential-flag handling\n // (`--token \"\"` falls through to env). A user passing `--config \"$VAR\"`\n // with `VAR` unset gets `--config \"\"`, which should not error: it should\n // fall through to the normal cosmiconfig search.\n const explicitPath = configFile || undefined;\n\n const home = homedir();\n const explorer = cosmiconfigSync(MODULE_NAME, {\n searchPlaces: [`.${MODULE_NAME}rc`, 'package.json', `${home}/.${MODULE_NAME}rc`],\n stopDir: home,\n });\n\n let result: ReturnType<typeof explorer.search>;\n try {\n result = explicitPath ? explorer.load(explicitPath) : explorer.search();\n } catch (error) {\n if (isShipError(error)) throw error;\n // Wrap any cosmiconfig failure (missing explicit path, bad JSON, permissions)\n // in a ShipError. Surfacing this beats a confusing \"auth failed\" later.\n const message = error instanceof Error ? error.message : String(error);\n const where = explicitPath ? ` (${explicitPath})` : '';\n throw ShipError.config(`Failed to read ship config${where}: ${message}`);\n }\n\n if (!result?.config) return {};\n\n try {\n return FileConfigSchema.parse(result.config);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const issue = error.issues[0];\n // Keys from retired credential vocabularies get a rename hint instead\n // of a bare rejection — the fix is one edit, so the error names it.\n if (issue.code === 'unrecognized_keys') {\n const legacy = issue.keys.filter((key) => key === 'apiKey' || key === 'deployToken');\n if (legacy.length > 0) {\n const keys = legacy.map((key) => `\"${key}\"`).join(' and ');\n throw ShipError.config(\n `Invalid config in ${result.filepath}: ${keys} ${legacy.length > 1 ? 'are' : 'is'} no longer supported — the key is now \"token\". Run \\`ship config\\` to rewrite it.`,\n );\n }\n }\n const path = issue.path.length > 0 ? ` at ${issue.path.join('.')}` : '';\n throw ShipError.config(`Invalid config in ${result.filepath}${path}: ${issue.message}`);\n }\n throw ShipError.config(`Invalid config in ${result.filepath}`);\n }\n}\n","/**\n * @file Resolves CLI configuration into a `Ship` instance.\n *\n * Owns the credential precedence contract: **flag > env > file**.\n *\n * Env-over-file is the canonical CLI tooling posture: CI runners and secret\n * managers set environment variables; a stale dotfile from local dev should\n * never override them. The merge is extracted as a pure function so the\n * contract is unit-testable and a future refactor can't silently flip the\n * order.\n *\n * The SDK itself only knows about constructor args + env vars (see\n * `node/index.ts`). File resolution lives here, in the CLI layer, exactly\n * once — keeping the SDK pure is what guarantees embedded consumers like\n * MCP can't inadvertently inherit the host developer's `~/.shiprc`.\n */\n\nimport type { ShipClientOptions } from '../../shared/types.js';\nimport { readEnvConfig } from '../core/config.js';\nimport { Ship } from '../index.js';\nimport { loadShipFile } from './shiprc.js';\n\n/**\n * The subset of CLI flags that participate in config resolution.\n * Other flags (`--json`, `--quiet`, etc.) flow through Commander separately.\n */\nexport interface CliFlags {\n /** Path to a specific config file, from `--config <file>`. */\n config?: string;\n apiUrl?: string;\n token?: string;\n}\n\n/**\n * Pure precedence merge: flag > env > file, per value. There is one token\n * and one API URL — nothing to arbitrate beyond source order.\n *\n * Empty strings are treated as absence and fall through to the next source\n * (mirrors the env reader, which normalizes empty `process.env` values to\n * `undefined`). This handles CI/CD shell-expansion of unset variables —\n * `--token \"$TOKEN\"` with `TOKEN` unset becomes `--token \"\"`, which we\n * must not lock in as a credential. Without this, an empty flag would\n * silently demote an authenticated deploy to anonymous PUBLIC_ACCOUNT.\n *\n * Exported separately from `createClient` so tests can lock in the contract\n * without mocking the SDK or the filesystem.\n */\nexport function mergeCliConfig(\n flags: CliFlags,\n env: Partial<ShipClientOptions>,\n file: Partial<ShipClientOptions>,\n): ShipClientOptions {\n return {\n apiUrl: flags.apiUrl || env.apiUrl || file.apiUrl,\n token: flags.token || env.token || file.token,\n };\n}\n\n/**\n * Resolve CLI flags + env + file into a `Ship` instance, ready for command\n * action handlers. Called once per CLI invocation by `withErrorHandling`.\n *\n * Synchronous all the way down — matches the SDK's sync constructor.\n */\nexport function createClient(flags: CliFlags = {}): Ship {\n return new Ship(mergeCliConfig(flags, readEnvConfig(), loadShipFile(flags.config)));\n}\n","/**\n * @file CLI-specific error UX utilities.\n *\n * Two pure functions: `toShipError` normalizes any thrown value into a typed\n * `ShipError` for the CLI's global error boundary; `getUserMessage` translates\n * a `ShipError` into the actionable string the CLI prints. Both are pure for\n * easy unit testing.\n *\n * Distinct from `ShipError.fromFetchError` (in `@shipstatic/types`), which is\n * for HTTP fetch failures. The CLI's global handler also catches things like\n * Commander parse errors, runtime exceptions in user code, etc. — so it uses\n * `toShipError` and intentionally normalizes unknowns to `Business` (a client\n * error type) so `getUserMessage`'s `isClientError()` branch surfaces the\n * original message rather than swallowing it as a generic \"server error\".\n */\n\nimport { isShipError, ShipError } from '@shipstatic/types';\nimport type { OutputContext } from './formatters.js';\n\n/**\n * Normalize any thrown value to a `ShipError` for the CLI error boundary.\n * Pass-through for existing `ShipError`s; wraps other Errors and unknowns\n * as `Business` so their message is preserved through `getUserMessage`.\n */\nexport function toShipError(err: unknown): ShipError {\n if (isShipError(err)) {\n return err;\n }\n if (err instanceof Error) {\n return ShipError.business(err.message);\n }\n return ShipError.business(String(err ?? 'Unknown error'));\n}\n\n/**\n * CLI options relevant to error message generation.\n */\nexport interface ErrorOptions {\n /**\n * The credential the CLI resolved (flag > env > file) — not the raw\n * `--token` flag. Presence selects the \"invalid or expired\" auth message;\n * absence selects the \"how to authenticate\" one.\n */\n token?: string;\n}\n\n/**\n * Get actionable user-facing message from an error.\n * Transforms technical errors into helpful messages that tell users what to do.\n *\n * This is a pure function - given the same inputs, always returns the same output.\n * All error message logic is centralized here for easy testing and maintenance.\n */\nexport function getUserMessage(\n err: ShipError,\n _context?: OutputContext,\n options?: ErrorOptions,\n): string {\n // Auth errors - tell user what credentials to provide\n if (err.isAuthError()) {\n if (options?.token) {\n return 'authentication failed: invalid or expired token';\n }\n return 'authentication required: pass --token, set SHIP_TOKEN, or run ship config';\n }\n\n // Network errors - include context about what failed\n if (err.isNetworkError()) {\n const url = (err.details as { url?: string } | undefined)?.url;\n if (url) {\n return `network error: could not reach ${url}`;\n }\n return 'network error: could not reach the API. check your internet connection';\n }\n\n // Client errors (Business | Config | File | Forbidden | Validation) —\n // trust the original message; the API or local code authored it.\n if (err.isClientError()) {\n return err.message;\n }\n\n // Other 4xx (NotFound, RateLimit, anything else with a 4xx status) —\n // the API's message is user-facing; trust it.\n if (err.status && err.status >= 400 && err.status < 500) {\n return err.message;\n }\n\n // Server errors (5xx) - generic but actionable\n return 'server error: please try again or check https://status.shipstatic.com';\n}\n\n/**\n * Format error for JSON output.\n * Returns the JSON string to be output (without newline).\n */\nexport function formatErrorJson(message: string, details?: unknown): string {\n return JSON.stringify(\n {\n error: message,\n ...(details ? { details } : {}),\n },\n null,\n 2,\n );\n}\n","/**\n * Pure formatting functions for CLI output.\n * All formatters are synchronous and have no side effects beyond console output.\n */\nimport type {\n Account,\n Deployment,\n DeploymentCreateResponse,\n DeploymentListResponse,\n Domain,\n DomainDnsResponse,\n DomainListResponse,\n DomainRecordsResponse,\n DomainValidateResponse,\n TokenCreateResponse,\n TokenListResponse,\n} from '@shipstatic/types';\nimport type { CLIResult, DomainShareResponse, EnrichedDomain, MessageResult } from './types.js';\nimport { error, formatDetails, formatTable, info, success } from './utils.js';\n\nconst setupUrl = (hash: string, domain: string) => `https://setup.shipstatic.com/${hash}/${domain}`;\n\nexport interface OutputContext {\n operation?: string;\n resourceType?: string;\n resourceId?: string;\n}\n\nexport interface FormatOptions {\n json?: boolean;\n quiet?: boolean;\n noColor?: boolean;\n}\n\n/**\n * Format deployments list\n */\nexport function formatDeploymentsList(\n result: DeploymentListResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (result.deployments.length === 0) {\n console.log('no deployments found');\n console.log();\n return;\n }\n\n const columns = ['deployment', 'labels', 'files', 'size', 'created', 'via'];\n console.log(formatTable(result.deployments, columns, noColor));\n}\n\n/**\n * Format domains list\n */\nexport function formatDomainsList(\n result: DomainListResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (result.domains.length === 0) {\n console.log('no domains found');\n console.log();\n return;\n }\n\n const columns = ['domain', 'deployment', 'labels', 'linked', 'links', 'created'];\n console.log(formatTable(result.domains, columns, noColor));\n}\n\n/**\n * Format single domain result.\n * Accepts plain Domain (from get) or EnrichedDomain (from set, with DNS info).\n */\nexport function formatDomain(\n result: Domain | EnrichedDomain,\n context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n // Destructure enrichment fields (undefined when result is plain Domain)\n const { _dnsRecords, _shareHash, isCreate, ...displayResult } = result as EnrichedDomain;\n\n // Show success message for set operations\n if (context.operation === 'set') {\n const verb = isCreate ? 'created' : 'updated';\n success(`${result.url} domain ${verb}`, false, noColor);\n }\n\n // Display pre-fetched DNS records (for new external domains)\n if (_dnsRecords && _dnsRecords.length > 0) {\n console.log();\n info('DNS Records to configure:', false, noColor);\n _dnsRecords.forEach((record) => {\n console.log(` ${record.type}: ${record.name} → ${record.value}`);\n });\n }\n\n // Display setup instructions link\n if (_shareHash) {\n console.log();\n info(`Setup instructions: ${setupUrl(_shareHash, result.domain)}`, false, noColor);\n }\n\n console.log(formatDetails(displayResult, noColor));\n}\n\n/**\n * Format single deployment result\n */\nexport function formatDeployment(\n result: Deployment | DeploymentCreateResponse,\n context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n // Show success message for upload operations\n if (context.operation === 'upload') {\n success(`${result.url} deployment uploaded`, false, noColor);\n }\n\n console.log(formatDetails(result, noColor));\n\n // Public deployment — claim URL + CTA after details\n const claim = (result as DeploymentCreateResponse).claim;\n if (claim) {\n const days = result.expires ? Math.round((result.expires - result.created) / 86400) : null;\n console.log(\n `IMPORTANT: this deployment${days ? ` expires in ${days} day${days !== 1 ? 's' : ''}` : ' will expire'}, claim it to keep permanently:\\n${claim}\\n`,\n );\n info(\n `configure a free API key with 'ship config' to deploy to your own account`,\n false,\n noColor,\n );\n }\n}\n\n/**\n * Format account/email result\n */\nexport function formatAccount(\n result: Account,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n console.log(formatDetails(result, noColor));\n}\n\n/**\n * Format message result (e.g., from DNS verification)\n */\nexport function formatMessage(\n result: MessageResult,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n if (result.message) {\n success(result.message, false, noColor);\n }\n}\n\n/**\n * Format domain validation result\n */\nexport function formatDomainValidate(\n result: DomainValidateResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (result.valid) {\n success(`domain is valid`, false, noColor);\n console.log();\n if (result.normalized) {\n console.log(` normalized: ${result.normalized}`);\n }\n if (result.available !== null) {\n const availabilityText = result.available\n ? noColor\n ? 'available'\n : 'available ✓'\n : 'already taken';\n console.log(` availability: ${availabilityText}`);\n }\n console.log();\n } else {\n error(result.error || 'domain is invalid', false, noColor);\n }\n}\n\n/**\n * Format domain DNS records result\n */\nexport function formatDomainRecords(\n result: DomainRecordsResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (result.records.length === 0) {\n console.log('no records found');\n console.log();\n return;\n }\n\n const columns = ['type', 'name', 'value'];\n console.log(formatTable(result.records, columns, noColor));\n}\n\n/**\n * Format domain DNS provider result\n */\nexport function formatDomainDns(\n result: DomainDnsResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n const provider = result.dns?.provider?.name || null;\n console.log(formatDetails({ domain: result.domain, provider }, noColor));\n}\n\n/**\n * Format domain share result as setup URL\n */\nexport function formatDomainShare(\n result: DomainShareResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n success(setupUrl(result.hash, result.domain), false, noColor);\n}\n\n/**\n * Format tokens list\n */\nexport function formatTokensList(\n result: TokenListResponse,\n _context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (result.tokens.length === 0) {\n console.log('no tokens found');\n console.log();\n return;\n }\n\n const columns = ['token', 'labels', 'created', 'expires'];\n console.log(formatTable(result.tokens, columns, noColor));\n}\n\n/**\n * Format single token result (creation response includes both token ID and secret)\n */\nexport function formatToken(\n result: TokenCreateResponse,\n context: OutputContext,\n options: FormatOptions,\n): void {\n const { noColor } = options;\n\n if (context.operation === 'create' && result.token) {\n success(`token ${result.token} created`, false, noColor);\n }\n\n console.log(formatDetails(result, noColor));\n}\n\n/**\n * Main output function - routes to appropriate formatter based on result shape.\n * Handles JSON mode, removal operations, and ping results.\n */\nexport function formatOutput(\n result: CLIResult,\n context: OutputContext,\n options: FormatOptions,\n): void {\n const { json, quiet, noColor } = options;\n\n // Quiet mode: output only the key identifier\n if (quiet) {\n if (result === undefined || typeof result === 'boolean') return;\n if (result !== null && typeof result === 'object') {\n if ('deployments' in result) {\n for (const d of (result as DeploymentListResponse).deployments) console.log(d.deployment);\n } else if ('domains' in result) {\n for (const d of (result as DomainListResponse).domains) console.log(d.domain);\n } else if ('tokens' in result) {\n for (const t of (result as TokenListResponse).tokens) console.log(t.token);\n } else if ('records' in result) {\n for (const r of (result as DomainRecordsResponse).records)\n console.log(`${r.type} ${r.name} ${r.value}`);\n } else if ('hash' in result) {\n const r = result as DomainShareResponse;\n console.log(setupUrl(r.hash, r.domain));\n } else if ('dns' in result) {\n const name = (result as DomainDnsResponse).dns?.provider?.name;\n if (name) console.log(name);\n } else if ('domain' in result) {\n console.log((result as Domain).domain);\n } else if ('deployment' in result) {\n console.log((result as Deployment).deployment);\n } else if ('secret' in result) {\n console.log((result as TokenCreateResponse).secret);\n } else if ('email' in result) {\n console.log((result as Account).email);\n } else if ('valid' in result) {\n const v = result as DomainValidateResponse;\n if (v.valid && v.normalized) console.log(v.normalized);\n } else if ('message' in result) {\n console.log((result as MessageResult).message);\n }\n }\n return;\n }\n\n // Handle void/undefined results (removal operations)\n if (result === undefined) {\n if (context.operation === 'remove' && context.resourceType && context.resourceId) {\n success(`${context.resourceId} ${context.resourceType.toLowerCase()} removed`, json, noColor);\n } else {\n success('removed successfully', json, noColor);\n }\n return;\n }\n\n // Handle ping result (boolean from client.ping())\n if (typeof result === 'boolean') {\n if (result) {\n success('api reachable', json, noColor);\n } else {\n error('api unreachable', json, noColor);\n }\n return;\n }\n\n // JSON mode: output raw JSON for all results\n if (json && result !== null && typeof result === 'object') {\n // Filter internal fields from JSON output\n const output = { ...result } as Record<string, unknown>;\n delete output._dnsRecords;\n delete output._shareHash;\n delete output.isCreate;\n console.log(JSON.stringify(output, null, 2));\n console.log();\n return;\n }\n\n // Route to specific formatter based on result shape\n // Order matters: check list types before singular types\n if (result !== null && typeof result === 'object') {\n if ('deployments' in result) {\n formatDeploymentsList(result as DeploymentListResponse, context, options);\n } else if ('domains' in result) {\n formatDomainsList(result as DomainListResponse, context, options);\n } else if ('tokens' in result) {\n formatTokensList(result as TokenListResponse, context, options);\n } else if ('records' in result) {\n formatDomainRecords(result as DomainRecordsResponse, context, options);\n } else if ('hash' in result) {\n formatDomainShare(result as DomainShareResponse, context, options);\n } else if ('dns' in result) {\n formatDomainDns(result as DomainDnsResponse, context, options);\n } else if ('domain' in result) {\n formatDomain(result as Domain, context, options);\n } else if ('deployment' in result) {\n formatDeployment(result as Deployment, context, options);\n } else if ('token' in result) {\n formatToken(result as TokenCreateResponse, context, options);\n } else if ('email' in result) {\n formatAccount(result as Account, context, options);\n } else if ('valid' in result) {\n formatDomainValidate(result as DomainValidateResponse, context, options);\n } else if ('message' in result) {\n formatMessage(result as MessageResult, context, options);\n } else {\n // Fallback\n success('success', json, noColor);\n }\n } else {\n // Fallback for non-object results\n success('success', json, noColor);\n }\n}\n"],"mappings":";skBAgUO,SAASA,EAAYC,EAAO,CAC/B,OAAQA,IAAU,MACd,OAAOA,GAAU,UACjB,SAAUA,GACVA,EAAM,OAAS,aACf,WAAYA,CACpB,CAsEO,SAASC,GAAmBC,EAAU,CACzC,IAAMC,EAAWD,EAAS,YAAY,GAAG,EACzC,GAAIC,IAAa,IAAMA,IAAaD,EAAS,OAAS,EAClD,MAAO,GACX,IAAME,EAAMF,EAAS,MAAMC,EAAW,CAAC,EAAE,YAAY,EACrD,OAAOE,GAAmB,IAAID,CAAG,CACrC,CA0BO,SAASE,GAAeJ,EAAU,CACrC,OAAOK,GAAsB,KAAKL,CAAQ,CAC9C,CAoBO,SAASM,GAAiBC,EAAU,CAEvC,OADiBA,EAAS,QAAQ,MAAO,GAAG,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO,EACvD,KAAMC,GAAMC,GAAwB,IAAID,CAAC,CAAC,CAC9D,CA0FO,SAASE,GAAcC,EAAO,CACjC,OAAIA,EAAM,WAAWC,GAAQ,MAAM,EACxBC,EAAU,QACjBF,EAAM,WAAWG,GAAa,MAAM,EAC7BD,EAAU,aACdA,EAAU,MACrB,CAmCA,SAASE,GAA2BC,EAAOC,EAAOC,EAAO,CACrD,GAAI,CAACF,EAAM,WAAWC,EAAM,MAAM,EAC9B,MAAME,EAAU,WAAW,GAAGD,CAAK,qBAAqBD,EAAM,MAAM,GAAG,EAE3E,GAAID,EAAM,SAAWC,EAAM,aACvB,MAAME,EAAU,WAAW,GAAGD,CAAK,YAAYD,EAAM,YAAY,sBAAsBA,EAAM,MAAM,MAAMA,EAAM,UAAU,aAAa,EAE1I,IAAMG,EAAUJ,EAAM,MAAMC,EAAM,OAAO,MAAM,EAC/C,GAAI,CAAC,IAAI,OAAO,aAAaA,EAAM,UAAU,KAAM,GAAG,EAAE,KAAKG,CAAO,EAChE,MAAMD,EAAU,WAAW,GAAGD,CAAK,iB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,OACA,SACA,cACA,UACA,SACA,UACA,SACA,YACF,EACwB,KAAKA,EAAS;AAAA,EAAO,GAAG,CAAC,EACjD,QAAQ,KAAK,CAAC,CAChB,CAIE,QAAQ,IAAI,WAAa,SACxB,QAAQ,KAAK,SAAS,YAAY,GACjC,QAAQ,KAAK,SAAS,WAAW,GACjC,QAAQ,KAAK,SAAS,YAAY,IAEpCH,GAAiB,EAInB,GAAI,QAAQ,IAAI,WAAa,OAC3B,GAAI,CACF7F,EAAQ,MAAM,QAAQ,IAAI,CAC5B,OAASC,EAAK,CAGZ,GAAIA,aAAe,OAAS,SAAUA,EAAK,CACzC,IAAMgG,EAAQhG,EAAkC,KAC1CiG,EAAYjG,EAAsC,SACpDgG,GAAM,WAAW,YAAY,GAC/B,QAAQ,KAAKC,GAAY,CAAC,CAE9B,CACA,MAAMjG,CACR","names":["isShipError","error","isBlockedExtension","filename","dotIndex","ext","BLOCKED_EXTENSIONS","hasUnsafeChars","UNSAFE_FILENAME_CHARS","hasUnbuiltMarker","filePath","s","UNBUILT_PROJECT_MARKERS","classifyToken","token","API_KEY","TokenKind","DEPLOY_TOKEN","validatePrefixedCredential","value","shape","label","ShipError","hexPart","validateApiKey","apiKey","validateDeployToken","deployToken","validateToken","validateCaller","caller","CALLER","validateApiUrl","apiUrl","url","validatePassword","trimmed","PASSWORD_CONSTRAINTS","ErrorType","CLIENT_ONLY_ERROR_TYPES","ERROR_CATEGORIES","SERVER_PRODUCIBLE_ERROR_TYPES","AuthMethod","DEPLOYMENT_CONFIG_FILENAME","SPA_DEFAULT_CONFIG","DEFAULT_API","LABEL_CONSTRAINTS","LABEL_PATTERN","init_dist","__esmMin","t","_ShipError","type","message","status","details","authDetails","response","operationName","bodyType","json","obj","text","cause","op","resource","id","errorType","detectEnvironment","getENV","_testEnvironment","init_env","__esmMin","md5Blob","blob","SparkMD5","spark","chunkSize","start","end","md5Buffer","buffer","createHash","hash","md5Path","path","createReadStream","resolve","reject","stream","err","ShipError","chunk","calculateMD5","input","init_md5","__esmMin","init_dist","findCommonParent","dirPaths","normalizedPaths","p","pathSegments","commonSegments","minLength","segment","segments","normalizeWebPath","path","init_path","__esmMin","optimizeDeployPaths","filePaths","options","path","normalizeWebPath","extractFileName","commonPrefix","findCommonDirectory","filePath","deployPath","prefixToRemove","pathSegments","commonSegments","minLength","segments","segment","init_deploy_paths","__esmMin","init_path","validateFileName","filename","hasUnsafeChars","reservedNames","nameWithoutPath","init_file_validation","__esmMin","init_dist","filterJunk","filePaths","options","p","hasUnbuiltMarker","ShipError","filePath","parts","basename","part","directorySegments","segment","JUNK_DIRECTORIES","junkDir","import_junk","init_junk","__esmMin","init_dist","validateDeployPath","deployPath","sourceIdentifier","ShipError","validateDeployFile","nameCheck","validateFileName","isBlockedExtension","init_security","__esmMin","init_dist","init_file_validation","node_files_exports","__export","processFilesForNode","findAllFilePaths","dirPath","visited","results","realPath","entries","entry","fullPath","stats","subFiles","paths","options","platformLimits","getENV","ShipError","p","absPath","marker","e","UNBUILT_PROJECT_MARKERS","isShipError","absolutePaths","uniquePaths","inputAbsolutePaths","inputBasePath","findCommonParent","contentPaths","rel","deployPaths","optimizeDeployPaths","f","filteredSet","filterJunk","validAbsPaths","validDeployPaths","i","totalSize","filePath","deployPath","validateDeployPath","validateDeployFile","content","md5","calculateMD5","error","errorMessage","fs","path","init_node_files","__esmMin","init_dist","init_deploy_paths","init_env","init_junk","init_md5","init_path","init_security","import_node_fs","path","init_dist","import_commander","import_yoctocolors","init_dist","import_zod","import_zod","CREDENTIAL_FIELDS","init_env","EnvConfigSchema","CREDENTIAL_FIELDS","ENV_VAR_BY_FIELD","readEnvConfig","getENV","raw","error","issue","field","envVar","ShipError","fs","os","path","import_columnify","import_yoctocolors","INTERNAL_FIELDS","applyColor","colorFn","text","noColor","decapitalize","msg","success","json","error","errorPrefix","errorMsg","warn","warnPrefix","warnMsg","info","infoPrefix","infoMsg","formatTimestamp","timestamp","context","isoString","formatValue","key","value","mb","formatTable","data","columns","headerMap","firstItem","columnOrder","transformedData","item","record","transformed","col","columnify","config","heading","line","formatDetails","obj","entries","detectShell","shell","getShellPaths","homeDir","installCompletion","scriptDir","options","json","noColor","error","paths","sourceScript","fishDir","success","info","sourceLine","content","prefix","warn","e","message","uninstallCompletion","lines","filtered","i","removed","endsWithNewline","newContent","import_node_fs","import_node_os","import_node_path","import_promises","init_dist","import_yoctocolors","CONFIG_PATH","maskToken","token","readExistingConfig","runConfig","options","noColor","json","applyDim","text","applyGreen","existing","apiUrl","DEFAULT_API","existingToken","rl","prompt","input","validateToken","init_dist","init_dist","init_dist","SimpleEvents","event","handler","eventHandlers","args","handlerArray","error","err","init_dist","validateLabels","labels","LABEL_CONSTRAINTS","ShipError","normalized","label","i","cleaned","LABEL_PATTERN","unique","ENDPOINTS","DEFAULT_REQUEST_TIMEOUT","ApiHttp","SimpleEvents","options","DEFAULT_API","headers","url","operationName","cleanup","timeout","fetchOptions","response","ShipError","error","shipError","data","customHeaders","existingSignal","controller","timeoutId","abort","files","file","validatePassword","labels","validateLabels","flags","body","bodyHeaders","id","normalized","name","deployment","status","ttl","token","_options","indexFile","f","indexContent","init_dist","mergeDeployOptions","options","clientDefaults","result","init_dist","init_md5","createSPAConfig","configString","SPA_DEFAULT_CONFIG","content","md5","calculateMD5","DEPLOYMENT_CONFIG_FILENAME","detectAndConfigureSPA","files","apiClient","options","f","spaConfig","createDeploymentResource","ctx","getApi","ensureInit","processInput","clientDefaults","input","options","mergedOptions","mergeDeployOptions","ShipError","apiClient","staticFiles","detectAndConfigureSPA","id","createDomainResource","name","createAccountResource","createTokenResource","token","Ship","options","validateCaller","ShipError","validateToken","ApiHttp","ctx","createDeploymentResource","input","opts","createDomainResource","createAccountResource","createTokenResource","error","event","handler","headers","token","value","init_env","init_dist","createDeployBody","files","context","FormData","File","FormDataEncoder","labels","via","password","flags","captcha","formData","checksums","file","ShipError","fileInstance","encoder","chunks","chunk","body","Ship","options","getENV","ShipError","env","readEnvConfig","input","paths","p","processFilesForNode","createDeployBody","import_node_os","init_dist","import_cosmiconfig","import_zod","FileConfigSchema","CREDENTIAL_FIELDS","MODULE_NAME","loadShipFile","configFile","explicitPath","home","explorer","result","error","isShipError","message","where","ShipError","issue","legacy","key","keys","path","mergeCliConfig","flags","env","file","createClient","Ship","readEnvConfig","loadShipFile","init_dist","toShipError","err","isShipError","ShipError","getUserMessage","_context","options","url","formatErrorJson","message","details","setupUrl","hash","domain","formatDeploymentsList","result","_context","options","noColor","columns","formatTable","formatDomainsList","formatDomain","context","_dnsRecords","_shareHash","isCreate","displayResult","verb","success","info","record","formatDetails","formatDeployment","claim","days","formatAccount","formatMessage","formatDomainValidate","availabilityText","error","formatDomainRecords","formatDomainDns","provider","formatDomainShare","formatTokensList","formatToken","formatOutput","json","quiet","d","t","name","v","output","loadPackageJson","paths","p","packageJson","program","err","displayHelp","processOptions","globalOptions","message","error","str","noColor","applyBold","text","applyDim","icon","emoji","output","collect","value","previous","mergeLabelOption","cmdOptions","programOpts","labels","filtered","l","mergePasswordOption","handleUnknownSubcommand","parentName","validSubcommands","args","commandObj","unknownArg","arg","command","options","forceColor","resolveCliToken","flags","file","loadShipFile","token","mergeCliConfig","readEnvConfig","handleError","context","opts","shipError","toShipError","getUserMessage","formatErrorJson","ErrorType","withErrorHandling","handler","resolvedContext","config","apiUrl","client","createClient","result","formatOutput","performDeploy","deployPath","password","ShipError","stats","deployOptions","abortController","spinner","yoctoSpinner","sigintHandler","thisCommand","validateToken","validateApiUrl","validationError","isShipError","_options","deploymentsCmd","deployment","id","domainsCmd","name","resolve","data","chunk","setOptions","records","share","tokensCmd","accountCmd","completionCmd","scriptDir","installCompletion","uninstallCompletion","runConfig","handleCompletion","isBash","isZsh","isFish","code","exitCode"]}