cvx-kit 0.1.32 → 0.1.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/oxlint/ownership.mjs +1 -1
- package/dist/oxlint/ownership.mjs.map +1 -1
- package/dist/oxlint/reserved-files.mjs +1 -1
- package/dist/oxlint/reserved-files.mjs.map +1 -1
- package/dist/zod-table.d.mts +36 -13
- package/dist/zod-table.mjs +1 -1
- package/dist/zod-table.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{architectureAnchor as e,createResolver as t,inspectArchitecture as n,resolveImport as r}from"./architecture.mjs";import{appFile as i,binding as a,componentRoot as o,consumerOptions as s,containsComponentReference as c,delegatingBody as l,exportedNames as u,imported as d,isDbAccess as f,isDbWrite as p,isExternalCall as m,isFunctionsImport as h,memberPath as g,metadata as _,propertyName as v,rootMember as y,sourceVisitors as b,typeOnlySource as x}from"./ast.mjs";import{basename as S,resolve as C}from"node:path";import{existsSync as w,realpathSync as T}from"node:fs";const E={"project-structure":{meta:_(`Validate the application tree, colocated tests, and module cycles.`,{structure:`{{file}}: {{message}}`}),create(t){let r=s.parse(t.options[0]??{}),i=C(t.cwd,r.convexDir);return(w(t.filename)?T(t.filename):C(t.filename))===e(i)?{Program(e){for(let i of n({cwd:t.cwd,convexDir:r.convexDir,componentDirs:r.componentDirs}))t.report({node:e,messageId:`structure`,data:{file:i.file,message:i.message}})}}:{}}},"root-wiring-only":{meta:_(`Keep root files limited to configuration, assembly, and component facades.`,{ownership:`Root files only wire configuration and components. Move behavior into domain/<module>/: {{reason}}.`}),create(e){let t=i(e);if(!t||t.includes(`/`))return{};let n=null,r=`business implementation`,a=!1,o=/^(?:convex\.config|auth\.config|vite\.config|vitest\.config|auth|schema|functions|triggers|foundation|http|crons)\.[cm]?[jt]s$/.test(t);function s(e){n??=e}return{Program(e){e.body.some(e=>e.type===`FunctionDeclaration`||e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`)&&s(e)},NewExpression(t){d(e,t.callee)&&t.arguments.some(t=>c(e,t))&&(a=!0)},CallExpression(n){d(e,n.callee)&&n.arguments.some(t=>c(e,t))&&(a=!0),(p(n)||m(e,n)||t===`schema.ts`&&d(e,n.callee)?.name!==`defineSchema`)&&s(n)},ArrowFunctionExpression(e){(!e.body||!l(e.body))&&s(e)},FunctionExpression(e){(!e.body||!l(e.body))&&s(e)},IfStatement:s,SwitchStatement:s,ConditionalExpression:s,ForStatement:s,ForOfStatement:s,WhileStatement:s,"Program:exit"(t){!o&&!a&&(n=t,r=`unknown root file; only declared component facades may add root source files`),n&&e.report({node:n,messageId:`ownership`,data:{reason:r}})}}}},"application-orchestration":{meta:_(`Reserve application/ for thin cross-domain coordination.`,{ownership:`application/ only coordinates two or more domains. Move schemas, providers, storage access, helpers, and business decisions into their owning domain.`}),create(e){if(!i(e)?.startsWith(`application/`))return{};let n=/* @__PURE__ */ new Set,a=t(),s=null;function c(e){s??=e}let l=b(e,(t,s)=>{if(x(t))return;let l=r(a,e.filename,s),u=l&&i(e,l),d=u?.match(/^domain\/([^/]+)\/(?:commands|queries|rules)(?:\.[cm]?[jt]s)?$/);d&&d[1]!==`shared`&&n.add(d[1]),u?.startsWith(`domain/`)&&!d&&!u.startsWith(`domain/shared/`)&&c(t),!u&&!o(e,e.filename)&&![`cvx-kit`,`cvx-kit/components/foundation`,`@convex-dev/workflow`,`convex/values`].includes(s)&&c(t)});return{...l,Program(e){let t=u(e);for(let n of e.body){n.type===`FunctionDeclaration`&&n.id&&!t.has(n.id.name)&&c(n);let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if((e?.type===`TSTypeAliasDeclaration`||e?.type===`TSInterfaceDeclaration`)&&c(n),e?.type===`VariableDeclaration`)for(let r of e.declarations)r.init&&[`ObjectExpression`,`ArrayExpression`,`Literal`].includes(r.init.type)&&c(r),n.type===`VariableDeclaration`&&r.id.type===`Identifier`&&!t.has(r.id.name)&&[`ArrowFunctionExpression`,`FunctionExpression`].includes(r.init?.type??``)&&c(r)}},CallExpression(t){l.CallExpression?.(t),(f(t)||m(e,t))&&c(t);let n=d(e,t.callee);n&&[`zod`,`zod/v4`].includes(n.source)&&c(t)},MemberExpression(t){let r=g(t);if(r.length>=4&&r[1]===`domain`){let i=d(e,y(t));i?.name===`internal`&&/_generated\/api/.test(i.source)&&n.add(r[2])}},NewExpression:c,IfStatement:c,SwitchStatement:c,ConditionalExpression:c,"Program:exit"(t){(n.size<2||s)&&e.report({node:s??t,messageId:`ownership`})}}}},"internal-function-ownership":{meta:_(`Place internal handlers with their owner, never in root, api/, or shared/.`,{ownership:`Declare system/internal handlers in domain/<module>/, cross-domain application/, migrations/, or an isolated component.`}),create(e){let t=i(e)??``;return o(e,e.filename)||/^(?:domain\/(?!shared\/)[^/]+\/|application\/|migrations\/)/.test(t)?{}:{CallExpression(t){if(t.callee.type===`CallExpression`)return;let n=d(e,t.callee);n&&(h(e,n.source)&&/^system(Query|Mutation|Action)$/.test(n.name)||/(?:_generated\/server|convex\/server)/.test(n.source)&&/^internal(Query|Mutation|Action)(Generic)?$/.test(n.name))&&e.report({node:t,messageId:`ownership`})}}}},"domain-file-responsibilities":{meta:_(`Keep invariants pure, reads read-only, shapes declarative, and I/O action-side.`,{ownership:`Respect this domain file responsibility: pure rules, read-only queries, declarative schemas/tables/constants, and external I/O only in actions or integrations.`}),create(e){let n=i(e)??``,s=n===`domain/table.ts`;if(!s&&!/^domain\/[^/]+\//.test(n)&&!o(e,e.filename))return{};let c=S(n).replace(/\.[cm]?[jt]s$/,``),l=c===`rules`,u=c===`queries`,g=[`schema`,`table`,`contracts`,`constants`].includes(c),_=/(?:^|\/)(?:actions|integrations|providers)(?:\/|\.)/.test(n)||/(?:^|_)actions\./.test(n),y=t(),C=null;function w(e){C??=e}let T=b(e,(t,n)=>{if(x(t))return;let a=r(y,e.filename,n),c=a&&i(e,a);s&&n!==`cvx-kit/zod-table`&&!/^domain\/[^/]+\/table(?:\.[cm]?[jt]s)?$/.test(c??``)&&w(t),l&&c&&!/(?:^|\/)(?:rules|constants)(?:\.[cm]?[jt]s)?$/.test(c)&&w(t),(l||u||g)&&!c&&!o(e,e.filename)&&![`zod`,`zod/v4`,`convex/values`,`cvx-kit`,`cvx-kit/zod-table`,`cvx-kit/errors`,`cvx-kit/contracts`].includes(n)&&w(t),u&&c&&/(?:^|\/)(?:commands|actions|integrations|providers)(?:[./]|$)/.test(c)&&w(t)});return{...T,Program(e){if(s)for(let t of e.body){if(t.type===`ImportDeclaration`||t.type===`EmptyStatement`)continue;let e=t.type===`ExportNamedDeclaration`?t.declaration:t;(e?.type!==`VariableDeclaration`||e.declarations.some(e=>e.init?.type!==`CallExpression`))&&w(t)}},CallExpression(t){if(T.CallExpression?.(t),s){let n=d(e,t.callee);
|
|
1
|
+
import{architectureAnchor as e,createResolver as t,inspectArchitecture as n,resolveImport as r}from"./architecture.mjs";import{appFile as i,binding as a,componentRoot as o,consumerOptions as s,containsComponentReference as c,delegatingBody as l,exportedNames as u,imported as d,isDbAccess as f,isDbWrite as p,isExternalCall as m,isFunctionsImport as h,memberPath as g,metadata as _,propertyName as v,rootMember as y,sourceVisitors as b,typeOnlySource as x}from"./ast.mjs";import{basename as S,resolve as C}from"node:path";import{existsSync as w,realpathSync as T}from"node:fs";const E={"project-structure":{meta:_(`Validate the application tree, colocated tests, and module cycles.`,{structure:`{{file}}: {{message}}`}),create(t){let r=s.parse(t.options[0]??{}),i=C(t.cwd,r.convexDir);return(w(t.filename)?T(t.filename):C(t.filename))===e(i)?{Program(e){for(let i of n({cwd:t.cwd,convexDir:r.convexDir,componentDirs:r.componentDirs}))t.report({node:e,messageId:`structure`,data:{file:i.file,message:i.message}})}}:{}}},"root-wiring-only":{meta:_(`Keep root files limited to configuration, assembly, and component facades.`,{ownership:`Root files only wire configuration and components. Move behavior into domain/<module>/: {{reason}}.`}),create(e){let t=i(e);if(!t||t.includes(`/`))return{};let n=null,r=`business implementation`,a=!1,o=/^(?:convex\.config|auth\.config|vite\.config|vitest\.config|auth|schema|functions|triggers|foundation|http|crons)\.[cm]?[jt]s$/.test(t);function s(e){n??=e}return{Program(e){e.body.some(e=>e.type===`FunctionDeclaration`||e.type===`ExportNamedDeclaration`&&e.declaration?.type===`FunctionDeclaration`)&&s(e)},NewExpression(t){d(e,t.callee)&&t.arguments.some(t=>c(e,t))&&(a=!0)},CallExpression(n){d(e,n.callee)&&n.arguments.some(t=>c(e,t))&&(a=!0),(p(n)||m(e,n)||t===`schema.ts`&&d(e,n.callee)?.name!==`defineSchema`)&&s(n)},ArrowFunctionExpression(e){(!e.body||!l(e.body))&&s(e)},FunctionExpression(e){(!e.body||!l(e.body))&&s(e)},IfStatement:s,SwitchStatement:s,ConditionalExpression:s,ForStatement:s,ForOfStatement:s,WhileStatement:s,"Program:exit"(t){!o&&!a&&(n=t,r=`unknown root file; only declared component facades may add root source files`),n&&e.report({node:n,messageId:`ownership`,data:{reason:r}})}}}},"application-orchestration":{meta:_(`Reserve application/ for thin cross-domain coordination.`,{ownership:`application/ only coordinates two or more domains. Move schemas, providers, storage access, helpers, and business decisions into their owning domain.`}),create(e){if(!i(e)?.startsWith(`application/`))return{};let n=/* @__PURE__ */ new Set,a=t(),s=null;function c(e){s??=e}let l=b(e,(t,s)=>{if(x(t))return;let l=r(a,e.filename,s),u=l&&i(e,l),d=u?.match(/^domain\/([^/]+)\/(?:commands|queries|rules)(?:\.[cm]?[jt]s)?$/);d&&d[1]!==`shared`&&n.add(d[1]),u?.startsWith(`domain/`)&&!d&&!u.startsWith(`domain/shared/`)&&c(t),!u&&!o(e,e.filename)&&![`cvx-kit`,`cvx-kit/components/foundation`,`@convex-dev/workflow`,`convex/values`].includes(s)&&c(t)});return{...l,Program(e){let t=u(e);for(let n of e.body){n.type===`FunctionDeclaration`&&n.id&&!t.has(n.id.name)&&c(n);let e=n.type===`ExportNamedDeclaration`?n.declaration:n;if((e?.type===`TSTypeAliasDeclaration`||e?.type===`TSInterfaceDeclaration`)&&c(n),e?.type===`VariableDeclaration`)for(let r of e.declarations)r.init&&[`ObjectExpression`,`ArrayExpression`,`Literal`].includes(r.init.type)&&c(r),n.type===`VariableDeclaration`&&r.id.type===`Identifier`&&!t.has(r.id.name)&&[`ArrowFunctionExpression`,`FunctionExpression`].includes(r.init?.type??``)&&c(r)}},CallExpression(t){l.CallExpression?.(t),(f(t)||m(e,t))&&c(t);let n=d(e,t.callee);n&&[`zod`,`zod/v4`].includes(n.source)&&c(t)},MemberExpression(t){let r=g(t);if(r.length>=4&&r[1]===`domain`){let i=d(e,y(t));i?.name===`internal`&&/_generated\/api/.test(i.source)&&n.add(r[2])}},NewExpression:c,IfStatement:c,SwitchStatement:c,ConditionalExpression:c,"Program:exit"(t){(n.size<2||s)&&e.report({node:s??t,messageId:`ownership`})}}}},"internal-function-ownership":{meta:_(`Place internal handlers with their owner, never in root, api/, or shared/.`,{ownership:`Declare system/internal handlers in domain/<module>/, cross-domain application/, migrations/, or an isolated component.`}),create(e){let t=i(e)??``;return o(e,e.filename)||/^(?:domain\/(?!shared\/)[^/]+\/|application\/|migrations\/)/.test(t)?{}:{CallExpression(t){if(t.callee.type===`CallExpression`)return;let n=d(e,t.callee);n&&(h(e,n.source)&&/^system(Query|Mutation|Action)$/.test(n.name)||/(?:_generated\/server|convex\/server)/.test(n.source)&&/^internal(Query|Mutation|Action)(Generic)?$/.test(n.name))&&e.report({node:t,messageId:`ownership`})}}}},"domain-file-responsibilities":{meta:_(`Keep invariants pure, reads read-only, shapes declarative, and I/O action-side.`,{ownership:`Respect this domain file responsibility: pure rules, read-only queries, declarative schemas/tables/constants, and external I/O only in actions or integrations.`}),create(e){let n=i(e)??``,s=n===`domain/table.ts`;if(!s&&!/^domain\/[^/]+\//.test(n)&&!o(e,e.filename))return{};let c=S(n).replace(/\.[cm]?[jt]s$/,``),l=c===`rules`,u=c===`queries`,g=[`schema`,`table`,`contracts`,`constants`].includes(c),_=/(?:^|\/)(?:actions|integrations|providers)(?:\/|\.)/.test(n)||/(?:^|_)actions\./.test(n),y=t(),C=null;function w(e){C??=e}let T=b(e,(t,n)=>{if(x(t))return;let a=r(y,e.filename,n),c=a&&i(e,a);s&&n!==`cvx-kit/zod-table`&&!/^domain\/[^/]+\/table(?:\.[cm]?[jt]s)?$/.test(c??``)&&w(t),l&&c&&!/(?:^|\/)(?:rules|constants)(?:\.[cm]?[jt]s)?$/.test(c)&&w(t),(l||u||g)&&!c&&!o(e,e.filename)&&![`zod`,`zod/v4`,`convex/values`,`cvx-kit`,`cvx-kit/zod-table`,`cvx-kit/errors`,`cvx-kit/contracts`].includes(n)&&w(t),u&&c&&/(?:^|\/)(?:commands|actions|integrations|providers)(?:[./]|$)/.test(c)&&w(t)});return{...T,Program(e){if(s)for(let t of e.body){if(t.type===`ImportDeclaration`||t.type===`EmptyStatement`)continue;let e=t.type===`ExportNamedDeclaration`?t.declaration:t;(e?.type!==`VariableDeclaration`||e.declarations.some(e=>e.init?.type!==`CallExpression`))&&w(t)}},CallExpression(t){if(T.CallExpression?.(t),s){let n=d(e,t.callee);n?.source===`cvx-kit/zod-table`&&n.name===`createModule`||n?.source===`cvx-kit/zod-table`&&n.name===`namespaceIndex`||w(t)}let n=t.callee.type===`MemberExpression`?v(t.callee):null;(l||g)&&(f(t)||[`runQuery`,`runMutation`,`runAction`,`runAfter`,`runAt`].includes(n??``))&&w(t),u&&(p(t)||[`runMutation`,`runAction`,`runAfter`,`runAt`].includes(n??``))&&w(t);let r=d(e,t.callee);r&&h(e,r.source)&&(l||g||u&&/(?:Mutation|Action)$/.test(r.name))&&w(t),u&&t.callee.type===`MemberExpression`&&v(t.callee.object)===`storage`&&[`store`,`delete`,`generateUploadUrl`].includes(n??``)&&w(t),!_&&m(e,t)&&w(t),l&&t.callee.type===`MemberExpression`&&t.callee.object.type===`Identifier`&&!a(e,t.callee.object)?.defs.length&&(t.callee.object.name===`Date`&&n===`now`||t.callee.object.name===`Math`&&n===`random`)&&w(t)},Property(e){c===`contracts`&&[`handler`,`context`,`audit`,`prepare`,`middleware`,`guard`].includes(e.key.type===`Identifier`?e.key.name:String(e.key.type===`Literal`?e.key.value:``))&&w(e)},MemberExpression(e){l&&[`db`,`storage`,`scheduler`,`env`].includes(v(e)??``)&&w(e)},NewExpression(t){(l||u||g)&&(t.callee.type!==`Identifier`||a(e,t.callee)?.defs.length||![`Error`,`TypeError`,`RangeError`,`Set`,`Map`,`RegExp`].includes(t.callee.name))&&w(t)},"Program:exit"(){C&&e.report({node:C,messageId:`ownership`})}}}}};export{E as ownershipRules};
|
|
2
2
|
//# sourceMappingURL=ownership.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.mjs","names":["ownershipRules","metadata","settings","consumerOptions","context","root","resolve","existsSync","realpathSync","architectureAnchor","issue","inspectArchitecture","file","appFile","reason","componentFacade","standard","flag","node","statement","imported","containsComponentReference","argument","isDbWrite","isExternalCall","delegatingBody","owners","resolver","createResolver","sources","sourceVisitors","typeOnlySource","target","resolveImport","source","path","match","componentRoot","publicNames","exportedNames","declaration","item","isDbAccess","ref","memberPath","rootMember","isFunctionsImport","assembly","role","basename","pure","read","declarative","actionSide","method","propertyName","constructor","binding"],"sources":["../../src/oxlint/ownership.ts"],"sourcesContent":["import { existsSync, realpathSync } from 'node:fs'\nimport { basename, resolve } from 'node:path'\nimport type { CreateRule, ESTree } from '@oxlint/plugins'\nimport {\n\tarchitectureAnchor,\n\tinspectArchitecture,\n\tcreateResolver,\n\tresolveImport,\n} from './architecture'\nimport {\n\tconsumerOptions,\n\tappFile,\n\timported,\n\tsourceVisitors,\n\tisFunctionsImport,\n\ttypeOnlySource,\n\tisDbAccess,\n\tisExternalCall,\n\tcontainsComponentReference,\n\trootMember,\n\tmemberPath,\n\tisDbWrite,\n\tmetadata,\n\tcomponentRoot,\n\tpropertyName,\n\tbinding,\n\texportedNames,\n\tdelegatingBody,\n} from './ast'\n\nexport const ownershipRules = {\n\t'project-structure': {\n\t\tmeta: metadata('Validate the application tree, colocated tests, and module cycles.', {\n\t\t\tstructure: '{{file}}: {{message}}',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst settings = consumerOptions.parse(context.options[0] ?? {})\n\t\t\tconst root = resolve(context.cwd, settings.convexDir)\n\t\t\tif (\n\t\t\t\t(existsSync(context.filename)\n\t\t\t\t\t? realpathSync(context.filename)\n\t\t\t\t\t: resolve(context.filename)) !== architectureAnchor(root)\n\t\t\t)\n\t\t\t\treturn {}\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tfor (const issue of inspectArchitecture({\n\t\t\t\t\t\tcwd: context.cwd,\n\t\t\t\t\t\tconvexDir: settings.convexDir,\n\t\t\t\t\t\tcomponentDirs: settings.componentDirs,\n\t\t\t\t\t}))\n\t\t\t\t\t\tcontext.report({\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tmessageId: 'structure',\n\t\t\t\t\t\t\tdata: { file: issue.file, message: issue.message },\n\t\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'root-wiring-only': {\n\t\tmeta: metadata('Keep root files limited to configuration, assembly, and component facades.', {\n\t\t\townership:\n\t\t\t\t'Root files only wire configuration and components. Move behavior into domain/<module>/: {{reason}}.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context)\n\t\t\tif (!file || file.includes('/')) return {}\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tlet reason = 'business implementation'\n\t\t\tlet componentFacade = false\n\t\t\tconst standard =\n\t\t\t\t/^(?:convex\\.config|auth\\.config|vite\\.config|vitest\\.config|auth|schema|functions|triggers|foundation|http|crons)\\.[cm]?[jt]s$/.test(\n\t\t\t\t\tfile,\n\t\t\t\t)\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.body.some(\n\t\t\t\t\t\t\t(statement) =>\n\t\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' ||\n\t\t\t\t\t\t\t\t(statement.type === 'ExportNamedDeclaration' &&\n\t\t\t\t\t\t\t\t\tstatement.declaration?.type === 'FunctionDeclaration'),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tNewExpression(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\timported(context, node.callee) &&\n\t\t\t\t\t\tnode.arguments.some((argument) => containsComponentReference(context, argument))\n\t\t\t\t\t)\n\t\t\t\t\t\tcomponentFacade = true\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\timported(context, node.callee) &&\n\t\t\t\t\t\tnode.arguments.some((argument) => containsComponentReference(context, argument))\n\t\t\t\t\t)\n\t\t\t\t\t\tcomponentFacade = true\n\t\t\t\t\tif (\n\t\t\t\t\t\tisDbWrite(node) ||\n\t\t\t\t\t\tisExternalCall(context, node) ||\n\t\t\t\t\t\t(file === 'schema.ts' && !(imported(context, node.callee)?.name === 'defineSchema'))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tArrowFunctionExpression(node) {\n\t\t\t\t\tif (!node.body || !delegatingBody(node.body)) flag(node)\n\t\t\t\t},\n\t\t\t\tFunctionExpression(node) {\n\t\t\t\t\tif (!node.body || !delegatingBody(node.body)) flag(node)\n\t\t\t\t},\n\t\t\t\tIfStatement: flag,\n\t\t\t\tSwitchStatement: flag,\n\t\t\t\tConditionalExpression: flag,\n\t\t\t\tForStatement: flag,\n\t\t\t\tForOfStatement: flag,\n\t\t\t\tWhileStatement: flag,\n\t\t\t\t'Program:exit'(node) {\n\t\t\t\t\tif (!standard && !componentFacade) {\n\t\t\t\t\t\tissue = node\n\t\t\t\t\t\treason = 'unknown root file; only declared component facades may add root source files'\n\t\t\t\t\t}\n\t\t\t\t\tif (issue) context.report({ node: issue, messageId: 'ownership', data: { reason } })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'application-orchestration': {\n\t\tmeta: metadata('Reserve application/ for thin cross-domain coordination.', {\n\t\t\townership:\n\t\t\t\t'application/ only coordinates two or more domains. Move schemas, providers, storage access, helpers, and business decisions into their owning domain.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tif (!appFile(context)?.startsWith('application/')) return {}\n\t\t\tconst owners = new Set<string>()\n\t\t\tconst resolver = createResolver()\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\tconst sources = sourceVisitors(context, (node, source) => {\n\t\t\t\tif (typeOnlySource(node)) return\n\t\t\t\tconst target = resolveImport(resolver, context.filename, source)\n\t\t\t\tconst path = target && appFile(context, target)\n\t\t\t\tconst match = path?.match(/^domain\\/([^/]+)\\/(?:commands|queries|rules)(?:\\.[cm]?[jt]s)?$/)\n\t\t\t\tif (match && match[1] !== 'shared') owners.add(match[1])\n\t\t\t\tif (path?.startsWith('domain/') && !match && !path.startsWith('domain/shared/')) flag(node)\n\t\t\t\tif (\n\t\t\t\t\t!path &&\n\t\t\t\t\t!componentRoot(context, context.filename) &&\n\t\t\t\t\t![\n\t\t\t\t\t\t'cvx-kit',\n\t\t\t\t\t\t'cvx-kit/components/foundation',\n\t\t\t\t\t\t'@convex-dev/workflow',\n\t\t\t\t\t\t'convex/values',\n\t\t\t\t\t].includes(source)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...sources,\n\t\t\t\tProgram(node) {\n\t\t\t\t\tconst publicNames = exportedNames(node)\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' &&\n\t\t\t\t\t\t\tstatement.id &&\n\t\t\t\t\t\t\t!publicNames.has(statement.id.name)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t\tconst declaration =\n\t\t\t\t\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tdeclaration?.type === 'TSTypeAliasDeclaration' ||\n\t\t\t\t\t\t\tdeclaration?.type === 'TSInterfaceDeclaration'\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t\tif (declaration?.type === 'VariableDeclaration')\n\t\t\t\t\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\titem.init &&\n\t\t\t\t\t\t\t\t\t['ObjectExpression', 'ArrayExpression', 'Literal'].includes(item.init.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tflag(item)\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tstatement.type === 'VariableDeclaration' &&\n\t\t\t\t\t\t\t\t\titem.id.type === 'Identifier' &&\n\t\t\t\t\t\t\t\t\t!publicNames.has(item.id.name) &&\n\t\t\t\t\t\t\t\t\t['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type ?? '')\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tflag(item)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tsources.CallExpression?.(node)\n\t\t\t\t\tif (isDbAccess(node) || isExternalCall(context, node)) flag(node)\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (ref && ['zod', 'zod/v4'].includes(ref.source)) flag(node)\n\t\t\t\t},\n\t\t\t\tMemberExpression(node) {\n\t\t\t\t\tconst path = memberPath(node)\n\t\t\t\t\tif (path.length >= 4 && path[1] === 'domain') {\n\t\t\t\t\t\tconst ref = imported(context, rootMember(node))\n\t\t\t\t\t\tif (ref?.name === 'internal' && /_generated\\/api/.test(ref.source)) owners.add(path[2])\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tNewExpression: flag,\n\t\t\t\tIfStatement: flag,\n\t\t\t\tSwitchStatement: flag,\n\t\t\t\tConditionalExpression: flag,\n\t\t\t\t'Program:exit'(node) {\n\t\t\t\t\tif (owners.size < 2 || issue)\n\t\t\t\t\t\tcontext.report({ node: issue ?? node, messageId: 'ownership' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'internal-function-ownership': {\n\t\tmeta: metadata('Place internal handlers with their owner, never in root, api/, or shared/.', {\n\t\t\townership:\n\t\t\t\t'Declare system/internal handlers in domain/<module>/, cross-domain application/, migrations/, or an isolated component.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context) ?? ''\n\t\t\tif (\n\t\t\t\tcomponentRoot(context, context.filename) ||\n\t\t\t\t/^(?:domain\\/(?!shared\\/)[^/]+\\/|application\\/|migrations\\/)/.test(file)\n\t\t\t)\n\t\t\t\treturn {}\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (node.callee.type === 'CallExpression') return\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tref &&\n\t\t\t\t\t\t((isFunctionsImport(context, ref.source) &&\n\t\t\t\t\t\t\t/^system(Query|Mutation|Action)$/.test(ref.name)) ||\n\t\t\t\t\t\t\t(/(?:_generated\\/server|convex\\/server)/.test(ref.source) &&\n\t\t\t\t\t\t\t\t/^internal(Query|Mutation|Action)(Generic)?$/.test(ref.name)))\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'ownership' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'domain-file-responsibilities': {\n\t\tmeta: metadata(\n\t\t\t'Keep invariants pure, reads read-only, shapes declarative, and I/O action-side.',\n\t\t\t{\n\t\t\t\townership:\n\t\t\t\t\t'Respect this domain file responsibility: pure rules, read-only queries, declarative schemas/tables/constants, and external I/O only in actions or integrations.',\n\t\t\t},\n\t\t),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context) ?? ''\n\t\t\tconst assembly = file === 'domain/table.ts'\n\t\t\tif (!assembly && !/^domain\\/[^/]+\\//.test(file) && !componentRoot(context, context.filename))\n\t\t\t\treturn {}\n\t\t\tconst role = basename(file).replace(/\\.[cm]?[jt]s$/, '')\n\t\t\tconst pure = role === 'rules'\n\t\t\tconst read = role === 'queries'\n\t\t\tconst declarative = ['schema', 'table', 'contracts', 'constants'].includes(role)\n\t\t\tconst actionSide =\n\t\t\t\t/(?:^|\\/)(?:actions|integrations|providers)(?:\\/|\\.)/.test(file) ||\n\t\t\t\t/(?:^|_)actions\\./.test(file)\n\t\t\tconst resolver = createResolver()\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\tconst sources = sourceVisitors(context, (node, source) => {\n\t\t\t\tif (typeOnlySource(node)) return\n\t\t\t\tconst target = resolveImport(resolver, context.filename, source)\n\t\t\t\tconst path = target && appFile(context, target)\n\t\t\t\tif (\n\t\t\t\t\tassembly &&\n\t\t\t\t\tsource !== 'cvx-kit/zod-table' &&\n\t\t\t\t\t!/^domain\\/[^/]+\\/table(?:\\.[cm]?[jt]s)?$/.test(path ?? '')\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t\tif (pure && path && !/(?:^|\\/)(?:rules|constants)(?:\\.[cm]?[jt]s)?$/.test(path)) flag(node)\n\t\t\t\tif (\n\t\t\t\t\t(pure || read || declarative) &&\n\t\t\t\t\t!path &&\n\t\t\t\t\t!componentRoot(context, context.filename) &&\n\t\t\t\t\t![\n\t\t\t\t\t\t'zod',\n\t\t\t\t\t\t'zod/v4',\n\t\t\t\t\t\t'convex/values',\n\t\t\t\t\t\t'cvx-kit',\n\t\t\t\t\t\t'cvx-kit/zod-table',\n\t\t\t\t\t\t'cvx-kit/errors',\n\t\t\t\t\t\t'cvx-kit/contracts',\n\t\t\t\t\t].includes(source)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t\tif (\n\t\t\t\t\tread &&\n\t\t\t\t\tpath &&\n\t\t\t\t\t/(?:^|\\/)(?:commands|actions|integrations|providers)(?:[./]|$)/.test(path)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...sources,\n\t\t\t\tProgram(node) {\n\t\t\t\t\tif (!assembly) return\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (statement.type === 'ImportDeclaration' || statement.type === 'EmptyStatement')\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tconst declaration =\n\t\t\t\t\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tdeclaration?.type !== 'VariableDeclaration' ||\n\t\t\t\t\t\t\tdeclaration.declarations.some((item) => item.init?.type !== 'CallExpression')\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tsources.CallExpression?.(node)\n\t\t\t\t\tif (assembly) {\n\t\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\t\tif (ref?.source !== 'cvx-kit/zod-table' || ref.name !== 'createModule') flag(node)\n\t\t\t\t\t}\n\t\t\t\t\tconst method = node.callee.type === 'MemberExpression' ? propertyName(node.callee) : null\n\t\t\t\t\tif (\n\t\t\t\t\t\t(pure || declarative) &&\n\t\t\t\t\t\t(isDbAccess(node) ||\n\t\t\t\t\t\t\t['runQuery', 'runMutation', 'runAction', 'runAfter', 'runAt'].includes(method ?? ''))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tread &&\n\t\t\t\t\t\t(isDbWrite(node) ||\n\t\t\t\t\t\t\t['runMutation', 'runAction', 'runAfter', 'runAt'].includes(method ?? ''))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tconst constructor = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tconstructor &&\n\t\t\t\t\t\tisFunctionsImport(context, constructor.source) &&\n\t\t\t\t\t\t(pure || declarative || (read && /(?:Mutation|Action)$/.test(constructor.name)))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tread &&\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression' &&\n\t\t\t\t\t\tpropertyName(node.callee.object) === 'storage' &&\n\t\t\t\t\t\t['store', 'delete', 'generateUploadUrl'].includes(method ?? '')\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (!actionSide && isExternalCall(context, node)) flag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tpure &&\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression' &&\n\t\t\t\t\t\tnode.callee.object.type === 'Identifier' &&\n\t\t\t\t\t\t!binding(context, node.callee.object)?.defs.length &&\n\t\t\t\t\t\t((node.callee.object.name === 'Date' && method === 'now') ||\n\t\t\t\t\t\t\t(node.callee.object.name === 'Math' && method === 'random'))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tProperty(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\trole === 'contracts' &&\n\t\t\t\t\t\t['handler', 'context', 'audit', 'prepare', 'middleware', 'guard'].includes(\n\t\t\t\t\t\t\tnode.key.type === 'Identifier'\n\t\t\t\t\t\t\t\t? node.key.name\n\t\t\t\t\t\t\t\t: String(node.key.type === 'Literal' ? node.key.value : ''),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tMemberExpression(node) {\n\t\t\t\t\tif (pure && ['db', 'storage', 'scheduler', 'env'].includes(propertyName(node) ?? ''))\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tNewExpression(node) {\n\t\t\t\t\tif (!(pure || read || declarative)) return\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.callee.type === 'Identifier' &&\n\t\t\t\t\t\t!binding(context, node.callee)?.defs.length &&\n\t\t\t\t\t\t['Error', 'TypeError', 'RangeError', 'Set', 'Map', 'RegExp'].includes(node.callee.name)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\t'Program:exit'() {\n\t\t\t\t\tif (issue) context.report({ node: issue, messageId: 'ownership' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n} satisfies Record<string, CreateRule>\n\nexport type OwnershipRuleName = keyof typeof ownershipRules\n"],"mappings":"ikBA8BA,MAAaA,EAAiB,CAC7B,oBAAqB,CACpB,KAAMC,EAAS,qEAAsE,CACpF,UAAW,uBACZ,CAAC,EACD,OAAO,EAAS,CACf,IAAMC,EAAWC,EAAgB,MAAMC,EAAQ,QAAQ,IAAM,CAAC,CAAC,EACzDC,EAAOC,EAAQF,EAAQ,IAAKF,EAAS,SAAS,EAOpD,OALEK,EAAWH,EAAQ,QAAQ,EACzBI,EAAaJ,EAAQ,QAAQ,EAC7BE,EAAQF,EAAQ,QAAQ,KAAOK,EAAmBJ,CAAI,EAGnD,CACN,QAAQ,EAAM,CACb,IAAK,IAAMK,KAASC,EAAoB,CACvC,IAAKP,EAAQ,IACb,UAAWF,EAAS,UACpB,cAAeA,EAAS,aACzB,CAAC,EACAE,EAAQ,OAAO,CACd,OACA,UAAW,YACX,KAAM,CAAE,KAAMM,EAAM,KAAM,QAASA,EAAM,OAAQ,CAClD,CAAC,CACH,CACD,EAdQ,CAAC,CAeV,CACD,EACA,mBAAoB,CACnB,KAAMT,EAAS,6EAA8E,CAC5F,UACC,qGACF,CAAC,EACD,OAAO,EAAS,CACf,IAAMW,EAAOC,EAAQT,C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M,IAAM,WACrC,CAAC,QAAS,SAAU,mBAAmB,CAAC,CAAC,SAASoC,GAAU,EAAE,GAE9DrC,EAAKC,CAAI,EACN,CAACmC,GAAc7B,EAAepB,EAASc,CAAI,GAAGD,EAAKC,CAAI,EAE1DgC,GACAhC,EAAK,OAAO,OAAS,oBACrBA,EAAK,OAAO,OAAO,OAAS,cAC5B,CAACuC,EAAQrD,EAASc,EAAK,OAAO,MAAM,CAAC,EAAE,KAAK,SAC1CA,EAAK,OAAO,OAAO,OAAS,QAAUoC,IAAW,OACjDpC,EAAK,OAAO,OAAO,OAAS,QAAUoC,IAAW,WAEnDrC,EAAKC,CAAI,CACX,EACA,SAAS,EAAM,CAEb8B,IAAS,aACT,CAAC,UAAW,UAAW,QAAS,UAAW,aAAc,OAAO,CAAC,CAAC,SACjE9B,EAAK,IAAI,OAAS,aACfA,EAAK,IAAI,KACT,OAAOA,EAAK,IAAI,OAAS,UAAYA,EAAK,IAAI,MAAQ,EAAE,CAC5D,GAEAD,EAAKC,CAAI,CACX,EACA,iBAAiB,EAAM,CAClBgC,GAAQ,CAAC,KAAM,UAAW,YAAa,KAAK,CAAC,CAAC,SAASK,EAAarC,CAAI,GAAK,EAAE,GAClFD,EAAKC,CAAI,CACX,EACA,cAAc,EAAM,EACbgC,GAAQC,GAAQC,KAErBlC,EAAK,OAAO,OAAS,cACpBuC,EAAQrD,EAASc,EAAK,MAAM,CAAC,EAAE,KAAK,QACrC,EAAC,QAAS,YAAa,aAAc,MAAO,MAAO,QAAQ,CAAC,CAAC,SAASA,EAAK,OAAO,IAAI,IAGvFD,EAAKC,CAAI,CACV,EACA,gBAAiB,CACZR,GAAON,EAAQ,OAAO,CAAE,KAAMM,EAAO,UAAW,WAAY,CAAC,CAClE,CACD,CACD,CACD,CACD"}
|
|
1
|
+
{"version":3,"file":"ownership.mjs","names":["ownershipRules","metadata","settings","consumerOptions","context","root","resolve","existsSync","realpathSync","architectureAnchor","issue","inspectArchitecture","file","appFile","reason","componentFacade","standard","flag","node","statement","imported","containsComponentReference","argument","isDbWrite","isExternalCall","delegatingBody","owners","resolver","createResolver","sources","sourceVisitors","typeOnlySource","target","resolveImport","source","path","match","componentRoot","publicNames","exportedNames","declaration","item","isDbAccess","ref","memberPath","rootMember","isFunctionsImport","assembly","role","basename","pure","read","declarative","actionSide","method","propertyName","constructor","binding"],"sources":["../../src/oxlint/ownership.ts"],"sourcesContent":["import { existsSync, realpathSync } from 'node:fs'\nimport { basename, resolve } from 'node:path'\nimport type { CreateRule, ESTree } from '@oxlint/plugins'\nimport {\n\tarchitectureAnchor,\n\tinspectArchitecture,\n\tcreateResolver,\n\tresolveImport,\n} from './architecture'\nimport {\n\tconsumerOptions,\n\tappFile,\n\timported,\n\tsourceVisitors,\n\tisFunctionsImport,\n\ttypeOnlySource,\n\tisDbAccess,\n\tisExternalCall,\n\tcontainsComponentReference,\n\trootMember,\n\tmemberPath,\n\tisDbWrite,\n\tmetadata,\n\tcomponentRoot,\n\tpropertyName,\n\tbinding,\n\texportedNames,\n\tdelegatingBody,\n} from './ast'\n\nexport const ownershipRules = {\n\t'project-structure': {\n\t\tmeta: metadata('Validate the application tree, colocated tests, and module cycles.', {\n\t\t\tstructure: '{{file}}: {{message}}',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst settings = consumerOptions.parse(context.options[0] ?? {})\n\t\t\tconst root = resolve(context.cwd, settings.convexDir)\n\t\t\tif (\n\t\t\t\t(existsSync(context.filename)\n\t\t\t\t\t? realpathSync(context.filename)\n\t\t\t\t\t: resolve(context.filename)) !== architectureAnchor(root)\n\t\t\t)\n\t\t\t\treturn {}\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tfor (const issue of inspectArchitecture({\n\t\t\t\t\t\tcwd: context.cwd,\n\t\t\t\t\t\tconvexDir: settings.convexDir,\n\t\t\t\t\t\tcomponentDirs: settings.componentDirs,\n\t\t\t\t\t}))\n\t\t\t\t\t\tcontext.report({\n\t\t\t\t\t\t\tnode,\n\t\t\t\t\t\t\tmessageId: 'structure',\n\t\t\t\t\t\t\tdata: { file: issue.file, message: issue.message },\n\t\t\t\t\t\t})\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'root-wiring-only': {\n\t\tmeta: metadata('Keep root files limited to configuration, assembly, and component facades.', {\n\t\t\townership:\n\t\t\t\t'Root files only wire configuration and components. Move behavior into domain/<module>/: {{reason}}.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context)\n\t\t\tif (!file || file.includes('/')) return {}\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tlet reason = 'business implementation'\n\t\t\tlet componentFacade = false\n\t\t\tconst standard =\n\t\t\t\t/^(?:convex\\.config|auth\\.config|vite\\.config|vitest\\.config|auth|schema|functions|triggers|foundation|http|crons)\\.[cm]?[jt]s$/.test(\n\t\t\t\t\tfile,\n\t\t\t\t)\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tProgram(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.body.some(\n\t\t\t\t\t\t\t(statement) =>\n\t\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' ||\n\t\t\t\t\t\t\t\t(statement.type === 'ExportNamedDeclaration' &&\n\t\t\t\t\t\t\t\t\tstatement.declaration?.type === 'FunctionDeclaration'),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tNewExpression(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\timported(context, node.callee) &&\n\t\t\t\t\t\tnode.arguments.some((argument) => containsComponentReference(context, argument))\n\t\t\t\t\t)\n\t\t\t\t\t\tcomponentFacade = true\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\timported(context, node.callee) &&\n\t\t\t\t\t\tnode.arguments.some((argument) => containsComponentReference(context, argument))\n\t\t\t\t\t)\n\t\t\t\t\t\tcomponentFacade = true\n\t\t\t\t\tif (\n\t\t\t\t\t\tisDbWrite(node) ||\n\t\t\t\t\t\tisExternalCall(context, node) ||\n\t\t\t\t\t\t(file === 'schema.ts' && !(imported(context, node.callee)?.name === 'defineSchema'))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tArrowFunctionExpression(node) {\n\t\t\t\t\tif (!node.body || !delegatingBody(node.body)) flag(node)\n\t\t\t\t},\n\t\t\t\tFunctionExpression(node) {\n\t\t\t\t\tif (!node.body || !delegatingBody(node.body)) flag(node)\n\t\t\t\t},\n\t\t\t\tIfStatement: flag,\n\t\t\t\tSwitchStatement: flag,\n\t\t\t\tConditionalExpression: flag,\n\t\t\t\tForStatement: flag,\n\t\t\t\tForOfStatement: flag,\n\t\t\t\tWhileStatement: flag,\n\t\t\t\t'Program:exit'(node) {\n\t\t\t\t\tif (!standard && !componentFacade) {\n\t\t\t\t\t\tissue = node\n\t\t\t\t\t\treason = 'unknown root file; only declared component facades may add root source files'\n\t\t\t\t\t}\n\t\t\t\t\tif (issue) context.report({ node: issue, messageId: 'ownership', data: { reason } })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'application-orchestration': {\n\t\tmeta: metadata('Reserve application/ for thin cross-domain coordination.', {\n\t\t\townership:\n\t\t\t\t'application/ only coordinates two or more domains. Move schemas, providers, storage access, helpers, and business decisions into their owning domain.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tif (!appFile(context)?.startsWith('application/')) return {}\n\t\t\tconst owners = new Set<string>()\n\t\t\tconst resolver = createResolver()\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\tconst sources = sourceVisitors(context, (node, source) => {\n\t\t\t\tif (typeOnlySource(node)) return\n\t\t\t\tconst target = resolveImport(resolver, context.filename, source)\n\t\t\t\tconst path = target && appFile(context, target)\n\t\t\t\tconst match = path?.match(/^domain\\/([^/]+)\\/(?:commands|queries|rules)(?:\\.[cm]?[jt]s)?$/)\n\t\t\t\tif (match && match[1] !== 'shared') owners.add(match[1])\n\t\t\t\tif (path?.startsWith('domain/') && !match && !path.startsWith('domain/shared/')) flag(node)\n\t\t\t\tif (\n\t\t\t\t\t!path &&\n\t\t\t\t\t!componentRoot(context, context.filename) &&\n\t\t\t\t\t![\n\t\t\t\t\t\t'cvx-kit',\n\t\t\t\t\t\t'cvx-kit/components/foundation',\n\t\t\t\t\t\t'@convex-dev/workflow',\n\t\t\t\t\t\t'convex/values',\n\t\t\t\t\t].includes(source)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...sources,\n\t\t\t\tProgram(node) {\n\t\t\t\t\tconst publicNames = exportedNames(node)\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tstatement.type === 'FunctionDeclaration' &&\n\t\t\t\t\t\t\tstatement.id &&\n\t\t\t\t\t\t\t!publicNames.has(statement.id.name)\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t\tconst declaration =\n\t\t\t\t\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tdeclaration?.type === 'TSTypeAliasDeclaration' ||\n\t\t\t\t\t\t\tdeclaration?.type === 'TSInterfaceDeclaration'\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t\tif (declaration?.type === 'VariableDeclaration')\n\t\t\t\t\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\titem.init &&\n\t\t\t\t\t\t\t\t\t['ObjectExpression', 'ArrayExpression', 'Literal'].includes(item.init.type)\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tflag(item)\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\tstatement.type === 'VariableDeclaration' &&\n\t\t\t\t\t\t\t\t\titem.id.type === 'Identifier' &&\n\t\t\t\t\t\t\t\t\t!publicNames.has(item.id.name) &&\n\t\t\t\t\t\t\t\t\t['ArrowFunctionExpression', 'FunctionExpression'].includes(item.init?.type ?? '')\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tflag(item)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tsources.CallExpression?.(node)\n\t\t\t\t\tif (isDbAccess(node) || isExternalCall(context, node)) flag(node)\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (ref && ['zod', 'zod/v4'].includes(ref.source)) flag(node)\n\t\t\t\t},\n\t\t\t\tMemberExpression(node) {\n\t\t\t\t\tconst path = memberPath(node)\n\t\t\t\t\tif (path.length >= 4 && path[1] === 'domain') {\n\t\t\t\t\t\tconst ref = imported(context, rootMember(node))\n\t\t\t\t\t\tif (ref?.name === 'internal' && /_generated\\/api/.test(ref.source)) owners.add(path[2])\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tNewExpression: flag,\n\t\t\t\tIfStatement: flag,\n\t\t\t\tSwitchStatement: flag,\n\t\t\t\tConditionalExpression: flag,\n\t\t\t\t'Program:exit'(node) {\n\t\t\t\t\tif (owners.size < 2 || issue)\n\t\t\t\t\t\tcontext.report({ node: issue ?? node, messageId: 'ownership' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'internal-function-ownership': {\n\t\tmeta: metadata('Place internal handlers with their owner, never in root, api/, or shared/.', {\n\t\t\townership:\n\t\t\t\t'Declare system/internal handlers in domain/<module>/, cross-domain application/, migrations/, or an isolated component.',\n\t\t}),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context) ?? ''\n\t\t\tif (\n\t\t\t\tcomponentRoot(context, context.filename) ||\n\t\t\t\t/^(?:domain\\/(?!shared\\/)[^/]+\\/|application\\/|migrations\\/)/.test(file)\n\t\t\t)\n\t\t\t\treturn {}\n\t\t\treturn {\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tif (node.callee.type === 'CallExpression') return\n\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tref &&\n\t\t\t\t\t\t((isFunctionsImport(context, ref.source) &&\n\t\t\t\t\t\t\t/^system(Query|Mutation|Action)$/.test(ref.name)) ||\n\t\t\t\t\t\t\t(/(?:_generated\\/server|convex\\/server)/.test(ref.source) &&\n\t\t\t\t\t\t\t\t/^internal(Query|Mutation|Action)(Generic)?$/.test(ref.name)))\n\t\t\t\t\t)\n\t\t\t\t\t\tcontext.report({ node, messageId: 'ownership' })\n\t\t\t\t},\n\t\t\t}\n\t\t},\n\t},\n\t'domain-file-responsibilities': {\n\t\tmeta: metadata(\n\t\t\t'Keep invariants pure, reads read-only, shapes declarative, and I/O action-side.',\n\t\t\t{\n\t\t\t\townership:\n\t\t\t\t\t'Respect this domain file responsibility: pure rules, read-only queries, declarative schemas/tables/constants, and external I/O only in actions or integrations.',\n\t\t\t},\n\t\t),\n\t\tcreate(context) {\n\t\t\tconst file = appFile(context) ?? ''\n\t\t\tconst assembly = file === 'domain/table.ts'\n\t\t\tif (!assembly && !/^domain\\/[^/]+\\//.test(file) && !componentRoot(context, context.filename))\n\t\t\t\treturn {}\n\t\t\tconst role = basename(file).replace(/\\.[cm]?[jt]s$/, '')\n\t\t\tconst pure = role === 'rules'\n\t\t\tconst read = role === 'queries'\n\t\t\tconst declarative = ['schema', 'table', 'contracts', 'constants'].includes(role)\n\t\t\tconst actionSide =\n\t\t\t\t/(?:^|\\/)(?:actions|integrations|providers)(?:\\/|\\.)/.test(file) ||\n\t\t\t\t/(?:^|_)actions\\./.test(file)\n\t\t\tconst resolver = createResolver()\n\t\t\tlet issue: ESTree.Node | null = null\n\t\t\tfunction flag(node: ESTree.Node) {\n\t\t\t\tissue ??= node\n\t\t\t}\n\t\t\tconst sources = sourceVisitors(context, (node, source) => {\n\t\t\t\tif (typeOnlySource(node)) return\n\t\t\t\tconst target = resolveImport(resolver, context.filename, source)\n\t\t\t\tconst path = target && appFile(context, target)\n\t\t\t\tif (\n\t\t\t\t\tassembly &&\n\t\t\t\t\tsource !== 'cvx-kit/zod-table' &&\n\t\t\t\t\t!/^domain\\/[^/]+\\/table(?:\\.[cm]?[jt]s)?$/.test(path ?? '')\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t\tif (pure && path && !/(?:^|\\/)(?:rules|constants)(?:\\.[cm]?[jt]s)?$/.test(path)) flag(node)\n\t\t\t\tif (\n\t\t\t\t\t(pure || read || declarative) &&\n\t\t\t\t\t!path &&\n\t\t\t\t\t!componentRoot(context, context.filename) &&\n\t\t\t\t\t![\n\t\t\t\t\t\t'zod',\n\t\t\t\t\t\t'zod/v4',\n\t\t\t\t\t\t'convex/values',\n\t\t\t\t\t\t'cvx-kit',\n\t\t\t\t\t\t'cvx-kit/zod-table',\n\t\t\t\t\t\t'cvx-kit/errors',\n\t\t\t\t\t\t'cvx-kit/contracts',\n\t\t\t\t\t].includes(source)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t\tif (\n\t\t\t\t\tread &&\n\t\t\t\t\tpath &&\n\t\t\t\t\t/(?:^|\\/)(?:commands|actions|integrations|providers)(?:[./]|$)/.test(path)\n\t\t\t\t)\n\t\t\t\t\tflag(node)\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...sources,\n\t\t\t\tProgram(node) {\n\t\t\t\t\tif (!assembly) return\n\t\t\t\t\tfor (const statement of node.body) {\n\t\t\t\t\t\tif (statement.type === 'ImportDeclaration' || statement.type === 'EmptyStatement')\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tconst declaration =\n\t\t\t\t\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tdeclaration?.type !== 'VariableDeclaration' ||\n\t\t\t\t\t\t\tdeclaration.declarations.some((item) => item.init?.type !== 'CallExpression')\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\tflag(statement)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tCallExpression(node) {\n\t\t\t\t\tsources.CallExpression?.(node)\n\t\t\t\t\tif (assembly) {\n\t\t\t\t\t\tconst ref = imported(context, node.callee)\n\t\t\t\t\t\tconst assemblyCall =\n\t\t\t\t\t\t\t(ref?.source === 'cvx-kit/zod-table' && ref.name === 'createModule') ||\n\t\t\t\t\t\t\t(ref?.source === 'cvx-kit/zod-table' && ref.name === 'namespaceIndex')\n\t\t\t\t\t\tif (!assemblyCall) flag(node)\n\t\t\t\t\t}\n\t\t\t\t\tconst method = node.callee.type === 'MemberExpression' ? propertyName(node.callee) : null\n\t\t\t\t\tif (\n\t\t\t\t\t\t(pure || declarative) &&\n\t\t\t\t\t\t(isDbAccess(node) ||\n\t\t\t\t\t\t\t['runQuery', 'runMutation', 'runAction', 'runAfter', 'runAt'].includes(method ?? ''))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tread &&\n\t\t\t\t\t\t(isDbWrite(node) ||\n\t\t\t\t\t\t\t['runMutation', 'runAction', 'runAfter', 'runAt'].includes(method ?? ''))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tconst constructor = imported(context, node.callee)\n\t\t\t\t\tif (\n\t\t\t\t\t\tconstructor &&\n\t\t\t\t\t\tisFunctionsImport(context, constructor.source) &&\n\t\t\t\t\t\t(pure || declarative || (read && /(?:Mutation|Action)$/.test(constructor.name)))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tread &&\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression' &&\n\t\t\t\t\t\tpropertyName(node.callee.object) === 'storage' &&\n\t\t\t\t\t\t['store', 'delete', 'generateUploadUrl'].includes(method ?? '')\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t\tif (!actionSide && isExternalCall(context, node)) flag(node)\n\t\t\t\t\tif (\n\t\t\t\t\t\tpure &&\n\t\t\t\t\t\tnode.callee.type === 'MemberExpression' &&\n\t\t\t\t\t\tnode.callee.object.type === 'Identifier' &&\n\t\t\t\t\t\t!binding(context, node.callee.object)?.defs.length &&\n\t\t\t\t\t\t((node.callee.object.name === 'Date' && method === 'now') ||\n\t\t\t\t\t\t\t(node.callee.object.name === 'Math' && method === 'random'))\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tProperty(node) {\n\t\t\t\t\tif (\n\t\t\t\t\t\trole === 'contracts' &&\n\t\t\t\t\t\t['handler', 'context', 'audit', 'prepare', 'middleware', 'guard'].includes(\n\t\t\t\t\t\t\tnode.key.type === 'Identifier'\n\t\t\t\t\t\t\t\t? node.key.name\n\t\t\t\t\t\t\t\t: String(node.key.type === 'Literal' ? node.key.value : ''),\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tMemberExpression(node) {\n\t\t\t\t\tif (pure && ['db', 'storage', 'scheduler', 'env'].includes(propertyName(node) ?? ''))\n\t\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\tNewExpression(node) {\n\t\t\t\t\tif (!(pure || read || declarative)) return\n\t\t\t\t\tif (\n\t\t\t\t\t\tnode.callee.type === 'Identifier' &&\n\t\t\t\t\t\t!binding(context, node.callee)?.defs.length &&\n\t\t\t\t\t\t['Error', 'TypeError', 'RangeError', 'Set', 'Map', 'RegExp'].includes(node.callee.name)\n\t\t\t\t\t)\n\t\t\t\t\t\treturn\n\t\t\t\t\tflag(node)\n\t\t\t\t},\n\t\t\t\t'Program:exit'() {\n\t\t\t\t\tif (issue) context.report({ node: issue, messageId: 'ownership'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QAAUoC,IAAW,WAEnDrC,EAAKC,CAAI,CACX,EACA,SAAS,EAAM,CAEb8B,IAAS,aACT,CAAC,UAAW,UAAW,QAAS,UAAW,aAAc,OAAO,CAAC,CAAC,SACjE9B,EAAK,IAAI,OAAS,aACfA,EAAK,IAAI,KACT,OAAOA,EAAK,IAAI,OAAS,UAAYA,EAAK,IAAI,MAAQ,EAAE,CAC5D,GAEAD,EAAKC,CAAI,CACX,EACA,iBAAiB,EAAM,CAClBgC,GAAQ,CAAC,KAAM,UAAW,YAAa,KAAK,CAAC,CAAC,SAASK,EAAarC,CAAI,GAAK,EAAE,GAClFD,EAAKC,CAAI,CACX,EACA,cAAc,EAAM,EACbgC,GAAQC,GAAQC,KAErBlC,EAAK,OAAO,OAAS,cACpBuC,EAAQrD,EAASc,EAAK,MAAM,CAAC,EAAE,KAAK,QACrC,EAAC,QAAS,YAAa,aAAc,MAAO,MAAO,QAAQ,CAAC,CAAC,SAASA,EAAK,OAAO,IAAI,IAGvFD,EAAKC,CAAI,CACV,EACA,gBAAiB,CACZR,GAAON,EAAQ,OAAO,CAAE,KAAMM,EAAO,UAAW,WAAY,CAAC,CAClE,CACD,CACD,CACD,CACD"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createResolver as e,resolveImport as t}from"./architecture.mjs";import{appFile as n,exportName as r,metadata as i,propertyName as a}from"./ast.mjs";import{readFileSync as o}from"node:fs";import{parseSync as s}from"oxc-parser";const c={meta:i(`Require kit-backed declarations in reserved domain files.`,{anatomy:`{{file}} must export {{expected}} built with cvx-kit; imports or local lookalikes do not count.`}),create(e){let t=n(e)??``,r=t.match(/^domain\/(?:.+\/)?(commands|queries|contracts|schema|table)\.ts$/);if(!r)return{};let i=r[1];return{Program(n){let r=u(e,n,e.filename),a=l(n).map(e=>r(e)),o=i===`commands`?`one Command registry`:i===`queries`?`one Query registry`:i===`schema`?`zodTable shapes`:i===`contracts`?`declarative contracts`:t===`domain/table.ts`?`createModule assembly`:`a table topology map`,s=i===`commands`?`registry:Command`:i===`queries`?`registry:Query`:i===`schema`?`shape`:i===`contracts`?`contract`:t===`domain/table.ts`?`assembly`:`topology`,c=a.filter(e=>e===s).length;(i===`commands`||i===`queries`?c===1:c>0)||e.report({node:n,messageId:`anatomy`,data:{file:t,expected:o}})}}}};function l(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e.body){let e=r.type===`ExportNamedDeclaration`?r.declaration:r;if(e?.type===`VariableDeclaration`&&e.kind===`const`)for(let i of e.declarations)i.id.type===`Identifier`&&i.init&&(n.set(i.id.name,i.init),r.type===`ExportNamedDeclaration`&&t.push(i.init))}for(let i of e.body){if(i.type===`ExportNamedDeclaration`&&i.exportKind!==`type`&&!i.source)for(let e of i.specifiers){if(e.exportKind===`type`)continue;let i=n.get(r(e.local)??``);i&&t.push(i)}i.type===`ExportDefaultDeclaration`&&i.declaration.type!==`FunctionDeclaration`&&i.declaration.type!==`ClassDeclaration`&&i.declaration.type!==`TSInterfaceDeclaration`&&t.push(i.declaration)}return t}function u(i,c,l,d=/* @__PURE__ */ new Set){let f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=e();for(let e of c.body){if(e.type===`ImportDeclaration`&&e.importKind!==`type`)for(let t of e.specifiers)(t.type!==`ImportSpecifier`||t.importKind!==`type`)&&f.set(t.local.name,{source:e.source.value,name:t.type===`ImportSpecifier`?r(t.imported)??``:t.type===`ImportNamespaceSpecifier`?`*`:`default`});let t=e.type===`ExportNamedDeclaration`?e.declaration:e;if(t?.type===`VariableDeclaration`&&t.kind===`const`){for(let e of t.declarations)if(e.init&&(e.id.type===`Identifier`&&p.set(e.id.name,{expression:e.init}),e.id.type===`ObjectPattern`))for(let t of e.id.properties)t.type===`Property`&&t.value.type===`Identifier`&&p.set(t.value.name,{expression:e.init,member:r(t.key)??``})}}function h(e,a){if([`cvx-kit`,`cvx-kit/effect`,`cvx-kit/components/foundation`,`cvx-kit/contracts`,`cvx-kit/zod-table`,`cvx-kit/errors`].includes(e))return a===`*`?`namespace:${e}`:e===`cvx-kit/effect`&&a===`createEffectFoundation`||e===`cvx-kit`&&a===`createFoundation`||[`cvx-kit`,`cvx-kit/components/foundation`].includes(e)&&a===`Foundation`?`foundationFactory`:[`cvx-kit`,`cvx-kit/zod-table`].includes(e)&&[`zodTable`,`zodVariantTable`].includes(a)?`shapeFactory`:[`cvx-kit`,`cvx-kit/zod-table`].includes(e)&&a===`createModule`?`assemblyFactory`:e===`cvx-kit/contracts`&&[`defineDomainContract`,`operationContract`].includes(a)||e===`cvx-kit/errors`&&a===`defineErrorContract`?`contractFactory`:null;if([`zod`,`zod/v4`,`convex/values`].includes(e))return`validator`;let c=t(m,l,e),f=c&&n(i,c);if(!c||!f||!/^(?:foundation\.ts|domain\/.+\/(?:schema|contracts)\.ts)$/.test(f)||d.has(c)||d.size>=6)return null;if(a===`*`)return`namespace:${e}`;let p=s(c,o(c,`utf8`));if(p.errors.length)return null;let h=p.program,g=u(i,h,c,new Set(d).add(c));for(let e of h.body)if(e.type===`ExportNamedDeclaration`&&e.exportKind!==`type`){if(e.declaration?.type===`VariableDeclaration`)for(let t of e.declaration.declarations){if(t.id.type===`Identifier`&&t.id.name===a)return g(t.id);if(t.id.type===`ObjectPattern`){for(let e of t.id.properties)if(e.type===`Property`&&e.value.type===`Identifier`&&e.value.name===a)return g(e.value)}}for(let t of e.specifiers)if(t.exportKind!==`type`&&r(t.exported)===a&&!e.source)return g(t.local)}return null}function g(e,t){return e===`foundation`&&[`Command`,`Query`].includes(t)?t:e?.startsWith(`namespace:`)?h(e.slice(10),t):e===`validator`||e===`contract`?`validator`:e===`shape`&&t===`table`?`table`:e===`table`&&[`index`,`searchIndex`,`vectorIndex`].includes(t)?`indexFactory`:null}function _(e,t=/* @__PURE__ */ new Set){if(e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`)return _(e.expression,t);if(e.type===`Identifier`){if(t.has(e.name))return null;let n=f.get(e.name);if(n)return h(n.source,n.name);let r=p.get(e.name);if(!r)return null;let i=_(r.expression,new Set(t).add(e.name));return r.member?g(i,r.member):i}if(e.type===`MemberExpression`)return g(_(e.object,t),a(e)??``);if(e.type===`CallExpression`||e.type===`NewExpression`){let n=_(e.callee,t);
|
|
1
|
+
import{createResolver as e,resolveImport as t}from"./architecture.mjs";import{appFile as n,exportName as r,metadata as i,propertyName as a}from"./ast.mjs";import{readFileSync as o}from"node:fs";import{parseSync as s}from"oxc-parser";const c={meta:i(`Require kit-backed declarations in reserved domain files.`,{anatomy:`{{file}} must export {{expected}} built with cvx-kit; imports or local lookalikes do not count.`}),create(e){let t=n(e)??``,r=t.match(/^domain\/(?:.+\/)?(commands|queries|contracts|schema|table)\.ts$/);if(!r)return{};let i=r[1];return{Program(n){let r=u(e,n,e.filename),a=l(n).map(e=>r(e)),o=i===`commands`?`one Command registry`:i===`queries`?`one Query registry`:i===`schema`?`zodTable shapes`:i===`contracts`?`declarative contracts`:t===`domain/table.ts`?`createModule assembly`:`a table topology map`,s=i===`commands`?`registry:Command`:i===`queries`?`registry:Query`:i===`schema`?`shape`:i===`contracts`?`contract`:t===`domain/table.ts`?`assembly`:`topology`,c=a.filter(e=>e===s).length;(i===`commands`||i===`queries`?c===1:c>0)||e.report({node:n,messageId:`anatomy`,data:{file:t,expected:o}})}}}};function l(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e.body){let e=r.type===`ExportNamedDeclaration`?r.declaration:r;if(e?.type===`VariableDeclaration`&&e.kind===`const`)for(let i of e.declarations)i.id.type===`Identifier`&&i.init&&(n.set(i.id.name,i.init),r.type===`ExportNamedDeclaration`&&t.push(i.init))}for(let i of e.body){if(i.type===`ExportNamedDeclaration`&&i.exportKind!==`type`&&!i.source)for(let e of i.specifiers){if(e.exportKind===`type`)continue;let i=n.get(r(e.local)??``);i&&t.push(i)}i.type===`ExportDefaultDeclaration`&&i.declaration.type!==`FunctionDeclaration`&&i.declaration.type!==`ClassDeclaration`&&i.declaration.type!==`TSInterfaceDeclaration`&&t.push(i.declaration)}return t}function u(i,c,l,d=/* @__PURE__ */ new Set){let f=/* @__PURE__ */ new Map,p=/* @__PURE__ */ new Map,m=e();for(let e of c.body){if(e.type===`ImportDeclaration`&&e.importKind!==`type`)for(let t of e.specifiers)(t.type!==`ImportSpecifier`||t.importKind!==`type`)&&f.set(t.local.name,{source:e.source.value,name:t.type===`ImportSpecifier`?r(t.imported)??``:t.type===`ImportNamespaceSpecifier`?`*`:`default`});let t=e.type===`ExportNamedDeclaration`?e.declaration:e;if(t?.type===`VariableDeclaration`&&t.kind===`const`){for(let e of t.declarations)if(e.init&&(e.id.type===`Identifier`&&p.set(e.id.name,{expression:e.init}),e.id.type===`ObjectPattern`))for(let t of e.id.properties)t.type===`Property`&&t.value.type===`Identifier`&&p.set(t.value.name,{expression:e.init,member:r(t.key)??``})}}function h(e,a){if([`cvx-kit`,`cvx-kit/effect`,`cvx-kit/components/foundation`,`cvx-kit/contracts`,`cvx-kit/zod-table`,`cvx-kit/errors`].includes(e))return a===`*`?`namespace:${e}`:e===`cvx-kit/effect`&&a===`createEffectFoundation`||e===`cvx-kit`&&a===`createFoundation`||[`cvx-kit`,`cvx-kit/components/foundation`].includes(e)&&a===`Foundation`?`foundationFactory`:[`cvx-kit`,`cvx-kit/zod-table`].includes(e)&&[`zodTable`,`zodVariantTable`].includes(a)?`shapeFactory`:[`cvx-kit`,`cvx-kit/zod-table`].includes(e)&&a===`createModule`?`assemblyFactory`:e===`cvx-kit/zod-table`&&a===`namespace`?`namespaceFactory`:e===`cvx-kit/contracts`&&[`defineDomainContract`,`operationContract`].includes(a)||e===`cvx-kit/errors`&&a===`defineErrorContract`?`contractFactory`:null;if([`zod`,`zod/v4`,`convex/values`].includes(e))return`validator`;let c=t(m,l,e),f=c&&n(i,c);if(!c||!f||!/^(?:foundation\.ts|domain\/.+\/(?:schema|contracts)\.ts)$/.test(f)||d.has(c)||d.size>=6)return null;if(a===`*`)return`namespace:${e}`;let p=s(c,o(c,`utf8`));if(p.errors.length)return null;let h=p.program,g=u(i,h,c,new Set(d).add(c));for(let e of h.body)if(e.type===`ExportNamedDeclaration`&&e.exportKind!==`type`){if(e.declaration?.type===`VariableDeclaration`)for(let t of e.declaration.declarations){if(t.id.type===`Identifier`&&t.id.name===a)return g(t.id);if(t.id.type===`ObjectPattern`){for(let e of t.id.properties)if(e.type===`Property`&&e.value.type===`Identifier`&&e.value.name===a)return g(e.value)}}for(let t of e.specifiers)if(t.exportKind!==`type`&&r(t.exported)===a&&!e.source)return g(t.local)}return null}function g(e,t){return e===`foundation`&&[`Command`,`Query`].includes(t)?t:e?.startsWith(`namespace:`)?h(e.slice(10),t):e===`validator`||e===`contract`?`validator`:e===`shape`&&t===`table`?`table`:e===`table`&&[`index`,`searchIndex`,`vectorIndex`].includes(t)?`indexFactory`:null}function _(e,t=/* @__PURE__ */ new Set){if(e.type===`TSAsExpression`||e.type===`TSSatisfiesExpression`||e.type===`TSNonNullExpression`)return _(e.expression,t);if(e.type===`Identifier`){if(t.has(e.name))return null;let n=f.get(e.name);if(n)return h(n.source,n.name);let r=p.get(e.name);if(!r)return null;let i=_(r.expression,new Set(t).add(e.name));return r.member?g(i,r.member):i}if(e.type===`MemberExpression`)return g(_(e.object,t),a(e)??``);if(e.type===`CallExpression`||e.type===`NewExpression`){let n=_(e.callee,t);if(n===`foundationFactory`)return`foundation`;if(n===`Command`||n===`Query`)return`registry:${n}`;if(n===`shapeFactory`)return`shape`;if(n===`assemblyFactory`)return`assembly`;if(n===`contractFactory`||n===`validator`)return`contract`;if(n===`indexFactory`)return`table`;if(n===`namespaceFactory`){let n=e.arguments[1];if(n?.type!==`ObjectExpression`)return null;let r=n.properties.map(e=>e.type===`Property`?_(e.value,t):null);return r.length&&r.every(e=>e===`table`||e===`topology`||e===`shape`)?`topology`:null}return null}if(e.type===`ObjectExpression`){let n=e.properties.map(e=>e.type===`Property`?_(e.value,t):null);if(n.length&&n.every(e=>e===`table`||e===`topology`))return`topology`;if(n.some(e=>e===`contract`||e===`validator`)&&n.every(e=>e===`contract`||e===`validator`||e===`data`))return`contract`;if(n.every(e=>e===`data`))return`data`}return e.type===`Literal`?`data`:null}return _}export{c as reservedDomainFiles};
|
|
2
2
|
//# sourceMappingURL=reserved-files.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reserved-files.mjs","names":["reservedDomainFiles","metadata","file","appFile","context","match","role","evaluate","provenance","program","values","publicExpressions","expression","expected","wanted","count","value","expressions","declarations","statement","declaration","item","specifier","exportName","imports","variables","resolver","createResolver","property","imported","source","name","target","resolveImport","filename","visited","parsed","parseSync","readFileSync","remote","evaluateRemote","member","owner","node","active","reference","variable","propertyName","callee"],"sources":["../../src/oxlint/reserved-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport type { Context, CreateRule, ESTree } from '@oxlint/plugins'\nimport { parseSync } from 'oxc-parser'\nimport { appFile, metadata, propertyName, exportName } from './ast'\nimport { createResolver, resolveImport } from './architecture'\n\n/** Reserved files prove their exported declaration's provenance, not an unused import. */\nexport const reservedDomainFiles: CreateRule = {\n\tmeta: metadata('Require kit-backed declarations in reserved domain files.', {\n\t\tanatomy:\n\t\t\t'{{file}} must export {{expected}} built with cvx-kit; imports or local lookalikes do not count.',\n\t}),\n\tcreate(context) {\n\t\tconst file = appFile(context) ?? ''\n\t\tconst match = file.match(/^domain\\/(?:.+\\/)?(commands|queries|contracts|schema|table)\\.ts$/)\n\t\tif (!match) return {}\n\t\tconst role = match[1]\n\t\treturn {\n\t\t\tProgram(program) {\n\t\t\t\tconst evaluate = provenance(context, program, context.filename)\n\t\t\t\tconst exports = publicExpressions(program)\n\t\t\t\tconst values = exports.map((expression) => evaluate(expression))\n\t\t\t\tconst expected =\n\t\t\t\t\trole === 'commands'\n\t\t\t\t\t\t? 'one Command registry'\n\t\t\t\t\t\t: role === 'queries'\n\t\t\t\t\t\t\t? 'one Query registry'\n\t\t\t\t\t\t\t: role === 'schema'\n\t\t\t\t\t\t\t\t? 'zodTable shapes'\n\t\t\t\t\t\t\t\t: role === 'contracts'\n\t\t\t\t\t\t\t\t\t? 'declarative contracts'\n\t\t\t\t\t\t\t\t\t: file === 'domain/table.ts'\n\t\t\t\t\t\t\t\t\t\t? 'createModule assembly'\n\t\t\t\t\t\t\t\t\t\t: 'a table topology map'\n\t\t\t\tconst wanted =\n\t\t\t\t\trole === 'commands'\n\t\t\t\t\t\t? 'registry:Command'\n\t\t\t\t\t\t: role === 'queries'\n\t\t\t\t\t\t\t? 'registry:Query'\n\t\t\t\t\t\t\t: role === 'schema'\n\t\t\t\t\t\t\t\t? 'shape'\n\t\t\t\t\t\t\t\t: role === 'contracts'\n\t\t\t\t\t\t\t\t\t? 'contract'\n\t\t\t\t\t\t\t\t\t: file === 'domain/table.ts'\n\t\t\t\t\t\t\t\t\t\t? 'assembly'\n\t\t\t\t\t\t\t\t\t\t: 'topology'\n\t\t\t\tconst count = values.filter((value) => value === wanted).length\n\t\t\t\tconst valid = role === 'commands' || role === 'queries' ? count === 1 : count > 0\n\t\t\t\tif (!valid)\n\t\t\t\t\tcontext.report({ node: program, messageId: 'anatomy', data: { file, expected } })\n\t\t\t},\n\t\t}\n\t},\n}\n\nfunction publicExpressions(program: ESTree.Program): ESTree.Expression[] {\n\tconst expressions: ESTree.Expression[] = []\n\tconst declarations = new Map<string, ESTree.Expression>()\n\tfor (const statement of program.body) {\n\t\tconst declaration =\n\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\tif (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const')\n\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\tif (item.id.type === 'Identifier' && item.init) {\n\t\t\t\t\tdeclarations.set(item.id.name, item.init)\n\t\t\t\t\tif (statement.type === 'ExportNamedDeclaration') expressions.push(item.init)\n\t\t\t\t}\n\t\t\t}\n\t}\n\tfor (const statement of program.body) {\n\t\tif (\n\t\t\tstatement.type === 'ExportNamedDeclaration' &&\n\t\t\tstatement.exportKind !== 'type' &&\n\t\t\t!statement.source\n\t\t)\n\t\t\tfor (const specifier of statement.specifiers) {\n\t\t\t\tif (specifier.exportKind === 'type') continue\n\t\t\t\tconst expression = declarations.get(exportName(specifier.local) ?? '')\n\t\t\t\tif (expression) expressions.push(expression)\n\t\t\t}\n\t\tif (\n\t\t\tstatement.type === 'ExportDefaultDeclaration' &&\n\t\t\tstatement.declaration.type !== 'FunctionDeclaration' &&\n\t\t\tstatement.declaration.type !== 'ClassDeclaration' &&\n\t\t\tstatement.declaration.type !== 'TSInterfaceDeclaration'\n\t\t) {\n\t\t\texpressions.push(statement.declaration)\n\t\t}\n\t}\n\treturn expressions\n}\n\nfunction provenance(\n\tcontext: Context,\n\tprogram: ESTree.Program,\n\tfilename: string,\n\tvisited = new Set<string>(),\n) {\n\tconst imports = new Map<string, { source: string; name: string }>()\n\tconst variables = new Map<string, { expression: ESTree.Expression; member?: string }>()\n\tconst resolver = createResolver()\n\tfor (const statement of program.body) {\n\t\tif (statement.type === 'ImportDeclaration' && statement.importKind !== 'type')\n\t\t\tfor (const specifier of statement.specifiers) {\n\t\t\t\tif (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type') continue\n\t\t\t\timports.set(specifier.local.name, {\n\t\t\t\t\tsource: statement.source.value,\n\t\t\t\t\tname:\n\t\t\t\t\t\tspecifier.type === 'ImportSpecifier'\n\t\t\t\t\t\t\t? (exportName(specifier.imported) ?? '')\n\t\t\t\t\t\t\t: specifier.type === 'ImportNamespaceSpecifier'\n\t\t\t\t\t\t\t\t? '*'\n\t\t\t\t\t\t\t\t: 'default',\n\t\t\t\t})\n\t\t\t}\n\t\tconst declaration =\n\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\tif (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const')\n\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\tif (!item.init) continue\n\t\t\t\tif (item.id.type === 'Identifier') variables.set(item.id.name, { expression: item.init })\n\t\t\t\tif (item.id.type === 'ObjectPattern')\n\t\t\t\t\tfor (const property of item.id.properties) {\n\t\t\t\t\t\tif (property.type === 'Property' && property.value.type === 'Identifier')\n\t\t\t\t\t\t\tvariables.set(property.value.name, {\n\t\t\t\t\t\t\t\texpression: item.init,\n\t\t\t\t\t\t\t\tmember: exportName(property.key) ?? '',\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t}\n\t}\n\tfunction imported(source: string, name: string): string | null {\n\t\tif (\n\t\t\t[\n\t\t\t\t'cvx-kit',\n\t\t\t\t'cvx-kit/effect',\n\t\t\t\t'cvx-kit/components/foundation',\n\t\t\t\t'cvx-kit/contracts',\n\t\t\t\t'cvx-kit/zod-table',\n\t\t\t\t'cvx-kit/errors',\n\t\t\t].includes(source)\n\t\t) {\n\t\t\tif (name === '*') return `namespace:${source}`\n\t\t\tif (\n\t\t\t\t(source === 'cvx-kit/effect' && name === 'createEffectFoundation') ||\n\t\t\t\t(source === 'cvx-kit' && name === 'createFoundation') ||\n\t\t\t\t(['cvx-kit', 'cvx-kit/components/foundation'].includes(source) && name === 'Foundation')\n\t\t\t)\n\t\t\t\treturn 'foundationFactory'\n\t\t\tif (\n\t\t\t\t['cvx-kit', 'cvx-kit/zod-table'].includes(source) &&\n\t\t\t\t['zodTable', 'zodVariantTable'].includes(name)\n\t\t\t)\n\t\t\t\treturn 'shapeFactory'\n\t\t\tif (['cvx-kit', 'cvx-kit/zod-table'].includes(source) && name === 'createModule')\n\t\t\t\treturn 'assemblyFactory'\n\t\t\tif (\n\t\t\t\tsource === 'cvx-kit/contracts' &&\n\t\t\t\t['defineDomainContract', 'operationContract'].includes(name)\n\t\t\t)\n\t\t\t\treturn 'contractFactory'\n\t\t\tif (source === 'cvx-kit/errors' && name === 'defineErrorContract') return 'contractFactory'\n\t\t\treturn null\n\t\t}\n\t\tif (['zod', 'zod/v4', 'convex/values'].includes(source)) return 'validator'\n\t\tconst target = resolveImport(resolver, filename, source)\n\t\tconst file = target && appFile(context, target)\n\t\tif (\n\t\t\t!target ||\n\t\t\t!file ||\n\t\t\t!/^(?:foundation\\.ts|domain\\/.+\\/(?:schema|contracts)\\.ts)$/.test(file) ||\n\t\t\tvisited.has(target) ||\n\t\t\tvisited.size >= 6\n\t\t)\n\t\t\treturn null\n\t\tif (name === '*') return `namespace:${source}`\n\t\tconst parsed = parseSync(target, readFileSync(target, 'utf8'))\n\t\tif (parsed.errors.length) return null\n\t\t// SAFETY: oxc-parser and the rule API share these declaration fields; provenance never reads rule-API loc/tokens.\n\t\t// oxlint-disable-next-line anti-slop/no-chained-type-assertions\n\t\tconst remote = parsed.program as unknown as ESTree.Program\n\t\tconst nextVisited = new Set(visited).add(target)\n\t\tconst evaluateRemote = provenance(context, remote, target, nextVisited)\n\t\tfor (const statement of remote.body) {\n\t\t\tif (statement.type !== 'ExportNamedDeclaration' || statement.exportKind === 'type') continue\n\t\t\tif (statement.declaration?.type === 'VariableDeclaration')\n\t\t\t\tfor (const item of statement.declaration.declarations) {\n\t\t\t\t\tif (item.id.type === 'Identifier' && item.id.name === name) return evaluateRemote(item.id)\n\t\t\t\t\tif (item.id.type === 'ObjectPattern')\n\t\t\t\t\t\tfor (const property of item.id.properties)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tproperty.type === 'Property' &&\n\t\t\t\t\t\t\t\tproperty.value.type === 'Identifier' &&\n\t\t\t\t\t\t\t\tproperty.value.name === name\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn evaluateRemote(property.value)\n\t\t\t\t}\n\t\t\tfor (const specifier of statement.specifiers)\n\t\t\t\tif (\n\t\t\t\t\tspecifier.exportKind !== 'type' &&\n\t\t\t\t\texportName(specifier.exported) === name &&\n\t\t\t\t\t!statement.source\n\t\t\t\t)\n\t\t\t\t\treturn evaluateRemote(specifier.local)\n\t\t}\n\t\treturn null\n\t}\n\tfunction member(owner: string | null, name: string): string | null {\n\t\tif (owner === 'foundation' && ['Command', 'Query'].includes(name)) return name\n\t\tif (owner?.startsWith('namespace:')) return imported(owner.slice(10), name)\n\t\tif (owner === 'validator' || owner === 'contract') return 'validator'\n\t\tif (owner === 'shape' && name === 'table') return 'table'\n\t\tif (owner === 'table' && ['index', 'searchIndex', 'vectorIndex'].includes(name))\n\t\t\treturn 'indexFactory'\n\t\treturn null\n\t}\n\tfunction evaluate(node: ESTree.Node, active = new Set<string>()): string | null {\n\t\tif (\n\t\t\tnode.type === 'TSAsExpression' ||\n\t\t\tnode.type === 'TSSatisfiesExpression' ||\n\t\t\tnode.type === 'TSNonNullExpression'\n\t\t)\n\t\t\treturn evaluate(node.expression, active)\n\t\tif (node.type === 'Identifier') {\n\t\t\tif (active.has(node.name)) return null\n\t\t\tconst reference = imports.get(node.name)\n\t\t\tif (reference) return imported(reference.source, reference.name)\n\t\t\tconst variable = variables.get(node.name)\n\t\t\tif (!variable) return null\n\t\t\tconst value = evaluate(variable.expression, new Set(active).add(node.name))\n\t\t\treturn variable.member ? member(value, variable.member) : value\n\t\t}\n\t\tif (node.type === 'MemberExpression')\n\t\t\treturn member(evaluate(node.object, active), propertyName(node) ?? '')\n\t\tif (node.type === 'CallExpression' || node.type === 'NewExpression') {\n\t\t\tconst callee = evaluate(node.callee, active)\n\t\t\tif (callee === 'foundationFactory') return 'foundation'\n\t\t\tif (callee === 'Command' || callee === 'Query') return `registry:${callee}`\n\t\t\tif (callee === 'shapeFactory') return 'shape'\n\t\t\tif (callee === 'assemblyFactory') return 'assembly'\n\t\t\tif (callee === 'contractFactory' || callee === 'validator') return 'contract'\n\t\t\tif (callee === 'indexFactory') return 'table'\n\t\t\treturn null\n\t\t}\n\t\tif (node.type === 'ObjectExpression') {\n\t\t\tconst values = node.properties.map((property) =>\n\t\t\t\tproperty.type === 'Property' ? evaluate(property.value, active) : null,\n\t\t\t)\n\t\t\tif (values.length && values.every((value) => value === 'table' || value === 'topology'))\n\t\t\t\treturn 'topology'\n\t\t\tif (\n\t\t\t\tvalues.some((value) => value === 'contract' || value === 'validator') &&\n\t\t\t\tvalues.every((value) => value === 'contract' || value === 'validator' || value === 'data')\n\t\t\t)\n\t\t\t\treturn 'contract'\n\t\t\tif (values.every((value) => value === 'data')) return 'data'\n\t\t}\n\t\tif (node.type === 'Literal') return 'data'\n\t\treturn null\n\t}\n\treturn evaluate\n}\n"],"mappings":"yOAOA,MAAaA,EAAkC,CAC9C,KAAMC,EAAS,4DAA6D,CAC3E,QACC,iGACF,CAAC,EACD,OAAO,EAAS,CACf,IAAMC,EAAOC,EAAQC,CAAO,GAAK,GAC3BC,EAAQH,EAAK,MAAM,kEAAkE,EAC3F,GAAI,CAACG,EAAO,MAAO,CAAC,EACpB,IAAMC,EAAOD,EAAM,GACnB,MAAO,CACN,QAAQ,EAAS,CAChB,IAAME,EAAWC,EAAWJ,EAASK,EAASL,EAAQ,QAAQ,EAExDM,EADUC,EAAkBF,CACb,CAAC,CAAC,IAAK,GAAeF,EAASK,CAAU,CAAC,EACzDC,EACLP,IAAS,WACN,uBACAA,IAAS,UACR,qBACAA,IAAS,SACR,kBACAA,IAAS,YACR,wBACAJ,IAAS,kBACR,wBACA,uBACFY,EACLR,IAAS,WACN,mBACAA,IAAS,UACR,iBACAA,IAAS,SACR,QACAA,IAAS,YACR,WACAJ,IAAS,kBACR,WACA,WACFa,EAAQL,EAAO,OAAQ,GAAUM,IAAUF,CAAM,CAAC,CAAC,QAC3CR,IAAS,YAAcA,IAAS,UAAYS,IAAU,EAAIA,EAAQ,IAE/EX,EAAQ,OAAO,CAAE,KAAMK,EAAS,UAAW,UAAW,KAAM,CAAE,OAAM,UAAS,CAAE,CAAC,CAClF,CACD,CACD,CACD,EAEA,SAASE,EAAkB,EAA8C,CACxE,IAAMM,EAAmC,CAAC,EACpCC,kBAAe,IAAI,IACzB,IAAK,IAAMC,KAAaV,EAAQ,KAAM,CACrC,IAAMW,EACLD,EAAU,OAAS,yBAA2BA,EAAU,YAAcA,EACvE,GAAIC,GAAa,OAAS,uBAAyBA,EAAY,OAAS,QAClE,IAAA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ACR,GAAIN,EAAO,MAAO,GAAUM,IAAU,MAAM,EAAG,MAAO,MACvD,CAEA,OADI2B,EAAK,OAAS,UAAkB,OAC7B,IACR,CACA,OAAOpC,CACR"}
|
|
1
|
+
{"version":3,"file":"reserved-files.mjs","names":["reservedDomainFiles","metadata","file","appFile","context","match","role","evaluate","provenance","program","values","publicExpressions","expression","expected","wanted","count","value","expressions","declarations","statement","declaration","item","specifier","exportName","imports","variables","resolver","createResolver","property","imported","source","name","target","resolveImport","filename","visited","parsed","parseSync","readFileSync","remote","evaluateRemote","member","owner","node","active","reference","variable","propertyName","callee","members"],"sources":["../../src/oxlint/reserved-files.ts"],"sourcesContent":["import { readFileSync } from 'node:fs'\nimport type { Context, CreateRule, ESTree } from '@oxlint/plugins'\nimport { parseSync } from 'oxc-parser'\nimport { appFile, metadata, propertyName, exportName } from './ast'\nimport { createResolver, resolveImport } from './architecture'\n\n/** Reserved files prove their exported declaration's provenance, not an unused import. */\nexport const reservedDomainFiles: CreateRule = {\n\tmeta: metadata('Require kit-backed declarations in reserved domain files.', {\n\t\tanatomy:\n\t\t\t'{{file}} must export {{expected}} built with cvx-kit; imports or local lookalikes do not count.',\n\t}),\n\tcreate(context) {\n\t\tconst file = appFile(context) ?? ''\n\t\tconst match = file.match(/^domain\\/(?:.+\\/)?(commands|queries|contracts|schema|table)\\.ts$/)\n\t\tif (!match) return {}\n\t\tconst role = match[1]\n\t\treturn {\n\t\t\tProgram(program) {\n\t\t\t\tconst evaluate = provenance(context, program, context.filename)\n\t\t\t\tconst exports = publicExpressions(program)\n\t\t\t\tconst values = exports.map((expression) => evaluate(expression))\n\t\t\t\tconst expected =\n\t\t\t\t\trole === 'commands'\n\t\t\t\t\t\t? 'one Command registry'\n\t\t\t\t\t\t: role === 'queries'\n\t\t\t\t\t\t\t? 'one Query registry'\n\t\t\t\t\t\t\t: role === 'schema'\n\t\t\t\t\t\t\t\t? 'zodTable shapes'\n\t\t\t\t\t\t\t\t: role === 'contracts'\n\t\t\t\t\t\t\t\t\t? 'declarative contracts'\n\t\t\t\t\t\t\t\t\t: file === 'domain/table.ts'\n\t\t\t\t\t\t\t\t\t\t? 'createModule assembly'\n\t\t\t\t\t\t\t\t\t\t: 'a table topology map'\n\t\t\t\tconst wanted =\n\t\t\t\t\trole === 'commands'\n\t\t\t\t\t\t? 'registry:Command'\n\t\t\t\t\t\t: role === 'queries'\n\t\t\t\t\t\t\t? 'registry:Query'\n\t\t\t\t\t\t\t: role === 'schema'\n\t\t\t\t\t\t\t\t? 'shape'\n\t\t\t\t\t\t\t\t: role === 'contracts'\n\t\t\t\t\t\t\t\t\t? 'contract'\n\t\t\t\t\t\t\t\t\t: file === 'domain/table.ts'\n\t\t\t\t\t\t\t\t\t\t? 'assembly'\n\t\t\t\t\t\t\t\t\t\t: 'topology'\n\t\t\t\tconst count = values.filter((value) => value === wanted).length\n\t\t\t\tconst valid = role === 'commands' || role === 'queries' ? count === 1 : count > 0\n\t\t\t\tif (!valid)\n\t\t\t\t\tcontext.report({ node: program, messageId: 'anatomy', data: { file, expected } })\n\t\t\t},\n\t\t}\n\t},\n}\n\nfunction publicExpressions(program: ESTree.Program): ESTree.Expression[] {\n\tconst expressions: ESTree.Expression[] = []\n\tconst declarations = new Map<string, ESTree.Expression>()\n\tfor (const statement of program.body) {\n\t\tconst declaration =\n\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\tif (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const')\n\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\tif (item.id.type === 'Identifier' && item.init) {\n\t\t\t\t\tdeclarations.set(item.id.name, item.init)\n\t\t\t\t\tif (statement.type === 'ExportNamedDeclaration') expressions.push(item.init)\n\t\t\t\t}\n\t\t\t}\n\t}\n\tfor (const statement of program.body) {\n\t\tif (\n\t\t\tstatement.type === 'ExportNamedDeclaration' &&\n\t\t\tstatement.exportKind !== 'type' &&\n\t\t\t!statement.source\n\t\t)\n\t\t\tfor (const specifier of statement.specifiers) {\n\t\t\t\tif (specifier.exportKind === 'type') continue\n\t\t\t\tconst expression = declarations.get(exportName(specifier.local) ?? '')\n\t\t\t\tif (expression) expressions.push(expression)\n\t\t\t}\n\t\tif (\n\t\t\tstatement.type === 'ExportDefaultDeclaration' &&\n\t\t\tstatement.declaration.type !== 'FunctionDeclaration' &&\n\t\t\tstatement.declaration.type !== 'ClassDeclaration' &&\n\t\t\tstatement.declaration.type !== 'TSInterfaceDeclaration'\n\t\t) {\n\t\t\texpressions.push(statement.declaration)\n\t\t}\n\t}\n\treturn expressions\n}\n\nfunction provenance(\n\tcontext: Context,\n\tprogram: ESTree.Program,\n\tfilename: string,\n\tvisited = new Set<string>(),\n) {\n\tconst imports = new Map<string, { source: string; name: string }>()\n\tconst variables = new Map<string, { expression: ESTree.Expression; member?: string }>()\n\tconst resolver = createResolver()\n\tfor (const statement of program.body) {\n\t\tif (statement.type === 'ImportDeclaration' && statement.importKind !== 'type')\n\t\t\tfor (const specifier of statement.specifiers) {\n\t\t\t\tif (specifier.type === 'ImportSpecifier' && specifier.importKind === 'type') continue\n\t\t\t\timports.set(specifier.local.name, {\n\t\t\t\t\tsource: statement.source.value,\n\t\t\t\t\tname:\n\t\t\t\t\t\tspecifier.type === 'ImportSpecifier'\n\t\t\t\t\t\t\t? (exportName(specifier.imported) ?? '')\n\t\t\t\t\t\t\t: specifier.type === 'ImportNamespaceSpecifier'\n\t\t\t\t\t\t\t\t? '*'\n\t\t\t\t\t\t\t\t: 'default',\n\t\t\t\t})\n\t\t\t}\n\t\tconst declaration =\n\t\t\tstatement.type === 'ExportNamedDeclaration' ? statement.declaration : statement\n\t\tif (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const')\n\t\t\tfor (const item of declaration.declarations) {\n\t\t\t\tif (!item.init) continue\n\t\t\t\tif (item.id.type === 'Identifier') variables.set(item.id.name, { expression: item.init })\n\t\t\t\tif (item.id.type === 'ObjectPattern')\n\t\t\t\t\tfor (const property of item.id.properties) {\n\t\t\t\t\t\tif (property.type === 'Property' && property.value.type === 'Identifier')\n\t\t\t\t\t\t\tvariables.set(property.value.name, {\n\t\t\t\t\t\t\t\texpression: item.init,\n\t\t\t\t\t\t\t\tmember: exportName(property.key) ?? '',\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t}\n\t}\n\tfunction imported(source: string, name: string): string | null {\n\t\tif (\n\t\t\t[\n\t\t\t\t'cvx-kit',\n\t\t\t\t'cvx-kit/effect',\n\t\t\t\t'cvx-kit/components/foundation',\n\t\t\t\t'cvx-kit/contracts',\n\t\t\t\t'cvx-kit/zod-table',\n\t\t\t\t'cvx-kit/errors',\n\t\t\t].includes(source)\n\t\t) {\n\t\t\tif (name === '*') return `namespace:${source}`\n\t\t\tif (\n\t\t\t\t(source === 'cvx-kit/effect' && name === 'createEffectFoundation') ||\n\t\t\t\t(source === 'cvx-kit' && name === 'createFoundation') ||\n\t\t\t\t(['cvx-kit', 'cvx-kit/components/foundation'].includes(source) && name === 'Foundation')\n\t\t\t)\n\t\t\t\treturn 'foundationFactory'\n\t\t\tif (\n\t\t\t\t['cvx-kit', 'cvx-kit/zod-table'].includes(source) &&\n\t\t\t\t['zodTable', 'zodVariantTable'].includes(name)\n\t\t\t)\n\t\t\t\treturn 'shapeFactory'\n\t\t\tif (['cvx-kit', 'cvx-kit/zod-table'].includes(source) && name === 'createModule')\n\t\t\t\treturn 'assemblyFactory'\n\t\t\tif (source === 'cvx-kit/zod-table' && name === 'namespace') return 'namespaceFactory'\n\t\t\tif (\n\t\t\t\tsource === 'cvx-kit/contracts' &&\n\t\t\t\t['defineDomainContract', 'operationContract'].includes(name)\n\t\t\t)\n\t\t\t\treturn 'contractFactory'\n\t\t\tif (source === 'cvx-kit/errors' && name === 'defineErrorContract') return 'contractFactory'\n\t\t\treturn null\n\t\t}\n\t\tif (['zod', 'zod/v4', 'convex/values'].includes(source)) return 'validator'\n\t\tconst target = resolveImport(resolver, filename, source)\n\t\tconst file = target && appFile(context, target)\n\t\tif (\n\t\t\t!target ||\n\t\t\t!file ||\n\t\t\t!/^(?:foundation\\.ts|domain\\/.+\\/(?:schema|contracts)\\.ts)$/.test(file) ||\n\t\t\tvisited.has(target) ||\n\t\t\tvisited.size >= 6\n\t\t)\n\t\t\treturn null\n\t\tif (name === '*') return `namespace:${source}`\n\t\tconst parsed = parseSync(target, readFileSync(target, 'utf8'))\n\t\tif (parsed.errors.length) return null\n\t\t// SAFETY: oxc-parser and the rule API share these declaration fields; provenance never reads rule-API loc/tokens.\n\t\t// oxlint-disable-next-line anti-slop/no-chained-type-assertions\n\t\tconst remote = parsed.program as unknown as ESTree.Program\n\t\tconst nextVisited = new Set(visited).add(target)\n\t\tconst evaluateRemote = provenance(context, remote, target, nextVisited)\n\t\tfor (const statement of remote.body) {\n\t\t\tif (statement.type !== 'ExportNamedDeclaration' || statement.exportKind === 'type') continue\n\t\t\tif (statement.declaration?.type === 'VariableDeclaration')\n\t\t\t\tfor (const item of statement.declaration.declarations) {\n\t\t\t\t\tif (item.id.type === 'Identifier' && item.id.name === name) return evaluateRemote(item.id)\n\t\t\t\t\tif (item.id.type === 'ObjectPattern')\n\t\t\t\t\t\tfor (const property of item.id.properties)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tproperty.type === 'Property' &&\n\t\t\t\t\t\t\t\tproperty.value.type === 'Identifier' &&\n\t\t\t\t\t\t\t\tproperty.value.name === name\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\treturn evaluateRemote(property.value)\n\t\t\t\t}\n\t\t\tfor (const specifier of statement.specifiers)\n\t\t\t\tif (\n\t\t\t\t\tspecifier.exportKind !== 'type' &&\n\t\t\t\t\texportName(specifier.exported) === name &&\n\t\t\t\t\t!statement.source\n\t\t\t\t)\n\t\t\t\t\treturn evaluateRemote(specifier.local)\n\t\t}\n\t\treturn null\n\t}\n\tfunction member(owner: string | null, name: string): string | null {\n\t\tif (owner === 'foundation' && ['Command', 'Query'].includes(name)) return name\n\t\tif (owner?.startsWith('namespace:')) return imported(owner.slice(10), name)\n\t\tif (owner === 'validator' || owner === 'contract') return 'validator'\n\t\tif (owner === 'shape' && name === 'table') return 'table'\n\t\tif (owner === 'table' && ['index', 'searchIndex', 'vectorIndex'].includes(name))\n\t\t\treturn 'indexFactory'\n\t\treturn null\n\t}\n\tfunction evaluate(node: ESTree.Node, active = new Set<string>()): string | null {\n\t\tif (\n\t\t\tnode.type === 'TSAsExpression' ||\n\t\t\tnode.type === 'TSSatisfiesExpression' ||\n\t\t\tnode.type === 'TSNonNullExpression'\n\t\t)\n\t\t\treturn evaluate(node.expression, active)\n\t\tif (node.type === 'Identifier') {\n\t\t\tif (active.has(node.name)) return null\n\t\t\tconst reference = imports.get(node.name)\n\t\t\tif (reference) return imported(reference.source, reference.name)\n\t\t\tconst variable = variables.get(node.name)\n\t\t\tif (!variable) return null\n\t\t\tconst value = evaluate(variable.expression, new Set(active).add(node.name))\n\t\t\treturn variable.member ? member(value, variable.member) : value\n\t\t}\n\t\tif (node.type === 'MemberExpression')\n\t\t\treturn member(evaluate(node.object, active), propertyName(node) ?? '')\n\t\tif (node.type === 'CallExpression' || node.type === 'NewExpression') {\n\t\t\tconst callee = evaluate(node.callee, active)\n\t\t\tif (callee === 'foundationFactory') return 'foundation'\n\t\t\tif (callee === 'Command' || callee === 'Query') return `registry:${callee}`\n\t\t\tif (callee === 'shapeFactory') return 'shape'\n\t\t\tif (callee === 'assemblyFactory') return 'assembly'\n\t\t\tif (callee === 'contractFactory' || callee === 'validator') return 'contract'\n\t\t\tif (callee === 'indexFactory') return 'table'\n\t\t\tif (callee === 'namespaceFactory') {\n\t\t\t\t// namespace(name, members) is a topology map when every member is a table\n\t\t\t\t// definition or a table boundary (namespace() unwraps boundaries itself).\n\t\t\t\tconst members = node.arguments[1]\n\t\t\t\tif (members?.type !== 'ObjectExpression') return null\n\t\t\t\tconst values = members.properties.map((property) =>\n\t\t\t\t\tproperty.type === 'Property' ? evaluate(property.value, active) : null,\n\t\t\t\t)\n\t\t\t\treturn values.length &&\n\t\t\t\t\tvalues.every((value) => value === 'table' || value === 'topology' || value === 'shape')\n\t\t\t\t\t? 'topology'\n\t\t\t\t\t: null\n\t\t\t}\n\t\t\treturn null\n\t\t}\n\t\tif (node.type === 'ObjectExpression') {\n\t\t\tconst values = node.properties.map((property) =>\n\t\t\t\tproperty.type === 'Property' ? evaluate(property.value, active) : null,\n\t\t\t)\n\t\t\tif (values.length && values.every((value) => value === 'table' || value === 'topology'))\n\t\t\t\treturn 'topology'\n\t\t\tif (\n\t\t\t\tvalues.some((value) => value === 'contract' || value === 'validator') &&\n\t\t\t\tvalues.every((value) => value === 'contract' || value === 'validator' || value === 'data')\n\t\t\t)\n\t\t\t\treturn 'contract'\n\t\t\tif (values.every((value) => value === 'data')) return 'data'\n\t\t}\n\t\tif (node.type === 'Literal') return 'data'\n\t\treturn null\n\t}\n\treturn evaluate\n}\n"],"mappings":"yOAOA,MAAaA,EAAkC,CAC9C,KAAMC,EAAS,4DAA6D,CAC3E,QACC,iGACF,CAAC,EACD,OAAO,EAAS,CACf,IAAMC,EAAOC,EAAQC,CAAO,GAAK,GAC3BC,EAAQH,EAAK,MAAM,kEAAkE,EAC3F,GAAI,CAACG,EAAO,MAAO,CAAC,EACpB,IAAMC,EAAOD,EAAM,GACnB,MAAO,CACN,QAAQ,EAAS,CAChB,IAAME,EAAWC,EAAWJ,EAASK,EAASL,EAAQ,QAAQ,EAExDM,EADUC,EAAkBF,CACb,CAAC,CAAC,IAAK,GAAeF,EAASK,CAAU,CAAC,EACzDC,EACLP,IAAS,WACN,uBACAA,IAAS,UACR,qBACAA,IAAS,SACR,kBACAA,IAAS,YACR,wBACAJ,IAAS,kBACR,wBACA,uBACFY,EACLR,IAAS,WACN,mBACAA,IAAS,UACR,iBACAA,IAAS,SACR,QACAA,IAAS,YACR,WACAJ,IAAS,kBACR,WACA,WACFa,EAAQL,EAAO,OAAQ,GAAUM,IAAUF,CAAM,CAAC,CAAC,QAC3CR,I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tC,GAAIA,IAAW,kBAAmB,MAAO,WACzC,GAAIA,IAAW,mBAAqBA,IAAW,YAAa,MAAO,WACnE,GAAIA,IAAW,eAAgB,MAAO,QACtC,GAAIA,IAAW,mBAAoB,CAGlC,IAAMC,EAAUN,EAAK,UAAU,GAC/B,GAAIM,GAAS,OAAS,mBAAoB,OAAO,KACjD,IAAMvC,EAASuC,EAAQ,WAAW,IAAK,GACtCrB,EAAS,OAAS,WAAarB,EAASqB,EAAS,MAAOgB,CAAM,EAAI,IACnE,EACA,OAAOlC,EAAO,QACbA,EAAO,MAAO,GAAUM,IAAU,SAAWA,IAAU,YAAcA,IAAU,OAAO,EACpF,WACA,IACJ,CACA,OAAO,IACR,CACA,GAAI2B,EAAK,OAAS,mBAAoB,CACrC,IAAMjC,EAASiC,EAAK,WAAW,IAAK,GACnCf,EAAS,OAAS,WAAarB,EAASqB,EAAS,MAAOgB,CAAM,EAAI,IACnE,EACA,GAAIlC,EAAO,QAAUA,EAAO,MAAO,GAAUM,IAAU,SAAWA,IAAU,UAAU,EACrF,MAAO,WACR,GACCN,EAAO,KAAM,GAAUM,IAAU,YAAcA,IAAU,WAAW,GACpEN,EAAO,MAAO,GAAUM,IAAU,YAAcA,IAAU,aAAeA,IAAU,MAAM,EAEzF,MAAO,WACR,GAAIN,EAAO,MAAO,GAAUM,IAAU,MAAM,EAAG,MAAO,MACvD,CAEA,OADI2B,EAAK,OAAS,UAAkB,OAC7B,IACR,CACA,OAAOpC,CACR"}
|
package/dist/zod-table.d.mts
CHANGED
|
@@ -151,10 +151,22 @@ export type Namespace<Name extends string, Tables extends Record<string, TableDe
|
|
|
151
151
|
export type NamespaceTag<Name extends string, Tables extends string> = {
|
|
152
152
|
readonly [namespaceKey]: NamespaceInfo<Name, Tables>;
|
|
153
153
|
};
|
|
154
|
-
|
|
155
|
-
|
|
154
|
+
type DotsToUnderscores<Name extends string> = Name extends `${infer Head}.${infer Tail}` ? `${Head}_${DotsToUnderscores<Tail>}` : Name;
|
|
155
|
+
/** Stored-table prefix of a namespace: `Microsoft.Inventory` → `Microsoft_Inventory_`. */
|
|
156
|
+
export type NamespacePrefix<Name extends string> = `${DotsToUnderscores<Name>}_`;
|
|
157
|
+
/**
|
|
158
|
+
* Member name of a table. A table stored with its namespace prefix drops it
|
|
159
|
+
* (`Inventory_Items` in `Inventory` → `Items`); any other table name is
|
|
160
|
+
* PascalCased (`itemLedgerEntries` → `ItemLedgerEntries`).
|
|
161
|
+
*/
|
|
162
|
+
export type MemberName<TableName extends string, Name extends string = never> = [Name] extends [never] ? Capitalize<TableName> : TableName extends `${NamespacePrefix<Name>}${infer Rest extends string}` ? Rest extends '' ? Capitalize<TableName> : Rest : Capitalize<TableName>;
|
|
156
163
|
/** Fully qualified name: `<Namespace>.<Member>`, e.g. `Inventory.Items`. */
|
|
157
|
-
export type QualifiedName<Name extends string, TableName extends string> = `${Name}.${MemberName<TableName>}`;
|
|
164
|
+
export type QualifiedName<Name extends string, TableName extends string> = `${Name}.${MemberName<TableName, Name>}`;
|
|
165
|
+
/** Options for `namespace(...)`. */
|
|
166
|
+
export type NamespaceOptions<Prefixed extends boolean = boolean> = {
|
|
167
|
+
/** Require every key to start with the namespace prefix (`Inventory_`). */
|
|
168
|
+
prefixed?: Prefixed;
|
|
169
|
+
};
|
|
158
170
|
type NamespaceMember = TableDefinition<any> | {
|
|
159
171
|
tableName: string;
|
|
160
172
|
table: TableDefinition<any>;
|
|
@@ -162,29 +174,40 @@ type NamespaceMember = TableDefinition<any> | {
|
|
|
162
174
|
type MemberTables<Members extends Record<string, NamespaceMember>> = { [Key in keyof Members]: Members[Key] extends {
|
|
163
175
|
table: infer Table extends TableDefinition<any>;
|
|
164
176
|
} ? Table : Extract<Members[Key], TableDefinition<any>>; };
|
|
165
|
-
type CheckedMembers<Members extends Record<string, NamespaceMember
|
|
177
|
+
type CheckedMembers<Members extends Record<string, NamespaceMember>, Name extends string, Prefixed extends boolean> = { [Key in keyof Members]: Prefixed extends true ? Key extends `${NamespacePrefix<Name>}${infer Rest}` ? Rest extends '' ? never : CheckedMember<Members[Key], Key> : never : CheckedMember<Members[Key], Key>; };
|
|
178
|
+
type CheckedMember<Member, Key> = Member extends {
|
|
166
179
|
tableName: infer TableName;
|
|
167
|
-
} ? TableName extends Key ?
|
|
180
|
+
} ? TableName extends Key ? Member : {
|
|
168
181
|
tableName: Key;
|
|
169
182
|
table: TableDefinition<any>;
|
|
170
|
-
} :
|
|
183
|
+
} : Member;
|
|
171
184
|
type CheckedNamespaceName<Name extends string> = Name extends '' ? never : Name extends `${string}..${string}` | `.${string}` | `${string}.` ? never : Name;
|
|
172
185
|
/**
|
|
173
186
|
* Groups tables under a declaration-level namespace, like AL's
|
|
174
187
|
* `namespace Microsoft.Inventory.Item;`. Keys are the real (stored) table
|
|
175
|
-
* names, exactly as in an un-namespaced module map
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
* `
|
|
188
|
+
* names, exactly as in an un-namespaced module map. A key stored with the
|
|
189
|
+
* namespace prefix (`Inventory_Items`, or `Microsoft_Inventory_Items` for
|
|
190
|
+
* `Microsoft.Inventory`) has the remainder as its member name (`Items`);
|
|
191
|
+
* any other key is PascalCased (`items` → `Items`). The qualified name is
|
|
192
|
+
* `<Namespace>.<Member>` (`Inventory.Items`). Storage, ids, queries and
|
|
193
|
+
* generated types are unchanged.
|
|
194
|
+
*
|
|
195
|
+
* `{ prefixed: true }` requires every key to carry the prefix: a key
|
|
196
|
+
* without it is a type error and a runtime error.
|
|
179
197
|
*
|
|
180
198
|
* A member may be a `TableDefinition` (`items.table.index(...)`) or a table
|
|
181
199
|
* boundary (`items`); a boundary whose `tableName` differs from its key is a
|
|
182
200
|
* type error and a runtime error. Dotted names (`Microsoft.Inventory`) are
|
|
183
201
|
* allowed; each segment must be PascalCase.
|
|
184
202
|
*/
|
|
185
|
-
export declare function namespace<const Name extends string, const Members extends Record<string, NamespaceMember
|
|
186
|
-
/**
|
|
187
|
-
export declare function
|
|
203
|
+
export declare function namespace<const Name extends string, const Members extends Record<string, NamespaceMember>, const Prefixed extends boolean = false>(name: Name & CheckedNamespaceName<Name>, members: Members & CheckedMembers<Members, Name, Prefixed>, options?: NamespaceOptions<Prefixed>): Namespace<Name, MemberTables<Members>>;
|
|
204
|
+
/** Stored-table prefix of a namespace: `Microsoft.Inventory` → `Microsoft_Inventory_`. */
|
|
205
|
+
export declare function namespacePrefix<const Name extends string>(name: Name): NamespacePrefix<Name>;
|
|
206
|
+
/**
|
|
207
|
+
* Member name of a table name: without the namespace prefix when given and
|
|
208
|
+
* present (`memberName('Inventory_Items', 'Inventory')` → `Items`), else PascalCased.
|
|
209
|
+
*/
|
|
210
|
+
export declare function memberName<const TableName extends string, const Name extends string = never>(tableName: TableName, namespaceName?: Name): MemberName<TableName, Name>;
|
|
188
211
|
/** The namespace name of a `namespace(...)` map. */
|
|
189
212
|
export declare function namespaceName<const Name extends string>(ns: NamespaceTag<Name, string>): Name;
|
|
190
213
|
/** The stored table names declared in a namespace, in declaration order. */
|
package/dist/zod-table.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{zodToConvex as e}from"./zod-convex.mjs";import{memoize as t}from"./modules/contracts/lazy.mjs";import{pageResult as n}from"./querying/shared/page.mjs";import{scalarPaginationSchema as r}from"./querying/filters.mjs";import{convexToZod as i,convexToZod as a,zid as o,zid as s}from"convex-helpers/server/zod4";import{defineTable as c,paginationOptsValidator as l}from"convex/server";import{z as u}from"zod";const d={createdAt:u.number().optional(),updatedAt:u.number().optional(),archivedAt:u.number().optional()},f=[`createdAt`,`updatedAt`,`archivedAt`];function p(n,i,a={}){let o=i(s);L(o,[`_id`,`_creationTime`,...f]);let l={...o,...d};R(l,a.serverFields??[],a.commandFields??[],a.publicFields??[]);let p=u.strictObject({...l}),m=t(()=>N(l,n)),h=[...f,...a.serverFields??[]],g=[...a.commandFields??[]],_=[...a.publicFields??[]],v=t(()=>F(l,h)),y=t(()=>P(l,g)),b=t(()=>u.strictObject({...v()})),x=t(()=>u.strictObject({...v()}).partial()),S=t(()=>u.strictObject({...y()})),C=t(()=>u.strictObject(P(l,_))),w={get schema(){return m()},get insertSchema(){return b()},get updateSchema(){return x()},get commandInput(){return S()},get publicDto(){return C()}},T=t(()=>u.strictObject({})),E=t(()=>/* @__PURE__ */ new Set([`_id`,`_creationTime`,`tenant`,`__proto__`,...f]));function D(e){return k(e)}function k(e){let t=e===!0||e===!1?{_id:e}:e,n=t?.extend??{};if(A(n),!t?._id&&Object.keys(n).length===0)return w.publicDto;let r=u.strictObject({...w.publicDto.shape,...n});return t?._id?r.extend({_id:w.schema.shape._id}):r}function A(e){for(let t of Object.keys(e)){if(E().has(t)||Object.hasOwn(w.publicDto.shape,t))throw Error(`DTO extension collision for field "${t}" on table "${n}"`);I(e[t])}}function j(e,t){let n=t===!0||t===!1?{_id:t}:t;A(n?.extend??{});let r=w.publicDto.parse(Object.fromEntries(Object.keys(w.publicDto.shape).map(t=>[t,e[t]]))),i=n?.extend,a=(i==null?T():u.strictObject(i)).parse(n?.values??{}),o={...r,...a};return n?._id&&(o._id=w.schema.shape._id.parse(`_id`in e?e._id:void 0)),o}function z(e){return e?w.insertSchema.omit(e):w.insertSchema}function B(e){return e?w.updateSchema.omit(e):w.updateSchema}let V=e(p),H=c(V),U=()=>Object.fromEntries(Object.entries(w.schema.shape).map(([t,n])=>[t,e(n)]));function W(e,t){return r(U(),e,t)}let G=t(()=>({insert:w.commandInput,update:u.strictObject({data:u.strictObject({...y()}).partial(),id:O(n)}),id:u.strictObject({id:O(n)})}));return{tableName:n,get schema(){return w.schema},set schema(e){M(this,`schema`,e)},storage:p,get insertSchema(){return w.insertSchema},set insertSchema(e){M(this,`insertSchema`,e)},get updateSchema(){return w.updateSchema},set updateSchema(e){M(this,`updateSchema`,e)},get commandInput(){return w.commandInput},set commandInput(e){M(this,`commandInput`,e)},get publicDto(){return w.publicDto},set publicDto(e){M(this,`publicDto`,e)},dto:D,toPublicDto:j,paginationOpts:W,table:H,insert:z,update:B,get tools(){return G()},set tools(e){M(this,`tools`,e)}}}function m(e){return L(e,[`_id`,`_creationTime`,...f]),function(t,n,r={}){return p(t,r=>{let i=n(r);for(let n of Object.keys(i))if(Object.hasOwn(e,n))throw Error(`Duplicate shared table field "${n}" on table "${t}"`);return L(i,[`_id`,`_creationTime`,...f]),{...e,...i}},r)}}const h={tenant:u.string().min(1)};function g(e,t,n={}){return p(e,e=>{let n=t(e);return L(n,[`tenant`,`_id`,`_creationTime`,...f]),{...n,...h}},{...n,serverFields:[...n.serverFields??[],`tenant`]})}function _(...e){let t={},n=/* @__PURE__ */ new Set;for(let r of e){let e=x(r);if(e){if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.add(e.name)}for(let[e,n]of Object.entries(r)){if(e in t)throw Error(`Table "${e}" is declared by more than one module`);t[e]=n}}return t}const v=Symbol.for(`cvx-kit/zod-table/namespace`),y=/^[A-Z][A-Za-z0-9]*$/;function b(e,t){if(!e.split(`.`).every(e=>y.test(e)))throw Error(`Namespace "${e}" must be dot-separated PascalCase segments (e.g. "Microsoft.Inventory")`);let n={};for(let[r,i]of Object.entries(t)){if(!/^[a-z][A-Za-z0-9]*$/.test(r))throw Error(`Namespace "${e}" member "${r}" must be a camelCase table name`);if(`tableName`in i){if(i.tableName!==r)throw Error(`Namespace "${e}" member "${r}" holds table "${i.tableName}"; keys must be the table name`);n[r]=i.table}else n[r]=i}return Object.defineProperty(n,v,{value:Object.freeze({name:e,tables:Object.freeze(Object.keys(n))}),enumerable:!1}),n}function x(e){return e[v]}function S(e){return e.charAt(0).toUpperCase()+e.slice(1)}function C(e){return x(e).name}function w(e){return x(e).tables}function T(...e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let r of e){let e=x(r);if(!e)throw Error(`namespaceIndex accepts only namespace(...) maps`);if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.set(e.name,e.tables);for(let n of e.tables){let r=t.get(n);if(r)throw Error(`Table "${n}" is declared by namespaces "${r}" and "${e.name}"`);t.set(n,e.name)}}let r=e=>{let n=t.get(e);if(n===void 0)throw Error(`Table "${e}" is not in a namespace`);return n};return{qualifiedName(e){return`${r(e)}.${S(e)}`},namespaceOf(e){return r(e)},memberName:S,tablesOf(e){let t=n.get(e);if(!t)throw Error(`Namespace "${e}" is not indexed`);return t},namespaces:[...n.keys()],has(e){return t.has(e)}}}function E(e){return{args:{paginationOpts:a(l)},result:n(e)}}function D(t,n,r){return r?k(t,n,r):{tableName:t,storage:n,insertSchema:n,table:c(e(n))}}function O(e){let t=s(e);return u.string().refine(e=>t.safeParse(e).success).describe(`Convex document id for table "${e}"; validated against the table by Convex`)}function k(n,r,i){if(!(r instanceof u.ZodDiscriminatedUnion)||r.def.discriminator!==i.discriminator)throw Error(`Variant boundaries require a discriminated union with the configured discriminator`);if(r.def.checks?.length)throw Error(`Variant boundaries do not support union-level refinements`);let a=i.timestamps,o=i.discriminator;if([`_id`,`_creationTime`,...f].includes(o))throw Error(`Variant discriminator cannot be a reserved field`);let l=/* @__PURE__ */ new Map;for(let e of r.options){if(!(e instanceof u.ZodObject)||!(e.def.catchall instanceof u.ZodNever))throw Error(`Variant boundaries require strict object branches`);if(e.def.checks?.length)throw Error(`Variant boundaries do not support object-level refinements`);try{I(e,/* @__PURE__ */ new Set,!0)}catch(e){throw Error(`Variant boundaries require supported value-preserving field validators without object catchalls`,{cause:e})}let r=e.shape[o];if(!(r instanceof u.ZodLiteral)||r.values.size!==1)throw Error(`Variant branches require one string literal discriminator`);let s=[...r.values][0];if(!u.string().safeParse(s).success)throw Error(`Variant branches require a string discriminator`);let c=s;if(l.has(c))throw Error(`Duplicate variant discriminator "${c}"`);if(!Object.hasOwn(i.variants,c))throw Error(`Missing variant configuration "${c}"`);let p={serverFields:[...i.variants[c].serverFields??[]],commandFields:[...i.variants[c].commandFields??[]],publicFields:[...i.variants[c].publicFields??[]]};L(e.shape,[`_id`,`_creationTime`,...a===!1?[]:f]);let m={...e.shape};a&&Object.assign(m,d),R(m,p.serverFields??[],p.commandFields??[],p.publicFields??[],a!==!1);for(let e of[p.serverFields,p.commandFields,p.publicFields])if(e?.includes(o))throw Error(`The variant discriminator is retained automatically and cannot appear in masks`);for(let e of p.commandFields)A(m[e]);let h=u.strictObject({...m}),g=t(()=>u.strictObject(F(m,[...a===!1?[]:f,...p.serverFields??[]]))),_=t(()=>u.strictObject(P(m,[o,...p.commandFields??[]]))),v=e=>e.partial().extend({[o]:r}),y=t(()=>N(m,n)),b=t(()=>v(u.strictObject(F(m,[...a===!1?[]:f,...p.serverFields])))),x=t(()=>v(u.strictObject(P(m,[o,...p.commandFields])))),S=t(()=>u.strictObject(P(m,[o,...p.commandFields]))),C=t(()=>u.strictObject(P(m,[o,...p.publicFields??[]])));l.set(c,{storage:h,get document(){return y()},get insert(){return g()},get update(){return b()},get command(){return _()},get commandUpdate(){return x()},get toolCommand(){return S()},get public(){return C()}})}for(let e of Object.keys(i.variants))if(!l.has(e))throw Error(`Unknown variant configuration "${e}"`);function p(e,t=!1,r=!1){let i=[...l.values()].map(i=>{let a=r&&e===`command`?i.toolCommand:i[e];return r?u.strictObject(Object.fromEntries(Object.entries(a.shape).map(([e,t])=>[e,j(t)]))):t?a.extend({_id:s(n)}):a});if(!i.length)throw Error(`Variant boundaries require at least one branch`);return u.discriminatedUnion(o,i)}let m=p(`storage`),h=t(()=>p(`document`)),g=t(()=>p(`insert`)),_=t(()=>p(`update`)),v=t(()=>p(`command`)),y=t(()=>p(`public`));function b(e=!1){return e?p(`public`,!0):y()}let x;function S(e,t=!1){let r=u.string().parse(e[o]),i=l.get(r);if(!i)throw Error(`Unknown variant discriminator "${r}"`);let a=t?i.public.extend({_id:x??=s(n)}):i.public;return a.parse(Object.fromEntries(Object.keys(a.shape).filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]])))}let C=t(()=>({id:u.strictObject({id:O(n)}),insert:p(`command`,!1,!0),update:u.strictObject({id:O(n),data:p(`commandUpdate`,!1,!0)})}));return{tableName:n,storage:m,get schema(){return h()},set schema(e){M(this,`schema`,e)},get insertSchema(){return g()},set insertSchema(e){M(this,`insertSchema`,e)},get updateSchema(){return _()},set updateSchema(e){M(this,`updateSchema`,e)},get commandInput(){return v()},set commandInput(e){M(this,`commandInput`,e)},get publicDto(){return y()},set publicDto(e){M(this,`publicDto`,e)},dto:b,toPublicDto:S,table:c(e(m)),get tools(){return C()},set tools(e){M(this,`tools`,e)}}}function A(e){if(!(e instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(e instanceof u.ZodBigInt||e instanceof u.ZodLiteral&&[...e.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);e instanceof u.ZodOptional||e instanceof u.ZodNullable||e instanceof u.ZodNonOptional?A(e.unwrap()):e instanceof u.ZodArray?A(e.element):e instanceof u.ZodObject?Object.values(e.shape).forEach(A):e instanceof u.ZodUnion?e.options.forEach(A):e instanceof u.ZodRecord?(A(e.keyType),A(e.valueType)):e instanceof u.ZodTuple?(e.def.items.forEach(A),e.def.rest&&A(e.def.rest)):e instanceof u.ZodIntersection&&(A(e.def.left),A(e.def.right))}function j(t){if(!(t instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(t instanceof u.ZodBigInt||t instanceof u.ZodLiteral&&[...t.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);let n=e(t);if(n.kind===`id`){let e=O(n.tableName);return n.isOptional===`optional`?e.optional().refine(e=>t.safeParse(e).success):e.refine(e=>t.safeParse(e).success)}if(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodNonOptional)return t.clone({...t.def,innerType:j(t.unwrap())});if(t instanceof u.ZodArray)return t.clone({...t.def,element:j(t.element)});if(t instanceof u.ZodObject){let e=Object.fromEntries(Object.entries(t.shape).map(([e,t])=>[e,j(t)]));return t.clone(Object.assign({},t.def,{shape:e}))}return t instanceof u.ZodUnion?t.clone({...t.def,options:t.options.map(j)}):t instanceof u.ZodRecord?t.clone({...t.def,keyType:j(t.keyType),valueType:j(t.valueType)}):t instanceof u.ZodTuple?t.clone({...t.def,items:t.def.items.map(j),rest:t.def.rest?j(t.def.rest):null}):t instanceof u.ZodIntersection?t.clone({...t.def,left:j(t.def.left),right:j(t.def.right)}):t}function M(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function N(e,t){return u.strictObject({...e,_id:s(t),_creationTime:u.number()})}function P(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}function F(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function I(t,n=/* @__PURE__ */ new Set,r=!1){if(n.has(t))return;n.add(t);let i=t._zod.def,a=()=>{throw Error(`DTO extensions require supported value-preserving validation schemas`)};`coerce`in i&&i.coerce&&a(),`normalize`in i&&i.normalize&&a();let o=e=>I(e,n,r);for(let e of i.checks??[])if(e._zod.def.check===`overwrite`&&a(),`normalize`in e._zod.def&&e._zod.def.normalize&&a(),e._zod.def.check===`property`&&o(e._zod.def.schema),e._zod.def.check===`properties`)for(let t of Object.values(e._zod.def.shape))o(t);switch(i.type){case`custom`:if(r&&e(t).kind===`id`)return;a();return;case`string`:case`number`:case`boolean`:case`bigint`:case`date`:case`symbol`:case`null`:case`undefined`:case`void`:case`never`:case`literal`:case`enum`:return;case`object`:if(r&&i.catchall&&i.catchall._zod.def.type!==`never`)throw Error(`Variant fields cannot use object catchalls; use a record field instead`);for(let e of Object.values(i.shape))o(e);i.catchall&&o(i.catchall);return;case`array`:o(i.element);return;case`optional`:case`nullable`:case`nonoptional`:o(i.innerType);return;case`union`:for(let e of i.options)o(e);return;case`intersection`:o(i.left),o(i.right);return;case`tuple`:for(let e of i.items)o(e);i.rest&&o(i.rest);return;case`record`:o(i.keyType),o(i.valueType);return;default:a()}}function L(e,t){for(let n of t)if(Object.hasOwn(e,n))throw Error(`Reserved table field "${n}" cannot be declared`)}function R(e,t,n,r,i=!0){for(let i of[...t,...n,...r])if(!Object.hasOwn(e,i))throw Error(`Unknown table field "${i}"`);let a=/* @__PURE__ */ new Set([...i?f:[],...t]);for(let e of n)if(a.has(e))throw Error(`Server-owned field "${e}" cannot be a command input`)}export{f as TIMESTAMP_FIELDS,i as convexToZod,_ as createModule,m as createTable,O as jsonSafeZid,S as memberName,b as namespace,T as namespaceIndex,C as namespaceName,E as paginated,w as tablesOf,g as tenantTable,o as zid,p as zodTable,e as zodToConvex,D as zodVariantTable};
|
|
1
|
+
import{zodToConvex as e}from"./zod-convex.mjs";import{memoize as t}from"./modules/contracts/lazy.mjs";import{pageResult as n}from"./querying/shared/page.mjs";import{scalarPaginationSchema as r}from"./querying/filters.mjs";import{convexToZod as i,convexToZod as a,zid as o,zid as s}from"convex-helpers/server/zod4";import{defineTable as c,paginationOptsValidator as l}from"convex/server";import{z as u}from"zod";const d={createdAt:u.number().optional(),updatedAt:u.number().optional(),archivedAt:u.number().optional()},f=[`createdAt`,`updatedAt`,`archivedAt`];function p(n,i,a={}){let o=i(s);B(o,[`_id`,`_creationTime`,...f]);let l={...o,...d};V(l,a.serverFields??[],a.commandFields??[],a.publicFields??[]);let p=u.strictObject({...l}),m=t(()=>I(l,n)),h=[...f,...a.serverFields??[]],g=[...a.commandFields??[]],_=[...a.publicFields??[]],v=t(()=>R(l,h)),y=t(()=>L(l,g)),b=t(()=>u.strictObject({...v()})),x=t(()=>u.strictObject({...v()}).partial()),S=t(()=>u.strictObject({...y()})),C=t(()=>u.strictObject(L(l,_))),w={get schema(){return m()},get insertSchema(){return b()},get updateSchema(){return x()},get commandInput(){return S()},get publicDto(){return C()}},T=t(()=>u.strictObject({})),E=t(()=>/* @__PURE__ */ new Set([`_id`,`_creationTime`,`tenant`,`__proto__`,...f]));function D(e){return O(e)}function O(e){let t=e===!0||e===!1?{_id:e}:e,n=t?.extend??{};if(k(n),!t?._id&&Object.keys(n).length===0)return w.publicDto;let r=u.strictObject({...w.publicDto.shape,...n});return t?._id?r.extend({_id:w.schema.shape._id}):r}function k(e){for(let t of Object.keys(e)){if(E().has(t)||Object.hasOwn(w.publicDto.shape,t))throw Error(`DTO extension collision for field "${t}" on table "${n}"`);z(e[t])}}function A(e,t){let n=t===!0||t===!1?{_id:t}:t;k(n?.extend??{});let r=w.publicDto.parse(Object.fromEntries(Object.keys(w.publicDto.shape).map(t=>[t,e[t]]))),i=n?.extend,a=(i==null?T():u.strictObject(i)).parse(n?.values??{}),o={...r,...a};return n?._id&&(o._id=w.schema.shape._id.parse(`_id`in e?e._id:void 0)),o}function M(e){return e?w.insertSchema.omit(e):w.insertSchema}function N(e){return e?w.updateSchema.omit(e):w.updateSchema}let P=e(p),H=c(P),U=()=>Object.fromEntries(Object.entries(w.schema.shape).map(([t,n])=>[t,e(n)]));function W(e,t){return r(U(),e,t)}let G=t(()=>({insert:w.commandInput,update:u.strictObject({data:u.strictObject({...y()}).partial(),id:j(n)}),id:u.strictObject({id:j(n)})}));return{tableName:n,get schema(){return w.schema},set schema(e){F(this,`schema`,e)},storage:p,get insertSchema(){return w.insertSchema},set insertSchema(e){F(this,`insertSchema`,e)},get updateSchema(){return w.updateSchema},set updateSchema(e){F(this,`updateSchema`,e)},get commandInput(){return w.commandInput},set commandInput(e){F(this,`commandInput`,e)},get publicDto(){return w.publicDto},set publicDto(e){F(this,`publicDto`,e)},dto:D,toPublicDto:A,paginationOpts:W,table:H,insert:M,update:N,get tools(){return G()},set tools(e){F(this,`tools`,e)}}}function m(e){return B(e,[`_id`,`_creationTime`,...f]),function(t,n,r={}){return p(t,r=>{let i=n(r);for(let n of Object.keys(i))if(Object.hasOwn(e,n))throw Error(`Duplicate shared table field "${n}" on table "${t}"`);return B(i,[`_id`,`_creationTime`,...f]),{...e,...i}},r)}}const h={tenant:u.string().min(1)};function g(e,t,n={}){return p(e,e=>{let n=t(e);return B(n,[`tenant`,`_id`,`_creationTime`,...f]),{...n,...h}},{...n,serverFields:[...n.serverFields??[],`tenant`]})}function _(...e){let t={},n=/* @__PURE__ */ new Set;for(let r of e){let e=S(r);if(e){if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.add(e.name)}for(let[e,n]of Object.entries(r)){if(e in t)throw Error(`Table "${e}" is declared by more than one module`);t[e]=n}}return t}const v=Symbol.for(`cvx-kit/zod-table/namespace`),y=/^[A-Z][A-Za-z0-9]*$/,b=/^[A-Za-z][A-Za-z0-9_]*$/;function x(e,t,n={}){if(!e.split(`.`).every(e=>y.test(e)))throw Error(`Namespace "${e}" must be dot-separated PascalCase segments (e.g. "Microsoft.Inventory")`);let r={};for(let[i,a]of Object.entries(t)){if(!b.test(i))throw Error(`Namespace "${e}" member "${i}" must be a table name (letters, digits and underscores)`);if(n.prefixed&&!w(i,e))throw Error(`Namespace "${e}" member "${i}" must start with "${C(e)}"`);if(`tableName`in a){if(a.tableName!==i)throw Error(`Namespace "${e}" member "${i}" holds table "${a.tableName}"; keys must be the table name`);r[i]=a.table}else r[i]=a}return Object.defineProperty(r,v,{value:Object.freeze({name:e,tables:Object.freeze(Object.keys(r))}),enumerable:!1}),r}function S(e){return e[v]}function C(e){return`${e.replaceAll(`.`,`_`)}_`}function w(e,t){let n=C(t);return e.startsWith(n)&&e.length>n.length}function T(e,t){return t!==void 0&&w(e,t)?e.slice(C(t).length):e.charAt(0).toUpperCase()+e.slice(1)}function E(e){return S(e).name}function D(e){return S(e).tables}function O(...e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;for(let r of e){let e=S(r);if(!e)throw Error(`namespaceIndex accepts only namespace(...) maps`);if(n.has(e.name))throw Error(`Namespace "${e.name}" is declared more than once`);n.set(e.name,e.tables);for(let n of e.tables){let r=t.get(n);if(r)throw Error(`Table "${n}" is declared by namespaces "${r}" and "${e.name}"`);t.set(n,e.name)}}let r=e=>{let n=t.get(e);if(n===void 0)throw Error(`Table "${e}" is not in a namespace`);return n};return{qualifiedName(e){let t=r(e);return`${t}.${T(e,t)}`},namespaceOf(e){return r(e)},memberName:T,tablesOf(e){let t=n.get(e);if(!t)throw Error(`Namespace "${e}" is not indexed`);return t},namespaces:[...n.keys()],has(e){return t.has(e)}}}function k(e){return{args:{paginationOpts:a(l)},result:n(e)}}function A(t,n,r){return r?M(t,n,r):{tableName:t,storage:n,insertSchema:n,table:c(e(n))}}function j(e){let t=s(e);return u.string().refine(e=>t.safeParse(e).success).describe(`Convex document id for table "${e}"; validated against the table by Convex`)}function M(n,r,i){if(!(r instanceof u.ZodDiscriminatedUnion)||r.def.discriminator!==i.discriminator)throw Error(`Variant boundaries require a discriminated union with the configured discriminator`);if(r.def.checks?.length)throw Error(`Variant boundaries do not support union-level refinements`);let a=i.timestamps,o=i.discriminator;if([`_id`,`_creationTime`,...f].includes(o))throw Error(`Variant discriminator cannot be a reserved field`);let l=/* @__PURE__ */ new Map;for(let e of r.options){if(!(e instanceof u.ZodObject)||!(e.def.catchall instanceof u.ZodNever))throw Error(`Variant boundaries require strict object branches`);if(e.def.checks?.length)throw Error(`Variant boundaries do not support object-level refinements`);try{z(e,/* @__PURE__ */ new Set,!0)}catch(e){throw Error(`Variant boundaries require supported value-preserving field validators without object catchalls`,{cause:e})}let r=e.shape[o];if(!(r instanceof u.ZodLiteral)||r.values.size!==1)throw Error(`Variant branches require one string literal discriminator`);let s=[...r.values][0];if(!u.string().safeParse(s).success)throw Error(`Variant branches require a string discriminator`);let c=s;if(l.has(c))throw Error(`Duplicate variant discriminator "${c}"`);if(!Object.hasOwn(i.variants,c))throw Error(`Missing variant configuration "${c}"`);let p={serverFields:[...i.variants[c].serverFields??[]],commandFields:[...i.variants[c].commandFields??[]],publicFields:[...i.variants[c].publicFields??[]]};B(e.shape,[`_id`,`_creationTime`,...a===!1?[]:f]);let m={...e.shape};a&&Object.assign(m,d),V(m,p.serverFields??[],p.commandFields??[],p.publicFields??[],a!==!1);for(let e of[p.serverFields,p.commandFields,p.publicFields])if(e?.includes(o))throw Error(`The variant discriminator is retained automatically and cannot appear in masks`);for(let e of p.commandFields)N(m[e]);let h=u.strictObject({...m}),g=t(()=>u.strictObject(R(m,[...a===!1?[]:f,...p.serverFields??[]]))),_=t(()=>u.strictObject(L(m,[o,...p.commandFields??[]]))),v=e=>e.partial().extend({[o]:r}),y=t(()=>I(m,n)),b=t(()=>v(u.strictObject(R(m,[...a===!1?[]:f,...p.serverFields])))),x=t(()=>v(u.strictObject(L(m,[o,...p.commandFields])))),S=t(()=>u.strictObject(L(m,[o,...p.commandFields]))),C=t(()=>u.strictObject(L(m,[o,...p.publicFields??[]])));l.set(c,{storage:h,get document(){return y()},get insert(){return g()},get update(){return b()},get command(){return _()},get commandUpdate(){return x()},get toolCommand(){return S()},get public(){return C()}})}for(let e of Object.keys(i.variants))if(!l.has(e))throw Error(`Unknown variant configuration "${e}"`);function p(e,t=!1,r=!1){let i=[...l.values()].map(i=>{let a=r&&e===`command`?i.toolCommand:i[e];return r?u.strictObject(Object.fromEntries(Object.entries(a.shape).map(([e,t])=>[e,P(t)]))):t?a.extend({_id:s(n)}):a});if(!i.length)throw Error(`Variant boundaries require at least one branch`);return u.discriminatedUnion(o,i)}let m=p(`storage`),h=t(()=>p(`document`)),g=t(()=>p(`insert`)),_=t(()=>p(`update`)),v=t(()=>p(`command`)),y=t(()=>p(`public`));function b(e=!1){return e?p(`public`,!0):y()}let x;function S(e,t=!1){let r=u.string().parse(e[o]),i=l.get(r);if(!i)throw Error(`Unknown variant discriminator "${r}"`);let a=t?i.public.extend({_id:x??=s(n)}):i.public;return a.parse(Object.fromEntries(Object.keys(a.shape).filter(t=>Object.hasOwn(e,t)).map(t=>[t,e[t]])))}let C=t(()=>({id:u.strictObject({id:j(n)}),insert:p(`command`,!1,!0),update:u.strictObject({id:j(n),data:p(`commandUpdate`,!1,!0)})}));return{tableName:n,storage:m,get schema(){return h()},set schema(e){F(this,`schema`,e)},get insertSchema(){return g()},set insertSchema(e){F(this,`insertSchema`,e)},get updateSchema(){return _()},set updateSchema(e){F(this,`updateSchema`,e)},get commandInput(){return v()},set commandInput(e){F(this,`commandInput`,e)},get publicDto(){return y()},set publicDto(e){F(this,`publicDto`,e)},dto:b,toPublicDto:S,table:c(e(m)),get tools(){return C()},set tools(e){F(this,`tools`,e)}}}function N(e){if(!(e instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(e instanceof u.ZodBigInt||e instanceof u.ZodLiteral&&[...e.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);e instanceof u.ZodOptional||e instanceof u.ZodNullable||e instanceof u.ZodNonOptional?N(e.unwrap()):e instanceof u.ZodArray?N(e.element):e instanceof u.ZodObject?Object.values(e.shape).forEach(N):e instanceof u.ZodUnion?e.options.forEach(N):e instanceof u.ZodRecord?(N(e.keyType),N(e.valueType)):e instanceof u.ZodTuple?(e.def.items.forEach(N),e.def.rest&&N(e.def.rest)):e instanceof u.ZodIntersection&&(N(e.def.left),N(e.def.right))}function P(t){if(!(t instanceof u.ZodType))throw Error(`Variant tools require classic Zod field schemas`);if(t instanceof u.ZodBigInt||t instanceof u.ZodLiteral&&[...t.values].some(e=>u.bigint().safeParse(e).success))throw Error(`Variant tool command fields cannot contain bigint; JSON Schema cannot represent it`);let n=e(t);if(n.kind===`id`){let e=j(n.tableName);return n.isOptional===`optional`?e.optional().refine(e=>t.safeParse(e).success):e.refine(e=>t.safeParse(e).success)}if(t instanceof u.ZodOptional||t instanceof u.ZodNullable||t instanceof u.ZodNonOptional)return t.clone({...t.def,innerType:P(t.unwrap())});if(t instanceof u.ZodArray)return t.clone({...t.def,element:P(t.element)});if(t instanceof u.ZodObject){let e=Object.fromEntries(Object.entries(t.shape).map(([e,t])=>[e,P(t)]));return t.clone(Object.assign({},t.def,{shape:e}))}return t instanceof u.ZodUnion?t.clone({...t.def,options:t.options.map(P)}):t instanceof u.ZodRecord?t.clone({...t.def,keyType:P(t.keyType),valueType:P(t.valueType)}):t instanceof u.ZodTuple?t.clone({...t.def,items:t.def.items.map(P),rest:t.def.rest?P(t.def.rest):null}):t instanceof u.ZodIntersection?t.clone({...t.def,left:P(t.def.left),right:P(t.def.right)}):t}function F(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function I(e,t){return u.strictObject({...e,_id:s(t),_creationTime:u.number()})}function L(e,t){return Object.fromEntries(t.map(t=>[t,e[t]]))}function R(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function z(t,n=/* @__PURE__ */ new Set,r=!1){if(n.has(t))return;n.add(t);let i=t._zod.def,a=()=>{throw Error(`DTO extensions require supported value-preserving validation schemas`)};`coerce`in i&&i.coerce&&a(),`normalize`in i&&i.normalize&&a();let o=e=>z(e,n,r);for(let e of i.checks??[])if(e._zod.def.check===`overwrite`&&a(),`normalize`in e._zod.def&&e._zod.def.normalize&&a(),e._zod.def.check===`property`&&o(e._zod.def.schema),e._zod.def.check===`properties`)for(let t of Object.values(e._zod.def.shape))o(t);switch(i.type){case`custom`:if(r&&e(t).kind===`id`)return;a();return;case`string`:case`number`:case`boolean`:case`bigint`:case`date`:case`symbol`:case`null`:case`undefined`:case`void`:case`never`:case`literal`:case`enum`:return;case`object`:if(r&&i.catchall&&i.catchall._zod.def.type!==`never`)throw Error(`Variant fields cannot use object catchalls; use a record field instead`);for(let e of Object.values(i.shape))o(e);i.catchall&&o(i.catchall);return;case`array`:o(i.element);return;case`optional`:case`nullable`:case`nonoptional`:o(i.innerType);return;case`union`:for(let e of i.options)o(e);return;case`intersection`:o(i.left),o(i.right);return;case`tuple`:for(let e of i.items)o(e);i.rest&&o(i.rest);return;case`record`:o(i.keyType),o(i.valueType);return;default:a()}}function B(e,t){for(let n of t)if(Object.hasOwn(e,n))throw Error(`Reserved table field "${n}" cannot be declared`)}function V(e,t,n,r,i=!0){for(let i of[...t,...n,...r])if(!Object.hasOwn(e,i))throw Error(`Unknown table field "${i}"`);let a=/* @__PURE__ */ new Set([...i?f:[],...t]);for(let e of n)if(a.has(e))throw Error(`Server-owned field "${e}" cannot be a command input`)}export{f as TIMESTAMP_FIELDS,i as convexToZod,_ as createModule,m as createTable,j as jsonSafeZid,T as memberName,x as namespace,O as namespaceIndex,E as namespaceName,C as namespacePrefix,k as paginated,D as tablesOf,g as tenantTable,o as zid,p as zodTable,e as zodToConvex,A as zodVariantTable};
|
|
2
2
|
//# sourceMappingURL=zod-table.mjs.map
|
package/dist/zod-table.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod-table.mjs","names":["zid","convexToZod","convexToZod$1","zid$1","timestampFields","z","TIMESTAMP_FIELDS","zodTable","declared","fields","assertOwnedFields","columns","assertFieldLists","options","storage","getSchema","memoize","documentSchema","tableName","omittedKeys","commandKeys","publicKeys","getWriteFields","omitFields","getCommandFields","pickFields","getInsertSchema","getUpdateSchema","getCommandInput","getPublicDto","derived","getEmptyDtoExtension","getReservedDtoFields","dto","deriveDto","normalized","extension","assertDtoExtension","resultSchema","key","assertDtoValidationSchema","toPublicDto","projected","row","extensionFields","result","insert","omit","update","nativeStorage","zodToConvex","table","defineTable","getPaginationFields","field","paginationOpts","scalarPaginationSchema","selection","getTools","jsonSafeZid","replaceBoundaryValue","value","createTable","shared","id","tenantFields","tenantTable","createModule","maps","combined","namespaceNames","map","meta","namespaceMeta","definition","namespaceKey","NAMESPACE_SEGMENT","namespace","name","segment","tables","member","members","memberName","namespaceName","ns","tablesOf","namespaceIndex","spaces","byTable","byName","space","owner","paginated","paginationOptsValidator","pageResult","zodVariantTable","deriveVariantTable","timestamps","discriminator","branches","branch","cause","tagSchema","tag","tagValue","config","mask","assertVariantToolField","stored","getInsert","getCommand","partial","schema","getDocument","getUpdate","getCommandUpdate","getToolCommand","getPublic","union","schemas","tool","mode","variantToolField","includeId","projectionId","projection","native","child","\"shape\"","boundary","keys","omitted","seen","def","reject","visit","allowNativeIds","check","reserved","server","command","managed","managedTimestamps","convexToZod","zid"],"sources":["../src/zod-table.ts"],"sourcesContent":["import { pageResult } from './querying/shared/page'\nimport { memoize } from './modules/contracts/lazy'\nimport type { PaginationValidatorOptions } from './querying/shared/filters'\nimport { convexToZod, zid, type ConvexValidatorFromZod, type Zid } from 'convex-helpers/server/zod4'\nimport {\n\tdefineTable,\n\tpaginationOptsValidator,\n\ttype TableDefinition,\n\ttype PaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\n\nimport { zodToConvex } from './zod-convex'\n\nimport {\n\tscalarPaginationSchema,\n\ttype ScalarPaginationSchema,\n\ttype ScalarSelection,\n\ttype ExactScalarSelection,\n} from './querying/filters'\n\n// Use this entry point when deriving validators from kit-owned schemas so\n// the producer and converter consult the same convex-helpers ID registry.\nexport { zid, convexToZod } from 'convex-helpers/server/zod4'\nexport { zodToConvex } from './zod-convex'\n\ntype FieldSchemas = Record<string, z.ZodType>\ntype FieldKey<Fields extends FieldSchemas> = Extract<keyof Fields, string>\n\n/**\n * Opinionated lifecycle timestamps — every table has them, server-owned,\n * always excluded from insert/command boundaries. Maintained by the\n * `timestamps` trigger helper (see cvx-kit/triggers).\n */\nconst timestampFields = {\n\tcreatedAt: z.number().optional(),\n\tupdatedAt: z.number().optional(),\n\tarchivedAt: z.number().optional(),\n} satisfies FieldSchemas\n\ntype TimestampFields = typeof timestampFields\ntype ReservedStorageField = '_id' | '_creationTime' | keyof TimestampFields\ntype OwnedFields<Fields> = {\n\t[Key in keyof Fields]: Key extends ReservedStorageField ? never : Fields[Key]\n}\ntype SystemFields<Table extends string> = { _id: Zid<Table>; _creationTime: z.ZodNumber }\n\nexport const TIMESTAMP_FIELDS = ['createdAt', 'updatedAt', 'archivedAt'] as const\n\nexport type TableBoundaryOptions<\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n\tCommandFields extends readonly FieldKey<Fields>[],\n\tPublicFields extends readonly FieldKey<Fields & TimestampFields>[],\n> = {\n\tserverFields?: ServerFields\n\tcommandFields?: CommandFields &\n\t\treadonly Exclude<FieldKey<Fields>, ServerFields[number] | keyof TimestampFields>[]\n\tpublicFields?: PublicFields\n}\n\ntype StrictObject<Fields extends FieldSchemas> = z.ZodObject<Fields, z.core.$strict>\ntype WriteFields<\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n> = Omit<Fields & TimestampFields, ServerFields[number] | (typeof TIMESTAMP_FIELDS)[number]>\ntype PartialFields<Fields extends FieldSchemas> = {\n\t[Key in keyof Fields]: z.ZodOptional<Fields[Key]>\n}\n\n/** Options shared by the DTO return schema and row projector.\n * Promised contributions must be present, including in reusable options.\n * New extension schemas support validation only: no transforms, pipes,\n * coercion, preprocess, defaults, catches, or overwrites, even when nested.\n * Refinements must validate without mutating their input.\n */\nexport type DtoOptions<IncludeId extends boolean = false, Extension extends FieldSchemas = {}> = ([\n\tIncludeId,\n] extends [true]\n\t? { _id: IncludeId }\n\t: { _id?: IncludeId }) &\n\t(keyof Extension extends never ? { extend?: Extension } : { extend: Extension })\n\ntype DtoProjectionOptions<IncludeId extends boolean> = DtoOptions<IncludeId> & {\n\textend?: Record<string, never>\n\tvalues?: never\n}\n\ntype ReservedDtoField =\n\t| '_id'\n\t| '_creationTime'\n\t| 'tenant'\n\t| '__proto__'\n\t| (typeof TIMESTAMP_FIELDS)[number]\ntype DtoExtension<Public extends FieldSchemas, Extension extends FieldSchemas> = {\n\t[Key in keyof Extension]: Key extends keyof Public | ReservedDtoField\n\t\t? never\n\t\t: Extension[Key] extends z.ZodPipe | z.ZodTransform\n\t\t\t? never\n\t\t\t: unknown\n}\n// Broad dictionaries cannot promise any particular extension field.\ntype KnownExtension<Extension> = string extends keyof Extension ? {} : Extension\n\ntype DtoSchema<\n\tTable extends string,\n\tPublic extends FieldSchemas,\n\tIncludeId extends boolean,\n\tExtension extends FieldSchemas = {},\n> = IncludeId extends true\n\t? StrictObject<Public & { _id: Zid<Table> } & KnownExtension<Extension>>\n\t: StrictObject<Public & KnownExtension<Extension>>\ntype DtoRow<Row, IncludeId extends boolean> = Row & (true extends IncludeId ? { _id: string } : {})\ntype DtoValues<Extension extends FieldSchemas> = keyof Extension extends never\n\t? { values?: never }\n\t: { values: z.input<StrictObject<NoInfer<Extension>>> }\n\ntype DtoBoundary<Table extends string, Fields extends FieldSchemas, Public extends FieldSchemas> = {\n\tdto(): StrictObject<Public>\n\tdto<const IncludeId extends boolean>(includeId: IncludeId): DtoSchema<Table, Public, IncludeId>\n\tdto<const IncludeId extends boolean = false>(\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): DtoSchema<Table, Public, IncludeId>\n\tdto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\toptions: DtoOptions<IncludeId, Extension> & { extend?: DtoExtension<Public, Extension> },\n\t): DtoSchema<Table, Public, IncludeId, Extension>\n\ttoPublicDto(row: z.input<StrictObject<Fields>>): z.output<StrictObject<Public>>\n\ttoPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\ttoPublicDto<const IncludeId extends boolean = false>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\ttoPublicDto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\toptions: DtoOptions<IncludeId, Extension> & {\n\t\t\textend?: DtoExtension<Public, Extension>\n\t\t} & DtoValues<Extension>,\n\t): z.output<DtoSchema<Table, Public, IncludeId, Extension>>\n}\n\n/** Named schema relationships keep generated declarations bounded and consumers fully typed. */\nexport type TableBoundary<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n\tCommandFields extends readonly FieldKey<Fields>[],\n\tPublicFields extends readonly FieldKey<Fields & TimestampFields>[],\n> = DtoBoundary<\n\tTable,\n\tFields & TimestampFields,\n\tPick<Fields & TimestampFields, PublicFields[number]>\n> & {\n\tpaginationOpts<\n\t\tconst Selection extends ScalarSelection<Fields & TimestampFields & SystemFields<Table>>,\n\t>(\n\t\tselection: ExactScalarSelection<Fields & TimestampFields & SystemFields<Table>, Selection>,\n\t\toptions?: PaginationValidatorOptions,\n\t): ScalarPaginationSchema<Fields & TimestampFields & SystemFields<Table>, Selection>\n\ttableName: Table\n\tstorage: StrictObject<Fields & TimestampFields>\n\tschema: ReturnType<typeof documentSchema<Fields & TimestampFields, Table>>\n\tinsertSchema: StrictObject<WriteFields<Fields, ServerFields>>\n\tupdateSchema: StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>\n\tcommandInput: StrictObject<Pick<Fields & TimestampFields, CommandFields[number]>>\n\tpublicDto: StrictObject<Pick<Fields & TimestampFields, PublicFields[number]>>\n\ttable: TableDefinition<ConvexValidatorFromZod<StrictObject<Fields & TimestampFields>, 'required'>>\n\tinsert(): StrictObject<WriteFields<Fields, ServerFields>>\n\tinsert<Mask extends z.util.Mask<keyof WriteFields<Fields, ServerFields>>>(\n\t\tomit: Mask,\n\t): ZodObjectOmit<StrictObject<WriteFields<Fields, ServerFields>>, Mask>\n\tupdate(): StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>\n\tupdate<Mask extends z.util.Mask<keyof WriteFields<Fields, ServerFields>>>(\n\t\tomit: Mask,\n\t): ZodObjectOmit<StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>, Mask>\n\ttools: {\n\t\tinsert: StrictObject<Pick<Fields & TimestampFields, CommandFields[number]>>\n\t\tupdate: StrictObject<{\n\t\t\tdata: StrictObject<PartialFields<Pick<Fields & TimestampFields, CommandFields[number]>>>\n\t\t\tid: z.ZodType<GenericId<Table>, string>\n\t\t}>\n\t\tid: StrictObject<{ id: z.ZodType<GenericId<Table>, string> }>\n\t}\n}\n\n/** Defines one table and derives its storage, document, write, and DTO boundaries. */\nexport function zodTable<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tconst ServerFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst CommandFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst PublicFields extends readonly FieldKey<Fields & TimestampFields>[] = readonly [],\n>(\n\ttableName: Table,\n\tfields: (id: typeof zid) => Fields & OwnedFields<Fields>,\n\toptions: TableBoundaryOptions<Fields, ServerFields, CommandFields, PublicFields> = {},\n): TableBoundary<Table, Fields, ServerFields, CommandFields, PublicFields> {\n\tconst declared = fields(zid)\n\tassertOwnedFields(declared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\tconst columns: Fields & TimestampFields = { ...declared, ...timestampFields }\n\tassertFieldLists(\n\t\tcolumns,\n\t\toptions.serverFields ?? [],\n\t\toptions.commandFields ?? [],\n\t\toptions.publicFields ?? [],\n\t)\n\tconst storage: z.ZodObject<Fields & TimestampFields, z.core.$strict> = z.strictObject({\n\t\t...columns,\n\t})\n\tconst getSchema = memoize(() =>\n\t\tdocumentSchema<Fields & TimestampFields, Table>(columns, tableName),\n\t)\n\tconst omittedKeys: readonly (ServerFields[number] | (typeof TIMESTAMP_FIELDS)[number])[] = [\n\t\t...TIMESTAMP_FIELDS,\n\t\t...(options.serverFields ?? []),\n\t]\n\tconst commandKeys: readonly CommandFields[number][] = [...(options.commandFields ?? [])]\n\tconst publicKeys: readonly PublicFields[number][] = [...(options.publicFields ?? [])]\n\t// Reuse declaration-time selections, never a mutable public schema's shape.\n\tconst getWriteFields = memoize(() => omitFields(columns, omittedKeys))\n\tconst getCommandFields = memoize(() => pickFields(columns, commandKeys))\n\tconst getInsertSchema = memoize(\n\t\t(): z.ZodObject<WriteFields<Fields, ServerFields>, z.core.$strict> =>\n\t\t\tz.strictObject({ ...getWriteFields() }),\n\t)\n\tconst getUpdateSchema = memoize(() => z.strictObject({ ...getWriteFields() }).partial())\n\tconst getCommandInput = memoize(\n\t\t(): z.ZodObject<Pick<Fields & TimestampFields, CommandFields[number]>, z.core.$strict> =>\n\t\t\tz.strictObject({ ...getCommandFields() }),\n\t)\n\tconst getPublicDto = memoize(\n\t\t(): z.ZodObject<Pick<Fields & TimestampFields, PublicFields[number]>, z.core.$strict> =>\n\t\t\tz.strictObject(pickFields(columns, publicKeys)),\n\t)\n\tconst derived = {\n\t\tget schema() {\n\t\t\treturn getSchema()\n\t\t},\n\t\tget insertSchema() {\n\t\t\treturn getInsertSchema()\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn getUpdateSchema()\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn getCommandInput()\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn getPublicDto()\n\t\t},\n\t}\n\n\ttype Public = Pick<Fields & TimestampFields, PublicFields[number]>\n\ttype Row = z.input<typeof storage>\n\ttype RuntimeDtoFields = Public & FieldSchemas\n\ttype RuntimeDto = z.output<StrictObject<RuntimeDtoFields>> & { _id?: GenericId<Table> }\n\ttype RuntimeOptions = { _id?: boolean; extend?: FieldSchemas; values?: unknown }\n\t// Private to this boundary: callers cannot mutate a shared empty validator.\n\tconst getEmptyDtoExtension = memoize(() => z.strictObject({}))\n\tconst getReservedDtoFields = memoize(\n\t\t() => new Set<string>(['_id', '_creationTime', 'tenant', '__proto__', ...TIMESTAMP_FIELDS]),\n\t)\n\n\tfunction dto(): typeof derived.publicDto\n\tfunction dto<const IncludeId extends boolean>(\n\t\tincludeId: IncludeId,\n\t): DtoSchema<Table, Public, IncludeId>\n\tfunction dto<const IncludeId extends boolean = false>(\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): DtoSchema<Table, Public, IncludeId>\n\tfunction dto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\toptions: DtoOptions<IncludeId, Extension> & { extend?: DtoExtension<Public, Extension> },\n\t): DtoSchema<Table, Public, IncludeId, Extension>\n\tfunction dto(options?: boolean | RuntimeOptions) {\n\t\treturn deriveDto(options)\n\t}\n\n\tfunction deriveDto(options?: boolean | RuntimeOptions) {\n\t\tconst normalized = options === true || options === false ? { _id: options } : options\n\t\tconst extension = normalized?.extend ?? {}\n\t\tassertDtoExtension(extension)\n\t\tif (!normalized?._id && Object.keys(extension).length === 0) return derived.publicDto\n\t\tconst resultSchema = z.strictObject({ ...derived.publicDto.shape, ...extension })\n\t\treturn normalized?._id ? resultSchema.extend({ _id: derived.schema.shape._id }) : resultSchema\n\t}\n\n\tfunction assertDtoExtension(extension: FieldSchemas) {\n\t\tfor (const key of Object.keys(extension)) {\n\t\t\tif (getReservedDtoFields().has(key) || Object.hasOwn(derived.publicDto.shape, key)) {\n\t\t\t\tthrow new Error(`DTO extension collision for field \"${key}\" on table \"${tableName}\"`)\n\t\t\t}\n\t\t\tassertDtoValidationSchema(extension[key])\n\t\t}\n\t}\n\n\tfunction toPublicDto(row: Row): z.output<typeof derived.publicDto>\n\tfunction toPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\tfunction toPublicDto<const IncludeId extends boolean = false>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\tfunction toPublicDto<\n\t\tconst IncludeId extends boolean = false,\n\t\tconst Extension extends FieldSchemas = {},\n\t>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\toptions: DtoOptions<IncludeId, Extension> & {\n\t\t\textend?: DtoExtension<Public, Extension>\n\t\t} & DtoValues<Extension>,\n\t): z.output<DtoSchema<Table, Public, IncludeId, Extension>>\n\tfunction toPublicDto(row: Row, options?: boolean | RuntimeOptions): RuntimeDto {\n\t\tconst normalized = options === true || options === false ? { _id: options } : options\n\t\t// Enforce extension collisions and validation-only schemas before parsing values.\n\t\tassertDtoExtension(normalized?.extend ?? {})\n\t\tconst projected = derived.publicDto.parse(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.keys(derived.publicDto.shape).map((key) => {\n\t\t\t\t\t// SAFETY: derived.publicDto contains only keys selected from the storage fields.\n\t\t\t\t\treturn [key, row[key as keyof typeof row]]\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t\tconst extensionFields = normalized?.extend\n\t\tconst extensionSchema =\n\t\t\textensionFields == null ? getEmptyDtoExtension() : z.strictObject(extensionFields)\n\t\tconst extension = extensionSchema.parse(normalized?.values ?? {})\n\t\tconst result: RuntimeDto = { ...projected, ...extension }\n\t\tif (normalized?._id) {\n\t\t\tresult._id = derived.schema.shape._id.parse('_id' in row ? row._id : undefined)\n\t\t}\n\t\treturn result\n\t}\n\n\ttype InsertSchema = typeof derived.insertSchema\n\ttype UpdateSchema = typeof derived.updateSchema\n\ttype InsertMask = z.util.Mask<keyof InsertSchema['shape']>\n\ttype UpdateMask = z.util.Mask<keyof UpdateSchema['shape']>\n\n\tfunction insert(): InsertSchema\n\tfunction insert<OmitMask extends InsertMask>(\n\t\tomit: OmitMask,\n\t): ZodObjectOmit<InsertSchema, OmitMask>\n\tfunction insert(omit?: InsertMask) {\n\t\t// SAFETY: InsertMask contains only derived.insertSchema keys; the overload retains Zod's exact mask relationship.\n\t\treturn omit ? derived.insertSchema.omit(omit as never) : derived.insertSchema\n\t}\n\n\tfunction update(): UpdateSchema\n\tfunction update<OmitMask extends UpdateMask>(\n\t\tomit: OmitMask,\n\t): ZodObjectOmit<UpdateSchema, OmitMask>\n\tfunction update(omit?: UpdateMask) {\n\t\t// SAFETY: UpdateMask contains only derived.updateSchema keys; the overload retains Zod's exact mask relationship.\n\t\treturn omit ? derived.updateSchema.omit(omit as never) : derived.updateSchema\n\t}\n\n\tconst nativeStorage = zodToConvex(storage)\n\tconst table: TableDefinition<ConvexValidatorFromZod<typeof storage, 'required'>> =\n\t\tdefineTable(nativeStorage)\n\t// The public shape is mutable. Reconvert its fields on each call so subsequent\n\t// pagination validators observe replacements and nested schema changes.\n\tconst getPaginationFields = () =>\n\t\tObject.fromEntries(\n\t\t\tObject.entries(derived.schema.shape).map(([key, field]) => [key, zodToConvex(field)]),\n\t\t)\n\ttype EntityFields = Fields & TimestampFields & SystemFields<Table>\n\tfunction paginationOpts<const Selection extends ScalarSelection<EntityFields>>(\n\t\tselection: ExactScalarSelection<EntityFields, Selection>,\n\t\toptions?: PaginationValidatorOptions,\n\t): ScalarPaginationSchema<EntityFields, Selection> {\n\t\treturn scalarPaginationSchema<EntityFields, Selection>(\n\t\t\tgetPaginationFields(),\n\t\t\tselection,\n\t\t\toptions,\n\t\t)\n\t}\n\tconst getTools = memoize(() => ({\n\t\t// jsonSafeZid (not zid): tool masks feed generated JSON schemas, so\n\t\t// ids must present as plain strings while keeping the Id<...> type.\n\t\tinsert: derived.commandInput,\n\t\tupdate: z.strictObject({\n\t\t\tdata: z.strictObject({ ...getCommandFields() }).partial(),\n\t\t\tid: jsonSafeZid(tableName),\n\t\t}),\n\t\tid: z.strictObject({ id: jsonSafeZid(tableName) }),\n\t}))\n\n\treturn {\n\t\ttableName,\n\t\tget schema() {\n\t\t\treturn derived.schema\n\t\t},\n\t\tset schema(value: ReturnType<typeof getSchema>) {\n\t\t\treplaceBoundaryValue(this, 'schema', value)\n\t\t},\n\t\tstorage,\n\t\tget insertSchema() {\n\t\t\treturn derived.insertSchema\n\t\t},\n\t\tset insertSchema(value: ReturnType<typeof getInsertSchema>) {\n\t\t\treplaceBoundaryValue(this, 'insertSchema', value)\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn derived.updateSchema\n\t\t},\n\t\tset updateSchema(value: ReturnType<typeof getUpdateSchema>) {\n\t\t\treplaceBoundaryValue(this, 'updateSchema', value)\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn derived.commandInput\n\t\t},\n\t\tset commandInput(value: ReturnType<typeof getCommandInput>) {\n\t\t\treplaceBoundaryValue(this, 'commandInput', value)\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn derived.publicDto\n\t\t},\n\t\tset publicDto(value: ReturnType<typeof getPublicDto>) {\n\t\t\treplaceBoundaryValue(this, 'publicDto', value)\n\t\t},\n\t\tdto,\n\t\ttoPublicDto,\n\t\tpaginationOpts,\n\t\ttable,\n\t\tinsert,\n\t\tupdate,\n\t\tget tools() {\n\t\t\treturn getTools()\n\t\t},\n\t\tset tools(value: ReturnType<typeof getTools>) {\n\t\t\treplaceBoundaryValue(this, 'tools', value)\n\t\t},\n\t}\n}\n\n/** Reuses ordinary fields while deriving every boundary through zodTable. */\nexport function createTable<Shared extends FieldSchemas>(shared: Shared & OwnedFields<Shared>) {\n\tassertOwnedFields(shared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\treturn function customTable<\n\t\tTable extends string,\n\t\tFields extends FieldSchemas,\n\t\tconst ServerFields extends readonly FieldKey<Shared & Fields>[] = readonly [],\n\t\tconst CommandFields extends readonly FieldKey<Shared & Fields>[] = readonly [],\n\t\tconst PublicFields extends readonly FieldKey<Shared & Fields & TimestampFields>[] = readonly [],\n\t>(\n\t\ttableName: Table,\n\t\tfields: (id: typeof zid) => Fields &\n\t\t\tOwnedFields<Fields> & {\n\t\t\t\t[Key in keyof Fields]: Key extends (string extends keyof Shared ? never : keyof Shared)\n\t\t\t\t\t? never\n\t\t\t\t\t: Fields[Key]\n\t\t\t},\n\t\toptions: TableBoundaryOptions<Shared & Fields, ServerFields, CommandFields, PublicFields> = {},\n\t): TableBoundary<Table, Shared & Fields, ServerFields, CommandFields, PublicFields> {\n\t\treturn zodTable<Table, Shared & Fields, ServerFields, CommandFields, PublicFields>(\n\t\t\ttableName,\n\t\t\t(id) => {\n\t\t\t\tconst declared = fields(id)\n\t\t\t\tfor (const key of Object.keys(declared)) {\n\t\t\t\t\tif (Object.hasOwn(shared, key))\n\t\t\t\t\t\tthrow new Error(`Duplicate shared table field \"${key}\" on table \"${tableName}\"`)\n\t\t\t\t}\n\t\t\t\tassertOwnedFields(declared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\t\t\t\tconst combined: Shared & Fields = { ...shared, ...declared }\n\t\t\t\t// SAFETY: duplicates and reserved keys are rejected before merging; like\n\t\t\t\t// tenantTable, this wrapper forwards the unchanged validators to zodTable.\n\t\t\t\treturn combined as Shared & Fields & OwnedFields<Shared & Fields>\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t}\n}\n\nconst tenantFields = {\n\ttenant: z.string().min(1),\n} satisfies FieldSchemas\n\ntype TenantFields = typeof tenantFields\n\n/**\n * A zodTable whose rows are tenant-owned: injects the server-owned `tenant`\n * field (the tenancy boundary — see cvx-kit/tenancy). Like timestamps, it is\n * excluded from insert/update/command boundaries; handlers stamp it from\n * ctx.tenant, row-level security matches on it, and the tenantOwnership\n * trigger forbids reassigning it. Expose it via publicFields only when a DTO\n * genuinely needs it.\n */\nexport function tenantTable<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tconst ServerFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst CommandFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst PublicFields extends readonly FieldKey<Fields & TenantFields & TimestampFields>[] =\n\t\treadonly [],\n>(\n\ttableName: Table,\n\tfields: (\n\t\tid: typeof zid,\n\t) => Fields &\n\t\tOwnedFields<Fields> & { [Key in keyof Fields]: Key extends 'tenant' ? never : Fields[Key] },\n\toptions: TableBoundaryOptions<\n\t\tFields & TenantFields,\n\t\treadonly (ServerFields[number] | 'tenant')[],\n\t\tCommandFields,\n\t\tPublicFields\n\t> = {},\n) {\n\treturn zodTable<\n\t\tTable,\n\t\tFields & TenantFields,\n\t\treadonly (ServerFields[number] | 'tenant')[],\n\t\tCommandFields,\n\t\tPublicFields\n\t>(\n\t\ttableName,\n\t\t(id) => {\n\t\t\tconst declared = fields(id)\n\t\t\tassertOwnedFields(declared, ['tenant', '_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\t\t\t// SAFETY: reserved keys were rejected before injecting tenant; the generic\n\t\t\t// wrapper forwards the same checked fields to the ordinary table constructor.\n\t\t\treturn { ...declared, ...tenantFields } as Fields &\n\t\t\t\tTenantFields &\n\t\t\t\tOwnedFields<Fields & TenantFields>\n\t\t},\n\t\t{\n\t\t\t...options,\n\t\t\tserverFields: [...(options.serverFields ?? []), 'tenant'],\n\t\t},\n\t)\n}\n\n/**\n * Merges per-module table maps into the application schema map, rejecting\n * duplicate table names across modules — the module-registry combinator for\n * domain/table.ts: `defineSchema(createModule(catalogTables, salesTables))`.\n * Accepts plain maps and `namespace(...)` maps side by side; namespaces add\n * no keys, so the result is the same flat `{ tableName: TableDefinition }`.\n */\nexport function createModule<const Maps extends readonly Record<string, TableDefinition<any>>[]>(\n\t...maps: Maps\n): FlatTables<UnionToIntersection<Maps[number]>> {\n\tconst combined: Record<string, TableDefinition<any>> = {}\n\tconst namespaceNames = new Set<string>()\n\tfor (const map of maps) {\n\t\tconst meta = namespaceMeta(map)\n\t\tif (meta) {\n\t\t\tif (namespaceNames.has(meta.name)) {\n\t\t\t\tthrow new Error(`Namespace \"${meta.name}\" is declared more than once`)\n\t\t\t}\n\t\t\tnamespaceNames.add(meta.name)\n\t\t}\n\t\tfor (const [tableName, definition] of Object.entries(map)) {\n\t\t\tif (tableName in combined) {\n\t\t\t\tthrow new Error(`Table \"${tableName}\" is declared by more than one module`)\n\t\t\t}\n\t\t\tcombined[tableName] = definition\n\t\t}\n\t}\n\t// SAFETY: every string-keyed input entry is copied, and duplicate keys are rejected above.\n\treturn combined as FlatTables<UnionToIntersection<Maps[number]>>\n}\n\ntype FlatTables<Map> = { [Key in keyof Map as Key extends string ? Key : never]: Map[Key] }\n\nconst namespaceKey: unique symbol = Symbol.for('cvx-kit/zod-table/namespace')\n\n/** Declaration-level metadata carried by a `namespace(...)` table map. */\nexport type NamespaceInfo<Name extends string, Tables extends string> = {\n\treadonly name: Name\n\treadonly tables: readonly Tables[]\n}\n\n/**\n * A table map tagged with a namespace. It is still a plain\n * `{ tableName: TableDefinition }` map (the tag is a non-enumerable symbol),\n * so `createModule`/`defineSchema` see exactly the tables they saw before.\n */\nexport type Namespace<\n\tName extends string,\n\tTables extends Record<string, TableDefinition<any>>,\n> = Tables & NamespaceTag<Name, keyof Tables & string>\n\n/** The metadata-only shape of a `namespace(...)` map. */\nexport type NamespaceTag<Name extends string, Tables extends string> = {\n\treadonly [namespaceKey]: NamespaceInfo<Name, Tables>\n}\n\n/** PascalCase member name of a table: `itemLedgerEntries` → `ItemLedgerEntries`. */\nexport type MemberName<TableName extends string> = Capitalize<TableName>\n\n/** Fully qualified name: `<Namespace>.<Member>`, e.g. `Inventory.Items`. */\nexport type QualifiedName<\n\tName extends string,\n\tTableName extends string,\n> = `${Name}.${MemberName<TableName>}`\n\ntype NamespaceMember = TableDefinition<any> | { tableName: string; table: TableDefinition<any> }\ntype MemberTables<Members extends Record<string, NamespaceMember>> = {\n\t[Key in keyof Members]: Members[Key] extends { table: infer Table extends TableDefinition<any> }\n\t\t? Table\n\t\t: Extract<Members[Key], TableDefinition<any>>\n}\ntype CheckedMembers<Members extends Record<string, NamespaceMember>> = {\n\t[Key in keyof Members]: Members[Key] extends { tableName: infer TableName }\n\t\t? TableName extends Key\n\t\t\t? Members[Key]\n\t\t\t: { tableName: Key; table: TableDefinition<any> }\n\t\t: Members[Key]\n}\ntype CheckedNamespaceName<Name extends string> = Name extends ''\n\t? never\n\t: Name extends `${string}..${string}` | `.${string}` | `${string}.`\n\t\t? never\n\t\t: Name\n\nconst NAMESPACE_SEGMENT = /^[A-Z][A-Za-z0-9]*$/\n\n/**\n * Groups tables under a declaration-level namespace, like AL's\n * `namespace Microsoft.Inventory.Item;`. Keys are the real (stored) table\n * names, exactly as in an un-namespaced module map; each table's member name\n * is the PascalCase form of its key (`items` → `Items`) and its qualified\n * name is `<Namespace>.<Member>` (`Inventory.Items`). Storage, `id('items')`,\n * `ctx.db.query('items')` and generated types are unchanged.\n *\n * A member may be a `TableDefinition` (`items.table.index(...)`) or a table\n * boundary (`items`); a boundary whose `tableName` differs from its key is a\n * type error and a runtime error. Dotted names (`Microsoft.Inventory`) are\n * allowed; each segment must be PascalCase.\n */\nexport function namespace<\n\tconst Name extends string,\n\tconst Members extends Record<string, NamespaceMember>,\n>(\n\tname: Name & CheckedNamespaceName<Name>,\n\tmembers: Members & CheckedMembers<Members>,\n): Namespace<Name, MemberTables<Members>> {\n\tif (!name.split('.').every((segment) => NAMESPACE_SEGMENT.test(segment))) {\n\t\tthrow new Error(\n\t\t\t`Namespace \"${name}\" must be dot-separated PascalCase segments (e.g. \"Microsoft.Inventory\")`,\n\t\t)\n\t}\n\tconst tables: Record<string, TableDefinition<any>> = {}\n\tfor (const [key, member] of Object.entries(members as Record<string, NamespaceMember>)) {\n\t\tif (!/^[a-z][A-Za-z0-9]*$/.test(key)) {\n\t\t\tthrow new Error(`Namespace \"${name}\" member \"${key}\" must be a camelCase table name`)\n\t\t}\n\t\tif ('tableName' in member) {\n\t\t\tif (member.tableName !== key) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Namespace \"${name}\" member \"${key}\" holds table \"${member.tableName}\"; keys must be the table name`,\n\t\t\t\t)\n\t\t\t}\n\t\t\ttables[key] = member.table\n\t\t} else {\n\t\t\ttables[key] = member\n\t\t}\n\t}\n\tObject.defineProperty(tables, namespaceKey, {\n\t\tvalue: Object.freeze({ name, tables: Object.freeze(Object.keys(tables)) }),\n\t\tenumerable: false,\n\t})\n\t// SAFETY: tables holds one TableDefinition per member key plus the symbol tag.\n\treturn tables as Namespace<Name, MemberTables<Members>>\n}\n\nfunction namespaceMeta(map: object): NamespaceInfo<string, string> | undefined {\n\treturn (map as { [namespaceKey]?: NamespaceInfo<string, string> })[namespaceKey]\n}\n\n/** PascalCase member name of a table name. */\nexport function memberName<const TableName extends string>(tableName: TableName) {\n\treturn (tableName.charAt(0).toUpperCase() + tableName.slice(1)) as MemberName<TableName>\n}\n\n/** The namespace name of a `namespace(...)` map. */\nexport function namespaceName<const Name extends string>(ns: NamespaceTag<Name, string>): Name {\n\treturn namespaceMeta(ns)!.name as Name\n}\n\n/** The stored table names declared in a namespace, in declaration order. */\nexport function tablesOf<const Tables extends string>(\n\tns: NamespaceTag<string, Tables>,\n): readonly Tables[] {\n\treturn namespaceMeta(ns)!.tables as readonly Tables[]\n}\n\ntype NamespaceEntries<Spaces extends readonly NamespaceTag<string, string>[]> = {\n\t[Index in keyof Spaces]: Spaces[Index] extends NamespaceTag<infer Name, infer Tables>\n\t\t? { [TableName in Tables]: Name }\n\t\t: never\n}[number]\ntype TableNamespaceMap<Spaces extends readonly NamespaceTag<string, string>[]> =\n\tUnionToIntersection<NamespaceEntries<Spaces>>\n\n/**\n * Typed, read-only qualified-name lookup over namespaces (no global registry:\n * build one next to `createModule` and import it where labels are needed).\n * Rejects duplicate namespace names and tables claimed by two namespaces.\n */\nexport function namespaceIndex<const Spaces extends readonly NamespaceTag<string, string>[]>(\n\t...spaces: Spaces\n) {\n\ttype Map = TableNamespaceMap<Spaces>\n\ttype TableName = keyof Map & string\n\ttype NameOf = Spaces[number] extends NamespaceTag<infer Name, string> ? Name : never\n\tconst byTable = new Map<string, string>()\n\tconst byName = new Map<string, readonly string[]>()\n\tfor (const space of spaces) {\n\t\tconst meta = namespaceMeta(space)\n\t\tif (!meta) throw new Error('namespaceIndex accepts only namespace(...) maps')\n\t\tif (byName.has(meta.name)) {\n\t\t\tthrow new Error(`Namespace \"${meta.name}\" is declared more than once`)\n\t\t}\n\t\tbyName.set(meta.name, meta.tables)\n\t\tfor (const table of meta.tables) {\n\t\t\tconst owner = byTable.get(table)\n\t\t\tif (owner) {\n\t\t\t\tthrow new Error(`Table \"${table}\" is declared by namespaces \"${owner}\" and \"${meta.name}\"`)\n\t\t\t}\n\t\t\tbyTable.set(table, meta.name)\n\t\t}\n\t}\n\tconst owner = (table: string) => {\n\t\tconst name = byTable.get(table)\n\t\tif (name === undefined) throw new Error(`Table \"${table}\" is not in a namespace`)\n\t\treturn name\n\t}\n\treturn {\n\t\tqualifiedName<const Table extends TableName>(table: Table) {\n\t\t\treturn `${owner(table)}.${memberName(table)}` as {\n\t\t\t\t[Key in Table]: QualifiedName<Map[Key] & string, Key>\n\t\t\t}[Table]\n\t\t},\n\t\tnamespaceOf<const Table extends TableName>(table: Table) {\n\t\t\treturn owner(table) as Map[Table]\n\t\t},\n\t\tmemberName,\n\t\ttablesOf<const Name extends NameOf>(name: Name) {\n\t\t\tconst tables = byName.get(name)\n\t\t\tif (!tables) throw new Error(`Namespace \"${name}\" is not indexed`)\n\t\t\treturn tables as readonly {\n\t\t\t\t[Table in TableName]: Map[Table] extends Name ? Table : never\n\t\t\t}[TableName][]\n\t\t},\n\t\tnamespaces: [...byName.keys()] as readonly string[] as readonly NameOf[],\n\t\thas(table: string): table is TableName {\n\t\t\treturn byTable.has(table)\n\t\t},\n\t}\n}\n\ntype UnionToIntersection<Union> = (\n\tUnion extends unknown ? (member: Union) => void : never\n) extends (member: infer Intersection) => void\n\t? Intersection\n\t: never\n\n/**\n * Cursor-pagination boundary schemas bridged from Convex's own validators:\n * `args.paginationOpts` for function args, `result` for the page shape.\n * Pair with `include(...).paginate(opts)` (cvx-kit/auth). The result object\n * is deliberately non-strict — Convex may attach engine fields (splitCursor,\n * pageStatus); the page items themselves are validated against the dto.\n * Note: under row-level security, pages may be SHORTER than numItems when\n * rules reject rows mid-page; cursors remain correct.\n */\n/** Completeness of the requested page, independently of global isDone exhaustion. */\nexport type PageCompleteness =\n\t| 'complete'\n\t| 'row-budget'\n\t| 'byte-budget'\n\t| 'native-limit'\n\t| 'result-cap'\nexport type EnginePaginationResult<Row> = PaginationResult<Row> & {\n\tpaginationMode?: 'native-search'\n\tcompleteness?: PageCompleteness\n}\n\nexport function paginated<Dto extends z.ZodType>(dto: Dto) {\n\treturn {\n\t\targs: { paginationOpts: convexToZod(paginationOptsValidator) },\n\t\tresult: pageResult(dto),\n\t}\n}\n\ntype VariantSchema = z.ZodDiscriminatedUnion<readonly StrictObject<FieldSchemas>[], string>\ntype VariantDiscriminator<Schema extends VariantSchema> = Schema['_zod']['def']['discriminator']\ntype VariantTags<Schema extends VariantSchema> = Extract<\n\tz.output<Schema>[VariantDiscriminator<Schema>],\n\tstring\n>\ntype VariantBranch<Schema extends VariantSchema, Tag extends string> = Extract<\n\tSchema['options'][number],\n\tz.ZodObject<{ [Key in VariantDiscriminator<Schema>]: z.ZodLiteral<Tag> }, z.core.$strict>\n>\ntype VariantKeys<Schema extends VariantSchema, Tag extends string> = FieldKey<\n\tVariantBranch<Schema, Tag>['shape']\n>\n\n/** Boundary mode supports strict object branches with one string literal tag each. */\nexport type VariantBoundaryOptions<Schema extends VariantSchema> = {\n\tdiscriminator: VariantDiscriminator<Schema>\n\ttimestamps?: boolean\n\tvariants: {\n\t\t[Tag in VariantTags<Schema>]: {\n\t\t\tserverFields?: readonly Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>[]\n\t\t\tcommandFields?: readonly Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>[]\n\t\t\tpublicFields?: readonly (\n\t\t\t\t| Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>\n\t\t\t\t| keyof TimestampFields\n\t\t\t)[]\n\t\t}\n\t}\n}\ntype VariantMaskKeys<Config, Mask extends string> = Config extends {\n\t[Key in Mask]?: readonly (infer Field)[]\n}\n\t? Extract<Field, string>\n\t: never\ntype CheckedVariantOptions<\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n> = {\n\tvariants: {\n\t\t[Tag in keyof Options['variants']]: Tag extends VariantTags<Schema>\n\t\t\t? {\n\t\t\t\t\tcommandFields?: readonly Exclude<\n\t\t\t\t\t\tVariantKeys<Schema, Tag>,\n\t\t\t\t\t\tVariantDiscriminator<Schema> | VariantMaskKeys<Options['variants'][Tag], 'serverFields'>\n\t\t\t\t\t>[]\n\t\t\t\t\tpublicFields?: readonly (\n\t\t\t\t\t\t| Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>\n\t\t\t\t\t\t| (Options extends { timestamps: true } ? keyof TimestampFields : never)\n\t\t\t\t\t)[]\n\t\t\t\t}\n\t\t\t: never\n\t}\n}\ntype VariantMode =\n\t| 'storage'\n\t| 'document'\n\t| 'insert'\n\t| 'update'\n\t| 'command'\n\t| 'commandUpdate'\n\t| 'public'\ntype VariantFields<\n\tTable extends string,\n\tBranch extends StrictObject<FieldSchemas>,\n\tDiscriminator extends string,\n\tConfig,\n\tTimestamps extends boolean,\n\tMode extends VariantMode,\n> = Mode extends 'storage'\n\t? Branch['shape'] & (true extends Timestamps ? TimestampFields : {})\n\t: Mode extends 'document'\n\t\t? VariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'> &\n\t\t\t\tSystemFields<Table>\n\t\t: Mode extends 'public' | 'command'\n\t\t\t? Pick<\n\t\t\t\t\tVariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'>,\n\t\t\t\t\tExtract<\n\t\t\t\t\t\t| Discriminator\n\t\t\t\t\t\t| VariantMaskKeys<Config, Mode extends 'public' ? 'publicFields' : 'commandFields'>,\n\t\t\t\t\t\tkeyof VariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'>\n\t\t\t\t\t>\n\t\t\t\t>\n\t\t\t: Mode extends 'insert'\n\t\t\t\t? Omit<Branch['shape'], VariantMaskKeys<Config, 'serverFields'>>\n\t\t\t\t: PartialFields<\n\t\t\t\t\t\tOmit<\n\t\t\t\t\t\t\tVariantFields<\n\t\t\t\t\t\t\t\tTable,\n\t\t\t\t\t\t\t\tBranch,\n\t\t\t\t\t\t\t\tDiscriminator,\n\t\t\t\t\t\t\t\tConfig,\n\t\t\t\t\t\t\t\tTimestamps,\n\t\t\t\t\t\t\t\tMode extends 'update' ? 'insert' : 'command'\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tDiscriminator\n\t\t\t\t\t\t>\n\t\t\t\t\t> &\n\t\t\t\t\t\tPick<Branch['shape'], Extract<Discriminator, keyof Branch['shape']>>\ntype DerivedVariantBranches<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n\tMode extends VariantMode,\n\tIncludeId extends boolean,\n\tBranches extends readonly StrictObject<FieldSchemas>[],\n> = {\n\t[Index in keyof Branches]: Branches[Index] extends StrictObject<FieldSchemas>\n\t\t? StrictObject<\n\t\t\t\tVariantFields<\n\t\t\t\t\tTable,\n\t\t\t\t\tBranches[Index],\n\t\t\t\t\tVariantDiscriminator<Schema>,\n\t\t\t\t\tOptions['variants'][Extract<\n\t\t\t\t\t\tz.output<Branches[Index]>[VariantDiscriminator<Schema>],\n\t\t\t\t\t\tkeyof Options['variants']\n\t\t\t\t\t>],\n\t\t\t\t\tOptions extends { timestamps: infer Enabled }\n\t\t\t\t\t\t? true extends Enabled\n\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t: false,\n\t\t\t\t\tMode\n\t\t\t\t> &\n\t\t\t\t\t(IncludeId extends true ? { _id: Zid<Table> } : {})\n\t\t\t>\n\t\t: never\n}\ntype DerivedVariant<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n\tMode extends VariantMode,\n\tIncludeId extends boolean = false,\n> = IncludeId extends true\n\t? z.ZodDiscriminatedUnion<\n\t\t\tDerivedVariantBranches<Table, Schema, Options, Mode, true, Schema['options']>,\n\t\t\tVariantDiscriminator<Schema>\n\t\t>\n\t: z.ZodDiscriminatedUnion<\n\t\t\tDerivedVariantBranches<Table, Schema, Options, Mode, false, Schema['options']>,\n\t\t\tVariantDiscriminator<Schema>\n\t\t>\n\nexport type VariantTableBoundary<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n> = {\n\ttableName: Table\n\tstorage: DerivedVariant<Table, Schema, Options, 'storage'>\n\tschema: DerivedVariant<Table, Schema, Options, 'document'>\n\tinsertSchema: DerivedVariant<Table, Schema, Options, 'insert'>\n\tupdateSchema: DerivedVariant<Table, Schema, Options, 'update'>\n\tcommandInput: DerivedVariant<Table, Schema, Options, 'command'>\n\tpublicDto: DerivedVariant<Table, Schema, Options, 'public'>\n\ttable: TableDefinition<\n\t\tConvexValidatorFromZod<DerivedVariant<Table, Schema, Options, 'storage'>, 'required'>\n\t>\n\tdto(): DerivedVariant<Table, Schema, Options, 'public'>\n\tdto<const IncludeId extends boolean>(\n\t\tincludeId: IncludeId,\n\t): DerivedVariant<Table, Schema, Options, 'public', IncludeId>\n\ttoPublicDto(\n\t\trow: z.input<DerivedVariant<Table, Schema, Options, 'storage'>>,\n\t): z.output<DerivedVariant<Table, Schema, Options, 'public'>>\n\ttoPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<z.input<DerivedVariant<Table, Schema, Options, 'storage'>>, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DerivedVariant<Table, Schema, Options, 'public', IncludeId>>\n\ttools: {\n\t\tid: StrictObject<{ id: z.ZodType<GenericId<Table>, string> }>\n\t\tinsert: z.ZodType<\n\t\t\tz.output<DerivedVariant<Table, Schema, Options, 'command'>>,\n\t\t\tz.input<DerivedVariant<Table, Schema, Options, 'command'>>\n\t\t>\n\t\tupdate: StrictObject<{\n\t\t\tid: z.ZodType<GenericId<Table>, string>\n\t\t\tdata: z.ZodType<\n\t\t\t\tz.output<DerivedVariant<Table, Schema, Options, 'commandUpdate'>>,\n\t\t\t\tz.input<DerivedVariant<Table, Schema, Options, 'commandUpdate'>>\n\t\t\t>\n\t\t}>\n\t}\n}\n\n/** Legacy mode preserves arbitrary storage; the third argument opts into derived boundaries. */\nexport function zodVariantTable<Table extends string, Schema extends z.ZodType>(\n\ttableName: Table,\n\tstorage: Schema,\n): {\n\ttableName: Table\n\tstorage: Schema\n\tinsertSchema: Schema\n\ttable: TableDefinition<ConvexValidatorFromZod<Schema, 'required'>>\n}\nexport function zodVariantTable<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tconst Options extends VariantBoundaryOptions<Schema>,\n>(\n\ttableName: Table,\n\tstorage: Schema,\n\toptions: Options & CheckedVariantOptions<Schema, NoInfer<Options>>,\n): VariantTableBoundary<Table, Schema, Options>\nexport function zodVariantTable(\n\ttableName: string,\n\tstorage: z.ZodType,\n\toptions?: {\n\t\tdiscriminator: string\n\t\ttimestamps?: boolean\n\t\tvariants: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tserverFields?: readonly string[]\n\t\t\t\tcommandFields?: readonly string[]\n\t\t\t\tpublicFields?: readonly string[]\n\t\t\t}\n\t\t>\n\t},\n) {\n\tif (options) return deriveVariantTable(tableName, storage, options)\n\treturn {\n\t\ttableName,\n\t\tstorage,\n\t\tinsertSchema: storage,\n\t\ttable: defineTable(zodToConvex(storage)),\n\t}\n}\n\n/**\n * A zid that presents as a plain string in generated JSON schemas so\n * LLM-tool inputs stay primitive, while keeping the Id type at compile time.\n */\nexport function jsonSafeZid<Table extends string>(\n\ttableName: Table,\n): z.ZodType<GenericId<Table>, string> {\n\tconst id = zid(tableName)\n\treturn z\n\t\t.string()\n\t\t.refine((value): value is GenericId<Table> => id.safeParse(value).success)\n\t\t.describe(`Convex document id for table \"${tableName}\"; validated against the table by Convex`)\n}\n\nfunction deriveVariantTable(\n\ttableName: string,\n\tdeclared: z.ZodType,\n\toptions: {\n\t\tdiscriminator: string\n\t\ttimestamps?: boolean\n\t\tvariants: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tserverFields?: readonly string[]\n\t\t\t\tcommandFields?: readonly string[]\n\t\t\t\tpublicFields?: readonly string[]\n\t\t\t}\n\t\t>\n\t},\n) {\n\tif (\n\t\t!(declared instanceof z.ZodDiscriminatedUnion) ||\n\t\tdeclared.def.discriminator !== options.discriminator\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant boundaries require a discriminated union with the configured discriminator',\n\t\t)\n\tif (declared.def.checks?.length)\n\t\tthrow new Error('Variant boundaries do not support union-level refinements')\n\tconst timestamps = options.timestamps\n\tconst discriminator = options.discriminator\n\tif (['_id', '_creationTime', ...TIMESTAMP_FIELDS].includes(discriminator))\n\t\tthrow new Error('Variant discriminator cannot be a reserved field')\n\tconst branches = new Map<\n\t\tstring,\n\t\t{\n\t\t\tstorage: StrictObject<FieldSchemas>\n\t\t\tdocument: StrictObject<FieldSchemas>\n\t\t\tinsert: StrictObject<FieldSchemas>\n\t\t\tupdate: StrictObject<FieldSchemas>\n\t\t\tcommand: StrictObject<FieldSchemas>\n\t\t\tcommandUpdate: StrictObject<FieldSchemas>\n\t\t\ttoolCommand: StrictObject<FieldSchemas>\n\t\t\tpublic: StrictObject<FieldSchemas>\n\t\t}\n\t>()\n\tfor (const branch of declared.options) {\n\t\tif (!(branch instanceof z.ZodObject) || !(branch.def.catchall instanceof z.ZodNever))\n\t\t\tthrow new Error('Variant boundaries require strict object branches')\n\t\tif (branch.def.checks?.length)\n\t\t\tthrow new Error('Variant boundaries do not support object-level refinements')\n\t\ttry {\n\t\t\tassertDtoValidationSchema(branch, new Set(), true)\n\t\t} catch (cause) {\n\t\t\tthrow new Error(\n\t\t\t\t'Variant boundaries require supported value-preserving field validators without object catchalls',\n\t\t\t\t{ cause },\n\t\t\t)\n\t\t}\n\t\tconst tagSchema = branch.shape[discriminator]\n\t\tif (!(tagSchema instanceof z.ZodLiteral) || tagSchema.values.size !== 1)\n\t\t\tthrow new Error('Variant branches require one string literal discriminator')\n\t\tconst tag = [...tagSchema.values][0]\n\t\tif (!z.string().safeParse(tag).success)\n\t\t\tthrow new Error('Variant branches require a string discriminator')\n\t\t// SAFETY: a single literal value was checked as a string above.\n\t\tconst tagValue = tag as string\n\t\tif (branches.has(tagValue)) throw new Error(`Duplicate variant discriminator \"${tagValue}\"`)\n\t\tif (!Object.hasOwn(options.variants, tagValue))\n\t\t\tthrow new Error(`Missing variant configuration \"${tagValue}\"`)\n\t\tconst config = {\n\t\t\tserverFields: [...(options.variants[tagValue].serverFields ?? [])],\n\t\t\tcommandFields: [...(options.variants[tagValue].commandFields ?? [])],\n\t\t\tpublicFields: [...(options.variants[tagValue].publicFields ?? [])],\n\t\t}\n\t\tassertOwnedFields(branch.shape, [\n\t\t\t'_id',\n\t\t\t'_creationTime',\n\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t])\n\t\tconst columns = { ...branch.shape } satisfies FieldSchemas\n\t\tif (timestamps) Object.assign(columns, timestampFields)\n\t\tassertFieldLists(\n\t\t\tcolumns,\n\t\t\tconfig.serverFields ?? [],\n\t\t\tconfig.commandFields ?? [],\n\t\t\tconfig.publicFields ?? [],\n\t\t\ttimestamps !== false,\n\t\t)\n\t\tfor (const mask of [config.serverFields, config.commandFields, config.publicFields]) {\n\t\t\tif (mask?.includes(discriminator))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'The variant discriminator is retained automatically and cannot appear in masks',\n\t\t\t\t)\n\t\t}\n\t\tfor (const field of config.commandFields) assertVariantToolField(columns[field])\n\t\tconst stored = z.strictObject({ ...columns })\n\t\tconst getInsert = memoize(() =>\n\t\t\tz.strictObject(\n\t\t\t\tomitFields(columns, [\n\t\t\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t\t\t\t...(config.serverFields ?? []),\n\t\t\t\t]),\n\t\t\t),\n\t\t)\n\t\tconst getCommand = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...(config.commandFields ?? [])])),\n\t\t)\n\t\tconst partial = (schema: StrictObject<FieldSchemas>) =>\n\t\t\tschema.partial().extend({ [discriminator]: tagSchema })\n\t\tconst getDocument = memoize(() => documentSchema(columns, tableName))\n\t\tconst getUpdate = memoize(() =>\n\t\t\tpartial(\n\t\t\t\tz.strictObject(\n\t\t\t\t\tomitFields(columns, [\n\t\t\t\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t\t\t\t\t...config.serverFields,\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\tconst getCommandUpdate = memoize(() =>\n\t\t\tpartial(z.strictObject(pickFields(columns, [discriminator, ...config.commandFields]))),\n\t\t)\n\t\tconst getToolCommand = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...config.commandFields])),\n\t\t)\n\t\tconst getPublic = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...(config.publicFields ?? [])])),\n\t\t)\n\t\tbranches.set(tagValue, {\n\t\t\tstorage: stored,\n\t\t\tget document() {\n\t\t\t\treturn getDocument()\n\t\t\t},\n\t\t\tget insert() {\n\t\t\t\treturn getInsert()\n\t\t\t},\n\t\t\tget update() {\n\t\t\t\treturn getUpdate()\n\t\t\t},\n\t\t\tget command() {\n\t\t\t\treturn getCommand()\n\t\t\t},\n\t\t\tget commandUpdate() {\n\t\t\t\treturn getCommandUpdate()\n\t\t\t},\n\t\t\tget toolCommand() {\n\t\t\t\treturn getToolCommand()\n\t\t\t},\n\t\t\tget public() {\n\t\t\t\treturn getPublic()\n\t\t\t},\n\t\t})\n\t}\n\tfor (const tag of Object.keys(options.variants)) {\n\t\tif (!branches.has(tag)) throw new Error(`Unknown variant configuration \"${tag}\"`)\n\t}\n\tfunction union(mode: VariantMode, includeId = false, tool = false) {\n\t\tconst schemas = [...branches.values()].map((branch) => {\n\t\t\tconst schema = tool && mode === 'command' ? branch.toolCommand : branch[mode]\n\t\t\tif (tool)\n\t\t\t\treturn z.strictObject(\n\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\tObject.entries(schema.shape).map(([key, field]) => [key, variantToolField(field)]),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\treturn includeId ? schema.extend({ _id: zid(tableName) }) : schema\n\t\t})\n\t\tif (!schemas.length) throw new Error('Variant boundaries require at least one branch')\n\t\t// SAFETY: all entries are checked strict objects with a unique required literal tag; nonempty checked above.\n\t\treturn z.discriminatedUnion(\n\t\t\tdiscriminator,\n\t\t\tschemas as [StrictObject<FieldSchemas>, ...StrictObject<FieldSchemas>[]],\n\t\t)\n\t}\n\tconst storage = union('storage')\n\tconst getSchema = memoize(() => union('document'))\n\tconst getInsertSchema = memoize(() => union('insert'))\n\tconst getUpdateSchema = memoize(() => union('update'))\n\tconst getCommandInput = memoize(() => union('command'))\n\tconst getPublicDto = memoize(() => union('public'))\n\tfunction dto(includeId = false) {\n\t\treturn includeId ? union('public', true) : getPublicDto()\n\t}\n\t// Projection-only ID schema is never returned by dto() or exposed on the declaration.\n\tlet projectionId: Zid<string> | undefined\n\tfunction toPublicDto(row: z.input<StrictObject<FieldSchemas>>, includeId = false) {\n\t\tconst tag = z.string().parse(row[discriminator])\n\t\tconst branch = branches.get(tag)\n\t\tif (!branch) throw new Error(`Unknown variant discriminator \"${tag}\"`)\n\t\tconst projection = includeId\n\t\t\t? branch.public.extend({ _id: (projectionId ??= zid(tableName)) })\n\t\t\t: branch.public\n\t\treturn projection.parse(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.keys(projection.shape)\n\t\t\t\t\t.filter((key) => Object.hasOwn(row, key))\n\t\t\t\t\t.map((key) => [key, row[key]]),\n\t\t\t),\n\t\t)\n\t}\n\tconst getTools = memoize(() => ({\n\t\tid: z.strictObject({ id: jsonSafeZid(tableName) }),\n\t\tinsert: union('command', false, true),\n\t\tupdate: z.strictObject({\n\t\t\tid: jsonSafeZid(tableName),\n\t\t\tdata: union('commandUpdate', false, true),\n\t\t}),\n\t}))\n\n\treturn {\n\t\ttableName,\n\t\tstorage,\n\t\tget schema() {\n\t\t\treturn getSchema()\n\t\t},\n\t\tset schema(value: ReturnType<typeof getSchema>) {\n\t\t\treplaceBoundaryValue(this, 'schema', value)\n\t\t},\n\t\tget insertSchema() {\n\t\t\treturn getInsertSchema()\n\t\t},\n\t\tset insertSchema(value: ReturnType<typeof getInsertSchema>) {\n\t\t\treplaceBoundaryValue(this, 'insertSchema', value)\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn getUpdateSchema()\n\t\t},\n\t\tset updateSchema(value: ReturnType<typeof getUpdateSchema>) {\n\t\t\treplaceBoundaryValue(this, 'updateSchema', value)\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn getCommandInput()\n\t\t},\n\t\tset commandInput(value: ReturnType<typeof getCommandInput>) {\n\t\t\treplaceBoundaryValue(this, 'commandInput', value)\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn getPublicDto()\n\t\t},\n\t\tset publicDto(value: ReturnType<typeof getPublicDto>) {\n\t\t\treplaceBoundaryValue(this, 'publicDto', value)\n\t\t},\n\t\tdto,\n\t\ttoPublicDto,\n\t\ttable: defineTable(zodToConvex(storage)),\n\t\tget tools() {\n\t\t\treturn getTools()\n\t\t},\n\t\tset tools(value: ReturnType<typeof getTools>) {\n\t\t\treplaceBoundaryValue(this, 'tools', value)\n\t\t},\n\t}\n}\n\n/** Validate tool eligibility without constructing any derived command/tool objects. */\nfunction assertVariantToolField(schema: z.core.$ZodType): void {\n\tif (!(schema instanceof z.ZodType))\n\t\tthrow new Error('Variant tools require classic Zod field schemas')\n\tif (\n\t\tschema instanceof z.ZodBigInt ||\n\t\t(schema instanceof z.ZodLiteral &&\n\t\t\t[...schema.values].some((value) => z.bigint().safeParse(value).success))\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant tool command fields cannot contain bigint; JSON Schema cannot represent it',\n\t\t)\n\tif (\n\t\tschema instanceof z.ZodOptional ||\n\t\tschema instanceof z.ZodNullable ||\n\t\tschema instanceof z.ZodNonOptional\n\t)\n\t\tassertVariantToolField(schema.unwrap())\n\telse if (schema instanceof z.ZodArray) assertVariantToolField(schema.element)\n\telse if (schema instanceof z.ZodObject)\n\t\tObject.values(schema.shape).forEach(assertVariantToolField)\n\telse if (schema instanceof z.ZodUnion) schema.options.forEach(assertVariantToolField)\n\telse if (schema instanceof z.ZodRecord) {\n\t\tassertVariantToolField(schema.keyType)\n\t\tassertVariantToolField(schema.valueType)\n\t} else if (schema instanceof z.ZodTuple) {\n\t\tschema.def.items.forEach(assertVariantToolField)\n\t\tif (schema.def.rest) assertVariantToolField(schema.def.rest)\n\t} else if (schema instanceof z.ZodIntersection) {\n\t\tassertVariantToolField(schema.def.left)\n\t\tassertVariantToolField(schema.def.right)\n\t}\n}\n\nfunction variantToolField(schema: z.core.$ZodType): z.ZodType {\n\tif (!(schema instanceof z.ZodType))\n\t\tthrow new Error('Variant tools require classic Zod field schemas')\n\tif (\n\t\tschema instanceof z.ZodBigInt ||\n\t\t(schema instanceof z.ZodLiteral &&\n\t\t\t[...schema.values].some((value) => z.bigint().safeParse(value).success))\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant tool command fields cannot contain bigint; JSON Schema cannot represent it',\n\t\t)\n\tconst native = zodToConvex(schema)\n\tif (native.kind === 'id') {\n\t\tconst id = jsonSafeZid(native.tableName)\n\t\tif (native.isOptional === 'optional')\n\t\t\treturn id.optional().refine((value) => schema.safeParse(value).success)\n\t\treturn id.refine((value) => schema.safeParse(value).success)\n\t}\n\tif (schema instanceof z.ZodOptional)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodNullable)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodNonOptional)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodArray)\n\t\treturn schema.clone({ ...schema.def, element: variantToolField(schema.element) })\n\tif (schema instanceof z.ZodObject) {\n\t\tconst fields = Object.fromEntries(\n\t\t\tObject.entries(schema.shape).map(([key, child]) => [key, variantToolField(child)]),\n\t\t)\n\t\treturn schema.clone(Object.assign({}, schema.def, { ['shape']: fields }))\n\t}\n\tif (schema instanceof z.ZodUnion)\n\t\treturn schema.clone({ ...schema.def, options: schema.options.map(variantToolField) })\n\tif (schema instanceof z.ZodRecord)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\t// SAFETY: conversion preserves the original record key output; IDs remain strings.\n\t\t\tkeyType: variantToolField(schema.keyType) as z.core.$ZodRecordKey,\n\t\t\tvalueType: variantToolField(schema.valueType),\n\t\t})\n\tif (schema instanceof z.ZodTuple)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\titems: schema.def.items.map(variantToolField),\n\t\t\trest: schema.def.rest ? variantToolField(schema.def.rest) : null,\n\t\t})\n\tif (schema instanceof z.ZodIntersection)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\tleft: variantToolField(schema.def.left),\n\t\t\tright: variantToolField(schema.def.right),\n\t\t})\n\treturn schema\n}\n\ntype ZodObjectOmit<\n\tSchema extends z.ZodObject<any, any>,\n\tOmitMask extends z.util.Mask<keyof Schema['shape']>,\n> =\n\tSchema extends z.ZodObject<infer ObjectFields, infer Config>\n\t\t? z.ZodObject<\n\t\t\t\tz.util.Flatten<Omit<ObjectFields, Extract<keyof ObjectFields, keyof OmitMask>>>,\n\t\t\t\tConfig\n\t\t\t>\n\t\t: never\n\n/** A public replacement never changes the private schemas captured by boundary helpers. */\nfunction replaceBoundaryValue<Boundary extends object, Key extends keyof Boundary>(\n\tboundary: Boundary,\n\tkey: Key,\n\tvalue: Boundary[Key],\n): void {\n\tObject.defineProperty(boundary, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t})\n}\n\nfunction documentSchema<Fields extends FieldSchemas, Table extends string>(\n\tfields: Fields,\n\ttableName: Table,\n) {\n\treturn z.strictObject({ ...fields, _id: zid(tableName), _creationTime: z.number() })\n}\n\nfunction pickFields<Fields extends FieldSchemas, const Keys extends readonly FieldKey<Fields>[]>(\n\tfields: Fields,\n\tkeys: Keys,\n) {\n\t// SAFETY: each entry uses a requested key and its original validator, preserving Pick.\n\treturn Object.fromEntries(keys.map((key) => [key, fields[key]])) as Pick<Fields, Keys[number]>\n}\n\nfunction omitFields<Fields extends FieldSchemas, const Keys extends readonly FieldKey<Fields>[]>(\n\tfields: Fields,\n\tkeys: Keys,\n) {\n\tconst omitted = new Set<string>(keys)\n\t// SAFETY: filtering removes exactly the supplied keys and keeps every remaining validator.\n\treturn Object.fromEntries(Object.entries(fields).filter(([key]) => !omitted.has(key))) as Omit<\n\t\tFields,\n\t\tKeys[number]\n\t>\n}\n\ntype DtoPropertiesCheck = z.core.$ZodCheck & {\n\treadonly _zod: {\n\t\treadonly def: { readonly check: 'properties' } & Record<\n\t\t\t'shape',\n\t\t\tRecord<string, z.core.$ZodType>\n\t\t>\n\t}\n}\n\n/** Inspect Zod 4's discriminated definitions, failing closed for unsupported nodes.\n * Used by DTO extensions and opt-in variant boundaries; legacy schemas are unchanged.\n */\nfunction assertDtoValidationSchema(\n\tschema: z.core.$ZodType,\n\tseen = new Set<z.core.$ZodType>(),\n\tallowNativeIds = false,\n): void {\n\tif (seen.has(schema)) return\n\tseen.add(schema)\n\t// SAFETY: Zod 4 exposes its built-in schema definitions as this discriminated union.\n\tconst def = (schema as z.core.$ZodTypes)._zod.def\n\tconst reject = () => {\n\t\tthrow new Error('DTO extensions require supported value-preserving validation schemas')\n\t}\n\tif ('coerce' in def && def.coerce) reject()\n\tif ('normalize' in def && def.normalize) reject()\n\tconst visit = (child: z.core.$ZodType) => assertDtoValidationSchema(child, seen, allowNativeIds)\n\tfor (const check of def.checks ?? []) {\n\t\tif (check._zod.def.check === 'overwrite') reject()\n\t\tif ('normalize' in check._zod.def && check._zod.def.normalize) reject()\n\t\tif (check._zod.def.check === 'property') {\n\t\t\t// SAFETY: the property discriminator owns this embedded schema in Zod 4.\n\t\t\tvisit((check as z.core.$ZodCheckProperty)._zod.def.schema)\n\t\t}\n\t\tif (check._zod.def.check === 'properties') {\n\t\t\t// SAFETY: the properties discriminator owns this schema shape in Zod 4.\n\t\t\tfor (const child of Object.values((check as DtoPropertiesCheck)._zod.def.shape)) {\n\t\t\t\tvisit(child)\n\t\t\t}\n\t\t}\n\t}\n\tswitch (def.type) {\n\t\tcase 'custom':\n\t\t\tif (allowNativeIds && zodToConvex(schema).kind === 'id') return\n\t\t\treject()\n\t\t\treturn\n\t\tcase 'string':\n\t\tcase 'number':\n\t\tcase 'boolean':\n\t\tcase 'bigint':\n\t\tcase 'date':\n\t\tcase 'symbol':\n\t\tcase 'null':\n\t\tcase 'undefined':\n\t\tcase 'void':\n\t\tcase 'never':\n\t\tcase 'literal':\n\t\tcase 'enum':\n\t\t\treturn\n\t\tcase 'object':\n\t\t\tif (allowNativeIds && def.catchall && def.catchall._zod.def.type !== 'never')\n\t\t\t\tthrow new Error('Variant fields cannot use object catchalls; use a record field instead')\n\t\t\tfor (const child of Object.values(def.shape)) visit(child)\n\t\t\tif (def.catchall) visit(def.catchall)\n\t\t\treturn\n\t\tcase 'array':\n\t\t\tvisit(def.element)\n\t\t\treturn\n\t\tcase 'optional':\n\t\tcase 'nullable':\n\t\tcase 'nonoptional':\n\t\t\tvisit(def.innerType)\n\t\t\treturn\n\t\tcase 'union':\n\t\t\tfor (const child of def.options) visit(child)\n\t\t\treturn\n\t\tcase 'intersection':\n\t\t\tvisit(def.left)\n\t\t\tvisit(def.right)\n\t\t\treturn\n\t\tcase 'tuple':\n\t\t\tfor (const child of def.items) visit(child)\n\t\t\tif (def.rest) visit(def.rest)\n\t\t\treturn\n\t\tcase 'record':\n\t\t\tvisit(def.keyType)\n\t\t\tvisit(def.valueType)\n\t\t\treturn\n\t\tdefault:\n\t\t\treject()\n\t}\n}\n\nfunction assertOwnedFields(fields: FieldSchemas, reserved: readonly string[]): void {\n\tfor (const key of reserved) {\n\t\tif (Object.hasOwn(fields, key))\n\t\t\tthrow new Error(`Reserved table field \"${key}\" cannot be declared`)\n\t}\n}\n\nfunction assertFieldLists(\n\tfields: FieldSchemas,\n\tserver: readonly string[],\n\tcommand: readonly string[],\n\tpublicKeys: readonly string[],\n\tmanagedTimestamps = true,\n): void {\n\tfor (const key of [...server, ...command, ...publicKeys]) {\n\t\tif (!Object.hasOwn(fields, key)) throw new Error(`Unknown table field \"${key}\"`)\n\t}\n\tconst managed = new Set<string>([...(managedTimestamps ? TIMESTAMP_FIELDS : []), ...server])\n\tfor (const key of command) {\n\t\tif (managed.has(key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js","names":["zid","convexToZod","convexToZod$1","zid$1","timestampFields","z","TIMESTAMP_FIELDS","zodTable","declared","fields","assertOwnedFields","columns","assertFieldLists","options","storage","getSchema","memoize","documentSchema","tableName","omittedKeys","commandKeys","publicKeys","getWriteFields","omitFields","getCommandFields","pickFields","getInsertSchema","getUpdateSchema","getCommandInput","getPublicDto","derived","getEmptyDtoExtension","getReservedDtoFields","dto","deriveDto","normalized","extension","assertDtoExtension","resultSchema","key","assertDtoValidationSchema","toPublicDto","projected","row","extensionFields","result","insert","omit","update","nativeStorage","zodToConvex","table","defineTable","getPaginationFields","field","paginationOpts","scalarPaginationSchema","selection","getTools","jsonSafeZid","replaceBoundaryValue","value","createTable","shared","id","tenantFields","tenantTable","createModule","maps","combined","namespaceNames","map","meta","namespaceMeta","definition","namespaceKey","NAMESPACE_SEGMENT","TABLE_NAME","namespace","name","segment","tables","member","members","hasPrefix","namespacePrefix","prefix","memberName","namespaceName","ns","tablesOf","namespaceIndex","spaces","byTable","byName","space","owner","paginated","paginationOptsValidator","pageResult","zodVariantTable","deriveVariantTable","timestamps","discriminator","branches","branch","cause","tagSchema","tag","tagValue","config","mask","assertVariantToolField","stored","getInsert","getCommand","partial","schema","getDocument","getUpdate","getCommandUpdate","getToolCommand","getPublic","union","schemas","tool","mode","variantToolField","includeId","projectionId","projection","native","child","\"shape\"","boundary","keys","omitted","seen","def","reject","visit","allowNativeIds","check","reserved","server","command","managed","managedTimestamps","convexToZod","zid"],"sources":["../src/zod-table.ts"],"sourcesContent":["import { pageResult } from './querying/shared/page'\nimport { memoize } from './modules/contracts/lazy'\nimport type { PaginationValidatorOptions } from './querying/shared/filters'\nimport { convexToZod, zid, type ConvexValidatorFromZod, type Zid } from 'convex-helpers/server/zod4'\nimport {\n\tdefineTable,\n\tpaginationOptsValidator,\n\ttype TableDefinition,\n\ttype PaginationResult,\n} from 'convex/server'\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\n\nimport { zodToConvex } from './zod-convex'\n\nimport {\n\tscalarPaginationSchema,\n\ttype ScalarPaginationSchema,\n\ttype ScalarSelection,\n\ttype ExactScalarSelection,\n} from './querying/filters'\n\n// Use this entry point when deriving validators from kit-owned schemas so\n// the producer and converter consult the same convex-helpers ID registry.\nexport { zid, convexToZod } from 'convex-helpers/server/zod4'\nexport { zodToConvex } from './zod-convex'\n\ntype FieldSchemas = Record<string, z.ZodType>\ntype FieldKey<Fields extends FieldSchemas> = Extract<keyof Fields, string>\n\n/**\n * Opinionated lifecycle timestamps — every table has them, server-owned,\n * always excluded from insert/command boundaries. Maintained by the\n * `timestamps` trigger helper (see cvx-kit/triggers).\n */\nconst timestampFields = {\n\tcreatedAt: z.number().optional(),\n\tupdatedAt: z.number().optional(),\n\tarchivedAt: z.number().optional(),\n} satisfies FieldSchemas\n\ntype TimestampFields = typeof timestampFields\ntype ReservedStorageField = '_id' | '_creationTime' | keyof TimestampFields\ntype OwnedFields<Fields> = {\n\t[Key in keyof Fields]: Key extends ReservedStorageField ? never : Fields[Key]\n}\ntype SystemFields<Table extends string> = { _id: Zid<Table>; _creationTime: z.ZodNumber }\n\nexport const TIMESTAMP_FIELDS = ['createdAt', 'updatedAt', 'archivedAt'] as const\n\nexport type TableBoundaryOptions<\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n\tCommandFields extends readonly FieldKey<Fields>[],\n\tPublicFields extends readonly FieldKey<Fields & TimestampFields>[],\n> = {\n\tserverFields?: ServerFields\n\tcommandFields?: CommandFields &\n\t\treadonly Exclude<FieldKey<Fields>, ServerFields[number] | keyof TimestampFields>[]\n\tpublicFields?: PublicFields\n}\n\ntype StrictObject<Fields extends FieldSchemas> = z.ZodObject<Fields, z.core.$strict>\ntype WriteFields<\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n> = Omit<Fields & TimestampFields, ServerFields[number] | (typeof TIMESTAMP_FIELDS)[number]>\ntype PartialFields<Fields extends FieldSchemas> = {\n\t[Key in keyof Fields]: z.ZodOptional<Fields[Key]>\n}\n\n/** Options shared by the DTO return schema and row projector.\n * Promised contributions must be present, including in reusable options.\n * New extension schemas support validation only: no transforms, pipes,\n * coercion, preprocess, defaults, catches, or overwrites, even when nested.\n * Refinements must validate without mutating their input.\n */\nexport type DtoOptions<IncludeId extends boolean = false, Extension extends FieldSchemas = {}> = ([\n\tIncludeId,\n] extends [true]\n\t? { _id: IncludeId }\n\t: { _id?: IncludeId }) &\n\t(keyof Extension extends never ? { extend?: Extension } : { extend: Extension })\n\ntype DtoProjectionOptions<IncludeId extends boolean> = DtoOptions<IncludeId> & {\n\textend?: Record<string, never>\n\tvalues?: never\n}\n\ntype ReservedDtoField =\n\t| '_id'\n\t| '_creationTime'\n\t| 'tenant'\n\t| '__proto__'\n\t| (typeof TIMESTAMP_FIELDS)[number]\ntype DtoExtension<Public extends FieldSchemas, Extension extends FieldSchemas> = {\n\t[Key in keyof Extension]: Key extends keyof Public | ReservedDtoField\n\t\t? never\n\t\t: Extension[Key] extends z.ZodPipe | z.ZodTransform\n\t\t\t? never\n\t\t\t: unknown\n}\n// Broad dictionaries cannot promise any particular extension field.\ntype KnownExtension<Extension> = string extends keyof Extension ? {} : Extension\n\ntype DtoSchema<\n\tTable extends string,\n\tPublic extends FieldSchemas,\n\tIncludeId extends boolean,\n\tExtension extends FieldSchemas = {},\n> = IncludeId extends true\n\t? StrictObject<Public & { _id: Zid<Table> } & KnownExtension<Extension>>\n\t: StrictObject<Public & KnownExtension<Extension>>\ntype DtoRow<Row, IncludeId extends boolean> = Row & (true extends IncludeId ? { _id: string } : {})\ntype DtoValues<Extension extends FieldSchemas> = keyof Extension extends never\n\t? { values?: never }\n\t: { values: z.input<StrictObject<NoInfer<Extension>>> }\n\ntype DtoBoundary<Table extends string, Fields extends FieldSchemas, Public extends FieldSchemas> = {\n\tdto(): StrictObject<Public>\n\tdto<const IncludeId extends boolean>(includeId: IncludeId): DtoSchema<Table, Public, IncludeId>\n\tdto<const IncludeId extends boolean = false>(\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): DtoSchema<Table, Public, IncludeId>\n\tdto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\toptions: DtoOptions<IncludeId, Extension> & { extend?: DtoExtension<Public, Extension> },\n\t): DtoSchema<Table, Public, IncludeId, Extension>\n\ttoPublicDto(row: z.input<StrictObject<Fields>>): z.output<StrictObject<Public>>\n\ttoPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\ttoPublicDto<const IncludeId extends boolean = false>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\ttoPublicDto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\trow: DtoRow<z.input<StrictObject<Fields>>, IncludeId>,\n\t\toptions: DtoOptions<IncludeId, Extension> & {\n\t\t\textend?: DtoExtension<Public, Extension>\n\t\t} & DtoValues<Extension>,\n\t): z.output<DtoSchema<Table, Public, IncludeId, Extension>>\n}\n\n/** Named schema relationships keep generated declarations bounded and consumers fully typed. */\nexport type TableBoundary<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tServerFields extends readonly FieldKey<Fields>[],\n\tCommandFields extends readonly FieldKey<Fields>[],\n\tPublicFields extends readonly FieldKey<Fields & TimestampFields>[],\n> = DtoBoundary<\n\tTable,\n\tFields & TimestampFields,\n\tPick<Fields & TimestampFields, PublicFields[number]>\n> & {\n\tpaginationOpts<\n\t\tconst Selection extends ScalarSelection<Fields & TimestampFields & SystemFields<Table>>,\n\t>(\n\t\tselection: ExactScalarSelection<Fields & TimestampFields & SystemFields<Table>, Selection>,\n\t\toptions?: PaginationValidatorOptions,\n\t): ScalarPaginationSchema<Fields & TimestampFields & SystemFields<Table>, Selection>\n\ttableName: Table\n\tstorage: StrictObject<Fields & TimestampFields>\n\tschema: ReturnType<typeof documentSchema<Fields & TimestampFields, Table>>\n\tinsertSchema: StrictObject<WriteFields<Fields, ServerFields>>\n\tupdateSchema: StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>\n\tcommandInput: StrictObject<Pick<Fields & TimestampFields, CommandFields[number]>>\n\tpublicDto: StrictObject<Pick<Fields & TimestampFields, PublicFields[number]>>\n\ttable: TableDefinition<ConvexValidatorFromZod<StrictObject<Fields & TimestampFields>, 'required'>>\n\tinsert(): StrictObject<WriteFields<Fields, ServerFields>>\n\tinsert<Mask extends z.util.Mask<keyof WriteFields<Fields, ServerFields>>>(\n\t\tomit: Mask,\n\t): ZodObjectOmit<StrictObject<WriteFields<Fields, ServerFields>>, Mask>\n\tupdate(): StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>\n\tupdate<Mask extends z.util.Mask<keyof WriteFields<Fields, ServerFields>>>(\n\t\tomit: Mask,\n\t): ZodObjectOmit<StrictObject<PartialFields<WriteFields<Fields, ServerFields>>>, Mask>\n\ttools: {\n\t\tinsert: StrictObject<Pick<Fields & TimestampFields, CommandFields[number]>>\n\t\tupdate: StrictObject<{\n\t\t\tdata: StrictObject<PartialFields<Pick<Fields & TimestampFields, CommandFields[number]>>>\n\t\t\tid: z.ZodType<GenericId<Table>, string>\n\t\t}>\n\t\tid: StrictObject<{ id: z.ZodType<GenericId<Table>, string> }>\n\t}\n}\n\n/** Defines one table and derives its storage, document, write, and DTO boundaries. */\nexport function zodTable<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tconst ServerFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst CommandFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst PublicFields extends readonly FieldKey<Fields & TimestampFields>[] = readonly [],\n>(\n\ttableName: Table,\n\tfields: (id: typeof zid) => Fields & OwnedFields<Fields>,\n\toptions: TableBoundaryOptions<Fields, ServerFields, CommandFields, PublicFields> = {},\n): TableBoundary<Table, Fields, ServerFields, CommandFields, PublicFields> {\n\tconst declared = fields(zid)\n\tassertOwnedFields(declared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\tconst columns: Fields & TimestampFields = { ...declared, ...timestampFields }\n\tassertFieldLists(\n\t\tcolumns,\n\t\toptions.serverFields ?? [],\n\t\toptions.commandFields ?? [],\n\t\toptions.publicFields ?? [],\n\t)\n\tconst storage: z.ZodObject<Fields & TimestampFields, z.core.$strict> = z.strictObject({\n\t\t...columns,\n\t})\n\tconst getSchema = memoize(() =>\n\t\tdocumentSchema<Fields & TimestampFields, Table>(columns, tableName),\n\t)\n\tconst omittedKeys: readonly (ServerFields[number] | (typeof TIMESTAMP_FIELDS)[number])[] = [\n\t\t...TIMESTAMP_FIELDS,\n\t\t...(options.serverFields ?? []),\n\t]\n\tconst commandKeys: readonly CommandFields[number][] = [...(options.commandFields ?? [])]\n\tconst publicKeys: readonly PublicFields[number][] = [...(options.publicFields ?? [])]\n\t// Reuse declaration-time selections, never a mutable public schema's shape.\n\tconst getWriteFields = memoize(() => omitFields(columns, omittedKeys))\n\tconst getCommandFields = memoize(() => pickFields(columns, commandKeys))\n\tconst getInsertSchema = memoize(\n\t\t(): z.ZodObject<WriteFields<Fields, ServerFields>, z.core.$strict> =>\n\t\t\tz.strictObject({ ...getWriteFields() }),\n\t)\n\tconst getUpdateSchema = memoize(() => z.strictObject({ ...getWriteFields() }).partial())\n\tconst getCommandInput = memoize(\n\t\t(): z.ZodObject<Pick<Fields & TimestampFields, CommandFields[number]>, z.core.$strict> =>\n\t\t\tz.strictObject({ ...getCommandFields() }),\n\t)\n\tconst getPublicDto = memoize(\n\t\t(): z.ZodObject<Pick<Fields & TimestampFields, PublicFields[number]>, z.core.$strict> =>\n\t\t\tz.strictObject(pickFields(columns, publicKeys)),\n\t)\n\tconst derived = {\n\t\tget schema() {\n\t\t\treturn getSchema()\n\t\t},\n\t\tget insertSchema() {\n\t\t\treturn getInsertSchema()\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn getUpdateSchema()\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn getCommandInput()\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn getPublicDto()\n\t\t},\n\t}\n\n\ttype Public = Pick<Fields & TimestampFields, PublicFields[number]>\n\ttype Row = z.input<typeof storage>\n\ttype RuntimeDtoFields = Public & FieldSchemas\n\ttype RuntimeDto = z.output<StrictObject<RuntimeDtoFields>> & { _id?: GenericId<Table> }\n\ttype RuntimeOptions = { _id?: boolean; extend?: FieldSchemas; values?: unknown }\n\t// Private to this boundary: callers cannot mutate a shared empty validator.\n\tconst getEmptyDtoExtension = memoize(() => z.strictObject({}))\n\tconst getReservedDtoFields = memoize(\n\t\t() => new Set<string>(['_id', '_creationTime', 'tenant', '__proto__', ...TIMESTAMP_FIELDS]),\n\t)\n\n\tfunction dto(): typeof derived.publicDto\n\tfunction dto<const IncludeId extends boolean>(\n\t\tincludeId: IncludeId,\n\t): DtoSchema<Table, Public, IncludeId>\n\tfunction dto<const IncludeId extends boolean = false>(\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): DtoSchema<Table, Public, IncludeId>\n\tfunction dto<const IncludeId extends boolean = false, const Extension extends FieldSchemas = {}>(\n\t\toptions: DtoOptions<IncludeId, Extension> & { extend?: DtoExtension<Public, Extension> },\n\t): DtoSchema<Table, Public, IncludeId, Extension>\n\tfunction dto(options?: boolean | RuntimeOptions) {\n\t\treturn deriveDto(options)\n\t}\n\n\tfunction deriveDto(options?: boolean | RuntimeOptions) {\n\t\tconst normalized = options === true || options === false ? { _id: options } : options\n\t\tconst extension = normalized?.extend ?? {}\n\t\tassertDtoExtension(extension)\n\t\tif (!normalized?._id && Object.keys(extension).length === 0) return derived.publicDto\n\t\tconst resultSchema = z.strictObject({ ...derived.publicDto.shape, ...extension })\n\t\treturn normalized?._id ? resultSchema.extend({ _id: derived.schema.shape._id }) : resultSchema\n\t}\n\n\tfunction assertDtoExtension(extension: FieldSchemas) {\n\t\tfor (const key of Object.keys(extension)) {\n\t\t\tif (getReservedDtoFields().has(key) || Object.hasOwn(derived.publicDto.shape, key)) {\n\t\t\t\tthrow new Error(`DTO extension collision for field \"${key}\" on table \"${tableName}\"`)\n\t\t\t}\n\t\t\tassertDtoValidationSchema(extension[key])\n\t\t}\n\t}\n\n\tfunction toPublicDto(row: Row): z.output<typeof derived.publicDto>\n\tfunction toPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\tfunction toPublicDto<const IncludeId extends boolean = false>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\toptions: DtoProjectionOptions<IncludeId>,\n\t): z.output<DtoSchema<Table, Public, IncludeId>>\n\tfunction toPublicDto<\n\t\tconst IncludeId extends boolean = false,\n\t\tconst Extension extends FieldSchemas = {},\n\t>(\n\t\trow: DtoRow<Row, IncludeId>,\n\t\toptions: DtoOptions<IncludeId, Extension> & {\n\t\t\textend?: DtoExtension<Public, Extension>\n\t\t} & DtoValues<Extension>,\n\t): z.output<DtoSchema<Table, Public, IncludeId, Extension>>\n\tfunction toPublicDto(row: Row, options?: boolean | RuntimeOptions): RuntimeDto {\n\t\tconst normalized = options === true || options === false ? { _id: options } : options\n\t\t// Enforce extension collisions and validation-only schemas before parsing values.\n\t\tassertDtoExtension(normalized?.extend ?? {})\n\t\tconst projected = derived.publicDto.parse(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.keys(derived.publicDto.shape).map((key) => {\n\t\t\t\t\t// SAFETY: derived.publicDto contains only keys selected from the storage fields.\n\t\t\t\t\treturn [key, row[key as keyof typeof row]]\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t\tconst extensionFields = normalized?.extend\n\t\tconst extensionSchema =\n\t\t\textensionFields == null ? getEmptyDtoExtension() : z.strictObject(extensionFields)\n\t\tconst extension = extensionSchema.parse(normalized?.values ?? {})\n\t\tconst result: RuntimeDto = { ...projected, ...extension }\n\t\tif (normalized?._id) {\n\t\t\tresult._id = derived.schema.shape._id.parse('_id' in row ? row._id : undefined)\n\t\t}\n\t\treturn result\n\t}\n\n\ttype InsertSchema = typeof derived.insertSchema\n\ttype UpdateSchema = typeof derived.updateSchema\n\ttype InsertMask = z.util.Mask<keyof InsertSchema['shape']>\n\ttype UpdateMask = z.util.Mask<keyof UpdateSchema['shape']>\n\n\tfunction insert(): InsertSchema\n\tfunction insert<OmitMask extends InsertMask>(\n\t\tomit: OmitMask,\n\t): ZodObjectOmit<InsertSchema, OmitMask>\n\tfunction insert(omit?: InsertMask) {\n\t\t// SAFETY: InsertMask contains only derived.insertSchema keys; the overload retains Zod's exact mask relationship.\n\t\treturn omit ? derived.insertSchema.omit(omit as never) : derived.insertSchema\n\t}\n\n\tfunction update(): UpdateSchema\n\tfunction update<OmitMask extends UpdateMask>(\n\t\tomit: OmitMask,\n\t): ZodObjectOmit<UpdateSchema, OmitMask>\n\tfunction update(omit?: UpdateMask) {\n\t\t// SAFETY: UpdateMask contains only derived.updateSchema keys; the overload retains Zod's exact mask relationship.\n\t\treturn omit ? derived.updateSchema.omit(omit as never) : derived.updateSchema\n\t}\n\n\tconst nativeStorage = zodToConvex(storage)\n\tconst table: TableDefinition<ConvexValidatorFromZod<typeof storage, 'required'>> =\n\t\tdefineTable(nativeStorage)\n\t// The public shape is mutable. Reconvert its fields on each call so subsequent\n\t// pagination validators observe replacements and nested schema changes.\n\tconst getPaginationFields = () =>\n\t\tObject.fromEntries(\n\t\t\tObject.entries(derived.schema.shape).map(([key, field]) => [key, zodToConvex(field)]),\n\t\t)\n\ttype EntityFields = Fields & TimestampFields & SystemFields<Table>\n\tfunction paginationOpts<const Selection extends ScalarSelection<EntityFields>>(\n\t\tselection: ExactScalarSelection<EntityFields, Selection>,\n\t\toptions?: PaginationValidatorOptions,\n\t): ScalarPaginationSchema<EntityFields, Selection> {\n\t\treturn scalarPaginationSchema<EntityFields, Selection>(\n\t\t\tgetPaginationFields(),\n\t\t\tselection,\n\t\t\toptions,\n\t\t)\n\t}\n\tconst getTools = memoize(() => ({\n\t\t// jsonSafeZid (not zid): tool masks feed generated JSON schemas, so\n\t\t// ids must present as plain strings while keeping the Id<...> type.\n\t\tinsert: derived.commandInput,\n\t\tupdate: z.strictObject({\n\t\t\tdata: z.strictObject({ ...getCommandFields() }).partial(),\n\t\t\tid: jsonSafeZid(tableName),\n\t\t}),\n\t\tid: z.strictObject({ id: jsonSafeZid(tableName) }),\n\t}))\n\n\treturn {\n\t\ttableName,\n\t\tget schema() {\n\t\t\treturn derived.schema\n\t\t},\n\t\tset schema(value: ReturnType<typeof getSchema>) {\n\t\t\treplaceBoundaryValue(this, 'schema', value)\n\t\t},\n\t\tstorage,\n\t\tget insertSchema() {\n\t\t\treturn derived.insertSchema\n\t\t},\n\t\tset insertSchema(value: ReturnType<typeof getInsertSchema>) {\n\t\t\treplaceBoundaryValue(this, 'insertSchema', value)\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn derived.updateSchema\n\t\t},\n\t\tset updateSchema(value: ReturnType<typeof getUpdateSchema>) {\n\t\t\treplaceBoundaryValue(this, 'updateSchema', value)\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn derived.commandInput\n\t\t},\n\t\tset commandInput(value: ReturnType<typeof getCommandInput>) {\n\t\t\treplaceBoundaryValue(this, 'commandInput', value)\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn derived.publicDto\n\t\t},\n\t\tset publicDto(value: ReturnType<typeof getPublicDto>) {\n\t\t\treplaceBoundaryValue(this, 'publicDto', value)\n\t\t},\n\t\tdto,\n\t\ttoPublicDto,\n\t\tpaginationOpts,\n\t\ttable,\n\t\tinsert,\n\t\tupdate,\n\t\tget tools() {\n\t\t\treturn getTools()\n\t\t},\n\t\tset tools(value: ReturnType<typeof getTools>) {\n\t\t\treplaceBoundaryValue(this, 'tools', value)\n\t\t},\n\t}\n}\n\n/** Reuses ordinary fields while deriving every boundary through zodTable. */\nexport function createTable<Shared extends FieldSchemas>(shared: Shared & OwnedFields<Shared>) {\n\tassertOwnedFields(shared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\treturn function customTable<\n\t\tTable extends string,\n\t\tFields extends FieldSchemas,\n\t\tconst ServerFields extends readonly FieldKey<Shared & Fields>[] = readonly [],\n\t\tconst CommandFields extends readonly FieldKey<Shared & Fields>[] = readonly [],\n\t\tconst PublicFields extends readonly FieldKey<Shared & Fields & TimestampFields>[] = readonly [],\n\t>(\n\t\ttableName: Table,\n\t\tfields: (id: typeof zid) => Fields &\n\t\t\tOwnedFields<Fields> & {\n\t\t\t\t[Key in keyof Fields]: Key extends (string extends keyof Shared ? never : keyof Shared)\n\t\t\t\t\t? never\n\t\t\t\t\t: Fields[Key]\n\t\t\t},\n\t\toptions: TableBoundaryOptions<Shared & Fields, ServerFields, CommandFields, PublicFields> = {},\n\t): TableBoundary<Table, Shared & Fields, ServerFields, CommandFields, PublicFields> {\n\t\treturn zodTable<Table, Shared & Fields, ServerFields, CommandFields, PublicFields>(\n\t\t\ttableName,\n\t\t\t(id) => {\n\t\t\t\tconst declared = fields(id)\n\t\t\t\tfor (const key of Object.keys(declared)) {\n\t\t\t\t\tif (Object.hasOwn(shared, key))\n\t\t\t\t\t\tthrow new Error(`Duplicate shared table field \"${key}\" on table \"${tableName}\"`)\n\t\t\t\t}\n\t\t\t\tassertOwnedFields(declared, ['_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\t\t\t\tconst combined: Shared & Fields = { ...shared, ...declared }\n\t\t\t\t// SAFETY: duplicates and reserved keys are rejected before merging; like\n\t\t\t\t// tenantTable, this wrapper forwards the unchanged validators to zodTable.\n\t\t\t\treturn combined as Shared & Fields & OwnedFields<Shared & Fields>\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t}\n}\n\nconst tenantFields = {\n\ttenant: z.string().min(1),\n} satisfies FieldSchemas\n\ntype TenantFields = typeof tenantFields\n\n/**\n * A zodTable whose rows are tenant-owned: injects the server-owned `tenant`\n * field (the tenancy boundary — see cvx-kit/tenancy). Like timestamps, it is\n * excluded from insert/update/command boundaries; handlers stamp it from\n * ctx.tenant, row-level security matches on it, and the tenantOwnership\n * trigger forbids reassigning it. Expose it via publicFields only when a DTO\n * genuinely needs it.\n */\nexport function tenantTable<\n\tTable extends string,\n\tFields extends FieldSchemas,\n\tconst ServerFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst CommandFields extends readonly FieldKey<Fields>[] = readonly [],\n\tconst PublicFields extends readonly FieldKey<Fields & TenantFields & TimestampFields>[] =\n\t\treadonly [],\n>(\n\ttableName: Table,\n\tfields: (\n\t\tid: typeof zid,\n\t) => Fields &\n\t\tOwnedFields<Fields> & { [Key in keyof Fields]: Key extends 'tenant' ? never : Fields[Key] },\n\toptions: TableBoundaryOptions<\n\t\tFields & TenantFields,\n\t\treadonly (ServerFields[number] | 'tenant')[],\n\t\tCommandFields,\n\t\tPublicFields\n\t> = {},\n) {\n\treturn zodTable<\n\t\tTable,\n\t\tFields & TenantFields,\n\t\treadonly (ServerFields[number] | 'tenant')[],\n\t\tCommandFields,\n\t\tPublicFields\n\t>(\n\t\ttableName,\n\t\t(id) => {\n\t\t\tconst declared = fields(id)\n\t\t\tassertOwnedFields(declared, ['tenant', '_id', '_creationTime', ...TIMESTAMP_FIELDS])\n\t\t\t// SAFETY: reserved keys were rejected before injecting tenant; the generic\n\t\t\t// wrapper forwards the same checked fields to the ordinary table constructor.\n\t\t\treturn { ...declared, ...tenantFields } as Fields &\n\t\t\t\tTenantFields &\n\t\t\t\tOwnedFields<Fields & TenantFields>\n\t\t},\n\t\t{\n\t\t\t...options,\n\t\t\tserverFields: [...(options.serverFields ?? []), 'tenant'],\n\t\t},\n\t)\n}\n\n/**\n * Merges per-module table maps into the application schema map, rejecting\n * duplicate table names across modules — the module-registry combinator for\n * domain/table.ts: `defineSchema(createModule(catalogTables, salesTables))`.\n * Accepts plain maps and `namespace(...)` maps side by side; namespaces add\n * no keys, so the result is the same flat `{ tableName: TableDefinition }`.\n */\nexport function createModule<const Maps extends readonly Record<string, TableDefinition<any>>[]>(\n\t...maps: Maps\n): FlatTables<UnionToIntersection<Maps[number]>> {\n\tconst combined: Record<string, TableDefinition<any>> = {}\n\tconst namespaceNames = new Set<string>()\n\tfor (const map of maps) {\n\t\tconst meta = namespaceMeta(map)\n\t\tif (meta) {\n\t\t\tif (namespaceNames.has(meta.name)) {\n\t\t\t\tthrow new Error(`Namespace \"${meta.name}\" is declared more than once`)\n\t\t\t}\n\t\t\tnamespaceNames.add(meta.name)\n\t\t}\n\t\tfor (const [tableName, definition] of Object.entries(map)) {\n\t\t\tif (tableName in combined) {\n\t\t\t\tthrow new Error(`Table \"${tableName}\" is declared by more than one module`)\n\t\t\t}\n\t\t\tcombined[tableName] = definition\n\t\t}\n\t}\n\t// SAFETY: every string-keyed input entry is copied, and duplicate keys are rejected above.\n\treturn combined as FlatTables<UnionToIntersection<Maps[number]>>\n}\n\ntype FlatTables<Map> = { [Key in keyof Map as Key extends string ? Key : never]: Map[Key] }\n\nconst namespaceKey: unique symbol = Symbol.for('cvx-kit/zod-table/namespace')\n\n/** Declaration-level metadata carried by a `namespace(...)` table map. */\nexport type NamespaceInfo<Name extends string, Tables extends string> = {\n\treadonly name: Name\n\treadonly tables: readonly Tables[]\n}\n\n/**\n * A table map tagged with a namespace. It is still a plain\n * `{ tableName: TableDefinition }` map (the tag is a non-enumerable symbol),\n * so `createModule`/`defineSchema` see exactly the tables they saw before.\n */\nexport type Namespace<\n\tName extends string,\n\tTables extends Record<string, TableDefinition<any>>,\n> = Tables & NamespaceTag<Name, keyof Tables & string>\n\n/** The metadata-only shape of a `namespace(...)` map. */\nexport type NamespaceTag<Name extends string, Tables extends string> = {\n\treadonly [namespaceKey]: NamespaceInfo<Name, Tables>\n}\n\ntype DotsToUnderscores<Name extends string> = Name extends `${infer Head}.${infer Tail}`\n\t? `${Head}_${DotsToUnderscores<Tail>}`\n\t: Name\n\n/** Stored-table prefix of a namespace: `Microsoft.Inventory` → `Microsoft_Inventory_`. */\nexport type NamespacePrefix<Name extends string> = `${DotsToUnderscores<Name>}_`\n\n/**\n * Member name of a table. A table stored with its namespace prefix drops it\n * (`Inventory_Items` in `Inventory` → `Items`); any other table name is\n * PascalCased (`itemLedgerEntries` → `ItemLedgerEntries`).\n */\nexport type MemberName<\n\tTableName extends string,\n\tName extends string = never,\n> = [Name] extends [never]\n\t? Capitalize<TableName>\n\t: TableName extends `${NamespacePrefix<Name>}${infer Rest extends string}`\n\t\t? Rest extends ''\n\t\t\t? Capitalize<TableName>\n\t\t\t: Rest\n\t\t: Capitalize<TableName>\n\n/** Fully qualified name: `<Namespace>.<Member>`, e.g. `Inventory.Items`. */\nexport type QualifiedName<\n\tName extends string,\n\tTableName extends string,\n> = `${Name}.${MemberName<TableName, Name>}`\n\n/** Options for `namespace(...)`. */\nexport type NamespaceOptions<Prefixed extends boolean = boolean> = {\n\t/** Require every key to start with the namespace prefix (`Inventory_`). */\n\tprefixed?: Prefixed\n}\n\ntype NamespaceMember = TableDefinition<any> | { tableName: string; table: TableDefinition<any> }\ntype MemberTables<Members extends Record<string, NamespaceMember>> = {\n\t[Key in keyof Members]: Members[Key] extends { table: infer Table extends TableDefinition<any> }\n\t\t? Table\n\t\t: Extract<Members[Key], TableDefinition<any>>\n}\ntype CheckedMembers<\n\tMembers extends Record<string, NamespaceMember>,\n\tName extends string,\n\tPrefixed extends boolean,\n> = {\n\t[Key in keyof Members]: Prefixed extends true\n\t\t? Key extends `${NamespacePrefix<Name>}${infer Rest}`\n\t\t\t? Rest extends ''\n\t\t\t\t? never\n\t\t\t\t: CheckedMember<Members[Key], Key>\n\t\t\t: never\n\t\t: CheckedMember<Members[Key], Key>\n}\ntype CheckedMember<Member, Key> = Member extends { tableName: infer TableName }\n\t? TableName extends Key\n\t\t? Member\n\t\t: { tableName: Key; table: TableDefinition<any> }\n\t: Member\ntype CheckedNamespaceName<Name extends string> = Name extends ''\n\t? never\n\t: Name extends `${string}..${string}` | `.${string}` | `${string}.`\n\t\t? never\n\t\t: Name\n\nconst NAMESPACE_SEGMENT = /^[A-Z][A-Za-z0-9]*$/\n// Convex table names: letters, digits and underscores, not starting with an underscore.\nconst TABLE_NAME = /^[A-Za-z][A-Za-z0-9_]*$/\n\n/**\n * Groups tables under a declaration-level namespace, like AL's\n * `namespace Microsoft.Inventory.Item;`. Keys are the real (stored) table\n * names, exactly as in an un-namespaced module map. A key stored with the\n * namespace prefix (`Inventory_Items`, or `Microsoft_Inventory_Items` for\n * `Microsoft.Inventory`) has the remainder as its member name (`Items`);\n * any other key is PascalCased (`items` → `Items`). The qualified name is\n * `<Namespace>.<Member>` (`Inventory.Items`). Storage, ids, queries and\n * generated types are unchanged.\n *\n * `{ prefixed: true }` requires every key to carry the prefix: a key\n * without it is a type error and a runtime error.\n *\n * A member may be a `TableDefinition` (`items.table.index(...)`) or a table\n * boundary (`items`); a boundary whose `tableName` differs from its key is a\n * type error and a runtime error. Dotted names (`Microsoft.Inventory`) are\n * allowed; each segment must be PascalCase.\n */\nexport function namespace<\n\tconst Name extends string,\n\tconst Members extends Record<string, NamespaceMember>,\n\tconst Prefixed extends boolean = false,\n>(\n\tname: Name & CheckedNamespaceName<Name>,\n\tmembers: Members & CheckedMembers<Members, Name, Prefixed>,\n\toptions: NamespaceOptions<Prefixed> = {},\n): Namespace<Name, MemberTables<Members>> {\n\tif (!name.split('.').every((segment) => NAMESPACE_SEGMENT.test(segment))) {\n\t\tthrow new Error(\n\t\t\t`Namespace \"${name}\" must be dot-separated PascalCase segments (e.g. \"Microsoft.Inventory\")`,\n\t\t)\n\t}\n\tconst tables: Record<string, TableDefinition<any>> = {}\n\tfor (const [key, member] of Object.entries(members as Record<string, NamespaceMember>)) {\n\t\tif (!TABLE_NAME.test(key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Namespace \"${name}\" member \"${key}\" must be a table name (letters, digits and underscores)`,\n\t\t\t)\n\t\t}\n\t\tif (options.prefixed && !hasPrefix(key, name)) {\n\t\t\tthrow new Error(\n\t\t\t\t`Namespace \"${name}\" member \"${key}\" must start with \"${namespacePrefix(name)}\"`,\n\t\t\t)\n\t\t}\n\t\tif ('tableName' in member) {\n\t\t\tif (member.tableName !== key) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Namespace \"${name}\" member \"${key}\" holds table \"${member.tableName}\"; keys must be the table name`,\n\t\t\t\t)\n\t\t\t}\n\t\t\ttables[key] = member.table\n\t\t} else {\n\t\t\ttables[key] = member\n\t\t}\n\t}\n\tObject.defineProperty(tables, namespaceKey, {\n\t\tvalue: Object.freeze({ name, tables: Object.freeze(Object.keys(tables)) }),\n\t\tenumerable: false,\n\t})\n\t// SAFETY: tables holds one TableDefinition per member key plus the symbol tag.\n\treturn tables as Namespace<Name, MemberTables<Members>>\n}\n\nfunction namespaceMeta(map: object): NamespaceInfo<string, string> | undefined {\n\treturn (map as { [namespaceKey]?: NamespaceInfo<string, string> })[namespaceKey]\n}\n\n/** Stored-table prefix of a namespace: `Microsoft.Inventory` → `Microsoft_Inventory_`. */\nexport function namespacePrefix<const Name extends string>(name: Name) {\n\treturn `${name.replaceAll('.', '_')}_` as NamespacePrefix<Name>\n}\n\nfunction hasPrefix(tableName: string, name: string) {\n\tconst prefix = namespacePrefix(name)\n\treturn tableName.startsWith(prefix) && tableName.length > prefix.length\n}\n\n/**\n * Member name of a table name: without the namespace prefix when given and\n * present (`memberName('Inventory_Items', 'Inventory')` → `Items`), else PascalCased.\n */\nexport function memberName<const TableName extends string, const Name extends string = never>(\n\ttableName: TableName,\n\tnamespaceName?: Name,\n) {\n\tconst name =\n\t\tnamespaceName !== undefined && hasPrefix(tableName, namespaceName)\n\t\t\t? tableName.slice(namespacePrefix(namespaceName).length)\n\t\t\t: tableName.charAt(0).toUpperCase() + tableName.slice(1)\n\treturn name as MemberName<TableName, Name>\n}\n\n/** The namespace name of a `namespace(...)` map. */\nexport function namespaceName<const Name extends string>(ns: NamespaceTag<Name, string>): Name {\n\treturn namespaceMeta(ns)!.name as Name\n}\n\n/** The stored table names declared in a namespace, in declaration order. */\nexport function tablesOf<const Tables extends string>(\n\tns: NamespaceTag<string, Tables>,\n): readonly Tables[] {\n\treturn namespaceMeta(ns)!.tables as readonly Tables[]\n}\n\ntype NamespaceEntries<Spaces extends readonly NamespaceTag<string, string>[]> = {\n\t[Index in keyof Spaces]: Spaces[Index] extends NamespaceTag<infer Name, infer Tables>\n\t\t? { [TableName in Tables]: Name }\n\t\t: never\n}[number]\ntype TableNamespaceMap<Spaces extends readonly NamespaceTag<string, string>[]> =\n\tUnionToIntersection<NamespaceEntries<Spaces>>\n\n/**\n * Typed, read-only qualified-name lookup over namespaces (no global registry:\n * build one next to `createModule` and import it where labels are needed).\n * Rejects duplicate namespace names and tables claimed by two namespaces.\n */\nexport function namespaceIndex<const Spaces extends readonly NamespaceTag<string, string>[]>(\n\t...spaces: Spaces\n) {\n\ttype Map = TableNamespaceMap<Spaces>\n\ttype TableName = keyof Map & string\n\ttype NameOf = Spaces[number] extends NamespaceTag<infer Name, string> ? Name : never\n\tconst byTable = new Map<string, string>()\n\tconst byName = new Map<string, readonly string[]>()\n\tfor (const space of spaces) {\n\t\tconst meta = namespaceMeta(space)\n\t\tif (!meta) throw new Error('namespaceIndex accepts only namespace(...) maps')\n\t\tif (byName.has(meta.name)) {\n\t\t\tthrow new Error(`Namespace \"${meta.name}\" is declared more than once`)\n\t\t}\n\t\tbyName.set(meta.name, meta.tables)\n\t\tfor (const table of meta.tables) {\n\t\t\tconst owner = byTable.get(table)\n\t\t\tif (owner) {\n\t\t\t\tthrow new Error(`Table \"${table}\" is declared by namespaces \"${owner}\" and \"${meta.name}\"`)\n\t\t\t}\n\t\t\tbyTable.set(table, meta.name)\n\t\t}\n\t}\n\tconst owner = (table: string) => {\n\t\tconst name = byTable.get(table)\n\t\tif (name === undefined) throw new Error(`Table \"${table}\" is not in a namespace`)\n\t\treturn name\n\t}\n\treturn {\n\t\tqualifiedName<const Table extends TableName>(table: Table) {\n\t\t\tconst name = owner(table)\n\t\t\treturn `${name}.${memberName(table, name)}` as {\n\t\t\t\t[Key in Table]: QualifiedName<Map[Key] & string, Key>\n\t\t\t}[Table]\n\t\t},\n\t\tnamespaceOf<const Table extends TableName>(table: Table) {\n\t\t\treturn owner(table) as Map[Table]\n\t\t},\n\t\tmemberName,\n\t\ttablesOf<const Name extends NameOf>(name: Name) {\n\t\t\tconst tables = byName.get(name)\n\t\t\tif (!tables) throw new Error(`Namespace \"${name}\" is not indexed`)\n\t\t\treturn tables as readonly {\n\t\t\t\t[Table in TableName]: Map[Table] extends Name ? Table : never\n\t\t\t}[TableName][]\n\t\t},\n\t\tnamespaces: [...byName.keys()] as readonly string[] as readonly NameOf[],\n\t\thas(table: string): table is TableName {\n\t\t\treturn byTable.has(table)\n\t\t},\n\t}\n}\n\ntype UnionToIntersection<Union> = (\n\tUnion extends unknown ? (member: Union) => void : never\n) extends (member: infer Intersection) => void\n\t? Intersection\n\t: never\n\n/**\n * Cursor-pagination boundary schemas bridged from Convex's own validators:\n * `args.paginationOpts` for function args, `result` for the page shape.\n * Pair with `include(...).paginate(opts)` (cvx-kit/auth). The result object\n * is deliberately non-strict — Convex may attach engine fields (splitCursor,\n * pageStatus); the page items themselves are validated against the dto.\n * Note: under row-level security, pages may be SHORTER than numItems when\n * rules reject rows mid-page; cursors remain correct.\n */\n/** Completeness of the requested page, independently of global isDone exhaustion. */\nexport type PageCompleteness =\n\t| 'complete'\n\t| 'row-budget'\n\t| 'byte-budget'\n\t| 'native-limit'\n\t| 'result-cap'\nexport type EnginePaginationResult<Row> = PaginationResult<Row> & {\n\tpaginationMode?: 'native-search'\n\tcompleteness?: PageCompleteness\n}\n\nexport function paginated<Dto extends z.ZodType>(dto: Dto) {\n\treturn {\n\t\targs: { paginationOpts: convexToZod(paginationOptsValidator) },\n\t\tresult: pageResult(dto),\n\t}\n}\n\ntype VariantSchema = z.ZodDiscriminatedUnion<readonly StrictObject<FieldSchemas>[], string>\ntype VariantDiscriminator<Schema extends VariantSchema> = Schema['_zod']['def']['discriminator']\ntype VariantTags<Schema extends VariantSchema> = Extract<\n\tz.output<Schema>[VariantDiscriminator<Schema>],\n\tstring\n>\ntype VariantBranch<Schema extends VariantSchema, Tag extends string> = Extract<\n\tSchema['options'][number],\n\tz.ZodObject<{ [Key in VariantDiscriminator<Schema>]: z.ZodLiteral<Tag> }, z.core.$strict>\n>\ntype VariantKeys<Schema extends VariantSchema, Tag extends string> = FieldKey<\n\tVariantBranch<Schema, Tag>['shape']\n>\n\n/** Boundary mode supports strict object branches with one string literal tag each. */\nexport type VariantBoundaryOptions<Schema extends VariantSchema> = {\n\tdiscriminator: VariantDiscriminator<Schema>\n\ttimestamps?: boolean\n\tvariants: {\n\t\t[Tag in VariantTags<Schema>]: {\n\t\t\tserverFields?: readonly Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>[]\n\t\t\tcommandFields?: readonly Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>[]\n\t\t\tpublicFields?: readonly (\n\t\t\t\t| Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>\n\t\t\t\t| keyof TimestampFields\n\t\t\t)[]\n\t\t}\n\t}\n}\ntype VariantMaskKeys<Config, Mask extends string> = Config extends {\n\t[Key in Mask]?: readonly (infer Field)[]\n}\n\t? Extract<Field, string>\n\t: never\ntype CheckedVariantOptions<\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n> = {\n\tvariants: {\n\t\t[Tag in keyof Options['variants']]: Tag extends VariantTags<Schema>\n\t\t\t? {\n\t\t\t\t\tcommandFields?: readonly Exclude<\n\t\t\t\t\t\tVariantKeys<Schema, Tag>,\n\t\t\t\t\t\tVariantDiscriminator<Schema> | VariantMaskKeys<Options['variants'][Tag], 'serverFields'>\n\t\t\t\t\t>[]\n\t\t\t\t\tpublicFields?: readonly (\n\t\t\t\t\t\t| Exclude<VariantKeys<Schema, Tag>, VariantDiscriminator<Schema>>\n\t\t\t\t\t\t| (Options extends { timestamps: true } ? keyof TimestampFields : never)\n\t\t\t\t\t)[]\n\t\t\t\t}\n\t\t\t: never\n\t}\n}\ntype VariantMode =\n\t| 'storage'\n\t| 'document'\n\t| 'insert'\n\t| 'update'\n\t| 'command'\n\t| 'commandUpdate'\n\t| 'public'\ntype VariantFields<\n\tTable extends string,\n\tBranch extends StrictObject<FieldSchemas>,\n\tDiscriminator extends string,\n\tConfig,\n\tTimestamps extends boolean,\n\tMode extends VariantMode,\n> = Mode extends 'storage'\n\t? Branch['shape'] & (true extends Timestamps ? TimestampFields : {})\n\t: Mode extends 'document'\n\t\t? VariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'> &\n\t\t\t\tSystemFields<Table>\n\t\t: Mode extends 'public' | 'command'\n\t\t\t? Pick<\n\t\t\t\t\tVariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'>,\n\t\t\t\t\tExtract<\n\t\t\t\t\t\t| Discriminator\n\t\t\t\t\t\t| VariantMaskKeys<Config, Mode extends 'public' ? 'publicFields' : 'commandFields'>,\n\t\t\t\t\t\tkeyof VariantFields<Table, Branch, Discriminator, Config, Timestamps, 'storage'>\n\t\t\t\t\t>\n\t\t\t\t>\n\t\t\t: Mode extends 'insert'\n\t\t\t\t? Omit<Branch['shape'], VariantMaskKeys<Config, 'serverFields'>>\n\t\t\t\t: PartialFields<\n\t\t\t\t\t\tOmit<\n\t\t\t\t\t\t\tVariantFields<\n\t\t\t\t\t\t\t\tTable,\n\t\t\t\t\t\t\t\tBranch,\n\t\t\t\t\t\t\t\tDiscriminator,\n\t\t\t\t\t\t\t\tConfig,\n\t\t\t\t\t\t\t\tTimestamps,\n\t\t\t\t\t\t\t\tMode extends 'update' ? 'insert' : 'command'\n\t\t\t\t\t\t\t>,\n\t\t\t\t\t\t\tDiscriminator\n\t\t\t\t\t\t>\n\t\t\t\t\t> &\n\t\t\t\t\t\tPick<Branch['shape'], Extract<Discriminator, keyof Branch['shape']>>\ntype DerivedVariantBranches<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n\tMode extends VariantMode,\n\tIncludeId extends boolean,\n\tBranches extends readonly StrictObject<FieldSchemas>[],\n> = {\n\t[Index in keyof Branches]: Branches[Index] extends StrictObject<FieldSchemas>\n\t\t? StrictObject<\n\t\t\t\tVariantFields<\n\t\t\t\t\tTable,\n\t\t\t\t\tBranches[Index],\n\t\t\t\t\tVariantDiscriminator<Schema>,\n\t\t\t\t\tOptions['variants'][Extract<\n\t\t\t\t\t\tz.output<Branches[Index]>[VariantDiscriminator<Schema>],\n\t\t\t\t\t\tkeyof Options['variants']\n\t\t\t\t\t>],\n\t\t\t\t\tOptions extends { timestamps: infer Enabled }\n\t\t\t\t\t\t? true extends Enabled\n\t\t\t\t\t\t\t? true\n\t\t\t\t\t\t\t: false\n\t\t\t\t\t\t: false,\n\t\t\t\t\tMode\n\t\t\t\t> &\n\t\t\t\t\t(IncludeId extends true ? { _id: Zid<Table> } : {})\n\t\t\t>\n\t\t: never\n}\ntype DerivedVariant<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n\tMode extends VariantMode,\n\tIncludeId extends boolean = false,\n> = IncludeId extends true\n\t? z.ZodDiscriminatedUnion<\n\t\t\tDerivedVariantBranches<Table, Schema, Options, Mode, true, Schema['options']>,\n\t\t\tVariantDiscriminator<Schema>\n\t\t>\n\t: z.ZodDiscriminatedUnion<\n\t\t\tDerivedVariantBranches<Table, Schema, Options, Mode, false, Schema['options']>,\n\t\t\tVariantDiscriminator<Schema>\n\t\t>\n\nexport type VariantTableBoundary<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tOptions extends VariantBoundaryOptions<Schema>,\n> = {\n\ttableName: Table\n\tstorage: DerivedVariant<Table, Schema, Options, 'storage'>\n\tschema: DerivedVariant<Table, Schema, Options, 'document'>\n\tinsertSchema: DerivedVariant<Table, Schema, Options, 'insert'>\n\tupdateSchema: DerivedVariant<Table, Schema, Options, 'update'>\n\tcommandInput: DerivedVariant<Table, Schema, Options, 'command'>\n\tpublicDto: DerivedVariant<Table, Schema, Options, 'public'>\n\ttable: TableDefinition<\n\t\tConvexValidatorFromZod<DerivedVariant<Table, Schema, Options, 'storage'>, 'required'>\n\t>\n\tdto(): DerivedVariant<Table, Schema, Options, 'public'>\n\tdto<const IncludeId extends boolean>(\n\t\tincludeId: IncludeId,\n\t): DerivedVariant<Table, Schema, Options, 'public', IncludeId>\n\ttoPublicDto(\n\t\trow: z.input<DerivedVariant<Table, Schema, Options, 'storage'>>,\n\t): z.output<DerivedVariant<Table, Schema, Options, 'public'>>\n\ttoPublicDto<const IncludeId extends boolean>(\n\t\trow: DtoRow<z.input<DerivedVariant<Table, Schema, Options, 'storage'>>, IncludeId>,\n\t\tincludeId: IncludeId,\n\t): z.output<DerivedVariant<Table, Schema, Options, 'public', IncludeId>>\n\ttools: {\n\t\tid: StrictObject<{ id: z.ZodType<GenericId<Table>, string> }>\n\t\tinsert: z.ZodType<\n\t\t\tz.output<DerivedVariant<Table, Schema, Options, 'command'>>,\n\t\t\tz.input<DerivedVariant<Table, Schema, Options, 'command'>>\n\t\t>\n\t\tupdate: StrictObject<{\n\t\t\tid: z.ZodType<GenericId<Table>, string>\n\t\t\tdata: z.ZodType<\n\t\t\t\tz.output<DerivedVariant<Table, Schema, Options, 'commandUpdate'>>,\n\t\t\t\tz.input<DerivedVariant<Table, Schema, Options, 'commandUpdate'>>\n\t\t\t>\n\t\t}>\n\t}\n}\n\n/** Legacy mode preserves arbitrary storage; the third argument opts into derived boundaries. */\nexport function zodVariantTable<Table extends string, Schema extends z.ZodType>(\n\ttableName: Table,\n\tstorage: Schema,\n): {\n\ttableName: Table\n\tstorage: Schema\n\tinsertSchema: Schema\n\ttable: TableDefinition<ConvexValidatorFromZod<Schema, 'required'>>\n}\nexport function zodVariantTable<\n\tTable extends string,\n\tSchema extends VariantSchema,\n\tconst Options extends VariantBoundaryOptions<Schema>,\n>(\n\ttableName: Table,\n\tstorage: Schema,\n\toptions: Options & CheckedVariantOptions<Schema, NoInfer<Options>>,\n): VariantTableBoundary<Table, Schema, Options>\nexport function zodVariantTable(\n\ttableName: string,\n\tstorage: z.ZodType,\n\toptions?: {\n\t\tdiscriminator: string\n\t\ttimestamps?: boolean\n\t\tvariants: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tserverFields?: readonly string[]\n\t\t\t\tcommandFields?: readonly string[]\n\t\t\t\tpublicFields?: readonly string[]\n\t\t\t}\n\t\t>\n\t},\n) {\n\tif (options) return deriveVariantTable(tableName, storage, options)\n\treturn {\n\t\ttableName,\n\t\tstorage,\n\t\tinsertSchema: storage,\n\t\ttable: defineTable(zodToConvex(storage)),\n\t}\n}\n\n/**\n * A zid that presents as a plain string in generated JSON schemas so\n * LLM-tool inputs stay primitive, while keeping the Id type at compile time.\n */\nexport function jsonSafeZid<Table extends string>(\n\ttableName: Table,\n): z.ZodType<GenericId<Table>, string> {\n\tconst id = zid(tableName)\n\treturn z\n\t\t.string()\n\t\t.refine((value): value is GenericId<Table> => id.safeParse(value).success)\n\t\t.describe(`Convex document id for table \"${tableName}\"; validated against the table by Convex`)\n}\n\nfunction deriveVariantTable(\n\ttableName: string,\n\tdeclared: z.ZodType,\n\toptions: {\n\t\tdiscriminator: string\n\t\ttimestamps?: boolean\n\t\tvariants: Record<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tserverFields?: readonly string[]\n\t\t\t\tcommandFields?: readonly string[]\n\t\t\t\tpublicFields?: readonly string[]\n\t\t\t}\n\t\t>\n\t},\n) {\n\tif (\n\t\t!(declared instanceof z.ZodDiscriminatedUnion) ||\n\t\tdeclared.def.discriminator !== options.discriminator\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant boundaries require a discriminated union with the configured discriminator',\n\t\t)\n\tif (declared.def.checks?.length)\n\t\tthrow new Error('Variant boundaries do not support union-level refinements')\n\tconst timestamps = options.timestamps\n\tconst discriminator = options.discriminator\n\tif (['_id', '_creationTime', ...TIMESTAMP_FIELDS].includes(discriminator))\n\t\tthrow new Error('Variant discriminator cannot be a reserved field')\n\tconst branches = new Map<\n\t\tstring,\n\t\t{\n\t\t\tstorage: StrictObject<FieldSchemas>\n\t\t\tdocument: StrictObject<FieldSchemas>\n\t\t\tinsert: StrictObject<FieldSchemas>\n\t\t\tupdate: StrictObject<FieldSchemas>\n\t\t\tcommand: StrictObject<FieldSchemas>\n\t\t\tcommandUpdate: StrictObject<FieldSchemas>\n\t\t\ttoolCommand: StrictObject<FieldSchemas>\n\t\t\tpublic: StrictObject<FieldSchemas>\n\t\t}\n\t>()\n\tfor (const branch of declared.options) {\n\t\tif (!(branch instanceof z.ZodObject) || !(branch.def.catchall instanceof z.ZodNever))\n\t\t\tthrow new Error('Variant boundaries require strict object branches')\n\t\tif (branch.def.checks?.length)\n\t\t\tthrow new Error('Variant boundaries do not support object-level refinements')\n\t\ttry {\n\t\t\tassertDtoValidationSchema(branch, new Set(), true)\n\t\t} catch (cause) {\n\t\t\tthrow new Error(\n\t\t\t\t'Variant boundaries require supported value-preserving field validators without object catchalls',\n\t\t\t\t{ cause },\n\t\t\t)\n\t\t}\n\t\tconst tagSchema = branch.shape[discriminator]\n\t\tif (!(tagSchema instanceof z.ZodLiteral) || tagSchema.values.size !== 1)\n\t\t\tthrow new Error('Variant branches require one string literal discriminator')\n\t\tconst tag = [...tagSchema.values][0]\n\t\tif (!z.string().safeParse(tag).success)\n\t\t\tthrow new Error('Variant branches require a string discriminator')\n\t\t// SAFETY: a single literal value was checked as a string above.\n\t\tconst tagValue = tag as string\n\t\tif (branches.has(tagValue)) throw new Error(`Duplicate variant discriminator \"${tagValue}\"`)\n\t\tif (!Object.hasOwn(options.variants, tagValue))\n\t\t\tthrow new Error(`Missing variant configuration \"${tagValue}\"`)\n\t\tconst config = {\n\t\t\tserverFields: [...(options.variants[tagValue].serverFields ?? [])],\n\t\t\tcommandFields: [...(options.variants[tagValue].commandFields ?? [])],\n\t\t\tpublicFields: [...(options.variants[tagValue].publicFields ?? [])],\n\t\t}\n\t\tassertOwnedFields(branch.shape, [\n\t\t\t'_id',\n\t\t\t'_creationTime',\n\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t])\n\t\tconst columns = { ...branch.shape } satisfies FieldSchemas\n\t\tif (timestamps) Object.assign(columns, timestampFields)\n\t\tassertFieldLists(\n\t\t\tcolumns,\n\t\t\tconfig.serverFields ?? [],\n\t\t\tconfig.commandFields ?? [],\n\t\t\tconfig.publicFields ?? [],\n\t\t\ttimestamps !== false,\n\t\t)\n\t\tfor (const mask of [config.serverFields, config.commandFields, config.publicFields]) {\n\t\t\tif (mask?.includes(discriminator))\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'The variant discriminator is retained automatically and cannot appear in masks',\n\t\t\t\t)\n\t\t}\n\t\tfor (const field of config.commandFields) assertVariantToolField(columns[field])\n\t\tconst stored = z.strictObject({ ...columns })\n\t\tconst getInsert = memoize(() =>\n\t\t\tz.strictObject(\n\t\t\t\tomitFields(columns, [\n\t\t\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t\t\t\t...(config.serverFields ?? []),\n\t\t\t\t]),\n\t\t\t),\n\t\t)\n\t\tconst getCommand = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...(config.commandFields ?? [])])),\n\t\t)\n\t\tconst partial = (schema: StrictObject<FieldSchemas>) =>\n\t\t\tschema.partial().extend({ [discriminator]: tagSchema })\n\t\tconst getDocument = memoize(() => documentSchema(columns, tableName))\n\t\tconst getUpdate = memoize(() =>\n\t\t\tpartial(\n\t\t\t\tz.strictObject(\n\t\t\t\t\tomitFields(columns, [\n\t\t\t\t\t\t...(timestamps === false ? [] : TIMESTAMP_FIELDS),\n\t\t\t\t\t\t...config.serverFields,\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\tconst getCommandUpdate = memoize(() =>\n\t\t\tpartial(z.strictObject(pickFields(columns, [discriminator, ...config.commandFields]))),\n\t\t)\n\t\tconst getToolCommand = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...config.commandFields])),\n\t\t)\n\t\tconst getPublic = memoize(() =>\n\t\t\tz.strictObject(pickFields(columns, [discriminator, ...(config.publicFields ?? [])])),\n\t\t)\n\t\tbranches.set(tagValue, {\n\t\t\tstorage: stored,\n\t\t\tget document() {\n\t\t\t\treturn getDocument()\n\t\t\t},\n\t\t\tget insert() {\n\t\t\t\treturn getInsert()\n\t\t\t},\n\t\t\tget update() {\n\t\t\t\treturn getUpdate()\n\t\t\t},\n\t\t\tget command() {\n\t\t\t\treturn getCommand()\n\t\t\t},\n\t\t\tget commandUpdate() {\n\t\t\t\treturn getCommandUpdate()\n\t\t\t},\n\t\t\tget toolCommand() {\n\t\t\t\treturn getToolCommand()\n\t\t\t},\n\t\t\tget public() {\n\t\t\t\treturn getPublic()\n\t\t\t},\n\t\t})\n\t}\n\tfor (const tag of Object.keys(options.variants)) {\n\t\tif (!branches.has(tag)) throw new Error(`Unknown variant configuration \"${tag}\"`)\n\t}\n\tfunction union(mode: VariantMode, includeId = false, tool = false) {\n\t\tconst schemas = [...branches.values()].map((branch) => {\n\t\t\tconst schema = tool && mode === 'command' ? branch.toolCommand : branch[mode]\n\t\t\tif (tool)\n\t\t\t\treturn z.strictObject(\n\t\t\t\t\tObject.fromEntries(\n\t\t\t\t\t\tObject.entries(schema.shape).map(([key, field]) => [key, variantToolField(field)]),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\treturn includeId ? schema.extend({ _id: zid(tableName) }) : schema\n\t\t})\n\t\tif (!schemas.length) throw new Error('Variant boundaries require at least one branch')\n\t\t// SAFETY: all entries are checked strict objects with a unique required literal tag; nonempty checked above.\n\t\treturn z.discriminatedUnion(\n\t\t\tdiscriminator,\n\t\t\tschemas as [StrictObject<FieldSchemas>, ...StrictObject<FieldSchemas>[]],\n\t\t)\n\t}\n\tconst storage = union('storage')\n\tconst getSchema = memoize(() => union('document'))\n\tconst getInsertSchema = memoize(() => union('insert'))\n\tconst getUpdateSchema = memoize(() => union('update'))\n\tconst getCommandInput = memoize(() => union('command'))\n\tconst getPublicDto = memoize(() => union('public'))\n\tfunction dto(includeId = false) {\n\t\treturn includeId ? union('public', true) : getPublicDto()\n\t}\n\t// Projection-only ID schema is never returned by dto() or exposed on the declaration.\n\tlet projectionId: Zid<string> | undefined\n\tfunction toPublicDto(row: z.input<StrictObject<FieldSchemas>>, includeId = false) {\n\t\tconst tag = z.string().parse(row[discriminator])\n\t\tconst branch = branches.get(tag)\n\t\tif (!branch) throw new Error(`Unknown variant discriminator \"${tag}\"`)\n\t\tconst projection = includeId\n\t\t\t? branch.public.extend({ _id: (projectionId ??= zid(tableName)) })\n\t\t\t: branch.public\n\t\treturn projection.parse(\n\t\t\tObject.fromEntries(\n\t\t\t\tObject.keys(projection.shape)\n\t\t\t\t\t.filter((key) => Object.hasOwn(row, key))\n\t\t\t\t\t.map((key) => [key, row[key]]),\n\t\t\t),\n\t\t)\n\t}\n\tconst getTools = memoize(() => ({\n\t\tid: z.strictObject({ id: jsonSafeZid(tableName) }),\n\t\tinsert: union('command', false, true),\n\t\tupdate: z.strictObject({\n\t\t\tid: jsonSafeZid(tableName),\n\t\t\tdata: union('commandUpdate', false, true),\n\t\t}),\n\t}))\n\n\treturn {\n\t\ttableName,\n\t\tstorage,\n\t\tget schema() {\n\t\t\treturn getSchema()\n\t\t},\n\t\tset schema(value: ReturnType<typeof getSchema>) {\n\t\t\treplaceBoundaryValue(this, 'schema', value)\n\t\t},\n\t\tget insertSchema() {\n\t\t\treturn getInsertSchema()\n\t\t},\n\t\tset insertSchema(value: ReturnType<typeof getInsertSchema>) {\n\t\t\treplaceBoundaryValue(this, 'insertSchema', value)\n\t\t},\n\t\tget updateSchema() {\n\t\t\treturn getUpdateSchema()\n\t\t},\n\t\tset updateSchema(value: ReturnType<typeof getUpdateSchema>) {\n\t\t\treplaceBoundaryValue(this, 'updateSchema', value)\n\t\t},\n\t\tget commandInput() {\n\t\t\treturn getCommandInput()\n\t\t},\n\t\tset commandInput(value: ReturnType<typeof getCommandInput>) {\n\t\t\treplaceBoundaryValue(this, 'commandInput', value)\n\t\t},\n\t\tget publicDto() {\n\t\t\treturn getPublicDto()\n\t\t},\n\t\tset publicDto(value: ReturnType<typeof getPublicDto>) {\n\t\t\treplaceBoundaryValue(this, 'publicDto', value)\n\t\t},\n\t\tdto,\n\t\ttoPublicDto,\n\t\ttable: defineTable(zodToConvex(storage)),\n\t\tget tools() {\n\t\t\treturn getTools()\n\t\t},\n\t\tset tools(value: ReturnType<typeof getTools>) {\n\t\t\treplaceBoundaryValue(this, 'tools', value)\n\t\t},\n\t}\n}\n\n/** Validate tool eligibility without constructing any derived command/tool objects. */\nfunction assertVariantToolField(schema: z.core.$ZodType): void {\n\tif (!(schema instanceof z.ZodType))\n\t\tthrow new Error('Variant tools require classic Zod field schemas')\n\tif (\n\t\tschema instanceof z.ZodBigInt ||\n\t\t(schema instanceof z.ZodLiteral &&\n\t\t\t[...schema.values].some((value) => z.bigint().safeParse(value).success))\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant tool command fields cannot contain bigint; JSON Schema cannot represent it',\n\t\t)\n\tif (\n\t\tschema instanceof z.ZodOptional ||\n\t\tschema instanceof z.ZodNullable ||\n\t\tschema instanceof z.ZodNonOptional\n\t)\n\t\tassertVariantToolField(schema.unwrap())\n\telse if (schema instanceof z.ZodArray) assertVariantToolField(schema.element)\n\telse if (schema instanceof z.ZodObject)\n\t\tObject.values(schema.shape).forEach(assertVariantToolField)\n\telse if (schema instanceof z.ZodUnion) schema.options.forEach(assertVariantToolField)\n\telse if (schema instanceof z.ZodRecord) {\n\t\tassertVariantToolField(schema.keyType)\n\t\tassertVariantToolField(schema.valueType)\n\t} else if (schema instanceof z.ZodTuple) {\n\t\tschema.def.items.forEach(assertVariantToolField)\n\t\tif (schema.def.rest) assertVariantToolField(schema.def.rest)\n\t} else if (schema instanceof z.ZodIntersection) {\n\t\tassertVariantToolField(schema.def.left)\n\t\tassertVariantToolField(schema.def.right)\n\t}\n}\n\nfunction variantToolField(schema: z.core.$ZodType): z.ZodType {\n\tif (!(schema instanceof z.ZodType))\n\t\tthrow new Error('Variant tools require classic Zod field schemas')\n\tif (\n\t\tschema instanceof z.ZodBigInt ||\n\t\t(schema instanceof z.ZodLiteral &&\n\t\t\t[...schema.values].some((value) => z.bigint().safeParse(value).success))\n\t)\n\t\tthrow new Error(\n\t\t\t'Variant tool command fields cannot contain bigint; JSON Schema cannot represent it',\n\t\t)\n\tconst native = zodToConvex(schema)\n\tif (native.kind === 'id') {\n\t\tconst id = jsonSafeZid(native.tableName)\n\t\tif (native.isOptional === 'optional')\n\t\t\treturn id.optional().refine((value) => schema.safeParse(value).success)\n\t\treturn id.refine((value) => schema.safeParse(value).success)\n\t}\n\tif (schema instanceof z.ZodOptional)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodNullable)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodNonOptional)\n\t\treturn schema.clone({ ...schema.def, innerType: variantToolField(schema.unwrap()) })\n\tif (schema instanceof z.ZodArray)\n\t\treturn schema.clone({ ...schema.def, element: variantToolField(schema.element) })\n\tif (schema instanceof z.ZodObject) {\n\t\tconst fields = Object.fromEntries(\n\t\t\tObject.entries(schema.shape).map(([key, child]) => [key, variantToolField(child)]),\n\t\t)\n\t\treturn schema.clone(Object.assign({}, schema.def, { ['shape']: fields }))\n\t}\n\tif (schema instanceof z.ZodUnion)\n\t\treturn schema.clone({ ...schema.def, options: schema.options.map(variantToolField) })\n\tif (schema instanceof z.ZodRecord)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\t// SAFETY: conversion preserves the original record key output; IDs remain strings.\n\t\t\tkeyType: variantToolField(schema.keyType) as z.core.$ZodRecordKey,\n\t\t\tvalueType: variantToolField(schema.valueType),\n\t\t})\n\tif (schema instanceof z.ZodTuple)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\titems: schema.def.items.map(variantToolField),\n\t\t\trest: schema.def.rest ? variantToolField(schema.def.rest) : null,\n\t\t})\n\tif (schema instanceof z.ZodIntersection)\n\t\treturn schema.clone({\n\t\t\t...schema.def,\n\t\t\tleft: variantToolField(schema.def.left),\n\t\t\tright: variantToolField(schema.def.right),\n\t\t})\n\treturn schema\n}\n\ntype ZodObjectOmit<\n\tSchema extends z.ZodObject<any, any>,\n\tOmitMask extends z.util.Mask<keyof Schema['shape']>,\n> =\n\tSchema extends z.ZodObject<infer ObjectFields, infer Config>\n\t\t? z.ZodObject<\n\t\t\t\tz.util.Flatten<Omit<ObjectFields, Extract<keyof ObjectFields, keyof OmitMask>>>,\n\t\t\t\tConfig\n\t\t\t>\n\t\t: never\n\n/** A public replacement never changes the private schemas captured by boundary helpers. */\nfunction replaceBoundaryValue<Boundary extends object, Key extends keyof Boundary>(\n\tboundary: Boundary,\n\tkey: Key,\n\tvalue: Boundary[Key],\n): void {\n\tObject.defineProperty(boundary, key, {\n\t\tvalue,\n\t\twritable: true,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t})\n}\n\nfunction documentSchema<Fields extends FieldSchemas, Table extends string>(\n\tfields: Fields,\n\ttableName: Table,\n) {\n\treturn z.strictObject({ ...fields, _id: zid(tableName), _creationTime: z.number() })\n}\n\nfunction pickFields<Fields extends FieldSchemas, const Keys extends readonly FieldKey<Fields>[]>(\n\tfields: Fields,\n\tkeys: Keys,\n) {\n\t// SAFETY: each entry uses a requested key and its original validator, preserving Pick.\n\treturn Object.fromEntries(keys.map((key) => [key, fields[key]])) as Pick<Fields, Keys[number]>\n}\n\nfunction omitFields<Fields extends FieldSchemas, const Keys extends readonly FieldKey<Fields>[]>(\n\tfields: Fields,\n\tkeys: Keys,\n) {\n\tconst omitted = new Set<string>(keys)\n\t// SAFETY: filtering removes exactly the supplied keys and keeps every remaining validator.\n\treturn Object.fromEntries(Object.entries(fields).filter(([key]) => !omitted.has(key))) as Omit<\n\t\tFields,\n\t\tKeys[number]\n\t>\n}\n\ntype DtoPropertiesCheck = z.core.$ZodCheck & {\n\treadonly _zod: {\n\t\treadonly def: { readonly check: 'properties' } & Record<\n\t\t\t'shape',\n\t\t\tRecord<string, z.core.$ZodType>\n\t\t>\n\t}\n}\n\n/** Inspect Zod 4's discriminated definitions, failing closed for unsupported nodes.\n * Used by DTO extensions and opt-in variant boundaries; legacy schemas are unchanged.\n */\nfunction assertDtoValidationSchema(\n\tschema: z.core.$ZodType,\n\tseen = new Set<z.core.$ZodType>(),\n\tallowNativeIds = false,\n): void {\n\tif (seen.has(schema)) return\n\tseen.add(schema)\n\t// SAFETY: Zod 4 exposes its built-in schema definitions as this discriminated union.\n\tconst def = (schema as z.core.$ZodTypes)._zod.def\n\tconst reject = () => {\n\t\tthrow new Error('DTO extensions require supported value-preserving validation schemas')\n\t}\n\tif ('coerce' in def && def.coerce) reject()\n\tif ('normalize' in def && def.normalize) reject()\n\tconst visit = (child: z.core.$ZodType) => assertDtoValidationSchema(child, seen, allowNativeIds)\n\tfor (const check of def.checks ?? []) {\n\t\tif (check._zod.def.check === 'overwrite') reject()\n\t\tif ('normalize' in check._zod.def && check._zod.def.normalize) reject()\n\t\tif (check._zod.def.check === 'property') {\n\t\t\t// SAFETY: the property discriminator owns this embedded schema in Zod 4.\n\t\t\tvisit((check as z.core.$ZodCheckProperty)._zod.def.schema)\n\t\t}\n\t\tif (check._zod.def.check === 'properties') {\n\t\t\t// SAFETY: the properties discriminator owns this schema shape in Zod 4.\n\t\t\tfor (const child of Object.values((check as DtoPropertiesCheck)._zod.def.shape)) {\n\t\t\t\tvisit(child)\n\t\t\t}\n\t\t}\n\t}\n\tswitch (def.type) {\n\t\tcase 'custom':\n\t\t\tif (allowNativeIds && zodToConvex(schema).kind === 'id') return\n\t\t\treject()\n\t\t\treturn\n\t\tcase 'string':\n\t\tcase 'number':\n\t\tcase 'boolean':\n\t\tcase 'bigint':\n\t\tcase 'date':\n\t\tcase 'symbol':\n\t\tcase 'null':\n\t\tcase 'undefined':\n\t\tcase 'void':\n\t\tcase 'never':\n\t\tcase 'literal':\n\t\tcase 'enum':\n\t\t\treturn\n\t\tcase 'object':\n\t\t\tif (allowNativeIds && def.catchall && def.catchall._zod.def.type !== 'never')\n\t\t\t\tthrow new Error('Variant fields cannot use object catchalls; use a record field instead')\n\t\t\tfor (const child of Object.values(def.shape)) visit(child)\n\t\t\tif (def.catchall) visit(def.catchall)\n\t\t\treturn\n\t\tcase 'array':\n\t\t\tvisit(def.element)\n\t\t\treturn\n\t\tcase 'optional':\n\t\tcase 'nullable':\n\t\tcase 'nonoptional':\n\t\t\tvisit(def.innerType)\n\t\t\treturn\n\t\tcase 'union':\n\t\t\tfor (const child of def.options) visit(child)\n\t\t\treturn\n\t\tcase 'intersection':\n\t\t\tvisit(def.left)\n\t\t\tvisit(def.right)\n\t\t\treturn\n\t\tcase 'tuple':\n\t\t\tfor (const child of def.items) visit(child)\n\t\t\tif (def.rest) visit(def.rest)\n\t\t\treturn\n\t\tcase 'record':\n\t\t\tvisit(def.keyType)\n\t\t\tvisit(def.valueType)\n\t\t\treturn\n\t\tdefault:\n\t\t\treject()\n\t}\n}\n\nfunction assertOwnedFields(fields: FieldSchemas, reserved: readonly string[]): void {\n\tfor (const key of reserved) {\n\t\tif (Object.hasOwn(fields, key))\n\t\t\tthrow new Error(`Reserved table field \"${key}\" cannot be declared`)\n\t}\n}\n\nfunction assertFieldLists(\n\tfields: FieldSchemas,\n\tserver: readonly string[],\n\tcommand: readonly string[],\n\tpublicKeys: readonly string[],\n\tmanagedTimestamps = true,\n): void {\n\tfor (const key of [...server, ...command, ...publicKeys]) {\n\t\tif (!Object.hasOwn(fields, key)) throw new Error(`Unknown table field \"${key}\"`)\n\t}\n\tconst managed = new Set<string>([...(managedTimestamps ? TIMESTAMP_FIELDS : []), ...server])\n\tfor (const key of command) {\n\t\tif (managed.has(key)) throw new Error(`Server-owned field \"${key}\" cannot be a command input`)\n\t}\n}\n"],"mappings":"2ZAmCA,MAAMI,EAAkB,CACvB,UAAWC,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,UAAWA,EAAE,OAAO,CAAC,CAAC,SAAS,EAC/B,WAAYA,EAAE,OAAO,CAAC,CAAC,SAAS,CACjC,EASaC,EAAmB,CAAC,YAAa,YAAa,YAAY,EA6IvE,SAAgBC,EAOf,EACA,EACA,EAAmF,CAAC,EACV,CAC1E,IAAMC,EAAWC,EAAOT,CAAG,EAC3BU,EAAkBF,EAAU,CAAC,MAAO,gBAAiB,GAAGF,CAAgB,CAAC,EACzE,IAAMK,EAAoC,CAAE,GAAGH,EAAU,GAAGJ,CAAgB,EAC5EQ,EACCD,EACAE,EAAQ,cAAgB,CAAC,EACzBA,EAAQ,eAAiB,CAAC,EAC1BA,EAAQ,cAAgB,CAAC,CAC1B,EACA,IAAMC,EAAiET,EAAE,aAAa,CACrF,GAAGM,CACJ,CAAC,EACKI,EAAYC,MACjBC,EAAgDN,EAASO,CAAS,CACnE,EACMC,EAAqF,CAC1F,GAAGb,EACH,GAAIO,EAAQ,cAAgB,CAAC,CAC9B,EACMO,EAAgD,CAAC,GAAIP,EAAQ,eAAiB,CAAC,CAAE,EACjFQ,EAA8C,CAAC,GAAIR,EAAQ,cAAgB,CAAC,CAAE,EAE9ES,EAAiBN,MAAcO,EAAWZ,EAASQ,CAAW,CAAC,EAC/DK,EAAmBR,MAAcS,EAAWd,EAASS,CAAW,CAAC,EACjEM,EAAkBV,MAEtBX,EAAE,aAAa,CAAE,GAAGiB,EAAe,CAAE,CAAC,CACxC,EACMK,EAAkBX,MAAcX,EAAE,aAAa,CAAE,GAAGiB,EAAe,CAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EACjFM,EAAkBZ,MAEtBX,EAAE,aAAa,CAAE,GAAGmB,EAAiB,CAAE,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ACnF,IAAK,IAAM6B,KAAOwG,EACjB,GAAI,OAAO,OAAOtI,EAAQ8B,CAAG,EAC5B,MAAU,MAAM,yBAAyBA,EAAI,qBAAqB,CAErE,CAEA,SAAS3B,EACR,EACA,EACA,EACA,EACA,EAAoB,GACb,CACP,IAAK,IAAM2B,IAAO,CAAC,GAAGyG,EAAQ,GAAGC,EAAS,GAAG5H,CAAU,EACtD,GAAI,CAAC,OAAO,OAAOZ,EAAQ8B,CAAG,EAAG,MAAU,MAAM,wBAAwBA,EAAI,EAAE,EAEhF,IAAM2G,kBAAU,IAAI,IAAY,CAAC,GAAIC,EAAoB7I,EAAmB,CAAC,EAAI,GAAG0I,CAAM,CAAC,EAC3F,IAAK,IAAMzG,KAAO0G,EACjB,GAAIC,EAAQ,IAAI3G,CAAG,EAAG,MAAU,MAAM,uBAAuBA,EAAI,4BAA4B,CAE/F"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cvx-kit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.34",
|
|
4
4
|
"description": "Reusable Convex application kit: foundation kernels, approvals component, zod table boundaries, WorkOS-backed auth function constructors, and audited command protocol.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"component",
|