@tailor-platform/sdk 2.21.0 → 2.23.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 (119) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/agent-skills/tailor/SKILL.md +3 -1
  3. package/dist/aigateway-DsWDjzk4.mjs.map +1 -1
  4. package/dist/application-BtZ8hmx9.mjs +1 -0
  5. package/dist/{application-D4913edS.mjs → application-m2G91kKI.mjs} +29 -29
  6. package/dist/application-m2G91kKI.mjs.map +1 -0
  7. package/dist/assert-WeXvmG4j.mjs.map +1 -1
  8. package/dist/authconnection-CynFBIv8.mjs.map +1 -1
  9. package/dist/brand-C8nMKhJC.mjs.map +1 -1
  10. package/dist/cli/commands/deploy/app-id-lock.d.mts +31 -0
  11. package/dist/cli/lib.d.mts +2 -2
  12. package/dist/cli/lib.mjs +1 -1
  13. package/dist/cli/lib.mjs.map +1 -1
  14. package/dist/cli/main.mjs +41 -41
  15. package/dist/cli/main.mjs.map +1 -1
  16. package/dist/cli/shared/client.d.mts +17 -2
  17. package/dist/cli/shared/logger.d.mts +9 -0
  18. package/dist/cli/shared/tailordb-namespaces.d.mts +1 -1
  19. package/dist/completion/zsh-worker.zsh +13 -7
  20. package/dist/configure/config/index.d.mts +2 -0
  21. package/dist/configure/index.mjs.map +1 -1
  22. package/dist/context-D0QjfxzD.mjs.map +1 -1
  23. package/dist/crashreport-CBaRJl5h.mjs +1 -0
  24. package/dist/{crashreport-BAz-ph5O.mjs → crashreport-DFpRn-LS.mjs} +4 -4
  25. package/dist/crashreport-DFpRn-LS.mjs.map +1 -0
  26. package/dist/date-Dri6Yas-.mjs.map +1 -1
  27. package/dist/errors-CpvSChyL.mjs +7 -0
  28. package/dist/errors-CpvSChyL.mjs.map +1 -0
  29. package/dist/es-builtins-SfvXRVoG.mjs.map +1 -1
  30. package/dist/field-parse-DhnFs9WG.mjs.map +1 -1
  31. package/dist/file-DKBOj5q4.mjs.map +1 -1
  32. package/dist/globals-BCmGX05J.mjs.map +1 -1
  33. package/dist/guards-yDXyKC9F.mjs +2 -0
  34. package/dist/guards-yDXyKC9F.mjs.map +1 -0
  35. package/dist/iconv-DlFMt2gW.mjs.map +1 -1
  36. package/dist/idp-G_ojPBB5.mjs.map +1 -1
  37. package/dist/interceptor-DQg3cR_9.mjs.map +1 -1
  38. package/dist/kysely/index.mjs.map +1 -1
  39. package/dist/kysely-type-C-iyFFH7.mjs.map +1 -1
  40. package/dist/logger-DP2BjQ93.mjs.map +1 -1
  41. package/dist/logger-Db-YRTwK.mjs +9 -0
  42. package/dist/logger-Db-YRTwK.mjs.map +1 -0
  43. package/dist/{manager-C0dE7pd0.mjs → manager-8-JOvuLl.mjs} +2 -2
  44. package/dist/manager-8-JOvuLl.mjs.map +1 -0
  45. package/dist/multiline-EyzjEwn9.mjs.map +1 -1
  46. package/dist/node-builtins-DYfhPBnz.mjs.map +1 -1
  47. package/dist/package-json-C690ceex.mjs.map +1 -1
  48. package/dist/platform-serialize-DkiTdHOt.mjs.map +1 -1
  49. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  50. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  51. package/dist/plugin/index.mjs +1 -1
  52. package/dist/plugin/index.mjs.map +1 -1
  53. package/dist/register-ts-hook-ztnEFW6n.mjs +922 -0
  54. package/dist/register-ts-hook-ztnEFW6n.mjs.map +1 -0
  55. package/dist/registry-BijIDRVA.mjs.map +1 -1
  56. package/dist/repl-editor-DGJBfIt1.mjs.map +1 -1
  57. package/dist/schema-CRtAmDcl.mjs.map +1 -1
  58. package/dist/secret-file-C9wp_FCX.mjs.map +1 -1
  59. package/dist/secretmanager-5olfnI1b.mjs.map +1 -1
  60. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  61. package/dist/seed/index.mjs +7 -6
  62. package/dist/seed/index.mjs.map +1 -1
  63. package/dist/seed-C3P_T_Eh.mjs.map +1 -1
  64. package/dist/service-Bx-7Lz06.mjs +1 -0
  65. package/dist/{service-BrGSi2IQ.mjs → service-CL1Bp4It.mjs} +3 -3
  66. package/dist/service-CL1Bp4It.mjs.map +1 -0
  67. package/dist/{service-8xznUrPU.mjs → service-DFmt9UJP.mjs} +2 -2
  68. package/dist/service-DFmt9UJP.mjs.map +1 -0
  69. package/dist/service_pb-ZClWtj1X.mjs +2 -0
  70. package/dist/service_pb-ZClWtj1X.mjs.map +1 -0
  71. package/dist/service_pb-dB3RrGeh.mjs +1 -0
  72. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +83 -1
  73. package/dist/tailor-proto/src/tailor/v1/function_resource_pb.d.mts +7 -1
  74. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +79 -7
  75. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +40 -1
  76. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +119 -2
  77. package/dist/tailor-proto/src/tailor/v1/workspace_pb.d.mts +7 -0
  78. package/dist/tailordb-ddl-DqInYupv.mjs.map +1 -1
  79. package/dist/telemetry-Bklv9kQY.mjs.map +1 -1
  80. package/dist/type-source--ZNcV8RJ.mjs.map +1 -1
  81. package/dist/user-agent-vdHYF3QL.mjs.map +1 -1
  82. package/dist/utils/test/index.mjs.map +1 -1
  83. package/dist/vitest/environment.mjs.map +1 -1
  84. package/dist/vitest/index.mjs.map +1 -1
  85. package/dist/vitest/mocks/file.d.mts +1 -1
  86. package/dist/vitest/setup.mjs.map +1 -1
  87. package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -1
  88. package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -1
  89. package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
  90. package/dist/{workspace_resource_pb-D2njwgsE.mjs → workspace_resource_pb-CxR_6fyN.mjs} +2 -2
  91. package/dist/workspace_resource_pb-CxR_6fyN.mjs.map +1 -0
  92. package/docs/cli/application.md +23 -5
  93. package/docs/cli/function.md +2 -2
  94. package/docs/cli-reference.md +22 -12
  95. package/docs/configuration.md +1 -1
  96. package/docs/github-actions.md +90 -24
  97. package/docs/migration/v2.md +70 -5
  98. package/docs/plugin/index.md +1 -1
  99. package/package.json +10 -10
  100. package/dist/application-D4913edS.mjs.map +0 -1
  101. package/dist/application-DBHaxmJE.mjs +0 -1
  102. package/dist/crashreport-BAz-ph5O.mjs.map +0 -1
  103. package/dist/crashreport-BfOkOFgc.mjs +0 -1
  104. package/dist/errors-sNtg2Mv3.mjs +0 -7
  105. package/dist/errors-sNtg2Mv3.mjs.map +0 -1
  106. package/dist/guards-DsX7dJCP.mjs +0 -2
  107. package/dist/guards-DsX7dJCP.mjs.map +0 -1
  108. package/dist/logger-Cp5U2IDI.mjs +0 -9
  109. package/dist/logger-Cp5U2IDI.mjs.map +0 -1
  110. package/dist/manager-C0dE7pd0.mjs.map +0 -1
  111. package/dist/register-ts-hook-YtsAGTMD.mjs +0 -921
  112. package/dist/register-ts-hook-YtsAGTMD.mjs.map +0 -1
  113. package/dist/service-8xznUrPU.mjs.map +0 -1
  114. package/dist/service-BrGSi2IQ.mjs.map +0 -1
  115. package/dist/service-DWMm-4Vm.mjs +0 -1
  116. package/dist/service_pb-DNskuJQC.mjs +0 -1
  117. package/dist/service_pb-y2GYIgfs.mjs +0 -2
  118. package/dist/service_pb-y2GYIgfs.mjs.map +0 -1
  119. package/dist/workspace_resource_pb-D2njwgsE.mjs.map +0 -1
