@tailor-platform/sdk 2.0.0-next.4 → 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 (258) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/dist/{application-BX13RArL.mjs → application-Bf8wxOi6.mjs} +417 -589
  3. package/dist/application-Bf8wxOi6.mjs.map +1 -0
  4. package/dist/application-CUkjzfij.mjs +3 -0
  5. package/dist/cli/cache/bundle-cache.d.mts +2 -1
  6. package/dist/cli/cache/store.d.mts +1 -1
  7. package/dist/cli/commands/api/index.d.mts +1 -0
  8. package/dist/cli/commands/deploy/aigateway.d.mts +5 -1
  9. package/dist/cli/commands/deploy/application.d.mts +7 -1
  10. package/dist/cli/commands/deploy/apply-phases.d.mts +14 -1
  11. package/dist/cli/commands/deploy/auth.d.mts +5 -1
  12. package/dist/cli/commands/deploy/deploy.d.mts +5 -0
  13. package/dist/cli/commands/deploy/executor.d.mts +7 -1
  14. package/dist/cli/commands/deploy/function-registry.d.mts +5 -0
  15. package/dist/cli/commands/deploy/idp.d.mts +5 -1
  16. package/dist/cli/commands/deploy/resolver.d.mts +5 -1
  17. package/dist/cli/commands/deploy/secret-manager.d.mts +5 -1
  18. package/dist/cli/commands/deploy/staticwebsite.d.mts +5 -1
  19. package/dist/cli/commands/deploy/tailordb/index.d.mts +8 -1
  20. package/dist/cli/commands/deploy/types.d.mts +3 -1
  21. package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +3 -1
  22. package/dist/cli/commands/deploy/workflow.d.mts +4 -1
  23. package/dist/cli/commands/executor/get.d.mts +0 -1
  24. package/dist/cli/commands/executor/jobs.d.mts +0 -1
  25. package/dist/cli/commands/executor/list.d.mts +0 -1
  26. package/dist/cli/commands/executor/transform.d.mts +1 -0
  27. package/dist/cli/commands/executor/trigger.d.mts +0 -1
  28. package/dist/cli/commands/executor/webhook.d.mts +0 -1
  29. package/dist/cli/commands/function/get.d.mts +0 -1
  30. package/dist/cli/commands/function/list.d.mts +0 -1
  31. package/dist/cli/commands/function/transform.d.mts +1 -0
  32. package/dist/cli/commands/generate/service.d.mts +5 -1
  33. package/dist/cli/commands/machineuser/list.d.mts +0 -1
  34. package/dist/cli/commands/machineuser/token.d.mts +0 -1
  35. package/dist/cli/commands/oauth2client/get.d.mts +0 -1
  36. package/dist/cli/commands/oauth2client/list.d.mts +0 -1
  37. package/dist/cli/commands/oauth2client/transform.d.mts +1 -0
  38. package/dist/cli/commands/organization/folder/create.d.mts +0 -1
  39. package/dist/cli/commands/organization/folder/delete.d.mts +0 -1
  40. package/dist/cli/commands/organization/folder/get.d.mts +0 -1
  41. package/dist/cli/commands/organization/folder/list.d.mts +0 -1
  42. package/dist/cli/commands/organization/folder/update.d.mts +0 -1
  43. package/dist/cli/commands/organization/get.d.mts +0 -1
  44. package/dist/cli/commands/organization/list.d.mts +0 -1
  45. package/dist/cli/commands/organization/transform.d.mts +2 -0
  46. package/dist/cli/commands/organization/tree.d.mts +0 -1
  47. package/dist/cli/commands/organization/update.d.mts +0 -1
  48. package/dist/cli/commands/remove.d.mts +0 -1
  49. package/dist/cli/commands/show.d.mts +9 -4
  50. package/dist/cli/commands/tailordb/migrate/config.d.mts +0 -1
  51. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +16 -3
  52. package/dist/cli/commands/tailordb/migrate/generate.d.mts +0 -1
  53. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +6 -0
  54. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -1
  55. package/dist/cli/commands/tailordb/truncate.d.mts +0 -1
  56. package/dist/cli/commands/workflow/executions.d.mts +0 -1
  57. package/dist/cli/commands/workflow/get.d.mts +2 -1
  58. package/dist/cli/commands/workflow/list.d.mts +0 -1
  59. package/dist/cli/commands/workflow/resume.d.mts +0 -1
  60. package/dist/cli/commands/workflow/start.d.mts +0 -1
  61. package/dist/cli/commands/workflow/status.d.mts +1 -0
  62. package/dist/cli/commands/workflow/transform.d.mts +1 -0
  63. package/dist/cli/commands/workflow/wait.d.mts +0 -1
  64. package/dist/cli/commands/workflow/waiter.d.mts +1 -1
  65. package/dist/cli/commands/workspace/app/health.d.mts +0 -1
  66. package/dist/cli/commands/workspace/app/list.d.mts +0 -1
  67. package/dist/cli/commands/workspace/app/transform.d.mts +2 -0
  68. package/dist/cli/commands/workspace/create.d.mts +0 -1
  69. package/dist/cli/commands/workspace/delete.d.mts +0 -1
  70. package/dist/cli/commands/workspace/get.d.mts +0 -1
  71. package/dist/cli/commands/workspace/list.d.mts +0 -1
  72. package/dist/cli/commands/workspace/restore.d.mts +0 -1
  73. package/dist/cli/commands/workspace/transform.d.mts +2 -0
  74. package/dist/cli/commands/workspace/user/invite.d.mts +0 -1
  75. package/dist/cli/commands/workspace/user/list.d.mts +0 -1
  76. package/dist/cli/commands/workspace/user/remove.d.mts +0 -1
  77. package/dist/cli/commands/workspace/user/transform.d.mts +1 -0
  78. package/dist/cli/commands/workspace/user/update.d.mts +0 -1
  79. package/dist/cli/index.d.mts +6 -3
  80. package/dist/cli/index.mjs +142 -73
  81. package/dist/cli/index.mjs.map +1 -1
  82. package/dist/cli/lib.d.mts +4 -2
  83. package/dist/cli/lib.mjs +3 -3
  84. package/dist/cli/lib.mjs.map +1 -1
  85. package/dist/cli/query/index.d.mts +0 -1
  86. package/dist/cli/services/application.d.mts +12 -1
  87. package/dist/cli/services/auth/service.d.mts +2 -0
  88. package/dist/cli/services/executor/service.d.mts +1 -1
  89. package/dist/cli/services/http-adapter/bundler.d.mts +3 -1
  90. package/dist/cli/services/http-adapter/service.d.mts +2 -1
  91. package/dist/cli/services/resolver/service.d.mts +1 -1
  92. package/dist/cli/services/tailordb/service.d.mts +3 -1
  93. package/dist/cli/services/workflow/bundler.d.mts +2 -1
  94. package/dist/cli/services/workflow/service.d.mts +1 -1
  95. package/dist/cli/shared/args.d.mts +1 -1
  96. package/dist/cli/shared/client.d.mts +1 -1
  97. package/dist/cli/shared/config-loader.d.mts +0 -1
  98. package/dist/cli/shared/context.d.mts +2 -1
  99. package/dist/cli/shared/script-executor.d.mts +0 -1
  100. package/dist/cli/shared/seed-chunker.d.mts +7 -3
  101. package/dist/cli/shared/type-generator.d.mts +0 -1
  102. package/dist/completion/zsh-worker.zsh +1 -1
  103. package/dist/configure/config/index.d.mts +0 -1
  104. package/dist/configure/config/types.d.mts +2 -2
  105. package/dist/configure/index.d.mts +14 -4
  106. package/dist/configure/index.mjs +196 -2
  107. package/dist/configure/index.mjs.map +1 -1
  108. package/dist/configure/services/aigateway/index.d.mts +0 -1
  109. package/dist/configure/services/aigateway/types.d.mts +0 -1
  110. package/dist/configure/services/auth/index.d.mts +0 -1
  111. package/dist/configure/services/auth/types.d.mts +15 -14
  112. package/dist/configure/services/executor/executor.d.mts +1 -1
  113. package/dist/configure/services/executor/index.d.mts +1 -0
  114. package/dist/configure/services/executor/operation.d.mts +2 -2
  115. package/dist/configure/services/executor/trigger/event.d.mts +0 -1
  116. package/dist/configure/services/executor/trigger/index.d.mts +0 -1
  117. package/dist/configure/services/executor/trigger/schedule.d.mts +0 -1
  118. package/dist/configure/services/executor/trigger/webhook.d.mts +0 -1
  119. package/dist/configure/services/http-adapter/http-adapter.d.mts +1 -2
  120. package/dist/configure/services/idp/index.d.mts +1 -5
  121. package/dist/configure/services/idp/permission.d.mts +4 -5
  122. package/dist/configure/services/idp/types.d.mts +0 -1
  123. package/dist/configure/services/index.d.mts +5 -0
  124. package/dist/configure/services/resolver/resolver.d.mts +1 -0
  125. package/dist/configure/services/resolver/types.d.mts +0 -1
  126. package/dist/configure/services/secrets/index.d.mts +0 -1
  127. package/dist/configure/services/secrets/types.d.mts +0 -1
  128. package/dist/configure/services/staticwebsite/index.d.mts +0 -1
  129. package/dist/configure/services/staticwebsite/types.d.mts +0 -1
  130. package/dist/configure/services/tailordb/permission.d.mts +4 -5
  131. package/dist/configure/services/tailordb/schema.d.mts +85 -49
  132. package/dist/configure/services/tailordb/types.d.mts +66 -17
  133. package/dist/configure/services/workflow/execution-policy.d.mts +0 -1
  134. package/dist/configure/services/workflow/execution-policy.types.d.mts +0 -1
  135. package/dist/configure/services/workflow/index.d.mts +1 -0
  136. package/dist/configure/services/workflow/job.d.mts +0 -1
  137. package/dist/configure/services/workflow/wait-point.d.mts +0 -1
  138. package/dist/configure/services/workflow/workflow.d.mts +1 -1
  139. package/dist/configure/types/field-runtime.d.mts +0 -1
  140. package/dist/configure/types/field.d.mts +1 -2
  141. package/dist/configure/types/field.types.d.mts +6 -45
  142. package/dist/configure/types/index.d.mts +1 -0
  143. package/dist/configure/types/type.d.mts +1 -2
  144. package/dist/kysely/index.d.mts +3 -4
  145. package/dist/{kysely-type-D-zflMGf.mjs → kysely-type-DqIRgDYR.mjs} +4 -3
  146. package/dist/kysely-type-DqIRgDYR.mjs.map +1 -0
  147. package/dist/parser/service/auth/index.d.mts +1 -1
  148. package/dist/parser/service/auth/schema.d.mts +2 -0
  149. package/dist/parser/service/http-adapter/index.d.mts +1 -1
  150. package/dist/parser/service/idp/types.d.mts +1 -0
  151. package/dist/parser/service/tailordb/types.d.mts +6 -1
  152. package/dist/plugin/builtin/enum-constants/index.d.mts +0 -1
  153. package/dist/plugin/builtin/file-utils/index.d.mts +0 -1
  154. package/dist/plugin/builtin/kysely-type/index.d.mts +0 -1
  155. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  156. package/dist/plugin/builtin/seed/index.d.mts +0 -1
  157. package/dist/plugin/get-generated-type.d.mts +0 -1
  158. package/dist/plugin/manager.d.mts +2 -1
  159. package/dist/plugin/types.d.mts +0 -1
  160. package/dist/plugin/with-context.d.mts +0 -1
  161. package/dist/{register-ts-hook-BM1caLT0.mjs → register-ts-hook-BhzVkej0.mjs} +553 -199
  162. package/dist/register-ts-hook-BhzVkej0.mjs.map +1 -0
  163. package/dist/runtime/aigateway.d.mts +0 -1
  164. package/dist/runtime/authconnection.d.mts +0 -1
  165. package/dist/runtime/context.d.mts +0 -1
  166. package/dist/runtime/globals.d.mts +0 -1
  167. package/dist/runtime/index.d.mts +0 -1
  168. package/dist/runtime/types.d.mts +9 -4
  169. package/dist/{schema-C4LYbXVG.mjs → schema-iCd1ugGp.mjs} +253 -50
  170. package/dist/schema-iCd1ugGp.mjs.map +1 -0
  171. package/dist/seed/index.d.mts +3 -2
  172. package/dist/service-BT0GPd01.mjs +3 -0
  173. package/dist/{service-ufH7sS8o.mjs → service-CzZEVrp9.mjs} +14 -9
  174. package/dist/service-CzZEVrp9.mjs.map +1 -0
  175. package/dist/{service_pb-B5w9rjPY.mjs → service_pb-Bk7dL-yT.mjs} +12 -2
  176. package/dist/{service_pb-B5w9rjPY.mjs.map → service_pb-Bk7dL-yT.mjs.map} +1 -1
  177. package/dist/{service_pb-B2FF59sP.mjs → service_pb-DZkfjB_6.mjs} +1 -1
  178. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +0 -1
  179. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +0 -1
  180. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +0 -1
  181. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +0 -1
  182. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +0 -1
  183. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +0 -1
  184. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +0 -1
  185. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +0 -1
  186. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +0 -1
  187. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +0 -1
  188. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +0 -1
  189. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +0 -1
  190. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +0 -1
  191. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +0 -1
  192. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +0 -1
  193. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +0 -1
  194. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +0 -1
  195. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +0 -1
  196. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +0 -1
  197. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +0 -1
  198. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +0 -1
  199. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +0 -1
  200. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +0 -1
  201. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +0 -1
  202. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +0 -1
  203. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +0 -1
  204. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +0 -1
  205. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +0 -1
  206. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +0 -1
  207. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +0 -1
  208. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +0 -1
  209. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +0 -1
  210. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +0 -1
  211. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +0 -1
  212. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +0 -1
  213. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +0 -1
  214. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +0 -1
  215. package/dist/types/aigateway.generated.d.mts +5 -2
  216. package/dist/types/auth-connection.generated.d.mts +24 -11
  217. package/dist/types/auth.generated.d.mts +115 -84
  218. package/dist/types/executor.generated.d.mts +76 -84
  219. package/dist/types/helpers.d.mts +7 -6
  220. package/dist/types/http-adapter.generated.d.mts +11 -5
  221. package/dist/types/idp.generated.d.mts +536 -524
  222. package/dist/types/resolver.generated.d.mts +26 -11
  223. package/dist/types/staticwebsite.generated.d.mts +7 -3
  224. package/dist/types/tailordb.generated.d.mts +57 -29
  225. package/dist/types/workflow.generated.d.mts +9 -4
  226. package/dist/utils/test/index.d.mts +1 -2
  227. package/dist/utils/test/index.mjs +36 -10
  228. package/dist/utils/test/index.mjs.map +1 -1
  229. package/dist/utils/test/mock.d.mts +0 -1
  230. package/dist/vitest/index.d.mts +1 -1
  231. package/dist/vitest/mock-kysely.d.mts +0 -1
  232. package/dist/vitest/mocks/aigateway.d.mts +2 -2
  233. package/dist/vitest/mocks/authconnection.d.mts +2 -2
  234. package/dist/vitest/mocks/idp.d.mts +2 -2
  235. package/dist/vitest/mocks/secretmanager.d.mts +3 -1
  236. package/dist/vitest/mocks/tailordb.d.mts +6 -3
  237. package/dist/vitest/mocks/workflow.d.mts +11 -6
  238. package/dist/vitest/workflow-local.d.mts +1 -0
  239. package/docs/cli/setup.md +1 -1
  240. package/docs/cli-reference.md +7 -6
  241. package/docs/migration/v2.md +206 -0
  242. package/docs/services/aigateway.md +2 -0
  243. package/docs/services/tailordb.md +100 -68
  244. package/docs/services/workflow.md +1 -1
  245. package/package.json +22 -22
  246. package/dist/application-BO4ZF8wP.mjs +0 -3
  247. package/dist/application-BX13RArL.mjs.map +0 -1
  248. package/dist/cli/shared/trigger-context.d.mts +0 -1
  249. package/dist/field-runtime-CAnh_oow.mjs +0 -183
  250. package/dist/field-runtime-CAnh_oow.mjs.map +0 -1
  251. package/dist/kysely-type-D-zflMGf.mjs.map +0 -1
  252. package/dist/register-ts-hook-BM1caLT0.mjs.map +0 -1
  253. package/dist/schema-C4LYbXVG.mjs.map +0 -1
  254. package/dist/service-CkIwEctX.mjs +0 -3
  255. package/dist/service-ufH7sS8o.mjs.map +0 -1
  256. package/dist/types-C-lQ4se3.mjs +0 -4
  257. package/dist/types-CXF2OYdR.mjs +0 -199
  258. package/dist/types-CXF2OYdR.mjs.map +0 -1
