@happyvertical/smrt-config 0.61.0 → 0.61.2

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted-app-BomhfPIt.js","names":["describe"],"sources":["../../src/deployment/compose-contract.ts","../../src/deployment/sha256.ts","../../src/deployment/hosted-app.ts"],"sourcesContent":["/**\n * The compose deployment contract: a Compose file annotated with\n * `x-happyvertical` extension fields is an application's deployment\n * declaration. Compose ignores `x-` keys, so the same file runs locally, on a\n * self-hosted box, and on a platform that reads the annotations.\n *\n * This module validates a parsed Compose document against contract version 1\n * and the supported platform subset, and resolves it into a plain declaration\n * that a platform composer or the `smrt-app` chart renderer consumes. It does\n * no I/O and has no Node dependency: the caller parses the YAML.\n *\n * The published JSON Schema (`schemas/x-happyvertical.v1.schema.json`) covers\n * the shape of the annotations. The rules that span services live here.\n */\n\n/** The Compose extension key the contract lives under. */\nexport const X_HAPPYVERTICAL_KEY = 'x-happyvertical';\n\n/** The contract version this module validates. */\nexport const X_HAPPYVERTICAL_VERSION = 1;\n\n/** `$id` of the published JSON Schema for {@link X_HAPPYVERTICAL_VERSION}. */\nexport const X_HAPPYVERTICAL_SCHEMA_ID =\n 'https://s-m-r-t.dev/schemas/x-happyvertical/v1.schema.json';\n\n/** Platform presets a version 1 declaration may name. */\nexport const X_HAPPYVERTICAL_PRESETS = ['smrt'] as const;\n\n/** Roles a service the application runs may take. */\nexport const X_HAPPYVERTICAL_ROLES = ['web', 'worker'] as const;\n\n/** Platform services a local container may stand in for. */\nexport const X_HAPPYVERTICAL_BINDINGS = [\n 'postgres',\n 'bucket',\n 'email',\n 'ai',\n] as const;\n\nexport type XHappyVerticalPreset = (typeof X_HAPPYVERTICAL_PRESETS)[number];\nexport type XHappyVerticalRole = (typeof X_HAPPYVERTICAL_ROLES)[number];\nexport type XHappyVerticalBinding = (typeof X_HAPPYVERTICAL_BINDINGS)[number];\n\n/**\n * `declare` checks the file as it sits in the repository: services may be\n * built locally or use tags. `deploy` additionally requires every web and\n * worker service to resolve to an image digest, because the platform deploys\n * what CI already built and never runs `build:`.\n */\nexport type ComposeDeploymentStage = 'declare' | 'deploy';\n\nexport interface ComposeDeploymentOptions {\n /** Defaults to `declare`. */\n stage?: ComposeDeploymentStage;\n /**\n * Image digest references by service name (`registry/name@sha256:…`),\n * normally the digests a release carries. They take precedence over the\n * `image:` written in the file.\n */\n images?: Record<string, string>;\n}\n\nexport type ComposeDeploymentIssueCode =\n | 'document-invalid'\n | 'not-self-contained'\n | 'contract-missing'\n | 'contract-invalid'\n | 'version-unsupported'\n | 'preset-unknown'\n | 'domain-invalid'\n | 'migrate-missing'\n | 'migrate-invalid'\n | 'migrate-service-not-role'\n | 'services-missing'\n | 'service-invalid'\n | 'service-name-invalid'\n | 'annotation-invalid'\n | 'role-and-binding'\n | 'role-unknown'\n | 'binding-unknown'\n | 'binding-duplicate'\n | 'binding-with-health'\n | 'binding-no-local-image'\n | 'health-missing'\n | 'health-invalid'\n | 'worker-health-needs-command'\n | 'web-service-count'\n | 'ingress-port-count'\n | 'ingress-port-invalid'\n | 'worker-publishes-port'\n | 'service-no-image'\n | 'image-not-digest'\n | 'image-for-unknown-service'\n | 'privileged'\n | 'host-network'\n | 'volume-not-declared'\n | 'volume-not-plain'\n | 'command-not-list'\n | 'interpolated-value'\n | 'merge-key-unresolved'\n | 'local-only-service';\n\nexport interface ComposeDeploymentIssue {\n code: ComposeDeploymentIssueCode;\n severity: 'error' | 'warning';\n /** Where in the Compose file the problem is, for example `services.web.ports`. */\n path: string;\n /** The service the issue belongs to, when it belongs to one. */\n service?: string;\n /** What is wrong, in plain language. */\n message: string;\n /** What to change. */\n fix: string;\n}\n\nexport type ComposeDeploymentHealth = { path: string } | { command: string[] };\n\nexport interface ComposeDeploymentVolume {\n /** Name of the volume declared under top-level `volumes:`. */\n name: string;\n /** Path the volume is mounted at inside the container. */\n target: string;\n readOnly: boolean;\n}\n\nexport interface ComposeDeploymentWorkload {\n name: string;\n role: XHappyVerticalRole;\n /**\n * At the `deploy` stage, always an image digest reference. At the `declare`\n * stage, the `image:` written in the file, absent for a service that is\n * only built locally or whose image is interpolated (contains `$`).\n */\n image?: string;\n /**\n * Present only when the Compose file sets `entrypoint`; an empty list means\n * the image's own entrypoint is ignored. Absent means the image's entrypoint\n * runs, with `command` as its arguments, exactly as Compose does.\n */\n entrypoint?: string[];\n /**\n * Present only when the Compose file sets `command`; an empty list means\n * the image's default command is discarded. Absent means the image's\n * default command runs.\n */\n command?: string[];\n /** The ingress port. Present on the web service only. */\n port?: number;\n health: ComposeDeploymentHealth;\n volumes: ComposeDeploymentVolume[];\n}\n\nexport interface ComposeDeploymentBinding {\n /** The Compose service name of the local stand-in. */\n name: string;\n kind: XHappyVerticalBinding;\n}\n\nexport interface ComposeDeploymentMigration {\n /** The web or worker service whose image runs the migration. */\n service: string;\n command: string[];\n /** Same meaning as {@link ComposeDeploymentWorkload.image}. */\n image?: string;\n}\n\n/** The resolved declaration. Environment values are deliberately not part of it. */\nexport interface ComposeDeploymentDeclaration {\n version: typeof X_HAPPYVERTICAL_VERSION;\n preset: XHappyVerticalPreset;\n stage: ComposeDeploymentStage;\n /** Top-level Compose `name:`, when the file sets a literal one (no `$`). */\n name?: string;\n domain?: string;\n migrate: ComposeDeploymentMigration;\n workloads: ComposeDeploymentWorkload[];\n bindings: ComposeDeploymentBinding[];\n /** Services with no annotation. They run locally and are never deployed. */\n localOnly: string[];\n}\n\nexport interface ComposeDeploymentResult {\n ok: boolean;\n errors: ComposeDeploymentIssue[];\n warnings: ComposeDeploymentIssue[];\n /** Present only when there are no errors. */\n declaration?: ComposeDeploymentDeclaration;\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst SERVICE_NAME = /^[a-z][a-z0-9-]{0,30}$/;\nconst DIGEST_IMAGE = /^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/;\nconst DOMAIN =\n /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;\nconst HEALTH_PATH = /^\\/\\S*$/;\n// A string command Compose splits exactly as whitespace does: no quoting,\n// escaping, or interpolation that a shell-style split would treat specially.\nconst PLAIN_COMMAND = /^[A-Za-z0-9_./:=@,+-]+( +[A-Za-z0-9_./:=@,+-]+)*$/;\nconst INTERPOLATION = /\\$\\{[^}]*\\}|\\$[A-Za-z_][A-Za-z0-9_]*/g;\n\nconst APPLICATION_FIELDS = ['version', 'preset', 'domain', 'migrate'];\nconst MIGRATE_FIELDS = ['service', 'command'];\nconst SERVICE_FIELDS = ['role', 'health', 'binding'];\nconst HEALTH_FIELDS = ['path', 'command'];\n\nfunction isRecord(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((item) => typeof item === 'string' && item.length > 0)\n );\n}\n\n/**\n * Put an arbitrary parsed value into a message without ever throwing: the\n * document is hostile input and may hold objects with no usable `toString`,\n * cycles built from YAML aliases, or values JSON cannot serialize.\n */\nfunction describe(value: unknown): string {\n if (typeof value === 'string') {\n return value.length > 80 ? `${value.slice(0, 80)}…` : value;\n }\n if (\n typeof value === 'number' ||\n typeof value === 'boolean' ||\n typeof value === 'bigint'\n ) {\n return `${value}`;\n }\n if (value === null || value === undefined) return 'an empty value';\n if (Array.isArray(value)) return 'a list';\n return typeof value === 'object' ? 'a mapping' : `a ${typeof value}`;\n}\n\n/**\n * Compose substitutes `$VAR` and `${VAR}` in every string of the file,\n * extension fields included, before it runs anything. A consumer of the\n * declaration reads the file as written, so a carried string that contains\n * `$` would mean one thing locally and another once deployed.\n */\nfunction refuseVariables(\n values: readonly string[],\n path: string,\n what: string,\n issues: IssueCollector,\n service?: string,\n): boolean {\n if (!values.some((value) => value.includes('$'))) return false;\n issues.error(\n 'interpolated-value',\n path,\n `${what} contains \\`$\\`. Compose replaces variables before it runs the stack, but the platform reads the file as written, so the two would not run the same thing.`,\n 'Write the literal value. Settings that differ between environments belong in the environment the application reads, not in this line.',\n service,\n );\n return true;\n}\n\n/**\n * Path of the first `<<` key anywhere in the document, or undefined. Visits\n * each object once, so cycles built from YAML aliases cannot loop.\n */\nfunction findMergeKey(root: unknown): string | undefined {\n const seen = new Set<object>();\n const pending: Array<[unknown, string]> = [[root, '']];\n while (pending.length > 0) {\n const [value, path] = pending.pop() as [unknown, string];\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n continue;\n }\n seen.add(value);\n if (Array.isArray(value)) {\n value.forEach((item, index) => {\n pending.push([item, `${path}[${index}]`]);\n });\n continue;\n }\n for (const [key, item] of Object.entries(value)) {\n const here = path ? `${path}.${key}` : key;\n if (key === '<<') return here;\n pending.push([item, here]);\n }\n }\n return undefined;\n}\n\n/** Compose interpolates this value, so the text in the file is not what runs. */\nfunction isLiteral(value: string): boolean {\n return !value.includes('$');\n}\n\nfunction quoteList(values: readonly string[]): string {\n return values.map((value) => `\\`${value}\\``).join(', ');\n}\n\nfunction unknownFields(value: UnknownRecord, known: string[]): string[] {\n return Object.keys(value).filter((key) => !known.includes(key));\n}\n\nclass IssueCollector {\n readonly errors: ComposeDeploymentIssue[] = [];\n readonly warnings: ComposeDeploymentIssue[] = [];\n\n error(\n code: ComposeDeploymentIssueCode,\n path: string,\n message: string,\n fix: string,\n service?: string,\n ): void {\n this.errors.push({\n code,\n severity: 'error',\n path,\n ...(service ? { service } : {}),\n message,\n fix,\n });\n }\n\n warning(\n code: ComposeDeploymentIssueCode,\n path: string,\n message: string,\n fix: string,\n service?: string,\n ): void {\n this.warnings.push({\n code,\n severity: 'warning',\n path,\n ...(service ? { service } : {}),\n message,\n fix,\n });\n }\n}\n\ninterface ParsedApplication {\n preset?: XHappyVerticalPreset;\n domain?: string;\n migrateService?: string;\n migrateCommand?: string[];\n}\n\nfunction parseApplication(\n document: UnknownRecord,\n issues: IssueCollector,\n): ParsedApplication {\n const path = X_HAPPYVERTICAL_KEY;\n const block = document[X_HAPPYVERTICAL_KEY];\n if (block === undefined) {\n issues.error(\n 'contract-missing',\n path,\n `The file has no top-level \\`${X_HAPPYVERTICAL_KEY}\\` block, so it is an ordinary Compose file and not a deployment declaration.`,\n `Add a top-level \\`${X_HAPPYVERTICAL_KEY}\\` block with \\`version: 1\\`, \\`preset: smrt\\` and a \\`migrate\\` command.`,\n );\n return {};\n }\n if (!isRecord(block)) {\n issues.error(\n 'contract-invalid',\n path,\n `The top-level \\`${X_HAPPYVERTICAL_KEY}\\` block must be a mapping of fields.`,\n 'Write it as indented `key: value` lines: `version`, `preset`, `domain`, `migrate`.',\n );\n return {};\n }\n\n const parsed: ParsedApplication = {};\n for (const field of unknownFields(block, APPLICATION_FIELDS)) {\n issues.error(\n 'contract-invalid',\n `${path}.${field}`,\n `\\`${field}\\` is not a field of the version 1 contract.`,\n `Remove it or fix the spelling. The top-level fields are ${quoteList(APPLICATION_FIELDS)}.`,\n );\n }\n\n if (block.version !== X_HAPPYVERTICAL_VERSION) {\n issues.error(\n 'version-unsupported',\n `${path}.version`,\n block.version === undefined\n ? 'The contract version is missing.'\n : `Contract version \\`${describe(block.version)}\\` is not supported here.`,\n 'Set `version: 1` (a number, without quotes).',\n );\n }\n\n if (\n typeof block.preset === 'string' &&\n (X_HAPPYVERTICAL_PRESETS as readonly string[]).includes(block.preset)\n ) {\n parsed.preset = block.preset as XHappyVerticalPreset;\n } else {\n issues.error(\n 'preset-unknown',\n `${path}.preset`,\n block.preset === undefined\n ? 'The preset is missing, so the platform does not know what kind of application this is.'\n : `\\`${describe(block.preset)}\\` is not a preset the platform knows.`,\n `Set \\`preset\\` to one of: ${quoteList(X_HAPPYVERTICAL_PRESETS)}.`,\n );\n }\n\n if (block.domain !== undefined) {\n if (\n typeof block.domain === 'string' &&\n block.domain.length <= 253 &&\n DOMAIN.test(block.domain)\n ) {\n parsed.domain = block.domain;\n } else {\n issues.error(\n 'domain-invalid',\n `${path}.domain`,\n `\\`${describe(block.domain)}\\` is not a hostname.`,\n 'Write only the hostname in lowercase, for example `app.example.com`: no `https://`, no port, no path.',\n );\n }\n }\n\n const migrate = block.migrate;\n if (migrate === undefined) {\n issues.error(\n 'migrate-missing',\n `${path}.migrate`,\n 'There is no `migrate` entry, so the platform does not know how to prepare the database before a release starts.',\n 'Add `migrate:` with a `command` list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"db:migrate\"]`.',\n );\n return parsed;\n }\n if (!isRecord(migrate)) {\n issues.error(\n 'migrate-invalid',\n `${path}.migrate`,\n '`migrate` must be a mapping with a `command`.',\n 'Write `migrate:` followed by an indented `command:` list.',\n );\n return parsed;\n }\n for (const field of unknownFields(migrate, MIGRATE_FIELDS)) {\n issues.error(\n 'migrate-invalid',\n `${path}.migrate.${field}`,\n `\\`${field}\\` is not a field of \\`migrate\\`.`,\n `Remove it or fix the spelling. \\`migrate\\` takes ${quoteList(MIGRATE_FIELDS)}.`,\n );\n }\n if (isStringList(migrate.command)) {\n if (\n !refuseVariables(\n migrate.command,\n `${path}.migrate.command`,\n 'The migration command',\n issues,\n )\n ) {\n parsed.migrateCommand = [...migrate.command];\n }\n } else {\n issues.error(\n 'migrate-invalid',\n `${path}.migrate.command`,\n 'The migration command must be a list with one argument per item.',\n 'Write it as a list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"db:migrate\"]`.',\n );\n }\n if (migrate.service !== undefined) {\n if (typeof migrate.service === 'string' && migrate.service.length > 0) {\n parsed.migrateService = migrate.service;\n } else {\n issues.error(\n 'migrate-invalid',\n `${path}.migrate.service`,\n '`migrate.service` must be the name of a service in this file.',\n 'Name your web or worker service, or remove the line to use the web service.',\n );\n }\n }\n return parsed;\n}\n\nfunction parseHealth(\n name: string,\n role: XHappyVerticalRole,\n health: unknown,\n issues: IssueCollector,\n): ComposeDeploymentHealth | undefined {\n const path = `services.${name}.${X_HAPPYVERTICAL_KEY}.health`;\n if (health === undefined) {\n issues.error(\n 'health-missing',\n path,\n `Service \\`${name}\\` has no health check, so the platform cannot tell when it is ready.`,\n role === 'web'\n ? 'Add `health:` with a `path` that answers 200 when the app is ready, for example `path: /api/health`.'\n : 'Add `health:` with a `command` list that exits 0 when the worker is ready.',\n name,\n );\n return undefined;\n }\n if (!isRecord(health)) {\n issues.error(\n 'health-invalid',\n path,\n `The health check of \\`${name}\\` must be a mapping with either \\`path\\` or \\`command\\`.`,\n 'Write `health:` followed by an indented `path:` or `command:`.',\n name,\n );\n return undefined;\n }\n const extra = unknownFields(health, HEALTH_FIELDS);\n if (extra.length > 0) {\n issues.error(\n 'health-invalid',\n `${path}.${extra[0]}`,\n `\\`${extra[0]}\\` is not a field of a health check.`,\n `Remove it or fix the spelling. A health check takes ${quoteList(HEALTH_FIELDS)}.`,\n name,\n );\n return undefined;\n }\n const hasPath = health.path !== undefined;\n const hasCommand = health.command !== undefined;\n if (hasPath === hasCommand) {\n issues.error(\n 'health-invalid',\n path,\n hasPath\n ? `The health check of \\`${name}\\` has both \\`path\\` and \\`command\\`.`\n : `The health check of \\`${name}\\` is empty.`,\n 'Keep exactly one: `path` for an HTTP check, or `command` for a check run inside the container.',\n name,\n );\n return undefined;\n }\n if (hasPath) {\n if (role === 'worker') {\n issues.error(\n 'worker-health-needs-command',\n `${path}.path`,\n `Worker \\`${name}\\` has an HTTP health path, but workers do not serve HTTP.`,\n 'Use `command:` with a list that exits 0 when the worker is ready.',\n name,\n );\n return undefined;\n }\n if (typeof health.path !== 'string' || !HEALTH_PATH.test(health.path)) {\n issues.error(\n 'health-invalid',\n `${path}.path`,\n `The health path of \\`${name}\\` must start with \\`/\\` and contain no spaces.`,\n 'Write a path such as `/api/health`.',\n name,\n );\n return undefined;\n }\n if (\n refuseVariables(\n [health.path],\n `${path}.path`,\n `The health path of \\`${name}\\``,\n issues,\n name,\n )\n ) {\n return undefined;\n }\n return { path: health.path };\n }\n if (!isStringList(health.command)) {\n issues.error(\n 'health-invalid',\n `${path}.command`,\n `The health command of \\`${name}\\` must be a list with one argument per item.`,\n 'Write it as a list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"app\", \"doctor\"]`.',\n name,\n );\n return undefined;\n }\n if (\n refuseVariables(\n health.command,\n `${path}.command`,\n `The health command of \\`${name}\\``,\n issues,\n name,\n )\n ) {\n return undefined;\n }\n return { command: [...health.command] };\n}\n\nfunction parseCommand(\n name: string,\n field: 'command' | 'entrypoint',\n value: unknown,\n issues: IssueCollector,\n): string[] | undefined {\n if (value === undefined || value === null) return undefined;\n // Empty is meaningful in Compose, for both fields: `[]` or '' discards what\n // the image declares, and only a missing or null value inherits it.\n const empty =\n (Array.isArray(value) && value.length === 0) ||\n (typeof value === 'string' && value.trim() === '');\n if (empty) return [];\n const path = `services.${name}.${field}`;\n const what = `The \\`${field}\\` of \\`${name}\\``;\n if (isStringList(value)) {\n return refuseVariables(value, path, what, issues, name)\n ? undefined\n : [...value];\n }\n if (typeof value === 'string') {\n if (refuseVariables([value], path, what, issues, name)) return undefined;\n if (PLAIN_COMMAND.test(value.trim())) return value.trim().split(/ +/);\n }\n issues.error(\n 'command-not-list',\n `services.${name}.${field}`,\n `The \\`${field}\\` of \\`${name}\\` uses quoting or shell syntax, or is not text, which Compose and the platform would read differently.`,\n `Write \\`${field}\\` as a list with one argument per item, for example \\`[\"node\", \"build\"]\\`.`,\n name,\n );\n return undefined;\n}\n\ninterface PortScan {\n ports: number[];\n invalid: boolean;\n}\n\nfunction scanPortEntry(\n name: string,\n field: 'ports' | 'expose',\n entry: unknown,\n index: number,\n issues: IssueCollector,\n): number | undefined {\n const path = `services.${name}.${field}[${index}]`;\n const invalid = (reason: string): undefined => {\n issues.error(\n 'ingress-port-invalid',\n path,\n `Port entry \\`${describe(entry)}\\` of \\`${name}\\` ${reason}.`,\n 'Publish one fixed TCP port, for example `\"3000:3000\"`.',\n name,\n );\n return undefined;\n };\n\n if (typeof entry === 'number') {\n return Number.isInteger(entry) && entry > 0 && entry < 65536\n ? entry\n : invalid('is not a valid port number');\n }\n if (typeof entry === 'string') {\n // A published side may be interpolated (`${WEB_PORT:-3000}:3000`); only\n // the container side has to be a literal the platform can read.\n const withoutVariables = entry.replace(INTERPOLATION, '\\u0000');\n const [address, protocol] = withoutVariables.split('/');\n if (protocol !== undefined && protocol.toLowerCase() !== 'tcp') {\n return invalid('is not TCP');\n }\n const container = address.split(':').at(-1) ?? '';\n if (!/^\\d+$/.test(container)) {\n return invalid(\n container.includes('-')\n ? 'is a port range'\n : 'does not name a fixed container port',\n );\n }\n const port = Number(container);\n return port > 0 && port < 65536\n ? port\n : invalid('is not a valid port number');\n }\n if (isRecord(entry)) {\n if (entry.mode !== undefined && entry.mode !== 'ingress') {\n issues.error(\n 'host-network',\n path,\n `Service \\`${name}\\` publishes a port in \\`${describe(entry.mode)}\\` mode, which binds it to the network of the machine it runs on.`,\n 'Remove the `mode` line. The platform routes traffic to the container for you.',\n name,\n );\n return undefined;\n }\n if (\n entry.protocol !== undefined &&\n !(\n typeof entry.protocol === 'string' &&\n entry.protocol.toLowerCase() === 'tcp'\n )\n ) {\n return invalid('is not TCP');\n }\n const target =\n typeof entry.target === 'number'\n ? entry.target\n : typeof entry.target === 'string' && /^\\d+$/.test(entry.target)\n ? Number(entry.target)\n : Number.NaN;\n return Number.isInteger(target) && target > 0 && target < 65536\n ? target\n : invalid('does not name a fixed container port in `target`');\n }\n return invalid('is not a port');\n}\n\nfunction scanPorts(\n name: string,\n field: 'ports' | 'expose',\n value: unknown,\n issues: IssueCollector,\n): PortScan {\n if (value === undefined || value === null) {\n return { ports: [], invalid: false };\n }\n if (!Array.isArray(value)) {\n issues.error(\n 'ingress-port-invalid',\n `services.${name}.${field}`,\n `\\`${field}\\` of \\`${name}\\` must be a list.`,\n 'Publish one fixed TCP port, for example `ports: [\"3000:3000\"]`.',\n name,\n );\n return { ports: [], invalid: true };\n }\n const before = issues.errors.length;\n const ports = new Set<number>();\n value.forEach((entry, index) => {\n const port = scanPortEntry(name, field, entry, index, issues);\n if (port !== undefined) ports.add(port);\n });\n return { ports: [...ports], invalid: issues.errors.length > before };\n}\n\nfunction isHostPath(source: string): boolean {\n return (\n source.startsWith('.') ||\n source.startsWith('/') ||\n source.startsWith('~') ||\n source.includes('$') ||\n source.includes('\\\\') ||\n /^[A-Za-z]:/.test(source)\n );\n}\n\nfunction scanVolumes(\n name: string,\n service: UnknownRecord,\n declared: UnknownRecord,\n issues: IssueCollector,\n): ComposeDeploymentVolume[] {\n const volumes: ComposeDeploymentVolume[] = [];\n const notDeclared = (path: string, what: string): void => {\n issues.error(\n 'volume-not-declared',\n path,\n `Service \\`${name}\\` ${what}. The platform only keeps data in volumes the file declares.`,\n 'Declare a named volume under top-level `volumes:` and mount it as `name:/path/in/container`. Files the app needs belong in its image.',\n name,\n );\n };\n const useNamed = (\n path: string,\n source: string,\n target: string,\n readOnly: boolean,\n ): void => {\n if (!Object.hasOwn(declared, source)) {\n notDeclared(\n path,\n `mounts the volume \\`${source}\\`, which is not declared in this file`,\n );\n return;\n }\n const definition = declared[source];\n if (isRecord(definition)) {\n const external =\n definition.external !== undefined && definition.external !== false;\n const customDriver =\n definition.driver !== undefined && definition.driver !== 'local';\n if (external || customDriver || definition.driver_opts !== undefined) {\n issues.error(\n 'volume-not-plain',\n `volumes.${source}`,\n `Volume \\`${source}\\` is external or uses driver options, so its contents live somewhere this file does not describe.`,\n 'Declare it as a plain named volume (just `name:` with nothing under it).',\n name,\n );\n return;\n }\n }\n if (\n refuseVariables(\n [target],\n path,\n `The mount path of volume \\`${source}\\` in \\`${name}\\``,\n issues,\n name,\n )\n ) {\n return;\n }\n volumes.push({ name: source, target, readOnly });\n };\n\n if (\n Array.isArray(service.volumes_from)\n ? service.volumes_from.length > 0\n : service.volumes_from !== undefined && service.volumes_from !== null\n ) {\n notDeclared(\n `services.${name}.volumes_from`,\n \"borrows another container's volumes with `volumes_from`\",\n );\n }\n\n const entries = service.volumes;\n if (entries === undefined || entries === null) return volumes;\n if (!Array.isArray(entries)) {\n notDeclared(\n `services.${name}.volumes`,\n 'has a `volumes` entry that is not a list',\n );\n return volumes;\n }\n entries.forEach((entry, index) => {\n const path = `services.${name}.volumes[${index}]`;\n if (typeof entry === 'string') {\n // A drive letter or a backslash is a Windows host path; splitting it\n // on `:` would mistake the drive letter for a volume name.\n if (/^[A-Za-z]:[\\\\/]/.test(entry) || entry.includes('\\\\')) {\n notDeclared(\n path,\n `mounts \\`${describe(entry)}\\` from the machine it runs on (a bind mount)`,\n );\n return;\n }\n const [source, target, mode] = entry.split(':');\n if (target === undefined) {\n notDeclared(path, `mounts an unnamed volume at \\`${entry}\\``);\n } else if (isHostPath(source)) {\n notDeclared(\n path,\n `mounts \\`${source}\\` from the machine it runs on (a bind mount)`,\n );\n } else {\n useNamed(path, source, target, (mode ?? '').split(',').includes('ro'));\n }\n return;\n }\n if (isRecord(entry)) {\n const type = entry.type ?? 'volume';\n if (type === 'tmpfs') return;\n if (type !== 'volume') {\n notDeclared(\n path,\n `uses a \\`${describe(type)}\\` mount, which reads from the machine it runs on`,\n );\n return;\n }\n if (typeof entry.source !== 'string' || entry.source.length === 0) {\n notDeclared(path, 'mounts an unnamed volume');\n return;\n }\n if (typeof entry.target !== 'string' || entry.target.length === 0) {\n notDeclared(path, 'has a volume entry with no `target` path');\n return;\n }\n useNamed(\n path,\n entry.source,\n entry.target,\n entry.read_only !== undefined && entry.read_only !== false,\n );\n return;\n }\n notDeclared(path, 'has a volume entry that is not a mount');\n });\n return volumes;\n}\n\ninterface RoleService {\n name: string;\n role: XHappyVerticalRole;\n definition: UnknownRecord;\n health?: ComposeDeploymentHealth;\n}\n\nfunction resolveImage(\n entry: RoleService,\n options: ComposeDeploymentOptions,\n stage: ComposeDeploymentStage,\n issues: IssueCollector,\n): string | undefined {\n const { name, definition } = entry;\n const declared =\n typeof definition.image === 'string' && definition.image.length > 0\n ? definition.image\n : undefined;\n const hasBuild = definition.build !== undefined && definition.build !== null;\n // Own keys only: a service may be called `constructor` or `toString`.\n const supplied =\n options.images && Object.hasOwn(options.images, name)\n ? options.images[name]\n : undefined;\n\n if (declared === undefined && !hasBuild) {\n issues.error(\n 'service-no-image',\n `services.${name}`,\n `Service \\`${name}\\` has neither \\`image\\` nor \\`build\\`, so nothing can run it.`,\n 'Add `build: .` to build it locally, or `image:` with the image to run.',\n name,\n );\n }\n if (stage === 'declare') {\n // Informational at this stage: carry the image only as literal text.\n const image = supplied ?? declared;\n return image !== undefined && isLiteral(image) ? image : undefined;\n }\n\n const effective = supplied ?? declared;\n if (effective !== undefined && DIGEST_IMAGE.test(effective)) {\n return effective;\n }\n issues.error(\n 'image-not-digest',\n `services.${name}.image`,\n effective === undefined\n ? `Service \\`${name}\\` is only built locally. The platform deploys an image that CI already built and pushed; it never runs \\`build:\\`.`\n : `The image of \\`${name}\\` (\\`${effective}\\`) is a tag, which can change after it was tested. The platform deploys exact image digests only.`,\n `Supply the digest CI pushed for \\`${name}\\`, in the form \\`registry/name@sha256:\\` followed by 64 hex characters.`,\n name,\n );\n return undefined;\n}\n\nfunction checkRoleService(\n entry: RoleService,\n declaredVolumes: UnknownRecord,\n options: ComposeDeploymentOptions,\n stage: ComposeDeploymentStage,\n issues: IssueCollector,\n): ComposeDeploymentWorkload | undefined {\n const { name, role, definition } = entry;\n const before = issues.errors.length;\n\n if (definition.extends !== undefined) {\n issues.error(\n 'not-self-contained',\n `services.${name}.extends`,\n `Service \\`${name}\\` takes part of its definition from another service with \\`extends\\`, so what it runs is not written here.`,\n 'Write the service out in full. The platform reads each service as written, in this one file.',\n name,\n );\n }\n\n const image = resolveImage(entry, options, stage, issues);\n\n // Fail closed: Compose reads YAML 1.1 booleans (`yes`, `on`), which a\n // YAML 1.2 parser hands over as strings. Anything but an explicit false is\n // treated as a request for privileged mode.\n if (\n definition.privileged !== undefined &&\n definition.privileged !== null &&\n definition.privileged !== false\n ) {\n issues.error(\n 'privileged',\n `services.${name}.privileged`,\n `Service \\`${name}\\` sets \\`privileged\\`. Privileged mode gives a container control of the machine it runs on, and Compose accepts more spellings of \"yes\" than can be told apart here.`,\n 'Remove the `privileged` line. The platform never runs privileged containers.',\n name,\n );\n }\n\n if (definition.network_mode === 'host') {\n issues.error(\n 'host-network',\n `services.${name}.network_mode`,\n `Service \\`${name}\\` uses the host's network instead of its own.`,\n 'Remove `network_mode: host`. Services reach each other by service name, and the platform routes outside traffic to the web service.',\n name,\n );\n }\n\n const volumes = scanVolumes(name, definition, declaredVolumes, issues);\n const entrypoint = parseCommand(\n name,\n 'entrypoint',\n definition.entrypoint,\n issues,\n );\n const command = parseCommand(name, 'command', definition.command, issues);\n\n let port: number | undefined;\n const publishesNothing =\n definition.ports === undefined ||\n definition.ports === null ||\n (Array.isArray(definition.ports) && definition.ports.length === 0);\n const published =\n role === 'web'\n ? scanPorts(name, 'ports', definition.ports, issues)\n : { ports: [], invalid: false };\n if (role === 'web') {\n const exposed =\n published.ports.length === 0 && !published.invalid\n ? scanPorts(name, 'expose', definition.expose, issues)\n : { ports: [], invalid: false };\n const ports = published.ports.length > 0 ? published.ports : exposed.ports;\n if (!published.invalid && !exposed.invalid && ports.length !== 1) {\n issues.error(\n 'ingress-port-count',\n `services.${name}.ports`,\n ports.length === 0\n ? `Web service \\`${name}\\` publishes no port, so there is nothing to send visitors to.`\n : `Web service \\`${name}\\` publishes ${ports.length} ports (${ports.join(', ')}). The platform routes visitors to exactly one.`,\n 'Publish exactly one port, the one the app listens on, for example `ports: [\"3000:3000\"]`.',\n name,\n );\n }\n port = ports[0];\n } else if (!publishesNothing) {\n issues.error(\n 'worker-publishes-port',\n `services.${name}.ports`,\n `Worker \\`${name}\\` publishes a port, but only the web service receives traffic.`,\n 'Remove `ports` from the worker, or give the service `role: web` if it is the one visitors reach.',\n name,\n );\n }\n\n if (issues.errors.length > before || entry.health === undefined) {\n return undefined;\n }\n return {\n name,\n role,\n ...(image !== undefined ? { image } : {}),\n ...(entrypoint ? { entrypoint } : {}),\n ...(command ? { command } : {}),\n ...(port !== undefined ? { port } : {}),\n health: entry.health,\n volumes,\n };\n}\n\n/**\n * Validate a parsed Compose document as a deployment declaration.\n *\n * Errors are things the platform refuses. Warnings never block: they report\n * services that only run locally. `declaration` is present when there are no\n * errors.\n */\nexport function validateComposeDeployment(\n document: unknown,\n options: ComposeDeploymentOptions = {},\n): ComposeDeploymentResult {\n const issues = new IssueCollector();\n const stage = options.stage ?? 'declare';\n const finish = (\n declaration?: ComposeDeploymentDeclaration,\n ): ComposeDeploymentResult => ({\n ok: issues.errors.length === 0,\n errors: issues.errors,\n warnings: issues.warnings,\n ...(issues.errors.length === 0 && declaration ? { declaration } : {}),\n });\n\n if (!isRecord(document)) {\n issues.error(\n 'document-invalid',\n '',\n 'This is not a Compose file: the top level must be a mapping with `services`.',\n 'Check that the file is valid YAML and starts with top-level keys such as `services:`.',\n );\n return finish();\n }\n\n // A `<<` key anywhere means the caller parsed without YAML merge keys, so\n // some mapping is missing whatever its anchor carries: a port's protocol, a\n // volume's driver, a whole service. Nothing below can be trusted, so stop.\n const mergeKey = findMergeKey(document);\n if (mergeKey !== undefined) {\n issues.error(\n 'merge-key-unresolved',\n mergeKey,\n 'The file still contains a YAML merge key (`<<`), so the part of it that comes from an anchor was not read.',\n 'Parse the file with YAML merge keys enabled, as Compose does (`smrt deploy:check` does this for you).',\n );\n return finish();\n }\n\n if (document.include !== undefined) {\n issues.error(\n 'not-self-contained',\n 'include',\n 'The file pulls in other Compose files with `include`.',\n 'Put every service in this one file. The platform reads this file and nothing else.',\n );\n }\n\n const application = parseApplication(document, issues);\n\n const services = document.services;\n if (!isRecord(services) || Object.keys(services).length === 0) {\n issues.error(\n 'services-missing',\n 'services',\n 'The file declares no services.',\n 'Add your application under `services:`, with at least a web service.',\n );\n return finish();\n }\n const declaredVolumes = isRecord(document.volumes) ? document.volumes : {};\n\n const roleServices: RoleService[] = [];\n const bindings: ComposeDeploymentBinding[] = [];\n const localOnly: string[] = [];\n\n for (const [name, definition] of Object.entries(services)) {\n if (!isRecord(definition)) {\n issues.error(\n 'service-invalid',\n `services.${name}`,\n `Service \\`${name}\\` is empty or not a mapping.`,\n 'Give it an `image` or `build` and the settings it needs, or remove it.',\n name,\n );\n continue;\n }\n const annotationPath = `services.${name}.${X_HAPPYVERTICAL_KEY}`;\n const annotation = definition[X_HAPPYVERTICAL_KEY];\n if (annotation === undefined) {\n localOnly.push(name);\n continue;\n }\n if (!isRecord(annotation)) {\n issues.error(\n 'annotation-invalid',\n annotationPath,\n `The \\`${X_HAPPYVERTICAL_KEY}\\` block of \\`${name}\\` must be a mapping.`,\n 'Write `role: web` or `role: worker` with a `health` check, or `binding:` with the platform service it stands in for.',\n name,\n );\n continue;\n }\n const extra = unknownFields(annotation, SERVICE_FIELDS);\n if (extra.length > 0) {\n issues.error(\n 'annotation-invalid',\n `${annotationPath}.${extra[0]}`,\n `\\`${extra[0]}\\` is not a field of a service annotation.`,\n `Remove it or fix the spelling. A service takes ${quoteList(SERVICE_FIELDS)}.`,\n name,\n );\n continue;\n }\n const hasRole = annotation.role !== undefined;\n const hasBinding = annotation.binding !== undefined;\n if (hasRole && hasBinding) {\n issues.error(\n 'role-and-binding',\n annotationPath,\n `Service \\`${name}\\` has both \\`role\\` and \\`binding\\`. A service is either part of your application or a stand-in for a platform service.`,\n 'Keep `role` for something you build and run, or `binding` for something the platform provides.',\n name,\n );\n continue;\n }\n if (!hasRole && !hasBinding) {\n issues.error(\n 'annotation-invalid',\n annotationPath,\n `The \\`${X_HAPPYVERTICAL_KEY}\\` block of \\`${name}\\` says neither what the service is nor what it stands in for.`,\n 'Add `role: web`, `role: worker`, or `binding:`. Remove the block if the service is only for local use.',\n name,\n );\n continue;\n }\n if (!SERVICE_NAME.test(name)) {\n issues.error(\n 'service-name-invalid',\n `services.${name}`,\n `The service name \\`${name}\\` cannot be used as a platform resource name.`,\n 'Rename it using lowercase letters, digits and hyphens, starting with a letter, at most 31 characters.',\n name,\n );\n }\n\n if (hasBinding) {\n const kind = annotation.binding;\n if (\n typeof kind !== 'string' ||\n !(X_HAPPYVERTICAL_BINDINGS as readonly string[]).includes(kind)\n ) {\n issues.error(\n 'binding-unknown',\n `${annotationPath}.binding`,\n `\\`${describe(kind)}\\` is not a platform service this contract knows.`,\n `Set \\`binding\\` to one of: ${quoteList(X_HAPPYVERTICAL_BINDINGS)}.`,\n name,\n );\n continue;\n }\n if (annotation.health !== undefined) {\n issues.error(\n 'binding-with-health',\n `${annotationPath}.health`,\n `Binding \\`${name}\\` has a \\`health\\` check, but the platform runs its own service in place of this container.`,\n 'Remove `health` from the annotation. A Compose `healthcheck:` on the service is fine for local use.',\n name,\n );\n }\n const hasImage =\n typeof definition.image === 'string' && definition.image.length > 0;\n const hasBuild =\n definition.build !== undefined && definition.build !== null;\n if (!hasImage && !hasBuild) {\n issues.error(\n 'binding-no-local-image',\n `services.${name}.image`,\n `Binding \\`${name}\\` has no local image, so the stack cannot run anywhere the platform is not providing ${kind}.`,\n 'Add the image you run locally, for example `image: postgres:18-alpine`, so the file stays a complete working stack on its own.',\n name,\n );\n }\n const duplicate = bindings.find((binding) => binding.kind === kind);\n if (duplicate) {\n issues.error(\n 'binding-duplicate',\n `${annotationPath}.binding`,\n `Services \\`${duplicate.name}\\` and \\`${name}\\` both stand in for \\`${kind}\\`. Version 1 binds each platform service once.`,\n `Keep one \\`${kind}\\` binding.`,\n name,\n );\n continue;\n }\n bindings.push({ name, kind: kind as XHappyVerticalBinding });\n continue;\n }\n\n const role = annotation.role;\n if (\n typeof role !== 'string' ||\n !(X_HAPPYVERTICAL_ROLES as readonly string[]).includes(role)\n ) {\n issues.error(\n 'role-unknown',\n `${annotationPath}.role`,\n `\\`${describe(role)}\\` is not a role.`,\n `Set \\`role\\` to one of: ${quoteList(X_HAPPYVERTICAL_ROLES)}.`,\n name,\n );\n continue;\n }\n roleServices.push({\n name,\n role: role as XHappyVerticalRole,\n definition,\n health: parseHealth(\n name,\n role as XHappyVerticalRole,\n annotation.health,\n issues,\n ),\n });\n }\n\n const webServices = roleServices.filter((entry) => entry.role === 'web');\n if (webServices.length !== 1) {\n issues.error(\n 'web-service-count',\n 'services',\n webServices.length === 0\n ? 'No service has `role: web`, so there is nothing for visitors to reach.'\n : `${webServices.length} services have \\`role: web\\` (${quoteList(webServices.map((entry) => entry.name))}). The platform routes visitors to exactly one.`,\n 'Give exactly one service `role: web`. Anything else you run is `role: worker`.',\n );\n }\n\n const workloads: ComposeDeploymentWorkload[] = [];\n for (const entry of roleServices) {\n const workload = checkRoleService(\n entry,\n declaredVolumes,\n options,\n stage,\n issues,\n );\n if (workload) workloads.push(workload);\n }\n\n for (const name of Object.keys(options.images ?? {})) {\n if (!roleServices.some((entry) => entry.name === name)) {\n issues.error(\n 'image-for-unknown-service',\n `services.${name}`,\n `An image digest was supplied for \\`${name}\\`, which is not a web or worker service in this file.`,\n `Supply digests only for: ${quoteList(roleServices.map((entry) => entry.name))}.`,\n name,\n );\n }\n }\n\n const migrateService = application.migrateService ?? webServices[0]?.name;\n if (\n application.migrateService !== undefined &&\n !roleServices.some((entry) => entry.name === application.migrateService)\n ) {\n issues.error(\n 'migrate-service-not-role',\n `${X_HAPPYVERTICAL_KEY}.migrate.service`,\n `\\`migrate.service\\` names \\`${application.migrateService}\\`, which is not a web or worker service in this file. The migration ships inside one of your application images.`,\n `Name one of: ${quoteList(roleServices.map((entry) => entry.name))}, or remove the line to use the web service.`,\n );\n }\n\n for (const name of localOnly) {\n issues.warning(\n 'local-only-service',\n `services.${name}`,\n `Service \\`${name}\\` has no \\`${X_HAPPYVERTICAL_KEY}\\` annotation. It runs on your machine only; the platform will not run it.`,\n 'Nothing to do if that is intended. Otherwise give it `role: web`, `role: worker` or a `binding`.',\n name,\n );\n }\n\n if (\n issues.errors.length > 0 ||\n application.preset === undefined ||\n application.migrateCommand === undefined ||\n migrateService === undefined\n ) {\n return finish();\n }\n\n const migrateImage = workloads.find(\n (workload) => workload.name === migrateService,\n )?.image;\n return finish({\n version: X_HAPPYVERTICAL_VERSION,\n preset: application.preset,\n stage,\n ...(typeof document.name === 'string' &&\n document.name.length > 0 &&\n isLiteral(document.name)\n ? { name: document.name }\n : {}),\n ...(application.domain !== undefined ? { domain: application.domain } : {}),\n migrate: {\n service: migrateService,\n command: application.migrateCommand,\n ...(migrateImage !== undefined ? { image: migrateImage } : {}),\n },\n workloads,\n bindings,\n localOnly,\n });\n}\n\nfunction formatIssue(issue: ComposeDeploymentIssue, index: number): string {\n const where = issue.path ? `${issue.path}: ` : '';\n return `${index + 1}. ${where}${issue.message}\\n Fix: ${issue.fix}`;\n}\n\n/** Render a validation result as plain text for a terminal or a log. */\nexport function formatComposeDeploymentReport(\n result: ComposeDeploymentResult,\n): string {\n const lines: string[] = [];\n if (result.ok) {\n lines.push('The deployment declaration is valid.');\n const declaration = result.declaration;\n if (declaration) {\n const describe = (workload: ComposeDeploymentWorkload): string =>\n workload.port !== undefined\n ? `${workload.name} (${workload.role}, port ${workload.port})`\n : `${workload.name} (${workload.role})`;\n lines.push(\n `Preset: ${declaration.preset}`,\n `Runs: ${declaration.workloads.map(describe).join(', ')}`,\n `Migration: ${declaration.migrate.command.join(' ')} (in the ${declaration.migrate.service} image)`,\n `Platform services: ${\n declaration.bindings.length > 0\n ? declaration.bindings\n .map((binding) => `${binding.kind} (local: ${binding.name})`)\n .join(', ')\n : 'none'\n }`,\n );\n if (declaration.domain) lines.push(`Domain: ${declaration.domain}`);\n }\n } else {\n const count = result.errors.length;\n lines.push(\n `The deployment declaration has ${count} problem${count === 1 ? '' : 's'}.`,\n '',\n ...result.errors.map(formatIssue),\n );\n }\n if (result.warnings.length > 0) {\n lines.push(\n '',\n `Runs only on your machine (the platform will not run it): ${result.warnings\n .map((warning) => warning.service ?? warning.path)\n .join(', ')}`,\n );\n }\n return lines.join('\\n');\n}\n","/**\n * A synchronous SHA-256 with no platform dependency, so the deployment entry\n * stays browser-safe (`node:crypto` is not available there and `crypto.subtle`\n * is asynchronous). It exists only to derive stable release identifiers from\n * public image digests; it is not a place to hash secrets.\n */\n\nconst K = new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n]);\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits));\n}\n\n/** Hex SHA-256 of the UTF-8 encoding of `text`. */\nexport function sha256Hex(text: string): string {\n const bytes = new TextEncoder().encode(text);\n const padded = new Uint8Array(((bytes.length + 9 + 63) >> 6) << 6);\n padded.set(bytes);\n padded[bytes.length] = 0x80;\n const view = new DataView(padded.buffer);\n const bitLength = bytes.length * 8;\n view.setUint32(padded.length - 8, Math.floor(bitLength / 0x100000000));\n view.setUint32(padded.length - 4, bitLength >>> 0);\n\n const h = new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19,\n ]);\n const w = new Uint32Array(64);\n for (let offset = 0; offset < padded.length; offset += 64) {\n for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);\n const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);\n w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;\n }\n let [a, b, c, d, e, f, g, hh] = h;\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const choose = (e & f) ^ (~e & g);\n const t1 = (hh + s1 + choose + K[i] + w[i]) | 0;\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (s0 + majority) | 0;\n hh = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n h[0] += a;\n h[1] += b;\n h[2] += c;\n h[3] += d;\n h[4] += e;\n h[5] += f;\n h[6] += g;\n h[7] += hh;\n }\n return Array.from(h, (word) => word.toString(16).padStart(8, '0')).join('');\n}\n","/**\n * Hosted rendering of the compose deployment contract: turn a declaration\n * resolved at the `deploy` stage into a `HostedApp`\n * (`hosting.happyvertical.com/v1alpha1`) for the platform operator's `smrt`\n * preset. It is the hosted counterpart of `renderSmrtAppChartValues`: both\n * start from the same declaration.\n *\n * The declaration says what the application is. What it may have is the\n * platform's decision, so the caller passes that in as {@link HostedAppEntitlements}\n * (approved bindings, verified domains, volume size) and gets either a\n * manifest or structured rejections that are safe to show a customer. This\n * module is pure: no I/O, no cluster access, browser-safe.\n */\n\nimport {\n type ComposeDeploymentDeclaration,\n type ComposeDeploymentIssue,\n validateComposeDeployment,\n} from './compose-contract.js';\nimport { sha256Hex } from './sha256.js';\n\nexport const HOSTED_APP_API_VERSION = 'hosting.happyvertical.com/v1alpha1';\nexport const HOSTED_APP_KIND = 'HostedApp';\nexport const HOSTED_APP_PRESET = 'smrt';\n/** Longest `metadata.name` the operator accepts. */\nexport const HOSTED_APP_NAME_MAX_LENGTH = 40;\n\nexport const HOSTED_APP_TIERS = ['T1', 'T2', 'T3'] as const;\nexport type HostedAppTier = (typeof HOSTED_APP_TIERS)[number];\n\nexport const HOSTED_APP_WORKER_ROLES = [\n 'background',\n 'schedule',\n 'task',\n] as const;\nexport type HostedAppWorkerRole = (typeof HOSTED_APP_WORKER_ROLES)[number];\n\n/** The `HostedApp` fields this module writes. The operator's CRD is the authority. */\nexport interface HostedAppManifest {\n apiVersion: typeof HOSTED_APP_API_VERSION;\n kind: typeof HOSTED_APP_KIND;\n metadata: { name: string; labels: Record<string, string> };\n spec: {\n poolRef: string;\n tier: HostedAppTier;\n resourceClass?: string;\n release: { id: string; commit?: string };\n domains?: string[];\n preset: {\n name: typeof HOSTED_APP_PRESET;\n images: Record<string, string>;\n parameters: Record<string, string>;\n };\n bindings?: Array<{ name: string; type: string }>;\n };\n}\n\n/**\n * A reason a request cannot be honoured. The message is written for the\n * person who owns the compose file and never carries internals or secrets.\n */\nexport interface HostedAppRejection {\n code: string;\n message: string;\n}\n\n/** Where and how the app is hosted. Chosen by the platform, not the declaration. */\nexport interface HostedAppPlacement {\n /** `metadata.name`: a DNS label of at most {@link HOSTED_APP_NAME_MAX_LENGTH} characters. */\n name: string;\n poolRef: string;\n tier: HostedAppTier;\n resourceClass?: string;\n /** Extra `metadata.labels`, for example the id a collector discovers apps by. */\n labels?: Record<string, string>;\n}\n\n/** What this app may have. The caller derives these from its own policy. */\nexport interface HostedAppEntitlements {\n /** Binding kinds the app may use. A declared binding outside this list is rejected. */\n bindings: readonly string[];\n /** Custom domains verified for the app. A declared domain outside this list is rejected. */\n domains?: readonly string[];\n /**\n * The host the platform derives for the app. A declared domain equal to it\n * is accepted and not written to `spec.domains`, which lists only custom\n * domains.\n */\n platformHost?: string;\n /**\n * Size of every declared volume, a Kubernetes quantity such as `5Gi`. The\n * declaration carries none. Required when the declaration has a volume.\n */\n volumeSize?: string;\n}\n\n/** Preset parameters the declaration does not carry but the caller may set. */\nexport interface HostedAppPresetOptions {\n /** `background` (default), `schedule` or `task`. Applies when there is a worker. */\n workerRole?: HostedAppWorkerRole;\n /** `SMRT_APP_ENVIRONMENT`. */\n environment?: string;\n /** `SMRT_RUNTIME_PROFILE`. */\n runtimeProfile?: string;\n}\n\nexport interface ComposeHostedAppInput {\n /** The parsed compose document, read at `commit`. Untrusted. */\n document: unknown;\n /** The commit the document was read at, 7 to 64 hex digits. */\n commit: string;\n /**\n * The image digests CI built, by Compose service name\n * (`ghcr.io/acme/app@sha256:...`).\n */\n digests: Record<string, string>;\n app: HostedAppPlacement;\n entitlements: HostedAppEntitlements;\n preset?: HostedAppPresetOptions;\n}\n\nexport type ComposeHostedAppResult =\n | {\n ok: true;\n manifest: HostedAppManifest;\n declaration: ComposeDeploymentDeclaration;\n warnings: HostedAppRejection[];\n }\n | { ok: false; rejections: HostedAppRejection[] };\n\nconst COMMIT_PATTERN = /^[a-f0-9]{7,64}$/;\nconst DNS_LABEL = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;\nconst QUANTITY = /^[1-9][0-9]*(Ki|Mi|Gi|Ti|k|M|G|T)?$/;\nconst LABEL_KEY =\n /^([a-z0-9.-]{1,253}\\/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/;\nconst LABEL_VALUE = /^([A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$/;\n\n/** Deterministic, so a repeated CI call for the same build is the same release. */\nexport function hostedAppReleaseId(\n commit: string,\n digests: Record<string, string>,\n): string {\n const hash = sha256Hex(\n JSON.stringify(\n Object.entries(digests).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),\n ),\n ).slice(0, 8);\n return `rel-${commit.slice(0, 12)}-${hash}`;\n}\n\n/** Whether `commit` is a spelling {@link composeHostedApp} accepts. */\nexport function isHostedAppCommit(commit: unknown): commit is string {\n return typeof commit === 'string' && COMMIT_PATTERN.test(commit);\n}\n\nfunction issueToRejection(issue: ComposeDeploymentIssue): HostedAppRejection {\n return { code: issue.code, message: `${issue.message} ${issue.fix}`.trim() };\n}\n\nfunction reject(code: string, message: string): ComposeHostedAppResult {\n return { ok: false, rejections: [{ code, message }] };\n}\n\nfunction labelProblem(labels: unknown): string | undefined {\n if (labels === undefined) return undefined;\n if (typeof labels !== 'object' || labels === null || Array.isArray(labels)) {\n return 'The labels must be an object of strings.';\n }\n for (const [key, value] of Object.entries(labels)) {\n if (\n !LABEL_KEY.test(key) ||\n typeof value !== 'string' ||\n !LABEL_VALUE.test(value)\n ) {\n return 'A label is not a valid Kubernetes label.';\n }\n }\n return undefined;\n}\n\n/**\n * Compose the `HostedApp` for one release: validate the declaration at the\n * `deploy` stage, intersect it with the entitlements, and emit the custom\n * resource the operator's `smrt` preset accepts. Never throws on a bad\n * document or bad inputs; every refusal is a rejection.\n */\nexport function composeHostedApp(\n input: ComposeHostedAppInput,\n): ComposeHostedAppResult {\n const { app, entitlements, commit, digests } = input;\n\n if (!isHostedAppCommit(commit)) {\n return reject('commit-invalid', 'The commit must be 7 to 64 hex digits.');\n }\n if (\n typeof app.name !== 'string' ||\n !DNS_LABEL.test(app.name) ||\n app.name.length > HOSTED_APP_NAME_MAX_LENGTH\n ) {\n return reject(\n 'platform-name-invalid',\n `The app name must be a DNS label of at most ${HOSTED_APP_NAME_MAX_LENGTH} characters.`,\n );\n }\n if (!HOSTED_APP_TIERS.includes(app.tier)) {\n return reject(\n 'tier-invalid',\n `The tier must be one of: ${HOSTED_APP_TIERS.join(', ')}.`,\n );\n }\n if (typeof app.poolRef !== 'string' || app.poolRef === '') {\n return reject('pool-invalid', 'The app has no pool to run in.');\n }\n const labelIssue = labelProblem(app.labels);\n if (labelIssue) return reject('labels-invalid', labelIssue);\n const workerRole = input.preset?.workerRole;\n if (\n workerRole !== undefined &&\n !HOSTED_APP_WORKER_ROLES.includes(workerRole)\n ) {\n return reject(\n 'worker-role-invalid',\n `The worker role must be one of: ${HOSTED_APP_WORKER_ROLES.join(', ')}.`,\n );\n }\n\n const validated = validateComposeDeployment(input.document, {\n stage: 'deploy',\n images: digests,\n });\n const warnings = validated.warnings.map(issueToRejection);\n if (!validated.ok || !validated.declaration) {\n return { ok: false, rejections: validated.errors.map(issueToRejection) };\n }\n const declaration = validated.declaration;\n const rejections: HostedAppRejection[] = [];\n\n // The preset knows one web and at most one worker.\n const workers = declaration.workloads.filter(\n (workload) => workload.role === 'worker',\n );\n if (workers.length > 1) {\n rejections.push({\n code: 'multiple-workers-unsupported',\n message: `The hosted preset runs one worker, and this file has ${workers.length} (${workers.map((worker) => worker.name).join(', ')}). Merge them into one worker service.`,\n });\n }\n\n // Entitlement intersection: every binding the app asks for must be covered.\n const approved = new Set(entitlements.bindings);\n for (const binding of declaration.bindings) {\n if (!approved.has(binding.kind)) {\n rejections.push({\n code: 'binding-not-entitled',\n message: `This app asks for a ${binding.kind} binding, which is not approved for it. Ask the platform operator to approve it or remove it from the compose file.`,\n });\n }\n }\n\n // Domains: the platform host is derived; any other must be verified.\n const domains: string[] = [];\n if (declaration.domain && declaration.domain !== entitlements.platformHost) {\n if (entitlements.domains?.includes(declaration.domain)) {\n domains.push(declaration.domain);\n } else {\n rejections.push({\n code: 'domain-not-verified',\n message: `The domain ${declaration.domain} has not been verified for this app. Point its DNS at the platform and verify it first.`,\n });\n }\n }\n\n const hasVolume = declaration.workloads.some(\n (workload) => workload.volumes.length > 0,\n );\n if (hasVolume) {\n if (entitlements.volumeSize === undefined) {\n rejections.push({\n code: 'volume-not-entitled',\n message:\n 'This app declares a data volume, but no volume size is approved for it. Ask the platform operator or remove the volume from the compose file.',\n });\n } else if (!QUANTITY.test(entitlements.volumeSize)) {\n rejections.push({\n code: 'volume-size-invalid',\n message:\n 'The approved volume size is not a valid quantity such as 5Gi.',\n });\n }\n }\n\n const images: Record<string, string> = {};\n for (const workload of declaration.workloads) {\n if (workload.image !== undefined) images[workload.role] = workload.image;\n }\n if (!images.web) {\n rejections.push({\n code: 'web-image-missing',\n message: 'The release has no web image digest.',\n });\n }\n\n // The preset takes one argv per workload and a web health path. It cannot\n // say \"run nothing\" (Compose `entrypoint: []`/`command: []` discards the\n // image's own command, which an empty argv would silently restore) and it\n // has no web health command, so refuse both rather than drop them.\n for (const workload of declaration.workloads) {\n const declared =\n workload.entrypoint !== undefined || workload.command !== undefined;\n const argv = [...(workload.entrypoint ?? []), ...(workload.command ?? [])];\n if (declared && argv.length === 0) {\n rejections.push({\n code: 'startup-command-unsupported',\n message: `The ${workload.name} service discards its image's command (empty entrypoint/command), which the hosted preset cannot represent. Declare the command to run, or remove the empty entrypoint/command.`,\n });\n }\n if (workload.role === 'web' && 'command' in workload.health) {\n rejections.push({\n code: 'web-health-command-unsupported',\n message: `The ${workload.name} service declares a command health check, but the hosted preset only supports a web health path. Declare health.path instead.`,\n });\n }\n }\n\n if (rejections.length > 0) return { ok: false, rejections };\n\n const bindings = declaration.bindings.map((binding) => ({\n name: binding.name,\n type: binding.kind,\n }));\n const manifest: HostedAppManifest = {\n apiVersion: HOSTED_APP_API_VERSION,\n kind: HOSTED_APP_KIND,\n metadata: { name: app.name, labels: { ...(app.labels ?? {}) } },\n spec: {\n poolRef: app.poolRef,\n tier: app.tier,\n ...(app.resourceClass ? { resourceClass: app.resourceClass } : {}),\n release: { id: hostedAppReleaseId(commit, digests), commit },\n ...(domains.length > 0 ? { domains } : {}),\n preset: {\n name: HOSTED_APP_PRESET,\n images,\n parameters: presetParameters(\n declaration,\n entitlements.volumeSize,\n input.preset,\n ),\n },\n ...(bindings.length > 0 ? { bindings } : {}),\n },\n };\n return { ok: true, manifest, declaration, warnings };\n}\n\nfunction presetParameters(\n declaration: ComposeDeploymentDeclaration,\n volumeSize: string | undefined,\n options: HostedAppPresetOptions | undefined,\n): Record<string, string> {\n const parameters: Record<string, string> = {\n migrateCommand: JSON.stringify(declaration.migrate.command),\n };\n const migrateRole = declaration.workloads.find(\n (workload) => workload.name === declaration.migrate.service,\n )?.role;\n if (migrateRole === 'worker') parameters.migrateService = 'worker';\n if (options?.workerRole) parameters.workerRole = options.workerRole;\n if (options?.environment) parameters.environment = options.environment;\n if (options?.runtimeProfile) {\n parameters.runtimeProfile = options.runtimeProfile;\n }\n\n const volumes = new Map<\n string,\n {\n name: string;\n size: string;\n mounts: Array<{ workload: string; path: string; readOnly?: true }>;\n }\n >();\n for (const workload of declaration.workloads) {\n const prefix = workload.role;\n const argv = [...(workload.entrypoint ?? []), ...(workload.command ?? [])];\n // Nothing declared leaves the image's own command to run.\n if (argv.length > 0) parameters[`${prefix}Command`] = JSON.stringify(argv);\n if (workload.role === 'web') {\n if (workload.port !== undefined) {\n parameters.webPort = String(workload.port);\n }\n if ('path' in workload.health) {\n parameters.webHealthPath = workload.health.path;\n }\n } else if ('command' in workload.health) {\n parameters.workerHealthCommand = JSON.stringify(workload.health.command);\n }\n for (const volume of workload.volumes) {\n const entry = volumes.get(volume.name) ?? {\n name: volume.name,\n size: volumeSize as string,\n mounts: [],\n };\n entry.mounts.push({\n workload: workload.role,\n path: volume.target,\n ...(volume.readOnly ? { readOnly: true as const } : {}),\n });\n volumes.set(volume.name, entry);\n }\n }\n if (volumes.size > 0) {\n parameters.volumes = JSON.stringify([...volumes.values()]);\n }\n return parameters;\n}\n"],"mappings":";AAgBO,IAAM,sBAAsB;AAG5B,IAAM,0BAA0B;AAGhC,IAAM,4BACX;AAGK,IAAM,0BAA0B,CAAC,MAAM;AAGvC,IAAM,wBAAwB,CAAC,OAAO,QAAQ;AAG9C,IAAM,2BAA2B;CACtC;CACA;CACA;CACA;AACF;AA0JA,IAAM,eAAe;AACrB,IAAM,eAAe;AACrB,IAAM,SACJ;AACF,IAAM,cAAc;AAGpB,IAAM,gBAAgB;AACtB,IAAM,gBAAgB;AAEtB,IAAM,qBAAqB;CAAC;CAAW;CAAU;CAAU;AAAS;AACpE,IA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O;EAE/C,OAAA,IAAW,aAAa,SAAS,QAC/B,WAAW,sBAAsB,KAAK,UAAU,SAAS,OAAO,OAAO;EAEzE,KAAA,MAAW,UAAU,SAAS,SAAS;GACrC,MAAM,QAAQ,QAAQ,IAAI,OAAO,IAAI,KAAK;IACxC,MAAM,OAAO;IACb,MAAM;IACN,QAAQ,CAAC;GACX;GACA,MAAM,OAAO,KAAK;IAChB,UAAU,SAAS;IACnB,MAAM,OAAO;IACb,GAAI,OAAO,WAAW,EAAE,UAAU,KAAc,IAAI,CAAC;GACvD,CAAC;GACD,QAAQ,IAAI,OAAO,MAAM,KAAK;EAChC;CACF;CACA,IAAI,QAAQ,OAAO,GACjB,WAAW,UAAU,KAAK,UAAU,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC;CAE3D,OAAO;AACT"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Reading a compose declaration at an exact commit. Network and YAML parsing
3
+ * live here, outside the browser-safe `./deployment` entry, so that what is
4
+ * validated is exactly what CI built: GitHub's contents API with
5
+ * `ref=<commit>`, never a branch.
6
+ *
7
+ * Errors are {@link ComposeDeclarationReadError}s whose message names what
8
+ * failed and never contains the token, a response body or file contents.
9
+ */
10
+ /** Compose file names read, in order, when the caller names none. */
11
+ export declare const COMPOSE_DECLARATION_PATHS: readonly ["compose.yaml", "compose.yml", "docker-compose.yml"];
12
+ /** Anchors and aliases a document may use. The contract needs none; this caps expansion attacks. */
13
+ export declare const COMPOSE_MAX_ALIAS_COUNT = 50;
14
+ /** Largest compose file read, in characters. */
15
+ export declare const COMPOSE_MAX_SOURCE_LENGTH = 1048576;
16
+ export type ComposeDeclarationReadErrorCode = 'invalid-request' | 'not-found' | 'fetch-failed' | 'too-large' | 'invalid-yaml';
17
+ export declare class ComposeDeclarationReadError extends Error {
18
+ readonly code: ComposeDeclarationReadErrorCode;
19
+ /** The HTTP status, when the failure was a response. */
20
+ readonly status?: number | undefined;
21
+ constructor(code: ComposeDeclarationReadErrorCode, message: string,
22
+ /** The HTTP status, when the failure was a response. */
23
+ status?: number | undefined);
24
+ }
25
+ /**
26
+ * Parse compose YAML for `validateComposeDeployment`: merge keys are not
27
+ * expanded (the validator refuses `<<`), aliases are capped, and a parse
28
+ * failure carries only a line number, never a snippet of the file.
29
+ */
30
+ export declare function parseComposeDocument(text: string): unknown;
31
+ export interface GitHubComposeSourceOptions {
32
+ owner: string;
33
+ repo: string;
34
+ /** The exact commit, 7 to 64 hex digits. A branch or tag name is refused. */
35
+ commit: string;
36
+ /** A GitHub token that can read the repository's contents. Never logged or echoed. */
37
+ token: string;
38
+ fetch?: typeof fetch;
39
+ /** Paths tried in order. Defaults to {@link COMPOSE_DECLARATION_PATHS}. */
40
+ paths?: readonly string[];
41
+ /** Defaults to `https://api.github.com`. */
42
+ apiBase?: string;
43
+ }
44
+ export interface GitHubComposeDeclaration {
45
+ /** The path the file was found at. */
46
+ path: string;
47
+ /** The parsed document, ready for `validateComposeDeployment`. */
48
+ document: unknown;
49
+ }
50
+ /**
51
+ * Read and parse the compose declaration at `commit`. Resolves with the first
52
+ * of `paths` that exists; rejects with `not-found` when none does.
53
+ */
54
+ export declare function readGitHubComposeDeclaration(options: GitHubComposeSourceOptions): Promise<GitHubComposeDeclaration>;
55
+ //# sourceMappingURL=compose-source.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose-source.d.ts","sourceRoot":"","sources":["../../src/deployment/compose-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,qEAAqE;AACrE,eAAO,MAAM,yBAAyB,gEAI5B,CAAC;AAEX,oGAAoG;AACpG,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,gDAAgD;AAChD,eAAO,MAAM,yBAAyB,UAAY,CAAC;AAEnD,MAAM,MAAM,+BAA+B,GACvC,iBAAiB,GACjB,WAAW,GACX,cAAc,GACd,WAAW,GACX,cAAc,CAAC;AAEnB,qBAAa,2BAA4B,SAAQ,KAAK;IAElD,QAAQ,CAAC,IAAI,EAAE,+BAA+B;IAE9C,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM;gBAHf,IAAI,EAAE,+BAA+B,EAC9C,OAAO,EAAE,MAAM;IACf,wDAAwD;IAC/C,MAAM,CAAC,EAAE,MAAM,YAAA;CAK3B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAqB1D;AAED,MAAM,WAAW,0BAA0B;IACzC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,6EAA6E;IAC7E,MAAM,EAAE,MAAM,CAAC;IACf,sFAAsF;IACtF,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,2EAA2E;IAC3E,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,4CAA4C;IAC5C,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,wBAAwB;IACvC,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,QAAQ,EAAE,OAAO,CAAC;CACnB;AAgBD;;;GAGG;AACH,wBAAsB,4BAA4B,CAChD,OAAO,EAAE,0BAA0B,GAClC,OAAO,CAAC,wBAAwB,CAAC,CA4DnC"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Server-side apply of a `HostedApp`. This is the one write path from a
3
+ * deployer to the cluster: one custom resource kind, one credential whose
4
+ * RBAC is what bounds it. The client cannot name another resource.
5
+ *
6
+ * Errors carry the HTTP status only: never the token, the request or the
7
+ * response body.
8
+ */
9
+ import { type HostedAppManifest } from './hosted-app.js';
10
+ export interface HostedAppApplier {
11
+ /** Create or update the HostedApp; resolves with the resulting `metadata.generation`. */
12
+ apply(manifest: HostedAppManifest): Promise<{
13
+ generation: number;
14
+ }>;
15
+ /** Delete the HostedApp by name. The operator enforces retention on the data. A missing one is not an error. */
16
+ remove(name: string): Promise<void>;
17
+ }
18
+ export declare class HostedAppApplyError extends Error {
19
+ readonly status: number;
20
+ constructor(status: number, message: string);
21
+ }
22
+ export interface HostedAppApplierOptions {
23
+ /** The Kubernetes API server origin, for example `https://k8s.example:6443`. */
24
+ apiServer: string;
25
+ /** A bearer token scoped to the HostedApp kind. Never logged or echoed. */
26
+ token: string;
27
+ fetch?: typeof fetch;
28
+ /** Defaults to `smrt-hosting`. */
29
+ fieldManager?: string;
30
+ }
31
+ export declare function createHostedAppApplier(options: HostedAppApplierOptions): HostedAppApplier;
32
+ //# sourceMappingURL=hosted-app-applier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted-app-applier.d.ts","sourceRoot":"","sources":["../../src/deployment/hosted-app-applier.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,KAAK,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAAC;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACpE,gHAAgH;IAChH,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACrC;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAE1C,QAAQ,CAAC,MAAM,EAAE,MAAM;gBAAd,MAAM,EAAE,MAAM,EACvB,OAAO,EAAE,MAAM;CAKlB;AAED,MAAM,WAAW,uBAAuB;IACtC,gFAAgF;IAChF,SAAS,EAAE,MAAM,CAAC;IAClB,2EAA2E;IAC3E,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,kCAAkC;IAClC,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAKD,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,uBAAuB,GAC/B,gBAAgB,CAqElB"}
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Hosted rendering of the compose deployment contract: turn a declaration
3
+ * resolved at the `deploy` stage into a `HostedApp`
4
+ * (`hosting.happyvertical.com/v1alpha1`) for the platform operator's `smrt`
5
+ * preset. It is the hosted counterpart of `renderSmrtAppChartValues`: both
6
+ * start from the same declaration.
7
+ *
8
+ * The declaration says what the application is. What it may have is the
9
+ * platform's decision, so the caller passes that in as {@link HostedAppEntitlements}
10
+ * (approved bindings, verified domains, volume size) and gets either a
11
+ * manifest or structured rejections that are safe to show a customer. This
12
+ * module is pure: no I/O, no cluster access, browser-safe.
13
+ */
14
+ import { type ComposeDeploymentDeclaration } from './compose-contract.js';
15
+ export declare const HOSTED_APP_API_VERSION = "hosting.happyvertical.com/v1alpha1";
16
+ export declare const HOSTED_APP_KIND = "HostedApp";
17
+ export declare const HOSTED_APP_PRESET = "smrt";
18
+ /** Longest `metadata.name` the operator accepts. */
19
+ export declare const HOSTED_APP_NAME_MAX_LENGTH = 40;
20
+ export declare const HOSTED_APP_TIERS: readonly ["T1", "T2", "T3"];
21
+ export type HostedAppTier = (typeof HOSTED_APP_TIERS)[number];
22
+ export declare const HOSTED_APP_WORKER_ROLES: readonly ["background", "schedule", "task"];
23
+ export type HostedAppWorkerRole = (typeof HOSTED_APP_WORKER_ROLES)[number];
24
+ /** The `HostedApp` fields this module writes. The operator's CRD is the authority. */
25
+ export interface HostedAppManifest {
26
+ apiVersion: typeof HOSTED_APP_API_VERSION;
27
+ kind: typeof HOSTED_APP_KIND;
28
+ metadata: {
29
+ name: string;
30
+ labels: Record<string, string>;
31
+ };
32
+ spec: {
33
+ poolRef: string;
34
+ tier: HostedAppTier;
35
+ resourceClass?: string;
36
+ release: {
37
+ id: string;
38
+ commit?: string;
39
+ };
40
+ domains?: string[];
41
+ preset: {
42
+ name: typeof HOSTED_APP_PRESET;
43
+ images: Record<string, string>;
44
+ parameters: Record<string, string>;
45
+ };
46
+ bindings?: Array<{
47
+ name: string;
48
+ type: string;
49
+ }>;
50
+ };
51
+ }
52
+ /**
53
+ * A reason a request cannot be honoured. The message is written for the
54
+ * person who owns the compose file and never carries internals or secrets.
55
+ */
56
+ export interface HostedAppRejection {
57
+ code: string;
58
+ message: string;
59
+ }
60
+ /** Where and how the app is hosted. Chosen by the platform, not the declaration. */
61
+ export interface HostedAppPlacement {
62
+ /** `metadata.name`: a DNS label of at most {@link HOSTED_APP_NAME_MAX_LENGTH} characters. */
63
+ name: string;
64
+ poolRef: string;
65
+ tier: HostedAppTier;
66
+ resourceClass?: string;
67
+ /** Extra `metadata.labels`, for example the id a collector discovers apps by. */
68
+ labels?: Record<string, string>;
69
+ }
70
+ /** What this app may have. The caller derives these from its own policy. */
71
+ export interface HostedAppEntitlements {
72
+ /** Binding kinds the app may use. A declared binding outside this list is rejected. */
73
+ bindings: readonly string[];
74
+ /** Custom domains verified for the app. A declared domain outside this list is rejected. */
75
+ domains?: readonly string[];
76
+ /**
77
+ * The host the platform derives for the app. A declared domain equal to it
78
+ * is accepted and not written to `spec.domains`, which lists only custom
79
+ * domains.
80
+ */
81
+ platformHost?: string;
82
+ /**
83
+ * Size of every declared volume, a Kubernetes quantity such as `5Gi`. The
84
+ * declaration carries none. Required when the declaration has a volume.
85
+ */
86
+ volumeSize?: string;
87
+ }
88
+ /** Preset parameters the declaration does not carry but the caller may set. */
89
+ export interface HostedAppPresetOptions {
90
+ /** `background` (default), `schedule` or `task`. Applies when there is a worker. */
91
+ workerRole?: HostedAppWorkerRole;
92
+ /** `SMRT_APP_ENVIRONMENT`. */
93
+ environment?: string;
94
+ /** `SMRT_RUNTIME_PROFILE`. */
95
+ runtimeProfile?: string;
96
+ }
97
+ export interface ComposeHostedAppInput {
98
+ /** The parsed compose document, read at `commit`. Untrusted. */
99
+ document: unknown;
100
+ /** The commit the document was read at, 7 to 64 hex digits. */
101
+ commit: string;
102
+ /**
103
+ * The image digests CI built, by Compose service name
104
+ * (`ghcr.io/acme/app@sha256:...`).
105
+ */
106
+ digests: Record<string, string>;
107
+ app: HostedAppPlacement;
108
+ entitlements: HostedAppEntitlements;
109
+ preset?: HostedAppPresetOptions;
110
+ }
111
+ export type ComposeHostedAppResult = {
112
+ ok: true;
113
+ manifest: HostedAppManifest;
114
+ declaration: ComposeDeploymentDeclaration;
115
+ warnings: HostedAppRejection[];
116
+ } | {
117
+ ok: false;
118
+ rejections: HostedAppRejection[];
119
+ };
120
+ /** Deterministic, so a repeated CI call for the same build is the same release. */
121
+ export declare function hostedAppReleaseId(commit: string, digests: Record<string, string>): string;
122
+ /** Whether `commit` is a spelling {@link composeHostedApp} accepts. */
123
+ export declare function isHostedAppCommit(commit: unknown): commit is string;
124
+ /**
125
+ * Compose the `HostedApp` for one release: validate the declaration at the
126
+ * `deploy` stage, intersect it with the entitlements, and emit the custom
127
+ * resource the operator's `smrt` preset accepts. Never throws on a bad
128
+ * document or bad inputs; every refusal is a rejection.
129
+ */
130
+ export declare function composeHostedApp(input: ComposeHostedAppInput): ComposeHostedAppResult;
131
+ //# sourceMappingURL=hosted-app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hosted-app.d.ts","sourceRoot":"","sources":["../../src/deployment/hosted-app.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EACL,KAAK,4BAA4B,EAGlC,MAAM,uBAAuB,CAAC;AAG/B,eAAO,MAAM,sBAAsB,uCAAuC,CAAC;AAC3E,eAAO,MAAM,eAAe,cAAc,CAAC;AAC3C,eAAO,MAAM,iBAAiB,SAAS,CAAC;AACxC,oDAAoD;AACpD,eAAO,MAAM,0BAA0B,KAAK,CAAC;AAE7C,eAAO,MAAM,gBAAgB,6BAA8B,CAAC;AAC5D,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE9D,eAAO,MAAM,uBAAuB,6CAI1B,CAAC;AACX,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,uBAAuB,CAAC,CAAC,MAAM,CAAC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AKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,qBAAqB,GAC3B,sBAAsB,CAqKxB"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A synchronous SHA-256 with no platform dependency, so the deployment entry
3
+ * stays browser-safe (`node:crypto` is not available there and `crypto.subtle`
4
+ * is asynchronous). It exists only to derive stable release identifiers from
5
+ * public image digests; it is not a place to hash secrets.
6
+ */
7
+ /** Hex SHA-256 of the UTF-8 encoding of `text`. */
8
+ export declare function sha256Hex(text: string): string;
9
+ //# sourceMappingURL=sha256.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sha256.d.ts","sourceRoot":"","sources":["../../src/deployment/sha256.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAoBH,mDAAmD;AACnD,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAiD9C"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@happyvertical/smrt-config/deployment/hosting`: the I/O half of hosting a
3
+ * compose-declared application.
4
+ *
5
+ * Reads the declaration at an exact commit from GitHub and server-side-applies
6
+ * the `HostedApp` composed by `composeHostedApp` (from the browser-safe
7
+ * `@happyvertical/smrt-config/deployment` entry). It uses `fetch` and a YAML
8
+ * parser, so it is kept apart from that entry.
9
+ */
10
+ export { COMPOSE_DECLARATION_PATHS, COMPOSE_MAX_ALIAS_COUNT, COMPOSE_MAX_SOURCE_LENGTH, ComposeDeclarationReadError, type ComposeDeclarationReadErrorCode, type GitHubComposeDeclaration, type GitHubComposeSourceOptions, parseComposeDocument, readGitHubComposeDeclaration, } from './deployment/compose-source.js';
11
+ export { createHostedAppApplier, type HostedAppApplier, type HostedAppApplierOptions, HostedAppApplyError, } from './deployment/hosted-app-applier.js';
12
+ //# sourceMappingURL=deployment-hosting.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deployment-hosting.d.ts","sourceRoot":"","sources":["../src/deployment-hosting.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EACL,yBAAyB,EACzB,uBAAuB,EACvB,yBAAyB,EACzB,2BAA2B,EAC3B,KAAK,+BAA+B,EACpC,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,oBAAoB,EACpB,4BAA4B,GAC7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,sBAAsB,EACtB,KAAK,gBAAgB,EACrB,KAAK,uBAAuB,EAC5B,mBAAmB,GACpB,MAAM,oCAAoC,CAAC"}
@@ -0,0 +1,122 @@
1
+ import "./chunks/hosted-app-BomhfPIt.js";
2
+ import { parse } from "yaml";
3
+ //#region src/deployment/compose-source.ts
4
+ var COMPOSE_DECLARATION_PATHS = [
5
+ "compose.yaml",
6
+ "compose.yml",
7
+ "docker-compose.yml"
8
+ ];
9
+ var COMPOSE_MAX_ALIAS_COUNT = 50;
10
+ var COMPOSE_MAX_SOURCE_LENGTH = 1048576;
11
+ var ComposeDeclarationReadError = class extends Error {
12
+ constructor(code, message, status) {
13
+ super(message);
14
+ this.code = code;
15
+ this.status = status;
16
+ this.name = "ComposeDeclarationReadError";
17
+ }
18
+ code;
19
+ status;
20
+ };
21
+ function parseComposeDocument(text) {
22
+ if (text.length > 1048576) throw new ComposeDeclarationReadError("too-large", "The compose file is too large to read.");
23
+ try {
24
+ return parse(text, {
25
+ maxAliasCount: 50,
26
+ merge: false,
27
+ uniqueKeys: true
28
+ });
29
+ } catch (error) {
30
+ const line = error.linePos?.[0]?.line;
31
+ throw new ComposeDeclarationReadError("invalid-yaml", `The compose file is not valid YAML${typeof line === "number" ? ` (line ${line})` : ""}.`);
32
+ }
33
+ }
34
+ var OWNER = /^[A-Za-z0-9]([-A-Za-z0-9]{0,38})$|^[A-Za-z0-9]$/;
35
+ var REPO = /^[A-Za-z0-9._-]{1,100}$/;
36
+ var COMMIT = /^[a-f0-9]{7,64}$/;
37
+ function usablePath(path) {
38
+ return path.length > 0 && !path.startsWith("/") && path.split("/").every((part) => part !== "" && part !== "." && part !== "..");
39
+ }
40
+ async function readGitHubComposeDeclaration(options) {
41
+ const paths = options.paths ?? COMPOSE_DECLARATION_PATHS;
42
+ if (!OWNER.test(options.owner) || !REPO.test(options.repo) || options.repo === "." || options.repo === ".." || !COMMIT.test(options.commit) || paths.length === 0 || !paths.every(usablePath) || typeof options.token !== "string" || options.token === "") throw new ComposeDeclarationReadError("invalid-request", "The repository, commit, token or declaration path is not valid.");
43
+ const doFetch = options.fetch ?? fetch;
44
+ const base = (options.apiBase ?? "https://api.github.com").replace(/\/+$/, "");
45
+ for (const path of paths) {
46
+ const url = `${base}/repos/${encodeURIComponent(options.owner)}/${encodeURIComponent(options.repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(options.commit)}`;
47
+ let response;
48
+ try {
49
+ response = await doFetch(url, { headers: {
50
+ accept: "application/vnd.github.raw+json",
51
+ authorization: `Bearer ${options.token}`,
52
+ "x-github-api-version": "2022-11-28"
53
+ } });
54
+ } catch {
55
+ throw new ComposeDeclarationReadError("fetch-failed", "The compose declaration could not be fetched.");
56
+ }
57
+ if (response.status === 404) continue;
58
+ if (!response.ok) throw new ComposeDeclarationReadError("fetch-failed", `The compose declaration could not be fetched (${response.status}).`, response.status);
59
+ return {
60
+ path,
61
+ document: parseComposeDocument(await response.text())
62
+ };
63
+ }
64
+ throw new ComposeDeclarationReadError("not-found", "There is no compose declaration at that commit.", 404);
65
+ }
66
+ //#endregion
67
+ //#region src/deployment/hosted-app-applier.ts
68
+ var HostedAppApplyError = class extends Error {
69
+ constructor(status, message) {
70
+ super(message);
71
+ this.status = status;
72
+ this.name = "HostedAppApplyError";
73
+ }
74
+ status;
75
+ };
76
+ var COLLECTION = "apis/hosting.happyvertical.com/v1alpha1/hostedapps";
77
+ var NAME = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;
78
+ function createHostedAppApplier(options) {
79
+ const doFetch = options.fetch ?? fetch;
80
+ let base;
81
+ try {
82
+ const url = new URL(options.apiServer);
83
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
84
+ base = `${url.origin}${url.pathname}`.replace(/\/+$/, "");
85
+ } catch {
86
+ throw new HostedAppApplyError(0, "The API server is not a valid URL.");
87
+ }
88
+ if (typeof options.token !== "string" || options.token === "") throw new HostedAppApplyError(0, "A token is required.");
89
+ const headers = { authorization: `Bearer ${options.token}` };
90
+ const checkName = (name) => {
91
+ if (typeof name !== "string" || !NAME.test(name) || name.length > 63) throw new HostedAppApplyError(0, "The app name is not a DNS label.");
92
+ return name;
93
+ };
94
+ return {
95
+ async apply(manifest) {
96
+ if (manifest.apiVersion !== "hosting.happyvertical.com/v1alpha1" || manifest.kind !== "HostedApp") throw new HostedAppApplyError(0, "Only a HostedApp can be applied.");
97
+ const name = checkName(manifest.metadata?.name);
98
+ const manager = encodeURIComponent(options.fieldManager ?? "smrt-hosting");
99
+ const response = await doFetch(`${base}/${COLLECTION}/${encodeURIComponent(name)}?fieldManager=${manager}&force=true`, {
100
+ method: "PATCH",
101
+ headers: {
102
+ ...headers,
103
+ "content-type": "application/apply-patch+yaml"
104
+ },
105
+ body: JSON.stringify(manifest)
106
+ });
107
+ if (!response.ok) throw new HostedAppApplyError(response.status, `apply failed (${response.status})`);
108
+ return { generation: (await response.json()).metadata?.generation ?? 0 };
109
+ },
110
+ async remove(name) {
111
+ const response = await doFetch(`${base}/${COLLECTION}/${encodeURIComponent(checkName(name))}`, {
112
+ method: "DELETE",
113
+ headers
114
+ });
115
+ if (!response.ok && response.status !== 404) throw new HostedAppApplyError(response.status, `delete failed (${response.status})`);
116
+ }
117
+ };
118
+ }
119
+ //#endregion
120
+ export { COMPOSE_DECLARATION_PATHS, COMPOSE_MAX_ALIAS_COUNT, COMPOSE_MAX_SOURCE_LENGTH, ComposeDeclarationReadError, HostedAppApplyError, createHostedAppApplier, parseComposeDocument, readGitHubComposeDeclaration };
121
+
122
+ //# sourceMappingURL=deployment-hosting.js.map