@tailor-platform/sdk 2.0.0-next.3 → 2.0.0-next.5

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 (327) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/aigateway-DR4Kwuik.mjs +9 -0
  3. package/dist/{aigateway-B3oZZE6v.mjs.map → aigateway-DR4Kwuik.mjs.map} +1 -1
  4. package/dist/{application-eHp9jXld.mjs → application-Bf8wxOi6.mjs} +701 -597
  5. package/dist/application-Bf8wxOi6.mjs.map +1 -0
  6. package/dist/application-CUkjzfij.mjs +3 -0
  7. package/dist/authconnection-CZvi9ANm.mjs +9 -0
  8. package/dist/authconnection-CZvi9ANm.mjs.map +1 -0
  9. package/dist/brand-Eo4pLXPJ.mjs.map +1 -1
  10. package/dist/cli/cache/bundle-cache.d.mts +2 -1
  11. package/dist/cli/cache/store.d.mts +1 -1
  12. package/dist/cli/commands/api/index.d.mts +1 -0
  13. package/dist/cli/commands/deploy/aigateway.d.mts +5 -1
  14. package/dist/cli/commands/deploy/application.d.mts +7 -1
  15. package/dist/cli/commands/deploy/apply-phases.d.mts +14 -1
  16. package/dist/cli/commands/deploy/auth.d.mts +5 -1
  17. package/dist/cli/commands/deploy/deploy.d.mts +5 -0
  18. package/dist/cli/commands/deploy/executor.d.mts +7 -1
  19. package/dist/cli/commands/deploy/function-registry.d.mts +5 -0
  20. package/dist/cli/commands/deploy/idp.d.mts +5 -1
  21. package/dist/cli/commands/deploy/resolver.d.mts +5 -1
  22. package/dist/cli/commands/deploy/secret-manager.d.mts +5 -1
  23. package/dist/cli/commands/deploy/staticwebsite.d.mts +5 -1
  24. package/dist/cli/commands/deploy/tailordb/index.d.mts +8 -1
  25. package/dist/cli/commands/deploy/types.d.mts +3 -1
  26. package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +3 -0
  27. package/dist/cli/commands/deploy/workflow.d.mts +4 -1
  28. package/dist/cli/commands/executor/get.d.mts +0 -1
  29. package/dist/cli/commands/executor/jobs.d.mts +0 -1
  30. package/dist/cli/commands/executor/list.d.mts +0 -1
  31. package/dist/cli/commands/executor/transform.d.mts +1 -0
  32. package/dist/cli/commands/executor/trigger.d.mts +0 -1
  33. package/dist/cli/commands/executor/webhook.d.mts +0 -1
  34. package/dist/cli/commands/function/get.d.mts +0 -1
  35. package/dist/cli/commands/function/list.d.mts +0 -1
  36. package/dist/cli/commands/function/transform.d.mts +1 -0
  37. package/dist/cli/commands/generate/service.d.mts +5 -1
  38. package/dist/cli/commands/machineuser/list.d.mts +0 -1
  39. package/dist/cli/commands/machineuser/token.d.mts +0 -1
  40. package/dist/cli/commands/oauth2client/get.d.mts +0 -1
  41. package/dist/cli/commands/oauth2client/list.d.mts +0 -1
  42. package/dist/cli/commands/oauth2client/transform.d.mts +1 -0
  43. package/dist/cli/commands/organization/folder/create.d.mts +0 -1
  44. package/dist/cli/commands/organization/folder/delete.d.mts +0 -1
  45. package/dist/cli/commands/organization/folder/get.d.mts +0 -1
  46. package/dist/cli/commands/organization/folder/list.d.mts +0 -1
  47. package/dist/cli/commands/organization/folder/update.d.mts +0 -1
  48. package/dist/cli/commands/organization/get.d.mts +0 -1
  49. package/dist/cli/commands/organization/list.d.mts +0 -1
  50. package/dist/cli/commands/organization/transform.d.mts +2 -0
  51. package/dist/cli/commands/organization/tree.d.mts +0 -1
  52. package/dist/cli/commands/organization/update.d.mts +0 -1
  53. package/dist/cli/commands/remove.d.mts +0 -1
  54. package/dist/cli/commands/show.d.mts +9 -4
  55. package/dist/cli/commands/tailordb/migrate/config.d.mts +0 -1
  56. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +16 -3
  57. package/dist/cli/commands/tailordb/migrate/generate.d.mts +0 -1
  58. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +6 -0
  59. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -1
  60. package/dist/cli/commands/tailordb/truncate.d.mts +0 -1
  61. package/dist/cli/commands/workflow/executions.d.mts +0 -1
  62. package/dist/cli/commands/workflow/get.d.mts +2 -1
  63. package/dist/cli/commands/workflow/list.d.mts +0 -1
  64. package/dist/cli/commands/workflow/resume.d.mts +0 -1
  65. package/dist/cli/commands/workflow/start.d.mts +0 -1
  66. package/dist/cli/commands/workflow/status.d.mts +1 -0
  67. package/dist/cli/commands/workflow/transform.d.mts +1 -0
  68. package/dist/cli/commands/workflow/wait.d.mts +0 -1
  69. package/dist/cli/commands/workflow/waiter.d.mts +1 -1
  70. package/dist/cli/commands/workspace/app/health.d.mts +0 -1
  71. package/dist/cli/commands/workspace/app/list.d.mts +0 -1
  72. package/dist/cli/commands/workspace/app/transform.d.mts +2 -0
  73. package/dist/cli/commands/workspace/create.d.mts +0 -1
  74. package/dist/cli/commands/workspace/delete.d.mts +0 -1
  75. package/dist/cli/commands/workspace/get.d.mts +0 -1
  76. package/dist/cli/commands/workspace/list.d.mts +0 -1
  77. package/dist/cli/commands/workspace/restore.d.mts +0 -1
  78. package/dist/cli/commands/workspace/transform.d.mts +2 -0
  79. package/dist/cli/commands/workspace/user/invite.d.mts +0 -1
  80. package/dist/cli/commands/workspace/user/list.d.mts +0 -1
  81. package/dist/cli/commands/workspace/user/remove.d.mts +0 -1
  82. package/dist/cli/commands/workspace/user/transform.d.mts +1 -0
  83. package/dist/cli/commands/workspace/user/update.d.mts +0 -1
  84. package/dist/cli/index.d.mts +6 -3
  85. package/dist/cli/index.mjs +273 -104
  86. package/dist/cli/index.mjs.map +1 -1
  87. package/dist/cli/lib.d.mts +4 -2
  88. package/dist/cli/lib.mjs +4 -4
  89. package/dist/cli/lib.mjs.map +1 -1
  90. package/dist/cli/query/index.d.mts +4 -1
  91. package/dist/cli/services/application.d.mts +12 -1
  92. package/dist/cli/services/auth/service.d.mts +2 -0
  93. package/dist/cli/services/executor/service.d.mts +1 -1
  94. package/dist/cli/services/http-adapter/bundler.d.mts +3 -1
  95. package/dist/cli/services/http-adapter/service.d.mts +2 -1
  96. package/dist/cli/services/resolver/service.d.mts +1 -1
  97. package/dist/cli/services/tailordb/service.d.mts +3 -1
  98. package/dist/cli/services/workflow/bundler.d.mts +2 -1
  99. package/dist/cli/services/workflow/service.d.mts +1 -1
  100. package/dist/cli/shared/args.d.mts +1 -1
  101. package/dist/cli/shared/client.d.mts +1 -1
  102. package/dist/cli/shared/config-loader.d.mts +0 -1
  103. package/dist/cli/shared/context.d.mts +2 -1
  104. package/dist/cli/shared/script-executor.d.mts +0 -1
  105. package/dist/cli/shared/seed-chunker.d.mts +7 -3
  106. package/dist/cli/shared/type-generator.d.mts +0 -1
  107. package/dist/cli/ts-hook.mjs +43 -13
  108. package/dist/completion/zsh-worker.zsh +10 -10
  109. package/dist/configure/config/index.d.mts +0 -1
  110. package/dist/configure/config/types.d.mts +3 -1
  111. package/dist/configure/index.d.mts +17 -5
  112. package/dist/configure/index.mjs +309 -5
  113. package/dist/configure/index.mjs.map +1 -1
  114. package/dist/configure/services/aigateway/index.d.mts +0 -1
  115. package/dist/configure/services/aigateway/types.d.mts +0 -1
  116. package/dist/configure/services/auth/index.d.mts +0 -1
  117. package/dist/configure/services/auth/types.d.mts +15 -14
  118. package/dist/configure/services/executor/executor.d.mts +1 -1
  119. package/dist/configure/services/executor/index.d.mts +1 -0
  120. package/dist/configure/services/executor/operation.d.mts +2 -2
  121. package/dist/configure/services/executor/trigger/event.d.mts +0 -1
  122. package/dist/configure/services/executor/trigger/index.d.mts +0 -1
  123. package/dist/configure/services/executor/trigger/schedule.d.mts +0 -1
  124. package/dist/configure/services/executor/trigger/webhook.d.mts +0 -1
  125. package/dist/configure/services/http-adapter/http-adapter.d.mts +1 -2
  126. package/dist/configure/services/idp/index.d.mts +1 -5
  127. package/dist/configure/services/idp/permission.d.mts +4 -5
  128. package/dist/configure/services/idp/types.d.mts +0 -1
  129. package/dist/configure/services/index.d.mts +8 -1
  130. package/dist/configure/services/resolver/resolver.d.mts +1 -0
  131. package/dist/configure/services/resolver/types.d.mts +0 -1
  132. package/dist/configure/services/secrets/index.d.mts +0 -1
  133. package/dist/configure/services/secrets/types.d.mts +0 -1
  134. package/dist/configure/services/staticwebsite/index.d.mts +0 -1
  135. package/dist/configure/services/staticwebsite/types.d.mts +0 -1
  136. package/dist/configure/services/tailordb/permission.d.mts +4 -5
  137. package/dist/configure/services/tailordb/schema.d.mts +104 -68
  138. package/dist/configure/services/tailordb/types.d.mts +66 -17
  139. package/dist/configure/services/workflow/execution-policy.d.mts +70 -0
  140. package/dist/configure/services/workflow/execution-policy.types.d.mts +103 -0
  141. package/dist/configure/services/workflow/index.d.mts +4 -1
  142. package/dist/configure/services/workflow/job.d.mts +7 -3
  143. package/dist/configure/services/workflow/wait-point.d.mts +0 -1
  144. package/dist/configure/services/workflow/workflow.d.mts +1 -1
  145. package/dist/configure/types/field-runtime.d.mts +0 -1
  146. package/dist/configure/types/field.d.mts +1 -2
  147. package/dist/configure/types/field.types.d.mts +6 -45
  148. package/dist/configure/types/index.d.mts +1 -0
  149. package/dist/configure/types/type.d.mts +1 -2
  150. package/dist/{context-Bd266-ru.mjs → context-DYQVYWqZ.mjs} +4 -5
  151. package/dist/{context-Bd266-ru.mjs.map → context-DYQVYWqZ.mjs.map} +1 -1
  152. package/dist/{file-BbdFGdMV.mjs → file-BUcmVIH2.mjs} +12 -14
  153. package/dist/file-BUcmVIH2.mjs.map +1 -0
  154. package/dist/{file-utils-CYZnO1pX.mjs → file-utils-yEiIS4nJ.mjs} +2 -2
  155. package/dist/file-utils-yEiIS4nJ.mjs.map +1 -0
  156. package/dist/{globals-DhwZj0RB.mjs → globals-BjhJJ2dN.mjs} +2 -2
  157. package/dist/globals-BjhJJ2dN.mjs.map +1 -0
  158. package/dist/iconv-QWaZh0TT.mjs +38 -0
  159. package/dist/iconv-QWaZh0TT.mjs.map +1 -0
  160. package/dist/{idp-Bx25ZBdN.mjs → idp-RA_swu-h.mjs} +4 -5
  161. package/dist/idp-RA_swu-h.mjs.map +1 -0
  162. package/dist/kysely/index.d.mts +3 -4
  163. package/dist/{kysely-type-5eAChaHO.mjs → kysely-type-DqIRgDYR.mjs} +4 -5
  164. package/dist/kysely-type-DqIRgDYR.mjs.map +1 -0
  165. package/dist/parser/service/auth/index.d.mts +1 -1
  166. package/dist/parser/service/auth/schema.d.mts +2 -0
  167. package/dist/parser/service/http-adapter/index.d.mts +1 -1
  168. package/dist/parser/service/idp/types.d.mts +1 -0
  169. package/dist/parser/service/tailordb/types.d.mts +6 -1
  170. package/dist/plugin/builtin/enum-constants/index.d.mts +0 -1
  171. package/dist/plugin/builtin/file-utils/index.d.mts +0 -1
  172. package/dist/plugin/builtin/file-utils/index.mjs +1 -1
  173. package/dist/plugin/builtin/kysely-type/index.d.mts +0 -1
  174. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  175. package/dist/plugin/builtin/seed/index.d.mts +0 -1
  176. package/dist/plugin/get-generated-type.d.mts +0 -1
  177. package/dist/plugin/manager.d.mts +2 -1
  178. package/dist/plugin/types.d.mts +0 -1
  179. package/dist/plugin/with-context.d.mts +0 -1
  180. package/dist/{register-ts-hook-ZpBacA07.mjs → register-ts-hook-BhzVkej0.mjs} +799 -446
  181. package/dist/register-ts-hook-BhzVkej0.mjs.map +1 -0
  182. package/dist/{registry-DH4m7eYo.mjs → registry-BSbq6SPo.mjs} +4 -3
  183. package/dist/registry-BSbq6SPo.mjs.map +1 -0
  184. package/dist/resource_pb-BRv7AMXK.mjs +49 -0
  185. package/dist/resource_pb-BRv7AMXK.mjs.map +1 -0
  186. package/dist/runtime/aigateway.d.mts +5 -15
  187. package/dist/runtime/aigateway.mjs +2 -2
  188. package/dist/runtime/authconnection.d.mts +5 -15
  189. package/dist/runtime/authconnection.mjs +2 -2
  190. package/dist/runtime/context.d.mts +14 -6
  191. package/dist/runtime/context.mjs +2 -2
  192. package/dist/runtime/file.d.mts +14 -54
  193. package/dist/runtime/file.mjs +2 -2
  194. package/dist/runtime/globals.d.mts +1 -2
  195. package/dist/runtime/iconv.d.mts +5 -53
  196. package/dist/runtime/iconv.mjs +2 -2
  197. package/dist/runtime/idp.d.mts +13 -70
  198. package/dist/runtime/idp.mjs +2 -2
  199. package/dist/runtime/index.d.mts +11 -12
  200. package/dist/runtime/index.mjs +9 -9
  201. package/dist/runtime/secretmanager.d.mts +7 -20
  202. package/dist/runtime/secretmanager.mjs +2 -2
  203. package/dist/runtime/types.d.mts +9 -4
  204. package/dist/runtime/workflow.d.mts +42 -41
  205. package/dist/runtime/workflow.mjs +2 -2
  206. package/dist/{schema-89dYxNC2.mjs → schema-iCd1ugGp.mjs} +257 -54
  207. package/dist/schema-iCd1ugGp.mjs.map +1 -0
  208. package/dist/secretmanager-CYlpffsz.mjs +13 -0
  209. package/dist/secretmanager-CYlpffsz.mjs.map +1 -0
  210. package/dist/seed/index.d.mts +3 -2
  211. package/dist/service-BT0GPd01.mjs +3 -0
  212. package/dist/{service-ufH7sS8o.mjs → service-CzZEVrp9.mjs} +14 -9
  213. package/dist/service-CzZEVrp9.mjs.map +1 -0
  214. package/dist/{service_pb-CIrhGwHk.mjs → service_pb-Bk7dL-yT.mjs} +27 -50
  215. package/dist/service_pb-Bk7dL-yT.mjs.map +1 -0
  216. package/dist/{service_pb-DjwIn4jO.mjs → service_pb-DZkfjB_6.mjs} +1 -1
  217. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +0 -1
  218. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +0 -1
  219. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +0 -1
  220. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +0 -1
  221. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +0 -1
  222. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +0 -1
  223. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +0 -1
  224. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +0 -1
  225. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +0 -1
  226. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +0 -1
  227. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +0 -1
  228. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +0 -1
  229. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +0 -1
  230. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +0 -1
  231. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +0 -1
  232. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +0 -1
  233. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +0 -1
  234. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +0 -1
  235. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +0 -1
  236. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +0 -1
  237. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +0 -1
  238. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +0 -1
  239. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +0 -1
  240. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +0 -1
  241. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +1 -2
  242. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +0 -1
  243. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +0 -1
  244. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +0 -1
  245. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +0 -1
  246. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +0 -1
  247. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +0 -1
  248. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +0 -1
  249. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +0 -1
  250. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +29 -10
  251. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +35 -2
  252. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +0 -1
  253. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +0 -1
  254. package/dist/types/aigateway.generated.d.mts +5 -2
  255. package/dist/types/auth-connection.generated.d.mts +24 -11
  256. package/dist/types/auth.generated.d.mts +115 -84
  257. package/dist/types/executor.generated.d.mts +76 -84
  258. package/dist/types/helpers.d.mts +7 -6
  259. package/dist/types/http-adapter.generated.d.mts +11 -5
  260. package/dist/types/idp.generated.d.mts +536 -524
  261. package/dist/types/resolver.generated.d.mts +26 -11
  262. package/dist/types/staticwebsite.generated.d.mts +7 -3
  263. package/dist/types/tailordb.generated.d.mts +57 -29
  264. package/dist/types/workflow.generated.d.mts +9 -4
  265. package/dist/utils/test/index.d.mts +1 -2
  266. package/dist/utils/test/index.mjs +36 -10
  267. package/dist/utils/test/index.mjs.map +1 -1
  268. package/dist/utils/test/mock.d.mts +0 -1
  269. package/dist/vitest/environment.mjs +1 -1
  270. package/dist/vitest/index.d.mts +1 -1
  271. package/dist/vitest/index.mjs +11 -11
  272. package/dist/vitest/index.mjs.map +1 -1
  273. package/dist/vitest/mock-kysely.d.mts +0 -1
  274. package/dist/vitest/mocks/aigateway.d.mts +2 -2
  275. package/dist/vitest/mocks/authconnection.d.mts +2 -2
  276. package/dist/vitest/mocks/idp.d.mts +2 -2
  277. package/dist/vitest/mocks/secretmanager.d.mts +3 -1
  278. package/dist/vitest/mocks/tailordb.d.mts +6 -3
  279. package/dist/vitest/mocks/workflow.d.mts +15 -8
  280. package/dist/vitest/setup.mjs +1 -1
  281. package/dist/vitest/workflow-local.d.mts +1 -0
  282. package/dist/workflow-GNuSnsTx.mjs +22 -0
  283. package/dist/workflow-GNuSnsTx.mjs.map +1 -0
  284. package/docs/cli/auth.md +3 -3
  285. package/docs/cli/setup.md +9 -9
  286. package/docs/cli-reference.md +7 -6
  287. package/docs/configuration.md +24 -0
  288. package/docs/migration/v2.md +317 -0
  289. package/docs/plugin/custom.md +4 -4
  290. package/docs/plugin/index.md +2 -2
  291. package/docs/runtime.md +4 -2
  292. package/docs/services/aigateway.md +2 -0
  293. package/docs/services/auth.md +2 -2
  294. package/docs/services/resolver.md +1 -1
  295. package/docs/services/tailordb-migration.md +1 -1
  296. package/docs/services/tailordb.md +125 -93
  297. package/docs/services/workflow.md +78 -0
  298. package/package.json +22 -22
  299. package/dist/aigateway-B3oZZE6v.mjs +0 -15
  300. package/dist/application-D2hSK1ZL.mjs +0 -3
  301. package/dist/application-eHp9jXld.mjs.map +0 -1
  302. package/dist/authconnection-BGQM8FZI.mjs +0 -15
  303. package/dist/authconnection-BGQM8FZI.mjs.map +0 -1
  304. package/dist/cli/shared/trigger-context.d.mts +0 -1
  305. package/dist/field-runtime-CAnh_oow.mjs +0 -183
  306. package/dist/field-runtime-CAnh_oow.mjs.map +0 -1
  307. package/dist/file-BbdFGdMV.mjs.map +0 -1
  308. package/dist/file-utils-CYZnO1pX.mjs.map +0 -1
  309. package/dist/globals-DhwZj0RB.mjs.map +0 -1
  310. package/dist/iconv-D2vi8G36.mjs +0 -63
  311. package/dist/iconv-D2vi8G36.mjs.map +0 -1
  312. package/dist/idp-Bx25ZBdN.mjs.map +0 -1
  313. package/dist/kysely-type-5eAChaHO.mjs.map +0 -1
  314. package/dist/register-ts-hook-ZpBacA07.mjs.map +0 -1
  315. package/dist/registry-DH4m7eYo.mjs.map +0 -1
  316. package/dist/rolldown-runtime-DXywRVcq.mjs +0 -20
  317. package/dist/schema-89dYxNC2.mjs.map +0 -1
  318. package/dist/secretmanager-BVxw3ih_.mjs +0 -24
  319. package/dist/secretmanager-BVxw3ih_.mjs.map +0 -1
  320. package/dist/service-CkIwEctX.mjs +0 -3
  321. package/dist/service-ufH7sS8o.mjs.map +0 -1
  322. package/dist/service_pb-CIrhGwHk.mjs.map +0 -1
  323. package/dist/types-C-lQ4se3.mjs +0 -4
  324. package/dist/types-CXF2OYdR.mjs +0 -199
  325. package/dist/types-CXF2OYdR.mjs.map +0 -1
  326. package/dist/workflow-Bo59B75H.mjs +0 -50
  327. package/dist/workflow-Bo59B75H.mjs.map +0 -1
