mnfst-types 0.1.11 → 0.1.12

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
@@ -20,21 +20,25 @@ This writes `manifest.d.ts` in the current directory. Re-run it whenever you add
20
20
  --init Also write a baseline jsconfig.json (only if missing)
21
21
  --ci Also write .github/workflows/types.yml (only if missing)
22
22
  --check Exit 1 if the output is out of date; write nothing
23
+ --tsc Type-check app/ and shared/ (paths from the import map)
23
24
  -h, --help Show usage
24
25
  ```
25
26
 
26
27
  ## Type checks without a build
27
28
 
28
- `--init` writes a `jsconfig.json` whose `paths` mirror the page's import map,
29
- so JSDoc-annotated app modules type-check with no build step:
30
-
31
29
  ```bash
32
- npx mnfst-types --init
33
- npx -p typescript@7 tsc -p jsconfig.json
30
+ npx mnfst-types --tsc
34
31
  ```
35
32
 
36
- `--ci` adds a GitHub Actions workflow running `mnfst-types --check` and `tsc`
37
- on every push. See https://manifestx.dev/docs/framework/getting-started/type-checks.
33
+ Type-checks `app/` and `shared/` with TypeScript. The config is built on every
34
+ run: paths come from the page's import map, so adding an alias like `@shared/`
35
+ never needs a config change. A project `jsconfig.json` or `tsconfig.json` is
36
+ extended — its own options and paths win.
37
+
38
+ `--init` writes a `jsconfig.json` so editors show the same errors as you type;
39
+ run it again after changing the import map to add new aliases to it. `--ci`
40
+ adds a GitHub Actions workflow running `--check` and `--tsc` on every push. See
41
+ https://manifestx.dev/docs/framework/getting-started/type-checks.
38
42
 
39
43
  ## How it works
40
44
 
@@ -8,7 +8,9 @@
8
8
  // Re-running the CLI overwrites the augmentation block (between the
9
9
  // AUGMENTATION:start / AUGMENTATION:end markers in the template).
10
10
 
11
- import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from 'node:fs';
11
+ import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync, mkdtempSync, rmSync, realpathSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { spawnSync } from 'node:child_process';
12
14
  import { dirname, join, resolve, isAbsolute, relative } from 'node:path';
13
15
  import { fileURLToPath, pathToFileURL } from 'node:url';
14
16
  import { createRequire } from 'node:module';
@@ -45,26 +47,32 @@ export async function main(argv) {
45
47
  const output = applyAugmentation(template, augmentation);
46
48
 
47
49
  const outPath = resolve(cwd, opts.out);
50
+ const typesPath = relative(projectRoot, outPath).split('\\').join('/');
48
51
  if (opts.check) {
49
52
  const current = existsSync(outPath) ? readFileSync(outPath, 'utf8') : '';
50
53
  if (current !== output) {
51
54
  console.error(`mnfst-types: ${opts.out} is out of date with manifest.json — run \`npx mnfst-types\` and commit it`);
52
55
  process.exitCode = 1;
53
- return;
56
+ } else {
57
+ console.log(`mnfst-types: ${opts.out} is up to date`);
54
58
  }
55
- console.log(`mnfst-types: ${opts.out} is up to date`);
56
- return;
59
+ } else if (!opts.tsc) {
60
+ writeFileSync(outPath, output);
61
+ console.log(`mnfst-types: wrote ${outPath}`);
57
62
  }
58
- writeFileSync(outPath, output);
59
- console.log(`mnfst-types: wrote ${outPath}`);
60
63
 
61
- const typesPath = relative(projectRoot, outPath).split('\\').join('/');
62
64
  if (opts.init) {
63
- writeOnce(join(projectRoot, 'jsconfig.json'), defaultJsconfig(typesPath, importMapPaths(projectRoot)));
65
+ const jsconfig = join(projectRoot, 'jsconfig.json');
66
+ if (existsSync(jsconfig)) syncJsconfigPaths(jsconfig, typesPath, importMapPaths(projectRoot));
67
+ else writeOnce(jsconfig, defaultJsconfig(typesPath, importMapPaths(projectRoot)));
64
68
  }
65
69
  if (opts.ci) {
66
70
  writeOnce(join(projectRoot, '.github', 'workflows', 'types.yml'), defaultWorkflow(typesPath));
67
71
  }
72
+ if (opts.tsc) {
73
+ const status = runTsc(projectRoot, typesPath);
74
+ if (status) process.exitCode = process.exitCode || status;
75
+ }
68
76
  }
69
77
 
