@tailor-platform/sdk 1.76.1 → 1.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/{application-BUfYmf0O.mjs → application-CUxVA7Fs.mjs} +378 -1679
  3. package/dist/application-CUxVA7Fs.mjs.map +1 -0
  4. package/dist/application-Dp_-ioiP.mjs +3 -0
  5. package/dist/cli/cache/bundle-cache.d.mts +2 -1
  6. package/dist/cli/cache/store.d.mts +1 -1
  7. package/dist/cli/commands/api/index.d.mts +1 -0
  8. package/dist/cli/commands/deploy/aigateway.d.mts +5 -1
  9. package/dist/cli/commands/deploy/application.d.mts +7 -1
  10. package/dist/cli/commands/deploy/apply-phases.d.mts +14 -1
  11. package/dist/cli/commands/deploy/auth.d.mts +5 -1
  12. package/dist/cli/commands/deploy/deploy.d.mts +13 -3
  13. package/dist/cli/commands/deploy/executor.d.mts +7 -1
  14. package/dist/cli/commands/deploy/function-registry.d.mts +5 -0
  15. package/dist/cli/commands/deploy/idp.d.mts +5 -1
  16. package/dist/cli/commands/deploy/resolver.d.mts +5 -1
  17. package/dist/cli/commands/deploy/secret-manager.d.mts +5 -1
  18. package/dist/cli/commands/deploy/staticwebsite.d.mts +5 -1
  19. package/dist/cli/commands/deploy/tailordb/index.d.mts +8 -1
  20. package/dist/cli/commands/deploy/types.d.mts +3 -1
  21. package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +3 -1
  22. package/dist/cli/commands/deploy/workflow.d.mts +4 -1
  23. package/dist/cli/commands/executor/get.d.mts +0 -1
  24. package/dist/cli/commands/executor/jobs.d.mts +0 -1
  25. package/dist/cli/commands/executor/list.d.mts +0 -1
  26. package/dist/cli/commands/executor/transform.d.mts +1 -0
  27. package/dist/cli/commands/executor/trigger.d.mts +0 -1
  28. package/dist/cli/commands/executor/webhook.d.mts +0 -1
  29. package/dist/cli/commands/function/get.d.mts +0 -1
  30. package/dist/cli/commands/function/list.d.mts +0 -1
  31. package/dist/cli/commands/function/transform.d.mts +1 -0
  32. package/dist/cli/commands/generate/service.d.mts +5 -1
  33. package/dist/cli/commands/generate/types.d.mts +3 -1
  34. package/dist/cli/commands/machineuser/list.d.mts +0 -1
  35. package/dist/cli/commands/machineuser/token.d.mts +0 -1
  36. package/dist/cli/commands/oauth2client/get.d.mts +0 -1
  37. package/dist/cli/commands/oauth2client/list.d.mts +0 -1
  38. package/dist/cli/commands/oauth2client/transform.d.mts +1 -0
  39. package/dist/cli/commands/organization/folder/create.d.mts +0 -1
  40. package/dist/cli/commands/organization/folder/delete.d.mts +0 -1
  41. package/dist/cli/commands/organization/folder/get.d.mts +0 -1
  42. package/dist/cli/commands/organization/folder/list.d.mts +0 -1
  43. package/dist/cli/commands/organization/folder/update.d.mts +0 -1
  44. package/dist/cli/commands/organization/get.d.mts +0 -1
  45. package/dist/cli/commands/organization/list.d.mts +0 -1
  46. package/dist/cli/commands/organization/transform.d.mts +2 -0
  47. package/dist/cli/commands/organization/tree.d.mts +0 -1
  48. package/dist/cli/commands/organization/update.d.mts +0 -1
  49. package/dist/cli/commands/remove.d.mts +0 -1
  50. package/dist/cli/commands/show.d.mts +9 -4
  51. package/dist/cli/commands/tailordb/migrate/config.d.mts +0 -1
  52. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +0 -1
  53. package/dist/cli/commands/tailordb/migrate/generate.d.mts +0 -1
  54. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -1
  55. package/dist/cli/commands/tailordb/truncate.d.mts +0 -1
  56. package/dist/cli/commands/workflow/executions.d.mts +0 -1
  57. package/dist/cli/commands/workflow/get.d.mts +2 -1
  58. package/dist/cli/commands/workflow/list.d.mts +0 -1
  59. package/dist/cli/commands/workflow/resume.d.mts +0 -1
  60. package/dist/cli/commands/workflow/start.d.mts +0 -1
  61. package/dist/cli/commands/workflow/status.d.mts +1 -0
  62. package/dist/cli/commands/workflow/transform.d.mts +1 -0
  63. package/dist/cli/commands/workflow/wait.d.mts +0 -1
  64. package/dist/cli/commands/workflow/waiter.d.mts +1 -1
  65. package/dist/cli/commands/workspace/app/health.d.mts +0 -1
  66. package/dist/cli/commands/workspace/app/list.d.mts +0 -1
  67. package/dist/cli/commands/workspace/app/transform.d.mts +2 -0
  68. package/dist/cli/commands/workspace/create.d.mts +3 -1
  69. package/dist/cli/commands/workspace/delete.d.mts +0 -1
  70. package/dist/cli/commands/workspace/get.d.mts +0 -1
  71. package/dist/cli/commands/workspace/list.d.mts +1 -1
  72. package/dist/cli/commands/workspace/restore.d.mts +0 -1
  73. package/dist/cli/commands/workspace/transform.d.mts +4 -0
  74. package/dist/cli/commands/workspace/user/invite.d.mts +0 -1
  75. package/dist/cli/commands/workspace/user/list.d.mts +0 -1
  76. package/dist/cli/commands/workspace/user/remove.d.mts +0 -1
  77. package/dist/cli/commands/workspace/user/transform.d.mts +1 -0
  78. package/dist/cli/commands/workspace/user/update.d.mts +0 -1
  79. package/dist/cli/index.d.mts +3 -1
  80. package/dist/cli/index.mjs +660 -56
  81. package/dist/cli/index.mjs.map +1 -1
  82. package/dist/cli/lib.d.mts +4 -2
  83. package/dist/cli/lib.mjs +3 -3
  84. package/dist/cli/lib.mjs.map +1 -1
  85. package/dist/cli/query/index.d.mts +0 -1
  86. package/dist/cli/services/application.d.mts +12 -1
  87. package/dist/cli/services/auth/service.d.mts +2 -0
  88. package/dist/cli/services/executor/service.d.mts +1 -1
  89. package/dist/cli/services/http-adapter/bundler.d.mts +3 -1
  90. package/dist/cli/services/http-adapter/service.d.mts +2 -1
  91. package/dist/cli/services/resolver/service.d.mts +1 -1
  92. package/dist/cli/services/tailordb/service.d.mts +3 -1
  93. package/dist/cli/services/workflow/bundler.d.mts +2 -1
  94. package/dist/cli/services/workflow/service.d.mts +1 -1
  95. package/dist/cli/shared/args.d.mts +1 -1
  96. package/dist/cli/shared/client.d.mts +1 -1
  97. package/dist/cli/shared/config-loader.d.mts +0 -1
  98. package/dist/cli/shared/context.d.mts +2 -1
  99. package/dist/cli/shared/script-executor.d.mts +0 -1
  100. package/dist/cli/shared/seed-chunker.d.mts +7 -3
  101. package/dist/cli/shared/type-generator.d.mts +0 -1
  102. package/dist/cli/shared/workspace-name.d.mts +1 -0
  103. package/dist/cli/skills.mjs +1 -1
  104. package/dist/completion/zsh-worker.zsh +18 -1
  105. package/dist/configure/config/index.d.mts +0 -1
  106. package/dist/configure/config/types.d.mts +2 -2
  107. package/dist/configure/index.d.mts +2 -1
  108. package/dist/configure/index.mjs +248 -4
  109. package/dist/configure/index.mjs.map +1 -1
  110. package/dist/configure/services/aigateway/index.d.mts +0 -1
  111. package/dist/configure/services/aigateway/types.d.mts +0 -1
  112. package/dist/configure/services/auth/index.d.mts +0 -1
  113. package/dist/configure/services/auth/types.d.mts +14 -13
  114. package/dist/configure/services/executor/executor.d.mts +0 -1
  115. package/dist/configure/services/executor/index.d.mts +1 -0
  116. package/dist/configure/services/executor/operation.d.mts +1 -2
  117. package/dist/configure/services/executor/trigger/event.d.mts +0 -1
  118. package/dist/configure/services/executor/trigger/index.d.mts +0 -1
  119. package/dist/configure/services/executor/trigger/schedule.d.mts +0 -1
  120. package/dist/configure/services/executor/trigger/webhook.d.mts +0 -1
  121. package/dist/configure/services/http-adapter/http-adapter.d.mts +1 -2
  122. package/dist/configure/services/idp/index.d.mts +1 -5
  123. package/dist/configure/services/idp/permission.d.mts +4 -5
  124. package/dist/configure/services/idp/types.d.mts +0 -1
  125. package/dist/configure/services/index.d.mts +5 -0
  126. package/dist/configure/services/resolver/resolver.d.mts +0 -1
  127. package/dist/configure/services/resolver/types.d.mts +0 -1
  128. package/dist/configure/services/secrets/index.d.mts +0 -1
  129. package/dist/configure/services/secrets/types.d.mts +0 -1
  130. package/dist/configure/services/staticwebsite/index.d.mts +0 -1
  131. package/dist/configure/services/staticwebsite/types.d.mts +0 -1
  132. package/dist/configure/services/tailordb/permission.d.mts +4 -5
  133. package/dist/configure/services/tailordb/schema.d.mts +21 -8
  134. package/dist/configure/services/tailordb/types.d.mts +4 -5
  135. package/dist/configure/services/workflow/execution-policy.d.mts +0 -1
  136. package/dist/configure/services/workflow/execution-policy.types.d.mts +0 -1
  137. package/dist/configure/services/workflow/index.d.mts +1 -0
  138. package/dist/configure/services/workflow/job.d.mts +0 -1
  139. package/dist/configure/services/workflow/wait-point.d.mts +0 -1
  140. package/dist/configure/services/workflow/workflow.d.mts +0 -1
  141. package/dist/configure/types/field-runtime.d.mts +1 -1
  142. package/dist/configure/types/field.d.mts +1 -2
  143. package/dist/configure/types/field.types.d.mts +1 -2
  144. package/dist/configure/types/type.d.mts +1 -1
  145. package/dist/configure/user.d.mts +0 -1
  146. package/dist/{crashreport-ayWANEZ6.mjs → crashreport-BNWUM6Kf.mjs} +4 -3
  147. package/dist/{crashreport-ayWANEZ6.mjs.map → crashreport-BNWUM6Kf.mjs.map} +1 -1
  148. package/dist/{crashreport-Dy4ZzSkd.mjs → crashreport-BafWvjjX.mjs} +1 -1
  149. package/dist/errors-DVFS0AZk.mjs +100 -0
  150. package/dist/errors-DVFS0AZk.mjs.map +1 -0
  151. package/dist/{globals-CcU1ONiK.mjs → globals-CvizbGLY.mjs} +2 -2
  152. package/dist/{globals-CcU1ONiK.mjs.map → globals-CvizbGLY.mjs.map} +1 -1
  153. package/dist/kysely/index.d.mts +3 -4
  154. package/dist/{logger-BEiZZ3qT.mjs → logger-BwS4ppwO.mjs} +3 -3
  155. package/dist/logger-BwS4ppwO.mjs.map +1 -0
  156. package/dist/parser/service/auth/index.d.mts +1 -1
  157. package/dist/parser/service/auth/schema.d.mts +1 -0
  158. package/dist/parser/service/http-adapter/index.d.mts +1 -1
  159. package/dist/parser/service/idp/types.d.mts +1 -0
  160. package/dist/parser/service/tailordb/types.d.mts +0 -1
  161. package/dist/plugin/builtin/enum-constants/index.d.mts +0 -1
  162. package/dist/plugin/builtin/file-utils/index.d.mts +0 -1
  163. package/dist/plugin/builtin/kysely-type/index.d.mts +0 -1
  164. package/dist/plugin/builtin/seed/index.d.mts +0 -1
  165. package/dist/plugin/builtin/seed/index.mjs +1 -1
  166. package/dist/plugin/get-generated-type.d.mts +0 -1
  167. package/dist/plugin/manager.d.mts +3 -1
  168. package/dist/plugin/types.d.mts +0 -1
  169. package/dist/plugin/with-context.d.mts +0 -1
  170. package/dist/{registry-NfSW0BRo.mjs → registry-CYBRvfaU.mjs} +4 -49
  171. package/dist/registry-CYBRvfaU.mjs.map +1 -0
  172. package/dist/runtime/aigateway.d.mts +0 -2
  173. package/dist/runtime/authconnection.d.mts +0 -2
  174. package/dist/runtime/globals.d.mts +0 -1
  175. package/dist/runtime/index.d.mts +0 -1
  176. package/dist/runtime/types.d.mts +16 -7
  177. package/dist/{runtime-_vUgjiqT.mjs → runtime-BD2vYJFT.mjs} +2382 -1167
  178. package/dist/runtime-BD2vYJFT.mjs.map +1 -0
  179. package/dist/{schema-DrVyN-LP.mjs → schema-U6DxoZ8D.mjs} +204 -3
  180. package/dist/schema-U6DxoZ8D.mjs.map +1 -0
  181. package/dist/{secret-file-VSVGy1V0.mjs → secret-file-DBqZhjFQ.mjs} +2 -27
  182. package/dist/{secret-file-VSVGy1V0.mjs.map → secret-file-DBqZhjFQ.mjs.map} +1 -1
  183. package/dist/{secretmanager-Bd45j7an.mjs → secretmanager-IY4UvinW.mjs} +42 -9
  184. package/dist/secretmanager-IY4UvinW.mjs.map +1 -0
  185. package/dist/seed/index.d.mts +3 -2
  186. package/dist/{seed-fm0LeYP2.mjs → seed-DFFigL8V.mjs} +3 -13
  187. package/dist/seed-DFFigL8V.mjs.map +1 -0
  188. package/dist/service-CghpdV-9.mjs +3 -0
  189. package/dist/{service-DBFZQloR.mjs → service-Cp0I7ZFe.mjs} +3 -3
  190. package/dist/{service-DBFZQloR.mjs.map → service-Cp0I7ZFe.mjs.map} +1 -1
  191. package/dist/{service-BCRJ-3NV.mjs → service-D12iQGcS.mjs} +2 -2
  192. package/dist/{service-BCRJ-3NV.mjs.map → service-D12iQGcS.mjs.map} +1 -1
  193. package/dist/service_pb-BoLM0X4K.mjs +167 -0
  194. package/dist/service_pb-BoLM0X4K.mjs.map +1 -0
  195. package/dist/{service_pb-B2FF59sP.mjs → service_pb-r1T7kpJc.mjs} +1 -1
  196. package/dist/tailor-proto/src/tailor/v1/aigateway_pb.d.mts +0 -1
  197. package/dist/tailor-proto/src/tailor/v1/aigateway_resource_pb.d.mts +0 -1
  198. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +0 -1
  199. package/dist/tailor-proto/src/tailor/v1/application_resource_pb.d.mts +0 -1
  200. package/dist/tailor-proto/src/tailor/v1/auth_pb.d.mts +0 -1
  201. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +0 -1
  202. package/dist/tailor-proto/src/tailor/v1/events_pb.d.mts +0 -1
  203. package/dist/tailor-proto/src/tailor/v1/events_resource_pb.d.mts +0 -1
  204. package/dist/tailor-proto/src/tailor/v1/executor_pb.d.mts +0 -1
  205. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +0 -1
  206. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +0 -1
  207. package/dist/tailor-proto/src/tailor/v1/function_registry_pb.d.mts +0 -1
  208. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +0 -1
  209. package/dist/tailor-proto/src/tailor/v1/http_adapter_resource_pb.d.mts +0 -1
  210. package/dist/tailor-proto/src/tailor/v1/idp_pb.d.mts +0 -1
  211. package/dist/tailor-proto/src/tailor/v1/idp_resource_pb.d.mts +0 -1
  212. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +0 -1
  213. package/dist/tailor-proto/src/tailor/v1/metadata_resource_pb.d.mts +0 -1
  214. package/dist/tailor-proto/src/tailor/v1/meter_pb.d.mts +0 -1
  215. package/dist/tailor-proto/src/tailor/v1/pipeline_pb.d.mts +0 -1
  216. package/dist/tailor-proto/src/tailor/v1/pipeline_resource_pb.d.mts +0 -1
  217. package/dist/tailor-proto/src/tailor/v1/resource_pb.d.mts +0 -1
  218. package/dist/tailor-proto/src/tailor/v1/secret_manager_pb.d.mts +0 -1
  219. package/dist/tailor-proto/src/tailor/v1/secret_manager_resource_pb.d.mts +0 -1
  220. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +0 -1
  221. package/dist/tailor-proto/src/tailor/v1/stateflow_pb.d.mts +0 -1
  222. package/dist/tailor-proto/src/tailor/v1/stateflow_resource_pb.d.mts +0 -1
  223. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +0 -1
  224. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +0 -1
  225. package/dist/tailor-proto/src/tailor/v1/tailordb_pb.d.mts +0 -1
  226. package/dist/tailor-proto/src/tailor/v1/tailordb_resource_pb.d.mts +0 -1
  227. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_pb.d.mts +0 -1
  228. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +0 -1
  229. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +0 -1
  230. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +0 -1
  231. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +0 -1
  232. package/dist/tailor-proto/src/tailor/v1/workspace_resource_pb.d.mts +0 -1
  233. package/dist/test-env-key-DuZycyWM.mjs +49 -0
  234. package/dist/test-env-key-DuZycyWM.mjs.map +1 -0
  235. package/dist/type-source-DH_LH20p.mjs +13 -0
  236. package/dist/type-source-DH_LH20p.mjs.map +1 -0
  237. package/dist/types/aigateway.generated.d.mts +5 -2
  238. package/dist/types/auth-connection.generated.d.mts +11 -5
  239. package/dist/types/auth.generated.d.mts +118 -85
  240. package/dist/types/executor.generated.d.mts +76 -84
  241. package/dist/types/helpers.d.mts +5 -5
  242. package/dist/types/http-adapter.generated.d.mts +11 -5
  243. package/dist/types/idp.generated.d.mts +536 -524
  244. package/dist/types/resolver.generated.d.mts +24 -10
  245. package/dist/types/staticwebsite.generated.d.mts +7 -3
  246. package/dist/types/tailordb.generated.d.mts +55 -29
  247. package/dist/types/workflow.generated.d.mts +9 -4
  248. package/dist/user-agent-DX2Jnw0-.mjs +28 -0
  249. package/dist/user-agent-DX2Jnw0-.mjs.map +1 -0
  250. package/dist/utils/test/index.d.mts +0 -1
  251. package/dist/utils/test/index.mjs +1 -1
  252. package/dist/utils/test/mock.d.mts +0 -1
  253. package/dist/vitest/environment.mjs +1 -1
  254. package/dist/vitest/index.d.mts +9 -9
  255. package/dist/vitest/index.mjs +600 -185
  256. package/dist/vitest/index.mjs.map +1 -1
  257. package/dist/vitest/mock-kysely.d.mts +0 -1
  258. package/dist/vitest/mock.d.mts +8 -8
  259. package/dist/vitest/mocks/aigateway.d.mts +16 -6
  260. package/dist/vitest/mocks/authconnection.d.mts +16 -6
  261. package/dist/vitest/mocks/file.d.mts +24 -6
  262. package/dist/vitest/mocks/iconv.d.mts +28 -4
  263. package/dist/vitest/mocks/idp.d.mts +26 -10
  264. package/dist/vitest/mocks/secretmanager.d.mts +16 -5
  265. package/dist/vitest/mocks/tailordb.d.mts +54 -10
  266. package/dist/vitest/mocks/workflow.d.mts +48 -11
  267. package/dist/vitest/setup.mjs +2 -2
  268. package/dist/{service_pb-B5w9rjPY.mjs → workspace_resource_pb-Db3fv68L.mjs} +57 -165
  269. package/dist/workspace_resource_pb-Db3fv68L.mjs.map +1 -0
  270. package/docs/cli/application.md +58 -11
  271. package/docs/cli/setup.md +1 -1
  272. package/docs/cli/workspace.md +6 -4
  273. package/docs/cli-reference.md +12 -8
  274. package/docs/runtime.md +3 -4
  275. package/docs/services/aigateway.md +2 -0
  276. package/docs/services/tailordb.md +52 -1
  277. package/docs/services/workflow.md +1 -1
  278. package/docs/testing.md +103 -89
  279. package/package.json +16 -16
  280. package/dist/application-BUfYmf0O.mjs.map +0 -1
  281. package/dist/application-DbvD5UUz.mjs +0 -3
  282. package/dist/cli/shared/trigger-context.d.mts +0 -1
  283. package/dist/errors-Dtf2WPaW.mjs +0 -42
  284. package/dist/errors-Dtf2WPaW.mjs.map +0 -1
  285. package/dist/field-runtime-9bfXBAOK.mjs +0 -183
  286. package/dist/field-runtime-9bfXBAOK.mjs.map +0 -1
  287. package/dist/job-D-PbD1P3.mjs +0 -55
  288. package/dist/job-D-PbD1P3.mjs.map +0 -1
  289. package/dist/logger-BEiZZ3qT.mjs.map +0 -1
  290. package/dist/registry-NfSW0BRo.mjs.map +0 -1
  291. package/dist/resource_pb-BRv7AMXK.mjs +0 -49
  292. package/dist/resource_pb-BRv7AMXK.mjs.map +0 -1
  293. package/dist/runtime-_vUgjiqT.mjs.map +0 -1
  294. package/dist/schema-DrVyN-LP.mjs.map +0 -1
  295. package/dist/secretmanager-Bd45j7an.mjs.map +0 -1
  296. package/dist/seed-fm0LeYP2.mjs.map +0 -1
  297. package/dist/service-CPMlIg3X.mjs +0 -3
  298. package/dist/service_pb-B5w9rjPY.mjs.map +0 -1
  299. package/dist/types-BwzB2okW.mjs +0 -199
  300. package/dist/types-BwzB2okW.mjs.map +0 -1
  301. package/dist/types-KlawuVKa.mjs +0 -4
