Skip to content

Commit

Permalink
feat: enhance loader api + fix esm build
Browse files Browse the repository at this point in the history
  • Loading branch information
tada5hi committed Nov 29, 2022
1 parent d4e2750 commit 253ea59
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 178 deletions.
176 changes: 62 additions & 114 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@semantic-release/release-notes-generator": "^10.0.3",
"@tada5hi/eslint-config-typescript": "^1.0.10",
"@types/glob": "^8.0.0",
"@types/is-file-esm": "^1.0.0",
"@types/jest": "^27.5.0",
"@types/node": "^18.11.9",
"@types/yargs": "^17.0.14",
Expand All @@ -71,7 +72,8 @@
"typescript": "^4.9.3"
},
"dependencies": {
"glob": "^8.0.3"
"glob": "^8.0.3",
"is-file-esm": "^1.0.0"
},
"config": {
"commitizen": {
Expand Down
10 changes: 8 additions & 2 deletions src/loader/file-type/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,13 @@
*/

import fs from 'fs';
import { LocatorInfo } from '../../locator';
import { handleFileLoadError } from '../../utils';
import { buildLoaderFilePath } from '../utils';

export async function loadJsonFile(info: LocatorInfo) : Promise<unknown | undefined> {
const filePath = buildLoaderFilePath(info, true);

export async function loadJsonFile(filePath: string) : Promise<unknown | undefined> {
try {
const file = await fs.promises.readFile(filePath);
return JSON.parse(file.toString('utf-8'));
Expand All @@ -17,7 +21,9 @@ export async function loadJsonFile(filePath: string) : Promise<unknown | undefin
}
}

export function loadJsonFileSync(filePath: string) : unknown | undefined {
export function loadJsonFileSync(info: LocatorInfo) : unknown | undefined {
const filePath = buildLoaderFilePath(info, true);

try {
const file = fs.readFileSync(filePath);
return JSON.parse(file.toString('utf-8'));
Expand Down
37 changes: 26 additions & 11 deletions src/loader/file-type/script/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,38 @@
* view the LICENSE file that was distributed with this source code.
*/

import isFileEsm from 'is-file-esm';
import { pathToFileURL } from 'url';
import { getExportItem } from './utils';
import { LoaderFilterFn, ScriptFileExportItem } from './type';
import { LocatorInfo, isLocatorInfo } from '../../../locator';
import { LocatorInfo, pathToLocatorInfo } from '../../../locator';
import { buildLoaderFilePath } from '../../utils';
import { handleFileLoadError } from '../../../utils';

export async function loadScriptFile(data: LocatorInfo | string) : Promise<unknown | undefined> {
const filePath = isLocatorInfo(data) ?
buildLoaderFilePath(data) :
data;
let locatorInfo : LocatorInfo;
let filePath : string;

if (typeof data === 'string') {
filePath = data;
locatorInfo = pathToLocatorInfo(data);
} else {
filePath = buildLoaderFilePath(data, true);
locatorInfo = data;
}

try {
if (['.js', '.mjs', '.cjs'].indexOf(locatorInfo.extension) !== -1) {
const check = await isFileEsm(filePath);
/* istanbul ignore next */
if (check.esm) {
return await import(pathToFileURL(filePath).href);
}
}

return await import(filePath);
} catch (e) {
/* istanbul ignore next */
return handleFileLoadError(e);
}
}
Expand All @@ -27,18 +45,15 @@ export async function loadScriptFileExport(
data: LocatorInfo | string,
filterFn?: LoaderFilterFn,
) : Promise<ScriptFileExportItem | undefined> {
const filePath = isLocatorInfo(data) ?
buildLoaderFilePath(data) :
data;

try {
const data = await loadScriptFile(filePath);
if (typeof data === 'object') {
return getExportItem(data, filterFn);
const output = await loadScriptFile(data);
if (typeof output === 'object') {
return getExportItem(output, filterFn);
}

return undefined;
} catch (e) {
/* istanbul ignore next */
return handleFileLoadError(e);
}
}
38 changes: 25 additions & 13 deletions src/loader/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,48 @@
* view the LICENSE file that was distributed with this source code.
*/

import { LocatorInfo } from '../locator';
import { LocatorInfo, pathToLocatorInfo } from '../locator';
import {
loadJsonFile, loadJsonFileSync, loadScriptFile, loadScriptFileSync,
loadJsonFile,
loadJsonFileSync,
loadScriptFile,
loadScriptFileSync,
} from './file-type';
import { buildLoaderFilePath } from './utils';

export async function loadFile(info: LocatorInfo) : Promise<unknown | undefined> {
if (!info) {
export async function loadFile(input: LocatorInfo | string) : Promise<unknown | undefined> {
if (!input) {
return undefined;
}

const filePath = buildLoaderFilePath(info);
let info : LocatorInfo;
if (typeof input === 'string') {
info = pathToLocatorInfo(input);
} else {
info = input;
}

if (info.extension === '.json') {
return loadJsonFile(filePath);
return loadJsonFile(info);
}

return loadScriptFile(filePath);
return loadScriptFile(info);
}

export function loadFileSync(info: LocatorInfo) : unknown | undefined {
if (!info) {
export function loadFileSync(input: LocatorInfo | string) : unknown | undefined {
if (!input) {
return undefined;
}

const filePath = buildLoaderFilePath(info);
let info : LocatorInfo;
if (typeof input === 'string') {
info = pathToLocatorInfo(input);
} else {
info = input;
}

if (info.extension === '.json') {
return loadJsonFileSync(filePath);
return loadJsonFileSync(info);
}

return loadScriptFileSync(filePath);
return loadScriptFileSync(info);
}
9 changes: 6 additions & 3 deletions src/loader/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
import path from 'path';
import { LocatorInfo } from '../locator';

export function buildLoaderFilePath(info: LocatorInfo) {
return path.join(info.path, info.name) +
(info.extension === '.json' ? '.json' : '');
export function buildLoaderFilePath(info: LocatorInfo, withExtension?: boolean) {
if (withExtension) {
return path.join(info.path, info.name) + info.extension;
}

return path.join(info.path, info.name);
}
19 changes: 3 additions & 16 deletions src/locator/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
*/

import { glob } from 'glob';
import path from 'path';
import { promisify } from 'util';
import { LocatorInfo, LocatorOptions } from './type';
import { buildLocatorOptions } from './utils';
import { buildLocatorOptions, pathToLocatorInfo } from './utils';

const globAsync = promisify(glob);

Expand All @@ -35,13 +34,7 @@ export async function locateFiles(
});

for (let k = 0; k < files.length; k++) {
const fileInfo = path.parse(files[k]);

items.push({
path: fileInfo.dir.split('/').join(path.sep),
name: fileInfo.name,
extension: fileInfo.ext,
});
items.push(pathToLocatorInfo(files[k], true));
}
}
}
Expand Down Expand Up @@ -70,13 +63,7 @@ export async function locateFile(

const element = files.shift();
if (element) {
const fileInfo = path.parse(element);

return {
path: fileInfo.dir.split('/').join(path.sep),
name: fileInfo.name,
extension: fileInfo.ext,
};
return pathToLocatorInfo(element, true);
}
}
}
Expand Down
19 changes: 3 additions & 16 deletions src/locator/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
*/

import { sync as globSync } from 'glob';
import path from 'path';
import { LocatorInfo, LocatorOptions } from './type';
import { buildLocatorOptions } from './utils';
import { buildLocatorOptions, pathToLocatorInfo } from './utils';

export function locateFilesSync(
pattern: string | string[],
Expand All @@ -32,13 +31,7 @@ export function locateFilesSync(
});

for (let k = 0; k < files.length; k++) {
const fileInfo = path.parse(files[k]);

items.push({
path: fileInfo.dir.split('/').join(path.sep),
name: fileInfo.name,
extension: fileInfo.ext,
});
items.push(pathToLocatorInfo(files[k], true));
}
}
}
Expand Down Expand Up @@ -67,13 +60,7 @@ export function locateFileSync(

const element = files.shift();
if (element) {
const fileInfo = path.parse(element);

return {
path: fileInfo.dir.split('/').join(path.sep),
name: fileInfo.name,
extension: fileInfo.ext,
};
return pathToLocatorInfo(element, true);
}
}
}
Expand Down
18 changes: 18 additions & 0 deletions src/locator/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* view the LICENSE file that was distributed with this source code.
*/

import path from 'path';
import { LocatorInfo, LocatorOptions } from './type';
import { hasOwnProperty, toArray } from '../utils';

Expand Down Expand Up @@ -45,3 +46,20 @@ export function isLocatorInfo(data: unknown) : data is LocatorInfo {
return !(!hasOwnProperty(data, 'extension') ||
typeof data.extension !== 'string');
}

export function pathToLocatorInfo(
input: string,
skipResolve?: boolean,
) : LocatorInfo {
if (!skipResolve && !path.isAbsolute(input)) {
input = path.resolve(process.cwd(), input);
}

const info = path.parse(input);

return {
path: info.dir.split('/').join(path.sep),
name: info.name,
extension: info.ext,
};
}
20 changes: 19 additions & 1 deletion test/unit/loader.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@


import path from "path";
import {loadScriptFileExport, loadScriptFileExportSync, locateFile, locateFileSync} from "../../src";
import {
buildLoaderFilePath, loadScriptFile,
loadScriptFileExport,
loadScriptFileExportSync, loadScriptFileSync,
locateFile,
locateFileSync
} from "../../src";
import {loadFile, loadFileSync} from "../../src";

const basePath = path.join(__dirname, '..', 'data');
Expand All @@ -20,11 +26,17 @@ describe('src/loader/**', () => {
expect(loaderContent.default).toBeDefined();
expect(loaderContent.foo).toEqual('bar');

loaderContent = await loadFile(buildLoaderFilePath(locatorInfo));
expect(loaderContent).toBeDefined();

loaderContent = await loadScriptFileExport(locatorInfo);
expect(loaderContent).toBeDefined();
expect(loaderContent.key).toEqual('default');
expect(loaderContent.value).toEqual({foo: 'bar'});

loaderContent = await loadScriptFile(buildLoaderFilePath(locatorInfo));
expect(loaderContent).toBeDefined();

// --------------------------------------------------------------------

locatorInfo = locateFileSync( 'file.js', {path: [basePath]});
Expand All @@ -33,10 +45,16 @@ describe('src/loader/**', () => {
expect(loaderContent.default).toBeUndefined();
expect(loaderContent.foo).toEqual('bar');

loaderContent = loadFileSync(buildLoaderFilePath(locatorInfo));
expect(loaderContent).toBeDefined();

loaderContent = loadScriptFileExportSync(locatorInfo);
expect(loaderContent).toBeDefined();
expect(loaderContent.key).toEqual('default');
expect(loaderContent.value).toEqual({foo: 'bar'});

loaderContent = loadScriptFileSync(buildLoaderFilePath(locatorInfo));
expect(loaderContent).toBeDefined();
});

it('should load .ts file', async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/unit/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* view the LICENSE file that was distributed with this source code.
*/

import { removeFileNameExtension } from "../../src/utils";
import { removeFileNameExtension } from "../../src";

describe('src/utils/*.ts', function () {
it('should remove file name extension', () => {
Expand Down

0 comments on commit 253ea59

Please sign in to comment.