@tailor-platform/sdk 2.13.1 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/application-BWOMdL3D.mjs +1 -0
  3. package/dist/{application-D3HlhR3i.mjs → application-CfevPO-k.mjs} +21 -17
  4. package/dist/application-CfevPO-k.mjs.map +1 -0
  5. package/dist/cli/commands/api/api-call.d.mts +4 -5
  6. package/dist/cli/commands/deploy/config-id-injector.d.mts +3 -4
  7. package/dist/cli/commands/deploy/deploy.d.mts +3 -4
  8. package/dist/cli/commands/deploy/function-registry-types.d.mts +2 -3
  9. package/dist/cli/commands/executor/get.d.mts +3 -4
  10. package/dist/cli/commands/executor/jobs.d.mts +10 -11
  11. package/dist/cli/commands/executor/list.d.mts +3 -4
  12. package/dist/cli/commands/executor/transform.d.mts +6 -7
  13. package/dist/cli/commands/executor/trigger.d.mts +4 -5
  14. package/dist/cli/commands/executor/webhook.d.mts +4 -5
  15. package/dist/cli/commands/function/get.d.mts +3 -4
  16. package/dist/cli/commands/function/list.d.mts +3 -4
  17. package/dist/cli/commands/function/transform.d.mts +2 -3
  18. package/dist/cli/commands/generate/options.d.mts +2 -3
  19. package/dist/cli/commands/generate/seed/bundler.d.mts +3 -4
  20. package/dist/cli/commands/generate/service.d.mts +2 -3
  21. package/dist/cli/commands/machineuser/list.d.mts +4 -5
  22. package/dist/cli/commands/machineuser/token.d.mts +4 -5
  23. package/dist/cli/commands/oauth2client/get.d.mts +3 -4
  24. package/dist/cli/commands/oauth2client/list.d.mts +3 -4
  25. package/dist/cli/commands/oauth2client/transform.d.mts +3 -4
  26. package/dist/cli/commands/organization/folder/create.d.mts +3 -4
  27. package/dist/cli/commands/organization/folder/delete.d.mts +3 -4
  28. package/dist/cli/commands/organization/folder/get.d.mts +3 -4
  29. package/dist/cli/commands/organization/folder/list.d.mts +3 -4
  30. package/dist/cli/commands/organization/folder/update.d.mts +3 -4
  31. package/dist/cli/commands/organization/get.d.mts +3 -4
  32. package/dist/cli/commands/organization/list.d.mts +3 -4
  33. package/dist/cli/commands/organization/transform.d.mts +5 -6
  34. package/dist/cli/commands/organization/tree.d.mts +3 -4
  35. package/dist/cli/commands/organization/update.d.mts +3 -4
  36. package/dist/cli/commands/remove.d.mts +3 -4
  37. package/dist/cli/commands/show.d.mts +6 -7
  38. package/dist/cli/commands/staticwebsite/deploy.d.mts +3 -4
  39. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +3 -4
  40. package/dist/cli/commands/tailordb/migrate/config.d.mts +3 -4
  41. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +35 -35
  42. package/dist/cli/commands/tailordb/migrate/generate.d.mts +3 -4
  43. package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +3 -4
  44. package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +4 -5
  45. package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +13 -14
  46. package/dist/cli/commands/tailordb/migrate/snapshot-local.d.mts +2 -3
  47. package/dist/cli/commands/tailordb/migrate/snapshot-migrations.d.mts +2 -3
  48. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +21 -22
  49. package/dist/cli/commands/tailordb/migrate/types.d.mts +2 -3
  50. package/dist/cli/commands/tailordb/truncate.d.mts +3 -4
  51. package/dist/cli/commands/workflow/executions.d.mts +8 -9
  52. package/dist/cli/commands/workflow/get.d.mts +3 -4
  53. package/dist/cli/commands/workflow/list.d.mts +3 -4
  54. package/dist/cli/commands/workflow/resume.d.mts +4 -5
  55. package/dist/cli/commands/workflow/start.d.mts +5 -6
  56. package/dist/cli/commands/workflow/status.d.mts +3 -4
  57. package/dist/cli/commands/workflow/transform.d.mts +5 -6
  58. package/dist/cli/commands/workflow/wait.d.mts +3 -4
  59. package/dist/cli/commands/workflow/waiter.d.mts +3 -4
  60. package/dist/cli/commands/workspace/app/health.d.mts +3 -4
  61. package/dist/cli/commands/workspace/app/list.d.mts +3 -4
  62. package/dist/cli/commands/workspace/app/transform.d.mts +3 -4
  63. package/dist/cli/commands/workspace/create.d.mts +3 -4
  64. package/dist/cli/commands/workspace/delete.d.mts +3 -4
  65. package/dist/cli/commands/workspace/get.d.mts +3 -4
  66. package/dist/cli/commands/workspace/list.d.mts +3 -4
  67. package/dist/cli/commands/workspace/restore.d.mts +3 -4
  68. package/dist/cli/commands/workspace/transform.d.mts +3 -4
  69. package/dist/cli/commands/workspace/user/invite.d.mts +3 -4
  70. package/dist/cli/commands/workspace/user/list.d.mts +3 -4
  71. package/dist/cli/commands/workspace/user/remove.d.mts +3 -4
  72. package/dist/cli/commands/workspace/user/transform.d.mts +2 -3
  73. package/dist/cli/commands/workspace/user/update.d.mts +3 -4
  74. package/dist/cli/lib.mjs +1 -1
  75. package/dist/cli/lib.mjs.map +1 -1
  76. package/dist/cli/main.d.mts +2 -3
  77. package/dist/cli/main.mjs +43 -41
  78. package/dist/cli/main.mjs.map +1 -1
  79. package/dist/cli/query/index.d.mts +2 -3
  80. package/dist/cli/shared/args.d.mts +11 -12
  81. package/dist/cli/shared/beta.d.mts +2 -3
  82. package/dist/cli/shared/client.d.mts +4 -5
  83. package/dist/cli/shared/command.d.mts +2 -3
  84. package/dist/cli/shared/config-loader.d.mts +5 -6
  85. package/dist/cli/shared/config.d.mts +2 -3
  86. package/dist/cli/shared/context.d.mts +3 -4
  87. package/dist/cli/shared/error-json.d.mts +4 -5
  88. package/dist/cli/shared/logger.d.mts +7 -8
  89. package/dist/cli/shared/prompt.d.mts +7 -8
  90. package/dist/cli/shared/readonly-guard.d.mts +2 -3
  91. package/dist/cli/shared/script-executor.d.mts +7 -8
  92. package/dist/cli/shared/seed-chunker.d.mts +5 -6
  93. package/dist/cli/shared/seed-context.d.mts +5 -5
  94. package/dist/cli/shared/tailordb-namespaces.d.mts +5 -6
  95. package/dist/cli/shared/type-generator.d.mts +2 -3
  96. package/dist/cli/shared/workspace-name.d.mts +2 -3
  97. package/dist/completion/zsh-worker.zsh +1 -1
  98. package/dist/configure/config/index.d.mts +3 -4
  99. package/dist/configure/config/types.d.mts +14 -15
  100. package/dist/configure/index.d.mts +10 -10
  101. package/dist/configure/index.mjs +1 -1
  102. package/dist/configure/index.mjs.map +1 -1
  103. package/dist/configure/services/aigateway/index.d.mts +2 -2
  104. package/dist/configure/services/aigateway/types.d.mts +4 -5
  105. package/dist/configure/services/auth/index.d.mts +3 -3
  106. package/dist/configure/services/auth/types.d.mts +24 -25
  107. package/dist/configure/services/executor/executor.d.mts +3 -4
  108. package/dist/configure/services/executor/operation.d.mts +6 -7
  109. package/dist/configure/services/executor/trigger/event.d.mts +56 -57
  110. package/dist/configure/services/executor/trigger/index.d.mts +2 -2
  111. package/dist/configure/services/executor/trigger/schedule.d.mts +4 -5
  112. package/dist/configure/services/executor/trigger/webhook.d.mts +8 -9
  113. package/dist/configure/services/http-adapter/http-adapter.d.mts +12 -13
  114. package/dist/configure/services/idp/index.d.mts +2 -2
  115. package/dist/configure/services/idp/permission.d.mts +4 -5
  116. package/dist/configure/services/idp/types.d.mts +5 -6
  117. package/dist/configure/services/resolver/permission.d.mts +4 -5
  118. package/dist/configure/services/resolver/resolver.d.mts +3 -4
  119. package/dist/configure/services/resolver/types.d.mts +2 -3
  120. package/dist/configure/services/secrets/index.d.mts +3 -3
  121. package/dist/configure/services/secrets/types.d.mts +3 -4
  122. package/dist/configure/services/staticwebsite/index.d.mts +2 -2
  123. package/dist/configure/services/staticwebsite/types.d.mts +3 -4
  124. package/dist/configure/services/tailordb/permission.d.mts +6 -7
  125. package/dist/configure/services/tailordb/schema.d.mts +8 -9
  126. package/dist/configure/services/tailordb/types.d.mts +25 -26
  127. package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
  128. package/dist/configure/services/workflow/execution-policy.types.d.mts +8 -9
  129. package/dist/configure/services/workflow/job.d.mts +4 -5
  130. package/dist/configure/services/workflow/wait-point.d.mts +5 -6
  131. package/dist/configure/services/workflow/workflow.d.mts +4 -4
  132. package/dist/configure/types/aigateway-name.d.mts +3 -4
  133. package/dist/configure/types/auth-namespace-name.d.mts +3 -4
  134. package/dist/configure/types/connection-name.d.mts +3 -4
  135. package/dist/configure/types/field.d.mts +3 -4
  136. package/dist/configure/types/field.types.d.mts +18 -12
  137. package/dist/configure/types/idp-name.d.mts +3 -4
  138. package/dist/configure/types/permission-operand.types.d.mts +7 -8
  139. package/dist/configure/types/type.d.mts +3 -4
  140. package/dist/date-DrUO8rOJ.mjs +2 -0
  141. package/dist/date-DrUO8rOJ.mjs.map +1 -0
  142. package/dist/kysely/index.d.mts +18 -18
  143. package/dist/parser/service/idp/types.d.mts +2 -3
  144. package/dist/parser/service/tailordb/type-source.d.mts +2 -3
  145. package/dist/parser/service/tailordb/types.d.mts +13 -14
  146. package/dist/plugin/builtin/enum-constants/index.d.mts +3 -4
  147. package/dist/plugin/builtin/file-utils/index.d.mts +3 -4
  148. package/dist/plugin/builtin/kysely-type/index.d.mts +4 -5
  149. package/dist/plugin/builtin/seed/index.d.mts +4 -5
  150. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +2 -3
  151. package/dist/plugin/get-generated-table.d.mts +2 -3
  152. package/dist/plugin/index.mjs +1 -1
  153. package/dist/plugin/index.mjs.map +1 -1
  154. package/dist/plugin/types.d.mts +29 -29
  155. package/dist/plugin/with-context.d.mts +9 -10
  156. package/dist/register-ts-hook-DZ1Kpt4s.mjs +642 -0
  157. package/dist/register-ts-hook-DZ1Kpt4s.mjs.map +1 -0
  158. package/dist/runtime/aigateway.d.mts +4 -5
  159. package/dist/runtime/authconnection.d.mts +3 -4
  160. package/dist/runtime/context.d.mts +6 -7
  161. package/dist/runtime/date.d.mts +16 -0
  162. package/dist/runtime/field-parse.d.mts +2 -3
  163. package/dist/runtime/file.d.mts +14 -15
  164. package/dist/runtime/globals.d.mts +2 -1
  165. package/dist/runtime/iconv.d.mts +5 -6
  166. package/dist/runtime/idp.d.mts +14 -15
  167. package/dist/runtime/index.d.mts +8 -7
  168. package/dist/runtime/index.mjs +1 -1
  169. package/dist/runtime/logger.d.mts +10 -11
  170. package/dist/runtime/secretmanager.d.mts +3 -4
  171. package/dist/runtime/types.d.mts +7 -8
  172. package/dist/runtime/workflow.d.mts +7 -8
  173. package/dist/schema-DMlLMsWA.mjs +2 -0
  174. package/dist/schema-DMlLMsWA.mjs.map +1 -0
  175. package/dist/seed/index.d.mts +3 -3
  176. package/dist/service-7SCy2bhm.mjs +7 -0
  177. package/dist/service-7SCy2bhm.mjs.map +1 -0
  178. package/dist/service-CWFQ8EVo.mjs +1 -0
  179. package/dist/shared/src/color.d.mts +2 -3
  180. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +21 -22
  181. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +2 -3
  182. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +35 -36
  183. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +6 -7
  184. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +229 -230
  185. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +40 -41
  186. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +9 -10
  187. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +3 -4
  188. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +45 -46
  189. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +24 -25
  190. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +17 -18
  191. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +29 -30
  192. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +8 -9
  193. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +2 -3
  194. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +37 -38
  195. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +13 -14
  196. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +19 -20
  197. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +2 -3
  198. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +25 -26
  199. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +59 -60
  200. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +10 -11
  201. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +7 -8
  202. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +37 -38
  203. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +4 -5
  204. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +6 -7
  205. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +21 -22
  206. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +3 -4
  207. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +50 -51
  208. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +4 -5
  209. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +74 -75
  210. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +35 -36
  211. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +41 -42
  212. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +11 -12
  213. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +97 -98
  214. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +11 -12
  215. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +209 -210
  216. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +24 -25
  217. package/dist/types/aigateway.generated.d.mts +3 -4
  218. package/dist/types/app-config.generated.d.mts +2 -3
  219. package/dist/types/auth-connection.generated.d.mts +3 -4
  220. package/dist/types/auth.generated.d.mts +15 -16
  221. package/dist/types/executor.generated.d.mts +26 -27
  222. package/dist/types/helpers.d.mts +15 -13
  223. package/dist/types/http-adapter.generated.d.mts +2 -3
  224. package/dist/types/idp.generated.d.mts +7 -8
  225. package/dist/types/resolver.generated.d.mts +6 -5
  226. package/dist/types/secrets.generated.d.mts +3 -4
  227. package/dist/types/staticwebsite.generated.d.mts +3 -4
  228. package/dist/types/tailordb.generated.d.mts +7 -8
  229. package/dist/types/workflow.generated.d.mts +3 -4
  230. package/dist/utils/test/index.d.mts +3 -4
  231. package/dist/vitest/index.d.mts +2 -2
  232. package/dist/vitest/mock-kysely.d.mts +4 -5
  233. package/dist/vitest/mocks/aigateway.d.mts +3 -4
  234. package/dist/vitest/mocks/authconnection.d.mts +3 -4
  235. package/dist/vitest/mocks/file.d.mts +3 -4
  236. package/dist/vitest/mocks/iconv.d.mts +3 -4
  237. package/dist/vitest/mocks/idp.d.mts +3 -4
  238. package/dist/vitest/mocks/logger.d.mts +3 -4
  239. package/dist/vitest/mocks/secretmanager.d.mts +3 -4
  240. package/dist/vitest/mocks/tailordb-pglite.d.mts +4 -5
  241. package/dist/vitest/mocks/tailordb.d.mts +6 -7
  242. package/dist/vitest/mocks/workflow.d.mts +2 -3
  243. package/dist/vitest/pglite-kysely.d.mts +5 -6
  244. package/dist/vitest/setup.d.mts +6 -7
  245. package/dist/vitest/workflow-local.d.mts +5 -6
  246. package/docs/services/idp.md +6 -3
  247. package/docs/services/resolver.md +21 -0
  248. package/docs/services/tailordb-migration.md +25 -3
  249. package/docs/services/tailordb.md +2 -0
  250. package/package.json +13 -13
  251. package/dist/application-BFTkaW6X.mjs +0 -1
  252. package/dist/application-D3HlhR3i.mjs.map +0 -1
  253. package/dist/register-ts-hook-BJmGCQAA.mjs +0 -642
  254. package/dist/register-ts-hook-BJmGCQAA.mjs.map +0 -1
  255. package/dist/schema-6d_OHyZf.mjs +0 -2
  256. package/dist/schema-6d_OHyZf.mjs.map +0 -1
  257. package/dist/service-BzsSm2f6.mjs +0 -7
  258. package/dist/service-BzsSm2f6.mjs.map +0 -1
  259. package/dist/service-CmwD9bwv.mjs +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"main.mjs","names":["CLIError","listCommand","listCommand","statusCommand","statusCommand","randomState","listCommand","listCommand","listCommand","getCommand","getCommand","listCommand","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","listCommand","deployCommand","listCommand","generateCommand","scriptCommand","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/status.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/script-scaffold.ts","../../src/cli/commands/function/run.ts","../../src/cli/commands/function/script.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/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\ninterface InspectMessageJson {\n typeName: string;\n fields: InspectFieldJson[];\n /** True when truncated to break a recursive type cycle. */\n recursive?: boolean;\n}\n\ninterface 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: \"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: \"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: \"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: \"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 { loadAuthStatus } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const statusCommand = defineAppCommand({\n name: \"status\",\n description: \"Show the active Tailor Platform authentication status without printing tokens.\",\n args: z.strictObject({\n profile: workspaceArgs.profile,\n }),\n run: async ({ profile }) => {\n const status = await loadAuthStatus({ profile });\n logger.out(status);\n if (!status.authenticated) {\n throw new Error(\"Not authenticated. Run 'tailor login' and try again.\");\n }\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 { statusCommand } from \"./status\";\nimport { tokenCommand } from \"./token\";\n\nexport const authCommand = defineCommand({\n name: \"auth\",\n description: \"Authentication helpers for scripts and plugins.\",\n subCommands: {\n status: statusCommand,\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { toError } from \"#/cli/shared/errors\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 // A fetch failure rejects with TypeError, which the top-level handler\n // classifies as an SDK bug and crash-reports.\n const response = await fetch(url).catch((error: unknown) => {\n throw new Error(`Failed to fetch OIDC discovery from ${url}: ${toError(error).message}`, {\n cause: error,\n });\n });\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 handleCallback = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\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(toError(err));\n }\n };\n const server = http.createServer((req, res) => void handleCallback(req, res));\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 const announceAuthorizeUrl = async (): Promise<void> => {\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 server.listen(args.port, () => void announceAuthorizeUrl());\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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\";\nimport { parseBoolean } from \"#/cli/shared/parse-boolean\";\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 =\n parseBoolean(process.env.TAILOR_CONSOLE_NEXT) === true\n ? `/workspaces/${workspaceId}/services/auth-connections`\n : `/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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 function 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 */\ninterface 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 function 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, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\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 { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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. function 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 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 the function run command\n *\n * Bundles a single function file for server-side execution.\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 BundleForRunOptions {\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 BundleForRunResult {\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 `function run` execution.\n * @param options - Bundle options\n * @returns Bundled code and script name\n */\nexport async function bundleForRun(options: BundleForRunOptions): Promise<BundleForRunResult> {\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 function 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 function 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 when executing workflow jobs this way.\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 the function 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\ntype 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 * Scaffolding helpers for the `tailor function script` command.\n *\n * A scaffolded one-off script is a plain default-exported function that\n * `tailor function run` executes on the platform without deploying. When the\n * project does not configure `kyselyTypePlugin`, the scaffold also writes a\n * script-scoped `db.ts` generated from local table definitions by default, plus a\n * `db.snapshot.json` snapshot that `function run` checks for schema drift.\n */\n\nimport * as fs from \"node:fs\";\nimport { parseSync } from \"oxc-parser\";\nimport * as path from \"pathe\";\nimport {\n hasChanges,\n formatMigrationDiff,\n type MigrationDiff,\n} from \"#/cli/commands/tailordb/migrate/diff-calculator\";\nimport { fetchRemoteSchemaSnapshot } from \"#/cli/commands/tailordb/migrate/schema-checks\";\nimport {\n compareSnapshots,\n createRemoteComparableSnapshot,\n createSnapshotType,\n normalizeSchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type SchemaSnapshot,\n type TailorDBSnapshotType,\n} from \"#/cli/commands/tailordb/migrate/snapshot\";\nimport { DEFAULT_CONFIG_PATH } from \"#/cli/shared/args\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { formatCopyableCommand } from \"#/cli/shared/errors\";\nimport { loadTailorDBNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport {\n generateUnifiedKyselyTypes,\n processKyselyFields,\n} from \"#/plugin/builtin/kysely-type/type-processor\";\nimport type { SnapshotFieldConfig } from \"#/cli/commands/tailordb/migrate/snapshot-types\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\nimport type { LoadedConfig } from \"#/cli/shared/config-loader\";\n\n/** File name of the script-scoped Kysely types written next to a scaffolded script. */\nexport const SCRIPT_DB_TYPES_FILE_NAME = \"db.ts\";\n/** File name of the schema snapshot written next to a scaffolded script. */\nexport const SCRIPT_SNAPSHOT_FILE_NAME = \"db.snapshot.json\";\n\nconst GENERATED_DB_TYPES_HEADER = [\n \"/**\",\n \" * Auto-generated Kysely types for one-off scripts in this directory.\",\n \" * Generated by `tailor function script` from the selected TailorDB schema.\",\n \" *\",\n \" * DO NOT EDIT - Re-run `tailor function script` to refresh.\",\n \" */\",\n].join(\"\\n\");\n\n/**\n * Generate the script-scoped `db.ts` contents from a schema snapshot.\n * @param snapshot - Schema snapshot of the target namespace\n * @returns Generated `db.ts` file contents\n */\nexport function generateScriptDbTypes(snapshot: SchemaSnapshot): string {\n const types = Object.values(snapshot.tables).map((table) =>\n processKyselyFields(table.name, table.fields),\n );\n const body = generateUnifiedKyselyTypes([{ namespace: snapshot.namespace, types }]);\n return `${GENERATED_DB_TYPES_HEADER}\\n\\n${body}`;\n}\n\n/**\n * Whether an existing file at the script-scoped `db.ts` path was written by\n * the scaffold (and is therefore safe to overwrite).\n * @param content - Existing file contents\n * @returns true when the scaffold header is present\n */\nexport function isGeneratedScriptDbTypes(content: string): boolean {\n return content.includes(\"Generated by `tailor function script`\");\n}\n\n/**\n * Assert generated TypeScript parses before it is written to disk.\n * @param filePath - Destination path (named in the error)\n * @param content - Generated source\n */\nexport function assertGeneratedTypeScript(filePath: string, content: string): void {\n const { errors } = parseSync(path.basename(filePath), content);\n if (errors.length > 0) {\n throw new Error(\n `Generated ${filePath} does not parse as TypeScript: ${errors\n .map((error) => error.message)\n .join(\"; \")}`,\n );\n }\n}\n\n/** Options for {@link generateScriptSkeleton}. */\nexport interface ScriptSkeletonOptions {\n /** Module specifier the skeleton imports `getDB` from */\n getDBImportPath: string;\n /** TailorDB namespace passed to `getDB()` */\n namespace: string;\n}\n\n/**\n * Generate the one-off script skeleton.\n * @param options - Skeleton options\n * @returns Skeleton file contents\n */\nexport function generateScriptSkeleton(options: ScriptSkeletonOptions): string {\n const { getDBImportPath, namespace } = options;\n return [\n \"/**\",\n \" * One-off script. Run it on the platform without deploying:\",\n \" *\",\n \" * tailor function run <this file>\",\n \" *\",\n \" * For large tables, batch updates by primary-key range instead of one\",\n ' * statement over the whole table; see the \"Performance and Large Tables\"',\n \" * section in @tailor-platform/sdk's docs/services/tailordb-migration.md.\",\n \" */\",\n \"\",\n `import { getDB } from ${JSON.stringify(getDBImportPath)};`,\n \"\",\n \"export default async function main() {\",\n ` const db = getDB(${JSON.stringify(namespace)});`,\n \"\",\n \" // A transaction rolls every change back when any statement fails.\",\n \" await db.transaction().execute(async (trx) => {\",\n ' // e.g. await trx.updateTable(\"MyTable\").set({ ... }).where(\"id\", \"=\", \"...\").execute();',\n \" });\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** A schema snapshot sidecar found next to a script. */\nexport interface ScriptSchemaSnapshotSidecar {\n /** Path of the snapshot file */\n snapshotPath: string;\n /** Source used to generate the stored snapshot */\n source: \"local\" | \"remote\";\n /** The stored snapshot, normalized */\n snapshot: NormalizedSchemaSnapshot;\n}\n\n/**\n * Load the schema snapshot written next to a scaffolded script, if present.\n * @param scriptPath - Absolute path of the script passed to `function run`\n * @returns The snapshot sidecar, or null when the script has none\n */\nexport function loadScriptSchemaSnapshot(scriptPath: string): ScriptSchemaSnapshotSidecar | null {\n const snapshotPath = path.join(path.dirname(scriptPath), SCRIPT_SNAPSHOT_FILE_NAME);\n if (!fs.existsSync(snapshotPath)) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(snapshotPath, \"utf-8\"));\n } catch (error) {\n throw new Error(\n `Failed to parse schema snapshot ${snapshotPath}: ${error instanceof Error ? error.message : error}. ` +\n \"Re-run `tailor function script` to regenerate it.\",\n { cause: error },\n );\n }\n const candidate = parsed as Record<string, unknown> | null;\n if (\n typeof candidate !== \"object\" ||\n candidate === null ||\n typeof candidate.namespace !== \"string\" ||\n typeof candidate.tables !== \"object\" ||\n candidate.tables === null\n ) {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n const source = candidate.source ?? \"remote\";\n if (source !== \"local\" && source !== \"remote\") {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n const snapshotData = { ...candidate };\n delete snapshotData.source;\n\n try {\n return {\n snapshotPath,\n source,\n snapshot: normalizeSchemaSnapshot(snapshotData as unknown as SchemaSnapshot),\n };\n } catch {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n}\n\nfunction unexpectedSnapshotShapeError(snapshotPath: string): Error {\n return new Error(\n `Schema snapshot ${snapshotPath} has an unexpected shape. ` +\n \"Re-run `tailor function script` to regenerate it.\",\n );\n}\n\n/** Options for {@link verifyScriptSchemaSnapshot}. */\nexport interface VerifyScriptSchemaSnapshotOptions {\n /** Operator client */\n client: OperatorClient;\n /** Workspace ID */\n workspaceId: string;\n /** Loaded config */\n config: LoadedConfig;\n /** Config path as passed on the command line (threaded into hints) */\n configArgValue: string;\n /** Script path as passed on the command line (threaded into hints) */\n scriptArgValue: string;\n /** Profile as passed on the command line, when any (threaded into hints) */\n profileArgValue?: string;\n /** The snapshot sidecar found next to the script */\n sidecar: ScriptSchemaSnapshotSidecar;\n}\n\n/**\n * Verify a scaffolded script's schema snapshot still matches the local table\n * definitions (when the config owns the namespace) and the deployed schema.\n * @param options - Verification inputs\n * @throws When either comparison detects drift\n */\nexport async function verifyScriptSchemaSnapshot(\n options: VerifyScriptSchemaSnapshotOptions,\n): Promise<void> {\n const { client, workspaceId, config, configArgValue, sidecar } = options;\n const { snapshot } = sidecar;\n const namespace = snapshot.namespace;\n\n if (extractOwnedNamespaces(config).includes(namespace)) {\n const { namespaces } = await loadTailorDBNamespaces({\n configPath: configArgValue,\n namespaces: [namespace],\n });\n const namespaceData = namespaces[0];\n if (namespaceData) {\n const localTables: Record<string, TailorDBSnapshotType> = Object.fromEntries(\n Object.values(namespaceData.tables).map((table) => [table.name, createSnapshotType(table)]),\n );\n // Compare the field contract that generated db.ts consumes. Local\n // create hooks and defaults are represented remotely as\n // optionalOnCreate, so normalize all three forms to that contract.\n const diff = compareSnapshots(\n generatedContractSnapshot(snapshot),\n generatedContractSnapshot({ ...snapshot, tables: localTables }),\n );\n if (hasChanges(diff)) {\n throw schemaDriftError(\"the local table definitions\", diff, options);\n }\n }\n }\n\n const remoteSnapshot = await fetchRemoteSchemaSnapshot(client, workspaceId, namespace);\n // Legacy and remote-generated sidecars are directly comparable with the\n // deployed schema. Local sidecars require the generated-contract projection\n // because create hooks and defaults become optionalOnCreate when deployed.\n const remoteDiff = compareSnapshots(\n sidecar.source === \"local\"\n ? generatedContractSnapshot(snapshot)\n : normalizeSchemaSnapshot(pickTableFields(snapshot)),\n sidecar.source === \"local\"\n ? generatedContractSnapshot(remoteSnapshot)\n : normalizeSchemaSnapshot(pickTableFields(remoteSnapshot)),\n );\n if (hasChanges(remoteDiff)) {\n throw schemaDriftError(\"the deployed schema\", remoteDiff, options);\n }\n}\n\n/**\n * Project a snapshot down to what the generated db.ts depends on: table\n * fields, with script-bearing props stripped by the remote-comparable\n * projection.\n * @param snapshot - Snapshot to project\n * @returns Normalized snapshot carrying only table names and fields\n */\nfunction fieldsOnlySnapshot(snapshot: SchemaSnapshot): NormalizedSchemaSnapshot {\n return normalizeSchemaSnapshot(pickTableFields(createRemoteComparableSnapshot(snapshot)));\n}\n\n/**\n * Project a snapshot to the field contract consumed by generated Kysely types.\n * @param snapshot - Snapshot to project\n * @returns Normalized fields-only snapshot with generated-on-create semantics preserved\n */\nfunction generatedContractSnapshot(snapshot: SchemaSnapshot): NormalizedSchemaSnapshot {\n const comparable = fieldsOnlySnapshot(snapshot);\n const tables = Object.fromEntries(\n Object.entries(comparable.tables).map(([tableName, table]) => {\n const sourceTable = snapshot.tables[tableName];\n const fields = Object.fromEntries(\n Object.entries(table.fields).map(([fieldName, field]) => [\n fieldName,\n preserveGeneratedContract(field, sourceTable?.fields[fieldName]),\n ]),\n );\n return [tableName, { ...table, fields }];\n }),\n );\n return normalizeSchemaSnapshot({ ...comparable, tables });\n}\n\nfunction preserveGeneratedContract(\n comparable: SnapshotFieldConfig,\n source: SnapshotFieldConfig | undefined,\n): SnapshotFieldConfig {\n const fields = comparable.fields\n ? Object.fromEntries(\n Object.entries(comparable.fields).map(([fieldName, field]) => [\n fieldName,\n preserveGeneratedContract(field, source?.fields?.[fieldName]),\n ]),\n )\n : undefined;\n const generated =\n source?.hooks?.create !== undefined ||\n source?.default !== undefined ||\n source?.optionalOnCreate === true;\n return {\n ...comparable,\n ...(fields === undefined ? {} : { fields }),\n ...(generated ? { optionalOnCreate: true } : {}),\n };\n}\n\n/**\n * Keep only what the generated db.ts is built from: table names and fields.\n * @param snapshot - Snapshot to project\n * @returns Snapshot whose tables carry only name, pluralForm, and fields\n */\nfunction pickTableFields(snapshot: SchemaSnapshot): SchemaSnapshot {\n const tables = Object.fromEntries(\n Object.entries(snapshot.tables).map(([tableName, table]) => [\n tableName,\n { name: table.name, pluralForm: table.pluralForm, fields: table.fields },\n ]),\n );\n return { ...snapshot, tables };\n}\n\nfunction schemaDriftError(\n target: string,\n diff: MigrationDiff,\n options: VerifyScriptSchemaSnapshotOptions,\n): Error {\n const contextFlags = [\n ...(options.configArgValue !== DEFAULT_CONFIG_PATH\n ? [`--config=${options.configArgValue}`]\n : []),\n `--workspace-id=${options.workspaceId}`,\n ...(options.profileArgValue !== undefined ? [`--profile=${options.profileArgValue}`] : []),\n ];\n const rescaffold = formatCopyableCommand([\n \"tailor\",\n \"function\",\n \"script\",\n options.scriptArgValue,\n ...(options.sidecar.source === \"remote\" ? [\"--remote\"] : []),\n ...contextFlags,\n ]);\n const override = formatCopyableCommand([\n \"tailor\",\n \"function\",\n \"run\",\n options.scriptArgValue,\n \"--allow-schema-drift\",\n ...contextFlags,\n ]);\n return new Error(\n `Schema drift detected: ${SCRIPT_SNAPSHOT_FILE_NAME} next to the script no longer matches ${target}.\\n\\n` +\n `${formatMigrationDiff(diff)}\\n\\n` +\n `Refresh the generated types with ${rescaffold}, or run anyway with ${override}.`,\n );\n}\n","/**\n * `tailor function 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, extractFields, toCamelCase } from \"politty\";\nimport { z } from \"zod\";\nimport { resolveResolverDefaultPermissionForFile } from \"#/cli/services/resolver/default-permission\";\nimport {\n commonArgs,\n resolveMachineUserInputSource,\n type MachineUserInputSource,\n workspaceArgs,\n} from \"#/cli/shared/args\";\nimport { type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadMachineUserName } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { executeScript } from \"#/cli/shared/script-executor\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { bundleForRun, type ResolvedMachineUser } from \"./bundle\";\nimport { detectFunctionType } from \"./detect\";\nimport {\n SCRIPT_SNAPSHOT_FILE_NAME,\n loadScriptSchemaSnapshot,\n verifyScriptSchemaSnapshot,\n} from \"./script-scaffold\";\nimport type { Jsonifiable } from \"type-fest\";\n\nexport const runFunctionCommand = defineAppCommand({\n name: \"run\",\n aliases: [\"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 \"allow-schema-drift\": arg(z.boolean().default(false), {\n description: \"Run a scaffolded script even when its schema snapshot no longer matches\",\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\nA script scaffolded by \\`function script\\` with a generated \\`db.ts\\` is checked against its \\`db.snapshot.json\\` before execution and refused on schema drift; pass \\`--allow-schema-drift\\` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n\\`test-run\\` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job \\`.start()\\` calls do not work in this 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 if (invokedViaTestRunAlias(process.argv)) {\n logger.warn(\n \"`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.\",\n );\n }\n\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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\n if (!isPreBundled) {\n if (args[\"allow-schema-drift\"]) {\n if (fs.existsSync(path.join(path.dirname(filePath), SCRIPT_SNAPSHOT_FILE_NAME))) {\n logger.warn(\"Skipping the schema snapshot check (--allow-schema-drift).\");\n }\n } else {\n const sidecar = loadScriptSchemaSnapshot(filePath);\n if (sidecar) {\n logger.info(\"Checking the script's schema snapshot for drift...\");\n await verifyScriptSchemaSnapshot({\n client,\n workspaceId,\n config,\n configArgValue: args.config,\n scriptArgValue: args.file,\n profileArgValue: args.profile,\n sidecar,\n });\n }\n }\n }\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 bundleForRun({\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 the bundled script\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 * Global option tokens that consume the following argv token as their value.\n * politty accepts both the kebab-case and camelCase spelling of every name.\n */\nconst valueTakingGlobalFlags: ReadonlySet<string> = new Set(\n extractFields(z.strictObject(commonArgs))\n .fields.filter((field) => field.type !== \"boolean\")\n .flatMap((field) => [field.cliName, ...(field.alias ?? [])].flatMap(toFlagTokens)),\n);\n\nfunction toFlagTokens(name: string): string[] {\n if (name.length === 1) return [`-${name}`];\n return [`--${name}`, `--${toCamelCase(name)}`];\n}\n\n/**\n * Detect whether the command was invoked through the deprecated `test-run`\n * alias. politty resolves aliases before dispatch, so the invoked name is only\n * observable from the raw argv. Global options may sit anywhere before the\n * subcommand (`tailor function --json test-run`), so option tokens and any\n * values they consume are skipped; an option value is never read as a command\n * name.\n * @param argv - Process argv tokens\n * @returns true when `test-run` was the subcommand name under `function`\n */\nfunction invokedViaTestRunAlias(argv: readonly string[]): boolean {\n const names: string[] = [];\n // argv[0] is the node binary and argv[1] the CLI entry point.\n for (let i = 2; i < argv.length && names.length < 2; i++) {\n const token = argv[i];\n if (token === undefined || token === \"--\") break;\n if (!token.startsWith(\"-\")) {\n names.push(token);\n continue;\n }\n if (!token.includes(\"=\") && valueTakingGlobalFlags.has(token)) i++;\n }\n return names[0] === \"function\" && names[1] === \"test-run\";\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","/**\n * `tailor function script` command\n *\n * Scaffolds a one-off script that `tailor function run` executes on the\n * Tailor Platform server without deploying.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchRemoteSchemaSnapshot } from \"#/cli/commands/tailordb/migrate/schema-checks\";\nimport {\n createSnapshotFromLocalTypes,\n type NormalizedSchemaSnapshot,\n} from \"#/cli/commands/tailordb/migrate/snapshot\";\nimport { workspaceArgs, configArg, DEFAULT_CONFIG_PATH } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { extractAllNamespaces, extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig, type LoadedConfig } from \"#/cli/shared/config-loader\";\nimport { formatCopyableCommand } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { loadTailorDBNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport {\n KyselyGeneratorID,\n DEFAULT_KYSELY_TYPES_DIST_PATH,\n} from \"#/plugin/builtin/kysely-type/index\";\nimport { resolvePluginConfig } from \"#/plugin/get-plugin-config\";\nimport { assertDefined } from \"#/utils/assert\";\nimport {\n SCRIPT_DB_TYPES_FILE_NAME,\n SCRIPT_SNAPSHOT_FILE_NAME,\n assertGeneratedTypeScript,\n generateScriptDbTypes,\n generateScriptSkeleton,\n isGeneratedScriptDbTypes,\n loadScriptSchemaSnapshot,\n} from \"./script-scaffold\";\nimport type { Plugin } from \"#/plugin/types\";\n\nexport const scriptCommand = defineAppCommand({\n name: \"script\",\n description: \"Scaffold a one-off script to run with `function run`.\",\n // strip unknown keys\n args: z.object({\n ...workspaceArgs,\n ...configArg,\n file: arg(z.string(), {\n positional: true,\n description: \"Path to create the script at (must end with .ts)\",\n }),\n namespace: arg(z.string().optional(), {\n description: \"Target TailorDB namespace (required when the config does not pin one)\",\n }),\n remote: arg(z.boolean().default(false), {\n description: \"Generate script-scoped DB types from the deployed schema\",\n }),\n }),\n notes: `The scaffolded script is a plain default-exported function; execute it with \\`tailor function run <file>\\`.\n\nBy default, when the project configures \\`kyselyTypePlugin\\`, the skeleton imports \\`getDB()\\` from the plugin's generated types. Without the plugin, the command uses the namespace's local table definitions to write a script-scoped \\`db.ts\\` plus a \\`db.snapshot.json\\` next to the script; \\`function run\\` refuses to run the script when that snapshot no longer matches the deployed or locally defined table and field structure.\n\nPass \\`--remote\\` to generate the script-scoped files from the deployed schema instead, even when \\`kyselyTypePlugin\\` is configured. This is required for an external namespace. Re-running the command refreshes \\`db.ts\\` and \\`db.snapshot.json\\` from the selected source and leaves the script itself untouched.`,\n examples: [\n {\n cmd: \"scripts/fix-prices.ts\",\n desc: \"Scaffold a one-off script (single-namespace project)\",\n },\n {\n cmd: \"scripts/fix-prices.ts --namespace tailordb\",\n desc: \"Scaffold a script targeting a specific namespace\",\n },\n {\n cmd: \"scripts/fix-prices.ts --namespace shared --remote\",\n desc: \"Scaffold from a deployed or external namespace\",\n },\n ],\n run: async (args) => {\n const filePath = path.resolve(args.file);\n if (!filePath.endsWith(\".ts\")) {\n throw new Error(`Script path must end with .ts: ${args.file}`);\n }\n const scriptDir = path.dirname(filePath);\n const scriptExists = fs.existsSync(filePath);\n const dbTypesPath = path.join(scriptDir, SCRIPT_DB_TYPES_FILE_NAME);\n const snapshotPath = path.join(scriptDir, SCRIPT_SNAPSHOT_FILE_NAME);\n if (filePath === dbTypesPath) {\n throw new Error(\n `${SCRIPT_DB_TYPES_FILE_NAME} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,\n );\n }\n\n const { config, plugins } = await loadConfig(args.config);\n const kyselyPlugin = plugins.find((plugin) => plugin.id === KyselyGeneratorID);\n const hasSnapshotSidecar = fs.existsSync(snapshotPath);\n if (args.remote && kyselyPlugin !== undefined && scriptExists && !hasSnapshotSidecar) {\n throw new Error(\n `Script already exists: ${path.relative(process.cwd(), filePath)}. ` +\n \"Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.\",\n );\n }\n // A directory that already carries a snapshot sidecar keeps using\n // script-scoped generated types, even when the project has since\n // configured kyselyTypePlugin: its scripts import ./db.\n const useGeneratedDbTypes = args.remote || kyselyPlugin === undefined || hasSnapshotSidecar;\n\n let existingSidecarNamespace: string | undefined;\n if (useGeneratedDbTypes) {\n try {\n existingSidecarNamespace = loadScriptSchemaSnapshot(filePath)?.snapshot.namespace;\n } catch {\n // A corrupt sidecar is regenerated below; resolve from the config instead.\n }\n }\n const namespace = resolveNamespace({\n config,\n explicit: args.namespace,\n sidecarNamespace: existingSidecarNamespace,\n remote: args.remote,\n });\n if (existingSidecarNamespace !== undefined && existingSidecarNamespace !== namespace) {\n throw new Error(\n `This directory's generated types target namespace \"${existingSidecarNamespace}\" (${SCRIPT_SNAPSHOT_FILE_NAME}). ` +\n `Scaffold scripts for namespace \"${namespace}\" in a separate directory.`,\n );\n }\n\n const created: string[] = [];\n let getDBImportPath: string;\n let resolvedWorkspaceId: string | undefined;\n\n if (!useGeneratedDbTypes) {\n if (scriptExists) {\n throw new Error(\n `Script already exists: ${path.relative(process.cwd(), filePath)}. ` +\n \"It imports the project's generated Kysely types, so there is nothing to refresh.\",\n );\n }\n const generatedTypesPath = resolveKyselyTypesPath(plugins);\n getDBImportPath = toImportSpecifier(path.relative(scriptDir, generatedTypesPath));\n if (!fs.existsSync(generatedTypesPath)) {\n logger.warn(\n `Generated Kysely types not found at ${styles.path(path.relative(process.cwd(), generatedTypesPath))}. Run \\`tailor generate\\` before executing the script.`,\n );\n }\n } else {\n let snapshot: NormalizedSchemaSnapshot;\n if (args.remote) {\n const { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\n });\n resolvedWorkspaceId = workspaceId;\n\n logger.info(`Fetching deployed schema of namespace ${styles.bold(namespace)}...`);\n snapshot = await fetchRemoteSchemaSnapshot(client, workspaceId, namespace);\n } else {\n logger.info(`Loading local definitions of namespace ${styles.bold(namespace)}...`);\n const { namespaces } = await loadTailorDBNamespaces({\n configPath: args.config,\n namespaces: [namespace],\n });\n const namespaceData = assertDefined(namespaces[0], `namespace ${namespace}`);\n snapshot = createSnapshotFromLocalTypes(namespaceData.tables, namespace);\n }\n if (Object.keys(snapshot.tables).length === 0) {\n const sourceDescription = args.remote\n ? `deployed tables in workspace ${assertDefined(resolvedWorkspaceId, \"workspace ID\")}`\n : \"locally defined tables\";\n throw new Error(`Namespace \"${namespace}\" has no ${sourceDescription}.`);\n }\n\n if (fs.existsSync(dbTypesPath)) {\n const existing = fs.readFileSync(dbTypesPath, \"utf-8\");\n if (!isGeneratedScriptDbTypes(existing)) {\n throw new Error(\n `Refusing to overwrite ${path.relative(process.cwd(), dbTypesPath)}: ` +\n \"it was not generated by `tailor function script`.\",\n );\n }\n }\n const dbTypesContent = generateScriptDbTypes(snapshot);\n assertGeneratedTypeScript(dbTypesPath, dbTypesContent);\n fs.mkdirSync(scriptDir, { recursive: true });\n fs.writeFileSync(dbTypesPath, dbTypesContent);\n created.push(dbTypesPath);\n fs.writeFileSync(\n snapshotPath,\n JSON.stringify({ ...snapshot, source: args.remote ? \"remote\" : \"local\" }, null, 2) + \"\\n\",\n );\n created.push(snapshotPath);\n getDBImportPath = \"./db\";\n }\n\n if (!scriptExists) {\n const skeleton = generateScriptSkeleton({ getDBImportPath, namespace });\n assertGeneratedTypeScript(filePath, skeleton);\n fs.mkdirSync(scriptDir, { recursive: true });\n fs.writeFileSync(filePath, skeleton);\n created.unshift(filePath);\n }\n\n const relScript = path.relative(process.cwd(), filePath);\n const runArgv = [\"tailor\", \"function\", \"run\", relScript];\n if (args.config !== DEFAULT_CONFIG_PATH) {\n runArgv.push(`--config=${args.config}`);\n }\n const workspaceIdForHint = resolvedWorkspaceId ?? args[\"workspace-id\"];\n if (workspaceIdForHint !== undefined) {\n runArgv.push(`--workspace-id=${workspaceIdForHint}`);\n }\n if (args.profile !== undefined) {\n runArgv.push(`--profile=${args.profile}`);\n }\n\n if (logger.jsonMode) {\n logger.out({\n script: filePath,\n created,\n namespace,\n usesGeneratedDbTypes: useGeneratedDbTypes,\n });\n return;\n }\n\n if (scriptExists) {\n logger.info(`Script already exists; refreshed generated types only.`);\n }\n for (const file of created) {\n logger.success(`Created ${styles.path(path.relative(process.cwd(), file))}`);\n }\n logger.info(`Next: edit the script, then run ${formatCopyableCommand(runArgv)}`);\n },\n});\n\ninterface ResolveNamespaceOptions {\n config: LoadedConfig;\n explicit: string | undefined;\n sidecarNamespace: string | undefined;\n remote: boolean;\n}\n\n/**\n * Resolve the target TailorDB namespace for the scaffold.\n * @param options - Resolution inputs\n * @returns The namespace name\n */\nfunction resolveNamespace(options: ResolveNamespaceOptions): string {\n const { config, explicit, sidecarNamespace, remote } = options;\n const allNamespaces = extractAllNamespaces(config);\n const ownedNamespaces = extractOwnedNamespaces(config);\n const configured = remote ? allNamespaces : ownedNamespaces;\n\n if (explicit) {\n if (!remote && !ownedNamespaces.includes(explicit)) {\n throw new Error(`Namespace \"${explicit}\" is not owned by the config and requires --remote.`);\n }\n return explicit;\n }\n\n if (sidecarNamespace !== undefined) {\n if (!remote && !ownedNamespaces.includes(sidecarNamespace)) {\n throw new Error(\n `Namespace \"${sidecarNamespace}\" is not owned by the config and requires --remote.`,\n );\n }\n return sidecarNamespace;\n }\n\n if (configured.length === 1) {\n const namespace = configured[0];\n if (namespace !== undefined) return namespace;\n }\n if (configured.length > 1) {\n throw new Error(\n `Multiple TailorDB namespaces are defined (${configured.join(\", \")}). Specify one with --namespace.`,\n );\n }\n if (!remote && allNamespaces.length > 0) {\n throw new Error(\n `No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${allNamespaces.join(\", \")}.`,\n );\n }\n throw new Error(\"No TailorDB namespace is defined in the config.\");\n}\n\n/**\n * Resolve the absolute path of the kysely-type plugin's generated types file.\n * The plugin's relative `distPath` resolves against the working directory,\n * matching where `tailor generate` writes it.\n * @param plugins - The project's configured plugins\n * @returns Absolute path of the generated types file\n */\nfunction resolveKyselyTypesPath(plugins: readonly Plugin[]): string {\n const distPath =\n resolvePluginConfig(plugins, KyselyGeneratorID)?.distPath ?? DEFAULT_KYSELY_TYPES_DIST_PATH;\n if (distPath.length === 0) {\n throw new Error(\"kyselyTypePlugin is configured without a distPath; cannot locate getDB().\");\n }\n return path.resolve(distPath);\n}\n\n/**\n * Convert a relative file path into a TypeScript import specifier.\n * @param relativePath - Path relative to the importing file's directory\n * @returns Import specifier with a ./ prefix and no .ts extension\n */\nfunction toImportSpecifier(relativePath: string): string {\n const withoutExt = relativePath.replace(/\\.ts$/, \"\");\n return withoutExt.startsWith(\".\") ? withoutExt : `./${withoutExt}`;\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { logsCommand } from \"./logs\";\nimport { runFunctionCommand } from \"./run\";\nimport { scriptCommand } from \"./script\";\n\nexport const functionCommand = defineCommand({\n name: \"function\",\n description: \"Manage functions\",\n subCommands: {\n get: getCommand,\n list: listCommand,\n logs: logsCommand,\n run: runFunctionCommand,\n script: scriptCommand,\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 { toError } from \"#/cli/shared/errors\";\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 // A fetch failure here rejects with TypeError, which the top-level handler\n // classifies as an SDK bug and crash-reports.\n const authorizeUri = await client.authorizationCode\n .getAuthorizeUri({ redirectUri, state, codeVerifier })\n .catch((error: unknown) => {\n throw new Error(`Failed to prepare the login authorization URL: ${toError(error).message}`, {\n cause: error,\n });\n });\n\n return new Promise<void>((resolve, reject) => {\n const handleCallback = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\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(toError(error));\n } finally {\n // Close the server after handling one request.\n server.close();\n }\n };\n const server = http.createServer((req, res) => void handleCallback(req, res));\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 const openBrowser = async (): Promise<void> => {\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 server.listen(redirectPort, () => void openBrowser());\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\";\nimport { parseBoolean } from \"#/cli/shared/parse-boolean\";\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 =\n parseBoolean(process.env.TAILOR_CONSOLE_NEXT) === true\n ? `/workspaces/${workspaceId}/services/applications/${encodeURIComponent(applicationName)}`\n : `/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 \"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 setup: \"@tailor-platform/sdk-plugin-setup\",\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 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 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options?.profile,\n workspaceId: options?.workspaceId,\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 { 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 if (logger.jsonMode) {\n logger.out([]);\n }\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options?.profile,\n workspaceId: options?.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { formatNextAction } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 table 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { fetchAll, fetchAllTolerant, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { subscribesToEvents } from \"#/cli/shared/publish-events\";\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 table 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 table 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 tables load, and may trigger on the target's tables.\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 tables\n // their record triggers depend on.\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 executorUsedTables = new Set<string>();\n for (const executor of Object.values(executorService?.executors ?? {})) {\n if (!subscribesToEvents(executor)) continue;\n if (executor.trigger.kind === \"tailordb\") {\n executorUsedTables.add(executor.trigger.tableName);\n }\n }\n const manifestOptions: GenerateAllManifestsOptions = {\n executorUsedTables,\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 table definitions — fix the migration files.\",\n { mode: \"plain\" },\n );\n logger.info(\n \" - Table 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 * table 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 tables: upsert the ones defined\n // in the snapshot, delete remote ones with no snapshot counterpart\n // (including those of deleted tables — an orphaned permission can block\n // the table 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(` Tables to create: ${styles.bold(String(creates.length))}`);\n logger.log(` Tables to update: ${styles.bold(String(updates.length))}`);\n logger.log(` Tables 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 tables; the label\n // may still be stale, so the sync proceeds to update it.\n logger.info(\"No tables to apply; only the migration label will be updated.\");\n } else {\n logger.warn(\n \"This operation will overwrite remote TailorDB tables to match the selected snapshot.\",\n );\n if (deletes.length > 0) {\n logger.warn(\"Existing data in deleted tables 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 = (tableName: string) => {\n const manifest = manifests.get(tableName);\n if (!manifest) {\n throw new Error(\n `Internal error: no manifest generated for table \"${tableName}\". No changes were applied.`,\n );\n }\n return manifest;\n };\n const createManifests = creates.map((tableName) => manifestFor(tableName));\n const updateManifests = updates.map((tableName) => manifestFor(tableName));\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((tableName) =>\n client.deleteTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbTypeName: tableName,\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 tables in a baseline snapshot.\n * @param dataDir - Directory containing `<Type>.jsonl` files\n * @param tableNames - Baseline table names to load\n * @param snapshot - Baseline schema used to remove fields introduced by pending migrations\n * @returns Seed rows keyed by table name\n */\nexport function loadSnapshotSeedData(\n dataDir: string,\n tableNames: string[],\n snapshot?: NormalizedSchemaSnapshot,\n): SeedData {\n const data: SeedData = {};\n for (const tableName of tableNames) {\n const snapshotType = snapshot?.tables[tableName];\n const jsonlPath = path.join(dataDir, `${tableName}.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[tableName] = [];\n continue;\n }\n throw error;\n }\n data[tableName] = 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 );\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 tables 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 tableNames = Object.keys(snapshot.tables);\n const available = new Set(tableNames);\n const dependencies = new Map<string, string[]>();\n const selfRefTypes: string[] = [];\n for (const [tableName, 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 === tableName) {\n selfRefTypes.push(tableName);\n } else if (available.has(target)) {\n referenced.add(target);\n }\n }\n dependencies.set(tableName, [...referenced]);\n }\n\n const visited = new Set<string>();\n const order: string[] = [];\n const visit = (tableName: string): void => {\n if (visited.has(tableName)) return;\n visited.add(tableName);\n for (const dependency of dependencies.get(tableName) ?? []) {\n visit(dependency);\n }\n order.push(tableName);\n };\n for (const tableName of tableNames) {\n visit(tableName);\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 tables 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((tableName) => (data[tableName]?.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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 tables 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 reports.map((r) => ({\n hasDrift: r.remoteSchema?.hasDrift ?? false,\n drifts: r.remoteSchema?.drifts ?? [],\n })),\n );\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 tables 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 { workspaceArgs } from \"#/cli/shared/args\";\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({ profile: workspaceArgs.profile }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const profile = args.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 { workspaceArgs } from \"#/cli/shared/args\";\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, activeProfile?: string): string | null {\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) {\n throw new Error(`Profile \"${activeProfile}\" not found`);\n }\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({ profile: workspaceArgs.profile }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n const activeProfile = args.profile || process.env.TAILOR_PLATFORM_PROFILE;\n const currentUserKey = activeCurrentUserKey(config, activeProfile);\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 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 { formatTimestamp } from \"#/cli/shared/format\";\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 createdAt: Date | null;\n /** `null` until the token has been used to authenticate. */\n lastUsedAt: Date | null;\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 createdAt: formatTimestamp(pat.createdAt),\n lastUsedAt: formatTimestamp(pat.lastUsedAt),\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 { loadAccessToken } from \"#/cli/shared/context\";\n\nexport async function createPatOperatorClient(activeProfile?: string) {\n const accessToken = await loadAccessToken({ profile: activeProfile });\n return await initOperatorClient(accessToken);\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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 { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { humanizeRelativeTime } from \"#/cli/shared/format\";\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(), profile: workspaceArgs.profile }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const client = await createPatOperatorClient(args.profile);\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 logger.out(patInfos, {\n display: {\n scopes: (value) => (value as string[]).join(\"/\"),\n lastUsedAt: (value) => (value === null ? \"never\" : humanizeRelativeTime(value as Date)),\n },\n });\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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 { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const activeProfileName = args.profile || 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 { 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 } 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.\nThe \\`setup\\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,\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 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\nvoid runMain(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: logger.verbose }));\n } else if (isCLIError(error)) {\n logger.log(error.format());\n if (logger.verbose && 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 (logger.verbose && 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":";i9GASA,MAAM,GAAmC,GAAgB,QAAQ,OAC9D,GAA4B,EAAE,aAAe,OAChD,EAEA,SAAgB,iBAA4B,CAC1C,OAAO,GAAc,IAAK,GAAM,EA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AY,MAAM,CACpE,CACF,CAAC,EAEI,GAAQ,GAAa,CACxB,QAAS,GAAY,QAErB,WAAY,EAAE,OAAO,EAAU,EAC/B,cAAe,GAGf,qBAAsB,CAAE,cAAa,OAAM,UACzC,8BAA8B,CAC5B,cACA,OACA,OACA,WACA,QAAS,QAAQ,IAAI,uBACvB,CAAC,EACH,QAAS,MAAO,CAAE,WAAY,CAC5B,GAAI,EAAO,CACT,GAAI,EAAO,SACT,EAAO,IAAI,GAAe,EAAO,CAAE,aAAc,EAAO,OAAQ,CAAC,CAAC,OAC7D,GAAI,GAAW,CAAK,EACzB,EAAO,IAAI,EAAM,OAAO,CAAC,EACrB,EAAO,SAAW,EAAM,OAC1B,EAAO,MAAM,mBAAmB,EAAM,OAAO,OAE1C,GAAI,aAAiB,MAAO,CACjC,EAAO,MAAM,EAAM,OAAO,EAC1B,IAAM,EAAO,GAAmB,CAAK,EACjC,GACF,EAAO,IAAI,KAAK,EAAO,KAAK,aAAa,EAAE,GAAG,GAAM,EAElD,EAAO,SAAW,EAAM,OAC1B,EAAO,MAAM,mBAAmB,EAAM,OAAO,CAEjD,MACE,EAAO,MAAM,kBAAkB,GAAO,EAWxC,GAFE,CAAC,GAAW,CAAK,IAChB,EAAE,aAAiB,QAAU,aAAiB,WAAa,aAAiB,YAC7D,CAEhB,GAAM,CAAE,eAAgB,MAAM,OAAO,+BACrC,MAAM,EAAY,EAAO,cAAc,CACzC,CACF,CACA,GAAM,CAAE,qBAAsB,MAAM,OAAO,6BAC3C,MAAM,EAAkB,CAC1B,CACF,CAAC"}