@@ -2,7 +2,7 @@ import { n as isSdkBranded } from "./brand-Eo4pLXPJ.mjs";
2
2
  import { i as PageDirection } from "./resource_pb-BRv7AMXK.mjs";
3
3
  import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
4
4
  import { a as parseBoolean, n as logger, r as styles } from "./logger-BEiZZ3qT.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-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";
6
6
  import { t as multiline } from "./multiline-sfHpTZZK.mjs";
7
7
  import { t as readPackageJson } from "./package-json-8b0O9TlX.mjs";
8
8
  import { i as userAgent, n as tightenSecretFilePermissions, r as writeSecretFile } from "./secret-file-aoNXJmKa.mjs";
@@ -498,7 +498,7 @@ function initOAuth2Client(config) {
498
498
  */
499
499
  async function initOperatorClient(accessToken, config) {
500
500
  const platformConfig = config ?? getPlatformConfigForToken(accessToken);
501
- const [{ createTracingInterceptor }, { OperatorService }] = await Promise.all([import("./interceptor-e33JtsC-.mjs"), import("./service_pb-B2FF59sP.mjs")]);
501
+ const [{ createTracingInterceptor }, { OperatorService }] = await Promise.all([import("./interceptor-e33JtsC-.mjs"), import("./service_pb-DZkfjB_6.mjs")]);
502
502
  const interceptors = [
503
503
  await userAgentInterceptor(),
504
504
  await bearerTokenInterceptor(accessToken),
@@ -2526,100 +2526,20 @@ async function removeStaleEntryFiles(outputDir) {
2526
2526
  await Promise.all(files.filter((file) => file.endsWith(".entry.js")).map((file) => fs.rm(path.join(outputDir, file), { force: true })));
2527
2527
  }
2528
2528
 
2529
- //#endregion
2530
- //#region src/cli/shared/bundle-log-level.ts
2531
- const INFO_LEVEL_CONSOLE_METHODS = [
2532
- "console.info",
2533
- "console.table",
2534
- "console.dir",
2535
- "console.dirxml",
2536
- "console.count",
2537
- "console.countReset",
2538
- "console.time",
2539
- "console.timeLog",
2540
- "console.timeEnd",
2541
- "console.group",
2542
- "console.groupCollapsed",
2543
- "console.groupEnd",
2544
- "console.clear"
2545
- ];
2546
- const DEBUG_LEVEL_CONSOLE_METHODS = [
2547
- "console.debug",
2548
- "console.log",
2549
- "console.trace"
2550
- ];
2551
- const WARN_LEVEL_CONSOLE_METHODS = ["console.warn"];
2552
- const ERROR_LEVEL_CONSOLE_METHODS = ["console.error"];
2553
- const MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL = {
2554
- DEBUG: [],
2555
- INFO: DEBUG_LEVEL_CONSOLE_METHODS,
2556
- WARN: [...DEBUG_LEVEL_CONSOLE_METHODS, ...INFO_LEVEL_CONSOLE_METHODS],
2557
- ERROR: [
2558
- ...DEBUG_LEVEL_CONSOLE_METHODS,
2559
- ...INFO_LEVEL_CONSOLE_METHODS,
2560
- ...WARN_LEVEL_CONSOLE_METHODS
2561
- ],
2562
- SILENT: [
2563
- ...DEBUG_LEVEL_CONSOLE_METHODS,
2564
- ...INFO_LEVEL_CONSOLE_METHODS,
2565
- ...WARN_LEVEL_CONSOLE_METHODS,
2566
- ...ERROR_LEVEL_CONSOLE_METHODS
2567
- ]
2568
- };
2569
- function normalizeBundleLogLevel(value) {
2570
- const normalized = value.trim().toUpperCase();
2571
- return isLogLevel(normalized) ? normalized : void 0;
2572
- }
2573
- function resolveBundleLogLevel(configValue) {
2574
- if (configValue === void 0) return "DEBUG";
2575
- const resolved = normalizeBundleLogLevel(configValue);
2576
- if (resolved) return resolved;
2577
- throw new Error(`Invalid logLevel "${configValue}". Expected one of: ${LOG_LEVELS.join(", ")}`);
2578
- }
2579
- function manualPureFunctionsForLogLevel(logLevel) {
2580
- return MANUAL_PURE_FUNCTIONS_BY_LOG_LEVEL[logLevel];
2581
- }
2582
- function createLogLevelTreeshakeOptions(logLevel) {
2583
- const manualPureFunctions = manualPureFunctionsForLogLevel(logLevel);
2584
- return manualPureFunctions.length > 0 ? { manualPureFunctions } : {};
2585
- }
2586
-
2587
- //#endregion
2588
- //#region src/cli/shared/function-treeshake.ts
2589
- const BASE_FUNCTION_TREESHAKE_OPTIONS = {
2590
- moduleSideEffects: false,
2591
- annotations: true,
2592
- unknownGlobalSideEffects: false
2593
- };
2594
- function mergeFunctionTreeshakeOptions(fragments) {
2595
- const merged = {};
2596
- const manualPureFunctions = /* @__PURE__ */ new Set();
2597
- for (const fragment of fragments) {
2598
- Object.assign(merged, fragment);
2599
- for (const name of fragment.manualPureFunctions ?? []) manualPureFunctions.add(name);
2600
- }
2601
- if (manualPureFunctions.size > 0) merged.manualPureFunctions = [...manualPureFunctions];
2602
- else delete merged.manualPureFunctions;
2603
- return merged;
2604
- }
2605
- function composeFunctionTreeshakeOptions(fragments = []) {
2606
- return mergeFunctionTreeshakeOptions([BASE_FUNCTION_TREESHAKE_OPTIONS, ...fragments]);
2607
- }
2608
-
2609
- //#endregion
2610
- //#region src/cli/shared/platform-bundle-plugin.ts
2611
- const GATE = /(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g;
2612
- const platformBundleDefinePlugin = {
2613
- name: "tailor-platform-bundle-define",
2614
- transform(code) {
2615
- if (!code.includes("process.env.__TAILOR_PLATFORM_BUNDLE")) return null;
2616
- return { code: code.replace(GATE, "true") };
2617
- }
2618
- };
2619
-
2620
2529
  //#endregion
2621
2530
  //#region src/cli/services/workflow/ast-utils.ts
2622
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
+ /**
2623
2543
  * Check if a module source is from the Tailor SDK package (including subpaths)
2624
2544
  * @param source - Module source string
2625
2545
  * @returns True if the source is from the Tailor SDK package
@@ -2662,7 +2582,7 @@ function getTriggerCallInfo(node, sourceText) {
2662
2582
  const callee = callExpr.callee;
2663
2583
  if (callee.type !== "MemberExpression") return null;
2664
2584
  const memberExpr = callee;
2665
- 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;
2666
2586
  return {
2667
2587
  identifierName: memberExpr.object.name,
2668
2588
  callRange: {
@@ -2749,20 +2669,6 @@ function findStatementEnd(source, position) {
2749
2669
  if (i < source.length && source[i] === "\n") i++;
2750
2670
  return i;
2751
2671
  }
2752
- /**
2753
- * Resolve a relative path from a base directory
2754
- * Simple implementation that handles ./ and ../ prefixes
2755
- * @param baseDir - Base directory
2756
- * @param relativePath - Relative path to resolve
2757
- * @returns Resolved absolute path
2758
- */
2759
- function resolvePath(baseDir, relativePath) {
2760
- const parts = relativePath.replace(/\\/g, "/").split("/");
2761
- const baseParts = baseDir.replace(/\\/g, "/").split("/");
2762
- for (const part of parts) if (part === ".") {} else if (part === "..") baseParts.pop();
2763
- else baseParts.push(part);
2764
- return baseParts.join("/");
2765
- }
2766
2672
 
2767
2673
  //#endregion
2768
2674
  //#region src/cli/services/workflow/sdk-binding-collector.ts
@@ -2906,43 +2812,6 @@ function findAllJobs(program, _sourceText) {
2906
2812
  walk(program);
2907
2813
  return jobs;
2908
2814
  }
2909
- /**
2910
- * Build a map from export name to job name from detected jobs
2911
- * @param jobs - Detected job locations
2912
- * @returns Map from export name to job name
2913
- */
2914
- function buildJobNameMap(jobs) {
2915
- const map = /* @__PURE__ */ new Map();
2916
- for (const job of jobs) if (job.exportName) map.set(job.exportName, job.name);
2917
- return map;
2918
- }
2919
- /**
2920
- * Detect all .trigger() calls in the source code
2921
- * Returns information about each trigger call for transformation
2922
- * @param program - Parsed TypeScript program
2923
- * @param sourceText - Source code text
2924
- * @returns Detected trigger calls
2925
- */
2926
- function detectTriggerCalls(program, sourceText) {
2927
- const calls = [];
2928
- function walk(node) {
2929
- if (!node || typeof node !== "object") return;
2930
- const triggerCall = getTriggerCallInfo(node, sourceText);
2931
- if (triggerCall) calls.push({
2932
- identifierName: triggerCall.identifierName,
2933
- callRange: triggerCall.callRange,
2934
- argsText: triggerCall.argsText,
2935
- optionsText: triggerCall.optionsText
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);
2944
- return calls;
2945
- }
2946
2815
 
2947
2816
  //#endregion
2948
2817
  //#region src/cli/services/workflow/workflow-detector.ts
@@ -2994,51 +2863,113 @@ function findAllWorkflows(program, _sourceText) {
2994
2863
  walk(program);
2995
2864
  return workflows;
2996
2865
  }
2866
+
2867
+ //#endregion
2868
+ //#region src/cli/shared/trigger-context.ts
2997
2869
  /**
2998
- * Build a map from export name to workflow name from detected workflows
2999
- * @param workflows - Detected workflows
3000
- * @returns Map from export name to workflow name
3001
- */
3002
- function buildWorkflowNameMap(workflows) {
3003
- const map = /* @__PURE__ */ new Map();
3004
- for (const workflow of workflows) if (workflow.exportName) map.set(workflow.exportName, workflow.name);
3005
- return map;
3006
- }
3007
- /**
3008
- * Detect default imports in a source file and return a map from local name to import source
3009
- * @param program - Parsed TypeScript program
3010
- * @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
3011
2873
  */
3012
- function detectDefaultImports(program) {
3013
- const imports = /* @__PURE__ */ new Map();
3014
- function walk(node) {
3015
- if (!node || typeof node !== "object") return;
3016
- if (node.type === "ImportDeclaration") {
3017
- const importDecl = node;
3018
- const source = importDecl.source.value;
3019
- if (typeof source === "string") {
3020
- for (const specifier of importDecl.specifiers) if (specifier.type === "ImportDefaultSpecifier") {
3021
- const spec = specifier;
3022
- if (spec.local.name) imports.set(spec.local.name, source);
3023
- }
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);
3024
2898
  }
2899
+ continue;
3025
2900
  }
3026
- for (const key of Object.keys(node)) {
3027
- const child = node[key];
3028
- if (Array.isArray(child)) child.forEach((c) => walk(c));
3029
- 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);
3030
2917
  }
3031
2918
  }
3032
- walk(program);
3033
- 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 ?? "");
3034
2969
  }
3035
2970
 
3036
2971
  //#endregion
3037
2972
  //#region src/cli/services/workflow/trigger-transformer.ts
3038
- /**
3039
- * Name of the injected runtime normalizer helper. Chosen to be unique enough
3040
- * to avoid collisions with user code.
3041
- */
3042
2973
  const NORMALIZER_IDENTIFIER = "__tailor_normalizeTriggerOptions";
3043
2974
  /**
3044
2975
  * Build the source text of the injected normalizer helper.
@@ -3054,341 +2985,285 @@ const NORMALIZER_IDENTIFIER = "__tailor_normalizeTriggerOptions";
3054
2985
  function buildNormalizerHelperSource(authNamespace) {
3055
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`;
3056
2987
  }
3057
- /**
3058
- * Check if an AST binding pattern (parameter, catch clause, etc.) contains an Identifier with the given name.
3059
- * @param node - AST node to inspect
3060
- * @param name - Identifier name to look for
3061
- * @returns True if the binding pattern contains the name
3062
- */
3063
- function containsBindingName(node, name) {
3064
- if (!node || typeof node !== "object") return false;
3065
- if (node.type === "Identifier" && node.name === name) return true;
3066
- for (const key of Object.keys(node)) {
3067
- const child = node[key];
3068
- if (Array.isArray(child)) {
3069
- if (child.some((c) => containsBindingName(c, name))) return true;
3070
- } else if (child && typeof child === "object") {
3071
- if (containsBindingName(child, name)) return true;
3072
- }
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);
3073
3007
  }
3074
- return false;
3075
3008
  }
3076
- /**
3077
- * Build a map of reference counts for multiple identifiers in a single AST pass.
3078
- * Scope-aware: references inside functions or catch clauses that shadow the name
3079
- * via parameters are excluded, so only references to the original import binding
3080
- * are counted.
3081
- * Excludes import declarations and property names in non-computed member expressions.
3082
- * @param program - The parsed AST program
3083
- * @param names - Set of identifier names to count
3084
- * @returns Map from identifier name to reference count
3085
- */
3086
- function buildReferenceCountMap(program, names) {
3087
- if (names.size === 0) return /* @__PURE__ */ new Map();
3088
- const counts = /* @__PURE__ */ new Map();
3089
- const shadowDepth = /* @__PURE__ */ new Map();
3090
- for (const name of names) {
3091
- counts.set(name, 0);
3092
- shadowDepth.set(name, 0);
3093
- }
3094
- 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) {
3095
3024
  if (!node || typeof node !== "object") return;
3096
- const nodeType = node.type;
3097
- if (nodeType === "ImportDeclaration") return;
3098
- const shadowedHere = [];
3099
- if (nodeType === "FunctionDeclaration" || nodeType === "FunctionExpression" || nodeType === "ArrowFunctionExpression") {
3100
- const params = node.params;
3101
- if (params) {
3102
- for (const name of names) if (params.some((p) => containsBindingName(p, name))) {
3103
- shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);
3104
- shadowedHere.push(name);
3105
- }
3106
- }
3107
- }
3108
- if (nodeType === "CatchClause") {
3109
- const param = node.param;
3110
- if (param) {
3111
- for (const name of names) if (containsBindingName(param, name)) {
3112
- shadowDepth.set(name, (shadowDepth.get(name) ?? 0) + 1);
3113
- shadowedHere.push(name);
3114
- }
3115
- }
3116
- }
3117
- if (nodeType === "Identifier") {
3118
- const identName = node.name;
3119
- if (identName && names.has(identName) && (shadowDepth.get(identName) ?? 0) === 0) {
3120
- const isMemberProperty = parentNode && parentNode.type === "MemberExpression" && parentKey === "property" && !parentNode.computed;
3121
- const isObjectPropertyKey = parentNode && parentNode.type === "Property" && parentKey === "key" && !parentNode.shorthand && !parentNode.computed;
3122
- if (!isMemberProperty && !isObjectPropertyKey) counts.set(identName, (counts.get(identName) ?? 0) + 1);
3123
- }
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);
3124
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);
3125
3068
  for (const key of Object.keys(node)) {
3069
+ if (key === "parent") continue;
3126
3070
  const child = node[key];
3127
- if (Array.isArray(child)) child.forEach((c) => walk(c, node, key));
3128
- 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);
3129
3073
  }
