cvx-kit 0.1.29 → 0.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +52 -0
  2. package/dist/auth.d.mts +29 -11
  3. package/dist/auth.mjs +1 -1
  4. package/dist/auth.mjs.map +1 -1
  5. package/dist/effect.d.mts +5 -1
  6. package/dist/effect.mjs +1 -1
  7. package/dist/modules/contracts/binding.d.mts +1 -3
  8. package/dist/modules/contracts/binding.mjs +1 -1
  9. package/dist/modules/contracts/binding.mjs.map +1 -1
  10. package/dist/modules/contracts/domain.d.mts +5 -1
  11. package/dist/modules/contracts/domain.mjs +1 -1
  12. package/dist/modules/contracts/domain.mjs.map +1 -1
  13. package/dist/modules/contracts/errors.d.mts +4 -0
  14. package/dist/modules/contracts/errors.mjs +1 -1
  15. package/dist/modules/contracts/errors.mjs.map +1 -1
  16. package/dist/modules/contracts/lazy.mjs +1 -1
  17. package/dist/modules/contracts/lazy.mjs.map +1 -1
  18. package/dist/modules/effect/action.d.mts +64 -0
  19. package/dist/modules/effect/action.mjs +2 -0
  20. package/dist/modules/effect/action.mjs.map +1 -0
  21. package/dist/modules/effect/api-runtime.mjs +1 -1
  22. package/dist/modules/effect/api-runtime.mjs.map +1 -1
  23. package/dist/modules/effect/client.d.mts +5 -1
  24. package/dist/modules/effect/client.mjs +1 -1
  25. package/dist/modules/effect/command.d.mts +15 -9
  26. package/dist/modules/effect/command.mjs +1 -1
  27. package/dist/modules/effect/command.mjs.map +1 -1
  28. package/dist/modules/effect/crud.d.mts +17 -16
  29. package/dist/modules/effect/domain.d.mts +19 -8
  30. package/dist/modules/effect/domain.mjs +1 -1
  31. package/dist/modules/effect/domain.mjs.map +1 -1
  32. package/dist/modules/effect/errors.d.mts +5 -1
  33. package/dist/modules/effect/errors.mjs +1 -1
  34. package/dist/modules/effect/errors.mjs.map +1 -1
  35. package/dist/modules/effect/failure-audit.d.mts +48 -0
  36. package/dist/modules/effect/failure-audit.mjs +2 -0
  37. package/dist/modules/effect/failure-audit.mjs.map +1 -0
  38. package/dist/modules/effect/failures.d.mts +22 -0
  39. package/dist/modules/effect/failures.mjs +2 -0
  40. package/dist/modules/effect/failures.mjs.map +1 -0
  41. package/dist/modules/effect/foundation.d.mts +6 -1
  42. package/dist/modules/effect/foundation.mjs +1 -1
  43. package/dist/modules/effect/foundation.mjs.map +1 -1
  44. package/dist/modules/effect/operation.d.mts +10 -2
  45. package/dist/modules/effect/operation.mjs +1 -1
  46. package/dist/modules/effect/operation.mjs.map +1 -1
  47. package/dist/modules/effect/query.d.mts +5 -1
  48. package/dist/modules/effect/query.mjs +1 -1
  49. package/dist/modules/effect/query.mjs.map +1 -1
  50. package/dist/modules/effect/scope.d.mts +27 -0
  51. package/dist/modules/effect/scope.mjs +2 -0
  52. package/dist/modules/effect/scope.mjs.map +1 -0
  53. package/dist/relations.mjs +1 -1
  54. package/dist/relations.mjs.map +1 -1
  55. package/dist/zod-registration.mjs +1 -1
  56. package/dist/zod-registration.mjs.map +1 -1
  57. package/package.json +2 -1
@@ -1,2 +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:c(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:s(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?s(n):t},decode(e){try{if(!o(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?(s(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:c(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=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:{}}});function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function s(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(s(e[r],t));return n}if(!o(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,s(n,t)]))}finally{t.delete(e)}}function c(e,t,n){if(!o(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,s(e.details[n].parse(t[n]))]}))}export{i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,a as queryErrors};
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:c(i,t,!1)}}catch{throw Error(`Invalid declared error details`)}let a=Object.freeze({_tag:`DeclaredError`,code:e,details:s(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?s(n):t},decode(e){try{if(!o(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?(s(e.details),{_tag:`DeclaredFailure`,version:1,code:e.code,message:n.message,details:c(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=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:{}}});function o(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function s(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(s(e[r],t));return n}if(!o(e))throw Error(`Invalid JSON`);return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,s(n,t)]))}finally{t.delete(e)}}function c(e,t,n){if(!o(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,s(e.details[n].parse(t[n]))]}))}export{i as combineErrorContracts,r as decodeFailure,n as defineErrorContract,o as isRecord,a as queryErrors};
2
2
  //# sourceMappingURL=errors.mjs.map
