Skip to content

Commit

Permalink
Merge pull request #38 from publicodes/compilation-better-errors
Browse files Browse the repository at this point in the history
feat(compilation): better error message
  • Loading branch information
EmileRolley authored May 29, 2024
2 parents 3b48325 + 6a6b214 commit c717888
Show file tree
Hide file tree
Showing 25 changed files with 383 additions and 225 deletions.
17 changes: 10 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
"version": "1.1.2",
"description": "A set of utility functions to build tools around Publicodes models",
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsup",
"watch": "tsup --watch",
Expand Down Expand Up @@ -65,28 +68,28 @@
"prettier": "^3.0.0",
"ts-jest": "^29.0.4",
"ts-node": "^10.9.2",
"tsup": "^6.5.0",
"tsup": "^8.0.2",
"typedoc": "^0.24.8",
"typedoc-plugin-export-functions": "^1.0.0",
"typescript": "^4.9.4",
"yaml": "^2.3.1"
},
"tsup": {
"verbose": true,
"entry": [
"source/index.ts",
"source/optims/index.ts",
"source/compilation/index.ts",
"source/migration/index.ts"
"src/index.ts",
"src/optims/index.ts",
"src/compilation/index.ts",
"src/migration/index.ts"
],
"cjsInterop": true,
"format": [
"cjs",
"esm"
],
"allowJs": true,
"sourceMap": true,
"dts": true,
"clean": true,
"target": "es2020",
"skipNodeModulesBundle": true
},
"publishConfig": {
Expand Down
2 changes: 1 addition & 1 deletion source/commons.ts → src/commons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import yaml from 'yaml'
*/

/**
* Represents a rule name, i.e. 'rule . A. B'
* Represents a rule name, i.e. 'rule . A . B'
*/
export type RuleName = string

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { readFileSync, statSync } from 'fs'
import glob from 'glob'
import yaml from 'yaml'
import { readFileSync, statSync } from 'fs'
import { getDoubleDefError, RawRules } from '../commons'
import { resolveImports } from './resolveImports'

Expand Down
6 changes: 3 additions & 3 deletions source/compilation/index.ts → src/compilation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ To import rules from a _packaged_ Publicodes model, you need to specify the foll
```yaml
importer!:
depuis:
nom: <npm_package_name>
source: <path_to_the_model_file> (optional)
url: <url_to_the_package_documentation> (optional)
nom: <npm_package_name>
source: <path_to_the_model_file> (optional)
url: <url_to_the_package_documentation> (optional)
dans: <namespace> (optional)
les règles:
- <rule_name_from_the_npm_package>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
getDoubleDefError,
} from '../commons'
import { readFileSync } from 'fs'
import { dirname, join } from 'path'
import { dirname, join, basename } from 'path'

/**
* @param {string} packageName - The package name.
Expand All @@ -33,28 +33,44 @@ const enginesCache = {}
* @param filePath - The path to the file containing the rules in a JSON format.
* @param opts - Options.
*
* @throws {Error} If the package is not found.
* @throws {Error} If the package name is missing in the macro.
*/
function getEngine(
filePath: string,
{ depuis }: ImportMacro,
verbose: boolean,
): Engine {
const packageName = depuis.nom
const packageName = depuis?.nom
const fileDirPath = dirname(filePath)

if (packageName === undefined) {
throw new Error(
`Le nom du package est manquant dans la macro 'importer!' dans le fichier: ${filePath}`,
`[ Erreur dans la macro 'importer!' ]
Le nom du package est manquant dans la macro 'importer!' dans le fichier: ${basename(filePath)}.
[ Solution ]
Ajoutez le nom du package dans la macro 'importer!'.
[ Exemple ]
importer!:
depuis:
nom: package-name
les règles:
- ruleA
- ruleB
...
`,
)
}

if (!enginesCache[packageName]) {
const modelPath =
depuis.source !== undefined
? join(fileDirPath, depuis.source)
: packageModelPath(packageName)

if (!enginesCache[modelPath]) {
try {
const modelPath =
depuis.source !== undefined
? join(fileDirPath, depuis.source)
: packageModelPath(packageName)
const model = JSON.parse(readFileSync(modelPath, 'utf-8'))
const engine = new Engine(model, {
logger: {
Expand All @@ -67,13 +83,26 @@ function getEngine(
if (verbose) {
console.debug(`📦 ${packageName} loaded`)
}
enginesCache[packageName] = engine
enginesCache[modelPath] = engine
} catch (e) {
console.error(`Error when loading '${packageName}': ${e}`)
throw new Error(`[ Erreur dans la macro 'importer!' ]
Le package '${packageName}' n'a pas pu être trouvé. (Le fichier '${modelPath}' est introuvable).
[ Solution ]
- Assurez-vous que le package existe et qu'il est correctement installé dans vos 'node_modules'.
- Assurez-vous que le fichier '${packageName}.model.json' existe à la racine du package. Sinon,
précisez le chemin du fichier dans la macro 'importer!' grâce à l'attribut 'source'.
[ Exemple ]
importer!:
depuis:
nom: package-name
source: ../custom-package/path/package-name.model.json
`)
}
}

return enginesCache[packageName]
return enginesCache[modelPath]
}

function getDependencies(engine: Engine, rule: RuleNode, acc = []) {
Expand Down Expand Up @@ -213,7 +242,11 @@ export function resolveImports(
rulesToImport?.forEach(({ ruleName, attrs }) => {
if (appearsMoreThanOnce(rulesToImport, ruleName)) {
throw new Error(
`La règle '${ruleName}' est définie deux fois dans ${importMacro.depuis.nom}`,
`[ Erreur dans la macro 'importer!' ]
La règle '${ruleName}' est définie deux fois dans ${importMacro.depuis.nom}
[ Solution ]
Supprimez une des deux définitions de la règle '${ruleName}' dans la macro 'importer!'`,
)
}
if (accFind(acc, ruleName)) {
Expand All @@ -224,9 +257,12 @@ export function resolveImports(
try {
rule = engine.getRule(ruleName)
} catch (e) {
throw new Error(
`La règle '${ruleName}' n'existe pas dans ${importMacro.depuis.nom}`,
)
throw new Error(`[ Erreur dans la macro 'importer!' ]
La règle '${ruleName}' n'existe pas dans '${importMacro.depuis.nom}'.
[ Solution ]
- Vérifiez que le nom de la règle est correct.
- Assurez-vous que la règle '${ruleName}' existe dans '${importMacro.depuis.nom}'.`)
}