@@ -1,7 +1,8 @@
1
1
  import { n as isSdkBranded } from "./brand-Eo4pLXPJ.mjs";
2
+ import { i as PageDirection } from "./resource_pb-BRv7AMXK.mjs";
2
3
  import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
3
4
  import { a as parseBoolean, n as logger, r as styles } from "./logger-BEiZZ3qT.mjs";
4
- import { a as AuthConfigSchema, c as stripTailorDBTypeBuilderHelpers, d as applyRelationMetadataToFieldConfig, f as buildRelationInfo, g as functionSchema, h as loadFilesWithIgnores, l as TailorDBServiceConfigSchema, m as validateRelationConfig, n as loadExecutor, o as AuthInvokerSchema, p as processRelationMetadata, s as TailorFieldSchema, t as createExecutorService, u as TailorDBTypeSchema } from "./service-ufH7sS8o.mjs";
5
+ import { a as AuthConfigSchema, c as stripTailorDBTypeBuilderHelpers, d as applyRelationMetadataToFieldConfig, f as buildRelationInfo, g as functionSchema, h as loadFilesWithIgnores, l as TailorDBServiceConfigSchema, m as validateRelationConfig, n as loadExecutor, o as AuthInvokerSchema, p as processRelationMetadata, s as TailorFieldSchema, t as createExecutorService, u as TailorDBTypeSchema } from "./service-CzZEVrp9.mjs";
5
6
  import { t as multiline } from "./multiline-sfHpTZZK.mjs";
6
7
  import { t as readPackageJson } from "./package-json-8b0O9TlX.mjs";
7
8
  import { i as userAgent, n as tightenSecretFilePermissions, r as writeSecretFile } from "./secret-file-aoNXJmKa.mjs";
@@ -11,10 +12,12 @@ import { builtinModules, createRequire } from "node:module";
11
12
  import * as path from "pathe";
12
13
  import { join, resolve } from "pathe";
13
14
  import { resolveTSConfig } from "pkg-types";
15
+ import { arg } from "politty";
14
16
  import { z } from "zod";
15
17
  import { create } from "@bufbuild/protobuf";
16
18
  import * as fs$1 from "node:fs";
17
19
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
20
+ import { parseEnv } from "node:util";
18
21
  import { MethodOptions_IdempotencyLevel } from "@bufbuild/protobuf/wkt";
19
22
  import { pathToFileURL } from "node:url";
20
23
  import { parseYAML, stringifyYAML } from "confbox";
@@ -33,6 +36,256 @@ import * as inflection from "inflection";
33
36
  import * as globals from "globals";
34
37
  import * as os from "node:os";
35
38
 
