@stateward/core 1.2.2 → 1.3.1

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.
Files changed (75) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/fingerprints.d.ts +3 -1
  4. package/dist/backend/fingerprints.js +198 -9
  5. package/dist/backend/program-record.d.ts +7 -0
  6. package/dist/backend/program-size.d.ts +32 -0
  7. package/dist/backend/program-size.js +166 -0
  8. package/dist/backend/typescript6.d.ts +62 -32
  9. package/dist/backend/typescript6.js +1615 -164
  10. package/dist/baseline.d.ts +1 -1
  11. package/dist/baseline.js +14 -10
  12. package/dist/cache.d.ts +92 -4
  13. package/dist/cache.js +257 -68
  14. package/dist/checker.d.ts +28 -3
  15. package/dist/checker.js +42 -8
  16. package/dist/class-id.d.ts +34 -0
  17. package/dist/class-id.js +93 -0
  18. package/dist/code-text.d.ts +8 -0
  19. package/dist/code-text.js +66 -0
  20. package/dist/config-file.js +7 -5
  21. package/dist/config.d.ts +10 -2
  22. package/dist/config.js +490 -48
  23. package/dist/define.d.ts +8 -2
  24. package/dist/disk-cache.d.ts +34 -2
  25. package/dist/disk-cache.js +82 -15
  26. package/dist/engine.d.ts +64 -3
  27. package/dist/engine.js +474 -59
  28. package/dist/fact-lines.d.ts +31 -0
  29. package/dist/fact-lines.js +197 -0
  30. package/dist/facts-versions.d.ts +27 -0
  31. package/dist/facts-versions.js +99 -0
  32. package/dist/fixes.js +4 -1
  33. package/dist/ignores.d.ts +11 -0
  34. package/dist/ignores.js +74 -27
  35. package/dist/implementation.d.ts +0 -6
  36. package/dist/implementation.js +0 -17
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.js +12 -7
  39. package/dist/internal.d.ts +13 -6
  40. package/dist/internal.js +7 -3
  41. package/dist/journal.d.ts +40 -0
  42. package/dist/journal.js +197 -0
  43. package/dist/lazy.d.ts +8 -1
  44. package/dist/lazy.js +27 -2
  45. package/dist/ledger.d.ts +2 -2
  46. package/dist/ledger.js +2 -2
  47. package/dist/memory-plan.d.ts +121 -0
  48. package/dist/memory-plan.js +174 -0
  49. package/dist/off-by-default.d.ts +13 -0
  50. package/dist/off-by-default.js +15 -0
  51. package/dist/options.d.ts +21 -5
  52. package/dist/options.js +22 -7
  53. package/dist/package-facts.d.ts +211 -17
  54. package/dist/package-facts.js +520 -38
  55. package/dist/plan.d.ts +1 -1
  56. package/dist/plan.js +7 -2
  57. package/dist/release.d.ts +12 -21
  58. package/dist/release.js +26 -38
  59. package/dist/renamed.d.ts +22 -3
  60. package/dist/renamed.js +50 -16
  61. package/dist/rollout.js +7 -4
  62. package/dist/severity.d.ts +1 -1
  63. package/dist/severity.js +17 -3
  64. package/dist/test-runner.d.ts +18 -0
  65. package/dist/test-runner.js +483 -0
  66. package/dist/testing.d.ts +3 -3
  67. package/dist/testing.js +5 -5
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +60 -38
  70. package/dist/types.d.ts +704 -20
  71. package/dist/unread.d.ts +90 -0
  72. package/dist/unread.js +405 -0
  73. package/dist/vocabulary.d.ts +1 -1
  74. package/dist/vocabulary.js +1 -1
  75. package/package.json +4 -2
