@rsconcept/domain 2.2.0 → 3.0.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 (55) hide show
  1. package/dist/{diagnostics-Db1F7ruF.d.ts → diagnostics-DsEhmFh0.d.ts} +6 -4
  2. package/dist/{diagnostics-B1OfMra1.js → diagnostics-ndGYbvgh.js} +374 -15
  3. package/dist/diagnostics-ndGYbvgh.js.map +1 -0
  4. package/dist/index-DpiTybDB.d.ts +376 -0
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +2 -2
  7. package/dist/library/diagnostics.d.ts +1 -1
  8. package/dist/library/diagnostics.js +1 -1
  9. package/dist/library/index.d.ts +6 -5
  10. package/dist/library/index.js +1 -1
  11. package/dist/library/index.js.map +1 -1
  12. package/dist/library/oss-api.d.ts +1 -1
  13. package/dist/library/oss-api.js +1 -1
  14. package/dist/library/oss-api.js.map +1 -1
  15. package/dist/library/rsengine.d.ts +1 -1
  16. package/dist/library/rsengine.js +2 -2
  17. package/dist/library/rsform-api/index.d.ts +2 -146
  18. package/dist/library/rsform-api/index.js +2 -2
  19. package/dist/library/rsform.d.ts +2 -2
  20. package/dist/library/rsform.js.map +1 -1
  21. package/dist/library/rsmodel-api.d.ts +9 -4
  22. package/dist/library/rsmodel-api.js +7 -3
  23. package/dist/library/rsmodel-api.js.map +1 -1
  24. package/dist/library/rsmodel.d.ts +1 -1
  25. package/dist/library/structure-planner.d.ts +1 -1
  26. package/dist/library/structure-planner.js +2 -2
  27. package/dist/library/structure-planner.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/index.ts +1 -0
  30. package/src/library/diagnostics.ts +20 -9
  31. package/src/library/index.ts +1 -0
  32. package/src/library/oss-api.ts +5 -1
  33. package/src/library/rsform-api/alias.ts +60 -4
  34. package/src/library/rsform-api/attribution.ts +87 -0
  35. package/src/library/rsform-api/cst-type.ts +7 -5
  36. package/src/library/rsform-api/expression.ts +3 -3
  37. package/src/library/rsform-api/formal-graph.test.ts +2 -2
  38. package/src/library/rsform-api/formal-graph.ts +6 -10
  39. package/src/library/rsform-api/index.ts +38 -2
  40. package/src/library/rsform-api/semantic-relations.ts +4 -7
  41. package/src/library/rsform-api/stats.ts +6 -5
  42. package/src/library/rsform-api/structure.ts +12 -6
  43. package/src/library/rsform-api/substitution.ts +82 -0
  44. package/src/library/rsform-api/synthesis.test.ts +157 -0
  45. package/src/library/rsform-api/synthesis.ts +149 -6
  46. package/src/library/rsform-api/text-resolution.test.ts +84 -0
  47. package/src/library/rsform-api/text-resolution.ts +152 -0
  48. package/src/library/rsform-api/transforms.test.ts +161 -0
  49. package/src/library/rsform-api/transforms.ts +42 -0
  50. package/src/library/rsform-api/types.ts +102 -4
  51. package/src/library/rsform.ts +1 -1
  52. package/src/library/rsmodel-api.ts +10 -5
  53. package/src/library/structure-planner.ts +6 -2
  54. package/src/library/template-instantiation.ts +11 -9
  55. package/dist/diagnostics-B1OfMra1.js.map +0 -1
@@ -1,7 +1,8 @@
1
1
  import { b as Typification, f as ExpressionType } from "../typification-9lNu9R4k.js";
2
2
  import { d as ValuePath, l as Value } from "../value-BduA_ZGp.js";
3
- import { S as RSForm, f as EvalStatus, l as BasicBinding, m as RSModelStats, v as Constituenta, x as CstType } from "../diagnostics-Db1F7ruF.js";
3
+ import { S as RSForm, f as EvalStatus, l as BasicBinding, m as RSModelStats, x as CstType } from "../diagnostics-DsEhmFh0.js";
4
4
  import { RSEngine } from "./rsengine.js";
5
+ import { st as ModelEvalFields } from "../index-DpiTybDB.js";
5
6
 
6
7
  //#region src/library/rsmodel-api.d.ts
7
8
  /** Evaluate if parsed data is a basic binding data. */
@@ -10,11 +11,15 @@ declare function validateBasicBindingData(data: unknown): data is Record<string,
10
11
  declare function toBasicBinding(data: Record<string | number, string>): BasicBinding;
11
12
  /** Evaluate if parsed data is a {@link Value} data. */
12
13
  declare function validateValueData(data: unknown): data is Value;
13
- declare function generateRandomValue(type: Typification, basics: Map<number, BasicBinding>, cstByAlias: Map<string, Constituenta>, setElementsCount?: number): Value | null;
14
+ declare function generateRandomValue(type: Typification, basics: Map<number, BasicBinding>, cstByAlias: Map<string, {
15
+ id: number;
16
+ }>, setElementsCount?: number): Value | null;
14
17
  /** Calculate statistics for {@link RSModel}. */
15
18
  declare function calculateModelStats(schema: RSForm, engine: RSEngine, _engineGeneration?: number): RSModelStats;
16
19
  /** Checks whether evaluation status contributes to model status issues. */
17
- declare function isModelIssue(engine: RSEngine, cst: Constituenta): boolean;
20
+ declare function isModelIssue(engine: RSEngine, cst: ModelEvalFields): boolean;
21
+ /** Filters items whose evaluation status contributes to model issues. */
22
+ declare function getEvalIssueItems(items: readonly ModelEvalFields[], engine: RSEngine): ModelEvalFields[];
18
23
  /** Evaluate if {@link CstType} is interpretable. */
19
24
  declare function isInterpretable(type: CstType): boolean;
20
25
  /** Evaluate if {@link CstType} is inferrable. */