@@ -1 +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","value","prototype","ancestors","result","index","child","fields","strict","field"],"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\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 = 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\nfunction 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"],"mappings":"4CAsEA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACdC,EAAuC,CAC5C,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAON,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAiB,EACrE,IAAMC,EAAaH,EAAaE,GAEhC,EAAW,CACV,KAAM,kBACN,QAAS,EACT,OACA,QAASC,EAAW,QACpB,QAASI,EAAaJ,EAAYK,EAAS,EAAK,CACjD,CACD,MAAQ,CAEP,MAAM,MAAM,gCAAgC,CAC7C,CAEA,IAAMC,EAAQ,OAAO,OAAO,CAC3B,KAAM,gBACN,OACA,QAASC,EAASJ,EAAS,OAAO,CACnC,CAAC,EAED,OADAF,EAAQ,IAAIK,EAAOH,CAAQ,EACpBG,CACR,EACA,SAAS,EAAM,EAAS,CAEvB,OAAOJ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AU,MAAQ,OAAOA,GAAU,UAAY,OAAOA,GAAU,WAChE,OAAOA,GAAU,UAAY,OAAO,SAASA,CAAK,EAAG,OAAOA,EAChE,GAAI,OAAOA,GAAU,WAAYA,GAAkBE,EAAU,IAAIF,CAAK,EACrE,MAAM,MAAM,cAAc,EAC3BE,EAAU,IAAIF,CAAK,EACnB,GAAI,CACH,GAAI,MAAM,QAAQA,CAAK,EAAG,CACzB,IAAMG,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAQ,EAAGA,EAAQJ,EAAM,OAAQ,IACzCG,EAAO,KAAKf,EAASY,EAAMI,GAAQF,CAAS,CAAC,EAC9C,OAAOC,CACR,CACA,GAAI,CAACb,EAASU,CAAK,EAAG,MAAM,MAAM,cAAc,EAChD,OAAO,OAAO,YACb,OAAO,QAAQA,CAAK,CAAC,CAAC,KAAK,CAACR,EAAKa,KAAW,CAACb,EAAKJ,EAASiB,EAAOH,CAAS,CAAC,CAAC,CAC9E,CACD,QAAU,CACTA,EAAU,OAAOF,CAAK,CACvB,CACD,CAEA,SAASf,EACR,EACA,EACA,EACsB,CACtB,GAAI,CAACK,EAASU,CAAK,EAAG,MAAM,MAAM,iBAAiB,EACnD,IAAMM,EAAS,OAAO,KAAKzB,EAAW,OAAO,EAC7C,GAAI0B,GAAU,OAAO,KAAKP,CAAK,CAAC,CAAC,KAAM,GAAQ,CAAC,OAAO,OAAOnB,EAAW,QAASW,CAAG,CAAC,EACrF,MAAM,MAAM,mBAAmB,EAGhC,OAAO,OAAO,YACbc,EAAO,IAAK,GAAU,CACrB,GAAI,CAAC,OAAO,OAAON,EAAOQ,CAAK,EAAG,MAAM,MAAM,gBAAgB,EAC9D,MAAO,CAACA,EAAOpB,EAASP,EAAW,QAAQ2B,EAAM,CAAC,MAAMR,EAAMQ,EAAM,CAAC,CAAC,CACvE,CAAC,CACF,CACD"}
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","value","prototype","ancestors","result","index","child","fields","strict","field"],"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 = 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/** 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"],"mappings":"4CA2EA,MAAMA,EAAiC,OAAO,OAAO,CACpD,KAAM,iBACN,QAAS,CACV,CAAC,EAID,SAAgBC,EACf,EAC6B,CAE7B,IAAMC,EAAe,OAAO,YAC3B,OAAO,QAAQC,CAAW,CAAC,CAAC,KAAK,CAACC,EAAMC,KAAgB,CACvD,GAAI,CAACD,GAAQ,CAACC,EAAW,SAAWA,EAAW,QAAQ,OAAS,IAC/D,MAAM,MAAM,yEAAyE,EAEtF,MAAO,CAACD,EAAM,CAAE,QAASC,EAAW,QAAS,QAAS,CAAE,GAAGA,EAAW,OAAQ,CAAE,CAAC,CAClF,CAAC,CACF,EACMC,kBAAU,IAAI,QACdC,EAAuC,CAC5C,OAAO,EAAM,EAAS,CACrB,IAAIC,EACJ,GAAI,CACH,GAAI,CAAC,OAAO,OAAON,EAAcE,CAAI,EAAG,MAAM,MAAM,iBAAiB,EACrE,IAAMC,EAAaH,EAAaE,GAEhC,EAAW,CACV,KAAM,kBACN,QAAS,EACT,OACA,QAASC,EAAW,QACpB,QAASI,EAAaJ,EAAYK,EAAS,EAAK,CACjD,CACD,MAAQ,CAEP,MAAM,MAAM,gCAAgC,CAC7C,CAEA,IAAMC,EAAQ,OAAO,OAAO,CAC3B,KAAM,gBACN,OACA,QAAS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AMQ,EAAM,CAAC,CAAC,CACvE,CAAC,CACF,CACD"}
@@ -1,2 +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`);n()}export{r as forceRegistry,e as memoize,n as registerLazyRegistry};
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
2
  //# sourceMappingURL=lazy.mjs.map
@@ -1 +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\tbuild()\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,EAC5DA,EAAM,CACP"}
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"}
@@ -0,0 +1,64 @@
1
+ import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
2
+ import { AuditEntryInput } from "../../components/foundation/client.mjs";
3
+ import { DomainActionContract, DomainAuditInput, DomainContract } from "../contracts/domain.mjs";
4
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
5
+ import { CallbackError, CallbackRequirements, ValidatedEffectOperations, effectActionFactory } from "./operation.mjs";
6
+ import { FailureAuditOptions } from "./failure-audit.mjs";
7
+ import { BoundOperations } from "../contracts/binding.mjs";
8
+ import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations } from "./domain.mjs";
9
+ import { DomainOf, HostOf, HostParameter, Registry, Resolver, createEffectCommand } from "./command.mjs";
10
+ import { Effect } from "effect";
11
+ //#region src/modules/effect/action.d.ts
12
+ type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
13
+ /** Host policies an Action registry uses; actions have no mutation-side permission host. */
14
+ export type EffectActionDependencies = {
15
+ observability: Observability;
16
+ /** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */
17
+ writeActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>;
18
+ auditFailure?: FailureAuditOptions;
19
+ nestedAudit?: NestedAuditMode;
20
+ };
21
+ type ActionWriter<Dependencies extends EffectActionDependencies> = [Exclude<Dependencies['writeActionAudit'], undefined>] extends [never] ? (host: never, entry: AuditEntryInput) => void : Exclude<Dependencies['writeActionAudit'], undefined>;
22
+ /** The command kernel runs actions with the action writer in its audit-writer slot. */
23
+ type KernelDependencies<Dependencies extends EffectActionDependencies> = {
24
+ observability: Observability;
25
+ writeAudit: ActionWriter<Dependencies>;
26
+ auditFailure?: FailureAuditOptions;
27
+ nestedAudit?: NestedAuditMode;
28
+ };
29
+ type ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [HostOf<Resolve>] extends [HostParameter<Dependencies['writeActionAudit']>] ? unknown : {
30
+ context: never;
31
+ };
32
+ type ActionFactory<Resolve extends Resolver, Guard> = ReturnType<typeof effectActionFactory<DomainOf<Resolve>, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>>;
33
+ type Kernel<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = ReturnType<typeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>>;
34
+ /** Actions are executed by their own Convex action functions; they are never exposed as mutations. */
35
+ export type EffectActionRegistry<Resolve extends Resolver, Operations extends Registry<DomainOf<Resolve>>, Dependencies extends EffectActionDependencies, Guard> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>;
36
+ export declare class ActionAuditWriterError extends Error {
37
+ readonly code = "ACTION_AUDIT_WRITER_MISSING";
38
+ readonly name = "ActionAuditWriterError";
39
+ constructor(operation: string);
40
+ }
41
+ /** Bind trusted application policies once; each registry resolves its own invocation context. */
42
+ export declare function bindEffectAction<const Dependencies extends EffectActionDependencies>(dependencies: Dependencies): {
43
+ <Resolve extends Resolver, const Contract extends DomainContract & {
44
+ actions: Readonly<Record<string, DomainActionContract>>;
45
+ }, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>, Returned extends AuditValue = never, Guard = never>(configuration: {
46
+ contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['actions']> & ValidatedEffectOperations<Operations> ? unknown : never>;
47
+ context: Resolve;
48
+ audit?: (resolution: DomainAuditInput<Contract['actions']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
49
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['actions'], 'action', never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
50
+ defaults?: {
51
+ guard?: (context: DomainOf<Resolve>) => Guard;
52
+ };
53
+ } & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? BoundOperations<Operations, Contract['actions']> : AuditedOperations<BoundOperations<Operations, Contract['actions']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
54
+ <Resolve extends Resolver, const Operations extends Registry<DomainOf<Resolve>>, Returned extends AuditValue = never, Guard = never>(configuration: {
55
+ context: Resolve;
56
+ audit?: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
57
+ operations: (define: ActionFactory<Resolve, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
58
+ defaults?: {
59
+ guard?: (context: DomainOf<Resolve>) => Guard;
60
+ };
61
+ } & ActionCompatible<Resolve, Dependencies>): EffectActionRegistry<Resolve, [Returned] extends [never] ? Operations : AuditedOperations<Operations, (resolution: never, context: never) => Returned>, Dependencies, Guard>;
62
+ };
63
+ //#endregion
64
+ //# sourceMappingURL=action.d.mts.map
@@ -0,0 +1,2 @@
1
+ import{memoize as e,registerLazyRegistry as t}from"../contracts/lazy.mjs";import{effectActionFactory as n}from"./operation.mjs";import{snapshotOperations as r}from"../contracts/binding.mjs";import{domainEffectFactory as i}from"./domain.mjs";import{createEffectCommand as a}from"./command.mjs";var o=class extends Error{code=`ACTION_AUDIT_WRITER_MISSING`;name=`ActionAuditWriterError`;constructor(e){super(`Action "${e}" declares an audit but the Foundation has no writeActionAudit`)}};function s(s){function c(c){let l=e(()=>{let e=r(c.operations(c.contract?i(c.contract.actions??{},`action`,c.contract.errors):n()),c.contract,`actions`,c.audit);if(!s.writeActionAudit){for(let[t,n]of Object.entries(e))if(`audit`in n&&n.audit!==void 0)throw new o(t)}return e}),u=a({...c,observability:s.observability,auditFailure:s.auditFailure,nestedAudit:s.nestedAudit,writeAudit:s.writeActionAudit??(()=>void 0),operations:l,mode:`action`});return t({exec:u.exec,withContext:u.withContext},l)}return c}export{o as ActionAuditWriterError,s as bindEffectAction};
2
+ //# sourceMappingURL=action.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.mjs","names":["ActionAuditWriterError","operation","bindEffectAction","action","getOperations","memoize","operations","snapshotOperations","configuration","domainEffectFactory","effectActionFactory","dependencies","definition","kernel","createEffectCommand","registerLazyRegistry"],"sources":["../../../src/modules/effect/action.ts"],"sourcesContent":["/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport type { Effect } from 'effect'\nimport type { AuditEntryInput } from '../../components/foundation/client'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation observability without entering the Convex component deployment graph.\nimport type { Observability } from '../../components/foundation/modules/observability/observability'\nimport type { DomainActionContract, DomainAuditInput, DomainContract } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport { memoize, registerLazyRegistry } from '../contracts/lazy'\nimport {\n\tcreateEffectCommand,\n\ttype DomainOf,\n\ttype HostOf,\n\ttype HostParameter,\n\ttype Registry,\n\ttype Resolver,\n} from './command'\nimport {\n\tdomainEffectFactory,\n\ttype AuditedOperations,\n\ttype AuditValue,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n} from './domain'\nimport type { FailureAuditOptions } from './failure-audit'\nimport {\n\teffectActionFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\nimport type { NestedAuditMode, RequestScope } from './scope'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\n\n/** Host policies an Action registry uses; actions have no mutation-side permission host. */\nexport type EffectActionDependencies = {\n\tobservability: Observability\n\t/** Writes action audit entries, typically through `ctx.runMutation`; required once any action audits. */\n\twriteActionAudit?: (host: never, entry: AuditEntryInput) => Supported<unknown>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionWriter<Dependencies extends EffectActionDependencies> = [\n\tExclude<Dependencies['writeActionAudit'], undefined>,\n] extends [never]\n\t? (host: never, entry: AuditEntryInput) => void\n\t: Exclude<Dependencies['writeActionAudit'], undefined>\n/** The command kernel runs actions with the action writer in its audit-writer slot. */\ntype KernelDependencies<Dependencies extends EffectActionDependencies> = {\n\tobservability: Observability\n\twriteAudit: ActionWriter<Dependencies>\n\tauditFailure?: FailureAuditOptions\n\tnestedAudit?: NestedAuditMode\n}\ntype ActionCompatible<Resolve extends Resolver, Dependencies extends EffectActionDependencies> = [\n\tHostOf<Resolve>,\n] extends [HostParameter<Dependencies['writeActionAudit']>]\n\t? unknown\n\t: { context: never }\ntype ActionFactory<Resolve extends Resolver, Guard> = ReturnType<\n\ttypeof effectActionFactory<\n\t\tDomainOf<Resolve>,\n\t\tNoInfer<CallbackError<Guard>>,\n\t\tNoInfer<CallbackRequirements<Guard>>\n\t>\n>\ntype Kernel<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = ReturnType<\n\ttypeof createEffectCommand<Resolve, Operations, KernelDependencies<Dependencies>, Guard>\n>\n/** Actions are executed by their own Convex action functions; they are never exposed as mutations. */\nexport type EffectActionRegistry<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tDependencies extends EffectActionDependencies,\n\tGuard,\n> = Pick<Kernel<Resolve, Operations, Dependencies, Guard>, 'exec' | 'withContext'>\n\nexport class ActionAuditWriterError extends Error {\n\treadonly code = 'ACTION_AUDIT_WRITER_MISSING'\n\treadonly name = 'ActionAuditWriterError'\n\tconstructor(operation: string) {\n\t\tsuper(`Action \"${operation}\" declares an audit but the Foundation has no writeActionAudit`)\n\t}\n}\n\n/** Bind trusted application policies once; each registry resolves its own invocation context. */\nexport function bindEffectAction<const Dependencies extends EffectActionDependencies>(\n\tdependencies: Dependencies,\n) {\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tactions: Readonly<Record<string, DomainActionContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['actions']>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['actions']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Contract['actions']>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['actions'],\n\t\t\t\t\t'action',\n\t\t\t\t\tnever,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>,\n\t\t\t\t\tContract['errors']\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? BoundOperations<Operations, Contract['actions']>\n\t\t\t: AuditedOperations<\n\t\t\t\t\tBoundOperations<Operations, Contract['actions']>,\n\t\t\t\t\t(resolution: never, context: never) => Returned\n\t\t\t\t>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends Registry<DomainOf<Resolve>>,\n\t\tReturned extends AuditValue = never,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontext: Resolve\n\t\t\taudit?: (\n\t\t\t\tresolution: DomainAuditInput<Operations>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: ActionFactory<Resolve, Guard>,\n\t\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & ActionCompatible<Resolve, Dependencies>,\n\t): EffectActionRegistry<\n\t\tResolve,\n\t\t[Returned] extends [never]\n\t\t\t? Operations\n\t\t\t: AuditedOperations<Operations, (resolution: never, context: never) => Returned>,\n\t\tDependencies,\n\t\tGuard\n\t>\n\tfunction action(configuration: {\n\t\tcontext: Resolver\n\t\tcontract?: DomainContract\n\t\taudit?: (resolution: never, context: never, scope: never) => AuditValue\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { guard?: (context: never) => unknown }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst operations = snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: each overload checks callbacks against this exact inline or contracted helper factory.\n\t\t\t\t\t(configuration.contract\n\t\t\t\t\t\t? domainEffectFactory(\n\t\t\t\t\t\t\t\tconfiguration.contract.actions ?? {},\n\t\t\t\t\t\t\t\t'action',\n\t\t\t\t\t\t\t\tconfiguration.contract.errors,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: effectActionFactory()) as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'actions',\n\t\t\t\tconfiguration.audit,\n\t\t\t)\n\t\t\tif (!dependencies.writeActionAudit) {\n\t\t\t\tfor (const [operation, definition] of Object.entries(operations))\n\t\t\t\t\tif ('audit' in definition && definition.audit !== undefined)\n\t\t\t\t\t\tthrow new ActionAuditWriterError(operation)\n\t\t\t}\n\t\t\treturn operations\n\t\t}\n\t\tconst getOperations = memoize(buildOperations)\n\t\t// SAFETY: overloads check callbacks and schemas; binding validates exact keys and snapshots runtime records.\n\t\tconst kernel = createEffectCommand({\n\t\t\t...configuration,\n\t\t\tobservability: dependencies.observability,\n\t\t\tauditFailure: dependencies.auditFailure,\n\t\t\tnestedAudit: dependencies.nestedAudit,\n\t\t\twriteAudit: dependencies.writeActionAudit ?? (() => undefined),\n\t\t\toperations: getOperations,\n\t\t\tmode: 'action',\n\t\t} as never)\n\t\treturn registerLazyRegistry(\n\t\t\t{ exec: kernel.exec, withContext: kernel.withContext },\n\t\t\tgetOperations,\n\t\t)\n\t}\n\treturn action\n}\n"],"mappings":"qSAmFA,IAAaA,EAAb,cAA4C,KAAM,CACjD,KAAgB,8BAChB,KAAgB,yBAChB,YAAY,EAAmB,CAC9B,MAAM,WAAWC,EAAU,+DAA+D,CAC3F,CACD,EAGA,SAAgBC,EACf,EACC,CA0ED,SAASC,EAAO,EAMJ,CAwBX,IAAMC,EAAgBC,MAvBQ,CAC7B,IAAMC,EAAaC,EAClBC,EAAc,WAEZA,EAAc,SACZC,EACAD,EAAc,SAAS,SAAW,CAAC,EACnC,SACAA,EAAc,SAAS,MACxB,EACCE,EAAoB,CACxB,EACAF,EAAc,SACd,UACAA,EAAc,KACf,EACA,GAAI,CAACG,EAAa,iBACZ,KAAA,GAAM,CAACV,EAAWW,KAAe,OAAO,QAAQN,CAAU,EAC9D,GAAI,UAAWM,GAAcA,EAAW,QAAU,IAAA,GACjD,MAAM,IAAIZ,EAAuBC,CAAS,CAAA,CAE7C,OAAOK,CACR,CAC6C,EAEvCO,EAASC,EAAoB,CAClC,GAAGN,EACH,cAAeG,EAAa,cAC5B,aAAcA,EAAa,aAC3B,YAAaA,EAAa,YAC1B,WAAYA,EAAa,uBAA2B,IAAA,IACpD,WAAYP,EACZ,KAAM,QACP,CAAU,EACV,OAAOW,EACN,CAAE,KAAMF,EAAO,KAAM,YAAaA,EAAO,WAAY,EACrDT,CACD,CACD,CACA,OAAOD,CACR"}
@@ -1,2 +1,2 @@
1
- import{projectErrorCause as e}from"./errors.mjs";import{normalizeEffect as t}from"./normalize.mjs";import{ConvexError as n}from"convex/values";import{Cause as r,Context as i,Effect as a,Exit as o}from"effect";function s(s,c){return l=>{let u=typeof l==`function`?l:l.handler,d=async(s,...l)=>{let d=t(()=>c.services?c.services(s):i.empty()).pipe(a.flatMap(e=>t(()=>c.context?c.context(s):{}).pipe(a.flatMap(e=>a.sync(()=>{if(typeof e!=`object`||!e)throw Error(`Effect API context must be an object`);let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)throw Error(`Effect API context additions must be a plain record`);let n=s;for(let t of Reflect.ownKeys(e))if(t in n)throw Error(`Effect API context cannot replace ${String(t)}`);return c.context?Object.create(Object.getPrototypeOf(n),{...Object.getOwnPropertyDescriptors(n),...Object.getOwnPropertyDescriptors(e)}):s})),a.flatMap(e=>t(()=>u(e,...l))),a.provideContext(e)))),f=await a.runPromiseExit(a.scoped(d));if(o.isSuccess(f))return f.value;if(c.errors)throw new n(e(c.errors,f.cause));let p=f.cause.reasons.length===1?f.cause.reasons[0]:void 0;throw p&&r.isFailReason(p)?c.mapError?c.mapError(p.error):p.error:p&&r.isDieReason(p)?p.defect:Error(`Effect API execution failed`,{cause:f.cause})};return s(typeof l==`function`?d:{...l,handler:d})}}export{s as wrapEffectBuilder};
1
+ import{memoize as e}from"../contracts/lazy.mjs";import{projectErrorCause as t}from"./errors.mjs";import{normalizeEffect as n}from"./normalize.mjs";import{ConvexError as r}from"convex/values";import{Cause as i,Context as a,Effect as o,Exit as s}from"effect";function c(e,c){return u=>{let d=typeof u==`function`?u:u.handler,f=async(e,...l)=>{let u=n(()=>c.services?c.services(e):a.empty()).pipe(o.flatMap(t=>n(()=>c.context?c.context(e):{}).pipe(o.flatMap(t=>o.sync(()=>{if(typeof t!=`object`||!t)throw Error(`Effect API context must be an object`);let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw Error(`Effect API context additions must be a plain record`);let r=e;for(let e of Reflect.ownKeys(t))if(e in r)throw Error(`Effect API context cannot replace ${String(e)}`);return c.context?Object.create(Object.getPrototypeOf(r),{...Object.getOwnPropertyDescriptors(r),...Object.getOwnPropertyDescriptors(t)}):e})),o.flatMap(e=>n(()=>d(e,...l))),o.provideContext(t)))),f=await o.runPromiseExit(o.scoped(u));if(s.isSuccess(f))return f.value;if(c.errors)throw new r(t(c.errors,f.cause));let p=f.cause.reasons.length===1?f.cause.reasons[0]:void 0;throw p&&i.isFailReason(p)?c.mapError?c.mapError(p.error):p.error:p&&i.isDieReason(p)?p.defect:Error(`Effect API execution failed`,{cause:f.cause})};return e(typeof u==`function`?f:l(u,f))}}function l(t,n){let r={handler:n};for(let n of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,n);n!==`handler`&&i?.enumerable&&Object.defineProperty(r,n,{configurable:!0,enumerable:!0,...i.get?{get:e(()=>i.get.call(t))}:{value:i.value,writable:!0}})}return r}export{c as wrapEffectBuilder};
2
2
  //# sourceMappingURL=api-runtime.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-runtime.mjs","names":["wrapEffectBuilder","original","definition","handler","args","program","normalizeEffect","options","ctx","Context","Effect","added","additionsPrototype","originalContext","key","context","services","exit","Exit","ConvexError","projectErrorCause","reason","Cause","builder"],"sources":["../../../src/modules/effect/api-runtime.ts"],"sourcesContent":["import { Cause, Context, Effect, Exit } from 'effect'\nimport type { Scope } from 'effect'\nimport { ConvexError, type Value } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions } from '../contracts/errors'\nimport { projectErrorCause } from './errors'\nimport { normalizeEffect } from './normalize'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Projection receives any expected failure and its result is always thrown, never returned as public data.\nexport type EffectApiErrorProjection = (error: unknown) => unknown\nexport type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\nexport type EffectApiHandlerValue<Value> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, unknown, unknown>\n\nexport type EffectApiServices =\n\t| Context.Context<never>\n\t| PromiseLike<Context.Context<never>>\n\t| Effect.Effect<Context.Context<never>, unknown, Scope.Scope>\nexport type ProvidedServices<Provider> =\n\tEffectValue<Provider> extends Context.Context<infer Services> ? Services : never\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- This inference constraint requires record-shaped additions; each adapter preserves its concrete inferred fields and runtime checks the record boundary.\nexport type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>\ntype KeysOfUnion<Value> = Value extends object ? keyof Value : never\nexport type CheckedContext<Ctx, Added> =\n\tExtract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never\nexport type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = (\n\t[ProvidedServices<Provider>] extends [never]\n\t\t? { services?: (ctx: Ctx) => Provider }\n\t\t: { services: (ctx: Ctx) => Provider }\n) & (\n\t[KeysOfUnion<EffectValue<Added>>] extends [never]\n\t\t? { context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n\t\t: { context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n) & (\n\t| { errors: EffectApiErrorContract; mapError?: never }\n\t| { errors?: never; mapError?: EffectApiErrorProjection }\n)\nexport type CheckedApiRequirements<Returned, Provider> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\n\n/** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */\nexport function wrapEffectBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn (definition: Function | { handler: Function }) => {\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native registration explicitly accepts a callable or an object with a handler.\n\t\tconst original = typeof definition === 'function' ? definition : definition.handler\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Private erased callback receives the context already constructed by the checked native/custom builder.\n\t\tconst handler = async (ctx: unknown, ...args: unknown[]) => {\n\t\t\tconst program = normalizeEffect(() =>\n\t\t\t\toptions.services ? options.services(ctx) : Context.empty(),\n\t\t\t).pipe(\n\t\t\t\tEffect.flatMap((services) =>\n\t\t\t\t\tnormalizeEffect(() => (options.context ? options.context(ctx) : {})).pipe(\n\t\t\t\t\t\tEffect.flatMap((added) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate erased context additions before enumerating or merging their fields.\n\t\t\t\t\t\t\t\tif (added === null || typeof added !== 'object')\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context must be an object')\n\t\t\t\t\t\t\t\tconst additionsPrototype = Object.getPrototypeOf(added)\n\t\t\t\t\t\t\t\tif (additionsPrototype !== Object.prototype && additionsPrototype !== null)\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context additions must be a plain record')\n\t\t\t\t\t\t\t\t// SAFETY: native and custom builders construct an object context before invoking this private handler.\n\t\t\t\t\t\t\t\tconst originalContext = ctx as object\n\t\t\t\t\t\t\t\tfor (const key of Reflect.ownKeys(added)) {\n\t\t\t\t\t\t\t\t\tif (key in originalContext)\n\t\t\t\t\t\t\t\t\t\tthrow Error(`Effect API context cannot replace ${String(key)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn options.context\n\t\t\t\t\t\t\t\t\t? Object.create(Object.getPrototypeOf(originalContext), {\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(originalContext),\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(added),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: ctx\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.flatMap((context) => normalizeEffect(() => original(context, ...args))),\n\t\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t// SAFETY: checked public signatures prohibit unprovided handler requirements and\n\t\t\t// permit only Scope in providers; services are constructed within this same scope.\n\t\t\tconst exit = await Effect.runPromiseExit(\n\t\t\t\tEffect.scoped(program) as Effect.Effect<unknown, unknown>,\n\t\t\t)\n\t\t\tif (Exit.isSuccess(exit)) return exit.value\n\t\t\tif (options.errors) {\n\t\t\t\t// SAFETY: declared projection copies validated JSON-safe fields; all other Causes have a fixed safe envelope.\n\t\t\t\tthrow new ConvexError(projectErrorCause(options.errors, exit.cause) as Value)\n\t\t\t}\n\t\t\tconst reason = exit.cause.reasons.length === 1 ? exit.cause.reasons[0] : undefined\n\t\t\tif (reason && Cause.isFailReason(reason)) {\n\t\t\t\tthrow options.mapError ? options.mapError(reason.error) : reason.error\n\t\t\t}\n\t\t\tif (reason && Cause.isDieReason(reason)) throw reason.defect\n\t\t\tthrow new Error('Effect API execution failed', { cause: exit.cause })\n\t\t}\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Preserve the original native callable or object registration form.\n\t\treturn builder(typeof definition === 'function' ? handler : { ...definition, handler })\n\t}\n}\n"],"mappings":"iNA+CA,SAAgBA,EACf,EACA,EAMW,CACX,MAAQ,IAAiD,CAExD,IAAMC,EAAW,OAAOC,GAAe,WAAaA,EAAaA,EAAW,QAEtEC,EAAU,MAAO,EAAc,GAAGC,IAAoB,CAC3D,IAAMC,EAAUC,MACfC,EAAQ,SAAWA,EAAQ,SAASC,CAAG,EAAIC,EAAQ,MAAM,CAC1D,CAAC,CAAC,KACDC,EAAO,QAAS,GACfJ,MAAuBC,EAAQ,QAAUA,EAAQ,QAAQC,CAAG,EAAI,CAAC,CAAE,CAAC,CAAC,KACpEE,EAAO,QAAS,GACfA,EAAO,SAAW,CAEjB,GAAsB,OAAOC,GAAU,WAAnCA,EACH,MAAM,MAAM,sCAAsC,EACnD,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,GAAIC,IAAuB,OAAO,WAAaA,IAAuB,KACrE,MAAM,MAAM,qDAAqD,EAElE,IAAMC,EAAkBL,EACxB,IAAK,IAAMM,KAAO,QAAQ,QAAQH,CAAK,EACtC,GAAIG,KAAOD,EACV,MAAM,MAAM,qCAAqC,OAAOC,CAAG,GAAG,EAEhE,OAAOP,EAAQ,QACZ,OAAO,OAAO,OAAO,eAAeM,CAAe,EAAG,CACtD,GAAG,OAAO,0BAA0BA,CAAe,EACnD,GAAG,OAAO,0BAA0BF,CAAK,CAC1C,CAAC,EACAH,CACJ,CAAC,CACF,EACAE,EAAO,QAAS,GAAYJ,MAAsBL,EAASc,EAAS,GAAGX,CAAI,CAAC,CAAC,EAC7EM,EAAO,eAAeM,CAAQ,CAC/B,CACD,CACD,EAGMC,EAAO,MAAMP,EAAO,eACzBA,EAAO,OAAOL,CAAO,CACtB,EACA,GAAIa,EAAK,UAAUD,CAAI,EAAG,OAAOA,EAAK,MACtC,GAAIV,EAAQ,OAEX,MAAM,IAAIY,EAAYC,EAAkBb,EAAQ,OAAQU,EAAK,KAAK,CAAU,EAE7E,IAAMI,EAASJ,EAAK,MAAM,QAAQ,SAAW,EAAIA,EAAK,MAAM,QAAQ,GAAK,IAAA,GAKzE,MAJII,GAAUC,EAAM,aAAaD,CAAM,EAChCd,EAAQ,SAAWA,EAAQ,SAASc,EAAO,KAAK,EAAIA,EAAO,MAE9DA,GAAUC,EAAM,YAAYD,CAAM,EAASA,EAAO,OAC5C,MAAM,8BAA+B,CAAE,MAAOJ,EAAK,KAAM,CAAC,CACrE,EAEA,OAAOM,EAAQ,OAAOrB,GAAe,WAAaC,EAAU,CAAE,GAAGD,EAAY,SAAQ,CAAC,CACvF,CACD"}
1
+ {"version":3,"file":"api-runtime.mjs","names":["wrapEffectBuilder","original","definition","handler","args","program","normalizeEffect","options","ctx","Context","Effect","added","additionsPrototype","originalContext","key","context","services","exit","Exit","ConvexError","projectErrorCause","reason","Cause","builder","withHandler","copy","descriptor","memoize"],"sources":["../../../src/modules/effect/api-runtime.ts"],"sourcesContent":["import { Cause, Context, Effect, Exit } from 'effect'\nimport type { Scope } from 'effect'\nimport { ConvexError, type Value } from 'convex/values'\nimport type { ErrorContract, ErrorDefinitions } from '../contracts/errors'\nimport { memoize } from '../contracts/lazy'\nimport { projectErrorCause } from './errors'\nimport { normalizeEffect } from './normalize'\nimport type { CallbackRequirements, EffectValue } from './operation'\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters, anti-slop/no-unknown-returns -- Projection receives any expected failure and its result is always thrown, never returned as public data.\nexport type EffectApiErrorProjection = (error: unknown) => unknown\nexport type EffectApiErrorContract = Pick<ErrorContract<ErrorDefinitions>, 'project'>\n\nexport type EffectApiHandlerValue<Value> =\n\t| Value\n\t| PromiseLike<Value>\n\t| Effect.Effect<Value, unknown, unknown>\n\nexport type EffectApiServices =\n\t| Context.Context<never>\n\t| PromiseLike<Context.Context<never>>\n\t| Effect.Effect<Context.Context<never>, unknown, Scope.Scope>\nexport type ProvidedServices<Provider> =\n\tEffectValue<Provider> extends Context.Context<infer Services> ? Services : never\n// oxlint-disable-next-line anti-slop/no-unsafe-dictionary-type -- This inference constraint requires record-shaped additions; each adapter preserves its concrete inferred fields and runtime checks the record boundary.\nexport type EffectApiContext = EffectApiHandlerValue<Record<string, unknown>>\ntype KeysOfUnion<Value> = Value extends object ? keyof Value : never\nexport type CheckedContext<Ctx, Added> =\n\tExtract<KeysOfUnion<EffectValue<Added>>, keyof Ctx> extends never ? unknown : never\nexport type EffectApiOptions<Ctx, Provider extends EffectApiServices, Added = {}> = (\n\t[ProvidedServices<Provider>] extends [never]\n\t\t? { services?: (ctx: Ctx) => Provider }\n\t\t: { services: (ctx: Ctx) => Provider }\n) & (\n\t[KeysOfUnion<EffectValue<Added>>] extends [never]\n\t\t? { context?: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n\t\t: { context: (ctx: Ctx) => Added & CheckedContext<Ctx, Added> }\n) & (\n\t| { errors: EffectApiErrorContract; mapError?: never }\n\t| { errors?: never; mapError?: EffectApiErrorProjection }\n)\nexport type CheckedApiRequirements<Returned, Provider> = [\n\tExclude<CallbackRequirements<NoInfer<Returned>>, ProvidedServices<Provider> | Scope.Scope>,\n] extends [never]\n\t? unknown\n\t: never\n\n/** Internal erasure is limited to the registration boundary; public adapters check A/E/R. */\nexport function wrapEffectBuilder(\n\tbuilder: Function,\n\toptions: {\n\t\tservices?: Function\n\t\tcontext?: Function\n\t\tmapError?: EffectApiErrorProjection\n\t\terrors?: EffectApiErrorContract\n\t},\n): Function {\n\treturn (definition: Function | { handler: Function }) => {\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Native registration explicitly accepts a callable or an object with a handler.\n\t\tconst original = typeof definition === 'function' ? definition : definition.handler\n\t\t// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Private erased callback receives the context already constructed by the checked native/custom builder.\n\t\tconst handler = async (ctx: unknown, ...args: unknown[]) => {\n\t\t\tconst program = normalizeEffect(() =>\n\t\t\t\toptions.services ? options.services(ctx) : Context.empty(),\n\t\t\t).pipe(\n\t\t\t\tEffect.flatMap((services) =>\n\t\t\t\t\tnormalizeEffect(() => (options.context ? options.context(ctx) : {})).pipe(\n\t\t\t\t\t\tEffect.flatMap((added) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Validate erased context additions before enumerating or merging their fields.\n\t\t\t\t\t\t\t\tif (added === null || typeof added !== 'object')\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context must be an object')\n\t\t\t\t\t\t\t\tconst additionsPrototype = Object.getPrototypeOf(added)\n\t\t\t\t\t\t\t\tif (additionsPrototype !== Object.prototype && additionsPrototype !== null)\n\t\t\t\t\t\t\t\t\tthrow Error('Effect API context additions must be a plain record')\n\t\t\t\t\t\t\t\t// SAFETY: native and custom builders construct an object context before invoking this private handler.\n\t\t\t\t\t\t\t\tconst originalContext = ctx as object\n\t\t\t\t\t\t\t\tfor (const key of Reflect.ownKeys(added)) {\n\t\t\t\t\t\t\t\t\tif (key in originalContext)\n\t\t\t\t\t\t\t\t\t\tthrow Error(`Effect API context cannot replace ${String(key)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn options.context\n\t\t\t\t\t\t\t\t\t? Object.create(Object.getPrototypeOf(originalContext), {\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(originalContext),\n\t\t\t\t\t\t\t\t\t\t\t...Object.getOwnPropertyDescriptors(added),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t: ctx\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tEffect.flatMap((context) => normalizeEffect(() => original(context, ...args))),\n\t\t\t\t\t\tEffect.provideContext(services),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t)\n\t\t\t// SAFETY: checked public signatures prohibit unprovided handler requirements and\n\t\t\t// permit only Scope in providers; services are constructed within this same scope.\n\t\t\tconst exit = await Effect.runPromiseExit(\n\t\t\t\tEffect.scoped(program) as Effect.Effect<unknown, unknown>,\n\t\t\t)\n\t\t\tif (Exit.isSuccess(exit)) return exit.value\n\t\t\tif (options.errors) {\n\t\t\t\t// SAFETY: declared projection copies validated JSON-safe fields; all other Causes have a fixed safe envelope.\n\t\t\t\tthrow new ConvexError(projectErrorCause(options.errors, exit.cause) as Value)\n\t\t\t}\n\t\t\tconst reason = exit.cause.reasons.length === 1 ? exit.cause.reasons[0] : undefined\n\t\t\tif (reason && Cause.isFailReason(reason)) {\n\t\t\t\tthrow options.mapError ? options.mapError(reason.error) : reason.error\n\t\t\t}\n\t\t\tif (reason && Cause.isDieReason(reason)) throw reason.defect\n\t\t\tthrow new Error('Effect API execution failed', { cause: exit.cause })\n\t\t}\n\t\t// oxlint-disable-next-line anti-slop/no-runtime-typeof -- Preserve the original native callable or object registration form.\n\t\treturn builder(typeof definition === 'function' ? handler : withHandler(definition, handler))\n\t}\n}\n\n/**\n * Object-spread equivalent that forwards accessors instead of reading them, so\n * getter-declared args and returns stay unread until the builder needs them.\n */\nfunction withHandler(definition: { handler: Function }, handler: Function) {\n\tconst copy = { handler }\n\tfor (const key of Reflect.ownKeys(definition)) {\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(definition, key)\n\t\tif (key === 'handler' || !descriptor?.enumerable) continue\n\t\tObject.defineProperty(copy, key, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: true,\n\t\t\t...(descriptor.get\n\t\t\t\t? { get: memoize(() => descriptor.get!.call(definition)) }\n\t\t\t\t: { value: descriptor.value, writable: true }),\n\t\t})\n\t}\n\treturn copy\n}\n"],"mappings":"iQAgDA,SAAgBA,EACf,EACA,EAMW,CACX,MAAQ,IAAiD,CAExD,IAAMC,EAAW,OAAOC,GAAe,WAAaA,EAAaA,EAAW,QAEtEC,EAAU,MAAO,EAAc,GAAGC,IAAoB,CAC3D,IAAMC,EAAUC,MACfC,EAAQ,SAAWA,EAAQ,SAASC,CAAG,EAAIC,EAAQ,MAAM,CAC1D,CAAC,CAAC,KACDC,EAAO,QAAS,GACfJ,MAAuBC,EAAQ,QAAUA,EAAQ,QAAQC,CAAG,EAAI,CAAC,CAAE,CAAC,CAAC,KACpEE,EAAO,QAAS,GACfA,EAAO,SAAW,CAEjB,GAAsB,OAAOC,GAAU,WAAnCA,EACH,MAAM,MAAM,sCAAsC,EACnD,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,GAAIC,IAAuB,OAAO,WAAaA,IAAuB,KACrE,MAAM,MAAM,qDAAqD,EAElE,IAAMC,EAAkBL,EACxB,IAAK,IAAMM,KAAO,QAAQ,QAAQH,CAAK,EACtC,GAAIG,KAAOD,EACV,MAAM,MAAM,qCAAqC,OAAOC,CAAG,GAAG,EAEhE,OAAOP,EAAQ,QACZ,OAAO,OAAO,OAAO,eAAeM,CAAe,EAAG,CACtD,GAAG,OAAO,0BAA0BA,CAAe,EACnD,GAAG,OAAO,0BAA0BF,CAAK,CAC1C,CAAC,EACAH,CACJ,CAAC,CACF,EACAE,EAAO,QAAS,GAAYJ,MAAsBL,EAASc,EAAS,GAAGX,CAAI,CAAC,CAAC,EAC7EM,EAAO,eAAeM,CAAQ,CAC/B,CACD,CACD,EAGMC,EAAO,MAAMP,EAAO,eACzBA,EAAO,OAAOL,CAAO,CACtB,EACA,GAAIa,EAAK,UAAUD,CAAI,EAAG,OAAOA,EAAK,MACtC,GAAIV,EAAQ,OAEX,MAAM,IAAIY,EAAYC,EAAkBb,EAAQ,OAAQU,EAAK,KAAK,CAAU,EAE7E,IAAMI,EAASJ,EAAK,MAAM,QAAQ,SAAW,EAAIA,EAAK,MAAM,QAAQ,GAAK,IAAA,GAKzE,MAJII,GAAUC,EAAM,aAAaD,CAAM,EAChCd,EAAQ,SAAWA,EAAQ,SAASc,EAAO,KAAK,EAAIA,EAAO,MAE9DA,GAAUC,EAAM,YAAYD,CAAM,EAASA,EAAO,OAC5C,MAAM,8BAA+B,CAAE,MAAOJ,EAAK,KAAM,CAAC,CACrE,EAEA,OAAOM,EAAQ,OAAOrB,GAAe,WAAaC,EAAUqB,EAAYtB,EAAYC,CAAO,CAAC,CAC7F,CACD,CAMA,SAASqB,EAAY,EAAmC,EAAmB,CAC1E,IAAMC,EAAO,CAAE,SAAQ,EACvB,IAAK,IAAMX,KAAO,QAAQ,QAAQZ,CAAU,EAAG,CAC9C,IAAMwB,EAAa,OAAO,yBAAyBxB,EAAYY,CAAG,EAC9DA,IAAQ,WAAcY,GAAY,YACtC,OAAO,eAAeD,EAAMX,EAAK,CAChC,aAAc,GACd,WAAY,GACZ,GAAIY,EAAW,IACZ,CAAE,IAAKC,MAAcD,EAAW,IAAK,KAAKxB,CAAU,CAAC,CAAE,EACvD,CAAE,MAAOwB,EAAW,MAAO,SAAU,EAAK,CAC9C,CAAC,CACF,CACA,OAAOD,CACR"}
@@ -1,12 +1,16 @@
1
1
  import { OperationExecutor, OperationPublicResult, OperationTool, OperationToolConverter, OperationToolDefinition, OperationToolJsonSchema, OperationToolOutcome, SelectedOperation, bindOperationExecutor, createOperationTools, operationToolDialect, selectOperation } from "../contracts/exposure.mjs";
2
2
  import { ContractDecoderError, ContractDecoderRequirements, ContractValidationError, EffectDecoder, decodeEffectContract, effectContract, effectSchema, effectStandardSchema } from "./schema.mjs";
3
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
3
4
  import { CallbackError, CallbackRequirements, EffectMiddlewareInput, EffectOperationArgument, EffectOperationError, EffectOperationHandlerResult, EffectOperationInput, EffectOperationRequirements, EffectOperationResult, EffectPreparation, EffectValue, effectOperationFactory } from "./operation.mjs";
4
5
  import { EffectZodApiBuilder, effectZodApiBuilder } from "./api-zod.mjs";
5
6
  import "./agent-tools.mjs";
7
+ import { FailureAuditEntry, FailureAuditOptions } from "./failure-audit.mjs";
8
+ import { EffectErrors, effectErrors } from "./failures.mjs";
9
+ import { ActionAuditWriterError, EffectActionDependencies, EffectActionRegistry } from "./action.mjs";
6
10
  import { EffectFoundationOptions, createEffectFoundation } from "./foundation.mjs";
7
11
  import { EffectIdempotencyPreparation, effectTransactionalIdempotency } from "./idempotency.mjs";
8
12
  import { EffectCrudConfig, EffectCrudContext, EffectCrudPage, EffectCrudPagination, EffectCrudRepository, EffectCrudTable, createEffectCrud } from "./crud.mjs";
9
13
  import { EffectApiBuilder, effectApiBuilder } from "./api.mjs";
10
14
  import { projectErrorCause } from "./errors.mjs";
11
15
  import { EffectReceiptProtectedWorkflowMutation, effectReceiptWorkflowMutation, effectTerminalWorkflowAttempt, effectWorkflowAttempt, effectWorkflowStatusBindings } from "./workflow.mjs";
12
- export { type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectApiBuilder, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type SelectedOperation, bindOperationExecutor, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
16
+ export { ActionAuditWriterError, type CallbackError, type CallbackRequirements, type ContractDecoderError, type ContractDecoderRequirements, ContractValidationError, type EffectActionDependencies, type EffectActionRegistry, type EffectApiBuilder, type EffectCrudConfig, type EffectCrudContext, type EffectCrudPage, type EffectCrudPagination, type EffectCrudRepository, type EffectCrudTable, type EffectDecoder, type EffectErrors, type EffectFoundationOptions, type EffectIdempotencyPreparation, type EffectMiddlewareInput, type EffectOperationArgument, type EffectOperationError, type EffectOperationHandlerResult, type EffectOperationInput, type EffectOperationRequirements, type EffectOperationResult, type EffectPreparation, type EffectReceiptProtectedWorkflowMutation, type EffectValue, type EffectZodApiBuilder, type FailureAuditEntry, type FailureAuditOptions, type NestedAuditMode, type OperationExecutor, type OperationPublicResult, type OperationTool, type OperationToolConverter, type OperationToolDefinition, type OperationToolJsonSchema, type OperationToolOutcome, type RequestScope, type SelectedOperation, bindOperationExecutor, createEffectCrud, createEffectFoundation, createOperationTools, decodeEffectContract, effectApiBuilder, effectContract, effectErrors, effectOperationFactory, effectReceiptWorkflowMutation, effectSchema, effectStandardSchema, effectTerminalWorkflowAttempt, effectTransactionalIdempotency, effectWorkflowAttempt, effectWorkflowStatusBindings, effectZodApiBuilder, operationToolDialect, projectErrorCause, selectOperation };
@@ -1 +1 @@
1
- import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"../contracts/exposure.mjs";import{projectErrorCause as i}from"./errors.mjs";import{effectZodApiBuilder as a}from"./api-zod.mjs";import{effectOperationFactory as o}from"./operation.mjs";import{ContractValidationError as s,decodeEffectContract as c,effectContract as l,effectSchema as u,effectStandardSchema as d}from"./schema.mjs";import{createEffectFoundation as f}from"./foundation.mjs";import{effectTransactionalIdempotency as p}from"./idempotency.mjs";import{createEffectCrud as m}from"./crud.mjs";import{effectApiBuilder as h}from"./api.mjs";import{effectReceiptWorkflowMutation as g,effectTerminalWorkflowAttempt as _,effectWorkflowAttempt as v,effectWorkflowStatusBindings as y}from"./workflow.mjs";export{s as ContractValidationError,e as bindOperationExecutor,m as createEffectCrud,f as createEffectFoundation,t as createOperationTools,c as decodeEffectContract,h as effectApiBuilder,l as effectContract,o as effectOperationFactory,g as effectReceiptWorkflowMutation,u as effectSchema,d as effectStandardSchema,_ as effectTerminalWorkflowAttempt,p as effectTransactionalIdempotency,v as effectWorkflowAttempt,y as effectWorkflowStatusBindings,a as effectZodApiBuilder,n as operationToolDialect,i as projectErrorCause,r as selectOperation};
1
+ import{bindOperationExecutor as e,createOperationTools as t,operationToolDialect as n,selectOperation as r}from"../contracts/exposure.mjs";import{projectErrorCause as i}from"./errors.mjs";import{effectZodApiBuilder as a}from"./api-zod.mjs";import{effectOperationFactory as o}from"./operation.mjs";import{ContractValidationError as s,decodeEffectContract as c,effectContract as l,effectSchema as u,effectStandardSchema as d}from"./schema.mjs";import{effectErrors as f}from"./failures.mjs";import{ActionAuditWriterError as p}from"./action.mjs";import{createEffectFoundation as m}from"./foundation.mjs";import{effectTransactionalIdempotency as h}from"./idempotency.mjs";import{createEffectCrud as g}from"./crud.mjs";import{effectApiBuilder as _}from"./api.mjs";import{effectReceiptWorkflowMutation as v,effectTerminalWorkflowAttempt as y,effectWorkflowAttempt as b,effectWorkflowStatusBindings as x}from"./workflow.mjs";export{p as ActionAuditWriterError,s as ContractValidationError,e as bindOperationExecutor,g as createEffectCrud,m as createEffectFoundation,t as createOperationTools,c as decodeEffectContract,_ as effectApiBuilder,l as effectContract,f as effectErrors,o as effectOperationFactory,v as effectReceiptWorkflowMutation,u as effectSchema,d as effectStandardSchema,y as effectTerminalWorkflowAttempt,h as effectTransactionalIdempotency,b as effectWorkflowAttempt,x as effectWorkflowStatusBindings,a as effectZodApiBuilder,n as operationToolDialect,i as projectErrorCause,r as selectOperation};
@@ -3,16 +3,18 @@ import { OperationPublicResult, SelectedOperation } from "../contracts/exposure.
3
3
  import { Observability } from "../../components/foundation/modules/observability/observability.mjs";
4
4
  import { AuditEntryInput } from "../../components/foundation/client.mjs";
5
5
  import { DomainAuditInput, DomainCommandContract, DomainContract } from "../contracts/domain.mjs";
6
+ import { NestedAuditMode, RequestScope } from "./scope.mjs";
6
7
  import { CallbackError, CallbackRequirements, CheckedEffectOperation, EffectOperationArgument, EffectOperationError, EffectOperationRequirements, EffectOperationResult, EffectValue, UnwrappedDefaultError, UnwrappedDefaultRequirements, ValidatedEffectOperations, effectOperationFactory } from "./operation.mjs";
8
+ import { FailureAuditOptions } from "./failure-audit.mjs";
7
9
  import { BoundOperations } from "../contracts/binding.mjs";
8
10
  import { AuditValue, AuditedOperations, DomainEffectFactory, DomainEffectImplementations, ExactDomainOperations, SharedEffectFactory } from "./domain.mjs";
9
11
  import { Effect } from "effect";
10
12
  //#region src/modules/effect/command.d.ts
11
13
  type Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>;
12
14
  type Callback = (...arguments_: never[]) => Supported<unknown>;
13
- type Resolver = (host: never) => Supported<unknown>;
14
- type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0];
15
- type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>;
15
+ export type Resolver = (host: never) => Supported<unknown>;
16
+ export type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0];
17
+ export type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>;
16
18
  type Operation = {
17
19
  input: ContractSchema;
18
20
  result: ContractSchema;
@@ -26,7 +28,7 @@ type Operation = {
26
28
  aggregates?: readonly string[];
27
29
  replayResult?: ContractSchema;
28
30
  };
29
- type Registry<Context> = Readonly<Record<string, Pick<Operation, 'input' | 'result' | 'classification' | 'handler' | 'audit'> & CheckedEffectOperation<Context>>>;
31
+ export type Registry<Context> = Readonly<Record<string, Pick<Operation, 'input' | 'result' | 'handler'> & Partial<Pick<Operation, 'classification' | 'audit'>> & CheckedEffectOperation<Context>>>;
30
32
  export type EffectCommandDependencies = {
31
33
  observability: Observability;
32
34
  checkPermission?: (host: never, input: {
@@ -34,8 +36,12 @@ export type EffectCommandDependencies = {
34
36
  operation: string;
35
37
  }) => Supported<void>;
36
38
  writeAudit: (host: never, entry: AuditEntryInput) => Supported<unknown>;
39
+ /** `fold` (default): an operation nested under an auditing operation leaves the audit to it. */
40
+ nestedAudit?: NestedAuditMode;
41
+ /** Host-free sink for failed operations; see `FailureAuditOptions`. */
42
+ auditFailure?: FailureAuditOptions;
37
43
  };
38
- type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never] ? unknown : Exclude<Policy, undefined> extends ((...arguments_: infer Arguments) => Supported<unknown>) ? Arguments extends [] ? unknown : Arguments[0] : unknown;
44
+ export type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never] ? unknown : Exclude<Policy, undefined> extends ((...arguments_: infer Arguments) => Supported<unknown>) ? Arguments extends [] ? unknown : Arguments[0] : unknown;
39
45
  type PolicyHost<Dependencies extends EffectCommandDependencies> = HostParameter<Dependencies['writeAudit']> & HostParameter<Dependencies['checkPermission']>;