@@ -0,0 +1,37 @@
1
+ import type { Plugin, PluginAnalysis } from "./types.js";
2
+ /** An analysis's name: kebab-case, like a rule's key (`throws`). */
3
+ export declare const ANALYSIS_NAME: RegExp;
4
+ /**
5
+ * What is wrong with a project rule's `reads`, as the end of a message, or undefined when it is
6
+ * absent or a list of analysis ids.
7
+ */
8
+ export declare function readsProblem(value: unknown): string | undefined;
9
+ /** Where a read id leads: the analysis, or why the rule cannot have it. */
10
+ export type ReadTarget = {
11
+ readonly kind: "found";
12
+ readonly plugin: string;
13
+ readonly analysis: PluginAnalysis;
14
+ }
15
+ /** The publisher is not in the config's plugins. */
16
+ | {
17
+ readonly kind: "no-plugin";
18
+ readonly plugin: string;
19
+ }
20
+ /** The publisher is there but publishes no analysis by that name (an older version of it). */
21
+ | {
22
+ readonly kind: "no-analysis";
23
+ readonly plugin: string;
24
+ readonly name: string;
25
+ };
26
+ /** Finds the analysis `id` names among the config's plugins. */
27
+ export declare function readTarget(plugins: readonly Plugin[], id: string): ReadTarget;
28
+ /** A rule that reads an analysis the config cannot give it: the "not checked" finding's text. */
29
+ export declare function missingAnalysis(ruleId: string, id: string, target: Exclude<ReadTarget, {
30
+ kind: "found";
31
+ }>): {
32
+ message: string;
33
+ hint: string;
34
+ };
35
+ /** The config error for a rule that reads an analysis its loaded publisher does not publish. */
36
+ export declare function unpublishedRead(plugin: string, key: string, id: string, publisher: string): string;
37
+ //# sourceMappingURL=analyses.d.ts.map
@@ -0,0 +1,57 @@
1
+ /*
2
+ * Analyses a pack publishes for the project rules of any pack: the names a
3
+ * plugin may give one, the ids a rule reads one by, and where a read id leads in the config.
4
+ */
5
+ /** An analysis's name: kebab-case, like a rule's key (`throws`). */
6
+ export const ANALYSIS_NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
7
+ /** An analysis's id as a rule reads it: `"<plugin>/<name>"` (`errors/throws`). */
8
+ const ANALYSIS_ID = /^[^/\s]+\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
9
+ /**
10
+ * What is wrong with a project rule's `reads`, as the end of a message, or undefined when it is
11
+ * absent or a list of analysis ids.
12
+ */
13
+ export function readsProblem(value) {
14
+ if (value === undefined)
15
+ return undefined;
16
+ if (!Array.isArray(value)) {
17
+ return `reads must be a list of analysis ids, like ["errors/throws"]`;
18
+ }
19
+ for (const item of value) {
20
+ if (typeof item !== "string" || !ANALYSIS_ID.test(item)) {
21
+ return `reads: ${JSON.stringify(item)} is not an analysis id "<plugin>/<name>", like "errors/throws"`;
22
+ }
23
+ }
24
+ return undefined;
25
+ }
26
+ /** Finds the analysis `id` names among the config's plugins. */
27
+ export function readTarget(plugins, id) {
28
+ const slash = id.indexOf("/");
29
+ const pluginName = id.slice(0, slash);
30
+ const name = id.slice(slash + 1);
31
+ const plugin = plugins.find((one) => one.name === pluginName);
32
+ if (plugin === undefined)
33
+ return { kind: "no-plugin", plugin: pluginName };
34
+ const analyses = plugin.analyses;
35
+ const analysis = analyses !== undefined && Object.hasOwn(analyses, name) ? analyses[name] : undefined;
36
+ return analysis === undefined
37
+ ? { kind: "no-analysis", plugin: pluginName, name }
38
+ : { kind: "found", plugin: pluginName, analysis };
39
+ }
40
+ /** A rule that reads an analysis the config cannot give it: the "not checked" finding's text. */
41
+ export function missingAnalysis(ruleId, id, target) {
42
+ if (target.kind === "no-plugin") {
43
+ return {
44
+ message: `not checked: \`${ruleId}\` reads \`${id}\`, and the \`${target.plugin}\` pack is not in \`plugins\``,
45
+ hint: `add \`${target.plugin}()\` to \`plugins\``,
46
+ };
47
+ }
48
+ return {
49
+ message: `not checked: \`${ruleId}\` reads \`${id}\`, which the \`${target.plugin}\` pack in \`plugins\` does not publish`,
50
+ hint: `update the \`${target.plugin}\` pack to a version that publishes \`${target.name}\``,
51
+ };
52
+ }
53
+ /** The config error for a rule that reads an analysis its loaded publisher does not publish. */
54
+ export function unpublishedRead(plugin, key, id, publisher) {
55
+ return `plugin "${plugin}": rule "${key}" reads "${id}", which plugin "${publisher}" does not publish`;
56
+ }
57
+ //# sourceMappingURL=analyses.js.map
@@ -45,7 +45,9 @@ export declare function shapeHash(sourceFile: ts.SourceFile): string;
45
45
  * `/// <reference …/>`). The offset of a top-level `X.y = …` is not kept: the qualified id of `y`
