@ttsc/strip 0.30.3 → 0.31.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/driver/config.go CHANGED
@@ -13,6 +13,7 @@ import (
13
13
  "strings"
14
14
 
15
15
  "github.com/samchon/ttsc/packages/ttsc/driver"
16
+ "github.com/samchon/ttsc/packages/ttsc/driver/resolutioninputs"
16
17
  "github.com/samchon/ttsc/packages/ttsc/driver/windowsjunction"
17
18
  )
18
19
 
@@ -38,18 +39,17 @@ var allowedTsconfigKeys = map[string]struct{}{
38
39
  "transform": {},
39
40
  }
40
41
 
41
- // loadStripConfigMap validates the tsconfig plugin entry and loads the strip
42
- // configuration from either an explicit configFile or an auto-discovered
43
- // strip.config.* file. Returns the raw config map ready for parseStrip.
44
- func loadStripConfigMap(pluginConfig map[string]any, cwd, tsconfigPath string) (map[string]any, error) {
45
- return loadStripConfigMapWithReporter(pluginConfig, cwd, tsconfigPath, nil)
46
- }
47
-
48
- func loadStripConfigMapWithReporter(pluginConfig map[string]any, cwd, tsconfigPath string, reporter func(string)) (map[string]any, error) {
49
- return loadStripConfigMapWithReporters(pluginConfig, cwd, tsconfigPath, reporter, nil, nil)
50
- }
51
-
52
- func loadStripConfigMapWithReporters(pluginConfig map[string]any, cwd, tsconfigPath string, reporter func(string), hashReporter, realpathReporter func(string, *string)) (map[string]any, error) {
42
+ // loadStripConfigMapWithReporters validates the tsconfig plugin entry and loads
43
+ // the strip configuration from either an explicit configFile or an
44
+ // auto-discovered strip.config.* file. It returns the raw config map ready for
45
+ // parseStrip, which applies the built-in defaults to an empty one.
46
+ //
47
+ // The reporters declare the exact known configuration inputs: the evaluated
48
+ // config and everything its evaluation read, and the discovery candidates that
49
+ // were rejected on the way. Optional incomplete reporters disclose unavailable
50
+ // public resolution observation separately from a moved input's missing proof;
51
+ // the evaluated value remains usable.
52
+ func loadStripConfigMapWithReporters(pluginConfig map[string]any, cwd, tsconfigPath string, reporter func(string), hashReporter, realpathReporter func(string, *string), incompleteReporters ...func()) (map[string]any, error) {
53
53
  // Reject any key that @ttsc/strip does not recognise. This surfaces
54
54
  // stale inline keys (calls, statements) with a clear error so users
55
55
  // migrate to a config file instead of silently using defaults.
@@ -100,6 +100,13 @@ func loadStripConfigMapWithReporters(pluginConfig map[string]any, cwd, tsconfigP
100
100
  return nil, err
101
101
  }
102
102
  reportStripConfigInputs(loaded.inputs, loaded.hashes, loaded.realpaths, reporter, hashReporter, realpathReporter)
103
+ if !loaded.complete {
104
+ for _, report := range incompleteReporters {
105
+ if report != nil {
106
+ report()
107
+ }
108
+ }
109
+ }
103
110
  cfg, ok := loaded.value.(map[string]any)
104
111
  if !ok {
105
112
  return nil, fmt.Errorf("@ttsc/strip: config file %s must export an object", configFilePath)
@@ -151,7 +158,8 @@ func stripDiscoveryBaseDir(cwd, tsconfigPath string) string {
151
158
 
152
159
  // resolveStripConfigFilePath resolves a user-supplied config path to an
153
160
  // absolute path. Absolute paths are returned unchanged; relative paths are
154
- // joined to the tsconfig directory (or cwd when no tsconfig is set).
161
+ // joined to the explicit host discovery anchor, otherwise the tsconfig
162
+ // directory (or cwd when no tsconfig is set).
155
163
  func resolveStripConfigFilePath(configPath, cwd, tsconfigPath string) string {
156
164
  if filepath.IsAbs(configPath) {
157
165
  return configPath
@@ -159,26 +167,27 @@ func resolveStripConfigFilePath(configPath, cwd, tsconfigPath string) string {
159
167
  return filepath.Join(stripDiscoveryBaseDir(cwd, tsconfigPath), configPath)
160
168
  }
161
169
 
162
- // loadStripConfigFile loads and deserializes a strip config file at location.
163
- // The format is determined by extension: .json is parsed natively; .js/.cjs/.mjs
164
- // run through a Node subprocess; .ts/.cts/.mts run through ttsx.
165
- //
166
- // resolutionRoot is the project directory the TypeScript branch anchors its
167
- // toolchain resolution on when the config file's own ancestry answers nothing;
168
- // see stripConfigToolAnchors. The JSON and JS branches spawn no ttsx and
169
- // ignore it.
170
- func loadStripConfigFile(location, resolutionRoot string) (any, error) {
171
- loaded, err := loadStripConfigFileWithInputs(location, resolutionRoot)
172
- return loaded.value, err
173
- }
174
-
170
+ // stripLoadedConfig is an evaluated config value with the inputs its
171
+ // evaluation read.
175
172
  type stripLoadedConfig struct {
173
+ // complete concerns resolution capability, independently of per-input stability.
174
+ complete bool
175
+
176
176
  hashes map[string]*string
177
177
  inputs []string
178
178
  realpaths map[string]*string
179
179
  value any
180
180
  }
181
181
 
182
+ // loadStripConfigFileWithInputs loads and deserializes a strip config file at
183
+ // location together with the inputs its evaluation read. The format is
184
+ // determined by extension: .json is parsed natively; .js/.cjs/.mjs run through
185
+ // a Node subprocess; .ts/.cts/.mts run through ttsx.
186
+ //
187
+ // resolutionRoot is the project directory the TypeScript branch anchors its
188
+ // toolchain resolution on when the config file's own ancestry answers nothing;
189
+ // see stripConfigToolAnchors. The JSON and JS branches spawn no ttsx and
190
+ // ignore it.
182
191
  func loadStripConfigFileWithInputs(location, resolutionRoot string) (stripLoadedConfig, error) {
183
192
  ext := strings.ToLower(filepath.Ext(location))
184
193
  switch ext {
@@ -189,7 +198,7 @@ func loadStripConfigFileWithInputs(location, resolutionRoot string) (stripLoaded
189
198
  }
190
199
  value, err := parseStripJSONConfigFile(location, body)
191
200
  digest := fmt.Sprintf("%x", sha256.Sum256(body))
192
- return stripLoadedConfig{hashes: map[string]*string{location: &digest}, inputs: []string{location}, realpaths: map[string]*string{location: stripPhysicalHostInput(location)}, value: value}, err
201
+ return stripLoadedConfig{complete: true, hashes: map[string]*string{location: &digest}, inputs: []string{location}, realpaths: map[string]*string{location: stripPhysicalHostInput(location)}, value: value}, err
193
202
  case ".js", ".cjs", ".mjs":
194
203
  return loadStripScriptConfigFileWithInputs(location)
195
204
  case ".ts", ".cts", ".mts":
@@ -282,17 +291,6 @@ func stripResolveHostInputLinkAncestor(location string) (string, bool) {
282
291
  }
283
292
  }
284
293
 
285
- // loadStripJSONConfigFile reads and JSON-parses a strip config file. A leading
286
- // UTF-8 BOM is stripped before parsing so files saved by Windows editors are
287
- // accepted.
288
- func loadStripJSONConfigFile(location string) (any, error) {
289
- body, err := os.ReadFile(location)
290
- if err != nil {
291
- return nil, fmt.Errorf("@ttsc/strip: read config file %s: %w", location, err)
292
- }
293
- return parseStripJSONConfigFile(location, body)
294
- }
295
-
296
294
  func parseStripJSONConfigFile(location string, body []byte) (any, error) {
297
295
  body = bytes.TrimPrefix(body, []byte{0xEF, 0xBB, 0xBF})
298
296
  var out any
@@ -303,232 +301,20 @@ func parseStripJSONConfigFile(location string, body []byte) (any, error) {
303
301
  }
304
302
 
305
303
  // stripScriptLoaderSource is the inline Node.js script used by
306
- // loadStripScriptConfigFile to evaluate a .js/.cjs/.mjs strip config and
304
+ // loadStripScriptConfigFileWithInputs to evaluate a .js/.cjs/.mjs strip config and
307
305
  // serialize the result to stdout as JSON.
308
306
  const stripScriptLoaderSource = `
309
- const nodeModule = require("node:module");
310
- const { createRequire, isBuiltin, registerHooks } = nodeModule;
311
- const crypto = require("node:crypto");
312
- const fs = require("node:fs");
313
- const path = require("node:path");
314
- const { fileURLToPath, pathToFileURL } = require("node:url");
315
- const inputs = new Set();
316
- const hashes = new Map();
317
- const realpaths = new Map();
318
- const signatures = new Map();
319
- const unstableHashes = new Set();
320
-
321
- function existingFile(file) {
322
- try { return fs.statSync(file).isFile(); }
323
- catch { return false; }
324
- }
325
-
326
- function missingPathError(error) {
327
- return error && (error.code === "ENOENT" || error.code === "ENOTDIR");
328
- }
329
-
330
- function inputMetadataSignature(file) {
331
- const requested = path.resolve(file);
332
- let current = requested;
333
- for (;;) {
334
- try {
335
- const link = fs.lstatSync(current, { bigint: true });
336
- let target = link;
337
- if (link.isSymbolicLink()) {
338
- try { target = fs.statSync(current, { bigint: true }); }
339
- catch { return undefined; }
340
- }
341
- return [path.relative(current, requested), link.dev, link.ino, link.mode, link.size, link.mtimeNs, link.ctimeNs, target.dev, target.ino, target.mode, target.size, target.mtimeNs, target.ctimeNs].join(":");
342
- } catch (error) {
343
- if (!missingPathError(error)) return undefined;
344
- const parent = path.dirname(current);
345
- if (parent === current) return undefined;
346
- current = parent;
347
- }
348
- }
349
- }
350
-
351
- function recordInput(file) {
352
- file = path.resolve(file);
353
- inputs.add(file);
354
- if (unstableHashes.has(file)) return;
355
- const beforeSignature = inputMetadataSignature(file);
356
- let observed;
357
- let observedRealpath;
358
- try { observed = fs.statSync(file).isDirectory() ? crypto.createHash("sha256").update("ttsc:host-input:directory\0").digest("hex") : crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
359
- catch { observed = null; }
360
- try { observedRealpath = fs.realpathSync.native(file); }
361
- catch { observedRealpath = null; }
362
- const afterSignature = inputMetadataSignature(file);
363
- if (beforeSignature === undefined || afterSignature === undefined || beforeSignature !== afterSignature || (signatures.has(file) && signatures.get(file) !== afterSignature) || (hashes.has(file) && hashes.get(file) !== observed) || (realpaths.has(file) && realpaths.get(file) !== observedRealpath)) {
364
- hashes.delete(file);
365
- realpaths.delete(file);
366
- signatures.delete(file);
367
- unstableHashes.add(file);
368
- return;
369
- }
370
- signatures.set(file, afterSignature);
371
- hashes.set(file, observed);
372
- realpaths.set(file, observedRealpath);
373
- }
374
-
375
- function recordFile(file) {
376
- const resolvedFile = path.resolve(file);
377
- recordInput(resolvedFile);
378
- for (let directory = path.dirname(resolvedFile);;) {
379
- const manifest = path.join(directory, "package.json");
380
- recordInput(manifest);
381
- if (existingFile(manifest)) {
382
- break;
383
- }
384
- const parent = path.dirname(directory);
385
- if (parent === directory) {
386
- break;
387
- }
388
- directory = parent;
389
- }
390
- }
391
-
392
- function recordPackageManifests(file) {
393
- for (let directory = path.dirname(path.resolve(file));;) {
394
- const manifest = path.join(directory, "package.json");
395
- recordInput(manifest);
396
- if (existingFile(manifest)) return;
397
- const parent = path.dirname(directory);
398
- if (parent === directory) return;
399
- directory = parent;
400
- }
401
- }
402
-
403
- const moduleProbeExtensions = [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json", ".node"];
404
- function moduleCandidates(base) {
405
- return [
406
- base,
407
- ...moduleProbeExtensions.map((extension) => base + extension),
408
- path.join(base, "package.json"),
409
- ...moduleProbeExtensions.map((extension) => path.join(base, "index" + extension)),
410
- ];
411
- }
412
- const recordedModuleBases = new Set();
413
- function recordManifestTargets(value, directory, allowBare = false) {
414
- if (typeof value === "string") {
415
- if (value !== "" && (allowBare || value.startsWith("./") || value.startsWith("../"))) recordModuleCandidates(path.resolve(directory, value));
416
- return;
417
- }
418
- if (Array.isArray(value)) {
419
- for (const item of value) recordManifestTargets(item, directory, allowBare);
420
- return;
421
- }
422
- if (value && typeof value === "object") {
423
- for (const item of Object.values(value)) recordManifestTargets(item, directory, allowBare);
424
- }
425
- }
426
- function recordModuleCandidates(base) {
427
- const resolvedBase = path.resolve(base);
428
- if (recordedModuleBases.has(resolvedBase)) return;
429
- recordedModuleBases.add(resolvedBase);
430
- for (const candidate of moduleCandidates(resolvedBase)) recordInput(candidate);
431
- try {
432
- const manifest = JSON.parse(fs.readFileSync(path.join(resolvedBase, "package.json"), "utf8").replace(/^\uFEFF/, ""));
433
- recordManifestTargets(manifest.exports, resolvedBase);
434
- recordManifestTargets(manifest.module, resolvedBase, true);
435
- recordManifestTargets(manifest.main, resolvedBase, true);
436
- } catch {}
437
- }
438
- function candidateSelected(base, resolvedFile) {
439
- for (const candidate of moduleCandidates(base)) {
440
- try {
441
- const canonical = fs.realpathSync.native(candidate);
442
- const relative = path.relative(canonical, resolvedFile);
443
- if (relative === "" || (fs.statSync(canonical).isDirectory() && relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative))) return true;
444
- } catch {}
445
- }
446
- return false;
447
- }
448
- function localBases(specifier, parentDirectory) {
449
- if (specifier.startsWith("file:")) return [fileURLToPath(specifier)];
450
- const raw = path.resolve(parentDirectory, specifier);
451
- const suffixStart = specifier.search(/[?#]/);
452
- if (suffixStart === -1) return [raw];
453
- const pathname = specifier.slice(0, suffixStart);
454
- return pathname === "" ? [raw] : [...new Set([raw, path.resolve(parentDirectory, pathname)])];
455
- }
456
- function recordResolutionCandidates(specifier, parentURL, resolvedURL) {
457
- if (typeof parentURL !== "string" || !parentURL.startsWith("file:")) return;
458
- const parentDirectory = path.dirname(fileURLToPath(parentURL));
459
- let resolvedFile;
460
- try {
461
- resolvedFile = typeof resolvedURL === "string" && resolvedURL.startsWith("file:")
462
- ? fs.realpathSync.native(fileURLToPath(resolvedURL))
463
- : undefined;
464
- } catch {}
465
- if (specifier.startsWith(".") || path.isAbsolute(specifier) || specifier.startsWith("file:")) {
466
- try {
467
- for (const base of localBases(specifier, parentDirectory)) {
468
- recordPackageManifests(base);
469
- let exact = false;
470
- try { exact = resolvedFile === undefined ? fs.statSync(base).isFile() : fs.realpathSync.native(base) === resolvedFile; } catch {}
471
- if (exact) recordInput(base);
472
- else recordModuleCandidates(base);
473
- }
474
- } catch {}
475
- return;
476
- }
477
- if (isBuiltin(specifier) || specifier.startsWith("#")) return;
478
- const parts = specifier.split("/");
479
- const packageParts = parts[0].startsWith("@") ? parts.slice(0, 2) : parts.slice(0, 1);
480
- if (packageParts.some((part) => part === undefined || part === "")) return;
481
- const packageName = packageParts.join("/");
482
- const subpath = parts.slice(packageParts.length);
483
- const searchPaths = createRequire(parentURL).resolve.paths(specifier) ?? [];
484
- for (const searchPath of searchPaths) {
485
- const packageDirectory = path.join(searchPath, packageName);
486
- recordModuleCandidates(packageDirectory);
487
- if (subpath.length !== 0) recordModuleCandidates(path.join(packageDirectory, ...subpath));
488
- if (resolvedFile !== undefined && candidateSelected(packageDirectory, resolvedFile)) break;
489
- }
490
- }
491
-
492
- recordFile(process.argv[1]);
493
- registerHooks({
494
- resolve(specifier, context, nextResolve) {
495
- recordResolutionCandidates(specifier, context.parentURL, undefined);
496
- const resolved = nextResolve(specifier, context);
497
- const url = typeof resolved === "string" ? resolved : resolved && resolved.url;
498
- recordResolutionCandidates(specifier, context.parentURL, url);
499
- if (typeof url === "string" && url.startsWith("file:")) {
500
- recordFile(fileURLToPath(url));
501
- }
502
- return resolved;
503
- },
504
- });
505
-
506
- // The hook above never sees a require() made from inside a CommonJS module the
507
- // ESM loader evaluated, which on Node 22 is every require the config makes:
508
- // module.registerHooks observes the import() of that module and nothing within
509
- // it. A config's own dependencies would then be reported without the candidates
510
- // that decide them, so a spelling appearing later could change what the config
511
- // resolves to with nothing in the envelope to notice it (samchon/ttsc#1280).
512
- // Wrapping the CommonJS resolver records the same two observations the hook
513
- // does, on the graph the hook cannot reach.
514
- const nextResolveFilename = nodeModule._resolveFilename;
515
- nodeModule._resolveFilename = function resolveFilename(request, parent, isMain, options) {
516
- // _resolveFilename is an internal entry point anything may call, so a
517
- // non-string request arrives here as readily as a specifier does. Reading it
518
- // would replace Node's own argument error with a TypeError from this loader.
519
- if (typeof request !== "string") {
520
- return nextResolveFilename.call(this, request, parent, isMain, options);
521
- }
522
- const parentFile = parent && typeof parent.filename === "string" ? parent.filename : undefined;
523
- const parentURL = parentFile === undefined ? undefined : pathToFileURL(parentFile).href;
524
- recordResolutionCandidates(request, parentURL, undefined);
525
- const resolved = nextResolveFilename.call(this, request, parent, isMain, options);
526
- if (path.isAbsolute(resolved)) {
527
- recordResolutionCandidates(request, parentURL, pathToFileURL(resolved).href);
528
- recordFile(resolved);
529
- }
530
- return resolved;
531
- };
307
+ const { pathToFileURL } = require("node:url");
308
+ // Which inputs a resolution read is the one rule ttsc owns
309
+ // (resolutioninputs.Recorder), evaluated before any hook is installed.
310
+ const { createResolutionInputRecorder, observeResolutions } = RESOLUTION_INPUT_RECORDER;
311
+ const recorder = createResolutionInputRecorder({ extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json", ".node"] });
312
+
313
+ recorder.recordFile(process.argv[1]);
314
+ // Every resolution the config makes is recorded: through a resolve hook, and
315
+ // on a runtime whose require.resolve bypasses the hooks, through the one
316
+ // entry point it reaches (resolutioninputs.Recorder, samchon/ttsc#1523).
317
+ observeResolutions(recorder);
532
318
 
533
319
  (async () => {
534
320
  const mod = await import(pathToFileURL(process.argv[1]).href);
@@ -545,8 +331,8 @@ nodeModule._resolveFilename = function resolveFilename(request, parent, isMain,
545
331
  throw new Error("strip config file must export an object");
546
332
  }
547
333
  const serializedValue = JSON.stringify(value);
548
- for (const input of [...inputs]) recordInput(input);
549
- process.stdout.write(JSON.stringify({ value: JSON.parse(serializedValue), hashes: Object.fromEntries(hashes), inputs: [...inputs].sort(), realpaths: Object.fromEntries(realpaths) }));
334
+ const recorded = recorder.finish();
335
+ process.stdout.write(JSON.stringify({ value: JSON.parse(serializedValue), complete: recorded.complete, hashes: recorded.hashes, inputs: recorded.inputs, realpaths: recorded.realpaths }));
550
336
  })().catch((error) => {
551
337
  process.stderr.write(error && error.stack ? error.stack : String(error));
552
338
  process.exitCode = 1;
@@ -554,14 +340,9 @@ nodeModule._resolveFilename = function resolveFilename(request, parent, isMain,
554
340
  });
555
341
  `
556
342
 
557
- // loadStripScriptConfigFile evaluates a .js/.cjs/.mjs config file by running a
558
- // Node subprocess that dynamic-imports the file, resolves the default export,
559
- // and serializes the result as JSON to stdout.
560
- func loadStripScriptConfigFile(location string) (any, error) {
561
- loaded, err := loadStripScriptConfigFileWithInputs(location)
562
- return loaded.value, err
563
- }
564
-
343
+ // loadStripScriptConfigFileWithInputs evaluates a .js/.cjs/.mjs config file by
344
+ // running a Node subprocess that dynamic-imports the file, resolves the default
345
+ // export, and serializes the result and the inputs it read as JSON to stdout.
565
346
  func loadStripScriptConfigFileWithInputs(location string) (stripLoadedConfig, error) {
566
347
  node := os.Getenv("TTSC_NODE_BINARY")
567
348
  if node == "" {
@@ -576,7 +357,8 @@ func loadStripScriptConfigFileWithInputs(location string) (stripLoadedConfig, er
576
357
  // both the loader and the imported user config without using string eval.
577
358
  cmd := exec.CommandContext(ctx, node, "--input-type=commonjs", "-", location)
578
359
  cmd.Stdin = strings.NewReader(
579
- "process.argv.splice(1, 1);\n" + stripScriptLoaderSource,
360
+ "process.argv.splice(1, 1);\nconst RESOLUTION_INPUT_RECORDER = " +
361
+ resolutioninputs.CommonJSExpression() + ";\n" + stripScriptLoaderSource,
580
362
  )
581
363
  cmd.Env = stripNodeConfigLoaderEnv(location)
582
364
  // The child's stderr is human output and goes straight to this process's
@@ -601,8 +383,14 @@ func loadStripScriptConfigFileWithInputs(location string) (stripLoadedConfig, er
601
383
  return loaded, nil
602
384
  }
603
385
 
386
+ // decodeStripConfigLoaderOutput requires the value and recorder snapshot from
387
+ // the executed loader. Accepting a bare value would report complete dependency
388
+ // observations even though no observations were returned. Missing probe values
389
+ // remain legitimate nullable entries inside the snapshot maps.
604
390
  func decodeStripConfigLoaderOutput(output []byte) (stripLoadedConfig, error) {
605
391
  var envelope struct {
392
+ Complete *bool `json:"complete"`
393
+
606
394
  Error string `json:"__ttscLoaderError"`
607
395
  Hashes map[string]*string `json:"hashes"`
608
396
  Inputs []string `json:"inputs"`
@@ -615,282 +403,35 @@ func decodeStripConfigLoaderOutput(output []byte) (stripLoadedConfig, error) {
615
403
  if envelope.Error != "" {
616
404
  return stripLoadedConfig{}, fmt.Errorf("%s", envelope.Error)
617
405
  }
618
- if len(envelope.Value) == 0 {
619
- // Test/fallback launchers written against the historical payload return
620
- // the config value directly. Preserve that accepted contract while real
621
- // loaders use the envelope to carry runtime inputs.
622
- var value any
623
- if err := json.Unmarshal(output, &value); err != nil {
624
- return stripLoadedConfig{}, err
625
- }
626
- return stripLoadedConfig{value: value}, nil
406
+ if len(envelope.Value) == 0 || envelope.Complete == nil || envelope.Inputs == nil || envelope.Hashes == nil || envelope.Realpaths == nil {
407
+ return stripLoadedConfig{}, fmt.Errorf("config loader must return a value with dependency observations")
627
408
  }
628
409
  var value any
629
410
  if err := json.Unmarshal(envelope.Value, &value); err != nil {
630
411
  return stripLoadedConfig{}, err
631
412
  }
632
- return stripLoadedConfig{hashes: envelope.Hashes, inputs: envelope.Inputs, realpaths: envelope.Realpaths, value: value}, nil
413
+ return stripLoadedConfig{complete: *envelope.Complete, hashes: envelope.Hashes, inputs: envelope.Inputs, realpaths: envelope.Realpaths, value: value}, nil
633
414
  }
634
415
 
635
416
  // stripTypeScriptLoaderSource returns the TypeScript source of the ephemeral
636
417
  // loader script that ttsx executes to evaluate a TypeScript strip config file.
637
418
  // importLiteral must be a JSON-encoded relative import path (e.g.
638
419
  // `"./strip.config.ts"`) produced by json.Marshal.
639
- func stripTypeScriptLoaderSource(importLiteral string) string {
420
+ func stripTypeScriptLoaderSource(importLiteral, recorderLiteral string) string {
640
421
  return fmt.Sprintf(`// @ts-nocheck
641
- import Module, { createRequire, isBuiltin, registerHooks } from "node:module";
642
- import crypto from "node:crypto";
643
- import fs from "node:fs";
644
- import path from "node:path";
645
- import { fileURLToPath, pathToFileURL } from "node:url";
646
-
647
- const inputs = new Set<string>();
648
- const hashes = new Map<string, string | null>();
649
- const realpaths = new Map<string, string | null>();
650
- const signatures = new Map<string, string>();
651
- const unstableHashes = new Set<string>();
652
-
653
- function existingFile(file: string): boolean {
654
- try { return fs.statSync(file).isFile(); }
655
- catch { return false; }
656
- }
657
-
658
- function missingPathError(error: unknown): boolean {
659
- const code = (error as { code?: unknown } | undefined)?.code;
660
- return code === "ENOENT" || code === "ENOTDIR";
661
- }
662
-
663
- function inputMetadataSignature(file: string): string | undefined {
664
- const requested = path.resolve(file);
665
- let current = requested;
666
- for (;;) {
667
- try {
668
- const link = fs.lstatSync(current, { bigint: true });
669
- let target = link;
670
- if (link.isSymbolicLink()) {
671
- try { target = fs.statSync(current, { bigint: true }); }
672
- catch { return undefined; }
673
- }
674
- return [path.relative(current, requested), link.dev, link.ino, link.mode, link.size, link.mtimeNs, link.ctimeNs, target.dev, target.ino, target.mode, target.size, target.mtimeNs, target.ctimeNs].join(":");
675
- } catch (error) {
676
- if (!missingPathError(error)) return undefined;
677
- const parent = path.dirname(current);
678
- if (parent === current) return undefined;
679
- current = parent;
680
- }
681
- }
682
- }
683
-
684
- function recordInput(file: string): void {
685
- file = path.resolve(file);
686
- inputs.add(file);
687
- if (unstableHashes.has(file)) return;
688
- const beforeSignature = inputMetadataSignature(file);
689
- let observed: string | null;
690
- let observedRealpath: string | null;
691
- try { observed = fs.statSync(file).isDirectory() ? crypto.createHash("sha256").update("ttsc:host-input:directory\0").digest("hex") : crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
692
- catch { observed = null; }
693
- try { observedRealpath = fs.realpathSync.native(file); }
694
- catch { observedRealpath = null; }
695
- const afterSignature = inputMetadataSignature(file);
696
- if (beforeSignature === undefined || afterSignature === undefined || beforeSignature !== afterSignature || (signatures.has(file) && signatures.get(file) !== afterSignature) || (hashes.has(file) && hashes.get(file) !== observed) || (realpaths.has(file) && realpaths.get(file) !== observedRealpath)) {
697
- hashes.delete(file);
698
- realpaths.delete(file);
699
- signatures.delete(file);
700
- unstableHashes.add(file);
701
- return;
702
- }
703
- signatures.set(file, afterSignature);
704
- hashes.set(file, observed);
705
- realpaths.set(file, observedRealpath);
706
- }
707
-
708
- function recordFile(file: string): void {
709
- const resolvedFile = path.resolve(file);
710
- recordInput(resolvedFile);
711
- for (let directory = path.dirname(resolvedFile);;) {
712
- const manifest = path.join(directory, "package.json");
713
- recordInput(manifest);
714
- if (existingFile(manifest)) {
715
- break;
716
- }
717
- const parent = path.dirname(directory);
718
- if (parent === directory) {
719
- break;
720
- }
721
- directory = parent;
722
- }
723
- }
422
+ import { createRequire } from "node:module";
724
423
 
725
- function recordPackageManifests(file: string): void {
726
- for (let directory = path.dirname(path.resolve(file));;) {
727
- const manifest = path.join(directory, "package.json");
728
- recordInput(manifest);
729
- if (existingFile(manifest)) return;
730
- const parent = path.dirname(directory);
731
- if (parent === directory) return;
732
- directory = parent;
733
- }
734
- }
424
+ // Which inputs a resolution read is the one rule ttsc owns
425
+ // (resolutioninputs.Recorder), written beside this loader and required before
426
+ // any hook is installed, so the recorder itself is no input.
427
+ const recorderFile: string = %[2]s;
428
+ const { createResolutionInputRecorder, observeResolutions } = createRequire(recorderFile)(recorderFile);
429
+ const recorder = createResolutionInputRecorder({ extensions: [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json", ".node"] });
735
430
 
736
- const moduleProbeExtensions = [".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".json", ".node"] as const;
737
- const jsToTsProbeExtensions = new Map<string, readonly string[]>([
738
- [".js", [".ts", ".tsx"]],
739
- [".jsx", [".tsx"]],
740
- [".mjs", [".mts"]],
741
- [".cjs", [".cts"]],
742
- ]);
743
- function sourceSubstitutionCandidates(base: string): string[] {
744
- const extension = path.extname(base).toLowerCase();
745
- const substitutions = jsToTsProbeExtensions.get(extension);
746
- if (substitutions === undefined) return [];
747
- const stem = base.slice(0, base.length - extension.length);
748
- return substitutions.map((candidate) => stem + candidate);
749
- }
750
- function moduleCandidates(base: string): string[] {
751
- return [
752
- base,
753
- ...sourceSubstitutionCandidates(base),
754
- ...moduleProbeExtensions.map((extension) => base + extension),
755
- path.join(base, "package.json"),
756
- ...moduleProbeExtensions.map((extension) => path.join(base, "index" + extension)),
757
- ];
758
- }
759
- const recordedModuleBases = new Set<string>();
760
- function recordManifestTargets(value: unknown, directory: string, allowBare: boolean = false): void {
761
- if (typeof value === "string") {
762
- if (value !== "" && (allowBare || value.startsWith("./") || value.startsWith("../"))) recordModuleCandidates(path.resolve(directory, value));
763
- return;
764
- }
765
- if (Array.isArray(value)) {
766
- for (const item of value) recordManifestTargets(item, directory, allowBare);
767
- return;
768
- }
769
- if (value !== null && typeof value === "object") {
770
- for (const item of Object.values(value)) recordManifestTargets(item, directory, allowBare);
771
- }
772
- }
773
- function recordModuleCandidates(base: string): void {
774
- const resolvedBase = path.resolve(base);
775
- if (recordedModuleBases.has(resolvedBase)) return;
776
- recordedModuleBases.add(resolvedBase);
777
- for (const candidate of moduleCandidates(resolvedBase)) recordInput(candidate);
778
- try {
779
- const manifest = JSON.parse(fs.readFileSync(path.join(resolvedBase, "package.json"), "utf8").replace(/^\uFEFF/, ""));
780
- recordManifestTargets(manifest.exports, resolvedBase);
781
- recordManifestTargets(manifest.module, resolvedBase, true);
782
- recordManifestTargets(manifest.main, resolvedBase, true);
783
- } catch {}
784
- }
785
- function candidateSelected(base: string, resolvedFile: string): boolean {
786
- for (const candidate of moduleCandidates(base)) {
787
- try {
788
- const canonical = fs.realpathSync.native(candidate);
789
- const relative = path.relative(canonical, resolvedFile);
790
- if (relative === "" || (fs.statSync(canonical).isDirectory() && relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative))) return true;
791
- } catch {}
792
- }
793
- return false;
794
- }
795
- function localBases(specifier: string, parentDirectory: string): string[] {
796
- if (specifier.startsWith("file:")) return [fileURLToPath(specifier)];
797
- const raw = path.resolve(parentDirectory, specifier);
798
- const suffixStart = specifier.search(/[?#]/);
799
- if (suffixStart === -1) return [raw];
800
- const pathname = specifier.slice(0, suffixStart);
801
- return pathname === "" ? [raw] : [...new Set([raw, path.resolve(parentDirectory, pathname)])];
802
- }
803
- function recordResolutionCandidates(specifier: string, parentURL: string | undefined, resolvedURL: string | undefined): void {
804
- if (typeof parentURL !== "string" || !parentURL.startsWith("file:")) return;
805
- const parentDirectory = path.dirname(fileURLToPath(parentURL));
806
- let resolvedFile: string | undefined;
807
- try {
808
- resolvedFile = typeof resolvedURL === "string" && resolvedURL.startsWith("file:")
809
- ? fs.realpathSync.native(fileURLToPath(resolvedURL))
810
- : undefined;
811
- } catch {}
812
- if (specifier.startsWith(".") || path.isAbsolute(specifier) || specifier.startsWith("file:")) {
813
- try {
814
- for (const base of localBases(specifier, parentDirectory)) {
815
- recordPackageManifests(base);
816
- let exact = false;
817
- try { exact = resolvedFile === undefined ? fs.statSync(base).isFile() : fs.realpathSync.native(base) === resolvedFile; } catch {}
818
- if (exact) recordInput(base);
819
- else recordModuleCandidates(base);
820
- }
821
- } catch {}
822
- return;
823
- }
824
- if (isBuiltin(specifier) || specifier.startsWith("#")) return;
825
- const parts = specifier.split("/");
826
- const packageParts = parts[0]!.startsWith("@") ? parts.slice(0, 2) : parts.slice(0, 1);
827
- if (packageParts.some((part) => part === undefined || part === "")) return;
828
- const packageName = packageParts.join("/");
829
- const subpath = parts.slice(packageParts.length);
830
- const searchPaths = createRequire(parentURL).resolve.paths(specifier) ?? [];
831
- for (const searchPath of searchPaths) {
832
- const packageDirectory = path.join(searchPath, packageName);
833
- recordModuleCandidates(packageDirectory);
834
- if (subpath.length !== 0) recordModuleCandidates(path.join(packageDirectory, ...subpath));
835
- if (resolvedFile !== undefined && candidateSelected(packageDirectory, resolvedFile)) break;
836
- }
837
- }
838
-
839
- registerHooks({
840
- resolve(specifier, context, nextResolve) {
841
- recordResolutionCandidates(specifier, context.parentURL, undefined);
842
- const resolved = nextResolve(specifier, context);
843
- const url = typeof resolved === "string" ? resolved : resolved?.url;
844
- recordResolutionCandidates(specifier, context.parentURL, url);
845
- if (typeof url === "string" && url.startsWith("file:")) {
846
- recordFile(fileURLToPath(url));
847
- }
848
- return resolved;
849
- },
850
- });
851
-
852
- // The hook above never sees a require() made from inside a CommonJS module the
853
- // ESM loader evaluated, which on Node 22 is every require the config makes:
854
- // module.registerHooks observes the import() of that module and nothing within
855
- // it. A config's own dependencies would then be reported without the candidates
856
- // that decide them, so a spelling appearing later could change what the config
857
- // resolves to with nothing in the envelope to notice it (samchon/ttsc#1280).
858
- // Wrapping the CommonJS resolver records the same two observations the hook
859
- // does, on the graph the hook cannot reach.
860
- const moduleInternals = Module as unknown as {
861
- _resolveFilename(
862
- request: string,
863
- parent: { filename?: string | null } | null | undefined,
864
- isMain: boolean,
865
- options?: unknown,
866
- ): string;
867
- };
868
- const nextResolveFilename = moduleInternals._resolveFilename;
869
- moduleInternals._resolveFilename = function resolveFilename(
870
- this: unknown,
871
- request: string,
872
- parent: { filename?: string | null } | null | undefined,
873
- isMain: boolean,
874
- options?: unknown,
875
- ): string {
876
- // _resolveFilename is an internal entry point anything may call, so a
877
- // non-string request arrives here as readily as a specifier does. Reading it
878
- // would replace Node's own argument error with a TypeError from this loader.
879
- if (typeof request !== "string") {
880
- return nextResolveFilename.call(this, request, parent, isMain, options);
881
- }
882
- const parentURL =
883
- typeof parent?.filename === "string"
884
- ? pathToFileURL(parent.filename).href
885
- : undefined;
886
- recordResolutionCandidates(request, parentURL, undefined);
887
- const resolved = nextResolveFilename.call(this, request, parent, isMain, options);
888
- if (path.isAbsolute(resolved)) {
889
- recordResolutionCandidates(request, parentURL, pathToFileURL(resolved).href);
890
- recordFile(resolved);
891
- }
892
- return resolved;
893
- };
431
+ // Every resolution the config makes is recorded: through a resolve hook, and
432
+ // on a runtime whose require.resolve bypasses the hooks, through the one
433
+ // entry point it reaches (resolutioninputs.Recorder, samchon/ttsc#1523).
434
+ observeResolutions(recorder);
894
435
 
895
436
  declare const process: {
896
437
  exitCode?: number;
@@ -906,7 +447,7 @@ declare const process: {
906
447
  // left for a trailing handler to settle.
907
448
  (async () => {
908
449
  try {
909
- const importedConfig = await import(%s);
450
+ const importedConfig = await import(%[1]s);
910
451
  let current: unknown = importedConfig;
911
452
  for (let i = 0; i < 8; i++) {
912
453
  if (current !== null && typeof current === "object" && Object.prototype.hasOwnProperty.call(current as Record<string, unknown>, "default")) {
@@ -922,8 +463,8 @@ declare const process: {
922
463
  throw new Error("strip config file must export an object");
923
464
  }
924
465
  const serializedValue = JSON.stringify(current);
925
- for (const input of [...inputs]) recordInput(input);
926
- process.stdout.write(JSON.stringify({ value: JSON.parse(serializedValue), hashes: Object.fromEntries(hashes), inputs: [...inputs].sort(), realpaths: Object.fromEntries(realpaths) }));
466
+ const recorded = recorder.finish();
467
+ process.stdout.write(JSON.stringify({ value: JSON.parse(serializedValue), complete: recorded.complete, hashes: recorded.hashes, inputs: recorded.inputs, realpaths: recorded.realpaths }));
927
468
  } catch (error) {
928
469
  process.stderr.write(error instanceof Error && error.stack ? error.stack : String(error));
929
470
  // The stack above is for the reader. This is for the caller: the parent
@@ -939,10 +480,10 @@ declare const process: {
939
480
  );
940
481
  }
941
482
  })();
942
- `, importLiteral)
483
+ `, importLiteral, recorderLiteral)
943
484
  }
944
485
 
945
- // loadStripTypeScriptConfigFile evaluates a .ts/.cts/.mts config file by writing
486
+ // loadStripTypeScriptConfigFileWithInputs evaluates a .ts/.cts/.mts config file by writing
946
487
  // an ephemeral loader script and tsconfig into a temp directory, symlinking the
947
488
  // nearest node_modules, then running ttsx.
948
489
  //
@@ -954,11 +495,6 @@ declare const process: {
954
495
  // Both tools this spawns — the launcher and the compiler handed to it — are
955
496
  // resolved from the project rather than from the process environment alone;
956
497
  // see stripConfigToolAnchors.
957
- func loadStripTypeScriptConfigFile(location, resolutionRoot string) (any, error) {
958
- loaded, err := loadStripTypeScriptConfigFileWithInputs(location, resolutionRoot)
959
- return loaded.value, err
960
- }
961
-
962
498
  func loadStripTypeScriptConfigFileWithInputs(location, resolutionRoot string) (stripLoadedConfig, error) {
963
499
  tempDir, err := os.MkdirTemp(stripLoaderTempBase(location, os.TempDir()), "ttsc-strip-config-")
964
500
  if err != nil {
@@ -980,7 +516,15 @@ func loadStripTypeScriptConfigFileWithInputs(location, resolutionRoot string) (s
980
516
  if err != nil {
981
517
  return stripLoadedConfig{}, fmt.Errorf("@ttsc/strip: encode config import %s: %w", location, err)
982
518
  }
983
- if err := os.WriteFile(loader, []byte(stripTypeScriptLoaderSource(string(importLiteral))), 0o644); err != nil {
519
+ recorder := filepath.Join(tempDir, "ttsc-resolution-inputs.cjs")
520
+ if err := os.WriteFile(recorder, []byte(resolutioninputs.Recorder), 0o644); err != nil {
521
+ return stripLoadedConfig{}, fmt.Errorf("@ttsc/strip: write config loader: %w", err)
522
+ }
523
+ recorderLiteral, err := json.Marshal(recorder)
524
+ if err != nil {
525
+ return stripLoadedConfig{}, fmt.Errorf("@ttsc/strip: encode config loader recorder %s: %w", recorder, err)
526
+ }
527
+ if err := os.WriteFile(loader, []byte(stripTypeScriptLoaderSource(string(importLiteral), string(recorderLiteral))), 0o644); err != nil {
984
528
  return stripLoadedConfig{}, fmt.Errorf("@ttsc/strip: write config loader: %w", err)
985
529
  }
986
530
  if err := os.WriteFile(tsconfig, []byte(stripTypeScriptLoaderTsconfig(loader, location, tempDir)), 0o644); err != nil {
@@ -1075,11 +619,8 @@ func stripTypeScriptLoaderTsconfig(loader, location, outDir string) string {
1075
619
  // packages/banner/driver/banner.go and packages/strip/driver/config.go. #1169
1076
620
  // decided against extracting it — the only home the three modules could share
1077
621
  // is the public `packages/ttsc/driver` seam, and packages/lint's go.mod
1078
- // deliberately requires no in-tree ttsc module — and replaced the checklist
1079
- // with a gate: `scripts/ci/config-loader-copies.cjs` compares every function
1080
- // between these markers across all three copies on every pull request, so
1081
- // editing one and not the others fails by name. That file's header carries the
1082
- // full decision and the rules for changing this block.
622
+ // deliberately requires no in-tree ttsc module — so a change to one copy must
623
+ // be made to all three.
1083
624
  //
1084
625
  // The code between the markers must stay identical. Comments may differ, the
1085
626
  // `@ttsc/<pkg>:` error prefix may differ, and @ttsc/strip spells each name with
@@ -1223,11 +764,11 @@ func stripRealpathIfPossible(location string) string {
1223
764
  // the project being compiled, with an explicit environment variable winning
1224
765
  // and a last resort that invents no path.
1225
766
  //
1226
- // The three Go copies are held identical by the gate named at the top of this
1227
- // block. The JS original — `resolveConfigTsgo` / `resolveTtsxLauncher` in
1228
- // packages/lint/src/index.ts — is a fourth copy in another language that no Go
1229
- // gate can reach; what it owes is that both policies stay describable in one
1230
- // sentence.
767
+ // No automated check holds the three Go copies identical: a change lands in
768
+ // all three by hand, and each package's own config-loader tests exercise it.
769
+ // The JS original — `resolveConfigTsgo` / `resolveTtsxLauncher` in
770
+ // packages/lint/src/index.ts — is a fourth copy in another language; what it
771
+ // owes is that both policies stay describable in one sentence.
1231
772
  //
1232
773
  // The environment alone is the wrong place to ask. `ttsx` exports
1233
774
  // TTSC_TSGO_BINARY and TTSC_TTSX_BINARY to its own descendants, so a host
@@ -1549,8 +1090,8 @@ func stripSetEnv(env []string, key, value string) []string {
1549
1090
  // payload channel when it stops on an error it can name.
1550
1091
  //
1551
1092
  // The loader's stack goes to this process's stderr as it runs, which is where a
1552
- // reader wants it. But the *reason* — "config file must export an object with a
1553
- // non-empty text string" — is a fact about the user's config, and a caller
1093
+ // reader wants it. But the reason, such as a non-object config export, is a
1094
+ // fact about the user's config, and a caller
1554
1095
  // deserves it in the error rather than having to go find it in the log. So it
1555
1096
  // travels as data through the same stdout the payload uses, and only a
1556
1097
  // well-formed envelope is honoured: anything else leaves the process status to