@@ -8,12 +8,12 @@ import { CreateExecutorExecutorRequestSchema, CreateExecutorExecutorResponseSche
8
8
  import { CreateSecretManagerSecretRequestSchema, CreateSecretManagerSecretResponseSchema, CreateSecretManagerVaultRequestSchema, CreateSecretManagerVaultResponseSchema, DeleteSecretManagerSecretRequestSchema, DeleteSecretManagerSecretResponseSchema, DeleteSecretManagerVaultRequestSchema, DeleteSecretManagerVaultResponseSchema, GetSecretManagerSecretRequestSchema, GetSecretManagerSecretResponseSchema, GetSecretManagerVaultRequestSchema, GetSecretManagerVaultResponseSchema, ListSecretManagerSecretsRequestSchema, ListSecretManagerSecretsResponseSchema, ListSecretManagerVaultsRequestSchema, ListSecretManagerVaultsResponseSchema, UpdateSecretManagerSecretRequestSchema, UpdateSecretManagerSecretResponseSchema } from "./secret_manager_pb.mjs";
9
9
  import { CreateAuthConnectionRequestSchema, CreateAuthConnectionResponseSchema, CreateAuthHookRequestSchema, CreateAuthHookResponseSchema, CreateAuthIDPConfigRequestSchema, CreateAuthIDPConfigResponseSchema, CreateAuthMachineUserRequestSchema, CreateAuthMachineUserResponseSchema, CreateAuthOAuth2ClientRequestSchema, CreateAuthOAuth2ClientResponseSchema, CreateAuthSCIMConfigRequestSchema, CreateAuthSCIMConfigResponseSchema, CreateAuthSCIMResourceRequestSchema, CreateAuthSCIMResourceResponseSchema, CreateAuthServiceRequestSchema, CreateAuthServiceResponseSchema, CreateControlplaneMachineUserRequestSchema, CreateControlplaneMachineUserResponseSchema, CreatePersonalAccessTokenRequestSchema, CreatePersonalAccessTokenResponseSchema, CreateTenantConfigRequestSchema, CreateTenantConfigResponseSchema, CreateUserProfileConfigRequestSchema, CreateUserProfileConfigResponseSchema, DeleteAuthConnectionRequestSchema, DeleteAuthConnectionResponseSchema, DeleteAuthHookRequestSchema, DeleteAuthHookResponseSchema, DeleteAuthIDPConfigRequestSchema, DeleteAuthIDPConfigResponseSchema, DeleteAuthMachineUserRequestSchema, DeleteAuthMachineUserResponseSchema, DeleteAuthOAuth2ClientRequestSchema, DeleteAuthOAuth2ClientResponseSchema, DeleteAuthSCIMConfigRequestSchema, DeleteAuthSCIMConfigResponseSchema, DeleteAuthSCIMResourceRequestSchema, DeleteAuthSCIMResourceResponseSchema, DeleteAuthServiceRequestSchema, DeleteAuthServiceResponseSchema, DeleteControlplaneMachineUserRequestSchema, DeleteControlplaneMachineUserResponseSchema, DeletePersonalAccessTokenRequestSchema, DeletePersonalAccessTokenResponseSchema, DeleteTenantConfigRequestSchema, DeleteTenantConfigResponseSchema, DeleteUserProfileConfigRequestSchema, DeleteUserProfileConfigResponseSchema, ExchangeAuthConnectionAuthorizationCodeRequestSchema, ExchangeAuthConnectionAuthorizationCodeResponseSchema, GetAuthHookRequestSchema, GetAuthHookResponseSchema, GetAuthIDPConfigRequestSchema, GetAuthIDPConfigResponseSchema, GetAuthMachineUserRequestSchema, GetAuthMachineUserResponseSchema, GetAuthOAuth2ClientRequestSchema, GetAuthOAuth2ClientResponseSchema, GetAuthSCIMConfigRequestSchema, GetAuthSCIMConfigResponseSchema, GetAuthSCIMResourceRequestSchema, GetAuthSCIMResourceResponseSchema, GetAuthSCIMResourcesRequestSchema, GetAuthSCIMResourcesResponseSchema, GetAuthServiceRequestSchema, GetAuthServiceResponseSchema, GetControlplaneMachineUserByNameRequestSchema, GetControlplaneMachineUserByNameResponseSchema, GetControlplaneMachineUserRequestSchema, GetControlplaneMachineUserResponseSchema, GetTenantConfigRequestSchema, GetTenantConfigResponseSchema, GetUserProfileConfigRequestSchema, GetUserProfileConfigResponseSchema, ListAuthConnectionsRequestSchema, ListAuthConnectionsResponseSchema, ListAuthIDPConfigsRequestSchema, ListAuthIDPConfigsResponseSchema, ListAuthMachineUsersRequestSchema, ListAuthMachineUsersResponseSchema, ListAuthOAuth2ClientsRequestSchema, ListAuthOAuth2ClientsResponseSchema, ListAuthServicesRequestSchema, ListAuthServicesResponseSchema, ListControlplaneMachineUsersRequestSchema, ListControlplaneMachineUsersResponseSchema, ListPersonalAccessTokensRequestSchema, ListPersonalAccessTokensResponseSchema, RegisterAuthConnectionSessionRequestSchema, RegisterAuthConnectionSessionResponseSchema, RevokeAuthConnectionRequestSchema, RevokeAuthConnectionResponseSchema, UpdateAuthConnectionRequestSchema, UpdateAuthConnectionResponseSchema, UpdateAuthHookRequestSchema, UpdateAuthHookResponseSchema, UpdateAuthIDPConfigRequestSchema, UpdateAuthIDPConfigResponseSchema, UpdateAuthMachineUserRequestSchema, UpdateAuthMachineUserResponseSchema, UpdateAuthOAuth2ClientRequestSchema, UpdateAuthOAuth2ClientResponseSchema, UpdateAuthSCIMConfigRequestSchema, UpdateAuthSCIMConfigResponseSchema, UpdateAuthSCIMResourceRequestSchema, UpdateAuthSCIMResourceResponseSchema, UpdateAuthServiceRequestSchema, UpdateAuthServiceResponseSchema, UpdateControlplaneMachineUserRequestSchema, UpdateControlplaneMachineUserResponseSchema, UpdateTenantConfigRequestSchema, UpdateTenantConfigResponseSchema, UpdateUserProfileConfigRequestSchema, UpdateUserProfileConfigResponseSchema } from "./auth_pb.mjs";
10
10
  import { ListControlplaneActivityLogsRequestSchema, ListControlplaneActivityLogsResponseSchema, ListDataplaneEventsRequestSchema, ListDataplaneEventsResponseSchema } from "./events_pb.mjs";
11
- import { ExecScriptRequestSchema, ExecScriptResponseSchema, GetFunctionExecutionRequestSchema, GetFunctionExecutionResponseSchema, ListFunctionExecutionsRequestSchema, ListFunctionExecutionsResponseSchema, TestExecScriptRequestSchema, TestExecScriptResponseSchema } from "./function_pb.mjs";
11
+ import { CancelJobFunctionExecutionRequestSchema, CancelJobFunctionExecutionResponseSchema, ExecScriptRequestSchema, ExecScriptResponseSchema, GetFunctionExecutionRequestSchema, GetFunctionExecutionResponseSchema, ListFunctionExecutionsRequestSchema, ListFunctionExecutionsResponseSchema, StartJobFunctionRequestSchema, StartJobFunctionResponseSchema, TestExecScriptRequestSchema, TestExecScriptResponseSchema } from "./function_pb.mjs";
12
12
  import { CreateFunctionRegistryRequestSchema, CreateFunctionRegistryResponseSchema, DeleteFunctionRegistryRequestSchema, DeleteFunctionRegistryResponseSchema, DownloadFunctionRegistryScriptRequestSchema, DownloadFunctionRegistryScriptResponseSchema, GetFunctionRegistryRequestSchema, GetFunctionRegistryResponseSchema, ListFunctionRegistriesRequestSchema, ListFunctionRegistriesResponseSchema, UpdateFunctionRegistryRequestSchema, UpdateFunctionRegistryResponseSchema } from "./function_registry_pb.mjs";
13
13
  import { ListMeterAITokenUsagesRequestSchema, ListMeterAITokenUsagesResponseSchema, ListMeterEventCountsRequestSchema, ListMeterEventCountsResponseSchema, ListMeterExecutionCountsRequestSchema, ListMeterExecutionCountsResponseSchema, ListMeterRequestCountsRequestSchema, ListMeterRequestCountsResponseSchema } from "./meter_pb.mjs";
14
14
  import { CreateIdPClientRequestSchema, CreateIdPClientResponseSchema, CreateIdPServiceRequestSchema, CreateIdPServiceResponseSchema, DeleteIdPClientRequestSchema, DeleteIdPClientResponseSchema, DeleteIdPServiceRequestSchema, DeleteIdPServiceResponseSchema, GetIdPClientRequestSchema, GetIdPClientResponseSchema, GetIdPServiceRequestSchema, GetIdPServiceResponseSchema, ListIdPClientsRequestSchema, ListIdPClientsResponseSchema, ListIdPServicesRequestSchema, ListIdPServicesResponseSchema, UpdateIdPServiceRequestSchema, UpdateIdPServiceResponseSchema } from "./idp_pb.mjs";
15
15
  import { AddCustomDomainRequestSchema, AddCustomDomainResponseSchema, CreateDeploymentRequestSchema, CreateDeploymentResponseSchema, CreateStaticWebsiteRequestSchema, CreateStaticWebsiteResponseSchema, DeleteStaticWebsiteRequestSchema, DeleteStaticWebsiteResponseSchema, GetCustomDomainRequestSchema, GetCustomDomainResponseSchema, GetStaticWebsiteRequestSchema, GetStaticWebsiteResponseSchema, ListCustomDomainsRequestSchema, ListCustomDomainsResponseSchema, ListStaticWebsitesRequestSchema, ListStaticWebsitesResponseSchema, PublishDeploymentRequestSchema, PublishDeploymentResponseSchema, RemoveCustomDomainRequestSchema, RemoveCustomDomainResponseSchema, UpdateStaticWebsiteRequestSchema, UpdateStaticWebsiteResponseSchema, UploadFileRequestSchema, UploadFileResponseSchema } from "./staticwebsite_pb.mjs";
16
- import { CreateWorkflowJobFunctionExecutionPolicyRequestSchema, CreateWorkflowJobFunctionExecutionPolicyResponseSchema, CreateWorkflowJobFunctionRequestSchema, CreateWorkflowJobFunctionResponseSchema, CreateWorkflowRequestSchema, CreateWorkflowResponseSchema, DeleteWorkflowJobFunctionExecutionPolicyRequestSchema, DeleteWorkflowJobFunctionExecutionPolicyResponseSchema, DeleteWorkflowJobFunctionRequestSchema, DeleteWorkflowJobFunctionResponseSchema, DeleteWorkflowRequestSchema, DeleteWorkflowResponseSchema, GetWorkflowByNameRequestSchema, GetWorkflowByNameResponseSchema, GetWorkflowExecutionRequestSchema, GetWorkflowExecutionResponseSchema, GetWorkflowJobFunctionByNameRequestSchema, GetWorkflowJobFunctionByNameResponseSchema, GetWorkflowJobFunctionExecutionPolicyByKeyRequestSchema, GetWorkflowJobFunctionExecutionPolicyByKeyResponseSchema, GetWorkflowJobFunctionExecutionPolicyRequestSchema, GetWorkflowJobFunctionExecutionPolicyResponseSchema, GetWorkflowJobFunctionRequestSchema, GetWorkflowJobFunctionResponseSchema, GetWorkflowRequestSchema, GetWorkflowResponseSchema, ListWorkflowExecutionsRequestSchema, ListWorkflowExecutionsResponseSchema, ListWorkflowJobFunctionExecutionPoliciesRequestSchema, ListWorkflowJobFunctionExecutionPoliciesResponseSchema, ListWorkflowJobFunctionsRequestSchema, ListWorkflowJobFunctionsResponseSchema, ListWorkflowsRequestSchema, ListWorkflowsResponseSchema, ResumeWorkflowExecutionRequestSchema, ResumeWorkflowExecutionResponseSchema, StartWorkflowRequestSchema, StartWorkflowResponseSchema, TestResumeWorkflowRequestSchema, TestResumeWorkflowResponseSchema, TestStartWorkflowRequestSchema, TestStartWorkflowResponseSchema, UpdateWorkflowJobFunctionExecutionPolicyRequestSchema, UpdateWorkflowJobFunctionExecutionPolicyResponseSchema, UpdateWorkflowJobFunctionRequestSchema, UpdateWorkflowJobFunctionResponseSchema, UpdateWorkflowRequestSchema, UpdateWorkflowResponseSchema } from "./workflow_pb.mjs";
16
+ import { CancelWorkflowExecutionRequestSchema, CancelWorkflowExecutionResponseSchema, CreateWorkflowJobFunctionExecutionPolicyRequestSchema, CreateWorkflowJobFunctionExecutionPolicyResponseSchema, CreateWorkflowJobFunctionRequestSchema, CreateWorkflowJobFunctionResponseSchema, CreateWorkflowRequestSchema, CreateWorkflowResponseSchema, DeleteWorkflowJobFunctionExecutionPolicyRequestSchema, DeleteWorkflowJobFunctionExecutionPolicyResponseSchema, DeleteWorkflowJobFunctionRequestSchema, DeleteWorkflowJobFunctionResponseSchema, DeleteWorkflowRequestSchema, DeleteWorkflowResponseSchema, GetWorkflowByNameRequestSchema, GetWorkflowByNameResponseSchema, GetWorkflowExecutionRequestSchema, GetWorkflowExecutionResponseSchema, GetWorkflowJobFunctionByNameRequestSchema, GetWorkflowJobFunctionByNameResponseSchema, GetWorkflowJobFunctionExecutionPolicyByKeyRequestSchema, GetWorkflowJobFunctionExecutionPolicyByKeyResponseSchema, GetWorkflowJobFunctionExecutionPolicyRequestSchema, GetWorkflowJobFunctionExecutionPolicyResponseSchema, GetWorkflowJobFunctionRequestSchema, GetWorkflowJobFunctionResponseSchema, GetWorkflowRequestSchema, GetWorkflowResponseSchema, ListWorkflowExecutionsRequestSchema, ListWorkflowExecutionsResponseSchema, ListWorkflowJobFunctionExecutionPoliciesRequestSchema, ListWorkflowJobFunctionExecutionPoliciesResponseSchema, ListWorkflowJobFunctionsRequestSchema, ListWorkflowJobFunctionsResponseSchema, ListWorkflowsRequestSchema, ListWorkflowsResponseSchema, ResumeWorkflowExecutionRequestSchema, ResumeWorkflowExecutionResponseSchema, StartWorkflowRequestSchema, StartWorkflowResponseSchema, TestResumeWorkflowRequestSchema, TestResumeWorkflowResponseSchema, TestStartWorkflowRequestSchema, TestStartWorkflowResponseSchema, UpdateWorkflowJobFunctionExecutionPolicyRequestSchema, UpdateWorkflowJobFunctionExecutionPolicyResponseSchema, UpdateWorkflowJobFunctionRequestSchema, UpdateWorkflowJobFunctionResponseSchema, UpdateWorkflowRequestSchema, UpdateWorkflowResponseSchema } from "./workflow_pb.mjs";
17
17
  import { BulkSetMetadataRequestSchema, BulkSetMetadataResponseSchema, GetMetadataRequestSchema, GetMetadataResponseSchema, ListMetadataRequestSchema, ListMetadataResponseSchema, SetMetadataRequestSchema, SetMetadataResponseSchema } from "./metadata_pb.mjs";
18
18
  import { CreateOTLPExporterRequestSchema, CreateOTLPExporterResponseSchema, CreateResourceAttributesConfigRequestSchema, CreateResourceAttributesConfigResponseSchema, DeleteOTLPExporterRequestSchema, DeleteOTLPExporterResponseSchema, DeleteResourceAttributesConfigRequestSchema, DeleteResourceAttributesConfigResponseSchema, GetOTLPExporterRequestSchema, GetOTLPExporterResponseSchema, GetResourceAttributesConfigRequestSchema, GetResourceAttributesConfigResponseSchema, ListOTLPExportersRequestSchema, ListOTLPExportersResponseSchema, TestOTLPExporterRequestSchema, TestOTLPExporterResponseSchema, UpdateOTLPExporterRequestSchema, UpdateOTLPExporterResponseSchema, UpdateResourceAttributesConfigRequestSchema, UpdateResourceAttributesConfigResponseSchema } from "./telemetryrouter_pb.mjs";
19
19
  import { GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";
@@ -244,12 +244,14 @@ export declare const OperatorService: GenService<{
244
244
  output: typeof UpdateWorkspacePlatformUserResponseSchema;
245
245
  };
246
246
  /**
247
- * GetWorkspacePlatformUser returns a workspace platform user.
247
+ * GetWorkspacePlatformUser returns the workspace platform user identified by
248
+ * email. GetWorkspaceRole returns the caller's own role instead.
248
249
  *
249
250
  * [Errors]
250
251
  * - Unauthenticated: token is missing, expired, or invalid
251
252
  * - InvalidArgument: request is invalid
252
- * - NotFound: workspace does not exist or can not be accessed
253
+ * - NotFound: workspace does not exist or can not be accessed, no platform
254
+ * user has that email, or the user is not a platform user of the workspace
253
255
  *
254
256
  * @generated from rpc tailor.v1.OperatorService.GetWorkspacePlatformUser
255
257
  */
@@ -259,7 +261,7 @@ export declare const OperatorService: GenService<{
259
261
  output: typeof GetWorkspacePlatformUserResponseSchema;
260
262
  };
261
263
  /**
262
- * GetWorkspaceRole returns a workspace role of the platform user.
264
+ * GetWorkspaceRole returns the caller's own workspace role.
263
265
  *
264
266
  * [Errors]
265
267
  * - Unauthenticated: token is missing, expired, or invalid
@@ -927,14 +929,15 @@ export declare const OperatorService: GenService<{
927
929
  };
928
930
  /**
929
931
  * CloneApplicationData clones data for an application from a source to a target.
930
- * The RPC returns immediately and the clone runs asynchronously.
932
+ * The RPC returns immediately and the clone runs asynchronously. The target must be
933
+ * empty for every namespace and copy type in scope; a non-empty target is rejected.
931
934
  *
932
935
  * [Errors]
933
936
  * - Unauthenticated: token is missing, expired, or invalid
934
937
  * - Unimplemented: feature flag is disabled
935
938
  * - InvalidArgument: request is invalid
936
939
  * - NotFound: workspace or application does not exist or cannot be accessed
937
- * - FailedPrecondition: cross-region clone or namespace mismatch
940
+ * - FailedPrecondition: cross-region clone, namespace mismatch, or target is not empty
938
941
  *
939
942
  * @generated from rpc tailor.v1.OperatorService.CloneApplicationData
940
943
  */
@@ -1149,6 +1152,10 @@ export declare const OperatorService: GenService<{
1149
1152
  * - Unauthenticated: token is missing, expired, or invalid
1150
1153
  * - InvalidArgument: request is invalid
1151
1154
  * - NotFound: TailorDB type does not exist or can not be accessed
1155
+ * - FailedPrecondition: a field cannot be changed from optional to required while
1156
+ * existing records contain null values for it. The error carries a
1157
+ * google.rpc.PreconditionFailure detail with violation type
1158
+ * "REQUIRED_FIELD_HAS_NULL_VALUES" and the field name as subject.
1152
1159
  *
1153
1160
  * @generated from rpc tailor.v1.OperatorService.UpdateTailorDBType
1154
1161
  */
@@ -2504,6 +2511,12 @@ export declare const OperatorService: GenService<{
2504
2511
  /**
2505
2512
  * Function ---------------------------------------------------------
2506
2513
  * ExecScript executes specified JavaScript code in which I/O operations are allowed and returns the result.
2514
+ * Omitting invoker runs the script as the anonymous dataplane identity.
2515
+ *
2516
+ * [Errors]
2517
+ * - Unauthenticated: token is missing, expired, or invalid
2518
+ * - InvalidArgument: request is invalid, or invoker names only one of namespace / machine_user_name
2519
+ * - NotFound: workspace does not exist or can not be accessed
2507
2520
  *
2508
2521
  * @generated from rpc tailor.v1.OperatorService.ExecScript
2509
2522
  */
@@ -2535,6 +2548,43 @@ export declare const OperatorService: GenService<{
2535
2548
  input: typeof GetFunctionExecutionRequestSchema;
2536
2549
  output: typeof GetFunctionExecutionResponseSchema;
2537
2550
  };
2551
+ /**
2552
+ * StartJobFunction runs a function from the Function Registry as an
2553
+ * asynchronous job and returns its execution id without waiting for the run
2554
+ * to finish. It is the asynchronous counterpart of ExecScript, but takes a
2555
+ * script_ref instead of inline code. The returned execution_id can be passed
2556
+ * to GetFunctionExecution and CancelJobFunctionExecution.
2557
+ *
2558
+ * [Errors]
2559
+ * - Unauthenticated: token is missing, expired, or invalid
2560
+ * - InvalidArgument: request is invalid
2561
+ * - PermissionDenied: can view workspace but no permission to start a job function
2562
+ * - NotFound: workspace or script_ref does not exist or can not be accessed
2563
+ *
2564
+ * @generated from rpc tailor.v1.OperatorService.StartJobFunction
2565
+ */
2566
+ startJobFunction: {
2567
+ methodKind: "unary";
2568
+ input: typeof StartJobFunctionRequestSchema;
2569
+ output: typeof StartJobFunctionResponseSchema;
2570
+ };
2571
+ /**
2572
+ * CancelJobFunctionExecution cancels an in-flight job function execution by
2573
+ * execution_id, regardless of how it was started (workflow, executor, or
2574
+ * directly). RUNNING transitions to CANCELING and is finalized to CANCELED
2575
+ * by reconciliation. SUSPEND transitions directly to CANCELED. Canceling an
2576
+ * already CANCELING/CANCELED execution succeeds (idempotent).
2577
+ * SUCCESS/FAILED returns FailedPrecondition, as does a standard (synchronous)
2578
+ * function execution, which is not cancelable. An unknown execution_id
2579
+ * returns NotFound.
2580
+ *
2581
+ * @generated from rpc tailor.v1.OperatorService.CancelJobFunctionExecution
2582
+ */
2583
+ cancelJobFunctionExecution: {
2584
+ methodKind: "unary";
2585
+ input: typeof CancelJobFunctionExecutionRequestSchema;
2586
+ output: typeof CancelJobFunctionExecutionResponseSchema;
2587
+ };
2538
2588
  /**
2539
2589
  * ListFunctionExecutions lists function executions.
2540
2590
  *
@@ -3214,6 +3264,7 @@ export declare const OperatorService: GenService<{
3214
3264
  };
3215
3265
  /**
3216
3266
  * StartWorkflow starts a workflow execution.
3267
+ * Omitting auth_invoker runs the execution as the anonymous dataplane identity.
3217
3268
  *
3218
3269
  * [Errors]
3219
3270
  * - Unauthenticated: token is missing, expired, or invalid
@@ -3243,6 +3294,27 @@ export declare const OperatorService: GenService<{
3243
3294
  input: typeof ResumeWorkflowExecutionRequestSchema;
3244
3295
  output: typeof ResumeWorkflowExecutionResponseSchema;
3245
3296
  };
3297
+ /**
3298
+ * CancelWorkflowExecution cancels an in-flight workflow execution by
3299
+ * execution_id. The execution and every job function execution still in
3300
+ * flight under it are CANCELED together before the RPC returns; only the
3301
+ * teardown of the job functions' compute happens asynchronously afterwards.
3302
+ * CANCELED is terminal and, unlike FAILED, not resumable. Canceling an
3303
+ * already CANCELED execution succeeds (idempotent).
3304
+ *
3305
+ * [Errors]
3306
+ * - Unauthenticated: token is missing, expired, or invalid
3307
+ * - InvalidArgument: request is invalid
3308
+ * - NotFound: execution does not exist or can not be accessed
3309
+ * - FailedPrecondition: execution already reached SUCCESS or FAILED
3310
+ *
3311
+ * @generated from rpc tailor.v1.OperatorService.CancelWorkflowExecution
3312
+ */
3313
+ cancelWorkflowExecution: {
3314
+ methodKind: "unary";
3315
+ input: typeof CancelWorkflowExecutionRequestSchema;
3316
+ output: typeof CancelWorkflowExecutionResponseSchema;
3317
+ };
3246
3318
  /**
3247
3319
  * TestStartWorkflow is the deprecated legacy alias of StartWorkflow, kept so tailorctl / Console callers can migrate on their own cadence.
3248
3320
  *
@@ -1,6 +1,6 @@
1
1
  import { Filter, PageDirection } from "./resource_pb.mjs";
2
2
  import { AuthInvoker } from "./auth_resource_pb.mjs";
3
- import { ConcurrencyPolicy, RetryPolicy, Workflow, WorkflowExecution, WorkflowJobFunction, WorkflowJobFunctionExecutionPolicy, WorkflowJobFunctionSummary } from "./workflow_resource_pb.mjs";
3
+ import { ConcurrencyPolicy, RetryPolicy, Workflow, WorkflowExecution, WorkflowExecution_Status, WorkflowJobFunction, WorkflowJobFunctionExecutionPolicy, WorkflowJobFunctionSummary } from "./workflow_resource_pb.mjs";
4
4
  import { GenMessage } from "@bufbuild/protobuf/codegenv2";
5
5
  import { Message } from "@bufbuild/protobuf";
6
6
  //#region ../tailor-proto/src/tailor/v1/workflow_pb.d.ts
@@ -611,6 +611,8 @@ export declare type TestStartWorkflowRequest = Message<"tailor.v1.TestStartWorkf
611
611
  */
612
612
  workflowId: string;
613
613
  /**
614
+ * Machine user the execution runs as. Omit to run it as the anonymous dataplane identity.
615
+ *
614
616
  * @generated from field: tailor.v1.AuthInvoker auth_invoker = 3;
615
617
  */
616
618
  authInvoker?: AuthInvoker;
@@ -683,6 +685,8 @@ export declare type StartWorkflowRequest = Message<"tailor.v1.StartWorkflowReque
683
685
  */
684
686
  workflowId: string;
685
687
  /**
688
+ * Machine user the execution runs as. Omit to run it as the anonymous dataplane identity.
689
+ *
686
690
  * @generated from field: tailor.v1.AuthInvoker auth_invoker = 3;
687
691
  */
688
692
  authInvoker?: AuthInvoker;
@@ -742,6 +746,41 @@ export declare type ResumeWorkflowExecutionResponse = Message<"tailor.v1.ResumeW
742
746
  * Use `create(ResumeWorkflowExecutionResponseSchema)` to create a new message.
743
747
  */
744
748
  export declare const ResumeWorkflowExecutionResponseSchema: GenMessage<ResumeWorkflowExecutionResponse>;
749
+ /**
750
+ * @generated from message tailor.v1.CancelWorkflowExecutionRequest
751
+ */
752
+ export declare type CancelWorkflowExecutionRequest = Message<"tailor.v1.CancelWorkflowExecutionRequest"> & {
753
+ /**
754
+ * @generated from field: string workspace_id = 1;
755
+ */
756
+ workspaceId: string;
757
+ /**
758
+ * @generated from field: string execution_id = 2;
759
+ */
760
+ executionId: string;
761
+ };
762
+ /**
763
+ * Describes the message tailor.v1.CancelWorkflowExecutionRequest.
764
+ * Use `create(CancelWorkflowExecutionRequestSchema)` to create a new message.
765
+ */
766
+ export declare const CancelWorkflowExecutionRequestSchema: GenMessage<CancelWorkflowExecutionRequest>;
767
+ /**
768
+ * @generated from message tailor.v1.CancelWorkflowExecutionResponse
769
+ */
770
+ export declare type CancelWorkflowExecutionResponse = Message<"tailor.v1.CancelWorkflowExecutionResponse"> & {
771
+ /**
772
+ * Status after the cancel took effect. Always STATUS_CANCELED; carried so
773
+ * the caller does not need a follow-up GetWorkflowExecution.
774
+ *
775
+ * @generated from field: tailor.v1.WorkflowExecution.Status status = 1;
776
+ */
777
+ status: WorkflowExecution_Status;
778
+ };
779
+ /**
780
+ * Describes the message tailor.v1.CancelWorkflowExecutionResponse.
781
+ * Use `create(CancelWorkflowExecutionResponseSchema)` to create a new message.
782
+ */
783
+ export declare const CancelWorkflowExecutionResponseSchema: GenMessage<CancelWorkflowExecutionResponse>;
745
784
  /**
746
785
  * @generated from message tailor.v1.CreateWorkflowJobFunctionExecutionPolicyRequest
747
786
  */
@@ -209,6 +209,10 @@ export declare type WorkflowJobExecution = Message<"tailor.v1.WorkflowJobExecuti
209
209
  */
210
210
  status: WorkflowJobExecution_Status;
211
211
  /**
212
+ * The function service execution behind this job. Meaningful only when kind
213
+ * is job_function; a wait checkpoint runs no function and carries the nil
214
+ * UUID here.
215
+ *
212
216
  * execution_id in Function Execution
213
217
  *
214
218
  * @generated from field: string execution_id = 4;
@@ -222,6 +226,101 @@ export declare type WorkflowJobExecution = Message<"tailor.v1.WorkflowJobExecuti
222
226
  * @generated from field: google.protobuf.Timestamp finished_at = 6;
223
227
  */
224
228
  finishedAt?: Timestamp;
229
+ /**
230
+ * Where this job sits in the run's execution tree.
231
+ *
232
+ * @generated from field: tailor.v1.WorkflowJobExecution.Position position = 7;
233
+ */
234
+ position?: WorkflowJobExecution_Position;
235
+ /**
236
+ * What kind of job this row is. wait() occupies a call_index in its parent's
237
+ * script and returns a value, exactly like a triggered job function, so it is
238
+ * one of these jobs rather than a separate concept. A reader that does not
239
+ * recognize the variant must still place the job using position.
240
+ *
241
+ * @generated from oneof tailor.v1.WorkflowJobExecution.kind
242
+ */
243
+ kind: {
244
+ /**
245
+ * @generated from field: tailor.v1.WorkflowJobExecution.JobFunctionCall job_function = 8;
246
+ */
247
+ value: WorkflowJobExecution_JobFunctionCall;
248
+ case: "jobFunction";
249
+ } | {
250
+ /**
251
+ * @generated from field: tailor.v1.WorkflowJobExecution.WaitCheckpoint wait = 9;
252
+ */
253
+ value: WorkflowJobExecution_WaitCheckpoint;
254
+ case: "wait";
255
+ } | {
256
+ case: undefined;
257
+ value?: undefined;
258
+ };
259
+ };
260
+ /**
261
+ * Position of a job within its run's execution tree. Siblings are ordered
262
+ * by (call_index, branch_index); started_at is not an ordering, because the
263
+ * branches of one parallel group start together.
264
+ *
265
+ * @generated from message tailor.v1.WorkflowJobExecution.Position
266
+ */
267
+ export declare type WorkflowJobExecution_Position = Message<"tailor.v1.WorkflowJobExecution.Position"> & {
268
+ /**
269
+ * The parent job execution's id (field 1 of this message), not its
270
+ * execution_id. Empty on the main job function, which has no caller, and
271
+ * on jobs recorded before this field existed. Otherwise set, but not
272
+ * always resolvable: job executions are deleted by age and nothing
273
+ * clears the references to them, so a parent can be gone while its
274
+ * children still name it.
275
+ *
276
+ * @generated from field: string parent_workflow_job_execution_id = 1;
277
+ */
278
+ parentWorkflowJobExecutionId: string;
279
+ /**
280
+ * Zero-based order of the call within the parent's script. Unset on the
281
+ * main job function, and on jobs recorded before this field existed.
282
+ *
283
+ * @generated from field: optional int32 call_index = 2;
284
+ */
285
+ callIndex?: number;
286
+ /**
287
+ * Zero-based branch within a parallelJobFunctions.all() group sharing one
288
+ * call_index. Unset when the call did not fan out.
289
+ *
290
+ * @generated from field: optional int32 branch_index = 3;
291
+ */
292
+ branchIndex?: number;
293
+ /**
294
+ * Distance from the main job function, which is 0. Redundant with walking
295
+ * the parent links, and carried so a reader can still indent a job whose
296
+ * parent is outside the set it holds.
297
+ *
298
+ * @generated from field: int32 depth = 4;
299
+ */
300
+ depth: number;
301
+ };
302
+ /**
303
+ * @generated from message tailor.v1.WorkflowJobExecution.JobFunctionCall
304
+ */
305
+ export declare type WorkflowJobExecution_JobFunctionCall = Message<"tailor.v1.WorkflowJobExecution.JobFunctionCall"> & {
306
+ /**
307
+ * Matches WorkflowJobFunction.name.
308
+ *
309
+ * @generated from field: string name = 1;
310
+ */
311
+ name: string;
312
+ };
313
+ /**
314
+ * @generated from message tailor.v1.WorkflowJobExecution.WaitCheckpoint
315
+ */
316
+ export declare type WorkflowJobExecution_WaitCheckpoint = Message<"tailor.v1.WorkflowJobExecution.WaitCheckpoint"> & {
317
+ /**
318
+ * The key passed to tailor.workflow.wait(), as accepted by
319
+ * ResolveWaitingExecution. The payload stays on the wait / resolve APIs.
320
+ *
321
+ * @generated from field: string key = 1;
322
+ */
323
+ key: string;
225
324
  };
226
325
  /**
227
326
  * @generated from enum tailor.v1.WorkflowJobExecution.Status
@@ -250,7 +349,16 @@ export declare enum WorkflowJobExecution_Status {
250
349
  /**
251
350
  * @generated from enum value: STATUS_WAITING = 5;
252
351
  */
253
- WAITING = 5
352
+ WAITING = 5,
353
+ /**
354
+ * Terminal state. The execution was canceled, either directly via
355
+ * CancelJobFunctionExecution or as a descendant of an ancestor that was
356
+ * canceled. Never retried automatically. Must stay integer-aligned with
357
+ * the controlplane enum (the operator transform casts directly).
358
+ *
359
+ * @generated from enum value: STATUS_CANCELED = 6;
360
+ */
361
+ CANCELED = 6
254
362
  }
255
363
  /**
256
364
  * @generated from message tailor.v1.WorkflowExecution
@@ -324,6 +432,15 @@ export declare enum WorkflowExecution_Status {
324
432
  /**
325
433
  * @generated from enum value: STATUS_WAITING = 7;
326
434
  */
327
- WAITING = 7
435
+ WAITING = 7,
436
+ /**
437
+ * Terminal state. The execution was canceled via
438
+ * CancelWorkflowExecution. Never retried automatically and not resumable.
439
+ * Must stay integer-aligned with the controlplane enum (the operator
440
+ * transform casts directly).
441
+ *
442
+ * @generated from enum value: STATUS_CANCELED = 8;
443
+ */
444
+ CANCELED = 8
328
445
  }
329
446
  //#endregion
@@ -478,6 +478,13 @@ export declare type GetWorkspacePlatformUserRequest = Message<"tailor.v1.GetWork
478
478
  * @generated from field: string workspace_id = 1;
479
479
  */
480
480
  workspaceId: string;
481
+ /**
482
+ * email identifies the member to read. Use GetWorkspaceRole to read the
483
+ * caller's own role.
484
+ *
485
+ * @generated from field: string email = 2;
486
+ */
487
+ email: string;
481
488
  };
