@tailor-platform/sdk 2.14.0 → 2.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/application-BWOMdL3D.mjs +1 -0
  3. package/dist/{application-CiN_er9X.mjs → application-CfevPO-k.mjs} +8 -8
  4. package/dist/application-CfevPO-k.mjs.map +1 -0
  5. package/dist/cli/commands/api/api-call.d.mts +4 -5
  6. package/dist/cli/commands/deploy/config-id-injector.d.mts +3 -4
  7. package/dist/cli/commands/deploy/deploy.d.mts +3 -4
  8. package/dist/cli/commands/deploy/function-registry-types.d.mts +2 -3
  9. package/dist/cli/commands/executor/get.d.mts +3 -4
  10. package/dist/cli/commands/executor/jobs.d.mts +10 -11
  11. package/dist/cli/commands/executor/list.d.mts +3 -4
  12. package/dist/cli/commands/executor/transform.d.mts +6 -7
  13. package/dist/cli/commands/executor/trigger.d.mts +4 -5
  14. package/dist/cli/commands/executor/webhook.d.mts +4 -5
  15. package/dist/cli/commands/function/get.d.mts +3 -4
  16. package/dist/cli/commands/function/list.d.mts +3 -4
  17. package/dist/cli/commands/function/transform.d.mts +2 -3
  18. package/dist/cli/commands/generate/options.d.mts +2 -3
  19. package/dist/cli/commands/generate/seed/bundler.d.mts +3 -4
  20. package/dist/cli/commands/generate/service.d.mts +2 -3
  21. package/dist/cli/commands/machineuser/list.d.mts +4 -5
  22. package/dist/cli/commands/machineuser/token.d.mts +4 -5
  23. package/dist/cli/commands/oauth2client/get.d.mts +3 -4
  24. package/dist/cli/commands/oauth2client/list.d.mts +3 -4
  25. package/dist/cli/commands/oauth2client/transform.d.mts +3 -4
  26. package/dist/cli/commands/organization/folder/create.d.mts +3 -4
  27. package/dist/cli/commands/organization/folder/delete.d.mts +3 -4
  28. package/dist/cli/commands/organization/folder/get.d.mts +3 -4
  29. package/dist/cli/commands/organization/folder/list.d.mts +3 -4
  30. package/dist/cli/commands/organization/folder/update.d.mts +3 -4
  31. package/dist/cli/commands/organization/get.d.mts +3 -4
  32. package/dist/cli/commands/organization/list.d.mts +3 -4
  33. package/dist/cli/commands/organization/transform.d.mts +5 -6
  34. package/dist/cli/commands/organization/tree.d.mts +3 -4
  35. package/dist/cli/commands/organization/update.d.mts +3 -4
  36. package/dist/cli/commands/remove.d.mts +3 -4
  37. package/dist/cli/commands/show.d.mts +6 -7
  38. package/dist/cli/commands/staticwebsite/deploy.d.mts +3 -4
  39. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +3 -4
  40. package/dist/cli/commands/tailordb/migrate/config.d.mts +3 -4
  41. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +34 -35
  42. package/dist/cli/commands/tailordb/migrate/generate.d.mts +3 -4
  43. package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +3 -4
  44. package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +4 -5
  45. package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +13 -14
  46. package/dist/cli/commands/tailordb/migrate/snapshot-local.d.mts +2 -3
  47. package/dist/cli/commands/tailordb/migrate/snapshot-migrations.d.mts +2 -3
  48. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +21 -22
  49. package/dist/cli/commands/tailordb/migrate/types.d.mts +2 -3
  50. package/dist/cli/commands/tailordb/truncate.d.mts +3 -4
  51. package/dist/cli/commands/workflow/executions.d.mts +8 -9
  52. package/dist/cli/commands/workflow/get.d.mts +3 -4
  53. package/dist/cli/commands/workflow/list.d.mts +3 -4
  54. package/dist/cli/commands/workflow/resume.d.mts +4 -5
  55. package/dist/cli/commands/workflow/start.d.mts +5 -6
  56. package/dist/cli/commands/workflow/status.d.mts +3 -4
  57. package/dist/cli/commands/workflow/transform.d.mts +5 -6
  58. package/dist/cli/commands/workflow/wait.d.mts +3 -4
  59. package/dist/cli/commands/workflow/waiter.d.mts +3 -4
  60. package/dist/cli/commands/workspace/app/health.d.mts +3 -4
  61. package/dist/cli/commands/workspace/app/list.d.mts +3 -4
  62. package/dist/cli/commands/workspace/app/transform.d.mts +3 -4
  63. package/dist/cli/commands/workspace/create.d.mts +3 -4
  64. package/dist/cli/commands/workspace/delete.d.mts +3 -4
  65. package/dist/cli/commands/workspace/get.d.mts +3 -4
  66. package/dist/cli/commands/workspace/list.d.mts +3 -4
  67. package/dist/cli/commands/workspace/restore.d.mts +3 -4
  68. package/dist/cli/commands/workspace/transform.d.mts +3 -4
  69. package/dist/cli/commands/workspace/user/invite.d.mts +3 -4
  70. package/dist/cli/commands/workspace/user/list.d.mts +3 -4
  71. package/dist/cli/commands/workspace/user/remove.d.mts +3 -4
  72. package/dist/cli/commands/workspace/user/transform.d.mts +2 -3
  73. package/dist/cli/commands/workspace/user/update.d.mts +3 -4
  74. package/dist/cli/lib.mjs +1 -1
  75. package/dist/cli/main.d.mts +2 -3
  76. package/dist/cli/main.mjs +18 -18
  77. package/dist/cli/main.mjs.map +1 -1
  78. package/dist/cli/query/index.d.mts +2 -3
  79. package/dist/cli/shared/args.d.mts +11 -12
  80. package/dist/cli/shared/beta.d.mts +2 -3
  81. package/dist/cli/shared/client.d.mts +4 -5
  82. package/dist/cli/shared/command.d.mts +2 -3
  83. package/dist/cli/shared/config-loader.d.mts +5 -6
  84. package/dist/cli/shared/config.d.mts +2 -3
  85. package/dist/cli/shared/context.d.mts +3 -4
  86. package/dist/cli/shared/error-json.d.mts +4 -5
  87. package/dist/cli/shared/logger.d.mts +7 -8
  88. package/dist/cli/shared/prompt.d.mts +7 -8
  89. package/dist/cli/shared/readonly-guard.d.mts +2 -3
  90. package/dist/cli/shared/script-executor.d.mts +7 -8
  91. package/dist/cli/shared/seed-chunker.d.mts +5 -6
  92. package/dist/cli/shared/seed-context.d.mts +5 -5
  93. package/dist/cli/shared/tailordb-namespaces.d.mts +5 -6
  94. package/dist/cli/shared/type-generator.d.mts +2 -3
  95. package/dist/cli/shared/workspace-name.d.mts +2 -3
  96. package/dist/completion/zsh-worker.zsh +1 -1
  97. package/dist/configure/config/index.d.mts +3 -4
  98. package/dist/configure/config/types.d.mts +14 -15
  99. package/dist/configure/index.d.mts +6 -6
  100. package/dist/configure/services/aigateway/index.d.mts +2 -2
  101. package/dist/configure/services/aigateway/types.d.mts +4 -5
  102. package/dist/configure/services/auth/index.d.mts +3 -3
  103. package/dist/configure/services/auth/types.d.mts +24 -25
  104. package/dist/configure/services/executor/executor.d.mts +3 -4
  105. package/dist/configure/services/executor/operation.d.mts +6 -7
  106. package/dist/configure/services/executor/trigger/event.d.mts +56 -57
  107. package/dist/configure/services/executor/trigger/index.d.mts +2 -2
  108. package/dist/configure/services/executor/trigger/schedule.d.mts +4 -5
  109. package/dist/configure/services/executor/trigger/webhook.d.mts +8 -9
  110. package/dist/configure/services/http-adapter/http-adapter.d.mts +12 -13
  111. package/dist/configure/services/idp/index.d.mts +2 -2
  112. package/dist/configure/services/idp/permission.d.mts +4 -5
  113. package/dist/configure/services/idp/types.d.mts +5 -6
  114. package/dist/configure/services/resolver/permission.d.mts +4 -5
  115. package/dist/configure/services/resolver/resolver.d.mts +3 -4
  116. package/dist/configure/services/resolver/types.d.mts +2 -3
  117. package/dist/configure/services/secrets/index.d.mts +3 -3
  118. package/dist/configure/services/secrets/types.d.mts +3 -4
  119. package/dist/configure/services/staticwebsite/index.d.mts +2 -2
  120. package/dist/configure/services/staticwebsite/types.d.mts +3 -4
  121. package/dist/configure/services/tailordb/permission.d.mts +6 -7
  122. package/dist/configure/services/tailordb/schema.d.mts +7 -8
  123. package/dist/configure/services/tailordb/types.d.mts +25 -26
  124. package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
  125. package/dist/configure/services/workflow/execution-policy.types.d.mts +8 -9
  126. package/dist/configure/services/workflow/job.d.mts +4 -5
  127. package/dist/configure/services/workflow/wait-point.d.mts +5 -6
  128. package/dist/configure/services/workflow/workflow.d.mts +4 -4
  129. package/dist/configure/types/aigateway-name.d.mts +3 -4
  130. package/dist/configure/types/auth-namespace-name.d.mts +3 -4
  131. package/dist/configure/types/connection-name.d.mts +3 -4
  132. package/dist/configure/types/field.d.mts +3 -4
  133. package/dist/configure/types/field.types.d.mts +13 -14
  134. package/dist/configure/types/idp-name.d.mts +3 -4
  135. package/dist/configure/types/permission-operand.types.d.mts +7 -8
  136. package/dist/configure/types/type.d.mts +3 -4
  137. package/dist/kysely/index.d.mts +18 -18
  138. package/dist/parser/service/idp/types.d.mts +2 -3
  139. package/dist/parser/service/tailordb/type-source.d.mts +2 -3
  140. package/dist/parser/service/tailordb/types.d.mts +13 -14
  141. package/dist/plugin/builtin/enum-constants/index.d.mts +3 -4
  142. package/dist/plugin/builtin/file-utils/index.d.mts +3 -4
  143. package/dist/plugin/builtin/kysely-type/index.d.mts +4 -5
  144. package/dist/plugin/builtin/seed/index.d.mts +4 -5
  145. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +2 -3
  146. package/dist/plugin/get-generated-table.d.mts +2 -3
  147. package/dist/plugin/index.mjs +1 -1
  148. package/dist/plugin/index.mjs.map +1 -1
  149. package/dist/plugin/types.d.mts +29 -29
  150. package/dist/plugin/with-context.d.mts +9 -10
  151. package/dist/{register-ts-hook-DS1zYiCV.mjs → register-ts-hook-DZ1Kpt4s.mjs} +44 -44
  152. package/dist/register-ts-hook-DZ1Kpt4s.mjs.map +1 -0
  153. package/dist/runtime/aigateway.d.mts +4 -5
  154. package/dist/runtime/authconnection.d.mts +3 -4
  155. package/dist/runtime/context.d.mts +6 -7
  156. package/dist/runtime/date.d.mts +2 -3
  157. package/dist/runtime/field-parse.d.mts +2 -3
  158. package/dist/runtime/file.d.mts +14 -15
  159. package/dist/runtime/globals.d.mts +2 -1
  160. package/dist/runtime/iconv.d.mts +5 -6
  161. package/dist/runtime/idp.d.mts +14 -15
  162. package/dist/runtime/index.d.mts +7 -7
  163. package/dist/runtime/logger.d.mts +10 -11
  164. package/dist/runtime/secretmanager.d.mts +3 -4
  165. package/dist/runtime/types.d.mts +7 -8
  166. package/dist/runtime/workflow.d.mts +7 -8
  167. package/dist/seed/index.d.mts +3 -3
  168. package/dist/shared/src/color.d.mts +2 -3
  169. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +21 -22
  170. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +2 -3
  171. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +35 -36
  172. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +6 -7
  173. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +229 -230
  174. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +40 -41
  175. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +9 -10
  176. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +3 -4
  177. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +45 -46
  178. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +24 -25
  179. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +17 -18
  180. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +29 -30
  181. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +8 -9
  182. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +2 -3
  183. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +37 -38
  184. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +13 -14
  185. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +19 -20
  186. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +2 -3
  187. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +25 -26
  188. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +59 -60
  189. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +10 -11
  190. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +7 -8
  191. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +37 -38
  192. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +4 -5
  193. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +6 -7
  194. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +21 -22
  195. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +3 -4
  196. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +50 -51
  197. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +4 -5
  198. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +74 -75
  199. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +35 -36
  200. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +41 -42
  201. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +11 -12
  202. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +97 -98
  203. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +11 -12
  204. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +209 -210
  205. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +24 -25
  206. package/dist/types/aigateway.generated.d.mts +3 -4
  207. package/dist/types/app-config.generated.d.mts +2 -3
  208. package/dist/types/auth-connection.generated.d.mts +3 -4
  209. package/dist/types/auth.generated.d.mts +15 -16
  210. package/dist/types/executor.generated.d.mts +26 -27
  211. package/dist/types/helpers.d.mts +15 -13
  212. package/dist/types/http-adapter.generated.d.mts +2 -3
  213. package/dist/types/idp.generated.d.mts +7 -8
  214. package/dist/types/resolver.generated.d.mts +4 -5
  215. package/dist/types/secrets.generated.d.mts +3 -4
  216. package/dist/types/staticwebsite.generated.d.mts +3 -4
  217. package/dist/types/tailordb.generated.d.mts +7 -8
  218. package/dist/types/workflow.generated.d.mts +3 -4
  219. package/dist/utils/test/index.d.mts +3 -4
  220. package/dist/vitest/index.d.mts +2 -2
  221. package/dist/vitest/mock-kysely.d.mts +4 -5
  222. package/dist/vitest/mocks/aigateway.d.mts +3 -4
  223. package/dist/vitest/mocks/authconnection.d.mts +3 -4
  224. package/dist/vitest/mocks/file.d.mts +3 -4
  225. package/dist/vitest/mocks/iconv.d.mts +3 -4
  226. package/dist/vitest/mocks/idp.d.mts +3 -4
  227. package/dist/vitest/mocks/logger.d.mts +3 -4
  228. package/dist/vitest/mocks/secretmanager.d.mts +3 -4
  229. package/dist/vitest/mocks/tailordb-pglite.d.mts +4 -5
  230. package/dist/vitest/mocks/tailordb.d.mts +6 -7
  231. package/dist/vitest/mocks/workflow.d.mts +2 -3
  232. package/dist/vitest/pglite-kysely.d.mts +5 -6
  233. package/dist/vitest/setup.d.mts +6 -7
  234. package/dist/vitest/workflow-local.d.mts +5 -6
  235. package/docs/services/idp.md +6 -3
  236. package/package.json +12 -12
  237. package/dist/application-CiN_er9X.mjs.map +0 -1
  238. package/dist/application-_8rjQRx8.mjs +0 -1
  239. package/dist/register-ts-hook-DS1zYiCV.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @tailor-platform/sdk
2
2
 
