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
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{APPROVAL_CALLBACK_KINDS as
|
|
1
|
+
import{k as e}from"../../k/index.mjs";import{APPROVAL_CALLBACK_KINDS as t,APPROVAL_DECISIONS as n,APPROVAL_QUORUM_KINDS as r,APPROVAL_RUN_STATES as i,APPROVAL_STEP_KINDS as a}from"./constants.mjs";const o=e.number().refine(Number.isFinite,`Expected a finite number`),s=e.enum(i),c=e.enum(n),l=e.enum(a),u=e.enum(t),d=e.enum(r),f=e.string().trim().min(1).max(256),p=e.string().trim().min(1).max(96).regex(/^[A-Za-z][A-Za-z0-9._-]*$/),m=e.string().trim().min(1).max(500),h=e.record(e.string().min(1).max(64).regex(/^(?![$_])[\x20-\x7E]+$/),e.string().max(512)).refine(e=>Object.keys(e).length<=32,`Metadata may contain at most 32 entries`),g=e.object({stepKey:p,actorRef:f,decision:c,reason:m.optional(),decidedAt:o}),_=g.omit(`stepKey`),v=e.object({runId:f,scopeRef:f,resourceType:p,resourceRef:f,metadata:h.optional(),decision:e.object({stepKey:p,outcome:e.union([c,e.literal(`expired`)]),evidence:e.array(g),terminalEvidence:_.optional()}).optional()}),y=v.validator,b=e.object({actorRef:f,capabilities:e.array(p).max(32),metadata:h.optional()}),x=e.object({kind:e.literal(`mutation`),handle:f,retry:e.boolean()}),S=e.object({kind:e.literal(`action`),handle:f,retry:e.boolean()}),C=e.discriminatedUnion(`kind`,[x,S]),w=e.object({kind:d,approvals:e.int().min(1).max(8)}),T=e.discriminatedUnion(`kind`,[e.object({kind:e.literal(`mutation`),key:p,callback:x}),e.object({kind:e.literal(`action`),key:p,callback:S})]),E=e.object({kind:e.literal(`notify`),key:p,callback:S}),D=e.object({kind:e.literal(`decision`),key:p,decisions:e.array(c).min(1).max(8),quorum:w,makerChecker:e.boolean(),expiresAfterMs:e.int().min(1).refine(Number.isSafeInteger,`Expected a safe integer`).optional()}),O=e.object({kind:e.literal(`branch`),key:p,approvedStepKey:p,rejectedStepKey:p}),k=e.union([T,E,D,O]),A=e.object({schemaVersion:e.literal(1),compatibilityKey:p,name:p,steps:e.array(k).min(1).max(32)}).check((e,t)=>{let n=/* @__PURE__ */ new Set,r=new Map(e.steps.map(e=>[e.key,e])),i=/* @__PURE__ */ new Map;for(let[r,i]of e.steps.entries())n.has(i.key)&&t.addIssue({message:`Duplicate workflow step key: ${i.key}`,path:[`steps`,r,`key`]}),n.add(i.key),i.kind===`decision`&&new Set(i.decisions).size!==i.decisions.length&&t.addIssue({message:`Duplicate decision value in step: ${i.key}`,path:[`steps`,r,`decisions`]});for(let[n,a]of e.steps.entries())if(a.kind===`branch`){e.steps[n-1]?.kind!==`decision`&&t.addIssue({message:`Branch must immediately follow a decision: ${a.key}`,path:[`steps`,n]});for(let o of[a.approvedStepKey,a.rejectedStepKey]){let a=r.get(o),s=e.steps.findIndex(e=>e.key===o);a?a.kind!==`mutation`&&a.kind!==`action`&&a.kind!==`notify`?t.addIssue({message:`Branch target must be a callback step: ${o}`,path:[`steps`,n]}):s<=n&&t.addIssue({message:`Branch target must be declared after its branch: ${o}`,path:[`steps`,n]}):t.addIssue({message:`Unknown branch target: ${o}`,path:[`steps`,n]}),i.set(o,(i.get(o)??0)+1)}}for(let[e,n]of i)n!==1&&t.addIssue({message:`Branch callback must belong to exactly one branch: ${e}`,path:[`steps`]})}),j=e.object({scopeRef:f,resourceType:p,resourceRef:f,requester:b,metadata:h.optional(),workflow:A,state:s,currentStepKey:p.optional(),executionFailedStepKey:p.optional(),expiresAt:o.optional(),workflowId:f.optional(),createdAt:o,updatedAt:o,terminalAt:o.optional()}),M=e.object({runId:e.id(`approvalRuns`),stepKey:p,actor:b,decision:c,reason:m.optional(),decidedAt:o}),N=e.object({action:e.string(),actorId:e.any().optional(),metadata:e.object({correlationKey:e.string(),transition:e.string()}).strip()}).strip(),P=e.string().optional();export{S as approvalActionCallback,b as approvalActor,N as approvalAuditEventProjection,O as approvalBranchStep,C as approvalCallback,y as approvalCallbackArgs,v as approvalCallbackInput,u as approvalCallbackKind,T as approvalCallbackStep,c as approvalDecision,M as approvalDecisionDocument,D as approvalDecisionStep,h as approvalMetadata,x as approvalMutationCallback,p as approvalName,E as approvalNotifyStep,P as approvalOptionalString,w as approvalQuorum,d as approvalQuorumKind,m as approvalReason,f as approvalReference,j as approvalRunDocument,s as approvalRunState,l as approvalStepKind,A as approvalWorkflowDescriptor,k as approvalWorkflowStep};
|
|
2
2
|
//# sourceMappingURL=validators.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validators.mjs","names":["approvalRunState","z","APPROVAL_RUN_STATES","approvalDecision","APPROVAL_DECISIONS","approvalStepKind","APPROVAL_STEP_KINDS","approvalCallbackKind","APPROVAL_CALLBACK_KINDS","approvalQuorumKind","APPROVAL_QUORUM_KINDS","approvalReference","approvalName","approvalReason","approvalMetadata","value","approvalCallbackEvidence","approvalCallbackTerminalEvidence","approvalCallbackInput","approvalCallbackArgs","zodToConvex","approvalActor","approvalMutationCallback","approvalActionCallback","approvalCallback","approvalQuorum","approvalCallbackStep","approvalNotifyStep","approvalDecisionStep","approvalBranchStep","approvalWorkflowStep","approvalWorkflowDescriptor","keys","stepsByKey","descriptor","step","branchTargetOwners","index","context","target","targetStep","targetIndex","candidate","owners","approvalRunDocument","approvalDecisionDocument","zid"],"sources":["../../../src/components/approvals/validators.ts"],"sourcesContent":["import { zid, zodToConvex } from 'convex-helpers/server/zod4'\nimport { z } from 'zod'\n\nimport {\n\tAPPROVAL_CALLBACK_KINDS,\n\tAPPROVAL_DECISIONS,\n\tAPPROVAL_DESCRIPTOR_SCHEMA_VERSION,\n\tAPPROVAL_QUORUM_KINDS,\n\tAPPROVAL_RUN_STATES,\n\tAPPROVAL_STEP_KINDS,\n\tMAX_APPROVAL_CAPABILITIES,\n\tMAX_APPROVAL_DECISIONS_PER_STEP,\n\tMAX_APPROVAL_METADATA_ENTRIES,\n\tMAX_APPROVAL_METADATA_KEY_LENGTH,\n\tMAX_APPROVAL_METADATA_VALUE_LENGTH,\n\tMAX_APPROVAL_NAME_LENGTH,\n\tMAX_APPROVAL_REASON_LENGTH,\n\tMAX_APPROVAL_REFERENCE_LENGTH,\n\tMAX_APPROVAL_WORKFLOW_STEPS,\n} from './constants'\n\nexport const approvalRunState = z.enum(APPROVAL_RUN_STATES)\nexport const approvalDecision = z.enum(APPROVAL_DECISIONS)\nexport const approvalStepKind = z.enum(APPROVAL_STEP_KINDS)\nexport const approvalCallbackKind = z.enum(APPROVAL_CALLBACK_KINDS)\nexport const approvalQuorumKind = z.enum(APPROVAL_QUORUM_KINDS)\n\nexport const approvalReference = z.string().trim().min(1).max(MAX_APPROVAL_REFERENCE_LENGTH)\n\nexport const approvalName = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(MAX_APPROVAL_NAME_LENGTH)\n\t.regex(/^[A-Za-z][A-Za-z0-9._-]*$/)\n\nexport const approvalReason = z.string().trim().min(1).max(MAX_APPROVAL_REASON_LENGTH)\n\nexport const approvalMetadata = z\n\t.record(\n\t\tz\n\t\t\t.string()\n\t\t\t.min(1)\n\t\t\t.max(MAX_APPROVAL_METADATA_KEY_LENGTH)\n\t\t\t.regex(/^(?![$_])[\\x20-\\x7E]+$/),\n\t\tz.string().max(MAX_APPROVAL_METADATA_VALUE_LENGTH),\n\t)\n\t.refine(\n\t\t(value) => Object.keys(value).length <= MAX_APPROVAL_METADATA_ENTRIES,\n\t\t`Metadata may contain at most ${MAX_APPROVAL_METADATA_ENTRIES} entries`,\n\t)\n\nconst approvalCallbackEvidence = z\n\t.object({\n\t\tstepKey: approvalName,\n\t\tactorRef: approvalReference,\n\t\tdecision: approvalDecision,\n\t\treason: approvalReason.optional(),\n\t\tdecidedAt: z.number(),\n\t})\n\t.strict()\n\nconst approvalCallbackTerminalEvidence = approvalCallbackEvidence.omit({\n\tstepKey: true,\n})\n\nexport const approvalCallbackInput = z\n\t.object({\n\t\trunId: approvalReference,\n\t\tscopeRef: approvalReference,\n\t\tresourceType: approvalName,\n\t\tresourceRef: approvalReference,\n\t\tmetadata: approvalMetadata.optional(),\n\t\tdecision: z\n\t\t\t.object({\n\t\t\t\tstepKey: approvalName,\n\t\t\t\toutcome: z.union([approvalDecision, z.literal('expired')]),\n\t\t\t\tevidence: z.array(approvalCallbackEvidence),\n\t\t\t\tterminalEvidence: approvalCallbackTerminalEvidence.optional(),\n\t\t\t})\n\t\t\t.strict()\n\t\t\t.optional(),\n\t})\n\t.strict()\n\n/** Convex argument validator for approval mutation, action, and notify callbacks. */\nexport const approvalCallbackArgs = zodToConvex(approvalCallbackInput)\n\nexport const approvalActor = z\n\t.object({\n\t\tactorRef: approvalReference,\n\t\tcapabilities: z.array(approvalName).max(MAX_APPROVAL_CAPABILITIES),\n\t\tmetadata: approvalMetadata.optional(),\n\t})\n\t.strict()\n\nexport const approvalMutationCallback = z\n\t.object({\n\t\tkind: z.literal('mutation'),\n\t\thandle: approvalReference,\n\t\tretry: z.boolean(),\n\t})\n\t.strict()\n\nexport const approvalActionCallback = z\n\t.object({\n\t\tkind: z.literal('action'),\n\t\thandle: approvalReference,\n\t\tretry: z.boolean(),\n\t})\n\t.strict()\n\nexport const approvalCallback = z.discriminatedUnion('kind', [\n\tapprovalMutationCallback,\n\tapprovalActionCallback,\n])\n\nexport const approvalQuorum = z\n\t.object({\n\t\tkind: approvalQuorumKind,\n\t\tapprovals: z.number().int().positive().max(MAX_APPROVAL_DECISIONS_PER_STEP),\n\t})\n\t.strict()\n\nexport const approvalCallbackStep = z.discriminatedUnion('kind', [\n\tz\n\t\t.object({\n\t\t\tkind: z.literal('mutation'),\n\t\t\tkey: approvalName,\n\t\t\tcallback: approvalMutationCallback,\n\t\t})\n\t\t.strict(),\n\tz\n\t\t.object({\n\t\t\tkind: z.literal('action'),\n\t\t\tkey: approvalName,\n\t\t\tcallback: approvalActionCallback,\n\t\t})\n\t\t.strict(),\n])\n\nexport const approvalNotifyStep = z\n\t.object({\n\t\tkind: z.literal('notify'),\n\t\tkey: approvalName,\n\t\tcallback: approvalActionCallback,\n\t})\n\t.strict()\n\nexport const approvalDecisionStep = z\n\t.object({\n\t\tkind: z.literal('decision'),\n\t\tkey: approvalName,\n\t\tdecisions: z.array(approvalDecision).min(1).max(MAX_APPROVAL_DECISIONS_PER_STEP),\n\t\tquorum: approvalQuorum,\n\t\tmakerChecker: z.boolean(),\n\t\texpiresAfterMs: z.number().int().positive().optional(),\n\t})\n\t.strict()\n\nexport const approvalBranchStep = z\n\t.object({\n\t\tkind: z.literal('branch'),\n\t\tkey: approvalName,\n\t\tapprovedStepKey: approvalName,\n\t\trejectedStepKey: approvalName,\n\t})\n\t.strict()\n\nexport const approvalWorkflowStep = z.discriminatedUnion('kind', [\n\tapprovalCallbackStep,\n\tapprovalNotifyStep,\n\tapprovalDecisionStep,\n\tapprovalBranchStep,\n])\n\nexport const approvalWorkflowDescriptor = z\n\t.object({\n\t\tschemaVersion: z.literal(APPROVAL_DESCRIPTOR_SCHEMA_VERSION),\n\t\tcompatibilityKey: approvalName,\n\t\tname: approvalName,\n\t\tsteps: z.array(approvalWorkflowStep).min(1).max(MAX_APPROVAL_WORKFLOW_STEPS),\n\t})\n\t.strict()\n\t.superRefine((descriptor, context) => {\n\t\tconst keys = new Set<string>()\n\t\tconst stepsByKey = new Map(descriptor.steps.map((step) => [step.key, step] as const))\n\t\tconst branchTargetOwners = new Map<string, number>()\n\t\tfor (const [index, step] of descriptor.steps.entries()) {\n\t\t\tif (keys.has(step.key))\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: 'custom',\n\t\t\t\t\tmessage: `Duplicate workflow step key: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index, 'key'],\n\t\t\t\t})\n\t\t\tkeys.add(step.key)\n\t\t\tif (step.kind === 'decision' && new Set(step.decisions).size !== step.decisions.length)\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: 'custom',\n\t\t\t\t\tmessage: `Duplicate decision value in step: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index, 'decisions'],\n\t\t\t\t})\n\t\t}\n\t\tfor (const [index, step] of descriptor.steps.entries()) {\n\t\t\tif (step.kind !== 'branch') continue\n\t\t\tif (descriptor.steps[index - 1]?.kind !== 'decision')\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: 'custom',\n\t\t\t\t\tmessage: `Branch must immediately follow a decision: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t})\n\t\t\tfor (const target of [step.approvedStepKey, step.rejectedStepKey]) {\n\t\t\t\tconst targetStep = stepsByKey.get(target)\n\t\t\t\tconst targetIndex = descriptor.steps.findIndex((candidate) => candidate.key === target)\n\t\t\t\tif (!targetStep)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tcode: 'custom',\n\t\t\t\t\t\tmessage: `Unknown branch target: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\telse if (\n\t\t\t\t\ttargetStep.kind !== 'mutation' &&\n\t\t\t\t\ttargetStep.kind !== 'action' &&\n\t\t\t\t\ttargetStep.kind !== 'notify'\n\t\t\t\t)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tcode: 'custom',\n\t\t\t\t\t\tmessage: `Branch target must be a callback step: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\telse if (targetIndex <= index)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tcode: 'custom',\n\t\t\t\t\t\tmessage: `Branch target must be declared after its branch: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\tbranchTargetOwners.set(target, (branchTargetOwners.get(target) ?? 0) + 1)\n\t\t\t}\n\t\t}\n\t\tfor (const [target, owners] of branchTargetOwners) {\n\t\t\tif (owners !== 1)\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tcode: 'custom',\n\t\t\t\t\tmessage: `Branch callback must belong to exactly one branch: ${target}`,\n\t\t\t\t\tpath: ['steps'],\n\t\t\t\t})\n\t\t}\n\t})\n\nexport const approvalRunDocument = z\n\t.object({\n\t\tscopeRef: approvalReference,\n\t\tresourceType: approvalName,\n\t\tresourceRef: approvalReference,\n\t\trequester: approvalActor,\n\t\tmetadata: approvalMetadata.optional(),\n\t\tworkflow: approvalWorkflowDescriptor,\n\t\tstate: approvalRunState,\n\t\tcurrentStepKey: approvalName.optional(),\n\t\texecutionFailedStepKey: approvalName.optional(),\n\t\texpiresAt: z.number().optional(),\n\t\tworkflowId: approvalReference.optional(),\n\t\tcreatedAt: z.number(),\n\t\tupdatedAt: z.number(),\n\t\tterminalAt: z.number().optional(),\n\t})\n\t.strict()\n\nexport const approvalDecisionDocument = z\n\t.object({\n\t\trunId: zid('approvalRuns'),\n\t\tstepKey: approvalName,\n\t\tactor: approvalActor,\n\t\tdecision: approvalDecision,\n\t\treason: approvalReason.optional(),\n\t\tdecidedAt: z.number(),\n\t})\n\t.strict()\n\nexport type ApprovalWorkflowDescriptor = z.infer<typeof approvalWorkflowDescriptor>\nexport type ApprovalActor = z.infer<typeof approvalActor>\nexport type ApprovalMetadata = z.infer<typeof approvalMetadata>\nexport type ApprovalCallbackInput = Readonly<z.infer<typeof approvalCallbackInput>>\n"],"mappings":"yPAqBA,MAAaA,EAAmBC,EAAE,KAAKC,CAAmB,EAC7CC,EAAmBF,EAAE,KAAKG,CAAkB,EAC5CC,EAAmBJ,EAAE,KAAKK,CAAmB,EAC7CC,EAAuBN,EAAE,KAAKO,CAAuB,EACrDC,EAAqBR,EAAE,KAAKS,CAAqB,EAEjDC,EAAoBV,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,GAAiC,EAE9EW,EAAeX,EAC1B,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAA,EAA4B,CAAC,CAC7B,MAAM,2BAA2B,EAEtBY,EAAiBZ,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAA,GAA8B,EAExEa,EAAmBb,EAC9B,OACAA,EACE,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAA,EAAoC,CAAC,CACrC,MAAM,wBAAwB,EAChCA,EAAE,OAAO,CAAC,CAAC,IAAA,GAAsC,CAClD,CAAC,CACA,OACC,GAAU,OAAO,KAAKc,CAAK,CAAC,CAAC,QAAA,GAC9B,yCACD,EAEKC,EAA2Bf,EAC/B,OAAO,CACP,QAASW,EACT,SAAUD,EACV,SAAUR,EACV,OAAQU,EAAe,SAAS,EAChC,UAAWZ,EAAE,OAAO,CACrB,CAAC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,QAAS,sDAAsDC,IAC/D,KAAM,CAAC,OAAO,CACf,CAAC,CAEJ,CAAC,EAEWK,EAAsB3C,EACjC,OAAO,CACP,SAAUU,EACV,aAAcC,EACd,YAAaD,EACb,UAAWU,EACX,SAAUP,EAAiB,SAAS,EACpC,SAAUiB,EACV,MAAO/B,EACP,eAAgBY,EAAa,SAAS,EACtC,uBAAwBA,EAAa,SAAS,EAC9C,UAAWX,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,WAAYU,EAAkB,SAAS,EACvC,UAAWV,EAAE,OAAO,EACpB,UAAWA,EAAE,OAAO,EACpB,WAAYA,EAAE,OAAO,CAAC,CAAC,SAAS,CACjC,CAAC,CAAC,CACD,OAAO,EAEI4C,EAA2B5C,EACtC,OAAO,CACP,MAAO6C,EAAI,cAAc,EACzB,QAASlC,EACT,MAAOS,EACP,SAAUlB,EACV,OAAQU,EAAe,SAAS,EAChC,UAAWZ,EAAE,OAAO,CACrB,CAAC,CAAC,CACD,OAAO"}
|
|
1
|
+
{"version":3,"file":"validators.mjs","names":["approvalNumber","k","approvalRunState","APPROVAL_RUN_STATES","approvalDecision","APPROVAL_DECISIONS","approvalStepKind","APPROVAL_STEP_KINDS","approvalCallbackKind","APPROVAL_CALLBACK_KINDS","approvalQuorumKind","APPROVAL_QUORUM_KINDS","approvalReference","approvalName","approvalReason","approvalMetadata","value","approvalCallbackEvidence","approvalCallbackTerminalEvidence","approvalCallbackInput","approvalCallbackArgs","approvalActor","approvalMutationCallback","approvalActionCallback","approvalCallback","approvalQuorum","approvalCallbackStep","approvalNotifyStep","approvalDecisionStep","approvalBranchStep","approvalWorkflowStep","approvalWorkflowDescriptor","keys","stepsByKey","descriptor","step","branchTargetOwners","index","context","target","targetStep","targetIndex","candidate","owners","approvalRunDocument","approvalDecisionDocument","approvalAuditEventProjection","approvalOptionalString"],"sources":["../../../src/components/approvals/validators.ts"],"sourcesContent":["import { k } from '../../k'\n\nimport {\n\tAPPROVAL_CALLBACK_KINDS,\n\tAPPROVAL_DECISIONS,\n\tAPPROVAL_DESCRIPTOR_SCHEMA_VERSION,\n\tAPPROVAL_QUORUM_KINDS,\n\tAPPROVAL_RUN_STATES,\n\tAPPROVAL_STEP_KINDS,\n\tMAX_APPROVAL_CAPABILITIES,\n\tMAX_APPROVAL_DECISIONS_PER_STEP,\n\tMAX_APPROVAL_METADATA_ENTRIES,\n\tMAX_APPROVAL_METADATA_KEY_LENGTH,\n\tMAX_APPROVAL_METADATA_VALUE_LENGTH,\n\tMAX_APPROVAL_NAME_LENGTH,\n\tMAX_APPROVAL_REASON_LENGTH,\n\tMAX_APPROVAL_REFERENCE_LENGTH,\n\tMAX_APPROVAL_WORKFLOW_STEPS,\n} from './constants'\n\n/** v1's `z.number()` rejected `NaN` and infinities on parse; natively this stays `v.number()`. */\nconst approvalNumber = k.number().refine(Number.isFinite, 'Expected a finite number')\n\nexport const approvalRunState = k.enum(APPROVAL_RUN_STATES)\nexport const approvalDecision = k.enum(APPROVAL_DECISIONS)\nexport const approvalStepKind = k.enum(APPROVAL_STEP_KINDS)\nexport const approvalCallbackKind = k.enum(APPROVAL_CALLBACK_KINDS)\nexport const approvalQuorumKind = k.enum(APPROVAL_QUORUM_KINDS)\n\nexport const approvalReference = k.string().trim().min(1).max(MAX_APPROVAL_REFERENCE_LENGTH)\n\nexport const approvalName = k\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(MAX_APPROVAL_NAME_LENGTH)\n\t.regex(/^[A-Za-z][A-Za-z0-9._-]*$/)\n\nexport const approvalReason = k.string().trim().min(1).max(MAX_APPROVAL_REASON_LENGTH)\n\nexport const approvalMetadata = k\n\t.record(\n\t\tk\n\t\t\t.string()\n\t\t\t.min(1)\n\t\t\t.max(MAX_APPROVAL_METADATA_KEY_LENGTH)\n\t\t\t.regex(/^(?![$_])[\\x20-\\x7E]+$/),\n\t\tk.string().max(MAX_APPROVAL_METADATA_VALUE_LENGTH),\n\t)\n\t.refine(\n\t\t(value) => Object.keys(value).length <= MAX_APPROVAL_METADATA_ENTRIES,\n\t\t`Metadata may contain at most ${MAX_APPROVAL_METADATA_ENTRIES} entries`,\n\t)\n\nconst approvalCallbackEvidence = k.object({\n\tstepKey: approvalName,\n\tactorRef: approvalReference,\n\tdecision: approvalDecision,\n\treason: approvalReason.optional(),\n\tdecidedAt: approvalNumber,\n})\n\nconst approvalCallbackTerminalEvidence = approvalCallbackEvidence.omit('stepKey')\n\nexport const approvalCallbackInput = k.object({\n\trunId: approvalReference,\n\tscopeRef: approvalReference,\n\tresourceType: approvalName,\n\tresourceRef: approvalReference,\n\tmetadata: approvalMetadata.optional(),\n\tdecision: k\n\t\t.object({\n\t\t\tstepKey: approvalName,\n\t\t\toutcome: k.union([approvalDecision, k.literal('expired')]),\n\t\t\tevidence: k.array(approvalCallbackEvidence),\n\t\t\tterminalEvidence: approvalCallbackTerminalEvidence.optional(),\n\t\t})\n\t\t.optional(),\n})\n\n/** Convex argument validator for approval mutation, action, and notify callbacks. */\nexport const approvalCallbackArgs = approvalCallbackInput.validator\n\nexport const approvalActor = k.object({\n\tactorRef: approvalReference,\n\tcapabilities: k.array(approvalName).max(MAX_APPROVAL_CAPABILITIES),\n\tmetadata: approvalMetadata.optional(),\n})\n\nexport const approvalMutationCallback = k.object({\n\tkind: k.literal('mutation'),\n\thandle: approvalReference,\n\tretry: k.boolean(),\n})\n\nexport const approvalActionCallback = k.object({\n\tkind: k.literal('action'),\n\thandle: approvalReference,\n\tretry: k.boolean(),\n})\n\nexport const approvalCallback = k.discriminatedUnion('kind', [\n\tapprovalMutationCallback,\n\tapprovalActionCallback,\n])\n\nexport const approvalQuorum = k.object({\n\tkind: approvalQuorumKind,\n\tapprovals: k.int().min(1).max(MAX_APPROVAL_DECISIONS_PER_STEP),\n})\n\nexport const approvalCallbackStep = k.discriminatedUnion('kind', [\n\tk.object({\n\t\tkind: k.literal('mutation'),\n\t\tkey: approvalName,\n\t\tcallback: approvalMutationCallback,\n\t}),\n\tk.object({\n\t\tkind: k.literal('action'),\n\t\tkey: approvalName,\n\t\tcallback: approvalActionCallback,\n\t}),\n])\n\nexport const approvalNotifyStep = k.object({\n\tkind: k.literal('notify'),\n\tkey: approvalName,\n\tcallback: approvalActionCallback,\n})\n\nexport const approvalDecisionStep = k.object({\n\tkind: k.literal('decision'),\n\tkey: approvalName,\n\tdecisions: k.array(approvalDecision).min(1).max(MAX_APPROVAL_DECISIONS_PER_STEP),\n\tquorum: approvalQuorum,\n\tmakerChecker: k.boolean(),\n\t// v1's `.int()` accepted safe integers only.\n\texpiresAfterMs: k.int().min(1).refine(Number.isSafeInteger, 'Expected a safe integer').optional(),\n})\n\nexport const approvalBranchStep = k.object({\n\tkind: k.literal('branch'),\n\tkey: approvalName,\n\tapprovedStepKey: approvalName,\n\trejectedStepKey: approvalName,\n})\n\n/**\n * A plain union, not a discriminated one: its first member is itself a union over `kind`, which a\n * discriminated union cannot dispatch to. Natively both are the same `v.union`.\n */\nexport const approvalWorkflowStep = k.union([\n\tapprovalCallbackStep,\n\tapprovalNotifyStep,\n\tapprovalDecisionStep,\n\tapprovalBranchStep,\n])\n\nexport const approvalWorkflowDescriptor = k\n\t.object({\n\t\tschemaVersion: k.literal(APPROVAL_DESCRIPTOR_SCHEMA_VERSION),\n\t\tcompatibilityKey: approvalName,\n\t\tname: approvalName,\n\t\tsteps: k.array(approvalWorkflowStep).min(1).max(MAX_APPROVAL_WORKFLOW_STEPS),\n\t})\n\t.check((descriptor, context) => {\n\t\tconst keys = new Set<string>()\n\t\tconst stepsByKey = new Map(descriptor.steps.map((step) => [step.key, step] as const))\n\t\tconst branchTargetOwners = new Map<string, number>()\n\t\tfor (const [index, step] of descriptor.steps.entries()) {\n\t\t\tif (keys.has(step.key))\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tmessage: `Duplicate workflow step key: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index, 'key'],\n\t\t\t\t})\n\t\t\tkeys.add(step.key)\n\t\t\tif (step.kind === 'decision' && new Set(step.decisions).size !== step.decisions.length)\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tmessage: `Duplicate decision value in step: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index, 'decisions'],\n\t\t\t\t})\n\t\t}\n\t\tfor (const [index, step] of descriptor.steps.entries()) {\n\t\t\tif (step.kind !== 'branch') continue\n\t\t\tif (descriptor.steps[index - 1]?.kind !== 'decision')\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tmessage: `Branch must immediately follow a decision: ${step.key}`,\n\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t})\n\t\t\tfor (const target of [step.approvedStepKey, step.rejectedStepKey]) {\n\t\t\t\tconst targetStep = stepsByKey.get(target)\n\t\t\t\tconst targetIndex = descriptor.steps.findIndex((candidate) => candidate.key === target)\n\t\t\t\tif (!targetStep)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tmessage: `Unknown branch target: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\telse if (\n\t\t\t\t\ttargetStep.kind !== 'mutation' &&\n\t\t\t\t\ttargetStep.kind !== 'action' &&\n\t\t\t\t\ttargetStep.kind !== 'notify'\n\t\t\t\t)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tmessage: `Branch target must be a callback step: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\telse if (targetIndex <= index)\n\t\t\t\t\tcontext.addIssue({\n\t\t\t\t\t\tmessage: `Branch target must be declared after its branch: ${target}`,\n\t\t\t\t\t\tpath: ['steps', index],\n\t\t\t\t\t})\n\t\t\t\tbranchTargetOwners.set(target, (branchTargetOwners.get(target) ?? 0) + 1)\n\t\t\t}\n\t\t}\n\t\tfor (const [target, owners] of branchTargetOwners) {\n\t\t\tif (owners !== 1)\n\t\t\t\tcontext.addIssue({\n\t\t\t\t\tmessage: `Branch callback must belong to exactly one branch: ${target}`,\n\t\t\t\t\tpath: ['steps'],\n\t\t\t\t})\n\t\t}\n\t})\n\nexport const approvalRunDocument = k.object({\n\tscopeRef: approvalReference,\n\tresourceType: approvalName,\n\tresourceRef: approvalReference,\n\trequester: approvalActor,\n\tmetadata: approvalMetadata.optional(),\n\tworkflow: approvalWorkflowDescriptor,\n\tstate: approvalRunState,\n\tcurrentStepKey: approvalName.optional(),\n\texecutionFailedStepKey: approvalName.optional(),\n\texpiresAt: approvalNumber.optional(),\n\tworkflowId: approvalReference.optional(),\n\tcreatedAt: approvalNumber,\n\tupdatedAt: approvalNumber,\n\tterminalAt: approvalNumber.optional(),\n})\n\nexport const approvalDecisionDocument = k.object({\n\trunId: k.id('approvalRuns'),\n\tstepKey: approvalName,\n\tactor: approvalActor,\n\tdecision: approvalDecision,\n\treason: approvalReason.optional(),\n\tdecidedAt: approvalNumber,\n})\n\n/**\n * The fields `approvals.audit.history` reads from an audit-log event. Unknown keys are stripped, as\n * v1's non-strict Zod objects did, and a non-string `actorId` is dropped by the caller.\n */\nexport const approvalAuditEventProjection = k\n\t.object({\n\t\taction: k.string(),\n\t\tactorId: k.any().optional(),\n\t\tmetadata: k.object({ correlationKey: k.string(), transition: k.string() }).strip(),\n\t})\n\t.strip()\n\nexport const approvalOptionalString = k.string().optional()\n\nexport type ApprovalWorkflowDescriptor = k.infer<typeof approvalWorkflowDescriptor>\nexport type ApprovalActor = k.infer<typeof approvalActor>\nexport type ApprovalMetadata = k.infer<typeof approvalMetadata>\nexport type ApprovalCallbackInput = Readonly<k.infer<typeof approvalCallbackInput>>\n"],"mappings":"A,qMAqBA,MAAMA,EAAiBC,EAAE,OAAO,CAAC,CAAC,OAAO,OAAO,SAAU,0BAA0B,EAEvEC,EAAmBD,EAAE,KAAKE,CAAmB,EAC7CC,EAAmBH,EAAE,KAAKI,CAAkB,EAC5CC,EAAmBL,EAAE,KAAKM,CAAmB,EAC7CC,EAAuBP,EAAE,KAAKQ,CAAuB,EACrDC,EAAqBT,EAAE,KAAKU,CAAqB,EAEjDC,EAAoBX,EA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("convex/server").RegisteredMutation<"internal", import("@convex-dev/workflow").WorkflowArgs<{
|
|
7
7
|
runId: import("convex/values").VId<import("convex/values").GenericId<"approvalRuns">, "required">;
|
|
8
8
|
}>, import("@convex-dev/workflow").WorkflowMutationResult<null>>;
|
|
9
|
-
//#endregion
|
|
10
9
|
export { workflow_d_exports };
|
|
11
10
|
//# sourceMappingURL=workflow.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{components as e,internal as t}from"./_generated/api.mjs";import{APPROVAL_DECISIONS as n,APPROVAL_RUN_STATES as r}from"./constants.mjs";import{approvalDecisionEventName as i,callbackReference as a,resolveWorkflowStepIndex as o}from"./workflow_steps.mjs";import{v as s}from"convex/values";import{WorkflowManager as c}from"@convex-dev/workflow";const l=new c(e.workflow),u=l.define({args:{runId:s.id(`approvalRuns`)},returns:s.null(),handler:async(e,a)=>{let c;try{let l=await e.runQuery(t.requests.getForWorkflow,{runId:a.runId},{name:`loadLinkedApproval`});if(!l)throw Error(`Approval request not found`);if(l.workflowId!==e.workflowId)throw Error(`Approval workflow linkage is incomplete`);let u=d(l),p=l.workflow.steps.map(e=>e.key),m=new Set(l.workflow.steps.flatMap(e=>e.kind===`branch`?[e.approvedStepKey,e.rejectedStepKey]:[])),h=null,g=null,_,v=0;for(;v<l.workflow.steps.length;){let a=l.workflow.steps[v];if(a.kind===`mutation`||a.kind===`action`||a.kind===`notify`){if(m.has(a.key)){v+=1;continue}c=a.key,await f(e,a,u),c=void 0,v+=1;continue}if(a.kind===`decision`){await e.runMutation(t.decisions.enter,{runId:l._id,stepKey:a.key,workflowId:e.workflowId,expiresAfterMs:a.expiresAfterMs},{name:`enter:${a.key}`});let o=await e.awaitEvent({name:i(l._id,a.key),validator:s.object({outcome:s.union(s.literal(n[0]),s.literal(n[1]),s.literal(r[3])),terminalEvidence:s.optional(s.object({actorRef:s.string(),decision:s.union(s.literal(n[0]),s.literal(n[1])),reason:s.optional(s.string()),decidedAt:s.number()}))})});if(h=o.outcome,_=o.terminalEvidence,g=a.key,h!==`approved`&&l.workflow.steps[v+1]?.kind!==`branch`)break;v+=1;continue}if(!h)throw Error(`Branch requires a preceding decision step`);let d=h===`approved`?a.approvedStepKey:a.rejectedStepKey,y=o(p,d),b=l.workflow.steps[y];if(b.kind!==`mutation`&&b.kind!==`action`&&b.kind!==`notify`)throw Error(`Approval branch target must be a callback step`);let x=await e.runQuery(t.decisions.listForWorkflow,{runId:l._id,stepKey:g??a.key},{name:`evidence:${a.key}`});if(c=b.key,await f(e,b,{...u,decision:{stepKey:g??a.key,outcome:h,evidence:x,terminalEvidence:_}}),c=void 0,h===`rejected`||h===`expired`)break;v+=1}return await e.runMutation(t.requests.recordExecutionTerminal,{runId:l._id,outcome:`completed`},{name:`recordExecutionCompleted`}),null}catch(n){throw await e.runMutation(t.requests.recordExecutionTerminal,{runId:a.runId,outcome:`failed`,failedStepKey:c},{name:`recordExecutionFailed`}),n}}});function d(e){return{runId:e._id,scopeRef:e.scopeRef,resourceType:e.resourceType,resourceRef:e.resourceRef,metadata:e.metadata}}async function f(e,t,n){
|
|
1
|
+
import{components as e,internal as t}from"./_generated/api.mjs";import{APPROVAL_DECISIONS as n,APPROVAL_RUN_STATES as r}from"./constants.mjs";import{approvalDecisionEventName as i,callbackReference as a,resolveWorkflowStepIndex as o}from"./workflow_steps.mjs";import{v as s}from"convex/values";import{WorkflowManager as c}from"@convex-dev/workflow";const l=new c(e.workflow),u=l.define({args:{runId:s.id(`approvalRuns`)},returns:s.null(),handler:async(e,a)=>{let c;try{let l=await e.runQuery(t.requests.getForWorkflow,{runId:a.runId},{name:`loadLinkedApproval`});if(!l)throw Error(`Approval request not found`);if(l.workflowId!==e.workflowId)throw Error(`Approval workflow linkage is incomplete`);let u=d(l),p=l.workflow.steps.map(e=>e.key),m=new Set(l.workflow.steps.flatMap(e=>e.kind===`branch`?[e.approvedStepKey,e.rejectedStepKey]:[])),h=null,g=null,_,v=0;for(;v<l.workflow.steps.length;){let a=l.workflow.steps[v];if(a.kind===`mutation`||a.kind===`action`||a.kind===`notify`){if(m.has(a.key)){v+=1;continue}c=a.key,await f(e,a,u),c=void 0,v+=1;continue}if(a.kind===`decision`){await e.runMutation(t.decisions.enter,{runId:l._id,stepKey:a.key,workflowId:e.workflowId,expiresAfterMs:a.expiresAfterMs},{name:`enter:${a.key}`});let o=await e.awaitEvent({name:i(l._id,a.key),validator:s.object({outcome:s.union(s.literal(n[0]),s.literal(n[1]),s.literal(r[3])),terminalEvidence:s.optional(s.object({actorRef:s.string(),decision:s.union(s.literal(n[0]),s.literal(n[1])),reason:s.optional(s.string()),decidedAt:s.number()}))})});if(h=o.outcome,_=o.terminalEvidence,g=a.key,h!==`approved`&&l.workflow.steps[v+1]?.kind!==`branch`)break;v+=1;continue}if(!h)throw Error(`Branch requires a preceding decision step`);let d=h===`approved`?a.approvedStepKey:a.rejectedStepKey,y=o(p,d),b=l.workflow.steps[y];if(b.kind!==`mutation`&&b.kind!==`action`&&b.kind!==`notify`)throw Error(`Approval branch target must be a callback step`);let x=await e.runQuery(t.decisions.listForWorkflow,{runId:l._id,stepKey:g??a.key},{name:`evidence:${a.key}`});if(c=b.key,await f(e,b,{...u,decision:{stepKey:g??a.key,outcome:h,evidence:x,terminalEvidence:_}}),c=void 0,h===`rejected`||h===`expired`)break;v+=1}return await e.runMutation(t.requests.recordExecutionTerminal,{runId:l._id,outcome:`completed`},{name:`recordExecutionCompleted`}),null}catch(n){throw await e.runMutation(t.requests.recordExecutionTerminal,{runId:a.runId,outcome:`failed`,failedStepKey:c},{name:`recordExecutionFailed`}),n}}});function d(e){return{runId:e._id,scopeRef:e.scopeRef,resourceType:e.resourceType,resourceRef:e.resourceRef,metadata:e.metadata}}async function f(e,t,n){t.callback.kind===`mutation`?await e.runMutation(a(t.callback.handle),n,{name:t.key}):await e.runAction(a(t.callback.handle),n,{name:t.key,retry:t.callback.retry})}export{l as approvalWorkflow,u as run};
|
|
2
2
|
//# sourceMappingURL=workflow.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow.mjs","names":["approvalWorkflow","WorkflowManager","components","run","v","failedStepKey","step","internal","input","callbackInput","buildCallbackInput","stepKeys","workflowStep","branchTargets","lastDecision","lastDecisionStepKey","terminalEvidence","index","executeCallback","event","approvalDecisionEventName","APPROVAL_DECISIONS","APPROVAL_RUN_STATES","targetKey","targetIndex","resolveWorkflowStepIndex","target","evidence","error","callbackReference"],"sources":["../../../src/components/approvals/workflow.ts"],"sourcesContent":["import type { ApprovalCallbackInput } from './validators'\nimport { WorkflowManager, type WorkflowCtx } from '@convex-dev/workflow'\nimport { v } from 'convex/values'\n\nimport { components, internal } from './_generated/api'\nimport type { Doc } from './_generated/dataModel'\nimport { APPROVAL_DECISIONS, APPROVAL_RUN_STATES } from './constants'\nimport {\n\tapprovalDecisionEventName,\n\tcallbackReference,\n\tresolveWorkflowStepIndex,\n} from './workflow_steps'\n\nexport const approvalWorkflow = new WorkflowManager(components.workflow)\n\nexport const run = approvalWorkflow.define({\n\targs: { runId: v.id('approvalRuns') },\n\treturns: v.null(),\n\thandler: async (step, input) => {\n\t\tlet failedStepKey: string | undefined\n\t\ttry {\n\t\t\tconst run: Doc<'approvalRuns'> | null = await step.runQuery(\n\t\t\t\tinternal.requests.getForWorkflow,\n\t\t\t\t{ runId: input.runId },\n\t\t\t\t{ name: 'loadLinkedApproval' },\n\t\t\t)\n\t\t\tif (!run) throw new Error('Approval request not found')\n\t\t\tif (run.workflowId !== step.workflowId)\n\t\t\t\tthrow new Error('Approval workflow linkage is incomplete')\n\n\t\t\tconst callbackInput = buildCallbackInput(run)\n\t\t\tconst stepKeys = run.workflow.steps.map((workflowStep) => workflowStep.key)\n\t\t\tconst branchTargets = new Set(\n\t\t\t\trun.workflow.steps.flatMap((workflowStep) =>\n\t\t\t\t\tworkflowStep.kind === 'branch'\n\t\t\t\t\t\t? [workflowStep.approvedStepKey, workflowStep.rejectedStepKey]\n\t\t\t\t\t\t: [],\n\t\t\t\t),\n\t\t\t)\n\t\t\tlet lastDecision: 'approved' | 'rejected' | 'expired' | null = null\n\t\t\tlet lastDecisionStepKey: string | null = null\n\t\t\tlet terminalEvidence:\n\t\t\t\t| {\n\t\t\t\t\t\tactorRef: string\n\t\t\t\t\t\tdecision: 'approved' | 'rejected'\n\t\t\t\t\t\treason?: string\n\t\t\t\t\t\tdecidedAt: number\n\t\t\t\t }\n\t\t\t\t| undefined\n\t\t\tlet index = 0\n\t\t\twhile (index < run.workflow.steps.length) {\n\t\t\t\tconst workflowStep = run.workflow.steps[index]\n\t\t\t\tif (\n\t\t\t\t\tworkflowStep.kind === 'mutation' ||\n\t\t\t\t\tworkflowStep.kind === 'action' ||\n\t\t\t\t\tworkflowStep.kind === 'notify'\n\t\t\t\t) {\n\t\t\t\t\tif (branchTargets.has(workflowStep.key)) {\n\t\t\t\t\t\tindex += 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfailedStepKey = workflowStep.key\n\t\t\t\t\tawait executeCallback(step, workflowStep, callbackInput)\n\t\t\t\t\tfailedStepKey = undefined\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (workflowStep.kind === 'decision') {\n\t\t\t\t\tawait step.runMutation(\n\t\t\t\t\t\tinternal.decisions.enter,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trunId: run._id,\n\t\t\t\t\t\t\tstepKey: workflowStep.key,\n\t\t\t\t\t\t\tworkflowId: step.workflowId,\n\t\t\t\t\t\t\texpiresAfterMs: workflowStep.expiresAfterMs,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ name: `enter:${workflowStep.key}` },\n\t\t\t\t\t)\n\t\t\t\t\tconst event = await step.awaitEvent({\n\t\t\t\t\t\tname: approvalDecisionEventName(run._id, workflowStep.key),\n\t\t\t\t\t\tvalidator: v.object({\n\t\t\t\t\t\t\toutcome: v.union(\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[0]),\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[1]),\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_RUN_STATES[3]),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tterminalEvidence: v.optional(\n\t\t\t\t\t\t\t\tv.object({\n\t\t\t\t\t\t\t\t\tactorRef: v.string(),\n\t\t\t\t\t\t\t\t\tdecision: v.union(\n\t\t\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[0]),\n\t\t\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[1]),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\treason: v.optional(v.string()),\n\t\t\t\t\t\t\t\t\tdecidedAt: v.number(),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t\tlastDecision = event.outcome\n\t\t\t\t\tterminalEvidence = event.terminalEvidence\n\t\t\t\t\tlastDecisionStepKey = workflowStep.key\n\t\t\t\t\tif (lastDecision !== 'approved' && run.workflow.steps[index + 1]?.kind !== 'branch') break\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!lastDecision) throw new Error('Branch requires a preceding decision step')\n\t\t\t\tconst targetKey =\n\t\t\t\t\tlastDecision === 'approved' ? workflowStep.approvedStepKey : workflowStep.rejectedStepKey\n\t\t\t\tconst targetIndex = resolveWorkflowStepIndex(stepKeys, targetKey)\n\t\t\t\tconst target = run.workflow.steps[targetIndex]\n\t\t\t\tif (target.kind !== 'mutation' && target.kind !== 'action' && target.kind !== 'notify')\n\t\t\t\t\tthrow new Error('Approval branch target must be a callback step')\n\t\t\t\tconst evidence = await step.runQuery(\n\t\t\t\t\tinternal.decisions.listForWorkflow,\n\t\t\t\t\t{ runId: run._id, stepKey: lastDecisionStepKey ?? workflowStep.key },\n\t\t\t\t\t{ name: `evidence:${workflowStep.key}` },\n\t\t\t\t)\n\t\t\t\tfailedStepKey = target.key\n\t\t\t\tawait executeCallback(step, target, {\n\t\t\t\t\t...callbackInput,\n\t\t\t\t\tdecision: {\n\t\t\t\t\t\tstepKey: lastDecisionStepKey ?? workflowStep.key,\n\t\t\t\t\t\toutcome: lastDecision,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\tterminalEvidence: terminalEvidence,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tfailedStepKey = undefined\n\t\t\t\tif (lastDecision === 'rejected' || lastDecision === 'expired') break\n\t\t\t\tindex += 1\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tawait step.runMutation(\n\t\t\t\tinternal.requests.recordExecutionTerminal,\n\t\t\t\t{ runId: run._id, outcome: 'completed' },\n\t\t\t\t{ name: 'recordExecutionCompleted' },\n\t\t\t)\n\t\t\treturn null\n\t\t} catch (error) {\n\t\t\tawait step.runMutation(\n\t\t\t\tinternal.requests.recordExecutionTerminal,\n\t\t\t\t{\n\t\t\t\t\trunId: input.runId,\n\t\t\t\t\toutcome: 'failed',\n\t\t\t\t\tfailedStepKey: failedStepKey,\n\t\t\t\t},\n\t\t\t\t{ name: 'recordExecutionFailed' },\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\t},\n})\n\ntype CallbackStep = Extract<\n\tDoc<'approvalRuns'>['workflow']['steps'][number],\n\t{ kind: 'mutation' | 'action' | 'notify' }\n>\n\nfunction buildCallbackInput(run: Doc<'approvalRuns'>): ApprovalCallbackInput {\n\treturn {\n\t\trunId: run._id,\n\t\tscopeRef: run.scopeRef,\n\t\tresourceType: run.resourceType,\n\t\tresourceRef: run.resourceRef,\n\t\tmetadata: run.metadata,\n\t}\n}\n\nasync function executeCallback(\n\tstep: WorkflowCtx,\n\tworkflowStep: CallbackStep,\n\tinput: ApprovalCallbackInput,\n): Promise<void> {\n\tif (workflowStep.callback.kind === 'mutation') {\n\t\tawait step.runMutation(callbackReference<'mutation'>(workflowStep.callback.handle), input, {\n\t\t\tname: workflowStep.key,\n\t\t})\n\t\treturn\n\t}\n\tawait step.runAction(callbackReference<'action'>(workflowStep.callback.handle), input, {\n\t\tname: workflowStep.key,\n\t\tretry: workflowStep.callback.retry,\n\t})\n}\n"],"mappings":"6VAaA,MAAaA,EAAmB,IAAIC,EAAgBC,EAAW,QAAQ,EAE1DC,EAAMH,EAAiB,OAAO,CAC1C,KAAM,CAAE,MAAOI,EAAE,GAAG,cAAc,CAAE,EACpC,QAASA,EAAE,KAAK,EAChB,QAAS,MAAO,EAAM,IAAU,CAC/B,IAAIC,EACJ,GAAI,CACH,IAAMF,EAAkC,MAAMG,EAAK,SAClDC,EAAS,SAAS,eAClB,CAAE,MAAOC,EAAM,KAAM,EACrB,CAAE,KAAM,oBAAqB,CAC9B,EACA,GAAI,CAACL,EAAK,MAAU,MAAM,4BAA4B,EACtD,GAAIA,EAAI,aAAeG,EAAK,WAC3B,MAAU,MAAM,yCAAyC,EAE1D,IAAMG,EAAgBC,EAAmBP,CAAG,EACtCQ,EAAWR,EAAI,SAAS,MAAM,IAAK,GAAiBS,EAAa,GAAG,EACpEC,EAAgB,IAAI,IACzBV,EAAI,SAAS,MAAM,QAAS,GAC3BS,EAAa,OAAS,SACnB,CAACA,EAAa,gBAAiBA,EAAa,eAAe,EAC3D,CAAC,CACL,CACD,EACIE,EAA2D,KAC3DC,EAAqC,KACrCC,EAQAC,EAAQ,EACZ,KAAOA,EAAQd,EAAI,SAAS,MAAM,QAAQ,CACzC,IAAMS,EAAeT,EAAI,SAAS,MAAMc,GACxC,GACCL,EAAa,OAAS,YACtBA,EAAa,OAAS,UACtBA,EAAa,OAAS,SACrB,CACD,GAAIC,EAAc,IAAID,EAAa,GAAG,EAAG,CACxC,GAAS,EACT,QACD,CACA,EAAgBA,EAAa,IAC7B,MAAMM,EAAgBZ,EAAMM,EAAcH,CAAa,EACvD,EAAgB,IAAA,GAChB,GAAS,EACT,QACD,CACA,GAAIG,EAAa,OAAS,WAAY,CACrC,M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AAYA,EAAa,KAAM,CACxC,EAYA,GAXA,EAAgBc,EAAO,IACvB,MAAMR,EAAgBZ,EAAMoB,EAAQ,CACnC,GAAGjB,EACH,SAAU,CACT,QAASM,GAAuBH,EAAa,IAC7C,QAASE,EACT,WACkB,kBACnB,CACD,CAAC,EACD,EAAgB,IAAA,GACZA,IAAiB,YAAcA,IAAiB,UAAW,MAC/D,GAAS,CAEV,CAOA,OALA,MAAMR,EAAK,YACVC,EAAS,SAAS,wBAClB,CAAE,MAAOJ,EAAI,IAAK,QAAS,WAAY,EACvC,CAAE,KAAM,0BAA2B,CACpC,EACO,IACR,OAASyB,EAAO,CAUf,MATA,MAAMtB,EAAK,YACVC,EAAS,SAAS,wBAClB,CACC,MAAOC,EAAM,MACb,QAAS,SACM,eAChB,EACA,CAAE,KAAM,uBAAwB,CACjC,EACMoB,CACP,CACD,CACD,CAAC,EAOD,SAASlB,EAAmB,EAAiD,CAC5E,MAAO,CACN,MAAOP,EAAI,IACX,SAAUA,EAAI,SACd,aAAcA,EAAI,aAClB,YAAaA,EAAI,YACjB,SAAUA,EAAI,QACf,CACD,CAEA,eAAee,EACd,EACA,EACA,EACgB,CAChB,GAAIN,EAAa,SAAS,OAAS,WAAY,CAC9C,MAAMN,EAAK,YAAYuB,EAA8BjB,EAAa,SAAS,MAAM,EAAGJ,EAAO,CAC1F,KAAMI,EAAa,GACpB,CAAC,EACD,MACD,CACA,MAAMN,EAAK,UAAUuB,EAA4BjB,EAAa,SAAS,MAAM,EAAGJ,EAAO,CACtF,KAAMI,EAAa,IACnB,MAAOA,EAAa,SAAS,KAC9B,CAAC,CACF"}
|
|
1
|
+
{"version":3,"file":"workflow.mjs","names":["approvalWorkflow","WorkflowManager","components","run","v","failedStepKey","step","internal","input","callbackInput","buildCallbackInput","stepKeys","workflowStep","branchTargets","lastDecision","lastDecisionStepKey","terminalEvidence","index","executeCallback","event","approvalDecisionEventName","APPROVAL_DECISIONS","APPROVAL_RUN_STATES","targetKey","targetIndex","resolveWorkflowStepIndex","target","evidence","error","callbackReference"],"sources":["../../../src/components/approvals/workflow.ts"],"sourcesContent":["import type { ApprovalCallbackInput } from './validators'\nimport { WorkflowManager, type WorkflowCtx } from '@convex-dev/workflow'\nimport { v } from 'convex/values'\n\nimport { components, internal } from './_generated/api'\nimport type { Doc } from './_generated/dataModel'\nimport { APPROVAL_DECISIONS, APPROVAL_RUN_STATES } from './constants'\nimport {\n\tapprovalDecisionEventName,\n\tcallbackReference,\n\tresolveWorkflowStepIndex,\n} from './workflow_steps'\n\nexport const approvalWorkflow = new WorkflowManager(components.workflow)\n\nexport const run = approvalWorkflow.define({\n\targs: { runId: v.id('approvalRuns') },\n\treturns: v.null(),\n\thandler: async (step, input) => {\n\t\tlet failedStepKey: string | undefined\n\t\ttry {\n\t\t\tconst run: Doc<'approvalRuns'> | null = await step.runQuery(\n\t\t\t\tinternal.requests.getForWorkflow,\n\t\t\t\t{ runId: input.runId },\n\t\t\t\t{ name: 'loadLinkedApproval' },\n\t\t\t)\n\t\t\tif (!run) throw new Error('Approval request not found')\n\t\t\tif (run.workflowId !== step.workflowId)\n\t\t\t\tthrow new Error('Approval workflow linkage is incomplete')\n\n\t\t\tconst callbackInput = buildCallbackInput(run)\n\t\t\tconst stepKeys = run.workflow.steps.map((workflowStep) => workflowStep.key)\n\t\t\tconst branchTargets = new Set(\n\t\t\t\trun.workflow.steps.flatMap((workflowStep) =>\n\t\t\t\t\tworkflowStep.kind === 'branch'\n\t\t\t\t\t\t? [workflowStep.approvedStepKey, workflowStep.rejectedStepKey]\n\t\t\t\t\t\t: [],\n\t\t\t\t),\n\t\t\t)\n\t\t\tlet lastDecision: 'approved' | 'rejected' | 'expired' | null = null\n\t\t\tlet lastDecisionStepKey: string | null = null\n\t\t\tlet terminalEvidence:\n\t\t\t\t| {\n\t\t\t\t\t\tactorRef: string\n\t\t\t\t\t\tdecision: 'approved' | 'rejected'\n\t\t\t\t\t\treason?: string\n\t\t\t\t\t\tdecidedAt: number\n\t\t\t\t }\n\t\t\t\t| undefined\n\t\t\tlet index = 0\n\t\t\twhile (index < run.workflow.steps.length) {\n\t\t\t\tconst workflowStep = run.workflow.steps[index]\n\t\t\t\tif (\n\t\t\t\t\tworkflowStep.kind === 'mutation' ||\n\t\t\t\t\tworkflowStep.kind === 'action' ||\n\t\t\t\t\tworkflowStep.kind === 'notify'\n\t\t\t\t) {\n\t\t\t\t\tif (branchTargets.has(workflowStep.key)) {\n\t\t\t\t\t\tindex += 1\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfailedStepKey = workflowStep.key\n\t\t\t\t\tawait executeCallback(step, workflowStep, callbackInput)\n\t\t\t\t\tfailedStepKey = undefined\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (workflowStep.kind === 'decision') {\n\t\t\t\t\tawait step.runMutation(\n\t\t\t\t\t\tinternal.decisions.enter,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trunId: run._id,\n\t\t\t\t\t\t\tstepKey: workflowStep.key,\n\t\t\t\t\t\t\tworkflowId: step.workflowId,\n\t\t\t\t\t\t\texpiresAfterMs: workflowStep.expiresAfterMs,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ name: `enter:${workflowStep.key}` },\n\t\t\t\t\t)\n\t\t\t\t\tconst event = await step.awaitEvent({\n\t\t\t\t\t\tname: approvalDecisionEventName(run._id, workflowStep.key),\n\t\t\t\t\t\tvalidator: v.object({\n\t\t\t\t\t\t\toutcome: v.union(\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[0]),\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[1]),\n\t\t\t\t\t\t\t\tv.literal(APPROVAL_RUN_STATES[3]),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tterminalEvidence: v.optional(\n\t\t\t\t\t\t\t\tv.object({\n\t\t\t\t\t\t\t\t\tactorRef: v.string(),\n\t\t\t\t\t\t\t\t\tdecision: v.union(\n\t\t\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[0]),\n\t\t\t\t\t\t\t\t\t\tv.literal(APPROVAL_DECISIONS[1]),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\treason: v.optional(v.string()),\n\t\t\t\t\t\t\t\t\tdecidedAt: v.number(),\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}),\n\t\t\t\t\t})\n\t\t\t\t\tlastDecision = event.outcome\n\t\t\t\t\tterminalEvidence = event.terminalEvidence\n\t\t\t\t\tlastDecisionStepKey = workflowStep.key\n\t\t\t\t\tif (lastDecision !== 'approved' && run.workflow.steps[index + 1]?.kind !== 'branch') break\n\t\t\t\t\tindex += 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (!lastDecision) throw new Error('Branch requires a preceding decision step')\n\t\t\t\tconst targetKey =\n\t\t\t\t\tlastDecision === 'approved' ? workflowStep.approvedStepKey : workflowStep.rejectedStepKey\n\t\t\t\tconst targetIndex = resolveWorkflowStepIndex(stepKeys, targetKey)\n\t\t\t\tconst target = run.workflow.steps[targetIndex]\n\t\t\t\tif (target.kind !== 'mutation' && target.kind !== 'action' && target.kind !== 'notify')\n\t\t\t\t\tthrow new Error('Approval branch target must be a callback step')\n\t\t\t\tconst evidence = await step.runQuery(\n\t\t\t\t\tinternal.decisions.listForWorkflow,\n\t\t\t\t\t{ runId: run._id, stepKey: lastDecisionStepKey ?? workflowStep.key },\n\t\t\t\t\t{ name: `evidence:${workflowStep.key}` },\n\t\t\t\t)\n\t\t\t\tfailedStepKey = target.key\n\t\t\t\tawait executeCallback(step, target, {\n\t\t\t\t\t...callbackInput,\n\t\t\t\t\tdecision: {\n\t\t\t\t\t\tstepKey: lastDecisionStepKey ?? workflowStep.key,\n\t\t\t\t\t\toutcome: lastDecision,\n\t\t\t\t\t\tevidence,\n\t\t\t\t\t\tterminalEvidence: terminalEvidence,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\tfailedStepKey = undefined\n\t\t\t\tif (lastDecision === 'rejected' || lastDecision === 'expired') break\n\t\t\t\tindex += 1\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tawait step.runMutation(\n\t\t\t\tinternal.requests.recordExecutionTerminal,\n\t\t\t\t{ runId: run._id, outcome: 'completed' },\n\t\t\t\t{ name: 'recordExecutionCompleted' },\n\t\t\t)\n\t\t\treturn null\n\t\t} catch (error) {\n\t\t\tawait step.runMutation(\n\t\t\t\tinternal.requests.recordExecutionTerminal,\n\t\t\t\t{\n\t\t\t\t\trunId: input.runId,\n\t\t\t\t\toutcome: 'failed',\n\t\t\t\t\tfailedStepKey: failedStepKey,\n\t\t\t\t},\n\t\t\t\t{ name: 'recordExecutionFailed' },\n\t\t\t)\n\t\t\tthrow error\n\t\t}\n\t},\n})\n\ntype CallbackStep = Extract<\n\tDoc<'approvalRuns'>['workflow']['steps'][number],\n\t{ kind: 'mutation' | 'action' | 'notify' }\n>\n\nfunction buildCallbackInput(run: Doc<'approvalRuns'>): ApprovalCallbackInput {\n\treturn {\n\t\trunId: run._id,\n\t\tscopeRef: run.scopeRef,\n\t\tresourceType: run.resourceType,\n\t\tresourceRef: run.resourceRef,\n\t\tmetadata: run.metadata,\n\t}\n}\n\nasync function executeCallback(\n\tstep: WorkflowCtx,\n\tworkflowStep: CallbackStep,\n\tinput: ApprovalCallbackInput,\n): Promise<void> {\n\tif (workflowStep.callback.kind === 'mutation') {\n\t\tawait step.runMutation(callbackReference<'mutation'>(workflowStep.callback.handle), input, {\n\t\t\tname: workflowStep.key,\n\t\t})\n\t\treturn\n\t}\n\tawait step.runAction(callbackReference<'action'>(workflowStep.callback.handle), input, {\n\t\tname: workflowStep.key,\n\t\tretry: workflowStep.callback.retry,\n\t})\n}\n"],"mappings":"A,6VAaA,MAAaA,EAAmB,IAAIC,EAAgBC,EAAW,QAAQ,EAE1DC,EAAMH,EAAiB,OAAO,CAC1C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S,CAEV,CAOA,OALA,MAAMR,EAAK,YACVC,EAAS,SAAS,wBAClB,CAAE,MAAOJ,EAAI,IAAK,QAAS,WAAY,EACvC,CAAE,KAAM,0BAA2B,CACpC,EACO,IACR,OAASyB,EAAO,CAUf,MATA,MAAMtB,EAAK,YACVC,EAAS,SAAS,wBAClB,CACC,MAAOC,EAAM,MACb,QAAS,SACM,eAChB,EACA,CAAE,KAAM,uBAAwB,CACjC,EACMoB,CACP,CACD,CACD,CAAC,EAOD,SAASlB,EAAmB,EAAiD,CAC5E,MAAO,CACN,MAAOP,EAAI,IACX,SAAUA,EAAI,SACd,aAAcA,EAAI,aAClB,YAAaA,EAAI,YACjB,SAAUA,EAAI,QACf,CACD,CAEA,eAAee,EACd,EACA,EACA,EACgB,CACZN,EAAa,SAAS,OAAS,WAClC,MAAMN,EAAK,YAAYuB,EAA8BjB,EAAa,SAAS,MAAM,EAAGJ,EAAO,CAC1F,KAAMI,EAAa,GACpB,CAAC,EAGF,MAAMN,EAAK,UAAUuB,EAA4BjB,EAAa,SAAS,MAAM,EAAGJ,EAAO,CACtF,KAAMI,EAAa,IACnB,MAAOA,EAAa,SAAS,KAC9B,CAAC,CACF,C"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ApprovalCallbackInput, ApprovalWorkflowDescriptor } from "./validators.mjs";
|
|
2
1
|
import { ApprovalDecision } from "./constants.mjs";
|
|
2
|
+
import { ApprovalCallbackInput, ApprovalWorkflowDescriptor } from "./validators.mjs";
|
|
3
3
|
import { FunctionReference, FunctionType } from "convex/server";
|
|
4
4
|
declare namespace workflow_steps_d_exports {
|
|
5
5
|
export { ApprovalActionStep, ApprovalBranchStep, ApprovalDecisionEvidence, ApprovalDecisionStep, ApprovalDefinition, ApprovalMutationStep, ApprovalNotifyStep, ApprovalWorkflowStep, CreateApprovalHandle, approvalDecisionEventName, callbackReference, compileApprovalDescriptor, evaluateDecisionOutcome, resolveWorkflowStepIndex };
|
|
@@ -55,6 +55,5 @@ export declare function evaluateDecisionOutcome(decisions: readonly ApprovalDeci
|
|
|
55
55
|
export declare function resolveWorkflowStepIndex(stepKeys: readonly string[], targetKey: string): number;
|
|
56
56
|
export declare function callbackReference<Type extends FunctionType>(handle: string): FunctionReference<Type, 'internal', ApprovalCallbackInput, unknown>;
|
|
57
57
|
export declare function compileApprovalDescriptor(definition: ApprovalDefinition, createHandle?: CreateApprovalHandle): Promise<Readonly<ApprovalWorkflowDescriptor>>;
|
|
58
|
-
//#endregion
|
|
59
58
|
export { workflow_steps_d_exports };
|
|
60
59
|
//# sourceMappingURL=workflow_steps.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow_steps.mjs","names":["approvalDecisionEventName","runId","stepKey","evaluateDecisionOutcome","decisions","decision","approvalsRequired","resolveWorkflowStepIndex","index","stepKeys","targetKey","callbackReference","handle","compileApprovalDescriptor","createFunctionHandle","steps","definition","step","createHandle","deepFreeze","approvalWorkflowDescriptor","descriptor"],"sources":["../../../src/components/approvals/workflow_steps.ts"],"sourcesContent":["import {\n\tcreateFunctionHandle,\n\ttype FunctionReference,\n\ttype FunctionType,\n\ttype FunctionHandle,\n} from 'convex/server'\n\nimport type { ApprovalDecision } from './constants'\nimport {\n\tapprovalWorkflowDescriptor,\n\ttype ApprovalCallbackInput,\n\ttype ApprovalWorkflowDescriptor,\n} from './validators'\n\nexport type ApprovalMutationStep = Readonly<{\n\tkind: 'mutation'\n\tkey: string\n\thandler: FunctionReference<'mutation', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalActionStep = Readonly<{\n\tkind: 'action'\n\tkey: string\n\thandler: FunctionReference<'action', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalNotifyStep = Readonly<{\n\tkind: 'notify'\n\tkey: string\n\thandler: FunctionReference<'action', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalDecisionStep = Readonly<{\n\tkind: 'decision'\n\tkey: string\n\tdecisions: readonly ApprovalDecision[]\n\tquorum: Readonly<{ kind: 'count'; approvals: number }>\n\tmakerChecker: boolean\n\texpiresAfterMs?: number\n}>\n\nexport type ApprovalBranchStep = Readonly<{\n\tkind: 'branch'\n\tkey: string\n\tapprovedStepKey: string\n\trejectedStepKey: string\n}>\n\nexport type ApprovalWorkflowStep =\n\t| ApprovalMutationStep\n\t| ApprovalActionStep\n\t| ApprovalNotifyStep\n\t| ApprovalDecisionStep\n\t| ApprovalBranchStep\n\nexport type ApprovalDefinition = Readonly<{\n\tname: string\n\tcompatibilityKey: string\n\tsteps: readonly ApprovalWorkflowStep[]\n}>\n\nexport type CreateApprovalHandle = (\n\treference: FunctionReference<'mutation' | 'action', 'internal'>,\n) => Promise<string>\n\nexport type ApprovalDecisionEvidence = Readonly<{\n\tactorRef: string\n\tdecision: ApprovalDecision\n}>\n\nexport function approvalDecisionEventName(runId: string, stepKey: string): string {\n\treturn `approval:${runId}:${stepKey}`\n}\n\nexport function evaluateDecisionOutcome(\n\tdecisions: readonly ApprovalDecisionEvidence[],\n\tapprovalsRequired: number,\n): ApprovalDecision | null {\n\tif (decisions.some((decision) => decision.decision === 'rejected')) return 'rejected'\n\treturn decisions.filter((decision) => decision.decision === 'approved').length >=\n\t\tapprovalsRequired\n\t\t? 'approved'\n\t\t: null\n}\n\nexport function resolveWorkflowStepIndex(stepKeys: readonly string[], targetKey: string): number {\n\tconst index = stepKeys.indexOf(targetKey)\n\tif (index === -1) throw new Error(`Unknown approval workflow step: ${targetKey}`)\n\treturn index\n}\n\nexport function callbackReference<Type extends FunctionType>(\n\thandle: string,\n): FunctionReference<Type, 'internal', ApprovalCallbackInput, unknown> {\n\t// SAFETY: descriptors persist handles produced by createFunctionHandle; Convex resolves them on invocation.\n\treturn handle as FunctionHandle<Type, ApprovalCallbackInput, unknown>\n}\n\nexport async function compileApprovalDescriptor(\n\tdefinition: ApprovalDefinition,\n\tcreateHandle: CreateApprovalHandle = createFunctionHandle,\n): Promise<Readonly<ApprovalWorkflowDescriptor>> {\n\tconst steps = await Promise.all(\n\t\tdefinition.steps.map(async (step) => {\n\t\t\tif (step.kind === 'mutation' || step.kind === 'action') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: step.kind,\n\t\t\t\t\tkey: step.key,\n\t\t\t\t\tcallback: {\n\t\t\t\t\t\tkind: step.kind,\n\t\t\t\t\t\thandle: await createHandle(step.handler),\n\t\t\t\t\t\tretry: step.retry,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (step.kind === 'notify') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: step.kind,\n\t\t\t\t\tkey: step.key,\n\t\t\t\t\tcallback: {\n\t\t\t\t\t\tkind: 'action' as const,\n\t\t\t\t\t\thandle: await createHandle(step.handler),\n\t\t\t\t\t\tretry: step.retry,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (step.kind === 'decision') {\n\t\t\t\treturn {\n\t\t\t\t\t...step,\n\t\t\t\t\tdecisions: [...step.decisions],\n\t\t\t\t\tquorum: { ...step.quorum },\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ...step }\n\t\t}),\n\t)\n\tconst descriptor = approvalWorkflowDescriptor.parse({\n\t\tschemaVersion: 1,\n\t\tcompatibilityKey: definition.compatibilityKey,\n\t\tname: definition.name,\n\t\tsteps,\n\t})\n\treturn deepFreeze(descriptor)\n}\n\nfunction deepFreeze(descriptor: ApprovalWorkflowDescriptor): Readonly<ApprovalWorkflowDescriptor> {\n\tfor (const step of descriptor.steps) {\n\t\tif (step.kind === 'decision') {\n\t\t\tObject.freeze(step.decisions)\n\t\t\tObject.freeze(step.quorum)\n\t\t} else if ('callback' in step) {\n\t\t\tObject.freeze(step.callback)\n\t\t}\n\t\tObject.freeze(step)\n\t}\n\tObject.freeze(descriptor.steps)\n\treturn Object.freeze(descriptor)\n}\n"],"mappings":"mHAyEA,SAAgBA,EAA0B,EAAe,EAAyB,CACjF,MAAO,YAAYC,EAAM,GAAGC,GAC7B,CAEA,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AAK,QAAQ,EAE5B,OAAO,OAAOA,CAAI,EAGnB,OADA,OAAO,OAAOI,EAAW,KAAK,EACvB,OAAO,OAAOA,CAAU,CAChC"}
|
|
1
|
+
{"version":3,"file":"workflow_steps.mjs","names":["approvalDecisionEventName","runId","stepKey","evaluateDecisionOutcome","decisions","decision","approvalsRequired","resolveWorkflowStepIndex","index","stepKeys","targetKey","callbackReference","handle","compileApprovalDescriptor","createFunctionHandle","steps","definition","step","createHandle","deepFreeze","approvalWorkflowDescriptor","descriptor"],"sources":["../../../src/components/approvals/workflow_steps.ts"],"sourcesContent":["import {\n\tcreateFunctionHandle,\n\ttype FunctionReference,\n\ttype FunctionType,\n\ttype FunctionHandle,\n} from 'convex/server'\n\nimport type { ApprovalDecision } from './constants'\nimport {\n\tapprovalWorkflowDescriptor,\n\ttype ApprovalCallbackInput,\n\ttype ApprovalWorkflowDescriptor,\n} from './validators'\n\nexport type ApprovalMutationStep = Readonly<{\n\tkind: 'mutation'\n\tkey: string\n\thandler: FunctionReference<'mutation', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalActionStep = Readonly<{\n\tkind: 'action'\n\tkey: string\n\thandler: FunctionReference<'action', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalNotifyStep = Readonly<{\n\tkind: 'notify'\n\tkey: string\n\thandler: FunctionReference<'action', 'internal'>\n\tretry: boolean\n}>\n\nexport type ApprovalDecisionStep = Readonly<{\n\tkind: 'decision'\n\tkey: string\n\tdecisions: readonly ApprovalDecision[]\n\tquorum: Readonly<{ kind: 'count'; approvals: number }>\n\tmakerChecker: boolean\n\texpiresAfterMs?: number\n}>\n\nexport type ApprovalBranchStep = Readonly<{\n\tkind: 'branch'\n\tkey: string\n\tapprovedStepKey: string\n\trejectedStepKey: string\n}>\n\nexport type ApprovalWorkflowStep =\n\t| ApprovalMutationStep\n\t| ApprovalActionStep\n\t| ApprovalNotifyStep\n\t| ApprovalDecisionStep\n\t| ApprovalBranchStep\n\nexport type ApprovalDefinition = Readonly<{\n\tname: string\n\tcompatibilityKey: string\n\tsteps: readonly ApprovalWorkflowStep[]\n}>\n\nexport type CreateApprovalHandle = (\n\treference: FunctionReference<'mutation' | 'action', 'internal'>,\n) => Promise<string>\n\nexport type ApprovalDecisionEvidence = Readonly<{\n\tactorRef: string\n\tdecision: ApprovalDecision\n}>\n\nexport function approvalDecisionEventName(runId: string, stepKey: string): string {\n\treturn `approval:${runId}:${stepKey}`\n}\n\nexport function evaluateDecisionOutcome(\n\tdecisions: readonly ApprovalDecisionEvidence[],\n\tapprovalsRequired: number,\n): ApprovalDecision | null {\n\tif (decisions.some((decision) => decision.decision === 'rejected')) return 'rejected'\n\treturn decisions.filter((decision) => decision.decision === 'approved').length >=\n\t\tapprovalsRequired\n\t\t? 'approved'\n\t\t: null\n}\n\nexport function resolveWorkflowStepIndex(stepKeys: readonly string[], targetKey: string): number {\n\tconst index = stepKeys.indexOf(targetKey)\n\tif (index === -1) throw new Error(`Unknown approval workflow step: ${targetKey}`)\n\treturn index\n}\n\nexport function callbackReference<Type extends FunctionType>(\n\thandle: string,\n): FunctionReference<Type, 'internal', ApprovalCallbackInput, unknown> {\n\t// SAFETY: descriptors persist handles produced by createFunctionHandle; Convex resolves them on invocation.\n\treturn handle as FunctionHandle<Type, ApprovalCallbackInput, unknown>\n}\n\nexport async function compileApprovalDescriptor(\n\tdefinition: ApprovalDefinition,\n\tcreateHandle: CreateApprovalHandle = createFunctionHandle,\n): Promise<Readonly<ApprovalWorkflowDescriptor>> {\n\tconst steps = await Promise.all(\n\t\tdefinition.steps.map(async (step) => {\n\t\t\tif (step.kind === 'mutation' || step.kind === 'action') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: step.kind,\n\t\t\t\t\tkey: step.key,\n\t\t\t\t\tcallback: {\n\t\t\t\t\t\tkind: step.kind,\n\t\t\t\t\t\thandle: await createHandle(step.handler),\n\t\t\t\t\t\tretry: step.retry,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (step.kind === 'notify') {\n\t\t\t\treturn {\n\t\t\t\t\tkind: step.kind,\n\t\t\t\t\tkey: step.key,\n\t\t\t\t\tcallback: {\n\t\t\t\t\t\tkind: 'action' as const,\n\t\t\t\t\t\thandle: await createHandle(step.handler),\n\t\t\t\t\t\tretry: step.retry,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (step.kind === 'decision') {\n\t\t\t\treturn {\n\t\t\t\t\t...step,\n\t\t\t\t\tdecisions: [...step.decisions],\n\t\t\t\t\tquorum: { ...step.quorum },\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { ...step }\n\t\t}),\n\t)\n\tconst descriptor = approvalWorkflowDescriptor.parse({\n\t\tschemaVersion: 1,\n\t\tcompatibilityKey: definition.compatibilityKey,\n\t\tname: definition.name,\n\t\tsteps,\n\t})\n\treturn deepFreeze(descriptor)\n}\n\nfunction deepFreeze(descriptor: ApprovalWorkflowDescriptor): Readonly<ApprovalWorkflowDescriptor> {\n\tfor (const step of descriptor.steps) {\n\t\tif (step.kind === 'decision') {\n\t\t\tObject.freeze(step.decisions)\n\t\t\tObject.freeze(step.quorum)\n\t\t} else if ('callback' in step) {\n\t\t\tObject.freeze(step.callback)\n\t\t}\n\t\tObject.freeze(step)\n\t}\n\tObject.freeze(descriptor.steps)\n\treturn Object.freeze(descriptor)\n}\n"],"mappings":"A,mHAyEA,SAAgBA,EAA0B,EAAe,EAAyB,CACjF,MAAO,YAAYC,EAAM,GAAGC,GAC7B,CAEA,SAAgBC,EACf,EACA,EAC0B,CAE1B,OADIC,EAAU,KAAM,GAAaC,EAAS,WAAa,UAAU,EAAU,WACpED,EAAU,OAAQ,GAAaC,EAAS,WAAa,UAAU,CAAC,CAAC,QACvEC,EACE,WACA,IACJ,CAEA,SAAgBC,EAAyB,EAA6B,EAA2B,CAChG,IAAMC,EAAQC,EAAS,QAAQC,CAAS,EACxC,GAAIF,IAAU,GAAI,MAAU,MAAM,mCAAmCE,GAAW,EAChF,OAAOF,CACR,CAEA,SAAgBG,EACf,EACsE,CAEtE,OAAOC,CACR,CAEA,eAAsBC,EACrB,EACA,EAAqCC,EACW,CAChD,IAAMC,EAAQ,MAAM,QAAQ,IAC3BC,EAAW,MAAM,IAAI,KAAO,IACvBC,EAAK,OAAS,YAAcA,EAAK,OAAS,SACtC,CACN,KAAMA,EAAK,KACX,IAAKA,EAAK,IACV,SAAU,CACT,KAAMA,EAAK,KACX,OAAQ,MAAMC,EAAaD,EAAK,OAAO,EACvC,MAAOA,EAAK,KACb,CACD,EAEGA,EAAK,OAAS,SACV,CACN,KAAMA,EAAK,KACX,IAAKA,EAAK,IACV,SAAU,CACT,KAAM,SACN,OAAQ,MAAMC,EAAaD,EAAK,OAAO,EACvC,MAAOA,EAAK,KACb,CACD,EAEGA,EAAK,OAAS,WACV,CACN,GAAGA,EACH,UAAW,CAAC,GAAGA,EAAK,SAAS,EAC7B,OAAQ,CAAE,GAAGA,EAAK,MAAO,CAC1B,EAEM,CAAE,GAAGA,CAAK,CACjB,CACF,EAOA,OAAOE,EANYC,EAA2B,MAAM,CACnD,cAAe,EACf,iBAAkBJ,EAAW,iBAC7B,KAAMA,EAAW,KACjB,OACD,CAC2B,CAAC,CAC7B,CAEA,SAASG,EAAW,EAA8E,CACjG,IAAK,IAAMF,KAAQI,EAAW,MACzBJ,EAAK,OAAS,YACjB,OAAO,OAAOA,EAAK,SAAS,EAC5B,OAAO,OAAOA,EAAK,MAAM,GACf,aAAcA,GACxB,OAAO,OAAOA,EAAK,QAAQ,EAE5B,OAAO,OAAOA,CAAI,EAGnB,OADA,OAAO,OAAOI,EAAW,KAAK,EACvB,OAAO,OAAOA,CAAU,CAChC,C"}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
+
import { client_d_exports } from "../client.mjs";
|
|
2
|
+
import { functions_d_exports } from "../functions.mjs";
|
|
1
3
|
import { command_d_exports } from "../modules/command/command.mjs";
|
|
2
4
|
import { observability_d_exports } from "../modules/observability/observability.mjs";
|
|
3
5
|
import { query_d_exports } from "../modules/query/query.mjs";
|
|
4
6
|
import { result_d_exports } from "../result.mjs";
|
|
5
7
|
import { telemetry_d_exports } from "../telemetry.mjs";
|
|
6
|
-
import { client_d_exports } from "../client.mjs";
|
|
7
|
-
import { functions_d_exports } from "../functions.mjs";
|
|
8
8
|
import { ApiFromModules, FilterApi, FunctionReference } from "convex/server";
|
|
9
|
-
//#region src/components/foundation/_generated/api.d.ts
|
|
10
9
|
declare const fullApi: ApiFromModules<{
|
|
11
10
|
client: typeof client_d_exports;
|
|
12
11
|
functions: typeof functions_d_exports;
|
|
@@ -35,5 +34,5 @@ export declare const api: FilterApi<typeof fullApi, FunctionReference<any, "publ
|
|
|
35
34
|
*/
|
|
36
35
|
export declare const internal: FilterApi<typeof fullApi, FunctionReference<any, "internal">>;
|
|
37
36
|
export declare const components: {};
|
|
38
|
-
|
|
37
|
+
export {};
|
|
39
38
|
//# sourceMappingURL=api.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.mjs","names":["api","anyApi","internal","components","componentsGeneric"],"sources":["../../../../src/components/foundation/_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 client from \"../client.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as modules_command_command from \"../modules/command/command.js\";\nimport type * as modules_observability_observability from \"../modules/observability/observability.js\";\nimport type * as modules_query_query from \"../modules/query/query.js\";\nimport type * as result from \"../result.js\";\nimport type * as telemetry from \"../telemetry.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 client: typeof client;\n functions: typeof functions;\n \"modules/command/command\": typeof modules_command_command;\n \"modules/observability/observability\": typeof modules_observability_observability;\n \"modules/query/query\": typeof modules_query_query;\n result: typeof result;\n telemetry: typeof telemetry;\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"],"mappings":"8DA2CA,MAAaA,EAGTC,EAUSC,EAGTD,EAESE,EAAaC,EAAkB"}
|
|
1
|
+
{"version":3,"file":"api.mjs","names":["api","anyApi","internal","components","componentsGeneric"],"sources":["../../../../src/components/foundation/_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 client from \"../client.js\";\nimport type * as functions from \"../functions.js\";\nimport type * as modules_command_command from \"../modules/command/command.js\";\nimport type * as modules_observability_observability from \"../modules/observability/observability.js\";\nimport type * as modules_query_query from \"../modules/query/query.js\";\nimport type * as result from \"../result.js\";\nimport type * as telemetry from \"../telemetry.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 client: typeof client;\n functions: typeof functions;\n \"modules/command/command\": typeof modules_command_command;\n \"modules/observability/observability\": typeof modules_observability_observability;\n \"modules/query/query\": typeof modules_query_query;\n result: typeof result;\n telemetry: typeof telemetry;\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"],"mappings":"A,8DA2CA,MAAaA,EAGTC,EAUSC,EAGTD,EAESE,EAAaC,EAAkB,E"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { FunctionReference } from "convex/server";
|
|
2
|
-
//#region src/components/foundation/_generated/component.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A utility for referencing a Convex component's exposed API.
|
|
5
4
|
*
|
|
@@ -16,5 +15,4 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
|
|
|
16
15
|
status: FunctionReference<"query", "internal", {}, "ready", Name>;
|
|
17
16
|
};
|
|
18
17
|
};
|
|
19
|
-
//#endregion
|
|
20
18
|
//# 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/foundation/_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/foundation/_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/foundation/_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"}
|
|
@@ -177,6 +177,5 @@ export declare class Foundation<Component extends FoundationComponentApi = Found
|
|
|
177
177
|
readonly emitSemanticEvent: typeof emitSemanticEvent;
|
|
178
178
|
constructor(component: Component, options: FoundationOptions);
|
|
179
179
|
}
|
|
180
|
-
//#endregion
|
|
181
180
|
export { type AnyQueryMiddleware, type CommandArgument, type CommandExecution, type CommandHandlerResult, type CommandInput, type CommandObservation, type CommandPreparation, type CommandRegistry, type CommandResult, type ObservabilityOptions, type Parseable, type QueryExecution, type QueryMiddleware, type Result, type ResultBoundary, type SchemaOutput, type TransactionMetricsContext, type TypedOperation, client_d_exports };
|
|
182
181
|
//# sourceMappingURL=client.d.mts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Command as e,decodeCommandSchema as t,parseCommandSchema as n}from"./modules/command/command.mjs";import{Observability as r}from"./modules/observability/observability.mjs";import{Query as i}from"./modules/query/query.mjs";import{CommandPermissionError as a,executeCommandLifecycle as o,promiseLifecycle as s}from"./modules/command/lifecycle.mjs";import{executeResultBoundary as c,projectResult as l}from"./result.mjs";import{emitSemanticEvent as u}from"./telemetry.mjs";import{operationFactory as d}from"./operation.mjs";var f=class{static withContext=d;#e;#t;#n;#r;#i;aggregates;static operation(e){return e}static middleware(e){return e}constructor(t,n){this.#t=n.observability,this.#n=n.writeAudit,this.#r=n.checkPermission,this.#i=n.defaults??{},this.aggregates=Object.freeze(Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.aggregates]))),this.#e=new e({operations:t,execute:e=>this.#a(e)})}exec(e){return this.#e.exec({operation:e.operation,handler:(t,n)=>e.handler(t,n)})}async#a(e){let r=e.definition;return this.#t.observe({operation:e.operation,classification:r.classification},()=>o(s,{operation:e.operation,classification:r.classification,context:e.context,command:e.command,permission:r.permission===void 0?void 0:async()=>{if(!this.#r)throw new a(e.operation);await this.#r(e.context,{permission:r.permission,operation:e.operation})},prepare:async()=>{let t=await r.prepare?.(e.context,e.command);return t?.kind===`execute`?{kind:`execute`,complete:t.complete?async e=>{await t.complete(e)}:void 0}:t},parseReplay:t=>r.replayResult?n(r.replayResult,t):e.parseResult(t),decodeReplay:async n=>{if(!r.replayResult)return e.decodeResult?e.decodeResult(n):e.parseResult(n);let i=r.replayResult;return await t(i,n)},middleware:[...this.#i.middleware??[],...r.middleware??[]].map(e=>async t=>e({...t,definition:r,command:t.command,context:t.context,next:t.next})),defaultGuard:async e=>{await this.#i.guard?.(e)},guard:async t=>{await r.guard?.(t,e.command)},run:t=>e.runUnparsed(t),parseResult:e.parseResult,decodeResult:e.decodeResult,audit:async t=>r.audit({command:e.command,result:t},e.context),aggregates:r.aggregates,writeAudit:async t=>this.#n(e.context,t)}))}},p=class{status;Command;Query=i;observability;executeResultBoundary=c;projectResult=l;emitSemanticEvent=u;constructor(e,t){this.status=e.functions.status;let n=new r(t.observability);this.observability=n;let i=t.observability.writeAudit??(()=>void 0),a=t.checkPermission;class o extends f{constructor(e,t){super(e,{observability:n,writeAudit:i,checkPermission:a,defaults:t})}}this.Command=o}};export{p as Foundation};
|
|
2
2
|
//# sourceMappingURL=client.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":["CommandKernelClass","BoundCommand","operationFactory","definition","middleware","#observability","deps","#writeAudit","#checkPermission","#defaults","operations","operation","#kernel","Command","#execute","execution","executor","context","command","executeCommandLifecycle","promiseLifecycle","CommandPermissionError","preparation","result","parseCommandSchema","value","replay","decodeCommandSchema","layer","input","entry","Foundation","Query","executeResultBoundary","projectResult","emitSemanticEvent","component","observability","Observability","options","writeAudit","checkPermission","HostCommand"],"sources":["../../../src/components/foundation/client.ts"],"sourcesContent":["import type { Value } from 'convex/values'\nimport {\n\tCommand as CommandKernelClass,\n\ttype CommandExecution,\n\ttype CommandHandlerResult,\n\ttype CommandInput,\n\ttype CommandRegistry,\n\ttype CommandResult,\n\ttype CommandSchema,\n\tdecodeCommandSchema,\n\tparseCommandSchema,\n} from './modules/command/command'\nimport { Observability, type ObservabilityOptions } from './modules/observability/observability'\nimport { Query } from './modules/query/query'\nimport {\n\texecuteCommandLifecycle,\n\tpromiseLifecycle,\n\tCommandPermissionError,\n\ttype PromiseExecution,\n} from './modules/command/lifecycle'\nimport { executeResultBoundary, projectResult } from './result'\nimport { emitSemanticEvent } from './telemetry'\nimport {\n\toperationFactory,\n\ttype CommandPreparation,\n\ttype OperationExtension,\n\ttype OperationHostContext,\n} from './operation'\n\n/** Shape handed to the injected audit writer; classification comes from the operation. */\nexport type AuditEntryInput = {\n\toperation: string\n\tactorId: string\n\taggregate: { type: string; id: string }\n\tmetadata?: Record<string, Value>\n\tclassification: string\n}\n\nexport type AuditWriter<Result = unknown> = (\n\tcontext: never,\n\tentry: AuditEntryInput,\n) => MaybePromise<Result>\n\ntype MaybePromise<Value> = Value | Promise<Value>\ntype OperationKey<Operations extends CommandRegistry> = Extract<keyof Operations, string>\n\nexport type AuditedOperation = Readonly<{\n\tcommand: CommandSchema\n\tresult: CommandSchema\n\tclassification: string\n\t/**\n\t * Permission slug required to execute this operation. Checked through the\n\t * Foundation's injected checkPermission BEFORE guards and the handler;\n\t * declaring a permission without injecting a checker fails closed.\n\t */\n\tpermission?: string\n\tprepare?: (context: never, command: never) => MaybePromise<CommandPreparation<never>>\n\treplayResult?: CommandSchema\n\t/**\n\t * Per-operation precondition, after the permission check and the registry\n\t * default guard, before the handler. Throw to deny — nothing has run yet.\n\t */\n\tguard?: (context: never, command: never) => MaybePromise<void>\n\t/**\n\t * Allowlist of aggregate types this operation's audit may reference. When\n\t * declared, an audit entry whose aggregate.type is not listed throws —\n\t * the audit vocabulary is enforced, not advisory.\n\t */\n\taggregates?: readonly string[]\n\t/** Per-operation middleware, inside the registry-wide chain. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n\taudit: (\n\t\tresolution: Readonly<{ command: never; result: never }>,\n\t\tcontext: never,\n\t) => MaybePromise<Omit<AuditEntryInput, 'classification'> | null>\n}>\n\n/**\n * Composable, next()-based middleware wrapping [guards → handler]. Runs\n * INSIDE the pipeline's invariants: after the permission check, before the\n * result-schema parse, aggregate allowlist, and audit — so middleware can\n * time, trace, enrich context (`next({ context })`), short-circuit, or\n * transform results, but can never skip authorization, return an invalid\n * result, or desynchronize audit from effects.\n */\nexport type CommandMiddleware<\n\tContext = never,\n\tExtension extends object = object,\n\tInput = unknown,\n\tResult = unknown,\n> = (input: {\n\toperation: string\n\tcommand: Input\n\tcontext: Context\n\tnext: (options?: {\n\t\t/** Merged into the context handed to inner middleware, guards, handler. */\n\t\tcontext?: Extension\n\t}) => Promise<Result>\n}) => Promise<Result>\n\n/** Any-context middleware — what registries and operations accept. */\n// Contravariant seam: the supertype every typed CommandMiddleware<C, E>\n// assigns to. Context, command, and next are contravariant storage slots;\n// dispatch restores the selected operation's types before invocation.\nexport type AnyCommandMiddleware<Input = never, Result = unknown, NextResult = never> = (input: {\n\toperation: string\n\tdefinition?: AuditedOperation\n\tcommand: Input\n\tcontext: never\n\tnext: (options?: { context?: object }) => Promise<NextResult>\n}) => Promise<Result>\n\n/** Registry-wide defaults applied to every operation of one Command. */\nexport type CommandDefaults = Readonly<{\n\t/** Runs before every operation's own guard. Throw to deny. */\n\tguard?: (context: never) => MaybePromise<void>\n\t/** Outermost middleware, in array order, around every operation. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n}>\n\n/** Injected permission policy: throw to deny. Host semantics, kit ordering. */\nexport type PermissionChecker = (\n\tcontext: never,\n\tinput: Readonly<{ permission: string; operation: string }>,\n) => MaybePromise<void>\n\nexport type AuditedRegistry = Readonly<Record<string, AuditedOperation>>\n\nexport type FoundationOptions = Readonly<{\n\tobservability: ObservabilityOptions &\n\t\tReadonly<{\n\t\t\t/**\n\t\t\t * In-transaction audit writer used by Command. Operations that\n\t\t\t * return an audit record get it written here automatically.\n\t\t\t */\n\t\t\twriteAudit?: AuditWriter\n\t\t}>\n\t/**\n\t * Permission policy for operations that declare a `permission`. Runs\n\t * before guards and the handler; throw to deny. An operation with a\n\t * permission but no injected checker fails closed.\n\t */\n\tcheckPermission?: PermissionChecker\n}>\n\ntype FoundationComponentApi = Readonly<{\n\tfunctions: Readonly<{ status: unknown }>\n}>\n\n/**\n * Application command protocol bound to a Foundation instance:\n * validate, observe, execute, and audit. `classification` and `audit()`\n * are mandatory per operation — auditing is type-enforced, not opt-in.\n * Obtain it by destructuring the Foundation: `const { Command } = new Foundation(...)`.\n */\nclass BoundCommand<Context, const Operations extends AuditedRegistry> {\n\tstatic withContext = operationFactory\n\treadonly #kernel: CommandKernelClass<Context, Operations>\n\treadonly #observability: Observability\n\treadonly #writeAudit: AuditWriter\n\treadonly #checkPermission: PermissionChecker | undefined\n\treadonly #defaults: CommandDefaults\n\n\t/** Declared aggregate types per operation — introspectable for tests. */\n\treadonly aggregates: Readonly<{\n\t\t[Key in OperationKey<Operations>]: Operations[Key]['aggregates']\n\t}>\n\n\tstatic operation<const Definition extends AuditedOperation>(definition: Definition): Definition {\n\t\treturn definition\n\t}\n\n\t/**\n\t * Identity helper that types a middleware against its context and the\n\t * context extension it passes downstream via next({ context }).\n\t */\n\tstatic middleware<\n\t\tContext = never,\n\t\tconst Extension extends object = object,\n\t\tInput = unknown,\n\t\tResult = unknown,\n\t>(\n\t\tmiddleware: CommandMiddleware<Context, Extension, Input, Result>,\n\t): CommandMiddleware<Context, Extension, Input, Result> {\n\t\treturn middleware\n\t}\n\n\tconstructor(\n\t\toperations: Operations,\n\t\tdeps: {\n\t\t\tobservability: Observability\n\t\t\twriteAudit: AuditWriter\n\t\t\tcheckPermission?: PermissionChecker\n\t\t\tdefaults?: CommandDefaults\n\t\t},\n\t) {\n\t\tthis.#observability = deps.observability\n\t\tthis.#writeAudit = deps.writeAudit\n\t\tthis.#checkPermission = deps.checkPermission\n\t\tthis.#defaults = deps.defaults ?? {}\n\t\t// SAFETY: this map preserves every operations key and selects its aggregates property.\n\t\tthis.aggregates = Object.freeze(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(operations).map(([operation, definition]) => [\n\t\t\t\t\toperation,\n\t\t\t\t\tdefinition.aggregates,\n\t\t\t\t]),\n\t\t\t),\n\t\t) as this['aggregates']\n\t\tthis.#kernel = new CommandKernelClass<Context, Operations>({\n\t\t\toperations,\n\t\t\texecute: (execution) => this.#execute(execution),\n\t\t})\n\t}\n\n\t/**\n\t * @deprecated Declare handlers inside command({...}) using createEffectFoundation\n\t * from cvx-kit/effect, then call exec(operation, input, host).\n\t */\n\texec<const Key extends OperationKey<Operations>>(executor: {\n\t\toperation: Key\n\t\thandler: (\n\t\t\tcontext: Context & OperationExtension<Operations[Key]>,\n\t\t\tcommand: CommandInput<Operations, Key>,\n\t\t) => MaybePromise<CommandHandlerResult<Operations, Key>>\n\t}) {\n\t\treturn this.#kernel.exec({\n\t\t\toperation: executor.operation,\n\t\t\thandler: (context, command) =>\n\t\t\t\texecutor.handler(\n\t\t\t\t\t// SAFETY: operationFactory requires enrichment middleware before this handler.\n\t\t\t\t\tcontext as Context & OperationExtension<Operations[Key]>,\n\t\t\t\t\tcommand,\n\t\t\t\t),\n\t\t})\n\t}\n\n\tasync #execute<Key extends OperationKey<Operations>>(\n\t\texecution: CommandExecution<Context, Operations, Key>,\n\t): Promise<CommandResult<Operations, Key>> {\n\t\tconst definition = execution.definition\n\t\treturn this.#observability.observe(\n\t\t\t{ operation: execution.operation, classification: definition.classification },\n\t\t\t() =>\n\t\t\t\texecuteCommandLifecycle<\n\t\t\t\t\tPromiseExecution,\n\t\t\t\t\tContext,\n\t\t\t\t\tCommandInput<Operations, Key>,\n\t\t\t\t\tCommandHandlerResult<Operations, Key>,\n\t\t\t\t\tCommandResult<Operations, Key>\n\t\t\t\t>(promiseLifecycle, {\n\t\t\t\t\toperation: execution.operation,\n\t\t\t\t\tclassification: definition.classification,\n\t\t\t\t\tcontext: execution.context,\n\t\t\t\t\tcommand: execution.command,\n\t\t\t\t\tpermission:\n\t\t\t\t\t\tdefinition.permission === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: async () => {\n\t\t\t\t\t\t\t\t\tif (!this.#checkPermission) throw new CommandPermissionError(execution.operation)\n\t\t\t\t\t\t\t\t\t// SAFETY: injected policy consumes this invocation's original host context.\n\t\t\t\t\t\t\t\t\tawait this.#checkPermission(execution.context as never, {\n\t\t\t\t\t\t\t\t\t\tpermission: definition.permission!,\n\t\t\t\t\t\t\t\t\t\toperation: execution.operation,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\tprepare: async () => {\n\t\t\t\t\t\t// SAFETY: selected definition and parsed input are paired by the kernel.\n\t\t\t\t\t\tconst preparation = await definition.prepare?.(\n\t\t\t\t\t\t\texecution.context as never,\n\t\t\t\t\t\t\texecution.command as never,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif (preparation?.kind !== 'execute') return preparation\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'execute' as const,\n\t\t\t\t\t\t\tcomplete: preparation.complete\n\t\t\t\t\t\t\t\t? async (result: CommandResult<Operations, Key>) => {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: completion belongs to this operation's validated final result.\n\t\t\t\t\t\t\t\t\t\tawait preparation.complete!(result as never)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tparseReplay: (value) => {\n\t\t\t\t\t\tif (!definition.replayResult) return execution.parseResult(value)\n\t\t\t\t\t\t// SAFETY: selected replay schema validates this operation's stored output.\n\t\t\t\t\t\treturn parseCommandSchema(definition.replayResult, value) as CommandResult<\n\t\t\t\t\t\t\tOperations,\n\t\t\t\t\t\t\tKey\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tdecodeReplay: async (value) => {\n\t\t\t\t\t\tif (!definition.replayResult) {\n\t\t\t\t\t\t\treturn execution.decodeResult\n\t\t\t\t\t\t\t\t? execution.decodeResult(value)\n\t\t\t\t\t\t\t\t: execution.parseResult(value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst replay = definition.replayResult\n\t\t\t\t\t\t// SAFETY: selected replay decoder owns the final output representation.\n\t\t\t\t\t\treturn (await decodeCommandSchema(replay, value)) as CommandResult<Operations, Key>\n\t\t\t\t\t},\n\t\t\t\t\tmiddleware: [...(this.#defaults.middleware ?? []), ...(definition.middleware ?? [])].map(\n\t\t\t\t\t\t(layer) => async (input) => {\n\t\t\t\t\t\t\t// SAFETY: selected definition owns this heterogeneous middleware's pre-validation output.\n\t\t\t\t\t\t\treturn layer({\n\t\t\t\t\t\t\t\t...input,\n\t\t\t\t\t\t\t\tdefinition,\n\t\t\t\t\t\t\t\t// SAFETY: selected command schema owns this heterogeneous storage value.\n\t\t\t\t\t\t\t\tcommand: input.command as never,\n\t\t\t\t\t\t\t\t// SAFETY: only heterogeneous storage erases the selected middleware context.\n\t\t\t\t\t\t\t\tcontext: input.context as never,\n\t\t\t\t\t\t\t\t// SAFETY: selected operation pairs downstream output with its final schema.\n\t\t\t\t\t\t\t\tnext: input.next as (options?: { context?: object }) => Promise<never>,\n\t\t\t\t\t\t\t}) as Promise<CommandHandlerResult<Operations, Key>>\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t\tdefaultGuard: async (context) => {\n\t\t\t\t\t\t// SAFETY: default guards consume the downstream middleware context.\n\t\t\t\t\t\tawait this.#defaults.guard?.(context as never)\n\t\t\t\t\t},\n\t\t\t\t\tguard: async (context) => {\n\t\t\t\t\t\t// SAFETY: selected guard consumes its parsed input and enriched context.\n\t\t\t\t\t\tawait definition.guard?.(context as never, execution.command as never)\n\t\t\t\t\t},\n\t\t\t\t\trun: (context) => execution.runUnparsed(context),\n\t\t\t\t\tparseResult: execution.parseResult,\n\t\t\t\t\tdecodeResult: execution.decodeResult,\n\t\t\t\t\taudit: async (result) => {\n\t\t\t\t\t\t// SAFETY: audit receives this selected parsed command/result and original context.\n\t\t\t\t\t\treturn definition.audit(\n\t\t\t\t\t\t\t{ command: execution.command, result } as never,\n\t\t\t\t\t\t\texecution.context as never,\n\t\t\t\t\t\t)\n\t\t\t\t\t},\n\t\t\t\t\taggregates: definition.aggregates,\n\t\t\t\t\twriteAudit: async (entry) => {\n\t\t\t\t\t\t// SAFETY: host supplied writer for this invocation's original context.\n\t\t\t\t\t\treturn this.#writeAudit(execution.context as never, entry)\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t)\n\t}\n}\n\n/** @deprecated Use the registry returned by createEffectFoundation(...).Command from cvx-kit/effect. */\nexport type ApplicationCommand<Context, Operations extends AuditedRegistry> = BoundCommand<\n\tContext,\n\tOperations\n>\n\n/**\n * The constructor shape a Foundation instance exposes as `Command`.\n * Exported as a TYPE ONLY so factories (e.g. cvx-kit/crud) can accept the\n * destructured facade class as input without importing any runtime kernel.\n * @deprecated Use createEffectFoundation from cvx-kit/effect and declare handlers inside command({...}).\n */\nexport type CommandConstructor = {\n\t/** @deprecated Use createEffectFoundation(...).Command({ context, operations }) from cvx-kit/effect. */\n\tnew <Context, const Operations extends AuditedRegistry>(\n\t\toperations: Operations & {\n\t\t\treadonly [Key in keyof Operations]: OperationHostContext<Context>\n\t\t},\n\t\tdefaults?: CommandDefaults,\n\t): BoundCommand<Context, Operations>\n\toperation: (typeof BoundCommand)['operation']\n\twithContext: (typeof BoundCommand)['withContext']\n\tmiddleware: (typeof BoundCommand)['middleware']\n}\n\n/**\n * Host facade for a component that owns no application execution capability.\n * Declared once; the sole source of the command protocol, query kernel, and\n * observability: `const { Command, Query, observability } = new Foundation(...)`.\n */\nexport class Foundation<Component extends FoundationComponentApi = FoundationComponentApi> {\n\treadonly status: Component['functions']['status']\n\t/** @deprecated Use createEffectFoundation(...).Command from cvx-kit/effect. */\n\treadonly Command: CommandConstructor\n\treadonly Query = Query\n\treadonly observability: Observability\n\t/** Typed-failure boundary — see result.ts. Facade-bound like the kernels. */\n\treadonly executeResultBoundary = executeResultBoundary\n\treadonly projectResult = projectResult\n\treadonly emitSemanticEvent = emitSemanticEvent\n\n\tconstructor(component: Component, options: FoundationOptions) {\n\t\tthis.status = component.functions.status\n\t\tconst observability = new Observability(options.observability)\n\t\tthis.observability = observability\n\t\tconst writeAudit = options.observability.writeAudit ?? (() => undefined)\n\t\tconst checkPermission = options.checkPermission\n\t\tclass HostCommand<Context, const Operations extends AuditedRegistry> extends BoundCommand<\n\t\t\tContext,\n\t\t\tOperations\n\t\t> {\n\t\t\tconstructor(operations: Operations, defaults?: CommandDefaults) {\n\t\t\t\tsuper(operations, {\n\t\t\t\t\tobservability,\n\t\t\t\t\twriteAudit,\n\t\t\t\t\tcheckPermission,\n\t\t\t\t\tdefaults,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tthis.Command = HostCommand\n\t}\n}\n\n// Kernel CLASSES are deliberately NOT exported: Command, Query, and\n// Observability exist only as capabilities of a Foundation instance —\n// `const { Command, Query, observability } = new Foundation(...)`. A loose\n// import would construct kernels without the injected observability, audit\n// writer, and permission checker. Types stay exported for signatures.\nexport type { CommandPreparation, TypedOperation } from './operation'\nexport type {\n\tCommandArgument,\n\tCommandExecution,\n\tCommandHandlerResult,\n\tCommandInput,\n\tCommandRegistry,\n\tCommandResult,\n\tSchemaOutput,\n\tParseable,\n} from './modules/command/command'\nexport type {\n\tCommandObservation,\n\tObservabilityOptions,\n} from './modules/observability/observability'\nexport type { AnyQueryMiddleware, QueryExecution, QueryMiddleware } from './modules/query/query'\nexport type { Result, ResultBoundary, TransactionMetricsContext } from './result'\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 foundation from 'cvx-kit/components/foundation/convex.config'\n"],"mappings":"ghBA2JA,IAAMC,EAAN,KAAsE,CACrE,OAAO,YAAcC,EACrB,GACA,GACA,GACA,GACA,GAGA,WAIA,OAAO,UAAqD,EAAoC,CAC/F,OAAOC,CACR,CAMA,OAAO,WAMN,EACuD,CACvD,OAAOC,CACR,CAEA,YACC,EACA,EAMC,CACD,KAAKC,GAAiBC,EAAK,cAC3B,KAAKC,GAAcD,EAAK,WACxB,KAAKE,GAAmBF,EAAK,gBAC7B,KAAKG,GAAYH,EAAK,UAAY,CAAC,EAEnC,KAAK,WAAa,OAAO,OACxB,OAAO,YACN,OAAO,QAAQI,CAAU,CAAC,CAAC,KAAK,CAACC,EAAWR,KAAgB,CAC3DQ,EACAR,EAAW,UACZ,CAAC,CACF,CACD,EACA,KAAKS,GAAU,IAAIZ,EAAwC,CAC1D,aACA,QAAU,GAAc,KAAKc,GAASC,CAAS,CAChD,CAAC,CACF,CAMA,KAAiD,EAM9C,CACF,OAAO,KAAKH,GAAQ,KAAK,CACxB,UAAWI,EAAS,UACpB,SAAU,EAAS,IAClBA,EAAS,QAERC,EACAC,CACD,CACF,CAAC,CACF,CAEA,KAAMJ,GACL,EAC0C,CAC1C,IAAMX,EAAaY,EAAU,WAC7B,OAAO,KAAKV,GAAe,QAC1B,CAAE,UAAWU,EAAU,UAAW,eAAgBZ,EAAW,cAAe,MAE3EgB,EAMEC,EAAkB,CACnB,UAAWL,EAAU,UACrB,eAAgBZ,EAAW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xB,MAAO,KAAO,IAENZ,EAAW,MACjB,CAAE,QAASY,EAAU,QAAS,QAAO,EACrCA,EAAU,OACX,EAED,WAAYZ,EAAW,WACvB,WAAY,KAAO,IAEX,KAAKI,GAAYQ,EAAU,QAAkBe,CAAK,CAE3D,CAAC,CACH,CACD,CACD,EAgCaC,EAAb,KAA2F,CAC1F,OAEA,QACA,MAAiBC,EACjB,cAEA,sBAAiCC,EACjC,cAAyBC,EACzB,kBAA6BC,EAE7B,YAAY,EAAsB,EAA4B,CAC7D,KAAK,OAASC,EAAU,UAAU,OAClC,IAAMC,EAAgB,IAAIC,EAAcC,EAAQ,aAAa,EAC7D,KAAK,cAAgBF,EACrB,IAAMG,EAAaD,EAAQ,cAAc,iBAAqB,IAAA,IACxDE,EAAkBF,EAAQ,gBAChC,MAAMG,UAAuEzC,CAG3E,CACD,YAAY,EAAwB,EAA4B,CAC/D,MAAMS,EAAY,CACjB,gBACA,aACA,kBACA,UACD,CAAC,CACF,CACD,CACA,KAAK,QAAUgC,CAChB,CACD"}
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["CommandKernelClass","BoundCommand","operationFactory","definition","middleware","#observability","deps","#writeAudit","#checkPermission","#defaults","operations","operation","#kernel","Command","#execute","execution","executor","context","command","executeCommandLifecycle","promiseLifecycle","CommandPermissionError","preparation","result","parseCommandSchema","value","replay","decodeCommandSchema","layer","input","entry","Foundation","Query","executeResultBoundary","projectResult","emitSemanticEvent","component","observability","Observability","options","writeAudit","checkPermission","HostCommand"],"sources":["../../../src/components/foundation/client.ts"],"sourcesContent":["import type { Value } from 'convex/values'\nimport {\n\tCommand as CommandKernelClass,\n\ttype CommandExecution,\n\ttype CommandHandlerResult,\n\ttype CommandInput,\n\ttype CommandRegistry,\n\ttype CommandResult,\n\ttype CommandSchema,\n\tdecodeCommandSchema,\n\tparseCommandSchema,\n} from './modules/command/command'\nimport { Observability, type ObservabilityOptions } from './modules/observability/observability'\nimport { Query } from './modules/query/query'\nimport {\n\texecuteCommandLifecycle,\n\tpromiseLifecycle,\n\tCommandPermissionError,\n\ttype PromiseExecution,\n} from './modules/command/lifecycle'\nimport { executeResultBoundary, projectResult } from './result'\nimport { emitSemanticEvent } from './telemetry'\nimport {\n\toperationFactory,\n\ttype CommandPreparation,\n\ttype OperationExtension,\n\ttype OperationHostContext,\n} from './operation'\n\n/** Shape handed to the injected audit writer; classification comes from the operation. */\nexport type AuditEntryInput = {\n\toperation: string\n\tactorId: string\n\taggregate: { type: string; id: string }\n\tmetadata?: Record<string, Value>\n\tclassification: string\n}\n\nexport type AuditWriter<Result = unknown> = (\n\tcontext: never,\n\tentry: AuditEntryInput,\n) => MaybePromise<Result>\n\ntype MaybePromise<Value> = Value | Promise<Value>\ntype OperationKey<Operations extends CommandRegistry> = Extract<keyof Operations, string>\n\nexport type AuditedOperation = Readonly<{\n\tcommand: CommandSchema\n\tresult: CommandSchema\n\tclassification: string\n\t/**\n\t * Permission slug required to execute this operation. Checked through the\n\t * Foundation's injected checkPermission BEFORE guards and the handler;\n\t * declaring a permission without injecting a checker fails closed.\n\t */\n\tpermission?: string\n\tprepare?: (context: never, command: never) => MaybePromise<CommandPreparation<never>>\n\treplayResult?: CommandSchema\n\t/**\n\t * Per-operation precondition, after the permission check and the registry\n\t * default guard, before the handler. Throw to deny — nothing has run yet.\n\t */\n\tguard?: (context: never, command: never) => MaybePromise<void>\n\t/**\n\t * Allowlist of aggregate types this operation's audit may reference. When\n\t * declared, an audit entry whose aggregate.type is not listed throws —\n\t * the audit vocabulary is enforced, not advisory.\n\t */\n\taggregates?: readonly string[]\n\t/** Per-operation middleware, inside the registry-wide chain. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n\taudit: (\n\t\tresolution: Readonly<{ command: never; result: never }>,\n\t\tcontext: never,\n\t) => MaybePromise<Omit<AuditEntryInput, 'classification'> | null>\n}>\n\n/**\n * Composable, next()-based middleware wrapping [guards → handler]. Runs\n * INSIDE the pipeline's invariants: after the permission check, before the\n * result-schema parse, aggregate allowlist, and audit — so middleware can\n * time, trace, enrich context (`next({ context })`), short-circuit, or\n * transform results, but can never skip authorization, return an invalid\n * result, or desynchronize audit from effects.\n */\nexport type CommandMiddleware<\n\tContext = never,\n\tExtension extends object = object,\n\tInput = unknown,\n\tResult = unknown,\n> = (input: {\n\toperation: string\n\tcommand: Input\n\tcontext: Context\n\tnext: (options?: {\n\t\t/** Merged into the context handed to inner middleware, guards, handler. */\n\t\tcontext?: Extension\n\t}) => Promise<Result>\n}) => Promise<Result>\n\n/** Any-context middleware — what registries and operations accept. */\n// Contravariant seam: the supertype every typed CommandMiddleware<C, E>\n// assigns to. Context, command, and next are contravariant storage slots;\n// dispatch restores the selected operation's types before invocation.\nexport type AnyCommandMiddleware<Input = never, Result = unknown, NextResult = never> = (input: {\n\toperation: string\n\tdefinition?: AuditedOperation\n\tcommand: Input\n\tcontext: never\n\tnext: (options?: { context?: object }) => Promise<NextResult>\n}) => Promise<Result>\n\n/** Registry-wide defaults applied to every operation of one Command. */\nexport type CommandDefaults = Readonly<{\n\t/** Runs before every operation's own guard. Throw to deny. */\n\tguard?: (context: never) => MaybePromise<void>\n\t/** Outermost middleware, in array order, around every operation. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n}>\n\n/** Injected permission policy: throw to deny. Host semantics, kit ordering. */\nexport type PermissionChecker = (\n\tcontext: never,\n\tinput: Readonly<{ permission: string; operation: string }>,\n) => MaybePromise<void>\n\nexport type AuditedRegistry = Readonly<Record<string, AuditedOperation>>\n\nexport type FoundationOptions = Readonly<{\n\tobservability: ObservabilityOptions &\n\t\tReadonly<{\n\t\t\t/**\n\t\t\t * In-transaction audit writer used by Command. Operations that\n\t\t\t * return an audit record get it written here automatically.\n\t\t\t */\n\t\t\twriteAudit?: AuditWriter\n\t\t}>\n\t/**\n\t * Permission policy for operations that declare a `permission`. Runs\n\t * before guards and the handler; throw to deny. An operation with a\n\t * permission but no injected checker fails closed.\n\t */\n\tcheckPermission?: PermissionChecker\n}>\n\ntype FoundationComponentApi = Readonly<{\n\tfunctions: Readonly<{ status: unknown }>\n}>\n\n/**\n * Application command protocol bound to a Foundation instance:\n * validate, observe, execute, and audit. `classification` and `audit()`\n * are mandatory per operation — auditing is type-enforced, not opt-in.\n * Obtain it by destructuring the Foundation: `const { Command } = new Foundation(...)`.\n */\nclass BoundCommand<Context, const Operations extends AuditedRegistry> {\n\tstatic withContext = operationFactory\n\treadonly #kernel: CommandKernelClass<Context, Operations>\n\treadonly #observability: Observability\n\treadonly #writeAudit: AuditWriter\n\treadonly #checkPermission: PermissionChecker | undefined\n\treadonly #defaults: CommandDefaults\n\n\t/** Declared aggregate types per operation — introspectable for tests. */\n\treadonly aggregates: Readonly<{\n\t\t[Key in OperationKey<Operations>]: Operations[Key]['aggregates']\n\t}>\n\n\tstatic operation<const Definition extends AuditedOperation>(definition: Definition): Definition {\n\t\treturn definition\n\t}\n\n\t/**\n\t * Identity helper that types a middleware against its context and the\n\t * context extension it passes downstream via next({ context }).\n\t */\n\tstatic middleware<\n\t\tContext = never,\n\t\tconst Extension extends object = object,\n\t\tInput = unknown,\n\t\tResult = unknown,\n\t>(\n\t\tmiddleware: CommandMiddleware<Context, Extension, Input, Result>,\n\t): CommandMiddleware<Context, Extension, Input, Result> {\n\t\treturn middleware\n\t}\n\n\tconstructor(\n\t\toperations: Operations,\n\t\tdeps: {\n\t\t\tobservability: Observability\n\t\t\twriteAudit: AuditWriter\n\t\t\tcheckPermission?: PermissionChecker\n\t\t\tdefaults?: CommandDefaults\n\t\t},\n\t) {\n\t\tthis.#observability = deps.observability\n\t\tthis.#writeAudit = deps.writeAudit\n\t\tthis.#checkPermission = deps.checkPermission\n\t\tthis.#defaults = deps.defaults ?? {}\n\t\t// SAFETY: this map preserves every operations key and selects its aggregates property.\n\t\tthis.aggregates = Object.freeze(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.entries(operations).map(([operation, definition]) => [\n\t\t\t\t\toperation,\n\t\t\t\t\tdefinition.aggregates,\n\t\t\t\t]),\n\t\t\t),\n\t\t) as this['aggregates']\n\t\tthis.#kernel = new CommandKernelClass<Context, Operations>({\n\t\t\toperations,\n\t\t\texecute: (execution) => this.#execute(execution),\n\t\t})\n\t}\n\n\t/**\n\t * @deprecated Declare handlers inside command({...}) using createEffectFoundation\n\t * from cvx-kit/effect, then call exec(operation, input, host).\n\t */\n\texec<const Key extends OperationKey<Operations>>(executor: {\n\t\toperation: Key\n\t\thandler: (\n\t\t\tcontext: Context & OperationExtension<Operations[Key]>,\n\t\t\tcommand: CommandInput<Operations, Key>,\n\t\t) => MaybePromise<CommandHandlerResult<Operations, Key>>\n\t}) {\n\t\treturn this.#kernel.exec({\n\t\t\toperation: executor.operation,\n\t\t\thandler: (context, command) =>\n\t\t\t\texecutor.handler(\n\t\t\t\t\t// SAFETY: operationFactory requires enrichment middleware before this handler.\n\t\t\t\t\tcontext as Context & OperationExtension<Operations[Key]>,\n\t\t\t\t\tcommand,\n\t\t\t\t),\n\t\t})\n\t}\n\n\tasync #execute<Key extends OperationKey<Operations>>(\n\t\texecution: CommandExecution<Context, Operations, Key>,\n\t): Promise<CommandResult<Operations, Key>> {\n\t\tconst definition = execution.definition\n\t\treturn this.#observability.observe(\n\t\t\t{ operation: execution.operation, classification: definition.classification },\n\t\t\t() =>\n\t\t\t\texecuteCommandLifecycle<\n\t\t\t\t\tPromiseExecution,\n\t\t\t\t\tContext,\n\t\t\t\t\tCommandInput<Operations, Key>,\n\t\t\t\t\tCommandHandlerResult<Operations, Key>,\n\t\t\t\t\tCommandResult<Operations, Key>\n\t\t\t\t>(promiseLifecycle, {\n\t\t\t\t\toperation: execution.operation,\n\t\t\t\t\tclassification: definition.classification,\n\t\t\t\t\tcontext: execution.context,\n\t\t\t\t\tcommand: execution.command,\n\t\t\t\t\tpermission:\n\t\t\t\t\t\tdefinition.permission === undefined\n\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t: async () => {\n\t\t\t\t\t\t\t\t\tif (!this.#checkPermission) throw new CommandPermissionError(execution.operation)\n\t\t\t\t\t\t\t\t\t// SAFETY: injected policy consumes this invocation's original host context.\n\t\t\t\t\t\t\t\t\tawait this.#checkPermission(execution.context as never, {\n\t\t\t\t\t\t\t\t\t\tpermission: definition.permission!,\n\t\t\t\t\t\t\t\t\t\toperation: execution.operation,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\tprepare: async () => {\n\t\t\t\t\t\t// SAFETY: selected definition and parsed input are paired by the kernel.\n\t\t\t\t\t\tconst preparation = await definition.prepare?.(\n\t\t\t\t\t\t\texecution.context as never,\n\t\t\t\t\t\t\texecution.command as never,\n\t\t\t\t\t\t)\n\t\t\t\t\t\tif (preparation?.kind !== 'execute') return preparation\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tkind: 'execute' as const,\n\t\t\t\t\t\t\tcomplete: preparation.complete\n\t\t\t\t\t\t\t\t? async (result: CommandResult<Operations, Key>) => {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: completion belongs to this operation's validated final result.\n\t\t\t\t\t\t\t\t\t\tawait preparation.complete!(result as never)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tparseReplay: (value) => {\n\t\t\t\t\t\tif (!definition.replayResult) return execution.parseResult(value)\n\t\t\t\t\t\t// SAFETY: selected replay schema validates this operation's stored output.\n\t\t\t\t\t\treturn parseCommandSchema(definition.replayResult, value) as CommandResult<\n\t\t\t\t\t\t\tOperations,\n\t\t\t\t\t\t\tKey\n\t\t\t\t\t\t>\n\t\t\t\t\t},\n\t\t\t\t\tdecodeReplay: async (value) => {\n\t\t\t\t\t\tif (!definition.replayResult) {\n\t\t\t\t\t\t\treturn execution.decodeResult\n\t\t\t\t\t\t\t\t? execution.decodeResult(value)\n\t\t\t\t\t\t\t\t: execution.parseResult(value)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst replay = definition.replayResult\n\t\t\t\t\t\t// SAFETY: selected replay decoder owns the final output representation.\n\t\t\t\t\t\treturn (await decodeCommandSchema(replay, value)) as CommandResult<Operations, Key>\n\t\t\t\t\t},\n\t\t\t\t\tmiddleware: [...(this.#defaults.middleware ?? []), ...(definition.middleware ?? [])].map(\n\t\t\t\t\t\t(layer) => async (input) => {\n\t\t\t\t\t\t\t// SAFETY: selected definition owns this heterogeneous middleware's pre-validation output.\n\t\t\t\t\t\t\treturn layer({\n\t\t\t\t\t\t\t\t...input,\n\t\t\t\t\t\t\t\tdefinition,\n\t\t\t\t\t\t\t\t// SAFETY: selected command schema owns this heterogeneous storage value.\n\t\t\t\t\t\t\t\tcommand: input.command as never,\n\t\t\t\t\t\t\t\t// SAFETY: only heterogeneous storage erases the selected middleware context.\n\t\t\t\t\t\t\t\tcontext: input.context as never,\n\t\t\t\t\t\t\t\t// SAFETY: selected operation pairs downstream output with its final schema.\n\t\t\t\t\t\t\t\tnext: input.next as (options?: { context?: object }) => Promise<never>,\n\t\t\t\t\t\t\t}) as Promise<CommandHandlerResult<Operations, Key>>\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t\tdefaultGuard: async (context) => {\n\t\t\t\t\t\t// SAFETY: default guards consume the downstream middleware context.\n\t\t\t\t\t\tawait this.#defaults.guard?.(context as never)\n\t\t\t\t\t},\n\t\t\t\t\tguard: async (context) => {\n\t\t\t\t\t\t// SAFETY: selected guard consumes its parsed input and enriched context.\n\t\t\t\t\t\tawait definition.guard?.(context as never, execution.command as never)\n\t\t\t\t\t},\n\t\t\t\t\trun: (context) => execution.runUnparsed(context),\n\t\t\t\t\tparseResult: execution.parseResult,\n\t\t\t\t\tdecodeResult: execution.decodeResult,\n\t\t\t\t\taudit: async (result) => {\n\t\t\t\t\t\t// SAFETY: audit receives this selected parsed command/result and original context.\n\t\t\t\t\t\treturn definition.audit(\n\t\t\t\t\t\t\t{ command: execution.command, result } as never,\n\t\t\t\t\t\t\texecution.context as never,\n\t\t\t\t\t\t)\n\t\t\t\t\t},\n\t\t\t\t\taggregates: definition.aggregates,\n\t\t\t\t\twriteAudit: async (entry) => {\n\t\t\t\t\t\t// SAFETY: host supplied writer for this invocation's original context.\n\t\t\t\t\t\treturn this.#writeAudit(execution.context as never, entry)\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t)\n\t}\n}\n\n/** @deprecated Use the registry returned by createEffectFoundation(...).Command from cvx-kit/effect. */\nexport type ApplicationCommand<Context, Operations extends AuditedRegistry> = BoundCommand<\n\tContext,\n\tOperations\n>\n\n/**\n * The constructor shape a Foundation instance exposes as `Command`.\n * Exported as a TYPE ONLY so factories (e.g. cvx-kit/crud) can accept the\n * destructured facade class as input without importing any runtime kernel.\n * @deprecated Use createEffectFoundation from cvx-kit/effect and declare handlers inside command({...}).\n */\nexport type CommandConstructor = {\n\t/** @deprecated Use createEffectFoundation(...).Command({ context, operations }) from cvx-kit/effect. */\n\tnew <Context, const Operations extends AuditedRegistry>(\n\t\toperations: Operations & {\n\t\t\treadonly [Key in keyof Operations]: OperationHostContext<Context>\n\t\t},\n\t\tdefaults?: CommandDefaults,\n\t): BoundCommand<Context, Operations>\n\toperation: (typeof BoundCommand)['operation']\n\twithContext: (typeof BoundCommand)['withContext']\n\tmiddleware: (typeof BoundCommand)['middleware']\n}\n\n/**\n * Host facade for a component that owns no application execution capability.\n * Declared once; the sole source of the command protocol, query kernel, and\n * observability: `const { Command, Query, observability } = new Foundation(...)`.\n */\nexport class Foundation<Component extends FoundationComponentApi = FoundationComponentApi> {\n\treadonly status: Component['functions']['status']\n\t/** @deprecated Use createEffectFoundation(...).Command from cvx-kit/effect. */\n\treadonly Command: CommandConstructor\n\treadonly Query = Query\n\treadonly observability: Observability\n\t/** Typed-failure boundary — see result.ts. Facade-bound like the kernels. */\n\treadonly executeResultBoundary = executeResultBoundary\n\treadonly projectResult = projectResult\n\treadonly emitSemanticEvent = emitSemanticEvent\n\n\tconstructor(component: Component, options: FoundationOptions) {\n\t\tthis.status = component.functions.status\n\t\tconst observability = new Observability(options.observability)\n\t\tthis.observability = observability\n\t\tconst writeAudit = options.observability.writeAudit ?? (() => undefined)\n\t\tconst checkPermission = options.checkPermission\n\t\tclass HostCommand<Context, const Operations extends AuditedRegistry> extends BoundCommand<\n\t\t\tContext,\n\t\t\tOperations\n\t\t> {\n\t\t\tconstructor(operations: Operations, defaults?: CommandDefaults) {\n\t\t\t\tsuper(operations, {\n\t\t\t\t\tobservability,\n\t\t\t\t\twriteAudit,\n\t\t\t\t\tcheckPermission,\n\t\t\t\t\tdefaults,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tthis.Command = HostCommand\n\t}\n}\n\n// Kernel CLASSES are deliberately NOT exported: Command, Query, and\n// Observability exist only as capabilities of a Foundation instance —\n// `const { Command, Query, observability } = new Foundation(...)`. A loose\n// import would construct kernels without the injected observability, audit\n// writer, and permission checker. Types stay exported for signatures.\nexport type { CommandPreparation, TypedOperation } from './operation'\nexport type {\n\tCommandArgument,\n\tCommandExecution,\n\tCommandHandlerResult,\n\tCommandInput,\n\tCommandRegistry,\n\tCommandResult,\n\tSchemaOutput,\n\tParseable,\n} from './modules/command/command'\nexport type {\n\tCommandObservation,\n\tObservabilityOptions,\n} from './modules/observability/observability'\nexport type { AnyQueryMiddleware, QueryExecution, QueryMiddleware } from './modules/query/query'\nexport type { Result, ResultBoundary, TransactionMetricsContext } from './result'\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 foundation from 'cvx-kit/components/foundation/convex.config'\n"],"mappings":"A,ghBA2JA,IAAMC,EAAN,KAAsE,CACrE,OAAO,YAAcC,EACrB,GACA,GACA,GACA,GACA,GAGA,WAIA,OAAO,UAAqD,EAAoC,CAC/F,OAAOC,CACR,CAMA,OAAO,WAMN,EACuD,CACvD,OAAOC,CACR,CAEA,YACC,EACA,EAMC,CACD,KAAKC,GAAiBC,EAAK,cAC3B,KAAKC,G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A,kBACA,UACD,CAAC,CACF,CACD,CACA,KAAK,QAAUgC,CAChB,CACD,E"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convex.config.mjs","names":["convex_config_default","defineComponent"],"sources":["../../../src/components/foundation/convex.config.ts"],"sourcesContent":["import { defineComponent } from 'convex/server'\n\nexport default defineComponent('foundation')\n"],"mappings":"gDAEA,IAAAA,EAAeC,EAAgB,YAAY"}
|
|
1
|
+
{"version":3,"file":"convex.config.mjs","names":["convex_config_default","defineComponent"],"sources":["../../../src/components/foundation/convex.config.ts"],"sourcesContent":["import { defineComponent } from 'convex/server'\n\nexport default defineComponent('foundation')\n"],"mappings":"A,gDAEA,IAAAA,EAAeC,EAAgB,YAAY,E"}
|
|
@@ -3,6 +3,5 @@ declare namespace functions_d_exports {
|
|
|
3
3
|
}
|
|
4
4
|
/** Minimal health signal exposed only through the configured host facade. */
|
|
5
5
|
export declare const status: import("convex/server").RegisteredQuery<"public", {}, Promise<"ready">>;
|
|
6
|
-
//#endregion
|
|
7
6
|
export { functions_d_exports };
|
|
8
7
|
//# sourceMappingURL=functions.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"functions.mjs","names":["status","query","v"],"sources":["../../../src/components/foundation/functions.ts"],"sourcesContent":["import { v } from 'convex/values'\n\nimport { query } from './_generated/server'\n\n/** Minimal health signal exposed only through the configured host facade. */\nexport const status = query({\n\targs: {},\n\treturns: v.literal('ready'),\n\thandler: async () => 'ready' as const,\n})\n"],"mappings":"kFAKA,MAAaA,EAASC,EAAM,CAC3B,KAAM,CAAC,EACP,QAASC,EAAE,QAAQ,OAAO,EAC1B,QAAS,SAAY,OACtB,CAAC"}
|
|
1
|
+
{"version":3,"file":"functions.mjs","names":["status","query","v"],"sources":["../../../src/components/foundation/functions.ts"],"sourcesContent":["import { v } from 'convex/values'\n\nimport { query } from './_generated/server'\n\n/** Minimal health signal exposed only through the configured host facade. */\nexport const status = query({\n\targs: {},\n\treturns: v.literal('ready'),\n\thandler: async () => 'ready' as const,\n})\n"],"mappings":"A,kFAKA,MAAaA,EAASC,EAAM,CAC3B,KAAM,CAAC,EACP,QAASC,EAAE,QAAQ,OAAO,EAC1B,QAAS,SAAY,OACtB,CAAC,E"}
|
|
@@ -92,6 +92,5 @@ export declare class Command<Context, const Registry extends CommandRegistry> {
|
|
|
92
92
|
export declare function parseCommandSchema<S extends CommandSchema>(schema: S, value: unknown): SchemaOutput<S>;
|
|
93
93
|
/** Interpreter-owned decoding awaits validation and leaves thrown/rejected defects intact. */
|
|
94
94
|
export declare function decodeCommandSchema<S extends CommandSchema>(schema: S, value: unknown): Promise<SchemaOutput<S>>;
|
|
95
|
-
//#endregion
|
|
96
95
|
export { command_d_exports };
|
|
97
96
|
//# sourceMappingURL=command.d.mts.map
|