482
489
  /**
483
490
  * Describes the message tailor.v1.GetWorkspacePlatformUserRequest.
@@ -1 +1 @@
1
- {"version":3,"file":"tailordb-ddl-DqInYupv.mjs","names":[],"sources":["../src/utils/field-column-type.ts","../src/utils/tailordb-ddl.ts"],"sourcesContent":["/** The Kysely column type a TailorDB field maps to, before array/null modifiers. */\nexport type FieldColumnType = \"string\" | \"number\" | \"boolean\" | \"Timestamp\";\n\n/**\n * Map a scalar TailorDB field type to the column type generated code uses for it.\n *\n * `date` resolves to `Timestamp` because the function runtime hands back a\n * `Date` for a date column, same as for datetime.\n *\n * `enum` and `nested` carry their own shape, so each generator resolves them\n * before reaching here; passing either is a caller bug rather than a `string`\n * column.\n * @param fieldType - TailorDB scalar field type name\n * @returns The column type for the field, defaulting to `string`\n * @throws If given `enum` or `nested`\n */\nexport function mapFieldTypeToColumnType(fieldType: string): FieldColumnType {\n switch (fieldType) {\n case \"uuid\":\n case \"string\":\n case \"decimal\":\n return \"string\";\n case \"integer\":\n case \"float\":\n return \"number\";\n case \"date\":\n case \"datetime\":\n return \"Timestamp\";\n case \"bool\":\n case \"boolean\":\n return \"boolean\";\n case \"enum\":\n case \"nested\":\n throw new Error(\n `Field type \"${fieldType}\" has no scalar column type; resolve it before mapping.`,\n );\n default:\n return \"string\";\n }\n}\n\n/** The select and write types a `ColumnType`-shaped alias expands to. */\nexport type ColumnTypeAliasExpansion = {\n /** Type the alias reads back as. */\n readonly select: string;\n /** Type the alias accepts on insert and update. */\n readonly write: string;\n};\n\n/**\n * Column types whose alias expands to a `ColumnType`, mapped to that expansion.\n *\n * Kysely only unwraps a `ColumnType` at the top level of a table property, so an\n * array of one of these stays wrapped in `ArrayColumnType<...>` rather than taking\n * a `[]` suffix, which would nest the `ColumnType` out of Kysely's reach. Where a\n * generator has to spell out the slots itself, it reads the expansion from here\n * rather than inlining the alias, which would nest just the same.\n *\n * Both type generators track alias usage per alias to decide which declarations to\n * emit, so adding an entry here also means teaching them to report the new alias.\n */\nexport const COLUMN_TYPE_ALIASES: ReadonlyMap<string, ColumnTypeAliasExpansion> = new Map<\n FieldColumnType,\n ColumnTypeAliasExpansion\n>([[\"Timestamp\", { select: \"Date\", write: \"Date | string\" }]]);\n","/**\n * PostgreSQL DDL derived from TailorDB table definitions, for creating the\n * tables a PGlite-backed test needs. The columns match the flat shape the\n * Kysely type generators emit, not TailorDB's storage layout.\n */\n\n/** The field shape the DDL generator reads; parsed and snapshot field configs are both assignable. */\nexport interface DDLFieldConfig {\n type: string;\n required?: boolean;\n array?: boolean;\n unique?: boolean;\n serial?: { start: number; maxValue?: number; format?: string };\n scale?: number;\n default?: unknown;\n optionalOnCreate?: boolean;\n hooks?: { create?: unknown; update?: unknown };\n fields?: Record<string, DDLFieldConfig>;\n}\n\n/** A table to emit DDL for. */\nexport interface DDLTableConfig {\n name: string;\n fields: Record<string, DDLFieldConfig>;\n indexes?: Record<string, { fields: string[]; unique?: boolean }>;\n}\n\nconst MAX_IDENTIFIER_BYTES = 63;\n// The platform rounds decimals to their scale (6 unless configured); numeric\n// needs a precision to carry a scale, and the maximum leaves it unconstrained.\nconst DECIMAL_PRECISION = 1000;\nconst DEFAULT_DECIMAL_SCALE = 6;\nconst utf8 = new TextEncoder();\n\n/**\n * Map a TailorDB field type to the PostgreSQL column type PGlite tests use for it.\n * @param fieldType - TailorDB field type name\n * @returns The PostgreSQL type name\n * @throws If the type is not a TailorDB field type\n */\nexport function mapFieldTypeToPostgresType(fieldType: string): string {\n switch (fieldType) {\n case \"uuid\":\n return \"uuid\";\n case \"string\":\n case \"enum\":\n return \"text\";\n case \"boolean\":\n case \"bool\":\n return \"boolean\";\n case \"integer\":\n return \"integer\";\n case \"float\":\n return \"double precision\";\n case \"decimal\":\n return \"numeric\";\n case \"date\":\n return \"date\";\n case \"datetime\":\n return \"timestamptz\";\n case \"time\":\n return \"time\";\n case \"nested\":\n return \"jsonb\";\n default:\n throw new Error(`Field type \"${fieldType}\" has no PostgreSQL column type.`);\n }\n}\n\nfunction identifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction fnv1aHex(value: string): string {\n let hash = 0x811c9dc5;\n for (const byte of utf8.encode(value)) {\n hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\nfunction derivedIdentifier(tableName: string, memberName: string, kind: \"seq\" | \"idx\"): string {\n const suffix = `_${fnv1aHex(JSON.stringify([tableName, memberName, kind]))}_${kind}`;\n let head = `${tableName}_${memberName}`;\n while (utf8.encode(head + suffix).length > MAX_IDENTIFIER_BYTES) head = head.slice(0, -1);\n return identifier(head + suffix);\n}\n\nfunction stringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction columnType(field: DDLFieldConfig): string {\n const base =\n field.type === \"decimal\"\n ? `numeric(${DECIMAL_PRECISION}, ${field.scale ?? DEFAULT_DECIMAL_SCALE})`\n : mapFieldTypeToPostgresType(field.type);\n return field.array && field.type !== \"nested\" ? `${base}[]` : base;\n}\n\nfunction scalarLiteral(value: unknown, field: DDLFieldConfig, label: string): string {\n const pgType = mapFieldTypeToPostgresType(field.type);\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`Default of field ${label} is an invalid Date.`);\n }\n return `${stringLiteral(value.toISOString())}::${pgType}`;\n }\n switch (typeof value) {\n case \"string\":\n return pgType === \"text\" ? stringLiteral(value) : `${stringLiteral(value)}::${pgType}`;\n case \"number\":\n if (!Number.isFinite(value)) {\n throw new Error(`Default of field ${label} is not a finite number.`);\n }\n return String(value);\n case \"boolean\":\n return value ? \"TRUE\" : \"FALSE\";\n default:\n throw new Error(`Default of field ${label} cannot be rendered as a SQL literal.`);\n }\n}\n\nconst CURRENT_TIME_EXPRESSIONS = new Map([\n [\"datetime\", \"now()\"],\n [\"date\", \"CURRENT_DATE\"],\n [\"time\", \"LOCALTIME\"],\n]);\n\nfunction defaultExpression(field: DDLFieldConfig, label: string): string {\n const value = field.default;\n const currentTime = CURRENT_TIME_EXPRESSIONS.get(field.type);\n if (value === \"now\" && currentTime !== undefined) {\n return currentTime;\n }\n if (field.array) {\n if (!Array.isArray(value)) {\n throw new Error(`Default of array field ${label} must be an array.`);\n }\n const pgType = columnType(field);\n if (value.length === 0) return `'{}'::${pgType}`;\n return `ARRAY[${value.map((v) => scalarLiteral(v, field, label)).join(\", \")}]::${pgType}`;\n }\n return scalarLiteral(value, field, label);\n}\n\ninterface SerialFormat {\n prefix: string;\n width: number;\n zeroPad: boolean;\n conversion: \"d\" | \"x\" | \"X\";\n suffix: string;\n}\n\n// printf-style with exactly one conversion specifier; octal has no Postgres\n// formatting function to stand in for it.\nfunction parseSerialFormat(format: string, label: string): SerialFormat {\n const match =\n /^(?<prefix>[^%]*)%(?<zero>0?)(?<width>\\d*)(?<conversion>[a-zA-Z])(?<suffix>[^%]*)$/.exec(\n format,\n );\n const groups = match?.groups;\n const conversion = groups?.conversion;\n if (!groups || (conversion !== \"d\" && conversion !== \"x\" && conversion !== \"X\")) {\n throw new Error(\n `Serial format \"${format}\" of field ${label} is not supported; use a single %d, %x, or %X specifier with an optional width (e.g. \"INV-%05d\").`,\n );\n }\n return {\n prefix: groups.prefix ?? \"\",\n zeroPad: groups.zero === \"0\",\n width: groups.width ? Number(groups.width) : 0,\n conversion,\n suffix: groups.suffix ?? \"\",\n };\n}\n\nfunction sequenceName(tableName: string, fieldName: string): string {\n return derivedIdentifier(tableName, fieldName, \"seq\");\n}\n\n// A sequence's minimum defaults to 1, which rejects a start of 0.\nfunction sequenceRange(serial: NonNullable<DDLFieldConfig[\"serial\"]>): string {\n const range = [`START WITH ${serial.start}`, `MINVALUE ${serial.start}`];\n if (serial.maxValue !== undefined) range.push(`MAXVALUE ${serial.maxValue}`);\n return range.join(\" \");\n}\n\nconst SERIAL_CONVERSIONS: Record<SerialFormat[\"conversion\"], (nextval: string) => string> = {\n d: (nextval) => nextval,\n x: (nextval) => `to_hex(${nextval})`,\n X: (nextval) => `upper(to_hex(${nextval}))`,\n};\n\nfunction serialStringDefault(sequence: string, format: string | undefined, label: string): string {\n const nextval = `nextval(${stringLiteral(sequence)})`;\n if (format === undefined) return `(${nextval}::text)`;\n const { prefix, width, zeroPad, conversion, suffix } = parseSerialFormat(format, label);\n const number = SERIAL_CONVERSIONS[conversion](nextval);\n let value = conversion === \"d\" ? `${number}::text` : number;\n if (width > 0) {\n value = `format('%${width}s', ${number})`;\n if (zeroPad) value = `translate(${value}, ' ', '0')`;\n }\n const parts = [\n ...(prefix ? [stringLiteral(prefix)] : []),\n value,\n ...(suffix ? [stringLiteral(suffix)] : []),\n ];\n return `(${parts.join(\" || \")})`;\n}\n\nfunction columnDefinition(tableName: string, fieldName: string, field: DDLFieldConfig): string {\n const column = identifier(fieldName);\n const label = `${identifier(tableName)}.${column}`;\n const parts = [column, columnType(field)];\n\n if (field.serial) {\n if (field.type === \"integer\") {\n parts.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(field.serial)})`);\n if (field.unique) parts.push(\"UNIQUE\");\n return parts.join(\" \");\n }\n if (field.required) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n parts.push(\n `DEFAULT ${serialStringDefault(sequenceName(tableName, fieldName), field.serial.format, label)}`,\n );\n return parts.join(\" \");\n }\n\n const hasDefault = field.default !== undefined;\n const filledOnCreate = field.hooks?.create !== undefined || field.optionalOnCreate === true;\n if (field.required && (hasDefault || !filledOnCreate)) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n if (hasDefault) parts.push(`DEFAULT ${defaultExpression(field, label)}`);\n return parts.join(\" \");\n}\n\n/**\n * DDL statements that create one table: any sequences its string serial\n * fields draw from, the table, the sequences' ownership of their columns,\n * then its unique indexes. Every statement is `IF NOT EXISTS` or otherwise\n * idempotent, so re-applying the script on a database that already has the\n * table is a no-op. Owning a sequence makes `DROP TABLE` drop it and\n * `TRUNCATE ... RESTART IDENTITY` reset it to the configured start. Index\n * names end in `_idx` so they cannot take the `<table>_<column>_key` name\n * Postgres gives a UNIQUE column, which `IF NOT EXISTS` would otherwise\n * silently skip.\n * @param table - Table name, fields, and indexes\n * @returns Statements in execution order, without trailing semicolons\n * @throws If a field type, default, or serial format cannot be expressed\n */\nexport function generateTableDDL(table: DDLTableConfig): string[] {\n const tableIdentifier = identifier(table.name);\n const sequences: string[] = [];\n const ownerships: string[] = [];\n const columns = [` \"id\" uuid PRIMARY KEY DEFAULT gen_random_uuid()`];\n\n for (const [fieldName, field] of Object.entries(table.fields)) {\n if (fieldName === \"id\") continue;\n if (field.serial && field.type !== \"integer\") {\n const sequence = sequenceName(table.name, fieldName);\n sequences.push(`CREATE SEQUENCE IF NOT EXISTS ${sequence} ${sequenceRange(field.serial)}`);\n ownerships.push(\n `ALTER SEQUENCE ${sequence} OWNED BY ${tableIdentifier}.${identifier(fieldName)}`,\n );\n }\n columns.push(` ${columnDefinition(table.name, fieldName, field)}`);\n }\n\n const indexes = Object.entries(table.indexes ?? {})\n .filter(([, index]) => index.unique)\n .map(\n ([name, index]) =>\n `CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(table.name, name, \"idx\")} ON ${tableIdentifier} (${index.fields.map(identifier).join(\", \")})`,\n );\n\n return [\n ...sequences,\n `CREATE TABLE IF NOT EXISTS ${tableIdentifier} (\\n${columns.join(\",\\n\")}\\n)`,\n ...ownerships,\n ...indexes,\n ];\n}\n\n/**\n * A single SQL script creating every given table, for `pglite.exec()`.\n * @param tables - Tables in the order to create them\n * @returns The script, empty when there are no tables\n */\nexport function generateSchemaDDL(tables: readonly DDLTableConfig[]): string {\n return tables\n .map((table) =>\n generateTableDDL(table)\n .map((statement) => `${statement};`)\n .join(\"\\n\"),\n )\n .join(\"\\n\\n\");\n}\n\n/** One namespace's tables, as the schema module groups them. */\nexport interface PgliteSchemaNamespace {\n namespace: string;\n tables: readonly DDLTableConfig[];\n}\n\n/** Options for {@link generatePgliteSchemaModule}. */\nexport interface PgliteSchemaModuleOptions {\n /** Named in the generated header as the producer users must not edit around. */\n generatedBy: string;\n}\n\n// A template literal keeps line feeds but folds a carriage return into one.\nfunction templateLiteral(value: string): string {\n const escaped = value\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(\"`\", \"\\\\`\")\n .replaceAll(\"${\", \"\\\\${\")\n .replaceAll(\"\\r\", \"\\\\r\");\n return `\\`${escaped}\\``;\n}\n\n/**\n * Render the module that exports each namespace's `CREATE TABLE` script for\n * `pglite.exec()`.\n * @param namespaces - Namespaces with the tables to create\n * @param options - Header wording\n * @returns TypeScript source of the schema module\n */\nexport function generatePgliteSchemaModule(\n namespaces: readonly PgliteSchemaNamespace[],\n options: PgliteSchemaModuleOptions,\n): string {\n const entries = namespaces.map(\n ({ namespace, tables }) =>\n ` ${JSON.stringify(namespace)}: ${templateLiteral(generateSchemaDDL(tables))},`,\n );\n return [\n \"/**\",\n \" * Auto-generated PGlite schema for TailorDB tables.\",\n \" * Create a namespace's tables in a test with `pglite.exec(pgliteSchema[namespace])`.\",\n \" *\",\n ` * DO NOT EDIT - This file is auto-generated by ${options.generatedBy}.`,\n \" */\",\n \"\",\n \"export const pgliteSchema = {\",\n ...entries,\n \"} as const;\",\n \"\",\n ].join(\"\\n\");\n}\n"],"mappings":"AAgBA,SAAgB,yBAAyB,EAAoC,CAC3E,OAAQ,EAAR,CACE,IAAK,OACL,IAAK,SACL,IAAK,UACH,MAAO,SACT,IAAK,UACL,IAAK,QACH,MAAO,SACT,IAAK,OACL,IAAK,WACH,MAAO,YACT,IAAK,OACL,IAAK,UACH,MAAO,UACT,IAAK,OACL,IAAK,SACH,MAAU,MACR,eAAe,EAAU,wDAC3B,EACF,QACE,MAAO,QACX,CACF,CAsBA,MAAa,kBAAqE,IAAI,IAGpF,CAAC,CAAC,YAAa,CAAE,OAAQ,OAAQ,MAAO,eAAgB,CAAC,CAAC,CAAC,EChCvD,EAAO,IAAI,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AM,SAAW,CAAC,CAAC,CAAC,CAChD,QAAQ,EAAG,KAAW,EAAM,MAAM,CAAC,CACnC,KACE,CAAC,EAAM,KACN,qCAAqC,kBAAkB,EAAM,KAAM,EAAM,KAAK,EAAE,MAAM,EAAgB,IAAI,EAAM,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE,EACtJ,EAEF,MAAO,CACL,GAAG,EACH,8BAA8B,EAAgB,MAAM,EAAQ,KAAK;CAAK,EAAE,KACxE,GAAG,EACH,GAAG,CACL,CACF,CAOA,SAAgB,kBAAkB,EAA2C,CAC3E,OAAO,EACJ,IAAK,GACJ,iBAAiB,CAAK,CAAC,CACpB,IAAK,GAAc,GAAG,EAAU,EAAE,CAAC,CACnC,KAAK;CAAI,CACd,CAAC,CACA,KAAK;;CAAM,CAChB,CAeA,SAAS,gBAAgB,EAAuB,CAM9C,MAAO,KALS,EACb,WAAW,KAAM,MAAM,CAAC,CACxB,WAAW,IAAK,KAAK,CAAC,CACtB,WAAW,KAAM,MAAM,CAAC,CACxB,WAAW,KAAM,KACF,EAAE,GACtB,CASA,SAAgB,2BACd,EACA,EACQ,CACR,IAAM,EAAU,EAAW,KACxB,CAAE,YAAW,YACZ,KAAK,KAAK,UAAU,CAAS,EAAE,IAAI,gBAAgB,kBAAkB,CAAM,CAAC,EAAE,EAClF,EACA,MAAO,CACL,MACA,uDACA,wFACA,KACA,mDAAmD,EAAQ,YAAY,GACvE,MACA,GACA,gCACA,GAAG,EACH,cACA,EACF,CAAC,CAAC,KAAK;CAAI,CACb"}
1
+ {"version":3,"file":"tailordb-ddl-DqInYupv.mjs","names":["fieldType","COLUMN_TYPE_ALIASES","utf8","name","hash","byte","value","suffix","tableName","memberName","kind","head","base","field","pgType","label","CURRENT_TIME_EXPRESSIONS","currentTime","v","groups","format","conversion","fieldName","range","serial","SERIAL_CONVERSIONS","nextval","sequence","number","width","zeroPad","prefix","column","parts","hasDefault","filledOnCreate","tableIdentifier","table","sequences","ownerships","columns","indexes","index","tables","statement","entries","namespaces","namespace","options"],"sources":["../src/utils/field-column-type.ts","../src/utils/tailordb-ddl.ts"],"sourcesContent":["/** The Kysely column type a TailorDB field maps to, before array/null modifiers. */\nexport type FieldColumnType = \"string\" | \"number\" | \"boolean\" | \"Timestamp\";\n\n/**\n * Map a scalar TailorDB field type to the column type generated code uses for it.\n *\n * `date` resolves to `Timestamp` because the function runtime hands back a\n * `Date` for a date column, same as for datetime.\n *\n * `enum` and `nested` carry their own shape, so each generator resolves them\n * before reaching here; passing either is a caller bug rather than a `string`\n * column.\n * @param fieldType - TailorDB scalar field type name\n * @returns The column type for the field, defaulting to `string`\n * @throws If given `enum` or `nested`\n */\nexport function mapFieldTypeToColumnType(fieldType: string): FieldColumnType {\n switch (fieldType) {\n case \"uuid\":\n case \"string\":\n case \"decimal\":\n return \"string\";\n case \"integer\":\n case \"float\":\n return \"number\";\n case \"date\":\n case \"datetime\":\n return \"Timestamp\";\n case \"bool\":\n case \"boolean\":\n return \"boolean\";\n case \"enum\":\n case \"nested\":\n throw new Error(\n `Field type \"${fieldType}\" has no scalar column type; resolve it before mapping.`,\n );\n default:\n return \"string\";\n }\n}\n\n/** The select and write types a `ColumnType`-shaped alias expands to. */\nexport type ColumnTypeAliasExpansion = {\n /** Type the alias reads back as. */\n readonly select: string;\n /** Type the alias accepts on insert and update. */\n readonly write: string;\n};\n\n/**\n * Column types whose alias expands to a `ColumnType`, mapped to that expansion.\n *\n * Kysely only unwraps a `ColumnType` at the top level of a table property, so an\n * array of one of these stays wrapped in `ArrayColumnType<...>` rather than taking\n * a `[]` suffix, which would nest the `ColumnType` out of Kysely's reach. Where a\n * generator has to spell out the slots itself, it reads the expansion from here\n * rather than inlining the alias, which would nest just the same.\n *\n * Both type generators track alias usage per alias to decide which declarations to\n * emit, so adding an entry here also means teaching them to report the new alias.\n */\nexport const COLUMN_TYPE_ALIASES: ReadonlyMap<string, ColumnTypeAliasExpansion> = new Map<\n FieldColumnType,\n ColumnTypeAliasExpansion\n>([[\"Timestamp\", { select: \"Date\", write: \"Date | string\" }]]);\n","/**\n * PostgreSQL DDL derived from TailorDB table definitions, for creating the\n * tables a PGlite-backed test needs. The columns match the flat shape the\n * Kysely type generators emit, not TailorDB's storage layout.\n */\n\n/** The field shape the DDL generator reads; parsed and snapshot field configs are both assignable. */\nexport interface DDLFieldConfig {\n type: string;\n required?: boolean;\n array?: boolean;\n unique?: boolean;\n serial?: { start: number; maxValue?: number; format?: string };\n scale?: number;\n default?: unknown;\n optionalOnCreate?: boolean;\n hooks?: { create?: unknown; update?: unknown };\n fields?: Record<string, DDLFieldConfig>;\n}\n\n/** A table to emit DDL for. */\nexport interface DDLTableConfig {\n name: string;\n fields: Record<string, DDLFieldConfig>;\n indexes?: Record<string, { fields: string[]; unique?: boolean }>;\n}\n\nconst MAX_IDENTIFIER_BYTES = 63;\n// The platform rounds decimals to their scale (6 unless configured); numeric\n// needs a precision to carry a scale, and the maximum leaves it unconstrained.\nconst DECIMAL_PRECISION = 1000;\nconst DEFAULT_DECIMAL_SCALE = 6;\nconst utf8 = new TextEncoder();\n\n/**\n * Map a TailorDB field type to the PostgreSQL column type PGlite tests use for it.\n * @param fieldType - TailorDB field type name\n * @returns The PostgreSQL type name\n * @throws If the type is not a TailorDB field type\n */\nexport function mapFieldTypeToPostgresType(fieldType: string): string {\n switch (fieldType) {\n case \"uuid\":\n return \"uuid\";\n case \"string\":\n case \"enum\":\n return \"text\";\n case \"boolean\":\n case \"bool\":\n return \"boolean\";\n case \"integer\":\n return \"integer\";\n case \"float\":\n return \"double precision\";\n case \"decimal\":\n return \"numeric\";\n case \"date\":\n return \"date\";\n case \"datetime\":\n return \"timestamptz\";\n case \"time\":\n return \"time\";\n case \"nested\":\n return \"jsonb\";\n default:\n throw new Error(`Field type \"${fieldType}\" has no PostgreSQL column type.`);\n }\n}\n\nfunction identifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction fnv1aHex(value: string): string {\n let hash = 0x811c9dc5;\n for (const byte of utf8.encode(value)) {\n hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\nfunction derivedIdentifier(tableName: string, memberName: string, kind: \"seq\" | \"idx\"): string {\n const suffix = `_${fnv1aHex(JSON.stringify([tableName, memberName, kind]))}_${kind}`;\n let head = `${tableName}_${memberName}`;\n while (utf8.encode(head + suffix).length > MAX_IDENTIFIER_BYTES) head = head.slice(0, -1);\n return identifier(head + suffix);\n}\n\nfunction stringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction columnType(field: DDLFieldConfig): string {\n const base =\n field.type === \"decimal\"\n ? `numeric(${DECIMAL_PRECISION}, ${field.scale ?? DEFAULT_DECIMAL_SCALE})`\n : mapFieldTypeToPostgresType(field.type);\n return field.array && field.type !== \"nested\" ? `${base}[]` : base;\n}\n\nfunction scalarLiteral(value: unknown, field: DDLFieldConfig, label: string): string {\n const pgType = mapFieldTypeToPostgresType(field.type);\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`Default of field ${label} is an invalid Date.`);\n }\n return `${stringLiteral(value.toISOString())}::${pgType}`;\n }\n switch (typeof value) {\n case \"string\":\n return pgType === \"text\" ? stringLiteral(value) : `${stringLiteral(value)}::${pgType}`;\n case \"number\":\n if (!Number.isFinite(value)) {\n throw new Error(`Default of field ${label} is not a finite number.`);\n }\n return String(value);\n case \"boolean\":\n return value ? \"TRUE\" : \"FALSE\";\n default:\n throw new Error(`Default of field ${label} cannot be rendered as a SQL literal.`);\n }\n}\n\nconst CURRENT_TIME_EXPRESSIONS = new Map([\n [\"datetime\", \"now()\"],\n [\"date\", \"CURRENT_DATE\"],\n [\"time\", \"LOCALTIME\"],\n]);\n\nfunction defaultExpression(field: DDLFieldConfig, label: string): string {\n const value = field.default;\n const currentTime = CURRENT_TIME_EXPRESSIONS.get(field.type);\n if (value === \"now\" && currentTime !== undefined) {\n return currentTime;\n }\n if (field.array) {\n if (!Array.isArray(value)) {\n throw new Error(`Default of array field ${label} must be an array.`);\n }\n const pgType = columnType(field);\n if (value.length === 0) return `'{}'::${pgType}`;\n return `ARRAY[${value.map((v) => scalarLiteral(v, field, label)).join(\", \")}]::${pgType}`;\n }\n return scalarLiteral(value, field, label);\n}\n\ninterface SerialFormat {\n prefix: string;\n width: number;\n zeroPad: boolean;\n conversion: \"d\" | \"x\" | \"X\";\n suffix: string;\n}\n\n// printf-style with exactly one conversion specifier; octal has no Postgres\n// formatting function to stand in for it.\nfunction parseSerialFormat(format: string, label: string): SerialFormat {\n const match =\n /^(?<prefix>[^%]*)%(?<zero>0?)(?<width>\\d*)(?<conversion>[a-zA-Z])(?<suffix>[^%]*)$/.exec(\n format,\n );\n const groups = match?.groups;\n const conversion = groups?.conversion;\n if (!groups || (conversion !== \"d\" && conversion !== \"x\" && conversion !== \"X\")) {\n throw new Error(\n `Serial format \"${format}\" of field ${label} is not supported; use a single %d, %x, or %X specifier with an optional width (e.g. \"INV-%05d\").`,\n );\n }\n return {\n prefix: groups.prefix ?? \"\",\n zeroPad: groups.zero === \"0\",\n width: groups.width ? Number(groups.width) : 0,\n conversion,\n suffix: groups.suffix ?? \"\",\n };\n}\n\nfunction sequenceName(tableName: string, fieldName: string): string {\n return derivedIdentifier(tableName, fieldName, \"seq\");\n}\n\n// A sequence's minimum defaults to 1, which rejects a start of 0.\nfunction sequenceRange(serial: NonNullable<DDLFieldConfig[\"serial\"]>): string {\n const range = [`START WITH ${serial.start}`, `MINVALUE ${serial.start}`];\n if (serial.maxValue !== undefined) range.push(`MAXVALUE ${serial.maxValue}`);\n return range.join(\" \");\n}\n\nconst SERIAL_CONVERSIONS: Record<SerialFormat[\"conversion\"], (nextval: string) => string> = {\n d: (nextval) => nextval,\n x: (nextval) => `to_hex(${nextval})`,\n X: (nextval) => `upper(to_hex(${nextval}))`,\n};\n\nfunction serialStringDefault(sequence: string, format: string | undefined, label: string): string {\n const nextval = `nextval(${stringLiteral(sequence)})`;\n if (format === undefined) return `(${nextval}::text)`;\n const { prefix, width, zeroPad, conversion, suffix } = parseSerialFormat(format, label);\n const number = SERIAL_CONVERSIONS[conversion](nextval);\n let value = conversion === \"d\" ? `${number}::text` : number;\n if (width > 0) {\n value = `format('%${width}s', ${number})`;\n if (zeroPad) value = `translate(${value}, ' ', '0')`;\n }\n const parts = [\n ...(prefix ? [stringLiteral(prefix)] : []),\n value,\n ...(suffix ? [stringLiteral(suffix)] : []),\n ];\n return `(${parts.join(\" || \")})`;\n}\n\nfunction columnDefinition(tableName: string, fieldName: string, field: DDLFieldConfig): string {\n const column = identifier(fieldName);\n const label = `${identifier(tableName)}.${column}`;\n const parts = [column, columnType(field)];\n\n if (field.serial) {\n if (field.type === \"integer\") {\n parts.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(field.serial)})`);\n if (field.unique) parts.push(\"UNIQUE\");\n return parts.join(\" \");\n }\n if (field.required) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n parts.push(\n `DEFAULT ${serialStringDefault(sequenceName(tableName, fieldName), field.serial.format, label)}`,\n );\n return parts.join(\" \");\n }\n\n const hasDefault = field.default !== undefined;\n const filledOnCreate = field.hooks?.create !== undefined || field.optionalOnCreate === true;\n if (field.required && (hasDefault || !filledOnCreate)) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n if (hasDefault) parts.push(`DEFAULT ${defaultExpression(field, label)}`);\n return parts.join(\" \");\n}\n\n/**\n * DDL statements that create one table: any sequences its string serial\n * fields draw from, the table, the sequences' ownership of their columns,\n * then its unique indexes. Every statement is `IF NOT EXISTS` or otherwise\n * idempotent, so re-applying the script on a database that already has the\n * table is a no-op. Owning a sequence makes `DROP TABLE` drop it and\n * `TRUNCATE ... RESTART IDENTITY` reset it to the configured start. Index\n * names end in `_idx` so they cannot take the `<table>_<column>_key` name\n * Postgres gives a UNIQUE column, which `IF NOT EXISTS` would otherwise\n * silently skip.\n * @param table - Table name, fields, and indexes\n * @returns Statements in execution order, without trailing semicolons\n * @throws If a field type, default, or serial format cannot be expressed\n */\nexport function generateTableDDL(table: DDLTableConfig): string[] {\n const tableIdentifier = identifier(table.name);\n const sequences: string[] = [];\n const ownerships: string[] = [];\n const columns = [` \"id\" uuid PRIMARY KEY DEFAULT gen_random_uuid()`];\n\n for (const [fieldName, field] of Object.entries(table.fields)) {\n if (fieldName === \"id\") continue;\n if (field.serial && field.type !== \"integer\") {\n const sequence = sequenceName(table.name, fieldName);\n sequences.push(`CREATE SEQUENCE IF NOT EXISTS ${sequence} ${sequenceRange(field.serial)}`);\n ownerships.push(\n `ALTER SEQUENCE ${sequence} OWNED BY ${tableIdentifier}.${identifier(fieldName)}`,\n );\n }\n columns.push(` ${columnDefinition(table.name, fieldName, field)}`);\n }\n\n const indexes = Object.entries(table.indexes ?? {})\n .filter(([, index]) => index.unique)\n .map(\n ([name, index]) =>\n `CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(table.name, name, \"idx\")} ON ${tableIdentifier} (${index.fields.map(identifier).join(\", \")})`,\n );\n\n return [\n ...sequences,\n `CREATE TABLE IF NOT EXISTS ${tableIdentifier} (\\n${columns.join(\",\\n\")}\\n)`,\n ...ownerships,\n ...indexes,\n ];\n}\n\n/**\n * A single SQL script creating every given table, for `pglite.exec()`.\n * @param tables - Tables in the order to create them\n * @returns The script, empty when there are no tables\n */\nexport function generateSchemaDDL(tables: readonly DDLTableConfig[]): string {\n return tables\n .map((table) =>\n generateTableDDL(table)\n .map((statement) => `${statement};`)\n .join(\"\\n\"),\n )\n .join(\"\\n\\n\");\n}\n\n/** One namespace's tables, as the schema module groups them. */\nexport interface PgliteSchemaNamespace {\n namespace: string;\n tables: readonly DDLTableConfig[];\n}\n\n/** Options for {@link generatePgliteSchemaModule}. */\nexport interface PgliteSchemaModuleOptions {\n /** Named in the generated header as the producer users must not edit around. */\n generatedBy: string;\n}\n\n// A template literal keeps line feeds but folds a carriage return into one.\nfunction templateLiteral(value: string): string {\n const escaped = value\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(\"`\", \"\\\\`\")\n .replaceAll(\"${\", \"\\\\${\")\n .replaceAll(\"\\r\", \"\\\\r\");\n return `\\`${escaped}\\``;\n}\n\n/**\n * Render the module that exports each namespace's `CREATE TABLE` script for\n * `pglite.exec()`.\n * @param namespaces - Namespaces with the tables to create\n * @param options - Header wording\n * @returns TypeScript source of the schema module\n */\nexport function generatePgliteSchemaModule(\n namespaces: readonly PgliteSchemaNamespace[],\n options: PgliteSchemaModuleOptions,\n): string {\n const entries = namespaces.map(\n ({ namespace, tables }) =>\n ` ${JSON.stringify(namespace)}: ${templateLiteral(generateSchemaDDL(tables))},`,\n );\n return [\n \"/**\",\n \" * Auto-generated PGlite schema for TailorDB tables.\",\n \" * Create a namespace's tables in a test with `pglite.exec(pgliteSchema[namespace])`.\",\n \" *\",\n ` * DO NOT EDIT - This file is auto-generated by ${options.generatedBy}.`,\n \" */\",\n \"\",\n \"export const pgliteSchema = {\",\n ...entries,\n \"} as const;\",\n \"\",\n ].join(\"\\n\");\n}\n"],"mappings":"AAgBA,SAAgB,yBAAyB,EAAoC,CAC3E,OAAQA,EAAR,CACE,IAAK,OACL,IAAK,SACL,IAAK,UACH,MAAO,SACT,IAAK,UACL,IAAK,QACH,MAAO,SACT,IAAK,OACL,IAAK,WACH,MAAO,YACT,IAAK,OACL,IAAK,UACH,MAAO,UACT,IAAK,OACL,IAAK,SACH,MAAU,MACR,eAAeA,EAAU,wDAC3B,EACF,QACE,MAAO,QACX,CACF,CAsBA,MAAaC,kBAAqE,IAAI,IAGpF,CAAC,CAAC,YAAa,CAAE,OAAQ,OAAQ,MAAO,eAAgB,CAAC,CAAC,CAAC,EChCvDC,EAAO,IAAI,YAQjB,SAAgB,2BAA2B,EAA2B,CACpE,OAAQF,EAAR,CACE,IAAK,OACH,MAAO,OACT,IAAK,SACL,IAAK,OACH,MAAO,OACT,IAAK,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AWd,CAAS,GAChF,CACF,CACAkB,EAAQ,KAAK,KAAK,iBAAiBH,EAAM,KAAMf,EAAWT,CAAK,GAAG,CADlE,CAIF,IAAM4B,EAAU,OAAO,QAAQJ,EAAM,SAAW,CAAC,CAAC,CAAC,CAChD,QAAQ,EAAGK,KAAWA,EAAM,MAAM,CAAC,CACnC,KACE,CAACvC,EAAMuC,KACN,qCAAqC,kBAAkBL,EAAM,KAAMlC,EAAM,KAAK,EAAE,MAAMiC,EAAgB,IAAIM,EAAM,OAAO,IAAI,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE,EACtJ,EAEF,MAAO,CACL,GAAGJ,EACH,8BAA8BF,EAAgB,MAAMI,EAAQ,KAAK;CAAK,EAAE,KACxE,GAAGD,EACH,GAAGE,CACL,CACF,CAOA,SAAgB,kBAAkB,EAA2C,CAC3E,OAAOE,EACJ,IAAK,GACJ,iBAAiBN,CAAK,CAAC,CACpB,IAAK,GAAc,GAAGO,EAAU,EAAE,CAAC,CACnC,KAAK;CAAI,CACd,CAAC,CACA,KAAK;;CAAM,CAChB,CAeA,SAAS,gBAAgB,EAAuB,CAM9C,MAAO,KALStC,EACb,WAAW,KAAM,MAAM,CAAC,CACxB,WAAW,IAAK,KAAK,CAAC,CACtB,WAAW,KAAM,MAAM,CAAC,CACxB,WAAW,KAAM,KACF,EAAE,GACtB,CASA,SAAgB,2BACd,EACA,EACQ,CACR,IAAMuC,EAAUC,EAAW,KACxB,CAAE,YAAW,YACZ,KAAK,KAAK,UAAUC,CAAS,EAAE,IAAI,gBAAgB,kBAAkBJ,CAAM,CAAC,EAAE,EAClF,EACA,MAAO,CACL,MACA,uDACA,wFACA,KACA,mDAAmDK,EAAQ,YAAY,GACvE,MACA,GACA,gCACA,GAAGH,EACH,cACA,EACF,CAAC,CAAC,KAAK;CAAI,CACb"}
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry-Bklv9kQY.mjs","names":[],"sources":["../src/cli/telemetry/config.ts","../src/cli/telemetry/index.ts"],"sourcesContent":["/**\n * Telemetry configuration parsed from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n */\nexport interface TelemetryConfig {\n readonly enabled: boolean;\n readonly endpoint: string;\n}\n\n/**\n * Parse telemetry configuration from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * @returns Telemetry configuration\n */\nexport function parseTelemetryConfig(): TelemetryConfig {\n const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? \"\";\n const enabled = endpoint.length > 0;\n\n return {\n enabled,\n endpoint,\n };\n}\n","import { trace, SpanStatusCode, type Span } from \"@opentelemetry/api\";\nimport { parseTelemetryConfig, type TelemetryConfig } from \"./config\";\n\nlet _config: TelemetryConfig | undefined;\nlet _initialized = false;\nlet _provider: { register: () => void; shutdown: () => Promise<void> } | undefined;\n\n/**\n * Check whether telemetry is currently enabled.\n * @returns true if telemetry has been initialized and is enabled\n */\nexport function isTelemetryEnabled(): boolean {\n return _config?.enabled ?? false;\n}\n\n/**\n * Initialize telemetry if OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * When disabled, this is a no-op with zero overhead beyond reading env vars.\n * @returns Promise that resolves when initialization completes\n */\nexport async function initTelemetry(): Promise<void> {\n if (_initialized) return;\n _initialized = true;\n\n _config = parseTelemetryConfig();\n if (!_config.enabled) return;\n\n // Dynamic imports - only loaded when tracing is enabled\n const [\n { NodeTracerProvider, BatchSpanProcessor },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION },\n { readPackageJson },\n ] = await Promise.all([\n import(\"@opentelemetry/sdk-trace-node\"),\n import(\"@opentelemetry/exporter-trace-otlp-proto\"),\n import(\"@opentelemetry/resources\"),\n import(\"@opentelemetry/semantic-conventions\"),\n import(\"#/cli/shared/package-json\"),\n ]);\n\n const packageJson = await readPackageJson();\n const version = packageJson.version ?? \"unknown\";\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: \"tailor\",\n [ATTR_SERVICE_VERSION]: version,\n });\n\n const exporter = new OTLPTraceExporter({\n url: `${_config.endpoint}/v1/traces`,\n });\n\n _provider = new NodeTracerProvider({\n resource,\n spanProcessors: [new BatchSpanProcessor(exporter)],\n });\n\n _provider.register();\n}\n\n/**\n * Shutdown the telemetry provider, flushing all pending spans.\n * Must be called before process exit to ensure traces are exported.\n * @returns Promise that resolves when shutdown completes\n */\nexport async function shutdownTelemetry(): Promise<void> {\n if (!_provider) return;\n await _provider.shutdown();\n}\n\n/**\n * Execute a function within a new span. Records exceptions and sets span status.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @param name - Span name\n * @param fn - Function to execute within the span\n * @returns Result of fn\n */\nexport async function withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T> {\n const tracer = trace.getTracer(\"tailor\");\n\n return tracer.startActiveSpan(name, async (span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n}\n"],"mappings":"+DAcA,SAAgB,sBAAwC,CACtD,IAAM,EAAW,QAAQ,IAAI,6BAA+B,GAG5D,MAAO,CACL,QAHc,EAAS,OAAS,EAIhC,UACF,CACF,CCnBA,IAAI,EACA,EAAe,GACf,EAeJ,eAAsB,eAA+B,CAKnD,GAJI,IACJ,EAAe,GAEf,EAAU,qBAAqB,EAC3B,CAAC,EAAQ,SAAS,OAGtB,GAAM,CACJ,CAAE,qBAAoB,sBACtB,CAAE,qBACF,CAAE,0BACF,CAAE,oBAAmB,wBACrB,CAAE,oBACA,MAAM,QAAQ,IAAI,CACpB,OAAO,iCACP,OAAO,4CACP,OAAO,4BACP,OAAO,uCACP,OAAO,8BACT,CAAC,EAGK,GAAU,MADU,EAAgB,EAAA,CACd,SAAW,UAWvC,EAAY,IAAI,EAAmB,CACjC,SAVe,EAAuB,EACrC,GAAoB,UACpB,GAAuB,CAC1B,CAOS,EACP,eAAgB,CAAC,IAAI,EAAmB,IANrB,EAAkB,CACrC,IAAK,GAAG,EAAQ,SAAS,WAC3B,CAIiD,CAAC,CAAC,CACnD,CAAC,EAED,EAAU,SAAS,CACrB,CAOA,eAAsB,mBAAmC,CAClD,GACL,MAAM,EAAU,SAAS,CAC3B,CAUA,eAAsB,SAAY,EAAc,EAA4C,CAG1F,OAFe,EAAM,UAAU,QAEnB,CAAC,CAAC,gBAAgB,EAAM,KAAO,IAAS,CAClD,GAAI,CACF,IAAM,EAAS,MAAM,EAAG,CAAI,EAE5B,OADA,EAAK,UAAU,CAAE,KAAM,EAAe,EAAG,CAAC,EACnC,CACT,OAAS,EAAO,CAKd,MAJA,EAAK,UAAU,CAAE,KAAM,EAAe,KAAM,CAAC,EACzC,aAAiB,OACnB,EAAK,gBAAgB,CAAK,EAEtB,CACR,QAAU,CACR,EAAK,IAAI,CACX,CACF,CAAC,CACH"}
1
+ {"version":3,"file":"telemetry-Bklv9kQY.mjs","names":["endpoint","_config","_initialized","_provider","version","readPackageJson","NodeTracerProvider","resourceFromAttributes","ATTR_SERVICE_NAME","ATTR_SERVICE_VERSION","BatchSpanProcessor","OTLPTraceExporter","trace","name","result","fn","span","SpanStatusCode","error"],"sources":["../src/cli/telemetry/config.ts","../src/cli/telemetry/index.ts"],"sourcesContent":["/**\n * Telemetry configuration parsed from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n */\nexport interface TelemetryConfig {\n readonly enabled: boolean;\n readonly endpoint: string;\n}\n\n/**\n * Parse telemetry configuration from standard OpenTelemetry environment variables.\n * Tracing is enabled when OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * @returns Telemetry configuration\n */\nexport function parseTelemetryConfig(): TelemetryConfig {\n const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? \"\";\n const enabled = endpoint.length > 0;\n\n return {\n enabled,\n endpoint,\n };\n}\n","import { trace, SpanStatusCode, type Span } from \"@opentelemetry/api\";\nimport { parseTelemetryConfig, type TelemetryConfig } from \"./config\";\n\nlet _config: TelemetryConfig | undefined;\nlet _initialized = false;\nlet _provider: { register: () => void; shutdown: () => Promise<void> } | undefined;\n\n/**\n * Check whether telemetry is currently enabled.\n * @returns true if telemetry has been initialized and is enabled\n */\nexport function isTelemetryEnabled(): boolean {\n return _config?.enabled ?? false;\n}\n\n/**\n * Initialize telemetry if OTEL_EXPORTER_OTLP_ENDPOINT is set.\n * When disabled, this is a no-op with zero overhead beyond reading env vars.\n * @returns Promise that resolves when initialization completes\n */\nexport async function initTelemetry(): Promise<void> {\n if (_initialized) return;\n _initialized = true;\n\n _config = parseTelemetryConfig();\n if (!_config.enabled) return;\n\n // Dynamic imports - only loaded when tracing is enabled\n const [\n { NodeTracerProvider, BatchSpanProcessor },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION },\n { readPackageJson },\n ] = await Promise.all([\n import(\"@opentelemetry/sdk-trace-node\"),\n import(\"@opentelemetry/exporter-trace-otlp-proto\"),\n import(\"@opentelemetry/resources\"),\n import(\"@opentelemetry/semantic-conventions\"),\n import(\"#/cli/shared/package-json\"),\n ]);\n\n const packageJson = await readPackageJson();\n const version = packageJson.version ?? \"unknown\";\n\n const resource = resourceFromAttributes({\n [ATTR_SERVICE_NAME]: \"tailor\",\n [ATTR_SERVICE_VERSION]: version,\n });\n\n const exporter = new OTLPTraceExporter({\n url: `${_config.endpoint}/v1/traces`,\n });\n\n _provider = new NodeTracerProvider({\n resource,\n spanProcessors: [new BatchSpanProcessor(exporter)],\n });\n\n _provider.register();\n}\n\n/**\n * Shutdown the telemetry provider, flushing all pending spans.\n * Must be called before process exit to ensure traces are exported.\n * @returns Promise that resolves when shutdown completes\n */\nexport async function shutdownTelemetry(): Promise<void> {\n if (!_provider) return;\n await _provider.shutdown();\n}\n\n/**\n * Execute a function within a new span. Records exceptions and sets span status.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @param name - Span name\n * @param fn - Function to execute within the span\n * @returns Result of fn\n */\nexport async function withSpan<T>(name: string, fn: (span: Span) => Promise<T>): Promise<T> {\n const tracer = trace.getTracer(\"tailor\");\n\n return tracer.startActiveSpan(name, async (span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n}\n"],"mappings":"+DAcA,SAAgB,sBAAwC,CACtD,IAAMA,EAAW,QAAQ,IAAI,6BAA+B,GAG5D,MAAO,CACL,QAHcA,EAAS,OAAS,EAIhC,UACF,CACF,CCnBA,IAAIC,EACAC,EAAe,GACfC,EAeJ,eAAsB,eAA+B,CAKnD,GAJID,IACJ,EAAe,GAEf,EAAU,qBAAqB,EAC3B,CAACD,EAAQ,SAAS,OAGtB,GAAM,CACJ,CAAE,qBAAoB,sBACtB,CAAE,qBACF,CAAE,0BACF,CAAE,oBAAmB,wBACrB,CAAE,oBACA,MAAM,QAAQ,IAAI,CACpB,OAAO,iCACP,OAAO,4CACP,OAAO,4BACP,OAAO,uCACP,OAAO,8BACT,CAAC,EAGKG,GAAU,MADUC,EAAgB,EAAA,CACd,SAAW,UAWvC,EAAY,IAAIC,EAAmB,CACjC,SAVeC,EAAuB,EACrCC,GAAoB,UACpBC,GAAuBL,CAC1B,CAOS,EACP,eAAgB,CAAC,IAAIM,EAAmB,IANrBC,EAAkB,CACrC,IAAK,GAAGV,EAAQ,SAAS,WAC3B,CAIiD,CAAC,CAAC,CACnD,CAAC,EAEDE,EAAU,SAAS,CACrB,CAOA,eAAsB,mBAAmC,CAClDA,GACL,MAAMA,EAAU,SAAS,CAC3B,CAUA,eAAsB,SAAY,EAAc,EAA4C,CAG1F,OAFeS,EAAM,UAAU,QAEnB,CAAC,CAAC,gBAAgBC,EAAM,KAAO,IAAS,CAClD,GAAI,CACF,IAAMC,EAAS,MAAMC,EAAGC,CAAI,EAE5B,OADAA,EAAK,UAAU,CAAE,KAAMC,EAAe,EAAG,CAAC,EACnCH,CACT,OAASI,EAAO,CAKd,MAJAF,EAAK,UAAU,CAAE,KAAMC,EAAe,KAAM,CAAC,EACzCC,aAAiB,OACnBF,EAAK,gBAAgBE,CAAK,EAEtBA,CACR,QAAU,CACRF,EAAK,IAAI,CACX,CACF,CAAC,CACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"type-source--ZNcV8RJ.mjs","names":[],"sources":["../src/parser/service/tailordb/type-source.ts"],"sourcesContent":["import type { PluginGeneratedTableSource, TypeSourceInfoEntry } from \"./types\";\n\n/**\n * Checks if a table source is generated by a plugin.\n * @param source - The table source entry to check.\n * @returns True if the source was generated by a plugin.\n */\nexport function isPluginGeneratedTable(\n source: TypeSourceInfoEntry,\n): source is PluginGeneratedTableSource {\n return source.pluginId !== undefined;\n}\n"],"mappings":"AAOA,SAAgB,uBACd,EACsC,CACtC,OAAO,EAAO,WAAa,IAAA,EAC7B"}
1
+ {"version":3,"file":"type-source--ZNcV8RJ.mjs","names":["source"],"sources":["../src/parser/service/tailordb/type-source.ts"],"sourcesContent":["import type { PluginGeneratedTableSource, TypeSourceInfoEntry } from \"./types\";\n\n/**\n * Checks if a table source is generated by a plugin.\n * @param source - The table source entry to check.\n * @returns True if the source was generated by a plugin.\n */\nexport function isPluginGeneratedTable(\n source: TypeSourceInfoEntry,\n): source is PluginGeneratedTableSource {\n return source.pluginId !== undefined;\n}\n"],"mappings":"AAOA,SAAgB,uBACd,EACsC,CACtC,OAAOA,EAAO,WAAa,IAAA,EAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"user-agent-vdHYF3QL.mjs","names":[],"sources":["../src/cli/shared/user-agent.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/${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"],"mappings":"gDASA,SAAgB,qBAAqB,EAAyB,CAC5D,MAAO,UAAU,GACnB,CAUA,eAAsB,WAAY,CAEhC,OAAO,sBAAqB,MADF,EAAgB,EAAA,CACF,SAAW,SAAS,CAC9D"}
1
+ {"version":3,"file":"user-agent-vdHYF3QL.mjs","names":["readPackageJson","version"],"sources":["../src/cli/shared/user-agent.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/${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"],"mappings":"gDASA,SAAgB,qBAAqB,EAAyB,CAC5D,MAAO,UAAUC,GACnB,CAUA,eAAsB,WAAY,CAEhC,OAAO,sBAAqB,MADFD,EAAgB,EAAA,CACF,SAAW,SAAS,CAC9D"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/utils/test/index.ts"],"sourcesContent":["import { isNestedObject } from \"#/runtime/field-parse\";\nimport type { output } from \"#/configure/index\";\nimport type { TailorDBType } from \"#/configure/services/tailordb/schema\";\nimport type { TailorField } from \"#/configure/types/type\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Not `record[key] = value`: assigning to `__proto__` goes through the inherited\n// setter, which mutates the prototype instead of recording the field and leaves\n// no own property behind for the value to be read from.\nfunction setField(record: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(record, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Creates a hook function that processes TailorDB table fields\n * - Uses existing id from data if provided, otherwise generates UUID for id fields\n * - Recursively processes nested types\n * - Executes hooks.create for fields with create hooks\n * - Takes each field from the data's own properties, so a field named after a\n * member of `Object` such as `toString` is read from the record rather than\n * from the prototype\n * @template T - The output type of the hook function\n * @param type - TailorDB table definition\n * @returns A function that transforms input data according to field hooks\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createTailorDBHook<T extends TailorDBType<any, any>>(type: T) {\n return (data: unknown, now: Date = new Date()) => {\n const obj = data && typeof data === \"object\" ? (data as Record<string, unknown>) : undefined;\n const hooked = Object.entries(type.fields).reduce(\n (hooked, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const field = value as TailorField<any, any, any>;\n // `Object.hasOwn`, not `obj?.[key]`: a field named after an Object member\n // such as `toString` would otherwise read the inherited value.\n const input = obj && Object.hasOwn(obj, key) ? obj[key] : undefined;\n let hookedValue: unknown;\n if (key === \"id\") {\n hookedValue = input ?? crypto.randomUUID();\n } else if (field.type === \"nested\") {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nestedHook = createTailorDBHook({ fields: field.fields } as any);\n if (field.metadata.array) {\n hookedValue = Array.isArray(input)\n ? input.map((item) => (isNestedObject(item) ? nestedHook(item, now) : item))\n : input;\n } else {\n hookedValue = isNestedObject(input) ? nestedHook(input, now) : input;\n }\n } else if (field.metadata.hooks?.create) {\n hookedValue = field.metadata.hooks.create({ input, invoker: null, now });\n if (hookedValue instanceof Date) {\n hookedValue = hookedValue.toISOString();\n }\n } else {\n hookedValue = input;\n }\n if (hookedValue == null && field.metadata.default !== undefined) {\n const isTimeType =\n field.type === \"datetime\" || field.type === \"date\" || field.type === \"time\";\n hookedValue =\n field.metadata.default === \"now\" && isTimeType\n ? now.toISOString()\n : field.metadata.default;\n }\n // Set even when there is no value: the key carrying `undefined` is what\n // tells a schema inferred from the record that the column is nullable,\n // and it shadows a same-named member of `Object.prototype`.\n setField(hooked, key, hookedValue);\n return hooked;\n },\n {} as Record<string, unknown>,\n );\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- metadata absent in recursive nested calls\n if (type.metadata?.typeHook?.create) {\n const { id: _id, ...typeHookInput } = hooked;\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n const overrides = type.metadata.typeHook.create({\n input: typeHookInput,\n invoker: null,\n now,\n });\n if (overrides && typeof overrides === \"object\") {\n for (const [key, value] of Object.entries(overrides as Record<string, unknown>)) {\n setField(hooked, key, value instanceof Date ? value.toISOString() : value);\n }\n }\n }\n\n return hooked as Partial<output<T>>;\n };\n}\n\n// Collect the issues the table's own `validate` reports for a record, so they\n// surface the same way a field's do instead of ending the run.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction typeLevelIssues(type: TailorDBType<any, any> | undefined, hooked: unknown) {\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- absent on a nested type\n const typeValidate = type?.metadata?.typeValidate;\n if (!typeValidate) {\n return [];\n }\n const { id: _id, ...newRecord } = hooked as Record<string, unknown>;\n const issues: StandardSchemaV1.Issue[] = [];\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n typeValidate({ newRecord, oldRecord: null, invoker: null }, (field: string, message: string) => {\n issues.push({ message, path: [field] });\n });\n return issues;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype DeclaredFields = Record<string, TailorField<any, any, any>>;\n\nfunction undeclaredFieldMessage(key: string): string {\n return `Field \"${key}\" is not declared by the table. Remove it from the row, or add it to the table definition and run \\`tailor generate\\`.`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n// Reads the raw row, not the hooked one: the hook only copies the declared fields,\n// so an undeclared key is gone by the time the field schema runs.\nfunction collectUndeclaredFieldIssues(\n value: unknown,\n fields: DeclaredFields,\n path: string[],\n issues: StandardSchemaV1.Issue[],\n): void {\n if (!isRecord(value)) {\n return;\n }\n for (const key of Object.keys(value)) {\n // `Object.hasOwn`, not `key in fields`: a key such as `constructor` would\n // otherwise resolve to a member of `Object.prototype`.\n if (!Object.hasOwn(fields, key)) {\n issues.push({ message: undeclaredFieldMessage(key), path: path.concat(key) });\n continue;\n }\n const field = fields[key];\n if (field?.type !== \"nested\") {\n continue;\n }\n const nested = value[key];\n const nestedFields = field.fields as DeclaredFields;\n if (field.metadata.array) {\n if (Array.isArray(nested)) {\n nested.forEach((item, index) => {\n collectUndeclaredFieldIssues(item, nestedFields, path.concat(key, `[${index}]`), issues);\n });\n }\n } else {\n collectUndeclaredFieldIssues(nested, nestedFields, path.concat(key), issues);\n }\n }\n}\n\n/**\n * Creates the standard schema definition used to validate seed rows.\n * Runs the hook, then the table's own `validate`, and the field schema only when\n * that reported nothing, so both levels of validation report as issues rather\n * than by throwing. When the table is given, a key the row carries that the table\n * does not declare is reported as an issue as well, including keys inside nested\n * objects, so a row that no longer matches the table fails here instead of when\n * it is applied.\n * @template T - The output type after validation\n * @param schemaType - TailorDB field schema for validation\n * @param hook - Hook function to transform data before validation\n * @param type - TailorDB table definition; runs its table-level `validate` and\n * rejects fields it does not declare\n * @returns Schema object with ~standard section for defineSchema\n */\nexport function createStandardSchema<T = Record<string, unknown>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schemaType: TailorField<any, T>,\n hook: (data: unknown) => Partial<T>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n type?: TailorDBType<any, any>,\n) {\n const validateHooked = (hooked: Partial<T>): StandardSchemaV1.Result<T> => {\n const issues = typeLevelIssues(type, hooked);\n if (issues.length > 0) {\n return { issues };\n }\n const result = schemaType.parse({\n value: hooked,\n data: hooked,\n invoker: null,\n });\n if (result.issues) {\n return result;\n }\n return { value: hooked as T };\n };\n\n return {\n \"~standard\": {\n version: 1,\n vendor: \"@tailor-platform/sdk\",\n validate: (value: unknown) => {\n const hooked = hook(value);\n const undeclared: StandardSchemaV1.Issue[] = [];\n if (type) {\n collectUndeclaredFieldIssues(value, type.fields as DeclaredFields, [], undeclared);\n }\n const result = validateHooked(hooked);\n const issues = [...undeclared, ...(result.issues ?? [])];\n return issues.length > 0 ? { issues } : result;\n },\n },\n } as const satisfies StandardSchemaV1<T>;\n}\n"],"mappings":"mDASA,SAAS,SAAS,EAAiC,EAAa,EAAsB,CACpF,OAAO,eAAe,EAAQ,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,CACH,CAeA,SAAgB,mBAAqD,EAAS,CAC5E,OAAQ,EAAe,kBAAY,IAAI,OAAW,CAChD,IAAM,EAAM,GAAQ,OAAO,GAAS,SAAY,EAAmC,IAAA,GAC7E,EAAS,OAAO,QAAQ,EAAK,MAAM,CAAC,CAAC,QACxC,EAAQ,CAAC,EAAK,KAAW,CAExB,IAAM,EAAQ,EAGR,EAAQ,GAAO,OAAO,OAAO,EAAK,CAAG,EAAI,EAAI,GAAO,IAAA,GACtD,EACJ,GAAI,IAAQ,KACV,EAAc,GAAS,OAAO,WAAW,OACpC,GAAI,EAAM,OAAS,SAAU,CAElC,IAAM,EAAa,mBAAmB,CAAE,OAAQ,EAAM,MAAO,CAAQ,EACrE,AAKE,EALE,EAAM,SAAS,MACH,M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AAY,GAAI,EAAO,QAAU,CAAC,CAAE,EACvD,OAAO,EAAO,OAAS,EAAI,CAAE,QAAO,EAAI,CAC1C,CACF,CACF,CACF"}
1
+ {"version":3,"file":"index.mjs","names":["isNestedObject","record","key","obj","data","hooked","type","value","field","input","hookedValue","nestedHook","item","now","isTimeType","_id","typeHookInput","overrides","typeValidate","newRecord","issues","fields","path","nested","nestedFields","index","result","schemaType","hook","undeclared"],"sources":["../../../src/utils/test/index.ts"],"sourcesContent":["import { isNestedObject } from \"#/runtime/field-parse\";\nimport type { output } from \"#/configure/index\";\nimport type { TailorDBType } from \"#/configure/services/tailordb/schema\";\nimport type { TailorField } from \"#/configure/types/type\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Not `record[key] = value`: assigning to `__proto__` goes through the inherited\n// setter, which mutates the prototype instead of recording the field and leaves\n// no own property behind for the value to be read from.\nfunction setField(record: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(record, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/**\n * Creates a hook function that processes TailorDB table fields\n * - Uses existing id from data if provided, otherwise generates UUID for id fields\n * - Recursively processes nested types\n * - Executes hooks.create for fields with create hooks\n * - Takes each field from the data's own properties, so a field named after a\n * member of `Object` such as `toString` is read from the record rather than\n * from the prototype\n * @template T - The output type of the hook function\n * @param type - TailorDB table definition\n * @returns A function that transforms input data according to field hooks\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createTailorDBHook<T extends TailorDBType<any, any>>(type: T) {\n return (data: unknown, now: Date = new Date()) => {\n const obj = data && typeof data === \"object\" ? (data as Record<string, unknown>) : undefined;\n const hooked = Object.entries(type.fields).reduce(\n (hooked, [key, value]) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const field = value as TailorField<any, any, any>;\n // `Object.hasOwn`, not `obj?.[key]`: a field named after an Object member\n // such as `toString` would otherwise read the inherited value.\n const input = obj && Object.hasOwn(obj, key) ? obj[key] : undefined;\n let hookedValue: unknown;\n if (key === \"id\") {\n hookedValue = input ?? crypto.randomUUID();\n } else if (field.type === \"nested\") {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nestedHook = createTailorDBHook({ fields: field.fields } as any);\n if (field.metadata.array) {\n hookedValue = Array.isArray(input)\n ? input.map((item) => (isNestedObject(item) ? nestedHook(item, now) : item))\n : input;\n } else {\n hookedValue = isNestedObject(input) ? nestedHook(input, now) : input;\n }\n } else if (field.metadata.hooks?.create) {\n hookedValue = field.metadata.hooks.create({ input, invoker: null, now });\n if (hookedValue instanceof Date) {\n hookedValue = hookedValue.toISOString();\n }\n } else {\n hookedValue = input;\n }\n if (hookedValue == null && field.metadata.default !== undefined) {\n const isTimeType =\n field.type === \"datetime\" || field.type === \"date\" || field.type === \"time\";\n hookedValue =\n field.metadata.default === \"now\" && isTimeType\n ? now.toISOString()\n : field.metadata.default;\n }\n // Set even when there is no value: the key carrying `undefined` is what\n // tells a schema inferred from the record that the column is nullable,\n // and it shadows a same-named member of `Object.prototype`.\n setField(hooked, key, hookedValue);\n return hooked;\n },\n {} as Record<string, unknown>,\n );\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- metadata absent in recursive nested calls\n if (type.metadata?.typeHook?.create) {\n const { id: _id, ...typeHookInput } = hooked;\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n const overrides = type.metadata.typeHook.create({\n input: typeHookInput,\n invoker: null,\n now,\n });\n if (overrides && typeof overrides === \"object\") {\n for (const [key, value] of Object.entries(overrides as Record<string, unknown>)) {\n setField(hooked, key, value instanceof Date ? value.toISOString() : value);\n }\n }\n }\n\n return hooked as Partial<output<T>>;\n };\n}\n\n// Collect the issues the table's own `validate` reports for a record, so they\n// surface the same way a field's do instead of ending the run.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction typeLevelIssues(type: TailorDBType<any, any> | undefined, hooked: unknown) {\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- absent on a nested type\n const typeValidate = type?.metadata?.typeValidate;\n if (!typeValidate) {\n return [];\n }\n const { id: _id, ...newRecord } = hooked as Record<string, unknown>;\n const issues: StandardSchemaV1.Issue[] = [];\n // oxlint-disable-next-line typescript/no-unsafe-function-type\n typeValidate({ newRecord, oldRecord: null, invoker: null }, (field: string, message: string) => {\n issues.push({ message, path: [field] });\n });\n return issues;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype DeclaredFields = Record<string, TailorField<any, any, any>>;\n\nfunction undeclaredFieldMessage(key: string): string {\n return `Field \"${key}\" is not declared by the table. Remove it from the row, or add it to the table definition and run \\`tailor generate\\`.`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n// Reads the raw row, not the hooked one: the hook only copies the declared fields,\n// so an undeclared key is gone by the time the field schema runs.\nfunction collectUndeclaredFieldIssues(\n value: unknown,\n fields: DeclaredFields,\n path: string[],\n issues: StandardSchemaV1.Issue[],\n): void {\n if (!isRecord(value)) {\n return;\n }\n for (const key of Object.keys(value)) {\n // `Object.hasOwn`, not `key in fields`: a key such as `constructor` would\n // otherwise resolve to a member of `Object.prototype`.\n if (!Object.hasOwn(fields, key)) {\n issues.push({ message: undeclaredFieldMessage(key), path: path.concat(key) });\n continue;\n }\n const field = fields[key];\n if (field?.type !== \"nested\") {\n continue;\n }\n const nested = value[key];\n const nestedFields = field.fields as DeclaredFields;\n if (field.metadata.array) {\n if (Array.isArray(nested)) {\n nested.forEach((item, index) => {\n collectUndeclaredFieldIssues(item, nestedFields, path.concat(key, `[${index}]`), issues);\n });\n }\n } else {\n collectUndeclaredFieldIssues(nested, nestedFields, path.concat(key), issues);\n }\n }\n}\n\n/**\n * Creates the standard schema definition used to validate seed rows.\n * Runs the hook, then the table's own `validate`, and the field schema only when\n * that reported nothing, so both levels of validation report as issues rather\n * than by throwing. When the table is given, a key the row carries that the table\n * does not declare is reported as an issue as well, including keys inside nested\n * objects, so a row that no longer matches the table fails here instead of when\n * it is applied.\n * @template T - The output type after validation\n * @param schemaType - TailorDB field schema for validation\n * @param hook - Hook function to transform data before validation\n * @param type - TailorDB table definition; runs its table-level `validate` and\n * rejects fields it does not declare\n * @returns Schema object with ~standard section for defineSchema\n */\nexport function createStandardSchema<T = Record<string, unknown>>(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schemaType: TailorField<any, T>,\n hook: (data: unknown) => Partial<T>,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n type?: TailorDBType<any, any>,\n) {\n const validateHooked = (hooked: Partial<T>): StandardSchemaV1.Result<T> => {\n const issues = typeLevelIssues(type, hooked);\n if (issues.length > 0) {\n return { issues };\n }\n const result = schemaType.parse({\n value: hooked,\n data: hooked,\n invoker: null,\n });\n if (result.issues) {\n return result;\n }\n return { value: hooked as T };\n };\n\n return {\n \"~standard\": {\n version: 1,\n vendor: \"@tailor-platform/sdk\",\n validate: (value: unknown) => {\n const hooked = hook(value);\n const undeclared: StandardSchemaV1.Issue[] = [];\n if (type) {\n collectUndeclaredFieldIssues(value, type.fields as DeclaredFields, [], undeclared);\n }\n const result = validateHooked(hooked);\n const issues = [...undeclared, ...(result.issues ?? [])];\n return issues.length > 0 ? { issues } : result;\n },\n },\n } as const satisfies StandardSchemaV1<T>;\n}\n"],"mappings":"mDASA,SAAS,SAAS,EAAiC,EAAa,EAAsB,CACpF,OAAO,eAAeC,EAAQC,EAAK,CACjC,QACA,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,CACH,CAeA,SAAgB,mBAAqD,EAAS,CAC5E,OAAQ,EAAe,kBAAY,IAAI,OAAW,CAChD,IAAMC,EAAMC,GAAQ,OAAOA,GAAS,SAAYA,EAAmC,IAAA,GAC7EC,EAAS,OAAO,QAAQC,EAAK,MAAM,CAAC,CAAC,QACxC,EAAQ,CAACJ,EAAKK,KAAW,CAExB,IAAMC,EAAQD,EAGRE,EAAQN,GAAO,OAAO,OAAOA,EAAKD,CAAG,E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