@@ -31,5 +36,5 @@ declare function updateValueElement(value: Value | null, path: ValuePath, newVal
31
36
  declare function deleteValueElement(value: Value | null, path: ValuePath, type: Typification, target: number): Value | null;
32
37
  declare function addValueElement(value: Value | null, path: ValuePath, type: Typification, currentType: Typification): Value | null;
33
38
  //#endregion
34
- export { addValueElement, calculateModelStats, deleteValueElement, generateRandomValue, inferEvalStatus, isInferrable, isInterpretable, isModelIssue, toBasicBinding, tryFixValue, updateValueElement, validateBasicBindingData, validateValueData };
39
+ export { addValueElement, calculateModelStats, deleteValueElement, generateRandomValue, getEvalIssueItems, inferEvalStatus, isInferrable, isInterpretable, isModelIssue, toBasicBinding, tryFixValue, updateValueElement, validateBasicBindingData, validateValueData };
35
40
  //# sourceMappingURL=rsmodel-api.d.ts.map
@@ -1,8 +1,8 @@
1
1
  import { TypeID } from "../rslang/semantic/typification.js";
2
+ import { CstType } from "./rsform.js";
2
3
  import { O as setNestedValue, _ as extractValue, b as isTupleValue, f as tuple, l as compare, x as makeDefaultValue } from "../value-COprb2Je.js";
3
4
  import "../rslang/index.js";
4
- import { CstType } from "./rsform.js";
5
- import { F as isBasicConcept, P as isBaseSet, f as calculateSchemaStats, s as modelStatusCstDiagnostic } from "../diagnostics-B1OfMra1.js";
5
+ import { Q as isBasicConcept, S as calculateSchemaStats, Z as isBaseSet, s as modelStatusCstDiagnostic } from "../diagnostics-ndGYbvgh.js";
6
6
  import { EvalStatus } from "./rsmodel.js";
7
7
  //#region src/library/rsmodel-api.ts
8
8
  const RANDOM_INTEGER_MIN = -100;
@@ -75,6 +75,10 @@ function calculateModelStats(schema, engine, _engineGeneration) {
75
75
  function isModelIssue(engine, cst) {
76
76
  return modelStatusCstDiagnostic(engine.getCstStatus(cst.id), cst.cst_type) !== null;
77
77
  }
78
+ /** Filters items whose evaluation status contributes to model issues. */
79
+ function getEvalIssueItems(items, engine) {
80
+ return items.filter((cst) => isModelIssue(engine, cst));
81
+ }
78
82
  /** Evaluate if {@link CstType} is interpretable. */
79
83
  function isInterpretable(type) {
80
84
  switch (type) {
@@ -190,6 +194,6 @@ function countBaseElements(cst, engine) {
190
194
  return value.length;
191
195
  }
192
196
  //#endregion
193
- export { addValueElement, calculateModelStats, deleteValueElement, generateRandomValue, inferEvalStatus, isInferrable, isInterpretable, isModelIssue, toBasicBinding, tryFixValue, updateValueElement, validateBasicBindingData, validateValueData };
197
+ export { addValueElement, calculateModelStats, deleteValueElement, generateRandomValue, getEvalIssueItems, inferEvalStatus, isInferrable, isInterpretable, isModelIssue, toBasicBinding, tryFixValue, updateValueElement, validateBasicBindingData, validateValueData };
194
198
 
195
199
  //# sourceMappingURL=rsmodel-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rsmodel-api.js","names":[],"sources":["../../src/library/rsmodel-api.ts"],"sourcesContent":["import { type ExpressionType, TypeID, type Typification, type Value } from '../rslang';\nimport { compare, tuple, TUPLE_ID, VALUE_TRUE, type ValuePath } from '../rslang/eval/value';\nimport { extractValue, isTupleValue, makeDefaultValue, setNestedValue } from '../rslang/eval/value-api';\nimport { type EchelonCollection } from '../rslang/semantic/typification';\n\nimport { modelStatusCstDiagnostic } from './diagnostics';\nimport { type RSEngine } from './rsengine';\nimport { type Constituenta, CstType, type RSForm } from './rsform';\nimport { calculateSchemaStats, isBaseSet, isBasicConcept } from './rsform-api';\nimport { type BasicBinding, EvalStatus, type RSModelStats } from './rsmodel';\n\nconst RANDOM_INTEGER_MIN = -100;\nconst RANDOM_INTEGER_MAX = 100;\nconst DEFAULT_RANDOM_SET_ELEMENTS_COUNT = 5;\n\n/** Evaluate if parsed data is a basic binding data. */\nexport function validateBasicBindingData(data: unknown): data is Record<string, string> {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return false;\n }\n return Object.entries(data).every(([key, value]) => typeof value === 'string' && Number.isInteger(Number(key)));\n}\n\n/** Convert parsed data to a basic binding. */\nexport function toBasicBinding(data: Record<string | number, string>): BasicBinding {\n const result: BasicBinding = {};\n for (const [k, v] of Object.entries(data)) {\n result[Number(k)] = v;\n }\n return result;\n}\n\n/** Evaluate if parsed data is a {@link Value} data. */\nexport function validateValueData(data: unknown): data is Value {\n if (typeof data === 'number') {\n return Number.isFinite(data);\n }\n if (!Array.isArray(data)) {\n return false;\n }\n return data.every(item => validateValueData(item));\n}\n\nexport function generateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, Constituenta>,\n setElementsCount: number = DEFAULT_RANDOM_SET_ELEMENTS_COUNT\n): Value | null {\n switch (type.typeID) {\n case TypeID.integer:\n return Math.floor(Math.random() * (RANDOM_INTEGER_MAX - RANDOM_INTEGER_MIN + 1)) + RANDOM_INTEGER_MIN;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n const ids = Object.keys(binding ?? {}).map(Number);\n if (ids.length === 0) {\n return null;\n }\n return ids[Math.floor(Math.random() * ids.length)];\n }\n case TypeID.tuple: {\n const factors: Value[] = [];\n for (const factor of type.factors) {\n const sample = generateRandomValue(factor, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n factors.push(sample);\n }\n return tuple(factors);\n }\n case TypeID.collection: {\n const result: Value[] = [];\n const randomElementsCount = Math.floor(Math.random() * (setElementsCount + 1));\n for (let i = 0; i < randomElementsCount; i++) {\n const sample = generateRandomValue(type.base, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n result.push(sample);\n }\n return result;\n }\n case TypeID.anyTypification:\n return null;\n }\n}\n\n/** Calculate statistics for {@link RSModel}. */\nexport function calculateModelStats(schema: RSForm, engine: RSEngine, _engineGeneration?: number): RSModelStats {\n const items = schema.items;\n const statusByID = new Map<number, EvalStatus>();\n for (const cst of items) {\n statusByID.set(cst.id, engine.getCstStatus(cst.id));\n }\n return {\n ...calculateSchemaStats(schema),\n base_elements: items.reduce((sum, cst) => sum + countBaseElements(cst, engine), 0),\n count_missing_base: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && isBasicConcept(cst.cst_type) ? 1 : 0),\n 0\n ),\n count_false_axioms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.AXIOM_FALSE ? 1 : 0),\n 0\n ),\n count_invalid_data: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.INVALID_DATA ? 1 : 0),\n 0\n ),\n count_invalid_calculations: items.reduce(\n (sum, cst) =>\n sum +\n (statusByID.get(cst.id) === EvalStatus.EVAL_FAIL || statusByID.get(cst.id) === EvalStatus.NOT_PROCESSED\n ? 1\n : 0),\n 0\n ),\n count_empty_terms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && cst.cst_type === CstType.TERM ? 1 : 0),\n 0\n )\n };\n}\n\n/** Checks whether evaluation status contributes to model status issues. */\nexport function isModelIssue(engine: RSEngine, cst: Constituenta): boolean {\n return modelStatusCstDiagnostic(engine.getCstStatus(cst.id), cst.cst_type) !== null;\n}\n\n/** Evaluate if {@link CstType} is interpretable. */\nexport function isInterpretable(type: CstType): boolean {\n switch (type) {\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 true;\n\n case CstType.NOMINAL:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is inferrable. */\nexport function isInferrable(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.TERM:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Infers status of a given {@link Value} and {@link CstType}. */\nexport function inferEvalStatus(\n value: Value | null,\n cstType: CstType,\n wasCalculated: boolean = true,\n isInvalid: boolean = false\n): EvalStatus {\n if (isBaseSet(cstType) || cstType === CstType.STRUCTURED) {\n if (isInvalid) {\n return EvalStatus.INVALID_DATA;\n }\n if (value === null || (Array.isArray(value) && value.length === 0)) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n }\n if (!isInferrable(cstType)) {\n return EvalStatus.NO_EVAL;\n }\n if (!wasCalculated) {\n return EvalStatus.NOT_PROCESSED;\n }\n if (value === null) {\n return EvalStatus.EVAL_FAIL;\n }\n if (cstType === CstType.AXIOM && value !== VALUE_TRUE) {\n return EvalStatus.AXIOM_FALSE;\n }\n if (Array.isArray(value) && value.length === 0) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n}\n\n/** Tries to fix value removing invalid base elements not present in the target value.\n * returns null if no fixing is possible.\n * returns true if fixing was successful.\n * returns false if fixing was not needed.\n */\nexport function tryFixValue(\n value: Value,\n type: ExpressionType,\n targetAlias: string,\n targetValue: Value[]\n): boolean | null {\n switch (type.typeID) {\n case TypeID.integer:\n return false;\n case TypeID.basic:\n if (type.baseID !== targetAlias) {\n return false;\n }\n if (typeof value !== 'number') {\n return null;\n }\n if (!targetValue.includes(value)) {\n return null;\n }\n return false;\n case TypeID.tuple: {\n if (!isTupleValue(value)) {\n return null;\n }\n let wasChanged = false;\n for (let i = 0; i < type.factors.length; i++) {\n const componentChanged = tryFixValue(value[i + 1], type.factors[i], targetAlias, targetValue);\n if (componentChanged === null) {\n return null;\n }\n if (componentChanged) {\n wasChanged = true;\n }\n }\n return wasChanged;\n }\n case TypeID.collection:\n if (!Array.isArray(value) || (value.length > 1 && value[0] === TUPLE_ID)) {\n return null;\n }\n let wasChanged = false;\n const removeElements: Value[] = [];\n for (const item of value) {\n const elementChanged = tryFixValue(item, type.base, targetAlias, targetValue);\n if (elementChanged === null || elementChanged === true) {\n wasChanged = true;\n if (elementChanged === null) {\n removeElements.push(item);\n }\n }\n }\n for (const item of removeElements) {\n const index = value.indexOf(item);\n if (index !== -1) {\n value.splice(index, 1);\n }\n }\n if (wasChanged) {\n value.sort((a, b) => compare(a, b));\n let i = 1;\n while (i < value.length) {\n if (compare(value[i], value[i - 1]) === 0) {\n value.splice(i, 1);\n } else {\n i++;\n }\n }\n }\n return wasChanged;\n\n case TypeID.logic:\n case TypeID.anyTypification:\n case TypeID.predicate:\n case TypeID.function:\n return null;\n }\n}\n\nexport function updateValueElement(value: Value | null, path: ValuePath, newValue: number): Value | null {\n return setNestedValue(value, path, newValue);\n}\n\nexport function deleteValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n target: number\n): Value | null {\n if (value === null) {\n return null;\n }\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return null;\n }\n\n const arrayValue = extractValue(value, path);\n if (!Array.isArray(arrayValue)) {\n return null;\n }\n const updatedArray = [...arrayValue.slice(0, target), ...arrayValue.slice(target + 1)];\n return setNestedValue(value, path, updatedArray);\n}\n\nexport function addValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n currentType: Typification\n): Value | null {\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return makeDefaultValue(type);\n }\n\n const newElem = makeDefaultValue((currentType as EchelonCollection).base);\n const arrayValue = (extractValue(value!, path) as Value[] | null) ?? [];\n const updatedArray = [newElem, ...arrayValue];\n return setNestedValue(value, path, updatedArray);\n}\n\n// ========= Internal functions ==========\n\nfunction countBaseElements(cst: Constituenta, engine: RSEngine): number {\n if (!isBasicConcept(cst.cst_type)) {\n return 0;\n }\n const value = engine.getCstValue(cst.id);\n if (value === null) {\n return 0;\n }\n if (!Array.isArray(value) || value[0] === TUPLE_ID) {\n return 1;\n }\n return value.length;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,qBAAqB;AAE3B,MAAM,oCAAoC;;AAG1C,SAAgB,yBAAyB,MAA+C;CACtF,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACzD,OAAO;CAET,OAAO,OAAO,QAAQ,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,WAAW,OAAO,UAAU,YAAY,OAAO,UAAU,OAAO,GAAG,CAAC,CAAC;AAChH;;AAGA,SAAgB,eAAe,MAAqD;CAClF,MAAM,SAAuB,CAAC;CAC9B,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,IAAI,GACtC,OAAO,OAAO,CAAC,KAAK;CAEtB,OAAO;AACT;;AAGA,SAAgB,kBAAkB,MAA8B;CAC9D,IAAI,OAAO,SAAS,UAClB,OAAO,OAAO,SAAS,IAAI;CAE7B,IAAI,CAAC,MAAM,QAAQ,IAAI,GACrB,OAAO;CAET,OAAO,KAAK,OAAM,SAAQ,kBAAkB,IAAI,CAAC;AACnD;AAEA,SAAgB,oBACd,MACA,QACA,YACA,mBAA2B,mCACb;CACd,QAAQ,KAAK,QAAb;EACE,KAAK,OAAO,SACV,OAAO,KAAK,MAAM,KAAK,OAAO,IAAK,GAA4C,IAAI;EACrF,KAAK,OAAO,OAAO;GACjB,MAAM,MAAM,WAAW,IAAI,KAAK,MAAM;GACtC,MAAM,UAAU,MAAM,OAAO,IAAI,IAAI,EAAE,IAAI;GAC3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AAC,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAA,MACjC,OAAO;CAET,OAAO,MAAM;AACf"}
1
+ {"version":3,"file":"rsmodel-api.js","names":[],"sources":["../../src/library/rsmodel-api.ts"],"sourcesContent":["import { type ExpressionType, TypeID, type Typification, type Value } from '../rslang';\nimport { compare, tuple, TUPLE_ID, VALUE_TRUE, type ValuePath } from '../rslang/eval/value';\nimport { extractValue, isTupleValue, makeDefaultValue, setNestedValue } from '../rslang/eval/value-api';\nimport { type EchelonCollection } from '../rslang/semantic/typification';\n\nimport { modelStatusCstDiagnostic } from './diagnostics';\nimport { type RSEngine } from './rsengine';\nimport { CstType, type RSForm } from './rsform';\nimport { calculateSchemaStats, isBaseSet, isBasicConcept, type ModelEvalFields } from './rsform-api';\nimport { type BasicBinding, EvalStatus, type RSModelStats } from './rsmodel';\n\nconst RANDOM_INTEGER_MIN = -100;\nconst RANDOM_INTEGER_MAX = 100;\nconst DEFAULT_RANDOM_SET_ELEMENTS_COUNT = 5;\n\n/** Evaluate if parsed data is a basic binding data. */\nexport function validateBasicBindingData(data: unknown): data is Record<string, string> {\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return false;\n }\n return Object.entries(data).every(([key, value]) => typeof value === 'string' && Number.isInteger(Number(key)));\n}\n\n/** Convert parsed data to a basic binding. */\nexport function toBasicBinding(data: Record<string | number, string>): BasicBinding {\n const result: BasicBinding = {};\n for (const [k, v] of Object.entries(data)) {\n result[Number(k)] = v;\n }\n return result;\n}\n\n/** Evaluate if parsed data is a {@link Value} data. */\nexport function validateValueData(data: unknown): data is Value {\n if (typeof data === 'number') {\n return Number.isFinite(data);\n }\n if (!Array.isArray(data)) {\n return false;\n }\n return data.every(item => validateValueData(item));\n}\n\nexport function generateRandomValue(\n type: Typification,\n basics: Map<number, BasicBinding>,\n cstByAlias: Map<string, { id: number }>,\n setElementsCount: number = DEFAULT_RANDOM_SET_ELEMENTS_COUNT\n): Value | null {\n switch (type.typeID) {\n case TypeID.integer:\n return Math.floor(Math.random() * (RANDOM_INTEGER_MAX - RANDOM_INTEGER_MIN + 1)) + RANDOM_INTEGER_MIN;\n case TypeID.basic: {\n const cst = cstByAlias.get(type.baseID);\n const binding = cst ? basics.get(cst.id) : undefined;\n const ids = Object.keys(binding ?? {}).map(Number);\n if (ids.length === 0) {\n return null;\n }\n return ids[Math.floor(Math.random() * ids.length)];\n }\n case TypeID.tuple: {\n const factors: Value[] = [];\n for (const factor of type.factors) {\n const sample = generateRandomValue(factor, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n factors.push(sample);\n }\n return tuple(factors);\n }\n case TypeID.collection: {\n const result: Value[] = [];\n const randomElementsCount = Math.floor(Math.random() * (setElementsCount + 1));\n for (let i = 0; i < randomElementsCount; i++) {\n const sample = generateRandomValue(type.base, basics, cstByAlias, setElementsCount);\n if (sample === null) {\n return null;\n }\n result.push(sample);\n }\n return result;\n }\n case TypeID.anyTypification:\n return null;\n }\n}\n\n/** Calculate statistics for {@link RSModel}. */\nexport function calculateModelStats(schema: RSForm, engine: RSEngine, _engineGeneration?: number): RSModelStats {\n const items = schema.items;\n const statusByID = new Map<number, EvalStatus>();\n for (const cst of items) {\n statusByID.set(cst.id, engine.getCstStatus(cst.id));\n }\n return {\n ...calculateSchemaStats(schema),\n base_elements: items.reduce((sum, cst) => sum + countBaseElements(cst, engine), 0),\n count_missing_base: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && isBasicConcept(cst.cst_type) ? 1 : 0),\n 0\n ),\n count_false_axioms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.AXIOM_FALSE ? 1 : 0),\n 0\n ),\n count_invalid_data: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.INVALID_DATA ? 1 : 0),\n 0\n ),\n count_invalid_calculations: items.reduce(\n (sum, cst) =>\n sum +\n (statusByID.get(cst.id) === EvalStatus.EVAL_FAIL || statusByID.get(cst.id) === EvalStatus.NOT_PROCESSED\n ? 1\n : 0),\n 0\n ),\n count_empty_terms: items.reduce(\n (sum, cst) => sum + (statusByID.get(cst.id) === EvalStatus.EMPTY && cst.cst_type === CstType.TERM ? 1 : 0),\n 0\n )\n };\n}\n\n/** Checks whether evaluation status contributes to model status issues. */\nexport function isModelIssue(engine: RSEngine, cst: ModelEvalFields): boolean {\n return modelStatusCstDiagnostic(engine.getCstStatus(cst.id), cst.cst_type) !== null;\n}\n\n/** Filters items whose evaluation status contributes to model issues. */\nexport function getEvalIssueItems(items: readonly ModelEvalFields[], engine: RSEngine): ModelEvalFields[] {\n return items.filter(cst => isModelIssue(engine, cst));\n}\n\n/** Evaluate if {@link CstType} is interpretable. */\nexport function isInterpretable(type: CstType): boolean {\n switch (type) {\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 true;\n\n case CstType.NOMINAL:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Evaluate if {@link CstType} is inferrable. */\nexport function isInferrable(type: CstType): boolean {\n switch (type) {\n case CstType.AXIOM:\n case CstType.STATEMENT:\n case CstType.TERM:\n return true;\n\n case CstType.NOMINAL:\n case CstType.BASE:\n case CstType.CONSTANT:\n case CstType.STRUCTURED:\n case CstType.FUNCTION:\n case CstType.PREDICATE:\n return false;\n }\n}\n\n/** Infers status of a given {@link Value} and {@link CstType}. */\nexport function inferEvalStatus(\n value: Value | null,\n cstType: CstType,\n wasCalculated: boolean = true,\n isInvalid: boolean = false\n): EvalStatus {\n if (isBaseSet(cstType) || cstType === CstType.STRUCTURED) {\n if (isInvalid) {\n return EvalStatus.INVALID_DATA;\n }\n if (value === null || (Array.isArray(value) && value.length === 0)) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n }\n if (!isInferrable(cstType)) {\n return EvalStatus.NO_EVAL;\n }\n if (!wasCalculated) {\n return EvalStatus.NOT_PROCESSED;\n }\n if (value === null) {\n return EvalStatus.EVAL_FAIL;\n }\n if (cstType === CstType.AXIOM && value !== VALUE_TRUE) {\n return EvalStatus.AXIOM_FALSE;\n }\n if (Array.isArray(value) && value.length === 0) {\n return EvalStatus.EMPTY;\n }\n return EvalStatus.HAS_DATA;\n}\n\n/** Tries to fix value removing invalid base elements not present in the target value.\n * returns null if no fixing is possible.\n * returns true if fixing was successful.\n * returns false if fixing was not needed.\n */\nexport function tryFixValue(\n value: Value,\n type: ExpressionType,\n targetAlias: string,\n targetValue: Value[]\n): boolean | null {\n switch (type.typeID) {\n case TypeID.integer:\n return false;\n case TypeID.basic:\n if (type.baseID !== targetAlias) {\n return false;\n }\n if (typeof value !== 'number') {\n return null;\n }\n if (!targetValue.includes(value)) {\n return null;\n }\n return false;\n case TypeID.tuple: {\n if (!isTupleValue(value)) {\n return null;\n }\n let wasChanged = false;\n for (let i = 0; i < type.factors.length; i++) {\n const componentChanged = tryFixValue(value[i + 1], type.factors[i], targetAlias, targetValue);\n if (componentChanged === null) {\n return null;\n }\n if (componentChanged) {\n wasChanged = true;\n }\n }\n return wasChanged;\n }\n case TypeID.collection:\n if (!Array.isArray(value) || (value.length > 1 && value[0] === TUPLE_ID)) {\n return null;\n }\n let wasChanged = false;\n const removeElements: Value[] = [];\n for (const item of value) {\n const elementChanged = tryFixValue(item, type.base, targetAlias, targetValue);\n if (elementChanged === null || elementChanged === true) {\n wasChanged = true;\n if (elementChanged === null) {\n removeElements.push(item);\n }\n }\n }\n for (const item of removeElements) {\n const index = value.indexOf(item);\n if (index !== -1) {\n value.splice(index, 1);\n }\n }\n if (wasChanged) {\n value.sort((a, b) => compare(a, b));\n let i = 1;\n while (i < value.length) {\n if (compare(value[i], value[i - 1]) === 0) {\n value.splice(i, 1);\n } else {\n i++;\n }\n }\n }\n return wasChanged;\n\n case TypeID.logic:\n case TypeID.anyTypification:\n case TypeID.predicate:\n case TypeID.function:\n return null;\n }\n}\n\nexport function updateValueElement(value: Value | null, path: ValuePath, newValue: number): Value | null {\n return setNestedValue(value, path, newValue);\n}\n\nexport function deleteValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n target: number\n): Value | null {\n if (value === null) {\n return null;\n }\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return null;\n }\n\n const arrayValue = extractValue(value, path);\n if (!Array.isArray(arrayValue)) {\n return null;\n }\n const updatedArray = [...arrayValue.slice(0, target), ...arrayValue.slice(target + 1)];\n return setNestedValue(value, path, updatedArray);\n}\n\nexport function addValueElement(\n value: Value | null,\n path: ValuePath,\n type: Typification,\n currentType: Typification\n): Value | null {\n if (path.length === 0 && type.typeID !== TypeID.collection) {\n return makeDefaultValue(type);\n }\n\n const newElem = makeDefaultValue((currentType as EchelonCollection).base);\n const arrayValue = (extractValue(value!, path) as Value[] | null) ?? [];\n const updatedArray = [newElem, ...arrayValue];\n return setNestedValue(value, path, updatedArray);\n}\n\n// ========= Internal functions ==========\n\nfunction countBaseElements(cst: ModelEvalFields, engine: RSEngine): number {\n if (!isBasicConcept(cst.cst_type)) {\n return 0;\n }\n const value = engine.getCstValue(cst.id);\n if (value === null) {\n return 0;\n }\n if (!Array.isArray(value) || value[0] === TUPLE_ID) {\n return 1;\n }\n return value.length;\n}\n"],"mappings":";;;;;;;AAWA,MAAM,qBAAqB;AAE3B,MAAM,oCAAoC;;AAG1C,SAAgB,yBAAyB,MAA+C;CACtF,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GACzD,OAAO;CAET,OAAO,OAAO,QAAQ,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,WAAW,OAAO,UAAU,YAAY,OAAO,UAAU,OAAO,GAAG,CAAC,CAAC;AAChH;;AAGA,SAAgB,eAAe,MAAqD;CAClF,MAAM,SAAuB,CAAC;CAC9B,KAAK,MAAM,CAAC,GAAG,MAAM,OAAO,QAAQ,IAAI,GACtC,OAAO,OAAO,CAAC,KAAK;CAEtB,OAAO;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,CAAC,MAAM,QAAQ,UAAU,GAC3B,OAAO;CAGT,OAAO,eAAe,OAAO,MAAM,CADb,GAAG,WAAW,MAAM,GAAG,MAAM,GAAG,GAAG,WAAW,MAAM,SAAS,CAAC,CACjD,CAAY;AACjD;AAEA,SAAgB,gBACd,OACA,MACA,MACA,aACc;CACd,IAAI,KAAK,WAAW,KAAK,KAAK,WAAW,OAAO,YAC9C,OAAO,iBAAiB,IAAI;CAM9B,OAAO,eAAe,OAAO,MAAM,CAHnB,iBAAkB,YAAkC,IAE9C,GAAS,GADX,aAAa,OAAQ,IAAI,KAAwB,CAAC,CAEnC,CAAY;AACjD;AAIA,SAAS,kBAAkB,KAAsB,QAA0B;CACzE,IAAI,CAAC,eAAe,IAAI,QAAQ,GAC9B,OAAO;CAET,MAAM,QAAQ,OAAO,YAAY,IAAI,EAAE;CACvC,IAAI,UAAU,MACZ,OAAO;CAET,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAA,MACjC,OAAO;CAET,OAAO,MAAM;AACf"}
@@ -1,2 +1,2 @@
1
- import { d as DEFAULT_VALUE_TEXT, f as EvalStatus, h as TYPE_BASIC, l as BasicBinding, m as RSModelStats, p as RSModel, u as BasicsContext } from "../diagnostics-Db1F7ruF.js";
1
+ import { d as DEFAULT_VALUE_TEXT, f as EvalStatus, h as TYPE_BASIC, l as BasicBinding, m as RSModelStats, p as RSModel, u as BasicsContext } from "../diagnostics-DsEhmFh0.js";
2
2
  export { BasicBinding, BasicsContext, DEFAULT_VALUE_TEXT, EvalStatus, RSModel, RSModelStats, TYPE_BASIC };
@@ -1,5 +1,5 @@
1
1
  import { b as Typification, y as TypePath } from "../typification-9lNu9R4k.js";
2
- import { S as RSForm, v as Constituenta } from "../diagnostics-Db1F7ruF.js";
2
+ import { S as RSForm, v as Constituenta } from "../diagnostics-DsEhmFh0.js";
3
3
 
4
4
  //#region src/library/structure-planner.d.ts
5
5
  /** Represents a node in the structure planner. */
@@ -1,9 +1,9 @@
1
1
  import { TypeID, bool, isTypification, makeTypePath } from "../rslang/semantic/typification.js";
2
2
  import { labelType } from "../rslang/labels.js";
3
3
  import { splitTemplateDefinition } from "../rslang/api.js";
4
- import "../rslang/index.js";
5
4
  import { CstType } from "./rsform.js";
6
- import { l as findCstByStructure } from "../diagnostics-B1OfMra1.js";
5
+ import "../rslang/index.js";
6
+ import { y as findCstByStructure } from "../diagnostics-ndGYbvgh.js";
7
7
  //#region src/library/structure-planner.ts
8
8
  /** Structure planner for {@link Constituenta}. */
9
9
  var StructurePlanner = class {
@@ -1 +1 @@
1
- {"version":3,"file":"structure-planner.js","names":[],"sources":["../../src/library/structure-planner.ts"],"sourcesContent":["import { makeTypePath, TypeID, type TypePath, type Typification } from '../rslang';\nimport { splitTemplateDefinition } from '../rslang/api';\nimport { labelType } from '../rslang/labels';\nimport { bool, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';\n\nimport { type Constituenta, CstType, type RSForm } from './rsform';\nimport { findCstByStructure } from './rsform-api';\n\n/** Represents a node in the structure planner. */\nexport interface SPNode {\n key: string;\n path: TypePath;\n type: Typification;\n parent: number | null;\n definition: string;\n existing: Constituenta | null;\n}\n\n/** Structure planner for {@link Constituenta}. */\nexport class StructurePlanner {\n private items: SPNode[] = [];\n private schema: RSForm;\n private target: Constituenta;\n private rootType: Typification;\n\n constructor(schema: RSForm, target: Constituenta) {\n const eff = target.effectiveType;\n if (eff == null) {\n throw new Error('Invalid typification for target');\n }\n this.schema = schema;\n this.target = target;\n if (target.cst_type === CstType.FUNCTION && !isTypification(eff)) {\n this.rootType = (eff as EchelonFunctional).result;\n } else if (isTypification(eff)) {\n this.rootType = eff as Typification;\n } else {\n throw new Error('Invalid typification for target');\n }\n }\n\n public build(): SPNode[] {\n this.items.push({\n key: 'root',\n path: makeTypePath([]),\n type: this.rootType,\n parent: null,\n definition: labelType(this.target.effectiveType),\n existing: this.target\n });\n this.visit(this.rootType, this.rootType.typeID === TypeID.collection ? [0] : [], 0);\n return this.items;\n }\n\n private visit(type: Typification, path: number[], parent: number) {\n switch (type.typeID) {\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n type.base.factors.forEach((factor, index) => {\n const nextPath = [...path, index + 1];\n const nextType = bool(factor);\n const nextNode = this.pushNode(nextPath, nextType, parent);\n this.visit(nextType, nextPath, nextNode);\n });\n } else if (type.base.typeID === TypeID.collection) {\n const nextPath = [...path, 0];\n const nextNode = this.pushNode(nextPath, type.base, parent);\n this.visit(type.base, nextPath, nextNode);\n }\n return;\n case TypeID.tuple:\n type.factors.forEach((factor, index) => {\n const nextPath = [...path, index + 1];\n const nextNode = this.pushNode(nextPath, factor, parent);\n this.visit(factor, nextPath, nextNode);\n });\n return;\n default:\n return;\n }\n }\n\n private pushNode(path: number[], type: Typification, parent: number) {\n const typePath = makeTypePath(path);\n this.items.push({\n key: formatPathText(typePath),\n path: typePath,\n type: type,\n parent: parent,\n definition: produceDefinition(this.target, this.rootType, typePath),\n existing: findCstByStructure(this.schema, this.target, typePath)\n });\n return this.items.length - 1;\n }\n}\n\n// ======= Internals =======\nfunction produceDefinition(target: Constituenta, rootType: Typification, path: TypePath): string {\n let current = rootType;\n let expression = target.alias;\n let index = rootType.typeID === TypeID.collection ? 1 : 0;\n let prefix = '';\n if (target.cst_type === CstType.FUNCTION) {\n prefix = `[${splitTemplateDefinition(target.definition_formal).head}] `;\n const funcType =\n target.effectiveType && !isTypification(target.effectiveType)\n ? (target.effectiveType as EchelonFunctional)\n : null;\n if (funcType) {\n expression = `${expression}[${funcType.args.map(arg => arg.alias).join(', ')}]`;\n }\n }\n\n while (index < path.length) {\n const step = path[index];\n switch (current.typeID) {\n case TypeID.collection:\n if (current.base.typeID === TypeID.tuple) {\n expression = `Pr${step}(${expression})`;\n current = bool(current.base.factors[step - 1]);\n index += 1;\n } else {\n expression = `red(${expression})`;\n current = current.base;\n index += 1;\n }\n break;\n case TypeID.tuple:\n expression = `pr${step}(${expression})`;\n current = current.factors[step - 1];\n index += 1;\n break;\n default:\n return prefix + expression;\n }\n }\n\n return prefix + expression;\n}\n\nfunction formatPathText(path: TypePath): string {\n return path.map(step => String(step)).join('.');\n}\n"],"mappings":";;;;;;;;AAmBA,IAAa,mBAAb,MAA8B;CAC5B,QAA0B,CAAC;CAC3B;CACA;CACA;CAEA,YAAY,QAAgB,QAAsB;EAChD,MAAM,MAAM,OAAO;EACnB,IAAI,OAAO,MACT,MAAM,IAAI,MAAM,iCAAiC;EAEnD,KAAK,SAAS;EACd,KAAK,SAAS;EACd,IAAI,OAAO,aAAa,QAAQ,YAAY,CAAC,eAAe,GAAG,GAC7D,KAAK,WAAY,IAA0B;OACtC,IAAI,eAAe,GAAG,GAC3B,KAAK,WAAW;OAEhB,MAAM,IAAI,MAAM,iCAAiC;CAErD;CAEA,QAAyB;EACvB,KAAK,MAAM,KAAK;GACd,KAAK;GACL,MAAM,aAAa,CAAC,CAAC;GACrB,MAAM,KAAK;GACX,QAAQ;GACR,YAAY,UAAU,KAAK,OAAO,aAAa;GAC/C,UAAU,KAAK;EACjB,CAAC;EACD,KAAK,MAAM,KAAK,UAAU,KAAK,SAAS,WAAW,OAAO,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;EAClF,OAAO,KAAK;CACd;CAEA,MAAc,MAAoB,MAAgB,QAAgB;EAChE,QAAQ,KAAK,QAAb;GACE,KAAK,OAAO;IACV,IAAI,KAAK,KAAK,WAAW,OAAO,OAC9B,KAAK,KAAK,QAAQ,SAAS,QAAQ,UAAU;KAC3C,MAAM,WAAW,CAAC,GAAG,MAAM,QAAQ,CAAC;KACpC,MAAM,WAAW,KAAK,MAAM;KAC5B,MAAM,WAAW,KAAK,SAAS,UAAU,UAAU,MAAM;KACzD,KAAK,MAAM,UAAU,UAAU,QAAQ;IACzC,CAAC;SACI,IAAI,KAAK,KAAK,WAAW,OAAO,YAAY;KACjD,MAAM,WAAW,CAAC,GAAG,MAAM,CAAC;KAC5B,MAAM,WAAW,KAAK,SAAS,UAAU,KAAK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,KAAK,QAAQ,OAAO,EAAE;KAC7C,SAAS;IACX,OAAO;KACL,aAAa,OAAO,WAAW;KAC/B,UAAU,QAAQ;KAClB,SAAS;IACX;IACA;GACF,KAAK,OAAO;IACV,aAAa,KAAK,KAAK,GAAG,WAAW;IACrC,UAAU,QAAQ,QAAQ,OAAO;IACjC,SAAS;IACT;GACF,SACE,OAAO,SAAS;EACpB;CACF;CAEA,OAAO,SAAS;AAClB;AAEA,SAAS,eAAe,MAAwB;CAC9C,OAAO,KAAK,KAAI,SAAQ,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AAChD"}
1
+ {"version":3,"file":"structure-planner.js","names":[],"sources":["../../src/library/structure-planner.ts"],"sourcesContent":["import { makeTypePath, TypeID, type TypePath, type Typification } from '../rslang';\nimport { splitTemplateDefinition } from '../rslang/api';\nimport { labelType } from '../rslang/labels';\nimport { bool, type EchelonFunctional, isTypification } from '../rslang/semantic/typification';\n\nimport { type Constituenta, CstType, type RSForm } from './rsform';\nimport { findCstByStructure, type FormalOrderFields, type StructureCapableFields } from './rsform-api';\n\n/** Represents a node in the structure planner. */\nexport interface SPNode {\n key: string;\n path: TypePath;\n type: Typification;\n parent: number | null;\n definition: string;\n existing: Constituenta | null;\n}\n\n/** Structure planner for {@link Constituenta}. */\nexport class StructurePlanner {\n private items: SPNode[] = [];\n private schema: RSForm;\n private target: Constituenta;\n private rootType: Typification;\n\n constructor(schema: RSForm, target: Constituenta) {\n const eff = target.effectiveType;\n if (eff == null) {\n throw new Error('Invalid typification for target');\n }\n this.schema = schema;\n this.target = target;\n if (target.cst_type === CstType.FUNCTION && !isTypification(eff)) {\n this.rootType = (eff as EchelonFunctional).result;\n } else if (isTypification(eff)) {\n this.rootType = eff as Typification;\n } else {\n throw new Error('Invalid typification for target');\n }\n }\n\n public build(): SPNode[] {\n this.items.push({\n key: 'root',\n path: makeTypePath([]),\n type: this.rootType,\n parent: null,\n definition: labelType(this.target.effectiveType),\n existing: this.target\n });\n this.visit(this.rootType, this.rootType.typeID === TypeID.collection ? [0] : [], 0);\n return this.items;\n }\n\n private visit(type: Typification, path: number[], parent: number) {\n switch (type.typeID) {\n case TypeID.collection:\n if (type.base.typeID === TypeID.tuple) {\n type.base.factors.forEach((factor, index) => {\n const nextPath = [...path, index + 1];\n const nextType = bool(factor);\n const nextNode = this.pushNode(nextPath, nextType, parent);\n this.visit(nextType, nextPath, nextNode);\n });\n } else if (type.base.typeID === TypeID.collection) {\n const nextPath = [...path, 0];\n const nextNode = this.pushNode(nextPath, type.base, parent);\n this.visit(type.base, nextPath, nextNode);\n }\n return;\n case TypeID.tuple:\n type.factors.forEach((factor, index) => {\n const nextPath = [...path, index + 1];\n const nextNode = this.pushNode(nextPath, factor, parent);\n this.visit(factor, nextPath, nextNode);\n });\n return;\n default:\n return;\n }\n }\n\n private pushNode(path: number[], type: Typification, parent: number) {\n const typePath = makeTypePath(path);\n this.items.push({\n key: formatPathText(typePath),\n path: typePath,\n type: type,\n parent: parent,\n definition: produceDefinition(this.target, this.rootType, typePath),\n existing: findCstByStructure(this.schema, this.target, typePath)\n });\n return this.items.length - 1;\n }\n}\n\n// ======= Internals =======\nfunction produceDefinition(\n target: FormalOrderFields & StructureCapableFields,\n rootType: Typification,\n path: TypePath\n): string {\n let current = rootType;\n let expression = target.alias;\n let index = rootType.typeID === TypeID.collection ? 1 : 0;\n let prefix = '';\n if (target.cst_type === CstType.FUNCTION) {\n prefix = `[${splitTemplateDefinition(target.definition_formal).head}] `;\n const funcType =\n target.effectiveType && !isTypification(target.effectiveType)\n ? (target.effectiveType as EchelonFunctional)\n : null;\n if (funcType) {\n expression = `${expression}[${funcType.args.map(arg => arg.alias).join(', ')}]`;\n }\n }\n\n while (index < path.length) {\n const step = path[index];\n switch (current.typeID) {\n case TypeID.collection:\n if (current.base.typeID === TypeID.tuple) {\n expression = `Pr${step}(${expression})`;\n current = bool(current.base.factors[step - 1]);\n index += 1;\n } else {\n expression = `red(${expression})`;\n current = current.base;\n index += 1;\n }\n break;\n case TypeID.tuple:\n expression = `pr${step}(${expression})`;\n current = current.factors[step - 1];\n index += 1;\n break;\n default:\n return prefix + expression;\n }\n }\n\n return prefix + expression;\n}\n\nfunction formatPathText(path: TypePath): string {\n return path.map(step => String(step)).join('.');\n}\n"],"mappings":";;;;;;;;AAmBA,IAAa,mBAAb,MAA8B;CAC5B,QAA0B,CAAC;CAC3B;CACA;CACA;CAEA,YAAY,QAAgB,QAAsB;EAChD,MAAM,MAAM,OAAO;EACnB,IAAI,OAAO,MACT,MAAM,IAAI,MAAM,iCAAiC;EAEnD,KAAK,SAAS;EACd,KAAK,SAAS;EACd,IAAI,OAAO,aAAa,QAAQ,YAAY,CAAC,eAAe,GAAG,GAC7D,KAAK,WAAY,IAA0B;OACtC,IAAI,eAAe,GAAG,GAC3B,KAAK,WAAW;OAEhB,MAAM,IAAI,MAAM,iCAAiC;CAErD;CAEA,QAAyB;EACvB,KAAK,MAAM,KAAK;GACd,KAAK;GACL,MAAM,aAAa,CAAC,CAAC;GACrB,MAAM,KAAK;GACX,QAAQ;GACR,YAAY,UAAU,KAAK,OAAO,aAAa;GAC/C,UAAU,KAAK;EACjB,CAAC;EACD,KAAK,MAAM,KAAK,UAAU,KAAK,SAAS,WAAW,OAAO,aAAa,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;EAClF,OAAO,KAAK;CACd;CAEA,MAAc,MAAoB,MAAgB,QAAgB;EAChE,QAAQ,KAAK,QAAb;GACE,KAAK,OAAO;IACV,IAAI,KAAK,KAAK,WAAW,OAAO,OAC9B,KAAK,KAAK,QAAQ,SAAS,QAAQ,UAAU;KAC3C,MAAM,WAAW,CAAC,GAAG,MAAM,QAAQ,CAAC;KACpC,MAAM,WAAW,KAAK,MAAM;KAC5B,MAAM,WAAW,KAAK,SAAS,UAAU,UAAU,MAAM;KACzD,KAAK,MAAM,UAAU,UAAU,QAAQ;IACzC,CAAC;SACI,IAAI,KAAK,KAAK,WAAW,OAAO,YAAY;KACjD,MAA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AO;KACxC,aAAa,KAAK,KAAK,GAAG,WAAW;KACrC,UAAU,KAAK,QAAQ,KAAK,QAAQ,OAAO,EAAE;KAC7C,SAAS;IACX,OAAO;KACL,aAAa,OAAO,WAAW;KAC/B,UAAU,QAAQ;KAClB,SAAS;IACX;IACA;GACF,KAAK,OAAO;IACV,aAAa,KAAK,KAAK,GAAG,WAAW;IACrC,UAAU,QAAQ,QAAQ,OAAO;IACjC,SAAS;IACT;GACF,SACE,OAAO,SAAS;EACpB;CACF;CAEA,OAAO,SAAS;AAClB;AAEA,SAAS,eAAe,MAAwB;CAC9C,OAAO,KAAK,KAAI,SAAQ,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;AAChD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsconcept/domain",
3
- "version": "2.2.0",
3
+ "version": "3.0.0",
4
4
  "description": "Shared TypeScript domain for RS language, RSForm, RSModel, RSEngine, OSS, and concept-text helpers.",
5
5
  "license": "MIT",
6
6
  "author": "IRBorisov",
package/src/index.ts CHANGED
@@ -54,6 +54,7 @@ export {
54
54
  type RSForm,
55
55
  type RSFormStats,
56
56
  type Substitution,
57
+ type TermForm,
57
58
  type TypeInfo
58
59
  } from './library/rsform';
59
60
  export {
@@ -3,8 +3,10 @@
3
3
  */
4
4
 
5
5
  import { type Graph } from '../graph';
6
+ import { type ExpressionType } from '../rslang';
6
7
  import { labelType } from '../rslang/labels';
7
8
 
9
+ import { type BasicTextCheckFields } from './rsform-api/types';
8
10
  import { type Constituenta, type CstType } from './rsform';
9
11
  import { isBasicConcept, isLogical } from './rsform-api';
10
12
  import { EvalStatus } from './rsmodel';
@@ -41,8 +43,11 @@ export interface CstDiagnostic {
41
43
  params?: readonly string[];
42
44
  }
43
45
 
44
- /** Whether a constituent has a schema/model diagnostic with the given code. */
45
- export function hasCstDiagnostic(cst: Constituenta, code: RSDiagnosticCode): boolean {
46
+ /** Whether an item has a schema/model diagnostic with the given code. */
47
+ export function hasCstDiagnostic(
48
+ cst: { diagnostics?: readonly CstDiagnostic[] | null },
49
+ code: RSDiagnosticCode
50
+ ): boolean {
46
51
  return cst.diagnostics?.some(item => item.code === code) ?? false;
47
52
  }
48
53
 
@@ -160,7 +165,13 @@ export function modelStatusCstDiagnostic(status: EvalStatus, cstType: CstType):
160
165
  return { kind: DiagnosticKind.MODEL, code, params: [String(status)] };
161
166
  }
162
167
 
163
- function collectLocalSchemaDiagnostics(cst: Constituenta): CstDiagnostic[] {
168
+ function collectLocalSchemaDiagnostics(
169
+ cst: BasicTextCheckFields & {
170
+ is_type_mismatch: boolean;
171
+ typification_manual: string;
172
+ analysis: { type: ExpressionType | null };
173
+ }
174
+ ): CstDiagnostic[] {
164
175
  const result: CstDiagnostic[] = [];
165
176
  if (cst.is_type_mismatch) {
166
177
  result.push({
@@ -180,13 +191,13 @@ function collectLocalSchemaDiagnostics(cst: Constituenta): CstDiagnostic[] {
180
191
  return result;
181
192
  }
182
193
 
183
- function detectGroupedAliasDiagnostics(
184
- items: Constituenta[],
194
+ function detectGroupedAliasDiagnostics<T extends { id: number }>(
195
+ items: readonly T[],
185
196
  resolveAlias: (id: number) => string,
186
- groupKey: (cst: Constituenta) => string | undefined,
197
+ groupKey: (cst: T) => string | undefined,
187
198
  code: RSDiagnosticCode
188
199
  ): Map<number, CstDiagnostic> {
189
- const groups = new Map<string, Constituenta[]>();
200
+ const groups = new Map<string, T[]>();
190
201
  for (const cst of items) {
191
202
  const key = groupKey(cst);
192
203
  if (!key) {
@@ -218,7 +229,7 @@ function detectGroupedAliasDiagnostics(
218
229
  }
219
230
 
220
231
  function detectHomonymDiagnostics(
221
- items: Constituenta[],
232
+ items: readonly { id: number; term_resolved: string }[],
222
233
  resolveAlias: (id: number) => string
223
234
  ): Map<number, CstDiagnostic> {
224
235
  return detectGroupedAliasDiagnostics(
@@ -233,7 +244,7 @@ function detectHomonymDiagnostics(
233
244
  }
234
245
 
235
246
  function detectFormalDuplicateDiagnostics(
236
- items: Constituenta[],
247
+ items: readonly { id: number }[],
237
248
  resolveAlias: (id: number) => string,
238
249
  normalizedDefinitions: ReadonlyMap<number, string>
239
250
  ): Map<number, CstDiagnostic> {
@@ -44,6 +44,7 @@ export {
44
44
  type RSForm,
45
45
  type RSFormStats,
46
46
  type Substitution,
47
+ type TermForm,
47
48
  type TypeInfo
48
49
  } from './rsform';
49
50
  export {
@@ -10,6 +10,7 @@ import { extractBases } from '../rslang/semantic/typification-api';
10
10
  import { type LibraryItem } from './library';
11
11
  import { NodeType, type OperationSchema, type SubstitutionErrorDescription, SubstitutionErrorType } from './oss';
12
12
  import { type Constituenta, CstClass, CstType, type RSForm, type Substitution } from './rsform';
13
+ import { type FormalOrderFields } from './rsform-api';
13
14
 
14
15
  const STARTING_SUB_INDEX = 900; // max semantic index for starting substitution
15
16
 
@@ -387,7 +388,10 @@ export class SubstitutionValidator {
387
388
  return result;
388
389
  }
389
390
 
390
- private checkEqual(left: Constituenta, right: Constituenta): boolean {
391
+ private checkEqual(
392
+ left: FormalOrderFields & { schema: number },
393
+ right: FormalOrderFields & { schema: number }
394
+ ): boolean {
391
395
  const schema1 = this.schemaByID.get(left.schema)!;
392
396
  const inputs1 = schema1.graph.at(left.id)!.inputs;
393
397
  if (inputs1.some(id => !this.constituents.has(id))) {
@@ -4,12 +4,13 @@
4
4
 
5
5
  import { applyEntityReferenceMapping } from '../../cctext/language-api';
6
6
  import { type AliasMapping, applyAliasMapping, applyTypificationMapping } from '../../rslang/api';
7
- import { type ArgumentValue, type CstType, type RSForm } from '../rsform';
7
+ import { type ArgumentValue, CstType, type RSForm } from '../rsform';
8
8
 
9
9
  import { getCstTypePrefix } from './cst-type';
10
+ import { type AliasTypedFields } from './types';
10
11
 
11
- /** Fields of {@link Constituenta} updated in place by alias mapping. */
12
- export interface ConstituentaMappableFields {
12
+ /** Fields updated in place by alias mapping. */
13
+ export interface MappableFields {
13
14
  alias: string;
14
15
  definition_formal: string;
15
16
  typification_manual: string;
@@ -76,7 +77,7 @@ export function generateAlias(type: CstType, schema: RSForm, takenAliases: strin
76
77
  * Remap formal expressions and terminological entity references in constituent fields.
77
78
  * Mutates each element of `items` in place; pass owned or cloned data only.
78
79
  */
79
- export function applyMappingToConstituents<T extends ConstituentaMappableFields>(
80
+ export function applyMappingToConstituents<T extends MappableFields>(
80
81
  items: T[],
81
82
  mapping: AliasMapping,
82
83
  changeAliases: boolean
@@ -92,6 +93,61 @@ export function applyMappingToConstituents<T extends ConstituentaMappableFields>
92
93
  }
93
94
  }
94
95
 
96
+ /** Highest numeric alias suffix for {@link type} among {@link items} (0 when none). */
97
+ export function maxAliasIndex(items: readonly AliasTypedFields[], type: CstType): number {
98
+ const prefix = getCstTypePrefix(type);
99
+ return items.reduce((max, cst) => {
100
+ if (cst.cst_type !== type) {
101
+ return max;
102
+ }
103
+ const index = Number(cst.alias.slice(prefix.length));
104
+ return Number.isFinite(index) ? Math.max(max, index) : max;
105
+ }, 0);
106
+ }
107
+
108
+ /**
109
+ * Build alias → new-alias mapping that renumbers each type sequentially in list order.
110
+ * Matches backend {@code RSFormCached.reset_aliases}.
111
+ */
112
+ export function buildSequentialAliasMapping(items: readonly AliasTypedFields[]): AliasMapping {
113
+ const counts: Record<string, number> = {};
114
+ for (const value of Object.values(CstType)) {
115
+ counts[value] = 1;
116
+ }
117
+ const mapping: AliasMapping = {};
118
+ for (const cst of items) {
119
+ const alias = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;
120
+ counts[cst.cst_type] += 1;
121
+ if (cst.alias !== alias) {
122
+ mapping[cst.alias] = alias;
123
+ }
124
+ }
125
+ return mapping;
126
+ }
127
+
128
+ /**
129
+ * Allocate fresh aliases for {@link source} constituents being imported into a non-empty receiver.
130
+ * Returns an empty mapping when the receiver has no items (aliases kept as-is).
131
+ */
132
+ export function allocateImportAliases(
133
+ receiver: readonly AliasTypedFields[],
134
+ source: readonly AliasTypedFields[]
135
+ ): AliasMapping {
136
+ if (receiver.length === 0) {
137
+ return {};
138
+ }
139
+ const counts: Record<string, number> = {};
140
+ for (const value of Object.values(CstType)) {
141
+ counts[value] = maxAliasIndex(receiver, value);
142
+ }
143
+ const mapping: AliasMapping = {};
144
+ for (const cst of source) {
145
+ counts[cst.cst_type] += 1;
146
+ mapping[cst.alias] = `${getCstTypePrefix(cst.cst_type)}${counts[cst.cst_type]}`;
147
+ }
148
+ return mapping;
149
+ }
150
+
95
151
  /** Remove alias from expression. */
96
152
  export function removeAliasReference(expression: string, alias: string): string {
97
153
  const escaped = alias.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Attribution remapping helpers for substitution and schema embedding.
3
+ */
4
+
5
+ import { type Attribution } from '../rsform';
6
+
7
+ function attributionKey(attr: Attribution): string {
8
+ return `${attr.container}:${attr.attribute}`;
9
+ }
10
+
11
+ /**
12
+ * Remap attributions when constituents are substituted (original → replacement).
13
+ * Drops self-loops and duplicates. Matches sandbox / backend substitute attribution rewrite.
14
+ */
15
+ export function remapAttributionsUnderSubstitution(
16
+ attributions: readonly Attribution[],
17
+ origToSub: ReadonlyMap<number, number>
18
+ ): Attribution[] {
19
+ const result: Attribution[] = [];
20
+ const seen = new Set<string>();
21
+
22
+ for (const attr of attributions) {
23
+ if (!origToSub.has(attr.container) && !origToSub.has(attr.attribute)) {
24
+ const key = attributionKey(attr);
25
+ if (!seen.has(key)) {
26
+ seen.add(key);
27
+ result.push({ ...attr });
28
+ }
29
+ continue;
30
+ }
31
+
32
+ const container = origToSub.get(attr.container) ?? attr.container;
33
+ const attribute = origToSub.get(attr.attribute) ?? attr.attribute;
34
+ if (container === attribute) {
35
+ continue;
36
+ }
37
+ const key = `${container}:${attribute}`;
38
+ if (seen.has(key)) {
39
+ continue;
40
+ }
41
+ seen.add(key);
42
+ result.push({ container, attribute });
43
+ }
44
+
45
+ return result;
46
+ }
47
+
48
+ /**
49
+ * Copy attributions whose both endpoints are in {@link sourceIdSet}, remapping ids via {@link idMap}.
50
+ * Appends onto a clone of {@link existing} with dedupe. Used by schema embedding / insert.
51
+ */
52
+ export function importAttributions(
53
+ sourceAttributions: readonly Attribution[],
54
+ sourceIdSet: ReadonlySet<number>,
55
+ idMap: Readonly<Record<number, number>>,
56
+ existing: readonly Attribution[] = []
57
+ ): Attribution[] {
58
+ const result = existing.map(attr => ({ ...attr }));
59
+ const seen = new Set(result.map(attributionKey));
60
+
61
+ for (const attr of sourceAttributions) {
62
+ if (!sourceIdSet.has(attr.container) || !sourceIdSet.has(attr.attribute)) {
63
+ continue;
64
+ }
65
+ const container = idMap[attr.container];
66
+ const attribute = idMap[attr.attribute];
67
+ if (container === undefined || attribute === undefined || container === attribute) {
68
+ continue;
69
+ }
70
+ const key = `${container}:${attribute}`;
71
+ if (seen.has(key)) {
72
+ continue;
73
+ }
74
+ seen.add(key);
75
+ result.push({ container, attribute });
76
+ }
77
+
78
+ return result;
79
+ }
80
+
81
+ /** Drop attributions that reference any id in {@link deletedIds}. */
82
+ export function filterAttributions(
83
+ attributions: readonly Attribution[],
84
+ deletedIds: ReadonlySet<number>
85
+ ): Attribution[] {
86
+ return attributions.filter(attr => !deletedIds.has(attr.container) && !deletedIds.has(attr.attribute));
87
+ }
@@ -4,7 +4,9 @@
4
4
 
5
5
  import { TypeClass, TypeID, type Typification } from '../../rslang';
6
6
  import { type EchelonFunctional, isTypification } from '../../rslang/semantic/typification';
7
- import { type Constituenta, CstClass, CstType } from '../rsform';
7
+ import { CstClass, CstType } from '../rsform';
8
+
9
+ import { type StructureCapableFields } from './types';
8
10
 
9
11
  /** Record of {@link CstType} prefixes. */
10
12
  const CST_TYPE_PREFIX: Record<CstType, string> = {
@@ -58,8 +60,8 @@ export function inferClass(type: CstType, isTemplate: boolean = false): CstClass
58
60
  return CST_TYPE_TO_CLASS[type];
59
61
  }
60
62
 
61
- /** Check if {@link Constituenta} is a template or a category. */
62
- export function isTemplateCst(cst: Constituenta): boolean {
63
+ /** Check if item type is a template or a category. */
64
+ export function isTemplateCst(cst: { cst_type: CstType }): boolean {
63
65
  return cst.cst_type === CstType.FUNCTION || cst.cst_type === CstType.PREDICATE || cst.cst_type === CstType.STATEMENT;
64
66
  }
65
67
 
@@ -177,8 +179,8 @@ export function typeClassForCstType(cstType: CstType): TypeClass {
177
179
  }
178
180
  }
179
181
 
180
- /** Evaluate if {@link Constituenta} can be used produce structure. */
181
- export function canProduceStructure(cst: Constituenta): boolean {
182
+ /** Evaluate if an item can be used to produce structure. */
183
+ export function canProduceStructure(cst: StructureCapableFields): boolean {
182
184
  switch (cst.cst_type) {
183
185
  case CstType.NOMINAL:
184
186
  case CstType.BASE:
@@ -5,7 +5,7 @@
5
5
  import { type AstNode } from '../../parsing';
6
6
  import { ValueClass } from '../../rslang';
7
7
  import { generateExpressionFromAst, parseRSLangExpression } from '../../rslang/api';
8
- import { type ArgumentValue, type Constituenta, CstStatus, CstType } from '../rsform';
8
+ import { type ArgumentValue, CstStatus, CstType } from '../rsform';
9
9
 
10
10
  import { isBasicConcept } from './cst-type';
11
11
 
@@ -61,8 +61,8 @@ export function inferTemplate(expression: string): boolean {
61
61
  return (match && match?.length > 0) ?? false;
62
62
  }
63
63
 
64
- /** Apply filter based on start {@link Constituenta} type. */
65
- export function applyFilterCategory(start: Constituenta, items: Constituenta[]): Constituenta[] {
64
+ /** Apply filter based on start item type within an ordered list. */
65
+ export function applyFilterCategory<T extends { cst_type: CstType }>(start: T, items: readonly T[]): T[] {
66
66
  const startIndex = items.indexOf(start);
67
67
  if (startIndex === -1) {
68
68
  return [];
@@ -4,9 +4,9 @@ import { CstType } from '../rsform';
4
4
 
5
5
  import { buildFormalDependencyGraph, restoreConstituentOrder } from './formal-graph';
6
6
  import { computeSemanticRelations } from './semantic-relations';
7
- import { type OrderableConstituenta } from './types';
7
+ import { type FormalOrderFields } from './types';
8
8
 
9
- function cst(id: number, alias: string, cst_type: CstType, definition_formal = ''): OrderableConstituenta {
9
+ function cst(id: number, alias: string, cst_type: CstType, definition_formal = ''): FormalOrderFields {
10
10
  return { id, alias, cst_type, definition_formal };
11
11
  }
12
12
 
@@ -7,13 +7,13 @@ import { extractGlobals } from '../../rslang/api';
7
7
  import { CstType } from '../rsform';
8
8
 
9
9
  import { computeSemanticRelations } from './semantic-relations';
10
- import { type OrderableConstituenta, type SemanticRelations } from './types';
10
+ import { type FormalOrderFields, type SemanticRelations } from './types';
11
11
 
12
12
  /**
13
13
  * Build the formal dependency graph: supplier → dependent.
14
14
  * Matches backend {@code RSForm.graph_formal}.
15
15
  */
16
- export function buildFormalDependencyGraph(items: readonly OrderableConstituenta[]): Graph<number> {
16
+ export function buildFormalDependencyGraph(items: readonly FormalOrderFields[]): Graph<number> {
17
17
  const graph = new Graph<number>();
18
18
  const byAlias = new Map(items.map(cst => [cst.alias, cst]));
19
19
  for (const cst of items) {
@@ -36,7 +36,7 @@ export function buildFormalDependencyGraph(items: readonly OrderableConstituenta
36
36
  *
37
37
  * One Kahn pass over the formal dependency graph.
38
38
  */
39
- export function restoreConstituentOrder<T extends OrderableConstituenta>(
39
+ export function restoreConstituentOrder<T extends FormalOrderFields>(
40
40
  items: readonly T[],
41
41
  graph: Graph<number> = buildFormalDependencyGraph(items),
42
42
  relations: SemanticRelations = computeSemanticRelations(items, graph)
@@ -77,9 +77,7 @@ export function restoreConstituentOrder<T extends OrderableConstituenta>(
77
77
  const pendingChildren: number[] = [];
78
78
 
79
79
  function enqueueSticky(candidateIds: readonly number[]): void {
80
- const sticky = candidateIds.filter(
81
- childId => ready.has(childId) && !pendingChildren.includes(childId)
82
- );
80
+ const sticky = candidateIds.filter(childId => ready.has(childId) && !pendingChildren.includes(childId));
83
81
  sticky.sort((left, right) => (rank.get(left) ?? 0) - (rank.get(right) ?? 0));
84
82
  pendingChildren.push(...sticky);
85
83
  }
@@ -138,7 +136,7 @@ export function restoreConstituentOrder<T extends OrderableConstituenta>(
138
136
  return result;
139
137
  }
140
138
 
141
- function kernelPriority<T extends OrderableConstituenta>(
139
+ function kernelPriority<T extends FormalOrderFields>(
142
140
  items: readonly T[],
143
141
  graph: Graph<number>,
144
142
  parentOf: Map<number, number>
@@ -176,9 +174,7 @@ function kernelPriority<T extends OrderableConstituenta>(
176
174
  const parentId = parentOf.get(cst.id) ?? cst.id;
177
175
  const parent = byId.get(parentId);
178
176
  return (
179
- cst.cst_type === CstType.STRUCTURED ||
180
- cst.cst_type === CstType.AXIOM ||
181
- parent?.cst_type === CstType.STRUCTURED
177
+ cst.cst_type === CstType.STRUCTURED || cst.cst_type === CstType.AXIOM || parent?.cst_type === CstType.STRUCTURED
182
178
  );
183
179
  })
184
180
  .map(cst => cst.id);