@rsconcept/domain 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +1 -1
  2. package/dist/cctext/language-api.js.map +1 -1
  3. package/dist/cctext/language.d.ts +7 -4
  4. package/dist/cctext/language.js.map +1 -1
  5. package/dist/{diagnostics-DYMvTSev.js → diagnostics-BSryP66e.js} +131 -40
  6. package/dist/diagnostics-BSryP66e.js.map +1 -0
  7. package/dist/{diagnostics-Clo3mkba.d.ts → diagnostics-Dtzgj5Q9.d.ts} +14 -5
  8. package/dist/graph/graph.d.ts +1 -1
  9. package/dist/graph/graph.js +88 -1
  10. package/dist/graph/graph.js.map +1 -1
  11. package/dist/graph/index.d.ts +1 -1
  12. package/dist/{graph-DR8rL2o3.d.ts → graph-DPOvglEm.d.ts} +10 -2
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.js +2 -2
  15. package/dist/library/diagnostics.d.ts +2 -2
  16. package/dist/library/diagnostics.js +2 -2
  17. package/dist/library/index.d.ts +2 -2
  18. package/dist/library/index.js +2 -2
  19. package/dist/library/oss-api.d.ts +1 -1
  20. package/dist/library/oss.d.ts +1 -1
  21. package/dist/library/rsengine.d.ts +1 -1
  22. package/dist/library/rsengine.js +1 -1
  23. package/dist/library/rsform-api.d.ts +13 -2
  24. package/dist/library/rsform-api.js +2 -2
  25. package/dist/library/rsform.d.ts +1 -1
  26. package/dist/library/rsmodel-api.d.ts +1 -1
  27. package/dist/library/rsmodel-api.js +1 -1
  28. package/dist/library/rsmodel.d.ts +1 -1
  29. package/dist/library/structure-planner.d.ts +1 -1
  30. package/dist/library/structure-planner.js +1 -1
  31. package/package.json +14 -13
  32. package/src/cctext/language-api.test.ts +5 -0
  33. package/src/cctext/language-api.ts +6 -6
  34. package/src/cctext/language.ts +3 -4
  35. package/src/graph/graph.test.ts +22 -0
  36. package/src/graph/graph.ts +105 -1
  37. package/src/index.ts +2 -0
  38. package/src/library/diagnostics.test.ts +115 -0
  39. package/src/library/diagnostics.ts +75 -40
  40. package/src/library/index.ts +2 -0
  41. package/src/library/rsform-api.test.ts +99 -3
  42. package/src/library/rsform-api.ts +147 -6
  43. package/dist/diagnostics-DYMvTSev.js.map +0 -1
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Shared TypeScript domain layer for the [Concept Portal](https://portal.acconcept.ru) stack.
4
4
 
5
- This package implements the formal language **RSLang**, the schema model **RSForm**, the evaluation engine **RSEngine**, the operation-of-schemas model **OSS**, and supporting helpers (graphs, parsing utilities, concept-text grammemes). It is consumed both by the Portal frontend and by [`@rsconcept/rstool`](https://www.npmjs.com/package/@rsconcept/rstool).
5
+ This package implements the formal language **RSLang** (language of structural species explication), the schema model **RSForm**, the evaluation engine **RSEngine**, the operation-of-schemas model **OSS**, and supporting helpers (graphs, parsing utilities, concept-text grammemes). It is consumed both by the Portal frontend and by [`@rsconcept/rstool`](https://www.npmjs.com/package/@rsconcept/rstool).
6
6
 
7
7
  ## Install
8
8
 
@@ -1 +1 @@
1
- {"version":3,"file":"language-api.js","names":[],"sources":["../../src/cctext/language-api.ts"],"sourcesContent":["/**\n * Module: Natural language model API.\n */\n\nimport {\n Case,\n type EntityReference,\n Grammeme,\n type IReference,\n Plurality,\n ReferenceType,\n type SyntacticReference,\n type TermContext,\n type TermContextItem,\n type WordForm\n} from './language';\n\ninterface Position {\n from: number;\n to: number;\n}\n\ninterface ResolvedReference {\n ref: IReference;\n resolved: string;\n posInput: Position;\n}\n\nconst REFERENCE_PATTERN = /@{[^{}]*?}/g;\nconst ENTITY_REFERENCE_PATTERN = /@{([^0-9\\-][^}|{]*?)\\|([^}|{]*?)}/g;\n\n/** Represents generated lexeme forms. */\nexport interface Lexeme {\n items: { text: string; grams: string }[];\n}\n\n/** Equality comparator for {@link WordForm}. Compares a set of Grammemes attached to wordforms. */\nexport function wordFormEquals(left: WordForm, right: WordForm): boolean {\n if (left.grams.length !== right.grams.length) {\n return false;\n }\n for (let index = 0; index < left.grams.length; ++index) {\n if (left.grams[index] !== right.grams[index]) {\n return false;\n }\n }\n return true;\n}\n\n/** Transforms {@link Grammeme} enumeration to {@link Grammeme}. */\nexport function parseGrammemes(termForm: string): Grammeme[] {\n const result: Grammeme[] = [];\n for (const chunk of termForm.split(',')) {\n const gram = chunk.trim();\n if (gram !== '') {\n result.push(gram as Grammeme);\n }\n }\n return result.sort(grammemeCompare);\n}\n\n/** Generates all supported noun forms using nominal text for every form. */\nexport function generateNominalLexeme(data: { text: string }): Lexeme {\n return {\n items: Plurality.flatMap(plurality =>\n Case.map(gramCase => ({\n text: data.text,\n grams: `${plurality},${gramCase}`\n }))\n )\n };\n}\n\n/**\n * Extracts {@link EntityReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{GLOBAL_ID|GRAMMEMES\\}'\n */\nexport function parseEntityReference(text: string): EntityReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.ENTITY) {\n throw new Error(`Invalid entity reference: ${text}`);\n }\n return ref.data as EntityReference;\n}\n\n/**\n * Extracts {@link SyntacticReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{OFFSET|NOMINAL_FORM\\}'\n */\nexport function parseSyntacticReference(text: string): SyntacticReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.SYNTACTIC) {\n throw new Error(`Invalid syntactic reference: ${text}`);\n }\n return ref.data as SyntacticReference;\n}\n\n/** Extracts a validated reference from string representation. */\nexport function parseReference(text: string): IReference | null {\n if (text.length < 4 || !text.startsWith('@{') || !text.endsWith('}')) {\n return null;\n }\n\n const blocks = text\n .slice(2, text.length - 1)\n .split('|')\n .map(block => block.trim());\n if (blocks.length !== 2 || blocks[0] === '' || blocks[0].startsWith('0')) {\n return null;\n }\n\n if (blocks[0].startsWith('-') || /^[1-9]/.test(blocks[0])) {\n const offset = Number(blocks[0]);\n if (!Number.isInteger(offset) || offset === 0 || blocks[1] === '') {\n return null;\n }\n return {\n type: ReferenceType.SYNTACTIC,\n data: { offset, nominal: blocks[1] }\n };\n }\n\n return {\n type: ReferenceType.ENTITY,\n data: { entity: blocks[0], tags: parseGrammemes(blocks[1].replaceAll(' ', '')) }\n };\n}\n\n/** Apply alias mapping to entity references in terminological text. */\nexport function applyEntityReferenceMapping(text: string, mapping: Record<string, string>): string {\n if (text === '' || Object.keys(mapping).length === 0) {\n return text;\n }\n\n let posInput = 0;\n let output = '';\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1];\n const entityKey = entity.trim();\n const start = segment.index ?? 0;\n if (entityKey in mapping) {\n output += text.substring(posInput, start + 2);\n output += mapping[entityKey];\n output += text.substring(start + 2 + entity.length, start + segment[0].length);\n posInput = start + segment[0].length;\n }\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Extracts unique entity aliases referenced by text. */\nexport function extractEntities(text: string): string[] {\n const result: string[] = [];\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1].trim();\n if (!result.includes(entity)) {\n result.push(entity);\n }\n }\n return result;\n}\n\n/** Resolves text references using nominal terms and optional manually edited forms. */\nexport function resolveTextReferences(text: string, context: TermContext): string {\n const references = parseReferences(text);\n if (references.length === 0) {\n return text;\n }\n\n for (const ref of references) {\n if (ref.ref.type === ReferenceType.ENTITY) {\n ref.resolved = resolveEntity(ref.ref.data as EntityReference, context);\n }\n }\n references.forEach((ref, index) => {\n if (ref.ref.type === ReferenceType.SYNTACTIC) {\n ref.resolved = resolveSyntactic(ref.ref.data as SyntacticReference, index, references);\n }\n });\n\n let posInput = 0;\n let output = '';\n for (const ref of references) {\n output += text.substring(posInput, ref.posInput.from);\n output += ref.resolved;\n posInput = ref.posInput.to;\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Transforms {@link IReference} to string representation. */\nexport function referenceToString(ref: IReference): string {\n switch (ref.type) {\n case ReferenceType.ENTITY: {\n const entity = ref.data as EntityReference;\n return `@{${entity.entity}|${entity.tags.join(',')}}`;\n }\n case ReferenceType.SYNTACTIC: {\n const syntactic = ref.data as SyntacticReference;\n return `@{${syntactic.offset}|${syntactic.nominal}}`;\n }\n }\n}\n\n// ===== Internals =======\n\n/** Compares {@link Grammeme} based on Grammeme enum and alpha order for strings. */\nfunction grammemeCompare(left: Grammeme, right: Grammeme): number {\n const indexLeft = Object.values(Grammeme).findIndex(gram => gram === left);\n const indexRight = Object.values(Grammeme).findIndex(gram => gram === right);\n if (indexLeft === -1 && indexRight === -1) {\n return left.localeCompare(right);\n } else if (indexLeft === -1 && indexRight !== -1) {\n return 1;\n } else if (indexLeft !== -1 && indexRight === -1) {\n return -1;\n } else {\n return indexLeft - indexRight;\n }\n}\n\nfunction parseReferences(text: string): ResolvedReference[] {\n const result: ResolvedReference[] = [];\n for (const segment of text.matchAll(REFERENCE_PATTERN)) {\n const ref = parseReference(segment[0]);\n if (ref) {\n result.push({\n ref,\n resolved: '',\n posInput: { from: segment.index ?? 0, to: (segment.index ?? 0) + segment[0].length }\n });\n }\n }\n return result;\n}\n\nfunction resolveEntity(ref: EntityReference, context: TermContext): string {\n const entity = context[ref.entity];\n if (!entity) {\n return `!Неизвестная сущность: ${ref.entity}!`;\n }\n\n const resolved = getEntityForm(entity, ref.tags);\n return resolved === '' ? `!Отсутствует термин: ${ref.entity}!` : resolved;\n}\n\nfunction getEntityForm(entity: TermContextItem, grams: Grammeme[]): string {\n if (grams.length === 0) {\n return entity.nominal;\n }\n\n const manual = entity.forms?.find(form => matchGrams(grams, form.grams));\n return manual?.text ?? entity.nominal;\n}\n\nfunction matchGrams(query: Grammeme[], candidate: Grammeme[]): boolean {\n for (const gram of candidate) {\n if (!query.includes(gram)) {\n return false;\n }\n }\n return true;\n}\n\nfunction resolveSyntactic(ref: SyntacticReference, index: number, references: ResolvedReference[]): string {\n const master = findSyntacticMaster(ref.offset, index, references);\n if (!master) {\n return `!Некорректное смещение: ${ref.offset}!`;\n }\n return ref.nominal;\n}\n\nfunction findSyntacticMaster(\n offset: number,\n index: number,\n references: ResolvedReference[]\n): ResolvedReference | undefined {\n if (offset > 0) {\n let position = index + 1;\n let left = offset;\n while (position < references.length) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === 1) {\n return references[position];\n }\n left -= 1;\n }\n position += 1;\n }\n } else {\n let position = index - 1;\n let left = offset;\n while (position >= 0) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === -1) {\n return references[position];\n }\n left += 1;\n }\n position -= 1;\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;AA4BA,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;;AAQjC,SAAgB,eAAe,MAAgB,OAA0B;CACvE,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAET,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,MAAM,QAAQ,EAAE,OAC/C,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAGX,OAAO;AACT;;AAGA,SAAgB,eAAe,UAA8B;CAC3D,MAAM,SAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS,SAAS,MAAM,GAAG,GAAG;EACvC,MAAM,OAAO,MAAM,KAAK;EACxB,IAAI,SAAS,IACX,OAAO,KAAK,IAAgB;CAEhC;CACA,OAAO,OAAO,KAAK,eAAe;AACpC;;AAGA,SAAgB,sBAAsB,MAAgC;CACpE,OAAO,EACL,OAAO,UAAU,SAAQ,cACvB,KAAK,KAAI,cAAa;EACpB,MAAM,KAAK;EACX,OAAO,GAAG,UAAU,GAAG;CACzB,EAAE,CACJ,EACF;AACF;;;;;;AAOA,SAAgB,qBAAqB,MAA+B;CAClE,MAAM,MAAM,eAAe,IAAI;CAC/B,IAAI,KAAK,SAAS,cAAc,QAC9B,MAAM,IAAI,MAAM,6BAA6B,MAAM;CAErD,OAAO,IAAI;AACb;;;;;;AAOA,SAAgB,wBAAwB,MAAkC;CACxE,MAAM,MAAM,eAAe,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yB,OAAe,YAAyC;CAEzG,IAAI,CADW,oBAAoB,IAAI,QAAQ,OAAO,UACjD,GACH,OAAO,2BAA2B,IAAI,OAAO;CAE/C,OAAO,IAAI;AACb;AAEA,SAAS,oBACP,QACA,OACA,YAC+B;CAC/B,IAAI,SAAS,GAAG;EACd,IAAI,WAAW,QAAQ;EACvB,IAAI,OAAO;EACX,OAAO,WAAW,WAAW,QAAQ;GACnC,IAAI,WAAW,SAAS,CAAC,IAAI,SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,GACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF,OAAO;EACL,IAAI,WAAW,QAAQ;EACvB,IAAI,OAAO;EACX,OAAO,YAAY,GAAG;GACpB,IAAI,WAAW,SAAS,CAAC,IAAI,SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,IACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF;AAEF"}
1
+ {"version":3,"file":"language-api.js","names":[],"sources":["../../src/cctext/language-api.ts"],"sourcesContent":["/**\n * Module: Natural language model API.\n */\n\nimport {\n Case,\n type EntityReference,\n Grammeme,\n type IReference,\n Plurality,\n ReferenceType,\n type SyntacticReference,\n type TermContext,\n type TermContextItem,\n type WordForm\n} from './language';\n\ninterface Position {\n from: number;\n to: number;\n}\n\ninterface ResolvedReference {\n ref: IReference;\n resolved: string;\n posInput: Position;\n}\n\nconst REFERENCE_PATTERN = /@{[^{}]*?}/g;\nconst ENTITY_REFERENCE_PATTERN = /@{([^0-9\\-][^}|{]*?)\\|([^}|{]*?)}/g;\n\n/** Represents generated lexeme forms. */\nexport interface Lexeme {\n items: { text: string; grams: string }[];\n}\n\n/** Equality comparator for {@link WordForm}. Compares a set of Grammemes attached to wordforms. */\nexport function wordFormEquals(left: WordForm, right: WordForm): boolean {\n if (left.grams.length !== right.grams.length) {\n return false;\n }\n for (let index = 0; index < left.grams.length; ++index) {\n if (left.grams[index] !== right.grams[index]) {\n return false;\n }\n }\n return true;\n}\n\n/** Transforms {@link Grammeme} enumeration to {@link Grammeme}. */\nexport function parseGrammemes(termForm: string): Grammeme[] {\n const result: Grammeme[] = [];\n for (const chunk of termForm.split(',')) {\n const gram = chunk.trim();\n if (gram !== '') {\n result.push(gram as Grammeme);\n }\n }\n return result.sort(grammemeCompare);\n}\n\n/** Generates all supported noun forms using nominal text for every form. */\nexport function generateNominalLexeme(data: { text: string }): Lexeme {\n return {\n items: Plurality.flatMap(plurality =>\n Case.map(gramCase => ({\n text: data.text,\n grams: `${plurality},${gramCase}`\n }))\n )\n };\n}\n\n/**\n * Extracts {@link EntityReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{GLOBAL_ID|GRAMMEMES\\}'\n */\nexport function parseEntityReference(text: string): EntityReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.ENTITY) {\n throw new Error(`Invalid entity reference: ${text}`);\n }\n return ref.data;\n}\n\n/**\n * Extracts {@link SyntacticReference} from string representation.\n *\n * @param text - Reference text in a valid pattern. Must fit format '\\@\\{OFFSET|NOMINAL_FORM\\}'\n */\nexport function parseSyntacticReference(text: string): SyntacticReference {\n const ref = parseReference(text);\n if (ref?.type !== ReferenceType.SYNTACTIC) {\n throw new Error(`Invalid syntactic reference: ${text}`);\n }\n return ref.data;\n}\n\n/** Extracts a validated reference from string representation. */\nexport function parseReference(text: string): IReference | null {\n if (text.length < 4 || !text.startsWith('@{') || !text.endsWith('}')) {\n return null;\n }\n\n const blocks = text\n .slice(2, text.length - 1)\n .split('|')\n .map(block => block.trim());\n if (blocks.length !== 2 || blocks[0] === '' || blocks[0].startsWith('0')) {\n return null;\n }\n\n if (blocks[0].startsWith('-') || /^[1-9]/.test(blocks[0])) {\n const offset = Number(blocks[0]);\n if (!Number.isInteger(offset) || offset === 0 || blocks[1] === '') {\n return null;\n }\n return {\n type: ReferenceType.SYNTACTIC,\n data: { offset, nominal: blocks[1] }\n };\n }\n\n return {\n type: ReferenceType.ENTITY,\n data: { entity: blocks[0], tags: parseGrammemes(blocks[1].replaceAll(' ', '')) }\n };\n}\n\n/** Apply alias mapping to entity references in terminological text. */\nexport function applyEntityReferenceMapping(text: string, mapping: Record<string, string>): string {\n if (text === '' || Object.keys(mapping).length === 0) {\n return text;\n }\n\n let posInput = 0;\n let output = '';\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1];\n const entityKey = entity.trim();\n const start = segment.index ?? 0;\n if (entityKey in mapping) {\n output += text.substring(posInput, start + 2);\n output += mapping[entityKey];\n output += text.substring(start + 2 + entity.length, start + segment[0].length);\n posInput = start + segment[0].length;\n }\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Extracts unique entity aliases referenced by text. */\nexport function extractEntities(text: string): string[] {\n const result: string[] = [];\n for (const segment of text.matchAll(ENTITY_REFERENCE_PATTERN)) {\n const entity = segment[1].trim();\n if (!result.includes(entity)) {\n result.push(entity);\n }\n }\n return result;\n}\n\n/** Resolves text references using nominal terms and optional manually edited forms. */\nexport function resolveTextReferences(text: string, context: TermContext): string {\n const references = parseReferences(text);\n if (references.length === 0) {\n return text;\n }\n\n for (const ref of references) {\n if (ref.ref.type === ReferenceType.ENTITY) {\n ref.resolved = resolveEntity(ref.ref.data, context);\n }\n }\n references.forEach((ref, index) => {\n if (ref.ref.type === ReferenceType.SYNTACTIC) {\n ref.resolved = resolveSyntactic(ref.ref.data, index, references);\n }\n });\n\n let posInput = 0;\n let output = '';\n for (const ref of references) {\n output += text.substring(posInput, ref.posInput.from);\n output += ref.resolved;\n posInput = ref.posInput.to;\n }\n output += text.substring(posInput);\n return output;\n}\n\n/** Transforms {@link IReference} to string representation. */\nexport function referenceToString(ref: IReference): string {\n switch (ref.type) {\n case ReferenceType.ENTITY: {\n const entity = ref.data;\n return `@{${entity.entity}|${entity.tags.join(',')}}`;\n }\n case ReferenceType.SYNTACTIC: {\n const syntactic = ref.data;\n return `@{${syntactic.offset}|${syntactic.nominal}}`;\n }\n }\n}\n\n// ===== Internals =======\n\n/** Compares {@link Grammeme} based on Grammeme enum and alpha order for strings. */\nfunction grammemeCompare(left: Grammeme, right: Grammeme): number {\n const indexLeft = Object.values(Grammeme).findIndex(gram => gram === left);\n const indexRight = Object.values(Grammeme).findIndex(gram => gram === right);\n if (indexLeft === -1 && indexRight === -1) {\n return left.localeCompare(right);\n } else if (indexLeft === -1 && indexRight !== -1) {\n return 1;\n } else if (indexLeft !== -1 && indexRight === -1) {\n return -1;\n } else {\n return indexLeft - indexRight;\n }\n}\n\nfunction parseReferences(text: string): ResolvedReference[] {\n const result: ResolvedReference[] = [];\n for (const segment of text.matchAll(REFERENCE_PATTERN)) {\n const ref = parseReference(segment[0]);\n if (ref) {\n result.push({\n ref,\n resolved: '',\n posInput: { from: segment.index ?? 0, to: (segment.index ?? 0) + segment[0].length }\n });\n }\n }\n return result;\n}\n\nfunction resolveEntity(ref: EntityReference, context: TermContext): string {\n const entity = context[ref.entity];\n if (!entity) {\n return `!Неизвестная сущность: ${ref.entity}!`;\n }\n\n const resolved = getEntityForm(entity, ref.tags);\n return resolved === '' ? `!Отсутствует термин: ${ref.entity}!` : resolved;\n}\n\nfunction getEntityForm(entity: TermContextItem, grams: Grammeme[]): string {\n if (grams.length === 0) {\n return entity.nominal;\n }\n\n const manual = entity.forms?.find(form => matchGrams(grams, form.grams));\n return manual?.text ?? entity.nominal;\n}\n\nfunction matchGrams(query: Grammeme[], candidate: Grammeme[]): boolean {\n for (const gram of candidate) {\n if (!query.includes(gram)) {\n return false;\n }\n }\n return true;\n}\n\nfunction resolveSyntactic(ref: SyntacticReference, index: number, references: ResolvedReference[]): string {\n const master = findSyntacticMaster(ref.offset, index, references);\n if (!master) {\n return `!Некорректное смещение: ${ref.offset}!`;\n }\n return ref.nominal;\n}\n\nfunction findSyntacticMaster(\n offset: number,\n index: number,\n references: ResolvedReference[]\n): ResolvedReference | undefined {\n if (offset > 0) {\n let position = index + 1;\n let left = offset;\n while (position < references.length) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === 1) {\n return references[position];\n }\n left -= 1;\n }\n position += 1;\n }\n } else {\n let position = index - 1;\n let left = offset;\n while (position >= 0) {\n if (references[position].ref.type === ReferenceType.ENTITY) {\n if (left === -1) {\n return references[position];\n }\n left += 1;\n }\n position -= 1;\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;AA4BA,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B;;AAQjC,SAAgB,eAAe,MAAgB,OAA0B;CACvE,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAET,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,MAAM,QAAQ,EAAE,OAC/C,IAAI,KAAK,MAAM,WAAW,MAAM,MAAM,QACpC,OAAO;CAGX,OAAO;AACT;;AAGA,SAAgB,eAAe,UAA8B;CAC3D,MAAM,SAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS,SAAS,MAAM,GAAG,GAAG;EACvC,MAAM,OAAO,MAAM,KAAK;EACxB,IAAI,SAAS,IACX,OAAO,KAAK,IAAgB;CAEhC;CACA,OAAO,OAAO,KAAK,eAAe;AACpC;;AAGA,SAAgB,sBAAsB,MAAgC;CACpE,OAAO,EACL,OAAO,UAAU,SAAQ,cACvB,KAAK,KAAI,cAAa;EACpB,MAAM,KAAK;EACX,OAAO,GAAG,UAAU,GAAG;CACzB,EAAE,CACJ,EACF;AACF;;;;;;AAOA,SAAgB,qBAAqB,MAA+B;CAClE,MAAM,MAAM,eAAe,IAAI;CAC/B,IAAI,KAAK,SAAS,cAAc,QAC9B,MAAM,IAAI,MAAM,6BAA6B,MAAM;CAErD,OAAO,IAAI;AACb;;;;;;AAOA,SAAgB,wBAAwB,MAAkC;CACxE,MAAM,MAAM,eAAe,IAAI;CAC/B,IAAI,KAAK,SAAS,cAAc,WAC9B,MAAM,IAAI,MAAM,gCAAgC,MAAM;CAExD,OAAO,IAAI;AACb;;AAGA,SAAgB,eAAe,MAAiC;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SAAS,oBACP,QACA,OACA,YAC+B;CAC/B,IAAI,SAAS,GAAG;EACd,IAAI,WAAW,QAAQ;EACvB,IAAI,OAAO;EACX,OAAO,WAAW,WAAW,QAAQ;GACnC,IAAI,WAAW,SAAS,CAAC,IAAI,SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,GACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF,OAAO;EACL,IAAI,WAAW,QAAQ;EACvB,IAAI,OAAO;EACX,OAAO,YAAY,GAAG;GACpB,IAAI,WAAW,SAAS,CAAC,IAAI,SAAS,cAAc,QAAQ;IAC1D,IAAI,SAAS,IACX,OAAO,WAAW;IAEpB,QAAQ;GACV;GACA,YAAY;EACd;CACF;AAEF"}
@@ -51,10 +51,13 @@ interface SyntacticReference {
51
51
  nominal: string;
52
52
  }
53
53
  /** Represents abstract reference data. */
54
- interface IReference {
55
- type: ReferenceType;
56
- data: EntityReference | SyntacticReference;
57
- }
54
+ type IReference = {
55
+ type: typeof ReferenceType.ENTITY;
56
+ data: EntityReference;
57
+ } | {
58
+ type: typeof ReferenceType.SYNTACTIC;
59
+ data: SyntacticReference;
60
+ };
58
61
  //#endregion
59
62
  export { Case, EntityReference, Grammeme, IReference, Plurality, ReferenceType, SyntacticReference, TermContext, TermContextItem, WordForm, supportedGrammemes };
60
63
  //# sourceMappingURL=language.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"language.js","names":[],"sources":["../../src/cctext/language.ts"],"sourcesContent":["/**\n * Module: Natural language model declarations.\n */\n\n/** Represents single unit of language Morphology. */\n// prettier-ignore\nexport const Grammeme = {\n // Число\n sing: 'sing', plur: 'plur',\n\n // Падеж\n nomn: 'nomn', gent: 'gent', datv: 'datv',\n accs: 'accs', ablt: 'ablt', loct: 'loct',\n} as const;\nexport type Grammeme = (typeof Grammeme)[keyof typeof Grammeme];\n\n/** Represents case language concept. */\nexport const Case: Grammeme[] = [\n Grammeme.nomn,\n Grammeme.gent,\n Grammeme.datv,\n Grammeme.accs,\n Grammeme.ablt,\n Grammeme.loct\n] as const;\n\n/** Represents plurality language concept. */\nexport const Plurality: Grammeme[] = [Grammeme.sing, Grammeme.plur] as const;\n\n/** Represents specific wordform attached to {@link Grammeme}s. */\nexport interface WordForm {\n text: string;\n grams: Grammeme[];\n}\n\n/** Represents a term available for text reference resolution. */\nexport interface TermContextItem {\n nominal: string;\n forms?: WordForm[];\n}\n\n/** Represents term lookup context keyed by entity alias. */\nexport type TermContext = Record<string, TermContextItem>;\n\n/**\n * Represents list of {@link Grammeme}s available in reference construction.\n */\n// prettier-ignore\nexport const supportedGrammemes = [\n Grammeme.sing, Grammeme.plur,\n Grammeme.nomn, Grammeme.gent, Grammeme.datv,\n Grammeme.accs, Grammeme.ablt, Grammeme.loct,\n] as const;\n\n// ====== Reference resolution =====\n\n/** Represents text reference type. */\nexport const ReferenceType = {\n ENTITY: 'entity',\n SYNTACTIC: 'syntax'\n} as const;\nexport type ReferenceType = (typeof ReferenceType)[keyof typeof ReferenceType];\n\n/** Represents entity reference payload. */\nexport interface EntityReference {\n entity: string;\n tags: Grammeme[];\n}\n\n/** Represents syntactic reference payload. */\nexport interface SyntacticReference {\n offset: number;\n nominal: string;\n}\n\n/** Represents abstract reference data. */\nexport interface IReference {\n type: ReferenceType;\n data: EntityReference | SyntacticReference;\n}\n"],"mappings":";;;;;AAMA,MAAa,WAAW;CAEtB,MAAM;CAAQ,MAAM;CAGpB,MAAM;CAAQ,MAAM;CAAQ,MAAM;CAClC,MAAM;CAAQ,MAAM;CAAQ,MAAM;AACpC;;AAIA,MAAa,OAAmB;CAC9B,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX;;AAGA,MAAa,YAAwB,CAAC,SAAS,MAAM,SAAS,IAAI;;;;AAqBlE,MAAa,qBAAqB;CAChC,SAAS;CAAM,SAAS;CACxB,SAAS;CAAM,SAAS;CAAM,SAAS;CACvC,SAAS;CAAM,SAAS;CAAM,SAAS;AACzC;;AAKA,MAAa,gBAAgB;CAC3B,QAAQ;CACR,WAAW;AACb"}
1
+ {"version":3,"file":"language.js","names":[],"sources":["../../src/cctext/language.ts"],"sourcesContent":["/**\n * Module: Natural language model declarations.\n */\n\n/** Represents single unit of language Morphology. */\n// prettier-ignore\nexport const Grammeme = {\n // Число\n sing: 'sing', plur: 'plur',\n\n // Падеж\n nomn: 'nomn', gent: 'gent', datv: 'datv',\n accs: 'accs', ablt: 'ablt', loct: 'loct',\n} as const;\nexport type Grammeme = (typeof Grammeme)[keyof typeof Grammeme];\n\n/** Represents case language concept. */\nexport const Case: Grammeme[] = [\n Grammeme.nomn,\n Grammeme.gent,\n Grammeme.datv,\n Grammeme.accs,\n Grammeme.ablt,\n Grammeme.loct\n] as const;\n\n/** Represents plurality language concept. */\nexport const Plurality: Grammeme[] = [Grammeme.sing, Grammeme.plur] as const;\n\n/** Represents specific wordform attached to {@link Grammeme}s. */\nexport interface WordForm {\n text: string;\n grams: Grammeme[];\n}\n\n/** Represents a term available for text reference resolution. */\nexport interface TermContextItem {\n nominal: string;\n forms?: WordForm[];\n}\n\n/** Represents term lookup context keyed by entity alias. */\nexport type TermContext = Record<string, TermContextItem>;\n\n/**\n * Represents list of {@link Grammeme}s available in reference construction.\n */\n// prettier-ignore\nexport const supportedGrammemes = [\n Grammeme.sing, Grammeme.plur,\n Grammeme.nomn, Grammeme.gent, Grammeme.datv,\n Grammeme.accs, Grammeme.ablt, Grammeme.loct,\n] as const;\n\n// ====== Reference resolution =====\n\n/** Represents text reference type. */\nexport const ReferenceType = {\n ENTITY: 'entity',\n SYNTACTIC: 'syntax'\n} as const;\nexport type ReferenceType = (typeof ReferenceType)[keyof typeof ReferenceType];\n\n/** Represents entity reference payload. */\nexport interface EntityReference {\n entity: string;\n tags: Grammeme[];\n}\n\n/** Represents syntactic reference payload. */\nexport interface SyntacticReference {\n offset: number;\n nominal: string;\n}\n\n/** Represents abstract reference data. */\nexport type IReference =\n | { type: typeof ReferenceType.ENTITY; data: EntityReference }\n | { type: typeof ReferenceType.SYNTACTIC; data: SyntacticReference };\n"],"mappings":";;;;;AAMA,MAAa,WAAW;CAEtB,MAAM;CAAQ,MAAM;CAGpB,MAAM;CAAQ,MAAM;CAAQ,MAAM;CAClC,MAAM;CAAQ,MAAM;CAAQ,MAAM;AACpC;;AAIA,MAAa,OAAmB;CAC9B,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;CACT,SAAS;AACX;;AAGA,MAAa,YAAwB,CAAC,SAAS,MAAM,SAAS,IAAI;;;;AAqBlE,MAAa,qBAAqB;CAChC,SAAS;CAAM,SAAS;CACxB,SAAS;CAAM,SAAS;CAAM,SAAS;CACvC,SAAS;CAAM,SAAS;CAAM,SAAS;AACzC;;AAKA,MAAa,gBAAgB;CAC3B,QAAQ;CACR,WAAW;AACb"}
@@ -3,7 +3,7 @@ import { labelType } from "./rslang/labels.js";
3
3
  import { applyEntityReferenceMapping } from "./cctext/language-api.js";
4
4
  import { RSErrorCode } from "./rslang/error.js";
5
5
  import { generateExpressionFromAst } from "./rslang/parser/expression-generator.js";
6
- import { applyAliasMapping, applyTypificationMapping, parseRSLangExpression } from "./rslang/api.js";
6
+ import { applyAliasMapping, applyTypificationMapping, extractGlobals, parseRSLangExpression } from "./rslang/api.js";
7
7
  import { applyPath } from "./rslang/semantic/typification-api.js";
8
8
  import { ValueClass } from "./rslang/semantic/value-class.js";
9
9
  import "./rslang/index.js";
@@ -307,10 +307,71 @@ function getAnalysisFor(expression, cstType, schema, alias) {
307
307
  ast: null
308
308
  };
309
309
  }
310
- return schema.analyzer.checkFull(expression, {
310
+ return refineAnalysisForDependencyCycles(schema.analyzer.checkFull(expression, {
311
311
  expected: typeClassForCstType(cstType),
312
312
  isDomain: cstType === CstType.STRUCTURED
313
+ }), expression, schema, alias);
314
+ }
315
+ /**
316
+ * When an untyped / bare F·P reference names a constituent on a definition cycle with the
317
+ * current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.
318
+ *
319
+ * Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`
320
+ * (bare `P1` / `F1` treated as a call without arguments).
321
+ *
322
+ * Uses a draft dependency graph: incoming edges of the edited constituent are taken from
323
+ * `expression`, so Check works before Save.
324
+ */
325
+ function refineAnalysisForDependencyCycles(analysis, expression, schema, alias) {
326
+ if (analysis.errors.length === 0 || !schema.graph) return analysis;
327
+ const currentId = alias ? schema.cstByAlias.get(alias)?.id : void 0;
328
+ const expressionGlobals = extractGlobals(expression);
329
+ const draftGraph = currentId !== void 0 ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;
330
+ let changed = false;
331
+ const errors = analysis.errors.map((error) => {
332
+ if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) return error;
333
+ const missingAlias = error.params?.[0];
334
+ if (!missingAlias) return error;
335
+ const missing = schema.cstByAlias.get(missingAlias);
336
+ if (!missing) return error;
337
+ const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);
338
+ if (!cycleText) return error;
339
+ changed = true;
340
+ return {
341
+ ...error,
342
+ code: RSDiagnosticCode.schemaDependencyCycle,
343
+ params: [cycleText]
344
+ };
313
345
  });
346
+ return changed ? {
347
+ ...analysis,
348
+ errors
349
+ } : analysis;
350
+ }
351
+ /**
352
+ * Clone the schema graph and replace dependencies of `currentId` with globals from the
353
+ * expression under check (unsaved draft).
354
+ */
355
+ function buildDraftDependencyGraph(schema, currentId, expressionGlobals) {
356
+ const graph = schema.graph.clone();
357
+ const node = graph.at(currentId);
358
+ if (node) for (const parentId of [...node.inputs]) graph.removeEdge(parentId, currentId);
359
+ else graph.addNode(currentId);
360
+ for (const globalAlias of expressionGlobals) {
361
+ const source = schema.cstByAlias.get(globalAlias);
362
+ if (source) graph.addEdge(source.id, currentId);
363
+ }
364
+ return graph;
365
+ }
366
+ function resolveDependencyCycleText(schema, graph, currentId, missingId) {
367
+ for (const cycle of graph.findCycles()) {
368
+ const members = new Set(cycle);
369
+ if (!members.has(missingId)) continue;
370
+ if (currentId !== void 0 && !members.has(currentId)) continue;
371
+ return formatDependencyCycle(cycle.map((id) => schema.cstByID.get(id)?.alias ?? String(id)));
372
+ }
373
+ if (currentId === void 0) return (schema.cstByID.get(missingId)?.diagnostics.find((item) => item.code === RSDiagnosticCode.schemaDependencyCycle))?.params?.[0] ?? null;
374
+ return null;
314
375
  }
315
376
  /** Calculate statistics for {@link RSForm}. */
316
377
  function calculateSchemaStats(target) {
@@ -345,8 +406,10 @@ function calculateSchemaStats(target) {
345
406
  }
346
407
  /** Finds {@link Constituenta} by structure path. */
347
408
  function findCstByStructure(schema, target, path) {
348
- for (const cst of schema.items) if (cst.spawner === target.id && cst.spawner_path) {
349
- if (cst.spawner_path.length === path.length && cst.spawner_path.every((v, i) => v === path[i])) return cst;
409
+ for (const cst of schema.items) {
410
+ if (!cst.spawner_path) continue;
411
+ const absolutePath = resolveAbsoluteSpawnerPath(schema, cst, target.id);
412
+ if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) return cst;
350
413
  }
351
414
  return null;
352
415
  }
@@ -391,6 +454,24 @@ function isMissingConvention(cst) {
391
454
  }
392
455
  return false;
393
456
  }
457
+ function resolveAbsoluteSpawnerPath(schema, cst, targetId) {
458
+ if (!cst.spawner_path || cst.spawner == null) return null;
459
+ if (cst.spawner === targetId) return cst.spawner_path;
460
+ const byId = schema.cstByID ?? new Map(schema.items.map((item) => [item.id, item]));
461
+ const visited = /* @__PURE__ */ new Set([cst.id]);
462
+ let currentPath = [...cst.spawner_path];
463
+ let currentSpawnerId = cst.spawner;
464
+ while (currentSpawnerId != null) {
465
+ if (currentSpawnerId === targetId) return currentPath;
466
+ if (visited.has(currentSpawnerId)) return null;
467
+ visited.add(currentSpawnerId);
468
+ const parent = byId.get(currentSpawnerId);
469
+ if (!parent?.spawner_path || parent.spawner == null) return null;
470
+ currentPath = [...parent.spawner_path, ...currentPath];
471
+ currentSpawnerId = parent.spawner;
472
+ }
473
+ return null;
474
+ }
394
475
  /** Evaluate if {@link Typification} can be used to produce structure. */
395
476
  function typeCanProduceStructure(type) {
396
477
  if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) return false;
@@ -399,9 +480,6 @@ function typeCanProduceStructure(type) {
399
480
  }
400
481
  //#endregion
401
482
  //#region src/library/diagnostics.ts
402
- /**
403
- * Module: Compact diagnostics for constituents (schema and model issue codes).
404
- */
405
483
  /** Origin of a diagnostic. */
406
484
  const DiagnosticKind = {
407
485
  EXPRESSION: "expression",
@@ -415,6 +493,7 @@ const RSDiagnosticCode = {
415
493
  schemaMissingConvention: 35075,
416
494
  schemaMissingTerm: 35076,
417
495
  schemaTypeMismatch: 35077,
496
+ schemaDependencyCycle: 35078,
418
497
  modelEmpty: 35088,
419
498
  modelAxiomFalse: 35089,
420
499
  modelInvalidData: 35090,
@@ -425,15 +504,19 @@ function hasCstDiagnostic(cst, code) {
425
504
  return cst.diagnostics?.some((item) => item.code === code) ?? false;
426
505
  }
427
506
  /**
428
- * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch).
507
+ * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).
429
508
  *
430
509
  * Requires normalized formal definitions for duplicate detection (same as Portal loader).
510
+ * When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.
431
511
  */
432
- function assignSchemaDiagnostics(items, resolveAlias, normalizedDefinitions) {
512
+ function assignSchemaDiagnostics(items, resolveAlias, normalizedDefinitions, graph) {
433
513
  const homonymById = detectHomonymDiagnostics(items, resolveAlias);
434
514
  const duplicateById = detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions);
515
+ const cycleById = graph ? detectDependencyCycleDiagnostics(graph, resolveAlias) : /* @__PURE__ */ new Map();
435
516
  for (const cst of items) {
436
517
  const diagnostics = [];
518
+ const cycle = cycleById.get(cst.id);
519
+ if (cycle) diagnostics.push(cycle);
437
520
  const homonym = homonymById.get(cst.id);
438
521
  if (homonym) diagnostics.push(homonym);
439
522
  const duplicate = duplicateById.get(cst.id);
@@ -442,6 +525,28 @@ function assignSchemaDiagnostics(items, resolveAlias, normalizedDefinitions) {
442
525
  cst.diagnostics = diagnostics;
443
526
  }
444
527
  }
528
+ /** Format a closed cycle of aliases as `A → B → A`. */
529
+ function formatDependencyCycle(aliases) {
530
+ return aliases.join(" → ");
531
+ }
532
+ /**
533
+ * Map each node id that participates in a dependency cycle to a schema diagnostic.
534
+ * `params[0]` is the closed cycle path (`F3 → P1 → F3`).
535
+ */
536
+ function detectDependencyCycleDiagnostics(graph, resolveAlias) {
537
+ const result = /* @__PURE__ */ new Map();
538
+ for (const cycle of graph.findCycles()) {
539
+ if (cycle.length < 2) continue;
540
+ const cycleText = formatDependencyCycle(cycle.map((id) => resolveAlias(id)));
541
+ const memberIds = new Set(cycle);
542
+ for (const id of memberIds) result.set(id, {
543
+ kind: DiagnosticKind.SCHEMA,
544
+ code: RSDiagnosticCode.schemaDependencyCycle,
545
+ params: [cycleText]
546
+ });
547
+ }
548
+ return result;
549
+ }
445
550
  /** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */
446
551
  function modelStatusCstDiagnostic(status, cstType) {
447
552
  const code = modelStatusToCode(status, cstType);
@@ -471,51 +576,37 @@ function collectLocalSchemaDiagnostics(cst) {
471
576
  }
472
577
  return result;
473
578
  }
474
- function detectHomonymDiagnostics(items, resolveAlias) {
475
- const byTerm = /* @__PURE__ */ new Map();
579
+ function detectGroupedAliasDiagnostics(items, resolveAlias, groupKey, code) {
580
+ const groups = /* @__PURE__ */ new Map();
476
581
  for (const cst of items) {
477
- const key = cst.term_resolved.trim().toLocaleLowerCase();
478
- if (key === "") continue;
479
- const group = byTerm.get(key) ?? [];
582
+ const key = groupKey(cst);
583
+ if (!key) continue;
584
+ const group = groups.get(key) ?? [];
480
585
  group.push(cst);
481
- byTerm.set(key, group);
586
+ groups.set(key, group);
482
587
  }
483
588
  const result = /* @__PURE__ */ new Map();
484
- for (const group of byTerm.values()) {
589
+ for (const group of groups.values()) {
485
590
  if (group.length <= 1) continue;
486
591
  for (const cst of group) {
487
592
  const aliases = group.filter((other) => other.id !== cst.id).map((other) => resolveAlias(other.id)).join(", ");
488
593
  result.set(cst.id, {
489
594
  kind: DiagnosticKind.SCHEMA,
490
- code: RSDiagnosticCode.schemaHomonym,
595
+ code,
491
596
  params: [aliases]
492
597
  });
493
598
  }
494
599
  }
495
600
  return result;
496
601
  }
602
+ function detectHomonymDiagnostics(items, resolveAlias) {
603
+ return detectGroupedAliasDiagnostics(items, resolveAlias, (cst) => {
604
+ const key = cst.term_resolved.trim().toLocaleLowerCase();
605
+ return key === "" ? void 0 : key;
606
+ }, RSDiagnosticCode.schemaHomonym);
607
+ }
497
608
  function detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions) {
498
- const byDefinition = /* @__PURE__ */ new Map();
499
- for (const cst of items) {
500
- const key = normalizedDefinitions.get(cst.id);
501
- if (!key) continue;
502
- const group = byDefinition.get(key) ?? [];
503
- group.push(cst);
504
- byDefinition.set(key, group);
505
- }
506
- const result = /* @__PURE__ */ new Map();
507
- for (const group of byDefinition.values()) {
508
- if (group.length <= 1) continue;
509
- for (const cst of group) {
510
- const aliases = group.filter((other) => other.id !== cst.id).map((other) => resolveAlias(other.id)).join(", ");
511
- result.set(cst.id, {
512
- kind: DiagnosticKind.SCHEMA,
513
- code: RSDiagnosticCode.schemaFormalDuplicate,
514
- params: [aliases]
515
- });
516
- }
517
- }
518
- return result;
609
+ return detectGroupedAliasDiagnostics(items, resolveAlias, (cst) => normalizedDefinitions.get(cst.id), RSDiagnosticCode.schemaFormalDuplicate);
519
610
  }
520
611
  function modelStatusToCode(status, cstType) {
521
612
  switch (status) {
@@ -527,6 +618,6 @@ function modelStatusToCode(status, cstType) {
527
618
  }
528
619
  }
529
620
  //#endregion
530
- export { isTemplateCst as A, inferTemplate as C, isFunctional as D, isBasicConcept as E, validateAliasFormat as F, validateNewAlias as I, removeAliasReference as M, sortItemsForInlineSynthesis as N, isLogical as O, typeClassForCstType as P, inferStatus as S, isBaseSet as T, getCstTypePrefix as _, modelStatusCstDiagnostic as a, inferClass as b, applyMappingToConstituents as c, canHaveFormalDefinition as d, canHaveManualTypification as f, getAnalysisFor as g, generateAlias as h, hasCstDiagnostic as i, normalizeExpression as j, isSchemaIssue as k, argumentValuesToMapping as l, findCstByStructure as m, RSDiagnosticCode as n, addAliasReference as o, canProduceStructure as p, assignSchemaDiagnostics as r, applyFilterCategory as s, DiagnosticKind as t, calculateSchemaStats as u, getStructureName as v, inferTemplatedType as w, inferNewSpawnPosition as x, guessCstType as y };
621
+ export { isLogical as A, inferNewSpawnPosition as C, isBaseSet as D, inferTemplatedType as E, removeAliasReference as F, sortItemsForInlineSynthesis as I, typeClassForCstType as L, isTemplateCst as M, normalizeExpression as N, isBasicConcept as O, refineAnalysisForDependencyCycles as P, validateAliasFormat as R, inferClass as S, inferTemplate as T, generateAlias as _, formatDependencyCycle as a, getStructureName as b, addAliasReference as c, argumentValuesToMapping as d, calculateSchemaStats as f, findCstByStructure as g, canProduceStructure as h, detectDependencyCycleDiagnostics as i, isSchemaIssue as j, isFunctional as k, applyFilterCategory as l, canHaveManualTypification as m, RSDiagnosticCode as n, hasCstDiagnostic as o, canHaveFormalDefinition as p, assignSchemaDiagnostics as r, modelStatusCstDiagnostic as s, DiagnosticKind as t, applyMappingToConstituents as u, getAnalysisFor as v, inferStatus as w, guessCstType as x, getCstTypePrefix as y, validateNewAlias as z };
531
622
 
532
- //# sourceMappingURL=diagnostics-DYMvTSev.js.map
623
+ //# sourceMappingURL=diagnostics-BSryP66e.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics-BSryP66e.js","names":[],"sources":["../src/library/rsform-api.ts","../src/library/diagnostics.ts"],"sourcesContent":["/**\n * Module: API for formal representation for systems of concepts.\n */\n\nimport { applyEntityReferenceMapping } from '../cctext/language-api';\nimport { type Graph } from '../graph';\nimport { type AstNode } from '../parsing';\nimport {\n type AnalysisFull,\n RSErrorCode,\n TypeClass,\n TypeID,\n type TypePath,\n type Typification,\n ValueClass\n} from '../rslang';\nimport {\n type AliasMapping,\n applyAliasMapping,\n applyTypificationMapping,\n extractGlobals,\n generateExpressionFromAst,\n parseRSLangExpression\n} from '../rslang/api';\nimport { basic, bool, constant, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';\nimport { applyPath } from '../rslang/semantic/typification-api';\n\nimport { formatDependencyCycle, hasCstDiagnostic, RSDiagnosticCode } from './diagnostics';\nimport { type LibraryItem } from './library';\nimport {\n type ArgumentValue,\n type Constituenta,\n CstClass,\n CstStatus,\n CstType,\n type RSForm,\n type RSFormStats\n} from './rsform';\n\n/** Record of {@link CstType} prefixes. */\nconst CST_TYPE_PREFIX: Record<CstType, string> = {\n [CstType.NOMINAL]: 'N',\n [CstType.BASE]: 'X',\n [CstType.CONSTANT]: 'C',\n [CstType.STRUCTURED]: 'S',\n [CstType.AXIOM]: 'A',\n [CstType.TERM]: 'D',\n [CstType.FUNCTION]: 'F',\n [CstType.PREDICATE]: 'P',\n [CstType.STATEMENT]: 'T'\n};\n\n/** Record of {@link CstType} to {@link CstClass} mapping. */\nconst CST_TYPE_TO_CLASS: Record<CstType, CstClass> = {\n [CstType.NOMINAL]: CstClass.NOMINAL,\n [CstType.BASE]: CstClass.BASIC,\n [CstType.CONSTANT]: CstClass.BASIC,\n [CstType.STRUCTURED]: CstClass.BASIC,\n [CstType.TERM]: CstClass.DERIVED,\n [CstType.FUNCTION]: CstClass.DERIVED,\n [CstType.AXIOM]: CstClass.STATEMENT,\n [CstType.PREDICATE]: CstClass.DERIVED,\n [CstType.STATEMENT]: CstClass.STATEMENT\n};\n\n/** Checks if {@link Constituenta} is a schema issue. */\nexport function isSchemaIssue(cst: Constituenta): boolean {\n return (\n (cst.diagnostics?.length ?? 0) > 0 || cst.status === CstStatus.INCORRECT || cst.status === CstStatus.INCALCULABLE\n );\n}\n\n/** Infers the status of an expression based on parsing and value information. */\nexport function inferStatus(parse: boolean, value?: ValueClass | null): CstStatus {\n if (!parse) {\n return CstStatus.INCORRECT;\n }\n if (value === null) {\n return CstStatus.INCALCULABLE;\n }\n if (value === ValueClass.PROPERTY) {\n return CstStatus.PROPERTY;\n }\n return CstStatus.VERIFIED;\n}\n\n/** Infers type of constituent for a given template and arguments. */\nexport function inferTemplatedType(templateType: CstType, args: ArgumentValue[]): CstType {\n if (args.length === 0 || args.some(arg => !arg.value)) {\n return templateType;\n } else if (templateType === CstType.PREDICATE) {\n return CstType.AXIOM;\n } else {\n return CstType.TERM;\n }\n}\n\n/** Build alias mapping from template argument bindings. */\nexport function argumentValuesToMapping(args: ArgumentValue[]): AliasMapping {\n const mapping: AliasMapping = {};\n for (const arg of args) {\n if (arg.value) {\n mapping[arg.alias] = arg.value;\n }\n }\n return mapping;\n}\n\n/**\n * Normalize a RSLang expression for duplicate comparison.\n *\n * Returns `null` for basic concepts without formal definitions. Pass a pre-parsed `ast`\n * when the expression was already analyzed to avoid re-parsing.\n */\nexport function normalizeExpression(expression: string, cst_type: CstType, ast?: AstNode | null): string | null {\n if (isBasicConcept(cst_type) && cst_type !== CstType.AXIOM) {\n return null;\n }\n const parsed = ast ?? parseRSLangExpression(expression);\n let normalized = '';\n if (parsed && !parsed.hasError) {\n normalized = generateExpressionFromAst(parsed, { normalize: true });\n } else {\n normalized = expression;\n }\n normalized = normalized.replace(/\\s+/g, '');\n return normalized === '' ? null : normalized;\n}\n\n/** Checks if given expression is a template. */\nexport function inferTemplate(expression: string): boolean {\n const match = expression.match(/R\\d+/g);\n return (match && match?.length > 0) ?? false;\n}\n\n/** Infers the {@link CstClass} based on the provided {@link CstType} and template status. */\nexport function inferClass(type: CstType, isTemplate: boolean = false): CstClass {\n if (isTemplate) {\n return CstClass.TEMPLATE;\n }\n return CST_TYPE_TO_CLASS[type];\n}\n\n/** Check if {@link Constituenta} is a template or a category. */\nexport function isTemplateCst(cst: Constituenta): boolean {\n return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;\n}\n\n/** Apply filter based on start {@link Constituenta} type. */\nexport function applyFilterCategory(start: Constituenta, items: Constituenta[]): Constituenta[] {\n const startIndex = items.indexOf(start);\n if (startIndex === -1) {\n return [];\n }\n const nextCategoryIndex = items.findIndex((cst, index) => index > startIndex && cst.cst_type === CstType.STATEMENT);\n\n return items.filter((_, index) => index >= startIndex && (nextCategoryIndex === -1 || index < nextCategoryIndex));\n}\n\n/** Prefix for alias indicating {@link CstType}. */\nexport function getCstTypePrefix(type: CstType): string {\n return CST_TYPE_PREFIX[type];\n}\n\n/** Guess {@link CstType} from user input hint. */\nexport function guessCstType(hint: string): CstType | null {\n if (hint.length !== 1) {\n return null;\n }\n for (const [type, prefix] of Object.entries(CST_TYPE_PREFIX)) {\n if (hint === prefix) {\n return type as CstType;\n }\n }\n return null;\n}\n\n/** Evaluate if {@link CstType} is basic concept. */\nexport function isBasicConcept(type: CstType): boolean {\n switch (type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n return true;\n\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is base set or constant set. */\nexport function isBaseSet(type: CstType): boolean {\n switch (type) {\n case CstType.BASE:\n case CstType.CONSTANT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is a function. */\nexport function isFunctional(type: CstType): boolean {\n switch (type) {\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.AXIOM:\n case CstType.TERM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is logical. */\nexport function isLogical(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link Constituenta} can be used produce structure. */\nexport function canProduceStructure(cst: Constituenta): boolean {\n switch (cst.cst_type) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.PREDICATE:\n return false;\n }\n if (!cst.effectiveType) {\n return false;\n }\n if (cst.cst_type === CstType.FUNCTION) {\n const result = (cst.effectiveType as EchelonFunctional).result;\n return typeCanProduceStructure(result);\n }\n if (!isTypification(cst.effectiveType)) {\n return false;\n }\n return typeCanProduceStructure(cst.effectiveType as Typification);\n}\n\n/** Evaluate if {@link CstType} can have manual typification. */\nexport function canHaveManualTypification(type: CstType): boolean {\n switch (type) {\n case CstType.STRUCTURED:\n case CstType.TERM:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return false;\n }\n}\n\n/** Validate alias format for a given {@link CstType} (prefix + digits, min length 2). */\nexport function validateAliasFormat(alias: string, type: CstType): boolean {\n if (alias.length < 2) {\n return false;\n }\n const prefix = getCstTypePrefix(type);\n if (!alias.startsWith(prefix)) {\n return false;\n }\n if (!/^\\d+$/.exec(alias.substring(prefix.length))) {\n return false;\n }\n return true;\n}\n\n/** Validate new alias against {@link CstType} and {@link RSForm}. */\nexport function validateNewAlias(alias: string, type: CstType, schema: RSForm): boolean {\n if (!validateAliasFormat(alias, type)) {\n return false;\n }\n if (schema.cstByAlias.has(alias)) {\n return false;\n }\n return true;\n}\n\n/** Generate alias for new {@link Constituenta} of a given {@link CstType} for current {@link RSForm}. */\nexport function generateAlias(type: CstType, schema: RSForm, takenAliases: string[] = []): string {\n const prefix = getCstTypePrefix(type);\n if (schema.items.length <= 0) {\n return `${prefix}1`;\n }\n let index = schema.items.reduce((prev, cst, index) => {\n if (cst.cst_type !== type) {\n return prev;\n }\n index = Number(cst.alias.slice(1 - cst.alias.length)) + 1;\n return Math.max(prev, index);\n }, 1);\n let alias = `${prefix}${index}`;\n while (takenAliases.includes(alias)) {\n index = index + 1;\n alias = `${prefix}${index}`;\n }\n return alias;\n}\n\n/**\n * Id to pass as `insert_after` when creating a new {@link Constituenta} spawned by `targetId`:\n * after the last existing child of that spawner, or after the spawner itself if none.\n */\nexport function inferNewSpawnPosition(schema: RSForm, targetId: number): number {\n let last: number | null = null;\n for (const cst of schema.items) {\n if (cst.spawner === targetId) {\n last = cst.id;\n }\n }\n return last ?? targetId;\n}\n\n/** Sorts library items relevant for InlineSynthesis with specified {@link RSForm}. */\nexport function sortItemsForInlineSynthesis(receiver: RSForm, items: readonly LibraryItem[]): LibraryItem[] {\n const result = items.filter(item => item.location === receiver.location);\n for (const item of items) {\n if (item.visible && item.owner === item.owner && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (item.visible && !result.includes(item)) {\n result.push(item);\n }\n }\n for (const item of items) {\n if (!result.includes(item)) {\n result.push(item);\n }\n }\n return result;\n}\n\n/** Fields of {@link Constituenta} updated in place by alias mapping. */\nexport interface ConstituentaMappableFields {\n alias: string;\n definition_formal: string;\n typification_manual: string;\n term_raw: string;\n definition_raw: string;\n}\n\n/**\n * Remap formal expressions and terminological entity references in constituent fields.\n * Mutates each element of `items` in place; pass owned or cloned data only.\n */\nexport function applyMappingToConstituents<T extends ConstituentaMappableFields>(\n items: T[],\n mapping: AliasMapping,\n changeAliases: boolean\n): void {\n for (const cst of items) {\n if (changeAliases && cst.alias in mapping) {\n cst.alias = mapping[cst.alias];\n }\n cst.definition_formal = applyAliasMapping(cst.definition_formal, mapping);\n cst.typification_manual = applyTypificationMapping(cst.typification_manual, mapping);\n cst.term_raw = applyEntityReferenceMapping(cst.term_raw, mapping);\n cst.definition_raw = applyEntityReferenceMapping(cst.definition_raw, mapping);\n }\n}\n\n/** Remove alias from expression. */\nexport function removeAliasReference(expression: string, alias: string): string {\n const result = expression.replaceAll(new RegExp(`\\\\b${alias}\\\\b`, 'g'), 'DEL');\n return result === 'DEL' ? '' : result;\n}\n\n/** Add alias to expression. */\nexport function addAliasReference(expression: string, alias: string): string {\n return expression + ' ' + alias;\n}\n\n/** Returns expected {@link TypeClass} of formal definition for {@link CstType}. */\nexport function typeClassForCstType(cstType: CstType): TypeClass {\n switch (cstType) {\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.TERM:\n return TypeClass.typification;\n case CstType.FUNCTION:\n return TypeClass.function;\n case CstType.PREDICATE:\n return TypeClass.predicate;\n case CstType.AXIOM:\n case CstType.STATEMENT:\n return TypeClass.logic;\n }\n}\n\n/** Checks whether a constituenta type supports formal definitions. */\nexport function canHaveFormalDefinition(cstType: CstType): boolean {\n return cstType !== CstType.BASE && cstType !== CstType.CONSTANT;\n}\n\n/** Analyze expression for {@link RSForm}. */\nexport function getAnalysisFor(expression: string, cstType: CstType, schema: RSForm, alias?: string): AnalysisFull {\n if (!canHaveFormalDefinition(cstType)) {\n if (expression.trim().length === 0) {\n const fallbackAlias = alias && alias.length > 0 ? alias : 'X0';\n const type = cstType === CstType.BASE ? bool(basic(fallbackAlias)) : bool(constant(fallbackAlias));\n return {\n success: true,\n type,\n valueClass: ValueClass.VALUE,\n errors: [],\n ast: null\n };\n }\n return {\n success: false,\n type: null,\n valueClass: null,\n errors: [\n {\n code: RSErrorCode.definitionNotAllowed,\n from: 0,\n to: Math.max(expression.length, 1),\n params: [cstType, alias ?? '']\n }\n ],\n ast: null\n };\n }\n const analysis = schema.analyzer.checkFull(expression, {\n expected: typeClassForCstType(cstType),\n isDomain: cstType === CstType.STRUCTURED\n });\n return refineAnalysisForDependencyCycles(analysis, expression, schema, alias);\n}\n\n/**\n * When an untyped / bare F·P reference names a constituent on a definition cycle with the\n * current expression, replace that error with {@link RSDiagnosticCode.schemaDependencyCycle}.\n *\n * Covers both semantic `globalNotTyped` (e.g. `F3[σ]`) and parser `globalFuncWithoutArgs`\n * (bare `P1` / `F1` treated as a call without arguments).\n *\n * Uses a draft dependency graph: incoming edges of the edited constituent are taken from\n * `expression`, so Check works before Save.\n */\nexport function refineAnalysisForDependencyCycles(\n analysis: AnalysisFull,\n expression: string,\n schema: RSForm,\n alias?: string\n): AnalysisFull {\n if (analysis.errors.length === 0 || !schema.graph) {\n return analysis;\n }\n\n const currentId = alias ? schema.cstByAlias.get(alias)?.id : undefined;\n const expressionGlobals = extractGlobals(expression);\n const draftGraph =\n currentId !== undefined ? buildDraftDependencyGraph(schema, currentId, expressionGlobals) : schema.graph;\n\n let changed = false;\n const errors = analysis.errors.map(error => {\n if (error.code !== RSErrorCode.globalNotTyped && error.code !== RSErrorCode.globalFuncWithoutArgs) {\n return error;\n }\n const missingAlias = error.params?.[0];\n if (!missingAlias) {\n return error;\n }\n const missing = schema.cstByAlias.get(missingAlias);\n if (!missing) {\n return error;\n }\n const cycleText = resolveDependencyCycleText(schema, draftGraph, currentId, missing.id);\n if (!cycleText) {\n return error;\n }\n changed = true;\n return {\n ...error,\n code: RSDiagnosticCode.schemaDependencyCycle as unknown as RSErrorCode,\n params: [cycleText]\n };\n });\n return changed ? { ...analysis, errors } : analysis;\n}\n\n/**\n * Clone the schema graph and replace dependencies of `currentId` with globals from the\n * expression under check (unsaved draft).\n */\nfunction buildDraftDependencyGraph(schema: RSForm, currentId: number, expressionGlobals: ReadonlySet<string>): Graph {\n const graph = schema.graph.clone();\n const node = graph.at(currentId);\n if (node) {\n for (const parentId of [...node.inputs]) {\n graph.removeEdge(parentId, currentId);\n }\n } else {\n graph.addNode(currentId);\n }\n for (const globalAlias of expressionGlobals) {\n const source = schema.cstByAlias.get(globalAlias);\n if (source) {\n graph.addEdge(source.id, currentId);\n }\n }\n return graph;\n}\n\nfunction resolveDependencyCycleText(\n schema: RSForm,\n graph: Graph,\n currentId: number | undefined,\n missingId: number\n): string | null {\n for (const cycle of graph.findCycles()) {\n const members = new Set(cycle);\n if (!members.has(missingId)) {\n continue;\n }\n if (currentId !== undefined && !members.has(currentId)) {\n continue;\n }\n return formatDependencyCycle(cycle.map(id => schema.cstByID.get(id)?.alias ?? String(id)));\n }\n\n if (currentId === undefined) {\n const cycleDiag = schema.cstByID\n .get(missingId)\n ?.diagnostics.find(item => item.code === RSDiagnosticCode.schemaDependencyCycle);\n return cycleDiag?.params?.[0] ?? null;\n }\n\n return null;\n}\n\n/** Calculate statistics for {@link RSForm}. */\nexport function calculateSchemaStats(target: RSForm): RSFormStats {\n const items = target.items;\n return {\n count_all: items.length,\n count_crucial: items.reduce((sum, cst) => sum + (cst.crucial ? 1 : 0), 0),\n\n step_complexity: items.reduce((sum, cst) => sum + calculateStepComplexity(cst), 0),\n\n count_problematic: items.reduce((sum, cst) => sum + (isSchemaIssue(cst) ? 1 : 0), 0),\n count_homonyms: items.reduce(\n (sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaHomonym) ? 1 : 0),\n 0\n ),\n count_formal_duplicates: items.reduce(\n (sum, cst) => sum + (hasCstDiagnostic(cst, RSDiagnosticCode.schemaFormalDuplicate) ? 1 : 0),\n 0\n ),\n count_missing_convention: items.reduce((sum, cst) => sum + (isMissingConvention(cst) ? 1 : 0), 0),\n count_type_mismatch: items.reduce((sum, cst) => sum + (cst.is_type_mismatch ? 1 : 0), 0),\n\n count_incorrect: items.reduce((sum, cst) => sum + (cst.status === CstStatus.INCORRECT ? 1 : 0), 0),\n count_property: items.reduce((sum, cst) => sum + (cst.analysis?.valueClass === ValueClass.PROPERTY ? 1 : 0), 0),\n count_incalculable: items.reduce(\n (sum, cst) => sum + (cst.analysis?.success && cst.analysis.valueClass === null ? 1 : 0),\n 0\n ),\n count_inherited: items.reduce((sum, cst) => sum + (cst.is_inherited ? 1 : 0), 0),\n\n count_text_term: items.reduce((sum, cst) => sum + (cst.term_raw ? 1 : 0), 0),\n count_definition: items.reduce((sum, cst) => sum + (cst.definition_raw ? 1 : 0), 0),\n count_convention: items.reduce((sum, cst) => sum + (isBasicConcept(cst.cst_type) && cst.convention ? 1 : 0), 0),\n count_comment: items.reduce((sum, cst) => sum + (!isBasicConcept(cst.cst_type) && !cst.convention ? 1 : 0), 0),\n\n count_base: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.BASE ? 1 : 0), 0),\n count_constant: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.CONSTANT ? 1 : 0), 0),\n count_structured: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STRUCTURED ? 1 : 0), 0),\n count_axiom: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.AXIOM ? 1 : 0), 0),\n count_term: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.TERM ? 1 : 0), 0),\n count_function: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.FUNCTION ? 1 : 0), 0),\n count_predicate: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.PREDICATE ? 1 : 0), 0),\n count_statement: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.STATEMENT ? 1 : 0), 0),\n count_nominal: items.reduce((sum, cst) => sum + (cst.cst_type === CstType.NOMINAL ? 1 : 0), 0)\n };\n}\n\n/** Finds {@link Constituenta} by structure path. */\nexport function findCstByStructure(schema: RSForm, target: Constituenta, path: TypePath): Constituenta | null {\n for (const cst of schema.items) {\n if (!cst.spawner_path) {\n continue;\n }\n const absolutePath = resolveAbsoluteSpawnerPath(schema, cst, target.id);\n if (absolutePath?.length === path.length && absolutePath.every((v, i) => v === path[i])) {\n return cst;\n }\n }\n return null;\n}\n\n/** Retrieves name for piece of target {@link Constituenta} structure. */\nexport function getStructureName(schema: RSForm, target: Constituenta, path: TypePath): string {\n const representation = findCstByStructure(schema, target, path);\n if (representation) {\n return `${representation.alias}: ${representation.term_resolved}`;\n }\n if (!isTypification(target.effectiveType)) {\n return '';\n }\n const type = applyPath(target.effectiveType as Typification, path);\n if (type?.typeID === TypeID.basic) {\n const cst = schema.cstByAlias.get(type.baseID);\n if (cst?.term_resolved) {\n return `${cst.alias}: ${cst.term_resolved}`;\n }\n }\n return '';\n}\n\n// ========= Internals =====\nfunction calculateStepComplexity(cst: Constituenta): number {\n if (cst.cst_type === CstType.AXIOM || cst.cst_type === CstType.NOMINAL || !isBasicConcept(cst.cst_type)) {\n return 0;\n }\n if (cst.cst_type === CstType.BASE || cst.cst_type === CstType.CONSTANT || !cst.effectiveType) {\n return 1;\n }\n\n const type = cst.effectiveType as Typification;\n return calculateTypificationComplexity(type) + 1;\n}\n\nfunction calculateTypificationComplexity(type: Typification): number {\n switch (type.typeID) {\n case TypeID.basic:\n case TypeID.integer:\n case TypeID.anyTypification:\n return 0;\n case TypeID.tuple:\n return (\n type.factors.length + type.factors.reduce((sum, factor) => sum + calculateTypificationComplexity(factor), 0)\n );\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n let sum = 0;\n type.base.factors.forEach(factor => {\n sum += calculateTypificationComplexity(factor);\n });\n return sum + type.base.factors.length;\n } else if (type.base.typeID === TypeID.collection) {\n return calculateTypificationComplexity(type.base) + 1;\n }\n return 0;\n }\n}\n\nfunction isMissingConvention(cst: Constituenta): boolean {\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention || !cst.term_resolved) {\n return true;\n }\n }\n return false;\n}\n\nfunction resolveAbsoluteSpawnerPath(schema: RSForm, cst: Constituenta, targetId: number): TypePath | null {\n if (!cst.spawner_path || cst.spawner == null) {\n return null;\n }\n if (cst.spawner === targetId) {\n return cst.spawner_path;\n }\n\n const byId = schema.cstByID ?? new Map(schema.items.map(item => [item.id, item]));\n const visited = new Set<number>([cst.id]);\n let currentPath: number[] = [...cst.spawner_path];\n let currentSpawnerId: number | null = cst.spawner;\n\n while (currentSpawnerId != null) {\n if (currentSpawnerId === targetId) {\n return currentPath as TypePath;\n }\n if (visited.has(currentSpawnerId)) {\n return null;\n }\n visited.add(currentSpawnerId);\n\n const parent = byId.get(currentSpawnerId);\n if (!parent?.spawner_path || parent.spawner == null) {\n return null;\n }\n\n currentPath = [...parent.spawner_path, ...currentPath];\n currentSpawnerId = parent.spawner;\n }\n\n return null;\n}\n\n/** Evaluate if {@link Typification} can be used to produce structure. */\nfunction typeCanProduceStructure(type: Typification): boolean {\n if (type.typeID === TypeID.basic || type.typeID === TypeID.integer || type.typeID === TypeID.anyTypification) {\n return false;\n } else if (type.typeID === TypeID.tuple) {\n return true;\n } else {\n return (\n type.base.typeID !== TypeID.basic &&\n type.base.typeID !== TypeID.integer &&\n type.base.typeID !== TypeID.anyTypification\n );\n }\n}\n","/**\n * Module: Compact diagnostics for constituents (schema and model issue codes).\n */\n\nimport { type Graph } from '../graph';\nimport { labelType } from '../rslang/labels';\n\nimport { type Constituenta, type CstType } from './rsform';\nimport { isBasicConcept, isLogical } from './rsform-api';\nimport { EvalStatus } from './rsmodel';\n\n/** Origin of a diagnostic. */\nexport const DiagnosticKind = {\n EXPRESSION: 'expression',\n SCHEMA: 'schema',\n MODEL: 'model'\n} as const;\nexport type DiagnosticKind = (typeof DiagnosticKind)[keyof typeof DiagnosticKind];\n\n/** Schema and model diagnostic codes (same numeric format as {@link RSErrorCode}). */\nexport const RSDiagnosticCode = {\n schemaHomonym: 0x8901,\n schemaFormalDuplicate: 0x8902,\n schemaMissingConvention: 0x8903,\n schemaMissingTerm: 0x8904,\n schemaTypeMismatch: 0x8905,\n schemaDependencyCycle: 0x8906,\n\n modelEmpty: 0x8910,\n modelAxiomFalse: 0x8911,\n modelInvalidData: 0x8912,\n modelEvalFail: 0x8913\n} as const;\nexport type RSDiagnosticCode = (typeof RSDiagnosticCode)[keyof typeof RSDiagnosticCode];\n\n/** Compact diagnostic stored on {@link Constituenta} after schema loading. */\nexport interface CstDiagnostic {\n kind: DiagnosticKind;\n code: number;\n /** Positional message arguments (per-code; homonyms/duplicates use `[aliases]`). */\n params?: readonly string[];\n}\n\n/** Whether a constituent has a schema/model diagnostic with the given code. */\nexport function hasCstDiagnostic(cst: Constituenta, code: RSDiagnosticCode): boolean {\n return cst.diagnostics?.some(item => item.code === code) ?? false;\n}\n\n/**\n * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).\n *\n * Requires normalized formal definitions for duplicate detection (same as Portal loader).\n * When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.\n */\nexport function assignSchemaDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>,\n graph?: Graph\n): void {\n const homonymById = detectHomonymDiagnostics(items, resolveAlias);\n const duplicateById = detectFormalDuplicateDiagnostics(items, resolveAlias, normalizedDefinitions);\n const cycleById = graph ? detectDependencyCycleDiagnostics(graph, resolveAlias) : new Map<number, CstDiagnostic>();\n\n for (const cst of items) {\n const diagnostics: CstDiagnostic[] = [];\n const cycle = cycleById.get(cst.id);\n if (cycle) {\n diagnostics.push(cycle);\n }\n const homonym = homonymById.get(cst.id);\n if (homonym) {\n diagnostics.push(homonym);\n }\n const duplicate = duplicateById.get(cst.id);\n if (duplicate) {\n diagnostics.push(duplicate);\n }\n diagnostics.push(...collectLocalSchemaDiagnostics(cst));\n cst.diagnostics = diagnostics;\n }\n}\n\n/** Format a closed cycle of aliases as `A → B → A`. */\nexport function formatDependencyCycle(aliases: readonly string[]): string {\n return aliases.join(' → ');\n}\n\n/**\n * Map each node id that participates in a dependency cycle to a schema diagnostic.\n * `params[0]` is the closed cycle path (`F3 → P1 → F3`).\n */\nexport function detectDependencyCycleDiagnostics(\n graph: Graph,\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n const result = new Map<number, CstDiagnostic>();\n for (const cycle of graph.findCycles()) {\n if (cycle.length < 2) {\n continue;\n }\n const aliases = cycle.map(id => resolveAlias(id));\n const cycleText = formatDependencyCycle(aliases);\n const memberIds = new Set(cycle);\n for (const id of memberIds) {\n result.set(id, {\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaDependencyCycle,\n params: [cycleText]\n });\n }\n }\n return result;\n}\n\n/** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */\nexport function modelStatusCstDiagnostic(status: EvalStatus, cstType: CstType): CstDiagnostic | null {\n const code = modelStatusToCode(status, cstType);\n if (code === null) {\n return null;\n }\n return { kind: DiagnosticKind.MODEL, code, params: [String(status)] };\n}\n\nfunction collectLocalSchemaDiagnostics(cst: Constituenta): CstDiagnostic[] {\n const result: CstDiagnostic[] = [];\n if (cst.is_type_mismatch) {\n result.push({\n kind: DiagnosticKind.SCHEMA,\n code: RSDiagnosticCode.schemaTypeMismatch,\n params: [cst.typification_manual, labelType(cst.analysis.type)]\n });\n }\n if (isBasicConcept(cst.cst_type) && !isLogical(cst.cst_type)) {\n if (!cst.convention.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingConvention });\n }\n if (!cst.term_resolved.trim()) {\n result.push({ kind: DiagnosticKind.SCHEMA, code: RSDiagnosticCode.schemaMissingTerm });\n }\n }\n return result;\n}\n\nfunction detectGroupedAliasDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string,\n groupKey: (cst: Constituenta) => string | undefined,\n code: RSDiagnosticCode\n): Map<number, CstDiagnostic> {\n const groups = new Map<string, Constituenta[]>();\n for (const cst of items) {\n const key = groupKey(cst);\n if (!key) {\n continue;\n }\n const group = groups.get(key) ?? [];\n group.push(cst);\n groups.set(key, group);\n }\n\n const result = new Map<number, CstDiagnostic>();\n for (const group of groups.values()) {\n if (group.length <= 1) {\n continue;\n }\n for (const cst of group) {\n const aliases = group\n .filter(other => other.id !== cst.id)\n .map(other => resolveAlias(other.id))\n .join(', ');\n result.set(cst.id, {\n kind: DiagnosticKind.SCHEMA,\n code,\n params: [aliases]\n });\n }\n }\n return result;\n}\n\nfunction detectHomonymDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => {\n const key = cst.term_resolved.trim().toLocaleLowerCase();\n return key === '' ? undefined : key;\n },\n RSDiagnosticCode.schemaHomonym\n );\n}\n\nfunction detectFormalDuplicateDiagnostics(\n items: Constituenta[],\n resolveAlias: (id: number) => string,\n normalizedDefinitions: ReadonlyMap<number, string>\n): Map<number, CstDiagnostic> {\n return detectGroupedAliasDiagnostics(\n items,\n resolveAlias,\n cst => normalizedDefinitions.get(cst.id),\n RSDiagnosticCode.schemaFormalDuplicate\n );\n}\n\nfunction modelStatusToCode(status: EvalStatus, cstType: CstType): RSDiagnosticCode | null {\n switch (status) {\n case EvalStatus.EMPTY:\n return isBasicConcept(cstType) ? RSDiagnosticCode.modelEmpty : null;\n case EvalStatus.AXIOM_FALSE:\n return RSDiagnosticCode.modelAxiomFalse;\n case EvalStatus.INVALID_DATA:\n return RSDiagnosticCode.modelInvalidData;\n case EvalStatus.EVAL_FAIL:\n return RSDiagnosticCode.modelEvalFail;\n default:\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwCA,MAAM,kBAA2C;EAC9C,QAAQ,UAAU;EAClB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,aAAa;EACrB,QAAQ,QAAQ;EAChB,QAAQ,OAAO;EACf,QAAQ,WAAW;EACnB,QAAQ,YAAY;EACpB,QAAQ,YAAY;AACvB;;AAGA,MAAM,oBAA+C;EAClD,QAAQ,UAAU,SAAS;EAC3B,QAAQ,OAAO,SAAS;EACxB,QAAQ,WAAW,SAAS;EAC5B,QAAQ,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KAAK,SAAY;CAClC,GACA,iBAAiB,aACnB;AACF;AAEA,SAAS,iCACP,OACA,cACA,uBAC4B;CAC5B,OAAO,8BACL,OACA,eACA,QAAO,sBAAsB,IAAI,IAAI,EAAE,GACvC,iBAAiB,qBACnB;AACF;AAEA,SAAS,kBAAkB,QAAoB,SAA2C;CACxF,QAAQ,QAAR;EACE,KAAK,WAAW,OACd,OAAO,eAAe,OAAO,IAAI,iBAAiB,aAAa;EACjE,KAAK,WAAW,aACd,OAAO,iBAAiB;EAC1B,KAAK,WAAW,cACd,OAAO,iBAAiB;EAC1B,KAAK,WAAW,WACd,OAAO,iBAAiB;EAC1B,SACE,OAAO;CACX;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as Graph } from "./graph-DR8rL2o3.js";
1
+ import { t as Graph } from "./graph-DPOvglEm.js";
2
2
  import { f as ExpressionType, y as TypePath } from "./typification-9lNu9R4k.js";
3
3
  import { l as Value } from "./value-BduA_ZGp.js";
4
4
  import { a as RSLangAnalyzer, t as AnalysisBase } from "./analyzer-iqAXyROE.js";
@@ -251,6 +251,7 @@ declare const RSDiagnosticCode: {
251
251
  readonly schemaMissingConvention: 35075;
252
252
  readonly schemaMissingTerm: 35076;
253
253
  readonly schemaTypeMismatch: 35077;
254
+ readonly schemaDependencyCycle: 35078;
254
255
  readonly modelEmpty: 35088;
255
256
  readonly modelAxiomFalse: 35089;
256
257
  readonly modelInvalidData: 35090;
@@ -267,13 +268,21 @@ interface CstDiagnostic {
267
268
  /** Whether a constituent has a schema/model diagnostic with the given code. */
268
269
  declare function hasCstDiagnostic(cst: Constituenta, code: RSDiagnosticCode): boolean;
269
270
  /**
270
- * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch).
271
+ * Populate `diagnostics` on each constituent (homonyms, duplicates, metadata, type mismatch, cycles).
271
272
  *
272
273
  * Requires normalized formal definitions for duplicate detection (same as Portal loader).
274
+ * When `graph` is provided, dependency cycles are reported as {@link RSDiagnosticCode.schemaDependencyCycle}.
273
275
  */
274
- declare function assignSchemaDiagnostics(items: Constituenta[], resolveAlias: (id: number) => string, normalizedDefinitions: ReadonlyMap<number, string>): void;
276
+ declare function assignSchemaDiagnostics(items: Constituenta[], resolveAlias: (id: number) => string, normalizedDefinitions: ReadonlyMap<number, string>, graph?: Graph): void;
277
+ /** Format a closed cycle of aliases as `A → B → A`. */
278
+ declare function formatDependencyCycle(aliases: readonly string[]): string;
279
+ /**
280
+ * Map each node id that participates in a dependency cycle to a schema diagnostic.
281
+ * `params[0]` is the closed cycle path (`F3 → P1 → F3`).
282
+ */
283
+ declare function detectDependencyCycleDiagnostics(graph: Graph, resolveAlias: (id: number) => string): Map<number, CstDiagnostic>;
275
284
  /** Map a model evaluation status to a compact diagnostic, or `null` when not an issue. */
276
285
  declare function modelStatusCstDiagnostic(status: EvalStatus, cstType: CstType): CstDiagnostic | null;
277
286
  //#endregion
278
- export { TypeInfo as C, Substitution as S, CstClass as _, hasCstDiagnostic as a, RSForm as b, BasicsContext as c, RSModel as d, RSModelStats as f, Constituenta as g, Attribution as h, assignSchemaDiagnostics as i, DEFAULT_VALUE_TEXT as l, ArgumentValue as m, DiagnosticKind as n, modelStatusCstDiagnostic as o, TYPE_BASIC as p, RSDiagnosticCode as r, BasicBinding as s, CstDiagnostic as t, EvalStatus as u, CstStatus as v, RSFormStats as x, CstType as y };
279
- //# sourceMappingURL=diagnostics-Clo3mkba.d.ts.map
287
+ export { RSFormStats as C, RSForm as S, TypeInfo as T, Attribution as _, detectDependencyCycleDiagnostics as a, CstStatus as b, modelStatusCstDiagnostic as c, DEFAULT_VALUE_TEXT as d, EvalStatus as f, ArgumentValue as g, TYPE_BASIC as h, assignSchemaDiagnostics as i, BasicBinding as l, RSModelStats as m, DiagnosticKind as n, formatDependencyCycle as o, RSModel as p, RSDiagnosticCode as r, hasCstDiagnostic as s, CstDiagnostic as t, BasicsContext as u, Constituenta as v, Substitution as w, CstType as x, CstClass as y };
288
+ //# sourceMappingURL=diagnostics-Dtzgj5Q9.d.ts.map
@@ -1,2 +1,2 @@
1
- import { n as GraphNode, t as Graph } from "../graph-DR8rL2o3.js";
1
+ import { n as GraphNode, t as Graph } from "../graph-DPOvglEm.js";
2
2
  export { Graph, GraphNode };
@@ -287,7 +287,7 @@ var Graph = class Graph {
287
287
  * Finds a cycle in the graph.
288
288
  *
289
289
  * @returns {NodeID[] | null} The cycle if found, otherwise `null`.
290
- * Uses non-recursive DFS.
290
+ * Uses non-recursive DFS. The returned path is closed (first id equals last).
291
291
  */
292
292
  findCycle() {
293
293
  const visited = /* @__PURE__ */ new Set();
@@ -335,6 +335,93 @@ var Graph = class Graph {
335
335
  }
336
336
  return null;
337
337
  }
338
+ /**
339
+ * Finds one closed cycle path per cyclic strongly connected component.
340
+ *
341
+ * @returns Closed paths (first id equals last). Empty when the graph is acyclic.
342
+ */
343
+ findCycles() {
344
+ const components = this.stronglyConnectedComponents();
345
+ const result = [];
346
+ for (const component of components) {
347
+ if (component.length === 1) {
348
+ const id = component[0];
349
+ if (this.hasEdge(id, id)) result.push([id, id]);
350
+ continue;
351
+ }
352
+ const subgraph = new Graph();
353
+ const memberIds = new Set(component);
354
+ for (const id of component) {
355
+ subgraph.addNode(id);
356
+ const node = this.nodes.get(id);
357
+ if (!node) continue;
358
+ for (const child of node.outputs) if (memberIds.has(child)) subgraph.addEdge(id, child);
359
+ }
360
+ const cycle = subgraph.findCycle();
361
+ if (cycle) result.push(cycle);
362
+ }
363
+ return result;
364
+ }
365
+ /** Tarjan strongly connected components (non-recursive). */
366
+ stronglyConnectedComponents() {
367
+ let index = 0;
368
+ const indices = /* @__PURE__ */ new Map();
369
+ const lowlink = /* @__PURE__ */ new Map();
370
+ const onStack = /* @__PURE__ */ new Set();
371
+ const stack = [];
372
+ const components = [];
373
+ for (const startId of this.nodes.keys()) {
374
+ if (indices.has(startId)) continue;
375
+ const callStack = [{
376
+ nodeId: startId,
377
+ edgeIndex: 0,
378
+ entered: false
379
+ }];
380
+ while (callStack.length > 0) {
381
+ const frame = callStack[callStack.length - 1];
382
+ const node = this.nodes.get(frame.nodeId);
383
+ if (!node) {
384
+ callStack.pop();
385
+ continue;
386
+ }
387
+ if (!frame.entered) {
388
+ frame.entered = true;
389
+ indices.set(frame.nodeId, index);
390
+ lowlink.set(frame.nodeId, index);
391
+ index += 1;
392
+ stack.push(frame.nodeId);
393
+ onStack.add(frame.nodeId);
394
+ }
395
+ if (frame.edgeIndex < node.outputs.length) {
396
+ const child = node.outputs[frame.edgeIndex];
397
+ frame.edgeIndex += 1;
398
+ if (!indices.has(child)) callStack.push({
399
+ nodeId: child,
400
+ edgeIndex: 0,
401
+ entered: false
402
+ });
403
+ else if (onStack.has(child)) lowlink.set(frame.nodeId, Math.min(lowlink.get(frame.nodeId), indices.get(child)));
404
+ continue;
405
+ }
406
+ callStack.pop();
407
+ if (callStack.length > 0) {
408
+ const parentId = callStack[callStack.length - 1].nodeId;
409
+ lowlink.set(parentId, Math.min(lowlink.get(parentId), lowlink.get(frame.nodeId)));
410
+ }
411
+ if (lowlink.get(frame.nodeId) === indices.get(frame.nodeId)) {
412
+ const component = [];
413
+ while (stack.length > 0) {
414
+ const id = stack.pop();
415
+ onStack.delete(id);
416
+ component.push(id);
417
+ if (id === frame.nodeId) break;
418
+ }
419
+ components.push(component);
420
+ }
421
+ }
422
+ }
423
+ return components;
424
+ }
338
425
  };
339
426
  //#endregion
340
427
  export { Graph, GraphNode };