40
46
  type HostCompatible<Resolve extends Resolver, Dependencies extends EffectCommandDependencies> = [HostOf<Resolve>] extends [PolicyHost<Dependencies>] ? unknown : {
41
47
  context: never;
@@ -67,7 +73,7 @@ export declare function bindEffectCommand<const Dependencies extends EffectComma
67
73
  contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
68
74
  context: Resolve;
69
75
  audit?: never;
70
- operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], Mode, never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>) => Operations;
76
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], Mode, never, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
71
77
  defaults?: {
72
78
  guard?: (context: DomainOf<Resolve>) => Guard;
73
79
  };
@@ -80,15 +86,15 @@ export declare function bindEffectCommand<const Dependencies extends EffectComma
80
86
  }, const Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands']>, Returned extends AuditValue, Guard = never>(configuration: {
81
87
  contract: Contract & NoInfer<Operations extends ExactDomainOperations<Operations, Contract['commands']> & ValidatedEffectOperations<Operations> ? unknown : never>;
82
88
  context: Resolve;
83
- audit: (resolution: DomainAuditInput<Contract['commands']>, context: DomainOf<Resolve>) => Returned;
84
- operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], true, [Returned] extends [never] ? never : (resolution: never, context: never) => Returned, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>>) => Operations;
89
+ audit: (resolution: DomainAuditInput<Contract['commands']>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
90
+ operations: (define: DomainEffectFactory<DomainOf<Resolve>, Contract['commands'], true, [Returned] extends [never] ? never : (resolution: never, context: never) => Returned, NoInfer<CallbackError<Guard>>, NoInfer<CallbackRequirements<Guard>>, Contract['errors']>) => Operations;
85
91
  defaults?: {
86
92
  guard?: (context: DomainOf<Resolve>) => Guard;
87
93
  };
88
94
  } & HostCompatible<Resolve, Dependencies>): ReturnType<typeof createEffectCommand<Resolve, AuditedOperations<BoundOperations<Operations, Contract['commands']>, (resolution: never, context: never) => Returned>, Dependencies, Guard>>;