3130
- for (const name of shadowedHere) shadowDepth.set(name, (shadowDepth.get(name) ?? 0) - 1);
3131
3074
  }
3132
- walk(program);
3133
- return counts;
3075
+ walk(program, /* @__PURE__ */ new Set());
3134
3076
  }
3135
- /**
3136
- * Find the text range to remove for a dead default import.
3137
- *
3138
- * - Default-only import (`import wf from "..."`): returns the full declaration range.
3139
- * - Mixed import (`import wf, { helper } from "..."`): returns the range covering
3140
- * the default specifier and trailing comma/whitespace so the result becomes
3141
- * `import { helper } from "..."`.
3142
- * @param program - The parsed AST program
3143
- * @param localName - The local name of the default import
3144
- * @param source - The source code text (used to locate the `{` in mixed imports)
3145
- * @returns Range to remove, or null if the import was not found
3146
- */
3147
- 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);
3148
3087
  for (const statement of program.body) {
3149
- if (statement.type !== "ImportDeclaration") continue;
3150
- const importDecl = statement;
3151
- const specifiers = importDecl.specifiers;
3152
- for (const spec of specifiers) {
3153
- if (spec.type !== "ImportDefaultSpecifier") continue;
3154
- const defaultSpec = spec;
3155
- if (defaultSpec.local.name !== localName) continue;
3156
- if (specifiers.length === 1) return {
3157
- start: importDecl.start,
3158
- end: importDecl.end,
3159
- isFullDeclaration: true
3160
- };
3161
- const braceIndex = source.indexOf("{", defaultSpec.end);
3162
- if (braceIndex !== -1) return {
3163
- start: defaultSpec.start,
3164
- end: braceIndex,
3165
- isFullDeclaration: false
3166
- };
3167
- 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);
3168
3101
  }
