Skip to content

Commit

Permalink
refactor: refact types (#5271)
Browse files Browse the repository at this point in the history
  • Loading branch information
D-Sketon authored Oct 31, 2023
1 parent 268882b commit b898f29
Show file tree
Hide file tree
Showing 124 changed files with 509 additions and 394 deletions.
18 changes: 10 additions & 8 deletions lib/box/file.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { readFile, readFileSync, stat, statSync } from 'hexo-fs';
import type Promise from 'bluebird';
import { readFile, readFileSync, stat, statSync, type ReadFileOptions } from 'hexo-fs';
import type fs from 'fs';

class File {
public source: any;
public path: any;
public source: string;
public path: string;
public params: any;
public type: any;
public type: string;
static TYPE_CREATE: 'create';
static TYPE_UPDATE: 'update';
static TYPE_SKIP: 'skip';
Expand All @@ -17,19 +19,19 @@ class File {
this.type = type;
}

read(options) {
read(options?: ReadFileOptions): Promise<string | Buffer> {
return readFile(this.source, options);
}

readSync(options) {
readSync(options?: ReadFileOptions): string | Buffer {
return readFileSync(this.source, options);
}

stat(options) {
stat(): Promise<fs.Stats> {
return stat(this.source);
}

statSync(options) {
statSync(): fs.Stats {
return statSync(this.source);
}
}
Expand Down
55 changes: 31 additions & 24 deletions lib/box/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { createReadStream, readdir, stat, watch } from 'hexo-fs';
import { magenta } from 'picocolors';
import { EventEmitter } from 'events';
import { isMatch, makeRe } from 'micromatch';
import type Hexo from '../hexo';

const defaultPattern = new Pattern(() => ({}));

Expand All @@ -16,20 +17,18 @@ interface Processor {

class Box extends EventEmitter {
public options: any;
public context: any;
public base: any;
public context: Hexo;
public base: string;
public processors: Processor[];
public _processingFiles: any;
public watcher: any;
public Cache: any;
// TODO: replace runtime class _File
public File: any;
public ignore: any;
public ignore: any[];
public source: any;
public emit: any;
public ctx: any;

constructor(ctx, base, options?: object) {
constructor(ctx: Hexo, base: string, options?: object) {
super();

this.options = Object.assign({
Expand Down Expand Up @@ -64,13 +63,13 @@ class Box extends EventEmitter {
class _File extends File {
public box: Box;

render(options) {
render(options?: object) {
return ctx.render.render({
path: this.source
}, options);
}

renderSync(options) {
renderSync(options?: object) {
return ctx.render.renderSync({
path: this.source
}, options);
Expand All @@ -82,7 +81,9 @@ class Box extends EventEmitter {
return _File;
}

addProcessor(pattern, fn) {
addProcessor(pattern: (...args: any[]) => any): void;
addProcessor(pattern: string | RegExp | Pattern | ((...args: any[]) => any), fn: (...args: any[]) => any): void;
addProcessor(pattern: string | RegExp | Pattern | ((...args: any[]) => any), fn?: (...args: any[]) => any): void {
if (!fn && typeof pattern === 'function') {
fn = pattern;
pattern = defaultPattern;
Expand All @@ -97,7 +98,7 @@ class Box extends EventEmitter {
});
}

_readDir(base, prefix = '') {
_readDir(base: string, prefix = ''): BlueBirdPromise<any> {
const { context: ctx } = this;
const results = [];
return readDirWalker(ctx, base, results, this.ignore, prefix)
Expand All @@ -106,7 +107,7 @@ class Box extends EventEmitter {
.map(file => this._processFile(file.type, file.path).return(file.path));
}

_checkFileStatus(path) {
_checkFileStatus(path: string) {
const { Cache, context: ctx } = this;
const src = join(this.base, path);

Expand All @@ -120,7 +121,7 @@ class Box extends EventEmitter {
}));
}

process(callback?) {
process(callback?: NodeJSLikeCallback<any>): BlueBirdPromise<any> {
const { base, Cache, context: ctx } = this;

return stat(base).then(stats => {
Expand All @@ -132,14 +133,14 @@ class Box extends EventEmitter {

// Handle deleted files
return this._readDir(base)
.then(files => cacheFiles.filter(path => !files.includes(path)))
.map(path => this._processFile(File.TYPE_DELETE, path));
.then((files: string[]) => cacheFiles.filter((path: string) => !files.includes(path)))
.map((path: string) => this._processFile(File.TYPE_DELETE, path) as PromiseLike<any>);
}).catch(err => {
if (err && err.code !== 'ENOENT') throw err;
}).asCallback(callback);
}

_processFile(type, path) {
_processFile(type: string, path: string): BlueBirdPromise<void> | BlueBirdPromise<string> {
if (this._processingFiles[path]) {
return BlueBirdPromise.resolve();
}
Expand Down Expand Up @@ -182,7 +183,7 @@ class Box extends EventEmitter {
}).thenReturn(path);
}

watch(callback?) {
watch(callback?: NodeJSLikeCallback<never>): BlueBirdPromise<void> {
if (this.isWatching()) {
return BlueBirdPromise.reject(new Error('Watcher has already started.')).asCallback(callback);
}
Expand Down Expand Up @@ -217,24 +218,24 @@ class Box extends EventEmitter {
}).asCallback(callback);
}

unwatch() {
unwatch(): void {
if (!this.isWatching()) return;

this.watcher.close();
this.watcher = null;
}

isWatching() {
isWatching(): boolean {
return Boolean(this.watcher);
}
}

function escapeBackslash(path) {
function escapeBackslash(path: string): string {
// Replace backslashes on Windows
return path.replace(/\\/g, '/');
}

function getHash(path) {
function getHash(path: string): BlueBirdPromise<string> {
const src = createReadStream(path);
const hasher = createSha1Hash();

Expand All @@ -248,7 +249,7 @@ function getHash(path) {
return finishedPromise.then(() => hasher.digest('hex'));
}

function toRegExp(ctx, arg) {
function toRegExp(ctx: Hexo, arg: string): RegExp | null {
if (!arg) return null;
if (typeof arg !== 'string') {
ctx.log.warn('A value of "ignore:" section in "_config.yml" is not invalid (not a string)');
Expand All @@ -262,11 +263,11 @@ function toRegExp(ctx, arg) {
return result;
}

function isIgnoreMatch(path, ignore) {
function isIgnoreMatch(path: string, ignore: string | any[]): boolean {
return path && ignore && ignore.length && isMatch(path, ignore);
}

function readDirWalker(ctx, base, results, ignore, prefix) {
function readDirWalker(ctx: Hexo, base: string, results: any[], ignore: any, prefix: string): BlueBirdPromise<any> {
if (isIgnoreMatch(base, ignore)) return BlueBirdPromise.resolve();

return BlueBirdPromise.map(readdir(base).catch(err => {
Expand All @@ -292,4 +293,10 @@ function readDirWalker(ctx, base, results, ignore, prefix) {
});
}

export = Box;
export interface _File extends File {
box: Box;
render(options?: any): any;
renderSync(options?: any): any;
}

export default Box;
4 changes: 2 additions & 2 deletions lib/extend/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Console {
return this.store[this.alias[name]];
}

list() {
list(): Store {
return this.store;
}

Expand All @@ -66,7 +66,7 @@ class Console {
register(name: string, desc: string, fn: AnyFn): void
register(name: string, options: Option, fn: AnyFn): void
register(name: string, desc: string, options: Option, fn: AnyFn): void
register(name: string, desc: string | Option | AnyFn, options?: Option | AnyFn, fn?: AnyFn) {
register(name: string, desc: string | Option | AnyFn, options?: Option | AnyFn, fn?: AnyFn): void {
if (!name) throw new TypeError('name is required');

if (!fn) {
Expand Down
6 changes: 3 additions & 3 deletions lib/extend/deployer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ class Deployer {
this.store = {};
}

list() {
list(): Store {
return this.store;
}

get(name: string) {
get(name: string): StoreFunction {
return this.store[name];
}

register(name: string, fn: StoreFunction) {
register(name: string, fn: StoreFunction): void {
if (!name) throw new TypeError('name is required');
if (typeof fn !== 'function') throw new TypeError('fn must be a function');

Expand Down
6 changes: 3 additions & 3 deletions lib/extend/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ class Filter {
register(fn: StoreFunction, priority: number): void
register(type: string, fn: StoreFunction): void
register(type: string, fn: StoreFunction, priority: number): void
register(type: string | StoreFunction, fn?: StoreFunction | number, priority?: number) {
register(type: string | StoreFunction, fn?: StoreFunction | number, priority?: number): void {
if (!priority) {
if (typeof type === 'function') {
priority = fn as number;
Expand All @@ -61,7 +61,7 @@ class Filter {
store.sort((a, b) => a.priority - b.priority);
}

unregister(type: string, fn: StoreFunction) {
unregister(type: string, fn: StoreFunction): void {
if (!type) throw new TypeError('type is required');
if (typeof fn !== 'function') throw new TypeError('fn must be a function');

Expand All @@ -75,7 +75,7 @@ class Filter {
if (index !== -1) list.splice(index, 1);
}

exec(type: string, data: any[], options: FilterOptions = {}) {
exec(type: string, data: any[], options: FilterOptions = {}): Promise<any> {
const filters = this.list(type);
if (filters.length === 0) return Promise.resolve(data);

Expand Down
6 changes: 3 additions & 3 deletions lib/extend/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,17 @@ class Generator {
this.store = {};
}

list() {
list(): Store {
return this.store;
}

get(name: string) {
get(name: string): StoreFunction {
return this.store[name];
}

register(fn: GeneratorFunction): void
register(name: string, fn: GeneratorFunction): void
register(name: string | GeneratorFunction, fn?: GeneratorFunction) {
register(name: string | GeneratorFunction, fn?: GeneratorFunction): void {
if (!fn) {
if (typeof name === 'function') { // fn
fn = name;
Expand Down
2 changes: 1 addition & 1 deletion lib/extend/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class Helper {
* @param {String} name - The name of the helper plugin
* @param {StoreFunction} fn - The helper plugin function
*/
register(name: string, fn: StoreFunction) {
register(name: string, fn: StoreFunction): void {
if (!name) throw new TypeError('name is required');
if (typeof fn !== 'function') throw new TypeError('fn must be a function');

Expand Down
14 changes: 7 additions & 7 deletions lib/extend/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ class Injector {
this.cache = new Cache();
}

list() {
list(): Store {
return this.store;
}

get(entry: Entry, to = 'default') {
get(entry: Entry, to = 'default'): any[] {
return Array.from(this.store[entry][to] || []);
}

getText(entry: Entry, to = 'default') {
getText(entry: Entry, to = 'default'): string {
const arr = this.get(entry, to);
if (!arr || !arr.length) return '';
return arr.join('');
Expand All @@ -42,7 +42,7 @@ class Injector {
return this.cache.apply(`${entry}-size`, Object.keys(this.store[entry]).length);
}

register(entry: Entry, value: string | (() => string), to = 'default') {
register(entry: Entry, value: string | (() => string), to = 'default'): void {
if (!entry) throw new TypeError('entry is required');
if (typeof value === 'function') value = value();

Expand All @@ -52,7 +52,7 @@ class Injector {
entryMap[to] = valueSet;
}

_getPageType(pageLocals) {
_getPageType(pageLocals): string {
let currentType = 'default';
if (pageLocals.__index) currentType = 'home';
if (pageLocals.__post) currentType = 'post';
Expand All @@ -65,7 +65,7 @@ class Injector {
return currentType;
}

_injector(input, pattern, flag, isBegin = true, currentType) {
_injector(input: string, pattern: string | RegExp, flag: Entry, isBegin = true, currentType: string): string {
if (input.includes(`hexo injector ${flag}`)) return input;

const code = this.cache.apply(`${flag}-${currentType}-code`, () => {
Expand All @@ -81,7 +81,7 @@ class Injector {
return input.replace(pattern, str => { return isBegin ? str + code : code + str; });
}

exec(data, locals = { page: {} }) {
exec(data: string, locals = { page: {} }): string {
const { page } = locals;
const currentType = this._getPageType(page);

Expand Down
6 changes: 3 additions & 3 deletions lib/extend/migrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ class Migrator {
this.store = {};
}

list() {
list(): Store {
return this.store;
}

get(name: string) {
get(name: string): StoreFunction {
return this.store[name];
}

register(name: string, fn: StoreFunction) {
register(name: string, fn: StoreFunction): void {
if (!name) throw new TypeError('name is required');
if (typeof fn !== 'function') throw new TypeError('fn must be a function');

Expand Down
Loading

0 comments on commit b898f29

Please sign in to comment.