39
+ //#region src/cli/shared/args.ts
40
+ const unitToMs = {
41
+ ms: 1,
42
+ s: 1e3,
43
+ m: 60 * 1e3
44
+ };
45
+ const durationPattern = /^(\d+)(ms|s|m)$/;
46
+ /**
47
+ * Schema for duration string validation (e.g., "3s", "500ms", "1m")
48
+ * Only validates format; use parseDuration() to convert to milliseconds
49
+ */
50
+ const durationArg = z.string().refine((val) => durationPattern.test(val), { message: "Invalid duration format. Expected format: '3s', '500ms', '1m'" }).refine((val) => {
51
+ const match = val.match(durationPattern);
52
+ if (!match) return false;
53
+ const digits = match[1];
54
+ return digits !== void 0 && parseInt(digits, 10) > 0;
55
+ }, { message: "Duration must be greater than 0" });
56
+ /**
57
+ * Parse a validated duration string into milliseconds
58
+ * @param duration - Duration string (e.g., "3s", "500ms", "1m")
59
+ * @returns Duration in milliseconds
60
+ */
61
+ function parseDuration(duration) {
62
+ const match = assertDefined(duration.match(durationPattern), `invalid duration format: ${duration}`);
63
+ const value = parseInt(assertDefined(match[1], "duration digits group missing"), 10);
64
+ const unit = assertDefined(match[2], "duration unit group missing");
65
+ return value * unitToMs[unit];
66
+ }
67
+ /**
68
+ * Schema for positive integer validation (from string input)
69
+ * Transforms the string to a number
70
+ */
71
+ const positiveIntArg = z.coerce.number().int().positive();
72
+ /**
73
+ * Schema for non-negative integer validation (from string input).
74
+ * Accepts 0 (used for `--limit 0` to disable the limit).
75
+ */
76
+ const nonNegativeIntArg = z.coerce.number().int().nonnegative();
77
+ /**
78
+ * Schema for sort order (`asc` or `desc`).
79
+ */
80
+ const orderArg = z.enum(["asc", "desc"]);
81
+ /**
82
+ * Translate a CLI `--order` value into the proto `PageDirection` enum.
83
+ * Returns `undefined` when the user did not specify an order so that
84
+ * callers can omit the field and fall back to the server default.
85
+ * @param order - Order string from CLI args (`"asc"` | `"desc"` | undefined)
86
+ * @returns PageDirection, or undefined when `order` is undefined
87
+ */
88
+ function toPageDirection(order) {
89
+ if (order === void 0) return void 0;
90
+ return order === "asc" ? PageDirection.ASC : PageDirection.DESC;
91
+ }
92
+ function hasMachineUserFlag(argv) {
93
+ return argv.slice(0, argv.indexOf("--") === -1 ? argv.length : argv.indexOf("--")).some((token) => token === "-m" || token.startsWith("-m=") || token === "--machine-user" || token.startsWith("--machine-user=") || token === "--machineUser" || token.startsWith("--machineUser=") || token === "--machineuser" || token.startsWith("--machineuser="));
94
+ }
95
+ /**
96
+ * Resolve whether a parsed machine user value came from an explicit CLI option or env fallback.
97
+ * @param machineUser - Parsed machine user value
98
+ * @param argv - Raw CLI argv, excluding the executable and script path
99
+ * @param options - Source resolution options
100
+ * @returns Machine user input source, or undefined when no value was parsed
101
+ */
102
+ function resolveMachineUserInputSource(machineUser, argv = process.argv.slice(2), options = {}) {
103
+ if (machineUser === void 0) return void 0;
104
+ if (options.valueIsExplicit) return "option";
105
+ if (hasMachineUserFlag(argv)) return "option";
106
+ return process.env.TAILOR_PLATFORM_MACHINE_USER_NAME === machineUser ? "env" : "option";
107
+ }
108
+ /**
109
+ * Load env files from parsed arguments.
110
+ * Processes --env-file first, then --env-file-if-exists.
111
+ *
112
+ * Follows Node.js --env-file behavior:
113
+ * - Variables already set in the environment are NOT overwritten
114
+ * - Variables from later files override those from earlier files
115
+ * @param envFiles - Required env file path(s) that must exist
116
+ * @param envFilesIfExists - Optional env file path(s) that are loaded if they exist
117
+ */
118
+ function loadEnvFiles(envFiles, envFilesIfExists) {
119
+ const originalEnvKeys = new Set(Object.keys(process.env));
120
+ const load = (files, required) => {
121
+ for (const file of [files ?? []].flat()) {
122
+ const envPath = path.resolve(process.cwd(), file);
123
+ if (!fs$1.existsSync(envPath)) {
124
+ if (required) throw new Error(`Environment file not found: ${envPath}`);
125
+ continue;
126
+ }
127
+ const parsed = parseEnv(fs$1.readFileSync(envPath, "utf-8"));
128
+ for (const [key, value] of Object.entries(parsed)) {
129
+ if (originalEnvKeys.has(key)) continue;
130
+ process.env[key] = value;
131
+ }
132
+ }
133
+ };
134
+ load(envFiles, true);
135
+ load(envFilesIfExists, false);
136
+ }
137
+ /**
138
+ * Common arguments for all CLI commands
139
+ *
140
+ * NOTE: --env-file and --env-file-if-exists collide with Node.js flags due to a bug
141
+ * (https://github.com/nodejs/node/issues/54232). Node.js parses these even after the
142
+ * script path, causing warnings (twice due to tsx loader).
143
+ */
144
+ const commonArgs = {
145
+ "env-file": arg(z.string().optional(), {
146
+ alias: "e",
147
+ description: "Path to the environment file (error if not found)",
148
+ completion: {
149
+ type: "file",
150
+ matcher: [".env.*", ".env"]
151
+ }
152
+ }),
153
+ "env-file-if-exists": arg(z.string().optional(), {
154
+ description: "Path to the environment file (ignored if not found)",
155
+ completion: {
156
+ type: "file",
157
+ matcher: [".env.*", ".env"]
158
+ },
159
+ effect: (_value, { args }) => {
160
+ loadEnvFiles(args["env-file"], args["env-file-if-exists"]);
161
+ }
162
+ }),
163
+ verbose: arg(z.boolean().default(false), {
164
+ description: "Enable verbose logging",
165
+ effect: (value) => {
166
+ verboseMode = value;
167
+ }
168
+ }),
169
+ json: arg(z.boolean().default(false), {
170
+ alias: "j",
171
+ description: "Output as JSON",
172
+ effect: (value) => {
173
+ logger.jsonMode = value;
174
+ }
175
+ })
176
+ };
177
+ /**
178
+ * Arguments for commands that require workspace context
179
+ */
180
+ const workspaceArgs = {
181
+ "workspace-id": arg(z.string().optional(), {
182
+ alias: "w",
183
+ description: "Workspace ID",
184
+ env: "TAILOR_PLATFORM_WORKSPACE_ID",
185
+ completion: { type: "none" }
186
+ }),
187
+ profile: arg(z.string().optional(), {
188
+ alias: "p",
189
+ description: "Workspace profile",
190
+ env: "TAILOR_PLATFORM_PROFILE",
191
+ completion: { type: "none" }
192
+ })
193
+ };
194
+ /**
195
+ * Shared config arg for commands that accept a config file path
196
+ */
197
+ const configArg = { config: arg(z.string().default("tailor.config.ts"), {
198
+ alias: "c",
199
+ description: "Path to Tailor config file",
200
+ env: "TAILOR_CONFIG_PATH",
201
+ completion: {
202
+ type: "file",
203
+ extensions: ["ts"]
204
+ }
205
+ }) };
206
+ /**
207
+ * Shared config arg for commands that accept one or more comma-separated config file paths
208
+ */
209
+ const multiConfigArg = { config: arg(z.string().default("tailor.config.ts"), {
210
+ alias: "c",
211
+ description: "Path to SDK config file. Use comma-separated paths to deploy multiple apps together.",
212
+ env: "TAILOR_PLATFORM_SDK_CONFIG_PATH",
213
+ completion: {
214
+ type: "file",
215
+ extensions: ["ts"]
216
+ }
217
+ }) };
218
+ /**
219
+ * Arguments for commands that interact with deployed resources (includes config)
220
+ */
221
+ const deploymentArgs = {
222
+ ...workspaceArgs,
223
+ ...configArg
224
+ };
225
+ /**
226
+ * Arguments for commands that require confirmation
227
+ */
228
+ const confirmationArgs = { yes: arg(z.boolean().default(false), {
229
+ alias: "y",
230
+ description: "Skip confirmation prompts"
231
+ }) };
232
+ /**
233
+ * Arguments for commands that require organization context
234
+ */
235
+ const organizationArgs = { "organization-id": arg(z.string(), {
236
+ alias: "o",
237
+ description: "Organization ID",
238
+ env: "TAILOR_PLATFORM_ORGANIZATION_ID",
239
+ completion: { type: "none" }
240
+ }) };
241
+ /**
242
+ * Arguments for list commands that accept `--order` / `--limit`. Sort
243
+ * order defaults to `desc` (newest first) because most callers want the
244
+ * latest items; pass `--order asc` to opt in to ascending order. The
245
+ * limit is unbounded by default so existing invocations keep returning
246
+ * every item; pass `--limit N` to cap the result size.
247
+ * @param defaultOrder - Default value for `--order` (defaults to `"desc"`)
248
+ * @returns Argument shape suitable for spreading into a command schema
249
+ */
250
+ const paginationArgs = (defaultOrder = "desc") => ({
251
+ order: arg(orderArg.default(defaultOrder), { description: "Sort order (asc or desc)" }),
252
+ limit: arg(nonNegativeIntArg.optional(), {
253
+ alias: "l",
254
+ description: "Maximum number of items to return (0 or omit: unlimited)"
255
+ })
256
+ });
257
+ /**
258
+ * Arguments for time-series log list commands. Defaults to newest-first
259
+ * (`desc`) and a 50-item cap so that listing stays responsive on busy
260
+ * workspaces. Pass `--limit 0` to disable the cap and fetch all entries.
261
+ */
262
+ const pagedLogArgs = {
263
+ order: arg(orderArg.default("desc"), { description: "Sort order (asc or desc)" }),
264
+ limit: arg(nonNegativeIntArg.default(50), {
265
+ alias: "l",
266
+ description: "Maximum number of items to return (0: unlimited)"
267
+ })
268
+ };
269
+ /**
270
+ * Arguments for commands that require folder context
271
+ */
272
+ const folderArgs = { "folder-id": arg(z.string(), {
273
+ alias: "f",
274
+ description: "Folder ID",
275
+ env: "TAILOR_PLATFORM_FOLDER_ID",
276
+ completion: { type: "none" }
277
+ }) };
278
+ let verboseMode = false;
279
+ /**
280
+ * Returns whether verbose mode is enabled.
281
+ * Used by the global cleanup handler which doesn't have access to parsed args.
282
+ * @returns Whether verbose mode is enabled
283
+ */
284
+ function isVerbose() {
285
+ return verboseMode;
286
+ }
287
+
288
+ //#endregion
36
289
  //#region src/parser/app-config/log-level.ts