46
46
  * counts the same-named ones before it (qualified-ids.ts), which the statements' tokens show.
47
47
  *
48
- * A function without a declared return type keeps its body: its type is inferred from it.
48
+ * A function without a declared return type keeps its body: its type is inferred from it. Unless
49
+ * it only returns JSX, `null`, `undefined` or a boolean literal (`returnedValues`, a React
50
+ * component mostly): then it keeps those values instead.
49
51
  */
50
52
  export declare function shapeText(sourceFile: ts.SourceFile): string | undefined;
51
53
  /**
@@ -12,7 +12,8 @@ import { stronglyConnectedComponents } from "../graph.js";
12
12
  * the file's *shape* (`shapeText`), with how each import resolved (adding a file can change
13
13
  * where an import goes);
14
14
  * - everything global: TypeScript's lib files, script files (no import or export), files with
15
- * `declare global` or `declare module "…"`, and the compiler options;
15
+ * `declare global` or `declare module "…"` (an own module's blocks alone when they name nothing
16
+ * of its scope: `augmentationText`), and the compiler options;
16
17
  * - the package each file belongs to (`TypeQueries.packageOf`): a rule may tell a library by the
17
18
  * name in its package.json, so renaming a package changes what it decides;
18
19
  * - for an own file, the packages its package.json depends on (`TypeQueries.dependenciesOf`): a
@@ -214,6 +215,68 @@ export function shapeHash(sourceFile) {
214
215
  return hash;
215
216
  }
216
217
  const TYPESCRIPT_SOURCE = /\.(?:[cm]?ts|tsx)$/;
218
+ /** What a returned expression is, when its type does not depend on anything around it. */
219
+ function returnedValue(expression) {
220
+ let at = expression;
221
+ while (ts.isParenthesizedExpression(at))
222
+ at = at.expression;
223
+ if (ts.isJsxElement(at) || ts.isJsxSelfClosingElement(at) || ts.isJsxFragment(at))
224
+ return "jsx";
225
+ if (at.kind === ts.SyntaxKind.NullKeyword)
226
+ return "null";
227
+ if (at.kind === ts.SyntaxKind.TrueKeyword)
228
+ return "true";
229
+ if (at.kind === ts.SyntaxKind.FalseKeyword)
230
+ return "false";
231
+ if (ts.isIdentifier(at) && at.text === "undefined")
232
+ return "undefined";
233
+ return undefined;
234
+ }
235
+ /**
236
+ * The values a function body without a declared return type returns, sorted and each once, when
237
+ * they alone decide its inferred return type (a React component's, mostly): an expression body
238
+ * that is one of them, or a block whose last statement is a `return`, with no `yield`, no bare
239
+ * `return;`, no binding named `undefined`, and every `return` giving JSX (an element, a fragment,
240
+ * a self-closing element), `null`, `undefined`, `true` or `false`. Undefined otherwise: the body
241
+ * then stays in the shape. The type of a JSX expression does not depend on what it holds, and the
242
+ * end of such a body cannot be reached, so the type is the union of these values.
243
+ */
244
+ function returnedValues(body) {
245
+ if (!ts.isBlock(body))
246
+ return returnedValue(body);
247
+ const last = body.statements.at(-1);
248
+ if (last === undefined || !ts.isReturnStatement(last))
249
+ return undefined;
250
+ const values = new Set();
251
+ /** Whether `node` keeps the return type decided by `values`; adds the values it returns. */
252
+ const decides = (node) => {
253
+ if (ts.isFunctionLike(node)) {
254
+ // Its own returns and yields are its own; its name and parameters are still this body's.
255
+ const own = "body" in node ? node.body : undefined;
256
+ return !ts.forEachChild(node, (child) => (child === own ? undefined : !decides(child)));
257
+ }
258
+ if (ts.isYieldExpression(node))
259
+ return false;
260
+ if ((ts.isVariableDeclaration(node) ||
261
+ ts.isParameter(node) ||
262
+ ts.isBindingElement(node) ||
263
+ ts.isFunctionDeclaration(node) ||
264
+ ts.isClassDeclaration(node)) &&
265
+ node.name !== undefined &&
266
+ ts.isIdentifier(node.name) &&
267
+ node.name.text === "undefined") {
268
+ return false;
269
+ }
270
+ if (ts.isReturnStatement(node)) {
271
+ const value = node.expression === undefined ? undefined : returnedValue(node.expression);
272
+ if (value === undefined)
273
+ return false;
274
+ values.add(value);
275
+ }
276
+ return !ts.forEachChild(node, (child) => !decides(child) || undefined);
277
+ };
278
+ return decides(body) ? [...values].sort().join(",") : undefined;
279
+ }
217
280
  /** The names a top-level statement declares when nothing outside the module sees it unless named. */