@@ -1,7 +1,207 @@
1
- import { n as mapAllowedValues, t as parseInternal } from "./field-runtime-9bfXBAOK.mjs";
2
1
  import { t as brandValue } from "./brand-Eo4pLXPJ.mjs";
3
2
  import { cloneDeep } from "es-toolkit";
4
3
 
4
+ //#region src/configure/types/field.ts
5
+ /**
6
+ * Normalize allowed values into EnumValue objects with descriptions.
7
+ * @param values - Allowed values as strings or EnumValue objects
8
+ * @returns Normalized allowed values
9
+ */
10
+ function mapAllowedValues(values) {
11
+ return values.map((value) => {
12
+ if (typeof value === "string") return {
13
+ value,
14
+ description: ""
15
+ };
16
+ return {
17
+ ...value,
18
+ description: value.description ?? ""
19
+ };
20
+ });
21
+ }
22
+
23
+ //#endregion
24
+ //#region src/configure/types/field-runtime.ts
25
+ const regex = {
26
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
27
+ date: /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,
28
+ time: /^(?<hour>\d{2}):(?<minute>\d{2})$/,
29
+ datetime: /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(\.(?<millisec>\d{3}))?Z$/,
30
+ decimal: /^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/
31
+ };
32
+ function validateBaseValue(args) {
33
+ const { field, value, pathArray, issues } = args;
34
+ const path = pathArray.length > 0 ? pathArray : void 0;
35
+ const initialIssueCount = issues.length;
36
+ switch (field.type) {
37
+ case "string":
38
+ if (typeof value !== "string") issues.push({
39
+ message: `Expected a string: received ${String(value)}`,
40
+ path
41
+ });
42
+ break;
43
+ case "integer":
44
+ if (typeof value !== "number" || !Number.isInteger(value)) issues.push({
45
+ message: `Expected an integer: received ${String(value)}`,
46
+ path
47
+ });
48
+ break;
49
+ case "float":
50
+ if (typeof value !== "number" || !Number.isFinite(value)) issues.push({
51
+ message: `Expected a number: received ${String(value)}`,
52
+ path
53
+ });
54
+ break;
55
+ case "boolean":
56
+ if (typeof value !== "boolean") issues.push({
57
+ message: `Expected a boolean: received ${String(value)}`,
58
+ path
59
+ });
60
+ break;
61
+ case "uuid":
62
+ if (typeof value !== "string" || !regex.uuid.test(value)) issues.push({
63
+ message: `Expected a valid UUID: received ${String(value)}`,
64
+ path
65
+ });
66
+ break;
67
+ case "date":
68
+ if (typeof value !== "string" || !regex.date.test(value)) issues.push({
69
+ message: `Expected to match "yyyy-MM-dd" format: received ${String(value)}`,
70
+ path
71
+ });
72
+ break;
73
+ case "datetime":
74
+ if (typeof value !== "string" || !regex.datetime.test(value)) issues.push({
75
+ message: `Expected to match ISO format: received ${String(value)}`,
76
+ path
77
+ });
78
+ break;
79
+ case "time":
80
+ if (typeof value !== "string" || !regex.time.test(value)) issues.push({
81
+ message: `Expected to match "HH:mm" format: received ${String(value)}`,
82
+ path
83
+ });
84
+ break;
85
+ case "decimal":
86
+ if (typeof value !== "string" || !regex.decimal.test(value)) issues.push({
87
+ message: `Expected a decimal string: received ${String(value)}`,
88
+ path
89
+ });
90
+ break;
91
+ case "enum":
92
+ if (field._metadata.allowedValues) {
93
+ const allowedValues = field._metadata.allowedValues.map((v) => v.value);
94
+ if (typeof value !== "string" || !allowedValues.includes(value)) issues.push({
95
+ message: `Must be one of [${allowedValues.join(", ")}]: received ${String(value)}`,
96
+ path
97
+ });
98
+ }
99
+ break;
100
+ case "nested": {
101
+ if (typeof value !== "object" || value === null || Array.isArray(value) || value instanceof Date) {
102
+ issues.push({
103
+ message: `Expected an object: received ${String(value)}`,
104
+ path
105
+ });
106
+ return false;
107
+ }
108
+ let nestedBaseValid = true;
109
+ for (const [fieldName, nestedField] of Object.entries(field.fields)) {
110
+ const fieldValue = value[fieldName];
111
+ if (!validateBaseField({
112
+ ...args,
113
+ field: nestedField,
114
+ value: fieldValue,
115
+ pathArray: pathArray.concat(fieldName)
116
+ })) nestedBaseValid = false;
117
+ }
118
+ return nestedBaseValid;
119
+ }
120
+ }
121
+ return issues.length === initialIssueCount;
122
+ }
123
+ function validateCustomValue(args, validateFns) {
124
+ const { value, data, user, pathArray, issues } = args;
125
+ const path = pathArray.length > 0 ? pathArray : void 0;
126
+ for (const validateInput of validateFns) {
127
+ const { fn, message } = typeof validateInput === "function" ? {
128
+ fn: validateInput,
129
+ message: "Validation failed"
130
+ } : {
131
+ fn: validateInput[0],
132
+ message: validateInput[1]
133
+ };
134
+ if (!fn({
135
+ value,
136
+ data,
137
+ user
138
+ })) issues.push({
139
+ message,
140
+ path
141
+ });
142
+ }
143
+ }
144
+ function validateBaseField(args) {
145
+ const { field, value, pathArray, issues } = args;
146
+ const path = pathArray.length > 0 ? pathArray : void 0;
147
+ const isNullOrUndefined = value === null || value === void 0;
148
+ if (field._metadata.required && isNullOrUndefined) {
149
+ issues.push({
150
+ message: "Required field is missing",
151
+ path
152
+ });
153
+ return false;
154
+ }
155
+ if (!field._metadata.required && isNullOrUndefined) return true;
156
+ let baseValid = true;
157
+ if (field._metadata.array) {
158
+ if (!Array.isArray(value)) {
159
+ issues.push({
160
+ message: "Expected an array",
161
+ path
162
+ });
163
+ return false;
164
+ }
165
+ for (let i = 0; i < value.length; i++) if (!validateBaseValue({
166
+ ...args,
167
+ value: value[i],
168
+ pathArray: pathArray.concat(`[${i}]`)
169
+ })) baseValid = false;
170
+ } else baseValid = validateBaseValue(args);
171
+ return baseValid;
172
+ }
173
+ function validateCustomField(args) {
174
+ const { field, value, pathArray } = args;
175
+ if (value === null || value === void 0) return;
176
+ if (field.type === "nested") {
177
+ const records = field._metadata.array ? value : [value];
178
+ for (let i = 0; i < records.length; i++) {
179
+ const record = records[i];
180
+ const recordPath = field._metadata.array ? pathArray.concat(`[${i}]`) : pathArray;
181
+ for (const [fieldName, nestedField] of Object.entries(field.fields)) validateCustomField({
182
+ ...args,
183
+ field: nestedField,
184
+ value: record[fieldName],
185
+ pathArray: recordPath.concat(fieldName)
186
+ });
187
+ }
188
+ }
189
+ const validateFns = field._metadata.validate;
190
+ if (validateFns?.length) validateCustomValue(args, validateFns);
191
+ }
192
+ function parseInternal(args) {
193
+ const { value } = args;
194
+ const issues = [];
195
+ const validationArgs = {
196
+ ...args,
197
+ issues
198
+ };
199
+ if (validateBaseField(validationArgs)) validateCustomField(validationArgs);
200
+ if (issues.length > 0) return { issues };
201
+ return { value: value ?? null };
202
+ }
203
+
204
+ //#endregion
5
205
  //#region src/configure/services/tailordb/schema.ts