37
290
  const LOG_LEVELS = [
38
291
  "DEBUG",
@@ -245,7 +498,7 @@ function initOAuth2Client(config) {
245
498
  */
246
499
  async function initOperatorClient(accessToken, config) {
247
500
  const platformConfig = config ?? getPlatformConfigForToken(accessToken);
248
- const [{ createTracingInterceptor }, { OperatorService }] = await Promise.all([import("./interceptor-e33JtsC-.mjs"), import("./service_pb-DjwIn4jO.mjs")]);
501
+ const [{ createTracingInterceptor }, { OperatorService }] = await Promise.all([import("./interceptor-e33JtsC-.mjs"), import("./service_pb-DZkfjB_6.mjs")]);
249
502
  const interceptors = [
250
503
  await userAgentInterceptor(),
251
504
  await bearerTokenInterceptor(accessToken),
@@ -415,7 +668,8 @@ const RETRY_SAFE_CREATE_METHODS = /* @__PURE__ */ new Set([
415
668
  "CreateTailorDBType",
416
669
  "CreateTenantConfig",
417
670
  "CreateUserProfileConfig",
418
- "CreateWorkflow"
671
+ "CreateWorkflow",
672
+ "CreateWorkflowJobFunctionExecutionPolicy"
419
673
  ]);
420
674
  /**
421
675
  * Whether an error is an `AlreadyExists` from a retry-safe Create RPC.
@@ -1183,7 +1437,15 @@ async function loadMachineUserName(opts) {
1183
1437
  message: "Machine user name cannot be empty.",
1184
1438
  suggestion: "Pass a non-empty machine user name, or omit the option to use the environment variable or profile default."
1185
1439
  });
1186
- const explicit = opts?.machineUser || process.env.TAILOR_PLATFORM_MACHINE_USER_NAME || void 0;
1440
+ const envMachineUser = process.env.TAILOR_PLATFORM_MACHINE_USER_NAME || void 0;
1441
+ const explicitMachineUser = opts?.machineUser ? {
1442
+ source: opts.machineUserSource ?? "option",
1443
+ value: opts.machineUser
1444
+ } : envMachineUser ? {
1445
+ source: "env",
1446
+ value: envMachineUser
1447
+ } : void 0;
1448
+ const explicit = explicitMachineUser?.value;
1187
1449
  const profile = opts?.profile || process.env.TAILOR_PLATFORM_PROFILE;
1188
1450
  if (!profile) return explicit;
1189
1451
  const entry = (await readPlatformConfig()).profiles[profile];
@@ -1192,12 +1454,15 @@ async function loadMachineUserName(opts) {
1192
1454
  throw new Error(`Profile "${profile}" not found`);
1193
1455
  }
1194
1456
  if (entry.machine_user && entry.machine_user_override === "deny") {
1195
- if (explicit && explicit !== entry.machine_user) throw createCLIError({
1196
- code: "PROFILE_MACHINE_USER_OVERRIDE_DENIED",
1197
- message: `Profile "${profile}" denies overriding the machine user.`,
1198
- details: `This profile fixes the machine user to "${entry.machine_user}" for application-data commands.`,
1199
- suggestion: `Omit the machine user option, unset TAILOR_PLATFORM_MACHINE_USER_NAME, or run 'tailor profile update ${profile} --machine-user-override allow'.`
1200
- });
1457
+ if (explicit && explicit !== entry.machine_user) {
1458
+ const details = explicitMachineUser.source === "env" ? `The machine user is being set to "${explicit}" via the TAILOR_PLATFORM_MACHINE_USER_NAME environment variable, which conflicts with this profile's pinned machine user "${entry.machine_user}".` : `This profile fixes the machine user to "${entry.machine_user}" for application-data commands.`;
1459
+ throw createCLIError({
1460
+ code: "PROFILE_MACHINE_USER_OVERRIDE_DENIED",
1461
+ message: `Profile "${profile}" denies overriding the machine user.`,
1462
+ details,
1463
+ suggestion: `Omit the machine user option, unset TAILOR_PLATFORM_MACHINE_USER_NAME, or run 'tailor profile update ${profile} --machine-user-override allow'.`
1464
+ });
1465
+ }
1201
1466
  return entry.machine_user;
1202
1467
  }
1203
1468
  return explicit || entry.machine_user;
@@ -2157,7 +2422,7 @@ function generateTypeFileContent(info) {
2157
2422
  */
2158
2423
  import { db } from "@tailor-platform/sdk";
2159
2424
 
2160
- export const ${variableName} = db.type(${JSON.stringify(type.name)}, ${fieldsCode});
2425
+ export const ${variableName} = db.table(${JSON.stringify(type.name)}, ${fieldsCode});
2161
2426
 
2162
2427
  export type ${type.name} = typeof ${variableName};
2163
2428
  `;
@@ -2261,100 +2526,20 @@ async function removeStaleEntryFiles(outputDir) {
2261
2526
  await Promise.all(files.filter((file) => file.endsWith(".entry.js")).map((file) => fs.rm(path.join(outputDir, file), { force: true })));
2262
2527
  }
2263
2528
 
2264
- //#endregion
2265
- //#region src/cli/shared/bundle-log-level.ts
2266
- const INFO_LEVEL_CONSOLE_METHODS = [
2267
- "console.info",
2268
- "console.table",
2269
- "console.dir",
2270
- "console.dirxml",
2271
- "console.count",
2272
- "console.countReset",
2273
- "console.time",
2274
- "console.timeLog",
2275
- "console.timeEnd",
2276
- "console.group",
2277
- "console.groupCollapsed",
2278
- "console.groupEnd",
2279
- "console.clear"
2280
- ];
2281
- const DEBUG_LEVEL_CONSOLE_METHODS = [
2282
- "console.debug",
2283
- "console.log",
2284
- "console.trace"
2285
- ];
2286
- const WARN_LEVEL_CONSOLE_METHODS = ["console.warn"];
2287
- const ERROR_LEVEL_CONSOLE_METHODS = ["console.error"];
2288
- const MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL = {
2289
- DEBUG: [],
2290
- INFO: DEBUG_LEVEL_CONSOLE_METHODS,
2291
- WARN: [...DEBUG_LEVEL_CONSOLE_METHODS, ...INFO_LEVEL_CONSOLE_METHODS],
2292
- ERROR: [
2293
- ...DEBUG_LEVEL_CONSOLE_METHODS,
2294
- ...INFO_LEVEL_CONSOLE_METHODS,
2295
- ...WARN_LEVEL_CONSOLE_METHODS
2296
- ],
2297
- SILENT: [
2298
- ...DEBUG_LEVEL_CONSOLE_METHODS,
2299
- ...INFO_LEVEL_CONSOLE_METHODS,
2300
- ...WARN_LEVEL_CONSOLE_METHODS,
2301
- ...ERROR_LEVEL_CONSOLE_METHODS
2302
- ]
2303
- };
2304
- function normalizeBundleLogLevel(value) {
2305
- const normalized = value.trim().toUpperCase();
2306
- return isLogLevel(normalized) ? normalized : void 0;
2307
- }
2308
- function resolveBundleLogLevel(configValue) {
2309
- if (configValue === void 0) return "DEBUG";
2310
- const resolved = normalizeBundleLogLevel(configValue);
2311
- if (resolved) return resolved;
2312
- throw new Error(`Invalid logLevel "${configValue}". Expected one of: ${LOG_LEVELS.join(", ")}`);
2313
- }
2314
- function manualPureFunctionsForLogLevel(logLevel) {
2315
- return MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL[logLevel];
2316
- }
2317
- function createLogLevelTreeshakeOptions(logLevel) {
2318
- const manualPureFunctions = manualPureFunctionsForLogLevel(logLevel);
2319
- return manualPureFunctions.length > 0 ? { manualPureFunctions } : {};
2320
- }
2321
-
2322
- //#endregion
2323
- //#region src/cli/shared/function-treeshake.ts
2324
- const BASE_FUNCTION_TREESHAKE_OPTIONS = {
2325
- moduleSideEffects: false,
2326
- annotations: true,
2327
- unknownGlobalSideEffects: false
2328
- };
2329
- function mergeFunctionTreeshakeOptions(fragments) {
2330
- const merged = {};
2331
- const manualPureFunctions = /* @__PURE__ */ new Set();
2332
- for (const fragment of fragments) {
2333
- Object.assign(merged, fragment);
2334
- for (const name of fragment.manualPureFunctions ?? []) manualPureFunctions.add(name);
2335
- }
2336
- if (manualPureFunctions.size > 0) merged.manualPureFunctions = [...manualPureFunctions];
2337
- else delete merged.manualPureFunctions;
2338
- return merged;
2339
- }
2340
- function composeFunctionTreeshakeOptions(fragments = []) {
2341
- return mergeFunctionTreeshakeOptions([BASE_FUNCTION_TREESHAKE_OPTIONS, ...fragments]);
2342
- }
2343
-
2344
- //#endregion
2345
- //#region src/cli/shared/platform-bundle-plugin.ts
2346
- const GATE = /(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g;
2347
- const platformBundleDefinePlugin = {
2348
- name: "tailor-platform-bundle-define",
2349
- transform(code) {
2350
- if (!code.includes("process.env.__TAILOR_PLATFORM_BUNDLE")) return null;
2351
- return { code: code.replace(GATE, "true") };
2352
- }
2353
- };
2354
-
2355
2529
  //#endregion
2356
2530
  //#region src/cli/services/workflow/ast-utils.ts
2357
2531
  /**
2532
+ * Read an import or export name from an OXC identifier or string-literal node.
2533
+ * @param node - Import/export name node
2534
+ * @returns Module binding name, or undefined for an unsupported node
2535
+ */
2536
+ function getModuleExportName(node) {
2537
+ if (!node || typeof node !== "object") return void 0;
2538
+ const exportName = node;
2539
+ if (exportName.name) return exportName.name;
2540
+ return typeof exportName.value === "string" ? exportName.value : void 0;
2541
+ }
2542
+ /**
2358
2543
  * Check if a module source is from the Tailor SDK package (including subpaths)
2359
2544
  * @param source - Module source string
2360
2545
  * @returns True if the source is from the Tailor SDK package
@@ -2397,7 +2582,7 @@ function getTriggerCallInfo(node, sourceText) {
2397
2582
  const callee = callExpr.callee;
2398
2583
  if (callee.type !== "MemberExpression") return null;
2399
2584
  const memberExpr = callee;
2400
- if (memberExpr.computed || memberExpr.object.type !== "Identifier" || memberExpr.property.name !== "trigger") return null;
2585
+ if (memberExpr.computed || memberExpr.property.name !== "trigger" || memberExpr.object.type !== "Identifier") return null;
2401
2586
  return {
2402
2587
  identifierName: memberExpr.object.name,
2403
2588
  callRange: {
@@ -2484,20 +2669,6 @@ function findStatementEnd(source, position) {
2484
2669
  if (i < source.length && source[i] === "\n") i++;
2485
2670
  return i;
2486
2671
  }
2487
- /**
2488
- * Resolve a relative path from a base directory
2489
- * Simple implementation that handles ./ and ../ prefixes
2490
- * @param baseDir - Base directory
2491
- * @param relativePath - Relative path to resolve
2492
- * @returns Resolved absolute path
2493
- */
2494
- function resolvePath(baseDir, relativePath) {
2495
- const parts = relativePath.replace(/\\/g, "/").split("/");
2496
- const baseParts = baseDir.replace(/\\/g, "/").split("/");
2497
- for (const part of parts) if (part === ".") {} else if (part === "..") baseParts.pop();
2498
- else baseParts.push(part);
2499
- return baseParts.join("/");
2500
- }
2501
2672
 
2502
2673
  //#endregion
2503
2674
  //#region src/cli/services/workflow/sdk-binding-collector.ts
@@ -2641,42 +2812,6 @@ function findAllJobs(program, _sourceText) {
2641
2812
  walk(program);
2642
2813
  return jobs;
2643
2814
  }
2644
- /**
2645
- * Build a map from export name to job name from detected jobs
2646
- * @param jobs - Detected job locations
2647
- * @returns Map from export name to job name
2648
- */
2649
- function buildJobNameMap(jobs) {
2650
- const map = /* @__PURE__ */ new Map();
2651
- for (const job of jobs) if (job.exportName) map.set(job.exportName, job.name);
2652
- return map;
2653
- }
2654
- /**
2655
- * Detect all .trigger() calls in the source code
2656
- * Returns information about each trigger call for transformation
2657
- * @param program - Parsed TypeScript program
2658
- * @param sourceText - Source code text
2659
- * @returns Detected trigger calls
2660
- */
2661
- function detectTriggerCalls(program, sourceText) {
2662
- const calls = [];
2663
- function walk(node) {
2664
- if (!node || typeof node !== "object") return;
2665
- const triggerCall = getTriggerCallInfo(node, sourceText);
2666
- if (triggerCall) calls.push({
2667
- identifierName: triggerCall.identifierName,
2668
- callRange: triggerCall.callRange,
2669
- argsText: triggerCall.argsText
2670
- });
2671
- for (const key of Object.keys(node)) {
2672
- const child = node[key];
2673
- if (Array.isArray(child)) child.forEach((c) => walk(c));
2674
- else if (child && typeof child === "object") walk(child);
2675
- }
2676
- }
2677
- walk(program);
2678
- return calls;
2679
- }
2680
2815
 
2681
2816
  //#endregion
2682
2817
  //#region src/cli/services/workflow/workflow-detector.ts
@@ -2728,51 +2863,113 @@ function findAllWorkflows(program, _sourceText) {
2728
2863
  walk(program);
2729
2864
  return workflows;
2730
2865
  }
2866
+
2867
+ //#endregion
2868
+ //#region src/cli/shared/trigger-context.ts
2731
2869
  /**
2732
- * Build a map from export name to workflow name from detected workflows
2733
- * @param workflows - Detected workflows
2734
- * @returns Map from export name to workflow name
2735
- */
2736
- function buildWorkflowNameMap(workflows) {
2737
- const map = /* @__PURE__ */ new Map();
2738
- for (const workflow of workflows) if (workflow.exportName) map.set(workflow.exportName, workflow.name);
2739
- return map;
2740
- }
2741
- /**
2742
- * Detect default imports in a source file and return a map from local name to import source
2743
- * @param program - Parsed TypeScript program
2744
- * @returns Map from local name to import source
2870
+ * Normalize a source module path for trigger binding lookup.
2871
+ * @param filePath - Source file path or extensionless relative import path
2872
+ * @returns Absolute path without a JavaScript or TypeScript extension
2745
2873
  */
2746
- function detectDefaultImports(program) {
2747
- const imports = /* @__PURE__ */ new Map();
2748
- function walk(node) {
2749
- if (!node || typeof node !== "object") return;
2750
- if (node.type === "ImportDeclaration") {
2751
- const importDecl = node;
2752
- const source = importDecl.source.value;
2753
- if (typeof source === "string") {
2754
- for (const specifier of importDecl.specifiers) if (specifier.type === "ImportDefaultSpecifier") {
2755
- const spec = specifier;
2756
- if (spec.local.name) imports.set(spec.local.name, source);
2757
- }
2874
+ function normalizeFilePath(filePath) {
2875
+ return path.resolve(filePath.replace(/[?#].*$/, "")).replace(/\.(ts|mts|cts|js|mjs|cjs)$/, "");
2876
+ }
2877
+ function createModuleBindings(program, source) {
2878
+ const localBindings = /* @__PURE__ */ new Map();
2879
+ const exports = /* @__PURE__ */ new Map();
2880
+ for (const workflow of findAllWorkflows(program, source)) {
2881
+ const target = {
2882
+ kind: "workflow",
2883
+ name: workflow.name
2884
+ };
2885
+ if (workflow.exportName) localBindings.set(workflow.exportName, target);
2886
+ if (workflow.isDefaultExport) exports.set("default", target);
2887
+ }
2888
+ for (const job of findAllJobs(program, source)) if (job.exportName) localBindings.set(job.exportName, {
2889
+ kind: "job",
2890
+ name: job.name
2891
+ });
2892
+ for (const statement of program.body) {
2893
+ if (statement.type === "ExportDefaultDeclaration") {
2894
+ const declaration = statement.declaration;
2895
+ if (declaration?.type === "Identifier") {
2896
+ const target = localBindings.get(declaration.name);
2897
+ if (target) exports.set("default", target);
2758
2898
  }
2899
+ continue;
2759
2900
  }
2760
- for (const key of Object.keys(node)) {
2761
- const child = node[key];
2762
- if (Array.isArray(child)) child.forEach((c) => walk(c));
2763
- else if (child && typeof child === "object") walk(child);
2901
+ if (statement.type !== "ExportNamedDeclaration") continue;
2902
+ const declaration = statement.declaration;
2903
+ if (declaration?.type === "VariableDeclaration") for (const declarator of declaration.declarations) {
2904
+ const id = declarator.id;
2905
+ if (id?.type !== "Identifier") continue;
2906
+ const localName = id.name;
2907
+ const target = localBindings.get(localName);
2908
+ if (target) exports.set(localName, target);
2909
+ }
2910
+ if (statement.source) continue;
2911
+ for (const specifier of statement.specifiers ?? []) {
2912
+ const localName = getModuleExportName(specifier.local);
2913
+ const exportedName = getModuleExportName(specifier.exported);
2914
+ if (!localName || !exportedName) continue;
2915
+ const target = localBindings.get(localName);
2916
+ if (target) exports.set(exportedName, target);
2764
2917
  }
2765
2918
  }
2766
- walk(program);
2767
- return imports;
2919
+ return {
2920
+ localBindings,
2921
+ exports
2922
+ };
2923
+ }
2924
+ /**
2925
+ * Build trigger context from configured workflow source files.
2926
+ * @param workflowConfig - Workflow file loading configuration
2927
+ * @param authNamespace - Auth service namespace (optional, used for string-literal invoker expansion)
2928
+ * @returns Module-local workflow and job binding metadata
2929
+ */
2930
+ async function buildTriggerContext(workflowConfig, authNamespace) {
2931
+ const modules = /* @__PURE__ */ new Map();
2932
+ if (!workflowConfig) return {
2933
+ modules,
2934
+ authNamespace
2935
+ };
2936
+ for (const file of loadFilesWithIgnores(workflowConfig)) try {
2937
+ const source = await fs$1.promises.readFile(file, "utf-8");
2938
+ const { program } = parseSync("input.ts", source);
2939
+ modules.set(normalizeFilePath(file), createModuleBindings(program, source));
2940
+ } catch (error) {
2941
+ const errorMessage = error instanceof Error ? error.message : String(error);
2942
+ logger.warn(`Failed to process workflow file ${file}: ${errorMessage}`, { mode: "stream" });
2943
+ }
2944
+ return {
2945
+ modules,
2946
+ authNamespace
2947
+ };
2948
+ }
2949
+ function sortedTargets(bindings) {
2950
+ return [...bindings].toSorted(([a], [b]) => a.localeCompare(b)).map(([binding, target]) => [
2951
+ binding,
2952
+ target.kind,
2953
+ target.name
2954
+ ]);
2955
+ }
2956
+ /**
2957
+ * Serialize trigger context to a deterministic cache input.
2958
+ * @param context - Trigger context to serialize
2959
+ * @returns Deterministic string, or an empty string when context is absent
2960
+ */
2961
+ function serializeTriggerContext(context) {
2962
+ if (!context) return "";
2963
+ const modules = [...context.modules].toSorted(([a], [b]) => a.localeCompare(b)).map(([file, bindings]) => [
2964
+ file,
2965
+ sortedTargets(bindings.localBindings),
2966
+ sortedTargets(bindings.exports)
2967
+ ]);
2968
+ return JSON.stringify(modules) + (context.authNamespace ?? "");
2768
2969
  }
2769
2970
 
2770
2971
  //#endregion
2771
2972
  //#region src/cli/services/workflow/trigger-transformer.ts
2772
- /**
2773
- * Name of the injected runtime normalizer helper. Chosen to be unique enough
2774
- * to avoid collisions with user code.
2775
- */
2776
2973
  const NORMALIZER_IDENTIFIER = "__tailor_normalizeTriggerOptions";
2777
2974
  /**
2778
2975
  * Build the source text of the injected normalizer helper.
@@ -2788,339 +2985,285 @@ const NORMALIZER_IDENTIFIER = "__tailor_normalizeTriggerOptions";
2788
2985
  function buildNormalizerHelperSource(authNamespace) {
2789
2986
  return `const ${NORMALIZER_IDENTIFIER} = (o) => { if (!o) return o; const { invoker, ...rest } = o; return typeof invoker === "string" ? { ...rest, authInvoker: { namespace: ${JSON.stringify(authNamespace)}, machineUserName: invoker } } : typeof invoker === "object" ? { ...rest, authInvoker: invoker } : o; };\n`;
2790
2987
  }
2791
- /**
2792
- * Check if an AST binding pattern (parameter, catch clause, etc.) contains an Identifier with the given name.
2793
- * @param node - AST node to inspect
2794
- * @param name - Identifier name to look for
2795
- * @returns True if the binding pattern contains the name
2796
- */
2797
- function containsBindingName(node, name) {
2798
- if (!node || typeof node !== "object") return false;
2799
- if (node.type === "Identifier" && node.name === name) return true;
2800
- for (const key of Object.keys(node)) {
2801
- const child = node[key];
2802
- if (Array.isArray(child)) {
2803
- if (child.some((c) => containsBindingName(c, name))) return true;
2804
- } else if (child && typeof child === "object") {
2805
- if (containsBindingName(child, name)) return true;
2806
- }
2988
+ function collectBindingNames(node, names) {
2989
+ if (!node || typeof node !== "object") return;
2990
+ switch (node.type) {
2991
+ case "Identifier":
2992
+ names.add(node.name);
2993
+ return;
2994
+ case "ObjectPattern":
2995
+ for (const property of node.properties) collectBindingNames(property.type === "RestElement" ? property.argument : property.value, names);
2996
+ return;
2997
+ case "ArrayPattern":
2998
+ for (const element of node.elements) collectBindingNames(element, names);
2999
+ return;
3000
+ case "AssignmentPattern":
3001
+ collectBindingNames(node.left, names);
3002
+ return;
3003
+ case "RestElement":
3004
+ collectBindingNames(node.argument, names);
3005
+ return;
3006
+ case "TSParameterProperty": collectBindingNames(node.parameter, names);
2807
3007
  }
2808
- return false;
2809
3008
  }
2810
- /**
2811
- * Build a map of reference counts for multiple identifiers in a single AST pass.
2812
- * Scope-aware: references inside functions or catch clauses that shadow the name
2813
- * via parameters are excluded, so only references to the original import binding
2814
- * are counted.
2815
- * Excludes import declarations and property names in non-computed member expressions.
2816
- * @param program - The parsed AST program
2817
- * @param names - Set of identifier names to count
2818
- * @returns Map from identifier name to reference count
2819
- */
2820
- function buildReferenceCountMap(program, names) {
2821
- if (names.size === 0) return /* @__PURE__ */ new Map();
2822
- const counts = /* @__PURE__ */ new Map();
2823
- const shadowDepth = /* @__PURE__ */ new Map();
2824
- for (const name of names) {
2825
- counts.set(name, 0);
2826
- shadowDepth.set(name, 0);
2827
- }
2828
- function walk(node, parentNode, parentKey) {
3009
+ function declarationNode(statement) {
3010
+ return statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
3011
+ }
3012
+ function collectBlockBindings(statements, names) {
3013
+ for (const statement of statements) {
3014
+ const declaration = declarationNode(statement);
3015
+ if (!declaration) continue;
3016
+ if (declaration.type === "VariableDeclaration") {
3017
+ if (declaration.kind === "var") continue;
3018
+ for (const declarator of declaration.declarations) collectBindingNames(declarator.id, names);
3019
+ } else if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") collectBindingNames(declaration.id, names);
3020
+ }
3021
+ }
3022
+ function collectFunctionVarBindings(root, names) {
3023
+ function walk(node) {
2829
3024
  if (!node || typeof node !== "object") return;
2830
- const nodeType = node.type;
2831
- if (nodeType === "ImportDeclaration") return;
2832
- const shadowedHere = [];
2833
- if (nodeType === "FunctionDeclaration" || nodeType === "FunctionExpression" || nodeType === "ArrowFunctionExpression") {
2834
- const params = node.params;
2835
- if (params) {
2836
- for (const name of names) if (params.some((p) => containsBindingName(p, name))) {
2837
- shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);
2838
- shadowedHere.push(name);
2839
- }
2840
- }
2841
- }
2842
- if (nodeType === "CatchClause") {
2843
- const param = node.param;
2844
- if (param) {
2845
- for (const name of names) if (containsBindingName(param, name)) {
2846
- shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);
2847
- shadowedHere.push(name);
2848
- }
2849
- }
2850
- }
2851
- if (nodeType === "Identifier") {
2852
- const identName = node.name;
2853
- if (identName && names.has(identName) && (shadowDepth.get(identName) ?? 0) === 0) {
2854
- const isMemberProperty = parentNode && parentNode.type === "MemberExpression" && parentKey === "property" && !parentNode.computed;
2855
- const isObjectPropertyKey = parentNode && parentNode.type === "Property" && parentKey === "key" && !parentNode.shorthand && !parentNode.computed;
2856
- if (!isMemberProperty && !isObjectPropertyKey) counts.set(identName, (counts.get(identName) ?? 0) + 1);
2857
- }
3025
+ if (node !== root && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "StaticBlock")) return;
3026
+ if (node.type === "VariableDeclaration" && node.kind === "var") for (const declarator of node.declarations) collectBindingNames(declarator.id, names);
3027
+ for (const key of Object.keys(node)) {
3028
+ if (key === "parent") continue;
3029
+ const child = node[key];
3030
+ if (Array.isArray(child)) for (const item of child) walk(item);
3031
+ else if (child && typeof child === "object") walk(child);
2858
3032
  }
3033
+ }
3034
+ walk(root);
3035
+ }
3036
+ function collectScopeBindings(node) {
3037
+ const names = /* @__PURE__ */ new Set();
3038
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
3039
+ collectBindingNames(node.id, names);
3040
+ for (const parameter of node.params) collectBindingNames(parameter, names);
3041
+ collectFunctionVarBindings(node, names);
3042
+ return names;
3043
+ }
3044
+ if (node.type === "BlockStatement") {
3045
+ collectBlockBindings(node.body, names);
3046
+ return names;
3047
+ }
3048
+ if (node.type === "CatchClause") {
3049
+ collectBindingNames(node.param, names);
3050
+ return names;
3051
+ }
3052
+ if (node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement") {
3053
+ const declaration = node.init ?? node.left;
3054
+ if (declaration?.type === "VariableDeclaration" && declaration.kind !== "var") for (const declarator of declaration.declarations) collectBindingNames(declarator.id, names);
3055
+ return names;
3056
+ }
3057
+ }
3058
+ function addShadowedBindings(shadowedNames, bindings, targetNames) {
3059
+ if (!bindings) return shadowedNames;
3060
+ const relevantBindings = [...bindings].filter((name) => targetNames.has(name));
3061
+ return relevantBindings.length === 0 ? shadowedNames : /* @__PURE__ */ new Set([...shadowedNames, ...relevantBindings]);
3062
+ }
3063
+ function walkBindingAware(program, targetNames, visitor) {
3064
+ function walk(node, shadowedNames, parentNode, parentKey) {
3065
+ if (!node || typeof node !== "object" || node.type === "ImportDeclaration") return;
3066
+ const nestedShadowedNames = node.type === "Program" ? shadowedNames : addShadowedBindings(shadowedNames, collectScopeBindings(node), targetNames);
3067
+ visitor(node, nestedShadowedNames, parentNode, parentKey);
2859
3068
  for (const key of Object.keys(node)) {
3069
+ if (key === "parent") continue;
2860
3070
  const child = node[key];
2861
- if (Array.isArray(child)) child.forEach((c) => walk(c, node, key));
2862
- else if (child && typeof child === "object") walk(child, node, key);
3071
+ if (Array.isArray(child)) for (const item of child) walk(item, nestedShadowedNames, node, key);
3072
+ else if (child && typeof child === "object") walk(child, nestedShadowedNames, node, key);
2863
3073
  }
2864
- for (const name of shadowedHere) shadowDepth.set(name, (shadowDepth.get(name) ?? 0) - 1);
2865
3074
  }
2866
- walk(program);
2867
- return counts;
3075
+ walk(program, /* @__PURE__ */ new Set());
2868
3076
  }
2869
- /**
2870
- * Find the text range to remove for a dead default import.
2871
- *
2872
- * - Default-only import (`import wf from "..."`): returns the full declaration range.
2873
- * - Mixed import (`import wf, { helper } from "..."`): returns the range covering
2874
- * the default specifier and trailing comma/whitespace so the result becomes
2875
- * `import { helper } from "..."`.
2876
- * @param program - The parsed AST program
2877
- * @param localName - The local name of the default import
2878
- * @param source - The source code text (used to locate the `{` in mixed imports)
2879
- * @returns Range to remove, or null if the import was not found
2880
- */
2881
- function findDefaultImportRemovalRange(program, localName, source) {
3077
+ function resolveRelativeImport(context, currentFilePath, importSource) {
3078
+ if (!importSource.startsWith(".")) return void 0;
3079
+ const currentDirectory = path.dirname(currentFilePath.replace(/[?#].*$/, ""));
3080
+ const modulePath = normalizeFilePath(path.resolve(currentDirectory, importSource));
3081
+ return context.modules.get(modulePath) ?? context.modules.get(path.join(modulePath, "index"));
3082
+ }
3083
+ function collectLocalTargets(program, context, currentFilePath) {
3084
+ const targets = /* @__PURE__ */ new Map();
3085
+ const currentModule = context.modules.get(normalizeFilePath(currentFilePath));
3086
+ if (currentModule) for (const [localName, target] of currentModule.localBindings) targets.set(localName, target);
2882
3087
  for (const statement of program.body) {
2883
- if (statement.type !== "ImportDeclaration") continue;
2884
- const importDecl = statement;
2885
- const specifiers = importDecl.specifiers;
2886
- for (const spec of specifiers) {
2887
- if (spec.type !== "ImportDefaultSpecifier") continue;
2888
- const defaultSpec = spec;
2889
- if (defaultSpec.local.name !== localName) continue;
2890
- if (specifiers.length === 1) return {
2891
- start: importDecl.start,
2892
- end: importDecl.end,
2893
- isFullDeclaration: true
2894
- };
2895
- const braceIndex = source.indexOf("{", defaultSpec.end);
2896
- if (braceIndex !== -1) return {
2897
- start: defaultSpec.start,
2898
- end: braceIndex,
2899
- isFullDeclaration: false
2900
- };
2901
- return null;
3088
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
3089
+ const importSource = statement.source.value;
3090
+ if (typeof importSource !== "string") continue;
3091
+ const importedModule = resolveRelativeImport(context, currentFilePath, importSource);
3092
+ if (!importedModule) continue;
3093
+ for (const specifier of statement.specifiers) {
3094
+ if (specifier.type === "ImportNamespaceSpecifier") continue;
3095
+ if (specifier.type === "ImportSpecifier" && specifier.importKind === "type") continue;
3096
+ const importedName = specifier.type === "ImportDefaultSpecifier" ? "default" : getModuleExportName(specifier.imported);
3097
+ if (!importedName) continue;
3098
+ const target = importedModule.exports.get(importedName);
3099
+ if (!target) continue;
3100
+ targets.set(specifier.local.name, target);
2902
3101
  }
2903
3102
  }
2904
- return null;
3103
+ return targets;
2905
3104
  }
2906
- /**
2907
- * Detect .trigger() calls for known workflows and jobs
2908
- * Only detects calls where the identifier is in workflowNames or jobNames
2909
- * @param program - The parsed AST program
2910
- * @param sourceText - The source code text
2911
- * @param workflowNames - Set of known workflow identifier names
2912
- * @param jobNames - Set of known job identifier names
2913
- * @returns Detected trigger call metadata
2914
- */
2915
- function detectExtendedTriggerCalls(program, sourceText, workflowNames, jobNames) {
3105
+ function detectTriggerCallsWithTargets(program, sourceText, targets) {
2916
3106
  const calls = [];
2917
- function walk(node) {
2918
- if (!node || typeof node !== "object") return;
3107
+ walkBindingAware(program, new Set(targets.keys()), (node, shadowedNames) => {
2919
3108
  const triggerCall = getTriggerCallInfo(node, sourceText);
2920
- if (triggerCall) {
2921
- const isWorkflow = workflowNames.has(triggerCall.identifierName);
2922
- const isJob = jobNames.has(triggerCall.identifierName);
2923
- if (isWorkflow) calls.push({
2924
- kind: "workflow",
2925
- identifierName: triggerCall.identifierName,
2926
- callRange: triggerCall.callRange,
2927
- argsText: triggerCall.argsText,
2928
- optionsText: triggerCall.optionsText
2929
- });
2930
- else if (isJob) calls.push({
2931
- kind: "job",
2932
- identifierName: triggerCall.identifierName,
2933
- callRange: triggerCall.callRange,
2934
- argsText: triggerCall.argsText
2935
- });
2936
- }
2937
- for (const key of Object.keys(node)) {
2938
- const child = node[key];
2939
- if (Array.isArray(child)) child.forEach((c) => walk(c));
2940
- else if (child && typeof child === "object") walk(child);
2941
- }
2942
- }
2943
- walk(program);
3109
+ if (!triggerCall || shadowedNames.has(triggerCall.identifierName)) return;
3110
+ const target = targets.get(triggerCall.identifierName);
3111
+ if (target) calls.push({
3112
+ ...triggerCall,
3113
+ kind: target.kind,
3114
+ targetName: target.name
3115
+ });
3116
+ });
2944
3117
  return calls;
2945
3118
  }
2946
- /**
2947
- * Transform trigger calls for resolver/executor/workflow functions
2948
- * Handles job.trigger() and workflow.trigger() calls
2949
- * @param source - The source code to transform
2950
- * @param workflowNameMap - Map from variable name to workflow name
2951
- * @param jobNameMap - Map from variable name to job name
2952
- * @param workflowFileMap - Map from file path (without extension) to workflow name for default exports
2953
- * @param currentFilePath - Path of the current file being transformed (for resolving relative imports)
2954
- * @param authNamespace - Auth service namespace used to expand string-literal `invoker` to object form
2955
- * @returns Transformed source code with trigger calls rewritten
2956
- */
2957
- function transformFunctionTriggers(source, workflowNameMap, jobNameMap, workflowFileMap, currentFilePath, authNamespace) {
3119
+ function detectResolvedTriggerCalls(program, sourceText, context, currentFilePath) {
3120
+ return detectTriggerCallsWithTargets(program, sourceText, collectLocalTargets(program, context, currentFilePath));
3121
+ }
3122
+ function transformFunctionTriggers(source, triggerContext, currentFilePath) {
2958
3123
  const { program } = parseSync("input.ts", source);
2959
- const localWorkflowNameMap = new Map(workflowNameMap);
2960
- const workflowDefaultImportNames = /* @__PURE__ */ new Set();
2961
- if (workflowFileMap && currentFilePath) {
2962
- const defaultImports = detectDefaultImports(program);
2963
- const currentDir = currentFilePath.replace(/[/\\][^/\\]+$/, "");
2964
- for (const [localName, importSource] of defaultImports) {
2965
- if (!importSource.startsWith(".")) continue;
2966
- const resolvedPath = resolvePath(currentDir, importSource).replace(/\.(ts|mts|cts|js|mjs|cjs)$/, "");
2967
- const workflowName = workflowFileMap.get(resolvedPath);
2968
- if (workflowName) {
2969
- localWorkflowNameMap.set(localName, workflowName);
2970
- workflowDefaultImportNames.add(localName);
2971
- }
2972
- }
2973
- }
2974
- const allTriggerCalls = detectExtendedTriggerCalls(program, source, new Set(localWorkflowNameMap.keys()), new Set(jobNameMap.keys()));
3124
+ const localTargets = collectLocalTargets(program, triggerContext, currentFilePath);
3125
+ const { authNamespace } = triggerContext;
3126
+ const allTriggerCalls = detectTriggerCallsWithTargets(program, source, localTargets);
2975
3127
  const nestedTriggerCalls = [];
2976
3128
  const triggerCalls = allTriggerCalls.filter((call) => {
2977
3129
  const parent = allTriggerCalls.find((other) => other !== call && other.callRange.start <= call.callRange.start && call.callRange.end <= other.callRange.end);
2978
- if (parent) {
2979
- nestedTriggerCalls.push({
2980
- call,
2981
- parent
2982
- });
2983
- return false;
2984
- }
2985
- return true;
3130
+ if (!parent) return true;
3131
+ nestedTriggerCalls.push({
3132
+ call,
3133
+ parent
3134
+ });
3135
+ return false;
2986
3136
  });
2987
3137
  for (const { call, parent } of nestedTriggerCalls) logger.warn(`Nested trigger call "${call.identifierName}.trigger(...)" inside "${parent.identifierName}.trigger(...)" cannot be converted. Move it to a separate statement and pass the result instead.`);
2988
3138
  const replacements = [];
2989
3139
  let needsNormalizerHelper = false;
2990
- const transformedCallsPerIdentifier = /* @__PURE__ */ new Map();
2991
- for (const call of triggerCalls) if (call.kind === "workflow") {
2992
- const workflowName = localWorkflowNameMap.get(call.identifierName);
2993
- if (workflowName) {
3140
+ for (const call of triggerCalls) {
3141
+ let transformedCall;
3142
+ if (call.kind === "workflow") {
2994
3143
  let optionsPart = "";
2995
3144
  if (call.optionsText !== void 0) if (authNamespace) {
2996
3145
  optionsPart = `, ${NORMALIZER_IDENTIFIER}(${call.optionsText})`;
2997
3146
  needsNormalizerHelper = true;
2998
3147
  } else optionsPart = `, ${call.optionsText}`;
2999
- const transformedCall = `tailor.workflow.triggerWorkflow("${workflowName}", ${call.argsText || "undefined"}${optionsPart})`;
3000
- replacements.push({
3001
- start: call.callRange.start,
3002
- end: call.callRange.end,
3003
- text: transformedCall
3004
- });
3005
- transformedCallsPerIdentifier.set(call.identifierName, (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1);
3006
- }
3007
- } else {
3008
- const jobName = jobNameMap.get(call.identifierName);
3009
- if (jobName) {
3010
- const transformedCall = `tailor.workflow.triggerJobFunction("${jobName}", ${call.argsText || "undefined"})`;
3011
- replacements.push({
3012
- start: call.callRange.start,
3013
- end: call.callRange.end,
3014
- text: transformedCall
3015
- });
3016
- transformedCallsPerIdentifier.set(call.identifierName, (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1);
3017
- }
3018
- }
3019
- const refCounts = buildReferenceCountMap(program, workflowDefaultImportNames);
3020
- for (const localName of workflowDefaultImportNames) {
3021
- const transformedCount = transformedCallsPerIdentifier.get(localName) ?? 0;
3022
- const refCount = refCounts.get(localName) ?? 0;
3023
- if (refCount === 0 || transformedCount >= refCount) {
3024
- const removal = findDefaultImportRemovalRange(program, localName, source);
3025
- if (removal) replacements.push({
3026
- start: removal.start,
3027
- end: removal.isFullDeclaration ? findStatementEnd(source, removal.end) : removal.end,
3028
- text: ""
3029
- });
3148
+ transformedCall = `tailor.workflow.triggerWorkflow(${JSON.stringify(call.targetName)}, ${call.argsText || "undefined"}${optionsPart})`;
3149
+ } else {
3150
+ const optionsPart = call.optionsText !== void 0 ? `, ${call.optionsText}` : "";
3151
+ transformedCall = `tailor.workflow.triggerJobFunction(${JSON.stringify(call.targetName)}, ${call.argsText || "undefined"}${optionsPart})`;
3030
3152
  }
3153
+ replacements.push({
3154
+ start: call.callRange.start,
3155
+ end: call.callRange.end,
3156
+ text: transformedCall
3157
+ });
3031
3158
  }
3032
3159
  const transformed = applyReplacements(source, replacements);
3033
- if (needsNormalizerHelper && authNamespace) return buildNormalizerHelperSource(authNamespace) + transformed;
3034
- return transformed;
3035
- }
3036
-
3037
- //#endregion
3038
- //#region src/cli/shared/trigger-context.ts
3039
- /**
3040
- * Normalize a file path by removing extension and resolving to absolute path
3041
- * @param filePath - File path to normalize
3042
- * @returns Normalized absolute path without extension
3043
- */
3044
- function normalizeFilePath(filePath) {
3045
- const absolutePath = path.resolve(filePath);
3046
- const ext = path.extname(absolutePath);
3047
- return absolutePath.slice(0, -ext.length);
3048
- }
3049
- /**
3050
- * Build trigger context from workflow configuration
3051
- * Scans workflow files to collect workflow and job mappings
3052
- * @param workflowConfig - Workflow file loading configuration
3053
- * @param authNamespace - Auth service namespace (optional, used for string-literal invoker expansion)
3054
- * @returns Trigger context built from workflow sources
3055
- */
3056
- async function buildTriggerContext(workflowConfig, authNamespace) {
3057
- const workflowNameMap = /* @__PURE__ */ new Map();
3058
- const jobNameMap = /* @__PURE__ */ new Map();
3059
- const workflowFileMap = /* @__PURE__ */ new Map();
3060
- if (!workflowConfig) return {
3061
- workflowNameMap,
3062
- jobNameMap,
3063
- workflowFileMap,
3064
- authNamespace
3065
- };
3066
- const workflowFiles = loadFilesWithIgnores(workflowConfig);
3067
- for (const file of workflowFiles) try {
3068
- const source = await fs$1.promises.readFile(file, "utf-8");
3069
- const { program } = parseSync("input.ts", source);
3070
- const workflows = findAllWorkflows(program, source);
3071
- const workflowMap = buildWorkflowNameMap(workflows);
3072
- for (const [exportName, workflowName] of workflowMap) workflowNameMap.set(exportName, workflowName);
3073
- for (const workflow of workflows) if (workflow.isDefaultExport) {
3074
- const normalizedPath = normalizeFilePath(file);
3075
- workflowFileMap.set(normalizedPath, workflow.name);
3076
- }
3077
- const jobMap = buildJobNameMap(findAllJobs(program, source));
3078
- for (const [exportName, jobName] of jobMap) jobNameMap.set(exportName, jobName);
3079
- } catch (error) {
3080
- const errorMessage = error instanceof Error ? error.message : String(error);
3081
- logger.warn(`Failed to process workflow file ${file}: ${errorMessage}`, { mode: "stream" });
3082
- continue;
3083
- }
3084
- return {
3085
- workflowNameMap,
3086
- jobNameMap,
3087
- workflowFileMap,
3088
- authNamespace
3089
- };
3090
- }
3091
- function sortedMapToJson(m) {
3092
- return JSON.stringify([...m.entries()].toSorted(([a], [b]) => a.localeCompare(b)));
3093
- }
3094
- /**
3095
- * Serialize trigger context to a deterministic string for cache hashing.
3096
- * Returns an empty string if no context is provided.
3097
- * @param ctx - Trigger context to serialize
3098
- * @returns Deterministic string representation
3099
- */
3100
- function serializeTriggerContext(ctx) {
3101
- if (!ctx) return "";
3102
- return sortedMapToJson(ctx.workflowNameMap) + sortedMapToJson(ctx.jobNameMap) + sortedMapToJson(ctx.workflowFileMap) + (ctx.authNamespace ?? "");
3160
+ return needsNormalizerHelper && authNamespace ? buildNormalizerHelperSource(authNamespace) + transformed : transformed;
3103
3161
  }
3104
- /**
3105
- * Create a rolldown plugin for transforming trigger calls
3106
- * Returns undefined if no trigger context is provided
3107
- * @param triggerContext - Trigger context to use for transformations
3108
- * @returns Rolldown plugin or undefined when no context
3109
- */
3110
3162
  function createTriggerTransformPlugin(triggerContext) {
3111
- if (!triggerContext) return;
3163
+ if (!triggerContext) return void 0;
3112
3164
  return {
3113
3165
  name: "trigger-transform",
3114
3166
  transform: {
3115
3167
  filter: { id: { include: [/\.(ts|mts|cts|js|mjs|cjs)$/] } },
3116
3168
  handler(code, id) {
3117
3169
  if (!code.includes(".trigger(")) return null;
3118
- return { code: transformFunctionTriggers(code, triggerContext.workflowNameMap, triggerContext.jobNameMap, triggerContext.workflowFileMap, id, triggerContext.authNamespace) };
3170
+ return { code: transformFunctionTriggers(code, triggerContext, id) };
3119
3171
  }
3120
3172
  }
3121
3173
  };
3122
3174
  }
3123
3175
 
3176
+ //#endregion
3177
+ //#region src/cli/shared/bundle-log-level.ts
3178
+ const INFO_LEVEL_CONSOLE_METHODS = [
3179
+ "console.info",
3180
+ "console.table",
3181
+ "console.dir",
3182
+ "console.dirxml",
3183
+ "console.count",
3184
+ "console.countReset",
3185
+ "console.time",
3186
+ "console.timeLog",
3187
+ "console.timeEnd",
3188
+ "console.group",
3189
+ "console.groupCollapsed",
3190
+ "console.groupEnd",
3191
+ "console.clear"
3192
+ ];
3193
+ const DEBUG_LEVEL_CONSOLE_METHODS = [
3194
+ "console.debug",
3195
+ "console.log",
3196
+ "console.trace"
3197
+ ];
3198
+ const WARN_LEVEL_CONSOLE_METHODS = ["console.warn"];
3199
+ const ERROR_LEVEL_CONSOLE_METHODS = ["console.error"];
3200
+ const MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL = {
3201
+ DEBUG: [],
3202
+ INFO: DEBUG_LEVEL_CONSOLE_METHODS,
3203
+ WARN: [...DEBUG_LEVEL_CONSOLE_METHODS, ...INFO_LEVEL_CONSOLE_METHODS],
3204
+ ERROR: [
3205
+ ...DEBUG_LEVEL_CONSOLE_METHODS,
3206
+ ...INFO_LEVEL_CONSOLE_METHODS,
3207
+ ...WARN_LEVEL_CONSOLE_METHODS
3208
+ ],
3209
+ SILENT: [
3210
+ ...DEBUG_LEVEL_CONSOLE_METHODS,
3211
+ ...INFO_LEVEL_CONSOLE_METHODS,
3212
+ ...WARN_LEVEL_CONSOLE_METHODS,
3213
+ ...ERROR_LEVEL_CONSOLE_METHODS
3214
+ ]
3215
+ };
3216
+ function normalizeBundleLogLevel(value) {
3217
+ const normalized = value.trim().toUpperCase();
3218
+ return isLogLevel(normalized) ? normalized : void 0;
3219
+ }
3220
+ function resolveBundleLogLevel(configValue) {
3221
+ if (configValue === void 0) return "DEBUG";
3222
+ const resolved = normalizeBundleLogLevel(configValue);
3223
+ if (resolved) return resolved;
3224
+ throw new Error(`Invalid logLevel "${configValue}". Expected one of: ${LOG_LEVELS.join(", ")}`);
3225
+ }
3226
+ function manualPureFunctionsForLogLevel(logLevel) {
3227
+ return MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL[logLevel];
3228
+ }
3229
+ function createLogLevelTreeshakeOptions(logLevel) {
3230
+ const manualPureFunctions = manualPureFunctionsForLogLevel(logLevel);
3231
+ return manualPureFunctions.length > 0 ? { manualPureFunctions } : {};
3232
+ }
3233
+
3234
+ //#endregion
3235
+ //#region src/cli/shared/function-treeshake.ts
3236
+ const BASE_FUNCTION_TREESHAKE_OPTIONS = {
3237
+ moduleSideEffects: false,
3238
+ annotations: true,
3239
+ unknownGlobalSideEffects: false
3240
+ };
3241
+ function mergeFunctionTreeshakeOptions(fragments) {
3242
+ const merged = {};
3243
+ const manualPureFunctions = /* @__PURE__ */ new Set();
3244
+ for (const fragment of fragments) {
3245
+ Object.assign(merged, fragment);
3246
+ for (const name of fragment.manualPureFunctions ?? []) manualPureFunctions.add(name);
3247
+ }
3248
+ if (manualPureFunctions.size > 0) merged.manualPureFunctions = [...manualPureFunctions];
3249
+ else delete merged.manualPureFunctions;
3250
+ return merged;
3251
+ }
3252
+ function composeFunctionTreeshakeOptions(fragments = []) {
3253
+ return mergeFunctionTreeshakeOptions([BASE_FUNCTION_TREESHAKE_OPTIONS, ...fragments]);
3254
+ }
3255
+
3256
+ //#endregion
3257
+ //#region src/cli/shared/platform-bundle-plugin.ts
3258
+ const GATE = /(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g;
3259
+ const platformBundleDefinePlugin = {
3260
+ name: "tailor-platform-bundle-define",
3261
+ transform(code) {
3262
+ if (!code.includes("process.env.__TAILOR_PLATFORM_BUNDLE")) return null;
3263
+ return { code: code.replace(GATE, "true") };
3264
+ }
3265
+ };
3266
+
3124
3267
  //#endregion
3125
3268
  //#region src/cli/services/auth/bundler.ts
3126
3269
  /**
@@ -3356,7 +3499,17 @@ function formatScriptContext(kind, context) {
3356
3499
  const convertToScriptExpr = (fn, kind, context) => {
3357
3500
  const precompiledExpr = getPrecompiledScriptExpr(fn);
3358
3501
  if (precompiledExpr) return precompiledExpr;
3359
- return assertParsableExpression(`(${stringifyFunction(fn)})({ value: _value, data: _data, invoker: ${tailorPrincipalMap} })`, formatScriptContext(kind, context));
3502
+ return assertParsableExpression(`(${stringifyFunction(fn)})(${kind === "validate" ? `{ value: _value }` : kind === "hooks.create" ? `{ input: _value, invoker: ${tailorPrincipalMap}, now: _now }` : `{ input: _value, oldValue: _oldValue, invoker: ${tailorPrincipalMap}, now: _now }`})`, formatScriptContext(kind, context));
3503
+ };
3504
+ const convertTypeHookToExpr = (fn) => {
3505
+ const precompiledExpr = getPrecompiledScriptExpr(fn);
3506
+ if (precompiledExpr) return precompiledExpr;
3507
+ return assertParsableExpression(`(${stringifyFunction(fn)})({ input: _input, oldRecord: _oldRecord, invoker: ${tailorPrincipalMap}, now: _now })`, "type-hook");
3508
+ };
3509
+ const convertTypeValidateToExpr = (fn) => {
3510
+ const precompiledExpr = getPrecompiledScriptExpr(fn);
3511
+ if (precompiledExpr) return precompiledExpr;
3512
+ return assertParsableExpression(`(${stringifyFunction(fn)})({ newRecord: _newRecord, oldRecord: _oldRecord, invoker: ${tailorPrincipalMap} }, __issues)`, "type-validate");
3360
3513
  };
3361
3514
  /**
3362
3515
  * Parse TailorDBField into OperatorFieldConfig.
@@ -3369,6 +3522,8 @@ function parseFieldConfig(field, context) {
3369
3522
  const metadata = field.metadata;
3370
3523
  const fieldType = field.type;
3371
3524
  const rawRelation = field.rawRelation;
3525
+ if (context && context.fieldPath.length > 1 && metadata.default !== void 0) throw new Error(`Field "${context.fieldPath.join(".")}" on type "${context.typeName}": .default() cannot be used on nested inner fields`);
3526
+ if (context && context.fieldPath.length > 1 && metadata.hooks) throw new Error(`Field "${context.fieldPath.join(".")}" on type "${context.typeName}": .hooks() cannot be used on nested inner fields`);
3372
3527
  const nestedFields = field.fields;
3373
3528
  return {
3374
3529
  type: fieldType,
@@ -3381,19 +3536,10 @@ function parseFieldConfig(field, context) {
3381
3536
  });
3382
3537
  return acc;
3383
3538
  }, {}) } : {},
3384
- validate: metadata.validate?.map((v) => {
3385
- const { fn, message } = typeof v === "function" ? {
3386
- fn: v,
3387
- message: `failed by \`${v.toString().trim()}\``
3388
- } : {
3389
- fn: v[0],
3390
- message: v[1]
3391
- };
3392
- return {
3393
- script: { expr: convertToScriptExpr(fn, "validate", context) },
3394
- errorMessage: message
3395
- };
3396
- }),
3539
+ validate: metadata.validate?.map((fn) => ({
3540
+ script: { expr: convertToScriptExpr(fn, "validate", context) },
3541
+ errorMessage: ""
3542
+ })),
3397
3543
  hooks: metadata.hooks ? {
3398
3544
  create: metadata.hooks.create ? { expr: convertToScriptExpr(metadata.hooks.create, "hooks.create", context) } : void 0,
3399
3545
  update: metadata.hooks.update ? { expr: convertToScriptExpr(metadata.hooks.update, "hooks.update", context) } : void 0
@@ -3633,7 +3779,12 @@ function parseTailorDBType(type, allTypeNames, rawTypes, typeSourceInfo) {
3633
3779
  settings: metadata.settings ?? {},
3634
3780
  permissions: parsePermissions(metadata.permissions),
3635
3781
  indexes: metadata.indexes,
3636
- files: metadata.files
3782
+ files: metadata.files,
3783
+ ...metadata.typeHook && { typeHookExpr: {
3784
+ ...typeof metadata.typeHook.create === "function" && { create: convertTypeHookToExpr(metadata.typeHook.create) },
3785
+ ...typeof metadata.typeHook.update === "function" && { update: convertTypeHookToExpr(metadata.typeHook.update) }
3786
+ } },
3787
+ ...typeof metadata.typeValidate === "function" && { typeValidateExpr: convertTypeValidateToExpr(metadata.typeValidate) }
3637
3788
  };
3638
3789
  }
3639
3790
  /**
@@ -3720,7 +3871,7 @@ function validatePluralFormUniqueness(types, namespace, typeSourceInfo) {
3720
3871
  const singularQuery = inflection.camelize(parsedType.name, true);
3721
3872
  if (singularQuery === inflection.camelize(parsedType.pluralForm, true)) {
3722
3873
  const location = formatTypeSourceLocation(getTypeSourceInfo(typeSourceInfo, parsedType.name));
3723
- errors.push(`Type "${parsedType.name}"${location} has identical singular and plural query names "${singularQuery}". Use db.type(["${parsedType.name}", "UniquePluralForm"], {...}) to set a unique pluralForm.`);
3874
+ errors.push(`Type "${parsedType.name}"${location} has identical singular and plural query names "${singularQuery}". Use db.table(["${parsedType.name}", "UniquePluralForm"], {...}) to set a unique pluralForm.`);
3724
3875
  }
3725
3876
  }
3726
3877
  const queryNameToSource = /* @__PURE__ */ new Map();
@@ -3824,29 +3975,35 @@ function collectScriptTargets(type) {
3824
3975
  const createHook = toScriptFunction(metadata.hooks?.create);
3825
3976
  if (createHook) targets.push({
3826
3977
  fn: createHook,
3827
- kind: "hooks"
3978
+ kind: "hooks.create"
3828
3979
  });
3829
3980
  const updateHook = toScriptFunction(metadata.hooks?.update);
3830
3981
  if (updateHook) targets.push({
3831
3982
  fn: updateHook,
3832
- kind: "hooks"
3983
+ kind: "hooks.update"
3833
3984
  });
3834
- for (const validateInput of metadata.validate ?? []) if (typeof validateInput === "function") {
3985
+ for (const validateInput of metadata.validate ?? []) {
3835
3986
  const validateFn = toScriptFunction(validateInput);
3836
3987
  if (validateFn) targets.push({
3837
3988
  fn: validateFn,
3838
3989
  kind: "validate"
3839
3990
  });
3840
- } else {
3841
- const validateFn = toScriptFunction(validateInput[0]);
3842
- if (validateFn) targets.push({
3843
- fn: validateFn,
3844
- kind: "validate"
3845
- });
3846
3991
  }
3847
3992
  if (field.type === "nested" && field.fields) for (const nestedField of Object.values(field.fields)) collectFieldTargets(nestedField);
3848
3993
  };
3849
3994
  for (const field of Object.values(type.fields)) collectFieldTargets(field);
3995
+ if (type.metadata.typeHook) for (const op of ["create", "update"]) {
3996
+ const fn = toScriptFunction(type.metadata.typeHook[op]);
3997
+ if (fn) targets.push({
3998
+ fn,
3999
+ kind: "typeHook"
4000
+ });
4001
+ }
4002
+ const typeValidateFn = toScriptFunction(type.metadata.typeValidate);
4003
+ if (typeValidateFn) targets.push({
4004
+ fn: typeValidateFn,
4005
+ kind: "typeValidate"
4006
+ });
3850
4007
  return targets;
3851
4008
  }
3852
4009
  /**
@@ -4040,11 +4197,11 @@ function resolveNeededBindings(freeVars, sourceBindings) {
4040
4197
  unresolved
4041
4198
  };
4042
4199
  }
4043
- function buildPrecompiledExpr(bundleCode) {
4200
+ function buildPrecompiledExpr(bundleCode, argsObject) {
4044
4201
  return `(() => {
4045
4202
  const module = { exports: {} };
4046
4203
  const exports = module.exports;
4047
- ${bundleCode}\n return module.exports.main({ value: _value, data: _data, invoker: ${tailorPrincipalMap} });\n})()`;
4204
+ ${bundleCode}\n return module.exports.main(${argsObject});\n})()`;
4048
4205
  }
4049
4206
  /**
4050
4207
  * Build entry file content from already-resolved imports and declarations.
@@ -4052,27 +4209,30 @@ ${bundleCode}\n return module.exports.main({ value: _value, data: _data, invoke
4052
4209
  * @param declarations - Declaration statement texts.
4053
4210
  * @param fnSource - The function source code.
4054
4211
  * @param sourceFilePath - Path to the source file for resolving relative imports.
4212
+ * @param multiArg - Whether the function accepts multiple arguments (spread via `...args`).
4055
4213
  * @returns Entry file content string.
4056
4214
  */
4057
- function buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath) {
4215
+ function buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath, multiArg = false) {
4058
4216
  const sourceDir = resolve(sourceFilePath, "..").replace(/\\/g, "/");
4059
4217
  return [
4060
4218
  ...imports.map((imp) => imp.replace(/from\s+["'](\.[^"']+)["']/g, (_match, relPath) => `from "${resolve(sourceDir, relPath).replace(/\\/g, "/")}"`)),
4061
4219
  ...declarations,
4062
- `export function main(input) { return (${fnSource})(input); }`
4220
+ multiArg ? `export function main(...args) { return (${fnSource})(...args); }` : `export function main(input) { return (${fnSource})(input); }`
4063
4221
  ].join("\n");
4064
4222
  }
4065
4223
  async function bundleScriptTarget(args) {
4066
4224
  const { fn, kind, sourceFilePath, sourceBindings, tempDir, targetIndex, tsconfig } = args;
4067
4225
  const context = `${kind} in ${sourceFilePath}`;
4068
4226
  const fnSource = stringifyFunction(fn);
4069
- const inlineExpr = assertParsableExpression(`(${fnSource})({ value: _value, data: _data, invoker: ${tailorPrincipalMap} })`, context);
4227
+ if ((kind === "typeValidate" || kind === "validate") && fn.constructor.name === "AsyncFunction") throw new Error(`${context} must be synchronous — the generated validator runs synchronously, so issues reported after an await are silently lost. Remove the async keyword.`);
4228
+ const argsObject = kind === "hooks.create" ? `{ input: _value, invoker: ${tailorPrincipalMap}, now: _now }` : kind === "hooks.update" ? `{ input: _value, oldValue: _oldValue, invoker: ${tailorPrincipalMap}, now: _now }` : kind === "validate" ? `{ value: _value }` : kind === "typeHook" ? `{ input: _input, oldRecord: _oldRecord, invoker: ${tailorPrincipalMap}, now: _now }` : `{ newRecord: _newRecord, oldRecord: _oldRecord, invoker: ${tailorPrincipalMap} }, __issues`;
4229
+ const inlineExpr = assertParsableExpression(`(${fnSource})(${argsObject})`, context);
4070
4230
  const freeVars = findUndefinedReferences(`const __fn = ${fnSource};`);
4071
4231
  if (freeVars.size === 0) return inlineExpr;
4072
4232
  const { imports, declarations, unresolved } = resolveNeededBindings(freeVars, sourceBindings);
4073
4233
  if (unresolved.length > 0) throw new Error(`${context} captures unresolvable variables (${unresolved.join(", ")}). Hooks and validators must not reference variables that cannot be resolved from the source file.
4074
4234
  ${kind}: ${fnSource}`);
4075
- const entryContent = buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath);
4235
+ const entryContent = buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath, kind === "typeValidate");
4076
4236
  const entryPath = join(tempDir, `tailordb-script-${targetIndex}.entry.ts`);
