{"version":3,"sources":["../src/index.ts","../src/error.ts","../src/utils.ts","../src/AST/index.ts","../src/evaluationFunctions.ts","../src/inferNodeType.ts","../src/evaluationUtils.ts","../src/mecanisms/inlineMecanism.ts","../src/mecanisms/abattement.ts","../src/mecanisms/applicable.ts","../src/units.ts","../src/mecanisms/arrondi.ts","../src/mecanisms/logarithme.ts","../src/nodeUnits.ts","../src/engine/isAValidOption.ts","../src/format.ts","../src/mecanisms/est-non-applicable.ts","../src/parsePossibilité.ts","../src/mecanisms/unePossibilité.ts","../src/ruleUtils.ts","../src/AST/findCycles.ts","../src/AST/graph.ts","../src/rule.ts","../src/mecanisms/avec.ts","../src/mecanisms/trancheUtils.ts","../src/mecanisms/bareme.ts","../src/mecanisms/condition.ts","../src/mecanisms/contexte.ts","../src/date.ts","../src/mecanisms/duree.ts","../src/mecanisms/est.ts","../src/mecanisms/grille.ts","../src/uniroot.ts","../src/mecanisms/inversion.ts","../src/mecanisms/max-min.ts","../src/mecanisms/somme.ts","../src/mecanisms/moyenne.ts","../src/mecanisms/non-applicable.ts","../src/mecanisms/operation.ts","../src/mecanisms/parDefaut.ts","../src/mecanisms/plafond.ts","../src/mecanisms/plancher.ts","../src/mecanisms/product.ts","../src/mecanisms/resoudre-reference-circulaire.ts","../src/mecanisms/simplifier-unite.ts","../src/mecanisms/situation.ts","../src/mecanisms/tauxProgressif.ts","../src/mecanisms/texte.ts","../src/mecanisms/toutes-ces-conditions.ts","../src/mecanisms/une-de-ces-conditions.ts","../src/mecanisms/unite.ts","../src/mecanisms/variablesManquantes.ts","../src/mecanisms/variations.ts","../src/parseExpression.ts","../src/parseReference.ts","../src/parse.ts","../src/parseReplacement.ts","../src/parsePublicodes.ts","../src/traversedVariables.ts","../src/engine/index.ts","../src/serializeEvaluation.ts"],"sourcesContent":["import { type ASTNode, type EvaluatedNode, type NodeKind } from './AST/types'\nimport { Engine } from './engine'\nimport parsePublicodes, { RawRule } from './parsePublicodes'\nimport { type Rule, type RuleNode } from './rule'\nimport {\n\ttype EngineOptions,\n\ttype StrictOptions,\n\ttype FlagOptions,\n\ttype WarnOptions,\n} from './engine/types'\nimport * as utils from './ruleUtils'\n\nexport {\n\treduceAST,\n\tmakeASTTransformer as transformAST,\n\ttraverseASTNode,\n} from './AST/index'\nexport { type Evaluation, type Unit } from './AST/types'\nexport { isPublicodesError, PublicodesError } from './error'\nexport { capitalise0, formatValue } from './format'\nexport { simplifyNodeUnit } from './nodeUnits'\nexport {\n\tparseExpression,\n\ttype ExprAST,\n\ttype BinaryOp,\n\ttype UnaryOp,\n} from './parseExpression'\nexport { default as serializeEvaluation } from './serializeEvaluation'\nexport { parseUnit, serializeUnit } from './units'\nexport { parsePublicodes }\n\n/**\n * Contains utilities to manipulate publicodes rules by name.\n *\n * @namespace\n * @experimental\n */\nexport { utils }\n\nexport default Engine\n\nexport {\n\ttype ASTNode,\n\ttype EngineOptions,\n\ttype EvaluatedNode,\n\ttype NodeKind,\n\ttype Rule,\n\ttype RuleNode,\n\ttype StrictOptions,\n\ttype FlagOptions,\n\ttype WarnOptions,\n}\n\nexport type { Possibility } from './parsePossibilité'\n/**\n * A publicodes expression that can be evaluated by the {@link Engine}.\n *\n * It can be parsed to an ASTNode with the {@link parseExpression} function or evaluated directly by the engine with the {@link Engine.evaluate} method.\n *\n * @example\n * ```js\n * const expression1 = 'prix du panier' // Rule name\n * const expression2 = 'prix du panier + 20' // Operation\n * const expression3 = { valeur: \"salaire brut\", unité: \"€/an\", \"arrondi\": \"oui\" } // Mecanism\n * ```\n */\nexport type PublicodesExpression = string | Record<string, unknown> | number\n\n/**\n * A logger object that can be passed to the engine to log messages.\n *\n * Useful for debugging or customizing the engine's output.\n *  @example only display errors and ignore warnings:\n * ```javascript\n * const logger = {\n * \tlog: () => {},\n * \twarn: () => {},\n * \terror: console.error,\n * }\n * const engine = new Engine(rules, { logger })\n * ```\n */\nexport type Logger = {\n\tlog(message: string): void\n\twarn(message: string): void\n\terror(message: string): void\n}\n\n/**@internal */\nexport type EvaluationFunction<Kind extends NodeKind = NodeKind> = (\n\tthis: Engine,\n\tnode: ASTNode & { nodeKind: Kind },\n) => { nodeKind: Kind } & EvaluatedNode\n\n/**\n * A set of rules that have been parsed from a {@link RawPublicodes} object.\n *\n * @remarks The {@link Engine.evaluate} method is responsable for parsing the rules and cache them in the engine, but you can also parse them manually with the ${@link parsePublicodes} function.\n */\nexport type ParsedRules<RuleNames extends string = string> = Record<\n\tRuleNames,\n\tRuleNode<RuleNames>\n>\n\n/**\n * Rules as they are output from the compilation step : a javascript object transformed from the yaml files\n *\n * They are parsed during the initialization of the engine (see {@link Engine.constructor})\n */\nexport type RawPublicodes<RuleNames extends string> = Partial<\n\tRecord<RuleNames, RawRule>\n>\n\n/**\n * A situation object that can be passed to the engine\n *\n * Can be used to set the values of any existing rules with the {@link Engine.setSituation} method.\n *\n * Note: When strict option on `situation` (see {@link StrictOptions}) is set to the Engine, the situation passed to the engine can be filtered (but retrieved with {@link Engine.getSituation}).\n *\n * @example\n * ```js\n * const situation = {\n * \t\"salaire brut\": 30000 # can be a number\n *  \"contrat . heures travaillées\": {\n * \t  \"valeur\": 35,\n * \t  \"unité\": \"h/semaine\"\n *   }\n *\n */\nexport type Situation<RuleNames extends string> = Partial<\n\tRecord<RuleNames, PublicodesExpression | ASTNode>\n>\n","import { WarnOptions } from '.'\nimport { Context } from './parsePublicodes'\n\n/**\n * Each error name with corresponding type in info value\n */\ninterface PublicodesErrorTypes {\n\tInternalError: {\n\t\tdottedName?: string\n\t}\n\tEngineError: Record<string, never>\n\tSyntaxError: {\n\t\tdottedName: string\n\t}\n\tEvaluationError: {\n\t\tdottedName: string\n\t}\n\tSituationError: { dottedName: string }\n\tUnknownRule: {\n\t\tdottedName: string\n\t}\n\tPrivateRule: {\n\t\tdottedName: string\n\t}\n\tTypeError: {\n\t\tdottedName: string\n\t}\n\tParserError: {\n\t\tdottedName: string\n\t\tposition: number\n\t\texpression: string\n\t\texpected: string\n\t\tfound: string\n\t}\n}\n\n/**\n * @returns true if `error` is a PublicodesError\n *\n * @internal\n *\n * use `name` parameter to check and narow error type\n * @example\n * try {\n * \tnew Engine().evaluate()\n * } catch (error) {\n * \tif (isPublicodesError(error, 'EngineError')) {\n * \t\tconsole.log(error.info)\n * \t}\n * }\n */\nexport const isPublicodesError = <Name extends keyof PublicodesErrorTypes>(\n\terror: unknown,\n\tname?: Name,\n): error is PublicodesError<\n\ttypeof name extends undefined ? keyof PublicodesErrorTypes : Name\n> =>\n\terror instanceof PublicodesError &&\n\t(name === undefined ? true : error.name === name)\n\n/**\n * Generic error for Publicodes\n * @internal\n */\nexport class PublicodesError<\n\tName extends keyof PublicodesErrorTypes,\n> extends Error {\n\tname: Name\n\tinfo: PublicodesErrorTypes[Name]\n\n\tconstructor(\n\t\tname: Name,\n\t\tmessage: string,\n\t\tinfo: PublicodesErrorTypes[Name],\n\t\toriginalError?: Error,\n\t) {\n\t\tsuper(buildMessage(name, message, info, originalError))\n\t\tthis.name = name\n\t\tthis.info = info\n\t}\n}\n\nconst buildMessage = (\n\tname: string,\n\tmessage: string,\n\tinfo?: PublicodesErrorTypes[keyof PublicodesErrorTypes],\n\toriginalError?: Error,\n) => {\n\tconst types: Partial<Record<keyof PublicodesErrorTypes, string>> = {\n\t\tSyntaxError: 'Erreur syntaxique',\n\t\tEvaluationError: \"Erreur d'évaluation\",\n\t\tSituationError: 'Erreur lors de la mise à jour de la situation',\n\t\tUnknownRule: 'Règle inconnue',\n\t\tPrivateRule: 'Règle privée',\n\t}\n\tconst isError = /error/i.test(name)\n\n\treturn (\n\t\t`\\n[ ${types[name] ?? name} ]` +\n\t\t(info && 'dottedName' in info && info.dottedName?.length ?\n\t\t\t`\\n➡️  Dans la règle \"${info.dottedName}\"`\n\t\t:\t'') +\n\t\t`\\n${isError ? '✖️' : '⚠️'}  ${message}` +\n\t\t(originalError ?\n\t\t\t'\\n' + (isError ? '    ' : 'ℹ️  ') + originalError.message\n\t\t:\t'')\n\t)\n}\n\n/**\n * @deprecated Throw an internal server error, replace this by `throw new PublicodesError('InternalError', ...)`\n */\nexport class PublicodesInternalError extends PublicodesError<'InternalError'> {\n\tconstructor(payload: Record<string, unknown>) {\n\t\tsuper(\n\t\t\t'InternalError',\n\t\t\t`\nErreur interne du moteur.\n\nCette erreur est le signe d'un bug dans publicodes. Pour nous aider à le résoudre, vous pouvez copier ce texte dans un nouveau ticket : https://github.com/betagouv/mon-entreprise/issues/new.\n\npayload:\n${JSON.stringify(payload, null, 2)}\n`,\n\t\t\tpayload,\n\t\t)\n\t}\n}\n\n/**\n * Use this error in default case of a switch to check exhaustivity statically\n * inspired by https://github.com/ts-essentials/ts-essentials#exhaustive-switch-cases\n */\nexport class UnreachableCaseError extends PublicodesInternalError {\n\tconstructor(value: never) {\n\t\tsuper({\n\t\t\ttype: 'UNREACHABLE_CODE',\n\t\t\tvalue,\n\t\t})\n\t}\n}\n\nexport function warning(\n\tcontext: Context,\n\tmessage: string,\n\ttype: keyof WarnOptions,\n\toriginalError?: Error,\n) {\n\tif (!context.warn[type]) {\n\t\treturn\n\t}\n\n\tcontext.logger.warn(\n\t\tbuildMessage(\n\t\t\t'Avertissement',\n\t\t\tmessage,\n\t\t\t{\n\t\t\t\tdottedName: context.evaluatedRule ?? context.dottedName,\n\t\t\t},\n\t\t\toriginalError,\n\t\t),\n\t)\n}\n\nexport function experimentalRuleWarning(context: Context, dottedName: string) {\n\tif (!context.warn.experimentalRules) {\n\t\treturn\n\t}\n\tcontext.logger.warn(\n\t\tbuildMessage(\n\t\t\t'Avertissement',\n\t\t\t\"Cette règle est tagguée comme experimentale. \\n\\nCela veut dire qu'elle peut être modifiée, renommée, ou supprimée sans qu'il n'y ait de changement de version majeure dans l'API.\\n\",\n\t\t\t{ dottedName },\n\t\t),\n\t)\n}\n","export function addToMapSet<T>(map: Map<T, Set<T>>, key: T, value: T) {\n\tif (map.has(key)) {\n\t\tmap.get(key)!.add(value)\n\t\treturn\n\t}\n\tmap.set(key, new Set([value]))\n}\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(obj1: Record<N, Array<T>>, obj2: Record<M, Array<T>>): Record<N | M, Array<T>>\n\nexport function mergeWithArray<\n\tN extends string | number | symbol,\n\tM extends string | number | symbol,\n\tT,\n>(\n\tobj1: Partial<Record<N, Array<T>>>,\n\tobj2: Partial<Record<M, Array<T>>>,\n): Partial<Record<N | M, Array<T>>>\n\nexport function mergeWithArray<K extends string | number | symbol, T>(\n\tobj1: Partial<Record<K, Array<T>>>,\n\tobj2: Partial<Record<K, Array<T>>>,\n): Partial<Record<K, Array<T>>> {\n\treturn (Object.entries(obj2) as Array<[K, Array<T>]>).reduce(\n\t\t(obj, [key, value]) => ({\n\t\t\t...obj,\n\t\t\t[key]: [...(obj[key] ?? []), ...value],\n\t\t}),\n\t\tobj1,\n\t)\n}\n\nexport const weakCopyObj = <T extends Record<string, unknown>>(obj: T): T => {\n\tconst copy = {} as T\n\tfor (const key in obj) {\n\t\tcopy[key] = obj[key]\n\t}\n\n\treturn copy\n}\n","import { ParsedRules, Possibility } from '..'\nimport { UnreachableCaseError } from '../error'\nimport { TrancheNodes } from '../mecanisms/trancheUtils'\nimport { ReferenceNode } from '../parseReference'\nimport { ReplacementRule } from '../parseReplacement'\nimport { weakCopyObj } from '../utils'\nimport {\n\tASTNode,\n\tASTTransformer,\n\tASTVisitor,\n\tNodeKind,\n\tTraverseFunction,\n} from './types'\n\n/**\n\tThis function creates a transormation of the AST from on a simpler\n\tcallback function `fn`\n\n\t`fn` will be called with the nodes of the ASTTree during the exploration\n\n\tThe outcome of the callback function has an influence on the exploration of the AST :\n\t- `false`, the node is not updated and the exploration does not continue further down this branch\n\t- `undefined`, the node is not updated but the exploration continues and its children will be transformed\n\t- `ASTNode`, the node is transformed to the new value and the exploration does not continue further down the branch\n\n\t`updateFn` : It is possible to specifically use the updated version of a child\n\tby using the function passed as second argument. The returned value will be the\n\ttransformed version of the node.\n\t*/\nexport function makeASTTransformer(\n\tfn: (node: ASTNode, transform: ASTTransformer) => ASTNode | undefined | false,\n\tstopOnUpdate = true,\n): ASTTransformer {\n\tfunction transform(node: ASTNode): ASTNode {\n\t\tconst updatedNode = fn(node, transform)\n\t\tif (updatedNode === false) {\n\t\t\treturn node\n\t\t}\n\t\tif (updatedNode === undefined) {\n\t\t\treturn traverseASTNode(transform, node)\n\t\t}\n\t\treturn stopOnUpdate ? updatedNode : traverseASTNode(transform, updatedNode)\n\t}\n\treturn transform\n}\nexport function makeASTVisitor(\n\tfn: (node: ASTNode, visit: ASTVisitor) => 'continue' | 'stop',\n): ASTVisitor {\n\tfunction visit(node: ASTNode) {\n\t\tswitch (fn(node, visit)) {\n\t\t\tcase 'continue':\n\t\t\t\ttraverseASTNode(transformizedVisit, node)\n\t\t\t\treturn\n\t\t\tcase 'stop':\n\t\t\t\treturn\n\t\t}\n\t}\n\tconst transformizedVisit: ASTTransformer = (node) => {\n\t\tvisit(node)\n\t\treturn node\n\t}\n\treturn visit\n}\n\n// Can be made more flexible with other args like a filter function (ASTNode -> Bool).\nexport function iterAST(\n\tchildrenSelector: (node: ASTNode) => Iterable<ASTNode>,\n\tnode: ASTNode,\n): ASTNode[] {\n\tfunction* iterate(node: ASTNode): IterableIterator<ASTNode> {\n\t\tyield node\n\t\tconst selectedSubNodes = childrenSelector(node)\n\t\tfor (const subNode of selectedSubNodes) yield* iterate(subNode)\n\t}\n\treturn [...iterate(node)]\n}\n\n/**\n * This function allows to construct a specific value while exploring the AST with\n * a simple reducing function as argument.\n *\n * `fn` will be called with the currently reduced value `acc` and the current node of the AST\n *\n * If the callback function returns:\n * - `undefined`, the exploration continues further down and all the children are reduced\n * \tsuccessively to a single value\n * - `T`, the reduced value is returned\n *\n * `reduceFn` : It is possible to specifically use the reduced value of a child\n * by using the function passed as second argument. The returned value will be the reduced version\n * of the node\n */\nexport function reduceAST<T>(\n\tfn: (acc: T, n: ASTNode, reduceFn: (n: ASTNode) => T) => T | undefined,\n\tstart: T,\n\tnode: ASTNode,\n): T {\n\tfunction traverseFn(acc: T, node: ASTNode): T {\n\t\tconst result = fn(acc, node, traverseFn.bind(null, start))\n\t\tif (result === undefined) {\n\t\t\treturn getChildrenNodes(node).reduce(traverseFn, acc)\n\t\t}\n\t\treturn result\n\t}\n\treturn traverseFn(start, node)\n}\n\nexport function getChildrenNodes(node: ASTNode): ASTNode[] {\n\tconst nodes: ASTNode[] = []\n\ttraverseASTNode((node) => {\n\t\tnodes.push(node)\n\t\treturn node\n\t}, node)\n\treturn nodes\n}\n\nexport function traverseParsedRules<Names extends string>(\n\tfn: ASTTransformer,\n\tparsedRules: ParsedRules<Names>,\n): ParsedRules<Names> {\n\tconst ret = {} as Record<Names, ASTNode>\n\tfor (const name in parsedRules) {\n\t\tret[name] = fn(parsedRules[name])\n\t}\n\n\treturn ret as ParsedRules<Names>\n}\n\n/**\n * Apply a transform function on children. Not recursive.\n */\nexport const traverseASTNode: TraverseFunction<NodeKind> = (fn, node) => {\n\tnode = traverseSourceMap(fn, node)\n\tswitch (node.nodeKind) {\n\t\tcase 'rule':\n\t\t\treturn traverseRuleNode(fn, node)\n\t\tcase 'reference':\n\t\tcase 'constant':\n\t\t\treturn node\n\t\tcase 'arrondi':\n\t\t\treturn traverseArrondiNode(fn, node)\n\t\tcase 'simplifier unité':\n\t\tcase 'variable manquante':\n\t\tcase 'est non applicable':\n\t\tcase 'est non défini':\n\t\tcase 'logarithme':\n\t\t\treturn traverseUnaryOperationNode(fn, node)\n\t\tcase 'barème':\n\t\tcase 'taux progressif':\n\t\tcase 'grille':\n\t\t\treturn traverseNodeWithTranches(fn, node)\n\t\tcase 'durée':\n\t\t\treturn traverseDuréeNode(fn, node)\n\t\tcase 'résoudre référence circulaire':\n\t\t\treturn traverseRésoudreRéférenceCirculaireNode(fn, node)\n\t\tcase 'inversion':\n\t\t\treturn traverseInversionNode(fn, node)\n\t\tcase 'operation':\n\t\t\treturn traverseOperationNode(fn, node)\n\t\tcase 'une possibilité':\n\t\t\treturn traverseUnePossibilitéNode(fn, node)\n\t\tcase 'contexte':\n\t\t\treturn traverseContexteNode(fn, node)\n\t\tcase 'unité':\n\t\t\treturn traverseUnitéNode(fn, node)\n\t\tcase 'variations':\n\t\t\treturn traverseVariationNode(fn, node)\n\t\tcase 'replacementRule':\n\t\t\treturn traverseReplacementNode(fn, node)\n\t\tcase 'texte':\n\t\t\treturn traverseTextNode(fn, node)\n\t\tcase 'condition':\n\t\t\treturn traverseConditionNode(fn, node)\n\n\t\tdefault:\n\t\t\tthrow new UnreachableCaseError(node)\n\t}\n}\n\nconst traverseSourceMap: TraverseFunction<NodeKind> = (fn, node) => {\n\tif (!('sourceMap' in node) || !node.sourceMap || !node.sourceMap.args) {\n\t\treturn node\n\t}\n\tconst sourceMap = node.sourceMap\n\n\tconst args = {}\n\tfor (const key in sourceMap.args) {\n\t\tconst value = sourceMap.args[key]\n\t\targs[key] = Array.isArray(value) ? value.map((v) => fn(v)) : fn(value)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tsourceMap: {\n\t\t\t...sourceMap,\n\t\t\targs,\n\t\t},\n\t}\n}\n\nconst traverseRuleNode: TraverseFunction<'rule'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.suggestions = {}\n\tfor (const key in node.suggestions) {\n\t\tcopy.suggestions[key] = fn(node.suggestions[key])\n\t}\n\tif (copy.possibilities) {\n\t\tcopy.possibilities = fn(copy.possibilities) as any\n\t}\n\tcopy.replacements = node.replacements.map(fn) as Array<ReplacementRule>\n\tcopy.explanation = {\n\t\truleDisabledByItsParent: node.explanation.ruleDisabledByItsParent,\n\t\tnullableParent:\n\t\t\tnode.explanation.nullableParent ?\n\t\t\t\tfn(node.explanation.nullableParent)\n\t\t\t:\tundefined,\n\t\tparents: node.explanation.parents.map(fn),\n\t\tvaleur: fn(node.explanation.valeur),\n\t}\n\treturn copy\n}\n\nconst traverseReplacementNode: TraverseFunction<'replacementRule'> = (\n\tfn,\n\tnode,\n) =>\n\t({\n\t\t...node,\n\t\tdefinitionRule: fn(node.definitionRule),\n\t\treplacedReference: fn(node.replacedReference),\n\t\twhiteListedNames: node.whiteListedNames.map(fn),\n\t\tblackListedNames: node.blackListedNames.map(fn),\n\t}) as ReplacementRule\n\nconst traverseUnaryOperationNode: TraverseFunction<\n\t| 'simplifier unité'\n\t| 'est non applicable'\n\t| 'est non défini'\n\t| 'variable manquante'\n\t| 'logarithme'\n> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = fn(node.explanation)\n\treturn copy\n}\n\nfunction traverseTranche(fn: (n: ASTNode) => ASTNode, tranches: TrancheNodes) {\n\treturn tranches.map((tranche) => ({\n\t\t...tranche,\n\t\t...(tranche.plafond && { plafond: fn(tranche.plafond) }),\n\t\t...('montant' in tranche && { montant: fn(tranche.montant) }),\n\t\t...('taux' in tranche && { taux: fn(tranche.taux) }),\n\t}))\n}\nconst traverseNodeWithTranches: TraverseFunction<\n\t'barème' | 'taux progressif' | 'grille'\n> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = {\n\t\tassiette: fn(node.explanation.assiette),\n\t\tmultiplicateur: fn(node.explanation.multiplicateur),\n\t\ttranches: traverseTranche(fn, node.explanation.tranches),\n\t}\n\treturn copy\n}\n\nconst traverseOperationNode: TraverseFunction<'operation'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = [fn(node.explanation[0]), fn(node.explanation[1])]\n\n\treturn copy\n}\n\nconst traverseDuréeNode: TraverseFunction<'durée'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = {\n\t\tdepuis: fn(node.explanation.depuis),\n\t\t\"jusqu'à\": fn(node.explanation[\"jusqu'à\"]),\n\t}\n\treturn copy\n}\n\nconst traverseInversionNode: TraverseFunction<'inversion'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = {\n\t\t...node.explanation,\n\t\tinversionCandidates: node.explanation.inversionCandidates.map(fn) as any, // TODO\n\t}\n\treturn copy\n}\n\nconst traverseArrondiNode: TraverseFunction<'arrondi'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = {\n\t\tvaleur: fn(node.explanation.valeur),\n\t\tarrondi: fn(node.explanation.arrondi),\n\t}\n\treturn copy\n}\n\nconst traverseRésoudreRéférenceCirculaireNode: TraverseFunction<\n\t'résoudre référence circulaire'\n> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = {\n\t\t...node.explanation,\n\t\tvaleur: fn(node.explanation.valeur),\n\t}\n\treturn copy\n}\n\nconst traverseTextNode: TraverseFunction<'texte'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\n\tcopy.explanation = node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : fn(element),\n\t)\n\treturn copy\n}\n\nconst traverseContexteNode: TraverseFunction<'contexte'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = {\n\t\t...copy.explanation,\n\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\tfn(name) as ReferenceNode,\n\t\t\tfn(value),\n\t\t]),\n\t\tvaleur: fn(node.explanation.valeur),\n\t}\n\treturn copy\n}\n\nconst traverseUnitéNode: TraverseFunction<'unité'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = fn(node.explanation)\n\n\treturn copy\n}\n\nconst traverseVariationNode: TraverseFunction<'variations'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = node.explanation.map(({ condition, consequence }) => ({\n\t\tcondition: fn(condition),\n\t\tconsequence: consequence && fn(consequence),\n\t}))\n\treturn copy\n}\n\nconst traverseConditionNode: TraverseFunction<'condition'> = (fn, node) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = {\n\t\tsi: fn(node.explanation.si),\n\t\talors: fn(node.explanation.alors),\n\t\tsinon: fn(node.explanation.sinon),\n\t}\n\treturn copy\n}\n\nconst traverseUnePossibilitéNode: TraverseFunction<'une possibilité'> = (\n\tfn,\n\tnode,\n) => {\n\tconst copy = weakCopyObj(node)\n\tcopy.explanation = node.explanation.map((node) => {\n\t\tconst copy = fn(node) as Possibility & ASTNode<'reference' | 'constant'>\n\t\tcopy.notApplicable = fn(node.notApplicable)\n\n\t\treturn copy\n\t})\n\n\treturn copy\n}\n","import { EvaluationFunction, PublicodesError } from '.'\nimport { ASTNode } from './AST/types'\n\nexport let evaluationFunctions = {\n\tconstant: (node) => node,\n} as any\n\nexport function registerEvaluationFunction<\n\tNodeName extends ASTNode['nodeKind'],\n>(nodeKind: NodeName, evaluationFunction: EvaluationFunction<NodeName>) {\n\tevaluationFunctions ??= {}\n\tif (evaluationFunctions[nodeKind]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Multiple evaluation functions registered for the nodeKind \\x1b[4m${nodeKind}`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\tevaluationFunctions[nodeKind] = evaluationFunction\n}\n","import { ParsedRules } from '.'\nimport { ASTNode, ConstantNode } from './AST/types'\n\nexport type NodesTypes = WeakMap<ASTNode, InferedType>\n\n// TODO: Currently only handle nullability, but the infering logic should be\n// extended to support the full unit type system.\nexport type InferedType = {\n\tisNullable: boolean | undefined\n} & Pick<ConstantNode, 'type'>\n\nconst UNDEFINED_TYPE = {\n\tisNullable: undefined,\n\ttype: undefined,\n}\n\nexport default function inferNodesTypes(\n\tnewRulesNames: Array<string>,\n\tparsedRules: ParsedRules<string>,\n\tnodesTypes: NodesTypes,\n) {\n\tfunction inferNodeUnitAndCache(node: ASTNode): InferedType {\n\t\tif (!node || typeof node !== 'object') {\n\t\t\treturn UNDEFINED_TYPE\n\t\t}\n\t\tif (nodesTypes.has(node)) {\n\t\t\treturn nodesTypes.get(node)!\n\t\t}\n\t\t// Sometimes there are cycles, so we need to prevent infinite loop by setting a default\n\t\tnodesTypes.set(node, UNDEFINED_TYPE)\n\t\tconst type = inferNodeType(node)\n\t\tnodesTypes.set(node, type)\n\t\treturn type\n\t}\n\n\tfunction inferNodeType(node: ASTNode): InferedType {\n\t\tswitch (node.nodeKind) {\n\t\t\tcase 'barème':\n\t\t\tcase 'durée':\n\t\t\tcase 'grille':\n\t\t\tcase 'taux progressif':\n\t\t\tcase 'inversion':\n\t\t\tcase 'résoudre référence circulaire':\n\t\t\t\treturn { isNullable: false, type: 'number' }\n\t\t\tcase 'est non défini':\n\t\t\tcase 'est non applicable':\n\t\t\t\treturn { isNullable: false, type: 'boolean' }\n\n\t\t\tcase 'constant':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: node.isNullable ?? node.nodeValue === null,\n\t\t\t\t\ttype: node.type,\n\t\t\t\t}\n\t\t\tcase 'operation':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable:\n\t\t\t\t\t\t['<', '<=', '>', '>=', '/', '*'].includes(node.operationKind) ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable ||\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[1]).isNullable\n\t\t\t\t\t\t: node.operationKind === '-' ?\n\t\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation[0]).isNullable\n\t\t\t\t\t\t:\tfalse,\n\t\t\t\t\ttype:\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t['<', '<=', '>', '>=', '=', '!=', 'et', 'ou'].includes(\n\t\t\t\t\t\t\t\tnode.operationKind,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t'boolean'\n\t\t\t\t\t\t:\t'number',\n\t\t\t\t}\n\n\t\t\tcase 'replacementRule':\n\t\t\t\treturn { isNullable: false, type: undefined }\n\t\t\tcase 'texte':\n\t\t\t\treturn { isNullable: false, type: 'string' }\n\t\t\tcase 'arrondi':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tisNullable: inferNodeUnitAndCache(node.explanation.valeur).isNullable,\n\t\t\t\t}\n\t\t\tcase 'logarithme':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tisNullable: inferNodeUnitAndCache(node.explanation).isNullable,\n\t\t\t\t}\n\t\t\tcase 'contexte':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation.valeur)\n\t\t\tcase 'une possibilité':\n\t\t\t\treturn node.type === 'reference' ?\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tisNullable: node.explanation.every(\n\t\t\t\t\t\t\t\t(n) => inferNodeUnitAndCache(n).isNullable,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\ttype: 'string',\n\t\t\t\t\t\t}\n\t\t\t\t\t:\t{\n\t\t\t\t\t\t\tisNullable: false,\n\t\t\t\t\t\t\ttype: node.type,\n\t\t\t\t\t\t}\n\n\t\t\tcase 'rule':\n\t\t\t\t{\n\t\t\t\t\tconst typeInfo = inferNodeUnitAndCache(node.explanation.valeur)\n\t\t\t\t\tif (node.possibilities) {\n\t\t\t\t\t\tconst possibilityTypeInfo = inferNodeUnitAndCache(\n\t\t\t\t\t\t\tnode.possibilities,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tisNullable: typeInfo.isNullable || possibilityTypeInfo.isNullable,\n\t\t\t\t\t\t\ttype: possibilityTypeInfo.type,\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (typeInfo.type !== undefined) {\n\t\t\t\t\t\treturn typeInfo\n\t\t\t\t\t}\n\t\t\t\t\tlet type =\n\t\t\t\t\t\tnode.rawNode.type === 'nombre' ? 'number'\n\t\t\t\t\t\t: node.rawNode.type === 'texte' ? 'string'\n\t\t\t\t\t\t: node.rawNode.type === 'date' ? 'date'\n\t\t\t\t\t\t: node.rawNode.type === 'booléen' ? 'boolean'\n\t\t\t\t\t\t: undefined\n\n\t\t\t\t\tif (!type && node.rawNode.question) {\n\t\t\t\t\t\ttype = 'boolean'\n\t\t\t\t\t}\n\t\t\t\t\treturn { isNullable: typeInfo.isNullable, type } as InferedType\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\tcase 'unité':\n\t\t\tcase 'simplifier unité':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tisNullable: inferNodeUnitAndCache(node.explanation).isNullable,\n\t\t\t\t}\n\t\t\tcase 'variable manquante':\n\t\t\t\treturn inferNodeUnitAndCache(node.explanation)\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: [\n\t\t\t\t\t\tnode.explanation.si,\n\t\t\t\t\t\tnode.explanation.alors,\n\t\t\t\t\t\tnode.explanation.sinon,\n\t\t\t\t\t].some((n) => inferNodeUnitAndCache(n).isNullable),\n\t\t\t\t\ttype:\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.alors).type ??\n\t\t\t\t\t\tinferNodeUnitAndCache(node.explanation.sinon).type,\n\t\t\t\t}\n\n\t\t\tcase 'variations': {\n\t\t\t\tconst consequencesTypes = node.explanation.map(({ consequence }) =>\n\t\t\t\t\tinferNodeUnitAndCache(consequence),\n\t\t\t\t)\n\t\t\t\treturn {\n\t\t\t\t\tisNullable: consequencesTypes.some(\n\t\t\t\t\t\t(consequence) => consequence.isNullable,\n\t\t\t\t\t),\n\t\t\t\t\ttype: consequencesTypes\n\t\t\t\t\t\t.map((c) => c.type)\n\t\t\t\t\t\t.find((type) => type !== undefined),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcase 'reference':\n\t\t\t\treturn inferNodeUnitAndCache(parsedRules[node.dottedName as string])\n\t\t}\n\t}\n\n\tnewRulesNames.forEach((name) => {\n\t\tconst rule = parsedRules[name]\n\t\tinferNodeUnitAndCache(rule)\n\t\trule.explanation.parents.forEach(inferNodeUnitAndCache)\n\t})\n\n\treturn nodesTypes\n}\n","import { ASTNode, ConstantNode, EvaluatedNode, Evaluation } from './AST/types'\n\nexport const collectNodeMissing = (\n\tnode: EvaluatedNode | ASTNode,\n): Record<string, number> =>\n\t'missingVariables' in node ? node.missingVariables : {}\n\nexport const bonus = (missings: Record<string, number> = {}) =>\n\tObject.fromEntries(\n\t\tObject.entries(missings).map(([key, value]) => [key, value + 1]),\n\t)\nexport const mergeMissing = (\n\tleft: Record<string, number> | undefined = {},\n\tright: Record<string, number> | undefined = {},\n): Record<string, number> =>\n\tObject.fromEntries(\n\t\t[...Object.keys(left), ...Object.keys(right)].map((key) => [\n\t\t\tkey,\n\t\t\t(left[key] ?? 0) + (right[key] ?? 0),\n\t\t]),\n\t)\n\nexport const mergeAllMissing = (missings: Array<EvaluatedNode | ASTNode>) =>\n\tmissings.map(collectNodeMissing).reduce(mergeMissing, {})\n\nexport const defaultNode = (nodeValue: Evaluation) =>\n\t({\n\t\tnodeValue,\n\t\ttype: typeof nodeValue,\n\t\tisDefault: true,\n\t\tnodeKind: 'constant',\n\t}) as ConstantNode\n\nexport const notApplicableNode = {\n\tnodeKind: 'constant',\n\tnodeValue: null,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: true,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNode = {\n\tnodeKind: 'constant',\n\tnodeValue: undefined,\n\tmissingVariables: {},\n\ttype: undefined,\n\tisNullable: false,\n} as EvaluatedNode<'constant'>\n\nexport const undefinedNumberNode = {\n\t...undefinedNode,\n\ttype: 'number',\n} as EvaluatedNode<'constant'>\n","import { PublicodesExpression } from '..'\nimport { makeASTTransformer } from '../AST'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport parse from '../parse'\nimport { Context, createContext } from '../parsePublicodes'\n\nexport function createParseInlinedMecanism(\n\tname: string,\n\targs: Record<string, { 'par défaut'?: PublicodesExpression; type?: 'liste' }>,\n\tbody: PublicodesExpression,\n) {\n\tlet parsedBody\n\tlet parsedDefaultArgs\n\tfunction parseInlineMecanism(providedArgs, context) {\n\t\tparsedBody ??= parse(body, createContext({ dottedName: 'INLINE_MECANISM' }))\n\t\tparsedDefaultArgs ??= {}\n\t\tfor (const name in args) {\n\t\t\tif ('par défaut' in args[name]) {\n\t\t\t\tparsedDefaultArgs[name] = parse(\n\t\t\t\t\targs[name]['par défaut'],\n\t\t\t\t\tcreateContext({}),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tparsedProvidedArgs[name] = parse(providedArgs[name], context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = makeASTTransformer((node) => {\n\t\t\tif (node.nodeKind !== 'reference' || !(node.name in args)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst argName = node.name\n\t\t\tif (argName in parsedProvidedArgs) {\n\t\t\t\treturn parsedProvidedArgs[argName]\n\t\t\t}\n\t\t\tif (argName in parsedDefaultArgs) {\n\t\t\t\treturn parsedDefaultArgs[argName]\n\t\t\t}\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Il manque la clé '${argName} dans le mécanisme ${name}`,\n\t\t\t\t{ dottedName: argName },\n\t\t\t)\n\t\t})(parsedBody)\n\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\n/**\n Note : Les transformations de mécanisme opérant sur les listes sont plus couteuses que celles opérant sur des scalaires.\n\n Cela vient du fait qu'il n'y a pas la possibilité de définir ces transformations dans publicodes : il manque le type liste et les opérations de bases associées (reduce, map).\n\n On doit donc déplier l'opération statiquement, au parsing, ce qui prend plus de temps, au parsing et à l'évaluation. somme: [1,2,3] est transformé en (1 + 2) + 3).\n\n De manière général, les baisse en performances de cette PR sont attenduee : il s'agit d'une contrepartie logique de l'utilisation de mécanisme de base publicodes. Ce qu'on gagne en solidité de l'évaluation & en amélioration du typage, on le perd en performance. C'est logique puisque l'evaluation de ces mécanisme n'est plus du JS natif mais passe par une structure intermédiaire.\n\n Pour améliorer les perfs, il y a plusieurs pistes :\n\n\t- optimiser d'avantage les opérations de bases\n\t- ajouter les listes et les opérations sur les listes dans publicodes\n\t- ajouter une implémentation \"native\" de certains mécanismes utilisés (on gagne quand même à les décomposer en mécanismes de base pour la partie spécification et typage).\n */\nexport function createParseInlinedMecanismWithArray(\n\tname: string,\n\targs: Record<string, { type?: 'liste' }>,\n\tbody: (\n\t\targs: Record<string, ASTNode | Array<ASTNode>>,\n\t) => PublicodesExpression,\n) {\n\tfunction parseInlineMecanism(providedArgs, context: Context) {\n\t\t// Case of unary mecanism\n\t\tif (Object.keys(args).length === 1 && 'valeur' in args) {\n\t\t\tprovidedArgs = {\n\t\t\t\tvaleur: providedArgs,\n\t\t\t}\n\t\t}\n\n\t\tconst parsedProvidedArgs = {}\n\t\tfor (const name in providedArgs) {\n\t\t\tconst value = providedArgs[name]\n\t\t\tparsedProvidedArgs[name] =\n\t\t\t\tArray.isArray(value) ?\n\t\t\t\t\tvalue.map((v) => parse(v, context))\n\t\t\t\t:\tparse(value, context)\n\t\t}\n\n\t\tconst parsedInlineMecanism = parse(body(parsedProvidedArgs), context)\n\t\tparsedInlineMecanism.sourceMap = {\n\t\t\tmecanismName: name,\n\t\t\targs: parsedProvidedArgs,\n\t\t}\n\t\treturn parsedInlineMecanism\n\t}\n\n\tparseInlineMecanism.nom = name\n\n\treturn Object.assign(parseInlineMecanism, 'name', {\n\t\tvalue: `parse${toCamelCase(name)}Inline`,\n\t})\n}\n\nfunction toCamelCase(str: string) {\n\treturn str\n\t\t.replace(/(?:^\\w|[A-Z]|\\b\\w)/g, (ltr) => ltr.toUpperCase())\n\t\t.replace(/\\s+/g, '')\n}\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'abattement',\n\t{\n\t\tabattement: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'-': ['valeur', 'abattement'],\n\t\tplancher: 0,\n\t},\n)\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'applicable si',\n\t{\n\t\t'applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'applicable si != non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { BaseUnit, Evaluation, Unit } from './AST/types'\nimport { PublicodesError } from './error'\n/** @experimental */\nexport type getUnitKey = (writtenUnit: string) => string\n/** @experimental */\nexport type formatUnit = (unit: string, count: number) => string\n/**\n * Parse a unit string into a Unit object\n *\n * @param string The unit string to parse\n * @param getUnitKey (@experimental DO NOT USE): A function to normalize the unit string\n *\n * @returns The parsed unit object\n *\n * @example\n * ```ts\n * parseUnit('m/s2')\n * // returns { numerators: ['m'], denominators: ['s', 's'] }\n * ```\n *\n * @experimental\n */\nexport function parseUnit(\n\tstring: string,\n\tgetUnitKey: getUnitKey = (x) => x,\n): Unit {\n\tif (string.includes('/ ')) {\n\t\tthrow new Error(\n\t\t\t`L'unité \"${string}\" ne doit pas contenir d'espace après \"/\"`,\n\t\t)\n\t}\n\tconst [a, ...b] = string.split('/')\n\t// denominator could be 'x/y' or 'x.y' or 'x.y/z'\n\tconst splitUnit = (string: string): string[] =>\n\t\tdecomposePower(\n\t\t\tstring\n\t\t\t\t.trim()\n\t\t\t\t.split('.')\n\t\t\t\t.filter(Boolean)\n\t\t\t\t.map((unit) => getUnitKey(unit)),\n\t\t)\n\tconst result = {\n\t\tnumerators: splitUnit(a),\n\t\tdenominators: b.flatMap((u) => splitUnit(u)),\n\t}\n\treturn result\n}\n\nconst lastNumberFromString = /(\\d+)(?!.*[A-Za-z])/g\n\n/**\n * Count the number of each unit, e.g. [m, m, kg, kg] -> {m: 2, kg: 2}\n */\nfunction getUnitCounts(baseUnits: Array<BaseUnit>): Record<string, number> {\n\tconst countUnits = {}\n\tbaseUnits.forEach((e) => {\n\t\tconst powerMatch = e.match(lastNumberFromString)\n\t\tif (powerMatch != null) {\n\t\t\tconst power = powerMatch[0]\n\t\t\tconst primaryUnit = e.split(power)[0]\n\t\t\tcountUnits[primaryUnit] = (countUnits[primaryUnit] ?? 0) + +power\n\t\t} else {\n\t\t\tcountUnits[e] = (countUnits[e] ?? 0) + 1\n\t\t}\n\t})\n\treturn countUnits\n}\n\n/**\n * Decompose power of units, e.g. [m2] -> [m, m] or [kg2, m3] -> [kg, kg, m, m, m]\n */\nfunction decomposePower(baseUnits: Array<BaseUnit>): Array<BaseUnit> {\n\tconst unitCounts = getUnitCounts(baseUnits)\n\treturn Object.entries(unitCounts).flatMap(([primaryUnit, power]) =>\n\t\tArray(power).fill(primaryUnit),\n\t)\n}\n\n/**\n * Combine power of units, e.g. [m2, m] -> [m3] or [m, m, kg, kg] -> [m2, kg2]\n */\nfunction combinePower(baseUnit: Array<BaseUnit>): Array<BaseUnit> {\n\tconst unitCounts = getUnitCounts(baseUnit)\n\treturn Object.entries(unitCounts).map(([primaryUnit, power]) =>\n\t\tpower > 1 ? `${primaryUnit}${power}` : primaryUnit,\n\t)\n}\n\nconst printUnits = (\n\tunits: Array<BaseUnit>,\n\tcount: number,\n\tformatUnit: formatUnit = (x) => x,\n): string => {\n\treturn combinePower(units.map((unit) => formatUnit(unit, count))).join('.')\n}\n\nconst plural = 2\n\n/**\n * Serialize a unit to a readable string\n * @experimental\n */\nexport function serializeUnit(\n\trawUnit: Unit | undefined | string,\n\tcount: number = plural,\n\tformatUnit: formatUnit = (x) => x,\n): string | undefined {\n\tif (rawUnit === null || typeof rawUnit !== 'object') {\n\t\treturn typeof rawUnit === 'string' ? formatUnit(rawUnit, count) : rawUnit\n\t}\n\tconst unit = simplify(rawUnit)\n\tconst { numerators = [], denominators = [] } = unit\n\n\tconst n = numerators.length > 0\n\tconst d = denominators.length > 0\n\tconst string =\n\t\t!n && !d ? ''\n\t\t: n && !d ? printUnits(numerators, count, formatUnit)\n\t\t: !n && d ? `/${printUnits(denominators, 1, formatUnit)}`\n\t\t: `${printUnits(numerators, plural, formatUnit)}/${printUnits(\n\t\t\t\tdenominators,\n\t\t\t\t1,\n\t\t\t\tformatUnit,\n\t\t\t)}`\n\n\treturn string\n}\n\ntype SupportedOperators = '*' | '/' | '//' | '+' | '-'\n\nconst noUnit = { numerators: [], denominators: [] }\nexport const inferUnit = (\n\toperator: SupportedOperators,\n\trawUnits: Array<Unit | undefined>,\n): Unit | undefined => {\n\tif (operator === '/') {\n\t\tif (rawUnits.length !== 2) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'InternalError',\n\t\t\t\t'Infer units of a division with units.length !== 2)',\n\t\t\t\t{},\n\t\t\t)\n\t\t}\n\n\t\treturn inferUnit('*', [\n\t\t\trawUnits[0] || noUnit,\n\t\t\t{\n\t\t\t\tnumerators: (rawUnits[1] || noUnit).denominators,\n\t\t\t\tdenominators: (rawUnits[1] || noUnit).numerators,\n\t\t\t},\n\t\t])\n\t}\n\tconst units = rawUnits.filter(Boolean)\n\tif (units.length <= 1) {\n\t\treturn units[0]\n\t}\n\tif (operator === '*')\n\t\treturn simplify({\n\t\t\tnumerators: units.flatMap((u) => u?.numerators ?? []),\n\t\t\tdenominators: units.flatMap((u) => u?.denominators ?? []),\n\t\t})\n\n\tif (operator === '-' || operator === '+') {\n\t\treturn rawUnits.find((u) => u)\n\t}\n\n\treturn undefined\n}\n\nconst equals = <T>(a: T, b: T) => {\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\treturn a.length === b.length && a.every((_, i) => a[i] === b[i])\n\t} else {\n\t\treturn a === b\n\t}\n}\n\nexport const removeOnce =\n\t<T>(element: T, eqFn: (a: T, b: T) => boolean = equals) =>\n\t(list: Array<T>): Array<T> => {\n\t\tconst index = list.findIndex((e) => eqFn(e, element))\n\t\treturn list.filter((_, i) => i !== index)\n\t}\n\nconst simplify = (\n\tunit: Unit,\n\teqFn: (a: string, b: string) => boolean = equals,\n): Unit => {\n\tconst simplifiedUnit = [...unit.numerators, ...unit.denominators].reduce(\n\t\t({ numerators, denominators }, next) =>\n\t\t\t(\n\t\t\t\tnumerators.find((u) => eqFn(next, u)) &&\n\t\t\t\tdenominators.find((u) => eqFn(next, u))\n\t\t\t) ?\n\t\t\t\t{\n\t\t\t\t\tnumerators: removeOnce(next, eqFn)(numerators),\n\t\t\t\t\tdenominators: removeOnce(next, eqFn)(denominators),\n\t\t\t\t}\n\t\t\t:\t{ numerators, denominators },\n\t\tunit,\n\t)\n\treturn simplifiedUnit\n}\n\nconst convertTable: ConvertTable = {\n\t'mois/an': 12,\n\t'jour/an': 365,\n\t'jour/mois': 365 / 12,\n\t'trimestre/an': 4,\n\t'mois/trimestre': 3,\n\t'jour/trimestre': (365 / 12) * 3,\n\t'€/k€': 10 ** 3,\n\t'g/kg': 10 ** 3,\n\t'mg/g': 10 ** 3,\n\t'mg/kg': 10 ** 6,\n\t'm/km': 10 ** 3,\n\t'cm/m': 10 ** 2,\n\t'mm/cm': 10 ** 1,\n\t'mm/m': 10 ** 3,\n\t'cm/km': 10 ** 5,\n\t'mm/km': 10 ** 6,\n}\n\nfunction singleUnitConversionFactor(\n\tfrom: string,\n\tto: string,\n): number | undefined {\n\treturn (\n\t\tconvertTable[`${to}/${from}`] ||\n\t\t(convertTable[`${from}/${to}`] && 1 / convertTable[`${from}/${to}`])\n\t)\n}\nfunction unitsConversionFactor(from: string[], to: string[]): number {\n\tlet factor =\n\t\t100 **\n\t\t// Factor is mutliplied or divided 100 for each '%' in units\n\t\t(to.filter((unit) => unit === '%').length -\n\t\t\tfrom.filter((unit) => unit === '%').length)\n\t;[factor] = from.reduce(\n\t\t([value, toUnits], fromUnit) => {\n\t\t\tconst index = toUnits.findIndex(\n\t\t\t\t(toUnit) => !!singleUnitConversionFactor(fromUnit, toUnit),\n\t\t\t)\n\t\t\tconst factor = singleUnitConversionFactor(fromUnit, toUnits[index]) || 1\n\t\t\treturn [\n\t\t\t\tvalue * factor,\n\t\t\t\t[...toUnits.slice(0, index + 1), ...toUnits.slice(index + 1)],\n\t\t\t]\n\t\t},\n\t\t[factor, to],\n\t)\n\treturn factor\n}\n\n// TODO(@clemog):\n// - Deal with other equivalent units : l: 'dm3',\n// - Convert unit instead of ignore warning\nconst equivalentTable = {\n\t'kW.h': 'kWh',\n\t'mn/h': 'noeud',\n}\n\nfunction areEquivalentSerializedUnit(\n\tserializedFrom: string | undefined,\n\tserializedTo: string | undefined,\n): boolean {\n\tif (!serializedFrom || !serializedTo) return false\n\treturn (\n\t\tserializedFrom === serializedTo ||\n\t\tserializedFrom === equivalentTable[serializedTo] ||\n\t\tserializedTo === equivalentTable[serializedFrom]\n\t)\n}\n\nexport function convertUnit<ValType extends Evaluation<number>>(\n\tfrom: Unit | undefined,\n\tto: Unit | undefined,\n\tvalue: ValType,\n): ValType {\n\tconst serializedFrom = serializeUnit(from)\n\tconst serializedTo = serializeUnit(to)\n\tif (\n\t\t!areEquivalentSerializedUnit(serializedFrom, serializedTo) &&\n\t\t!areUnitConvertible(from, to)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t`Impossible de convertir l'unité '${serializedFrom}' en '${serializedTo}'`,\n\t\t\t{},\n\t\t)\n\t}\n\tif (!value) {\n\t\treturn value\n\t}\n\tif (from === undefined) {\n\t\treturn value\n\t}\n\tconst [fromSimplified, factorTo] = simplifyUnitWithValue(from || noUnit)\n\tconst [toSimplified, factorFrom] = simplifyUnitWithValue(to || noUnit)\n\treturn round(\n\t\t((value * factorTo) / factorFrom) *\n\t\t\tunitsConversionFactor(\n\t\t\t\tfromSimplified.numerators,\n\t\t\t\ttoSimplified.numerators,\n\t\t\t) *\n\t\t\tunitsConversionFactor(\n\t\t\t\ttoSimplified.denominators,\n\t\t\t\tfromSimplified.denominators,\n\t\t\t),\n\t) as any\n}\n\nconst convertibleUnitClasses = unitClasses(convertTable)\ntype unitClasses = Array<Set<string>>\ntype ConvertTable = { readonly [index: string]: number }\n\n// Reduce the convertTable provided by the user into a list of compatibles\n// classes.\nfunction unitClasses(convertTable: ConvertTable) {\n\treturn Object.keys(convertTable).reduce(\n\t\t(classes: unitClasses, ratio: string) => {\n\t\t\tconst [a, b] = ratio.split('/')\n\t\t\tconst ia = classes.findIndex((units) => units.has(a))\n\t\t\tconst ib = classes.findIndex((units) => units.has(b))\n\t\t\tif (ia > -1 && ib > -1 && ia !== ib) {\n\t\t\t\tthrow new PublicodesError('EngineError', `Invalid ratio ${ratio}`, {})\n\t\t\t} else if (ia === -1 && ib === -1) {\n\t\t\t\tclasses.push(new Set([a, b]))\n\t\t\t} else if (ia > -1) {\n\t\t\t\tclasses[ia].add(b)\n\t\t\t} else if (ib > -1) {\n\t\t\t\tclasses[ib].add(a)\n\t\t\t}\n\t\t\treturn classes\n\t\t},\n\t\t[],\n\t)\n}\n\nfunction areSameClass(a: string, b: string) {\n\treturn (\n\t\ta === b ||\n\t\tconvertibleUnitClasses.some(\n\t\t\t(unitsClass) => unitsClass.has(a) && unitsClass.has(b),\n\t\t)\n\t)\n}\n\nfunction round(value: number) {\n\treturn +value.toFixed(16)\n}\n\nexport function simplifyUnit(unit: Unit): Unit {\n\tconst { numerators, denominators } = simplify(unit, areSameClass)\n\tif (numerators.length && numerators.every((symb) => symb === '%')) {\n\t\treturn { numerators: ['%'], denominators }\n\t}\n\treturn removePercentages({ numerators, denominators })\n}\n\nfunction simplifyUnitWithValue(unit: Unit, value = 1): [Unit, number] {\n\tconst factor = unitsConversionFactor(unit.numerators, unit.denominators)\n\treturn [\n\t\tsimplify(removePercentages(unit), areSameClass),\n\t\tvalue ? round(value * factor) : value,\n\t]\n}\n\nconst removePercentages = (unit: Unit): Unit => ({\n\tnumerators: unit.numerators.filter((e) => e !== '%'),\n\tdenominators: unit.denominators.filter((e) => e !== '%'),\n})\n\nexport function areUnitConvertible(a: Unit | undefined, b: Unit | undefined) {\n\tif (a == null || b == null) {\n\t\treturn true\n\t}\n\tconst countByUnitClass = (units: Array<BaseUnit>) =>\n\t\tunits.reduce((counters, unit) => {\n\t\t\tconst classIndex = convertibleUnitClasses.findIndex((unitClass) =>\n\t\t\t\tunitClass.has(unit),\n\t\t\t)\n\t\t\tconst key = classIndex === -1 ? unit : '' + classIndex\n\t\t\treturn { ...counters, [key]: 1 + (counters[key] ?? 0) }\n\t\t}, {})\n\n\tconst [numA, denomA, numB, denomB] = [\n\t\ta.numerators,\n\t\ta.denominators,\n\t\tb.numerators,\n\t\tb.denominators,\n\t].map(countByUnitClass)\n\tconst uniq = <T>(arr: Array<T>): Array<T> => [...new Set(arr)]\n\tconst unitClasses = [numA, denomA, numB, denomB].map(Object.keys).flat()\n\treturn uniq(unitClasses).every(\n\t\t(unitClass) =>\n\t\t\t(numA[unitClass] || 0) - (denomA[unitClass] || 0) ===\n\t\t\t\t(numB[unitClass] || 0) - (denomB[unitClass] || 0) || unitClass === '%',\n\t)\n}\n","import { EvaluationFunction, simplifyNodeUnit } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { serializeUnit } from '../units'\n\nexport type ArrondiNode = {\n\texplanation: {\n\t\tarrondi: ASTNode\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'arrondi'\n}\n\nfunction roundWithPrecision(n: number, fractionDigits: number) {\n\treturn (\n\t\tMath.round((n + Number.EPSILON) * 10 ** fractionDigits) /\n\t\t10 ** fractionDigits\n\t)\n}\n\nconst evaluate: EvaluationFunction<'arrondi'> = function (node) {\n\t// We need to simplify the node unit to correctly round values containing\n\t// percentages units, see #1358\n\tconst valeur = simplifyNodeUnit(this.evaluateNode(node.explanation.valeur))\n\tconst nodeValue = valeur.nodeValue\n\tlet arrondi = node.explanation.arrondi\n\tif (nodeValue !== false) {\n\t\tarrondi = this.evaluateNode(arrondi)\n\n\t\tif (\n\t\t\ttypeof (arrondi as EvaluatedNode).nodeValue === 'number' &&\n\t\t\t!serializeUnit((arrondi as EvaluatedNode).unit)?.match(/décimales?/)\n\t\t) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`L'unité ${serializeUnit(\n\t\t\t\t\t(arrondi as EvaluatedNode).unit,\n\t\t\t\t)} de l'arrondi est inconnu. Vous devez utiliser l'unité “décimales”`,\n\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\ttypeof valeur.nodeValue !== 'number' || !('nodeValue' in arrondi) ?\n\t\t\t\tvaleur.nodeValue\n\t\t\t: typeof arrondi.nodeValue === 'number' ?\n\t\t\t\troundWithPrecision(valeur.nodeValue, arrondi.nodeValue)\n\t\t\t: arrondi.nodeValue === true ? roundWithPrecision(valeur.nodeValue, 0)\n\t\t\t: arrondi.nodeValue === undefined ? undefined\n\t\t\t: valeur.nodeValue,\n\t\texplanation: { valeur, arrondi },\n\t\tmissingVariables: mergeAllMissing([valeur, arrondi]),\n\t\tunit: valeur.unit,\n\t}\n}\n\nexport default function parseArrondi(v, context) {\n\tconst explanation = {\n\t\tvaleur: parse(v.valeur, context),\n\t\tarrondi: parse(v.arrondi, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: parseArrondi.nom,\n\t}\n}\n\nparseArrondi.nom = 'arrondi' as const\n\nregisterEvaluationFunction(parseArrondi.nom, evaluate)\n","// packages/core/src/mecanisms/logarithm.ts\nimport { EvaluationFunction, PublicodesError, simplifyNodeUnit } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\n\nexport type LogarithmeNode = {\n\texplanation: ASTNode\n\tnodeKind: 'logarithme'\n}\n\nexport default function parseLogarithm(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'logarithme',\n\t} as LogarithmeNode\n}\n\nconst evaluate: EvaluationFunction<'logarithme'> = function (node) {\n\tconst value = simplifyNodeUnit(this.evaluateNode(node.explanation))\n\tlet y: undefined | number | null\n\tif (value.nodeValue === null || value.nodeValue === undefined) {\n\t\ty = value.nodeValue\n\t} else if (typeof value.nodeValue === 'number') {\n\t\ty = Math.log(value.nodeValue)\n\t} else {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Impossible de calculer le logarithme de ${value.nodeValue}`,\n\t\t\t{\n\t\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\t...node,\n\t\tnodeValue: y,\n\t\tmissingVariables: value.missingVariables,\n\t\texplanation: value,\n\t}\n}\n\nregisterEvaluationFunction('logarithme', evaluate)\n","import { EvaluatedNode, Unit } from './AST/types'\nimport { convertUnit, simplifyUnit } from './units'\n\n/**\n * Simplify if possible the unit of a node\n *\n * If not used, the result of the evaluation of a node will have the\n * most precise unit possible, in order to prevent rounding errors.\n *\n *\n * @param node - The node to simplify\n * @returns The node its unit simplified\n *\n * @example\n * ```ts\n * simplifyNodeUnit(engine.evaluate('42 €/mois * 1 an'))\n * // returns { nodeValue: 504, unit: { numerators: ['€'], denominators: [] } }\n * ```\n */\nexport function simplifyNodeUnit<Node extends EvaluatedNode = EvaluatedNode>(\n\tnode: Node,\n): Node {\n\tif (!node.unit) {\n\t\treturn node\n\t}\n\tconst unit = simplifyUnit(node.unit)\n\n\treturn convertNodeToUnit(unit, node)\n}\n\nexport function convertNodeToUnit<Node extends EvaluatedNode = EvaluatedNode>(\n\tto: Unit | undefined,\n\tnode: Node,\n): Node {\n\treturn {\n\t\t...node,\n\t\tnodeValue:\n\t\t\tnode.unit && typeof node.nodeValue === 'number' ?\n\t\t\t\tconvertUnit(node.unit, to, node.nodeValue)\n\t\t\t:\tnode.nodeValue,\n\t\tunit: to,\n\t}\n}\n","/**\n * Validates if a given value is a valid option according to the defined possibilities.\n *\n * @param engine - The Publicodes engine instance\n * @param possibilities - Node representing a \"une possibilité\" mechanism containing possible values\n * @param value - The node containing the value to validate\n *\n * @returns boolean - True if the value is valid according to the possibilities, false otherwise\n *\n * The validation rules differ based on the type of possibilities:\n * - For numbers: Checks if value matches any possibility (considering unit conversion)\n * - For strings: Checks if value matches any possibility's publicodes representation\n * - For references: Checks if value matches any applicable possibility\n *\n * Note: undefined or null values are always considered valid\n */\nimport { Engine } from '.'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport { UnePossibilitéNode } from '../mecanisms/unePossibilité'\n\nexport function isAValidOption(\n\tengine: Engine,\n\tpossibilities: UnePossibilitéNode,\n\tvalue: EvaluatedNode,\n): boolean {\n\tif (value.nodeValue === undefined || value.nodeValue === null) {\n\t\treturn true\n\t}\n\tswitch (possibilities.type) {\n\t\tcase 'number':\n\t\t\treturn possibilities.explanation.some((possibility) => {\n\t\t\t\tif ('unit' in possibility) {\n\t\t\t\t\treturn (\n\t\t\t\t\t\tconvertNodeToUnit(possibility.unit, value).nodeValue ===\n\t\t\t\t\t\tpossibility.nodeValue\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\t(possibility as ASTNode<'constant'>).nodeValue === value.nodeValue\n\t\t\t\t)\n\t\t\t})\n\t\tcase 'string':\n\t\t\treturn possibilities.explanation.some(\n\t\t\t\t(n) => n.publicodesValue === `'${value.nodeValue}'`,\n\t\t\t)\n\t\tcase 'reference': {\n\t\t\tconst evaluatedPossibilités = engine.evaluateNode(possibilities)\n\t\t\treturn evaluatedPossibilités.explanation.some(\n\t\t\t\t(n) =>\n\t\t\t\t\tn.publicodesValue === `'${value.nodeValue}'` &&\n\t\t\t\t\t(n.notApplicable as EvaluatedNode).nodeValue !== true,\n\t\t\t)\n\t\t}\n\t}\n}\n","import { Evaluation, Unit } from './AST/types'\nimport { convertUnit, formatUnit, serializeUnit, simplifyUnit } from './units'\n\nexport const numberFormatter =\n\t({\n\t\tstyle,\n\t\tmaximumFractionDigits = 2,\n\t\tminimumFractionDigits = 0,\n\t\tlanguage,\n\t}: {\n\t\tstyle?: 'currency' | 'percent' | 'decimal'\n\t\tmaximumFractionDigits?: number\n\t\tminimumFractionDigits?: number\n\t\tlanguage?: string\n\t}) =>\n\t(value: number) => {\n\t\t// When we format currency we don't want to display a single decimal digit\n\t\t// ie 8,1€ but we want to display 8,10€\n\t\tconst adaptedMinimumFractionDigits =\n\t\t\t(\n\t\t\t\tstyle === 'currency' &&\n\t\t\t\tmaximumFractionDigits >= 2 &&\n\t\t\t\tminimumFractionDigits === 0 &&\n\t\t\t\t!Number.isInteger(value)\n\t\t\t) ?\n\t\t\t\t2\n\t\t\t:\tminimumFractionDigits\n\t\treturn Intl.NumberFormat(language, {\n\t\t\tstyle,\n\t\t\tcurrency: 'EUR',\n\t\t\tmaximumFractionDigits,\n\t\t\tminimumFractionDigits: adaptedMinimumFractionDigits,\n\t\t}).format(value)\n\t}\n\nexport const formatCurrency = (\n\tnodeValue: number | undefined,\n\tlanguage: string,\n) => {\n\treturn nodeValue == undefined ? '' : (\n\t\t\t(formatNumber({ unit: '€', language, nodeValue }) ?? '').replace(\n\t\t\t\t/^(-)?€/,\n\t\t\t\t'$1€\\u00A0',\n\t\t\t)\n\t\t)\n}\n\nexport const formatPercentage = (nodeValue: number | undefined) =>\n\tnodeValue == undefined ? '' : (\n\t\tformatNumber({ unit: '%', nodeValue, maximumFractionDigits: 2 })\n\t)\n\ntype formatValueOptions = {\n\tmaximumFractionDigits?: number\n\tminimumFractionDigits?: number\n\tlanguage?: string\n\tunit?: Unit | string\n\tformatUnit?: formatUnit\n\tnodeValue: number\n}\n\nfunction formatNumber({\n\tmaximumFractionDigits,\n\tminimumFractionDigits,\n\tlanguage,\n\tformatUnit,\n\tunit,\n\tnodeValue,\n}: formatValueOptions) {\n\tif (typeof nodeValue !== 'number') {\n\t\treturn nodeValue\n\t}\n\tconst serializedUnit =\n\t\tunit ? serializeUnit(unit, nodeValue, formatUnit) : undefined\n\tswitch (serializedUnit) {\n\t\tcase '€':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'currency',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tminimumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue)\n\t\tcase '%':\n\t\t\treturn numberFormatter({\n\t\t\t\tstyle: 'percent',\n\t\t\t\tmaximumFractionDigits,\n\t\t\t\tlanguage,\n\t\t\t})(nodeValue / 100)\n\t\tdefault:\n\t\t\treturn (\n\t\t\t\tnumberFormatter({\n\t\t\t\t\tstyle: 'decimal',\n\t\t\t\t\tminimumFractionDigits,\n\t\t\t\t\tmaximumFractionDigits,\n\t\t\t\t\tlanguage,\n\t\t\t\t})(nodeValue) +\n\t\t\t\t(typeof serializedUnit === 'string' ? `\\u00A0${serializedUnit}` : '')\n\t\t\t)\n\t}\n}\n\nexport function capitalise0(name: undefined): undefined\nexport function capitalise0(name: string): string\n/**\n * @internal\n */\nexport function capitalise0(name?: string) {\n\treturn name && name[0].toUpperCase() + name.slice(1)\n}\n\nconst booleanTranslations = {\n\tfr: { true: 'oui', false: 'non' },\n\ten: { true: 'yes', false: 'no' },\n}\n\n/**\n * Format the result of an evaluation\n *\n * Useful to display the result of a calculation in a user interface.\n * It use the {@link Unit} to format the number and the unit.\n *\n * @param value - The value to format, usually a {@link EvaluatedNode}\n * @param options - Options to customize the formatting\n * @param options.language - @internal The language in which to display the result\n * @param options.displayedUnit - The unit to display, if different from the unit of the value\n * @param options.precision - The number of decimal digits to display\n *\n * @example\n *\n * ```ts\n * formatValue(engine.evaluate('3 € + 2 €')) // '5 €'\n * ```\n */\nexport function formatValue(\n\tvalue: number | { nodeValue: Evaluation; unit?: Unit } | undefined,\n\t{\n\t\tlanguage = 'fr',\n\t\tdisplayedUnit,\n\t\tformatUnit,\n\t\tprecision = 2,\n\t}: {\n\t\tlanguage?: string\n\t\tdisplayedUnit?: string\n\t\tprecision?: number\n\t\tformatUnit?: formatUnit\n\t} = {},\n) {\n\tlet nodeValue =\n\t\t(\n\t\t\ttypeof value === 'number' ||\n\t\t\ttypeof value === 'undefined' ||\n\t\t\tvalue === null\n\t\t) ?\n\t\t\tvalue\n\t\t:\tvalue.nodeValue\n\n\tif (typeof nodeValue === 'number' && Number.isNaN(nodeValue)) {\n\t\treturn 'Erreur dans le calcul du nombre'\n\t}\n\tif (nodeValue === undefined) {\n\t\treturn 'Pas encore défini'\n\t}\n\tif (nodeValue === null) {\n\t\treturn 'Non applicable'\n\t}\n\tif (typeof nodeValue === 'string') {\n\t\treturn nodeValue.replace('\\\\n', '\\n')\n\t}\n\tif (typeof nodeValue === 'boolean')\n\t\treturn booleanTranslations[language][nodeValue]\n\tif (typeof nodeValue === 'number') {\n\t\tlet unit =\n\t\t\t(\n\t\t\t\ttypeof value === 'number' ||\n\t\t\t\ttypeof value === 'undefined' ||\n\t\t\t\t!('unit' in value)\n\t\t\t) ?\n\t\t\t\tundefined\n\t\t\t:\tvalue.unit\n\t\tif (unit) {\n\t\t\tconst simplifiedUnit = simplifyUnit(unit)\n\t\t\tnodeValue = convertUnit(unit, simplifiedUnit, nodeValue)\n\t\t\tunit = simplifiedUnit\n\t\t}\n\t\treturn formatNumber({\n\t\t\tminimumFractionDigits: 0,\n\t\t\tmaximumFractionDigits: precision,\n\t\t\tlanguage,\n\t\t\tformatUnit,\n\t\t\tnodeValue,\n\t\t\tunit: displayedUnit ?? unit,\n\t\t}).trim()\n\t}\n\treturn undefined\n}\n\nexport function serializeValue(\n\t{ nodeValue, unit }: { nodeValue: Evaluation; unit?: Unit },\n\t{ format }: { format: formatUnit },\n) {\n\tconst serializedUnit = (\n\t\tunit && typeof nodeValue === 'number' ?\n\t\t\tserializeUnit(unit, nodeValue, format)\n\t\t:\t'')?.replace(/\\s*\\/\\s*/g, '/')\n\treturn `${nodeValue} ${serializedUnit}`.trim()\n}\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { evaluateDisablingParent } from '../rule'\n\nexport type EstNonApplicableNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non applicable'\n}\nexport function parseEstNonApplicable(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non applicable' as const,\n\t} as EstNonApplicableNode\n}\nparseEstNonApplicable.nom = 'est non applicable'\n\nconst isNotApplicable = (node: ASTNode) => {\n\treturn {\n\t\tnodeKind: 'est non applicable' as const,\n\t\texplanation: node,\n\t}\n}\n\nconst evaluateIsNotApplicable: EvaluationFunction<'est non applicable'> =\n\tfunction (node) {\n\t\tconst valeur = node.explanation\n\n\t\tif (\n\t\t\tthis.context.nodesTypes.get(valeur)?.isNullable === false &&\n\t\t\tvaleur.nodeKind !== 'rule' &&\n\t\t\tvaleur.nodeKind !== 'reference'\n\t\t) {\n\t\t\treturn { ...node, nodeValue: false, missingVariables: {} }\n\t\t}\n\n\t\tif (\n\t\t\tthis.cache.nodes.has(valeur) &&\n\t\t\tthis.cache.nodes.get(valeur) !== undefined\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\tnodeValue: this.cache.nodes.get(valeur)?.nodeValue === null,\n\t\t\t\tmissingVariables: this.cache.nodes.get(valeur)?.missingVariables ?? {},\n\t\t\t}\n\t\t}\n\n\t\tswitch (valeur.nodeKind) {\n\t\t\tcase 'rule': {\n\t\t\t\tconst { ruleDisabledByItsParent, parentMissingVariables } =\n\t\t\t\t\tevaluateDisablingParent(this, valeur)\n\n\t\t\t\tif (ruleDisabledByItsParent) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...node,\n\t\t\t\t\t\tnodeValue: true,\n\t\t\t\t\t\tmissingVariables: parentMissingVariables,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst isNotApplicableEvaluation = this.evaluateNode(\n\t\t\t\t\tisNotApplicable(valeur.explanation.valeur),\n\t\t\t\t)\n\t\t\t\tconst missingVariables = mergeMissing(\n\t\t\t\t\tparentMissingVariables,\n\t\t\t\t\tisNotApplicableEvaluation.missingVariables,\n\t\t\t\t)\n\t\t\t\t// If the rule can be disabled thought the situation, it should be listed inside the missing variables\n\t\t\t\tif (\n\t\t\t\t\tisNotApplicableEvaluation.nodeValue === false &&\n\t\t\t\t\tthis.context.nodesTypes.get(\n\t\t\t\t\t\tthis.context.parsedRules[`${valeur.dottedName} . $SITUATION`],\n\t\t\t\t\t)?.isNullable &&\n\t\t\t\t\t!Object.keys(isNotApplicableEvaluation.missingVariables).length\n\t\t\t\t) {\n\t\t\t\t\tmissingVariables[valeur.dottedName] = 1\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\t...node,\n\t\t\t\t\tnodeValue: isNotApplicableEvaluation.nodeValue,\n\t\t\t\t\tmissingVariables,\n\t\t\t\t}\n\t\t\t}\n\t\t\tcase 'reference':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode(\n\t\t\t\t\t\tisNotApplicable(this.context.parsedRules[valeur.dottedName!]),\n\t\t\t\t\t),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\n\t\t\tcase 'condition':\n\t\t\t\treturn {\n\t\t\t\t\t...this.evaluateNode({\n\t\t\t\t\t\t...valeur,\n\t\t\t\t\t\texplanation: {\n\t\t\t\t\t\t\tsi: valeur.explanation.si,\n\t\t\t\t\t\t\talors: isNotApplicable(valeur.explanation.alors),\n\t\t\t\t\t\t\tsinon: isNotApplicable(valeur.explanation.sinon),\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\t...node,\n\t\t\t\t}\n\t\t}\n\t\tconst evaluatedValeur = this.evaluateNode(valeur)\n\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue:\n\t\t\t\tevaluatedValeur.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tevaluatedValeur.nodeValue === null,\n\t\t\tmissingVariables: evaluatedValeur.missingVariables,\n\t\t}\n\t}\n\nregisterEvaluationFunction('est non applicable', evaluateIsNotApplicable)\n","import { ASTNode, PublicodesError, Unit } from '.'\nimport { parseEstNonApplicable } from './mecanisms/est-non-applicable'\n// import { defaultNode } from './evaluationUtils'\n// import { parseEstNonApplicable } from './mecanisms/est-non-applicable'\nimport parse from './parse'\nimport { Context } from './parsePublicodes'\nimport { Rule } from './rule'\nimport { weakCopyObj } from './utils'\n// import { weakCopyObj } from './utils'\n\n/**\n * Represents a single possibility value in a \"une possibilité\" mechanism. It can be a constant value (string or number), or a reference to an existing rule.\n */\nexport type Possibility = {\n\ttype: 'number' | 'string' | 'reference'\n\n\t/**\n\t * If the possibility is a reference, this contains a node that evaluates the applicability conditions of the referenced rule.\n\t * Otherwise, it contains a constant node evaluating to false (as constant possibility are always applicable, for now)\n\t */\n\tnotApplicable: ASTNode\n\n\t/**\n\t * Representation of this possibility's value in publicodes syntax, can be used in {@link Engine.setSituation} to set the value of the rule.\n\t *\n\t * String are wrapped in single quotes, and numbers are represented as number followed by an optional unit\n\t * @example\n\t * ```ts\n\t * \"'value'\"\n\t * \"42 m/s\"\n\t * ```\n\t */\n\tpublicodesValue: string\n\n\t/**\n\t * The value of the possibility, as it appears in the evaluated node.\n\t */\n\tnodeValue: string | number\n\n\t/**\n\t * The unit of the possibility value, if it is a number\n\t * @see {@link serializeUnit}\n\t */\n\tunit?: Unit\n\n\t/**\n\t * The dotted name of the referenced rule, if the possibility is a reference.\n\t */\n\tdottedName?: string\n\n\t/**\n\t * The title of the referenced rule, if the possibility is a reference.\n\t */\n\ttitle?: string\n}\n\nexport function parsePossibilité(\n\tpossibility: string | Record<string, Rule>,\n\tavec: Record<string, Rule>,\n\tcontext: Context,\n): Possibility & ASTNode<'constant' | 'reference'> {\n\tif (typeof possibility === 'object') {\n\t\tif (Object.keys(possibility).length !== 1) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Il ne peut y avoir qu'une seule définition de règle par possibilité.`,\n\t\t\t\t{ dottedName: context.dottedName },\n\t\t\t)\n\t\t}\n\t\tconst [key, value] = Object.entries(possibility)[0]\n\t\tif (key in avec) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`La règle \"${key}\" est déjà définie`,\n\t\t\t\t{ dottedName: context.dottedName },\n\t\t\t)\n\t\t}\n\t\tavec[key] = value\n\t\tpossibility = key\n\t}\n\n\tconst node = parse(possibility, context)\n\n\tif (node.nodeKind !== 'constant' && node.nodeKind !== 'reference') {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\"${possibility}\" n'est pas une constante ou une référence.\nLes choix possibles doivent être des constantes ou des références.`,\n\t\t\tcontext,\n\t\t)\n\t}\n\n\tif (node.nodeKind === 'reference') {\n\t\treturn {\n\t\t\t...node,\n\t\t\ttype: 'reference',\n\t\t\tnotApplicable:\n\t\t\t\tcontext.flag?.filterNotApplicablePossibilities ?\n\t\t\t\t\tparseEstNonApplicable(weakCopyObj(node), context)\n\t\t\t\t:\tfalseNode,\n\t\t\tnodeValue: node.name,\n\t\t\tpublicodesValue: `'${node.name}'`,\n\t\t} as Possibility & ASTNode<'reference'>\n\t}\n\n\tif (node.type !== 'string' && node.type !== 'number') {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Les choix possibles doivent être des nombres ou des chaînes de caractères.`,\n\t\t\tcontext,\n\t\t)\n\t}\n\n\treturn {\n\t\t...node,\n\t\ttype: node.type,\n\t\tnotApplicable: falseNode,\n\t\tpublicodesValue:\n\t\t\tnode.type === 'string' ?\n\t\t\t\t`'${node.nodeValue}'`\n\t\t\t:\t(node.rawNode as `${number}`),\n\t\tnodeValue: node.nodeValue as string | number,\n\t\t...('unit' in node && { unit: node.unit }),\n\t} as Possibility & ASTNode<'constant'>\n}\n\nconst falseNode = {\n\tnodeKind: 'constant',\n\ttype: 'boolean',\n\tnodeValue: false,\n} as ASTNode<'constant'>\n","import { PublicodesError, serializeUnit } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport { parsePossibilité, Possibility } from '../parsePossibilité'\nimport { Context } from '../parsePublicodes'\nimport { Rule } from '../rule'\nimport { convertUnit } from '../units'\nimport { weakCopyObj } from '../utils'\n\nexport type RulePossibilités =\n\t| Array<string | Record<string, Rule>>\n\t| { possibilités: Array<string | Record<string, Rule>> }\n\nexport type UnePossibilitéNode = {\n\tnodeKind: 'une possibilité'\n\ttype: 'number' | 'string' | 'reference'\n\tunit?: Unit\n\t/**\n\t * The list of possibility node, each representing a possible value for the rule.\n\t */\n\texplanation: Array<Possibility & ASTNode<'reference' | 'constant'>>\n\n\t/** @deprecated : explicitely define a rule for the absence of choice (for instance : 'aucun' or 'non applicable' or 'autre' ) */\n\t'choix obligatoire'?: 'oui' | 'non'\n}\n\n/**\n * Parses a \"une possibilité\" mechanism in a rule, which defines a finite list of possible values.\n *\n * The values can be defined in three ways (latter two are deprecated):\n * 1. At the root level with 'une possibilité'\n * 2. Inside 'valeur' or 'formule'\n * 3. With a nested 'possibilités'\n *\n * Allowed value types:\n * - Strings\n * - Numbers\n * - References to existing rules\n * - Inline rule definitions\n *\n * @param rawRule - Raw rule object containing the possibilities\n * @param context - Parser context with logging and metadata\n * @param avec - Rule definitions object, modified to include inline rules\n * @returns Node representing the mechanism, or null if not defined\n * @throws {PublicodesError} If possibilities are empty or invalid\n *\n * @example\n * ```yaml\n * my rule:\n *   une possibilité:\n *     - value1\n *     - value2:\n *         applicable si: condition\n * ```\n */\nexport function parseUnePossibilité(\n\trawRule: Rule,\n\tcontext: Context,\n\tavec: Record<string, Rule>,\n): UnePossibilitéNode | null {\n\tlet possibilités: RulePossibilités | false = false\n\tlet choixObligatoire: 'oui' | 'non' | undefined\n\tif (rawRule.valeur && rawRule.valeur['une possibilité']) {\n\t\tpossibilités = rawRule.valeur['une possibilité']\n\t\twarning(\n\t\t\tcontext,\n\t\t\t`La clé 'une possibilité' à l'intérieur de la clé 'valeur' est dépréciée, veuillez la déplacer\nau niveau supérieur.`,\n\t\t\t'deprecatedSyntax',\n\t\t)\n\t\tdelete rawRule.valeur['une possibilité']\n\t}\n\tif (rawRule.formule?.['une possibilité']) {\n\t\tpossibilités = rawRule.formule['une possibilité']\n\t\twarning(\n\t\t\tcontext,\n\t\t\t`La clé 'une possibilité' à l'intérieur de la clé 'formule' est dépréciée, veuillez la déplacer au niveau supérieur.`,\n\t\t\t'deprecatedSyntax',\n\t\t)\n\t\tdelete rawRule.formule['une possibilité']\n\t}\n\n\tif ('une possibilité' in rawRule) {\n\t\tif (!rawRule['une possibilité']) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`La clé 'une possibilité' ne peut pas être vide`,\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\tpossibilités = rawRule['une possibilité']\n\t}\n\n\tif (!possibilités) {\n\t\treturn null\n\t}\n\n\tif ('possibilités' in possibilités) {\n\t\t// TODO V2: Remove this block\n\t\tif (possibilités['choix obligatoire']) {\n\t\t\twarning(\n\t\t\t\tcontext,\n\t\t\t\t`Les clés 'choix obligatoire' et 'possibilités' à l'intérieur de 'une possibilité' sont dépréciées. \n\nDéplacez les possibilités directement à la racine de 'une possibilité' .${\n\t\t\t\t\tpossibilités['choix obligatoire'] === 'non' ?\n\t\t\t\t\t\t`Pour ajouter un choix « aucun », « non applicable » ou « autre » à la liste des possibilité, créer explicitement une règle dédiée. Par exemple : \n\n\\`une possibilité: [${possibilités.possibilités.join(', ')}, aucun]\\`\n`\n\t\t\t\t\t:\t''\n\t\t\t\t}`,\n\t\t\t\t'deprecatedSyntax',\n\t\t\t)\n\t\t\tchoixObligatoire = possibilités['choix obligatoire'] as 'oui' | 'non'\n\t\t} else {\n\t\t\twarning(\n\t\t\t\tcontext,\n\t\t\t\t`La clé 'possibilités' à l'intérieur de 'une possibilité' est dépréciée. \n\nDéplacez les possibilités directement à la racine de 'une possibilité'\n`,\n\t\t\t\t'deprecatedSyntax',\n\t\t\t)\n\t\t}\n\t\tpossibilités = possibilités['possibilités']\n\t}\n\n\tif (!possibilités) {\n\t\treturn null\n\t}\n\n\tif (!possibilités.length) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La clé 'une possibilité' doit être un tableau contenant au moins un élément`,\n\t\t\tcontext,\n\t\t)\n\t}\n\n\tconst node = parsePossibilités(possibilités, avec, context)\n\tif (choixObligatoire) {\n\t\tnode['choix obligatoire'] = choixObligatoire\n\t}\n\n\t// Check for duplicates\n\tlet values: Array<string | number>\n\n\tif (node.type === 'number') {\n\t\t// Unit conversion before checking for duplicates\n\t\tvalues = node.explanation.map((currentNode) =>\n\t\t\tconvertUnit(currentNode.unit, node.unit, currentNode.nodeValue as number),\n\t\t)\n\t} else {\n\t\tvalues = node.explanation.map((n) => n.publicodesValue)\n\t}\n\n\tif (new Set(values).size !== values.length) {\n\t\tconst doublons = values\n\t\t\t.map((v, i, a) =>\n\t\t\t\ta.indexOf(v) !== i ? node.explanation[i].publicodesValue : null,\n\t\t\t)\n\t\t\t.filter(Boolean)\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Il ne doit pas y avoir de doublons parmi les possibilités.\nLes valeurs suivantes sont en double : ${doublons.join(', ')}.`,\n\n\t\t\tcontext,\n\t\t)\n\t}\n\n\treturn node\n}\n\nfunction parsePossibilités(\n\tpossibilities: Array<string | Record<string, Rule>>,\n\tavec: Record<string, Rule>,\n\tcontext: Context,\n): UnePossibilitéNode {\n\tlet referenceNode: Possibility\n\n\tconst explanation = possibilities.map((possibility) => {\n\t\tconst node = parsePossibilité(possibility, avec, context)\n\n\t\treferenceNode ??= node\n\n\t\tif (node.type !== referenceNode.type) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Les possibilités doivent être toutes du même type.\n${referenceNode.publicodesValue} et ${node.publicodesValue} ne sont pas du même type.`,\n\t\t\t\tcontext,\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\treferenceNode.type === 'number' &&\n\t\t\tnode.type === 'number' &&\n\t\t\treferenceNode.unit\n\t\t) {\n\t\t\ttry {\n\t\t\t\tconvertUnit(node.unit, referenceNode.unit, 0)\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\t\t\t} catch (e) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t`Les possibilités doivent être toutes dans la même classe d'unité.\n\n\t\t\t\t\t${serializeUnit(node.unit)} n'est pas convertible en ${serializeUnit(\n\t\t\t\t\t\treferenceNode.unit,\n\t\t\t\t\t)}.`,\n\t\t\t\t\tcontext,\n\t\t\t\t)\n\t\t\t}\n\t\t\treferenceNode = node\n\t\t}\n\n\t\treturn node\n\t})\n\n\treferenceNode ??= explanation[0]\n\n\treturn {\n\t\tnodeKind: 'une possibilité',\n\t\t...('unit' in referenceNode ? { unit: referenceNode.unit } : {}),\n\t\ttype: referenceNode.type,\n\t\texplanation,\n\t}\n}\n\nregisterEvaluationFunction(\n\t'une possibilité',\n\tfunction evaluate(node: UnePossibilitéNode) {\n\t\tconst evalNode = weakCopyObj(node) as EvaluatedNode & UnePossibilitéNode\n\t\tif (node.type !== 'reference') {\n\t\t\tevalNode.missingVariables = {}\n\t\t\tevalNode.nodeValue = undefined\n\t\t\treturn evalNode\n\t\t}\n\n\t\tconst explanation = node.explanation.map((n) => {\n\t\t\tconst notApplicable = this.evaluateNode(n.notApplicable)\n\t\t\treturn {\n\t\t\t\t...n,\n\t\t\t\tnotApplicable,\n\t\t\t\tmissingVariables: notApplicable.missingVariables,\n\t\t\t}\n\t\t})\n\t\tevalNode.explanation = explanation\n\t\tevalNode.missingVariables = mergeAllMissing(\n\t\t\texplanation.map((n) => n.notApplicable),\n\t\t)\n\n\t\tconst applicableValues = explanation.filter(\n\t\t\t(n) => n.notApplicable.nodeValue !== true,\n\t\t)\n\n\t\t// If all values are not applicable, the whole possibility is not applicable\n\t\tif (applicableValues.length === 0) {\n\t\t\tevalNode.nodeValue = null\n\t\t\treturn evalNode\n\t\t}\n\n\t\t// If only one value is applicable, return it\n\t\tif (applicableValues.length === 1) {\n\t\t\tevalNode.nodeValue = applicableValues[0].nodeValue\n\t\t\treturn evalNode\n\t\t}\n\n\t\tevalNode.nodeValue = undefined\n\t\treturn evalNode\n\t},\n)\n","import { ParsedRules } from '.'\nimport { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport { ReferencesMaps } from './parsePublicodes'\nimport { ReferenceNode } from './parseReference'\nimport { addToMapSet } from './utils'\n\nexport { cyclicDependencies } from './AST/graph'\n\nconst splitName = (str: string) => str.split(' . ')\nconst joinName = (strs: Array<string>) => strs.join(' . ')\n\n/**\n * Returns the last part of a dottedName (the leaf).\n */\nexport const nameLeaf = (dottedName: string) =>\n\tsplitName(dottedName).slice(-1)?.[0]\n\n/**\n * Encodes a dottedName for the URL to be secure.\n * @see {@link decodeRuleName}\n */\nexport const encodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t?.replace(/\\s\\.\\s/g, '/')\n\t\t.replace(/-/g, '\\u2011') // replace with a insecable tiret to differenciate from space\n\t\t.replace(/\\s/g, '-')\n\n/**\n * Decodes an encoded dottedName.\n * @see {@link encodeRuleName}\n */\nexport const decodeRuleName = (dottedName: string): string =>\n\tdottedName\n\t\t.replace(/\\//g, ' . ')\n\t\t.replace(/-/g, ' ')\n\t\t.replace(/\\u2011/g, '-')\n\n/**\n * Return dottedName from contextName\n */\nexport const contextNameToDottedName = (contextName: string) =>\n\tcontextName.endsWith('$SITUATION') ? ruleParent(contextName) : contextName\n\n/**\n * Returns the parent dottedName\n */\nexport const ruleParent = (dottedName: string): string =>\n\tjoinName(splitName(dottedName).slice(0, -1))\n\n/**\n * Returns an array of dottedName from near parent to far parent.\n */\nexport function ruleParents(dottedName: string): Array<string> {\n\treturn splitName(dottedName)\n\t\t.slice(0, -1)\n\t\t.map((_, i, arr) => joinName(arr.slice(0, i + 1)))\n\t\t.reverse()\n}\n\n/**\n * Returns an array of all child rules of a dottedName\n */\nexport const getChildrenRules = (\n\tparsedRules: ParsedRules<string>,\n\tdottedName: string,\n) => {\n\tconst childrenRules = Object.keys(parsedRules).filter(\n\t\t(ruleDottedName) =>\n\t\t\truleDottedName.startsWith(dottedName) &&\n\t\t\tsplitName(ruleDottedName).length === splitName(dottedName).length + 1,\n\t)\n\n\treturn childrenRules\n}\n\n/**\n * Finds the common ancestor of two dottedName\n */\nexport function findCommonAncestor(dottedName1: string, dottedName2: string) {\n\tconst splitDottedName1 = splitName(dottedName1)\n\tconst splitDottedName2 = splitName(dottedName2)\n\tconst index = splitDottedName1.findIndex(\n\t\t(value, i) => splitDottedName2[i] !== value,\n\t)\n\n\treturn index === -1 ? dottedName1 : joinName(splitDottedName1.slice(0, index))\n}\n\n/**\n * Check wether a rule is accessible from a namespace.\n *\n * Takes into account that some namespace can be `private`, i.e. that they can only be\n * accessed by immediate parent, children or siblings.\n *\n * @param rules The parsed rules\n * @param contextName The context of the call\n * @param name The namespace checked for accessibility\n */\nexport function isAccessible(\n\trules: ParsedRules,\n\tcontextName: string,\n\tname: string,\n) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\n\tconst commonAncestor = findCommonAncestor(contextName, name)\n\tconst parents = [name, ...ruleParents(name), '']\n\tconst rulesToCheckForPrivacy = parents.slice(\n\t\t0,\n\t\tMath.max(parents.indexOf(commonAncestor) - 1, 0),\n\t)\n\n\treturn rulesToCheckForPrivacy.every(\n\t\t(dottedName) =>\n\t\t\t!(dottedName in rules) || rules[dottedName].private === false,\n\t)\n}\n\n/**\n * Check wether a rule is tagged as experimental.\n *\n * Takes into account the a children of an experimental rule is also experimental\n *\n * @param rules The parsed rules\n * @param name The namespace checked for experimental\n */\nexport function isExperimental(rules: ParsedRules, name: string) {\n\tif (!(name in rules)) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t`La règle \"${name}\" n'existe pas`,\n\t\t\t{ dottedName: name },\n\t\t)\n\t}\n\tconst parents = [name, ...ruleParents(name)]\n\treturn parents.some(\n\t\t(dottedName) =>\n\t\t\tdottedName in rules && rules[dottedName].rawNode?.experimental === 'oui',\n\t)\n}\n\nfunction dottedNameFromContext(context: string, partialName: string) {\n\treturn context ? context + ' . ' + partialName : partialName\n}\nexport function disambiguateReference<R extends ParsedRules>(\n\trules: R,\n\treferencedFrom = '',\n\tpartialName: string,\n): keyof R {\n\tconst possibleContexts = ruleParents(referencedFrom)\n\tpossibleContexts.push(referencedFrom)\n\n\t// If the partialName starts with ^ . ^ . ^ . , we want to go up in the parents\n\tif (partialName.startsWith('^ . ')) {\n\t\tconst numberParent = partialName.match(/^(\\^ \\. )+/)![0].length / 4\n\t\tpartialName = partialName.replace(/^(\\^ \\. )+/, '')\n\t\tpossibleContexts.splice(-numberParent)\n\t}\n\n\tconst rootContext = possibleContexts.pop()\n\tpossibleContexts.unshift(rootContext as string)\n\tpossibleContexts.push('')\n\n\tconst context = possibleContexts.find((context) => {\n\t\tconst dottedName = dottedNameFromContext(context, partialName)\n\t\tif (!(dottedName in rules)) {\n\t\t\treturn false\n\t\t}\n\t\tif (dottedName === referencedFrom) {\n\t\t\treturn false\n\t\t}\n\t\treturn isAccessible(rules, referencedFrom, dottedName)\n\t})\n\n\tif (context !== undefined) {\n\t\treturn dottedNameFromContext(context, partialName) as keyof R\n\t}\n\n\t// The last possibility we want to check is if the rule is referencing itself\n\tif (referencedFrom.endsWith(partialName)) {\n\t\treturn referencedFrom as keyof R\n\t}\n\n\tconst possibleDottedName = possibleContexts.map((c) =>\n\t\tdottedNameFromContext(c, partialName),\n\t)\n\n\tif (possibleDottedName.every((dottedName) => !(dottedName in rules))) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La référence \"${partialName}\" est introuvable.\nVérifiez que l'orthographe et l'espace de nom sont corrects`,\n\t\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t\t)\n\t}\n\n\tthrow new PublicodesError(\n\t\t'SyntaxError',\n\t\t`La règle \"${possibleDottedName.find(\n\t\t\t(dottedName) => dottedName in rules,\n\t\t)}\" n'est pas accessible depuis \"${referencedFrom}\".\n\tCela vient du fait qu'elle est privée ou qu'un de ses parent est privé`,\n\t\t{ dottedName: contextNameToDottedName(referencedFrom) },\n\t)\n}\n\nexport function ruleWithDedicatedDocumentationPage(rule) {\n\treturn (\n\t\trule.virtualRule !== true &&\n\t\trule.type !== 'groupe' &&\n\t\trule.type !== 'texte' &&\n\t\trule.type !== 'paragraphe' &&\n\t\trule.type !== 'notification'\n\t)\n}\n\nexport function updateReferencesMapsFromReferenceNode(\n\tnode: ASTNode,\n\treferencesMaps: ReferencesMaps<string>,\n\truleDottedName?: string,\n) {\n\tif (node.nodeKind === 'reference') {\n\t\taddToMapSet(\n\t\t\treferencesMaps.referencesIn,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t\tnode.dottedName,\n\t\t)\n\t\taddToMapSet(\n\t\t\treferencesMaps.rulesThatUse,\n\t\t\tnode.dottedName,\n\t\t\truleDottedName ?? node.contextDottedName,\n\t\t)\n\t}\n}\nexport function disambiguateReferenceNode(\n\tnode: ASTNode,\n\tparsedRules: ParsedRules<string>,\n): ReferenceNode | undefined {\n\tif (node.nodeKind !== 'reference') {\n\t\treturn\n\t}\n\tif (node.dottedName) {\n\t\treturn node\n\t}\n\n\tnode.dottedName = disambiguateReference(\n\t\tparsedRules,\n\t\tnode.contextDottedName,\n\t\tnode.name,\n\t)\n\tnode.title = parsedRules[node.dottedName].title\n\tnode.acronym = parsedRules[node.dottedName].rawNode.acronyme\n\treturn node\n}\n","/* eslint-disable prefer-rest-params */\n\n// Adapted from https://github.com/dagrejs/graphlib (MIT license)\n// and https://github.com/lodash/lodash (MIT license)\n\n// TODO: type this\n\nfunction has(obj, key) {\n\treturn obj != null && Object.prototype.hasOwnProperty.call(obj, key)\n}\nfunction constant(value) {\n\treturn function () {\n\t\treturn value\n\t}\n}\n\nconst DEFAULT_EDGE_NAME = '\\x00'\nconst EDGE_KEY_DELIM = '\\x01'\n\nconst incrementOrInitEntry = (map, k) => {\n\tif (map[k]) {\n\t\tmap[k]++\n\t} else {\n\t\tmap[k] = 1\n\t}\n}\n\nconst decrementOrRemoveEntry = (map, k) => {\n\tif (!--map[k]) {\n\t\tdelete map[k]\n\t}\n}\n\nconst edgeArgsToId = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\treturn (\n\t\tv +\n\t\tEDGE_KEY_DELIM +\n\t\tw +\n\t\tEDGE_KEY_DELIM +\n\t\t(name === undefined ? DEFAULT_EDGE_NAME : name)\n\t)\n}\n\nconst edgeArgsToObj = (isDirected, v_, w_, name) => {\n\tlet v = '' + v_\n\tlet w = '' + w_\n\tif (!isDirected && v > w) {\n\t\tconst tmp = v\n\t\tv = w\n\t\tw = tmp\n\t}\n\tconst edgeObj: any = { v: v, w: w }\n\tif (name) {\n\t\tedgeObj.name = name\n\t}\n\treturn edgeObj\n}\n\nconst edgeObjToId = (isDirected, edgeObj) => {\n\treturn edgeArgsToId(isDirected, edgeObj.v, edgeObj.w, edgeObj.name)\n}\nexport class Graph {\n\tprivate _nodeCount = 0\n\tprivate _edgeCount = 0\n\n\tprivate _isDirected: any\n\n\tprivate _label: undefined\n\tprivate _defaultNodeLabelFn: (...args: any[]) => any\n\tprivate _defaultEdgeLabelFn: (...args: any[]) => any\n\tprivate _nodes: Record<string, any>\n\tprivate _in: Record<string, any>\n\tprivate _preds: Record<string, Record<string, number>>\n\tprivate _out: Record<string, Record<string, string>>\n\tprivate _sucs: Record<string, Record<string, number>>\n\tprivate _edgeObjs: Record<any, any>\n\tprivate _edgeLabels: Record<any, string>\n\n\tconstructor(opts: Record<string, boolean> = {}) {\n\t\tthis._isDirected = has(opts, 'directed') ? opts.directed : true\n\n\t\t// Label for the graph itself\n\t\tthis._label = undefined\n\n\t\t// Defaults to be set when creating a new node\n\t\tthis._defaultNodeLabelFn = constant(undefined)\n\n\t\t// Defaults to be set when creating a new edge\n\t\tthis._defaultEdgeLabelFn = constant(undefined)\n\n\t\t// v -> label\n\t\tthis._nodes = {}\n\n\t\t// v -> edgeObj\n\t\tthis._in = {}\n\n\t\t// u -> v -> Number\n\t\tthis._preds = {}\n\n\t\t// v -> edgeObj\n\t\tthis._out = {} as Record<string, Record<string, string>>\n\n\t\t// v -> w -> Number\n\t\tthis._sucs = {}\n\n\t\t// e -> edgeObj\n\t\tthis._edgeObjs = {}\n\n\t\t// e -> label\n\t\tthis._edgeLabels = {}\n\t}\n\n\t/* === Graph functions ========= */\n\n\tisDirected() {\n\t\treturn this._isDirected\n\t}\n\tsetGraph(label) {\n\t\tthis._label = label\n\t\treturn this\n\t}\n\tgraph() {\n\t\treturn this._label\n\t}\n\n\t/* === Node functions ========== */\n\n\tnodeCount() {\n\t\treturn this._nodeCount\n\t}\n\tnodes() {\n\t\treturn Object.keys(this._nodes)\n\t}\n\tsetNode(v, value: any = undefined) {\n\t\tif (has(this._nodes, v)) {\n\t\t\tif (arguments.length > 1) {\n\t\t\t\tthis._nodes[v] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tthis._nodes[v] = arguments.length > 1 ? value : this._defaultNodeLabelFn(v)\n\t\tthis._in[v] = {}\n\t\tthis._preds[v] = {}\n\t\tthis._out[v] = {}\n\t\tthis._sucs[v] = {}\n\t\t++this._nodeCount\n\t\treturn this\n\t}\n\tsetNodes(vs, value) {\n\t\tvs.forEach((v) => {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis.setNode(v, value)\n\t\t\t} else {\n\t\t\t\tthis.setNode(v)\n\t\t\t}\n\t\t})\n\t\treturn this\n\t}\n\tnode(v) {\n\t\treturn this._nodes[v]\n\t}\n\thasNode(v) {\n\t\treturn has(this._nodes, v)\n\t}\n\tsuccessors(v) {\n\t\tconst sucsV = this._sucs[v]\n\t\tif (sucsV) {\n\t\t\treturn Object.keys(sucsV)\n\t\t}\n\t}\n\n\t/* === Edge functions ========== */\n\n\tedgeCount() {\n\t\treturn this._edgeCount\n\t}\n\tedges() {\n\t\treturn Object.values(this._edgeObjs)\n\t}\n\tsetEdge(\n\t\tv: string,\n\t\tw: string,\n\t\tvalue: any = undefined,\n\t\tname: string | undefined = undefined,\n\t) {\n\t\tv = '' + v\n\t\tw = '' + w\n\n\t\tconst e = edgeArgsToId(this._isDirected, v, w, name)\n\t\tif (has(this._edgeLabels, e)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tthis._edgeLabels[e] = value\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\t// It didn't exist, so we need to create it.\n\t\t// First ensure the nodes exist.\n\t\tthis.setNode(v)\n\t\tthis.setNode(w)\n\n\t\tthis._edgeLabels[e] =\n\t\t\tvalue !== undefined ? value : this._defaultEdgeLabelFn(v, w, name)\n\n\t\tconst edgeObj = edgeArgsToObj(this._isDirected, v, w, name)\n\t\t// Ensure we add undirected edges in a consistent way.\n\t\tv = edgeObj.v\n\t\tw = edgeObj.w\n\n\t\tObject.freeze(edgeObj)\n\t\tthis._edgeObjs[e] = edgeObj\n\t\tincrementOrInitEntry(this._preds[w], v)\n\t\tincrementOrInitEntry(this._sucs[v], w)\n\t\tthis._in[w][e] = edgeObj\n\t\tthis._out[v][e] = edgeObj\n\t\tthis._edgeCount++\n\t\treturn this\n\t}\n\n\tedge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn this._edgeLabels[e]\n\t}\n\n\thasEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\treturn has(this._edgeLabels, e)\n\t}\n\n\tremoveEdge(v, w, name) {\n\t\tconst e =\n\t\t\targuments.length === 1 ?\n\t\t\t\tedgeObjToId(this._isDirected, arguments[0])\n\t\t\t:\tedgeArgsToId(this._isDirected, v, w, name)\n\t\tconst edge = this._edgeObjs[e]\n\t\tif (edge) {\n\t\t\tv = edge.v\n\t\t\tw = edge.w\n\t\t\tdelete this._edgeLabels[e]\n\t\t\tdelete this._edgeObjs[e]\n\t\t\tdecrementOrRemoveEntry(this._preds[w], v)\n\t\t\tdecrementOrRemoveEntry(this._sucs[v], w)\n\t\t\tdelete this._in[w][e]\n\t\t\tdelete this._out[v][e]\n\t\t\tthis._edgeCount--\n\t\t}\n\t\treturn this\n\t}\n\n\toutEdges(v: string, w: string | undefined = undefined) {\n\t\tconst outV = this._out[v]\n\t\tif (outV) {\n\t\t\tconst edges: any = Object.values(outV)\n\t\t\tif (w === undefined) {\n\t\t\t\treturn edges\n\t\t\t}\n\t\t\treturn edges.filter(function (edge) {\n\t\t\t\treturn edge.w === w\n\t\t\t})\n\t\t}\n\t}\n}\n\n/** Cycles stuff **/\n\nfunction tarjan(graph) {\n\tlet index = 0\n\tconst stack: any[] = []\n\tconst visited = {} // node id -> { onStack, lowlink, index }\n\tconst results: any[] = []\n\n\tfunction dfs(v) {\n\t\tconst entry = (visited[v] = {\n\t\t\tonStack: true,\n\t\t\tlowlink: index,\n\t\t\tindex: index++,\n\t\t})\n\t\tstack.push(v)\n\n\t\tgraph.successors(v).forEach(function (w) {\n\t\t\tif (!Object.prototype.hasOwnProperty.call(visited, w)) {\n\t\t\t\tdfs(w)\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].lowlink)\n\t\t\t} else if (visited[w].onStack) {\n\t\t\t\tentry.lowlink = Math.min(entry.lowlink, visited[w].index)\n\t\t\t}\n\t\t})\n\n\t\tif (entry.lowlink === entry.index) {\n\t\t\tconst cmpt: any[] = []\n\t\t\tlet w\n\t\t\tdo {\n\t\t\t\tw = stack.pop()\n\t\t\t\tvisited[w].onStack = false\n\t\t\t\tcmpt.push(w)\n\t\t\t} while (v !== w)\n\t\t\tresults.push(cmpt)\n\t\t}\n\t}\n\n\tgraph.nodes().forEach(function (v) {\n\t\tif (!Object.prototype.hasOwnProperty.call(visited, v)) {\n\t\t\tdfs(v)\n\t\t}\n\t})\n\n\treturn results\n}\n\nexport function findCycles(graph): string[][] {\n\treturn tarjan(graph).filter(function (cmpt) {\n\t\treturn (\n\t\t\tcmpt.length > 1 || (cmpt.length === 1 && graph.hasEdge(cmpt[0], cmpt[0]))\n\t\t)\n\t})\n}\n","import parsePublicodes from '../parsePublicodes'\nimport { findCycles, Graph } from './findCycles'\n\ntype GraphCycles = string[][]\n\nfunction buildDependenciesGraph(rulesDeps: Map<string, Set<string>>) {\n\tconst g = new Graph()\n\t;[...rulesDeps.entries()].forEach(([ruleDottedName, dependencies]) => {\n\t\tdependencies.forEach((depDottedName) => {\n\t\t\tg.setEdge(ruleDottedName, depDottedName)\n\t\t})\n\t})\n\treturn g\n}\n\ntype RawRules = Parameters<typeof parsePublicodes>[0]\n\nexport function cyclesInDependenciesGraph(rawRules: RawRules): GraphCycles {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\treturn cycles.map((c) => c.reverse())\n}\n\n/**\n * Make the cycle as small as possible.\n */\nexport function squashCycle(\n\trulesDependenciesObject: Map<string, Set<string>>,\n\tcycle: string[],\n): string[] {\n\tfunction* loopFrom(i: number) {\n\t\tlet j = i\n\t\twhile (true) {\n\t\t\tyield cycle[j++ % cycle.length]\n\t\t}\n\t}\n\tconst smallCycleStartingAt: string[][] = []\n\tfor (let i = 0; i < cycle.length; i++) {\n\t\tconst smallCycle: string[] = []\n\t\tlet previousVertex: string | undefined = undefined\n\t\tfor (const vertex of loopFrom(i)) {\n\t\t\tif (previousVertex === undefined) {\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t} else if (rulesDependenciesObject.get(previousVertex)?.has(vertex)) {\n\t\t\t\tif (smallCycle.includes(vertex)) {\n\t\t\t\t\tsmallCycle.splice(0, smallCycle.lastIndexOf(vertex))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tsmallCycle.push(vertex)\n\t\t\t\tpreviousVertex = vertex\n\t\t\t}\n\t\t}\n\t\tsmallCycleStartingAt.push(smallCycle)\n\t}\n\n\tconst smallest = smallCycleStartingAt.reduce((minCycle, someCycle) =>\n\t\tsomeCycle.length > minCycle.length ? minCycle : someCycle,\n\t)\n\treturn smallest\n}\n\n/**\n * This function is useful so as to print the dependencies at each node of the\n * cycle.\n * ⚠️  Indeed, the findCycles function returns the cycle found using the\n * Tarjan method, which is **not necessarily the smallest cycle**. However, the\n * smallest cycle is more readable.\n */\nexport function cyclicDependencies(\n\trawRules: RawRules,\n): [GraphCycles, string[]] {\n\tconst { referencesMaps } = parsePublicodes(rawRules)\n\tconst dependenciesGraph = buildDependenciesGraph(referencesMaps.referencesIn)\n\tconst cycles = findCycles(dependenciesGraph)\n\n\tconst reversedCycles = cycles.map((c) => c.reverse())\n\n\tconst smallCycles = reversedCycles.map((cycle) =>\n\t\tsquashCycle(referencesMaps.referencesIn, cycle),\n\t)\n\n\tconst printableStronglyConnectedComponents = reversedCycles.map((c, i) =>\n\t\tprintInDotFormat(dependenciesGraph, c, smallCycles[i]),\n\t)\n\n\treturn [smallCycles, printableStronglyConnectedComponents]\n}\n\n/**\n * Is edge in the cycle, in the same order?\n */\nconst edgeIsInCycle = (cycle: string[], v: string, w: string): boolean => {\n\tfor (let i = 0; i < cycle.length + 1; i++) {\n\t\tif (v === cycle[i] && w === cycle[(i + 1) % cycle.length]) return true\n\t}\n\treturn false\n}\n\nexport function printInDotFormat(\n\tdependenciesGraph: Graph,\n\tcycle: string[],\n\tsubCycleToHighlight: string[],\n) {\n\tconst edgesSet = new Set()\n\tcycle.forEach((vertex) => {\n\t\tdependenciesGraph\n\t\t\t.outEdges(vertex)\n\t\t\t.filter(({ w }) => cycle.includes(w))\n\t\t\t.forEach(({ v, w }) => {\n\t\t\t\tedgesSet.add(\n\t\t\t\t\t`\"${v}\" -> \"${w}\"` +\n\t\t\t\t\t\t(edgeIsInCycle(subCycleToHighlight, v, w) ? ' [color=red]' : ''),\n\t\t\t\t)\n\t\t\t})\n\t})\n\treturn `digraph Cycle {\\n\\t${[...edgesSet].join(';\\n\\t')};\\n}`\n}\n","import Engine, { RawPublicodes } from '.'\nimport { ASTNode, EvaluatedNode, MissingVariables } from './AST/types'\nimport { isAValidOption } from './engine/isAValidOption'\nimport { PublicodesError, warning } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { defaultNode, mergeMissing, undefinedNode } from './evaluationUtils'\nimport { capitalise0 } from './format'\nimport {\n\tparseUnePossibilité,\n\tRulePossibilités,\n\tUnePossibilitéNode,\n} from './mecanisms/unePossibilité'\nimport parse, { mecanismKeys } from './parse'\nimport { Context } from './parsePublicodes'\nimport {\n\tparseRendNonApplicable,\n\tparseReplacements,\n\tReplacementRule,\n} from './parseReplacement'\nimport { isAccessible, nameLeaf, ruleParents } from './ruleUtils'\nimport { weakCopyObj } from './utils'\n\nexport type Rule = {\n\tformule?: Record<string, unknown> | string | number\n\tvaleur?: Record<string, unknown> | string | number\n\tquestion?: string\n\tdescription?: string\n\tunité?: string\n\tacronyme?: string\n\texemples?: any\n\trésumé?: string\n\ticônes?: string\n\ttitre?: string\n\tsévérité?: string\n\texperimental?: 'oui'\n\t'possiblement non applicable'?: 'oui'\n\tprivé?: 'oui'\n\tnote?: string\n\t'une possibilité'?: RulePossibilités\n\tremplace?: Remplace | Array<Remplace>\n\t'rend non applicable'?: Remplace | Array<Remplace>\n\tsuggestions?: Record<string, string | number | Record<string, unknown>>\n\tréférences?: { [source: string]: string }\n\tAPI?: string\n\t'identifiant court'?: string\n} & Record<string, unknown>\n\ntype Remplace =\n\t| {\n\t\t\t'références à': string\n\t\t\tdans?: Array<string> | string\n\t\t\t'sauf dans'?: Array<string> | string\n\t\t\tpriorité?: number\n\t  }\n\t| string\n\nexport type RuleNode<Name extends string = string> = {\n\tdottedName: Name\n\ttitle: string\n\tnodeKind: 'rule'\n\tvirtualRule: boolean\n\tprivate: boolean\n\trawNode: Rule\n\treplacements: Array<ReplacementRule>\n\tpossibilities: UnePossibilitéNode | undefined\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tparents: Array<ASTNode>\n\t\tnullableParent?: ASTNode\n\t\truleDisabledByItsParent: boolean\n\t}\n\tsuggestions: Record<string, ASTNode>\n\t'identifiant court'?: string\n}\n\nfunction parseRule(nom: string, rawRule: Rule, context: Context): RuleNode {\n\tconst privateRule = rawRule.privé === 'oui' || nom.startsWith('[privé] ')\n\tnom = nom.replace(/^\\[privé\\] /, '')\n\tconst dottedName = [context.dottedName, nom].filter(Boolean).join(' . ')\n\n\tconst name = nameLeaf(dottedName)\n\tconst title = capitalise0(rawRule['titre'] ?? name)\n\n\tif (context.parsedRules[dottedName]) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`La référence '${dottedName}' a déjà été définie`,\n\t\t\t{ dottedName },\n\t\t)\n\t}\n\n\tconst currentDottedNameContext = context.dottedName\n\tcontext.dottedName = dottedName\n\n\t// The following ensures that nested rules appears after the root rule when\n\t// iterating over parsedRule\n\tcontext.parsedRules[dottedName] = undefined as any\n\n\tconst ruleValue: Record<string, unknown> = {}\n\n\truleValue.avec = Object.assign({}, rawRule.avec)\n\tconst possibilities = parseUnePossibilité(\n\t\trawRule,\n\t\tcontext,\n\t\truleValue.avec as Record<string, Rule>,\n\t)\n\n\tfor (const key in rawRule) {\n\t\tif (mecanismKeys.includes(key)) {\n\t\t\truleValue[key] ??= rawRule[key]\n\t\t}\n\t}\n\n\tif ('formule' in rawRule) {\n\t\truleValue.valeur = rawRule.formule\n\t}\n\n\tif (!privateRule && !dottedName.endsWith('$SITUATION')) {\n\t\t// We create a $SITUATION child rule for each rule that is not private\n\t\t// This value will be used to evaluate the rule in the current situation (`setSituation`)\n\t\truleValue['dans la situation'] = `${dottedName} . $SITUATION`\n\n\t\tconst situationValue = weakCopyObj(undefinedNode)\n\t\tsituationValue.isNullable = rawRule['possiblement non applicable'] === 'oui'\n\t\t;(ruleValue['avec'] as Record<string, any>)['[privé] $SITUATION'] = {\n\t\t\tvaleur: situationValue,\n\t\t}\n\n\t\t// If the `par défaut` value is used, then the rule should be listed as a missingVariables\n\t\tif (ruleValue['par défaut'] != null) {\n\t\t\truleValue['par défaut'] = {\n\t\t\t\tvaleur: ruleValue['par défaut'],\n\t\t\t\t'variable manquante': dottedName,\n\t\t\t}\n\t\t}\n\t}\n\n\t// Parse possible choices\n\tconst explanation = {\n\t\tvaleur: parse(ruleValue, context),\n\t\t/*\n\t\tWe include a list of references to the parents to implement the branch\n\t\tdesactivation feature. When evaluating a rule we only need to know the\n\t\tfirst nullable parent, but this is something that we can't determine at\n\t\tthis stage :\n\t\t- we need to run remplacements (which works on references in the ASTs\n\t\t  which is why we insert these “virtual” references)\n\t\t- we need to infer unit of the rules\n\n\t\tAn alternative implementation would be possible that would colocate the\n\t\tcode related to branch desactivation (ie find the first nullable parent\n\t\tstatically after rules parsing)\n\n\t\tNote this option can be disabled by setting the `automaticNamespaceDisabling` flag to false.\n\t\t*/\n\t\tparents:\n\t\t\tcontext.flag.automaticNamespaceDisabling ?\n\t\t\t\truleParents(dottedName).map(\n\t\t\t\t\t(parent) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\tdottedName: parent,\n\t\t\t\t\t\t\tnodeKind: 'reference',\n\t\t\t\t\t\t\tcontextDottedName: context.dottedName,\n\t\t\t\t\t\t}) as ASTNode<'reference'>,\n\t\t\t\t)\n\t\t\t:\t[],\n\t}\n\n\tconst suggestions = {} as Record<string, ASTNode>\n\tif (rawRule.suggestions) {\n\t\tfor (const name in rawRule.suggestions) {\n\t\t\tsuggestions[name] = parse(rawRule.suggestions[name], context)\n\t\t}\n\t}\n\n\tcontext.parsedRules[dottedName] = {\n\t\tdottedName,\n\t\treplacements: [\n\t\t\t...parseRendNonApplicable(rawRule['rend non applicable'], context),\n\t\t\t...parseReplacements(rawRule.remplace, context),\n\t\t],\n\t\ttitle: title,\n\t\tprivate: privateRule,\n\t\tsuggestions,\n\t\tnodeKind: 'rule',\n\t\tpossibilities,\n\t\texplanation,\n\t\trawNode: rawRule,\n\t\tvirtualRule: privateRule,\n\t} as RuleNode\n\n\tcontext.dottedName = currentDottedNameContext\n\treturn context.parsedRules[dottedName]\n}\n\nexport function parseRules<RuleNames extends string>(\n\trules: RawPublicodes<RuleNames>,\n\tcontext: Context,\n) {\n\tfor (const dottedName in rules) {\n\t\tlet rule = rules[dottedName]\n\n\t\tif (typeof rule === 'string' || typeof rule === 'number') {\n\t\t\trule = { valeur: `${rule}` }\n\t\t}\n\t\tif (typeof rule !== 'object') {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`Rule ${dottedName} is incorrectly written. Please give it a proper value.\\n ${rule}`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\t\tconst copy = rule === null ? {} : weakCopyObj(rule)\n\t\tparseRule(dottedName, copy as Rule, context)\n\t}\n}\n\nregisterEvaluationFunction('rule', function evaluate(node) {\n\tif (\n\t\t!node.dottedName.endsWith('$SITUATION') &&\n\t\t!node.dottedName.includes('$INTERNAL')\n\t) {\n\t\tthis.context.evaluatedRule = node.dottedName\n\t}\n\tconst { ruleDisabledByItsParent, nullableParent, parentMissingVariables } =\n\t\tevaluateDisablingParent(this, node)\n\n\tconst explanation = {\n\t\t...node.explanation,\n\t\tnullableParent,\n\t\truleDisabledByItsParent,\n\t}\n\tif (ruleDisabledByItsParent) {\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue: null,\n\t\t\tmissingVariables: parentMissingVariables,\n\t\t\texplanation,\n\t\t}\n\t}\n\n\tif (\n\t\tthis.cache._meta.evaluationRuleStack.filter(\n\t\t\t(dottedName) => dottedName === node.dottedName,\n\t\t).length > 1\n\t) {\n\t\tconst cycleIndex = this.cache._meta.evaluationRuleStack.indexOf(\n\t\t\tnode.dottedName,\n\t\t)\n\t\tconst cycle = [\n\t\t\t...this.cache._meta.evaluationRuleStack\n\t\t\t\t.slice(0, cycleIndex + 1)\n\t\t\t\t.reverse(),\n\t\t\tnode.dottedName,\n\t\t]\n\t\tconst message = `\nUn cycle a été détecté lors de l'évaluation de cette règle:\n${cycle.join(cycle.length > 5 ? '\\n → ' : ' → ')}\n\nCela vient probablement d'une erreur dans votre modèle.\n\nSi le cycle est voulu, vous pouvez indiquer au moteur de résoudre la référence circulaire en trouvant le point fixe de la fonction. Pour cela, ajoutez l'attribut suivant niveau de la règle :\n\n\t${node.dottedName}:\n\t\trésoudre la référence circulaire: oui\"\n\t\t...\n`\n\n\t\t// Do not warn if the cycle is due to a rule being disabled by its parent (see https://github.com/publicodes/publicodes/issues/206 for the proper way of doing it)\n\t\tif (\n\t\t\t!this.cache._meta.parentRuleStack.length ||\n\t\t\tthis.cache._meta.parentRuleStack.some(\n\t\t\t\t(dottedName) => !dottedName.startsWith(node.dottedName),\n\t\t\t)\n\t\t) {\n\t\t\tif (this.context.strict.noCycleRuntime) {\n\t\t\t\tthrow new PublicodesError('EvaluationError', message, {\n\t\t\t\t\tdottedName: node.dottedName,\n\t\t\t\t})\n\t\t\t}\n\t\t\twarning(this.context, message, 'cyclicReferences')\n\t\t}\n\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: parentMissingVariables,\n\t\t\texplanation,\n\t\t}\n\t}\n\n\tthis.cache._meta.evaluationRuleStack.unshift(node.dottedName)\n\n\tconst possibilities =\n\t\tnode.possibilities && this.evaluateNode(node.possibilities)\n\n\tif (possibilities?.nodeValue !== undefined) {\n\t\treturn {\n\t\t\t...node,\n\t\t\t...(possibilities.unit ? { unit: possibilities.unit } : {}),\n\t\t\tnodeValue: possibilities.nodeValue,\n\t\t\tmissingVariables: mergeMissing(\n\t\t\t\tpossibilities.missingVariables,\n\t\t\t\tparentMissingVariables,\n\t\t\t),\n\t\t\tpossibilities,\n\t\t}\n\t}\n\n\tconst valeurEvaluation = this.evaluateNode(node.explanation.valeur)\n\tthis.cache._meta.evaluationRuleStack.shift()\n\n\tvaleurEvaluation.missingVariables ??= {}\n\tupdateRuleMissingVariables(this, node, valeurEvaluation)\n\n\tif (\n\t\tpossibilities &&\n\t\tthis.context.strict.checkPossibleValues &&\n\t\t!isAValidOption(this, possibilities, valeurEvaluation)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`La valeur \"${valeurEvaluation.nodeValue}\" de la règle ${node.dottedName} n'est pas une des possibilités attendues`,\n\t\t\t{\n\t\t\t\tdottedName: node.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\tconst unit = possibilities?.unit ?? valeurEvaluation.unit\n\tconst missingVariables = mergeMissing(\n\t\tmergeMissing(\n\t\t\tpossibilities?.missingVariables ?? {},\n\t\t\tvaleurEvaluation.missingVariables,\n\t\t),\n\t\tparentMissingVariables,\n\t)\n\n\treturn {\n\t\t...valeurEvaluation,\n\t\t...(unit ? { unit } : {}),\n\t\tmissingVariables,\n\t\t...node,\n\t\tpossibilities,\n\t\texplanation: {\n\t\t\tparents: node.explanation.parents,\n\t\t\tvaleur: valeurEvaluation,\n\t\t\tnullableParent,\n\t\t\truleDisabledByItsParent,\n\t\t},\n\t}\n})\n\n/*\n\tWe implement the terminal case for missing variables manually here as\n\ta rule is missing if it is undefined and has no other missing dependencies\n*/\nfunction updateRuleMissingVariables(\n\tengine: Engine,\n\tnode: RuleNode,\n\tvaleurEvaluation: EvaluatedNode,\n): void {\n\tif (\n\t\tnode.private === true ||\n\t\t!isAccessible(engine.context.parsedRules, '', node.dottedName)\n\t) {\n\t\treturn\n\t}\n\n\tif (\n\t\tvaleurEvaluation.nodeValue === undefined &&\n\t\t!Object.keys(valeurEvaluation.missingVariables).length\n\t) {\n\t\tvaleurEvaluation.missingVariables[node.dottedName] = 1\n\t}\n\n\treturn\n}\n\nexport function evaluateDisablingParent(\n\tengine: Engine,\n\tnode: RuleNode,\n): {\n\truleDisabledByItsParent: boolean\n\tparentMissingVariables: MissingVariables\n\tnullableParent?: ASTNode\n} {\n\tif (node.dottedName.endsWith('$SITUATION')) {\n\t\t// We do not need to check if a situation rule is disabled by its parent\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tconst nodesTypes = engine.context.nodesTypes\n\tconst nullableParent = node.explanation.parents.find(\n\t\t(ref) =>\n\t\t\tnodesTypes.get(ref)?.isNullable ||\n\t\t\tnodesTypes.get(ref)?.type === 'boolean',\n\t)\n\n\tif (!nullableParent) {\n\t\treturn { ruleDisabledByItsParent: false, parentMissingVariables: {} }\n\t}\n\n\tif (\n\t\t// TODO: remove this condition and the associated \"parentRuleStack\", cycles\n\t\t// should be detected and avoided at parse time.\n\t\t!engine.cache._meta.parentRuleStack.includes(node.dottedName)\n\t) {\n\t\tengine.cache._meta.parentRuleStack.unshift(node.dottedName)\n\t\tlet parentIsNotApplicable = defaultNode(false) as EvaluatedNode\n\t\tif (nodesTypes.get(nullableParent)?.isNullable) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'est non applicable',\n\t\t\t\texplanation: nullableParent,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tparentIsNotApplicable.nodeValue !== true &&\n\t\t\tnodesTypes.get(nullableParent)?.type === 'boolean'\n\t\t) {\n\t\t\tparentIsNotApplicable = engine.evaluateNode({\n\t\t\t\tnodeKind: 'operation',\n\t\t\t\toperator: '=',\n\t\t\t\toperationKind: '=',\n\t\t\t\texplanation: [nullableParent, defaultNode(false)],\n\t\t\t})\n\t\t}\n\n\t\tengine.cache._meta.parentRuleStack.shift()\n\t\tif (parentIsNotApplicable.nodeValue === true) {\n\t\t\treturn {\n\t\t\t\truleDisabledByItsParent: true,\n\t\t\t\tparentMissingVariables: parentIsNotApplicable.missingVariables ?? {},\n\t\t\t\tnullableParent,\n\t\t\t}\n\t\t}\n\t}\n\n\tlet parentMissingVariables: MissingVariables = {}\n\n\tif (nodesTypes.get(nullableParent)?.type === 'boolean') {\n\t\tconst parentEvaluation = engine.evaluateNode(nullableParent)\n\t\tparentMissingVariables = parentEvaluation.missingVariables ?? {}\n\t\treturn {\n\t\t\truleDisabledByItsParent: parentEvaluation.nodeValue === false,\n\t\t\tparentMissingVariables,\n\t\t\tnullableParent,\n\t\t}\n\t}\n\n\treturn {\n\t\truleDisabledByItsParent: false,\n\t\tparentMissingVariables,\n\t\tnullableParent,\n\t}\n}\n","import parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { parseRules } from '../rule'\n\nexport default function parseAvec(v, context: Context) {\n\tparseRules(v.avec, context)\n\tconst valeur = parse(v.valeur, context)\n\treturn valeur\n}\n\nparseAvec.nom = 'avec' as const\n","import Engine from '..'\nimport { ASTNode, Evaluation } from '../AST/types'\nimport { PublicodesError, warning } from '../error'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, inferUnit } from '../units'\n\ntype TrancheNode = { taux: ASTNode } | { montant: ASTNode }\nexport type TrancheNodes = Array<\n\tTrancheNode & { plafond?: ASTNode; isActive?: boolean }\n>\n\nexport const parseTranches = (tranches, context): TrancheNodes => {\n\treturn tranches.map((node, i) => {\n\t\tif (!node.plafond && i > tranches.length) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'SyntaxError',\n\t\t\t\t`La tranche n°${i} du barème n'a pas de plafond précisé. Seule la dernière tranche peut ne pas être plafonnée`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\t...(node.taux !== undefined ? { taux: parse(node.taux, context) } : {}),\n\t\t\t...(node.montant !== undefined ?\n\t\t\t\t{ montant: parse(node.montant, context) }\n\t\t\t:\t{}),\n\t\t\tplafond:\n\t\t\t\t'plafond' in node ?\n\t\t\t\t\tparse(node.plafond, context)\n\t\t\t\t:\t{\n\t\t\t\t\t\tnodeValue: Infinity,\n\t\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tisNullable: false,\n\t\t\t\t\t},\n\t\t}\n\t})\n}\n\nexport function evaluatePlafondUntilActiveTranche(\n\tthis: Engine,\n\t{ multiplicateur, assiette, parsedTranches },\n) {\n\treturn parsedTranches.reduce(\n\t\t([tranches, activeTrancheFound], parsedTranche, i: number) => {\n\t\t\tif (activeTrancheFound) {\n\t\t\t\treturn [\n\t\t\t\t\t[...tranches, { ...parsedTranche, isAfterActive: true }],\n\t\t\t\t\tactiveTrancheFound,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tconst plafond = this.evaluateNode(parsedTranche.plafond)\n\t\t\tconst plancher =\n\t\t\t\ttranches[i - 1] ? tranches[i - 1].plafond : { nodeValue: 0 }\n\n\t\t\tlet plafondValue: Evaluation<number> =\n\t\t\t\t(\n\t\t\t\t\tplafond.nodeValue === undefined ||\n\t\t\t\t\tmultiplicateur.nodeValue === undefined\n\t\t\t\t) ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplafond.nodeValue * multiplicateur.nodeValue\n\n\t\t\ttry {\n\t\t\t\tplafondValue =\n\t\t\t\t\tplafondValue === Infinity || plafondValue === 0 ?\n\t\t\t\t\t\tplafondValue\n\t\t\t\t\t:\tconvertUnit(\n\t\t\t\t\t\t\tinferUnit('*', [plafond.unit, multiplicateur.unit]),\n\t\t\t\t\t\t\tassiette.unit,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t)\n\t\t\t} catch (e) {\n\t\t\t\tif (!(e instanceof Error)) {\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t\twarning(\n\t\t\t\t\tthis.context,\n\t\t\t\t\t`L'unité du plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t}  n'est pas compatible avec celle l'assiette`,\n\t\t\t\t\t'unitConversion',\n\t\t\t\t\te,\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst plancherValue = tranches[i - 1] ? tranches[i - 1].plafondValue : 0\n\t\t\tconst isAfterActive =\n\t\t\t\tplancherValue === undefined || assiette.nodeValue === undefined ?\n\t\t\t\t\tundefined\n\t\t\t\t:\tplancherValue > assiette.nodeValue\n\n\t\t\tconst calculationValues = [plafond, assiette, multiplicateur, plancher]\n\t\t\tif (calculationValues.some((node) => node.nodeValue === undefined)) {\n\t\t\t\treturn [\n\t\t\t\t\t[\n\t\t\t\t\t\t...tranches,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...parsedTranche,\n\t\t\t\t\t\t\tplafond,\n\t\t\t\t\t\t\tplafondValue,\n\t\t\t\t\t\t\tplancherValue,\n\t\t\t\t\t\t\tnodeValue: undefined,\n\t\t\t\t\t\t\tisActive: undefined,\n\t\t\t\t\t\t\tisAfterActive,\n\t\t\t\t\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tfalse,\n\t\t\t\t]\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t!!tranches[i - 1] &&\n\t\t\t\t!!plancherValue &&\n\t\t\t\t(plafondValue as number) <= plancherValue\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'EvaluationError',\n\t\t\t\t\t`Le plafond de la tranche n°${\n\t\t\t\t\t\ti + 1\n\t\t\t\t\t} a une valeur inférieure à celui de la tranche précédente`,\n\t\t\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst tranche = {\n\t\t\t\t...parsedTranche,\n\t\t\t\tplafond,\n\t\t\t\tplancherValue,\n\t\t\t\tplafondValue,\n\t\t\t\tisAfterActive,\n\t\t\t\tisActive:\n\t\t\t\t\tassiette.nodeValue >= plancherValue &&\n\t\t\t\t\tassiette.nodeValue < (plafondValue as number),\n\t\t\t}\n\n\t\t\treturn [[...tranches, tranche], tranche.isActive]\n\t\t},\n\t\t[[], false],\n\t)[0]\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, NodeKind } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\nimport {\n\tTrancheNodes,\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n} from './trancheUtils'\n\n// Barème en taux marginaux.\nexport type BarèmeNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'barème'\n}\nexport default function parseBarème(v, context): BarèmeNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'barème',\n\t}\n}\n\nfunction evaluateBarème(tranches, assiette, evaluate) {\n\treturn tranches.map((tranche) => {\n\t\tif (tranche.isAfterActive) {\n\t\t\treturn { ...tranche, nodeValue: 0 }\n\t\t}\n\t\tconst taux = evaluate(tranche.taux)\n\t\tconst missingVariables = mergeAllMissing([taux, tranche])\n\n\t\tif (\n\t\t\t[\n\t\t\t\tassiette.nodeValue,\n\t\t\t\ttaux.nodeValue,\n\t\t\t\ttranche.plafondValue,\n\t\t\t\ttranche.plancherValue,\n\t\t\t].some((value) => value === undefined)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\ttaux,\n\t\t\t\tnodeValue: undefined,\n\t\t\t\tmissingVariables,\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...tranche,\n\t\t\ttaux,\n\t\t\t...('unit' in assiette && { unit: assiette.unit }),\n\t\t\tnodeValue:\n\t\t\t\t(Math.min(assiette.nodeValue, tranche.plafondValue) -\n\t\t\t\t\ttranche.plancherValue) *\n\t\t\t\tconvertUnit(taux.unit, parseUnit(''), taux.nodeValue as number),\n\t\t\tmissingVariables,\n\t\t}\n\t})\n}\nconst evaluate: EvaluationFunction<'barème'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(\n\t\tnode.explanation.assiette,\n\t) as EvaluatedNode<NodeKind, number>\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\n\tlet tranches: any = node.explanation.tranches\n\tlet nodeValue = assiette.nodeValue\n\n\tif (![0, undefined, null].includes(assiette.nodeValue)) {\n\t\ttranches = evaluateBarème(\n\t\t\tevaluatePlafondUntilActiveTranche.call(this, {\n\t\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\t\tassiette,\n\t\t\t\tmultiplicateur,\n\t\t\t}),\n\t\t\tassiette,\n\t\t\tevaluate,\n\t\t)\n\t\tnodeValue = tranches.reduce(\n\t\t\t(value, { nodeValue }) =>\n\t\t\t\tnodeValue == undefined ? undefined : value + nodeValue,\n\t\t\t0,\n\t\t)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([assiette, multiplicateur, ...tranches]),\n\t\texplanation: {\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: assiette.unit,\n\t} as any\n}\n\nregisterEvaluationFunction('barème', evaluate)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { PublicodesError } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, mergeAllMissing, mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type ConditionNode = {\n\texplanation: {\n\t\tsi: ASTNode\n\t\talors: ASTNode\n\t\tsinon: ASTNode\n\t}\n\tnodeKind: 'condition'\n}\n\nconst evaluate: EvaluationFunction<'condition'> = function (node) {\n\tlet evaluation\n\tconst condition = this.evaluateNode(node.explanation.si)\n\tlet alors = node.explanation.alors\n\tlet sinon = node.explanation.sinon\n\tif ('unit' in condition) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tif (condition.nodeValue === true) {\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\t;(alors as any).isActive = true\n\t\tevaluation = alors\n\t} else if (condition.nodeValue === false) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\tevaluation = sinon\n\t} else if (condition.nodeValue === null) {\n\t\tevaluation = condition\n\t} else if (condition.nodeValue === undefined) {\n\t\tsinon = this.evaluateNode(node.explanation.sinon)\n\t\talors = this.evaluateNode(node.explanation.alors)\n\t\tevaluation = {\n\t\t\t...condition,\n\t\t\tmissingVariables: mergeAllMissing([sinon, alors]),\n\t\t}\n\t} else {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t'La condition doit être de type booléen',\n\t\t\t{ dottedName: this.cache._meta.evaluationRuleStack[0] },\n\t\t)\n\t}\n\tconst unit = evaluation.unit ?? (alors as any).unit\n\treturn {\n\t\tnodeValue: evaluation.nodeValue,\n\t\tmissingVariables: mergeMissing(\n\t\t\tbonus(condition.missingVariables),\n\t\t\tevaluation.missingVariables,\n\t\t),\n\t\t...(unit != undefined ? { unit } : {}),\n\t\t...node,\n\t\texplanation: { si: condition, alors, sinon },\n\t}\n}\nexport default function parseCondition(v, context) {\n\tconst explanation = {\n\t\tsi: parse(v.si, context),\n\t\talors: parse(v.alors, context),\n\t\tsinon: parse(v.sinon, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'condition',\n\t} as ConditionNode\n}\n\nparseCondition.nom = 'condition'\n\nregisterEvaluationFunction('condition', evaluate)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { notApplicableNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { ReferenceNode } from '../parseReference'\nimport { serializeUnit } from '../units'\n\nexport type ContextNode = {\n\texplanation: {\n\t\tvaleur: ASTNode\n\t\tcontexte: Array<[ReferenceNode, ASTNode]>\n\t\tsubEngineId: number\n\t}\n\tnodeKind: 'contexte'\n}\n\nexport default function parseMecanismContexte(v, context) {\n\tconst node = parse(v.valeur, context)\n\tconst contexte = (\n\t\tObject.keys(v.contexte).map((dottedName) => [\n\t\t\tparse(dottedName, context),\n\t\t\tparse(v.contexte[dottedName], context),\n\t\t]) as Array<[ReferenceNode, ASTNode]>\n\t).sort(([a], [b]) => a.name.localeCompare(b.name))\n\tconst contextHash = simpleHash(JSON.stringify(contexte))\n\treturn {\n\t\texplanation: {\n\t\t\tvaleur: node,\n\t\t\tcontexte,\n\t\t\tsubEngineId: contextHash,\n\t\t},\n\t\tnodeKind: parseMecanismContexte.nom,\n\t} as ContextNode\n}\nparseMecanismContexte.nom = 'contexte' as const\n\nconst evaluateContexte: EvaluationFunction<'contexte'> = function (node) {\n\tconst undefinedContextRules: (string | undefined)[] = []\n\tconst amendedSituation = Object.fromEntries(\n\t\tnode.explanation.contexte\n\t\t\t.filter(([originRule, replacement]) => {\n\t\t\t\tconst originRuleEvaluation = this.evaluateNode(originRule)\n\t\t\t\tconst replacementEvaluation = this.evaluateNode(replacement)\n\t\t\t\tif (replacementEvaluation.nodeValue === undefined) {\n\t\t\t\t\tundefinedContextRules.push(originRule.dottedName)\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\toriginRuleEvaluation.nodeValue !== replacementEvaluation.nodeValue ||\n\t\t\t\t\tserializeUnit(originRuleEvaluation.unit) !==\n\t\t\t\t\t\tserializeUnit(replacementEvaluation.unit)\n\t\t\t\t)\n\t\t\t})\n\t\t\t.map(\n\t\t\t\t([originRule, replacement]) =>\n\t\t\t\t\t[originRule.dottedName, replacement] as [string, ASTNode],\n\t\t\t),\n\t)\n\tif (\n\t\tthis.cache._meta.currentContexteSituation ===\n\t\tJSON.stringify(amendedSituation)\n\t) {\n\t\t// If the situation is the same as the last time we evaluated the contexte, it means that\n\t\t// there is a loop\n\t\treturn {\n\t\t\t...notApplicableNode,\n\t\t\t...node,\n\t\t}\n\t}\n\n\tlet engine\n\tif (this.context.subEngines.has(node.explanation.subEngineId)) {\n\t\tengine = this.context.subEngines.get(node.explanation.subEngineId)\n\t} else {\n\t\tengine = this.shallowCopy()\n\t\tengine.context.warn.experimentalRules = false\n\t\tengine.context.subEngineId = node.explanation.subEngineId\n\t\tthis.context.subEngines.set(node.explanation.subEngineId, engine)\n\n\t\tif (Object.keys(amendedSituation).length) {\n\t\t\tengine.setSituation(amendedSituation, {\n\t\t\t\tkeepPreviousSituation: true,\n\t\t\t})\n\n\t\t\t// The following code ensure that we use the **origin context** evaluation\n\t\t\t// for the values in the ammended situation\n\n\t\t\t// We do so by altering the cache so that the situation rule seems to have already\n\t\t\t// been evaluated\n\n\t\t\t// This is not an elegant way of doing so, but its temporary.\n\t\t\t// The correct implementation is discussed in :\n\t\t\t// https://github.com/publicodes/publicodes/discussions/92\n\t\t\tObject.entries(amendedSituation).forEach(([originDottedName, value]) => {\n\t\t\t\tconst evaluation = this.cache.nodes.get(value)\n\t\t\t\tif (!evaluation) {\n\t\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t\t'InternalError',\n\t\t\t\t\t\t'The situation should have already been evaluated',\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst originRule =\n\t\t\t\t\tengine.context.parsedRules[originDottedName + ' . $SITUATION']\n\t\t\t\tif (!originRule?.explanation.valeur) {\n\t\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t\t'InternalError',\n\t\t\t\t\t\t'The origin rule should be defined',\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdottedName: this.context.dottedName,\n\t\t\t\t\t\t},\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tengine.cache.nodes.set(originRule.explanation.valeur, evaluation)\n\t\t\t})\n\t\t}\n\t}\n\n\tengine.cache._meta.currentContexteSituation = JSON.stringify(amendedSituation)\n\tconst evaluatedNode = engine.evaluateNode(node.explanation.valeur)\n\n\tconst contextRules: (string | undefined)[] = node.explanation.contexte.map(\n\t\t([originRule]) => {\n\t\t\treturn originRule.dottedName\n\t\t},\n\t)\n\tconst contextRulesToKeep = contextRules.filter((rule) =>\n\t\tundefinedContextRules.includes(rule as string),\n\t)\n\n\tconst evaluatedMissingVariables = Object.fromEntries(\n\t\tObject.entries(evaluatedNode.missingVariables).filter(\n\t\t\t([missingVariable]) =>\n\t\t\t\t!contextRules.includes(missingVariable) ||\n\t\t\t\tcontextRulesToKeep.includes(missingVariable),\n\t\t),\n\t) as any\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: evaluatedNode.nodeValue,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tvaleur: evaluatedNode,\n\t\t},\n\t\tmissingVariables: evaluatedMissingVariables,\n\t\t...('unit' in evaluatedNode && { unit: evaluatedNode.unit }),\n\t}\n}\n\nregisterEvaluationFunction('contexte', evaluateContexte)\n\nfunction simpleHash(str) {\n\tlet hash = 0\n\tfor (let i = 0, len = str.length; i < len; i++) {\n\t\tconst chr = str.charCodeAt(i)\n\t\thash = (hash << 5) - hash + chr\n\t\thash |= 0 // Convert to 32bit integer\n\t}\n\treturn hash\n}\n","import { PublicodesError } from './error'\n\nexport function normalizeDateString(dateString: string): string {\n\tlet [day, month, year] = dateString.split('/')\n\tif (!year) {\n\t\t;[day, month, year] = ['01', day, month]\n\t}\n\treturn normalizeDate(+year, +month, +day)\n}\n\nconst pad = (n: number): string => (+n < 10 ? `0${n}` : '' + n)\nexport function normalizeDate(\n\tyear: number,\n\tmonth: number,\n\tday: number,\n): string {\n\tconst date = new Date(+year, +month - 1, +day)\n\tif (!+date || date.getDate() !== +day) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`La date ${day}/${month}/${year} n'est pas valide`,\n\t\t\t{ dottedName: '' },\n\t\t)\n\t}\n\treturn `${pad(day)}/${pad(month)}/${pad(year)}`\n}\n\nexport function convertToDate(value: string): Date {\n\tconst [day, month, year] = normalizeDateString(value).split('/')\n\tconst result = new Date(+year, +month - 1, +day)\n\t// Reset date to utc midnight for exact calculation of day difference (no\n\t// daylight saving effect)\n\tresult.setMinutes(result.getMinutes() - result.getTimezoneOffset())\n\treturn result\n}\n\nexport function convertToString(date: Date): string {\n\treturn normalizeDate(date.getFullYear(), date.getMonth() + 1, date.getDate())\n}\n\nexport function getRelativeDate(date: string, dayDifferential: number): string {\n\tconst relativeDate = new Date(convertToDate(date))\n\trelativeDate.setDate(relativeDate.getDate() + dayDifferential)\n\treturn convertToString(relativeDate)\n}\n\nexport function getYear(date: string): number {\n\treturn +date.slice(-4)\n}\n\nexport function getTrimestreCivil(date: string) {\n\tconst [, month, year] = date.split('/')\n\tconst trimester = Math.floor((Number.parseInt(month, 10) - 1) / 3)\n\tconst startingMonth = 3 * trimester + 1\n\treturn `01/${startingMonth.toString().padStart(2, '0')}/${year}`\n}\n\nexport function getDifferenceInDays(from: string, to: string): number {\n\tconst millisecondsPerDay = 1000 * 60 * 60 * 24\n\treturn (\n\t\t(convertToDate(to).getTime() - convertToDate(from).getTime()) /\n\t\tmillisecondsPerDay\n\t)\n}\n\nexport function getDifferenceInMonths(from: string, to: string): number {\n\t// We want to compute the difference in actual month between the two dates\n\t// For date that start during a month, a pro-rata will be done depending on\n\t// the duration of the month in days\n\tconst [dayFrom, monthFrom, yearFrom] = from.split('/').map((x) => +x)\n\tconst [dayTo, monthTo, yearTo] = to.split('/').map((x) => +x)\n\tconst numberOfFullMonth = monthTo - monthFrom + 12 * (yearTo - yearFrom)\n\tconst numDayMonthFrom = new Date(yearFrom, monthFrom, 0).getDate()\n\tconst numDayMonthTo = new Date(yearTo, monthTo, 0).getDate()\n\tconst prorataMonthFrom = (dayFrom - 1) / numDayMonthFrom\n\tconst prorataMonthTo = dayTo / numDayMonthTo\n\treturn numberOfFullMonth - prorataMonthFrom + prorataMonthTo\n}\n\nexport function getDifferenceInYears(from: string, to: string): number {\n\tconst differenceInDays = getDifferenceInDays(from, to)\n\n\tconst isLeapYear = (year: number) =>\n\t\t(year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n\tconst after1stMarch = (date: Date) =>\n\t\tdate >= new Date(date.getFullYear(), 2, 1)\n\n\tconst fromDate = convertToDate(from)\n\tconst toDate = convertToDate(to)\n\n\tconst fromYear = fromDate.getFullYear() + (after1stMarch(fromDate) ? 1 : 0)\n\tconst toYear = toDate.getFullYear() + (after1stMarch(fromDate) ? 0 : -1)\n\n\tconst leapYearsCount = Array.from(\n\t\t{ length: toYear - fromYear + 1 },\n\t\t(_, i) => fromYear + i,\n\t).filter(isLeapYear).length\n\n\treturn (differenceInDays - leapYearsCount) / 365\n}\n\nexport function getDifferenceInTrimestreCivils(\n\tfrom: string,\n\tto: string,\n): number {\n\treturn (\n\t\tMath.floor(\n\t\t\tgetDifferenceInMonths(getTrimestreCivil(from), getTrimestreCivil(to)) / 3,\n\t\t) + 1\n\t)\n}\n\nexport function getDifferenceInYearsCivil(from: string, to: string): number {\n\tconst fromYear = '01/' + getYear(from)\n\tconst toYear = '01/' + getYear(to)\n\treturn Math.floor(getDifferenceInYears(fromYear, toYear)) + 1\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, Evaluation, Unit } from '../AST/types'\nimport {\n\tconvertToString,\n\tgetDifferenceInDays,\n\tgetDifferenceInMonths,\n\tgetDifferenceInTrimestreCivils,\n\tgetDifferenceInYears,\n\tgetDifferenceInYearsCivil,\n} from '../date'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\n\nexport type DuréeNode = {\n\texplanation: {\n\t\tdepuis: ASTNode\n\t\t\"jusqu'à\": ASTNode\n\t}\n\tunit: Unit\n\tnodeKind: 'durée'\n}\nconst evaluate: EvaluationFunction<'durée'> = function (node) {\n\tconst fromNode = this.evaluateNode(node.explanation.depuis)\n\tconst toNode = this.evaluateNode(node.explanation[\"jusqu'à\"])\n\n\tconst from = fromNode.nodeValue as Evaluation<string>\n\tconst to = toNode.nodeValue as Evaluation<string>\n\n\tlet nodeValue: Evaluation<number>\n\tif (from === null || to === null) {\n\t\tnodeValue = null\n\t} else if (from === undefined || to === undefined) {\n\t\tnodeValue = undefined\n\t} else {\n\t\tswitch (node.unit.numerators[0] as PossibleUnit) {\n\t\t\tcase 'jour':\n\t\t\t\tnodeValue = getDifferenceInDays(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'mois':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'an':\n\t\t\t\tnodeValue = getDifferenceInYears(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'trimestre':\n\t\t\t\tnodeValue = getDifferenceInMonths(from, to) / 3\n\t\t\t\tbreak\n\t\t\tcase 'trimestre civil':\n\t\t\t\tnodeValue = getDifferenceInTrimestreCivils(from, to)\n\t\t\t\tbreak\n\t\t\tcase 'année civile':\n\t\t\t\tnodeValue = getDifferenceInYearsCivil(from, to)\n\t\t\t\tbreak\n\t\t}\n\t}\n\n\tif (typeof nodeValue === 'number') {\n\t\tnodeValue = Math.max(0, nodeValue)\n\t}\n\n\treturn {\n\t\t...node,\n\t\tmissingVariables: mergeAllMissing([fromNode, toNode]),\n\t\tnodeValue,\n\t\texplanation: {\n\t\t\tdepuis: fromNode,\n\t\t\t\"jusqu'à\": toNode,\n\t\t},\n\t}\n}\n\nconst today = defaultNode(convertToString(new Date()))\nexport default (v, context) => {\n\tconst explanation = {\n\t\tdepuis: parse(v.depuis ?? today, context),\n\t\t\"jusqu'à\": parse(v[\"jusqu'à\"] ?? today, context),\n\t}\n\tconst unit = v.unité ? parseUnit(v.unité) : parseUnit('jour')\n\tif (\n\t\tunit.denominators.length > 0 ||\n\t\tunit.numerators.length > 1 ||\n\t\t!possibleUnit.includes(unit.numerators[0] as PossibleUnit)\n\t) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Seules les unités suivantes sont acceptées pour une durée : ${possibleUnit.join(\n\t\t\t\t', ',\n\t\t\t)}.\n\tL'unité fournie est: ${unit.numerators[0]}`,\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: 'durée',\n\t} as DuréeNode\n}\n\nregisterEvaluationFunction('durée', evaluate)\n\ntype PossibleUnit = (typeof possibleUnit)[number]\nconst possibleUnit = [\n\t'mois',\n\t'jour',\n\t'an',\n\t'trimestre',\n\t'trimestre civil',\n\t'année civile',\n] as const\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport type EstNonDéfiniNode = {\n\texplanation: ASTNode\n\tnodeKind: 'est non défini'\n}\n\nexport function parseEstNonDéfini(v, context) {\n\tconst explanation = parse(v, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'est non défini',\n\t} as EstNonDéfiniNode\n}\nparseEstNonDéfini.nom = 'est non défini'\n\nconst parseEstDéfini = createParseInlinedMecanism(\n\t'est défini',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non défini': 'valeur' }, 'non'],\n\t},\n)\n\nconst parseEstApplicable = createParseInlinedMecanism(\n\t'est applicable',\n\t{\n\t\tvaleur: {},\n\t},\n\t{\n\t\t'=': [{ 'est non applicable': 'valeur' }, 'non'],\n\t},\n)\n\nexport { parseEstDéfini, parseEstApplicable }\n\nconst evaluate: EvaluationFunction<'est non défini'> = function (node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tlet nodeValue: boolean | undefined | null = false\n\tif (valeur.nodeValue === undefined) {\n\t\tnodeValue = true\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: valeur.missingVariables,\n\t\texplanation: valeur,\n\t}\n}\nregisterEvaluationFunction('est non défini', evaluate)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type GrilleNode = {\n\texplanation: {\n\t\tassiette: ASTNode\n\t\tmultiplicateur: ASTNode\n\t\ttranches: TrancheNodes\n\t}\n\tnodeKind: 'grille'\n}\n\nexport default function parseGrille(v, context): GrilleNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t}\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'grille',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'grille'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError(\n\t\t\t'EvaluationError',\n\t\t\t`Le multiplicateur ne peut pas être nul`,\n\t\t\t{\n\t\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t\t},\n\t\t)\n\t}\n\n\tconst tranches = evaluatePlafondUntilActiveTranche\n\t\t.call(this, {\n\t\t\tparsedTranches: node.explanation.tranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t})\n\t\t.map((tranche) => {\n\t\t\tif (tranche.isActive === false) {\n\t\t\t\treturn tranche\n\t\t\t}\n\t\t\tconst montant = evaluate(tranche.montant)\n\t\t\treturn {\n\t\t\t\t...tranche,\n\t\t\t\tmontant,\n\t\t\t\tnodeValue: montant.nodeValue,\n\t\t\t\tunit: montant.unit,\n\t\t\t\tmissingVariables: mergeAllMissing([montant, tranche]),\n\t\t\t}\n\t\t})\n\n\tlet activeTranches\n\tconst activeTranche = tranches.find((tranche) => tranche.isActive)\n\tif (activeTranche) {\n\t\tactiveTranches = [activeTranche]\n\t} else if (tranches[tranches.length - 1].isAfterActive === false) {\n\t\tactiveTranches = [{ nodeValue: false }]\n\t} else {\n\t\tactiveTranches = tranches.filter(\n\t\t\t(tranche) => tranche.isActive === undefined,\n\t\t)\n\t}\n\n\tconst nodeValue =\n\t\t!activeTranches[0] ? false\n\t\t: activeTranches[0].isActive === undefined ? undefined\n\t\t: activeTranches[0].nodeValue\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tmissingVariables: mergeAllMissing([\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\t...activeTranches,\n\t\t]),\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t\ttranches,\n\t\t},\n\t\tunit: activeTranches[0]?.unit ?? undefined,\n\t} as any\n}\n\nregisterEvaluationFunction('grille', evaluate)\n","// We use a JavaScript implementation of the Brent method to find the root (the\n// \"zero\") of a monotone function. There are other methods like the\n// Newton-Raphson method, but they take the derivative of the function as an\n// input, wich in our case is costly to calculate. The Brent method doesn't\n// need to calculate the derivative.\n// An interesting description of the algorithm can be found here:\n// https://blogs.mathworks.com/cleve/2015/10/26/zeroin-part-2-brents-version/\n\n/* eslint-disable @typescript-eslint/no-unused-expressions */\n\n/**\n * Copied from https://gist.github.com/borgar/3317728\n *\n * Searches the interval from <tt>lowerLimit</tt> to <tt>upperLimit</tt>\n * for a root (i.e., zero) of the function <tt>func</tt> with respect to\n * its first argument using Brent's method root-finding algorithm.\n *\n * Translated from zeroin.c in http://www.netlib.org/c/brent.shar.\n *\n * Copyright (c) 2012 Borgar Thorsteinsson <borgar@borgar.net>\n * MIT License, http://www.opensource.org/licenses/mit-license.php\n *\n * @param func function for which the root is sought.\n * @param lowerLimit the lower point of the interval to be searched.\n * @param upperLimit the upper point of the interval to be searched.\n * @param errorTol the desired accuracy (convergence tolerance).\n * @param maxIter the maximum number of iterations.\n * @param acceptableErrorTol return a result even if errorTol isn't reached after maxIter.\n * @returns an estimate for the root within accuracy.\n *\n */\nexport default function uniroot(\n\tfunc: (x: number) => number,\n\tlowerLimit: number,\n\tupperLimit: number,\n\terrorTol = 0,\n\tmaxIter = 100,\n\tacceptableErrorTol = 0,\n) {\n\tlet a = lowerLimit,\n\t\tb = upperLimit,\n\t\tc = a,\n\t\tfa = func(a),\n\t\tfb = func(b),\n\t\tfc = fa,\n\t\tactualTolerance: number,\n\t\tnewStep: number, // Step at this iteration\n\t\tprevStep: number, // Distance from the last but one to the last approximation\n\t\tp: number, // Interpolation step is calculated in the form p/q; division is delayed until the last moment\n\t\tq: number,\n\t\tfallback: number | undefined = undefined\n\n\twhile (maxIter-- > 0) {\n\t\tprevStep = b - a\n\n\t\tif (Math.abs(fc) < Math.abs(fb)) {\n\t\t\t// Swap data for b to be the best approximation\n\t\t\t;(a = b), (b = c), (c = a)\n\t\t\t;(fa = fb), (fb = fc), (fc = fa)\n\t\t}\n\n\t\tactualTolerance = 1e-15 * Math.abs(b) + errorTol / 2\n\t\tnewStep = (c - b) / 2\n\n\t\tif (Math.abs(newStep) <= actualTolerance || fb === 0) {\n\t\t\treturn b // Acceptable approx. is found\n\t\t}\n\n\t\t// Decide if the interpolation can be tried\n\t\tif (Math.abs(prevStep) >= actualTolerance && Math.abs(fa) > Math.abs(fb)) {\n\t\t\t// If prevStep was large enough and was in true direction, Interpolatiom may be tried\n\t\t\tlet t1: number, t2: number\n\t\t\tconst cb = c - b\n\t\t\tif (a === c) {\n\t\t\t\t// If we have only two distinct points linear interpolation can only be applied\n\t\t\t\tt1 = fb / fa\n\t\t\t\tp = cb * t1\n\t\t\t\tq = 1.0 - t1\n\t\t\t} else {\n\t\t\t\t// Quadric inverse interpolation\n\t\t\t\t;(q = fa / fc), (t1 = fb / fc), (t2 = fb / fa)\n\t\t\t\tp = t2 * (cb * q * (q - t1) - (b - a) * (t1 - 1))\n\t\t\t\tq = (q - 1) * (t1 - 1) * (t2 - 1)\n\t\t\t}\n\n\t\t\tif (p > 0) {\n\t\t\t\tq = -q // p was calculated with the opposite sign; make p positive\n\t\t\t} else {\n\t\t\t\tp = -p // and assign possible minus to q\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tp < 0.75 * cb * q - Math.abs(actualTolerance * q) / 2 &&\n\t\t\t\tp < Math.abs((prevStep * q) / 2)\n\t\t\t) {\n\t\t\t\t// If (b + p / q) falls in [b,c] and isn't too large it is accepted\n\t\t\t\tnewStep = p / q\n\t\t\t}\n\n\t\t\t// If p/q is too large then the bissection procedure can reduce [b,c] range to more extent\n\t\t}\n\n\t\tif (Math.abs(newStep) < actualTolerance) {\n\t\t\t// Adjust the step to be not less than tolerance\n\t\t\tnewStep = newStep > 0 ? actualTolerance : -actualTolerance\n\t\t}\n\n\t\t;(a = b), (fa = fb) // Save the previous approx.\n\t\t;(b += newStep), (fb = func(b)) // Do step to a new approxim.\n\n\t\tif ((fb > 0 && fc > 0) || (fb < 0 && fc < 0)) {\n\t\t\t;(c = a), (fc = fa) // Adjust c for it to have a sign opposite to that of b\n\t\t}\n\t\tif (Math.abs(fb) < errorTol) {\n\t\t\treturn b\n\t\t}\n\t\tif (Math.abs(fb) < acceptableErrorTol) {\n\t\t\tfallback = b\n\t\t}\n\t}\n\treturn fallback\n}\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport { ReferenceNode } from '../parseReference'\nimport uniroot from '../uniroot'\n\nexport type InversionNode = {\n\texplanation: {\n\t\truleToInverse: string\n\t\tinversionCandidates: Array<ReferenceNode>\n\t\tmin: number\n\t\tmax: number\n\t\terrorTolerance: number\n\t\tunit?: Unit\n\n\t\t// Explanation computed during evaluation\n\t\tinversionGoal?: ASTNode\n\t\tnumberOfIteration?: number\n\t\tinversionFail?: boolean\n\t}\n\tnodeKind: 'inversion'\n}\n\n// The user of the inversion mechanism has to define a list of \"inversion\n// candidates\". At runtime, the evaluation function of the mechanism will look\n// at the situation value of these candidates, and use the first one that is\n// defined as its \"goal\" for the inversion\n//\n// The game is then to find an input such as the computed value of the \"goal\" is\n// equal to its situation value, mathematically we search for the zero of the\n// function x → f(x) - goal. The iteration logic between each test is\n// implemented in the `uniroot` file.\nexport const evaluateInversion: EvaluationFunction<'inversion'> = function (\n\tnode,\n) {\n\tconst inversionEngine = this.shallowCopy()\n\tinversionEngine.context.warn.experimentalRules = false\n\n\tif (\n\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t.slice(1)\n\t\t\t.includes(node.explanation.ruleToInverse)\n\t) {\n\t\treturn {\n\t\t\t...undefinedNumberNode,\n\t\t\t...node,\n\t\t}\n\t}\n\tinversionEngine.cache._meta.parentRuleStack = [\n\t\t...this.cache._meta.parentRuleStack,\n\t]\n\tinversionEngine.cache._meta.evaluationRuleStack = [\n\t\t...this.cache._meta.evaluationRuleStack,\n\t]\n\tconst inversionGoal = node.explanation.inversionCandidates.find(\n\t\t(candidate) => {\n\t\t\tif (\n\t\t\t\tthis.cache._meta.evaluationRuleStack.includes(candidate.dottedName!)\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tconst evaluation = inversionEngine.evaluateNode(\n\t\t\t\tinversionEngine.context.parsedRules[\n\t\t\t\t\t`${candidate.dottedName} . $SITUATION`\n\t\t\t\t],\n\t\t\t)\n\t\t\treturn (\n\t\t\t\ttypeof evaluation.nodeValue === 'number' &&\n\t\t\t\t!(candidate.dottedName! in evaluation.missingVariables)\n\t\t\t)\n\t\t},\n\t)\n\tif (inversionGoal === undefined) {\n\t\treturn {\n\t\t\t...node,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: {\n\t\t\t\t...Object.fromEntries(\n\t\t\t\t\tnode.explanation.inversionCandidates.map((candidate) => [\n\t\t\t\t\t\tcandidate.dottedName,\n\t\t\t\t\t\t1,\n\t\t\t\t\t]),\n\t\t\t\t),\n\t\t\t\t[node.explanation.ruleToInverse]: 1,\n\t\t\t},\n\t\t}\n\t}\n\n\tconst evaluatedInversionGoal = inversionEngine.evaluateNode(inversionGoal)\n\tlet numberOfIteration = 0\n\n\tinversionEngine.setSituation(\n\t\t{\n\t\t\t[inversionGoal.dottedName!]: undefinedNumberNode,\n\t\t},\n\t\t{ keepPreviousSituation: true },\n\t)\n\n\tinversionEngine.cache.traversedVariablesStack =\n\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\tlet lastEvaluation: EvaluatedNode\n\tconst evaluateWithValue = (n: number) => {\n\t\tnumberOfIteration++\n\t\tinversionEngine.setSituation(\n\t\t\t{\n\t\t\t\t[node.explanation.ruleToInverse]: {\n\t\t\t\t\tnodeValue: n,\n\t\t\t\t\tnodeKind: 'constant',\n\t\t\t\t\ttype: 'number',\n\t\t\t\t\tunit: evaluatedInversionGoal.unit,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ keepPreviousSituation: true },\n\t\t)\n\t\tinversionEngine.cache.traversedVariablesStack =\n\t\t\tthis.cache.traversedVariablesStack ? [] : undefined\n\n\t\tlastEvaluation = inversionEngine.evaluateNode(inversionGoal)\n\n\t\treturn lastEvaluation\n\t}\n\n\tconst goal = evaluatedInversionGoal.nodeValue as number\n\tlet nodeValue: number | undefined = undefined\n\n\t// We do some blind attempts here to avoid using the default minimum and\n\t// maximum of +/- 10^8 that are required by the `uniroot` function. For the\n\t// first attempt we use the goal value as a very rough first approximation.\n\t// For the second attempt we do a proportionality coefficient with the result\n\t// from the first try and the goal value. The two attempts are then used in\n\t// the following way:\n\t// - if both results are `undefined` we assume that the inversion is impossible\n\t//   because of missing variables\n\t// - otherwise, we calculate the missing variables of the node as the union of\n\t//   the missings variables of our two attempts\n\t// - we cache the result of our two attempts so that `uniroot` doesn't\n\t//   recompute them\n\tconst x1 = goal\n\tconst y1Node = evaluateWithValue(x1)\n\tconst y1 = y1Node.nodeValue as number\n\tconst coeff = y1 > goal ? 0.9 : 1.2\n\tconst x2 = y1 !== undefined ? (x1 * goal * coeff) / y1 : 2000\n\tconst y2Node = evaluateWithValue(x2)\n\tconst y2 = y2Node.nodeValue as number\n\n\tconst maxIterations = this.context.inversionMaxIterations ?? 10\n\n\tif (y1 !== undefined || y2 !== undefined) {\n\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t// with the already computed x1 or x2.\n\t\tconst test = (x: number): number => {\n\t\t\tconst y =\n\t\t\t\tx === x1 ? y1\n\t\t\t\t: x === x2 ? y2\n\t\t\t\t: evaluateWithValue(x).nodeValue\n\t\t\treturn (y as number) - goal\n\t\t}\n\n\t\tconst nearestBelowGoal =\n\t\t\ty2 !== undefined && y2 < goal && (y2 > y1 || y1 > goal) ? x2\n\t\t\t: y1 !== undefined && y1 < goal && (y1 > y2 || y2 > goal) ? x1\n\t\t\t: node.explanation.min\n\t\tconst nearestAboveGoal =\n\t\t\ty2 !== undefined && y2 > goal && (y2 < y1 || y1 < goal) ? x2\n\t\t\t: y1 !== undefined && y1 > goal && (y1 < y2 || y2 < goal) ? x1\n\t\t\t: node.explanation.max\n\t\tconst errorTolerance = node.explanation.errorTolerance\n\n\t\tnodeValue = uniroot(\n\t\t\ttest,\n\t\t\tnearestBelowGoal,\n\t\t\tnearestAboveGoal,\n\t\t\terrorTolerance,\n\t\t\tmaxIterations,\n\t\t\t1,\n\t\t)\n\n\t\t// nodeValue found is out of min/max bound\n\t\tif (\n\t\t\tnodeValue &&\n\t\t\t(nodeValue < node.explanation.min || nodeValue > node.explanation.max)\n\t\t) {\n\t\t\tnodeValue = undefined\n\t\t}\n\t}\n\n\tif (nodeValue == undefined) {\n\t\tthis.cache.inversionFail = true\n\t}\n\n\t// Uncomment to display the two attempts and their result\n\t// console.table([\n\t// \t{ x: x1, y: y1 },\n\t// \t{ x: x2, y: y2 },\n\t// ])\n\t// console.log('iteration inversion:', numberOfIteration)\n\tif (this.cache.traversedVariablesStack) {\n\t\tconst traversedVariablesStack = this.cache.traversedVariablesStack[0]\n\t\tif (traversedVariablesStack) {\n\t\t\t;(lastEvaluation!.traversedVariables ?? []).forEach((v) =>\n\t\t\t\ttraversedVariablesStack.add(v),\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\tunit: evaluatedInversionGoal.unit,\n\t\texplanation: {\n\t\t\t...node.explanation,\n\t\t\tinversionGoal,\n\t\t\tnumberOfIteration,\n\t\t\tinversionFail: this.cache.inversionFail,\n\t\t},\n\t\tmissingVariables: lastEvaluation!.missingVariables,\n\t}\n}\n\nexport const mecanismInversion = (v, context: Context) => {\n\tlet avec = typeof v === 'object' && 'avec' in v ? v.avec : v\n\tconst min = typeof v === 'object' && 'min' in v ? v.min : -1000000\n\tconst max = typeof v === 'object' && 'max' in v ? v.max : 100000000\n\tconst errorTolerance =\n\t\ttypeof v === 'object' && \"tolérance d'erreur\" in v ?\n\t\t\tv[\"tolérance d'erreur\"]\n\t\t:\t0.1\n\tif (v === null) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t\"Il manque les règles avec laquelle effectuer le calcul d'inversion dans le mécanisme `inversion numérique`\",\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (!Array.isArray(avec)) {\n\t\tavec = [avec]\n\t}\n\treturn {\n\t\texplanation: {\n\t\t\truleToInverse: context.dottedName,\n\t\t\tinversionCandidates: avec.map((node) => ({\n\t\t\t\t...parse(node, context),\n\t\t\t})),\n\t\t\tmin,\n\t\t\tmax,\n\t\t\terrorTolerance,\n\t\t},\n\t\tnodeKind: 'inversion',\n\t} as InversionNode\n}\n\nregisterEvaluationFunction('inversion', evaluateInversion)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport const parseMaximumDe = createParseInlinedMecanismWithArray(\n\t'le maximum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array<PublicodesExpression>).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '>': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n\nexport const parseMinimumDe = createParseInlinedMecanismWithArray(\n\t'le minimum de',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array<PublicodesExpression>).reduce(\n\t\t\t(acc, value) => ({\n\t\t\t\tcondition: {\n\t\t\t\t\tsi: {\n\t\t\t\t\t\t'est non applicable': '$INTERNAL valeur',\n\t\t\t\t\t},\n\t\t\t\t\talors: '$INTERNAL acc',\n\t\t\t\t\tsinon: {\n\t\t\t\t\t\tcondition: {\n\t\t\t\t\t\t\tsi: {\n\t\t\t\t\t\t\t\tou: [\n\t\t\t\t\t\t\t\t\t{ 'est non applicable': '$INTERNAL acc' },\n\t\t\t\t\t\t\t\t\t{ '<': ['$INTERNAL valeur', '$INTERNAL acc'] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\talors: '$INTERNAL valeur',\n\t\t\t\t\t\t\tsinon: '$INTERNAL acc',\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tavec: {\n\t\t\t\t\t'[privé] $INTERNAL valeur': { valeur: value },\n\t\t\t\t\t'[privé] $INTERNAL acc': { valeur: acc },\n\t\t\t\t},\n\t\t\t}),\n\t\t\tnotApplicableNode,\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToSumNodes(\n\tvaleurs: Array<PublicodesExpression>,\n): PublicodesExpression {\n\treturn valeurs\n\t\t.reverse()\n\t\t.reduce((acc, value) => ({ '+': [value, acc] }), notApplicableNode)\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'somme',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\treduceToSumNodes([...(valeur as Array<PublicodesExpression>)]),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\nimport { reduceToSumNodes } from './somme'\n\nexport default createParseInlinedMecanismWithArray(\n\t'moyenne',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => {\n\t\tconst valeurs = [...(valeur as Array<PublicodesExpression>)]\n\n\t\treturn {\n\t\t\t'/': [\n\t\t\t\treduceToSumNodes(valeurs),\n\t\t\t\treduceToSumNodes(valeurs.map(oneIfApplicable)),\n\t\t\t],\n\t\t}\n\t},\n)\n\nfunction oneIfApplicable(exp: PublicodesExpression): PublicodesExpression {\n\treturn {\n\t\t'applicable si': { 'est applicable': exp },\n\t\tvaleur: 1,\n\t}\n}\n","import { notApplicableNode } from '../evaluationUtils'\nimport { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'non applicable si',\n\t{\n\t\t'non applicable si': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: 'non applicable si = non',\n\t\t\talors: 'valeur',\n\t\t\tsinon: notApplicableNode,\n\t\t},\n\t},\n)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode, EvaluatedNode } from '../AST/types'\nimport { convertToDate } from '../date'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { inferUnit, serializeUnit } from '../units'\n\nconst knownOperations = {\n\t'*': [(a, b) => a * b, '×'],\n\t'/': [(a, b) => a / b, '∕'],\n\t'//': [(a, b) => (a - (a % b)) / b, '//'],\n\t'**': [(a, b) => a ** b, '**'],\n\t'+': [(a, b) => a + b],\n\t'-': [(a, b) => a - b, '−'],\n\t'<': [(a, b) => a < b],\n\t'<=': [(a, b) => a <= b, '≤'],\n\t'>': [(a, b) => a > b],\n\t'>=': [(a, b) => a >= b, '≥'],\n\t'=': [(a, b) => (a ?? false) === (b ?? false)],\n\t'!=': [(a, b) => (a ?? false) !== (b ?? false), '≠'],\n\tet: [(a, b) => (a ?? false) && (b ?? false)],\n\tou: [(a, b) => (a ?? false) || (b ?? false)],\n} as const\n\nexport type OperationNode = {\n\tnodeKind: 'operation'\n\texplanation: [ASTNode, ASTNode]\n\toperationKind: keyof typeof knownOperations\n\toperator: string\n}\n\nconst parseOperation = (k, symbol) => (v, context) => {\n\tconst explanation = v.map((node) => parse(node, context))\n\n\treturn {\n\t\t...v,\n\t\tnodeKind: 'operation',\n\t\toperationKind: k,\n\t\toperator: symbol || k,\n\t\texplanation,\n\t} as OperationNode\n}\n\nconst evaluate: EvaluationFunction<'operation'> = function (node) {\n\tlet node1 = this.evaluateNode(node.explanation[0])\n\n\tlet evaluatedNode: EvaluatedNode & OperationNode = {\n\t\t...node,\n\t\tmissingVariables: {},\n\t} as EvaluatedNode & OperationNode\n\n\t// LAZY EVALUATION\n\tif (\n\t\t(node1.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', '//', '-', 'et'].includes(\n\t\t\t\tnode.operationKind,\n\t\t\t)) ||\n\t\t(node1.nodeValue === 0 && ['/', '*'].includes(node.operationKind)) ||\n\t\t(node1.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node1.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node1.nodeValue,\n\t\t\tmissingVariables: node1.missingVariables,\n\t\t}\n\t}\n\n\tlet node2 = this.evaluateNode(node.explanation[1])\n\tevaluatedNode.explanation = [node1, node2]\n\n\tif (node.operationKind === '/' && node2.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: this.cache._meta.evaluationRuleStack[0],\n\t\t})\n\t}\n\n\t// LAZY EVALUATION 2\n\tif (\n\t\t(node2.nodeValue === null &&\n\t\t\t['<', '>', '<=', '>=', '/', '*', '//', 'et'].includes(\n\t\t\t\tnode.operationKind,\n\t\t\t)) ||\n\t\t(node2.nodeValue === 0 && ['*'].includes(node.operationKind)) ||\n\t\t(node2.nodeValue === false && node.operationKind === 'et') ||\n\t\t(node2.nodeValue === true && node.operationKind === 'ou')\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: node.operationKind === 'et' ? false : node2.nodeValue,\n\t\t\tmissingVariables: node2.missingVariables,\n\t\t}\n\t}\n\n\tevaluatedNode.missingVariables = mergeAllMissing([node1, node2])\n\n\tif (node1.nodeValue === undefined || node2.nodeValue === undefined) {\n\t\tevaluatedNode = {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t}\n\t}\n\n\tconst isAdditionOrSubstractionWithPercentage =\n\t\t['+', '-'].includes(node.operationKind) &&\n\t\tserializeUnit(node2.unit) === '%' &&\n\t\tserializeUnit(node1.unit) !== '%'\n\n\tif (\n\t\t!('nodeValue' in evaluatedNode) &&\n\t\t!['/', '*', '//'].includes(node.operationKind) &&\n\t\t!isAdditionOrSubstractionWithPercentage\n\t) {\n\t\ttry {\n\t\t\tif (node1.unit && 'unit' in node2) {\n\t\t\t\tnode2 = convertNodeToUnit(node1.unit, node2)\n\t\t\t} else if (node2.unit) {\n\t\t\t\tnode1 = convertNodeToUnit(node2.unit, node1)\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tif (!(e instanceof Error)) {\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\twarning(\n\t\t\t\tthis.context,\n\t\t\t\t`Dans l'expression '${\n\t\t\t\t\tnode.operationKind\n\t\t\t\t}', la partie gauche (unité: ${serializeUnit(\n\t\t\t\t\tnode1.unit,\n\t\t\t\t)}) n'est pas compatible avec la partie droite (unité: ${serializeUnit(\n\t\t\t\t\tnode2.unit,\n\t\t\t\t)})`,\n\t\t\t\t'unitConversion',\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\tconst operatorFunction = knownOperations[node.operationKind][0]\n\n\tconst a = node1.nodeValue as string | boolean | null\n\tconst b = node2.nodeValue as string | boolean | null\n\n\tevaluatedNode.nodeValue =\n\t\t'nodeValue' in evaluatedNode ? evaluatedNode.nodeValue\n\t\t: (\n\t\t\t['<', '>', '<=', '>=', '*', '/', '//'].includes(node.operationKind) &&\n\t\t\tnode2.nodeValue === null\n\t\t) ?\n\t\t\tnull\n\t\t: (\n\t\t\t[a, b].every(\n\t\t\t\t(value) =>\n\t\t\t\t\ttypeof value === 'string' &&\n\t\t\t\t\tvalue.match?.(/^[\\d]{2}\\/[\\d]{2}\\/[\\d]{4}$/),\n\t\t\t)\n\t\t) ?\n\t\t\t// We convert the date objects to timestamps to support comparison with the \"===\" operator:\n\t\t\t// new Date('2020-01-01') !== new Date('2020-01-01')\n\t\t\toperatorFunction(\n\t\t\t\tconvertToDate(a as string).getTime(),\n\t\t\t\tconvertToDate(b as string).getTime(),\n\t\t\t)\n\t\t:\toperatorFunction(a, b)\n\n\tif (\n\t\tnode.operationKind === '*' &&\n\t\tinferUnit('*', [node1.unit, node2.unit])?.numerators.includes('%')\n\t) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\tconst nodeValue = evaluatedNode.nodeValue\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: typeof nodeValue === 'number' ? nodeValue / 100 : nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\t// Addition or substraction of scalar with a percentage is a multiplication\n\t// TODO : this logic should be handle statically by changing sum with percentage into product.\n\t// It can be done when we'll have a sound type/unit inference\n\tif (isAdditionOrSubstractionWithPercentage) {\n\t\tconst unit = inferUnit('*', [node1.unit, node2.unit])\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue:\n\t\t\t\t(\n\t\t\t\t\ttypeof node1.nodeValue === 'number' &&\n\t\t\t\t\ttypeof node2.nodeValue === 'number'\n\t\t\t\t) ?\n\t\t\t\t\tnode1.nodeValue *\n\t\t\t\t\t(1 + (node2.nodeValue / 100) * (node.operationKind === '-' ? -1 : 1))\n\t\t\t\t:\tevaluatedNode.nodeValue,\n\t\t\tunit: inferUnit('*', [unit, { numerators: [], denominators: ['%'] }]),\n\t\t}\n\t}\n\n\tif (\n\t\tnode.operationKind === '*' ||\n\t\tnode.operationKind === '/' ||\n\t\tnode.operationKind === '//' ||\n\t\tnode.operationKind === '-' ||\n\t\tnode.operationKind === '+'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tunit: inferUnit(node.operationKind, [node1.unit, node2.unit]),\n\t\t}\n\t}\n\n\treturn evaluatedNode\n}\n\nregisterEvaluationFunction('operation', evaluate)\n\nconst operationDispatch = Object.fromEntries(\n\tObject.entries(knownOperations).map(([k, [, symbol]]) => [\n\t\tk,\n\t\tparseOperation(k, symbol),\n\t]),\n)\n\nexport default operationDispatch\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'par défaut',\n\t{\n\t\t'par défaut': {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'valeur' },\n\t\t\talors: 'par défaut',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plafond',\n\t{\n\t\tplafond: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plafond != non', 'valeur > plafond'] },\n\t\t\talors: 'plafond',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'plancher',\n\t{\n\t\tplancher: {},\n\t\tvaleur: {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { et: ['plancher != non', 'valeur < plancher'] },\n\t\t\talors: 'plancher',\n\t\t\tsinon: 'valeur',\n\t\t},\n\t},\n)\n","import { PublicodesExpression } from '..'\nimport { defaultNode } from '../evaluationUtils'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport function reduceToProduitNodes(\n\tvaleurs: Array<PublicodesExpression>,\n): PublicodesExpression {\n\treturn valeurs.reduce((acc, value) => ({ '*': [value, acc] }), defaultNode(1))\n}\n\nexport default createParseInlinedMecanismWithArray(\n\t'produit',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) => ({\n\t\tvaleur: reduceToProduitNodes([...(valeur as Array<PublicodesExpression>)]),\n\t\t\"simplifier l'unité\": 'oui',\n\t}),\n)\n","import { EvaluationFunction } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { undefinedNumberNode } from '../evaluationUtils'\nimport parse from '../parse'\nimport { Context } from '../parsePublicodes'\nimport uniroot from '../uniroot'\n\nexport type RésoudreRéférenceCirculaireNode = {\n\texplanation: {\n\t\truleToSolve: string\n\t\tvaleur: ASTNode\n\t}\n\tnodeKind: 'résoudre référence circulaire'\n}\n\nexport const evaluateRésoudreRéférenceCirculaire: EvaluationFunction<'résoudre référence circulaire'> =\n\tfunction (node) {\n\t\tif (\n\t\t\tthis.cache._meta.evaluationRuleStack\n\t\t\t\t.slice(1)\n\t\t\t\t.includes(node.explanation.ruleToSolve)\n\t\t) {\n\t\t\treturn {\n\t\t\t\t...undefinedNumberNode,\n\t\t\t\t...node,\n\t\t\t}\n\t\t}\n\n\t\tlet numberOfIterations = 0\n\t\tconst calculationEngine = this.shallowCopy()\n\t\tcalculationEngine.context.warn.experimentalRules = false\n\t\tcalculationEngine.cache._meta.parentRuleStack = [\n\t\t\t...this.cache._meta.parentRuleStack,\n\t\t]\n\t\tcalculationEngine.cache._meta.evaluationRuleStack = [\n\t\t\t...this.cache._meta.evaluationRuleStack,\n\t\t]\n\t\tconst maxIterations = this.context.inversionMaxIterations ?? 25\n\n\t\tconst evaluateWithValue = (n: number) => {\n\t\t\tnumberOfIterations++\n\t\t\tcalculationEngine.setSituation(\n\t\t\t\t{\n\t\t\t\t\t[node.explanation.ruleToSolve]: {\n\t\t\t\t\t\t...undefinedNumberNode,\n\t\t\t\t\t\tnodeValue: n,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{ keepPreviousSituation: true },\n\t\t\t)\n\n\t\t\treturn calculationEngine.evaluateNode(node.explanation.valeur)\n\t\t}\n\n\t\tconst inversionFailed = Symbol('inversion failed')\n\n\t\tlet nodeValue: number | undefined | typeof inversionFailed = inversionFailed\n\n\t\tconst x0 = 1\n\t\tlet valeur = evaluateWithValue(x0)\n\t\tconst y0 = valeur.nodeValue as number\n\t\tconst unit = valeur.unit\n\t\tif (y0 !== undefined) {\n\t\t\t// The `uniroot` function parameter. It will be called with its `min` and\n\t\t\t// `max` arguments, so we can use our cached nodes if the function is called\n\t\t\t// with the already computed x1 or x2.\n\t\t\tconst test = (x: number): number => {\n\t\t\t\tif (x === x0) {\n\t\t\t\t\treturn y0 - x0\n\t\t\t\t}\n\t\t\t\tvaleur = evaluateWithValue(x)\n\t\t\t\tconst y = valeur.nodeValue\n\t\t\t\treturn (y as number) - x\n\t\t\t}\n\n\t\t\tconst defaultMin = -1_000_000\n\t\t\tconst defaultMax = 100_000_000\n\n\t\t\tnodeValue = uniroot(test, defaultMin, defaultMax, 0.5, maxIterations, 2)\n\t\t}\n\n\t\tif (nodeValue === inversionFailed) {\n\t\t\tnodeValue = undefined\n\t\t\tthis.cache.inversionFail = true\n\t\t}\n\t\tif (nodeValue !== undefined) {\n\t\t\tvaleur = evaluateWithValue(nodeValue)\n\t\t}\n\t\treturn {\n\t\t\t...node,\n\t\t\tunit,\n\t\t\tnodeValue,\n\t\t\texplanation: {\n\t\t\t\t...node.explanation,\n\t\t\t\tvaleur,\n\t\t\t\tnumberOfIterations,\n\t\t\t},\n\t\t\tmissingVariables: valeur.missingVariables,\n\t\t}\n\t}\n\nexport default function parseRésoudreRéférenceCirculaire(v, context: Context) {\n\treturn {\n\t\texplanation: {\n\t\t\truleToSolve: context.dottedName,\n\t\t\tvaleur: parse(v.valeur, context),\n\t\t},\n\t\tnodeKind: 'résoudre référence circulaire',\n\t} as RésoudreRéférenceCirculaireNode\n}\n\nparseRésoudreRéférenceCirculaire.nom = 'résoudre la référence circulaire'\n\nregisterEvaluationFunction(\n\t'résoudre référence circulaire',\n\tevaluateRésoudreRéférenceCirculaire,\n)\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, simplifyUnit } from '../units'\n\nexport type SimplifierUnitéNode = {\n\texplanation: ASTNode\n\tnodeKind: 'simplifier unité'\n}\n\nexport default function parseSimplifierUnité(v, context): SimplifierUnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'simplifier unité',\n\t}\n}\n\nparseSimplifierUnité.nom = \"simplifier l'unité\" as const\n\nregisterEvaluationFunction('simplifier unité', function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\tconst nodeValue = valeur.nodeValue\n\tconst defaultReturn = {\n\t\t...valeur,\n\t\t...node,\n\t\texplanation: valeur,\n\t}\n\tif (nodeValue == null) {\n\t\treturn defaultReturn\n\t}\n\n\tif (!valeur.unit) {\n\t\treturn {\n\t\t\t...defaultReturn,\n\t\t\tunit: valeur.unit,\n\t\t}\n\t}\n\tconst unit = simplifyUnit(valeur.unit)\n\n\treturn {\n\t\t...defaultReturn,\n\t\tnodeValue:\n\t\t\ttypeof nodeValue === 'number' ?\n\t\t\t\tconvertUnit(valeur.unit, unit, nodeValue)\n\t\t\t:\tnodeValue,\n\t\tunit,\n\t}\n})\n","import { createParseInlinedMecanism } from './inlineMecanism'\n\nexport default createParseInlinedMecanism(\n\t'dans la situation',\n\t{\n\t\tvaleur: {},\n\t\t'dans la situation': {},\n\t},\n\t{\n\t\tcondition: {\n\t\t\tsi: { 'est non défini': 'dans la situation' },\n\t\t\talors: 'valeur',\n\t\t\tsinon: 'dans la situation',\n\t\t},\n\t},\n)\n","import { EvaluationFunction, PublicodesError } from '..'\nimport { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { defaultNode, mergeAllMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\nimport { parseUnit } from '../units'\nimport {\n\tevaluatePlafondUntilActiveTranche,\n\tparseTranches,\n\tTrancheNodes,\n} from './trancheUtils'\n\nexport type TauxProgressifNode = {\n\texplanation: {\n\t\ttranches: TrancheNodes\n\t\tmultiplicateur: ASTNode\n\t\tassiette: ASTNode\n\t}\n\tnodeKind: 'taux progressif'\n}\nexport default function parseTauxProgressif(v, context): TauxProgressifNode {\n\tconst explanation = {\n\t\tassiette: parse(v.assiette, context),\n\t\tmultiplicateur:\n\t\t\tv.multiplicateur ? parse(v.multiplicateur, context) : defaultNode(1),\n\t\ttranches: parseTranches(v.tranches, context),\n\t} as TauxProgressifNode['explanation']\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'taux progressif',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'taux progressif'> = function (node) {\n\tconst evaluate = this.evaluateNode.bind(this)\n\tconst assiette = this.evaluateNode(node.explanation.assiette)\n\tconst multiplicateur = this.evaluateNode(node.explanation.multiplicateur)\n\tif (multiplicateur.nodeValue === 0) {\n\t\tthrow new PublicodesError('EvaluationError', `Division by zero`, {\n\t\t\tdottedName: '',\n\t\t})\n\t}\n\tconst tranches = evaluatePlafondUntilActiveTranche.call(this, {\n\t\tparsedTranches: node.explanation.tranches,\n\t\tassiette,\n\t\tmultiplicateur,\n\t})\n\n\tconst evaluatedNode = {\n\t\t...node,\n\t\texplanation: {\n\t\t\ttranches,\n\t\t\tassiette,\n\t\t\tmultiplicateur,\n\t\t},\n\t\tunit: parseUnit('%'),\n\t}\n\n\tconst lastTranche = tranches[tranches.length - 1]\n\tif (\n\t\ttranches.every(({ isActive }) => isActive === false) ||\n\t\t(lastTranche.isActive && lastTranche.plafond.nodeValue === Infinity)\n\t) {\n\t\tconst taux = convertNodeToUnit(parseUnit('%'), evaluate(lastTranche.taux))\n\t\tconst { nodeValue, missingVariables } = taux\n\t\tlastTranche.taux = taux\n\t\tlastTranche.nodeValue = nodeValue\n\t\tlastTranche.missingVariables = missingVariables\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue,\n\t\t\tmissingVariables,\n\t\t}\n\t}\n\n\tif (\n\t\ttranches.every(({ isActive }) => isActive !== true) ||\n\t\ttypeof assiette.nodeValue !== 'number'\n\t) {\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(tranches),\n\t\t}\n\t}\n\n\tconst activeTrancheIndex = tranches.findIndex(\n\t\t({ isActive }) => isActive === true,\n\t)\n\tconst activeTranche = tranches[activeTrancheIndex]\n\tactiveTranche.taux = convertNodeToUnit(\n\t\tparseUnit('%'),\n\t\tevaluate(activeTranche.taux),\n\t)\n\n\tconst previousTranche = tranches[activeTrancheIndex - 1]\n\tif (previousTranche) {\n\t\tpreviousTranche.taux = convertNodeToUnit(\n\t\t\tparseUnit('%'),\n\t\t\tevaluate(previousTranche.taux),\n\t\t)\n\t\tpreviousTranche.isActive = true\n\t}\n\tconst previousTaux =\n\t\tpreviousTranche ? previousTranche.taux : activeTranche.taux\n\tconst calculationValues = [previousTaux, activeTranche.taux]\n\tif (calculationValues.some((n) => n.nodeValue === undefined)) {\n\t\tactiveTranche.nodeValue = undefined\n\t\treturn {\n\t\t\t...evaluatedNode,\n\t\t\tnodeValue: undefined,\n\t\t\tmissingVariables: mergeAllMissing(calculationValues),\n\t\t}\n\t}\n\n\tconst lowerTaux = previousTaux.nodeValue\n\tconst upperTaux = activeTranche.taux.nodeValue\n\tconst plancher = activeTranche.plancherValue\n\tconst plafond = activeTranche.plafondValue\n\tconst coeff = (upperTaux - lowerTaux) / (plafond - plancher)\n\tconst nodeValue = lowerTaux + (assiette.nodeValue - plancher) * coeff\n\tactiveTranche.nodeValue = nodeValue\n\treturn {\n\t\t...evaluatedNode,\n\t\tnodeValue,\n\t\tmissingVariables: {},\n\t}\n}\n\nregisterEvaluationFunction('taux progressif', evaluate)\n","import { ASTNode, formatValue } from '..'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeAllMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nconst NAME = 'texte'\n\nexport type TexteNode = {\n\texplanation: Array<ASTNode | string>\n\tnodeKind: typeof NAME\n}\n\nexport default function parseTexte(texte: string, context): TexteNode {\n\tconst explanation = [] as TexteNode['explanation']\n\tlet lastIndex = 0\n\tfor (const { 0: expression, index } of texte.matchAll(/{{(.|\\n)*?}}/g)) {\n\t\tconst publicodeExpression = expression.slice(2, -2).trim()\n\t\tconst parsedNode = parse(publicodeExpression, context)\n\t\texplanation.push(texte.substring(lastIndex, index), parsedNode)\n\t\tlastIndex = (index ?? 0) + expression.length\n\t}\n\texplanation.push(texte.slice(lastIndex))\n\treturn {\n\t\tnodeKind: NAME,\n\t\texplanation,\n\t}\n}\nparseTexte.nom = NAME\n\nregisterEvaluationFunction(NAME, function evaluate(node) {\n\tconst explanation = node.explanation.map((element) =>\n\t\ttypeof element === 'string' ? element : this.evaluateNode(element),\n\t)\n\treturn {\n\t\t...node,\n\t\texplanation,\n\t\tmissingVariables: mergeAllMissing(\n\t\t\texplanation.filter((element) => typeof element !== 'string'),\n\t\t),\n\t\tnodeValue: explanation\n\t\t\t.map((element) =>\n\t\t\t\ttypeof element === 'string' ? element : formatValue(element),\n\t\t\t)\n\t\t\t.join(''),\n\t}\n})\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'toutes ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array<PublicodesExpression>).reduce(\n\t\t\t(acc, value) => ({ et: [acc, value] }),\n\t\t\t'oui',\n\t\t),\n)\n","import { PublicodesExpression } from '..'\nimport { createParseInlinedMecanismWithArray } from './inlineMecanism'\n\nexport default createParseInlinedMecanismWithArray(\n\t'une de ces conditions',\n\t{\n\t\tvaleur: { type: 'liste' },\n\t},\n\t({ valeur }) =>\n\t\t(valeur as Array<PublicodesExpression>).reduce(\n\t\t\t(acc, value) => ({ ou: [acc, value] }),\n\t\t\t'non',\n\t\t),\n)\n","import { ASTNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport parse from '../parse'\nimport { convertUnit, parseUnit } from '../units'\n\nexport type UnitéNode = {\n\tunit: Unit\n\texplanation: ASTNode\n\tnodeKind: 'unité'\n}\n\nexport default function parseUnité(v, context): UnitéNode {\n\tconst explanation = parse(v.valeur, context)\n\tconst unit = parseUnit(v.unité, context.getUnitKey)\n\n\treturn {\n\t\texplanation,\n\t\tunit,\n\t\tnodeKind: parseUnité.nom,\n\t}\n}\n\nparseUnité.nom = 'unité' as const\n\nregisterEvaluationFunction(parseUnité.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tlet nodeValue = valeur.nodeValue\n\tif (nodeValue !== null && 'unit' in node) {\n\t\ttry {\n\t\t\tnodeValue = convertUnit(\n\t\t\t\tvaleur.unit,\n\t\t\t\tnode.unit,\n\t\t\t\tvaleur.nodeValue as number,\n\t\t\t)\n\t\t} catch (e) {\n\t\t\tif (!(e instanceof Error)) {\n\t\t\t\tthrow e\n\t\t\t}\n\t\t\twarning(\n\t\t\t\tthis.context,\n\t\t\t\t\"Erreur lors de la conversion d'unité explicite\",\n\t\t\t\t'unitConversion',\n\t\t\t\te,\n\t\t\t)\n\t\t}\n\t}\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\texplanation: valeur,\n\t\tmissingVariables: valeur.missingVariables,\n\t}\n})\n","import { ASTNode } from '../AST/types'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { mergeMissing } from '../evaluationUtils'\nimport parse from '../parse'\n\nexport type VariableManquanteNode = {\n\tmissingVariable: string\n\texplanation: ASTNode\n\tnodeKind: 'variable manquante'\n}\n\nexport default function parseVariableManquante(\n\tv,\n\tcontext,\n): VariableManquanteNode {\n\treturn {\n\t\tmissingVariable: v['variable manquante'],\n\t\tnodeKind: parseVariableManquante.nom,\n\t\texplanation: parse(v.valeur, context),\n\t}\n}\n\nparseVariableManquante.nom = 'variable manquante' as const\n\nregisterEvaluationFunction(parseVariableManquante.nom, function evaluate(node) {\n\tconst valeur = this.evaluateNode(node.explanation)\n\n\tconst maxMissingScore = Object.values(\n\t\tvaleur.missingVariables ?? {},\n\t).reduce<number>((a, b) => (a > b ? a : b), 0)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue: valeur.nodeValue,\n\t\tunit: valeur.unit,\n\t\texplanation: valeur,\n\t\tmissingVariables: mergeMissing(valeur.missingVariables, {\n\t\t\t[node.missingVariable]: maxMissingScore + 1,\n\t\t}),\n\t}\n})\n","import { EvaluationFunction } from '..'\nimport { ASTNode, EvaluatedNode, Unit } from '../AST/types'\nimport { warning } from '../error'\nimport { registerEvaluationFunction } from '../evaluationFunctions'\nimport { bonus, defaultNode, mergeMissing } from '../evaluationUtils'\nimport { convertNodeToUnit } from '../nodeUnits'\nimport parse from '../parse'\n\nexport type VariationNode = {\n\texplanation: Array<{\n\t\tcondition: ASTNode\n\t\tconsequence: ASTNode\n\t\tsatisfied?: boolean\n\t}>\n\tnodeKind: 'variations'\n}\n\nexport default function parseVariations(v, context): VariationNode {\n\tconst explanation = v.map(({ si, alors, sinon }) =>\n\t\tsinon !== undefined ?\n\t\t\t{ consequence: parse(sinon, context), condition: defaultNode(true) }\n\t\t:\t{ consequence: parse(alors, context), condition: parse(si, context) },\n\t)\n\n\treturn {\n\t\texplanation,\n\t\tnodeKind: 'variations',\n\t}\n}\n\nconst evaluate: EvaluationFunction<'variations'> = function (node) {\n\tconst [nodeValue, explanation, unit] = node.explanation.reduce<\n\t\t[\n\t\t\tEvaluatedNode['nodeValue'],\n\t\t\tVariationNode['explanation'],\n\t\t\tUnit | undefined,\n\t\t\tboolean | undefined,\n\t\t]\n\t>(\n\t\t(\n\t\t\t[evaluation, explanations, unit, previousConditions],\n\t\t\t{ condition, consequence },\n\t\t\ti: number,\n\t\t) => {\n\t\t\tif (previousConditions === true) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tconst evaluatedCondition = this.evaluateNode(condition)\n\t\t\tconst currentCondition =\n\t\t\t\tpreviousConditions === undefined ? previousConditions : (\n\t\t\t\t\t!previousConditions &&\n\t\t\t\t\t(evaluatedCondition.nodeValue === undefined ?\n\t\t\t\t\t\tundefined\n\t\t\t\t\t:\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\t\t\tevaluatedCondition.nodeValue !== null)\n\t\t\t\t)\n\n\t\t\tif (currentCondition === false || currentCondition === null) {\n\t\t\t\treturn [\n\t\t\t\t\tevaluation,\n\t\t\t\t\t[...explanations, { condition: evaluatedCondition, consequence }],\n\t\t\t\t\tunit,\n\t\t\t\t\tpreviousConditions,\n\t\t\t\t]\n\t\t\t}\n\t\t\tlet evaluatedConsequence: EvaluatedNode | undefined = undefined\n\t\t\tif (\n\t\t\t\tevaluatedCondition.nodeValue !== false &&\n\t\t\t\tevaluatedCondition.nodeValue !== null\n\t\t\t) {\n\t\t\t\tevaluatedConsequence = this.evaluateNode(consequence)\n\t\t\t\tif (unit) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tevaluatedConsequence = convertNodeToUnit(\n\t\t\t\t\t\t\tunit,\n\t\t\t\t\t\t\tevaluatedConsequence!,\n\t\t\t\t\t\t)\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tif (!(e instanceof Error)) {\n\t\t\t\t\t\t\tthrow e\n\t\t\t\t\t\t}\n\t\t\t\t\t\twarning(\n\t\t\t\t\t\t\tthis.context,\n\t\t\t\t\t\t\t`L'unité de la branche n° ${\n\t\t\t\t\t\t\t\ti + 1\n\t\t\t\t\t\t\t} du mécanisme 'variations' n'est pas compatible avec celle d'une branche précédente`,\n\t\t\t\t\t\t\t'unitConversion',\n\t\t\t\t\t\t\te,\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn [\n\t\t\t\tcurrentCondition && evaluatedConsequence?.nodeValue,\n\t\t\t\t[\n\t\t\t\t\t...explanations,\n\t\t\t\t\t{\n\t\t\t\t\t\tcondition: evaluatedCondition,\n\t\t\t\t\t\tconsequence: evaluatedConsequence ?? consequence,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tunit || evaluatedConsequence?.unit,\n\t\t\t\tpreviousConditions || currentCondition,\n\t\t\t]\n\t\t},\n\t\t[null, [], undefined, false],\n\t)\n\n\treturn {\n\t\t...node,\n\t\tnodeValue,\n\t\t...(unit !== undefined && { unit }),\n\t\texplanation,\n\t\tmissingVariables: explanation.reduce(\n\t\t\t(values, { condition, consequence }) =>\n\t\t\t\tmergeMissing(\n\t\t\t\t\tvalues,\n\t\t\t\t\tmergeMissing(\n\t\t\t\t\t\tbonus((condition as EvaluatedNode).missingVariables),\n\t\t\t\t\t\t(\n\t\t\t\t\t\t\t'nodeValue' in condition &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== false &&\n\t\t\t\t\t\t\t\tcondition.nodeValue !== null\n\t\t\t\t\t\t) ?\n\t\t\t\t\t\t\t(consequence as EvaluatedNode).missingVariables\n\t\t\t\t\t\t:\t{},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t{},\n\t\t),\n\t}\n}\n\nregisterEvaluationFunction('variations', evaluate)\n","import { normalizeDateString } from './date'\nimport { PublicodesError } from './error'\n\nexport type BinaryOp =\n\t| { '+': [ExprAST, ExprAST] }\n\t| { '-': [ExprAST, ExprAST] }\n\t| { '*': [ExprAST, ExprAST] }\n\t| { '/': [ExprAST, ExprAST] }\n\t| { '**': [ExprAST, ExprAST] }\n\t| { '>': [ExprAST, ExprAST] }\n\t| { '<': [ExprAST, ExprAST] }\n\t| { '>=': [ExprAST, ExprAST] }\n\t| { '<=': [ExprAST, ExprAST] }\n\t| { '=': [ExprAST, ExprAST] }\n\t| { '!=': [ExprAST, ExprAST] }\n\nexport type UnaryOp = {\n\t'-': [{ constant: { type: 'number'; nodeValue: 0 } }, ExprAST]\n}\n\n/** AST of a publicodes expression. */\nexport type ExprAST =\n\t| BinaryOp\n\t| UnaryOp\n\t| { variable: string }\n\t| { constant: { type: 'number'; nodeValue: number; rawUnit?: string } }\n\t| { constant: { type: 'boolean'; nodeValue: boolean } }\n\t// NOTE: pourquoi ne pas utiliser le type Date directement ?\n\t| { constant: { type: 'string' | 'date'; nodeValue: string } }\n\ntype ParserErrorDetails = {\n\texpression: string\n\tposition: number\n\texpected: string\n\tfound: string\n\tcustomMessage?: string\n}\n\nclass ParserError extends Error {\n\tdetails: ParserErrorDetails\n\n\tconstructor(details: ParserErrorDetails) {\n\t\tconst message = formatParserError(details)\n\t\tsuper(message)\n\t\tthis.details = details\n\t}\n}\n\nclass SyntaxError extends PublicodesError<'SyntaxError'> {\n\tconstructor(details: ParserErrorDetails & { dottedName: string }) {\n\t\tconst message = formatParserError(details)\n\t\tsuper('SyntaxError', message, details)\n\t}\n}\n\nfunction formatParserError({\n\texpression,\n\tposition,\n\texpected,\n\tfound,\n\tcustomMessage,\n}: ParserErrorDetails): string {\n\tconst pointer = ' '.repeat(position) + '^'\n\tconst defaultMessage = `${expected} est attendu, ${\n\t\tfound ?\n\t\t\t`mais \"${found}\" a été trouvé`\n\t\t:\t'hors l’expression se termine prématurément'\n\t}`\n\n\treturn `L'expression suivante n'est pas valide :\n   \n   ${expression}\n   ${pointer}\n   ${customMessage ?? defaultMessage}\n`\n}\n\ntype ParserState = {\n\treadonly strExpression: string\n\tcurrent: number\n\ttree: ExprAST | null\n}\n\nfunction createParser(expression: string): ParserState {\n\treturn {\n\t\tstrExpression: expression,\n\t\tcurrent: 0,\n\t\ttree: null,\n\t}\n}\n\nfunction throwParserError(\n\tparser: ParserState,\n\texpected: string,\n\tfound: string,\n\tcustomMessage?: string,\n): never {\n\tthrow new ParserError({\n\t\texpression: parser.strExpression,\n\t\tposition: parser.current,\n\t\texpected,\n\t\tfound,\n\t\tcustomMessage,\n\t})\n}\n\nfunction consume(parser: ParserState, expected: string): string {\n\tif (isEOL(parser)) {\n\t\tthrowParserError(parser, `'${expected}'`, '')\n\t}\n\treturn parser.strExpression[parser.current++]\n}\n\nfunction expect(parser: ParserState, expected: string): void {\n\tconst char = peek(parser)\n\tif (char !== expected) {\n\t\tthrowParserError(parser, `'${expected}'`, char)\n\t}\n\tconsume(parser, expected)\n}\n\nfunction expectRegExp(\n\tparser: ParserState,\n\tregexp: RegExp,\n\tdescription?: string,\n\terrorMessage?: string,\n): { parser: ParserState; value: string } {\n\tconst match = parser.strExpression.slice(parser.current).match(regexp)\n\tif (!match) {\n\t\tthrowParserError(\n\t\t\tparser,\n\t\t\tdescription ?? regexp.source,\n\t\t\tpeek(parser, 5),\n\t\t\terrorMessage,\n\t\t)\n\t}\n\tparser.current += match[0].length\n\treturn { parser, value: match[0] }\n}\n\nexport function parseExpression(\n\trawNode: string,\n\tdottedName = '<expression>',\n): ExprAST {\n\tif (typeof rawNode === 'number') {\n\t\treturn numberNode(rawNode)\n\t}\n\n\tconst singleLineExpression = (rawNode + '').replace(/\\s*\\n\\s*/g, ' ').trim()\n\n\ttry {\n\t\tconst parser = createParser(singleLineExpression)\n\t\tconst res = parseComparison(parser)\n\n\t\tif (!isEOL(res)) {\n\t\t\tif (isNextRegExp(res, operators)) {\n\t\t\t\tthrowParserError(\n\t\t\t\t\tres,\n\t\t\t\t\t'un opérateur entouré d’espaces',\n\t\t\t\t\tpeek(res),\n\t\t\t\t\t'Les opérateurs doivent être entourés d’espaces (\"2 + 2\" et non \"2+2\")',\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tthrowParserError(res, 'La fin d’expression', peek(res))\n\t\t}\n\n\t\treturn res.tree!\n\t} catch (error) {\n\t\tif (error instanceof ParserError) {\n\t\t\tthrow new SyntaxError({\n\t\t\t\t...error.details,\n\t\t\t\tdottedName,\n\t\t\t})\n\t\t}\n\t\tthrow error\n\t}\n}\n\nfunction parseComparison(parser: ParserState): ParserState {\n\tlet left = parseAddition(parser)\n\n\twhile (!isEOL(left) && isNextRegExp(left, comparisonOperator)) {\n\t\tconst op = expectRegExpGroup(left, comparisonOperator)\n\t\tconst right = parseAddition(op.parser)\n\n\t\tright.tree = binaryNode(op.value, left.tree!, right.tree!)\n\t\tleft = right\n\t}\n\n\treturn left\n}\n\nfunction parseAddition(parser: ParserState): ParserState {\n\tlet left = parseMultiplication(parser)\n\n\twhile (!isEOL(left) && isNextRegExp(left, additionOperator)) {\n\t\tconst op = expectRegExpGroup(left, additionOperator)\n\t\tconst right = parseMultiplication(op.parser)\n\n\t\tright.tree = binaryNode(op.value, left.tree!, right.tree!)\n\t\tleft = right\n\t}\n\n\treturn left\n}\n\nfunction parseMultiplication(parser: ParserState): ParserState {\n\tlet left = parseExponentiation(parser)\n\n\twhile (!isEOL(left) && isNextRegExp(left, multiplyOperator)) {\n\t\tconst op = expectRegExpGroup(left, multiplyOperator)\n\t\tconst right = parseExponentiation(op.parser)\n\n\t\tright.tree = binaryNode(op.value, left.tree!, right.tree!)\n\t\tleft = right\n\t}\n\n\treturn left\n}\n\nfunction parseExponentiation(parser: ParserState): ParserState {\n\tlet left = parsePrimary(parser)\n\n\twhile (!isEOL(left) && isNextRegExp(left, exponentiationOperator)) {\n\t\tconst op = expectRegExpGroup(left, exponentiationOperator)\n\t\tconst right = parseExponentiation(op.parser)\n\n\t\tright.tree = binaryNode(op.value, left.tree!, right.tree!)\n\t\tleft = right\n\t}\n\n\treturn left\n}\n\n// TODO: factoriser en sous-fonctions ?\nfunction parsePrimary(parser: ParserState): ParserState {\n\tif (peek(parser) === '(') {\n\t\tconsume(parser, '(')\n\t\texpectRegExp(parser, spaces)\n\t\tconst expr = parseComparison(parser)\n\t\texpectRegExp(expr, spaces)\n\t\texpect(expr, ')')\n\t\treturn expr\n\t} else if (peek(parser) === '-') {\n\t\tconsume(parser, '-')\n\t\texpectRegExp(parser, spaces)\n\t\tconst expr = parsePrimary(parser)\n\t\texpr.tree = minusNode(expr.tree!)\n\t\treturn expr\n\t} else if (isNextRegExp(parser, date)) {\n\t\tconst res = expectRegExp(parser, date, 'Une date')\n\t\treturn {\n\t\t\t...res.parser,\n\t\t\ttree: dateNode(res.value),\n\t\t}\n\t} else if (peek(parser).match(number)) {\n\t\tconst res = expectRegExp(parser, number, 'Un nombre')\n\t\tif (isNextRegExp(res.parser, unit)) {\n\t\t\tconst parsedUnit = expectRegExp(res.parser, unit, 'Une unité')\n\t\t\treturn {\n\t\t\t\t...parsedUnit.parser,\n\t\t\t\ttree: {\n\t\t\t\t\tconstant: {\n\t\t\t\t\t\ttype: 'number',\n\t\t\t\t\t\tnodeValue: parseFloat(res.value),\n\t\t\t\t\t\trawUnit: parsedUnit.value.trim(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t...res.parser,\n\t\t\ttree: numberNode(parseFloat(res.value)),\n\t\t}\n\t} else if (isNext(parser, \"'\") || isNext(parser, '\"')) {\n\t\tconst res = expectRegExp(parser, string, 'Une chaîne de caractères')\n\t\treturn {\n\t\t\t...res.parser,\n\t\t\ttree: { constant: { type: 'string', nodeValue: res.value.slice(1, -1) } },\n\t\t}\n\t} else if (peek(parser).match(letter) || peek(parser) === '^') {\n\t\tconst res = expectRegExp(parser, dotted_name, 'Un nom de règle')\n\n\t\treturn {\n\t\t\t...res.parser,\n\t\t\ttree:\n\t\t\t\tres.value === 'oui' || res.value === 'non' ?\n\t\t\t\t\tbooleanNode(res.value)\n\t\t\t\t:\t{ variable: res.value },\n\t\t}\n\t}\n\tthrowParserError(\n\t\tparser,\n\t\t'Une constante, une référence ou une expression entre parenthèses',\n\t\tpeek(parser),\n\t)\n}\n\nfunction peek(parser: ParserState, n?: number): string {\n\treturn n ?\n\t\t\tparser.strExpression.slice(parser.current, parser.current + n)\n\t\t:\tparser.strExpression[parser.current]\n}\n\n// PERF: il faudrait tester d'autre technique que le slice, mais pour l'instant\n// je fais au plus simple.\nfunction isNext(parser: ParserState, toMatch: string): boolean {\n\tconst slice = parser.strExpression.slice(\n\t\tparser.current,\n\t\tparser.current + toMatch.length,\n\t)\n\treturn slice === toMatch\n}\n\nfunction isNextRegExp(parser: ParserState, regexp: RegExp): boolean {\n\treturn parser.strExpression.slice(parser.current).match(regexp) != null\n}\n\nfunction expectRegExpGroup(\n\tparser: ParserState,\n\tregexp: RegExp,\n): { parser: ParserState; value: string } {\n\tconst match = parser.strExpression.slice(parser.current).match(regexp)\n\tif (!match) {\n\t\tthrow new Error(`Expected '${regexp.source}' but got ${peek(parser)}`)\n\t}\n\tparser.current += match[0].length\n\treturn { parser, value: match[1] }\n}\n\nfunction isEOL(parser: ParserState): boolean {\n\treturn parser.current >= parser.strExpression.length\n}\n\nfunction minusNode(expr: ExprAST): UnaryOp {\n\treturn { '-': [{ constant: { type: 'number', nodeValue: 0 } }, expr] }\n}\n\nfunction numberNode(value: number): ExprAST {\n\treturn { constant: { type: 'number', nodeValue: value } }\n}\n\nfunction booleanNode(value: 'oui' | 'non'): ExprAST {\n\treturn { constant: { type: 'boolean', nodeValue: value === 'oui' } }\n}\n\nfunction binaryNode(op: string, left: ExprAST, right: ExprAST): BinaryOp {\n\treturn { [op]: [left, right] } as BinaryOp\n}\n\nfunction dateNode(value: string): ExprAST {\n\treturn { constant: { type: 'date', nodeValue: normalizeDateString(value) } }\n}\n\nconst space =\n\t/[\\t\\u0020\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]/\n\nconst spaces = new RegExp(`^${space.source}*`)\nconst letter = /[a-zA-Z\\u00C0-\\u017F$]/\nconst symbol = /[',°€$%²_'\"'«»]/\n\nconst digit = /\\d/\nconst string = /'.*'|\".*\"/\n\nconst number = /\\d+(\\.\\d+)?/\nconst date = /^(?:(?:0?[1-9]|[12][0-9]|3[01])\\/)?(?:0?[1-9]|1[012])\\/\\d{4}/\n\nconst any_char = new RegExp(\n\t`(${letter.source}|${symbol.source}|${digit.source})`,\n)\n\nconst any_char_or_special_char = new RegExp(`(${any_char.source}|\\\\-|\\\\+|')`)\n\nconst phrase_starting_with = (char: RegExp) =>\n\tnew RegExp(\n\t\t`(${char.source}${any_char_or_special_char.source}*)(${space.source}${any_char.source}${any_char_or_special_char.source}*)*`,\n\t)\n\nconst rule_name = phrase_starting_with(letter)\n\nconst dotted_name = new RegExp(\n\t`^(${rule_name.source}|\\\\^)( \\\\. ${rule_name.source})*`,\n)\nconst unit_symbol = /[°%\\p{Sc}€$]/u // °, %, and all currency symbols (to do)\nconst unit_identifier = phrase_starting_with(\n\tnew RegExp(`(${unit_symbol.source}|${letter.source})`),\n)\n\nconst unit = new RegExp(\n\t`${spaces.source}(\\\\/)?${unit_identifier.source}(${space.source}*(\\\\.|\\\\/)${unit_identifier.source})*`,\n)\n\nconst oneOfBetweenAtLeastOneSpace = (values: string[]) =>\n\tnew RegExp(`^${space.source}+(${values.join('|')})${space.source}+`)\n\nconst exponentiationOperator = oneOfBetweenAtLeastOneSpace(['\\\\*\\\\*'])\nconst multiplyOperator = oneOfBetweenAtLeastOneSpace(['\\\\*', '\\\\/', '\\\\/\\\\/'])\nconst additionOperator = oneOfBetweenAtLeastOneSpace(['-', '\\\\+'])\nconst comparisonOperator = oneOfBetweenAtLeastOneSpace([\n\t'>',\n\t'<',\n\t'>=',\n\t'<=',\n\t'=',\n\t'!=',\n])\n\nconst operators = /(\\+|-|\\*|\\/|\\*\\*|>|<|>=|<=|=|!=)/\n","import { PublicodesError, PublicodesInternalError } from './error'\nimport { registerEvaluationFunction } from './evaluationFunctions'\nimport { Context } from './parsePublicodes'\n\nexport type ReferenceNode = {\n\tnodeKind: 'reference'\n\tname: string\n\tcontextDottedName: string\n\tdottedName?: string\n\ttitle?: string\n\tacronym?: string\n}\n\nexport default function parseReference(\n\tv: string,\n\tcontext: Context,\n): ReferenceNode {\n\tif (!context.dottedName) {\n\t\tthrow new PublicodesError(\n\t\t\t'InternalError',\n\t\t\t\"Une référence ne peut pas exister en dehors d'une règle (`context.dottedName` est vide)\",\n\t\t\t{\n\t\t\t\tdottedName: v,\n\t\t\t},\n\t\t)\n\t}\n\tif (!v) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t'Une référence ne peut pas être vide',\n\t\t\t{\n\t\t\t\tdottedName: context.dottedName,\n\t\t\t},\n\t\t)\n\t}\n\n\treturn {\n\t\tnodeKind: 'reference',\n\t\tname: v,\n\t\tcontextDottedName: context.dottedName,\n\t}\n}\n\nregisterEvaluationFunction('reference', function evaluateReference(node) {\n\tif (!node.dottedName) {\n\t\tthrow new PublicodesInternalError(node)\n\t}\n\tconst explanation = this.evaluateNode(\n\t\tthis.context.parsedRules[node.dottedName],\n\t)\n\tdelete explanation.sourceMap\n\treturn {\n\t\t...explanation,\n\t\t...node,\n\t}\n})\n","import { ASTNode } from './AST/types'\nimport { PublicodesError } from './error'\nimport abattement from './mecanisms/abattement'\nimport applicable from './mecanisms/applicable'\nimport arrondi from './mecanisms/arrondi'\nimport logarithme from './mecanisms/logarithme'\nimport avec from './mecanisms/avec'\nimport barème from './mecanisms/bareme'\nimport condition from './mecanisms/condition'\nimport contexte from './mecanisms/contexte'\nimport durée from './mecanisms/duree'\nimport {\n\tparseEstApplicable,\n\tparseEstDéfini,\n\tparseEstNonDéfini,\n} from './mecanisms/est'\nimport { parseEstNonApplicable } from './mecanisms/est-non-applicable'\nimport grille from './mecanisms/grille'\nimport { mecanismInversion } from './mecanisms/inversion'\nimport { parseMaximumDe, parseMinimumDe } from './mecanisms/max-min'\nimport moyenne from './mecanisms/moyenne'\nimport nonApplicable from './mecanisms/non-applicable'\nimport operations from './mecanisms/operation'\nimport parDéfaut from './mecanisms/parDefaut'\nimport plafond from './mecanisms/plafond'\nimport plancher from './mecanisms/plancher'\nimport produit from './mecanisms/product'\nimport résoudreRéférenceCirculaire from './mecanisms/resoudre-reference-circulaire'\nimport simplifierUnité from './mecanisms/simplifier-unite'\nimport situation from './mecanisms/situation'\nimport somme from './mecanisms/somme'\nimport tauxProgressif from './mecanisms/tauxProgressif'\nimport texte from './mecanisms/texte'\nimport toutesCesConditions from './mecanisms/toutes-ces-conditions'\nimport uneDeCesConditions from './mecanisms/une-de-ces-conditions'\nimport unité from './mecanisms/unite'\nimport variableManquante from './mecanisms/variablesManquantes'\nimport variations from './mecanisms/variations'\nimport { parseExpression } from './parseExpression'\nimport { Context } from './parsePublicodes'\nimport parseReference from './parseReference'\nimport { parseUnit } from './units'\n\nexport default function parse(rawNode, context: Context): ASTNode {\n\tif (rawNode == undefined) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\n\tUne des valeurs de la formule est vide.\n\tVérifiez que tous les champs à droite des deux points sont remplis`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (typeof rawNode === 'boolean') {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes valeurs booléennes true / false ne sont acceptées.\nUtilisez leur contrepartie française : 'oui' / 'non'`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tconst node =\n\t\ttypeof rawNode === 'object' ? rawNode : (\n\t\t\tparseExpression(rawNode, context.dottedName)\n\t\t)\n\tif ('nodeKind' in node) {\n\t\treturn node\n\t}\n\n\treturn {\n\t\t...parseChainedMecanisms(node, context),\n\t\trawNode,\n\t}\n}\n\nfunction parseMecanism(rawNode, context: Context) {\n\tif (Array.isArray(rawNode)) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nIl manque le nom du mécanisme pour le tableau : [${rawNode\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}]\nLes mécanisme possibles sont : 'somme', 'le maximum de', 'le minimum de', 'toutes ces conditions', 'une de ces conditions'.\n\t\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\n\tconst keys = Object.keys(rawNode)\n\tif (keys.length > 1) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`\nLes mécanismes suivants se situent au même niveau : ${keys\n\t\t\t\t.map((x) => `'${x}'`)\n\t\t\t\t.join(', ')}\nCela vient probablement d'une erreur dans l'indentation\n\t`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\tif (keys.length === 0) {\n\t\treturn { nodeKind: 'constant', nodeValue: undefined }\n\t}\n\n\tconst mecanismName = keys[0]\n\tconst values = rawNode[mecanismName]\n\tconst parseFn = parseFunctions[mecanismName]\n\n\tif (!parseFn) {\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\t`Le mécanisme \"${mecanismName}\" est inconnu.\n\nVérifiez qu'il n'y ait pas d'erreur dans l'orthographe du nom.`,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n\ttry {\n\t\treturn parseFn(values, context)\n\t} catch (e) {\n\t\tif (e instanceof PublicodesError || !(e instanceof Error)) {\n\t\t\tthrow e\n\t\t}\n\t\tthrow new PublicodesError(\n\t\t\t'SyntaxError',\n\t\t\tmecanismName ?\n\t\t\t\t`➡️ Dans le mécanisme ${mecanismName}\n${e.message}`\n\t\t\t:\te.message,\n\t\t\t{ dottedName: context.dottedName },\n\t\t)\n\t}\n}\n\n// Chainable mecanisme in their composition order (first one is applyied first)\nconst chainableMecanisms = [\n\tcontexte,\n\tvariableManquante,\n\tavec,\n\tapplicable,\n\tnonApplicable,\n\tarrondi,\n\tunité,\n\tsimplifierUnité,\n\tplancher,\n\tplafond,\n\tparDéfaut,\n\tsituation,\n\trésoudreRéférenceCirculaire,\n\tabattement,\n]\n\nfunction parseChainedMecanisms(rawNode, context: Context): ASTNode {\n\tconst parseFn = chainableMecanisms.find((fn) => fn.nom in rawNode)\n\tif (!parseFn) {\n\t\treturn parseMecanism(rawNode, context)\n\t}\n\tconst { [parseFn.nom]: param, ...valeur } = rawNode\n\n\treturn parseMecanism(\n\t\t{\n\t\t\t[parseFn.nom]: {\n\t\t\t\tvaleur,\n\t\t\t\t[parseFn.nom]: param,\n\t\t\t},\n\t\t},\n\t\tcontext,\n\t)\n}\n\nconst parseFunctions = {\n\t...operations,\n\t...chainableMecanisms.reduce((acc, fn) => ({ [fn.nom]: fn, ...acc }), {}),\n\tlogarithme: logarithme,\n\t'inversion numérique': mecanismInversion,\n\t'le maximum de': parseMaximumDe,\n\t'le minimum de': parseMinimumDe,\n\t'taux progressif': tauxProgressif,\n\t'toutes ces conditions': toutesCesConditions,\n\t'est non défini': parseEstNonDéfini,\n\t'est non applicable': parseEstNonApplicable,\n\t'est applicable': parseEstApplicable,\n\t'est défini': parseEstDéfini,\n\t'une de ces conditions': uneDeCesConditions,\n\tcondition,\n\tbarème,\n\tdurée,\n\tgrille,\n\tmultiplication: produit,\n\tproduit,\n\tsomme,\n\tmoyenne,\n\t[texte.nom]: texte,\n\tvaleur: parse,\n\tvariable: parseReference,\n\tvariations,\n\tconstant: (v, context: Context) =>\n\t\tObject.assign(v, {\n\t\t\t// In the documentation we want to display constants defined in the source\n\t\t\t// with their full precision. This is especially useful for percentages like\n\t\t\t// APEC 0,036 %.\n\t\t\tfullPrecision: true,\n\t\t\tisNullable: v.nodeValue == null,\n\t\t\tmissingVariables: {},\n\t\t\tnodeKind: 'constant',\n\t\t\tdottedName: context.dottedName,\n\t\t\t...(v.type === 'number' && v.rawUnit ?\n\t\t\t\t{ unit: parseUnit(v.rawUnit, context.getUnitKey) }\n\t\t\t:\t{}),\n\t\t}),\n}\n\nexport const mecanismKeys = Object.keys(parseFunctions)\nexport const valueMecanismKeys = mecanismKeys.filter(\n\t(name) => !chainableMecanisms.find(({ nom }) => nom === name),\n)\n","import { ParsedRules, PublicodesError } from '.'\nimport { makeASTTransformer, makeASTVisitor } from './AST'\nimport { ASTNode } from './AST/types'\nimport { PublicodesInternalError } from './error'\nimport { defaultNode, notApplicableNode } from './evaluationUtils'\nimport parse from './parse'\nimport { Context, ReferencesMaps, RulesReplacements } from './parsePublicodes'\nimport { Rule, RuleNode } from './rule'\nimport { updateReferencesMapsFromReferenceNode } from './ruleUtils'\nimport { mergeWithArray } from './utils'\n\nexport type ReplacementRule = {\n\tnodeKind: 'replacementRule'\n\tdefinitionRule: ASTNode<'reference'> & { dottedName: string }\n\treplacedReference: ASTNode<'reference'>\n\tpriority?: number\n\twhiteListedNames: Array<ASTNode<'reference'>>\n\trawNode: any\n\tblackListedNames: Array<ASTNode<'reference'>>\n\tremplacementRuleId: number\n\treplaceByNonApplicable: boolean\n}\n\n// Replacements depend on the context and their evaluation implies using\n// \"variations\" node everywhere there is a reference to the original rule.\n// However for performance reason we want to mutualize identical \"variations\"\n// nodes instead of duplicating them, to avoid wasteful computations.\n//\n// The implementation works by first attributing an identifier for each\n// replacementRule. We then use this identifier to create a cache key that\n// represents the combinaison of applicables replacements for a given reference.\n// For example if replacements 12, 13 et 643 are applicable we use the key\n// `12-13-643` as the cache identifier in the `inlineReplacements` function.\nlet remplacementRuleId = 0\nconst cache = {}\n\nexport function parseReplacements(\n\treplacements: Rule['remplace'],\n\tcontext: Context,\n): Array<ReplacementRule> {\n\tif (!replacements) {\n\t\treturn []\n\t}\n\n\treturn (Array.isArray(replacements) ? replacements : [replacements]).map(\n\t\t(replacement) => {\n\t\t\tif (typeof replacement === 'string') {\n\t\t\t\treplacement = { 'références à': replacement }\n\t\t\t}\n\n\t\t\tconst replacedReference = parse(replacement['références à'], context)\n\n\t\t\tconst [whiteListedNames, blackListedNames] = [\n\t\t\t\treplacement.dans ?? [],\n\t\t\t\treplacement['sauf dans'] ?? [],\n\t\t\t]\n\t\t\t\t.map((dottedName) =>\n\t\t\t\t\tArray.isArray(dottedName) ? dottedName : [dottedName],\n\t\t\t\t)\n\t\t\t\t.map((refs) => refs.map((ref) => parse(ref, context)))\n\t\t\tif (\n\t\t\t\treplacement.priorité != null &&\n\t\t\t\t(typeof replacement.priorité !== 'number' || replacement.priorité < 0)\n\t\t\t) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t'La priorité du remplacement doit être un nombre positif',\n\t\t\t\t\tcontext,\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tnodeKind: 'replacementRule',\n\t\t\t\trawNode: replacement,\n\t\t\t\tpriority: replacement.priorité,\n\t\t\t\tdefinitionRule: parse(context.dottedName, context),\n\t\t\t\treplacedReference,\n\t\t\t\treplaceByNonApplicable: false,\n\t\t\t\twhiteListedNames,\n\t\t\t\tblackListedNames,\n\t\t\t\tremplacementRuleId: remplacementRuleId++,\n\t\t\t} as ReplacementRule\n\t\t},\n\t)\n}\n\nexport function parseRendNonApplicable(\n\trules: Rule['rend non applicable'],\n\tcontext: Context,\n): Array<ReplacementRule> {\n\tconst rendNonApplicableReplacements = parseReplacements(rules, context)\n\trendNonApplicableReplacements.forEach(\n\t\t(r) => (r.replaceByNonApplicable = true),\n\t)\n\treturn rendNonApplicableReplacements\n}\n\nexport function getReplacements(\n\tparsedRules: Record<string, RuleNode>,\n): RulesReplacements<string> {\n\tconst ret = {}\n\tfor (const dottedName in parsedRules) {\n\t\tconst rule = parsedRules[dottedName]\n\t\tfor (const replacement of rule.replacements) {\n\t\t\tif (!replacement.replacedReference.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(replacement)\n\t\t\t}\n\t\t\tconst key = replacement.replacedReference.dottedName\n\t\t\tret[key] = [...(ret[key] ?? []), replacement]\n\t\t}\n\t}\n\n\treturn ret\n}\n\nexport function inlineReplacements<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>({\n\tnewRules,\n\tpreviousReplacements,\n\tparsedRules,\n\treferencesMaps,\n}: {\n\tnewRules: ParsedRules<NewNames>\n\tpreviousReplacements: RulesReplacements<PreviousNames>\n\tparsedRules: ParsedRules<PreviousNames | NewNames>\n\treferencesMaps: ReferencesMaps<NewNames | PreviousNames>\n}): [\n\tParsedRules<NewNames | PreviousNames>,\n\tRulesReplacements<NewNames | PreviousNames>,\n] {\n\ttype Names = NewNames | PreviousNames\n\tconst newReplacements = getReplacements(newRules) as RulesReplacements<Names>\n\n\tconst ruleNamesWithNewReplacements = new Set([]) as Set<Names>\n\tfor (const replacedReference in newReplacements) {\n\t\tconst rulesThatUse =\n\t\t\treferencesMaps.rulesThatUse.get(replacedReference as NewNames | Names) ??\n\t\t\t[]\n\n\t\tfor (const value of rulesThatUse) {\n\t\t\truleNamesWithNewReplacements.add(value)\n\t\t}\n\t}\n\n\tconst newRuleNamesWithPreviousReplacements: Set<NewNames> = new Set(\n\t\t(Object.keys(newRules) as Array<NewNames>).filter((ruleName) =>\n\t\t\t[...(referencesMaps.referencesIn.get(ruleName) ?? new Set())].some(\n\t\t\t\t(reference) =>\n\t\t\t\t\t(previousReplacements[reference as PreviousNames] ?? []).length,\n\t\t\t),\n\t\t),\n\t)\n\n\tconst replacements = mergeWithArray(previousReplacements, newReplacements)\n\tif (\n\t\t!newRuleNamesWithPreviousReplacements.size &&\n\t\t!ruleNamesWithNewReplacements.size\n\t) {\n\t\treturn [parsedRules, replacements]\n\t}\n\n\tconst inlinePreviousReplacement = makeReplacementInliner(\n\t\tpreviousReplacements,\n\t\treferencesMaps,\n\t)\n\tconst inlineNewReplacement = makeReplacementInliner(\n\t\tnewReplacements,\n\t\treferencesMaps,\n\t)\n\n\tnewRuleNamesWithPreviousReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlinePreviousReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode<Names>\n\t})\n\truleNamesWithNewReplacements.forEach((name) => {\n\t\tparsedRules[name] = inlineNewReplacement(\n\t\t\tparsedRules[name],\n\t\t) as RuleNode<Names>\n\t})\n\n\treturn [parsedRules, replacements]\n}\n\nexport function makeReplacementInliner(\n\treplacements: RulesReplacements<string>,\n\treferencesMaps: ReferencesMaps<string>,\n): (n: ASTNode) => ASTNode {\n\treturn makeASTTransformer((node, transform) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'replacementRule' ||\n\t\t\tnode.nodeKind === 'inversion' ||\n\t\t\tnode.nodeKind === 'une possibilité'\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (node.nodeKind === 'contexte') {\n\t\t\t// We don't replace references in contexte keys\n\t\t\treturn {\n\t\t\t\t...node,\n\t\t\t\texplanation: {\n\t\t\t\t\t...node.explanation,\n\t\t\t\t\tvaleur: transform(node.explanation.valeur),\n\t\t\t\t\tcontexte: node.explanation.contexte.map(([name, value]) => [\n\t\t\t\t\t\tname,\n\t\t\t\t\t\ttransform(value),\n\t\t\t\t\t]),\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif (node.nodeKind === 'reference') {\n\t\t\tif (!node.dottedName) {\n\t\t\t\tthrow new PublicodesInternalError(node)\n\t\t\t}\n\t\t\tconst replacedReferenceNode = replace(\n\t\t\t\tnode,\n\t\t\t\treplacements[node.dottedName] ?? [],\n\t\t\t)\n\t\t\t// Collect inlined replacement\n\t\t\tmakeASTVisitor((n) => {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(\n\t\t\t\t\tn,\n\t\t\t\t\treferencesMaps,\n\t\t\t\t\tnode.contextDottedName,\n\t\t\t\t)\n\t\t\t\treturn 'continue'\n\t\t\t})(replacedReferenceNode)\n\t\t\treturn replacedReferenceNode\n\t\t}\n\t})\n}\n\nfunction replace(\n\tnode: ASTNode<'reference'>,\n\treplacements: Array<ReplacementRule>,\n): ASTNode {\n\t// TODO : handle transitivité\n\n\tconst applicableReplacements = replacements\n\t\t.filter(\n\t\t\t({ definitionRule }) =>\n\t\t\t\tdefinitionRule.dottedName !== node.contextDottedName,\n\t\t)\n\t\t.filter(\n\t\t\t({ whiteListedNames }) =>\n\t\t\t\t!whiteListedNames.length ||\n\t\t\t\twhiteListedNames.some((name) =>\n\t\t\t\t\tnode.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.filter(\n\t\t\t({ blackListedNames }) =>\n\t\t\t\t!blackListedNames.length ||\n\t\t\t\tblackListedNames.every(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!node.contextDottedName.startsWith(name.dottedName as string),\n\t\t\t\t),\n\t\t)\n\t\t.reverse()\n\t\t.sort((a, b) => {\n\t\t\tconst result = (b.priority ?? 0) - (a.priority ?? 0)\n\t\t\tif (result !== 0) {\n\t\t\t\treturn result\n\t\t\t}\n\t\t\treturn b.definitionRule.dottedName.localeCompare(\n\t\t\t\ta.definitionRule.dottedName,\n\t\t\t)\n\t\t})\n\n\tif (!applicableReplacements.length) {\n\t\treturn node\n\t}\n\n\tconst applicableReplacementsCacheKey = applicableReplacements\n\t\t.map((n) => n.remplacementRuleId)\n\t\t.join('-')\n\tif (cache[applicableReplacementsCacheKey]) {\n\t\treturn cache[applicableReplacementsCacheKey]\n\t}\n\tconst replacementNode = {\n\t\tnodeKind: 'variations',\n\t\texplanation: [\n\t\t\t...applicableReplacements.map(\n\t\t\t\t({ definitionRule, replaceByNonApplicable }) =>\n\t\t\t\t\treplaceByNonApplicable ?\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcondition: definitionRule,\n\t\t\t\t\t\t\tconsequence: notApplicableNode,\n\t\t\t\t\t\t}\n\t\t\t\t\t:\t{\n\t\t\t\t\t\t\tcondition: estApplicable(definitionRule),\n\t\t\t\t\t\t\tconsequence: definitionRule,\n\t\t\t\t\t\t},\n\t\t\t),\n\t\t\t{ condition: oui, consequence: node },\n\t\t],\n\t} as ASTNode<'variations'>\n\n\treplacementNode.sourceMap = {\n\t\tmecanismName: 'replacement',\n\t\targs: {\n\t\t\tapplicableReplacements,\n\t\t\toriginalNode: node,\n\t\t},\n\t}\n\tcache[applicableReplacementsCacheKey] = replacementNode\n\treturn cache[applicableReplacementsCacheKey]\n}\n\nfunction estApplicable(node: ASTNode) {\n\treturn {\n\t\tnodeKind: 'condition',\n\t\texplanation: {\n\t\t\tsi: { nodeKind: 'est non applicable', explanation: node },\n\t\t\talors: non,\n\t\t\tsinon: oui,\n\t\t},\n\t} as ASTNode<'condition'>\n}\n\nconst oui = defaultNode(true)\nconst non = defaultNode(false)\n","import Engine, {\n\tLogger,\n\tParsedRules,\n\tPublicodesExpression,\n\tRawPublicodes,\n\tStrictOptions,\n} from '.'\nimport { makeASTTransformer, traverseParsedRules } from './AST'\nimport { FlagOptions, WarnOptions } from './engine/types'\nimport { PublicodesError } from './error'\nimport inferNodeType, { NodesTypes } from './inferNodeType'\nimport { ReplacementRule, inlineReplacements } from './parseReplacement'\nimport { Rule, parseRules } from './rule'\nimport {\n\tdisambiguateReferenceNode,\n\tupdateReferencesMapsFromReferenceNode,\n} from './ruleUtils'\nimport { getUnitKey } from './units'\nimport { weakCopyObj } from './utils'\n\nexport type Context<RuleNames extends string = string> = {\n\tdottedName: RuleNames | ''\n\tparsedRules: ParsedRules<RuleNames>\n\tnodesTypes: NodesTypes\n\treferencesMaps: ReferencesMaps<RuleNames>\n\trulesReplacements: RulesReplacements<RuleNames>\n\tlogger: Logger\n\n\tinversionMaxIterations?: number\n\n\t/**\n\t * This is used to generate unique IDs for sub-engines, we need to generate them at\n\t *  */\n\tsubEngineIncrementingNumber?: number\n\n\tstrict: Required<StrictOptions>\n\tflag: Required<FlagOptions>\n\twarn: Required<WarnOptions>\n\n\t// The subEngines attribute is used to get an outside reference to the\n\t// `contexte` intermediate calculations. The `contexte` mechanism uses\n\t// `shallowCopy` to instanciate a new engine, and we want to keep a reference\n\t// to it for the documentation.\n\t//\n\t// TODO: A better implementation would to remove the \"runtime\" concept of\n\t// \"subEngines\" and instead duplicate all rules names in the scope of the\n\t// `contexte` as described in\n\t// https://github.com/publicodes/publicodes/discussions/92\n\tsubEngines: Map<SituationHash, Engine<RuleNames>>\n\tsubEngineId: SituationHash | undefined\n\tevaluatedRule: RuleNames | undefined\n\tgetUnitKey: getUnitKey\n}\n\ntype PartialContext<RuleNames extends string> = Partial<\n\tOmit<Context<RuleNames>, 'strict' | 'flag' | 'warn'> & {\n\t\tstrict: StrictOptions\n\t\tflag: FlagOptions\n\t\twarn: WarnOptions\n\t}\n>\n\ntype SituationHash = number\n\nexport type RulesReplacements<RuleNames extends string> = Partial<\n\tRecord<RuleNames, ReplacementRule[]>\n>\n\nexport type ReferencesMaps<Names extends string> = {\n\treferencesIn: Map<Names, Set<Names>>\n\trulesThatUse: Map<Names, Set<Names>>\n}\n\nexport type RawRule = Omit<Rule, 'nom'> | PublicodesExpression | null\n\nexport function createContext<RuleNames extends string>(\n\tpartialContext: PartialContext<RuleNames>,\n): Context<RuleNames> {\n\treturn {\n\t\tevaluatedRule: undefined,\n\t\tdottedName: '',\n\t\tlogger: console,\n\t\tgetUnitKey: (x) => x,\n\t\tparsedRules: {} as ParsedRules<RuleNames>,\n\t\treferencesMaps: { referencesIn: new Map(), rulesThatUse: new Map() },\n\t\tnodesTypes: new WeakMap(),\n\t\trulesReplacements: {},\n\t\tsubEngines: new Map(),\n\t\tsubEngineId: undefined,\n\t\t...partialContext,\n\t\tflag: {\n\t\t\tfilterNotApplicablePossibilities: false,\n\t\t\tautomaticNamespaceDisabling: true,\n\t\t\t...partialContext.flag,\n\t\t},\n\t\tstrict: {\n\t\t\tsituation: true,\n\t\t\tnoOrphanRule: true,\n\t\t\tnoCycleRuntime: false,\n\t\t\tcheckPossibleValues: false,\n\t\t\t...partialContext.strict,\n\t\t},\n\t\twarn: {\n\t\t\tcyclicReferences: true,\n\t\t\texperimentalRules: true,\n\t\t\tunitConversion: true,\n\t\t\tdeprecatedSyntax: true,\n\t\t\tsituationIssues: true,\n\t\t\t...partialContext.warn,\n\t\t},\n\t}\n}\n\nexport function copyContext<C extends Context>(context: C): C {\n\treturn Object.assign({}, context, {\n\t\tparsedRules: weakCopyObj(context.parsedRules),\n\t\treferencesMaps: {\n\t\t\treferencesIn: new Map(context.referencesMaps.referencesIn),\n\t\t\trulesThatUse: new Map(context.referencesMaps.rulesThatUse),\n\t\t},\n\t\tsubEngines: new Map(),\n\t\twarn: weakCopyObj(context.warn),\n\t\tstrict: weakCopyObj(context.strict),\n\t\tflag: weakCopyObj(context.flag),\n\t})\n}\n/**\n * Parse a set of publicodes rules\n *\n * Allows to add new rules to a previously parsed set of rules (partialContext)\n *\n * @param rawRules - The new rules to parse\n * @param partialContext - The context to use for the parsing (if we want to add a set of rules to a previously parsed one)\n *\n * @returns The new context containing the parsed rules, the nodes types, the references maps and the rules replacements\n *\n * @experimental\n */\nexport default function parsePublicodes<\n\tContextNames extends string,\n\tNewRulesNames extends string,\n>(\n\trawRules: RawPublicodes<NewRulesNames>,\n\tpartialContext: PartialContext<ContextNames> = createContext({}),\n): Pick<\n\tContext<ContextNames | NewRulesNames>,\n\t'parsedRules' | 'nodesTypes' | 'referencesMaps' | 'rulesReplacements'\n> {\n\t// STEP 1 : get the rules as an object\n\n\tif (typeof rawRules === 'string')\n\t\tthrow new PublicodesError(\n\t\t\t'EngineError',\n\t\t\t'Publicodes does not parse yaml rule sets itself anymore. Please provide a parsed js object. E.g. the `eemeli/yaml` package.',\n\t\t\t{},\n\t\t)\n\n\t// let rules = { ...rawRules } // take 7-8ms\n\tconst rules = weakCopyObj(rawRules) // take 1-2ms\n\n\t// STEP 2: Rules parsing\n\tconst context = createContext(partialContext)\n\tconst previousParsedRules = context.parsedRules\n\tcontext.parsedRules = {} as ParsedRules<ContextNames>\n\tparseRules(rules, context)\n\n\tlet parsedRules = {} as ParsedRules<NewRulesNames | ContextNames>\n\tfor (const dottedName in previousParsedRules) {\n\t\tparsedRules[dottedName] = previousParsedRules[dottedName]\n\t}\n\tfor (const dottedName in context.parsedRules) {\n\t\tparsedRules[dottedName] = context.parsedRules[dottedName]\n\t}\n\n\t// STEP 3: Disambiguate reference\n\tconst [newRules, referencesMaps] =\n\t\tdisambiguateReferencesAndCollectDependencies(\n\t\t\tparsedRules,\n\t\t\tcontext.parsedRules,\n\t\t\tcontext.referencesMaps,\n\t\t\t!context.strict.noOrphanRule,\n\t\t)\n\n\t// STEP 4: Inline replacements\n\tlet rulesReplacements\n\t\t// eslint-disable-next-line prefer-const\n\t;[parsedRules, rulesReplacements] = inlineReplacements<\n\t\tNewRulesNames,\n\t\tContextNames\n\t>({\n\t\tparsedRules,\n\t\tnewRules: newRules as any,\n\t\treferencesMaps,\n\t\tpreviousReplacements: context.rulesReplacements,\n\t})\n\n\t// STEP 5: type inference\n\tconst nodesTypes = inferNodeType(\n\t\tObject.keys(newRules),\n\t\tparsedRules,\n\t\tcontext.nodesTypes,\n\t)\n\n\treturn {\n\t\tparsedRules,\n\t\tnodesTypes,\n\t\treferencesMaps,\n\t\trulesReplacements,\n\t}\n}\n\nfunction disambiguateReferencesAndCollectDependencies<\n\tNewNames extends string,\n\tPreviousNames extends string,\n>(\n\tparsedRules: ParsedRules<PreviousNames>,\n\tnewRules: ParsedRules<NewNames>,\n\treferencesMaps: ReferencesMaps<PreviousNames>,\n\tallowOrphanRules: boolean,\n): [\n\tparsedRules: ParsedRules<NewNames>,\n\treferencesMap: ReferencesMaps<PreviousNames | NewNames>,\n] {\n\tconst disambiguateReference = makeASTTransformer((node) =>\n\t\tdisambiguateReferenceNode(node, parsedRules),\n\t)\n\tconst disambiguateReferencesAndCollectDependencies = makeASTTransformer(\n\t\t(node) => {\n\t\t\tconst n = disambiguateReferenceNode(node, parsedRules)\n\t\t\tif (n) {\n\t\t\t\tupdateReferencesMapsFromReferenceNode(n, referencesMaps)\n\t\t\t}\n\t\t\treturn n\n\t\t},\n\t)\n\tconst disambiguatedRules = traverseParsedRules((node) => {\n\t\tif (node.nodeKind === 'replacementRule') {\n\t\t\t// The dependencies of replacements will be collected later, during the inlining\n\t\t\treturn disambiguateReference(node)\n\t\t}\n\t\tif (node.nodeKind === 'rule') {\n\t\t\tconst parentUndefined = (node.explanation.parents as any).find(\n\t\t\t\t(n: any) => !(n.dottedName in parsedRules),\n\t\t\t)\n\t\t\tif (!allowOrphanRules && parentUndefined) {\n\t\t\t\tthrow new PublicodesError(\n\t\t\t\t\t'SyntaxError',\n\t\t\t\t\t`La règle parente \"${parentUndefined.dottedName}\" n'existe pas`,\n\t\t\t\t\t{\n\t\t\t\t\t\tdottedName: node.dottedName,\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn disambiguateReferencesAndCollectDependencies(node)\n\t}, newRules)\n\treturn [\n\t\tdisambiguatedRules,\n\t\treferencesMaps as ReferencesMaps<NewNames | PreviousNames>,\n\t]\n}\n","import { ASTNode, EvaluatedNode } from '.'\n\nexport function computeTraversedVariableBeforeEval(\n\ttraversedVariablesStack: Array<Set<string>> | undefined,\n\tparsedNode: ASTNode,\n\tcachedNode: EvaluatedNode | undefined,\n\tpublicParsedRules: Record<string, ASTNode>,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (cachedNode !== undefined) {\n\t\tcachedNode.traversedVariables?.forEach((name) =>\n\t\t\ttraversedVariablesStack[0]?.add(name),\n\t\t)\n\t\treturn\n\t}\n\n\tif (isTraversedVariablesBoundary) {\n\t\t// Note: we use `unshift` instead of the more usual `push` to reverse the\n\t\t// order of the elements in the stack. This simplify access to the “top\n\t\t// element” with [0], instead of [length - 1]. We could also use the new\n\t\t// method `.at(-1)` but it isn't supported below Node v16.\n\t\ttraversedVariablesStack.unshift(new Set())\n\t}\n\n\tif (\n\t\tparsedNode.nodeKind === 'reference' &&\n\t\tparsedNode.dottedName &&\n\t\tparsedNode.dottedName in publicParsedRules\n\t) {\n\t\ttraversedVariablesStack[0].add(parsedNode.dottedName)\n\t}\n}\n\nexport function isTraversedVariablesBoundary(\n\ttraversedVariablesStack: Array<Set<string>> | undefined,\n\tparsedNode: ASTNode,\n) {\n\treturn (\n\t\t!!traversedVariablesStack &&\n\t\t(traversedVariablesStack.length === 0 || parsedNode.nodeKind === 'rule')\n\t)\n}\n\nexport function computeTraversedVariableAfterEval(\n\ttraversedVariablesStack: Array<Set<string>> | undefined,\n\tevaluatedNode: EvaluatedNode,\n\tisTraversedVariablesBoundary: boolean,\n) {\n\tif (traversedVariablesStack === undefined) {\n\t\treturn\n\t}\n\tif (isTraversedVariablesBoundary) {\n\t\tevaluatedNode.traversedVariables = Array.from(\n\t\t\ttraversedVariablesStack.shift() ?? [],\n\t\t)\n\n\t\tif (traversedVariablesStack.length > 0) {\n\t\t\tevaluatedNode.traversedVariables.forEach((name) => {\n\t\t\t\ttraversedVariablesStack[0].add(name)\n\t\t\t})\n\t\t}\n\t}\n}\n","import {\n\tParsedRules,\n\tPossibility,\n\tPublicodesError,\n\tPublicodesExpression,\n\tRawPublicodes,\n\tSituation,\n} from '..'\nimport { makeASTVisitor } from '../AST'\nimport { Evaluation, type ASTNode, type EvaluatedNode } from '../AST/types'\nimport { experimentalRuleWarning, warning } from '../error'\nimport { evaluationFunctions } from '../evaluationFunctions'\nimport parsePublicodes, {\n\tContext,\n\tcopyContext,\n\tcreateContext,\n} from '../parsePublicodes'\nimport { type RuleNode } from '../rule'\nimport * as utils from '../ruleUtils'\nimport {\n\tcomputeTraversedVariableAfterEval,\n\tcomputeTraversedVariableBeforeEval,\n\tisTraversedVariablesBoundary,\n} from '../traversedVariables'\nimport { weakCopyObj } from '../utils'\nimport { isAValidOption } from './isAValidOption'\nimport { Cache, EngineOptions } from './types'\n\nconst emptyCache = (): Cache => ({\n\t_meta: {\n\t\tevaluationRuleStack: [],\n\t\tparentRuleStack: [],\n\t},\n\ttraversedVariablesStack: undefined,\n\tnodes: new Map(),\n})\n/**\n * The engine is used to parse rules and evaluate expressions.\n * It is the main entry point to the publicodes library.\n *\n * @typeParam RuleNames - All rules names. Allows to automatically autocomplete rules names in the engine when using {@link Engine.getRule} or {@link Engine.setSituation}\n *\n */\nexport class Engine<RuleNames extends string = string> {\n\t/**@internal */\n\tbaseContext: Context<RuleNames>\n\t/**@internal */\n\tcontext: Context<string>\n\t/**@internal */\n\tpublicParsedRules: ParsedRules<RuleNames>\n\t/**@internal */\n\tpublicSituation: Situation<RuleNames>\n\n\t/**@internal */\n\tcache: Cache = emptyCache()\n\n\t/**\n\t * Creates an evaluation engine with the publicode rules given as arguments.\n\n\t * @param rules The publicodes model to use ({@link RawPublicodes} or {@link ParsedRules})\n\t * @param options Configuration options\n\t */\n\tconstructor(\n\t\trules: RawPublicodes<RuleNames> | ParsedRules<RuleNames> = {},\n\t\toptions: EngineOptions = {},\n\t) {\n\t\tconst strict = options.strict\n\t\tconst warn = options.warn\n\t\tconst initialContext = {\n\t\t\tdottedName: '' as never,\n\t\t\t...options,\n\t\t\tflag: {\n\t\t\t\tfilterNotApplicablePossibilities:\n\t\t\t\t\toptions.flag?.filterNotApplicablePossibilities ?? false,\n\t\t\t\tautomaticNamespaceDisabling:\n\t\t\t\t\toptions.flag?.automaticNamespaceDisabling ?? true,\n\t\t\t},\n\t\t\tstrict:\n\t\t\t\ttypeof strict === 'boolean' ?\n\t\t\t\t\t{\n\t\t\t\t\t\tsituation: strict,\n\t\t\t\t\t\tnoOrphanRule: options.allowOrphanRules === true ? false : strict,\n\t\t\t\t\t\tcheckPossibleValues: strict,\n\t\t\t\t\t\tnoCycleRuntime: strict,\n\t\t\t\t\t}\n\t\t\t\t: typeof strict === 'object' ? strict\n\t\t\t\t: {},\n\t\t\twarn:\n\t\t\t\ttypeof warn === 'boolean' ?\n\t\t\t\t\t{\n\t\t\t\t\t\tcyclicReferences: warn,\n\t\t\t\t\t\texperimentalRules: warn,\n\t\t\t\t\t\tunitConversion: warn,\n\t\t\t\t\t}\n\t\t\t\t: typeof warn === 'object' ? warn\n\t\t\t\t: {},\n\t\t}\n\t\tthis.baseContext = createContext({\n\t\t\t...initialContext,\n\t\t\t...parsePublicodes(rules as RawPublicodes<RuleNames>, initialContext),\n\t\t})\n\t\tthis.context = copyContext(this.baseContext)\n\n\t\tthis.publicParsedRules = {} as ParsedRules<RuleNames>\n\t\tfor (const name in this.baseContext.parsedRules) {\n\t\t\tconst rule = this.baseContext.parsedRules[name]\n\t\t\tif (\n\t\t\t\t!(rule as RuleNode).private &&\n\t\t\t\tutils.isAccessible(this.baseContext.parsedRules, '', name)\n\t\t\t) {\n\t\t\t\tthis.publicParsedRules[name] = rule as RuleNode<RuleNames>\n\t\t\t}\n\t\t}\n\n\t\tthis.publicSituation = {} as Situation<RuleNames>\n\t}\n\n\t/**\n\t * Reset the engine cache. This will clear all the cached evaluations.\n\t */\n\tresetCache() {\n\t\tthis.cache = emptyCache()\n\t\tthis.context.subEngines = new Map()\n\t}\n\n\t/**\n\t * Set the situation used for the evaluation.\n\t *\n\t * All subsequent evaluations will use this situation.\n\t * Reset the evaluation cache to avoid inconsistencies, so it is costly to call this method frequently with the same situation.\n\t */\n\tsetSituation(\n\t\t/**\n\t\t * The situation to set (see {@link Situation})\n\t\t */\n\t\tsituation: Situation<RuleNames> = {},\n\t\toptions: {\n\t\t\t/**\n\t\t\t * If true, the previous situation is kept and the new values are added to it.\n\t\t\t * @default false\n\t\t\t */\n\t\t\tkeepPreviousSituation?: boolean\n\t\t\t/**\n\t\t\t * If set to true, the engine will throw when the\n\t\t\t * situation contains invalid values\n\t\t\t * (rules that don't exists, or values with syntax errors).\n\t\t\t *\n\t\t\t * If set to false, it will log the error and filter the invalid values from the situation\n\t\t\t *\n\t\t\t * Overrides the {@link EngineOptions} strict option\n\t\t\t */\n\t\t\tstrict?: boolean\n\t\t} = {},\n\t) {\n\t\tthis.resetCache()\n\n\t\tconst keepPreviousSituation = options.keepPreviousSituation ?? false\n\n\t\tconst strictMode = options.strict || this.baseContext.strict.situation\n\n\t\tconst previousContext = this.context\n\t\tconst previousSituation = this.publicSituation\n\n\t\tconst handleError = (\n\t\t\terror: false | PublicodesError<'SituationError'>,\n\t\t\tguard: boolean,\n\t\t): boolean => {\n\t\t\tif (!error) return true\n\t\t\tif (guard) {\n\t\t\t\tthis.context = previousContext\n\t\t\t\tthis.publicSituation = previousSituation\n\t\t\t\tthrow error\n\t\t\t}\n\t\t\twarning(this.context, error.message, 'situationIssues')\n\t\t\treturn false\n\t\t}\n\n\t\tlet situationRules = Object.entries(situation).filter(([dottedName]) => {\n\t\t\treturn handleError(\n\t\t\t\tthis.checkSituationRuleStatic(dottedName as RuleNames),\n\t\t\t\tstrictMode,\n\t\t\t)\n\t\t})\n\n\t\tif (!keepPreviousSituation) {\n\t\t\tthis.context = copyContext(this.baseContext)\n\t\t\tthis.publicSituation = {}\n\t\t}\n\n\t\tif (strictMode) {\n\t\t\t// With strict mode, we parse everything at once to improve performance,\n\t\t\t// as the first error will stop the process anyway\n\t\t\tconst error = this.parseSituationRules(situationRules)\n\t\t\tif (error) {\n\t\t\t\tthis.context = previousContext\n\t\t\t\tthrow error\n\t\t\t}\n\t\t} else {\n\t\t\t// With strict mode off, we filter out the rules that throw an error during parsing\n\t\t\t// So we need to parse them one by one\n\t\t\tsituationRules = situationRules.filter((situationRule) => {\n\t\t\t\tconst error = this.parseSituationRules([situationRule])\n\t\t\t\tif (error) {\n\t\t\t\t\twarning(this.context, error.message, 'situationIssues')\n\t\t\t\t}\n\t\t\t\treturn !error\n\t\t\t})\n\t\t}\n\n\t\t// We only dynamically check for possiblities after the current situation\n\t\t// has been fully parsed to allow situation rules to depend on each other\n\t\t// (e.g. a rule's possibilities applicability condition depending on another\n\t\t// rule set in the situation)\n\t\tsituationRules = situationRules.filter(([dottedName, value]) => {\n\t\t\treturn handleError(\n\t\t\t\tthis.checkSituationRulePossibilities(\n\t\t\t\t\tdottedName as RuleNames,\n\t\t\t\t\tvalue as PublicodesExpression | ASTNode,\n\t\t\t\t),\n\t\t\t\tthis.baseContext.strict.checkPossibleValues,\n\t\t\t)\n\t\t})\n\n\t\tthis.publicSituation = Object.assign(\n\t\t\tthis.publicSituation,\n\t\t\tObject.fromEntries(situationRules),\n\t\t)\n\t\tif (this.context.warn.experimentalRules) {\n\t\t\tObject.keys(this.publicSituation).forEach((nom) => {\n\t\t\t\tif (utils.isExperimental(this.context.parsedRules, nom)) {\n\t\t\t\t\texperimentalRuleWarning(this.context, nom)\n\t\t\t\t}\n\t\t\t\tthis.checkExperimentalRule(\n\t\t\t\t\tthis.context.parsedRules[`${nom} . $SITUATION`],\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\n\t\treturn this\n\t}\n\n\t/**\n\t *\n\t * @returns true if the engine has encountered an inversion error during the last evaluation\n\t */\n\tinversionFail(): boolean {\n\t\treturn !!this.cache.inversionFail\n\t}\n\n\t/**\n\t * Get the rule with the given dottedName.\n\t * @param dottedName\n\t *\n\t * @throws PublicodesError if the rule does not exist or is private\n\t */\n\tgetRule(dottedName: RuleNames): RuleNode<RuleNames> {\n\t\tif (!(dottedName in this.baseContext.parsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'UnknownRule',\n\t\t\t\t`La règle '${dottedName}' n'existe pas`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\tif (!(dottedName in this.publicParsedRules)) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'PrivateRule',\n\t\t\t\t`La règle ${dottedName} est une règle privée.`,\n\t\t\t\t{ dottedName },\n\t\t\t)\n\t\t}\n\n\t\treturn this.publicParsedRules[dottedName] as RuleNode<RuleNames>\n\t}\n\n\t/**\n\t *\n\t * @returns the parsed rules used by the engine\n\t *\n\t * @remarks The private rules are not included in the parsed rules\n\t */\n\tgetParsedRules(): ParsedRules<RuleNames> {\n\t\treturn this.publicParsedRules\n\t}\n\n\t/**\n\t * Retrieve the current situation used for the evaluation\n\t *\n\t * This situation can be slightly different from the one set with\n\t * {@link setSituation} if some values were filtered out because of\n\t * evaluation errors.\n\t *\n\t * @returns {@link Situation} used by the engine\n\t */\n\tgetSituation(): Situation<RuleNames> {\n\t\treturn this.publicSituation\n\t}\n\n\t/**\n\t * Retrieves the list of possible values for a given rule.\n\t *\n\t * @param dottedName - The dotted name of the rule to get possibilities for\n\t * @param options - Options object\n\t * @param options.filterNotApplicable - When true, filters out possibilities that are not applicable based on the current situation. Defaults to false.\n\t * @returns Array of possibility nodes if the rule has possibilities defined, null otherwise\n\t *\n\t * @example\n\t * **Publicodes**\n\t * ```yaml\n\t * contrat:\n\t *  une possibilité:\n\t *   - \"'CDI'\"\n\t *   - \"'CDD'\"\n\t * ```js\n\t * engine.getPossibilitiesFor('contrat')\n\t *\n\t * ```\n\t */\n\tgetPossibilitiesFor(\n\t\tdottedName: RuleNames,\n\t\t{\n\t\t\tfilterNotApplicable = false,\n\t\t}: {\n\t\t\tfilterNotApplicable?: boolean\n\t\t} = {},\n\t): Array<Possibility> | null {\n\t\tif (\n\t\t\t!this.context.flag?.filterNotApplicablePossibilities &&\n\t\t\tfilterNotApplicable\n\t\t) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EngineError',\n\t\t\t\t'You must enable `flag.filterNotApplicablePossibilities` in engine instantiation to use the filterNotApplicable option',\n\t\t\t\t{},\n\t\t\t)\n\t\t}\n\t\tconst rule = this.getRule(dottedName)\n\t\tif (!rule.possibilities) {\n\t\t\treturn null\n\t\t}\n\t\tif (filterNotApplicable) {\n\t\t\treturn (\n\t\t\t\tthis.evaluateNode(rule.possibilities).explanation as Array<\n\t\t\t\t\tPossibility & {\n\t\t\t\t\t\tnotApplicable: { nodeValue: Evaluation }\n\t\t\t\t\t}\n\t\t\t\t>\n\t\t\t).filter((possibility) => possibility.notApplicable?.nodeValue !== true)\n\t\t}\n\t\treturn rule.possibilities.explanation\n\t}\n\n\t/**\n\t * Evaluate a publicodes expression.\n\t *\n\t * Use the current situation set by {@link setSituation}.\n\t *\n\t * @remarks\n\t * \tTo improve performance, the engine will cache the evaluation of the expression,\n\t * \tand all its byproducts (intermediate evaluations).\n\t * \tThe cache is reset when the situation is updated with {@link setSituation}.\n\t * \tYou can also manually reset it with {@link resetCache}.\n\t *\n\t * @param value - The publicodes expression to evaluate.\n\t * @returns The {@link ASTNode} of the publicodes expression decorated with evaluation results (nodeValue, unit, missingVariables, etc.)\n\t *\n\t */\n\tevaluate(value: PublicodesExpression | ASTNode): EvaluatedNode {\n\t\tconst cachedNode = this.cache.nodes.get(value)\n\t\tif (cachedNode) {\n\t\t\treturn cachedNode\n\t\t}\n\t\tthis.context = Object.assign(\n\t\t\tthis.context,\n\t\t\tparsePublicodes(\n\t\t\t\t{\n\t\t\t\t\t'[privé] $EVALUATION':\n\t\t\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t\t\t{ valeur: value }\n\t\t\t\t\t\t:\tvalue,\n\t\t\t\t},\n\t\t\t\tthis.context,\n\t\t\t),\n\t\t)\n\t\tthis.checkExperimentalRule(this.context.parsedRules['$EVALUATION'])\n\t\tthis.cache._meta = emptyCache()._meta\n\n\t\tconst evaluation = this.evaluateNode(\n\t\t\tthis.context.parsedRules['$EVALUATION'].explanation.valeur,\n\t\t)\n\t\tthis.cache.nodes.set(value, evaluation)\n\t\treturn evaluation\n\t}\n\n\t/**@internal */\n\tevaluateNode<T extends ASTNode>(parsedNode: T): EvaluatedNode & T {\n\t\tconst cachedNode = this.cache.nodes.get(parsedNode)\n\t\tlet traversedVariableBoundary: boolean = false\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\ttraversedVariableBoundary = isTraversedVariablesBoundary(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t)\n\t\t\tcomputeTraversedVariableBeforeEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tparsedNode,\n\t\t\t\tcachedNode,\n\t\t\t\tthis.publicParsedRules,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tif (cachedNode !== undefined) {\n\t\t\treturn cachedNode\n\t\t}\n\n\t\tif (!evaluationFunctions[parsedNode.nodeKind]) {\n\t\t\tthrow new PublicodesError(\n\t\t\t\t'EvaluationError',\n\t\t\t\t`Unknown \"nodeKind\": ${parsedNode.nodeKind}`,\n\t\t\t\t{ dottedName: '' },\n\t\t\t)\n\t\t}\n\n\t\tconst evaluatedNode = evaluationFunctions[parsedNode.nodeKind].call(\n\t\t\tthis,\n\t\t\tparsedNode,\n\t\t)\n\t\tif (this.cache.traversedVariablesStack) {\n\t\t\tcomputeTraversedVariableAfterEval(\n\t\t\t\tthis.cache.traversedVariablesStack,\n\t\t\t\tevaluatedNode,\n\t\t\t\ttraversedVariableBoundary,\n\t\t\t)\n\t\t}\n\n\t\tthis.cache.nodes.set(parsedNode, evaluatedNode)\n\t\treturn evaluatedNode\n\t}\n\n\t/**\n\t * Shallow Engine instance copy. Useful to evaluate the same rules with different situations.\n\t *\n\t * @returns a new Engine instance with the same baseContext, context, publicParsedRules, publicSituation and cache attributes.\n\t */\n\tshallowCopy(): Engine<RuleNames> {\n\t\tconst newEngine = new Engine<RuleNames>()\n\t\tnewEngine.baseContext = copyContext(this.baseContext)\n\t\tnewEngine.context = copyContext(this.context)\n\t\tnewEngine.publicParsedRules = this.publicParsedRules\n\t\tnewEngine.publicSituation = weakCopyObj(this.publicSituation)\n\t\tnewEngine.cache = {\n\t\t\t...emptyCache(),\n\t\t\tnodes: new Map(this.cache.nodes),\n\t\t}\n\t\treturn newEngine\n\t}\n\n\tprivate checkExperimentalRule = makeASTVisitor((node) => {\n\t\tif (\n\t\t\tnode.nodeKind === 'reference' &&\n\t\t\tutils.isExperimental(this.context.parsedRules, node.dottedName as string)\n\t\t) {\n\t\t\texperimentalRuleWarning(this.baseContext, node.dottedName as string)\n\t\t}\n\t\treturn 'continue'\n\t})\n\n\tprivate checkSituationRuleStatic(\n\t\tdottedName: RuleNames,\n\t): false | PublicodesError<'SituationError'> {\n\t\t// We check if the dotteName is a rule of the model\n\t\tif (!(dottedName in this.baseContext.parsedRules)) {\n\t\t\tconst errorMessage = `'${dottedName}' n'existe pas dans la base de règle.`\n\n\t\t\treturn new PublicodesError('SituationError', errorMessage, {\n\t\t\t\tdottedName,\n\t\t\t})\n\t\t}\n\t\tconst rule = this.baseContext.parsedRules[dottedName]\n\t\tif (rule.private) {\n\t\t\tconst errorMessage = `La règle ${dottedName} est une règle privée.`\n\t\t\treturn new PublicodesError('SituationError', errorMessage, { dottedName })\n\t\t}\n\n\t\treturn false\n\t}\n\n\tprivate checkSituationRulePossibilities(\n\t\tdottedName: RuleNames,\n\t\tvalue: PublicodesExpression | ASTNode,\n\t): false | PublicodesError<'SituationError'> {\n\t\tconst rule = this.baseContext.parsedRules[dottedName]\n\n\t\tif (\n\t\t\trule.possibilities &&\n\t\t\t!isAValidOption(this, rule.possibilities, this.evaluate(value))\n\t\t) {\n\t\t\treturn new PublicodesError(\n\t\t\t\t'SituationError',\n\t\t\t\t`La valeur \"${this.evaluate(value).nodeValue}\" ne fait pas partie des possibilités applicables listées pour cette règle.`,\n\t\t\t\t{\n\t\t\t\t\tdottedName,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\n\t\treturn false\n\t}\n\n\tprivate parseSituationRules(\n\t\tsituation: Array<[dottedName: string, value: unknown]>,\n\t): false | PublicodesError<'SituationError'> {\n\t\tconst situationToParse = Object.fromEntries(\n\t\t\tsituation.map(([dottedName, value]) => [\n\t\t\t\t`[privé] ${dottedName} . $SITUATION`,\n\t\t\t\tvalue && typeof value === 'object' && 'nodeKind' in value ?\n\t\t\t\t\t{ valeur: value }\n\t\t\t\t:\tvalue,\n\t\t\t]),\n\t\t) as RawPublicodes<RuleNames>\n\t\ttry {\n\t\t\tconst newContext = parsePublicodes(situationToParse, this.context)\n\t\t\tthis.context = Object.assign(this.context, newContext)\n\t\t\treturn false\n\t\t} catch (error) {\n\t\t\tlet message: string = ''\n\t\t\tlet dottedName: string | undefined\n\t\t\tif (!(error instanceof Error)) {\n\t\t\t\tthrow error\n\t\t\t}\n\n\t\t\tmessage = error.message\n\n\t\t\tif ('dottedName' in error) {\n\t\t\t\tdottedName = error.dottedName as string\n\t\t\t}\n\n\t\t\treturn new PublicodesError('SituationError', message, {\n\t\t\t\tdottedName: dottedName ?? '',\n\t\t\t})\n\t\t}\n\t}\n}\n","import { EvaluatedNode } from './index'\nimport { serializeUnit } from './units'\n\n/**\n * Serialize the evaluation of a node into a publicodes expression\n *\n */\nexport default function serializeEvaluation(\n\tnode: EvaluatedNode,\n): string | undefined {\n\tif (typeof node.nodeValue === 'number') {\n\t\tconst serializedUnit = serializeUnit(node.unit)\n\t\treturn (\n\t\t\t'' +\n\t\t\tnode.nodeValue +\n\t\t\t(serializedUnit ? serializedUnit.replace(/\\s/g, '') : '')\n\t\t)\n\t} else if (typeof node.nodeValue === 'boolean') {\n\t\treturn node.nodeValue ? 'oui' : 'non'\n\t} else if (typeof node.nodeValue === 'string') {\n\t\treturn `'${node.nodeValue}'`\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmDO,IAAM,oBAAoB,CAChC,OACA,SAIA,iBAAiB,oBAChB,SAAS,SAAY,OAAO,MAAM,SA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AAc,QACnD,EAAE,QAAQ,MAAM,IACf;AAAA,MACH,CAAC;AAAA,IACF;AACA,QAAI;AACH,YAAM,aAAa,gBAAgB,kBAAkB,KAAK,OAAO;AACjE,WAAK,UAAU,OAAO,OAAO,KAAK,SAAS,UAAU;AACrD,aAAO;AAAA,IACR,SAAS,OAAO;AACf,UAAI,UAAkB;AACtB,UAAI;AACJ,UAAI,EAAE,iBAAiB,QAAQ;AAC9B,cAAM;AAAA,MACP;AAEA,gBAAU,MAAM;AAEhB,UAAI,gBAAgB,OAAO;AAC1B,qBAAa,MAAM;AAAA,MACpB;AAEA,aAAO,IAAI,gBAAgB,kBAAkB,SAAS;AAAA,QACrD,YAAY,cAAc;AAAA,MAC3B,CAAC;AAAA,IACF;AAAA,EACD;AACD;;;ACxhBe,SAAR,oBACN,MACqB;AACrB,MAAI,OAAO,KAAK,cAAc,UAAU;AACvC,UAAM,iBAAiB,cAAc,KAAK,IAAI;AAC9C,WACC,KACA,KAAK,aACJ,iBAAiB,eAAe,QAAQ,OAAO,EAAE,IAAI;AAAA,EAExD,WAAW,OAAO,KAAK,cAAc,WAAW;AAC/C,WAAO,KAAK,YAAY,QAAQ;AAAA,EACjC,WAAW,OAAO,KAAK,cAAc,UAAU;AAC9C,WAAO,IAAI,KAAK,SAAS;AAAA,EAC1B;AACD;;;A5DiBA,IAAO,gBAAQ;","names":["node","copy","name","string","unit","formatUnit","factor","convertTable","unitClasses","evaluate","unit","formatUnit","unit","evaluate","context","name","evaluate","unit","evaluate","nodeValue","evaluate","unit","date","date","evaluate","unit","evaluate","evaluate","symbol","evaluate","unit","unit","evaluate","unit","evaluate","nodeValue","evaluate","unit","evaluate","evaluate","evaluate","unit","disambiguateReference","disambiguateReferencesAndCollectDependencies","isTraversedVariablesBoundary"]}