cvx-kit 0.2.0 → 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 +556 -99
- package/dist/agent-tools.d.mts +39 -26
- package/dist/agent-tools.mjs +1 -1
- package/dist/agent-tools.mjs.map +1 -1
- package/dist/auth.d.mts +120 -308
- package/dist/auth.mjs +1 -1
- package/dist/auth.mjs.map +1 -1
- package/dist/components/approvals/_generated/api.d.mts +7 -9
- package/dist/components/approvals/_generated/api.mjs.map +1 -1
- package/dist/components/approvals/_generated/component.d.mts +1 -4
- package/dist/components/approvals/_generated/dataModel.d.mts +5 -8
- package/dist/components/approvals/_generated/server.d.mts +12 -15
- package/dist/components/approvals/_generated/server.mjs.map +1 -1
- package/dist/components/approvals/audit.d.mts +8 -9
- package/dist/components/approvals/audit.mjs +1 -1
- package/dist/components/approvals/audit.mjs.map +1 -1
- package/dist/components/approvals/client.d.mts +11 -12
- package/dist/components/approvals/client.mjs +1 -1
- package/dist/components/approvals/client.mjs.map +1 -1
- package/dist/components/approvals/constants.d.mts +30 -31
- 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 +13 -17
- package/dist/components/approvals/decisions.mjs +1 -1
- package/dist/components/approvals/decisions.mjs.map +1 -1
- package/dist/components/approvals/functions.d.mts +3 -4
- package/dist/components/approvals/functions.mjs +1 -1
- package/dist/components/approvals/functions.mjs.map +1 -1
- package/dist/components/approvals/health.d.mts +2 -3
- package/dist/components/approvals/health.mjs.map +1 -1
- package/dist/components/approvals/requests.d.mts +114 -131
- 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 +323 -395
- package/dist/components/approvals/validators.mjs +1 -1
- package/dist/components/approvals/validators.mjs.map +1 -1
- package/dist/components/approvals/workflow.d.mts +4 -5
- 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 +16 -17
- package/dist/components/approvals/workflow_steps.mjs +1 -1
- package/dist/components/approvals/workflow_steps.mjs.map +1 -1
- package/dist/components/foundation/_generated/api.d.mts +6 -8
- package/dist/components/foundation/_generated/api.mjs.map +1 -1
- package/dist/components/foundation/_generated/component.d.mts +1 -4
- package/dist/components/foundation/_generated/dataModel.d.mts +5 -8
- package/dist/components/foundation/_generated/server.d.mts +12 -15
- package/dist/components/foundation/_generated/server.mjs.map +1 -1
- package/dist/components/foundation/client.d.mts +45 -38
- 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 +2 -3
- package/dist/components/foundation/functions.mjs.map +1 -1
- package/dist/components/foundation/modules/command/command.d.mts +65 -17
- package/dist/components/foundation/modules/command/command.mjs +1 -1
- package/dist/components/foundation/modules/command/command.mjs.map +1 -1
- package/dist/components/foundation/modules/command/lifecycle.d.mts +78 -0
- package/dist/components/foundation/modules/command/lifecycle.mjs +2 -0
- package/dist/components/foundation/modules/command/lifecycle.mjs.map +1 -0
- package/dist/components/foundation/modules/observability/observability.d.mts +13 -6
- package/dist/components/foundation/modules/observability/observability.mjs +1 -1
- package/dist/components/foundation/modules/observability/observability.mjs.map +1 -1
- package/dist/components/foundation/modules/query/query.d.mts +11 -12
- package/dist/components/foundation/modules/query/query.mjs +1 -1
- package/dist/components/foundation/modules/query/query.mjs.map +1 -1
- package/dist/components/foundation/operation.d.mts +72 -0
- package/dist/components/foundation/operation.mjs +2 -0
- package/dist/components/foundation/operation.mjs.map +1 -0
- package/dist/components/foundation/result.d.mts +7 -8
- 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 +2 -3
- package/dist/components/foundation/telemetry.mjs +1 -1
- package/dist/components/foundation/telemetry.mjs.map +1 -1
- package/dist/contracts.d.mts +5 -0
- package/dist/contracts.mjs +1 -0
- package/dist/crud.d.mts +185 -27
- package/dist/crud.mjs +1 -1
- package/dist/crud.mjs.map +1 -1
- package/dist/effect.d.mts +16 -0
- package/dist/effect.mjs +1 -0
- package/dist/errors.d.mts +6 -6
- package/dist/errors.mjs +1 -1
- package/dist/errors.mjs.map +1 -1
- package/dist/filters.d.mts +4 -0
- package/dist/filters.mjs +1 -0
- package/dist/idempotency.d.mts +2 -0
- package/dist/idempotency.mjs +1 -0
- package/dist/index.d.mts +14 -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 +8 -11
- package/dist/middleware.mjs +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/modules/contracts/binding.d.mts +23 -0
- package/dist/modules/contracts/binding.mjs +2 -0
- package/dist/modules/contracts/binding.mjs.map +1 -0
- package/dist/modules/contracts/contract.d.mts +67 -0
- package/dist/modules/contracts/contract.mjs +2 -0
- package/dist/modules/contracts/contract.mjs.map +1 -0
- package/dist/modules/contracts/convex.d.mts +18 -0
- package/dist/modules/contracts/convex.mjs +2 -0
- package/dist/modules/contracts/convex.mjs.map +1 -0
- package/dist/modules/contracts/domain.d.mts +62 -0
- package/dist/modules/contracts/domain.mjs +2 -0
- package/dist/modules/contracts/domain.mjs.map +1 -0
- package/dist/modules/contracts/errors.d.mts +737 -0
- package/dist/modules/contracts/errors.mjs +2 -0
- package/dist/modules/contracts/errors.mjs.map +1 -0
- package/dist/modules/contracts/exposure.d.mts +103 -0
- package/dist/modules/contracts/exposure.mjs +2 -0
- package/dist/modules/contracts/exposure.mjs.map +1 -0
- package/dist/modules/contracts/idempotency.d.mts +85 -0
- package/dist/modules/contracts/idempotency.mjs +2 -0
- package/dist/modules/contracts/idempotency.mjs.map +1 -0
- package/dist/modules/contracts/lazy.d.mts +6 -0
- package/dist/modules/contracts/lazy.mjs +2 -0
- package/dist/modules/contracts/lazy.mjs.map +1 -0
- package/dist/modules/contracts/standard.d.mts +17 -0
- package/dist/modules/contracts/standard.mjs +2 -0
- package/dist/modules/contracts/standard.mjs.map +1 -0
- package/dist/modules/contracts/workflow.d.mts +165 -0
- package/dist/modules/contracts/workflow.mjs +2 -0
- package/dist/modules/contracts/workflow.mjs.map +1 -0
- package/dist/modules/effect/action.d.mts +63 -0
- package/dist/modules/effect/action.mjs +2 -0
- package/dist/modules/effect/action.mjs.map +1 -0
- package/dist/modules/effect/agent-tools.d.mts +2 -0
- package/dist/modules/effect/agent-tools.mjs +1 -0
- package/dist/modules/effect/api-runtime.d.mts +36 -0
- package/dist/modules/effect/api-runtime.mjs +2 -0
- package/dist/modules/effect/api-runtime.mjs.map +1 -0
- package/dist/modules/effect/api.d.mts +46 -0
- package/dist/modules/effect/api.mjs +2 -0
- package/dist/modules/effect/api.mjs.map +1 -0
- package/dist/modules/effect/auth.d.mts +46 -0
- package/dist/modules/effect/auth.mjs +2 -0
- package/dist/modules/effect/auth.mjs.map +1 -0
- package/dist/modules/effect/client.d.mts +15 -0
- package/dist/modules/effect/client.mjs +1 -0
- package/dist/modules/effect/command.d.mts +108 -0
- package/dist/modules/effect/command.mjs +2 -0
- package/dist/modules/effect/command.mjs.map +1 -0
- package/dist/modules/effect/crud.d.mts +885 -0
- package/dist/modules/effect/crud.mjs +2 -0
- package/dist/modules/effect/crud.mjs.map +1 -0
- package/dist/modules/effect/domain.d.mts +82 -0
- package/dist/modules/effect/domain.mjs +2 -0
- package/dist/modules/effect/domain.mjs.map +1 -0
- package/dist/modules/effect/errors.d.mts +13 -0
- package/dist/modules/effect/errors.mjs +2 -0
- package/dist/modules/effect/errors.mjs.map +1 -0
- package/dist/modules/effect/failure-audit.d.mts +48 -0
- package/dist/modules/effect/failure-audit.mjs +2 -0
- package/dist/modules/effect/failure-audit.mjs.map +1 -0
- package/dist/modules/effect/failures.d.mts +21 -0
- package/dist/modules/effect/failures.mjs +2 -0
- package/dist/modules/effect/failures.mjs.map +1 -0
- package/dist/modules/effect/foundation.d.mts +23 -0
- package/dist/modules/effect/foundation.mjs +2 -0
- package/dist/modules/effect/foundation.mjs.map +1 -0
- package/dist/modules/effect/idempotency.d.mts +29 -0
- package/dist/modules/effect/idempotency.mjs +2 -0
- package/dist/modules/effect/idempotency.mjs.map +1 -0
- 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 +7 -0
- package/dist/modules/effect/normalize.mjs +2 -0
- package/dist/modules/effect/normalize.mjs.map +1 -0
- package/dist/modules/effect/operation.d.mts +148 -0
- package/dist/modules/effect/operation.mjs +2 -0
- package/dist/modules/effect/operation.mjs.map +1 -0
- package/dist/modules/effect/query.d.mts +90 -0
- package/dist/modules/effect/query.mjs +2 -0
- package/dist/modules/effect/query.mjs.map +1 -0
- package/dist/modules/effect/schema.d.mts +30 -0
- package/dist/modules/effect/schema.mjs +2 -0
- package/dist/modules/effect/schema.mjs.map +1 -0
- package/dist/modules/effect/scope.d.mts +25 -0
- package/dist/modules/effect/scope.mjs +2 -0
- package/dist/modules/effect/scope.mjs.map +1 -0
- package/dist/modules/effect/workflow.d.mts +75 -0
- package/dist/modules/effect/workflow.mjs +2 -0
- package/dist/modules/effect/workflow.mjs.map +1 -0
- package/dist/modules/foundation/foundation.d.mts +108 -0
- package/dist/modules/foundation/foundation.mjs +2 -0
- package/dist/modules/foundation/foundation.mjs.map +1 -0
- package/dist/modules/foundation/operation.d.mts +139 -0
- package/dist/modules/foundation/operation.mjs +2 -0
- package/dist/modules/foundation/operation.mjs.map +1 -0
- 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 +23 -0
- package/dist/oxlint/architecture.mjs +2 -0
- package/dist/oxlint/architecture.mjs.map +1 -0
- package/dist/oxlint/ast.d.mts +51 -0
- package/dist/oxlint/ast.mjs +2 -0
- package/dist/oxlint/ast.mjs.map +1 -0
- package/dist/oxlint/components.d.mts +4 -0
- package/dist/oxlint/components.mjs +2 -0
- package/dist/oxlint/components.mjs.map +1 -0
- package/dist/oxlint/ownership.d.mts +59 -0
- package/dist/oxlint/ownership.mjs +2 -0
- package/dist/oxlint/ownership.mjs.map +1 -0
- package/dist/oxlint/reserved-files.d.mts +4 -0
- package/dist/oxlint/reserved-files.mjs +2 -0
- package/dist/oxlint/reserved-files.mjs.map +1 -0
- package/dist/oxlint.d.mts +9 -0
- package/dist/oxlint.mjs +2 -0
- package/dist/oxlint.mjs.map +1 -0
- package/dist/querying/cursors.d.mts +94 -0
- package/dist/querying/cursors.mjs +2 -0
- package/dist/querying/cursors.mjs.map +1 -0
- package/dist/querying/execution.d.mts +40 -0
- package/dist/querying/execution.mjs +2 -0
- package/dist/querying/execution.mjs.map +1 -0
- package/dist/querying/failures.d.mts +11 -0
- package/dist/querying/failures.mjs +2 -0
- package/dist/querying/failures.mjs.map +1 -0
- package/dist/querying/filter-boundary.d.mts +25 -0
- package/dist/querying/filter-boundary.mjs +2 -0
- package/dist/querying/filter-boundary.mjs.map +1 -0
- package/dist/querying/filters.d.mts +180 -0
- package/dist/querying/filters.mjs +2 -0
- package/dist/querying/filters.mjs.map +1 -0
- package/dist/querying/planner.d.mts +61 -0
- package/dist/querying/planner.mjs +2 -0
- package/dist/querying/planner.mjs.map +1 -0
- package/dist/querying/relationships.d.mts +58 -0
- package/dist/querying/relationships.mjs +2 -0
- package/dist/querying/relationships.mjs.map +1 -0
- package/dist/querying/search.d.mts +69 -0
- package/dist/querying/search.mjs +2 -0
- package/dist/querying/search.mjs.map +1 -0
- package/dist/querying/security.d.mts +123 -0
- package/dist/querying/security.mjs +2 -0
- package/dist/querying/security.mjs.map +1 -0
- package/dist/querying/shared/ast.d.mts +26 -0
- package/dist/querying/shared/ast.mjs +2 -0
- package/dist/querying/shared/ast.mjs.map +1 -0
- package/dist/querying/shared/contract.d.mts +98 -0
- package/dist/querying/shared/contract.mjs +2 -0
- package/dist/querying/shared/contract.mjs.map +1 -0
- package/dist/querying/shared/evaluate.d.mts +5 -0
- package/dist/querying/shared/evaluate.mjs +2 -0
- package/dist/querying/shared/evaluate.mjs.map +1 -0
- package/dist/querying/shared/filters.d.mts +65 -0
- package/dist/querying/shared/filters.mjs +2 -0
- package/dist/querying/shared/filters.mjs.map +1 -0
- 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 +20 -0
- package/dist/querying/shared/page.mjs +2 -0
- package/dist/querying/shared/page.mjs.map +1 -0
- package/dist/querying.d.mts +82 -0
- package/dist/querying.mjs +2 -0
- package/dist/querying.mjs.map +1 -0
- package/dist/react/failures.d.mts +24 -0
- package/dist/react/failures.mjs +2 -0
- package/dist/react/failures.mjs.map +1 -0
- package/dist/react/optimistic.d.mts +46 -0
- package/dist/react/optimistic.mjs +2 -0
- package/dist/react/optimistic.mjs.map +1 -0
- package/dist/react/pagination-state.d.mts +39 -0
- package/dist/react/pagination-state.mjs +2 -0
- package/dist/react/pagination-state.mjs.map +1 -0
- package/dist/react/use-command.d.mts +22 -0
- package/dist/react/use-command.mjs +2 -0
- package/dist/react/use-command.mjs.map +1 -0
- package/dist/react/use-paginated-list.d.mts +34 -0
- package/dist/react/use-paginated-list.mjs +2 -0
- package/dist/react/use-paginated-list.mjs.map +1 -0
- package/dist/react.d.mts +6 -0
- package/dist/react.mjs +1 -0
- 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 -0
- package/dist/relations-public.mjs +1 -0
- package/dist/relations.d.mts +274 -0
- package/dist/relations.mjs +2 -0
- package/dist/relations.mjs.map +1 -0
- package/dist/state-machine.d.mts +1 -4
- 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 +6 -8
- package/dist/tenancy.mjs +1 -1
- package/dist/tenancy.mjs.map +1 -1
- package/dist/triggers.d.mts +12 -10
- package/dist/triggers.mjs +1 -1
- package/dist/triggers.mjs.map +1 -1
- package/dist/webhooks.d.mts +22 -112
- package/dist/webhooks.mjs +1 -1
- package/dist/webhooks.mjs.map +1 -1
- package/dist/workflow.d.mts +2 -0
- package/dist/workflow.mjs +1 -0
- package/dist/zod.d.mts +30 -0
- package/dist/zod.mjs +2 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +145 -33
- package/src/test.ts +9 -17
- package/CHANGELOG.md +0 -145
- package/ROADMAP.md +0 -126
- package/dist/zod-table.d.mts +0 -175
- package/dist/zod-table.mjs +0 -2
- package/dist/zod-table.mjs.map +0 -1
- package/docs/agent-tools.md +0 -41
- package/docs/approvals.md +0 -200
- package/docs/architecture.md +0 -124
- package/docs/auth.md +0 -218
- package/docs/commands.md +0 -278
- package/docs/conventions.md +0 -291
- package/docs/crud.md +0 -62
- package/docs/llms.md +0 -220
- package/docs/maintainability.md +0 -124
- package/docs/migration.md +0 -351
- package/docs/plans/2026-08-14-001-feat-v0.1.0-feature-set-plan.md +0 -461
- package/docs/plans/2026-08-21-0930-feat-resolve-organization-hook-plan.md +0 -178
- package/docs/tenancy.md +0 -179
- package/docs/triggers.md +0 -75
- package/docs/upgrading.md +0 -175
- package/docs/webhooks.md +0 -58
- package/docs/zod-table.md +0 -173
- package/scripts/convex-config-bridge.mjs +0 -55
- package/scripts/extract-changelog.mjs +0 -29
- package/scripts/smoke-packed-components.mjs +0 -374
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ConvexError as e}from"convex/values";const t=Object.freeze({_tag:`UnknownFailure`,version:1});function n(n){let r=Object.fromEntries(Object.entries(n).map(([e,t])=>{if(!e||!t.message||t.message.length>200)throw Error(`Declared errors require a code and a public message of 1–200 characters`);return[e,{message:t.message,details:{...t.details}}]})),i=/* @__PURE__ */ new WeakMap,a={create(e,t){let n;try{if(!Object.hasOwn(r,e))throw Error(`Undeclared code`);let i=r[e];n={_tag:`DeclaredFailure`,version:1,code:e,message:i.message,details:d(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:u(n.details)});return i.set(a,n),a},envelope(e,t){return a.project(a.create(e,t))},toConvexError(t,n){return new e(a.envelope(t,n))},project(e){if(typeof e!=`object`||!e)return t;let n=i.get(e);return n?u(n):t},decode(e){try{if(!l(e)||e._tag!==`DeclaredFailure`||e.version!==1||typeof e.code!=`string`||!Object.hasOwn(r,e.code)||Object.keys(e).length!==5||![`message`,`details`,`_tag`,`version`,`code`].every(t=>Object.hasOwn(e,t)))return t;let n=r[e.code];return e.message===n.message?(u(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:d(n,e.details,!0)}):t}catch{return t}}};return a}function r(n,r){try{if(n instanceof e){let e=n.data;if(typeof e==`string`){if(e.length>65536||new TextEncoder().encode(e).byteLength>65536)return t;e=JSON.parse(e)}return r.decode(e)}}catch{}return t}function i(...e){let n=t;return{project(t){for(let n of e){let e=n.project(t);if(e._tag===`DeclaredFailure`)return e;let i=r(t,n);if(i._tag===`DeclaredFailure`)return i}return n},decode(t){for(let n of e){let e=n.decode(t);if(e._tag===`DeclaredFailure`)return e}return n}}}const a=/* @__PURE__ */ n({"invalid-cursor":{message:`Invalid cursor`,details:{}},FIELD_GROUP_DENIED:{message:`Field group access denied`,details:{}},QUERY_FANOUT:{message:`Query fan-out limit exceeded`,details:{}},SEARCH_TEXT_REQUIRED:{message:`Search text required`,details:{}},SEARCH_END_CURSOR_UNSUPPORTED:{message:`Search end cursor unsupported`,details:{}},SEARCH_ORDER_UNSUPPORTED:{message:`Search ordering unsupported`,details:{}},SEARCH_RELATION_UNSUPPORTED:{message:`Relation search unsupported`,details:{}},SEARCH_OPTIONS_UNSUPPORTED:{message:`Search options unsupported`,details:{}},SEARCH_PROTOCOL_UNSUPPORTED:{message:`Search pagination protocol unsupported`,details:{}}}),o=Object.freeze({issues:20,pathSegments:32,segmentLength:128,codeLength:64,messageLength:256,totalBytes:32768});function s(e){if(!Array.isArray(e))return[];let t=o,n=[],r=0;for(let i of e.slice(0,t.issues)){if(typeof i!=`object`||!i)continue;let{path:e,code:a,message:o}=i,s={path:Array.isArray(e)?e.slice(0,t.pathSegments).map(e=>typeof e==`number`&&Number.isFinite(e)?e:typeof e==`string`?f(e,t.segmentLength):``):[],code:typeof a==`string`&&a?f(a,t.codeLength):`custom`,message:typeof o==`string`&&o?f(o,t.messageLength):`Invalid value`};if(r+=new TextEncoder().encode(JSON.stringify(s)).length+1,r>t.totalBytes)break;n.push(s)}return n}const c=/* @__PURE__ */ n({INVALID_ARGUMENTS:{message:`Invalid arguments`,details:{issues:{parse:p}}}});function l(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function u(e,t=/* @__PURE__ */ new Set){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||!e||t.has(e))throw Error(`Invalid JSON`);t.add(e);try{if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++)n.push(u(e[r],t));return n}if(!l(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,u(n,t)]))}finally{t.delete(e)}}function d(e,t,n){if(!l(t))throw Error(`Invalid details`);let r=Object.keys(e.details);if(n&&Object.keys(t).some(t=>!Object.hasOwn(e.details,t)))throw Error(`Undeclared detail`);return Object.fromEntries(r.map(n=>{if(!Object.hasOwn(t,n))throw Error(`Missing detail`);return[n,u(e.details[n].parse(t[n]))]}))}function f(e,t){return e.length>t?e.slice(0,t):e}function p(e){let t=o;if(!Array.isArray(e)||e.length>t.issues)throw Error(`Invalid issues`);return e.map(e=>{if(!l(e)||Object.keys(e).length!==3||!Array.isArray(e.path)||e.path.length>t.pathSegments||typeof e.code!=`string`||e.code.length>t.codeLength||typeof e.message!=`string`||e.message.length>t.messageLength)throw Error(`Invalid issue`);for(let n of e.path)if(!(typeof n==`number`&&Number.isFinite(n))&&!(typeof n==`string`&&n.length<=t.segmentLength))throw Error(`Invalid issue path`);return{path:[...e.path],code:e.code,message:e.message}})}export{o as ARGUMENT_ISSUE_LIMITS,c as argumentErrors,i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,l as isRecord,a as queryErrors,s as sanitizeArgumentIssues};
|
|
2
|
+
//# sourceMappingURL=errors.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":["unknownFailure","defineErrorContract","declarations","definitions","code","definition","trusted","contract","envelope","parseDetails","details","error","copyJson","ConvexError","isRecord","payload","key","decodeFailure","combineErrorContracts","contracts","unmatched","projected","decoded","queryErrors","ARGUMENT_ISSUE_LIMITS","sanitizeArgumentIssues","issues","limits","result","bytes","issue","entry","path","segment","bounded","message","argumentErrors","parseArgumentIssues","value","prototype","ancestors","index","child","fields","strict","field","max"],"sources":["../../../src/modules/contracts/errors.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- This neutral contract validates unknown transport data and an explicitly keyed code/detail declaration. */\n\nimport { ConvexError } from 'convex/values'\n\n/** Explicit synchronous validators for the final public detail representation. */\nexport type ErrorDetailParser<Output = unknown> = Readonly<{\n\tparse: (value: unknown) => Output\n}>\n\nexport type ErrorDefinitions = Readonly<\n\tRecord<\n\t\tstring,\n\t\tReadonly<{\n\t\t\tmessage: string\n\t\t\tdetails: Readonly<Record<string, ErrorDetailParser>>\n\t\t}>\n\t>\n>\n\ntype Code<Definitions extends ErrorDefinitions> = Extract<keyof Definitions, string>\ntype Details<Definition extends ErrorDefinitions[string]> =\n\tDefinition extends ErrorDefinitions[string]\n\t\t? { [Field in keyof Definition['details']]: ReturnType<Definition['details'][Field]['parse']> }\n\t\t: never\n/** The parsed detail fields one declared code carries. */\nexport type DeclaredErrorDetails<\n\tDefinitions extends ErrorDefinitions,\n\tKey extends Code<Definitions>,\n> = Details<Definitions[Key]>\n\ndeclare const declaredErrorBrand: unique symbol\n\n/** Server failures are trusted only by the contract that created them. */\nexport type DeclaredError<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredError'\n\t\tcode: Key\n\t\tdetails: Details<Definitions[Key]>\n\t\t[declaredErrorBrand]: true\n\t}>\n}[Code<Definitions>]\n\nexport type DeclaredFailure<Definitions extends ErrorDefinitions> = {\n\t[Key in Code<Definitions>]: Readonly<{\n\t\t_tag: 'DeclaredFailure'\n\t\tversion: 1\n\t\tcode: Key\n\t\tmessage: string\n\t\tdetails: Details<Definitions[Key]>\n\t}>\n}[Code<Definitions>]\n\nexport type UnknownFailure = Readonly<{ _tag: 'UnknownFailure'; version: 1 }>\nexport type DecodedFailure<Definitions extends ErrorDefinitions> =\n\t| DeclaredFailure<Definitions>\n\t| UnknownFailure\n\nexport type ErrorContract<Definitions extends ErrorDefinitions> = Readonly<{\n\tcreate: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredError<Definitions>, { code: Key }>\n\tenvelope: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => Extract<DeclaredFailure<Definitions>, { code: Key }>\n\ttoConvexError: <Key extends Code<Definitions>>(\n\t\tcode: Key,\n\t\tdetails: Details<Definitions[NoInfer<Key>]>,\n\t) => ConvexError<Extract<DeclaredFailure<Definitions>, { code: Key }>>\n\tproject: (error: unknown) => DecodedFailure<Definitions>\n\t/** Receives envelope data, e.g. ConvexError.data; never parses error messages. */\n\tdecode: (payload: unknown) => DecodedFailure<Definitions>\n}>\n\nconst unknownFailure: UnknownFailure = Object.freeze({\n\t_tag: 'UnknownFailure',\n\tversion: 1,\n})\ntype Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n/** Closed safe codes, allowlisted details, and a versioned checked transport union. */\nexport function defineErrorContract<const Definitions extends ErrorDefinitions>(\n\tdefinitions: Definitions,\n): ErrorContract<Definitions> {\n\t// SAFETY: the snapshot copies every declaration without changing its code, message or paired parsers.\n\tconst declarations = Object.fromEntries(\n\t\tObject.entries(definitions).map(([code, definition]) => {\n\t\t\tif (!code || !definition.message || definition.message.length > 200) {\n\t\t\t\tthrow Error('Declared errors require a code and a public message of 1–200 characters')\n\t\t\t}\n\t\t\treturn [code, { message: definition.message, details: { ...definition.details } }]\n\t\t}),\n\t) as Definitions\n\tconst trusted = new WeakMap<object, DeclaredFailure<Definitions>>()\n\tconst contract: ErrorContract<Definitions> = {\n\t\tcreate(code, details) {\n\t\t\tlet envelope: DeclaredFailure<Definitions>\n\t\t\ttry {\n\t\t\t\tif (!Object.hasOwn(declarations, code)) throw Error('Undeclared code')\n\t\t\t\tconst definition = declarations[code]\n\t\t\t\t// SAFETY: the selected closed declaration validates every field before construction.\n\t\t\t\tenvelope = {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, details, false),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\t// Validator messages, issue paths and provider causes remain private.\n\t\t\t\tthrow Error('Invalid declared error details')\n\t\t\t}\n\t\t\t// SAFETY: identity is registered below; the inaccessible brand cannot confer trust by itself.\n\t\t\tconst error = Object.freeze({\n\t\t\t\t_tag: 'DeclaredError',\n\t\t\t\tcode,\n\t\t\t\tdetails: copyJson(envelope.details),\n\t\t\t}) as Extract<DeclaredError<Definitions>, { code: typeof code }>\n\t\t\ttrusted.set(error, envelope)\n\t\t\treturn error\n\t\t},\n\t\tenvelope(code, details) {\n\t\t\t// SAFETY: create validates the selected code; project retrieves its private validated envelope.\n\t\t\treturn contract.project(contract.create(code, details)) as Extract<\n\t\t\t\tDeclaredFailure<Definitions>,\n\t\t\t\t{ code: typeof code }\n\t\t\t>\n\t\t},\n\t\ttoConvexError(code, details) {\n\t\t\treturn new ConvexError(contract.envelope(code, details))\n\t\t},\n\t\tproject(error) {\n\t\t\tif (error === null || typeof error !== 'object') return unknownFailure\n\t\t\tconst envelope = trusted.get(error)\n\t\t\t// SAFETY: only validated contract-owned envelopes enter the private map.\n\t\t\treturn envelope ? (copyJson(envelope) as DeclaredFailure<Definitions>) : unknownFailure\n\t\t},\n\t\tdecode(payload) {\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\t!isRecord(payload) ||\n\t\t\t\t\tpayload._tag !== 'DeclaredFailure' ||\n\t\t\t\t\tpayload.version !== 1 ||\n\t\t\t\t\ttypeof payload.code !== 'string' ||\n\t\t\t\t\t!Object.hasOwn(declarations, payload.code) ||\n\t\t\t\t\tObject.keys(payload).length !== 5 ||\n\t\t\t\t\t!['message', 'details', '_tag', 'version', 'code'].every((key) =>\n\t\t\t\t\t\tObject.hasOwn(payload, key),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\treturn unknownFailure\n\t\t\t\t}\n\t\t\t\tconst definition = declarations[payload.code]\n\t\t\t\tif (payload.message !== definition.message) return unknownFailure\n\t\t\t\t// Validate raw transport JSON too: parsers must not hide non-JSON payloads.\n\t\t\t\tcopyJson(payload.details)\n\t\t\t\t// SAFETY: code membership and every allowlisted field have been checked independently.\n\t\t\t\treturn {\n\t\t\t\t\t_tag: 'DeclaredFailure',\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tcode: payload.code,\n\t\t\t\t\tmessage: definition.message,\n\t\t\t\t\tdetails: parseDetails(definition, payload.details, true),\n\t\t\t\t} as DeclaredFailure<Definitions>\n\t\t\t} catch {\n\t\t\t\treturn unknownFailure\n\t\t\t}\n\t\t},\n\t}\n\treturn contract\n}\n\n/** A structural decoder also accepts combined contracts without requiring constructors. */\nexport type FailureContract = Pick<ErrorContract<ErrorDefinitions>, 'decode'>\nexport type FailureOf<Contract extends FailureContract> = ReturnType<Contract['decode']>\ntype ProjectingContract = FailureContract & Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\n/** Extract only ConvexError.data, including one bounded serialized JSON envelope. */\nexport function decodeFailure<Contract extends FailureContract>(\n\terror: unknown,\n\tcontract: Contract,\n): FailureOf<Contract> {\n\ttry {\n\t\tif (error instanceof ConvexError) {\n\t\t\tlet payload: unknown = error.data\n\t\t\tif (typeof payload === 'string') {\n\t\t\t\tif (payload.length > 65536 || new TextEncoder().encode(payload).byteLength > 65536)\n\t\t\t\t\t// SAFETY: every failure decoder includes UnknownFailure.\n\t\t\t\t\treturn unknownFailure as FailureOf<Contract>\n\t\t\t\tpayload = JSON.parse(payload)\n\t\t\t}\n\t\t\t// SAFETY: the structural contract owns the decoded union.\n\t\t\treturn contract.decode(payload) as FailureOf<Contract>\n\t\t}\n\t} catch {\n\t\t// Foreign errors, accessors and invalid JSON expose no diagnostics.\n\t}\n\t// SAFETY: every failure decoder includes UnknownFailure.\n\treturn unknownFailure as FailureOf<Contract>\n}\n\ntype CombinedErrorContract<Contracts extends readonly ProjectingContract[]> = Readonly<{\n\tproject: (error: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n\tdecode: (payload: unknown) => FailureOf<Contracts[number]> | UnknownFailure\n}>\n\n/** Ordered projection and decoding; duplicate codes retain the union of member details. */\nexport function combineErrorContracts<const Contracts extends readonly ProjectingContract[]>(\n\t...contracts: Contracts\n): CombinedErrorContract<Contracts> {\n\tconst unmatched = unknownFailure\n\treturn {\n\t\tproject(error) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst projected = contract.project(error)\n\t\t\t\tif (projected._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn projected as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t\tconst decoded = decodeFailure(error, contract)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: strict transported decoding preserves the same member union.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t\tdecode(payload) {\n\t\t\tfor (const contract of contracts) {\n\t\t\t\tconst decoded = contract.decode(payload)\n\t\t\t\tif (decoded._tag === 'DeclaredFailure') {\n\t\t\t\t\t// SAFETY: this result belongs to a member of the inferred tuple.\n\t\t\t\t\treturn decoded as FailureOf<Contracts[number]>\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn unmatched\n\t\t},\n\t}\n}\n\n/** Fixed, diagnostic-free transport shared by query endpoints and client recovery. */\nexport const queryErrors = /* @__PURE__ */ defineErrorContract({\n\t'invalid-cursor': { message: 'Invalid cursor', details: {} },\n\tFIELD_GROUP_DENIED: { message: 'Field group access denied', details: {} },\n\tQUERY_FANOUT: { message: 'Query fan-out limit exceeded', details: {} },\n\tSEARCH_TEXT_REQUIRED: { message: 'Search text required', details: {} },\n\tSEARCH_END_CURSOR_UNSUPPORTED: {\n\t\tmessage: 'Search end cursor unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_ORDER_UNSUPPORTED: {\n\t\tmessage: 'Search ordering unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_RELATION_UNSUPPORTED: {\n\t\tmessage: 'Relation search unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_OPTIONS_UNSUPPORTED: {\n\t\tmessage: 'Search options unsupported',\n\t\tdetails: {},\n\t},\n\tSEARCH_PROTOCOL_UNSUPPORTED: {\n\t\tmessage: 'Search pagination protocol unsupported',\n\t\tdetails: {},\n\t},\n})\n\n/** One allowlisted, bounded argument issue. The rejected input value is never carried. */\nexport type ArgumentIssue = Readonly<{\n\t// Mutable so the envelope stays assignable to Convex `Value`.\n\tpath: (string | number)[]\n\tcode: string\n\tmessage: string\n}>\n\n/** Bounds applied to every emitted and decoded argument failure. */\nexport const ARGUMENT_ISSUE_LIMITS = Object.freeze({\n\tissues: 20,\n\tpathSegments: 32,\n\tsegmentLength: 128,\n\tcodeLength: 64,\n\tmessageLength: 256,\n\t/** Serialized UTF-8 budget for all issues, so an envelope always fits the transport decoder. */\n\ttotalBytes: 32_768,\n})\n\n/**\n * Allowlist and bound validation issues (e.g. `KValidationError` issues). Only `path`, `code` and\n * `message` survive; `input`, `received`, `params` and nested errors are dropped.\n * Messages and path segments are passed as the schema produced them, exactly as the default\n * payload does: a schema whose own message interpolates the rejected value still exposes it.\n */\nexport function sanitizeArgumentIssues(issues: unknown): ArgumentIssue[] {\n\tif (!Array.isArray(issues)) return []\n\tconst limits = ARGUMENT_ISSUE_LIMITS\n\tconst result: ArgumentIssue[] = []\n\tlet bytes = 0\n\tfor (const issue of issues.slice(0, limits.issues)) {\n\t\tif (issue === null || typeof issue !== 'object') continue\n\t\t// SAFETY: a non-null object; every field read below is type-checked before use.\n\t\tconst { path, code, message } = issue as { path?: unknown; code?: unknown; message?: unknown }\n\t\tconst entry: ArgumentIssue = {\n\t\t\tpath: Array.isArray(path)\n\t\t\t\t? path\n\t\t\t\t\t\t.slice(0, limits.pathSegments)\n\t\t\t\t\t\t.map((segment: unknown) =>\n\t\t\t\t\t\t\ttypeof segment === 'number' && Number.isFinite(segment)\n\t\t\t\t\t\t\t\t? segment\n\t\t\t\t\t\t\t\t: typeof segment === 'string'\n\t\t\t\t\t\t\t\t\t? bounded(segment, limits.segmentLength)\n\t\t\t\t\t\t\t\t\t: '',\n\t\t\t\t\t\t)\n\t\t\t\t: [],\n\t\t\tcode: typeof code === 'string' && code ? bounded(code, limits.codeLength) : 'custom',\n\t\t\tmessage:\n\t\t\t\ttypeof message === 'string' && message\n\t\t\t\t\t? bounded(message, limits.messageLength)\n\t\t\t\t\t: 'Invalid value',\n\t\t}\n\t\t// Later issues are dropped once the serialized total would exceed the transport budget.\n\t\tbytes += new TextEncoder().encode(JSON.stringify(entry)).length + 1\n\t\tif (bytes > limits.totalBytes) break\n\t\tresult.push(entry)\n\t}\n\treturn result\n}\n\n/** Built-in declared contract for rejected function arguments. */\nexport const argumentErrors = /* @__PURE__ */ defineErrorContract({\n\tINVALID_ARGUMENTS: {\n\t\tmessage: 'Invalid arguments',\n\t\tdetails: { issues: { parse: parseArgumentIssues } },\n\t},\n})\n\n/** What an app hook receives when arguments are rejected. */\nexport type ArgumentFailure = Readonly<{\n\t/** `arguments`: the function's declared args; `filter`: the compact pagination filter guard. */\n\tsource: 'arguments' | 'filter'\n\tissues: readonly ArgumentIssue[]\n}>\n\n/**\n * How argument rejections are thrown:\n * - `'validation'` (default): `KValidationError`, a `ConvexError({ code: 'VALIDATION', issues })`.\n * - `'declared'`: `argumentErrors.toConvexError('INVALID_ARGUMENTS', { issues })`, with bounded issues.\n * - a function: its return value is thrown (e.g. the app's own `toConvexError`).\n */\nexport type ArgumentFailurePolicy =\n\t| 'validation'\n\t| 'declared'\n\t| ((failure: ArgumentFailure) => unknown)\n\n/** Plain object records only: no arrays, class instances or exotic prototypes. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n\n/** Copy data without invoking toJSON or retaining mutable provider objects. */\nfunction copyJson(value: unknown, ancestors = new Set<object>()): Json {\n\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\tif (typeof value !== 'object' || value === null || ancestors.has(value))\n\t\tthrow Error('Invalid JSON')\n\tancestors.add(value)\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tconst result: Json[] = []\n\t\t\tfor (let index = 0; index < value.length; index++)\n\t\t\t\tresult.push(copyJson(value[index], ancestors))\n\t\t\treturn result\n\t\t}\n\t\tif (!isRecord(value)) throw Error('Invalid JSON')\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value).map(([key, child]) => [key, copyJson(child, ancestors)]),\n\t\t)\n\t} finally {\n\t\tancestors.delete(value)\n\t}\n}\n\nfunction parseDetails<const Definition extends ErrorDefinitions[string]>(\n\tdefinition: Definition,\n\tvalue: unknown,\n\tstrict: boolean,\n): Details<Definition> {\n\tif (!isRecord(value)) throw Error('Invalid details')\n\tconst fields = Object.keys(definition.details)\n\tif (strict && Object.keys(value).some((key) => !Object.hasOwn(definition.details, key))) {\n\t\tthrow Error('Undeclared detail')\n\t}\n\t// SAFETY: each declared field is validated by its paired parser before its JSON-safe copy is returned.\n\treturn Object.fromEntries(\n\t\tfields.map((field) => {\n\t\t\tif (!Object.hasOwn(value, field)) throw Error('Missing detail')\n\t\t\treturn [field, copyJson(definition.details[field].parse(value[field]))]\n\t\t}),\n\t) as Details<Definition>\n}\n\nfunction bounded(value: string, max: number): string {\n\treturn value.length > max ? value.slice(0, max) : value\n}\n\n/** Strict parser for transported issue lists: exact keys and bounded sizes. */\nfunction parseArgumentIssues(value: unknown): ArgumentIssue[] {\n\tconst limits = ARGUMENT_ISSUE_LIMITS\n\tif (!Array.isArray(value) || value.length > limits.issues) throw Error('Invalid issues')\n\treturn value.map((issue) => {\n\t\tif (\n\t\t\t!isRecord(issue) ||\n\t\t\tObject.keys(issue).length !== 3 ||\n\t\t\t!Array.isArray(issue.path) ||\n\t\t\tissue.path.length > limits.pathSegments ||\n\t\t\ttypeof issue.code !== 'string' ||\n\t\t\tissue.code.length > limits.codeLength ||\n\t\t\ttypeof issue.message !== 'string' ||\n\t\t\tissue.message.length > limits.messageLength\n\t\t)\n\t\t\tthrow Error('Invalid issue')\n\t\tfor (const segment of issue.path)\n\t\t\tif (\n\t\t\t\t!(typeof segment === 'number' && Number.isFinite(segment)) &&\n\t\t\t\t!(typeof segment === 'string' && segment.length <= limits.segmentLength)\n\t\t\t)\n\t\t\t\tthrow Error('Invalid issue path')\n\t\treturn { path: [...issue.path], code: issue.code, message: issue.message }\n\t})\n}\n"],"mappings":"A,4CA2EA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CA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AAO,eAE1D,MAAM,MAAM,oBAAoB,EAClC,MAAO,CAAE,KAAM,CAAC,GAAGG,EAAM,IAAI,EAAG,KAAMA,EAAM,KAAM,QAASA,EAAM,OAAQ,CAC1E,CAAC,CACF,C"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { ContractInput, ContractOutput, ContractSchema } from "./contract.mjs";
|
|
2
|
+
import { DecodedFailure, ErrorContract, ErrorDefinitions, UnknownFailure } from "./errors.mjs";
|
|
3
|
+
declare const selectedTypes: unique symbol;
|
|
4
|
+
declare const executorTypes: unique symbol;
|
|
5
|
+
type Definition = {
|
|
6
|
+
input: ContractSchema;
|
|
7
|
+
result: ContractSchema;
|
|
8
|
+
wire?: {
|
|
9
|
+
schema: ContractSchema;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
export type OperationPublicResult<D extends Definition> = D extends {
|
|
13
|
+
wire: {
|
|
14
|
+
schema: infer Schema extends ContractSchema;
|
|
15
|
+
};
|
|
16
|
+
} ? ContractInput<Schema> : ContractOutput<D['result']>;
|
|
17
|
+
/** Only the selected input/public contracts are exposed, never handlers or other operations. */
|
|
18
|
+
export type SelectedOperation<Owner extends symbol, Key extends string, Input extends ContractSchema, Public> = Readonly<{
|
|
19
|
+
owner: Owner;
|
|
20
|
+
key: Key;
|
|
21
|
+
kind: 'mutation' | 'query';
|
|
22
|
+
input: Input;
|
|
23
|
+
result: ContractSchema;
|
|
24
|
+
readonly [selectedTypes]: {
|
|
25
|
+
readonly input: ContractInput<Input>;
|
|
26
|
+
readonly public: Public;
|
|
27
|
+
};
|
|
28
|
+
}>;
|
|
29
|
+
type Selection = Readonly<{
|
|
30
|
+
owner: symbol;
|
|
31
|
+
key: string;
|
|
32
|
+
kind: 'mutation' | 'query';
|
|
33
|
+
input: ContractSchema;
|
|
34
|
+
result: ContractSchema;
|
|
35
|
+
readonly [selectedTypes]: {
|
|
36
|
+
readonly input: unknown;
|
|
37
|
+
readonly public: unknown;
|
|
38
|
+
};
|
|
39
|
+
}>;
|
|
40
|
+
type InputOf<S extends Selection> = S[typeof selectedTypes]['input'];
|
|
41
|
+
type PublicOf<S extends Selection> = S[typeof selectedTypes]['public'];
|
|
42
|
+
/** Registry integrators must check membership before selecting their own definition. */
|
|
43
|
+
export declare function selectOperation<const Owner extends symbol, const Key extends string, const D extends Definition>(owner: Owner, kind: 'mutation' | 'query', key: Key, definition: D): SelectedOperation<Owner, Key, D['input'], OperationPublicResult<D>>;
|
|
44
|
+
export type OperationExecutor<S extends Selection> = Readonly<{
|
|
45
|
+
owner: S['owner'];
|
|
46
|
+
key: S['key'];
|
|
47
|
+
readonly [executorTypes]: S;
|
|
48
|
+
}>;
|
|
49
|
+
/** The host captures authority in an already authorized native Promise call. */
|
|
50
|
+
export declare function bindOperationExecutor<const S extends Selection>(selected: S, configuration: {
|
|
51
|
+
owner: NoInfer<S['owner']>;
|
|
52
|
+
key: NoInfer<S['key']>;
|
|
53
|
+
execute: (raw: NoInfer<InputOf<S>>) => Promise<NoInfer<PublicOf<S>>>;
|
|
54
|
+
}): OperationExecutor<S>;
|
|
55
|
+
export declare const operationToolDialect: 'https://json-schema.org/draft/2020-12/schema';
|
|
56
|
+
type Json = null | boolean | number | string | readonly Json[] | {
|
|
57
|
+
readonly [key: string]: Json;
|
|
58
|
+
};
|
|
59
|
+
export type OperationToolJsonSchema = Readonly<{
|
|
60
|
+
[keyword: string]: Json;
|
|
61
|
+
}>;
|
|
62
|
+
export type OperationToolConverter<Input extends ContractSchema = ContractSchema> = Readonly<{
|
|
63
|
+
dialect: typeof operationToolDialect;
|
|
64
|
+
/** Represent raw transport input. Unsupported IDs/transforms must throw, never be approximated. */
|
|
65
|
+
convert: (input: Input) => OperationToolJsonSchema;
|
|
66
|
+
}>;
|
|
67
|
+
export type OperationToolDefinition<S extends Selection = Selection, Errors extends ErrorDefinitions = ErrorDefinitions> = Readonly<{
|
|
68
|
+
operation: S;
|
|
69
|
+
executor: OperationExecutor<S>;
|
|
70
|
+
description: string;
|
|
71
|
+
converter: OperationToolConverter<S['input']>;
|
|
72
|
+
errors?: Pick<ErrorContract<Errors>, 'decode'>;
|
|
73
|
+
}>;
|
|
74
|
+
type ToolConstraint = Readonly<{
|
|
75
|
+
operation: Selection;
|
|
76
|
+
executor: OperationExecutor<Selection>;
|
|
77
|
+
description: string;
|
|
78
|
+
converter: {
|
|
79
|
+
dialect: typeof operationToolDialect;
|
|
80
|
+
convert: (input: never) => OperationToolJsonSchema;
|
|
81
|
+
};
|
|
82
|
+
errors?: Pick<ErrorContract<ErrorDefinitions>, 'decode'>;
|
|
83
|
+
}>;
|
|
84
|
+
type Checked<T extends ToolConstraint> = T & OperationToolDefinition<T['operation']>;
|
|
85
|
+
type FailureOf<T> = T extends {
|
|
86
|
+
errors: Pick<ErrorContract<infer E>, 'decode'>;
|
|
87
|
+
} ? DecodedFailure<E> : UnknownFailure;
|
|
88
|
+
export type OperationToolOutcome<Public, Failure = UnknownFailure> = Readonly<{
|
|
89
|
+
_tag: 'Success';
|
|
90
|
+
value: Public;
|
|
91
|
+
}> | Failure;
|
|
92
|
+
export type OperationTool<T extends ToolConstraint> = Readonly<{
|
|
93
|
+
name: string;
|
|
94
|
+
description: string;
|
|
95
|
+
args: OperationToolJsonSchema;
|
|
96
|
+
invoke: (raw: InputOf<T['operation']>) => Promise<OperationToolOutcome<PublicOf<T['operation']>, FailureOf<T>>>;
|
|
97
|
+
}>;
|
|
98
|
+
export declare function createOperationTools<const T extends Readonly<Record<string, ToolConstraint>>>(definitions: T & { [K in keyof T]: Checked<T[K]>; }): Readonly<{ [K in keyof T]: OperationTool<T[K]>; }>;
|
|
99
|
+
export declare function createOperationTools<const T extends readonly (ToolConstraint & {
|
|
100
|
+
name: string;
|
|
101
|
+
})[]>(definitions: T & { [K in keyof T]: Checked<T[K]>; }): Readonly<{ [D in T[number] as D['name']]: OperationTool<D>; }>;
|
|
102
|
+
export {};
|
|
103
|
+
//# sourceMappingURL=exposure.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ConvexError as e}from"convex/values";const t=/* @__PURE__ */ new WeakSet,n=/* @__PURE__ */ new WeakMap;function r(e,n,r,i){if(typeof e!=`symbol`||!r||n!==`mutation`&&n!==`query`||!i?.input||!i.result)throw Error(`Invalid selected operation`);let a=Object.freeze({owner:e,key:r,kind:n,input:i.input,result:i.wire?.schema??i.result});return t.add(a),a}function i(e,r){if(!t.has(e)||r.owner!==e.owner||r.key!==e.key||typeof r.execute!=`function`)throw Error(`Executor does not own the selected operation`);let i=Object.freeze({owner:e.owner,key:e.key});return n.set(i,{selection:e,execute:r.execute}),i}const a=`https://json-schema.org/draft/2020-12/schema`;function o(r){let i=Array.isArray(r)?r.map(e=>[e.name,e]):Object.entries(r),a=Object.create(null);for(let[r,o]of i){if(!r||Object.hasOwn(a,r))throw Error(`Duplicate or empty operation tool name`);let i=o.executor&&n.get(o.executor);if(!t.has(o.operation)||!i||i.selection!==o.operation)throw Error(`Tool requires its selected operation executor`);if(!o.description||o.converter?.dialect!==`https://json-schema.org/draft/2020-12/schema`||typeof o.converter.convert!=`function`)throw Error(`Unsupported operation tool converter`);let s=p(o.converter.convert(o.operation.input)),c=o.errors;a[r]=Object.freeze({name:r,description:o.description,args:s,async invoke(t){try{return{_tag:`Success`,value:await i.execute(t)}}catch(t){try{if(t instanceof e&&c)return c.decode(t.data)}catch{}return{_tag:`UnknownFailure`,version:1}}}})}return Object.freeze(a)}const s=/* @__PURE__ */ new Set([`properties`,`$defs`,`items`,`additionalProperties`,`anyOf`,`oneOf`,`allOf`,`not`,`required`,`enum`,`const`,`default`,`examples`]),c=/* @__PURE__ */ new Set([`object`,`array`,`string`,`number`,`integer`,`boolean`,`null`]),l=/* @__PURE__ */ new Set([`title`,`description`,`format`,`pattern`,`$ref`,`$id`,`x-convex-table`]),u=/* @__PURE__ */ new Set([`minLength`,`maxLength`,`minItems`,`maxItems`,`minProperties`,`maxProperties`]),d=/* @__PURE__ */ new Set([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`]),f=/* @__PURE__ */ new Set([...l,...u,...d,`type`,`uniqueItems`,`$schema`]);function p(e){let t=/* @__PURE__ */ new Set;function n(e){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||t.has(e))throw Error(`Converter schema must be JSON safe`);t.add(e);try{if(Array.isArray(e))return Object.freeze(e.map(n));if(!m(e))throw Error(`Converter schema must be a plain JSON object`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,t])=>[e,n(t)])))}finally{t.delete(e)}}function r(e){if(typeof e!=`boolean`){if(!m(e))throw Error(`Unsupported JSON Schema shape`);for(let[t,n]of Object.entries(e)){if(!f.has(t)&&!s.has(t))throw Error(`Unsupported JSON Schema keyword`);if(l.has(t)&&typeof n!=`string`)throw Error(`Invalid JSON Schema text keyword`);if(u.has(t)&&(typeof n!=`number`||!Number.isInteger(n)||n<0))throw Error(`Invalid JSON Schema count keyword`);if(d.has(t)&&(typeof n!=`number`||!Number.isFinite(n)||t===`multipleOf`&&n<=0))throw Error(`Invalid JSON Schema number keyword`);if(t===`uniqueItems`&&typeof n!=`boolean`)throw Error(`Invalid JSON Schema boolean keyword`);if(t===`pattern`)try{new RegExp(n)}catch{throw Error(`Invalid JSON Schema pattern`)}if((t===`enum`||t===`examples`)&&!Array.isArray(n))throw Error(`Invalid JSON Schema array keyword`);if(t===`enum`&&Array.isArray(n)&&!n.length)throw Error(`Invalid JSON Schema enum`);if(t===`$schema`&&n!==`https://json-schema.org/draft/2020-12/schema`)throw Error(`Unsupported JSON Schema dialect`);if(t===`type`&&!(typeof n==`string`&&c.has(n))&&!(Array.isArray(n)&&n.length>0&&n.every(e=>typeof e==`string`&&c.has(e))))throw Error(`Unsupported JSON Schema type`);if(t===`properties`||t===`$defs`){if(!m(n))throw Error(`Unsupported JSON Schema properties`);Object.values(n).forEach(r)}else if(t===`items`||t===`not`||t===`additionalProperties`)r(n);else if(t===`anyOf`||t===`oneOf`||t===`allOf`){if(!Array.isArray(n)||!n.length)throw Error(`Unsupported JSON Schema alternatives`);n.forEach(r)}else if(t===`required`&&(!Array.isArray(n)||n.some(e=>typeof e!=`string`)||new Set(n).size!==n.length))throw Error(`Unsupported JSON Schema required fields`)}}}let i=n(e);if(!m(i)||i.type!==`object`)throw Error(`Operation tool arguments require an object JSON Schema`);return r(i),i}function m(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}export{i as bindOperationExecutor,o as createOperationTools,a as operationToolDialect,r as selectOperation};
|
|
2
|
+
//# sourceMappingURL=exposure.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exposure.mjs","names":["selections","executors","selectOperation","owner","key","kind","definition","selected","bindOperationExecutor","configuration","executor","operationToolDialect","createOperationTools","entries","definitions","tools","name","paired","args","schemaSnapshot","errors","raw","error","ConvexError","schemaKeywords","types","textKeywords","countKeywords","numberKeywords","scalarKeywords","seen","copy","value","isRecord","item","check","schema","child","type","field","snapshot","prototype"],"sources":["../../../src/modules/contracts/exposure.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-unknown-type-aliases, anti-slop/no-runtime-typeof, anti-slop/no-unsafe-dictionary-type -- Selected native transport boundaries validate opaque identities and converter JSON without decoding domain inputs. */\nimport { ConvexError } from 'convex/values'\nimport type { ContractInput, ContractOutput, ContractSchema } from './contract'\nimport type { DecodedFailure, ErrorContract, ErrorDefinitions, UnknownFailure } from './errors'\n\ndeclare const selectedTypes: unique symbol\ndeclare const executorTypes: unique symbol\n\ntype Definition = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\twire?: { schema: ContractSchema }\n}\nexport type OperationPublicResult<D extends Definition> = D extends {\n\twire: { schema: infer Schema extends ContractSchema }\n}\n\t? ContractInput<Schema>\n\t: ContractOutput<D['result']>\n\n/** Only the selected input/public contracts are exposed, never handlers or other operations. */\nexport type SelectedOperation<\n\tOwner extends symbol,\n\tKey extends string,\n\tInput extends ContractSchema,\n\tPublic,\n> = Readonly<{\n\towner: Owner\n\tkey: Key\n\tkind: 'mutation' | 'query'\n\tinput: Input\n\tresult: ContractSchema\n\treadonly [selectedTypes]: { readonly input: ContractInput<Input>; readonly public: Public }\n}>\ntype Selection = Readonly<{\n\towner: symbol\n\tkey: string\n\tkind: 'mutation' | 'query'\n\tinput: ContractSchema\n\tresult: ContractSchema\n\treadonly [selectedTypes]: { readonly input: unknown; readonly public: unknown }\n}>\ntype InputOf<S extends Selection> = S[typeof selectedTypes]['input']\ntype PublicOf<S extends Selection> = S[typeof selectedTypes]['public']\n\nconst selections = new WeakSet<object>()\nconst executors = new WeakMap<\n\tobject,\n\t{\n\t\tselection: Selection\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Private heterogeneous storage erases public result types; selected identity checks recover the exact raw/public pair at invocation.\n\t\texecute: (input: never) => Promise<unknown>\n\t}\n>()\n\n/** Registry integrators must check membership before selecting their own definition. */\nexport function selectOperation<\n\tconst Owner extends symbol,\n\tconst Key extends string,\n\tconst D extends Definition,\n>(\n\towner: Owner,\n\tkind: 'mutation' | 'query',\n\tkey: Key,\n\tdefinition: D,\n): SelectedOperation<Owner, Key, D['input'], OperationPublicResult<D>> {\n\tif (\n\t\ttypeof owner !== 'symbol' ||\n\t\t!key ||\n\t\t(kind !== 'mutation' && kind !== 'query') ||\n\t\t!definition?.input ||\n\t\t!definition.result\n\t) {\n\t\tthrow Error('Invalid selected operation')\n\t}\n\t// SAFETY: private identity records this exact paired schema; its type-only slots are never read at runtime.\n\tconst selected = Object.freeze({\n\t\towner,\n\t\tkey,\n\t\tkind,\n\t\tinput: definition.input,\n\t\tresult: definition.wire?.schema ?? definition.result,\n\t}) as SelectedOperation<Owner, Key, D['input'], OperationPublicResult<D>>\n\tselections.add(selected)\n\treturn selected\n}\n\nexport type OperationExecutor<S extends Selection> = Readonly<{\n\towner: S['owner']\n\tkey: S['key']\n\treadonly [executorTypes]: S\n}>\n\n/** The host captures authority in an already authorized native Promise call. */\nexport function bindOperationExecutor<const S extends Selection>(\n\tselected: S,\n\tconfiguration: {\n\t\towner: NoInfer<S['owner']>\n\t\tkey: NoInfer<S['key']>\n\t\texecute: (raw: NoInfer<InputOf<S>>) => Promise<NoInfer<PublicOf<S>>>\n\t},\n): OperationExecutor<S> {\n\tif (\n\t\t!selections.has(selected) ||\n\t\tconfiguration.owner !== selected.owner ||\n\t\tconfiguration.key !== selected.key ||\n\t\ttypeof configuration.execute !== 'function'\n\t) {\n\t\tthrow Error('Executor does not own the selected operation')\n\t}\n\t// SAFETY: the private map restores the concrete selected raw/public pair only after identity checks.\n\tconst executor = Object.freeze({\n\t\towner: selected.owner,\n\t\tkey: selected.key,\n\t}) as OperationExecutor<S>\n\texecutors.set(executor, {\n\t\tselection: selected,\n\t\texecute: configuration.execute,\n\t})\n\treturn executor\n}\n\nexport const operationToolDialect = 'https://json-schema.org/draft/2020-12/schema' as const\ntype Json = null | boolean | number | string | readonly Json[] | { readonly [key: string]: Json }\nexport type OperationToolJsonSchema = Readonly<{ [keyword: string]: Json }>\nexport type OperationToolConverter<Input extends ContractSchema = ContractSchema> = Readonly<{\n\tdialect: typeof operationToolDialect\n\t/** Represent raw transport input. Unsupported IDs/transforms must throw, never be approximated. */\n\tconvert: (input: Input) => OperationToolJsonSchema\n}>\nexport type OperationToolDefinition<\n\tS extends Selection = Selection,\n\tErrors extends ErrorDefinitions = ErrorDefinitions,\n> = Readonly<{\n\toperation: S\n\texecutor: OperationExecutor<S>\n\tdescription: string\n\tconverter: OperationToolConverter<S['input']>\n\terrors?: Pick<ErrorContract<Errors>, 'decode'>\n}>\ntype ToolConstraint = Readonly<{\n\toperation: Selection\n\texecutor: OperationExecutor<Selection>\n\tdescription: string\n\tconverter: {\n\t\tdialect: typeof operationToolDialect\n\t\tconvert: (input: never) => OperationToolJsonSchema\n\t}\n\terrors?: Pick<ErrorContract<ErrorDefinitions>, 'decode'>\n}>\ntype Checked<T extends ToolConstraint> = T & OperationToolDefinition<T['operation']>\ntype FailureOf<T> = T extends { errors: Pick<ErrorContract<infer E>, 'decode'> }\n\t? DecodedFailure<E>\n\t: UnknownFailure\nexport type OperationToolOutcome<Public, Failure = UnknownFailure> =\n\t| Readonly<{ _tag: 'Success'; value: Public }>\n\t| Failure\nexport type OperationTool<T extends ToolConstraint> = Readonly<{\n\tname: string\n\tdescription: string\n\targs: OperationToolJsonSchema\n\tinvoke: (\n\t\traw: InputOf<T['operation']>,\n\t) => Promise<OperationToolOutcome<PublicOf<T['operation']>, FailureOf<T>>>\n}>\n\nexport function createOperationTools<const T extends Readonly<Record<string, ToolConstraint>>>(\n\tdefinitions: T & { [K in keyof T]: Checked<T[K]> },\n): Readonly<{ [K in keyof T]: OperationTool<T[K]> }>\nexport function createOperationTools<\n\tconst T extends readonly (ToolConstraint & { name: string })[],\n>(\n\tdefinitions: T & { [K in keyof T]: Checked<T[K]> },\n): Readonly<{ [D in T[number] as D['name']]: OperationTool<D> }>\nexport function createOperationTools(\n\tdefinitions:\n\t\t| Readonly<Record<string, ToolConstraint>>\n\t\t| readonly (ToolConstraint & { name: string })[],\n): Readonly<Record<string, OperationTool<ToolConstraint>>> {\n\tconst entries = Array.isArray(definitions)\n\t\t? definitions.map((definition) => [definition.name, definition] as const)\n\t\t: Object.entries(definitions)\n\tconst tools: Record<string, OperationTool<ToolConstraint>> = Object.create(null)\n\tfor (const [name, definition] of entries) {\n\t\tif (!name || Object.hasOwn(tools, name)) throw Error('Duplicate or empty operation tool name')\n\t\tconst paired = definition.executor && executors.get(definition.executor)\n\t\tif (\n\t\t\t!selections.has(definition.operation) ||\n\t\t\t!paired ||\n\t\t\tpaired.selection !== definition.operation\n\t\t)\n\t\t\tthrow Error('Tool requires its selected operation executor')\n\t\tif (\n\t\t\t!definition.description ||\n\t\t\tdefinition.converter?.dialect !== operationToolDialect ||\n\t\t\ttypeof definition.converter.convert !== 'function'\n\t\t)\n\t\t\tthrow Error('Unsupported operation tool converter')\n\t\t// Conversion never executes the input decoder, and invocation never executes conversion.\n\t\t// SAFETY: the checked tool overload pairs the converter with this selected input schema; the never cast bridges heterogeneous iteration without changing the schema.\n\t\tconst args = schemaSnapshot(definition.converter.convert(definition.operation.input as never))\n\t\tconst errors = definition.errors\n\t\ttools[name] = Object.freeze({\n\t\t\tname,\n\t\t\tdescription: definition.description,\n\t\t\targs,\n\t\t\tasync invoke(raw: unknown) {\n\t\t\t\ttry {\n\t\t\t\t\t// SAFETY: binding owns this raw/public pair and its native boundary performs decoding/policy/projection.\n\t\t\t\t\treturn { _tag: 'Success' as const, value: await paired.execute(raw as never) }\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// This catch runs only after the native call rejects. Native mutations retain rollback semantics.\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (error instanceof ConvexError && errors) return errors.decode(error.data)\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t/* Invalid host error decoders cannot publish diagnostics. */\n\t\t\t\t\t}\n\t\t\t\t\treturn { _tag: 'UnknownFailure' as const, version: 1 as const }\n\t\t\t\t}\n\t\t\t},\n\t\t})\n\t}\n\treturn Object.freeze(tools)\n}\n\nconst schemaKeywords = new Set([\n\t'properties',\n\t'$defs',\n\t'items',\n\t'additionalProperties',\n\t'anyOf',\n\t'oneOf',\n\t'allOf',\n\t'not',\n\t'required',\n\t'enum',\n\t'const',\n\t'default',\n\t'examples',\n])\nconst types = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'])\nconst textKeywords = new Set([\n\t'title',\n\t'description',\n\t'format',\n\t'pattern',\n\t'$ref',\n\t'$id',\n\t'x-convex-table',\n])\nconst countKeywords = new Set([\n\t'minLength',\n\t'maxLength',\n\t'minItems',\n\t'maxItems',\n\t'minProperties',\n\t'maxProperties',\n])\nconst numberKeywords = new Set([\n\t'minimum',\n\t'maximum',\n\t'exclusiveMinimum',\n\t'exclusiveMaximum',\n\t'multipleOf',\n])\nconst scalarKeywords = new Set([\n\t...textKeywords,\n\t...countKeywords,\n\t...numberKeywords,\n\t'type',\n\t'uniqueItems',\n\t'$schema',\n])\n\nfunction schemaSnapshot(value: OperationToolJsonSchema): OperationToolJsonSchema {\n\tconst seen = new Set<object>()\n\tfunction copy(value: Json): Json {\n\t\tif (value === null || typeof value === 'string' || typeof value === 'boolean') return value\n\t\tif (typeof value === 'number' && Number.isFinite(value)) return value\n\t\tif (typeof value !== 'object' || seen.has(value))\n\t\t\tthrow Error('Converter schema must be JSON safe')\n\t\tseen.add(value)\n\t\ttry {\n\t\t\tif (Array.isArray(value)) return Object.freeze(value.map(copy))\n\t\t\tif (!isRecord(value)) throw Error('Converter schema must be a plain JSON object')\n\t\t\treturn Object.freeze(\n\t\t\t\tObject.fromEntries(Object.entries(value).map(([key, item]) => [key, copy(item)])),\n\t\t\t)\n\t\t} finally {\n\t\t\tseen.delete(value)\n\t\t}\n\t}\n\tfunction check(schema: Json): void {\n\t\tif (typeof schema === 'boolean') return\n\t\tif (!isRecord(schema)) throw Error('Unsupported JSON Schema shape')\n\t\tfor (const [key, child] of Object.entries(schema)) {\n\t\t\tif (!scalarKeywords.has(key) && !schemaKeywords.has(key))\n\t\t\t\tthrow Error('Unsupported JSON Schema keyword')\n\t\t\tif (textKeywords.has(key) && typeof child !== 'string')\n\t\t\t\tthrow Error('Invalid JSON Schema text keyword')\n\t\t\tif (\n\t\t\t\tcountKeywords.has(key) &&\n\t\t\t\t(typeof child !== 'number' || !Number.isInteger(child) || child < 0)\n\t\t\t)\n\t\t\t\tthrow Error('Invalid JSON Schema count keyword')\n\t\t\tif (\n\t\t\t\tnumberKeywords.has(key) &&\n\t\t\t\t(typeof child !== 'number' ||\n\t\t\t\t\t!Number.isFinite(child) ||\n\t\t\t\t\t(key === 'multipleOf' && child <= 0))\n\t\t\t)\n\t\t\t\tthrow Error('Invalid JSON Schema number keyword')\n\t\t\tif (key === 'uniqueItems' && typeof child !== 'boolean')\n\t\t\t\tthrow Error('Invalid JSON Schema boolean keyword')\n\t\t\tif (key === 'pattern') {\n\t\t\t\ttry {\n\t\t\t\t\t// SAFETY: pattern belongs to textKeywords and passed the string check above; this validates syntax without matching input.\n\t\t\t\t\tnew RegExp(child as string)\n\t\t\t\t} catch {\n\t\t\t\t\tthrow Error('Invalid JSON Schema pattern')\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((key === 'enum' || key === 'examples') && !Array.isArray(child))\n\t\t\t\tthrow Error('Invalid JSON Schema array keyword')\n\t\t\tif (key === 'enum' && Array.isArray(child) && !child.length)\n\t\t\t\tthrow Error('Invalid JSON Schema enum')\n\t\t\tif (key === '$schema' && child !== operationToolDialect)\n\t\t\t\tthrow Error('Unsupported JSON Schema dialect')\n\t\t\tif (\n\t\t\t\tkey === 'type' &&\n\t\t\t\t!(typeof child === 'string' && types.has(child)) &&\n\t\t\t\t!(\n\t\t\t\t\tArray.isArray(child) &&\n\t\t\t\t\tchild.length > 0 &&\n\t\t\t\t\tchild.every((type) => typeof type === 'string' && types.has(type))\n\t\t\t\t)\n\t\t\t)\n\t\t\t\tthrow Error('Unsupported JSON Schema type')\n\t\t\tif (key === 'properties' || key === '$defs') {\n\t\t\t\tif (!isRecord(child)) throw Error('Unsupported JSON Schema properties')\n\t\t\t\tObject.values(child).forEach(check)\n\t\t\t} else if (key === 'items' || key === 'not' || key === 'additionalProperties') check(child)\n\t\t\telse if (key === 'anyOf' || key === 'oneOf' || key === 'allOf') {\n\t\t\t\tif (!Array.isArray(child) || !child.length)\n\t\t\t\t\tthrow Error('Unsupported JSON Schema alternatives')\n\t\t\t\tchild.forEach(check)\n\t\t\t} else if (\n\t\t\t\tkey === 'required' &&\n\t\t\t\t(!Array.isArray(child) ||\n\t\t\t\t\tchild.some((field) => typeof field !== 'string') ||\n\t\t\t\t\tnew Set(child).size !== child.length)\n\t\t\t)\n\t\t\t\tthrow Error('Unsupported JSON Schema required fields')\n\t\t}\n\t}\n\tconst snapshot = copy(value)\n\tif (!isRecord(snapshot) || snapshot.type !== 'object')\n\t\tthrow Error('Operation tool arguments require an object JSON Schema')\n\tcheck(snapshot)\n\treturn snapshot\n}\nfunction isRecord(value: Json): value is { readonly [key: string]: Json } {\n\tif (value === null || typeof value !== 'object' || Array.isArray(value)) return false\n\tconst prototype = Object.getPrototypeOf(value)\n\treturn prototype === Object.prototype || prototype === null\n}\n"],"mappings":"A,4CA4CA,MAAMA,kBAAa,IAAI,QACjBC,kBAAY,IAAI,QAUtB,SAAgBC,EAKf,EACA,EACA,EACA,EACsE,CACtE,GACC,OAAOC,GAAU,UACjB,CAACC,GACAC,IAAS,YAAcA,IAAS,SACjC,CAACC,GAAY,OACb,CAACA,EAAW,OAEZ,MAAM,MAAM,4BAA4B,EAGzC,IAAMC,EAAW,OAAO,OAAO,CAC9B,QACA,MACA,OACA,MAAOD,EAAW,MAClB,OAAQA,EAAW,MAAM,QAAUA,EAAW,MAC/C,CAAC,EAED,OADAN,EAAW,IAAIO,CAAQ,EAChBA,CACR,CASA,SAAgBC,EACf,EACA,EAKuB,CACvB,GACC,CAACR,EAAW,IAAIO,CAAQ,GACxBE,EAAc,QAAUF,EAAS,OACjCE,EAAc,MAAQF,EAAS,KAC/B,OAAOE,EAAc,SAAY,WAEjC,MAAM,MAAM,8CAA8C,EAG3D,IAAMC,EAAW,OAAO,OAAO,CAC9B,MAAOH,EAAS,MAChB,IAAKA,EAAS,GACf,CAAC,EAKD,OAJAN,EAAU,IAAIS,EAAU,CACvB,UAAWH,EACX,QAASE,EAAc,OACxB,CAAC,EACMC,CACR,CAEA,MAAaC,EAAuB,+CAoDpC,SAAgBC,EACf,EAG0D,CAC1D,IAAMC,EAAU,MAAM,QAAQC,CAAW,EACtCA,EAAY,IAAK,GAAe,CAACR,EAAW,KAAMA,CAAU,CAAU,EACtE,OAAO,QAAQQ,CAAW,EACvBC,EAAuD,OAAO,OAAO,IAAI,EAC/E,IAAK,GAAM,CAACC,EAAMV,KAAeO,EAAS,CACzC,GAAI,CAACG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AAM,KAAM,GAAU,OAAOE,GAAU,QAAQ,GAC/C,IAAI,IAAIF,CAAK,CAAC,CAAC,OAASA,EAAM,QAE/B,MAAM,MAAM,yCAAyC,CACvD,CA3DkE,CA4DnE,CACA,IAAMG,EAAWT,EAAKC,CAAK,EAC3B,GAAI,CAACC,EAASO,CAAQ,GAAKA,EAAS,OAAS,SAC5C,MAAM,MAAM,wDAAwD,EAErE,OADAL,EAAMK,CAAQ,EACPA,CACR,CACA,SAASP,EAAS,EAAwD,CACzE,GAAsB,OAAOD,GAAU,WAAnCA,GAA+C,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMS,EAAY,OAAO,eAAeT,CAAK,EAC7C,OAAOS,IAAc,OAAO,WAAaA,IAAc,IACxD,C"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { ContractInput, ContractOutput, NeutralSchema } from "./contract.mjs";
|
|
2
|
+
export type IdempotencyErrorCode = 'unsupported-binding' | 'invalid-input' | 'corrupt' | 'ambiguous' | 'pending' | 'stale' | 'conflict';
|
|
3
|
+
export declare class IdempotencyError extends Error {
|
|
4
|
+
readonly code: IdempotencyErrorCode;
|
|
5
|
+
readonly _tag = "IdempotencyError";
|
|
6
|
+
constructor(code: IdempotencyErrorCode, message: string);
|
|
7
|
+
}
|
|
8
|
+
export interface IdempotencyIdentity {
|
|
9
|
+
readonly operation: string;
|
|
10
|
+
/** Stable trusted tenant/principal or delegated-capability scope, supplied by the host. */
|
|
11
|
+
readonly scope: string;
|
|
12
|
+
readonly key: string;
|
|
13
|
+
}
|
|
14
|
+
export interface IdempotencyVersions {
|
|
15
|
+
readonly operation: string;
|
|
16
|
+
readonly contract: string;
|
|
17
|
+
readonly binding: string;
|
|
18
|
+
readonly fingerprintPolicy: string;
|
|
19
|
+
}
|
|
20
|
+
export interface IdempotencyReceipt {
|
|
21
|
+
readonly versions: IdempotencyVersions;
|
|
22
|
+
readonly fingerprint: string;
|
|
23
|
+
readonly state: 'pending' | 'completed';
|
|
24
|
+
readonly result?: unknown;
|
|
25
|
+
}
|
|
26
|
+
export interface CanonicalConvexBounds {
|
|
27
|
+
readonly maxDepth: number;
|
|
28
|
+
readonly maxNodes: number;
|
|
29
|
+
readonly maxBytes: number;
|
|
30
|
+
readonly maxArrayLength: number;
|
|
31
|
+
readonly maxObjectFields: number;
|
|
32
|
+
}
|
|
33
|
+
/** Bounded transport encoding, using the pinned Convex integer/binary/float representation. */
|
|
34
|
+
export declare function canonicalConvexBytes(value: unknown, bounds: CanonicalConvexBounds): string;
|
|
35
|
+
declare const invocationBytes: unique symbol;
|
|
36
|
+
export interface IdempotencyInvocation {
|
|
37
|
+
readonly identity: IdempotencyIdentity;
|
|
38
|
+
readonly versions: IdempotencyVersions;
|
|
39
|
+
readonly [invocationBytes]: string;
|
|
40
|
+
}
|
|
41
|
+
export interface IdempotencyCapture {
|
|
42
|
+
readonly binding: {
|
|
43
|
+
readonly kind: 'mutation';
|
|
44
|
+
readonly atomicity: 'same-mutation';
|
|
45
|
+
};
|
|
46
|
+
readonly identity: IdempotencyIdentity;
|
|
47
|
+
readonly versions: IdempotencyVersions;
|
|
48
|
+
readonly rawInput: unknown;
|
|
49
|
+
readonly canonical: {
|
|
50
|
+
readonly bounds: CanonicalConvexBounds;
|
|
51
|
+
/** Explicit deterministic equivalence; the host versions this policy in fingerprintPolicy. */
|
|
52
|
+
readonly normalize?: (raw: unknown) => unknown;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Call at the trusted native handler before domain decoding, once per invocation (including nested calls). */
|
|
56
|
+
export declare function captureIdempotencyInvocation(capture: IdempotencyCapture): IdempotencyInvocation;
|
|
57
|
+
/** Shared protocol checks have no Effect dependency and never decode final wire data. */
|
|
58
|
+
export declare function retainedIdempotencyReceipt(rows: readonly unknown[], invocation: IdempotencyInvocation): IdempotencyReceipt | undefined;
|
|
59
|
+
export declare function idempotencyCanonicalInput(invocation: IdempotencyInvocation): string;
|
|
60
|
+
export declare function idempotencyFingerprint(value: string, receipt?: IdempotencyReceipt): string;
|
|
61
|
+
export type IdempotencyPreparation<Result> = {
|
|
62
|
+
readonly kind: 'replay';
|
|
63
|
+
readonly result: unknown;
|
|
64
|
+
} | {
|
|
65
|
+
readonly kind: 'execute';
|
|
66
|
+
readonly complete: (result: Result) => Promise<void>;
|
|
67
|
+
};
|
|
68
|
+
type NeutralValue<A> = A | PromiseLike<A>;
|
|
69
|
+
/** Host callbacks close over the same secured mutation writer; native OCC/rollback remains host-owned. */
|
|
70
|
+
export declare function transactionalIdempotency<const Replay extends NeutralSchema, Claim>(configuration: {
|
|
71
|
+
readonly final: {
|
|
72
|
+
readonly replayResult: Replay;
|
|
73
|
+
readonly encode: (result: ContractOutput<Replay>) => NeutralValue<ContractInput<Replay>>;
|
|
74
|
+
};
|
|
75
|
+
readonly authorize: (invocation: IdempotencyInvocation) => NeutralValue<void>;
|
|
76
|
+
readonly lookup: (identity: IdempotencyIdentity) => NeutralValue<readonly unknown[]>;
|
|
77
|
+
readonly fingerprint: (canonicalBytes: string) => NeutralValue<string>;
|
|
78
|
+
readonly claim: (identity: IdempotencyIdentity, receipt: IdempotencyReceipt) => NeutralValue<Claim>;
|
|
79
|
+
readonly complete: (claim: Claim, receipt: IdempotencyReceipt) => NeutralValue<void>;
|
|
80
|
+
}): {
|
|
81
|
+
replayResult: Replay;
|
|
82
|
+
prepare(invocation: IdempotencyInvocation): Promise<IdempotencyPreparation<ContractOutput<Replay>>>;
|
|
83
|
+
};
|
|
84
|
+
export {};
|
|
85
|
+
//# sourceMappingURL=idempotency.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{convexToJson as e}from"convex/values";var t=class extends Error{code;_tag=`IdempotencyError`;constructor(e,t){super(t),this.code=e,this.name=`IdempotencyError`}};const n=new TextEncoder;function r(t,r){for(let e of[r.maxDepth,r.maxNodes,r.maxBytes,r.maxArrayLength,r.maxObjectFields])(!Number.isSafeInteger(e)||e<1)&&d(`Canonical bounds must be positive safe integers`);let i=/* @__PURE__ */ new Set,a=0,o=0;function s(e){o+=e,o>r.maxBytes&&d(`Canonical input exceeds byte bound`)}function c(e){return e.length>r.maxBytes&&d(`Canonical input exceeds byte bound`),n.encode(e).length}function l(e,t){if((++a>r.maxNodes||t>r.maxDepth)&&d(`Canonical input exceeds traversal bound`),e===null||typeof e==`boolean`)s(1);else if(typeof e==`number`)s(9);else if(typeof e==`bigint`)(e<-(1n<<63n)||e>(1n<<63n)-1n)&&d(`Convex integer exceeds signed int64`),s(9);else if(typeof e==`string`)s(2+c(e));else if(e instanceof ArrayBuffer)s(2+e.byteLength);else{typeof e!=`object`&&d(`Unsupported canonical Convex value`),i.has(e)&&d(`Cyclic canonical input`),i.add(e);try{if(Array.isArray(e)){e.length>r.maxArrayLength&&d(`Canonical array exceeds length bound`),s(2);for(let n of e)l(n,t+1);return}let n=Object.getPrototypeOf(e);n!==Object.prototype&&n!==null&&d(`Canonical input requires plain objects`),Object.getOwnPropertySymbols(e).length&&d(`Unsupported canonical symbol keys`);let i=Object.keys(e);i.length>r.maxObjectFields&&d(`Canonical object exceeds field bound`),s(2);for(let n of i){(n.length>1024||n.startsWith(`$`)||/[^\x20-\x7e]/.test(n))&&d(`Invalid Convex object key`);let r=Object.getOwnPropertyDescriptor(e,n);`value`in r||d(`Canonical input cannot contain accessors`),r.value!==void 0&&(s(c(n)+1),l(r.value,t+1))}}finally{i.delete(e)}}}l(t,0);function u(t){if(Array.isArray(t))return t.map(u);if(typeof t==`object`&&t&&!(t instanceof ArrayBuffer)){let e=Object.create(null);for(let n of Object.keys(t).sort()){let r=t[n];r!==void 0&&(e[n]=u(r))}return e}return e(t)}let f=JSON.stringify(u(t));return n.encode(f).length>r.maxBytes&&d(`Canonical encoding exceeds byte bound`),f}const i=[`operation`,`contract`,`binding`,`fingerprintPolicy`],a=Symbol(`idempotency invocation bytes`);function o(e){if(e.binding.kind!==`mutation`||e.binding.atomicity!==`same-mutation`)throw new t(`unsupported-binding`,`Idempotency requires the current native mutation transaction`);let n=Object.freeze({operation:e.identity.operation,scope:e.identity.scope,key:e.identity.key}),i=Object.freeze({operation:e.versions.operation,contract:e.versions.contract,binding:e.versions.binding,fingerprintPolicy:e.versions.fingerprintPolicy});f(n)&&p(i)||d(`Invalid trusted idempotency metadata`);let o=r(e.canonical.normalize?e.canonical.normalize(e.rawInput):e.rawInput,e.canonical.bounds);return Object.freeze({identity:n,versions:i,[a]:o})}function s(e,n){if(!Array.isArray(e))throw new t(`corrupt`,`Receipt lookup must return rows`);if(e.length>1)throw new t(`ambiguous`,`Multiple receipts match the stable identity`);if(e.length===0)return;let r=e[0];if(typeof r!=`object`||!r||!Object.hasOwn(r,`versions`)||!Object.hasOwn(r,`fingerprint`)||!Object.hasOwn(r,`state`))throw new t(`corrupt`,`Malformed retained receipt`);let a=r;if(!p(a.versions)||typeof a.fingerprint!=`string`||![`pending`,`completed`].includes(a.state)||a.state===`completed`&&!Object.hasOwn(a,`result`))throw new t(`corrupt`,`Malformed retained receipt`);if(i.some(e=>a.versions[e]!==n.versions[e]))throw new t(`stale`,`Retained receipt version differs from the current operation`);if(a.state===`pending`)throw new t(`pending`,`Retained receipt is incomplete`);return a}function c(e){if(!Object.hasOwn(e,a))throw new t(`unsupported-binding`,`Missing trusted invocation capture`);return e[a]}function l(e,n){if(typeof e!=`string`||e.length===0)throw new t(`invalid-input`,`Fingerprint policy must return a nonempty string`);if(n&&n.fingerprint!==e)throw new t(`conflict`,`Caller key was already used with different input`);return e}function u(e){return{replayResult:e.final.replayResult,async prepare(t){let n=c(t);await e.authorize(t);let r=s(await e.lookup(t.identity),t),i=l(await e.fingerprint(n),r);if(r)return{kind:`replay`,result:r.result};let a=await e.claim(t.identity,{state:`pending`,versions:t.versions,fingerprint:i});return{kind:`execute`,complete:async n=>{let r=await e.final.encode(n);await e.complete(a,{state:`completed`,versions:t.versions,fingerprint:i,result:r})}}}}}function d(e){throw new t(`invalid-input`,e)}function f(e){return[e.operation,e.scope,e.key].every(e=>typeof e==`string`&&e.length>0)}function p(e){if(typeof e!=`object`||!e)return!1;let t=e;return i.every(e=>{let n=t[e];return Object.hasOwn(t,e)&&typeof n==`string`&&n.length>0})}export{t as IdempotencyError,r as canonicalConvexBytes,o as captureIdempotencyInvocation,c as idempotencyCanonicalInput,l as idempotencyFingerprint,s as retainedIdempotencyReceipt,u as transactionalIdempotency};
|
|
2
|
+
//# sourceMappingURL=idempotency.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"idempotency.mjs","names":["IdempotencyError","message","code","encoder","canonicalConvexBytes","bound","bounds","invalid","ancestors","nodes","bytes","spend","amount","textBytes","text","visit","depth","current","item","prototype","keys","key","descriptor","value","project","output","convexToJson","encoded","versionFields","invocationBytes","captureIdempotencyInvocation","capture","identity","versions","validIdentity","validVersions","retainedIdempotencyReceipt","rows","receipt","candidate","invocation","idempotencyCanonicalInput","idempotencyFingerprint","transactionalIdempotency","configuration","canonical","retained","fingerprint","claim","wire","result","field"],"sources":["../../../src/modules/contracts/idempotency.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-parameters, anti-slop/no-runtime-typeof -- Canonical transport and retained receipts are explicit untrusted value boundaries. */\nimport { convexToJson, type Value, type JSONValue } from 'convex/values'\nimport type { ContractInput, ContractOutput, NeutralSchema } from './contract'\n\nexport type IdempotencyErrorCode =\n\t| 'unsupported-binding'\n\t| 'invalid-input'\n\t| 'corrupt'\n\t| 'ambiguous'\n\t| 'pending'\n\t| 'stale'\n\t| 'conflict'\nexport class IdempotencyError extends Error {\n\treadonly _tag = 'IdempotencyError'\n\tconstructor(\n\t\treadonly code: IdempotencyErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'IdempotencyError'\n\t}\n}\nexport interface IdempotencyIdentity {\n\treadonly operation: string\n\t/** Stable trusted tenant/principal or delegated-capability scope, supplied by the host. */\n\treadonly scope: string\n\treadonly key: string\n}\nexport interface IdempotencyVersions {\n\treadonly operation: string\n\treadonly contract: string\n\treadonly binding: string\n\treadonly fingerprintPolicy: string\n}\nexport interface IdempotencyReceipt {\n\treadonly versions: IdempotencyVersions\n\treadonly fingerprint: string\n\treadonly state: 'pending' | 'completed'\n\treadonly result?: unknown\n}\nexport interface CanonicalConvexBounds {\n\treadonly maxDepth: number\n\treadonly maxNodes: number\n\treadonly maxBytes: number\n\treadonly maxArrayLength: number\n\treadonly maxObjectFields: number\n}\n\nconst encoder = new TextEncoder()\n/** Bounded transport encoding, using the pinned Convex integer/binary/float representation. */\nexport function canonicalConvexBytes(value: unknown, bounds: CanonicalConvexBounds): string {\n\tfor (const bound of [\n\t\tbounds.maxDepth,\n\t\tbounds.maxNodes,\n\t\tbounds.maxBytes,\n\t\tbounds.maxArrayLength,\n\t\tbounds.maxObjectFields,\n\t])\n\t\tif (!Number.isSafeInteger(bound) || bound < 1)\n\t\t\tinvalid('Canonical bounds must be positive safe integers')\n\tconst ancestors = new Set<object>()\n\tlet nodes = 0\n\tlet bytes = 0\n\tfunction spend(amount: number) {\n\t\tbytes += amount\n\t\tif (bytes > bounds.maxBytes) invalid('Canonical input exceeds byte bound')\n\t}\n\tfunction textBytes(text: string) {\n\t\tif (text.length > bounds.maxBytes) invalid('Canonical input exceeds byte bound')\n\t\treturn encoder.encode(text).length\n\t}\n\tfunction visit(current: unknown, depth: number): void {\n\t\tif (++nodes > bounds.maxNodes || depth > bounds.maxDepth)\n\t\t\tinvalid('Canonical input exceeds traversal bound')\n\t\tif (current === null || typeof current === 'boolean') {\n\t\t\tspend(1)\n\t\t\treturn\n\t\t}\n\t\tif (typeof current === 'number') {\n\t\t\tspend(9)\n\t\t\treturn\n\t\t}\n\t\tif (typeof current === 'bigint') {\n\t\t\tif (current < -(1n << 63n) || current > (1n << 63n) - 1n)\n\t\t\t\tinvalid('Convex integer exceeds signed int64')\n\t\t\tspend(9)\n\t\t\treturn\n\t\t}\n\t\tif (typeof current === 'string') {\n\t\t\tspend(2 + textBytes(current))\n\t\t\treturn\n\t\t}\n\t\tif (current instanceof ArrayBuffer) {\n\t\t\tspend(2 + current.byteLength)\n\t\t\treturn\n\t\t}\n\t\tif (typeof current !== 'object') invalid('Unsupported canonical Convex value')\n\t\tif (ancestors.has(current)) invalid('Cyclic canonical input')\n\t\tancestors.add(current)\n\t\ttry {\n\t\t\tif (Array.isArray(current)) {\n\t\t\t\tif (current.length > bounds.maxArrayLength) invalid('Canonical array exceeds length bound')\n\t\t\t\tspend(2)\n\t\t\t\tfor (const item of current) visit(item, depth + 1)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst prototype = Object.getPrototypeOf(current)\n\t\t\tif (prototype !== Object.prototype && prototype !== null)\n\t\t\t\tinvalid('Canonical input requires plain objects')\n\t\t\tif (Object.getOwnPropertySymbols(current).length) invalid('Unsupported canonical symbol keys')\n\t\t\tconst keys = Object.keys(current)\n\t\t\tif (keys.length > bounds.maxObjectFields) invalid('Canonical object exceeds field bound')\n\t\t\tspend(2)\n\t\t\tfor (const key of keys) {\n\t\t\t\tif (key.length > 1024 || key.startsWith('$') || /[^\\x20-\\x7e]/.test(key))\n\t\t\t\t\tinvalid('Invalid Convex object key')\n\t\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(current, key)!\n\t\t\t\tif (!('value' in descriptor)) invalid('Canonical input cannot contain accessors')\n\t\t\t\tif (descriptor.value === undefined) continue\n\t\t\t\tspend(textBytes(key) + 1)\n\t\t\t\tvisit(descriptor.value, depth + 1)\n\t\t\t}\n\t\t} finally {\n\t\t\tancestors.delete(current)\n\t\t}\n\t}\n\tvisit(value, 0)\n\t// Object projection retains own __proto__ keys which the SDK's assignment-based object converter drops.\n\t// Scalars still use the pinned SDK's exact integer/binary/float representation.\n\tfunction project(current: Value): JSONValue {\n\t\tif (Array.isArray(current)) return current.map(project)\n\t\tif (current !== null && typeof current === 'object' && !(current instanceof ArrayBuffer)) {\n\t\t\tconst output: Record<string, JSONValue> = Object.create(null)\n\t\t\tfor (const key of Object.keys(current).sort()) {\n\t\t\t\t// SAFETY: prior bounded traversal excluded every object type except plain Convex dictionaries.\n\t\t\t\tconst item = (current as Record<string, Value | undefined>)[key]\n\t\t\t\tif (item !== undefined) output[key] = project(item)\n\t\t\t}\n\t\t\treturn output\n\t\t}\n\t\treturn convexToJson(current)\n\t}\n\t// SAFETY: the traversal validates the bounded supported Convex value subset before SDK conversion.\n\tconst encoded = JSON.stringify(project(value as Value))\n\tif (encoder.encode(encoded).length > bounds.maxBytes)\n\t\tinvalid('Canonical encoding exceeds byte bound')\n\treturn encoded\n}\n\nconst versionFields = ['operation', 'contract', 'binding', 'fingerprintPolicy'] as const\nconst invocationBytes: unique symbol = Symbol('idempotency invocation bytes')\nexport interface IdempotencyInvocation {\n\treadonly identity: IdempotencyIdentity\n\treadonly versions: IdempotencyVersions\n\treadonly [invocationBytes]: string\n}\nexport interface IdempotencyCapture {\n\treadonly binding: { readonly kind: 'mutation'; readonly atomicity: 'same-mutation' }\n\treadonly identity: IdempotencyIdentity\n\treadonly versions: IdempotencyVersions\n\treadonly rawInput: unknown\n\treadonly canonical: {\n\t\treadonly bounds: CanonicalConvexBounds\n\t\t/** Explicit deterministic equivalence; the host versions this policy in fingerprintPolicy. */\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- The explicit normalized transport policy is validated by canonicalConvexBytes before capture.\n\t\treadonly normalize?: (raw: unknown) => unknown\n\t}\n}\n/** Call at the trusted native handler before domain decoding, once per invocation (including nested calls). */\nexport function captureIdempotencyInvocation(capture: IdempotencyCapture): IdempotencyInvocation {\n\tif (capture.binding.kind !== 'mutation' || capture.binding.atomicity !== 'same-mutation')\n\t\tthrow new IdempotencyError(\n\t\t\t'unsupported-binding',\n\t\t\t'Idempotency requires the current native mutation transaction',\n\t\t)\n\tconst identity = Object.freeze({\n\t\toperation: capture.identity.operation,\n\t\tscope: capture.identity.scope,\n\t\tkey: capture.identity.key,\n\t})\n\tconst versions = Object.freeze({\n\t\toperation: capture.versions.operation,\n\t\tcontract: capture.versions.contract,\n\t\tbinding: capture.versions.binding,\n\t\tfingerprintPolicy: capture.versions.fingerprintPolicy,\n\t})\n\tif (!validIdentity(identity) || !validVersions(versions))\n\t\tinvalid('Invalid trusted idempotency metadata')\n\tconst bytes = canonicalConvexBytes(\n\t\tcapture.canonical.normalize ? capture.canonical.normalize(capture.rawInput) : capture.rawInput,\n\t\tcapture.canonical.bounds,\n\t)\n\treturn Object.freeze({ identity, versions, [invocationBytes]: bytes })\n}\n/** Shared protocol checks have no Effect dependency and never decode final wire data. */\nexport function retainedIdempotencyReceipt(\n\trows: readonly unknown[],\n\tinvocation: IdempotencyInvocation,\n): IdempotencyReceipt | undefined {\n\tif (!Array.isArray(rows)) throw new IdempotencyError('corrupt', 'Receipt lookup must return rows')\n\tif (rows.length > 1)\n\t\tthrow new IdempotencyError('ambiguous', 'Multiple receipts match the stable identity')\n\tif (rows.length === 0) return undefined\n\tconst receipt = rows[0]\n\tif (\n\t\ttypeof receipt !== 'object' ||\n\t\treceipt === null ||\n\t\t!Object.hasOwn(receipt, 'versions') ||\n\t\t!Object.hasOwn(receipt, 'fingerprint') ||\n\t\t!Object.hasOwn(receipt, 'state')\n\t)\n\t\tthrow new IdempotencyError('corrupt', 'Malformed retained receipt')\n\t// SAFETY: this temporary retained-row view is fully checked below before returning or using metadata.\n\tconst candidate = receipt as IdempotencyReceipt\n\tif (\n\t\t!validVersions(candidate.versions) ||\n\t\ttypeof candidate.fingerprint !== 'string' ||\n\t\t!['pending', 'completed'].includes(candidate.state) ||\n\t\t(candidate.state === 'completed' && !Object.hasOwn(candidate, 'result'))\n\t)\n\t\tthrow new IdempotencyError('corrupt', 'Malformed retained receipt')\n\tif (versionFields.some((key) => candidate.versions[key] !== invocation.versions[key]))\n\t\tthrow new IdempotencyError(\n\t\t\t'stale',\n\t\t\t'Retained receipt version differs from the current operation',\n\t\t)\n\tif (candidate.state === 'pending')\n\t\tthrow new IdempotencyError('pending', 'Retained receipt is incomplete')\n\treturn candidate\n}\nexport function idempotencyCanonicalInput(invocation: IdempotencyInvocation): string {\n\tif (!Object.hasOwn(invocation, invocationBytes))\n\t\tthrow new IdempotencyError('unsupported-binding', 'Missing trusted invocation capture')\n\treturn invocation[invocationBytes]\n}\nexport function idempotencyFingerprint(value: string, receipt?: IdempotencyReceipt): string {\n\tif (typeof value !== 'string' || value.length === 0)\n\t\tthrow new IdempotencyError('invalid-input', 'Fingerprint policy must return a nonempty string')\n\tif (receipt && receipt.fingerprint !== value)\n\t\tthrow new IdempotencyError('conflict', 'Caller key was already used with different input')\n\treturn value\n}\nexport type IdempotencyPreparation<Result> =\n\t| { readonly kind: 'replay'; readonly result: unknown }\n\t| { readonly kind: 'execute'; readonly complete: (result: Result) => Promise<void> }\ntype NeutralValue<A> = A | PromiseLike<A>\n/** Host callbacks close over the same secured mutation writer; native OCC/rollback remains host-owned. */\nexport function transactionalIdempotency<const Replay extends NeutralSchema, Claim>(configuration: {\n\treadonly final: {\n\t\treadonly replayResult: Replay\n\t\treadonly encode: (result: ContractOutput<Replay>) => NeutralValue<ContractInput<Replay>>\n\t}\n\treadonly authorize: (invocation: IdempotencyInvocation) => NeutralValue<void>\n\treadonly lookup: (identity: IdempotencyIdentity) => NeutralValue<readonly unknown[]>\n\treadonly fingerprint: (canonicalBytes: string) => NeutralValue<string>\n\treadonly claim: (\n\t\tidentity: IdempotencyIdentity,\n\t\treceipt: IdempotencyReceipt,\n\t) => NeutralValue<Claim>\n\treadonly complete: (claim: Claim, receipt: IdempotencyReceipt) => NeutralValue<void>\n}) {\n\treturn {\n\t\treplayResult: configuration.final.replayResult,\n\t\tasync prepare(\n\t\t\tinvocation: IdempotencyInvocation,\n\t\t): Promise<IdempotencyPreparation<ContractOutput<Replay>>> {\n\t\t\tconst canonical = idempotencyCanonicalInput(invocation)\n\t\t\tawait configuration.authorize(invocation)\n\t\t\tconst retained = retainedIdempotencyReceipt(\n\t\t\t\tawait configuration.lookup(invocation.identity),\n\t\t\t\tinvocation,\n\t\t\t)\n\t\t\tconst fingerprint = idempotencyFingerprint(\n\t\t\t\tawait configuration.fingerprint(canonical),\n\t\t\t\tretained,\n\t\t\t)\n\t\t\tif (retained) return { kind: 'replay', result: retained.result }\n\t\t\tconst claim = await configuration.claim(invocation.identity, {\n\t\t\t\tstate: 'pending',\n\t\t\t\tversions: invocation.versions,\n\t\t\t\tfingerprint,\n\t\t\t})\n\t\t\treturn {\n\t\t\t\tkind: 'execute',\n\t\t\t\tcomplete: async (result) => {\n\t\t\t\t\tconst wire = await configuration.final.encode(result)\n\t\t\t\t\tawait configuration.complete(claim, {\n\t\t\t\t\t\tstate: 'completed',\n\t\t\t\t\t\tversions: invocation.versions,\n\t\t\t\t\t\tfingerprint,\n\t\t\t\t\t\tresult: wire,\n\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunction invalid(message: string): never {\n\tthrow new IdempotencyError('invalid-input', message)\n}\nfunction validIdentity(value: IdempotencyIdentity): boolean {\n\treturn [value.operation, value.scope, value.key].every(\n\t\t(field) => typeof field === 'string' && field.length > 0,\n\t)\n}\nfunction validVersions(value: unknown): value is IdempotencyVersions {\n\tif (typeof value !== 'object' || value === null) return false\n\t// SAFETY: this temporary metadata view is checked field by field before the predicate certifies it.\n\tconst candidate = value as Partial<IdempotencyVersions>\n\treturn versionFields.every((field) => {\n\t\tconst item = candidate[field]\n\t\treturn Object.hasOwn(candidate, field) && typeof item === 'string' && item.length > 0\n\t})\n}\n"],"mappings":"A,6CAYA,IAAaA,EAAb,cAAsC,KAAM,CAGjC,KAFV,KAAgB,mBAChB,YACC,EACA,EACC,CACD,MAAMC,CAAO,EAHJ,KAAA,KAAAC,EAIT,KAAK,KAAO,kBACb,CACD,EA2BA,MAAMC,EAAU,IAAI,YAEpB,SAAgBC,EAAqB,EAAgB,EAAuC,CAC3F,IAAK,IAAMC,IAAS,CACnBC,EAAO,SACPA,EAAO,SACPA,EAAO,SACPA,EAAO,eACPA,EAAO,eACR,GACK,CAAC,OA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cACA,OAAQS,CACT,CAAC,CACF,CACD,CACD,CACD,CACD,CAEA,SAAS1C,EAAQ,EAAwB,CACxC,MAAM,IAAIP,EAAiB,gBAAiBC,CAAO,CACpD,CACA,SAASiC,EAAc,EAAqC,CAC3D,MAAO,CAACX,EAAM,UAAWA,EAAM,MAAOA,EAAM,GAAG,CAAC,CAAC,MAC/C,GAAU,OAAO4B,GAAU,UAAYA,EAAM,OAAS,CACxD,CACD,CACA,SAAShB,EAAc,EAA8C,CACpE,GAAI,OAAOZ,GAAU,WAAYA,EAAgB,MAAO,GAExD,IAAMgB,EAAYhB,EAClB,OAAOK,EAAc,MAAO,GAAU,CACrC,IAAMV,EAAOqB,EAAUY,GACvB,OAAO,OAAO,OAAOZ,EAAWY,CAAK,GAAK,OAAOjC,GAAS,UAAYA,EAAK,OAAS,CACrF,CAAC,CACF,C"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Retain both successful builds and configuration failures; never repeat declaration effects. */
|
|
2
|
+
export declare function memoize<Value>(build: () => Value): () => Value;
|
|
3
|
+
/** Internal bridge lets the architecture test path validate explicitly supplied registries. */
|
|
4
|
+
export declare function registerLazyRegistry<Registry extends object>(registry: Registry, build: () => object): Registry;
|
|
5
|
+
export declare function forceRegistry<Registry extends object>(registry: Registry): void;
|
|
6
|
+
//# sourceMappingURL=lazy.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){let t=`pending`,n,r;return()=>{if(t===`ready`)return n;if(t===`failed`)throw r;if(t===`building`)throw Error(`Recursive lazy declaration`);t=`building`;try{return n=e(),t=`ready`,n}catch(e){throw r=e,t=`failed`,e}}}const t=/* @__PURE__ */ new WeakMap;function n(e,n){return t.set(e,n),e}function r(e){let n=t.get(e);if(!n)throw Error(`Expected a kit Effect registry`);Object.values(n())}export{r as forceRegistry,e as memoize,n as registerLazyRegistry};
|
|
2
|
+
//# sourceMappingURL=lazy.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lazy.mjs","names":["memoize","state","value","failure","build","cause","registryBuilders","registerLazyRegistry","registry","forceRegistry"],"sources":["../../../src/modules/contracts/lazy.ts"],"sourcesContent":["/** Retain both successful builds and configuration failures; never repeat declaration effects. */\nexport function memoize<Value>(build: () => Value): () => Value {\n\tlet state: 'pending' | 'building' | 'ready' | 'failed' = 'pending'\n\tlet value: Value\n\tlet failure: unknown\n\treturn () => {\n\t\tif (state === 'ready') return value\n\t\tif (state === 'failed') throw failure\n\t\tif (state === 'building') throw new Error('Recursive lazy declaration')\n\t\tstate = 'building'\n\t\ttry {\n\t\t\tvalue = build()\n\t\t\tstate = 'ready'\n\t\t\treturn value\n\t\t} catch (cause) {\n\t\t\tfailure = cause\n\t\t\tstate = 'failed'\n\t\t\tthrow cause\n\t\t}\n\t}\n}\n\nconst registryBuilders = new WeakMap<object, () => object>()\n\n/** Internal bridge lets the architecture test path validate explicitly supplied registries. */\nexport function registerLazyRegistry<Registry extends object>(\n\tregistry: Registry,\n\tbuild: () => object,\n): Registry {\n\tregistryBuilders.set(registry, build)\n\treturn registry\n}\n\nexport function forceRegistry<Registry extends object>(registry: Registry): void {\n\tconst build = registryBuilders.get(registry)\n\tif (!build) throw new Error('Expected a kit Effect registry')\n\t// Getter-declared operations bind on first access; reading every value validates them here too.\n\tvoid Object.values(build())\n}\n"],"mappings":"AACA,SAAgBA,EAAe,EAAiC,CAC/D,IAAIC,EAAqD,UACrDC,EACAC,EACJ,UAAa,CACZ,GAAIF,IAAU,QAAS,OAAOC,EAC9B,GAAID,IAAU,SAAU,MAAME,EAC9B,GAAIF,IAAU,WAAY,MAAU,MAAM,4BAA4B,EACtE,EAAQ,WACR,GAAI,CAGH,MAFA,GAAQG,EAAM,EACd,EAAQ,QACDF,CACR,OAASG,EAAO,CAGf,KAFA,GAAUA,EACV,EAAQ,SACFA,CACP,CACD,CACD,CAEA,MAAMC,kBAAmB,IAAI,QAG7B,SAAgBC,EACf,EACA,EACW,CAEX,OADAD,EAAiB,IAAIE,EAAUJ,CAAK,EAC7BI,CACR,CAEA,SAAgBC,EAAuC,EAA0B,CAChF,IAAML,EAAQE,EAAiB,IAAIE,CAAQ,EAC3C,GAAI,CAACJ,EAAO,MAAU,MAAM,gCAAgC,EAE5D,OAAY,OAAOA,EAAM,CAAC,CAC3B,C"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ContractInput, ContractOutput, Decoder, StandardSchema, ValidationResult } from "./contract.mjs";
|
|
2
|
+
import { KType } from "../../k/types.mjs";
|
|
3
|
+
/** Standard Schema validation executes exactly the validator supplied by its author. */
|
|
4
|
+
export declare function standardContract<const S extends StandardSchema<unknown, unknown>>(schema: S): Decoder<ContractInput<S>, ContractOutput<S>, ValidationResult<ContractOutput<S>> | Promise<ValidationResult<ContractOutput<S>>>> & {
|
|
5
|
+
readonly kind: 'contract';
|
|
6
|
+
readonly schema: S;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A `k` schema as a contract: callers supply its input type (`k.input`, defaults optional, before any
|
|
10
|
+
* transform) and the handler receives its output (`k.infer`). Decoding is synchronous; a failure is a
|
|
11
|
+
* validation result whose issues carry the KTD6 `path`, `code` and `message`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function kContract<const S extends KType>(schema: S): Decoder<S['validator']['type'], S['_output'], ValidationResult<S['_output']>> & {
|
|
14
|
+
readonly kind: 'contract';
|
|
15
|
+
readonly schema: S;
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=standard.d.mts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){return{kind:`contract`,schema:e,decode:t=>e[`~standard`].validate(t)}}function t(e){let t=e;return{kind:`contract`,schema:e,decode:e=>{let n=t.safeParse(e);return n.success?{value:n.data}:{issues:n.issues}}}}export{t as kContract,e as standardContract};
|
|
2
|
+
//# sourceMappingURL=standard.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"standard.mjs","names":["standardContract","schema","value","kContract","parser","result"],"sources":["../../../src/modules/contracts/standard.ts"],"sourcesContent":["import type {\n\tContractInput,\n\tContractOutput,\n\tDecoder,\n\tStandardSchema,\n\tValidationResult,\n} from './contract'\nimport type { KSafeParseResult } from '../../k/issues'\nimport type { KType } from '../../k/types'\n\n/** Standard Schema validation executes exactly the validator supplied by its author. */\nexport function standardContract<const S extends StandardSchema<unknown, unknown>>(\n\tschema: S,\n): Decoder<\n\tContractInput<S>,\n\tContractOutput<S>,\n\tValidationResult<ContractOutput<S>> | Promise<ValidationResult<ContractOutput<S>>>\n> & { readonly kind: 'contract'; readonly schema: S } {\n\treturn {\n\t\tkind: 'contract',\n\t\tschema,\n\t\t// SAFETY: structural Standard Schema inference associates validate's output with S.\n\t\tdecode: (value) =>\n\t\t\tschema['~standard'].validate(value) as\n\t\t\t\t| ValidationResult<ContractOutput<S>>\n\t\t\t\t| Promise<ValidationResult<ContractOutput<S>>>,\n\t}\n}\n\n/**\n * A `k` schema as a contract: callers supply its input type (`k.input`, defaults optional, before any\n * transform) and the handler receives its output (`k.infer`). Decoding is synchronous; a failure is a\n * validation result whose issues carry the KTD6 `path`, `code` and `message`.\n */\nexport function kContract<const S extends KType>(\n\tschema: S,\n): Decoder<S['validator']['type'], S['_output'], ValidationResult<S['_output']>> & {\n\treadonly kind: 'contract'\n\treadonly schema: S\n} {\n\t// SAFETY: every KType at runtime is a KSchema record, which carries safeParse.\n\tconst parser = schema as S & {\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Contracts decode undecoded transport input.\n\t\tsafeParse: (value: unknown) => KSafeParseResult<S['_output']>\n\t}\n\treturn {\n\t\tkind: 'contract',\n\t\tschema,\n\t\tdecode: (value) => {\n\t\t\tconst result = parser.safeParse(value)\n\t\t\treturn result.success ? { value: result.data } : { issues: result.issues }\n\t\t},\n\t}\n}\n"],"mappings":"AAWA,SAAgBA,EACf,EAKqD,CACrD,MAAO,CACN,KAAM,WACN,SAEA,OAAS,GACRC,EAAO,YAAY,CAAC,SAASC,CAAK,CAGpC,CACD,CAOA,SAAgBC,EACf,EAIC,CAED,IAAMC,EAASH,EAIf,MAAO,CACN,KAAM,WACN,SACA,OAAS,GAAU,CAClB,IAAMI,EAASD,EAAO,UAAUF,CAAK,EACrC,OAAOG,EAAO,QAAU,CAAE,MAAOA,EAAO,IAAK,EAAI,CAAE,OAAQA,EAAO,MAAO,CAC1E,CACD,CACD,C"}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { ContractInput, ContractOutput, NeutralSchema } from "./contract.mjs";
|
|
2
|
+
import { CanonicalConvexBounds, IdempotencyInvocation, IdempotencyPreparation } from "./idempotency.mjs";
|
|
3
|
+
import { FunctionReference, FunctionType, FunctionVisibility } from "convex/server";
|
|
4
|
+
import { WorkflowCtx } from "@convex-dev/workflow";
|
|
5
|
+
export declare class WorkflowBindingError extends Error {
|
|
6
|
+
readonly _tag = "WorkflowBindingError";
|
|
7
|
+
constructor(message: string);
|
|
8
|
+
}
|
|
9
|
+
export interface WorkflowExecution<Args = unknown> {
|
|
10
|
+
readonly version: 1;
|
|
11
|
+
readonly operation: string;
|
|
12
|
+
readonly operationVersion: string;
|
|
13
|
+
readonly contractVersion: string;
|
|
14
|
+
readonly bindingVersion: string;
|
|
15
|
+
/** Host-issued business-run identity. Recovery preserves it. */
|
|
16
|
+
readonly run: string;
|
|
17
|
+
/** Opaque host capability; never caller-supplied principal or tenant authority. */
|
|
18
|
+
readonly capability: string;
|
|
19
|
+
/** Logical occurrence, distinct for each repeated loop step. */
|
|
20
|
+
readonly occurrence: string;
|
|
21
|
+
readonly args: Args;
|
|
22
|
+
}
|
|
23
|
+
export type WorkflowStepArguments<Args> = {
|
|
24
|
+
execution: WorkflowExecution<Args>;
|
|
25
|
+
};
|
|
26
|
+
/** Strict plain, versioned transport. Validity does not confer authority; the host resolves capability anew. */
|
|
27
|
+
export declare function workflowExecution<Args>(value: WorkflowExecution<Args>): WorkflowExecution<Args>;
|
|
28
|
+
export declare function workflowExecution(value: unknown): WorkflowExecution;
|
|
29
|
+
export interface WorkflowBinding<Kind extends FunctionType, Args extends NeutralSchema, Result extends NeutralSchema> {
|
|
30
|
+
readonly kind: Kind;
|
|
31
|
+
readonly operation: string;
|
|
32
|
+
readonly operationVersion: string;
|
|
33
|
+
readonly contractVersion: string;
|
|
34
|
+
readonly bindingVersion: string;
|
|
35
|
+
readonly args: Args;
|
|
36
|
+
readonly result: Result;
|
|
37
|
+
readonly reference: FunctionReference<NoInfer<Kind>, FunctionVisibility, WorkflowStepArguments<NoInfer<ContractInput<Args>>>, NoInfer<ContractInput<Result>>>;
|
|
38
|
+
/** Host explicitly lists deployed descriptor versions whose semantics remain compatible. */
|
|
39
|
+
readonly compatibleVersions?: readonly {
|
|
40
|
+
operationVersion: string;
|
|
41
|
+
contractVersion: string;
|
|
42
|
+
bindingVersion: string;
|
|
43
|
+
}[];
|
|
44
|
+
}
|
|
45
|
+
/** Both phantom reference args and results must match the explicit wire contracts. */
|
|
46
|
+
export declare function workflowBinding<Kind extends FunctionType, const Args extends NeutralSchema, const Result extends NeutralSchema>(binding: WorkflowBinding<Kind, Args, Result>): WorkflowBinding<Kind, Args, Result>;
|
|
47
|
+
export type WorkflowStepOptions = {
|
|
48
|
+
name?: string;
|
|
49
|
+
retry?: NonNullable<Parameters<WorkflowCtx['withOptions']>[0]['retry']>;
|
|
50
|
+
} & ({
|
|
51
|
+
inline?: false;
|
|
52
|
+
runAt?: number;
|
|
53
|
+
runAfter?: number;
|
|
54
|
+
} | {
|
|
55
|
+
inline: true;
|
|
56
|
+
runAt?: never;
|
|
57
|
+
runAfter?: never;
|
|
58
|
+
});
|
|
59
|
+
/** A structural seam allows invocation-scoped native WorkflowCtx without creating another durability runtime. */
|
|
60
|
+
export interface WorkflowStepRunner {
|
|
61
|
+
runQuery?: (reference: FunctionReference<'query', FunctionVisibility>, args: WorkflowStepArguments<unknown>, options?: WorkflowStepOptions) => Promise<unknown>;
|
|
62
|
+
runMutation?: (reference: FunctionReference<'mutation', FunctionVisibility>, args: WorkflowStepArguments<unknown>, options?: WorkflowStepOptions) => Promise<unknown>;
|
|
63
|
+
runAction?: (reference: FunctionReference<'action', FunctionVisibility>, args: WorkflowStepArguments<unknown>, options?: WorkflowStepOptions) => Promise<unknown>;
|
|
64
|
+
}
|
|
65
|
+
export declare function runWorkflowStep<Kind extends FunctionType, Args extends NeutralSchema, Result extends NeutralSchema>(step: WorkflowCtx | WorkflowStepRunner, binding: WorkflowBinding<Kind, Args, Result>, input: WorkflowExecution<ContractInput<Args>>, options?: WorkflowStepOptions): Promise<ContractInput<Result>>;
|
|
66
|
+
export declare function workflowDecode<S extends NeutralSchema>(schema: S, value: unknown): Promise<ContractOutput<S>>;
|
|
67
|
+
type Ordinary<A> = A | PromiseLike<A>;
|
|
68
|
+
/** This helper belongs inside a registered native function, never in the replaying workflow handler. */
|
|
69
|
+
export declare function workflowAttempt<Args, Authority, Result>(configuration: {
|
|
70
|
+
authorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>;
|
|
71
|
+
execute: (execution: WorkflowExecution<Args>, authority: Authority) => Ordinary<Result>;
|
|
72
|
+
}): (input: WorkflowExecution<Args>) => Promise<Result>;
|
|
73
|
+
export type WorkflowOutcome<Result = unknown, Failure = unknown> = {
|
|
74
|
+
readonly version: 1;
|
|
75
|
+
readonly kind: 'succeeded';
|
|
76
|
+
readonly value: Result;
|
|
77
|
+
} | {
|
|
78
|
+
readonly version: 1;
|
|
79
|
+
readonly kind: 'failed';
|
|
80
|
+
readonly error: Failure;
|
|
81
|
+
};
|
|
82
|
+
declare const protectedMutation: unique symbol;
|
|
83
|
+
export interface ReceiptProtectedWorkflowMutation<Args, Result> {
|
|
84
|
+
readonly [protectedMutation]: {
|
|
85
|
+
args: Args;
|
|
86
|
+
result: Result;
|
|
87
|
+
};
|
|
88
|
+
readonly handler: (execution: WorkflowExecution<Args>) => Promise<Result>;
|
|
89
|
+
}
|
|
90
|
+
export interface WorkflowReceiptAdapter<S extends NeutralSchema> {
|
|
91
|
+
readonly replayResult: S;
|
|
92
|
+
readonly prepare: (invocation: IdempotencyInvocation) => Promise<IdempotencyPreparation<ContractOutput<S>>>;
|
|
93
|
+
}
|
|
94
|
+
/** Host registers this handler as the inner native mutation. All callbacks share its transaction. */
|
|
95
|
+
export declare function receiptWorkflowMutation<Args, Authority, const Replay extends NeutralSchema>(configuration: {
|
|
96
|
+
authorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>;
|
|
97
|
+
receipt: (authority: Authority) => WorkflowReceiptAdapter<Replay>;
|
|
98
|
+
invocation: (execution: WorkflowExecution<Args>, authority: Authority) => IdempotencyInvocation;
|
|
99
|
+
execute: (execution: WorkflowExecution<Args>, authority: Authority) => Ordinary<ContractOutput<Replay>>;
|
|
100
|
+
}): ReceiptProtectedWorkflowMutation<Args, ContractOutput<Replay>>;
|
|
101
|
+
export declare function workflowReceiptInvocation(execution: WorkflowExecution, options: {
|
|
102
|
+
scope: string;
|
|
103
|
+
fingerprintPolicy: string;
|
|
104
|
+
bounds: CanonicalConvexBounds;
|
|
105
|
+
}): IdempotencyInvocation;
|
|
106
|
+
type TerminalMode<Args> = {
|
|
107
|
+
kind: 'mutation';
|
|
108
|
+
/** Assertion supplied only after host native rollback/journaling acceptance. */ atomicJournalProof: 'host-verified';
|
|
109
|
+
} | {
|
|
110
|
+
kind: 'action';
|
|
111
|
+
protectedMutation: ReceiptProtectedWorkflowMutation<Args, unknown>;
|
|
112
|
+
};
|
|
113
|
+
/** The native inner mutation rejection must cross its transaction boundary before terminal mapping. */
|
|
114
|
+
export declare function terminalWorkflowAttempt<Args, Authority, const Result extends NeutralSchema, const Failure extends NeutralSchema>(configuration: TerminalMode<Args> & {
|
|
115
|
+
authorize: (execution: WorkflowExecution<Args>) => Ordinary<Authority>;
|
|
116
|
+
invokeMutation: (execution: WorkflowExecution<Args>, authority: Authority) => Promise<ContractInput<Result>>;
|
|
117
|
+
terminal: (error: unknown) => Ordinary<ContractInput<Failure> | undefined>;
|
|
118
|
+
result: Result;
|
|
119
|
+
failure: Failure;
|
|
120
|
+
}): (input: WorkflowExecution<Args>) => Promise<WorkflowOutcome<ContractInput<Result>, ContractOutput<Failure>>>;
|
|
121
|
+
export type WorkflowNativeStatus = 'running' | 'succeeded' | 'failed' | 'canceled';
|
|
122
|
+
export interface WorkflowHostState<Result = unknown, Failure = unknown> {
|
|
123
|
+
readonly generation: number;
|
|
124
|
+
readonly status: WorkflowNativeStatus;
|
|
125
|
+
readonly nativeStatus: WorkflowNativeStatus;
|
|
126
|
+
readonly outcome?: WorkflowOutcome<Result, Failure>;
|
|
127
|
+
}
|
|
128
|
+
export interface WorkflowHostUpdate<Result = unknown, Failure = unknown> {
|
|
129
|
+
readonly generation: number;
|
|
130
|
+
readonly nativeStatus: WorkflowNativeStatus;
|
|
131
|
+
readonly outcome?: WorkflowOutcome<Result, Failure>;
|
|
132
|
+
}
|
|
133
|
+
export type WorkflowTransition<Result = unknown, Failure = unknown> = {
|
|
134
|
+
readonly kind: 'applied' | 'ignored';
|
|
135
|
+
readonly state: WorkflowHostState<Result, Failure>;
|
|
136
|
+
};
|
|
137
|
+
/** Call within a host transaction or compare-and-set. A late operation failure refines host success; cancellation and terminal native status stay fenced. */
|
|
138
|
+
export declare function workflowTransition<Result, Failure>(current: WorkflowHostState<Result, Failure>, update: WorkflowHostUpdate<Result, Failure>): WorkflowTransition<Result, Failure>;
|
|
139
|
+
export declare function workflowCancel<Result, Failure>(current: WorkflowHostState<Result, Failure>, expectedGeneration: number): WorkflowTransition<Result, Failure>;
|
|
140
|
+
/** Host calls after an authorized native restart. Receipt identity remains run plus occurrence. */
|
|
141
|
+
export declare function workflowRestart<Result, Failure>(current: WorkflowHostState<Result, Failure>): WorkflowHostState<Result, Failure>;
|
|
142
|
+
/** Host closures capture the trusted run, secured storage and manager. `write` must enforce expected generation atomically. */
|
|
143
|
+
export declare function workflowStatusBindings<Result, Failure>(configuration: {
|
|
144
|
+
authorize: () => Ordinary<void>;
|
|
145
|
+
read: () => Ordinary<WorkflowHostState<Result, Failure>>;
|
|
146
|
+
write: (expectedGeneration: number, state: WorkflowHostState<Result, Failure>) => Ordinary<void>;
|
|
147
|
+
nativeStatus: () => Ordinary<WorkflowNativeStatus>;
|
|
148
|
+
receiptOutcome: () => Ordinary<WorkflowOutcome<Result, Failure> | undefined>;
|
|
149
|
+
/** Host calls the manager in the same transaction as its guarded state write. */
|
|
150
|
+
cancelNative: () => Ordinary<void>;
|
|
151
|
+
restartNative: () => Ordinary<void>;
|
|
152
|
+
}): {
|
|
153
|
+
callback(expectedGeneration: number, nativeStatus: WorkflowNativeStatus, outcome?: WorkflowOutcome<Result, Failure>): Promise<WorkflowTransition<Result, Failure>>;
|
|
154
|
+
reconcile(expectedGeneration: number): Promise<WorkflowTransition<Result, Failure>>;
|
|
155
|
+
cancel(expectedGeneration: number): Promise<WorkflowTransition<Result, Failure>>;
|
|
156
|
+
restart(expectedGeneration: number): Promise<{
|
|
157
|
+
kind: 'ignored';
|
|
158
|
+
state: WorkflowHostState<Result, Failure>;
|
|
159
|
+
} | {
|
|
160
|
+
kind: 'applied';
|
|
161
|
+
state: WorkflowHostState<Result, Failure>;
|
|
162
|
+
}>;
|
|
163
|
+
};
|
|
164
|
+
export {};
|
|
165
|
+
//# sourceMappingURL=workflow.d.mts.map
|