3169
3102
  }
3170
- return null;
3103
+ return targets;
3171
3104
  }
3172
- /**
3173
- * Detect .trigger() calls for known workflows and jobs
3174
- * Only detects calls where the identifier is in workflowNames or jobNames
3175
- * @param program - The parsed AST program
3176
- * @param sourceText - The source code text
3177
- * @param workflowNames - Set of known workflow identifier names
3178
- * @param jobNames - Set of known job identifier names
3179
- * @returns Detected trigger call metadata
3180
- */
3181
- function detectExtendedTriggerCalls(program, sourceText, workflowNames, jobNames) {
3105
+ function detectTriggerCallsWithTargets(program, sourceText, targets) {
3182
3106
  const calls = [];
3183
- function walk(node) {
3184
- if (!node || typeof node !== "object") return;
3107
+ walkBindingAware(program, new Set(targets.keys()), (node, shadowedNames) => {
3185
3108
  const triggerCall = getTriggerCallInfo(node, sourceText);
3186
- if (triggerCall) {
3187
- const isWorkflow = workflowNames.has(triggerCall.identifierName);
3188
- const isJob = jobNames.has(triggerCall.identifierName);
3189
- if (isWorkflow) calls.push({
3190
- kind: "workflow",
3191
- identifierName: triggerCall.identifierName,
3192
- callRange: triggerCall.callRange,
3193
- argsText: triggerCall.argsText,
3194
- optionsText: triggerCall.optionsText
3195
- });
3196
- else if (isJob) calls.push({
3197
- kind: "job",
3198
- identifierName: triggerCall.identifierName,
3199
- callRange: triggerCall.callRange,
3200
- argsText: triggerCall.argsText,
3201
- optionsText: triggerCall.optionsText
3202
- });
3203
- }
3204
- for (const key of Object.keys(node)) {
3205
- const child = node[key];
3206
- if (Array.isArray(child)) child.forEach((c) => walk(c));
3207
- else if (child && typeof child === "object") walk(child);
3208
- }
3209
- }
3210
- 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
+ });
3211
3117
  return calls;
3212
3118
  }
3213
- /**
3214
- * Transform trigger calls for resolver/executor/workflow functions
3215
- * Handles job.trigger() and workflow.trigger() calls
3216
- * @param source - The source code to transform
3217
- * @param workflowNameMap - Map from variable name to workflow name
3218
- * @param jobNameMap - Map from variable name to job name
3219
- * @param workflowFileMap - Map from file path (without extension) to workflow name for default exports
3220
- * @param currentFilePath - Path of the current file being transformed (for resolving relative imports)
3221
- * @param authNamespace - Auth service namespace used to expand string-literal `invoker` to object form
3222
- * @returns Transformed source code with trigger calls rewritten
3223
- */
3224
- 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) {
3225
3123
  const { program } = parseSync("input.ts", source);
3226
- const localWorkflowNameMap = new Map(workflowNameMap);
3227
- const workflowDefaultImportNames = /* @__PURE__ */ new Set();
3228
- if (workflowFileMap && currentFilePath) {
3229
- const defaultImports = detectDefaultImports(program);
3230
- const currentDir = currentFilePath.replace(/[/\\][^/\\]+$/, "");
3231
- for (const [localName, importSource] of defaultImports) {
3232
- if (!importSource.startsWith(".")) continue;
3233
- const resolvedPath = resolvePath(currentDir, importSource).replace(/\.(ts|mts|cts|js|mjs|cjs)$/, "");
3234
- const workflowName = workflowFileMap.get(resolvedPath);
3235
- if (workflowName) {
3236
- localWorkflowNameMap.set(localName, workflowName);
3237
- workflowDefaultImportNames.add(localName);
3238
- }
3239
- }
3240
- }
3241
- 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);
3242
3127
  const nestedTriggerCalls = [];
