Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some fixes as description #70

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ tmp/
.idea/
coverage
dist
package-lock.json
package-lock.json
.vscode
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
66 changes: 41 additions & 25 deletions lib/front_matter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,31 @@ function split(str: string) {
return { content: str };
}

function parse(str: string, options?: yaml.LoadOptions) {
export type ParseResult = Record<string, any> &
Partial<{
_content: string;
title: string;
description: string;
thumbnail: string;
date: any;
updated: any;
permalink: string;
}>;

function parse(str: string, options: yaml.LoadOptions = {}) {
if (typeof str !== 'string') throw new TypeError('str is required!');

const splitData = split(str);
const raw = splitData.data;

if (!raw) return { _content: str };

let data;
let data: ParseResult;

if (splitData.separator.startsWith(';')) {
data = parseJSON(raw);
} else {
data = parseYAML(raw, options);
data = parseYAML(raw, options) as any;
}

if (!data) return { _content: str };
Expand All @@ -55,26 +66,28 @@ function parse(str: string, options?: yaml.LoadOptions) {
const item = data[key];

if (item instanceof Date) {
data[key] = new Date(item.getTime() + (item.getTimezoneOffset() * 60 * 1000));
data[key] = new Date(
item.getTime() + (item.getTimezoneOffset() * 60 * 1000)
);
}
});

data._content = splitData.content;
return data;
}

function parseYAML(str, options: yaml.LoadOptions) {
function parseYAML(str: string, options: yaml.LoadOptions) {
const result = yaml.load(escapeYAML(str), options);
if (typeof result !== 'object') return;

return result;
}

function parseJSON(str) {
function parseJSON(str: string) {
try {
return JSON.parse(`{${str}}`);
} catch (err) {
return; // eslint-disable-line
return; // eslint-disable-line
}
}

Expand All @@ -93,12 +106,12 @@ function escapeYAML(str: string) {
}

interface Options {
mode?: 'json' | '',
prefixSeparator?: boolean,
separator?: string
mode?: 'json' | '';
prefixSeparator?: boolean;
separator?: string;
}
dimaslanjaka marked this conversation as resolved.
Show resolved Hide resolved

function stringify(obj, options: Options = {}) {
function stringify(obj: Record<string, any>, options: Options = {}): string {
if (!obj) throw new TypeError('obj is required!');

const { _content: content = '' } = obj;
Expand All @@ -123,12 +136,14 @@ function stringify(obj, options: Options = {}) {
return result;
}

function stringifyYAML(obj, options) {
type YamlMergedOpts = Options & yaml.DumpOptions;

function stringifyYAML(obj: Record<string, any>, options: YamlMergedOpts) {
const keys = Object.keys(obj);
const data = {};
const nullKeys = [];
const dateKeys = [];
let key, value, i, len;
let key: string, value: any, i: number, len: number;

for (i = 0, len = keys.length; i < len; i++) {
key = keys[i];
Expand Down Expand Up @@ -162,24 +177,25 @@ function stringifyYAML(obj, options) {
}

function stringifyJSON(obj) {
return JSON.stringify(obj, null, ' ')
return (
JSON.stringify(obj, null, ' ')
// Remove indention
.replace(/\n {2}/g, () => '\n')
.replace(/\n {2}/g, () => '\n')
// Remove prefixing and trailing braces
.replace(/^{\n|}$/g, '');
.replace(/^{\n|}$/g, '')
);
}

function doubleDigit(num) {
function doubleDigit(num: number) {
return num.toString().padStart(2, '0');
}

function formatDate(date) {
return `${date.getFullYear()}-${doubleDigit(date.getMonth() + 1)}-${doubleDigit(date.getDate())} ${doubleDigit(date.getHours())}:${doubleDigit(date.getMinutes())}:${doubleDigit(date.getSeconds())}`;
function formatDate(date: Date) {
return `${date.getFullYear()}-${doubleDigit(
date.getMonth() + 1
)}-${doubleDigit(date.getDate())} ${doubleDigit(
date.getHours()
)}:${doubleDigit(date.getMinutes())}:${doubleDigit(date.getSeconds())}`;
}

export {
parse,
split,
escapeYAML as escape,
stringify
};
export { parse, split, escapeYAML as escape, stringify };
11 changes: 11 additions & 0 deletions lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* @type {{ [key: string]: import("lint-staged").Commands | import("lint-staged").ConfigFn }}
*/
const config = {
'*.ts': 'eslint --fix',
'*.js': 'eslint --fix',
'*.json': 'npx prettier --write',
'*.yml': 'npx prettier --write'
};

module.exports = config;
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,21 @@
"name": "hexo-front-matter",
"version": "4.1.0",
"description": "Front-matter parser.",
"main": "dist/front_matter",
"main": "dist/front_matter.js",
"types": "./dist/front_matter.d.ts",
"scripts": {
"prepublish ": "npm run clean && npm run build",
"build": "tsc -b",
"clean": "tsc -b --clean",
"eslint": "eslint .",
"pretest": "npm run clean && npm run build",
"test": "mocha test/index.js --require ts-node/register",
"test-cov": "c8 --reporter=lcovonly npm run test"
"test-cov": "c8 --reporter=lcovonly npm run test",
"prepare": "husky install"
},
"files": [
"dist/**"
"dist"
],
"types": "./dist/front_matter.d.ts",
"repository": "hexojs/hexo-front-matter",
"keywords": [
"front-matter",
Expand All @@ -32,13 +33,15 @@
},
"devDependencies": {
"@types/js-yaml": "^4.0.5",
"@types/node": "^18.11.7",
"@types/node": "^18.16.3",
"@typescript-eslint/eslint-plugin": "^5.41.0",
"@typescript-eslint/parser": "^5.41.0",
"c8": "^7.12.0",
"chai": "^4.3.6",
"eslint": "^8.23.1",
"eslint-config-hexo": "^5.0.0",
"husky": "^8.0.3",
"lint-staged": "^13.2.2",
"mocha": "^10.0.0",
"ts-node": "^10.9.1",
"typescript": "^4.8.4"
Expand Down
31 changes: 13 additions & 18 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"sourceMap": true,
"outDir": "dist",
"declaration": true,
"esModuleInterop": true,
"types": [
"node"
]
},
"include": [
"lib/front_matter.ts"
],
"exclude": [
"node_modules"
]
}
"compilerOptions": {
"module": "CommonJS",
"target": "ES6",
"sourceMap": true,
"outDir": "dist",
"declaration": true,
"esModuleInterop": true,
"skipDefaultLibCheck": true,
"skipLibCheck": true
},
"include": ["lib/front_matter.ts"],
"exclude": ["node_modules", "dist"]
}