6
206
  function isRelationSelfConfig(config) {
7
207
  return config.toward.type === "self";
@@ -94,6 +294,7 @@ function createTailorDBFieldRuntime(type, options, fields, values) {
94
294
  return cloneWith({ serial: config });
95
295
  },
96
296
  clone(cloneOptions) {
297
+ if (this._metadata.validate?.length && cloneOptions?.array !== void 0 && cloneOptions.array !== (this._metadata.array === true)) throw new Error("Cannot change the array option on a field with custom validation");
97
298
  let clonedFields = fields;
98
299
  if (fields) {
99
300
  const cloned = {};
@@ -435,5 +636,5 @@ timestamps: () => ({
435
636
  };
436
637
 
437
638
  //#endregion
438
- export { db as t };
439
- //# sourceMappingURL=schema-DrVyN-LP.mjs.map
639
+ export { parseInternal as n, mapAllowedValues as r, db as t };
640
+ //# sourceMappingURL=schema-U6DxoZ8D.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-U6DxoZ8D.mjs","names":["parseInternal","parseFieldInternal"],"sources":["../src/configure/types/field.ts","../src/configure/types/field-runtime.ts","../src/configure/services/tailordb/schema.ts"],"sourcesContent":["import type { EnumValue } from \"#/configure/types/field.types\";\n\nexport type AllowedValues = readonly [string | EnumValue, ...(string | EnumValue)[]];\n\n/**\n * Normalize allowed values into EnumValue objects with descriptions.\n * @param values - Allowed values as strings or EnumValue objects\n * @returns Normalized allowed values\n */\nexport function mapAllowedValues(values: AllowedValues): EnumValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> = V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n","import type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { TailorUser } from \"#/runtime/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(\\.(?<millisec>\\d{3}))?Z$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\nexport type FieldParseArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n};\n\nexport type FieldParseInternalArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\nexport type FieldRuntime<T extends TailorFieldType = TailorFieldType> = {\n readonly type: T;\n readonly fields: Record<string, FieldRuntime>;\n _metadata: FieldMetadata;\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<unknown>;\n};\n\ntype FieldParseRuntimeArgs<T extends TailorFieldType> = FieldParseInternalArgs & {\n field: FieldRuntime<T>;\n};\n\ntype FieldValidationArgs<T extends TailorFieldType> = FieldParseRuntimeArgs<T> & {\n issues: StandardSchemaV1.Issue[];\n};\n\nfunction validateBaseValue<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n const initialIssueCount = issues.length;\n\n switch (field.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path,\n });\n }\n }\n break;\n\n case \"nested\": {\n // Runtime input may not match the declared field type.\n // oxlint-disable typescript/no-unnecessary-condition\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n // oxlint-enable typescript/no-unnecessary-condition\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path,\n });\n return false;\n }\n\n let nestedBaseValid = true;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = (value as Record<string, unknown>)[fieldName];\n if (\n !validateBaseField({\n ...args,\n field: nestedField,\n value: fieldValue,\n pathArray: pathArray.concat(fieldName),\n })\n ) {\n nestedBaseValid = false;\n }\n }\n return nestedBaseValid;\n }\n }\n\n return issues.length === initialIssueCount;\n}\n\nfunction validateCustomValue<T extends TailorFieldType>(\n args: FieldValidationArgs<T>,\n validateFns: NonNullable<FieldMetadata[\"validate\"]>,\n): void {\n const { value, data, user, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path,\n });\n }\n }\n}\n\nfunction validateBaseField<T extends TailorFieldType>(args: FieldValidationArgs<T>): boolean {\n const { field, value, pathArray, issues } = args;\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path,\n });\n return false;\n }\n\n if (!field._metadata.required && isNullOrUndefined) {\n return true;\n }\n\n let baseValid = true;\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path,\n });\n return false;\n }\n\n for (let i = 0; i < value.length; i++) {\n if (\n !validateBaseValue({\n ...args,\n value: value[i],\n pathArray: pathArray.concat(`[${i}]`),\n })\n ) {\n baseValid = false;\n }\n }\n } else {\n baseValid = validateBaseValue(args);\n }\n\n return baseValid;\n}\n\nfunction validateCustomField<T extends TailorFieldType>(args: FieldValidationArgs<T>): void {\n const { field, value, pathArray } = args;\n if (value === null || value === undefined) {\n return;\n }\n\n if (field.type === \"nested\") {\n const records = field._metadata.array\n ? (value as Record<string, unknown>[])\n : [value as Record<string, unknown>];\n\n for (let i = 0; i < records.length; i++) {\n const record = records[i] as Record<string, unknown>;\n const recordPath = field._metadata.array ? pathArray.concat(`[${i}]`) : pathArray;\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n validateCustomField({\n ...args,\n field: nestedField,\n value: record[fieldName],\n pathArray: recordPath.concat(fieldName),\n });\n }\n }\n }\n\n const validateFns = field._metadata.validate;\n if (validateFns?.length) {\n validateCustomValue(args, validateFns);\n }\n}\n\nexport function parseInternal<T extends TailorFieldType, Output>(\n args: FieldParseRuntimeArgs<T>,\n): StandardSchemaV1.Result<Output> {\n const { value } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const validationArgs = { ...args, issues };\n const baseValid = validateBaseField(validationArgs);\n if (baseValid) {\n validateCustomField(validationArgs);\n }\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value: (value ?? null) as Output };\n}\n","import { cloneDeep } from \"es-toolkit\";\nimport {\n type AllowedValues,\n type AllowedValuesOutput,\n mapAllowedValues,\n} from \"#/configure/types/field\";\nimport {\n parseInternal as parseFieldInternal,\n type FieldParseArgs,\n type FieldParseInternalArgs,\n} from \"#/configure/types/field-runtime\";\nimport { brandValue } from \"#/utils/brand\";\nimport type {\n TailorDBField as TailorDBFieldBase,\n TailorDBType as TailorDBTypeBase,\n DBFieldMetadata,\n DefinedDBFieldMetadata,\n SerialConfig,\n IndexDef,\n TailorDBTypeMetadata,\n RawRelationConfig,\n RelationType,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n FieldOptions,\n FieldOutput,\n TailorFieldType,\n TailorToTs,\n FieldValidateInput,\n ValidateConfig,\n Validators,\n} from \"#/configure/types/field.types\";\nimport type { PluginAttachment, PluginConfigs } from \"#/plugin/types\";\nimport type { InferredAttributeMap } from \"#/runtime/types\";\nimport type { output, InferFieldsOutput, TypeLevelError } from \"#/types/helpers\";\nimport type { RawPermissions } from \"#/types/tailordb.generated\";\nimport type { TailorTypeGqlPermission, TailorTypePermission } from \"./permission\";\nimport type { Hook, Hooks, ExcludeNestedDBFields, TypeFeatures } from \"./types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Erased DB fields stay assignable across builder method-state changes.\n// oxlint-disable-next-line no-explicit-any\ntype AnyBuilderMethod = any;\n\nexport type TailorAnyDBField = Omit<\n TailorDBFieldBase<AnyBuilderMethod, AnyBuilderMethod>,\n \"fields\"\n> & {\n readonly fields: Record<string, AnyBuilderMethod>;\n _metadata: DBFieldMetadata;\n parse: AnyBuilderMethod;\n _parseInternal: AnyBuilderMethod;\n readonly typeName: TypeLevelError<string>;\n description: AnyBuilderMethod;\n relation: AnyBuilderMethod;\n index: AnyBuilderMethod;\n unique: AnyBuilderMethod;\n vector: AnyBuilderMethod;\n hooks: AnyBuilderMethod;\n validate: AnyBuilderMethod;\n serial: AnyBuilderMethod;\n clone: AnyBuilderMethod;\n};\n\n// Helper alias\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyDBType = TailorDBType<any, any, any>;\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\ntype DBFieldTypeNameMethod<Defined extends DefinedDBFieldMetadata> =\n IsAny<Defined> extends true\n ? TypeLevelError<string>\n : TypeLevelError<\"typeName cannot be used on TailorDB fields\">;\n\ntype WithDBFieldDescription<Defined> = Defined & { description: true };\ntype WithDBFieldRelation<Defined, S extends RelationType | RelationSelfConfig> = S extends\n | \"oneToOne\"\n | \"1-1\"\n ? Defined & { unique: true; index: true; relation: true }\n : S extends { type: \"oneToOne\" | \"1-1\" }\n ? Defined & { unique: true; index: true; relation: true }\n : Defined & { index: true; relation: true };\ntype WithDBFieldIndex<Defined> = Defined & { index: true };\ntype WithDBFieldUnique<Defined> = Defined & { unique: true; index: true };\ntype WithDBFieldVector<Defined> = Defined & { vector: true };\ntype WithDBFieldHooks<Defined, H> = Defined & {\n hooks: {\n create: H extends { create: unknown } ? true : false;\n update: H extends { update: unknown } ? true : false;\n };\n serial: false;\n};\ntype WithDBFieldValidate<Defined> = Defined & { validate: true };\ntype WithDBFieldSerial<Defined> = Defined & {\n serial: true;\n hooks: { create: false; update: false };\n};\ntype WithDBFieldCloneOptions<Defined extends DefinedDBFieldMetadata, NewOpt extends FieldOptions> =\n IsAny<Defined> extends true\n ? Defined\n : Omit<Defined, \"array\"> & {\n array: NewOpt extends { array: true } ? true : Defined[\"array\"];\n };\ntype DBFieldCloneOptions<Defined extends DefinedDBFieldMetadata> = Omit<FieldOptions, \"array\"> & {\n array?: Defined extends { validate: unknown } ? Defined[\"array\"] : boolean;\n};\ntype InvalidValidatedArrayCloneKeys<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = Opt extends { array: infer ArrayOption }\n ? {\n [P in K]: Fields[P] extends TailorDBField<infer Defined, infer _Output>\n ? Defined extends { validate: unknown }\n ? ArrayOption extends Defined[\"array\"]\n ? never\n : P\n : never\n : never;\n }[K]\n : never;\ntype DBFieldsCloneOptionsGuard<\n Fields extends Record<string, TailorAnyDBField>,\n K extends keyof Fields,\n Opt extends FieldOptions,\n> = [InvalidValidatedArrayCloneKeys<Fields, K, Opt>] extends [never]\n ? unknown\n : TypeLevelError<\"array cannot be changed on fields with custom validation\">;\ntype DefinedDBTypeMetadata = {\n hooks?: true;\n validate?: true;\n features?: true;\n indexes?: true;\n files?: true;\n permission?: true;\n gqlPermission?: true;\n description?: true;\n};\ntype WithDBTypeMetadata<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n> = Defined & Record<Key, true>;\ntype DBTypeDuplicateInputGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input,\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? TypeLevelError<Message>\n : Input;\ntype DBTypeDuplicateRestGuard<\n Defined extends DefinedDBTypeMetadata,\n Key extends keyof DefinedDBTypeMetadata,\n Input extends unknown[],\n Message extends string,\n> =\n IsAny<Defined> extends true\n ? Input\n : Defined extends Record<Key, unknown>\n ? [TypeLevelError<Message>, ...TypeLevelError<Message>[]]\n : Input;\ntype FileKeyConflictError<\n Fields extends Record<string, TailorAnyDBField>,\n User extends object,\n> = Partial<\n Record<\n keyof output<TailorDBType<Fields, User>> & string,\n TypeLevelError<\"file keys cannot use existing field names\">\n >\n>;\ntype DBFieldDescriptionFn<Defined extends DefinedDBFieldMetadata, Output> = (\n description: string,\n) => TailorDBField<WithDBFieldDescription<Defined>, Output>;\ntype DBFieldRelationFn<Defined extends DefinedDBFieldMetadata, Output> = {\n <S extends RelationType, T extends TailorAnyDBType>(\n config: RelationConfig<S, T>,\n ): TailorDBField<WithDBFieldRelation<Defined, S>, Output>;\n <S extends RelationSelfConfig>(config: S): TailorDBField<WithDBFieldRelation<Defined, S>, Output>;\n};\ntype DBFieldIndexFn<Defined extends DefinedDBFieldMetadata, Output> = () => TailorDBField<\n WithDBFieldIndex<Defined>,\n Output\n>;\ntype DBFieldUniqueFn<Defined extends DefinedDBFieldMetadata, Output> = () => TailorDBField<\n WithDBFieldUnique<Defined>,\n Output\n>;\ntype DBFieldVectorFn<Defined extends DefinedDBFieldMetadata, Output> = () => TailorDBField<\n WithDBFieldVector<Defined>,\n Output\n>;\ntype DBFieldHooksFn<Defined extends DefinedDBFieldMetadata, Output> = <\n const H extends Hook<unknown, Output>,\n>(\n hooks: H,\n) => TailorDBField<WithDBFieldHooks<Defined, H>, Output>;\ntype DBFieldValidateFn<Defined extends DefinedDBFieldMetadata, Output> = (\n ...validate: FieldValidateInput<Output>[]\n) => TailorDBField<WithDBFieldValidate<Defined>, Output>;\ntype DBFieldSerialFn<Defined extends DefinedDBFieldMetadata, Output> = (\n config: SerialConfig<Defined[\"type\"] & (\"integer\" | \"string\")>,\n) => TailorDBField<WithDBFieldSerial<Defined>, Output>;\ntype DBFieldDescriptionMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldDescriptionFn<Defined, Output>\n : Defined extends { description: unknown }\n ? TypeLevelError<\".description() has already been set\">\n : DBFieldDescriptionFn<Defined, Output>;\ntype DBFieldRelationMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldRelationFn<Defined, Output>\n : Defined extends { relation: unknown }\n ? TypeLevelError<\".relation() has already been set\">\n : DBFieldRelationFn<Defined, Output>;\ntype DBFieldArrayCheck<A extends boolean, Ok, Msg extends string> = A extends true\n ? TypeLevelError<Msg>\n : Ok;\ntype DBFieldIndexMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldIndexFn<Defined, Output>\n : Defined extends { index: unknown }\n ? TypeLevelError<\".index() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldIndexFn<Defined, Output>,\n \"index cannot be set on array fields\"\n >;\ntype DBFieldUniqueMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldUniqueFn<Defined, Output>\n : Defined extends { unique: unknown }\n ? TypeLevelError<\".unique() has already been set\">\n : DBFieldArrayCheck<\n Defined[\"array\"],\n DBFieldUniqueFn<Defined, Output>,\n \"unique cannot be set on array fields\"\n >;\ntype DBFieldVectorMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldVectorFn<Defined, Output>\n : Defined extends { vector: unknown }\n ? TypeLevelError<\".vector() has already been set\">\n : Defined extends { type: \"string\"; array: false }\n ? DBFieldVectorFn<Defined, Output>\n : TypeLevelError<\"vector can only be set on non-array string fields\">;\ntype DBFieldHooksMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldHooksFn<Defined, Output>\n : Defined extends {\n serial: true;\n hooks: { create: false; update: false };\n }\n ? TypeLevelError<\"hooks cannot be set after serial\">\n : Defined extends {\n hooks: unknown;\n }\n ? TypeLevelError<\".hooks() has already been set\">\n : Defined extends { type: \"nested\" }\n ? TypeLevelError<\"hooks cannot be set on nested type fields\">\n : DBFieldHooksFn<Defined, Output>;\ntype DBFieldValidateMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldValidateFn<Defined, Output>\n : Defined extends { validate: unknown }\n ? TypeLevelError<\".validate() has already been set\">\n : DBFieldValidateFn<Defined, Output>;\ntype DBFieldSerialMethod<Defined extends DefinedDBFieldMetadata, Output> =\n IsAny<Defined> extends true\n ? DBFieldSerialFn<Defined, Output>\n : Defined extends { serial: true }\n ? TypeLevelError<\".serial() has already been set\">\n : Defined extends { serial: false }\n ? TypeLevelError<\"serial cannot be set after hooks\">\n : IsAny<Output> extends true\n ? Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : null extends Output\n ? TypeLevelError<\"serial can only be set on non-array integer or string fields\">\n : Defined extends { type: \"integer\" | \"string\"; array: false }\n ? DBFieldSerialFn<Defined, Output>\n : TypeLevelError<\"serial can only be set on non-array integer or string fields\">;\n/**\n * Full TailorDBField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBField<\n Defined extends DefinedDBFieldMetadata = DefinedDBFieldMetadata,\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n> extends Omit<TailorDBFieldBase<Defined, Output>, \"fields\"> {\n readonly fields: Record<string, TailorAnyDBField>;\n _metadata: DBFieldMetadata;\n\n /**\n * Parse and validate a value against this field's validation rules\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @private\n */\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * typeName is not available on TailorDB fields.\n * Use typeName on pipeline fields (t.enum / t.object) instead.\n */\n typeName: DBFieldTypeNameMethod<Defined>;\n\n /**\n * Set a description for the field\n */\n description: DBFieldDescriptionMethod<Defined, Output>;\n\n /**\n * Define a relation to another type.\n */\n relation: DBFieldRelationMethod<Defined, Output>;\n\n /**\n * Add an index to the field\n */\n index: DBFieldIndexMethod<Defined, Output>;\n\n /**\n * Make the field unique (also adds an index)\n */\n unique: DBFieldUniqueMethod<Defined, Output>;\n\n /**\n * Enable vector search on the field (string type only)\n */\n vector: DBFieldVectorMethod<Defined, Output>;\n\n /**\n * Add hooks for create/update operations on this field.\n */\n hooks: DBFieldHooksMethod<Defined, Output>;\n\n /**\n * Add validation functions to the field.\n *\n * Validators receive `{ value, data, user }` and run after hooks and\n * built-in type validation; they are skipped when built-in validation\n * fails. For array fields, `value` is the complete array.\n */\n validate: DBFieldValidateMethod<Defined, Output>;\n\n /**\n * Configure serial/auto-increment behavior\n */\n serial: DBFieldSerialMethod<Defined, Output>;\n\n /**\n * Clone the field with optional overrides for field options.\n * The `array` option cannot change on fields with custom validation.\n */\n clone<const NewOpt extends DBFieldCloneOptions<Defined>>(\n options?: NewOpt,\n ): TailorDBField<\n WithDBFieldCloneOptions<Defined, NewOpt>,\n FieldOutput<TailorToTs[Defined[\"type\"]], NewOpt>\n >;\n}\n\n/**\n * Full TailorDBType interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBType<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> extends TailorDBTypeBase<Fields, User> {\n _description?: string;\n\n hooks(\n hooks: DBTypeDuplicateInputGuard<\n Defined,\n \"hooks\",\n Hooks<Fields>,\n \".hooks() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"hooks\">>;\n validate(\n validators: DBTypeDuplicateInputGuard<\n Defined,\n \"validate\",\n Validators<Fields>,\n \".validate() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"validate\">>;\n features(\n features: DBTypeDuplicateInputGuard<\n Defined,\n \"features\",\n Omit<TypeFeatures, \"pluralForm\">,\n \".features() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"features\">>;\n indexes(\n ...indexes: DBTypeDuplicateRestGuard<\n Defined,\n \"indexes\",\n IndexDef<TailorDBType<Fields, User, Defined>>[],\n \".indexes() has already been set\"\n >\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"indexes\">>;\n files<const F extends string>(\n files: DBTypeDuplicateInputGuard<\n Defined,\n \"files\",\n Record<F, string> & FileKeyConflictError<Fields, User>,\n \".files() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"files\">>;\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, Defined>>>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"permission\",\n P,\n \".permission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"permission\">>;\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(\n permission: DBTypeDuplicateInputGuard<\n Defined,\n \"gqlPermission\",\n P,\n \".gqlPermission() has already been set\"\n >,\n ): TailorDBType<Fields, U, WithDBTypeMetadata<Defined, \"gqlPermission\">>;\n description(\n description: DBTypeDuplicateInputGuard<\n Defined,\n \"description\",\n string,\n \".description() has already been set\"\n >,\n ): TailorDBType<Fields, User, WithDBTypeMetadata<Defined, \"description\">>;\n pickFields<K extends keyof Fields>(keys: K[]): Pick<Fields, K>;\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(\n keys: K[],\n options: Opt & DBFieldsCloneOptionsGuard<Fields, K, Opt>,\n ): {\n [P in K]: Fields[P] extends TailorDBField<infer D, infer _O>\n ? TailorDBField<WithDBFieldCloneOptions<D, Opt>, FieldOutput<TailorToTs[D[\"type\"]], Opt>>\n : never;\n };\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K>;\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, Defined>;\n}\n\nexport type TailorDBInstance<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n // oxlint-disable-next-line no-explicit-any\n Defined extends DefinedDBTypeMetadata = any,\n> = TailorDBType<Fields, User, Defined>;\n\ninterface RelationConfig<S extends RelationType, T extends TailorDBType> {\n type: S;\n toward: {\n type: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n };\n backward?: string;\n}\n\n// Special config variant for self-referencing relations\ntype RelationSelfConfig = {\n type: RelationType;\n toward: {\n type: \"self\";\n as?: string;\n key?: string;\n };\n backward?: string;\n};\n\nfunction isRelationSelfConfig(\n config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig,\n): config is RelationSelfConfig {\n return config.toward.type === \"self\";\n}\n\ntype DBFieldDefined<T extends TailorFieldType, Opt extends FieldOptions> = {\n type: T;\n array: Opt extends { array: true } ? true : false;\n};\ntype DBFieldOutput<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = FieldOutput<OutputBase, Opt>;\ntype TailorDBFieldInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBField<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntimeInstance<\n T extends TailorFieldType,\n Opt extends FieldOptions,\n OutputBase = TailorToTs[T],\n> = TailorDBFieldRuntime<DBFieldDefined<T, Opt>, DBFieldOutput<T, Opt, OutputBase>>;\ntype TailorDBFieldRuntime<Defined extends DefinedDBFieldMetadata, Output> = Omit<\n TailorDBFieldBase<Defined, Output>,\n \"fields\"\n> & {\n readonly fields: Record<string, TailorAnyDBField>;\n _metadata: DBFieldMetadata;\n description(description: string): object;\n typeName(typeName: string): object;\n validate(...validate: FieldValidateInput<Output>[]): object;\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig): object;\n index(): object;\n unique(): object;\n vector(): object;\n hooks(hooks: Hook<unknown, Output>): object;\n serial(config: SerialConfig): object;\n clone(options?: FieldOptions): TailorDBFieldRuntime<DefinedDBFieldMetadata, AnyBuilderMethod>;\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;\n _setRawRelation(relation: RawRelationConfig): void;\n};\n\n/**\n * Creates a new TailorDBField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorDBField\n */\nfunction createTailorDBField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldInstance<T, TOptions, OutputBase>;\nfunction createTailorDBField<const T extends TailorFieldType, const TOptions extends FieldOptions>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): object {\n return createTailorDBFieldRuntime(type, options, fields, values);\n}\n\nfunction createTailorDBFieldRuntime<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBFieldRuntimeInstance<T, TOptions, OutputBase> {\n type FieldValue = DBFieldOutput<T, TOptions, OutputBase>;\n type FieldType = TailorDBFieldRuntimeInstance<T, TOptions, OutputBase>;\n\n const _metadata: DBFieldMetadata = { required: true };\n let _rawRelation: RawRelationConfig | undefined;\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n function parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<FieldValue> {\n return parseFieldInternal<T, FieldValue>({\n ...args,\n field,\n });\n }\n\n function cloneWith(metadataUpdates: Partial<DBFieldMetadata>) {\n const cloned = field.clone();\n Object.assign(cloned._metadata, metadataUpdates);\n return cloned;\n }\n\n const field: FieldType = {\n type,\n fields: fields ?? {},\n _defined: undefined as unknown as DBFieldDefined<T, TOptions>,\n _output: undefined as FieldValue,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n get rawRelation(): Readonly<RawRelationConfig> | undefined {\n return _rawRelation ? { ..._rawRelation, toward: { ..._rawRelation.toward } } : undefined;\n },\n\n description(description: string) {\n return cloneWith({ description });\n },\n\n typeName(typeName: string) {\n return cloneWith({ typeName });\n },\n\n validate(...validateInputs: FieldValidateInput<FieldValue>[]) {\n return cloneWith({ validate: validateInputs });\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldValue> {\n return parseInternal({\n value: args.value,\n data: args.data,\n user: args.user,\n pathArray: [],\n });\n },\n\n _parseInternal: parseInternal,\n\n // TailorDBField specific methods\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig) {\n const cloned = field.clone();\n const targetType = isRelationSelfConfig(config) ? \"self\" : config.toward.type.name;\n cloned._setRawRelation({\n type: config.type,\n toward: {\n type: targetType,\n as: config.toward.as,\n key: config.toward.key,\n },\n backward: config.backward,\n });\n return cloned;\n },\n\n index() {\n return cloneWith({ index: true });\n },\n\n unique() {\n return cloneWith({ unique: true, index: true });\n },\n\n vector() {\n return cloneWith({ vector: true });\n },\n\n hooks(hooks: Hook<unknown, FieldValue>) {\n return cloneWith({ hooks });\n },\n\n serial(config: SerialConfig) {\n return cloneWith({ serial: config });\n },\n\n clone(cloneOptions?: FieldOptions) {\n if (\n this._metadata.validate?.length &&\n cloneOptions?.array !== undefined &&\n cloneOptions.array !== (this._metadata.array === true)\n ) {\n throw new Error(\"Cannot change the array option on a field with custom validation\");\n }\n\n // Deep clone nested object fields if present\n let clonedFields = fields;\n if (fields) {\n const cloned: Record<string, TailorAnyDBField> = {};\n for (const [key, field] of Object.entries(fields)) {\n cloned[key] = field.clone();\n }\n clonedFields = cloned;\n }\n\n // Create a new field with cloned configuration\n const clonedField = createTailorDBFieldRuntime(type, options, clonedFields, values);\n\n // Deep copy metadata using cloneDeep (preserves function references)\n Object.assign(clonedField._metadata, cloneDeep(this._metadata));\n\n // Apply new options if provided\n if (cloneOptions) {\n if (cloneOptions.optional !== undefined) {\n clonedField._metadata.required = !cloneOptions.optional;\n }\n if (cloneOptions.array !== undefined) {\n clonedField._metadata.array = cloneOptions.array;\n }\n }\n\n // Copy raw relation if exists\n if (_rawRelation) {\n clonedField._setRawRelation(cloneDeep(_rawRelation));\n }\n\n return clonedField;\n },\n\n _setRawRelation(relation: RawRelationConfig) {\n _rawRelation = relation;\n },\n };\n\n return field;\n}\n\nconst createField = createTailorDBField;\n\n/**\n * Create a UUID field.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example db.uuid()\n * @example db.uuid({ optional: true })\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\n/**\n * Create a string field.\n * @param options - Field configuration options\n * @returns A string field\n * @example db.string()\n * @example db.string({ optional: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\n/**\n * Create a boolean field.\n * Note: The method name is `bool` but creates a `boolean` type field.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example db.bool()\n * @example db.bool({ optional: true })\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\n/**\n * Create an integer field.\n * @param options - Field configuration options\n * @returns An integer field\n * @example db.int()\n * @example db.int({ optional: true })\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\n/**\n * Create a float (decimal number) field.\n * @param options - Field configuration options\n * @returns A float field\n * @example db.float()\n * @example db.float({ optional: true })\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\ninterface DecimalFieldOptions extends FieldOptions {\n scale?: number;\n}\n\n/**\n * Create a decimal field (stored as string for precision).\n * @param options - Field configuration options including optional scale (0-12)\n * @returns A decimal field\n * @example db.decimal()\n * @example db.decimal({ scale: 2 })\n * @example db.decimal({ scale: 2, optional: true })\n */\nfunction decimal<const Opt extends DecimalFieldOptions>(options?: Opt) {\n if (options?.scale !== undefined) {\n if (!Number.isInteger(options.scale) || options.scale < 0 || options.scale > 12) {\n throw new Error(\"scale must be an integer between 0 and 12\");\n }\n }\n const field = createField(\"decimal\", options);\n if (options?.scale !== undefined) {\n field._metadata.scale = options.scale;\n }\n return field;\n}\n\n/**\n * Create a date field (date only, no time component).\n * Format: \"yyyy-MM-dd\"\n * @param options - Field configuration options\n * @returns A date field\n * @example db.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\n/**\n * Create a datetime field (date and time).\n * Format: ISO 8601 \"yyyy-MM-ddTHH:mm:ssZ\"\n * @param options - Field configuration options\n * @returns A datetime field\n * @example db.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\n/**\n * Create a time field (time only, no date component).\n * Format: \"HH:mm\"\n * @param options - Field configuration options\n * @returns A time field\n * @example db.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\n/**\n * Create an enum field with a fixed set of allowed string values.\n * @param values - Array of allowed string values, or array of `{ value, description }` objects\n * @param options - Field configuration options\n * @returns An enum field\n * @example db.enum([\"active\", \"inactive\", \"suspended\"])\n * @example db.enum([\"small\", \"medium\", \"large\"], { optional: true })\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorDBField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field with sub-fields.\n * @param fields - Record of nested field definitions\n * @param options - Field configuration options\n * @returns A nested object field\n * @example db.object({ street: db.string(), city: db.string(), zip: db.string() })\n * @example db.object({ name: db.string() }, { optional: true })\n */\nfunction object<\n const F extends Record<string, TailorAnyDBField> & ExcludeNestedDBFields<F>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n return createField(\"nested\", options, fields) as unknown as TailorDBField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n}\n\n/**\n * Creates a new TailorDBType instance.\n * @param name - Type name\n * @param fields - Field definitions\n * @param options - Type options\n * @param options.pluralForm - Optional plural form\n * @param options.description - Optional description\n * @returns A new TailorDBType\n */\nfunction createTailorDBType<\n // oxlint-disable-next-line no-explicit-any\n const Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n>(\n name: string,\n fields: Fields,\n options: { pluralForm?: string; description?: string },\n): TailorDBType<Fields, User, DefinedDBTypeMetadata> {\n let _description = options.description;\n let _settings: TypeFeatures = {};\n let _indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[] = [];\n const _permissions: RawPermissions = {};\n let _files: Record<string, string> = {};\n const _plugins: PluginAttachment[] = [];\n const _definedMethods = new Set<keyof DefinedDBTypeMetadata>();\n if (options.description !== undefined) {\n _definedMethods.add(\"description\");\n }\n\n function runMethodOnce<T>(method: keyof DefinedDBTypeMetadata, action: () => T): T {\n if (_definedMethods.has(method)) {\n throw new Error(`.${method}() has already been set`);\n }\n const result = action();\n _definedMethods.add(method);\n return result;\n }\n type TypeAfter<Key extends keyof DefinedDBTypeMetadata> = TailorDBType<\n Fields,\n User,\n WithDBTypeMetadata<DefinedDBTypeMetadata, Key>\n >;\n type TypeAfterUser<\n NextUser extends object,\n Key extends keyof DefinedDBTypeMetadata,\n > = TailorDBType<Fields, NextUser, WithDBTypeMetadata<DefinedDBTypeMetadata, Key>>;\n\n if (options.pluralForm) {\n if (name === options.pluralForm) {\n throw new Error(`The name and the plural form must be different. name=${name}`);\n }\n _settings.pluralForm = options.pluralForm;\n }\n\n const dbType: TailorDBType<Fields, User, DefinedDBTypeMetadata> = {\n name,\n fields: { ...fields },\n _output: null as unknown as InferFieldsOutput<Fields>,\n _description,\n\n get metadata(): TailorDBTypeMetadata {\n // Convert indexes to the format expected by the manifest\n const indexes: Record<string, { fields: string[]; unique?: boolean }> = {};\n if (_indexes.length > 0) {\n _indexes.forEach((index) => {\n const fieldNames = index.fields.map((field) => String(field));\n const key = index.name || `idx_${fieldNames.join(\"_\")}`;\n indexes[key] = {\n fields: fieldNames,\n unique: index.unique,\n };\n });\n }\n\n return {\n name: this.name,\n description: _description,\n settings: _settings,\n permissions: _permissions,\n files: _files,\n ...(Object.keys(indexes).length > 0 && { indexes }),\n };\n },\n\n hooks(hooks: Hooks<Fields>): TypeAfter<\"hooks\"> {\n return runMethodOnce(\"hooks\", () => {\n // `Hooks<Fields>` is strongly typed, but `Object.entries()` loses that information.\n // oxlint-disable-next-line no-explicit-any\n Object.entries(hooks).forEach(([fieldName, fieldHooks]: [string, any]) => {\n const field = this.fields[fieldName];\n if (field === undefined) throw new Error(`field not found: ${fieldName}`);\n (this.fields as Record<string, TailorAnyDBField>)[fieldName] = (\n field as TailorAnyDBField\n ).hooks(fieldHooks);\n });\n return this as TypeAfter<\"hooks\">;\n });\n },\n\n validate(validators: Validators<Fields>): TypeAfter<\"validate\"> {\n return runMethodOnce(\"validate\", () => {\n Object.entries(validators).forEach(([fieldName, fieldValidators]) => {\n const field = this.fields[fieldName] as TailorAnyDBField;\n\n const validators = fieldValidators as\n | FieldValidateInput<unknown>\n | FieldValidateInput<unknown>[];\n\n const isValidateConfig = (v: unknown): v is ValidateConfig<unknown> => {\n return Array.isArray(v) && v.length === 2 && typeof v[1] === \"string\";\n };\n\n let updatedField: TailorAnyDBField;\n if (Array.isArray(validators)) {\n if (isValidateConfig(validators)) {\n updatedField = field.validate(validators);\n } else {\n updatedField = field.validate(...validators);\n }\n } else {\n updatedField = field.validate(validators);\n }\n (this.fields as Record<string, TailorAnyDBField>)[fieldName] = updatedField;\n });\n return this as TypeAfter<\"validate\">;\n });\n },\n\n features(features: Omit<TypeFeatures, \"pluralForm\">): TypeAfter<\"features\"> {\n return runMethodOnce(\"features\", () => {\n _settings = {\n ..._settings,\n ...features,\n };\n return this as TypeAfter<\"features\">;\n });\n },\n\n indexes(\n ...indexes: IndexDef<TailorDBType<Fields, User, DefinedDBTypeMetadata>>[]\n ): TypeAfter<\"indexes\"> {\n return runMethodOnce(\"indexes\", () => {\n _indexes = indexes;\n return this as TypeAfter<\"indexes\">;\n });\n },\n\n files<const F extends string>(\n files: Record<F, string> & FileKeyConflictError<Fields, User>,\n ): TypeAfter<\"files\"> {\n return runMethodOnce(\"files\", () => {\n _files = files;\n return this as TypeAfter<\"files\">;\n });\n },\n\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>> =\n TailorTypePermission<U, output<TailorDBType<Fields, User, DefinedDBTypeMetadata>>>,\n >(permission: P): TypeAfterUser<U, \"permission\"> {\n return runMethodOnce(\"permission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"permission\">;\n _permissions.record = permission as RawPermissions[\"record\"];\n return ret;\n });\n },\n\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(permission: P): TypeAfterUser<U, \"gqlPermission\"> {\n return runMethodOnce(\"gqlPermission\", () => {\n const ret = this as unknown as TypeAfterUser<U, \"gqlPermission\">;\n _permissions.gql = permission as RawPermissions[\"gql\"];\n return ret;\n });\n },\n\n description(description: string): TypeAfter<\"description\"> {\n return runMethodOnce(\"description\", () => {\n _description = description;\n this._description = description;\n return this as TypeAfter<\"description\">;\n });\n },\n\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options?: Opt) {\n const result = {} as Record<K, TailorAnyDBField>;\n for (const key of keys) {\n const field = this.fields[key] as TailorAnyDBField;\n if (options) {\n result[key] = field.clone(options);\n } else {\n result[key] = field;\n }\n }\n // oxlint-disable-next-line no-explicit-any\n return result as any;\n },\n\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K> {\n const keysSet = new Set(keys);\n const result = {} as Record<string, TailorAnyDBField>;\n for (const key in this.fields) {\n if (Object.hasOwn(this.fields, key) && !keysSet.has(key as unknown as K)) {\n result[key] = this.fields[key] as TailorAnyDBField;\n }\n }\n return result as Omit<Fields, K>;\n },\n\n get plugins(): PluginAttachment[] {\n return _plugins;\n },\n\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User, AnyBuilderMethod> {\n for (const [pluginId, pluginConfig] of Object.entries(config)) {\n _plugins.push({ pluginId, config: pluginConfig });\n }\n return this;\n },\n };\n\n return brandValue(dbType, \"tailordb-type\");\n}\n\nconst idField = uuid();\ntype idField = typeof idField;\ntype DBType<\n F extends { id?: never } & Record<string, TailorAnyDBField>,\n Defined extends DefinedDBTypeMetadata = DefinedDBTypeMetadata,\n> = TailorDBInstance<{ id: idField } & F, InferredAttributeMap, Defined>;\n\n/**\n * Creates a new database type with the specified fields.\n * An `id` field (UUID) is automatically added to every type.\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n * @example\n * export const user = db.type(\"User\", {\n * name: db.string(),\n * email: db.string(),\n * age: db.int({ optional: true }),\n * role: db.enum([\"admin\", \"member\"]),\n * ...db.fields.timestamps(),\n * });\n * // Always export both the value and type:\n * export type user = typeof user;\n */\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fields: F,\n): DBType<F>;\n/**\n * Creates a new database type with the specified fields and description.\n * An `id` field (UUID) is automatically added to every type.\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param description - A description of the type\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n */\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n description: string,\n fields: F,\n): DBType<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">>;\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fieldsOrDescription: string | F,\n fields?: F,\n): DBType<F> | DBType<F, WithDBTypeMetadata<DefinedDBTypeMetadata, \"description\">> {\n const typeName = Array.isArray(name) ? name[0] : name;\n const pluralForm = Array.isArray(name) ? name[1] : undefined;\n\n let description: string | undefined;\n let fieldDef: F;\n if (typeof fieldsOrDescription === \"string\") {\n description = fieldsOrDescription;\n fieldDef = fields as F;\n } else {\n fieldDef = fieldsOrDescription;\n }\n return createTailorDBType<{ id: idField } & F>(\n typeName,\n {\n id: idField,\n ...fieldDef,\n },\n { pluralForm, description },\n ) as DBType<F>;\n}\n\n/** TailorDB schema builder utilities for defining types and fields. */\nexport const db = {\n type: dbType,\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n fields: {\n /**\n * Creates standard timestamp fields (createdAt, updatedAt) with auto-hooks.\n * createdAt is set on create, updatedAt is set on update.\n * A user-specified createdAt is respected when provided (e.g. seeding historical\n * records); the current time is used only when the value is omitted.\n * @returns An object with createdAt and updatedAt fields\n * @example\n * const model = db.type(\"Model\", {\n * name: db.string(),\n * ...db.fields.timestamps(),\n * });\n */\n timestamps: () => ({\n createdAt: datetime()\n .hooks({ create: ({ value }) => value ?? new Date() })\n .description(\"Record creation timestamp\"),\n updatedAt: datetime({ optional: true })\n .hooks({ update: () => new Date() })\n .description(\"Record last update timestamp\"),\n }),\n },\n};\n"],"mappings":";;;;;;;;;AASA,SAAgB,iBAAiB,QAAoC;CACnE,OAAO,OAAO,KAAK,UAAU;EAC3B,IAAI,OAAO,UAAU,UACnB,OAAO;GAAE;GAAO,aAAa;EAAG;EAElC,OAAO;GAAE,GAAG;GAAO,aAAa,MAAM,eAAe;EAAG;CAC1D,CAAC;AACH;;;;ACZA,MAAM,QAAQ;CACZ,MAAM;CACN,MAAM;CACN,MAAM;CACN,UACE;CACF,SAAS;AACX;AA8BA,SAAS,kBAA6C,MAAuC;CAC3F,MAAM,EAAE,OAAO,OAAO,WAAW,WAAW;CAC5C,MAAM,OAAO,UAAU,SAAS,IAAI,YAAY;CAChD,MAAM,oBAAoB,OAAO;CAEjC,QAAQ,MAAM,MAAd;EACE,KAAK;GACH,IAAI,OAAO,UAAU,UACnB,OAAO,KAAK;IACV,SAAS,+BAA+B,OAAO,KAAK;IACpD;GACF,CAAC;GAEH;EAEF,KAAK;GACH,IAAI,OAAO,UAAU,YAAY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,8BAA8B;CAC/C,GACF;AACF"}
@@ -1,31 +1,6 @@
1
- import { t as readPackageJson } from "./package-json-8b0O9TlX.mjs";
2
1
  import * as fs from "node:fs";
3
2
  import * as path from "pathe";
4
3
 
5
- //#region src/cli/shared/user-agent.ts
6
- /**
7
- * Build the User-Agent string from an already-known SDK version, without
8
- * touching the filesystem. Use this when the caller has resolved the version
9
- * (e.g. crash reporting already reads `package.json`) to avoid a redundant read.
10
- * @param version - SDK version string
11
- * @returns User-Agent header value
12
- */
13
- function userAgentFromVersion(version) {
14
- return `tailor-sdk/${version}`;
15
- }
16
- /**
17
- * Build the User-Agent string for CLI requests.
18
- *
19
- * Lives in its own module (rather than `client.ts`) so callers that only need
20
- * the UA — e.g. crash reporting — do not pull in the operator client's heavy
21
- * OAuth2/Connect/Protobuf dependencies, and so importing it never forms a cycle.
22
- * @returns User-Agent header value
23
- */
24
- async function userAgent() {
25
- return userAgentFromVersion((await readPackageJson()).version ?? "unknown");
26
- }
27
-
28
- //#endregion
29
4
  //#region src/cli/shared/secret-file.ts
30
5
  const DIR_MODE = 448;
31
6
  const FILE_MODE = 384;
@@ -85,5 +60,5 @@ function tightenSecretFilePermissions(filePath) {
85
60
  }
86
61
 
87
62
  //#endregion
88
- export { userAgentFromVersion as a, userAgent as i, tightenSecretFilePermissions as n, writeSecretFile as r, ensureSecretDir as t };
89
- //# sourceMappingURL=secret-file-VSVGy1V0.mjs.map
63
+ export { tightenSecretFilePermissions as n, writeSecretFile as r, ensureSecretDir as t };
64
+ //# sourceMappingURL=secret-file-DBqZhjFQ.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"secret-file-VSVGy1V0.mjs","names":[],"sources":["../src/cli/shared/user-agent.ts","../src/cli/shared/secret-file.ts"],"sourcesContent":["import { readPackageJson } from \"./package-json\";\n\n/**\n * Build the User-Agent string from an already-known SDK version, without\n * touching the filesystem. Use this when the caller has resolved the version\n * (e.g. crash reporting already reads `package.json`) to avoid a redundant read.\n * @param version - SDK version string\n * @returns User-Agent header value\n */\nexport function userAgentFromVersion(version: string): string {\n return `tailor-sdk/${version}`;\n}\n\n/**\n * Build the User-Agent string for CLI requests.\n *\n * Lives in its own module (rather than `client.ts`) so callers that only need\n * the UA — e.g. crash reporting — do not pull in the operator client's heavy\n * OAuth2/Connect/Protobuf dependencies, and so importing it never forms a cycle.\n * @returns User-Agent header value\n */\nexport async function userAgent() {\n const packageJson = await readPackageJson();\n return userAgentFromVersion(packageJson.version ?? \"unknown\");\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * Best-effort chmod that only fires when the current mode differs from the\n * target. No-op on Windows (where POSIX mode bits are advisory and ACLs\n * govern access) and on missing paths / permission errors.\n * @param target - Path to chmod\n * @param mode - Desired POSIX mode bits\n */\nfunction chmodIfDifferent(target: string, mode: number): void {\n if (process.platform === \"win32\") return;\n try {\n if ((fs.statSync(target).mode & 0o777) !== mode) {\n fs.chmodSync(target, mode);\n }\n } catch {\n // Missing path or permission error — best-effort.\n }\n}\n\n/**\n * Write a file that may contain secrets with restrictive permissions.\n * Creates the parent directory with 0o700 and the file with 0o600 on POSIX\n * systems so other users on the host cannot read access tokens, refresh\n * tokens, or crash report payloads. On Windows the POSIX mode bits are\n * effectively ignored and ACLs govern access, so the chmod calls are\n * best-effort and silently skipped.\n * @param filePath - Absolute path to write\n * @param content - File content\n */\nexport function writeSecretFile(filePath: string, content: string | Buffer): void {\n ensureSecretDir(path.dirname(filePath));\n fs.writeFileSync(filePath, content, { mode: FILE_MODE });\n chmodIfDifferent(filePath, FILE_MODE);\n}\n\n/**\n * Ensure a directory exists with 0o700 permissions on POSIX systems.\n * `mkdirSync({ recursive: true })` does not chmod existing directories,\n * so this also tightens permissions on directories that were previously\n * created with looser modes.\n * @param dir - Directory path\n */\nexport function ensureSecretDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });\n chmodIfDifferent(dir, DIR_MODE);\n}\n\n/**\n * Tighten an existing file and its parent directory to secret-file modes\n * (0o600 / 0o700) if they are looser. Used by read paths that may not\n * trigger a subsequent write, so that legacy world-readable files are\n * still secured the next time the CLI runs. Silent no-op on Windows and\n * on missing files / permission errors.\n * @param filePath - Absolute path that should be 0o600 and live under a 0o700 directory\n */\nexport function tightenSecretFilePermissions(filePath: string): void {\n chmodIfDifferent(filePath, FILE_MODE);\n chmodIfDifferent(path.dirname(filePath), DIR_MODE);\n}\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,qBAAqB,SAAyB;CAC5D,OAAO,cAAc;AACvB;;;;;;;;;AAUA,eAAsB,YAAY;CAEhC,OAAO,sBAAqB,MADF,gBAAgB,EACH,CAAC,WAAW,SAAS;AAC9D;;;;ACrBA,MAAM,WAAW;AACjB,MAAM,YAAY;;;;;;;;AASlB,SAAS,iBAAiB,QAAgB,MAAoB;CAC5D,IAAI,QAAQ,aAAa,SAAS;CAClC,IAAI;EACF,KAAK,GAAG,SAAS,MAAM,CAAC,CAAC,OAAO,SAAW,MACzC,GAAG,UAAU,QAAQ,IAAI;CAE7B,QAAQ,CAER;AACF;;;;;;;;;;;AAYA,SAAgB,gBAAgB,UAAkB,SAAgC;CAChF,gBAAgB,KAAK,QAAQ,QAAQ,CAAC;CACtC,GAAG,cAAc,UAAU,SAAS,EAAE,MAAM,UAAU,CAAC;CACvD,iBAAiB,UAAU,SAAS;AACtC;;;;;;;;AASA,SAAgB,gBAAgB,KAAmB;CACjD,GAAG,UAAU,KAAK;EAAE,WAAW;EAAM,MAAM;CAAS,CAAC;CACrD,iBAAiB,KAAK,QAAQ;AAChC;;;;;;;;;AAUA,SAAgB,6BAA6B,UAAwB;CACnE,iBAAiB,UAAU,SAAS;CACpC,iBAAiB,KAAK,QAAQ,QAAQ,GAAG,QAAQ;AACnD"}
1
+ {"version":3,"file":"secret-file-DBqZhjFQ.mjs","names":[],"sources":["../src/cli/shared/secret-file.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * Best-effort chmod that only fires when the current mode differs from the\n * target. No-op on Windows (where POSIX mode bits are advisory and ACLs\n * govern access) and on missing paths / permission errors.\n * @param target - Path to chmod\n * @param mode - Desired POSIX mode bits\n */\nfunction chmodIfDifferent(target: string, mode: number): void {\n if (process.platform === \"win32\") return;\n try {\n if ((fs.statSync(target).mode & 0o777) !== mode) {\n fs.chmodSync(target, mode);\n }\n } catch {\n // Missing path or permission error — best-effort.\n }\n}\n\n/**\n * Write a file that may contain secrets with restrictive permissions.\n * Creates the parent directory with 0o700 and the file with 0o600 on POSIX\n * systems so other users on the host cannot read access tokens, refresh\n * tokens, or crash report payloads. On Windows the POSIX mode bits are\n * effectively ignored and ACLs govern access, so the chmod calls are\n * best-effort and silently skipped.\n * @param filePath - Absolute path to write\n * @param content - File content\n */\nexport function writeSecretFile(filePath: string, content: string | Buffer): void {\n ensureSecretDir(path.dirname(filePath));\n fs.writeFileSync(filePath, content, { mode: FILE_MODE });\n chmodIfDifferent(filePath, FILE_MODE);\n}\n\n/**\n * Ensure a directory exists with 0o700 permissions on POSIX systems.\n * `mkdirSync({ recursive: true })` does not chmod existing directories,\n * so this also tightens permissions on directories that were previously\n * created with looser modes.\n * @param dir - Directory path\n */\nexport function ensureSecretDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });\n chmodIfDifferent(dir, DIR_MODE);\n}\n\n/**\n * Tighten an existing file and its parent directory to secret-file modes\n * (0o600 / 0o700) if they are looser. Used by read paths that may not\n * trigger a subsequent write, so that legacy world-readable files are\n * still secured the next time the CLI runs. Silent no-op on Windows and\n * on missing files / permission errors.\n * @param filePath - Absolute path that should be 0o600 and live under a 0o700 directory\n */\nexport function tightenSecretFilePermissions(filePath: string): void {\n chmodIfDifferent(filePath, FILE_MODE);\n chmodIfDifferent(path.dirname(filePath), DIR_MODE);\n}\n"],"mappings":";;;;AAGA,MAAM,WAAW;AACjB,MAAM,YAAY;;;;;;;;AASlB,SAAS,iBAAiB,QAAgB,MAAoB;CAC5D,IAAI,QAAQ,aAAa,SAAS;CAClC,IAAI;EACF,KAAK,GAAG,SAAS,MAAM,CAAC,CAAC,OAAO,SAAW,MACzC,GAAG,UAAU,QAAQ,IAAI;CAE7B,QAAQ,CAER;AACF;;;;;;;;;;;AAYA,SAAgB,gBAAgB,UAAkB,SAAgC;CAChF,gBAAgB,KAAK,QAAQ,QAAQ,CAAC;CACtC,GAAG,cAAc,UAAU,SAAS,EAAE,MAAM,UAAU,CAAC;CACvD,iBAAiB,UAAU,SAAS;AACtC;;;;;;;;AASA,SAAgB,gBAAgB,KAAmB;CACjD,GAAG,UAAU,KAAK;EAAE,WAAW;EAAM,MAAM;CAAS,CAAC;CACrD,iBAAiB,KAAK,QAAQ;AAChC;;;;;;;;;AAUA,SAAgB,6BAA6B,UAAwB;CACnE,iBAAiB,UAAU,SAAS;CACpC,iBAAiB,KAAK,QAAQ,QAAQ,GAAG,QAAQ;AACnD"}
@@ -30,29 +30,38 @@ const SECRET_STORE = Symbol("tailorSecretStore");
30
30
  * inherited (cloned) from the currently-installed mock on acquisition and
31
31
  * restored on dispose, so secrets seeded outside the test survive across
32
32
  * `using` scopes while per-test `setSecrets()` overrides stay isolated.
33
+ * @param options - Initial Secret Manager fixtures
33
34
  * @returns Disposable SecretManager mock control object
34
35
  * @example
35
36
  * ```typescript
36
37
  * import { mockSecretmanager } from "@tailor-platform/sdk/vitest";
37
38
  *
38
39
  * test("reads secrets from vault", async () => {
39
- * using sm = mockSecretmanager();
40
- * sm.setSecrets({ "my-vault": { API_KEY: "sk-123" } });
40
+ * using sm = mockSecretmanager({ secrets: { "my-vault": { API_KEY: "sk-123" } } });
41
+ * sm.setSecret("my-vault", "API_KEY", "replacement");
41
42
  * // …
42
43
  * });
43
44
  * ```
44
45
  */
45
- function mockSecretmanager() {
46
+ function mockSecretmanager(options = {}) {
46
47
  const root = tailorRoot();
47
48
  const prev = root.secretmanager;
48
49
  const holder = { store: structuredClone(prev?.[SECRET_STORE]?.store ?? {}) };
49
- const getSecret = vi.fn(async (vault, name) => holder.store[vault]?.[name]);
50
- const getSecrets = vi.fn(async (vault, names) => {
50
+ for (const [vault, secrets] of Object.entries(options.secrets ?? {})) holder.store[vault] = {
51
+ ...holder.store[vault],
52
+ ...secrets
53
+ };
54
+ async function defaultGetSecret(vault, name) {
55
+ return holder.store[vault]?.[name];
56
+ }
57
+ async function defaultGetSecrets(vault, names) {
51
58
  const vaultData = holder.store[vault] ?? {};
52
59
  const result = {};
53
60
  for (const name of names) if (name in vaultData) result[name] = assertDefined(vaultData[name], `vault entry missing for: ${name}`);
54
61
  return result;
55
- });
62
+ }
63
+ const getSecret = vi.fn(defaultGetSecret);
64
+ const getSecrets = vi.fn(defaultGetSecrets);
56
65
  root.secretmanager = {
57
66
  getSecret,
58
67
  getSecrets,
@@ -66,6 +75,24 @@ function mockSecretmanager() {
66
75
  setSecrets(secrets) {
67
76
  holder.store = secrets;
68
77
  },
78
+ setSecret(vault, name, value) {
79
+ holder.store = {
80
+ ...holder.store,
81
+ [vault]: {
82
+ ...holder.store[vault],
83
+ [name]: value
84
+ }
85
+ };
86
+ },
87
+ mergeSecrets(vault, secrets) {
88
+ holder.store = {
89
+ ...holder.store,
90
+ [vault]: {
91
+ ...holder.store[vault],
92
+ ...secrets
93
+ }
94
+ };
95
+ },
69
96
  get calls() {
70
97
  return [...getSecret.mock.calls.map((args, i) => ({
71
98
  order: getSecret.mock.invocationCallOrder[i] ?? 0,
@@ -83,10 +110,16 @@ function mockSecretmanager() {
83
110
  }
84
111
  }))].toSorted((a, b) => a.order - b.order).map((e) => e.call);
85
112
  },
86
- reset() {
87
- holder.store = {};
113
+ clear() {
88
114
  getSecret.mockClear();
89
115
  getSecrets.mockClear();
116
+ },
117
+ reset() {
118
+ holder.store = {};
119
+ getSecret.mockReset();
120
+ getSecret.mockImplementation(defaultGetSecret);
121
+ getSecrets.mockReset();
122
+ getSecrets.mockImplementation(defaultGetSecrets);
90
123
  }
91
124
  }, () => {
92
125
  root.secretmanager = prev;
@@ -95,4 +128,4 @@ function mockSecretmanager() {
95
128
 
96
129
  //#endregion
97
130
  export { withDispose as i, tailorRoot as n, tailordbRoot as r, mockSecretmanager as t };
98
- //# sourceMappingURL=secretmanager-Bd45j7an.mjs.map
131
+ //# sourceMappingURL=secretmanager-IY4UvinW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secretmanager-IY4UvinW.mjs","names":[],"sources":["../src/vitest/mocks/shared.ts","../src/vitest/mocks/secretmanager.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\n// Attach a non-enumerable `Symbol.dispose` to a facade so it works with `using`.\nexport function withDispose<T extends object>(facade: T, dispose: () => void): T & Disposable {\n Object.defineProperty(facade, Symbol.dispose, {\n value: dispose,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n return facade as T & Disposable;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function tailorRoot(): Record<string, any> {\n const g = globalThis as Record<string, unknown>;\n if (!g.tailor) {\n // Ensure the container (and the always-present context stub) exists even if\n // the base globals were not installed (e.g. a unit test that only acquires\n // a single mock without the tailor-runtime environment).\n g.tailor = { context: { getInvoker: () => null } };\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return g.tailor as Record<string, any>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function tailordbRoot(): Record<string, any> {\n const g = globalThis as Record<string, unknown>;\n if (!g.tailordb) {\n g.tailordb = {};\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return g.tailordb as Record<string, any>;\n}\n","import { vi } from \"vitest\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { tailorRoot, withDispose } from \"./shared\";\n\ninterface SecretCall {\n method: \"getSecret\" | \"getSecrets\";\n vault: string;\n name?: string;\n names?: readonly string[];\n}\n\n/** Initial fixtures for a Secret Manager mock. */\nexport interface MockSecretmanagerOptions {\n /** Secrets to merge over fixtures inherited from the currently installed mock. */\n secrets?: Record<string, Record<string, string>>;\n}\n\n// ---------------------------------------------------------------------------\n// SecretManager Mock\n// ---------------------------------------------------------------------------\n\n// Hidden accessor key used to inherit the previous scope's secret store on\n// acquisition (so secrets seeded once outside tests — e.g. from tailor.config.ts\n// via setup.ts — remain visible) while still isolating per-test overrides.\nconst SECRET_STORE = Symbol(\"tailorSecretStore\");\n\n/**\n * Acquire a disposable mock for `tailor.secretmanager`. The secret store is\n * inherited (cloned) from the currently-installed mock on acquisition and\n * restored on dispose, so secrets seeded outside the test survive across\n * `using` scopes while per-test `setSecrets()` overrides stay isolated.\n * @param options - Initial Secret Manager fixtures\n * @returns Disposable SecretManager mock control object\n * @example\n * ```typescript\n * import { mockSecretmanager } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"reads secrets from vault\", async () => {\n * using sm = mockSecretmanager({ secrets: { \"my-vault\": { API_KEY: \"sk-123\" } } });\n * sm.setSecret(\"my-vault\", \"API_KEY\", \"replacement\");\n * // …\n * });\n * ```\n */\nexport function mockSecretmanager(options: MockSecretmanagerOptions = {}) {\n const root = tailorRoot();\n const prev = root.secretmanager;\n\n const holder: { store: Record<string, Record<string, string>> } = {\n // prior mock state may be absent\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n store: structuredClone((prev?.[SECRET_STORE]?.store as typeof holder.store) ?? {}),\n };\n for (const [vault, secrets] of Object.entries(options.secrets ?? {})) {\n holder.store[vault] = { ...holder.store[vault], ...secrets };\n }\n\n async function defaultGetSecret(vault: string, name: string): Promise<string | undefined> {\n return holder.store[vault]?.[name];\n }\n\n async function defaultGetSecrets<const T extends readonly string[]>(\n vault: string,\n names: T,\n ): Promise<Partial<Record<T[number], string>>> {\n const vaultData = holder.store[vault] ?? {};\n const result: Record<string, string> = {};\n for (const name of names) {\n if (name in vaultData) {\n result[name] = assertDefined(vaultData[name], `vault entry missing for: ${name}`);\n }\n }\n return result as Partial<Record<T[number], string>>;\n }\n\n const getSecret = vi.fn(defaultGetSecret);\n const getSecrets = vi.fn(defaultGetSecrets);\n\n root.secretmanager = { getSecret, getSecrets, [SECRET_STORE]: holder };\n\n const facade = {\n /** The `getSecret` `vi.fn`. */\n getSecret,\n /** The `getSecrets` `vi.fn`. */\n getSecrets,\n\n setSecrets(secrets: Record<string, Record<string, string>>): void {\n holder.store = secrets;\n },\n\n setSecret(vault: string, name: string, value: string): void {\n holder.store = {\n ...holder.store,\n [vault]: { ...holder.store[vault], [name]: value },\n };\n },\n\n mergeSecrets(vault: string, secrets: Record<string, string>): void {\n holder.store = {\n ...holder.store,\n [vault]: { ...holder.store[vault], ...secrets },\n };\n },\n\n get calls(): SecretCall[] {\n // Merge both methods' calls back into chronological order via vi.fn's\n // global invocationCallOrder, so a test mixing getSecret/getSecrets sees\n // them in the order they actually ran (not all getSecret, then all getSecrets).\n const entries: { order: number; call: SecretCall }[] = [\n ...getSecret.mock.calls.map((args, i) => ({\n order: getSecret.mock.invocationCallOrder[i] ?? 0,\n call: { method: \"getSecret\" as const, vault: args[0] as string, name: args[1] as string },\n })),\n ...getSecrets.mock.calls.map((args, i) => ({\n order: getSecrets.mock.invocationCallOrder[i] ?? 0,\n call: {\n method: \"getSecrets\" as const,\n vault: args[0] as string,\n names: args[1] as readonly string[],\n },\n })),\n ];\n return entries.toSorted((a, b) => a.order - b.order).map((e) => e.call);\n },\n\n clear(): void {\n getSecret.mockClear();\n getSecrets.mockClear();\n },\n\n reset(): void {\n holder.store = {};\n getSecret.mockReset();\n getSecret.mockImplementation(defaultGetSecret);\n getSecrets.mockReset();\n getSecrets.mockImplementation(defaultGetSecrets);\n },\n };\n\n return withDispose(facade, () => {\n root.secretmanager = prev;\n });\n}\n"],"mappings":";;;;AAKA,SAAgB,YAA8B,QAAW,SAAqC;CAC5F,OAAO,eAAe,QAAQ,OAAO,SAAS;EAC5C,OAAO;EACP,YAAY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ACb,GAAG,OAAO;KACT,QAAQ;KAAE,GAAG,OAAO,MAAM;MAAS,OAAO;IAAM;GACnD;EACF;EAEA,aAAa,OAAe,SAAuC;GACjE,OAAO,QAAQ;IACb,GAAG,OAAO;KACT,QAAQ;KAAE,GAAG,OAAO,MAAM;KAAQ,GAAG;IAAQ;GAChD;EACF;EAEA,IAAI,QAAsB;GAkBxB,OAAO,CAbL,GAAG,UAAU,KAAK,MAAM,KAAK,MAAM,OAAO;IACxC,OAAO,UAAU,KAAK,oBAAoB,MAAM;IAChD,MAAM;KAAE,QAAQ;KAAsB,OAAO,KAAK;KAAc,MAAM,KAAK;IAAa;GAC1F,EAAE,GACF,GAAG,WAAW,KAAK,MAAM,KAAK,MAAM,OAAO;IACzC,OAAO,WAAW,KAAK,oBAAoB,MAAM;IACjD,MAAM;KACJ,QAAQ;KACR,OAAO,KAAK;KACZ,OAAO,KAAK;IACd;GACF,EAAE,CAES,CAAC,CAAC,UAAU,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC,KAAK,MAAM,EAAE,IAAI;EACxE;EAEA,QAAc;GACZ,UAAU,UAAU;GACpB,WAAW,UAAU;EACvB;EAEA,QAAc;GACZ,OAAO,QAAQ,CAAC;GAChB,UAAU,UAAU;GACpB,UAAU,mBAAmB,gBAAgB;GAC7C,WAAW,UAAU;GACrB,WAAW,mBAAmB,iBAAiB;EACjD;CAGsB,SAAS;EAC/B,KAAK,gBAAgB;CACvB,CAAC;AACH"}
@@ -1,8 +1,9 @@
1
1
  import { ForeignKeyDefinition, IndexDefinition, defineSchema } from "@toiroakr/lines-db";
2
-
3
2
  //#region src/seed/index.d.ts
4
3
  type ValidateSeedDataOptions = {
5
- /** Resolved absolute path to a data directory or a .jsonl file */path: string; /** Show verbose error output */
4
+ /** Resolved absolute path to a data directory or a .jsonl file */
5
+ path: string;
6
+ /** Show verbose error output */
6
7
  verbose?: boolean;
7
8
  };
8
9
  type ValidateSeedResult = {
@@ -1,5 +1,6 @@
1
1
  import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
2
2
  import { t as multiline } from "./multiline-sfHpTZZK.mjs";
3
+ import { t as isPluginGeneratedType } from "./type-source-DH_LH20p.mjs";
3
4
  import * as path from "pathe";
4
5
 
5
6
  //#region src/plugin/builtin/seed/idp-user-processor.ts
@@ -155,17 +156,6 @@ function generateIdpUserSchemaFile(options) {
155
156
  `;
156
157
  }
157
158
 
158
- //#endregion
159
- //#region src/parser/service/tailordb/type-source.ts
160
- /**
161
- * Checks if a type source is generated by a plugin.
162
- * @param source - The type source entry to check.
163
- * @returns True if the source was generated by a plugin.
164
- */
165
- function isPluginGeneratedType(source) {
166
- return source.pluginId !== void 0;
167
- }
168
-
169
159
  //#endregion
170
160
  //#region src/plugin/builtin/seed/lines-db-processor.ts
171
161
  /**
@@ -1177,5 +1167,5 @@ function seedPlugin(options) {
1177
1167
  }
1178
1168
 
1179
1169
  //#endregion
1180
- export { seedPlugin as n, isPluginGeneratedType as r, SeedGeneratorID as t };
1181
- //# sourceMappingURL=seed-fm0LeYP2.mjs.map
1170
+ export { seedPlugin as n, SeedGeneratorID as t };
1171
+ //# sourceMappingURL=seed-DFFigL8V.mjs.map