3243
3128
  const triggerCalls = allTriggerCalls.filter((call) => {
3244
3129
  const parent = allTriggerCalls.find((other) => other !== call && other.callRange.start <= call.callRange.start && call.callRange.end <= other.callRange.end);
3245
- if (parent) {
3246
- nestedTriggerCalls.push({
3247
- call,
3248
- parent
3249
- });
3250
- return false;
3251
- }
3252
- return true;
3130
+ if (!parent) return true;
3131
+ nestedTriggerCalls.push({
3132
+ call,
3133
+ parent
3134
+ });
3135
+ return false;
3253
3136
  });
3254
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.`);
3255
3138
  const replacements = [];
3256
3139
  let needsNormalizerHelper = false;
3257
- const transformedCallsPerIdentifier = /* @__PURE__ */ new Map();
3258
- for (const call of triggerCalls) if (call.kind === "workflow") {
3259
- const workflowName = localWorkflowNameMap.get(call.identifierName);
3260
- if (workflowName) {
3140
+ for (const call of triggerCalls) {
3141
+ let transformedCall;
3142
+ if (call.kind === "workflow") {
3261
3143
  let optionsPart = "";
3262
3144
  if (call.optionsText !== void 0) if (authNamespace) {
3263
3145
  optionsPart = `, ${NORMALIZER_IDENTIFIER}(${call.optionsText})`;
3264
3146
  needsNormalizerHelper = true;
3265
3147
  } else optionsPart = `, ${call.optionsText}`;
3266
- const transformedCall = `tailor.workflow.triggerWorkflow("${workflowName}", ${call.argsText || "undefined"}${optionsPart})`;
3267
- replacements.push({
3268
- start: call.callRange.start,
3269
- end: call.callRange.end,
3270
- text: transformedCall
3271
- });
3272
- transformedCallsPerIdentifier.set(call.identifierName, (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1);
3273
- }
3274
- } else {
3275
- const jobName = jobNameMap.get(call.identifierName);
3276
- if (jobName) {
3148
+ transformedCall = `tailor.workflow.triggerWorkflow(${JSON.stringify(call.targetName)}, ${call.argsText || "undefined"}${optionsPart})`;
3149
+ } else {
3277
3150
  const optionsPart = call.optionsText !== void 0 ? `, ${call.optionsText}` : "";
3278
- const transformedCall = `tailor.workflow.triggerJobFunction("${jobName}", ${call.argsText || "undefined"}${optionsPart})`;
3279
- replacements.push({
3280
- start: call.callRange.start,
3281
- end: call.callRange.end,
3282
- text: transformedCall
3283
- });
3284
- transformedCallsPerIdentifier.set(call.identifierName, (transformedCallsPerIdentifier.get(call.identifierName) ?? 0) + 1);
3285
- }
3286
- }
3287
- const refCounts = buildReferenceCountMap(program, workflowDefaultImportNames);
3288
- for (const localName of workflowDefaultImportNames) {
3289
- const transformedCount = transformedCallsPerIdentifier.get(localName) ?? 0;
3290
- const refCount = refCounts.get(localName) ?? 0;
3291
- if (refCount === 0 || transformedCount >= refCount) {
3292
- const removal = findDefaultImportRemovalRange(program, localName, source);
3293
- if (removal) replacements.push({
3294
- start: removal.start,
3295
- end: removal.isFullDeclaration ? findStatementEnd(source, removal.end) : removal.end,
3296
- text: ""
3297
- });
3151
+ transformedCall = `tailor.workflow.triggerJobFunction(${JSON.stringify(call.targetName)}, ${call.argsText || "undefined"}${optionsPart})`;
3298
3152
  }
3153
+ replacements.push({
3154
+ start: call.callRange.start,
3155
+ end: call.callRange.end,
3156
+ text: transformedCall
3157
+ });
3299
3158
  }
3300
3159
  const transformed = applyReplacements(source, replacements);
3301
- if (needsNormalizerHelper && authNamespace) return buildNormalizerHelperSource(authNamespace) + transformed;
3302
- return transformed;
3160
+ return needsNormalizerHelper && authNamespace ? buildNormalizerHelperSource(authNamespace) + transformed : transformed;
3303
3161
  }
3304
-
3305
- //#endregion
3306
- //#region src/cli/shared/trigger-context.ts
3307
- /**
3308
- * Normalize a file path by removing extension and resolving to absolute path
3309
- * @param filePath - File path to normalize
3310
- * @returns Normalized absolute path without extension
3311
- */
3312
- function normalizeFilePath(filePath) {
3313
- const absolutePath = path.resolve(filePath);
3314
- const ext = path.extname(absolutePath);
3315
- return absolutePath.slice(0, -ext.length);
3316
- }
3317
- /**
3318
- * Build trigger context from workflow configuration
3319
- * Scans workflow files to collect workflow and job mappings
3320
- * @param workflowConfig - Workflow file loading configuration
3321
- * @param authNamespace - Auth service namespace (optional, used for string-literal invoker expansion)
3322
- * @returns Trigger context built from workflow sources
3323
- */
3324
- async function buildTriggerContext(workflowConfig, authNamespace) {
3325
- const workflowNameMap = /* @__PURE__ */ new Map();
3326
- const jobNameMap = /* @__PURE__ */ new Map();
3327
- const workflowFileMap = /* @__PURE__ */ new Map();
3328
- if (!workflowConfig) return {
3329
- workflowNameMap,
3330
- jobNameMap,
3331
- workflowFileMap,
3332
- authNamespace
3333
- };
3334
- const workflowFiles = loadFilesWithIgnores(workflowConfig);
3335
- for (const file of workflowFiles) try {
3336
- const source = await fs$1.promises.readFile(file, "utf-8");
3337
- const { program } = parseSync("input.ts", source);
3338
- const workflows = findAllWorkflows(program, source);
3339
- const workflowMap = buildWorkflowNameMap(workflows);
3340
- for (const [exportName, workflowName] of workflowMap) workflowNameMap.set(exportName, workflowName);
3341
- for (const workflow of workflows) if (workflow.isDefaultExport) {
3342
- const normalizedPath = normalizeFilePath(file);
3343
- workflowFileMap.set(normalizedPath, workflow.name);
3344
- }
3345
- const jobMap = buildJobNameMap(findAllJobs(program, source));
3346
- for (const [exportName, jobName] of jobMap) jobNameMap.set(exportName, jobName);
3347
- } catch (error) {
3348
- const errorMessage = error instanceof Error ? error.message : String(error);
3349
- logger.warn(`Failed to process workflow file ${file}: ${errorMessage}`, { mode: "stream" });
3350
- continue;
3351
- }
3352
- return {
3353
- workflowNameMap,
3354
- jobNameMap,
3355
- workflowFileMap,
3356
- authNamespace
3357
- };
3358
- }
3359
- function sortedMapToJson(m) {
3360
- return JSON.stringify([...m.entries()].toSorted(([a], [b]) => a.localeCompare(b)));
3361
- }
3362
- /**
3363
- * Serialize trigger context to a deterministic string for cache hashing.
3364
- * Returns an empty string if no context is provided.
3365
- * @param ctx - Trigger context to serialize
3366
- * @returns Deterministic string representation
3367
- */
3368
- function serializeTriggerContext(ctx) {
3369
- if (!ctx) return "";
3370
- return sortedMapToJson(ctx.workflowNameMap) + sortedMapToJson(ctx.jobNameMap) + sortedMapToJson(ctx.workflowFileMap) + (ctx.authNamespace ?? "");
3371
- }
3372
- /**
3373
- * Create a rolldown plugin for transforming trigger calls
3374
- * Returns undefined if no trigger context is provided
3375
- * @param triggerContext - Trigger context to use for transformations
3376
- * @returns Rolldown plugin or undefined when no context
3377
- */
3378
3162
  function createTriggerTransformPlugin(triggerContext) {
3379
- if (!triggerContext) return;
3163
+ if (!triggerContext) return void 0;
3380
3164
  return {
3381
3165
  name: "trigger-transform",
3382
3166
  transform: {
3383
3167
  filter: { id: { include: [/\.(ts|mts|cts|js|mjs|cjs)$/] } },
3384
3168
  handler(code, id) {
3385
3169
  if (!code.includes(".trigger(")) return null;
3386
- return { code: transformFunctionTriggers(code, triggerContext.workflowNameMap, triggerContext.jobNameMap, triggerContext.workflowFileMap, id, triggerContext.authNamespace) };
3170
+ return { code: transformFunctionTriggers(code, triggerContext, id) };
3387
3171
  }
3388
3172
  }
3389
3173
  };
3390
3174
  }
3391
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
+
3392
3267
  //#endregion
3393
3268
  //#region src/cli/services/auth/bundler.ts
3394
3269
  /**
@@ -3624,7 +3499,17 @@ function formatScriptContext(kind, context) {
3624
3499
  const convertToScriptExpr = (fn, kind, context) => {
3625
3500
  const precompiledExpr = getPrecompiledScriptExpr(fn);
3626
3501
  if (precompiledExpr) return precompiledExpr;
3627
- 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");
3628
3513
  };
3629
3514
  /**
3630
3515
  * Parse TailorDBField into OperatorFieldConfig.
@@ -3637,6 +3522,8 @@ function parseFieldConfig(field, context) {
3637
3522
  const metadata = field.metadata;
3638
3523
  const fieldType = field.type;
3639
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`);
3640
3527
  const nestedFields = field.fields;