4077
4237
  writeFileSync(entryPath, entryContent);
4078
4238
  const bundledCode = (await rolldown.build({
@@ -4093,7 +4253,7 @@ async function bundleScriptTarget(args) {
4093
4253
  },
4094
4254
  logLevel: "silent"
4095
4255
  })).output[0].code;
4096
- return assertParsableExpression(buildPrecompiledExpr(bundledCode), context);
4256
+ return assertParsableExpression(buildPrecompiledExpr(bundledCode, argsObject), context);
4097
4257
  }
4098
4258
  /**
4099
4259
  * Precompile TailorDB hooks/validators into self-contained script expressions using rolldown.
@@ -5243,36 +5403,15 @@ function assertUniqueResolverNames(resolvers, namespace) {
5243
5403
  */
5244
5404
  function findVariableDeclarationsByName(program) {
5245
5405
  const declarations = /* @__PURE__ */ new Map();
5246
- function walk(node) {
5247
- if (!node || typeof node !== "object") return;
5248
- const nodeType = node.type;
5249
- if (nodeType === "VariableDeclaration") {
5250
- const varDecl = node;
5251
- for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) {
5252
- if (!declarations.has(decl.id.name)) declarations.set(decl.id.name, {
5253
- start: varDecl.start,
5254
- end: varDecl.end
5255
- });
5256
- }
5257
- }
5258
- if (nodeType === "ExportNamedDeclaration") {
5259
- const exportDecl = node;
5260
- const declaration = exportDecl.declaration;
5261
- if (declaration?.type === "VariableDeclaration") {
5262
- const varDecl = declaration;
5263
- for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) declarations.set(decl.id.name, {
5264
- start: exportDecl.start,
5265
- end: exportDecl.end
5266
- });
5267
- }
5268
- }
5269
- for (const key of Object.keys(node)) {
5270
- const child = node[key];
5271
- if (Array.isArray(child)) child.forEach((c) => walk(c));
5272
- else if (child && typeof child === "object") walk(child);
5273
- }
5406
+ for (const statement of program.body) {
5407
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
5408
+ if (declaration?.type !== "VariableDeclaration") continue;
5409
+ const variableDeclaration = declaration;
5410
+ for (const declarator of variableDeclaration.declarations) if (declarator.id.type === "Identifier") declarations.set(declarator.id.name, {
5411
+ start: statement.start,
5412
+ end: statement.end
5413
+ });
5274
5414
  }