3
+ ## 2.14.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2281](https://github.com/tailor-platform/sdk/pull/2281) [`ee9374a`](https://github.com/tailor-platform/sdk/commit/ee9374aca30aad24b03009cba76e857b430c9cfa) Thanks [@k1LoW](https://github.com/k1LoW)! - Validate IdP `userAuthPolicy.allowedEmailDomains` locally and document `["*"]`, the lone entry that allows every email domain and the only way to enable `allowGoogleOauth` or `allowMicrosoftOauth` without enumerating domains. Each entry must be a hostname or `"*"`, entries must be unique when compared case-insensitively and number at most 100, and `"*"` cannot sit alongside another entry. These were already rejected on deploy, so they now surface before the apply instead of during it.
8
+
9
+ `tailor deploy` also warns on an IdP service that leaves `allowedEmailDomains` empty. An empty list still allows every domain, but a future platform release requires that state to be explicit, so set `["*"]` to keep the current behavior or list the domains you accept.
10
+
11
+ Fixes a plan diff that re-applied `allowedEmailDomains` on every deploy when an entry was written in mixed case.
12
+
13
+ - [#2252](https://github.com/tailor-platform/sdk/pull/2252) [`d56876d`](https://github.com/tailor-platform/sdk/commit/d56876d6947a18345150bdbaee2d63fa1ce17992) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @bufbuild/protobuf to v2.14.1
14
+
15
+ - [#2255](https://github.com/tailor-platform/sdk/pull/2255) [`39662f4`](https://github.com/tailor-platform/sdk/commit/39662f4bf56ccc7b0fa251d70a2b47d16979c2bc) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update @opentelemetry
16
+
17
+ - [#2273](https://github.com/tailor-platform/sdk/pull/2273) [`656714a`](https://github.com/tailor-platform/sdk/commit/656714a8215a03458b2a2a5b084faafb805b3b59) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update @inquirer
18
+
19
+ - [#2276](https://github.com/tailor-platform/sdk/pull/2276) [`453a11b`](https://github.com/tailor-platform/sdk/commit/453a11b1db0fa87a0b5d1ab41620bb4b094f5365) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency @toiroakr/lines-db to v0.12.6
20
+
21
+ - [#2277](https://github.com/tailor-platform/sdk/pull/2277) [`7926310`](https://github.com/tailor-platform/sdk/commit/7926310a7d5154e5bace9be7f66760a264df1151) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update dependency pkg-types to v2.3.2
22
+
23
+ - [#2279](https://github.com/tailor-platform/sdk/pull/2279) [`9f926d5`](https://github.com/tailor-platform/sdk/commit/9f926d510a8e972d025a33266936a3d9be80f526) Thanks [@renovate](https://github.com/apps/renovate)! - fix(deps): update rolldown
24
+
3
25
  ## 2.14.0
4
26
 
5
27
  ### Minor Changes
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./application-CfevPO-k.mjs";export{t as defineApplication,e as generatePluginFilesIfNeeded};
@@ -63,8 +63,8 @@ import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from
63
63
 
64
64
  export type ${t.name} = typeof ${a};
65
65
  `}function generateFieldsCode(e){let t=[];for(let[n,r]of Object.entries(e.fields)){if(!isFieldDefinition(r))continue;let e=generateSingleFieldCode(r);e&&t.push(` ${n}: ${e}`)}return`{\n${t.join(`,
66
- `)},\n}`}const ke={string:`string`,integer:`int`,float:`float`,boolean:`bool`,uuid:`uuid`,datetime:`datetime`,date:`date`,time:`time`,enum:`enum`,nested:`nested`};function generateSingleFieldCode(e){let t=e.type;if(!t)return null;let n=ke[t]??t,r=e._metadata??e.metadata??{},i=[];r.required===!1&&i.push(`optional: true`);let a=i.length>0?`{ ${i.join(`, `)} }`:``;if(t===`enum`){let e=r.allowedValues,t=[];Array.isArray(e)&&(t=e.map(e=>e.value));let n=`db.enum(${JSON.stringify(t)}${a?`, ${a}`:``})`;return r.index&&(n+=`.index()`),r.unique&&(n+=`.unique()`),r.description&&(n+=`.description(${JSON.stringify(r.description)})`),n}let o=`db.${n}(${a})`;return r.index&&(o+=`.index()`),r.unique&&(o+=`.unique()`),r.description&&(o+=`.description(${JSON.stringify(r.description)})`),o}function sanitizePluginId(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function toCamelCase(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function createDepCollectorPlugin(){let e=new Set,t={name:`cache-dep-collector`,load:{filter:{id:{include:[/\.[^/]+$/]}},handler(t){return!t.includes(`node_modules`)&&!t.endsWith(`.entry.js`)&&e.add(t),null}}};function getResult(){return Array.from(e).toSorted()}return{plugin:t,getResult}}function hashContent(e){return he.createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function hashFile(e){let t=A.readFileSync(e);return he.createHash(`sha256`).update(t).digest(`hex`)}function hashFiles(e){return hashContent(e.toSorted().map(e=>hashFileOrMissing(e)).join(``))}function hashFileOrMissing(e){try{return hashFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return`<missing>`;throw e}}function buildCacheKey(e,t,n){return n?`${e}:${n}:${t}`:`${e}:${t}`}function combineHash(e,t){return t?hashContent(e+t):e}function computeBundlerContextHash(e){let{sourceFile:t,extraContext:n,tsconfig:r,inlineSourcemap:i,bundleLogLevel:a,prefix:o}=e;return hashContent((o??``)+O.resolve(t)+n+(r?hashFile(r):``)+String(i??!1)+(a??``))}async function withCache(e){let{cache:t,kind:n,namespace:r,name:i,sourceFile:a,contextHash:o,build:l}=e;if(!t)return await l([],()=>{});let u=t.tryRestore({kind:n,namespace:r,name:i,contextHash:o});if(u!==void 0)return s.debug(` ${c.dim(`cached`)}: ${i}`),u;let d=new Set,{plugin:f,getResult:p}=createDepCollectorPlugin(),m=await l([f],e=>d.add(e));return t.save({kind:n,namespace:r,name:i,sourceFile:a,content:m,dependencyPaths:[...p(),...d],contextHash:o}),m}function createBundleCache(e){function tryRestore(t){let n=buildCacheKey(t.kind,t.name,t.namespace),r=e.getEntry(n);if(!r)return;let i;try{i=combineHash(hashFiles(r.dependencyPaths),t.contextHash)}catch{return}if(i!==r.inputHash)return;let a=e.restoreBundleContent(n),o=r.outputFiles.find(e=>e.outputPath===n);if(!(a===void 0||!o||hashContent(a)!==o.contentHash))return a}function save(t){let{kind:n,namespace:r,name:i,sourceFile:a,content:o,dependencyPaths:s,contextHash:c}=t,l=buildCacheKey(n,i,r),u=s.includes(a)?s:[a,...s],d;try{d=combineHash(hashFiles(u),c)}catch{return}let f=hashContent(o);e.storeBundleContent(l,o),e.setEntry(l,{kind:`bundle`,inputHash:d,dependencyPaths:u,outputFiles:[{outputPath:l,contentHash:f}],createdAt:new Date().toISOString()})}return{tryRestore,save}}function getModuleExportName(e){if(!e||typeof e!=`object`)return;let t=e;return t.name?t.name:typeof t.value==`string`?t.value:void 0}function isTailorSdkSource(e){return/^@tailor-platform\/sdk(\/|$)/.test(e)}function getImportSource(e){if(!e)return null;if(e.type===`ImportExpression`){let t=e.source;if(t.type===`Literal`&&typeof t.value==`string`)return t.value}if(e.type===`CallExpression`){let t=e;if(t.callee.type===`Identifier`&&t.callee.name===`require`){let e=t.arguments[0];if(e&&`type`in e&&e.type===`Literal`&&`value`in e&&typeof e.value==`string`)return e.value}}return null}function argumentSourceText(e,t){if(e&&typeof e==`object`&&`start`in e&&`end`in e)return t.slice(e.start,e.end)}function getStartCallInfo(e,t){if(!e||typeof e!=`object`||e.type!==`CallExpression`)return null;let n=e,r=n.callee;if(r.type!==`MemberExpression`)return null;let i=r;return i.computed||i.property.name!==`start`||i.object.type!==`Identifier`?null:{identifierName:i.object.name,callRange:{start:n.start,end:n.end},argsText:argumentSourceText(n.arguments[0],t)??``,optionsText:argumentSourceText(n.arguments[1],t)}}function unwrapAwait(e){return e?.type===`AwaitExpression`?e.argument:e}function isStringLiteral(e){return e?.type===`Literal`&&typeof e.value==`string`}function isFunctionExpression(e){return e?.type===`ArrowFunctionExpression`||e?.type===`FunctionExpression`}function findProperty(e,t){for(let n of e)if(n.type===`Property`){let e=n;if((e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?e.key.value:null)===t)return{key:e.key,value:e.value,start:e.start,end:e.end}}return null}function applyReplacements(e,t){let n=t.toSorted((e,t)=>t.start-e.start);for(let e=0;e+1<n.length;e++){let t=a(n[e],`replacement missing at index ${e}`),r=a(n[e+1],`replacement missing at index ${e+1}`);if(r.end>t.start)throw Error(`applyReplacements: overlapping replacement ranges [${r.start}, ${r.end}) and [${t.start}, ${t.end})`)}let r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}function findStatementEnd(e,t){let n=t;for(;n<e.length&&(e[n]===`;`||e[n]===` `||e[n]===` `);)n++;return n<e.length&&e[n]===`
67
- `&&n++,n}function collectSdkBindings(e,t){let n=new Set;function walk(e){if(!e||typeof e!=`object`)return;let r=e.type;if(r===`ImportDeclaration`){let r=e,i=r.source.value;if(typeof i==`string`&&isTailorSdkSource(i)){for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let r=e;(r.imported.type===`Identifier`?r.imported.name:r.imported.value)===t&&n.add(r.local.name)}else if(e.type===`ImportDefaultSpecifier`||e.type===`ImportNamespaceSpecifier`){let t=e;n.add(`__namespace__:${t.local.name}`)}}}if(r===`VariableDeclaration`){let r=e;for(let e of r.declarations){let r=getImportSource(unwrapAwait(e.init));if(r&&isTailorSdkSource(r)){let r=e.id;if(r.type===`Identifier`)n.add(`__namespace__:${r.name}`);else if(r.type===`ObjectPattern`){let e=r;for(let r of e.properties)if(r.type===`Property`){let e=r,i=e.key.type===`Identifier`?e.key.name:e.key.value;if(i===t){let t=e.value.type===`Identifier`?e.value.name:i;n.add(t)}}}}}}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}return walk(e),n}function isSdkFunctionCall(e,t,n){if(e.type!==`CallExpression`)return!1;let r=e.callee;if(r.type===`Identifier`){let e=r;return t.has(e.name)}if(r.type===`MemberExpression`){let e=r;if(!e.computed){let r=e.object,i=e.property;if(r.type===`Identifier`&&t.has(`__namespace__:${r.name}`)&&i.name===n)return!0}}return!1}function findAllJobs(e,t){let n=[],r=collectSdkBindings(e,`createWorkflowJob`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflowJob`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=a(i,`createWorkflowJob first argument missing`),r=findProperty(e.properties,`name`),o=findProperty(e.properties,`body`);if(r&&isStringLiteral(r.value)&&o&&isFunctionExpression(o.value)){let e,i;for(let n=t.length-1;n>=0;n--){let r=a(t[n],`parent at index ${n} missing`);if(r.type===`VariableDeclarator`){let e=r;e.id?.type===`Identifier`&&(i=e.id.name)}(r.type===`ExportNamedDeclaration`||r.type===`VariableDeclaration`)&&(e={start:r.start,end:r.end})}n.push({name:r.value.value,exportName:i,nameRange:{start:r.start,end:r.end},bodyValueRange:{start:o.value.start,end:o.value.end},statementRange:e})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function findAllWorkflows(e,t){let n=[],r=collectSdkBindings(e,`createWorkflow`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflow`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=findProperty(a(i,`createWorkflow first argument missing`).properties,`name`);if(e&&isStringLiteral(e.value)){let r,i=!1;for(let e=t.length-1;e>=0;e--){let n=a(t[e],`parent at index ${e} missing`);if(n.type===`VariableDeclarator`){let e=n;if(e.id?.type===`Identifier`){r=e.id.name;break}}n.type===`ExportDefaultDeclaration`&&(i=!0)}n.push({name:e.value.value,exportName:r,isDefaultExport:i})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function normalizeFilePath(e){return O.resolve(e.replace(/[?#].*$/,``)).replace(/\.(ts|mts|cts|js|mjs|cjs)$/,``)}function createModuleBindings(e,t,n){let r=new Map,i=new Map;for(let e of findAllWorkflows(t,n)){let t={kind:`workflow`,name:e.name};e.exportName&&r.set(e.exportName,t),e.isDefaultExport&&i.set(`default`,t)}for(let e of findAllJobs(t,n))e.exportName&&r.set(e.exportName,{kind:`job`,name:e.name});for(let e of t.body){if(e.type===`ExportDefaultDeclaration`){let t=e.declaration;if(t?.type===`Identifier`){let e=r.get(t.name);e&&i.set(`default`,e)}continue}if(e.type!==`ExportNamedDeclaration`)continue;let t=e.declaration;if(t?.type===`VariableDeclaration`)for(let e of t.declarations){let t=e.id;if(t?.type!==`Identifier`)continue;let n=t.name,a=r.get(n);a&&i.set(n,a)}if(!e.source)for(let t of e.specifiers??[]){let e=getModuleExportName(t.local),n=getModuleExportName(t.exported);if(!e||!n)continue;let a=r.get(e);a&&i.set(n,a)}}return{sourceFile:e,localBindings:r,exports:i}}async function buildStartContext(e,t,n=process.cwd()){let r=new Map;if(!e)return{modules:r,authNamespace:t};for(let t of m(e,n))try{let e=await A.promises.readFile(t,`utf-8`),{program:n,errors:i}=P(t,e);if(i.length>0){s.warn(`Failed to parse workflow file ${t}: ${i.map(e=>e.message).join(`; `)}`,{mode:`stream`});continue}r.set(normalizeFilePath(t),createModuleBindings(t,n,e))}catch(e){let n=e instanceof Error?e.message:String(e);s.warn(`Failed to process workflow file ${t}: ${n}`,{mode:`stream`})}return{modules:r,authNamespace:t}}function sortedTargets(e){return[...e].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.kind,t.name])}function serializeStartContext(e){if(!e)return``;let t=[...e.modules].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,sortedTargets(t.localBindings),sortedTargets(t.exports)]);return JSON.stringify(t)+(e.authNamespace??``)}const Ae=/\.start(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\(/;function hasStartCall(e){return Ae.test(e)}const je=`__tailor_normalizeStartOptions`;function buildNormalizerHelperSource(e){return`const ${je} = (o) => { if (!o) return o; const { invoker, ...rest } = o; return typeof invoker === "string" ? { ...rest, authInvoker: { namespace: ${JSON.stringify(e)}, machineUserName: invoker } } : typeof invoker === "object" ? { ...rest, authInvoker: invoker } : o; };\n`}function collectBindingNames(e,t){if(!(!e||typeof e!=`object`))switch(e.type){case`Identifier`:t.add(e.name);return;case`ObjectPattern`:for(let n of e.properties)collectBindingNames(n.type===`RestElement`?n.argument:n.value,t);return;case`ArrayPattern`:for(let n of e.elements)collectBindingNames(n,t);return;case`AssignmentPattern`:collectBindingNames(e.left,t);return;case`RestElement`:collectBindingNames(e.argument,t);return;case`TSParameterProperty`:collectBindingNames(e.parameter,t)}}function declarationNode(e){return e.type===`ExportNamedDeclaration`||e.type===`ExportDefaultDeclaration`?e.declaration:e}function collectBlockBindings(e,t){for(let n of e){let e=declarationNode(n);if(e){if(e.type===`VariableDeclaration`){if(e.kind===`var`)continue;for(let n of e.declarations)collectBindingNames(n.id,t)}else(e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&collectBindingNames(e.id,t)}}}function collectFunctionVarBindings(e,t){function walk(n){if(!(!n||typeof n!=`object`)&&(n===e||n.type!==`FunctionDeclaration`&&n.type!==`FunctionExpression`&&n.type!==`ArrowFunctionExpression`&&n.type!==`StaticBlock`)){if(n.type===`VariableDeclaration`&&n.kind===`var`)for(let e of n.declarations)collectBindingNames(e.id,t);for(let e of Object.keys(n)){if(e===`parent`)continue;let t=n[e];if(Array.isArray(t))for(let e of t)walk(e);else t&&typeof t==`object`&&walk(t)}}}walk(e)}function collectScopeBindings(e){let t=new Set;if(e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`){collectBindingNames(e.id,t);for(let n of e.params)collectBindingNames(n,t);return collectFunctionVarBindings(e,t),t}if(e.type===`BlockStatement`)return collectBlockBindings(e.body,t),t;if(e.type===`CatchClause`)return collectBindingNames(e.param,t),t;if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.init??e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations)collectBindingNames(e.id,t);return t}}function addShadowedBindings(e,t,n){if(!t)return e;let r=[...t].filter(e=>n.has(e));return r.length===0?e:new Set([...e,...r])}function walkBindingAware(e,t,n){function walk(e,r,i,a){if(!e||typeof e!=`object`||e.type===`ImportDeclaration`)return;let o=e.type===`Program`?r:addShadowedBindings(r,collectScopeBindings(e),t);n(e,o,i,a);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];if(Array.isArray(n))for(let r of n)walk(r,o,e,t);else n&&typeof n==`object`&&walk(n,o,e,t)}}walk(e,new Set)}function resolveRelativeImport(e,t,n){if(!n.startsWith(`.`))return;let r=O.dirname(t.replace(/[?#].*$/,``)),i=normalizeFilePath(O.resolve(r,n));return e.modules.get(i)??e.modules.get(O.join(i,`index`))}function collectLocalTargets(e,t,n){let r=new Map,i=t.modules.get(normalizeFilePath(n));if(i)for(let[e,t]of i.localBindings)r.set(e,t);for(let i of e.body){if(i.type!==`ImportDeclaration`||i.importKind===`type`)continue;let e=i.source.value;if(typeof e!=`string`)continue;let a=resolveRelativeImport(t,n,e);if(a)for(let e of i.specifiers){if(e.type===`ImportNamespaceSpecifier`||e.type===`ImportSpecifier`&&e.importKind===`type`)continue;let t=e.type===`ImportDefaultSpecifier`?`default`:getModuleExportName(e.imported);if(!t)continue;let n=a.exports.get(t);n&&r.set(e.local.name,n)}}return r}function detectStartCallsWithTargets(e,t,n){let r=[];return walkBindingAware(e,new Set(n.keys()),(e,i)=>{let a=getStartCallInfo(e,t);if(!a||i.has(a.identifierName))return;let o=n.get(a.identifierName);o&&r.push({...a,kind:o.kind,targetName:o.name})}),r}function detectResolvedStartCalls(e,t,n,r){return detectStartCallsWithTargets(e,t,collectLocalTargets(e,n,r))}function transformStartCalls(e,t,n){let{program:r}=P(`input.ts`,e),i=collectLocalTargets(r,t,n),{authNamespace:a}=t,o=detectStartCallsWithTargets(r,e,i),c=[],l=o.filter(e=>{let t=o.find(t=>t!==e&&t.callRange.start<=e.callRange.start&&e.callRange.end<=t.callRange.end);return!t||(c.push({call:e,parent:t}),!1)});for(let{call:e,parent:t}of c)s.warn(`Nested start call "${e.identifierName}.start(...)" inside "${t.identifierName}.start(...)" cannot be converted. Move it to a separate statement and pass the result instead.`);let u=[],d=!1;for(let e of l){let t;if(e.kind===`workflow`){let n=``;e.optionsText!==void 0&&(a?(n=`, ${je}(${e.optionsText})`,d=!0):n=`, ${e.optionsText}`),t=`tailor.workflow.startWorkflow(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}else{let n=e.optionsText===void 0?``:`, ${e.optionsText}`;t=`tailor.workflow.execJobFunction(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}u.push({start:e.callRange.start,end:e.callRange.end,text:t})}let f=applyReplacements(e,u);return d&&a?buildNormalizerHelperSource(a)+f:f}function createStartTransformPlugin(e){if(!(!e||e.modules.size===0))return{name:`start-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){return hasStartCall(t)?{code:transformStartCalls(t,e,n)}:null}}}}function createBundleLog(e={}){let t=new Map;return{options:{logLevel:`warn`,onLog:(e,n)=>{n.code===`UNRESOLVED_IMPORT`&&t.set(JSON.stringify([n.exporter,n.id]),n)}},assertAllResolved(){if(t.size>0)throw unresolvedImportError([...t.values()],e.tsconfig)}}}function unresolvedImportError(e,t){let n=e.map(formatUnresolvedImport),r=n.length===1?`Could not resolve ${n[0]}.`:`Could not resolve ${n.length} imports.`,i=n.length===1?void 0:n.map(e=>`- ${e}`).join(`
66
+ `)},\n}`}const ke={string:`string`,integer:`int`,float:`float`,boolean:`bool`,uuid:`uuid`,datetime:`datetime`,date:`date`,time:`time`,enum:`enum`,nested:`nested`};function generateSingleFieldCode(e){let t=e.type;if(!t)return null;let n=ke[t]??t,r=e._metadata??e.metadata??{},i=[];r.required===!1&&i.push(`optional: true`);let a=i.length>0?`{ ${i.join(`, `)} }`:``;if(t===`enum`){let e=r.allowedValues,t=[];Array.isArray(e)&&(t=e.map(e=>e.value));let n=`db.enum(${JSON.stringify(t)}${a?`, ${a}`:``})`;return r.index&&(n+=`.index()`),r.unique&&(n+=`.unique()`),r.description&&(n+=`.description(${JSON.stringify(r.description)})`),n}let o=`db.${n}(${a})`;return r.index&&(o+=`.index()`),r.unique&&(o+=`.unique()`),r.description&&(o+=`.description(${JSON.stringify(r.description)})`),o}function sanitizePluginId(e){return e.replace(/^@/,``).replace(/\//g,`-`)}function toKebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).replace(/[\s_]+/g,`-`).toLowerCase()}function toCamelCase(e){let t=e.replace(/[-_\s]+(.)?/g,(e,t)=>t?t.toUpperCase():``);return t.charAt(0).toLowerCase()+t.slice(1)}function createDepCollectorPlugin(){let e=new Set,t={name:`cache-dep-collector`,load:{filter:{id:{include:[/\.[^/]+$/]}},handler(t){return!t.includes(`node_modules`)&&!t.endsWith(`.entry.js`)&&e.add(t),null}}};function getResult(){return Array.from(e).toSorted()}return{plugin:t,getResult}}function hashContent(e){return he.createHash(`sha256`).update(e,`utf-8`).digest(`hex`)}function hashFile(e){let t=A.readFileSync(e);return he.createHash(`sha256`).update(t).digest(`hex`)}function hashFiles(e){return hashContent(e.toSorted().map(e=>hashFileOrMissing(e)).join(``))}function hashFileOrMissing(e){try{return hashFile(e)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return`<missing>`;throw e}}function buildCacheKey(e,t,n){return n?`${e}:${n}:${t}`:`${e}:${t}`}function combineHash(e,t){return t?hashContent(e+t):e}function computeBundlerContextHash(e){let{sourceFile:t,extraContext:n,tsconfig:r,inlineSourcemap:i,bundleLogLevel:a,prefix:o}=e;return hashContent((o??``)+O.resolve(t)+n+(r?hashFile(r):``)+String(i??!1)+(a??``))}async function withCache(e){let{cache:t,kind:n,namespace:r,name:i,sourceFile:a,contextHash:o,build:l}=e;if(!t)return await l([],()=>{});let u=t.tryRestore({kind:n,namespace:r,name:i,contextHash:o});if(u!==void 0)return s.debug(` ${c.dim(`cached`)}: ${i}`),u;let d=new Set,{plugin:f,getResult:p}=createDepCollectorPlugin(),m=await l([f],e=>d.add(e));return t.save({kind:n,namespace:r,name:i,sourceFile:a,content:m,dependencyPaths:[...p(),...d],contextHash:o}),m}function createBundleCache(e){function tryRestore(t){let n=buildCacheKey(t.kind,t.name,t.namespace),r=e.getEntry(n);if(!r)return;let i;try{i=combineHash(hashFiles(r.dependencyPaths),t.contextHash)}catch{return}if(i!==r.inputHash)return;let a=e.restoreBundleContent(n),o=r.outputFiles.find(e=>e.outputPath===n);if(a!==void 0&&o&&hashContent(a)===o.contentHash)return a}function save(t){let{kind:n,namespace:r,name:i,sourceFile:a,content:o,dependencyPaths:s,contextHash:c}=t,l=buildCacheKey(n,i,r),u=s.includes(a)?s:[a,...s],d;try{d=combineHash(hashFiles(u),c)}catch{return}let f=hashContent(o);e.storeBundleContent(l,o),e.setEntry(l,{kind:`bundle`,inputHash:d,dependencyPaths:u,outputFiles:[{outputPath:l,contentHash:f}],createdAt:new Date().toISOString()})}return{tryRestore,save}}function getModuleExportName(e){if(!e||typeof e!=`object`)return;let t=e;return t.name?t.name:typeof t.value==`string`?t.value:void 0}function isTailorSdkSource(e){return/^@tailor-platform\/sdk(\/|$)/.test(e)}function getImportSource(e){if(!e)return null;if(e.type===`ImportExpression`){let t=e.source;if(t.type===`Literal`&&typeof t.value==`string`)return t.value}if(e.type===`CallExpression`){let t=e;if(t.callee.type===`Identifier`&&t.callee.name===`require`){let e=t.arguments[0];if(e&&`type`in e&&e.type===`Literal`&&`value`in e&&typeof e.value==`string`)return e.value}}return null}function argumentSourceText(e,t){if(e&&typeof e==`object`&&`start`in e&&`end`in e)return t.slice(e.start,e.end)}function getStartCallInfo(e,t){if(!e||typeof e!=`object`||e.type!==`CallExpression`)return null;let n=e,r=n.callee;if(r.type!==`MemberExpression`)return null;let i=r;return i.computed||i.property.name!==`start`||i.object.type!==`Identifier`?null:{identifierName:i.object.name,callRange:{start:n.start,end:n.end},argsText:argumentSourceText(n.arguments[0],t)??``,optionsText:argumentSourceText(n.arguments[1],t)}}function unwrapAwait(e){return e?.type===`AwaitExpression`?e.argument:e}function isStringLiteral(e){return e?.type===`Literal`&&typeof e.value==`string`}function isFunctionExpression(e){return e?.type===`ArrowFunctionExpression`||e?.type===`FunctionExpression`}function findProperty(e,t){for(let n of e)if(n.type===`Property`){let e=n;if((e.key.type===`Identifier`?e.key.name:e.key.type===`Literal`?e.key.value:null)===t)return{key:e.key,value:e.value,start:e.start,end:e.end}}return null}function applyReplacements(e,t){let n=t.toSorted((e,t)=>t.start-e.start);for(let e=0;e+1<n.length;e++){let t=a(n[e],`replacement missing at index ${e}`),r=a(n[e+1],`replacement missing at index ${e+1}`);if(r.end>t.start)throw Error(`applyReplacements: overlapping replacement ranges [${r.start}, ${r.end}) and [${t.start}, ${t.end})`)}let r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}function findStatementEnd(e,t){let n=t;for(;n<e.length&&(e[n]===`;`||e[n]===` `||e[n]===` `);)n++;return n<e.length&&e[n]===`
67
+ `&&n++,n}function collectSdkBindings(e,t){let n=new Set;function walk(e){if(!e||typeof e!=`object`)return;let r=e.type;if(r===`ImportDeclaration`){let r=e,i=r.source.value;if(typeof i==`string`&&isTailorSdkSource(i)){for(let e of r.specifiers)if(e.type===`ImportSpecifier`){let r=e;(r.imported.type===`Identifier`?r.imported.name:r.imported.value)===t&&n.add(r.local.name)}else if(e.type===`ImportDefaultSpecifier`||e.type===`ImportNamespaceSpecifier`){let t=e;n.add(`__namespace__:${t.local.name}`)}}}if(r===`VariableDeclaration`){let r=e;for(let e of r.declarations){let r=getImportSource(unwrapAwait(e.init));if(r&&isTailorSdkSource(r)){let r=e.id;if(r.type===`Identifier`)n.add(`__namespace__:${r.name}`);else if(r.type===`ObjectPattern`){let e=r;for(let r of e.properties)if(r.type===`Property`){let e=r,i=e.key.type===`Identifier`?e.key.name:e.key.value;if(i===t){let t=e.value.type===`Identifier`?e.value.name:i;n.add(t)}}}}}}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}return walk(e),n}function isSdkFunctionCall(e,t,n){if(e.type!==`CallExpression`)return!1;let r=e.callee;if(r.type===`Identifier`){let e=r;return t.has(e.name)}if(r.type===`MemberExpression`){let e=r;if(!e.computed){let r=e.object,i=e.property;if(r.type===`Identifier`&&t.has(`__namespace__:${r.name}`)&&i.name===n)return!0}}return!1}function findAllJobs(e,t){let n=[],r=collectSdkBindings(e,`createWorkflowJob`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflowJob`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=a(i,`createWorkflowJob first argument missing`),r=findProperty(e.properties,`name`),o=findProperty(e.properties,`body`);if(r&&isStringLiteral(r.value)&&o&&isFunctionExpression(o.value)){let e,i;for(let n=t.length-1;n>=0;n--){let r=a(t[n],`parent at index ${n} missing`);if(r.type===`VariableDeclarator`){let e=r;e.id?.type===`Identifier`&&(i=e.id.name)}(r.type===`ExportNamedDeclaration`||r.type===`VariableDeclaration`)&&(e={start:r.start,end:r.end})}n.push({name:r.value.value,exportName:i,nameRange:{start:r.start,end:r.end},bodyValueRange:{start:o.value.start,end:o.value.end},statementRange:e})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function findAllWorkflows(e,t){let n=[],r=collectSdkBindings(e,`createWorkflow`);function walk(e,t=[]){if(!e||typeof e!=`object`)return;if(isSdkFunctionCall(e,r,`createWorkflow`)){let r=e.arguments,i=r[0];if(r.length>=1&&i?.type===`ObjectExpression`){let e=findProperty(a(i,`createWorkflow first argument missing`).properties,`name`);if(e&&isStringLiteral(e.value)){let r,i=!1;for(let e=t.length-1;e>=0;e--){let n=a(t[e],`parent at index ${e} missing`);if(n.type===`VariableDeclarator`){let e=n;if(e.id?.type===`Identifier`){r=e.id.name;break}}n.type===`ExportDefaultDeclaration`&&(i=!0)}n.push({name:e.value.value,exportName:r,isDefaultExport:i})}}}let i=[...t,e];for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e,i)):n&&typeof n==`object`&&walk(n,i)}}return walk(e),n}function normalizeFilePath(e){return O.resolve(e.replace(/[?#].*$/,``)).replace(/\.(ts|mts|cts|js|mjs|cjs)$/,``)}function createModuleBindings(e,t,n){let r=new Map,i=new Map;for(let e of findAllWorkflows(t,n)){let t={kind:`workflow`,name:e.name};e.exportName&&r.set(e.exportName,t),e.isDefaultExport&&i.set(`default`,t)}for(let e of findAllJobs(t,n))e.exportName&&r.set(e.exportName,{kind:`job`,name:e.name});for(let e of t.body){if(e.type===`ExportDefaultDeclaration`){let t=e.declaration;if(t?.type===`Identifier`){let e=r.get(t.name);e&&i.set(`default`,e)}continue}if(e.type!==`ExportNamedDeclaration`)continue;let t=e.declaration;if(t?.type===`VariableDeclaration`)for(let e of t.declarations){let t=e.id;if(t?.type!==`Identifier`)continue;let n=t.name,a=r.get(n);a&&i.set(n,a)}if(!e.source)for(let t of e.specifiers??[]){let e=getModuleExportName(t.local),n=getModuleExportName(t.exported);if(!e||!n)continue;let a=r.get(e);a&&i.set(n,a)}}return{sourceFile:e,localBindings:r,exports:i}}async function buildStartContext(e,t,n=process.cwd()){let r=new Map;if(!e)return{modules:r,authNamespace:t};for(let t of m(e,n))try{let e=await A.promises.readFile(t,`utf-8`),{program:n,errors:i}=P(t,e);if(i.length>0){s.warn(`Failed to parse workflow file ${t}: ${i.map(e=>e.message).join(`; `)}`,{mode:`stream`});continue}r.set(normalizeFilePath(t),createModuleBindings(t,n,e))}catch(e){let n=e instanceof Error?e.message:String(e);s.warn(`Failed to process workflow file ${t}: ${n}`,{mode:`stream`})}return{modules:r,authNamespace:t}}function sortedTargets(e){return[...e].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.kind,t.name])}function serializeStartContext(e){if(!e)return``;let t=[...e.modules].toSorted(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,sortedTargets(t.localBindings),sortedTargets(t.exports)]);return JSON.stringify(t)+(e.authNamespace??``)}const Ae=/\.start(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\(/;function hasStartCall(e){return Ae.test(e)}const je=`__tailor_normalizeStartOptions`;function buildNormalizerHelperSource(e){return`const ${je} = (o) => { if (!o) return o; const { invoker, ...rest } = o; return typeof invoker === "string" ? { ...rest, authInvoker: { namespace: ${JSON.stringify(e)}, machineUserName: invoker } } : typeof invoker === "object" ? { ...rest, authInvoker: invoker } : o; };\n`}function collectBindingNames(e,t){if(e&&typeof e==`object`)switch(e.type){case`Identifier`:t.add(e.name);return;case`ObjectPattern`:for(let n of e.properties)collectBindingNames(n.type===`RestElement`?n.argument:n.value,t);return;case`ArrayPattern`:for(let n of e.elements)collectBindingNames(n,t);return;case`AssignmentPattern`:collectBindingNames(e.left,t);return;case`RestElement`:collectBindingNames(e.argument,t);return;case`TSParameterProperty`:collectBindingNames(e.parameter,t)}}function declarationNode(e){return e.type===`ExportNamedDeclaration`||e.type===`ExportDefaultDeclaration`?e.declaration:e}function collectBlockBindings(e,t){for(let n of e){let e=declarationNode(n);if(e){if(e.type===`VariableDeclaration`){if(e.kind===`var`)continue;for(let n of e.declarations)collectBindingNames(n.id,t)}else(e.type===`FunctionDeclaration`||e.type===`ClassDeclaration`)&&collectBindingNames(e.id,t)}}}function collectFunctionVarBindings(e,t){function walk(n){if(n&&typeof n==`object`&&(n===e||n.type!==`FunctionDeclaration`&&n.type!==`FunctionExpression`&&n.type!==`ArrowFunctionExpression`&&n.type!==`StaticBlock`)){if(n.type===`VariableDeclaration`&&n.kind===`var`)for(let e of n.declarations)collectBindingNames(e.id,t);for(let e of Object.keys(n)){if(e===`parent`)continue;let t=n[e];if(Array.isArray(t))for(let e of t)walk(e);else t&&typeof t==`object`&&walk(t)}}}walk(e)}function collectScopeBindings(e){let t=new Set;if(e.type===`FunctionDeclaration`||e.type===`FunctionExpression`||e.type===`ArrowFunctionExpression`){collectBindingNames(e.id,t);for(let n of e.params)collectBindingNames(n,t);return collectFunctionVarBindings(e,t),t}if(e.type===`BlockStatement`)return collectBlockBindings(e.body,t),t;if(e.type===`CatchClause`)return collectBindingNames(e.param,t),t;if(e.type===`ForStatement`||e.type===`ForInStatement`||e.type===`ForOfStatement`){let n=e.init??e.left;if(n?.type===`VariableDeclaration`&&n.kind!==`var`)for(let e of n.declarations)collectBindingNames(e.id,t);return t}}function addShadowedBindings(e,t,n){if(!t)return e;let r=[...t].filter(e=>n.has(e));return r.length===0?e:new Set([...e,...r])}function walkBindingAware(e,t,n){function walk(e,r,i,a){if(!e||typeof e!=`object`||e.type===`ImportDeclaration`)return;let o=e.type===`Program`?r:addShadowedBindings(r,collectScopeBindings(e),t);n(e,o,i,a);for(let t of Object.keys(e)){if(t===`parent`)continue;let n=e[t];if(Array.isArray(n))for(let r of n)walk(r,o,e,t);else n&&typeof n==`object`&&walk(n,o,e,t)}}walk(e,new Set)}function resolveRelativeImport(e,t,n){if(!n.startsWith(`.`))return;let r=O.dirname(t.replace(/[?#].*$/,``)),i=normalizeFilePath(O.resolve(r,n));return e.modules.get(i)??e.modules.get(O.join(i,`index`))}function collectLocalTargets(e,t,n){let r=new Map,i=t.modules.get(normalizeFilePath(n));if(i)for(let[e,t]of i.localBindings)r.set(e,t);for(let i of e.body){if(i.type!==`ImportDeclaration`||i.importKind===`type`)continue;let e=i.source.value;if(typeof e!=`string`)continue;let a=resolveRelativeImport(t,n,e);if(a)for(let e of i.specifiers){if(e.type===`ImportNamespaceSpecifier`||e.type===`ImportSpecifier`&&e.importKind===`type`)continue;let t=e.type===`ImportDefaultSpecifier`?`default`:getModuleExportName(e.imported);if(!t)continue;let n=a.exports.get(t);n&&r.set(e.local.name,n)}}return r}function detectStartCallsWithTargets(e,t,n){let r=[];return walkBindingAware(e,new Set(n.keys()),(e,i)=>{let a=getStartCallInfo(e,t);if(!a||i.has(a.identifierName))return;let o=n.get(a.identifierName);o&&r.push({...a,kind:o.kind,targetName:o.name})}),r}function detectResolvedStartCalls(e,t,n,r){return detectStartCallsWithTargets(e,t,collectLocalTargets(e,n,r))}function transformStartCalls(e,t,n){let{program:r}=P(`input.ts`,e),i=collectLocalTargets(r,t,n),{authNamespace:a}=t,o=detectStartCallsWithTargets(r,e,i),c=[],l=o.filter(e=>{let t=o.find(t=>t!==e&&t.callRange.start<=e.callRange.start&&e.callRange.end<=t.callRange.end);return!t||(c.push({call:e,parent:t}),!1)});for(let{call:e,parent:t}of c)s.warn(`Nested start call "${e.identifierName}.start(...)" inside "${t.identifierName}.start(...)" cannot be converted. Move it to a separate statement and pass the result instead.`);let u=[],d=!1;for(let e of l){let t;if(e.kind===`workflow`){let n=``;e.optionsText!==void 0&&(a?(n=`, ${je}(${e.optionsText})`,d=!0):n=`, ${e.optionsText}`),t=`tailor.workflow.startWorkflow(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}else{let n=e.optionsText===void 0?``:`, ${e.optionsText}`;t=`tailor.workflow.execJobFunction(${JSON.stringify(e.targetName)}, ${e.argsText||`undefined`}${n})`}u.push({start:e.callRange.start,end:e.callRange.end,text:t})}let f=applyReplacements(e,u);return d&&a?buildNormalizerHelperSource(a)+f:f}function createStartTransformPlugin(e){if(e&&e.modules.size!==0)return{name:`start-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){return hasStartCall(t)?{code:transformStartCalls(t,e,n)}:null}}}}function createBundleLog(e={}){let t=new Map;return{options:{logLevel:`warn`,onLog:(e,n)=>{n.code===`UNRESOLVED_IMPORT`&&t.set(JSON.stringify([n.exporter,n.id]),n)}},assertAllResolved(){if(t.size>0)throw unresolvedImportError([...t.values()],e.tsconfig)}}}function unresolvedImportError(e,t){let n=e.map(formatUnresolvedImport),r=n.length===1?`Could not resolve ${n[0]}.`:`Could not resolve ${n.length} imports.`,i=n.length===1?void 0:n.map(e=>`- ${e}`).join(`
68
68
  `),a=unresolvedImportSuggestion(e,t);return ee({code:`UNRESOLVED_IMPORT`,message:r,details:i,suggestion:a})}function unresolvedImportSuggestion(e,t){let n=e.map(e=>e.exporter).filter(e=>e!==void 0).filter(D).map(ne),r=e.some(e=>e.exporter===void 0||!D(e.exporter)),i=t?`Check that each import path is correct, and that a \`compilerOptions.paths\` entry covering it is declared in the importing file's own tsconfig.json or an ancestor. The build used "${t}".`:"No tsconfig.json was found, so `compilerOptions.paths` aliases were not applied. Add a tsconfig.json declaring the aliases these files import.";return[...new Set([...n,...r?[i]:[]])].join(`
69
69
  `)}function formatUnresolvedImport(e){let t=e.exporter??`an imported module`,n=e.id?.startsWith(`\0`)?`a generated entry (${e.id.slice(1)})`:e.id&&`"${e.id}"`;return`"${t}"${n?` imported from ${n}`:``}`}const z=[`console.info`,`console.table`,`console.dir`,`console.dirxml`,`console.count`,`console.countReset`,`console.time`,`console.timeLog`,`console.timeEnd`,`console.group`,`console.groupCollapsed`,`console.groupEnd`,`console.clear`],B=[`console.debug`,`console.log`,`console.trace`],Me=[`console.warn`],Ne=[`console.error`],V=[`globalThis.tailor.logger.debug`],H=[`globalThis.tailor.logger.info`],Pe=[`globalThis.tailor.logger.warn`],Fe=[`globalThis.tailor.logger.error`],Ie={DEBUG:[],INFO:[...B,...V],WARN:[...B,...z,...V,...H],ERROR:[...B,...z,...Me,...V,...H,...Pe],SILENT:[...B,...z,...Me,...Ne,...V,...H,...Pe,...Fe]};function normalizeBundleLogLevel(e){let t=e.trim().toUpperCase();return isLogLevel(t)?t:void 0}function resolveBundleLogLevel(e){if(e===void 0)return`DEBUG`;let t=normalizeBundleLogLevel(e);if(t)return t;throw Error(`Invalid logLevel "${e}". Expected one of: ${I.join(`, `)}`)}function manualPureFunctionsForLogLevel(e){return Ie[e]}function createLogLevelTreeshakeOptions(e){let t=manualPureFunctionsForLogLevel(e);return t.length>0?{manualPureFunctions:t}:{}}const Le={moduleSideEffects:!1,annotations:!0,unknownGlobalSideEffects:!1};function mergeFunctionTreeshakeOptions(e){let t={},n=new Set;for(let r of e){Object.assign(t,r);for(let e of r.manualPureFunctions??[])n.add(e)}return n.size>0?t.manualPureFunctions=[...n]:delete t.manualPureFunctions,t}function composeFunctionTreeshakeOptions(e=[]){return mergeFunctionTreeshakeOptions([Le,...e])}const Re=/(?<![\w$.])process\.env\.__TAILOR_PLATFORM_BUNDLE\b/g,U={name:`tailor-platform-bundle-define`,transform(e){return e.includes(`process.env.__TAILOR_PLATFORM_BUNDLE`)?{code:e.replace(Re,`true`)}:null},resolveId(e){return e===`node:async_hooks`?{id:e,external:!0}:null}},ze=new Set;async function resolveTSConfigWithFallback(e){let t=await tryResolve(e);if(t||e===process.cwd())return t;let n=await tryResolve(process.cwd());return n&&!ze.has(e)&&(ze.add(e),s.warn(`No tsconfig found from "${e}"; falling back to the tsconfig resolved from process.cwd(). Move (or extend) a tsconfig into this directory before v2, when this fallback will be removed.`)),n}async function tryResolve(e){try{return await ce(e)}catch{return}}function createTsconfigLookupCache(){return{tsconfigCache:new Map,contextCache:new Map}}function createTsconfigPathsPlugin(e={}){let{tsconfigCache:t,contextCache:n}=e.cache??createTsconfigLookupCache();return{name:`tailor-tsconfig-paths`,resolveId:{order:`post`,async handler(r,i){if(!i||r.startsWith(`.`)||r.startsWith(`/`)||r.startsWith(`\0`))return null;let a=i.startsWith(`\0`)?e.virtualEntrySourceFile:i;if(!a)return null;let o=getResolutionContext(O.dirname(a),t,n,e.onTsconfigRead);if(!o)return null;let s=o.matcher(r);if(s.length===0||await this.resolve(r,i,{skipSelf:!0}))return null;for(let e of s){let t=await this.resolve(e,i,{skipSelf:!0});if(t)return t}return null}}}}function getResolutionContext(e,t,n,r){let i=n.get(e);if(i!==void 0)return reportTsconfigDependencies(t,r),i;let a=_e(e,`tsconfig.json`,t);reportTsconfigDependencies(t,r);let o=a?.config.compilerOptions?.paths,s=o&&Object.keys(o).length>0?ge(a):null,c=s?{matcher:s}:null;return n.set(e,c),c}function reportTsconfigDependencies(e,t){if(!t)return;let n=new Set,r=new Set;for(let[t,i]of e){let e=dependencyPathFromCacheKey(t);e&&(t.startsWith(`statSync:`)&&isDirectoryStat(i)?n.add(e):r.add(e))}for(let e of r)n.has(e)||t(e)}function dependencyPathFromCacheKey(e){if(e.startsWith(`readFileSync:`)&&e.endsWith(`:utf8`))return e.slice(13,-5);for(let t of[`existsSync:`,`statSync:`])if(e.startsWith(t))return e.slice(t.length)}function isDirectoryStat(e){return typeof e==`object`&&!!e&&`isDirectory`in e&&typeof e.isDirectory==`function`&&e.isDirectory()}function createVirtualEntry(e,t,n=`js`,r){let i=`tailor-entry:${e}.${n}`,a=`\0${i}`;return{input:i,plugin:{name:`tailor-virtual-entry`,async resolveId(e,t){return e===i&&t===void 0?a:t!==a||!r||e.startsWith(`.`)||O.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})},load(e){return e===a?t:null}}}}function createGeneratedEntryResolverPlugin(e,t){let n=O.resolve(e),r=O.join(O.resolve(t),`__tailor_sdk_generated_entry__.js`);return{name:`tailor-generated-entry-resolver`,async resolveId(e,t){return t===void 0||O.resolve(t)!==n||e.startsWith(`.`)||O.isAbsolute(e)||e.startsWith(`\0`)?null:this.resolve(e,r,{skipSelf:!0})}}}async function bundleAuthHooks(e){let{configPath:t,authName:n,handlerAccessPath:r,env:i={},startContext:a,cache:o,inlineSourcemap:l,bundleLogLevel:u=`DEBUG`,baseDir:d,tsconfigCache:f}=e;s.newline(),s.log(`Bundling auth hook for ${c.info(`"${n}"`)}`);let p=O.resolve(t),m=await resolveTSConfigWithFallback(d),h=`auth-hook--${n}--before-login`,g=await withCache({cache:o,kind:`auth-hook`,name:h,sourceFile:p,contextHash:computeBundlerContextHash({sourceFile:p,extraContext:serializeStartContext(a),tsconfig:m,inlineSourcemap:l,bundleLogLevel:u,prefix:JSON.stringify(Object.fromEntries(Object.entries(i).toSorted(([e],[t])=>e.localeCompare(t))))}),async build(e,t){let n=T`
70
70
  import _config from "${p}";
@@ -104,7 +104,7 @@ import{n as e}from"./brand-C8nMKhJC.mjs";import{a as t,i as n,n as r,o as i}from
104
104
  })(${t})`}const Ve=makePrincipalExpr({source:`user`,normalize:!0,fields:{type:{raw:`$raw?.type`},id:`$raw.id`,workspaceId:`$raw.workspace_id ?? $raw.workspaceId`,attributes:`$raw.attribute_map ?? $raw.attributeMap ?? {}`,attributeList:`$raw.attributes ?? []`}}),firstObjectProperty=e=>{let t=P(`stringify-function.ts`,e,{sourceType:`module`});if(t.errors.length>0)return;let n=t.program.body[0],r=n?.type===`ExpressionStatement`&&n.expression.type===`ParenthesizedExpression`?n.expression.expression:void 0;return r?.type===`ObjectExpression`?r.properties[0]:void 0},stringifyFunction=e=>{let t=e.toString().trim();if(firstObjectProperty(`({m: ${t}})`))return t;let n=`({${t}})`,r=firstObjectProperty(n);if(r?.type===`Property`&&r.method&&r.computed)throw Error(`Computed-key method shorthand cannot be converted to a TailorDB script expression. Use an arrow function or function expression instead.`);if(r?.type===`Property`&&r.method&&r.value.type===`FunctionExpression`){let{async:e,generator:t}=r.value,i=n.slice(r.value.start,r.value.end);return`${e?`async `:``}function${t?`*`:``} ${i}`}return t};function formatScriptContext(e,t){return t?`${e} for ${t.tableName}.${t.fieldPath.join(`.`)}`:e===`validate`?e:`hooks`}const convertToScriptExpr=(e,t,n)=>getPrecompiledScriptExpr(e,t)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(t)})`,formatScriptContext(t,n)),convertTypeHookToExpr=(e,t)=>{let n=`typeHook.${t}`;return getPrecompiledScriptExpr(e,n)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(n)})`,`type-hook`)},convertTypeValidateToExpr=e=>getPrecompiledScriptExpr(e,`typeValidate`)||assertParsableExpression(`(${stringifyFunction(e)})(${buildHookCallArgs(`typeValidate`)})`,`type-validate`);function formatFieldLocation(e){return e?`Field "${e.fieldPath.join(`.`)}" on table "${e.tableName}": `:``}function parseFieldConfig(e,t){let n=e.metadata,r=e.type,i=e.rawRelation;if(t&&t.fieldPath.length>1&&n.default!==void 0)throw Error(`${formatFieldLocation(t)}.default() cannot be used on nested inner fields`);if(t&&t.fieldPath.length>1&&n.hooks)throw Error(`${formatFieldLocation(t)}.hooks() cannot be used on nested inner fields`);if(r===`enum`&&(n.allowedValues??[]).length===0)throw Error(`${formatFieldLocation(t)}enum fields must define at least one allowed value`);let a=e.fields;return{type:r,...n,rawRelation:i,...r===`nested`&&a&&Object.keys(a).length>0?{fields:Object.entries(a).reduce((e,[n,r])=>(e[n]=parseFieldConfig(r,t&&{...t,fieldPath:[...t.fieldPath,n]}),e),{})}:{},validate:n.validate?.map(e=>({script:{expr:convertToScriptExpr(e,`validate`,t)},errorMessage:``})),hooks:n.hooks?{create:n.hooks.create?{expr:convertToScriptExpr(n.hooks.create,`hooks.create`,t)}:void 0,update:n.hooks.update?{expr:convertToScriptExpr(n.hooks.update,`hooks.update`,t)}:void 0}:void 0,serial:n.serial?{start:n.serial.start,maxValue:n.serial.maxValue,format:`format`in n.serial?n.serial.format:void 0}:void 0}}function isObjectPermissionFormat(e){return typeof e==`object`&&!!e&&`conditions`in e}function isSingleConditionFormat(e){return e.length>=2&&typeof e[1]==`string`}function normalizeOperand(e){if(e===null)throw Error(`Invalid permission operand: null`);if(typeof e==`object`&&!Array.isArray(e)&&`user`in e){let t=e.user;return{user:t===`id`?`_id`:t}}return e}function createPermissionNormalizer(e){function normalizeConditions(t){return t.map(t=>{let[n,r,i]=t;return[normalizeOperand(n),e[r],normalizeOperand(i)]})}function normalizeActionPermission(e){if(isObjectPermissionFormat(e)){let t=e.conditions;return{conditions:normalizeConditions(isSingleConditionFormat(t)?[t]:t),permit:e.permit?`allow`:`deny`,description:e.description}}if(!Array.isArray(e))throw Error(`Invalid permission format`);if(isSingleConditionFormat(e)){let[t,n,r,i]=[...e,!0];return{conditions:normalizeConditions([[t,n,r]]),permit:i?`allow`:`deny`}}let t=[],n=!0;for(let r of e){if(typeof r==`boolean`){n=r;continue}t.push(r)}return{conditions:normalizeConditions(t),permit:n?`allow`:`deny`}}return{normalizeConditions,normalizeActionPermission}}function hasOmittedPermit(e){return isObjectPermissionFormat(e)&&e.permit===void 0}const{normalizeConditions:He,normalizeActionPermission:Ue}=createPermissionNormalizer({"=":`eq`,"!=":`ne`,in:`in`,"not in":`nin`,hasAny:`hasAny`,"not hasAny":`nhasAny`});function normalizePermission(e){return Object.keys(e).reduce((t,n)=>(t[n]=e[n].map(e=>normalizeActionPermission(e)),t),{})}function normalizeGqlPermission(e){return e.map(e=>normalizeGqlPolicy(e))}function normalizeGqlPolicy(e){return{conditions:He(e.conditions),actions:e.actions===`all`?[`all`]:e.actions,permit:e.permit?`allow`:`deny`,description:e.description}}function parsePermissions(e){return{...e.record&&{record:normalizePermission(e.record)},...e.gql&&{gql:normalizeGqlPermission(e.gql)}}}function normalizeActionPermission(e){return Ue(e)}function findOmittedPermitRules(e){let t=[],n=e.record;if(n)for(let e of Object.keys(n))n[e].forEach((n,r)=>{hasOmittedPermit(n)&&t.push(`record.${String(e)}[${r}]`)});let r=e.gql;return r&&r.forEach((e,n)=>{e.permit===void 0&&t.push(`gql[${n}]`)}),t}function isGqlOperationsFullyDisabled(e){return e?e.create===!1&&e.update===!1&&e.delete===!1&&e.read===!1:!1}function findMissingPermissionConfig(e,t){return{missingPermission:!e.record,missingGqlPermission:!e.gql&&!isGqlOperationsFullyDisabled(t)}}function parseTypes(e,t,n){let r=createRecord(),i=new Set(Object.keys(e));for(let[t,a]of Object.entries(e))r[t]=parseTailorDBType(a,i,e,n);return buildBackwardRelationships(r,t,n),validatePluralFormUniqueness(r,t,n),r}function parseTailorDBType(e,t,n,r){let i=e.metadata,a=i.settings?.pluralForm||F.pluralize(e.name),o=formatTypeSourceLocation(getTypeSourceInfo(r,e.name)),s=createRecord(),c=createRecord();for(let[r,a]of Object.entries(e.fields)){let l={tableName:e.name,fieldName:r,allTableNames:t},u=parseFieldConfig(a,{tableName:e.name,fieldPath:[r]}),d=u.rawRelation;if(d){if(h(d,l),[`n-1`,`manyToOne`,`N-1`].includes(d.type)&&u.unique)throw Error(`Field "${r}" on table "${e.name}": cannot set unique on n-1 (manyToOne) relation. Use 1-1 (oneToOne) relation instead, or remove the unique constraint.`);let t=_(d,l,u.array);u=p(u,t)}if(u.array&&u.index)throw Error(`Field "${r}" on table "${e.name}": index cannot be set on array fields`);if(u.array&&u.unique)throw Error(`Field "${r}" on table "${e.name}": unique cannot be set on array fields`);let f={name:r,config:u},m=d?b(d,l):void 0;if(m){f.relation={...m};let t=m.forwardName;if(t.length===0)throw Error(`Forward relation name for field "${r}" on table "${e.name}"${o} cannot be empty. Use the "as" option in .relation({ toward: { as: ... } }) to specify a non-empty name.`);let a=c[t];if(a)throw Error(`Forward relation name "${t}" on table "${e.name}"${o} is duplicated between fields "${a.targetField}" and "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a unique name.`);if(Object.hasOwn(e.fields,t)){let n=t===r?`Forward relation name "${t}" on table "${e.name}"${o} is the same as its own relation field "${r}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`:`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with existing field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`;throw Error(n)}if(Object.hasOwn(i.files,t))throw Error(`Forward relation name "${t}" from field "${r}" on table "${e.name}"${o} conflicts with files field "${t}". Use the "as" option in .relation({ toward: { as: ... } }) to specify a different name.`);let s=n[m.targetType];c[t]={name:t,targetType:m.targetType,targetField:r,sourceField:m.key,isArray:!1,description:s?.metadata.description||``}}s[r]=f}return{name:e.name,pluralForm:a,description:i.description,fields:s,forwardRelationships:c,backwardRelationships:createRecord(),settings:i.settings??{},permissions:parsePermissions(i.permissions),indexes:i.indexes,files:i.files,...i.typeHook&&{typeHookExpr:{...typeof i.typeHook.create==`function`&&{create:convertTypeHookToExpr(i.typeHook.create,`create`)},...typeof i.typeHook.update==`function`&&{update:convertTypeHookToExpr(i.typeHook.update,`update`)}}},...typeof i.typeValidate==`function`&&{typeValidateExpr:convertTypeValidateToExpr(i.typeValidate)}}}function buildBackwardRelationships(e,t,n){let r=Object.create(null);for(let t of Object.keys(e))r[t]=Object.create(null);for(let[t,n]of Object.entries(e))for(let[i,a]of Object.entries(e))for(let[e,o]of Object.entries(a.fields))if(o.relation&&o.relation.targetType===t){let s=o.relation.backwardName;if(!s){let e=F.camelize(i,!0);s=o.relation.unique?F.singularize(e):F.pluralize(e)}let c=r[t];if(c===void 0)throw Error(`backward name sources not initialized for table: ${t}`);c[s]||(c[s]=[]);let l=c[s];if(l===void 0)throw Error(`backward name sources entry not initialized for: ${s}`);l.push({sourceType:i,fieldName:e}),n.backwardRelationships[s]={name:s,targetType:i,targetField:e,sourceField:o.relation.key,isArray:!o.relation.unique,description:a.description||``}}let i=[];for(let[t,a]of Object.entries(r)){let r=e[t];if(r===void 0)throw Error(`type not found: ${t}`);let o=formatTypeSourceLocation(getTypeSourceInfo(n,t));for(let[e,s]of Object.entries(a)){if(s.length>1){let r=s.map(e=>{let t=formatTypeSourceLocation(getTypeSourceInfo(n,e.sourceType));return`${e.sourceType}.${e.fieldName}${t}`}).join(`, `);i.push(`Backward relation name "${e}" on table "${t}" is duplicated from: ${r}. Use the "backward" option in .relation() to specify unique names.`)}if(Object.hasOwn(r.fields,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with existing field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(r.files&&Object.hasOwn(r.files,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Backward relation name "${e}" from ${r.sourceType}.${r.fieldName}${a} conflicts with files field "${e}" on table "${t}"${o}. Use the "backward" option in .relation() to specify a different name.`)}if(Object.hasOwn(r.forwardRelationships,e)){let r=s[0];if(r===void 0)throw Error(`no source found for backward name: ${e}`);let a=formatTypeSourceLocation(getTypeSourceInfo(n,r.sourceType));i.push(`Relation name "${e}" on table "${t}"${o} is used by both a forward relationship and a backward relationship from ${r.sourceType}.${r.fieldName}${a}. Use the "as" option in .relation({ toward: { as: ... } }) or the "backward" option in .relation() to specify unique names.`)}}}if(i.length>0)throw Error(`Backward relation name conflicts detected in TailorDB service "${t}".\n${i.map(e=>` - ${e}`).join(`
105
105
  `)}`)}function validatePluralFormUniqueness(e,t,n){let r=[];for(let[,t]of Object.entries(e)){let e=F.camelize(t.name,!0);if(e===F.camelize(t.pluralForm,!0)){let i=formatTypeSourceLocation(getTypeSourceInfo(n,t.name));r.push(`Table "${t.name}"${i} has identical singular and plural query names "${e}". Use db.table(["${t.name}", "UniquePluralForm"], {...}) to set a unique pluralForm.`)}}let i=new Map;for(let t of Object.values(e)){let e=F.camelize(t.name,!0),n=F.camelize(t.pluralForm,!0),r=i.get(e)??[];if(r.push({tableName:t.name,kind:`singular`}),i.set(e,r),e!==n){let e=i.get(n)??[];e.push({tableName:t.name,kind:`plural`}),i.set(n,e)}}let a=[...i].filter(([,e])=>e.length>1);for(let[e,t]of a){let i=t.map(e=>{let t=formatTypeSourceLocation(getTypeSourceInfo(n,e.tableName));return`"${e.tableName}"${t} (${e.kind})`}).join(`, `);r.push(`GraphQL query field "${e}" conflicts between: ${i}`)}if(r.length>0)throw Error(`GraphQL field name conflicts detected in TailorDB service "${t}".\n${r.map(e=>` - ${e}`).join(`
106
106
  `)}`)}function getTypeSourceInfo(e,t){return e&&Object.hasOwn(e,t)?e[t]:void 0}function formatTypeSourceLocation(e){return e?ae(e)?` (plugin: ${e.pluginId})`:` (${e.filePath})`:``}function createRecord(){return Object.create(null)}const We=new Set([`typeAnnotation`,`typeParameters`,`returnType`,`superTypeArguments`,`typeArguments`]);function collectBindingsFromPattern(e,t){switch(e.type){case`Identifier`:t.add(e.name);break;case`ObjectPattern`:for(let n of e.properties)n.type===`RestElement`?collectBindingsFromPattern(n.argument,t):collectBindingsFromPattern(n.value,t);break;case`ArrayPattern`:for(let n of e.elements)n&&(n.type===`RestElement`?collectBindingsFromPattern(n.argument,t):collectBindingsFromPattern(n,t));break;case`AssignmentPattern`:collectBindingsFromPattern(e.left,t)}}function isBindingPattern(e){return e.type!==`TSParameterProperty`}function isBoundInScope(e,t){for(let n=e;n;n=n.parent)if(n.bindings.has(t))return!0;return!1}const Ge=new Set([`!==`,`!=`]),Ke=new Set([`===`,`==`]);function staticStringValue(e){if(e.type===`Literal`&&typeof e.value==`string`)return e.value;if(e.type===`TemplateLiteral`&&e.expressions.length===0&&e.quasis.length===1)return e.quasis[0]?.value.cooked??void 0}function typeofGuardTarget(e){if(e.type!==`BinaryExpression`)return;let{left:t,right:n,operator:r}=e,[i,a]=t.type===`UnaryExpression`&&t.operator===`typeof`&&t.argument.type===`Identifier`?[t,n]:n.type===`UnaryExpression`&&n.operator===`typeof`&&n.argument.type===`Identifier`?[n,t]:[void 0,void 0];if(!i)return;let o=staticStringValue(a);if(o===void 0)return;let s=o===`undefined`;if(Ge.has(r)&&s||Ke.has(r)&&!s)return i.argument.name}function walkGuardedChain(e,t,n){return e.type===`Identifier`?e.name===t:e.type===`MemberExpression`&&walkGuardedChain(e.object,t,n)?(e.computed&&n(e.property),!0):!1}function findUndefinedReferences(e){let{program:t,errors:n}=P(`_.js`,e);if(n.length>0){let e=n.map(e=>` - ${e.message}`).join(`
107
- `);throw Error(`Failed to parse code for free-variable analysis.\nParse errors:\n${e}`)}let r=[],i={bindings:new Set,parent:null},walk=e=>{if(!e)return;switch(e.type){case`VariableDeclarator`:collectBindingsFromPattern(e.id,i.bindings),walk(e.init);return;case`ImportDeclaration`:for(let t of e.specifiers)i.bindings.add(t.local.name);return;case`FunctionDeclaration`:case`FunctionExpression`:{e.type===`FunctionDeclaration`&&e.id&&i.bindings.add(e.id.name);let t={bindings:new Set,parent:i};e.type===`FunctionExpression`&&e.id&&t.bindings.add(e.id.name);for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ArrowFunctionExpression`:{let t={bindings:new Set,parent:i};for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ClassDeclaration`:case`ClassExpression`:e.id&&i.bindings.add(e.id.name),walk(e.superClass),walk(e.body);return;case`CatchClause`:e.param&&collectBindingsFromPattern(e.param,i.bindings),walk(e.body);return;case`MemberExpression`:walk(e.object),e.computed&&walk(e.property);return;case`UnaryExpression`:if(e.operator===`typeof`&&e.argument.type===`Identifier`)return;walk(e.argument);return;case`LogicalExpression`:{let t=e.operator===`&&`?typeofGuardTarget(e.left):void 0;if(walk(e.left),t&&walkGuardedChain(e.right,t,walk))return;walk(e.right);return}case`Property`:e.computed&&walk(e.key),walk(e.value);return;case`MethodDefinition`:case`TSAbstractMethodDefinition`:case`PropertyDefinition`:case`TSAbstractPropertyDefinition`:case`AccessorProperty`:case`TSAbstractAccessorProperty`:for(let t of e.decorators)walk(t.expression);e.computed&&walk(e.key),walk(e.value);return;case`LabeledStatement`:walk(e.body);return;case`Identifier`:r.push({name:e.name,scope:i});return}let t=e;for(let[e,n]of Object.entries(t))if(!(e===`type`||We.has(e))){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};walk(t);let a=new Set;for(let{name:e,scope:t}of r)!isBoundInScope(t,e)&&!te.has(e)&&a.add(e);return a}function toScriptFunction(e,t){if(typeof e==`function`&&!getPrecompiledScriptExpr(e,t))return e}function collectScriptTargets(e){let t=[],collectFieldTargets=e=>{let n=e.metadata,r=toScriptFunction(n.hooks?.create,`hooks.create`);r&&t.push({fn:r,kind:`hooks.create`});let i=toScriptFunction(n.hooks?.update,`hooks.update`);i&&t.push({fn:i,kind:`hooks.update`});for(let e of n.validate??[]){let n=toScriptFunction(e,`validate`);n&&t.push({fn:n,kind:`validate`})}if(e.type===`nested`&&e.fields)for(let t of Object.values(e.fields))collectFieldTargets(t)};for(let t of Object.values(e.fields))collectFieldTargets(t);if(e.metadata.typeHook)for(let n of[`create`,`update`]){let r=`typeHook.${n}`,i=toScriptFunction(e.metadata.typeHook[n],r);i&&t.push({fn:i,kind:r})}let n=toScriptFunction(e.metadata.typeValidate,`typeValidate`);return n&&t.push({fn:n,kind:`typeValidate`}),t}function collectIdentifierNames(e){let{program:t}=P(`_.ts`,e),n=new Set,walk=e=>{if(!e||typeof e!=`object`)return;let t=e;t.type===`Identifier`&&typeof t.name==`string`&&n.add(t.name);for(let[e,n]of Object.entries(t))if(!(e===`property`&&t.type===`MemberExpression`&&!t.computed)&&!(e===`key`&&t.type===`Property`&&!t.computed)&&!We.has(e)){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};return walk(t),n}function collectSourceBindings(e){let t=ue(e,`utf-8`),{program:n}=P(e,t),r=new Map;for(let e of n.body)if(e.type===`ImportDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.specifiers)r.set(e.local.name,{name:e.local.name,sourceText:i,kind:`import`})}else if(e.type===`VariableDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.declarations)e.id.type===`Identifier`&&r.set(e.id.name,{name:e.id.name,sourceText:i,kind:`declaration`})}else if(e.type===`FunctionDeclaration`){let n=e;if(n.id){let e=t.slice(n.start,n.end);r.set(n.id.name,{name:n.id.name,sourceText:e,kind:`declaration`})}}else if(e.type===`ExportNamedDeclaration`){let n=e.declaration;if(!n)continue;if(n.type===`VariableDeclaration`){let e=n,i=t.slice(e.start,e.end);for(let t of e.declarations)t.id.type===`Identifier`&&r.set(t.id.name,{name:t.id.name,sourceText:i,kind:`declaration`})}else if(n.type===`FunctionDeclaration`){let e=n;if(e.id){let n=t.slice(e.start,e.end);r.set(e.id.name,{name:e.id.name,sourceText:n,kind:`declaration`})}}}return r}function resolveNeededBindings(e,t){let n=new Set,r=new Set,i=[],a=new Set,resolveVars=e=>{for(let o of e){if(a.has(o))continue;a.add(o);let e=t.get(o);if(!e){i.push(o);continue}if(e.kind===`import`)n.add(e.sourceText);else{let n=collectIdentifierNames(e.sourceText),i=new Set;for(let e of n)e!==o&&t.has(e)&&i.add(e);resolveVars(i),r.add(e.sourceText)}}};return resolveVars(e),{imports:[...n],declarations:[...r],unresolved:i}}function buildPrecompiledExpr(e,t){return`(() => {
107
+ `);throw Error(`Failed to parse code for free-variable analysis.\nParse errors:\n${e}`)}let r=[],i={bindings:new Set,parent:null},walk=e=>{if(!e)return;switch(e.type){case`VariableDeclarator`:collectBindingsFromPattern(e.id,i.bindings),walk(e.init);return;case`ImportDeclaration`:for(let t of e.specifiers)i.bindings.add(t.local.name);return;case`FunctionDeclaration`:case`FunctionExpression`:{e.type===`FunctionDeclaration`&&e.id&&i.bindings.add(e.id.name);let t={bindings:new Set,parent:i};e.type===`FunctionExpression`&&e.id&&t.bindings.add(e.id.name);for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ArrowFunctionExpression`:{let t={bindings:new Set,parent:i};for(let n of e.params)isBindingPattern(n)&&collectBindingsFromPattern(n,t.bindings);let n=i;i=t;for(let t of e.params)isBindingPattern(t)&&walk(t);walk(e.body),i=n;return}case`ClassDeclaration`:case`ClassExpression`:e.id&&i.bindings.add(e.id.name),walk(e.superClass),walk(e.body);return;case`CatchClause`:e.param&&collectBindingsFromPattern(e.param,i.bindings),walk(e.body);return;case`MemberExpression`:walk(e.object),e.computed&&walk(e.property);return;case`UnaryExpression`:if(e.operator===`typeof`&&e.argument.type===`Identifier`)return;walk(e.argument);return;case`LogicalExpression`:{let t=e.operator===`&&`?typeofGuardTarget(e.left):void 0;if(walk(e.left),t&&walkGuardedChain(e.right,t,walk))return;walk(e.right);return}case`Property`:e.computed&&walk(e.key),walk(e.value);return;case`MethodDefinition`:case`TSAbstractMethodDefinition`:case`PropertyDefinition`:case`TSAbstractPropertyDefinition`:case`AccessorProperty`:case`TSAbstractAccessorProperty`:for(let t of e.decorators)walk(t.expression);e.computed&&walk(e.key),walk(e.value);return;case`LabeledStatement`:walk(e.body);return;case`Identifier`:r.push({name:e.name,scope:i});return}let t=e;for(let[e,n]of Object.entries(t))if(!(e===`type`||We.has(e))){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};walk(t);let a=new Set;for(let{name:e,scope:t}of r)!isBoundInScope(t,e)&&!te.has(e)&&a.add(e);return a}function toScriptFunction(e,t){if(typeof e==`function`&&!getPrecompiledScriptExpr(e,t))return e}function collectScriptTargets(e){let t=[],collectFieldTargets=e=>{let n=e.metadata,r=toScriptFunction(n.hooks?.create,`hooks.create`);r&&t.push({fn:r,kind:`hooks.create`});let i=toScriptFunction(n.hooks?.update,`hooks.update`);i&&t.push({fn:i,kind:`hooks.update`});for(let e of n.validate??[]){let n=toScriptFunction(e,`validate`);n&&t.push({fn:n,kind:`validate`})}if(e.type===`nested`&&e.fields)for(let t of Object.values(e.fields))collectFieldTargets(t)};for(let t of Object.values(e.fields))collectFieldTargets(t);if(e.metadata.typeHook)for(let n of[`create`,`update`]){let r=`typeHook.${n}`,i=toScriptFunction(e.metadata.typeHook[n],r);i&&t.push({fn:i,kind:r})}let n=toScriptFunction(e.metadata.typeValidate,`typeValidate`);return n&&t.push({fn:n,kind:`typeValidate`}),t}function collectIdentifierNames(e){let{program:t}=P(`_.ts`,e),n=new Set,walk=e=>{if(!e||typeof e!=`object`)return;let t=e;t.type===`Identifier`&&typeof t.name==`string`&&n.add(t.name);for(let[e,n]of Object.entries(t))if((e!==`property`||t.type!==`MemberExpression`||t.computed)&&(e!==`key`||t.type!==`Property`||t.computed)&&!We.has(e)){if(Array.isArray(n))for(let e of n)walk(e);else n&&typeof n==`object`&&`type`in n&&walk(n)}};return walk(t),n}function collectSourceBindings(e){let t=ue(e,`utf-8`),{program:n}=P(e,t),r=new Map;for(let e of n.body)if(e.type===`ImportDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.specifiers)r.set(e.local.name,{name:e.local.name,sourceText:i,kind:`import`})}else if(e.type===`VariableDeclaration`){let n=e,i=t.slice(n.start,n.end);for(let e of n.declarations)e.id.type===`Identifier`&&r.set(e.id.name,{name:e.id.name,sourceText:i,kind:`declaration`})}else if(e.type===`FunctionDeclaration`){let n=e;if(n.id){let e=t.slice(n.start,n.end);r.set(n.id.name,{name:n.id.name,sourceText:e,kind:`declaration`})}}else if(e.type===`ExportNamedDeclaration`){let n=e.declaration;if(!n)continue;if(n.type===`VariableDeclaration`){let e=n,i=t.slice(e.start,e.end);for(let t of e.declarations)t.id.type===`Identifier`&&r.set(t.id.name,{name:t.id.name,sourceText:i,kind:`declaration`})}else if(n.type===`FunctionDeclaration`){let e=n;if(e.id){let n=t.slice(e.start,e.end);r.set(e.id.name,{name:e.id.name,sourceText:n,kind:`declaration`})}}}return r}function resolveNeededBindings(e,t){let n=new Set,r=new Set,i=[],a=new Set,resolveVars=e=>{for(let o of e){if(a.has(o))continue;a.add(o);let e=t.get(o);if(!e){i.push(o);continue}if(e.kind===`import`)n.add(e.sourceText);else{let n=collectIdentifierNames(e.sourceText),i=new Set;for(let e of n)e!==o&&t.has(e)&&i.add(e);resolveVars(i),r.add(e.sourceText)}}};return resolveVars(e),{imports:[...n],declarations:[...r],unresolved:i}}function buildPrecompiledExpr(e,t){return`(() => {
108
108
  const module = { exports: {} };
109
109
  const exports = module.exports;
110
110
  ${e}\n return module.exports.main(${t});\n})()`}function buildMinimalEntryFromResolved(e,t,n,r,i=!1){let a=se(r,`..`).replace(/\\/g,`/`);return[...e.map(e=>e.replace(/from\s+["'](\.[^"']+)["']/g,(e,t)=>`from "${se(a,t).replace(/\\/g,`/`)}"`)),...t,i?`export function main(...args) { return (${n})(...args); }`:`export function main(input) { return (${n})(input); }`].join(`
@@ -185,7 +185,7 @@ globalThis.transform = __adapter.output;
185
185
  };
186
186
 
187
187
  export { $tailor_resolver_body as main };
188
- `,f=createVirtualEntry(`resolver:${n.name}`,d,`js`,o),p=createStartTransformPlugin(a),m=[f.plugin];p&&m.push(p),m.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:l}),U,...e);let h=createBundleLog({tsconfig:r}),g=await N.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:r,plugins:m,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(c)]),...h.options});h.assertAllResolved();let _=g.output[0].code;return assertNoForbiddenRuntimeGlobals(_,`Resolver "${n.name}"`),_}});return[n.name,f]}function parseResolverDefaultPermission(e){let{namespace:t,config:n}=e;if(n.defaultPermission===void 0)return;let r=ot.safeParse(n.defaultPermission);if(!r.success)throw Error(`Invalid \`defaultPermission\` for resolver namespace "${t}": `+r.error.issues.map(e=>e.message).join(`; `));return r.data}function resolveResolverDefaultPermissionForFile(e){let{config:t,filePath:n,baseDir:r}=e;if(!t)return;let i=O.resolve(n),a=[];for(let[e,n]of Object.entries(t))`external`in n||m(n,r).some(e=>O.resolve(e)===i)&&a.push({namespace:e,config:n});if(a.length>1)throw Error(`Resolver ${O.relative(process.cwd(),i)} matches more than one resolver namespace: ${a.map(e=>`"${e.namespace}"`).join(`, `)}. Each namespace applies its own \`defaultPermission\`, so narrow the \`files\`/\`ignores\` patterns until exactly one namespace claims this file.`);let[o]=a;return o?parseResolverDefaultPermission(o):void 0}function createResolverService(t,n,r){let i={},a=parseResolverDefaultPermission({namespace:t,config:n}),o=!1,loadResolverForFile=async t=>{try{let n=await u(t),r=X.safeParse(n.default);if(r.success){let e=O.relative(process.cwd(),t);return s.log(`Resolver: ${c.successBright(`"${r.data.name}"`)} loaded from ${c.path(e)}`),i[t]=r.data,r.data}if(e(n.default,`resolver`))throw r.error}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`Failed to load resolver from ${c.bold(n)}`),s.error(String(e)),e}};return{namespace:t,config:n,defaultPermission:a,get resolvers(){return i},loadResolvers:async()=>{if(o||n.files.length===0)return;let e=m(n,r);s.log(`Found ${c.highlight(e.length.toString())} resolver files for service ${c.highlight(`"${t}"`)}`),await Promise.all(e.map(e=>loadResolverForFile(e))),assertUniqueResolverNames(i,t),warnUndeclaredPermissions({namespace:t,defaultPermission:a,resolvers:i}),o=!0}}}function warnUndeclaredPermissions(e){let{namespace:t,defaultPermission:n,resolvers:r}=e;if(n!==void 0)return;let i=Object.values(r),a=i.filter(e=>e.permission===void 0);if(a.length===0)return;s.warn(`Resolver namespace ${c.highlight(`"${t}"`)}: ${a.length} of ${i.length} resolvers declare no \`permission\`, so anonymous callers can reach them. Set \`defaultPermission\` on the namespace, or declare \`permission\` on each resolver ("allowAnonymous" if public access is intended).`);let o=a.map(e=>e.name).toSorted();s.debug(` Resolvers without \`permission\`: ${o.join(`, `)}`)}function assertUniqueResolverNames(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=O.relative(process.cwd(),r),a=n.get(i.name);if(a)throw Error(`Duplicate resolver name "${i.name}" found in namespace "${t}":\n - ${a}\n - ${e}\nEach resolver must have a unique name within a namespace.`);n.set(i.name,e)}}function findVariableDeclarationsByName(e){let t=new Map;for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type!==`VariableDeclaration`)continue;let r=e;for(let e of r.declarations)e.id.type===`Identifier`&&t.set(e.id.name,{start:n.start,end:n.end})}return t}function findWorkflowDefaultExport(e){let t=collectSdkBindings(e,`createWorkflow`);for(let n of e.body)if(n.type===`ExportDefaultDeclaration`){let e=n,r=e.declaration;if(isSdkFunctionCall(r,t,`createWorkflow`)||r.type===`Identifier`)return{start:e.start,end:e.end}}return null}function transformWorkflowSource(e,t,n,r){let{program:i}=P(`input.ts`,e),a=findAllJobs(i,e);if(!a.some(e=>e.name===t))return e;let o=findVariableDeclarationsByName(i),s=[],c=new Set;for(let n of a)if(n.name!==t){if(n.statementRange&&!c.has(n.statementRange.start)){let t=findStatementEnd(e,n.statementRange.end);c.add(n.statementRange.start),s.push({start:n.statementRange.start,end:t,text:``})}else n.statementRange||(c.add(n.bodyValueRange.start),s.push({start:n.bodyValueRange.start,end:n.bodyValueRange.end,text:`() => {}`}))}if(r)for(let t of r){if(t===n)continue;let r=o.get(t);if(r&&!c.has(r.start)){let t=findStatementEnd(e,r.end);c.add(r.start),s.push({start:r.start,end:t,text:``})}}let l=findWorkflowDefaultExport(i);if(l&&!c.has(l.start)){let t=findStatementEnd(e,l.end);c.add(l.start),s.push({start:l.start,end:t,text:``})}return applyReplacements(e,s)}function safeRealpath(e){let t=O.resolve(e);try{return A.realpathSync(t)}catch(e){return s.debug(`realpathSync failed for ${t}: ${e instanceof Error?e.message:e}`),t}}var WorkflowJobDetectionError=class extends Error{};function isExecJobFunctionCallee(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==`MemberExpression`)return!1;let n=t.property;if(n?.type!==`Identifier`||n.name!==`execJobFunction`)return!1;let r=t.object;if(r?.type!==`MemberExpression`)return!1;let i=r.property;if(i?.type!==`Identifier`||i.name!==`workflow`)return!1;let a=r.object;return a?.type===`Identifier`&&a.name===`tailor`}function extractStaticStringValue(e){if(!e||typeof e!=`object`)return;let t=e;if(t.type===`Literal`&&typeof t.value==`string`)return t.value;if(t.type===`TemplateLiteral`){let e=t.quasis,n=t.expressions;if(e?.length===1&&(n?.length??0)===0)return e[0]?.value?.cooked}}const st=new Set([`@tailor-platform/sdk/runtime`,`@tailor-platform/sdk/runtime/workflow`]);function collectRuntimeWorkflowImportBindings(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source;if(!(typeof e?.value!=`string`||!st.has(e.value)))for(let e of n.specifiers??[]){if(e.type!==`ImportSpecifier`||e.importKind===`type`)continue;let n=getModuleExportName(e.imported),r=getModuleExportName(e.local);n===`workflow`&&r&&t.add(r)}}return t}function isDirectExecJobFunctionCallee(e,t){if(isExecJobFunctionCallee(e))return!0;if(!e||typeof e!=`object`)return!1;let n=e;if(n.type!==`MemberExpression`)return!1;let r=n.property;if(r?.type!==`Identifier`||r.name!==`execJobFunction`)return!1;let i=n.object;return i?.type===`Identifier`&&t.has(i.name)}function findDirectExecJobFunctionCalls(e){let t=collectRuntimeWorkflowImportBindings(e),n=[];function walk(e){if(!(!e||typeof e!=`object`)){if(e.type===`CallExpression`&&isDirectExecJobFunctionCallee(e.callee,t)){let t=e.arguments;n.push({targetName:extractStaticStringValue(t?.[0])})}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(e),n}function buildDirectExecJobFunctionErrorMessage(e,t){return t.targetName===void 0?`Workflow file ${e} calls execJobFunction(...) directly with a job name that isn't a string literal, so the target can't be resolved at build time. Call the target job's own .start(...) method from inside a job body instead of calling execJobFunction directly.`:`Workflow file ${e} calls execJobFunction("${t.targetName}", ...) directly. A direct call is never recognized as a dependency, so "${t.targetName}" would silently be dropped from the bundle unless something else happens to reference it. Call the "${t.targetName}" job's .start(...) method from inside a job body instead.`}function collectExecJobFunctionTargets(e){let{program:t,errors:n}=P(`input.js`,e);if(n.length>0)throw new WorkflowJobDetectionError(`Failed to parse bundled job code while checking for missed dependencies: ${n.map(e=>e.message).join(`; `)}`);let r=[];function walk(e){if(!(!e||typeof e!=`object`)){if(e.type===`CallExpression`&&isExecJobFunctionCallee(e.callee)){let t=e.arguments,n=extractStaticStringValue(t?.[0]);n!==void 0&&r.push(n)}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(t),r}function validateBundledDependencies(e,t){let n=new Set(t);for(let[t,r]of e){let e;try{e=collectExecJobFunctionTargets(r)}catch(e){throw new WorkflowJobDetectionError(`Failed to check the bundled output of workflow job "${t}" for missed dependencies: ${e instanceof Error?e.message:String(e)}`)}for(let r of e)if(!n.has(r))throw new WorkflowJobDetectionError(`Workflow job "${t}" calls execJobFunction("${r}", ...) — usually the result of a rewritten "${r}" job .start() call — but "${r}" was not detected as a dependency and is not included in the bundle. Call the "${r}" job's .start() method from inside the body of workflow job "${t}" (a nested function inside body works too), or make sure the file containing the call is covered by the workflow service's "files" pattern.`)}}async function bundleWorkflowJobs(e,t,n={},r,i,a,o,l=`DEBUG`,u){if(e.length===0)return s.warn(`No workflow jobs to bundle`),{mainJobDeps:{},usedJobNames:[],bundledCode:new Map};let{usedJobs:d,mainJobDeps:f}=await filterUsedJobs(e,t,r);s.newline(),s.log(`Bundling ${c.highlight(d.length.toString())} files for ${c.info(`"workflow-job"`)}`);let p=await resolveTSConfigWithFallback(i),m=await withBundleConcurrency(d,e=>bundleSingleJob(e,d,p,n,r,a,o,l,u)),h=new Map;for(let[e,t]of m)h.set(e,t);return validateBundledDependencies(h,d.map(e=>e.name)),s.log(`${c.success(`Bundled`)} ${c.info(`"workflow-job"`)}`),{mainJobDeps:f,usedJobNames:d.map(e=>e.name),bundledCode:h}}async function filterUsedJobs(e,t,n){if(e.length===0||t.length===0)return{usedJobs:[],mainJobDeps:{}};let r=new Map;for(let t of e){let e=r.get(t.sourceFile)||[];e.push(t),r.set(t.sourceFile,e)}let i=new Map(r),a=new Set([...r.keys()].map(safeRealpath));for(let e of n.modules.values())a.has(safeRealpath(e.sourceFile))||i.set(e.sourceFile,[]);let o=new Map,s=await Promise.all(Array.from(i.entries()).map(async([e,t])=>{try{let r=await A.promises.readFile(e,`utf-8`),{program:i,errors:a}=P(e,r);if(a.length>0)throw new WorkflowJobDetectionError(`Failed to parse ${e}: ${a.map(e=>e.message).join(`; `)}`);let[o]=findDirectExecJobFunctionCalls(i);if(o)throw new WorkflowJobDetectionError(buildDirectExecJobFunctionErrorMessage(e,o));let s=findAllJobs(i,r),c=detectResolvedStartCalls(i,r,n,e),l=[];for(let n of t){let t=s.find(e=>e.name===n.name);if(!t)throw new WorkflowJobDetectionError(`Workflow job "${n.name}" (export "${n.exportName}" in ${e}) could not be statically detected: createWorkflowJob's "name" must be a string literal and "body" must be a function expression. Dynamic or computed values (e.g. body: someWrapper(fn)) cannot be bundled and would be silently dropped.`);let r=new Set;for(let e of c)e.kind===`job`&&e.callRange.start>=t.bodyValueRange.start&&e.callRange.end<=t.bodyValueRange.end&&r.add(e.targetName);r.size>0&&l.push({jobName:n.name,deps:r})}for(let t of c)if(t.kind===`job`&&!s.some(e=>t.callRange.start>=e.bodyValueRange.start&&t.callRange.end<=e.bodyValueRange.end))throw new WorkflowJobDetectionError(`Call to job "${t.targetName}".start() in ${e} is not inside any workflow job's body: it was factored into a function defined outside the calling job's body. Dependency detection only sees .start() calls lexically inside a job body, so this call would silently drop "${t.targetName}" from the bundle. Move the call to a function defined inside the calling job's body.`);return l}catch(e){if(e instanceof WorkflowJobDetectionError)throw e;return[]}}));for(let e of s)for(let{jobName:t,deps:n}of e)o.set(t,n);let c=new Set,l={};function collectDeps(e,t){if(t.has(e))return;t.add(e);let n=o.get(e);if(n)for(let e of n)collectDeps(e,t)}for(let e of t){let t=new Set;collectDeps(e,t),l[e]=Array.from(t);for(let e of t)c.add(e)}return{usedJobs:e.filter(e=>c.has(e.name)),mainJobDeps:l}}async function bundleSingleJob(e,t,n,r,i,a,o,s=`DEBUG`,c){let l=serializeStartContext(i),u=JSON.stringify(Object.fromEntries(Object.entries(r).toSorted(([e],[t])=>e.localeCompare(t)))),d=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:l,tsconfig:n,inlineSourcemap:o,bundleLogLevel:s,prefix:u}),f=await withCache({cache:a,kind:`workflow-job`,name:e.name,sourceFile:e.sourceFile,contextHash:d,async build(a,l){let u=O.resolve(e.sourceFile),d=T`
188
+ `,f=createVirtualEntry(`resolver:${n.name}`,d,`js`,o),p=createStartTransformPlugin(a),m=[f.plugin];p&&m.push(p),m.push(createTsconfigPathsPlugin({onTsconfigRead:t,cache:l}),U,...e);let h=createBundleLog({tsconfig:r}),g=await N.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!s||`inline`,minify:!s||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:r,plugins:m,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(c)]),...h.options});h.assertAllResolved();let _=g.output[0].code;return assertNoForbiddenRuntimeGlobals(_,`Resolver "${n.name}"`),_}});return[n.name,f]}function parseResolverDefaultPermission(e){let{namespace:t,config:n}=e;if(n.defaultPermission===void 0)return;let r=ot.safeParse(n.defaultPermission);if(!r.success)throw Error(`Invalid \`defaultPermission\` for resolver namespace "${t}": `+r.error.issues.map(e=>e.message).join(`; `));return r.data}function resolveResolverDefaultPermissionForFile(e){let{config:t,filePath:n,baseDir:r}=e;if(!t)return;let i=O.resolve(n),a=[];for(let[e,n]of Object.entries(t))`external`in n||m(n,r).some(e=>O.resolve(e)===i)&&a.push({namespace:e,config:n});if(a.length>1)throw Error(`Resolver ${O.relative(process.cwd(),i)} matches more than one resolver namespace: ${a.map(e=>`"${e.namespace}"`).join(`, `)}. Each namespace applies its own \`defaultPermission\`, so narrow the \`files\`/\`ignores\` patterns until exactly one namespace claims this file.`);let[o]=a;return o?parseResolverDefaultPermission(o):void 0}function createResolverService(t,n,r){let i={},a=parseResolverDefaultPermission({namespace:t,config:n}),o=!1,loadResolverForFile=async t=>{try{let n=await u(t),r=X.safeParse(n.default);if(r.success){let e=O.relative(process.cwd(),t);return s.log(`Resolver: ${c.successBright(`"${r.data.name}"`)} loaded from ${c.path(e)}`),i[t]=r.data,r.data}if(e(n.default,`resolver`))throw r.error}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`Failed to load resolver from ${c.bold(n)}`),s.error(String(e)),e}};return{namespace:t,config:n,defaultPermission:a,get resolvers(){return i},loadResolvers:async()=>{if(o||n.files.length===0)return;let e=m(n,r);s.log(`Found ${c.highlight(e.length.toString())} resolver files for service ${c.highlight(`"${t}"`)}`),await Promise.all(e.map(e=>loadResolverForFile(e))),assertUniqueResolverNames(i,t),warnUndeclaredPermissions({namespace:t,defaultPermission:a,resolvers:i}),o=!0}}}function warnUndeclaredPermissions(e){let{namespace:t,defaultPermission:n,resolvers:r}=e;if(n!==void 0)return;let i=Object.values(r),a=i.filter(e=>e.permission===void 0);if(a.length===0)return;s.warn(`Resolver namespace ${c.highlight(`"${t}"`)}: ${a.length} of ${i.length} resolvers declare no \`permission\`, so anonymous callers can reach them. Set \`defaultPermission\` on the namespace, or declare \`permission\` on each resolver ("allowAnonymous" if public access is intended).`);let o=a.map(e=>e.name).toSorted();s.debug(` Resolvers without \`permission\`: ${o.join(`, `)}`)}function assertUniqueResolverNames(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=O.relative(process.cwd(),r),a=n.get(i.name);if(a)throw Error(`Duplicate resolver name "${i.name}" found in namespace "${t}":\n - ${a}\n - ${e}\nEach resolver must have a unique name within a namespace.`);n.set(i.name,e)}}function findVariableDeclarationsByName(e){let t=new Map;for(let n of e.body){let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if(e?.type!==`VariableDeclaration`)continue;let r=e;for(let e of r.declarations)e.id.type===`Identifier`&&t.set(e.id.name,{start:n.start,end:n.end})}return t}function findWorkflowDefaultExport(e){let t=collectSdkBindings(e,`createWorkflow`);for(let n of e.body)if(n.type===`ExportDefaultDeclaration`){let e=n,r=e.declaration;if(isSdkFunctionCall(r,t,`createWorkflow`)||r.type===`Identifier`)return{start:e.start,end:e.end}}return null}function transformWorkflowSource(e,t,n,r){let{program:i}=P(`input.ts`,e),a=findAllJobs(i,e);if(!a.some(e=>e.name===t))return e;let o=findVariableDeclarationsByName(i),s=[],c=new Set;for(let n of a)if(n.name!==t){if(n.statementRange&&!c.has(n.statementRange.start)){let t=findStatementEnd(e,n.statementRange.end);c.add(n.statementRange.start),s.push({start:n.statementRange.start,end:t,text:``})}else n.statementRange||(c.add(n.bodyValueRange.start),s.push({start:n.bodyValueRange.start,end:n.bodyValueRange.end,text:`() => {}`}))}if(r)for(let t of r){if(t===n)continue;let r=o.get(t);if(r&&!c.has(r.start)){let t=findStatementEnd(e,r.end);c.add(r.start),s.push({start:r.start,end:t,text:``})}}let l=findWorkflowDefaultExport(i);if(l&&!c.has(l.start)){let t=findStatementEnd(e,l.end);c.add(l.start),s.push({start:l.start,end:t,text:``})}return applyReplacements(e,s)}function safeRealpath(e){let t=O.resolve(e);try{return A.realpathSync(t)}catch(e){return s.debug(`realpathSync failed for ${t}: ${e instanceof Error?e.message:e}`),t}}var WorkflowJobDetectionError=class extends Error{};function isExecJobFunctionCallee(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.type!==`MemberExpression`)return!1;let n=t.property;if(n?.type!==`Identifier`||n.name!==`execJobFunction`)return!1;let r=t.object;if(r?.type!==`MemberExpression`)return!1;let i=r.property;if(i?.type!==`Identifier`||i.name!==`workflow`)return!1;let a=r.object;return a?.type===`Identifier`&&a.name===`tailor`}function extractStaticStringValue(e){if(!e||typeof e!=`object`)return;let t=e;if(t.type===`Literal`&&typeof t.value==`string`)return t.value;if(t.type===`TemplateLiteral`){let e=t.quasis,n=t.expressions;if(e?.length===1&&(n?.length??0)===0)return e[0]?.value?.cooked}}const st=new Set([`@tailor-platform/sdk/runtime`,`@tailor-platform/sdk/runtime/workflow`]);function collectRuntimeWorkflowImportBindings(e){let t=new Set;for(let n of e.body??[]){if(n.type!==`ImportDeclaration`||n.importKind===`type`)continue;let e=n.source;if(typeof e?.value==`string`&&st.has(e.value))for(let e of n.specifiers??[]){if(e.type!==`ImportSpecifier`||e.importKind===`type`)continue;let n=getModuleExportName(e.imported),r=getModuleExportName(e.local);n===`workflow`&&r&&t.add(r)}}return t}function isDirectExecJobFunctionCallee(e,t){if(isExecJobFunctionCallee(e))return!0;if(!e||typeof e!=`object`)return!1;let n=e;if(n.type!==`MemberExpression`)return!1;let r=n.property;if(r?.type!==`Identifier`||r.name!==`execJobFunction`)return!1;let i=n.object;return i?.type===`Identifier`&&t.has(i.name)}function findDirectExecJobFunctionCalls(e){let t=collectRuntimeWorkflowImportBindings(e),n=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isDirectExecJobFunctionCallee(e.callee,t)){let t=e.arguments;n.push({targetName:extractStaticStringValue(t?.[0])})}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(e),n}function buildDirectExecJobFunctionErrorMessage(e,t){return t.targetName===void 0?`Workflow file ${e} calls execJobFunction(...) directly with a job name that isn't a string literal, so the target can't be resolved at build time. Call the target job's own .start(...) method from inside a job body instead of calling execJobFunction directly.`:`Workflow file ${e} calls execJobFunction("${t.targetName}", ...) directly. A direct call is never recognized as a dependency, so "${t.targetName}" would silently be dropped from the bundle unless something else happens to reference it. Call the "${t.targetName}" job's .start(...) method from inside a job body instead.`}function collectExecJobFunctionTargets(e){let{program:t,errors:n}=P(`input.js`,e);if(n.length>0)throw new WorkflowJobDetectionError(`Failed to parse bundled job code while checking for missed dependencies: ${n.map(e=>e.message).join(`; `)}`);let r=[];function walk(e){if(e&&typeof e==`object`){if(e.type===`CallExpression`&&isExecJobFunctionCallee(e.callee)){let t=e.arguments,n=extractStaticStringValue(t?.[0]);n!==void 0&&r.push(n)}for(let t of Object.keys(e)){let n=e[t];Array.isArray(n)?n.forEach(e=>walk(e)):n&&typeof n==`object`&&walk(n)}}}return walk(t),r}function validateBundledDependencies(e,t){let n=new Set(t);for(let[t,r]of e){let e;try{e=collectExecJobFunctionTargets(r)}catch(e){throw new WorkflowJobDetectionError(`Failed to check the bundled output of workflow job "${t}" for missed dependencies: ${e instanceof Error?e.message:String(e)}`)}for(let r of e)if(!n.has(r))throw new WorkflowJobDetectionError(`Workflow job "${t}" calls execJobFunction("${r}", ...) — usually the result of a rewritten "${r}" job .start() call — but "${r}" was not detected as a dependency and is not included in the bundle. Call the "${r}" job's .start() method from inside the body of workflow job "${t}" (a nested function inside body works too), or make sure the file containing the call is covered by the workflow service's "files" pattern.`)}}async function bundleWorkflowJobs(e,t,n={},r,i,a,o,l=`DEBUG`,u){if(e.length===0)return s.warn(`No workflow jobs to bundle`),{mainJobDeps:{},usedJobNames:[],bundledCode:new Map};let{usedJobs:d,mainJobDeps:f}=await filterUsedJobs(e,t,r);s.newline(),s.log(`Bundling ${c.highlight(d.length.toString())} files for ${c.info(`"workflow-job"`)}`);let p=await resolveTSConfigWithFallback(i),m=await withBundleConcurrency(d,e=>bundleSingleJob(e,d,p,n,r,a,o,l,u)),h=new Map;for(let[e,t]of m)h.set(e,t);return validateBundledDependencies(h,d.map(e=>e.name)),s.log(`${c.success(`Bundled`)} ${c.info(`"workflow-job"`)}`),{mainJobDeps:f,usedJobNames:d.map(e=>e.name),bundledCode:h}}async function filterUsedJobs(e,t,n){if(e.length===0||t.length===0)return{usedJobs:[],mainJobDeps:{}};let r=new Map;for(let t of e){let e=r.get(t.sourceFile)||[];e.push(t),r.set(t.sourceFile,e)}let i=new Map(r),a=new Set([...r.keys()].map(safeRealpath));for(let e of n.modules.values())a.has(safeRealpath(e.sourceFile))||i.set(e.sourceFile,[]);let o=new Map,s=await Promise.all(Array.from(i.entries()).map(async([e,t])=>{try{let r=await A.promises.readFile(e,`utf-8`),{program:i,errors:a}=P(e,r);if(a.length>0)throw new WorkflowJobDetectionError(`Failed to parse ${e}: ${a.map(e=>e.message).join(`; `)}`);let[o]=findDirectExecJobFunctionCalls(i);if(o)throw new WorkflowJobDetectionError(buildDirectExecJobFunctionErrorMessage(e,o));let s=findAllJobs(i,r),c=detectResolvedStartCalls(i,r,n,e),l=[];for(let n of t){let t=s.find(e=>e.name===n.name);if(!t)throw new WorkflowJobDetectionError(`Workflow job "${n.name}" (export "${n.exportName}" in ${e}) could not be statically detected: createWorkflowJob's "name" must be a string literal and "body" must be a function expression. Dynamic or computed values (e.g. body: someWrapper(fn)) cannot be bundled and would be silently dropped.`);let r=new Set;for(let e of c)e.kind===`job`&&e.callRange.start>=t.bodyValueRange.start&&e.callRange.end<=t.bodyValueRange.end&&r.add(e.targetName);r.size>0&&l.push({jobName:n.name,deps:r})}for(let t of c)if(t.kind===`job`&&!s.some(e=>t.callRange.start>=e.bodyValueRange.start&&t.callRange.end<=e.bodyValueRange.end))throw new WorkflowJobDetectionError(`Call to job "${t.targetName}".start() in ${e} is not inside any workflow job's body: it was factored into a function defined outside the calling job's body. Dependency detection only sees .start() calls lexically inside a job body, so this call would silently drop "${t.targetName}" from the bundle. Move the call to a function defined inside the calling job's body.`);return l}catch(e){if(e instanceof WorkflowJobDetectionError)throw e;return[]}}));for(let e of s)for(let{jobName:t,deps:n}of e)o.set(t,n);let c=new Set,l={};function collectDeps(e,t){if(t.has(e))return;t.add(e);let n=o.get(e);if(n)for(let e of n)collectDeps(e,t)}for(let e of t){let t=new Set;collectDeps(e,t),l[e]=Array.from(t);for(let e of t)c.add(e)}return{usedJobs:e.filter(e=>c.has(e.name)),mainJobDeps:l}}async function bundleSingleJob(e,t,n,r,i,a,o,s=`DEBUG`,c){let l=serializeStartContext(i),u=JSON.stringify(Object.fromEntries(Object.entries(r).toSorted(([e],[t])=>e.localeCompare(t)))),d=computeBundlerContextHash({sourceFile:e.sourceFile,extraContext:l,tsconfig:n,inlineSourcemap:o,bundleLogLevel:s,prefix:u}),f=await withCache({cache:a,kind:`workflow-job`,name:e.name,sourceFile:e.sourceFile,contextHash:d,async build(a,l){let u=O.resolve(e.sourceFile),d=T`
189
189
  import { ${e.exportName} } from "${u}";
190
190
 
191
191
  export async function main(input) {
@@ -193,7 +193,7 @@ globalThis.transform = __adapter.output;
193
193
  const invoker = ${q};
194
194
  return await ${e.exportName}.body(input, { env, invoker });
195
195
  }
196
- `,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),U,...a],g=createBundleLog({tsconfig:n}),_=await N.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let v=_.output[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const ct=k.strictObject({name:k.string().describe(`Job name (must be unique across the project)`),start:w.describe(`Start function that initiates the job`),body:w.describe(`Job implementation function`),publishEvents:k.boolean().optional().describe(`Enable publishing job execution events for this job`)}),lt=[`ms`,`s`,`m`],ut={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=e.match(/^(\d+)(ms|s|m)$/);if(!t)return 0;let n=t[1],r=t[2];return n===void 0||r===void 0?0:parseInt(n,10)*ut[r]}const dt=k.templateLiteral([k.number().int().positive(),k.enum(lt)]),durationSchema=e=>dt.refine(t=>durationToSeconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),ft=k.strictObject({maxRetries:k.number().int().min(1).max(10).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(3600).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(86400).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:k.number().min(1).describe(`Backoff multiplier (>= 1)`)}).refine(e=>durationToSeconds(e.initialBackoff)<=durationToSeconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>durationToSeconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),pt=k.strictObject({maxConcurrentExecutions:k.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),mt=k.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`),ht=k.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 execJobFunction's executionPolicyKey option`),gt=k.strictObject({name:mt,key:ht,concurrencyPolicy:pt.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),_t=k.strictObject({name:k.string().describe(`Workflow name`),mainJob:ct.describe(`Main job that starts the workflow`),retryPolicy:ft.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:pt.optional().describe(`Concurrency policy for the workflow`),publishEvents:k.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(t){if(!e(t,`workflow`)||typeof t!=`object`||!t||!(`start`in t))return t;let{start:n,...r}=t;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],o=0,l=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return o},loadWorkflows:async()=>{if(l)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,o=e.fileCount,l=!0},printLoadedWorkflows:()=>{if(o!==0){s.newline(),s.log(`Found ${c.highlight(o.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=O.relative(process.cwd(),t);s.log(`Workflow: ${c.successBright(`"${e.name}"`)} loaded from ${c.path(n)}`)}}}}}async function loadAndCollectJobs(e,t){let n={},r=[],i=[];if(e.files.length===0)return{workflows:n,workflowSources:r,jobs:i,fileCount:0};let a=m(e,t),o=a.length,s=new Map,c=await Promise.all(a.map(async e=>{let{jobs:t,workflow:n}=await loadFileContent(e);return{workflowFile:e,jobs:t,workflow:n}}));for(let{workflowFile:e,jobs:t,workflow:a}of c){a&&(r.push({workflow:a,sourceFile:e}),n[e]=a);for(let e of t){let t=s.get(e.name);if(t)throw Error(`Duplicate job name "${e.name}" found:\n - ${t.sourceFile} (export: ${t.exportName})\n - ${e.sourceFile} (export: ${e.exportName})\nEach job must have a unique name.`);s.set(e.name,e),i.push(e)}}return{workflows:n,workflowSources:r,jobs:i,fileCount:o}}async function loadFileContent(t){let n=[],r=null;try{let i=await u(t);for(let[a,o]of Object.entries(i)){if(a==="default"){let t=_t.safeParse(stripRuntimeStart(o));if(t.success)r=t.data;else if(e(o,[`workflow`,`workflow-job`]))throw t.error;continue}let i=ct.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:t,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(e(o,[`workflow`,`workflow-job`]))throw i.error}}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`${c.error(`Failed to load workflow from`)} ${c.errorBright(n)}`),s.error(String(e)),e}return{jobs:n,workflow:r}}function getApplicationAuthNamespace(e){return e.authService?.config.name??e.config?.auth?.name}function requireApplicationAuthNamespace(e){let t=getApplicationAuthNamespace(e);if(!t)throw Error(`No Auth service configured`);return t}let Z=null;const getDistDir=()=>{let e=process.env.TAILOR_BUILD_OUTPUT_DIR;return e&&e!==Z?Z=e:Z===null&&(Z=e||`.tailor`),Z};function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=o(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const vt=k.strictObject({name:k.string().regex(/^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/,`Must be 3-30 lowercase alphanumeric characters or hyphens`).describe(`AI Gateway name`),authNamespace:k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Must be 3-63 lowercase alphanumeric characters or hyphens`).optional().describe(`Auth namespace used to resolve request tokens against the workspace's auth. Defaults to the application's own auth service when omitted; omitting it without an Auth service configured is rejected.`),cors:k.array(k.string()).optional().describe("Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.")});function normalizeIdPGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0,sendPasswordResetEmail:!1,requestMfaSettingsUrl:!0,unenrollMfa:!1}:e}const yt=k.union([k.literal(`query`),k.strictObject({create:k.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:k.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:k.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:k.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:k.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:k.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:k.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
197
- All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),bt=k.enum([`en`,`ja`]).describe(`IdP UI language`),xt=k.strictObject({useNonEmailIdentifier:k.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:k.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:k.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:k.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:k.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:k.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:k.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:k.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:k.array(k.string()).optional().describe(`Restrict registration to these email domains`),allowGoogleOauth:k.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:k.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:k.boolean().optional().describe(`Disable password-based authentication`),enableMfa:k.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:k.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:k.array(k.string().regex(/^(https?:\/\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/,`must be an http(s) origin like "https://app.example.com" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like "<name>:url"`)).optional().describe(`Application origins (scheme + host + optional port) allowed as MFA self-service return targets`),mfaIssuer:k.string().max(64,`mfaIssuer must be 64 characters or less`).optional().describe(`Label shown next to the user account in authenticator apps`)}).refine(e=>e.passwordMinLength===void 0||e.passwordMaxLength===void 0||e.passwordMinLength<=e.passwordMaxLength,{message:`passwordMinLength must be less than or equal to passwordMaxLength`,path:[`passwordMinLength`]}).refine(e=>!e.allowedEmailDomains||e.allowedEmailDomains.length===0||!e.useNonEmailIdentifier,{message:`allowedEmailDomains cannot be set when useNonEmailIdentifier is true`,path:[`allowedEmailDomains`]}).refine(e=>e.allowGoogleOauth===void 0||e.allowGoogleOauth===!1||!e.useNonEmailIdentifier,{message:`allowGoogleOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowGoogleOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowGoogleOauth requires allowedEmailDomains to be set`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowMicrosoftOauth||!e.useNonEmailIdentifier,{message:`allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowMicrosoftOauth requires allowedEmailDomains to be set`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.disablePasswordAuth===!0,{message:`allowMicrosoftOauth requires disablePasswordAuth to be enabled`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.disablePasswordAuth||e.allowGoogleOauth===!0||e.allowMicrosoftOauth===!0,{message:`disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled`,path:[`disablePasswordAuth`]}).refine(e=>!e.disablePasswordAuth||!e.allowSelfPasswordReset,{message:`disablePasswordAuth cannot be used with allowSelfPasswordReset`,path:[`disablePasswordAuth`]}).refine(e=>!e.requireMfa||e.enableMfa===!0,{message:`requireMfa requires enableMfa to be enabled`,path:[`requireMfa`]}).refine(e=>!e.enableMfa||e.allowedReturnOrigins&&e.allowedReturnOrigins.length>0,{message:`enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target`,path:[`enableMfa`]}),St=k.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),Ct=k.strictObject({fromName:St.optional().describe(`Default sender display name for emails`),passwordResetSubject:St.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=k.union([k.string(),k.boolean(),k.array(k.string()).readonly(),k.array(k.boolean()).readonly(),k.strictObject({user:k.string()}),k.strictObject({idpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({oldIdpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({newIdpUser:k.enum([`id`,`name`,`disabled`])})]),wt=k.enum([`=`,`!=`,`in`,`not in`]),Tt=k.tuple([Q,wt,Q]).readonly(),$=k.union([k.strictObject({conditions:k.union([Tt,k.array(Tt).readonly()]),description:k.string().optional(),permit:k.boolean().optional()}),k.tuple([Q,wt,Q]).readonly(),k.tuple([Q,wt,Q,k.boolean()]).readonly(),k.array(k.union([Tt,k.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),Et=k.strictObject({create:k.array($).readonly(),read:k.array($).readonly(),update:k.array($).readonly(),delete:k.array($).readonly(),sendPasswordResetEmail:k.array($).readonly().optional(),unenrollMfa:k.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Dt=k.strictObject({name:k.string().describe(`IdP service name`),authorization:k.union([k.literal(`insecure`),k.literal(`loggedIn`),k.strictObject({cel:k.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:k.array(k.string()).describe(`OAuth2 client names that can use this IdP`),lang:bt.optional().describe(`UI language for IdP pages`),userAuthPolicy:xt.transform(e=>xt.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:k.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:yt.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:Ct.optional().describe(`Namespace-level email configuration defaults`),permission:Et.optional().describe(`Per-operation permission policies for IdP users`)}).refine(e=>!e.userAuthPolicy?.enableMfa||e.gqlOperations?.unenrollMfa===!1||e.permission!==void 0&&e.permission.unenrollMfa!==void 0,{message:`permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.`,path:[`permission`,`unenrollMfa`]}).refine(e=>!e.permission||e.userAuthPolicy?.disablePasswordAuth===!0||e.gqlOperations?.sendPasswordResetEmail===!1||e.permission.sendPasswordResetEmail!==void 0,{message:`permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)`,path:[`permission`,`sendPasswordResetEmail`]}),Ot=k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),kt=k.record(Ot,k.string().nullish()),At=k.strictObject({vaults:k.record(Ot,kt),options:k.strictObject({ignoreNullishValues:k.boolean()})}),jt=k.strictObject({name:k.string().describe(`Static website name`),description:k.string().optional().describe(`Static website description`),allowedIpAddresses:k.array(k.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:k.array(k.string()).optional().describe(`Custom domains for the static website`)}),Mt=/^[a-z0-9]+$/,Nt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:r,declaredBy:a}=e,o=r.split(`-`),s=o.filter(i);if(s.length>0&&a!==`define`)return a===`property`?`Invalid wait point key "${r}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${r}")<Payload, Result>().`:`Invalid wait point key "${r}": createWaitPoint takes its type arguments first, which stops TypeScript inferring the key as a literal, so it cannot type the $params. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${r}")<Payload, Result>() })).`;let c=new Set,l=0;for(let e of o){if(e.startsWith(`$`)){let t=e.slice(1);if(!Nt.test(t))return`Invalid wait point key "${r}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(t))return`Invalid wait point key "${r}": parameter "$${t}" appears more than once.`;c.add(t);continue}if(e!==``){if(!Mt.test(e))return`Invalid wait point key "${r}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${n}, with $params standing in for runtime values.`;l+=1}}if(l===0&&s.length>0)return r.startsWith(`-`)||r.endsWith(`-`)?`Invalid wait point key "${r}": must match ${n}.`:`Invalid wait point key "${r}": it needs at least one literal segment alongside its $params, otherwise the key carries no identity of its own and can collide with an unrelated wait point.`;if(s.length===0)return t.test(r)?void 0:`Invalid wait point key "${r}": must match ${n}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${r}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:t.test(u)?void 0:`Invalid wait point key "${r}": must match ${n}.`}function collectWaitPointKeyFailures(e){let t=[],n=new Set;for(let r of e){let e=`${r.declaredBy} ${r.key}`;if(n.has(e))continue;n.add(e);let i=checkWaitPointKey(r);i&&t.push(i)}return t}function defineTailorDB(e,t,n){let r=[],i=[],a=[];if(!e)return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a};for(let[o,s]of Object.entries(e)){if(`external`in s)i.push(o);else{let e=createTailorDBService({namespace:o,config:C.parse(s),pluginManager:n,baseDir:t});r.push(e)}a.push({Type:`tailordb`,Name:o})}return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a}}function defineResolver(e,t){let n=[],r=[];if(!e)return{resolverServices:n,subgraphs:r};for(let[i,a]of Object.entries(e)){if(!(`external`in a)){let e=createResolverService(i,a,t);n.push(e)}r.push({Type:`pipeline`,Name:i})}return{resolverServices:n,subgraphs:r}}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e){let t=[],n=[];if(!e)return{idpServices:t,subgraphs:n};let r=new Set;return e.forEach(e=>{let i=e.name;if(r.has(i))throw Error(`IdP with name "${i}" already defined.`);if(r.add(i),!(`external`in e)){let n=Dt.parse(stripIdpProviderHelper(e));t.push(n)}n.push({Type:`idp`,Name:i})}),{idpServices:t,subgraphs:n}}function defineAuth(e,t,n){let r=[];if(!e)return{authService:void 0,subgraphs:r};let i;return`external`in e||(i=createAuthService(l.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(!(!e&&!n))return S({config:e??{files:[]},baseDir:t})}function defineWorkflow(e,t){if(e)return createWorkflowService({config:e,baseDir:t})}function defineHttpAdapterService(e,t){if(e)return createHttpAdapterService({config:e,baseDir:t})}function stripStaticWebsiteUrlHelper(e){let t=e;if(t.url!==`${e.name}:url`)return e;let{url:n,...r}=t;return r}function defineStaticWebsites(e){let t=[],n=new Set;return(e??[]).forEach(e=>{let r=jt.parse(stripStaticWebsiteUrlHelper(e));if(n.has(r.name))throw Error(`Static website with name "${r.name}" already defined.`);n.add(r.name),t.push(r)}),t}function defineAIGateways(e,t){let n=[],r=new Set;return(e??[]).forEach(e=>{let i=vt.parse(e);if(r.has(i.name))throw Error(`AI Gateway with name "${i.name}" already defined.`);if(r.add(i.name),i.authNamespace===void 0){if(!t)throw Error(`AI Gateway "${i.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);i.authNamespace=t}n.push(i)}),n}function parseSecretManager(e){if(!e)return{secrets:[],ignoreNullishValues:!1};let t=At.parse(e),{ignoreNullishValues:n}=t.options,r=Object.entries(t.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!n){for(let e of r)for(let t of e.secrets)if(t.value==null)throw Error(`Secret "${e.vaultName}/${t.name}" has no value. Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`)}return{secrets:r,ignoreNullishValues:n}}function defineServices(e,t,n){let r=defineTailorDB(e.db,t,n),i=defineResolver(e.resolver,t),a=defineIdp(e.idp),o=defineAuth(e.auth,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites),c=defineAIGateways(e.aiGateways,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets);return{tailordbResult:r,resolverResult:i,idpResult:a,authResult:o,staticWebsiteServices:s,aiGatewayServices:c,secrets:l,ignoreNullishValues:u}}function buildApplication(e){let t={name:e.config.name,id:e.config.id,config:e.config,subgraphs:[...e.tailordbResult.subgraphs,...e.resolverResult.subgraphs,...e.idpResult.subgraphs,...e.authResult.subgraphs],tailorDBServices:e.tailordbResult.tailorDBServices,externalTailorDBNamespaces:e.tailordbResult.externalTailorDBNamespaces,resolverServices:e.resolverResult.resolverServices,idpServices:e.idpResult.idpServices,authService:e.authResult.authService,executorService:e.executorService,workflowService:e.workflowService,httpAdapterService:e.httpAdapterService,staticWebsiteServices:e.staticWebsiteServices,aiGatewayServices:e.aiGatewayServices,secrets:e.secrets,ignoreNullishValues:e.ignoreNullishValues,env:e.env,get applications(){return[t]}};return t}function defineApplication(e){let{config:t,pluginManager:n}=e,r=O.dirname(t.path),i=defineServices(t,r,n),a=defineExecutor(t.executor,r,!1),o=defineWorkflow(t.workflow,r),s=defineHttpAdapterService(t.httpAdapter,r);return buildApplication({config:t,...i,executorService:a,workflowService:o,httpAdapterService:s,env:t.env??{}})}function generatePluginFilesIfNeeded(e,t,n){if(!e)return[];let r=new Map;for(let e of t){let t=e.typeSourceInfo;for(let[e,n]of Object.entries(t))n.filePath&&r.set(e,{filePath:n.filePath,exportName:n.exportName})}return e.generatePluginFiles({outputDir:O.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(r());if(e.length!==0)throw Error(e.join(`
198
- `))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r}=e,i=O.dirname(t.path),{tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p}=defineServices(t,i,n);for(let e of a.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:a.tailorDBServices});let m=generatePluginFilesIfNeeded(n,a.tailorDBServices,t.path),h=defineExecutor(t.executor,i,m.length>0),g=defineWorkflow(t.workflow,i);g&&await g.loadWorkflows();let _=defineHttpAdapterService(t.httpAdapter,i);_&&await _.loadAdapters();let v=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:l.authService,config:t}),i),y=resolveInlineSourcemap(t.inlineSourcemap),b=resolveBundleLogLevel(t.logLevel),x=createTsconfigLookupCache(),S={resolvers:new Map,executors:new Map,workflowJobs:new Map,authHooks:new Map};for(let e of o.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:i,defaultPermission:e.defaultPermission,startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,tsconfigCache:x});for(let[n,r]of t)S.resolvers.set(resolverBundleKey(e.namespace,n),r)}h&&(S.executors=await bundleExecutors({config:h.config,startContext:v,additionalFiles:[...m],cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x}));let C;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);C=await bundleWorkflowJobs(g.jobs,e,t.env??{},v,i,r,y,b,x),S.workflowJobs=C.bundledCode}let w;if(_&&_.adapters.length>0&&(w=await bundleHttpAdapters(_.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),i,r,b,x)),l.authService?.config.hooks?.beforeLogin){let e=l.authService.config.name;S.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:t.env??{},startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x})}for(let e of o.resolverServices)await e.loadResolvers();return h&&(await h.loadExecutors(),m.length>0&&await h.loadPluginExecutorFiles([...m])),assertWaitPointKeys(),g&&g.printLoadedWorkflows(),_&&_.printLoadedAdapters(),s.newline(),{application:buildApplication({config:t,tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,executorService:h,workflowService:g,httpAdapterService:_,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p,env:t.env??{}}),workflowBuildResult:C,httpAdapterBuildResult:w,bundledScripts:S}}export{isDefaultPlatform as $,createLogLevelTreeshakeOptions as A,be as B,Ve as C,resolveTSConfigWithFallback as D,createTsconfigPathsPlugin as E,hashFile as F,fetchPlatformMachineUserToken as G,fetchAllTolerant as H,getPluginGenerationDependencies as I,getOAuth2ClientId as J,fetchUserInfo as K,getRawPluginTableName as L,createBundleLog as M,createBundleCache as N,U as O,hashContent as P,initOperatorClient as Q,hasGenerationHooks as R,stringifyFunction as S,createGeneratedEntryResolverPlugin as T,fetchMachineUserToken as U,fetchAll as V,fetchPaged as W,getPlatformBaseUrl as X,getOrNull as Y,initOAuth2Client as Z,buildResolverValidatedInputExpr as _,resolveInlineSourcemap as a,createApplyLimiter as at,createPermissionNormalizer as b,requireApplicationAuthNamespace as c,resolveResolverDefaultPermissionForFile as d,isNotFoundError as et,X as f,buildResolverOperationHookExpr as g,buildExecutorArgsExpr as h,resolverBundleKey as i,byName as it,resolveBundleLogLevel as j,composeFunctionTreeshakeOptions as k,gt as l,q as m,generatePluginFilesIfNeeded as n,rememberPlatformConfigForToken as nt,getDistDir as o,I as ot,Y as p,getConsoleBaseUrl as q,loadApplication as r,resolveStaticWebsiteUrls as rt,getApplicationAuthNamespace as s,defineApplication as t,normalizeBaseUrl as tt,ct as u,assertUniqueLocalTailorDBTypeNames as v,G as w,hasOmittedPermit as x,assertUniqueTailorDBTypeNamesWithExternal as y,closeConnectionPool as z};
199
- //# sourceMappingURL=application-CiN_er9X.mjs.map
196
+ `,f=createVirtualEntry(`workflow-job:${e.name}`,d,`js`,u),p=safeRealpath(e.sourceFile),m=t.filter(t=>t.name!==e.name&&safeRealpath(t.sourceFile)===p).map(e=>e.exportName),h=[f.plugin,{name:`workflow-transform`,transform:{filter:{id:{include:[/\.(ts|mts|cts|js|mjs|cjs)$/]}},handler(t,n){if(!t.includes(`createWorkflowJob`)&&!t.includes(`createWorkflow`)&&!hasStartCall(t))return null;let r=t;return safeRealpath(n)===p&&(r=transformWorkflowSource(t,e.name,e.exportName,m)),hasStartCall(r)&&(r=transformStartCalls(r,i,n)),r===t?null:{code:r}}}},createTsconfigPathsPlugin({onTsconfigRead:l,cache:c}),U,...a],g=createBundleLog({tsconfig:n}),_=await N.build({input:f.input,write:!1,output:{format:`esm`,sourcemap:!o||`inline`,minify:!o||{mangle:{keepNames:!0}},codeSplitting:!1},tsconfig:n,plugins:h,treeshake:composeFunctionTreeshakeOptions([createLogLevelTreeshakeOptions(s)]),...g.options});g.assertAllResolved();let v=_.output[0].code;return assertNoForbiddenRuntimeGlobals(v,`Workflow job "${e.name}"`),v}});return[e.name,f]}const ct=k.strictObject({name:k.string().describe(`Job name (must be unique across the project)`),start:w.describe(`Start function that initiates the job`),body:w.describe(`Job implementation function`),publishEvents:k.boolean().optional().describe(`Enable publishing job execution events for this job`)}),lt=[`ms`,`s`,`m`],ut={ms:1/1e3,s:1,m:60};function durationToSeconds(e){let t=e.match(/^(\d+)(ms|s|m)$/);if(!t)return 0;let n=t[1],r=t[2];return n===void 0||r===void 0?0:parseInt(n,10)*ut[r]}const dt=k.templateLiteral([k.number().int().positive(),k.enum(lt)]),durationSchema=e=>dt.refine(t=>durationToSeconds(t)<=e,{message:`Duration must be at most ${e} seconds`}),ft=k.strictObject({maxRetries:k.number().int().min(1).max(10).describe(`Maximum number of retries (1-10)`),initialBackoff:durationSchema(3600).describe(`Initial backoff duration (e.g., '1s', '500ms', '1m', max 1h)`),maxBackoff:durationSchema(86400).describe(`Maximum backoff duration (e.g., '30s', '5m', max 24h)`),backoffMultiplier:k.number().min(1).describe(`Backoff multiplier (>= 1)`)}).refine(e=>durationToSeconds(e.initialBackoff)<=durationToSeconds(e.maxBackoff),{message:`initialBackoff must be less than or equal to maxBackoff`,path:[`initialBackoff`]}).refine(e=>durationToSeconds(e.initialBackoff)>0,{message:`initialBackoff must be greater than 0`,path:[`initialBackoff`]}),pt=k.strictObject({maxConcurrentExecutions:k.number().int().min(1).max(1e3).describe(`Maximum number of concurrent executions (1-1000)`)}),mt=k.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`),ht=k.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 execJobFunction's executionPolicyKey option`),gt=k.strictObject({name:mt,key:ht,concurrencyPolicy:pt.optional().describe(`Optional per-key concurrency cap for job function dispatches matching this policy`)}),_t=k.strictObject({name:k.string().describe(`Workflow name`),mainJob:ct.describe(`Main job that starts the workflow`),retryPolicy:ft.optional().describe(`Retry policy for the workflow`),concurrencyPolicy:pt.optional().describe(`Concurrency policy for the workflow`),publishEvents:k.boolean().optional().describe(`Enable publishing workflow execution events for this workflow`)});function stripRuntimeStart(t){if(!e(t,`workflow`)||typeof t!=`object`||!t||!(`start`in t))return t;let{start:n,...r}=t;return r}function createWorkflowService(e){let{config:t,baseDir:n}=e,r={},i=[],a=[],o=0,l=!1;return{config:t,get workflows(){return r},get workflowSources(){return i},get jobs(){return a},get fileCount(){return o},loadWorkflows:async()=>{if(l)return;let e=await loadAndCollectJobs(t,n);r=e.workflows,i=e.workflowSources,a=e.jobs,o=e.fileCount,l=!0},printLoadedWorkflows:()=>{if(o!==0){s.newline(),s.log(`Found ${c.highlight(o.toString())} workflow files`);for(let{workflow:e,sourceFile:t}of i){let n=O.relative(process.cwd(),t);s.log(`Workflow: ${c.successBright(`"${e.name}"`)} loaded from ${c.path(n)}`)}}}}}async function loadAndCollectJobs(e,t){let n={},r=[],i=[];if(e.files.length===0)return{workflows:n,workflowSources:r,jobs:i,fileCount:0};let a=m(e,t),o=a.length,s=new Map,c=await Promise.all(a.map(async e=>{let{jobs:t,workflow:n}=await loadFileContent(e);return{workflowFile:e,jobs:t,workflow:n}}));for(let{workflowFile:e,jobs:t,workflow:a}of c){a&&(r.push({workflow:a,sourceFile:e}),n[e]=a);for(let e of t){let t=s.get(e.name);if(t)throw Error(`Duplicate job name "${e.name}" found:\n - ${t.sourceFile} (export: ${t.exportName})\n - ${e.sourceFile} (export: ${e.exportName})\nEach job must have a unique name.`);s.set(e.name,e),i.push(e)}}return{workflows:n,workflowSources:r,jobs:i,fileCount:o}}async function loadFileContent(t){let n=[],r=null;try{let i=await u(t);for(let[a,o]of Object.entries(i)){if(a==="default"){let t=_t.safeParse(stripRuntimeStart(o));if(t.success)r=t.data;else if(e(o,[`workflow`,`workflow-job`]))throw t.error;continue}let i=ct.safeParse(o);if(i.success)n.push({name:i.data.name,exportName:a,sourceFile:t,...i.data.publishEvents===void 0?{}:{publishEvents:i.data.publishEvents}});else if(e(o,[`workflow`,`workflow-job`]))throw i.error}}catch(e){let n=O.relative(process.cwd(),t);throw s.error(`${c.error(`Failed to load workflow from`)} ${c.errorBright(n)}`),s.error(String(e)),e}return{jobs:n,workflow:r}}function getApplicationAuthNamespace(e){return e.authService?.config.name??e.config?.auth?.name}function requireApplicationAuthNamespace(e){let t=getApplicationAuthNamespace(e);if(!t)throw Error(`No Auth service configured`);return t}let Z=null;const getDistDir=()=>{let e=process.env.TAILOR_BUILD_OUTPUT_DIR;return e&&e!==Z?Z=e:Z===null&&(Z=e||`.tailor`),Z};function resolveInlineSourcemap(e){if(e!==void 0)return e;let t=o(process.env.TAILOR_INLINE_SOURCEMAP);return t===void 0||t}function resolverBundleKey(e,t){return`${e}:${t}`}const vt=k.strictObject({name:k.string().regex(/^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/,`Must be 3-30 lowercase alphanumeric characters or hyphens`).describe(`AI Gateway name`),authNamespace:k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/,`Must be 3-63 lowercase alphanumeric characters or hyphens`).optional().describe(`Auth namespace used to resolve request tokens against the workspace's auth. Defaults to the application's own auth service when omitted; omitting it without an Auth service configured is rejected.`),cors:k.array(k.string()).optional().describe("Allowed CORS origins for browser-based clients. Each entry is `*`, `http(s)://*`, `http(s)://*.example.com`, or `http(s)://app.example.com`, optionally with `:port`. Empty list disables cross-origin access.")}),yt=/^(\*|[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$/;function containsAllEmailDomains(e){return e.some(e=>e.trim()===`*`)}function hasImplicitAllEmailDomains(e){return e?.useNonEmailIdentifier===!0?!1:!e?.allowedEmailDomains||e.allowedEmailDomains.length===0}function normalizeIdPGqlOperations(e){return e===`query`?{create:!1,update:!1,delete:!1,read:!0,sendPasswordResetEmail:!1,requestMfaSettingsUrl:!0,unenrollMfa:!1}:e}const bt=k.union([k.literal(`query`),k.strictObject({create:k.boolean().optional().describe(`Enable _createUser mutation (default: true)`),update:k.boolean().optional().describe(`Enable _updateUser mutation (default: true)`),delete:k.boolean().optional().describe(`Enable _deleteUser mutation (default: true)`),read:k.boolean().optional().describe(`Enable _users and _user queries (default: true)`),sendPasswordResetEmail:k.boolean().optional().describe(`Enable _sendPasswordResetEmail mutation (default: true)`),requestMfaSettingsUrl:k.boolean().optional().describe(`Enable _requestMfaSettingsUrl query (default: true)`),unenrollMfa:k.boolean().optional().describe(`Enable _unenrollMfa mutation (default: true)`)})]).describe(`Configuration for GraphQL operations on IdP users.
197
+ All operations are enabled by default (undefined or true = enabled, false = disabled).`).transform(e=>normalizeIdPGqlOperations(e)),xt=k.enum([`en`,`ja`]).describe(`IdP UI language`),St=k.strictObject({useNonEmailIdentifier:k.boolean().optional().describe(`Use non-email identifier for usernames`),allowSelfPasswordReset:k.boolean().optional().describe(`Allow users to reset their own passwords`),passwordRequireUppercase:k.boolean().optional().describe(`Require uppercase letters in passwords`),passwordRequireLowercase:k.boolean().optional().describe(`Require lowercase letters in passwords`),passwordRequireNonAlphanumeric:k.boolean().optional().describe(`Require non-alphanumeric characters in passwords`),passwordRequireNumeric:k.boolean().optional().describe(`Require numeric characters in passwords`),passwordMinLength:k.number().int().refine(e=>e>=6&&e<=30,{message:`passwordMinLength must be between 6 and 30`}).optional().describe(`Minimum password length (6-30)`),passwordMaxLength:k.number().int().refine(e=>e>=6&&e<=4096,{message:`passwordMaxLength must be between 6 and 4096`}).optional().describe(`Maximum password length (6-4096)`),allowedEmailDomains:k.array(k.string().regex(yt,`must be a hostname, or * to allow all email domains`)).max(100,`allowedEmailDomains accepts at most 100 entries`).refine(e=>new Set(e.map(e=>e.toLowerCase())).size===e.length,{message:`allowedEmailDomains entries must be unique, compared case-insensitively`}).refine(e=>e.length<=1||!containsAllEmailDomains(e),{message:`allowedEmailDomains cannot contain other entries when * is set`}).optional().describe(`Restrict registration to these email domains. A lone * entry allows every domain`),allowGoogleOauth:k.boolean().optional().describe(`Enable Google OAuth login`),allowMicrosoftOauth:k.boolean().optional().describe(`Enable Microsoft OAuth login`),disablePasswordAuth:k.boolean().optional().describe(`Disable password-based authentication`),enableMfa:k.boolean().optional().describe(`Make TOTP MFA available for users in this namespace`),requireMfa:k.boolean().optional().describe(`Require TOTP MFA enrollment and challenge for password-authenticated users (requires enableMfa)`),allowedReturnOrigins:k.array(k.string().regex(/^(https?:\/\/[a-zA-Z0-9.-]+(:[0-9]+)?|[a-z0-9][a-z0-9-]{1,61}[a-z0-9]:url)$/,`must be an http(s) origin like "https://app.example.com" (scheme + host + optional port, no path/query/fragment) or a static-website placeholder like "<name>:url"`)).optional().describe(`Application origins (scheme + host + optional port) allowed as MFA self-service return targets`),mfaIssuer:k.string().max(64,`mfaIssuer must be 64 characters or less`).optional().describe(`Label shown next to the user account in authenticator apps`)}).refine(e=>e.passwordMinLength===void 0||e.passwordMaxLength===void 0||e.passwordMinLength<=e.passwordMaxLength,{message:`passwordMinLength must be less than or equal to passwordMaxLength`,path:[`passwordMinLength`]}).refine(e=>!e.allowedEmailDomains||e.allowedEmailDomains.length===0||!e.useNonEmailIdentifier,{message:`allowedEmailDomains cannot be set when useNonEmailIdentifier is true`,path:[`allowedEmailDomains`]}).refine(e=>e.allowGoogleOauth===void 0||e.allowGoogleOauth===!1||!e.useNonEmailIdentifier,{message:`allowGoogleOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowGoogleOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowGoogleOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowGoogleOauth`]}).refine(e=>!e.allowMicrosoftOauth||!e.useNonEmailIdentifier,{message:`allowMicrosoftOauth cannot be set when useNonEmailIdentifier is true`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.allowedEmailDomains&&e.allowedEmailDomains.length>0,{message:`allowMicrosoftOauth requires a non-empty allowedEmailDomains (["*"] to allow every domain)`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.allowMicrosoftOauth||e.disablePasswordAuth===!0,{message:`allowMicrosoftOauth requires disablePasswordAuth to be enabled`,path:[`allowMicrosoftOauth`]}).refine(e=>!e.disablePasswordAuth||e.allowGoogleOauth===!0||e.allowMicrosoftOauth===!0,{message:`disablePasswordAuth requires allowGoogleOauth or allowMicrosoftOauth to be enabled`,path:[`disablePasswordAuth`]}).refine(e=>!e.disablePasswordAuth||!e.allowSelfPasswordReset,{message:`disablePasswordAuth cannot be used with allowSelfPasswordReset`,path:[`disablePasswordAuth`]}).refine(e=>!e.requireMfa||e.enableMfa===!0,{message:`requireMfa requires enableMfa to be enabled`,path:[`requireMfa`]}).refine(e=>!e.enableMfa||e.allowedReturnOrigins&&e.allowedReturnOrigins.length>0,{message:`enableMfa requires allowedReturnOrigins to list at least one origin so MFA self-service has a valid return target`,path:[`enableMfa`]}),Ct=k.string().max(200,`must be 200 characters or less`).regex(/^[^\r\n]*$/,`must not contain newline characters`),wt=k.strictObject({fromName:Ct.optional().describe(`Default sender display name for emails`),passwordResetSubject:Ct.optional().describe(`Default subject for password reset emails`)}).describe(`Namespace-level email configuration defaults`),Q=k.union([k.string(),k.boolean(),k.array(k.string()).readonly(),k.array(k.boolean()).readonly(),k.strictObject({user:k.string()}),k.strictObject({idpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({oldIdpUser:k.enum([`id`,`name`,`disabled`])}),k.strictObject({newIdpUser:k.enum([`id`,`name`,`disabled`])})]),Tt=k.enum([`=`,`!=`,`in`,`not in`]),Et=k.tuple([Q,Tt,Q]).readonly(),$=k.union([k.strictObject({conditions:k.union([Et,k.array(Et).readonly()]),description:k.string().optional(),permit:k.boolean().optional()}),k.tuple([Q,Tt,Q]).readonly(),k.tuple([Q,Tt,Q,k.boolean()]).readonly(),k.array(k.union([Et,k.boolean()])).refine(e=>{let t=e.findIndex(e=>typeof e==`boolean`);return t===-1||t===e.length-1},{message:`Boolean permit flag must only appear at the end`}).readonly()]),Dt=k.strictObject({create:k.array($).readonly(),read:k.array($).readonly(),update:k.array($).readonly(),delete:k.array($).readonly(),sendPasswordResetEmail:k.array($).readonly().optional(),unenrollMfa:k.array($).readonly().optional()}).describe(`Per-operation permission policies for IdP users`),Ot=k.strictObject({name:k.string().describe(`IdP service name`),authorization:k.union([k.literal(`insecure`),k.literal(`loggedIn`),k.strictObject({cel:k.string()})]).optional().describe(`Authorization mode for IdP API access`),clients:k.array(k.string()).describe(`OAuth2 client names that can use this IdP`),lang:xt.optional().describe(`UI language for IdP pages`),userAuthPolicy:St.transform(e=>St.parse(e??{})).optional().describe(`User authentication policy configuration`),publishEvents:k.boolean().optional().describe(`Enable publishing user lifecycle events`),gqlOperations:bt.optional().describe(`Configure which GraphQL operations are enabled`),emailConfig:wt.optional().describe(`Namespace-level email configuration defaults`),permission:Dt.optional().describe(`Per-operation permission policies for IdP users`)}).refine(e=>!e.userAuthPolicy?.enableMfa||e.gqlOperations?.unenrollMfa===!1||e.permission!==void 0&&e.permission.unenrollMfa!==void 0,{message:`permission.unenrollMfa must be set explicitly when userAuthPolicy.enableMfa is true (set [{ conditions: [...], permit: true }] to allow, or [] to deny all). permission itself must also be defined. The requirement is only relaxed when gqlOperations.unenrollMfa is false.`,path:[`permission`,`unenrollMfa`]}).refine(e=>!e.permission||e.userAuthPolicy?.disablePasswordAuth===!0||e.gqlOperations?.sendPasswordResetEmail===!1||e.permission.sendPasswordResetEmail!==void 0,{message:`permission.sendPasswordResetEmail must be set explicitly when password authentication is enabled (set [{ conditions: [...], permit: true }] to allow, or [] to deny; only optional when userAuthPolicy.disablePasswordAuth is true or gqlOperations.sendPasswordResetEmail is false)`,path:[`permission`,`sendPasswordResetEmail`]}),kt=k.string().regex(/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/),At=k.record(kt,k.string().nullish()),jt=k.strictObject({vaults:k.record(kt,At),options:k.strictObject({ignoreNullishValues:k.boolean()})}),Mt=k.strictObject({name:k.string().describe(`Static website name`),description:k.string().optional().describe(`Static website description`),allowedIpAddresses:k.array(k.string()).optional().describe(`IP addresses allowed to access the website`),customDomains:k.array(k.string()).optional().describe(`Custom domains for the static website`)}),Nt=/^[a-z0-9]+$/,Pt=/^[A-Za-z_][A-Za-z0-9_]*$/;function checkWaitPointKey(e){let{key:r,declaredBy:a}=e,o=r.split(`-`),s=o.filter(i);if(s.length>0&&a!==`define`)return a===`property`?`Invalid wait point key "${r}": $params cannot come from a property name. Pass the key to define instead, e.g. define.for("${r}")<Payload, Result>().`:`Invalid wait point key "${r}": createWaitPoint takes its type arguments first, which stops TypeScript inferring the key as a literal, so it cannot type the $params. Declare it through createWaitPoints instead: createWaitPoints((define) => ({ myWaitPoint: define.for("${r}")<Payload, Result>() })).`;let c=new Set,l=0;for(let e of o){if(e.startsWith(`$`)){let t=e.slice(1);if(!Pt.test(t))return`Invalid wait point key "${r}": "${e}" is not a usable parameter name. Use letters, digits and underscores, starting with a letter or underscore.`;if(c.has(t))return`Invalid wait point key "${r}": parameter "$${t}" appears more than once.`;c.add(t);continue}if(e!==``){if(!Nt.test(e))return`Invalid wait point key "${r}": segment "${e}" may only contain [a-z0-9]. Wait point keys accept ${n}, with $params standing in for runtime values.`;l+=1}}if(l===0&&s.length>0)return r.startsWith(`-`)||r.endsWith(`-`)?`Invalid wait point key "${r}": must match ${n}.`:`Invalid wait point key "${r}": it needs at least one literal segment alongside its $params, otherwise the key carries no identity of its own and can collide with an unrelated wait point.`;if(s.length===0)return t.test(r)?void 0:`Invalid wait point key "${r}": must match ${n}.`;let u=o.map(e=>e.startsWith(`$`)?`0`:e).join(`-`);return u.length>63?`Wait point key "${r}" cannot fit in 63 characters: even single-character parameter values produce ${u.length}.`:t.test(u)?void 0:`Invalid wait point key "${r}": must match ${n}.`}function collectWaitPointKeyFailures(e){let t=[],n=new Set;for(let r of e){let e=`${r.declaredBy} ${r.key}`;if(n.has(e))continue;n.add(e);let i=checkWaitPointKey(r);i&&t.push(i)}return t}function defineTailorDB(e,t,n){let r=[],i=[],a=[];if(!e)return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a};for(let[o,s]of Object.entries(e)){if(`external`in s)i.push(o);else{let e=createTailorDBService({namespace:o,config:C.parse(s),pluginManager:n,baseDir:t});r.push(e)}a.push({Type:`tailordb`,Name:o})}return{tailorDBServices:r,externalTailorDBNamespaces:i,subgraphs:a}}function defineResolver(e,t){let n=[],r=[];if(!e)return{resolverServices:n,subgraphs:r};for(let[i,a]of Object.entries(e)){if(!(`external`in a)){let e=createResolverService(i,a,t);n.push(e)}r.push({Type:`pipeline`,Name:i})}return{resolverServices:n,subgraphs:r}}function stripIdpProviderHelper(e){let t=e;if(typeof t.provider!=`function`)return e;let{provider:n,...r}=t;return r}function defineIdp(e){let t=[],n=[];if(!e)return{idpServices:t,subgraphs:n};let r=new Set;return e.forEach(e=>{let i=e.name;if(r.has(i))throw Error(`IdP with name "${i}" already defined.`);if(r.add(i),!(`external`in e)){let n=Ot.parse(stripIdpProviderHelper(e));t.push(n)}n.push({Type:`idp`,Name:i})}),{idpServices:t,subgraphs:n}}function defineAuth(e,t,n){let r=[];if(!e)return{authService:void 0,subgraphs:r};let i;return`external`in e||(i=createAuthService(l.parse(e),t,n)),r.push({Type:`auth`,Name:e.name}),{authService:i,subgraphs:r}}function defineExecutor(e,t,n){if(e||n)return S({config:e??{files:[]},baseDir:t})}function defineWorkflow(e,t){if(e)return createWorkflowService({config:e,baseDir:t})}function defineHttpAdapterService(e,t){if(e)return createHttpAdapterService({config:e,baseDir:t})}function stripStaticWebsiteUrlHelper(e){let t=e;if(t.url!==`${e.name}:url`)return e;let{url:n,...r}=t;return r}function defineStaticWebsites(e){let t=[],n=new Set;return(e??[]).forEach(e=>{let r=Mt.parse(stripStaticWebsiteUrlHelper(e));if(n.has(r.name))throw Error(`Static website with name "${r.name}" already defined.`);n.add(r.name),t.push(r)}),t}function defineAIGateways(e,t){let n=[],r=new Set;return(e??[]).forEach(e=>{let i=vt.parse(e);if(r.has(i.name))throw Error(`AI Gateway with name "${i.name}" already defined.`);if(r.add(i.name),i.authNamespace===void 0){if(!t)throw Error(`AI Gateway "${i.name}" has no "authNamespace" and no Auth service is configured to default to. Define an Auth service, or set "authNamespace" explicitly.`);i.authNamespace=t}n.push(i)}),n}function parseSecretManager(e){if(!e)return{secrets:[],ignoreNullishValues:!1};let t=jt.parse(e),{ignoreNullishValues:n}=t.options,r=Object.entries(t.vaults).map(([e,t])=>({vaultName:e,secrets:Object.entries(t).map(([e,t])=>({name:e,value:t}))}));if(!n){for(let e of r)for(let t of e.secrets)if(t.value==null)throw Error(`Secret "${e.vaultName}/${t.name}" has no value. Use { ignoreNullishValues: true } option in defineSecretManager() to skip secrets without values.`)}return{secrets:r,ignoreNullishValues:n}}function defineServices(e,t,n){let r=defineTailorDB(e.db,t,n),i=defineResolver(e.resolver,t),a=defineIdp(e.idp),o=defineAuth(e.auth,r.tailorDBServices,r.externalTailorDBNamespaces),s=defineStaticWebsites(e.staticWebsites),c=defineAIGateways(e.aiGateways,getApplicationAuthNamespace({authService:o.authService,config:e})),{secrets:l,ignoreNullishValues:u}=parseSecretManager(e.secrets);return{tailordbResult:r,resolverResult:i,idpResult:a,authResult:o,staticWebsiteServices:s,aiGatewayServices:c,secrets:l,ignoreNullishValues:u}}function buildApplication(e){let t={name:e.config.name,id:e.config.id,config:e.config,subgraphs:[...e.tailordbResult.subgraphs,...e.resolverResult.subgraphs,...e.idpResult.subgraphs,...e.authResult.subgraphs],tailorDBServices:e.tailordbResult.tailorDBServices,externalTailorDBNamespaces:e.tailordbResult.externalTailorDBNamespaces,resolverServices:e.resolverResult.resolverServices,idpServices:e.idpResult.idpServices,authService:e.authResult.authService,executorService:e.executorService,workflowService:e.workflowService,httpAdapterService:e.httpAdapterService,staticWebsiteServices:e.staticWebsiteServices,aiGatewayServices:e.aiGatewayServices,secrets:e.secrets,ignoreNullishValues:e.ignoreNullishValues,env:e.env,get applications(){return[t]}};return t}function defineApplication(e){let{config:t,pluginManager:n}=e,r=O.dirname(t.path),i=defineServices(t,r,n),a=defineExecutor(t.executor,r,!1),o=defineWorkflow(t.workflow,r),s=defineHttpAdapterService(t.httpAdapter,r);return buildApplication({config:t,...i,executorService:a,workflowService:o,httpAdapterService:s,env:t.env??{}})}function generatePluginFilesIfNeeded(e,t,n){if(!e)return[];let r=new Map;for(let e of t){let t=e.typeSourceInfo;for(let[e,n]of Object.entries(t))n.filePath&&r.set(e,{filePath:n.filePath,exportName:n.exportName})}return e.generatePluginFiles({outputDir:O.join(getDistDir(),`plugin`),sourceTableInfoMap:r,configPath:n,tableGenerator:generatePluginTableFiles,executorGenerator:generatePluginExecutorFiles})}function assertWaitPointKeys(){let e=collectWaitPointKeyFailures(r());if(e.length!==0)throw Error(e.join(`
198
+ `))}async function loadApplication(e){let{config:t,pluginManager:n,bundleCache:r}=e,i=O.dirname(t.path),{tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p}=defineServices(t,i,n);for(let e of a.tailorDBServices)await e.loadTypes(),await e.processNamespacePlugins();assertUniqueLocalTailorDBTypeNames({tailorDBServices:a.tailorDBServices});let m=generatePluginFilesIfNeeded(n,a.tailorDBServices,t.path),h=defineExecutor(t.executor,i,m.length>0),g=defineWorkflow(t.workflow,i);g&&await g.loadWorkflows();let _=defineHttpAdapterService(t.httpAdapter,i);_&&await _.loadAdapters();let v=await buildStartContext(t.workflow,getApplicationAuthNamespace({authService:l.authService,config:t}),i),y=resolveInlineSourcemap(t.inlineSourcemap),b=resolveBundleLogLevel(t.logLevel),x=createTsconfigLookupCache(),S={resolvers:new Map,executors:new Map,workflowJobs:new Map,authHooks:new Map};for(let e of o.resolverServices){let t=await bundleResolvers({namespace:e.namespace,config:e.config,baseDir:i,defaultPermission:e.defaultPermission,startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,tsconfigCache:x});for(let[n,r]of t)S.resolvers.set(resolverBundleKey(e.namespace,n),r)}h&&(S.executors=await bundleExecutors({config:h.config,startContext:v,additionalFiles:[...m],cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x}));let C;if(g&&g.jobs.length>0){let e=g.workflowSources.map(e=>e.workflow.mainJob.name);C=await bundleWorkflowJobs(g.jobs,e,t.env??{},v,i,r,y,b,x),S.workflowJobs=C.bundledCode}let w;if(_&&_.adapters.length>0&&(w=await bundleHttpAdapters(_.adapters.map(e=>({name:e.adapter.name,sourceFile:e.sourceFile,methods:e.methods,hasOutput:e.hasOutput})),i,r,b,x)),l.authService?.config.hooks?.beforeLogin){let e=l.authService.config.name;S.authHooks=await bundleAuthHooks({configPath:t.path,authName:e,handlerAccessPath:`auth.hooks.beforeLogin.handler`,env:t.env??{},startContext:v,cache:r,inlineSourcemap:y,bundleLogLevel:b,baseDir:i,tsconfigCache:x})}for(let e of o.resolverServices)await e.loadResolvers();return h&&(await h.loadExecutors(),m.length>0&&await h.loadPluginExecutorFiles([...m])),assertWaitPointKeys(),g&&g.printLoadedWorkflows(),_&&_.printLoadedAdapters(),s.newline(),{application:buildApplication({config:t,tailordbResult:a,resolverResult:o,idpResult:c,authResult:l,executorService:h,workflowService:g,httpAdapterService:_,staticWebsiteServices:u,aiGatewayServices:d,secrets:f,ignoreNullishValues:p,env:t.env??{}}),workflowBuildResult:C,httpAdapterBuildResult:w,bundledScripts:S}}export{initOperatorClient as $,composeFunctionTreeshakeOptions as A,closeConnectionPool as B,stringifyFunction as C,createTsconfigPathsPlugin as D,createGeneratedEntryResolverPlugin as E,hashContent as F,fetchPaged as G,fetchAll as H,hashFile as I,getConsoleBaseUrl as J,fetchPlatformMachineUserToken as K,getPluginGenerationDependencies as L,resolveBundleLogLevel as M,createBundleLog as N,resolveTSConfigWithFallback as O,createBundleCache as P,initOAuth2Client as Q,getRawPluginTableName as R,hasOmittedPermit as S,G as T,fetchAllTolerant as U,be as V,fetchMachineUserToken as W,getOrNull as X,getOAuth2ClientId as Y,getPlatformBaseUrl as Z,buildResolverOperationHookExpr as _,resolverBundleKey as a,byName as at,assertUniqueTailorDBTypeNamesWithExternal as b,getApplicationAuthNamespace as c,ct as d,isDefaultPlatform as et,resolveResolverDefaultPermissionForFile as f,buildExecutorArgsExpr as g,q as h,hasImplicitAllEmailDomains as i,resolveStaticWebsiteUrls as it,createLogLevelTreeshakeOptions as j,U as k,requireApplicationAuthNamespace as l,Y as m,generatePluginFilesIfNeeded as n,normalizeBaseUrl as nt,resolveInlineSourcemap as o,createApplyLimiter as ot,X as p,fetchUserInfo as q,loadApplication as r,rememberPlatformConfigForToken as rt,getDistDir as s,I as st,defineApplication as t,isNotFoundError as tt,gt as u,buildResolverValidatedInputExpr as v,Ve as w,createPermissionNormalizer as x,assertUniqueLocalTailorDBTypeNames as y,hasGenerationHooks as z};
199
+ //# sourceMappingURL=application-CfevPO-k.mjs.map