@tsmodule/tsmodule 10.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- export declare const bannerLog: (msg: string) => void;
2
- /**
3
- * Build TS to JS. This will contain incomplete specifiers like `./foo` which
4
- * could mean many things, all of which is handled by the loader which will
5
- * resolve them for us.
6
- */
7
- export declare const build: ({ files, dev, fast }: {
8
- files?: string;
9
- dev?: boolean;
10
- fast?: boolean;
11
- }) => Promise<void>;
1
+ export declare const bannerLog: (msg: string) => void;
2
+ /**
3
+ * Build TS to JS. This will contain incomplete specifiers like `./foo` which
4
+ * could mean many things, all of which is handled by the loader which will
5
+ * resolve them for us.
6
+ */
7
+ export declare const build: ({ files, dev, fast }: {
8
+ files?: string;
9
+ dev?: boolean;
10
+ fast?: boolean;
11
+ }) => Promise<void>;
@@ -1,3 +1,3 @@
1
- import{build as S}from"esbuild";import{existsSync as F,readFileSync as T,writeFileSync as E}from"fs";import{extname as N,isAbsolute as O,resolve as m}from"path";import p from"chalk";import{env as D}from"process";import h from"fs/promises";import J from"fast-glob";import i from"ora";import{createDebugLogger as P,log as f}from"create-debug-logger";import{isTs as u,isTsxOrJsx as c}from"../../utils/index.js";import{emitTsDeclarations as C}from"./lib/emitTsDeclarations.js";import{getPackageJsonFile as G}from"../../utils/pkgJson.js";import{normalizeImportSpecifiers as j}from"../normalize/index.js";const k=t=>{f(p.bgBlue(p.white(` ${t} `)))},W=async({files:t="src/**/*",dev:r=!1,fast:d=!1})=>{r&&(D.NODE_ENV="development");const s=P(W);s.log("Building",{files:t,dev:r,fast:d}),r||k("Building for production.");const x=await G(),o=process.cwd(),g={absWorkingDir:o,outbase:"src",outdir:"dist",assetNames:"[name].js",logLevel:r?"warning":"error",charset:"utf8",format:"esm",target:"esnext",minify:!r,define:{PACKAGE_JSON:x}},y=m(o,"src"),n=m(o,"dist");if(s.log("Cleaning old output:",{outDir:n}),r&&O(t)){const e=t.replace(y,n).replace(u,".js").replace(c,".js");await h.rm(e,{force:!0})}else await h.rm(n,{force:!0,recursive:!0});console.log();const l=J.sync(t,{cwd:o}).filter(e=>N(e)!==".d.ts").map(e=>m(e)),b=l.filter(e=>u.test(e)).filter(e=>!c.test(e));s.log("Compiling TS files:",{tsFiles:b}),await S({...g,entryPoints:b.filter(e=>!e.endsWith(".d.ts"))}),i("Built TS files.").succeed();const w=l.filter(e=>c.test(e));if(s.log("Compiling TSX files:",{tsxFiles:w}),await S({...g,entryPoints:w.filter(e=>!e.endsWith(".d.ts")),jsxFactory:"createElement",banner:{js:`import { createElement } from "react";
2
- `}}),i("Built TSX files.").succeed(),process.env.NO_REWRITES)return;const B=t.replace(y,n).replace(/^src\//,"dist/").replace(u,".js").replace(c,".js");if(t?await j(B):await j(),i("Normalized import specifiers.").succeed(),console.log(),r||d)return;k("Running post-build setup."),f(`Generating type declarations.
3
- This might take a moment.`),C(l),i(`Generated delcarations for ${l.length} files.`).succeed();let a;F("dist/package.json")?a=JSON.parse(T("dist/package.json","utf-8")):a={},a.type="module",E("dist/package.json",JSON.stringify(a,null,2)),i('Forced "type": "module" in output.').succeed(),f(p.green("Build complete."))};export{k as bannerLog,W as build};
1
+ import{build as w}from"esbuild";import{existsSync as k,readFileSync as x,writeFileSync as F}from"fs";import{extname as O,isAbsolute as B,resolve as p}from"path";import c from"chalk";import{env as h}from"process";import j from"fs/promises";import D from"fast-glob";import o from"ora";import{createDebugLogger as J,log as d}from"create-debug-logger";import{isTs as u,isTsxOrJsx as m}from"../../utils/index.js";import{emitTsDeclarations as P}from"./lib/emitTsDeclarations.js";import{getPackageJsonFile as C}from"../../utils/pkgJson.js";import{normalizeImportSpecifiers as G}from"../normalize/index.js";const E=t=>{d(c.bgBlue(c.white(` ${t} `)))},W=async({files:t="src/**/*",dev:r=!1,fast:f=!1})=>{h.NODE_ENV=r?"development":"production";const s=J(W);s.log("Building",{files:t,dev:r,fast:f}),E(`${c.bold("TS Module")} [${h.NODE_ENV}]`);const N=await C(),i=process.cwd(),g={absWorkingDir:i,outbase:"src",outdir:"dist",assetNames:"[name].js",logLevel:r?"warning":"error",charset:"utf8",format:"esm",target:"esnext",minify:!r,define:{PACKAGE_JSON:N}},b=p(i,"src"),n=p(i,"dist");if(B(t)){const e=t.replace(b,n).replace(u,".js").replace(m,".js");s.log("Cleaning emitted file:",{outfile:e}),await j.rm(e,{force:!0})}else s.log("Cleaning old output:",{outDir:n}),await j.rm(n,{force:!0,recursive:!0});console.log();const l=D.sync(t,{cwd:i}).filter(e=>O(e)!==".d.ts").map(e=>p(e)),y=l.filter(e=>u.test(e)).filter(e=>!m.test(e));s.log("Compiling TS files:",{tsFiles:y}),await w({...g,entryPoints:y.filter(e=>!e.endsWith(".d.ts"))}),o("Built TS files.").succeed();const S=l.filter(e=>m.test(e));if(s.log("Compiling TSX files:",{tsxFiles:S}),await w({...g,entryPoints:S.filter(e=>!e.endsWith(".d.ts")),jsxFactory:"createElement",banner:{js:`import { createElement } from "react";
2
+ `}}),o("Built TSX files.").succeed(),process.env.NO_REWRITES)return;const T=t.replace(b,n).replace(/^(\.\/)?src\//,"dist/").replace(u,".js").replace(m,".js");if(await G(T),o("Normalized import specifiers.").succeed(),console.log(),r||f)return;E("Running post-build setup."),d(`Generating type declarations.
3
+ This might take a moment.`),P(l),o(`Generated delcarations for ${l.length} files.`).succeed();let a;k("dist/package.json")?a=JSON.parse(x("dist/package.json","utf-8")):a={},a.type="module",F("dist/package.json",JSON.stringify(a,null,2)),o('Forced "type": "module" in output.').succeed(),d(c.green("Build complete."))};export{E as bannerLog,W as build};
@@ -1 +1 @@
1
- export declare const emitTsDeclarations: (files: string[]) => void;
1
+ export declare const emitTsDeclarations: (files: string[]) => void;
@@ -1 +1 @@
1
- export declare const create: (name: string) => Promise<void>;
1
+ export declare const create: (name: string) => Promise<void>;
@@ -1 +1 @@
1
- import{fileURLToPath as d,URL as m}from"url";import g from"chalk";import r from"fs/promises";import f from"ora";import{resolve as n}from"path";import{shell as i}from"await-shell";const P=async e=>{const o=process.cwd(),t=f(`Creating new module ${g.blueBright(e)}.`).start(),c=new m("../../../template",import.meta.url);await i(`cp -R ${d(c)} ${n(o,e)}`);const s=n(o,e,"package.json"),l=await r.readFile(s,"utf-8"),a=JSON.parse(l);a.name=e,await r.writeFile(s,JSON.stringify(a,null,2)),t.succeed("Project created."),t.start("Installing dependencies."),process.chdir(e);const p=["@tsmodule/tsmodule"];globalThis.SHELL_OPTIONS={stdio:["ignore","ignore","inherit"]},await i(`yarn add -D ${p.join(" ")}`),t.succeed("Dependencies installed."),t.start("Initializing git."),await i("git init"),t.succeed("Git initialized.")};export{P as create};
1
+ import{fileURLToPath as d,URL as m}from"url";import g from"chalk";import s from"fs/promises";import f from"ora";import{resolve as a}from"path";import{shell as n}from"await-shell";import{copy as u}from"fs-extra";const S=async t=>{const i=process.cwd(),e=f(`Creating new module ${g.blueBright(t)}.`).start(),c=new m("../../../template",import.meta.url);await u(d(c),a(i,t));const o=a(i,t,"package.json"),l=await s.readFile(o,"utf-8"),r=JSON.parse(l);r.name=t,await s.writeFile(o,JSON.stringify(r,null,2)),e.succeed("Project created."),process.chdir(t);const p=["@tsmodule/tsmodule"];globalThis.SHELL_OPTIONS={stdio:["ignore","ignore","inherit"]},e.start("Installing dependencies."),await n(`yarn add -D ${p.join(" ")}`),e.succeed("Dependencies installed."),e.start("Initializing git."),await n("git init"),e.succeed("Git initialized.")};export{S as create};
@@ -1 +1 @@
1
- export declare const dev: () => Promise<void>;
1
+ export declare const dev: () => Promise<void>;
@@ -1,3 +1,3 @@
1
- import{relative as n,resolve as s}from"path";import{build as t}from"../build/index.js";import e from"chalk";import{log as a}from"create-debug-logger";import m from"ora";import{watch as l}from"chokidar";const h=async()=>{const o=process.cwd();await t({dev:!0}),l(s(o,"src")).on("change",async r=>{console.clear();const i=Date.now();await t({dev:!0,files:r});const c=Date.now()-i;m(e.blueBright(`Dev refresh finished in ${e.bold(`${c}ms`)}.`)).succeed(),a(`
2
- `,e.gray(`Built ${n(o,r)}`),`
3
- `,e.blue(new Date().toLocaleString()))})};export{h as dev};
1
+ import{relative as a,resolve as m}from"path";import{build as o}from"../build/index.js";import e from"chalk";import{log as l}from"create-debug-logger";import p from"ora";import{watch as d}from"chokidar";import{shell as f}from"await-shell";const s=()=>{console.clear()},i=r=>{l(`
2
+ `,e.gray(`Built ${e.bold(r)}.`),`
3
+ `,e.blue(new Date().toLocaleString()))},$=async()=>{const r=process.cwd();await f("clear"),s(),await o({dev:!0}),i("src/**/*"),d(m(r,"src"),{persistent:!0}).on("change",async t=>{s();const c=Date.now();await o({dev:!0,files:t});const n=Date.now()-c;p(e.blueBright(`Dev refresh finished in ${e.bold(`${n}ms`)}.`)).succeed(),i(a(r,t))})};export{$ as dev};
@@ -1 +1 @@
1
- export declare const execute: () => void;
1
+ export declare const execute: () => void;
@@ -1,19 +1,19 @@
1
- /**
2
- * @fileoverview
3
- * This module contains the logic for normalizing import specifiers. It must use
4
- * fully-specified filepaths here, since the bootstrap script will compile it
5
- * with esbuild and then use it to normalize emitted output.
6
- */
7
- /**
8
- * Matches a complete import statement, including the import keyword, as well as
9
- * dynamic imports, requires, and export statements.
10
- */
11
- export declare const generateImportPattern: (importSource: string) => RegExp;
12
- /**
13
- * Rewrite an import/export/require statement.
14
- */
15
- export declare const rewriteImportStatement: (importStatement: string, specifierToReplace: string, specifierReplacement: string) => string;
16
- /**
17
- * Rewrite imports in the emitted JS to ESM-compliant paths.
18
- */
19
- export declare const normalizeImportSpecifiers: (files?: string) => Promise<any>;
1
+ /**
2
+ * @fileoverview
3
+ * This module contains the logic for normalizing import specifiers. It must use
4
+ * fully-specified filepaths here, since the bootstrap script will compile it
5
+ * with esbuild and then use it to normalize emitted output.
6
+ */
7
+ /**
8
+ * Matches a complete import statement, including the import keyword, as well as
9
+ * dynamic imports, requires, and export statements.
10
+ */
11
+ export declare const generateImportPattern: (importSource: string) => RegExp;
12
+ /**
13
+ * Rewrite an import/export/require statement.
14
+ */
15
+ export declare const rewriteImportStatement: (importStatement: string, specifierToReplace: string, specifierReplacement: string) => string;
16
+ /**
17
+ * Rewrite imports in the emitted JS to ESM-compliant paths.
18
+ */
19
+ export declare const normalizeImportSpecifiers: (files?: string) => Promise<any>;
@@ -1,13 +1,13 @@
1
- import ts from "typescript";
2
- export declare const TS_CONFIG: ts.CompilerOptions;
3
- export declare const compilerHost: ts.CompilerHost;
4
- interface SpecifierReplacement {
5
- specifierToReplace: string;
6
- specifierReplacement: string;
7
- }
8
- /**
9
- * Get the rewritten specifiers for a given module. Import/export specifiers
10
- * will be resolved ahead-of-time by the TypeScript compiler and returned.
11
- */
12
- export declare const getRewrittenSpecifiers: (modulePath: string) => SpecifierReplacement[];
13
- export {};
1
+ import ts from "typescript";
2
+ export declare const TS_CONFIG: ts.CompilerOptions;
3
+ export declare const compilerHost: ts.CompilerHost;
4
+ interface SpecifierReplacement {
5
+ specifierToReplace: string;
6
+ specifierReplacement: string;
7
+ }
8
+ /**
9
+ * Get the rewritten specifiers for a given module. Import/export specifiers
10
+ * will be resolved ahead-of-time by the TypeScript compiler and returned.
11
+ */
12
+ export declare const getRewrittenSpecifiers: (modulePath: string) => SpecifierReplacement[];
13
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env node
2
- export {};
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
1
  #!/usr/bin/env node
2
- var r="@tsmodule/tsmodule",a="module",m="10.0.0",d="tsmodule/tsmodule",s="TypeScript Module loader and compiler",l="MIT",p={tsmodule:"dist/index.js"},c={".":"./dist/loader/index.js","./*":"./dist/*/index.js","./package.json":"./package.json"},f="dist/types/index.d.ts",u=[{name:"C. Lewis",email:"ctj.lewis@icloud.com",url:"https://ctjlewis.com"}],v=["dist/","template/"],g={node:">=14"},b={bootstrap:"node bootstrap.js",prebuild:"yarn bootstrap",build:"node --no-warnings --loader ./dist/loader/index.js src/index.ts build",lint:"eslint --fix src",prepare:"yarn build -f",prepublishOnly:"yarn build && yarn test",test:"ava --no-worker-threads"},h={"@types/cross-spawn":"^6.0.2","@types/node":"17.0.8","@types/react":"17.0.38","@typescript-eslint/eslint-plugin":"^5.9.1","@typescript-eslint/parser":"^5.9.1",ava:"^4.0.1","await-shell":"^4.1.0",chalk:"^5.0.0",chokidar:"^3.5.3",commander:"^8.3.0","create-debug-logger":"^1.10.1","cross-spawn":"^7.0.3",esbuild:"^0.14.0",eslint:"^8.6.0","fast-glob":"^3.2.10",ora:"^6.0.1",path:"^0.12.7",react:"^17.0.2",typescript:"^4.5.5"},S=["esm","loader","typescript","loader hook","require hook","experimental-loader"],w={files:["test/**/*.test.ts"],extensions:{ts:"module"},nodeArguments:["--no-warnings","--loader=@tsmodule/tsmodule"]},t={name:r,type:a,version:m,repository:d,description:s,license:l,bin:p,exports:c,types:f,contributors:u,files:v,engines:g,scripts:b,dependencies:h,keywords:S,ava:w};import i from"chalk";import{Command as B}from"commander";import{build as T}from"./commands/build/index.js";import{create as y}from"./commands/create/index.js";import{dev as A}from"./commands/dev/index.js";import{execute as C}from"./commands/execute/index.js";import{normalizeImportSpecifiers as E}from"./commands/normalize/index.js";const{version:j}=t,e=new B;e.name(i.bold(i.blueBright("tsmodule"))).description(i.blueBright("A tool for building TypeScript modules.")).version(String(j)),e.command("run",{isDefault:!0}).argument("<file>","The file to run.").option("--d, --dev","Enable development mode").description("Run the given TS program, analogous to `node <file>`.").action(C),e.command("dev").description("Build and watch for changes.").action(A),e.command("build").option("--files <files>","The files to build (default: all)").option("-d, --dev","Build development version").option("-f, --fast","Do not emit type declarations, only transform to JS").description("Builds TS files to output in dist/.").action(T),e.command("create <name>").description("Create a new project.").action(y),e.command("normalize [files]").description(`Rewrites import specifiers in files to ESM-compliant paths.
3
- (default: dist/**/*.js)`).action(async({files:n})=>{await E(n)}),e.parse(process.argv);
2
+ var r="@tsmodule/tsmodule",d="module",m="11.0.0",a="tsmodule/tsmodule",s="TypeScript Module loader and compiler",l="MIT",c={tsmodule:"dist/index.js"},p={".":"./dist/loader/index.js","./*":"./dist/*/index.js","./package.json":"./package.json"},u="dist/types/index.d.ts",f=[{name:"C. Lewis",email:"ctj.lewis@icloud.com",url:"https://ctjlewis.com"}],b=["dist/","template/"],v={node:">=14"},g={bootstrap:"node bootstrap.js",bootload:"node --no-warnings --loader ./dist/loader/index.js src/index.ts build -f",prebuild:"yarn bootstrap && yarn bootload && yarn link -f",build:"tsmodule build",dev:"tsmodule dev",lint:"eslint --fix src",prepare:"yarn build -f",prepublishOnly:"yarn build && yarn test",test:"ava --no-worker-threads"},h={"@types/cross-spawn":"^6.0.2","@types/node":"17.0.8","@types/react":"17.0.38","@typescript-eslint/eslint-plugin":"^5.9.1","@typescript-eslint/parser":"^5.9.1",ava:"^4.0.1","await-shell":"^13.0.0",chalk:"^5.0.0",chokidar:"^3.5.3",commander:"^8.3.0","create-debug-logger":"^1.10.1","cross-spawn":"^7.0.3",esbuild:"^0.14.0",eslint:"^8.6.0","fast-glob":"^3.2.10","fs-extra":"^10.0.0",ora:"^6.0.1",path:"^0.12.7",react:"^17.0.2",typescript:"^4.5.5"},S=["esm","loader","typescript","loader hook","require hook","experimental-loader"],w={timeout:"10 minutes",files:["test/**/*.test.ts"],extensions:{ts:"module"},nodeArguments:["--no-warnings","--loader=@tsmodule/tsmodule"]},T={"@types/fs-extra":"^9.0.13"},t={name:r,type:d,version:m,repository:a,description:s,license:l,bin:c,exports:p,types:u,contributors:f,files:b,engines:v,scripts:g,dependencies:h,keywords:S,ava:w,devDependencies:T};import e from"chalk";import{Command as y}from"commander";import{build as B}from"./commands/build/index.js";import{create as A}from"./commands/create/index.js";import{dev as C}from"./commands/dev/index.js";import{execute as E}from"./commands/execute/index.js";import{normalizeImportSpecifiers as R}from"./commands/normalize/index.js";const{version:j}=t,i=new y;i.name(e.white(e.bold("tsmodule"))).usage(e.white(e.bold("<file | command> [options]"))).description(e.blueBright(`A tool for building TypeScript modules.
3
+
4
+ Run TS directly: ${e.bold("tsmodule src/index.ts")}
5
+ Use a command: ${e.bold("tsmodule build")}`)).version(String(j)),i.command("dev").description("Build and watch for changes.").action(C),i.command("build").option("--files <files>","The files to build (default: all)").option("-d, --dev","Build development version").option("-f, --fast","Do not emit type declarations, only transform to JS").description("Builds TS files to output in dist/.").action(B),i.command("create <name>").description("Create a new project.").action(A),i.command("normalize [files]").description(`Rewrites import specifiers in files to ESM-compliant paths.
6
+ (default: dist/**/*.js)`).action(async({files:n})=>{await R(n)}),i.command("run",{isDefault:!0}).argument("<file>","The file to run.").option("--d, --dev","Enable development mode").description("Run the given TS program, analogous to `node <file>`.").action(E),i.parse(process.argv);
@@ -1,11 +1,11 @@
1
- import type { GetFormatHook as ModuleGetFormatHook, LoadHook as ModuleLoadHook, ResolveHook as ModuleResolveHook, TransformHook as ModuleTransformSourceHook } from "./types";
2
- export declare const resolve: ModuleResolveHook;
3
- export declare const load: ModuleLoadHook;
4
- /**
5
- * @deprecated As of Node 17.
6
- */
7
- export declare const getFormat: ModuleGetFormatHook;
8
- /**
9
- * @deprecated As of Node 17.
10
- */
11
- export declare const transformSource: ModuleTransformSourceHook;
1
+ import type { GetFormatHook as ModuleGetFormatHook, LoadHook as ModuleLoadHook, ResolveHook as ModuleResolveHook, TransformHook as ModuleTransformSourceHook } from "./types";
2
+ export declare const resolve: ModuleResolveHook;
3
+ export declare const load: ModuleLoadHook;
4
+ /**
5
+ * @deprecated As of Node 17.
6
+ */
7
+ export declare const getFormat: ModuleGetFormatHook;
8
+ /**
9
+ * @deprecated As of Node 17.
10
+ */
11
+ export declare const transformSource: ModuleTransformSourceHook;
@@ -1 +1 @@
1
- import{extname as m,isAbsolute as U,join as E,normalize as w,resolve as S}from"path";import{fileURLToPath as H,pathToFileURL as v,URL as L}from"url";import{promises as G}from"fs";import{transform as h}from"esbuild";import{posix as M}from"path";import{win32 as T}from"path";import{checkExtensions as k,checkTsExtensions as D,fileExists as b,isJs as N,isTs as P,MODULE_LOADERS as R}from"../utils/index.js";import{getPackageJsonFile as y}from"../utils/pkgJson.js";import{createDebugLogger as c}from"create-debug-logger";const F=await y(),A=async(o,r,t)=>{const{parentURL:s}=r,e=c(A);if(e.log("Resolving specifier:",{importedFromURL:s,specifier:o}),!o.startsWith(".")&&!U(o))return e.log("Using defaultResolve for named module:",{specifier:o}),t(o,r,t);const{href:l}=v(process.cwd()),{href:i}=new L(s||l);e.log("Finding import URL for",{specifier:o,baseURL:i});let n=o;o.startsWith("file://")||(U(o)?(e.log("Setting import URL to absolute specifier."),n=v(S(w(o))).href):(e.log("Setting import URL relative to baseURL."),n=new L(o,i).href),e.log("Resolved import URL:",{importedFileURL:n,importedFromURL:s}));const f=m(s??"").toLowerCase(),d=m(n).toLowerCase();if(e.log("Rewriting file extension:",{parentExtension:f,specifierExtension:d}),d){const a=n.substring(0,n.lastIndexOf(d));if(e.log("Re-resolving specifier:",{unresolvedSpecifier:a}),N.test(d)&&P.test(f)){const p=D(a);if(p)return e.log("Found JS import in TS:",{unresolvedSpecifier:a,resolvedTsSourceFile:p}),{url:p}}return b(a)?(e.log("Found file at unresolved specifier:",{unresolvedSpecifier:a}),{url:a}):t(o,r,t)}e.log("Resolving incomplete URL import to file:",{specifier:o});const g=k(n);if(g)return e.log("Resolved import URL to file:",{resolvedFile:g}),{url:g};const x=new L(E(n,"index")).href,u=k(x);return u?(e.log("Resolved import URL to index file:",{resolvedIndexFile:u}),{url:u}):t(o,r,t)},J=async(o,r,t)=>{const s=c(J);if(s.log("Loading source file:",{url:o}),!o.includes(T.sep)&&!o.includes(M.sep))return s.log("Using defaultLoad for named module:",{url:o}),t(o,r,t);const e=m(o),l=R[e];if(!l)return s.log("No loader found, using defaultLoad:",{url:o}),t(o,r,t);const i=H(o),n=await G.readFile(i),f=await h(n.toString(),{...l,sourcefile:i,format:"esm",define:{PACKAGE_JSON:F}});return{format:"module",source:f.code}},O=async(o,r,t)=>{const s=c(O);s.log("Getting format for source file:",{url:o});const e=m(o);return R[e]?{format:"module"}:(s.log("No loader found, using default format:",{url:o}),t(o,r,t))},B=async(o,r,t)=>{const s=c(B);s.log("Transforming source from context:",{context:r});const{url:e}=r,l=m(e),i=R[l];return i?{source:(await h(o.toString(),{...i,logLevel:"info",charset:"utf8",target:"esnext",sourcefile:r.url,format:r.format==="module"?"esm":"cjs",define:{PACKAGE_JSON:F}})).code}:(s.log("No loader found, using default transformer:",{url:e}),t(o,r,t))};export{O as getFormat,J as load,A as resolve,B as transformSource};
1
+ import{extname as m,isAbsolute as U,join as E,normalize as w,resolve as S}from"path";import{fileURLToPath as H,pathToFileURL as v,URL as L}from"url";import{createDebugLogger as c}from"create-debug-logger";import{promises as G}from"fs";import{transform as h}from"esbuild";import{posix as M}from"path";import{win32 as T}from"path";import{checkExtensions as k,checkTsExtensions as D,fileExists as b,isJs as N,isTs as P,MODULE_LOADERS as R}from"../utils/index.js";import{getPackageJsonFile as y}from"../utils/pkgJson.js";const F=await y(),A=async(o,r,t)=>{const{parentURL:s}=r,e=c(A);if(e.log("Resolving specifier:",{importedFromURL:s,specifier:o}),!o.startsWith(".")&&!U(o))return e.log("Using defaultResolve for named module:",{specifier:o}),t(o,r,t);const{href:l}=v(process.cwd()),{href:i}=new L(s||l);e.log("Finding import URL for",{specifier:o,baseURL:i});let n=o;o.startsWith("file://")||(U(o)?(e.log("Setting import URL to absolute specifier."),n=v(S(w(o))).href):(e.log("Setting import URL relative to baseURL."),n=new L(o,i).href),e.log("Resolved import URL:",{importedFileURL:n,importedFromURL:s}));const f=m(s??"").toLowerCase(),d=m(n).toLowerCase();if(e.log("Rewriting file extension:",{parentExtension:f,specifierExtension:d}),d){const a=n.substring(0,n.lastIndexOf(d));if(e.log("Re-resolving specifier:",{unresolvedSpecifier:a}),N.test(d)&&P.test(f)){const p=D(a);if(p)return e.log("Found JS import in TS:",{unresolvedSpecifier:a,resolvedTsSourceFile:p}),{url:p}}return b(a)?(e.log("Found file at unresolved specifier:",{unresolvedSpecifier:a}),{url:a}):t(o,r,t)}e.log("Resolving incomplete URL import to file:",{specifier:o});const g=k(n);if(g)return e.log("Resolved import URL to file:",{resolvedFile:g}),{url:g};const x=new L(E(n,"index")).href,u=k(x);return u?(e.log("Resolved import URL to index file:",{resolvedIndexFile:u}),{url:u}):t(o,r,t)},J=async(o,r,t)=>{const s=c(J);if(s.log("Loading source file:",{url:o}),!o.includes(T.sep)&&!o.includes(M.sep))return s.log("Using defaultLoad for named module:",{url:o}),t(o,r,t);const e=m(o),l=R[e];if(!l)return s.log("No loader found, using defaultLoad:",{url:o}),t(o,r,t);const i=H(o),n=await G.readFile(i),f=await h(n.toString(),{...l,sourcefile:i,format:"esm",define:{PACKAGE_JSON:F}});return{format:"module",source:f.code}},O=async(o,r,t)=>{const s=c(O);s.log("Getting format for source file:",{url:o});const e=m(o);return R[e]?{format:"module"}:(s.log("No loader found, using default format:",{url:o}),t(o,r,t))},B=async(o,r,t)=>{const s=c(B);s.log("Transforming source from context:",{context:r});const{url:e}=r,l=m(e),i=R[l];return i?{source:(await h(o.toString(),{...i,logLevel:"info",charset:"utf8",target:"esnext",sourcefile:r.url,format:r.format==="module"?"esm":"cjs",define:{PACKAGE_JSON:F}})).code}:(s.log("No loader found, using default transformer:",{url:e}),t(o,r,t))};export{O as getFormat,J as load,A as resolve,B as transformSource};
@@ -1,22 +1,22 @@
1
- export declare type Promisable<T> = Promise<T> | T;
2
- export declare type ModuleSource = string | SharedArrayBuffer | Uint8Array;
3
- export declare type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm";
4
- export declare type ResolveHook = (specifier: string, context: {
5
- conditions: string[];
6
- parentURL?: string;
7
- }, fallback: ResolveHook) => Promisable<{
8
- url: string;
9
- format?: ModuleFormat;
10
- }>;
11
- export declare type GetFormatHook = (url: string, context: object, fallback: GetFormatHook) => Promisable<{
12
- format: ModuleFormat;
13
- }>;
14
- export declare type TransformHook = (source: ModuleSource, context: Record<"url" | "format", string>, fallback: TransformHook) => Promisable<{
15
- source: ModuleSource;
16
- }>;
17
- export declare type LoadHook = (url: string, context: {
18
- format?: ModuleFormat;
19
- }, fallback: LoadHook) => Promisable<{
20
- format: ModuleFormat;
21
- source: ModuleSource;
22
- }>;
1
+ export declare type Promisable<T> = Promise<T> | T;
2
+ export declare type ModuleSource = string | SharedArrayBuffer | Uint8Array;
3
+ export declare type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm";
4
+ export declare type ResolveHook = (specifier: string, context: {
5
+ conditions: string[];
6
+ parentURL?: string;
7
+ }, fallback: ResolveHook) => Promisable<{
8
+ url: string;
9
+ format?: ModuleFormat;
10
+ }>;
11
+ export declare type GetFormatHook = (url: string, context: object, fallback: GetFormatHook) => Promisable<{
12
+ format: ModuleFormat;
13
+ }>;
14
+ export declare type TransformHook = (source: ModuleSource, context: Record<"url" | "format", string>, fallback: TransformHook) => Promisable<{
15
+ source: ModuleSource;
16
+ }>;
17
+ export declare type LoadHook = (url: string, context: {
18
+ format?: ModuleFormat;
19
+ }, fallback: LoadHook) => Promisable<{
20
+ format: ModuleFormat;
21
+ source: ModuleSource;
22
+ }>;
@@ -1,4 +1,4 @@
1
- declare global {
2
- const PACKAGE_JSON: Record<string, unknown>;
3
- }
4
- export * from "../loader/types";
1
+ declare global {
2
+ const PACKAGE_JSON: Record<string, unknown>;
3
+ }
4
+ export * from "../loader/types";
@@ -1,27 +1,27 @@
1
- export declare const DEVELOPMENT_MODE: boolean;
2
- export declare const isTs: RegExp;
3
- export declare const isJs: RegExp;
4
- export declare const isTsxOrJsx: RegExp;
5
- export declare const BASE_CONFIG: {
6
- format: string;
7
- charset: string;
8
- sourcemap: string;
9
- target: string;
10
- minify: boolean;
11
- };
12
- export declare type ModuleLoaders = {
13
- [extension: string]: {
14
- [configKey: string]: unknown;
15
- };
16
- };
17
- export declare const MODULE_LOADERS: ModuleLoaders;
18
- export declare const POSSIBLE_EXTENSIONS: string[];
19
- /**
20
- * Force a Unix-like path.
21
- */
22
- export declare const normalizeSpecifier: (specifier: string) => string;
23
- export declare const fileExists: (fileUrl: string) => string | void;
24
- export declare const fileExistsAny: (fileUrls: string[]) => string | void;
25
- export declare const checkTsExtensions: (specifier: string) => string | void;
26
- export declare const checkJsExtension: (specifier: string) => string | void;
27
- export declare const checkExtensions: (specifier: string) => string;
1
+ export declare const DEVELOPMENT_MODE: boolean;
2
+ export declare const isTs: RegExp;
3
+ export declare const isJs: RegExp;
4
+ export declare const isTsxOrJsx: RegExp;
5
+ export declare const BASE_CONFIG: {
6
+ format: string;
7
+ charset: string;
8
+ sourcemap: string;
9
+ target: string;
10
+ minify: boolean;
11
+ };
12
+ export declare type ModuleLoaders = {
13
+ [extension: string]: {
14
+ [configKey: string]: unknown;
15
+ };
16
+ };
17
+ export declare const MODULE_LOADERS: ModuleLoaders;
18
+ export declare const POSSIBLE_EXTENSIONS: string[];
19
+ /**
20
+ * Force a Unix-like path.
21
+ */
22
+ export declare const normalizeSpecifier: (specifier: string) => string;
23
+ export declare const fileExists: (fileUrl: string) => string | void;
24
+ export declare const fileExistsAny: (fileUrls: string[]) => string | void;
25
+ export declare const checkTsExtensions: (specifier: string) => string | void;
26
+ export declare const checkJsExtension: (specifier: string) => string | void;
27
+ export declare const checkExtensions: (specifier: string) => string;
@@ -1 +1 @@
1
- export declare const getPackageJsonFile: () => Promise<string>;
1
+ export declare const getPackageJsonFile: () => Promise<string>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tsmodule/tsmodule",
3
3
  "type": "module",
4
- "version": "10.0.0",
4
+ "version": "11.0.0",
5
5
  "repository": "tsmodule/tsmodule",
6
6
  "description": "TypeScript Module loader and compiler",
7
7
  "license": "MIT",
@@ -30,8 +30,10 @@
30
30
  },
31
31
  "scripts": {
32
32
  "bootstrap": "node bootstrap.js",
33
- "prebuild": "yarn bootstrap",
34
- "build": "node --no-warnings --loader ./dist/loader/index.js src/index.ts build",
33
+ "bootload": "node --no-warnings --loader ./dist/loader/index.js src/index.ts build -f",
34
+ "prebuild": "yarn bootstrap && yarn bootload && yarn link -f",
35
+ "build": "tsmodule build",
36
+ "dev": "tsmodule dev",
35
37
  "lint": "eslint --fix src",
36
38
  "prepare": "yarn build -f",
37
39
  "prepublishOnly": "yarn build && yarn test",
@@ -44,7 +46,7 @@
44
46
  "@typescript-eslint/eslint-plugin": "^5.9.1",
45
47
  "@typescript-eslint/parser": "^5.9.1",
46
48
  "ava": "^4.0.1",
47
- "await-shell": "^4.1.0",
49
+ "await-shell": "^13.0.0",
48
50
  "chalk": "^5.0.0",
49
51
  "chokidar": "^3.5.3",
50
52
  "commander": "^8.3.0",
@@ -53,6 +55,7 @@
53
55
  "esbuild": "^0.14.0",
54
56
  "eslint": "^8.6.0",
55
57
  "fast-glob": "^3.2.10",
58
+ "fs-extra": "^10.0.0",
56
59
  "ora": "^6.0.1",
57
60
  "path": "^0.12.7",
58
61
  "react": "^17.0.2",
@@ -67,6 +70,7 @@
67
70
  "experimental-loader"
68
71
  ],
69
72
  "ava": {
73
+ "timeout": "10 minutes",
70
74
  "files": [
71
75
  "test/**/*.test.ts"
72
76
  ],
@@ -77,5 +81,8 @@
77
81
  "--no-warnings",
78
82
  "--loader=@tsmodule/tsmodule"
79
83
  ]
84
+ },
85
+ "devDependencies": {
86
+ "@types/fs-extra": "^9.0.13"
80
87
  }
81
88
  }
@@ -10,12 +10,12 @@ on:
10
10
 
11
11
  jobs:
12
12
  test:
13
- name: Node.js v${{ matrix.nodejs }} (${{ matrix.os }})
13
+ name: Node ${{ matrix.nodejs }} on ${{ matrix.os }}
14
14
  runs-on: ${{ matrix.os }}
15
- timeout-minutes: 5
15
+ timeout-minutes: 10
16
16
  strategy:
17
17
  matrix:
18
- nodejs: [16]
18
+ nodejs: [14, 16, "lts/*"]
19
19
  os: [ubuntu-latest, windows-latest, macos-latest]
20
20
  steps:
21
21
  - uses: actions/checkout@v2
@@ -18,6 +18,7 @@
18
18
  "lint": "eslint src --fix"
19
19
  },
20
20
  "ava": {
21
+ "timout": 240000,
21
22
  "files": [
22
23
  "test/**/*.test.ts"
23
24
  ],
File without changes