cvx-kit 0.1.35 → 2.0.0-beta.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.
- package/README.md +92 -49
- package/dist/agent-tools.d.mts +21 -25
- package/dist/agent-tools.mjs +1 -1
- package/dist/agent-tools.mjs.map +1 -1
- package/dist/auth.d.mts +20 -14
- package/dist/auth.mjs +1 -1
- package/dist/auth.mjs.map +1 -1
- package/dist/components/approvals/_generated/api.d.mts +4 -5
- package/dist/components/approvals/_generated/api.mjs.map +1 -1
- package/dist/components/approvals/_generated/component.d.mts +0 -2
- package/dist/components/approvals/_generated/dataModel.d.mts +1 -3
- package/dist/components/approvals/_generated/server.d.mts +0 -2
- package/dist/components/approvals/_generated/server.mjs.map +1 -1
- package/dist/components/approvals/audit.d.mts +0 -1
- package/dist/components/approvals/audit.mjs +1 -1
- package/dist/components/approvals/audit.mjs.map +1 -1
- package/dist/components/approvals/client.d.mts +0 -1
- package/dist/components/approvals/client.mjs +1 -1
- package/dist/components/approvals/client.mjs.map +1 -1
- package/dist/components/approvals/constants.d.mts +0 -1
- package/dist/components/approvals/constants.mjs.map +1 -1
- package/dist/components/approvals/convex.config.d.mts +0 -2
- package/dist/components/approvals/convex.config.mjs.map +1 -1
- package/dist/components/approvals/decisions.d.mts +1 -4
- package/dist/components/approvals/decisions.mjs +1 -1
- package/dist/components/approvals/decisions.mjs.map +1 -1
- package/dist/components/approvals/functions.d.mts +0 -1
- package/dist/components/approvals/functions.mjs.map +1 -1
- package/dist/components/approvals/health.d.mts +0 -1
- package/dist/components/approvals/health.mjs.map +1 -1
- package/dist/components/approvals/requests.d.mts +106 -123
- package/dist/components/approvals/requests.mjs +1 -1
- package/dist/components/approvals/requests.mjs.map +1 -1
- package/dist/components/approvals/schema.d.ts +106 -315
- package/dist/components/approvals/schema.js +1 -1
- package/dist/components/approvals/validators.d.mts +321 -393
- package/dist/components/approvals/validators.mjs +1 -1
- package/dist/components/approvals/validators.mjs.map +1 -1
- package/dist/components/approvals/workflow.d.mts +0 -1
- package/dist/components/approvals/workflow.mjs +1 -1
- package/dist/components/approvals/workflow.mjs.map +1 -1
- package/dist/components/approvals/workflow_steps.d.mts +1 -2
- package/dist/components/approvals/workflow_steps.mjs.map +1 -1
- package/dist/components/foundation/_generated/api.d.mts +3 -4
- package/dist/components/foundation/_generated/api.mjs.map +1 -1
- package/dist/components/foundation/_generated/component.d.mts +0 -2
- package/dist/components/foundation/_generated/dataModel.d.mts +1 -3
- package/dist/components/foundation/_generated/server.d.mts +0 -2
- package/dist/components/foundation/_generated/server.mjs.map +1 -1
- package/dist/components/foundation/client.d.mts +0 -1
- package/dist/components/foundation/client.mjs +1 -1
- package/dist/components/foundation/client.mjs.map +1 -1
- package/dist/components/foundation/convex.config.d.mts +0 -2
- package/dist/components/foundation/convex.config.mjs.map +1 -1
- package/dist/components/foundation/functions.d.mts +0 -1
- package/dist/components/foundation/functions.mjs.map +1 -1
- package/dist/components/foundation/modules/command/command.d.mts +0 -1
- package/dist/components/foundation/modules/command/command.mjs.map +1 -1
- package/dist/components/foundation/modules/command/lifecycle.d.mts +0 -2
- package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -1
- package/dist/components/foundation/modules/observability/observability.d.mts +0 -1
- package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
- package/dist/components/foundation/modules/query/query.d.mts +0 -1
- package/dist/components/foundation/modules/query/query.mjs.map +1 -1
- package/dist/components/foundation/operation.d.mts +2 -3
- package/dist/components/foundation/operation.mjs.map +1 -1
- package/dist/components/foundation/result.d.mts +0 -1
- package/dist/components/foundation/result.mjs.map +1 -1
- package/dist/components/foundation/schema.d.ts +0 -2
- package/dist/components/foundation/telemetry.d.mts +0 -1
- package/dist/components/foundation/telemetry.mjs +1 -1
- package/dist/components/foundation/telemetry.mjs.map +1 -1
- package/dist/contracts.d.mts +2 -2
- package/dist/contracts.mjs +1 -1
- package/dist/crud.d.mts +93 -97
- package/dist/crud.mjs +1 -1
- package/dist/crud.mjs.map +1 -1
- package/dist/effect.d.mts +2 -3
- package/dist/effect.mjs +1 -1
- package/dist/errors.d.mts +2 -4
- package/dist/errors.mjs +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/filters.d.mts +1 -1
- package/dist/filters.mjs +1 -1
- package/dist/idempotency.mjs +1 -1
- package/dist/index.d.mts +10 -7
- package/dist/index.mjs +1 -1
- package/dist/json-schema.d.mts +40 -0
- package/dist/json-schema.mjs +2 -0
- package/dist/json-schema.mjs.map +1 -0
- package/dist/k/compile.d.mts +17 -0
- package/dist/k/compile.mjs +2 -0
- package/dist/k/compile.mjs.map +1 -0
- package/dist/k/dates.d.mts +23 -0
- package/dist/k/dates.mjs +2 -0
- package/dist/k/dates.mjs.map +1 -0
- package/dist/k/formats.d.mts +24 -0
- package/dist/k/formats.mjs +2 -0
- package/dist/k/formats.mjs.map +1 -0
- package/dist/k/index.d.mts +32 -0
- package/dist/k/index.mjs +2 -0
- package/dist/k/index.mjs.map +1 -0
- package/dist/k/issues.d.mts +31 -0
- package/dist/k/issues.mjs +2 -0
- package/dist/k/issues.mjs.map +1 -0
- package/dist/k/kinds.d.mts +81 -0
- package/dist/k/kinds.mjs +2 -0
- package/dist/k/kinds.mjs.map +1 -0
- package/dist/k/object.d.mts +43 -0
- package/dist/k/object.mjs +2 -0
- package/dist/k/object.mjs.map +1 -0
- package/dist/k/parse.d.mts +29 -0
- package/dist/k/parse.mjs +2 -0
- package/dist/k/parse.mjs.map +1 -0
- package/dist/k/schema.d.mts +100 -0
- package/dist/k/schema.mjs +2 -0
- package/dist/k/schema.mjs.map +1 -0
- package/dist/k/standard.d.mts +8 -0
- package/dist/k/standard.mjs +2 -0
- package/dist/k/standard.mjs.map +1 -0
- package/dist/k/types.d.mts +64 -0
- package/dist/k/types.mjs +1 -0
- package/dist/k.d.mts +8 -0
- package/dist/k.mjs +1 -0
- package/dist/middleware.d.mts +0 -2
- package/dist/middleware.mjs +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/modules/contracts/binding.d.mts +1 -2
- package/dist/modules/contracts/binding.mjs.map +1 -1
- package/dist/modules/contracts/contract.d.mts +0 -2
- package/dist/modules/contracts/contract.mjs.map +1 -1
- package/dist/modules/contracts/convex.d.mts +1 -3
- package/dist/modules/contracts/convex.mjs.map +1 -1
- package/dist/modules/contracts/domain.d.mts +1 -2
- package/dist/modules/contracts/domain.mjs.map +1 -1
- package/dist/modules/contracts/errors.d.mts +161 -2
- package/dist/modules/contracts/errors.mjs +1 -1
- package/dist/modules/contracts/errors.mjs.map +1 -1
- package/dist/modules/contracts/exposure.d.mts +1 -2
- package/dist/modules/contracts/exposure.mjs.map +1 -1
- package/dist/modules/contracts/idempotency.d.mts +1 -2
- package/dist/modules/contracts/idempotency.mjs +1 -1
- package/dist/modules/contracts/idempotency.mjs.map +1 -1
- package/dist/modules/contracts/lazy.d.mts +0 -2
- package/dist/modules/contracts/lazy.mjs.map +1 -1
- package/dist/modules/contracts/standard.d.mts +7 -5
- package/dist/modules/contracts/standard.mjs +1 -1
- package/dist/modules/contracts/standard.mjs.map +1 -1
- package/dist/modules/contracts/workflow.d.mts +1 -2
- package/dist/modules/contracts/workflow.mjs.map +1 -1
- package/dist/modules/effect/action.d.mts +6 -7
- package/dist/modules/effect/action.mjs +1 -1
- package/dist/modules/effect/action.mjs.map +1 -1
- package/dist/modules/effect/agent-tools.mjs +1 -1
- package/dist/modules/effect/api-runtime.d.mts +1 -2
- package/dist/modules/effect/api-runtime.mjs +1 -1
- package/dist/modules/effect/api-runtime.mjs.map +1 -1
- package/dist/modules/effect/api.d.mts +41 -15
- package/dist/modules/effect/api.mjs +1 -1
- package/dist/modules/effect/api.mjs.map +1 -1
- package/dist/modules/effect/auth.d.mts +5 -6
- package/dist/modules/effect/auth.mjs +1 -1
- package/dist/modules/effect/auth.mjs.map +1 -1
- package/dist/modules/effect/client.d.mts +7 -8
- package/dist/modules/effect/client.mjs +1 -1
- package/dist/modules/effect/command.d.mts +7 -5
- package/dist/modules/effect/command.mjs +1 -1
- package/dist/modules/effect/command.mjs.map +1 -1
- package/dist/modules/effect/crud.d.mts +272 -206
- package/dist/modules/effect/crud.mjs +1 -1
- package/dist/modules/effect/crud.mjs.map +1 -1
- package/dist/modules/effect/domain.d.mts +5 -6
- package/dist/modules/effect/domain.mjs.map +1 -1
- package/dist/modules/effect/errors.d.mts +4 -2
- package/dist/modules/effect/errors.mjs +1 -1
- package/dist/modules/effect/errors.mjs.map +1 -1
- package/dist/modules/effect/failure-audit.d.mts +2 -2
- package/dist/modules/effect/failure-audit.mjs +1 -1
- package/dist/modules/effect/failure-audit.mjs.map +1 -1
- package/dist/modules/effect/failures.d.mts +1 -2
- package/dist/modules/effect/failures.mjs.map +1 -1
- package/dist/modules/effect/foundation.d.mts +0 -2
- package/dist/modules/effect/foundation.mjs.map +1 -1
- package/dist/modules/effect/idempotency.d.mts +2 -3
- package/dist/modules/effect/idempotency.mjs +1 -1
- package/dist/modules/effect/idempotency.mjs.map +1 -1
- package/dist/modules/effect/input.d.mts +10 -0
- package/dist/modules/effect/input.mjs +2 -0
- package/dist/modules/effect/input.mjs.map +1 -0
- package/dist/modules/effect/normalize.d.mts +0 -2
- package/dist/modules/effect/normalize.mjs.map +1 -1
- package/dist/modules/effect/operation.d.mts +2 -3
- package/dist/modules/effect/operation.mjs.map +1 -1
- package/dist/modules/effect/query.d.mts +6 -4
- package/dist/modules/effect/query.mjs +1 -1
- package/dist/modules/effect/query.mjs.map +1 -1
- package/dist/modules/effect/schema.d.mts +0 -2
- package/dist/modules/effect/schema.mjs.map +1 -1
- package/dist/modules/effect/scope.d.mts +0 -2
- package/dist/modules/effect/scope.mjs.map +1 -1
- package/dist/modules/effect/workflow.d.mts +4 -5
- package/dist/modules/effect/workflow.mjs +1 -1
- package/dist/modules/effect/workflow.mjs.map +1 -1
- package/dist/modules/foundation/foundation.d.mts +4 -5
- package/dist/modules/foundation/foundation.mjs +1 -1
- package/dist/modules/foundation/foundation.mjs.map +1 -1
- package/dist/modules/foundation/operation.d.mts +2 -3
- package/dist/modules/foundation/operation.mjs.map +1 -1
- package/dist/namespace.d.mts +104 -0
- package/dist/namespace.mjs +2 -0
- package/dist/namespace.mjs.map +1 -0
- package/dist/oxlint/architecture.d.mts +0 -2
- package/dist/oxlint/architecture.mjs +1 -1
- package/dist/oxlint/architecture.mjs.map +1 -1
- package/dist/oxlint/ast.d.mts +16 -8
- package/dist/oxlint/ast.mjs +1 -1
- package/dist/oxlint/ast.mjs.map +1 -1
- package/dist/oxlint/components.d.mts +0 -2
- package/dist/oxlint/components.mjs.map +1 -1
- package/dist/oxlint/ownership.d.mts +0 -2
- package/dist/oxlint/ownership.mjs +1 -1
- package/dist/oxlint/ownership.mjs.map +1 -1
- package/dist/oxlint/reserved-files.d.mts +0 -2
- package/dist/oxlint/reserved-files.mjs +1 -1
- package/dist/oxlint/reserved-files.mjs.map +1 -1
- package/dist/oxlint.d.mts +0 -2
- package/dist/oxlint.mjs +1 -1
- package/dist/oxlint.mjs.map +1 -1
- package/dist/querying/cursors.d.mts +27 -9
- package/dist/querying/cursors.mjs +1 -1
- package/dist/querying/cursors.mjs.map +1 -1
- package/dist/querying/execution.d.mts +6 -7
- package/dist/querying/execution.mjs +1 -1
- package/dist/querying/execution.mjs.map +1 -1
- package/dist/querying/failures.d.mts +0 -2
- package/dist/querying/failures.mjs +1 -1
- package/dist/querying/failures.mjs.map +1 -1
- package/dist/querying/filter-boundary.d.mts +18 -9
- package/dist/querying/filter-boundary.mjs +1 -1
- package/dist/querying/filter-boundary.mjs.map +1 -1
- package/dist/querying/filters.d.mts +71 -35
- package/dist/querying/filters.mjs +1 -1
- package/dist/querying/filters.mjs.map +1 -1
- package/dist/querying/planner.d.mts +16 -20
- package/dist/querying/planner.mjs +1 -1
- package/dist/querying/planner.mjs.map +1 -1
- package/dist/querying/relationships.d.mts +6 -6
- package/dist/querying/relationships.mjs +1 -1
- package/dist/querying/relationships.mjs.map +1 -1
- package/dist/querying/search.d.mts +12 -12
- package/dist/querying/search.mjs +1 -1
- package/dist/querying/search.mjs.map +1 -1
- package/dist/querying/security.d.mts +2 -3
- package/dist/querying/security.mjs.map +1 -1
- package/dist/querying/shared/ast.d.mts +0 -2
- package/dist/querying/shared/ast.mjs.map +1 -1
- package/dist/querying/shared/contract.d.mts +17 -23
- package/dist/querying/shared/contract.mjs +1 -1
- package/dist/querying/shared/contract.mjs.map +1 -1
- package/dist/querying/shared/evaluate.d.mts +0 -2
- package/dist/querying/shared/evaluate.mjs.map +1 -1
- package/dist/querying/shared/filters.d.mts +47 -29
- package/dist/querying/shared/filters.mjs +1 -1
- package/dist/querying/shared/filters.mjs.map +1 -1
- package/dist/querying/shared/native-json.d.mts +7 -0
- package/dist/querying/shared/native-json.mjs +2 -0
- package/dist/querying/shared/native-json.mjs.map +1 -0
- package/dist/querying/shared/page.d.mts +19 -22
- package/dist/querying/shared/page.mjs +1 -1
- package/dist/querying/shared/page.mjs.map +1 -1
- package/dist/querying.d.mts +6 -9
- package/dist/querying.mjs +1 -1
- package/dist/querying.mjs.map +1 -1
- package/dist/react/failures.d.mts +0 -2
- package/dist/react/failures.mjs.map +1 -1
- package/dist/react/optimistic.d.mts +2 -3
- package/dist/react/optimistic.mjs.map +1 -1
- package/dist/react/pagination-state.d.mts +1 -2
- package/dist/react/pagination-state.mjs.map +1 -1
- package/dist/react/use-command.d.mts +0 -2
- package/dist/react/use-command.mjs.map +1 -1
- package/dist/react/use-paginated-list.d.mts +1 -3
- package/dist/react/use-paginated-list.mjs +1 -1
- package/dist/react/use-paginated-list.mjs.map +1 -1
- package/dist/react.d.mts +1 -1
- package/dist/react.mjs +1 -1
- package/dist/registration.d.mts +65 -0
- package/dist/registration.mjs +2 -0
- package/dist/registration.mjs.map +1 -0
- package/dist/relations-public.d.mts +2 -2
- package/dist/relations-public.mjs +1 -1
- package/dist/relations.d.mts +55 -46
- package/dist/relations.mjs +1 -1
- package/dist/relations.mjs.map +1 -1
- package/dist/state-machine.d.mts +0 -2
- package/dist/state-machine.mjs.map +1 -1
- package/dist/table.d.mts +222 -0
- package/dist/table.mjs +2 -0
- package/dist/table.mjs.map +1 -0
- package/dist/tenancy.d.mts +0 -2
- package/dist/tenancy.mjs.map +1 -1
- package/dist/triggers.d.mts +2 -4
- package/dist/triggers.mjs +1 -1
- package/dist/triggers.mjs.map +1 -1
- package/dist/webhooks.d.mts +9 -9
- package/dist/webhooks.mjs +1 -1
- package/dist/webhooks.mjs.map +1 -1
- package/dist/workflow.mjs +1 -1
- package/dist/zod.d.mts +30 -0
- package/dist/zod.mjs +2 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +51 -29
- package/dist/modules/effect/api-zod.d.mts +0 -34
- package/dist/modules/effect/api-zod.mjs +0 -2
- package/dist/modules/effect/api-zod.mjs.map +0 -1
- package/dist/querying/schema-snapshot.d.mts +0 -49
- package/dist/querying/schema-snapshot.mjs +0 -2
- package/dist/querying/schema-snapshot.mjs.map +0 -1
- package/dist/zod-convex.d.mts +0 -10
- package/dist/zod-convex.mjs +0 -2
- package/dist/zod-convex.mjs.map +0 -1
- package/dist/zod-registration.d.mts +0 -15
- package/dist/zod-registration.mjs +0 -2
- package/dist/zod-registration.mjs.map +0 -1
- package/dist/zod-table.d.mts +0 -351
- package/dist/zod-table.mjs +0 -2
- package/dist/zod-table.mjs.map +0 -1
package/dist/auth.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.mjs","names":["defaultRoleMap","normalized","roleSlug","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","core","createAuthCore","config","triggers","wrapDB","ctx","mutationInput","bundle","secureWriter","serviceMutation","zCustomMutation","servicePrincipal","principal","roleMutation","allowed","authenticated","requireRole","createAuthReaders","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","claimedOrganizationId","role","base","securityConfig","securityRules","security","sets","createTenantRules","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","wrapDatabaseWriter","verifiedMembership","membership","queryInput","actionInput","verified","rawFunctionArgs","servicePrincipalContract","reserved","key","serviceQuery","zCustomQuery","roleQuery","roleAction","zCustomAction","z"],"sources":["../src/auth.ts"],"sourcesContent":["import { z } from 'zod'\nimport { rawFunctionArgs, zCustomAction, zCustomMutation, zCustomQuery } from './zod-registration'\nimport type { CustomBuilder } from 'convex-helpers/server/zod4'\nimport type {\n\tActionBuilder,\n\tDefaultFunctionArgs,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * The bundle handed to security rules. Service principals (serviceQuery /\n * serviceMutation) may carry extra host-supplied fields beside the standard\n * bundle; rules read them as unknown and narrow as needed.\n */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras\n\n/** Extra fields a host factory attaches to a service principal. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type ServiceExtras = Readonly<Record<string, unknown>>\n\n/**\n * A trusted host factory producing the principal a service function runs as.\n * `args` are the raw (unparsed) arguments of the invocation, so the host can\n * derive the scope (e.g. a client id) from them. Never accept the principal\n * itself from the caller — only derive it.\n */\nexport type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (\n\tctx: Ctx,\n\targs: DefaultFunctionArgs,\n) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: SecurityBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\n/**\n * Configuration for createAuthReaders: everything createAuthFunctions takes\n * except the mutation builders and trigger wrapping, so a module built from\n * it never has to import the trigger registry.\n */\nexport type AuthReadersConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/**\n\t * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).\n\t * The already-resolved, non-null identity is supplied as a second argument.\n\t * Callbacks may ignore it; using it can avoid a redundant identity lookup.\n\t */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t\tidentity: UserIdentity,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*,\n\t * admin*, and service* constructor. system* constructors stay unwrapped\n\t * (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** A reader config plus the mutation builders and trigger wrapping. */\nexport type AuthFunctionsConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = AuthReadersConfig<DataModel, Role> & {\n\tmutation: MutationBuilder<DataModel, 'public'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/zod-table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * Keep native contexts symbolic in published declarations. Inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\t/**\n\t * Internal query running as a host-supplied service principal with the\n\t * app's security rules fully applied. No identity lookup; the trusted\n\t * host's factory is the only principal source.\n\t */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => ServiceQuery<DataModel, Role, Extra>\n\t/** Internal mutation running as a service principal: triggers first, then the secured writer. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => ServiceMutation<DataModel, Role, Extra>\n\tsystemQuery: CustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: CustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: CustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** The read-only constructors: everything AuthFunctions has except mutations. */\nexport type AuthReaders<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>\n\nexport type ServiceQuery<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'query',\n\t{},\n\tGenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericQueryCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\nexport type ServiceMutation<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = CustomBuilder<\n\t'mutation',\n\t{},\n\tGenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericMutationCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst core = createAuthCore(config)\n\tconst { include, secureWriter, servicePrincipal, requireRole } = core\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await core.authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\t/** Internal mutation running as the host-derived service principal: triggers, then rules. */\n\tfunction serviceMutation<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t): ServiceMutation<DataModel, Role, Extra> {\n\t\treturn zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\treturn {\n\t\t...core.readers,\n\t\troleMutation,\n\t\tauthMutation: zCustomMutation(config.mutation, {\n\t\t\targs: {},\n\t\t\tinput: mutationInput,\n\t\t}),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tserviceMutation,\n\t\tsystemMutation: zCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx: { ...wrapDB(ctx), include }, args: {} }),\n\t\t}),\n\t}\n}\n\n/**\n * Builds the read-only constructors (queries and actions) from the same\n * policy as createAuthFunctions, without mutation builders or triggers.\n * Identity, tenancy, rules, role gates, membership checks and errors are the\n * same implementation, so a module built from these never imports the\n * trigger registry or the domains it pulls in.\n */\nexport function createAuthReaders<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role> {\n\treturn createAuthCore(config).readers\n}\n\n/** Shared implementation behind createAuthFunctions and createAuthReaders. */\nfunction createAuthCore<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx, identity) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims.parse(identity)\n\t\t\tconst claimedOrganizationId = claims.organization?.organizationId ?? claims.org_id\n\t\t\tif (!claimedOrganizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claimedOrganizationId\n\t\t\torganizationRole = claims.organization?.role ?? claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t\tmode: 'authenticated' | 'trusted' = 'authenticated',\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode,\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function servicePrincipal<\n\t\tCtx extends GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n\t\tExtra extends Record<string, unknown>,\n\t>(principal: ServicePrincipal<Ctx, Role, Extra>, ctx: Ctx) {\n\t\tconst bundle = await principal(ctx, rawFunctionArgs(ctx))\n\t\tif (!servicePrincipalContract.safeParse(bundle).success) {\n\t\t\tthrow new Error('A service principal must be an AuthBundle with user.id and tenant')\n\t\t}\n\t\t// Extras are spread onto the secured ctx; a host field named like a native\n\t\t// handle (db, auth, scheduler, ...) would silently replace the secured one.\n\t\tconst reserved = Object.keys(bundle).filter((key) => key in ctx)\n\t\tif (reserved.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`A service principal cannot override native context fields: ${reserved.join(', ')}`,\n\t\t\t)\n\t\t}\n\t\treturn bundle\n\t}\n\n\t/** Internal query running as the host-derived service principal, rules applied. */\n\tfunction serviceQuery<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t): ServiceQuery<DataModel, Role, Extra> {\n\t\treturn zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureReader(ctx, bundle, 'trusted'), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn zCustomQuery(config.query, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => {\n\t\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\t\treturn authenticated\n\t\t\t},\n\t\t})\n\t}\n\n\tconst readers: AuthReaders<DataModel, Role> = {\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\troleQuery,\n\t\troleAction,\n\t\tauthQuery: zCustomQuery(config.query, { args: {}, input: queryInput }),\n\t\tauthAction: zCustomAction(config.action, {\n\t\t\targs: {},\n\t\t\tinput: actionInput,\n\t\t}),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tserviceQuery,\n\t\tsystemQuery: zCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({\n\t\t\t\tctx: {\n\t\t\t\t\t...ctx,\n\t\t\t\t\tinclude,\n\t\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\t\tscope: {\n\t\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\t\trole: null,\n\t\t\t\t\t\t},\n\t\t\t\t\t\trules: {},\n\t\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\targs: {},\n\t\t\t}),\n\t\t}),\n\t\tsystemAction: zCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: async (ctx) => ({ ctx, args: {} }),\n\t\t}),\n\t}\n\treturn { readers, include, authenticatedUser, secureWriter, servicePrincipal, requireRole }\n}\n\n/** The minimum a host factory must return; the rest of the bundle is the host's contract. */\nconst servicePrincipalContract = z.object({\n\tuser: z.object({ id: z.string() }),\n\ttenant: z.string(),\n})\n\nconst organizationClaims = z.object({\n\torganization: z\n\t\t.object({\n\t\t\torganizationId: z.string().optional().catch(undefined),\n\t\t\trole: z.string().optional().catch(undefined),\n\t\t})\n\t\t.optional()\n\t\t.catch(undefined),\n\torg_id: z.string().optional().catch(undefined),\n\trole: z.string().optional().catch(undefined),\n})\n"],"mappings":"mYAqMA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADID,IAAe,SAAiB,SAC7BA,IAAe,UAAYA,IAAe,UAAYA,IAAe,QACzEA,EACA,IACJ,CA2JA,SAAgBE,EAAc,EAAgE,CAC7F,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAUF,GAAS,SAAW,IAEpC,SAASG,EACR,EACA,E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","createInclude","errors","options","defaultErrors","maxRows","attach","execute","limit","data","selected","query","transform","paginate","opts","result","value","select","shouldMatch","indexName","indexRange","createAuthFunctions","core","createAuthCore","config","inputs","createMutationInputs","serviceMutation","kCustomMutation","principal","roleMutation","allowed","readers","createAuthReaders","serviceQuery","kCustomQuery","roleQuery","roleAction","kCustomAction","triggers","wrapDB","ctx","mutationInput","bundle","secureWriter","servicePrincipal","authenticated","requireRole","builders","kCustomFunctions","include","authenticatedUser","identity","user","organizationId","organizationRole","resolved","claims","organizationClaims","role","base","securityConfig","securityRules","security","sets","createTenantRules","composeRules","secureReader","rules","defaultPolicy","ordinary","wrapDatabaseReader","suppliedPolicyRules","registerQueryReader","wrapDatabaseWriter","verifiedMembership","membership","queryInput","actionInput","verified","rawFunctionArgs","principalContract","reserved","key","memoize","k","organization","claimRecord","claimString"],"sources":["../src/auth.ts"],"sourcesContent":["import { kCustomFunctions, rawFunctionArgs, type KCustomBuilder } from './registration'\nimport type { ArgumentFailurePolicy } from './modules/contracts/errors'\nimport { k } from './k/index'\nimport { memoize } from './modules/contracts/lazy'\nimport type { JSONValue } from 'convex/values'\nimport type {\n\tActionBuilder,\n\tDefaultFunctionArgs,\n\tDocumentByInfo,\n\tPaginationOptions,\n\tPaginationResult,\n\tGenericActionCtx,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n\tGenericTableInfo,\n\tIndexNames,\n\tIndexRange,\n\tIndexRangeBuilder,\n\tMutationBuilder,\n\tNamedIndex,\n\tQuery,\n\tQueryBuilder,\n\tQueryInitializer,\n\tUserIdentity,\n} from 'convex/server'\nimport type { Triggers } from 'convex-helpers/server/triggers'\nimport type { TableNamesInDataModel } from 'convex/server'\nimport { defaultErrors, type ErrorFactory } from './errors'\nimport {\n\tregisterQueryReader,\n\tsuppliedPolicyRules,\n\ttype SecurityPolicyContext,\n} from './querying/security'\nexport type { SecurityPolicyContext } from './querying/security'\nimport {\n\tcomposeRules,\n\tcreateTenantRules,\n\twrapDatabaseReader,\n\twrapDatabaseWriter,\n\ttype RLSConfig,\n\ttype Rules,\n} from './tenancy'\n\n/** The default vocabulary; every app can supply its own via the Role generic. */\nexport type DefaultRole = 'reader' | 'writer' | 'admin'\n\nexport type Actor<Role extends string> = Readonly<{\n\tuserId: string\n\torganizationId: string\n\trole: Role\n}>\n\nexport type AuthBundle<Role extends string> = Readonly<{\n\tidentity: UserIdentity\n\tuser: Readonly<{ id: string }>\n\torg: Readonly<{ organizationId: string; role: Role }>\n\trole: Role\n\tactor: Actor<Role>\n\t/** The resolved tenant — security.tenancy.resolve, or the organization id. */\n\ttenant: string\n}>\n\n/**\n * The bundle handed to security rules. Service principals (serviceQuery /\n * serviceMutation) may carry extra host-supplied fields beside the standard\n * bundle; rules read them as unknown and narrow as needed.\n */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type SecurityBundle<Role extends string> = AuthBundle<Role> & ServiceExtras\n\n/** Extra fields a host factory attaches to a service principal. */\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- Host extras are open by design; rules narrow the fields they own.\nexport type ServiceExtras = Readonly<Record<string, unknown>>\n\n/**\n * A trusted host factory producing the principal a service function runs as.\n * `args` are the raw (unparsed) arguments of the invocation, so the host can\n * derive the scope (e.g. a client id) from them. Never accept the principal\n * itself from the caller — only derive it.\n */\nexport type ServicePrincipal<Ctx, Role extends string, Extra extends Record<string, unknown>> = (\n\tctx: Ctx,\n\targs: DefaultFunctionArgs,\n) => (AuthBundle<Role> & Extra) | Promise<AuthBundle<Role> & Extra>\n\n/**\n * Row-level security configuration. Tenant isolation and role-level rules\n * compose (AND) onto the same wrapped database: queries get a wrapped\n * reader, mutations get triggers first, then a wrapped writer.\n */\nexport type SecurityConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/**\n\t * Tenant isolation. `tables` is THE registry: every listed table gets\n\t * read/insert/modify gated on row.tenant === ctx.tenant. Pair with\n\t * tenantTable (schema) and tenantOwnership (triggers) on the same list.\n\t */\n\ttenancy?: {\n\t\ttables: readonly TableNamesInDataModel<DataModel>[]\n\t\t/** Maps the auth bundle to the tenant; defaults to org.organizationId. */\n\t\tresolve?: (bundle: Omit<AuthBundle<Role>, 'tenant'>) => string\n\t}\n\t/**\n\t * Role-level (or any policy) rules derived from the authenticated bundle,\n\t * composed AND-wise with tenant isolation. E.g. gate `modify` on a table\n\t * to admin roles.\n\t */\n\trules?: (bundle: SecurityBundle<Role>) => Rules<SecurityPolicyContext<DataModel>, DataModel>\n\t/**\n\t * Policy for tables with no rule. Defaults to 'deny' when tenancy is\n\t * configured (unlisted tables are unreachable — fail closed), 'allow'\n\t * otherwise.\n\t */\n\tdefaultPolicy?: RLSConfig['defaultPolicy']\n}\n\ntype AnyAuthContext<DataModel extends GenericDataModel> =\n\t| GenericQueryCtx<DataModel>\n\t| GenericMutationCtx<DataModel>\n\t| GenericActionCtx<DataModel>\n\n/**\n * Configuration for createAuthReaders: everything createAuthFunctions takes\n * except the mutation builders and trigger wrapping, so a module built from\n * it never has to import the trigger registry.\n */\nexport type AuthReadersConfig<DataModel extends GenericDataModel, Role extends string> = {\n\t/** The consumer's generated function builders (from ./_generated/server). */\n\tquery: QueryBuilder<DataModel, 'public'>\n\taction: ActionBuilder<DataModel, 'public'>\n\tinternalQuery: QueryBuilder<DataModel, 'internal'>\n\tinternalAction: ActionBuilder<DataModel, 'internal'>\n\t/**\n\t * Resolves the synchronized principal, e.g. (ctx) => authKit.getAuthUser(ctx).\n\t * The already-resolved, non-null identity is supplied as a second argument.\n\t * Callbacks may ignore it; using it can avoid a redundant identity lookup.\n\t */\n\tgetAuthUser: (\n\t\tctx: AnyAuthContext<DataModel>,\n\t\tidentity: UserIdentity,\n\t) => Promise<{ id: string } | null>\n\t/**\n\t * Maps an identity role slug onto the app's role vocabulary. Returning\n\t * null rejects the caller with FORBIDDEN — unknown roles never pass.\n\t */\n\tmapRole: (roleSlug?: string) => Role | null\n\t/** Roles allowed through the admin* constructors. */\n\tadminRoles: readonly NoInfer<Role>[]\n\t/**\n\t * Live membership check for actions (queries/mutations trust the JWT).\n\t * Authentication fails closed with FORBIDDEN when verification errors.\n\t * Omit to let actions trust the JWT like queries do.\n\t */\n\tverifyMembership?: (input: {\n\t\tuserId: string\n\t\torganizationId: string\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/**\n\t * Resolves organization authority from the app's own data for identity\n\t * providers whose tokens carry no org claims. When configured, its result\n\t * overrides claim-based resolution; null or an error rejects with FORBIDDEN\n\t * (fail closed). In actions the ctx has no db — resolve via ctx.runQuery.\n\t */\n\tresolveOrganization?: (input: {\n\t\tctx: AnyAuthContext<DataModel>\n\t\tidentity: UserIdentity\n\t\tuser: { id: string }\n\t}) => Promise<{ organizationId: string; roleSlug: string } | null>\n\t/** Host error policy; defaults to throwing KitError. */\n\terrors?: ErrorFactory\n\t/** Upper bound for include() reads. */\n\tmaxIncludedQueryRows?: number\n\t/**\n\t * How argument validation failures are thrown by every constructor. `'validation'`\n\t * (default) throws `KValidationError` (`ConvexError({ code: 'VALIDATION', issues })`);\n\t * `'declared'` throws `argumentErrors` `INVALID_ARGUMENTS`; a function returns the value to throw.\n\t */\n\targumentFailure?: ArgumentFailurePolicy\n\t/**\n\t * Row-level security: tenant isolation (from a table registry) and\n\t * role-level rules, applied structurally inside every auth*, role*,\n\t * admin*, and service* constructor. system* constructors stay unwrapped\n\t * (trusted).\n\t */\n\tsecurity?: SecurityConfig<DataModel, Role>\n}\n\n/** A reader config plus the mutation builders and trigger wrapping. */\nexport type AuthFunctionsConfig<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n> = AuthReadersConfig<DataModel, Role> & {\n\tmutation: MutationBuilder<DataModel, 'public'>\n\tinternalMutation: MutationBuilder<DataModel, 'internal'>\n\t/**\n\t * Application trigger registry. When set, every authMutation,\n\t * roleMutation, and systemMutation write runs through triggers.wrapDB —\n\t * evaluations registered on tables fire structurally.\n\t */\n\ttriggers?: Triggers<DataModel>\n\t/** Lower-level alternative to `triggers`: a custom ctx wrapper. */\n\twrapDB?: (ctx: GenericMutationCtx<DataModel>) => GenericMutationCtx<DataModel>\n}\n\n/** WorkOS-style default: `member` writes; reader/writer/admin pass through. */\nexport function defaultRoleMap(roleSlug?: string): DefaultRole | null {\n\tconst normalized = roleSlug?.trim().toLowerCase()\n\tif (normalized === 'member') return 'writer'\n\treturn normalized === 'reader' || normalized === 'writer' || normalized === 'admin'\n\t\t? normalized\n\t\t: null\n}\n\nexport type IncludedQuery<Table extends GenericTableInfo> = {\n\twhen<Value>(\n\t\tvalue: Value | null | undefined,\n\t\tselect: (query: QueryInitializer<Table>, value: Value) => Query<Table>,\n\t): IncludedQuery<Table>\n\tmatching<IndexName extends IndexNames<Table>>(\n\t\tindexName: IndexName,\n\t\tindexRange?: (\n\t\t\tquery: IndexRangeBuilder<DocumentByInfo<Table>, NamedIndex<Table, IndexName>>,\n\t\t) => IndexRange,\n\t\tshouldMatch?: boolean,\n\t): IncludedQuery<Table>\n\totherwise(select: (query: QueryInitializer<Table>) => Query<Table>): Query<Table>\n\tresolve(): Query<Table>\n\texecute(limit: number): Promise<DocumentByInfo<Table>[]>\n\texecute<Result>(\n\t\tlimit: number,\n\t\ttransform: (data: Awaited<ReturnType<Query<Table>['take']>>) => Result | Promise<Result>,\n\t): Promise<Result>\n\t/**\n\t * Cursor pagination over the selected indexed query. numItems is bounded\n\t * by the same maxRows policy as execute(). Under row-level security a\n\t * page may be shorter than numItems (rejected rows are filtered after\n\t * pagination); cursors remain correct. Pair with paginated(dto) from\n\t * cvx-kit/table for the boundary schemas.\n\t */\n\tpaginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\tpaginate<Item>(\n\t\topts: PaginationOptions,\n\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t): Promise<PaginationResult<Item>>\n}\n\nexport type Include = <Table extends GenericTableInfo>(\n\tquery: QueryInitializer<Table>,\n) => IncludedQuery<Table>\n\n/**\n * The auth-aware constructors, registered through `k` schemas and native validators\n * (src/registration.ts). Keep native contexts symbolic in published declarations: inferred spreads\n * copy build-time Convex methods and override the consumer's native context.\n */\nexport type AuthFunctions<DataModel extends GenericDataModel, Role extends string = DefaultRole> = {\n\tinclude: Include\n\tauthenticatedUser: (ctx: AnyAuthContext<DataModel>) => Promise<AuthBundle<Role>>\n\tauthQuery: KCustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthMutation: KCustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & AuthBundle<Role> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\tauthAction: KCustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel> & AuthBundle<Role>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'public',\n\t\tobject\n\t>\n\troleQuery: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authQuery']\n\troleMutation: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authMutation']\n\troleAction: (...allowed: readonly Role[]) => AuthFunctions<DataModel, Role>['authAction']\n\tadminQuery: AuthFunctions<DataModel, Role>['authQuery']\n\tadminMutation: AuthFunctions<DataModel, Role>['authMutation']\n\tadminAction: AuthFunctions<DataModel, Role>['authAction']\n\t/**\n\t * Internal query running as a host-supplied service principal with the\n\t * app's security rules fully applied. No identity lookup; the trusted\n\t * host's factory is the only principal source.\n\t */\n\tserviceQuery: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t) => ServiceQuery<DataModel, Role, Extra>\n\t/** Internal mutation running as a service principal: triggers first, then the secured writer. */\n\tserviceMutation: <Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t) => ServiceMutation<DataModel, Role, Extra>\n\tsystemQuery: KCustomBuilder<\n\t\t'query',\n\t\t{},\n\t\tGenericQueryCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericQueryCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemMutation: KCustomBuilder<\n\t\t'mutation',\n\t\t{},\n\t\tGenericMutationCtx<DataModel> & { include: Include },\n\t\t{},\n\t\tGenericMutationCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n\tsystemAction: KCustomBuilder<\n\t\t'action',\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t{},\n\t\tGenericActionCtx<DataModel>,\n\t\t'internal',\n\t\tobject\n\t>\n}\n\n/** The read-only constructors: everything AuthFunctions has except mutations. */\nexport type AuthReaders<\n\tDataModel extends GenericDataModel,\n\tRole extends string = DefaultRole,\n> = Omit<AuthFunctions<DataModel, Role>, `${string}Mutation`>\n\nexport type ServiceQuery<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = KCustomBuilder<\n\t'query',\n\t{},\n\tGenericQueryCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericQueryCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\nexport type ServiceMutation<\n\tDataModel extends GenericDataModel,\n\tRole extends string,\n\tExtra extends Record<string, unknown> = {},\n> = KCustomBuilder<\n\t'mutation',\n\t{},\n\tGenericMutationCtx<DataModel> & AuthBundle<Role> & Extra & { include: Include },\n\t{},\n\tGenericMutationCtx<DataModel>,\n\t'internal',\n\tobject\n>\n\n/** Builds an include() that selects the first matching indexed query and bounds the read. */\nexport function createInclude(options?: { errors?: ErrorFactory; maxRows?: number }): Include {\n\tconst errors = options?.errors ?? defaultErrors\n\tconst maxRows = options?.maxRows ?? 100\n\n\tfunction attach<Table extends GenericTableInfo>(\n\t\tquery: QueryInitializer<Table>,\n\t\tselected?: Query<Table>,\n\t): IncludedQuery<Table> {\n\t\tfunction execute(limit: number): Promise<DocumentByInfo<Table>[]>\n\t\tfunction execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t): Promise<Result>\n\t\tasync function execute<Result>(\n\t\t\tlimit: number,\n\t\t\ttransform?: (data: DocumentByInfo<Table>[]) => Result | Promise<Result>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(limit) || limit < 1 || limit > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A bounded query limit must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst data = await (selected ?? query.fullTableScan()).take(limit)\n\t\t\treturn transform ? transform(data) : data\n\t\t}\n\t\tfunction paginate(opts: PaginationOptions): Promise<PaginationResult<DocumentByInfo<Table>>>\n\t\tfunction paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t): Promise<PaginationResult<Item>>\n\t\tasync function paginate<Item>(\n\t\t\topts: PaginationOptions,\n\t\t\ttransform?: (page: DocumentByInfo<Table>[]) => Item[] | Promise<Item[]>,\n\t\t) {\n\t\t\tif (!Number.isSafeInteger(opts.numItems) || opts.numItems < 1 || opts.numItems > maxRows) {\n\t\t\t\treturn errors.throw({\n\t\t\t\t\tcode: 'INVALID_REQUEST_BOUNDARY',\n\t\t\t\t\tmessage: `A page size must be from 1 to ${maxRows}`,\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst result = await (selected ?? query.fullTableScan()).paginate(opts)\n\t\t\treturn transform ? { ...result, page: await transform(result.page) } : result\n\t\t}\n\t\treturn {\n\t\t\twhen: (value, select) =>\n\t\t\t\tselected || value === undefined || value === null\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, select(query, value)),\n\t\t\tmatching: (indexName, indexRange, shouldMatch = true) =>\n\t\t\t\tselected || !shouldMatch\n\t\t\t\t\t? attach(query, selected)\n\t\t\t\t\t: attach(query, query.withIndex(indexName, indexRange)),\n\t\t\totherwise: (select) => selected ?? select(query),\n\t\t\tresolve: () => selected ?? query.fullTableScan(),\n\t\t\texecute,\n\t\t\tpaginate,\n\t\t}\n\t}\n\n\treturn (query) => attach(query)\n}\n\n/**\n * Builds the auth-aware function constructors from the host's injected\n * policy: identity resolution, the app's own role vocabulary, live\n * membership verification for actions, trigger wrapping for mutations,\n * and errors. Role-based access is first-class — every constructor family\n * has a role-gated variant (roleQuery/roleMutation/roleAction), and the\n * admin* constructors are just that gate applied to config.adminRoles.\n */\nexport function createAuthFunctions<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthFunctionsConfig<DataModel, Role>): AuthFunctions<DataModel, Role> {\n\tconst core = createAuthCore(config)\n\tconst inputs = createMutationInputs(config, core)\n\tconst { kCustomMutation } = core.builders\n\n\t/** Internal mutation running as the host-derived service principal: triggers, then rules. */\n\tfunction serviceMutation<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t): ServiceMutation<DataModel, Role, Extra> {\n\t\treturn kCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: inputs.serviceMutationInput(principal),\n\t\t})\n\t}\n\n\t/** Mutation constructor allowing only the given roles. */\n\tfunction roleMutation(...allowed: readonly Role[]) {\n\t\treturn kCustomMutation(config.mutation, { args: {}, input: inputs.roleMutationInput(allowed) })\n\t}\n\n\treturn {\n\t\t...readers(config, core),\n\t\troleMutation,\n\t\tauthMutation: kCustomMutation(config.mutation, { args: {}, input: inputs.mutationInput }),\n\t\tadminMutation: roleMutation(...config.adminRoles),\n\t\tserviceMutation,\n\t\tsystemMutation: kCustomMutation(config.internalMutation, {\n\t\t\targs: {},\n\t\t\tinput: inputs.systemMutationInput,\n\t\t}),\n\t}\n}\n\n/**\n * Builds the read-only constructors (queries and actions) from the same\n * policy as createAuthFunctions, without mutation builders or triggers.\n * Identity, tenancy, rules, role gates, membership checks and errors are the\n * same implementation, so a module built from these never imports the\n * trigger registry or the domains it pulls in.\n */\nexport function createAuthReaders<\n\tDataModel extends GenericDataModel,\n\tconst Role extends string = DefaultRole,\n>(config: AuthReadersConfig<DataModel, Role>): AuthReaders<DataModel, Role> {\n\treturn readers(config, createAuthCore(config))\n}\n\ntype AuthCore<DataModel extends GenericDataModel, Role extends string> = ReturnType<\n\ttypeof createAuthCore<DataModel, Role>\n>\n\n/** Assembly of the read-only constructors. */\nfunction readers<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n\tcore: AuthCore<DataModel, Role>,\n): AuthReaders<DataModel, Role> {\n\tconst { kCustomQuery, kCustomAction } = core.builders\n\t/** Internal query running as the host-derived service principal, rules applied. */\n\tfunction serviceQuery<Extra extends Record<string, unknown> = {}>(\n\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t): ServiceQuery<DataModel, Role, Extra> {\n\t\treturn kCustomQuery(config.internalQuery, {\n\t\t\targs: {},\n\t\t\tinput: core.serviceQueryInput(principal),\n\t\t})\n\t}\n\n\t/** Query constructor allowing only the given roles. */\n\tfunction roleQuery(...allowed: readonly Role[]) {\n\t\treturn kCustomQuery(config.query, { args: {}, input: core.roleQueryInput(allowed) })\n\t}\n\n\t/** Action constructor allowing only the given roles (post live verification). */\n\tfunction roleAction(...allowed: readonly Role[]) {\n\t\treturn kCustomAction(config.action, { args: {}, input: core.roleActionInput(allowed) })\n\t}\n\n\treturn {\n\t\tinclude: core.include,\n\t\tauthenticatedUser: core.authenticatedUser,\n\t\troleQuery,\n\t\troleAction,\n\t\tauthQuery: kCustomQuery(config.query, { args: {}, input: core.queryInput }),\n\t\tauthAction: kCustomAction(config.action, { args: {}, input: core.actionInput }),\n\t\tadminQuery: roleQuery(...config.adminRoles),\n\t\tadminAction: roleAction(...config.adminRoles),\n\t\tserviceQuery,\n\t\tsystemQuery: kCustomQuery(config.internalQuery, { args: {}, input: core.systemQueryInput }),\n\t\tsystemAction: kCustomAction(config.internalAction, {\n\t\t\targs: {},\n\t\t\tinput: core.systemActionInput,\n\t\t}),\n\t}\n}\n\n/** The mutation customizations createAuthFunctions adds to the readers. */\nfunction createMutationInputs<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthFunctionsConfig<DataModel, Role>,\n\tcore: AuthCore<DataModel, Role>,\n) {\n\tconst { include, secureWriter, servicePrincipal, requireRole } = core\n\tconst triggers = config.triggers\n\tconst wrapDB = triggers\n\t\t? (ctx: GenericMutationCtx<DataModel>) => triggers.wrapDB(ctx)\n\t\t: (config.wrapDB ?? ((ctx) => ctx))\n\n\tasync function mutationInput(ctx: GenericMutationCtx<DataModel>) {\n\t\tconst bundle = await core.authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\treturn {\n\t\tmutationInput,\n\t\tserviceMutationInput:\n\t\t\t<Extra extends Record<string, unknown>>(\n\t\t\t\tprincipal: ServicePrincipal<GenericMutationCtx<DataModel>, Role, Extra>,\n\t\t\t) =>\n\t\t\tasync (ctx: GenericMutationCtx<DataModel>) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureWriter(wrapDB(ctx), bundle), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\troleMutationInput: (allowed: readonly Role[]) => async (ctx: GenericMutationCtx<DataModel>) => {\n\t\t\tconst authenticated = await mutationInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\tsystemMutationInput: async (ctx: GenericMutationCtx<DataModel>) => ({\n\t\t\tctx: { ...wrapDB(ctx), include },\n\t\t\targs: {},\n\t\t}),\n\t}\n}\n\n/** Shared implementation behind the constructors: everything but the registration builders. */\nfunction createAuthCore<DataModel extends GenericDataModel, Role extends string>(\n\tconfig: AuthReadersConfig<DataModel, Role>,\n) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst builders = kCustomFunctions({ argumentFailure: config.argumentFailure })\n\tconst include = createInclude({\n\t\terrors,\n\t\tmaxRows: config.maxIncludedQueryRows,\n\t})\n\n\tasync function authenticatedUser(ctx: AnyAuthContext<DataModel>): Promise<AuthBundle<Role>> {\n\t\tconst identity = await ctx.auth.getUserIdentity()\n\t\tconst user = identity ? await config.getAuthUser(ctx, identity) : null\n\t\tif (!identity || !user) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\tlet organizationId: string\n\t\tlet organizationRole: string | undefined\n\t\tif (config.resolveOrganization) {\n\t\t\t// The hook is the organization authority — claims are skipped\n\t\t\t// entirely. Authentication fails closed when it errors or abstains.\n\t\t\tlet resolved: { organizationId: string; roleSlug: string } | null = null\n\t\t\ttry {\n\t\t\t\tresolved = await config.resolveOrganization({ ctx, identity, user })\n\t\t\t} catch {\n\t\t\t\t// Authentication fails closed when the hook cannot resolve.\n\t\t\t}\n\t\t\tif (!resolved) return errors.throw({ code: 'FORBIDDEN' })\n\t\t\torganizationId = resolved.organizationId\n\t\t\torganizationRole = resolved.roleSlug\n\t\t} else {\n\t\t\tconst claims = organizationClaims(identity)\n\t\t\tif (!claims.organizationId) return errors.throw({ code: 'UNAUTHENTICATED' })\n\t\t\torganizationId = claims.organizationId\n\t\t\torganizationRole = claims.role\n\t\t}\n\t\tconst role = config.mapRole(organizationRole)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst base = {\n\t\t\tidentity,\n\t\t\tuser: Object.freeze({ id: user.id }),\n\t\t\torg: Object.freeze({ organizationId, role }),\n\t\t\trole,\n\t\t\tactor: Object.freeze({ userId: user.id, organizationId, role }),\n\t\t}\n\t\treturn Object.freeze({\n\t\t\t...base,\n\t\t\ttenant: config.security?.tenancy?.resolve?.(base) ?? organizationId,\n\t\t})\n\t}\n\n\tconst securityConfig: RLSConfig | undefined = config.security\n\t\t? {\n\t\t\t\tdefaultPolicy:\n\t\t\t\t\tconfig.security.defaultPolicy ?? (config.security.tenancy ? 'deny' : 'allow'),\n\t\t\t}\n\t\t: undefined\n\n\tfunction securityRules(\n\t\tbundle: AuthBundle<Role>,\n\t): Rules<SecurityPolicyContext<DataModel>, DataModel> | undefined {\n\t\tconst security = config.security\n\t\tif (!security) return undefined\n\t\tconst sets: Rules<SecurityPolicyContext<DataModel>, DataModel>[] = []\n\t\tif (security.tenancy) {\n\t\t\tsets.push(createTenantRules<DataModel>(bundle.tenant, security.tenancy.tables))\n\t\t}\n\t\tif (security.rules) sets.push(security.rules(bundle))\n\t\treturn sets.length === 1 ? sets[0] : composeRules(...sets)\n\t}\n\n\tfunction secureReader(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t\tmode: 'authenticated' | 'trusted' = 'authenticated',\n\t): GenericQueryCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tconst defaultPolicy = securityConfig?.defaultPolicy ?? 'allow'\n\t\tconst ordinary = rules\n\t\t\t? wrapDatabaseReader(\n\t\t\t\t\t{ db: ctx.db },\n\t\t\t\t\tctx.db,\n\t\t\t\t\tsuppliedPolicyRules(ctx.db, rules, defaultPolicy),\n\t\t\t\t\tsecurityConfig,\n\t\t\t\t)\n\t\t\t: ctx.db\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: registerQueryReader(ctx.db, ordinary, {\n\t\t\t\tscope: {\n\t\t\t\t\tmode,\n\t\t\t\t\tprincipal: bundle.user.id,\n\t\t\t\t\torganization: bundle.org.organizationId,\n\t\t\t\t\ttenant: bundle.tenant,\n\t\t\t\t\trole: bundle.role,\n\t\t\t\t},\n\t\t\t\trules: rules ?? {},\n\t\t\t\tdefaultPolicy,\n\t\t\t}),\n\t\t}\n\t}\n\n\tfunction secureWriter(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tbundle: AuthBundle<Role>,\n\t): GenericMutationCtx<DataModel> {\n\t\tconst rules = securityRules(bundle)\n\t\tif (!rules) return ctx\n\t\t// Triggers wrap first (ctx already trigger-wrapped by the caller),\n\t\t// then row-level security wraps the triggered db — order matters.\n\t\treturn {\n\t\t\t...ctx,\n\t\t\tdb: wrapDatabaseWriter(\n\t\t\t\t{ db: ctx.db },\n\t\t\t\tctx.db,\n\t\t\t\tsuppliedPolicyRules(ctx.db, rules, securityConfig?.defaultPolicy ?? 'allow'),\n\t\t\t\tsecurityConfig,\n\t\t\t),\n\t\t}\n\t}\n\n\tasync function verifiedMembership(userId: string, organizationId: string) {\n\t\tif (!config.verifyMembership) return null\n\t\ttry {\n\t\t\tconst membership = await config.verifyMembership({\n\t\t\t\tuserId,\n\t\t\t\torganizationId,\n\t\t\t})\n\t\t\tif (membership && membership.organizationId === organizationId) {\n\t\t\t\treturn membership\n\t\t\t}\n\t\t} catch {\n\t\t\t// Authentication fails closed when membership cannot be verified.\n\t\t}\n\t\treturn errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tfunction requireRole(role: Role, allowed: readonly Role[]) {\n\t\tif (!allowed.includes(role)) return errors.throw({ code: 'FORBIDDEN' })\n\t}\n\n\tasync function queryInput(ctx: GenericQueryCtx<DataModel>) {\n\t\tconst bundle = await authenticatedUser(ctx)\n\t\treturn {\n\t\t\tctx: { ...secureReader(ctx, bundle), include, ...bundle },\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function actionInput(ctx: GenericActionCtx<DataModel>) {\n\t\tconst authenticated = await authenticatedUser(ctx)\n\t\tconst membership = await verifiedMembership(\n\t\t\tauthenticated.user.id,\n\t\t\tauthenticated.org.organizationId,\n\t\t)\n\t\tif (!membership) return { ctx: { ...ctx, ...authenticated }, args: {} }\n\t\tconst role = config.mapRole(membership.roleSlug)\n\t\tif (!role) return errors.throw({ code: 'FORBIDDEN' })\n\t\tconst verified = {\n\t\t\tidentity: authenticated.identity,\n\t\t\tuser: authenticated.user,\n\t\t\torg: Object.freeze({\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t\trole,\n\t\t\tactor: Object.freeze({\n\t\t\t\tuserId: authenticated.user.id,\n\t\t\t\torganizationId: membership.organizationId,\n\t\t\t\trole,\n\t\t\t}),\n\t\t}\n\t\treturn {\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\t...verified,\n\t\t\t\t// Tenant re-derives from the live-verified organization.\n\t\t\t\ttenant: config.security?.tenancy?.resolve?.(verified) ?? membership.organizationId,\n\t\t\t},\n\t\t\targs: {},\n\t\t}\n\t}\n\n\tasync function servicePrincipal<\n\t\tCtx extends GenericQueryCtx<DataModel> | GenericMutationCtx<DataModel>,\n\t\tExtra extends Record<string, unknown>,\n\t>(principal: ServicePrincipal<Ctx, Role, Extra>, ctx: Ctx) {\n\t\tconst bundle = await principal(ctx, rawFunctionArgs(ctx))\n\t\tif (!principalContract().safeParse(bundle).success) {\n\t\t\tthrow new Error('A service principal must be an AuthBundle with user.id and tenant')\n\t\t}\n\t\t// Extras are spread onto the secured ctx; a host field named like a native\n\t\t// handle (db, auth, scheduler, ...) would silently replace the secured one.\n\t\tconst reserved = Object.keys(bundle).filter((key) => key in ctx)\n\t\tif (reserved.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`A service principal cannot override native context fields: ${reserved.join(', ')}`,\n\t\t\t)\n\t\t}\n\t\treturn bundle\n\t}\n\n\treturn {\n\t\tbuilders,\n\t\tinclude,\n\t\tauthenticatedUser,\n\t\tsecureWriter,\n\t\tservicePrincipal,\n\t\trequireRole,\n\t\tqueryInput,\n\t\tactionInput,\n\t\tserviceQueryInput:\n\t\t\t<Extra extends Record<string, unknown>>(\n\t\t\t\tprincipal: ServicePrincipal<GenericQueryCtx<DataModel>, Role, Extra>,\n\t\t\t) =>\n\t\t\tasync (ctx: GenericQueryCtx<DataModel>) => {\n\t\t\t\tconst bundle = await servicePrincipal(principal, ctx)\n\t\t\t\treturn {\n\t\t\t\t\tctx: { ...secureReader(ctx, bundle, 'trusted'), ...bundle, include },\n\t\t\t\t\targs: {},\n\t\t\t\t}\n\t\t\t},\n\t\troleQueryInput: (allowed: readonly Role[]) => async (ctx: GenericQueryCtx<DataModel>) => {\n\t\t\tconst authenticated = await queryInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\troleActionInput: (allowed: readonly Role[]) => async (ctx: GenericActionCtx<DataModel>) => {\n\t\t\tconst authenticated = await actionInput(ctx)\n\t\t\trequireRole(authenticated.ctx.actor.role, allowed)\n\t\t\treturn authenticated\n\t\t},\n\t\tsystemQueryInput: async (ctx: GenericQueryCtx<DataModel>) => ({\n\t\t\tctx: {\n\t\t\t\t...ctx,\n\t\t\t\tinclude,\n\t\t\t\tdb: registerQueryReader(ctx.db, ctx.db, {\n\t\t\t\t\tscope: {\n\t\t\t\t\t\tmode: 'system',\n\t\t\t\t\t\tprincipal: null,\n\t\t\t\t\t\torganization: null,\n\t\t\t\t\t\ttenant: null,\n\t\t\t\t\t\trole: null,\n\t\t\t\t\t},\n\t\t\t\t\trules: {},\n\t\t\t\t\tdefaultPolicy: 'allow',\n\t\t\t\t}),\n\t\t\t},\n\t\t\targs: {},\n\t\t}),\n\t\tsystemActionInput: async (ctx: GenericActionCtx<DataModel>) => ({ ctx, args: {} }),\n\t}\n}\n\n/** The minimum a host factory must return; unknown keys pass, the rest of the bundle is the host's contract. */\nconst principalContract = memoize(() =>\n\tk.object({ user: k.object({ id: k.string() }).strip(), tenant: k.string() }).strip(),\n)\n\n/** The organization authority an identity's claims carry; each claim is undefined when malformed. */\nfunction organizationClaims(identity: UserIdentity) {\n\tconst organization = claimRecord(identity.organization)\n\treturn {\n\t\torganizationId: claimString(organization?.organizationId) ?? claimString(identity.org_id),\n\t\trole: claimString(organization?.role) ?? claimString(identity.role),\n\t}\n}\n\n/* oxlint-disable anti-slop/no-runtime-typeof -- Identity claims are undecoded JSON narrowed by representation. */\nfunction claimString(value: JSONValue | undefined): string | undefined {\n\treturn typeof value === 'string' ? value : undefined\n}\n\nfunction claimRecord(value: JSONValue | undefined): { [key: string]: JSONValue } | undefined {\n\treturn value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined\n}\n/* oxlint-enable anti-slop/no-runtime-typeof */\n"],"mappings":"A,4ZA6MA,SAAgBA,EAAe,EAAuC,CACrE,IAAMC,EAAaC,GAAU,KAAK,CAAC,CAAC,YAAY,EAEhD,OADID,IAAe,SAAiB,SAC7BA,IAAe,UAAYA,IAAe,UAAYA,IAAe,QACzEA,EACA,IACJ,CA4JA,SAAgBE,EAAc,EAAgE,CAC7F,IAAMC,EAASC,GAAS,QAAUC,EAC5BC,EAAUF,GAAS,SAAW,IAEpC,SAASG,EACR,EACA,EACuB,CAMvB,eAAeC,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,CAAK,GAAKA,EAAQ,GAAKA,EAAQH,EACxD,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,2CAA2CG,GACrD,CAAC,EAEF,IAAMI,EAAO,MAAOC,GAAYC,EAAM,cAAc,EAAA,CAAG,KAAKH,CAAK,EACjE,OAAOI,EAAYA,EAAUH,CAAI,EAAIA,CACtC,CAMA,eAAeI,EACd,EACA,EACC,CACD,GAAI,CAAC,OAAO,cAAcC,EAAK,QAAQ,GAAKA,EAAK,SAAW,GAAKA,EAAK,SAAWT,EAChF,OAAOH,EAAO,MAAM,CACnB,KAAM,2BACN,QAAS,iCAAiCG,GAC3C,CAAC,EAEF,IAAMU,EAAS,MAAOL,GAAYC,EAAM,cAAc,EAAA,CAAG,SAASG,CAAI,EACtE,OAAOF,EAAY,CAA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AA,EACvF,C"}
|
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
import { audit_d_exports } from "../audit.mjs";
|
|
2
|
-
import { validators_d_exports } from "../validators.mjs";
|
|
3
|
-
import { constants_d_exports } from "../constants.mjs";
|
|
4
|
-
import { workflow_steps_d_exports } from "../workflow_steps.mjs";
|
|
5
2
|
import { client_d_exports } from "../client.mjs";
|
|
3
|
+
import { constants_d_exports } from "../constants.mjs";
|
|
6
4
|
import { decisions_d_exports } from "../decisions.mjs";
|
|
7
5
|
import { functions_d_exports } from "../functions.mjs";
|
|
8
6
|
import { health_d_exports } from "../health.mjs";
|
|
9
7
|
import { requests_d_exports } from "../requests.mjs";
|
|
8
|
+
import { validators_d_exports } from "../validators.mjs";
|
|
10
9
|
import { workflow_d_exports } from "../workflow.mjs";
|
|
10
|
+
import { workflow_steps_d_exports } from "../workflow_steps.mjs";
|
|
11
11
|
import { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
|
|
12
|
-
//#region src/components/approvals/_generated/api.d.ts
|
|
13
12
|
declare const fullApi: ApiFromModules<{
|
|
14
13
|
audit: typeof audit_d_exports;
|
|
15
14
|
client: typeof client_d_exports;
|
|
@@ -44,5 +43,5 @@ export declare const components: {
|
|
|
44
43
|
workflow: import("@convex-dev/workflow/_generated/component.js").ComponentApi<"workflow">;
|
|
45
44
|
auditLog: import("convex-audit-log/_generated/component.js").ComponentApi<"auditLog">;
|
|
46
45
|
};
|
|
47
|
-
|
|
46
|
+
export {};
|
|
48
47
|
//# sourceMappingURL=api.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.mjs","names":["api","anyApi","internal","components","componentsGeneric"],"sources":["../../../../src/components/approvals/_generated/api.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated `api` utility.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type * as audit from \"../audit.js\";\nimport type * as client from \"../client.js\";\nimport type * as constants from \"../constants.js\";\nimport type * as decisions from \"../decisions.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as health from \"../health.js\";\nimport type * as requests from \"../requests.js\";\nimport type * as validators from \"../validators.js\";\nimport type * as workflow from \"../workflow.js\";\nimport type * as workflow_steps from \"../workflow_steps.js\";\n\nimport type {\n ApiFromModules,\n FilterApi,\n FunctionReference,\n} from \"convex/server\";\nimport { anyApi, componentsGeneric } from \"convex/server\";\n\nconst fullApi: ApiFromModules<{\n audit: typeof audit;\n client: typeof client;\n constants: typeof constants;\n decisions: typeof decisions;\n functions: typeof functions;\n health: typeof health;\n requests: typeof requests;\n validators: typeof validators;\n workflow: typeof workflow;\n workflow_steps: typeof workflow_steps;\n}> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's public API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = api.myModule.myFunction;\n * ```\n */\nexport const api: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"public\">\n> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's internal API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = internal.myModule.myFunction;\n * ```\n */\nexport const internal: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"internal\">\n> = anyApi as any;\n\nexport const components = componentsGeneric() as unknown as {\n workflow: import(\"@convex-dev/workflow/_generated/component.js\").ComponentApi<\"workflow\">;\n auditLog: import(\"convex-audit-log/_generated/component.js\").ComponentApi<\"auditLog\">;\n};\n"],"mappings":"8DAiDA,MAAaA,EAGTC,EAUSC,EAGTD,EAESE,EAAaC,EAAkB"}
|
|
1
|
+
{"version":3,"file":"api.mjs","names":["api","anyApi","internal","components","componentsGeneric"],"sources":["../../../../src/components/approvals/_generated/api.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated `api` utility.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type * as audit from \"../audit.js\";\nimport type * as client from \"../client.js\";\nimport type * as constants from \"../constants.js\";\nimport type * as decisions from \"../decisions.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as health from \"../health.js\";\nimport type * as requests from \"../requests.js\";\nimport type * as validators from \"../validators.js\";\nimport type * as workflow from \"../workflow.js\";\nimport type * as workflow_steps from \"../workflow_steps.js\";\n\nimport type {\n ApiFromModules,\n FilterApi,\n FunctionReference,\n} from \"convex/server\";\nimport { anyApi, componentsGeneric } from \"convex/server\";\n\nconst fullApi: ApiFromModules<{\n audit: typeof audit;\n client: typeof client;\n constants: typeof constants;\n decisions: typeof decisions;\n functions: typeof functions;\n health: typeof health;\n requests: typeof requests;\n validators: typeof validators;\n workflow: typeof workflow;\n workflow_steps: typeof workflow_steps;\n}> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's public API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = api.myModule.myFunction;\n * ```\n */\nexport const api: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"public\">\n> = anyApi as any;\n\n/**\n * A utility for referencing Convex functions in your app's internal API.\n *\n * Usage:\n * ```js\n * const myFunctionReference = internal.myModule.myFunction;\n * ```\n */\nexport const internal: FilterApi<\n typeof fullApi,\n FunctionReference<any, \"internal\">\n> = anyApi as any;\n\nexport const components = componentsGeneric() as unknown as {\n workflow: import(\"@convex-dev/workflow/_generated/component.js\").ComponentApi<\"workflow\">;\n auditLog: import(\"convex-audit-log/_generated/component.js\").ComponentApi<\"auditLog\">;\n};\n"],"mappings":"A,8DAiDA,MAAaA,EAGTC,EAUSC,EAGTD,EAESE,EAAaC,EAAkB,E"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { FunctionReference } from "convex/server";
|
|
2
|
-
//#region src/components/approvals/_generated/component.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A utility for referencing a Convex component's exposed API.
|
|
5
4
|
*
|
|
@@ -299,5 +298,4 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
299
298
|
}, Name>;
|
|
300
299
|
};
|
|
301
300
|
};
|
|
302
|
-
//#endregion
|
|
303
301
|
//# sourceMappingURL=component.d.mts.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import _default from "../schema.js";
|
|
2
|
-
import { DataModelFromSchemaDefinition, DocumentByName, SystemTableNames, TableNamesInDataModel } from "convex/server";
|
|
3
2
|
import { GenericId } from "convex/values";
|
|
4
|
-
|
|
3
|
+
import { DataModelFromSchemaDefinition, DocumentByName, SystemTableNames, TableNamesInDataModel } from "convex/server";
|
|
5
4
|
/**
|
|
6
5
|
* The names of all of your Convex tables.
|
|
7
6
|
*/
|
|
@@ -36,5 +35,4 @@ export type Id<TableName extends TableNames | SystemTableNames> = GenericId<Tabl
|
|
|
36
35
|
* `mutationGeneric` to make them type-safe.
|
|
37
36
|
*/
|
|
38
37
|
export type DataModel = DataModelFromSchemaDefinition<typeof _default>;
|
|
39
|
-
//#endregion
|
|
40
38
|
//# sourceMappingURL=dataModel.d.mts.map
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { DataModel } from "./dataModel.mjs";
|
|
2
2
|
import { ActionBuilder, GenericActionCtx, GenericDatabaseReader, GenericDatabaseWriter, GenericMutationCtx, GenericQueryCtx, HttpActionBuilder, MutationBuilder, QueryBuilder } from "convex/server";
|
|
3
|
-
//#region src/components/approvals/_generated/server.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Define a query in this Convex app's public API.
|
|
6
5
|
*
|
|
@@ -111,5 +110,4 @@ export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
|
111
110
|
* for the guarantees Convex provides your functions.
|
|
112
111
|
*/
|
|
113
112
|
export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
|
|
114
|
-
//#endregion
|
|
115
113
|
//# sourceMappingURL=server.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","names":["query","queryGeneric","internalQuery","internalQueryGeneric","mutation","mutationGeneric","internalMutation","internalMutationGeneric","action","actionGeneric","internalAction","internalActionGeneric","httpAction","httpActionGeneric"],"sources":["../../../../src/components/approvals/_generated/server.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated utilities for implementing server-side Convex query and mutation functions.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type {\n ActionBuilder,\n HttpActionBuilder,\n MutationBuilder,\n QueryBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n GenericDatabaseReader,\n GenericDatabaseWriter,\n} from \"convex/server\";\nimport {\n actionGeneric,\n httpActionGeneric,\n queryGeneric,\n mutationGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"convex/server\";\nimport type { DataModel } from \"./dataModel.js\";\n\n/**\n * Define a query in this Convex app's public API.\n *\n * This function will be allowed to read your Convex database and will be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const query: QueryBuilder<DataModel, \"public\"> = queryGeneric;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to read from your Convex database. It will not be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const internalQuery: QueryBuilder<DataModel, \"internal\"> =\n internalQueryGeneric;\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * This function will be allowed to modify your Convex database and will be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const mutation: MutationBuilder<DataModel, \"public\"> = mutationGeneric;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to modify your Convex database. It will not be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const internalMutation: MutationBuilder<DataModel, \"internal\"> =\n internalMutationGeneric;\n\n/**\n * Define an action in this Convex app's public API.\n *\n * An action is a function which can execute any JavaScript code, including non-deterministic\n * code and code with side-effects, like calling third-party services.\n * They can be run in Convex's JavaScript environment or in Node.js using the \"use node\" directive.\n * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.\n *\n * @param func - The action. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped action. Include this as an `export` to name it and make it accessible.\n */\nexport const action: ActionBuilder<DataModel, \"public\"> = actionGeneric;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n */\nexport const internalAction: ActionBuilder<DataModel, \"internal\"> =\n internalActionGeneric;\n\n/**\n * Define an HTTP action.\n *\n * The wrapped function will be used to respond to HTTP requests received\n * by a Convex deployment if the requests matches the path and method where\n * this action is routed. Be sure to route your httpAction in `convex/http.js`.\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument\n * and a Fetch API `Request` object as its second.\n * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.\n */\nexport const httpAction: HttpActionBuilder = httpActionGeneric;\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type QueryCtx = GenericQueryCtx<DataModel>;\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type MutationCtx = GenericMutationCtx<DataModel>;\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * function run on the server.\n */\nexport type ActionCtx = GenericActionCtx<DataModel>;\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * The two entry points are {@link DatabaseReader.get}, which fetches a single\n * document by its {@link Id}, or {@link DatabaseReader.query}, which starts\n * building a query.\n */\nexport type DatabaseReader = GenericDatabaseReader<DataModel>;\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n */\nexport type DatabaseWriter = GenericDatabaseWriter<DataModel>;\n"],"mappings":"8LAwCA,MAAaA,EAA2CC,EAU3CC,EACXC,EAUWC,EAAiDC,EAUjDC,EACXC,EAaWC,EAA6CC,EAQ7CC,EACXC,EAaWC,EAAgCC"}
|
|
1
|
+
{"version":3,"file":"server.mjs","names":["query","queryGeneric","internalQuery","internalQueryGeneric","mutation","mutationGeneric","internalMutation","internalMutationGeneric","action","actionGeneric","internalAction","internalActionGeneric","httpAction","httpActionGeneric"],"sources":["../../../../src/components/approvals/_generated/server.ts"],"sourcesContent":["/* eslint-disable */\n/**\n * Generated utilities for implementing server-side Convex query and mutation functions.\n *\n * THIS CODE IS AUTOMATICALLY GENERATED.\n *\n * To regenerate, run `npx convex dev`.\n * @module\n */\n\nimport type {\n ActionBuilder,\n HttpActionBuilder,\n MutationBuilder,\n QueryBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n GenericDatabaseReader,\n GenericDatabaseWriter,\n} from \"convex/server\";\nimport {\n actionGeneric,\n httpActionGeneric,\n queryGeneric,\n mutationGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"convex/server\";\nimport type { DataModel } from \"./dataModel.js\";\n\n/**\n * Define a query in this Convex app's public API.\n *\n * This function will be allowed to read your Convex database and will be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const query: QueryBuilder<DataModel, \"public\"> = queryGeneric;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to read from your Convex database. It will not be accessible from the client.\n *\n * @param func - The query function. It receives a {@link QueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n */\nexport const internalQuery: QueryBuilder<DataModel, \"internal\"> =\n internalQueryGeneric;\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * This function will be allowed to modify your Convex database and will be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const mutation: MutationBuilder<DataModel, \"public\"> = mutationGeneric;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * This function will be allowed to modify your Convex database. It will not be accessible from the client.\n *\n * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n */\nexport const internalMutation: MutationBuilder<DataModel, \"internal\"> =\n internalMutationGeneric;\n\n/**\n * Define an action in this Convex app's public API.\n *\n * An action is a function which can execute any JavaScript code, including non-deterministic\n * code and code with side-effects, like calling third-party services.\n * They can be run in Convex's JavaScript environment or in Node.js using the \"use node\" directive.\n * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.\n *\n * @param func - The action. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped action. Include this as an `export` to name it and make it accessible.\n */\nexport const action: ActionBuilder<DataModel, \"public\"> = actionGeneric;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n */\nexport const internalAction: ActionBuilder<DataModel, \"internal\"> =\n internalActionGeneric;\n\n/**\n * Define an HTTP action.\n *\n * The wrapped function will be used to respond to HTTP requests received\n * by a Convex deployment if the requests matches the path and method where\n * this action is routed. Be sure to route your httpAction in `convex/http.js`.\n *\n * @param func - The function. It receives an {@link ActionCtx} as its first argument\n * and a Fetch API `Request` object as its second.\n * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.\n */\nexport const httpAction: HttpActionBuilder = httpActionGeneric;\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type QueryCtx = GenericQueryCtx<DataModel>;\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.\n */\nexport type MutationCtx = GenericMutationCtx<DataModel>;\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * function run on the server.\n */\nexport type ActionCtx = GenericActionCtx<DataModel>;\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * The two entry points are {@link DatabaseReader.get}, which fetches a single\n * document by its {@link Id}, or {@link DatabaseReader.query}, which starts\n * building a query.\n */\nexport type DatabaseReader = GenericDatabaseReader<DataModel>;\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n */\nexport type DatabaseWriter = GenericDatabaseWriter<DataModel>;\n"],"mappings":"A,8LAwCA,MAAaA,EAA2CC,EAU3CC,EACXC,EAUWC,EAAiDC,EAUjDC,EACXC,EAaWC,EAA6CC,EAQ7CC,EACXC,EAaWC,EAAgCC,E"}
|
|
@@ -35,6 +35,5 @@ export declare const cleanup: import("convex/server").RegisteredMutation<"public
|
|
|
35
35
|
}, Promise<number>>;
|
|
36
36
|
export declare function approvalAuditEvent(input: ApprovalAuditTransition): AuditEventInput;
|
|
37
37
|
export declare function logApprovalTransition(ctx: MutationCtx, input: ApprovalAuditTransition): Promise<void>;
|
|
38
|
-
//#endregion
|
|
39
38
|
export { audit_d_exports };
|
|
40
39
|
//# sourceMappingURL=audit.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{components as e}from"./_generated/api.mjs";import{mutation as t,query as n}from"./_generated/server.mjs";import{APPROVAL_AUDIT_RETENTION_CATEGORY as r,MAX_APPROVAL_AUDIT_RETENTION_DAYS as i}from"./constants.mjs";import{
|
|
1
|
+
import{components as e}from"./_generated/api.mjs";import{mutation as t,query as n}from"./_generated/server.mjs";import{APPROVAL_AUDIT_RETENTION_CATEGORY as r,MAX_APPROVAL_AUDIT_RETENTION_DAYS as i}from"./constants.mjs";import{approvalAuditEventProjection as a,approvalOptionalString as o}from"./validators.mjs";import{v as s}from"convex/values";import{AuditLog as c}from"convex-audit-log";const l=new c(e.auditLog,{samplingEnabled:!1}),u=n({args:{resourceType:s.string(),resourceRef:s.string(),limit:s.optional(s.number())},returns:s.array(s.object({action:s.string(),actorRef:s.optional(s.string()),correlationKey:s.string(),transition:s.string()})),handler:async(e,t)=>{let n=Math.max(1,Math.min(Math.trunc(t.limit??100),100)),r=await l.queryByResource(e,{resourceType:t.resourceType,resourceId:t.resourceRef,limit:n}),i=/* @__PURE__ */ new Map;for(let e of r){let t=h(e);t&&i.set(t.correlationKey,t)}return[...i.values()]}}),d=t({args:{olderThanDays:s.number(),batchSize:s.number()},returns:s.number(),handler:(e,t)=>{let n=m(t.olderThanDays,1,i,`olderThanDays`),a=m(t.batchSize,1,100,`batchSize`);return l.cleanup(e,{olderThanDays:n,batchSize:a,retentionCategory:r})}});function f(e){return{action:e.action,actorId:e.actorRef,resourceType:e.resourceType,resourceId:e.resourceRef,severity:e.severity??`info`,tags:[`approvals`],retentionCategory:r,metadata:{correlationKey:`${e.runId}:${e.transition}`,runId:e.runId,transition:e.transition}}}async function p(e,t){await l.log(e,f(t))}function m(e,t,n,r){if(!Number.isInteger(e)||e<t||e>n)throw Error(`${r} must be an integer between ${t} and ${n}`);return e}function h(e){let t=a.safeParse(e);if(!t.success)return null;let{action:n,actorId:r,metadata:i}=t.data,s=o.safeParse(r);return{action:n,actorRef:s.success?s.data:void 0,...i}}export{l as approvalAudit,f as approvalAuditEvent,d as cleanup,u as history,p as logApprovalTransition};
|
|
2
2
|
//# sourceMappingURL=audit.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"audit.mjs","names":["approvalAudit","AuditLog","components","history","query","v","limit","input","events","ctx","unique","event","projection","auditProjection","cleanup","mutation","olderThanDays","boundedInteger","MAX_APPROVAL_AUDIT_RETENTION_DAYS","batchSize","APPROVAL_AUDIT_RETENTION_CATEGORY","approvalAuditEvent","logApprovalTransition","value","minimum","maximum","name","
|
|
1
|
+
{"version":3,"file":"audit.mjs","names":["approvalAudit","AuditLog","components","history","query","v","limit","input","events","ctx","unique","event","projection","auditProjection","cleanup","mutation","olderThanDays","boundedInteger","MAX_APPROVAL_AUDIT_RETENTION_DAYS","batchSize","APPROVAL_AUDIT_RETENTION_CATEGORY","approvalAuditEvent","logApprovalTransition","value","minimum","maximum","name","parsed","approvalAuditEventProjection","actorRef","approvalOptionalString","actorId","metadata"],"sources":["../../../src/components/approvals/audit.ts"],"sourcesContent":["import { AuditLog, type AuditEventInput } from 'convex-audit-log'\nimport { v } from 'convex/values'\n\nimport { components } from './_generated/api'\nimport { mutation, query, type MutationCtx } from './_generated/server'\nimport {\n\tAPPROVAL_AUDIT_RETENTION_CATEGORY,\n\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n} from './constants'\nimport { approvalAuditEventProjection, approvalOptionalString } from './validators'\n\nexport type ApprovalAuditTransition = Readonly<{\n\taction: string\n\tactorRef?: string\n\trunId: string\n\tresourceType: string\n\tresourceRef: string\n\ttransition: string\n\tseverity?: AuditEventInput['severity']\n}>\n\nexport type ApprovalAuditProjection = Readonly<{\n\taction: string\n\tactorRef?: string\n\tcorrelationKey: string\n\ttransition: string\n}>\n\nexport const approvalAudit = new AuditLog(components.auditLog, {\n\tsamplingEnabled: false,\n})\n\nexport const history = query({\n\targs: {\n\t\tresourceType: v.string(),\n\t\tresourceRef: v.string(),\n\t\tlimit: v.optional(v.number()),\n\t},\n\treturns: v.array(\n\t\tv.object({\n\t\t\taction: v.string(),\n\t\t\tactorRef: v.optional(v.string()),\n\t\t\tcorrelationKey: v.string(),\n\t\t\ttransition: v.string(),\n\t\t}),\n\t),\n\thandler: async (ctx, input) => {\n\t\tconst limit = Math.max(1, Math.min(Math.trunc(input.limit ?? 100), 100))\n\t\tconst events = await approvalAudit.queryByResource(ctx, {\n\t\t\tresourceType: input.resourceType,\n\t\t\tresourceId: input.resourceRef,\n\t\t\tlimit,\n\t\t})\n\t\tconst unique = new Map<string, ApprovalAuditProjection>()\n\t\tfor (const event of events) {\n\t\t\tconst projection = auditProjection(event)\n\t\t\tif (projection) unique.set(projection.correlationKey, projection)\n\t\t}\n\t\treturn [...unique.values()]\n\t},\n})\n\nexport const cleanup = mutation({\n\targs: {\n\t\tolderThanDays: v.number(),\n\t\tbatchSize: v.number(),\n\t},\n\treturns: v.number(),\n\thandler: (ctx, input) => {\n\t\tconst olderThanDays = boundedInteger(\n\t\t\tinput.olderThanDays,\n\t\t\tMIN_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\tMAX_APPROVAL_AUDIT_RETENTION_DAYS,\n\t\t\t'olderThanDays',\n\t\t)\n\t\tconst batchSize = boundedInteger(\n\t\t\tinput.batchSize,\n\t\t\t1,\n\t\t\tMAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE,\n\t\t\t'batchSize',\n\t\t)\n\t\treturn approvalAudit.cleanup(ctx, {\n\t\t\tolderThanDays,\n\t\t\tbatchSize,\n\t\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\t})\n\t},\n})\n\nexport function approvalAuditEvent(input: ApprovalAuditTransition): AuditEventInput {\n\treturn {\n\t\taction: input.action,\n\t\tactorId: input.actorRef,\n\t\tresourceType: input.resourceType,\n\t\tresourceId: input.resourceRef,\n\t\tseverity: input.severity ?? 'info',\n\t\ttags: ['approvals'],\n\t\tretentionCategory: APPROVAL_AUDIT_RETENTION_CATEGORY,\n\t\tmetadata: {\n\t\t\tcorrelationKey: `${input.runId}:${input.transition}`,\n\t\t\trunId: input.runId,\n\t\t\ttransition: input.transition,\n\t\t},\n\t}\n}\n\nexport async function logApprovalTransition(\n\tctx: MutationCtx,\n\tinput: ApprovalAuditTransition,\n): Promise<void> {\n\tawait approvalAudit.log(ctx, approvalAuditEvent(input))\n}\n\nfunction boundedInteger(value: number, minimum: number, maximum: number, name: string): number {\n\tif (!Number.isInteger(value) || value < minimum || value > maximum)\n\t\tthrow new Error(`${name} must be an integer between ${minimum} and ${maximum}`)\n\treturn value\n}\n\nfunction auditProjection(\n\tevent: Awaited<ReturnType<typeof approvalAudit.queryByResource>>[number],\n): ApprovalAuditProjection | null {\n\tconst parsed = approvalAuditEventProjection.safeParse(event)\n\tif (!parsed.success) return null\n\tconst { action, actorId, metadata } = parsed.data\n\tconst actorRef = approvalOptionalString.safeParse(actorId)\n\treturn { action, actorRef: actorRef.success ? actorRef.data : undefined, ...metadata }\n}\n"],"mappings":"A,qYA8BA,MAAaA,EAAgB,IAAIC,EAASC,EAAW,SAAU,CAC9D,gBAAiB,EAClB,CAAC,EAEYC,EAAUC,EAAM,CAC5B,KAAM,CACL,aAAcC,EAAE,OAAO,EACvB,YAAaA,EAAE,OAAO,EACtB,MAAOA,EAAE,SAASA,EAAE,OAAO,CAAC,CAC7B,EACA,QAASA,EAAE,MACVA,EAAE,OAAO,CACR,OAAQA,EAAE,OAAO,EACjB,SAAUA,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vD,CAEA,SAASU,EAAe,EAAe,EAAiB,EAAiB,EAAsB,CAC9F,GAAI,CAAC,OAAO,UAAUM,CAAK,GAAKA,EAAQC,GAAWD,EAAQE,EAC1D,MAAU,MAAM,GAAGC,EAAK,8BAA8BF,EAAQ,OAAOC,GAAS,EAC/E,OAAOF,CACR,CAEA,SAASV,EACR,EACiC,CACjC,IAAMc,EAASC,EAA6B,UAAUjB,CAAK,EAC3D,GAAI,CAACgB,EAAO,QAAS,OAAO,KAC5B,GAAM,CAAE,SAAQ,UAAS,YAAaA,EAAO,KACvCE,EAAWC,EAAuB,UAAUC,CAAO,EACzD,MAAO,CAAE,SAAQ,SAAUF,EAAS,QAAUA,EAAS,KAAO,IAAA,GAAW,GAAGG,CAAS,CACtF,C"}
|
|
@@ -92,6 +92,5 @@ export declare class ConfiguredApprovalWorkflow<Component extends ComponentApi =
|
|
|
92
92
|
list<DataModel extends GenericDataModel>(ctx: GenericQueryCtx<DataModel>, input: FunctionArgs<Component['requests']['list']>): Promise<FunctionReturnType<Component['requests']['list']>>;
|
|
93
93
|
restart<DataModel extends GenericDataModel>(ctx: GenericMutationCtx<DataModel>, runId: string): Promise<FunctionReturnType<Component['requests']['restart']>>;
|
|
94
94
|
}
|
|
95
|
-
//#endregion
|
|
96
95
|
export { type ApprovalCallbackInput, approvalCallbackArgs, approvalCallbackInput, client_d_exports };
|
|
97
96
|
//# sourceMappingURL=client.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{compileApprovalDescriptor as e}from"./workflow_steps.mjs";import{approvalCallbackArgs as t,approvalCallbackInput as n}from"./validators.mjs";var r=class{component;createHandle;constructor(e,t={}){this.component=e,this.createHandle=t.createHandle}cleanupAudit(e,t){return e.runMutation(this.component.audit.cleanup,t)}mutation(e,t){return Object.freeze({kind:`mutation`,key:e,handler:t.handler,retry:t.retry??!1})}action(e,t){return Object.freeze({kind:`action`,key:e,handler:t.handler,retry:t.retry??!1})}notify(e,t){return Object.freeze({kind:`notify`,key:e,handler:t.handler,retry:t.retry??!1})}decision(e,t){return Object.freeze({kind:`decision`,key:e,decisions:Object.freeze([...t.decisions]),quorum:Object.freeze({...t.quorum}),makerChecker:t.makerChecker??!1,expiresAfterMs:t.expiresAfterMs})}branch(e,t){return Object.freeze({kind:`branch`,key:e,...t})}define(e){let t=a({name:e.name,compatibilityKey:e.compatibilityKey??e.name,steps:e.steps});return new i(this.component,t,this.createHandle)}},i=class{name;compatibilityKey;steps;component;definition;createHandle;constructor(e,t,n){this.component=e,this.definition=t,this.name=t.name,this.compatibilityKey=t.compatibilityKey,this.steps=t.steps,this.createHandle=n,Object.freeze(this)}descriptor(){return e(this.definition,this.createHandle)}async start(e,t){return e.runMutation(this.component.requests.start,{...t,workflow:await this.descriptor()})}decide(e,t,n){return e.runMutation(this.component.decisions.decide,{...t,actor:n,compatibilityKey:this.compatibilityKey})}evidence(e,t){return e.runQuery(this.component.decisions.list,{runId:t})}auditHistory(e,t){return e.runQuery(this.component.audit.history,t)}cancel(e,t,n){return e.runMutation(this.component.requests.cancel,{runId:t,actor:n,compatibilityKey:this.compatibilityKey})}status(e,t){return e.runQuery(this.component.requests.status,{runId:t,compatibilityKey:this.compatibilityKey})}list(e,t){return e.runQuery(this.component.requests.list,t)}restart(e,t){return e.runMutation(this.component.requests.restart,{runId:t,compatibilityKey:this.compatibilityKey})}};function a(e){return Object.freeze({...e,steps:Object.freeze(e.steps.map(e=>e.kind===`decision`?Object.freeze({...e,decisions:Object.freeze([...e.decisions]),quorum:Object.freeze({...e.quorum})}):Object.freeze({...e})))})}export{r as Approvals,i as ConfiguredApprovalWorkflow,t as approvalCallbackArgs,n as approvalCallbackInput};
|
|
2
2
|
//# sourceMappingURL=client.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":["Approvals","component","options","ctx","input","definition","freezeDefinition","ConfiguredApprovalWorkflow","createHandle","compileApprovalDescriptor","step","approvalCallbackArgs","approvalCallbackInput"],"sources":["../../../src/components/approvals/client.ts"],"sourcesContent":["import type { ApprovalCallbackInput } from './validators'\nimport type {\n\tFunctionArgs,\n\tFunctionReference,\n\tFunctionReturnType,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n} from 'convex/server'\n\nimport type { ComponentApi } from './_generated/component'\nimport type { ApprovalDecision } from './constants'\nimport type { ApprovalActor, ApprovalMetadata, ApprovalWorkflowDescriptor } from './validators'\nimport {\n\tcompileApprovalDescriptor,\n\ttype ApprovalActionStep,\n\ttype ApprovalBranchStep,\n\ttype ApprovalDecisionStep,\n\ttype ApprovalDefinition,\n\ttype ApprovalMutationStep,\n\ttype ApprovalNotifyStep,\n\ttype ApprovalWorkflowStep,\n\ttype CreateApprovalHandle,\n} from './workflow_steps'\n\nexport { approvalCallbackArgs, approvalCallbackInput } from './validators'\nexport type { ApprovalCallbackInput } from './validators'\n\nexport type ApprovalsOptions = Readonly<{\n\tcreateHandle?: CreateApprovalHandle\n}>\n\nexport type ApprovalStartInput = Readonly<{\n\tscopeRef: string\n\tresourceType: string\n\tresourceRef: string\n\trequester: ApprovalActor\n\tmetadata?: ApprovalMetadata\n}>\n\nexport type ApprovalDecisionInput = Readonly<{\n\trunId: string\n\tdecision: ApprovalDecision\n\treason?: string\n}>\n\nexport type ApprovalEvidenceItem = Readonly<{\n\tstepKey: string\n\tactorRef: string\n\tdecision: ApprovalDecision\n\treason?: string\n\tdecidedAt: number\n}>\n\nexport type ApprovalAuditHistoryInput = Readonly<{\n\tresourceType: string\n\tresourceRef: string\n\tlimit?: number\n}>\n\nexport type ApprovalAuditCleanupInput = Readonly<{\n\tolderThanDays: number\n\tbatchSize: number\n}>\n\nexport type ApprovalStatus = FunctionReturnType<ComponentApi['requests']['status']>\n\nexport class Approvals<Component extends ComponentApi = ComponentApi> {\n\tprivate readonly component: Component\n\tprivate readonly createHandle: CreateApprovalHandle | undefined\n\n\tconstructor(component: Component, options: ApprovalsOptions = {}) {\n\t\tthis.component = component\n\t\tthis.createHandle = options.createHandle\n\t}\n\n\tcleanupAudit<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalAuditCleanupInput,\n\t): Promise<FunctionReturnType<Component['audit']['cleanup']>> {\n\t\treturn ctx.runMutation(this.component.audit.cleanup, input)\n\t}\n\n\tmutation(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'mutation', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalMutationStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'mutation',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\taction(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'action', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalActionStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'action',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\tnotify(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'action', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalNotifyStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'notify',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\tdecision(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\tdecisions: readonly ApprovalDecision[]\n\t\t\tquorum: Readonly<{ kind: 'count'; approvals: number }>\n\t\t\tmakerChecker?: boolean\n\t\t\texpiresAfterMs?: number\n\t\t}>,\n\t): ApprovalDecisionStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'decision',\n\t\t\tkey,\n\t\t\tdecisions: Object.freeze([...options.decisions]),\n\t\t\tquorum: Object.freeze({ ...options.quorum }),\n\t\t\tmakerChecker: options.makerChecker ?? false,\n\t\t\texpiresAfterMs: options.expiresAfterMs,\n\t\t})\n\t}\n\n\tbranch(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\tapprovedStepKey: string\n\t\t\trejectedStepKey: string\n\t\t}>,\n\t): ApprovalBranchStep {\n\t\treturn Object.freeze({ kind: 'branch', key, ...options })\n\t}\n\n\tdefine(\n\t\tinput: Readonly<{\n\t\t\tname: string\n\t\t\tcompatibilityKey?: string\n\t\t\tsteps: readonly ApprovalWorkflowStep[]\n\t\t}>,\n\t): ConfiguredApprovalWorkflow<Component> {\n\t\tconst definition = freezeDefinition({\n\t\t\tname: input.name,\n\t\t\tcompatibilityKey: input.compatibilityKey ?? input.name,\n\t\t\tsteps: input.steps,\n\t\t})\n\t\treturn new ConfiguredApprovalWorkflow(this.component, definition, this.createHandle)\n\t}\n}\n\nexport class ConfiguredApprovalWorkflow<Component extends ComponentApi = ComponentApi> {\n\treadonly name: string\n\treadonly compatibilityKey: string\n\treadonly steps: readonly ApprovalWorkflowStep[]\n\n\tprivate readonly component: Component\n\tprivate readonly definition: ApprovalDefinition\n\tprivate readonly createHandle: CreateApprovalHandle | undefined\n\n\tconstructor(\n\t\tcomponent: Component,\n\t\tdefinition: ApprovalDefinition,\n\t\tcreateHandle?: CreateApprovalHandle,\n\t) {\n\t\tthis.component = component\n\t\tthis.definition = definition\n\t\tthis.name = definition.name\n\t\tthis.compatibilityKey = definition.compatibilityKey\n\t\tthis.steps = definition.steps\n\t\tthis.createHandle = createHandle\n\t\tObject.freeze(this)\n\t}\n\n\tdescriptor(): Promise<Readonly<ApprovalWorkflowDescriptor>> {\n\t\treturn compileApprovalDescriptor(this.definition, this.createHandle)\n\t}\n\n\tasync start<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalStartInput,\n\t): Promise<FunctionReturnType<Component['requests']['start']>> {\n\t\treturn ctx.runMutation(this.component.requests.start, {\n\t\t\t...input,\n\t\t\tworkflow: await this.descriptor(),\n\t\t})\n\t}\n\n\tdecide<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalDecisionInput,\n\t\tactor: ApprovalActor,\n\t): Promise<FunctionReturnType<Component['decisions']['decide']>> {\n\t\treturn ctx.runMutation(this.component.decisions.decide, {\n\t\t\t...input,\n\t\t\tactor,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tevidence<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<FunctionReturnType<Component['decisions']['list']>> {\n\t\treturn ctx.runQuery(this.component.decisions.list, { runId })\n\t}\n\n\tauditHistory<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tinput: ApprovalAuditHistoryInput,\n\t): Promise<FunctionReturnType<Component['audit']['history']>> {\n\t\treturn ctx.runQuery(this.component.audit.history, input)\n\t}\n\n\tcancel<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\trunId: string,\n\t\tactor: ApprovalActor,\n\t): Promise<FunctionReturnType<Component['requests']['cancel']>> {\n\t\treturn ctx.runMutation(this.component.requests.cancel, {\n\t\t\trunId,\n\t\t\tactor,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tstatus<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<ApprovalStatus | null> {\n\t\treturn ctx.runQuery(this.component.requests.status, {\n\t\t\trunId,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tlist<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tinput: FunctionArgs<Component['requests']['list']>,\n\t): Promise<FunctionReturnType<Component['requests']['list']>> {\n\t\treturn ctx.runQuery(this.component.requests.list, input)\n\t}\n\n\trestart<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<FunctionReturnType<Component['requests']['restart']>> {\n\t\treturn ctx.runMutation(this.component.requests.restart, {\n\t\t\trunId,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n}\n\nfunction freezeDefinition(definition: ApprovalDefinition): ApprovalDefinition {\n\treturn Object.freeze({\n\t\t...definition,\n\t\tsteps: Object.freeze(\n\t\t\tdefinition.steps.map((step) => {\n\t\t\t\tif (step.kind === 'decision')\n\t\t\t\t\treturn Object.freeze({\n\t\t\t\t\t\t...step,\n\t\t\t\t\t\tdecisions: Object.freeze([...step.decisions]),\n\t\t\t\t\t\tquorum: Object.freeze({ ...step.quorum }),\n\t\t\t\t\t})\n\t\t\t\treturn Object.freeze({ ...step })\n\t\t\t}),\n\t\t),\n\t})\n}\n\n// The component definition is deliberately NOT re-exported here: Convex's\n// CLI only discovers a component whose resolved file is convex.config.js,\n// so hosts must mount via the dedicated subpath:\n// import approvals from 'cvx-kit/components/approvals/convex.config'\n"],"mappings":"oJAmEA,IAAaA,EAAb,KAAsE,CACrE,UACA,aAEA,YAAY,EAAsB,EAA4B,CAAC,EAAG,CACjE,KAAK,UAAYC,EACjB,KAAK,aAAeC,EAAQ,YAC7B,CAEA,aACC,EACA,EAC6D,CAC7D,OAAOC,EAAI,YAAY,KAAK,UAAU,MAAM,QAASC,CAAK,CAC3D,CAEA,SACC,EACA,EAIuB,CACvB,OAAO,OAAO,OAAO,CACpB,KAAM,WACN,MACA,QAASF,EAAQ,QACjB,MAAOA,EAAQ,OAAS,EACzB,CAAC,CACF,CAEA,OACC,EACA,EAIqB,CACrB,OAAO,OAAO,OAAO,CACpB,KAAM,SACN,MACA,QAASA,EAAQ,QACjB,MAAOA,EAAQ,OAAS,EACzB,CAAC,CACF,CAEA,OACC,EACA,EAIqB,CACrB,OAAO,OA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CAC9D,OAAOD,EAAI,SAAS,KAAK,UAAU,UAAU,KAAM,CAAE,OAAM,CAAC,CAC7D,CAEA,aACC,EACA,EAC6D,CAC7D,OAAOA,EAAI,SAAS,KAAK,UAAU,MAAM,QAASC,CAAK,CACxD,CAEA,OACC,EACA,EACA,EAC+D,CAC/D,OAAOD,EAAI,YAAY,KAAK,UAAU,SAAS,OAAQ,CACtD,QACA,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CAEA,OACC,EACA,EACiC,CACjC,OAAOA,EAAI,SAAS,KAAK,UAAU,SAAS,OAAQ,CACnD,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CAEA,KACC,EACA,EAC6D,CAC7D,OAAOA,EAAI,SAAS,KAAK,UAAU,SAAS,KAAMC,CAAK,CACxD,CAEA,QACC,EACA,EACgE,CAChE,OAAOD,EAAI,YAAY,KAAK,UAAU,SAAS,QAAS,CACvD,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CACD,EAEA,SAASG,EAAiB,EAAoD,CAC7E,OAAO,OAAO,OAAO,CACpB,GAAGD,EACH,MAAO,OAAO,OACbA,EAAW,MAAM,IAAK,GACjBK,EAAK,OAAS,WACV,OAAO,OAAO,CACpB,GAAGA,EACH,UAAW,OAAO,OAAO,CAAC,GAAGA,EAAK,SAAS,CAAC,EAC5C,OAAQ,OAAO,OAAO,CAAE,GAAGA,EAAK,MAAO,CAAC,CACzC,CAAC,EACK,OAAO,OAAO,CAAE,GAAGA,CAAK,CAAC,CAChC,CACF,CACD,CAAC,CACF"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["Approvals","component","options","ctx","input","definition","freezeDefinition","ConfiguredApprovalWorkflow","createHandle","compileApprovalDescriptor","step","approvalCallbackArgs","approvalCallbackInput"],"sources":["../../../src/components/approvals/client.ts"],"sourcesContent":["import type { ApprovalCallbackInput } from './validators'\nimport type {\n\tFunctionArgs,\n\tFunctionReference,\n\tFunctionReturnType,\n\tGenericDataModel,\n\tGenericMutationCtx,\n\tGenericQueryCtx,\n} from 'convex/server'\n\nimport type { ComponentApi } from './_generated/component'\nimport type { ApprovalDecision } from './constants'\nimport type { ApprovalActor, ApprovalMetadata, ApprovalWorkflowDescriptor } from './validators'\nimport {\n\tcompileApprovalDescriptor,\n\ttype ApprovalActionStep,\n\ttype ApprovalBranchStep,\n\ttype ApprovalDecisionStep,\n\ttype ApprovalDefinition,\n\ttype ApprovalMutationStep,\n\ttype ApprovalNotifyStep,\n\ttype ApprovalWorkflowStep,\n\ttype CreateApprovalHandle,\n} from './workflow_steps'\n\nexport { approvalCallbackArgs, approvalCallbackInput } from './validators'\nexport type { ApprovalCallbackInput } from './validators'\n\nexport type ApprovalsOptions = Readonly<{\n\tcreateHandle?: CreateApprovalHandle\n}>\n\nexport type ApprovalStartInput = Readonly<{\n\tscopeRef: string\n\tresourceType: string\n\tresourceRef: string\n\trequester: ApprovalActor\n\tmetadata?: ApprovalMetadata\n}>\n\nexport type ApprovalDecisionInput = Readonly<{\n\trunId: string\n\tdecision: ApprovalDecision\n\treason?: string\n}>\n\nexport type ApprovalEvidenceItem = Readonly<{\n\tstepKey: string\n\tactorRef: string\n\tdecision: ApprovalDecision\n\treason?: string\n\tdecidedAt: number\n}>\n\nexport type ApprovalAuditHistoryInput = Readonly<{\n\tresourceType: string\n\tresourceRef: string\n\tlimit?: number\n}>\n\nexport type ApprovalAuditCleanupInput = Readonly<{\n\tolderThanDays: number\n\tbatchSize: number\n}>\n\nexport type ApprovalStatus = FunctionReturnType<ComponentApi['requests']['status']>\n\nexport class Approvals<Component extends ComponentApi = ComponentApi> {\n\tprivate readonly component: Component\n\tprivate readonly createHandle: CreateApprovalHandle | undefined\n\n\tconstructor(component: Component, options: ApprovalsOptions = {}) {\n\t\tthis.component = component\n\t\tthis.createHandle = options.createHandle\n\t}\n\n\tcleanupAudit<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalAuditCleanupInput,\n\t): Promise<FunctionReturnType<Component['audit']['cleanup']>> {\n\t\treturn ctx.runMutation(this.component.audit.cleanup, input)\n\t}\n\n\tmutation(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'mutation', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalMutationStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'mutation',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\taction(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'action', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalActionStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'action',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\tnotify(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\thandler: FunctionReference<'action', 'internal', ApprovalCallbackInput, unknown>\n\t\t\tretry?: boolean\n\t\t}>,\n\t): ApprovalNotifyStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'notify',\n\t\t\tkey,\n\t\t\thandler: options.handler,\n\t\t\tretry: options.retry ?? false,\n\t\t})\n\t}\n\n\tdecision(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\tdecisions: readonly ApprovalDecision[]\n\t\t\tquorum: Readonly<{ kind: 'count'; approvals: number }>\n\t\t\tmakerChecker?: boolean\n\t\t\texpiresAfterMs?: number\n\t\t}>,\n\t): ApprovalDecisionStep {\n\t\treturn Object.freeze({\n\t\t\tkind: 'decision',\n\t\t\tkey,\n\t\t\tdecisions: Object.freeze([...options.decisions]),\n\t\t\tquorum: Object.freeze({ ...options.quorum }),\n\t\t\tmakerChecker: options.makerChecker ?? false,\n\t\t\texpiresAfterMs: options.expiresAfterMs,\n\t\t})\n\t}\n\n\tbranch(\n\t\tkey: string,\n\t\toptions: Readonly<{\n\t\t\tapprovedStepKey: string\n\t\t\trejectedStepKey: string\n\t\t}>,\n\t): ApprovalBranchStep {\n\t\treturn Object.freeze({ kind: 'branch', key, ...options })\n\t}\n\n\tdefine(\n\t\tinput: Readonly<{\n\t\t\tname: string\n\t\t\tcompatibilityKey?: string\n\t\t\tsteps: readonly ApprovalWorkflowStep[]\n\t\t}>,\n\t): ConfiguredApprovalWorkflow<Component> {\n\t\tconst definition = freezeDefinition({\n\t\t\tname: input.name,\n\t\t\tcompatibilityKey: input.compatibilityKey ?? input.name,\n\t\t\tsteps: input.steps,\n\t\t})\n\t\treturn new ConfiguredApprovalWorkflow(this.component, definition, this.createHandle)\n\t}\n}\n\nexport class ConfiguredApprovalWorkflow<Component extends ComponentApi = ComponentApi> {\n\treadonly name: string\n\treadonly compatibilityKey: string\n\treadonly steps: readonly ApprovalWorkflowStep[]\n\n\tprivate readonly component: Component\n\tprivate readonly definition: ApprovalDefinition\n\tprivate readonly createHandle: CreateApprovalHandle | undefined\n\n\tconstructor(\n\t\tcomponent: Component,\n\t\tdefinition: ApprovalDefinition,\n\t\tcreateHandle?: CreateApprovalHandle,\n\t) {\n\t\tthis.component = component\n\t\tthis.definition = definition\n\t\tthis.name = definition.name\n\t\tthis.compatibilityKey = definition.compatibilityKey\n\t\tthis.steps = definition.steps\n\t\tthis.createHandle = createHandle\n\t\tObject.freeze(this)\n\t}\n\n\tdescriptor(): Promise<Readonly<ApprovalWorkflowDescriptor>> {\n\t\treturn compileApprovalDescriptor(this.definition, this.createHandle)\n\t}\n\n\tasync start<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalStartInput,\n\t): Promise<FunctionReturnType<Component['requests']['start']>> {\n\t\treturn ctx.runMutation(this.component.requests.start, {\n\t\t\t...input,\n\t\t\tworkflow: await this.descriptor(),\n\t\t})\n\t}\n\n\tdecide<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\tinput: ApprovalDecisionInput,\n\t\tactor: ApprovalActor,\n\t): Promise<FunctionReturnType<Component['decisions']['decide']>> {\n\t\treturn ctx.runMutation(this.component.decisions.decide, {\n\t\t\t...input,\n\t\t\tactor,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tevidence<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<FunctionReturnType<Component['decisions']['list']>> {\n\t\treturn ctx.runQuery(this.component.decisions.list, { runId })\n\t}\n\n\tauditHistory<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tinput: ApprovalAuditHistoryInput,\n\t): Promise<FunctionReturnType<Component['audit']['history']>> {\n\t\treturn ctx.runQuery(this.component.audit.history, input)\n\t}\n\n\tcancel<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\trunId: string,\n\t\tactor: ApprovalActor,\n\t): Promise<FunctionReturnType<Component['requests']['cancel']>> {\n\t\treturn ctx.runMutation(this.component.requests.cancel, {\n\t\t\trunId,\n\t\t\tactor,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tstatus<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<ApprovalStatus | null> {\n\t\treturn ctx.runQuery(this.component.requests.status, {\n\t\t\trunId,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n\n\tlist<DataModel extends GenericDataModel>(\n\t\tctx: GenericQueryCtx<DataModel>,\n\t\tinput: FunctionArgs<Component['requests']['list']>,\n\t): Promise<FunctionReturnType<Component['requests']['list']>> {\n\t\treturn ctx.runQuery(this.component.requests.list, input)\n\t}\n\n\trestart<DataModel extends GenericDataModel>(\n\t\tctx: GenericMutationCtx<DataModel>,\n\t\trunId: string,\n\t): Promise<FunctionReturnType<Component['requests']['restart']>> {\n\t\treturn ctx.runMutation(this.component.requests.restart, {\n\t\t\trunId,\n\t\t\tcompatibilityKey: this.compatibilityKey,\n\t\t})\n\t}\n}\n\nfunction freezeDefinition(definition: ApprovalDefinition): ApprovalDefinition {\n\treturn Object.freeze({\n\t\t...definition,\n\t\tsteps: Object.freeze(\n\t\t\tdefinition.steps.map((step) => {\n\t\t\t\tif (step.kind === 'decision')\n\t\t\t\t\treturn Object.freeze({\n\t\t\t\t\t\t...step,\n\t\t\t\t\t\tdecisions: Object.freeze([...step.decisions]),\n\t\t\t\t\t\tquorum: Object.freeze({ ...step.quorum }),\n\t\t\t\t\t})\n\t\t\t\treturn Object.freeze({ ...step })\n\t\t\t}),\n\t\t),\n\t})\n}\n\n// The component definition is deliberately NOT re-exported here: Convex's\n// CLI only discovers a component whose resolved file is convex.config.js,\n// so hosts must mount via the dedicated subpath:\n// import approvals from 'cvx-kit/components/approvals/convex.config'\n"],"mappings":"A,oJAmEA,IAAaA,EAAb,KAAsE,CACrE,UACA,aAEA,YAAY,EAAsB,EAA4B,CAAC,EAAG,CACjE,KAAK,UAAYC,EACjB,KAAK,aAAeC,EAAQ,YAC7B,CAEA,aACC,EACA,EAC6D,CAC7D,OAAOC,EAAI,YAAY,KAAK,UAAU,MAAM,QAASC,CAAK,CAC3D,CAEA,SACC,EACA,EAIuB,CACvB,OAAO,OAAO,OAAO,CACpB,KAAM,WACN,MACA,QAASF,EAAQ,QACjB,MAAOA,EAAQ,OAAS,EACzB,CAAC,CACF,CAEA,OACC,EACA,EAIqB,CACrB,OAAO,OAAO,OAAO,CACpB,KAAM,SACN,MACA,QAASA,EAAQ,QACjB,MAAOA,EAAQ,OAAS,EACzB,CAAC,CACF,CAEA,OACC,EACA,EAIqB,CACrB,OAAO,OAAO,OAAO,CACpB,KAAM,SACN,MACA,QAASA,EAAQ,QACjB,MAAOA,EAAQ,OAAS,EACzB,CAAC,CACF,CAEA,SACC,EACA,EAMuB,CACvB,OAAO,OAAO,OAAO,CACpB,KAAM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ASC,CAAK,CACxD,CAEA,OACC,EACA,EACA,EAC+D,CAC/D,OAAOD,EAAI,YAAY,KAAK,UAAU,SAAS,OAAQ,CACtD,QACA,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CAEA,OACC,EACA,EACiC,CACjC,OAAOA,EAAI,SAAS,KAAK,UAAU,SAAS,OAAQ,CACnD,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CAEA,KACC,EACA,EAC6D,CAC7D,OAAOA,EAAI,SAAS,KAAK,UAAU,SAAS,KAAMC,CAAK,CACxD,CAEA,QACC,EACA,EACgE,CAChE,OAAOD,EAAI,YAAY,KAAK,UAAU,SAAS,QAAS,CACvD,QACA,iBAAkB,KAAK,gBACxB,CAAC,CACF,CACD,EAEA,SAASG,EAAiB,EAAoD,CAC7E,OAAO,OAAO,OAAO,CACpB,GAAGD,EACH,MAAO,OAAO,OACbA,EAAW,MAAM,IAAK,GACjBK,EAAK,OAAS,WACV,OAAO,OAAO,CACpB,GAAGA,EACH,UAAW,OAAO,OAAO,CAAC,GAAGA,EAAK,SAAS,CAAC,EAC5C,OAAQ,OAAO,OAAO,CAAE,GAAGA,EAAK,MAAO,CAAC,CACzC,CAAC,EACK,OAAO,OAAO,CAAE,GAAGA,CAAK,CAAC,CAChC,CACF,CACD,CAAC,CACF,C"}
|
|
@@ -32,6 +32,5 @@ export type ApprovalDecision = (typeof APPROVAL_DECISIONS)[number];
|
|
|
32
32
|
export type ApprovalExecutionState = (typeof APPROVAL_EXECUTION_STATES)[number];
|
|
33
33
|
export type ApprovalStepKind = (typeof APPROVAL_STEP_KINDS)[number];
|
|
34
34
|
export type ApprovalCallbackKind = (typeof APPROVAL_CALLBACK_KINDS)[number];
|
|
35
|
-
//#endregion
|
|
36
35
|
export { constants_d_exports };
|
|
37
36
|
//# sourceMappingURL=constants.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","names":["APPROVAL_RUN_STATES","APPROVAL_DECISIONS","APPROVAL_EXECUTION_STATES","APPROVAL_STEP_KINDS","APPROVAL_QUORUM_KINDS","APPROVAL_CALLBACK_KINDS","APPROVAL_DESCRIPTOR_SCHEMA_VERSION","APPROVAL_COMPONENT_SCHEMA_VERSION","APPROVAL_DECISION_HISTORY_INDEX","APPROVAL_ACTOR_DECISION_INDEX","APPROVAL_REQUIRED_DECISION_INDEXES","APPROVAL_AUDIT_RETENTION_CATEGORY","MIN_APPROVAL_AUDIT_RETENTION_DAYS","MAX_APPROVAL_AUDIT_RETENTION_DAYS","MAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE","MAX_APPROVAL_REFERENCE_LENGTH","MAX_APPROVAL_NAME_LENGTH","MAX_APPROVAL_REASON_LENGTH","MAX_APPROVAL_CAPABILITIES","MAX_APPROVAL_METADATA_ENTRIES","MAX_APPROVAL_METADATA_KEY_LENGTH","MAX_APPROVAL_METADATA_VALUE_LENGTH","MAX_APPROVAL_WORKFLOW_STEPS","MAX_APPROVAL_DECISIONS_PER_STEP"],"sources":["../../../src/components/approvals/constants.ts"],"sourcesContent":["export const APPROVAL_RUN_STATES = [\n\t'pending',\n\t'approved',\n\t'rejected',\n\t'expired',\n\t'canceled',\n] as const\n\nexport const APPROVAL_DECISIONS = ['approved', 'rejected'] as const\n\nexport const APPROVAL_EXECUTION_STATES = ['inProgress', 'completed', 'canceled', 'failed'] as const\n\nexport const APPROVAL_STEP_KINDS = ['mutation', 'action', 'notify', 'decision', 'branch'] as const\n\nexport const APPROVAL_QUORUM_KINDS = ['count'] as const\n\nexport const APPROVAL_CALLBACK_KINDS = ['mutation', 'action'] as const\n\nexport const APPROVAL_DESCRIPTOR_SCHEMA_VERSION = 1 as const\n\n/** Version of the component-owned tables and indexes deployed by cvx-kit. */\nexport const APPROVAL_COMPONENT_SCHEMA_VERSION = 1 as const\n\n/** Indexes required by approval evidence reads and decision writes. */\nexport const APPROVAL_DECISION_HISTORY_INDEX = 'by_runId_and_decidedAt' as const\nexport const APPROVAL_ACTOR_DECISION_INDEX = 'by_runId_and_stepKey_and_actor_actorRef' as const\nexport const APPROVAL_REQUIRED_DECISION_INDEXES = [\n\tAPPROVAL_DECISION_HISTORY_INDEX,\n\tAPPROVAL_ACTOR_DECISION_INDEX,\n] as const\n\nexport const APPROVAL_AUDIT_RETENTION_CATEGORY = 'approval-protocol'\nexport const MIN_APPROVAL_AUDIT_RETENTION_DAYS = 1\nexport const MAX_APPROVAL_AUDIT_RETENTION_DAYS = 3_650\nexport const MAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE = 100\n\nexport const MAX_APPROVAL_REFERENCE_LENGTH = 256\nexport const MAX_APPROVAL_NAME_LENGTH = 96\nexport const MAX_APPROVAL_REASON_LENGTH = 500\nexport const MAX_APPROVAL_CAPABILITIES = 32\nexport const MAX_APPROVAL_METADATA_ENTRIES = 32\nexport const MAX_APPROVAL_METADATA_KEY_LENGTH = 64\nexport const MAX_APPROVAL_METADATA_VALUE_LENGTH = 512\nexport const MAX_APPROVAL_WORKFLOW_STEPS = 32\nexport const MAX_APPROVAL_DECISIONS_PER_STEP = 8\n\nexport type ApprovalRunState = (typeof APPROVAL_RUN_STATES)[number]\nexport type ApprovalDecision = (typeof APPROVAL_DECISIONS)[number]\nexport type ApprovalExecutionState = (typeof APPROVAL_EXECUTION_STATES)[number]\nexport type ApprovalStepKind = (typeof APPROVAL_STEP_KINDS)[number]\nexport type ApprovalCallbackKind = (typeof APPROVAL_CALLBACK_KINDS)[number]\n"],"mappings":"AAAA,MAAaA,EAAsB,CAClC,UACA,WACA,WACA,UACA,UACD,EAEaC,EAAqB,CAAC,WAAY,UAAU,EAE5CC,EAA4B,CAAC,aAAc,YAAa,WAAY,QAAQ,EAE5EC,EAAsB,CAAC,WAAY,SAAU,SAAU,WAAY,QAAQ,EAE3EC,EAAwB,CAAC,OAAO,EAEhCC,EAA0B,CAAC,WAAY,QAAQ,EAE/CC,EAAqC,EAGrCC,EAAoC,EAGpCC,EAAkC,yBAClCC,EAAgC,0CAChCC,EAAqC,CACjDF,EACAC,CACD,EAEaE,EAAoC,oBACpCC,EAAoC,EACpCC,EAAoC,KACpCC,EAAwC,IAExCC,EAAgC,IAChCC,EAA2B,GAC3BC,EAA6B,IAC7BC,EAA4B,GAC5BC,EAAgC,GAChCC,EAAmC,GACnCC,EAAqC,IACrCC,EAA8B,GAC9BC,EAAkC"}
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":["APPROVAL_RUN_STATES","APPROVAL_DECISIONS","APPROVAL_EXECUTION_STATES","APPROVAL_STEP_KINDS","APPROVAL_QUORUM_KINDS","APPROVAL_CALLBACK_KINDS","APPROVAL_DESCRIPTOR_SCHEMA_VERSION","APPROVAL_COMPONENT_SCHEMA_VERSION","APPROVAL_DECISION_HISTORY_INDEX","APPROVAL_ACTOR_DECISION_INDEX","APPROVAL_REQUIRED_DECISION_INDEXES","APPROVAL_AUDIT_RETENTION_CATEGORY","MIN_APPROVAL_AUDIT_RETENTION_DAYS","MAX_APPROVAL_AUDIT_RETENTION_DAYS","MAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE","MAX_APPROVAL_REFERENCE_LENGTH","MAX_APPROVAL_NAME_LENGTH","MAX_APPROVAL_REASON_LENGTH","MAX_APPROVAL_CAPABILITIES","MAX_APPROVAL_METADATA_ENTRIES","MAX_APPROVAL_METADATA_KEY_LENGTH","MAX_APPROVAL_METADATA_VALUE_LENGTH","MAX_APPROVAL_WORKFLOW_STEPS","MAX_APPROVAL_DECISIONS_PER_STEP"],"sources":["../../../src/components/approvals/constants.ts"],"sourcesContent":["export const APPROVAL_RUN_STATES = [\n\t'pending',\n\t'approved',\n\t'rejected',\n\t'expired',\n\t'canceled',\n] as const\n\nexport const APPROVAL_DECISIONS = ['approved', 'rejected'] as const\n\nexport const APPROVAL_EXECUTION_STATES = ['inProgress', 'completed', 'canceled', 'failed'] as const\n\nexport const APPROVAL_STEP_KINDS = ['mutation', 'action', 'notify', 'decision', 'branch'] as const\n\nexport const APPROVAL_QUORUM_KINDS = ['count'] as const\n\nexport const APPROVAL_CALLBACK_KINDS = ['mutation', 'action'] as const\n\nexport const APPROVAL_DESCRIPTOR_SCHEMA_VERSION = 1 as const\n\n/** Version of the component-owned tables and indexes deployed by cvx-kit. */\nexport const APPROVAL_COMPONENT_SCHEMA_VERSION = 1 as const\n\n/** Indexes required by approval evidence reads and decision writes. */\nexport const APPROVAL_DECISION_HISTORY_INDEX = 'by_runId_and_decidedAt' as const\nexport const APPROVAL_ACTOR_DECISION_INDEX = 'by_runId_and_stepKey_and_actor_actorRef' as const\nexport const APPROVAL_REQUIRED_DECISION_INDEXES = [\n\tAPPROVAL_DECISION_HISTORY_INDEX,\n\tAPPROVAL_ACTOR_DECISION_INDEX,\n] as const\n\nexport const APPROVAL_AUDIT_RETENTION_CATEGORY = 'approval-protocol'\nexport const MIN_APPROVAL_AUDIT_RETENTION_DAYS = 1\nexport const MAX_APPROVAL_AUDIT_RETENTION_DAYS = 3_650\nexport const MAX_APPROVAL_AUDIT_CLEANUP_BATCH_SIZE = 100\n\nexport const MAX_APPROVAL_REFERENCE_LENGTH = 256\nexport const MAX_APPROVAL_NAME_LENGTH = 96\nexport const MAX_APPROVAL_REASON_LENGTH = 500\nexport const MAX_APPROVAL_CAPABILITIES = 32\nexport const MAX_APPROVAL_METADATA_ENTRIES = 32\nexport const MAX_APPROVAL_METADATA_KEY_LENGTH = 64\nexport const MAX_APPROVAL_METADATA_VALUE_LENGTH = 512\nexport const MAX_APPROVAL_WORKFLOW_STEPS = 32\nexport const MAX_APPROVAL_DECISIONS_PER_STEP = 8\n\nexport type ApprovalRunState = (typeof APPROVAL_RUN_STATES)[number]\nexport type ApprovalDecision = (typeof APPROVAL_DECISIONS)[number]\nexport type ApprovalExecutionState = (typeof APPROVAL_EXECUTION_STATES)[number]\nexport type ApprovalStepKind = (typeof APPROVAL_STEP_KINDS)[number]\nexport type ApprovalCallbackKind = (typeof APPROVAL_CALLBACK_KINDS)[number]\n"],"mappings":"AAAA,MAAaA,EAAsB,CAClC,UACA,WACA,WACA,UACA,UACD,EAEaC,EAAqB,CAAC,WAAY,UAAU,EAE5CC,EAA4B,CAAC,aAAc,YAAa,WAAY,QAAQ,EAE5EC,EAAsB,CAAC,WAAY,SAAU,SAAU,WAAY,QAAQ,EAE3EC,EAAwB,CAAC,OAAO,EAEhCC,EAA0B,CAAC,WAAY,QAAQ,EAE/CC,EAAqC,EAGrCC,EAAoC,EAGpCC,EAAkC,yBAClCC,EAAgC,0CAChCC,EAAqC,CACjDF,EACAC,CACD,EAEaE,EAAoC,oBACpCC,EAAoC,EACpCC,EAAoC,KACpCC,EAAwC,IAExCC,EAAgC,IAChCC,EAA2B,GAC3BC,EAA6B,IAC7BC,EAA4B,GAC5BC,EAAgC,GAChCC,EAAmC,GACnCC,EAAqC,IACrCC,EAA8B,GAC9BC,EAAkC,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convex.config.mjs","names":["workflow","auditLog","approvals","defineComponent"],"sources":["../../../src/components/approvals/convex.config.ts"],"sourcesContent":["import workflow from '@convex-dev/workflow/convex.config'\nimport auditLog from 'convex-audit-log/convex.config.js'\nimport { defineComponent } from 'convex/server'\n\nconst approvals = defineComponent('approvals')\n\napprovals.use(workflow, { name: 'workflow' })\napprovals.use(auditLog, { name: 'auditLog' })\n\nexport default approvals\n"],"mappings":"mJAIA,MAAME,EAAYC,EAAgB,WAAW,EAE7CD,EAAU,IAAIF,EAAU,CAAE,KAAM,UAAW,CAAC,EAC5CE,EAAU,IAAID,EAAU,CAAE,KAAM,UAAW,CAAC"}
|
|
1
|
+
{"version":3,"file":"convex.config.mjs","names":["workflow","auditLog","approvals","defineComponent"],"sources":["../../../src/components/approvals/convex.config.ts"],"sourcesContent":["import workflow from '@convex-dev/workflow/convex.config'\nimport auditLog from 'convex-audit-log/convex.config.js'\nimport { defineComponent } from 'convex/server'\n\nconst approvals = defineComponent('approvals')\n\napprovals.use(workflow, { name: 'workflow' })\napprovals.use(auditLog, { name: 'auditLog' })\n\nexport default approvals\n"],"mappings":"A,mJAIA,MAAME,EAAYC,EAAgB,WAAW,EAE7CD,EAAU,IAAIF,EAAU,CAAE,KAAM,UAAW,CAAC,EAC5CE,EAAU,IAAID,EAAU,CAAE,KAAM,UAAW,CAAC,E"}
|
|
@@ -5,9 +5,7 @@ export declare const decide: import("convex/server").RegisteredMutation<"public"
|
|
|
5
5
|
actor: {
|
|
6
6
|
actorRef: string;
|
|
7
7
|
capabilities: string[];
|
|
8
|
-
metadata?:
|
|
9
|
-
[x: string]: string;
|
|
10
|
-
} | undefined;
|
|
8
|
+
metadata?: Record<string, string> | undefined;
|
|
11
9
|
};
|
|
12
10
|
compatibilityKey: string;
|
|
13
11
|
decision: "approved" | "rejected";
|
|
@@ -55,6 +53,5 @@ export declare const expire: import("convex/server").RegisteredMutation<"interna
|
|
|
55
53
|
} | {
|
|
56
54
|
state: "approved" | "canceled" | "expired" | "pending" | "rejected";
|
|
57
55
|
}>>;
|
|
58
|
-
//#endregion
|
|
59
56
|
export { decisions_d_exports };
|
|
60
57
|
//# sourceMappingURL=decisions.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{components as e,internal as t}from"./_generated/api.mjs";import{internalMutation as n,internalQuery as r,mutation as i,query as a}from"./_generated/server.mjs";import{
|
|
1
|
+
import{components as e,internal as t}from"./_generated/api.mjs";import{internalMutation as n,internalQuery as r,mutation as i,query as a}from"./_generated/server.mjs";import{logApprovalTransition as o}from"./audit.mjs";import{APPROVAL_ACTOR_DECISION_INDEX as s,APPROVAL_DECISIONS as c,APPROVAL_DECISION_HISTORY_INDEX as l,APPROVAL_RUN_STATES as u}from"./constants.mjs";import{canTransitionApprovalRun as d,classifyPendingRunAt as f}from"./functions.mjs";import{approvalActor as p,approvalDecision as m,approvalReason as h}from"./validators.mjs";import{approvalDecisionEventName as g,evaluateDecisionOutcome as _}from"./workflow_steps.mjs";import{v}from"convex/values";import{WorkflowManager as y}from"@convex-dev/workflow";const b=i({args:{runId:v.id(`approvalRuns`),decision:m.validator,reason:v.optional(h.validator),actor:p.validator,compatibilityKey:v.string()},returns:v.object({state:v.union(v.literal(u[0]),v.literal(u[1]),v.literal(u[2]),v.literal(u[3]),v.literal(u[4]))}),handler:async(e,t)=>{let n=await e.db.get(t.runId);if(!n)throw Error(`Approval request not found`);O(n.workflow.compatibilityKey,t.compatibilityKey);let r=n.workflow.steps.find(e=>e.kind===`decision`&&e.key===n.currentStepKey);if(!r||r.kind!==`decision`)throw Error(`Approval request is not waiting for a decision`);let i=await e.db.query(`approvalDecisions`).withIndex(s,e=>e.eq(`runId`,n._id).eq(`stepKey`,r.key).eq(`actor.actorRef`,t.actor.actorRef)).unique();if(i){if(i.decision!==t.decision)throw Error(`Actor already submitted a contradictory decision`);return{state:n.state}}if(n.state!==`pending`)throw Error(`Approval request is already ${n.state}`);if(n.expiresAt!==void 0&&f(Date.now(),n.expiresAt)===`expired`)return E(e,n,r.key);if(!r.decisions.includes(t.decision))throw Error(`Decision is not allowed by this workflow step`);if(r.makerChecker&&t.actor.actorRef===n.requester.actorRef)throw Error(`Requester cannot decide this approval step`);let a=Date.now();await e.db.insert(`approvalDecisions`,{runId:n._id,stepKey:r.key,actor:t.actor,decision:t.decision,reason:t.reason,decidedAt:a});let c=await e.db.query(`approvalDecisions`).withIndex(`by_runId_and_stepKey_and_decidedAt`,e=>e.eq(`runId`,n._id).eq(`stepKey`,r.key)).collect(),l=_(c.map(e=>({actorRef:e.actor.actorRef,decision:e.decision})),r.quorum.approvals);if(await o(e,{action:`approval.decision.${t.decision}`,actorRef:t.actor.actorRef,runId:n._id,resourceType:n.resourceType,resourceRef:n.resourceRef,transition:`${r.key}:${t.actor.actorRef}:${t.decision}`}),!l)return{state:`pending`};let u=j(n,r.key,l);return await D(e,n,r.key,l,u,{actorRef:t.actor.actorRef,decision:t.decision,reason:t.reason,decidedAt:a}),u?{state:l}:{state:`pending`}}}),x=a({args:{runId:v.id(`approvalRuns`)},returns:v.array(v.object({stepKey:v.string(),actorRef:v.string(),decision:m.validator,reason:v.optional(h.validator),decidedAt:v.number()})),handler:(e,t)=>k(e,t.runId)}),S=r({args:{runId:v.id(`approvalRuns`),stepKey:v.string()},returns:v.array(v.object({stepKey:v.string(),actorRef:v.string(),decision:m.validator,reason:v.optional(h.validator),decidedAt:v.number()})),handler:(e,t)=>A(e,t.runId,t.stepKey)}),C=n({args:{runId:v.id(`approvalRuns`),stepKey:v.string(),workflowId:v.string(),expiresAfterMs:v.optional(v.number())},returns:v.object({state:v.union(v.literal(u[0]),v.literal(u[1]),v.literal(u[2]),v.literal(u[3]),v.literal(u[4])),expiresAt:v.optional(v.number())}),handler:async(e,n)=>{let r=await e.db.get(n.runId);if(!r)throw Error(`Approval request not found`);if(r.workflowId!==n.workflowId)throw Error(`Approval workflow linkage is incomplete`);if(r.state!==`pending`)return{state:r.state,expiresAt:r.expiresAt};let i=Number(r.metadata?.approvalExpiresAt),a=Number.isFinite(i)?i:n.expiresAfterMs===void 0?void 0:Date.now()+n.expiresAfterMs;return await e.db.patch(r._id,{currentStepKey:n.stepKey,expiresAt:a,updatedAt:Date.now()}),await o(e,{action:`approval.waiting`,runId:r._id,resourceType:r.resourceType,resourceRef:r.resourceRef,transition:`${n.stepKey}:waiting`}),a!==void 0&&await e.scheduler.runAt(a,t.decisions.expire,{runId:r._id,stepKey:n.stepKey}),{state:`pending`,expiresAt:a}}}),w=n({args:{runId:v.id(`approvalRuns`),stepKey:v.string()},returns:v.object({state:v.union(v.literal(`missing`),v.literal(u[0]),v.literal(u[1]),v.literal(u[2]),v.literal(u[3]),v.literal(u[4]))}),handler:async(e,t)=>{let n=await e.db.get(t.runId);return n?n.state!==`pending`||n.currentStepKey!==t.stepKey||n.expiresAt===void 0||f(Date.now(),n.expiresAt)===`pending`?{state:n.state}:E(e,n,t.stepKey):{state:`missing`}}}),T=new y(e.workflow);async function E(e,t,n){if(!d(t.state,`expired`))throw Error(`Approval request cannot transition from ${t.state}`);let r=Date.now();if(await e.db.patch(t._id,{state:`expired`,expiresAt:void 0,updatedAt:r,terminalAt:r}),await o(e,{action:`approval.expired`,runId:t._id,resourceType:t.resourceType,resourceRef:t.resourceRef,transition:`${n}:expired`}),!t.workflowId)throw Error(`Approval workflow is not linked`);return await T.sendEvent(e,{workflowId:t.workflowId,name:g(t._id,n),validator:v.object({outcome:v.literal(u[3])}),value:{outcome:`expired`}}),{state:`expired`}}async function D(e,t,n,r,i,a){if(i){if(!d(t.state,r))throw Error(`Approval request cannot transition from ${t.state}`);let i=Date.now();await e.db.patch(t._id,{state:r,expiresAt:void 0,updatedAt:i,terminalAt:i}),await o(e,{action:`approval.${r}`,runId:t._id,resourceType:t.resourceType,resourceRef:t.resourceRef,transition:`${n}:terminal:${r}`})}if(!t.workflowId)throw Error(`Approval workflow is not linked`);await T.sendEvent(e,{workflowId:t.workflowId,name:g(t._id,n),validator:v.object({outcome:v.union(v.literal(c[0]),v.literal(c[1])),terminalEvidence:v.object({actorRef:v.string(),decision:m.validator,reason:v.optional(h.validator),decidedAt:v.number()})}),value:{outcome:r,terminalEvidence:a}})}function O(e,t){if(e!==t)throw Error(`Approval workflow compatibility mismatch: expected ${t}, received ${e}`)}async function k(e,t){return(await e.db.query(`approvalDecisions`).withIndex(l,e=>e.eq(`runId`,t)).collect()).map(e=>({stepKey:e.stepKey,actorRef:e.actor.actorRef,decision:e.decision,reason:e.reason,decidedAt:e.decidedAt}))}async function A(e,t,n){return(await e.db.query(`approvalDecisions`).withIndex(`by_runId_and_stepKey_and_decidedAt`,e=>e.eq(`runId`,t).eq(`stepKey`,n)).collect()).map(e=>({stepKey:e.stepKey,actorRef:e.actor.actorRef,decision:e.decision,reason:e.reason,decidedAt:e.decidedAt}))}function j(e,t,n){if(n===`rejected`)return!0;let r=e.workflow.steps.findIndex(e=>e.kind===`decision`&&e.key===t);return!e.workflow.steps.slice(r+1).some(e=>e.kind===`decision`)}export{b as decide,C as enter,w as expire,x as list,S as listForWorkflow};
|
|
2
2
|
//# sourceMappingURL=decisions.mjs.map
|