5275
- walk(program);
5276
5415
  return declarations;
5277
5416
  }
5278
5417
  /**
@@ -5299,48 +5438,32 @@ function findWorkflowDefaultExport(program) {
5299
5438
  }
5300
5439
  /**
5301
5440
  * Transform workflow source code
5302
- * - Transform .trigger() calls to tailor.workflow.triggerJobFunction()
5303
5441
  * - Other jobs: remove entire variable declaration
5304
5442
  * @param source - The source code to transform
5305
5443
  * @param targetJobName - The name of the target job (from job config)
5306
5444
  * @param targetJobExportName - The export name of the target job (optional, for enhanced detection)
5307
5445
  * @param otherJobExportNames - Export names of other jobs to remove (optional, for enhanced detection)
5308
- * @param allJobsMap - Map from export name to job name for trigger transformation (optional)
5309
5446
  * @returns Transformed workflow source code
5310
5447
  */
5311
- function transformWorkflowSource(source, targetJobName, targetJobExportName, otherJobExportNames, allJobsMap) {
5448
+ function transformWorkflowSource(source, targetJobName, targetJobExportName, otherJobExportNames) {
5312
5449
  const { program } = parseSync("input.ts", source);
5313
5450
  const detectedJobs = findAllJobs(program, source);
5314
5451
  if (!detectedJobs.some((j) => j.name === targetJobName)) return source;
5315
- const jobNameMap = allJobsMap ?? buildJobNameMap(detectedJobs);
5316
5452
  const allDeclarations = findVariableDeclarationsByName(program);
5317
- const triggerCalls = detectTriggerCalls(program, source);
5318
5453
  const replacements = [];
5319
- const removedRanges = [];
5320
- const isInsideRemovedRange = (pos) => {
5321
- return removedRanges.some((r) => pos >= r.start && pos < r.end);
5322
- };
5323
- const isAlreadyMarkedForRemoval = (start) => {
5324
- return removedRanges.some((r) => r.start === start);
5325
- };
5454
+ const removedStarts = /* @__PURE__ */ new Set();
5326
5455
  for (const job of detectedJobs) {
5327
5456
  if (job.name === targetJobName) continue;
5328
- if (job.statementRange && !isAlreadyMarkedForRemoval(job.statementRange.start)) {
5457
+ if (job.statementRange && !removedStarts.has(job.statementRange.start)) {
5329
5458
  const endPos = findStatementEnd(source, job.statementRange.end);
5330
- removedRanges.push({
5331
- start: job.statementRange.start,
5332
- end: endPos
5333
- });
5459
+ removedStarts.add(job.statementRange.start);
5334
5460
  replacements.push({
5335
5461
  start: job.statementRange.start,
5336
5462
  end: endPos,
5337
5463
  text: ""
5338
5464
  });
5339
5465
  } else if (!job.statementRange) {
5340
- removedRanges.push({
5341
- start: job.bodyValueRange.start,
5342
- end: job.bodyValueRange.end
5343
- });
5466
+ removedStarts.add(job.bodyValueRange.start);
5344
5467
  replacements.push({
5345
5468
  start: job.bodyValueRange.start,
5346
5469
  end: job.bodyValueRange.end,
@@ -5351,12 +5474,9 @@ function transformWorkflowSource(source, targetJobName, targetJobExportName, oth
5351
5474
  if (otherJobExportNames) for (const exportName of otherJobExportNames) {
5352
5475
  if (exportName === targetJobExportName) continue;
5353
5476
  const declRange = allDeclarations.get(exportName);
5354
- if (declRange && !isAlreadyMarkedForRemoval(declRange.start)) {
5477
+ if (declRange && !removedStarts.has(declRange.start)) {
5355
5478
  const endPos = findStatementEnd(source, declRange.end);
5356
- removedRanges.push({
5357
- start: declRange.start,
5358
- end: endPos
5359
- });
5479
+ removedStarts.add(declRange.start);
5360
5480
  replacements.push({
5361
5481
  start: declRange.start,
5362
5482
  end: endPos,
@@ -5365,30 +5485,15 @@ function transformWorkflowSource(source, targetJobName, targetJobExportName, oth
5365
5485
  }
5366
5486
  }
5367
5487
  const workflowExport = findWorkflowDefaultExport(program);
5368
- if (workflowExport && !isAlreadyMarkedForRemoval(workflowExport.start)) {
5488
+ if (workflowExport && !removedStarts.has(workflowExport.start)) {
5369
5489
  const endPos = findStatementEnd(source, workflowExport.end);
5370
- removedRanges.push({
5371
- start: workflowExport.start,
5372
- end: endPos
5373
- });
5490
+ removedStarts.add(workflowExport.start);
5374
5491
  replacements.push({
5375
5492
  start: workflowExport.start,
5376
5493
  end: endPos,
5377
5494
  text: ""
5378
5495
  });
5379
5496
  }
5380
- for (const call of triggerCalls) {
5381
- if (isInsideRemovedRange(call.callRange.start)) continue;
5382
- const jobName = jobNameMap.get(call.identifierName);
5383
- if (jobName) {
5384
- const transformedCall = `tailor.workflow.triggerJobFunction("${jobName}", ${call.argsText || "undefined"})`;
5385
- replacements.push({
5386
- start: call.callRange.start,
5387
- end: call.callRange.end,
5388
- text: transformedCall
5389
- });
5390
- }
5391
- }
5392
5497
  return applyReplacements(source, replacements);
5393
5498
  }
5394
5499
 
@@ -5430,7 +5535,7 @@ async function bundleWorkflowJobs(allJobs, mainJobNames, env = {}, triggerContex
5430
5535
  bundledCode: /* @__PURE__ */ new Map()
5431
5536
  };
5432
5537
  }
5433
- const { usedJobs, mainJobDeps } = await filterUsedJobs(allJobs, mainJobNames);
5538
+ const { usedJobs, mainJobDeps } = await filterUsedJobs(allJobs, mainJobNames, triggerContext);
5434
5539
  logger.newline();
5435
5540
  logger.log(`Bundling ${styles.highlight(usedJobs.length.toString())} files for ${styles.info("\"workflow-job\"")}`);
5436
5541
  const outputDir = path.resolve(getDistDir(), "workflow-jobs");
@@ -5464,9 +5569,10 @@ async function bundleWorkflowJobs(allJobs, mainJobNames, env = {}, triggerContex
5464
5569
  * Also returns a map of mainJob -> all jobs it depends on (for metadata).
5465
5570
  * @param allJobs - All available job infos
5466
5571
  * @param mainJobNames - Names of main jobs
5572
+ * @param triggerContext - Module binding metadata for resolving trigger targets
5467
5573
  * @returns Used jobs and main job dependency map
5468
5574
  */
5469
- async function filterUsedJobs(allJobs, mainJobNames) {
5575
+ async function filterUsedJobs(allJobs, mainJobNames, triggerContext) {
5470
5576
  if (allJobs.length === 0 || mainJobNames.length === 0) return {
5471
5577
  usedJobs: [],
5472
5578
  mainJobDeps: {}
@@ -5477,26 +5583,19 @@ async function filterUsedJobs(allJobs, mainJobNames) {
5477
5583
  existing.push(job);
5478
5584
  jobsBySourceFile.set(job.sourceFile, existing);
5479
5585
  }
5480
- const exportNameToJobName = /* @__PURE__ */ new Map();
5481
- for (const job of allJobs) exportNameToJobName.set(job.exportName, job.name);
5482
5586
  const dependencies = /* @__PURE__ */ new Map();
5483
5587
  const fileResults = await Promise.all(Array.from(jobsBySourceFile.entries()).map(async ([sourceFile, jobs]) => {
5484
5588
  try {
5485
5589
  const source = await fs$1.promises.readFile(sourceFile, "utf-8");
5486
5590
  const { program } = parseSync("input.ts", source);
5487
5591
  const detectedJobs = findAllJobs(program, source);
5488
- const localExportNameToJobName = /* @__PURE__ */ new Map();
5489
- for (const detected of detectedJobs) if (detected.exportName) localExportNameToJobName.set(detected.exportName, detected.name);
5490
- const triggerCalls = detectTriggerCalls(program, source);
5592
+ const triggerCalls = detectResolvedTriggerCalls(program, source, triggerContext, sourceFile);
5491
5593
  const jobDependencies = [];
5492
5594
  for (const job of jobs) {
5493
5595
  const detectedJob = detectedJobs.find((d) => d.name === job.name);
5494
5596
  if (!detectedJob) continue;
5495
5597
  const jobDeps = /* @__PURE__ */ new Set();
5496
- for (const call of triggerCalls) if (call.callRange.start >= detectedJob.bodyValueRange.start && call.callRange.end <= detectedJob.bodyValueRange.end) {
5497
- const triggeredJobName = localExportNameToJobName.get(call.identifierName) || exportNameToJobName.get(call.identifierName);
5498
- if (triggeredJobName) jobDeps.add(triggeredJobName);
5499
- }
5598
+ for (const call of triggerCalls) if (call.kind === "job" && call.callRange.start >= detectedJob.bodyValueRange.start && call.callRange.end <= detectedJob.bodyValueRange.end) jobDeps.add(call.targetName);
5500
5599
  if (jobDeps.size > 0) jobDependencies.push({
5501
5600
  jobName: job.name,
5502
5601
  deps: jobDeps
@@ -5557,10 +5656,8 @@ async function bundleSingleJob(job, allJobs, outputDir, tsconfig, env, triggerCo
5557
5656
  }
5558
5657
  `;
5559
5658
  fs$1.writeFileSync(entryPath, entryContent);
5560
- const otherJobExportNames = allJobs.filter((j) => j.name !== job.name).map((j) => j.exportName);
5561
- const allJobsMap = /* @__PURE__ */ new Map();
5562
- for (const j of allJobs) allJobsMap.set(j.exportName, j.name);
5563
5659
  const resolvedSourceFile = safeRealpath(job.sourceFile);
5660
+ const otherJobExportNames = allJobs.filter((candidate) => candidate.name !== job.name && safeRealpath(candidate.sourceFile) === resolvedSourceFile).map((j) => j.exportName);
5564
5661
  const plugins = [
5565
5662
  {
5566
5663
  name: "workflow-transform",
@@ -5569,8 +5666,8 @@ async function bundleSingleJob(job, allJobs, outputDir, tsconfig, env, triggerCo
5569
5666
  handler(code, id) {
5570
5667
  if (!code.includes("createWorkflowJob") && !code.includes("createWorkflow") && !code.includes(".trigger(")) return null;
5571
5668
  let transformed = code;
5572
- if (safeRealpath(id) === resolvedSourceFile) transformed = transformWorkflowSource(code, job.name, job.exportName, otherJobExportNames, allJobsMap);
5573
- if (triggerContext && transformed.includes(".trigger(")) transformed = transformFunctionTriggers(transformed, triggerContext.workflowNameMap, triggerContext.jobNameMap, triggerContext.workflowFileMap, id, triggerContext.authNamespace);
5669
+ if (safeRealpath(id) === resolvedSourceFile) transformed = transformWorkflowSource(code, job.name, job.exportName, otherJobExportNames);
5670
+ if (transformed.includes(".trigger(")) transformed = transformFunctionTriggers(transformed, triggerContext, id);
5574
5671
  if (transformed === code) return null;
5575
5672
  return { code: transformed };
5576
5673
  }
@@ -5638,6 +5735,13 @@ const RetryPolicySchema = z.strictObject({
5638
5735
  path: ["initialBackoff"]
5639
5736
  });
5640
5737
  const ConcurrencyPolicySchema = z.strictObject({ maxConcurrentExecutions: z.number().int().min(1).max(1e3).describe("Maximum number of concurrent executions (1-1000)") });
5738
+ const ExecutionPolicyNameSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/, "Invalid execution policy name: must match [a-z0-9-] (3-63 chars; must start and end with [a-z0-9])").describe("Workspace-unique execution policy name embedded in the resource TRN");
5739
+ const ExecutionPolicyKeySchema = z.string().regex(/^[a-z0-9][a-z0-9_:.-]{0,62}[a-z0-9*]$/, "Invalid execution policy key: must match [a-z0-9_:.-] (2-64 chars; must start with [a-z0-9] and end with [a-z0-9] or a trailing '*')").describe("Execution policy key passed to triggerJobFunction's executionPolicyKey option");
5740
+ const WorkflowJobFunctionExecutionPolicySchema = z.strictObject({
5741
+ name: ExecutionPolicyNameSchema,
5742
+ key: ExecutionPolicyKeySchema,
5743
+ concurrencyPolicy: ConcurrencyPolicySchema.optional().describe("Optional per-key concurrency cap for job function dispatches matching this policy")
5744
+ });
5641
5745
  const WorkflowSchema = z.strictObject({
5642
5746
  name: z.string().describe("Workflow name"),
5643
5747
  mainJob: WorkflowJobSchema.describe("Main job that starts the workflow"),
@@ -6389,5 +6493,5 @@ async function loadApplication(params) {
6389
6493
  }
6390
6494
 
6391
6495
  //#endregion
6392
- export { getConsoleBaseUrl as $, hasUserTokenEntry as A, removeLegacyUserAlias as B, getDistDir as C, deleteUserTokens as D, loadConfig as E, loadPlatformClientConfig as F, closeConnectionPool as G, resolveUserTokenKey as H, loadStoredUserTokens as I, fetchAllTolerant as J, defaultPlatformBaseUrl as K, loadWorkspaceId as L, loadConfigPath as M, loadConsoleBaseUrl as N, fetchLatestToken as O, loadMachineUserName as P, fetchUserInfo as Q, platformConfigFromProfile as R, createBundleCache as S, hashFile as T, saveUserTokens as U, resolveConfigUser as V, writePlatformConfig as W, fetchPaged as X, fetchMachineUserToken as Y, fetchPlatformMachineUserToken as Z, composeFunctionTreeshakeOptions as _, resolveInlineSourcemap as a, isDefaultPlatform as at, getPluginGenerationDependencies as b, ResolverSchema as c, buildExecutorArgsExpr as d, getOAuth2ClientId as et, buildResolverOperationHookExpr as f, platformBundleDefinePlugin as g, stringifyFunction as h, resolverBundleKey as i, initOperatorClient as it, loadAccessToken as j, hasAnyUserTokenEntry as k, HTTP_METHODS as l, assertUniqueTailorDBTypeNamesWithExternal as m, generatePluginFilesIfNeeded as n, getPlatformBaseUrl as nt, getApplicationAuthNamespace as o, resolveStaticWebsiteUrls as ot, assertUniqueLocalTailorDBTypeNames as p, fetchAll as q, loadApplication as r, initOAuth2Client as rt, WorkflowJobSchema as s, byName as st, defineApplication as t, getOrNull as tt, INVOKER_EXPR as u, createLogLevelTreeshakeOptions as v, hashContent as w, hasGenerationHooks as x, resolveBundleLogLevel as y, readPlatformConfig as z };
6393
- //# sourceMappingURL=application-eHp9jXld.mjs.map
6496
+ export { fetchUserInfo as $, hasAnyUserTokenEntry as A, readPlatformConfig as B, createBundleCache as C, positiveIntArg as Ct, loadConfig as D, hashFile as E, workspaceArgs as Et, loadMachineUserName as F, writePlatformConfig as G, resolveConfigUser as H, loadPlatformClientConfig as I, fetchAll as J, closeConnectionPool as K, loadStoredUserTokens as L, loadAccessToken as M, loadConfigPath as N, deleteUserTokens as O, loadConsoleBaseUrl as P, fetchPlatformMachineUserToken as Q, loadWorkspaceId as R, hasGenerationHooks as S, parseDuration as St, hashContent as T, toPageDirection as Tt, resolveUserTokenKey as U, removeLegacyUserAlias as V, saveUserTokens as W, fetchMachineUserToken as X, fetchAllTolerant as Y, fetchPaged as Z, platformBundleDefinePlugin as _, nonNegativeIntArg as _t, resolveInlineSourcemap as a, initOperatorClient as at, resolveBundleLogLevel as b, pagedLogArgs as bt, WorkflowJobSchema as c, byName as ct, INVOKER_EXPR as d, confirmationArgs as dt, getConsoleBaseUrl as et, buildExecutorArgsExpr as f, deploymentArgs as ft, stringifyFunction as g, multiConfigArg as gt, assertUniqueTailorDBTypeNamesWithExternal as h, isVerbose as ht, resolverBundleKey as i, initOAuth2Client as it, hasUserTokenEntry as j, fetchLatestToken as k, ResolverSchema as l, commonArgs as lt, assertUniqueLocalTailorDBTypeNames as m, folderArgs as mt, generatePluginFilesIfNeeded as n, getOrNull as nt, getApplicationAuthNamespace as o, isDefaultPlatform as ot, buildResolverOperationHookExpr as p, durationArg as pt, defaultPlatformBaseUrl as q, loadApplication as r, getPlatformBaseUrl as rt, WorkflowJobFunctionExecutionPolicySchema as s, resolveStaticWebsiteUrls as st, defineApplication as t, getOAuth2ClientId as tt, HTTP_METHODS as u, configArg as ut, composeFunctionTreeshakeOptions as v, orderArg as vt, getDistDir as w, resolveMachineUserInputSource as wt, getPluginGenerationDependencies as x, paginationArgs as xt, createLogLevelTreeshakeOptions as y, organizationArgs as yt, platformConfigFromProfile as z };
6497
+ //# sourceMappingURL=application-Bf8wxOi6.mjs.map