3641
3528
  return {
3642
3529
  type: fieldType,
@@ -3649,19 +3536,10 @@ function parseFieldConfig(field, context) {
3649
3536
  });
3650
3537
  return acc;
3651
3538
  }, {}) } : {},
3652
- validate: metadata.validate?.map((v) => {
3653
- const { fn, message } = typeof v === "function" ? {
3654
- fn: v,
3655
- message: `failed by \`${v.toString().trim()}\``
3656
- } : {
3657
- fn: v[0],
3658
- message: v[1]
3659
- };
3660
- return {
3661
- script: { expr: convertToScriptExpr(fn, "validate", context) },
3662
- errorMessage: message
3663
- };
3664
- }),
3539
+ validate: metadata.validate?.map((fn) => ({
3540
+ script: { expr: convertToScriptExpr(fn, "validate", context) },
3541
+ errorMessage: ""
3542
+ })),
3665
3543
  hooks: metadata.hooks ? {
3666
3544
  create: metadata.hooks.create ? { expr: convertToScriptExpr(metadata.hooks.create, "hooks.create", context) } : void 0,
3667
3545
  update: metadata.hooks.update ? { expr: convertToScriptExpr(metadata.hooks.update, "hooks.update", context) } : void 0
@@ -3901,7 +3779,12 @@ function parseTailorDBType(type, allTypeNames, rawTypes, typeSourceInfo) {
3901
3779
  settings: metadata.settings ?? {},
3902
3780
  permissions: parsePermissions(metadata.permissions),
3903
3781
  indexes: metadata.indexes,
3904
- 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) }
3905
3788
  };
3906
3789
  }
