@travetto/compiler 3.0.0-rc.4 → 3.0.0-rc.7

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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  <!-- This file was generated by @travetto/doc and should not be modified directly -->
2
- <!-- Please modify https://github.com/travetto/travetto/tree/main/module/compiler/doc.ts and execute "npx trv doc" to rebuild -->
2
+ <!-- Please modify https://github.com/travetto/travetto/tree/main/module/compiler/DOC.ts and execute "npx trv doc" to rebuild -->
3
3
  # Compiler
4
- ## Node-integration of Typescript Compiler with advanced functionality for detecting changes in classes and methods.
4
+ ## Compiler
5
5
 
6
6
  **Install: @travetto/compiler**
7
7
  ```bash
@@ -17,9 +17,12 @@ This module expands upon [Typescript](https://typescriptlang.org), with suppleme
17
17
  * Support for detecting changes in sources files at runtime
18
18
  * Allows for hot-reloading of classes during development
19
19
  * Utilizes `es2015` `Proxy`s to allow for swapping out implementation at runtime
20
-
21
20
  Additionally, there is support for common AST transformations via [Transformation](https://github.com/travetto/travetto/tree/main/module/transformer#readme "Functionality for AST transformations, with transformer registration, and general utils")
22
-
23
21
  ## Debugging
24
-
25
22
  When dealing with transformers, logging is somewhat tricky as the compiler executes before the code is loaded. To that end, the file `compiler.log` is created in the cache directory during the compilation process. This is a location that transformers should be free to log to, for debugging, and any additional feedback.
23
+
24
+ ## CLI
25
+
26
+ The module provides the ability to clear the compilation cache to handle any inconsistencies that may arise.
27
+
28
+ TODO: Describe cli behavior
package/__index__.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './src/compiler';
2
+ export * from './src/state';
3
+ export * from './src/util';
@@ -0,0 +1,32 @@
1
+ import type { ManifestContext, Package } from '@travetto/manifest';
2
+
3
+ declare namespace Transpile {
4
+ type CompileCommand = 'build' | 'watch' | 'clean' | 'manifest';
5
+
6
+ /**
7
+ * Writes a package json file
8
+ */
9
+ function writePackageJson(ctx: ManifestContext, inputFile: string, outputFile: string, transform?: (pkg: Package) => Package): Promise<void>;
10
+
11
+ /**
12
+ * Transpiles a file
13
+ */
14
+ function transpileFile(ctx: ManifestContext, inputFile: string, outputFile: string): Promise<void>;
15
+
16
+ /**
17
+ * Write js file
18
+ */
19
+ function writeJsFile(ctx: ManifestContext, inputFile: string, outputFile: string): Promise<void>;
20
+
21
+ /**
22
+ * Build an entire package
23
+ */
24
+ function buildPackage(ctx: ManifestContext, name: string, sourcePath: string, mainSource: string, extraSource: string[]): Promise<string>;
25
+
26
+ /**
27
+ * Get Context for building
28
+ */
29
+ function getContext(folder?: string): Promise<ManifestContext>;
30
+ }
31
+
32
+ export = Transpile;
@@ -0,0 +1,227 @@
1
+ // @ts-check
2
+
3
+ const _opts = {};
4
+
5
+ /**
6
+ * @typedef {import('@travetto/manifest').Package} Pkg
7
+ * @typedef {import('@travetto/manifest').ManifestContext} ManifestContext
8
+ */
9
+
10
+ function $imp(mod) {
11
+ try { return require(mod); } catch { return import(mod).then(x => x.default); }
12
+ }
13
+
14
+ /** @type {() => import('typescript')} */
15
+ const $getTs = $imp.bind(null, 'typescript');
16
+ /** @type {() => import('fs/promises')} */
17
+ const $getFs = $imp.bind(null, 'fs/promises');
18
+ /** @type {() => import('path')} */
19
+ const $getPath = $imp.bind(null, 'path');
20
+ /** @type {() => ({createRequire:(folder:string) => ({ resolve: (file:string)=>string})})} */
21
+ const $getModule = $imp.bind(null, 'module');
22
+ /** @param {string} x */
23
+ const toPosix = x => x.replace(/\\/g, '/');
24
+
25
+ /**
26
+ * Returns the package.json
27
+ * @param {string} inputFolder
28
+ * @returns {Promise<Pkg>}
29
+ */
30
+ async function $getPkg(inputFolder) {
31
+ const fs = await $getFs();
32
+ const path = await $getPath();
33
+ if (!inputFolder.endsWith('.json')) {
34
+ inputFolder = path.resolve(inputFolder, 'package.json');
35
+ }
36
+ return JSON.parse(await fs.readFile(inputFolder, 'utf8'));
37
+ }
38
+
39
+ /**
40
+ * Get workspace root
41
+ * @return {Promise<string>}
42
+ */
43
+ async function $getWorkspaceRoot() {
44
+ const path = await $getPath();
45
+ const fs = await $getFs();
46
+ let folder = process.cwd();
47
+ let prevFolder = '';
48
+ while (folder !== prevFolder) {
49
+ try {
50
+ const pkg = await $getPkg(folder);
51
+ if (!!pkg.workspaces || !!pkg.travetto?.isolated) {
52
+ return folder;
53
+ }
54
+ } catch { }
55
+ if (await fs.stat(path.resolve(folder, '.git')).catch(() => { })) {
56
+ break;
57
+ }
58
+ prevFolder = folder;
59
+ folder = path.dirname(folder);
60
+ }
61
+ return process.cwd();
62
+ }
63
+
64
+ /**
65
+ * Returns the compiler options
66
+ * @param {ManifestContext} ctx
67
+ * @returns
68
+ */
69
+ async function $getOpts(ctx) {
70
+ if (!(ctx.workspacePath in _opts)) {
71
+ const path = await $getPath();
72
+ const fs = await $getFs();
73
+ const ts = await $getTs();
74
+ const mod = await $getModule();
75
+ const req = mod.createRequire(`${ctx.workspacePath}/node_modules`);
76
+
77
+ const framework = req.resolve('@travetto/compiler/tsconfig.trv.json');
78
+ const self = path.resolve(ctx.workspacePath, 'tsconfig.json');
79
+ const loc = (await fs.stat(self).catch(() => false)) ? self : framework;
80
+ const { options } = ts.parseJsonSourceFileConfigFileContent(
81
+ ts.readJsonConfigFile(loc, ts.sys.readFile), ts.sys, ctx.workspacePath
82
+ );
83
+ options.inlineSourceMap = true;
84
+ options.sourceMap = false;
85
+ try {
86
+ const { type } = await $getPkg(ctx.workspacePath);
87
+ if (type) {
88
+ options.module = type.toLowerCase() === 'commonjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext;
89
+ }
90
+ } catch { }
91
+
92
+ _opts[ctx.workspacePath] = options;
93
+ }
94
+ return _opts[ctx.workspacePath];
95
+ }
96
+
97
+ /**
98
+ * Writes a package json file
99
+ * @param {ManifestContext} ctx
100
+ * @param {string} inputFile
101
+ * @param {string} outputFile
102
+ * @param {(pkg:Pkg) => Pkg} transform
103
+ */
104
+ async function writePackageJson(ctx, inputFile, outputFile, transform) {
105
+ const opts = await $getOpts(ctx);
106
+ const ts = await $getTs();
107
+ const isEsm = opts.module !== ts.ModuleKind.CommonJS;
108
+ let pkg = await $getPkg(inputFile);
109
+ pkg = transform?.(pkg) ?? pkg;
110
+ pkg.main = pkg.main?.replace(/[.]ts$/, '.js');
111
+ pkg.type = isEsm ? 'module' : 'commonjs';
112
+ pkg.files = pkg.files?.map(x => x.replace('.ts', '.js'));
113
+
114
+ ts.sys.writeFile(outputFile, JSON.stringify(pkg, null, 2));
115
+ }
116
+
117
+ /**
118
+ * Transpiles a file
119
+ * @param {ManifestContext} ctx
120
+ * @param {string} inputFile
121
+ * @param {string} outputFile
122
+ */
123
+ async function transpileFile(ctx, inputFile, outputFile) {
124
+ const ts = await $getTs();
125
+ const fs = await $getFs();
126
+
127
+ const opts = await $getOpts(ctx);
128
+ const content = ts.transpile(await fs.readFile(inputFile, 'utf8'), opts, inputFile)
129
+ .replace(/^((?:im|ex)port .*from '[.][^']+)(')/mg, (_, a, b) => `${a}.js${b}`)
130
+ .replace(/^(import [^\n]*from '[^.][^\n/]+[/][^\n/]+[/][^\n']+)(')/mg, (_, a, b) => `${a}.js${b}`);
131
+
132
+ ts.sys.writeFile(outputFile, content);
133
+ }
134
+
135
+ /**
136
+ * Writes a js file
137
+ * @param {ManifestContext} ctx
138
+ * @param {string} inputFile
139
+ * @param {string} outputFile
140
+ */
141
+ async function writeJsFile(ctx, inputFile, outputFile) {
142
+ const ts = await $getTs();
143
+ const fs = await $getFs();
144
+
145
+ const opts = await $getOpts(ctx);
146
+ const isEsm = opts.module !== ts.ModuleKind.CommonJS;
147
+
148
+ let content = await fs.readFile(inputFile, 'utf8');
149
+ if (isEsm) {
150
+ content = content
151
+ .replace(/^(?:async )?function [^$]/mg, a => `export ${a}`)
152
+ .replace(/^module.exports.*/mg, '');
153
+ }
154
+
155
+ await fs.writeFile(outputFile, content, 'utf8');
156
+ }
157
+
158
+ /**
159
+ * Write an entire package
160
+ * @param {ManifestContext} ctx
161
+ * @param {string} name
162
+ * @param {string} sourcePath
163
+ * @param {string} mainSource
164
+ * @param {string[]} extraSources
165
+ */
166
+ async function buildPackage(ctx, name, sourcePath, mainSource, extraSources) {
167
+ const path = await $getPath();
168
+ const fs = await $getFs();
169
+
170
+ const files = [mainSource, ...extraSources].map(x => ({ src: x, out: x.replace(/[.]ts$/, '.js') }));
171
+ const main = files[0].out;
172
+ const outputPath = path.resolve(ctx.workspacePath, ctx.compilerFolder, 'node_modules', name);
173
+
174
+ for (const { src, out } of files) {
175
+ const inputFile = path.resolve(sourcePath, src);
176
+ const outputFile = path.resolve(outputPath, out);
177
+
178
+ const [outStat, inStat] = await Promise.all([
179
+ fs.stat(outputFile).catch(() => undefined),
180
+ fs.stat(inputFile)
181
+ ]);
182
+
183
+ if (!outStat || (outStat.mtimeMs < inStat.mtimeMs)) {
184
+ await fs.mkdir(path.dirname(outputFile), { recursive: true });
185
+
186
+ if (inputFile.endsWith('.ts')) {
187
+ await transpileFile(ctx, inputFile, outputFile);
188
+ } else if (inputFile.endsWith('.js')) {
189
+ await writeJsFile(ctx, inputFile, outputFile);
190
+ } else if (inputFile.endsWith('.json')) {
191
+ await writePackageJson(ctx, inputFile, outputFile,
192
+ (pkg) => ({ ...pkg, files: files.map(x => x.out), name, main }));
193
+ }
194
+ }
195
+ }
196
+
197
+ return path.resolve(outputPath, main);
198
+ }
199
+
200
+ /**
201
+ * Gets build context
202
+ * @return {Promise<ManifestContext>}
203
+ */
204
+ async function getContext(folder = process.cwd()) {
205
+ const path = await $getPath();
206
+
207
+ const workspacePath = path.resolve(await $getWorkspaceRoot());
208
+ const mainPath = toPosix(folder);
209
+
210
+ const { name: mainModule, workspaces, travetto } = (await $getPkg(mainPath));
211
+ const monoRepo = workspacePath !== mainPath || !!workspaces;
212
+
213
+ // All relative to workspacePath
214
+ const manifestFile = `node_modules/${mainModule}/manifest.json`;
215
+
216
+ return {
217
+ mainModule,
218
+ mainPath,
219
+ workspacePath,
220
+ monoRepo,
221
+ manifestFile,
222
+ outputFolder: travetto?.outputFolder ?? '.trv_output',
223
+ compilerFolder: '.trv_compiler'
224
+ };
225
+ }
226
+
227
+ module.exports = { transpileFile, writePackageJson, writeJsFile, buildPackage, getContext };
package/bin/trv.js ADDED
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env node
2
+
3
+ // @ts-check
4
+
5
+ /**
6
+ * @param {import('@travetto/manifest').ManifestContext} ctx
7
+ * @return {Promise<import('../support/bin/compiler-bootstrap')>}
8
+ */
9
+ async function $getBootstrap(ctx) {
10
+ const path = require('path');
11
+ const { buildPackage } = require('./transpile');
12
+
13
+ const root = path.resolve(__dirname, '..');
14
+
15
+ const loc = await buildPackage(
16
+ ctx, '__compiler_bootstrap__', root, 'support/bin/compiler-bootstrap.ts',
17
+ ['support/bin/utils.ts', 'bin/transpile.js', 'package.json']
18
+ );
19
+
20
+ try { return require(loc); } catch { return import(loc); }
21
+ }
22
+
23
+ /**
24
+ * @param {import('@travetto/manifest').ManifestContext} ctx
25
+ * @param {boolean} [watch]
26
+ */
27
+ const compile = (ctx, watch) => $getBootstrap(ctx).then(({ compile: go }) => go(ctx, watch));
28
+
29
+ /** @param {string[]} args */
30
+ async function exec(args) {
31
+ const { getContext } = require('./transpile');
32
+ const op = args.find(x => !x.startsWith('-'));
33
+ /** @type {{clean?: boolean, quiet?: boolean}} */
34
+ const flags = Object.fromEntries(args.filter(x => x.startsWith('-')).map(x => x.split('-').pop()).map(x => [x, true]));
35
+
36
+ const ctx = await getContext();
37
+ const message = flags.quiet ? () => { } : console.log.bind(console);
38
+
39
+ // Clean if needed
40
+ if (op === 'clean' || (op && flags.clean)) {
41
+ const fs = require('fs/promises');
42
+ await Promise.all([ctx.outputFolder, ctx.compilerFolder].map(folder =>
43
+ fs.rm(`${ctx.workspacePath}/${folder}`, { force: true, recursive: true })));
44
+ if (op === 'clean') {
45
+ message(`Cleaned ${ctx.workspacePath}: [${ctx.outputFolder}, ${ctx.compilerFolder}]`);
46
+ }
47
+ }
48
+
49
+ switch (op) {
50
+ case 'clean': break;
51
+ case 'manifest': {
52
+ const { writeManifest, buildManifest } = await $getBootstrap(ctx);
53
+ const manifest = (await buildManifest(ctx)).manifest;
54
+ await writeManifest(ctx, manifest);
55
+ const output = `${ctx.workspacePath}/${ctx.outputFolder}/${ctx.manifestFile}`;
56
+ message(`Wrote manifest ${output}`);
57
+ break;
58
+ }
59
+ case 'watch':
60
+ message(`Watching ${ctx.workspacePath} for changes...`);
61
+ await compile(ctx, true);
62
+ return;
63
+ case 'build':
64
+ await compile(ctx);
65
+ message(`Built to ${ctx.workspacePath}/${ctx.outputFolder}`);
66
+ break;
67
+ default: {
68
+ const path = require('path/posix');
69
+ const { manifest } = await compile(ctx);
70
+ const out = path.join(ctx.workspacePath, ctx.outputFolder);
71
+ // TODO: Externalize somehow?
72
+ const cliMain = path.join(out, manifest.modules['@travetto/cli'].output, 'support', 'main.cli.js');
73
+ process.env.TRV_MANIFEST = ctx.mainModule;
74
+ process.env.TRV_OUTPUT = out;
75
+ await import(process.env.TRV_MAIN = cliMain);
76
+ return;
77
+ }
78
+ }
79
+ }
80
+
81
+ exec(process.argv.slice(2));
package/package.json CHANGED
@@ -1,16 +1,11 @@
1
1
  {
2
2
  "name": "@travetto/compiler",
3
- "displayName": "Compiler",
4
- "version": "3.0.0-rc.4",
5
- "description": "Node-integration of Typescript Compiler with advanced functionality for detecting changes in classes and methods.",
3
+ "version": "3.0.0-rc.7",
4
+ "description": "Compiler",
6
5
  "keywords": [
7
- "tsc",
8
- "typescript",
9
6
  "compiler",
10
- "caching",
11
- "change-detection",
12
- "real-time",
13
- "travetto"
7
+ "travetto",
8
+ "typescript"
14
9
  ],
15
10
  "homepage": "https://travetto.io",
16
11
  "license": "MIT",
@@ -19,20 +14,40 @@
19
14
  "name": "Travetto Framework"
20
15
  },
21
16
  "files": [
22
- "index.ts",
17
+ "__index__.ts",
23
18
  "src",
24
- "support"
19
+ "bin",
20
+ "support",
21
+ "tsconfig.trv.json"
25
22
  ],
26
- "main": "index.ts",
23
+ "main": "__index__.ts",
24
+ "bin": {
25
+ "trv": "bin/trv.js"
26
+ },
27
27
  "repository": {
28
28
  "url": "https://github.com/travetto/travetto.git",
29
29
  "directory": "module/compiler"
30
30
  },
31
31
  "dependencies": {
32
- "@travetto/base": "^3.0.0-rc.2",
33
- "@travetto/transformer": "^3.0.0-rc.4",
34
- "@travetto/watch": "^3.0.0-rc.2"
32
+ "@travetto/manifest": "^3.0.0-rc.3",
33
+ "@travetto/terminal": "^3.0.0-rc.4",
34
+ "@travetto/transformer": "^3.0.0-rc.7"
35
+ },
36
+ "peerDependencies": {
37
+ "@travetto/cli": "^3.0.0-rc.5"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@travetto/cli": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "travetto": {
45
+ "displayName": "Compiler",
46
+ "profiles": [
47
+ "compile"
48
+ ]
35
49
  },
50
+ "private": false,
36
51
  "publishConfig": {
37
52
  "access": "public"
38
53
  }