1
+ {"version":3,"file":"main.mjs","names":["CLIError","listCommand","listCommand","statusCommand","statusCommand","randomState","listCommand","listCommand","listCommand","getCommand","getCommand","listCommand","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","listCommand","deployCommand","listCommand","generateCommand","scriptCommand","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/status.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/script-scaffold.ts","../../src/cli/commands/function/run.ts","../../src/cli/commands/function/script.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/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\ninterface InspectMessageJson {\n typeName: string;\n fields: InspectFieldJson[];\n /** True when truncated to break a recursive type cycle. */\n recursive?: boolean;\n}\n\ninterface 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: \"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: \"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: \"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: \"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 { loadAuthStatus } from \"#/cli/shared/context\";\nimport { logger } from \"#/cli/shared/logger\";\n\nexport const statusCommand = defineAppCommand({\n name: \"status\",\n description: \"Show the active Tailor Platform authentication status without printing tokens.\",\n args: z.strictObject({\n profile: workspaceArgs.profile,\n }),\n run: async ({ profile }) => {\n const status = await loadAuthStatus({ profile });\n logger.out(status);\n if (!status.authenticated) {\n throw new Error(\"Not authenticated. Run 'tailor login' and try again.\");\n }\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 { statusCommand } from \"./status\";\nimport { tokenCommand } from \"./token\";\n\nexport const authCommand = defineCommand({\n name: \"auth\",\n description: \"Authentication helpers for scripts and plugins.\",\n subCommands: {\n status: statusCommand,\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { toError } from \"#/cli/shared/errors\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 // A fetch failure rejects with TypeError, which the top-level handler\n // classifies as an SDK bug and crash-reports.\n const response = await fetch(url).catch((error: unknown) => {\n throw new Error(`Failed to fetch OIDC discovery from ${url}: ${toError(error).message}`, {\n cause: error,\n });\n });\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 handleCallback = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\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(toError(err));\n }\n };\n const server = http.createServer((req, res) => void handleCallback(req, res));\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 const announceAuthorizeUrl = async (): Promise<void> => {\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 server.listen(args.port, () => void announceAuthorizeUrl());\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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\";\nimport { parseBoolean } from \"#/cli/shared/parse-boolean\";\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 =\n parseBoolean(process.env.TAILOR_CONSOLE_NEXT) === true\n ? `/workspaces/${workspaceId}/services/auth-connections`\n : `/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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 function 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 */\ninterface 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 function 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, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\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 { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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. function 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 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 the function run command\n *\n * Bundles a single function file for server-side execution.\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 { buildResolverValidatedInputExpr, 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 BundleForRunOptions {\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 BundleForRunResult {\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 `function run` execution.\n * @param options - Bundle options\n * @returns Bundled code and script name\n */\nexport async function bundleForRun(options: BundleForRunOptions): Promise<BundleForRunResult> {\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 buildResolverValidatedInputExpr 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 function run, we embed machine user info since there's no operationHook.\n const principalExpr = buildMachinePrincipalExpr(machineUser, workspaceId);\n const validatedInputExpr = buildResolverValidatedInputExpr({\n permission: detected.permission,\n defaultPermission,\n });\n return ml /* js */ `\n import _internalResolver from \"${absoluteSourcePath}\";\n import { t } from \"@tailor-platform/sdk\";\n import { serializeDateFields } from \"@tailor-platform/sdk/runtime\";\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 const input = ${validatedInputExpr};\n const result = await _internalResolver.body({ ...context, input });\n return serializeDateFields(_internalResolver.output, result);\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 function 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 when executing workflow jobs this way.\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 the function 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\ntype 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 * Scaffolding helpers for the `tailor function script` command.\n *\n * A scaffolded one-off script is a plain default-exported function that\n * `tailor function run` executes on the platform without deploying. When the\n * project does not configure `kyselyTypePlugin`, the scaffold also writes a\n * script-scoped `db.ts` generated from local table definitions by default, plus a\n * `db.snapshot.json` snapshot that `function run` checks for schema drift.\n */\n\nimport * as fs from \"node:fs\";\nimport { parseSync } from \"oxc-parser\";\nimport * as path from \"pathe\";\nimport {\n hasChanges,\n formatMigrationDiff,\n type MigrationDiff,\n} from \"#/cli/commands/tailordb/migrate/diff-calculator\";\nimport { fetchRemoteSchemaSnapshot } from \"#/cli/commands/tailordb/migrate/schema-checks\";\nimport {\n compareSnapshots,\n createRemoteComparableSnapshot,\n createSnapshotType,\n normalizeSchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type SchemaSnapshot,\n type TailorDBSnapshotType,\n} from \"#/cli/commands/tailordb/migrate/snapshot\";\nimport { DEFAULT_CONFIG_PATH } from \"#/cli/shared/args\";\nimport { extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { formatCopyableCommand } from \"#/cli/shared/errors\";\nimport { loadTailorDBNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport {\n generateUnifiedKyselyTypes,\n processKyselyFields,\n} from \"#/plugin/builtin/kysely-type/type-processor\";\nimport type { SnapshotFieldConfig } from \"#/cli/commands/tailordb/migrate/snapshot-types\";\nimport type { OperatorClient } from \"#/cli/shared/client\";\nimport type { LoadedConfig } from \"#/cli/shared/config-loader\";\n\n/** File name of the script-scoped Kysely types written next to a scaffolded script. */\nexport const SCRIPT_DB_TYPES_FILE_NAME = \"db.ts\";\n/** File name of the schema snapshot written next to a scaffolded script. */\nexport const SCRIPT_SNAPSHOT_FILE_NAME = \"db.snapshot.json\";\n\nconst GENERATED_DB_TYPES_HEADER = [\n \"/**\",\n \" * Auto-generated Kysely types for one-off scripts in this directory.\",\n \" * Generated by `tailor function script` from the selected TailorDB schema.\",\n \" *\",\n \" * DO NOT EDIT - Re-run `tailor function script` to refresh.\",\n \" */\",\n].join(\"\\n\");\n\n/**\n * Generate the script-scoped `db.ts` contents from a schema snapshot.\n * @param snapshot - Schema snapshot of the target namespace\n * @returns Generated `db.ts` file contents\n */\nexport function generateScriptDbTypes(snapshot: SchemaSnapshot): string {\n const types = Object.values(snapshot.tables).map((table) =>\n processKyselyFields(table.name, table.fields),\n );\n const body = generateUnifiedKyselyTypes([{ namespace: snapshot.namespace, types }]);\n return `${GENERATED_DB_TYPES_HEADER}\\n\\n${body}`;\n}\n\n/**\n * Whether an existing file at the script-scoped `db.ts` path was written by\n * the scaffold (and is therefore safe to overwrite).\n * @param content - Existing file contents\n * @returns true when the scaffold header is present\n */\nexport function isGeneratedScriptDbTypes(content: string): boolean {\n return content.includes(\"Generated by `tailor function script`\");\n}\n\n/**\n * Assert generated TypeScript parses before it is written to disk.\n * @param filePath - Destination path (named in the error)\n * @param content - Generated source\n */\nexport function assertGeneratedTypeScript(filePath: string, content: string): void {\n const { errors } = parseSync(path.basename(filePath), content);\n if (errors.length > 0) {\n throw new Error(\n `Generated ${filePath} does not parse as TypeScript: ${errors\n .map((error) => error.message)\n .join(\"; \")}`,\n );\n }\n}\n\n/** Options for {@link generateScriptSkeleton}. */\nexport interface ScriptSkeletonOptions {\n /** Module specifier the skeleton imports `getDB` from */\n getDBImportPath: string;\n /** TailorDB namespace passed to `getDB()` */\n namespace: string;\n}\n\n/**\n * Generate the one-off script skeleton.\n * @param options - Skeleton options\n * @returns Skeleton file contents\n */\nexport function generateScriptSkeleton(options: ScriptSkeletonOptions): string {\n const { getDBImportPath, namespace } = options;\n return [\n \"/**\",\n \" * One-off script. Run it on the platform without deploying:\",\n \" *\",\n \" * tailor function run <this file>\",\n \" *\",\n \" * For large tables, batch updates by primary-key range instead of one\",\n ' * statement over the whole table; see the \"Performance and Large Tables\"',\n \" * section in @tailor-platform/sdk's docs/services/tailordb-migration.md.\",\n \" */\",\n \"\",\n `import { getDB } from ${JSON.stringify(getDBImportPath)};`,\n \"\",\n \"export default async function main() {\",\n ` const db = getDB(${JSON.stringify(namespace)});`,\n \"\",\n \" // A transaction rolls every change back when any statement fails.\",\n \" await db.transaction().execute(async (trx) => {\",\n ' // e.g. await trx.updateTable(\"MyTable\").set({ ... }).where(\"id\", \"=\", \"...\").execute();',\n \" });\",\n \"}\",\n \"\",\n ].join(\"\\n\");\n}\n\n/** A schema snapshot sidecar found next to a script. */\nexport interface ScriptSchemaSnapshotSidecar {\n /** Path of the snapshot file */\n snapshotPath: string;\n /** Source used to generate the stored snapshot */\n source: \"local\" | \"remote\";\n /** The stored snapshot, normalized */\n snapshot: NormalizedSchemaSnapshot;\n}\n\n/**\n * Load the schema snapshot written next to a scaffolded script, if present.\n * @param scriptPath - Absolute path of the script passed to `function run`\n * @returns The snapshot sidecar, or null when the script has none\n */\nexport function loadScriptSchemaSnapshot(scriptPath: string): ScriptSchemaSnapshotSidecar | null {\n const snapshotPath = path.join(path.dirname(scriptPath), SCRIPT_SNAPSHOT_FILE_NAME);\n if (!fs.existsSync(snapshotPath)) {\n return null;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(snapshotPath, \"utf-8\"));\n } catch (error) {\n throw new Error(\n `Failed to parse schema snapshot ${snapshotPath}: ${error instanceof Error ? error.message : error}. ` +\n \"Re-run `tailor function script` to regenerate it.\",\n { cause: error },\n );\n }\n const candidate = parsed as Record<string, unknown> | null;\n if (\n typeof candidate !== \"object\" ||\n candidate === null ||\n typeof candidate.namespace !== \"string\" ||\n typeof candidate.tables !== \"object\" ||\n candidate.tables === null\n ) {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n const source = candidate.source ?? \"remote\";\n if (source !== \"local\" && source !== \"remote\") {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n const snapshotData = { ...candidate };\n delete snapshotData.source;\n\n try {\n return {\n snapshotPath,\n source,\n snapshot: normalizeSchemaSnapshot(snapshotData as unknown as SchemaSnapshot),\n };\n } catch {\n throw unexpectedSnapshotShapeError(snapshotPath);\n }\n}\n\nfunction unexpectedSnapshotShapeError(snapshotPath: string): Error {\n return new Error(\n `Schema snapshot ${snapshotPath} has an unexpected shape. ` +\n \"Re-run `tailor function script` to regenerate it.\",\n );\n}\n\n/** Options for {@link verifyScriptSchemaSnapshot}. */\nexport interface VerifyScriptSchemaSnapshotOptions {\n /** Operator client */\n client: OperatorClient;\n /** Workspace ID */\n workspaceId: string;\n /** Loaded config */\n config: LoadedConfig;\n /** Config path as passed on the command line (threaded into hints) */\n configArgValue: string;\n /** Script path as passed on the command line (threaded into hints) */\n scriptArgValue: string;\n /** Profile as passed on the command line, when any (threaded into hints) */\n profileArgValue?: string;\n /** The snapshot sidecar found next to the script */\n sidecar: ScriptSchemaSnapshotSidecar;\n}\n\n/**\n * Verify a scaffolded script's schema snapshot still matches the local table\n * definitions (when the config owns the namespace) and the deployed schema.\n * @param options - Verification inputs\n * @throws When either comparison detects drift\n */\nexport async function verifyScriptSchemaSnapshot(\n options: VerifyScriptSchemaSnapshotOptions,\n): Promise<void> {\n const { client, workspaceId, config, configArgValue, sidecar } = options;\n const { snapshot } = sidecar;\n const namespace = snapshot.namespace;\n\n if (extractOwnedNamespaces(config).includes(namespace)) {\n const { namespaces } = await loadTailorDBNamespaces({\n configPath: configArgValue,\n namespaces: [namespace],\n });\n const namespaceData = namespaces[0];\n if (namespaceData) {\n const localTables: Record<string, TailorDBSnapshotType> = Object.fromEntries(\n Object.values(namespaceData.tables).map((table) => [table.name, createSnapshotType(table)]),\n );\n // Compare the field contract that generated db.ts consumes. Local\n // create hooks and defaults are represented remotely as\n // optionalOnCreate, so normalize all three forms to that contract.\n const diff = compareSnapshots(\n generatedContractSnapshot(snapshot),\n generatedContractSnapshot({ ...snapshot, tables: localTables }),\n );\n if (hasChanges(diff)) {\n throw schemaDriftError(\"the local table definitions\", diff, options);\n }\n }\n }\n\n const remoteSnapshot = await fetchRemoteSchemaSnapshot(client, workspaceId, namespace);\n // Legacy and remote-generated sidecars are directly comparable with the\n // deployed schema. Local sidecars require the generated-contract projection\n // because create hooks and defaults become optionalOnCreate when deployed.\n const remoteDiff = compareSnapshots(\n sidecar.source === \"local\"\n ? generatedContractSnapshot(snapshot)\n : normalizeSchemaSnapshot(pickTableFields(snapshot)),\n sidecar.source === \"local\"\n ? generatedContractSnapshot(remoteSnapshot)\n : normalizeSchemaSnapshot(pickTableFields(remoteSnapshot)),\n );\n if (hasChanges(remoteDiff)) {\n throw schemaDriftError(\"the deployed schema\", remoteDiff, options);\n }\n}\n\n/**\n * Project a snapshot down to what the generated db.ts depends on: table\n * fields, with script-bearing props stripped by the remote-comparable\n * projection.\n * @param snapshot - Snapshot to project\n * @returns Normalized snapshot carrying only table names and fields\n */\nfunction fieldsOnlySnapshot(snapshot: SchemaSnapshot): NormalizedSchemaSnapshot {\n return normalizeSchemaSnapshot(pickTableFields(createRemoteComparableSnapshot(snapshot)));\n}\n\n/**\n * Project a snapshot to the field contract consumed by generated Kysely types.\n * @param snapshot - Snapshot to project\n * @returns Normalized fields-only snapshot with generated-on-create semantics preserved\n */\nfunction generatedContractSnapshot(snapshot: SchemaSnapshot): NormalizedSchemaSnapshot {\n const comparable = fieldsOnlySnapshot(snapshot);\n const tables = Object.fromEntries(\n Object.entries(comparable.tables).map(([tableName, table]) => {\n const sourceTable = snapshot.tables[tableName];\n const fields = Object.fromEntries(\n Object.entries(table.fields).map(([fieldName, field]) => [\n fieldName,\n preserveGeneratedContract(field, sourceTable?.fields[fieldName]),\n ]),\n );\n return [tableName, { ...table, fields }];\n }),\n );\n return normalizeSchemaSnapshot({ ...comparable, tables });\n}\n\nfunction preserveGeneratedContract(\n comparable: SnapshotFieldConfig,\n source: SnapshotFieldConfig | undefined,\n): SnapshotFieldConfig {\n const fields = comparable.fields\n ? Object.fromEntries(\n Object.entries(comparable.fields).map(([fieldName, field]) => [\n fieldName,\n preserveGeneratedContract(field, source?.fields?.[fieldName]),\n ]),\n )\n : undefined;\n const generated =\n source?.hooks?.create !== undefined ||\n source?.default !== undefined ||\n source?.optionalOnCreate === true;\n return {\n ...comparable,\n ...(fields === undefined ? {} : { fields }),\n ...(generated ? { optionalOnCreate: true } : {}),\n };\n}\n\n/**\n * Keep only what the generated db.ts is built from: table names and fields.\n * @param snapshot - Snapshot to project\n * @returns Snapshot whose tables carry only name, pluralForm, and fields\n */\nfunction pickTableFields(snapshot: SchemaSnapshot): SchemaSnapshot {\n const tables = Object.fromEntries(\n Object.entries(snapshot.tables).map(([tableName, table]) => [\n tableName,\n { name: table.name, pluralForm: table.pluralForm, fields: table.fields },\n ]),\n );\n return { ...snapshot, tables };\n}\n\nfunction schemaDriftError(\n target: string,\n diff: MigrationDiff,\n options: VerifyScriptSchemaSnapshotOptions,\n): Error {\n const contextFlags = [\n ...(options.configArgValue !== DEFAULT_CONFIG_PATH\n ? [`--config=${options.configArgValue}`]\n : []),\n `--workspace-id=${options.workspaceId}`,\n ...(options.profileArgValue !== undefined ? [`--profile=${options.profileArgValue}`] : []),\n ];\n const rescaffold = formatCopyableCommand([\n \"tailor\",\n \"function\",\n \"script\",\n options.scriptArgValue,\n ...(options.sidecar.source === \"remote\" ? [\"--remote\"] : []),\n ...contextFlags,\n ]);\n const override = formatCopyableCommand([\n \"tailor\",\n \"function\",\n \"run\",\n options.scriptArgValue,\n \"--allow-schema-drift\",\n ...contextFlags,\n ]);\n return new Error(\n `Schema drift detected: ${SCRIPT_SNAPSHOT_FILE_NAME} next to the script no longer matches ${target}.\\n\\n` +\n `${formatMigrationDiff(diff)}\\n\\n` +\n `Refresh the generated types with ${rescaffold}, or run anyway with ${override}.`,\n );\n}\n","/**\n * `tailor function 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, extractFields, toCamelCase } from \"politty\";\nimport { z } from \"zod\";\nimport { resolveResolverDefaultPermissionForFile } from \"#/cli/services/resolver/default-permission\";\nimport {\n commonArgs,\n resolveMachineUserInputSource,\n type MachineUserInputSource,\n workspaceArgs,\n} from \"#/cli/shared/args\";\nimport { type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { loadMachineUserName } from \"#/cli/shared/context\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { executeScript } from \"#/cli/shared/script-executor\";\nimport { formatErrorWithSourcemap } from \"#/cli/shared/stack-trace\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { bundleForRun, type ResolvedMachineUser } from \"./bundle\";\nimport { detectFunctionType } from \"./detect\";\nimport {\n SCRIPT_SNAPSHOT_FILE_NAME,\n loadScriptSchemaSnapshot,\n verifyScriptSchemaSnapshot,\n} from \"./script-scaffold\";\nimport type { Jsonifiable } from \"type-fest\";\n\nexport const runFunctionCommand = defineAppCommand({\n name: \"run\",\n aliases: [\"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 \"allow-schema-drift\": arg(z.boolean().default(false), {\n description: \"Run a scaffolded script even when its schema snapshot no longer matches\",\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\nA script scaffolded by \\`function script\\` with a generated \\`db.ts\\` is checked against its \\`db.snapshot.json\\` before execution and refused on schema drift; pass \\`--allow-schema-drift\\` to run it anyway. The check compares table and field structure; hook and validator code changes are not detected.\n\n\\`test-run\\` is a deprecated alias of this command and will be removed in v3.\n\n> [!WARNING]\n> Workflow job \\`.start()\\` calls do not work in this 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 if (invokedViaTestRunAlias(process.argv)) {\n logger.warn(\n \"`tailor function test-run` is deprecated and will be removed in v3. Use `tailor function run` instead.\",\n );\n }\n\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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\n if (!isPreBundled) {\n if (args[\"allow-schema-drift\"]) {\n if (fs.existsSync(path.join(path.dirname(filePath), SCRIPT_SNAPSHOT_FILE_NAME))) {\n logger.warn(\"Skipping the schema snapshot check (--allow-schema-drift).\");\n }\n } else {\n const sidecar = loadScriptSchemaSnapshot(filePath);\n if (sidecar) {\n logger.info(\"Checking the script's schema snapshot for drift...\");\n await verifyScriptSchemaSnapshot({\n client,\n workspaceId,\n config,\n configArgValue: args.config,\n scriptArgValue: args.file,\n profileArgValue: args.profile,\n sidecar,\n });\n }\n }\n }\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 bundleForRun({\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 the bundled script\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 * Global option tokens that consume the following argv token as their value.\n * politty accepts both the kebab-case and camelCase spelling of every name.\n */\nconst valueTakingGlobalFlags: ReadonlySet<string> = new Set(\n extractFields(z.strictObject(commonArgs))\n .fields.filter((field) => field.type !== \"boolean\")\n .flatMap((field) => [field.cliName, ...(field.alias ?? [])].flatMap(toFlagTokens)),\n);\n\nfunction toFlagTokens(name: string): string[] {\n if (name.length === 1) return [`-${name}`];\n return [`--${name}`, `--${toCamelCase(name)}`];\n}\n\n/**\n * Detect whether the command was invoked through the deprecated `test-run`\n * alias. politty resolves aliases before dispatch, so the invoked name is only\n * observable from the raw argv. Global options may sit anywhere before the\n * subcommand (`tailor function --json test-run`), so option tokens and any\n * values they consume are skipped; an option value is never read as a command\n * name.\n * @param argv - Process argv tokens\n * @returns true when `test-run` was the subcommand name under `function`\n */\nfunction invokedViaTestRunAlias(argv: readonly string[]): boolean {\n const names: string[] = [];\n // argv[0] is the node binary and argv[1] the CLI entry point.\n for (let i = 2; i < argv.length && names.length < 2; i++) {\n const token = argv[i];\n if (token === undefined || token === \"--\") break;\n if (!token.startsWith(\"-\")) {\n names.push(token);\n continue;\n }\n if (!token.includes(\"=\") && valueTakingGlobalFlags.has(token)) i++;\n }\n return names[0] === \"function\" && names[1] === \"test-run\";\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","/**\n * `tailor function script` command\n *\n * Scaffolds a one-off script that `tailor function run` executes on the\n * Tailor Platform server without deploying.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { fetchRemoteSchemaSnapshot } from \"#/cli/commands/tailordb/migrate/schema-checks\";\nimport {\n createSnapshotFromLocalTypes,\n type NormalizedSchemaSnapshot,\n} from \"#/cli/commands/tailordb/migrate/snapshot\";\nimport { workspaceArgs, configArg, DEFAULT_CONFIG_PATH } from \"#/cli/shared/args\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { extractAllNamespaces, extractOwnedNamespaces } from \"#/cli/shared/config\";\nimport { loadConfig, type LoadedConfig } from \"#/cli/shared/config-loader\";\nimport { formatCopyableCommand } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { loadTailorDBNamespaces } from \"#/cli/shared/tailordb-namespaces\";\nimport {\n KyselyGeneratorID,\n DEFAULT_KYSELY_TYPES_DIST_PATH,\n} from \"#/plugin/builtin/kysely-type/index\";\nimport { resolvePluginConfig } from \"#/plugin/get-plugin-config\";\nimport { assertDefined } from \"#/utils/assert\";\nimport {\n SCRIPT_DB_TYPES_FILE_NAME,\n SCRIPT_SNAPSHOT_FILE_NAME,\n assertGeneratedTypeScript,\n generateScriptDbTypes,\n generateScriptSkeleton,\n isGeneratedScriptDbTypes,\n loadScriptSchemaSnapshot,\n} from \"./script-scaffold\";\nimport type { Plugin } from \"#/plugin/types\";\n\nexport const scriptCommand = defineAppCommand({\n name: \"script\",\n description: \"Scaffold a one-off script to run with `function run`.\",\n // strip unknown keys\n args: z.object({\n ...workspaceArgs,\n ...configArg,\n file: arg(z.string(), {\n positional: true,\n description: \"Path to create the script at (must end with .ts)\",\n }),\n namespace: arg(z.string().optional(), {\n description: \"Target TailorDB namespace (required when the config does not pin one)\",\n }),\n remote: arg(z.boolean().default(false), {\n description: \"Generate script-scoped DB types from the deployed schema\",\n }),\n }),\n notes: `The scaffolded script is a plain default-exported function; execute it with \\`tailor function run <file>\\`.\n\nBy default, when the project configures \\`kyselyTypePlugin\\`, the skeleton imports \\`getDB()\\` from the plugin's generated types. Without the plugin, the command uses the namespace's local table definitions to write a script-scoped \\`db.ts\\` plus a \\`db.snapshot.json\\` next to the script; \\`function run\\` refuses to run the script when that snapshot no longer matches the deployed or locally defined table and field structure.\n\nPass \\`--remote\\` to generate the script-scoped files from the deployed schema instead, even when \\`kyselyTypePlugin\\` is configured. This is required for an external namespace. Re-running the command refreshes \\`db.ts\\` and \\`db.snapshot.json\\` from the selected source and leaves the script itself untouched.`,\n examples: [\n {\n cmd: \"scripts/fix-prices.ts\",\n desc: \"Scaffold a one-off script (single-namespace project)\",\n },\n {\n cmd: \"scripts/fix-prices.ts --namespace tailordb\",\n desc: \"Scaffold a script targeting a specific namespace\",\n },\n {\n cmd: \"scripts/fix-prices.ts --namespace shared --remote\",\n desc: \"Scaffold from a deployed or external namespace\",\n },\n ],\n run: async (args) => {\n const filePath = path.resolve(args.file);\n if (!filePath.endsWith(\".ts\")) {\n throw new Error(`Script path must end with .ts: ${args.file}`);\n }\n const scriptDir = path.dirname(filePath);\n const scriptExists = fs.existsSync(filePath);\n const dbTypesPath = path.join(scriptDir, SCRIPT_DB_TYPES_FILE_NAME);\n const snapshotPath = path.join(scriptDir, SCRIPT_SNAPSHOT_FILE_NAME);\n if (filePath === dbTypesPath) {\n throw new Error(\n `${SCRIPT_DB_TYPES_FILE_NAME} is reserved for the generated Kysely types written next to the script. Choose a different script file name.`,\n );\n }\n\n const { config, plugins } = await loadConfig(args.config);\n const kyselyPlugin = plugins.find((plugin) => plugin.id === KyselyGeneratorID);\n const hasSnapshotSidecar = fs.existsSync(snapshotPath);\n if (args.remote && kyselyPlugin !== undefined && scriptExists && !hasSnapshotSidecar) {\n throw new Error(\n `Script already exists: ${path.relative(process.cwd(), filePath)}. ` +\n \"Scaffold --remote at a new path so the generated script imports its script-scoped db.ts.\",\n );\n }\n // A directory that already carries a snapshot sidecar keeps using\n // script-scoped generated types, even when the project has since\n // configured kyselyTypePlugin: its scripts import ./db.\n const useGeneratedDbTypes = args.remote || kyselyPlugin === undefined || hasSnapshotSidecar;\n\n let existingSidecarNamespace: string | undefined;\n if (useGeneratedDbTypes) {\n try {\n existingSidecarNamespace = loadScriptSchemaSnapshot(filePath)?.snapshot.namespace;\n } catch {\n // A corrupt sidecar is regenerated below; resolve from the config instead.\n }\n }\n const namespace = resolveNamespace({\n config,\n explicit: args.namespace,\n sidecarNamespace: existingSidecarNamespace,\n remote: args.remote,\n });\n if (existingSidecarNamespace !== undefined && existingSidecarNamespace !== namespace) {\n throw new Error(\n `This directory's generated types target namespace \"${existingSidecarNamespace}\" (${SCRIPT_SNAPSHOT_FILE_NAME}). ` +\n `Scaffold scripts for namespace \"${namespace}\" in a separate directory.`,\n );\n }\n\n const created: string[] = [];\n let getDBImportPath: string;\n let resolvedWorkspaceId: string | undefined;\n\n if (!useGeneratedDbTypes) {\n if (scriptExists) {\n throw new Error(\n `Script already exists: ${path.relative(process.cwd(), filePath)}. ` +\n \"It imports the project's generated Kysely types, so there is nothing to refresh.\",\n );\n }\n const generatedTypesPath = resolveKyselyTypesPath(plugins);\n getDBImportPath = toImportSpecifier(path.relative(scriptDir, generatedTypesPath));\n if (!fs.existsSync(generatedTypesPath)) {\n logger.warn(\n `Generated Kysely types not found at ${styles.path(path.relative(process.cwd(), generatedTypesPath))}. Run \\`tailor generate\\` before executing the script.`,\n );\n }\n } else {\n let snapshot: NormalizedSchemaSnapshot;\n if (args.remote) {\n const { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\n });\n resolvedWorkspaceId = workspaceId;\n\n logger.info(`Fetching deployed schema of namespace ${styles.bold(namespace)}...`);\n snapshot = await fetchRemoteSchemaSnapshot(client, workspaceId, namespace);\n } else {\n logger.info(`Loading local definitions of namespace ${styles.bold(namespace)}...`);\n const { namespaces } = await loadTailorDBNamespaces({\n configPath: args.config,\n namespaces: [namespace],\n });\n const namespaceData = assertDefined(namespaces[0], `namespace ${namespace}`);\n snapshot = createSnapshotFromLocalTypes(namespaceData.tables, namespace);\n }\n if (Object.keys(snapshot.tables).length === 0) {\n const sourceDescription = args.remote\n ? `deployed tables in workspace ${assertDefined(resolvedWorkspaceId, \"workspace ID\")}`\n : \"locally defined tables\";\n throw new Error(`Namespace \"${namespace}\" has no ${sourceDescription}.`);\n }\n\n if (fs.existsSync(dbTypesPath)) {\n const existing = fs.readFileSync(dbTypesPath, \"utf-8\");\n if (!isGeneratedScriptDbTypes(existing)) {\n throw new Error(\n `Refusing to overwrite ${path.relative(process.cwd(), dbTypesPath)}: ` +\n \"it was not generated by `tailor function script`.\",\n );\n }\n }\n const dbTypesContent = generateScriptDbTypes(snapshot);\n assertGeneratedTypeScript(dbTypesPath, dbTypesContent);\n fs.mkdirSync(scriptDir, { recursive: true });\n fs.writeFileSync(dbTypesPath, dbTypesContent);\n created.push(dbTypesPath);\n fs.writeFileSync(\n snapshotPath,\n JSON.stringify({ ...snapshot, source: args.remote ? \"remote\" : \"local\" }, null, 2) + \"\\n\",\n );\n created.push(snapshotPath);\n getDBImportPath = \"./db\";\n }\n\n if (!scriptExists) {\n const skeleton = generateScriptSkeleton({ getDBImportPath, namespace });\n assertGeneratedTypeScript(filePath, skeleton);\n fs.mkdirSync(scriptDir, { recursive: true });\n fs.writeFileSync(filePath, skeleton);\n created.unshift(filePath);\n }\n\n const relScript = path.relative(process.cwd(), filePath);\n const runArgv = [\"tailor\", \"function\", \"run\", relScript];\n if (args.config !== DEFAULT_CONFIG_PATH) {\n runArgv.push(`--config=${args.config}`);\n }\n const workspaceIdForHint = resolvedWorkspaceId ?? args[\"workspace-id\"];\n if (workspaceIdForHint !== undefined) {\n runArgv.push(`--workspace-id=${workspaceIdForHint}`);\n }\n if (args.profile !== undefined) {\n runArgv.push(`--profile=${args.profile}`);\n }\n\n if (logger.jsonMode) {\n logger.out({\n script: filePath,\n created,\n namespace,\n usesGeneratedDbTypes: useGeneratedDbTypes,\n });\n return;\n }\n\n if (scriptExists) {\n logger.info(`Script already exists; refreshed generated types only.`);\n }\n for (const file of created) {\n logger.success(`Created ${styles.path(path.relative(process.cwd(), file))}`);\n }\n logger.info(`Next: edit the script, then run ${formatCopyableCommand(runArgv)}`);\n },\n});\n\ninterface ResolveNamespaceOptions {\n config: LoadedConfig;\n explicit: string | undefined;\n sidecarNamespace: string | undefined;\n remote: boolean;\n}\n\n/**\n * Resolve the target TailorDB namespace for the scaffold.\n * @param options - Resolution inputs\n * @returns The namespace name\n */\nfunction resolveNamespace(options: ResolveNamespaceOptions): string {\n const { config, explicit, sidecarNamespace, remote } = options;\n const allNamespaces = extractAllNamespaces(config);\n const ownedNamespaces = extractOwnedNamespaces(config);\n const configured = remote ? allNamespaces : ownedNamespaces;\n\n if (explicit) {\n if (!remote && !ownedNamespaces.includes(explicit)) {\n throw new Error(`Namespace \"${explicit}\" is not owned by the config and requires --remote.`);\n }\n return explicit;\n }\n\n if (sidecarNamespace !== undefined) {\n if (!remote && !ownedNamespaces.includes(sidecarNamespace)) {\n throw new Error(\n `Namespace \"${sidecarNamespace}\" is not owned by the config and requires --remote.`,\n );\n }\n return sidecarNamespace;\n }\n\n if (configured.length === 1) {\n const namespace = configured[0];\n if (namespace !== undefined) return namespace;\n }\n if (configured.length > 1) {\n throw new Error(\n `Multiple TailorDB namespaces are defined (${configured.join(\", \")}). Specify one with --namespace.`,\n );\n }\n if (!remote && allNamespaces.length > 0) {\n throw new Error(\n `No owned TailorDB namespace is defined in the config. External namespaces require --remote: ${allNamespaces.join(\", \")}.`,\n );\n }\n throw new Error(\"No TailorDB namespace is defined in the config.\");\n}\n\n/**\n * Resolve the absolute path of the kysely-type plugin's generated types file.\n * The plugin's relative `distPath` resolves against the working directory,\n * matching where `tailor generate` writes it.\n * @param plugins - The project's configured plugins\n * @returns Absolute path of the generated types file\n */\nfunction resolveKyselyTypesPath(plugins: readonly Plugin[]): string {\n const distPath =\n resolvePluginConfig(plugins, KyselyGeneratorID)?.distPath ?? DEFAULT_KYSELY_TYPES_DIST_PATH;\n if (distPath.length === 0) {\n throw new Error(\"kyselyTypePlugin is configured without a distPath; cannot locate getDB().\");\n }\n return path.resolve(distPath);\n}\n\n/**\n * Convert a relative file path into a TypeScript import specifier.\n * @param relativePath - Path relative to the importing file's directory\n * @returns Import specifier with a ./ prefix and no .ts extension\n */\nfunction toImportSpecifier(relativePath: string): string {\n const withoutExt = relativePath.replace(/\\.ts$/, \"\");\n return withoutExt.startsWith(\".\") ? withoutExt : `./${withoutExt}`;\n}\n","import { defineCommand, runCommand } from \"politty\";\nimport { getCommand } from \"./get\";\nimport { listCommand } from \"./list\";\nimport { logsCommand } from \"./logs\";\nimport { runFunctionCommand } from \"./run\";\nimport { scriptCommand } from \"./script\";\n\nexport const functionCommand = defineCommand({\n name: \"function\",\n description: \"Manage functions\",\n subCommands: {\n get: getCommand,\n list: listCommand,\n logs: logsCommand,\n run: runFunctionCommand,\n script: scriptCommand,\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 { toError } from \"#/cli/shared/errors\";\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 // A fetch failure here rejects with TypeError, which the top-level handler\n // classifies as an SDK bug and crash-reports.\n const authorizeUri = await client.authorizationCode\n .getAuthorizeUri({ redirectUri, state, codeVerifier })\n .catch((error: unknown) => {\n throw new Error(`Failed to prepare the login authorization URL: ${toError(error).message}`, {\n cause: error,\n });\n });\n\n return new Promise<void>((resolve, reject) => {\n const handleCallback = async (\n req: http.IncomingMessage,\n res: http.ServerResponse,\n ): Promise<void> => {\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(toError(error));\n } finally {\n // Close the server after handling one request.\n server.close();\n }\n };\n const server = http.createServer((req, res) => void handleCallback(req, res));\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 const openBrowser = async (): Promise<void> => {\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 server.listen(redirectPort, () => void openBrowser());\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\";\nimport { parseBoolean } from \"#/cli/shared/parse-boolean\";\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 =\n parseBoolean(process.env.TAILOR_CONSOLE_NEXT) === true\n ? `/workspaces/${workspaceId}/services/applications/${encodeURIComponent(applicationName)}`\n : `/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 \"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 setup: \"@tailor-platform/sdk-plugin-setup\",\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 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 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { vaultArgs } from \"./args\";\nimport type { SecretManagerSecret } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\ninterface 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport type { SecretManagerVault } from \"@tailor-platform/tailor-proto/secret_manager_resource_pb\";\n\ninterface 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options?.profile,\n workspaceId: options?.workspaceId,\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 { 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 if (logger.jsonMode) {\n logger.out([]);\n }\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: args.profile,\n workspaceId: args[\"workspace-id\"],\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 } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { logger } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options?.profile,\n workspaceId: options?.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { formatNextAction } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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\ninterface 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 table 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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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\ninterface 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { getNamespacesWithMigrations } from \"./config\";\nimport { fetchRemoteMigrationState } from \"./remote-state\";\nimport {\n getMigrationFiles,\n loadDiff,\n loadSnapshot,\n formatMigrationNumber,\n UnsupportedMigrationFileVersionError,\n} from \"./snapshot\";\n\ninterface 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 { fetchAll, fetchAllTolerant, type OperatorClient } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\nimport { prompt } from \"#/cli/shared/prompt\";\nimport { subscribesToEvents } from \"#/cli/shared/publish-events\";\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\ninterface 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 table 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 table 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 tables load, and may trigger on the target's tables.\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 tables\n // their record triggers depend on.\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 executorUsedTables = new Set<string>();\n for (const executor of Object.values(executorService?.executors ?? {})) {\n if (!subscribesToEvents(executor)) continue;\n if (executor.trigger.kind === \"tailordb\") {\n executorUsedTables.add(executor.trigger.tableName);\n }\n }\n const manifestOptions: GenerateAllManifestsOptions = {\n executorUsedTables,\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 table definitions — fix the migration files.\",\n { mode: \"plain\" },\n );\n logger.info(\n \" - Table 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 * table 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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 tables: upsert the ones defined\n // in the snapshot, delete remote ones with no snapshot counterpart\n // (including those of deleted tables — an orphaned permission can block\n // the table 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(` Tables to create: ${styles.bold(String(creates.length))}`);\n logger.log(` Tables to update: ${styles.bold(String(updates.length))}`);\n logger.log(` Tables 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 tables; the label\n // may still be stale, so the sync proceeds to update it.\n logger.info(\"No tables to apply; only the migration label will be updated.\");\n } else {\n logger.warn(\n \"This operation will overwrite remote TailorDB tables to match the selected snapshot.\",\n );\n if (deletes.length > 0) {\n logger.warn(\"Existing data in deleted tables 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 = (tableName: string) => {\n const manifest = manifests.get(tableName);\n if (!manifest) {\n throw new Error(\n `Internal error: no manifest generated for table \"${tableName}\". No changes were applied.`,\n );\n }\n return manifest;\n };\n const createManifests = creates.map((tableName) => manifestFor(tableName));\n const updateManifests = updates.map((tableName) => manifestFor(tableName));\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((tableName) =>\n client.deleteTailorDBType({\n workspaceId,\n namespaceName: target.namespace,\n tailordbTypeName: tableName,\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 tables in a baseline snapshot.\n * @param dataDir - Directory containing `<Type>.jsonl` files\n * @param tableNames - Baseline table names to load\n * @param snapshot - Baseline schema used to remove fields introduced by pending migrations\n * @returns Seed rows keyed by table name\n */\nexport function loadSnapshotSeedData(\n dataDir: string,\n tableNames: string[],\n snapshot?: NormalizedSchemaSnapshot,\n): SeedData {\n const data: SeedData = {};\n for (const tableName of tableNames) {\n const snapshotType = snapshot?.tables[tableName];\n const jsonlPath = path.join(dataDir, `${tableName}.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[tableName] = [];\n continue;\n }\n throw error;\n }\n data[tableName] = 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 );\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 tables 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 tableNames = Object.keys(snapshot.tables);\n const available = new Set(tableNames);\n const dependencies = new Map<string, string[]>();\n const selfRefTypes: string[] = [];\n for (const [tableName, 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 === tableName) {\n selfRefTypes.push(tableName);\n } else if (available.has(target)) {\n referenced.add(target);\n }\n }\n dependencies.set(tableName, [...referenced]);\n }\n\n const visited = new Set<string>();\n const order: string[] = [];\n const visit = (tableName: string): void => {\n if (visited.has(tableName)) return;\n visited.add(tableName);\n for (const dependency of dependencies.get(tableName) ?? []) {\n visit(dependency);\n }\n order.push(tableName);\n };\n for (const tableName of tableNames) {\n visit(tableName);\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 tables 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((tableName) => (data[tableName]?.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 { defineAppCommand } from \"#/cli/shared/command\";\nimport { loadConfig } from \"#/cli/shared/config-loader\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { loadOperatorWorkspaceContext } from \"#/cli/shared/operator-context\";\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 logMissingCheckpointGuidance,\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 RebaselinePendingInfo,\n RemoteSchemaVerificationResult,\n RemoteSchemaVerificationSkipReason,\n SchemaDrift,\n} from \"./types\";\n\ninterface 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 tables 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 * Set alongside `checkpointMissingLocal` when the cause is an environment that fell behind\n * before `migration rebaseline` ran, rather than a generic history mismatch.\n */\n rebaselinePending?: RebaselinePendingInfo;\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 rebaselinePending?: 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.rebaselinePending ? { rebaselinePending: remote.rebaselinePending } : {}),\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 { client, workspaceId } = await loadOperatorWorkspaceContext({\n profile: options.profile,\n workspaceId: options.workspaceId,\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 if (remote.rebaselinePending) {\n logger.log(\n ` Fell behind before 'migration rebaseline' ran; must reach ${formatMigrationNumber(remote.rebaselinePending.replacedLatestMigration)} first.`,\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 hasMissingCheckpoint(\n report: NamespaceValidationReport,\n): report is NamespaceValidationReport & {\n remoteSchema: CompletedRemoteSchemaReport & { checkpointMissingLocal: true };\n} {\n return report.remoteSchema?.checkpointMissingLocal === true;\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 const missingCheckpointReports = reports.filter(hasMissingCheckpoint);\n if (missingCheckpointReports.length > 0) {\n logMissingCheckpointGuidance(\n missingCheckpointReports.map((r) => ({\n namespace: r.namespace,\n remoteMigrationNumber: r.remoteSchema.remoteMigrationNumber,\n ...(r.remoteSchema.rebaselinePending\n ? { rebaselinePending: r.remoteSchema.rebaselinePending }\n : {}),\n })),\n );\n }\n if (reports.some((r) => r.remoteSchema?.hasDrift)) {\n logRemoteDriftGuidance(\n reports.map((r) => ({\n hasDrift: r.remoteSchema?.hasDrift ?? false,\n drifts: r.remoteSchema?.drifts ?? [],\n })),\n );\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 tables 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 { workspaceArgs } from \"#/cli/shared/args\";\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({ profile: workspaceArgs.profile }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const profile = args.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 { workspaceArgs } from \"#/cli/shared/args\";\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, activeProfile?: string): string | null {\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) {\n throw new Error(`Profile \"${activeProfile}\" not found`);\n }\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({ profile: workspaceArgs.profile }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const jsonOutput = logger.jsonMode;\n const activeProfile = args.profile || process.env.TAILOR_PLATFORM_PROFILE;\n const currentUserKey = activeCurrentUserKey(config, activeProfile);\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 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 { formatTimestamp } from \"#/cli/shared/format\";\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 createdAt: Date | null;\n /** `null` until the token has been used to authenticate. */\n lastUsedAt: Date | null;\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 createdAt: formatTimestamp(pat.createdAt),\n lastUsedAt: formatTimestamp(pat.lastUsedAt),\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 { loadAccessToken } from \"#/cli/shared/context\";\n\nexport async function createPatOperatorClient(activeProfile?: string) {\n const accessToken = await loadAccessToken({ profile: activeProfile });\n return await initOperatorClient(accessToken);\n}\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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 { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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, workspaceArgs } from \"#/cli/shared/args\";\nimport { fetchPaged } from \"#/cli/shared/client\";\nimport { defineAppCommand } from \"#/cli/shared/command\";\nimport { humanizeRelativeTime } from \"#/cli/shared/format\";\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(), profile: workspaceArgs.profile }),\n run: async (args) => {\n const jsonOutput = logger.jsonMode;\n const client = await createPatOperatorClient(args.profile);\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 logger.out(patInfos, {\n display: {\n scopes: (value) => (value as string[]).join(\"/\"),\n lastUsedAt: (value) => (value === null ? \"never\" : humanizeRelativeTime(value as Date)),\n },\n });\n },\n});\n","import { arg } from \"politty\";\nimport { z } from \"zod\";\nimport { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n await assertWritable({ profile: args.profile });\n const client = await createPatOperatorClient(args.profile);\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 { workspaceArgs } from \"#/cli/shared/args\";\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 profile: workspaceArgs.profile,\n }),\n run: async (args) => {\n const config = await readPlatformConfig();\n const activeProfileName = args.profile || 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 { 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 } 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.\nThe \\`setup\\` commands are provided by the @tailor-platform/sdk-plugin-setup CLI plugin.`,\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 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\nvoid runMain(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: logger.verbose }));\n } else if (isCLIError(error)) {\n logger.log(error.format());\n if (logger.verbose && 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 (logger.verbose && 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":";i+GASA,MAAM,GAAmC,GAAgB,QAAQ,OAC9D,GAA4B,EAAE,aAAe,OAChD,EAEA,SAAgB,iBAA4B,CAC1C,OAAO,GAAc,IAAK,GAAM,EAAE,IAAI,CAAC,CAAC,SAAS,CACnD,CAUA,SAAgB,mBAA8B,CAC5C,OAAO,GAAc,QAAS,GAAM,CAAC,EAAE,KAAM,GAAG,GAAgB,SAAS,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,SAAS,CAClG,CAEA,SAAgB,oBAAoB,EAAiD,CACnF,OAAO,GAAc,KAAM,GAAM,EAAE,OAAS,CAAU,CACxD,CAEA,SAAgB,kBAAkB,EAA0B,CAE1D,OADK,EAAS,SAAS,GAAG,EACnB,EAAS,MAAM,GAAG,CAAC,CAAC,IAAI,GAAK,EADA,CAEtC,CAQA,SAAgB,cAAc,EAA2C,CAGvE,GAFI,EAAM,YAAc,WACpB,EAAM,YAAc,QAAU,EAAM,WAAa,WACjD,EAAM,YAAc,OAAS,EAAM,UAAY,UAAW,OAAO,EAAM,OAE7E,CAWA,SAAS,gBAAgB,EAA+B,CACtD,OAAO,EAAQ,SAAS,WAAW,kBAAkB,CACvD,CAOA,MAAM,GAAmC,IAAI,IAAI,CAC/C,yBACA,wBACA,4BACA,4BACA,sBACA,uBACF,CAAC,EAMD,SAAS,+BAA+B,EAA+B,CACrE,OAAO,GAAiC,IAAI,EAAQ,QAAQ,CAC9D,CAsBA,SAAgB,6BAA6B,EAAgD,CAC3F,IAAM,EAAS,oBAAoB,CAAU,EAC7C,GAAI,CAAC,EAAQ,MAAO,CAAC,EAErB,IAAM,EAAyC,CAAC,EAC1C,EAAU,IAAI,IAEpB,SAAS,KAAK,EAA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