218
281
  function localNames(statement) {
219
282
  const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;
@@ -286,7 +349,9 @@ function jsDocTexts(node, text, into) {
286
349
  * `/// <reference …/>`). The offset of a top-level `X.y = …` is not kept: the qualified id of `y`
287
350
  * counts the same-named ones before it (qualified-ids.ts), which the statements' tokens show.
288
351
  *
289
- * A function without a declared return type keeps its body: its type is inferred from it.
352
+ * A function without a declared return type keeps its body: its type is inferred from it. Unless
353
+ * it only returns JSX, `null`, `undefined` or a boolean literal (`returnedValues`, a React
354
+ * component mostly): then it keeps those values instead.
290
355
  */
291
356
  export function shapeText(sourceFile) {
292
357
  if (sourceFile.isDeclarationFile ||
@@ -325,7 +390,12 @@ export function shapeText(sourceFile) {
325
390
  const visit = (node) => {
326
391
  const kind = stripped.get(node);
327
392
  if (kind !== undefined) {
328
- tokens += kind === "block" ? "{} " : "__stripped ";
393
+ tokens +=
394
+ kind === "block"
395
+ ? "{} "
396
+ : kind === "expression"
397
+ ? "__stripped "
398
+ : `__returns(${kind.returns}) `;
329
399
  return;
330
400
  }
331
401
  if (ts.isIdentifier(node)) {
@@ -350,6 +420,16 @@ export function shapeText(sourceFile) {
350
420
  node.body !== undefined) {
351
421
  strip(node.body, bodyKind(node.body));
352
422
  }
423
+ else if ((ts.isFunctionDeclaration(node) ||
424
+ ts.isMethodDeclaration(node) ||
425
+ ts.isGetAccessorDeclaration(node) ||
426
+ ts.isFunctionExpression(node) ||
427
+ ts.isArrowFunction(node)) &&
428
+ node.body !== undefined) {
429
+ const returns = returnedValues(node.body);
430
+ if (returns !== undefined)
431
+ strip(node.body, { returns });
432
+ }
353
433
  else if (ts.isSetAccessorDeclaration(node) || ts.isConstructorDeclaration(node)) {
354
434
  strip(node.body, "block");
355
435
  }
@@ -649,6 +729,90 @@ function affectsGlobalScope(program, sourceFile) {
649
729
  (ts.isStringLiteral(statement.name) ||
650
730
  (statement.flags & ts.NodeFlags.GlobalAugmentation) !== 0));
651
731
  }
732
+ /** A top-level `declare global { … }` or `declare module "…" { … }` of a module. */
733
+ function isAugmentation(statement) {
734
+ return (ts.isModuleDeclaration(statement) &&
735
+ (ts.isStringLiteral(statement.name) ||
736
+ (statement.flags & ts.NodeFlags.GlobalAugmentation) !== 0));
737
+ }
738
+ /** The names a module declares at its top level outside its augmentations, imports included. */
739
+ function moduleScopeNames(sourceFile) {
740
+ const names = new Set();
741
+ for (const statement of sourceFile.statements) {
742
+ if (isAugmentation(statement))
743
+ continue;
744
+ for (const name of declaredNames(statement))
745
+ names.add(name);
746
+ }
747
+ return names;
748
+ }
749
+ /**
750
+ * Whether an identifier in a declaration names something rather than declaring a member or a
751
+ * parameter. `parent` is given by the walk: fingerprints are computed before the program is bound,
752
+ * and only binding sets `node.parent`.
753
+ */
754
+ function isReference(identifier, parent) {
755
+ if ((ts.isPropertySignature(parent) ||
756
+ ts.isMethodSignature(parent) ||
757
+ ts.isPropertyDeclaration(parent) ||
758
+ ts.isMethodDeclaration(parent) ||
759
+ ts.isGetAccessorDeclaration(parent) ||
760
+ ts.isSetAccessorDeclaration(parent) ||
761
+ ts.isParameter(parent) ||
762
+ ts.isEnumMember(parent) ||
763
+ ts.isPropertyAssignment(parent) ||
764
+ ts.isInterfaceDeclaration(parent) ||
765
+ ts.isTypeAliasDeclaration(parent) ||
766
+ ts.isClassDeclaration(parent) ||
767
+ ts.isEnumDeclaration(parent) ||
768
+ ts.isModuleDeclaration(parent) ||
769
+ ts.isFunctionDeclaration(parent) ||
770
+ ts.isVariableDeclaration(parent) ||
771
+ ts.isNamedTupleMember(parent)) &&
772
+ parent.name === identifier) {
773
+ return false;
774
+ }
775
+ if (ts.isQualifiedName(parent) && parent.right === identifier)
776
+ return false;
777
+ if (ts.isPropertyAccessExpression(parent) && parent.name === identifier)
778
+ return false;
779
+ return true;
780
+ }
781
+ /**
782
+ * What a module's augmentations (`declare global`, `declare module "…"`) add to the global scope,
783
+ * as text to hash, when they name nothing of the module's own scope; undefined otherwise. A name
784
+ * in such a block resolves to a declaration in the blocks, in the module's scope (its imports and
785
+ * its own declarations), or in the global scope, which only files in the global hash declare. So
786
+ * when no name of the module's scope is used, the blocks' text and what each `declare module`
787
+ * resolves to decide what they add. A type parameter named like a declaration of the module, an
788
+ * `import("…")` type, or a `declare module` of an own file keeps the whole component hash.
789
+ */
790
+ function augmentationText(sourceFile, resolvedHash) {
791
+ const scope = moduleScopeNames(sourceFile);
792
+ const parts = [];
793
+ for (const statement of sourceFile.statements) {
794
+ if (!isAugmentation(statement))
795
+ continue;
796
+ if (ts.isStringLiteral(statement.name)) {
797
+ const target = resolvedHash(statement.name.text);
798
+ if (target === undefined)
799
+ return undefined;
800
+ parts.push(`module ${statement.name.text}\u0001${target}`);
801
+ }
802
+ const usesScope = (node, parent) => {
803
+ if (ts.isImportTypeNode(node))
804
+ return true;
805
+ if (ts.isIdentifier(node) && scope.has(node.text) && isReference(node, parent))
806
+ return true;
807
+ return ts.forEachChild(node, (child) => usesScope(child, node));
808
+ };
809
+ const contained = !ts.forEachChild(statement, (child) => usesScope(child, statement));
810
+ if (!contained)
811
+ return undefined;
812
+ parts.push(sourceFile.text.slice(statement.getStart(sourceFile), statement.end));
813
+ }
814
+ return parts.join("\n");
815
+ }
652
816
  /** The fingerprint of each source file of `program`, by file name; see above. */
653
817
  export function computeFingerprints(program, own, packageOf, isEntry, dependenciesOf,
654
818
  /** `packageManifests`: a library file's label carries its package.json's hash. */
@@ -656,15 +820,23 @@ manifestOf) {
656
820
  const files = [...program.getSourceFiles()].sort((a, b) => a.fileName < b.fileName ? -1 : a.fileName > b.fileName ? 1 : 0);
657
821
  const walk = resolutionWalk(program);
658
822
  const edges = new Map();
823
+ /** The own modules with augmentations, which may add to the global hash less than their component. */
824
+ const augmenting = new Set(files.filter((file) => own.has(file.fileName) &&
825
+ ts.isExternalModule(file) &&
826
+ file.statements.some((statement) => isAugmentation(statement))));
827
+ /** Where each import of those modules resolved, by specifier. */
828
+ const resolvedBy = new Map();
659
829
  /** Each file's label with its full text's hash, and with its shape's. */
660
830
  const fullLabels = new Map();
661
831
  const shapeLabels = new Map();
662
832
  for (const file of files) {
663
833
  const imports = [];
664
834
  const targets = [];
665
- const add = (specifier, resolved) => {
666
- const target = resolved === undefined ? undefined : program.getSourceFile(resolved);
667
- imports.push(`${specifier}\u0001${target?.fileName ?? resolved ?? "?"}`);
835
+ const resolved = new Map();
836
+ const add = (specifier, resolvedName) => {
837
+ const target = resolvedName === undefined ? undefined : program.getSourceFile(resolvedName);
838
+ resolved.set(specifier, target);
839
+ imports.push(`${specifier}\u0001${target?.fileName ?? resolvedName ?? "?"}`);
668
840
  if (target !== undefined)
669
841
  targets.push(target);
670
842
  };
@@ -673,6 +845,8 @@ manifestOf) {
673
845
  add(`/// ${reference.fileName}`, path.resolve(path.dirname(file.fileName), reference.fileName).replaceAll("\\", "/"));
674
846
  }
675
847
  edges.set(file, targets);
848
+ if (augmenting.has(file))
849
+ resolvedBy.set(file, resolved);
676
850
  const isOwn = own.has(file.fileName);
677
851
  const label = (text) => [
678
852
  file.fileName,
@@ -710,12 +884,27 @@ manifestOf) {
710
884
  for (const member of component)
711
885
  componentHash.set(member, hash);
712
886
  }
887
+ /**
888
+ * What a file that affects the global scope adds to the global hash: an own module's
889
+ * self-contained augmentations alone (`augmentationText`), else its component hash.
890
+ */
891
+ const globalPart = (file) => {
892
+ const whole = componentHash.get(file) ?? "";
893
+ if (!augmenting.has(file))
894
+ return whole;
895
+ const byName = resolvedBy.get(file);
896
+ const text = augmentationText(file, (specifier) => {
897
+ const target = byName?.get(specifier);
898
+ if (target === undefined || own.has(target.fileName))
899
+ return undefined;
900
+ return componentHash.get(target);
901
+ });
902
+ return text === undefined ? whole : `augments ${file.fileName}\u0000${sha1(text)}`;
903
+ };
713
904
  const global = sha1([
714
905
  ts.version,
715
906
  JSON.stringify(program.getCompilerOptions()),
716
- ...files
717
- .filter((file) => affectsGlobalScope(program, file))
718
- .map((file) => componentHash.get(file) ?? ""),
907
+ ...files.filter((file) => affectsGlobalScope(program, file)).map((file) => globalPart(file)),
719
908
  ].join("\n"));
720
909
  for (const file of files) {
721
910
  // The file's own text in full (its rules read all of it), the shapes of what it imports.
@@ -29,6 +29,13 @@ export type ProgramRecord = {
29
29
  * filled while the run that built the program asks for them.
30
30
  */
31
31
  readonly reads: Record<string, string>;
32
+ /** The package modules the own files import (`importedModules`), sorted. */
33
+ readonly imports: readonly string[];
34
+ /**
35
+ * What the config's `facts` keys resolve to in the program (`ProjectUnit.factKeys`), as JSON,
36
+ * by a digest of the facts: filled while the run that asks for them has the program.
37
+ */
38
+ readonly facts: Record<string, string>;
32
39
  };
33
40
  export declare function isQueryKind(value: unknown): value is QueryKind;
34
41
  /** Everything else a program depends on: its inputs, TypeScript's version and lib folder, the process folder. */
@@ -0,0 +1,32 @@
1
+ import ts from "typescript";
2
+ /**
3
+ * How large a project's program will be, found without building it: the files TypeScript would
4
+ * load and their text. What a memory budget plans from (`memory-plan.ts`): parsing and binding a
5
+ * program grows with its text, and the plan must be known before the parse, which on a large
6
+ * project is most of the memory.
7
+ */
8
+ export type ProgramSize = {
9
+ /** Every file the program would load: roots, what they import, libraries and type packages. */
10
+ readonly files: number;
11
+ /** Their text, in characters. */
12
+ readonly chars: number;
13
+ /**
14
+ * Their code, in characters: the text without comments and white space. What parsing costs
15
+ * follows: a library's declaration files are often mostly documentation comments, which
16
+ * TypeScript skips.
17
+ */
18
+ readonly codeChars: number;
19
+ /** The project's own files, the ones stateward checks. */
20
+ readonly ownFiles: number;
21
+ /** Their text, in characters: what the rules and the type checker work through. */
22
+ readonly ownChars: number;
23
+ };
24
+ /**
25
+ * Walks the files a program of `parsed` would load, from its roots, the default libraries and the
26
+ * automatic type packages, following each file's imports, references and `lib` references as
27
+ * TypeScript resolves them. Each file's text is scanned for those (`ts.preProcessFile`), not
28
+ * parsed, so nothing large is kept. An estimate: what TypeScript adds beyond these (an import
29
+ * helper library, a module only a type query names) is left out.
30
+ */
31
+ export declare function programSize(parsed: ts.ParsedCommandLine, own: readonly string[], overlays: ReadonlyMap<string, string>): ProgramSize;
32
+ //# sourceMappingURL=program-size.d.ts.map
@@ -0,0 +1,166 @@
1
+ import path from "node:path";
2
+ import ts from "typescript";
3
+ const JS_EXTENSIONS = [
4
+ ts.Extension.Js,
5
+ ts.Extension.Jsx,
6
+ ts.Extension.Mjs,
7
+ ts.Extension.Cjs,
8
+ ];
9
+ /** Whether TypeScript reads a resolved file into the program (it skips package JavaScript, as tsc does by default). */
10
+ function loaded(resolved, options) {
11
+ if (resolved.isExternalLibraryImport === true && JS_EXTENSIONS.includes(resolved.extension)) {
12
+ return (options.maxNodeModuleJsDepth ?? 0) > 0;
13
+ }
14
+ if (resolved.resolvedFileName.endsWith(".json"))
15
+ return options.resolveJsonModule === true;
16
+ return true;
17
+ }
18
+ /** The `jsx-runtime` module a JSX file imports without saying so (`jsx: react-jsx`). */
19
+ function jsxRuntime(options) {
20
+ if (options.jsx === ts.JsxEmit.ReactJSX)
21
+ return `${options.jsxImportSource ?? "react"}/jsx-runtime`;
22
+ if (options.jsx === ts.JsxEmit.ReactJSXDev) {
23
+ return `${options.jsxImportSource ?? "react"}/jsx-dev-runtime`;
24
+ }
25
+ return undefined;
26
+ }
27
+ const EXPORTS = /^\s*export\b/m;
28
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true);
29
+ /**
30
+ * The characters of `text`'s tokens: its text without comments and white space. Without a parser
31
+ * the scanner reads the `}` that closes a template's substitution as a brace, so the braces are
32
+ * counted here to read the rest of the template as one (a regular expression is still read as
33
+ * division: an estimate).
34
+ */
35
+ function codeLength(text) {
36
+ scanner.setText(text);
37
+ let length = 0;
38
+ /** For each open `{` or `${`: whether it is a template's substitution. */
39
+ const open = [];
40
+ for (let kind = scanner.scan(); kind !== ts.SyntaxKind.EndOfFileToken; kind = scanner.scan()) {
41
+ if (kind === ts.SyntaxKind.OpenBraceToken)
42
+ open.push(false);
43
+ else if (kind === ts.SyntaxKind.TemplateHead)
44
+ open.push(true);
45
+ else if (kind === ts.SyntaxKind.CloseBraceToken && open.pop() === true) {
46
+ if (scanner.reScanTemplateToken(false) === ts.SyntaxKind.TemplateMiddle)
47
+ open.push(true);
48
+ }
49
+ length += scanner.getTokenEnd() - scanner.getTokenStart();
50
+ }
51
+ scanner.setText(undefined);
52
+ return length;
53
+ }
54
+ /**
55
+ * Whether TypeScript treats the file as a module (or `isolatedModules` makes it act as one): it
56
+ * imports or exports, or module detection is forced, or it is JSX under the automatic runtime.
57
+ * From the text, without parsing: a line that starts with `export` counts.
58
+ */
59
+ function isModule(file, text, found, options) {
60
+ if (options.isolatedModules === true)
61
+ return true;
62
+ if (options.moduleDetection === ts.ModuleDetectionKind.Force)
63
+ return true;
64
+ if (found.importedFiles.length > 0 || EXPORTS.test(text))
65
+ return true;
66
+ return ((file.endsWith(ts.Extension.Tsx) || file.endsWith(ts.Extension.Jsx)) &&
67
+ (options.jsx === ts.JsxEmit.ReactJSX || options.jsx === ts.JsxEmit.ReactJSXDev));
68
+ }
69
+ /**
70
+ * Walks the files a program of `parsed` would load, from its roots, the default libraries and the
71
+ * automatic type packages, following each file's imports, references and `lib` references as
72
+ * TypeScript resolves them. Each file's text is scanned for those (`ts.preProcessFile`), not
73
+ * parsed, so nothing large is kept. An estimate: what TypeScript adds beyond these (an import
74
+ * helper library, a module only a type query names) is left out.
75
+ */
76
+ export function programSize(parsed, own, overlays) {
77
+ const { options } = parsed;
78
+ const base = ts.createCompilerHost(options, true);
79
+ const host = {
80
+ fileExists: (file) => overlays.has(file) || base.fileExists(file),
81
+ readFile: (file) => overlays.get(file) ?? base.readFile(file),
82
+ realpath: (file) => base.realpath?.(file) ?? file,
83
+ directoryExists: (dir) => base.directoryExists?.(dir) ?? true,
84
+ getCurrentDirectory: () => base.getCurrentDirectory(),
85
+ getDirectories: (dir) => base.getDirectories?.(dir) ?? [],
86
+ };
87
+ const resolutionCache = ts.createModuleResolutionCache(base.getCurrentDirectory(), (name) => base.getCanonicalFileName(name), options);
88
+ const libFolder = path.dirname(ts.getDefaultLibFilePath(options));
89
+ const seen = new Set();
90
+ const queue = [];
91
+ const add = (file) => {
92
+ if (file === undefined)
93
+ return;
94
+ const name = file.replaceAll("\\", "/");
95
+ if (seen.has(name))
96
+ return;
97
+ seen.add(name);
98
+ queue.push(name);
99
+ };
100
+ const addLib = (name) => {
101
+ add(path.join(libFolder, name.startsWith("lib.") ? name : `lib.${name.toLowerCase()}.d.ts`));
102
+ };
103
+ const resolveModule = (name, from) => {
104
+ const { resolvedModule } = ts.resolveModuleName(name, from, options, host, resolutionCache);
105
+ if (resolvedModule !== undefined && loaded(resolvedModule, options)) {
106
+ add(resolvedModule.resolvedFileName);
107
+ }
108
+ };
109
+ const resolveTypes = (name, from) => {
110
+ const { resolvedTypeReferenceDirective } = ts.resolveTypeReferenceDirective(name, from, options, host);
111
+ add(resolvedTypeReferenceDirective?.resolvedFileName);
112
+ };
113
+ for (const root of parsed.fileNames)
114
+ add(root);
115
+ if (options.noLib !== true) {
116
+ if (options.lib === undefined)
117
+ addLib(ts.getDefaultLibFileName(options));
118
+ else
119
+ for (const lib of options.lib)
120
+ addLib(lib);
121
+ }
122
+ const inferred = path.join(base.getCurrentDirectory(), "__inferred type names__.ts");
123
+ for (const name of ts.getAutomaticTypeDirectiveNames(options, host))
124
+ resolveTypes(name, inferred);
125
+ const runtime = jsxRuntime(options);
126
+ const implicitImports = [
127
+ ...(runtime === undefined ? [] : [runtime]),
128
+ ...(options.importHelpers === true ? ["tslib"] : []),
129
+ ];
130
+ const owned = new Set(own.map((file) => file.replaceAll("\\", "/")));
131
+ let files = 0;
132
+ let chars = 0;
133
+ let codeChars = 0;
134
+ let ownChars = 0;
135
+ // The queue grows while it is read: an array's iterator reads its length at every step.
136
+ for (const next of queue) {
137
+ const text = host.readFile(next);
138
+ if (text === undefined)
139
+ continue;
140
+ files += 1;
141
+ chars += text.length;
142
+ codeChars += codeLength(text);
143
+ if (owned.has(next))
144
+ ownChars += text.length;
145
+ if (next.endsWith(ts.Extension.Json))
146
+ continue;
147
+ const isJs = JS_EXTENSIONS.some((extension) => next.endsWith(extension));
148
+ const found = ts.preProcessFile(text, true, isJs);
149
+ for (const imported of found.importedFiles)
150
+ resolveModule(imported.fileName, next);
151
+ for (const reference of found.referencedFiles) {
152
+ add(path.resolve(path.dirname(next), reference.fileName));
153
+ }
154
+ for (const types of found.typeReferenceDirectives)
155
+ resolveTypes(types.fileName, next);
156
+ for (const lib of found.libReferenceDirectives)
157
+ addLib(lib.fileName);
158
+ // TypeScript adds these imports to a module that is not a declaration file.
159
+ if (!next.endsWith(".d.ts") && isModule(next, text, found, options)) {
160
+ for (const implicit of implicitImports)
161
+ resolveModule(implicit, next);
162
+ }
163
+ }
164
+ return { files, chars, codeChars, ownFiles: own.length, ownChars };
165
+ }
166
+ //# sourceMappingURL=program-size.js.map