Skip to content

Commit

Permalink
fix(loader): add new load hook for new API design;
Browse files Browse the repository at this point in the history
- Closes #13
  • Loading branch information
lukeed committed Oct 27, 2021
1 parent 221143e commit e44ab69
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
timeout-minutes: 3
strategy:
matrix:
nodejs: [12, 14, 16]
nodejs: [12, 14, 16.11, 16]
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v2
Expand Down
37 changes: 35 additions & 2 deletions src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync } from 'fs';
import { existsSync, promises as fs } from 'fs';
import { fileURLToPath, URL } from 'url';
import * as tsm from './utils.js';

Expand All @@ -22,7 +22,10 @@ type Resolve = (
parentURL?: string;
},
fallback: Resolve
) => Promisable<{ url: string }>;
) => Promisable<{
url: string;
format?: Format;
}>;

type Inspect = (
url: string,
Expand All @@ -36,6 +39,15 @@ type Transform = (
fallback: Transform
) => Promisable<{ source: Source }>;

type Load = (
url: string,
context: { format?: Format },
fallback: Load
) => Promisable<{
format: Format;
source: Source;
}>;

async function toConfig(): Promise<Config> {
let mod = await setup;
mod = mod && mod.default || mod;
Expand Down Expand Up @@ -101,6 +113,27 @@ export const resolve: Resolve = async function (ident, context, fallback) {
return fallback(ident, context, fallback);
}

export const load: Load = async function (uri, context, fallback) {
// note: inline `getFormat`
let options = await toOptions(uri);
if (options == null) return fallback(uri, context, fallback);
let format: Format = options.format === 'cjs' ? 'commonjs' : 'module';

// TODO: decode SAB/U8 correctly
let path = fileURLToPath(uri);
let source = await fs.readFile(path);

// note: inline `transformSource`
esbuild = esbuild || await import('esbuild');
let result = await esbuild.transform(source.toString(), {
...options,
sourcefile: path,
format: format === 'module' ? 'esm' : 'cjs',
});

return { format, source: result.code };
}

/** @deprecated */
export const getFormat: Inspect = async function (uri, context, fallback) {
let options = await toOptions(uri);
Expand Down

0 comments on commit e44ab69

Please sign in to comment.