@nifrajs/cli 5.17.0 → 5.18.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 (178) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/check-diagnostics.d.ts +7 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +3 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan-sql.d.ts +95 -0
  7. package/dist/check-scan-sql.d.ts.map +1 -0
  8. package/dist/check-scan-sql.js +1190 -0
  9. package/dist/check-scan-sql.js.map +1 -0
  10. package/dist/check-scan.d.ts +5 -93
  11. package/dist/check-scan.d.ts.map +1 -1
  12. package/dist/check-scan.js +20 -1207
  13. package/dist/check-scan.js.map +1 -1
  14. package/dist/check.d.ts.map +1 -1
  15. package/dist/check.js +9 -0
  16. package/dist/check.js.map +1 -1
  17. package/dist/cli.d.ts +2 -6
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +249 -80
  20. package/dist/cli.js.map +1 -1
  21. package/dist/command-catalog.d.ts +3 -0
  22. package/dist/command-catalog.d.ts.map +1 -1
  23. package/dist/command-catalog.js +18 -4
  24. package/dist/command-catalog.js.map +1 -1
  25. package/dist/frontend-guidance.js +1 -1
  26. package/dist/frontend-guidance.js.map +1 -1
  27. package/dist/internal/a11y-element.d.ts +33 -0
  28. package/dist/internal/a11y-element.d.ts.map +1 -0
  29. package/dist/internal/a11y-element.js +124 -0
  30. package/dist/internal/a11y-element.js.map +1 -0
  31. package/dist/internal/a11y-jsx.d.ts +12 -0
  32. package/dist/internal/a11y-jsx.d.ts.map +1 -0
  33. package/dist/internal/a11y-jsx.js +42 -0
  34. package/dist/internal/a11y-jsx.js.map +1 -0
  35. package/dist/internal/a11y-template.d.ts +11 -0
  36. package/dist/internal/a11y-template.d.ts.map +1 -0
  37. package/dist/internal/a11y-template.js +56 -0
  38. package/dist/internal/a11y-template.js.map +1 -0
  39. package/dist/internal/aria-data.d.ts +23 -0
  40. package/dist/internal/aria-data.d.ts.map +1 -0
  41. package/dist/internal/aria-data.js +220 -0
  42. package/dist/internal/aria-data.js.map +1 -0
  43. package/dist/internal/edit-distance.d.ts +3 -0
  44. package/dist/internal/edit-distance.d.ts.map +1 -0
  45. package/dist/internal/edit-distance.js +12 -0
  46. package/dist/internal/edit-distance.js.map +1 -0
  47. package/dist/internal/imported-as.d.ts +10 -0
  48. package/dist/internal/imported-as.d.ts.map +1 -0
  49. package/dist/internal/imported-as.js +23 -0
  50. package/dist/internal/imported-as.js.map +1 -0
  51. package/dist/internal/source-facts.d.ts +3 -0
  52. package/dist/internal/source-facts.d.ts.map +1 -1
  53. package/dist/internal/source-facts.js +2 -0
  54. package/dist/internal/source-facts.js.map +1 -1
  55. package/dist/internal/template-markup.d.ts +58 -0
  56. package/dist/internal/template-markup.d.ts.map +1 -0
  57. package/dist/internal/template-markup.js +221 -0
  58. package/dist/internal/template-markup.js.map +1 -0
  59. package/dist/internal/typescript-import.d.ts.map +1 -1
  60. package/dist/internal/typescript-import.js +11 -0
  61. package/dist/internal/typescript-import.js.map +1 -1
  62. package/dist/mcp-exec.d.ts.map +1 -1
  63. package/dist/mcp-exec.js +37 -23
  64. package/dist/mcp-exec.js.map +1 -1
  65. package/dist/mcp-http.js +1 -1
  66. package/dist/mcp-io.d.ts.map +1 -1
  67. package/dist/mcp-io.js +5 -3
  68. package/dist/mcp-io.js.map +1 -1
  69. package/dist/mcp-root.js +1 -1
  70. package/dist/mcp-root.js.map +1 -1
  71. package/dist/mcp-ws.d.ts.map +1 -1
  72. package/dist/mcp-ws.js +3 -2
  73. package/dist/mcp-ws.js.map +1 -1
  74. package/dist/migrate-layout-config.d.ts +63 -0
  75. package/dist/migrate-layout-config.d.ts.map +1 -0
  76. package/dist/migrate-layout-config.js +507 -0
  77. package/dist/migrate-layout-config.js.map +1 -0
  78. package/dist/migrate-layout-split.d.ts +46 -0
  79. package/dist/migrate-layout-split.d.ts.map +1 -0
  80. package/dist/migrate-layout-split.js +687 -0
  81. package/dist/migrate-layout-split.js.map +1 -0
  82. package/dist/migrate-layout.d.ts +4 -24
  83. package/dist/migrate-layout.d.ts.map +1 -1
  84. package/dist/migrate-layout.js +8 -1183
  85. package/dist/migrate-layout.js.map +1 -1
  86. package/dist/output-schemas.d.ts.map +1 -1
  87. package/dist/output-schemas.js +78 -10
  88. package/dist/output-schemas.js.map +1 -1
  89. package/dist/recipes/5.18.0.d.ts +9 -0
  90. package/dist/recipes/5.18.0.d.ts.map +1 -0
  91. package/dist/recipes/5.18.0.js +56 -0
  92. package/dist/recipes/5.18.0.js.map +1 -0
  93. package/dist/recipes/index.d.ts.map +1 -1
  94. package/dist/recipes/index.js +2 -0
  95. package/dist/recipes/index.js.map +1 -1
  96. package/dist/review.d.ts.map +1 -1
  97. package/dist/review.js +6 -0
  98. package/dist/review.js.map +1 -1
  99. package/dist/rules/a11y.d.ts +5 -0
  100. package/dist/rules/a11y.d.ts.map +1 -0
  101. package/dist/rules/a11y.js +78 -0
  102. package/dist/rules/a11y.js.map +1 -0
  103. package/dist/rules/codes.d.ts +6 -0
  104. package/dist/rules/codes.d.ts.map +1 -1
  105. package/dist/rules/codes.js +6 -0
  106. package/dist/rules/codes.js.map +1 -1
  107. package/dist/rules/comment-markers.js +1 -1
  108. package/dist/rules/comment-markers.js.map +1 -1
  109. package/dist/rules/explanations.d.ts.map +1 -1
  110. package/dist/rules/explanations.js +30 -0
  111. package/dist/rules/explanations.js.map +1 -1
  112. package/dist/rules/host-exposure.d.ts +23 -0
  113. package/dist/rules/host-exposure.d.ts.map +1 -0
  114. package/dist/rules/host-exposure.js +380 -0
  115. package/dist/rules/host-exposure.js.map +1 -0
  116. package/dist/rules/internal-links.d.ts.map +1 -1
  117. package/dist/rules/internal-links.js +16 -141
  118. package/dist/rules/internal-links.js.map +1 -1
  119. package/dist/rules/islands.d.ts +54 -0
  120. package/dist/rules/islands.d.ts.map +1 -1
  121. package/dist/rules/islands.js +577 -80
  122. package/dist/rules/islands.js.map +1 -1
  123. package/dist/rules/security.d.ts +1 -0
  124. package/dist/rules/security.d.ts.map +1 -1
  125. package/dist/rules/security.js +34 -7
  126. package/dist/rules/security.js.map +1 -1
  127. package/dist/runtime-differences.js +3 -3
  128. package/dist/runtime-differences.js.map +1 -1
  129. package/dist/scaffold.d.ts +1 -1
  130. package/dist/scaffold.d.ts.map +1 -1
  131. package/dist/scaffold.js +2 -2
  132. package/dist/scaffold.js.map +1 -1
  133. package/dist/source-rewrites.d.ts.map +1 -1
  134. package/dist/source-rewrites.js +2 -19
  135. package/dist/source-rewrites.js.map +1 -1
  136. package/docs/examples.json +4 -4
  137. package/docs/llms-full.txt +422 -42
  138. package/docs/types.json +466 -56
  139. package/package.json +12 -12
  140. package/src/check-diagnostics.ts +11 -0
  141. package/src/check-scan-sql.ts +1746 -0
  142. package/src/check-scan.ts +34 -1754
  143. package/src/check.ts +10 -1
  144. package/src/cli.ts +258 -98
  145. package/src/command-catalog.ts +21 -4
  146. package/src/frontend-guidance.ts +1 -1
  147. package/src/internal/a11y-element.ts +227 -0
  148. package/src/internal/a11y-jsx.ts +54 -0
  149. package/src/internal/a11y-template.ts +74 -0
  150. package/src/internal/aria-data.ts +242 -0
  151. package/src/internal/edit-distance.ts +16 -0
  152. package/src/internal/imported-as.ts +30 -0
  153. package/src/internal/source-facts.ts +4 -0
  154. package/src/internal/template-markup.ts +270 -0
  155. package/src/internal/typescript-import.ts +15 -0
  156. package/src/mcp-exec.ts +43 -22
  157. package/src/mcp-http.ts +1 -1
  158. package/src/mcp-io.ts +5 -3
  159. package/src/mcp-root.ts +1 -1
  160. package/src/mcp-ws.ts +3 -2
  161. package/src/migrate-layout-config.ts +615 -0
  162. package/src/migrate-layout-split.ts +870 -0
  163. package/src/migrate-layout.ts +37 -1468
  164. package/src/output-schemas.ts +85 -17
  165. package/src/recipes/5.18.0.ts +63 -0
  166. package/src/recipes/index.ts +2 -0
  167. package/src/review.ts +6 -0
  168. package/src/rules/a11y.ts +119 -0
  169. package/src/rules/codes.ts +6 -0
  170. package/src/rules/comment-markers.ts +2 -2
  171. package/src/rules/explanations.ts +30 -0
  172. package/src/rules/host-exposure.ts +531 -0
  173. package/src/rules/internal-links.ts +21 -154
  174. package/src/rules/islands.ts +698 -86
  175. package/src/rules/security.ts +48 -7
  176. package/src/runtime-differences.ts +3 -3
  177. package/src/scaffold.ts +3 -3
  178. package/src/source-rewrites.ts +2 -15