3907
3790
  /**
@@ -4092,29 +3975,35 @@ function collectScriptTargets(type) {
4092
3975
  const createHook = toScriptFunction(metadata.hooks?.create);
4093
3976
  if (createHook) targets.push({
4094
3977
  fn: createHook,
4095
- kind: "hooks"
3978
+ kind: "hooks.create"
4096
3979
  });
4097
3980
  const updateHook = toScriptFunction(metadata.hooks?.update);
4098
3981
  if (updateHook) targets.push({
4099
3982
  fn: updateHook,
4100
- kind: "hooks"
3983
+ kind: "hooks.update"
4101
3984
  });
4102
- for (const validateInput of metadata.validate ?? []) if (typeof validateInput === "function") {
3985
+ for (const validateInput of metadata.validate ?? []) {
4103
3986
  const validateFn = toScriptFunction(validateInput);
4104
3987
  if (validateFn) targets.push({
4105
3988
  fn: validateFn,
4106
3989
  kind: "validate"
4107
3990
  });
4108
- } else {
4109
- const validateFn = toScriptFunction(validateInput[0]);
4110
- if (validateFn) targets.push({
4111
- fn: validateFn,
4112
- kind: "validate"
4113
- });
4114
3991
  }
4115
3992
  if (field.type === "nested" && field.fields) for (const nestedField of Object.values(field.fields)) collectFieldTargets(nestedField);
4116
3993
  };
4117
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
+ });
4118
4007
  return targets;
4119
4008
  }
4120
4009
  /**
@@ -4308,11 +4197,11 @@ function resolveNeededBindings(freeVars, sourceBindings) {
4308
4197
  unresolved
4309
4198
  };
4310
4199
  }
4311
- function buildPrecompiledExpr(bundleCode) {
4200
+ function buildPrecompiledExpr(bundleCode, argsObject) {
4312
4201
  return `(() => {
4313
4202
  const module = { exports: {} };
4314
4203
  const exports = module.exports;
4315
- ${bundleCode}\n return module.exports.main({ value: _value, data: _data, invoker: ${tailorPrincipalMap} });\n})()`;
4204
+ ${bundleCode}\n return module.exports.main(${argsObject});\n})()`;
4316
4205
  }
4317
4206
  /**
4318
4207
  * Build entry file content from already-resolved imports and declarations.
@@ -4320,27 +4209,30 @@ ${bundleCode}\n return module.exports.main({ value: _value, data: _data, invoke
4320
4209
  * @param declarations - Declaration statement texts.
4321
4210
  * @param fnSource - The function source code.
4322
4211
  * @param sourceFilePath - Path to the source file for resolving relative imports.
4212
+ * @param multiArg - Whether the function accepts multiple arguments (spread via `...args`).
4323
4213
  * @returns Entry file content string.
4324
4214
  */
4325
- function buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath) {
4215
+ function buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath, multiArg = false) {
4326
4216
  const sourceDir = resolve(sourceFilePath, "..").replace(/\\/g, "/");
4327
4217
  return [
4328
4218
  ...imports.map((imp) => imp.replace(/from\s+["'](\.[^"']+)["']/g, (_match, relPath) => `from "${resolve(sourceDir, relPath).replace(/\\/g, "/")}"`)),
4329
4219
  ...declarations,
4330
- `export function main(input) { return (${fnSource})(input); }`
4220
+ multiArg ? `export function main(...args) { return (${fnSource})(...args); }` : `export function main(input) { return (${fnSource})(input); }`
4331
4221
  ].join("\n");
4332
4222
  }
4333
4223
  async function bundleScriptTarget(args) {
4334
4224
  const { fn, kind, sourceFilePath, sourceBindings, tempDir, targetIndex, tsconfig } = args;
4335
4225
  const context = `${kind} in ${sourceFilePath}`;
4336
4226
  const fnSource = stringifyFunction(fn);
4337
- 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);
4338
4230
  const freeVars = findUndefinedReferences(`const __fn = ${fnSource};`);
4339
4231
  if (freeVars.size === 0) return inlineExpr;
4340
4232
  const { imports, declarations, unresolved } = resolveNeededBindings(freeVars, sourceBindings);
