@poppinss/ts-exec 1.1.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.
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ # The MIT License
2
+
3
+ Copyright (c) 2023
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # ts-exec
2
+
3
+ <br />
4
+
5
+ [![gh-workflow-image]][gh-workflow-url] [![npm-image]][npm-url] ![][typescript-image] [![license-image]][license-url]
6
+
7
+ ## Introduction
8
+
9
+ ## Official Documentation
10
+
11
+ ## Contributing
12
+
13
+ One of the primary goals of <org> is to have a vibrant community of users and contributors who believes in the principles of the framework.
14
+
15
+ We encourage you to read the [contribution guide](https://github.com/<org>/.github/blob/main/docs/CONTRIBUTING.md) before contributing to the framework.
16
+
17
+ ## Code of Conduct
18
+
19
+ In order to ensure that the <org> community is welcoming to all, please review and abide by the [Code of Conduct](https://github.com/<org>/.github/blob/main/docs/CODE_OF_CONDUCT.md).
20
+
21
+ ## License
22
+
23
+ <pkg-name> is open-sourced software licensed under the [MIT license](LICENSE.md).
24
+
25
+ [gh-workflow-image]: https://img.shields.io/github/actions/workflow/status/<org>/<repo>/checks.yml?style=for-the-badge
26
+ [gh-workflow-url]: https://github.com/<org>/<repo>/actions/workflows/checks.yml 'Github action'
27
+ [typescript-image]: https://img.shields.io/badge/Typescript-294E80.svg?style=for-the-badge&logo=typescript
28
+ [typescript-url]: "typescript"
29
+ [npm-image]: https://img.shields.io/npm/v/<scope>/<repo>.svg?style=for-the-badge&logo=npm
30
+ [npm-url]: https://npmjs.org/package/<scope>/<repo> 'npm'
31
+ [license-image]: https://img.shields.io/npm/l/<scope>/<repo>?color=blueviolet&style=for-the-badge
32
+ [license-url]: LICENSE.md 'license'
@@ -0,0 +1 @@
1
+ export {};
package/build/index.js ADDED
@@ -0,0 +1,3 @@
1
+ // index.ts
2
+ import { register } from "node:module";
3
+ register("./src/loader.js", import.meta.url);
@@ -0,0 +1,2 @@
1
+ declare const _default: import("util").DebugLogger;
2
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import type { Config as SWCConfig } from '@swc/core';
2
+ import { type TsConfigJsonResolved } from 'get-tsconfig';
3
+ /**
4
+ * Returns the TSConfig and the SWC config by searching for the "tsconfig.json"
5
+ * file in the provided search path
6
+ */
7
+ export declare function getConfig(searchPath: string | URL): {
8
+ tsConfig: TsConfigJsonResolved | null;
9
+ tsConfigPath: string | null;
10
+ swcConfig: SWCConfig;
11
+ };
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Returns the contents of the package.json file
3
+ */
4
+ export declare function getPackageJson(searchPath: string | URL): Promise<any>;
@@ -0,0 +1,20 @@
1
+ import type { LoadHook, ResolveHook } from 'node:module';
2
+ /**
3
+ * Initialize hook to load different config files
4
+ */
5
+ export declare function initialize(): Promise<void>;
6
+ /**
7
+ * Resolve hook to rewrite ".js" imports to ".ts" file only when
8
+ * "allowArbitraryExtensions" is not enabled. Otherwise, we expect
9
+ * the user to always specify the accurate file extensions and we
10
+ * won't check for file existence on the disk, since that may
11
+ * lead to many false positives.
12
+ *
13
+ * For example, someone registers a loader to import files from Github and
14
+ * our extension rewrite checks for same file on disk, hence it will fail.
15
+ */
16
+ export declare const resolve: ResolveHook;
17
+ /**
18
+ * Load hook to compile TypeScript and JSX files on the fly
19
+ */
20
+ export declare const load: LoadHook;
@@ -0,0 +1,228 @@
1
+ // src/loader.ts
2
+ import { extname } from "node:path";
3
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
4
+ import { resolveImports } from "resolve-pkg-maps";
5
+
6
+ // src/debug.ts
7
+ import { debuglog } from "node:util";
8
+ var debug_default = debuglog("ts-exec");
9
+
10
+ // src/get_config.ts
11
+ import { fileURLToPath } from "node:url";
12
+ import { getTsconfig } from "get-tsconfig";
13
+ var DEFAULT_CONFIG = {
14
+ sourceMaps: true,
15
+ module: {
16
+ type: "es6"
17
+ },
18
+ jsc: {
19
+ target: "esnext",
20
+ externalHelpers: false,
21
+ parser: {
22
+ syntax: "typescript",
23
+ tsx: true,
24
+ decorators: true,
25
+ dynamicImport: true
26
+ },
27
+ transform: {
28
+ decoratorMetadata: true,
29
+ legacyDecorator: true,
30
+ verbatimModuleSyntax: true,
31
+ useDefineForClassFields: true,
32
+ react: {
33
+ runtime: "automatic"
34
+ }
35
+ },
36
+ keepClassNames: true
37
+ }
38
+ };
39
+ function tsConfigToSwcConfig(tsConfig2) {
40
+ const tsTarget = tsConfig2.compilerOptions?.target?.toLowerCase();
41
+ return {
42
+ sourceMaps: tsConfig2.compilerOptions?.sourceMap ?? true,
43
+ module: {
44
+ /**
45
+ * Since, we will run the SWC transformer via Nodejs loader hooks, the
46
+ * entry point will always be ES6
47
+ */
48
+ type: "es6"
49
+ },
50
+ jsc: {
51
+ target: tsTarget ? tsTarget === "es6" ? "esnext" : tsTarget : "esnext",
52
+ baseUrl: tsConfig2.compilerOptions?.baseUrl,
53
+ externalHelpers: false,
54
+ parser: {
55
+ syntax: "typescript",
56
+ tsx: !!tsConfig2.compilerOptions?.jsx,
57
+ decorators: true,
58
+ dynamicImport: true
59
+ },
60
+ transform: {
61
+ decoratorMetadata: tsConfig2.compilerOptions?.emitDecoratorMetadata,
62
+ legacyDecorator: tsConfig2.compilerOptions?.experimentalDecorators,
63
+ verbatimModuleSyntax: tsConfig2.compilerOptions?.verbatimModuleSyntax,
64
+ useDefineForClassFields: tsConfig2.compilerOptions?.useDefineForClassFields,
65
+ react: {
66
+ runtime: "automatic",
67
+ importSource: tsConfig2.compilerOptions?.jsxImportSource
68
+ }
69
+ },
70
+ keepClassNames: true
71
+ }
72
+ };
73
+ }
74
+ function getConfig(searchPath) {
75
+ const tsConfig2 = getTsconfig(
76
+ typeof searchPath === "string" ? searchPath : fileURLToPath(searchPath)
77
+ );
78
+ if (!tsConfig2) {
79
+ debug_default("Unable to locate tsconfig file");
80
+ return {
81
+ tsConfig: null,
82
+ tsConfigPath: null,
83
+ swcConfig: {
84
+ ...DEFAULT_CONFIG
85
+ }
86
+ };
87
+ }
88
+ debug_default("tsConfig %O", tsConfig2.config);
89
+ const swcConfig2 = tsConfigToSwcConfig(tsConfig2.config);
90
+ debug_default("swcConfig %O", swcConfig2);
91
+ return { tsConfig: tsConfig2.config, tsConfigPath: tsConfig2.path, swcConfig: swcConfig2 };
92
+ }
93
+
94
+ // src/transform.ts
95
+ import { transformSync as swcTransform } from "@swc/core";
96
+ function transformSync(source, options) {
97
+ const input = `${source ?? ""}`;
98
+ const { format, ...rest } = options;
99
+ rest.module.type = format === "commonjs-typescript" ? "commonjs" : "es6";
100
+ return swcTransform(input, rest);
101
+ }
102
+
103
+ // src/get_package_json.ts
104
+ import { join } from "node:path";
105
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
106
+ import { readFile } from "node:fs/promises";
107
+ async function getPackageJson(searchPath) {
108
+ try {
109
+ const pkgFile = await readFile(
110
+ join(typeof searchPath === "string" ? searchPath : fileURLToPath2(searchPath), "package.json"),
111
+ "utf-8"
112
+ );
113
+ return JSON.parse(pkgFile);
114
+ } catch (error) {
115
+ if (error.code === "ENOENT") {
116
+ return null;
117
+ }
118
+ throw error;
119
+ }
120
+ }
121
+
122
+ // src/loader.ts
123
+ var swcConfig;
124
+ var tsConfig;
125
+ var subPathImports;
126
+ var UNALLOWED_FILE_EXTENSIONS = [".tsx", ".ts", ".mts", ".cts"];
127
+ function isLocalPath(specifier) {
128
+ return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("file:");
129
+ }
130
+ function wrapAndReThrowSwcError(error) {
131
+ const errorHints = `${error.filename}:${error.startLine}
132
+ ${error.snippet}
133
+ `;
134
+ switch (error.code) {
135
+ case "UnsupportedSyntax": {
136
+ const unsupportedSyntaxError = new Error(error.message);
137
+ unsupportedSyntaxError.name = "UnsupportedSyntaxError";
138
+ unsupportedSyntaxError.stack = `${errorHints}${unsupportedSyntaxError.stack}`;
139
+ throw unsupportedSyntaxError;
140
+ }
141
+ case "InvalidSyntax": {
142
+ const syntaxError = new SyntaxError(error.message);
143
+ syntaxError.stack = `${errorHints}${syntaxError.stack}`;
144
+ throw syntaxError;
145
+ }
146
+ default:
147
+ throw new Error(error.message);
148
+ }
149
+ }
150
+ async function initialize() {
151
+ const searchPath = process.env.TS_EXEC_PWD ?? process.cwd();
152
+ const config = getConfig(searchPath);
153
+ const pkgJSON = await getPackageJson(searchPath);
154
+ swcConfig = config.swcConfig;
155
+ tsConfig = config.tsConfig;
156
+ subPathImports = pkgJSON ? pkgJSON.imports : null;
157
+ }
158
+ var resolve = async (specifier, context, nextResolve) => {
159
+ debug_default("resolving specifier %s", specifier);
160
+ if (specifier.startsWith("#") && subPathImports) {
161
+ debug_default("resolving subpath import %s %O", specifier, subPathImports);
162
+ const resolvedPaths = resolveImports(subPathImports, specifier, context.conditions);
163
+ if (resolvedPaths.length) {
164
+ specifier = resolvedPaths[0];
165
+ }
166
+ }
167
+ const allowArbitraryExtensions = !!tsConfig?.compilerOptions?.allowArbitraryExtensions;
168
+ if (!allowArbitraryExtensions) {
169
+ if (isLocalPath(specifier)) {
170
+ const fileExtension = extname(specifier);
171
+ if (UNALLOWED_FILE_EXTENSIONS.includes(fileExtension) && context.parentURL) {
172
+ throw new Error(`Unknown file extension "${fileExtension}"`);
173
+ }
174
+ if (fileExtension === ".js") {
175
+ specifier = specifier.replace(".js", ".ts");
176
+ } else if (fileExtension === ".mjs") {
177
+ specifier = specifier.replace(".mjs", ".mts");
178
+ } else if (fileExtension === ".cjs") {
179
+ specifier = specifier.replace(".cjs", ".cts");
180
+ } else if (fileExtension === ".jsx") {
181
+ specifier = specifier.replace(".jsx", ".tsx");
182
+ }
183
+ }
184
+ }
185
+ debug_default("resolving file with specifier %s", specifier);
186
+ return nextResolve(specifier, context);
187
+ };
188
+ var load = async function load2(url, context, nextLoad) {
189
+ const { format } = context;
190
+ debug_default("load file %s, %O", url, context);
191
+ if (format && (format === "module-typescript" || format === "commonjs-typescript") || url.endsWith(".tsx") || url.endsWith(".jsx")) {
192
+ try {
193
+ const { source } = await nextLoad(url, {
194
+ ...context,
195
+ format: "module"
196
+ });
197
+ const { code, map } = transformSync(source.toString(), {
198
+ format: format ?? "module-tsx",
199
+ filename: fileURLToPath3(url),
200
+ ...swcConfig
201
+ });
202
+ let output = code;
203
+ if (map) {
204
+ const base64SourceMap = Buffer.from(map).toString("base64");
205
+ output = `${code}
206
+
207
+ //# sourceMappingURL=data:application/json;base64,${base64SourceMap}`;
208
+ }
209
+ return {
210
+ format: format ? format.replace("-typescript", "") : "module",
211
+ source: `${output}
212
+
213
+ //# sourceURL=${url}`
214
+ };
215
+ } catch (error) {
216
+ if (error.code !== void 0) {
217
+ wrapAndReThrowSwcError(error);
218
+ }
219
+ throw error;
220
+ }
221
+ }
222
+ return nextLoad(url, context);
223
+ };
224
+ export {
225
+ initialize,
226
+ load,
227
+ resolve
228
+ };
@@ -0,0 +1,8 @@
1
+ import { Config as SwcConfig } from '@swc/core';
2
+ /**
3
+ * Transforms source code using SWC
4
+ */
5
+ export declare function transformSync(source: string, options: SwcConfig & {
6
+ filename: string;
7
+ format: 'module-typescript' | 'commonjs-typescript' | 'module-tsx';
8
+ }): import("@swc/types").Output;
package/package.json ADDED
@@ -0,0 +1,127 @@
1
+ {
2
+ "name": "@poppinss/ts-exec",
3
+ "description": "",
4
+ "version": "1.1.0",
5
+ "engines": {
6
+ "node": ">=20.6.0"
7
+ },
8
+ "type": "module",
9
+ "files": [
10
+ "build",
11
+ "!build/bin",
12
+ "!build/tests"
13
+ ],
14
+ "main": "build/index.js",
15
+ "exports": {
16
+ ".": "./build/index.js"
17
+ },
18
+ "scripts": {
19
+ "pretest": "npm run lint && npm run build",
20
+ "test": "c8 npm run quick:test",
21
+ "lint": "eslint .",
22
+ "format": "prettier --write .",
23
+ "typecheck": "tsc --noEmit",
24
+ "precompile": "npm run lint",
25
+ "compile": "tsup-node && tsc --emitDeclarationOnly --declaration",
26
+ "build": "npm run compile",
27
+ "version": "npm run build",
28
+ "prepublishOnly": "npm run build",
29
+ "release": "release-it",
30
+ "quick:test": "node --experimental-transform-types --enable-source-maps bin/test.ts"
31
+ },
32
+ "devDependencies": {
33
+ "@adonisjs/eslint-config": "^2.0.0-beta.6",
34
+ "@adonisjs/prettier-config": "^1.4.0",
35
+ "@adonisjs/tsconfig": "^1.4.0",
36
+ "@japa/assert": "^4.0.0",
37
+ "@japa/expect": "^3.0.2",
38
+ "@japa/expect-type": "^2.0.2",
39
+ "@japa/file-system": "^2.3.2",
40
+ "@japa/runner": "^3.1.4",
41
+ "@japa/snapshot": "^2.0.8",
42
+ "@release-it/conventional-changelog": "^9.0.4",
43
+ "@types/node": "^22.10.2",
44
+ "c8": "^10.1.3",
45
+ "eslint": "^9.17.0",
46
+ "ipaddr.js": "^2.2.0",
47
+ "preact": "^10.26.6",
48
+ "preact-render-to-string": "^6.5.13",
49
+ "prettier": "^3.4.2",
50
+ "release-it": "^17.11.0",
51
+ "tsup": "^8.3.5",
52
+ "typescript": "^5.7.2"
53
+ },
54
+ "dependencies": {
55
+ "@swc/core": "^1.11.24",
56
+ "get-tsconfig": "^4.10.0",
57
+ "resolve-pkg-maps": "^1.0.0"
58
+ },
59
+ "homepage": "https://github.com/thetutlage/ts-exec#readme",
60
+ "repository": {
61
+ "type": "git",
62
+ "url": "git+https://github.com/thetutlage/ts-exec.git"
63
+ },
64
+ "bugs": {
65
+ "url": "https://github.com/thetutlage/ts-exec/issues"
66
+ },
67
+ "keywords": [
68
+ "typescript",
69
+ "ts-node",
70
+ "transpiler",
71
+ "tsx"
72
+ ],
73
+ "author": "Harminder Virk <virk@adonisjs.com>",
74
+ "license": "MIT",
75
+ "publishConfig": {
76
+ "access": "public"
77
+ },
78
+ "tsup": {
79
+ "entry": [
80
+ "index.ts",
81
+ "src/loader.ts"
82
+ ],
83
+ "outDir": "./build",
84
+ "clean": true,
85
+ "format": "esm",
86
+ "dts": false,
87
+ "sourcemap": false,
88
+ "target": "esnext"
89
+ },
90
+ "release-it": {
91
+ "git": {
92
+ "requireCleanWorkingDir": true,
93
+ "requireUpstream": true,
94
+ "commitMessage": "chore(release): ${version}",
95
+ "tagAnnotation": "v${version}",
96
+ "push": true,
97
+ "tagName": "v${version}"
98
+ },
99
+ "github": {
100
+ "release": true
101
+ },
102
+ "npm": {
103
+ "publish": true,
104
+ "skipChecks": true
105
+ },
106
+ "plugins": {
107
+ "@release-it/conventional-changelog": {
108
+ "preset": {
109
+ "name": "angular"
110
+ }
111
+ }
112
+ }
113
+ },
114
+ "c8": {
115
+ "reporter": [
116
+ "text",
117
+ "html"
118
+ ],
119
+ "exclude": [
120
+ "tests/**"
121
+ ]
122
+ },
123
+ "prettier": "@adonisjs/prettier-config",
124
+ "volta": {
125
+ "node": "24.0.0"
126
+ }
127
+ }