@travetto/compiler 3.0.0-rc.12 → 3.0.0-rc.13

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/bin/trv.js CHANGED
@@ -11,7 +11,7 @@ const VALID_OPS = { watch: 'watch', build: 'build', clean: 'clean', manifest: 'm
11
11
 
12
12
  /**
13
13
  * @param {import('@travetto/manifest').ManifestContext} ctx
14
- * @return {Promise<import('@travetto/compiler/support/launcher')>}
14
+ * @return {Promise<import('@travetto/compiler/support/launcher').launch>}
15
15
  */
16
16
  const $getLauncher = async (ctx) => {
17
17
  const compPkg = createRequire(path.resolve('node_modules')).resolve('@travetto/compiler/package.json');
@@ -48,49 +48,20 @@ const $getLauncher = async (ctx) => {
48
48
  files.push(target);
49
49
  }
50
50
 
51
- try { return await require(files[0]); }
52
- catch { return import(files[0]); }
51
+ try { return require(files[0]).launch; }
52
+ catch { return import(files[0]).then(x => x.launch); }
53
53
  };
54
54
 
55
- /**
56
- * Parse arguments
57
- * @param {string[]} args
58
- * @returns {{ op?: keyof typeof VALID_OPS, clean?: boolean, outputPath?: string, env?: string }}
59
- */
60
- function parseArgs(args) {
61
- const op = VALID_OPS[args.find(x => !x.startsWith('-')) ?? ''];
62
- return {
63
- op,
64
- clean: args.includes('--clean') || args.includes('-c'),
65
- ...(op === 'manifest' ? { outputPath: args[1], env: args[2] } : {})
66
- };
67
- }
68
-
69
- const exec = async () => {
55
+ (async () => {
70
56
  const ctx = await getManifestContext();
71
- const { op, outputPath, env, ...flags } = parseArgs(process.argv.slice(2));
57
+ const [op, args] = [VALID_OPS[process.argv[2]], process.argv.slice(3)];
72
58
 
73
- // Clean if needed
74
- if (op === 'clean' || (op && flags.clean)) {
59
+ if (op === 'clean') {
75
60
  for (const f of [ctx.outputFolder, ctx.compilerFolder]) {
76
61
  await fs.rm(path.resolve(ctx.workspacePath, f), { force: true, recursive: true });
77
62
  }
78
- }
79
-
80
- if (op === 'clean') { // Clean needs to not attempt to compile/load launcher
81
63
  return console.log(`Cleaned ${ctx.workspacePath}: [${ctx.outputFolder}, ${ctx.compilerFolder}]`);
82
64
  }
83
65
 
84
- const { compile, launchMain, exportManifest } = await $getLauncher(ctx);
85
-
86
- switch (op) {
87
- case 'manifest': return exportManifest(ctx, outputPath ?? '', env);
88
- case 'watch':
89
- case 'build': return compile(ctx, op);
90
- default:
91
- await compile(ctx, op);
92
- return launchMain(ctx);
93
- }
94
- };
95
-
96
- exec();
66
+ return (await $getLauncher(ctx))(ctx, op, args);
67
+ })();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@travetto/compiler",
3
- "version": "3.0.0-rc.12",
3
+ "version": "3.0.0-rc.13",
4
4
  "description": "Compiler",
5
5
  "keywords": [
6
6
  "compiler",
@@ -31,12 +31,12 @@
31
31
  },
32
32
  "dependencies": {
33
33
  "@parcel/watcher": "^2.1.0",
34
- "@travetto/manifest": "^3.0.0-rc.7",
34
+ "@travetto/manifest": "^3.0.0-rc.8",
35
35
  "@travetto/terminal": "^3.0.0-rc.6",
36
- "@travetto/transformer": "^3.0.0-rc.10"
36
+ "@travetto/transformer": "^3.0.0-rc.11"
37
37
  },
38
38
  "peerDependencies": {
39
- "@travetto/cli": "^3.0.0-rc.9"
39
+ "@travetto/cli": "^3.0.0-rc.10"
40
40
  },
41
41
  "peerDependenciesMeta": {
42
42
  "@travetto/cli": {
package/src/state.ts CHANGED
@@ -189,7 +189,7 @@ export class CompilerState {
189
189
  data?: ts.WriteFileCallbackData
190
190
  ): void => {
191
191
  if (outputFile.endsWith('package.json')) {
192
- text = CompilerUtil.rewritePackageJSON(this.#manifest, text, options);
192
+ text = CompilerUtil.rewritePackageJSON(this.#manifest, text);
193
193
  } else if (!options.inlineSourceMap && options.sourceMap && outputFile.endsWith('.map')) {
194
194
  text = CompilerUtil.rewriteSourceMap(this.#manifest.workspacePath, text, f => this.#sourceInputOutput.get(this.#inputToSource.get(f)!));
195
195
  } else if (options.inlineSourceMap && CompilerUtil.isSourceMapUrlPosData(data)) {
package/src/util.ts CHANGED
@@ -79,7 +79,7 @@ export class CompilerUtil {
79
79
  * @param text
80
80
  * @returns
81
81
  */
82
- static rewritePackageJSON(manifest: ManifestRoot, text: string, opts: ts.CompilerOptions): string {
82
+ static rewritePackageJSON(manifest: ManifestRoot, text: string): string {
83
83
  const pkg: Package = JSON.parse(text);
84
84
  if (pkg.files) {
85
85
  pkg.files = pkg.files.map(x => this.inputToOutput(x));
@@ -87,7 +87,7 @@ export class CompilerUtil {
87
87
  if (pkg.main) {
88
88
  pkg.main = this.inputToOutput(pkg.main);
89
89
  }
90
- pkg.type = opts.module !== ts.ModuleKind.CommonJS ? 'module' : 'commonjs';
90
+ pkg.type = manifest.moduleType;
91
91
  for (const key of ['devDependencies', 'dependencies', 'peerDependencies'] as const) {
92
92
  if (key in pkg) {
93
93
  for (const dep of Object.keys(pkg[key] ?? {})) {
@@ -1,6 +1,5 @@
1
1
  import fs from 'fs/promises';
2
2
  import path from 'path';
3
- import { Module } from 'module';
4
3
 
5
4
  import type { ManifestContext } from '@travetto/manifest';
6
5
  import { TranspileUtil } from './transpile';
@@ -20,7 +19,7 @@ async function compileIfStale(ctx: ManifestContext, scope: string, mod: string,
20
19
  const out: string[] = [];
21
20
 
22
21
  try {
23
- await TranspileUtil.withLogger(scope, { args: [mod], basic: false }, async log => {
22
+ await TranspileUtil.withLogger(scope, async log => {
24
23
  if (files.some(f => f.stale)) {
25
24
  log('debug', 'Starting');
26
25
  for (const file of files.filter(x => x.stale)) {
@@ -34,7 +33,7 @@ async function compileIfStale(ctx: ManifestContext, scope: string, mod: string,
34
33
  } else {
35
34
  log('debug', 'Skipped');
36
35
  }
37
- });
36
+ }, false, [mod]);
38
37
  } catch (err) {
39
38
  console.error(err);
40
39
  }
@@ -44,7 +43,7 @@ async function compileIfStale(ctx: ManifestContext, scope: string, mod: string,
44
43
  /**
45
44
  * Run the compiler
46
45
  */
47
- export async function compile(ctx: ManifestContext, op?: 'watch' | 'build'): Promise<void> {
46
+ async function compile(ctx: ManifestContext, op?: 'watch' | 'build'): Promise<void> {
48
47
  let changes = 0;
49
48
 
50
49
  await TranspileUtil.withLogger('precompile', async () => {
@@ -73,8 +72,10 @@ export async function compile(ctx: ManifestContext, op?: 'watch' | 'build'): Pro
73
72
  });
74
73
 
75
74
  if (changes) {
76
- await fs.rm(path.resolve(ctx.workspacePath, ctx.outputFolder), { recursive: true, force: true });
77
- TranspileUtil.log('reset', [], 'info', 'Clearing output due to compiler changes');
75
+ await TranspileUtil.withLogger('reset', async log => {
76
+ await fs.rm(path.resolve(ctx.workspacePath, ctx.outputFolder), { recursive: true, force: true });
77
+ log('info', 'Clearing output due to compiler changes');
78
+ }, false);
78
79
  }
79
80
 
80
81
  // Write manifest
@@ -95,7 +96,7 @@ export async function compile(ctx: ManifestContext, op?: 'watch' | 'build'): Pro
95
96
  }
96
97
  });
97
98
 
98
- await TranspileUtil.withLogger('compile', { args: [], basic: false }, async log => {
99
+ await TranspileUtil.withLogger('compile', async log => {
99
100
  const changed = delta.filter(x => x.type === 'added' || x.type === 'changed');
100
101
  log('debug', `Started action=${op} changed=${changed.map(x => `${x.module}/${x.file}`)}`);
101
102
  if (changed.length || op === 'watch') {
@@ -104,17 +105,13 @@ export async function compile(ctx: ManifestContext, op?: 'watch' | 'build'): Pro
104
105
  } else {
105
106
  log('debug', 'Skipped');
106
107
  }
107
- });
108
-
109
- if (op === 'build') {
110
- TranspileUtil.log('build', [], 'info', 'Successfully built');
111
- }
108
+ }, false);
112
109
  }
113
110
 
114
111
  /**
115
112
  * Export manifests
116
113
  */
117
- export async function exportManifest(ctx: ManifestContext, output?: string, env = 'dev'): Promise<string | undefined> {
114
+ async function exportManifest(ctx: ManifestContext, output?: string, env = 'dev'): Promise<void> {
118
115
  const { ManifestUtil } = await importManifest(ctx);
119
116
  const manifest = await ManifestUtil.buildManifest(ctx);
120
117
 
@@ -136,25 +133,27 @@ export async function exportManifest(ctx: ManifestContext, output?: string, env
136
133
 
137
134
  await TranspileUtil.writeTextFile(output, JSON.stringify(manifest));
138
135
  TranspileUtil.log('manifest', [], 'info', `Wrote manifest ${output}`);
139
- return output;
140
136
  } else {
141
137
  console.log(JSON.stringify(manifest, null, 2));
142
- return;
143
138
  }
144
139
  }
145
140
 
146
- export async function launchMain(ctx: ManifestContext): Promise<void> {
147
- // Rewriting node_path
148
- const nodeOut = path.resolve(ctx.workspacePath, ctx.outputFolder, 'node_modules');
149
- const og = process.env.NODE_PATH;
150
- process.env.NODE_PATH = [nodeOut, og].join(path.delimiter);
151
- // @ts-expect-error
152
- Module._initPaths();
153
- process.env.NODE_PATH = og; // Restore
154
-
155
- process.env.TRV_MANIFEST = path.resolve(nodeOut, ctx.mainModule);
156
-
157
- // TODO: Externalize somehow?
158
- const cliMain = path.join(nodeOut, '@travetto/cli/support/cli.js');
159
- return await import(cliMain);
141
+ /**
142
+ * Launch
143
+ */
144
+ export async function launch(ctx: ManifestContext, op?: 'build' | 'watch' | 'manifest', args: (string | undefined)[] = []): Promise<void> {
145
+ if (op !== 'manifest') {
146
+ await compile(ctx, op);
147
+ }
148
+ switch (op) {
149
+ case 'manifest': return exportManifest(ctx, ...args);
150
+ case 'build': return TranspileUtil.log('build', [], 'info', 'Successfully built');
151
+ case undefined: {
152
+ // TODO: Externalize somehow?
153
+ const outputPath = path.resolve(ctx.workspacePath, ctx.outputFolder);
154
+ process.env.TRV_MANIFEST = path.resolve(outputPath, 'node_modules', ctx.mainModule);
155
+ const cliMain = path.join(outputPath, 'node_modules', '@travetto/cli/support/cli.js');
156
+ return import(cliMain);
157
+ }
158
+ }
160
159
  }
@@ -6,25 +6,24 @@ import { createRequire } from 'module';
6
6
 
7
7
  import { DeltaEvent, ManifestContext, ManifestRoot, Package } from '@travetto/manifest';
8
8
 
9
- type ModFile = { input: string, output: string, stale: boolean };
10
-
11
- const SRC_REQ = createRequire(path.resolve('node_modules'));
12
- const recentStat = (stat: { ctimeMs: number, mtimeMs: number }): number => Math.max(stat.ctimeMs, stat.mtimeMs);
13
-
14
9
  export type CompilerLogEvent = [level: 'info' | 'debug' | 'warn', message: string];
10
+ type ModFile = { input: string, output: string, stale: boolean };
15
11
  type WithLogger<T> = (log: (...ev: CompilerLogEvent) => void) => Promise<T>;
16
- type LogConfig = { args?: string[], basic?: boolean };
17
- const isCompilerLogEvent = (o: unknown): o is CompilerLogEvent => o !== null && o !== undefined && Array.isArray(o);
18
12
 
13
+ const OPT_CACHE: Record<string, import('typescript').CompilerOptions> = {};
14
+ const SRC_REQ = createRequire(path.resolve('node_modules'));
19
15
  const LEVELS = { warn: true, debug: /^debug$/.test(process.env.TRV_BUILD ?? ''), info: !/^warn$/.test(process.env.TRV_BUILD ?? '') };
20
16
  const SCOPE_MAX = 15;
17
+ const RECENT_STAT = (stat: { ctimeMs: number, mtimeMs: number }): number => Math.max(stat.ctimeMs, stat.mtimeMs);
18
+ const IS_LOG_EV = (o: unknown): o is CompilerLogEvent => o !== null && o !== undefined && Array.isArray(o);
21
19
 
22
20
  /**
23
21
  * Transpile utilities for launching
24
22
  */
25
23
  export class TranspileUtil {
26
- static #optCache: Record<string, {}> = {};
27
-
24
+ /**
25
+ * Log message with filtering by level
26
+ */
28
27
  static log(scope: string, args: string[], ...[level, msg]: CompilerLogEvent): void {
29
28
  const message = msg.replaceAll(process.cwd(), '.');
30
29
  LEVELS[level] && console.debug(new Date().toISOString(), `[${scope.padEnd(SCOPE_MAX, ' ')}]`, ...args, message);
@@ -33,14 +32,10 @@ export class TranspileUtil {
33
32
  /**
34
33
  * With logger
35
34
  */
36
- static withLogger<T>(scope: string, op: WithLogger<T>): Promise<T>;
37
- static withLogger<T>(scope: string, opts: LogConfig, op: WithLogger<T>): Promise<T>;
38
- static withLogger<T>(scope: string, opts: LogConfig | WithLogger<T>, op?: WithLogger<T>): Promise<T> {
39
- const cfg = { basic: true, ...typeof opts === 'function' ? {} : opts };
40
- const go = typeof opts === 'function' ? opts : op!;
41
- const log = this.log.bind(null, scope, cfg.args ?? []);
42
- cfg.basic && log('debug', 'Started');
43
- return go(log).finally(() => cfg.basic && log('debug', 'Completed'));
35
+ static withLogger<T>(scope: string, op: WithLogger<T>, basic = true, args: string[] = []): Promise<T> {
36
+ const log = this.log.bind(null, scope, args);
37
+ basic && log('debug', 'Started');
38
+ return op(log).finally(() => basic && log('debug', 'Completed'));
44
39
  }
45
40
 
46
41
  /**
@@ -53,7 +48,7 @@ export class TranspileUtil {
53
48
  * Returns the compiler options
54
49
  */
55
50
  static async getCompilerOptions(ctx: ManifestContext): Promise<{}> {
56
- if (!(ctx.workspacePath in this.#optCache)) {
51
+ if (!(ctx.workspacePath in OPT_CACHE)) {
57
52
  let tsconfig = path.resolve(ctx.workspacePath, 'tsconfig.json');
58
53
 
59
54
  if (!await fs.stat(tsconfig).then(_ => true, _ => false)) {
@@ -66,19 +61,17 @@ export class TranspileUtil {
66
61
  ts.readJsonConfigFile(tsconfig, ts.sys.readFile), ts.sys, ctx.workspacePath
67
62
  );
68
63
 
69
- options.allowJs = true;
70
- options.resolveJsonModule = true;
71
- options.sourceRoot = ctx.workspacePath;
72
- options.rootDir = ctx.workspacePath;
73
- options.outDir = path.resolve(ctx.workspacePath);
74
-
75
- try {
76
- options.module = ctx.moduleType === 'commonjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext;
77
- } catch { }
78
-
79
- this.#optCache[ctx.workspacePath] = options;
64
+ OPT_CACHE[ctx.workspacePath] = {
65
+ ...options,
66
+ allowJs: true,
67
+ resolveJsonModule: true,
68
+ sourceRoot: ctx.workspacePath,
69
+ rootDir: ctx.workspacePath,
70
+ outDir: path.resolve(ctx.workspacePath),
71
+ module: ctx.moduleType === 'commonjs' ? ts.ModuleKind.CommonJS : ts.ModuleKind.ESNext,
72
+ };
80
73
  }
81
- return this.#optCache[ctx.workspacePath];
74
+ return OPT_CACHE[ctx.workspacePath];
82
75
  }
83
76
 
84
77
  /**
@@ -143,9 +136,9 @@ export class TranspileUtil {
143
136
  const out: ModFile[] = [];
144
137
  for (const input of files) {
145
138
  const output = input.replace(inputFolder, outputFolder).replace(/[.]ts$/, '.js');
146
- const inputTs = await fs.stat(input).then(recentStat, () => 0);
139
+ const inputTs = await fs.stat(input).then(RECENT_STAT, () => 0);
147
140
  if (inputTs) {
148
- const outputTs = await fs.stat(output).then(recentStat, () => 0);
141
+ const outputTs = await fs.stat(output).then(RECENT_STAT, () => 0);
149
142
  await fs.mkdir(path.dirname(output), { recursive: true, });
150
143
  out.push({ input, output, stale: inputTs > outputTs });
151
144
  }
@@ -168,18 +161,16 @@ export class TranspileUtil {
168
161
 
169
162
  await this.writeTextFile(deltaFile, changedFiles.join('\n'));
170
163
 
171
- await this.withLogger('compiler-exec', async log => {
172
- await new Promise((res, rej) =>
173
- cp.spawn(process.argv0, [main, deltaFile, `${watch}`], {
174
- env: {
175
- ...process.env,
176
- TRV_MANIFEST: path.resolve(ctx.workspacePath, ctx.outputFolder, 'node_modules', ctx.mainModule),
177
- },
178
- stdio: [0, 1, 2, 'ipc'],
179
- })
180
- .on('message', msg => isCompilerLogEvent(msg) && log(...msg))
181
- .on('exit', code => (code !== null && code > 0) ? rej() : res(null))
182
- );
183
- });
164
+ await this.withLogger('compiler-exec', log => new Promise((res, rej) =>
165
+ cp.spawn(process.argv0, [main, deltaFile, `${watch}`], {
166
+ env: {
167
+ ...process.env,
168
+ TRV_MANIFEST: path.resolve(ctx.workspacePath, ctx.outputFolder, 'node_modules', ctx.mainModule),
169
+ },
170
+ stdio: [0, 1, 2, 'ipc'],
171
+ })
172
+ .on('message', msg => IS_LOG_EV(msg) && log(...msg))
173
+ .on('exit', code => (code !== null && code > 0) ? rej() : res(null))
174
+ )).finally(() => fs.unlink(deltaFile));
184
175
  }
185
176
  }