70
78
  function writeOnce(path, content) {
@@ -87,6 +95,7 @@ function parseArgs(argv) {
87
95
  init: false,
88
96
  ci: false,
89
97
  check: false,
98
+ tsc: false,
90
99
  help: false
91
100
  };
92
101
  for (let i = 0; i < argv.length; i++) {
@@ -95,6 +104,7 @@ function parseArgs(argv) {
95
104
  else if (a === '--init') opts.init = true;
96
105
  else if (a === '--ci') opts.ci = true;
97
106
  else if (a === '--check') opts.check = true;
107
+ else if (a === '--tsc') opts.tsc = true;
98
108
  else if (a === '--manifest') opts.manifest = argv[++i];
99
109
  else if (a === '--out') opts.out = argv[++i];
100
110
  else if (a.startsWith('--manifest=')) opts.manifest = a.slice('--manifest='.length);
@@ -115,6 +125,8 @@ Options:
115
125
  --init Also write a baseline jsconfig.json (only if missing)
116
126
  --ci Also write .github/workflows/types.yml (only if missing)
117
127
  --check Exit 1 if the output file is out of date; write nothing
128
+ --tsc Type-check app/ and shared/ with tsc; paths come from the
129
+ import map on every run (extends your jsconfig/tsconfig if any)
118
130
  -h, --help Show this message
119
131
  `);
120
132
  }
@@ -137,21 +149,137 @@ function importMapPaths(projectRoot) {
137
149
  return paths;
138
150
  }
139
151
 
152
+ const COMPILER_DEFAULTS = {
153
+ target: 'es2022',
154
+ module: 'esnext',
155
+ moduleResolution: 'bundler',
156
+ checkJs: true,
157
+ allowJs: true,
158
+ noEmit: true,
159
+ strict: false,
160
+ skipLibCheck: true,
161
+ lib: ['es2022', 'dom', 'dom.iterable']
162
+ };
163
+ const DEFAULT_INCLUDE = (types) => ['app/**/*', 'shared/**/*', types, '*.d.ts'];
164
+
165
+ // JSON with comments and trailing commas, as tsconfig allows; null when unreadable
166
+ function readJsonc(path) {
167
+ try {
168
+ const text = readFileSync(path, 'utf8')
169
+ .replace(/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (m, str) => str || '')
170
+ .replace(/,(\s*[}\]])/g, '$1');
171
+ return JSON.parse(text);
172
+ } catch { return null; }
173
+ }
174
+
175
+ // A config and its relative `extends` chain, nearest first: [{ file, config }]
176
+ function configChain(file) {
177
+ const chain = [];
178
+ const seen = new Set();
179
+ let current = file;
180
+ while (current && !seen.has(current) && existsSync(current)) {
181
+ seen.add(current);
182
+ const config = readJsonc(current);
183
+ chain.push({ file: current, config });
184
+ const ext = config && config.extends;
185
+ const next = Array.isArray(ext) ? ext[ext.length - 1] : ext;
186
+ if (typeof next !== 'string' || !/^\.{1,2}[\\/]/.test(next)) break;
187
+ current = resolve(dirname(current), next.endsWith('.json') ? next : next + '.json');
188
+ }
189
+ return chain;
190
+ }
191
+
192
+ // Effective paths: a config's `paths` replaces any inherited one, so the nearest wins outright
193
+ function chainPaths(chain) {
194
+ const hit = chain.find(({ config }) => config && config.compilerOptions && config.compilerOptions.paths);
195
+ if (!hit) return {};
196
+ const opts = hit.config.compilerOptions;
197
+ const base = opts.baseUrl ? resolve(dirname(hit.file), opts.baseUrl) : dirname(hit.file);
198
+ const out = {};
199
+ for (const [k, v] of Object.entries(opts.paths)) out[k] = (Array.isArray(v) ? v : [v]).map((x) => resolve(base, x));
200
+ return out;
201
+ }
202
+
203
+ // --init on an existing jsconfig: add import-map paths it lacks (plain JSON only)
204
+ function syncJsconfigPaths(path, types, aliases) {
205
+ const text = readFileSync(path, 'utf8');
206
+ let config;
207
+ try { config = JSON.parse(text); } catch {
208
+ console.log(`mnfst-types: ${path} isn't plain JSON (comments or trailing commas); add any new import-map aliases to its paths by hand (npx mnfst-types --tsc merges them anyway)`);
209
+ return;
210
+ }
211
+ const dir = dirname(path);
212
+ const inherited = chainPaths(configChain(path).slice(1));
213
+ const own = (config.compilerOptions ||= {}).paths;
214
+ const known = new Set(Object.keys(own || inherited));
215
+ const wanted = { mnfst: [`./${types}`], ...aliases };
216
+ const added = Object.keys(wanted).filter((k) => !known.has(k));
217
+ if (!added.length) {
218
+ console.log(`mnfst-types: ${path} already maps every import-map alias`);
219
+ return;
220
+ }
221
+ // A child `paths` replaces the base's, so carry inherited entries over
222
+ const paths = own || Object.fromEntries(Object.entries(inherited).map(([k, v]) => [k, v.map((t) => './' + relative(dir, t).split('\\').join('/'))]));
223
+ for (const k of added) paths[k] = wanted[k];
224
+ config.compilerOptions.paths = paths;
225
+ const indent = (text.match(/\n([ \t]+)"/) || [, ' '])[1];
226
+ writeFileSync(path, JSON.stringify(config, null, indent) + '\n');
227
+ console.log(`mnfst-types: added ${added.join(', ')} to ${path}`);
228
+ }
229
+
230
+ // tsc from the project, then next to mnfst-types, else npx
231
+ function findTsc(projectRoot) {
232
+ for (const from of [join(projectRoot, 'package.json'), fileURLToPath(import.meta.url)]) {
233
+ try {
234
+ const req = createRequire(from);
235
+ const pkgPath = req.resolve('typescript/package.json');
236
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
237
+ const bin = typeof pkg.bin === 'string' ? pkg.bin : pkg.bin && pkg.bin.tsc;
238
+ if (bin) return { cmd: process.execPath, args: [join(dirname(pkgPath), bin)] };
239
+ } catch { /* next */ }
240
+ }
241
+ return { cmd: 'npx', args: ['-y', '-p', 'typescript@7', 'tsc'], shell: process.platform === 'win32' };
242
+ }
243
+
244
+ // Type-check with a config built now: import-map paths can't drift. A project
245
+ // jsconfig/tsconfig is extended, and its own paths win over the import map.
246
+ function runTsc(projectRoot, types) {
247
+ const abs = (p) => resolve(projectRoot, p);
248
+ const own = ['tsconfig.json', 'jsconfig.json'].map((f) => join(projectRoot, f)).find((f) => existsSync(f));
249
+ const config = { compilerOptions: {} };
250
+ let paths = { mnfst: [abs(types)] };
251
+ for (const [k, v] of Object.entries(importMapPaths(projectRoot))) paths[k] = v.map(abs);
252
+ if (own) {
253
+ config.extends = own;
254
+ const chain = configChain(own);
255
+ if (!chain[0].config) console.warn(`mnfst-types: couldn't read ${own}; extending it with import-map paths only`);
256
+ paths = { ...paths, ...chainPaths(chain) };
257
+ if (!chain.some(({ config: c }) => c && (c.include || c.files))) config.include = DEFAULT_INCLUDE(types).map(abs);
258
+ } else {
259
+ Object.assign(config.compilerOptions, COMPILER_DEFAULTS);
260
+ config.include = DEFAULT_INCLUDE(types).map(abs);
261
+ config.exclude = ['node_modules', 'website'].map(abs);
262
+ }
263
+ config.compilerOptions.paths = paths;
264
+ config.compilerOptions.noEmit = true;
265
+ const dir = mkdtempSync(join(tmpdir(), 'mnfst-tsc-'));
266
+ const file = join(dir, 'tsconfig.json');
267
+ try {
268
+ writeFileSync(file, JSON.stringify(config, null, 2));
269
+ const { cmd, args, shell } = findTsc(projectRoot);
270
+ const r = spawnSync(cmd, [...args, '-p', shell ? `"${file}"` : file, '--pretty', 'false'], { cwd: realpathSync(projectRoot), stdio: 'inherit', shell: !!shell });
271
+ if (r.error) { console.error(`mnfst-types: couldn't run tsc (${r.error.message})`); return 2; }
272
+ if (r.status === 0) console.log('mnfst-types: no type errors');
273
+ return r.status ?? 1;
274
+ } finally {
275
+ rmSync(dir, { recursive: true, force: true });
276
+ }
277
+ }
278
+
140
279
  function defaultJsconfig(types, aliases = {}) {
141
280
  return JSON.stringify({
142
- compilerOptions: {
143
- target: 'es2022',
144
- module: 'esnext',
145
- moduleResolution: 'bundler',
146
- checkJs: true,
147
- allowJs: true,
148
- noEmit: true,
149
- strict: false,
150
- skipLibCheck: true,
151
- lib: ['es2022', 'dom', 'dom.iterable'],
152
- paths: { mnfst: [`./${types}`], ...aliases }
153
- },
154
- include: ['app/**/*', 'shared/**/*', types, '*.d.ts'],
281
+ compilerOptions: { ...COMPILER_DEFAULTS, paths: { mnfst: [`./${types}`], ...aliases } },
282
+ include: DEFAULT_INCLUDE(types),
155
283
  exclude: ['node_modules', 'website']
156
284
  }, null, 4) + '\n';
157
285
  }
@@ -171,7 +299,7 @@ function defaultWorkflow(out) {
171
299
  ' with:',
172
300
  ' node-version: 22',
173
301
  ` - run: npx -y mnfst-types@latest --check --out ${out}`,
174
- ' - run: npx -y -p typescript@7 tsc -p jsconfig.json',
302
+ ` - run: npx -y -p typescript@7 -p mnfst-types@latest mnfst-types --tsc --out ${out}`,
175
303
  ''
176
304
  ].join('\n');
177
305
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mnfst-types",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Generate TypeScript types for a Manifest project from manifest.json and sample data",
5
5
  "type": "module",
6
6
  "bin": {