89
95
  <Resolve extends Resolver, const Operations extends Readonly<Record<string, Pick<Operation, "classification" | "handler" | "input" | "result"> & CheckedEffectOperation<EffectValue<ReturnType<Resolve>>>>>, Returned extends AuditValue, Guard>(configuration: {
90
96
  context: Resolve;
91
- audit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>) => Returned;
97
+ audit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>, scope: RequestScope | undefined) => Returned;
92
98
  operations: (define: SharedEffectFactory<DomainOf<Resolve>, Guard>) => Operations & NoInfer<ValidatedEffectOperations<Operations>>;
93
99
  defaults?: {
94
100
  guard?: (context: DomainOf<Resolve>) => Guard;
@@ -1,2 +1,2 @@
1
- import{selectOperation as e}from"../contracts/exposure.mjs";import{memoize as t,registerLazyRegistry as n}from"../contracts/lazy.mjs";import{normalizeEffect as r,observationFailure as i}from"./normalize.mjs";import{effectOperationFactory as a}from"./operation.mjs";import{decodeEffectContract as o}from"./schema.mjs";import{CommandPermissionError as s,executeCommandLifecycle as c}from"../../components/foundation/modules/command/lifecycle.mjs";import{snapshotOperations as l}from"../contracts/binding.mjs";import{domainEffectFactory as u}from"./domain.mjs";import{Effect as d,Exit as f}from"effect";const p={succeed:d.succeed,suspend:d.suspend,flatMap:d.flatMap};function m(l){let u=t(()=>l.operations(a())),m=(e,t,n)=>d.suspend(()=>{let a=u();if(!Object.prototype.hasOwnProperty.call(a,e))throw Error(`The selected command operation is not configured`);let m=a[e];return d.flatMap(o(m.input,t),t=>{let a=t,u=l.observability.start({operation:e,classification:m.classification}),h=l.context;return r(()=>h(n)).pipe(d.flatMap(t=>c(p,{operation:e,classification:m.classification,context:t,command:a,permission:m.permission===void 0?void 0:()=>r(()=>{if(!l.checkPermission)throw new s(e);return l.checkPermission(n,{permission:m.permission,operation:e})}).pipe(d.asVoid),prepare:()=>r(()=>m.prepare?.(t,a)).pipe(d.map(e=>e?.kind===`execute`?{kind:`execute`,complete:e.complete?t=>r(()=>e.complete(t)).pipe(d.asVoid):void 0}:e)),decodeReplay:e=>o(m.replayResult??m.result,e),middleware:m.middleware?[e=>g(()=>m.middleware({...e,input:a}))]:[],defaultGuard:e=>r(()=>l.defaults?.guard?.(e)).pipe(d.asVoid),guard:e=>r(()=>m.guard?.(e,a)).pipe(d.asVoid),run:e=>g(()=>m.handler(a,e)),decodeResult:e=>o(m.result,e),audit:e=>r(()=>m.audit({command:a,result:e},t)),writeAudit:e=>r(()=>l.writeAudit(n,e)),aggregates:m.aggregates})),d.onExit(e=>d.sync(()=>{f.isSuccess(e)?u.completed():u.failed(i(e.cause))})))})});return n({withContext(e){return{exec:(t,n)=>m(t,n,e)}},expose(t,n){let r=u();if(!Object.hasOwn(r,n))throw Error(`The selected command operation is not configured`);return e(t,`mutation`,n,r[n])},exec:m},u)}function h(e){function t(t){let n=()=>{let e=t.contract?u(t.contract.commands??{},!0):a();return l(t.operations(e),t.contract,`commands`,t.audit)};return m({...t,...e,operations:n})}return t}function g(e){return r(e)}export{h as bindEffectCommand,m as createEffectCommand};
1
+ import{selectOperation as e}from"../contracts/exposure.mjs";import{memoize as t,registerLazyRegistry as n}from"../contracts/lazy.mjs";import{normalizeEffect as r,observationFailure as i}from"./normalize.mjs";import{effectOperationFactory as a}from"./operation.mjs";import{decodeEffectContract as o}from"./schema.mjs";import{CommandPermissionError as s,executeCommandLifecycle as c}from"../../components/foundation/modules/command/lifecycle.mjs";import{reportAuditWriteFailure as l,reportFailure as u}from"./failure-audit.mjs";import{auditFolded as d,enterRequestScope as f}from"./scope.mjs";import{snapshotOperations as p}from"../contracts/binding.mjs";import{domainEffectFactory as m}from"./domain.mjs";import{Cause as h,Effect as g,Exit as _}from"effect";const v={succeed:g.succeed,suspend:g.suspend,flatMap:g.flatMap};function y(p){let m=t(()=>p.operations(a())),y=p,b=y.contract?.errors,S=y.mode??`command`,C=(e,t,n)=>g.suspend(()=>{let a=m();if(!Object.prototype.hasOwnProperty.call(a,e))throw Error(`The selected command operation is not configured`);let y=a[e];return g.flatMap(o(y.input,t),t=>{let a=t,m=y.classification??S,C=y.audit,w=p.observability.start({operation:e,classification:m}),T=p.context;return f(e,C!==void 0,(t,f)=>r(()=>T(n)).pipe(g.flatMap(i=>c(v,{operation:e,classification:m,context:i,command:a,permission:y.permission===void 0?void 0:()=>r(()=>{if(!p.checkPermission)throw new s(e);return p.checkPermission(n,{permission:y.permission,operation:e})}).pipe(g.asVoid),prepare:()=>r(()=>y.prepare?.(i,a)).pipe(g.map(e=>e?.kind===`execute`?{kind:`execute`,complete:e.complete?t=>r(()=>e.complete(t)).pipe(g.asVoid):void 0}:e)),decodeReplay:e=>o(y.replayResult??y.result,e),middleware:y.middleware?[e=>x(()=>y.middleware({...e,input:a}))]:[],defaultGuard:e=>r(()=>p.defaults?.guard?.(e)).pipe(g.asVoid),guard:e=>r(()=>y.guard?.(e,a)).pipe(g.asVoid),run:e=>x(()=>y.handler(a,e)),decodeResult:e=>o(y.result,e),audit:e=>!C||S!==`action`&&d(p.nestedAudit,t)?g.succeed(null):r(()=>C({command:a,result:e},i,t?.scope)),writeAudit:i=>{let a=r(()=>p.writeAudit(n,i));return S===`action`?a.pipe(g.catchCause(n=>h.hasInterrupts(n)?g.failCause(n):l(p.auditFailure,{operation:e,classification:m,entered:t}))):a},aggregates:y.aggregates})),g.onExit(n=>g.sync(()=>{_.isSuccess(n)?w.completed():w.failed(i(n.cause))}).pipe(g.andThen(u(p.auditFailure,n,{kind:S,operation:e,classification:m,input:a,contract:b,entered:t,current:f}))))))})});return n({withContext(e){return{exec:(t,n)=>C(t,n,e)}},expose(t,n){let r=m();if(!Object.hasOwn(r,n))throw Error(`The selected command operation is not configured`);return e(t,`mutation`,n,r[n])},exec:C},m)}function b(e){function t(t){let n=()=>{let e=t.contract?m(t.contract.commands??{},!0,t.contract.errors):a();return p(t.operations(e),t.contract,`commands`,t.audit)};return y({...t,...e,operations:n})}return t}function x(e){return r(e)}export{b as bindEffectCommand,y as createEffectCommand};
2
2
  //# sourceMappingURL=command.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"command.mjs","names":["effectLifecycle","Effect","createEffectCommand","getOperations","memoize","configuration","effectOperationFactory","exec","operations","operation","definition","decodeEffectContract","input","command","decoded","observation","resolve","normalizeEffect","host","executeCommandLifecycle","CommandPermissionError","context","preparation","result","value","normalizeCommandResult","input_","enriched","entry","Exit","exit","observationFailure","registerLazyRegistry","selectOperation","owner","bindEffectCommand","buildOperations","definitions","domainEffectFactory","snapshotOperations","dependencies","invoke"],"sources":["../../../src/modules/effect/command.ts"],"sourcesContent":["import { memoize, registerLazyRegistry } from '../contracts/lazy'\n/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport { Effect, Exit } from 'effect'\nimport type { AuditEntryInput } from '../../components/foundation/client'\nimport type { ContractSchema } from '../contracts/contract'\nimport {\n\tselectOperation,\n\ttype SelectedOperation,\n\ttype OperationPublicResult,\n} from '../contracts/exposure'\nimport { decodeEffectContract } from './schema'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tCommandPermissionError,\n\texecuteCommandLifecycle,\n\ttype ExecutionKind,\n\ttype LifecycleAlgebra,\n\ttype LifecyclePreparation,\n} from '../../components/foundation/modules/command/lifecycle'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport type { Observability } from '../../components/foundation/modules/observability/observability'\nimport { normalizeEffect, observationFailure } from './normalize'\nimport {\n\teffectOperationFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype EffectValue,\n\ttype EffectOperationArgument,\n\ttype EffectOperationInput,\n\ttype EffectOperationHandlerResult,\n\ttype EffectPreparation,\n\ttype EffectOperationResult,\n\ttype EffectOperationError,\n\ttype EffectOperationRequirements,\n\ttype CheckedEffectOperation,\n\ttype UnwrappedDefaultError,\n\ttype UnwrappedDefaultRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\n\nimport type { DomainContract, DomainCommandContract, DomainAuditInput } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport {\n\tdomainEffectFactory,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n\ttype AuditedOperations,\n\ttype SharedEffectFactory,\n\ttype AuditValue,\n} from './domain'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\n// Heterogeneous storage constraints preserve concrete callbacks in inferred definitions.\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal callback storage; selected definitions retain concrete return contracts.\ntype Callback = (...arguments_: never[]) => Supported<unknown>\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Resolver constraint captures its concrete return in Resolve; it never exposes this storage type at exec.\ntype Resolver = (host: never) => Supported<unknown>\ntype HostOf<Resolve extends Resolver> = Parameters<Resolve>[0]\ntype DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>\ntype Operation = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\tclassification: string\n\thandler: Callback\n\taudit: Callback\n\tguard?: Callback\n\tprepare?: Callback\n\tmiddleware?: Callback\n\tpermission?: string\n\taggregates?: readonly string[]\n\treplayResult?: ContractSchema\n}\ntype Registry<Context> = Readonly<\n\tRecord<\n\t\tstring,\n\t\tPick<Operation, 'input' | 'result' | 'classification' | 'handler' | 'audit'> &\n\t\t\tCheckedEffectOperation<Context>\n\t>\n>\nexport type EffectCommandDependencies = {\n\tobservability: Observability\n\tcheckPermission?: (\n\t\thost: never,\n\t\tinput: { permission: string; operation: string },\n\t) => Supported<void>\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Audit writer storage; its concrete return/error/services remain in Dependencies.\n\twriteAudit: (host: never, entry: AuditEntryInput) => Supported<unknown>\n}\ntype HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never]\n\t? unknown\n\t: // oxlint-disable-next-line anti-slop/no-unknown-returns -- Conditional parameter-extraction predicate, not an executable callback contract.\n\t\tExclude<Policy, undefined> extends (...arguments_: infer Arguments) => Supported<unknown>\n\t\t? Arguments extends []\n\t\t\t? unknown\n\t\t\t: Arguments[0]\n\t\t: unknown\ntype PolicyHost<Dependencies extends EffectCommandDependencies> = HostParameter<\n\tDependencies['writeAudit']\n> &\n\tHostParameter<Dependencies['checkPermission']>\ntype HostCompatible<Resolve extends Resolver, Dependencies extends EffectCommandDependencies> = [\n\tHostOf<Resolve>,\n] extends [PolicyHost<Dependencies>]\n\t? unknown\n\t: { context: never }\ntype Factory<Resolve extends Resolver, Guard> = ReturnType<\n\ttypeof effectOperationFactory<\n\t\tDomainOf<Resolve>,\n\t\tRecord<never, never>,\n\t\tNoInfer<CallbackError<Guard>>,\n\t\tNoInfer<CallbackRequirements<Guard>>\n\t>\n>\nexport type EffectCommandConfiguration<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tGuard,\n> = {\n\tcontext: Resolve\n\toperations: (\n\t\tdefine: Factory<Resolve, Guard>,\n\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n}\ntype ErrorOf<Definition, Resolve, Dependencies, Guard> =\n\t| EffectOperationError<Definition>\n\t| CallbackError<Resolve | Dependencies[keyof Dependencies]>\n\t| UnwrappedDefaultError<Definition, Guard>\ntype RequirementsOf<Definition, Resolve, Dependencies, Guard> =\n\t| EffectOperationRequirements<Definition>\n\t| CallbackRequirements<Resolve | Dependencies[keyof Dependencies]>\n\t| UnwrappedDefaultRequirements<Definition, Guard>\ninterface EffectExecution extends ExecutionKind {\n\treadonly type: Effect.Effect<this['value'], unknown, unknown>\n}\nconst effectLifecycle: LifecycleAlgebra<EffectExecution> = {\n\tsucceed: Effect.succeed,\n\tsuspend: Effect.suspend,\n\tflatMap: Effect.flatMap,\n}\ntype RuntimeOperation<Context, Input, Raw, Result> = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\tclassification: string\n\tpermission?: string\n\taggregates?: readonly string[]\n\treplayResult?: ContractSchema\n\thandler: (input: Input, context: Context) => Supported<Raw>\n\tguard?: (context: Context, input: Input) => Supported<void>\n\tprepare?: (\n\t\tcontext: Context,\n\t\tinput: Input,\n\t) => Supported<EffectPreparation<Result, unknown, unknown>>\n\taudit: (\n\t\tresolution: { command: Input; result: Result },\n\t\tcontext: Context,\n\t) => Supported<Omit<AuditEntryInput, 'classification'> | null>\n\tmiddleware?: (input: {\n\t\toperation: string\n\t\tcommand: Input\n\t\tinput: Input\n\t\tcontext: Context\n\t\tnext: (options?: { context?: object }) => Effect.Effect<Raw, unknown, unknown>\n\t}) => Supported<Raw>\n}\n\n/** Internal registry constructor: the public Foundation binds host policies once. */\nexport function createEffectCommand<\n\tResolve extends Resolver,\n\tconst Operations extends Registry<DomainOf<Resolve>>,\n\tconst Dependencies extends EffectCommandDependencies,\n\tGuard = never,\n>(\n\tconfiguration: EffectCommandConfiguration<Resolve, Operations, Guard> &\n\t\tDependencies &\n\t\tHostCompatible<Resolve, Dependencies>,\n) {\n\tconst getOperations = memoize<Operations>(() =>\n\t\tconfiguration.operations(\n\t\t\teffectOperationFactory<\n\t\t\t\tDomainOf<Resolve>,\n\t\t\t\tRecord<never, never>,\n\t\t\t\tCallbackError<Guard>,\n\t\t\t\tCallbackRequirements<Guard>\n\t\t\t>(),\n\t\t),\n\t)\n\tconst exec = <Key extends Extract<keyof Operations, string>>(\n\t\toperation: Key,\n\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\thost: HostOf<Resolve>,\n\t): Effect.Effect<\n\t\tEffectOperationResult<Operations[Key]>,\n\t\tErrorOf<Operations[Key], Resolve, Dependencies, Guard>,\n\t\tRequirementsOf<Operations[Key], Resolve, Dependencies, Guard>\n\t> => {\n\t\tconst execution = Effect.suspend(() => {\n\t\t\tconst operations = getOperations()\n\t\t\tif (!Object.prototype.hasOwnProperty.call(operations, operation))\n\t\t\t\tthrow Error('The selected command operation is not configured')\n\t\t\t// SAFETY: this helper checked selected callbacks against their parsed schemas and domain context.\n\t\t\tconst definition = operations[operation] as Operations[Key] &\n\t\t\t\tRuntimeOperation<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tEffectOperationInput<Operations[Key]>,\n\t\t\t\t\tEffectOperationHandlerResult<Operations[Key]>,\n\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t>\n\t\t\t// SAFETY: selected command input was parsed by its own paired schema.\n\t\t\treturn Effect.flatMap(decodeEffectContract(definition.input, input), (decoded) => {\n\t\t\t\t// SAFETY: the selected operation's decoder owns this concrete domain input.\n\t\t\t\tconst command = decoded as EffectOperationInput<Operations[Key]>\n\t\t\t\tconst observation = configuration.observability.start({\n\t\t\t\t\toperation,\n\t\t\t\t\tclassification: definition.classification,\n\t\t\t\t})\n\t\t\t\t// SAFETY: resolver identity owns its concrete invocation return and host parameter.\n\t\t\t\tconst resolve = configuration.context as (host: HostOf<Resolve>) => ReturnType<Resolve>\n\t\t\t\treturn normalizeEffect(() => resolve(host)).pipe(\n\t\t\t\t\tEffect.flatMap((context) => {\n\t\t\t\t\t\tconst lifecycle = executeCommandLifecycle<\n\t\t\t\t\t\t\tEffectExecution,\n\t\t\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\t\t\tEffectOperationInput<Operations[Key]>,\n\t\t\t\t\t\t\tEffectOperationHandlerResult<Operations[Key]>,\n\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t\t\t>(effectLifecycle, {\n\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\tclassification: definition.classification,\n\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\tcommand,\n\t\t\t\t\t\t\tpermission:\n\t\t\t\t\t\t\t\tdefinition.permission === undefined\n\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t: () =>\n\t\t\t\t\t\t\t\t\t\t\tnormalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t\t\t\tif (!configuration.checkPermission)\n\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new CommandPermissionError(operation)\n\t\t\t\t\t\t\t\t\t\t\t\t// SAFETY: HostCompatible proves this invocation satisfies the configured policy host.\n\t\t\t\t\t\t\t\t\t\t\t\treturn configuration.checkPermission(host as never, {\n\t\t\t\t\t\t\t\t\t\t\t\t\tpermission: definition.permission!,\n\t\t\t\t\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t}).pipe(Effect.asVoid),\n\t\t\t\t\t\t\tprepare: () =>\n\t\t\t\t\t\t\t\tnormalizeEffect(() => definition.prepare?.(context, command)).pipe(\n\t\t\t\t\t\t\t\t\tEffect.map((preparation) => {\n\t\t\t\t\t\t\t\t\t\tif (preparation?.kind !== 'execute') return preparation\n\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\tkind: 'execute',\n\t\t\t\t\t\t\t\t\t\t\tcomplete: preparation.complete\n\t\t\t\t\t\t\t\t\t\t\t\t? (result) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tnormalizeEffect(() => preparation.complete!(result)).pipe(Effect.asVoid)\n\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t} satisfies LifecyclePreparation<\n\t\t\t\t\t\t\t\t\t\t\tEffectExecution,\n\t\t\t\t\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t// SAFETY: the selected final replay contract owns this result; operation types retain its E/R.\n\t\t\t\t\t\t\tdecodeReplay: (value) =>\n\t\t\t\t\t\t\t\tdecodeEffectContract(\n\t\t\t\t\t\t\t\t\tdefinition.replayResult ?? definition.result,\n\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t) as Effect.Effect<EffectOperationResult<Operations[Key]>, unknown, unknown>,\n\t\t\t\t\t\t\tmiddleware: definition.middleware\n\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t(input_) =>\n\t\t\t\t\t\t\t\t\t\t\tnormalizeCommandResult(() =>\n\t\t\t\t\t\t\t\t\t\t\t\tdefinition.middleware!({ ...input_, input: command }),\n\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t: [],\n\t\t\t\t\t\t\tdefaultGuard: (enriched) =>\n\t\t\t\t\t\t\t\tnormalizeEffect(() => configuration.defaults?.guard?.(enriched)).pipe(\n\t\t\t\t\t\t\t\t\tEffect.asVoid,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tguard: (enriched) =>\n\t\t\t\t\t\t\t\tnormalizeEffect(() => definition.guard?.(enriched, command)).pipe(Effect.asVoid),\n\t\t\t\t\t\t\trun: (enriched) =>\n\t\t\t\t\t\t\t\tnormalizeCommandResult(() => definition.handler(command, enriched)),\n\t\t\t\t\t\t\t// SAFETY: the selected contract owns the decoded result; the public operation retains decoder E/R.\n\t\t\t\t\t\t\tdecodeResult: (value) =>\n\t\t\t\t\t\t\t\tdecodeEffectContract(definition.result, value) as Effect.Effect<\n\t\t\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>,\n\t\t\t\t\t\t\t\t\tunknown,\n\t\t\t\t\t\t\t\t\tunknown\n\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\taudit: (result) =>\n\t\t\t\t\t\t\t\tnormalizeEffect(() => definition.audit({ command, result }, context)),\n\t\t\t\t\t\t\twriteAudit: (entry) =>\n\t\t\t\t\t\t\t\tnormalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t// SAFETY: HostCompatible proves this invocation satisfies the configured writer host.\n\t\t\t\t\t\t\t\t\treturn configuration.writeAudit(host as never, entry)\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\taggregates: definition.aggregates,\n\t\t\t\t\t\t})\n\t\t\t\t\t\treturn lifecycle\n\t\t\t\t\t}),\n\t\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\tif (Exit.isSuccess(exit)) observation.completed()\n\t\t\t\t\t\t\telse observation.failed(observationFailure(exit.cause))\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t})\n\t\t})\n\t\t// SAFETY: dispatch selects exactly this operation; callbacks preserve the concrete definition/policy E/R.\n\t\treturn execution as Effect.Effect<\n\t\t\tEffectOperationResult<Operations[Key]>,\n\t\t\tErrorOf<Operations[Key], Resolve, Dependencies, Guard>,\n\t\t\tRequirementsOf<Operations[Key], Resolve, Dependencies, Guard>\n\t\t>\n\t}\n\treturn registerLazyRegistry(\n\t\t{\n\t\t\t/** Bind invocation context without resolving it or running an operation. */\n\t\t\twithContext(context: HostOf<Resolve>) {\n\t\t\t\treturn {\n\t\t\t\t\texec: <Key extends Extract<keyof Operations, string>>(\n\t\t\t\t\t\toperation: Key,\n\t\t\t\t\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\t\t\t\t) => exec(operation, input, context),\n\t\t\t\t}\n\t\t\t},\n\t\t\texpose<const Owner extends symbol, const Key extends Extract<keyof Operations, string>>(\n\t\t\t\towner: Owner,\n\t\t\t\toperation: Key,\n\t\t\t): SelectedOperation<\n\t\t\t\tOwner,\n\t\t\t\tKey,\n\t\t\t\tOperations[Key]['input'],\n\t\t\t\tOperationPublicResult<Operations[Key]>\n\t\t\t> {\n\t\t\t\tconst operations = getOperations()\n\t\t\t\tif (!Object.hasOwn(operations, operation))\n\t\t\t\t\tthrow Error('The selected command operation is not configured')\n\t\t\t\treturn selectOperation(owner, 'mutation', operation, operations[operation])\n\t\t\t},\n\t\t\texec,\n\t\t},\n\t\tgetOperations,\n\t)\n}\n\n/** Bind trusted application policies without exposing a loose public command kernel. */\nexport function bindEffectCommand<const Dependencies extends EffectCommandDependencies>(\n\tdependencies: Dependencies,\n) {\n\ttype LooseRegistry<Context> = Readonly<\n\t\tRecord<\n\t\t\tstring,\n\t\t\tPick<Operation, 'input' | 'result' | 'classification' | 'handler'> &\n\t\t\t\tCheckedEffectOperation<Context>\n\t\t>\n\t>\n\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tcommands: Readonly<Record<string, DomainCommandContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<\n\t\t\tDomainOf<Resolve>,\n\t\t\tContract['commands'],\n\t\t\ttrue\n\t\t>,\n\t\tMode extends true,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['commands']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit?: never\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['commands'],\n\t\t\t\t\tMode,\n\t\t\t\t\tnever,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tBoundOperations<Operations, Contract['commands']> & {\n\t\t\t\t[Key in keyof Contract['commands']]: {\n\t\t\t\t\tclassification: Contract['commands'][Key]['classification']\n\t\t\t\t\taudit: Operations[Key]['audit']\n\t\t\t\t}\n\t\t\t},\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tcommands: Readonly<Record<string, DomainCommandContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands']>,\n\t\tReturned extends AuditValue,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['commands']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit: (\n\t\t\t\tresolution: DomainAuditInput<Contract['commands']>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['commands'],\n\t\t\t\t\ttrue,\n\t\t\t\t\t[Returned] extends [never] ? never : (resolution: never, context: never) => Returned,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tAuditedOperations<\n\t\t\t\tBoundOperations<Operations, Contract['commands']>,\n\t\t\t\t(resolution: never, context: never) => Returned\n\t\t\t>,\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends LooseRegistry<DomainOf<Resolve>>,\n\t\tReturned extends AuditValue,\n\t\tGuard,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontext: Resolve\n\t\t\taudit: (resolution: DomainAuditInput<Operations>, context: DomainOf<Resolve>) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: SharedEffectFactory<DomainOf<Resolve>, Guard>,\n\t\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tAuditedOperations<Operations, (resolution: never, context: never) => Returned>,\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends Registry<DomainOf<Resolve>>,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: EffectCommandConfiguration<Resolve, Operations, Guard> &\n\t\t\tHostCompatible<Resolve, Dependencies>,\n\t): ReturnType<typeof createEffectCommand<Resolve, Operations, Dependencies, Guard>>\n\tfunction command(configuration: {\n\t\tcontext: Resolver\n\t\tcontract?: DomainContract\n\t\taudit?: (resolution: never, context: never) => AuditValue\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { guard?: (context: never) => unknown }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst definitions = configuration.contract\n\t\t\t\t? domainEffectFactory(configuration.contract.commands ?? {}, true)\n\t\t\t\t: effectOperationFactory()\n\t\t\treturn snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: the overload chooses this exact inline or contracted helper factory.\n\t\t\t\t\tdefinitions as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'commands',\n\t\t\t\tconfiguration.audit,\n\t\t\t)\n\t\t}\n\n\t\t// SAFETY: overloads check callbacks and schemas; binding validates exact keys and snapshots runtime records.\n\t\treturn createEffectCommand({\n\t\t\t...configuration,\n\t\t\t...dependencies,\n\t\t\toperations: buildOperations,\n\t\t} as never)\n\t}\n\treturn command\n}\n\nfunction normalizeCommandResult<Value>(\n\tinvoke: () => Supported<Value>,\n): Effect.Effect<Value, unknown, unknown> {\n\t// SAFETY: selected definition helper checks the callback's normalized success against the schema input.\n\treturn normalizeEffect(invoke) as Effect.Effect<Value, unknown, unknown>\n}\n"],"mappings":"wlBAwIA,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iC,EACNlC,EAAc,WAEbgC,CACD,EACAhC,EAAc,SACd,WACAA,EAAc,KACf,CACD,EAGA,OAAOH,EAAoB,CAC1B,GAAGG,EACH,GAAGmC,EACH,WAAYJ,CACb,CAAU,CACX,CACA,OAAOvB,CACR,CAEA,SAASY,EACR,EACyC,CAEzC,OAAOR,EAAgBwB,CAAM,CAC9B"}
1
+ {"version":3,"file":"command.mjs","names":["effectLifecycle","Effect","createEffectCommand","getOperations","memoize","configuration","effectOperationFactory","internal","errorContract","kind","exec","operations","operation","definition","decodeEffectContract","input","command","decoded","classification","audit","observation","resolve","enterRequestScope","normalizeEffect","host","executeCommandLifecycle","CommandPermissionError","context","preparation","result","value","normalizeCommandResult","input_","enriched","auditFolded","entered","write","entry","Cause","cause","reportAuditWriteFailure","Exit","exit","observationFailure","reportFailure","registerLazyRegistry","selectOperation","owner","bindEffectCommand","buildOperations","definitions","domainEffectFactory","snapshotOperations","dependencies","invoke"],"sources":["../../../src/modules/effect/command.ts"],"sourcesContent":["import { memoize, registerLazyRegistry } from '../contracts/lazy'\n/* oxlint-disable anti-slop/no-unknown-returns, anti-slop/no-unsafe-dictionary-type -- Overload implementation storage is erased; public signatures retain concrete values, errors and services. */\nimport { Cause, Effect, Exit } from 'effect'\nimport type { AuditEntryInput } from '../../components/foundation/client'\nimport type { ContractSchema } from '../contracts/contract'\nimport {\n\tselectOperation,\n\ttype SelectedOperation,\n\ttype OperationPublicResult,\n} from '../contracts/exposure'\nimport { decodeEffectContract } from './schema'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport {\n\tCommandPermissionError,\n\texecuteCommandLifecycle,\n\ttype ExecutionKind,\n\ttype LifecycleAlgebra,\n\ttype LifecyclePreparation,\n} from '../../components/foundation/modules/command/lifecycle'\n// oxlint-disable-next-line cvx/component-boundaries -- SAFETY: Internal optional adapter shares the Effect-free Foundation lifecycle and types without entering the Convex component deployment graph.\nimport type { Observability } from '../../components/foundation/modules/observability/observability'\nimport { normalizeEffect, observationFailure } from './normalize'\nimport { reportAuditWriteFailure, reportFailure, type FailureAuditOptions } from './failure-audit'\nimport {\n\tauditFolded,\n\tenterRequestScope,\n\ttype NestedAuditMode,\n\ttype RequestScope,\n\ttype ScopeState,\n} from './scope'\nimport {\n\teffectOperationFactory,\n\ttype CallbackError,\n\ttype CallbackRequirements,\n\ttype EffectValue,\n\ttype EffectOperationArgument,\n\ttype EffectOperationInput,\n\ttype EffectOperationHandlerResult,\n\ttype EffectPreparation,\n\ttype EffectOperationResult,\n\ttype EffectOperationError,\n\ttype EffectOperationRequirements,\n\ttype CheckedEffectOperation,\n\ttype UnwrappedDefaultError,\n\ttype UnwrappedDefaultRequirements,\n\ttype ValidatedEffectOperations,\n} from './operation'\n\nimport type { DomainContract, DomainCommandContract, DomainAuditInput } from '../contracts/domain'\nimport { snapshotOperations, type BoundOperations } from '../contracts/binding'\nimport {\n\tdomainEffectFactory,\n\ttype DomainEffectFactory,\n\ttype DomainEffectImplementations,\n\ttype ExactDomainOperations,\n\ttype AuditedOperations,\n\ttype SharedEffectFactory,\n\ttype AuditValue,\n} from './domain'\n\ntype Supported<Value> = Value | PromiseLike<Value> | Effect.Effect<Value, unknown, unknown>\n// Heterogeneous storage constraints preserve concrete callbacks in inferred definitions.\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Internal callback storage; selected definitions retain concrete return contracts.\ntype Callback = (...arguments_: never[]) => Supported<unknown>\n// oxlint-disable-next-line anti-slop/no-unknown-returns -- Resolver constraint captures its concrete return in Resolve; it never exposes this storage type at exec.\nexport type Resolver = (host: never) => Supported<unknown>\nexport type HostOf<Resolve extends Resolver> = Parameters<Resolve>[0]\nexport type DomainOf<Resolve extends Resolver> = EffectValue<ReturnType<Resolve>>\ntype Operation = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\tclassification: string\n\thandler: Callback\n\taudit: Callback\n\tguard?: Callback\n\tprepare?: Callback\n\tmiddleware?: Callback\n\tpermission?: string\n\taggregates?: readonly string[]\n\treplayResult?: ContractSchema\n}\nexport type Registry<Context> = Readonly<\n\tRecord<\n\t\tstring,\n\t\tPick<Operation, 'input' | 'result' | 'handler'> &\n\t\t\tPartial<Pick<Operation, 'classification' | 'audit'>> &\n\t\t\tCheckedEffectOperation<Context>\n\t>\n>\nexport type EffectCommandDependencies = {\n\tobservability: Observability\n\tcheckPermission?: (\n\t\thost: never,\n\t\tinput: { permission: string; operation: string },\n\t) => Supported<void>\n\t// oxlint-disable-next-line anti-slop/no-unknown-returns -- Audit writer storage; its concrete return/error/services remain in Dependencies.\n\twriteAudit: (host: never, entry: AuditEntryInput) => Supported<unknown>\n\t/** `fold` (default): an operation nested under an auditing operation leaves the audit to it. */\n\tnestedAudit?: NestedAuditMode\n\t/** Host-free sink for failed operations; see `FailureAuditOptions`. */\n\tauditFailure?: FailureAuditOptions\n}\nexport type HostParameter<Policy> = [Exclude<Policy, undefined>] extends [never]\n\t? unknown\n\t: // oxlint-disable-next-line anti-slop/no-unknown-returns -- Conditional parameter-extraction predicate, not an executable callback contract.\n\t\tExclude<Policy, undefined> extends (...arguments_: infer Arguments) => Supported<unknown>\n\t\t? Arguments extends []\n\t\t\t? unknown\n\t\t\t: Arguments[0]\n\t\t: unknown\ntype PolicyHost<Dependencies extends EffectCommandDependencies> = HostParameter<\n\tDependencies['writeAudit']\n> &\n\tHostParameter<Dependencies['checkPermission']>\ntype HostCompatible<Resolve extends Resolver, Dependencies extends EffectCommandDependencies> = [\n\tHostOf<Resolve>,\n] extends [PolicyHost<Dependencies>]\n\t? unknown\n\t: { context: never }\ntype Factory<Resolve extends Resolver, Guard> = ReturnType<\n\ttypeof effectOperationFactory<\n\t\tDomainOf<Resolve>,\n\t\tRecord<never, never>,\n\t\tNoInfer<CallbackError<Guard>>,\n\t\tNoInfer<CallbackRequirements<Guard>>\n\t>\n>\nexport type EffectCommandConfiguration<\n\tResolve extends Resolver,\n\tOperations extends Registry<DomainOf<Resolve>>,\n\tGuard,\n> = {\n\tcontext: Resolve\n\toperations: (\n\t\tdefine: Factory<Resolve, Guard>,\n\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n}\ntype ErrorOf<Definition, Resolve, Dependencies, Guard> =\n\t| EffectOperationError<Definition>\n\t| CallbackError<Resolve | Dependencies[keyof Dependencies]>\n\t| UnwrappedDefaultError<Definition, Guard>\ntype RequirementsOf<Definition, Resolve, Dependencies, Guard> =\n\t| EffectOperationRequirements<Definition>\n\t| CallbackRequirements<Resolve | Dependencies[keyof Dependencies]>\n\t| UnwrappedDefaultRequirements<Definition, Guard>\ninterface EffectExecution extends ExecutionKind {\n\treadonly type: Effect.Effect<this['value'], unknown, unknown>\n}\nconst effectLifecycle: LifecycleAlgebra<EffectExecution> = {\n\tsucceed: Effect.succeed,\n\tsuspend: Effect.suspend,\n\tflatMap: Effect.flatMap,\n}\ntype RuntimeOperation<Context, Input, Raw, Result> = {\n\tinput: ContractSchema\n\tresult: ContractSchema\n\tclassification?: string\n\tpermission?: string\n\taggregates?: readonly string[]\n\treplayResult?: ContractSchema\n\thandler: (input: Input, context: Context) => Supported<Raw>\n\tguard?: (context: Context, input: Input) => Supported<void>\n\tprepare?: (\n\t\tcontext: Context,\n\t\tinput: Input,\n\t) => Supported<EffectPreparation<Result, unknown, unknown>>\n\taudit?: (\n\t\tresolution: { command: Input; result: Result },\n\t\tcontext: Context,\n\t\tscope: RequestScope | undefined,\n\t) => Supported<Omit<AuditEntryInput, 'classification'> | null>\n\tmiddleware?: (input: {\n\t\toperation: string\n\t\tcommand: Input\n\t\tinput: Input\n\t\tcontext: Context\n\t\tnext: (options?: { context?: object }) => Effect.Effect<Raw, unknown, unknown>\n\t}) => Supported<Raw>\n}\n\n/** Internal registry constructor: the public Foundation binds host policies once. */\nexport function createEffectCommand<\n\tResolve extends Resolver,\n\tconst Operations extends Registry<DomainOf<Resolve>>,\n\tconst Dependencies extends EffectCommandDependencies,\n\tGuard = never,\n>(\n\tconfiguration: EffectCommandConfiguration<Resolve, Operations, Guard> &\n\t\tDependencies &\n\t\tHostCompatible<Resolve, Dependencies>,\n) {\n\tconst getOperations = memoize<Operations>(() =>\n\t\tconfiguration.operations(\n\t\t\teffectOperationFactory<\n\t\t\t\tDomainOf<Resolve>,\n\t\t\t\tRecord<never, never>,\n\t\t\t\tCallbackError<Guard>,\n\t\t\t\tCallbackRequirements<Guard>\n\t\t\t>(),\n\t\t),\n\t)\n\t// SAFETY: the contracted overloads spread their checked `contract`, and the action binding its\n\t// `mode`, into this configuration.\n\tconst internal = configuration as {\n\t\tcontract?: Pick<DomainContract, 'errors'>\n\t\tmode?: 'action'\n\t}\n\tconst errorContract = internal.contract?.errors\n\tconst kind = internal.mode ?? 'command'\n\tconst exec = <Key extends Extract<keyof Operations, string>>(\n\t\toperation: Key,\n\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\thost: HostOf<Resolve>,\n\t): Effect.Effect<\n\t\tEffectOperationResult<Operations[Key]>,\n\t\tErrorOf<Operations[Key], Resolve, Dependencies, Guard>,\n\t\tRequirementsOf<Operations[Key], Resolve, Dependencies, Guard>\n\t> => {\n\t\tconst execution = Effect.suspend(() => {\n\t\t\tconst operations = getOperations()\n\t\t\tif (!Object.prototype.hasOwnProperty.call(operations, operation))\n\t\t\t\tthrow Error('The selected command operation is not configured')\n\t\t\t// SAFETY: this helper checked selected callbacks against their parsed schemas and domain context.\n\t\t\tconst definition = operations[operation] as Operations[Key] &\n\t\t\t\tRuntimeOperation<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tEffectOperationInput<Operations[Key]>,\n\t\t\t\t\tEffectOperationHandlerResult<Operations[Key]>,\n\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t>\n\t\t\t// SAFETY: selected command input was parsed by its own paired schema.\n\t\t\treturn Effect.flatMap(decodeEffectContract(definition.input, input), (decoded) => {\n\t\t\t\t// SAFETY: the selected operation's decoder owns this concrete domain input.\n\t\t\t\tconst command = decoded as EffectOperationInput<Operations[Key]>\n\t\t\t\tconst classification = definition.classification ?? kind\n\t\t\t\tconst audit = definition.audit\n\t\t\t\tconst observation = configuration.observability.start({ operation, classification })\n\t\t\t\t// SAFETY: resolver identity owns its concrete invocation return and host parameter.\n\t\t\t\tconst resolve = configuration.context as (host: HostOf<Resolve>) => ReturnType<Resolve>\n\t\t\t\tconst run = (entered: ScopeState | undefined, current: ScopeState) =>\n\t\t\t\t\tnormalizeEffect(() => resolve(host)).pipe(\n\t\t\t\t\t\tEffect.flatMap((context) => {\n\t\t\t\t\t\t\tconst lifecycle = executeCommandLifecycle<\n\t\t\t\t\t\t\t\tEffectExecution,\n\t\t\t\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\t\t\t\tEffectOperationInput<Operations[Key]>,\n\t\t\t\t\t\t\t\tEffectOperationHandlerResult<Operations[Key]>,\n\t\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t\t\t\t>(effectLifecycle, {\n\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\tclassification,\n\t\t\t\t\t\t\t\tcontext,\n\t\t\t\t\t\t\t\tcommand,\n\t\t\t\t\t\t\t\tpermission:\n\t\t\t\t\t\t\t\t\tdefinition.permission === undefined\n\t\t\t\t\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t\t\t\t\t: () =>\n\t\t\t\t\t\t\t\t\t\t\t\tnormalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t\t\t\t\tif (!configuration.checkPermission)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tthrow new CommandPermissionError(operation)\n\t\t\t\t\t\t\t\t\t\t\t\t\t// SAFETY: HostCompatible proves this invocation satisfies the configured policy host.\n\t\t\t\t\t\t\t\t\t\t\t\t\treturn configuration.checkPermission(host as never, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tpermission: definition.permission!,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\t\t\t}).pipe(Effect.asVoid),\n\t\t\t\t\t\t\t\tprepare: () =>\n\t\t\t\t\t\t\t\t\tnormalizeEffect(() => definition.prepare?.(context, command)).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.map((preparation) => {\n\t\t\t\t\t\t\t\t\t\t\tif (preparation?.kind !== 'execute') return preparation\n\t\t\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\t\t\tkind: 'execute',\n\t\t\t\t\t\t\t\t\t\t\t\tcomplete: preparation.complete\n\t\t\t\t\t\t\t\t\t\t\t\t\t? (result) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnormalizeEffect(() => preparation.complete!(result)).pipe(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tEffect.asVoid,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\t\t\t\t} satisfies LifecyclePreparation<\n\t\t\t\t\t\t\t\t\t\t\t\tEffectExecution,\n\t\t\t\t\t\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>\n\t\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t// SAFETY: the selected final replay contract owns this result; operation types retain its E/R.\n\t\t\t\t\t\t\t\tdecodeReplay: (value) =>\n\t\t\t\t\t\t\t\t\tdecodeEffectContract(\n\t\t\t\t\t\t\t\t\t\tdefinition.replayResult ?? definition.result,\n\t\t\t\t\t\t\t\t\t\tvalue,\n\t\t\t\t\t\t\t\t\t) as Effect.Effect<EffectOperationResult<Operations[Key]>, unknown, unknown>,\n\t\t\t\t\t\t\t\tmiddleware: definition.middleware\n\t\t\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t\t\t(input_) =>\n\t\t\t\t\t\t\t\t\t\t\t\tnormalizeCommandResult(() =>\n\t\t\t\t\t\t\t\t\t\t\t\t\tdefinition.middleware!({ ...input_, input: command }),\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t\t\t: [],\n\t\t\t\t\t\t\t\tdefaultGuard: (enriched) =>\n\t\t\t\t\t\t\t\t\tnormalizeEffect(() => configuration.defaults?.guard?.(enriched)).pipe(\n\t\t\t\t\t\t\t\t\t\tEffect.asVoid,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\tguard: (enriched) =>\n\t\t\t\t\t\t\t\t\tnormalizeEffect(() => definition.guard?.(enriched, command)).pipe(Effect.asVoid),\n\t\t\t\t\t\t\t\trun: (enriched) =>\n\t\t\t\t\t\t\t\t\tnormalizeCommandResult(() => definition.handler(command, enriched)),\n\t\t\t\t\t\t\t\t// SAFETY: the selected contract owns the decoded result; the public operation retains decoder E/R.\n\t\t\t\t\t\t\t\tdecodeResult: (value) =>\n\t\t\t\t\t\t\t\t\tdecodeEffectContract(definition.result, value) as Effect.Effect<\n\t\t\t\t\t\t\t\t\t\tEffectOperationResult<Operations[Key]>,\n\t\t\t\t\t\t\t\t\t\tunknown,\n\t\t\t\t\t\t\t\t\t\tunknown\n\t\t\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\t\taudit: (result) =>\n\t\t\t\t\t\t\t\t\t// Actions commit as they go, so a nested action's effects always need their own entry.\n\t\t\t\t\t\t\t\t\t!audit || (kind !== 'action' && auditFolded(configuration.nestedAudit, entered))\n\t\t\t\t\t\t\t\t\t\t? Effect.succeed(null)\n\t\t\t\t\t\t\t\t\t\t: normalizeEffect(() => audit({ command, result }, context, entered?.scope)),\n\t\t\t\t\t\t\t\twriteAudit: (entry) => {\n\t\t\t\t\t\t\t\t\tconst write = normalizeEffect(() => {\n\t\t\t\t\t\t\t\t\t\t// SAFETY: HostCompatible proves this invocation satisfies the configured writer host.\n\t\t\t\t\t\t\t\t\t\treturn configuration.writeAudit(host as never, entry)\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\treturn kind === 'action'\n\t\t\t\t\t\t\t\t\t\t? write.pipe(\n\t\t\t\t\t\t\t\t\t\t\t\tEffect.catchCause((cause) =>\n\t\t\t\t\t\t\t\t\t\t\t\t\tCause.hasInterrupts(cause)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? Effect.failCause(cause)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: reportAuditWriteFailure(configuration.auditFailure, {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tclassification,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tentered,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t\t: write\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\taggregates: definition.aggregates,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\treturn lifecycle\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tEffect.onExit((exit) =>\n\t\t\t\t\t\t\tEffect.sync(() => {\n\t\t\t\t\t\t\t\tif (Exit.isSuccess(exit)) observation.completed()\n\t\t\t\t\t\t\t\telse observation.failed(observationFailure(exit.cause))\n\t\t\t\t\t\t\t}).pipe(\n\t\t\t\t\t\t\t\tEffect.andThen(\n\t\t\t\t\t\t\t\t\treportFailure(configuration.auditFailure, exit, {\n\t\t\t\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\t\t\t\toperation,\n\t\t\t\t\t\t\t\t\t\tclassification,\n\t\t\t\t\t\t\t\t\t\tinput: command,\n\t\t\t\t\t\t\t\t\t\tcontract: errorContract,\n\t\t\t\t\t\t\t\t\t\tentered,\n\t\t\t\t\t\t\t\t\t\tcurrent,\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\treturn enterRequestScope(operation, audit !== undefined, run)\n\t\t\t})\n\t\t})\n\t\t// SAFETY: dispatch selects exactly this operation; callbacks preserve the concrete definition/policy E/R.\n\t\treturn execution as Effect.Effect<\n\t\t\tEffectOperationResult<Operations[Key]>,\n\t\t\tErrorOf<Operations[Key], Resolve, Dependencies, Guard>,\n\t\t\tRequirementsOf<Operations[Key], Resolve, Dependencies, Guard>\n\t\t>\n\t}\n\treturn registerLazyRegistry(\n\t\t{\n\t\t\t/** Bind invocation context without resolving it or running an operation. */\n\t\t\twithContext(context: HostOf<Resolve>) {\n\t\t\t\treturn {\n\t\t\t\t\texec: <Key extends Extract<keyof Operations, string>>(\n\t\t\t\t\t\toperation: Key,\n\t\t\t\t\t\tinput: EffectOperationArgument<Operations[Key]>,\n\t\t\t\t\t) => exec(operation, input, context),\n\t\t\t\t}\n\t\t\t},\n\t\t\texpose<const Owner extends symbol, const Key extends Extract<keyof Operations, string>>(\n\t\t\t\towner: Owner,\n\t\t\t\toperation: Key,\n\t\t\t): SelectedOperation<\n\t\t\t\tOwner,\n\t\t\t\tKey,\n\t\t\t\tOperations[Key]['input'],\n\t\t\t\tOperationPublicResult<Operations[Key]>\n\t\t\t> {\n\t\t\t\tconst operations = getOperations()\n\t\t\t\tif (!Object.hasOwn(operations, operation))\n\t\t\t\t\tthrow Error('The selected command operation is not configured')\n\t\t\t\treturn selectOperation(owner, 'mutation', operation, operations[operation])\n\t\t\t},\n\t\t\texec,\n\t\t},\n\t\tgetOperations,\n\t)\n}\n\n/** Bind trusted application policies without exposing a loose public command kernel. */\nexport function bindEffectCommand<const Dependencies extends EffectCommandDependencies>(\n\tdependencies: Dependencies,\n) {\n\ttype LooseRegistry<Context> = Readonly<\n\t\tRecord<\n\t\t\tstring,\n\t\t\tPick<Operation, 'input' | 'result' | 'classification' | 'handler'> &\n\t\t\t\tCheckedEffectOperation<Context>\n\t\t>\n\t>\n\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tcommands: Readonly<Record<string, DomainCommandContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<\n\t\t\tDomainOf<Resolve>,\n\t\t\tContract['commands'],\n\t\t\ttrue\n\t\t>,\n\t\tMode extends true,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['commands']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit?: never\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['commands'],\n\t\t\t\t\tMode,\n\t\t\t\t\tnever,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>,\n\t\t\t\t\tContract['errors']\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tBoundOperations<Operations, Contract['commands']> & {\n\t\t\t\t[Key in keyof Contract['commands']]: {\n\t\t\t\t\tclassification: Contract['commands'][Key]['classification']\n\t\t\t\t\taudit: Operations[Key]['audit']\n\t\t\t\t}\n\t\t\t},\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Contract extends DomainContract & {\n\t\t\tcommands: Readonly<Record<string, DomainCommandContract>>\n\t\t},\n\t\tconst Operations extends DomainEffectImplementations<DomainOf<Resolve>, Contract['commands']>,\n\t\tReturned extends AuditValue,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontract: Contract &\n\t\t\t\tNoInfer<\n\t\t\t\t\tOperations extends ExactDomainOperations<Operations, Contract['commands']> &\n\t\t\t\t\t\tValidatedEffectOperations<Operations>\n\t\t\t\t\t\t? unknown\n\t\t\t\t\t\t: never\n\t\t\t\t>\n\t\t\tcontext: Resolve\n\t\t\taudit: (\n\t\t\t\tresolution: DomainAuditInput<Contract['commands']>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: DomainEffectFactory<\n\t\t\t\t\tDomainOf<Resolve>,\n\t\t\t\t\tContract['commands'],\n\t\t\t\t\ttrue,\n\t\t\t\t\t[Returned] extends [never] ? never : (resolution: never, context: never) => Returned,\n\t\t\t\t\tNoInfer<CallbackError<Guard>>,\n\t\t\t\t\tNoInfer<CallbackRequirements<Guard>>,\n\t\t\t\t\tContract['errors']\n\t\t\t\t>,\n\t\t\t) => Operations\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tAuditedOperations<\n\t\t\t\tBoundOperations<Operations, Contract['commands']>,\n\t\t\t\t(resolution: never, context: never) => Returned\n\t\t\t>,\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends LooseRegistry<DomainOf<Resolve>>,\n\t\tReturned extends AuditValue,\n\t\tGuard,\n\t>(\n\t\tconfiguration: {\n\t\t\tcontext: Resolve\n\t\t\taudit: (\n\t\t\t\tresolution: DomainAuditInput<Operations>,\n\t\t\t\tcontext: DomainOf<Resolve>,\n\t\t\t\tscope: RequestScope | undefined,\n\t\t\t) => Returned\n\t\t\toperations: (\n\t\t\t\tdefine: SharedEffectFactory<DomainOf<Resolve>, Guard>,\n\t\t\t) => Operations & NoInfer<ValidatedEffectOperations<Operations>>\n\t\t\tdefaults?: { guard?: (context: DomainOf<Resolve>) => Guard }\n\t\t} & HostCompatible<Resolve, Dependencies>,\n\t): ReturnType<\n\t\ttypeof createEffectCommand<\n\t\t\tResolve,\n\t\t\tAuditedOperations<Operations, (resolution: never, context: never) => Returned>,\n\t\t\tDependencies,\n\t\t\tGuard\n\t\t>\n\t>\n\n\tfunction command<\n\t\tResolve extends Resolver,\n\t\tconst Operations extends Registry<DomainOf<Resolve>>,\n\t\tGuard = never,\n\t>(\n\t\tconfiguration: EffectCommandConfiguration<Resolve, Operations, Guard> &\n\t\t\tHostCompatible<Resolve, Dependencies>,\n\t): ReturnType<typeof createEffectCommand<Resolve, Operations, Dependencies, Guard>>\n\tfunction command(configuration: {\n\t\tcontext: Resolver\n\t\tcontract?: DomainContract\n\t\taudit?: (resolution: never, context: never, scope: never) => AuditValue\n\t\toperations: (define: never) => Readonly<Record<string, object>>\n\t\tdefaults?: { guard?: (context: never) => unknown }\n\t}): unknown {\n\t\tconst buildOperations = () => {\n\t\t\tconst definitions = configuration.contract\n\t\t\t\t? domainEffectFactory(\n\t\t\t\t\t\tconfiguration.contract.commands ?? {},\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\tconfiguration.contract.errors,\n\t\t\t\t\t)\n\t\t\t\t: effectOperationFactory()\n\t\t\treturn snapshotOperations(\n\t\t\t\tconfiguration.operations(\n\t\t\t\t\t// SAFETY: the overload chooses this exact inline or contracted helper factory.\n\t\t\t\t\tdefinitions as never,\n\t\t\t\t),\n\t\t\t\tconfiguration.contract,\n\t\t\t\t'commands',\n\t\t\t\tconfiguration.audit,\n\t\t\t)\n\t\t}\n\n\t\t// SAFETY: overloads check callbacks and schemas; binding validates exact keys and snapshots runtime records.\n\t\treturn createEffectCommand({\n\t\t\t...configuration,\n\t\t\t...dependencies,\n\t\t\toperations: buildOperations,\n\t\t} as never)\n\t}\n\treturn command\n}\n\nfunction normalizeCommandResult<Value>(\n\tinvoke: () => Supported<Value>,\n): Effect.Effect<Value, unknown, unknown> {\n\t// SAFETY: selected definition helper checks the callback's normalized success against the schema input.\n\treturn normalizeEffect(invoke) as Effect.Effect<Value, unknown, unknown>\n}\n"],"mappings":"qvBAqJA,MAAMA,EAAqD,CAC1D,QAASC,EAAO,QAChB,QAASA,EAAO,QAChB,QAASA,EAAO,OACjB,EA6BA,SAAgBC,EAMf,EAGC,CACD,IAAMC,EAAgBC,MACrBC,EAAc,WACbC,EAKE,CACH,CACD,EAGMC,EAAWF,EAIXG,EAAgBD,EAAS,UAAU,OACnCE,EAAOF,EAAS,MAAQ,UACxBG,GACL,EACA,EACA,IAMkBT,EAAO,YAAc,CACtC,IAAMU,EAAaR,EAAc,EACjC,GAAI,CAAC,OAAO,UAAU,eAAe,KAAKQ,EAAYC,CAAS,EAC9D,MAAM,MAAM,kDAAkD,EAE/D,IAAMC,EAAaF,EAAWC,GAQ9B,OAAOX,EAAO,QAAQa,EAAqBD,EAAW,MAAOE,CAAK,EAAI,GAAY,CAEjF,IAAMC,EAAUC,EACVC,EAAiBL,EAAW,gBAAkBJ,EAC9CU,EAAQN,EAAW,MACnBO,EAAcf,EAAc,cAAc,MAAM,CAAE,YAAW,gBAAe,CAAC,EAE7EgB,EAAUhB,EAAc,QA0H9B,OAAOiB,EAAkBV,EAAWO,IAAU,IAAA,IAzHjC,EAAiC,IAC7CI,MAAsBF,EAAQG,CAAI,CAAC,CAAC,CAAC,KACpCvB,EAAO,QAAS,GACGwB,EAMhBzB,EAAiB,CAClB,YACA,iBACA,UACA,UACA,WACCa,EAAW,aAAe,IAAA,GACvB,IAAA,OAEAU,MAAsB,CACrB,GAAI,CAAClB,EAAc,gBAClB,MAAM,IAAIqB,EAAuBd,CAAS,EAE3C,OAAOP,EAAc,gBAAgBmB,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