const getUpdatedRule = (ruleName: RuleName, rule: Rule) => {
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { RawRule, RuleName } from './commons'
type SerializedRule = RawRule | number | string | null

function serializedRuleToRawRule(serializedRule: SerializedRule): RawRule {
if (typeof serializedRule === 'object') {
if (serializedRule !== null && typeof serializedRule === 'object') {
return serializedRule
}
return {
Expand Down
24 changes: 21 additions & 3 deletions test/compilation/getModelFromSource.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getModelFromSource } from '../../source/compilation/getModelFromSource'
import { getModelFromSource } from '../../src/compilation/getModelFromSource'
import { join, resolve } from 'path'

const testDataDir = resolve('./test/compilation/data/')
Expand Down Expand Up @@ -158,7 +158,12 @@ Ajout d'une description`,
expect(() => {
getModelFromSource(join(testDataDir, 'unknown-import.publicodes'))
}).toThrow(
"La règle 'root . unknown' n'existe pas dans my-external-package",
`[ Erreur dans la macro 'importer!' ]
La règle 'root . unknown' n'existe pas dans 'my-external-package'.
[ Solution ]
- Vérifiez que le nom de la règle est correct.
- Assurez-vous que la règle 'root . unknown' existe dans 'my-external-package'.`,
)
})

Expand All @@ -167,7 +172,20 @@ Ajout d'une description`,
expect(() => {
getModelFromSource(path)
}).toThrow(
`Le nom du package est manquant dans la macro 'importer!' dans le fichier: ${path}`,
`[ Erreur dans la macro 'importer!' ]
Le nom du package est manquant dans la macro 'importer!' dans le fichier: no-name-import.publicodes.
[ Solution ]
Ajoutez le nom du package dans la macro 'importer!'.
[ Exemple ]
importer!:
depuis:
nom: package-name
les règles:
- ruleA
- ruleB
...`,
)
})

Expand Down
2 changes: 1 addition & 1 deletion test/migration/migrateSituation.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { migrateSituation } from '../../source/migration/migrateSituation'
import { migrateSituation } from '../../src/migration/migrateSituation'

const migrationInstructions = {
keysToMigrate: { age: 'âge', 'année de naissance': '' },
Expand Down
6 changes: 3 additions & 3 deletions test/optims/constantFolding.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Engine, { RuleNode } from 'publicodes'
import { serializeParsedRules } from '../../source'
import { RuleName, RawRules, disabledLogger } from '../../source/commons'
import { constantFolding } from '../../source/optims/'
import { serializeParsedRules } from '../../src'
import { RuleName, RawRules, disabledLogger } from '../../src/commons'
import { constantFolding } from '../../src/optims/'
import { callWithEngine } from '../utils.test'

function constantFoldingWith(rawRules: any, targets?: RuleName[]): RawRules {
Expand Down
5 changes: 1 addition & 4 deletions test/parseExpression.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import {
serializeParsedExprAST,
substituteInParsedExpr,
} from '../source/commons'
import { serializeParsedExprAST, substituteInParsedExpr } from '../src/commons'

describe('substituteInParsedExpr', () => {
it('should return the same parsed expression if no occurence of the variable is found', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/serializeParsedRules.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Engine from 'publicodes'
import { serializeParsedRules } from '../source/index'
import { serializeParsedRules } from '../src/index'

describe('API > mecanisms list', () => {
it('should serialize empty rules', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RuleName, disabledLogger } from '../source/commons'
import { RuleName, disabledLogger } from '../src/commons'
import Engine from 'publicodes'
import type { ParsedRules } from 'publicodes'

Expand Down
21 changes: 8 additions & 13 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"rootDir": "src",
"outDir": "dist",
"rootDir": "source",
"types": ["node", "jest"],
"esModuleInterop": true,
"allowJs": true,
"lib": ["es2021"],
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"sourceMap": true,
"types": ["jest", "node"],
"declaration": true,
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true,
},
"ts-node": {
"transpileOnly": true,
"files": true,
},
"include": ["source/**/*.ts"],
"include": ["src"],
"exclude": ["./node_modules/", "./dist/", "./jest.config.js", "./test/"],
}
7 changes: 1 addition & 6 deletions typedoc.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
{
"$schema": "https://typedoc.org/schema.json",
"name": "@publicodes/tools API",
"entryPoints": [
"./source",
"./source/optims/",
"./source/compilation/",
"./source/migration"
],
"entryPoints": ["./src", "./src/optims/", "./src/compilation/"],
"navigationLinks": {
"GitHub": "https://github.com/publicodes/tools"
},
Expand Down
Loading

0 comments on commit c717888

Please sign in to comment.