4341
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.
4342
4234
  ${kind}: ${fnSource}`);
4343
- const entryContent = buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath);
4235
+ const entryContent = buildMinimalEntryFromResolved(imports, declarations, fnSource, sourceFilePath, kind === "typeValidate");
4344
4236
  const entryPath = join(tempDir, `tailordb-script-${targetIndex}.entry.ts`);
4345
4237
  writeFileSync(entryPath, entryContent);
4346
4238
  const bundledCode = (await rolldown.build({
@@ -4361,7 +4253,7 @@ async function bundleScriptTarget(args) {
4361
4253
  },
4362
4254
  logLevel: "silent"
4363
4255
  })).output[0].code;
4364
- return assertParsableExpression(buildPrecompiledExpr(bundledCode), context);
4256
+ return assertParsableExpression(buildPrecompiledExpr(bundledCode, argsObject), context);
4365
4257
  }
4366
4258
  /**
4367
4259
  * Precompile TailorDB hooks/validators into self-contained script expressions using rolldown.
@@ -5511,36 +5403,15 @@ function assertUniqueResolverNames(resolvers, namespace) {
5511
5403
  */
5512
5404
  function findVariableDeclarationsByName(program) {
5513
5405
  const declarations = /* @__PURE__ */ new Map();
5514
- function walk(node) {
5515
- if (!node || typeof node !== "object") return;
5516
- const nodeType = node.type;
5517
- if (nodeType === "VariableDeclaration") {
5518
- const varDecl = node;
5519
- for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) {
5520
- if (!declarations.has(decl.id.name)) declarations.set(decl.id.name, {
5521
- start: varDecl.start,
5522
- end: varDecl.end
5523
- });
5524
- }
5525
- }
5526
- if (nodeType === "ExportNamedDeclaration") {
5527
- const exportDecl = node;
5528
- const declaration = exportDecl.declaration;
5529
- if (declaration?.type === "VariableDeclaration") {
5530
- const varDecl = declaration;
5531
- for (const decl of varDecl.declarations) if (decl.id.type === "Identifier" && decl.id.name) declarations.set(decl.id.name, {
5532
- start: exportDecl.start,
5533
- end: exportDecl.end
5534
- });
5535
- }
5536
- }
5537
- for (const key of Object.keys(node)) {
5538
- const child = node[key];
5539
- if (Array.isArray(child)) child.forEach((c) => walk(c));
5540
- else if (child && typeof child === "object") walk(child);
5541
- }
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
+ });
5542
5414
  }
5543
- walk(program);
5544
5415
  return declarations;
5545
5416
  }
5546
5417
  /**
@@ -5567,48 +5438,32 @@ function findWorkflowDefaultExport(program) {
5567
5438
  }
5568
5439
  /**
5569
5440
  * Transform workflow source code
5570
- * - Transform .trigger() calls to tailor.workflow.triggerJobFunction()
5571
5441
  * - Other jobs: remove entire variable declaration
5572
5442
  * @param source - The source code to transform
5573
5443
  * @param targetJobName - The name of the target job (from job config)
5574
5444
  * @param targetJobExportName - The export name of the target job (optional, for enhanced detection)
5575
5445
  * @param otherJobExportNames - Export names of other jobs to remove (optional, for enhanced detection)
5576
- * @param allJobsMap - Map from export name to job name for trigger transformation (optional)
5577
5446
  * @returns Transformed workflow source code
5578
5447
  */
5579
- function transformWorkflowSource(source, targetJobName, targetJobExportName, otherJobExportNames, allJobsMap) {
5448
+ function transformWorkflowSource(source, targetJobName, targetJobExportName, otherJobExportNames) {
5580
5449
  const { program } = parseSync("input.ts", source);
5581
5450
  const detectedJobs = findAllJobs(program, source);
5582
5451
  if (!detectedJobs.some((j) => j.name === targetJobName)) return source;
5583
- const jobNameMap = allJobsMap ?? buildJobNameMap(detectedJobs);
5584
5452
  const allDeclarations = findVariableDeclarationsByName(program);
5585
- const triggerCalls = detectTriggerCalls(program, source);
5586
5453
  const replacements = [];
5587
- const removedRanges = [];
5588
- const isInsideRemovedRange = (pos) => {
5589
- return removedRanges.some((r) => pos >= r.start && pos < r.end);
5590
- };
5591
- const isAlreadyMarkedForRemoval = (start) => {
5592
- return removedRanges.some((r) => r.start === start);
5593
- };
5454
+ const removedStarts = /* @__PURE__ */ new Set();
5594
5455
  for (const job of detectedJobs) {
5595
5456
  if (job.name === targetJobName) continue;
5596
- if (job.statementRange && !isAlreadyMarkedForRemoval(job.statementRange.start)) {
5457
+ if (job.statementRange && !removedStarts.has(job.statementRange.start)) {
5597
5458
  const endPos = findStatementEnd(source, job.statementRange.end);
5598
- removedRanges.push({
5599
- start: job.statementRange.start,
5600
- end: endPos
5601
- });
5459
+ removedStarts.add(job.statementRange.start);
5602
5460
  replacements.push({
5603
5461
  start: job.statementRange.start,
5604
5462
  end: endPos,
5605
5463
  text: ""
5606
5464
  });
5607
5465
  } else if (!job.statementRange) {
5608
- removedRanges.push({
5609
- start: job.bodyValueRange.start,
5610
- end: job.bodyValueRange.end
5611
- });
5466
+ removedStarts.add(job.bodyValueRange.start);
5612
5467
  replacements.push({
5613
5468
  start: job.bodyValueRange.start,
5614
5469
  end: job.bodyValueRange.end,
@@ -5619,12 +5474,9 @@ function transformWorkflowSource(source, targetJobName, targetJobExportName, oth
5619
5474
  if (otherJobExportNames) for (const exportName of otherJobExportNames) {
5620
5475
  if (exportName === targetJobExportName) continue;
5621
5476
  const declRange = allDeclarations.get(exportName);
5622
- if (declRange && !isAlreadyMarkedForRemoval(declRange.start)) {
5477
+ if (declRange && !removedStarts.has(declRange.start)) {
5623
5478
  const endPos = findStatementEnd(source, declRange.end);
5624
- removedRanges.push({
5625
- start: declRange.start,
5626
- end: endPos
5627
- });
5479
+ removedStarts.add(declRange.start);
5628
5480
  replacements.push({
5629
5481
  start: declRange.start,
5630
5482
  end: endPos,
@@ -5633,31 +5485,15 @@ function transformWorkflowSource(source, targetJobName, targetJobExportName, oth
5633
5485
  }
5634
5486
  }
5635
5487
  const workflowExport = findWorkflowDefaultExport(program);
5636
- if (workflowExport && !isAlreadyMarkedForRemoval(workflowExport.start)) {
5488
+ if (workflowExport && !removedStarts.has(workflowExport.start)) {
5637
5489
  const endPos = findStatementEnd(source, workflowExport.end);
5638
- removedRanges.push({
5639
- start: workflowExport.start,
5640
- end: endPos
5641
- });
5490
+ removedStarts.add(workflowExport.start);
5642
5491
  replacements.push({
5643
5492
  start: workflowExport.start,
5644
5493
  end: endPos,
5645
5494
  text: ""
5646
5495
  });
5647
5496
  }
5648
- for (const call of triggerCalls) {
5649
- if (isInsideRemovedRange(call.callRange.start)) continue;
5650
- const jobName = jobNameMap.get(call.identifierName);
5651
- if (jobName) {
5652
- const optionsPart = call.optionsText !== void 0 ? `, ${call.optionsText}` : "";
5653
- const transformedCall = `tailor.workflow.triggerJobFunction("${jobName}", ${call.argsText || "undefined"}${optionsPart})`;
5654
- replacements.push({
5655
- start: call.callRange.start,
5656
- end: call.callRange.end,
5657
- text: transformedCall
5658
- });
5659
- }
5660
- }
5661
5497
  return applyReplacements(source, replacements);
5662
5498
  }
5663
5499
 
@@ -5699,7 +5535,7 @@ async function bundleWorkflowJobs(allJobs, mainJobNames, env = {}, triggerContex
5699
5535
  bundledCode: /* @__PURE__ */ new Map()
5700
5536
  };
5701
5537
  }
5702
- const { usedJobs, mainJobDeps } = await filterUsedJobs(allJobs, mainJobNames);
5538
+ const { usedJobs, mainJobDeps } = await filterUsedJobs(allJobs, mainJobNames, triggerContext);
5703
5539
  logger.newline();
5704
5540
  logger.log(`Bundling ${styles.highlight(usedJobs.length.toString())} files for ${styles.info("\"workflow-job\"")}`);
5705
5541
  const outputDir = path.resolve(getDistDir(), "workflow-jobs");
@@ -5733,9 +5569,10 @@ async function bundleWorkflowJobs(allJobs, mainJobNames, env = {}, triggerContex
5733
5569
  * Also returns a map of mainJob -> all jobs it depends on (for metadata).
5734
5570
  * @param allJobs - All available job infos
5735
5571
  * @param mainJobNames - Names of main jobs
5572
+ * @param triggerContext - Module binding metadata for resolving trigger targets
5736
5573
  * @returns Used jobs and main job dependency map
5737
5574
  */
5738
- async function filterUsedJobs(allJobs, mainJobNames) {
5575
+ async function filterUsedJobs(allJobs, mainJobNames, triggerContext) {
5739
5576
  if (allJobs.length === 0 || mainJobNames.length === 0) return {
5740
5577
  usedJobs: [],
5741
5578
  mainJobDeps: {}
@@ -5746,26 +5583,19 @@ async function filterUsedJobs(allJobs, mainJobNames) {
5746
5583
  existing.push(job);
5747
5584
  jobsBySourceFile.set(job.sourceFile, existing);
5748
5585
  }
5749
- const exportNameToJobName = /* @__PURE__ */ new Map();
5750
- for (const job of allJobs) exportNameToJobName.set(job.exportName, job.name);
5751
5586
  const dependencies = /* @__PURE__ */ new Map();
5752
5587
  const fileResults = await Promise.all(Array.from(jobsBySourceFile.entries()).map(async ([sourceFile, jobs]) => {
5753
5588
  try {
5754
5589
  const source = await fs$1.promises.readFile(sourceFile, "utf-8");
5755
5590
  const { program } = parseSync("input.ts", source);
5756
5591
  const detectedJobs = findAllJobs(program, source);
5757
- const localExportNameToJobName = /* @__PURE__ */ new Map();
5758
- for (const detected of detectedJobs) if (detected.exportName) localExportNameToJobName.set(detected.exportName, detected.name);
5759
- const triggerCalls = detectTriggerCalls(program, source);
5592
+ const triggerCalls = detectResolvedTriggerCalls(program, source, triggerContext, sourceFile);
5760
5593
  const jobDependencies = [];
5761
5594
  for (const job of jobs) {
5762
5595
  const detectedJob = detectedJobs.find((d) => d.name === job.name);
5763
5596
  if (!detectedJob) continue;
5764
5597
  const jobDeps = /* @__PURE__ */ new Set();
5765
- for (const call of triggerCalls) if (call.callRange.start >= detectedJob.bodyValueRange.start && call.callRange.end <= detectedJob.bodyValueRange.end) {
5766
- const triggeredJobName = localExportNameToJobName.get(call.identifierName) || exportNameToJobName.get(call.identifierName);
5767
- if (triggeredJobName) jobDeps.add(triggeredJobName);
5768
- }
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);
5769
5599
  if (jobDeps.size > 0) jobDependencies.push({
5770
5600
  jobName: job.name,
5771
5601
  deps: jobDeps
@@ -5826,10 +5656,8 @@ async function bundleSingleJob(job, allJobs, outputDir, tsconfig, env, triggerCo
5826
5656
  }
5827
5657
  `;
5828
5658
  fs$1.writeFileSync(entryPath, entryContent);
5829
- const otherJobExportNames = allJobs.filter((j) => j.name !== job.name).map((j) => j.exportName);
5830
- const allJobsMap = /* @__PURE__ */ new Map();
5831
- for (const j of allJobs) allJobsMap.set(j.exportName, j.name);
5832
5659
  const resolvedSourceFile = safeRealpath(job.sourceFile);
5660
+ const otherJobExportNames = allJobs.filter((candidate) => candidate.name !== job.name && safeRealpath(candidate.sourceFile) === resolvedSourceFile).map((j) => j.exportName);
5833
5661
  const plugins = [
5834
5662
  {
5835
5663
  name: "workflow-transform",
@@ -5838,8 +5666,8 @@ async function bundleSingleJob(job, allJobs, outputDir, tsconfig, env, triggerCo
5838
5666
  handler(code, id) {
5839
5667
  if (!code.includes("createWorkflowJob") && !code.includes("createWorkflow") && !code.includes(".trigger(")) return null;
5840
5668
  let transformed = code;
5841
- if (safeRealpath(id) === resolvedSourceFile) transformed = transformWorkflowSource(code, job.name, job.exportName, otherJobExportNames, allJobsMap);
5842
- 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);
5843
5671
  if (transformed === code) return null;
5844
5672
  return { code: transformed };
5845
5673
  }
@@ -6666,4 +6494,4 @@ async function loadApplication(params) {
6666
6494
 
6667
6495
  //#endregion
6668
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 };
6669
- //# sourceMappingURL=application-BX13RArL.mjs.map
6497
+ //# sourceMappingURL=application-Bf8wxOi6.mjs.map