@@ -1,14 +1,10 @@
1
- import { readFileSync, realpathSync } from "node:fs";
2
- import { dirname, isAbsolute, join, posix, resolve, sep } from "node:path";
1
+ import { join, posix, sep } from "node:path";
3
2
  import { isServerPackageSpecifier } from "@nifrajs/web/zones";
4
3
  import { Glob } from "bun";
5
4
  import { codeUnitOrder } from "./internal/code-unit-order.js";
6
5
  import { gitIgnored } from "./internal/git-ignored.js";
7
6
  import { lineAt } from "./internal/line-at.js";
8
7
  import { toPosix } from "./internal/posix-path.js";
9
- import { realpathOrSelf } from "./internal/realpath-or-self.js";
10
- import { scriptKindOf } from "./internal/script-kind.js";
11
- import { loadProjectTypeScript, } from "./internal/typescript-import.js";
12
8
  import { commentBlockExpectation } from "./rules/comment-markers.js";
13
9
  const TYPED_CLIENT_EXPECTATION = ["NF-C002"];
14
10
  function typedClientFinding(file, lines, line) {
@@ -21,7 +17,7 @@ const FETCH_CALL = /(?<![.\w])fetch\s*\(/g;
21
17
  const HTTP_VERBS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
22
18
  const SOCKET_VERB = new Set(["WS"]);
23
19
  export const SIMPLE_REWRITE_METHODS = new Set(["GET", "DELETE", "HEAD", "OPTIONS"]);
24
- const IGNORED_DIR = /(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//;
20
+ export const IGNORED_DIR = /(^|\/)(node_modules|dist(-[a-z0-9]+)?|build|\.nifra|\.git|\.wrangler|coverage)\//;
25
21
  const TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
26
22
  export const IGNORED = new RegExp(`${IGNORED_DIR.source}|${TEST_FILE.source}`);
27
23
  const normalizeProjectPath = toPosix;
@@ -100,7 +96,8 @@ const ROUTE_ARGUMENT = /\.([A-Za-z]+)\s*\(\s*([A-Za-z_$][\w$]*|`(?:\\.|[^`\\])*`
100
96
  const NAMED_IMPORTS = /(?<![\w$.])import\s*\{([^}]*)\}\s*from\s*(["'])([^"'\r\n]+)\2/g;
101
97
  function parseQuotedLiteral(raw) {
102
98
  try {
103
- return JSON.parse(raw);
99
+ const value = JSON.parse(raw);
100
+ return typeof value === "string" ? value : undefined;
104
101
  }
105
102
  catch {
106
103
  if (!raw.startsWith("'") || !raw.endsWith("'"))
@@ -109,9 +106,9 @@ function parseQuotedLiteral(raw) {
109
106
  const inner = raw.slice(1, -1);
110
107
  let body = "";
111
108
  for (let i = 0; i < inner.length; i++) {
112
- const ch = inner[i];
109
+ const ch = inner.charAt(i);
113
110
  if (ch === "\\" && i + 1 < inner.length) {
114
- const next = inner[i + 1];
111
+ const next = inner.charAt(i + 1);
115
112
  body += next === "'" ? "'" : ch + next;
116
113
  i++;
117
114
  }
@@ -122,7 +119,8 @@ function parseQuotedLiteral(raw) {
122
119
  body += ch;
123
120
  }
124
121
  }
125
- return JSON.parse(`"${body}"`);
122
+ const value = JSON.parse(`"${body}"`);
123
+ return typeof value === "string" ? value : undefined;
126
124
  }
127
125
  catch {
128
126
  return undefined;
@@ -544,14 +542,18 @@ export function scanStreamText(file, content, externalMounts = []) {
544
542
  return ownPathCalls(file, content, STREAM_CONSTRUCT, externalMounts);
545
543
  }
546
544
  export function scanStaticRouteText(file, content, facts, project) {
545
+ return scanStaticRegistrations(file, content, facts, project);
546
+ }
547
+ function scanStaticRegistrations(file, content, facts, project, verbs) {
547
548
  const code = stripComments(content);
548
549
  if (!isPotentialBackendSource(code, file, project))
549
550
  return [];
551
+ const methods = verbs === undefined && code.includes(METHODS_SUBPATH);
550
552
  return [
551
- ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts),
552
- ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts),
553
- ...(code.includes(METHODS_SUBPATH) ? scanMethodRoutes(file, content, code, facts) : []),
554
- ...scanRouteArguments(file, content, facts, project).routes,
553
+ ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts, verbs),
554
+ ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts, verbs),
555
+ ...(methods ? scanMethodRoutes(file, content, code, facts) : []),
556
+ ...scanRouteArguments(file, content, facts, project, verbs).routes,
555
557
  ].sort(bySite);
556
558
  }
557
559
  function literalEnd(text) {
@@ -698,14 +700,7 @@ export function scanUnresolvedRoutePaths(file, content, project, facts) {
698
700
  ].sort(bySite);
699
701
  }
700
702
  export function scanStaticSocketText(file, content, facts, project) {
701
- const code = stripComments(content);
702
- if (!isPotentialBackendSource(code, file, project))
703
- return [];
704
- return [
705
- ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_DQ, facts, SOCKET_VERB),
706
- ...scanRoutePattern(file, content, code, ROUTE_REGISTRATION_SQ, facts, SOCKET_VERB),
707
- ...scanRouteArguments(file, content, facts, project, SOCKET_VERB).routes,
708
- ].sort(bySite);
703
+ return scanStaticRegistrations(file, content, facts, project, SOCKET_VERB);
709
704
  }
710
705
  function scanMethodRoutes(file, content, code, facts) {
711
706
  const out = [];
@@ -742,1189 +737,7 @@ function scanMethodRoutes(file, content, code, facts) {
742
737
  }
743
738
  return out;
744
739
  }
745
- const SQL_METHODS = new Set([
746
- "query",
747
- "queryRaw",
748
- "prepare",
749
- "exec",
750
- "execute",
751
- "run",
752
- "unsafe",
753
- "$queryRawUnsafe",
754
- "$executeRawUnsafe",
755
- "raw",
756
- ]);
757
- const SQL_KEYWORD = /\b(select|insert\s+into|update|delete\s+from|drop\s+table|create\s+table|alter\s+table|truncate|from|where|values|set|join|union)\b/i;
758
- const ALWAYS_UNSAFE = new Set(["unsafe", "$queryRawUnsafe", "$executeRawUnsafe", "raw"]);
759
- const DRIVER_READ_METHODS = new Set([
760
- "all",
761
- "get",
762
- "each",
763
- "any",
764
- "one",
765
- "none",
766
- "many",
767
- "oneOrNone",
768
- "manyOrNone",
769
- "result",
770
- "multi",
771
- "multiResult",
772
- ]);
773
- const STATEMENT_START = /^\s*\(?\s*(?:select|insert|update|delete|with|replace|merge|create|drop|alter|truncate|pragma)\s/i;
774
- function sqlModuleScope(ts, id, source) {
775
- const consts = new Map();
776
- const imports = new Map();
777
- const localExports = new Map();
778
- const reExports = new Map();
779
- const starExports = [];
780
- for (const statement of source.statements) {
781
- if (ts.isVariableStatement(statement)) {
782
- if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0)
783
- continue;
784
- const exported = statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true;
785
- for (const declaration of statement.declarationList.declarations) {
786
- if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined)
787
- continue;
788
- consts.set(declaration.name.text, declaration.initializer);
789
- if (exported)
790
- localExports.set(declaration.name.text, declaration.name.text);
791
- }
792
- continue;
793
- }
794
- if (ts.isImportDeclaration(statement)) {
795
- const clause = statement.importClause;
796
- if (clause === undefined || clause.isTypeOnly)
797
- continue;
798
- if (!ts.isStringLiteral(statement.moduleSpecifier))
799
- continue;
800
- const bindings = clause.namedBindings;
801
- if (bindings === undefined || !ts.isNamedImports(bindings))
802
- continue;
803
- for (const element of bindings.elements) {
804
- if (element.isTypeOnly)
805
- continue;
806
- imports.set(element.name.text, {
807
- specifier: statement.moduleSpecifier.text,
808
- exported: element.propertyName?.text ?? element.name.text,
809
- });
810
- }
811
- continue;
812
- }
813
- if (!ts.isExportDeclaration(statement) || statement.isTypeOnly)
814
- continue;
815
- const from = statement.moduleSpecifier;
816
- if (from !== undefined && !ts.isStringLiteral(from))
817
- continue;
818
- const clause = statement.exportClause;
819
- if (clause === undefined) {
820
- if (from !== undefined)
821
- starExports.push(from.text);
822
- continue;
823
- }
824
- if (!ts.isNamedExports(clause))
825
- continue;
826
- for (const element of clause.elements) {
827
- if (element.isTypeOnly)
828
- continue;
829
- const local = element.propertyName?.text ?? element.name.text;
830
- if (from === undefined)
831
- localExports.set(element.name.text, local);
832
- else
833
- reExports.set(element.name.text, { specifier: from.text, exported: local });
834
- }
835
- }
836
- return { id, consts, imports, localExports, reExports, starExports };
837
- }
838
- export const createSqlImports = (load) => ({
839
- load,
840
- scopes: new Map(),
841
- });
842
- function parseSqlSource(ts, file, content) {
843
- const kind = scriptKindOf(ts, file);
844
- let source;
845
- try {
846
- source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, kind);
847
- }
848
- catch {
849
- return undefined;
850
- }
851
- const parseDiagnostics = source.parseDiagnostics;
852
- return parseDiagnostics !== undefined && parseDiagnostics.length > 0 ? undefined : source;
853
- }
854
- const SQL_IMPORT_HOPS = 3;
855
- function loadSqlModuleScope(ts, imports, fromModule, specifier) {
856
- const loaded = imports.load(fromModule, specifier);
857
- if (loaded === undefined)
858
- return undefined;
859
- if (imports.scopes.has(loaded.id))
860
- return imports.scopes.get(loaded.id);
861
- const source = parseSqlSource(ts, loaded.id, loaded.content);
862
- const scope = source === undefined ? undefined : sqlModuleScope(ts, loaded.id, source);
863
- imports.scopes.set(loaded.id, scope);
864
- return scope;
865
- }
866
- function resolveExportedConst(ts, imports, scope, name, hops, seen) {
867
- if (hops > SQL_IMPORT_HOPS)
868
- return undefined;
869
- const key = `${scope.id}#${name}`;
870
- if (seen.has(key))
871
- return undefined;
872
- const nextSeen = new Set(seen).add(key);
873
- const follow = (edge) => {
874
- const target = loadSqlModuleScope(ts, imports, scope.id, edge.specifier);
875
- return target === undefined
876
- ? undefined
877
- : resolveExportedConst(ts, imports, target, edge.exported, hops + 1, nextSeen);
878
- };
879
- const local = scope.localExports.get(name);
880
- if (local !== undefined) {
881
- const initializer = scope.consts.get(local);
882
- if (initializer !== undefined)
883
- return { expression: initializer, scope };
884
- const via = scope.imports.get(local);
885
- return via === undefined ? undefined : follow(via);
886
- }
887
- const reExported = scope.reExports.get(name);
888
- if (reExported !== undefined)
889
- return follow(reExported);
890
- let found;
891
- for (const specifier of scope.starExports) {
892
- const hit = follow({ specifier, exported: name });
893
- if (hit === undefined)
894
- continue;
895
- if (found !== undefined)
896
- return undefined;
897
- found = hit;
898
- }
899
- return found;
900
- }
901
- function isShadowedAt(ts, at, name) {
902
- let scope;
903
- for (let node = at.parent; node !== undefined; node = node.parent) {
904
- if (ts.isSourceFile(node))
905
- break;
906
- if (ts.isFunctionLike(node) || ts.isBlock(node))
907
- scope = node;
908
- }
909
- if (scope === undefined)
910
- return false;
911
- const bindsName = (binding) => ts.isIdentifier(binding)
912
- ? binding.text === name
913
- : binding.elements.some((element) => !ts.isOmittedExpression(element) &&
914
- (ts.isIdentifier(element.name) ? element.name.text === name : bindsName(element.name)));
915
- let found = false;
916
- const scan = (node) => {
917
- if (found)
918
- return;
919
- if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) &&
920
- bindsName(node.name)) {
921
- found = true;
922
- return;
923
- }
924
- if (ts.isFunctionDeclaration(node) && node.name?.text === name) {
925
- found = true;
926
- return;
927
- }
928
- ts.forEachChild(node, scan);
929
- };
930
- scan(scope);
931
- return found;
932
- }
933
- const CONST_RESOLUTION_DEPTH = 5;
934
- function resolveStaticSqlText(ts, node, scope, depth) {
935
- if (depth > CONST_RESOLUTION_DEPTH)
936
- return undefined;
937
- if (ts.isParenthesizedExpression(node)) {
938
- return resolveStaticSqlText(ts, node.expression, scope, depth);
939
- }
940
- if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
941
- return resolveStaticSqlText(ts, node.expression, scope, depth);
942
- }
943
- if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
944
- return node.text;
945
- if (ts.isNumericLiteral(node))
946
- return node.text;
947
- if (ts.isTemplateExpression(node)) {
948
- let text = node.head.text;
949
- for (const span of node.templateSpans) {
950
- const part = placeholderNumber(ts, text, span.expression, depth) ??
951
- resolveStaticSqlText(ts, span.expression, scope, depth + 1);
952
- if (part === undefined)
953
- return undefined;
954
- text += part + span.literal.text;
955
- }
956
- return text;
957
- }
958
- if (ts.isConditionalExpression(node)) {
959
- const whenTrue = resolveStaticSqlText(ts, node.whenTrue, scope, depth + 1);
960
- const whenFalse = resolveStaticSqlText(ts, node.whenFalse, scope, depth + 1);
961
- if (whenTrue === undefined || whenFalse === undefined)
962
- return undefined;
963
- return `${whenTrue} ${whenFalse}`;
964
- }
965
- if (ts.isCallExpression(node))
966
- return resolveStaticJoin(ts, node, scope, depth);
967
- if (ts.isIdentifier(node)) {
968
- const local = localConstInitializer(ts, node);
969
- if (local === "shadow")
970
- return undefined;
971
- if (local !== undefined)
972
- return resolveStaticSqlText(ts, local, scope, depth + 1);
973
- const initializer = scope.module.consts.get(node.text);
974
- const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined;
975
- if (initializer === undefined && edge === undefined)
976
- return undefined;
977
- if (isShadowedAt(ts, node, node.text))
978
- return undefined;
979
- if (initializer !== undefined)
980
- return resolveStaticSqlText(ts, initializer, scope, depth + 1);
981
- if (edge === undefined || scope.imports === undefined)
982
- return undefined;
983
- const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier);
984
- if (target === undefined)
985
- return undefined;
986
- const exported = resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set());
987
- if (exported === undefined)
988
- return undefined;
989
- return resolveStaticSqlText(ts, exported.expression, { module: exported.scope, imports: scope.imports }, depth + 1);
990
- }
991
- return undefined;
992
- }
993
- function localConstInitializer(ts, node) {
994
- const source = node.getSourceFile();
995
- for (let scope = node.parent; scope !== undefined; scope = scope.parent) {
996
- if (ts.isSourceFile(scope))
997
- return undefined;
998
- const binding = directBinding(ts, source, scope, node.text);
999
- if (binding === "shadow")
1000
- return "shadow";
1001
- if (binding !== undefined)
1002
- return binding.constant ? binding.initializer : "shadow";
1003
- }
1004
- return undefined;
1005
- }
1006
- const unwrapExpression = (ts, node) => {
1007
- let current = node;
1008
- while (ts.isParenthesizedExpression(current) ||
1009
- ts.isAsExpression(current) ||
1010
- ts.isSatisfiesExpression(current)) {
1011
- current = current.expression;
1012
- }
1013
- return current;
1014
- };
1015
- function frozenArrayLiteral(ts, node) {
1016
- const call = unwrapExpression(ts, node);
1017
- if (!ts.isCallExpression(call) || call.arguments.length !== 1)
1018
- return undefined;
1019
- const callee = call.expression;
1020
- if (!ts.isPropertyAccessExpression(callee) ||
1021
- callee.name.text !== "freeze" ||
1022
- !ts.isIdentifier(callee.expression) ||
1023
- callee.expression.text !== "Object" ||
1024
- isShadowedAt(ts, callee.expression, "Object")) {
1025
- return undefined;
1026
- }
1027
- const array = unwrapExpression(ts, call.arguments[0]);
1028
- return ts.isArrayLiteralExpression(array) ? array : undefined;
1029
- }
1030
- const ARRAY_READS = new Set(["join", "includes", "indexOf"]);
1031
- function onlyReadsArray(ts, source, name, declaration, pushed) {
1032
- let ok = true;
1033
- const visit = (node) => {
1034
- if (!ok)
1035
- return;
1036
- if (ts.isIdentifier(node) && node.text === name && node !== declaration) {
1037
- const access = node.parent;
1038
- const call = ts.isPropertyAccessExpression(access) &&
1039
- access.expression === node &&
1040
- ts.isCallExpression(access.parent) &&
1041
- access.parent.expression === access
1042
- ? access.parent
1043
- : undefined;
1044
- if (pushed !== undefined &&
1045
- call !== undefined &&
1046
- ts.isPropertyAccessExpression(access) &&
1047
- access.name.text === "push") {
1048
- if (call.arguments.some((argument) => ts.isSpreadElement(argument)))
1049
- ok = false;
1050
- else
1051
- pushed.push(...call.arguments);
1052
- for (const argument of call.arguments)
1053
- visit(argument);
1054
- return;
1055
- }
1056
- const read = ts.isPropertyAccessExpression(access) &&
1057
- access.expression === node &&
1058
- (access.name.text === "length"
1059
- ? !isWrittenTo(ts, access)
1060
- : ARRAY_READS.has(access.name.text) && call !== undefined);
1061
- if (!read)
1062
- ok = false;
1063
- return;
1064
- }
1065
- ts.forEachChild(node, visit);
1066
- };
1067
- visit(source);
1068
- return ok;
1069
- }
1070
- function isWrittenTo(ts, node) {
1071
- const parent = node.parent;
1072
- if (ts.isBinaryExpression(parent) &&
1073
- parent.left === node &&
1074
- parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1075
- parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
1076
- return true;
1077
- }
1078
- if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
1079
- return (parent.operator === ts.SyntaxKind.PlusPlusToken ||
1080
- parent.operator === ts.SyntaxKind.MinusMinusToken);
1081
- }
1082
- return ts.isDeleteExpression(parent);
1083
- }
1084
- function staticArrayItems(ts, receiver, scope, depth) {
1085
- const node = unwrapExpression(ts, receiver);
1086
- let array = ts.isArrayLiteralExpression(node) ? node : frozenArrayLiteral(ts, node);
1087
- let itemScope = scope;
1088
- const pushed = [];
1089
- if (array === undefined && ts.isIdentifier(node)) {
1090
- const local = localConstInitializer(ts, node);
1091
- if (local === "shadow")
1092
- return undefined;
1093
- let initializer = local;
1094
- let exported = false;
1095
- if (initializer === undefined && !isShadowedAt(ts, node, node.text)) {
1096
- initializer = scope.module.consts.get(node.text);
1097
- exported = [...scope.module.localExports.values()].includes(node.text);
1098
- const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined;
1099
- if (edge !== undefined && scope.imports !== undefined) {
1100
- const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier);
1101
- const found = target === undefined
1102
- ? undefined
1103
- : resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set());
1104
- if (found === undefined)
1105
- return undefined;
1106
- array = frozenArrayLiteral(ts, found.expression);
1107
- itemScope = { module: found.scope, imports: scope.imports };
1108
- }
1109
- }
1110
- if (array === undefined && initializer !== undefined) {
1111
- array = frozenArrayLiteral(ts, initializer);
1112
- const literal = unwrapExpression(ts, initializer);
1113
- if (array === undefined &&
1114
- !exported &&
1115
- ts.isArrayLiteralExpression(literal) &&
1116
- ts.isVariableDeclaration(initializer.parent) &&
1117
- onlyReadsArray(ts, node.getSourceFile(), node.text, initializer.parent.name, pushed)) {
1118
- array = literal;
1119
- }
1120
- }
1121
- }
1122
- if (array === undefined)
1123
- return undefined;
1124
- const items = [];
1125
- for (const element of [...array.elements, ...pushed]) {
1126
- if (ts.isSpreadElement(element) || ts.isOmittedExpression(element))
1127
- return undefined;
1128
- const text = resolveStaticSqlText(ts, element, itemScope, depth + 1);
1129
- if (text === undefined)
1130
- return undefined;
1131
- items.push(text);
1132
- }
1133
- return items;
1134
- }
1135
- function resolveStaticJoin(ts, call, scope, depth) {
1136
- const callee = call.expression;
1137
- if (!ts.isPropertyAccessExpression(callee) ||
1138
- callee.questionDotToken !== undefined ||
1139
- callee.name.text !== "join" ||
1140
- call.arguments.length > 1) {
1141
- return undefined;
1142
- }
1143
- const separatorArg = call.arguments[0];
1144
- const separator = separatorArg === undefined
1145
- ? ","
1146
- : ts.isStringLiteral(separatorArg) || ts.isNoSubstitutionTemplateLiteral(separatorArg)
1147
- ? separatorArg.text
1148
- : undefined;
1149
- if (separator === undefined)
1150
- return undefined;
1151
- const items = staticArrayItems(ts, callee.expression, scope, depth + 1) ??
1152
- mappedItem(ts, callee.expression, scope, depth + 1);
1153
- return items?.join(separator);
1154
- }
1155
- function mappedItem(ts, receiver, scope, depth) {
1156
- const call = unwrapExpression(ts, receiver);
1157
- if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
1158
- return undefined;
1159
- const method = call.expression.name.text;
1160
- const argument = indexCallbackArgument(ts, call);
1161
- if (argument === undefined || !(method === "map" || method === "flatMap" || argument === 1))
1162
- return undefined;
1163
- const fn = call.arguments[argument];
1164
- if (fn === undefined || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
1165
- return undefined;
1166
- const only = ts.isBlock(fn.body) && fn.body.statements.length === 1 ? fn.body.statements[0] : undefined;
1167
- const body = ts.isBlock(fn.body)
1168
- ? only !== undefined && ts.isReturnStatement(only)
1169
- ? only.expression
1170
- : undefined
1171
- : fn.body;
1172
- const text = body === undefined ? undefined : resolveStaticSqlText(ts, body, scope, depth + 1);
1173
- return text === undefined ? undefined : [text];
1174
- }
1175
- const INDEX_PARAMETER = new Map([
1176
- ["map", 1],
1177
- ["flatMap", 1],
1178
- ["forEach", 1],
1179
- ["filter", 1],
1180
- ["some", 1],
1181
- ["every", 1],
1182
- ["find", 1],
1183
- ["findIndex", 1],
1184
- ["reduce", 2],
1185
- ["reduceRight", 2],
1186
- ]);
1187
- function indexCallbackArgument(ts, call) {
1188
- const callee = call.expression;
1189
- if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
1190
- return undefined;
1191
- if (INDEX_PARAMETER.has(callee.name.text))
1192
- return 0;
1193
- return callee.name.text === "from" &&
1194
- ts.isIdentifier(callee.expression) &&
1195
- callee.expression.text === "Array" &&
1196
- !isShadowedAt(ts, callee.expression, "Array")
1197
- ? 1
1198
- : undefined;
1199
- }
1200
- function placeholderNumber(ts, before, node, depth) {
1201
- return before.endsWith("$") && isNumericExpression(ts, node, depth) ? "1" : undefined;
1202
- }
1203
- const NUMERIC_OPERATORS = (ts) => new Set([
1204
- ts.SyntaxKind.MinusToken,
1205
- ts.SyntaxKind.AsteriskToken,
1206
- ts.SyntaxKind.AsteriskAsteriskToken,
1207
- ts.SyntaxKind.SlashToken,
1208
- ts.SyntaxKind.PercentToken,
1209
- ts.SyntaxKind.AmpersandToken,
1210
- ts.SyntaxKind.BarToken,
1211
- ts.SyntaxKind.CaretToken,
1212
- ts.SyntaxKind.LessThanLessThanToken,
1213
- ts.SyntaxKind.GreaterThanGreaterThanToken,
1214
- ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
1215
- ]);
1216
- const NUMBER_FUNCTIONS = new Set(["Number", "parseInt", "parseFloat"]);
1217
- function isNumericExpression(ts, node, depth) {
1218
- if (depth > CONST_RESOLUTION_DEPTH)
1219
- return false;
1220
- const expression = unwrapExpression(ts, node);
1221
- if (ts.isNumericLiteral(expression))
1222
- return true;
1223
- if (ts.isPrefixUnaryExpression(expression))
1224
- return expression.operator !== ts.SyntaxKind.ExclamationToken;
1225
- if (ts.isPostfixUnaryExpression(expression))
1226
- return true;
1227
- if (ts.isBinaryExpression(expression)) {
1228
- const operator = expression.operatorToken.kind;
1229
- if (operator === ts.SyntaxKind.PlusToken) {
1230
- return (isNumericExpression(ts, expression.left, depth + 1) &&
1231
- isNumericExpression(ts, expression.right, depth + 1));
1232
- }
1233
- return NUMERIC_OPERATORS(ts).has(operator);
1234
- }
1235
- if (ts.isIdentifier(expression))
1236
- return isNumericName(ts, expression, depth);
1237
- if (ts.isCallExpression(expression)) {
1238
- const callee = expression.expression;
1239
- if (ts.isIdentifier(callee))
1240
- return NUMBER_FUNCTIONS.has(callee.text) && !isShadowedAt(ts, callee, callee.text);
1241
- if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
1242
- return false;
1243
- if (callee.name.text === "push")
1244
- return true;
1245
- return (ts.isIdentifier(callee.expression) &&
1246
- callee.expression.text === "Math" &&
1247
- !isShadowedAt(ts, callee.expression, "Math"));
1248
- }
1249
- if (ts.isPropertyAccessExpression(expression) &&
1250
- expression.name.text === "length" &&
1251
- ts.isIdentifier(expression.expression)) {
1252
- const binding = nameBinding(ts, expression.expression);
1253
- return (binding.kind === "value" &&
1254
- ts.isArrayLiteralExpression(unwrapExpression(ts, binding.initializer)));
1255
- }
1256
- return false;
1257
- }
1258
- function nameBinding(ts, node) {
1259
- const source = node.getSourceFile();
1260
- for (let scope = node.parent; scope !== undefined; scope = scope.parent) {
1261
- if (ts.isFunctionLike(scope)) {
1262
- const position = scope.parameters.findIndex((p) => bindingNameCovers(ts, p.name, node.text));
1263
- if (position !== -1) {
1264
- return ts.isIdentifier(scope.parameters[position]?.name ?? node)
1265
- ? { kind: "parameter", fn: scope, position }
1266
- : { kind: "unknown" };
1267
- }
1268
- }
1269
- const binding = directBinding(ts, source, scope, node.text);
1270
- if (binding === "shadow") {
1271
- const list = ts.isForStatement(scope) ? scope.initializer : undefined;
1272
- const declaration = list !== undefined && ts.isVariableDeclarationList(list)
1273
- ? list.declarations.find((d) => ts.isIdentifier(d.name) && d.name.text === node.text)
1274
- : undefined;
1275
- return declaration?.initializer === undefined
1276
- ? { kind: "unknown" }
1277
- : { kind: "counter", initializer: declaration.initializer };
1278
- }
1279
- if (binding !== undefined)
1280
- return { kind: "value", initializer: binding.initializer };
1281
- if (ts.isSourceFile(scope))
1282
- break;
1283
- }
1284
- return { kind: "unknown" };
1285
- }
1286
- function isNumericName(ts, node, depth) {
1287
- const source = node.getSourceFile();
1288
- const binding = nameBinding(ts, node);
1289
- if (binding.kind === "value")
1290
- return isNumericExpression(ts, binding.initializer, depth + 1);
1291
- if (binding.kind === "counter") {
1292
- return (isNumericExpression(ts, binding.initializer, depth + 1) &&
1293
- onlyNumericWrites(ts, source, node.text, depth));
1294
- }
1295
- if (binding.kind !== "parameter")
1296
- return false;
1297
- const call = binding.fn.parent;
1298
- if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
1299
- return false;
1300
- const argument = indexCallbackArgument(ts, call);
1301
- const position = argument === 1 ? 1 : INDEX_PARAMETER.get(call.expression.name.text);
1302
- return (argument !== undefined &&
1303
- call.arguments[argument] === binding.fn &&
1304
- binding.position === position &&
1305
- !isReassignedInFile(ts, source, node.text));
1306
- }
1307
- const NUMERIC_ASSIGNMENTS = (ts) => new Set([
1308
- ts.SyntaxKind.MinusEqualsToken,
1309
- ts.SyntaxKind.AsteriskEqualsToken,
1310
- ts.SyntaxKind.AsteriskAsteriskEqualsToken,
1311
- ts.SyntaxKind.SlashEqualsToken,
1312
- ts.SyntaxKind.PercentEqualsToken,
1313
- ts.SyntaxKind.AmpersandEqualsToken,
1314
- ts.SyntaxKind.BarEqualsToken,
1315
- ts.SyntaxKind.CaretEqualsToken,
1316
- ts.SyntaxKind.LessThanLessThanEqualsToken,
1317
- ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
1318
- ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
1319
- ]);
1320
- function onlyNumericWrites(ts, source, name, depth) {
1321
- let ok = true;
1322
- const visit = (node) => {
1323
- if (!ok)
1324
- return;
1325
- if (ts.isIdentifier(node) && node.text === name && isWrittenTo(ts, node)) {
1326
- const parent = node.parent;
1327
- if (ts.isBinaryExpression(parent)) {
1328
- const operator = parent.operatorToken.kind;
1329
- ok =
1330
- operator === ts.SyntaxKind.EqualsToken || operator === ts.SyntaxKind.PlusEqualsToken
1331
- ? isNumericExpression(ts, parent.right, depth + 1)
1332
- : NUMERIC_ASSIGNMENTS(ts).has(operator);
1333
- }
1334
- else
1335
- ok = !ts.isDeleteExpression(parent);
1336
- return;
1337
- }
1338
- ts.forEachChild(node, visit);
1339
- };
1340
- visit(source);
1341
- return ok;
1342
- }
1343
- function templateShape(ts, template, scope) {
1344
- let staticText = template.head.text;
1345
- let dynamic = false;
1346
- for (const span of template.templateSpans) {
1347
- const resolved = scope === undefined
1348
- ? undefined
1349
- : (placeholderNumber(ts, staticText, span.expression, 0) ??
1350
- resolveStaticSqlText(ts, span.expression, scope, 0));
1351
- if (resolved === undefined)
1352
- dynamic = true;
1353
- else
1354
- staticText += resolved;
1355
- staticText += span.literal.text;
1356
- }
1357
- return { staticText, dynamic };
1358
- }
1359
- function isReassignedInFile(ts, source, name) {
1360
- let found = false;
1361
- const visit = (node) => {
1362
- if (found)
1363
- return;
1364
- if (ts.isBinaryExpression(node) &&
1365
- node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
1366
- node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
1367
- ts.isIdentifier(node.left) &&
1368
- node.left.text === name) {
1369
- found = true;
1370
- return;
1371
- }
1372
- if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
1373
- (node.operator === ts.SyntaxKind.PlusPlusToken ||
1374
- node.operator === ts.SyntaxKind.MinusMinusToken) &&
1375
- ts.isIdentifier(node.operand) &&
1376
- node.operand.text === name) {
1377
- found = true;
1378
- return;
1379
- }
1380
- ts.forEachChild(node, visit);
1381
- };
1382
- visit(source);
1383
- return found;
1384
- }
1385
- function bindingNameCovers(ts, binding, name) {
1386
- return ts.isIdentifier(binding)
1387
- ? binding.text === name
1388
- : binding.elements.some((element) => !ts.isOmittedExpression(element) &&
1389
- (ts.isIdentifier(element.name)
1390
- ? element.name.text === name
1391
- : bindingNameCovers(ts, element.name, name)));
1392
- }
1393
- function directBinding(ts, source, scope, name) {
1394
- if (ts.isFunctionLike(scope)) {
1395
- for (const parameter of scope.parameters) {
1396
- if (bindingNameCovers(ts, parameter.name, name))
1397
- return "shadow";
1398
- }
1399
- }
1400
- if (ts.isCatchClause(scope)) {
1401
- const declared = scope.variableDeclaration;
1402
- if (declared !== undefined && bindingNameCovers(ts, declared.name, name))
1403
- return "shadow";
1404
- }
1405
- for (const statement of scopeStatements(ts, scope) ?? []) {
1406
- if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
1407
- statement.name?.text === name) {
1408
- return "shadow";
1409
- }
1410
- }
1411
- for (const list of scopeDeclarationLists(ts, scope)) {
1412
- for (const declaration of list.declarations) {
1413
- if (!bindingNameCovers(ts, declaration.name, name))
1414
- continue;
1415
- if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined)
1416
- return "shadow";
1417
- const isConst = (list.flags & ts.NodeFlags.Const) !== 0;
1418
- const isLet = (list.flags & ts.NodeFlags.Let) !== 0;
1419
- if (isConst)
1420
- return { initializer: declaration.initializer, constant: true };
1421
- if (isLet && !isReassignedInFile(ts, source, name))
1422
- return { initializer: declaration.initializer, constant: false };
1423
- return "shadow";
1424
- }
1425
- }
1426
- return undefined;
1427
- }
1428
- function scopeStatements(ts, scope) {
1429
- return ts.isSourceFile(scope) ||
1430
- ts.isBlock(scope) ||
1431
- ts.isModuleBlock(scope) ||
1432
- ts.isCaseClause(scope) ||
1433
- ts.isDefaultClause(scope)
1434
- ? scope.statements
1435
- : undefined;
1436
- }
1437
- function scopeDeclarationLists(ts, scope) {
1438
- const lists = [];
1439
- for (const statement of scopeStatements(ts, scope) ?? []) {
1440
- if (ts.isVariableStatement(statement))
1441
- lists.push(statement.declarationList);
1442
- }
1443
- if ((ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) &&
1444
- scope.initializer !== undefined &&
1445
- ts.isVariableDeclarationList(scope.initializer)) {
1446
- lists.push(scope.initializer);
1447
- }
1448
- return lists;
1449
- }
1450
- function mutableDeclaration(ts, scope, name) {
1451
- for (const list of scopeDeclarationLists(ts, scope)) {
1452
- if ((list.flags & ts.NodeFlags.Const) !== 0)
1453
- continue;
1454
- for (const declaration of list.declarations) {
1455
- if (ts.isIdentifier(declaration.name) && declaration.name.text === name)
1456
- return declaration;
1457
- }
1458
- }
1459
- return undefined;
1460
- }
1461
- function variableWrites(ts, node) {
1462
- const source = node.getSourceFile();
1463
- const name = node.text;
1464
- for (let scope = node.parent; scope !== undefined; scope = scope.parent) {
1465
- const binding = directBinding(ts, source, scope, name);
1466
- if (binding === "shadow") {
1467
- const declaration = mutableDeclaration(ts, scope, name);
1468
- if (declaration === undefined)
1469
- return undefined;
1470
- let owner = declaration;
1471
- while (!ts.isFunctionLike(owner) && !ts.isSourceFile(owner))
1472
- owner = owner.parent;
1473
- const writes = writesTo(ts, owner, name);
1474
- return {
1475
- key: declaration,
1476
- writes: declaration.initializer === undefined
1477
- ? writes
1478
- : [{ value: declaration.initializer, appends: false }, ...writes],
1479
- };
1480
- }
1481
- if (binding !== undefined) {
1482
- return { key: binding.initializer, writes: [{ value: binding.initializer, appends: false }] };
1483
- }
1484
- if (ts.isSourceFile(scope))
1485
- break;
1486
- }
1487
- return undefined;
1488
- }
1489
- function writesTo(ts, root, name) {
1490
- const writes = [];
1491
- const visit = (node) => {
1492
- if (ts.isIdentifier(node) && node.text === name) {
1493
- const parent = node.parent;
1494
- if (ts.isBinaryExpression(parent) && parent.left === node) {
1495
- const operator = parent.operatorToken.kind;
1496
- if (operator === ts.SyntaxKind.PlusEqualsToken) {
1497
- writes.push({ value: parent.right, appends: true });
1498
- }
1499
- else if (operator === ts.SyntaxKind.EqualsToken ||
1500
- operator === ts.SyntaxKind.QuestionQuestionEqualsToken ||
1501
- operator === ts.SyntaxKind.BarBarEqualsToken ||
1502
- operator === ts.SyntaxKind.AmpersandAmpersandEqualsToken) {
1503
- writes.push({ value: parent.right, appends: false });
1504
- }
1505
- }
1506
- }
1507
- ts.forEachChild(node, visit);
1508
- };
1509
- visit(root);
1510
- return writes;
1511
- }
1512
- function mentionsName(ts, node, name) {
1513
- if (ts.isPropertyAccessExpression(node))
1514
- return mentionsName(ts, node.expression, name);
1515
- if (ts.isPropertyAssignment(node)) {
1516
- return (mentionsName(ts, node.initializer, name) ||
1517
- (ts.isComputedPropertyName(node.name) && mentionsName(ts, node.name.expression, name)));
1518
- }
1519
- if (ts.isIdentifier(node))
1520
- return node.text === name;
1521
- return ts.forEachChild(node, (child) => mentionsName(ts, child, name) || undefined) === true;
1522
- }
1523
- const UNKNOWN_SQL = {
1524
- staticText: "",
1525
- dynamic: true,
1526
- concatenated: false,
1527
- literal: false,
1528
- parameterizedTag: false,
1529
- };
1530
- function textShape(text) {
1531
- return {
1532
- staticText: text,
1533
- dynamic: false,
1534
- concatenated: false,
1535
- literal: true,
1536
- parameterizedTag: false,
1537
- };
1538
- }
1539
- function joinShapes(shapes) {
1540
- return {
1541
- staticText: shapes.map((shape) => shape.staticText).join(""),
1542
- dynamic: shapes.some((shape) => shape.dynamic || shape.parameterizedTag),
1543
- concatenated: true,
1544
- literal: false,
1545
- parameterizedTag: false,
1546
- };
1547
- }
1548
- function sqlRisk(shape) {
1549
- const dynamic = !shape.dynamic
1550
- ? 0
1551
- : SQL_KEYWORD.test(shape.staticText) || STATEMENT_START.test(shape.staticText)
1552
- ? 3
1553
- : shape.concatenated
1554
- ? 2
1555
- : 1;
1556
- return dynamic * 2 + (shape.parameterizedTag ? 0 : 1);
1557
- }
1558
- function writtenShape(ts, name, writes, scope, trail) {
1559
- const replacing = [];
1560
- const building = [];
1561
- for (const write of writes) {
1562
- const shape = sqlExpressionShape(ts, write.value, scope, trail);
1563
- if (write.appends || mentionsName(ts, write.value, name))
1564
- building.push(shape);
1565
- else
1566
- replacing.push(shape);
1567
- }
1568
- const candidates = building.length === 0 ? replacing : [...replacing, joinShapes([...replacing, ...building])];
1569
- let worst;
1570
- for (const candidate of candidates) {
1571
- if (worst === undefined || sqlRisk(candidate) > sqlRisk(worst))
1572
- worst = candidate;
1573
- }
1574
- return worst ?? UNKNOWN_SQL;
1575
- }
1576
- const TEXT_METHODS = new Set([
1577
- "toString",
1578
- "valueOf",
1579
- "trim",
1580
- "trimStart",
1581
- "trimEnd",
1582
- "toLowerCase",
1583
- "toUpperCase",
1584
- ]);
1585
- function passedThrough(ts, call) {
1586
- const callee = call.expression;
1587
- if (ts.isIdentifier(callee) && callee.text === "String" && call.arguments.length === 1) {
1588
- return call.arguments[0];
1589
- }
1590
- if (ts.isPropertyAccessExpression(callee) &&
1591
- TEXT_METHODS.has(callee.name.text) &&
1592
- call.arguments.length === 0) {
1593
- return callee.expression;
1594
- }
1595
- return undefined;
1596
- }
1597
- function joinedParts(ts, call) {
1598
- const callee = call.expression;
1599
- if (!ts.isPropertyAccessExpression(callee))
1600
- return undefined;
1601
- if (callee.name.text === "concat")
1602
- return [callee.expression, ...call.arguments];
1603
- const items = unwrapExpression(ts, callee.expression);
1604
- if (callee.name.text !== "join" || !ts.isArrayLiteralExpression(items))
1605
- return undefined;
1606
- const separator = call.arguments[0];
1607
- const glue = separator === undefined ? "," : ts.isStringLiteralLike(separator) ? separator.text : separator;
1608
- const parts = [];
1609
- items.elements.forEach((element, index) => {
1610
- if (index > 0)
1611
- parts.push(glue);
1612
- if (ts.isSpreadElement(element))
1613
- parts.push(element.expression);
1614
- else if (!ts.isOmittedExpression(element))
1615
- parts.push(element);
1616
- });
1617
- return parts;
1618
- }
1619
- function definesSqlFunction(ts, tag) {
1620
- for (let scope = tag.parent; scope !== undefined; scope = scope.parent) {
1621
- if (ts.isFunctionLike(scope) &&
1622
- scope.parameters.some((parameter) => bindingNameCovers(ts, parameter.name, tag.text))) {
1623
- return false;
1624
- }
1625
- for (const statement of scopeStatements(ts, scope) ?? []) {
1626
- if (ts.isFunctionDeclaration(statement) && statement.name?.text === tag.text)
1627
- return true;
1628
- }
1629
- for (const list of scopeDeclarationLists(ts, scope)) {
1630
- for (const declaration of list.declarations) {
1631
- if (!ts.isIdentifier(declaration.name) || declaration.name.text !== tag.text)
1632
- continue;
1633
- const value = declaration.initializer === undefined
1634
- ? undefined
1635
- : unwrapExpression(ts, declaration.initializer);
1636
- return value !== undefined && (ts.isArrowFunction(value) || ts.isFunctionExpression(value));
1637
- }
1638
- }
1639
- }
1640
- return false;
1641
- }
1642
- function sqlExpressionShape(ts, expression, scope, trail = []) {
1643
- let node = unwrapExpression(ts, expression);
1644
- while (ts.isNonNullExpression(node))
1645
- node = unwrapExpression(ts, node.expression);
1646
- if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
1647
- return {
1648
- staticText: node.text,
1649
- dynamic: false,
1650
- concatenated: false,
1651
- literal: true,
1652
- parameterizedTag: false,
1653
- };
1654
- }
1655
- if (ts.isTaggedTemplateExpression(node)) {
1656
- const tag = node.tag;
1657
- const parameterizedTag = (ts.isIdentifier(tag) && tag.text === "sql" && !definesSqlFunction(ts, tag)) ||
1658
- (ts.isPropertyAccessExpression(tag) && tag.getText() === "Prisma.sql");
1659
- const template = node.template;
1660
- const templated = ts.isTemplateExpression(template)
1661
- ? templateShape(ts, template, parameterizedTag ? undefined : scope)
1662
- : { staticText: template.text, dynamic: false };
1663
- const staticText = templated.staticText;
1664
- return {
1665
- staticText,
1666
- dynamic: templated.dynamic && !parameterizedTag,
1667
- concatenated: false,
1668
- literal: !ts.isTemplateExpression(template),
1669
- parameterizedTag,
1670
- };
1671
- }
1672
- if (ts.isTemplateExpression(node)) {
1673
- const templated = templateShape(ts, node, scope);
1674
- return {
1675
- staticText: templated.staticText,
1676
- dynamic: templated.dynamic,
1677
- concatenated: [node.head, ...node.templateSpans.map((span) => span.literal)].every((part) => part.text.trim() === ""),
1678
- literal: false,
1679
- parameterizedTag: false,
1680
- };
1681
- }
1682
- if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
1683
- const left = sqlExpressionShape(ts, node.left, scope, trail);
1684
- const right = sqlExpressionShape(ts, node.right, scope, trail);
1685
- return {
1686
- staticText: left.staticText + right.staticText,
1687
- dynamic: left.dynamic || right.dynamic || left.parameterizedTag || right.parameterizedTag,
1688
- concatenated: true,
1689
- literal: left.literal && right.literal,
1690
- parameterizedTag: false,
1691
- };
1692
- }
1693
- if (scope !== undefined) {
1694
- const resolved = resolveStaticSqlText(ts, node, scope, 0);
1695
- if (resolved !== undefined) {
1696
- return {
1697
- staticText: resolved,
1698
- dynamic: false,
1699
- concatenated: false,
1700
- literal: false,
1701
- parameterizedTag: false,
1702
- };
1703
- }
1704
- }
1705
- if (ts.isCallExpression(node)) {
1706
- const inner = passedThrough(ts, node);
1707
- if (inner !== undefined)
1708
- return { ...sqlExpressionShape(ts, inner, scope, trail), literal: false };
1709
- const parts = joinedParts(ts, node);
1710
- if (parts !== undefined) {
1711
- return joinShapes(parts.map((part) => typeof part === "string" ? textShape(part) : sqlExpressionShape(ts, part, scope, trail)));
1712
- }
1713
- }
1714
- if (ts.isIdentifier(node)) {
1715
- const read = variableWrites(ts, node);
1716
- if (read !== undefined && trail.includes(read.key))
1717
- return { ...textShape(""), literal: false };
1718
- if (read !== undefined && trail.length <= CONST_RESOLUTION_DEPTH) {
1719
- const written = writtenShape(ts, node.text, read.writes, scope, [...trail, read.key]);
1720
- return { ...written, literal: false };
1721
- }
1722
- }
1723
- return UNKNOWN_SQL;
1724
- }
1725
- function sqlMethod(ts, call) {
1726
- const sink = (method, receiver) => SQL_METHODS.has(method) || DRIVER_READ_METHODS.has(method)
1727
- ? { method, receiver: receiver?.getText() }
1728
- : undefined;
1729
- const callee = call.expression;
1730
- if (ts.isPropertyAccessExpression(callee) &&
1731
- callee.name.text === "raw" &&
1732
- ts.isIdentifier(callee.expression) &&
1733
- callee.expression.text === "$state") {
1734
- const source = callee.getSourceFile();
1735
- const imported = source.statements.some((statement) => {
1736
- if (ts.isImportEqualsDeclaration(statement))
1737
- return statement.name.text === "$state";
1738
- if (!ts.isImportDeclaration(statement))
1739
- return false;
1740
- const clause = statement.importClause;
1741
- const bindings = clause?.namedBindings;
1742
- return (clause?.name?.text === "$state" ||
1743
- (bindings !== undefined &&
1744
- (ts.isNamespaceImport(bindings)
1745
- ? bindings.name.text === "$state"
1746
- : bindings.elements.some((binding) => binding.name.text === "$state"))));
1747
- });
1748
- let bound = imported || isShadowedAt(ts, callee.expression, "$state");
1749
- for (let scope = callee.parent; scope !== undefined && !bound; scope = scope.parent) {
1750
- bound = directBinding(ts, source, scope, "$state") !== undefined;
1751
- }
1752
- if (/\.svelte(?:\.[jt]s)?$/.test(source.fileName) && !bound)
1753
- return undefined;
1754
- }
1755
- if (ts.isIdentifier(callee))
1756
- return sink(callee.text, undefined);
1757
- if (ts.isPropertyAccessExpression(callee))
1758
- return sink(callee.name.text, callee.expression);
1759
- if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
1760
- return sink(callee.argumentExpression.text, callee.expression);
1761
- }
1762
- return undefined;
1763
- }
1764
- const SQL_RECEIVER = /(?:^|\.)(?:db|sql|prisma|drizzle|database|conn|connection|client|tx)$/i;
1765
- function isAssembledSql(sink, shape) {
1766
- if (!shape.dynamic)
1767
- return false;
1768
- if (sink.receiver === undefined || DRIVER_READ_METHODS.has(sink.method)) {
1769
- return STATEMENT_START.test(shape.staticText);
1770
- }
1771
- return (SQL_KEYWORD.test(shape.staticText) || (shape.concatenated && SQL_RECEIVER.test(sink.receiver)));
1772
- }
1773
- function statementArgument(ts, argument) {
1774
- const node = unwrapExpression(ts, argument);
1775
- if (!ts.isObjectLiteralExpression(node))
1776
- return argument;
1777
- for (const property of node.properties) {
1778
- if (ts.isShorthandPropertyAssignment(property) && STATEMENT_KEYS.has(property.name.text)) {
1779
- return property.name;
1780
- }
1781
- if (ts.isPropertyAssignment(property) &&
1782
- (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
1783
- STATEMENT_KEYS.has(property.name.text)) {
1784
- return property.initializer;
1785
- }
1786
- }
1787
- return undefined;
1788
- }
1789
- const STATEMENT_KEYS = new Set(["text", "sql"]);
1790
- function statementHelpers(ts, source) {
1791
- const helpers = new Map();
1792
- const visit = (node) => {
1793
- const sink = ts.isCallExpression(node) ? sqlMethod(ts, node) : undefined;
1794
- const passed = sink !== undefined && ts.isCallExpression(node) ? node.arguments[0] : undefined;
1795
- const argument = passed === undefined ? undefined : statementArgument(ts, passed);
1796
- const statement = argument === undefined ? undefined : unwrapExpression(ts, argument);
1797
- if (sink !== undefined && statement !== undefined && ts.isIdentifier(statement)) {
1798
- const binding = nameBinding(ts, statement);
1799
- const name = binding.kind === "parameter" ? functionName(ts, binding.fn) : undefined;
1800
- if (binding.kind === "parameter" && name !== undefined && !helpers.has(name)) {
1801
- helpers.set(name, { position: binding.position, sink });
1802
- }
1803
- }
1804
- ts.forEachChild(node, visit);
1805
- };
1806
- visit(source);
1807
- return helpers;
1808
- }
1809
- function functionName(ts, fn) {
1810
- if (ts.isFunctionDeclaration(fn))
1811
- return fn.name?.text;
1812
- if ((ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) &&
1813
- ts.isVariableDeclaration(fn.parent) &&
1814
- ts.isIdentifier(fn.parent.name)) {
1815
- return fn.parent.name.text;
1816
- }
1817
- return undefined;
1818
- }
1819
- function literalsBlanked(ts, source, content) {
1820
- const out = content.split("");
1821
- const visit = (node) => {
1822
- if (ts.isStringLiteralLike(node) ||
1823
- ts.isTemplateHead(node) ||
1824
- ts.isTemplateMiddle(node) ||
1825
- ts.isTemplateTail(node) ||
1826
- ts.isRegularExpressionLiteral(node) ||
1827
- ts.isJsxText(node)) {
1828
- for (let i = node.getStart(source); i < node.end; i++)
1829
- if (out[i] !== "\n")
1830
- out[i] = " ";
1831
- return;
1832
- }
1833
- ts.forEachChild(node, visit);
1834
- };
1835
- visit(source);
1836
- return out.join("");
1837
- }
1838
- const SQL_DYNAMIC_EXPECTATION = ["NF-C006", "sql-dynamic"];
1839
- export function scanInterpolatedSql(file, content, ts, imports) {
1840
- return scanSqlSites(file, content, ts, imports).filter((site) => site.expected === undefined);
1841
- }
1842
- export function scanSqlSites(file, content, ts, imports, parse = (path, text) => parseSqlSource(ts, path, text)) {
1843
- const out = [];
1844
- const lines = content.split("\n");
1845
- const source = parse(file, content);
1846
- if (source === undefined)
1847
- return out;
1848
- const scope = { module: sqlModuleScope(ts, file, source), imports };
1849
- const helpers = statementHelpers(ts, source);
1850
- let markerLines;
1851
- const visit = (node) => {
1852
- if (ts.isCallExpression(node)) {
1853
- const helper = ts.isIdentifier(node.expression)
1854
- ? helpers.get(node.expression.text)
1855
- : undefined;
1856
- const sink = helper?.sink ?? sqlMethod(ts, node);
1857
- const passed = node.arguments[helper?.position ?? 0];
1858
- const argument = passed === undefined ? undefined : statementArgument(ts, passed);
1859
- if (sink !== undefined && argument !== undefined) {
1860
- const shape = sqlExpressionShape(ts, argument, scope);
1861
- const unsafeEscape = helper === undefined &&
1862
- sink.receiver !== undefined &&
1863
- ALWAYS_UNSAFE.has(sink.method) &&
1864
- !shape.literal &&
1865
- !shape.parameterizedTag;
1866
- if (unsafeEscape || isAssembledSql(sink, shape)) {
1867
- const index = node.getStart(source);
1868
- const line = source.getLineAndCharacterOfPosition(index).line + 1;
1869
- markerLines ??= literalsBlanked(ts, source, content).split("\n");
1870
- const reason = commentBlockExpectation(markerLines, line, SQL_DYNAMIC_EXPECTATION)?.reason;
1871
- const site = { file, line, snippet: (lines[line - 1] ?? "").trim() };
1872
- out.push(reason === undefined ? site : { ...site, expected: reason });
1873
- }
1874
- }
1875
- }
1876
- ts.forEachChild(node, visit);
1877
- };
1878
- visit(source);
1879
- return out;
1880
- }
1881
- export async function scanProjectSql(cwd) {
1882
- const sourceFiles = [];
1883
- await walkSource(cwd, (file, content) => sourceFiles.push({ file, content }));
1884
- const contents = new Map(sourceFiles.map(({ file, content }) => [file, content]));
1885
- const sourceIndex = {
1886
- files: sourceFiles.map(({ file }) => file),
1887
- read: (file) => contents.get(file),
1888
- };
1889
- const loaded = await loadProjectTypeScript(cwd, undefined, sourceIndex);
1890
- if (loaded.compiler === undefined)
1891
- return undefined;
1892
- const out = [];
1893
- const imports = createProjectSqlImports(cwd);
1894
- try {
1895
- for (const { file, content } of sourceFiles) {
1896
- out.push(...scanInterpolatedSql(file, content, loaded.compiler, imports));
1897
- }
1898
- return out.sort(bySite);
1899
- }
1900
- finally {
1901
- await loaded.session?.close();
1902
- }
1903
- }
1904
- const SQL_DECLARATION_FILE = /\.d\.[cm]?ts$/;
1905
- const SQL_SOURCE_FILE = /\.[cm]?tsx?$/;
1906
- export function createProjectSqlImports(cwd) {
1907
- const root = realpathOrSelf(resolve(cwd));
1908
- return createSqlImports((fromModule, specifier) => {
1909
- if (!isRelativeSpecifier(specifier))
1910
- return undefined;
1911
- try {
1912
- const fromAbs = isAbsolute(fromModule) ? fromModule : join(root, fromModule);
1913
- const resolved = realpathSync(Bun.resolveSync(specifier, dirname(fromAbs)));
1914
- if (!resolved.startsWith(root + sep))
1915
- return undefined;
1916
- const rel = resolved.slice(root.length + 1);
1917
- if (IGNORED_DIR.test(rel))
1918
- return undefined;
1919
- if (SQL_DECLARATION_FILE.test(resolved) || !SQL_SOURCE_FILE.test(resolved))
1920
- return undefined;
1921
- return { id: resolved, content: readFileSync(resolved, "utf8") };
1922
- }
1923
- catch {
1924
- return undefined;
1925
- }
1926
- });
1927
- }
740
+ export { createProjectSqlImports, createSqlImports, scanInterpolatedSql, scanProjectSql, scanSqlSites, } from "./check-scan-sql.js";
1928
741
  const CLIENT_CALL = /(?<![.\w])client\s*\(/g;
1929
742
  export function scanUntypedClient(file, content) {
1930
743
  const out = [];
@@ -2058,7 +871,7 @@ function hasBackendOnlyMarker(content) {
2058
871
  }
2059
872
  return false;
2060
873
  }
2061
- const isRelativeSpecifier = (spec) => spec.startsWith("./") || spec.startsWith("../");
874
+ export const isRelativeSpecifier = (spec) => spec.startsWith("./") || spec.startsWith("../");
2062
875
  const staticImportRegex = () => new RegExp(STATIC_IMPORT.source, STATIC_IMPORT.flags);
2063
876
  function staticImportEdges(content, facts, file, positions = codePositionMask(content)) {
2064
877
  const edges = [];
@@ -2414,7 +1227,7 @@ export function componentScripts(text) {
2414
1227
  }
2415
1228
  return out + blank(text.slice(at));
2416
1229
  }
2417
- const bySite = (a, b) => codeUnitOrder(a.file, b.file) || a.line - b.line;
1230
+ export const bySite = (a, b) => codeUnitOrder(a.file, b.file) || a.line - b.line;
2418
1231
  export async function scanProject(cwd) {
2419
1232
  const out = [];
2420
1233
  await walkSource(cwd, (rel, content) => out.push(...scanFetchText(rel, content)));