Skip to content

Commit

Permalink
refactor: convert pug-error to TypeScript (#3355)
Browse files Browse the repository at this point in the history
  • Loading branch information
ForbesLindesay authored Dec 23, 2021
1 parent a724446 commit 4767caf
Show file tree
Hide file tree
Showing 11 changed files with 282 additions and 89 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ cov-pt*
**/test/temp
.release.json
package-lock.json

scripts/tsconfig.json
packages/pug-error/lib
130 changes: 67 additions & 63 deletions README.md

Large diffs are not rendered by default.

11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
"devDependencies": {
"coveralls": "3.0.9",
"jest": "^26.0.1",
"prettier": "1.19.1"
"prettier": "1.19.1",
"typescript": "^4.1.2",
"wsrun": "^5.2.0"
},
"repository": {
"type": "git",
Expand All @@ -17,7 +19,7 @@
"scripts": {
"prettier:check": "prettier --ignore-path .gitignore --list-different './**/*.js'",
"format": "prettier --ignore-path .gitignore --write './**/*.js'",
"build": "wsrun --stages --exclude-missing --fast-exit --collect-logs build",
"build": "node scripts/prebuild && wsrun --stages --exclude-missing --fast-exit --collect-logs build && tsc --build scripts",
"pretest": "yarn build",
"test": "jest",
"coverage": "jest --coverage",
Expand All @@ -32,8 +34,5 @@
"./scripts/buffer-serializer.js"
]
},
"license": "MIT",
"dependencies": {
"wsrun": "^5.2.0"
}
"license": "MIT"
}
4 changes: 3 additions & 1 deletion packages/pug-error/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
"name": "pug-error",
"version": "1.3.3",
"description": "Standard error objects for pug",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"keywords": [
"pug"
],
"files": [
"index.js"
"lib/"
],
"repository": {
"type": "git",
Expand Down
41 changes: 23 additions & 18 deletions packages/pug-error/index.js → packages/pug-error/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
'use strict';

module.exports = makeError;
function makeError(code, message, options) {
var line = options.line;
var column = options.column;
var filename = options.filename;
var src = options.src;
var fullMessage;
var location = line + (column ? ':' + column : '');
export default function makeError(
code: string,
message: string,
options: {line: number; column: number; filename?: string; src?: string},
) {
const line = options.line;
const column = options.column;
const filename = options.filename;
const src = options.src;
let fullMessage;
const location = line + (column ? ':' + column : '');
if (src && line >= 1 && line <= src.split('\n').length) {
var lines = src.split('\n');
var start = Math.max(line - 3, 0);
var end = Math.min(lines.length, line + 3);
const lines = src.split('\n');
const start = Math.max(line - 3, 0);
const end = Math.min(lines.length, line + 3);
// Error context
var context = lines
const context = lines
.slice(start, end)
.map(function(text, i) {
var curr = i + start + 1;
var preamble = (curr == line ? ' > ' : ' ') + curr + '| ';
var out = preamble + text;
const curr = i + start + 1;
const preamble = (curr == line ? ' > ' : ' ') + curr + '| ';
let out = preamble + text;
if (curr === line && column > 0) {
out += '\n';
out += Array(preamble.length + column).join('-') + '^';
Expand All @@ -31,7 +32,7 @@ function makeError(code, message, options) {
} else {
fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message;
}
var err = new Error(fullMessage);
const err: any = new Error(fullMessage);
err.code = 'PUG:' + code;
err.msg = message;
err.line = line;
Expand All @@ -49,3 +50,7 @@ function makeError(code, message, options) {
};
return err;
}

// Make this easier to use from CommonJS
module.exports = makeError;
module.exports.default = makeError;
1 change: 0 additions & 1 deletion packages/pug-error/test/index.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict';

var assert = require('assert');
var error = require('../');

describe('with a source', function() {
Expand Down
10 changes: 10 additions & 0 deletions packages/pug-error/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "lib",
"tsBuildInfoFile": "lib/tsconfig.tsbuildinfo",
},
"references": [],
}
19 changes: 19 additions & 0 deletions packages/pug-strip-comments/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2021 Forbes Lindesay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
132 changes: 132 additions & 0 deletions scripts/prebuild.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
const {
readdirSync,
writeFileSync,
statSync,
readFileSync,
existsSync,
} = require('fs');

const LICENSE = `Copyright (c) ${new Date().getFullYear()} Forbes Lindesay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.`;

const packageNames = [];
const typeScriptPackages = [];
const packageDirectories = readdirSync(__dirname + '/../packages')
.filter(directory =>
statSync(__dirname + '/../packages/' + directory).isDirectory()
)
.sort();
packageDirectories.forEach(directory => {
if (!existsSync(__dirname + '/../packages/' + directory + '/LICENSE')) {
writeFileSync(
__dirname + '/../packages/' + directory + '/LICENSE',
LICENSE
);
}
let pkg = {};
try {
pkg = JSON.parse(
readFileSync(
__dirname + '/../packages/' + directory + '/package.json',
'utf8'
)
);
} catch (ex) {
if (ex.code !== 'ENOENT') {
throw ex;
}
}
const before = JSON.stringify(pkg);
if (!pkg.name) {
pkg.name = directory;
}
packageNames.push(pkg.name);
const after = JSON.stringify(pkg);
if (before !== after) {
writeFileSync(
__dirname + '/../packages/' + directory + '/package.json',
JSON.stringify(pkg, null, ' ') + '\n'
);
}
if (existsSync(__dirname + '/../packages/' + directory + '/tsconfig.json')) {
typeScriptPackages.push(directory);
const deps = [
...Object.keys(pkg.dependencies || {}),
...Object.keys(pkg.devDependencies || {}),
]
.filter(dep =>
existsSync(__dirname + '/../packages/' + dep + '/tsconfig.json')
)
.map(
dep =>
`\n {"path": ${JSON.stringify(
`../${dep.substr(`@databases/`.length)}`
)}},`
)
.join(``);
writeFileSync(
__dirname + '/../packages/' + directory + '/tsconfig.json',
`{
"extends": "../../tsconfig.json",
"compilerOptions": {
"composite": true,
"rootDir": "src",
"outDir": "lib",
"tsBuildInfoFile": "lib/tsconfig.tsbuildinfo",
},
"references": ${deps.length ? `[${deps}\n ],` : `[],`}
}
`
);
}
});

writeFileSync(
`scripts/tsconfig.json`,
`{
"extends": "../tsconfig.json",
"references": [${typeScriptPackages
.map(n => `\n {"path": ${JSON.stringify(`../packages/${n}`)}},`)
.join(``)}
],
}`
);
const [README_HEADER, _table, README_FOOTER] = readFileSync(
__dirname + '/../README.md',
'utf8'
).split('<!-- VERSION_TABLE -->');

const versionsTable = `
Package Name | Version
-------------|--------
${packageNames
.sort()
.map(
name =>
`${name} | [![NPM version](https://img.shields.io/npm/v/${name}?style=for-the-badge)](https://www.npmjs.com/package/${name})`
)
.join('\n')}
`;
writeFileSync(
__dirname + '/../README.md',
[README_HEADER, versionsTable, README_FOOTER || ''].join(
'<!-- VERSION_TABLE -->'
)
);
15 changes: 15 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"declaration": true,
"sourceMap": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": false,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"lib": ["es2016", "dom"],
"pretty": true
}
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4039,6 +4039,11 @@ typedarray-to-buffer@^3.1.5:
dependencies:
is-typedarray "^1.0.0"

typescript@^4.1.2:
version "4.5.4"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.5.4.tgz#a17d3a0263bf5c8723b9c52f43c5084edf13c2e8"
integrity sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==

uc.micro@^1.0.1, uc.micro@^1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac"
Expand Down

0 comments on commit 4767caf

Please sign in to comment.