@tailor-platform/sdk 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +199 -0
  2. package/{dist/cli/index.mjs → bin/tailor.mjs} +1 -1
  3. package/dist/application-BZfk4HKm.mjs +3 -0
  4. package/dist/{application-D77KJFKD.mjs → application-F-nl107y.mjs} +121 -27
  5. package/dist/application-F-nl107y.mjs.map +1 -0
  6. package/dist/cli/commands/deploy/tailordb/index.d.mts +2 -1
  7. package/dist/cli/commands/deploy/types.d.mts +2 -1
  8. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +52 -22
  9. package/dist/cli/commands/tailordb/migrate/file-state.d.mts +1 -0
  10. package/dist/cli/commands/tailordb/migrate/generate.d.mts +6 -0
  11. package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +22 -0
  12. package/dist/cli/commands/tailordb/migrate/schema-checks.d.mts +2 -2
  13. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +9 -2
  14. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +30 -9
  15. package/dist/cli/lib.d.mts +4 -4
  16. package/dist/cli/lib.mjs +3 -482
  17. package/dist/cli/lib.mjs.map +1 -1
  18. package/dist/cli/main.mjs +1151 -208
  19. package/dist/cli/main.mjs.map +1 -1
  20. package/dist/cli/ts-hook.mjs +52 -7
  21. package/dist/completion/zsh-worker.zsh +167 -4
  22. package/dist/configure/index.d.mts +3 -3
  23. package/dist/configure/index.mjs +90 -23
  24. package/dist/configure/index.mjs.map +1 -1
  25. package/dist/configure/services/index.d.mts +3 -2
  26. package/dist/configure/services/tailordb/index.d.mts +2 -1
  27. package/dist/configure/services/tailordb/schema.d.mts +46 -46
  28. package/dist/configure/services/tailordb/types.d.mts +30 -4
  29. package/dist/configure/services/workflow/index.d.mts +2 -2
  30. package/dist/configure/services/workflow/wait-point.d.mts +72 -13
  31. package/dist/{crashreport-B5LqCTfF.mjs → crashreport-CIIfLnoO.mjs} +2 -2
  32. package/dist/{crashreport-B5LqCTfF.mjs.map → crashreport-CIIfLnoO.mjs.map} +1 -1
  33. package/dist/{crashreport-eI7ty7ok.mjs → crashreport-CINZ5dVN.mjs} +1 -1
  34. package/dist/errors-BVb6vYGy.mjs +89 -0
  35. package/dist/errors-BVb6vYGy.mjs.map +1 -0
  36. package/dist/kysely/index.d.mts +53 -5
  37. package/dist/kysely/index.mjs +7 -2
  38. package/dist/kysely/index.mjs.map +1 -1
  39. package/dist/{logger-CXQq9YIp.mjs → logger-DSdExfor.mjs} +83 -42
  40. package/dist/logger-DSdExfor.mjs.map +1 -0
  41. package/dist/plugin/builtin/seed/index.mjs +1 -1
  42. package/dist/{register-ts-hook-BU18uU44.mjs → register-ts-hook-ClI226n2.mjs} +3541 -703
  43. package/dist/register-ts-hook-ClI226n2.mjs.map +1 -0
  44. package/dist/schema--xYWRGfe.mjs.map +1 -1
  45. package/dist/seed/index.d.mts +52 -3
  46. package/dist/seed/index.mjs +200 -44
  47. package/dist/seed/index.mjs.map +1 -1
  48. package/dist/{seed-B-yckgQY.mjs → seed-xqM9WIHP.mjs} +8 -8
  49. package/dist/seed-xqM9WIHP.mjs.map +1 -0
  50. package/dist/{service-k1xy_A5G.mjs → service-C_WpbKHu.mjs} +39 -5
  51. package/dist/service-C_WpbKHu.mjs.map +1 -0
  52. package/dist/service-D1RCdzIL.mjs +3 -0
  53. package/dist/{service-B5WynBHQ.mjs → service-hZskxZmg.mjs} +3 -3
  54. package/dist/{service-B5WynBHQ.mjs.map → service-hZskxZmg.mjs.map} +1 -1
  55. package/dist/{service_pb-D5--My_M.mjs → service_pb-BEWj1pOV.mjs} +2 -2
  56. package/dist/{service_pb-D5--My_M.mjs.map → service_pb-BEWj1pOV.mjs.map} +1 -1
  57. package/dist/{service_pb-i8CmnQP4.mjs → service_pb-BjlhvK9E.mjs} +1 -1
  58. package/dist/utils/test/index.d.mts +6 -3
  59. package/dist/utils/test/index.mjs +25 -13
  60. package/dist/utils/test/index.mjs.map +1 -1
  61. package/dist/vitest/index.d.mts +2 -1
  62. package/dist/vitest/index.mjs +167 -3
  63. package/dist/vitest/index.mjs.map +1 -1
  64. package/dist/vitest/mocks/workflow.d.mts +13 -1
  65. package/dist/vitest/pglite-kysely.d.mts +43 -0
  66. package/dist/wait-point-invoker-__oE88_P.mjs +148 -0
  67. package/dist/wait-point-invoker-__oE88_P.mjs.map +1 -0
  68. package/dist/wait-point-registry-TL99zotw.mjs +47 -0
  69. package/dist/wait-point-registry-TL99zotw.mjs.map +1 -0
  70. package/dist/{workspace_resource_pb-DXnO2AT-.mjs → workspace_resource_pb-HNIL_Vfj.mjs} +10 -2
  71. package/dist/{workspace_resource_pb-DXnO2AT-.mjs.map → workspace_resource_pb-HNIL_Vfj.mjs.map} +1 -1
  72. package/docs/cli/setup.md +14 -1
  73. package/docs/cli/tailordb.md +96 -28
  74. package/docs/cli-reference.md +15 -12
  75. package/docs/configuration.md +1 -1
  76. package/docs/github-actions.md +73 -28
  77. package/docs/migration/v2.md +55 -1
  78. package/docs/plugin/custom.md +48 -48
  79. package/docs/plugin/index.md +24 -24
  80. package/docs/services/auth.md +10 -10
  81. package/docs/services/executor.md +1 -1
  82. package/docs/services/resolver.md +2 -2
  83. package/docs/services/tailordb-migration.md +485 -84
  84. package/docs/services/tailordb.md +28 -28
  85. package/docs/services/workflow.md +52 -2
  86. package/docs/testing.md +14 -0
  87. package/package.json +12 -7
  88. package/dist/application-Af1zIqSI.mjs +0 -3
  89. package/dist/application-D77KJFKD.mjs.map +0 -1
  90. package/dist/errors-D7583Zz7.mjs +0 -58
  91. package/dist/errors-D7583Zz7.mjs.map +0 -1
  92. package/dist/logger-CXQq9YIp.mjs.map +0 -1
  93. package/dist/register-ts-hook-BU18uU44.mjs.map +0 -1
  94. package/dist/seed-B-yckgQY.mjs.map +0 -1
  95. package/dist/service-M7OYziQP.mjs +0 -3
  96. package/dist/service-k1xy_A5G.mjs.map +0 -1
  97. package/dist/test-env-key-D7UkZp99.mjs +0 -75
  98. package/dist/test-env-key-D7UkZp99.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"main.mjs","names":["CLIError","listCommand","listCommand","randomState","listCommand","listCommand","listCommand","getCommand","getCommand","listCommand","detectPackageManager","listCommand","tokenCommand","listCommand","getCommand","createCommand","deleteCommand","getCommand","listCommand","updateCommand","getCommand","listCommand","updateCommand","listCommand","listCommand","createCommand","deleteCommand","listCommand","updateCommand","createCommand","deleteCommand","listCommand","updateCommand","createCommand","deleteCommand","listCommand","createCommand","deleteCommand","listCommand","branchTemplate","tagTemplate","previewTemplate","actionTemplate","coordinateTemplate","defaultLoadErdNamespaces","defaultLoadHasMigrations","defaultLoadHasSeeds","defaultLoadHasStaticWebsites","escapesRoot","resolve","deleteCommand","listCommand","deployCommand","listCommand","generateCommand","listCommand","userCommand","listCommand","listCommand","getCommand","listCommand","listCommand","updateCommand","createCommand","deleteCommand","getCommand","listCommand","removeCommand","userCommand"],"sources":["../../src/cli/commands/api/proto-reflect.ts","../../src/cli/commands/api/render.ts","../../src/cli/commands/api/inspect.ts","../../src/cli/commands/api/list.ts","../../src/cli/commands/api/index.ts","../../src/cli/commands/auth/token.ts","../../src/cli/commands/auth/index.ts","../../src/cli/commands/authconnection/args.ts","../../src/cli/commands/authconnection/authorize.ts","../../src/cli/commands/authconnection/delete.ts","../../src/cli/commands/authconnection/list.ts","../../src/cli/commands/authconnection/open.ts","../../src/cli/commands/authconnection/revoke.ts","../../src/cli/commands/authconnection/index.ts","../../src/cli/commands/crashreport/list.ts","../../src/cli/commands/crashreport/send.ts","../../src/cli/commands/crashreport/index.ts","../../src/cli/commands/deploy/index.ts","../../src/cli/commands/executor/index.ts","../../src/cli/shared/function-script-download.ts","../../src/cli/shared/stack-trace.ts","../../src/cli/commands/function/logs.ts","../../src/cli/commands/function/bundle.ts","../../src/cli/commands/function/detect.ts","../../src/cli/commands/function/test-run.ts","../../src/cli/commands/function/index.ts","../../src/cli/commands/generate/index.ts","../../src/cli/commands/init.ts","../../src/cli/commands/login.ts","../../src/cli/commands/logout.ts","../../src/cli/commands/machineuser/index.ts","../../src/cli/commands/oauth2client/index.ts","../../src/cli/commands/open.ts","../../src/cli/commands/organization/folder/index.ts","../../src/cli/commands/organization/index.ts","../../src/cli/shared/builtin-commands.ts","../../src/cli/shared/plugin.ts","../../src/cli/commands/plugin/list.ts","../../src/cli/commands/plugin/index.ts","../../src/cli/commands/profile/create.ts","../../src/cli/commands/profile/delete.ts","../../src/cli/commands/profile/list.ts","../../src/cli/commands/profile/update.ts","../../src/cli/commands/profile/index.ts","../../src/cli/commands/secret/args.ts","../../src/cli/commands/secret/check-vault-managed.ts","../../src/cli/commands/secret/create.ts","../../src/cli/commands/secret/delete.ts","../../src/cli/commands/secret/list.ts","../../src/cli/commands/secret/update.ts","../../src/cli/commands/secret/vault/args.ts","../../src/cli/commands/secret/vault/create.ts","../../src/cli/commands/secret/vault/delete.ts","../../src/cli/commands/secret/vault/list.ts","../../src/cli/commands/secret/vault/index.ts","../../src/cli/commands/secret/index.ts","../../src/cli/commands/setup/git.ts","../../src/cli/commands/setup/lock.ts","../../src/cli/commands/setup/action.yml","../../src/cli/commands/setup/branch.workflow.yml","../../src/cli/commands/setup/coordinate.workflow.yml","../../src/cli/commands/setup/preview.workflow.yml","../../src/cli/commands/setup/tag.workflow.yml","../../src/cli/commands/setup/templates.ts","../../src/cli/commands/setup/generate.ts","../../src/cli/commands/setup/check.ts","../../src/cli/commands/setup/delete.ts","../../src/cli/commands/setup/index.ts","../../src/cli/commands/staticwebsite/domain/status.ts","../../src/cli/commands/staticwebsite/domain/get.ts","../../src/cli/commands/staticwebsite/domain/list.ts","../../src/cli/commands/staticwebsite/domain/index.ts","../../src/cli/commands/staticwebsite/get.ts","../../src/cli/commands/staticwebsite/list.ts","../../src/cli/commands/staticwebsite/index.ts","../../src/cli/commands/tailordb/migrate/script.ts","../../src/cli/commands/tailordb/migrate/remote-state.ts","../../src/cli/commands/tailordb/migrate/set.ts","../../src/cli/commands/tailordb/migrate/status.ts","../../src/cli/commands/tailordb/migrate/sync.ts","../../src/cli/commands/tailordb/migrate/validate.ts","../../src/cli/commands/tailordb/migrate/index.ts","../../src/cli/commands/tailordb/index.ts","../../src/cli/commands/upgrade/index.ts","../../src/cli/commands/user/current.ts","../../src/cli/commands/user/list.ts","../../src/cli/commands/user/pat/transform.ts","../../src/cli/commands/user/pat/user.ts","../../src/cli/commands/user/pat/create.ts","../../src/cli/commands/user/pat/delete.ts","../../src/cli/commands/user/pat/list.ts","../../src/cli/commands/user/pat/update.ts","../../src/cli/commands/user/pat/index.ts","../../src/cli/commands/user/switch.ts","../../src/cli/commands/user/index.ts","../../src/cli/commands/workflow/index.ts","../../src/cli/commands/workspace/app/index.ts","../../src/cli/commands/workspace/user/index.ts","../../src/cli/commands/workspace/index.ts","../../src/cli/main.ts"],"sourcesContent":["import { ScalarType } from \"@bufbuild/protobuf\";\nimport { OperatorService } from \"@tailor-platform/tailor-proto/service_pb\";\nimport type { DescField, DescMessage, DescMethodUnary } from \"@bufbuild/protobuf\";\n\n// `tailor api` issues a single JSON POST and reads one JSON response, so\n// only unary RPCs can be invoked. Streaming methods are filtered out of all\n// discovery surfaces (`api list`, `api inspect`). `OperatorService.methods`\n// is invariant at runtime, so we filter once and reuse — completion-script\n// generation walks every method and would otherwise re-filter per call.\nconst UNARY_METHODS: DescMethodUnary[] = OperatorService.methods.filter(\n (m): m is DescMethodUnary => m.methodKind === \"unary\",\n);\n\nexport function listMethodNames(): string[] {\n return UNARY_METHODS.map((m) => m.name).toSorted();\n}\n\n/**\n * Returns every accepted form of the `endpoint` positional — bare method name\n * and fully-qualified `service/Method`. politty's expand completion keys its\n * static table by the literal endpoint string, so both forms must appear in\n * `choices` or the user typing the fully-qualified name gets no `--field`\n * completion candidates back at TAB time.\n * @returns Sorted list of accepted endpoint values\n */\nexport function listMethodChoices(): string[] {\n return UNARY_METHODS.flatMap((m) => [m.name, `${OperatorService.typeName}/${m.name}`]).toSorted();\n}\n\nexport function getMethodDescriptor(methodName: string): DescMethodUnary | undefined {\n return UNARY_METHODS.find((m) => m.name === methodName);\n}\n\nexport function extractMethodName(endpoint: string): string {\n if (!endpoint.includes(\"/\")) return endpoint;\n return endpoint.split(\"/\").pop() ?? endpoint;\n}\n\n/**\n * Returns the nested message descriptor when the field is a message, a list of\n * messages, or a map with message values. Otherwise returns undefined.\n * @param field - The proto field descriptor to inspect\n * @returns The nested message descriptor, or undefined when the field isn't message-shaped\n */\nexport function nestedMessage(field: DescField): DescMessage | undefined {\n if (field.fieldKind === \"message\") return field.message;\n if (field.fieldKind === \"list\" && field.listKind === \"message\") return field.message;\n if (field.fieldKind === \"map\" && field.mapKind === \"message\") return field.message;\n return undefined;\n}\n\n/**\n * Most `google.protobuf.*` well-known types serialize as scalars in proto JSON\n * (Timestamp/Duration → RFC3339/duration string, FieldMask → comma-joined\n * string, *Value wrappers → underlying primitive, etc.), so we must not let\n * `--field` drill into their internal fields. Treating them as leaves keeps\n * the completion and the body shape consistent with what the server expects.\n * @param message - The proto message descriptor to inspect\n * @returns True when the message is a well-known type\n */\nfunction isWellKnownType(message: DescMessage): boolean {\n return message.typeName.startsWith(\"google.protobuf.\");\n}\n\n// Well-known types whose proto JSON shape is an object/array/null/arbitrary\n// value — they cannot be expressed by a single `--field key=value` string.\n// Drill-down would build the wrong shape, and a flat `key=foo` would send\n// \"foo\" where the server expects e.g. an object; we skip them entirely from\n// completion and from leaf resolution.\nconst UNREPRESENTABLE_WELL_KNOWN_TYPES = new Set([\n \"google.protobuf.Struct\",\n \"google.protobuf.Value\",\n \"google.protobuf.ListValue\",\n \"google.protobuf.NullValue\",\n \"google.protobuf.Any\",\n \"google.protobuf.Empty\",\n]);\n\n/**\n * @param message - The proto message descriptor to inspect\n * @returns True when the message is a well-known type that `--field` cannot represent\n */\nfunction isUnrepresentableWellKnownType(message: DescMessage): boolean {\n return UNREPRESENTABLE_WELL_KNOWN_TYPES.has(message.typeName);\n}\n\nexport interface FieldCompletionCandidate {\n value: string;\n description: string;\n}\n\n/**\n * Pre-enumerates every `--field` completion candidate for `methodName`,\n * walking the input message tree to produce a flat list that the shell can\n * prefix-filter at TAB time. Used by the `expand` completion variant so no\n * Node process is spawned per keystroke.\n *\n * For each leaf field, emits `key=` (key completion). Enum leaves additionally\n * emit `key=ENUM_VALUE` per value, bool leaves emit `key=true` and\n * `key=false`. For nested messages, emits `key.` (drill-down) and recurses.\n *\n * Returns an empty array when `methodName` is unknown so the `expand`\n * generator stays exception-free at script-generation time.\n * @param methodName - Name of the unary RPC whose input message is being walked\n * @returns Flat list of `{ value, description }` candidates\n */\nexport function enumerateAllFieldCompletions(methodName: string): FieldCompletionCandidate[] {\n const method = getMethodDescriptor(methodName);\n if (!method) return [];\n\n const candidates: FieldCompletionCandidate[] = [];\n const visited = new Set<DescMessage>();\n\n function walk(message: DescMessage, prefix: string): void {\n visited.add(message);\n for (const field of message.fields) {\n // `--field` uses `key=value` with dotted keys building nested objects;\n // it has no syntax for arrays or maps. Skip list/map fields so we don't\n // tab-complete a path that `setNestedPath` would silently turn into the\n // wrong shape (e.g. `subgraphs.name=x` → `{subgraphs:{name:\"x\"}}` when\n // the proto expects a repeated message).\n if (field.fieldKind === \"list\" || field.fieldKind === \"map\") continue;\n const fullKey = prefix + field.localName;\n if (field.fieldKind === \"message\") {\n if (isUnrepresentableWellKnownType(field.message)) continue;\n if (!isWellKnownType(field.message)) {\n const nested = field.message;\n candidates.push({ value: `${fullKey}.`, description: `${fullKey} (message)` });\n if (!visited.has(nested)) walk(nested, `${fullKey}.`);\n continue;\n }\n // Representable well-known types (Timestamp, Duration, FieldMask, …)\n // fall through to a single `key=` leaf since proto JSON serializes\n // them as a scalar string.\n }\n candidates.push({ value: `${fullKey}=`, description: `Set ${fullKey}` });\n if (field.fieldKind === \"enum\") {\n for (const v of field.enum.values) {\n candidates.push({ value: `${fullKey}=${v.name}`, description: v.name });\n }\n } else if (field.fieldKind === \"scalar\" && field.scalar === ScalarType.BOOL) {\n candidates.push({ value: `${fullKey}=true`, description: \"true\" });\n candidates.push({ value: `${fullKey}=false`, description: \"false\" });\n }\n }\n visited.delete(message);\n }\n\n walk(method.input, \"\");\n return candidates;\n}\n\n/**\n * Resolves the leaf `DescField` at a dotted `--field` path within an input\n * message tree. Returns undefined when any segment is missing or when a\n * non-leaf segment isn't a singular message — callers fall back to treating\n * the value as a string in that case.\n * @param input - The RPC input message descriptor\n * @param path - Dot-split path segments to follow (e.g. [\"application\", \"name\"])\n * @returns The leaf field descriptor, or undefined when the path doesn't resolve\n */\nexport function resolveLeafField(input: DescMessage, path: string[]): DescField | undefined {\n let message = input;\n for (let i = 0; i < path.length; i++) {\n const field = message.fields.find((f) => f.localName === path[i]);\n if (!field) return undefined;\n if (i === path.length - 1) {\n // Refuse to resolve a leaf inside an unrepresentable well-known type —\n // even if the user typed `payload=...` for a Struct field manually,\n // we don't want to claim a scalar shape we can't actually coerce.\n if (field.fieldKind === \"message\" && isUnrepresentableWellKnownType(field.message)) {\n return undefined;\n }\n return field;\n }\n // Mirror enumerateAllFieldCompletions: don't drill into list/map fields\n // or well-known types — `--field` cannot represent their internal shape.\n if (field.fieldKind !== \"message\") return undefined;\n if (isWellKnownType(field.message)) return undefined;\n message = field.message;\n }\n return undefined;\n}\n","import { ScalarType } from \"@bufbuild/protobuf\";\nimport { nestedMessage } from \"./proto-reflect\";\nimport type { DescEnum, DescField, DescMessage, DescMethodUnary } from \"@bufbuild/protobuf\";\n\nexport interface InspectMessageJson {\n typeName: string;\n fields: InspectFieldJson[];\n /** True when truncated to break a recursive type cycle. */\n recursive?: boolean;\n}\n\nexport interface InspectFieldJson {\n name: string;\n protoName: string;\n type: string;\n fieldKind: string;\n repeated: boolean;\n enumValues?: string[];\n /** Name of the proto `oneof` group this field belongs to, if any. */\n oneof?: string;\n message?: InspectMessageJson | undefined;\n}\n\nexport interface InspectMethodJson {\n method: string;\n input: {\n typeName: string;\n fields: InspectFieldJson[];\n };\n output: {\n typeName: string;\n };\n}\n\nconst SCALAR_LABEL: Partial<Record<number, string>> = {\n [ScalarType.DOUBLE]: \"double\",\n [ScalarType.FLOAT]: \"float\",\n [ScalarType.INT64]: \"int64\",\n [ScalarType.UINT64]: \"uint64\",\n [ScalarType.INT32]: \"int32\",\n [ScalarType.FIXED64]: \"fixed64\",\n [ScalarType.FIXED32]: \"fixed32\",\n [ScalarType.BOOL]: \"bool\",\n [ScalarType.STRING]: \"string\",\n [ScalarType.BYTES]: \"bytes\",\n [ScalarType.UINT32]: \"uint32\",\n [ScalarType.SFIXED32]: \"sfixed32\",\n [ScalarType.SFIXED64]: \"sfixed64\",\n [ScalarType.SINT32]: \"sint32\",\n [ScalarType.SINT64]: \"sint64\",\n};\n\nfunction shortName(typeName: string): string {\n const dot = typeName.lastIndexOf(\".\");\n return dot < 0 ? typeName : typeName.slice(dot + 1);\n}\n\nfunction scalarLabel(scalar: ScalarType): string {\n return SCALAR_LABEL[scalar] ?? `scalar(${scalar})`;\n}\n\nfunction enumLabel(enumDesc: DescEnum): string {\n return `enum ${shortName(enumDesc.typeName)}`;\n}\n\nfunction enumOf(field: DescField): DescEnum | undefined {\n if (field.fieldKind === \"enum\") return field.enum;\n if (field.fieldKind === \"list\" && field.listKind === \"enum\") return field.enum;\n return undefined;\n}\n\nexport function describeFieldType(field: DescField): string {\n switch (field.fieldKind) {\n case \"scalar\":\n return scalarLabel(field.scalar);\n case \"enum\":\n return enumLabel(field.enum);\n case \"message\":\n return shortName(field.message.typeName);\n case \"list\": {\n let inner: string;\n if (field.listKind === \"scalar\") {\n inner = scalarLabel(field.scalar);\n } else if (field.listKind === \"enum\") {\n inner = enumLabel(field.enum);\n } else {\n inner = shortName(field.message.typeName);\n }\n return `repeated ${inner}`;\n }\n case \"map\": {\n const keyType = scalarLabel(field.mapKey);\n let valType: string;\n if (field.mapKind === \"scalar\") valType = scalarLabel(field.scalar);\n else if (field.mapKind === \"enum\") valType = enumLabel(field.enum);\n else valType = shortName(field.message.typeName);\n return `map<${keyType}, ${valType}>`;\n }\n default:\n return \"<unknown>\";\n }\n}\n\nfunction fieldToJson(field: DescField, visited: Set<DescMessage>): InspectFieldJson {\n const json: InspectFieldJson = {\n name: field.localName,\n protoName: field.name,\n type: describeFieldType(field),\n fieldKind: field.fieldKind,\n repeated: field.fieldKind === \"list\",\n };\n\n if (field.oneof) json.oneof = field.oneof.name;\n\n const fieldEnum = enumOf(field);\n if (fieldEnum) {\n json.enumValues = fieldEnum.values.map((v) => v.name);\n }\n\n const nested = nestedMessage(field);\n if (nested && !visited.has(nested)) {\n visited.add(nested);\n json.message = {\n typeName: nested.typeName,\n fields: nested.fields.map((f) => fieldToJson(f, visited)),\n };\n visited.delete(nested);\n } else if (nested) {\n json.message = { typeName: nested.typeName, fields: [], recursive: true };\n }\n\n return json;\n}\n\nexport function renderInspectJson(method: DescMethodUnary): InspectMethodJson {\n const visited = new Set<DescMessage>([method.input]);\n return {\n method: method.name,\n input: {\n typeName: method.input.typeName,\n fields: method.input.fields.map((f) => fieldToJson(f, visited)),\n },\n output: { typeName: method.output.typeName },\n };\n}\n\nfunction renderFieldText(field: DescField, indent: string, visited: Set<DescMessage>): string[] {\n const lines: string[] = [];\n const oneofTag = field.oneof ? ` (oneof ${field.oneof.name})` : \"\";\n lines.push(`${indent}${field.localName}: ${describeFieldType(field)}${oneofTag}`);\n\n const fieldEnum = enumOf(field);\n if (fieldEnum) {\n const values = fieldEnum.values.map((v) => v.name).join(\", \");\n lines.push(`${indent} values: ${values}`);\n }\n\n const nested = nestedMessage(field);\n if (nested && !visited.has(nested)) {\n visited.add(nested);\n for (const sub of nested.fields) {\n lines.push(...renderFieldText(sub, `${indent} `, visited));\n }\n visited.delete(nested);\n } else if (nested) {\n lines.push(`${indent} …(recursive ${nested.typeName})`);\n }\n\n return lines;\n}\n\nexport function renderInspectText(method: DescMethodUnary): string {\n const lines: string[] = [];\n lines.push(`${method.name}`);\n lines.push(` request: ${method.input.typeName}`);\n const visited = new Set<DescMessage>([method.input]);\n for (const f of method.input.fields) {\n lines.push(...renderFieldText(f, \" \", visited));\n }\n lines.push(` response: ${method.output.typeName}`);\n return lines.join(\"\\n\");\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { CLIError } from \"#/cli/shared/errors\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { extractMethodName, getMethodDescriptor, listMethodNames } from \"./proto-reflect\";\nimport { renderInspectJson, renderInspectText } from \"./render\";\n\nexport const inspectCommand = defineAppCommand({\n name: \"inspect\",\n description: \"Print the input message tree of an OperatorService endpoint.\",\n notes:\n \"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.\",\n examples: [\n { cmd: \"GetApplication\", desc: \"Show fields of GetApplicationRequest.\" },\n {\n cmd: \"CreateExecutorExecutor\",\n desc: \"Inspect a deeply nested input with `(oneof config)` annotations.\",\n },\n ],\n args: z.strictObject({\n endpoint: arg(z.string(), {\n positional: true,\n description:\n \"API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').\",\n completion: { custom: { choices: listMethodNames() } },\n }),\n }),\n run: (args) => {\n const methodName = extractMethodName(args.endpoint);\n const method = getMethodDescriptor(methodName);\n if (!method) {\n throw CLIError({\n message: `unknown method: ${methodName}`,\n suggestion: \"Run `tailor api list` to see available methods.\",\n command: \"api inspect\",\n });\n }\n if (logger.jsonMode) {\n logger.out(renderInspectJson(method));\n } else {\n logger.out(renderInspectText(method));\n }\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { listMethodNames } from \"./proto-reflect\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all invocable OperatorService methods.\",\n notes:\n \"Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.\",\n args: z.strictObject({}),\n run: () => {\n const names = listMethodNames();\n if (logger.jsonMode) {\n logger.out(names);\n } else {\n for (const name of names) logger.out(name);\n }\n },\n});\n","import { ScalarType } from \"@bufbuild/protobuf\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { configArg, workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { apiCall } from \"./api-call\";\nimport { inspectCommand } from \"./inspect\";\nimport { listCommand } from \"./list\";\nimport {\n enumerateAllFieldCompletions,\n extractMethodName,\n getMethodDescriptor,\n listMethodChoices,\n resolveLeafField,\n} from \"./proto-reflect\";\nimport type { LoadedConfig } from \"#/cli/shared/config-loader\";\nimport type { DescField } from \"@bufbuild/protobuf\";\n\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./api-call\";\n\nfunction resolveNamespaceName(methodName: string, config: LoadedConfig): string | undefined {\n if (/Auth|Tenant|UserProfile/.test(methodName)) {\n return config.auth?.name;\n }\n if (/IdP/.test(methodName)) {\n if (config.idp?.length === 1) return assertDefined(config.idp[0], \"idp config missing\").name;\n return undefined;\n }\n if (/TailorDB/.test(methodName)) {\n const keys = Object.keys(config.db ?? {});\n if (keys.length === 1) return keys[0];\n return undefined;\n }\n if (/Pipeline/.test(methodName)) {\n const keys = Object.keys(config.resolver ?? {});\n if (keys.length === 1) return keys[0];\n return undefined;\n }\n return undefined;\n}\n\n/**\n * Parse a JSON body string as a plain object for field injection.\n * Returns undefined for invalid JSON or non-object values (null, arrays, primitives),\n * so callers can fall back to sending the raw string unchanged.\n * @param body - Raw body string\n * @returns Parsed object or undefined\n */\nfunction parseBodyAsObject(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return undefined;\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Set a dotted path on a body object, replacing non-object intermediates as\n * needed. `--field` takes precedence over `--body`, so collisions overwrite.\n * @param obj - The body object to mutate\n * @param path - Dot-split path segments (e.g. [\"application\", \"name\"])\n * @param value - Value to assign at the leaf\n */\nfunction setNestedPath(obj: Record<string, unknown>, path: string[], value: unknown): void {\n let cursor: Record<string, unknown> = obj;\n for (let i = 0; i < path.length - 1; i++) {\n const key = assertDefined(path[i], \"path segment missing\");\n const next = cursor[key];\n if (typeof next !== \"object\" || next === null || Array.isArray(next)) {\n cursor[key] = {};\n }\n cursor = cursor[key] as Record<string, unknown>;\n }\n cursor[assertDefined(path[path.length - 1], \"path last segment missing\")] = value;\n}\n\n/**\n * Coerces a raw `--field` string value to match the leaf proto type so the\n * JSON body sends a properly typed value. Today we only coerce bool — the\n * completion candidates explicitly suggest `=true`/`=false`, so sending the\n * literal string \"true\" would be a visible mismatch. Other scalars are left\n * as strings: proto JSON accepts string forms for ints/floats/int64/etc.,\n * and we'd rather pass through what the user typed than silently coerce.\n * @param field - The resolved leaf field descriptor, or undefined when the path didn't resolve\n * @param raw - The raw string value after `=`\n * @returns The value to write into the body object\n */\nfunction coerceFieldValue(field: DescField | undefined, raw: string): unknown {\n if (field && field.fieldKind === \"scalar\" && field.scalar === ScalarType.BOOL) {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n throw new Error(`Invalid value for bool field: '${raw}'. Expected 'true' or 'false'.`);\n }\n return raw;\n}\n\ninterface ParsedField {\n path: string[];\n value: string;\n}\n\n/**\n * Collapse top-level body keys that address a known input field by its\n * protobuf name (snake_case) or JSON name to the field's `localName`. protojson\n * accepts every alias, so converging them here lets the presence checks below\n * reason in a single namespace — otherwise a `--body` written as\n * `{\"workspace_id\": ...}` slips past the camelCase check and we inject a second\n * `workspaceId`, which the server rejects as a duplicate field. When both forms\n * are present the canonical key wins and the alias is dropped.\n * @param body - The parsed body object to mutate\n * @param fields - The target endpoint's input fields\n * @returns Whether any key was rewritten\n */\nexport function normalizeBodyFieldKeys(\n body: Record<string, unknown>,\n fields: readonly DescField[],\n): boolean {\n const aliasToLocal = new Map<string, string>();\n for (const f of fields) {\n aliasToLocal.set(f.name, f.localName);\n aliasToLocal.set(f.jsonName, f.localName);\n }\n let changed = false;\n for (const key of Object.keys(body)) {\n const local = aliasToLocal.get(key);\n if (!local || local === key) continue;\n if (!Object.hasOwn(body, local)) body[local] = body[key];\n delete body[key];\n changed = true;\n }\n return changed;\n}\n\n// Prototype-pollution sinks: `setNestedPath` walks `cursor[key]`, so a\n// segment that resolves on `Object.prototype` (e.g. `__proto__`) would let an\n// untrusted dotted key mutate the runtime prototype instead of the body.\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst fieldArg = z.string().transform((val, ctx): ParsedField => {\n const eq = val.indexOf(\"=\");\n if (eq < 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field format: '${val}'. Expected format: 'key=value' or 'a.b.c=value'`,\n });\n return z.NEVER;\n }\n const key = val.slice(0, eq);\n if (key.length === 0) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"Field key cannot be empty\" });\n return z.NEVER;\n }\n const segments = key.split(\".\");\n if (segments.some((seg) => seg.length === 0)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field key: '${key}'. Dotted segments cannot be empty`,\n });\n return z.NEVER;\n }\n const forbidden = segments.find((seg) => FORBIDDEN_SEGMENTS.has(seg));\n if (forbidden) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field key: '${key}'. Segment '${forbidden}' is not allowed.`,\n });\n return z.NEVER;\n }\n return { path: segments, value: val.slice(eq + 1) };\n});\n\nexport const apiCommand = defineAppCommand({\n name: \"api\",\n description: \"Call Tailor Platform API endpoints directly.\",\n notes: `Use \\`tailor api list\\` to enumerate invocable methods and \\`tailor api inspect <endpoint>\\` to print an endpoint's input message tree (combine with \\`--json\\` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from \\`--body\\`:\n\n- \\`workspaceId\\` — resolved from \\`-w\\` / \\`TAILOR_PLATFORM_WORKSPACE_ID\\` / the selected profile.\n- \\`namespaceName\\` — resolved from \\`tailor.config.ts\\` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use \\`auth.name\\`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in \\`--body\\` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse \\`--field key=value\\` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. \\`application.name=foo\\`) build nested objects. \\`--field\\` overrides matching fields in \\`--body\\` and tab-completes from the endpoint's request schema.`,\n examples: [\n {\n cmd: 'GetApplication -b \\'{\"applicationName\":\"app-1\"}\\'',\n desc: \"Call an endpoint; workspaceId is auto-injected.\",\n },\n {\n cmd: \"GetApplication -f applicationName=app-1\",\n desc: \"Same as above, using --field instead of --body.\",\n },\n {\n cmd: \"list\",\n desc: \"List all invocable OperatorService methods.\",\n },\n {\n cmd: \"inspect GetApplication\",\n desc: \"Show the input message tree for an endpoint.\",\n },\n ],\n subCommands: {\n list: listCommand,\n inspect: inspectCommand,\n },\n args: z.strictObject({\n ...workspaceArgs,\n ...configArg,\n body: arg(z.string().default(\"{}\"), {\n alias: \"b\",\n description: \"Request body as JSON.\",\n }),\n field: arg(fieldArg.array().optional(), {\n alias: \"f\",\n description:\n \"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.\",\n completion: {\n custom: {\n expand: {\n dependsOn: [\"endpoint\"],\n enumerate: ({ endpoint }) =>\n enumerateAllFieldCompletions(extractMethodName(endpoint ?? \"\")),\n },\n },\n },\n }),\n endpoint: arg(z.string(), {\n positional: true,\n description:\n \"API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').\",\n completion: { custom: { choices: listMethodChoices() } },\n }),\n }),\n run: async (args) => {\n // Direct API calls can target any OperatorService method, including\n // Create/Update/Delete. Block all of them under a readonly profile rather\n // than try to classify endpoints by name.\n await assertWritable({ profile: args.profile });\n const methodName = extractMethodName(args.endpoint);\n const method = getMethodDescriptor(methodName);\n\n const parsedBody = parseBodyAsObject(args.body);\n let mutated = false;\n\n if (args.field && args.field.length > 0) {\n if (!parsedBody) {\n throw new Error(\"--field requires --body to be a JSON object (or omitted).\");\n }\n for (const f of args.field) {\n const leaf = method ? resolveLeafField(method.input, f.path) : undefined;\n setNestedPath(parsedBody, f.path, coerceFieldValue(leaf, f.value));\n }\n mutated = true;\n }\n\n if (parsedBody && method) {\n // Converge any snake_case / JSON aliases to each field's localName first,\n // so the presence checks below operate in a single (camelCase) namespace.\n if (normalizeBodyFieldKeys(parsedBody, method.input.fields)) {\n mutated = true;\n }\n\n const fieldNames = method.input.fields.map((f) => f.localName);\n\n if (fieldNames.includes(\"workspaceId\") && !Object.hasOwn(parsedBody, \"workspaceId\")) {\n try {\n parsedBody.workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n mutated = true;\n } catch {\n // Cannot resolve workspace ID — skip\n }\n }\n\n if (fieldNames.includes(\"namespaceName\") && !Object.hasOwn(parsedBody, \"namespaceName\")) {\n try {\n const { config } = await loadConfig(args.config);\n const ns = resolveNamespaceName(methodName, config);\n if (ns) {\n parsedBody.namespaceName = ns;\n mutated = true;\n }\n } catch {\n // Config not available — skip\n }\n }\n }\n\n const result = await apiCall({\n profile: args.profile,\n endpoint: args.endpoint,\n body: mutated && parsedBody ? JSON.stringify(parsedBody) : args.body,\n });\n\n logger.out(JSON.stringify(result.data, null, 2));\n },\n});\n","import { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const tokenCommand = defineAppCommand({\n name: \"token\",\n description:\n \"Print a valid Tailor Platform access token to stdout, refreshing it first if expired.\",\n args: z.strictObject({\n profile: workspaceArgs.profile,\n }),\n run: async ({ profile }) => {\n const token = await loadAccessToken({ profile });\n logger.out(token);\n },\n});\n","import { defineCommand } from \"politty\";\nimport { tokenCommand } from \"./token\";\n\nexport const authCommand = defineCommand({\n name: \"auth\",\n description: \"Authentication helpers for scripts and plugins.\",\n subCommands: {\n token: tokenCommand,\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\n/**\n * Arguments for identifying an auth connection\n */\nexport const connectionNameArgs = {\n name: arg(z.string(), {\n alias: \"n\",\n description: \"Auth connection name\",\n }),\n};\n","import * as crypto from \"node:crypto\";\nimport * as http from \"node:http\";\nimport open from \"open\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nconst defaultPort = 8080;\nconst defaultScopes = \"openid,profile,email\";\n\n/**\n * Fetch the OpenID Connect discovery document from a provider URL.\n * @param providerUrl - OAuth2 provider base URL\n * @returns Discovery document with authorization_endpoint\n */\nasync function fetchOIDCDiscovery(\n providerUrl: string,\n): Promise<{ authorization_endpoint: string }> {\n const url = providerUrl.replace(/\\/$/, \"\") + \"/.well-known/openid-configuration\";\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch OIDC discovery from ${url}: ${response.status}`);\n }\n return response.json() as Promise<{\n authorization_endpoint: string;\n }>;\n}\n\nfunction randomState() {\n return crypto.randomBytes(32).toString(\"base64url\");\n}\n\nexport const authorizeAuthConnectionCommand = defineAppCommand({\n name: \"authorize\",\n description: \"Authorize an auth connection via OAuth2 flow.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n scopes: z\n .string()\n .optional()\n .default(defaultScopes)\n .describe(\"OAuth2 scopes to request (comma-separated)\"),\n port: z.coerce.number().optional().default(defaultPort).describe(\"Local callback server port\"),\n \"no-browser\": z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Don't open browser automatically\"),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // Find the connection to get its provider URL and client ID\n const connections = await fetchAll(async (pageToken, maxPageSize) => {\n const { connections, nextPageToken } = await client.listAuthConnections({\n workspaceId,\n pageToken,\n pageSize: maxPageSize,\n });\n return [connections, nextPageToken];\n });\n\n const connection = connections.find((c) => c.name === args.name);\n if (!connection) {\n throw new Error(`Auth connection \"${args.name}\" not found.`);\n }\n\n if (connection.config.case !== \"oauth2\") {\n throw new Error(`Auth connection \"${args.name}\" is not an OAuth2 connection.`);\n }\n\n const oauth2Config = connection.config.value;\n const redirectUri = `http://localhost:${args.port}/callback`;\n const state = randomState();\n\n // Resolve authorization endpoint from discovery or explicit config\n let authorizationEndpoint: string;\n if (oauth2Config.authUrl) {\n authorizationEndpoint = oauth2Config.authUrl;\n } else {\n const discovery = await fetchOIDCDiscovery(oauth2Config.providerUrl);\n authorizationEndpoint = discovery.authorization_endpoint;\n }\n\n // Build authorization URL\n const authUrl = new URL(authorizationEndpoint);\n authUrl.searchParams.set(\"client_id\", oauth2Config.clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUri);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"scope\", args.scopes.replace(/,/g, \" \"));\n authUrl.searchParams.set(\"state\", state);\n authUrl.searchParams.set(\"access_type\", \"offline\");\n\n await new Promise<void>((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n if (!req.url?.startsWith(\"/callback\")) {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n try {\n const url = new URL(req.url, `http://localhost:${args.port}`);\n const code = url.searchParams.get(\"code\");\n const returnedState = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n\n if (error) {\n throw new Error(`Authorization failed: ${error}`);\n }\n\n if (returnedState !== state) {\n throw new Error(\"State mismatch — possible CSRF attack.\");\n }\n\n if (!code) {\n throw new Error(\"No authorization code received.\");\n }\n\n // Send authorization code to the platform for server-side token exchange\n await client.exchangeAuthConnectionAuthorizationCode({\n workspaceId,\n connectionName: args.name,\n authorizationCode: code,\n redirectUri,\n });\n\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>\",\n );\n server.close();\n resolve();\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"text/plain\" });\n res.end(`Authorization failed: ${err instanceof Error ? err.message : \"Unknown error\"}`);\n server.close();\n reject(err);\n }\n });\n\n const timeout = setTimeout(\n () => {\n server.close();\n reject(new Error(\"Authorization timeout exceeded (5 minutes).\"));\n },\n 5 * 60 * 1000,\n );\n\n server.on(\"close\", () => {\n clearTimeout(timeout);\n });\n\n server.on(\"error\", (err) => {\n // A listen failure never emits \"close\", so clear the pending timeout\n // here to avoid keeping the process alive after the command has failed.\n clearTimeout(timeout);\n // Any error here means the local callback server could not be started.\n // Guide the user to the Console-based flow as a fallback.\n const code = (err as NodeJS.ErrnoException).code;\n const portHint =\n code === \"EADDRINUSE\" || code === \"EACCES\"\n ? `Try a different port with --port, or authorize via the Console instead:`\n : `Authorize via the Console instead:`;\n logger.warn(\n `Could not start the local callback server on port ${args.port}${code ? ` (${code})` : \"\"}.\\n` +\n `${portHint}\\n` +\n ` tailor authconnection open`,\n );\n reject(err);\n });\n\n server.listen(args.port, async () => {\n const authorizeUrl = authUrl.toString();\n logger.info(\n args[\"no-browser\"]\n ? `Open this URL in your browser to authorize:\\n\\n${authorizeUrl}\\n`\n : `Opening browser for authorization:\\n\\n${authorizeUrl}\\n`,\n );\n logger.info(\n `If this flow doesn't complete, you can authorize via the Console instead:\\n` +\n ` tailor authconnection open`,\n );\n if (!args[\"no-browser\"]) {\n try {\n await open(authorizeUrl);\n } catch {\n logger.warn(\n \"Failed to open browser automatically. Please open the URL above manually.\",\n );\n }\n }\n });\n });\n\n logger.success(`Auth connection \"${args.name}\" authorized successfully.`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nexport const deleteAuthConnectionCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete an auth connection entirely.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the connection name to confirm deletion (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Auth connection deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteAuthConnection({ workspaceId, connectionName: args.name });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Auth connection \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Auth connection \"${args.name}\" deleted.`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { AuthConnection } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n\ninterface ConnectionInfo {\n name: string;\n type: string;\n providerUrl: string;\n issuerUrl: string;\n clientId: string;\n authUrl: string;\n tokenUrl: string;\n createdAt: Date | null;\n}\n\nfunction connectionInfo(connection: AuthConnection): ConnectionInfo {\n const oauth2 = connection.config.case === \"oauth2\" ? connection.config.value : undefined;\n return {\n name: connection.name,\n type: connection.config.case ?? \"unknown\",\n providerUrl: oauth2?.providerUrl ?? \"\",\n issuerUrl: oauth2?.issuerUrl ?? \"\",\n clientId: oauth2?.clientId ?? \"\",\n authUrl: oauth2?.authUrl ?? \"\",\n tokenUrl: oauth2?.tokenUrl ?? \"\",\n createdAt: connection.createdAt ? timestampDate(connection.createdAt) : null,\n };\n}\n\nexport const listAuthConnectionCommand = defineAppCommand({\n name: \"list\",\n description: \"List all auth connections.\",\n args: z.strictObject({ ...workspaceArgs, ...paginationArgs() }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n const pageDirection = toPageDirection(args.order);\n const connections = await fetchPaged(\n async (pageToken, pageSize) => {\n const { connections, nextPageToken } = await client.listAuthConnections({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [connections, nextPageToken];\n },\n { limit: args.limit },\n );\n logger.out(connections.map(connectionInfo));\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n logger.out([]);\n return;\n }\n throw error;\n }\n },\n});\n","import open from \"open\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConsoleBaseUrl, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const openAuthConnectionCommand = defineAppCommand({\n name: \"open\",\n description: \"Open the auth connections page in the Tailor Platform Console.\",\n args: z.strictObject({ ...workspaceArgs }),\n run: async (args) => {\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n const consolePath = `/workspaces/${workspaceId}/settings/connections`;\n const consoleBaseUrl = await loadConsoleBaseUrl({\n profile: args.profile,\n ...(args[\"workspace-id\"] !== undefined ? { allowMissingProfile: true } : {}),\n });\n const consoleUrl = new URL(consolePath, consoleBaseUrl).toString();\n const jsonOutput = logger.jsonMode;\n\n logger.info(\"Opening auth connections page in Tailor Platform Console...\");\n\n let opened = true;\n try {\n await open(consoleUrl);\n } catch {\n opened = false;\n }\n\n if (jsonOutput) {\n logger.out({ consoleUrl, workspaceId, opened });\n return;\n }\n\n if (opened) {\n logger.out(`Console URL: ${consoleUrl}`);\n logger.out(`Workspace ID: ${workspaceId}`);\n } else {\n logger.warn(\n `Failed to open browser automatically. Please open this URL manually:\\n${consoleUrl}`,\n );\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nexport const revokeAuthConnectionCommand = defineAppCommand({\n name: \"revoke\",\n description:\n \"Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).\",\n notes:\n \"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the connection name to confirm revocation (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Auth connection revocation cancelled.\");\n return;\n }\n }\n\n try {\n await client.revokeAuthConnection({\n workspaceId,\n connectionName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Auth connection \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Auth connection \"${args.name}\" revoked.`);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { authorizeAuthConnectionCommand } from \"./authorize\";\nimport { deleteAuthConnectionCommand } from \"./delete\";\nimport { listAuthConnectionCommand } from \"./list\";\nimport { openAuthConnectionCommand } from \"./open\";\nimport { revokeAuthConnectionCommand } from \"./revoke\";\n\nexport const authconnectionCommand = defineCommand({\n name: \"authconnection\",\n description: \"Manage auth connections.\",\n subCommands: {\n authorize: authorizeAuthConnectionCommand,\n list: listAuthConnectionCommand,\n open: openAuthConnectionCommand,\n revoke: revokeAuthConnectionCommand,\n delete: deleteAuthConnectionCommand,\n },\n async run() {\n await runCommand(listAuthConnectionCommand, []);\n },\n});\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { z } from \"zod\";\nimport { parseCrashReportConfig } from \"#/cli/crashreport/config\";\nimport { CRASH_LOG_EXTENSION } from \"#/cli/crashreport/writer\";\nimport { type Order, paginationArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport function orderAndLimitCrashReports(\n entries: string[],\n options: { order?: Order; limit?: number },\n): string[] {\n const sorted = entries.filter((f) => f.endsWith(CRASH_LOG_EXTENSION)).toSorted();\n const ordered = options.order === \"asc\" ? sorted : sorted.toReversed();\n return options.limit && options.limit > 0 ? ordered.slice(0, options.limit) : ordered;\n}\n\nfunction formatCrashReportFiles(files: string[], localDir: string) {\n return files.map((file) => ({\n file,\n path: path.join(localDir, file),\n }));\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List local crash report files.\",\n args: z.strictObject({\n ...paginationArgs(),\n }),\n run: async (args) => {\n const config = parseCrashReportConfig();\n const jsonOutput = logger.jsonMode;\n if (!config.localDir) {\n logger.info(\"Crash report directory not available.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n let entries: string[];\n try {\n entries = fs.readdirSync(config.localDir);\n } catch {\n logger.info(\"No crash reports found.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const files = orderAndLimitCrashReports(entries, { order: args.order, limit: args.limit });\n\n if (files.length === 0) {\n logger.info(\"No crash reports found.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n if (jsonOutput) {\n logger.out(formatCrashReportFiles(files, config.localDir));\n return;\n }\n\n logger.info(`${files.length} crash report(s) in ${config.localDir}:`);\n for (const file of files) {\n logger.log(` ${file}`);\n }\n },\n});\n","import * as fs from \"node:fs\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { sendCrashReport } from \"#/cli/crashreport/sender\";\nimport { JSON_FOOTER_MARKER } from \"#/cli/crashreport/writer\";\nimport { userAgent } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { CrashReport } from \"#/cli/crashreport/report\";\n\nexport const sendCommand = defineAppCommand({\n name: \"send\",\n description: \"Submit a crash report to help improve the SDK.\",\n args: z.strictObject({\n file: arg(z.string(), {\n description: \"Path to the crash report file\",\n required: true,\n completion: { type: \"file\", extensions: [\"log\"] },\n }),\n }),\n run: async (args) => {\n let content: string;\n try {\n content = fs.readFileSync(args.file, \"utf-8\");\n } catch {\n logger.error(`Crash report file not found: ${args.file}`);\n process.exit(1);\n }\n\n const report = parseCrashLogFile(content);\n if (!report) {\n logger.error(\"Failed to parse crash report file. The file may be corrupted.\");\n process.exit(1);\n }\n\n const ua = await userAgent();\n logger.info(\"Sending crash report...\");\n const success = await sendCrashReport(report, ua);\n\n if (success) {\n logger.success(\"Crash report submitted successfully. Thank you!\");\n } else {\n logger.error(\"Failed to submit crash report. The server may be unavailable.\");\n process.exit(1);\n }\n },\n});\n\n/**\n * Parse a crash log file back into a CrashReport object.\n * Reads the embedded JSON footer appended by formatCrashReport.\n * @param content - File content\n * @returns Parsed report or undefined if parsing fails\n */\nexport function parseCrashLogFile(content: string): CrashReport | undefined {\n try {\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const marker = `\\n${JSON_FOOTER_MARKER}\\n`;\n const lastIdx = normalized.lastIndexOf(marker);\n if (lastIdx === -1) return undefined;\n const jsonLine = normalized.slice(lastIdx + marker.length).split(\"\\n\")[0];\n if (!jsonLine) return undefined;\n return JSON.parse(jsonLine) as CrashReport;\n } catch {\n return undefined;\n }\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\nimport { sendCommand } from \"./send\";\n\nexport const crashReportCommand = defineCommand({\n name: \"crashreport\",\n description: \"Manage crash reports.\",\n subCommands: {\n list: listCommand,\n send: sendCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { deployFromCLI } from \"#/cli/commands/deploy/deploy\";\nimport { confirmationArgs, multiConfigArg, workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\n\nexport const deployCommand = defineAppCommand({\n name: \"deploy\",\n description: \"Deploy your application by applying the Tailor configuration.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...multiConfigArg,\n ...confirmationArgs,\n \"create-workspace\": arg(z.boolean().optional(), {\n description: \"Create a workspace when the account has none\",\n }),\n \"workspace-name\": arg(z.string().optional(), {\n description: \"Name for a workspace created during deploy\",\n }),\n \"workspace-region\": arg(z.string().optional(), {\n description: \"Region for a workspace created during deploy\",\n }),\n \"organization-id\": arg(z.string().optional(), {\n description: \"Organization ID for a workspace created during deploy\",\n env: \"TAILOR_PLATFORM_ORGANIZATION_ID\",\n }),\n \"folder-id\": arg(z.string().optional(), {\n description: \"Folder ID for a workspace created during deploy\",\n env: \"TAILOR_PLATFORM_FOLDER_ID\",\n }),\n \"dry-run\": arg(z.boolean().optional(), {\n alias: \"d\",\n description: \"Run the command without making any changes\",\n }),\n \"no-schema-check\": arg(z.boolean().optional(), {\n description: \"Skip schema diff check against migration snapshots\",\n }),\n \"no-validate\": arg(z.boolean().optional(), {\n description: \"Skip client-side validation against platform resource constraints\",\n }),\n \"no-cache\": arg(z.boolean().optional(), {\n description: \"Disable bundle caching for this run\",\n }),\n \"clean-cache\": arg(z.boolean().optional(), {\n description: \"Clean the bundle cache before building\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n await deployFromCLI(\n {\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n configPath: args.config,\n dryRun: args[\"dry-run\"],\n yes: args.yes,\n createWorkspace: args[\"create-workspace\"],\n workspaceName: args[\"workspace-name\"],\n workspaceRegion: args[\"workspace-region\"],\n organizationId: args[\"organization-id\"],\n folderId: args[\"folder-id\"],\n noSchemaCheck: args[\"no-schema-check\"],\n noValidate: args[\"no-validate\"],\n noCache: args[\"no-cache\"],\n cleanCache: args[\"clean-cache\"],\n },\n {\n envFile: args[\"env-file\"],\n envFileIfExists: args[\"env-file-if-exists\"],\n verbose: args.verbose,\n json: args.json,\n },\n );\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { jobsCommand } from \"./jobs\";\nimport { listCommand } from \"./list\";\nimport { triggerCommand } from \"./trigger\";\nimport { webhookCommand } from \"./webhook\";\n\nexport const executorCommand = defineCommand({\n name: \"executor\",\n description: \"Manage executors\",\n subCommands: {\n trigger: triggerCommand,\n jobs: jobsCommand,\n list: listCommand,\n get: getCommand,\n webhook: webhookCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","/**\n * Download a deployed function script from the function registry.\n *\n * Wraps the server-streaming `downloadFunctionRegistryScript` RPC and\n * concatenates content chunks into a single UTF-8 string.\n */\n\nimport { FunctionExecution_Type } from \"@tailor-platform/tailor-proto/function_resource_pb\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\n\n/**\n * Translate a `FunctionExecution.scriptName` into the corresponding\n * function registry name used by `downloadFunctionRegistryScript`.\n *\n * The platform records executions under a script-name format that\n * differs from the registry name. The execution `type` is used as the\n * primary discriminator because workflow job names are unconstrained\n * strings (`WorkflowJobSchema.name: z.string()`) and may contain dots\n * that collide with the resolver / executor / hook filename suffixes.\n *\n * JOB: `<jobName>` -> `workflow--<jobName>`\n * STANDARD resolver: `<namespace>.<name>.body.js` -> `resolver--<namespace>--<name>`\n * STANDARD executor: `<name>.operation.js` -> `executor--<name>`\n * STANDARD auth hook: `<authName>.<hookPoint>.hook.js` -> `auth-hook--<authName>--<hookPoint>`\n *\n * For older servers that leave `type` as `UNSPECIFIED`, the same\n * filename-suffix heuristic is applied, with a bare-name fallback to\n * `workflow--<name>` for backward compatibility. Returns `null` for\n * unrecognized formats (ad-hoc test-run scripts, seed scripts, etc.\n * that are not stored in the registry).\n * @param scriptName - The `scriptName` field from a `FunctionExecution`\n * @param executionType - The `type` field from a `FunctionExecution`\n * @returns The function registry name, or null when no mapping applies\n */\nexport function scriptNameToRegistryName(\n scriptName: string,\n executionType: FunctionExecution_Type,\n): string | null {\n // JOB: scriptName IS the workflow job name. Job names are\n // unconstrained, so dots must be preserved.\n if (executionType === FunctionExecution_Type.JOB) {\n return `workflow--${scriptName}`;\n }\n\n // Resolver: `<namespace>.<name>.body.js`\n // Use a non-greedy match for namespace so a name containing dots is\n // grouped into `name`, mirroring how resolvers are registered.\n const resolverMatch = /^([^.]+)\\.(.+)\\.body\\.js$/.exec(scriptName);\n if (resolverMatch) {\n const [, namespace, name] = resolverMatch;\n return `resolver--${namespace}--${name}`;\n }\n\n // Executor: `<name>.operation.js`\n const executorMatch = /^(.+)\\.operation\\.js$/.exec(scriptName);\n if (executorMatch) {\n const [, name] = executorMatch;\n return `executor--${name}`;\n }\n\n // Auth hook: `<authName>.<hookPoint>.hook.js`\n const authHookMatch = /^([^.]+)\\.([^.]+)\\.hook\\.js$/.exec(scriptName);\n if (authHookMatch) {\n const [, authName, hookPoint] = authHookMatch;\n return `auth-hook--${authName}--${hookPoint}`;\n }\n\n // Legacy (UNSPECIFIED) servers may not populate `type`. Fall back to\n // the historical bare-name heuristic for simple workflow job names.\n // Dotted job names cannot be disambiguated here and are left\n // unmapped; callers should upgrade the server for full coverage.\n if (executionType === FunctionExecution_Type.UNSPECIFIED && !scriptName.includes(\".\")) {\n return `workflow--${scriptName}`;\n }\n\n // Unknown format (ad-hoc test-run scripts, seed scripts, etc.) are\n // not in the registry; signal with null so the caller can fall back.\n return null;\n}\n\n/** Options for downloading a function registry script */\nexport interface DownloadFunctionScriptOptions {\n /** Operator client instance */\n client: OperatorClient;\n /** Workspace ID */\n workspaceId: string;\n /** Function registry name (translated from FunctionExecution.scriptName via scriptNameToRegistryName) */\n name: string;\n /** Optional content hash for a specific version (defaults to current version) */\n contentHash?: string;\n}\n\n/** Result of a successful function script download */\nexport interface DownloadedFunctionScript {\n /** Bundled script content as a UTF-8 string */\n code: string;\n}\n\n/**\n * Download a deployed function script.\n *\n * Returns the bundled script content. Returns null when the download\n * fails (script removed, network error, etc.) or when no content\n * chunks are received; errors are swallowed so callers can fall back\n * to a non-sourcemap display.\n * @param options - Download options\n * @returns Script content, or null on failure / empty response\n */\nexport async function downloadFunctionScript(\n options: DownloadFunctionScriptOptions,\n): Promise<DownloadedFunctionScript | null> {\n const { client, workspaceId, name, contentHash } = options;\n try {\n const chunks: Uint8Array[] = [];\n for await (const response of client.downloadFunctionRegistryScript({\n workspaceId,\n name,\n contentHash,\n })) {\n if (response.payload.case === \"chunk\") {\n chunks.push(response.payload.value);\n }\n }\n if (chunks.length === 0) return null;\n return { code: Buffer.concat(chunks).toString(\"utf-8\") };\n } catch (error) {\n logger.debug(`Failed to download function script \"${options.name}\": ${error}`);\n return null;\n }\n}\n","/**\n * Stack trace parsing, sourcemap-based source identification, and\n * formatted error display for the test-run command.\n *\n * The platform runtime automatically applies inline sourcemaps to V8\n * stack traces, so frame positions are already original source positions.\n * This module identifies which source file each frame belongs to via\n * reverse lookup (generatedPositionFor), then produces human-readable\n * output with file paths and code snippets.\n */\n\nimport { TraceMap, generatedPositionFor, originalPositionFor } from \"@jridgewell/trace-mapping\";\nimport * as path from \"pathe\";\nimport { styles } from \"#/cli/shared/logger\";\nimport { assertDefined } from \"#/utils/assert\";\n\n/** A single frame parsed from a V8 stack trace */\nexport interface StackFrame {\n /** Function name (e.g. \"M\", \"Object.body\", \"<anonymous>\") */\n functionName: string;\n /** File URL (e.g. \"file:///test-run--error-test.js\") */\n file: string;\n /** Line number (1-based) */\n line: number;\n /** Column number (1-based) */\n column: number;\n}\n\n/** Result of parsing a V8 stack trace string */\nexport interface ParsedStackTrace {\n /** Error message with rpc prefix stripped */\n errorMessage: string;\n /** Parsed stack frames (only file:/// frames) */\n frames: StackFrame[];\n}\n\n// Matches: \" at functionName (file:///path:line:col)\"\n// Or: \" at file:///path:line:col\"\nconst STACK_FRAME_REGEX = /^\\s+at\\s+(?:(.+?)\\s+\\()?(file:\\/\\/\\/.+?):(\\d+):(\\d+)\\)?$/;\n\n// The rpc error prefix added by the platform\nconst RPC_ERROR_PREFIX = \"rpc error: code = Aborted desc = \";\n\n/**\n * Parse a V8 stack trace string into structured frames.\n * Only frames with `file:///` URLs are included (eval frames are skipped).\n * @param error - Raw error string potentially containing a V8 stack trace\n * @returns Parsed error message and stack frames\n */\nexport function parseStackTrace(error: string): ParsedStackTrace {\n const lines = error.split(\"\\n\");\n\n const messageLines: string[] = [];\n const frameLines: string[] = [];\n\n for (const line of lines) {\n if (/^\\s+at\\s+/.test(line)) {\n frameLines.push(line);\n } else if (frameLines.length === 0) {\n messageLines.push(line);\n }\n }\n\n let errorMessage = messageLines.join(\"\\n\");\n\n if (errorMessage.startsWith(RPC_ERROR_PREFIX)) {\n errorMessage = errorMessage.slice(RPC_ERROR_PREFIX.length);\n }\n\n const frames: StackFrame[] = [];\n for (const line of frameLines) {\n const match = STACK_FRAME_REGEX.exec(line);\n if (match) {\n frames.push({\n functionName: match[1] || \"<anonymous>\",\n file: assertDefined(match[2], \"stack frame file missing\"),\n line: Number(assertDefined(match[3], \"stack frame line missing\")),\n column: Number(assertDefined(match[4], \"stack frame column missing\")),\n });\n }\n }\n\n return { errorMessage, frames };\n}\n\nconst INLINE_SOURCEMAP_REGEX =\n /\\/\\/[#@]\\s*sourceMappingURL=data:application\\/json[^,]*;base64,(.+)$/m;\n\n/** Original source position resolved from a sourcemap */\nexport interface MappedSourcePosition {\n source: string;\n line: number;\n column: number;\n name: string | null;\n}\n\n/** A stack frame mapped back to original source */\nexport interface MappedStackFrame {\n /** The original parsed frame */\n original: StackFrame;\n /** Mapped source position, or null if mapping failed */\n mapped: MappedSourcePosition | null;\n}\n\n/**\n * Extract an inline sourcemap from bundled code and return a TraceMap.\n * @param bundledCode - Bundled JavaScript code potentially containing an inline sourcemap\n * @returns TraceMap instance, or null if no valid inline sourcemap is found\n */\nexport function extractInlineSourcemap(bundledCode: string): TraceMap | null {\n const match = INLINE_SOURCEMAP_REGEX.exec(bundledCode);\n if (!match) return null;\n\n try {\n const decoded = Buffer.from(\n assertDefined(match[1], \"sourcemap base64 data missing\"),\n \"base64\",\n ).toString(\"utf-8\");\n const rawSourceMap = JSON.parse(decoded);\n return new TraceMap(rawSourceMap);\n } catch {\n return null;\n }\n}\n\n/**\n * Map parsed stack frames to their source files using a TraceMap.\n *\n * The platform runtime applies inline sourcemaps automatically, so V8\n * reports already-mapped original source positions in stack traces.\n * This function uses generatedPositionFor to reverse-lookup which source\n * file each frame's line:column belongs to.\n * @param frames - Parsed stack frames (positions are already original source positions)\n * @param traceMap - TraceMap from inline sourcemap, or null\n * @returns Frames with identified source files\n */\nexport function mapStackFrames(\n frames: StackFrame[],\n traceMap: TraceMap | null,\n): MappedStackFrame[] {\n return frames.map((frame) => {\n if (!traceMap) {\n return { original: frame, mapped: null };\n }\n\n try {\n // Iterate in reverse: user code and entry file are typically last\n // in the sources array, while SDK internals and node_modules come first.\n for (let i = traceMap.sources.length - 1; i >= 0; i--) {\n const source = traceMap.sources[i];\n if (source == null) continue;\n\n const genPos = generatedPositionFor(traceMap, {\n source,\n line: frame.line,\n column: frame.column - 1, // V8 is 1-based, trace-mapping is 0-based\n });\n\n if (genPos.line == null) continue;\n\n // Round-trip validation: generatedPositionFor uses\n // GREATEST_LOWER_BOUND bias by default, so it may return a\n // near-match when the queried source has a mapping on the target\n // line at an earlier column. Verify the generated position maps\n // back to the exact (source, line, column) we queried before\n // accepting the match; otherwise try the next source.\n const origPos = originalPositionFor(traceMap, {\n line: genPos.line,\n column: genPos.column,\n });\n if (\n origPos.source !== source ||\n origPos.line !== frame.line ||\n origPos.column !== frame.column - 1\n ) {\n continue;\n }\n\n return {\n original: frame,\n mapped: {\n source,\n line: frame.line,\n column: frame.column,\n name: null,\n },\n };\n }\n\n return { original: frame, mapped: null };\n } catch {\n return { original: frame, mapped: null };\n }\n });\n}\n\n/**\n * Detect the URI scheme for opening files based on VISUAL/EDITOR env vars.\n * @returns \"vscode\" if the editor looks like VS Code, otherwise null (use file://)\n */\nfunction detectEditorScheme(): string | null {\n const editor = process.env.VISUAL || process.env.EDITOR || \"\";\n if (/\\bcode\\b/.test(editor)) return \"vscode\";\n return null;\n}\n\n/**\n * Wrap text in an OSC 8 terminal hyperlink.\n * @param uri - URI to open when the link is clicked\n * @param text - Visible text displayed in the terminal\n * @returns Escaped string with OSC 8 sequences\n */\nfunction osc8Link(uri: string, text: string): string {\n return `\\x1b]8;;${uri}\\x07${text}\\x1b]8;;\\x07`;\n}\n\n/**\n * Build a clickable terminal link for a source location.\n * Uses vscode:// URI if the editor is VS Code, otherwise file:// URI.\n * @param displayPath - Path to display in the terminal\n * @param absolutePath - Absolute file path for the URI\n * @param line - 1-based line number\n * @param column - 1-based column number\n * @returns OSC 8 hyperlinked location string\n */\nfunction buildSourceLink(\n displayPath: string,\n absolutePath: string,\n line: number,\n column: number,\n): string {\n const location = `${displayPath}:${line}:${column}`;\n const scheme = detectEditorScheme();\n if (scheme === \"vscode\") {\n return osc8Link(`vscode://file${absolutePath}:${line}:${column}`, location);\n }\n return osc8Link(`file://${absolutePath}`, location);\n}\n\nconst SNIPPET_CONTEXT_LINES = 2;\n\n/**\n * Build a code snippet around a target line from source content.\n * Shows SNIPPET_CONTEXT_LINES above and below with line numbers.\n * The target line is marked with `>` and highlighted.\n * @param content - Full source file content\n * @param targetLine - 1-based line number to highlight\n * @returns Formatted snippet string\n */\nfunction buildCodeSnippet(content: string, targetLine: number): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, targetLine - 1 - SNIPPET_CONTEXT_LINES);\n const end = Math.min(lines.length, targetLine + SNIPPET_CONTEXT_LINES);\n\n const gutterWidth = String(end).length;\n const snippetLines: string[] = [];\n\n for (let i = start; i < end; i++) {\n const lineNum = i + 1;\n const gutter = String(lineNum).padStart(gutterWidth);\n const lineContent = lines[i];\n\n if (lineNum === targetLine) {\n snippetLines.push(` ${styles.error(\">\")} ${styles.error(`${gutter} | ${lineContent}`)}`);\n } else {\n snippetLines.push(` ${styles.dim(`${gutter} | ${lineContent}`)}`);\n }\n }\n\n return snippetLines.join(\"\\n\");\n}\n\n/**\n * Format mapped stack frames into a human-readable error display.\n * Includes file paths (clickable in terminals), code snippets, and\n * falls back to raw frame info for unmapped frames.\n * @param errorMessage - Cleaned error message\n * @param frames - Mapped stack frames\n * @param traceMap - TraceMap for retrieving source content (may be null)\n * @param bundleDir - Absolute path to bundle output directory for resolving source paths\n * @returns Formatted error string for display\n */\nexport function formatMappedError(\n errorMessage: string,\n frames: MappedStackFrame[],\n traceMap: TraceMap | null,\n bundleDir?: string,\n): string {\n const parts: string[] = [` ${styles.error(errorMessage)}`];\n\n for (const frame of frames) {\n if (frame.mapped) {\n const { source, line, column, name } = frame.mapped;\n const absolutePath = bundleDir ? path.resolve(bundleDir, source) : path.resolve(source);\n const rel = path.relative(process.cwd(), absolutePath);\n // Only paths escaping cwd (starting with `..`) are shown as-is; all\n // other relative paths get an explicit `./` prefix so dotfiles like\n // `.tailor/...` are not mistaken for relative-path markers.\n const displaySource = rel.startsWith(\"..\") ? rel : `./${rel}`;\n const fnName = name ?? frame.original.functionName;\n const link = buildSourceLink(displaySource, absolutePath, line, column);\n parts.push(`\\n at ${fnName} (${link})`);\n\n if (traceMap) {\n const sourceIndex = traceMap.sources.indexOf(source);\n if (sourceIndex !== -1) {\n const content = traceMap.sourcesContent?.[sourceIndex];\n if (content) {\n parts.push(buildCodeSnippet(content, line));\n }\n }\n }\n } else {\n const file = frame.original.file.replace(/^file:\\/\\/\\//, \"\");\n const location = `${file}:${frame.original.line}:${frame.original.column}`;\n parts.push(`\\n ${styles.dim(`at ${frame.original.functionName} (${location})`)}`);\n }\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Format an error string with sourcemap-based source locations.\n * This is the main entry point for test-run error display.\n *\n * The platform runtime applies inline sourcemaps automatically, so V8\n * stack frames already contain original source positions. This function\n * identifies which source file each frame belongs to and formats the\n * error with file paths, line numbers, and code snippets.\n *\n * Returns null if sourcemap processing is not possible (no inline\n * sourcemap, no stack trace, or processing error).\n * @param error - Raw error string from script execution (may contain V8 stack trace)\n * @param bundledCode - Bundled JavaScript code (may contain inline sourcemap)\n * @param bundleDir - Absolute path to the bundle output directory (sourcemap paths are relative to this)\n * @returns Formatted error string, or null to fall back to default display\n */\nexport function formatErrorWithSourcemap(\n error: string,\n bundledCode: string,\n bundleDir: string,\n): string | null {\n try {\n const { errorMessage, frames } = parseStackTrace(error);\n if (frames.length === 0) return null;\n\n const traceMap = extractInlineSourcemap(bundledCode);\n if (!traceMap) return null;\n\n const mappedFrames = mapStackFrames(frames, traceMap);\n\n if (mappedFrames.some((f) => f.mapped !== null)) {\n return formatMappedError(errorMessage, mappedFrames, traceMap, bundleDir);\n }\n\n return null;\n } catch {\n return null;\n }\n}\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { FunctionExecution_Type } from \"@tailor-platform/tailor-proto/function_resource_pb\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { pagedLogArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { formatKeyValueTable } from \"#/cli/shared/format\";\nimport { functionExecutionStatusToString } from \"#/cli/shared/function-execution\";\nimport {\n downloadFunctionScript,\n scriptNameToRegistryName,\n} from \"#/cli/shared/function-script-download\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport type { FunctionExecution } from \"@tailor-platform/tailor-proto/function_resource_pb\";\n\ninterface FunctionExecutionListInfo {\n id: string;\n scriptName: string;\n status: string;\n type: string;\n startedAt: Date | null;\n finishedAt: Date | null;\n}\n\ninterface FunctionExecutionErrorDisplay {\n name: string;\n message: string;\n stackTrace: string;\n}\n\ninterface FunctionExecutionDetailInfo extends FunctionExecutionListInfo {\n logs: string;\n result: string;\n error: FunctionExecutionErrorDisplay | null;\n}\n\n/**\n * Convert function execution type enum to string.\n * @param type - Function execution type enum value\n * @returns Type string representation\n */\nfunction functionExecutionTypeToString(type: FunctionExecution_Type): string {\n switch (type) {\n case FunctionExecution_Type.STANDARD:\n return \"STANDARD\";\n case FunctionExecution_Type.JOB:\n return \"JOB\";\n default:\n return \"UNSPECIFIED\";\n }\n}\n\n/**\n * Transform FunctionExecution to FunctionExecutionListInfo for list display.\n * @param execution - FunctionExecution from proto\n * @returns Function execution list info\n */\nfunction toFunctionExecutionListInfo(execution: FunctionExecution): FunctionExecutionListInfo {\n return {\n id: execution.id,\n scriptName: execution.scriptName,\n status: functionExecutionStatusToString(execution.status),\n type: functionExecutionTypeToString(execution.type),\n startedAt: execution.startedAt ? timestampDate(execution.startedAt) : null,\n finishedAt: execution.finishedAt ? timestampDate(execution.finishedAt) : null,\n };\n}\n\n/**\n * Transform FunctionExecution to FunctionExecutionDetailInfo for detail display.\n * @param execution - FunctionExecution from proto\n * @returns Function execution detail info\n */\nfunction toFunctionExecutionDetailInfo(execution: FunctionExecution): FunctionExecutionDetailInfo {\n return {\n ...toFunctionExecutionListInfo(execution),\n logs: execution.logs,\n result: execution.result,\n error: execution.error\n ? {\n name: execution.error.name,\n message: execution.error.message,\n stackTrace: execution.error.stackTrace,\n }\n : null,\n };\n}\n\n/**\n * Compose a V8-style error string from a FunctionErrorInfo so that it\n * can be parsed by `parseStackTrace`.\n *\n * `Error.prototype.stack` in V8 begins with `Name: message`, but the\n * platform may store only the frame lines; in that case prepend the\n * message line. When `stackTrace` is empty, return only `Name: message`.\n * @param error - Function error info from FunctionExecution\n * @returns Error string suitable for parseStackTrace\n */\nexport function composeExecutionErrorString(error: FunctionExecutionErrorDisplay): string {\n const { name, message, stackTrace } = error;\n if (!stackTrace) return `${name}: ${message}`;\n const firstLine = stackTrace.split(\"\\n\", 1)[0] ?? \"\";\n if (/^\\s+at\\s+/.test(firstLine)) {\n return `${name}: ${message}\\n${stackTrace}`;\n }\n return stackTrace;\n}\n\n/**\n * Plain-text fallback used when sourcemap mapping is unavailable.\n * Shows `Name: message` then the raw stack trace lines (dimmed).\n *\n * Uses `composeExecutionErrorString` to produce a canonical\n * `Name: message\\n<frames>` string first, so the header is never\n * duplicated when `stackTrace` already begins with `Name: message`.\n * @param error - Function error info from FunctionExecution\n * @returns Formatted fallback string for display\n */\nfunction formatExecutionErrorFallback(error: FunctionExecutionErrorDisplay): string {\n const composed = composeExecutionErrorString(error);\n const [headerLine, ...frameLines] = composed.split(\"\\n\");\n return [\n ` ${styles.error(headerLine)}`,\n ...frameLines.map((line) => ` ${styles.dim(line)}`),\n ].join(\"\\n\");\n}\n\n/**\n * Format an execution error for display, applying sourcemap mapping\n * when bundled code is available.\n * @param error - Function error info from FunctionExecution\n * @param bundledCode - Downloaded bundled script content (may be null)\n * @returns Formatted error string for display\n */\nexport function formatExecutionError(\n error: FunctionExecutionErrorDisplay,\n bundledCode: string | null,\n): string {\n if (bundledCode && error.stackTrace) {\n const errorString = composeExecutionErrorString(error);\n const formatted = formatErrorWithSourcemap(errorString, bundledCode, process.cwd());\n if (formatted) return formatted;\n }\n return formatExecutionErrorFallback(error);\n}\n\ninterface PrintFunctionExecutionDetailOptions {\n detail: FunctionExecutionDetailInfo;\n /** Bundled script content for sourcemap-based stack trace mapping (optional) */\n bundledCode?: string | null;\n}\n\n/**\n * Print function execution detail in a human-readable format.\n * @param options - Print options\n * @param options.detail - Function execution detail info\n * @param options.bundledCode - Downloaded bundled script content (used for sourcemap mapping)\n */\nfunction printFunctionExecutionDetail(options: PrintFunctionExecutionDetailOptions) {\n const { detail, bundledCode } = options;\n const formatDate = (date: Date | null): string => (date ? date.toISOString() : \"N/A\");\n\n const summaryData: [string, string][] = [\n [\"id\", detail.id],\n [\"scriptName\", detail.scriptName],\n [\"status\", detail.status],\n [\"type\", detail.type],\n [\"startedAt\", formatDate(detail.startedAt)],\n [\"finishedAt\", formatDate(detail.finishedAt)],\n ];\n logger.out(formatKeyValueTable(summaryData));\n\n if (detail.logs) {\n logger.log(styles.bold(\"\\nLogs:\"));\n for (const line of detail.logs.split(\"\\n\")) {\n logger.log(` ${line}`);\n }\n }\n\n if (detail.result) {\n logger.log(styles.bold(\"\\nResult:\"));\n try {\n const parsed = JSON.parse(detail.result);\n logger.log(` ${JSON.stringify(parsed, null, 2).split(\"\\n\").join(\"\\n \")}`);\n } catch {\n logger.log(` ${detail.result}`);\n }\n }\n\n if (detail.error) {\n logger.log(styles.bold(\"\\nError:\"));\n logger.log(formatExecutionError(detail.error, bundledCode ?? null));\n }\n}\n\ninterface DownloadScriptForMappingOptions {\n client: OperatorClient;\n workspaceId: string;\n /** FunctionExecution.scriptName (not the function registry name) */\n scriptName: string;\n /**\n * FunctionExecution.type. Used as the discriminator for the registry\n * name translation so that workflow job names containing dots are\n * not misread as resolver / seed scripts.\n */\n executionType: FunctionExecution_Type;\n /**\n * FunctionExecution.contentHash. When non-empty, the registry\n * download is pinned to this exact bundle so the stack trace maps\n * against the code that actually ran, regardless of subsequent\n * redeploys. Empty values cannot be mapped safely.\n */\n executionContentHash: string;\n}\n\n/**\n * Download a deployed function script for sourcemap mapping. Logs a\n * debug message on failure but never throws. Error display falls back\n * to a plain-text format when the script cannot be retrieved.\n *\n * When `executionContentHash` is non-empty, the download is pinned to\n * that exact bundle so mapping stays correct across redeploys. When\n * empty, mapping is skipped because the exact bundle cannot be\n * identified.\n *\n * `FunctionExecution.scriptName` does not match the function registry\n * name directly; `scriptNameToRegistryName` translates between the two\n * formats.\n * @param options - Lookup options\n * @param options.client - Operator client instance\n * @param options.workspaceId - Workspace ID\n * @param options.scriptName - Script name (matches FunctionExecution.scriptName)\n * @param options.executionType - Execution type used to discriminate registry name translation\n * @param options.executionContentHash - Content hash of the bundle that ran; pins the download when non-empty\n * @returns Bundled script content, or null when unavailable\n */\nexport async function downloadScriptForMapping(\n options: DownloadScriptForMappingOptions,\n): Promise<string | null> {\n const { client, workspaceId, scriptName, executionType, executionContentHash } = options;\n const registryName = scriptNameToRegistryName(scriptName, executionType);\n if (registryName == null) {\n logger.debug(\n `Script \"${scriptName}\" is not a deployed registry script (e.g. test-run or seed); skipping sourcemap mapping.`,\n );\n return null;\n }\n\n if (executionContentHash === \"\") {\n logger.debug(\n `Function execution \"${scriptName}\" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`,\n );\n return null;\n }\n\n const pinned = await downloadFunctionScript({\n client,\n workspaceId,\n name: registryName,\n contentHash: executionContentHash,\n });\n if (pinned == null) {\n logger.debug(\n `Could not download pinned script \"${scriptName}\" (registry: \"${registryName}\", contentHash: \"${executionContentHash}\") for stack trace mapping; showing raw stack trace.`,\n );\n return null;\n }\n return pinned.code;\n}\n\nexport const logsCommand = defineAppCommand({\n name: \"logs\",\n description: \"List or get function execution logs.\",\n notes: `When viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching \\`function test-run\\` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.`,\n examples: [\n {\n cmd: \"\",\n desc: \"List all function execution logs\",\n },\n {\n cmd: \"<execution-id>\",\n desc: \"Get execution details with logs\",\n },\n {\n cmd: \"--json\",\n desc: \"Output as JSON\",\n },\n {\n cmd: \"<execution-id> --json\",\n desc: \"Get execution details as JSON\",\n },\n ],\n args: z.strictObject({\n ...workspaceArgs,\n ...pagedLogArgs,\n \"execution-id\": arg(z.string().optional(), {\n positional: true,\n description: \"Execution ID (if provided, shows details with logs)\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (args.executionId) {\n const { execution } = await client.getFunctionExecution({\n workspaceId,\n executionId: args.executionId,\n });\n\n if (!execution) {\n throw new Error(`Function execution '${args.executionId}' not found.`);\n }\n\n const detail = toFunctionExecutionDetailInfo(execution);\n\n if (args.json) {\n logger.out(detail);\n } else {\n // Download the deployed script when an error is present so the\n // stack trace can be mapped back to original sources via the\n // inline sourcemap. Failure (script removed, no permission, etc.)\n // is non-fatal; we fall back to a plain-text error display.\n const bundledCode = detail.error\n ? await downloadScriptForMapping({\n client,\n workspaceId,\n scriptName: detail.scriptName,\n executionType: execution.type,\n executionContentHash: execution.contentHash,\n })\n : null;\n printFunctionExecutionDetail({ detail, bundledCode });\n }\n } else {\n const pageDirection = toPageDirection(args.order);\n const executions = await fetchPaged(\n async (pageToken, pageSize) => {\n const { executions, nextPageToken } = await client.listFunctionExecutions({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [executions, nextPageToken];\n },\n { limit: args.limit },\n );\n\n const logs = executions.map(toFunctionExecutionListInfo);\n\n if (logs.length === 0 && !args.json) {\n logger.info(\"No function execution logs found.\");\n return;\n }\n logger.out(logs);\n }\n },\n});\n","/**\n * Bundler for function test-run command\n *\n * Bundles a single function file for execution via the TestExecScript API.\n * Generates an entry file based on the detected function type and bundles\n * with rolldown, following the same patterns as the existing bundlers.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport * as rolldown from \"rolldown\";\nimport { createBundleLog } from \"#/cli/shared/bundle-log\";\nimport {\n createLogLevelTreeshakeOptions,\n resolveBundleLogLevel,\n} from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { resolveInlineSourcemap } from \"#/cli/shared/inline-sourcemap\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { resolveTSConfigWithFallback } from \"#/cli/shared/resolve-tsconfig\";\nimport { buildResolverPermissionAndInputCheckExpr, INVOKER_EXPR } from \"#/cli/shared/runtime-exprs\";\nimport { createTsconfigPathsPlugin } from \"#/cli/shared/tsconfig-paths-plugin\";\nimport { createGeneratedEntryResolverPlugin } from \"#/cli/shared/virtual-entry\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport type { LogLevelInput } from \"#/configure/config/types\";\nimport type { Resolver } from \"#/types/resolver.generated\";\nimport type { DetectedFunction } from \"./detect\";\n\n/** Machine user info resolved from config and API for bundle-time principal context. */\nexport interface ResolvedMachineUser {\n /** Machine user name */\n name: string;\n /** Machine user ID (UUID from API, or nil UUID if unavailable) */\n id: string;\n /** Attributes from config (null if not found in config, e.g. external auth) */\n attributes: Record<string, unknown> | null;\n /** Attribute list from config */\n attributeList: unknown[];\n}\n\ninterface BundleForTestRunOptions {\n /** Detected function info */\n detected: DetectedFunction;\n /** Absolute path to the source file */\n sourceFile: string;\n /** Directory to resolve the bundler's tsconfig against (the owning config's directory) */\n baseDir: string;\n /** Environment variables (injected into workflow job bundles) */\n env?: Record<string, string | number | boolean>;\n /** Inline sourcemap config value from defineConfig */\n inlineSourcemap?: boolean;\n /** Log level config value from defineConfig */\n logLevel?: LogLevelInput;\n /** Machine user info for injecting principal context into the bundle */\n machineUser: ResolvedMachineUser;\n /** Workspace ID for user context */\n workspaceId: string;\n /** For resolvers: the `defaultPermission` of the namespace owning the file */\n defaultPermission?: Resolver[\"permission\"];\n}\n\ninterface BundleForTestRunResult {\n /** The bundled JavaScript code */\n bundledCode: string;\n /** Name used for the script */\n scriptName: string;\n}\n\n/**\n * Bundle a function file for test-run execution via TestExecScript API.\n * @param options - Bundle options\n * @returns Bundled code and script name\n */\nexport async function bundleForTestRun(\n options: BundleForTestRunOptions,\n): Promise<BundleForTestRunResult> {\n const { detected, sourceFile, baseDir, env = {}, machineUser, workspaceId } = options;\n const inlineSourcemap = resolveInlineSourcemap(options.inlineSourcemap);\n const bundleLogLevel = resolveBundleLogLevel(options.logLevel);\n\n const outputDir = path.resolve(getDistDir(), \"test-run\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n const baseName = `test-run--${detected.name}`;\n const scriptName = `${baseName}.js`;\n const entryPath = path.join(outputDir, `${baseName}.entry.js`);\n\n const entryContent = generateEntry({\n detected,\n sourceFile,\n env,\n machineUser,\n workspaceId,\n defaultPermission: options.defaultPermission,\n });\n fs.writeFileSync(entryPath, entryContent);\n\n const tsconfig = await resolveTSConfigWithFallback(baseDir);\n\n const bundleLog = createBundleLog({ tsconfig });\n const buildResult = await rolldown.build({\n plugins: [\n createGeneratedEntryResolverPlugin(entryPath, baseDir),\n createTsconfigPathsPlugin(),\n platformBundleDefinePlugin,\n ],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: inlineSourcemap ? \"inline\" : true,\n minify: inlineSourcemap\n ? {\n mangle: {\n keepNames: true,\n },\n }\n : true,\n codeSplitting: false,\n // Emit sourcemap `sources` relative to cwd so stack traces resolve\n // back to paths a user can open (e.g. `resolvers/add.ts`), not the\n // rolldown-default virtual output dir which produces spurious `..`\n // segments.\n dir: process.cwd(),\n },\n tsconfig,\n treeshake: composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(bundleLogLevel)]),\n ...bundleLog.options,\n } as rolldown.BuildOptions);\n bundleLog.assertAllResolved();\n\n const bundledCode = buildResult.output[0].code;\n\n return { bundledCode, scriptName };\n}\n\ntype GenerateEntryOptions = {\n detected: DetectedFunction;\n /** Absolute path to the source file */\n sourceFile: string;\n /** Environment variables for workflow job bundles */\n env: Record<string, string | number | boolean>;\n machineUser: ResolvedMachineUser;\n workspaceId: string;\n /** For resolvers: the `defaultPermission` of the namespace owning the file */\n defaultPermission?: Resolver[\"permission\"];\n};\n\n/**\n * Generate entry file content based on the detected function type.\n * @param options - Detected function info and the context embedded into the entry\n * @returns Entry file content string\n */\nfunction generateEntry(options: GenerateEntryOptions): string {\n const { detected, sourceFile, env, machineUser, workspaceId, defaultPermission } = options;\n const absoluteSourcePath = path.resolve(sourceFile);\n\n switch (detected.type) {\n case \"plain\":\n if (detected.namedMain) {\n return ml /* js */ `\n export { main } from \"${absoluteSourcePath}\";\n `;\n }\n return ml /* js */ `\n import _fn from \"${absoluteSourcePath}\";\n export { _fn as main };\n `;\n\n case \"resolver\": {\n // Mirrors the production resolver bundler (services/resolver/bundler.ts):\n // both call buildResolverPermissionAndInputCheckExpr so the permission\n // guard and input validation can't drift between the two entry points.\n // In production, the operationHook injects caller/env into context.\n // For test-run, we embed machine user info since there's no operationHook.\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n const guardAndInputCheckExpr = buildResolverPermissionAndInputCheckExpr({\n permission: detected.permission,\n defaultPermission,\n });\n return ml /* js */ `\n import _internalResolver from \"${absoluteSourcePath}\";\n import { t } from \"@tailor-platform/sdk\";\n\n const $tailor_resolver_body = async (rawInput) => {\n const _caller = ${principalExpr};\n const invoker = (${INVOKER_EXPR}) ?? _caller;\n const context = { input: rawInput, env: ${JSON.stringify(env)}, caller: _caller, invoker };\n ${guardAndInputCheckExpr}\n return _internalResolver.body(context);\n };\n\n export { $tailor_resolver_body as main };\n `;\n }\n\n case \"executor\": {\n // Mirrors the production executor bundler (services/executor/bundler.ts).\n // In production, buildExecutorArgsExpr injects actor/env into args.\n // For test-run, we embed machine user as actor.\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n return ml /* js */ `\n import _internalExecutor from \"${absoluteSourcePath}\";\n\n const _env = ${JSON.stringify(env)};\n const _actor = ${principalExpr};\n\n const __executor_function = async (args) => {\n const _invoker = ${INVOKER_EXPR} ?? _actor;\n return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });\n };\n\n export { __executor_function as main };\n `;\n }\n\n case \"workflow-job\": {\n // Mirrors the production workflow bundler (services/workflow/bundler.ts).\n // Note: user context is not available in TestExecScript for workflow jobs.\n // The production workflow bundler's user mapping is being fixed in fix/workflow-user.\n const exportName = assertDefined(detected.exportName, \"workflow job export name missing\");\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n return ml /* js */ `\n import { ${exportName} } from \"${absoluteSourcePath}\";\n\n const env = ${JSON.stringify(env)};\n const fallbackInvoker = ${principalExpr};\n\n export async function main(input) {\n const invoker = ${INVOKER_EXPR} ?? fallbackInvoker;\n return await ${exportName}.body(input, { env, invoker });\n }\n `;\n }\n }\n}\n\n/**\n * Build a JSON expression for a machine user TailorPrincipal object.\n * @param machineUser - Resolved machine user info\n * @param workspaceId - Workspace ID\n * @returns JSON string for the user expression\n */\nfunction buildMachinePrincipalExpr(machineUser: ResolvedMachineUser, workspaceId: string): string {\n return JSON.stringify({\n id: machineUser.id,\n type: \"machine_user\",\n workspaceId,\n attributes: machineUser.attributes ?? {},\n attributeList: machineUser.attributeList,\n });\n}\n","/**\n * Function type detection for test-run command\n *\n * Detects the function type (resolver, executor, workflow job, or plain function)\n * by dynamically importing the module and checking against known schemas.\n */\n\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { stripExecutorTriggerArgs } from \"#/cli/services/executor/loader\";\nimport { ExecutorSchema } from \"#/parser/service/executor/index\";\nimport { ResolverSchema } from \"#/parser/service/resolver/index\";\nimport { WorkflowJobSchema } from \"#/parser/service/workflow/index\";\nimport { type FieldRuntime, parseInputFields } from \"#/runtime/field-parse\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type { TailorPrincipal } from \"#/runtime/types\";\nimport type { Resolver } from \"#/types/resolver.generated\";\n\nexport type FunctionType = \"resolver\" | \"executor\" | \"workflow-job\" | \"plain\";\n\ninterface InputParseArgs {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n}\n\n/** Minimal schema interface for local format detection (subset of TailorField) */\ninterface InputSchema {\n parse(args: InputParseArgs): {\n issues?: readonly { message: string; path?: readonly unknown[] }[];\n };\n}\n\nexport interface DetectedFunction {\n /** Detected function type */\n type: FunctionType;\n /** Function name (resolver name, executor name, job name, or filename-derived) */\n name: string;\n /** For workflow jobs: the TypeScript export name needed for bundling */\n exportName?: string;\n /** For plain functions: whether main is a named export rather than default export */\n namedMain?: boolean;\n /** For resolvers: whether the resolver defines an input schema */\n hasInput?: boolean;\n /** For resolvers with input: pre-built schema object with .parse() for local format detection */\n inputSchema?: InputSchema;\n /** For resolvers: the resolver's `permission` config, enforced the same way as production */\n permission?: Resolver[\"permission\"];\n}\n\ninterface DetectFunctionOptions {\n /** Absolute path to the function file */\n filePath: string;\n /** Workflow job name to select (matches the `name` field of createWorkflowJob) */\n jobName?: string;\n}\n\n/**\n * Detect the function type from a file by importing it and checking against schemas.\n * @param options - Detection options\n * @returns Detected function information\n */\nexport async function detectFunctionType(\n options: DetectFunctionOptions,\n): Promise<DetectedFunction> {\n const { filePath, jobName } = options;\n\n const module = await import(pathToFileURL(filePath).href);\n\n // Priority: resolver → executor → workflow job → plain function\n\n // 1. Check resolver\n const resolverResult = ResolverSchema.safeParse(module.default);\n if (resolverResult.success) {\n const rawInput = module.default.input;\n let inputSchema: DetectedFunction[\"inputSchema\"];\n if (rawInput) {\n // Fields built by the user's dynamically imported module match\n // FieldRuntime structurally; the cast stays at this import boundary.\n const fields = rawInput as Record<string, FieldRuntime>;\n inputSchema = {\n parse: (args) => parseInputFields({ ...args, fields }),\n };\n }\n return {\n type: \"resolver\",\n name: resolverResult.data.name,\n hasInput: rawInput != null,\n inputSchema,\n permission: resolverResult.data.permission,\n };\n }\n\n // 2. Check executor (only function/jobFunction kinds)\n const executorResult = ExecutorSchema.safeParse(stripExecutorTriggerArgs(module.default));\n if (executorResult.success) {\n const { operation } = executorResult.data;\n if (operation.kind === \"function\" || operation.kind === \"jobFunction\") {\n return { type: \"executor\", name: executorResult.data.name };\n }\n }\n\n // 3. Check workflow jobs (scan all named exports)\n const workflowJobResult = detectWorkflowJob(module, jobName);\n if (workflowJobResult) {\n return workflowJobResult;\n }\n\n // 4. Check plain function (default export or named export \"main\")\n if (typeof module.default === \"function\") {\n const name = deriveNameFromPath(filePath);\n return { type: \"plain\", name };\n }\n\n if (typeof module.main === \"function\") {\n const name = deriveNameFromPath(filePath);\n return { type: \"plain\", name, namedMain: true };\n }\n\n throw new Error(\n `Could not detect function type from ${filePath}.\\n` +\n \"The file must have one of:\\n\" +\n \" - A default-exported resolver (createResolver)\\n\" +\n \" - A default-exported executor (createExecutor) with function/jobFunction operation\\n\" +\n \" - A named-exported workflow job (createWorkflowJob)\\n\" +\n \" - A default-exported function\\n\" +\n ' - A named-exported \"main\" function',\n );\n}\n\n/**\n * Scan all named exports for workflow jobs.\n * If jobName is specified, find the job whose `.name` matches.\n * If not specified and exactly one job exists, use it.\n * If multiple jobs exist, throw an error with the list.\n * @param module - The imported module\n * @param jobName - Workflow job name to select\n * @returns Detected function or null if no workflow jobs found\n */\nfunction detectWorkflowJob(\n module: Record<string, unknown>,\n jobName?: string,\n): DetectedFunction | null {\n const jobs: Array<{ name: string; exportName: string }> = [];\n\n for (const [exportName, exportValue] of Object.entries(module)) {\n if (exportName === \"default\") continue;\n const result = WorkflowJobSchema.safeParse(exportValue);\n if (result.success) {\n jobs.push({ name: result.data.name, exportName });\n }\n }\n\n if (jobs.length === 0) {\n return null;\n }\n\n if (jobName) {\n const match = jobs.find((j) => j.name === jobName);\n if (!match) {\n const available = jobs.map((j) => ` - \"${j.name}\" (export: ${j.exportName})`).join(\"\\n\");\n throw new Error(`Workflow job \"${jobName}\" not found. Available jobs:\\n${available}`);\n }\n return { type: \"workflow-job\", name: match.name, exportName: match.exportName };\n }\n\n if (jobs.length === 1) {\n const [jobEntry] = jobs;\n const job = assertDefined(jobEntry, \"workflow job missing\");\n return {\n type: \"workflow-job\",\n name: job.name,\n exportName: job.exportName,\n };\n }\n\n const available = jobs.map((j) => ` - \"${j.name}\" (export: ${j.exportName})`).join(\"\\n\");\n throw new Error(`Multiple workflow jobs found. Specify one with --name:\\n${available}`);\n}\n\n/**\n * Derive a script name from a file path (filename without extension).\n * @param filePath - Absolute path to the function file\n * @returns Filename without extension\n */\nfunction deriveNameFromPath(filePath: string): string {\n return path.basename(filePath, path.extname(filePath));\n}\n","/**\n * `tailor function test-run` command\n *\n * Bundles and executes a function on the Tailor Platform server\n * without deploying (applying) the application.\n */\n\nimport * as fs from \"node:fs\";\nimport { create } from \"@bufbuild/protobuf\";\nimport { AuthInvokerSchema } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resolveResolverDefaultPermissionForFile } from \"#/cli/services/resolver/default-permission\";\nimport {\n resolveMachineUserInputSource,\n type MachineUserInputSource,\n workspaceArgs,\n} from \"#/cli/shared/args\";\nimport { initOperatorClient, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadMachineUserName, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { executeScript } from \"#/cli/shared/script-executor\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { bundleForTestRun, type ResolvedMachineUser } from \"./bundle\";\nimport { detectFunctionType } from \"./detect\";\nimport type { Jsonifiable } from \"type-fest\";\n\nexport const testRunCommand = defineAppCommand({\n name: \"test-run\",\n description: \"Run a function on the Tailor Platform server without deploying.\",\n // strip unknown keys\n args: z.object({\n ...workspaceArgs,\n file: arg(z.string(), {\n positional: true,\n description: \"Path to the function file\",\n }),\n name: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Workflow job name to run (matches the `name` field of createWorkflowJob)\",\n }),\n arg: arg(z.string().optional(), {\n alias: \"a\",\n description: \"JSON argument to pass to the function\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Machine user name for authentication. Falls back to the active profile's default machine user.\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_NAME\",\n }),\n config: arg(z.string().default(\"tailor.config.ts\"), {\n alias: \"c\",\n description: \"Path to SDK config file\",\n }),\n }),\n notes: `You can pass either a source file (\\`.ts\\`) or a pre-bundled file (\\`.js\\`).\nWhen a \\`.js\\` file is provided, detection and bundling are skipped and the file is executed as-is.\n\n> [!WARNING]\n> Workflow job \\`.start()\\` calls do not work in test-run mode.\n> Started jobs are not executed; only the target job's \\`body\\` function runs in isolation.`,\n examples: [\n {\n cmd: 'resolvers/add.ts --arg \\'{\"a\":1,\"b\":2}\\'',\n desc: \"Run a resolver with input arguments\",\n },\n {\n cmd: \"workflows/sample.ts --name validate-order\",\n desc: \"Run a specific workflow job by name\",\n },\n {\n cmd: 'build/resolvers/add.js --arg \\'{\"a\":1,\"b\":2}\\'',\n desc: \"Run a pre-bundled .js file directly\",\n },\n ],\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n\n // 1. Resolve and validate file path\n const filePath = path.resolve(args.file);\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n\n // 2. Load config (required)\n const { config } = await loadConfig(args.config);\n\n // 3. Resolve auth, workspace, and machine user info (needed before bundling)\n const authNamespace = resolveAuthNamespace(config.auth);\n const machineUserName = await resolveMachineUserName({\n cliMachineUser: args[\"machine-user\"],\n cliMachineUserSource: resolveMachineUserInputSource(args[\"machine-user\"]),\n profile: args.profile,\n authConfig: config.auth,\n });\n\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const machineUser = await resolveMachineUser({\n client,\n workspaceId,\n authNamespace,\n machineUserName,\n authConfig: config.auth,\n });\n\n // 4. Resolve bundled code and script name\n const relativePath = path.relative(process.cwd(), filePath);\n const isPreBundled = filePath.endsWith(\".js\");\n let bundledCode: string;\n let scriptName: string;\n let functionType: string | undefined;\n let functionName: string | undefined;\n\n if (isPreBundled) {\n // Pre-bundled .js file\n scriptName = path.basename(filePath);\n bundledCode = fs.readFileSync(filePath, \"utf-8\");\n logger.info(`Using pre-bundled script ${styles.bold(scriptName)}`);\n } else {\n // Source file: detect type and bundle\n logger.info(`Detecting function type from ${styles.path(relativePath)}`);\n\n const detected = await detectFunctionType({\n filePath,\n jobName: args.name,\n });\n\n functionType = detected.type;\n functionName = detected.name;\n logger.info(`Detected: ${styles.bold(detected.type)} ${styles.info(`\"${detected.name}\"`)}`);\n\n if (detected.type === \"resolver\" && args.arg && !detected.hasInput) {\n logger.warn(\n '--arg is ignored because this resolver has no input schema. Define \"input\" in your resolver to use --arg.',\n );\n args.arg = undefined;\n }\n\n logger.info(\"Bundling...\");\n const baseDir = path.dirname(config.path);\n ({ bundledCode, scriptName } = await bundleForTestRun({\n detected,\n sourceFile: filePath,\n baseDir,\n defaultPermission:\n detected.type === \"resolver\"\n ? resolveResolverDefaultPermissionForFile({\n config: config.resolver,\n filePath,\n baseDir,\n })\n : undefined,\n env: config.env ?? {},\n inlineSourcemap: config.inlineSourcemap,\n logLevel: config.logLevel,\n machineUser,\n workspaceId,\n }));\n logger.info(`Bundled as ${styles.bold(scriptName)}`);\n }\n\n // 5. Execute via TestExecScript\n const invoker = create(AuthInvokerSchema, {\n namespace: authNamespace,\n machineUserName: machineUser.name,\n });\n\n logger.info(`Executing on workspace ${styles.dim(workspaceId)}...`);\n\n let parsedArg: Jsonifiable | undefined;\n if (args.arg !== undefined) {\n try {\n parsedArg = JSON.parse(args.arg);\n } catch (error) {\n throw new Error(`Invalid --arg JSON: ${error instanceof Error ? error.message : error}`, {\n cause: error,\n });\n }\n }\n\n const result = await executeScript({\n client,\n workspaceId,\n name: scriptName,\n code: bundledCode,\n arg: parsedArg,\n invoker,\n });\n\n // 7. Display result\n if (jsonOutput) {\n logger.out({\n success: result.success,\n scriptName,\n functionType,\n functionName,\n logs: result.logs,\n result: result.result,\n error: result.error,\n });\n } else {\n if (result.success) {\n logger.success(\"Execution succeeded\");\n } else {\n logger.error(\"Execution failed\");\n }\n\n if (result.logs.trim()) {\n logger.log(styles.bold(\"\\nLogs:\"));\n for (const line of result.logs.split(\"\\n\")) {\n logger.log(` ${line}`);\n }\n }\n\n if (result.result && result.success) {\n logger.log(styles.bold(\"\\nResult:\"));\n try {\n const parsed = JSON.parse(result.result);\n logger.log(` ${JSON.stringify(parsed, null, 2).split(\"\\n\").join(\"\\n \")}`);\n } catch {\n logger.log(` ${result.result}`);\n }\n }\n\n if (result.error && !result.success) {\n logger.log(styles.bold(\"\\nError:\"));\n const formatted = formatErrorWithSourcemap(result.error, bundledCode, process.cwd());\n if (formatted) {\n logger.log(formatted);\n } else {\n logger.log(` ${styles.error(result.error)}`);\n }\n }\n }\n\n if (!result.success) {\n process.exit(1);\n }\n },\n});\n\n/**\n * Resolve auth namespace from config.\n * @param authConfig - Auth configuration from tailor.config.ts\n * @returns Resolved auth namespace\n */\nfunction resolveAuthNamespace(\n authConfig: { name: string; external?: boolean } | undefined,\n): string {\n if (authConfig?.name) {\n return authConfig.name;\n }\n throw new Error(\"Auth namespace is required. Ensure tailor.config.ts has an auth config.\");\n}\n\ntype ResolveMachineUserNameOptions = {\n cliMachineUser: string | undefined;\n cliMachineUserSource: MachineUserInputSource | undefined;\n profile: string | undefined;\n authConfig:\n | { name: string; external?: boolean; machineUsers?: Record<string, unknown> }\n | undefined;\n};\n\n/**\n * Resolve machine user name from CLI args, profile default, or config.\n * Priority: --machine-user / env > profile default > first key of config.auth.machineUsers > error\n * @param options - Resolution options\n * @returns Resolved machine user name\n */\nasync function resolveMachineUserName(options: ResolveMachineUserNameOptions): Promise<string> {\n const { cliMachineUser, cliMachineUserSource, profile, authConfig } = options;\n\n const resolved = await loadMachineUserName({\n machineUser: cliMachineUser,\n machineUserSource: cliMachineUserSource,\n profile,\n });\n if (resolved) {\n return resolved;\n }\n\n if (authConfig && !(\"external\" in authConfig && authConfig.external)) {\n const machineUsers = authConfig.machineUsers;\n if (machineUsers) {\n const keys = Object.keys(machineUsers);\n if (keys.length > 0) {\n return assertDefined(keys[0], \"machine user key missing\");\n }\n }\n }\n throw new Error(\n \"Machine user is required. Provide --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, set a profile default with 'tailor profile update <profile> --machine-user <name>', or ensure tailor.config.ts has machine users configured.\",\n );\n}\n\ninterface ResolveMachineUserOptions {\n client: OperatorClient;\n workspaceId: string;\n authNamespace: string;\n machineUserName: string;\n authConfig:\n | { name: string; external?: boolean; machineUsers?: Record<string, unknown> }\n | undefined;\n}\n\n/**\n * Resolve full machine user info: name, id (from API), and attributes (from config).\n * @param options - Options for resolving machine user\n * @returns Resolved machine user with id, attributes, and attributeList\n */\nasync function resolveMachineUser(\n options: ResolveMachineUserOptions,\n): Promise<ResolvedMachineUser> {\n const { client, workspaceId, authNamespace, machineUserName, authConfig } = options;\n\n // Get machine user ID from the server\n let id = \"00000000-0000-0000-0000-000000000000\";\n try {\n const { machineUser } = await client.getAuthMachineUser({\n workspaceId,\n authNamespace,\n name: machineUserName,\n });\n if (machineUser?.id) {\n id = machineUser.id;\n }\n } catch {\n logger.debug(`Could not fetch machine user \"${machineUserName}\" from server, using nil UUID`);\n }\n\n // Get attributes from config\n const machineUserConfig = authConfig?.machineUsers?.[machineUserName];\n let attributes: Record<string, unknown> | null = null;\n let attributeList: unknown[] = [];\n if (machineUserConfig && typeof machineUserConfig === \"object\") {\n const cfg = machineUserConfig as {\n attributes?: Record<string, unknown>;\n attributeList?: unknown[];\n };\n attributes = cfg.attributes ?? null;\n attributeList = cfg.attributeList ?? [];\n }\n\n return { name: machineUserName, id, attributes, attributeList };\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { logsCommand } from \"./logs\";\nimport { testRunCommand } from \"./test-run\";\n\nexport const functionCommand = defineCommand({\n name: \"function\",\n description: \"Manage functions\",\n subCommands: {\n get: getCommand,\n list: listCommand,\n logs: logsCommand,\n \"test-run\": testRunCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { generate } from \"#/cli/commands/generate/service\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\n\nexport const generateCommand = defineAppCommand({\n name: \"generate\",\n description: \"Generate files using Tailor configuration.\",\n args: z.strictObject({\n config: arg(z.string().default(\"tailor.config.ts\"), {\n alias: \"c\",\n description: \"Path to SDK config file\",\n }),\n }),\n run: async (args) => {\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n await generate({\n configPath: args.config,\n });\n },\n});\n","import { spawnSync } from \"node:child_process\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\n\nconst detectPackageManager = () => {\n const availablePMs = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n const userAgent = process.env.npm_config_user_agent;\n if (!userAgent) return;\n const [name] = userAgent.split(\"/\") as [string, ...string[]];\n if (!availablePMs.includes(name)) return;\n return name;\n};\n\nexport const initCommand = defineAppCommand({\n name: \"init\",\n description: \"Initialize a new project using create-sdk.\",\n args: z.strictObject({\n name: arg(z.string().optional(), {\n positional: true,\n description: \"Project name\",\n }),\n template: arg(z.string().optional(), {\n alias: \"t\",\n description: \"Template name\",\n }),\n }),\n run: async (args) => {\n const packageJson = await readPackageJson();\n const version =\n packageJson.version && packageJson.version !== \"0.0.0\" ? packageJson.version : \"latest\";\n\n let packageManager = detectPackageManager();\n if (!packageManager) {\n logger.warn(\"Could not detect package manager, defaulting to npm\");\n packageManager = \"npm\";\n }\n const initArgs = [\n \"create\",\n `@tailor-platform/sdk@${version}`,\n ...(args.name ? [args.name] : []),\n ...(packageManager === \"npm\" ? [\"--\"] : []),\n ...(args.template ? [\"--template\", args.template] : []),\n ];\n logger.log(`Running: ${packageManager} ${initArgs.join(\" \")}`);\n\n spawnSync(packageManager, initArgs, { stdio: \"inherit\" });\n },\n});\n","import * as crypto from \"node:crypto\";\nimport * as http from \"node:http\";\nimport { generateCodeVerifier } from \"@badgateway/oauth2-client\";\nimport open from \"open\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport {\n closeConnectionPool,\n fetchPlatformMachineUserToken,\n fetchUserInfo,\n initOAuth2Client,\n isDefaultPlatform,\n type PlatformClientConfig,\n} from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n removeLegacyUserAlias,\n saveUserTokens,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\n\nconst redirectPort = 8085;\nconst redirectUri = `http://localhost:${redirectPort}/callback`;\ntype ProfileLoginOptions = {\n profile?: string;\n profileUser?: string;\n platformConfig?: PlatformClientConfig;\n updateCurrentUser?: boolean;\n loginMode?: \"user\" | \"machine-user\";\n};\ntype ProfileUserMismatch = {\n profile: string;\n oldUser: string;\n authenticatedUser: string;\n loginMode: \"user\" | \"machine-user\";\n};\n\nfunction randomState() {\n return crypto.randomBytes(32).toString(\"base64url\");\n}\n\nfunction getProfileUserMismatch(\n args: ProfileLoginOptions,\n authenticatedUser: string,\n authenticatedSubject?: string,\n): ProfileUserMismatch | undefined {\n if (\n !args.profile ||\n !args.profileUser ||\n authenticatedUser === args.profileUser ||\n authenticatedSubject === args.profileUser\n ) {\n return undefined;\n }\n return {\n profile: args.profile,\n oldUser: args.profileUser,\n authenticatedUser,\n loginMode: args.loginMode ?? \"user\",\n };\n}\n\nfunction quoteCommandArg(value: string, platform: NodeJS.Platform = process.platform) {\n if (platform === \"win32\") {\n if (/^[A-Za-z0-9_./:@+=,-]+$/.test(value)) {\n return value;\n }\n return undefined;\n }\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction profileUpdateCommand(mismatch: ProfileUserMismatch) {\n const profileArg = quoteCommandArg(mismatch.profile);\n const userArg = quoteCommandArg(mismatch.authenticatedUser);\n if (profileArg && userArg) {\n return `tailor profile update --user ${userArg} -- ${profileArg}`;\n }\n return [\n \"tailor profile update --user <authenticated-user> -- <profile>\",\n `profile = ${JSON.stringify(mismatch.profile)}`,\n `authenticated user = ${JSON.stringify(mismatch.authenticatedUser)}`,\n ].join(\"\\n\");\n}\n\nfunction retryInstruction(mismatch: ProfileUserMismatch) {\n if (mismatch.loginMode === \"machine-user\") {\n return \"Then retry the original machine-user login command.\";\n }\n const profileArg = quoteCommandArg(mismatch.profile);\n if (!profileArg) {\n return \"Then retry the browser login with the same profile value.\";\n }\n return `Then run:\\n tailor login --profile ${profileArg}`;\n}\n\nfunction profileUserMismatchError(mismatch: ProfileUserMismatch) {\n const updateCommand = profileUpdateCommand(mismatch);\n const nextStep = retryInstruction(mismatch);\n return new Error(ml`\n Profile \"${mismatch.profile}\" is configured for \"${mismatch.oldUser}\", but login authenticated \"${mismatch.authenticatedUser}\".\n The authenticated user has been saved. To use it with this profile, run:\n ${updateCommand}\n ${nextStep}\n `);\n}\n\nfunction shouldUpdateCurrentUser(\n profile: string | undefined,\n platformConfig: PlatformClientConfig | undefined,\n) {\n if (!profile) return true;\n return isDefaultPlatform(platformConfig);\n}\n\nconst startAuthServer = async (args: ProfileLoginOptions = {}) => {\n const client = initOAuth2Client(args.platformConfig);\n const state = randomState();\n const codeVerifier = await generateCodeVerifier();\n\n return new Promise<void>((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n try {\n if (!req.url?.startsWith(\"/callback\")) {\n throw new Error(\"Invalid callback URL\");\n }\n const tokens = await client.authorizationCode.getTokenFromCodeRedirect(\n `http://${req.headers.host}${req.url}`,\n {\n redirectUri: redirectUri,\n state,\n codeVerifier,\n },\n );\n const userInfo = await fetchUserInfo(tokens.accessToken, args.platformConfig);\n\n const pfConfig = await readPlatformConfig();\n await saveUserTokens(\n pfConfig,\n userInfo.sub,\n {\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken ?? undefined,\n },\n new Date(\n assertDefined(tokens.expiresAt, \"token response missing expiresAt\"),\n ).toISOString(),\n { platformConfig: args.platformConfig, email: userInfo.email },\n );\n const mismatch = getProfileUserMismatch(args, userInfo.email, userInfo.sub);\n if (mismatch) {\n writePlatformConfig(pfConfig);\n throw profileUserMismatchError(mismatch);\n }\n if (args.updateCurrentUser ?? true) {\n pfConfig.current_user = userInfo.sub;\n }\n await removeLegacyUserAlias(pfConfig, userInfo.email, userInfo.sub, args.platformConfig);\n writePlatformConfig(pfConfig);\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n status: \"ok\",\n message: \"Successfully authenticated. Please close this window.\",\n }),\n );\n resolve();\n } catch (error) {\n res.writeHead(401);\n res.end(\"Authentication failed\");\n reject(error);\n } finally {\n // Close the server after handling one request.\n server.close();\n }\n });\n\n const timeout = setTimeout(\n () => {\n server.close();\n reject(new Error(\"Login timeout exceeded\"));\n },\n 5 * 60 * 1000,\n );\n\n server.on(\"close\", () => {\n clearTimeout(timeout);\n });\n\n server.on(\"error\", (error) => {\n reject(error);\n });\n\n server.listen(redirectPort, async () => {\n const authorizeUri = await client.authorizationCode.getAuthorizeUri({\n redirectUri,\n state,\n codeVerifier,\n });\n\n logger.info(`Opening browser for login:\\n\\n${authorizeUri}\\n`);\n try {\n await open(authorizeUri);\n } catch {\n logger.warn(\"Failed to open browser automatically. Please open the URL above manually.\");\n }\n });\n });\n};\n\nasync function loginAsMachineUser(\n args: { clientId: string; clientSecret?: string } & ProfileLoginOptions,\n) {\n const clientSecret = args.clientSecret ?? (await prompt.password({ message: \"Client secret\" }));\n const tokens = await fetchPlatformMachineUserToken(\n args.clientId,\n clientSecret,\n args.platformConfig,\n );\n\n const pfConfig = await readPlatformConfig();\n await saveUserTokens(\n pfConfig,\n args.clientId,\n { accessToken: tokens.accessToken },\n new Date(assertDefined(tokens.expiresAt, \"token response missing expiresAt\")).toISOString(),\n { platformConfig: args.platformConfig },\n );\n const mismatch = getProfileUserMismatch(args, args.clientId);\n if (mismatch) {\n writePlatformConfig(pfConfig);\n throw profileUserMismatchError(mismatch);\n }\n if (args.updateCurrentUser ?? true) {\n pfConfig.current_user = args.clientId;\n }\n writePlatformConfig(pfConfig);\n}\n\nexport const loginCommand = defineAppCommand({\n name: \"login\",\n description: \"Login to Tailor Platform.\",\n args: z.xor([\n z\n .strictObject({\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for login.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n })\n .describe(\"User Login\"),\n z\n .strictObject({\n \"machine-user\": arg(z.literal(true), {\n description: \"Login as a platform machine user.\",\n required: true,\n }),\n \"client-id\": arg(z.string(), {\n description: \"Client ID\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID\",\n required: true,\n }),\n \"client-secret\": arg(z.string().optional(), {\n description: \"Client secret\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET\",\n }),\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for login.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n })\n .describe(\"Machine User Login\"),\n ]),\n run: async (args) => {\n try {\n let platformConfig: PlatformClientConfig | undefined;\n let profileUser: string | undefined;\n if (\"profile\" in args && args.profile) {\n const pfConfig = await readPlatformConfig();\n const profileEntry = pfConfig.profiles[args.profile];\n if (!profileEntry) {\n throw new Error(`Profile \"${args.profile}\" not found`);\n }\n platformConfig = platformConfigFromProfile(profileEntry);\n profileUser = profileEntry.user;\n }\n const updateCurrentUser = shouldUpdateCurrentUser(args.profile, platformConfig);\n if (\"machine-user\" in args) {\n await loginAsMachineUser({\n clientId: args.clientId,\n clientSecret: args.clientSecret,\n profile: args.profile,\n profileUser,\n platformConfig,\n updateCurrentUser,\n loginMode: \"machine-user\",\n });\n } else {\n await startAuthServer({\n profile: args.profile,\n profileUser,\n platformConfig,\n updateCurrentUser,\n loginMode: \"user\",\n });\n }\n logger.success(\"Successfully logged in to Tailor Platform.\");\n } finally {\n await closeConnectionPool();\n }\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defaultPlatformBaseUrl, initOAuth2Client, isDefaultPlatform } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n deleteUserTokens,\n hasAnyUserTokenEntry,\n hasUserTokenEntry,\n loadStoredUserTokens,\n platformConfigFromProfile,\n readPlatformConfig,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const logoutCommand = defineAppCommand({\n name: \"logout\",\n description: \"Logout from Tailor Platform.\",\n args: z.strictObject({\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for logout.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n }),\n run: async (args) => {\n const profile = args.profile || process.env.TAILOR_PLATFORM_PROFILE;\n const pfConfig = await readPlatformConfig();\n const profileEntry = profile ? pfConfig.profiles[profile] : undefined;\n if (profile && !profileEntry) {\n throw new Error(`Profile \"${profile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const currentUser = profileEntry ? profileEntry.user : pfConfig.current_user;\n const deletesDefaultToken = isDefaultPlatform(platformConfig);\n const lookupOptions = profile ? { allowLegacyUserKey: true } : undefined;\n if (!currentUser) {\n logger.info(\"You are not logged in.\");\n return;\n }\n const hasDefaultUserToken = () =>\n hasUserTokenEntry(pfConfig, currentUser, { platformUrl: defaultPlatformBaseUrl });\n const shouldClearCurrentUser = () =>\n pfConfig.current_user === currentUser &&\n (deletesDefaultToken\n ? !hasDefaultUserToken()\n : !hasAnyUserTokenEntry(pfConfig, currentUser) && !hasDefaultUserToken());\n let storedTokens: Awaited<ReturnType<typeof loadStoredUserTokens>>;\n let tokenLoadFailed = false;\n try {\n storedTokens = await loadStoredUserTokens(\n pfConfig,\n currentUser,\n platformConfig,\n lookupOptions,\n );\n } catch (error) {\n tokenLoadFailed = true;\n logger.warn(`Failed to revoke token: ${error instanceof Error ? error.message : error}`);\n }\n if (!storedTokens && !tokenLoadFailed) {\n logger.info(\"You are not logged in.\");\n if (shouldClearCurrentUser()) {\n pfConfig.current_user = null;\n }\n writePlatformConfig(pfConfig);\n return;\n }\n\n if (storedTokens) {\n try {\n const client = initOAuth2Client(platformConfig);\n const tokenTypeHint = storedTokens.refreshToken ? \"refresh_token\" : \"access_token\";\n await client.revoke(\n {\n accessToken: storedTokens.accessToken,\n refreshToken: storedTokens.refreshToken ?? null,\n expiresAt: Date.parse(storedTokens.userEntry.token_expires_at),\n },\n tokenTypeHint,\n );\n } catch (error) {\n logger.warn(`Failed to revoke token: ${error instanceof Error ? error.message : error}`);\n }\n }\n\n await deleteUserTokens(pfConfig, currentUser, platformConfig, lookupOptions);\n if (shouldClearCurrentUser()) {\n pfConfig.current_user = null;\n }\n writePlatformConfig(pfConfig);\n logger.success(\"Successfully logged out from Tailor Platform.\");\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\nimport { tokenCommand } from \"./token\";\n\nexport const machineuserCommand = defineCommand({\n name: \"machineuser\",\n description: \"Manage machine users in your Tailor Platform application.\",\n subCommands: {\n list: listCommand,\n token: tokenCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\n\nexport const oauth2clientCommand = defineCommand({\n name: \"oauth2client\",\n description: \"Manage OAuth2 clients in your Tailor Platform application.\",\n subCommands: {\n list: listCommand,\n get: getCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import open from \"open\";\nimport { z } from \"zod\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadConsoleBaseUrl, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const openCommand = defineAppCommand({\n name: \"open\",\n description: \"Open Tailor Platform Console.\",\n args: z.strictObject({\n ...deploymentArgs,\n }),\n run: async (args) => {\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n const { config } = await loadConfig(args.config);\n const applicationName = config.name;\n const consolePath = `/workspaces/${workspaceId}/applications/${encodeURIComponent(applicationName)}/overview`;\n const consoleBaseUrl = await loadConsoleBaseUrl({\n profile: args.profile,\n ...(args[\"workspace-id\"] !== undefined ? { allowMissingProfile: true } : {}),\n });\n const consoleUrl = new URL(consolePath, consoleBaseUrl).toString();\n const jsonOutput = logger.jsonMode;\n\n logger.info(\"Opening Tailor Platform Console...\");\n\n let opened = true;\n try {\n await open(consoleUrl);\n } catch {\n opened = false;\n }\n\n if (jsonOutput) {\n logger.out({ consoleUrl, workspaceId, applicationName, opened });\n return;\n }\n\n if (opened) {\n logger.out(`Console URL: ${consoleUrl}`);\n logger.out(`Workspace ID: ${workspaceId}`);\n logger.out(`Application Name: ${applicationName}`);\n } else {\n logger.warn(\n `Failed to open browser automatically. Please open this URL manually:\\n${consoleUrl}`,\n );\n }\n },\n});\n","import { defineCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport const folderCommand = defineCommand({\n name: \"folder\",\n description: \"Manage organization folders.\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n get: getCommand,\n list: listCommand,\n update: updateCommand,\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { folderCommand } from \"./folder\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { treeCommand } from \"./tree\";\nimport { updateCommand } from \"./update\";\n\nexport const organizationCommand = defineCommand({\n name: \"organization\",\n description: \"Manage Tailor Platform organizations.\",\n subCommands: {\n folder: folderCommand,\n get: getCommand,\n list: listCommand,\n tree: treeCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","/**\n * Top-level builtin command names. A plugin named the same as one of these is\n * shadowed by the builtin and can never be dispatched.\n *\n * This list is the single source of truth used by `plugin list` to flag\n * shadowed plugins without importing the (cyclic) command tree. It is kept in\n * sync with `main-command.ts` by a drift test in `options.test.ts`.\n */\nexport const BUILTIN_COMMAND_NAMES = [\n \"api\",\n \"auth\",\n \"authconnection\",\n \"crashreport\",\n \"deploy\",\n \"executor\",\n \"function\",\n \"generate\",\n \"init\",\n \"login\",\n \"logout\",\n \"machineuser\",\n \"oauth2client\",\n \"open\",\n \"organization\",\n \"plugin\",\n \"profile\",\n \"query\",\n \"remove\",\n \"secret\",\n \"setup\",\n \"show\",\n \"skills\",\n \"staticwebsite\",\n \"tailordb\",\n \"upgrade\",\n \"user\",\n \"workflow\",\n \"workspace\",\n] as const;\n","import { spawn } from \"node:child_process\";\nimport { accessSync, constants, readdirSync } from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"pathe\";\nimport { getOAuth2ClientId, getPlatformBaseUrl, type PlatformClientConfig } from \"./client\";\nimport {\n loadAccessToken,\n loadConfigPath,\n loadPlatformClientConfig,\n loadWorkspaceId,\n readPlatformConfig,\n} from \"./context\";\nimport { logger } from \"./logger\";\nimport { readPackageJson } from \"./package-json\";\n\n/**\n * npm packages known to provide a plugin slug, keyed by the slug the\n * dispatcher resolves (command path joined with `-`). Used to suggest an\n * install command when the plugin executable is not found.\n */\nconst KNOWN_PLUGIN_PACKAGES: Record<string, string> = {\n seed: \"@tailor-platform/sdk-plugin-seed\",\n \"tailordb-erd\": \"@tailor-platform/sdk-plugin-tailordb-erd\",\n};\n\n/**\n * A plugin discovered on the filesystem. `tailor <name>` dispatches to the\n * external `tailor-<name>` executable.\n */\nexport interface DiscoveredPlugin {\n /** Plugin name (the part after the `<cli>-` prefix). */\n name: string;\n /** Absolute path to the executable. */\n path: string;\n /** Where the executable was found. */\n source: \"node_modules\" | \"path\";\n}\n\n/** PATH entry separator (`;` on Windows, `:` elsewhere). */\nconst pathDelimiter = process.platform === \"win32\" ? \";\" : \":\";\n\n/**\n * Yield `start` and each ancestor directory up to the filesystem root.\n * @param start - Directory to start from\n * @yields Each ancestor directory, starting with `start`\n */\nfunction* ancestorDirs(start: string): Generator<string> {\n let dir = path.resolve(start);\n // Walk up until `dirname` stops changing (the filesystem root), yielding the\n // root on the final iteration.\n let parent = path.dirname(dir);\n while (parent !== dir) {\n yield dir;\n dir = parent;\n parent = path.dirname(dir);\n }\n yield dir;\n}\n\n/** Fallback executable extensions when `PATHEXT` is unset (Windows). */\nconst DEFAULT_PATHEXT = \".COM;.EXE;.BAT;.CMD;.PS1\";\n\n/**\n * Lowercased executable extensions from `PATHEXT` (Windows).\n * @returns Recognized executable extensions (e.g. `.exe`, `.cmd`)\n */\nfunction windowsExecutableExts(): string[] {\n return (process.env.PATHEXT ?? DEFAULT_PATHEXT)\n .split(\";\")\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean);\n}\n\n/**\n * Check whether a path exists and is runnable: X_OK on POSIX; on Windows, the\n * file must exist and either be extension-less (shebang script) or carry a\n * `PATHEXT` extension, so plain data files are not mistaken for plugins.\n * @param filePath - Path to check\n * @returns Whether the path is an executable file\n */\nfunction isExecutable(filePath: string): boolean {\n try {\n accessSync(filePath, process.platform === \"win32\" ? constants.F_OK : constants.X_OK);\n } catch {\n return false;\n }\n if (process.platform === \"win32\") {\n const ext = path.extname(filePath).toLowerCase();\n return ext === \"\" || windowsExecutableExts().includes(ext);\n }\n return true;\n}\n\n/**\n * Candidate file names for a plugin binary, accounting for Windows extensions.\n * @param binName - Base binary name (e.g. `tailor-foo`)\n * @returns Ordered candidate file names\n */\nfunction binaryCandidates(binName: string): string[] {\n if (process.platform !== \"win32\") {\n return [binName];\n }\n // Bare name first (shebang scripts), then PATHEXT variants.\n return [binName, ...windowsExecutableExts().map((ext) => `${binName}${ext}`)];\n}\n\n/**\n * Directories on the user's PATH.\n * @returns PATH entries\n */\nfunction pathDirs(): string[] {\n return (process.env.PATH ?? \"\").split(pathDelimiter).filter(Boolean);\n}\n\n/**\n * Nearest `node_modules/.bin` directories, walking up from the current working\n * directory. Project-local bins take precedence over those higher in the tree.\n * @returns Ordered `node_modules/.bin` directories\n */\nfunction nodeModulesBinDirs(): string[] {\n const dirs: string[] = [];\n for (const dir of ancestorDirs(process.cwd())) {\n dirs.push(path.join(dir, \"node_modules\", \".bin\"));\n }\n return dirs;\n}\n\n/**\n * Find the first existing executable for the given base name across a set of\n * directories.\n * @param dirs - Directories to search\n * @param binName - Base binary name\n * @returns Absolute path, or undefined when not found\n */\nfunction findExecutableIn(dirs: string[], binName: string): string | undefined {\n const candidates = binaryCandidates(binName);\n for (const dir of dirs) {\n for (const candidate of candidates) {\n const full = path.join(dir, candidate);\n if (isExecutable(full)) return full;\n }\n }\n return undefined;\n}\n\n/**\n * Resolve a plugin executable by name.\n * Search order: project-local `node_modules/.bin` (nearest first), then PATH.\n * @param name - Plugin name (without the `<cli>-` prefix)\n * @param cliName - The host CLI name (e.g. `tailor`)\n * @returns The discovered plugin, or null when not found\n */\nexport function resolvePlugin(name: string, cliName: string): DiscoveredPlugin | null {\n // Reject names that could escape the `<cli>-` prefix via path traversal\n // (e.g. `../evil`) or embed a NUL, before joining them into a filesystem path.\n if (name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\")) {\n return null;\n }\n const binName = `${cliName}-${name}`;\n\n const fromNodeModules = findExecutableIn(nodeModulesBinDirs(), binName);\n if (fromNodeModules) {\n return { name, path: fromNodeModules, source: \"node_modules\" };\n }\n\n const fromPath = findExecutableIn(pathDirs(), binName);\n if (fromPath) {\n return { name, path: fromPath, source: \"path\" };\n }\n\n return null;\n}\n\n/**\n * Strip a known binary extension from a file name (Windows).\n * @param fileName - File name\n * @returns File name without a recognized executable extension\n */\nfunction stripBinExt(fileName: string): string {\n if (process.platform !== \"win32\") return fileName;\n const ext = path.extname(fileName);\n return ext ? fileName.slice(0, -ext.length) : fileName;\n}\n\n/**\n * Discover all plugins reachable from `node_modules/.bin` and PATH.\n * Earlier entries win on name collisions (project-local over PATH).\n * @param cliName - The host CLI name (e.g. `tailor`)\n * @returns Discovered plugins, deduped by name\n */\nexport function listPlugins(cliName: string): DiscoveredPlugin[] {\n const prefix = `${cliName}-`;\n const seen = new Map<string, DiscoveredPlugin>();\n\n const scan = (dirs: string[], source: DiscoveredPlugin[\"source\"]) => {\n for (const dir of dirs) {\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n const base = stripBinExt(entry);\n if (!base.startsWith(prefix) || base.length === prefix.length) continue;\n const name = base.slice(prefix.length);\n if (seen.has(name)) continue;\n const full = path.join(dir, entry);\n if (!isExecutable(full)) continue;\n seen.set(name, { name, path: full, source });\n }\n }\n };\n\n scan(nodeModulesBinDirs(), \"node_modules\");\n scan(pathDirs(), \"path\");\n\n return [...seen.values()];\n}\n\n/**\n * Options for {@link buildPluginEnv}.\n */\ninterface PluginContextOptions {\n /** Active profile used to resolve the workspace, user, and token. */\n profile?: string | undefined;\n /** Skip platform context (URL, client ID, workspace, user, token) injection. */\n skipPlatformContext?: boolean;\n}\n\n/**\n * Resolve the active user identifier, preferring the stored email over the\n * internal user key.\n * @param profile - Active profile name, if any\n * @returns The resolved user (email when known), or undefined when not logged in\n */\nasync function resolveActiveUser(profile?: string): Promise<string | undefined> {\n const config = await readPlatformConfig();\n const user = profile ? config.profiles[profile]?.user : config.current_user;\n if (!user) return undefined;\n return config.users[user]?.email ?? user;\n}\n\n/**\n * Build the environment variables injected into a dispatched plugin.\n * Workspace, user, and token are resolved best-effort: whichever the current\n * context can provide is injected, and the rest are omitted so auth-free\n * plugins still run.\n * @param options - Plugin context options\n * @returns Environment variables to merge into the child process env\n */\nasync function buildPluginEnv(options: PluginContextOptions = {}): Promise<Record<string, string>> {\n const { profile } = options;\n const env: Record<string, string> = {};\n\n const binPath = process.argv[1];\n if (binPath) {\n env.TAILOR_BIN = binPath;\n }\n\n try {\n const { version } = await readPackageJson();\n if (version) env.TAILOR_VERSION = version;\n } catch {\n // Version is informational; skip when unavailable.\n }\n\n const configPath = loadConfigPath();\n if (configPath) {\n env.TAILOR_CONFIG_PATH = configPath;\n }\n\n // An explicit --env-file supplies the plugin's platform context itself.\n // Injected values would shadow it (the plugin's env-file loader never\n // overwrites pre-existing keys), so skip context injection entirely.\n if (options.skipPlatformContext) {\n return env;\n }\n\n // Resolve the active profile's platform settings so the injected URL and\n // OAuth client match the profile the token and workspace belong to.\n let platformConfig: PlatformClientConfig | undefined;\n try {\n platformConfig = await loadPlatformClientConfig({ profile, allowMissingProfile: true });\n } catch {\n // Fall back to env/default platform settings when the profile is unreadable.\n }\n env.TAILOR_PLATFORM_URL = getPlatformBaseUrl(platformConfig);\n env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID = getOAuth2ClientId(platformConfig);\n\n try {\n env.TAILOR_PLATFORM_WORKSPACE_ID = await loadWorkspaceId({ profile });\n } catch {\n // No workspace resolvable; plugins that need it surface their own error.\n }\n\n try {\n const user = await resolveActiveUser(profile);\n if (user) env.TAILOR_PLATFORM_USER = user;\n } catch {\n // User context is best-effort; skip when the config is unreadable.\n }\n\n try {\n const token = await loadAccessToken({ profile });\n if (token) env.TAILOR_PLATFORM_TOKEN = token;\n } catch {\n // Not logged in (or no token): dispatch without a token so auth-free\n // plugins still work. Auth-requiring plugins surface their own error\n // (e.g. via `tailor auth token`).\n }\n\n return env;\n}\n\n/**\n * Map an exit signal to a conventional exit code (128 + signal number).\n * @param signal - Signal name\n * @returns Exit code\n */\nfunction signalToExitCode(signal: NodeJS.Signals): number {\n const num = os.constants.signals[signal];\n return typeof num === \"number\" ? 128 + num : 1;\n}\n\n/**\n * Build the command + args for spawning a plugin, handling Windows shebang\n * scripts via `sh` (following the `gh` extension dispatcher).\n * @param pluginPath - Resolved plugin executable path\n * @param args - Args to forward to the plugin\n * @returns Spawn command, args, and whether a shell is required\n */\nfunction buildSpawnTarget(\n pluginPath: string,\n args: readonly string[],\n): { command: string; args: string[]; shell: boolean } {\n if (process.platform !== \"win32\") {\n return { command: pluginPath, args: [...args], shell: false };\n }\n\n const ext = path.extname(pluginPath).toLowerCase();\n if (ext === \".exe\" || ext === \".com\") {\n return { command: pluginPath, args: [...args], shell: false };\n }\n if (ext === \".cmd\" || ext === \".bat\") {\n // .cmd/.bat must run through the shell on Windows.\n return { command: pluginPath, args: [...args], shell: true };\n }\n if (ext === \".ps1\") {\n // PowerShell scripts are not directly executable via spawn.\n const pwsh =\n findExecutableIn(pathDirs(), \"pwsh\") ??\n findExecutableIn(pathDirs(), \"powershell\") ??\n \"powershell\";\n return {\n command: pwsh,\n args: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", pluginPath, ...args],\n shell: false,\n };\n }\n\n // Extension-less shebang script: dispatch through `sh` (Git for Windows).\n const sh = findExecutableIn(pathDirs(), \"sh\") ?? \"sh\";\n return { command: sh, args: [\"-c\", 'command \"$@\"', \"--\", pluginPath, ...args], shell: false };\n}\n\n/**\n * Check whether args forwarded to a plugin carry an explicit env-file flag.\n * Scanning stops at a `--` terminator. The check is presence-only:\n * `--env-file-if-exists` counts even when the named file does not exist, so\n * no platform context is injected in that case either.\n * @param args - Args forwarded to the plugin\n * @returns Whether an `--env-file`/`-e`/`--env-file-if-exists` flag is present\n */\nexport function hasEnvFileFlag(args: readonly string[]): boolean {\n for (const token of args) {\n if (token === \"--\") return false;\n if (token === \"--env-file\" || token === \"-e\" || token === \"--env-file-if-exists\") {\n return true;\n }\n if (\n token.startsWith(\"--env-file=\") ||\n token.startsWith(\"-e=\") ||\n token.startsWith(\"--env-file-if-exists=\")\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Extract an explicit `--profile`/`-p` value from args forwarded to a plugin,\n * so the injected platform context matches the profile the plugin will use.\n * Scanning stops at a `--` terminator; the last occurrence wins.\n * @param args - Args forwarded to the plugin\n * @returns The explicit profile value, or undefined when not present\n */\nexport function explicitProfileFromArgs(args: readonly string[]): string | undefined {\n let profile: string | undefined;\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n if (token === undefined || token === \"--\") break;\n if (token === \"--profile\" || token === \"-p\") {\n const next = args[i + 1];\n if (next !== undefined && !next.startsWith(\"-\")) {\n profile = next;\n i++;\n }\n continue;\n }\n if (token.startsWith(\"--profile=\")) {\n profile = token.slice(\"--profile=\".length);\n } else if (token.startsWith(\"-p=\")) {\n profile = token.slice(\"-p=\".length);\n }\n }\n return profile || undefined;\n}\n\n/**\n * Parameters for {@link dispatchPlugin}.\n */\ninterface DispatchPluginParams {\n /** Plugin name (the part after the `<cli>-` prefix). */\n name: string;\n /** Args to forward to the plugin. */\n args: readonly string[];\n /** The host CLI name (e.g. `tailor`). */\n cliName: string;\n /** Parent command path preceding the unknown subcommand, if any. */\n commandPath?: readonly string[] | undefined;\n /** Active profile name, if any. */\n profile?: string | undefined;\n}\n\n/**\n * Build the plugin slug from the known command path plus the unknown name,\n * so `tailor tailordb erd` resolves `tailor-tailordb-erd`.\n * @param commandPath - Parent command path preceding the unknown subcommand\n * @param name - Unknown subcommand name\n * @returns The plugin slug\n */\nfunction pluginSlug(commandPath: readonly string[] | undefined, name: string): string {\n return [...(commandPath ?? []), name].join(\"-\");\n}\n\n/**\n * Resolve and execute a plugin, forwarding stdio and propagating its exit code.\n * @param params - Dispatch parameters\n * @returns The plugin's exit code, or undefined when no matching plugin exists\n */\nexport async function dispatchPlugin(params: DispatchPluginParams): Promise<number | undefined> {\n const slug = pluginSlug(params.commandPath, params.name);\n const plugin = resolvePlugin(slug, params.cliName);\n if (!plugin) {\n return undefined;\n }\n\n const profile = explicitProfileFromArgs(params.args) ?? params.profile;\n const env = {\n ...process.env,\n ...(await buildPluginEnv({ profile, skipPlatformContext: hasEnvFileFlag(params.args) })),\n };\n const { command, args, shell } = buildSpawnTarget(plugin.path, params.args);\n\n return await new Promise<number>((resolve) => {\n const child = spawn(command, args, { stdio: \"inherit\", env, shell });\n child.on(\"error\", (error) => {\n logger.error(`Failed to run plugin \"${params.cliName}-${slug}\": ${error.message}`);\n resolve(1);\n });\n child.on(\"close\", (code, signal) => {\n if (signal) {\n resolve(signalToExitCode(signal));\n } else {\n resolve(code ?? 0);\n }\n });\n });\n}\n\n/**\n * Dispatch a plugin, printing an install hint when the subcommand maps to a\n * known plugin package that is not installed.\n * @param params - Dispatch parameters\n * @returns The plugin's exit code (1 after an install hint), or undefined when\n * the subcommand matches no plugin and no known package\n */\nexport async function dispatchPluginWithInstallHint(\n params: DispatchPluginParams,\n): Promise<number | undefined> {\n const exitCode = await dispatchPlugin(params);\n if (exitCode !== undefined) {\n return exitCode;\n }\n const knownPackage = KNOWN_PLUGIN_PACKAGES[pluginSlug(params.commandPath, params.name)];\n if (!knownPackage) {\n return undefined;\n }\n const fullCommand = [params.cliName, ...(params.commandPath ?? []), params.name].join(\" \");\n logger.error(\n `\"${fullCommand}\" is provided by the ${knownPackage} CLI plugin, which is not installed.`,\n );\n logger.info(`Install it with: npm install -D ${knownPackage}`);\n return 1;\n}\n","import { z } from \"zod\";\nimport { BUILTIN_COMMAND_NAMES } from \"#/cli/shared/builtin-commands\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { listPlugins } from \"#/cli/shared/plugin\";\nimport ml from \"#/utils/multiline\";\n\ninterface PluginListItem {\n name: string;\n source: \"node_modules\" | \"path\";\n path: string;\n /** True when a builtin command of the same name shadows this plugin. */\n shadowed: boolean;\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description:\n \"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).\",\n args: z.strictObject({}),\n run: async () => {\n const pkg = await readPackageJson();\n const cliName = Object.keys(pkg.bin ?? {})[0] || \"tailor\";\n const builtins = new Set<string>(BUILTIN_COMMAND_NAMES);\n\n const plugins = listPlugins(cliName);\n if (plugins.length === 0) {\n logger.info(ml`\n No plugins found.\n Install an executable named \"${cliName}-<name>\" on your PATH or in node_modules/.bin,\n then run it with \"${cliName} <name>\".\n `);\n if (logger.jsonMode) {\n logger.out([]);\n }\n return;\n }\n\n const items: PluginListItem[] = plugins.map((plugin) => ({\n name: plugin.name,\n source: plugin.source,\n path: plugin.path,\n shadowed: builtins.has(plugin.name),\n }));\n\n logger.out(items);\n\n for (const item of items) {\n if (item.shadowed) {\n logger.warn(\n `Plugin \"${cliName}-${item.name}\" is shadowed by the builtin \"${cliName} ${item.name}\" command and will not be dispatched.`,\n );\n }\n }\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\n\nexport const pluginCommand = defineCommand({\n name: \"plugin\",\n description: \"Manage and inspect CLI plugins (beta).\",\n subCommands: {\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { fetchLatestToken, readPlatformConfig, writePlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new profile.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n user: arg(z.string(), {\n alias: \"u\",\n description: \"User email address or machine user client ID\",\n }),\n \"workspace-id\": arg(z.string(), {\n alias: \"w\",\n description: \"Workspace ID\",\n }),\n permission: arg(z.enum([\"write\", \"read\"]).default(\"write\"), {\n description:\n \"Profile permission. 'read' blocks all write commands while the profile is active.\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Default machine user name for application-data commands (query, workflow start, function test-run, machineuser token).\",\n }),\n \"machine-user-override\": arg(z.enum([\"allow\", \"deny\"]).optional(), {\n description:\n \"Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user.\",\n }),\n \"platform-url\": arg(z.url().optional(), {\n description: \"Platform API base URL for this profile.\",\n env: \"TAILOR_PLATFORM_URL\",\n }),\n \"oauth2-client-id\": arg(z.string().optional(), {\n description: \"OAuth2 client ID for logging in to this profile's platform.\",\n env: \"TAILOR_PLATFORM_OAUTH2_CLIENT_ID\",\n }),\n \"console-url\": arg(z.url().optional(), {\n description: \"Console base URL for this profile.\",\n env: \"TAILOR_PLATFORM_CONSOLE_URL\",\n }),\n }),\n run: async (args) => {\n if (args[\"machine-user-override\"] === \"deny\" && !args[\"machine-user\"]) {\n throw new Error(\"--machine-user-override deny requires --machine-user.\");\n }\n\n const config = await readPlatformConfig();\n\n // Check if profile already exists\n if (config.profiles[args.name]) {\n throw new Error(`Profile \"${args.name}\" already exists.`);\n }\n\n // Check if user exists\n const platformConfigInput = {\n ...(args[\"platform-url\"] ? { platformUrl: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2ClientId: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { consoleUrl: args[\"console-url\"] } : {}),\n };\n const platformConfig =\n Object.keys(platformConfigInput).length > 0 ? platformConfigInput : undefined;\n const { accessToken: token, user: resolvedUser } = await fetchLatestToken(\n config,\n args.user,\n platformConfig,\n );\n\n // Check if workspace exists\n const client = await initOperatorClient(token, platformConfig);\n const workspaces = await fetchAll(async (pageToken, maxPageSize) => {\n const { workspaces, nextPageToken } = await client.listWorkspaces({\n pageToken,\n pageSize: maxPageSize,\n });\n return [workspaces, nextPageToken];\n });\n\n const workspace = workspaces.find((ws) => ws.id === args[\"workspace-id\"]);\n if (!workspace) {\n throw new Error(`Workspace \"${args[\"workspace-id\"]}\" not found.`);\n }\n\n // Create new profile\n config.profiles[args.name] = {\n user: resolvedUser,\n workspace_id: args[\"workspace-id\"],\n ...(args.permission === \"read\" ? { readonly: true } : {}),\n ...(args[\"machine-user\"] ? { machine_user: args[\"machine-user\"] } : {}),\n ...(args[\"machine-user-override\"] === \"deny\"\n ? { machine_user_override: \"deny\" as const }\n : {}),\n ...(args[\"platform-url\"] ? { platform_url: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2_client_id: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { console_url: args[\"console-url\"] } : {}),\n };\n writePlatformConfig(config);\n\n if (!args.json) {\n logger.success(`Profile \"${args.name}\" created successfully.`);\n }\n\n // Show profile info\n const profileInfo: ProfileInfo = {\n name: args.name,\n user: resolvedUser,\n workspaceId: args[\"workspace-id\"],\n permission: args.permission,\n ...(args[\"machine-user\"]\n ? {\n machineUser: args[\"machine-user\"],\n machineUserOverride: args[\"machine-user-override\"] ?? \"allow\",\n }\n : {}),\n ...(args[\"platform-url\"] ? { platformUrl: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2ClientId: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { consoleUrl: args[\"console-url\"] } : {}),\n };\n logger.out(profileInfo);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { readPlatformConfig, writePlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a profile.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n\n // Check if profile exists\n if (!config.profiles[args.name]) {\n throw new Error(`Profile \"${args.name}\" not found.`);\n }\n\n // Delete profile\n delete config.profiles[args.name];\n writePlatformConfig(config);\n\n logger.success(`Profile \"${args.name}\" deleted successfully.`);\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { readPlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all profiles.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n\n const profiles = Object.entries(config.profiles);\n if (profiles.length === 0) {\n logger.info(ml`\n No profiles found.\n Please create a profile first using 'tailor profile create' command.\n `);\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const profileInfos: ProfileInfo[] = profiles.map(([name, profile]) => {\n const p = assertDefined(profile, `profile entry \"${name}\" is undefined`);\n return {\n name,\n user: p.user,\n workspaceId: p.workspace_id,\n permission: p.readonly === true ? \"read\" : \"write\",\n ...(p.machine_user\n ? {\n machineUser: p.machine_user,\n machineUserOverride: p.machine_user_override ?? \"allow\",\n }\n : {}),\n ...(p.platform_url ? { platformUrl: p.platform_url } : {}),\n ...(p.oauth2_client_id ? { oauth2ClientId: p.oauth2_client_id } : {}),\n ...(p.console_url ? { consoleUrl: p.console_url } : {}),\n };\n });\n logger.out(profileInfos);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n fetchLatestToken,\n platformConfigFromProfile,\n readPlatformConfig,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const updateCommand = defineAppCommand({\n name: \"update\",\n description: \"Update profile properties.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n user: arg(z.string().optional(), {\n alias: \"u\",\n description: \"New user email address or machine user client ID\",\n }),\n \"workspace-id\": arg(z.string().optional(), {\n alias: \"w\",\n description: \"New workspace ID\",\n }),\n permission: arg(z.enum([\"write\", \"read\"]).optional(), {\n description:\n \"Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Default machine user name for application-data commands (query, workflow start, function test-run, machineuser token). Pass an empty string to clear.\",\n }),\n \"machine-user-override\": arg(z.enum([\"allow\", \"deny\"]).optional(), {\n description:\n \"Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.\",\n }),\n \"platform-url\": arg(z.union([z.url(), z.literal(\"\")]).optional(), {\n description: \"Platform API base URL for this profile. Pass an empty string to clear.\",\n }),\n \"oauth2-client-id\": arg(z.string().optional(), {\n description:\n \"OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.\",\n }),\n \"console-url\": arg(z.union([z.url(), z.literal(\"\")]).optional(), {\n description: \"Console base URL for this profile. Pass an empty string to clear.\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n\n // Check if profile exists\n const profile = config.profiles[args.name];\n if (!profile) {\n throw new Error(`Profile \"${args.name}\" not found.`);\n }\n\n // Check if at least one property is provided\n if (\n !args.user &&\n !args[\"workspace-id\"] &&\n args.permission === undefined &&\n args[\"machine-user\"] === undefined &&\n args[\"machine-user-override\"] === undefined &&\n args[\"platform-url\"] === undefined &&\n args[\"oauth2-client-id\"] === undefined &&\n args[\"console-url\"] === undefined\n ) {\n throw new Error(\"Please provide at least one property to update.\");\n }\n const oldUser = profile.user;\n const newUser = args.user || oldUser;\n const oldWorkspaceId = profile.workspace_id;\n const newWorkspaceId = args[\"workspace-id\"] || oldWorkspaceId;\n let resolvedUser = newUser;\n\n // Compute the final machine_user and machine_user_override to validate the combination.\n const finalMachineUser =\n args[\"machine-user\"] === \"\" ? undefined : (args[\"machine-user\"] ?? profile.machine_user);\n const finalOverride =\n args[\"machine-user-override\"] === \"allow\"\n ? undefined\n : (args[\"machine-user-override\"] ?? profile.machine_user_override);\n const finalPlatformUrl =\n args[\"platform-url\"] === \"\" ? undefined : (args[\"platform-url\"] ?? profile.platform_url);\n const finalOAuth2ClientId =\n args[\"oauth2-client-id\"] === \"\"\n ? undefined\n : (args[\"oauth2-client-id\"] ?? profile.oauth2_client_id);\n const finalConsoleUrl =\n args[\"console-url\"] === \"\" ? undefined : (args[\"console-url\"] ?? profile.console_url);\n const finalPlatformConfigInput = {\n ...(finalPlatformUrl ? { platformUrl: finalPlatformUrl } : {}),\n ...(finalOAuth2ClientId ? { oauth2ClientId: finalOAuth2ClientId } : {}),\n ...(finalConsoleUrl ? { consoleUrl: finalConsoleUrl } : {}),\n };\n const finalPlatformConfig =\n Object.keys(finalPlatformConfigInput).length > 0 ? finalPlatformConfigInput : undefined;\n const tokenLookupPlatformConfig =\n args[\"platform-url\"] === \"\" ? platformConfigFromProfile(profile) : finalPlatformConfig;\n\n if (\n (args[\"machine-user\"] !== undefined || args[\"machine-user-override\"] !== undefined) &&\n finalOverride === \"deny\" &&\n !finalMachineUser\n ) {\n if (args[\"machine-user-override\"] === \"deny\") {\n throw new Error(\"--machine-user-override deny requires --machine-user.\");\n }\n throw new Error(\n `Cannot clear the machine user while machine-user-override is \"deny\". Also pass --machine-user-override allow.`,\n );\n }\n\n // Skip remote validation when neither user nor workspace is changing.\n // This keeps `profile update <name> --permission write|read` working\n // offline and when the saved token is expired or the workspace has been\n // removed, important so a user can always lift their own readonly flag.\n if (\n args.user !== undefined ||\n args[\"workspace-id\"] !== undefined ||\n args[\"platform-url\"] !== undefined\n ) {\n // Check if user exists\n const refreshed = await fetchLatestToken(config, newUser, tokenLookupPlatformConfig);\n resolvedUser = refreshed.user;\n\n // Check if workspace exists\n const client = await initOperatorClient(refreshed.accessToken, finalPlatformConfig);\n const workspaces = await fetchAll(async (pageToken, maxPageSize) => {\n const { workspaces, nextPageToken } = await client.listWorkspaces({\n pageToken,\n pageSize: maxPageSize,\n });\n return [workspaces, nextPageToken];\n });\n const workspace = workspaces.find((ws) => ws.id === newWorkspaceId);\n if (!workspace) {\n throw new Error(`Workspace \"${newWorkspaceId}\" not found.`);\n }\n }\n\n // Update properties\n profile.user = resolvedUser;\n profile.workspace_id = newWorkspaceId;\n if (args.permission === \"read\") {\n profile.readonly = true;\n } else if (args.permission === \"write\") {\n delete profile.readonly;\n }\n if (args[\"machine-user\"] !== undefined) {\n if (args[\"machine-user\"] === \"\") {\n delete profile.machine_user;\n } else {\n profile.machine_user = args[\"machine-user\"];\n }\n }\n if (args[\"machine-user-override\"] === \"deny\") {\n profile.machine_user_override = \"deny\";\n } else if (args[\"machine-user-override\"] === \"allow\") {\n delete profile.machine_user_override;\n }\n if (args[\"platform-url\"] !== undefined) {\n if (args[\"platform-url\"] === \"\") {\n delete profile.platform_url;\n } else {\n profile.platform_url = args[\"platform-url\"];\n }\n }\n if (args[\"oauth2-client-id\"] !== undefined) {\n if (args[\"oauth2-client-id\"] === \"\") {\n delete profile.oauth2_client_id;\n } else {\n profile.oauth2_client_id = args[\"oauth2-client-id\"];\n }\n }\n if (args[\"console-url\"] !== undefined) {\n if (args[\"console-url\"] === \"\") {\n delete profile.console_url;\n } else {\n profile.console_url = args[\"console-url\"];\n }\n }\n writePlatformConfig(config);\n if (!args.json) {\n logger.success(`Profile \"${args.name}\" updated successfully`);\n }\n\n // Show profile info\n const profileInfo: ProfileInfo = {\n name: args.name,\n user: resolvedUser,\n workspaceId: newWorkspaceId,\n permission: profile.readonly === true ? \"read\" : \"write\",\n ...(profile.machine_user\n ? {\n machineUser: profile.machine_user,\n machineUserOverride: profile.machine_user_override ?? \"allow\",\n }\n : {}),\n ...(profile.platform_url ? { platformUrl: profile.platform_url } : {}),\n ...(profile.oauth2_client_id ? { oauth2ClientId: profile.oauth2_client_id } : {}),\n ...(profile.console_url ? { consoleUrl: profile.console_url } : {}),\n };\n logger.out(profileInfo);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport type { ProfileInfo } from \"./types\";\n\nexport const profileCommand = defineCommand({\n name: \"profile\",\n description: \"Manage workspace profiles (user + workspace combinations).\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n list: listCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\n/**\n * Arguments for specify secret key\n */\nexport const vaultArgs = {\n \"vault-name\": arg(z.string(), {\n alias: \"V\",\n description: \"Vault name\",\n }),\n};\n\n/**\n * Arguments for specify secret key\n */\nexport const secretIdentifyArgs = {\n ...vaultArgs,\n name: arg(z.string(), {\n alias: \"n\",\n description: \"Secret name\",\n }),\n};\n\n/**\n * Arguments for specify secret key\n */\nexport const secretValueArgs = {\n ...secretIdentifyArgs,\n value: arg(z.string(), {\n alias: \"v\",\n description: \"Secret value\",\n }),\n};\n","import {\n resourceTrn,\n sdkAppIdLabelKey,\n sdkNameLabelKey,\n sdkVersionLabelKey,\n writeMetadataLabels,\n} from \"#/cli/commands/deploy/label\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\n\ntype CheckVaultManagedParams = {\n client: OperatorClient;\n workspaceId: string;\n vaultName: string;\n};\n\ntype CheckVaultManagedResult = {\n isManaged: boolean;\n trn: string;\n existingLabels: Record<string, string>;\n};\n\n/**\n * Check if a vault is managed by defineSecretManager() and warn the user.\n * Returns management status and metadata needed for releasing ownership.\n * @param params - Check parameters\n * @returns Management status, TRN, and existing labels\n */\nexport async function checkVaultManaged(\n params: CheckVaultManagedParams,\n): Promise<CheckVaultManagedResult> {\n const { client, workspaceId, vaultName } = params;\n const trn = resourceTrn(workspaceId, \"vault\", vaultName);\n const notManaged = { isManaged: false, trn, existingLabels: {} };\n\n let owner: string | undefined;\n let allLabels: Record<string, string>;\n try {\n const { metadata } = await client.getMetadata({ trn });\n allLabels = metadata?.labels ?? {};\n owner = allLabels[sdkNameLabelKey];\n } catch {\n // If metadata fetch fails (e.g., vault doesn't exist yet), proceed silently.\n // The actual operation will surface the appropriate error.\n return notManaged;\n }\n\n if (!owner) return notManaged;\n\n logger.warn(\n `Vault \"${vaultName}\" is managed by defineSecretManager() in tailor.config.ts (owner: \"${owner}\"). ` +\n `Changes made via CLI may conflict with the config on the next apply.`,\n );\n\n return { isManaged: true, trn, existingLabels: allLabels };\n}\n\n/**\n * Release ownership of a managed vault by removing SDK labels from metadata.\n * Call this after the user has confirmed they want to proceed with a CLI operation on a managed vault.\n * The labels are read again at write time, so the caller does not pass the ones\n * `checkVaultManaged` saw: anything written since then is kept, and only the\n * ownership labels are removed.\n *\n * That includes the app id, which decides ownership on its own: leaving it\n * behind would keep the vault SDK-owned, and the next deploy of a config that\n * no longer declares it would delete the vault and every secret in it.\n * @param params - Client and TRN from the checkVaultManaged result\n * @param params.client - Operator client used to update vault metadata\n * @param params.trn - TRN of the vault resource\n */\nexport async function releaseVaultOwnership(params: {\n client: OperatorClient;\n trn: string;\n}): Promise<void> {\n const { client, trn } = params;\n await writeMetadataLabels(client, {\n trn,\n remove: [sdkNameLabelKey, sdkVersionLabelKey, sdkAppIdLabelKey],\n });\n logger.info(\n \"Config ownership has been removed from this vault. \" +\n \"Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.\",\n );\n}\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretValueArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const createSecretCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretValueArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const managed = await checkVaultManaged({\n client,\n workspaceId,\n vaultName: args[\"vault-name\"],\n });\n if (managed.isManaged && !args.yes) {\n const confirmed = await prompt.confirm({\n message: \"Do you want to proceed?\",\n default: false,\n });\n if (!confirmed) return;\n }\n try {\n await client.createSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n secretmanagerSecretValue: args.value,\n });\n } catch (error) {\n if (error instanceof ConnectError) {\n if (error.code === Code.NotFound) {\n throw new Error(`Vault \"${args[\"vault-name\"]}\" not found.`, { cause: error });\n }\n if (error.code === Code.AlreadyExists) {\n throw new Error(`Secret \"${args.name}\" already exists.`, { cause: error });\n }\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} created in vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretIdentifyArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const deleteSecretCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretIdentifyArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // No additional confirmation for managed vaults — the name-typing confirmation below is a stronger guard.\n const managed = await checkVaultManaged({ client, workspaceId, vaultName: args[\"vault-name\"] });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the secret name to confirm deletion (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Secret deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Secret \"${args.name}\" not found in vault \"${args[\"vault-name\"]}\".`, {\n cause: error,\n });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} deleted from vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { vaultArgs } from \"./args\";\nimport type { SecretManagerSecret } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\nexport interface SecretListOptions {\n workspaceId?: string;\n profile?: string;\n vaultName: string;\n order?: Order;\n limit?: number;\n}\n\nexport interface SecretInfo {\n name: string;\n createdAt: Date | null;\n updatedAt: Date | null;\n}\n\nfunction secretInfo(secret: SecretManagerSecret): SecretInfo {\n return {\n name: secret.name,\n createdAt: secret.createTime ? timestampDate(secret.createTime) : null,\n updatedAt: secret.updateTime ? timestampDate(secret.updateTime) : null,\n };\n}\n\n/**\n * List secrets in a Secret Manager vault.\n * @param options - Secret listing options\n * @returns List of secrets\n */\nasync function secretList(options: SecretListOptions): Promise<SecretInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const pageDirection = toPageDirection(options.order);\n const secrets = await fetchPaged(\n async (pageToken, pageSize) => {\n const { secrets, nextPageToken } = await client.listSecretManagerSecrets({\n workspaceId,\n secretmanagerVaultName: options.vaultName,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [secrets, nextPageToken];\n },\n { limit: options.limit },\n );\n\n return secrets.map(secretInfo);\n}\n\nexport const listSecretCommand = defineAppCommand({\n name: \"list\",\n description: \"List all secrets in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...vaultArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n try {\n const secrets = await secretList({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n vaultName: args[\"vault-name\"],\n order: args.order,\n limit: args.limit,\n });\n logger.out(secrets);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Vault \"${args[\"vault-name\"]}\" not found.`, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretValueArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const updateSecretCommand = defineAppCommand({\n name: \"update\",\n description: \"Update a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretValueArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const managed = await checkVaultManaged({\n client,\n workspaceId,\n vaultName: args[\"vault-name\"],\n });\n if (managed.isManaged && !args.yes) {\n const confirmed = await prompt.confirm({\n message: \"Do you want to proceed?\",\n default: false,\n });\n if (!confirmed) return;\n }\n try {\n await client.updateSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n secretmanagerSecretValue: args.value,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Secret \"${args.name}\" not found in vault \"${args[\"vault-name\"]}\".`, {\n cause: error,\n });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} updated in vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\ntype ArgsShape = Record<string, z.ZodType>;\n\nexport const nameArgs = {\n name: arg(z.string(), {\n positional: true,\n description: \"Vault name\",\n }),\n} satisfies ArgsShape;\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { nameArgs } from \"./args\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new Secret Manager vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...nameArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n await client.createSecretManagerVault({\n workspaceId,\n secretmanagerVaultName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.AlreadyExists) {\n throw new Error(`Vault \"${args.name}\" already exists.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Vault: ${args.name} created`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { checkVaultManaged } from \"../check-vault-managed\";\nimport { nameArgs } from \"./args\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a Secret Manager vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...nameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // No additional confirmation for managed vaults — the name-typing confirmation below is a stronger guard.\n const managed = await checkVaultManaged({ client, workspaceId, vaultName: args.name });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the vault name to confirm deletion (\"${args.name}\"):`,\n });\n if (confirmation !== args.name) {\n logger.info(\"Vault deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteSecretManagerVault({\n workspaceId,\n secretmanagerVaultName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Vault \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n logger.info(\n \"Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.\",\n );\n }\n\n logger.success(`Vault: ${args.name} deleted`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { SecretManagerVault } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\nexport interface VaultListOptions {\n workspaceId?: string;\n profile?: string;\n order?: Order;\n limit?: number;\n}\n\nexport interface VaultInfo {\n name: string;\n createdAt: Date | null;\n updatedAt: Date | null;\n}\n\nfunction vaultInfo(vault: SecretManagerVault): VaultInfo {\n return {\n name: vault.name,\n createdAt: vault.createTime ? timestampDate(vault.createTime) : null,\n updatedAt: vault.updateTime ? timestampDate(vault.updateTime) : null,\n };\n}\n\n/**\n * List Secret Manager vaults in the workspace.\n * @param options - Vault listing options\n * @returns List of vaults\n */\nasync function vaultList(options?: VaultListOptions): Promise<VaultInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options?.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options?.workspaceId,\n profile: options?.profile,\n });\n\n const pageDirection = toPageDirection(options?.order);\n const vaults = await fetchPaged(\n async (pageToken, pageSize) => {\n const { vaults, nextPageToken } = await client.listSecretManagerVaults({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [vaults, nextPageToken];\n },\n { limit: options?.limit },\n );\n\n return vaults.map(vaultInfo);\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all Secret Manager vaults in the workspace.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n const vaults = await vaultList({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n order: args.order,\n limit: args.limit,\n });\n\n logger.out(vaults);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\n\nexport const vaultCommand = defineCommand({\n name: \"vault\",\n description: \"Manage Secret Manager vaults.\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createSecretCommand } from \"./create\";\nimport { deleteSecretCommand } from \"./delete\";\nimport { listSecretCommand } from \"./list\";\nimport { updateSecretCommand } from \"./update\";\nimport { vaultCommand } from \"./vault\";\n\nexport const secretCommand = defineCommand({\n name: \"secret\",\n description: \"Manage Secret Manager vaults and secrets.\",\n subCommands: {\n vault: vaultCommand,\n create: createSecretCommand,\n update: updateSecretCommand,\n list: listSecretCommand,\n delete: deleteSecretCommand,\n },\n async run() {\n await runCommand(vaultCommand, []);\n },\n});\n","import { spawnSync } from \"node:child_process\";\n\n/**\n * Runs a git command and returns its trimmed stdout, or null on failure.\n * Injectable so callers (and tests) can substitute the git runner.\n * @param args - Arguments passed to `git`\n * @param cwd - Working directory to run git in\n * @returns Trimmed stdout, or null when git is unavailable or exits non-zero\n */\nexport type GitRunner = (args: string[], cwd: string) => string | null;\n\nconst defaultGitRunner: GitRunner = (args, cwd) => {\n const result = spawnSync(\"git\", args, { cwd, encoding: \"utf-8\" });\n if (result.status !== 0 || typeof result.stdout !== \"string\") {\n return null;\n }\n return result.stdout.trim();\n};\n\n/**\n * Detect the remote default branch by reading `refs/remotes/origin/HEAD`.\n *\n * Throws an AI-first error (with a remediation hint) when the symbolic ref is\n * not set, so the caller can surface a clear next step instead of a silent\n * fallback.\n * @param cwd - Repository directory to inspect\n * @param run - Git runner, injectable for testing\n * @returns The default branch name (e.g. `main`)\n */\nexport function detectDefaultBranch(cwd: string, run: GitRunner = defaultGitRunner): string {\n const ref = run([\"symbolic-ref\", \"--short\", \"refs/remotes/origin/HEAD\"], cwd);\n const branch = ref?.startsWith(\"origin/\") ? ref.slice(\"origin/\".length) : ref;\n if (!branch) {\n throw new Error(\n \"Could not detect the default branch from git. \" +\n \"Pass --branch <name>, or run 'git remote set-head origin --auto' to record it.\",\n );\n }\n return branch;\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\n/** Current lock schema version. Bumped only on breaking lock-format changes. */\nexport const LOCK_VERSION = 1;\n\n/** Lock file path, relative to the repository root. */\nconst LOCK_FILENAME = \".github/tailor.lock\";\n\nexport type TargetKind = \"branch\" | \"tag\" | \"preview\" | \"action\" | \"coordinate\";\n\nexport type LockInputs = {\n branch: string | null;\n /** True when `branch` was auto-detected (no explicit `--branch`). */\n branchAutoDetected?: boolean;\n tagPattern: string | null;\n environment: string;\n dir: string;\n packageManager: string;\n /** For `preview` kind: workspace region used when creating the preview workspace. */\n region?: string;\n /**\n * For `preview` kind: when true, the preview workflow deploys only for PRs labeled\n * `tailor:preview`. False (default) means all PRs trigger a preview deploy.\n */\n requirePreviewLabel?: boolean;\n /** For `coordinate` kind: ordered list of app dirs whose per-app actions are orchestrated. */\n actionDirs?: string[];\n erdPreview?: boolean;\n erdNamespaces?: string[];\n /** Whether tailor-migration-drift-check was generated (config had namespaces with migrations). */\n migrationDriftCheck?: boolean;\n /** Whether tailor-seed-validate was generated (config used seedPlugin). */\n seedValidate?: boolean;\n /** Whether the config had staticWebsites when setup was last run (action kind only). */\n hasStaticWebsites?: boolean;\n};\n\nexport type LockTarget = {\n kind: TargetKind;\n workspaceName: string;\n /** outputDir-relative, posix-separated path to the generated workflow file. */\n file: string;\n templateVersion: number;\n inputs: LockInputs;\n /** Managed job/step ids: jobs as `<job>`, steps as `<job>/<step>`. */\n generatedIds: string[];\n /** Reserved for future eject semantics; preserved as-is across regenerations. */\n ejectedIds: string[];\n /** `sha256:<hex>` of the written file content. */\n contentHash: string;\n};\n\nexport type LockFile = {\n version: number;\n targets: LockTarget[];\n};\n\n/**\n * Compute the lock content hash for a rendered workflow file.\n * @param content - File content to hash\n * @returns `sha256:<hex>` digest string\n */\nexport function hashContent(content: string): string {\n return `sha256:${createHash(\"sha256\").update(content, \"utf-8\").digest(\"hex\")}`;\n}\n\n/**\n * Resolve the absolute lock file path for an output directory.\n * @param outputDir - Repository root where `.github` lives\n * @returns Absolute path to the lock file\n */\nexport function lockPath(outputDir: string): string {\n return path.join(outputDir, LOCK_FILENAME);\n}\n\n/**\n * Read and validate the lock file from disk.\n *\n * Returns null when no lock exists. Throws when the lock was written by a\n * newer SDK (forward-compatibility guard).\n * @param outputDir - Repository root where `.github` lives\n * @returns Parsed lock file, or null when absent\n */\nexport function readLock(outputDir: string): LockFile | null {\n const file = lockPath(outputDir);\n if (!fs.existsSync(file)) {\n return null;\n }\n let parsed: LockFile;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as LockFile;\n } catch (cause) {\n throw new Error(\n `${LOCK_FILENAME} is not valid JSON. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n { cause },\n );\n }\n if (typeof parsed.version !== \"number\") {\n throw new Error(\n `${LOCK_FILENAME} has no valid 'version' field. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n );\n }\n if (parsed.version > LOCK_VERSION) {\n throw new Error(\n `${LOCK_FILENAME} was written by a newer SDK (lock version ${String(parsed.version)}). ` +\n \"Update @tailor-platform/sdk to continue (e.g. pnpm update @tailor-platform/sdk).\",\n );\n }\n if (!Array.isArray(parsed.targets)) {\n throw new Error(\n `${LOCK_FILENAME} has no valid 'targets' array. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n );\n }\n return parsed;\n}\n\n/**\n * Write the lock file to disk (2-space JSON, trailing newline).\n * @param outputDir - Repository root where `.github` lives\n * @param lock - Lock file contents to serialize\n */\nexport function writeLock(outputDir: string, lock: LockFile): void {\n const file = lockPath(outputDir);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify(lock, null, 2)}\\n`, \"utf-8\");\n}\n\n/**\n * Find a lock target by identity. Targets are identified by (kind,\n * workspaceName); the full trigger/path cross-check is deferred to P2.\n * @param lock - Lock file to search, or null\n * @param kind - Target kind\n * @param workspaceName - Workspace name\n * @returns Matching target, or undefined\n */\nexport function findTarget(\n lock: LockFile | null,\n kind: TargetKind,\n workspaceName: string,\n): LockTarget | undefined {\n return lock?.targets.find((t) => t.kind === kind && t.workspaceName === workspaceName);\n}\n","export default \"# __HEADER__\\nname: __WORKSPACE_NAME__\\ndescription: >-\\n Deploy __WORKSPACE_NAME__ to Tailor Platform.\\n Checkout and dependency installation are expected to be handled by the caller.\\n\\ninputs:\\n workspace-id:\\n description: Tailor Platform workspace id\\n required: true\\n name:\\n description: Workspace name (used in Slack notifications)\\n required: true\\n working-directory:\\n description: App directory relative to the repository root\\n required: false\\n default: \\\".\\\"\\n config:\\n description: SDK config path, or comma-separated config paths for multi-config deploys\\n required: false\\n default: \\\"tailor.config.ts\\\"\\n deploy:\\n description: Whether to run the Tailor deploy step after build steps\\n required: false\\n default: \\\"true\\\"\\n build-site:\\n description: Whether to run the static website build slot when present\\n required: false\\n default: \\\"true\\\"\\n platform-client-id:\\n description: Machine-user client id\\n required: true\\n platform-client-secret:\\n description: Machine-user client secret\\n required: true\\n slack-token:\\n description: Slack bot token\\n required: false\\n slack-channel-id:\\n description: Slack channel id\\n required: false\\n user-mapping:\\n description: JSON string mapping GitHub usernames to Slack user IDs\\n required: false\\n package-manager:\\n description: Package manager used for dependency installation (pnpm, npm, yarn, bun)\\n required: false\\n default: pnpm\\n\\noutputs:\\n app-url:\\n description: Deployed application URL\\n value: ${{ steps.tailor-apply.outputs.app-url }}\\n\\nruns:\\n using: composite\\n steps:\\n # __STATIC_WEBSITE_BUILD_START__\\n - id: build-site\\n if: inputs.build-site == 'true'\\n shell: bash\\n run: |\\n # Replace with your static website build command.\\n # Example: pnpm --filter <package-name> run build:static\\n # Note: this run: command is user-editable. Custom build commands are preserved across\\n # reruns and are not treated as drift by setup check. Other edits to this file are flagged\\n # as drift and will be overwritten if you re-run setup action with --force.\\n true\\n # __STATIC_WEBSITE_BUILD_END__\\n - id: tailor-apply\\n if: inputs.deploy == 'true'\\n uses: tailor-platform/actions/deploy@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n env:\\n TAILOR_PLATFORM_SDK_CONFIG_PATH: ${{ inputs.config }}\\n with:\\n workspace-id: ${{ inputs.workspace-id }}\\n working-directory: ${{ inputs.working-directory }}\\n package-manager: ${{ inputs.package-manager }}\\n platform-client-id: ${{ inputs.platform-client-id }}\\n platform-client-secret: ${{ inputs.platform-client-secret }}\\n - id: tailor-notify\\n if: failure() && inputs.slack-token != '' && inputs.slack-channel-id != ''\\n uses: tailor-platform/actions/notify@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n provider: slack\\n status: failure\\n workspace-name: ${{ inputs.name }}\\n slack-token: ${{ inputs.slack-token }}\\n slack-channel-id: ${{ inputs.slack-channel-id }}\\n user-mapping: ${{ inputs.user-mapping }}\\n\";","export default \"# __HEADER__\\nname: Tailor (__WORKSPACE_NAME__)\\n\\non:\\n # __PULL_REQUEST_START__\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PATHS__\\n # __PULL_REQUEST_END__\\n push:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PATHS__\\n workflow_dispatch:\\n # __DISPATCH_INPUTS_START__\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n # __DISPATCH_INPUTS_END__\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __PLAN_JOB_START__\\n tailor-plan:\\n if: >-\\n github.event_name == 'pull_request' ||\\n (github.event_name == 'workflow_dispatch' && inputs['dry-run'])\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-plan-__WORKSPACE_NAME__-${{ github.event.pull_request.number || github.run_id }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_START__\\n - id: tailor-seed-validate\\n run: __TAILOR_CLI__ seed validate\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_END__\\n - id: tailor-drift-check\\n uses: tailor-platform/actions/drift-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __MIGRATION_DRIFT_CHECK_START__\\n - id: tailor-migration-drift-check\\n uses: tailor-platform/actions/migration-drift-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __MIGRATION_DRIFT_CHECK_END__\\n - id: tailor-plan\\n # Fork PRs cannot read secrets; the checks above still run for them.\\n if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork\\n uses: tailor-platform/actions/plan@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n label: __WORKSPACE_NAME__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n # __PLAN_JOB_END__\\n # __ERD_PREVIEW_JOB_START__\\n tailor-erd-preview-matrix:\\n if: github.event_name == 'pull_request'\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n contents: read\\n outputs:\\n namespaces: ${{ steps.tailor-erd-preview-matrix.outputs.namespaces }}\\n base-app-dir: ${{ steps.tailor-erd-preview-matrix.outputs['base-app-dir'] }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n persist-credentials: false\\n - id: tailor-checkout-base\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n repository: ${{ github.event.pull_request.base.repo.full_name }}\\n ref: ${{ github.event.pull_request.base.sha }}\\n path: .tailor-erd-base\\n persist-credentials: false\\n - id: tailor-erd-preview-matrix\\n shell: bash\\n env:\\n APP_DIR: \\\"__APP_DIR__\\\"\\n WORKSPACE_NAME: \\\"__WORKSPACE_NAME__\\\"\\n run: |\\n set -euo pipefail\\n node <<'NODE'\\n const fs = require(\\\"node:fs\\\");\\n\\n const appDir = process.env.APP_DIR || \\\".\\\";\\n const workspaceName = process.env.WORKSPACE_NAME;\\n const output = process.env.GITHUB_OUTPUT;\\n const dirPattern = /^[A-Za-z0-9._/-]+$/;\\n const namespacePattern = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\\n\\n function lockTarget(file) {\\n try {\\n const lock = JSON.parse(fs.readFileSync(file, \\\"utf8\\\"));\\n return lock.targets?.find(\\n (candidate) =>\\n candidate.kind === \\\"branch\\\" &&\\n candidate.workspaceName === workspaceName,\\n );\\n } catch (error) {\\n if (error && error.code === \\\"ENOENT\\\") return undefined;\\n throw error;\\n }\\n }\\n\\n function namespacesFromTarget(target, label) {\\n const namespaces =\\n target?.inputs?.erdPreview === true && Array.isArray(target.inputs?.erdNamespaces)\\n ? target.inputs.erdNamespaces\\n : [];\\n for (const namespace of namespaces) {\\n if (typeof namespace !== \\\"string\\\" || !namespacePattern.test(namespace)) {\\n throw new Error(`Invalid ERD namespace in ${label}: ${String(namespace)}`);\\n }\\n }\\n return namespaces;\\n }\\n\\n function normalizeDir(value, label) {\\n const raw = typeof value === \\\"string\\\" && value.length > 0 ? value : appDir;\\n const normalized =\\n raw.replaceAll(\\\"\\\\\\\\\\\", \\\"/\\\").replace(/\\\\/{2,}/g, \\\"/\\\").replace(/^\\\\.\\\\//, \\\"\\\").replace(/\\\\/$/, \\\"\\\") ||\\n \\\".\\\";\\n if (\\n !dirPattern.test(normalized) ||\\n normalized.startsWith(\\\"/\\\") ||\\n normalized.split(\\\"/\\\").includes(\\\"..\\\")\\n ) {\\n throw new Error(`Invalid ERD app dir in ${label}: ${raw}`);\\n }\\n return normalized;\\n }\\n\\n const headTarget = lockTarget(\\\".github/tailor.lock\\\");\\n const baseTarget = lockTarget(\\\".tailor-erd-base/.github/tailor.lock\\\");\\n const baseAppDir = normalizeDir(baseTarget?.inputs?.dir, \\\"base setup lock\\\");\\n const namespaces = [\\n ...new Set([\\n ...namespacesFromTarget(headTarget, \\\"head setup lock\\\"),\\n ...namespacesFromTarget(baseTarget, \\\"base setup lock\\\"),\\n ]),\\n ].sort((a, b) => a.localeCompare(b));\\n\\n if (namespaces.length === 0) {\\n console.error(\\\"No ERD preview namespaces found in the head or base setup lock.\\\");\\n process.exit(1);\\n }\\n\\n fs.appendFileSync(output, `namespaces=${JSON.stringify(namespaces)}\\\\n`);\\n fs.appendFileSync(output, `base-app-dir=${baseAppDir}\\\\n`);\\n NODE\\n\\n tailor-erd-preview:\\n needs: tailor-erd-preview-matrix\\n if: github.event_name == 'pull_request'\\n runs-on: ubuntu-latest\\n timeout-minutes: 15\\n permissions:\\n contents: read\\n strategy:\\n fail-fast: false\\n matrix:\\n namespace: ${{ fromJSON(needs.tailor-erd-preview-matrix.outputs.namespaces) }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n persist-credentials: false\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-checkout-base\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n repository: ${{ github.event.pull_request.base.repo.full_name }}\\n ref: ${{ github.event.pull_request.base.sha }}\\n path: .tailor-erd-base\\n persist-credentials: false\\n - id: tailor-detect-base-package-manager\\n shell: bash\\n run: |\\n set -euo pipefail\\n cd .tailor-erd-base\\n base_package_manager=\\\"$(\\n if [ -f pnpm-lock.yaml ]; then\\n echo pnpm\\n elif [ -f yarn.lock ]; then\\n echo yarn\\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then\\n echo bun\\n elif [ -f package-lock.json ]; then\\n echo npm\\n else\\n echo \\\"__PACKAGE_MANAGER__\\\"\\n fi\\n )\\\"\\n echo \\\"package-manager=$base_package_manager\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n if [ \\\"$base_package_manager\\\" = \\\"pnpm\\\" ]; then\\n base_pnpm_version=\\\"$(node <<'NODE'\\n const fs = require(\\\"node:fs\\\");\\n\\n const fallback = \\\"10\\\";\\n\\n function readManifest(file) {\\n try {\\n return JSON.parse(fs.readFileSync(file, \\\"utf8\\\"));\\n } catch {\\n return {};\\n }\\n }\\n\\n function pnpmVersion(manifest) {\\n const packageManager = manifest.packageManager;\\n if (typeof packageManager === \\\"string\\\" && packageManager.startsWith(\\\"pnpm@\\\")) {\\n return packageManager.slice(\\\"pnpm@\\\".length).split(\\\"+\\\")[0];\\n }\\n\\n const devPackageManager = manifest.devEngines?.packageManager;\\n if (devPackageManager?.name === \\\"pnpm\\\" && devPackageManager.version) {\\n return devPackageManager.version;\\n }\\n\\n return undefined;\\n }\\n\\n process.stdout.write(\\n pnpmVersion(readManifest(\\\"package.json\\\")) ?? fallback,\\n );\\n NODE\\n )\\\"\\n echo \\\"pnpm-version=$base_pnpm_version\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-setup-base-pnpm\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'pnpm'\\n uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10\\n with:\\n version: ${{ steps.tailor-detect-base-package-manager.outputs['pnpm-version'] }}\\n package_json_file: .tailor-erd-base/package.json\\n run_install: false\\n - id: tailor-setup-base-node\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] != 'bun'\\n uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7\\n with:\\n node-version-file: .tailor-erd-base/package.json\\n - id: tailor-setup-base-yarn\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'yarn'\\n shell: bash\\n working-directory: .tailor-erd-base\\n run: |\\n set -euo pipefail\\n corepack enable\\n - id: tailor-setup-base-bun\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'bun'\\n uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0\\n - id: tailor-install-base\\n shell: bash\\n working-directory: .tailor-erd-base\\n env:\\n BASE_PACKAGE_MANAGER: ${{ steps.tailor-detect-base-package-manager.outputs['package-manager'] }}\\n run: |\\n set -euo pipefail\\n case \\\"$BASE_PACKAGE_MANAGER\\\" in\\n pnpm) pnpm install --frozen-lockfile ;;\\n npm) npm ci ;;\\n yarn)\\n if grep -q '^__metadata:' yarn.lock; then\\n yarn install --immutable\\n else\\n yarn install --frozen-lockfile\\n fi\\n ;;\\n bun) bun install --frozen-lockfile ;;\\n *)\\n echo \\\"::error::Unsupported base package-manager '$BASE_PACKAGE_MANAGER' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n - id: tailor-restore-head-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-build-erd-preview\\n shell: bash\\n env:\\n APP_DIR: \\\"__APP_DIR__\\\"\\n BASE_APP_DIR: ${{ needs.tailor-erd-preview-matrix.outputs['base-app-dir'] }}\\n BASE_PACKAGE_MANAGER: ${{ steps.tailor-detect-base-package-manager.outputs['package-manager'] }}\\n NAMESPACE: ${{ matrix.namespace }}\\n run: |\\n set -euo pipefail\\n\\n run_tailor_cli() {\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) pnpm exec tailor \\\"$@\\\" ;;\\n npm) npx @tailor-platform/sdk \\\"$@\\\" ;;\\n yarn) yarn tailor \\\"$@\\\" ;;\\n bun) bun run tailor \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n }\\n\\n run_head_node() {\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) pnpm exec node \\\"$@\\\" ;;\\n npm) node \\\"$@\\\" ;;\\n yarn) yarn node \\\"$@\\\" ;;\\n bun) node \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n }\\n\\n tailor_cli_bin=\\\"$(\\n run_head_node - <<'NODE'\\n const path = require(\\\"node:path\\\");\\n const { createRequire } = require(\\\"node:module\\\");\\n const appDir = process.env.APP_DIR || \\\".\\\";\\n const githubWorkspace = process.env.GITHUB_WORKSPACE;\\n if (!githubWorkspace) {\\n throw new Error(\\\"GITHUB_WORKSPACE is required.\\\");\\n }\\n\\n let lastError;\\n for (const manifestPath of [\\n path.join(githubWorkspace, appDir, \\\"package.json\\\"),\\n path.join(githubWorkspace, \\\"package.json\\\"),\\n ]) {\\n try {\\n const requireFromManifest = createRequire(manifestPath);\\n process.stdout.write(\\n path.join(\\n path.dirname(requireFromManifest.resolve(\\\"@tailor-platform/sdk/cli\\\")),\\n \\\"index.mjs\\\",\\n ),\\n );\\n process.exit(0);\\n } catch (error) {\\n lastError = error;\\n }\\n }\\n throw lastError || new Error(\\\"Failed to resolve @tailor-platform/sdk/cli.\\\");\\n NODE\\n )\\\"\\n\\n run_head_tailor_cli_bin() {\\n local command_cwd=\\\"$1\\\"\\n shift\\n\\n run_head_cli_env() {\\n env TAILOR_CLI_BIN=\\\"$tailor_cli_bin\\\" TAILOR_CLI_CWD=\\\"$command_cwd\\\" \\\"$@\\\"\\n }\\n\\n (\\n cd \\\"$GITHUB_WORKSPACE\\\" || exit 1\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) run_head_cli_env pnpm exec node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n npm) run_head_cli_env node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n yarn) run_head_cli_env yarn node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n bun) run_head_cli_env bun \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n )\\n }\\n\\n run_base_tailor_cli_bin() {\\n local command_cwd=\\\"$1\\\"\\n shift\\n\\n run_head_cli_env() {\\n env TAILOR_CLI_BIN=\\\"$tailor_cli_bin\\\" TAILOR_CLI_CWD=\\\"$command_cwd\\\" \\\"$@\\\"\\n }\\n\\n (\\n cd \\\"$command_cwd\\\" || exit 1\\n case \\\"$BASE_PACKAGE_MANAGER\\\" in\\n pnpm) run_head_cli_env pnpm exec node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n npm) run_head_cli_env node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n yarn) run_head_cli_env yarn node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n bun) run_head_cli_env bun \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported base package-manager '$BASE_PACKAGE_MANAGER' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n )\\n }\\n\\n head_output=\\\"$RUNNER_TEMP/tailor-erd/head\\\"\\n base_output=\\\"$RUNNER_TEMP/tailor-erd/base\\\"\\n preview_output=\\\"$RUNNER_TEMP/tailor-erd/preview\\\"\\n dts_output=\\\"$RUNNER_TEMP/tailor-erd/dts\\\"\\n head_cli_runner=\\\"$RUNNER_TEMP/tailor-erd/run-head-cli.mjs\\\"\\n head_log=\\\"$RUNNER_TEMP/tailor-erd/head-$NAMESPACE.log\\\"\\n base_log=\\\"$RUNNER_TEMP/tailor-erd/base-$NAMESPACE.log\\\"\\n rm -rf \\\"$head_output\\\" \\\"$base_output\\\" \\\"$preview_output\\\" \\\"$dts_output\\\"\\n mkdir -p \\\"$head_output\\\" \\\"$base_output\\\" \\\"$preview_output\\\" \\\"$dts_output\\\"\\n cat > \\\"$head_cli_runner\\\" <<'NODE'\\n import { pathToFileURL } from \\\"node:url\\\";\\n\\n const cliBin = process.env.TAILOR_CLI_BIN;\\n const commandCwd = process.env.TAILOR_CLI_CWD;\\n if (!cliBin || !commandCwd) {\\n throw new Error(\\\"TAILOR_CLI_BIN and TAILOR_CLI_CWD are required.\\\");\\n }\\n\\n process.chdir(commandCwd);\\n process.argv = [process.argv[0], cliBin, ...process.argv.slice(2)];\\n await import(pathToFileURL(cliBin).href);\\n NODE\\n\\n head_config=\\\"$GITHUB_WORKSPACE/$APP_DIR/tailor.config.ts\\\"\\n base_config=\\\"$GITHUB_WORKSPACE/.tailor-erd-base/$BASE_APP_DIR/tailor.config.ts\\\"\\n head_html=\\\"$head_output/$NAMESPACE/dist/index.html\\\"\\n base_html=\\\"$base_output/$NAMESPACE/dist/index.html\\\"\\n preview_html=\\\"$preview_output/$NAMESPACE-viewer.html\\\"\\n\\n head_missing=\\\"false\\\"\\n if [ ! -f \\\"$head_config\\\" ]; then\\n echo \\\"Head ERD config not found; rendering base objects as removed.\\\"\\n head_missing=\\\"true\\\"\\n elif ! (\\n cd \\\"$GITHUB_WORKSPACE/$APP_DIR\\\" || exit 1\\n TAILOR_PLATFORM_SDK_DTS_PATH=\\\"$dts_output/head-$NAMESPACE.d.ts\\\" \\\\\\n run_tailor_cli tailordb erd export --config \\\"$head_config\\\" --namespace \\\"$NAMESPACE\\\" --output \\\"$head_output\\\"\\n ) >\\\"$head_log\\\" 2>&1; then\\n if grep -q 'not found in local config.db' \\\"$head_log\\\"; then\\n cat \\\"$head_log\\\"\\n echo \\\"Head ERD namespace '$NAMESPACE' not found; rendering base objects as removed.\\\"\\n head_missing=\\\"true\\\"\\n else\\n cat \\\"$head_log\\\"\\n exit 1\\n fi\\n elif [ -s \\\"$head_log\\\" ]; then\\n cat \\\"$head_log\\\"\\n fi\\n\\n base_missing=\\\"false\\\"\\n if [ ! -f \\\"$base_config\\\" ]; then\\n echo \\\"Base ERD config not found; rendering current objects as added.\\\"\\n base_missing=\\\"true\\\"\\n elif ! (\\n TAILOR_PLATFORM_SDK_DTS_PATH=\\\"$dts_output/base-$NAMESPACE.d.ts\\\" \\\\\\n run_base_tailor_cli_bin \\\"$GITHUB_WORKSPACE/.tailor-erd-base/$BASE_APP_DIR\\\" tailordb erd export --config \\\"$base_config\\\" --namespace \\\"$NAMESPACE\\\" --output \\\"$base_output\\\"\\n ) >\\\"$base_log\\\" 2>&1; then\\n if grep -q 'not found in local config.db' \\\"$base_log\\\"; then\\n cat \\\"$base_log\\\"\\n echo \\\"Base ERD namespace '$NAMESPACE' not found; rendering current objects as added.\\\"\\n base_missing=\\\"true\\\"\\n else\\n cat \\\"$base_log\\\"\\n exit 1\\n fi\\n elif [ -s \\\"$base_log\\\" ]; then\\n cat \\\"$base_log\\\"\\n fi\\n\\n if [ \\\"$head_missing\\\" = \\\"true\\\" ] && [ \\\"$base_missing\\\" = \\\"true\\\" ]; then\\n echo \\\"::error::ERD namespace '$NAMESPACE' was not found in head or base.\\\"\\n exit 1\\n fi\\n if [ \\\"$head_missing\\\" = \\\"false\\\" ] && [ ! -f \\\"$head_html\\\" ]; then\\n echo \\\"::error::Head ERD viewer was not generated at $head_html\\\"\\n exit 1\\n fi\\n if [ \\\"$base_missing\\\" = \\\"false\\\" ] && [ ! -f \\\"$base_html\\\" ]; then\\n echo \\\"::error::Base ERD viewer was not generated at $base_html\\\"\\n exit 1\\n fi\\n\\n diff_args=(--namespace \\\"$NAMESPACE\\\" --output \\\"$preview_html\\\")\\n if [ \\\"$head_missing\\\" = \\\"false\\\" ]; then\\n diff_args+=(--head-html \\\"$head_html\\\")\\n fi\\n if [ \\\"$base_missing\\\" = \\\"false\\\" ]; then\\n diff_args+=(--base-html \\\"$base_html\\\")\\n fi\\n run_head_tailor_cli_bin \\\"$GITHUB_WORKSPACE\\\" tailordb erd diff \\\"${diff_args[@]}\\\"\\n - id: tailor-upload-erd-viewer\\n uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1\\n with:\\n name: ${{ matrix.namespace }}-viewer.html\\n path: ${{ runner.temp }}/tailor-erd/preview/${{ matrix.namespace }}-viewer.html\\n if-no-files-found: error\\n archive: false\\n retention-days: 7\\n\\n # __ERD_PREVIEW_JOB_END__\\n # __ERD_PREVIEW_COMMENT_JOB_START__\\n tailor-erd-preview-comment:\\n needs: tailor-erd-preview\\n if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n actions: read\\n pull-requests: write\\n steps:\\n - id: tailor-comment-erd-preview\\n env:\\n GH_TOKEN: ${{ github.token }}\\n REPO: ${{ github.repository }}\\n RUN_ID: ${{ github.run_id }}\\n SERVER: ${{ github.server_url }}\\n PR_NUMBER: ${{ github.event.pull_request.number }}\\n BASE_REF: ${{ github.event.pull_request.base.ref }}\\n HEAD_SHA: ${{ github.event.pull_request.head.sha }}\\n MARKER: \\\"<!-- tailor-erd-preview: __WORKSPACE_NAME__ -->\\\"\\n run: |\\n set -euo pipefail\\n\\n current_head=$(gh api \\\"repos/$REPO/pulls/$PR_NUMBER\\\" --jq '.head.sha')\\n if [ \\\"$current_head\\\" != \\\"$HEAD_SHA\\\" ]; then\\n echo \\\"Skipping stale ERD preview comment for $HEAD_SHA; current head is $current_head.\\\"\\n exit 0\\n fi\\n\\n body=\\\"$MARKER\\\"$'\\\\n'\\\"### TailorDB ERD preview (__WORKSPACE_NAME__)\\\"$'\\\\n\\\\n'\\n body+=\\\"Self-contained ERD viewer HTML artifacts for this pull request. Each viewer can switch between the current schema and a diff against base branch \\\\`$BASE_REF\\\\`.\\\"$'\\\\n'\\n\\n while IFS=$'\\\\t' read -r name id; do\\n [ -z \\\"$name\\\" ] && continue\\n if [[ \\\"$name\\\" != *-viewer.html ]]; then\\n continue\\n fi\\n ns=${name%-viewer.html}\\n label=\\\"$ns viewer\\\"\\n body+=$'\\\\n'\\\"- **$label**: [$name]($SERVER/$REPO/actions/runs/$RUN_ID/artifacts/$id)\\\"\\n done < <(gh api \\\"repos/$REPO/actions/runs/$RUN_ID/artifacts\\\" --paginate \\\\\\n --jq '.artifacts[] | select(.name | endswith(\\\"-viewer.html\\\")) | [.name, (.id|tostring)] | @tsv' | sort)\\n\\n existing=$(gh api \\\"repos/$REPO/issues/$PR_NUMBER/comments\\\" --paginate \\\\\\n --jq 'map(select(.body | contains(env.MARKER))) | .[0].id // empty')\\n if [ -n \\\"$existing\\\" ]; then\\n gh api --method PATCH \\\"repos/$REPO/issues/comments/$existing\\\" -f body=\\\"$body\\\" >/dev/null\\n else\\n gh api --method POST \\\"repos/$REPO/issues/$PR_NUMBER/comments\\\" -f body=\\\"$body\\\" >/dev/null\\n fi\\n\\n # __ERD_PREVIEW_COMMENT_JOB_END__\\n tailor-deploy:\\n # __DEPLOY_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n permissions:\\n contents: read\\n environment: __ENVIRONMENT__\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-apply\\n uses: tailor-platform/actions/deploy@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n # __SEED_DATA_START__\\n - id: seed-data\\n if: false\\n shell: bash\\n # __WORKING_DIRECTORY__\\n run: |\\n # Uncomment and implement to seed data on deploy.\\n # Run after apply so the schema is ready.\\n # Example: node scripts/seed.mjs\\n true\\n # __SEED_DATA_END__\\n - id: slack-prereq\\n if: always()\\n shell: bash\\n env:\\n SLACK_TOKEN: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n SLACK_CHANNEL_ID: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n run: |\\n if [[ -n \\\"$SLACK_TOKEN\\\" && -n \\\"$SLACK_CHANNEL_ID\\\" ]]; then\\n echo \\\"ready=true\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-notify\\n if: always() && steps.slack-prereq.outputs.ready == 'true'\\n uses: tailor-platform/actions/notify@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n provider: slack\\n status: ${{ job.status }}\\n workspace-name: __WORKSPACE_NAME__\\n slack-token: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n slack-channel-id: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n # user-mapping: ${{ vars.TAILOR_SLACK_USER_MAPPING }}\\n\";","export default \"# __HEADER__\\nname: Tailor Coordinator (__WORKSPACE_NAME__)\\n\\non:\\n # __PULL_REQUEST_START__\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PULL_REQUEST_END__\\n push:\\n # __PUSH_BRANCHES_START__\\n branches: [\\\"__BRANCH__\\\"]\\n # __PUSH_BRANCHES_END__\\n # __PUSH_TAGS_START__\\n tags: [__TAG_PATTERN__]\\n # __PUSH_TAGS_END__\\n workflow_dispatch:\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __TAG_GUARD_JOB_START__\\n tailor-tag-guard:\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n contents: read\\n outputs:\\n on-branch: ${{ steps.tailor-tag-guard.outputs.on-branch }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n fetch-depth: 0\\n - id: tailor-tag-guard\\n uses: tailor-platform/actions/tag-guard@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n target-branch: __BRANCH__\\n # __TAG_GUARD_JOB_END__\\n\\n tailor-plan:\\n # __PLAN_NEEDS__\\n # __PLAN_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 60\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-plan-__WORKSPACE_NAME__-${{ github.event.pull_request.number || github.run_id }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: ./.github/actions/tailor-setup\\n # __PER_APP_PLAN_STEPS__\\n\\n tailor-deploy:\\n # __DEPLOY_NEEDS__\\n # __DEPLOY_IF__\\n # __DEPLOY_ENVIRONMENT__\\n runs-on: ubuntu-latest\\n timeout-minutes: 60\\n permissions:\\n contents: read\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: ./.github/actions/tailor-setup\\n # __PER_APP_DEPLOY_STEPS__\\n\";","export default \"# __HEADER__\\nname: Tailor Preview (__WORKSPACE_NAME__)\\n\\non:\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PR_TYPES__\\n # To deploy only for PRs that carry the `tailor:preview` label instead of all PRs,\\n # re-run: tailor setup preview --require-preview-label\\n # __PATHS__\\n\\npermissions:\\n contents: read\\n pull-requests: write\\n\\njobs:\\n tailor-preview-deploy:\\n # __DEPLOY_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-preview-__WORKSPACE_NAME__-${{ github.event.pull_request.number }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n - id: tailor-preview-deploy\\n uses: tailor-platform/actions/preview-deploy@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-name-prefix: __WORKSPACE_NAME__\\n region: \\\"__REGION__\\\"\\n organization-id: ${{ vars.TAILOR_PLATFORM_ORGANIZATION_ID }}\\n folder-id: ${{ vars.TAILOR_PLATFORM_FOLDER_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n - id: tailor-preview-comment\\n if: always()\\n uses: tailor-platform/actions/preview-comment@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-id: ${{ steps.tailor-preview-deploy.outputs.workspace-id }}\\n workspace-name: ${{ steps.tailor-preview-deploy.outputs.workspace-name }}\\n status: ${{ job.status == 'success' && 'success' || 'failure' }}\\n app-url: ${{ steps.tailor-preview-deploy.outputs.app-url }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n\\n tailor-preview-cleanup:\\n # __CLEANUP_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 15\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-preview-cleanup\\n uses: tailor-platform/actions/preview-cleanup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-name-prefix: __WORKSPACE_NAME__\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n\";","export default \"# __HEADER__\\nname: Tailor (__WORKSPACE_NAME__)\\n\\non:\\n push:\\n tags: [\\\"__TAG_PATTERN__\\\"]\\n workflow_dispatch:\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __TAG_GUARD_JOB_START__\\n tailor-tag-guard:\\n runs-on: ubuntu-latest\\n timeout-minutes: 10\\n permissions:\\n contents: read\\n outputs:\\n on-branch: ${{ steps.tailor-tag-guard.outputs.on-branch }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n fetch-depth: 0\\n - id: tailor-tag-guard\\n uses: tailor-platform/actions/tag-guard@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n target-branch: \\\"__BRANCH__\\\"\\n # __TAG_GUARD_JOB_END__\\n tailor-plan:\\n # __PLAN_NEEDS__\\n # __PLAN_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_START__\\n - id: tailor-seed-validate\\n run: __TAILOR_CLI__ seed validate\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_END__\\n - id: tailor-drift-check\\n uses: tailor-platform/actions/drift-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __MIGRATION_DRIFT_CHECK_START__\\n - id: tailor-migration-drift-check\\n uses: tailor-platform/actions/migration-drift-check@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __MIGRATION_DRIFT_CHECK_END__\\n - id: tailor-plan\\n uses: tailor-platform/actions/plan@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n label: __WORKSPACE_NAME__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n\\n tailor-deploy:\\n needs: tailor-plan\\n if: ${{ !(github.event_name == 'workflow_dispatch' && inputs['dry-run']) }}\\n environment: __ENVIRONMENT__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n permissions:\\n contents: read\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-apply\\n uses: tailor-platform/actions/deploy@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n # __SEED_DATA_START__\\n - id: seed-data\\n if: false\\n shell: bash\\n # __WORKING_DIRECTORY__\\n run: |\\n # Uncomment and implement to seed data on deploy.\\n # Run after apply so the schema is ready.\\n # Example: node scripts/seed.mjs\\n true\\n # __SEED_DATA_END__\\n - id: slack-prereq\\n if: always()\\n shell: bash\\n env:\\n SLACK_TOKEN: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n SLACK_CHANNEL_ID: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n run: |\\n if [[ -n \\\"$SLACK_TOKEN\\\" && -n \\\"$SLACK_CHANNEL_ID\\\" ]]; then\\n echo \\\"ready=true\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-notify\\n if: always() && steps.slack-prereq.outputs.ready == 'true'\\n uses: tailor-platform/actions/notify@1f2d0cc26b84b9fdae8a3a0427526df31e6c966b # v2.0.0\\n with:\\n provider: slack\\n status: ${{ job.status }}\\n workspace-name: __WORKSPACE_NAME__\\n slack-token: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n slack-channel-id: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n # user-mapping: ${{ vars.TAILOR_SLACK_USER_MAPPING }}\\n\";","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport actionTemplate from \"./action.yml\";\nimport branchTemplate from \"./branch.workflow.yml\";\nimport coordinateTemplate from \"./coordinate.workflow.yml\";\nimport previewTemplate from \"./preview.workflow.yml\";\nimport tagTemplate from \"./tag.workflow.yml\";\n\n// Bump on material template-structure changes (managed step ids, placeholders)\n// so old/new generations stay distinguishable in the lock.\n/** Template schema version, tracked per target in the lock file. */\nexport const TEMPLATE_VERSION = 9;\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"npm\" | \"bun\";\n\nconst TAILOR_CLI_COMMANDS: Record<PackageManager, string> = {\n pnpm: \"pnpm exec tailor\",\n npm: \"npx @tailor-platform/sdk\",\n yarn: \"yarn tailor\",\n bun: \"bun run tailor\",\n};\n\nconst HEADER = `# Generated by \\`tailor setup\\` — managed by the Tailor SDK.\n#\n# - Jobs and steps whose id starts with \\`tailor-\\` are managed by the SDK.\n# Do not edit or rename them.\n# - State is tracked in .github/tailor.lock (machine-owned: commit it, never edit it).\n# - Re-running \\`tailor setup\\` regenerates this file. If you have\n# edited it by hand, regeneration stops and asks for --force (which discards\n# your edits), so prefer keeping customizations in your own jobs/steps and\n# re-running setup after SDK updates.`;\n\nexport type RenderBranchParams = {\n workspaceName: string;\n branch: string;\n workingDirectory?: string;\n /** GitHub Environment for the plan/deploy jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Include the seed-validate step in the plan job (default: false). */\n seedValidate?: boolean;\n /** Include the migration-drift-check step in the plan job (default: false). */\n migrationDriftCheck?: boolean;\n erdPreview: { namespaces: string[] } | null;\n};\n\nexport type RenderTagParams = {\n workspaceName: string;\n tagPattern: string;\n /** Tag-reachability guard branch; omit for no guard. */\n branch?: string;\n workingDirectory?: string;\n /** GitHub Environment for the plan/deploy jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Include the seed-validate step in the plan job (default: false). */\n seedValidate?: boolean;\n /** Include the migration-drift-check step in the plan job (default: false). */\n migrationDriftCheck?: boolean;\n};\n\nexport type RenderPreviewParams = {\n workspaceName: string;\n branch: string;\n workingDirectory?: string;\n /** GitHub Environment for the preview jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Workspace region passed to `workspace create` on first PR push. */\n region: string;\n /**\n * When true, deploy preview only for PRs labeled `tailor:preview` (label-triggered mode).\n * Default false: preview deploys on every PR (open, sync, reopen).\n */\n requirePreviewLabel?: boolean;\n};\n\nexport type RenderActionParams = {\n workspaceName: string;\n workingDirectory?: string;\n /** Include the build-site slot (user-owned step for building static website assets). */\n hasStaticWebsites?: boolean;\n};\n\nexport type CoordinateApp = {\n /** App workspace name (same as the --action argument, e.g. \"ims\"). */\n name: string;\n /** App directory relative to repo root (e.g. \"apps/ims\"). */\n dir: string;\n /** Whether the app action contains the user-owned build-site slot. */\n hasStaticWebsites?: boolean;\n};\n\nexport type CoordinateAppGroup = {\n /** Stable step id suffix for this group. */\n id: string;\n /** Actions deployed together in one apply invocation. */\n apps: CoordinateApp[];\n};\n\nexport type CoordinateKind = \"branch\" | \"tag\";\n\nexport type RenderCoordinateParams = {\n coordinatorName: string;\n kind: CoordinateKind;\n actionGroups: CoordinateAppGroup[];\n branch?: string;\n tagPattern?: string;\n environment: string;\n packageManager: PackageManager;\n};\n\nexport type RenderResult = {\n content: string;\n generatedIds: string[];\n};\n\n/**\n * Detect the package manager used in a project directory by checking for lockfiles.\n * @param dir - Project directory to inspect\n * @returns Detected package manager, defaults to npm\n */\nexport function detectPackageManager(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (fs.existsSync(path.join(dir, \"yarn.lock\"))) return \"yarn\";\n if (fs.existsSync(path.join(dir, \"bun.lockb\")) || fs.existsSync(path.join(dir, \"bun.lock\")))\n return \"bun\";\n if (fs.existsSync(path.join(dir, \"package-lock.json\"))) return \"npm\";\n return \"npm\";\n}\n\n// Keep or drop a `# __X_START__` ... `# __X_END__` block (marker lines removed\n// when kept, whole block removed when dropped).\nfunction block(content: string, name: string, keep: boolean): string {\n if (keep) {\n return content.replace(new RegExp(`^ *# __${name}_(?:START|END)__\\\\n`, \"gm\"), \"\");\n }\n return content.replace(\n new RegExp(`^ *# __${name}_START__\\\\n[\\\\s\\\\S]*?^ *# __${name}_END__\\\\n`, \"m\"),\n \"\",\n );\n}\n\n// Replace a single-line `# __X__` marker. The marker line's own indentation is\n// reused for the replacement; when `replacement` is undefined the whole line is\n// removed. `replacement` may contain newlines for multi-line expansions.\nfunction line(content: string, name: string, replacement: string | undefined): string {\n const re = new RegExp(`^([ \\\\t]*)# __${name}__\\\\n`, \"gm\");\n return content.replace(re, (_match, indent: string) => {\n if (replacement === undefined) return \"\";\n return (\n replacement\n .split(\"\\n\")\n .map((l) => (l ? indent + l : l))\n .join(\"\\n\") + \"\\n\"\n );\n });\n}\n\nfunction applyCommon(\n content: string,\n params: {\n workspaceName: string;\n workingDirectory?: string;\n environment: string;\n packageManager: PackageManager;\n },\n): string {\n const { workingDirectory, environment, packageManager } = params;\n let out = line(content, \"HEADER\", HEADER);\n out = line(\n out,\n \"WORKING_DIRECTORY\",\n workingDirectory ? `working-directory: ${workingDirectory}` : undefined,\n );\n // Plain placeholders last so values containing `$` are not interpreted as\n // replacement patterns.\n return out\n .replaceAll(\"__WORKSPACE_NAME__\", () => params.workspaceName)\n .replaceAll(\"__ENVIRONMENT__\", () => environment)\n .replaceAll(\"__PACKAGE_MANAGER__\", () => packageManager)\n .replaceAll(\"__TAILOR_CLI__\", () => TAILOR_CLI_COMMANDS[packageManager])\n .replaceAll(\"__APP_DIR__\", () => workingDirectory ?? \".\");\n}\n\n/**\n * Render the branch-target deploy workflow.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderBranchWorkflow(params: RenderBranchParams): RenderResult {\n const { branch } = params;\n const seedValidate = params.seedValidate ?? false;\n const migrationDriftCheck = params.migrationDriftCheck ?? false;\n const erdPreview = params.erdPreview;\n\n let out = branchTemplate;\n out = block(out, \"PLAN_JOB\", true);\n out = block(out, \"ERD_PREVIEW_JOB\", erdPreview !== null);\n out = block(out, \"ERD_PREVIEW_COMMENT_JOB\", erdPreview !== null);\n out = block(out, \"PULL_REQUEST\", true);\n out = block(out, \"DISPATCH_INPUTS\", true);\n out = block(out, \"SEED_VALIDATE\", seedValidate);\n out = block(out, \"MIGRATION_DRIFT_CHECK\", migrationDriftCheck);\n // SEED_DATA is dropped from the default rendering; users add their own step.\n out = block(out, \"SEED_DATA\", false);\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: >-\\n github.event_name == 'push' ||\\n (github.event_name == 'workflow_dispatch' && !inputs['dry-run'])`,\n );\n out = line(\n out,\n \"PATHS\",\n params.workingDirectory ? `paths: [\"${params.workingDirectory}/**\"]` : undefined,\n );\n\n out = applyCommon(out, params).replaceAll(\"__BRANCH__\", () => branch);\n\n const generatedIds: string[] = [\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-install\",\n \"tailor-plan/tailor-generate-check\",\n ];\n if (seedValidate) {\n generatedIds.push(\"tailor-plan/tailor-seed-validate\");\n }\n generatedIds.push(\"tailor-plan/tailor-drift-check\");\n if (migrationDriftCheck) {\n generatedIds.push(\"tailor-plan/tailor-migration-drift-check\");\n }\n generatedIds.push(\"tailor-plan/tailor-plan\");\n if (erdPreview) {\n generatedIds.push(\n \"tailor-erd-preview-matrix\",\n \"tailor-erd-preview-matrix/tailor-checkout\",\n \"tailor-erd-preview-matrix/tailor-checkout-base\",\n \"tailor-erd-preview-matrix/tailor-erd-preview-matrix\",\n \"tailor-erd-preview\",\n \"tailor-erd-preview/tailor-checkout\",\n \"tailor-erd-preview/tailor-setup\",\n \"tailor-erd-preview/tailor-checkout-base\",\n \"tailor-erd-preview/tailor-detect-base-package-manager\",\n \"tailor-erd-preview/tailor-setup-base-pnpm\",\n \"tailor-erd-preview/tailor-setup-base-node\",\n \"tailor-erd-preview/tailor-setup-base-yarn\",\n \"tailor-erd-preview/tailor-setup-base-bun\",\n \"tailor-erd-preview/tailor-install-base\",\n \"tailor-erd-preview/tailor-restore-head-setup\",\n \"tailor-erd-preview/tailor-build-erd-preview\",\n \"tailor-erd-preview/tailor-upload-erd-viewer\",\n \"tailor-erd-preview-comment\",\n \"tailor-erd-preview-comment/tailor-comment-erd-preview\",\n );\n }\n generatedIds.push(\n \"tailor-deploy\",\n \"tailor-deploy/tailor-checkout\",\n \"tailor-deploy/tailor-setup\",\n \"tailor-deploy/tailor-install\",\n \"tailor-deploy/tailor-apply\",\n \"tailor-deploy/tailor-notify\",\n );\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the tag-target deploy workflow.\n *\n * When `branch` is set, a tag-reachability guard job is generated and the plan\n * job gates on it; otherwise no guard is emitted and tags deploy unconditionally.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderTagWorkflow(params: RenderTagParams): RenderResult {\n const { tagPattern, branch } = params;\n const hasGuard = branch !== undefined;\n const seedValidate = params.seedValidate ?? false;\n const migrationDriftCheck = params.migrationDriftCheck ?? false;\n\n let out = tagTemplate;\n out = block(out, \"TAG_GUARD_JOB\", hasGuard);\n out = block(out, \"SEED_VALIDATE\", seedValidate);\n out = block(out, \"MIGRATION_DRIFT_CHECK\", migrationDriftCheck);\n // SEED_DATA is dropped from the default rendering; users add their own step.\n out = block(out, \"SEED_DATA\", false);\n out = line(out, \"PLAN_NEEDS\", hasGuard ? \"needs: tailor-tag-guard\" : undefined);\n out = line(\n out,\n \"PLAN_IF\",\n hasGuard\n ? `if: >-\\n github.event_name == 'workflow_dispatch' ||\\n needs.tailor-tag-guard.outputs.on-branch == 'true'`\n : undefined,\n );\n\n out = applyCommon(out, params).replaceAll(\"__TAG_PATTERN__\", () => tagPattern);\n if (hasGuard) {\n out = out.replaceAll(\"__BRANCH__\", () => branch);\n }\n\n const generatedIds: string[] = [];\n if (hasGuard) {\n generatedIds.push(\n \"tailor-tag-guard\",\n \"tailor-tag-guard/tailor-checkout\",\n \"tailor-tag-guard/tailor-tag-guard\",\n );\n }\n generatedIds.push(\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-install\",\n \"tailor-plan/tailor-generate-check\",\n );\n if (seedValidate) {\n generatedIds.push(\"tailor-plan/tailor-seed-validate\");\n }\n generatedIds.push(\"tailor-plan/tailor-drift-check\");\n if (migrationDriftCheck) {\n generatedIds.push(\"tailor-plan/tailor-migration-drift-check\");\n }\n generatedIds.push(\n \"tailor-plan/tailor-plan\",\n \"tailor-deploy\",\n \"tailor-deploy/tailor-checkout\",\n \"tailor-deploy/tailor-setup\",\n \"tailor-deploy/tailor-install\",\n \"tailor-deploy/tailor-apply\",\n \"tailor-deploy/tailor-notify\",\n );\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the preview workflow (PR open/sync/close triggers).\n *\n * The deploy job runs on opened/synchronize/reopened events; the cleanup job\n * runs on the closed event. Both jobs run in the same workflow so PR number\n * context is always available.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderPreviewWorkflow(params: RenderPreviewParams): RenderResult {\n const { branch } = params;\n const requirePreviewLabel = params.requirePreviewLabel ?? false;\n\n let out = previewTemplate;\n out = line(\n out,\n \"PATHS\",\n params.workingDirectory ? `paths: [\"${params.workingDirectory}/**\"]` : undefined,\n );\n\n // PR trigger event types — single line() marker avoids duplicate YAML map keys in the template.\n out = line(\n out,\n \"PR_TYPES\",\n requirePreviewLabel\n ? \"types: [labeled, synchronize, reopened, closed]\"\n : \"types: [opened, synchronize, reopened, closed]\",\n );\n\n // Deploy job if condition. Fork PRs don't have access to secrets/vars, so guard them out.\n const deployIf = requirePreviewLabel\n ? `if: >-\\n contains(github.event.pull_request.labels.*.name, 'tailor:preview') &&\\n github.event.action != 'closed' &&\\n !github.event.pull_request.draft &&\\n !github.event.pull_request.head.repo.fork`\n : `if: >-\\n github.event.action != 'closed' &&\\n !github.event.pull_request.draft &&\\n !github.event.pull_request.head.repo.fork`;\n out = line(out, \"DEPLOY_IF\", deployIf);\n\n // Cleanup always runs on closed regardless of current labels: the label may have been\n // removed after a preview deploy, and the cleanup action is a no-op when no workspace exists.\n // Fork PRs also need guarding since cleanup requires secrets/vars.\n out = line(\n out,\n \"CLEANUP_IF\",\n `if: >-\\n github.event.action == 'closed' &&\\n !github.event.pull_request.head.repo.fork`,\n );\n\n out = applyCommon(out, params)\n .replaceAll(\"__BRANCH__\", () => branch)\n .replaceAll(\"__REGION__\", () => params.region);\n\n const generatedIds: string[] = [\n \"tailor-preview-deploy\",\n \"tailor-preview-deploy/tailor-checkout\",\n \"tailor-preview-deploy/tailor-setup\",\n \"tailor-preview-deploy/tailor-install\",\n \"tailor-preview-deploy/tailor-generate-check\",\n \"tailor-preview-deploy/tailor-preview-deploy\",\n \"tailor-preview-deploy/tailor-preview-comment\",\n \"tailor-preview-cleanup\",\n \"tailor-preview-cleanup/tailor-checkout\",\n \"tailor-preview-cleanup/tailor-setup\",\n \"tailor-preview-cleanup/tailor-install\",\n \"tailor-preview-cleanup/tailor-preview-cleanup\",\n ];\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the per-app composite action.\n *\n * The action contains only the deploy step and a failure notification.\n * Checkout, setup, and install are the caller's responsibility (coordinator workflow).\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed step ids\n */\nexport function renderActionWorkflow(params: RenderActionParams): RenderResult {\n let out = actionTemplate;\n out = line(out, \"HEADER\", HEADER);\n\n // build-site is a user-owned slot; include when staticWebsites are configured.\n out = block(out, \"STATIC_WEBSITE_BUILD\", params.hasStaticWebsites ?? false);\n\n out = out.replaceAll(\"__WORKSPACE_NAME__\", () => params.workspaceName);\n\n const generatedIds = [\"tailor-apply\", \"tailor-notify\"];\n\n return { content: out, generatedIds };\n}\n\nconst ACTIONS_SHA = \"1f2d0cc26b84b9fdae8a3a0427526df31e6c966b\";\nconst ACTIONS_VERSION = \"v2.0.0\";\n\n/**\n * Render the coordinator workflow that orchestrates per-app composite actions.\n *\n * Generates per-app plan steps (generate-check, drift-check, plan) and per-app\n * deploy steps (calling each app's composite action at .github/actions/tailor-<name>).\n * Checkout, setup, and install are done once per job using the local tailor-setup action.\n * @param params - Coordinator and app configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderCoordinateWorkflow(params: RenderCoordinateParams): RenderResult {\n const { coordinatorName, kind, actionGroups, environment, packageManager } = params;\n const isTag = kind === \"tag\";\n const branch = params.branch;\n const tagPattern = params.tagPattern ?? \"v*\";\n\n let out = coordinateTemplate;\n out = line(out, \"HEADER\", HEADER);\n\n out = block(out, \"PULL_REQUEST\", !isTag);\n out = block(out, \"PUSH_BRANCHES\", !isTag);\n out = block(out, \"PUSH_TAGS\", isTag);\n out = block(out, \"TAG_GUARD_JOB\", isTag && branch !== undefined);\n\n if (isTag && branch !== undefined) {\n out = line(out, \"PLAN_NEEDS\", \"needs: tailor-tag-guard\");\n out = line(\n out,\n \"PLAN_IF\",\n `if: >-\\n github.event_name == 'workflow_dispatch' ||\\n needs.tailor-tag-guard.outputs.on-branch == 'true'`,\n );\n } else if (isTag) {\n out = line(out, \"PLAN_NEEDS\", undefined);\n out = line(out, \"PLAN_IF\", undefined);\n } else {\n out = line(out, \"PLAN_NEEDS\", undefined);\n out = line(\n out,\n \"PLAN_IF\",\n `if: >-\\n github.event_name == 'pull_request' ||\\n (github.event_name == 'workflow_dispatch' && inputs['dry-run'])`,\n );\n }\n\n if (isTag) {\n // Tag coordinator: deploy runs after plan (plan checks tag reachability).\n // When plan is skipped via workflow_dispatch dry-run, deploy is also skipped.\n out = line(out, \"DEPLOY_NEEDS\", \"needs: tailor-plan\");\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: \\${{ !(github.event_name == 'workflow_dispatch' && inputs['dry-run']) }}`,\n );\n out = line(out, \"DEPLOY_ENVIRONMENT\", `environment: ${environment}`);\n } else {\n // Branch coordinator: plan (PR) and deploy (push) are independent jobs —\n // no needs relationship, so deploy is not skipped when plan is skipped on push.\n out = line(out, \"DEPLOY_NEEDS\", undefined);\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: >-\\n github.event_name == 'push' ||\\n (github.event_name == 'workflow_dispatch' && !inputs['dry-run'])`,\n );\n out = line(out, \"DEPLOY_ENVIRONMENT\", `environment: ${environment}`);\n }\n\n const driftCheckStep = [\n `- id: tailor-drift-check`,\n ` uses: tailor-platform/actions/drift-check@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ].join(\"\\n\");\n const configPath = (app: CoordinateApp) =>\n app.dir === \".\" ? \"tailor.config.ts\" : `${app.dir}/tailor.config.ts`;\n const groupConfigPath = (group: CoordinateAppGroup) => group.apps.map(configPath).join(\",\");\n const firstApp = (group: CoordinateAppGroup) => {\n const [app] = group.apps;\n if (!app) {\n throw new Error(\"Coordinate action groups must contain at least one app.\");\n }\n return app;\n };\n const singleAppPlanStep = (group: CoordinateAppGroup, app: CoordinateApp) => {\n const wd = app.dir !== \".\" ? app.dir : undefined;\n const wdLine = wd ? `\\n working-directory: ${wd}` : \"\";\n return [\n `- id: tailor-plan-${group.id}`,\n ` if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork`,\n ` uses: tailor-platform/actions/plan@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` package-manager: ${packageManager}${wdLine}`,\n ` label: ${coordinatorName}/${group.id}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` github-token: \\${{ secrets.GITHUB_TOKEN }}`,\n ];\n };\n const multiConfigPlanStep = (group: CoordinateAppGroup) => [\n `- id: tailor-plan-${group.id}`,\n ` if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork`,\n ` uses: tailor-platform/actions/plan@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` env:`,\n ` TAILOR_PLATFORM_SDK_CONFIG_PATH: ${groupConfigPath(group)}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` package-manager: ${packageManager}`,\n ` label: ${coordinatorName}/${group.id}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` github-token: \\${{ secrets.GITHUB_TOKEN }}`,\n ];\n const perAppPlanSteps = actionGroups\n .flatMap((group) => {\n const generateCheckSteps = group.apps.flatMap((app) => {\n const wd = app.dir !== \".\" ? app.dir : undefined;\n const wdLine = wd ? `\\n working-directory: ${wd}` : \"\";\n return [\n `- id: tailor-generate-check-${app.name}`,\n ` uses: tailor-platform/actions/generate-check@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}${wdLine}`,\n ];\n });\n const planStep =\n group.apps.length === 1\n ? singleAppPlanStep(group, firstApp(group))\n : multiConfigPlanStep(group);\n return [...generateCheckSteps, ...planStep];\n })\n .join(\"\\n\");\n out = line(out, \"PER_APP_PLAN_STEPS\", `${driftCheckStep}\\n${perAppPlanSteps}`);\n\n const singleAppDeployStep = (group: CoordinateAppGroup, app: CoordinateApp) => [\n `- id: tailor-deploy-${group.id}`,\n ` uses: ./.github/actions/tailor-${app.name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${app.name}`,\n ` working-directory: ${app.dir}`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ` # editable: api-url:`,\n ];\n const buildSiteStep = (app: CoordinateApp) => [\n `- id: tailor-build-site-${app.name}`,\n ` uses: ./.github/actions/tailor-${app.name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${app.name}`,\n ` working-directory: ${app.dir}`,\n ` deploy: \"false\"`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ];\n const multiConfigDeployStep = (group: CoordinateAppGroup) => [\n ...group.apps.filter((app) => app.hasStaticWebsites).flatMap(buildSiteStep),\n `- id: tailor-deploy-${group.id}`,\n // Grouped deploys reuse one app action; keep action.yml parameterized by config/deploy/build-site inputs.\n ` uses: ./.github/actions/tailor-${firstApp(group).name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${coordinatorName}/${group.id}`,\n ` working-directory: .`,\n ` config: ${groupConfigPath(group)}`,\n ` build-site: \"false\"`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ` # editable: api-url:`,\n ];\n const deploySteps = actionGroups\n .flatMap((group) =>\n group.apps.length === 1\n ? singleAppDeployStep(group, firstApp(group))\n : multiConfigDeployStep(group),\n )\n .join(\"\\n\");\n out = line(out, \"PER_APP_DEPLOY_STEPS\", deploySteps);\n\n // Plain placeholders last so values containing `$` are not interpreted as\n // replacement patterns.\n out = out.replaceAll(\"__WORKSPACE_NAME__\", () => coordinatorName);\n out = out.replaceAll(\"__ENVIRONMENT__\", () => environment);\n if (branch !== undefined) {\n out = out.replaceAll(\"__BRANCH__\", () => branch);\n }\n if (isTag) {\n out = out.replaceAll(\"__TAG_PATTERN__\", () => tagPattern);\n }\n\n const generatedIds: string[] = [];\n if (isTag && branch !== undefined) {\n generatedIds.push(\n \"tailor-tag-guard\",\n \"tailor-tag-guard/tailor-checkout\",\n \"tailor-tag-guard/tailor-tag-guard\",\n );\n }\n generatedIds.push(\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-drift-check\",\n );\n for (const group of actionGroups) {\n for (const app of group.apps) {\n generatedIds.push(`tailor-plan/tailor-generate-check-${app.name}`);\n }\n generatedIds.push(`tailor-plan/tailor-plan-${group.id}`);\n }\n generatedIds.push(\"tailor-deploy\", \"tailor-deploy/tailor-checkout\", \"tailor-deploy/tailor-setup\");\n for (const group of actionGroups) {\n for (const app of group.apps) {\n if (group.apps.length > 1 && app.hasStaticWebsites) {\n generatedIds.push(`tailor-deploy/tailor-build-site-${app.name}`);\n }\n }\n generatedIds.push(`tailor-deploy/tailor-deploy-${group.id}`);\n }\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the content of the user-owned .github/actions/tailor-setup/action.yml local action.\n *\n * This file is generated once by `setup coordinate` and never overwritten.\n * It wraps the setup and install actions with the package manager baked in.\n * @param params - Package manager configuration\n * @returns File content string\n */\nexport function renderTailorSetupAction(params: { packageManager: PackageManager }): string {\n const { packageManager } = params;\n return [\n `# This file is user-owned. Generated once by \\`tailor setup coordinate\\` and never overwritten.`,\n `# Customize freely: add pre/post steps, change install flags, etc.`,\n `name: Tailor Setup`,\n `description: Install dependencies and run tailor setup for composite action callers.`,\n `runs:`,\n ` using: composite`,\n ` steps:`,\n ` - uses: tailor-platform/actions/setup@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ` # Add custom steps here (e.g. private registry authentication)`,\n ` - uses: tailor-platform/actions/install@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ` # editable: install-command:`,\n ``,\n ].join(\"\\n\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureConfigId } from \"#/cli/commands/deploy/config-id-injector\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { workspaceNameSchema } from \"#/cli/shared/workspace-name\";\nimport { getNamespacesWithMigrations } from \"../tailordb/migrate/config\";\nimport { detectDefaultBranch, type GitRunner } from \"./git\";\nimport {\n findTarget,\n hashContent,\n LOCK_VERSION,\n readLock,\n writeLock,\n type LockFile,\n type LockInputs,\n type LockTarget,\n type TargetKind,\n} from \"./lock\";\nimport {\n detectPackageManager,\n renderActionWorkflow,\n renderBranchWorkflow,\n renderCoordinateWorkflow,\n renderPreviewWorkflow,\n renderTagWorkflow,\n renderTailorSetupAction,\n TEMPLATE_VERSION,\n type CoordinateApp,\n type CoordinateAppGroup,\n type CoordinateKind,\n type PackageManager,\n type RenderResult,\n} from \"./templates\";\n\ntype CommonSetupOptions = {\n workspaceName?: string;\n dir: string;\n environment?: string;\n force: boolean;\n outputDir: string;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n /** Injectable config-name loader, for testing. Defaults to loading the config. */\n loadConfigName?: (configPath: string) => Promise<string | undefined>;\n /** Injectable TailorDB namespace loader, for testing. Defaults to loading the config. */\n loadErdNamespaces?: (configPath: string) => Promise<string[]>;\n /** Injectable migration config detector, for testing. Defaults to loading the config. */\n loadHasMigrations?: (configPath: string) => Promise<boolean>;\n /** Injectable seed plugin detector, for testing. Defaults to loading the config. */\n loadHasSeeds?: (configPath: string) => Promise<boolean>;\n /** Injectable static website detector, for testing. Defaults to loading the config. */\n loadHasStaticWebsites?: (configPath: string) => Promise<boolean>;\n};\n\nexport type BranchSetupOptions = CommonSetupOptions & {\n kind: \"branch\";\n branch?: string;\n erdPreview: boolean;\n};\n\nexport type TagSetupOptions = CommonSetupOptions & {\n kind: \"tag\";\n tagPattern: string;\n branch?: string;\n};\n\nexport type PreviewSetupOptions = CommonSetupOptions & {\n kind: \"preview\";\n branch?: string;\n /** Workspace region for preview workspace creation (e.g. `us-west`). */\n region: string;\n /**\n * When true, the preview workflow deploys only for PRs labeled `tailor:preview`.\n * Default false: preview deploys on every PR.\n */\n requirePreviewLabel?: boolean;\n};\n\nexport type ActionSetupOptions = CommonSetupOptions & {\n kind: \"action\";\n};\n\nexport type SetupTargetOptions =\n | BranchSetupOptions\n | TagSetupOptions\n | PreviewSetupOptions\n | ActionSetupOptions;\n\nexport type CoordinateSetupOptions = {\n coordinatorName: string;\n coordinateKind: CoordinateKind;\n /** Action names or comma-separated action groups (without tailor- prefix), in deploy order. */\n actions: string[];\n branch?: string;\n tagPattern?: string;\n environment?: string;\n force: boolean;\n outputDir: string;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n};\n\nfunction actionName(input: string): string {\n return input.startsWith(\"tailor-\") ? input.slice(\"tailor-\".length) : input;\n}\n\nfunction splitActionGroup(input: string): string[] {\n const names = input.split(\",\").map((entry) => actionName(entry.trim()));\n if (names.some((name) => name.length === 0)) {\n throw new Error(\"--action must contain one or more non-empty action names.\");\n }\n return names;\n}\n\nfunction uniqueGroupId(names: readonly string[], usedIds: Set<string>): string {\n const base = names.join(\"-\");\n let id = base;\n let suffix = 2;\n while (usedIds.has(id)) {\n id = `${base}-${suffix}`;\n suffix += 1;\n }\n usedIds.add(id);\n return id;\n}\n\nasync function defaultLoadConfigName(configPath: string): Promise<string | undefined> {\n const { config } = await loadConfig(configPath);\n return config.name;\n}\n\nasync function defaultLoadErdNamespaces(configPath: string): Promise<string[]> {\n const { config } = await loadConfig(configPath);\n return extractOwnedNamespaces(config);\n}\n\nasync function defaultLoadHasMigrations(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return getNamespacesWithMigrations(config, path.dirname(configPath)).length > 0;\n}\n\nasync function defaultLoadHasSeeds(configPath: string): Promise<boolean> {\n const { plugins } = await loadConfig(configPath);\n return plugins.some((p) => p.id === \"@tailor-platform/seed\");\n}\n\nasync function defaultLoadHasStaticWebsites(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return (config.staticWebsites?.length ?? 0) > 0;\n}\n\n// The name is used as the plan label, the generated file name, and the default\n// GitHub Environment name, so it must stay within the workspace-name charset.\nfunction validateWorkspaceName(name: string): void {\n if (!workspaceNameSchema.safeParse(name).success) {\n throw new Error(\n `Invalid workspace name \"${name}\". Names must be 3-63 characters of lowercase ` +\n \"letters, numbers, and hyphens, and cannot start or end with a hyphen. \" +\n \"Pass a valid name with --name.\",\n );\n }\n}\n\n// The values below are embedded into workflow YAML. Restrict them to\n// characters that are safe inside a double-quoted YAML scalar (and cannot\n// smuggle a ${{ }} expression into the generated file).\nconst BRANCH_RE = /^[A-Za-z0-9._/-]+$/;\nconst TAG_PATTERN_RE = /^[A-Za-z0-9._/*?![\\]-]+$/;\n\nfunction validateBranch(branch: string): void {\n if (!BRANCH_RE.test(branch)) {\n throw new Error(\n `Invalid branch name \"${branch}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported here.`,\n );\n }\n}\n\nfunction validateTagPattern(pattern: string): void {\n if (!TAG_PATTERN_RE.test(pattern)) {\n throw new Error(\n `Invalid tag pattern \"${pattern}\". Only letters, numbers, \".\", \"_\", \"/\", \"-\", and the glob characters \"*?![]\" are supported.`,\n );\n }\n}\n\n// The environment name is embedded into workflow YAML as a plain scalar.\nconst ENVIRONMENT_RE = /^[A-Za-z0-9._/-]+$/;\n\nfunction validateEnvironment(environment: string): void {\n if (!ENVIRONMENT_RE.test(environment)) {\n throw new Error(\n `Invalid environment name \"${environment}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported.`,\n );\n }\n}\n\n// `--region` is embedded into workflow YAML as a plain scalar.\nconst REGION_RE = /^[A-Za-z0-9._-]+$/;\n\nfunction validateRegion(region: string): void {\n if (!REGION_RE.test(region)) {\n throw new Error(\n `Invalid region \"${region}\". Only letters, numbers, \".\", \"_\", and \"-\" are supported.`,\n );\n }\n}\n\n// `--dir` is embedded into workflow YAML (paths filters / working-directory).\n// Restrict it to POSIX path characters so it cannot break the YAML or smuggle\n// in a ${{ }} expression. Checked after backslashes are normalized to \"/\".\nconst DIR_RE = /^[A-Za-z0-9._/-]+$/;\n\nfunction validateDir(dir: string): void {\n if (!DIR_RE.test(dir)) {\n throw new Error(\n `Invalid --dir \"${dir}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported.`,\n );\n }\n}\n\n// ERD namespaces are embedded into a GitHub Actions matrix and artifact file\n// names. Keep them to path-safe scalar values.\nconst ERD_NAMESPACE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nfunction validateErdNamespaces(namespaces: readonly string[]): void {\n for (const namespace of namespaces) {\n if (!ERD_NAMESPACE_RE.test(namespace)) {\n throw new Error(\n `TailorDB namespace \"${namespace}\" cannot be used in --erd-preview. ` +\n \"Only letters, numbers, '.', '_', and '-' are supported, and the name must start with a letter or number.\",\n );\n }\n }\n}\n\n// `rel` is \"\" for the root itself, \"..\" or \"../foo\" for an escape. Guard on\n// the path segment so a sibling-prefixed name like \"..foo\" is not rejected.\nfunction escapesRoot(rel: string): boolean {\n return (\n rel === \"..\" || rel.startsWith(`..${path.sep}`) || rel.startsWith(\"../\") || path.isAbsolute(rel)\n );\n}\n\n/**\n * Resolve the config file path for the given app directory.\n *\n * `--dir` must stay inside the repository: the value is embedded in workflow\n * `paths:` filters and the config under it gets mutated (id injection), so\n * absolute paths and `..` traversal are rejected.\n * @param outputDir - Repository root (cwd)\n * @param dir - App directory relative to the repo root\n * @returns Absolute path to tailor.config.ts\n */\nfunction resolveConfigPath(outputDir: string, dir: string): string {\n const appDir = path.resolve(outputDir, dir);\n const rel = path.relative(outputDir, appDir);\n if (path.isAbsolute(dir) || escapesRoot(rel)) {\n throw new Error(`--dir must be a relative path inside the repository (got \"${dir}\").`);\n }\n // Also catch symlinked subdirectories that point outside the repository.\n if (fs.existsSync(appDir)) {\n const realAppDir = path.normalize(fs.realpathSync(appDir));\n const realOutputDir = path.normalize(fs.realpathSync(outputDir));\n const realRel = path.relative(realOutputDir, realAppDir);\n if (escapesRoot(realRel)) {\n throw new Error(\n `--dir must resolve to a directory inside the repository (got \"${dir}\", which links outside it).`,\n );\n }\n }\n const configPath = path.join(appDir, \"tailor.config.ts\");\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `tailor.config.ts not found at ${configPath}. ` +\n \"Run this from your SDK project root, or pass the app directory with --dir.\",\n );\n }\n return configPath;\n}\n\ntype Resolved = {\n kind: TargetKind;\n workspaceName: string;\n branch: string | null;\n environment: string;\n packageManager: PackageManager;\n erdNamespaces: string[];\n render: RenderResult;\n inputs: LockInputs;\n file: string;\n configPath: string;\n};\n\n/**\n * Resolve all derived values and render the workflow content.\n * @param options - Setup options\n * @returns Resolved target metadata and rendered content\n */\nasync function resolve(options: SetupTargetOptions): Promise<Resolved> {\n // Normalize before any filesystem use and before embedding into workflow\n // YAML (paths filters / working-directory): POSIX separators, collapse\n // duplicate slashes, drop a leading \"./\" and trailing \"/\" so values like\n // \"./apps/backend/\" produce a clean \"apps/backend\".\n const dir =\n options.dir\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/{2,}/g, \"/\")\n .replace(/^\\.\\//, \"\")\n .replace(/\\/$/, \"\") || \".\";\n validateDir(dir);\n const workingDirectory = dir !== \".\" ? dir : undefined;\n\n const configPath = resolveConfigPath(options.outputDir, dir);\n\n const loadName = options.loadConfigName ?? defaultLoadConfigName;\n const workspaceName = options.workspaceName ?? (await loadName(configPath));\n if (!workspaceName) {\n throw new Error(\n \"Could not determine the workspace name. \" +\n \"Pass --name, or set 'name' in tailor.config.ts.\",\n );\n }\n validateWorkspaceName(workspaceName);\n\n const { kind } = options;\n const packageManager = detectPackageManager(options.outputDir);\n // The env-scoped TAILOR_PLATFORM_WORKSPACE_ID variable is only readable by a\n // job that declares `environment:`, so every plan/deploy job sets one. When\n // --environment is omitted it defaults to the workspace name.\n const environment = options.environment ?? workspaceName;\n validateEnvironment(environment);\n\n if (kind === \"tag\") {\n validateTagPattern(options.tagPattern);\n }\n\n let branch: string | null = null;\n let branchAutoDetected = false;\n let render: RenderResult;\n let erdNamespaces: string[] = [];\n let hasMigrations = false;\n let hasSeeds = false;\n let hasStaticWebsites = false;\n const loadHasMigrations = options.loadHasMigrations ?? defaultLoadHasMigrations;\n const loadHasSeeds = options.loadHasSeeds ?? defaultLoadHasSeeds;\n const loadHasStaticWebsites = options.loadHasStaticWebsites ?? defaultLoadHasStaticWebsites;\n\n if (kind === \"branch\") {\n if (options.erdPreview) {\n const loadErdNamespaces = options.loadErdNamespaces ?? defaultLoadErdNamespaces;\n erdNamespaces = await loadErdNamespaces(configPath);\n if (erdNamespaces.length === 0) {\n throw new Error(\n \"No TailorDB namespaces found for --erd-preview. Define owned db namespaces in tailor.config.ts.\",\n );\n }\n validateErdNamespaces(erdNamespaces);\n }\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(options.outputDir, options.gitRunner);\n validateBranch(branch);\n hasMigrations = await loadHasMigrations(configPath);\n hasSeeds = await loadHasSeeds(configPath);\n render = renderBranchWorkflow({\n workspaceName,\n branch,\n workingDirectory,\n environment,\n packageManager,\n erdPreview: options.erdPreview ? { namespaces: erdNamespaces } : null,\n migrationDriftCheck: hasMigrations,\n seedValidate: hasSeeds,\n });\n } else if (kind === \"tag\") {\n branch = options.branch ?? null;\n if (branch !== null) {\n validateBranch(branch);\n }\n hasMigrations = await loadHasMigrations(configPath);\n hasSeeds = await loadHasSeeds(configPath);\n render = renderTagWorkflow({\n workspaceName,\n tagPattern: options.tagPattern,\n branch: options.branch,\n workingDirectory,\n environment,\n packageManager,\n migrationDriftCheck: hasMigrations,\n seedValidate: hasSeeds,\n });\n } else if (kind === \"preview\") {\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(options.outputDir, options.gitRunner);\n validateBranch(branch);\n validateRegion(options.region);\n render = renderPreviewWorkflow({\n workspaceName,\n branch,\n workingDirectory,\n environment,\n packageManager,\n region: options.region,\n requirePreviewLabel: options.requirePreviewLabel ?? false,\n });\n } else {\n // action — no branch detection, no package-manager embedding (caller installs)\n hasStaticWebsites = await loadHasStaticWebsites(configPath);\n render = renderActionWorkflow({ workspaceName, workingDirectory, hasStaticWebsites });\n }\n\n // File name encodes the target kind so branch + tag + preview can coexist\n // under the same workspace name without colliding.\n const kindSuffix = kind === \"tag\" ? \"-tag\" : kind === \"preview\" ? \"-preview\" : \"\";\n const file =\n kind === \"action\"\n ? `.github/actions/tailor-${workspaceName}/action.yml`\n : `.github/workflows/tailor-${workspaceName}${kindSuffix}.yml`;\n\n const inputs: LockInputs = {\n branch: kind === \"action\" ? null : branch,\n branchAutoDetected: kind === \"branch\" || kind === \"preview\" ? branchAutoDetected : undefined,\n tagPattern: kind === \"tag\" ? options.tagPattern : null,\n environment,\n dir,\n packageManager,\n region: kind === \"preview\" ? options.region : undefined,\n requirePreviewLabel: kind === \"preview\" ? (options.requirePreviewLabel ?? false) : undefined,\n erdPreview: kind === \"branch\" ? options.erdPreview : false,\n erdNamespaces: kind === \"branch\" && options.erdPreview ? erdNamespaces : undefined,\n migrationDriftCheck: kind === \"branch\" || kind === \"tag\" ? hasMigrations : undefined,\n seedValidate: kind === \"branch\" || kind === \"tag\" ? hasSeeds : undefined,\n hasStaticWebsites: kind === \"action\" ? hasStaticWebsites : undefined,\n };\n\n return {\n kind,\n workspaceName,\n branch,\n environment,\n packageManager,\n erdNamespaces,\n render,\n inputs,\n file,\n configPath,\n };\n}\n\ntype Decision =\n | { action: \"create\" }\n | { action: \"regenerate\" }\n | { action: \"restore\" }\n | { action: \"conflict\"; reason: string };\n\n// Matches the user-editable run: body under the build-site step. Used to\n// normalise the content before hashing so that custom build commands do not\n// trigger false hand-edit drift.\nconst BUILD_SITE_RUN_RE =\n /([ \\t]*- id: build-site\\n(?:[ \\t]+if: [^\\n]+\\n)?[ \\t]+shell: bash\\n[ \\t]+run: \\|)([\\s\\S]*?)(\\n[ \\t]*- |\\n*$)/;\n\n/**\n * Strip the mutable run: body of the build-site step before hashing.\n * When hasStaticWebsites is true the step is present; users are expected to\n * replace the placeholder command with their actual build command. We only\n * hash the structural parts (step id, shell declaration, run: key) so that\n * editing the build command does not look like unintended drift.\n * When hasStaticWebsites is false the step is absent, so the regex is a no-op.\n * @param content - Raw action workflow content\n * @returns Normalised content with the build-site run body replaced by a placeholder\n */\nexport function normalizeActionContent(content: string): string {\n return content.replace(\n BUILD_SITE_RUN_RE,\n (_, header, _body, tail) => `${header}\\n true${tail}`,\n );\n}\n\n/**\n * Extract the run: body of the build-site step from action content.\n * Returns null when the step is absent (hasStaticWebsites is false).\n * @param content - Action workflow content\n * @returns The captured run body string (includes leading newline), or null\n */\nfunction extractBuildSiteRunBody(content: string): string | null {\n const m = BUILD_SITE_RUN_RE.exec(content);\n return m ? (m[2] ?? null) : null;\n}\n\n/**\n * Replace the run: body of the build-site step in action content.\n * No-op when the step is absent.\n * @param content - Target action workflow content\n * @param body - Run body to inject (includes leading newline and indentation)\n * @returns Content with the run body replaced\n */\nfunction injectBuildSiteRunBody(content: string, body: string): string {\n return content.replace(\n BUILD_SITE_RUN_RE,\n (_, header, _placeholder, tail) => `${header}${body}${tail}`,\n );\n}\n\n/**\n * Decide how to reconcile a target with the on-disk file and lock state.\n * @param obj - Decision inputs\n * @param obj.existing - The matching lock target, if any\n * @param obj.fileExists - Whether the workflow file is present on disk\n * @param obj.currentContent - On-disk content when present\n * @param obj.force - Whether --force was passed\n * @param obj.normalize - Optional content normaliser applied before hashing\n * @returns The reconciliation action\n */\nexport function decideAction(obj: {\n existing: LockTarget | undefined;\n fileExists: boolean;\n currentContent: string | null;\n force: boolean;\n normalize?: (content: string) => string;\n}): Decision {\n const { existing, fileExists, currentContent, force, normalize } = obj;\n\n if (!existing) {\n if (!fileExists) return { action: \"create\" };\n if (force) return { action: \"regenerate\" };\n return {\n action: \"conflict\",\n reason:\n \"An unmanaged workflow file already exists at this path. \" +\n \"Delete it, or pass --force to bring it under SDK management (this overwrites it).\",\n };\n }\n\n // Lock has this target.\n if (!fileExists) return { action: \"restore\" };\n if (currentContent !== null) {\n const normalizedContent = normalize ? normalize(currentContent) : currentContent;\n if (hashContent(normalizedContent) === existing.contentHash) {\n return { action: \"regenerate\" };\n }\n }\n if (force) return { action: \"regenerate\" };\n return {\n action: \"conflict\",\n reason:\n \"This workflow file has been edited by hand since it was generated. \" +\n \"Re-run with --force to discard those edits and regenerate, or revert your changes.\",\n };\n}\n\n/**\n * Guard against two targets of different kinds colliding on the same file path.\n * @param obj - Conflict inputs\n * @param obj.lock - Existing lock file, or null\n * @param obj.kind - Target kind being generated\n * @param obj.workspaceName - Workspace name being generated\n * @param obj.file - Target file path\n */\nfunction assertNoKindCollision(obj: {\n lock: LockFile | null;\n kind: TargetKind;\n workspaceName: string;\n file: string;\n}): void {\n const { lock, kind, workspaceName, file } = obj;\n const collision = lock?.targets.find(\n (t) => t.file === file && !(t.kind === kind && t.workspaceName === workspaceName),\n );\n if (collision) {\n throw new Error(\n `A ${collision.kind} target already owns ${file}, which conflicts with this ${kind} target. ` +\n \"Pass a different name with --name to generate a separate workflow.\",\n );\n }\n}\n\n/**\n * Print next-step guidance after generating workflow files.\n * @param obj - Output context\n * @param obj.environment - Resolved GitHub Environment name for this target\n * @param obj.idInjected - Whether an app id was injected into the config\n */\nfunction printNextSteps(obj: { environment: string; idInjected: boolean }): void {\n const { environment, idInjected } = obj;\n\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`1. Set the machine-user credentials as secrets on the \"${environment}\" environment:`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID --env ${environment}`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET --env ${environment}`);\n\n logger.newline();\n logger.log(\n `2. Provision the workspace and set its id as the TAILOR_PLATFORM_WORKSPACE_ID variable ` +\n `on the \"${environment}\" environment:`,\n );\n logger.log(\" tailor workspace create # if it does not exist yet; copy the id\");\n logger.log(` gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env ${environment}`);\n\n logger.newline();\n logger.log(\"3. Commit the generated files:\");\n logger.log(\" - .github/workflows/tailor-*.yml\");\n logger.log(\" - .github/tailor.lock\");\n if (idInjected) {\n logger.log(\" - tailor.config.ts (app id was added)\");\n }\n}\n\n/**\n * Generate a deploy target workflow and reconcile it with the lock file.\n * @param options - Setup options\n */\nexport async function setupTarget(options: SetupTargetOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const resolved = await resolve(options);\n\n const lock = readLock(options.outputDir);\n const absFile = path.join(options.outputDir, resolved.file);\n\n assertNoKindCollision({\n lock,\n kind: resolved.kind,\n workspaceName: resolved.workspaceName,\n file: resolved.file,\n });\n\n const existing = findTarget(lock, resolved.kind, resolved.workspaceName);\n const fileExists = fs.existsSync(absFile);\n const currentContent = fileExists ? fs.readFileSync(absFile, \"utf-8\") : null;\n\n const normalize = resolved.kind === \"action\" ? normalizeActionContent : undefined;\n const decision = decideAction({\n existing,\n fileExists,\n currentContent,\n force: options.force,\n normalize,\n });\n\n if (decision.action === \"conflict\") {\n throw new Error(`${resolved.file}: ${decision.reason}`);\n }\n\n // Inject the app id only after reconciliation has ruled out conflicts, so\n // validation failures leave tailor.config.ts untouched (later filesystem\n // errors can still occur after injection).\n const idResult = await ensureConfigId(resolved.configPath);\n if (idResult === null) {\n logger.warn(\n \"Could not find a defineConfig() call to confirm an app id. \" +\n \"The CI deploy will fail unless your config resolves to one with an 'id'.\",\n );\n }\n const idInjected = idResult?.injected ?? false;\n\n // For action targets, preserve the user-editable build-site run body when\n // regenerating (hash matched after normalization) so that custom build commands\n // survive non-forced reruns without being silently overwritten.\n let contentToWrite = resolved.render.content;\n if (decision.action === \"regenerate\" && normalize && currentContent !== null) {\n const existingBody = extractBuildSiteRunBody(currentContent);\n if (existingBody !== null) {\n contentToWrite = injectBuildSiteRunBody(contentToWrite, existingBody);\n }\n }\n\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, contentToWrite, \"utf-8\");\n\n const newTarget: LockTarget = {\n kind: resolved.kind,\n workspaceName: resolved.workspaceName,\n file: resolved.file,\n templateVersion: TEMPLATE_VERSION,\n inputs: resolved.inputs,\n generatedIds: resolved.render.generatedIds,\n ejectedIds: existing?.ejectedIds ?? [],\n contentHash: hashContent(\n normalize ? normalize(resolved.render.content) : resolved.render.content,\n ),\n };\n\n // Replace in place to keep the lock diff minimal when re-running setup for\n // one of several targets.\n const targets = [...(lock?.targets ?? [])];\n const index = targets.findIndex(\n (t) => t.kind === newTarget.kind && t.workspaceName === newTarget.workspaceName,\n );\n if (index === -1) {\n targets.push(newTarget);\n } else {\n targets[index] = newTarget;\n }\n writeLock(options.outputDir, { version: LOCK_VERSION, targets });\n\n if (decision.action === \"restore\") {\n logger.success(`Regenerated ${styles.path(resolved.file)} (was missing on disk)`);\n } else if (decision.action === \"regenerate\") {\n logger.success(`Regenerated ${styles.path(resolved.file)}`);\n } else {\n logger.success(`Generated ${styles.path(resolved.file)}`);\n }\n\n if (resolved.kind === \"action\") {\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`The composite action has been generated at ${styles.path(resolved.file)}.`);\n logger.log(\n \"Use `tailor setup coordinate` to generate a coordinator workflow that orchestrates this action.\",\n );\n } else {\n printNextSteps({ environment: resolved.environment, idInjected });\n }\n}\n\n/**\n * Generate the coordinator workflow that orchestrates per-app composite actions.\n *\n * Unlike `setupTarget`, this function does not read a Tailor config. The coordinator\n * name is required via `--name`. App working directories are resolved from\n * the lock file entries created by `setup action`.\n * @param options - Coordinate setup options\n */\nexport async function setupCoordinate(options: CoordinateSetupOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { coordinatorName, coordinateKind, actions, force, outputDir } = options;\n validateWorkspaceName(coordinatorName);\n\n if (actions.length === 0) {\n throw new Error(\n \"At least one --action is required. \" +\n \"Run `tailor setup action --dir <app-dir>` for each app first.\",\n );\n }\n\n const environment = options.environment ?? coordinatorName;\n validateEnvironment(environment);\n\n let branch: string | null = null;\n let branchAutoDetected = false;\n if (coordinateKind === \"branch\") {\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(outputDir, options.gitRunner);\n validateBranch(branch);\n } else if (options.branch !== undefined) {\n validateBranch(options.branch);\n branch = options.branch;\n }\n\n const tagPattern = options.tagPattern ?? \"v*\";\n if (coordinateKind === \"tag\") {\n validateTagPattern(tagPattern);\n }\n\n const packageManager = detectPackageManager(outputDir);\n const lock = readLock(outputDir);\n\n if (!lock) {\n throw new Error(\n \".github/tailor.lock not found. \" +\n \"Run `tailor setup action --name <name>` for each app before running setup coordinate.\",\n );\n }\n\n const actionTargets = new Map(\n lock.targets.filter((t) => t.kind === \"action\").map((target) => [target.workspaceName, target]),\n );\n\n // Resolve each action name to its lock entry to get the working directory.\n const seenNames = new Set<string>();\n const usedGroupIds = new Set<string>();\n const actionGroups: CoordinateAppGroup[] = actions.map((actionGroup) => {\n const names = splitActionGroup(actionGroup);\n const apps: CoordinateApp[] = names.map((name) => {\n if (seenNames.has(name)) {\n throw new Error(\n `Duplicate --action \"${name}\". Each composite action can only appear once in a coordinator.`,\n );\n }\n seenNames.add(name);\n const entry = actionTargets.get(name);\n if (!entry) {\n throw new Error(\n `Action target \"${name}\" not found in .github/tailor.lock. ` +\n `Run \\`tailor setup action --name ${name}\\` first.`,\n );\n }\n if (names.length > 1 && entry.templateVersion < TEMPLATE_VERSION) {\n throw new Error(\n `Action target \"${name}\" was generated with an older setup template. ` +\n `Run \\`tailor setup action --name ${name} --force\\` before grouping it in setup coordinate.`,\n );\n }\n validateDir(entry.inputs.dir);\n return {\n name,\n dir: entry.inputs.dir,\n hasStaticWebsites: entry.inputs.hasStaticWebsites,\n };\n });\n return { id: uniqueGroupId(names, usedGroupIds), apps };\n });\n\n const render = renderCoordinateWorkflow({\n coordinatorName,\n kind: coordinateKind,\n actionGroups,\n branch: branch ?? undefined,\n tagPattern: coordinateKind === \"tag\" ? tagPattern : undefined,\n environment,\n packageManager,\n });\n\n const kindSuffix = coordinateKind === \"tag\" ? \"-tag\" : \"\";\n const file = `.github/workflows/tailor-coordinate-${coordinatorName}${kindSuffix}.yml`;\n const absFile = path.join(outputDir, file);\n\n assertNoKindCollision({ lock, kind: \"coordinate\", workspaceName: coordinatorName, file });\n\n const existing = findTarget(lock, \"coordinate\", coordinatorName);\n const fileExists = fs.existsSync(absFile);\n const currentContent = fileExists ? fs.readFileSync(absFile, \"utf-8\") : null;\n\n const decision = decideAction({ existing, fileExists, currentContent, force });\n if (decision.action === \"conflict\") {\n throw new Error(`${file}: ${decision.reason}`);\n }\n\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, render.content, \"utf-8\");\n\n // Generate the local tailor-setup action (user-owned: created once, never overwritten).\n const tailorSetupFile = \".github/actions/tailor-setup/action.yml\";\n const absTailorSetupFile = path.join(outputDir, tailorSetupFile);\n if (!fs.existsSync(absTailorSetupFile)) {\n fs.mkdirSync(path.dirname(absTailorSetupFile), { recursive: true });\n fs.writeFileSync(absTailorSetupFile, renderTailorSetupAction({ packageManager }), \"utf-8\");\n logger.success(`Generated ${styles.path(tailorSetupFile)}`);\n }\n\n const newTarget: LockTarget = {\n kind: \"coordinate\",\n workspaceName: coordinatorName,\n file,\n templateVersion: TEMPLATE_VERSION,\n inputs: {\n branch,\n branchAutoDetected:\n coordinateKind === \"branch\" ? branchAutoDetected : branch !== null ? false : undefined,\n tagPattern: coordinateKind === \"tag\" ? tagPattern : null,\n environment,\n dir: \".\",\n packageManager,\n actionDirs: actionGroups.flatMap((group) => group.apps.map((a) => a.dir)),\n },\n generatedIds: render.generatedIds,\n ejectedIds: existing?.ejectedIds ?? [],\n contentHash: hashContent(render.content),\n };\n\n const targets = [...lock.targets];\n const idx = targets.findIndex(\n (t) => t.kind === newTarget.kind && t.workspaceName === newTarget.workspaceName,\n );\n if (idx === -1) {\n targets.push(newTarget);\n } else {\n targets[idx] = newTarget;\n }\n writeLock(outputDir, { version: LOCK_VERSION, targets });\n\n if (decision.action === \"restore\") {\n logger.success(`Regenerated ${styles.path(file)} (was missing on disk)`);\n } else if (decision.action === \"regenerate\") {\n logger.success(`Regenerated ${styles.path(file)}`);\n } else {\n logger.success(`Generated ${styles.path(file)}`);\n }\n\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`1. Set the machine-user credentials as secrets on the \"${environment}\" environment:`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID --env ${environment}`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET --env ${environment}`);\n logger.newline();\n logger.log(\n `2. Provision the target workspace and set TAILOR_PLATFORM_WORKSPACE_ID on the \"${environment}\" environment:`,\n );\n logger.log(\" tailor workspace create # if it does not exist yet; copy the id\");\n logger.log(` gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env ${environment}`);\n logger.newline();\n logger.log(\"3. Commit the generated files:\");\n logger.log(` - ${file}`);\n logger.log(` - ${tailorSetupFile} (if newly created)`);\n logger.log(\" - .github/tailor.lock\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { getNamespacesWithMigrations } from \"../tailordb/migrate/config\";\nimport { normalizeActionContent } from \"./generate\";\nimport { detectDefaultBranch, type GitRunner } from \"./git\";\nimport { hashContent, type LockTarget, readLock } from \"./lock\";\nimport { TEMPLATE_VERSION } from \"./templates\";\n\n/**\n * Stable drift rule keys. These are part of the public contract: a future\n * `ignore` input on the workflow drift-check step suppresses findings by key.\n */\nexport type DriftRule =\n | \"missing-file\"\n | \"hand-edit\"\n | \"template-version\"\n | \"config-dir\"\n | \"default-branch\"\n | \"erd-namespaces\"\n | \"migration-drift\"\n | \"seed-validate\"\n | \"static-websites\";\n\nexport type DriftFinding = {\n /** Human label for the target: `<kind> <workspaceName>`. */\n target: string;\n rule: DriftRule;\n message: string;\n};\n\n/** Current repository/config state for one target, gathered by the caller. */\nexport type TargetState = {\n fileExists: boolean;\n /** Hash of the on-disk workflow file, or null when it is missing. */\n currentHash: string | null;\n /** Whether tailor.config.ts exists under the target's recorded dir. */\n configExists: boolean;\n /** Detected repository default branch, or null when it cannot be determined. */\n defaultBranch: string | null;\n /** The template version this SDK build generates. */\n templateVersion: number;\n /** Current owned TailorDB namespaces for ERD preview checks, or null when unavailable. */\n erdNamespaces: string[] | null;\n /** Whether the current config has TailorDB namespaces with migrations (branch/tag only). */\n hasMigrations?: boolean;\n /** Whether the current config uses the seed plugin (branch/tag only). */\n hasSeeds?: boolean;\n /** Whether the current config has staticWebsites configured (action only). */\n hasStaticWebsites?: boolean;\n};\n\n/**\n * Compute drift findings for one target by comparing its recorded lock state\n * against the current repository/config state.\n * @param target - The lock target being audited\n * @param state - Current repository/config state for this target\n * @returns Drift findings (empty when the target is in sync)\n */\nexport function findTargetDrift(target: LockTarget, state: TargetState): DriftFinding[] {\n const id = `${target.kind} ${target.workspaceName}`;\n const findings: DriftFinding[] = [];\n\n if (!state.fileExists) {\n findings.push({\n target: id,\n rule: \"missing-file\",\n message: `${target.file} is missing or unreadable. Re-run setup to restore it.`,\n });\n } else if (state.currentHash !== null && state.currentHash !== target.contentHash) {\n findings.push({\n target: id,\n rule: \"hand-edit\",\n message:\n `${target.file} was edited by hand since it was generated. Re-run setup with ` +\n \"--force to regenerate, or keep customizations in your own jobs/steps.\",\n });\n }\n\n if (target.templateVersion < state.templateVersion) {\n findings.push({\n target: id,\n rule: \"template-version\",\n message:\n `A newer workflow template is available (generated with v${String(target.templateVersion)}, ` +\n `current v${String(state.templateVersion)}). Re-run setup to update.`,\n });\n }\n\n if (!state.configExists) {\n findings.push({\n target: id,\n rule: \"config-dir\",\n message:\n `tailor.config.ts not found under \"${target.inputs.dir}\". The app directory may have ` +\n \"moved; re-run setup with the correct --dir.\",\n });\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"coordinate\" || target.kind === \"preview\") &&\n target.inputs.branchAutoDetected !== false &&\n state.defaultBranch !== null &&\n target.inputs.branch !== null &&\n target.inputs.branch !== state.defaultBranch\n ) {\n findings.push({\n target: id,\n rule: \"default-branch\",\n message:\n `The workflow triggers on \"${target.inputs.branch}\" but the repository default branch ` +\n `is now \"${state.defaultBranch}\". If this is intentional, ignore this; otherwise re-run ` +\n \"setup so the trigger matches the default branch.\",\n });\n }\n\n if (target.kind === \"branch\" && target.inputs.erdPreview && state.configExists) {\n const recorded = [...(target.inputs.erdNamespaces ?? [])].toSorted((a, b) =>\n a.localeCompare(b),\n );\n const current = state.erdNamespaces?.toSorted((a, b) => a.localeCompare(b)) ?? null;\n if (\n current === null ||\n recorded.length !== current.length ||\n recorded.some((namespace, index) => namespace !== current[index])\n ) {\n findings.push({\n target: id,\n rule: \"erd-namespaces\",\n message:\n \"TailorDB namespaces for ERD preview changed. Re-run setup so the ERD preview matrix is regenerated.\",\n });\n }\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.migrationDriftCheck === false &&\n state.hasMigrations === true\n ) {\n findings.push({\n target: id,\n rule: \"migration-drift\",\n message:\n \"TailorDB namespaces with migrations were added to the config. \" +\n \"Re-run setup so the tailor-migration-drift-check step is included in the plan job.\",\n });\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.seedValidate === false &&\n state.hasSeeds === true\n ) {\n findings.push({\n target: id,\n rule: \"seed-validate\",\n message:\n \"Seed plugin detected in the current config. \" +\n \"Re-run setup so the tailor-seed-validate step is included in the plan job.\",\n });\n }\n\n if (\n target.kind === \"action\" &&\n target.inputs.hasStaticWebsites === false &&\n state.hasStaticWebsites === true\n ) {\n findings.push({\n target: id,\n rule: \"static-websites\",\n message:\n \"Static websites were added to the config. \" +\n \"Re-run setup so the build-site slot is included in the composite action.\",\n });\n }\n\n return findings;\n}\n\nfunction detectDefaultBranchSafe(cwd: string, run: GitRunner | undefined): string | null {\n try {\n return detectDefaultBranch(cwd, run);\n } catch {\n return null;\n }\n}\n\nfunction escapesRoot(rel: string): boolean {\n return (\n path.isAbsolute(rel) || rel === \"..\" || rel.startsWith(`..${path.sep}`) || rel.startsWith(\"../\")\n );\n}\n\n// The lock is machine-owned, but a corrupted or hand-edited lock could carry an\n// absolute, `..`-traversing, or symlinked path. Reject lexical escapes and, when\n// the path exists, resolve symlinks and reject anything whose real location is\n// outside the repo root, so the audit never reads outside it.\nexport function resolveWithinRoot(outputDir: string, relPath: string): string | null {\n if (path.isAbsolute(relPath)) return null;\n const abs = path.join(outputDir, relPath);\n if (escapesRoot(path.relative(outputDir, abs))) return null;\n try {\n if (escapesRoot(path.relative(fs.realpathSync(outputDir), fs.realpathSync(abs)))) return null;\n } catch {\n // The path does not exist yet; the lexical check above is sufficient and a\n // missing file is reported as drift downstream.\n }\n return abs;\n}\n\n// Treat any read failure (missing file, EISDIR, TOCTOU race, permissions) as an\n// absent file so the audit reports drift instead of crashing.\nfunction readHash(absFile: string, normalize?: (content: string) => string): string | null {\n try {\n const content = fs.readFileSync(absFile, \"utf-8\");\n return hashContent(normalize ? normalize(content) : content);\n } catch {\n return null;\n }\n}\n\nexport type CheckGitHubOptions = {\n /** Repository root where `.github` lives. */\n outputDir: string;\n /**\n * When true, run in CI mode: skip checks that are handled at runtime by\n * the deployed GitHub Actions (e.g. TAILOR_PLATFORM_WORKSPACE_ID presence).\n */\n ci?: boolean;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n /** Injectable config-existence probe, for testing. */\n configExistsAt?: (configPath: string) => boolean;\n /** Injectable TailorDB namespace loader, for testing. Defaults to loading the config. */\n loadErdNamespaces?: (configPath: string) => Promise<string[]> | string[];\n /** Injectable migration detector, for testing. Defaults to loading the config. */\n loadHasMigrations?: (configPath: string) => Promise<boolean> | boolean;\n /** Injectable seed plugin detector, for testing. Defaults to loading the config. */\n loadHasSeeds?: (configPath: string) => Promise<boolean> | boolean;\n /** Injectable static website detector, for testing. Defaults to loading the config. */\n loadHasStaticWebsites?: (configPath: string) => Promise<boolean> | boolean;\n};\n\nasync function defaultLoadErdNamespaces(configPath: string): Promise<string[]> {\n const { config } = await loadConfig(configPath);\n return extractOwnedNamespaces(config);\n}\n\nasync function defaultLoadHasMigrations(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return getNamespacesWithMigrations(config, path.dirname(configPath)).length > 0;\n}\n\nasync function defaultLoadHasSeeds(configPath: string): Promise<boolean> {\n const { plugins } = await loadConfig(configPath);\n return plugins.some((p) => p.id === \"@tailor-platform/seed\");\n}\n\nasync function defaultLoadHasStaticWebsites(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return (config.staticWebsites?.length ?? 0) > 0;\n}\n\n/**\n * Audit the generated workflows for drift against the current config/repo\n * state. Read-only: never writes files, the lock, or the config.\n *\n * Throws when drift is found (so it composes like the other `:check`\n * commands). The workflow drift-check step layers advisory behaviour on top\n * (per-rule ignore / continue-on-error); the CLI itself reports via exit code.\n * @param options - Check options\n */\nexport async function checkGitHub(options: CheckGitHubOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { outputDir } = options;\n const lock = readLock(outputDir);\n if (!lock || lock.targets.length === 0) {\n throw new Error(\n \"No managed workflows found (.github/tailor.lock is missing or empty). \" +\n \"Run `tailor setup branch` (or another setup subcommand) first.\",\n );\n }\n\n // In local (non-CI) mode, check that TAILOR_PLATFORM_WORKSPACE_ID is set for\n // targets that directly read vars.TAILOR_PLATFORM_WORKSPACE_ID: branch, tag,\n // and coordinate (coordinators pass it into each per-app deploy step).\n // Action targets (composite actions) receive workspace-id as a caller input and\n // never read vars.* themselves. Preview targets create per-PR workspaces and\n // don't reference TAILOR_PLATFORM_WORKSPACE_ID either.\n // In CI the plan/deploy actions handle this at runtime.\n if (!options.ci) {\n const needsWorkspaceId = lock.targets.some(\n (t) => t.kind === \"branch\" || t.kind === \"tag\" || t.kind === \"coordinate\",\n );\n if (needsWorkspaceId && !process.env[\"TAILOR_PLATFORM_WORKSPACE_ID\"]) {\n throw new Error(\n \"TAILOR_PLATFORM_WORKSPACE_ID is not set. \" +\n \"Provision the workspace and set the variable:\\n\" +\n \" tailor workspace create # if it does not exist yet; copy the id\\n\" +\n \" gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env <environment>\",\n );\n }\n }\n\n const slackToken = Boolean(process.env[\"TAILOR_SLACK_BOT_TOKEN\"]);\n const slackChannelId = Boolean(process.env[\"TAILOR_SLACK_CHANNEL_ID\"]);\n if (slackToken !== slackChannelId) {\n throw new Error(\n `Slack is partially configured: ` +\n `${slackToken ? \"TAILOR_SLACK_BOT_TOKEN is set\" : \"TAILOR_SLACK_CHANNEL_ID is set\"} but not both. ` +\n \"TAILOR_SLACK_BOT_TOKEN (secret) and TAILOR_SLACK_CHANNEL_ID (variable) must be set together, \" +\n \"or neither should be set.\",\n );\n }\n\n const exists = options.configExistsAt ?? ((p: string) => fs.existsSync(p));\n const defaultBranch = detectDefaultBranchSafe(outputDir, options.gitRunner);\n const loadErdNamespaces = options.loadErdNamespaces ?? defaultLoadErdNamespaces;\n const loadHasMigrations = options.loadHasMigrations ?? defaultLoadHasMigrations;\n const loadHasSeeds = options.loadHasSeeds ?? defaultLoadHasSeeds;\n const loadHasStaticWebsites = options.loadHasStaticWebsites ?? defaultLoadHasStaticWebsites;\n\n const findings: DriftFinding[] = [];\n for (const target of lock.targets) {\n const absFile = resolveWithinRoot(outputDir, target.file);\n const currentHash =\n absFile === null\n ? null\n : readHash(absFile, target.kind === \"action\" ? normalizeActionContent : undefined);\n // Coordinator targets are config-less; skip the probe so config-dir drift is never emitted.\n const configAbs =\n target.kind === \"coordinate\"\n ? null\n : resolveWithinRoot(outputDir, path.join(target.inputs.dir, \"tailor.config.ts\"));\n const configExists = target.kind === \"coordinate\" || (configAbs !== null && exists(configAbs));\n const erdNamespaces =\n target.kind === \"branch\" && target.inputs.erdPreview && configAbs !== null && configExists\n ? await loadErdNamespaces(configAbs)\n : null;\n const hasMigrations =\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.migrationDriftCheck !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasMigrations(configAbs)\n : undefined;\n const hasSeeds =\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.seedValidate !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasSeeds(configAbs)\n : undefined;\n const hasStaticWebsites =\n target.kind === \"action\" &&\n target.inputs.hasStaticWebsites !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasStaticWebsites(configAbs)\n : undefined;\n findings.push(\n ...findTargetDrift(target, {\n fileExists: currentHash !== null,\n currentHash,\n configExists,\n defaultBranch,\n templateVersion: TEMPLATE_VERSION,\n erdNamespaces,\n hasMigrations,\n hasSeeds,\n hasStaticWebsites,\n }),\n );\n }\n\n const count = lock.targets.length;\n if (findings.length === 0) {\n logger.success(`No drift detected across ${String(count)} target(s).`);\n return;\n }\n\n for (const finding of findings) {\n logger.warn(`[${finding.target}] ${finding.message} (ignore key: ${finding.rule})`);\n }\n throw new Error(\n `Detected ${String(findings.length)} drift finding(s) across ${String(count)} target(s). ` +\n \"Re-run `tailor setup` to regenerate, or address each finding above.\",\n );\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { resolveWithinRoot } from \"./check\";\nimport { LOCK_VERSION, readLock, writeLock, type LockTarget } from \"./lock\";\n\nexport type DeleteOptions = {\n /** Repo-relative paths to managed workflow/action files, as printed by `setup <target>`. */\n files: string[];\n /** Skip the confirmation prompt. */\n yes: boolean;\n outputDir: string;\n};\n\n// Mirrors the --dir normalization in generate.ts's resolve(): POSIX separators,\n// collapsed duplicate slashes, no leading \"./\" or trailing \"/\", so a path typed\n// with either style still matches the posix-normalized `file` recorded in the lock.\nfunction normalizeRelPath(input: string): string {\n return input\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/{2,}/g, \"/\")\n .replace(/^\\.\\//, \"\")\n .replace(/\\/$/, \"\");\n}\n\ntype Match = { relPath: string; absPath: string; target: LockTarget };\n\nfunction targetKey(target: LockTarget): string {\n return `${target.kind}:${target.workspaceName}`;\n}\n\nfunction resolveMatch(outputDir: string, targets: readonly LockTarget[], input: string): Match {\n const relPath = normalizeRelPath(input);\n const absPath = resolveWithinRoot(outputDir, relPath);\n if (absPath === null) {\n throw new Error(`\"${input}\" must be a path inside the repository.`);\n }\n const target = targets.find((t) => t.file === relPath);\n if (!target) {\n throw new Error(\n `\"${relPath}\" is not a managed workflow/action file (not recorded in .github/tailor.lock). ` +\n \"Only files generated by `tailor setup` can be deleted with this command.\",\n );\n }\n return { relPath, absPath, target };\n}\n\n// Skips the warning when the referencing coordinator is also part of this\n// delete call, regardless of the order the files were passed in.\nfunction warnCoordinatorReferences(\n allTargets: readonly LockTarget[],\n deletedKeys: ReadonlySet<string>,\n match: Match,\n): void {\n if (match.target.kind !== \"action\") return;\n for (const coordinator of allTargets) {\n if (\n coordinator.kind === \"coordinate\" &&\n coordinator.inputs.actionDirs?.includes(match.target.inputs.dir) &&\n !deletedKeys.has(targetKey(coordinator))\n ) {\n logger.warn(\n `Coordinator \"${coordinator.workspaceName}\" still references this action's directory ` +\n `(${match.target.inputs.dir}). Remove \\`${match.target.workspaceName}\\` from the ` +\n `relevant \\`--action\\` value and re-run \\`tailor setup coordinate\\` to update it.`,\n );\n }\n }\n}\n\n/**\n * Delete managed workflow/action files and their `.github/tailor.lock` entries.\n *\n * Refuses to touch files that are not recorded in the lock, so it never\n * deletes hand-written workflows or the user-owned tailor-setup action.\n * @param options - Delete options\n */\nexport async function setupDelete(options: DeleteOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { outputDir, yes } = options;\n const lock = readLock(outputDir);\n if (!lock || lock.targets.length === 0) {\n throw new Error(\n \"No managed workflows found (.github/tailor.lock is missing or empty). \" +\n \"Run `tailor setup branch` (or another setup subcommand) first.\",\n );\n }\n\n const relPaths = [...new Set(options.files.map(normalizeRelPath))];\n const matches = relPaths.map((relPath) => resolveMatch(outputDir, lock.targets, relPath));\n\n const deletedKeys = new Set(matches.map((m) => targetKey(m.target)));\n for (const match of matches) {\n warnCoordinatorReferences(lock.targets, deletedKeys, match);\n }\n\n if (!yes) {\n const list = matches.map((m) => m.relPath).join(\"\\n \");\n const confirmed = await prompt.confirm({\n message:\n `This will delete the following file(s) and their .github/tailor.lock entries:\\n ${list}\\n` +\n \"Continue?\",\n default: false,\n });\n if (!confirmed) {\n logger.info(\"Delete cancelled.\");\n return;\n }\n }\n\n const remaining = [...lock.targets];\n try {\n for (const { relPath, absPath, target } of matches) {\n fs.rmSync(absPath, { force: true });\n if (target.kind === \"action\") {\n const dir = path.dirname(absPath);\n if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {\n fs.rmdirSync(dir);\n }\n }\n const index = remaining.findIndex((t) => targetKey(t) === targetKey(target));\n if (index !== -1) remaining.splice(index, 1);\n logger.success(`Deleted ${styles.path(relPath)} (${target.kind} ${target.workspaceName})`);\n }\n } finally {\n if (remaining.length !== lock.targets.length) {\n writeLock(outputDir, { version: LOCK_VERSION, targets: remaining });\n }\n }\n}\n","import { arg, defineCommand } from \"politty\";\nimport { z } from \"zod\";\nimport { confirmationArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { checkGitHub } from \"./check\";\nimport { setupDelete } from \"./delete\";\nimport { setupCoordinate, setupTarget } from \"./generate\";\n\nconst checkCommand = defineAppCommand({\n name: \"check\",\n description: \"Audit generated workflows for drift against the current config/repo (read-only).\",\n args: z.strictObject({\n ci: arg(z.boolean().default(false), {\n description:\n \"Run in CI mode: skip checks that are handled by the runtime \" +\n \"(e.g. TAILOR_PLATFORM_WORKSPACE_ID).\",\n }),\n }),\n run: async (args) => {\n await checkGitHub({ outputDir: process.cwd(), ci: args.ci });\n },\n});\n\nconst coordinateCommand = defineAppCommand({\n name: \"coordinate\",\n description:\n \"Generate a coordinator workflow that orchestrates multiple --action-generated composite actions.\",\n args: z.strictObject({\n name: arg(z.string().min(1), {\n alias: \"n\",\n description: \"Coordinator name (used in the generated workflow file name and job names)\",\n }),\n action: arg(z.array(z.string().min(1)).min(1), {\n description:\n \"Composite action to include. Repeat for separate deploy steps, or use commas to deploy actions as one multi-config group. tailor- prefix optional.\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Branch target: deploy trigger branch (defaults to the detected default branch)\",\n }),\n tag: arg(z.boolean().default(false), {\n description: \"Generate a tag target coordinator\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits and regenerate\",\n }),\n }),\n run: async (args) => {\n const coordinateKind = args.tag ? \"tag\" : \"branch\";\n await setupCoordinate({\n coordinatorName: args.name,\n coordinateKind,\n actions: args.action,\n branch: args.branch,\n environment: args.environment,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst actionCommand = defineAppCommand({\n name: \"action\",\n description:\n \"Generate a per-app composite action for use with setup coordinate (monorepo multi-app deploys).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment (defaults to the workspace name)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"action\",\n workspaceName: args.name,\n dir: args.dir,\n environment: args.environment,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst branchCommand = defineAppCommand({\n name: \"branch\",\n description: \"Generate a branch-target deploy workflow (push to branch triggers deploy).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Deploy trigger branch (defaults to the detected default branch)\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs (defaults to the workspace name)\",\n }),\n \"erd-preview\": arg(z.boolean().default(false), {\n description: \"Add PR ERD viewer artifacts with current/diff previews for TailorDB namespaces\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"branch\",\n workspaceName: args.name,\n branch: args.branch,\n environment: args.environment,\n erdPreview: args[\"erd-preview\"],\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst tagCommand = defineAppCommand({\n name: \"tag\",\n description: \"Generate a tag-target deploy workflow (tag push triggers deploy).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n \"tag-pattern\": arg(z.string().min(1).default(\"v*\"), {\n description: \"Tag glob to match (defaults to v*)\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Tag-reachability guard branch (no guard when omitted)\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs (defaults to the workspace name)\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"tag\",\n workspaceName: args.name,\n tagPattern: args[\"tag-pattern\"],\n branch: args.branch,\n environment: args.environment,\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst previewCommand = defineAppCommand({\n name: \"preview\",\n description: \"Generate a preview workflow (PR open/sync triggers deploy to a per-PR workspace).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Branch to filter PRs by (defaults to the detected default branch)\",\n }),\n region: arg(z.string().min(1), {\n description: \"Workspace region for preview workspace creation (e.g. us-west). Required.\",\n }),\n \"require-preview-label\": arg(z.boolean().default(false), {\n description: \"Deploy preview only for PRs labeled `tailor:preview` instead of all PRs.\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the preview jobs (defaults to the workspace name)\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"preview\",\n workspaceName: args.name,\n branch: args.branch,\n region: args.region,\n requirePreviewLabel: args[\"require-preview-label\"],\n environment: args.environment,\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete managed workflow/action file(s) and their .github/tailor.lock entries.\",\n args: z.strictObject({\n ...confirmationArgs,\n files: arg(z.string().array().min(1), {\n positional: true,\n description:\n \"Workflow/action file(s) to delete, as generated under .github/workflows or .github/actions\",\n }),\n }),\n run: async (args) => {\n await setupDelete({ files: args.files, yes: args.yes, outputDir: process.cwd() });\n },\n});\n\nexport const setupCommand = defineCommand({\n name: \"setup\",\n description: \"Generate CI deploy workflows for your project. (beta)\",\n subCommands: {\n branch: branchCommand,\n tag: tagCommand,\n preview: previewCommand,\n action: actionCommand,\n coordinate: coordinateCommand,\n check: checkCommand,\n delete: deleteCommand,\n },\n});\n","import { CustomDomainStatus } from \"@tailor-platform/tailor-proto/staticwebsite_resource_pb\";\n\nexport const statusLabels: Record<CustomDomainStatus, string> = {\n [CustomDomainStatus.UNSPECIFIED]: \"unspecified\",\n [CustomDomainStatus.PENDING]: \"pending\",\n [CustomDomainStatus.VERIFYING]: \"verifying\",\n [CustomDomainStatus.CERT_ISSUED]: \"cert_issued\",\n [CustomDomainStatus.ACTIVE]: \"active\",\n [CustomDomainStatus.FAILED]: \"failed\",\n};\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { statusLabels } from \"./status\";\n\nexport const domainGetCommand = defineAppCommand({\n name: \"get\",\n description: \"Get details of a custom domain.\",\n args: z.strictObject({\n ...workspaceArgs,\n domain: arg(z.string(), {\n positional: true,\n description: \"Custom domain name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const notFoundErrorMessage = `Custom domain \"${args.domain}\" not found.`;\n\n try {\n const { customDomain } = await client.getCustomDomain({\n workspaceId,\n domain: args.domain,\n });\n\n if (!customDomain) {\n throw new Error(notFoundErrorMessage);\n }\n\n const info = {\n domain: customDomain.domain,\n // platform may return enum values newer than this SDK\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n status: statusLabels[customDomain.status] ?? \"unknown\",\n trafficCnameTarget: customDomain.trafficCnameTarget,\n certificateCnameTarget: customDomain.certificateCnameTarget,\n errorMessage: customDomain.errorMessage || undefined,\n };\n\n logger.out(info);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(notFoundErrorMessage, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { statusLabels } from \"./status\";\n\nexport const domainListCommand = defineAppCommand({\n name: \"list\",\n description: \"List custom domains for a static website.\",\n args: z.strictObject({\n ...workspaceArgs,\n name: arg(z.string(), {\n positional: true,\n description: \"Static website name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n const { customDomains } = await client.listCustomDomains({\n workspaceId,\n staticWebsiteName: args.name,\n });\n\n if (customDomains.length === 0) {\n logger.info(\"No custom domains found.\");\n return;\n }\n\n const formatted = customDomains.map((d) => ({\n domain: d.domain,\n // platform may return enum values newer than this SDK\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n status: statusLabels[d.status] ?? \"unknown\",\n trafficCnameTarget: d.trafficCnameTarget,\n certificateCnameTarget: d.certificateCnameTarget,\n }));\n\n logger.out(formatted);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Static website \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { defineCommand } from \"politty\";\nimport { domainGetCommand } from \"./get\";\nimport { domainListCommand } from \"./list\";\n\nexport const domainCommand = defineCommand({\n name: \"domain\",\n description: \"Manage custom domains for static websites.\",\n subCommands: {\n list: domainListCommand,\n get: domainGetCommand,\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const getCommand = defineAppCommand({\n name: \"get\",\n description: \"Get details of a specific static website.\",\n args: z.strictObject({\n ...workspaceArgs,\n name: arg(z.string(), {\n positional: true,\n description: \"Static website name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const notFoundErrorMessage = `Static website \"${args.name}\" not found.`;\n\n try {\n const { staticwebsite } = await client.getStaticWebsite({\n workspaceId,\n name: args.name,\n });\n\n if (!staticwebsite) {\n throw new Error(notFoundErrorMessage);\n }\n\n const info = {\n workspaceId,\n name: staticwebsite.name,\n description: staticwebsite.description,\n url: staticwebsite.url,\n allowedIpAddresses: args.json\n ? staticwebsite.allowedIpAddresses\n : staticwebsite.allowedIpAddresses.join(\"\\n\"),\n };\n\n logger.out(info);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(notFoundErrorMessage, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport interface StaticWebsiteInfo {\n workspaceId: string;\n name: string;\n description: string;\n url: string;\n allowedIpAddresses: string[];\n}\n\ntype StaticWebsiteListOptions = {\n workspaceId?: string;\n profile?: string;\n order?: Order;\n limit?: number;\n};\n\n/**\n * List static websites in the workspace.\n * @param options - Static website listing options\n * @returns List of static websites\n */\nasync function listStaticWebsites(\n options?: StaticWebsiteListOptions,\n): Promise<StaticWebsiteInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options?.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options?.workspaceId,\n profile: options?.profile,\n });\n\n const pageDirection = toPageDirection(options?.order);\n const websites = await fetchPaged(\n async (pageToken, pageSize) => {\n const { staticwebsites, nextPageToken } = await client.listStaticWebsites({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [staticwebsites, nextPageToken];\n },\n { limit: options?.limit },\n );\n\n return websites.map((site) => ({\n workspaceId,\n name: site.name,\n description: site.description,\n url: site.url,\n allowedIpAddresses: site.allowedIpAddresses,\n }));\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all static websites in a workspace.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const websites = await listStaticWebsites({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n order: args.order,\n limit: args.limit,\n });\n\n const formatted = jsonOutput\n ? websites\n : websites.map(({ allowedIpAddresses, ...rest }) => {\n if (allowedIpAddresses.length === 0) {\n return {\n ...rest,\n allowedIpAddresses: \"No allowed IP addresses\",\n };\n }\n\n const count = allowedIpAddresses.length;\n const label = count === 1 ? \"1 IP address\" : `${count} IP addresses`;\n\n return {\n ...rest,\n allowedIpAddresses: label,\n };\n });\n\n logger.out(formatted);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { deployCommand } from \"./deploy\";\nimport { domainCommand } from \"./domain\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\n\nexport const staticwebsiteCommand = defineCommand({\n name: \"staticwebsite\",\n description: \"Manage static websites in your workspace.\",\n subCommands: {\n deploy: deployCommand,\n domain: domainCommand,\n list: listCommand,\n get: getCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","/**\n * Script command for TailorDB migrations\n *\n * Adds a `migrate.ts` (and supporting `db.ts`) template to an existing\n * migration directory. Useful for warning-tier changes where users may\n * want to write a custom data migration even though the change does not\n * automatically require one.\n */\n\nimport * as fs from \"node:fs\";\nimport * as fsPromises from \"node:fs/promises\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { configArg } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { getConfiguredEditorCommand, openInConfiguredEditor } from \"#/cli/shared/editor\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { getNamespacesWithMigrations, type NamespaceWithMigrations } from \"./config\";\nimport { writeDbTypesFile } from \"./db-types-generator\";\nimport { parseMigrationNumberArg } from \"./migration-number\";\nimport {\n formatMigrationNumber,\n getMigrationFilePath,\n loadDiff,\n reconstructSnapshotFromMigrations,\n INITIAL_SCHEMA_NUMBER,\n} from \"./snapshot\";\nimport { generateMigrationScript } from \"./template-generator\";\nimport type { ScriptSkippedInfo } from \"./diff-calculator\";\n\nexport interface ScriptOptions {\n configPath?: string;\n number: string;\n namespace?: string;\n noScript?: boolean;\n reason?: string;\n}\n\nexport interface MarkScriptSkippedOptions {\n migrationsDir: string;\n migrationNumber: number;\n reason: string;\n}\n\n/**\n * Record in diff.json that a migration requiring a script intentionally has none.\n * @param {MarkScriptSkippedOptions} options - Target migration and skip reason\n * @returns {ScriptSkippedInfo} The recorded acknowledgment\n */\nexport function markMigrationScriptSkipped(options: MarkScriptSkippedOptions): ScriptSkippedInfo {\n const { migrationsDir, migrationNumber, reason } = options;\n const label = formatMigrationNumber(migrationNumber);\n const normalizedReason = reason.trim();\n if (!normalizedReason) {\n throw new Error(\"Migration script skip reason must not be empty.\");\n }\n\n const diffPath = getMigrationFilePath(migrationsDir, migrationNumber, \"diff\");\n if (!fs.existsSync(diffPath)) {\n throw new Error(`Migration ${label} not found in ${migrationsDir}. Expected ${diffPath}.`);\n }\n\n const diff = loadDiff(diffPath);\n if (!diff.requiresMigrationScript) {\n throw new Error(`Migration ${label} does not require a migration script; nothing to skip.`);\n }\n if (diff.scriptSkipped) {\n throw new Error(\n `Migration ${label} already has a script skip recorded ` +\n `(${diff.scriptSkipped.acknowledgedAt}: ${diff.scriptSkipped.reason}).`,\n );\n }\n\n const migratePath = getMigrationFilePath(migrationsDir, migrationNumber, \"migrate\");\n if (fs.existsSync(migratePath)) {\n throw new Error(\n `Migration script exists at ${migratePath}. ` +\n `Delete migrate.ts first if this migration should run without a script.`,\n );\n }\n\n const scriptSkipped: ScriptSkippedInfo = {\n reason: normalizedReason,\n acknowledgedAt: new Date().toISOString(),\n };\n\n // Edit the raw JSON so keys unknown to this SDK version survive the rewrite.\n const raw = JSON.parse(fs.readFileSync(diffPath, \"utf-8\")) as Record<string, unknown>;\n raw.scriptSkipped = scriptSkipped;\n fs.writeFileSync(diffPath, JSON.stringify(raw, null, 2));\n\n return scriptSkipped;\n}\n\n/**\n * Remove a script skip acknowledgment after a real migration script is created.\n * @param diffPath - Migration diff file to update\n */\nexport function clearMigrationScriptSkipped(diffPath: string): void {\n const raw = JSON.parse(fs.readFileSync(diffPath, \"utf-8\")) as Record<string, unknown>;\n if (!Object.hasOwn(raw, \"scriptSkipped\")) return;\n delete raw.scriptSkipped;\n fs.writeFileSync(diffPath, JSON.stringify(raw, null, 2));\n}\n\n/**\n * Add a migrate.ts template to an existing migration directory.\n * @param {ScriptOptions} options - Command options\n */\nasync function script(options: ScriptOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const migrationNumber = parseMigrationNumberArg(options.number);\n\n if (migrationNumber === INITIAL_SCHEMA_NUMBER) {\n throw new Error(\n `Migration ${options.number} is the initial schema snapshot and cannot have a migration script.`,\n );\n }\n\n const { config } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n if (namespacesWithMigrations.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found\");\n }\n\n const targetNamespace = resolveTargetNamespace(namespacesWithMigrations, options.namespace);\n const { migrationsDir } = assertDefined(\n namespacesWithMigrations.find((ns) => ns.namespace === targetNamespace),\n \"namespace with migrations not found\",\n );\n\n if (options.noScript) {\n const reason = options.reason?.trim();\n if (!reason) {\n throw new Error(\"--reason is required with --no-script.\");\n }\n const scriptSkipped = markMigrationScriptSkipped({\n migrationsDir,\n migrationNumber,\n reason,\n });\n logger.success(\n `Recorded that migration ${styles.bold(options.number)} in namespace ${styles.bold(targetNamespace)} intentionally has no migration script`,\n );\n logger.info(` Reason: ${scriptSkipped.reason}`);\n logger.info(` Diff file: ${getMigrationFilePath(migrationsDir, migrationNumber, \"diff\")}`);\n return;\n }\n if (options.reason !== undefined) {\n throw new Error(\"--reason can only be used together with --no-script.\");\n }\n\n const diffPath = getMigrationFilePath(migrationsDir, migrationNumber, \"diff\");\n if (!fs.existsSync(diffPath)) {\n throw new Error(\n `Migration ${options.number} not found in ${migrationsDir}. Expected ${diffPath}.`,\n );\n }\n\n const migratePath = getMigrationFilePath(migrationsDir, migrationNumber, \"migrate\");\n if (fs.existsSync(migratePath)) {\n throw new Error(`Migration script already exists at ${migratePath}.`);\n }\n\n const diff = loadDiff(diffPath);\n\n // Reconstruct the schema state immediately before this migration so that\n // db.ts has Kysely types for the previous shape of the data.\n const previousSnapshot = reconstructSnapshotFromMigrations(migrationsDir, migrationNumber - 1);\n if (!previousSnapshot) {\n throw new Error(\n `Could not reconstruct previous schema for migration ${options.number}. Make sure migration ${INITIAL_SCHEMA_NUMBER} exists.`,\n );\n }\n\n const scriptContent = generateMigrationScript(diff);\n await fsPromises.writeFile(migratePath, scriptContent);\n await writeDbTypesFile(previousSnapshot, migrationsDir, migrationNumber, diff);\n clearMigrationScriptSkipped(diffPath);\n\n logger.success(\n `Added migration script for migration ${styles.bold(options.number)} in namespace ${styles.bold(targetNamespace)}`,\n );\n logger.info(` Migration script: ${migratePath}`);\n logger.info(` DB types: ${getMigrationFilePath(migrationsDir, migrationNumber, \"db\")}`);\n\n logger.newline();\n logger.log(\"Edit the script to implement your data migration logic.\");\n logger.log(\"It will be executed by 'tailor deploy' between Pre and Post phases.\");\n\n const editor = getConfiguredEditorCommand();\n if (!editor) return;\n\n logger.newline();\n logger.info(`Opening ${path.basename(migratePath)} in ${editor}...`);\n try {\n await openInConfiguredEditor(migratePath);\n } catch {\n return;\n }\n}\n\nfunction resolveTargetNamespace(\n namespacesWithMigrations: NamespaceWithMigrations[],\n requested?: string,\n): string {\n if (requested) {\n if (!namespacesWithMigrations.some((ns) => ns.namespace === requested)) {\n throw new Error(`Namespace \"${requested}\" not found or does not have migrations configured`);\n }\n return requested;\n }\n if (namespacesWithMigrations.length === 1) {\n const [ns] = namespacesWithMigrations;\n return assertDefined(ns, \"namespace with migrations missing\").namespace;\n }\n throw new Error(\n `Multiple TailorDB services found. Please specify namespace with --namespace flag: ${namespacesWithMigrations.map((ns) => ns.namespace).join(\", \")}`,\n );\n}\n\nexport const scriptCommand = defineAppCommand({\n name: \"script\",\n description:\n \"Add a migration script (migrate.ts) template to an existing migration directory, or record with --no-script that a migration intentionally has none.\",\n args: z.strictObject({\n ...configArg,\n number: arg(z.string(), {\n positional: true,\n description: \"Migration number to add a script to (e.g., 0001 or 1)\",\n }),\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n \"no-script\": arg(z.boolean().optional(), {\n description:\n \"Record that this migration intentionally runs without a migration script (requires --reason)\",\n }),\n reason: arg(z.string().optional(), {\n description: \"Reason why no migration script is needed (used with --no-script)\",\n }),\n }),\n run: async (args) => {\n await script({\n configPath: args.config,\n number: args.number,\n namespace: args.namespace,\n noScript: args[\"no-script\"],\n reason: args.reason,\n });\n },\n});\n","import { getOrNull, type OperatorClient } from \"#/cli/shared/client\";\nimport { MIGRATION_LABEL_KEY, parseMigrationLabelNumber } from \"./types\";\n\n/**\n * Fetch the namespace's current migration number from its metadata labels.\n *\n * Only a namespace that has not been deployed yet reads as \"no current\n * migration\". Every other lookup failure must propagate: treating it as\n * unset would misreport a transient error as \"no checkpoint\", showing\n * every migration as pending to callers.\n * @param client - Operator client\n * @param trn - Namespace TRN\n * @returns Parsed current migration number, or null when unset or unparseable\n */\nexport async function fetchRemoteMigrationNumber(\n client: OperatorClient,\n trn: string,\n): Promise<number | null> {\n const metadata = await getOrNull(async () => {\n const { metadata } = await client.getMetadata({ trn });\n return metadata;\n });\n const label = metadata?.labels[MIGRATION_LABEL_KEY];\n return label ? parseMigrationLabelNumber(label) : null;\n}\n","import * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn, writeMetadataLabels } from \"#/cli/commands/deploy/label\";\nimport { confirmationArgs, deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getNamespacesWithMigrations, selectTargetNamespace } from \"./config\";\nimport { parseMigrationNumberArg } from \"./migration-number\";\nimport { fetchRemoteMigrationNumber } from \"./remote-state\";\nimport {\n assertMigrationNumberExists,\n assertValidMigrationFiles,\n formatMigrationNumber,\n} from \"./snapshot\";\nimport { MIGRATION_LABEL_KEY, sanitizeMigrationLabel } from \"./types\";\n\nexport interface SetOptions {\n configPath?: string;\n number: string;\n namespace?: string;\n yes?: boolean;\n workspaceId?: string;\n profile?: string;\n}\n\n/**\n * Set migration checkpoint for a TailorDB namespace\n * @param {SetOptions} options - Command options\n */\nasync function set(options: SetOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n // 1. Validate migration number format\n const migrationNumber = parseMigrationNumberArg(options.number);\n\n // 2. Load configuration\n const { config } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n // 3. Determine target namespace\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n const target = selectTargetNamespace(namespacesWithMigrations, options.namespace);\n const targetNamespace = target.namespace;\n\n // 4. Validate the local migration history and the requested number\n assertValidMigrationFiles(target.migrationsDir, targetNamespace);\n assertMigrationNumberExists(target.migrationsDir, migrationNumber);\n\n // 5. Initialize client\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n // 6. Get current migration number\n const trn = resourceTrn(workspaceId, \"tailordb\", targetNamespace);\n const current = await fetchRemoteMigrationNumber(client, trn);\n const currentMigration = current ?? 0;\n\n // 7. Display warning and confirmation\n logger.newline();\n logger.warn(\"This operation will change the migration checkpoint.\");\n logger.log(`Namespace: ${styles.bold(targetNamespace)}`);\n logger.log(\n `Current migration: ${current === null ? \"<unset>\" : styles.bold(formatMigrationNumber(current))}`,\n );\n logger.log(`New migration: ${styles.bold(formatMigrationNumber(migrationNumber))}`);\n logger.newline();\n\n if (migrationNumber < currentMigration) {\n logger.warn(\n `Setting migration number backwards (${formatMigrationNumber(currentMigration)} → ${formatMigrationNumber(migrationNumber)}) will cause previous migrations to be re-executed on next apply.`,\n );\n logger.newline();\n } else if (migrationNumber > currentMigration) {\n logger.warn(\n `Setting migration number forwards (${formatMigrationNumber(currentMigration)} → ${formatMigrationNumber(migrationNumber)}) will skip migrations ${formatMigrationNumber(currentMigration + 1)} to ${formatMigrationNumber(migrationNumber)}.`,\n );\n logger.newline();\n }\n\n // 8. Confirmation prompt (unless --yes flag)\n if (!options.yes) {\n const confirmation = await prompt.confirm({\n message: \"Continue with migration checkpoint update?\",\n default: false,\n });\n\n if (!confirmation) {\n logger.info(\"Operation cancelled.\");\n return;\n }\n logger.newline();\n }\n\n // 9. Update migration label\n await writeMetadataLabels(client, {\n trn,\n labels: { [MIGRATION_LABEL_KEY]: sanitizeMigrationLabel(migrationNumber) },\n });\n\n logger.success(\n `Migration checkpoint set to ${styles.bold(formatMigrationNumber(migrationNumber))} for namespace ${styles.bold(targetNamespace)}`,\n );\n}\n\nexport const setCommand = defineAppCommand({\n name: \"set\",\n description: \"Set migration checkpoint to a specific number.\",\n notes: `The migration number must be a 4-digit value (e.g. \\`0001\\`) or a bare integer (e.g. \\`1\\`) within 0–9999, and must exist in the local migration history; \\`0\\` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.`,\n args: z.strictObject({\n ...deploymentArgs,\n ...confirmationArgs,\n number: arg(z.string(), {\n positional: true,\n description: \"Migration number to set (e.g., 0001 or 1)\",\n }),\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await set({\n configPath: args.config,\n number: args.number,\n namespace: args.namespace,\n yes: args.yes,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n },\n});\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn } from \"#/cli/commands/deploy/label\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { getNamespacesWithMigrations } from \"./config\";\nimport { fetchRemoteMigrationNumber } from \"./remote-state\";\nimport {\n getMigrationFiles,\n loadDiff,\n getMigrationFilePath,\n formatMigrationNumber,\n} from \"./snapshot\";\n\nexport interface StatusOptions {\n configPath?: string;\n namespace?: string;\n workspaceId?: string;\n profile?: string;\n json?: boolean;\n}\n\ninterface PendingMigrationStatusInfo {\n number: number;\n label: string;\n description?: string;\n}\n\ninterface MigrationStatusInfo {\n status: \"ok\";\n namespace: string;\n currentMigration: number;\n currentMigrationLabel: string;\n pendingMigrations: PendingMigrationStatusInfo[];\n}\n\ninterface MigrationStatusFailure {\n status: \"error\";\n namespace: string;\n error: string;\n}\n\ntype MigrationStatusRow = MigrationStatusInfo | MigrationStatusFailure;\n\nfunction isStatusFailure(row: MigrationStatusRow): row is MigrationStatusFailure {\n return row.status === \"error\";\n}\n\nasync function collectMigrationStatuses(options: StatusOptions): Promise<MigrationStatusRow[]> {\n const { config } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n\n if (namespacesWithMigrations.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found\");\n }\n\n const targetNamespaces = options.namespace\n ? namespacesWithMigrations.filter((ns) => ns.namespace === options.namespace)\n : namespacesWithMigrations;\n\n if (targetNamespaces.length === 0) {\n throw new Error(\n `Namespace \"${options.namespace}\" not found or does not have migrations configured`,\n );\n }\n\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const rows: MigrationStatusRow[] = [];\n\n for (const { namespace, migrationsDir } of targetNamespaces) {\n const trn = resourceTrn(workspaceId, \"tailordb\", namespace);\n let current: number | null;\n try {\n current = await fetchRemoteMigrationNumber(client, trn);\n } catch (error) {\n rows.push({\n status: \"error\",\n namespace,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const currentMigration = current ?? 0;\n\n const migrationFiles = getMigrationFiles(migrationsDir);\n const availableNumbers = migrationFiles\n .map((f) => f.number)\n .filter((n, i, arr) => arr.indexOf(n) === i) // deduplicate\n .toSorted((a, b) => a - b);\n const pendingNumbers = availableNumbers.filter((n) => n > currentMigration);\n\n const pendingMigrations = pendingNumbers.map((num) => {\n const diffPath = getMigrationFilePath(migrationsDir, num, \"diff\");\n let description: string | undefined;\n\n if (fs.existsSync(diffPath)) {\n try {\n const diff = loadDiff(diffPath);\n description = diff.description;\n } catch {\n // Ignore errors loading diff\n }\n }\n\n return {\n number: num,\n label: formatMigrationNumber(num),\n ...(description ? { description } : {}),\n };\n });\n\n rows.push({\n status: \"ok\",\n namespace,\n currentMigration,\n currentMigrationLabel: formatMigrationNumber(currentMigration),\n pendingMigrations,\n });\n }\n\n return rows;\n}\n\nfunction printMigrationStatuses(rows: MigrationStatusRow[]): void {\n for (const row of rows) {\n logger.newline();\n logger.info(`Namespace: ${styles.bold(row.namespace)}`);\n if (isStatusFailure(row)) {\n logger.error(` Failed to read migration state: ${row.error}`);\n continue;\n }\n logger.log(` Current migration: ${styles.bold(row.currentMigrationLabel)}`);\n\n if (row.pendingMigrations.length > 0) {\n logger.log(\" Pending migrations:\");\n for (const pending of row.pendingMigrations) {\n if (pending.description) {\n logger.log(` - ${pending.label}: ${pending.description}`);\n } else {\n logger.log(` - ${pending.label}`);\n }\n }\n } else {\n logger.log(\" Pending migrations: (none)\");\n }\n }\n\n logger.newline();\n}\n\n/**\n * Show migration status for TailorDB namespaces\n * @param {StatusOptions} options - Command options\n */\nasync function status(options: StatusOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const rows = await collectMigrationStatuses(options);\n if (options.json) {\n logger.out(rows);\n } else {\n printMigrationStatuses(rows);\n }\n\n const failures = rows.filter(isStatusFailure);\n if (failures.length > 0) {\n const namespaces = failures.map((f) => f.namespace).join(\", \");\n throw new Error(\n `Failed to read migration state for ${failures.length} namespace${failures.length === 1 ? \"\" : \"s\"}: ${namespaces}`,\n );\n }\n}\n\nexport const statusCommand = defineAppCommand({\n name: \"status\",\n description:\n \"Show the current migration status for TailorDB namespaces, including applied and pending migrations.\",\n notes:\n \"Metadata lookup failures (authentication, permission, or network errors) are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.\",\n args: z.strictObject({\n ...deploymentArgs,\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (shows all namespaces if not specified)\",\n }),\n }),\n run: async (args) => {\n await status({\n configPath: args.config,\n namespace: args.namespace,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n json: logger.jsonMode,\n });\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn, writeMetadataLabels } from \"#/cli/commands/deploy/label\";\nimport { confirmationArgs, deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport {\n fetchAll,\n fetchAllTolerant,\n initOperatorClient,\n type OperatorClient,\n} from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { PluginManager } from \"#/plugin/manager\";\nimport {\n getNamespacesWithMigrations,\n selectTargetNamespace,\n type NamespaceWithMigrations,\n} from \"./config\";\nimport { formatMigrationDiff, hasChanges } from \"./diff-calculator\";\nimport { parseMigrationNumberArg } from \"./migration-number\";\nimport { fetchRemoteMigrationNumber } from \"./remote-state\";\nimport {\n assertMigrationNumberExists,\n assertValidMigrationFiles,\n compareLocalTypesWithSnapshot,\n createSnapshotFromLocalTypes,\n formatMigrationNumber,\n reconstructSnapshotFromMigrations,\n} from \"./snapshot\";\nimport {\n compareSnapshotWithRemote,\n generateAllTypeManifestsFromSnapshot,\n protoGqlPermission,\n type GenerateAllManifestsOptions,\n} from \"./snapshot-manifest\";\nimport {\n handleOptionalToRequiredError,\n MIGRATION_LABEL_KEY,\n sanitizeMigrationLabel,\n} from \"./types\";\nimport type { TailorDBType as ProtoTailorDBType } from \"@tailor-platform/tailor-proto/tailordb_resource_pb\";\n\nexport interface SyncOptions {\n configPath?: string;\n number: string;\n namespace?: string;\n yes?: boolean;\n workspaceId?: string;\n profile?: string;\n}\n\ntype RemoteGqlPermission = Awaited<\n ReturnType<OperatorClient[\"listTailorDBGQLPermissions\"]>\n>[\"permissions\"][number];\n\nasync function fetchRemoteGqlPermissions(\n client: OperatorClient,\n workspaceId: string,\n namespace: string,\n): Promise<RemoteGqlPermission[]> {\n return fetchAllTolerant(async (pageToken, maxPageSize) => {\n const { permissions, nextPageToken } = await client.listTailorDBGQLPermissions({\n workspaceId,\n namespaceName: namespace,\n pageToken,\n pageSize: maxPageSize,\n });\n return [permissions, nextPageToken];\n });\n}\n\nasync function fetchRemoteTypes(\n client: OperatorClient,\n workspaceId: string,\n namespace: string,\n): Promise<ProtoTailorDBType[]> {\n return fetchAll(async (pageToken, maxPageSize) => {\n try {\n const { tailordbTypes, nextPageToken } = await client.listTailorDBTypes({\n workspaceId,\n namespaceName: namespace,\n pageToken,\n pageSize: maxPageSize,\n });\n return [tailordbTypes, nextPageToken];\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(\n `Cannot sync: TailorDB namespace \"${namespace}\" has not been deployed yet.`,\n { cause: error },\n );\n }\n throw error;\n }\n });\n}\n\n/**\n * Verify that replaying the full migration history reproduces the current\n * local type definitions, before anything is sent to the remote.\n *\n * Sync force-applies a snapshot reconstructed from the migration history, so\n * the history itself must be trustworthy. When the reconstruction at the\n * latest migration does not match the schema defined in the local type files,\n * either the migration files were edited incorrectly or a schema change has\n * not been recorded as a migration yet — and overwriting the remote with an\n * unverified snapshot could destroy data. Fails before any RPC is issued.\n *\n * Returns the manifest generation options deploy would use for this\n * namespace (executor-driven publishRecordEvents and namespace\n * gqlOperations), so the synced manifests match what deploy produces.\n * @param loaded - Result of `loadConfig` (config and plugins)\n * @param target - Namespace whose migration history is being synced\n * @returns Options for `generateAllTypeManifestsFromSnapshot`\n */\nasync function assertMigrationsReproduceLocalTypes(\n loaded: Awaited<ReturnType<typeof loadConfig>>,\n target: NamespaceWithMigrations,\n): Promise<GenerateAllManifestsOptions> {\n const { config, plugins } = loaded;\n const pluginManager = plugins.length > 0 ? new PluginManager(plugins) : undefined;\n const { defineApplication, generatePluginFilesIfNeeded } =\n await import(\"#/cli/services/application\");\n const application = defineApplication({ config, pluginManager });\n\n const tailordbService = application.tailorDBServices.find(\n (s) => s.namespace === target.namespace,\n );\n if (!tailordbService) {\n throw new Error(`No TailorDB service found for namespace \"${target.namespace}\"`);\n }\n // Load every namespace (not just the target): plugin executors are\n // registered while types load, and may trigger on the target's types.\n for (const service of application.tailorDBServices) {\n await service.loadTypes();\n await service.processNamespacePlugins();\n }\n\n // Mirror loadApplication: plugin-generated executor files must be loaded\n // too, or publishRecordEvents would be applied as false for the types\n // their record triggers depend on. Read the executors getter rather than\n // the loadExecutors() result — the latter is undefined for plugin-only\n // executor configurations.\n const pluginExecutorFiles = generatePluginFilesIfNeeded(\n pluginManager,\n application.tailorDBServices,\n config.path,\n );\n const executorService =\n application.executorService ??\n (pluginExecutorFiles.length > 0\n ? (await import(\"#/cli/services/executor/service\")).createExecutorService({\n config: { files: [] },\n baseDir: path.dirname(config.path),\n })\n : undefined);\n await executorService?.loadExecutors();\n if (pluginExecutorFiles.length > 0) {\n await executorService?.loadPluginExecutorFiles([...pluginExecutorFiles]);\n }\n const executorUsedTypes = new Set<string>();\n for (const executor of Object.values(executorService?.executors ?? {})) {\n if (executor.trigger.kind === \"tailordb\") {\n executorUsedTypes.add(executor.trigger.typeName);\n }\n }\n const manifestOptions: GenerateAllManifestsOptions = {\n executorUsedTypes,\n namespaceGqlOperations: tailordbService.config.gqlOperations,\n };\n\n const latestSnapshot = reconstructSnapshotFromMigrations(target.migrationsDir);\n if (!latestSnapshot) {\n return manifestOptions; // No migrations at all — reported by the caller's snapshot check.\n }\n const currentSnapshot = createSnapshotFromLocalTypes(tailordbService.types, target.namespace);\n const diff = compareLocalTypesWithSnapshot(\n latestSnapshot,\n currentSnapshot.types,\n target.namespace,\n );\n if (!hasChanges(diff)) {\n return manifestOptions;\n }\n\n logger.error(\n `Migration history does not reproduce the current local schema for namespace ${styles.bold(target.namespace)}:`,\n );\n logger.log(formatMigrationDiff(diff));\n logger.newline();\n logger.info(\"This usually means one of the following:\");\n logger.info(\n \" - Migration files were edited and replaying them no longer matches the type definitions — fix the migration files.\",\n { mode: \"plain\" },\n );\n logger.info(\n \" - Type definitions changed without a new migration — run 'tailor tailordb migration generate' first.\",\n { mode: \"plain\" },\n );\n logger.newline();\n throw new Error(\n \"Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.\",\n );\n}\n\n/**\n * Sync remote TailorDB schema to a specific migration snapshot.\n *\n * Reconstructs the schema state at `<number>` from `0000/schema.json` + diffs,\n * then issues create/update/delete RPCs so the remote matches that snapshot.\n * Updates the migration label to `<number>` on success. Before any remote\n * mutation, verifies that the migration history reproduces the current local\n * type definitions (see {@link assertMigrationsReproduceLocalTypes}).\n *\n * Intended for recovering from drift introduced by `deploy --no-schema-check`\n * runs against an older revision: instead of having to `git checkout` that\n * revision and re-deploy, the operator can sync the remote back to a known\n * snapshot version directly.\n * @param options - Command options\n */\nasync function sync(options: SyncOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const targetVersion = parseMigrationNumberArg(options.number);\n\n const loaded = await loadConfig(options.configPath);\n const { config } = loaded;\n const configDir = path.dirname(config.path);\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n const target = selectTargetNamespace(namespacesWithMigrations, options.namespace);\n\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n\n const latest = assertMigrationNumberExists(target.migrationsDir, targetVersion);\n\n const snapshot = reconstructSnapshotFromMigrations(target.migrationsDir, targetVersion);\n if (!snapshot) {\n throw new Error(\n `No initial schema snapshot found in ${target.migrationsDir}. Expected 0000/schema.json.`,\n );\n }\n\n const manifestOptions = await assertMigrationsReproduceLocalTypes(loaded, target);\n\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const trn = resourceTrn(workspaceId, \"tailordb\", target.namespace);\n const current = await fetchRemoteMigrationNumber(client, trn);\n const remoteTypes = await fetchRemoteTypes(client, workspaceId, target.namespace);\n const existingTypeNames = new Set(remoteTypes.map((t) => t.name));\n const { creates, updates, deletes } = compareSnapshotWithRemote(snapshot, existingTypeNames);\n\n // GQL permissions are reconciled alongside types: upsert the ones defined\n // in the snapshot, delete remote ones with no snapshot counterpart\n // (including those of deleted types — an orphaned permission can block\n // the type deletion).\n const remoteGqlPermissions = await fetchRemoteGqlPermissions(\n client,\n workspaceId,\n target.namespace,\n );\n const remoteGqlPermissionTypes = new Set(remoteGqlPermissions.map((p) => p.typeName));\n const desiredGqlPermissions = Object.entries(snapshot.types).flatMap(\n ([typeName, snapshotType]) =>\n snapshotType.permissions?.gql\n ? [{ typeName, permission: protoGqlPermission(snapshotType.permissions.gql) }]\n : [],\n );\n const desiredGqlPermissionTypes = new Set(desiredGqlPermissions.map((p) => p.typeName));\n const gqlPermissionDeletes = remoteGqlPermissions.filter(\n (p) => !desiredGqlPermissionTypes.has(p.typeName),\n );\n\n logger.newline();\n logger.info(`Namespace: ${styles.bold(target.namespace)}`);\n logger.log(\n ` Current migration: ${current === null ? \"<unset>\" : styles.bold(formatMigrationNumber(current))}`,\n );\n logger.log(` Target migration: ${styles.bold(formatMigrationNumber(targetVersion))}`);\n logger.log(` Types to create: ${styles.bold(String(creates.length))}`);\n logger.log(` Types to update: ${styles.bold(String(updates.length))}`);\n logger.log(` Types to delete: ${styles.bold(String(deletes.length))}`);\n logger.log(` GQL permissions to set: ${styles.bold(String(desiredGqlPermissions.length))}`);\n logger.log(` GQL permissions to delete: ${styles.bold(String(gqlPermissionDeletes.length))}`);\n logger.newline();\n\n const totalOps =\n creates.length +\n updates.length +\n deletes.length +\n desiredGqlPermissions.length +\n gqlPermissionDeletes.length;\n if (totalOps === 0) {\n // Reachable only when both snapshot and remote hold no types; the label\n // may still be stale, so the sync proceeds to update it.\n logger.info(\"No types to apply; only the migration label will be updated.\");\n } else {\n logger.warn(\n \"This operation will overwrite remote TailorDB types to match the selected snapshot.\",\n );\n if (deletes.length > 0) {\n logger.warn(\"Existing data in deleted types will be lost.\");\n }\n logger.newline();\n }\n\n logger.warn(\n \"Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.\",\n );\n logger.newline();\n\n if (current !== null && targetVersion < current) {\n logger.warn(\n `Migrations ${formatMigrationNumber(targetVersion + 1)}–${formatMigrationNumber(\n current,\n )} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`,\n );\n logger.newline();\n } else if (current !== null && targetVersion > current) {\n logger.warn(\n `Moving the migration label forwards (${formatMigrationNumber(current)} → ${formatMigrationNumber(\n targetVersion,\n )}): migrate.ts scripts for migrations ${formatMigrationNumber(current + 1)}–${formatMigrationNumber(\n targetVersion,\n )} will not run on the next deploy.`,\n );\n logger.newline();\n }\n\n if (!options.yes) {\n const confirmation = await prompt.confirm({\n message: `Continue and set migration label to ${formatMigrationNumber(targetVersion)}?`,\n default: false,\n });\n if (!confirmation) {\n logger.info(\"Operation cancelled.\");\n return;\n }\n logger.newline();\n }\n\n const manifests = generateAllTypeManifestsFromSnapshot(snapshot, manifestOptions);\n\n // Resolve all manifests before issuing any RPC: a missing manifest\n // indicates an internal inconsistency, and skipping or failing midway\n // would leave the remote schema partially synced.\n const manifestFor = (typeName: string) => {\n const manifest = manifests.get(typeName);\n if (!manifest) {\n throw new Error(\n `Internal error: no manifest generated for type \"${typeName}\". No changes were applied.`,\n );\n }\n return manifest;\n };\n const createManifests = creates.map((typeName) => manifestFor(typeName));\n const updateManifests = updates.map((typeName) => manifestFor(typeName));\n\n try {\n await Promise.all([\n ...createManifests.map((tailordbType) =>\n client.createTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbType,\n }),\n ),\n ...updateManifests.map((tailordbType) =>\n client.updateTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbType,\n }),\n ),\n ]);\n } catch (error) {\n handleOptionalToRequiredError(error, [\n \"The target snapshot marks a field as required, but existing remote records have no value for it.\",\n \"Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.\",\n ]);\n }\n await Promise.all(\n desiredGqlPermissions.map(({ typeName, permission }) => {\n const request = { workspaceId, namespaceName: target.namespace, typeName, permission };\n return remoteGqlPermissionTypes.has(typeName)\n ? client.updateTailorDBGQLPermission(request)\n : client.createTailorDBGQLPermission(request);\n }),\n );\n await Promise.all(\n gqlPermissionDeletes.map((p) =>\n client.deleteTailorDBGQLPermission({\n workspaceId,\n namespaceName: target.namespace,\n typeName: p.typeName,\n }),\n ),\n );\n await Promise.all(\n deletes.map((typeName) =>\n client.deleteTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbTypeName: typeName,\n }),\n ),\n );\n\n await writeMetadataLabels(client, {\n trn,\n labels: {\n [MIGRATION_LABEL_KEY]: sanitizeMigrationLabel(targetVersion),\n },\n });\n\n logger.success(\n `Synced namespace ${styles.bold(target.namespace)} to migration ${styles.bold(formatMigrationNumber(targetVersion))}.`,\n );\n\n if (targetVersion < latest) {\n logger.newline();\n logger.info(\n `Run 'tailor deploy' to apply migrations ${formatMigrationNumber(\n targetVersion + 1,\n )}–${formatMigrationNumber(latest)} from the working tree.`,\n );\n }\n}\n\nexport const syncCommand = defineAppCommand({\n name: \"sync\",\n description:\n \"Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).\",\n args: z.strictObject({\n ...deploymentArgs,\n ...confirmationArgs,\n number: arg(z.string(), {\n positional: true,\n description: \"Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)\",\n }),\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await sync({\n configPath: args.config,\n number: args.number,\n namespace: args.namespace,\n yes: args.yes,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n },\n});\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { assertUniqueLocalTailorDBTypeNames } from \"#/cli/services/tailordb/type-name-validation\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { PluginManager } from \"#/plugin/manager\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { getNamespacesWithMigrations, type NamespaceWithMigrations } from \"./config\";\nimport { formatDiffSummary, formatMigrationDiff, type MigrationDiff } from \"./diff-calculator\";\nimport {\n checkMigrationDiffs,\n logRemoteDriftGuidance,\n toTailorDBDeployInput,\n verifyRemoteSchema,\n type MigrationCheckResult,\n} from \"./schema-checks\";\nimport {\n assertValidMigrationFiles,\n formatMigrationNumber,\n formatSchemaDrifts,\n getMigrationFilePath,\n getMigrationFiles,\n loadDiff,\n reconstructSnapshotFromMigrations,\n} from \"./snapshot\";\nimport type {\n RemoteSchemaVerificationResult,\n RemoteSchemaVerificationSkipReason,\n SchemaDrift,\n} from \"./types\";\n\nexport interface ValidateOptions {\n configPath?: string;\n namespace?: string;\n workspaceId?: string;\n profile?: string;\n json?: boolean;\n}\n\ninterface MigrationFilesReport {\n valid: boolean;\n error?: string;\n}\n\ninterface LocalSchemaReport {\n hasDiff: boolean;\n /** Present when local types drifted from the latest migration snapshot; absent when the drift is a missing snapshot */\n diff?: MigrationDiff;\n}\n\ninterface CompletedRemoteSchemaReport {\n remoteMigrationNumber: number;\n hasDrift: boolean;\n drifts: SchemaDrift[];\n /** Set when the remote check could not run (no remote migration label, or no snapshot at the remote migration number) */\n skipped?: RemoteSchemaVerificationSkipReason;\n /** Set when the remote migration checkpoint does not exist in the local migration history */\n checkpointMissingLocal?: boolean;\n}\n\ninterface FailedRemoteSchemaReport {\n skipped: \"check_failed\";\n remoteMigrationNumber?: never;\n hasDrift?: never;\n drifts?: never;\n checkpointMissingLocal?: never;\n}\n\ntype RemoteSchemaReport = CompletedRemoteSchemaReport | FailedRemoteSchemaReport;\n\ninterface NamespaceValidationReport {\n namespace: string;\n valid: boolean;\n migrationFiles: MigrationFilesReport;\n /** Omitted when the migration files are invalid (the check cannot run) */\n localSchema?: LocalSchemaReport;\n /** Omitted when the migration files are invalid */\n remoteSchema?: RemoteSchemaReport;\n}\n\ninterface BuildValidationReportsOptions {\n targetNamespaces: NamespaceWithMigrations[];\n migrationFileErrors: Map<string, string>;\n localResults: MigrationCheckResult[];\n remoteResults?: RemoteSchemaVerificationResult[];\n}\n\ninterface CollectedValidationReports {\n reports: NamespaceValidationReport[];\n remoteError?: unknown;\n}\n\n/**\n * Assert that every migration in the local history whose diff requires a data\n * migration script has a migrate.ts on disk or an explicit skip acknowledgment\n * @param {string} migrationsDir - Migrations directory path\n * @param {string} namespace - TailorDB namespace (for error messages)\n */\nfunction assertRequiredMigrationScripts(migrationsDir: string, namespace: string): void {\n const missing: number[] = [];\n for (const file of getMigrationFiles(migrationsDir)) {\n if (file.type !== \"diff\") continue;\n const diff = loadDiff(file.path);\n if (!diff.requiresMigrationScript || diff.scriptSkipped) continue;\n if (!fs.existsSync(getMigrationFilePath(migrationsDir, file.number, \"migrate\"))) {\n missing.push(file.number);\n }\n }\n if (missing.length > 0) {\n throw new Error(\n `Migration(s) ${missing.map(formatMigrationNumber).join(\", \")} in namespace \"${namespace}\" ` +\n \"require a migration script but have no migrate.ts. \" +\n \"Add one with 'tailor tailordb migration script <number>', or record that no script \" +\n `is needed with 'tailor tailordb migration script <number> --no-script --reason \"...\"'.`,\n );\n }\n}\n\n/**\n * Build per-namespace reports from the checks that completed\n * @param {BuildValidationReportsOptions} options - Completed validation results\n * @returns {NamespaceValidationReport[]} Validation reports per namespace\n */\nfunction buildValidationReports(\n options: BuildValidationReportsOptions,\n): NamespaceValidationReport[] {\n const { targetNamespaces, migrationFileErrors, localResults, remoteResults } = options;\n\n return targetNamespaces.map((target) => {\n const fileError = migrationFileErrors.get(target.namespace);\n if (fileError !== undefined) {\n return {\n namespace: target.namespace,\n valid: false,\n migrationFiles: { valid: false, error: fileError },\n };\n }\n\n const local = assertDefined(\n localResults.find((result) => result.namespace === target.namespace),\n `local schema check result missing for namespace \"${target.namespace}\"`,\n );\n const localSchema: LocalSchemaReport = {\n hasDiff: local.hasDiff,\n ...(local.diff ? { diff: local.diff } : {}),\n };\n if (remoteResults === undefined) {\n return {\n namespace: target.namespace,\n valid: false,\n migrationFiles: { valid: true },\n localSchema,\n remoteSchema: { skipped: \"check_failed\" },\n };\n }\n\n const remote = assertDefined(\n remoteResults.find((result) => result.namespace === target.namespace),\n `remote schema check result missing for namespace \"${target.namespace}\"`,\n );\n const checkpointMissingLocal = remote.checkpointMissingLocal === true;\n const remoteSchema: RemoteSchemaReport = {\n remoteMigrationNumber: remote.remoteMigrationNumber,\n hasDrift: remote.hasDrift,\n drifts: remote.drifts,\n ...(remote.skipped ? { skipped: remote.skipped } : {}),\n ...(checkpointMissingLocal ? { checkpointMissingLocal: true } : {}),\n };\n\n return {\n namespace: target.namespace,\n valid: !localSchema.hasDiff && !remoteSchema.hasDrift && !checkpointMissingLocal,\n migrationFiles: { valid: true },\n localSchema,\n remoteSchema,\n };\n });\n}\n\n/**\n * Run all migration validation checks and collect per-namespace reports\n * @param {ValidateOptions} options - Command options\n * @returns {Promise<CollectedValidationReports>} Validation reports and any remote error\n */\nasync function collectValidationReports(\n options: ValidateOptions,\n): Promise<CollectedValidationReports> {\n const { config, plugins } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n if (namespacesWithMigrations.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found\");\n }\n\n const targetNamespaces = options.namespace\n ? namespacesWithMigrations.filter((ns) => ns.namespace === options.namespace)\n : namespacesWithMigrations;\n if (targetNamespaces.length === 0) {\n throw new Error(\n `Namespace \"${options.namespace}\" not found or does not have migrations configured`,\n );\n }\n\n const pluginManager = plugins.length > 0 ? new PluginManager(plugins) : undefined;\n const { defineApplication } = await import(\"#/cli/services/application\");\n const application = defineApplication({ config, pluginManager });\n // Load every namespace (not just the targets): plugins registered while\n // types load may contribute types to the target namespaces.\n for (const service of application.tailorDBServices) {\n await service.loadTypes();\n await service.processNamespacePlugins();\n }\n assertUniqueLocalTailorDBTypeNames({ tailorDBServices: application.tailorDBServices });\n for (const { namespace } of targetNamespaces) {\n if (!application.tailorDBServices.some((s) => s.namespace === namespace)) {\n throw new Error(`No TailorDB service found for namespace \"${namespace}\"`);\n }\n }\n const tailorDBInputs = application.tailorDBServices.map(toTailorDBDeployInput);\n const typesByNamespace = new Map(tailorDBInputs.map((input) => [input.namespace, input.types]));\n\n const migrationFileErrors = new Map<string, string>();\n const checkableNamespaces: NamespaceWithMigrations[] = [];\n for (const target of targetNamespaces) {\n try {\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n // Parse the whole history here so malformed snapshot/diff contents are\n // reported per namespace instead of aborting the run for every namespace.\n reconstructSnapshotFromMigrations(target.migrationsDir);\n assertRequiredMigrationScripts(target.migrationsDir, target.namespace);\n checkableNamespaces.push(target);\n } catch (error) {\n migrationFileErrors.set(\n target.namespace,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n const localResults = await checkMigrationDiffs(typesByNamespace, checkableNamespaces);\n const localReportOptions = {\n targetNamespaces,\n migrationFileErrors,\n localResults,\n };\n\n if (checkableNamespaces.length === 0) {\n return {\n reports: buildValidationReports(localReportOptions),\n };\n }\n\n let remoteResults: RemoteSchemaVerificationResult[];\n try {\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n remoteResults = await verifyRemoteSchema(\n client,\n workspaceId,\n checkableNamespaces,\n config,\n tailorDBInputs,\n );\n } catch (remoteError) {\n return {\n reports: buildValidationReports(localReportOptions),\n remoteError,\n };\n }\n\n return {\n reports: buildValidationReports({ ...localReportOptions, remoteResults }),\n };\n}\n\nfunction printValidationReports(reports: NamespaceValidationReport[]): void {\n for (const report of reports) {\n logger.newline();\n logger.info(`Namespace: ${styles.bold(report.namespace)}`);\n\n if (!report.migrationFiles.valid) {\n logger.log(` Migration files: ${styles.error(\"invalid\")}`);\n logger.log(` ${report.migrationFiles.error}`);\n continue;\n }\n logger.log(` Migration files: ${styles.success(\"OK\")}`);\n\n const local = report.localSchema;\n if (local?.hasDiff) {\n if (local.diff) {\n logger.log(` Local schema: ${styles.error(\"changes not in migration files\")}`);\n logger.log(` ${formatDiffSummary(local.diff)}`);\n logger.log(formatMigrationDiff(local.diff));\n } else {\n logger.log(` Local schema: ${styles.error(\"no migration snapshot found\")}`);\n }\n } else {\n logger.log(` Local schema: ${styles.success(\"OK\")}`);\n }\n\n const remote = report.remoteSchema;\n if (remote?.skipped === \"check_failed\") {\n logger.log(` Remote schema: ${styles.error(\"not checked\")}`);\n } else if (remote?.checkpointMissingLocal) {\n logger.log(\n ` Remote schema: ${styles.error(\n `remote migration ${formatMigrationNumber(remote.remoteMigrationNumber)} is not in the local migration history`,\n )}`,\n );\n } else if (remote?.hasDrift) {\n logger.log(\n ` Remote schema: ${styles.error(\"drift detected\")} (remote migration: ${formatMigrationNumber(remote.remoteMigrationNumber)})`,\n );\n logger.log(formatSchemaDrifts(remote.drifts));\n } else if (remote?.skipped === \"not_deployed\") {\n logger.log(` Remote schema: ${styles.dim(\"skipped (namespace not deployed)\")}`);\n } else if (remote?.skipped === \"no_migration_label\") {\n logger.log(\n ` Remote schema: ${styles.dim(\"skipped (deployed namespace has no migration state)\")}`,\n );\n } else if (remote?.skipped === \"no_snapshot\") {\n logger.log(\n ` Remote schema: ${styles.dim(`skipped (no local snapshot for remote migration ${formatMigrationNumber(remote.remoteMigrationNumber)})`)}`,\n );\n } else if (remote) {\n logger.log(\n ` Remote schema: ${styles.success(\"OK\")} (remote migration: ${formatMigrationNumber(remote.remoteMigrationNumber)})`,\n );\n }\n }\n logger.newline();\n}\n\nfunction printResolutionHints(reports: NamespaceValidationReport[]): void {\n if (reports.some((r) => r.localSchema?.hasDiff && !r.localSchema.diff)) {\n logger.info(\"Run 'tailor tailordb migration generate' to create the initial snapshot.\");\n }\n if (reports.some((r) => r.localSchema?.diff)) {\n logger.info(\"Run 'tailor tailordb migration generate' to create migration files.\");\n }\n if (reports.some((r) => r.remoteSchema?.checkpointMissingLocal)) {\n logger.info(\n \"The remote migration checkpoint is ahead of the local history. Pull the latest migration files, or run 'tailor tailordb migration status' to compare.\",\n );\n }\n if (reports.some((r) => r.remoteSchema?.hasDrift)) {\n logRemoteDriftGuidance();\n }\n}\n\n/**\n * Validate migration files and schema state without deploying\n * @param {ValidateOptions} options - Command options\n */\nasync function validate(options: ValidateOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const collected = await collectValidationReports(options);\n const { reports } = collected;\n const invalidCount = reports.filter((r) => !r.valid).length;\n\n if (options.json) {\n logger.out(reports);\n } else {\n printValidationReports(reports);\n if (invalidCount === 0 && !(\"remoteError\" in collected)) {\n logger.success(\"All migration validation checks passed.\");\n } else {\n printResolutionHints(reports);\n }\n }\n\n if (\"remoteError\" in collected) {\n throw collected.remoteError;\n }\n if (invalidCount > 0) {\n throw new Error(`Migration validation failed for ${invalidCount} namespace(s)`);\n }\n}\n\nexport const validateCommand = defineAppCommand({\n name: \"validate\",\n description:\n \"Validate the full migration history and detect schema drift (local types vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.\",\n args: z.strictObject({\n ...deploymentArgs,\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (validates all namespaces if not specified)\",\n }),\n }),\n run: async (args) => {\n await validate({\n configPath: args.config,\n namespace: args.namespace,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n json: logger.jsonMode,\n });\n },\n});\n","/**\n * TailorDB migration command\n *\n * Subcommands:\n * - generate: Generate migration files from schema differences\n * - script: Add a migrate.ts template to an existing migration\n * - set: Set migration checkpoint to a specific number\n * - status: Show migration status for TailorDB namespaces\n * - sync: Sync remote TailorDB schema to a specific migration snapshot\n * - validate: Validate migration files and detect schema drift without deploying\n */\n\nimport { defineCommand } from \"politty\";\nimport { generateCommand } from \"./generate\";\nimport { scriptCommand } from \"./script\";\nimport { setCommand } from \"./set\";\nimport { statusCommand } from \"./status\";\nimport { syncCommand } from \"./sync\";\nimport { validateCommand } from \"./validate\";\n\nexport const migrationCommand = defineCommand({\n name: \"migration\",\n description: \"Manage TailorDB schema migrations.\",\n subCommands: {\n generate: generateCommand,\n script: scriptCommand,\n set: setCommand,\n status: statusCommand,\n sync: syncCommand,\n validate: validateCommand,\n },\n});\n\nexport { generateCommand } from \"./generate\";\nexport { scriptCommand } from \"./script\";\nexport { setCommand } from \"./set\";\nexport { statusCommand } from \"./status\";\nexport { syncCommand } from \"./sync\";\nexport { validateCommand } from \"./validate\";\n","import { defineCommand } from \"politty\";\nimport { migrationCommand } from \"./migrate\";\nimport { truncateCommand } from \"./truncate\";\n\nexport const tailordbCommand = defineCommand({\n name: \"tailordb\",\n description: \"Manage TailorDB tables and data.\",\n notes:\n \"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.\",\n subCommands: {\n truncate: truncateCommand,\n migration: migrationCommand,\n },\n});\n","import * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\n\nexport const upgradeCommand = defineAppCommand({\n name: \"upgrade\",\n description: \"Run codemods to upgrade your project to a newer SDK version.\",\n args: z.strictObject({\n from: arg(z.string(), {\n description: \"SDK version before the upgrade (e.g., 1.33.0)\",\n }),\n \"dry-run\": arg(z.boolean().default(false), {\n alias: \"d\",\n description: \"Preview changes without modifying files\",\n }),\n path: arg(z.string().default(\".\"), {\n description: \"Project directory to upgrade\",\n completion: { type: \"directory\" },\n }),\n }),\n run: async (args) => {\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n\n const { upgrade } = await import(\"./service\");\n await upgrade({\n from: args.from,\n dryRun: args[\"dry-run\"],\n path: path.resolve(args.path),\n });\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n hasUserTokenEntry,\n platformConfigFromProfile,\n readPlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\nexport const currentCommand = defineAppCommand({\n name: \"current\",\n description: \"Show current user.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const profile = process.env.TAILOR_PLATFORM_PROFILE;\n const profileEntry = profile ? config.profiles[profile] : undefined;\n if (profile && !profileEntry) {\n throw new Error(`Profile \"${profile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const currentUser = profile ? (profileEntry?.user ?? null) : config.current_user;\n const jsonOutput = logger.jsonMode;\n\n // Check if current user is set\n if (!currentUser) {\n throw new Error(ml`\n Current user not set.\n Please login first using 'tailor login' command to register a user.\n `);\n }\n\n // Check if user exists\n if (!hasUserTokenEntry(config, currentUser, platformConfig)) {\n throw new Error(ml`\n Current user '${currentUser}' not found in registered users.\n Please login again using 'tailor login' command to register the user.\n `);\n }\n\n if (jsonOutput) {\n logger.out({ user: currentUser });\n return;\n }\n\n logger.out(currentUser);\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n resolveUserTokenKey,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\ntype PlatformConfig = Awaited<ReturnType<typeof readPlatformConfig>>;\n\ntype UserListInfo = {\n user: string;\n platformUrl: string | null;\n current: boolean;\n};\n\nfunction activeCurrentUserKey(config: PlatformConfig): string | null {\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n if (!activeProfile) {\n if (!config.current_user) return null;\n return resolveUserTokenKey(config, config.current_user);\n }\n const profile = config.profiles[activeProfile];\n if (!profile) return null;\n return resolveUserTokenKey(config, profile.user, platformConfigFromProfile(profile));\n}\n\nfunction toUserListInfo(userKey: string, currentUserKey: string | null): UserListInfo {\n const separatorIndex = userKey.indexOf(\"|\");\n const platformUrl = separatorIndex === -1 ? null : userKey.slice(0, separatorIndex);\n const user = separatorIndex === -1 ? userKey : userKey.slice(separatorIndex + 1);\n return {\n user,\n platformUrl,\n current: currentUserKey === userKey,\n };\n}\n\nfunction formatUserListInfo(info: UserListInfo): string {\n return `${info.user}${info.platformUrl ? ` [${info.platformUrl}]` : \"\"}${\n info.current ? \" (current)\" : \"\"\n }`;\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all users.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n\n const users = Object.keys(config.users);\n if (users.length === 0) {\n logger.info(ml`\n No users found.\n Please login first using 'tailor login' command to register a user.\n `);\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const currentUserKey = activeCurrentUserKey(config);\n const userInfos = users.map((user) => toUserListInfo(user, currentUserKey));\n if (jsonOutput) {\n logger.out([...new Set(userInfos.map((userInfo) => userInfo.user))]);\n return;\n }\n\n userInfos.forEach((userInfo) => {\n if (userInfo.current) {\n logger.success(formatUserListInfo(userInfo), { mode: \"plain\" });\n } else {\n logger.log(formatUserListInfo(userInfo));\n }\n });\n },\n});\n","import { PATScope } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\nimport type { PersonalAccessToken } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n\nexport interface PersonalAccessTokenInfo {\n name: string;\n scopes: string[];\n}\n\nfunction patScopeToString(scope: PATScope): string {\n switch (scope) {\n case PATScope.PAT_SCOPE_READ:\n return \"read\";\n case PATScope.PAT_SCOPE_WRITE:\n return \"write\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * Transform a PersonalAccessToken into CLI-friendly info.\n * @param pat - Personal access token resource\n * @returns Flattened token info\n */\nexport function transformPersonalAccessToken(pat: PersonalAccessToken): PersonalAccessTokenInfo {\n return {\n name: pat.name,\n scopes: pat.scopes.map(patScopeToString),\n };\n}\n\n/**\n * Get PAT scopes from a write flag.\n * @param write - Whether write access is required\n * @returns Scopes to apply to the token\n */\nexport function getScopesFromWriteFlag(write: boolean): PATScope[] {\n return write ? [PATScope.PAT_SCOPE_READ, PATScope.PAT_SCOPE_WRITE] : [PATScope.PAT_SCOPE_READ];\n}\n\nfunction getScopeStringsFromWriteFlag(write: boolean): string[] {\n return write ? [\"read\", \"write\"] : [\"read\"];\n}\n\n/**\n * Print the created or updated personal access token to the logger.\n * @param name - Token name\n * @param token - Token value\n * @param write - Whether the token has write scope\n * @param action - Action performed\n */\nexport function printCreatedToken(\n name: string,\n token: string,\n write: boolean,\n action: \"created\" | \"updated\",\n): void {\n const scopes = getScopeStringsFromWriteFlag(write);\n\n if (logger.jsonMode) {\n logger.out({ name, scopes, token });\n } else {\n logger.log(ml`\n Personal access token ${action} successfully.\n\n name: ${name}\n scopes: ${scopes.join(\"/\")}\n token: ${token}\n\n Please save this token in a secure location. You won't be able to see it again.\n `);\n }\n}\n","import { initOperatorClient } from \"#/cli/shared/client\";\nimport {\n fetchLatestToken,\n platformConfigFromProfile,\n readPlatformConfig,\n} from \"#/cli/shared/context\";\n\ntype PlatformConfig = Awaited<ReturnType<typeof readPlatformConfig>>;\n\nexport function resolvePatUser(config: PlatformConfig): string | null {\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n if (activeProfile) {\n return config.profiles[activeProfile]?.user ?? null;\n }\n return config.current_user;\n}\n\nexport async function createPatOperatorClient() {\n const config = await readPlatformConfig();\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n const profileEntry = activeProfile ? config.profiles[activeProfile] : undefined;\n if (activeProfile && !profileEntry) {\n throw new Error(`Profile \"${activeProfile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const user = resolvePatUser(config);\n\n if (!user) {\n throw new Error(\"No user logged in.\\nPlease login first using 'tailor login' command.\");\n }\n\n const { accessToken } = await fetchLatestToken(config, user, platformConfig);\n return await initOperatorClient(accessToken, platformConfig);\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getScopesFromWriteFlag, printCreatedToken } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new personal access token.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n write: arg(z.boolean().default(false), {\n alias: \"W\",\n description: \"Grant write permission (default: read-only)\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n const scopes = getScopesFromWriteFlag(args.write);\n const result = await client.createPersonalAccessToken({\n name: args.name,\n scopes,\n });\n\n if (!result.accessToken) {\n throw new Error(\"Failed to create personal access token\");\n }\n\n printCreatedToken(args.name, result.accessToken, args.write, \"created\");\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a personal access token.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n await client.deletePersonalAccessToken({\n name: args.name,\n });\n\n logger.success(`Personal access token \"${args.name}\" deleted successfully.`);\n },\n});\n","import { z } from \"zod\";\nimport { paginationArgs, toPageDirection } from \"#/cli/shared/args\";\nimport { fetchPaged } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\nimport { transformPersonalAccessToken, type PersonalAccessTokenInfo } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all personal access tokens.\",\n args: z.strictObject({ ...paginationArgs() }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const client = await createPatOperatorClient();\n\n const pageDirection = toPageDirection(args.order);\n const pats = await fetchPaged(\n async (pageToken, pageSize) => {\n const { personalAccessTokens, nextPageToken } = await client.listPersonalAccessTokens({\n pageToken,\n pageSize,\n pageDirection,\n });\n return [personalAccessTokens, nextPageToken];\n },\n { limit: args.limit },\n );\n\n if (pats.length === 0) {\n logger.info(ml`\n No personal access tokens found.\n Please create a token using 'tailor user pat create' command.\n `);\n if (!jsonOutput) {\n return;\n }\n }\n\n const patInfos: PersonalAccessTokenInfo[] = pats.map(transformPersonalAccessToken);\n if (jsonOutput) {\n logger.out(patInfos);\n return;\n }\n\n // Text format: aligned list \"name: scope1/scope2\"\n const maxNameLength = Math.max(...pats.map((pat) => pat.name.length));\n\n pats.forEach((pat) => {\n const info = transformPersonalAccessToken(pat);\n const paddedName = info.name.padStart(maxNameLength);\n logger.log(`${paddedName}: ${info.scopes.join(\"/\")}`);\n });\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getScopesFromWriteFlag, printCreatedToken } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const updateCommand = defineAppCommand({\n name: \"update\",\n description: \"Update a personal access token (delete and recreate).\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n write: arg(z.boolean().default(false), {\n alias: \"W\",\n description: \"Grant write permission (if not specified, keeps read-only)\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n // Delete the existing token\n await client.deletePersonalAccessToken({\n name: args.name,\n });\n\n // Create a new token with the same name\n const scopes = getScopesFromWriteFlag(args.write);\n const result = await client.createPersonalAccessToken({\n name: args.name,\n scopes,\n });\n\n if (!result.accessToken) {\n throw new Error(\"Failed to create personal access token\");\n }\n\n printCreatedToken(args.name, result.accessToken, args.write, \"updated\");\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport const patCommand = defineCommand({\n name: \"pat\",\n description: \"Manage personal access tokens.\",\n subCommands: {\n list: listCommand,\n create: createCommand,\n delete: deleteCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n resolveConfigUser,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\nexport const switchCommand = defineAppCommand({\n name: \"switch\",\n description: \"Set current user.\",\n args: z.strictObject({\n user: arg(z.string(), {\n positional: true,\n description: \"User email address or machine user client ID\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const activeProfileName = process.env.TAILOR_PLATFORM_PROFILE;\n const activeProfileEntry = activeProfileName ? config.profiles[activeProfileName] : undefined;\n if (activeProfileName && !activeProfileEntry) {\n throw new Error(`Profile \"${activeProfileName}\" not found`);\n }\n const platformConfig = activeProfileEntry\n ? platformConfigFromProfile(activeProfileEntry)\n : undefined;\n\n if (args.user.includes(\"|\")) {\n throw new Error(\n `User \"${args.user}\" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,\n );\n }\n\n const user = resolveConfigUser(config, args.user, platformConfig);\n if (!user) {\n throw new Error(ml`\n User \"${args.user}\" not found.\n Please login first using 'tailor login' command to register this user.\n `);\n }\n\n if (activeProfileEntry) {\n activeProfileEntry.user = user;\n } else {\n config.current_user = user;\n }\n writePlatformConfig(config);\n\n logger.success(`Current user set to \"${user}\" successfully.`);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { currentCommand } from \"./current\";\nimport { listCommand } from \"./list\";\nimport { patCommand } from \"./pat\";\nimport { switchCommand } from \"./switch\";\n\nexport const userCommand = defineCommand({\n name: \"user\",\n description: \"Manage Tailor Platform users.\",\n subCommands: {\n current: currentCommand,\n list: listCommand,\n switch: switchCommand,\n pat: patCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { executionsCommand } from \"./executions\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { resumeCommand } from \"./resume\";\nimport { startCommand } from \"./start\";\nimport { waitCommand } from \"./wait\";\n\nexport const workflowCommand = defineCommand({\n name: \"workflow\",\n description: \"Manage workflows and workflow executions.\",\n subCommands: {\n list: listCommand,\n get: getCommand,\n start: startCommand,\n wait: waitCommand,\n executions: executionsCommand,\n resume: resumeCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { healthCommand } from \"./health\";\nimport { listCommand } from \"./list\";\n\nexport const appCommand = defineCommand({\n name: \"app\",\n description: \"Manage workspace applications\",\n subCommands: {\n health: healthCommand,\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { inviteCommand } from \"./invite\";\nimport { listCommand } from \"./list\";\nimport { removeCommand } from \"./remove\";\nimport { updateCommand } from \"./update\";\n\nexport const userCommand = defineCommand({\n name: \"user\",\n description: \"Manage workspace users\",\n subCommands: {\n invite: inviteCommand,\n list: listCommand,\n remove: removeCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { appCommand } from \"./app\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { restoreCommand } from \"./restore\";\nimport { userCommand } from \"./user\";\n\nexport const workspaceCommand = defineCommand({\n name: \"workspace\",\n description: \"Manage Tailor Platform workspaces.\",\n subCommands: {\n app: appCommand,\n create: createCommand,\n delete: deleteCommand,\n get: getCommand,\n list: listCommand,\n restore: restoreCommand,\n user: userCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","#!/usr/bin/env node\n\nimport { dirname, resolve } from \"pathe\";\nimport { resolvePackageJSON } from \"pkg-types\";\nimport { defineCommand, runCommand, runMain, type AnyCommand } from \"politty\";\nimport { withCompletionCommand } from \"politty/completion\";\nimport { withSkillCommand } from \"politty/skill\";\nimport { z } from \"zod\";\nimport { apiCommand } from \"./commands/api\";\nimport { authCommand } from \"./commands/auth\";\nimport { authconnectionCommand } from \"./commands/authconnection\";\nimport { crashReportCommand } from \"./commands/crashreport\";\nimport { deployCommand } from \"./commands/deploy\";\nimport { executorCommand } from \"./commands/executor\";\nimport { functionCommand } from \"./commands/function\";\nimport { generateCommand } from \"./commands/generate\";\nimport { initCommand } from \"./commands/init\";\nimport { loginCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { machineuserCommand } from \"./commands/machineuser\";\nimport { oauth2clientCommand } from \"./commands/oauth2client\";\nimport { openCommand } from \"./commands/open\";\nimport { organizationCommand } from \"./commands/organization\";\nimport { pluginCommand } from \"./commands/plugin\";\nimport { profileCommand } from \"./commands/profile\";\nimport { removeCommand } from \"./commands/remove\";\nimport { secretCommand } from \"./commands/secret\";\nimport { setupCommand } from \"./commands/setup\";\nimport { showCommand } from \"./commands/show\";\nimport { staticwebsiteCommand } from \"./commands/staticwebsite\";\nimport { tailordbCommand } from \"./commands/tailordb\";\nimport { upgradeCommand } from \"./commands/upgrade\";\nimport { userCommand } from \"./commands/user\";\nimport { workflowCommand } from \"./commands/workflow\";\nimport { workspaceCommand } from \"./commands/workspace\";\nimport { initCrashReporting } from \"./crashreport\";\nimport { queryCommand } from \"./query\";\nimport { commonArgs, isVerbose } from \"./shared/args\";\nimport { serializeError } from \"./shared/error-json\";\nimport { isCLIError } from \"./shared/errors\";\nimport { logger } from \"./shared/logger\";\nimport { readPackageJson } from \"./shared/package-json\";\nimport { dispatchPluginWithInstallHint } from \"./shared/plugin\";\nimport { registerTsHook } from \"./shared/register-ts-hook\";\n\nawait registerTsHook(new URL(\"./ts-hook.mjs\", import.meta.url));\n\n// Runs before globalArgs effects load --env-file, so env file overrides for\n// TAILOR_CRASH_REPORTS_* are not available for early startup failures.\n// This is intentional: we want crash reporting active before argument parsing,\n// and env files require parsing to be complete. Shell-level env vars still work.\ninitCrashReporting();\n\nconst packageJson = await readPackageJson();\nconst cliName = Object.keys(packageJson.bin ?? {})[0] || \"tailor\";\nconst packageName = packageJson.name ?? \"@tailor-platform/sdk\";\nconst packageJsonPath = await resolvePackageJSON(import.meta.url);\nconst bundledSkillsDir = resolve(dirname(packageJsonPath), \"agent-skills\");\n\nfunction defaultSkillsRunToAdd(command: AnyCommand): AnyCommand {\n const add = (command.subCommands ?? {}).add as AnyCommand;\n return {\n ...command,\n async run() {\n const result = await runCommand(add, []);\n if (!result.success) {\n throw result.error;\n }\n },\n };\n}\n\nconst commandWithSkills = withSkillCommand(\n defineCommand({\n name: cliName,\n description:\n packageJson.description || \"Tailor CLI for managing Tailor Platform SDK applications\",\n notes: `CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \\`${cliName}-<name>\\` (found on your PATH or in node_modules/.bin), similar to \\`gh\\` extensions.\nRun \\`${cliName} plugin list\\` to see which plugins are installed and where they resolve from.`,\n subCommands: {\n api: apiCommand,\n auth: authCommand,\n authconnection: authconnectionCommand,\n crashreport: crashReportCommand,\n deploy: deployCommand,\n executor: executorCommand,\n function: functionCommand,\n generate: generateCommand,\n init: initCommand,\n login: loginCommand,\n logout: logoutCommand,\n machineuser: machineuserCommand,\n oauth2client: oauth2clientCommand,\n open: openCommand,\n organization: organizationCommand,\n plugin: pluginCommand,\n profile: profileCommand,\n query: queryCommand,\n remove: removeCommand,\n secret: secretCommand,\n setup: setupCommand,\n show: showCommand,\n staticwebsite: staticwebsiteCommand,\n tailordb: tailordbCommand,\n upgrade: upgradeCommand,\n user: userCommand,\n workflow: workflowCommand,\n workspace: workspaceCommand,\n },\n }),\n {\n sourceDir: bundledSkillsDir,\n package: packageName,\n mode: \"copy\",\n descriptionAppend: false,\n // strip unknown keys\n globalArgs: z.object(commonArgs),\n commandMap: { add: [\"add\"], remove: [\"remove\"] },\n unknownKeys: \"strict\",\n descriptions: {\n skills: \"Manage Tailor SDK agent skills.\",\n add: \"Install Tailor SDK agent skills.\",\n list: \"List Tailor SDK agent skills.\",\n remove: \"Remove installed Tailor SDK agent skills.\",\n sync: \"Remove and reinstall Tailor SDK agent skills.\",\n },\n },\n);\n\nexport const mainCommand = withCompletionCommand({\n ...commandWithSkills,\n subCommands: {\n ...commandWithSkills.subCommands,\n skills: defaultSkillsRunToAdd(commandWithSkills.subCommands.skills),\n },\n});\n\nrunMain(mainCommand, {\n version: packageJson.version,\n // strip unknown keys\n globalArgs: z.object(commonArgs),\n displayErrors: false,\n // CLI plugin dispatch: an unknown subcommand at any level execs the external\n // `tailor-<path...>-<name>` binary, forwarding args and injecting context.\n onUnknownSubcommand: ({ commandPath, name, args }) =>\n dispatchPluginWithInstallHint({\n commandPath,\n name,\n args,\n cliName,\n profile: process.env.TAILOR_PLATFORM_PROFILE,\n }),\n cleanup: async ({ error }) => {\n if (error) {\n if (logger.jsonMode) {\n logger.log(serializeError(error, { includeStack: isVerbose() }));\n } else if (isCLIError(error)) {\n logger.log(error.format());\n if (isVerbose() && error.stack) {\n logger.debug(`\\nStack trace:\\n${error.stack}`);\n }\n } else if (error instanceof Error) {\n logger.error(error.message);\n if (isVerbose() && error.stack) {\n logger.debug(`\\nStack trace:\\n${error.stack}`);\n }\n } else {\n logger.error(`Unknown error: ${error}`);\n }\n\n // Report programming bugs (native error types that indicate code defects).\n // Skip domain errors like ConnectError, CIPromptError, and plain Error\n // used for user-facing validation/not-found messages.\n // Exclude SyntaxError/ReferenceError: at runtime these typically come from\n // dynamically imported user config files, not from SDK code.\n const shouldReport =\n !isCLIError(error) &&\n (!(error instanceof Error) || error instanceof TypeError || error instanceof RangeError);\n if (shouldReport) {\n // Lazy import to match shutdownTelemetry pattern and keep cleanup handler lightweight.\n const { reportCrash } = await import(\"#/cli/crashreport/index\");\n await reportCrash(error, \"handledError\");\n }\n }\n const { shutdownTelemetry } = await import(\"#/cli/telemetry/index\");\n await shutdownTelemetry();\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAM,gBAAmC,gBAAgB,QAAQ,QAC9D,MAA4B,EAAE,eAAe,OAChD;AAEA,SAAgB,kBAA4B;CAC1C,OAAO,cAAc,KAAK,MAAM,EAAE,IAAI,CAAC,CAAC,SAAS;AACnD;;;;;;;;;AAUA,SAAgB,oBAA8B;CAC5C,OAAO,cAAc,SAAS,MAAM,CAAC,EAAE,MAAM,GAAG,gBAAgB,SAAS,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,SAAS;AAClG;AAEA,SAAgB,oBAAoB,YAAiD;CACnF,OAAO,cAAc,MAAM,MAAM,EAAE,SAAS,UAAU;AACxD;AAEA,SAAgB,kBAAkB,UAA0B;CAC1D,IAAI,CAAC,SAAS,SAAS,GAAG,GAAG,OAAO;CACpC,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;AACtC;;;;;;;AAQA,SAAgB,cAAc,OAA2C;CACvE,IAAI,MAAM,cAAc,WAAW,OAAO,MAAM;CAChD,IAAI,MAAM,cAAc,UAAU,MAAM,aAAa,WAAW,OAAO,MAAM;CAC7E,IAAI,MAAM,cAAc,SAAS,MAAM,YAAY,WAAW,OAAO,MAAM;AAE7E;;;;;;;;;;AAWA,SAAS,gBAAgB,SAA+B;CACtD,OAAO,QAAQ,SAAS,WAAW,kBAAkB;AACvD;AAOA,MAAM,mDAAmC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;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AO;IAC1B,IAAI,UAAU,KAAK,MAAM,OACvB,OAAO,MAAM,mBAAmB,MAAM,OAAO;GAEjD,OACE,OAAO,MAAM,kBAAkB,OAAO;GAWxC,IAFE,CAAC,WAAW,KAAK,MAChB,EAAE,iBAAiB,UAAU,iBAAiB,aAAa,iBAAiB,aAC7D;IAEhB,MAAM,EAAE,gBAAgB,MAAM,OAAO;IACrC,MAAM,YAAY,OAAO,cAAc;GACzC;EACF;EACA,MAAM,EAAE,sBAAsB,MAAM,OAAO;EAC3C,MAAM,kBAAkB;CAC1B;AACF,CAAC"}
1
+ {"version":3,"file":"main.mjs","names":["CLIError","listCommand","listCommand","randomState","listCommand","listCommand","listCommand","getCommand","getCommand","listCommand","detectPackageManager","listCommand","tokenCommand","listCommand","getCommand","createCommand","deleteCommand","getCommand","listCommand","updateCommand","getCommand","listCommand","updateCommand","listCommand","listCommand","createCommand","deleteCommand","listCommand","updateCommand","createCommand","deleteCommand","listCommand","updateCommand","createCommand","deleteCommand","listCommand","createCommand","deleteCommand","listCommand","branchTemplate","tagTemplate","previewTemplate","actionTemplate","coordinateTemplate","defaultLoadErdNamespaces","defaultLoadHasMigrations","defaultLoadHasSeeds","defaultLoadHasStaticWebsites","escapesRoot","resolve","deleteCommand","listCommand","deployCommand","listCommand","generateCommand","listCommand","userCommand","listCommand","listCommand","getCommand","listCommand","listCommand","updateCommand","createCommand","deleteCommand","getCommand","listCommand","removeCommand","userCommand"],"sources":["../../src/cli/commands/api/proto-reflect.ts","../../src/cli/commands/api/render.ts","../../src/cli/commands/api/inspect.ts","../../src/cli/commands/api/list.ts","../../src/cli/commands/api/index.ts","../../src/cli/commands/auth/token.ts","../../src/cli/commands/auth/index.ts","../../src/cli/commands/authconnection/args.ts","../../src/cli/commands/authconnection/authorize.ts","../../src/cli/commands/authconnection/delete.ts","../../src/cli/commands/authconnection/list.ts","../../src/cli/commands/authconnection/open.ts","../../src/cli/commands/authconnection/revoke.ts","../../src/cli/commands/authconnection/index.ts","../../src/cli/commands/crashreport/list.ts","../../src/cli/commands/crashreport/send.ts","../../src/cli/commands/crashreport/index.ts","../../src/cli/commands/deploy/index.ts","../../src/cli/commands/executor/index.ts","../../src/cli/shared/function-script-download.ts","../../src/cli/shared/stack-trace.ts","../../src/cli/commands/function/logs.ts","../../src/cli/commands/function/bundle.ts","../../src/cli/commands/function/detect.ts","../../src/cli/commands/function/test-run.ts","../../src/cli/commands/function/index.ts","../../src/cli/commands/generate/index.ts","../../src/cli/commands/init.ts","../../src/cli/commands/login.ts","../../src/cli/commands/logout.ts","../../src/cli/commands/machineuser/index.ts","../../src/cli/commands/oauth2client/index.ts","../../src/cli/commands/open.ts","../../src/cli/commands/organization/folder/index.ts","../../src/cli/commands/organization/index.ts","../../src/cli/shared/builtin-commands.ts","../../src/cli/shared/plugin.ts","../../src/cli/commands/plugin/list.ts","../../src/cli/commands/plugin/index.ts","../../src/cli/commands/profile/create.ts","../../src/cli/commands/profile/delete.ts","../../src/cli/commands/profile/list.ts","../../src/cli/commands/profile/update.ts","../../src/cli/commands/profile/index.ts","../../src/cli/commands/secret/args.ts","../../src/cli/commands/secret/check-vault-managed.ts","../../src/cli/commands/secret/create.ts","../../src/cli/commands/secret/delete.ts","../../src/cli/commands/secret/list.ts","../../src/cli/commands/secret/update.ts","../../src/cli/commands/secret/vault/args.ts","../../src/cli/commands/secret/vault/create.ts","../../src/cli/commands/secret/vault/delete.ts","../../src/cli/commands/secret/vault/list.ts","../../src/cli/commands/secret/vault/index.ts","../../src/cli/commands/secret/index.ts","../../src/cli/commands/setup/git.ts","../../src/cli/commands/setup/lock.ts","../../src/cli/commands/setup/action.yml","../../src/cli/commands/setup/branch.workflow.yml","../../src/cli/commands/setup/coordinate.workflow.yml","../../src/cli/commands/setup/preview.workflow.yml","../../src/cli/commands/setup/tag.workflow.yml","../../src/cli/commands/setup/templates.ts","../../src/cli/commands/setup/generate.ts","../../src/cli/commands/setup/check.ts","../../src/cli/commands/setup/delete.ts","../../src/cli/commands/setup/renovate.ts","../../src/cli/commands/setup/index.ts","../../src/cli/commands/staticwebsite/domain/status.ts","../../src/cli/commands/staticwebsite/domain/get.ts","../../src/cli/commands/staticwebsite/domain/list.ts","../../src/cli/commands/staticwebsite/domain/index.ts","../../src/cli/commands/staticwebsite/get.ts","../../src/cli/commands/staticwebsite/list.ts","../../src/cli/commands/staticwebsite/index.ts","../../src/cli/commands/tailordb/migrate/rebaseline.ts","../../src/cli/commands/tailordb/migrate/set.ts","../../src/cli/commands/tailordb/migrate/status.ts","../../src/cli/commands/tailordb/migrate/sync.ts","../../src/cli/commands/tailordb/migrate/test-runtime.ts","../../src/cli/commands/tailordb/migrate/test.ts","../../src/cli/commands/tailordb/migrate/validate.ts","../../src/cli/commands/tailordb/migrate/index.ts","../../src/cli/commands/tailordb/index.ts","../../src/cli/commands/upgrade/index.ts","../../src/cli/commands/user/current.ts","../../src/cli/commands/user/list.ts","../../src/cli/commands/user/pat/transform.ts","../../src/cli/commands/user/pat/user.ts","../../src/cli/commands/user/pat/create.ts","../../src/cli/commands/user/pat/delete.ts","../../src/cli/commands/user/pat/list.ts","../../src/cli/commands/user/pat/update.ts","../../src/cli/commands/user/pat/index.ts","../../src/cli/commands/user/switch.ts","../../src/cli/commands/user/index.ts","../../src/cli/commands/workflow/index.ts","../../src/cli/commands/workspace/app/index.ts","../../src/cli/commands/workspace/user/index.ts","../../src/cli/commands/workspace/index.ts","../../src/cli/main.ts"],"sourcesContent":["import { ScalarType } from \"@bufbuild/protobuf\";\nimport { OperatorService } from \"@tailor-platform/tailor-proto/service_pb\";\nimport type { DescField, DescMessage, DescMethodUnary } from \"@bufbuild/protobuf\";\n\n// `tailor api` issues a single JSON POST and reads one JSON response, so\n// only unary RPCs can be invoked. Streaming methods are filtered out of all\n// discovery surfaces (`api list`, `api inspect`). `OperatorService.methods`\n// is invariant at runtime, so we filter once and reuse — completion-script\n// generation walks every method and would otherwise re-filter per call.\nconst UNARY_METHODS: DescMethodUnary[] = OperatorService.methods.filter(\n (m): m is DescMethodUnary => m.methodKind === \"unary\",\n);\n\nexport function listMethodNames(): string[] {\n return UNARY_METHODS.map((m) => m.name).toSorted();\n}\n\n/**\n * Returns every accepted form of the `endpoint` positional — bare method name\n * and fully-qualified `service/Method`. politty's expand completion keys its\n * static table by the literal endpoint string, so both forms must appear in\n * `choices` or the user typing the fully-qualified name gets no `--field`\n * completion candidates back at TAB time.\n * @returns Sorted list of accepted endpoint values\n */\nexport function listMethodChoices(): string[] {\n return UNARY_METHODS.flatMap((m) => [m.name, `${OperatorService.typeName}/${m.name}`]).toSorted();\n}\n\nexport function getMethodDescriptor(methodName: string): DescMethodUnary | undefined {\n return UNARY_METHODS.find((m) => m.name === methodName);\n}\n\nexport function extractMethodName(endpoint: string): string {\n if (!endpoint.includes(\"/\")) return endpoint;\n return endpoint.split(\"/\").pop() ?? endpoint;\n}\n\n/**\n * Returns the nested message descriptor when the field is a message, a list of\n * messages, or a map with message values. Otherwise returns undefined.\n * @param field - The proto field descriptor to inspect\n * @returns The nested message descriptor, or undefined when the field isn't message-shaped\n */\nexport function nestedMessage(field: DescField): DescMessage | undefined {\n if (field.fieldKind === \"message\") return field.message;\n if (field.fieldKind === \"list\" && field.listKind === \"message\") return field.message;\n if (field.fieldKind === \"map\" && field.mapKind === \"message\") return field.message;\n return undefined;\n}\n\n/**\n * Most `google.protobuf.*` well-known types serialize as scalars in proto JSON\n * (Timestamp/Duration → RFC3339/duration string, FieldMask → comma-joined\n * string, *Value wrappers → underlying primitive, etc.), so we must not let\n * `--field` drill into their internal fields. Treating them as leaves keeps\n * the completion and the body shape consistent with what the server expects.\n * @param message - The proto message descriptor to inspect\n * @returns True when the message is a well-known type\n */\nfunction isWellKnownType(message: DescMessage): boolean {\n return message.typeName.startsWith(\"google.protobuf.\");\n}\n\n// Well-known types whose proto JSON shape is an object/array/null/arbitrary\n// value — they cannot be expressed by a single `--field key=value` string.\n// Drill-down would build the wrong shape, and a flat `key=foo` would send\n// \"foo\" where the server expects e.g. an object; we skip them entirely from\n// completion and from leaf resolution.\nconst UNREPRESENTABLE_WELL_KNOWN_TYPES = new Set([\n \"google.protobuf.Struct\",\n \"google.protobuf.Value\",\n \"google.protobuf.ListValue\",\n \"google.protobuf.NullValue\",\n \"google.protobuf.Any\",\n \"google.protobuf.Empty\",\n]);\n\n/**\n * @param message - The proto message descriptor to inspect\n * @returns True when the message is a well-known type that `--field` cannot represent\n */\nfunction isUnrepresentableWellKnownType(message: DescMessage): boolean {\n return UNREPRESENTABLE_WELL_KNOWN_TYPES.has(message.typeName);\n}\n\nexport interface FieldCompletionCandidate {\n value: string;\n description: string;\n}\n\n/**\n * Pre-enumerates every `--field` completion candidate for `methodName`,\n * walking the input message tree to produce a flat list that the shell can\n * prefix-filter at TAB time. Used by the `expand` completion variant so no\n * Node process is spawned per keystroke.\n *\n * For each leaf field, emits `key=` (key completion). Enum leaves additionally\n * emit `key=ENUM_VALUE` per value, bool leaves emit `key=true` and\n * `key=false`. For nested messages, emits `key.` (drill-down) and recurses.\n *\n * Returns an empty array when `methodName` is unknown so the `expand`\n * generator stays exception-free at script-generation time.\n * @param methodName - Name of the unary RPC whose input message is being walked\n * @returns Flat list of `{ value, description }` candidates\n */\nexport function enumerateAllFieldCompletions(methodName: string): FieldCompletionCandidate[] {\n const method = getMethodDescriptor(methodName);\n if (!method) return [];\n\n const candidates: FieldCompletionCandidate[] = [];\n const visited = new Set<DescMessage>();\n\n function walk(message: DescMessage, prefix: string): void {\n visited.add(message);\n for (const field of message.fields) {\n // `--field` uses `key=value` with dotted keys building nested objects;\n // it has no syntax for arrays or maps. Skip list/map fields so we don't\n // tab-complete a path that `setNestedPath` would silently turn into the\n // wrong shape (e.g. `subgraphs.name=x` → `{subgraphs:{name:\"x\"}}` when\n // the proto expects a repeated message).\n if (field.fieldKind === \"list\" || field.fieldKind === \"map\") continue;\n const fullKey = prefix + field.localName;\n if (field.fieldKind === \"message\") {\n if (isUnrepresentableWellKnownType(field.message)) continue;\n if (!isWellKnownType(field.message)) {\n const nested = field.message;\n candidates.push({ value: `${fullKey}.`, description: `${fullKey} (message)` });\n if (!visited.has(nested)) walk(nested, `${fullKey}.`);\n continue;\n }\n // Representable well-known types (Timestamp, Duration, FieldMask, …)\n // fall through to a single `key=` leaf since proto JSON serializes\n // them as a scalar string.\n }\n candidates.push({ value: `${fullKey}=`, description: `Set ${fullKey}` });\n if (field.fieldKind === \"enum\") {\n for (const v of field.enum.values) {\n candidates.push({ value: `${fullKey}=${v.name}`, description: v.name });\n }\n } else if (field.fieldKind === \"scalar\" && field.scalar === ScalarType.BOOL) {\n candidates.push({ value: `${fullKey}=true`, description: \"true\" });\n candidates.push({ value: `${fullKey}=false`, description: \"false\" });\n }\n }\n visited.delete(message);\n }\n\n walk(method.input, \"\");\n return candidates;\n}\n\n/**\n * Resolves the leaf `DescField` at a dotted `--field` path within an input\n * message tree. Returns undefined when any segment is missing or when a\n * non-leaf segment isn't a singular message — callers fall back to treating\n * the value as a string in that case.\n * @param input - The RPC input message descriptor\n * @param path - Dot-split path segments to follow (e.g. [\"application\", \"name\"])\n * @returns The leaf field descriptor, or undefined when the path doesn't resolve\n */\nexport function resolveLeafField(input: DescMessage, path: string[]): DescField | undefined {\n let message = input;\n for (let i = 0; i < path.length; i++) {\n const field = message.fields.find((f) => f.localName === path[i]);\n if (!field) return undefined;\n if (i === path.length - 1) {\n // Refuse to resolve a leaf inside an unrepresentable well-known type —\n // even if the user typed `payload=...` for a Struct field manually,\n // we don't want to claim a scalar shape we can't actually coerce.\n if (field.fieldKind === \"message\" && isUnrepresentableWellKnownType(field.message)) {\n return undefined;\n }\n return field;\n }\n // Mirror enumerateAllFieldCompletions: don't drill into list/map fields\n // or well-known types — `--field` cannot represent their internal shape.\n if (field.fieldKind !== \"message\") return undefined;\n if (isWellKnownType(field.message)) return undefined;\n message = field.message;\n }\n return undefined;\n}\n","import { ScalarType } from \"@bufbuild/protobuf\";\nimport { nestedMessage } from \"./proto-reflect\";\nimport type { DescEnum, DescField, DescMessage, DescMethodUnary } from \"@bufbuild/protobuf\";\n\nexport interface InspectMessageJson {\n typeName: string;\n fields: InspectFieldJson[];\n /** True when truncated to break a recursive type cycle. */\n recursive?: boolean;\n}\n\nexport interface InspectFieldJson {\n name: string;\n protoName: string;\n type: string;\n fieldKind: string;\n repeated: boolean;\n enumValues?: string[];\n /** Name of the proto `oneof` group this field belongs to, if any. */\n oneof?: string;\n message?: InspectMessageJson | undefined;\n}\n\nexport interface InspectMethodJson {\n method: string;\n input: {\n typeName: string;\n fields: InspectFieldJson[];\n };\n output: {\n typeName: string;\n };\n}\n\nconst SCALAR_LABEL: Partial<Record<number, string>> = {\n [ScalarType.DOUBLE]: \"double\",\n [ScalarType.FLOAT]: \"float\",\n [ScalarType.INT64]: \"int64\",\n [ScalarType.UINT64]: \"uint64\",\n [ScalarType.INT32]: \"int32\",\n [ScalarType.FIXED64]: \"fixed64\",\n [ScalarType.FIXED32]: \"fixed32\",\n [ScalarType.BOOL]: \"bool\",\n [ScalarType.STRING]: \"string\",\n [ScalarType.BYTES]: \"bytes\",\n [ScalarType.UINT32]: \"uint32\",\n [ScalarType.SFIXED32]: \"sfixed32\",\n [ScalarType.SFIXED64]: \"sfixed64\",\n [ScalarType.SINT32]: \"sint32\",\n [ScalarType.SINT64]: \"sint64\",\n};\n\nfunction shortName(typeName: string): string {\n const dot = typeName.lastIndexOf(\".\");\n return dot < 0 ? typeName : typeName.slice(dot + 1);\n}\n\nfunction scalarLabel(scalar: ScalarType): string {\n return SCALAR_LABEL[scalar] ?? `scalar(${scalar})`;\n}\n\nfunction enumLabel(enumDesc: DescEnum): string {\n return `enum ${shortName(enumDesc.typeName)}`;\n}\n\nfunction enumOf(field: DescField): DescEnum | undefined {\n if (field.fieldKind === \"enum\") return field.enum;\n if (field.fieldKind === \"list\" && field.listKind === \"enum\") return field.enum;\n return undefined;\n}\n\nexport function describeFieldType(field: DescField): string {\n switch (field.fieldKind) {\n case \"scalar\":\n return scalarLabel(field.scalar);\n case \"enum\":\n return enumLabel(field.enum);\n case \"message\":\n return shortName(field.message.typeName);\n case \"list\": {\n let inner: string;\n if (field.listKind === \"scalar\") {\n inner = scalarLabel(field.scalar);\n } else if (field.listKind === \"enum\") {\n inner = enumLabel(field.enum);\n } else {\n inner = shortName(field.message.typeName);\n }\n return `repeated ${inner}`;\n }\n case \"map\": {\n const keyType = scalarLabel(field.mapKey);\n let valType: string;\n if (field.mapKind === \"scalar\") valType = scalarLabel(field.scalar);\n else if (field.mapKind === \"enum\") valType = enumLabel(field.enum);\n else valType = shortName(field.message.typeName);\n return `map<${keyType}, ${valType}>`;\n }\n default:\n return \"<unknown>\";\n }\n}\n\nfunction fieldToJson(field: DescField, visited: Set<DescMessage>): InspectFieldJson {\n const json: InspectFieldJson = {\n name: field.localName,\n protoName: field.name,\n type: describeFieldType(field),\n fieldKind: field.fieldKind,\n repeated: field.fieldKind === \"list\",\n };\n\n if (field.oneof) json.oneof = field.oneof.name;\n\n const fieldEnum = enumOf(field);\n if (fieldEnum) {\n json.enumValues = fieldEnum.values.map((v) => v.name);\n }\n\n const nested = nestedMessage(field);\n if (nested && !visited.has(nested)) {\n visited.add(nested);\n json.message = {\n typeName: nested.typeName,\n fields: nested.fields.map((f) => fieldToJson(f, visited)),\n };\n visited.delete(nested);\n } else if (nested) {\n json.message = { typeName: nested.typeName, fields: [], recursive: true };\n }\n\n return json;\n}\n\nexport function renderInspectJson(method: DescMethodUnary): InspectMethodJson {\n const visited = new Set<DescMessage>([method.input]);\n return {\n method: method.name,\n input: {\n typeName: method.input.typeName,\n fields: method.input.fields.map((f) => fieldToJson(f, visited)),\n },\n output: { typeName: method.output.typeName },\n };\n}\n\nfunction renderFieldText(field: DescField, indent: string, visited: Set<DescMessage>): string[] {\n const lines: string[] = [];\n const oneofTag = field.oneof ? ` (oneof ${field.oneof.name})` : \"\";\n lines.push(`${indent}${field.localName}: ${describeFieldType(field)}${oneofTag}`);\n\n const fieldEnum = enumOf(field);\n if (fieldEnum) {\n const values = fieldEnum.values.map((v) => v.name).join(\", \");\n lines.push(`${indent} values: ${values}`);\n }\n\n const nested = nestedMessage(field);\n if (nested && !visited.has(nested)) {\n visited.add(nested);\n for (const sub of nested.fields) {\n lines.push(...renderFieldText(sub, `${indent} `, visited));\n }\n visited.delete(nested);\n } else if (nested) {\n lines.push(`${indent} …(recursive ${nested.typeName})`);\n }\n\n return lines;\n}\n\nexport function renderInspectText(method: DescMethodUnary): string {\n const lines: string[] = [];\n lines.push(`${method.name}`);\n lines.push(` request: ${method.input.typeName}`);\n const visited = new Set<DescMessage>([method.input]);\n for (const f of method.input.fields) {\n lines.push(...renderFieldText(f, \" \", visited));\n }\n lines.push(` response: ${method.output.typeName}`);\n return lines.join(\"\\n\");\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { CLIError } from \"#/cli/shared/errors\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { extractMethodName, getMethodDescriptor, listMethodNames } from \"./proto-reflect\";\nimport { renderInspectJson, renderInspectText } from \"./render\";\n\nexport const inspectCommand = defineAppCommand({\n name: \"inspect\",\n description: \"Print the input message tree of an OperatorService endpoint.\",\n notes:\n \"Combine with the global `--json` flag for a machine-readable descriptor. Recursive type references and `oneof` membership are annotated. Use `tailor api list` to discover endpoint names.\",\n examples: [\n { cmd: \"GetApplication\", desc: \"Show fields of GetApplicationRequest.\" },\n {\n cmd: \"CreateExecutorExecutor\",\n desc: \"Inspect a deeply nested input with `(oneof config)` annotations.\",\n },\n ],\n args: z.strictObject({\n endpoint: arg(z.string(), {\n positional: true,\n description:\n \"API endpoint to inspect (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').\",\n completion: { custom: { choices: listMethodNames() } },\n }),\n }),\n run: (args) => {\n const methodName = extractMethodName(args.endpoint);\n const method = getMethodDescriptor(methodName);\n if (!method) {\n throw CLIError({\n message: `unknown method: ${methodName}`,\n suggestion: \"Run `tailor api list` to see available methods.\",\n command: \"api inspect\",\n });\n }\n if (logger.jsonMode) {\n logger.out(renderInspectJson(method));\n } else {\n logger.out(renderInspectText(method));\n }\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { listMethodNames } from \"./proto-reflect\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all invocable OperatorService methods.\",\n notes:\n \"Only single-request (non-streaming) methods are listed, because the CLI issues a single JSON request and reads one JSON response.\",\n args: z.strictObject({}),\n run: () => {\n const names = listMethodNames();\n if (logger.jsonMode) {\n logger.out(names);\n } else {\n for (const name of names) logger.out(name);\n }\n },\n});\n","import { ScalarType } from \"@bufbuild/protobuf\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { configArg, workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { apiCall } from \"./api-call\";\nimport { inspectCommand } from \"./inspect\";\nimport { listCommand } from \"./list\";\nimport {\n enumerateAllFieldCompletions,\n extractMethodName,\n getMethodDescriptor,\n listMethodChoices,\n resolveLeafField,\n} from \"./proto-reflect\";\nimport type { LoadedConfig } from \"#/cli/shared/config-loader\";\nimport type { DescField } from \"@bufbuild/protobuf\";\n\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./api-call\";\n\nfunction resolveNamespaceName(methodName: string, config: LoadedConfig): string | undefined {\n if (/Auth|Tenant|UserProfile/.test(methodName)) {\n return config.auth?.name;\n }\n if (/IdP/.test(methodName)) {\n if (config.idp?.length === 1) return assertDefined(config.idp[0], \"idp config missing\").name;\n return undefined;\n }\n if (/TailorDB/.test(methodName)) {\n const keys = Object.keys(config.db ?? {});\n if (keys.length === 1) return keys[0];\n return undefined;\n }\n if (/Pipeline/.test(methodName)) {\n const keys = Object.keys(config.resolver ?? {});\n if (keys.length === 1) return keys[0];\n return undefined;\n }\n return undefined;\n}\n\n/**\n * Parse a JSON body string as a plain object for field injection.\n * Returns undefined for invalid JSON or non-object values (null, arrays, primitives),\n * so callers can fall back to sending the raw string unchanged.\n * @param body - Raw body string\n * @returns Parsed object or undefined\n */\nfunction parseBodyAsObject(body: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return undefined;\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Set a dotted path on a body object, replacing non-object intermediates as\n * needed. `--field` takes precedence over `--body`, so collisions overwrite.\n * @param obj - The body object to mutate\n * @param path - Dot-split path segments (e.g. [\"application\", \"name\"])\n * @param value - Value to assign at the leaf\n */\nfunction setNestedPath(obj: Record<string, unknown>, path: string[], value: unknown): void {\n let cursor: Record<string, unknown> = obj;\n for (let i = 0; i < path.length - 1; i++) {\n const key = assertDefined(path[i], \"path segment missing\");\n const next = cursor[key];\n if (typeof next !== \"object\" || next === null || Array.isArray(next)) {\n cursor[key] = {};\n }\n cursor = cursor[key] as Record<string, unknown>;\n }\n cursor[assertDefined(path[path.length - 1], \"path last segment missing\")] = value;\n}\n\n/**\n * Coerces a raw `--field` string value to match the leaf proto type so the\n * JSON body sends a properly typed value. Today we only coerce bool — the\n * completion candidates explicitly suggest `=true`/`=false`, so sending the\n * literal string \"true\" would be a visible mismatch. Other scalars are left\n * as strings: proto JSON accepts string forms for ints/floats/int64/etc.,\n * and we'd rather pass through what the user typed than silently coerce.\n * @param field - The resolved leaf field descriptor, or undefined when the path didn't resolve\n * @param raw - The raw string value after `=`\n * @returns The value to write into the body object\n */\nfunction coerceFieldValue(field: DescField | undefined, raw: string): unknown {\n if (field && field.fieldKind === \"scalar\" && field.scalar === ScalarType.BOOL) {\n if (raw === \"true\") return true;\n if (raw === \"false\") return false;\n throw new Error(`Invalid value for bool field: '${raw}'. Expected 'true' or 'false'.`);\n }\n return raw;\n}\n\ninterface ParsedField {\n path: string[];\n value: string;\n}\n\n/**\n * Collapse top-level body keys that address a known input field by its\n * protobuf name (snake_case) or JSON name to the field's `localName`. protojson\n * accepts every alias, so converging them here lets the presence checks below\n * reason in a single namespace — otherwise a `--body` written as\n * `{\"workspace_id\": ...}` slips past the camelCase check and we inject a second\n * `workspaceId`, which the server rejects as a duplicate field. When both forms\n * are present the canonical key wins and the alias is dropped.\n * @param body - The parsed body object to mutate\n * @param fields - The target endpoint's input fields\n * @returns Whether any key was rewritten\n */\nexport function normalizeBodyFieldKeys(\n body: Record<string, unknown>,\n fields: readonly DescField[],\n): boolean {\n const aliasToLocal = new Map<string, string>();\n for (const f of fields) {\n aliasToLocal.set(f.name, f.localName);\n aliasToLocal.set(f.jsonName, f.localName);\n }\n let changed = false;\n for (const key of Object.keys(body)) {\n const local = aliasToLocal.get(key);\n if (!local || local === key) continue;\n if (!Object.hasOwn(body, local)) body[local] = body[key];\n delete body[key];\n changed = true;\n }\n return changed;\n}\n\n// Prototype-pollution sinks: `setNestedPath` walks `cursor[key]`, so a\n// segment that resolves on `Object.prototype` (e.g. `__proto__`) would let an\n// untrusted dotted key mutate the runtime prototype instead of the body.\nconst FORBIDDEN_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst fieldArg = z.string().transform((val, ctx): ParsedField => {\n const eq = val.indexOf(\"=\");\n if (eq < 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field format: '${val}'. Expected format: 'key=value' or 'a.b.c=value'`,\n });\n return z.NEVER;\n }\n const key = val.slice(0, eq);\n if (key.length === 0) {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: \"Field key cannot be empty\" });\n return z.NEVER;\n }\n const segments = key.split(\".\");\n if (segments.some((seg) => seg.length === 0)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field key: '${key}'. Dotted segments cannot be empty`,\n });\n return z.NEVER;\n }\n const forbidden = segments.find((seg) => FORBIDDEN_SEGMENTS.has(seg));\n if (forbidden) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Invalid field key: '${key}'. Segment '${forbidden}' is not allowed.`,\n });\n return z.NEVER;\n }\n return { path: segments, value: val.slice(eq + 1) };\n});\n\nexport const apiCommand = defineAppCommand({\n name: \"api\",\n description: \"Call Tailor Platform API endpoints directly.\",\n notes: `Use \\`tailor api list\\` to enumerate invocable methods and \\`tailor api inspect <endpoint>\\` to print an endpoint's input message tree (combine with \\`--json\\` for machine-readable output).\n\nThe request body is inferred from the target endpoint's request schema, and commonly required fields are auto-injected so they can be omitted from \\`--body\\`:\n\n- \\`workspaceId\\` — resolved from \\`-w\\` / \\`TAILOR_PLATFORM_WORKSPACE_ID\\` / the selected profile.\n- \\`namespaceName\\` — resolved from \\`tailor.config.ts\\` based on the endpoint's service:\n - Auth / Tenant / UserProfile endpoints use \\`auth.name\\`.\n - IdP / TailorDB / Pipeline endpoints use the sole configured namespace when exactly one is defined.\n\nValues already present in \\`--body\\` are never overridden. If a value cannot be resolved (e.g. no config found), injection is silently skipped and the server-side validation error takes precedence.\n\nUse \\`--field key=value\\` (repeatable) to set request body fields without writing JSON. Dotted keys (e.g. \\`application.name=foo\\`) build nested objects. \\`--field\\` overrides matching fields in \\`--body\\` and tab-completes from the endpoint's request schema.`,\n examples: [\n {\n cmd: 'GetApplication -b \\'{\"applicationName\":\"app-1\"}\\'',\n desc: \"Call an endpoint; workspaceId is auto-injected.\",\n },\n {\n cmd: \"GetApplication -f applicationName=app-1\",\n desc: \"Same as above, using --field instead of --body.\",\n },\n {\n cmd: \"list\",\n desc: \"List all invocable OperatorService methods.\",\n },\n {\n cmd: \"inspect GetApplication\",\n desc: \"Show the input message tree for an endpoint.\",\n },\n ],\n subCommands: {\n list: listCommand,\n inspect: inspectCommand,\n },\n args: z.strictObject({\n ...workspaceArgs,\n ...configArg,\n body: arg(z.string().default(\"{}\"), {\n alias: \"b\",\n description: \"Request body as JSON.\",\n }),\n field: arg(fieldArg.array().optional(), {\n alias: \"f\",\n description:\n \"Set a body field as `key=value` (repeatable; dotted keys nest). Overrides --body.\",\n completion: {\n custom: {\n expand: {\n dependsOn: [\"endpoint\"],\n enumerate: ({ endpoint }) =>\n enumerateAllFieldCompletions(extractMethodName(endpoint ?? \"\")),\n },\n },\n },\n }),\n endpoint: arg(z.string(), {\n positional: true,\n description:\n \"API endpoint to call (e.g., 'GetApplication' or 'tailor.v1.OperatorService/GetApplication').\",\n completion: { custom: { choices: listMethodChoices() } },\n }),\n }),\n run: async (args) => {\n // Direct API calls can target any OperatorService method, including\n // Create/Update/Delete. Block all of them under a readonly profile rather\n // than try to classify endpoints by name.\n await assertWritable({ profile: args.profile });\n const methodName = extractMethodName(args.endpoint);\n const method = getMethodDescriptor(methodName);\n\n const parsedBody = parseBodyAsObject(args.body);\n let mutated = false;\n\n if (args.field && args.field.length > 0) {\n if (!parsedBody) {\n throw new Error(\"--field requires --body to be a JSON object (or omitted).\");\n }\n for (const f of args.field) {\n const leaf = method ? resolveLeafField(method.input, f.path) : undefined;\n setNestedPath(parsedBody, f.path, coerceFieldValue(leaf, f.value));\n }\n mutated = true;\n }\n\n if (parsedBody && method) {\n // Converge any snake_case / JSON aliases to each field's localName first,\n // so the presence checks below operate in a single (camelCase) namespace.\n if (normalizeBodyFieldKeys(parsedBody, method.input.fields)) {\n mutated = true;\n }\n\n const fieldNames = method.input.fields.map((f) => f.localName);\n\n if (fieldNames.includes(\"workspaceId\") && !Object.hasOwn(parsedBody, \"workspaceId\")) {\n try {\n parsedBody.workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n mutated = true;\n } catch {\n // Cannot resolve workspace ID — skip\n }\n }\n\n if (fieldNames.includes(\"namespaceName\") && !Object.hasOwn(parsedBody, \"namespaceName\")) {\n try {\n const { config } = await loadConfig(args.config);\n const ns = resolveNamespaceName(methodName, config);\n if (ns) {\n parsedBody.namespaceName = ns;\n mutated = true;\n }\n } catch {\n // Config not available — skip\n }\n }\n }\n\n const result = await apiCall({\n profile: args.profile,\n endpoint: args.endpoint,\n body: mutated && parsedBody ? JSON.stringify(parsedBody) : args.body,\n });\n\n logger.out(JSON.stringify(result.data, null, 2));\n },\n});\n","import { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const tokenCommand = defineAppCommand({\n name: \"token\",\n description:\n \"Print a valid Tailor Platform access token to stdout, refreshing it first if expired.\",\n args: z.strictObject({\n profile: workspaceArgs.profile,\n }),\n run: async ({ profile }) => {\n const token = await loadAccessToken({ profile });\n logger.out(token);\n },\n});\n","import { defineCommand } from \"politty\";\nimport { tokenCommand } from \"./token\";\n\nexport const authCommand = defineCommand({\n name: \"auth\",\n description: \"Authentication helpers for scripts and plugins.\",\n subCommands: {\n token: tokenCommand,\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\n/**\n * Arguments for identifying an auth connection\n */\nexport const connectionNameArgs = {\n name: arg(z.string(), {\n alias: \"n\",\n description: \"Auth connection name\",\n }),\n};\n","import * as crypto from \"node:crypto\";\nimport * as http from \"node:http\";\nimport open from \"open\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nconst defaultPort = 8080;\nconst defaultScopes = \"openid,profile,email\";\n\n/**\n * Fetch the OpenID Connect discovery document from a provider URL.\n * @param providerUrl - OAuth2 provider base URL\n * @returns Discovery document with authorization_endpoint\n */\nasync function fetchOIDCDiscovery(\n providerUrl: string,\n): Promise<{ authorization_endpoint: string }> {\n const url = providerUrl.replace(/\\/$/, \"\") + \"/.well-known/openid-configuration\";\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`Failed to fetch OIDC discovery from ${url}: ${response.status}`);\n }\n return response.json() as Promise<{\n authorization_endpoint: string;\n }>;\n}\n\nfunction randomState() {\n return crypto.randomBytes(32).toString(\"base64url\");\n}\n\nexport const authorizeAuthConnectionCommand = defineAppCommand({\n name: \"authorize\",\n description: \"Authorize an auth connection via OAuth2 flow.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n scopes: z\n .string()\n .optional()\n .default(defaultScopes)\n .describe(\"OAuth2 scopes to request (comma-separated)\"),\n port: z.coerce.number().optional().default(defaultPort).describe(\"Local callback server port\"),\n \"no-browser\": z\n .boolean()\n .optional()\n .default(false)\n .describe(\"Don't open browser automatically\"),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // Find the connection to get its provider URL and client ID\n const connections = await fetchAll(async (pageToken, maxPageSize) => {\n const { connections, nextPageToken } = await client.listAuthConnections({\n workspaceId,\n pageToken,\n pageSize: maxPageSize,\n });\n return [connections, nextPageToken];\n });\n\n const connection = connections.find((c) => c.name === args.name);\n if (!connection) {\n throw new Error(`Auth connection \"${args.name}\" not found.`);\n }\n\n if (connection.config.case !== \"oauth2\") {\n throw new Error(`Auth connection \"${args.name}\" is not an OAuth2 connection.`);\n }\n\n const oauth2Config = connection.config.value;\n const redirectUri = `http://localhost:${args.port}/callback`;\n const state = randomState();\n\n // Resolve authorization endpoint from discovery or explicit config\n let authorizationEndpoint: string;\n if (oauth2Config.authUrl) {\n authorizationEndpoint = oauth2Config.authUrl;\n } else {\n const discovery = await fetchOIDCDiscovery(oauth2Config.providerUrl);\n authorizationEndpoint = discovery.authorization_endpoint;\n }\n\n // Build authorization URL\n const authUrl = new URL(authorizationEndpoint);\n authUrl.searchParams.set(\"client_id\", oauth2Config.clientId);\n authUrl.searchParams.set(\"redirect_uri\", redirectUri);\n authUrl.searchParams.set(\"response_type\", \"code\");\n authUrl.searchParams.set(\"scope\", args.scopes.replace(/,/g, \" \"));\n authUrl.searchParams.set(\"state\", state);\n authUrl.searchParams.set(\"access_type\", \"offline\");\n\n await new Promise<void>((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n if (!req.url?.startsWith(\"/callback\")) {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n try {\n const url = new URL(req.url, `http://localhost:${args.port}`);\n const code = url.searchParams.get(\"code\");\n const returnedState = url.searchParams.get(\"state\");\n const error = url.searchParams.get(\"error\");\n\n if (error) {\n throw new Error(`Authorization failed: ${error}`);\n }\n\n if (returnedState !== state) {\n throw new Error(\"State mismatch — possible CSRF attack.\");\n }\n\n if (!code) {\n throw new Error(\"No authorization code received.\");\n }\n\n // Send authorization code to the platform for server-side token exchange\n await client.exchangeAuthConnectionAuthorizationCode({\n workspaceId,\n connectionName: args.name,\n authorizationCode: code,\n redirectUri,\n });\n\n res.writeHead(200, { \"Content-Type\": \"text/html\" });\n res.end(\n \"<html><body><h1>Authorization successful</h1><p>You can close this window.</p></body></html>\",\n );\n server.close();\n resolve();\n } catch (err) {\n res.writeHead(400, { \"Content-Type\": \"text/plain\" });\n res.end(`Authorization failed: ${err instanceof Error ? err.message : \"Unknown error\"}`);\n server.close();\n reject(err);\n }\n });\n\n const timeout = setTimeout(\n () => {\n server.close();\n reject(new Error(\"Authorization timeout exceeded (5 minutes).\"));\n },\n 5 * 60 * 1000,\n );\n\n server.on(\"close\", () => {\n clearTimeout(timeout);\n });\n\n server.on(\"error\", (err) => {\n // A listen failure never emits \"close\", so clear the pending timeout\n // here to avoid keeping the process alive after the command has failed.\n clearTimeout(timeout);\n // Any error here means the local callback server could not be started.\n // Guide the user to the Console-based flow as a fallback.\n const code = (err as NodeJS.ErrnoException).code;\n const portHint =\n code === \"EADDRINUSE\" || code === \"EACCES\"\n ? `Try a different port with --port, or authorize via the Console instead:`\n : `Authorize via the Console instead:`;\n logger.warn(\n `Could not start the local callback server on port ${args.port}${code ? ` (${code})` : \"\"}.\\n` +\n `${portHint}\\n` +\n ` tailor authconnection open`,\n );\n reject(err);\n });\n\n server.listen(args.port, async () => {\n const authorizeUrl = authUrl.toString();\n logger.info(\n args[\"no-browser\"]\n ? `Open this URL in your browser to authorize:\\n\\n${authorizeUrl}\\n`\n : `Opening browser for authorization:\\n\\n${authorizeUrl}\\n`,\n );\n logger.info(\n `If this flow doesn't complete, you can authorize via the Console instead:\\n` +\n ` tailor authconnection open`,\n );\n if (!args[\"no-browser\"]) {\n try {\n await open(authorizeUrl);\n } catch {\n logger.warn(\n \"Failed to open browser automatically. Please open the URL above manually.\",\n );\n }\n }\n });\n });\n\n logger.success(`Auth connection \"${args.name}\" authorized successfully.`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nexport const deleteAuthConnectionCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete an auth connection entirely.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the connection name to confirm deletion (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Auth connection deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteAuthConnection({ workspaceId, connectionName: args.name });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Auth connection \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Auth connection \"${args.name}\" deleted.`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { AuthConnection } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n\ninterface ConnectionInfo {\n name: string;\n type: string;\n providerUrl: string;\n issuerUrl: string;\n clientId: string;\n authUrl: string;\n tokenUrl: string;\n createdAt: Date | null;\n}\n\nfunction connectionInfo(connection: AuthConnection): ConnectionInfo {\n const oauth2 = connection.config.case === \"oauth2\" ? connection.config.value : undefined;\n return {\n name: connection.name,\n type: connection.config.case ?? \"unknown\",\n providerUrl: oauth2?.providerUrl ?? \"\",\n issuerUrl: oauth2?.issuerUrl ?? \"\",\n clientId: oauth2?.clientId ?? \"\",\n authUrl: oauth2?.authUrl ?? \"\",\n tokenUrl: oauth2?.tokenUrl ?? \"\",\n createdAt: connection.createdAt ? timestampDate(connection.createdAt) : null,\n };\n}\n\nexport const listAuthConnectionCommand = defineAppCommand({\n name: \"list\",\n description: \"List all auth connections.\",\n args: z.strictObject({ ...workspaceArgs, ...paginationArgs() }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n const pageDirection = toPageDirection(args.order);\n const connections = await fetchPaged(\n async (pageToken, pageSize) => {\n const { connections, nextPageToken } = await client.listAuthConnections({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [connections, nextPageToken];\n },\n { limit: args.limit },\n );\n logger.out(connections.map(connectionInfo));\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n logger.out([]);\n return;\n }\n throw error;\n }\n },\n});\n","import open from \"open\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConsoleBaseUrl, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const openAuthConnectionCommand = defineAppCommand({\n name: \"open\",\n description: \"Open the auth connections page in the Tailor Platform Console.\",\n args: z.strictObject({ ...workspaceArgs }),\n run: async (args) => {\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n const consolePath = `/workspaces/${workspaceId}/settings/connections`;\n const consoleBaseUrl = await loadConsoleBaseUrl({\n profile: args.profile,\n ...(args[\"workspace-id\"] !== undefined ? { allowMissingProfile: true } : {}),\n });\n const consoleUrl = new URL(consolePath, consoleBaseUrl).toString();\n const jsonOutput = logger.jsonMode;\n\n logger.info(\"Opening auth connections page in Tailor Platform Console...\");\n\n let opened = true;\n try {\n await open(consoleUrl);\n } catch {\n opened = false;\n }\n\n if (jsonOutput) {\n logger.out({ consoleUrl, workspaceId, opened });\n return;\n }\n\n if (opened) {\n logger.out(`Console URL: ${consoleUrl}`);\n logger.out(`Workspace ID: ${workspaceId}`);\n } else {\n logger.warn(\n `Failed to open browser automatically. Please open this URL manually:\\n${consoleUrl}`,\n );\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { connectionNameArgs } from \"./args\";\n\nexport const revokeAuthConnectionCommand = defineAppCommand({\n name: \"revoke\",\n description:\n \"Revoke an auth connection's tokens (keeps the connection; use 'delete' to remove it).\",\n notes:\n \"Revoke invalidates the connection's active session and tokens but keeps the connection and its stored credentials, so it can be re-authorized later. Use `delete` to remove the connection entirely.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...connectionNameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the connection name to confirm revocation (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Auth connection revocation cancelled.\");\n return;\n }\n }\n\n try {\n await client.revokeAuthConnection({\n workspaceId,\n connectionName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Auth connection \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Auth connection \"${args.name}\" revoked.`);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { authorizeAuthConnectionCommand } from \"./authorize\";\nimport { deleteAuthConnectionCommand } from \"./delete\";\nimport { listAuthConnectionCommand } from \"./list\";\nimport { openAuthConnectionCommand } from \"./open\";\nimport { revokeAuthConnectionCommand } from \"./revoke\";\n\nexport const authconnectionCommand = defineCommand({\n name: \"authconnection\",\n description: \"Manage auth connections.\",\n subCommands: {\n authorize: authorizeAuthConnectionCommand,\n list: listAuthConnectionCommand,\n open: openAuthConnectionCommand,\n revoke: revokeAuthConnectionCommand,\n delete: deleteAuthConnectionCommand,\n },\n async run() {\n await runCommand(listAuthConnectionCommand, []);\n },\n});\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { z } from \"zod\";\nimport { parseCrashReportConfig } from \"#/cli/crashreport/config\";\nimport { CRASH_LOG_EXTENSION } from \"#/cli/crashreport/writer\";\nimport { type Order, paginationArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport function orderAndLimitCrashReports(\n entries: string[],\n options: { order?: Order; limit?: number },\n): string[] {\n const sorted = entries.filter((f) => f.endsWith(CRASH_LOG_EXTENSION)).toSorted();\n const ordered = options.order === \"asc\" ? sorted : sorted.toReversed();\n return options.limit && options.limit > 0 ? ordered.slice(0, options.limit) : ordered;\n}\n\nfunction formatCrashReportFiles(files: string[], localDir: string) {\n return files.map((file) => ({\n file,\n path: path.join(localDir, file),\n }));\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List local crash report files.\",\n args: z.strictObject({\n ...paginationArgs(),\n }),\n run: async (args) => {\n const config = parseCrashReportConfig();\n const jsonOutput = logger.jsonMode;\n if (!config.localDir) {\n logger.info(\"Crash report directory not available.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n let entries: string[];\n try {\n entries = fs.readdirSync(config.localDir);\n } catch {\n logger.info(\"No crash reports found.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const files = orderAndLimitCrashReports(entries, { order: args.order, limit: args.limit });\n\n if (files.length === 0) {\n logger.info(\"No crash reports found.\");\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n if (jsonOutput) {\n logger.out(formatCrashReportFiles(files, config.localDir));\n return;\n }\n\n logger.info(`${files.length} crash report(s) in ${config.localDir}:`);\n for (const file of files) {\n logger.log(` ${file}`);\n }\n },\n});\n","import * as fs from \"node:fs\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { sendCrashReport } from \"#/cli/crashreport/sender\";\nimport { JSON_FOOTER_MARKER } from \"#/cli/crashreport/writer\";\nimport { userAgent } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { CrashReport } from \"#/cli/crashreport/report\";\n\nexport const sendCommand = defineAppCommand({\n name: \"send\",\n description: \"Submit a crash report to help improve the SDK.\",\n args: z.strictObject({\n file: arg(z.string(), {\n description: \"Path to the crash report file\",\n required: true,\n completion: { type: \"file\", extensions: [\"log\"] },\n }),\n }),\n run: async (args) => {\n let content: string;\n try {\n content = fs.readFileSync(args.file, \"utf-8\");\n } catch {\n logger.error(`Crash report file not found: ${args.file}`);\n process.exit(1);\n }\n\n const report = parseCrashLogFile(content);\n if (!report) {\n logger.error(\"Failed to parse crash report file. The file may be corrupted.\");\n process.exit(1);\n }\n\n const ua = await userAgent();\n logger.info(\"Sending crash report...\");\n const success = await sendCrashReport(report, ua);\n\n if (success) {\n logger.success(\"Crash report submitted successfully. Thank you!\");\n } else {\n logger.error(\"Failed to submit crash report. The server may be unavailable.\");\n process.exit(1);\n }\n },\n});\n\n/**\n * Parse a crash log file back into a CrashReport object.\n * Reads the embedded JSON footer appended by formatCrashReport.\n * @param content - File content\n * @returns Parsed report or undefined if parsing fails\n */\nexport function parseCrashLogFile(content: string): CrashReport | undefined {\n try {\n const normalized = content.replace(/\\r\\n/g, \"\\n\");\n const marker = `\\n${JSON_FOOTER_MARKER}\\n`;\n const lastIdx = normalized.lastIndexOf(marker);\n if (lastIdx === -1) return undefined;\n const jsonLine = normalized.slice(lastIdx + marker.length).split(\"\\n\")[0];\n if (!jsonLine) return undefined;\n return JSON.parse(jsonLine) as CrashReport;\n } catch {\n return undefined;\n }\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\nimport { sendCommand } from \"./send\";\n\nexport const crashReportCommand = defineCommand({\n name: \"crashreport\",\n description: \"Manage crash reports.\",\n subCommands: {\n list: listCommand,\n send: sendCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { deployFromCLI } from \"#/cli/commands/deploy/deploy\";\nimport { confirmationArgs, multiConfigArg, workspaceArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\n\nexport const deployCommand = defineAppCommand({\n name: \"deploy\",\n description: \"Deploy your application by applying the Tailor configuration.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...multiConfigArg,\n ...confirmationArgs,\n \"create-workspace\": arg(z.boolean().optional(), {\n description: \"Create a workspace when the account has none\",\n }),\n \"workspace-name\": arg(z.string().optional(), {\n description: \"Name for a workspace created during deploy\",\n }),\n \"workspace-region\": arg(z.string().optional(), {\n description: \"Region for a workspace created during deploy\",\n }),\n \"organization-id\": arg(z.string().optional(), {\n description: \"Organization ID for a workspace created during deploy\",\n env: \"TAILOR_PLATFORM_ORGANIZATION_ID\",\n }),\n \"folder-id\": arg(z.string().optional(), {\n description: \"Folder ID for a workspace created during deploy\",\n env: \"TAILOR_PLATFORM_FOLDER_ID\",\n }),\n \"dry-run\": arg(z.boolean().optional(), {\n alias: \"d\",\n description: \"Run the command without making any changes\",\n }),\n \"no-schema-check\": arg(z.boolean().optional(), {\n description: \"Skip schema diff check against migration snapshots\",\n }),\n \"no-validate\": arg(z.boolean().optional(), {\n description: \"Skip client-side validation against platform resource constraints\",\n }),\n \"no-cache\": arg(z.boolean().optional(), {\n description: \"Disable bundle caching for this run\",\n }),\n \"clean-cache\": arg(z.boolean().optional(), {\n description: \"Clean the bundle cache before building\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n await deployFromCLI(\n {\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n configPath: args.config,\n dryRun: args[\"dry-run\"],\n yes: args.yes,\n createWorkspace: args[\"create-workspace\"],\n workspaceName: args[\"workspace-name\"],\n workspaceRegion: args[\"workspace-region\"],\n organizationId: args[\"organization-id\"],\n folderId: args[\"folder-id\"],\n noSchemaCheck: args[\"no-schema-check\"],\n noValidate: args[\"no-validate\"],\n noCache: args[\"no-cache\"],\n cleanCache: args[\"clean-cache\"],\n },\n {\n envFile: args[\"env-file\"],\n envFileIfExists: args[\"env-file-if-exists\"],\n verbose: args.verbose,\n json: args.json,\n },\n );\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { jobsCommand } from \"./jobs\";\nimport { listCommand } from \"./list\";\nimport { triggerCommand } from \"./trigger\";\nimport { webhookCommand } from \"./webhook\";\n\nexport const executorCommand = defineCommand({\n name: \"executor\",\n description: \"Manage executors\",\n subCommands: {\n trigger: triggerCommand,\n jobs: jobsCommand,\n list: listCommand,\n get: getCommand,\n webhook: webhookCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","/**\n * Download a deployed function script from the function registry.\n *\n * Wraps the server-streaming `downloadFunctionRegistryScript` RPC and\n * concatenates content chunks into a single UTF-8 string.\n */\n\nimport { FunctionExecution_Type } from \"@tailor-platform/tailor-proto/function_resource_pb\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\n\n/**\n * Translate a `FunctionExecution.scriptName` into the corresponding\n * function registry name used by `downloadFunctionRegistryScript`.\n *\n * The platform records executions under a script-name format that\n * differs from the registry name. The execution `type` is used as the\n * primary discriminator because workflow job names are unconstrained\n * strings (`WorkflowJobSchema.name: z.string()`) and may contain dots\n * that collide with the resolver / executor / hook filename suffixes.\n *\n * JOB: `<jobName>` -> `workflow--<jobName>`\n * STANDARD resolver: `<namespace>.<name>.body.js` -> `resolver--<namespace>--<name>`\n * STANDARD executor: `<name>.operation.js` -> `executor--<name>`\n * STANDARD auth hook: `<authName>.<hookPoint>.hook.js` -> `auth-hook--<authName>--<hookPoint>`\n *\n * For older servers that leave `type` as `UNSPECIFIED`, the same\n * filename-suffix heuristic is applied, with a bare-name fallback to\n * `workflow--<name>` for backward compatibility. Returns `null` for\n * unrecognized formats (ad-hoc test-run scripts, seed scripts, etc.\n * that are not stored in the registry).\n * @param scriptName - The `scriptName` field from a `FunctionExecution`\n * @param executionType - The `type` field from a `FunctionExecution`\n * @returns The function registry name, or null when no mapping applies\n */\nexport function scriptNameToRegistryName(\n scriptName: string,\n executionType: FunctionExecution_Type,\n): string | null {\n // JOB: scriptName IS the workflow job name. Job names are\n // unconstrained, so dots must be preserved.\n if (executionType === FunctionExecution_Type.JOB) {\n return `workflow--${scriptName}`;\n }\n\n // Resolver: `<namespace>.<name>.body.js`\n // Use a non-greedy match for namespace so a name containing dots is\n // grouped into `name`, mirroring how resolvers are registered.\n const resolverMatch = /^([^.]+)\\.(.+)\\.body\\.js$/.exec(scriptName);\n if (resolverMatch) {\n const [, namespace, name] = resolverMatch;\n return `resolver--${namespace}--${name}`;\n }\n\n // Executor: `<name>.operation.js`\n const executorMatch = /^(.+)\\.operation\\.js$/.exec(scriptName);\n if (executorMatch) {\n const [, name] = executorMatch;\n return `executor--${name}`;\n }\n\n // Auth hook: `<authName>.<hookPoint>.hook.js`\n const authHookMatch = /^([^.]+)\\.([^.]+)\\.hook\\.js$/.exec(scriptName);\n if (authHookMatch) {\n const [, authName, hookPoint] = authHookMatch;\n return `auth-hook--${authName}--${hookPoint}`;\n }\n\n // Legacy (UNSPECIFIED) servers may not populate `type`. Fall back to\n // the historical bare-name heuristic for simple workflow job names.\n // Dotted job names cannot be disambiguated here and are left\n // unmapped; callers should upgrade the server for full coverage.\n if (executionType === FunctionExecution_Type.UNSPECIFIED && !scriptName.includes(\".\")) {\n return `workflow--${scriptName}`;\n }\n\n // Unknown format (ad-hoc test-run scripts, seed scripts, etc.) are\n // not in the registry; signal with null so the caller can fall back.\n return null;\n}\n\n/** Options for downloading a function registry script */\nexport interface DownloadFunctionScriptOptions {\n /** Operator client instance */\n client: OperatorClient;\n /** Workspace ID */\n workspaceId: string;\n /** Function registry name (translated from FunctionExecution.scriptName via scriptNameToRegistryName) */\n name: string;\n /** Optional content hash for a specific version (defaults to current version) */\n contentHash?: string;\n}\n\n/** Result of a successful function script download */\nexport interface DownloadedFunctionScript {\n /** Bundled script content as a UTF-8 string */\n code: string;\n}\n\n/**\n * Download a deployed function script.\n *\n * Returns the bundled script content. Returns null when the download\n * fails (script removed, network error, etc.) or when no content\n * chunks are received; errors are swallowed so callers can fall back\n * to a non-sourcemap display.\n * @param options - Download options\n * @returns Script content, or null on failure / empty response\n */\nexport async function downloadFunctionScript(\n options: DownloadFunctionScriptOptions,\n): Promise<DownloadedFunctionScript | null> {\n const { client, workspaceId, name, contentHash } = options;\n try {\n const chunks: Uint8Array[] = [];\n for await (const response of client.downloadFunctionRegistryScript({\n workspaceId,\n name,\n contentHash,\n })) {\n if (response.payload.case === \"chunk\") {\n chunks.push(response.payload.value);\n }\n }\n if (chunks.length === 0) return null;\n return { code: Buffer.concat(chunks).toString(\"utf-8\") };\n } catch (error) {\n logger.debug(`Failed to download function script \"${options.name}\": ${error}`);\n return null;\n }\n}\n","/**\n * Stack trace parsing, sourcemap-based source identification, and\n * formatted error display for the test-run command.\n *\n * The platform runtime automatically applies inline sourcemaps to V8\n * stack traces, so frame positions are already original source positions.\n * This module identifies which source file each frame belongs to via\n * reverse lookup (generatedPositionFor), then produces human-readable\n * output with file paths and code snippets.\n */\n\nimport { TraceMap, generatedPositionFor, originalPositionFor } from \"@jridgewell/trace-mapping\";\nimport * as path from \"pathe\";\nimport { styles } from \"#/cli/shared/logger\";\nimport { assertDefined } from \"#/utils/assert\";\n\n/** A single frame parsed from a V8 stack trace */\nexport interface StackFrame {\n /** Function name (e.g. \"M\", \"Object.body\", \"<anonymous>\") */\n functionName: string;\n /** File URL (e.g. \"file:///test-run--error-test.js\") */\n file: string;\n /** Line number (1-based) */\n line: number;\n /** Column number (1-based) */\n column: number;\n}\n\n/** Result of parsing a V8 stack trace string */\nexport interface ParsedStackTrace {\n /** Error message with rpc prefix stripped */\n errorMessage: string;\n /** Parsed stack frames (only file:/// frames) */\n frames: StackFrame[];\n}\n\n// Matches: \" at functionName (file:///path:line:col)\"\n// Or: \" at file:///path:line:col\"\nconst STACK_FRAME_REGEX = /^\\s+at\\s+(?:(.+?)\\s+\\()?(file:\\/\\/\\/.+?):(\\d+):(\\d+)\\)?$/;\n\n// The rpc error prefix added by the platform\nconst RPC_ERROR_PREFIX = \"rpc error: code = Aborted desc = \";\n\n/**\n * Parse a V8 stack trace string into structured frames.\n * Only frames with `file:///` URLs are included (eval frames are skipped).\n * @param error - Raw error string potentially containing a V8 stack trace\n * @returns Parsed error message and stack frames\n */\nexport function parseStackTrace(error: string): ParsedStackTrace {\n const lines = error.split(\"\\n\");\n\n const messageLines: string[] = [];\n const frameLines: string[] = [];\n\n for (const line of lines) {\n if (/^\\s+at\\s+/.test(line)) {\n frameLines.push(line);\n } else if (frameLines.length === 0) {\n messageLines.push(line);\n }\n }\n\n let errorMessage = messageLines.join(\"\\n\");\n\n if (errorMessage.startsWith(RPC_ERROR_PREFIX)) {\n errorMessage = errorMessage.slice(RPC_ERROR_PREFIX.length);\n }\n\n const frames: StackFrame[] = [];\n for (const line of frameLines) {\n const match = STACK_FRAME_REGEX.exec(line);\n if (match) {\n frames.push({\n functionName: match[1] || \"<anonymous>\",\n file: assertDefined(match[2], \"stack frame file missing\"),\n line: Number(assertDefined(match[3], \"stack frame line missing\")),\n column: Number(assertDefined(match[4], \"stack frame column missing\")),\n });\n }\n }\n\n return { errorMessage, frames };\n}\n\nconst INLINE_SOURCEMAP_REGEX =\n /\\/\\/[#@]\\s*sourceMappingURL=data:application\\/json[^,]*;base64,(.+)$/m;\n\n/** Original source position resolved from a sourcemap */\nexport interface MappedSourcePosition {\n source: string;\n line: number;\n column: number;\n name: string | null;\n}\n\n/** A stack frame mapped back to original source */\nexport interface MappedStackFrame {\n /** The original parsed frame */\n original: StackFrame;\n /** Mapped source position, or null if mapping failed */\n mapped: MappedSourcePosition | null;\n}\n\n/**\n * Extract an inline sourcemap from bundled code and return a TraceMap.\n * @param bundledCode - Bundled JavaScript code potentially containing an inline sourcemap\n * @returns TraceMap instance, or null if no valid inline sourcemap is found\n */\nexport function extractInlineSourcemap(bundledCode: string): TraceMap | null {\n const match = INLINE_SOURCEMAP_REGEX.exec(bundledCode);\n if (!match) return null;\n\n try {\n const decoded = Buffer.from(\n assertDefined(match[1], \"sourcemap base64 data missing\"),\n \"base64\",\n ).toString(\"utf-8\");\n const rawSourceMap = JSON.parse(decoded);\n return new TraceMap(rawSourceMap);\n } catch {\n return null;\n }\n}\n\n/**\n * Map parsed stack frames to their source files using a TraceMap.\n *\n * The platform runtime applies inline sourcemaps automatically, so V8\n * reports already-mapped original source positions in stack traces.\n * This function uses generatedPositionFor to reverse-lookup which source\n * file each frame's line:column belongs to.\n * @param frames - Parsed stack frames (positions are already original source positions)\n * @param traceMap - TraceMap from inline sourcemap, or null\n * @returns Frames with identified source files\n */\nexport function mapStackFrames(\n frames: StackFrame[],\n traceMap: TraceMap | null,\n): MappedStackFrame[] {\n return frames.map((frame) => {\n if (!traceMap) {\n return { original: frame, mapped: null };\n }\n\n try {\n // Iterate in reverse: user code and entry file are typically last\n // in the sources array, while SDK internals and node_modules come first.\n for (let i = traceMap.sources.length - 1; i >= 0; i--) {\n const source = traceMap.sources[i];\n if (source == null) continue;\n\n const genPos = generatedPositionFor(traceMap, {\n source,\n line: frame.line,\n column: frame.column - 1, // V8 is 1-based, trace-mapping is 0-based\n });\n\n if (genPos.line == null) continue;\n\n // Round-trip validation: generatedPositionFor uses\n // GREATEST_LOWER_BOUND bias by default, so it may return a\n // near-match when the queried source has a mapping on the target\n // line at an earlier column. Verify the generated position maps\n // back to the exact (source, line, column) we queried before\n // accepting the match; otherwise try the next source.\n const origPos = originalPositionFor(traceMap, {\n line: genPos.line,\n column: genPos.column,\n });\n if (\n origPos.source !== source ||\n origPos.line !== frame.line ||\n origPos.column !== frame.column - 1\n ) {\n continue;\n }\n\n return {\n original: frame,\n mapped: {\n source,\n line: frame.line,\n column: frame.column,\n name: null,\n },\n };\n }\n\n return { original: frame, mapped: null };\n } catch {\n return { original: frame, mapped: null };\n }\n });\n}\n\n/**\n * Detect the URI scheme for opening files based on VISUAL/EDITOR env vars.\n * @returns \"vscode\" if the editor looks like VS Code, otherwise null (use file://)\n */\nfunction detectEditorScheme(): string | null {\n const editor = process.env.VISUAL || process.env.EDITOR || \"\";\n if (/\\bcode\\b/.test(editor)) return \"vscode\";\n return null;\n}\n\n/**\n * Wrap text in an OSC 8 terminal hyperlink.\n * @param uri - URI to open when the link is clicked\n * @param text - Visible text displayed in the terminal\n * @returns Escaped string with OSC 8 sequences\n */\nfunction osc8Link(uri: string, text: string): string {\n return `\\x1b]8;;${uri}\\x07${text}\\x1b]8;;\\x07`;\n}\n\n/**\n * Build a clickable terminal link for a source location.\n * Uses vscode:// URI if the editor is VS Code, otherwise file:// URI.\n * @param displayPath - Path to display in the terminal\n * @param absolutePath - Absolute file path for the URI\n * @param line - 1-based line number\n * @param column - 1-based column number\n * @returns OSC 8 hyperlinked location string\n */\nfunction buildSourceLink(\n displayPath: string,\n absolutePath: string,\n line: number,\n column: number,\n): string {\n const location = `${displayPath}:${line}:${column}`;\n const scheme = detectEditorScheme();\n if (scheme === \"vscode\") {\n return osc8Link(`vscode://file${absolutePath}:${line}:${column}`, location);\n }\n return osc8Link(`file://${absolutePath}`, location);\n}\n\nconst SNIPPET_CONTEXT_LINES = 2;\n\n/**\n * Build a code snippet around a target line from source content.\n * Shows SNIPPET_CONTEXT_LINES above and below with line numbers.\n * The target line is marked with `>` and highlighted.\n * @param content - Full source file content\n * @param targetLine - 1-based line number to highlight\n * @returns Formatted snippet string\n */\nfunction buildCodeSnippet(content: string, targetLine: number): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, targetLine - 1 - SNIPPET_CONTEXT_LINES);\n const end = Math.min(lines.length, targetLine + SNIPPET_CONTEXT_LINES);\n\n const gutterWidth = String(end).length;\n const snippetLines: string[] = [];\n\n for (let i = start; i < end; i++) {\n const lineNum = i + 1;\n const gutter = String(lineNum).padStart(gutterWidth);\n const lineContent = lines[i];\n\n if (lineNum === targetLine) {\n snippetLines.push(` ${styles.error(\">\")} ${styles.error(`${gutter} | ${lineContent}`)}`);\n } else {\n snippetLines.push(` ${styles.dim(`${gutter} | ${lineContent}`)}`);\n }\n }\n\n return snippetLines.join(\"\\n\");\n}\n\n/**\n * Format mapped stack frames into a human-readable error display.\n * Includes file paths (clickable in terminals), code snippets, and\n * falls back to raw frame info for unmapped frames.\n * @param errorMessage - Cleaned error message\n * @param frames - Mapped stack frames\n * @param traceMap - TraceMap for retrieving source content (may be null)\n * @param bundleDir - Absolute path to bundle output directory for resolving source paths\n * @returns Formatted error string for display\n */\nexport function formatMappedError(\n errorMessage: string,\n frames: MappedStackFrame[],\n traceMap: TraceMap | null,\n bundleDir?: string,\n): string {\n const parts: string[] = [` ${styles.error(errorMessage)}`];\n\n for (const frame of frames) {\n if (frame.mapped) {\n const { source, line, column, name } = frame.mapped;\n const absolutePath = bundleDir ? path.resolve(bundleDir, source) : path.resolve(source);\n const rel = path.relative(process.cwd(), absolutePath);\n // Only paths escaping cwd (starting with `..`) are shown as-is; all\n // other relative paths get an explicit `./` prefix so dotfiles like\n // `.tailor/...` are not mistaken for relative-path markers.\n const displaySource = rel.startsWith(\"..\") ? rel : `./${rel}`;\n const fnName = name ?? frame.original.functionName;\n const link = buildSourceLink(displaySource, absolutePath, line, column);\n parts.push(`\\n at ${fnName} (${link})`);\n\n if (traceMap) {\n const sourceIndex = traceMap.sources.indexOf(source);\n if (sourceIndex !== -1) {\n const content = traceMap.sourcesContent?.[sourceIndex];\n if (content) {\n parts.push(buildCodeSnippet(content, line));\n }\n }\n }\n } else {\n const file = frame.original.file.replace(/^file:\\/\\/\\//, \"\");\n const location = `${file}:${frame.original.line}:${frame.original.column}`;\n parts.push(`\\n ${styles.dim(`at ${frame.original.functionName} (${location})`)}`);\n }\n }\n\n return parts.join(\"\\n\");\n}\n\n/**\n * Format an error string with sourcemap-based source locations.\n * This is the main entry point for test-run error display.\n *\n * The platform runtime applies inline sourcemaps automatically, so V8\n * stack frames already contain original source positions. This function\n * identifies which source file each frame belongs to and formats the\n * error with file paths, line numbers, and code snippets.\n *\n * Returns null if sourcemap processing is not possible (no inline\n * sourcemap, no stack trace, or processing error).\n * @param error - Raw error string from script execution (may contain V8 stack trace)\n * @param bundledCode - Bundled JavaScript code (may contain inline sourcemap)\n * @param bundleDir - Absolute path to the bundle output directory (sourcemap paths are relative to this)\n * @returns Formatted error string, or null to fall back to default display\n */\nexport function formatErrorWithSourcemap(\n error: string,\n bundledCode: string,\n bundleDir: string,\n): string | null {\n try {\n const { errorMessage, frames } = parseStackTrace(error);\n if (frames.length === 0) return null;\n\n const traceMap = extractInlineSourcemap(bundledCode);\n if (!traceMap) return null;\n\n const mappedFrames = mapStackFrames(frames, traceMap);\n\n if (mappedFrames.some((f) => f.mapped !== null)) {\n return formatMappedError(errorMessage, mappedFrames, traceMap, bundleDir);\n }\n\n return null;\n } catch {\n return null;\n }\n}\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { FunctionExecution_Type } from \"@tailor-platform/tailor-proto/function_resource_pb\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { pagedLogArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { formatKeyValueTable } from \"#/cli/shared/format\";\nimport { functionExecutionStatusToString } from \"#/cli/shared/function-execution\";\nimport {\n downloadFunctionScript,\n scriptNameToRegistryName,\n} from \"#/cli/shared/function-script-download\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport type { FunctionExecution } from \"@tailor-platform/tailor-proto/function_resource_pb\";\n\ninterface FunctionExecutionListInfo {\n id: string;\n scriptName: string;\n status: string;\n type: string;\n startedAt: Date | null;\n finishedAt: Date | null;\n}\n\ninterface FunctionExecutionErrorDisplay {\n name: string;\n message: string;\n stackTrace: string;\n}\n\ninterface FunctionExecutionDetailInfo extends FunctionExecutionListInfo {\n logs: string;\n result: string;\n error: FunctionExecutionErrorDisplay | null;\n}\n\n/**\n * Convert function execution type enum to string.\n * @param type - Function execution type enum value\n * @returns Type string representation\n */\nfunction functionExecutionTypeToString(type: FunctionExecution_Type): string {\n switch (type) {\n case FunctionExecution_Type.STANDARD:\n return \"STANDARD\";\n case FunctionExecution_Type.JOB:\n return \"JOB\";\n default:\n return \"UNSPECIFIED\";\n }\n}\n\n/**\n * Transform FunctionExecution to FunctionExecutionListInfo for list display.\n * @param execution - FunctionExecution from proto\n * @returns Function execution list info\n */\nfunction toFunctionExecutionListInfo(execution: FunctionExecution): FunctionExecutionListInfo {\n return {\n id: execution.id,\n scriptName: execution.scriptName,\n status: functionExecutionStatusToString(execution.status),\n type: functionExecutionTypeToString(execution.type),\n startedAt: execution.startedAt ? timestampDate(execution.startedAt) : null,\n finishedAt: execution.finishedAt ? timestampDate(execution.finishedAt) : null,\n };\n}\n\n/**\n * Transform FunctionExecution to FunctionExecutionDetailInfo for detail display.\n * @param execution - FunctionExecution from proto\n * @returns Function execution detail info\n */\nfunction toFunctionExecutionDetailInfo(execution: FunctionExecution): FunctionExecutionDetailInfo {\n return {\n ...toFunctionExecutionListInfo(execution),\n logs: execution.logs,\n result: execution.result,\n error: execution.error\n ? {\n name: execution.error.name,\n message: execution.error.message,\n stackTrace: execution.error.stackTrace,\n }\n : null,\n };\n}\n\n/**\n * Compose a V8-style error string from a FunctionErrorInfo so that it\n * can be parsed by `parseStackTrace`.\n *\n * `Error.prototype.stack` in V8 begins with `Name: message`, but the\n * platform may store only the frame lines; in that case prepend the\n * message line. When `stackTrace` is empty, return only `Name: message`.\n * @param error - Function error info from FunctionExecution\n * @returns Error string suitable for parseStackTrace\n */\nexport function composeExecutionErrorString(error: FunctionExecutionErrorDisplay): string {\n const { name, message, stackTrace } = error;\n if (!stackTrace) return `${name}: ${message}`;\n const firstLine = stackTrace.split(\"\\n\", 1)[0] ?? \"\";\n if (/^\\s+at\\s+/.test(firstLine)) {\n return `${name}: ${message}\\n${stackTrace}`;\n }\n return stackTrace;\n}\n\n/**\n * Plain-text fallback used when sourcemap mapping is unavailable.\n * Shows `Name: message` then the raw stack trace lines (dimmed).\n *\n * Uses `composeExecutionErrorString` to produce a canonical\n * `Name: message\\n<frames>` string first, so the header is never\n * duplicated when `stackTrace` already begins with `Name: message`.\n * @param error - Function error info from FunctionExecution\n * @returns Formatted fallback string for display\n */\nfunction formatExecutionErrorFallback(error: FunctionExecutionErrorDisplay): string {\n const composed = composeExecutionErrorString(error);\n const [headerLine = \"\", ...frameLines] = composed.split(\"\\n\");\n return [\n ` ${styles.error(headerLine)}`,\n ...frameLines.map((line) => ` ${styles.dim(line)}`),\n ].join(\"\\n\");\n}\n\n/**\n * Format an execution error for display, applying sourcemap mapping\n * when bundled code is available.\n * @param error - Function error info from FunctionExecution\n * @param bundledCode - Downloaded bundled script content (may be null)\n * @returns Formatted error string for display\n */\nexport function formatExecutionError(\n error: FunctionExecutionErrorDisplay,\n bundledCode: string | null,\n): string {\n if (bundledCode && error.stackTrace) {\n const errorString = composeExecutionErrorString(error);\n const formatted = formatErrorWithSourcemap(errorString, bundledCode, process.cwd());\n if (formatted) return formatted;\n }\n return formatExecutionErrorFallback(error);\n}\n\ninterface PrintFunctionExecutionDetailOptions {\n detail: FunctionExecutionDetailInfo;\n /** Bundled script content for sourcemap-based stack trace mapping (optional) */\n bundledCode?: string | null;\n}\n\n/**\n * Print function execution detail in a human-readable format.\n * @param options - Print options\n * @param options.detail - Function execution detail info\n * @param options.bundledCode - Downloaded bundled script content (used for sourcemap mapping)\n */\nfunction printFunctionExecutionDetail(options: PrintFunctionExecutionDetailOptions) {\n const { detail, bundledCode } = options;\n const formatDate = (date: Date | null): string => (date ? date.toISOString() : \"N/A\");\n\n const summaryData: [string, string][] = [\n [\"id\", detail.id],\n [\"scriptName\", detail.scriptName],\n [\"status\", detail.status],\n [\"type\", detail.type],\n [\"startedAt\", formatDate(detail.startedAt)],\n [\"finishedAt\", formatDate(detail.finishedAt)],\n ];\n logger.out(formatKeyValueTable(summaryData));\n\n if (detail.logs) {\n logger.log(styles.bold(\"\\nLogs:\"));\n for (const line of detail.logs.split(\"\\n\")) {\n logger.log(` ${line}`);\n }\n }\n\n if (detail.result) {\n logger.log(styles.bold(\"\\nResult:\"));\n try {\n const parsed = JSON.parse(detail.result);\n logger.log(` ${JSON.stringify(parsed, null, 2).split(\"\\n\").join(\"\\n \")}`);\n } catch {\n logger.log(` ${detail.result}`);\n }\n }\n\n if (detail.error) {\n logger.log(styles.bold(\"\\nError:\"));\n logger.log(formatExecutionError(detail.error, bundledCode ?? null));\n }\n}\n\ninterface DownloadScriptForMappingOptions {\n client: OperatorClient;\n workspaceId: string;\n /** FunctionExecution.scriptName (not the function registry name) */\n scriptName: string;\n /**\n * FunctionExecution.type. Used as the discriminator for the registry\n * name translation so that workflow job names containing dots are\n * not misread as resolver / seed scripts.\n */\n executionType: FunctionExecution_Type;\n /**\n * FunctionExecution.contentHash. When non-empty, the registry\n * download is pinned to this exact bundle so the stack trace maps\n * against the code that actually ran, regardless of subsequent\n * redeploys. Empty values cannot be mapped safely.\n */\n executionContentHash: string;\n}\n\n/**\n * Download a deployed function script for sourcemap mapping. Logs a\n * debug message on failure but never throws. Error display falls back\n * to a plain-text format when the script cannot be retrieved.\n *\n * When `executionContentHash` is non-empty, the download is pinned to\n * that exact bundle so mapping stays correct across redeploys. When\n * empty, mapping is skipped because the exact bundle cannot be\n * identified.\n *\n * `FunctionExecution.scriptName` does not match the function registry\n * name directly; `scriptNameToRegistryName` translates between the two\n * formats.\n * @param options - Lookup options\n * @param options.client - Operator client instance\n * @param options.workspaceId - Workspace ID\n * @param options.scriptName - Script name (matches FunctionExecution.scriptName)\n * @param options.executionType - Execution type used to discriminate registry name translation\n * @param options.executionContentHash - Content hash of the bundle that ran; pins the download when non-empty\n * @returns Bundled script content, or null when unavailable\n */\nexport async function downloadScriptForMapping(\n options: DownloadScriptForMappingOptions,\n): Promise<string | null> {\n const { client, workspaceId, scriptName, executionType, executionContentHash } = options;\n const registryName = scriptNameToRegistryName(scriptName, executionType);\n if (registryName == null) {\n logger.debug(\n `Script \"${scriptName}\" is not a deployed registry script (e.g. test-run or seed); skipping sourcemap mapping.`,\n );\n return null;\n }\n\n if (executionContentHash === \"\") {\n logger.debug(\n `Function execution \"${scriptName}\" has no contentHash; skipping sourcemap mapping because the exact bundle cannot be identified.`,\n );\n return null;\n }\n\n const pinned = await downloadFunctionScript({\n client,\n workspaceId,\n name: registryName,\n contentHash: executionContentHash,\n });\n if (pinned == null) {\n logger.debug(\n `Could not download pinned script \"${scriptName}\" (registry: \"${registryName}\", contentHash: \"${executionContentHash}\") for stack trace mapping; showing raw stack trace.`,\n );\n return null;\n }\n return pinned.code;\n}\n\nexport const logsCommand = defineAppCommand({\n name: \"logs\",\n description: \"List or get function execution logs.\",\n notes: `When viewing a specific execution that failed, the command displays error details with the stack trace mapped back to your original source files (clickable file links and code snippets, matching \\`function test-run\\` output).\n\nStack traces are mapped only when the execution includes a content hash for the exact build that ran. If the content hash is missing or the build is no longer available, the command falls back to a plain-text error display.`,\n examples: [\n {\n cmd: \"\",\n desc: \"List all function execution logs\",\n },\n {\n cmd: \"<execution-id>\",\n desc: \"Get execution details with logs\",\n },\n {\n cmd: \"--json\",\n desc: \"Output as JSON\",\n },\n {\n cmd: \"<execution-id> --json\",\n desc: \"Get execution details as JSON\",\n },\n ],\n args: z.strictObject({\n ...workspaceArgs,\n ...pagedLogArgs,\n \"execution-id\": arg(z.string().optional(), {\n positional: true,\n description: \"Execution ID (if provided, shows details with logs)\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n if (args.executionId) {\n const { execution } = await client.getFunctionExecution({\n workspaceId,\n executionId: args.executionId,\n });\n\n if (!execution) {\n throw new Error(`Function execution '${args.executionId}' not found.`);\n }\n\n const detail = toFunctionExecutionDetailInfo(execution);\n\n if (args.json) {\n logger.out(detail);\n } else {\n // Download the deployed script when an error is present so the\n // stack trace can be mapped back to original sources via the\n // inline sourcemap. Failure (script removed, no permission, etc.)\n // is non-fatal; we fall back to a plain-text error display.\n const bundledCode = detail.error\n ? await downloadScriptForMapping({\n client,\n workspaceId,\n scriptName: detail.scriptName,\n executionType: execution.type,\n executionContentHash: execution.contentHash,\n })\n : null;\n printFunctionExecutionDetail({ detail, bundledCode });\n }\n } else {\n const pageDirection = toPageDirection(args.order);\n const executions = await fetchPaged(\n async (pageToken, pageSize) => {\n const { executions, nextPageToken } = await client.listFunctionExecutions({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [executions, nextPageToken];\n },\n { limit: args.limit },\n );\n\n const logs = executions.map(toFunctionExecutionListInfo);\n\n if (logs.length === 0 && !args.json) {\n logger.info(\"No function execution logs found.\");\n return;\n }\n logger.out(logs);\n }\n },\n});\n","/**\n * Bundler for function test-run command\n *\n * Bundles a single function file for execution via the TestExecScript API.\n * Generates an entry file based on the detected function type and bundles\n * with rolldown, following the same patterns as the existing bundlers.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport * as rolldown from \"rolldown\";\nimport { createBundleLog } from \"#/cli/shared/bundle-log\";\nimport {\n createLogLevelTreeshakeOptions,\n resolveBundleLogLevel,\n} from \"#/cli/shared/bundle-log-level\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { composeFunctionTreeshakeOptions } from \"#/cli/shared/function-treeshake\";\nimport { resolveInlineSourcemap } from \"#/cli/shared/inline-sourcemap\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport { resolveTSConfigWithFallback } from \"#/cli/shared/resolve-tsconfig\";\nimport { buildResolverPermissionAndInputCheckExpr, INVOKER_EXPR } from \"#/cli/shared/runtime-exprs\";\nimport { createTsconfigPathsPlugin } from \"#/cli/shared/tsconfig-paths-plugin\";\nimport { createGeneratedEntryResolverPlugin } from \"#/cli/shared/virtual-entry\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport type { LogLevelInput } from \"#/configure/config/types\";\nimport type { Resolver } from \"#/types/resolver.generated\";\nimport type { DetectedFunction } from \"./detect\";\n\n/** Machine user info resolved from config and API for bundle-time principal context. */\nexport interface ResolvedMachineUser {\n /** Machine user name */\n name: string;\n /** Machine user ID (UUID from API, or nil UUID if unavailable) */\n id: string;\n /** Attributes from config (null if not found in config, e.g. external auth) */\n attributes: Record<string, unknown> | null;\n /** Attribute list from config */\n attributeList: unknown[];\n}\n\ninterface BundleForTestRunOptions {\n /** Detected function info */\n detected: DetectedFunction;\n /** Absolute path to the source file */\n sourceFile: string;\n /** Directory to resolve the bundler's tsconfig against (the owning config's directory) */\n baseDir: string;\n /** Environment variables (injected into workflow job bundles) */\n env?: Record<string, string | number | boolean>;\n /** Inline sourcemap config value from defineConfig */\n inlineSourcemap?: boolean;\n /** Log level config value from defineConfig */\n logLevel?: LogLevelInput;\n /** Machine user info for injecting principal context into the bundle */\n machineUser: ResolvedMachineUser;\n /** Workspace ID for user context */\n workspaceId: string;\n /** For resolvers: the `defaultPermission` of the namespace owning the file */\n defaultPermission?: Resolver[\"permission\"];\n}\n\ninterface BundleForTestRunResult {\n /** The bundled JavaScript code */\n bundledCode: string;\n /** Name used for the script */\n scriptName: string;\n}\n\n/**\n * Bundle a function file for test-run execution via TestExecScript API.\n * @param options - Bundle options\n * @returns Bundled code and script name\n */\nexport async function bundleForTestRun(\n options: BundleForTestRunOptions,\n): Promise<BundleForTestRunResult> {\n const { detected, sourceFile, baseDir, env = {}, machineUser, workspaceId } = options;\n const inlineSourcemap = resolveInlineSourcemap(options.inlineSourcemap);\n const bundleLogLevel = resolveBundleLogLevel(options.logLevel);\n\n const outputDir = path.resolve(getDistDir(), \"test-run\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n const baseName = `test-run--${detected.name}`;\n const scriptName = `${baseName}.js`;\n const entryPath = path.join(outputDir, `${baseName}.entry.js`);\n\n const entryContent = generateEntry({\n detected,\n sourceFile,\n env,\n machineUser,\n workspaceId,\n defaultPermission: options.defaultPermission,\n });\n fs.writeFileSync(entryPath, entryContent);\n\n const tsconfig = await resolveTSConfigWithFallback(baseDir);\n\n const bundleLog = createBundleLog({ tsconfig });\n const buildResult = await rolldown.build({\n plugins: [\n createGeneratedEntryResolverPlugin(entryPath, baseDir),\n createTsconfigPathsPlugin(),\n platformBundleDefinePlugin,\n ],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: inlineSourcemap ? \"inline\" : true,\n minify: inlineSourcemap\n ? {\n mangle: {\n keepNames: true,\n },\n }\n : true,\n codeSplitting: false,\n // Emit sourcemap `sources` relative to cwd so stack traces resolve\n // back to paths a user can open (e.g. `resolvers/add.ts`), not the\n // rolldown-default virtual output dir which produces spurious `..`\n // segments.\n dir: process.cwd(),\n },\n tsconfig,\n treeshake: composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(bundleLogLevel)]),\n ...bundleLog.options,\n } as rolldown.BuildOptions);\n bundleLog.assertAllResolved();\n\n const bundledCode = buildResult.output[0].code;\n\n return { bundledCode, scriptName };\n}\n\ntype GenerateEntryOptions = {\n detected: DetectedFunction;\n /** Absolute path to the source file */\n sourceFile: string;\n /** Environment variables for workflow job bundles */\n env: Record<string, string | number | boolean>;\n machineUser: ResolvedMachineUser;\n workspaceId: string;\n /** For resolvers: the `defaultPermission` of the namespace owning the file */\n defaultPermission?: Resolver[\"permission\"];\n};\n\n/**\n * Generate entry file content based on the detected function type.\n * @param options - Detected function info and the context embedded into the entry\n * @returns Entry file content string\n */\nfunction generateEntry(options: GenerateEntryOptions): string {\n const { detected, sourceFile, env, machineUser, workspaceId, defaultPermission } = options;\n const absoluteSourcePath = path.resolve(sourceFile);\n\n switch (detected.type) {\n case \"plain\":\n if (detected.namedMain) {\n return ml /* js */ `\n export { main } from \"${absoluteSourcePath}\";\n `;\n }\n return ml /* js */ `\n import _fn from \"${absoluteSourcePath}\";\n export { _fn as main };\n `;\n\n case \"resolver\": {\n // Mirrors the production resolver bundler (services/resolver/bundler.ts):\n // both call buildResolverPermissionAndInputCheckExpr so the permission\n // guard and input validation can't drift between the two entry points.\n // In production, the operationHook injects caller/env into context.\n // For test-run, we embed machine user info since there's no operationHook.\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n const guardAndInputCheckExpr = buildResolverPermissionAndInputCheckExpr({\n permission: detected.permission,\n defaultPermission,\n });\n return ml /* js */ `\n import _internalResolver from \"${absoluteSourcePath}\";\n import { t } from \"@tailor-platform/sdk\";\n\n const $tailor_resolver_body = async (rawInput) => {\n const _caller = ${principalExpr};\n const invoker = (${INVOKER_EXPR}) ?? _caller;\n const context = { input: rawInput, env: ${JSON.stringify(env)}, caller: _caller, invoker };\n ${guardAndInputCheckExpr}\n return _internalResolver.body(context);\n };\n\n export { $tailor_resolver_body as main };\n `;\n }\n\n case \"executor\": {\n // Mirrors the production executor bundler (services/executor/bundler.ts).\n // In production, buildExecutorArgsExpr injects actor/env into args.\n // For test-run, we embed machine user as actor.\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n return ml /* js */ `\n import _internalExecutor from \"${absoluteSourcePath}\";\n\n const _env = ${JSON.stringify(env)};\n const _actor = ${principalExpr};\n\n const __executor_function = async (args) => {\n const _invoker = ${INVOKER_EXPR} ?? _actor;\n return _internalExecutor.operation.body({ ...args, env: _env, actor: _actor, invoker: _invoker });\n };\n\n export { __executor_function as main };\n `;\n }\n\n case \"workflow-job\": {\n // Mirrors the production workflow bundler (services/workflow/bundler.ts).\n // Note: user context is not available in TestExecScript for workflow jobs.\n // The production workflow bundler's user mapping is being fixed in fix/workflow-user.\n const exportName = assertDefined(detected.exportName, \"workflow job export name missing\");\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n return ml /* js */ `\n import { ${exportName} } from \"${absoluteSourcePath}\";\n\n const env = ${JSON.stringify(env)};\n const fallbackInvoker = ${principalExpr};\n\n export async function main(input) {\n const invoker = ${INVOKER_EXPR} ?? fallbackInvoker;\n return await ${exportName}.body(input, { env, invoker });\n }\n `;\n }\n }\n}\n\n/**\n * Build a JSON expression for a machine user TailorPrincipal object.\n * @param machineUser - Resolved machine user info\n * @param workspaceId - Workspace ID\n * @returns JSON string for the user expression\n */\nfunction buildMachinePrincipalExpr(machineUser: ResolvedMachineUser, workspaceId: string): string {\n return JSON.stringify({\n id: machineUser.id,\n type: \"machine_user\",\n workspaceId,\n attributes: machineUser.attributes ?? {},\n attributeList: machineUser.attributeList,\n });\n}\n","/**\n * Function type detection for test-run command\n *\n * Detects the function type (resolver, executor, workflow job, or plain function)\n * by dynamically importing the module and checking against known schemas.\n */\n\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { stripExecutorTriggerArgs } from \"#/cli/services/executor/loader\";\nimport { ExecutorSchema } from \"#/parser/service/executor/index\";\nimport { ResolverSchema } from \"#/parser/service/resolver/index\";\nimport { WorkflowJobSchema } from \"#/parser/service/workflow/index\";\nimport { type FieldRuntime, parseInputFields } from \"#/runtime/field-parse\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type { TailorPrincipal } from \"#/runtime/types\";\nimport type { Resolver } from \"#/types/resolver.generated\";\n\nexport type FunctionType = \"resolver\" | \"executor\" | \"workflow-job\" | \"plain\";\n\ninterface InputParseArgs {\n value: unknown;\n data: unknown;\n invoker: TailorPrincipal | null;\n}\n\n/** Minimal schema interface for local format detection (subset of TailorField) */\ninterface InputSchema {\n parse(args: InputParseArgs): {\n issues?: readonly { message: string; path?: readonly unknown[] }[];\n };\n}\n\nexport interface DetectedFunction {\n /** Detected function type */\n type: FunctionType;\n /** Function name (resolver name, executor name, job name, or filename-derived) */\n name: string;\n /** For workflow jobs: the TypeScript export name needed for bundling */\n exportName?: string;\n /** For plain functions: whether main is a named export rather than default export */\n namedMain?: boolean;\n /** For resolvers: whether the resolver defines an input schema */\n hasInput?: boolean;\n /** For resolvers with input: pre-built schema object with .parse() for local format detection */\n inputSchema?: InputSchema;\n /** For resolvers: the resolver's `permission` config, enforced the same way as production */\n permission?: Resolver[\"permission\"];\n}\n\ninterface DetectFunctionOptions {\n /** Absolute path to the function file */\n filePath: string;\n /** Workflow job name to select (matches the `name` field of createWorkflowJob) */\n jobName?: string;\n}\n\n/**\n * Detect the function type from a file by importing it and checking against schemas.\n * @param options - Detection options\n * @returns Detected function information\n */\nexport async function detectFunctionType(\n options: DetectFunctionOptions,\n): Promise<DetectedFunction> {\n const { filePath, jobName } = options;\n\n const module = await import(pathToFileURL(filePath).href);\n\n // Priority: resolver → executor → workflow job → plain function\n\n // 1. Check resolver\n const resolverResult = ResolverSchema.safeParse(module.default);\n if (resolverResult.success) {\n const rawInput = module.default.input;\n let inputSchema: DetectedFunction[\"inputSchema\"];\n if (rawInput) {\n // Fields built by the user's dynamically imported module match\n // FieldRuntime structurally; the cast stays at this import boundary.\n const fields = rawInput as Record<string, FieldRuntime>;\n inputSchema = {\n parse: (args) => parseInputFields({ ...args, fields }),\n };\n }\n return {\n type: \"resolver\",\n name: resolverResult.data.name,\n hasInput: rawInput != null,\n inputSchema,\n permission: resolverResult.data.permission,\n };\n }\n\n // 2. Check executor (only function/jobFunction kinds)\n const executorResult = ExecutorSchema.safeParse(stripExecutorTriggerArgs(module.default));\n if (executorResult.success) {\n const { operation } = executorResult.data;\n if (operation.kind === \"function\" || operation.kind === \"jobFunction\") {\n return { type: \"executor\", name: executorResult.data.name };\n }\n }\n\n // 3. Check workflow jobs (scan all named exports)\n const workflowJobResult = detectWorkflowJob(module, jobName);\n if (workflowJobResult) {\n return workflowJobResult;\n }\n\n // 4. Check plain function (default export or named export \"main\")\n if (typeof module.default === \"function\") {\n const name = deriveNameFromPath(filePath);\n return { type: \"plain\", name };\n }\n\n if (typeof module.main === \"function\") {\n const name = deriveNameFromPath(filePath);\n return { type: \"plain\", name, namedMain: true };\n }\n\n throw new Error(\n `Could not detect function type from ${filePath}.\\n` +\n \"The file must have one of:\\n\" +\n \" - A default-exported resolver (createResolver)\\n\" +\n \" - A default-exported executor (createExecutor) with function/jobFunction operation\\n\" +\n \" - A named-exported workflow job (createWorkflowJob)\\n\" +\n \" - A default-exported function\\n\" +\n ' - A named-exported \"main\" function',\n );\n}\n\n/**\n * Scan all named exports for workflow jobs.\n * If jobName is specified, find the job whose `.name` matches.\n * If not specified and exactly one job exists, use it.\n * If multiple jobs exist, throw an error with the list.\n * @param module - The imported module\n * @param jobName - Workflow job name to select\n * @returns Detected function or null if no workflow jobs found\n */\nfunction detectWorkflowJob(\n module: Record<string, unknown>,\n jobName?: string,\n): DetectedFunction | null {\n const jobs: Array<{ name: string; exportName: string }> = [];\n\n for (const [exportName, exportValue] of Object.entries(module)) {\n if (exportName === \"default\") continue;\n const result = WorkflowJobSchema.safeParse(exportValue);\n if (result.success) {\n jobs.push({ name: result.data.name, exportName });\n }\n }\n\n if (jobs.length === 0) {\n return null;\n }\n\n if (jobName) {\n const match = jobs.find((j) => j.name === jobName);\n if (!match) {\n const available = jobs.map((j) => ` - \"${j.name}\" (export: ${j.exportName})`).join(\"\\n\");\n throw new Error(`Workflow job \"${jobName}\" not found. Available jobs:\\n${available}`);\n }\n return { type: \"workflow-job\", name: match.name, exportName: match.exportName };\n }\n\n if (jobs.length === 1) {\n const [jobEntry] = jobs;\n const job = assertDefined(jobEntry, \"workflow job missing\");\n return {\n type: \"workflow-job\",\n name: job.name,\n exportName: job.exportName,\n };\n }\n\n const available = jobs.map((j) => ` - \"${j.name}\" (export: ${j.exportName})`).join(\"\\n\");\n throw new Error(`Multiple workflow jobs found. Specify one with --name:\\n${available}`);\n}\n\n/**\n * Derive a script name from a file path (filename without extension).\n * @param filePath - Absolute path to the function file\n * @returns Filename without extension\n */\nfunction deriveNameFromPath(filePath: string): string {\n return path.basename(filePath, path.extname(filePath));\n}\n","/**\n * `tailor function test-run` command\n *\n * Bundles and executes a function on the Tailor Platform server\n * without deploying (applying) the application.\n */\n\nimport * as fs from \"node:fs\";\nimport { create } from \"@bufbuild/protobuf\";\nimport { AuthInvokerSchema } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resolveResolverDefaultPermissionForFile } from \"#/cli/services/resolver/default-permission\";\nimport {\n resolveMachineUserInputSource,\n type MachineUserInputSource,\n workspaceArgs,\n} from \"#/cli/shared/args\";\nimport { initOperatorClient, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadMachineUserName, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { executeScript } from \"#/cli/shared/script-executor\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { bundleForTestRun, type ResolvedMachineUser } from \"./bundle\";\nimport { detectFunctionType } from \"./detect\";\nimport type { Jsonifiable } from \"type-fest\";\n\nexport const testRunCommand = defineAppCommand({\n name: \"test-run\",\n description: \"Run a function on the Tailor Platform server without deploying.\",\n // strip unknown keys\n args: z.object({\n ...workspaceArgs,\n file: arg(z.string(), {\n positional: true,\n description: \"Path to the function file\",\n }),\n name: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Workflow job name to run (matches the `name` field of createWorkflowJob)\",\n }),\n arg: arg(z.string().optional(), {\n alias: \"a\",\n description: \"JSON argument to pass to the function\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Machine user name for authentication. Falls back to the active profile's default machine user.\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_NAME\",\n }),\n config: arg(z.string().default(\"tailor.config.ts\"), {\n alias: \"c\",\n description: \"Path to SDK config file\",\n }),\n }),\n notes: `You can pass either a source file (\\`.ts\\`) or a pre-bundled file (\\`.js\\`).\nWhen a \\`.js\\` file is provided, detection and bundling are skipped and the file is executed as-is.\n\n> [!WARNING]\n> Workflow job \\`.start()\\` calls do not work in test-run mode.\n> Started jobs are not executed; only the target job's \\`body\\` function runs in isolation.`,\n examples: [\n {\n cmd: 'resolvers/add.ts --arg \\'{\"a\":1,\"b\":2}\\'',\n desc: \"Run a resolver with input arguments\",\n },\n {\n cmd: \"workflows/sample.ts --name validate-order\",\n desc: \"Run a specific workflow job by name\",\n },\n {\n cmd: 'build/resolvers/add.js --arg \\'{\"a\":1,\"b\":2}\\'',\n desc: \"Run a pre-bundled .js file directly\",\n },\n ],\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n\n // 1. Resolve and validate file path\n const filePath = path.resolve(args.file);\n if (!fs.existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n\n // 2. Load config (required)\n const { config } = await loadConfig(args.config);\n\n // 3. Resolve auth, workspace, and machine user info (needed before bundling)\n const authNamespace = resolveAuthNamespace(config.auth);\n const machineUserName = await resolveMachineUserName({\n cliMachineUser: args[\"machine-user\"],\n cliMachineUserSource: resolveMachineUserInputSource(args[\"machine-user\"]),\n profile: args.profile,\n authConfig: config.auth,\n });\n\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const machineUser = await resolveMachineUser({\n client,\n workspaceId,\n authNamespace,\n machineUserName,\n authConfig: config.auth,\n });\n\n // 4. Resolve bundled code and script name\n const relativePath = path.relative(process.cwd(), filePath);\n const isPreBundled = filePath.endsWith(\".js\");\n let bundledCode: string;\n let scriptName: string;\n let functionType: string | undefined;\n let functionName: string | undefined;\n\n if (isPreBundled) {\n // Pre-bundled .js file\n scriptName = path.basename(filePath);\n bundledCode = fs.readFileSync(filePath, \"utf-8\");\n logger.info(`Using pre-bundled script ${styles.bold(scriptName)}`);\n } else {\n // Source file: detect type and bundle\n logger.info(`Detecting function type from ${styles.path(relativePath)}`);\n\n const detected = await detectFunctionType({\n filePath,\n jobName: args.name,\n });\n\n functionType = detected.type;\n functionName = detected.name;\n logger.info(`Detected: ${styles.bold(detected.type)} ${styles.info(`\"${detected.name}\"`)}`);\n\n if (detected.type === \"resolver\" && args.arg && !detected.hasInput) {\n logger.warn(\n '--arg is ignored because this resolver has no input schema. Define \"input\" in your resolver to use --arg.',\n );\n args.arg = undefined;\n }\n\n logger.info(\"Bundling...\");\n const baseDir = path.dirname(config.path);\n ({ bundledCode, scriptName } = await bundleForTestRun({\n detected,\n sourceFile: filePath,\n baseDir,\n defaultPermission:\n detected.type === \"resolver\"\n ? resolveResolverDefaultPermissionForFile({\n config: config.resolver,\n filePath,\n baseDir,\n })\n : undefined,\n env: config.env ?? {},\n inlineSourcemap: config.inlineSourcemap,\n logLevel: config.logLevel,\n machineUser,\n workspaceId,\n }));\n logger.info(`Bundled as ${styles.bold(scriptName)}`);\n }\n\n // 5. Execute via TestExecScript\n const invoker = create(AuthInvokerSchema, {\n namespace: authNamespace,\n machineUserName: machineUser.name,\n });\n\n logger.info(`Executing on workspace ${styles.dim(workspaceId)}...`);\n\n let parsedArg: Jsonifiable | undefined;\n if (args.arg !== undefined) {\n try {\n parsedArg = JSON.parse(args.arg);\n } catch (error) {\n throw new Error(`Invalid --arg JSON: ${error instanceof Error ? error.message : error}`, {\n cause: error,\n });\n }\n }\n\n const result = await executeScript({\n client,\n workspaceId,\n name: scriptName,\n code: bundledCode,\n arg: parsedArg,\n invoker,\n });\n\n // 7. Display result\n if (jsonOutput) {\n logger.out({\n success: result.success,\n scriptName,\n functionType,\n functionName,\n logs: result.logs,\n result: result.result,\n error: result.error,\n });\n } else {\n if (result.success) {\n logger.success(\"Execution succeeded\");\n } else {\n logger.error(\"Execution failed\");\n }\n\n if (result.logs.trim()) {\n logger.log(styles.bold(\"\\nLogs:\"));\n for (const line of result.logs.split(\"\\n\")) {\n logger.log(` ${line}`);\n }\n }\n\n if (result.result && result.success) {\n logger.log(styles.bold(\"\\nResult:\"));\n try {\n const parsed = JSON.parse(result.result);\n logger.log(` ${JSON.stringify(parsed, null, 2).split(\"\\n\").join(\"\\n \")}`);\n } catch {\n logger.log(` ${result.result}`);\n }\n }\n\n if (result.error && !result.success) {\n logger.log(styles.bold(\"\\nError:\"));\n const formatted = formatErrorWithSourcemap(result.error, bundledCode, process.cwd());\n if (formatted) {\n logger.log(formatted);\n } else {\n logger.log(` ${styles.error(result.error)}`);\n }\n }\n }\n\n if (!result.success) {\n process.exit(1);\n }\n },\n});\n\n/**\n * Resolve auth namespace from config.\n * @param authConfig - Auth configuration from tailor.config.ts\n * @returns Resolved auth namespace\n */\nfunction resolveAuthNamespace(\n authConfig: { name: string; external?: boolean } | undefined,\n): string {\n if (authConfig?.name) {\n return authConfig.name;\n }\n throw new Error(\"Auth namespace is required. Ensure tailor.config.ts has an auth config.\");\n}\n\ntype ResolveMachineUserNameOptions = {\n cliMachineUser: string | undefined;\n cliMachineUserSource: MachineUserInputSource | undefined;\n profile: string | undefined;\n authConfig:\n | { name: string; external?: boolean; machineUsers?: Record<string, unknown> }\n | undefined;\n};\n\n/**\n * Resolve machine user name from CLI args, profile default, or config.\n * Priority: --machine-user / env > profile default > first key of config.auth.machineUsers > error\n * @param options - Resolution options\n * @returns Resolved machine user name\n */\nasync function resolveMachineUserName(options: ResolveMachineUserNameOptions): Promise<string> {\n const { cliMachineUser, cliMachineUserSource, profile, authConfig } = options;\n\n const resolved = await loadMachineUserName({\n machineUser: cliMachineUser,\n machineUserSource: cliMachineUserSource,\n profile,\n });\n if (resolved) {\n return resolved;\n }\n\n if (authConfig && !(\"external\" in authConfig && authConfig.external)) {\n const machineUsers = authConfig.machineUsers;\n if (machineUsers) {\n const keys = Object.keys(machineUsers);\n if (keys.length > 0) {\n return assertDefined(keys[0], \"machine user key missing\");\n }\n }\n }\n throw new Error(\n \"Machine user is required. Provide --machine-user, set TAILOR_PLATFORM_MACHINE_USER_NAME, set a profile default with 'tailor profile update <profile> --machine-user <name>', or ensure tailor.config.ts has machine users configured.\",\n );\n}\n\ninterface ResolveMachineUserOptions {\n client: OperatorClient;\n workspaceId: string;\n authNamespace: string;\n machineUserName: string;\n authConfig:\n | { name: string; external?: boolean; machineUsers?: Record<string, unknown> }\n | undefined;\n}\n\n/**\n * Resolve full machine user info: name, id (from API), and attributes (from config).\n * @param options - Options for resolving machine user\n * @returns Resolved machine user with id, attributes, and attributeList\n */\nasync function resolveMachineUser(\n options: ResolveMachineUserOptions,\n): Promise<ResolvedMachineUser> {\n const { client, workspaceId, authNamespace, machineUserName, authConfig } = options;\n\n // Get machine user ID from the server\n let id = \"00000000-0000-0000-0000-000000000000\";\n try {\n const { machineUser } = await client.getAuthMachineUser({\n workspaceId,\n authNamespace,\n name: machineUserName,\n });\n if (machineUser?.id) {\n id = machineUser.id;\n }\n } catch {\n logger.debug(`Could not fetch machine user \"${machineUserName}\" from server, using nil UUID`);\n }\n\n // Get attributes from config\n const machineUserConfig = authConfig?.machineUsers?.[machineUserName];\n let attributes: Record<string, unknown> | null = null;\n let attributeList: unknown[] = [];\n if (machineUserConfig && typeof machineUserConfig === \"object\") {\n const cfg = machineUserConfig as {\n attributes?: Record<string, unknown>;\n attributeList?: unknown[];\n };\n attributes = cfg.attributes ?? null;\n attributeList = cfg.attributeList ?? [];\n }\n\n return { name: machineUserName, id, attributes, attributeList };\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { logsCommand } from \"./logs\";\nimport { testRunCommand } from \"./test-run\";\n\nexport const functionCommand = defineCommand({\n name: \"function\",\n description: \"Manage functions\",\n subCommands: {\n get: getCommand,\n list: listCommand,\n logs: logsCommand,\n \"test-run\": testRunCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { generate } from \"#/cli/commands/generate/service\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\n\nexport const generateCommand = defineAppCommand({\n name: \"generate\",\n description: \"Generate files using Tailor configuration.\",\n args: z.strictObject({\n config: arg(z.string().default(\"tailor.config.ts\"), {\n alias: \"c\",\n description: \"Path to SDK config file\",\n }),\n }),\n run: async (args) => {\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n await generate({\n configPath: args.config,\n });\n },\n});\n","import { spawnSync } from \"node:child_process\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\n\nconst detectPackageManager = () => {\n const availablePMs = [\"npm\", \"yarn\", \"pnpm\", \"bun\"];\n const userAgent = process.env.npm_config_user_agent;\n if (!userAgent) return;\n const [name] = userAgent.split(\"/\") as [string, ...string[]];\n if (!availablePMs.includes(name)) return;\n return name;\n};\n\nexport const initCommand = defineAppCommand({\n name: \"init\",\n description: \"Initialize a new project using create-sdk.\",\n args: z.strictObject({\n name: arg(z.string().optional(), {\n positional: true,\n description: \"Project name\",\n }),\n template: arg(z.string().optional(), {\n alias: \"t\",\n description: \"Template name\",\n }),\n }),\n run: async (args) => {\n const packageJson = await readPackageJson();\n const version =\n packageJson.version && packageJson.version !== \"0.0.0\" ? packageJson.version : \"latest\";\n\n let packageManager = detectPackageManager();\n if (!packageManager) {\n logger.warn(\"Could not detect package manager, defaulting to npm\");\n packageManager = \"npm\";\n }\n const initArgs = [\n \"create\",\n `@tailor-platform/sdk@${version}`,\n ...(args.name ? [args.name] : []),\n ...(packageManager === \"npm\" ? [\"--\"] : []),\n ...(args.template ? [\"--template\", args.template] : []),\n ];\n logger.log(`Running: ${packageManager} ${initArgs.join(\" \")}`);\n\n spawnSync(packageManager, initArgs, { stdio: \"inherit\" });\n },\n});\n","import * as crypto from \"node:crypto\";\nimport * as http from \"node:http\";\nimport { generateCodeVerifier } from \"@badgateway/oauth2-client\";\nimport open from \"open\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport {\n closeConnectionPool,\n fetchPlatformMachineUserToken,\n fetchUserInfo,\n initOAuth2Client,\n isDefaultPlatform,\n type PlatformClientConfig,\n} from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n removeLegacyUserAlias,\n saveUserTokens,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\n\nconst redirectPort = 8085;\nconst redirectUri = `http://localhost:${redirectPort}/callback`;\ntype ProfileLoginOptions = {\n profile?: string;\n profileUser?: string;\n platformConfig?: PlatformClientConfig;\n updateCurrentUser?: boolean;\n loginMode?: \"user\" | \"machine-user\";\n};\ntype ProfileUserMismatch = {\n profile: string;\n oldUser: string;\n authenticatedUser: string;\n loginMode: \"user\" | \"machine-user\";\n};\n\nfunction randomState() {\n return crypto.randomBytes(32).toString(\"base64url\");\n}\n\nfunction getProfileUserMismatch(\n args: ProfileLoginOptions,\n authenticatedUser: string,\n authenticatedSubject?: string,\n): ProfileUserMismatch | undefined {\n if (\n !args.profile ||\n !args.profileUser ||\n authenticatedUser === args.profileUser ||\n authenticatedSubject === args.profileUser\n ) {\n return undefined;\n }\n return {\n profile: args.profile,\n oldUser: args.profileUser,\n authenticatedUser,\n loginMode: args.loginMode ?? \"user\",\n };\n}\n\nfunction quoteCommandArg(value: string, platform: NodeJS.Platform = process.platform) {\n if (platform === \"win32\") {\n if (/^[A-Za-z0-9_./:@+=,-]+$/.test(value)) {\n return value;\n }\n return undefined;\n }\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction profileUpdateCommand(mismatch: ProfileUserMismatch) {\n const profileArg = quoteCommandArg(mismatch.profile);\n const userArg = quoteCommandArg(mismatch.authenticatedUser);\n if (profileArg && userArg) {\n return `tailor profile update --user ${userArg} -- ${profileArg}`;\n }\n return [\n \"tailor profile update --user <authenticated-user> -- <profile>\",\n `profile = ${JSON.stringify(mismatch.profile)}`,\n `authenticated user = ${JSON.stringify(mismatch.authenticatedUser)}`,\n ].join(\"\\n\");\n}\n\nfunction retryInstruction(mismatch: ProfileUserMismatch) {\n if (mismatch.loginMode === \"machine-user\") {\n return \"Then retry the original machine-user login command.\";\n }\n const profileArg = quoteCommandArg(mismatch.profile);\n if (!profileArg) {\n return \"Then retry the browser login with the same profile value.\";\n }\n return `Then run:\\n tailor login --profile ${profileArg}`;\n}\n\nfunction profileUserMismatchError(mismatch: ProfileUserMismatch) {\n const updateCommand = profileUpdateCommand(mismatch);\n const nextStep = retryInstruction(mismatch);\n return new Error(ml`\n Profile \"${mismatch.profile}\" is configured for \"${mismatch.oldUser}\", but login authenticated \"${mismatch.authenticatedUser}\".\n The authenticated user has been saved. To use it with this profile, run:\n ${updateCommand}\n ${nextStep}\n `);\n}\n\nfunction shouldUpdateCurrentUser(\n profile: string | undefined,\n platformConfig: PlatformClientConfig | undefined,\n) {\n if (!profile) return true;\n return isDefaultPlatform(platformConfig);\n}\n\nconst startAuthServer = async (args: ProfileLoginOptions = {}) => {\n const client = initOAuth2Client(args.platformConfig);\n const state = randomState();\n const codeVerifier = await generateCodeVerifier();\n\n return new Promise<void>((resolve, reject) => {\n const server = http.createServer(async (req, res) => {\n try {\n if (!req.url?.startsWith(\"/callback\")) {\n throw new Error(\"Invalid callback URL\");\n }\n const tokens = await client.authorizationCode.getTokenFromCodeRedirect(\n `http://${req.headers.host}${req.url}`,\n {\n redirectUri: redirectUri,\n state,\n codeVerifier,\n },\n );\n const userInfo = await fetchUserInfo(tokens.accessToken, args.platformConfig);\n\n const pfConfig = await readPlatformConfig();\n await saveUserTokens(\n pfConfig,\n userInfo.sub,\n {\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken ?? undefined,\n },\n new Date(\n assertDefined(tokens.expiresAt, \"token response missing expiresAt\"),\n ).toISOString(),\n { platformConfig: args.platformConfig, email: userInfo.email },\n );\n const mismatch = getProfileUserMismatch(args, userInfo.email, userInfo.sub);\n if (mismatch) {\n writePlatformConfig(pfConfig);\n throw profileUserMismatchError(mismatch);\n }\n if (args.updateCurrentUser ?? true) {\n pfConfig.current_user = userInfo.sub;\n }\n await removeLegacyUserAlias(pfConfig, userInfo.email, userInfo.sub, args.platformConfig);\n writePlatformConfig(pfConfig);\n\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n status: \"ok\",\n message: \"Successfully authenticated. Please close this window.\",\n }),\n );\n resolve();\n } catch (error) {\n res.writeHead(401);\n res.end(\"Authentication failed\");\n reject(error);\n } finally {\n // Close the server after handling one request.\n server.close();\n }\n });\n\n const timeout = setTimeout(\n () => {\n server.close();\n reject(new Error(\"Login timeout exceeded\"));\n },\n 5 * 60 * 1000,\n );\n\n server.on(\"close\", () => {\n clearTimeout(timeout);\n });\n\n server.on(\"error\", (error) => {\n reject(error);\n });\n\n server.listen(redirectPort, async () => {\n const authorizeUri = await client.authorizationCode.getAuthorizeUri({\n redirectUri,\n state,\n codeVerifier,\n });\n\n logger.info(`Opening browser for login:\\n\\n${authorizeUri}\\n`);\n try {\n await open(authorizeUri);\n } catch {\n logger.warn(\"Failed to open browser automatically. Please open the URL above manually.\");\n }\n });\n });\n};\n\nasync function loginAsMachineUser(\n args: { clientId: string; clientSecret?: string } & ProfileLoginOptions,\n) {\n const clientSecret = args.clientSecret ?? (await prompt.password({ message: \"Client secret\" }));\n const tokens = await fetchPlatformMachineUserToken(\n args.clientId,\n clientSecret,\n args.platformConfig,\n );\n\n const pfConfig = await readPlatformConfig();\n await saveUserTokens(\n pfConfig,\n args.clientId,\n { accessToken: tokens.accessToken },\n new Date(assertDefined(tokens.expiresAt, \"token response missing expiresAt\")).toISOString(),\n { platformConfig: args.platformConfig },\n );\n const mismatch = getProfileUserMismatch(args, args.clientId);\n if (mismatch) {\n writePlatformConfig(pfConfig);\n throw profileUserMismatchError(mismatch);\n }\n if (args.updateCurrentUser ?? true) {\n pfConfig.current_user = args.clientId;\n }\n writePlatformConfig(pfConfig);\n}\n\nexport const loginCommand = defineAppCommand({\n name: \"login\",\n description: \"Login to Tailor Platform.\",\n args: z.xor([\n z\n .strictObject({\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for login.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n })\n .describe(\"User Login\"),\n z\n .strictObject({\n \"machine-user\": arg(z.literal(true), {\n description: \"Login as a platform machine user.\",\n required: true,\n }),\n \"client-id\": arg(z.string(), {\n description: \"Client ID\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID\",\n required: true,\n }),\n \"client-secret\": arg(z.string().optional(), {\n description: \"Client secret\",\n env: \"TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET\",\n }),\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for login.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n })\n .describe(\"Machine User Login\"),\n ]),\n run: async (args) => {\n try {\n let platformConfig: PlatformClientConfig | undefined;\n let profileUser: string | undefined;\n if (\"profile\" in args && args.profile) {\n const pfConfig = await readPlatformConfig();\n const profileEntry = pfConfig.profiles[args.profile];\n if (!profileEntry) {\n throw new Error(`Profile \"${args.profile}\" not found`);\n }\n platformConfig = platformConfigFromProfile(profileEntry);\n profileUser = profileEntry.user;\n }\n const updateCurrentUser = shouldUpdateCurrentUser(args.profile, platformConfig);\n if (\"machine-user\" in args) {\n await loginAsMachineUser({\n clientId: args.clientId,\n clientSecret: args.clientSecret,\n profile: args.profile,\n profileUser,\n platformConfig,\n updateCurrentUser,\n loginMode: \"machine-user\",\n });\n } else {\n await startAuthServer({\n profile: args.profile,\n profileUser,\n platformConfig,\n updateCurrentUser,\n loginMode: \"user\",\n });\n }\n logger.success(\"Successfully logged in to Tailor Platform.\");\n } finally {\n await closeConnectionPool();\n }\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defaultPlatformBaseUrl, initOAuth2Client, isDefaultPlatform } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n deleteUserTokens,\n hasAnyUserTokenEntry,\n hasUserTokenEntry,\n loadStoredUserTokens,\n platformConfigFromProfile,\n readPlatformConfig,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const logoutCommand = defineAppCommand({\n name: \"logout\",\n description: \"Logout from Tailor Platform.\",\n args: z.strictObject({\n profile: arg(z.string().optional(), {\n alias: \"p\",\n description: \"Workspace profile whose platform settings should be used for logout.\",\n env: \"TAILOR_PLATFORM_PROFILE\",\n }),\n }),\n run: async (args) => {\n const profile = args.profile || process.env.TAILOR_PLATFORM_PROFILE;\n const pfConfig = await readPlatformConfig();\n const profileEntry = profile ? pfConfig.profiles[profile] : undefined;\n if (profile && !profileEntry) {\n throw new Error(`Profile \"${profile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const currentUser = profileEntry ? profileEntry.user : pfConfig.current_user;\n const deletesDefaultToken = isDefaultPlatform(platformConfig);\n const lookupOptions = profile ? { allowLegacyUserKey: true } : undefined;\n if (!currentUser) {\n logger.info(\"You are not logged in.\");\n return;\n }\n const hasDefaultUserToken = () =>\n hasUserTokenEntry(pfConfig, currentUser, { platformUrl: defaultPlatformBaseUrl });\n const shouldClearCurrentUser = () =>\n pfConfig.current_user === currentUser &&\n (deletesDefaultToken\n ? !hasDefaultUserToken()\n : !hasAnyUserTokenEntry(pfConfig, currentUser) && !hasDefaultUserToken());\n let storedTokens: Awaited<ReturnType<typeof loadStoredUserTokens>>;\n let tokenLoadFailed = false;\n try {\n storedTokens = await loadStoredUserTokens(\n pfConfig,\n currentUser,\n platformConfig,\n lookupOptions,\n );\n } catch (error) {\n tokenLoadFailed = true;\n logger.warn(`Failed to revoke token: ${error instanceof Error ? error.message : error}`);\n }\n if (!storedTokens && !tokenLoadFailed) {\n logger.info(\"You are not logged in.\");\n if (shouldClearCurrentUser()) {\n pfConfig.current_user = null;\n }\n writePlatformConfig(pfConfig);\n return;\n }\n\n if (storedTokens) {\n try {\n const client = initOAuth2Client(platformConfig);\n const tokenTypeHint = storedTokens.refreshToken ? \"refresh_token\" : \"access_token\";\n await client.revoke(\n {\n accessToken: storedTokens.accessToken,\n refreshToken: storedTokens.refreshToken ?? null,\n expiresAt: Date.parse(storedTokens.userEntry.token_expires_at),\n },\n tokenTypeHint,\n );\n } catch (error) {\n logger.warn(`Failed to revoke token: ${error instanceof Error ? error.message : error}`);\n }\n }\n\n await deleteUserTokens(pfConfig, currentUser, platformConfig, lookupOptions);\n if (shouldClearCurrentUser()) {\n pfConfig.current_user = null;\n }\n writePlatformConfig(pfConfig);\n logger.success(\"Successfully logged out from Tailor Platform.\");\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\nimport { tokenCommand } from \"./token\";\n\nexport const machineuserCommand = defineCommand({\n name: \"machineuser\",\n description: \"Manage machine users in your Tailor Platform application.\",\n subCommands: {\n list: listCommand,\n token: tokenCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\n\nexport const oauth2clientCommand = defineCommand({\n name: \"oauth2client\",\n description: \"Manage OAuth2 clients in your Tailor Platform application.\",\n subCommands: {\n list: listCommand,\n get: getCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import open from \"open\";\nimport { z } from \"zod\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadConsoleBaseUrl, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const openCommand = defineAppCommand({\n name: \"open\",\n description: \"Open Tailor Platform Console.\",\n args: z.strictObject({\n ...deploymentArgs,\n }),\n run: async (args) => {\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n const { config } = await loadConfig(args.config);\n const applicationName = config.name;\n const consolePath = `/workspaces/${workspaceId}/applications/${encodeURIComponent(applicationName)}/overview`;\n const consoleBaseUrl = await loadConsoleBaseUrl({\n profile: args.profile,\n ...(args[\"workspace-id\"] !== undefined ? { allowMissingProfile: true } : {}),\n });\n const consoleUrl = new URL(consolePath, consoleBaseUrl).toString();\n const jsonOutput = logger.jsonMode;\n\n logger.info(\"Opening Tailor Platform Console...\");\n\n let opened = true;\n try {\n await open(consoleUrl);\n } catch {\n opened = false;\n }\n\n if (jsonOutput) {\n logger.out({ consoleUrl, workspaceId, applicationName, opened });\n return;\n }\n\n if (opened) {\n logger.out(`Console URL: ${consoleUrl}`);\n logger.out(`Workspace ID: ${workspaceId}`);\n logger.out(`Application Name: ${applicationName}`);\n } else {\n logger.warn(\n `Failed to open browser automatically. Please open this URL manually:\\n${consoleUrl}`,\n );\n }\n },\n});\n","import { defineCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport const folderCommand = defineCommand({\n name: \"folder\",\n description: \"Manage organization folders.\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n get: getCommand,\n list: listCommand,\n update: updateCommand,\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { folderCommand } from \"./folder\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { treeCommand } from \"./tree\";\nimport { updateCommand } from \"./update\";\n\nexport const organizationCommand = defineCommand({\n name: \"organization\",\n description: \"Manage Tailor Platform organizations.\",\n subCommands: {\n folder: folderCommand,\n get: getCommand,\n list: listCommand,\n tree: treeCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","/**\n * Top-level builtin command names. A plugin named the same as one of these is\n * shadowed by the builtin and can never be dispatched.\n *\n * This list is the single source of truth used by `plugin list` to flag\n * shadowed plugins without importing the (cyclic) command tree. It is kept in\n * sync with `main-command.ts` by a drift test in `options.test.ts`.\n */\nexport const BUILTIN_COMMAND_NAMES = [\n \"api\",\n \"auth\",\n \"authconnection\",\n \"crashreport\",\n \"deploy\",\n \"executor\",\n \"function\",\n \"generate\",\n \"init\",\n \"login\",\n \"logout\",\n \"machineuser\",\n \"oauth2client\",\n \"open\",\n \"organization\",\n \"plugin\",\n \"profile\",\n \"query\",\n \"remove\",\n \"secret\",\n \"setup\",\n \"show\",\n \"skills\",\n \"staticwebsite\",\n \"tailordb\",\n \"upgrade\",\n \"user\",\n \"workflow\",\n \"workspace\",\n] as const;\n","import { spawn } from \"node:child_process\";\nimport { accessSync, constants, readdirSync } from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"pathe\";\nimport { getOAuth2ClientId, getPlatformBaseUrl, type PlatformClientConfig } from \"./client\";\nimport {\n loadAccessToken,\n loadConfigPath,\n loadPlatformClientConfig,\n loadWorkspaceId,\n readPlatformConfig,\n} from \"./context\";\nimport { logger } from \"./logger\";\nimport { readPackageJson } from \"./package-json\";\n\n/**\n * npm packages known to provide a plugin slug, keyed by the slug the\n * dispatcher resolves (command path joined with `-`). Used to suggest an\n * install command when the plugin executable is not found.\n */\nconst KNOWN_PLUGIN_PACKAGES: Record<string, string> = {\n seed: \"@tailor-platform/sdk-plugin-seed\",\n \"tailordb-erd\": \"@tailor-platform/sdk-plugin-tailordb-erd\",\n};\n\n/**\n * A plugin discovered on the filesystem. `tailor <name>` dispatches to the\n * external `tailor-<name>` executable.\n */\nexport interface DiscoveredPlugin {\n /** Plugin name (the part after the `<cli>-` prefix). */\n name: string;\n /** Absolute path to the executable. */\n path: string;\n /** Where the executable was found. */\n source: \"node_modules\" | \"path\";\n}\n\n/** PATH entry separator (`;` on Windows, `:` elsewhere). */\nconst pathDelimiter = process.platform === \"win32\" ? \";\" : \":\";\n\n/**\n * Yield `start` and each ancestor directory up to the filesystem root.\n * @param start - Directory to start from\n * @yields Each ancestor directory, starting with `start`\n */\nfunction* ancestorDirs(start: string): Generator<string> {\n let dir = path.resolve(start);\n // Walk up until `dirname` stops changing (the filesystem root), yielding the\n // root on the final iteration.\n let parent = path.dirname(dir);\n while (parent !== dir) {\n yield dir;\n dir = parent;\n parent = path.dirname(dir);\n }\n yield dir;\n}\n\n/** Fallback executable extensions when `PATHEXT` is unset (Windows). */\nconst DEFAULT_PATHEXT = \".COM;.EXE;.BAT;.CMD;.PS1\";\n\n/**\n * Lowercased executable extensions from `PATHEXT` (Windows).\n * @returns Recognized executable extensions (e.g. `.exe`, `.cmd`)\n */\nfunction windowsExecutableExts(): string[] {\n return (process.env.PATHEXT ?? DEFAULT_PATHEXT)\n .split(\";\")\n .map((e) => e.trim().toLowerCase())\n .filter(Boolean);\n}\n\n/**\n * Check whether a path exists and is runnable: X_OK on POSIX; on Windows, the\n * file must exist and either be extension-less (shebang script) or carry a\n * `PATHEXT` extension, so plain data files are not mistaken for plugins.\n * @param filePath - Path to check\n * @returns Whether the path is an executable file\n */\nfunction isExecutable(filePath: string): boolean {\n try {\n accessSync(filePath, process.platform === \"win32\" ? constants.F_OK : constants.X_OK);\n } catch {\n return false;\n }\n if (process.platform === \"win32\") {\n const ext = path.extname(filePath).toLowerCase();\n return ext === \"\" || windowsExecutableExts().includes(ext);\n }\n return true;\n}\n\n/**\n * Candidate file names for a plugin binary, accounting for Windows extensions.\n * @param binName - Base binary name (e.g. `tailor-foo`)\n * @returns Ordered candidate file names\n */\nfunction binaryCandidates(binName: string): string[] {\n if (process.platform !== \"win32\") {\n return [binName];\n }\n // Bare name first (shebang scripts), then PATHEXT variants.\n return [binName, ...windowsExecutableExts().map((ext) => `${binName}${ext}`)];\n}\n\n/**\n * Directories on the user's PATH.\n * @returns PATH entries\n */\nfunction pathDirs(): string[] {\n return (process.env.PATH ?? \"\").split(pathDelimiter).filter(Boolean);\n}\n\n/**\n * Nearest `node_modules/.bin` directories, walking up from the current working\n * directory. Project-local bins take precedence over those higher in the tree.\n * @returns Ordered `node_modules/.bin` directories\n */\nfunction nodeModulesBinDirs(): string[] {\n const dirs: string[] = [];\n for (const dir of ancestorDirs(process.cwd())) {\n dirs.push(path.join(dir, \"node_modules\", \".bin\"));\n }\n return dirs;\n}\n\n/**\n * Find the first existing executable for the given base name across a set of\n * directories.\n * @param dirs - Directories to search\n * @param binName - Base binary name\n * @returns Absolute path, or undefined when not found\n */\nfunction findExecutableIn(dirs: string[], binName: string): string | undefined {\n const candidates = binaryCandidates(binName);\n for (const dir of dirs) {\n for (const candidate of candidates) {\n const full = path.join(dir, candidate);\n if (isExecutable(full)) return full;\n }\n }\n return undefined;\n}\n\n/**\n * Resolve a plugin executable by name.\n * Search order: project-local `node_modules/.bin` (nearest first), then PATH.\n * @param name - Plugin name (without the `<cli>-` prefix)\n * @param cliName - The host CLI name (e.g. `tailor`)\n * @returns The discovered plugin, or null when not found\n */\nexport function resolvePlugin(name: string, cliName: string): DiscoveredPlugin | null {\n // Reject names that could escape the `<cli>-` prefix via path traversal\n // (e.g. `../evil`) or embed a NUL, before joining them into a filesystem path.\n if (name.includes(\"/\") || name.includes(\"\\\\\") || name.includes(\"\\0\")) {\n return null;\n }\n const binName = `${cliName}-${name}`;\n\n const fromNodeModules = findExecutableIn(nodeModulesBinDirs(), binName);\n if (fromNodeModules) {\n return { name, path: fromNodeModules, source: \"node_modules\" };\n }\n\n const fromPath = findExecutableIn(pathDirs(), binName);\n if (fromPath) {\n return { name, path: fromPath, source: \"path\" };\n }\n\n return null;\n}\n\n/**\n * Strip a known binary extension from a file name (Windows).\n * @param fileName - File name\n * @returns File name without a recognized executable extension\n */\nfunction stripBinExt(fileName: string): string {\n if (process.platform !== \"win32\") return fileName;\n const ext = path.extname(fileName);\n return ext ? fileName.slice(0, -ext.length) : fileName;\n}\n\n/**\n * Discover all plugins reachable from `node_modules/.bin` and PATH.\n * Earlier entries win on name collisions (project-local over PATH).\n * @param cliName - The host CLI name (e.g. `tailor`)\n * @returns Discovered plugins, deduped by name\n */\nexport function listPlugins(cliName: string): DiscoveredPlugin[] {\n const prefix = `${cliName}-`;\n const seen = new Map<string, DiscoveredPlugin>();\n\n const scan = (dirs: string[], source: DiscoveredPlugin[\"source\"]) => {\n for (const dir of dirs) {\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n const base = stripBinExt(entry);\n if (!base.startsWith(prefix) || base.length === prefix.length) continue;\n const name = base.slice(prefix.length);\n if (seen.has(name)) continue;\n const full = path.join(dir, entry);\n if (!isExecutable(full)) continue;\n seen.set(name, { name, path: full, source });\n }\n }\n };\n\n scan(nodeModulesBinDirs(), \"node_modules\");\n scan(pathDirs(), \"path\");\n\n return [...seen.values()];\n}\n\n/**\n * Options for {@link buildPluginEnv}.\n */\ninterface PluginContextOptions {\n /** Active profile used to resolve the workspace, user, and token. */\n profile?: string | undefined;\n /** Skip platform context (URL, client ID, workspace, user, token) injection. */\n skipPlatformContext?: boolean;\n}\n\n/**\n * Resolve the active user identifier, preferring the stored email over the\n * internal user key.\n * @param profile - Active profile name, if any\n * @returns The resolved user (email when known), or undefined when not logged in\n */\nasync function resolveActiveUser(profile?: string): Promise<string | undefined> {\n const config = await readPlatformConfig();\n const user = profile ? config.profiles[profile]?.user : config.current_user;\n if (!user) return undefined;\n return config.users[user]?.email ?? user;\n}\n\n/**\n * Build the environment variables injected into a dispatched plugin.\n * Workspace, user, and token are resolved best-effort: whichever the current\n * context can provide is injected, and the rest are omitted so auth-free\n * plugins still run.\n * @param options - Plugin context options\n * @returns Environment variables to merge into the child process env\n */\nasync function buildPluginEnv(options: PluginContextOptions = {}): Promise<Record<string, string>> {\n const { profile } = options;\n const env: Record<string, string> = {};\n\n const binPath = process.argv[1];\n if (binPath) {\n env.TAILOR_BIN = binPath;\n }\n\n try {\n const { version } = await readPackageJson();\n if (version) env.TAILOR_VERSION = version;\n } catch {\n // Version is informational; skip when unavailable.\n }\n\n const configPath = loadConfigPath();\n if (configPath) {\n env.TAILOR_CONFIG_PATH = configPath;\n }\n\n // An explicit --env-file supplies the plugin's platform context itself.\n // Injected values would shadow it (the plugin's env-file loader never\n // overwrites pre-existing keys), so skip context injection entirely.\n if (options.skipPlatformContext) {\n return env;\n }\n\n // Resolve the active profile's platform settings so the injected URL and\n // OAuth client match the profile the token and workspace belong to.\n let platformConfig: PlatformClientConfig | undefined;\n try {\n platformConfig = await loadPlatformClientConfig({ profile, allowMissingProfile: true });\n } catch {\n // Fall back to env/default platform settings when the profile is unreadable.\n }\n env.TAILOR_PLATFORM_URL = getPlatformBaseUrl(platformConfig);\n env.TAILOR_PLATFORM_OAUTH2_CLIENT_ID = getOAuth2ClientId(platformConfig);\n\n try {\n env.TAILOR_PLATFORM_WORKSPACE_ID = await loadWorkspaceId({ profile });\n } catch {\n // No workspace resolvable; plugins that need it surface their own error.\n }\n\n try {\n const user = await resolveActiveUser(profile);\n if (user) env.TAILOR_PLATFORM_USER = user;\n } catch {\n // User context is best-effort; skip when the config is unreadable.\n }\n\n try {\n const token = await loadAccessToken({ profile });\n if (token) env.TAILOR_PLATFORM_TOKEN = token;\n } catch {\n // Not logged in (or no token): dispatch without a token so auth-free\n // plugins still work. Auth-requiring plugins surface their own error\n // (e.g. via `tailor auth token`).\n }\n\n return env;\n}\n\n/**\n * Map an exit signal to a conventional exit code (128 + signal number).\n * @param signal - Signal name\n * @returns Exit code\n */\nfunction signalToExitCode(signal: NodeJS.Signals): number {\n const num = os.constants.signals[signal];\n return typeof num === \"number\" ? 128 + num : 1;\n}\n\n/**\n * Build the command + args for spawning a plugin, handling Windows shebang\n * scripts via `sh` (following the `gh` extension dispatcher).\n * @param pluginPath - Resolved plugin executable path\n * @param args - Args to forward to the plugin\n * @returns Spawn command, args, and whether a shell is required\n */\nfunction buildSpawnTarget(\n pluginPath: string,\n args: readonly string[],\n): { command: string; args: string[]; shell: boolean } {\n if (process.platform !== \"win32\") {\n return { command: pluginPath, args: [...args], shell: false };\n }\n\n const ext = path.extname(pluginPath).toLowerCase();\n if (ext === \".exe\" || ext === \".com\") {\n return { command: pluginPath, args: [...args], shell: false };\n }\n if (ext === \".cmd\" || ext === \".bat\") {\n // .cmd/.bat must run through the shell on Windows.\n return { command: pluginPath, args: [...args], shell: true };\n }\n if (ext === \".ps1\") {\n // PowerShell scripts are not directly executable via spawn.\n const pwsh =\n findExecutableIn(pathDirs(), \"pwsh\") ??\n findExecutableIn(pathDirs(), \"powershell\") ??\n \"powershell\";\n return {\n command: pwsh,\n args: [\"-NoProfile\", \"-ExecutionPolicy\", \"Bypass\", \"-File\", pluginPath, ...args],\n shell: false,\n };\n }\n\n // Extension-less shebang script: dispatch through `sh` (Git for Windows).\n const sh = findExecutableIn(pathDirs(), \"sh\") ?? \"sh\";\n return { command: sh, args: [\"-c\", 'command \"$@\"', \"--\", pluginPath, ...args], shell: false };\n}\n\n/**\n * Check whether args forwarded to a plugin carry an explicit env-file flag.\n * Scanning stops at a `--` terminator. The check is presence-only:\n * `--env-file-if-exists` counts even when the named file does not exist, so\n * no platform context is injected in that case either.\n * @param args - Args forwarded to the plugin\n * @returns Whether an `--env-file`/`-e`/`--env-file-if-exists` flag is present\n */\nexport function hasEnvFileFlag(args: readonly string[]): boolean {\n for (const token of args) {\n if (token === \"--\") return false;\n if (token === \"--env-file\" || token === \"-e\" || token === \"--env-file-if-exists\") {\n return true;\n }\n if (\n token.startsWith(\"--env-file=\") ||\n token.startsWith(\"-e=\") ||\n token.startsWith(\"--env-file-if-exists=\")\n ) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Extract an explicit `--profile`/`-p` value from args forwarded to a plugin,\n * so the injected platform context matches the profile the plugin will use.\n * Scanning stops at a `--` terminator; the last occurrence wins.\n * @param args - Args forwarded to the plugin\n * @returns The explicit profile value, or undefined when not present\n */\nexport function explicitProfileFromArgs(args: readonly string[]): string | undefined {\n let profile: string | undefined;\n for (let i = 0; i < args.length; i++) {\n const token = args[i];\n if (token === undefined || token === \"--\") break;\n if (token === \"--profile\" || token === \"-p\") {\n const next = args[i + 1];\n if (next !== undefined && !next.startsWith(\"-\")) {\n profile = next;\n i++;\n }\n continue;\n }\n if (token.startsWith(\"--profile=\")) {\n profile = token.slice(\"--profile=\".length);\n } else if (token.startsWith(\"-p=\")) {\n profile = token.slice(\"-p=\".length);\n }\n }\n return profile || undefined;\n}\n\n/**\n * Parameters for {@link dispatchPlugin}.\n */\ninterface DispatchPluginParams {\n /** Plugin name (the part after the `<cli>-` prefix). */\n name: string;\n /** Args to forward to the plugin. */\n args: readonly string[];\n /** The host CLI name (e.g. `tailor`). */\n cliName: string;\n /** Parent command path preceding the unknown subcommand, if any. */\n commandPath?: readonly string[] | undefined;\n /** Active profile name, if any. */\n profile?: string | undefined;\n}\n\n/**\n * Build the plugin slug from the known command path plus the unknown name,\n * so `tailor tailordb erd` resolves `tailor-tailordb-erd`.\n * @param commandPath - Parent command path preceding the unknown subcommand\n * @param name - Unknown subcommand name\n * @returns The plugin slug\n */\nfunction pluginSlug(commandPath: readonly string[] | undefined, name: string): string {\n return [...(commandPath ?? []), name].join(\"-\");\n}\n\n/**\n * Resolve and execute a plugin, forwarding stdio and propagating its exit code.\n * @param params - Dispatch parameters\n * @returns The plugin's exit code, or undefined when no matching plugin exists\n */\nexport async function dispatchPlugin(params: DispatchPluginParams): Promise<number | undefined> {\n const slug = pluginSlug(params.commandPath, params.name);\n const plugin = resolvePlugin(slug, params.cliName);\n if (!plugin) {\n return undefined;\n }\n\n const profile = explicitProfileFromArgs(params.args) ?? params.profile;\n const env = {\n ...process.env,\n ...(await buildPluginEnv({ profile, skipPlatformContext: hasEnvFileFlag(params.args) })),\n };\n const { command, args, shell } = buildSpawnTarget(plugin.path, params.args);\n\n return await new Promise<number>((resolve) => {\n const child = spawn(command, args, { stdio: \"inherit\", env, shell });\n child.on(\"error\", (error) => {\n logger.error(`Failed to run plugin \"${params.cliName}-${slug}\": ${error.message}`);\n resolve(1);\n });\n child.on(\"close\", (code, signal) => {\n if (signal) {\n resolve(signalToExitCode(signal));\n } else {\n resolve(code ?? 0);\n }\n });\n });\n}\n\n/**\n * Dispatch a plugin, printing an install hint when the subcommand maps to a\n * known plugin package that is not installed.\n * @param params - Dispatch parameters\n * @returns The plugin's exit code (1 after an install hint), or undefined when\n * the subcommand matches no plugin and no known package\n */\nexport async function dispatchPluginWithInstallHint(\n params: DispatchPluginParams,\n): Promise<number | undefined> {\n const exitCode = await dispatchPlugin(params);\n if (exitCode !== undefined) {\n return exitCode;\n }\n const knownPackage = KNOWN_PLUGIN_PACKAGES[pluginSlug(params.commandPath, params.name)];\n if (!knownPackage) {\n return undefined;\n }\n const fullCommand = [params.cliName, ...(params.commandPath ?? []), params.name].join(\" \");\n logger.error(\n `\"${fullCommand}\" is provided by the ${knownPackage} CLI plugin, which is not installed.`,\n );\n logger.info(`Install it with: npm install -D ${knownPackage}`);\n return 1;\n}\n","import { z } from \"zod\";\nimport { BUILTIN_COMMAND_NAMES } from \"#/cli/shared/builtin-commands\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { listPlugins } from \"#/cli/shared/plugin\";\nimport ml from \"#/utils/multiline\";\n\ninterface PluginListItem {\n name: string;\n source: \"node_modules\" | \"path\";\n path: string;\n /** True when a builtin command of the same name shadows this plugin. */\n shadowed: boolean;\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description:\n \"List discovered plugins (executables named `<cli>-<name>` on PATH or node_modules/.bin).\",\n args: z.strictObject({}),\n run: async () => {\n const pkg = await readPackageJson();\n const cliName = Object.keys(pkg.bin ?? {})[0] || \"tailor\";\n const builtins = new Set<string>(BUILTIN_COMMAND_NAMES);\n\n const plugins = listPlugins(cliName);\n if (plugins.length === 0) {\n logger.info(ml`\n No plugins found.\n Install an executable named \"${cliName}-<name>\" on your PATH or in node_modules/.bin,\n then run it with \"${cliName} <name>\".\n `);\n if (logger.jsonMode) {\n logger.out([]);\n }\n return;\n }\n\n const items: PluginListItem[] = plugins.map((plugin) => ({\n name: plugin.name,\n source: plugin.source,\n path: plugin.path,\n shadowed: builtins.has(plugin.name),\n }));\n\n logger.out(items);\n\n for (const item of items) {\n if (item.shadowed) {\n logger.warn(\n `Plugin \"${cliName}-${item.name}\" is shadowed by the builtin \"${cliName} ${item.name}\" command and will not be dispatched.`,\n );\n }\n }\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { listCommand } from \"./list\";\n\nexport const pluginCommand = defineCommand({\n name: \"plugin\",\n description: \"Manage and inspect CLI plugins (beta).\",\n subCommands: {\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { fetchLatestToken, readPlatformConfig, writePlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new profile.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n user: arg(z.string(), {\n alias: \"u\",\n description: \"User email address or machine user client ID\",\n }),\n \"workspace-id\": arg(z.string(), {\n alias: \"w\",\n description: \"Workspace ID\",\n }),\n permission: arg(z.enum([\"write\", \"read\"]).default(\"write\"), {\n description:\n \"Profile permission. 'read' blocks all write commands while the profile is active.\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Default machine user name for application-data commands (query, workflow start, function test-run, machineuser token).\",\n }),\n \"machine-user-override\": arg(z.enum([\"allow\", \"deny\"]).optional(), {\n description:\n \"Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user.\",\n }),\n \"platform-url\": arg(z.url().optional(), {\n description: \"Platform API base URL for this profile.\",\n env: \"TAILOR_PLATFORM_URL\",\n }),\n \"oauth2-client-id\": arg(z.string().optional(), {\n description: \"OAuth2 client ID for logging in to this profile's platform.\",\n env: \"TAILOR_PLATFORM_OAUTH2_CLIENT_ID\",\n }),\n \"console-url\": arg(z.url().optional(), {\n description: \"Console base URL for this profile.\",\n env: \"TAILOR_PLATFORM_CONSOLE_URL\",\n }),\n }),\n run: async (args) => {\n if (args[\"machine-user-override\"] === \"deny\" && !args[\"machine-user\"]) {\n throw new Error(\"--machine-user-override deny requires --machine-user.\");\n }\n\n const config = await readPlatformConfig();\n\n // Check if profile already exists\n if (config.profiles[args.name]) {\n throw new Error(`Profile \"${args.name}\" already exists.`);\n }\n\n // Check if user exists\n const platformConfigInput = {\n ...(args[\"platform-url\"] ? { platformUrl: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2ClientId: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { consoleUrl: args[\"console-url\"] } : {}),\n };\n const platformConfig =\n Object.keys(platformConfigInput).length > 0 ? platformConfigInput : undefined;\n const { accessToken: token, user: resolvedUser } = await fetchLatestToken(\n config,\n args.user,\n platformConfig,\n );\n\n // Check if workspace exists\n const client = await initOperatorClient(token, platformConfig);\n const workspaces = await fetchAll(async (pageToken, maxPageSize) => {\n const { workspaces, nextPageToken } = await client.listWorkspaces({\n pageToken,\n pageSize: maxPageSize,\n });\n return [workspaces, nextPageToken];\n });\n\n const workspace = workspaces.find((ws) => ws.id === args[\"workspace-id\"]);\n if (!workspace) {\n throw new Error(`Workspace \"${args[\"workspace-id\"]}\" not found.`);\n }\n\n // Create new profile\n config.profiles[args.name] = {\n user: resolvedUser,\n workspace_id: args[\"workspace-id\"],\n ...(args.permission === \"read\" ? { readonly: true } : {}),\n ...(args[\"machine-user\"] ? { machine_user: args[\"machine-user\"] } : {}),\n ...(args[\"machine-user-override\"] === \"deny\"\n ? { machine_user_override: \"deny\" as const }\n : {}),\n ...(args[\"platform-url\"] ? { platform_url: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2_client_id: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { console_url: args[\"console-url\"] } : {}),\n };\n writePlatformConfig(config);\n\n if (!args.json) {\n logger.success(`Profile \"${args.name}\" created successfully.`);\n }\n\n // Show profile info\n const profileInfo: ProfileInfo = {\n name: args.name,\n user: resolvedUser,\n workspaceId: args[\"workspace-id\"],\n permission: args.permission,\n ...(args[\"machine-user\"]\n ? {\n machineUser: args[\"machine-user\"],\n machineUserOverride: args[\"machine-user-override\"] ?? \"allow\",\n }\n : {}),\n ...(args[\"platform-url\"] ? { platformUrl: args[\"platform-url\"] } : {}),\n ...(args[\"oauth2-client-id\"] ? { oauth2ClientId: args[\"oauth2-client-id\"] } : {}),\n ...(args[\"console-url\"] ? { consoleUrl: args[\"console-url\"] } : {}),\n };\n logger.out(profileInfo);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { readPlatformConfig, writePlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a profile.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n\n // Check if profile exists\n if (!config.profiles[args.name]) {\n throw new Error(`Profile \"${args.name}\" not found.`);\n }\n\n // Delete profile\n delete config.profiles[args.name];\n writePlatformConfig(config);\n\n logger.success(`Profile \"${args.name}\" deleted successfully.`);\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { readPlatformConfig } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all profiles.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n\n const profiles = Object.entries(config.profiles);\n if (profiles.length === 0) {\n logger.info(ml`\n No profiles found.\n Please create a profile first using 'tailor profile create' command.\n `);\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const profileInfos: ProfileInfo[] = profiles.map(([name, profile]) => {\n const p = assertDefined(profile, `profile entry \"${name}\" is undefined`);\n return {\n name,\n user: p.user,\n workspaceId: p.workspace_id,\n permission: p.readonly === true ? \"read\" : \"write\",\n ...(p.machine_user\n ? {\n machineUser: p.machine_user,\n machineUserOverride: p.machine_user_override ?? \"allow\",\n }\n : {}),\n ...(p.platform_url ? { platformUrl: p.platform_url } : {}),\n ...(p.oauth2_client_id ? { oauth2ClientId: p.oauth2_client_id } : {}),\n ...(p.console_url ? { consoleUrl: p.console_url } : {}),\n };\n });\n logger.out(profileInfos);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchAll, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n fetchLatestToken,\n platformConfigFromProfile,\n readPlatformConfig,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { ProfileInfo } from \"./types\";\n\nexport const updateCommand = defineAppCommand({\n name: \"update\",\n description: \"Update profile properties.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Profile name\",\n }),\n user: arg(z.string().optional(), {\n alias: \"u\",\n description: \"New user email address or machine user client ID\",\n }),\n \"workspace-id\": arg(z.string().optional(), {\n alias: \"w\",\n description: \"New workspace ID\",\n }),\n permission: arg(z.enum([\"write\", \"read\"]).optional(), {\n description:\n \"Profile permission. 'read' blocks all write commands; 'write' lifts the restriction.\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n alias: \"m\",\n description:\n \"Default machine user name for application-data commands (query, workflow start, function test-run, machineuser token). Pass an empty string to clear.\",\n }),\n \"machine-user-override\": arg(z.enum([\"allow\", \"deny\"]).optional(), {\n description:\n \"Whether the command line or TAILOR_PLATFORM_MACHINE_USER_NAME may override the profile's machine user. 'deny' requires --machine-user; 'allow' lifts the restriction.\",\n }),\n \"platform-url\": arg(z.union([z.url(), z.literal(\"\")]).optional(), {\n description: \"Platform API base URL for this profile. Pass an empty string to clear.\",\n }),\n \"oauth2-client-id\": arg(z.string().optional(), {\n description:\n \"OAuth2 client ID for logging in to this profile's platform. Pass an empty string to clear.\",\n }),\n \"console-url\": arg(z.union([z.url(), z.literal(\"\")]).optional(), {\n description: \"Console base URL for this profile. Pass an empty string to clear.\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n\n // Check if profile exists\n const profile = config.profiles[args.name];\n if (!profile) {\n throw new Error(`Profile \"${args.name}\" not found.`);\n }\n\n // Check if at least one property is provided\n if (\n !args.user &&\n !args[\"workspace-id\"] &&\n args.permission === undefined &&\n args[\"machine-user\"] === undefined &&\n args[\"machine-user-override\"] === undefined &&\n args[\"platform-url\"] === undefined &&\n args[\"oauth2-client-id\"] === undefined &&\n args[\"console-url\"] === undefined\n ) {\n throw new Error(\"Please provide at least one property to update.\");\n }\n const oldUser = profile.user;\n const newUser = args.user || oldUser;\n const oldWorkspaceId = profile.workspace_id;\n const newWorkspaceId = args[\"workspace-id\"] || oldWorkspaceId;\n let resolvedUser = newUser;\n\n // Compute the final machine_user and machine_user_override to validate the combination.\n const finalMachineUser =\n args[\"machine-user\"] === \"\" ? undefined : (args[\"machine-user\"] ?? profile.machine_user);\n const finalOverride =\n args[\"machine-user-override\"] === \"allow\"\n ? undefined\n : (args[\"machine-user-override\"] ?? profile.machine_user_override);\n const finalPlatformUrl =\n args[\"platform-url\"] === \"\" ? undefined : (args[\"platform-url\"] ?? profile.platform_url);\n const finalOAuth2ClientId =\n args[\"oauth2-client-id\"] === \"\"\n ? undefined\n : (args[\"oauth2-client-id\"] ?? profile.oauth2_client_id);\n const finalConsoleUrl =\n args[\"console-url\"] === \"\" ? undefined : (args[\"console-url\"] ?? profile.console_url);\n const finalPlatformConfigInput = {\n ...(finalPlatformUrl ? { platformUrl: finalPlatformUrl } : {}),\n ...(finalOAuth2ClientId ? { oauth2ClientId: finalOAuth2ClientId } : {}),\n ...(finalConsoleUrl ? { consoleUrl: finalConsoleUrl } : {}),\n };\n const finalPlatformConfig =\n Object.keys(finalPlatformConfigInput).length > 0 ? finalPlatformConfigInput : undefined;\n const tokenLookupPlatformConfig =\n args[\"platform-url\"] === \"\" ? platformConfigFromProfile(profile) : finalPlatformConfig;\n\n if (\n (args[\"machine-user\"] !== undefined || args[\"machine-user-override\"] !== undefined) &&\n finalOverride === \"deny\" &&\n !finalMachineUser\n ) {\n if (args[\"machine-user-override\"] === \"deny\") {\n throw new Error(\"--machine-user-override deny requires --machine-user.\");\n }\n throw new Error(\n `Cannot clear the machine user while machine-user-override is \"deny\". Also pass --machine-user-override allow.`,\n );\n }\n\n // Skip remote validation when neither user nor workspace is changing.\n // This keeps `profile update <name> --permission write|read` working\n // offline and when the saved token is expired or the workspace has been\n // removed, important so a user can always lift their own readonly flag.\n if (\n args.user !== undefined ||\n args[\"workspace-id\"] !== undefined ||\n args[\"platform-url\"] !== undefined\n ) {\n // Check if user exists\n const refreshed = await fetchLatestToken(config, newUser, tokenLookupPlatformConfig);\n resolvedUser = refreshed.user;\n\n // Check if workspace exists\n const client = await initOperatorClient(refreshed.accessToken, finalPlatformConfig);\n const workspaces = await fetchAll(async (pageToken, maxPageSize) => {\n const { workspaces, nextPageToken } = await client.listWorkspaces({\n pageToken,\n pageSize: maxPageSize,\n });\n return [workspaces, nextPageToken];\n });\n const workspace = workspaces.find((ws) => ws.id === newWorkspaceId);\n if (!workspace) {\n throw new Error(`Workspace \"${newWorkspaceId}\" not found.`);\n }\n }\n\n // Update properties\n profile.user = resolvedUser;\n profile.workspace_id = newWorkspaceId;\n if (args.permission === \"read\") {\n profile.readonly = true;\n } else if (args.permission === \"write\") {\n delete profile.readonly;\n }\n if (args[\"machine-user\"] !== undefined) {\n if (args[\"machine-user\"] === \"\") {\n delete profile.machine_user;\n } else {\n profile.machine_user = args[\"machine-user\"];\n }\n }\n if (args[\"machine-user-override\"] === \"deny\") {\n profile.machine_user_override = \"deny\";\n } else if (args[\"machine-user-override\"] === \"allow\") {\n delete profile.machine_user_override;\n }\n if (args[\"platform-url\"] !== undefined) {\n if (args[\"platform-url\"] === \"\") {\n delete profile.platform_url;\n } else {\n profile.platform_url = args[\"platform-url\"];\n }\n }\n if (args[\"oauth2-client-id\"] !== undefined) {\n if (args[\"oauth2-client-id\"] === \"\") {\n delete profile.oauth2_client_id;\n } else {\n profile.oauth2_client_id = args[\"oauth2-client-id\"];\n }\n }\n if (args[\"console-url\"] !== undefined) {\n if (args[\"console-url\"] === \"\") {\n delete profile.console_url;\n } else {\n profile.console_url = args[\"console-url\"];\n }\n }\n writePlatformConfig(config);\n if (!args.json) {\n logger.success(`Profile \"${args.name}\" updated successfully`);\n }\n\n // Show profile info\n const profileInfo: ProfileInfo = {\n name: args.name,\n user: resolvedUser,\n workspaceId: newWorkspaceId,\n permission: profile.readonly === true ? \"read\" : \"write\",\n ...(profile.machine_user\n ? {\n machineUser: profile.machine_user,\n machineUserOverride: profile.machine_user_override ?? \"allow\",\n }\n : {}),\n ...(profile.platform_url ? { platformUrl: profile.platform_url } : {}),\n ...(profile.oauth2_client_id ? { oauth2ClientId: profile.oauth2_client_id } : {}),\n ...(profile.console_url ? { consoleUrl: profile.console_url } : {}),\n };\n logger.out(profileInfo);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport type { ProfileInfo } from \"./types\";\n\nexport const profileCommand = defineCommand({\n name: \"profile\",\n description: \"Manage workspace profiles (user + workspace combinations).\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n list: listCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\n/**\n * Arguments for specify secret key\n */\nexport const vaultArgs = {\n \"vault-name\": arg(z.string(), {\n alias: \"V\",\n description: \"Vault name\",\n }),\n};\n\n/**\n * Arguments for specify secret key\n */\nexport const secretIdentifyArgs = {\n ...vaultArgs,\n name: arg(z.string(), {\n alias: \"n\",\n description: \"Secret name\",\n }),\n};\n\n/**\n * Arguments for specify secret key\n */\nexport const secretValueArgs = {\n ...secretIdentifyArgs,\n value: arg(z.string(), {\n alias: \"v\",\n description: \"Secret value\",\n }),\n};\n","import {\n resourceTrn,\n sdkAppIdLabelKey,\n sdkNameLabelKey,\n sdkVersionLabelKey,\n writeMetadataLabels,\n} from \"#/cli/commands/deploy/label\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\n\ntype CheckVaultManagedParams = {\n client: OperatorClient;\n workspaceId: string;\n vaultName: string;\n};\n\ntype CheckVaultManagedResult = {\n isManaged: boolean;\n trn: string;\n existingLabels: Record<string, string>;\n};\n\n/**\n * Check if a vault is managed by defineSecretManager() and warn the user.\n * Returns management status and metadata needed for releasing ownership.\n * @param params - Check parameters\n * @returns Management status, TRN, and existing labels\n */\nexport async function checkVaultManaged(\n params: CheckVaultManagedParams,\n): Promise<CheckVaultManagedResult> {\n const { client, workspaceId, vaultName } = params;\n const trn = resourceTrn(workspaceId, \"vault\", vaultName);\n const notManaged = { isManaged: false, trn, existingLabels: {} };\n\n let owner: string | undefined;\n let allLabels: Record<string, string>;\n try {\n const { metadata } = await client.getMetadata({ trn });\n allLabels = metadata?.labels ?? {};\n owner = allLabels[sdkNameLabelKey];\n } catch {\n // If metadata fetch fails (e.g., vault doesn't exist yet), proceed silently.\n // The actual operation will surface the appropriate error.\n return notManaged;\n }\n\n if (!owner) return notManaged;\n\n logger.warn(\n `Vault \"${vaultName}\" is managed by defineSecretManager() in tailor.config.ts (owner: \"${owner}\"). ` +\n `Changes made via CLI may conflict with the config on the next apply.`,\n );\n\n return { isManaged: true, trn, existingLabels: allLabels };\n}\n\n/**\n * Release ownership of a managed vault by removing SDK labels from metadata.\n * Call this after the user has confirmed they want to proceed with a CLI operation on a managed vault.\n * The labels are read again at write time, so the caller does not pass the ones\n * `checkVaultManaged` saw: anything written since then is kept, and only the\n * ownership labels are removed.\n *\n * That includes the app id, which decides ownership on its own: leaving it\n * behind would keep the vault SDK-owned, and the next deploy of a config that\n * no longer declares it would delete the vault and every secret in it.\n * @param params - Client and TRN from the checkVaultManaged result\n * @param params.client - Operator client used to update vault metadata\n * @param params.trn - TRN of the vault resource\n */\nexport async function releaseVaultOwnership(params: {\n client: OperatorClient;\n trn: string;\n}): Promise<void> {\n const { client, trn } = params;\n await writeMetadataLabels(client, {\n trn,\n remove: [sdkNameLabelKey, sdkVersionLabelKey, sdkAppIdLabelKey],\n });\n logger.info(\n \"Config ownership has been removed from this vault. \" +\n \"Remove it from defineSecretManager() in your config to prevent the next apply from re-claiming it.\",\n );\n}\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretValueArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const createSecretCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretValueArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const managed = await checkVaultManaged({\n client,\n workspaceId,\n vaultName: args[\"vault-name\"],\n });\n if (managed.isManaged && !args.yes) {\n const confirmed = await prompt.confirm({\n message: \"Do you want to proceed?\",\n default: false,\n });\n if (!confirmed) return;\n }\n try {\n await client.createSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n secretmanagerSecretValue: args.value,\n });\n } catch (error) {\n if (error instanceof ConnectError) {\n if (error.code === Code.NotFound) {\n throw new Error(`Vault \"${args[\"vault-name\"]}\" not found.`, { cause: error });\n }\n if (error.code === Code.AlreadyExists) {\n throw new Error(`Secret \"${args.name}\" already exists.`, { cause: error });\n }\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} created in vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretIdentifyArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const deleteSecretCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretIdentifyArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // No additional confirmation for managed vaults — the name-typing confirmation below is a stronger guard.\n const managed = await checkVaultManaged({ client, workspaceId, vaultName: args[\"vault-name\"] });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the secret name to confirm deletion (\"${args.name}\"):`,\n });\n\n if (confirmation !== args.name) {\n logger.info(\"Secret deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Secret \"${args.name}\" not found in vault \"${args[\"vault-name\"]}\".`, {\n cause: error,\n });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} deleted from vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { vaultArgs } from \"./args\";\nimport type { SecretManagerSecret } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\nexport interface SecretListOptions {\n workspaceId?: string;\n profile?: string;\n vaultName: string;\n order?: Order;\n limit?: number;\n}\n\nexport interface SecretInfo {\n name: string;\n createdAt: Date | null;\n updatedAt: Date | null;\n}\n\nfunction secretInfo(secret: SecretManagerSecret): SecretInfo {\n return {\n name: secret.name,\n createdAt: secret.createTime ? timestampDate(secret.createTime) : null,\n updatedAt: secret.updateTime ? timestampDate(secret.updateTime) : null,\n };\n}\n\n/**\n * List secrets in a Secret Manager vault.\n * @param options - Secret listing options\n * @returns List of secrets\n */\nasync function secretList(options: SecretListOptions): Promise<SecretInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const pageDirection = toPageDirection(options.order);\n const secrets = await fetchPaged(\n async (pageToken, pageSize) => {\n const { secrets, nextPageToken } = await client.listSecretManagerSecrets({\n workspaceId,\n secretmanagerVaultName: options.vaultName,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [secrets, nextPageToken];\n },\n { limit: options.limit },\n );\n\n return secrets.map(secretInfo);\n}\n\nexport const listSecretCommand = defineAppCommand({\n name: \"list\",\n description: \"List all secrets in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...vaultArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n try {\n const secrets = await secretList({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n vaultName: args[\"vault-name\"],\n order: args.order,\n limit: args.limit,\n });\n logger.out(secrets);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Vault \"${args[\"vault-name\"]}\" not found.`, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { secretValueArgs } from \"./args\";\nimport { checkVaultManaged, releaseVaultOwnership } from \"./check-vault-managed\";\n\nexport const updateSecretCommand = defineAppCommand({\n name: \"update\",\n description: \"Update a secret in a vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...secretValueArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const managed = await checkVaultManaged({\n client,\n workspaceId,\n vaultName: args[\"vault-name\"],\n });\n if (managed.isManaged && !args.yes) {\n const confirmed = await prompt.confirm({\n message: \"Do you want to proceed?\",\n default: false,\n });\n if (!confirmed) return;\n }\n try {\n await client.updateSecretManagerSecret({\n workspaceId,\n secretmanagerVaultName: args[\"vault-name\"],\n secretmanagerSecretName: args.name,\n secretmanagerSecretValue: args.value,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Secret \"${args.name}\" not found in vault \"${args[\"vault-name\"]}\".`, {\n cause: error,\n });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n await releaseVaultOwnership({ client, ...managed });\n }\n\n logger.success(`Secret: ${args.name} updated in vault: ${args[\"vault-name\"]}`);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\n\ntype ArgsShape = Record<string, z.ZodType>;\n\nexport const nameArgs = {\n name: arg(z.string(), {\n positional: true,\n description: \"Vault name\",\n }),\n} satisfies ArgsShape;\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { nameArgs } from \"./args\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new Secret Manager vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...nameArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n await client.createSecretManagerVault({\n workspaceId,\n secretmanagerVaultName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.AlreadyExists) {\n throw new Error(`Vault \"${args.name}\" already exists.`, { cause: error });\n }\n throw error;\n }\n\n logger.success(`Vault: ${args.name} created`);\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { z } from \"zod\";\nimport { confirmationArgs, workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { checkVaultManaged } from \"../check-vault-managed\";\nimport { nameArgs } from \"./args\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a Secret Manager vault.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...nameArgs,\n ...confirmationArgs,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n // No additional confirmation for managed vaults — the name-typing confirmation below is a stronger guard.\n const managed = await checkVaultManaged({ client, workspaceId, vaultName: args.name });\n\n if (!args.yes) {\n const confirmation = await prompt.text({\n message: `Enter the vault name to confirm deletion (\"${args.name}\"):`,\n });\n if (confirmation !== args.name) {\n logger.info(\"Vault deletion cancelled.\");\n return;\n }\n }\n\n try {\n await client.deleteSecretManagerVault({\n workspaceId,\n secretmanagerVaultName: args.name,\n });\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Vault \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n\n if (managed.isManaged) {\n logger.info(\n \"Remove this vault from defineSecretManager() in your config to prevent the next apply from re-creating it.\",\n );\n }\n\n logger.success(`Vault: ${args.name} deleted`);\n },\n});\n","import { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport type { SecretManagerVault } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\nexport interface VaultListOptions {\n workspaceId?: string;\n profile?: string;\n order?: Order;\n limit?: number;\n}\n\nexport interface VaultInfo {\n name: string;\n createdAt: Date | null;\n updatedAt: Date | null;\n}\n\nfunction vaultInfo(vault: SecretManagerVault): VaultInfo {\n return {\n name: vault.name,\n createdAt: vault.createTime ? timestampDate(vault.createTime) : null,\n updatedAt: vault.updateTime ? timestampDate(vault.updateTime) : null,\n };\n}\n\n/**\n * List Secret Manager vaults in the workspace.\n * @param options - Vault listing options\n * @returns List of vaults\n */\nasync function vaultList(options?: VaultListOptions): Promise<VaultInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options?.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options?.workspaceId,\n profile: options?.profile,\n });\n\n const pageDirection = toPageDirection(options?.order);\n const vaults = await fetchPaged(\n async (pageToken, pageSize) => {\n const { vaults, nextPageToken } = await client.listSecretManagerVaults({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [vaults, nextPageToken];\n },\n { limit: options?.limit },\n );\n\n return vaults.map(vaultInfo);\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all Secret Manager vaults in the workspace.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n const vaults = await vaultList({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n order: args.order,\n limit: args.limit,\n });\n\n logger.out(vaults);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\n\nexport const vaultCommand = defineCommand({\n name: \"vault\",\n description: \"Manage Secret Manager vaults.\",\n subCommands: {\n create: createCommand,\n delete: deleteCommand,\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createSecretCommand } from \"./create\";\nimport { deleteSecretCommand } from \"./delete\";\nimport { listSecretCommand } from \"./list\";\nimport { updateSecretCommand } from \"./update\";\nimport { vaultCommand } from \"./vault\";\n\nexport const secretCommand = defineCommand({\n name: \"secret\",\n description: \"Manage Secret Manager vaults and secrets.\",\n subCommands: {\n vault: vaultCommand,\n create: createSecretCommand,\n update: updateSecretCommand,\n list: listSecretCommand,\n delete: deleteSecretCommand,\n },\n async run() {\n await runCommand(vaultCommand, []);\n },\n});\n","import { spawnSync } from \"node:child_process\";\n\n/**\n * Runs a git command and returns its trimmed stdout, or null on failure.\n * Injectable so callers (and tests) can substitute the git runner.\n * @param args - Arguments passed to `git`\n * @param cwd - Working directory to run git in\n * @returns Trimmed stdout, or null when git is unavailable or exits non-zero\n */\nexport type GitRunner = (args: string[], cwd: string) => string | null;\n\nconst defaultGitRunner: GitRunner = (args, cwd) => {\n const result = spawnSync(\"git\", args, { cwd, encoding: \"utf-8\" });\n if (result.status !== 0 || typeof result.stdout !== \"string\") {\n return null;\n }\n return result.stdout.trim();\n};\n\n/**\n * Detect the remote default branch by reading `refs/remotes/origin/HEAD`.\n *\n * Throws an AI-first error (with a remediation hint) when the symbolic ref is\n * not set, so the caller can surface a clear next step instead of a silent\n * fallback.\n * @param cwd - Repository directory to inspect\n * @param run - Git runner, injectable for testing\n * @returns The default branch name (e.g. `main`)\n */\nexport function detectDefaultBranch(cwd: string, run: GitRunner = defaultGitRunner): string {\n const ref = run([\"symbolic-ref\", \"--short\", \"refs/remotes/origin/HEAD\"], cwd);\n const branch = ref?.startsWith(\"origin/\") ? ref.slice(\"origin/\".length) : ref;\n if (!branch) {\n throw new Error(\n \"Could not detect the default branch from git. \" +\n \"Pass --branch <name>, or run 'git remote set-head origin --auto' to record it.\",\n );\n }\n return branch;\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\n/** Current lock schema version. Bumped only on breaking lock-format changes. */\nexport const LOCK_VERSION = 1;\n\n/** Lock file path, relative to the repository root. */\nconst LOCK_FILENAME = \".github/tailor.lock\";\n\nfunction assertSafeLockPath(outputDir: string): void {\n for (const relativePath of [\".github\", LOCK_FILENAME]) {\n try {\n if (fs.lstatSync(path.join(outputDir, relativePath)).isSymbolicLink()) {\n throw new Error(`Refusing to use ${LOCK_FILENAME}: \"${relativePath}\" is a symbolic link.`);\n }\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") continue;\n throw error;\n }\n }\n}\n\nexport type TargetKind = \"branch\" | \"tag\" | \"preview\" | \"action\" | \"coordinate\";\n\nexport type LockInputs = {\n branch: string | null;\n /** True when `branch` was auto-detected (no explicit `--branch`). */\n branchAutoDetected?: boolean;\n tagPattern: string | null;\n environment: string;\n dir: string;\n packageManager: string;\n /** For `preview` kind: workspace region used when creating the preview workspace. */\n region?: string;\n /**\n * For `preview` kind: when true, the preview workflow deploys only for PRs labeled\n * `tailor:preview`. False (default) means all PRs trigger a preview deploy.\n */\n requirePreviewLabel?: boolean;\n /** For `coordinate` kind: ordered list of app dirs whose per-app actions are orchestrated. */\n actionDirs?: string[];\n erdPreview?: boolean;\n erdNamespaces?: string[];\n /** Whether tailor-migration-drift-check was generated (config had namespaces with migrations). */\n migrationDriftCheck?: boolean;\n /** Whether tailor-seed-validate was generated (config used seedPlugin). */\n seedValidate?: boolean;\n /** Whether the config had staticWebsites when setup was last run (action kind only). */\n hasStaticWebsites?: boolean;\n};\n\nexport type LockTarget = {\n kind: TargetKind;\n workspaceName: string;\n /** outputDir-relative, posix-separated path to the generated workflow file. */\n file: string;\n templateVersion: number;\n inputs: LockInputs;\n /** Managed job/step ids: jobs as `<job>`, steps as `<job>/<step>`. */\n generatedIds: string[];\n /** Reserved for future eject semantics; preserved as-is across regenerations. */\n ejectedIds: string[];\n /** `sha256:<hex>` of the written file content. */\n contentHash: string;\n};\n\nexport type LockFile = {\n version: number;\n targets: LockTarget[];\n};\n\n/**\n * Compute the lock content hash for a rendered workflow file.\n * @param content - File content to hash\n * @returns `sha256:<hex>` digest string\n */\nexport function hashContent(content: string): string {\n return `sha256:${createHash(\"sha256\").update(content, \"utf-8\").digest(\"hex\")}`;\n}\n\n/**\n * Resolve the absolute lock file path for an output directory.\n * @param outputDir - Repository root where `.github` lives\n * @returns Absolute path to the lock file\n */\nexport function lockPath(outputDir: string): string {\n return path.join(outputDir, LOCK_FILENAME);\n}\n\n/**\n * Read and validate the lock file from disk.\n *\n * Returns null when no lock exists. Throws when the lock was written by a\n * newer SDK (forward-compatibility guard).\n * @param outputDir - Repository root where `.github` lives\n * @returns Parsed lock file, or null when absent\n */\nexport function readLock(outputDir: string): LockFile | null {\n assertSafeLockPath(outputDir);\n const file = lockPath(outputDir);\n if (!fs.existsSync(file)) {\n return null;\n }\n let parsed: LockFile;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as LockFile;\n } catch (cause) {\n throw new Error(\n `${LOCK_FILENAME} is not valid JSON. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n { cause },\n );\n }\n if (typeof parsed.version !== \"number\") {\n throw new Error(\n `${LOCK_FILENAME} has no valid 'version' field. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n );\n }\n if (parsed.version > LOCK_VERSION) {\n throw new Error(\n `${LOCK_FILENAME} was written by a newer SDK (lock version ${String(parsed.version)}). ` +\n \"Update @tailor-platform/sdk to continue (e.g. pnpm update @tailor-platform/sdk).\",\n );\n }\n if (!Array.isArray(parsed.targets)) {\n throw new Error(\n `${LOCK_FILENAME} has no valid 'targets' array. The lock file is machine-owned; ` +\n \"restore it from git (git checkout -- .github/tailor.lock) and re-run setup.\",\n );\n }\n return parsed;\n}\n\n/**\n * Write the lock file to disk (2-space JSON, trailing newline).\n * @param outputDir - Repository root where `.github` lives\n * @param lock - Lock file contents to serialize\n */\nexport function writeLock(outputDir: string, lock: LockFile): void {\n assertSafeLockPath(outputDir);\n const file = lockPath(outputDir);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(file, `${JSON.stringify(lock, null, 2)}\\n`, \"utf-8\");\n}\n\n/**\n * Find a lock target by identity. Targets are identified by (kind,\n * workspaceName); the full trigger/path cross-check is deferred to P2.\n * @param lock - Lock file to search, or null\n * @param kind - Target kind\n * @param workspaceName - Workspace name\n * @returns Matching target, or undefined\n */\nexport function findTarget(\n lock: LockFile | null,\n kind: TargetKind,\n workspaceName: string,\n): LockTarget | undefined {\n return lock?.targets.find((t) => t.kind === kind && t.workspaceName === workspaceName);\n}\n","export default \"# __HEADER__\\nname: __WORKSPACE_NAME__\\ndescription: >-\\n Deploy __WORKSPACE_NAME__ to Tailor Platform.\\n Checkout and dependency installation are expected to be handled by the caller.\\n\\ninputs:\\n workspace-id:\\n description: Tailor Platform workspace id\\n required: true\\n name:\\n description: Workspace name (used in Slack notifications)\\n required: true\\n working-directory:\\n description: App directory relative to the repository root\\n required: false\\n default: \\\".\\\"\\n config:\\n description: SDK config path, or comma-separated config paths for multi-config deploys\\n required: false\\n default: \\\"tailor.config.ts\\\"\\n deploy:\\n description: Whether to run the Tailor deploy step after build steps\\n required: false\\n default: \\\"true\\\"\\n build-site:\\n description: Whether to run the static website build slot when present\\n required: false\\n default: \\\"true\\\"\\n platform-client-id:\\n description: Machine-user client id\\n required: true\\n platform-client-secret:\\n description: Machine-user client secret\\n required: true\\n slack-token:\\n description: Slack bot token\\n required: false\\n slack-channel-id:\\n description: Slack channel id\\n required: false\\n user-mapping:\\n description: JSON string mapping GitHub usernames to Slack user IDs\\n required: false\\n package-manager:\\n description: Package manager used for dependency installation (pnpm, npm, yarn, bun)\\n required: false\\n default: pnpm\\n\\noutputs:\\n app-url:\\n description: Deployed application URL\\n value: ${{ steps.tailor-apply.outputs.app-url }}\\n\\nruns:\\n using: composite\\n steps:\\n # __STATIC_WEBSITE_BUILD_START__\\n - id: build-site\\n if: inputs.build-site == 'true'\\n shell: bash\\n run: |\\n # Replace with your static website build command.\\n # Example: pnpm --filter <package-name> run build:static\\n # Note: this run: command is user-editable. Custom build commands are preserved across\\n # reruns and are not treated as drift by setup check. Other edits to this file are flagged\\n # as drift and will be overwritten if you re-run setup action with --force.\\n true\\n # __STATIC_WEBSITE_BUILD_END__\\n - id: tailor-apply\\n if: inputs.deploy == 'true'\\n uses: tailor-platform/actions/deploy@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n env:\\n TAILOR_PLATFORM_SDK_CONFIG_PATH: ${{ inputs.config }}\\n with:\\n workspace-id: ${{ inputs.workspace-id }}\\n working-directory: ${{ inputs.working-directory }}\\n package-manager: ${{ inputs.package-manager }}\\n platform-client-id: ${{ inputs.platform-client-id }}\\n platform-client-secret: ${{ inputs.platform-client-secret }}\\n - id: tailor-notify\\n if: failure() && inputs.slack-token != '' && inputs.slack-channel-id != ''\\n uses: tailor-platform/actions/notify@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n provider: slack\\n status: failure\\n workspace-name: ${{ inputs.name }}\\n slack-token: ${{ inputs.slack-token }}\\n slack-channel-id: ${{ inputs.slack-channel-id }}\\n user-mapping: ${{ inputs.user-mapping }}\\n\";","export default \"# __HEADER__\\nname: Tailor (__WORKSPACE_NAME__)\\n\\non:\\n # __PULL_REQUEST_START__\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PATHS__\\n # __PULL_REQUEST_END__\\n push:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PATHS__\\n workflow_dispatch:\\n # __DISPATCH_INPUTS_START__\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n # __DISPATCH_INPUTS_END__\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __PLAN_JOB_START__\\n tailor-plan:\\n if: >-\\n github.event_name == 'pull_request' ||\\n (github.event_name == 'workflow_dispatch' && inputs['dry-run'])\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-plan-__WORKSPACE_NAME__-${{ github.event.pull_request.number || github.run_id }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_START__\\n - id: tailor-seed-validate\\n run: __TAILOR_CLI__ seed validate\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_END__\\n - id: tailor-drift-check\\n uses: tailor-platform/actions/drift-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n fail-on-drift: ${{ vars.TAILOR_PLATFORM_FAIL_ON_DRIFT == 'true' }}\\n # __MIGRATION_DRIFT_CHECK_START__\\n - id: tailor-migration-drift-check\\n uses: tailor-platform/actions/migration-drift-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __MIGRATION_DRIFT_CHECK_END__\\n - id: tailor-plan\\n # Fork PRs cannot read secrets; the checks above still run for them.\\n if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork\\n uses: tailor-platform/actions/plan@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n label: __WORKSPACE_NAME__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n # __PLAN_JOB_END__\\n # __ERD_PREVIEW_JOB_START__\\n tailor-erd-preview-matrix:\\n if: github.event_name == 'pull_request'\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n contents: read\\n outputs:\\n namespaces: ${{ steps.tailor-erd-preview-matrix.outputs.namespaces }}\\n base-app-dir: ${{ steps.tailor-erd-preview-matrix.outputs['base-app-dir'] }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n persist-credentials: false\\n - id: tailor-checkout-base\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n repository: ${{ github.event.pull_request.base.repo.full_name }}\\n ref: ${{ github.event.pull_request.base.sha }}\\n path: .tailor-erd-base\\n persist-credentials: false\\n - id: tailor-erd-preview-matrix\\n shell: bash\\n env:\\n APP_DIR: \\\"__APP_DIR__\\\"\\n WORKSPACE_NAME: \\\"__WORKSPACE_NAME__\\\"\\n run: |\\n set -euo pipefail\\n node <<'NODE'\\n const fs = require(\\\"node:fs\\\");\\n\\n const appDir = process.env.APP_DIR || \\\".\\\";\\n const workspaceName = process.env.WORKSPACE_NAME;\\n const output = process.env.GITHUB_OUTPUT;\\n const dirPattern = /^[A-Za-z0-9._/-]+$/;\\n const namespacePattern = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\\n\\n function lockTarget(file) {\\n try {\\n const lock = JSON.parse(fs.readFileSync(file, \\\"utf8\\\"));\\n return lock.targets?.find(\\n (candidate) =>\\n candidate.kind === \\\"branch\\\" &&\\n candidate.workspaceName === workspaceName,\\n );\\n } catch (error) {\\n if (error && error.code === \\\"ENOENT\\\") return undefined;\\n throw error;\\n }\\n }\\n\\n function namespacesFromTarget(target, label) {\\n const namespaces =\\n target?.inputs?.erdPreview === true && Array.isArray(target.inputs?.erdNamespaces)\\n ? target.inputs.erdNamespaces\\n : [];\\n for (const namespace of namespaces) {\\n if (typeof namespace !== \\\"string\\\" || !namespacePattern.test(namespace)) {\\n throw new Error(`Invalid ERD namespace in ${label}: ${String(namespace)}`);\\n }\\n }\\n return namespaces;\\n }\\n\\n function normalizeDir(value, label) {\\n const raw = typeof value === \\\"string\\\" && value.length > 0 ? value : appDir;\\n const normalized =\\n raw.replaceAll(\\\"\\\\\\\\\\\", \\\"/\\\").replace(/\\\\/{2,}/g, \\\"/\\\").replace(/^\\\\.\\\\//, \\\"\\\").replace(/\\\\/$/, \\\"\\\") ||\\n \\\".\\\";\\n if (\\n !dirPattern.test(normalized) ||\\n normalized.startsWith(\\\"/\\\") ||\\n normalized.split(\\\"/\\\").includes(\\\"..\\\")\\n ) {\\n throw new Error(`Invalid ERD app dir in ${label}: ${raw}`);\\n }\\n return normalized;\\n }\\n\\n const headTarget = lockTarget(\\\".github/tailor.lock\\\");\\n const baseTarget = lockTarget(\\\".tailor-erd-base/.github/tailor.lock\\\");\\n const baseAppDir = normalizeDir(baseTarget?.inputs?.dir, \\\"base setup lock\\\");\\n const namespaces = [\\n ...new Set([\\n ...namespacesFromTarget(headTarget, \\\"head setup lock\\\"),\\n ...namespacesFromTarget(baseTarget, \\\"base setup lock\\\"),\\n ]),\\n ].sort((a, b) => a.localeCompare(b));\\n\\n if (namespaces.length === 0) {\\n console.error(\\\"No ERD preview namespaces found in the head or base setup lock.\\\");\\n process.exit(1);\\n }\\n\\n fs.appendFileSync(output, `namespaces=${JSON.stringify(namespaces)}\\\\n`);\\n fs.appendFileSync(output, `base-app-dir=${baseAppDir}\\\\n`);\\n NODE\\n\\n tailor-erd-preview:\\n needs: tailor-erd-preview-matrix\\n if: github.event_name == 'pull_request'\\n runs-on: ubuntu-latest\\n timeout-minutes: 15\\n permissions:\\n contents: read\\n strategy:\\n fail-fast: false\\n matrix:\\n namespace: ${{ fromJSON(needs.tailor-erd-preview-matrix.outputs.namespaces) }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n persist-credentials: false\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-checkout-base\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n repository: ${{ github.event.pull_request.base.repo.full_name }}\\n ref: ${{ github.event.pull_request.base.sha }}\\n path: .tailor-erd-base\\n persist-credentials: false\\n - id: tailor-detect-base-package-manager\\n shell: bash\\n run: |\\n set -euo pipefail\\n cd .tailor-erd-base\\n base_package_manager=\\\"$(\\n if [ -f pnpm-lock.yaml ]; then\\n echo pnpm\\n elif [ -f yarn.lock ]; then\\n echo yarn\\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then\\n echo bun\\n elif [ -f package-lock.json ]; then\\n echo npm\\n else\\n echo \\\"__PACKAGE_MANAGER__\\\"\\n fi\\n )\\\"\\n echo \\\"package-manager=$base_package_manager\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n if [ \\\"$base_package_manager\\\" = \\\"pnpm\\\" ]; then\\n base_pnpm_version=\\\"$(node <<'NODE'\\n const fs = require(\\\"node:fs\\\");\\n\\n const fallback = \\\"10\\\";\\n\\n function readManifest(file) {\\n try {\\n return JSON.parse(fs.readFileSync(file, \\\"utf8\\\"));\\n } catch {\\n return {};\\n }\\n }\\n\\n function pnpmVersion(manifest) {\\n const packageManager = manifest.packageManager;\\n if (typeof packageManager === \\\"string\\\" && packageManager.startsWith(\\\"pnpm@\\\")) {\\n return packageManager.slice(\\\"pnpm@\\\".length).split(\\\"+\\\")[0];\\n }\\n\\n const devPackageManager = manifest.devEngines?.packageManager;\\n if (devPackageManager?.name === \\\"pnpm\\\" && devPackageManager.version) {\\n return devPackageManager.version;\\n }\\n\\n return undefined;\\n }\\n\\n process.stdout.write(\\n pnpmVersion(readManifest(\\\"package.json\\\")) ?? fallback,\\n );\\n NODE\\n )\\\"\\n echo \\\"pnpm-version=$base_pnpm_version\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-setup-base-pnpm\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'pnpm'\\n uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10\\n with:\\n version: ${{ steps.tailor-detect-base-package-manager.outputs['pnpm-version'] }}\\n package_json_file: .tailor-erd-base/package.json\\n run_install: false\\n - id: tailor-setup-base-node\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] != 'bun'\\n uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7\\n with:\\n node-version-file: .tailor-erd-base/package.json\\n - id: tailor-setup-base-yarn\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'yarn'\\n shell: bash\\n working-directory: .tailor-erd-base\\n run: |\\n set -euo pipefail\\n corepack enable\\n - id: tailor-setup-base-bun\\n if: steps.tailor-detect-base-package-manager.outputs['package-manager'] == 'bun'\\n uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0\\n - id: tailor-install-base\\n shell: bash\\n working-directory: .tailor-erd-base\\n env:\\n BASE_PACKAGE_MANAGER: ${{ steps.tailor-detect-base-package-manager.outputs['package-manager'] }}\\n run: |\\n set -euo pipefail\\n case \\\"$BASE_PACKAGE_MANAGER\\\" in\\n pnpm) pnpm install --frozen-lockfile ;;\\n npm) npm ci ;;\\n yarn)\\n if grep -q '^__metadata:' yarn.lock; then\\n yarn install --immutable\\n else\\n yarn install --frozen-lockfile\\n fi\\n ;;\\n bun) bun install --frozen-lockfile ;;\\n *)\\n echo \\\"::error::Unsupported base package-manager '$BASE_PACKAGE_MANAGER' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n - id: tailor-restore-head-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-build-erd-preview\\n shell: bash\\n env:\\n APP_DIR: \\\"__APP_DIR__\\\"\\n BASE_APP_DIR: ${{ needs.tailor-erd-preview-matrix.outputs['base-app-dir'] }}\\n BASE_PACKAGE_MANAGER: ${{ steps.tailor-detect-base-package-manager.outputs['package-manager'] }}\\n NAMESPACE: ${{ matrix.namespace }}\\n run: |\\n set -euo pipefail\\n\\n run_tailor_cli() {\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) pnpm exec tailor \\\"$@\\\" ;;\\n npm) npx @tailor-platform/sdk \\\"$@\\\" ;;\\n yarn) yarn tailor \\\"$@\\\" ;;\\n bun) bun run tailor \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n }\\n\\n run_head_node() {\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) pnpm exec node \\\"$@\\\" ;;\\n npm) node \\\"$@\\\" ;;\\n yarn) yarn node \\\"$@\\\" ;;\\n bun) node \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n }\\n\\n tailor_cli_bin=\\\"$(\\n run_head_node - <<'NODE'\\n const path = require(\\\"node:path\\\");\\n const { createRequire } = require(\\\"node:module\\\");\\n const appDir = process.env.APP_DIR || \\\".\\\";\\n const githubWorkspace = process.env.GITHUB_WORKSPACE;\\n if (!githubWorkspace) {\\n throw new Error(\\\"GITHUB_WORKSPACE is required.\\\");\\n }\\n\\n let lastError;\\n for (const manifestPath of [\\n path.join(githubWorkspace, appDir, \\\"package.json\\\"),\\n path.join(githubWorkspace, \\\"package.json\\\"),\\n ]) {\\n try {\\n const requireFromManifest = createRequire(manifestPath);\\n process.stdout.write(\\n path.join(\\n path.dirname(requireFromManifest.resolve(\\\"@tailor-platform/sdk/cli\\\")),\\n \\\"index.mjs\\\",\\n ),\\n );\\n process.exit(0);\\n } catch (error) {\\n lastError = error;\\n }\\n }\\n throw lastError || new Error(\\\"Failed to resolve @tailor-platform/sdk/cli.\\\");\\n NODE\\n )\\\"\\n\\n run_head_tailor_cli_bin() {\\n local command_cwd=\\\"$1\\\"\\n shift\\n\\n run_head_cli_env() {\\n env TAILOR_CLI_BIN=\\\"$tailor_cli_bin\\\" TAILOR_CLI_CWD=\\\"$command_cwd\\\" \\\"$@\\\"\\n }\\n\\n (\\n cd \\\"$GITHUB_WORKSPACE\\\" || exit 1\\n case \\\"__PACKAGE_MANAGER__\\\" in\\n pnpm) run_head_cli_env pnpm exec node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n npm) run_head_cli_env node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n yarn) run_head_cli_env yarn node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n bun) run_head_cli_env bun \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported package-manager '__PACKAGE_MANAGER__' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n )\\n }\\n\\n run_base_tailor_cli_bin() {\\n local command_cwd=\\\"$1\\\"\\n shift\\n\\n run_head_cli_env() {\\n env TAILOR_CLI_BIN=\\\"$tailor_cli_bin\\\" TAILOR_CLI_CWD=\\\"$command_cwd\\\" \\\"$@\\\"\\n }\\n\\n (\\n cd \\\"$command_cwd\\\" || exit 1\\n case \\\"$BASE_PACKAGE_MANAGER\\\" in\\n pnpm) run_head_cli_env pnpm exec node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n npm) run_head_cli_env node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n yarn) run_head_cli_env yarn node \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n bun) run_head_cli_env bun \\\"$head_cli_runner\\\" \\\"$@\\\" ;;\\n *)\\n echo \\\"::error::Unsupported base package-manager '$BASE_PACKAGE_MANAGER' (expected pnpm, npm, yarn, or bun)\\\"\\n exit 1\\n ;;\\n esac\\n )\\n }\\n\\n head_output=\\\"$RUNNER_TEMP/tailor-erd/head\\\"\\n base_output=\\\"$RUNNER_TEMP/tailor-erd/base\\\"\\n preview_output=\\\"$RUNNER_TEMP/tailor-erd/preview\\\"\\n dts_output=\\\"$RUNNER_TEMP/tailor-erd/dts\\\"\\n head_cli_runner=\\\"$RUNNER_TEMP/tailor-erd/run-head-cli.mjs\\\"\\n head_log=\\\"$RUNNER_TEMP/tailor-erd/head-$NAMESPACE.log\\\"\\n base_log=\\\"$RUNNER_TEMP/tailor-erd/base-$NAMESPACE.log\\\"\\n rm -rf \\\"$head_output\\\" \\\"$base_output\\\" \\\"$preview_output\\\" \\\"$dts_output\\\"\\n mkdir -p \\\"$head_output\\\" \\\"$base_output\\\" \\\"$preview_output\\\" \\\"$dts_output\\\"\\n cat > \\\"$head_cli_runner\\\" <<'NODE'\\n import { pathToFileURL } from \\\"node:url\\\";\\n\\n const cliBin = process.env.TAILOR_CLI_BIN;\\n const commandCwd = process.env.TAILOR_CLI_CWD;\\n if (!cliBin || !commandCwd) {\\n throw new Error(\\\"TAILOR_CLI_BIN and TAILOR_CLI_CWD are required.\\\");\\n }\\n\\n process.chdir(commandCwd);\\n process.argv = [process.argv[0], cliBin, ...process.argv.slice(2)];\\n await import(pathToFileURL(cliBin).href);\\n NODE\\n\\n head_config=\\\"$GITHUB_WORKSPACE/$APP_DIR/tailor.config.ts\\\"\\n base_config=\\\"$GITHUB_WORKSPACE/.tailor-erd-base/$BASE_APP_DIR/tailor.config.ts\\\"\\n head_html=\\\"$head_output/$NAMESPACE/dist/index.html\\\"\\n base_html=\\\"$base_output/$NAMESPACE/dist/index.html\\\"\\n preview_html=\\\"$preview_output/$NAMESPACE-viewer.html\\\"\\n\\n head_missing=\\\"false\\\"\\n if [ ! -f \\\"$head_config\\\" ]; then\\n echo \\\"Head ERD config not found; rendering base objects as removed.\\\"\\n head_missing=\\\"true\\\"\\n elif ! (\\n cd \\\"$GITHUB_WORKSPACE/$APP_DIR\\\" || exit 1\\n TAILOR_PLATFORM_SDK_DTS_PATH=\\\"$dts_output/head-$NAMESPACE.d.ts\\\" \\\\\\n run_tailor_cli tailordb erd export --config \\\"$head_config\\\" --namespace \\\"$NAMESPACE\\\" --output \\\"$head_output\\\"\\n ) >\\\"$head_log\\\" 2>&1; then\\n if grep -q 'not found in local config.db' \\\"$head_log\\\"; then\\n cat \\\"$head_log\\\"\\n echo \\\"Head ERD namespace '$NAMESPACE' not found; rendering base objects as removed.\\\"\\n head_missing=\\\"true\\\"\\n else\\n cat \\\"$head_log\\\"\\n exit 1\\n fi\\n elif [ -s \\\"$head_log\\\" ]; then\\n cat \\\"$head_log\\\"\\n fi\\n\\n base_missing=\\\"false\\\"\\n if [ ! -f \\\"$base_config\\\" ]; then\\n echo \\\"Base ERD config not found; rendering current objects as added.\\\"\\n base_missing=\\\"true\\\"\\n elif ! (\\n TAILOR_PLATFORM_SDK_DTS_PATH=\\\"$dts_output/base-$NAMESPACE.d.ts\\\" \\\\\\n run_base_tailor_cli_bin \\\"$GITHUB_WORKSPACE/.tailor-erd-base/$BASE_APP_DIR\\\" tailordb erd export --config \\\"$base_config\\\" --namespace \\\"$NAMESPACE\\\" --output \\\"$base_output\\\"\\n ) >\\\"$base_log\\\" 2>&1; then\\n if grep -q 'not found in local config.db' \\\"$base_log\\\"; then\\n cat \\\"$base_log\\\"\\n echo \\\"Base ERD namespace '$NAMESPACE' not found; rendering current objects as added.\\\"\\n base_missing=\\\"true\\\"\\n else\\n cat \\\"$base_log\\\"\\n exit 1\\n fi\\n elif [ -s \\\"$base_log\\\" ]; then\\n cat \\\"$base_log\\\"\\n fi\\n\\n if [ \\\"$head_missing\\\" = \\\"true\\\" ] && [ \\\"$base_missing\\\" = \\\"true\\\" ]; then\\n echo \\\"::error::ERD namespace '$NAMESPACE' was not found in head or base.\\\"\\n exit 1\\n fi\\n if [ \\\"$head_missing\\\" = \\\"false\\\" ] && [ ! -f \\\"$head_html\\\" ]; then\\n echo \\\"::error::Head ERD viewer was not generated at $head_html\\\"\\n exit 1\\n fi\\n if [ \\\"$base_missing\\\" = \\\"false\\\" ] && [ ! -f \\\"$base_html\\\" ]; then\\n echo \\\"::error::Base ERD viewer was not generated at $base_html\\\"\\n exit 1\\n fi\\n\\n diff_args=(--namespace \\\"$NAMESPACE\\\" --output \\\"$preview_html\\\")\\n if [ \\\"$head_missing\\\" = \\\"false\\\" ]; then\\n diff_args+=(--head-html \\\"$head_html\\\")\\n fi\\n if [ \\\"$base_missing\\\" = \\\"false\\\" ]; then\\n diff_args+=(--base-html \\\"$base_html\\\")\\n fi\\n run_head_tailor_cli_bin \\\"$GITHUB_WORKSPACE\\\" tailordb erd diff \\\"${diff_args[@]}\\\"\\n - id: tailor-upload-erd-viewer\\n uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1\\n with:\\n name: ${{ matrix.namespace }}-viewer.html\\n path: ${{ runner.temp }}/tailor-erd/preview/${{ matrix.namespace }}-viewer.html\\n if-no-files-found: error\\n archive: false\\n retention-days: 7\\n\\n # __ERD_PREVIEW_JOB_END__\\n # __ERD_PREVIEW_COMMENT_JOB_START__\\n tailor-erd-preview-comment:\\n needs: tailor-erd-preview\\n if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n actions: read\\n pull-requests: write\\n steps:\\n - id: tailor-comment-erd-preview\\n env:\\n GH_TOKEN: ${{ github.token }}\\n REPO: ${{ github.repository }}\\n RUN_ID: ${{ github.run_id }}\\n SERVER: ${{ github.server_url }}\\n PR_NUMBER: ${{ github.event.pull_request.number }}\\n BASE_REF: ${{ github.event.pull_request.base.ref }}\\n HEAD_SHA: ${{ github.event.pull_request.head.sha }}\\n MARKER: \\\"<!-- tailor-erd-preview: __WORKSPACE_NAME__ -->\\\"\\n run: |\\n set -euo pipefail\\n\\n current_head=$(gh api \\\"repos/$REPO/pulls/$PR_NUMBER\\\" --jq '.head.sha')\\n if [ \\\"$current_head\\\" != \\\"$HEAD_SHA\\\" ]; then\\n echo \\\"Skipping stale ERD preview comment for $HEAD_SHA; current head is $current_head.\\\"\\n exit 0\\n fi\\n\\n body=\\\"$MARKER\\\"$'\\\\n'\\\"### TailorDB ERD preview (__WORKSPACE_NAME__)\\\"$'\\\\n\\\\n'\\n body+=\\\"Self-contained ERD viewer HTML artifacts for this pull request. Each viewer can switch between the current schema and a diff against base branch \\\\`$BASE_REF\\\\`.\\\"$'\\\\n'\\n\\n while IFS=$'\\\\t' read -r name id; do\\n [ -z \\\"$name\\\" ] && continue\\n if [[ \\\"$name\\\" != *-viewer.html ]]; then\\n continue\\n fi\\n ns=${name%-viewer.html}\\n label=\\\"$ns viewer\\\"\\n body+=$'\\\\n'\\\"- **$label**: [$name]($SERVER/$REPO/actions/runs/$RUN_ID/artifacts/$id)\\\"\\n done < <(gh api \\\"repos/$REPO/actions/runs/$RUN_ID/artifacts\\\" --paginate \\\\\\n --jq '.artifacts[] | select(.name | endswith(\\\"-viewer.html\\\")) | [.name, (.id|tostring)] | @tsv' | sort)\\n\\n existing=$(gh api \\\"repos/$REPO/issues/$PR_NUMBER/comments\\\" --paginate \\\\\\n --jq 'map(select(.body | contains(env.MARKER))) | .[0].id // empty')\\n if [ -n \\\"$existing\\\" ]; then\\n gh api --method PATCH \\\"repos/$REPO/issues/comments/$existing\\\" -f body=\\\"$body\\\" >/dev/null\\n else\\n gh api --method POST \\\"repos/$REPO/issues/$PR_NUMBER/comments\\\" -f body=\\\"$body\\\" >/dev/null\\n fi\\n\\n # __ERD_PREVIEW_COMMENT_JOB_END__\\n tailor-deploy:\\n # __DEPLOY_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n permissions:\\n contents: read\\n environment: __ENVIRONMENT__\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-apply\\n uses: tailor-platform/actions/deploy@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n # __SEED_DATA_START__\\n - id: seed-data\\n if: false\\n shell: bash\\n # __WORKING_DIRECTORY__\\n run: |\\n # Uncomment and implement to seed data on deploy.\\n # Run after apply so the schema is ready.\\n # Example: node scripts/seed.mjs\\n true\\n # __SEED_DATA_END__\\n - id: slack-prereq\\n if: always()\\n shell: bash\\n env:\\n SLACK_TOKEN: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n SLACK_CHANNEL_ID: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n run: |\\n if [[ -n \\\"$SLACK_TOKEN\\\" && -n \\\"$SLACK_CHANNEL_ID\\\" ]]; then\\n echo \\\"ready=true\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-notify\\n if: always() && steps.slack-prereq.outputs.ready == 'true'\\n uses: tailor-platform/actions/notify@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n provider: slack\\n status: ${{ job.status }}\\n workspace-name: __WORKSPACE_NAME__\\n slack-token: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n slack-channel-id: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n # user-mapping: ${{ vars.TAILOR_SLACK_USER_MAPPING }}\\n\";","export default \"# __HEADER__\\nname: Tailor Coordinator (__WORKSPACE_NAME__)\\n\\non:\\n # __PULL_REQUEST_START__\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PULL_REQUEST_END__\\n push:\\n # __PUSH_BRANCHES_START__\\n branches: [\\\"__BRANCH__\\\"]\\n # __PUSH_BRANCHES_END__\\n # __PUSH_TAGS_START__\\n tags: [__TAG_PATTERN__]\\n # __PUSH_TAGS_END__\\n workflow_dispatch:\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __TAG_GUARD_JOB_START__\\n tailor-tag-guard:\\n runs-on: ubuntu-latest\\n timeout-minutes: 5\\n permissions:\\n contents: read\\n outputs:\\n on-branch: ${{ steps.tailor-tag-guard.outputs.on-branch }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n fetch-depth: 0\\n - id: tailor-tag-guard\\n uses: tailor-platform/actions/tag-guard@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n target-branch: __BRANCH__\\n # __TAG_GUARD_JOB_END__\\n\\n tailor-plan:\\n # __PLAN_NEEDS__\\n # __PLAN_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 60\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-plan-__WORKSPACE_NAME__-${{ github.event.pull_request.number || github.run_id }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: ./.github/actions/tailor-setup\\n # __PER_APP_PLAN_STEPS__\\n\\n tailor-deploy:\\n # __DEPLOY_NEEDS__\\n # __DEPLOY_IF__\\n # __DEPLOY_ENVIRONMENT__\\n runs-on: ubuntu-latest\\n timeout-minutes: 60\\n permissions:\\n contents: read\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: ./.github/actions/tailor-setup\\n # __PER_APP_DEPLOY_STEPS__\\n\";","export default \"# __HEADER__\\nname: Tailor Preview (__WORKSPACE_NAME__)\\n\\non:\\n pull_request:\\n branches: [\\\"__BRANCH__\\\"]\\n # __PR_TYPES__\\n # To deploy only for PRs that carry the `tailor:preview` label instead of all PRs,\\n # re-run: tailor setup preview --require-preview-label\\n # __PATHS__\\n\\npermissions:\\n contents: read\\n pull-requests: write\\n\\njobs:\\n tailor-preview-deploy:\\n # __DEPLOY_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n concurrency:\\n group: tailor-preview-__WORKSPACE_NAME__-${{ github.event.pull_request.number }}\\n cancel-in-progress: true\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n - id: tailor-drift-check\\n uses: tailor-platform/actions/drift-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n fail-on-drift: ${{ vars.TAILOR_PLATFORM_FAIL_ON_DRIFT == 'true' }}\\n - id: tailor-preview-deploy\\n uses: tailor-platform/actions/preview-deploy@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-name-prefix: __WORKSPACE_NAME__\\n region: \\\"__REGION__\\\"\\n organization-id: ${{ vars.TAILOR_PLATFORM_ORGANIZATION_ID }}\\n folder-id: ${{ vars.TAILOR_PLATFORM_FOLDER_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n - id: tailor-preview-comment\\n if: always()\\n uses: tailor-platform/actions/preview-comment@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-id: ${{ steps.tailor-preview-deploy.outputs.workspace-id }}\\n workspace-name: ${{ steps.tailor-preview-deploy.outputs.workspace-name }}\\n status: ${{ job.status == 'success' && 'success' || 'failure' }}\\n app-url: ${{ steps.tailor-preview-deploy.outputs.app-url }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n\\n tailor-preview-cleanup:\\n # __CLEANUP_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 15\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n pull-requests: write\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-preview-cleanup\\n uses: tailor-platform/actions/preview-cleanup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-name-prefix: __WORKSPACE_NAME__\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n github-token: ${{ secrets.GITHUB_TOKEN }}\\n\";","export default \"# __HEADER__\\nname: Tailor (__WORKSPACE_NAME__)\\n\\non:\\n push:\\n tags: [\\\"__TAG_PATTERN__\\\"]\\n workflow_dispatch:\\n inputs:\\n dry-run:\\n description: Preview changes without deploying\\n type: boolean\\n default: false\\n\\npermissions:\\n contents: read\\n\\njobs:\\n # __TAG_GUARD_JOB_START__\\n tailor-tag-guard:\\n runs-on: ubuntu-latest\\n timeout-minutes: 10\\n permissions:\\n contents: read\\n outputs:\\n on-branch: ${{ steps.tailor-tag-guard.outputs.on-branch }}\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n with:\\n fetch-depth: 0\\n - id: tailor-tag-guard\\n uses: tailor-platform/actions/tag-guard@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n target-branch: \\\"__BRANCH__\\\"\\n # __TAG_GUARD_JOB_END__\\n tailor-plan:\\n # __PLAN_NEEDS__\\n # __PLAN_IF__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n environment: __ENVIRONMENT__\\n permissions:\\n contents: read\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-generate-check\\n uses: tailor-platform/actions/generate-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_START__\\n - id: tailor-seed-validate\\n run: __TAILOR_CLI__ seed validate\\n # __WORKING_DIRECTORY__\\n # __SEED_VALIDATE_END__\\n - id: tailor-drift-check\\n uses: tailor-platform/actions/drift-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n fail-on-drift: ${{ vars.TAILOR_PLATFORM_FAIL_ON_DRIFT == 'true' }}\\n # __MIGRATION_DRIFT_CHECK_START__\\n - id: tailor-migration-drift-check\\n uses: tailor-platform/actions/migration-drift-check@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n # __MIGRATION_DRIFT_CHECK_END__\\n - id: tailor-plan\\n uses: tailor-platform/actions/plan@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n label: __WORKSPACE_NAME__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n\\n tailor-deploy:\\n needs: tailor-plan\\n if: ${{ !(github.event_name == 'workflow_dispatch' && inputs['dry-run']) }}\\n environment: __ENVIRONMENT__\\n runs-on: ubuntu-latest\\n timeout-minutes: 30\\n permissions:\\n contents: read\\n concurrency:\\n group: tailor-deploy-__WORKSPACE_NAME__\\n cancel-in-progress: false\\n steps:\\n - id: tailor-checkout\\n uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\\n - id: tailor-setup\\n uses: tailor-platform/actions/setup@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-install\\n uses: tailor-platform/actions/install@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n package-manager: __PACKAGE_MANAGER__\\n - id: tailor-apply\\n uses: tailor-platform/actions/deploy@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n workspace-id: ${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}\\n package-manager: __PACKAGE_MANAGER__\\n # __WORKING_DIRECTORY__\\n platform-client-id: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}\\n platform-client-secret: ${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}\\n # __SEED_DATA_START__\\n - id: seed-data\\n if: false\\n shell: bash\\n # __WORKING_DIRECTORY__\\n run: |\\n # Uncomment and implement to seed data on deploy.\\n # Run after apply so the schema is ready.\\n # Example: node scripts/seed.mjs\\n true\\n # __SEED_DATA_END__\\n - id: slack-prereq\\n if: always()\\n shell: bash\\n env:\\n SLACK_TOKEN: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n SLACK_CHANNEL_ID: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n run: |\\n if [[ -n \\\"$SLACK_TOKEN\\\" && -n \\\"$SLACK_CHANNEL_ID\\\" ]]; then\\n echo \\\"ready=true\\\" >> \\\"$GITHUB_OUTPUT\\\"\\n fi\\n - id: tailor-notify\\n if: always() && steps.slack-prereq.outputs.ready == 'true'\\n uses: tailor-platform/actions/notify@85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c # v2.2.0\\n with:\\n provider: slack\\n status: ${{ job.status }}\\n workspace-name: __WORKSPACE_NAME__\\n slack-token: ${{ secrets.TAILOR_SLACK_BOT_TOKEN }}\\n slack-channel-id: ${{ vars.TAILOR_SLACK_CHANNEL_ID }}\\n # user-mapping: ${{ vars.TAILOR_SLACK_USER_MAPPING }}\\n\";","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport actionTemplate from \"./action.yml\";\nimport branchTemplate from \"./branch.workflow.yml\";\nimport coordinateTemplate from \"./coordinate.workflow.yml\";\nimport previewTemplate from \"./preview.workflow.yml\";\nimport tagTemplate from \"./tag.workflow.yml\";\n\n// Bump on material template-structure changes (managed step ids, placeholders)\n// so old/new generations stay distinguishable in the lock.\n/** Template schema version, tracked per target in the lock file. */\nexport const TEMPLATE_VERSION = 11;\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"npm\" | \"bun\";\n\nconst TAILOR_CLI_COMMANDS: Record<PackageManager, string> = {\n pnpm: \"pnpm exec tailor\",\n npm: \"npx @tailor-platform/sdk\",\n yarn: \"yarn tailor\",\n bun: \"bun run tailor\",\n};\n\nconst HEADER = `# Generated by \\`tailor setup\\` — managed by the Tailor SDK.\n#\n# - Jobs and steps whose id starts with \\`tailor-\\` are managed by the SDK.\n# Do not edit or rename them.\n# - State is tracked in .github/tailor.lock (machine-owned: commit it, never edit it).\n# - Re-running \\`tailor setup\\` regenerates this file. If you have\n# edited it by hand, regeneration stops and asks for --force (which discards\n# your edits), so prefer keeping customizations in your own jobs/steps and\n# re-running setup after SDK updates.`;\n\nexport type RenderBranchParams = {\n workspaceName: string;\n branch: string;\n workingDirectory?: string;\n /** GitHub Environment for the plan/deploy jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Include the seed-validate step in the plan job (default: false). */\n seedValidate?: boolean;\n /** Include the migration-drift-check step in the plan job (default: false). */\n migrationDriftCheck?: boolean;\n erdPreview: { namespaces: string[] } | null;\n};\n\nexport type RenderTagParams = {\n workspaceName: string;\n tagPattern: string;\n /** Tag-reachability guard branch; omit for no guard. */\n branch?: string;\n workingDirectory?: string;\n /** GitHub Environment for the plan/deploy jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Include the seed-validate step in the plan job (default: false). */\n seedValidate?: boolean;\n /** Include the migration-drift-check step in the plan job (default: false). */\n migrationDriftCheck?: boolean;\n};\n\nexport type RenderPreviewParams = {\n workspaceName: string;\n branch: string;\n workingDirectory?: string;\n /** GitHub Environment for the preview jobs; defaults to the workspace name. */\n environment: string;\n packageManager: PackageManager;\n /** Workspace region passed to `workspace create` on first PR push. */\n region: string;\n /**\n * When true, deploy preview only for PRs labeled `tailor:preview` (label-triggered mode).\n * Default false: preview deploys on every PR (open, sync, reopen).\n */\n requirePreviewLabel?: boolean;\n};\n\nexport type RenderActionParams = {\n workspaceName: string;\n workingDirectory?: string;\n /** Include the build-site slot (user-owned step for building static website assets). */\n hasStaticWebsites?: boolean;\n};\n\nexport type CoordinateApp = {\n /** App workspace name (same as the --action argument, e.g. \"ims\"). */\n name: string;\n /** App directory relative to repo root (e.g. \"apps/ims\"). */\n dir: string;\n /** Whether the app action contains the user-owned build-site slot. */\n hasStaticWebsites?: boolean;\n};\n\nexport type CoordinateAppGroup = {\n /** Stable step id suffix for this group. */\n id: string;\n /** Actions deployed together in one apply invocation. */\n apps: CoordinateApp[];\n};\n\nexport type CoordinateKind = \"branch\" | \"tag\";\n\nexport type RenderCoordinateParams = {\n coordinatorName: string;\n kind: CoordinateKind;\n actionGroups: CoordinateAppGroup[];\n branch?: string;\n tagPattern?: string;\n environment: string;\n packageManager: PackageManager;\n};\n\nexport type RenderResult = {\n content: string;\n generatedIds: string[];\n};\n\n/**\n * Detect the package manager used in a project directory by checking for lockfiles.\n * @param dir - Project directory to inspect\n * @returns Detected package manager, defaults to npm\n */\nexport function detectPackageManager(dir: string): PackageManager {\n if (fs.existsSync(path.join(dir, \"pnpm-lock.yaml\"))) return \"pnpm\";\n if (fs.existsSync(path.join(dir, \"yarn.lock\"))) return \"yarn\";\n if (fs.existsSync(path.join(dir, \"bun.lockb\")) || fs.existsSync(path.join(dir, \"bun.lock\")))\n return \"bun\";\n if (fs.existsSync(path.join(dir, \"package-lock.json\"))) return \"npm\";\n return \"npm\";\n}\n\n// Keep or drop a `# __X_START__` ... `# __X_END__` block (marker lines removed\n// when kept, whole block removed when dropped).\nfunction block(content: string, name: string, keep: boolean): string {\n if (keep) {\n return content.replace(new RegExp(`^ *# __${name}_(?:START|END)__\\\\n`, \"gm\"), \"\");\n }\n return content.replace(\n new RegExp(`^ *# __${name}_START__\\\\n[\\\\s\\\\S]*?^ *# __${name}_END__\\\\n`, \"m\"),\n \"\",\n );\n}\n\n// Replace a single-line `# __X__` marker. The marker line's own indentation is\n// reused for the replacement; when `replacement` is undefined the whole line is\n// removed. `replacement` may contain newlines for multi-line expansions.\nfunction line(content: string, name: string, replacement: string | undefined): string {\n const re = new RegExp(`^([ \\\\t]*)# __${name}__\\\\n`, \"gm\");\n return content.replace(re, (_match, indent: string) => {\n if (replacement === undefined) return \"\";\n return (\n replacement\n .split(\"\\n\")\n .map((l) => (l ? indent + l : l))\n .join(\"\\n\") + \"\\n\"\n );\n });\n}\n\nfunction applyCommon(\n content: string,\n params: {\n workspaceName: string;\n workingDirectory?: string;\n environment: string;\n packageManager: PackageManager;\n },\n): string {\n const { workingDirectory, environment, packageManager } = params;\n let out = line(content, \"HEADER\", HEADER);\n out = line(\n out,\n \"WORKING_DIRECTORY\",\n workingDirectory ? `working-directory: ${workingDirectory}` : undefined,\n );\n // Plain placeholders last so values containing `$` are not interpreted as\n // replacement patterns.\n return out\n .replaceAll(\"__WORKSPACE_NAME__\", () => params.workspaceName)\n .replaceAll(\"__ENVIRONMENT__\", () => environment)\n .replaceAll(\"__PACKAGE_MANAGER__\", () => packageManager)\n .replaceAll(\"__TAILOR_CLI__\", () => TAILOR_CLI_COMMANDS[packageManager])\n .replaceAll(\"__APP_DIR__\", () => workingDirectory ?? \".\");\n}\n\n/**\n * Render the branch-target deploy workflow.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderBranchWorkflow(params: RenderBranchParams): RenderResult {\n const { branch } = params;\n const seedValidate = params.seedValidate ?? false;\n const migrationDriftCheck = params.migrationDriftCheck ?? false;\n const erdPreview = params.erdPreview;\n\n let out = branchTemplate;\n out = block(out, \"PLAN_JOB\", true);\n out = block(out, \"ERD_PREVIEW_JOB\", erdPreview !== null);\n out = block(out, \"ERD_PREVIEW_COMMENT_JOB\", erdPreview !== null);\n out = block(out, \"PULL_REQUEST\", true);\n out = block(out, \"DISPATCH_INPUTS\", true);\n out = block(out, \"SEED_VALIDATE\", seedValidate);\n out = block(out, \"MIGRATION_DRIFT_CHECK\", migrationDriftCheck);\n // SEED_DATA is dropped from the default rendering; users add their own step.\n out = block(out, \"SEED_DATA\", false);\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: >-\\n github.event_name == 'push' ||\\n (github.event_name == 'workflow_dispatch' && !inputs['dry-run'])`,\n );\n out = line(\n out,\n \"PATHS\",\n params.workingDirectory ? `paths: [\"${params.workingDirectory}/**\"]` : undefined,\n );\n\n out = applyCommon(out, params).replaceAll(\"__BRANCH__\", () => branch);\n\n const generatedIds: string[] = [\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-install\",\n \"tailor-plan/tailor-generate-check\",\n ];\n if (seedValidate) {\n generatedIds.push(\"tailor-plan/tailor-seed-validate\");\n }\n generatedIds.push(\"tailor-plan/tailor-drift-check\");\n if (migrationDriftCheck) {\n generatedIds.push(\"tailor-plan/tailor-migration-drift-check\");\n }\n generatedIds.push(\"tailor-plan/tailor-plan\");\n if (erdPreview) {\n generatedIds.push(\n \"tailor-erd-preview-matrix\",\n \"tailor-erd-preview-matrix/tailor-checkout\",\n \"tailor-erd-preview-matrix/tailor-checkout-base\",\n \"tailor-erd-preview-matrix/tailor-erd-preview-matrix\",\n \"tailor-erd-preview\",\n \"tailor-erd-preview/tailor-checkout\",\n \"tailor-erd-preview/tailor-setup\",\n \"tailor-erd-preview/tailor-checkout-base\",\n \"tailor-erd-preview/tailor-detect-base-package-manager\",\n \"tailor-erd-preview/tailor-setup-base-pnpm\",\n \"tailor-erd-preview/tailor-setup-base-node\",\n \"tailor-erd-preview/tailor-setup-base-yarn\",\n \"tailor-erd-preview/tailor-setup-base-bun\",\n \"tailor-erd-preview/tailor-install-base\",\n \"tailor-erd-preview/tailor-restore-head-setup\",\n \"tailor-erd-preview/tailor-build-erd-preview\",\n \"tailor-erd-preview/tailor-upload-erd-viewer\",\n \"tailor-erd-preview-comment\",\n \"tailor-erd-preview-comment/tailor-comment-erd-preview\",\n );\n }\n generatedIds.push(\n \"tailor-deploy\",\n \"tailor-deploy/tailor-checkout\",\n \"tailor-deploy/tailor-setup\",\n \"tailor-deploy/tailor-install\",\n \"tailor-deploy/tailor-apply\",\n \"tailor-deploy/tailor-notify\",\n );\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the tag-target deploy workflow.\n *\n * When `branch` is set, a tag-reachability guard job is generated and the plan\n * job gates on it; otherwise no guard is emitted and tags deploy unconditionally.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderTagWorkflow(params: RenderTagParams): RenderResult {\n const { tagPattern, branch } = params;\n const hasGuard = branch !== undefined;\n const seedValidate = params.seedValidate ?? false;\n const migrationDriftCheck = params.migrationDriftCheck ?? false;\n\n let out = tagTemplate;\n out = block(out, \"TAG_GUARD_JOB\", hasGuard);\n out = block(out, \"SEED_VALIDATE\", seedValidate);\n out = block(out, \"MIGRATION_DRIFT_CHECK\", migrationDriftCheck);\n // SEED_DATA is dropped from the default rendering; users add their own step.\n out = block(out, \"SEED_DATA\", false);\n out = line(out, \"PLAN_NEEDS\", hasGuard ? \"needs: tailor-tag-guard\" : undefined);\n out = line(\n out,\n \"PLAN_IF\",\n hasGuard\n ? `if: >-\\n github.event_name == 'workflow_dispatch' ||\\n needs.tailor-tag-guard.outputs.on-branch == 'true'`\n : undefined,\n );\n\n out = applyCommon(out, params).replaceAll(\"__TAG_PATTERN__\", () => tagPattern);\n if (hasGuard) {\n out = out.replaceAll(\"__BRANCH__\", () => branch);\n }\n\n const generatedIds: string[] = [];\n if (hasGuard) {\n generatedIds.push(\n \"tailor-tag-guard\",\n \"tailor-tag-guard/tailor-checkout\",\n \"tailor-tag-guard/tailor-tag-guard\",\n );\n }\n generatedIds.push(\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-install\",\n \"tailor-plan/tailor-generate-check\",\n );\n if (seedValidate) {\n generatedIds.push(\"tailor-plan/tailor-seed-validate\");\n }\n generatedIds.push(\"tailor-plan/tailor-drift-check\");\n if (migrationDriftCheck) {\n generatedIds.push(\"tailor-plan/tailor-migration-drift-check\");\n }\n generatedIds.push(\n \"tailor-plan/tailor-plan\",\n \"tailor-deploy\",\n \"tailor-deploy/tailor-checkout\",\n \"tailor-deploy/tailor-setup\",\n \"tailor-deploy/tailor-install\",\n \"tailor-deploy/tailor-apply\",\n \"tailor-deploy/tailor-notify\",\n );\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the preview workflow (PR open/sync/close triggers).\n *\n * The deploy job runs on opened/synchronize/reopened events; the cleanup job\n * runs on the closed event. Both jobs run in the same workflow so PR number\n * context is always available.\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderPreviewWorkflow(params: RenderPreviewParams): RenderResult {\n const { branch } = params;\n const requirePreviewLabel = params.requirePreviewLabel ?? false;\n\n let out = previewTemplate;\n out = line(\n out,\n \"PATHS\",\n params.workingDirectory ? `paths: [\"${params.workingDirectory}/**\"]` : undefined,\n );\n\n // PR trigger event types — single line() marker avoids duplicate YAML map keys in the template.\n out = line(\n out,\n \"PR_TYPES\",\n requirePreviewLabel\n ? \"types: [labeled, synchronize, reopened, closed]\"\n : \"types: [opened, synchronize, reopened, closed]\",\n );\n\n // Deploy job if condition. Fork PRs don't have access to secrets/vars, so guard them out.\n const deployIf = requirePreviewLabel\n ? `if: >-\\n contains(github.event.pull_request.labels.*.name, 'tailor:preview') &&\\n github.event.action != 'closed' &&\\n !github.event.pull_request.draft &&\\n !github.event.pull_request.head.repo.fork`\n : `if: >-\\n github.event.action != 'closed' &&\\n !github.event.pull_request.draft &&\\n !github.event.pull_request.head.repo.fork`;\n out = line(out, \"DEPLOY_IF\", deployIf);\n\n // Cleanup always runs on closed regardless of current labels: the label may have been\n // removed after a preview deploy, and the cleanup action is a no-op when no workspace exists.\n // Fork PRs also need guarding since cleanup requires secrets/vars.\n out = line(\n out,\n \"CLEANUP_IF\",\n `if: >-\\n github.event.action == 'closed' &&\\n !github.event.pull_request.head.repo.fork`,\n );\n\n out = applyCommon(out, params)\n .replaceAll(\"__BRANCH__\", () => branch)\n .replaceAll(\"__REGION__\", () => params.region);\n\n const generatedIds: string[] = [\n \"tailor-preview-deploy\",\n \"tailor-preview-deploy/tailor-checkout\",\n \"tailor-preview-deploy/tailor-setup\",\n \"tailor-preview-deploy/tailor-install\",\n \"tailor-preview-deploy/tailor-generate-check\",\n \"tailor-preview-deploy/tailor-drift-check\",\n \"tailor-preview-deploy/tailor-preview-deploy\",\n \"tailor-preview-deploy/tailor-preview-comment\",\n \"tailor-preview-cleanup\",\n \"tailor-preview-cleanup/tailor-checkout\",\n \"tailor-preview-cleanup/tailor-setup\",\n \"tailor-preview-cleanup/tailor-install\",\n \"tailor-preview-cleanup/tailor-preview-cleanup\",\n ];\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the per-app composite action.\n *\n * The action contains only the deploy step and a failure notification.\n * Checkout, setup, and install are the caller's responsibility (coordinator workflow).\n * @param params - Workspace and rendering configuration\n * @returns Rendered YAML and the list of managed step ids\n */\nexport function renderActionWorkflow(params: RenderActionParams): RenderResult {\n let out = actionTemplate;\n out = line(out, \"HEADER\", HEADER);\n\n // build-site is a user-owned slot; include when staticWebsites are configured.\n out = block(out, \"STATIC_WEBSITE_BUILD\", params.hasStaticWebsites ?? false);\n\n out = out.replaceAll(\"__WORKSPACE_NAME__\", () => params.workspaceName);\n\n const generatedIds = [\"tailor-apply\", \"tailor-notify\"];\n\n return { content: out, generatedIds };\n}\n\nconst ACTIONS_SHA = \"85f0ec85d3bcbdec915daa315b6ddf46ce9b6d2c\";\nconst ACTIONS_VERSION = \"v2.2.0\";\n\n/**\n * Render the coordinator workflow that orchestrates per-app composite actions.\n *\n * Generates per-app plan steps (generate-check, drift-check, plan) and per-app\n * deploy steps (calling each app's composite action at .github/actions/tailor-<name>).\n * Checkout, setup, and install are done once per job using the local tailor-setup action.\n * @param params - Coordinator and app configuration\n * @returns Rendered YAML and the list of managed job/step ids\n */\nexport function renderCoordinateWorkflow(params: RenderCoordinateParams): RenderResult {\n const { coordinatorName, kind, actionGroups, environment, packageManager } = params;\n const isTag = kind === \"tag\";\n const branch = params.branch;\n const tagPattern = params.tagPattern ?? \"v*\";\n\n let out = coordinateTemplate;\n out = line(out, \"HEADER\", HEADER);\n\n out = block(out, \"PULL_REQUEST\", !isTag);\n out = block(out, \"PUSH_BRANCHES\", !isTag);\n out = block(out, \"PUSH_TAGS\", isTag);\n out = block(out, \"TAG_GUARD_JOB\", isTag && branch !== undefined);\n\n if (isTag && branch !== undefined) {\n out = line(out, \"PLAN_NEEDS\", \"needs: tailor-tag-guard\");\n out = line(\n out,\n \"PLAN_IF\",\n `if: >-\\n github.event_name == 'workflow_dispatch' ||\\n needs.tailor-tag-guard.outputs.on-branch == 'true'`,\n );\n } else if (isTag) {\n out = line(out, \"PLAN_NEEDS\", undefined);\n out = line(out, \"PLAN_IF\", undefined);\n } else {\n out = line(out, \"PLAN_NEEDS\", undefined);\n out = line(\n out,\n \"PLAN_IF\",\n `if: >-\\n github.event_name == 'pull_request' ||\\n (github.event_name == 'workflow_dispatch' && inputs['dry-run'])`,\n );\n }\n\n if (isTag) {\n // Tag coordinator: deploy runs after plan (plan checks tag reachability).\n // When plan is skipped via workflow_dispatch dry-run, deploy is also skipped.\n out = line(out, \"DEPLOY_NEEDS\", \"needs: tailor-plan\");\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: \\${{ !(github.event_name == 'workflow_dispatch' && inputs['dry-run']) }}`,\n );\n out = line(out, \"DEPLOY_ENVIRONMENT\", `environment: ${environment}`);\n } else {\n // Branch coordinator: plan (PR) and deploy (push) are independent jobs —\n // no needs relationship, so deploy is not skipped when plan is skipped on push.\n out = line(out, \"DEPLOY_NEEDS\", undefined);\n out = line(\n out,\n \"DEPLOY_IF\",\n `if: >-\\n github.event_name == 'push' ||\\n (github.event_name == 'workflow_dispatch' && !inputs['dry-run'])`,\n );\n out = line(out, \"DEPLOY_ENVIRONMENT\", `environment: ${environment}`);\n }\n\n const driftCheckStep = [\n `- id: tailor-drift-check`,\n ` uses: tailor-platform/actions/drift-check@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ` fail-on-drift: \\${{ vars.TAILOR_PLATFORM_FAIL_ON_DRIFT == 'true' }}`,\n ].join(\"\\n\");\n const configPath = (app: CoordinateApp) =>\n app.dir === \".\" ? \"tailor.config.ts\" : `${app.dir}/tailor.config.ts`;\n const groupConfigPath = (group: CoordinateAppGroup) => group.apps.map(configPath).join(\",\");\n const firstApp = (group: CoordinateAppGroup) => {\n const [app] = group.apps;\n if (!app) {\n throw new Error(\"Coordinate action groups must contain at least one app.\");\n }\n return app;\n };\n const singleAppPlanStep = (group: CoordinateAppGroup, app: CoordinateApp) => {\n const wd = app.dir !== \".\" ? app.dir : undefined;\n const wdLine = wd ? `\\n working-directory: ${wd}` : \"\";\n return [\n `- id: tailor-plan-${group.id}`,\n ` if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork`,\n ` uses: tailor-platform/actions/plan@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` package-manager: ${packageManager}${wdLine}`,\n ` label: ${coordinatorName}/${group.id}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` github-token: \\${{ secrets.GITHUB_TOKEN }}`,\n ];\n };\n const multiConfigPlanStep = (group: CoordinateAppGroup) => [\n `- id: tailor-plan-${group.id}`,\n ` if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork`,\n ` uses: tailor-platform/actions/plan@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` env:`,\n ` TAILOR_PLATFORM_SDK_CONFIG_PATH: ${groupConfigPath(group)}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` package-manager: ${packageManager}`,\n ` label: ${coordinatorName}/${group.id}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` github-token: \\${{ secrets.GITHUB_TOKEN }}`,\n ];\n const perAppPlanSteps = actionGroups\n .flatMap((group) => {\n const generateCheckSteps = group.apps.flatMap((app) => {\n const wd = app.dir !== \".\" ? app.dir : undefined;\n const wdLine = wd ? `\\n working-directory: ${wd}` : \"\";\n return [\n `- id: tailor-generate-check-${app.name}`,\n ` uses: tailor-platform/actions/generate-check@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}${wdLine}`,\n ];\n });\n const planStep =\n group.apps.length === 1\n ? singleAppPlanStep(group, firstApp(group))\n : multiConfigPlanStep(group);\n return [...generateCheckSteps, ...planStep];\n })\n .join(\"\\n\");\n out = line(out, \"PER_APP_PLAN_STEPS\", `${driftCheckStep}\\n${perAppPlanSteps}`);\n\n const singleAppDeployStep = (group: CoordinateAppGroup, app: CoordinateApp) => [\n `- id: tailor-deploy-${group.id}`,\n ` uses: ./.github/actions/tailor-${app.name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${app.name}`,\n ` working-directory: ${app.dir}`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ` # editable: api-url:`,\n ];\n const buildSiteStep = (app: CoordinateApp) => [\n `- id: tailor-build-site-${app.name}`,\n ` uses: ./.github/actions/tailor-${app.name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${app.name}`,\n ` working-directory: ${app.dir}`,\n ` deploy: \"false\"`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ];\n const multiConfigDeployStep = (group: CoordinateAppGroup) => [\n ...group.apps.filter((app) => app.hasStaticWebsites).flatMap(buildSiteStep),\n `- id: tailor-deploy-${group.id}`,\n // Grouped deploys reuse one app action; keep action.yml parameterized by config/deploy/build-site inputs.\n ` uses: ./.github/actions/tailor-${firstApp(group).name}`,\n ` with:`,\n ` workspace-id: \\${{ vars.TAILOR_PLATFORM_WORKSPACE_ID }}`,\n ` name: ${coordinatorName}/${group.id}`,\n ` working-directory: .`,\n ` config: ${groupConfigPath(group)}`,\n ` build-site: \"false\"`,\n ` package-manager: ${packageManager}`,\n ` platform-client-id: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID }}`,\n ` platform-client-secret: \\${{ secrets.TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET }}`,\n ` slack-token: \\${{ secrets.TAILOR_SLACK_BOT_TOKEN }}`,\n ` slack-channel-id: \\${{ vars.TAILOR_SLACK_CHANNEL_ID }}`,\n ` # editable: api-url:`,\n ];\n const deploySteps = actionGroups\n .flatMap((group) =>\n group.apps.length === 1\n ? singleAppDeployStep(group, firstApp(group))\n : multiConfigDeployStep(group),\n )\n .join(\"\\n\");\n out = line(out, \"PER_APP_DEPLOY_STEPS\", deploySteps);\n\n // Plain placeholders last so values containing `$` are not interpreted as\n // replacement patterns.\n out = out.replaceAll(\"__WORKSPACE_NAME__\", () => coordinatorName);\n out = out.replaceAll(\"__ENVIRONMENT__\", () => environment);\n if (branch !== undefined) {\n out = out.replaceAll(\"__BRANCH__\", () => branch);\n }\n if (isTag) {\n out = out.replaceAll(\"__TAG_PATTERN__\", () => tagPattern);\n }\n\n const generatedIds: string[] = [];\n if (isTag && branch !== undefined) {\n generatedIds.push(\n \"tailor-tag-guard\",\n \"tailor-tag-guard/tailor-checkout\",\n \"tailor-tag-guard/tailor-tag-guard\",\n );\n }\n generatedIds.push(\n \"tailor-plan\",\n \"tailor-plan/tailor-checkout\",\n \"tailor-plan/tailor-setup\",\n \"tailor-plan/tailor-drift-check\",\n );\n for (const group of actionGroups) {\n for (const app of group.apps) {\n generatedIds.push(`tailor-plan/tailor-generate-check-${app.name}`);\n }\n generatedIds.push(`tailor-plan/tailor-plan-${group.id}`);\n }\n generatedIds.push(\"tailor-deploy\", \"tailor-deploy/tailor-checkout\", \"tailor-deploy/tailor-setup\");\n for (const group of actionGroups) {\n for (const app of group.apps) {\n if (group.apps.length > 1 && app.hasStaticWebsites) {\n generatedIds.push(`tailor-deploy/tailor-build-site-${app.name}`);\n }\n }\n generatedIds.push(`tailor-deploy/tailor-deploy-${group.id}`);\n }\n\n return { content: out, generatedIds };\n}\n\n/**\n * Render the content of the user-owned .github/actions/tailor-setup/action.yml local action.\n *\n * This file is generated once by `setup coordinate` and never overwritten.\n * It wraps the setup and install actions with the package manager baked in.\n * @param params - Package manager configuration\n * @returns File content string\n */\nexport function renderTailorSetupAction(params: { packageManager: PackageManager }): string {\n const { packageManager } = params;\n return [\n `# This file is user-owned. Generated once by \\`tailor setup coordinate\\` and never overwritten.`,\n `# Customize freely: add pre/post steps, change install flags, etc.`,\n `name: Tailor Setup`,\n `description: Install dependencies and run tailor setup for composite action callers.`,\n `runs:`,\n ` using: composite`,\n ` steps:`,\n ` - uses: tailor-platform/actions/setup@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ` # Add custom steps here (e.g. private registry authentication)`,\n ` - uses: tailor-platform/actions/install@${ACTIONS_SHA} # ${ACTIONS_VERSION}`,\n ` with:`,\n ` package-manager: ${packageManager}`,\n ` # editable: install-command:`,\n ``,\n ].join(\"\\n\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureConfigId } from \"#/cli/commands/deploy/config-id-injector\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { workspaceNameSchema } from \"#/cli/shared/workspace-name\";\nimport { getNamespacesWithMigrations } from \"../tailordb/migrate/config\";\nimport { detectDefaultBranch, type GitRunner } from \"./git\";\nimport {\n findTarget,\n hashContent,\n LOCK_VERSION,\n readLock,\n writeLock,\n type LockFile,\n type LockInputs,\n type LockTarget,\n type TargetKind,\n} from \"./lock\";\nimport {\n detectPackageManager,\n renderActionWorkflow,\n renderBranchWorkflow,\n renderCoordinateWorkflow,\n renderPreviewWorkflow,\n renderTagWorkflow,\n renderTailorSetupAction,\n TEMPLATE_VERSION,\n type CoordinateApp,\n type CoordinateAppGroup,\n type CoordinateKind,\n type PackageManager,\n type RenderResult,\n} from \"./templates\";\n\ntype CommonSetupOptions = {\n workspaceName?: string;\n dir: string;\n environment?: string;\n force: boolean;\n outputDir: string;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n /** Injectable config-name loader, for testing. Defaults to loading the config. */\n loadConfigName?: (configPath: string) => Promise<string | undefined>;\n /** Injectable TailorDB namespace loader, for testing. Defaults to loading the config. */\n loadErdNamespaces?: (configPath: string) => Promise<string[]>;\n /** Injectable migration config detector, for testing. Defaults to loading the config. */\n loadHasMigrations?: (configPath: string) => Promise<boolean>;\n /** Injectable seed plugin detector, for testing. Defaults to loading the config. */\n loadHasSeeds?: (configPath: string) => Promise<boolean>;\n /** Injectable static website detector, for testing. Defaults to loading the config. */\n loadHasStaticWebsites?: (configPath: string) => Promise<boolean>;\n};\n\nexport type BranchSetupOptions = CommonSetupOptions & {\n kind: \"branch\";\n branch?: string;\n erdPreview: boolean;\n};\n\nexport type TagSetupOptions = CommonSetupOptions & {\n kind: \"tag\";\n tagPattern: string;\n branch?: string;\n};\n\nexport type PreviewSetupOptions = CommonSetupOptions & {\n kind: \"preview\";\n branch?: string;\n /** Workspace region for preview workspace creation (e.g. `us-west`). */\n region: string;\n /**\n * When true, the preview workflow deploys only for PRs labeled `tailor:preview`.\n * Default false: preview deploys on every PR.\n */\n requirePreviewLabel?: boolean;\n};\n\nexport type ActionSetupOptions = CommonSetupOptions & {\n kind: \"action\";\n};\n\nexport type SetupTargetOptions =\n | BranchSetupOptions\n | TagSetupOptions\n | PreviewSetupOptions\n | ActionSetupOptions;\n\nexport type CoordinateSetupOptions = {\n coordinatorName: string;\n coordinateKind: CoordinateKind;\n /** Action names or comma-separated action groups (without tailor- prefix), in deploy order. */\n actions: string[];\n branch?: string;\n tagPattern?: string;\n environment?: string;\n force: boolean;\n outputDir: string;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n};\n\nfunction actionName(input: string): string {\n return input.startsWith(\"tailor-\") ? input.slice(\"tailor-\".length) : input;\n}\n\nfunction splitActionGroup(input: string): string[] {\n const names = input.split(\",\").map((entry) => actionName(entry.trim()));\n if (names.some((name) => name.length === 0)) {\n throw new Error(\"--action must contain one or more non-empty action names.\");\n }\n return names;\n}\n\nfunction uniqueGroupId(names: readonly string[], usedIds: Set<string>): string {\n const base = names.join(\"-\");\n let id = base;\n let suffix = 2;\n while (usedIds.has(id)) {\n id = `${base}-${suffix}`;\n suffix += 1;\n }\n usedIds.add(id);\n return id;\n}\n\nasync function defaultLoadConfigName(configPath: string): Promise<string | undefined> {\n const { config } = await loadConfig(configPath);\n return config.name;\n}\n\nasync function defaultLoadErdNamespaces(configPath: string): Promise<string[]> {\n const { config } = await loadConfig(configPath);\n return extractOwnedNamespaces(config);\n}\n\nasync function defaultLoadHasMigrations(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return getNamespacesWithMigrations(config, path.dirname(configPath)).length > 0;\n}\n\nasync function defaultLoadHasSeeds(configPath: string): Promise<boolean> {\n const { plugins } = await loadConfig(configPath);\n return plugins.some((p) => p.id === \"@tailor-platform/seed\");\n}\n\nasync function defaultLoadHasStaticWebsites(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return (config.staticWebsites?.length ?? 0) > 0;\n}\n\n// The name is used as the plan label, the generated file name, and the default\n// GitHub Environment name, so it must stay within the workspace-name charset.\nfunction validateWorkspaceName(name: string): void {\n if (!workspaceNameSchema.safeParse(name).success) {\n throw new Error(\n `Invalid workspace name \"${name}\". Names must be 3-63 characters of lowercase ` +\n \"letters, numbers, and hyphens, and cannot start or end with a hyphen. \" +\n \"Pass a valid name with --name.\",\n );\n }\n}\n\n// The values below are embedded into workflow YAML. Restrict them to\n// characters that are safe inside a double-quoted YAML scalar (and cannot\n// smuggle a ${{ }} expression into the generated file).\nconst BRANCH_RE = /^[A-Za-z0-9._/-]+$/;\nconst TAG_PATTERN_RE = /^[A-Za-z0-9._/*?![\\]-]+$/;\n\nfunction validateBranch(branch: string): void {\n if (!BRANCH_RE.test(branch)) {\n throw new Error(\n `Invalid branch name \"${branch}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported here.`,\n );\n }\n}\n\nfunction validateTagPattern(pattern: string): void {\n if (!TAG_PATTERN_RE.test(pattern)) {\n throw new Error(\n `Invalid tag pattern \"${pattern}\". Only letters, numbers, \".\", \"_\", \"/\", \"-\", and the glob characters \"*?![]\" are supported.`,\n );\n }\n}\n\n// The environment name is embedded into workflow YAML as a plain scalar.\nconst ENVIRONMENT_RE = /^[A-Za-z0-9._/-]+$/;\n\nfunction validateEnvironment(environment: string): void {\n if (!ENVIRONMENT_RE.test(environment)) {\n throw new Error(\n `Invalid environment name \"${environment}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported.`,\n );\n }\n}\n\n// `--region` is embedded into workflow YAML as a plain scalar.\nconst REGION_RE = /^[A-Za-z0-9._-]+$/;\n\nfunction validateRegion(region: string): void {\n if (!REGION_RE.test(region)) {\n throw new Error(\n `Invalid region \"${region}\". Only letters, numbers, \".\", \"_\", and \"-\" are supported.`,\n );\n }\n}\n\n// `--dir` is embedded into workflow YAML (paths filters / working-directory).\n// Restrict it to POSIX path characters so it cannot break the YAML or smuggle\n// in a ${{ }} expression. Checked after backslashes are normalized to \"/\".\nconst DIR_RE = /^[A-Za-z0-9._/-]+$/;\n\nfunction validateDir(dir: string): void {\n if (!DIR_RE.test(dir)) {\n throw new Error(\n `Invalid --dir \"${dir}\". Only letters, numbers, \".\", \"_\", \"/\", and \"-\" are supported.`,\n );\n }\n}\n\n// ERD namespaces are embedded into a GitHub Actions matrix and artifact file\n// names. Keep them to path-safe scalar values.\nconst ERD_NAMESPACE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\nfunction validateErdNamespaces(namespaces: readonly string[]): void {\n for (const namespace of namespaces) {\n if (!ERD_NAMESPACE_RE.test(namespace)) {\n throw new Error(\n `TailorDB namespace \"${namespace}\" cannot be used in --erd-preview. ` +\n \"Only letters, numbers, '.', '_', and '-' are supported, and the name must start with a letter or number.\",\n );\n }\n }\n}\n\n// `rel` is \"\" for the root itself, \"..\" or \"../foo\" for an escape. Guard on\n// the path segment so a sibling-prefixed name like \"..foo\" is not rejected.\nfunction escapesRoot(rel: string): boolean {\n return (\n rel === \"..\" || rel.startsWith(`..${path.sep}`) || rel.startsWith(\"../\") || path.isAbsolute(rel)\n );\n}\n\n/**\n * Resolve the config file path for the given app directory.\n *\n * `--dir` must stay inside the repository: the value is embedded in workflow\n * `paths:` filters and the config under it gets mutated (id injection), so\n * absolute paths and `..` traversal are rejected.\n * @param outputDir - Repository root (cwd)\n * @param dir - App directory relative to the repo root\n * @returns Absolute path to tailor.config.ts\n */\nfunction resolveConfigPath(outputDir: string, dir: string): string {\n const appDir = path.resolve(outputDir, dir);\n const rel = path.relative(outputDir, appDir);\n if (path.isAbsolute(dir) || escapesRoot(rel)) {\n throw new Error(`--dir must be a relative path inside the repository (got \"${dir}\").`);\n }\n // Also catch symlinked subdirectories that point outside the repository.\n if (fs.existsSync(appDir)) {\n const realAppDir = path.normalize(fs.realpathSync(appDir));\n const realOutputDir = path.normalize(fs.realpathSync(outputDir));\n const realRel = path.relative(realOutputDir, realAppDir);\n if (escapesRoot(realRel)) {\n throw new Error(\n `--dir must resolve to a directory inside the repository (got \"${dir}\", which links outside it).`,\n );\n }\n }\n const configPath = path.join(appDir, \"tailor.config.ts\");\n if (!fs.existsSync(configPath)) {\n throw new Error(\n `tailor.config.ts not found at ${configPath}. ` +\n \"Run this from your SDK project root, or pass the app directory with --dir.\",\n );\n }\n return configPath;\n}\n\ntype Resolved = {\n kind: TargetKind;\n workspaceName: string;\n branch: string | null;\n environment: string;\n packageManager: PackageManager;\n erdNamespaces: string[];\n render: RenderResult;\n inputs: LockInputs;\n file: string;\n configPath: string;\n};\n\n/**\n * Resolve all derived values and render the workflow content.\n * @param options - Setup options\n * @returns Resolved target metadata and rendered content\n */\nasync function resolve(options: SetupTargetOptions): Promise<Resolved> {\n // Normalize before any filesystem use and before embedding into workflow\n // YAML (paths filters / working-directory): POSIX separators, collapse\n // duplicate slashes, drop a leading \"./\" and trailing \"/\" so values like\n // \"./apps/backend/\" produce a clean \"apps/backend\".\n const dir =\n options.dir\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/{2,}/g, \"/\")\n .replace(/^\\.\\//, \"\")\n .replace(/\\/$/, \"\") || \".\";\n validateDir(dir);\n const workingDirectory = dir !== \".\" ? dir : undefined;\n\n const configPath = resolveConfigPath(options.outputDir, dir);\n\n const loadName = options.loadConfigName ?? defaultLoadConfigName;\n const workspaceName = options.workspaceName ?? (await loadName(configPath));\n if (!workspaceName) {\n throw new Error(\n \"Could not determine the workspace name. \" +\n \"Pass --name, or set 'name' in tailor.config.ts.\",\n );\n }\n validateWorkspaceName(workspaceName);\n\n const { kind } = options;\n const packageManager = detectPackageManager(options.outputDir);\n // The env-scoped TAILOR_PLATFORM_WORKSPACE_ID variable is only readable by a\n // job that declares `environment:`, so every plan/deploy job sets one. When\n // --environment is omitted it defaults to the workspace name.\n const environment = options.environment ?? workspaceName;\n validateEnvironment(environment);\n\n if (kind === \"tag\") {\n validateTagPattern(options.tagPattern);\n }\n\n let branch: string | null = null;\n let branchAutoDetected = false;\n let render: RenderResult;\n let erdNamespaces: string[] = [];\n let hasMigrations = false;\n let hasSeeds = false;\n let hasStaticWebsites = false;\n const loadHasMigrations = options.loadHasMigrations ?? defaultLoadHasMigrations;\n const loadHasSeeds = options.loadHasSeeds ?? defaultLoadHasSeeds;\n const loadHasStaticWebsites = options.loadHasStaticWebsites ?? defaultLoadHasStaticWebsites;\n\n if (kind === \"branch\") {\n if (options.erdPreview) {\n const loadErdNamespaces = options.loadErdNamespaces ?? defaultLoadErdNamespaces;\n erdNamespaces = await loadErdNamespaces(configPath);\n if (erdNamespaces.length === 0) {\n throw new Error(\n \"No TailorDB namespaces found for --erd-preview. Define owned db namespaces in tailor.config.ts.\",\n );\n }\n validateErdNamespaces(erdNamespaces);\n }\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(options.outputDir, options.gitRunner);\n validateBranch(branch);\n hasMigrations = await loadHasMigrations(configPath);\n hasSeeds = await loadHasSeeds(configPath);\n render = renderBranchWorkflow({\n workspaceName,\n branch,\n workingDirectory,\n environment,\n packageManager,\n erdPreview: options.erdPreview ? { namespaces: erdNamespaces } : null,\n migrationDriftCheck: hasMigrations,\n seedValidate: hasSeeds,\n });\n } else if (kind === \"tag\") {\n branch = options.branch ?? null;\n if (branch !== null) {\n validateBranch(branch);\n }\n hasMigrations = await loadHasMigrations(configPath);\n hasSeeds = await loadHasSeeds(configPath);\n render = renderTagWorkflow({\n workspaceName,\n tagPattern: options.tagPattern,\n branch: options.branch,\n workingDirectory,\n environment,\n packageManager,\n migrationDriftCheck: hasMigrations,\n seedValidate: hasSeeds,\n });\n } else if (kind === \"preview\") {\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(options.outputDir, options.gitRunner);\n validateBranch(branch);\n validateRegion(options.region);\n render = renderPreviewWorkflow({\n workspaceName,\n branch,\n workingDirectory,\n environment,\n packageManager,\n region: options.region,\n requirePreviewLabel: options.requirePreviewLabel ?? false,\n });\n } else {\n // action — no branch detection, no package-manager embedding (caller installs)\n hasStaticWebsites = await loadHasStaticWebsites(configPath);\n render = renderActionWorkflow({ workspaceName, workingDirectory, hasStaticWebsites });\n }\n\n // File name encodes the target kind so branch + tag + preview can coexist\n // under the same workspace name without colliding.\n const kindSuffix = kind === \"tag\" ? \"-tag\" : kind === \"preview\" ? \"-preview\" : \"\";\n const file =\n kind === \"action\"\n ? `.github/actions/tailor-${workspaceName}/action.yml`\n : `.github/workflows/tailor-${workspaceName}${kindSuffix}.yml`;\n\n const inputs: LockInputs = {\n branch: kind === \"action\" ? null : branch,\n branchAutoDetected: kind === \"branch\" || kind === \"preview\" ? branchAutoDetected : undefined,\n tagPattern: kind === \"tag\" ? options.tagPattern : null,\n environment,\n dir,\n packageManager,\n region: kind === \"preview\" ? options.region : undefined,\n requirePreviewLabel: kind === \"preview\" ? (options.requirePreviewLabel ?? false) : undefined,\n erdPreview: kind === \"branch\" ? options.erdPreview : false,\n erdNamespaces: kind === \"branch\" && options.erdPreview ? erdNamespaces : undefined,\n migrationDriftCheck: kind === \"branch\" || kind === \"tag\" ? hasMigrations : undefined,\n seedValidate: kind === \"branch\" || kind === \"tag\" ? hasSeeds : undefined,\n hasStaticWebsites: kind === \"action\" ? hasStaticWebsites : undefined,\n };\n\n return {\n kind,\n workspaceName,\n branch,\n environment,\n packageManager,\n erdNamespaces,\n render,\n inputs,\n file,\n configPath,\n };\n}\n\ntype Decision =\n | { action: \"create\" }\n | { action: \"regenerate\" }\n | { action: \"restore\" }\n | { action: \"conflict\"; reason: string };\n\n// Matches the user-editable run: body under the build-site step. Used to\n// normalise the content before hashing so that custom build commands do not\n// trigger false hand-edit drift.\nconst BUILD_SITE_RUN_RE =\n /([ \\t]*- id: build-site\\n(?:[ \\t]+if: [^\\n]+\\n)?[ \\t]+shell: bash\\n[ \\t]+run: \\|)([\\s\\S]*?)(\\n[ \\t]*- |\\n*$)/;\n\n/**\n * Strip the mutable run: body of the build-site step before hashing.\n * When hasStaticWebsites is true the step is present; users are expected to\n * replace the placeholder command with their actual build command. We only\n * hash the structural parts (step id, shell declaration, run: key) so that\n * editing the build command does not look like unintended drift.\n * When hasStaticWebsites is false the step is absent, so the regex is a no-op.\n * @param content - Raw action workflow content\n * @returns Normalised content with the build-site run body replaced by a placeholder\n */\nexport function normalizeActionContent(content: string): string {\n return content.replace(\n BUILD_SITE_RUN_RE,\n (_, header, _body, tail) => `${header}\\n true${tail}`,\n );\n}\n\n/**\n * Extract the run: body of the build-site step from action content.\n * Returns null when the step is absent (hasStaticWebsites is false).\n * @param content - Action workflow content\n * @returns The captured run body string (includes leading newline), or null\n */\nfunction extractBuildSiteRunBody(content: string): string | null {\n const m = BUILD_SITE_RUN_RE.exec(content);\n return m ? (m[2] ?? null) : null;\n}\n\n/**\n * Replace the run: body of the build-site step in action content.\n * No-op when the step is absent.\n * @param content - Target action workflow content\n * @param body - Run body to inject (includes leading newline and indentation)\n * @returns Content with the run body replaced\n */\nfunction injectBuildSiteRunBody(content: string, body: string): string {\n return content.replace(\n BUILD_SITE_RUN_RE,\n (_, header, _placeholder, tail) => `${header}${body}${tail}`,\n );\n}\n\n/**\n * Decide how to reconcile a target with the on-disk file and lock state.\n * @param obj - Decision inputs\n * @param obj.existing - The matching lock target, if any\n * @param obj.fileExists - Whether the workflow file is present on disk\n * @param obj.currentContent - On-disk content when present\n * @param obj.force - Whether --force was passed\n * @param obj.normalize - Optional content normaliser applied before hashing\n * @returns The reconciliation action\n */\nexport function decideAction(obj: {\n existing: LockTarget | undefined;\n fileExists: boolean;\n currentContent: string | null;\n force: boolean;\n normalize?: (content: string) => string;\n}): Decision {\n const { existing, fileExists, currentContent, force, normalize } = obj;\n\n if (!existing) {\n if (!fileExists) return { action: \"create\" };\n if (force) return { action: \"regenerate\" };\n return {\n action: \"conflict\",\n reason:\n \"An unmanaged workflow file already exists at this path. \" +\n \"Delete it, or pass --force to bring it under SDK management (this overwrites it).\",\n };\n }\n\n // Lock has this target.\n if (!fileExists) return { action: \"restore\" };\n if (currentContent !== null) {\n const normalizedContent = normalize ? normalize(currentContent) : currentContent;\n if (hashContent(normalizedContent) === existing.contentHash) {\n return { action: \"regenerate\" };\n }\n }\n if (force) return { action: \"regenerate\" };\n return {\n action: \"conflict\",\n reason:\n \"This workflow file has been edited by hand since it was generated. \" +\n \"Re-run with --force to discard those edits and regenerate, or revert your changes.\",\n };\n}\n\n/**\n * Guard against two targets of different kinds colliding on the same file path.\n * @param obj - Conflict inputs\n * @param obj.lock - Existing lock file, or null\n * @param obj.kind - Target kind being generated\n * @param obj.workspaceName - Workspace name being generated\n * @param obj.file - Target file path\n */\nfunction assertNoKindCollision(obj: {\n lock: LockFile | null;\n kind: TargetKind;\n workspaceName: string;\n file: string;\n}): void {\n const { lock, kind, workspaceName, file } = obj;\n const collision = lock?.targets.find(\n (t) => t.file === file && !(t.kind === kind && t.workspaceName === workspaceName),\n );\n if (collision) {\n throw new Error(\n `A ${collision.kind} target already owns ${file}, which conflicts with this ${kind} target. ` +\n \"Pass a different name with --name to generate a separate workflow.\",\n );\n }\n}\n\n/**\n * Print next-step guidance after generating workflow files.\n * @param obj - Output context\n * @param obj.environment - Resolved GitHub Environment name for this target\n * @param obj.idInjected - Whether an app id was injected into the config\n */\nfunction printNextSteps(obj: { environment: string; idInjected: boolean }): void {\n const { environment, idInjected } = obj;\n\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`1. Set the machine-user credentials as secrets on the \"${environment}\" environment:`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID --env ${environment}`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET --env ${environment}`);\n\n logger.newline();\n logger.log(\n `2. Provision the workspace and set its id as the TAILOR_PLATFORM_WORKSPACE_ID variable ` +\n `on the \"${environment}\" environment:`,\n );\n logger.log(\" tailor workspace create # if it does not exist yet; copy the id\");\n logger.log(` gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env ${environment}`);\n\n logger.newline();\n logger.log(\"3. Commit the generated files:\");\n logger.log(\" - .github/workflows/tailor-*.yml\");\n logger.log(\" - .github/tailor.lock\");\n if (idInjected) {\n logger.log(\" - tailor.config.ts (app id was added)\");\n }\n}\n\n/**\n * Generate a deploy target workflow and reconcile it with the lock file.\n * @param options - Setup options\n */\nexport async function setupTarget(options: SetupTargetOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const resolved = await resolve(options);\n\n const lock = readLock(options.outputDir);\n const absFile = path.join(options.outputDir, resolved.file);\n\n assertNoKindCollision({\n lock,\n kind: resolved.kind,\n workspaceName: resolved.workspaceName,\n file: resolved.file,\n });\n\n const existing = findTarget(lock, resolved.kind, resolved.workspaceName);\n const fileExists = fs.existsSync(absFile);\n const currentContent = fileExists ? fs.readFileSync(absFile, \"utf-8\") : null;\n\n const normalize = resolved.kind === \"action\" ? normalizeActionContent : undefined;\n const decision = decideAction({\n existing,\n fileExists,\n currentContent,\n force: options.force,\n normalize,\n });\n\n if (decision.action === \"conflict\") {\n throw new Error(`${resolved.file}: ${decision.reason}`);\n }\n\n // Inject the app id only after reconciliation has ruled out conflicts, so\n // validation failures leave tailor.config.ts untouched (later filesystem\n // errors can still occur after injection).\n const idResult = await ensureConfigId(resolved.configPath);\n if (idResult === null) {\n logger.warn(\n \"Could not find a defineConfig() call to confirm an app id. \" +\n \"The CI deploy will fail unless your config resolves to one with an 'id'.\",\n );\n }\n const idInjected = idResult?.injected ?? false;\n\n // For action targets, preserve the user-editable build-site run body when\n // regenerating (hash matched after normalization) so that custom build commands\n // survive non-forced reruns without being silently overwritten.\n let contentToWrite = resolved.render.content;\n if (decision.action === \"regenerate\" && normalize && currentContent !== null) {\n const existingBody = extractBuildSiteRunBody(currentContent);\n if (existingBody !== null) {\n contentToWrite = injectBuildSiteRunBody(contentToWrite, existingBody);\n }\n }\n\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, contentToWrite, \"utf-8\");\n\n const newTarget: LockTarget = {\n kind: resolved.kind,\n workspaceName: resolved.workspaceName,\n file: resolved.file,\n templateVersion: TEMPLATE_VERSION,\n inputs: resolved.inputs,\n generatedIds: resolved.render.generatedIds,\n ejectedIds: existing?.ejectedIds ?? [],\n contentHash: hashContent(\n normalize ? normalize(resolved.render.content) : resolved.render.content,\n ),\n };\n\n // Replace in place to keep the lock diff minimal when re-running setup for\n // one of several targets.\n const targets = [...(lock?.targets ?? [])];\n const index = targets.findIndex(\n (t) => t.kind === newTarget.kind && t.workspaceName === newTarget.workspaceName,\n );\n if (index === -1) {\n targets.push(newTarget);\n } else {\n targets[index] = newTarget;\n }\n writeLock(options.outputDir, { version: LOCK_VERSION, targets });\n\n if (decision.action === \"restore\") {\n logger.success(`Regenerated ${styles.path(resolved.file)} (was missing on disk)`);\n } else if (decision.action === \"regenerate\") {\n logger.success(`Regenerated ${styles.path(resolved.file)}`);\n } else {\n logger.success(`Generated ${styles.path(resolved.file)}`);\n }\n\n if (resolved.kind === \"action\") {\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`The composite action has been generated at ${styles.path(resolved.file)}.`);\n logger.log(\n \"Use `tailor setup coordinate` to generate a coordinator workflow that orchestrates this action.\",\n );\n } else {\n printNextSteps({ environment: resolved.environment, idInjected });\n }\n}\n\n/**\n * Generate the coordinator workflow that orchestrates per-app composite actions.\n *\n * Unlike `setupTarget`, this function does not read a Tailor config. The coordinator\n * name is required via `--name`. App working directories are resolved from\n * the lock file entries created by `setup action`.\n * @param options - Coordinate setup options\n */\nexport async function setupCoordinate(options: CoordinateSetupOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { coordinatorName, coordinateKind, actions, force, outputDir } = options;\n validateWorkspaceName(coordinatorName);\n\n if (actions.length === 0) {\n throw new Error(\n \"At least one --action is required. \" +\n \"Run `tailor setup action --dir <app-dir>` for each app first.\",\n );\n }\n\n const environment = options.environment ?? coordinatorName;\n validateEnvironment(environment);\n\n let branch: string | null = null;\n let branchAutoDetected = false;\n if (coordinateKind === \"branch\") {\n branchAutoDetected = options.branch === undefined;\n branch = options.branch ?? detectDefaultBranch(outputDir, options.gitRunner);\n validateBranch(branch);\n } else if (options.branch !== undefined) {\n validateBranch(options.branch);\n branch = options.branch;\n }\n\n const tagPattern = options.tagPattern ?? \"v*\";\n if (coordinateKind === \"tag\") {\n validateTagPattern(tagPattern);\n }\n\n const packageManager = detectPackageManager(outputDir);\n const lock = readLock(outputDir);\n\n if (!lock) {\n throw new Error(\n \".github/tailor.lock not found. \" +\n \"Run `tailor setup action --name <name>` for each app before running setup coordinate.\",\n );\n }\n\n const actionTargets = new Map(\n lock.targets.filter((t) => t.kind === \"action\").map((target) => [target.workspaceName, target]),\n );\n\n // Resolve each action name to its lock entry to get the working directory.\n const seenNames = new Set<string>();\n const usedGroupIds = new Set<string>();\n const actionGroups: CoordinateAppGroup[] = actions.map((actionGroup) => {\n const names = splitActionGroup(actionGroup);\n const apps: CoordinateApp[] = names.map((name) => {\n if (seenNames.has(name)) {\n throw new Error(\n `Duplicate --action \"${name}\". Each composite action can only appear once in a coordinator.`,\n );\n }\n seenNames.add(name);\n const entry = actionTargets.get(name);\n if (!entry) {\n throw new Error(\n `Action target \"${name}\" not found in .github/tailor.lock. ` +\n `Run \\`tailor setup action --name ${name}\\` first.`,\n );\n }\n if (names.length > 1 && entry.templateVersion < TEMPLATE_VERSION) {\n throw new Error(\n `Action target \"${name}\" was generated with an older setup template. ` +\n `Run \\`tailor setup action --name ${name} --force\\` before grouping it in setup coordinate.`,\n );\n }\n validateDir(entry.inputs.dir);\n return {\n name,\n dir: entry.inputs.dir,\n hasStaticWebsites: entry.inputs.hasStaticWebsites,\n };\n });\n return { id: uniqueGroupId(names, usedGroupIds), apps };\n });\n\n const render = renderCoordinateWorkflow({\n coordinatorName,\n kind: coordinateKind,\n actionGroups,\n branch: branch ?? undefined,\n tagPattern: coordinateKind === \"tag\" ? tagPattern : undefined,\n environment,\n packageManager,\n });\n\n const kindSuffix = coordinateKind === \"tag\" ? \"-tag\" : \"\";\n const file = `.github/workflows/tailor-coordinate-${coordinatorName}${kindSuffix}.yml`;\n const absFile = path.join(outputDir, file);\n\n assertNoKindCollision({ lock, kind: \"coordinate\", workspaceName: coordinatorName, file });\n\n const existing = findTarget(lock, \"coordinate\", coordinatorName);\n const fileExists = fs.existsSync(absFile);\n const currentContent = fileExists ? fs.readFileSync(absFile, \"utf-8\") : null;\n\n const decision = decideAction({ existing, fileExists, currentContent, force });\n if (decision.action === \"conflict\") {\n throw new Error(`${file}: ${decision.reason}`);\n }\n\n fs.mkdirSync(path.dirname(absFile), { recursive: true });\n fs.writeFileSync(absFile, render.content, \"utf-8\");\n\n // Generate the local tailor-setup action (user-owned: created once, never overwritten).\n const tailorSetupFile = \".github/actions/tailor-setup/action.yml\";\n const absTailorSetupFile = path.join(outputDir, tailorSetupFile);\n if (!fs.existsSync(absTailorSetupFile)) {\n fs.mkdirSync(path.dirname(absTailorSetupFile), { recursive: true });\n fs.writeFileSync(absTailorSetupFile, renderTailorSetupAction({ packageManager }), \"utf-8\");\n logger.success(`Generated ${styles.path(tailorSetupFile)}`);\n }\n\n const newTarget: LockTarget = {\n kind: \"coordinate\",\n workspaceName: coordinatorName,\n file,\n templateVersion: TEMPLATE_VERSION,\n inputs: {\n branch,\n branchAutoDetected:\n coordinateKind === \"branch\" ? branchAutoDetected : branch !== null ? false : undefined,\n tagPattern: coordinateKind === \"tag\" ? tagPattern : null,\n environment,\n dir: \".\",\n packageManager,\n actionDirs: actionGroups.flatMap((group) => group.apps.map((a) => a.dir)),\n },\n generatedIds: render.generatedIds,\n ejectedIds: existing?.ejectedIds ?? [],\n contentHash: hashContent(render.content),\n };\n\n const targets = [...lock.targets];\n const idx = targets.findIndex(\n (t) => t.kind === newTarget.kind && t.workspaceName === newTarget.workspaceName,\n );\n if (idx === -1) {\n targets.push(newTarget);\n } else {\n targets[idx] = newTarget;\n }\n writeLock(outputDir, { version: LOCK_VERSION, targets });\n\n if (decision.action === \"restore\") {\n logger.success(`Regenerated ${styles.path(file)} (was missing on disk)`);\n } else if (decision.action === \"regenerate\") {\n logger.success(`Regenerated ${styles.path(file)}`);\n } else {\n logger.success(`Generated ${styles.path(file)}`);\n }\n\n logger.newline();\n logger.info(\"Next steps:\");\n logger.newline();\n logger.log(`1. Set the machine-user credentials as secrets on the \"${environment}\" environment:`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_ID --env ${environment}`);\n logger.log(` gh secret set TAILOR_PLATFORM_MACHINE_USER_CLIENT_SECRET --env ${environment}`);\n logger.newline();\n logger.log(\n `2. Provision the target workspace and set TAILOR_PLATFORM_WORKSPACE_ID on the \"${environment}\" environment:`,\n );\n logger.log(\" tailor workspace create # if it does not exist yet; copy the id\");\n logger.log(` gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env ${environment}`);\n logger.newline();\n logger.log(\"3. Commit the generated files:\");\n logger.log(` - ${file}`);\n logger.log(` - ${tailorSetupFile} (if newly created)`);\n logger.log(\" - .github/tailor.lock\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { getNamespacesWithMigrations } from \"../tailordb/migrate/config\";\nimport { normalizeActionContent } from \"./generate\";\nimport { detectDefaultBranch, type GitRunner } from \"./git\";\nimport { hashContent, type LockTarget, readLock } from \"./lock\";\nimport { TEMPLATE_VERSION } from \"./templates\";\n\nconst DRIFT_COUNT_MARKER = \"TAILOR_SETUP_CHECK_DRIFT_COUNT\";\n\n/**\n * Stable drift rule keys. These are part of the public contract: a future\n * `ignore` input on the workflow drift-check step suppresses findings by key.\n */\nexport type DriftRule =\n | \"missing-file\"\n | \"hand-edit\"\n | \"template-version\"\n | \"config-dir\"\n | \"default-branch\"\n | \"erd-namespaces\"\n | \"migration-drift\"\n | \"seed-validate\"\n | \"static-websites\";\n\nexport type DriftFinding = {\n /** Human label for the target: `<kind> <workspaceName>`. */\n target: string;\n rule: DriftRule;\n message: string;\n};\n\n/** Current repository/config state for one target, gathered by the caller. */\nexport type TargetState = {\n fileExists: boolean;\n /** Hash of the on-disk workflow file, or null when it is missing. */\n currentHash: string | null;\n /** Whether tailor.config.ts exists under the target's recorded dir. */\n configExists: boolean;\n /** Detected repository default branch, or null when it cannot be determined. */\n defaultBranch: string | null;\n /** The template version this SDK build generates. */\n templateVersion: number;\n /** Current owned TailorDB namespaces for ERD preview checks, or null when unavailable. */\n erdNamespaces: string[] | null;\n /** Whether the current config has TailorDB namespaces with migrations (branch/tag only). */\n hasMigrations?: boolean;\n /** Whether the current config uses the seed plugin (branch/tag only). */\n hasSeeds?: boolean;\n /** Whether the current config has staticWebsites configured (action only). */\n hasStaticWebsites?: boolean;\n};\n\n/**\n * Compute drift findings for one target by comparing its recorded lock state\n * against the current repository/config state.\n * @param target - The lock target being audited\n * @param state - Current repository/config state for this target\n * @returns Drift findings (empty when the target is in sync)\n */\nexport function findTargetDrift(target: LockTarget, state: TargetState): DriftFinding[] {\n const id = `${target.kind} ${target.workspaceName}`;\n const findings: DriftFinding[] = [];\n\n if (!state.fileExists) {\n findings.push({\n target: id,\n rule: \"missing-file\",\n message: `${target.file} is missing or unreadable. Re-run setup to restore it.`,\n });\n } else if (state.currentHash !== null && state.currentHash !== target.contentHash) {\n findings.push({\n target: id,\n rule: \"hand-edit\",\n message:\n `${target.file} was edited by hand since it was generated. Re-run setup with ` +\n \"--force to regenerate, or keep customizations in your own jobs/steps.\",\n });\n }\n\n if (target.templateVersion < state.templateVersion) {\n findings.push({\n target: id,\n rule: \"template-version\",\n message:\n `A newer workflow template is available (generated with v${String(target.templateVersion)}, ` +\n `current v${String(state.templateVersion)}). Re-run setup to update.`,\n });\n }\n\n if (!state.configExists) {\n findings.push({\n target: id,\n rule: \"config-dir\",\n message:\n `tailor.config.ts not found under \"${target.inputs.dir}\". The app directory may have ` +\n \"moved; re-run setup with the correct --dir.\",\n });\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"coordinate\" || target.kind === \"preview\") &&\n target.inputs.branchAutoDetected !== false &&\n state.defaultBranch !== null &&\n target.inputs.branch !== null &&\n target.inputs.branch !== state.defaultBranch\n ) {\n findings.push({\n target: id,\n rule: \"default-branch\",\n message:\n `The workflow triggers on \"${target.inputs.branch}\" but the repository default branch ` +\n `is now \"${state.defaultBranch}\". If this is intentional, ignore this; otherwise re-run ` +\n \"setup so the trigger matches the default branch.\",\n });\n }\n\n if (target.kind === \"branch\" && target.inputs.erdPreview && state.configExists) {\n const recorded = [...(target.inputs.erdNamespaces ?? [])].toSorted((a, b) =>\n a.localeCompare(b),\n );\n const current = state.erdNamespaces?.toSorted((a, b) => a.localeCompare(b)) ?? null;\n if (\n current === null ||\n recorded.length !== current.length ||\n recorded.some((namespace, index) => namespace !== current[index])\n ) {\n findings.push({\n target: id,\n rule: \"erd-namespaces\",\n message:\n \"TailorDB namespaces for ERD preview changed. Re-run setup so the ERD preview matrix is regenerated.\",\n });\n }\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.migrationDriftCheck === false &&\n state.hasMigrations === true\n ) {\n findings.push({\n target: id,\n rule: \"migration-drift\",\n message:\n \"TailorDB namespaces with migrations were added to the config. \" +\n \"Re-run setup so the tailor-migration-drift-check step is included in the plan job.\",\n });\n }\n\n if (\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.seedValidate === false &&\n state.hasSeeds === true\n ) {\n findings.push({\n target: id,\n rule: \"seed-validate\",\n message:\n \"Seed plugin detected in the current config. \" +\n \"Re-run setup so the tailor-seed-validate step is included in the plan job.\",\n });\n }\n\n if (\n target.kind === \"action\" &&\n target.inputs.hasStaticWebsites === false &&\n state.hasStaticWebsites === true\n ) {\n findings.push({\n target: id,\n rule: \"static-websites\",\n message:\n \"Static websites were added to the config. \" +\n \"Re-run setup so the build-site slot is included in the composite action.\",\n });\n }\n\n return findings;\n}\n\nfunction detectDefaultBranchSafe(cwd: string, run: GitRunner | undefined): string | null {\n try {\n return detectDefaultBranch(cwd, run);\n } catch {\n return null;\n }\n}\n\nfunction escapesRoot(rel: string): boolean {\n return (\n path.isAbsolute(rel) || rel === \"..\" || rel.startsWith(`..${path.sep}`) || rel.startsWith(\"../\")\n );\n}\n\n// The lock is machine-owned, but a corrupted or hand-edited lock could carry an\n// absolute, `..`-traversing, or symlinked path. Reject lexical escapes and, when\n// the path exists, resolve symlinks and reject anything whose real location is\n// outside the repo root, so the audit never reads outside it.\nexport function resolveWithinRoot(outputDir: string, relPath: string): string | null {\n if (path.isAbsolute(relPath)) return null;\n const abs = path.join(outputDir, relPath);\n if (escapesRoot(path.relative(outputDir, abs))) return null;\n try {\n if (escapesRoot(path.relative(fs.realpathSync(outputDir), fs.realpathSync(abs)))) return null;\n } catch {\n // The path does not exist yet; the lexical check above is sufficient and a\n // missing file is reported as drift downstream.\n }\n return abs;\n}\n\n// Treat any read failure (missing file, EISDIR, TOCTOU race, permissions) as an\n// absent file so the audit reports drift instead of crashing.\nfunction readHash(absFile: string, normalize?: (content: string) => string): string | null {\n try {\n const content = fs.readFileSync(absFile, \"utf-8\");\n return hashContent(normalize ? normalize(content) : content);\n } catch {\n return null;\n }\n}\n\nexport type CheckGitHubOptions = {\n /** Repository root where `.github` lives. */\n outputDir: string;\n /**\n * When true, run in CI mode: skip checks that are handled at runtime by\n * the deployed GitHub Actions (e.g. TAILOR_PLATFORM_WORKSPACE_ID presence).\n */\n ci?: boolean;\n /** Injectable git runner, for testing. */\n gitRunner?: GitRunner;\n /** Injectable config-existence probe, for testing. */\n configExistsAt?: (configPath: string) => boolean;\n /** Injectable TailorDB namespace loader, for testing. Defaults to loading the config. */\n loadErdNamespaces?: (configPath: string) => Promise<string[]> | string[];\n /** Injectable migration detector, for testing. Defaults to loading the config. */\n loadHasMigrations?: (configPath: string) => Promise<boolean> | boolean;\n /** Injectable seed plugin detector, for testing. Defaults to loading the config. */\n loadHasSeeds?: (configPath: string) => Promise<boolean> | boolean;\n /** Injectable static website detector, for testing. Defaults to loading the config. */\n loadHasStaticWebsites?: (configPath: string) => Promise<boolean> | boolean;\n};\n\nasync function defaultLoadErdNamespaces(configPath: string): Promise<string[]> {\n const { config } = await loadConfig(configPath);\n return extractOwnedNamespaces(config);\n}\n\nasync function defaultLoadHasMigrations(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return getNamespacesWithMigrations(config, path.dirname(configPath)).length > 0;\n}\n\nasync function defaultLoadHasSeeds(configPath: string): Promise<boolean> {\n const { plugins } = await loadConfig(configPath);\n return plugins.some((p) => p.id === \"@tailor-platform/seed\");\n}\n\nasync function defaultLoadHasStaticWebsites(configPath: string): Promise<boolean> {\n const { config } = await loadConfig(configPath);\n return (config.staticWebsites?.length ?? 0) > 0;\n}\n\n/**\n * Audit the generated workflows for drift against the current config/repo\n * state. Read-only: never writes files, the lock, or the config.\n *\n * Throws when drift is found (so it composes like the other `:check`\n * commands). The workflow drift-check step layers advisory behaviour on top\n * (per-rule ignore / continue-on-error); the CLI itself reports via exit code.\n * @param options - Check options\n */\nexport async function checkGitHub(options: CheckGitHubOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { outputDir } = options;\n const lock = readLock(outputDir);\n if (!lock || lock.targets.length === 0) {\n throw new Error(\n \"No managed workflows found (.github/tailor.lock is missing or empty). \" +\n \"Run `tailor setup branch` (or another setup subcommand) first.\",\n );\n }\n\n // In local (non-CI) mode, check that TAILOR_PLATFORM_WORKSPACE_ID is set for\n // targets that directly read vars.TAILOR_PLATFORM_WORKSPACE_ID: branch, tag,\n // and coordinate (coordinators pass it into each per-app deploy step).\n // Action targets (composite actions) receive workspace-id as a caller input and\n // never read vars.* themselves. Preview targets create per-PR workspaces and\n // don't reference TAILOR_PLATFORM_WORKSPACE_ID either.\n // In CI the plan/deploy actions handle this at runtime.\n if (!options.ci) {\n const needsWorkspaceId = lock.targets.some(\n (t) => t.kind === \"branch\" || t.kind === \"tag\" || t.kind === \"coordinate\",\n );\n if (needsWorkspaceId && !process.env[\"TAILOR_PLATFORM_WORKSPACE_ID\"]) {\n throw new Error(\n \"TAILOR_PLATFORM_WORKSPACE_ID is not set. \" +\n \"Provision the workspace and set the variable:\\n\" +\n \" tailor workspace create # if it does not exist yet; copy the id\\n\" +\n \" gh variable set TAILOR_PLATFORM_WORKSPACE_ID --env <environment>\",\n );\n }\n }\n\n const slackToken = Boolean(process.env[\"TAILOR_SLACK_BOT_TOKEN\"]);\n const slackChannelId = Boolean(process.env[\"TAILOR_SLACK_CHANNEL_ID\"]);\n if (slackToken !== slackChannelId) {\n throw new Error(\n `Slack is partially configured: ` +\n `${slackToken ? \"TAILOR_SLACK_BOT_TOKEN is set\" : \"TAILOR_SLACK_CHANNEL_ID is set\"} but not both. ` +\n \"TAILOR_SLACK_BOT_TOKEN (secret) and TAILOR_SLACK_CHANNEL_ID (variable) must be set together, \" +\n \"or neither should be set.\",\n );\n }\n\n const exists = options.configExistsAt ?? ((p: string) => fs.existsSync(p));\n const defaultBranch = detectDefaultBranchSafe(outputDir, options.gitRunner);\n const loadErdNamespaces = options.loadErdNamespaces ?? defaultLoadErdNamespaces;\n const loadHasMigrations = options.loadHasMigrations ?? defaultLoadHasMigrations;\n const loadHasSeeds = options.loadHasSeeds ?? defaultLoadHasSeeds;\n const loadHasStaticWebsites = options.loadHasStaticWebsites ?? defaultLoadHasStaticWebsites;\n\n const findings: DriftFinding[] = [];\n for (const target of lock.targets) {\n const absFile = resolveWithinRoot(outputDir, target.file);\n const currentHash =\n absFile === null\n ? null\n : readHash(absFile, target.kind === \"action\" ? normalizeActionContent : undefined);\n // Coordinator targets are config-less; skip the probe so config-dir drift is never emitted.\n const configAbs =\n target.kind === \"coordinate\"\n ? null\n : resolveWithinRoot(outputDir, path.join(target.inputs.dir, \"tailor.config.ts\"));\n const configExists = target.kind === \"coordinate\" || (configAbs !== null && exists(configAbs));\n const erdNamespaces =\n target.kind === \"branch\" && target.inputs.erdPreview && configAbs !== null && configExists\n ? await loadErdNamespaces(configAbs)\n : null;\n const hasMigrations =\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.migrationDriftCheck !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasMigrations(configAbs)\n : undefined;\n const hasSeeds =\n (target.kind === \"branch\" || target.kind === \"tag\") &&\n target.inputs.seedValidate !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasSeeds(configAbs)\n : undefined;\n const hasStaticWebsites =\n target.kind === \"action\" &&\n target.inputs.hasStaticWebsites !== undefined &&\n configAbs !== null &&\n configExists\n ? await loadHasStaticWebsites(configAbs)\n : undefined;\n findings.push(\n ...findTargetDrift(target, {\n fileExists: currentHash !== null,\n currentHash,\n configExists,\n defaultBranch,\n templateVersion: TEMPLATE_VERSION,\n erdNamespaces,\n hasMigrations,\n hasSeeds,\n hasStaticWebsites,\n }),\n );\n }\n\n const count = lock.targets.length;\n if (findings.length === 0) {\n logger.success(`No drift detected across ${String(count)} target(s).`);\n return;\n }\n\n for (const finding of findings) {\n logger.warn(`[${finding.target}] ${finding.message} (ignore key: ${finding.rule})`);\n }\n if (options.ci) {\n logger.log(`${DRIFT_COUNT_MARKER}=${String(findings.length)}`);\n }\n throw new Error(\n `Detected ${String(findings.length)} drift finding(s) across ${String(count)} target(s). ` +\n \"Re-run `tailor setup` to regenerate, or address each finding above.\",\n );\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { resolveWithinRoot } from \"./check\";\nimport { LOCK_VERSION, readLock, writeLock, type LockTarget } from \"./lock\";\n\nexport type DeleteOptions = {\n /** Repo-relative paths to managed workflow/action files, as printed by `setup <target>`. */\n files: string[];\n /** Skip the confirmation prompt. */\n yes: boolean;\n outputDir: string;\n};\n\n// Mirrors the --dir normalization in generate.ts's resolve(): POSIX separators,\n// collapsed duplicate slashes, no leading \"./\" or trailing \"/\", so a path typed\n// with either style still matches the posix-normalized `file` recorded in the lock.\nfunction normalizeRelPath(input: string): string {\n return input\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/{2,}/g, \"/\")\n .replace(/^\\.\\//, \"\")\n .replace(/\\/$/, \"\");\n}\n\ntype Match = { relPath: string; absPath: string; target: LockTarget };\n\nfunction targetKey(target: LockTarget): string {\n return `${target.kind}:${target.workspaceName}`;\n}\n\nfunction resolveMatch(outputDir: string, targets: readonly LockTarget[], input: string): Match {\n const relPath = normalizeRelPath(input);\n const absPath = resolveWithinRoot(outputDir, relPath);\n if (absPath === null) {\n throw new Error(`\"${input}\" must be a path inside the repository.`);\n }\n const target = targets.find((t) => t.file === relPath);\n if (!target) {\n throw new Error(\n `\"${relPath}\" is not a managed workflow/action file (not recorded in .github/tailor.lock). ` +\n \"Only files generated by `tailor setup` can be deleted with this command.\",\n );\n }\n return { relPath, absPath, target };\n}\n\n// Skips the warning when the referencing coordinator is also part of this\n// delete call, regardless of the order the files were passed in.\nfunction warnCoordinatorReferences(\n allTargets: readonly LockTarget[],\n deletedKeys: ReadonlySet<string>,\n match: Match,\n): void {\n if (match.target.kind !== \"action\") return;\n for (const coordinator of allTargets) {\n if (\n coordinator.kind === \"coordinate\" &&\n coordinator.inputs.actionDirs?.includes(match.target.inputs.dir) &&\n !deletedKeys.has(targetKey(coordinator))\n ) {\n logger.warn(\n `Coordinator \"${coordinator.workspaceName}\" still references this action's directory ` +\n `(${match.target.inputs.dir}). Remove \\`${match.target.workspaceName}\\` from the ` +\n `relevant \\`--action\\` value and re-run \\`tailor setup coordinate\\` to update it.`,\n );\n }\n }\n}\n\n/**\n * Delete managed workflow/action files and their `.github/tailor.lock` entries.\n *\n * Refuses to touch files that are not recorded in the lock, so it never\n * deletes hand-written workflows or the user-owned tailor-setup action.\n * @param options - Delete options\n */\nexport async function setupDelete(options: DeleteOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const { outputDir, yes } = options;\n const lock = readLock(outputDir);\n if (!lock || lock.targets.length === 0) {\n throw new Error(\n \"No managed workflows found (.github/tailor.lock is missing or empty). \" +\n \"Run `tailor setup branch` (or another setup subcommand) first.\",\n );\n }\n\n const relPaths = [...new Set(options.files.map(normalizeRelPath))];\n const matches = relPaths.map((relPath) => resolveMatch(outputDir, lock.targets, relPath));\n\n const deletedKeys = new Set(matches.map((m) => targetKey(m.target)));\n for (const match of matches) {\n warnCoordinatorReferences(lock.targets, deletedKeys, match);\n }\n\n if (!yes) {\n const list = matches.map((m) => m.relPath).join(\"\\n \");\n const confirmed = await prompt.confirm({\n message:\n `This will delete the following file(s) and their .github/tailor.lock entries:\\n ${list}\\n` +\n \"Continue?\",\n default: false,\n });\n if (!confirmed) {\n logger.info(\"Delete cancelled.\");\n return;\n }\n }\n\n const remaining = [...lock.targets];\n try {\n for (const { relPath, absPath, target } of matches) {\n fs.rmSync(absPath, { force: true });\n if (target.kind === \"action\") {\n const dir = path.dirname(absPath);\n if (fs.existsSync(dir) && fs.readdirSync(dir).length === 0) {\n fs.rmdirSync(dir);\n }\n }\n const index = remaining.findIndex((t) => targetKey(t) === targetKey(target));\n if (index !== -1) remaining.splice(index, 1);\n logger.success(`Deleted ${styles.path(relPath)} (${target.kind} ${target.workspaceName})`);\n }\n } finally {\n if (remaining.length !== lock.targets.length) {\n writeLock(outputDir, { version: LOCK_VERSION, targets: remaining });\n }\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { logger, styles } from \"#/cli/shared/logger\";\n\nexport const RENOVATE_CONFIG_FILE = \"renovate.json\";\nexport const RENOVATE_PRESET = \"github>tailor-inc/renovate-config\";\n\nconst RENOVATE_CONFIG_FILES = [\n RENOVATE_CONFIG_FILE,\n \"renovate.jsonc\",\n \"renovate.json5\",\n \".github/renovate.json\",\n \".github/renovate.jsonc\",\n \".github/renovate.json5\",\n \".gitlab/renovate.json\",\n \".gitlab/renovate.jsonc\",\n \".gitlab/renovate.json5\",\n \".renovaterc\",\n \".renovaterc.json\",\n \".renovaterc.jsonc\",\n \".renovaterc.json5\",\n] as const;\n\nexport type SetupRenovateOptions = {\n outputDir: string;\n};\n\nfunction getPathEntry(filePath: string): fs.Stats | null {\n try {\n return fs.lstatSync(filePath);\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nfunction pathEntryExists(filePath: string): boolean {\n return getPathEntry(filePath) !== null;\n}\n\ntype ExistingConfig =\n /** The config's `extends` already references the shared preset. */\n | { kind: \"extends-preset\"; location: string }\n /** Strict JSON, so the preset can be appended without losing comments. */\n | { kind: \"appendable\"; location: string; filePath: string; config: object }\n /** Not strict JSON, or not a regular file; the `extends` array is unknown. */\n | { kind: \"unreadable\"; location: string };\n\nfunction extendsPreset(config: object): boolean {\n if (!(\"extends\" in config)) return false;\n const value = config.extends;\n return Array.isArray(value) && value.includes(RENOVATE_PRESET);\n}\n\nfunction readJsonConfig(filePath: string): object | null {\n const entry = getPathEntry(filePath);\n if (entry === null || !entry.isFile()) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n } catch {\n return null;\n }\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed) ? parsed : null;\n}\n\nfunction classifyConfig(location: string, filePath: string, config: object | null): ExistingConfig {\n if (config === null) return { kind: \"unreadable\", location };\n if (extendsPreset(config)) return { kind: \"extends-preset\", location };\n return { kind: \"appendable\", location, filePath, config };\n}\n\nfunction findExistingConfig(outputDir: string): ExistingConfig | null {\n for (const file of RENOVATE_CONFIG_FILES) {\n const filePath = path.join(outputDir, file);\n if (!pathEntryExists(filePath)) continue;\n return classifyConfig(file, filePath, readJsonConfig(filePath));\n }\n\n const packageJsonPath = path.join(outputDir, \"package.json\");\n if (!fs.existsSync(packageJsonPath)) return null;\n let packageJson: unknown;\n try {\n packageJson = JSON.parse(fs.readFileSync(packageJsonPath, \"utf-8\"));\n } catch (cause) {\n throw new Error(\"package.json is not valid JSON; could not inspect its Renovate config.\", {\n cause,\n });\n }\n if (typeof packageJson === \"object\" && packageJson !== null && \"renovate\" in packageJson) {\n const renovate = packageJson.renovate;\n const config =\n typeof renovate === \"object\" && renovate !== null && !Array.isArray(renovate)\n ? renovate\n : null;\n return classifyConfig(\"package.json#renovate\", packageJsonPath, config);\n }\n return null;\n}\n\nfunction detectIndent(source: string): number {\n return /^(?<indent>[ ]+)\"/m.exec(source)?.groups?.indent?.length ?? 2;\n}\n\nfunction appendPreset(existing: Extract<ExistingConfig, { kind: \"appendable\" }>): void {\n const source = fs.readFileSync(existing.filePath, \"utf-8\");\n const current = \"extends\" in existing.config ? existing.config.extends : undefined;\n if (current !== undefined && !Array.isArray(current)) {\n throw new Error(\n `Renovate config at \"${existing.location}\" has a non-array \"extends\". No files were changed. ` +\n `Add \"${RENOVATE_PRESET}\" to it manually.`,\n );\n }\n const config = { ...existing.config, extends: [...(current ?? []), RENOVATE_PRESET] };\n\n const root =\n existing.location === \"package.json#renovate\"\n ? { ...(JSON.parse(source) as Record<string, unknown>), renovate: config }\n : config;\n\n const trailingNewline = source.endsWith(\"\\n\") ? \"\\n\" : \"\";\n fs.writeFileSync(\n existing.filePath,\n `${JSON.stringify(root, null, detectIndent(source))}${trailingNewline}`,\n \"utf-8\",\n );\n}\n\nfunction renderRenovateConfig(): string {\n return `${JSON.stringify(\n {\n $schema: \"https://docs.renovatebot.com/renovate-schema.json\",\n extends: [RENOVATE_PRESET],\n },\n null,\n 2,\n )}\\n`;\n}\n\n/**\n * Generate a repository-level Renovate config that extends Tailor's shared preset.\n * @param options - Renovate setup options\n */\nexport async function setupRenovate(options: SetupRenovateOptions): Promise<void> {\n logBetaWarning(\"setup\");\n\n const existingConfig = findExistingConfig(options.outputDir);\n if (existingConfig !== null) {\n if (existingConfig.kind === \"extends-preset\") {\n logger.info(`Renovate is already set up at ${styles.path(existingConfig.location)}.`);\n return;\n }\n if (existingConfig.kind === \"unreadable\") {\n throw new Error(\n `Found a Renovate config at \"${existingConfig.location}\" but could not parse it as JSON. ` +\n `Comment-containing JSON5/JSONC configs are not supported yet. No files were changed. ` +\n `Check its extends array for \"${RENOVATE_PRESET}\" manually.`,\n );\n }\n appendPreset(existingConfig);\n logger.success(`Added the Tailor preset to ${styles.path(existingConfig.location)}`);\n return;\n }\n\n const outputPath = path.join(options.outputDir, RENOVATE_CONFIG_FILE);\n fs.writeFileSync(outputPath, renderRenovateConfig(), \"utf-8\");\n\n logger.success(`Generated ${styles.path(RENOVATE_CONFIG_FILE)}`);\n}\n","import { arg, defineCommand } from \"politty\";\nimport { z } from \"zod\";\nimport { confirmationArgs } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { checkGitHub } from \"./check\";\nimport { setupDelete } from \"./delete\";\nimport { setupCoordinate, setupTarget } from \"./generate\";\nimport { setupRenovate } from \"./renovate\";\n\nconst checkCommand = defineAppCommand({\n name: \"check\",\n description: \"Audit generated workflows for drift against the current config/repo (read-only).\",\n args: z.strictObject({\n ci: arg(z.boolean().default(false), {\n description:\n \"Run in CI mode: skip checks that are handled by the runtime \" +\n \"(e.g. TAILOR_PLATFORM_WORKSPACE_ID).\",\n }),\n }),\n run: async (args) => {\n await checkGitHub({ outputDir: process.cwd(), ci: args.ci });\n },\n});\n\nconst coordinateCommand = defineAppCommand({\n name: \"coordinate\",\n description:\n \"Generate a coordinator workflow that orchestrates multiple --action-generated composite actions.\",\n args: z.strictObject({\n name: arg(z.string().min(1), {\n alias: \"n\",\n description: \"Coordinator name (used in the generated workflow file name and job names)\",\n }),\n action: arg(z.array(z.string().min(1)).min(1), {\n description:\n \"Composite action to include. Repeat for separate deploy steps, or use commas to deploy actions as one multi-config group. tailor- prefix optional.\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Branch target: deploy trigger branch (defaults to the detected default branch)\",\n }),\n tag: arg(z.boolean().default(false), {\n description: \"Generate a tag target coordinator\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits and regenerate\",\n }),\n }),\n run: async (args) => {\n const coordinateKind = args.tag ? \"tag\" : \"branch\";\n await setupCoordinate({\n coordinatorName: args.name,\n coordinateKind,\n actions: args.action,\n branch: args.branch,\n environment: args.environment,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst actionCommand = defineAppCommand({\n name: \"action\",\n description:\n \"Generate a per-app composite action for use with setup coordinate (monorepo multi-app deploys).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment (defaults to the workspace name)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"action\",\n workspaceName: args.name,\n dir: args.dir,\n environment: args.environment,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst branchCommand = defineAppCommand({\n name: \"branch\",\n description: \"Generate a branch-target deploy workflow (push to branch triggers deploy).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Deploy trigger branch (defaults to the detected default branch)\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs (defaults to the workspace name)\",\n }),\n \"erd-preview\": arg(z.boolean().default(false), {\n description: \"Add PR ERD viewer artifacts with current/diff previews for TailorDB namespaces\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"branch\",\n workspaceName: args.name,\n branch: args.branch,\n environment: args.environment,\n erdPreview: args[\"erd-preview\"],\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst tagCommand = defineAppCommand({\n name: \"tag\",\n description: \"Generate a tag-target deploy workflow (tag push triggers deploy).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n \"tag-pattern\": arg(z.string().min(1).default(\"v*\"), {\n description: \"Tag glob to match (defaults to v*)\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Tag-reachability guard branch (no guard when omitted)\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the plan/deploy jobs (defaults to the workspace name)\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"tag\",\n workspaceName: args.name,\n tagPattern: args[\"tag-pattern\"],\n branch: args.branch,\n environment: args.environment,\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst previewCommand = defineAppCommand({\n name: \"preview\",\n description: \"Generate a preview workflow (PR open/sync triggers deploy to a per-PR workspace).\",\n args: z.strictObject({\n name: arg(z.string().min(1).optional(), {\n alias: \"n\",\n description: \"Name (defaults to the config 'name')\",\n }),\n branch: arg(z.string().min(1).optional(), {\n description: \"Branch to filter PRs by (defaults to the detected default branch)\",\n }),\n region: arg(z.string().min(1), {\n description: \"Workspace region for preview workspace creation (e.g. us-west). Required.\",\n }),\n \"require-preview-label\": arg(z.boolean().default(false), {\n description: \"Deploy preview only for PRs labeled `tailor:preview` instead of all PRs.\",\n }),\n environment: arg(z.string().min(1).optional(), {\n description: \"GitHub Environment for the preview jobs (defaults to the workspace name)\",\n }),\n dir: arg(z.string().min(1).default(\".\"), {\n alias: \"d\",\n description: \"App directory (for monorepo setups)\",\n }),\n force: arg(z.boolean().default(false), {\n description: \"Discard hand edits / take over unmanaged files and regenerate\",\n }),\n }),\n run: async (args) => {\n await setupTarget({\n kind: \"preview\",\n workspaceName: args.name,\n branch: args.branch,\n region: args.region,\n requirePreviewLabel: args[\"require-preview-label\"],\n environment: args.environment,\n dir: args.dir,\n force: args.force,\n outputDir: process.cwd(),\n });\n },\n});\n\nconst renovateCommand = defineAppCommand({\n name: \"renovate\",\n description: \"Generate a Renovate config for Tailor dependency and workflow updates.\",\n args: z.strictObject({}),\n run: async () => {\n await setupRenovate({ outputDir: process.cwd() });\n },\n});\n\nconst deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete managed workflow/action file(s) and their .github/tailor.lock entries.\",\n args: z.strictObject({\n ...confirmationArgs,\n files: arg(z.string().array().min(1), {\n positional: true,\n description:\n \"Workflow/action file(s) to delete, as generated under .github/workflows or .github/actions\",\n }),\n }),\n run: async (args) => {\n await setupDelete({ files: args.files, yes: args.yes, outputDir: process.cwd() });\n },\n});\n\nexport const setupCommand = defineCommand({\n name: \"setup\",\n description: \"Set up repository automation for your project. (beta)\",\n subCommands: {\n branch: branchCommand,\n tag: tagCommand,\n preview: previewCommand,\n action: actionCommand,\n coordinate: coordinateCommand,\n renovate: renovateCommand,\n check: checkCommand,\n delete: deleteCommand,\n },\n});\n","import { CustomDomainStatus } from \"@tailor-platform/tailor-proto/staticwebsite_resource_pb\";\n\nexport const statusLabels: Record<CustomDomainStatus, string> = {\n [CustomDomainStatus.UNSPECIFIED]: \"unspecified\",\n [CustomDomainStatus.PENDING]: \"pending\",\n [CustomDomainStatus.VERIFYING]: \"verifying\",\n [CustomDomainStatus.CERT_ISSUED]: \"cert_issued\",\n [CustomDomainStatus.ACTIVE]: \"active\",\n [CustomDomainStatus.FAILED]: \"failed\",\n};\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { statusLabels } from \"./status\";\n\nexport const domainGetCommand = defineAppCommand({\n name: \"get\",\n description: \"Get details of a custom domain.\",\n args: z.strictObject({\n ...workspaceArgs,\n domain: arg(z.string(), {\n positional: true,\n description: \"Custom domain name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const notFoundErrorMessage = `Custom domain \"${args.domain}\" not found.`;\n\n try {\n const { customDomain } = await client.getCustomDomain({\n workspaceId,\n domain: args.domain,\n });\n\n if (!customDomain) {\n throw new Error(notFoundErrorMessage);\n }\n\n const info = {\n domain: customDomain.domain,\n // platform may return enum values newer than this SDK\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n status: statusLabels[customDomain.status] ?? \"unknown\",\n trafficCnameTarget: customDomain.trafficCnameTarget,\n certificateCnameTarget: customDomain.certificateCnameTarget,\n errorMessage: customDomain.errorMessage || undefined,\n };\n\n logger.out(info);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(notFoundErrorMessage, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { statusLabels } from \"./status\";\n\nexport const domainListCommand = defineAppCommand({\n name: \"list\",\n description: \"List custom domains for a static website.\",\n args: z.strictObject({\n ...workspaceArgs,\n name: arg(z.string(), {\n positional: true,\n description: \"Static website name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n try {\n const { customDomains } = await client.listCustomDomains({\n workspaceId,\n staticWebsiteName: args.name,\n });\n\n if (customDomains.length === 0) {\n logger.info(\"No custom domains found.\");\n return;\n }\n\n const formatted = customDomains.map((d) => ({\n domain: d.domain,\n // platform may return enum values newer than this SDK\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n status: statusLabels[d.status] ?? \"unknown\",\n trafficCnameTarget: d.trafficCnameTarget,\n certificateCnameTarget: d.certificateCnameTarget,\n }));\n\n logger.out(formatted);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(`Static website \"${args.name}\" not found.`, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { defineCommand } from \"politty\";\nimport { domainGetCommand } from \"./get\";\nimport { domainListCommand } from \"./list\";\n\nexport const domainCommand = defineCommand({\n name: \"domain\",\n description: \"Manage custom domains for static websites.\",\n subCommands: {\n list: domainListCommand,\n get: domainGetCommand,\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const getCommand = defineAppCommand({\n name: \"get\",\n description: \"Get details of a specific static website.\",\n args: z.strictObject({\n ...workspaceArgs,\n name: arg(z.string(), {\n positional: true,\n description: \"Static website name\",\n }),\n }),\n run: async (args) => {\n const accessToken = await loadAccessToken({\n profile: args.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n\n const notFoundErrorMessage = `Static website \"${args.name}\" not found.`;\n\n try {\n const { staticwebsite } = await client.getStaticWebsite({\n workspaceId,\n name: args.name,\n });\n\n if (!staticwebsite) {\n throw new Error(notFoundErrorMessage);\n }\n\n const info = {\n workspaceId,\n name: staticwebsite.name,\n description: staticwebsite.description,\n url: staticwebsite.url,\n allowedIpAddresses: args.json\n ? staticwebsite.allowedIpAddresses\n : staticwebsite.allowedIpAddresses.join(\"\\n\"),\n };\n\n logger.out(info);\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(notFoundErrorMessage, { cause: error });\n }\n throw error;\n }\n },\n});\n","import { z } from \"zod\";\nimport { type Order, paginationArgs, toPageDirection, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged, initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport interface StaticWebsiteInfo {\n workspaceId: string;\n name: string;\n description: string;\n url: string;\n allowedIpAddresses: string[];\n}\n\ntype StaticWebsiteListOptions = {\n workspaceId?: string;\n profile?: string;\n order?: Order;\n limit?: number;\n};\n\n/**\n * List static websites in the workspace.\n * @param options - Static website listing options\n * @returns List of static websites\n */\nasync function listStaticWebsites(\n options?: StaticWebsiteListOptions,\n): Promise<StaticWebsiteInfo[]> {\n const accessToken = await loadAccessToken({\n profile: options?.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options?.workspaceId,\n profile: options?.profile,\n });\n\n const pageDirection = toPageDirection(options?.order);\n const websites = await fetchPaged(\n async (pageToken, pageSize) => {\n const { staticwebsites, nextPageToken } = await client.listStaticWebsites({\n workspaceId,\n pageToken,\n pageSize,\n pageDirection,\n });\n return [staticwebsites, nextPageToken];\n },\n { limit: options?.limit },\n );\n\n return websites.map((site) => ({\n workspaceId,\n name: site.name,\n description: site.description,\n url: site.url,\n allowedIpAddresses: site.allowedIpAddresses,\n }));\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all static websites in a workspace.\",\n args: z.strictObject({\n ...workspaceArgs,\n ...paginationArgs(),\n }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const websites = await listStaticWebsites({\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n order: args.order,\n limit: args.limit,\n });\n\n const formatted = jsonOutput\n ? websites\n : websites.map(({ allowedIpAddresses, ...rest }) => {\n if (allowedIpAddresses.length === 0) {\n return {\n ...rest,\n allowedIpAddresses: \"No allowed IP addresses\",\n };\n }\n\n const count = allowedIpAddresses.length;\n const label = count === 1 ? \"1 IP address\" : `${count} IP addresses`;\n\n return {\n ...rest,\n allowedIpAddresses: label,\n };\n });\n\n logger.out(formatted);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { deployCommand } from \"./deploy\";\nimport { domainCommand } from \"./domain\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\n\nexport const staticwebsiteCommand = defineCommand({\n name: \"staticwebsite\",\n description: \"Manage static websites in your workspace.\",\n subCommands: {\n deploy: deployCommand,\n domain: domainCommand,\n list: listCommand,\n get: getCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import * as fs from \"node:fs\";\nimport * as fsPromises from \"node:fs/promises\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn } from \"#/cli/commands/deploy/label\";\nimport { updateMigrationLabel } from \"#/cli/commands/deploy/tailordb/migration\";\nimport { loadFilesWithIgnores } from \"#/cli/services/file-loader\";\nimport { confirmationArgs, deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { formatNextAction } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { PluginManager } from \"#/plugin/manager\";\nimport { getNamespacesWithMigrations, selectTargetNamespace } from \"./config\";\nimport { formatMigrationDiff, hasChanges } from \"./diff-calculator\";\nimport { captureFileState, captureMigrationFileState } from \"./file-state\";\nimport { fetchRemoteMigrationState } from \"./remote-state\";\nimport {\n formatRemoteVerificationResults,\n toTailorDBDeployInput,\n verifyRemoteSchema,\n} from \"./schema-checks\";\nimport {\n assertValidMigrationFiles,\n compareLocalTypesWithSnapshot,\n createSnapshotFromLocalTypes,\n formatMigrationNumber,\n getLatestMigrationNumber,\n loadSnapshot,\n MIGRATION_FILE_NAMES,\n MIGRATION_NUMBER_PATTERN,\n reconstructSnapshotFromMigrations,\n SCHEMA_SNAPSHOT_VERSION,\n type NormalizedSchemaSnapshot,\n type RebaselineMarker,\n} from \"./snapshot\";\nimport { generateSchemaFile } from \"./template-generator\";\nimport { createMigrationHistoryId } from \"./types\";\n\nexport interface RebaselineOptions {\n configPath?: string;\n namespace?: string;\n yes?: boolean;\n workspaceId?: string;\n profile?: string;\n}\n\nconst MIGRATION_ARTIFACT_NAMES = new Set(Object.values(MIGRATION_FILE_NAMES));\n\nasync function activateBaseline(\n migrationsDir: string,\n snapshot: NormalizedSchemaSnapshot,\n namespace: string,\n rebaseline: RebaselineMarker,\n): Promise<void> {\n const resolvedMigrationsDir = await fsPromises.realpath(migrationsDir);\n const parentDir = path.dirname(resolvedMigrationsDir);\n const baseName = path.basename(resolvedMigrationsDir);\n const stagingDir = await fsPromises.mkdtemp(path.join(parentDir, `.${baseName}-rebaseline-`));\n const backupDir = `${stagingDir}-previous`;\n let movedLiveDirectory = false;\n let activatedStagingDirectory = false;\n\n try {\n await fsPromises.cp(resolvedMigrationsDir, stagingDir, { recursive: true });\n for (const entry of await fsPromises.readdir(stagingDir, { withFileTypes: true })) {\n if (!entry.isDirectory() || !MIGRATION_NUMBER_PATTERN.test(entry.name)) continue;\n const entryPath = path.join(stagingDir, entry.name);\n const childNames = await fsPromises.readdir(entryPath);\n if (!childNames.some((childName) => MIGRATION_ARTIFACT_NAMES.has(childName))) continue;\n await fsPromises.rm(entryPath, { recursive: true, force: true });\n }\n const stagedSnapshot = {\n ...snapshot,\n namespace,\n version: SCHEMA_SNAPSHOT_VERSION,\n createdAt: new Date().toISOString(),\n rebaseline,\n };\n const result = await generateSchemaFile(stagedSnapshot, stagingDir, 0);\n loadSnapshot(result.filePath);\n\n await fsPromises.rename(resolvedMigrationsDir, backupDir);\n movedLiveDirectory = true;\n try {\n await fsPromises.rename(stagingDir, resolvedMigrationsDir);\n activatedStagingDirectory = true;\n } catch (error) {\n await fsPromises.rename(backupDir, resolvedMigrationsDir);\n movedLiveDirectory = false;\n throw error;\n }\n\n try {\n await fsPromises.rm(backupDir, { recursive: true, force: true });\n } catch (error) {\n logger.warn(\n `The previous migration directory remains at ${backupDir}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n movedLiveDirectory = false;\n } finally {\n if (fs.existsSync(stagingDir)) {\n await fsPromises.rm(stagingDir, { recursive: true, force: true });\n }\n if (!activatedStagingDirectory && movedLiveDirectory && fs.existsSync(backupDir)) {\n await fsPromises.rename(backupDir, resolvedMigrationsDir);\n }\n }\n}\n\nasync function rebaseline(options: RebaselineOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const loaded = await loadConfig(options.configPath);\n const { config, plugins } = loaded;\n const configDir = path.dirname(config.path);\n const target = selectTargetNamespace(\n getNamespacesWithMigrations(config, configDir),\n options.namespace,\n );\n const generateCommand = formatNextAction({\n command: \"tailor\",\n args: [\"tailordb\", \"migration\", \"generate\", \"--config\", config.path],\n });\n\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n const latestSnapshot = reconstructSnapshotFromMigrations(target.migrationsDir);\n if (!latestSnapshot) {\n throw new Error(\n `No migration history found for namespace \"${target.namespace}\". Run ${generateCommand} first.`,\n );\n }\n const latestMigration = getLatestMigrationNumber(target.migrationsDir);\n const currentHistoryId =\n reconstructSnapshotFromMigrations(target.migrationsDir, 0)?.rebaseline?.historyId ?? null;\n const initialFileState = captureMigrationFileState([target])[target.namespace];\n\n const pluginManager = plugins.length > 0 ? new PluginManager(plugins) : undefined;\n const { defineApplication } = await import(\"#/cli/services/application\");\n const application = defineApplication({ config, pluginManager });\n for (const service of application.tailorDBServices) {\n await service.loadTypes();\n await service.processNamespacePlugins();\n }\n const targetService = application.tailorDBServices.find(\n (service) => service.namespace === target.namespace,\n );\n if (!targetService) {\n throw new Error(`No TailorDB service found for namespace \"${target.namespace}\"`);\n }\n\n const assertLocalTypesReady = (): void => {\n const currentSnapshot = createSnapshotFromLocalTypes(targetService.types, target.namespace);\n const localDiff = compareLocalTypesWithSnapshot(\n latestSnapshot,\n currentSnapshot.tables,\n target.namespace,\n );\n if (hasChanges(localDiff)) {\n logger.error(\n `Migration history does not reproduce the current local schema for namespace ${styles.bold(target.namespace)}:`,\n );\n logger.log(formatMigrationDiff(localDiff));\n throw new Error(\n `Refusing to re-baseline: the migration history must reproduce the current local schema. Run ${generateCommand} first.`,\n );\n }\n };\n const localSourceFiles = (): string[] => [\n config.path,\n ...loadFilesWithIgnores(targetService.config, configDir),\n ];\n assertLocalTypesReady();\n const initialLocalFileState = captureFileState(localSourceFiles());\n\n const accessToken = await loadAccessToken({ profile: options.profile });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n const remoteContextArgs = [\n \"--config\",\n config.path,\n \"--workspace-id\",\n workspaceId,\n ...(options.profile ? [\"--profile\", options.profile] : []),\n ];\n const setBaselineCommand = formatNextAction({\n command: \"tailor\",\n args: [\n \"tailordb\",\n \"migration\",\n \"set\",\n \"0\",\n \"--namespace\",\n target.namespace,\n ...remoteContextArgs,\n ],\n });\n const deployCommand = formatNextAction({\n command: \"tailor\",\n args: [\"deploy\", ...remoteContextArgs],\n });\n\n const assertConnectedWorkspaceReady = async (\n expectedHistoryId: string | null,\n phase: \"initial\" | \"confirmation\",\n ): Promise<void> => {\n const remoteState = await fetchRemoteMigrationState(\n client,\n resourceTrn(workspaceId, \"tailordb\", target.namespace),\n );\n const remoteMigration = remoteState.number;\n if (remoteMigration !== latestMigration) {\n const actual = remoteMigration === null ? \"<unset>\" : formatMigrationNumber(remoteMigration);\n throw new Error(\n `The connected workspace must be at the latest migration ${formatMigrationNumber(latestMigration)} before re-baselining; current checkpoint is ${actual}.`,\n );\n }\n if (remoteState.historyIdInvalid) {\n throw new Error(\n \"Refusing to re-baseline: the connected workspace has an invalid migration history marker.\",\n );\n }\n if (remoteState.historyId !== expectedHistoryId) {\n throw new Error(\n phase === \"confirmation\"\n ? \"The connected workspace migration history changed while waiting for confirmation. Run the command again.\"\n : \"Refusing to re-baseline: the connected workspace does not match the local migration history.\",\n );\n }\n\n const remoteResults = await verifyRemoteSchema(client, workspaceId, [target], config, [\n toTailorDBDeployInput(targetService),\n ]);\n const remoteResult = remoteResults[0];\n if (\n !remoteResult ||\n remoteResult.remoteMigrationNumber !== latestMigration ||\n remoteResult.hasDrift ||\n remoteResult.checkpointMissingLocal\n ) {\n if (remoteResult?.hasDrift) {\n logger.error(\"Remote schema drift detected:\");\n logger.log(formatRemoteVerificationResults(remoteResults));\n }\n throw new Error(\n \"Refusing to re-baseline: the connected workspace remote schema must match the latest migration.\",\n );\n }\n };\n\n await assertConnectedWorkspaceReady(currentHistoryId, \"initial\");\n\n logger.newline();\n logger.warn(`This will replace the migration history for ${styles.bold(target.namespace)}.`);\n logger.log(` Latest migration: ${formatMigrationNumber(latestMigration)}`);\n logger.log(\" New history: 0000/schema.json only\");\n logger.log(\" migrate.ts and db.ts files will disappear from the working tree.\");\n logger.log(\n \" Committed migration files will remain in Git history. Preserve any uncommitted files before continuing.\",\n );\n logger.log(\" Every other environment must already be at the latest migration.\");\n logger.log(\" The connected workspace checkpoint will be reset to 0000.\");\n logger.newline();\n\n if (!options.yes) {\n const confirmed = await prompt.confirm({\n message: \"Re-baseline this migration history and reset the connected workspace checkpoint?\",\n default: false,\n });\n if (!confirmed) {\n logger.info(\"Operation cancelled.\");\n return;\n }\n }\n\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n const currentFileState = captureMigrationFileState([target])[target.namespace];\n if (currentFileState !== initialFileState) {\n throw new Error(\n \"Migration files changed while waiting for confirmation. Run the command again.\",\n );\n }\n if (captureFileState(localSourceFiles()) !== initialLocalFileState) {\n throw new Error(\"Local TailorDB type or config files changed. Run the command again.\");\n }\n assertLocalTypesReady();\n await assertConnectedWorkspaceReady(currentHistoryId, \"confirmation\");\n\n const rebaselineMarker: RebaselineMarker = {\n historyId: createMigrationHistoryId(),\n replacedHistoryId: currentHistoryId,\n replacedLatestMigration: latestMigration,\n };\n await activateBaseline(target.migrationsDir, latestSnapshot, target.namespace, rebaselineMarker);\n try {\n await updateMigrationLabel(\n client,\n workspaceId,\n target.namespace,\n 0,\n rebaselineMarker.historyId,\n );\n } catch (error) {\n throw new Error(\n `The local migration history was re-baselined, but the connected workspace checkpoint could not be updated. Run ${setBaselineCommand}, or run ${deployCommand} with schema checks enabled after resolving the connection error.`,\n { cause: error },\n );\n }\n\n logger.success(\n `Re-baselined ${styles.bold(target.namespace)} and reset the connected workspace checkpoint to 0000.`,\n );\n}\n\nexport const rebaselineCommand = defineAppCommand({\n name: \"rebaseline\",\n description: \"Collapse the full migration history into a new 0000 baseline.\",\n notes: `Re-baselining removes migrations after 0000 from the working tree, records a new migration history ID, and resets the connected workspace checkpoint without changing its schema or data. Every environment must already have applied the latest migration before you run this command.`,\n args: z.strictObject({\n ...deploymentArgs,\n ...confirmationArgs,\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await rebaseline({\n configPath: args.config,\n namespace: args.namespace,\n yes: args.yes,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n },\n});\n","import * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn, writeMetadataLabels } from \"#/cli/commands/deploy/label\";\nimport { confirmationArgs, deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getNamespacesWithMigrations, selectTargetNamespace } from \"./config\";\nimport { parseMigrationNumberArg } from \"./migration-number\";\nimport { fetchRemoteMigrationState } from \"./remote-state\";\nimport {\n assertMigrationNumberExists,\n assertValidMigrationFiles,\n formatMigrationNumber,\n reconstructSnapshotFromMigrations,\n} from \"./snapshot\";\nimport { MIGRATION_HISTORY_LABEL_KEY, MIGRATION_LABEL_KEY, sanitizeMigrationLabel } from \"./types\";\n\nexport interface SetOptions {\n configPath?: string;\n number: string;\n namespace?: string;\n yes?: boolean;\n workspaceId?: string;\n profile?: string;\n}\n\n/**\n * Set migration checkpoint for a TailorDB namespace\n * @param {SetOptions} options - Command options\n */\nasync function set(options: SetOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n // 1. Validate migration number format\n const migrationNumber = parseMigrationNumberArg(options.number);\n\n // 2. Load configuration\n const { config } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n // 3. Determine target namespace\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n const target = selectTargetNamespace(namespacesWithMigrations, options.namespace);\n const targetNamespace = target.namespace;\n\n // 4. Validate the local migration history and the requested number\n assertValidMigrationFiles(target.migrationsDir, targetNamespace);\n assertMigrationNumberExists(target.migrationsDir, migrationNumber);\n const historyId = reconstructSnapshotFromMigrations(target.migrationsDir, 0)?.rebaseline\n ?.historyId;\n\n // 5. Initialize client\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n // 6. Get current migration state\n const trn = resourceTrn(workspaceId, \"tailordb\", targetNamespace);\n const currentState = await fetchRemoteMigrationState(client, trn);\n const current = currentState.number;\n const currentMigration = current ?? 0;\n const currentHistoryId = currentState.historyIdInvalid\n ? \"<invalid>\"\n : (currentState.historyId ?? \"<unset>\");\n const newHistoryId = historyId ?? \"<unset>\";\n\n // 7. Display warning and confirmation\n logger.newline();\n logger.warn(\"This operation will change TailorDB migration state metadata.\");\n logger.log(`Namespace: ${styles.bold(targetNamespace)}`);\n logger.log(\n `Current migration: ${current === null ? \"<unset>\" : styles.bold(formatMigrationNumber(current))}`,\n );\n logger.log(`New migration: ${styles.bold(formatMigrationNumber(migrationNumber))}`);\n logger.log(`Current migration history ID: ${styles.bold(currentHistoryId)}`);\n logger.log(`New migration history ID: ${styles.bold(newHistoryId)}`);\n logger.newline();\n\n if (migrationNumber < currentMigration) {\n logger.warn(\n `Setting migration number backwards (${formatMigrationNumber(currentMigration)} → ${formatMigrationNumber(migrationNumber)}) will cause previous migrations to be re-executed on next apply.`,\n );\n logger.newline();\n } else if (migrationNumber > currentMigration) {\n logger.warn(\n `Setting migration number forwards (${formatMigrationNumber(currentMigration)} → ${formatMigrationNumber(migrationNumber)}) will skip migrations ${formatMigrationNumber(currentMigration + 1)} to ${formatMigrationNumber(migrationNumber)}.`,\n );\n logger.newline();\n }\n\n // 8. Confirmation prompt (unless --yes flag)\n if (!options.yes) {\n const confirmation = await prompt.confirm({\n message: \"Continue with migration checkpoint and history ID update?\",\n default: false,\n });\n\n if (!confirmation) {\n logger.info(\"Operation cancelled.\");\n return;\n }\n logger.newline();\n }\n\n // 9. Update migration label\n await writeMetadataLabels(client, {\n trn,\n labels: {\n [MIGRATION_LABEL_KEY]: sanitizeMigrationLabel(migrationNumber),\n ...(historyId ? { [MIGRATION_HISTORY_LABEL_KEY]: historyId } : {}),\n },\n remove: historyId ? undefined : [MIGRATION_HISTORY_LABEL_KEY],\n });\n\n logger.success(\n `Migration checkpoint set to ${styles.bold(formatMigrationNumber(migrationNumber))} for namespace ${styles.bold(targetNamespace)}`,\n );\n}\n\nexport const setCommand = defineAppCommand({\n name: \"set\",\n description: \"Set migration checkpoint to a specific number.\",\n notes: `The migration number must be a 4-digit value (e.g. \\`0001\\`) or a bare integer (e.g. \\`1\\`) within 0–9999, and must exist in the local migration history; \\`0\\` is always accepted as the baseline, provided the local history passes validation. A gapped history is rejected.\n\nMetadata lookup failures (authentication, permission, or network errors) are reported as errors; only a not-yet-deployed namespace is treated as having no checkpoint.`,\n args: z.strictObject({\n ...deploymentArgs,\n ...confirmationArgs,\n number: arg(z.string(), {\n positional: true,\n description: \"Migration number to set (e.g., 0001 or 1)\",\n }),\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await set({\n configPath: args.config,\n number: args.number,\n namespace: args.namespace,\n yes: args.yes,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n },\n});\n","import * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn } from \"#/cli/commands/deploy/label\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { getNamespacesWithMigrations } from \"./config\";\nimport { fetchRemoteMigrationState } from \"./remote-state\";\nimport {\n getMigrationFiles,\n loadDiff,\n loadSnapshot,\n formatMigrationNumber,\n UnsupportedMigrationFileVersionError,\n} from \"./snapshot\";\n\nexport interface StatusOptions {\n configPath?: string;\n namespace?: string;\n workspaceId?: string;\n profile?: string;\n json?: boolean;\n}\n\ninterface PendingMigrationStatusInfo {\n number: number;\n label: string;\n description?: string;\n}\n\ninterface MigrationStatusInfo {\n status: \"ok\";\n namespace: string;\n currentMigration: number;\n currentMigrationLabel: string;\n pendingMigrations: PendingMigrationStatusInfo[];\n}\n\ninterface MigrationStatusFailure {\n status: \"error\";\n namespace: string;\n error: string;\n}\n\ntype MigrationStatusRow = MigrationStatusInfo | MigrationStatusFailure;\n\nfunction isStatusFailure(row: MigrationStatusRow): row is MigrationStatusFailure {\n return row.status === \"error\";\n}\n\nasync function collectMigrationStatuses(options: StatusOptions): Promise<MigrationStatusRow[]> {\n const { config } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n\n if (namespacesWithMigrations.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found\");\n }\n\n const targetNamespaces = options.namespace\n ? namespacesWithMigrations.filter((ns) => ns.namespace === options.namespace)\n : namespacesWithMigrations;\n\n if (targetNamespaces.length === 0) {\n throw new Error(\n `Namespace \"${options.namespace}\" not found or does not have migrations configured`,\n );\n }\n\n const localStates = new Map<\n string,\n {\n migrationFiles: ReturnType<typeof getMigrationFiles>;\n descriptions: Map<number, string>;\n historyId: string | null;\n }\n >();\n const localFailures = new Map<string, string>();\n\n for (const { namespace, migrationsDir } of targetNamespaces) {\n try {\n const migrationFiles = getMigrationFiles(migrationsDir);\n const descriptions = new Map<number, string>();\n let historyId: string | null = null;\n for (const file of migrationFiles) {\n if (file.type === \"schema\") {\n const snapshot = loadSnapshot(file.path);\n if (file.number === 0) {\n historyId = snapshot.rebaseline?.historyId ?? null;\n }\n continue;\n }\n try {\n const diff = loadDiff(file.path);\n if (diff.description) descriptions.set(file.number, diff.description);\n } catch (error) {\n if (error instanceof UnsupportedMigrationFileVersionError) throw error;\n // A malformed optional description must not hide migration status.\n }\n }\n localStates.set(namespace, { migrationFiles, descriptions, historyId });\n } catch (error) {\n localFailures.set(namespace, error instanceof Error ? error.message : String(error));\n }\n }\n\n if (localStates.size === 0) {\n return targetNamespaces.map(({ namespace }) => ({\n status: \"error\",\n namespace,\n error: localFailures.get(namespace) ?? \"Failed to read local migration history.\",\n }));\n }\n\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const rows: MigrationStatusRow[] = [];\n\n for (const { namespace } of targetNamespaces) {\n if (localFailures.has(namespace)) {\n rows.push({\n status: \"error\",\n namespace,\n error: localFailures.get(namespace) ?? \"Failed to read local migration history.\",\n });\n continue;\n }\n const localState = localStates.get(namespace);\n if (!localState) {\n rows.push({\n status: \"error\",\n namespace,\n error: \"Failed to read local migration history.\",\n });\n continue;\n }\n const { migrationFiles, descriptions, historyId: localHistoryId } = localState;\n\n const trn = resourceTrn(workspaceId, \"tailordb\", namespace);\n let remoteState;\n try {\n remoteState = await fetchRemoteMigrationState(client, trn);\n } catch (error) {\n rows.push({\n status: \"error\",\n namespace,\n error: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n const currentMigration = remoteState.number ?? 0;\n\n if (remoteState.historyIdInvalid) {\n rows.push({\n status: \"error\",\n namespace,\n error: \"Remote migration history ID is invalid.\",\n });\n continue;\n }\n\n const hasRemoteMigrationState = remoteState.number !== null || remoteState.historyId !== null;\n if (hasRemoteMigrationState && remoteState.historyId !== localHistoryId) {\n rows.push({\n status: \"error\",\n namespace,\n error:\n `Remote migration history ID ${remoteState.historyId ?? \"<unset>\"} does not match ` +\n `local migration history ID ${localHistoryId ?? \"<unset>\"}.`,\n });\n continue;\n }\n\n const availableNumbers = migrationFiles\n .map((f) => f.number)\n .filter((n, i, arr) => arr.indexOf(n) === i) // deduplicate\n .toSorted((a, b) => a - b);\n const pendingNumbers = availableNumbers.filter((n) => n > currentMigration);\n\n const pendingMigrations = pendingNumbers.map((num) => ({\n number: num,\n label: formatMigrationNumber(num),\n ...(descriptions.has(num) ? { description: descriptions.get(num) } : {}),\n }));\n\n rows.push({\n status: \"ok\",\n namespace,\n currentMigration,\n currentMigrationLabel: formatMigrationNumber(currentMigration),\n pendingMigrations,\n });\n }\n\n return rows;\n}\n\nfunction printMigrationStatuses(rows: MigrationStatusRow[]): void {\n for (const row of rows) {\n logger.newline();\n logger.info(`Namespace: ${styles.bold(row.namespace)}`);\n if (isStatusFailure(row)) {\n logger.error(` Migration status error: ${row.error}`);\n continue;\n }\n logger.log(` Current migration: ${styles.bold(row.currentMigrationLabel)}`);\n\n if (row.pendingMigrations.length > 0) {\n logger.log(\" Pending migrations:\");\n for (const pending of row.pendingMigrations) {\n if (pending.description) {\n logger.log(` - ${pending.label}: ${pending.description}`);\n } else {\n logger.log(` - ${pending.label}`);\n }\n }\n } else {\n logger.log(\" Pending migrations: (none)\");\n }\n }\n\n logger.newline();\n}\n\n/**\n * Show migration status for TailorDB namespaces\n * @param {StatusOptions} options - Command options\n */\nasync function status(options: StatusOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const rows = await collectMigrationStatuses(options);\n if (options.json) {\n logger.out(rows);\n } else {\n printMigrationStatuses(rows);\n }\n\n const failures = rows.filter(isStatusFailure);\n if (failures.length > 0) {\n const namespaces = failures.map((f) => f.namespace).join(\", \");\n throw new Error(\n `Migration status check failed for ${failures.length} namespace${failures.length === 1 ? \"\" : \"s\"}: ${namespaces}`,\n );\n }\n}\n\nexport const statusCommand = defineAppCommand({\n name: \"status\",\n description:\n \"Show the current migration status for TailorDB namespaces, including applied and pending migrations.\",\n notes:\n \"Every local migration file is checked for a compatible format version, and deployed migration history IDs must match the local baseline. Compatibility errors, history mismatches, and metadata lookup failures are reported per namespace and make the command exit non-zero; only a not-yet-deployed namespace is treated as having no applied migrations.\",\n args: z.strictObject({\n ...deploymentArgs,\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (shows all namespaces if not specified)\",\n }),\n }),\n run: async (args) => {\n await status({\n configPath: args.config,\n namespace: args.namespace,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n json: logger.jsonMode,\n });\n },\n});\n","import { Code, ConnectError } from \"@connectrpc/connect\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { resourceTrn, writeMetadataLabels } from \"#/cli/commands/deploy/label\";\nimport { confirmationArgs, deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport {\n fetchAll,\n fetchAllTolerant,\n initOperatorClient,\n type OperatorClient,\n} from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { PluginManager } from \"#/plugin/manager\";\nimport {\n getNamespacesWithMigrations,\n selectTargetNamespace,\n type NamespaceWithMigrations,\n} from \"./config\";\nimport { formatMigrationDiff, hasChanges } from \"./diff-calculator\";\nimport { parseMigrationNumberArg } from \"./migration-number\";\nimport { fetchRemoteMigrationNumber } from \"./remote-state\";\nimport {\n assertMigrationNumberExists,\n assertValidMigrationFiles,\n compareLocalTypesWithSnapshot,\n createSnapshotFromLocalTypes,\n formatMigrationNumber,\n reconstructSnapshotFromMigrations,\n} from \"./snapshot\";\nimport {\n compareSnapshotWithRemote,\n generateAllTypeManifestsFromSnapshot,\n protoGqlPermission,\n type GenerateAllManifestsOptions,\n} from \"./snapshot-manifest\";\nimport {\n handleOptionalToRequiredError,\n MIGRATION_HISTORY_LABEL_KEY,\n MIGRATION_LABEL_KEY,\n sanitizeMigrationLabel,\n} from \"./types\";\nimport type { TailorDBType as ProtoTailorDBType } from \"@tailor-platform/tailor-proto/tailordb_resource_pb\";\n\nexport interface SyncOptions {\n configPath?: string;\n number: string;\n namespace?: string;\n yes?: boolean;\n workspaceId?: string;\n profile?: string;\n}\n\ntype RemoteGqlPermission = Awaited<\n ReturnType<OperatorClient[\"listTailorDBGQLPermissions\"]>\n>[\"permissions\"][number];\n\nasync function fetchRemoteGqlPermissions(\n client: OperatorClient,\n workspaceId: string,\n namespace: string,\n): Promise<RemoteGqlPermission[]> {\n return fetchAllTolerant(async (pageToken, maxPageSize) => {\n const { permissions, nextPageToken } = await client.listTailorDBGQLPermissions({\n workspaceId,\n namespaceName: namespace,\n pageToken,\n pageSize: maxPageSize,\n });\n return [permissions, nextPageToken];\n });\n}\n\nasync function fetchRemoteTypes(\n client: OperatorClient,\n workspaceId: string,\n namespace: string,\n): Promise<ProtoTailorDBType[]> {\n return fetchAll(async (pageToken, maxPageSize) => {\n try {\n const { tailordbTypes, nextPageToken } = await client.listTailorDBTypes({\n workspaceId,\n namespaceName: namespace,\n pageToken,\n pageSize: maxPageSize,\n });\n return [tailordbTypes, nextPageToken];\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.NotFound) {\n throw new Error(\n `Cannot sync: TailorDB namespace \"${namespace}\" has not been deployed yet.`,\n { cause: error },\n );\n }\n throw error;\n }\n });\n}\n\n/**\n * Verify that replaying the full migration history reproduces the current\n * local type definitions, before anything is sent to the remote.\n *\n * Sync force-applies a snapshot reconstructed from the migration history, so\n * the history itself must be trustworthy. When the reconstruction at the\n * latest migration does not match the schema defined in the local type files,\n * either the migration files were edited incorrectly or a schema change has\n * not been recorded as a migration yet — and overwriting the remote with an\n * unverified snapshot could destroy data. Fails before any RPC is issued.\n *\n * Returns the manifest generation options deploy would use for this\n * namespace (executor-driven publishRecordEvents and namespace\n * gqlOperations), so the synced manifests match what deploy produces.\n * @param loaded - Result of `loadConfig` (config and plugins)\n * @param target - Namespace whose migration history is being synced\n * @returns Options for `generateAllTypeManifestsFromSnapshot`\n */\nasync function assertMigrationsReproduceLocalTypes(\n loaded: Awaited<ReturnType<typeof loadConfig>>,\n target: NamespaceWithMigrations,\n): Promise<GenerateAllManifestsOptions> {\n const { config, plugins } = loaded;\n const pluginManager = plugins.length > 0 ? new PluginManager(plugins) : undefined;\n const { defineApplication, generatePluginFilesIfNeeded } =\n await import(\"#/cli/services/application\");\n const application = defineApplication({ config, pluginManager });\n\n const tailordbService = application.tailorDBServices.find(\n (s) => s.namespace === target.namespace,\n );\n if (!tailordbService) {\n throw new Error(`No TailorDB service found for namespace \"${target.namespace}\"`);\n }\n // Load every namespace (not just the target): plugin executors are\n // registered while types load, and may trigger on the target's types.\n for (const service of application.tailorDBServices) {\n await service.loadTypes();\n await service.processNamespacePlugins();\n }\n\n // Mirror loadApplication: plugin-generated executor files must be loaded\n // too, or publishRecordEvents would be applied as false for the types\n // their record triggers depend on. Read the executors getter rather than\n // the loadExecutors() result — the latter is undefined for plugin-only\n // executor configurations.\n const pluginExecutorFiles = generatePluginFilesIfNeeded(\n pluginManager,\n application.tailorDBServices,\n config.path,\n );\n const executorService =\n application.executorService ??\n (pluginExecutorFiles.length > 0\n ? (await import(\"#/cli/services/executor/service\")).createExecutorService({\n config: { files: [] },\n baseDir: path.dirname(config.path),\n })\n : undefined);\n await executorService?.loadExecutors();\n if (pluginExecutorFiles.length > 0) {\n await executorService?.loadPluginExecutorFiles([...pluginExecutorFiles]);\n }\n const executorUsedTypes = new Set<string>();\n for (const executor of Object.values(executorService?.executors ?? {})) {\n if (executor.trigger.kind === \"tailordb\") {\n executorUsedTypes.add(executor.trigger.typeName);\n }\n }\n const manifestOptions: GenerateAllManifestsOptions = {\n executorUsedTypes,\n namespaceGqlOperations: tailordbService.config.gqlOperations,\n };\n\n const latestSnapshot = reconstructSnapshotFromMigrations(target.migrationsDir);\n if (!latestSnapshot) {\n return manifestOptions; // No migrations at all — reported by the caller's snapshot check.\n }\n const currentSnapshot = createSnapshotFromLocalTypes(tailordbService.types, target.namespace);\n const diff = compareLocalTypesWithSnapshot(\n latestSnapshot,\n currentSnapshot.tables,\n target.namespace,\n );\n if (!hasChanges(diff)) {\n return manifestOptions;\n }\n\n logger.error(\n `Migration history does not reproduce the current local schema for namespace ${styles.bold(target.namespace)}:`,\n );\n logger.log(formatMigrationDiff(diff));\n logger.newline();\n logger.info(\"This usually means one of the following:\");\n logger.info(\n \" - Migration files were edited and replaying them no longer matches the type definitions — fix the migration files.\",\n { mode: \"plain\" },\n );\n logger.info(\n \" - Type definitions changed without a new migration — run 'tailor tailordb migration generate' first.\",\n { mode: \"plain\" },\n );\n logger.newline();\n throw new Error(\n \"Refusing to sync: the migration history must reproduce the current local schema before it can be applied to the remote.\",\n );\n}\n\n/**\n * Sync remote TailorDB schema to a specific migration snapshot.\n *\n * Reconstructs the schema state at `<number>` from `0000/schema.json` + diffs,\n * then issues create/update/delete RPCs so the remote matches that snapshot.\n * Updates the migration label to `<number>` on success. Before any remote\n * mutation, verifies that the migration history reproduces the current local\n * type definitions (see {@link assertMigrationsReproduceLocalTypes}).\n *\n * Intended for recovering from drift introduced by `deploy --no-schema-check`\n * runs against an older revision: instead of having to `git checkout` that\n * revision and re-deploy, the operator can sync the remote back to a known\n * snapshot version directly.\n * @param options - Command options\n */\nasync function sync(options: SyncOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const targetVersion = parseMigrationNumberArg(options.number);\n\n const loaded = await loadConfig(options.configPath);\n const { config } = loaded;\n const configDir = path.dirname(config.path);\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n const target = selectTargetNamespace(namespacesWithMigrations, options.namespace);\n\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n\n const latest = assertMigrationNumberExists(target.migrationsDir, targetVersion);\n\n const snapshot = reconstructSnapshotFromMigrations(target.migrationsDir, targetVersion);\n if (!snapshot) {\n throw new Error(\n `No initial schema snapshot found in ${target.migrationsDir}. Expected 0000/schema.json.`,\n );\n }\n\n const manifestOptions = await assertMigrationsReproduceLocalTypes(loaded, target);\n\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n\n const trn = resourceTrn(workspaceId, \"tailordb\", target.namespace);\n const current = await fetchRemoteMigrationNumber(client, trn);\n const remoteTypes = await fetchRemoteTypes(client, workspaceId, target.namespace);\n const existingTypeNames = new Set(remoteTypes.map((t) => t.name));\n const { creates, updates, deletes } = compareSnapshotWithRemote(snapshot, existingTypeNames);\n\n // GQL permissions are reconciled alongside types: upsert the ones defined\n // in the snapshot, delete remote ones with no snapshot counterpart\n // (including those of deleted types — an orphaned permission can block\n // the type deletion).\n const remoteGqlPermissions = await fetchRemoteGqlPermissions(\n client,\n workspaceId,\n target.namespace,\n );\n const remoteGqlPermissionTypes = new Set(remoteGqlPermissions.map((p) => p.typeName));\n const desiredGqlPermissions = Object.entries(snapshot.tables).flatMap(\n ([typeName, snapshotType]) =>\n snapshotType.permissions?.gql\n ? [{ typeName, permission: protoGqlPermission(snapshotType.permissions.gql) }]\n : [],\n );\n const desiredGqlPermissionTypes = new Set(desiredGqlPermissions.map((p) => p.typeName));\n const gqlPermissionDeletes = remoteGqlPermissions.filter(\n (p) => !desiredGqlPermissionTypes.has(p.typeName),\n );\n\n logger.newline();\n logger.info(`Namespace: ${styles.bold(target.namespace)}`);\n logger.log(\n ` Current migration: ${current === null ? \"<unset>\" : styles.bold(formatMigrationNumber(current))}`,\n );\n logger.log(` Target migration: ${styles.bold(formatMigrationNumber(targetVersion))}`);\n logger.log(` Types to create: ${styles.bold(String(creates.length))}`);\n logger.log(` Types to update: ${styles.bold(String(updates.length))}`);\n logger.log(` Types to delete: ${styles.bold(String(deletes.length))}`);\n logger.log(` GQL permissions to set: ${styles.bold(String(desiredGqlPermissions.length))}`);\n logger.log(` GQL permissions to delete: ${styles.bold(String(gqlPermissionDeletes.length))}`);\n logger.newline();\n\n const totalOps =\n creates.length +\n updates.length +\n deletes.length +\n desiredGqlPermissions.length +\n gqlPermissionDeletes.length;\n if (totalOps === 0) {\n // Reachable only when both snapshot and remote hold no types; the label\n // may still be stale, so the sync proceeds to update it.\n logger.info(\"No types to apply; only the migration label will be updated.\");\n } else {\n logger.warn(\n \"This operation will overwrite remote TailorDB types to match the selected snapshot.\",\n );\n if (deletes.length > 0) {\n logger.warn(\"Existing data in deleted types will be lost.\");\n }\n logger.newline();\n }\n\n logger.warn(\n \"Sync never runs migrate.ts scripts; it only applies the schema snapshot and moves the migration label.\",\n );\n logger.newline();\n\n if (current !== null && targetVersion < current) {\n logger.warn(\n `Migrations ${formatMigrationNumber(targetVersion + 1)}–${formatMigrationNumber(\n current,\n )} will become pending again and re-execute on the next deploy, including their migrate.ts scripts. Make sure those scripts are idempotent (safe to re-run).`,\n );\n logger.newline();\n } else if (current !== null && targetVersion > current) {\n logger.warn(\n `Moving the migration label forwards (${formatMigrationNumber(current)} → ${formatMigrationNumber(\n targetVersion,\n )}): migrate.ts scripts for migrations ${formatMigrationNumber(current + 1)}–${formatMigrationNumber(\n targetVersion,\n )} will not run on the next deploy.`,\n );\n logger.newline();\n }\n\n if (!options.yes) {\n const confirmation = await prompt.confirm({\n message: `Continue and set migration label to ${formatMigrationNumber(targetVersion)}?`,\n default: false,\n });\n if (!confirmation) {\n logger.info(\"Operation cancelled.\");\n return;\n }\n logger.newline();\n }\n\n const manifests = generateAllTypeManifestsFromSnapshot(snapshot, manifestOptions);\n\n // Resolve all manifests before issuing any RPC: a missing manifest\n // indicates an internal inconsistency, and skipping or failing midway\n // would leave the remote schema partially synced.\n const manifestFor = (typeName: string) => {\n const manifest = manifests.get(typeName);\n if (!manifest) {\n throw new Error(\n `Internal error: no manifest generated for type \"${typeName}\". No changes were applied.`,\n );\n }\n return manifest;\n };\n const createManifests = creates.map((typeName) => manifestFor(typeName));\n const updateManifests = updates.map((typeName) => manifestFor(typeName));\n\n try {\n await Promise.all([\n ...createManifests.map((tailordbType) =>\n client.createTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbType,\n }),\n ),\n ...updateManifests.map((tailordbType) =>\n client.updateTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbType,\n }),\n ),\n ]);\n } catch (error) {\n handleOptionalToRequiredError(error, [\n \"The target snapshot marks a field as required, but existing remote records have no value for it.\",\n \"Populate those records first (e.g. with a migration script applied via 'tailor deploy'), then re-run the sync.\",\n ]);\n }\n await Promise.all(\n desiredGqlPermissions.map(({ typeName, permission }) => {\n const request = { workspaceId, namespaceName: target.namespace, typeName, permission };\n return remoteGqlPermissionTypes.has(typeName)\n ? client.updateTailorDBGQLPermission(request)\n : client.createTailorDBGQLPermission(request);\n }),\n );\n await Promise.all(\n gqlPermissionDeletes.map((p) =>\n client.deleteTailorDBGQLPermission({\n workspaceId,\n namespaceName: target.namespace,\n typeName: p.typeName,\n }),\n ),\n );\n await Promise.all(\n deletes.map((typeName) =>\n client.deleteTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbTypeName: typeName,\n }),\n ),\n );\n\n await writeMetadataLabels(client, {\n trn,\n labels: {\n [MIGRATION_LABEL_KEY]: sanitizeMigrationLabel(targetVersion),\n ...(snapshot.rebaseline?.historyId\n ? { [MIGRATION_HISTORY_LABEL_KEY]: snapshot.rebaseline.historyId }\n : {}),\n },\n remove: snapshot.rebaseline?.historyId ? undefined : [MIGRATION_HISTORY_LABEL_KEY],\n });\n\n logger.success(\n `Synced namespace ${styles.bold(target.namespace)} to migration ${styles.bold(formatMigrationNumber(targetVersion))}.`,\n );\n\n if (targetVersion < latest) {\n logger.newline();\n logger.info(\n `Run 'tailor deploy' to apply migrations ${formatMigrationNumber(\n targetVersion + 1,\n )}–${formatMigrationNumber(latest)} from the working tree.`,\n );\n }\n}\n\nexport const syncCommand = defineAppCommand({\n name: \"sync\",\n description:\n \"Sync remote TailorDB schema to a specific migration snapshot (recovery from --no-schema-check drift).\",\n args: z.strictObject({\n ...deploymentArgs,\n ...confirmationArgs,\n number: arg(z.string(), {\n positional: true,\n description: \"Migration number to sync to (e.g., 0001 or 1; 0 targets the baseline snapshot)\",\n }),\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (required if multiple namespaces exist)\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await sync({\n configPath: args.config,\n number: args.number,\n namespace: args.namespace,\n yes: args.yes,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n });\n },\n});\n","import { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport { Code, ConnectError } from \"@connectrpc/connect\";\nimport { CloneOperationStatus } from \"@tailor-platform/tailor-proto/application_pb\";\nimport * as path from \"pathe\";\nimport {\n deployMigrationTestBaseline,\n deployMigrationTestTarget,\n} from \"#/cli/commands/deploy/deploy\";\nimport { resourceTrn } from \"#/cli/commands/deploy/label\";\nimport {\n getMigrationMachineUser,\n updateMigrationLabel,\n} from \"#/cli/commands/deploy/tailordb/migration\";\nimport { bundleSeedScript } from \"#/cli/commands/generate/seed/bundler\";\nimport {\n fetchRemoteSchemaSnapshot,\n toTailorDBDeployInput,\n type TailorDBDeployInput,\n verifyRemoteSchema,\n} from \"#/cli/commands/tailordb/migrate/schema-checks\";\nimport { createValidatedWorkspaceWithClient } from \"#/cli/commands/workspace/create\";\nimport { getOrNull, initOperatorClient, type OperatorClient } from \"#/cli/shared/client\";\nimport { loadAccessToken, loadPlatformClientConfig, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { executeScript } from \"#/cli/shared/script-executor\";\nimport { chunkSeedData, type SeedData } from \"#/cli/shared/seed-chunker\";\nimport { loadSeedContext, type SeedContext } from \"#/cli/shared/seed-context\";\nimport { loadApplicationNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { bundleMigrationScript } from \"./bundler\";\nimport { getNamespacesWithMigrations } from \"./config\";\nimport { fetchRemoteMigrationNumber } from \"./remote-state\";\nimport {\n assertValidMigrationFiles,\n compareSnapshots,\n getLatestMigrationNumber,\n normalizeSchemaSnapshot,\n reconstructSnapshotFromMigrations,\n type NormalizedSchemaSnapshot,\n type SnapshotFieldConfig,\n} from \"./snapshot\";\nimport type { LoadedApplicationNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport type { TailorDBServiceConfig } from \"#/types/tailordb.generated\";\nimport type {\n MigrationTestDependencies,\n MigrationTestOptions,\n PreparedMigrationTest,\n} from \"./test-types\";\nimport type { JsonObject, JsonValue } from \"type-fest\";\n\nconst CLONE_POLL_INTERVAL = 1_000;\nconst CLONE_TIMEOUT = 5 * 60 * 1_000;\n\ninterface RuntimeState {\n client: OperatorClient;\n loaded: LoadedApplicationNamespaces;\n options: MigrationTestOptions;\n seedContext?: SeedContext;\n}\n\ninterface WaitForCloneOptions {\n sourceWorkspaceId: string;\n targetWorkspaceId: string;\n operationId: string;\n pollInterval?: number;\n timeout?: number;\n}\n\nfunction delay(milliseconds: number): Promise<void> {\n return milliseconds > 0\n ? new Promise((resolve) => setTimeout(resolve, milliseconds))\n : Promise.resolve();\n}\n\nfunction assertSeedDataDirectory(dataDir: string): void {\n let stats: fs.Stats;\n try {\n stats = fs.statSync(dataDir);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(\n `Seed data directory not found: ${dataDir}. Run 'tailor generate' before testing migrations.`,\n { cause: error },\n );\n }\n throw error;\n }\n if (!stats.isDirectory()) {\n throw new Error(`Seed data path is not a directory: ${dataDir}`);\n }\n}\n\nfunction assertAssertionScript(assertionPath: string): void {\n const resolvedPath = path.resolve(assertionPath);\n let stats: fs.Stats;\n try {\n stats = fs.statSync(resolvedPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n throw new Error(`Migration assertion script not found: ${resolvedPath}`, { cause: error });\n }\n throw error;\n }\n if (!stats.isFile()) {\n throw new Error(`Migration assertion path is not a file: ${resolvedPath}`);\n }\n}\n\n/**\n * Require a designated clone target to share the source workspace's region.\n * @param sourceRegion - Source workspace region\n * @param targetRegion - Target workspace region\n */\nexport function assertCloneTargetRegion(sourceRegion: string, targetRegion: string): void {\n if (sourceRegion !== targetRegion) {\n throw new Error(\n `Clone mode requires source and target workspaces in the same region (source: ${sourceRegion}, target: ${targetRegion}).`,\n );\n }\n}\n\n/**\n * Require the migration test target workspace to differ from the source workspace.\n * @param sourceWorkspaceId - Source workspace ID\n * @param targetWorkspaceId - Designated target workspace ID, if any\n */\nexport function assertTargetWorkspaceDiffers(\n sourceWorkspaceId: string,\n targetWorkspaceId?: string,\n): void {\n if (targetWorkspaceId?.toLowerCase() === sourceWorkspaceId.toLowerCase()) {\n throw new Error(\"The migration test target workspace must differ from the source workspace.\");\n }\n}\n\n/**\n * Resolve the namespace an assertion script runs against.\n * @param pendingNamespaces - Namespaces with pending migrations\n * @param assertionNamespace - Explicit namespace from `--assert-namespace`, if any\n * @returns Resolved assertion namespace\n */\nexport function resolveAssertionNamespace(\n pendingNamespaces: ReadonlyArray<string>,\n assertionNamespace?: string,\n): string {\n const namespace =\n assertionNamespace ?? (pendingNamespaces.length === 1 ? pendingNamespaces[0] : undefined);\n if (!namespace) {\n throw new Error(\n \"--assert-namespace is required when pending migrations span multiple namespaces.\",\n );\n }\n if (!pendingNamespaces.includes(namespace)) {\n throw new Error(`Assertion namespace \"${namespace}\" has no pending migrations.`);\n }\n return namespace;\n}\n\ninterface CreateBaselineSnapshotsOptions {\n client: OperatorClient;\n workspaceId: string;\n dataMode: MigrationTestOptions[\"data\"];\n inputs: ReadonlyArray<TailorDBDeployInput>;\n baselines: PreparedMigrationTest[\"baselines\"];\n}\n\n/**\n * Build the schema overrides used before migration-test data is loaded.\n * @param options - Source workspace, local inputs, and migration baselines\n * @returns Schema snapshots keyed by namespace\n */\nexport async function createMigrationTestBaselineSnapshots(\n options: CreateBaselineSnapshotsOptions,\n): Promise<Map<string, NormalizedSchemaSnapshot>> {\n const snapshots = new Map(\n [...options.baselines].map(([namespace, baseline]) => [namespace, baseline.snapshot]),\n );\n if (options.dataMode !== \"clone\") return snapshots;\n\n const unmigratedInputs = options.inputs.filter((input) => !snapshots.has(input.namespace));\n const remoteSnapshots = await Promise.all(\n unmigratedInputs.map((input) =>\n fetchRemoteSchemaSnapshot(options.client, options.workspaceId, input.namespace),\n ),\n );\n unmigratedInputs.forEach((input, index) => {\n snapshots.set(\n input.namespace,\n assertDefined(remoteSnapshots[index], `remote snapshot missing for \"${input.namespace}\"`),\n );\n });\n return snapshots;\n}\n\n/**\n * Wait for an application-data clone operation to reach a terminal state.\n * @param client - Operator client\n * @param options - Clone operation identifiers and polling limits\n */\nexport async function waitForCloneApplicationData(\n client: OperatorClient,\n options: WaitForCloneOptions,\n): Promise<void> {\n const pollInterval = options.pollInterval ?? CLONE_POLL_INTERVAL;\n const timeout = options.timeout ?? CLONE_TIMEOUT;\n const deadline = Date.now() + timeout;\n\n while (Date.now() <= deadline) {\n const operation = await client.getCloneApplicationDataOperation({\n sourceWorkspaceId: options.sourceWorkspaceId,\n targetWorkspaceId: options.targetWorkspaceId,\n operationId: options.operationId,\n });\n if (operation.status === CloneOperationStatus.COMPLETED) {\n return;\n }\n if (operation.status === CloneOperationStatus.FAILED) {\n throw new Error(\n `Application data clone failed: ${operation.errorMessage || \"unknown platform error\"}`,\n );\n }\n if (\n operation.status !== CloneOperationStatus.PENDING &&\n operation.status !== CloneOperationStatus.PROCESSING\n ) {\n throw new Error(`Application data clone returned unexpected status ${operation.status}.`);\n }\n await delay(pollInterval);\n }\n\n throw new Error(`Application data clone timed out after ${Math.round(timeout / 1_000)} seconds.`);\n}\n\n/**\n * Load generated JSONL seed rows for the types in a baseline snapshot.\n * @param dataDir - Directory containing `<Type>.jsonl` files\n * @param typeNames - Baseline type names to load\n * @param snapshot - Baseline schema used to remove fields introduced by pending migrations\n * @returns Seed rows keyed by type name\n */\nexport function loadSnapshotSeedData(\n dataDir: string,\n typeNames: string[],\n snapshot?: NormalizedSchemaSnapshot,\n): SeedData {\n const data: SeedData = {};\n for (const typeName of typeNames) {\n const snapshotType = snapshot?.tables[typeName];\n const jsonlPath = path.join(dataDir, `${typeName}.jsonl`);\n let content: string;\n try {\n content = fs.readFileSync(jsonlPath, \"utf8\").trim();\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n data[typeName] = [];\n continue;\n }\n throw error;\n }\n data[typeName] = content\n ? content.split(\"\\n\").map((line, index) => {\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch (error) {\n throw new Error(\n `Invalid JSON in ${jsonlPath} at line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Invalid seed row in ${jsonlPath} at line ${index + 1}: expected a JSON object`,\n );\n }\n const row = value as JsonObject;\n return snapshotType ? projectSeedObject(row, snapshotType.fields, new Set([\"id\"])) : row;\n })\n : [];\n }\n return data;\n}\n\nfunction projectSeedObject(\n value: JsonObject,\n fields: Readonly<Record<string, SnapshotFieldConfig>>,\n implicitFields: ReadonlySet<string> = new Set(),\n): JsonObject {\n return Object.fromEntries(\n Object.entries(value).flatMap(([fieldName, fieldValue]) => {\n const field = fields[fieldName];\n if (!field) return implicitFields.has(fieldName) ? [[fieldName, fieldValue]] : [];\n return [[fieldName, projectSeedValue(fieldValue, field)]];\n }),\n ) as JsonObject;\n}\n\nfunction projectSeedValue(value: JsonValue, field: SnapshotFieldConfig): JsonValue {\n const fields = field.fields;\n if (!fields) return value;\n if (field.array) {\n if (!Array.isArray(value)) return value;\n return value.map((entry) => (isJsonObject(entry) ? projectSeedObject(entry, fields) : entry));\n }\n return isJsonObject(value) ? projectSeedObject(value, fields) : value;\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/**\n * Derive insertion order and self-referencing types from a baseline snapshot.\n * @param snapshot - Baseline schema snapshot\n * @returns Dependency-ordered type names and self-referencing types\n */\nexport function sortSeedTypesForSnapshot(snapshot: NormalizedSchemaSnapshot): {\n order: string[];\n selfRefTypes: string[];\n} {\n const typeNames = Object.keys(snapshot.tables);\n const available = new Set(typeNames);\n const dependencies = new Map<string, string[]>();\n const selfRefTypes: string[] = [];\n for (const [typeName, type] of Object.entries(snapshot.tables)) {\n const referenced = new Set<string>();\n for (const field of Object.values(type.fields)) {\n const target = field.foreignKeyType;\n if (!target) continue;\n if (target === typeName) {\n selfRefTypes.push(typeName);\n } else if (available.has(target)) {\n referenced.add(target);\n }\n }\n dependencies.set(typeName, [...referenced]);\n }\n\n const visited = new Set<string>();\n const order: string[] = [];\n const visit = (typeName: string): void => {\n if (visited.has(typeName)) return;\n visited.add(typeName);\n for (const dependency of dependencies.get(typeName) ?? []) {\n visit(dependency);\n }\n order.push(typeName);\n };\n for (const typeName of typeNames) {\n visit(typeName);\n }\n return { order, selfRefTypes };\n}\n\nfunction temporaryWorkspaceName(): string {\n const timestamp = new Date()\n .toISOString()\n .replace(/[-:T.Z]/g, \"\")\n .slice(0, 14);\n return `migration-test-${timestamp}-${randomBytes(3).toString(\"hex\")}`;\n}\n\nfunction stateOrThrow(state: RuntimeState | undefined): RuntimeState {\n return assertDefined(state, \"migration test runtime was used before preparation\");\n}\n\n/**\n * Require the source workspace to still match the prepared baselines.\n *\n * The source is verified during preparation, but the baseline deploy runs in\n * between; a source deploy in that window would make the clone diverge from\n * the already-deployed baseline schemas.\n * @param state - Prepared migration test runtime state\n * @param prepared - Baselines captured during preparation\n * @param sourceWorkspaceId - Source workspace ID\n */\nexport async function assertSourceBaselineFresh(\n state: RuntimeState,\n prepared: PreparedMigrationTest,\n sourceWorkspaceId: string,\n): Promise<void> {\n const loaded = state.loaded;\n const namespaces = getNamespacesWithMigrations(loaded.config, path.dirname(loaded.config.path));\n const inputs = loaded.application.tailorDBServices.map(toTailorDBDeployInput);\n const remoteChecks = await verifyRemoteSchema(\n state.client,\n sourceWorkspaceId,\n namespaces,\n loaded.config,\n inputs,\n );\n const invalidRemote = remoteChecks.find(\n (check) => check.hasDrift || check.checkpointMissingLocal || check.checkpointRepair,\n );\n if (invalidRemote) {\n throw new Error(\n `Source namespace \"${invalidRemote.namespace}\" changed after migration test preparation. Run the migration test again.`,\n );\n }\n for (const namespace of namespaces) {\n const baseline = prepared.baselines.get(namespace.namespace);\n if (!baseline) continue;\n const migrationNumber = await fetchRemoteMigrationNumber(\n state.client,\n resourceTrn(sourceWorkspaceId, \"tailordb\", namespace.namespace),\n );\n if (migrationNumber !== baseline.migrationNumber) {\n throw new Error(\n `Source namespace \"${namespace.namespace}\" moved from migration ${baseline.migrationNumber} to ${migrationNumber ?? \"none\"} after migration test preparation. Run the migration test again.`,\n );\n }\n }\n const unmigratedInputs = inputs.filter((input) => !prepared.baselines.has(input.namespace));\n for (const input of unmigratedInputs) {\n const snapshot = prepared.baselineSnapshots.get(input.namespace);\n if (!snapshot) continue;\n const current = await fetchRemoteSchemaSnapshot(\n state.client,\n sourceWorkspaceId,\n input.namespace,\n );\n if (compareSnapshots(snapshot, current).changes.length > 0) {\n throw new Error(\n `Source namespace \"${input.namespace}\" schema changed after migration test preparation. Run the migration test again.`,\n );\n }\n }\n}\n\n/**\n * Delete the target workspace's user profile config when one exists.\n *\n * A retained target may carry a user profile config referencing types the\n * baseline deploy replaces; deleting it up front lets the baseline's planAuth\n * see no existing config instead of reordering delete phases.\n * @param state - Prepared migration test runtime state\n * @param targetWorkspaceId - Target workspace ID\n */\nexport async function deleteExistingUserProfileConfig(\n state: RuntimeState,\n targetWorkspaceId: string,\n): Promise<void> {\n const auth = state.loaded.application.authService;\n if (!auth) return;\n const namespaceName = auth.config.name;\n const existing = await getOrNull(() =>\n state.client.getUserProfileConfig({ workspaceId: targetWorkspaceId, namespaceName }),\n );\n if (!existing) return;\n await state.client.deleteUserProfileConfig({ workspaceId: targetWorkspaceId, namespaceName });\n}\n\nfunction migrationConfig(\n loaded: LoadedApplicationNamespaces,\n namespace: string,\n): TailorDBServiceConfig[\"migration\"] {\n return (loaded.config.db?.[namespace] as TailorDBServiceConfig | undefined)?.migration;\n}\n\nfunction authExecutionContext(\n state: RuntimeState,\n namespace: string,\n explicitMachineUser?: string,\n): { authNamespace: string; machineUserName: string } {\n const auth = state.loaded.application.authService;\n if (!auth) {\n throw new Error(\"Auth configuration is required to execute migration test scripts.\");\n }\n const machineUserName =\n explicitMachineUser ??\n getMigrationMachineUser(\n migrationConfig(state.loaded, namespace),\n auth.config.machineUsers ? Object.keys(auth.config.machineUsers) : undefined,\n );\n if (!machineUserName) {\n throw new Error(\n `No machine user is available for namespace \"${namespace}\". Pass --machine-user or configure one in auth or db.${namespace}.migration.`,\n );\n }\n return { authNamespace: auth.config.name, machineUserName };\n}\n\nasync function prepareMigrationTest(options: MigrationTestOptions): Promise<{\n state: RuntimeState;\n prepared: PreparedMigrationTest;\n}> {\n const loaded = await loadApplicationNamespaces({ configPath: options.configPath });\n const configDir = path.dirname(loaded.config.path);\n const namespaces = getNamespacesWithMigrations(loaded.config, configDir);\n if (namespaces.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found.\");\n }\n for (const namespace of namespaces) {\n assertValidMigrationFiles(namespace.migrationsDir, namespace.namespace);\n }\n\n let seedContext: SeedContext | undefined;\n if (options.data === \"seed\") {\n seedContext = await loadSeedContext({ configPath: loaded.config.path });\n assertSeedDataDirectory(path.join(seedContext.distPath, \"data\"));\n }\n if (options.assertionPath) {\n assertAssertionScript(options.assertionPath);\n }\n\n const inputs = loaded.application.tailorDBServices.map(toTailorDBDeployInput);\n const accessToken = await loadAccessToken({ profile: options.profile });\n const platformConfig = await loadPlatformClientConfig({ profile: options.profile });\n const client = await initOperatorClient(accessToken, platformConfig);\n const sourceWorkspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n assertTargetWorkspaceDiffers(sourceWorkspaceId, options.targetWorkspaceId);\n\n const [workspaceResponse, applicationResponse, targetWorkspaceResponse] = await Promise.all([\n client.getWorkspace({ workspaceId: sourceWorkspaceId }),\n client.getApplication({\n workspaceId: sourceWorkspaceId,\n applicationName: loaded.config.name,\n }),\n options.data === \"clone\" && options.targetWorkspaceId\n ? client.getWorkspace({ workspaceId: options.targetWorkspaceId })\n : Promise.resolve(undefined),\n ]);\n const sourceWorkspace = assertDefined(\n workspaceResponse.workspace,\n `source workspace \"${sourceWorkspaceId}\" not found`,\n );\n assertDefined(\n applicationResponse.application,\n `application \"${loaded.config.name}\" not found in source workspace`,\n );\n const designatedTarget = targetWorkspaceResponse\n ? assertDefined(\n targetWorkspaceResponse.workspace,\n `target workspace \"${options.targetWorkspaceId}\" not found`,\n )\n : undefined;\n\n const remoteChecks = await verifyRemoteSchema(\n client,\n sourceWorkspaceId,\n namespaces,\n loaded.config,\n inputs,\n );\n const invalidRemote = remoteChecks.find(\n (check) => check.hasDrift || check.checkpointMissingLocal,\n );\n if (invalidRemote) {\n throw new Error(\n `Source namespace \"${invalidRemote.namespace}\" does not match its migration checkpoint. Run 'tailor tailordb migration validate' first.`,\n );\n }\n const pendingRepair = remoteChecks.find((check) => check.checkpointRepair);\n if (pendingRepair) {\n throw new Error(\n `Source namespace \"${pendingRepair.namespace}\" has a pending migration checkpoint repair. Run 'tailor deploy' against the source workspace first.`,\n );\n }\n\n const baselines = new Map<\n string,\n { migrationNumber: number; snapshot: NormalizedSchemaSnapshot; historyId: string | null }\n >();\n const targetSnapshots = new Map<string, NormalizedSchemaSnapshot>();\n const pendingNamespaces: string[] = [];\n for (const namespace of namespaces) {\n const migrationNumber = await fetchRemoteMigrationNumber(\n client,\n resourceTrn(sourceWorkspaceId, \"tailordb\", namespace.namespace),\n );\n if (migrationNumber === null) {\n throw new Error(\n `Source namespace \"${namespace.namespace}\" has no sdk-migration checkpoint. Deploy or set its migration checkpoint before testing.`,\n );\n }\n const latest = getLatestMigrationNumber(namespace.migrationsDir);\n if (migrationNumber > latest) {\n throw new Error(\n `Source namespace \"${namespace.namespace}\" is at migration ${migrationNumber}, but the local history ends at ${latest}.`,\n );\n }\n const snapshot = reconstructSnapshotFromMigrations(namespace.migrationsDir, migrationNumber);\n if (!snapshot) {\n throw new Error(\n `No migration baseline snapshot found for namespace \"${namespace.namespace}\".`,\n );\n }\n baselines.set(namespace.namespace, {\n migrationNumber,\n snapshot,\n historyId: snapshot.rebaseline?.historyId ?? null,\n });\n const targetSnapshot = reconstructSnapshotFromMigrations(namespace.migrationsDir, latest);\n if (!targetSnapshot) {\n throw new Error(`No target migration snapshot found for namespace \"${namespace.namespace}\".`);\n }\n targetSnapshots.set(namespace.namespace, targetSnapshot);\n if (migrationNumber < latest) {\n pendingNamespaces.push(namespace.namespace);\n }\n }\n if (pendingNamespaces.length === 0) {\n throw new Error(\"No pending TailorDB migrations found in the source workspace.\");\n }\n\n const baselineSnapshots = await createMigrationTestBaselineSnapshots({\n client,\n workspaceId: sourceWorkspaceId,\n dataMode: options.data,\n inputs,\n baselines,\n });\n\n const prepared: PreparedMigrationTest = {\n sourceWorkspaceId,\n sourceApplicationName: loaded.config.name,\n temporaryWorkspace: {\n name: temporaryWorkspaceName(),\n region: sourceWorkspace.region,\n ...(sourceWorkspace.organizationId ? { organizationId: sourceWorkspace.organizationId } : {}),\n ...(sourceWorkspace.folderId ? { folderId: sourceWorkspace.folderId } : {}),\n },\n baselines,\n baselineSnapshots,\n targetSnapshots,\n pendingNamespaces,\n ...(designatedTarget\n ? { designatedTarget: { id: designatedTarget.id, region: designatedTarget.region } }\n : {}),\n };\n return {\n state: { client, loaded, options, ...(seedContext ? { seedContext } : {}) },\n prepared,\n };\n}\n\n/**\n * Create the platform operations used by `tailordb migration test`.\n * @returns Migration test dependencies backed by the Operator API\n */\nexport function createMigrationTestDependencies(): MigrationTestDependencies {\n let runtimeState: RuntimeState | undefined;\n return {\n prepare: async (options) => {\n const { state, prepared } = await prepareMigrationTest(options);\n runtimeState = state;\n return prepared;\n },\n createWorkspace: async (prepared) => {\n const state = stateOrThrow(runtimeState);\n const workspace = await createValidatedWorkspaceWithClient(\n state.client,\n prepared.temporaryWorkspace,\n );\n logger.info(`Created temporary workspace ${workspace.name} (${workspace.id}).`);\n return { id: workspace.id, name: workspace.name };\n },\n deployBaseline: async ({ prepared, targetWorkspaceId }) => {\n const state = stateOrThrow(runtimeState);\n await deleteExistingUserProfileConfig(state, targetWorkspaceId);\n await deployMigrationTestBaseline(\n {\n configPath: state.loaded.config.path,\n profile: state.options.profile,\n workspaceId: targetWorkspaceId,\n yes: true,\n },\n prepared.baselines,\n prepared.baselineSnapshots,\n );\n for (const [namespace, baseline] of prepared.baselines) {\n await updateMigrationLabel(\n state.client,\n targetWorkspaceId,\n namespace,\n baseline.migrationNumber,\n baseline.historyId ?? undefined,\n );\n }\n },\n seedData: async ({ prepared, targetWorkspaceId }) => {\n const state = stateOrThrow(runtimeState);\n const seedContext = assertDefined(\n state.seedContext,\n \"seed context missing after migration test preparation\",\n );\n const dataDir = path.join(seedContext.distPath, \"data\");\n assertSeedDataDirectory(dataDir);\n const seedSnapshots = new Map(\n state.loaded.application.tailorDBServices.map((service) => {\n const baseline = prepared.baselines.get(service.namespace);\n const input = toTailorDBDeployInput(service);\n return [\n service.namespace,\n baseline?.snapshot ??\n normalizeSchemaSnapshot({\n version: 1,\n namespace: service.namespace,\n createdAt: new Date().toISOString(),\n tables: input.types,\n }),\n ] as const;\n }),\n );\n for (const [namespace, snapshot] of seedSnapshots) {\n const { order, selfRefTypes } = sortSeedTypesForSnapshot(snapshot);\n const data = loadSnapshotSeedData(dataDir, order, snapshot);\n const typesWithData = order.filter((typeName) => (data[typeName]?.length ?? 0) > 0);\n if (typesWithData.length === 0) continue;\n const bundled = await bundleSeedScript(\n namespace,\n typesWithData,\n path.dirname(state.loaded.config.path),\n );\n const chunks = chunkSeedData({\n data,\n order,\n codeByteSize: new TextEncoder().encode(bundled.bundledCode).length,\n });\n const auth = authExecutionContext(\n state,\n namespace,\n state.options.machineUser ?? seedContext.machineUserName,\n );\n for (const chunk of chunks) {\n const execution = await executeScript({\n client: state.client,\n workspaceId: targetWorkspaceId,\n name: `migration-test-seed-${namespace}.ts`,\n code: bundled.bundledCode,\n arg: { data: chunk.data, order: chunk.order, selfRefTypes, upsert: false },\n invoker: {\n namespace: auth.authNamespace,\n machineUserName: auth.machineUserName,\n },\n });\n if (!execution.success) {\n throw new Error(\n execution.error ?? `Seed execution failed for namespace \"${namespace}\".`,\n );\n }\n const result = JSON.parse(execution.result || \"{}\") as { success?: boolean };\n if (result.success !== true) {\n throw new Error(`Seed execution reported failure for namespace \"${namespace}\".`);\n }\n }\n }\n },\n cloneData: async ({ prepared, sourceWorkspaceId, targetWorkspaceId, applicationName }) => {\n const state = stateOrThrow(runtimeState);\n await assertSourceBaselineFresh(state, prepared, sourceWorkspaceId);\n logger.warn(\n \"Clone mode copies TailorDB records only; IdP users and file blobs are not copied.\",\n );\n let operationId: string;\n try {\n const response = await state.client.cloneApplicationData({\n sourceWorkspaceId,\n sourceApplicationName: applicationName,\n targetWorkspaceId,\n targetApplicationName: applicationName,\n });\n operationId = response.operationId;\n } catch (error) {\n if (error instanceof ConnectError && error.code === Code.Unimplemented) {\n throw new Error(\n \"Application data clone is not enabled for this platform. Retry with '--data seed'.\",\n { cause: error },\n );\n }\n throw error;\n }\n if (!operationId) {\n throw new Error(\"Application data clone returned no operation ID.\");\n }\n await waitForCloneApplicationData(state.client, {\n sourceWorkspaceId,\n targetWorkspaceId,\n operationId,\n });\n },\n deployMigrations: async ({ prepared, targetWorkspaceId }) => {\n const state = stateOrThrow(runtimeState);\n await deployMigrationTestTarget(\n {\n configPath: state.loaded.config.path,\n profile: state.options.profile,\n workspaceId: targetWorkspaceId,\n yes: true,\n },\n prepared.targetSnapshots,\n );\n },\n runAssertion: async ({\n prepared,\n targetWorkspaceId,\n assertionPath,\n assertionNamespace,\n machineUser,\n }) => {\n const state = stateOrThrow(runtimeState);\n const namespace = resolveAssertionNamespace(prepared.pendingNamespaces, assertionNamespace);\n const auth = authExecutionContext(state, namespace, machineUser);\n const bundled = await bundleMigrationScript(\n assertionPath,\n namespace,\n 0,\n state.loaded.config.env ?? {},\n path.dirname(state.loaded.config.path),\n );\n const execution = await executeScript({\n client: state.client,\n workspaceId: targetWorkspaceId,\n name: `migration-test-assert-${namespace}.ts`,\n code: bundled.bundledCode,\n invoker: {\n namespace: auth.authNamespace,\n machineUserName: auth.machineUserName,\n },\n });\n if (!execution.success) {\n throw new Error(\n execution.error ?? `Migration assertion failed for namespace \"${namespace}\".`,\n );\n }\n },\n deleteWorkspace: async (workspaceId) => {\n const state = stateOrThrow(runtimeState);\n await state.client.deleteWorkspace({ workspaceId });\n },\n };\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { assertDefined } from \"#/utils/assert\";\nimport {\n assertCloneTargetRegion,\n assertTargetWorkspaceDiffers,\n createMigrationTestDependencies,\n resolveAssertionNamespace,\n} from \"./test-runtime\";\nimport type {\n MigrationTestDependencies,\n MigrationTestOptions,\n MigrationTestResult,\n} from \"./test-types\";\nexport type {\n MigrationTestDependencies,\n MigrationTestOptions,\n MigrationTestResult,\n PreparedMigrationTest,\n} from \"./test-types\";\n\n/**\n * Run pending migrations against an isolated target workspace.\n * @param options - Migration test options\n * @param dependencies - Runtime operations used by the migration test\n * @returns Migration test result\n */\nexport async function runMigrationTest(\n options: MigrationTestOptions,\n dependencies: MigrationTestDependencies = createMigrationTestDependencies(),\n): Promise<MigrationTestResult> {\n if (options.targetWorkspaceId && !options.yes) {\n throw new Error(\"--target-workspace-id requires --yes because the target may be overwritten.\");\n }\n if (options.keep && options.targetWorkspaceId) {\n throw new Error(\n \"--keep applies only to automatically created workspaces; a designated target is always retained.\",\n );\n }\n if (options.assertionNamespace && !options.assertionPath) {\n throw new Error(\"--assert is required when --assert-namespace is provided.\");\n }\n\n const prepared = await dependencies.prepare(options);\n assertTargetWorkspaceDiffers(prepared.sourceWorkspaceId, options.targetWorkspaceId);\n if (options.assertionPath) {\n resolveAssertionNamespace(prepared.pendingNamespaces, options.assertionNamespace);\n }\n if (options.data === \"clone\" && options.targetWorkspaceId) {\n const target = assertDefined(\n prepared.designatedTarget,\n \"designated clone target was not loaded during preparation\",\n );\n assertCloneTargetRegion(prepared.temporaryWorkspace.region, target.region);\n }\n const temporary = options.targetWorkspaceId === undefined;\n const workspace = temporary\n ? await dependencies.createWorkspace(prepared)\n : {\n id: assertDefined(options.targetWorkspaceId, \"designated target workspace missing\"),\n name: undefined,\n };\n let primaryError: unknown;\n let failed = false;\n let deleted = false;\n\n try {\n const target = { prepared, targetWorkspaceId: workspace.id };\n await dependencies.deployBaseline(target);\n\n const dataTarget = {\n ...target,\n sourceWorkspaceId: prepared.sourceWorkspaceId,\n applicationName: prepared.sourceApplicationName,\n };\n if (options.data === \"clone\") {\n await dependencies.cloneData(dataTarget);\n } else {\n await dependencies.seedData(dataTarget);\n }\n\n await dependencies.deployMigrations(target);\n if (options.assertionPath) {\n await dependencies.runAssertion({\n ...target,\n assertionPath: options.assertionPath,\n assertionNamespace: options.assertionNamespace,\n machineUser: options.machineUser,\n });\n }\n } catch (error) {\n primaryError = error;\n failed = true;\n }\n\n if (temporary && options.keep) {\n logger.info(`Keeping temporary workspace ${workspace.name ?? workspace.id}.`);\n } else if (temporary) {\n try {\n await dependencies.deleteWorkspace(workspace.id);\n deleted = true;\n } catch (cleanupError) {\n if (!failed) {\n throw new Error(\n `Failed to delete temporary workspace ${workspace.id}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n { cause: cleanupError },\n );\n }\n logger.warn(\n `Failed to delete temporary workspace ${workspace.id}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n );\n }\n }\n if (failed) {\n throw primaryError;\n }\n\n return {\n success: true,\n workspaceId: workspace.id,\n ...(workspace.name ? { workspaceName: workspace.name } : {}),\n temporary,\n deleted,\n data: options.data,\n pendingNamespaces: prepared.pendingNamespaces,\n };\n}\n\nasync function migrationTest(options: MigrationTestOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n const result = await runMigrationTest(options);\n if (options.json) {\n logger.out(result);\n return;\n }\n logger.success(\n `Pending migrations completed in workspace ${result.workspaceName ?? result.workspaceId}.`,\n );\n}\n\nexport const testCommand = defineAppCommand({\n name: \"test\",\n description:\n \"Test pending migrations with seed fixtures or cloned data in a temporary workspace.\",\n notes:\n \"The source workspace is read-only. Without --target-workspace-id, the command creates a workspace in the source workspace's region and deletes it after success or failure; pass --keep to retain it for inspection. A designated target is retained and requires --yes. Clone mode copies TailorDB records only; it does not copy IdP users or file blobs.\",\n args: z.strictObject({\n ...deploymentArgs,\n yes: arg(z.boolean().default(false), {\n alias: \"y\",\n description: \"Acknowledge that a designated target workspace may be overwritten\",\n }),\n data: arg(z.enum([\"seed\", \"clone\"]).default(\"seed\"), {\n description: \"Data source for the migration test (seed or clone)\",\n }),\n \"target-workspace-id\": arg(z.uuid().optional(), {\n description: \"Existing throwaway workspace to retain after the test (requires --yes)\",\n }),\n keep: arg(z.boolean().default(false), {\n description: \"Keep the automatically created workspace after the test\",\n }),\n assert: arg(z.string().optional(), {\n description: \"Path to a TypeScript assertion script to run after migrations\",\n completion: { type: \"file\", extensions: [\"ts\"] },\n }),\n \"assert-namespace\": arg(z.string().optional(), {\n description: \"TailorDB namespace exposed to the assertion script\",\n }),\n \"machine-user\": arg(z.string().optional(), {\n description: \"Machine user for seed and assertion script execution\",\n }),\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n await migrationTest({\n configPath: args.config,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n data: args.data,\n targetWorkspaceId: args[\"target-workspace-id\"],\n keep: args.keep,\n assertionPath: args.assert,\n assertionNamespace: args[\"assert-namespace\"],\n machineUser: args[\"machine-user\"],\n yes: args.yes,\n json: logger.jsonMode,\n });\n },\n});\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { assertUniqueLocalTailorDBTypeNames } from \"#/cli/services/tailordb/type-name-validation\";\nimport { deploymentArgs } from \"#/cli/shared/args\";\nimport { logBetaWarning } from \"#/cli/shared/beta\";\nimport { initOperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadAccessToken, loadWorkspaceId } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { PluginManager } from \"#/plugin/manager\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { getNamespacesWithMigrations, type NamespaceWithMigrations } from \"./config\";\nimport {\n formatDiffSummary,\n formatMigrationDiff,\n type MigrationDiff,\n type WarningChangeInfo,\n} from \"./diff-calculator\";\nimport { formatMigrationScriptCommand } from \"./hints\";\nimport {\n checkMigrationDiffs,\n logRemoteDriftGuidance,\n toTailorDBDeployInput,\n verifyRemoteSchema,\n type MigrationCheckResult,\n} from \"./schema-checks\";\nimport {\n assertValidMigrationFiles,\n formatMigrationNumber,\n formatSchemaDrifts,\n getMigrationFilePath,\n getMigrationFiles,\n loadDiff,\n reconstructSnapshotFromMigrations,\n} from \"./snapshot\";\nimport { MIGRATION_REVIEW_REQUIRED_MARKER } from \"./template-generator\";\nimport type {\n RemoteSchemaVerificationResult,\n RemoteSchemaVerificationSkipReason,\n SchemaDrift,\n} from \"./types\";\n\nexport interface ValidateOptions {\n configPath?: string;\n namespace?: string;\n workspaceId?: string;\n profile?: string;\n json?: boolean;\n strict?: boolean;\n}\n\ninterface MigrationFilesReport {\n valid: boolean;\n error?: string;\n}\n\ninterface LocalSchemaReport {\n hasDiff: boolean;\n /** Present when local types drifted from the latest migration snapshot; absent when the drift is a missing snapshot */\n diff?: MigrationDiff;\n}\n\ninterface CompletedRemoteSchemaReport {\n remoteMigrationNumber: number;\n hasDrift: boolean;\n drifts: SchemaDrift[];\n /** Set when the remote check could not run (no remote migration label, or no snapshot at the remote migration number) */\n skipped?: RemoteSchemaVerificationSkipReason;\n /** Set when the remote migration checkpoint does not exist in the local migration history */\n checkpointMissingLocal?: boolean;\n checkpointRepair?: { from: number; to: 0 };\n}\n\ninterface FailedRemoteSchemaReport {\n skipped: \"check_failed\";\n remoteMigrationNumber?: never;\n hasDrift?: never;\n drifts?: never;\n checkpointMissingLocal?: never;\n checkpointRepair?: never;\n}\n\ntype RemoteSchemaReport = CompletedRemoteSchemaReport | FailedRemoteSchemaReport;\n\ninterface UnacknowledgedWarningMigration {\n migrationNumber: number;\n warnings: WarningChangeInfo[];\n}\n\ninterface WarningAcknowledgmentsReport {\n valid: boolean;\n /** Pending migrations with data-loss warnings but no migrate.ts and no recorded acknowledgment */\n missing: UnacknowledgedWarningMigration[];\n}\n\ninterface NamespaceValidationReport {\n namespace: string;\n valid: boolean;\n migrationFiles: MigrationFilesReport;\n /** Omitted when the migration files are invalid (the check cannot run) */\n localSchema?: LocalSchemaReport;\n /** Omitted when the migration files are invalid */\n remoteSchema?: RemoteSchemaReport;\n /** Present only with --strict; omitted when the remote migration checkpoint is unknown */\n warningAcknowledgments?: WarningAcknowledgmentsReport;\n}\n\ninterface BuildValidationReportsOptions {\n targetNamespaces: NamespaceWithMigrations[];\n migrationFileErrors: Map<string, string>;\n localResults: MigrationCheckResult[];\n remoteResults?: RemoteSchemaVerificationResult[];\n /** Per-namespace candidates for the --strict warning acknowledgment check */\n unacknowledgedWarnings?: Map<string, UnacknowledgedWarningMigration[]>;\n}\n\ninterface CollectedValidationReports {\n reports: NamespaceValidationReport[];\n remoteError?: unknown;\n}\n\n/**\n * Walk the local migration history once to assert that every required\n * migration script exists, no migration carries both a --no-script\n * acknowledgment and a migrate.ts, and generated normalization logic has\n * been reviewed, and to collect migrations with data-loss warnings that\n * have neither a migrate.ts nor a recorded --no-script acknowledgment\n * @param {string} migrationsDir - Migrations directory path\n * @param {string} namespace - TailorDB namespace (for error messages)\n * @param {string} [configPath] - Config path the current run used (for remediation hints)\n * @returns {UnacknowledgedWarningMigration[]} Unacknowledged warning migrations in the local history\n */\nfunction assertMigrationScriptsReady(\n migrationsDir: string,\n namespace: string,\n configPath?: string,\n): UnacknowledgedWarningMigration[] {\n const missing: number[] = [];\n const conflicting: number[] = [];\n const unreviewed: number[] = [];\n const unacknowledgedWarnings: UnacknowledgedWarningMigration[] = [];\n for (const file of getMigrationFiles(migrationsDir)) {\n if (file.type !== \"diff\") continue;\n const diff = loadDiff(file.path);\n const migrateFilePath = getMigrationFilePath(migrationsDir, file.number, \"migrate\");\n const hasScript = fs.existsSync(migrateFilePath);\n if (diff.requiresMigrationScript && !diff.scriptSkipped && !hasScript) {\n missing.push(file.number);\n }\n if (diff.scriptSkipped && hasScript) {\n conflicting.push(file.number);\n }\n if (\n hasScript &&\n fs.readFileSync(migrateFilePath, \"utf8\").includes(MIGRATION_REVIEW_REQUIRED_MARKER)\n ) {\n unreviewed.push(file.number);\n }\n if (diff.hasWarnings && !diff.scriptSkipped && !hasScript) {\n unacknowledgedWarnings.push({ migrationNumber: file.number, warnings: diff.warnings });\n }\n }\n if (missing.length > 0) {\n throw new Error(\n `Migration(s) ${missing.map(formatMigrationNumber).join(\", \")} in namespace \"${namespace}\" ` +\n \"require a migration script but have no migrate.ts. \" +\n \"Add one with 'tailor tailordb migration script <number>', or record that no script \" +\n `is needed with 'tailor tailordb migration script <number> --no-script --reason \"...\"'.`,\n );\n }\n if (conflicting.length > 0) {\n const clearCommands = conflicting\n .map(\n (migrationNumber) =>\n ` ${formatMigrationScriptCommand({ migrationNumber, namespace, configPath })}`,\n )\n .join(\"\\n\");\n throw new Error(\n `Migration(s) ${conflicting.map(formatMigrationNumber).join(\", \")} in namespace \"${namespace}\" ` +\n \"have both a --no-script skip acknowledgment and migrate.ts. \" +\n \"Clear the stale acknowledgment(s):\\n\" +\n `${clearCommands}\\n` +\n \"Or delete migrate.ts to keep the skip.\",\n );\n }\n if (unreviewed.length > 0) {\n throw new Error(\n `Migration(s) ${unreviewed.map(formatMigrationNumber).join(\", \")} in namespace \"${namespace}\" ` +\n \"contain generated normalization logic that still requires review in migrate.ts. \" +\n `Review each ${MIGRATION_REVIEW_REQUIRED_MARKER} marker, then remove the marker and its associated ` +\n \"`never` annotation.\",\n );\n }\n return unacknowledgedWarnings;\n}\n\n/**\n * Build per-namespace reports from the checks that completed\n * @param {BuildValidationReportsOptions} options - Completed validation results\n * @returns {NamespaceValidationReport[]} Validation reports per namespace\n */\nfunction buildValidationReports(\n options: BuildValidationReportsOptions,\n): NamespaceValidationReport[] {\n const {\n targetNamespaces,\n migrationFileErrors,\n localResults,\n remoteResults,\n unacknowledgedWarnings,\n } = options;\n\n return targetNamespaces.map((target) => {\n const fileError = migrationFileErrors.get(target.namespace);\n if (fileError !== undefined) {\n return {\n namespace: target.namespace,\n valid: false,\n migrationFiles: { valid: false, error: fileError },\n };\n }\n\n const local = assertDefined(\n localResults.find((result) => result.namespace === target.namespace),\n `local schema check result missing for namespace \"${target.namespace}\"`,\n );\n const localSchema: LocalSchemaReport = {\n hasDiff: local.hasDiff,\n ...(local.diff ? { diff: local.diff } : {}),\n };\n if (remoteResults === undefined) {\n return {\n namespace: target.namespace,\n valid: false,\n migrationFiles: { valid: true },\n localSchema,\n remoteSchema: { skipped: \"check_failed\" },\n };\n }\n\n const remote = assertDefined(\n remoteResults.find((result) => result.namespace === target.namespace),\n `remote schema check result missing for namespace \"${target.namespace}\"`,\n );\n const checkpointMissingLocal = remote.checkpointMissingLocal === true;\n const remoteSchema: RemoteSchemaReport = {\n remoteMigrationNumber: remote.remoteMigrationNumber,\n hasDrift: remote.hasDrift,\n drifts: remote.drifts,\n ...(remote.skipped ? { skipped: remote.skipped } : {}),\n ...(checkpointMissingLocal ? { checkpointMissingLocal: true } : {}),\n ...(remote.checkpointRepair ? { checkpointRepair: remote.checkpointRepair } : {}),\n };\n\n // Only migrations not yet applied to the remote need an acknowledgment;\n // for applied ones the data is already gone and there is nothing to act on.\n const candidates = unacknowledgedWarnings?.get(target.namespace);\n let warningAcknowledgments: WarningAcknowledgmentsReport | undefined;\n if (candidates !== undefined) {\n const missing = candidates.filter(\n (candidate) => candidate.migrationNumber > remote.remoteMigrationNumber,\n );\n warningAcknowledgments = { valid: missing.length === 0, missing };\n }\n\n return {\n namespace: target.namespace,\n valid:\n !localSchema.hasDiff &&\n !remoteSchema.hasDrift &&\n !checkpointMissingLocal &&\n warningAcknowledgments?.valid !== false,\n migrationFiles: { valid: true },\n localSchema,\n remoteSchema,\n ...(warningAcknowledgments ? { warningAcknowledgments } : {}),\n };\n });\n}\n\n/**\n * Run all migration validation checks and collect per-namespace reports\n * @param {ValidateOptions} options - Command options\n * @returns {Promise<CollectedValidationReports>} Validation reports and any remote error\n */\nasync function collectValidationReports(\n options: ValidateOptions,\n): Promise<CollectedValidationReports> {\n const { config, plugins } = await loadConfig(options.configPath);\n const configDir = path.dirname(config.path);\n\n const namespacesWithMigrations = getNamespacesWithMigrations(config, configDir);\n if (namespacesWithMigrations.length === 0) {\n throw new Error(\"No TailorDB services with migrations configuration found\");\n }\n\n const targetNamespaces = options.namespace\n ? namespacesWithMigrations.filter((ns) => ns.namespace === options.namespace)\n : namespacesWithMigrations;\n if (targetNamespaces.length === 0) {\n throw new Error(\n `Namespace \"${options.namespace}\" not found or does not have migrations configured`,\n );\n }\n\n const pluginManager = plugins.length > 0 ? new PluginManager(plugins) : undefined;\n const { defineApplication } = await import(\"#/cli/services/application\");\n const application = defineApplication({ config, pluginManager });\n // Load every namespace (not just the targets): plugins registered while\n // types load may contribute types to the target namespaces.\n for (const service of application.tailorDBServices) {\n await service.loadTypes();\n await service.processNamespacePlugins();\n }\n assertUniqueLocalTailorDBTypeNames({ tailorDBServices: application.tailorDBServices });\n for (const { namespace } of targetNamespaces) {\n if (!application.tailorDBServices.some((s) => s.namespace === namespace)) {\n throw new Error(`No TailorDB service found for namespace \"${namespace}\"`);\n }\n }\n const tailorDBInputs = application.tailorDBServices.map(toTailorDBDeployInput);\n const typesByNamespace = new Map(tailorDBInputs.map((input) => [input.namespace, input.types]));\n\n const migrationFileErrors = new Map<string, string>();\n const checkableNamespaces: NamespaceWithMigrations[] = [];\n const unacknowledgedWarnings = options.strict\n ? new Map<string, UnacknowledgedWarningMigration[]>()\n : undefined;\n for (const target of targetNamespaces) {\n try {\n assertValidMigrationFiles(target.migrationsDir, target.namespace);\n // Parse the whole history here so malformed snapshot/diff contents are\n // reported per namespace instead of aborting the run for every namespace.\n reconstructSnapshotFromMigrations(target.migrationsDir);\n const namespaceWarnings = assertMigrationScriptsReady(\n target.migrationsDir,\n target.namespace,\n options.configPath,\n );\n unacknowledgedWarnings?.set(target.namespace, namespaceWarnings);\n checkableNamespaces.push(target);\n } catch (error) {\n migrationFileErrors.set(\n target.namespace,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n\n const localResults = await checkMigrationDiffs(typesByNamespace, checkableNamespaces);\n const localReportOptions = {\n targetNamespaces,\n migrationFileErrors,\n localResults,\n ...(unacknowledgedWarnings ? { unacknowledgedWarnings } : {}),\n };\n\n if (checkableNamespaces.length === 0) {\n return {\n reports: buildValidationReports(localReportOptions),\n };\n }\n\n let remoteResults: RemoteSchemaVerificationResult[];\n try {\n const accessToken = await loadAccessToken({\n profile: options.profile,\n });\n const client = await initOperatorClient(accessToken);\n const workspaceId = await loadWorkspaceId({\n workspaceId: options.workspaceId,\n profile: options.profile,\n });\n remoteResults = await verifyRemoteSchema(\n client,\n workspaceId,\n checkableNamespaces,\n config,\n tailorDBInputs,\n );\n } catch (remoteError) {\n return {\n reports: buildValidationReports(localReportOptions),\n remoteError,\n };\n }\n\n return {\n reports: buildValidationReports({ ...localReportOptions, remoteResults }),\n };\n}\n\nfunction printValidationReports(reports: NamespaceValidationReport[]): void {\n for (const report of reports) {\n logger.newline();\n logger.info(`Namespace: ${styles.bold(report.namespace)}`);\n\n if (!report.migrationFiles.valid) {\n logger.log(` Migration files: ${styles.error(\"invalid\")}`);\n logger.log(` ${report.migrationFiles.error}`);\n continue;\n }\n logger.log(` Migration files: ${styles.success(\"OK\")}`);\n\n const local = report.localSchema;\n if (local?.hasDiff) {\n if (local.diff) {\n logger.log(` Local schema: ${styles.error(\"changes not in migration files\")}`);\n logger.log(` ${formatDiffSummary(local.diff)}`);\n logger.log(formatMigrationDiff(local.diff));\n } else {\n logger.log(` Local schema: ${styles.error(\"no migration snapshot found\")}`);\n }\n } else {\n logger.log(` Local schema: ${styles.success(\"OK\")}`);\n }\n\n const remote = report.remoteSchema;\n if (remote?.skipped === \"check_failed\") {\n logger.log(` Remote schema: ${styles.error(\"not checked\")}`);\n } else if (remote?.checkpointRepair) {\n logger.log(\n ` Remote schema: ${styles.success(\"OK\")} (next deploy will reset the checkpoint to 0000 from ${formatMigrationNumber(remote.checkpointRepair.from)})`,\n );\n } else if (remote?.checkpointMissingLocal) {\n logger.log(\n ` Remote schema: ${styles.error(\n `remote migration ${formatMigrationNumber(remote.remoteMigrationNumber)} is not in the local migration history`,\n )}`,\n );\n } else if (remote?.hasDrift) {\n logger.log(\n ` Remote schema: ${styles.error(\"drift detected\")} (remote migration: ${formatMigrationNumber(remote.remoteMigrationNumber)})`,\n );\n logger.log(formatSchemaDrifts(remote.drifts));\n } else if (remote?.skipped === \"not_deployed\") {\n logger.log(` Remote schema: ${styles.dim(\"skipped (namespace not deployed)\")}`);\n } else if (remote?.skipped === \"no_migration_label\") {\n logger.log(\n ` Remote schema: ${styles.dim(\"skipped (deployed namespace has no migration state)\")}`,\n );\n } else if (remote?.skipped === \"no_snapshot\") {\n logger.log(\n ` Remote schema: ${styles.dim(`skipped (no local snapshot for remote migration ${formatMigrationNumber(remote.remoteMigrationNumber)})`)}`,\n );\n } else if (remote) {\n logger.log(\n ` Remote schema: ${styles.success(\"OK\")} (remote migration: ${formatMigrationNumber(remote.remoteMigrationNumber)})`,\n );\n }\n\n const acknowledgments = report.warningAcknowledgments;\n if (acknowledgments) {\n if (acknowledgments.valid) {\n logger.log(` Warning acknowledgments: ${styles.success(\"OK\")}`);\n } else {\n logger.log(\n ` Warning acknowledgments: ${styles.error(\"missing for pending migration(s) with possible data loss\")}`,\n );\n for (const migration of acknowledgments.missing) {\n const label = formatMigrationNumber(migration.migrationNumber);\n for (const warning of migration.warnings) {\n const field = warning.fieldName ? `.${warning.fieldName}` : \"\";\n logger.log(` ${label}: ${warning.tableName}${field}: ${warning.reason}`);\n }\n }\n }\n }\n }\n logger.newline();\n}\n\nfunction printResolutionHints(reports: NamespaceValidationReport[], configPath?: string): void {\n if (reports.some((r) => r.localSchema?.hasDiff && !r.localSchema.diff)) {\n logger.info(\"Run 'tailor tailordb migration generate' to create the initial snapshot.\");\n }\n if (reports.some((r) => r.localSchema?.diff)) {\n logger.info(\"Run 'tailor tailordb migration generate' to create migration files.\");\n }\n if (reports.some((r) => r.remoteSchema?.checkpointMissingLocal)) {\n logger.info(\n \"The remote migration checkpoint is ahead of the local history. Pull the latest migration files, or run 'tailor tailordb migration status' to compare.\",\n );\n }\n if (reports.some((r) => r.remoteSchema?.hasDrift)) {\n logRemoteDriftGuidance();\n }\n const missingAcknowledgments = reports.filter(\n (r) => r.warningAcknowledgments && !r.warningAcknowledgments.valid,\n );\n if (missingAcknowledgments.length > 0) {\n logger.info(\n \"For each migration listed, either add a data migration script with 'tailor tailordb migration script <number>' or record why none is needed:\",\n );\n for (const report of missingAcknowledgments) {\n for (const migration of report.warningAcknowledgments?.missing ?? []) {\n logger.info(\n ` ${formatMigrationScriptCommand({\n migrationNumber: migration.migrationNumber,\n namespace: report.namespace,\n configPath,\n noScript: true,\n })}`,\n { mode: \"plain\" },\n );\n }\n }\n }\n}\n\n/**\n * Validate migration files and schema state without deploying\n * @param {ValidateOptions} options - Command options\n */\nasync function validate(options: ValidateOptions): Promise<void> {\n logBetaWarning(\"tailordb migration\");\n\n const collected = await collectValidationReports(options);\n const { reports } = collected;\n const invalidCount = reports.filter((r) => !r.valid).length;\n\n if (options.json) {\n logger.out(reports);\n } else {\n printValidationReports(reports);\n if (invalidCount === 0 && !(\"remoteError\" in collected)) {\n logger.success(\"All migration validation checks passed.\");\n } else {\n printResolutionHints(reports, options.configPath);\n }\n }\n\n if (\"remoteError\" in collected) {\n throw collected.remoteError;\n }\n if (invalidCount > 0) {\n throw new Error(`Migration validation failed for ${invalidCount} namespace(s)`);\n }\n}\n\nexport const validateCommand = defineAppCommand({\n name: \"validate\",\n description:\n \"Validate the full migration history, unreviewed generated migration scripts, and schema drift (local types vs. migration snapshot, remote schema vs. migration checkpoint) without deploying. This includes the migration and schema-drift checks used by 'deploy' and exits with a non-zero code when issues are found.\",\n args: z.strictObject({\n ...deploymentArgs,\n namespace: arg(z.string().optional(), {\n alias: \"n\",\n description: \"Target TailorDB namespace (validates all namespaces if not specified)\",\n }),\n strict: arg(z.boolean().default(false), {\n description: \"Also fail when a pending migration can drop data without an acknowledgment\",\n }),\n }),\n run: async (args) => {\n await validate({\n configPath: args.config,\n namespace: args.namespace,\n workspaceId: args[\"workspace-id\"],\n profile: args.profile,\n json: logger.jsonMode,\n strict: args.strict,\n });\n },\n});\n","/**\n * TailorDB migration command\n *\n * Subcommands:\n * - generate: Generate migration files from schema differences\n * - rebaseline: Collapse the full migration history into a new baseline\n * - script: Add a migrate.ts template to an existing migration\n * - set: Set migration checkpoint to a specific number\n * - status: Show migration status for TailorDB namespaces\n * - sync: Sync remote TailorDB schema to a specific migration snapshot\n * - test: Test pending migrations in an isolated workspace\n * - validate: Validate migration files and detect schema drift without deploying\n */\n\nimport { defineCommand } from \"politty\";\nimport { generateCommand } from \"./generate\";\nimport { rebaselineCommand } from \"./rebaseline\";\nimport { scriptCommand } from \"./script\";\nimport { setCommand } from \"./set\";\nimport { statusCommand } from \"./status\";\nimport { syncCommand } from \"./sync\";\nimport { testCommand } from \"./test\";\nimport { validateCommand } from \"./validate\";\n\nexport const migrationCommand = defineCommand({\n name: \"migration\",\n description: \"Manage TailorDB schema migrations.\",\n subCommands: {\n generate: generateCommand,\n rebaseline: rebaselineCommand,\n script: scriptCommand,\n set: setCommand,\n status: statusCommand,\n sync: syncCommand,\n test: testCommand,\n validate: validateCommand,\n },\n});\n\nexport { generateCommand } from \"./generate\";\nexport { rebaselineCommand } from \"./rebaseline\";\nexport { scriptCommand } from \"./script\";\nexport { setCommand } from \"./set\";\nexport { statusCommand } from \"./status\";\nexport { syncCommand } from \"./sync\";\nexport { testCommand } from \"./test\";\nexport { validateCommand } from \"./validate\";\n","import { defineCommand } from \"politty\";\nimport { migrationCommand } from \"./migrate\";\nimport { truncateCommand } from \"./truncate\";\n\nexport const tailordbCommand = defineCommand({\n name: \"tailordb\",\n description: \"Manage TailorDB tables and data.\",\n notes:\n \"The `tailordb erd` commands are provided by the @tailor-platform/sdk-plugin-tailordb-erd CLI plugin.\",\n subCommands: {\n truncate: truncateCommand,\n migration: migrationCommand,\n },\n});\n","import * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\n\nexport const upgradeCommand = defineAppCommand({\n name: \"upgrade\",\n description: \"Run codemods to upgrade your project to a newer SDK version.\",\n args: z.strictObject({\n from: arg(z.string(), {\n description: \"SDK version before the upgrade (e.g., 1.33.0)\",\n }),\n \"dry-run\": arg(z.boolean().default(false), {\n alias: \"d\",\n description: \"Preview changes without modifying files\",\n }),\n path: arg(z.string().default(\".\"), {\n description: \"Project directory to upgrade\",\n completion: { type: \"directory\" },\n }),\n }),\n run: async (args) => {\n const { initTelemetry } = await import(\"#/cli/telemetry/index\");\n await initTelemetry();\n\n const { upgrade } = await import(\"./service\");\n await upgrade({\n from: args.from,\n dryRun: args[\"dry-run\"],\n path: path.resolve(args.path),\n });\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n hasUserTokenEntry,\n platformConfigFromProfile,\n readPlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\nexport const currentCommand = defineAppCommand({\n name: \"current\",\n description: \"Show current user.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const profile = process.env.TAILOR_PLATFORM_PROFILE;\n const profileEntry = profile ? config.profiles[profile] : undefined;\n if (profile && !profileEntry) {\n throw new Error(`Profile \"${profile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const currentUser = profile ? (profileEntry?.user ?? null) : config.current_user;\n const jsonOutput = logger.jsonMode;\n\n // Check if current user is set\n if (!currentUser) {\n throw new Error(ml`\n Current user not set.\n Please login first using 'tailor login' command to register a user.\n `);\n }\n\n // Check if user exists\n if (!hasUserTokenEntry(config, currentUser, platformConfig)) {\n throw new Error(ml`\n Current user '${currentUser}' not found in registered users.\n Please login again using 'tailor login' command to register the user.\n `);\n }\n\n if (jsonOutput) {\n logger.out({ user: currentUser });\n return;\n }\n\n logger.out(currentUser);\n },\n});\n","import { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n resolveUserTokenKey,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\ntype PlatformConfig = Awaited<ReturnType<typeof readPlatformConfig>>;\n\ntype UserListInfo = {\n user: string;\n platformUrl: string | null;\n current: boolean;\n};\n\nfunction activeCurrentUserKey(config: PlatformConfig): string | null {\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n if (!activeProfile) {\n if (!config.current_user) return null;\n return resolveUserTokenKey(config, config.current_user);\n }\n const profile = config.profiles[activeProfile];\n if (!profile) return null;\n return resolveUserTokenKey(config, profile.user, platformConfigFromProfile(profile));\n}\n\nfunction toUserListInfo(userKey: string, currentUserKey: string | null): UserListInfo {\n const separatorIndex = userKey.indexOf(\"|\");\n const platformUrl = separatorIndex === -1 ? null : userKey.slice(0, separatorIndex);\n const user = separatorIndex === -1 ? userKey : userKey.slice(separatorIndex + 1);\n return {\n user,\n platformUrl,\n current: currentUserKey === userKey,\n };\n}\n\nfunction formatUserListInfo(info: UserListInfo): string {\n return `${info.user}${info.platformUrl ? ` [${info.platformUrl}]` : \"\"}${\n info.current ? \" (current)\" : \"\"\n }`;\n}\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all users.\",\n args: z.strictObject({}),\n run: async () => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n\n const users = Object.keys(config.users);\n if (users.length === 0) {\n logger.info(ml`\n No users found.\n Please login first using 'tailor login' command to register a user.\n `);\n if (jsonOutput) {\n logger.out([]);\n }\n return;\n }\n\n const currentUserKey = activeCurrentUserKey(config);\n const userInfos = users.map((user) => toUserListInfo(user, currentUserKey));\n if (jsonOutput) {\n logger.out([...new Set(userInfos.map((userInfo) => userInfo.user))]);\n return;\n }\n\n userInfos.forEach((userInfo) => {\n if (userInfo.current) {\n logger.success(formatUserListInfo(userInfo), { mode: \"plain\" });\n } else {\n logger.log(formatUserListInfo(userInfo));\n }\n });\n },\n});\n","import { PATScope } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\nimport type { PersonalAccessToken } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n\nexport interface PersonalAccessTokenInfo {\n name: string;\n scopes: string[];\n}\n\nfunction patScopeToString(scope: PATScope): string {\n switch (scope) {\n case PATScope.PAT_SCOPE_READ:\n return \"read\";\n case PATScope.PAT_SCOPE_WRITE:\n return \"write\";\n default:\n return \"unknown\";\n }\n}\n\n/**\n * Transform a PersonalAccessToken into CLI-friendly info.\n * @param pat - Personal access token resource\n * @returns Flattened token info\n */\nexport function transformPersonalAccessToken(pat: PersonalAccessToken): PersonalAccessTokenInfo {\n return {\n name: pat.name,\n scopes: pat.scopes.map(patScopeToString),\n };\n}\n\n/**\n * Get PAT scopes from a write flag.\n * @param write - Whether write access is required\n * @returns Scopes to apply to the token\n */\nexport function getScopesFromWriteFlag(write: boolean): PATScope[] {\n return write ? [PATScope.PAT_SCOPE_READ, PATScope.PAT_SCOPE_WRITE] : [PATScope.PAT_SCOPE_READ];\n}\n\nfunction getScopeStringsFromWriteFlag(write: boolean): string[] {\n return write ? [\"read\", \"write\"] : [\"read\"];\n}\n\n/**\n * Print the created or updated personal access token to the logger.\n * @param name - Token name\n * @param token - Token value\n * @param write - Whether the token has write scope\n * @param action - Action performed\n */\nexport function printCreatedToken(\n name: string,\n token: string,\n write: boolean,\n action: \"created\" | \"updated\",\n): void {\n const scopes = getScopeStringsFromWriteFlag(write);\n\n if (logger.jsonMode) {\n logger.out({ name, scopes, token });\n } else {\n logger.log(ml`\n Personal access token ${action} successfully.\n\n name: ${name}\n scopes: ${scopes.join(\"/\")}\n token: ${token}\n\n Please save this token in a secure location. You won't be able to see it again.\n `);\n }\n}\n","import { initOperatorClient } from \"#/cli/shared/client\";\nimport {\n fetchLatestToken,\n platformConfigFromProfile,\n readPlatformConfig,\n} from \"#/cli/shared/context\";\n\ntype PlatformConfig = Awaited<ReturnType<typeof readPlatformConfig>>;\n\nexport function resolvePatUser(config: PlatformConfig): string | null {\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n if (activeProfile) {\n return config.profiles[activeProfile]?.user ?? null;\n }\n return config.current_user;\n}\n\nexport async function createPatOperatorClient() {\n const config = await readPlatformConfig();\n const activeProfile = process.env.TAILOR_PLATFORM_PROFILE;\n const profileEntry = activeProfile ? config.profiles[activeProfile] : undefined;\n if (activeProfile && !profileEntry) {\n throw new Error(`Profile \"${activeProfile}\" not found`);\n }\n const platformConfig = profileEntry ? platformConfigFromProfile(profileEntry) : undefined;\n const user = resolvePatUser(config);\n\n if (!user) {\n throw new Error(\"No user logged in.\\nPlease login first using 'tailor login' command.\");\n }\n\n const { accessToken } = await fetchLatestToken(config, user, platformConfig);\n return await initOperatorClient(accessToken, platformConfig);\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getScopesFromWriteFlag, printCreatedToken } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const createCommand = defineAppCommand({\n name: \"create\",\n description: \"Create a new personal access token.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n write: arg(z.boolean().default(false), {\n alias: \"W\",\n description: \"Grant write permission (default: read-only)\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n const scopes = getScopesFromWriteFlag(args.write);\n const result = await client.createPersonalAccessToken({\n name: args.name,\n scopes,\n });\n\n if (!result.accessToken) {\n throw new Error(\"Failed to create personal access token\");\n }\n\n printCreatedToken(args.name, result.accessToken, args.write, \"created\");\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const deleteCommand = defineAppCommand({\n name: \"delete\",\n description: \"Delete a personal access token.\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n await client.deletePersonalAccessToken({\n name: args.name,\n });\n\n logger.success(`Personal access token \"${args.name}\" deleted successfully.`);\n },\n});\n","import { z } from \"zod\";\nimport { paginationArgs, toPageDirection } from \"#/cli/shared/args\";\nimport { fetchPaged } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\nimport { transformPersonalAccessToken, type PersonalAccessTokenInfo } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const listCommand = defineAppCommand({\n name: \"list\",\n description: \"List all personal access tokens.\",\n args: z.strictObject({ ...paginationArgs() }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const client = await createPatOperatorClient();\n\n const pageDirection = toPageDirection(args.order);\n const pats = await fetchPaged(\n async (pageToken, pageSize) => {\n const { personalAccessTokens, nextPageToken } = await client.listPersonalAccessTokens({\n pageToken,\n pageSize,\n pageDirection,\n });\n return [personalAccessTokens, nextPageToken];\n },\n { limit: args.limit },\n );\n\n if (pats.length === 0) {\n logger.info(ml`\n No personal access tokens found.\n Please create a token using 'tailor user pat create' command.\n `);\n if (!jsonOutput) {\n return;\n }\n }\n\n const patInfos: PersonalAccessTokenInfo[] = pats.map(transformPersonalAccessToken);\n if (jsonOutput) {\n logger.out(patInfos);\n return;\n }\n\n // Text format: aligned list \"name: scope1/scope2\"\n const maxNameLength = Math.max(...pats.map((pat) => pat.name.length));\n\n pats.forEach((pat) => {\n const info = transformPersonalAccessToken(pat);\n const paddedName = info.name.padStart(maxNameLength);\n logger.log(`${paddedName}: ${info.scopes.join(\"/\")}`);\n });\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { assertWritable } from \"#/cli/shared/readonly-guard\";\nimport { getScopesFromWriteFlag, printCreatedToken } from \"./transform\";\nimport { createPatOperatorClient } from \"./user\";\n\nexport const updateCommand = defineAppCommand({\n name: \"update\",\n description: \"Update a personal access token (delete and recreate).\",\n args: z.strictObject({\n name: arg(z.string(), {\n positional: true,\n description: \"Token name\",\n }),\n write: arg(z.boolean().default(false), {\n alias: \"W\",\n description: \"Grant write permission (if not specified, keeps read-only)\",\n }),\n }),\n run: async (args) => {\n await assertWritable();\n const client = await createPatOperatorClient();\n\n // Delete the existing token\n await client.deletePersonalAccessToken({\n name: args.name,\n });\n\n // Create a new token with the same name\n const scopes = getScopesFromWriteFlag(args.write);\n const result = await client.createPersonalAccessToken({\n name: args.name,\n scopes,\n });\n\n if (!result.accessToken) {\n throw new Error(\"Failed to create personal access token\");\n }\n\n printCreatedToken(args.name, result.accessToken, args.write, \"updated\");\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { listCommand } from \"./list\";\nimport { updateCommand } from \"./update\";\n\nexport const patCommand = defineCommand({\n name: \"pat\",\n description: \"Manage personal access tokens.\",\n subCommands: {\n list: listCommand,\n create: createCommand,\n delete: deleteCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport {\n platformConfigFromProfile,\n readPlatformConfig,\n resolveConfigUser,\n writePlatformConfig,\n} from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\nimport ml from \"#/utils/multiline\";\n\nexport const switchCommand = defineAppCommand({\n name: \"switch\",\n description: \"Set current user.\",\n args: z.strictObject({\n user: arg(z.string(), {\n positional: true,\n description: \"User email address or machine user client ID\",\n }),\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const activeProfileName = process.env.TAILOR_PLATFORM_PROFILE;\n const activeProfileEntry = activeProfileName ? config.profiles[activeProfileName] : undefined;\n if (activeProfileName && !activeProfileEntry) {\n throw new Error(`Profile \"${activeProfileName}\" not found`);\n }\n const platformConfig = activeProfileEntry\n ? platformConfigFromProfile(activeProfileEntry)\n : undefined;\n\n if (args.user.includes(\"|\")) {\n throw new Error(\n `User \"${args.user}\" looks like a platform-scoped token key. Pass the user name without the platform URL and select the platform with TAILOR_PLATFORM_URL or a profile.`,\n );\n }\n\n const user = resolveConfigUser(config, args.user, platformConfig);\n if (!user) {\n throw new Error(ml`\n User \"${args.user}\" not found.\n Please login first using 'tailor login' command to register this user.\n `);\n }\n\n if (activeProfileEntry) {\n activeProfileEntry.user = user;\n } else {\n config.current_user = user;\n }\n writePlatformConfig(config);\n\n logger.success(`Current user set to \"${user}\" successfully.`);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { currentCommand } from \"./current\";\nimport { listCommand } from \"./list\";\nimport { patCommand } from \"./pat\";\nimport { switchCommand } from \"./switch\";\n\nexport const userCommand = defineCommand({\n name: \"user\",\n description: \"Manage Tailor Platform users.\",\n subCommands: {\n current: currentCommand,\n list: listCommand,\n switch: switchCommand,\n pat: patCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { executionsCommand } from \"./executions\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { resumeCommand } from \"./resume\";\nimport { startCommand } from \"./start\";\nimport { waitCommand } from \"./wait\";\n\nexport const workflowCommand = defineCommand({\n name: \"workflow\",\n description: \"Manage workflows and workflow executions.\",\n subCommands: {\n list: listCommand,\n get: getCommand,\n start: startCommand,\n wait: waitCommand,\n executions: executionsCommand,\n resume: resumeCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { healthCommand } from \"./health\";\nimport { listCommand } from \"./list\";\n\nexport const appCommand = defineCommand({\n name: \"app\",\n description: \"Manage workspace applications\",\n subCommands: {\n health: healthCommand,\n list: listCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { inviteCommand } from \"./invite\";\nimport { listCommand } from \"./list\";\nimport { removeCommand } from \"./remove\";\nimport { updateCommand } from \"./update\";\n\nexport const userCommand = defineCommand({\n name: \"user\",\n description: \"Manage workspace users\",\n subCommands: {\n invite: inviteCommand,\n list: listCommand,\n remove: removeCommand,\n update: updateCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","import { defineCommand, runCommand } from \"politty\";\nimport { appCommand } from \"./app\";\nimport { createCommand } from \"./create\";\nimport { deleteCommand } from \"./delete\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { restoreCommand } from \"./restore\";\nimport { userCommand } from \"./user\";\n\nexport const workspaceCommand = defineCommand({\n name: \"workspace\",\n description: \"Manage Tailor Platform workspaces.\",\n subCommands: {\n app: appCommand,\n create: createCommand,\n delete: deleteCommand,\n get: getCommand,\n list: listCommand,\n restore: restoreCommand,\n user: userCommand,\n },\n async run() {\n await runCommand(listCommand, []);\n },\n});\n","#!/usr/bin/env node\n\nimport { dirname, resolve } from \"pathe\";\nimport { resolvePackageJSON } from \"pkg-types\";\nimport { defineCommand, runCommand, runMain, type AnyCommand } from \"politty\";\nimport { withCompletionCommand } from \"politty/completion\";\nimport { withSkillCommand } from \"politty/skill\";\nimport { z } from \"zod\";\nimport { apiCommand } from \"./commands/api\";\nimport { authCommand } from \"./commands/auth\";\nimport { authconnectionCommand } from \"./commands/authconnection\";\nimport { crashReportCommand } from \"./commands/crashreport\";\nimport { deployCommand } from \"./commands/deploy\";\nimport { executorCommand } from \"./commands/executor\";\nimport { functionCommand } from \"./commands/function\";\nimport { generateCommand } from \"./commands/generate\";\nimport { initCommand } from \"./commands/init\";\nimport { loginCommand } from \"./commands/login\";\nimport { logoutCommand } from \"./commands/logout\";\nimport { machineuserCommand } from \"./commands/machineuser\";\nimport { oauth2clientCommand } from \"./commands/oauth2client\";\nimport { openCommand } from \"./commands/open\";\nimport { organizationCommand } from \"./commands/organization\";\nimport { pluginCommand } from \"./commands/plugin\";\nimport { profileCommand } from \"./commands/profile\";\nimport { removeCommand } from \"./commands/remove\";\nimport { secretCommand } from \"./commands/secret\";\nimport { setupCommand } from \"./commands/setup\";\nimport { showCommand } from \"./commands/show\";\nimport { staticwebsiteCommand } from \"./commands/staticwebsite\";\nimport { tailordbCommand } from \"./commands/tailordb\";\nimport { upgradeCommand } from \"./commands/upgrade\";\nimport { userCommand } from \"./commands/user\";\nimport { workflowCommand } from \"./commands/workflow\";\nimport { workspaceCommand } from \"./commands/workspace\";\nimport { initCrashReporting } from \"./crashreport\";\nimport { queryCommand } from \"./query\";\nimport { commonArgs, isVerbose } from \"./shared/args\";\nimport { serializeError } from \"./shared/error-json\";\nimport { isCLIError, typeOnlyImportHint } from \"./shared/errors\";\nimport { logger, styles } from \"./shared/logger\";\nimport { readPackageJson } from \"./shared/package-json\";\nimport { dispatchPluginWithInstallHint } from \"./shared/plugin\";\nimport { registerTsHook } from \"./shared/register-ts-hook\";\n\nawait registerTsHook(new URL(\"./ts-hook.mjs\", import.meta.url));\n\n// Runs before globalArgs effects load --env-file, so env file overrides for\n// TAILOR_CRASH_REPORTS_* are not available for early startup failures.\n// This is intentional: we want crash reporting active before argument parsing,\n// and env files require parsing to be complete. Shell-level env vars still work.\ninitCrashReporting();\n\nconst packageJson = await readPackageJson();\nconst cliName = Object.keys(packageJson.bin ?? {})[0] || \"tailor\";\nconst packageName = packageJson.name ?? \"@tailor-platform/sdk\";\nconst packageJsonPath = await resolvePackageJSON(import.meta.url);\nconst bundledSkillsDir = resolve(dirname(packageJsonPath), \"agent-skills\");\n\nfunction defaultSkillsRunToAdd(command: AnyCommand): AnyCommand {\n const add = (command.subCommands ?? {}).add as AnyCommand;\n return {\n ...command,\n async run() {\n const result = await runCommand(add, []);\n if (!result.success) {\n throw result.error;\n }\n },\n };\n}\n\nconst commandWithSkills = withSkillCommand(\n defineCommand({\n name: cliName,\n description:\n packageJson.description || \"Tailor CLI for managing Tailor Platform SDK applications\",\n notes: `CLI plugins (beta): an unknown subcommand is dispatched to an external plugin executable named \\`${cliName}-<name>\\` (found on your PATH or in node_modules/.bin), similar to \\`gh\\` extensions.\nRun \\`${cliName} plugin list\\` to see which plugins are installed and where they resolve from.`,\n subCommands: {\n api: apiCommand,\n auth: authCommand,\n authconnection: authconnectionCommand,\n crashreport: crashReportCommand,\n deploy: deployCommand,\n executor: executorCommand,\n function: functionCommand,\n generate: generateCommand,\n init: initCommand,\n login: loginCommand,\n logout: logoutCommand,\n machineuser: machineuserCommand,\n oauth2client: oauth2clientCommand,\n open: openCommand,\n organization: organizationCommand,\n plugin: pluginCommand,\n profile: profileCommand,\n query: queryCommand,\n remove: removeCommand,\n secret: secretCommand,\n setup: setupCommand,\n show: showCommand,\n staticwebsite: staticwebsiteCommand,\n tailordb: tailordbCommand,\n upgrade: upgradeCommand,\n user: userCommand,\n workflow: workflowCommand,\n workspace: workspaceCommand,\n },\n }),\n {\n sourceDir: bundledSkillsDir,\n package: packageName,\n mode: \"copy\",\n descriptionAppend: false,\n // strip unknown keys\n globalArgs: z.object(commonArgs),\n commandMap: { add: [\"add\"], remove: [\"remove\"] },\n unknownKeys: \"strict\",\n descriptions: {\n skills: \"Manage Tailor SDK agent skills.\",\n add: \"Install Tailor SDK agent skills.\",\n list: \"List Tailor SDK agent skills.\",\n remove: \"Remove installed Tailor SDK agent skills.\",\n sync: \"Remove and reinstall Tailor SDK agent skills.\",\n },\n },\n);\n\nexport const mainCommand = withCompletionCommand({\n ...commandWithSkills,\n subCommands: {\n ...commandWithSkills.subCommands,\n skills: defaultSkillsRunToAdd(commandWithSkills.subCommands.skills),\n },\n});\n\nrunMain(mainCommand, {\n version: packageJson.version,\n // strip unknown keys\n globalArgs: z.object(commonArgs),\n displayErrors: false,\n // CLI plugin dispatch: an unknown subcommand at any level execs the external\n // `tailor-<path...>-<name>` binary, forwarding args and injecting context.\n onUnknownSubcommand: ({ commandPath, name, args }) =>\n dispatchPluginWithInstallHint({\n commandPath,\n name,\n args,\n cliName,\n profile: process.env.TAILOR_PLATFORM_PROFILE,\n }),\n cleanup: async ({ error }) => {\n if (error) {\n if (logger.jsonMode) {\n logger.log(serializeError(error, { includeStack: isVerbose() }));\n } else if (isCLIError(error)) {\n logger.log(error.format());\n if (isVerbose() && error.stack) {\n logger.debug(`\\nStack trace:\\n${error.stack}`);\n }\n } else if (error instanceof Error) {\n logger.error(error.message);\n const hint = typeOnlyImportHint(error);\n if (hint) {\n logger.log(` ${styles.info(\"Suggestion:\")} ${hint}`);\n }\n if (isVerbose() && error.stack) {\n logger.debug(`\\nStack trace:\\n${error.stack}`);\n }\n } else {\n logger.error(`Unknown error: ${error}`);\n }\n\n // Report programming bugs (native error types that indicate code defects).\n // Skip domain errors like ConnectError, CIPromptError, and plain Error\n // used for user-facing validation/not-found messages.\n // Exclude SyntaxError/ReferenceError: at runtime these typically come from\n // dynamically imported user config files, not from SDK code.\n const shouldReport =\n !isCLIError(error) &&\n (!(error instanceof Error) || error instanceof TypeError || error instanceof RangeError);\n if (shouldReport) {\n // Lazy import to match shutdownTelemetry pattern and keep cleanup handler lightweight.\n const { reportCrash } = await import(\"#/cli/crashreport/index\");\n await reportCrash(error, \"handledError\");\n }\n }\n const { shutdownTelemetry } = await import(\"#/cli/telemetry/index\");\n await shutdownTelemetry();\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,MAAM,gBAAmC,gBAAgB,QAAQ,QAC9D,MAA4B,EAAE,eAAe,OAChD;AAEA,SAAgB,kBAA4B;CAC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