@happyvertical/smrt-config 0.61.0 → 0.61.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deployment-hosting.js","names":[],"sources":["../src/deployment/compose-source.ts","../src/deployment/hosted-app-applier.ts"],"sourcesContent":["/**\n * Reading a compose declaration at an exact commit. Network and YAML parsing\n * live here, outside the browser-safe `./deployment` entry, so that what is\n * validated is exactly what CI built: GitHub's contents API with\n * `ref=<commit>`, never a branch.\n *\n * Errors are {@link ComposeDeclarationReadError}s whose message names what\n * failed and never contains the token, a response body or file contents.\n */\n\nimport { parse } from 'yaml';\n\n/** Compose file names read, in order, when the caller names none. */\nexport const COMPOSE_DECLARATION_PATHS = [\n 'compose.yaml',\n 'compose.yml',\n 'docker-compose.yml',\n] as const;\n\n/** Anchors and aliases a document may use. The contract needs none; this caps expansion attacks. */\nexport const COMPOSE_MAX_ALIAS_COUNT = 50;\n/** Largest compose file read, in characters. */\nexport const COMPOSE_MAX_SOURCE_LENGTH = 1_048_576;\n\nexport type ComposeDeclarationReadErrorCode =\n | 'invalid-request'\n | 'not-found'\n | 'fetch-failed'\n | 'too-large'\n | 'invalid-yaml';\n\nexport class ComposeDeclarationReadError extends Error {\n constructor(\n readonly code: ComposeDeclarationReadErrorCode,\n message: string,\n /** The HTTP status, when the failure was a response. */\n readonly status?: number,\n ) {\n super(message);\n this.name = 'ComposeDeclarationReadError';\n }\n}\n\n/**\n * Parse compose YAML for `validateComposeDeployment`: merge keys are not\n * expanded (the validator refuses `<<`), aliases are capped, and a parse\n * failure carries only a line number, never a snippet of the file.\n */\nexport function parseComposeDocument(text: string): unknown {\n if (text.length > COMPOSE_MAX_SOURCE_LENGTH) {\n throw new ComposeDeclarationReadError(\n 'too-large',\n 'The compose file is too large to read.',\n );\n }\n try {\n return parse(text, {\n maxAliasCount: COMPOSE_MAX_ALIAS_COUNT,\n merge: false,\n uniqueKeys: true,\n });\n } catch (error) {\n const line = (error as { linePos?: Array<{ line?: number }> }).linePos?.[0]\n ?.line;\n throw new ComposeDeclarationReadError(\n 'invalid-yaml',\n `The compose file is not valid YAML${typeof line === 'number' ? ` (line ${line})` : ''}.`,\n );\n }\n}\n\nexport interface GitHubComposeSourceOptions {\n owner: string;\n repo: string;\n /** The exact commit, 7 to 64 hex digits. A branch or tag name is refused. */\n commit: string;\n /** A GitHub token that can read the repository's contents. Never logged or echoed. */\n token: string;\n fetch?: typeof fetch;\n /** Paths tried in order. Defaults to {@link COMPOSE_DECLARATION_PATHS}. */\n paths?: readonly string[];\n /** Defaults to `https://api.github.com`. */\n apiBase?: string;\n}\n\nexport interface GitHubComposeDeclaration {\n /** The path the file was found at. */\n path: string;\n /** The parsed document, ready for `validateComposeDeployment`. */\n document: unknown;\n}\n\nconst OWNER = /^[A-Za-z0-9]([-A-Za-z0-9]{0,38})$|^[A-Za-z0-9]$/;\nconst REPO = /^[A-Za-z0-9._-]{1,100}$/;\nconst COMMIT = /^[a-f0-9]{7,64}$/;\n\nfunction usablePath(path: string): boolean {\n return (\n path.length > 0 &&\n !path.startsWith('/') &&\n path\n .split('/')\n .every((part) => part !== '' && part !== '.' && part !== '..')\n );\n}\n\n/**\n * Read and parse the compose declaration at `commit`. Resolves with the first\n * of `paths` that exists; rejects with `not-found` when none does.\n */\nexport async function readGitHubComposeDeclaration(\n options: GitHubComposeSourceOptions,\n): Promise<GitHubComposeDeclaration> {\n const paths = options.paths ?? COMPOSE_DECLARATION_PATHS;\n if (\n !OWNER.test(options.owner) ||\n !REPO.test(options.repo) ||\n options.repo === '.' ||\n options.repo === '..' ||\n !COMMIT.test(options.commit) ||\n paths.length === 0 ||\n !paths.every(usablePath) ||\n typeof options.token !== 'string' ||\n options.token === ''\n ) {\n throw new ComposeDeclarationReadError(\n 'invalid-request',\n 'The repository, commit, token or declaration path is not valid.',\n );\n }\n const doFetch = options.fetch ?? fetch;\n const base = (options.apiBase ?? 'https://api.github.com').replace(\n /\\/+$/,\n '',\n );\n\n for (const path of paths) {\n const url = `${base}/repos/${encodeURIComponent(options.owner)}/${encodeURIComponent(options.repo)}/contents/${path\n .split('/')\n .map(encodeURIComponent)\n .join('/')}?ref=${encodeURIComponent(options.commit)}`;\n let response: Response;\n try {\n response = await doFetch(url, {\n headers: {\n accept: 'application/vnd.github.raw+json',\n authorization: `Bearer ${options.token}`,\n 'x-github-api-version': '2022-11-28',\n },\n });\n } catch {\n // The underlying error is dropped: it can name the request.\n throw new ComposeDeclarationReadError(\n 'fetch-failed',\n 'The compose declaration could not be fetched.',\n );\n }\n if (response.status === 404) continue;\n if (!response.ok) {\n throw new ComposeDeclarationReadError(\n 'fetch-failed',\n `The compose declaration could not be fetched (${response.status}).`,\n response.status,\n );\n }\n return { path, document: parseComposeDocument(await response.text()) };\n }\n throw new ComposeDeclarationReadError(\n 'not-found',\n 'There is no compose declaration at that commit.',\n 404,\n );\n}\n","/**\n * Server-side apply of a `HostedApp`. This is the one write path from a\n * deployer to the cluster: one custom resource kind, one credential whose\n * RBAC is what bounds it. The client cannot name another resource.\n *\n * Errors carry the HTTP status only: never the token, the request or the\n * response body.\n */\n\nimport {\n HOSTED_APP_API_VERSION,\n HOSTED_APP_KIND,\n type HostedAppManifest,\n} from './hosted-app.js';\n\nexport interface HostedAppApplier {\n /** Create or update the HostedApp; resolves with the resulting `metadata.generation`. */\n apply(manifest: HostedAppManifest): Promise<{ generation: number }>;\n /** Delete the HostedApp by name. The operator enforces retention on the data. A missing one is not an error. */\n remove(name: string): Promise<void>;\n}\n\nexport class HostedAppApplyError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = 'HostedAppApplyError';\n }\n}\n\nexport interface HostedAppApplierOptions {\n /** The Kubernetes API server origin, for example `https://k8s.example:6443`. */\n apiServer: string;\n /** A bearer token scoped to the HostedApp kind. Never logged or echoed. */\n token: string;\n fetch?: typeof fetch;\n /** Defaults to `smrt-hosting`. */\n fieldManager?: string;\n}\n\nconst COLLECTION = 'apis/hosting.happyvertical.com/v1alpha1/hostedapps';\nconst NAME = /^[a-z]([-a-z0-9]*[a-z0-9])?$/;\n\nexport function createHostedAppApplier(\n options: HostedAppApplierOptions,\n): HostedAppApplier {\n const doFetch = options.fetch ?? fetch;\n let base: string;\n try {\n const url = new URL(options.apiServer);\n if (url.protocol !== 'https:' && url.protocol !== 'http:')\n throw new Error();\n base = `${url.origin}${url.pathname}`.replace(/\\/+$/, '');\n } catch {\n throw new HostedAppApplyError(0, 'The API server is not a valid URL.');\n }\n if (typeof options.token !== 'string' || options.token === '') {\n throw new HostedAppApplyError(0, 'A token is required.');\n }\n const headers = { authorization: `Bearer ${options.token}` };\n const checkName = (name: unknown): string => {\n if (typeof name !== 'string' || !NAME.test(name) || name.length > 63) {\n throw new HostedAppApplyError(0, 'The app name is not a DNS label.');\n }\n return name;\n };\n\n return {\n async apply(manifest) {\n if (\n manifest.apiVersion !== HOSTED_APP_API_VERSION ||\n manifest.kind !== HOSTED_APP_KIND\n ) {\n throw new HostedAppApplyError(0, 'Only a HostedApp can be applied.');\n }\n const name = checkName(manifest.metadata?.name);\n const manager = encodeURIComponent(\n options.fieldManager ?? 'smrt-hosting',\n );\n const response = await doFetch(\n `${base}/${COLLECTION}/${encodeURIComponent(name)}?fieldManager=${manager}&force=true`,\n {\n method: 'PATCH',\n headers: {\n ...headers,\n 'content-type': 'application/apply-patch+yaml',\n },\n body: JSON.stringify(manifest),\n },\n );\n if (!response.ok) {\n throw new HostedAppApplyError(\n response.status,\n `apply failed (${response.status})`,\n );\n }\n const body = (await response.json()) as {\n metadata?: { generation?: number };\n };\n return { generation: body.metadata?.generation ?? 0 };\n },\n async remove(name) {\n const response = await doFetch(\n `${base}/${COLLECTION}/${encodeURIComponent(checkName(name))}`,\n { method: 'DELETE', headers },\n );\n if (!response.ok && response.status !== 404) {\n throw new HostedAppApplyError(\n response.status,\n `delete failed (${response.status})`,\n );\n }\n },\n };\n}\n"],"mappings":";;;AA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EAAE,eAAe,UAAU,QAAQ,QAAQ;CAC3D,MAAM,aAAa,SAA0B;EAC3C,IAAI,OAAO,SAAS,YAAY,CAAC,KAAK,KAAK,IAAI,KAAK,KAAK,SAAS,IAChE,MAAM,IAAI,oBAAoB,GAAG,kCAAkC;EAErE,OAAO;CACT;CAEA,OAAO;EACL,MAAM,MAAM,UAAU;GACpB,IACE,SAAS,eAAA,wCACT,SAAS,SAAA,aAET,MAAM,IAAI,oBAAoB,GAAG,kCAAkC;GAErE,MAAM,OAAO,UAAU,SAAS,UAAU,IAAI;GAC9C,MAAM,UAAU,mBACd,QAAQ,gBAAgB,cAC1B;GACA,MAAM,WAAW,MAAM,QACrB,GAAG,KAAI,GAAI,WAAU,GAAI,mBAAmB,IAAI,EAAC,gBAAiB,QAAO,cACzE;IACE,QAAQ;IACR,SAAS;KACP,GAAG;KACH,gBAAgB;IAClB;IACA,MAAM,KAAK,UAAU,QAAQ;GAC/B,CACF;GACA,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,oBACR,SAAS,QACT,iBAAiB,SAAS,OAAM,EAClC;GAKF,OAAO,EAAE,aAAY,MAHD,SAAS,KAAK,EAAA,CAGR,UAAU,cAAc,EAAE;EACtD;EACA,MAAM,OAAO,MAAM;GACjB,MAAM,WAAW,MAAM,QACrB,GAAG,KAAI,GAAI,WAAU,GAAI,mBAAmB,UAAU,IAAI,CAAC,KAC3D;IAAE,QAAQ;IAAU;GAAQ,CAC9B;GACA,IAAI,CAAC,SAAS,MAAM,SAAS,WAAW,KACtC,MAAM,IAAI,oBACR,SAAS,QACT,kBAAkB,SAAS,OAAM,EACnC;EAEJ;CACF;AACF"}
@@ -3,9 +3,11 @@
3
3
  *
4
4
  * A Compose file annotated with `x-happyvertical` extension fields declares
5
5
  * how an application is deployed. This entry validates that declaration,
6
- * resolves it into plain data, and renders it for the `smrt-app` chart. It is
7
- * browser-safe and separate from the configuration loader.
6
+ * resolves it into plain data, and renders it for the `smrt-app` chart or as a
7
+ * `HostedApp` for a hosting platform. It is browser-safe and separate from the
8
+ * configuration loader; the network half is `./deployment/hosting`.
8
9
  */
9
10
  export { renderSmrtAppChartValues, SMRT_RELEASE_GUARD, type SmrtAppChartInputs, type SmrtAppChartProbeTiming, type SmrtAppChartResources, type SmrtAppChartSecretEnv, type SmrtAppChartSecretRef, SmrtAppChartValuesError, type SmrtAppChartWorkerRole, type SmrtAppChartWorkloadInputs, } from './deployment/chart-values.js';
10
11
  export { type ComposeDeploymentBinding, type ComposeDeploymentDeclaration, type ComposeDeploymentHealth, type ComposeDeploymentIssue, type ComposeDeploymentIssueCode, type ComposeDeploymentMigration, type ComposeDeploymentOptions, type ComposeDeploymentResult, type ComposeDeploymentStage, type ComposeDeploymentVolume, type ComposeDeploymentWorkload, formatComposeDeploymentReport, validateComposeDeployment, X_HAPPYVERTICAL_BINDINGS, X_HAPPYVERTICAL_KEY, X_HAPPYVERTICAL_PRESETS, X_HAPPYVERTICAL_ROLES, X_HAPPYVERTICAL_SCHEMA_ID, X_HAPPYVERTICAL_VERSION, type XHappyVerticalBinding, type XHappyVerticalPreset, type XHappyVerticalRole, } from './deployment/compose-contract.js';
12
+ export { type ComposeHostedAppInput, type ComposeHostedAppResult, composeHostedApp, HOSTED_APP_API_VERSION, HOSTED_APP_KIND, HOSTED_APP_NAME_MAX_LENGTH, HOSTED_APP_PRESET, HOSTED_APP_TIERS, HOSTED_APP_WORKER_ROLES, type HostedAppEntitlements, type HostedAppManifest, type HostedAppPlacement, type HostedAppPresetOptions, type HostedAppRejection, type HostedAppTier, type HostedAppWorkerRole, hostedAppReleaseId, isHostedAppCommit, } from './deployment/hosted-app.js';
11
13
  //# sourceMappingURL=deployment.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"deployment.d.ts","sourceRoot":"","sources":["../src/deployment.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAClB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB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,EACnB,uBAAuB,EACvB,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,GACxB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACL,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAC3B,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,0BAA0B,EAC1B,iBAAiB,EACjB,gBAAgB,EAChB,uBAAuB,EACvB,KAAK,qBAAqB,EAC1B,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,sBAAsB,EAC3B,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,4BAA4B,CAAC"}
@@ -1,7 +1,8 @@
1
+ import { _ as validateComposeDeployment, a as HOSTED_APP_TIERS, c as hostedAppReleaseId, d as X_HAPPYVERTICAL_KEY, f as X_HAPPYVERTICAL_PRESETS, g as formatComposeDeploymentReport, h as X_HAPPYVERTICAL_VERSION, i as HOSTED_APP_PRESET, l as isHostedAppCommit, m as X_HAPPYVERTICAL_SCHEMA_ID, n as HOSTED_APP_KIND, o as HOSTED_APP_WORKER_ROLES, p as X_HAPPYVERTICAL_ROLES, r as HOSTED_APP_NAME_MAX_LENGTH, s as composeHostedApp, t as HOSTED_APP_API_VERSION, u as X_HAPPYVERTICAL_BINDINGS } from "./chunks/hosted-app-BomhfPIt.js";
1
2
  //#region src/deployment/chart-values.ts
2
3
  var SMRT_RELEASE_GUARD = "smrt-release-v1";
3
4
  var CHART_NAME = /^[a-z][a-z0-9-]{0,30}$/;
4
- var DIGEST_IMAGE$1 = /^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/;
5
+ var DIGEST_IMAGE = /^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/;
5
6
  var WORKER_ROLES = [
6
7
  "background",
7
8
  "task",
@@ -164,7 +165,7 @@ function renderSmrtAppChartValues(declaration, inputs) {
164
165
  const images = {};
165
166
  for (const workload of declaration.workloads) {
166
167
  if (RESERVED_WORKLOAD_NAMES.includes(workload.name)) problems.push(`Service \`${workload.name}\` uses a name the chart keeps for its own resources (${RESERVED_WORKLOAD_NAMES.join(", ")}). Rename the service.`);
167
- if (workload.image !== void 0 && DIGEST_IMAGE$1.test(workload.image)) images[workload.name] = workload.image;
168
+ if (workload.image !== void 0 && DIGEST_IMAGE.test(workload.image)) images[workload.name] = workload.image;
168
169
  else problems.push(`Service \`${workload.name}\` has no image digest. Validate the Compose file at the \`deploy\` stage with the digests CI pushed.`);
169
170
  if (workload.entrypoint === void 0) problems.push(`Service \`${workload.name}\` leaves its entrypoint to the image. The chart starts a workload with exactly the command it is given and never runs the image's own entrypoint, so the Compose file has to state it: add \`entrypoint:\` to the service, naming the image's entrypoint, or \`entrypoint: []\` when \`command\` is complete on its own.`);
170
171
  else if (workload.entrypoint.length + (workload.command ?? []).length === 0) problems.push(`Service \`${workload.name}\` has an empty \`entrypoint\` and no \`command\`, so there is nothing to start.`);
@@ -212,509 +213,6 @@ function renderSmrtAppChartValues(declaration, inputs) {
212
213
  };
213
214
  }
214
215
  //#endregion
215
- //#region src/deployment/compose-contract.ts
216
- var X_HAPPYVERTICAL_KEY = "x-happyvertical";
217
- var X_HAPPYVERTICAL_VERSION = 1;
218
- var X_HAPPYVERTICAL_SCHEMA_ID = "https://s-m-r-t.dev/schemas/x-happyvertical/v1.schema.json";
219
- var X_HAPPYVERTICAL_PRESETS = ["smrt"];
220
- var X_HAPPYVERTICAL_ROLES = ["web", "worker"];
221
- var X_HAPPYVERTICAL_BINDINGS = [
222
- "postgres",
223
- "bucket",
224
- "email",
225
- "ai"
226
- ];
227
- var SERVICE_NAME = /^[a-z][a-z0-9-]{0,30}$/;
228
- var DIGEST_IMAGE = /^[a-zA-Z0-9./:_-]+@sha256:[a-f0-9]{64}$/;
229
- var DOMAIN = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/;
230
- var HEALTH_PATH = /^\/\S*$/;
231
- var PLAIN_COMMAND = /^[A-Za-z0-9_./:=@,+-]+( +[A-Za-z0-9_./:=@,+-]+)*$/;
232
- var INTERPOLATION = /\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*/g;
233
- var APPLICATION_FIELDS = [
234
- "version",
235
- "preset",
236
- "domain",
237
- "migrate"
238
- ];
239
- var MIGRATE_FIELDS = ["service", "command"];
240
- var SERVICE_FIELDS = [
241
- "role",
242
- "health",
243
- "binding"
244
- ];
245
- var HEALTH_FIELDS = ["path", "command"];
246
- function isRecord(value) {
247
- return typeof value === "object" && value !== null && !Array.isArray(value);
248
- }
249
- function isStringList(value) {
250
- return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string" && item.length > 0);
251
- }
252
- function describe(value) {
253
- if (typeof value === "string") return value.length > 80 ? `${value.slice(0, 80)}\u2026` : value;
254
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return `${value}`;
255
- if (value === null || value === void 0) return "an empty value";
256
- if (Array.isArray(value)) return "a list";
257
- return typeof value === "object" ? "a mapping" : `a ${typeof value}`;
258
- }
259
- function refuseVariables(values, path, what, issues, service) {
260
- if (!values.some((value) => value.includes("$"))) return false;
261
- issues.error("interpolated-value", path, `${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.`, "Write the literal value. Settings that differ between environments belong in the environment the application reads, not in this line.", service);
262
- return true;
263
- }
264
- function findMergeKey(root) {
265
- const seen = /* @__PURE__ */ new Set();
266
- const pending = [[root, ""]];
267
- while (pending.length > 0) {
268
- const [value, path] = pending.pop();
269
- if (typeof value !== "object" || value === null || seen.has(value)) continue;
270
- seen.add(value);
271
- if (Array.isArray(value)) {
272
- value.forEach((item, index) => {
273
- pending.push([item, `${path}[${index}]`]);
274
- });
275
- continue;
276
- }
277
- for (const [key, item] of Object.entries(value)) {
278
- const here = path ? `${path}.${key}` : key;
279
- if (key === "<<") return here;
280
- pending.push([item, here]);
281
- }
282
- }
283
- }
284
- function isLiteral(value) {
285
- return !value.includes("$");
286
- }
287
- function quoteList(values) {
288
- return values.map((value) => `\`${value}\``).join(", ");
289
- }
290
- function unknownFields(value, known) {
291
- return Object.keys(value).filter((key) => !known.includes(key));
292
- }
293
- var IssueCollector = class {
294
- errors = [];
295
- warnings = [];
296
- error(code, path, message, fix, service) {
297
- this.errors.push({
298
- code,
299
- severity: "error",
300
- path,
301
- ...service ? { service } : {},
302
- message,
303
- fix
304
- });
305
- }
306
- warning(code, path, message, fix, service) {
307
- this.warnings.push({
308
- code,
309
- severity: "warning",
310
- path,
311
- ...service ? { service } : {},
312
- message,
313
- fix
314
- });
315
- }
316
- };
317
- function parseApplication(document, issues) {
318
- const path = X_HAPPYVERTICAL_KEY;
319
- const block = document[X_HAPPYVERTICAL_KEY];
320
- if (block === void 0) {
321
- issues.error("contract-missing", path, `The file has no top-level \`${X_HAPPYVERTICAL_KEY}\` block, so it is an ordinary Compose file and not a deployment declaration.`, `Add a top-level \`${X_HAPPYVERTICAL_KEY}\` block with \`version: 1\`, \`preset: smrt\` and a \`migrate\` command.`);
322
- return {};
323
- }
324
- if (!isRecord(block)) {
325
- issues.error("contract-invalid", path, `The top-level \`${X_HAPPYVERTICAL_KEY}\` block must be a mapping of fields.`, "Write it as indented `key: value` lines: `version`, `preset`, `domain`, `migrate`.");
326
- return {};
327
- }
328
- const parsed = {};
329
- for (const field of unknownFields(block, APPLICATION_FIELDS)) issues.error("contract-invalid", `${path}.${field}`, `\`${field}\` is not a field of the version 1 contract.`, `Remove it or fix the spelling. The top-level fields are ${quoteList(APPLICATION_FIELDS)}.`);
330
- if (block.version !== 1) issues.error("version-unsupported", `${path}.version`, block.version === void 0 ? "The contract version is missing." : `Contract version \`${describe(block.version)}\` is not supported here.`, "Set `version: 1` (a number, without quotes).");
331
- if (typeof block.preset === "string" && X_HAPPYVERTICAL_PRESETS.includes(block.preset)) parsed.preset = block.preset;
332
- else issues.error("preset-unknown", `${path}.preset`, block.preset === void 0 ? "The preset is missing, so the platform does not know what kind of application this is." : `\`${describe(block.preset)}\` is not a preset the platform knows.`, `Set \`preset\` to one of: ${quoteList(X_HAPPYVERTICAL_PRESETS)}.`);
333
- if (block.domain !== void 0) if (typeof block.domain === "string" && block.domain.length <= 253 && DOMAIN.test(block.domain)) parsed.domain = block.domain;
334
- else issues.error("domain-invalid", `${path}.domain`, `\`${describe(block.domain)}\` is not a hostname.`, "Write only the hostname in lowercase, for example `app.example.com`: no `https://`, no port, no path.");
335
- const migrate = block.migrate;
336
- if (migrate === void 0) {
337
- issues.error("migrate-missing", `${path}.migrate`, "There is no `migrate` entry, so the platform does not know how to prepare the database before a release starts.", "Add `migrate:` with a `command` list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"db:migrate\"]`.");
338
- return parsed;
339
- }
340
- if (!isRecord(migrate)) {
341
- issues.error("migrate-invalid", `${path}.migrate`, "`migrate` must be a mapping with a `command`.", "Write `migrate:` followed by an indented `command:` list.");
342
- return parsed;
343
- }
344
- for (const field of unknownFields(migrate, MIGRATE_FIELDS)) issues.error("migrate-invalid", `${path}.migrate.${field}`, `\`${field}\` is not a field of \`migrate\`.`, `Remove it or fix the spelling. \`migrate\` takes ${quoteList(MIGRATE_FIELDS)}.`);
345
- if (isStringList(migrate.command)) {
346
- if (!refuseVariables(migrate.command, `${path}.migrate.command`, "The migration command", issues)) parsed.migrateCommand = [...migrate.command];
347
- } else issues.error("migrate-invalid", `${path}.migrate.command`, "The migration command must be a list with one argument per item.", "Write it as a list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"db:migrate\"]`.");
348
- if (migrate.service !== void 0) if (typeof migrate.service === "string" && migrate.service.length > 0) parsed.migrateService = migrate.service;
349
- else issues.error("migrate-invalid", `${path}.migrate.service`, "`migrate.service` must be the name of a service in this file.", "Name your web or worker service, or remove the line to use the web service.");
350
- return parsed;
351
- }
352
- function parseHealth(name, role, health, issues) {
353
- const path = `services.${name}.${X_HAPPYVERTICAL_KEY}.health`;
354
- if (health === void 0) {
355
- issues.error("health-missing", path, `Service \`${name}\` has no health check, so the platform cannot tell when it is ready.`, role === "web" ? "Add `health:` with a `path` that answers 200 when the app is ready, for example `path: /api/health`." : "Add `health:` with a `command` list that exits 0 when the worker is ready.", name);
356
- return;
357
- }
358
- if (!isRecord(health)) {
359
- issues.error("health-invalid", path, `The health check of \`${name}\` must be a mapping with either \`path\` or \`command\`.`, "Write `health:` followed by an indented `path:` or `command:`.", name);
360
- return;
361
- }
362
- const extra = unknownFields(health, HEALTH_FIELDS);
363
- if (extra.length > 0) {
364
- issues.error("health-invalid", `${path}.${extra[0]}`, `\`${extra[0]}\` is not a field of a health check.`, `Remove it or fix the spelling. A health check takes ${quoteList(HEALTH_FIELDS)}.`, name);
365
- return;
366
- }
367
- const hasPath = health.path !== void 0;
368
- if (hasPath === (health.command !== void 0)) {
369
- issues.error("health-invalid", path, hasPath ? `The health check of \`${name}\` has both \`path\` and \`command\`.` : `The health check of \`${name}\` is empty.`, "Keep exactly one: `path` for an HTTP check, or `command` for a check run inside the container.", name);
370
- return;
371
- }
372
- if (hasPath) {
373
- if (role === "worker") {
374
- issues.error("worker-health-needs-command", `${path}.path`, `Worker \`${name}\` has an HTTP health path, but workers do not serve HTTP.`, "Use `command:` with a list that exits 0 when the worker is ready.", name);
375
- return;
376
- }
377
- if (typeof health.path !== "string" || !HEALTH_PATH.test(health.path)) {
378
- issues.error("health-invalid", `${path}.path`, `The health path of \`${name}\` must start with \`/\` and contain no spaces.`, "Write a path such as `/api/health`.", name);
379
- return;
380
- }
381
- if (refuseVariables([health.path], `${path}.path`, `The health path of \`${name}\``, issues, name)) return;
382
- return { path: health.path };
383
- }
384
- if (!isStringList(health.command)) {
385
- issues.error("health-invalid", `${path}.command`, `The health command of \`${name}\` must be a list with one argument per item.`, "Write it as a list, for example `command: [\"pnpm\", \"exec\", \"smrt\", \"app\", \"doctor\"]`.", name);
386
- return;
387
- }
388
- if (refuseVariables(health.command, `${path}.command`, `The health command of \`${name}\``, issues, name)) return;
389
- return { command: [...health.command] };
390
- }
391
- function parseCommand(name, field, value, issues) {
392
- if (value === void 0 || value === null) return void 0;
393
- if (Array.isArray(value) && value.length === 0 || typeof value === "string" && value.trim() === "") return [];
394
- const path = `services.${name}.${field}`;
395
- const what = `The \`${field}\` of \`${name}\``;
396
- if (isStringList(value)) return refuseVariables(value, path, what, issues, name) ? void 0 : [...value];
397
- if (typeof value === "string") {
398
- if (refuseVariables([value], path, what, issues, name)) return void 0;
399
- if (PLAIN_COMMAND.test(value.trim())) return value.trim().split(/ +/);
400
- }
401
- issues.error("command-not-list", `services.${name}.${field}`, `The \`${field}\` of \`${name}\` uses quoting or shell syntax, or is not text, which Compose and the platform would read differently.`, `Write \`${field}\` as a list with one argument per item, for example \`["node", "build"]\`.`, name);
402
- }
403
- function scanPortEntry(name, field, entry, index, issues) {
404
- const path = `services.${name}.${field}[${index}]`;
405
- const invalid = (reason) => {
406
- issues.error("ingress-port-invalid", path, `Port entry \`${describe(entry)}\` of \`${name}\` ${reason}.`, "Publish one fixed TCP port, for example `\"3000:3000\"`.", name);
407
- };
408
- if (typeof entry === "number") return Number.isInteger(entry) && entry > 0 && entry < 65536 ? entry : invalid("is not a valid port number");
409
- if (typeof entry === "string") {
410
- const [address, protocol] = entry.replace(INTERPOLATION, "\0").split("/");
411
- if (protocol !== void 0 && protocol.toLowerCase() !== "tcp") return invalid("is not TCP");
412
- const container = address.split(":").at(-1) ?? "";
413
- if (!/^\d+$/.test(container)) return invalid(container.includes("-") ? "is a port range" : "does not name a fixed container port");
414
- const port = Number(container);
415
- return port > 0 && port < 65536 ? port : invalid("is not a valid port number");
416
- }
417
- if (isRecord(entry)) {
418
- if (entry.mode !== void 0 && entry.mode !== "ingress") {
419
- issues.error("host-network", path, `Service \`${name}\` publishes a port in \`${describe(entry.mode)}\` mode, which binds it to the network of the machine it runs on.`, "Remove the `mode` line. The platform routes traffic to the container for you.", name);
420
- return;
421
- }
422
- if (entry.protocol !== void 0 && !(typeof entry.protocol === "string" && entry.protocol.toLowerCase() === "tcp")) return invalid("is not TCP");
423
- const target = typeof entry.target === "number" ? entry.target : typeof entry.target === "string" && /^\d+$/.test(entry.target) ? Number(entry.target) : NaN;
424
- return Number.isInteger(target) && target > 0 && target < 65536 ? target : invalid("does not name a fixed container port in `target`");
425
- }
426
- return invalid("is not a port");
427
- }
428
- function scanPorts(name, field, value, issues) {
429
- if (value === void 0 || value === null) return {
430
- ports: [],
431
- invalid: false
432
- };
433
- if (!Array.isArray(value)) {
434
- issues.error("ingress-port-invalid", `services.${name}.${field}`, `\`${field}\` of \`${name}\` must be a list.`, "Publish one fixed TCP port, for example `ports: [\"3000:3000\"]`.", name);
435
- return {
436
- ports: [],
437
- invalid: true
438
- };
439
- }
440
- const before = issues.errors.length;
441
- const ports = /* @__PURE__ */ new Set();
442
- value.forEach((entry, index) => {
443
- const port = scanPortEntry(name, field, entry, index, issues);
444
- if (port !== void 0) ports.add(port);
445
- });
446
- return {
447
- ports: [...ports],
448
- invalid: issues.errors.length > before
449
- };
450
- }
451
- function isHostPath(source) {
452
- return source.startsWith(".") || source.startsWith("/") || source.startsWith("~") || source.includes("$") || source.includes("\\") || /^[A-Za-z]:/.test(source);
453
- }
454
- function scanVolumes(name, service, declared, issues) {
455
- const volumes = [];
456
- const notDeclared = (path, what) => {
457
- issues.error("volume-not-declared", path, `Service \`${name}\` ${what}. The platform only keeps data in volumes the file declares.`, "Declare a named volume under top-level `volumes:` and mount it as `name:/path/in/container`. Files the app needs belong in its image.", name);
458
- };
459
- const useNamed = (path, source, target, readOnly) => {
460
- if (!Object.hasOwn(declared, source)) {
461
- notDeclared(path, `mounts the volume \`${source}\`, which is not declared in this file`);
462
- return;
463
- }
464
- const definition = declared[source];
465
- if (isRecord(definition)) {
466
- const external = definition.external !== void 0 && definition.external !== false;
467
- const customDriver = definition.driver !== void 0 && definition.driver !== "local";
468
- if (external || customDriver || definition.driver_opts !== void 0) {
469
- issues.error("volume-not-plain", `volumes.${source}`, `Volume \`${source}\` is external or uses driver options, so its contents live somewhere this file does not describe.`, "Declare it as a plain named volume (just `name:` with nothing under it).", name);
470
- return;
471
- }
472
- }
473
- if (refuseVariables([target], path, `The mount path of volume \`${source}\` in \`${name}\``, issues, name)) return;
474
- volumes.push({
475
- name: source,
476
- target,
477
- readOnly
478
- });
479
- };
480
- if (Array.isArray(service.volumes_from) ? service.volumes_from.length > 0 : service.volumes_from !== void 0 && service.volumes_from !== null) notDeclared(`services.${name}.volumes_from`, "borrows another container's volumes with `volumes_from`");
481
- const entries = service.volumes;
482
- if (entries === void 0 || entries === null) return volumes;
483
- if (!Array.isArray(entries)) {
484
- notDeclared(`services.${name}.volumes`, "has a `volumes` entry that is not a list");
485
- return volumes;
486
- }
487
- entries.forEach((entry, index) => {
488
- const path = `services.${name}.volumes[${index}]`;
489
- if (typeof entry === "string") {
490
- if (/^[A-Za-z]:[\\/]/.test(entry) || entry.includes("\\")) {
491
- notDeclared(path, `mounts \`${describe(entry)}\` from the machine it runs on (a bind mount)`);
492
- return;
493
- }
494
- const [source, target, mode] = entry.split(":");
495
- if (target === void 0) notDeclared(path, `mounts an unnamed volume at \`${entry}\``);
496
- else if (isHostPath(source)) notDeclared(path, `mounts \`${source}\` from the machine it runs on (a bind mount)`);
497
- else useNamed(path, source, target, (mode ?? "").split(",").includes("ro"));
498
- return;
499
- }
500
- if (isRecord(entry)) {
501
- const type = entry.type ?? "volume";
502
- if (type === "tmpfs") return;
503
- if (type !== "volume") {
504
- notDeclared(path, `uses a \`${describe(type)}\` mount, which reads from the machine it runs on`);
505
- return;
506
- }
507
- if (typeof entry.source !== "string" || entry.source.length === 0) {
508
- notDeclared(path, "mounts an unnamed volume");
509
- return;
510
- }
511
- if (typeof entry.target !== "string" || entry.target.length === 0) {
512
- notDeclared(path, "has a volume entry with no `target` path");
513
- return;
514
- }
515
- useNamed(path, entry.source, entry.target, entry.read_only !== void 0 && entry.read_only !== false);
516
- return;
517
- }
518
- notDeclared(path, "has a volume entry that is not a mount");
519
- });
520
- return volumes;
521
- }
522
- function resolveImage(entry, options, stage, issues) {
523
- const { name, definition } = entry;
524
- const declared = typeof definition.image === "string" && definition.image.length > 0 ? definition.image : void 0;
525
- const hasBuild = definition.build !== void 0 && definition.build !== null;
526
- const supplied = options.images && Object.hasOwn(options.images, name) ? options.images[name] : void 0;
527
- if (declared === void 0 && !hasBuild) issues.error("service-no-image", `services.${name}`, `Service \`${name}\` has neither \`image\` nor \`build\`, so nothing can run it.`, "Add `build: .` to build it locally, or `image:` with the image to run.", name);
528
- if (stage === "declare") {
529
- const image = supplied ?? declared;
530
- return image !== void 0 && isLiteral(image) ? image : void 0;
531
- }
532
- const effective = supplied ?? declared;
533
- if (effective !== void 0 && DIGEST_IMAGE.test(effective)) return effective;
534
- issues.error("image-not-digest", `services.${name}.image`, effective === void 0 ? `Service \`${name}\` is only built locally. The platform deploys an image that CI already built and pushed; it never runs \`build:\`.` : `The image of \`${name}\` (\`${effective}\`) is a tag, which can change after it was tested. The platform deploys exact image digests only.`, `Supply the digest CI pushed for \`${name}\`, in the form \`registry/name@sha256:\` followed by 64 hex characters.`, name);
535
- }
536
- function checkRoleService(entry, declaredVolumes, options, stage, issues) {
537
- const { name, role, definition } = entry;
538
- const before = issues.errors.length;
539
- if (definition.extends !== void 0) issues.error("not-self-contained", `services.${name}.extends`, `Service \`${name}\` takes part of its definition from another service with \`extends\`, so what it runs is not written here.`, "Write the service out in full. The platform reads each service as written, in this one file.", name);
540
- const image = resolveImage(entry, options, stage, issues);
541
- if (definition.privileged !== void 0 && definition.privileged !== null && definition.privileged !== false) issues.error("privileged", `services.${name}.privileged`, `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.`, "Remove the `privileged` line. The platform never runs privileged containers.", name);
542
- if (definition.network_mode === "host") issues.error("host-network", `services.${name}.network_mode`, `Service \`${name}\` uses the host's network instead of its own.`, "Remove `network_mode: host`. Services reach each other by service name, and the platform routes outside traffic to the web service.", name);
543
- const volumes = scanVolumes(name, definition, declaredVolumes, issues);
544
- const entrypoint = parseCommand(name, "entrypoint", definition.entrypoint, issues);
545
- const command = parseCommand(name, "command", definition.command, issues);
546
- let port;
547
- const publishesNothing = definition.ports === void 0 || definition.ports === null || Array.isArray(definition.ports) && definition.ports.length === 0;
548
- const published = role === "web" ? scanPorts(name, "ports", definition.ports, issues) : {
549
- ports: [],
550
- invalid: false
551
- };
552
- if (role === "web") {
553
- const exposed = published.ports.length === 0 && !published.invalid ? scanPorts(name, "expose", definition.expose, issues) : {
554
- ports: [],
555
- invalid: false
556
- };
557
- const ports = published.ports.length > 0 ? published.ports : exposed.ports;
558
- if (!published.invalid && !exposed.invalid && ports.length !== 1) issues.error("ingress-port-count", `services.${name}.ports`, ports.length === 0 ? `Web service \`${name}\` publishes no port, so there is nothing to send visitors to.` : `Web service \`${name}\` publishes ${ports.length} ports (${ports.join(", ")}). The platform routes visitors to exactly one.`, "Publish exactly one port, the one the app listens on, for example `ports: [\"3000:3000\"]`.", name);
559
- port = ports[0];
560
- } else if (!publishesNothing) issues.error("worker-publishes-port", `services.${name}.ports`, `Worker \`${name}\` publishes a port, but only the web service receives traffic.`, "Remove `ports` from the worker, or give the service `role: web` if it is the one visitors reach.", name);
561
- if (issues.errors.length > before || entry.health === void 0) return;
562
- return {
563
- name,
564
- role,
565
- ...image !== void 0 ? { image } : {},
566
- ...entrypoint ? { entrypoint } : {},
567
- ...command ? { command } : {},
568
- ...port !== void 0 ? { port } : {},
569
- health: entry.health,
570
- volumes
571
- };
572
- }
573
- function validateComposeDeployment(document, options = {}) {
574
- const issues = new IssueCollector();
575
- const stage = options.stage ?? "declare";
576
- const finish = (declaration) => ({
577
- ok: issues.errors.length === 0,
578
- errors: issues.errors,
579
- warnings: issues.warnings,
580
- ...issues.errors.length === 0 && declaration ? { declaration } : {}
581
- });
582
- if (!isRecord(document)) {
583
- issues.error("document-invalid", "", "This is not a Compose file: the top level must be a mapping with `services`.", "Check that the file is valid YAML and starts with top-level keys such as `services:`.");
584
- return finish();
585
- }
586
- const mergeKey = findMergeKey(document);
587
- if (mergeKey !== void 0) {
588
- issues.error("merge-key-unresolved", mergeKey, "The file still contains a YAML merge key (`<<`), so the part of it that comes from an anchor was not read.", "Parse the file with YAML merge keys enabled, as Compose does (`smrt deploy:check` does this for you).");
589
- return finish();
590
- }
591
- if (document.include !== void 0) issues.error("not-self-contained", "include", "The file pulls in other Compose files with `include`.", "Put every service in this one file. The platform reads this file and nothing else.");
592
- const application = parseApplication(document, issues);
593
- const services = document.services;
594
- if (!isRecord(services) || Object.keys(services).length === 0) {
595
- issues.error("services-missing", "services", "The file declares no services.", "Add your application under `services:`, with at least a web service.");
596
- return finish();
597
- }
598
- const declaredVolumes = isRecord(document.volumes) ? document.volumes : {};
599
- const roleServices = [];
600
- const bindings = [];
601
- const localOnly = [];
602
- for (const [name, definition] of Object.entries(services)) {
603
- if (!isRecord(definition)) {
604
- issues.error("service-invalid", `services.${name}`, `Service \`${name}\` is empty or not a mapping.`, "Give it an `image` or `build` and the settings it needs, or remove it.", name);
605
- continue;
606
- }
607
- const annotationPath = `services.${name}.${X_HAPPYVERTICAL_KEY}`;
608
- const annotation = definition[X_HAPPYVERTICAL_KEY];
609
- if (annotation === void 0) {
610
- localOnly.push(name);
611
- continue;
612
- }
613
- if (!isRecord(annotation)) {
614
- issues.error("annotation-invalid", annotationPath, `The \`${X_HAPPYVERTICAL_KEY}\` block of \`${name}\` must be a mapping.`, "Write `role: web` or `role: worker` with a `health` check, or `binding:` with the platform service it stands in for.", name);
615
- continue;
616
- }
617
- const extra = unknownFields(annotation, SERVICE_FIELDS);
618
- if (extra.length > 0) {
619
- issues.error("annotation-invalid", `${annotationPath}.${extra[0]}`, `\`${extra[0]}\` is not a field of a service annotation.`, `Remove it or fix the spelling. A service takes ${quoteList(SERVICE_FIELDS)}.`, name);
620
- continue;
621
- }
622
- const hasRole = annotation.role !== void 0;
623
- const hasBinding = annotation.binding !== void 0;
624
- if (hasRole && hasBinding) {
625
- issues.error("role-and-binding", annotationPath, `Service \`${name}\` has both \`role\` and \`binding\`. A service is either part of your application or a stand-in for a platform service.`, "Keep `role` for something you build and run, or `binding` for something the platform provides.", name);
626
- continue;
627
- }
628
- if (!hasRole && !hasBinding) {
629
- issues.error("annotation-invalid", annotationPath, `The \`${X_HAPPYVERTICAL_KEY}\` block of \`${name}\` says neither what the service is nor what it stands in for.`, "Add `role: web`, `role: worker`, or `binding:`. Remove the block if the service is only for local use.", name);
630
- continue;
631
- }
632
- if (!SERVICE_NAME.test(name)) issues.error("service-name-invalid", `services.${name}`, `The service name \`${name}\` cannot be used as a platform resource name.`, "Rename it using lowercase letters, digits and hyphens, starting with a letter, at most 31 characters.", name);
633
- if (hasBinding) {
634
- const kind = annotation.binding;
635
- if (typeof kind !== "string" || !X_HAPPYVERTICAL_BINDINGS.includes(kind)) {
636
- issues.error("binding-unknown", `${annotationPath}.binding`, `\`${describe(kind)}\` is not a platform service this contract knows.`, `Set \`binding\` to one of: ${quoteList(X_HAPPYVERTICAL_BINDINGS)}.`, name);
637
- continue;
638
- }
639
- if (annotation.health !== void 0) issues.error("binding-with-health", `${annotationPath}.health`, `Binding \`${name}\` has a \`health\` check, but the platform runs its own service in place of this container.`, "Remove `health` from the annotation. A Compose `healthcheck:` on the service is fine for local use.", name);
640
- const hasImage = typeof definition.image === "string" && definition.image.length > 0;
641
- const hasBuild = definition.build !== void 0 && definition.build !== null;
642
- if (!hasImage && !hasBuild) issues.error("binding-no-local-image", `services.${name}.image`, `Binding \`${name}\` has no local image, so the stack cannot run anywhere the platform is not providing ${kind}.`, "Add the image you run locally, for example `image: postgres:18-alpine`, so the file stays a complete working stack on its own.", name);
643
- const duplicate = bindings.find((binding) => binding.kind === kind);
644
- if (duplicate) {
645
- issues.error("binding-duplicate", `${annotationPath}.binding`, `Services \`${duplicate.name}\` and \`${name}\` both stand in for \`${kind}\`. Version 1 binds each platform service once.`, `Keep one \`${kind}\` binding.`, name);
646
- continue;
647
- }
648
- bindings.push({
649
- name,
650
- kind
651
- });
652
- continue;
653
- }
654
- const role = annotation.role;
655
- if (typeof role !== "string" || !X_HAPPYVERTICAL_ROLES.includes(role)) {
656
- issues.error("role-unknown", `${annotationPath}.role`, `\`${describe(role)}\` is not a role.`, `Set \`role\` to one of: ${quoteList(X_HAPPYVERTICAL_ROLES)}.`, name);
657
- continue;
658
- }
659
- roleServices.push({
660
- name,
661
- role,
662
- definition,
663
- health: parseHealth(name, role, annotation.health, issues)
664
- });
665
- }
666
- const webServices = roleServices.filter((entry) => entry.role === "web");
667
- if (webServices.length !== 1) issues.error("web-service-count", "services", webServices.length === 0 ? "No service has `role: web`, so there is nothing for visitors to reach." : `${webServices.length} services have \`role: web\` (${quoteList(webServices.map((entry) => entry.name))}). The platform routes visitors to exactly one.`, "Give exactly one service `role: web`. Anything else you run is `role: worker`.");
668
- const workloads = [];
669
- for (const entry of roleServices) {
670
- const workload = checkRoleService(entry, declaredVolumes, options, stage, issues);
671
- if (workload) workloads.push(workload);
672
- }
673
- for (const name of Object.keys(options.images ?? {})) if (!roleServices.some((entry) => entry.name === name)) issues.error("image-for-unknown-service", `services.${name}`, `An image digest was supplied for \`${name}\`, which is not a web or worker service in this file.`, `Supply digests only for: ${quoteList(roleServices.map((entry) => entry.name))}.`, name);
674
- const migrateService = application.migrateService ?? webServices[0]?.name;
675
- if (application.migrateService !== void 0 && !roleServices.some((entry) => entry.name === application.migrateService)) issues.error("migrate-service-not-role", `${X_HAPPYVERTICAL_KEY}.migrate.service`, `\`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.`, `Name one of: ${quoteList(roleServices.map((entry) => entry.name))}, or remove the line to use the web service.`);
676
- for (const name of localOnly) issues.warning("local-only-service", `services.${name}`, `Service \`${name}\` has no \`${X_HAPPYVERTICAL_KEY}\` annotation. It runs on your machine only; the platform will not run it.`, "Nothing to do if that is intended. Otherwise give it `role: web`, `role: worker` or a `binding`.", name);
677
- if (issues.errors.length > 0 || application.preset === void 0 || application.migrateCommand === void 0 || migrateService === void 0) return finish();
678
- const migrateImage = workloads.find((workload) => workload.name === migrateService)?.image;
679
- return finish({
680
- version: 1,
681
- preset: application.preset,
682
- stage,
683
- ...typeof document.name === "string" && document.name.length > 0 && isLiteral(document.name) ? { name: document.name } : {},
684
- ...application.domain !== void 0 ? { domain: application.domain } : {},
685
- migrate: {
686
- service: migrateService,
687
- command: application.migrateCommand,
688
- ...migrateImage !== void 0 ? { image: migrateImage } : {}
689
- },
690
- workloads,
691
- bindings,
692
- localOnly
693
- });
694
- }
695
- function formatIssue(issue, index) {
696
- const where = issue.path ? `${issue.path}: ` : "";
697
- return `${index + 1}. ${where}${issue.message}
698
- Fix: ${issue.fix}`;
699
- }
700
- function formatComposeDeploymentReport(result) {
701
- const lines = [];
702
- if (result.ok) {
703
- lines.push("The deployment declaration is valid.");
704
- const declaration = result.declaration;
705
- if (declaration) {
706
- const describe2 = (workload) => workload.port !== void 0 ? `${workload.name} (${workload.role}, port ${workload.port})` : `${workload.name} (${workload.role})`;
707
- lines.push(`Preset: ${declaration.preset}`, `Runs: ${declaration.workloads.map(describe2).join(", ")}`, `Migration: ${declaration.migrate.command.join(" ")} (in the ${declaration.migrate.service} image)`, `Platform services: ${declaration.bindings.length > 0 ? declaration.bindings.map((binding) => `${binding.kind} (local: ${binding.name})`).join(", ") : "none"}`);
708
- if (declaration.domain) lines.push(`Domain: ${declaration.domain}`);
709
- }
710
- } else {
711
- const count = result.errors.length;
712
- lines.push(`The deployment declaration has ${count} problem${count === 1 ? "" : "s"}.`, "", ...result.errors.map(formatIssue));
713
- }
714
- if (result.warnings.length > 0) lines.push("", `Runs only on your machine (the platform will not run it): ${result.warnings.map((warning) => warning.service ?? warning.path).join(", ")}`);
715
- return lines.join("\n");
716
- }
717
- //#endregion
718
- export { SMRT_RELEASE_GUARD, SmrtAppChartValuesError, X_HAPPYVERTICAL_BINDINGS, X_HAPPYVERTICAL_KEY, X_HAPPYVERTICAL_PRESETS, X_HAPPYVERTICAL_ROLES, X_HAPPYVERTICAL_SCHEMA_ID, X_HAPPYVERTICAL_VERSION, formatComposeDeploymentReport, renderSmrtAppChartValues, validateComposeDeployment };
216
+ export { HOSTED_APP_API_VERSION, HOSTED_APP_KIND, HOSTED_APP_NAME_MAX_LENGTH, HOSTED_APP_PRESET, HOSTED_APP_TIERS, HOSTED_APP_WORKER_ROLES, SMRT_RELEASE_GUARD, SmrtAppChartValuesError, X_HAPPYVERTICAL_BINDINGS, X_HAPPYVERTICAL_KEY, X_HAPPYVERTICAL_PRESETS, X_HAPPYVERTICAL_ROLES, X_HAPPYVERTICAL_SCHEMA_ID, X_HAPPYVERTICAL_VERSION, composeHostedApp, formatComposeDeploymentReport, hostedAppReleaseId, isHostedAppCommit, renderSmrtAppChartValues, validateComposeDeployment };
719
217
 
720
218
  //# sourceMappingURL=deployment.js.map