@nifrajs/cli 5.17.0 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/CHANGELOG.md +50 -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
@@ -0,0 +1,870 @@
1
+ /**
2
+ * Route source splitting and module merging for `nifra migrate layout`.
3
+ */
4
+ import { BACKEND_ROUTE_EXPORTS } from "@nifrajs/web/route-manifest"
5
+ import type * as TS from "typescript"
6
+ import { codeUnitOrder } from "./internal/code-unit-order.ts"
7
+ import { escapeRegExp } from "./internal/escape-regexp.ts"
8
+
9
+ const BACKEND_EXPORTS = BACKEND_ROUTE_EXPORTS
10
+ // ---------------------------------------------------------------------------------------------------
11
+ // Route splitting
12
+ // ---------------------------------------------------------------------------------------------------
13
+
14
+ interface StatementInfo {
15
+ readonly node: TS.Statement
16
+ /** Text including leading comments. */
17
+ readonly text: string
18
+ readonly declares: ReadonlySet<string>
19
+ /** Names this statement exports, local name -> exported names. */
20
+ readonly exports: ReadonlyMap<string, readonly string[]>
21
+ readonly valueRefs: ReadonlySet<string>
22
+ readonly typeRefs: ReadonlySet<string>
23
+ /** A local `export { a, b as c }`: each entry, which the reachability of its own half follows. */
24
+ readonly listed: ReadonlyArray<ListedExport>
25
+ }
26
+
27
+ interface ListedExport {
28
+ readonly exported: string
29
+ readonly local: string
30
+ /** `export type { X }` or `export { type X }`: a read in a type position. */
31
+ readonly type: boolean
32
+ }
33
+
34
+ /** The names one half reads, by position. */
35
+ interface Uses {
36
+ readonly value: ReadonlySet<string>
37
+ readonly type: ReadonlySet<string>
38
+ }
39
+
40
+ export interface SplitResult {
41
+ readonly frontend: string
42
+ /** `undefined` when the file exports nothing for the server. */
43
+ readonly backend: string | undefined
44
+ /** The module beside the route that holds constant data both halves import, when there is any. */
45
+ readonly shared?: string
46
+ readonly moved: readonly string[]
47
+ readonly issues: readonly string[]
48
+ }
49
+
50
+ function bindingNames(ts: typeof TS, name: TS.BindingName, into: Set<string>): void {
51
+ if (ts.isIdentifier(name)) into.add(name.text)
52
+ else
53
+ for (const element of name.elements)
54
+ if (!ts.isOmittedExpression(element)) bindingNames(ts, element.name, into)
55
+ }
56
+
57
+ export const hasModifier = (ts: typeof TS, node: TS.Node, kind: TS.SyntaxKind): boolean =>
58
+ (ts.canHaveModifiers(node) ? (ts.getModifiers(node) ?? []) : []).some((m) => m.kind === kind)
59
+
60
+ /** Identifiers a statement reads, split into value and type positions. Over-approximates on purpose:
61
+ * an extra name only keeps a declaration in a half that did not need it. */
62
+ interface JsxBindings {
63
+ readonly element: readonly string[]
64
+ readonly fragment: readonly string[]
65
+ }
66
+
67
+ /**
68
+ * The bindings classic JSX compiles to calls of, which no identifier in the source names: the roots
69
+ * of the `@jsx`/`@jsxFrag` pragmas, else TypeScript's default `React`. A file that names its own
70
+ * `@jsxImportSource` imports the runtime itself.
71
+ */
72
+ function jsxBindings(ts: typeof TS, source: string): JsxBindings {
73
+ const comments = (ts.getLeadingCommentRanges(source, 0) ?? [])
74
+ .map(({ pos, end }) => source.slice(pos, end))
75
+ .join("\n")
76
+ if (/@jsxImportSource\s/.test(comments)) return { element: [], fragment: [] }
77
+ const root = (pragma: string): string | undefined =>
78
+ new RegExp(`@${pragma}\\s+([A-Za-z_$][\\w$]*)`).exec(comments)?.[1]
79
+ const element = root("jsx") ?? "React"
80
+ return { element: [element], fragment: [root("jsxFrag") ?? element] }
81
+ }
82
+
83
+ function references(
84
+ ts: typeof TS,
85
+ node: TS.Node,
86
+ jsx: JsxBindings,
87
+ ): { value: Set<string>; type: Set<string> } {
88
+ const value = new Set<string>()
89
+ const type = new Set<string>()
90
+ const visit = (current: TS.Node, inType: boolean): void => {
91
+ if (ts.isJsxOpeningElement(current) || ts.isJsxSelfClosingElement(current))
92
+ for (const name of jsx.element) value.add(name)
93
+ else if (ts.isJsxFragment(current)) for (const name of jsx.fragment) value.add(name)
94
+ const typed =
95
+ inType ||
96
+ ts.isTypeNode(current) ||
97
+ // nifra-expect NF-S002: `token` is the heritage clause's syntax kind, not a credential.
98
+ (ts.isHeritageClause(current) && current.token === ts.SyntaxKind.ImplementsKeyword)
99
+ if (ts.isIdentifier(current)) {
100
+ const parent = current.parent
101
+ const isName =
102
+ parent !== undefined &&
103
+ ((ts.isPropertyAccessExpression(parent) && parent.name === current) ||
104
+ (ts.isPropertyAssignment(parent) && parent.name === current) ||
105
+ (ts.isPropertySignature(parent) && parent.name === current) ||
106
+ (ts.isPropertyDeclaration(parent) && parent.name === current) ||
107
+ (ts.isMethodDeclaration(parent) && parent.name === current) ||
108
+ (ts.isMethodSignature(parent) && parent.name === current) ||
109
+ (ts.isQualifiedName(parent) && parent.right === current) ||
110
+ (ts.isJsxAttribute(parent) && parent.name === current) ||
111
+ (ts.isBindingElement(parent) && parent.propertyName === current) ||
112
+ ts.isImportSpecifier(parent) ||
113
+ ts.isExportSpecifier(parent) ||
114
+ ts.isImportClause(parent) ||
115
+ ts.isNamespaceImport(parent))
116
+ if (!isName) (typed ? type : value).add(current.text)
117
+ return
118
+ }
119
+ if (ts.isShorthandPropertyAssignment(current)) value.add(current.name.text)
120
+ ts.forEachChild(current, (child) => visit(child, typed))
121
+ }
122
+ visit(node, false)
123
+ return { value, type }
124
+ }
125
+
126
+ function describeStatements(ts: typeof TS, sf: TS.SourceFile): StatementInfo[] {
127
+ const jsx = jsxBindings(ts, sf.text)
128
+ return sf.statements.map((node) => {
129
+ const declares = new Set<string>()
130
+ const exports = new Map<string, string[]>()
131
+ const listed: ListedExport[] = []
132
+ const exported = hasModifier(ts, node, ts.SyntaxKind.ExportKeyword)
133
+ const isDefault = hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword)
134
+ const addExport = (local: string, as: string): void => {
135
+ exports.set(local, [...(exports.get(local) ?? []), as])
136
+ }
137
+ if (ts.isImportDeclaration(node)) {
138
+ const clause = node.importClause
139
+ if (clause?.name) declares.add(clause.name.text)
140
+ const bindings = clause?.namedBindings
141
+ if (bindings && ts.isNamespaceImport(bindings)) declares.add(bindings.name.text)
142
+ if (bindings && ts.isNamedImports(bindings))
143
+ for (const el of bindings.elements) declares.add(el.name.text)
144
+ } else if (ts.isVariableStatement(node)) {
145
+ for (const decl of node.declarationList.declarations) {
146
+ const names = new Set<string>()
147
+ bindingNames(ts, decl.name, names)
148
+ for (const name of names) {
149
+ declares.add(name)
150
+ if (exported) addExport(name, name)
151
+ }
152
+ }
153
+ } else if (
154
+ ts.isFunctionDeclaration(node) ||
155
+ ts.isClassDeclaration(node) ||
156
+ ts.isInterfaceDeclaration(node) ||
157
+ ts.isTypeAliasDeclaration(node) ||
158
+ ts.isEnumDeclaration(node)
159
+ ) {
160
+ const name = node.name?.text
161
+ if (name !== undefined) declares.add(name)
162
+ if (exported) addExport(name ?? "default", isDefault ? "default" : (name ?? "default"))
163
+ } else if (ts.isExportAssignment(node)) {
164
+ addExport("default", "default")
165
+ } else if (
166
+ ts.isExportDeclaration(node) &&
167
+ node.exportClause &&
168
+ ts.isNamedExports(node.exportClause)
169
+ ) {
170
+ for (const el of node.exportClause.elements) {
171
+ const local = (el.propertyName ?? el.name).text
172
+ addExport(node.moduleSpecifier ? `\0${el.name.text}` : local, el.name.text)
173
+ if (node.moduleSpecifier === undefined)
174
+ listed.push({ exported: el.name.text, local, type: node.isTypeOnly || el.isTypeOnly })
175
+ }
176
+ }
177
+ const refs = ts.isImportDeclaration(node)
178
+ ? { value: new Set<string>(), type: new Set<string>() }
179
+ : references(ts, node, jsx)
180
+ for (const name of declares) {
181
+ refs.value.delete(name)
182
+ refs.type.delete(name)
183
+ }
184
+ return {
185
+ node,
186
+ text: node.getFullText(sf),
187
+ declares,
188
+ exports,
189
+ valueRefs: refs.value,
190
+ typeRefs: refs.type,
191
+ listed,
192
+ }
193
+ })
194
+ }
195
+
196
+ /**
197
+ * Rebuild an import keeping only the bindings `uses` names; `undefined` when none remain. Bindings
198
+ * read only in types become `import type`, so no bundler loads the module for them: always in a
199
+ * `fresh` module, and in the page only where the split narrowed the import.
200
+ */
201
+ function filterImport(
202
+ ts: typeof TS,
203
+ sf: TS.SourceFile,
204
+ node: TS.ImportDeclaration,
205
+ uses: Uses,
206
+ fresh: boolean,
207
+ ): string | undefined {
208
+ const clause = node.importClause
209
+ const spec = node.moduleSpecifier.getText(sf)
210
+ const attributes = node.attributes ? ` ${node.attributes.getText(sf)}` : ""
211
+ if (clause === undefined) return node.getFullText(sf)
212
+ interface Part {
213
+ readonly text: string
214
+ /** Without an inline `type`, for an `import type`. */
215
+ readonly bare: string
216
+ readonly typeOnly: boolean
217
+ }
218
+ const heads: Part[] = []
219
+ const named: Part[] = []
220
+ let total = 0
221
+ const add = (into: Part[], name: string, text: string, bare: string): void => {
222
+ total++
223
+ if (uses.value.has(name) || uses.type.has(name))
224
+ into.push({ text, bare, typeOnly: !uses.value.has(name) })
225
+ }
226
+ if (clause.name) add(heads, clause.name.text, clause.name.text, clause.name.text)
227
+ const bindings = clause.namedBindings
228
+ if (bindings && ts.isNamespaceImport(bindings)) {
229
+ const text = `* as ${bindings.name.text}`
230
+ add(heads, bindings.name.text, text, text)
231
+ }
232
+ if (bindings && ts.isNamedImports(bindings)) {
233
+ for (const el of bindings.elements) {
234
+ const renamed = el.propertyName ? `${el.propertyName.getText(sf)} as ` : ""
235
+ add(named, el.name.text, el.getText(sf), `${renamed}${el.name.text}`)
236
+ }
237
+ }
238
+ const kept = [...heads, ...named]
239
+ if (kept.length === 0) return undefined
240
+ const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart())
241
+ const statement = (typeOnly: boolean, body: string): string =>
242
+ `import ${typeOnly ? "type " : ""}${body} from ${spec}${attributes}${terminatorOf(sf, node)}`
243
+ const list = (parts: readonly Part[], text: (part: Part) => string): string[] =>
244
+ parts.length === 0 ? [] : [`{ ${parts.map(text).join(", ")} }`]
245
+ if (
246
+ !clause.isTypeOnly &&
247
+ node.attributes === undefined &&
248
+ (fresh || kept.length < total) &&
249
+ kept.every((part) => part.typeOnly)
250
+ ) {
251
+ // `import type` takes one default, namespace or list, so each goes in its own statement.
252
+ const bodies = [...heads.map((part) => part.bare), ...list(named, (part) => part.bare)]
253
+ return `${leading}${bodies.map((body) => statement(true, body)).join("\n")}`
254
+ }
255
+ const body = [...heads.map((part) => part.text), ...list(named, (part) => part.text)]
256
+ return `${leading}${statement(clause.isTypeOnly, body.join(", "))}`
257
+ }
258
+
259
+ /** The `;` a statement was written with, so a rebuilt one keeps the file's style. */
260
+ export const terminatorOf = (sf: TS.SourceFile, node: TS.Node): string =>
261
+ node.getText(sf).endsWith(";") ? ";" : ""
262
+
263
+ /** Rebuild `export { a, b as c }` keeping only the exported names `keep` accepts. */
264
+ function filterExportList(
265
+ ts: typeof TS,
266
+ sf: TS.SourceFile,
267
+ node: TS.ExportDeclaration,
268
+ keep: (exported: string) => boolean,
269
+ ): string | undefined {
270
+ const clause = node.exportClause
271
+ if (!clause || !ts.isNamedExports(clause)) return node.getFullText(sf)
272
+ const kept = clause.elements.filter((el) => keep(el.name.text)).map((el) => el.getText(sf))
273
+ if (kept.length === 0) return undefined
274
+ const from = node.moduleSpecifier ? ` from ${node.moduleSpecifier.getText(sf)}` : ""
275
+ const leading = node.getFullText(sf).slice(0, node.getStart(sf) - node.getFullStart())
276
+ return `${leading}export ${node.isTypeOnly ? "type " : ""}{ ${kept.join(", ")} }${from}${terminatorOf(sf, node)}`
277
+ }
278
+
279
+ const joinStatements = (texts: readonly string[]): string => {
280
+ const body = texts.join("").replace(/^\s*\n/, "")
281
+ return body.endsWith("\n") ? body : `${body}\n`
282
+ }
283
+
284
+ /** Options for {@link splitRouteSource}. */
285
+ export interface SplitOptions {
286
+ /**
287
+ * The file name of a module beside the route (`index.shared.ts`) to hold constant data both halves
288
+ * read, which each half then imports. Without it, that data is copied into each half.
289
+ */
290
+ readonly sharedFile?: string
291
+ }
292
+
293
+ const PURE_OBJECT_CALLS = new Set(["keys", "values", "entries", "freeze", "fromEntries"])
294
+
295
+ /**
296
+ * Whether `node` builds constant data: literals, arrays and objects of it, operators over it,
297
+ * `Object.keys`-style reads, and the file's own top-level names, which go into `reads`. `undefined`
298
+ * when it is data; else the import it reads, or `""` for anything else (a call, a function, a global).
299
+ */
300
+ function dataBlocker(
301
+ ts: typeof TS,
302
+ node: TS.Node,
303
+ isLocal: (name: string) => boolean,
304
+ reads: Set<string>,
305
+ ): string | undefined {
306
+ const data = (n: TS.Node): string | undefined => {
307
+ if (
308
+ ts.isStringLiteral(n) ||
309
+ ts.isNumericLiteral(n) ||
310
+ ts.isBigIntLiteral(n) ||
311
+ ts.isNoSubstitutionTemplateLiteral(n) ||
312
+ n.kind === ts.SyntaxKind.TrueKeyword ||
313
+ n.kind === ts.SyntaxKind.FalseKeyword ||
314
+ n.kind === ts.SyntaxKind.NullKeyword
315
+ )
316
+ return undefined
317
+ if (ts.isIdentifier(n)) {
318
+ if (isLocal(n.text)) {
319
+ reads.add(n.text)
320
+ return undefined
321
+ }
322
+ return n.text === "undefined" ? undefined : n.text
323
+ }
324
+ const every = (nodes: readonly TS.Node[]): string | undefined => {
325
+ for (const child of nodes) {
326
+ const blocker = data(child)
327
+ if (blocker !== undefined) return blocker
328
+ }
329
+ return undefined
330
+ }
331
+ if (ts.isTemplateExpression(n)) return every(n.templateSpans.map((span) => span.expression))
332
+ if (ts.isPrefixUnaryExpression(n))
333
+ return n.operator === ts.SyntaxKind.PlusPlusToken ||
334
+ n.operator === ts.SyntaxKind.MinusMinusToken
335
+ ? ""
336
+ : data(n.operand)
337
+ if (ts.isBinaryExpression(n)) {
338
+ const operator = n.operatorToken.kind
339
+ const assigns =
340
+ operator >= ts.SyntaxKind.FirstAssignment && operator <= ts.SyntaxKind.LastAssignment
341
+ if (
342
+ assigns ||
343
+ operator === ts.SyntaxKind.CommaToken ||
344
+ operator === ts.SyntaxKind.InKeyword ||
345
+ operator === ts.SyntaxKind.InstanceOfKeyword
346
+ )
347
+ return ""
348
+ return every([n.left, n.right])
349
+ }
350
+ if (ts.isConditionalExpression(n)) return every([n.condition, n.whenTrue, n.whenFalse])
351
+ if (ts.isArrayLiteralExpression(n))
352
+ return every(
353
+ n.elements.flatMap((element) =>
354
+ ts.isOmittedExpression(element)
355
+ ? []
356
+ : [ts.isSpreadElement(element) ? element.expression : element],
357
+ ),
358
+ )
359
+ if (ts.isObjectLiteralExpression(n)) {
360
+ for (const property of n.properties) {
361
+ const blocker = ts.isPropertyAssignment(property)
362
+ ? ((ts.isComputedPropertyName(property.name)
363
+ ? data(property.name.expression)
364
+ : undefined) ?? data(property.initializer))
365
+ : ts.isShorthandPropertyAssignment(property)
366
+ ? property.objectAssignmentInitializer === undefined
367
+ ? data(property.name)
368
+ : ""
369
+ : ts.isSpreadAssignment(property)
370
+ ? data(property.expression)
371
+ : ""
372
+ if (blocker !== undefined) return blocker
373
+ }
374
+ return undefined
375
+ }
376
+ if (
377
+ ts.isParenthesizedExpression(n) ||
378
+ ts.isAsExpression(n) ||
379
+ ts.isSatisfiesExpression(n) ||
380
+ ts.isNonNullExpression(n) ||
381
+ ts.isTypeAssertionExpression(n)
382
+ )
383
+ return data(n.expression)
384
+ if (ts.isPropertyAccessExpression(n))
385
+ return ts.isPrivateIdentifier(n.name) ? "" : data(n.expression)
386
+ if (ts.isElementAccessExpression(n)) return every([n.expression, n.argumentExpression])
387
+ if (ts.isCallExpression(n)) {
388
+ const callee = n.expression
389
+ const objectRead =
390
+ ts.isPropertyAccessExpression(callee) &&
391
+ ts.isIdentifier(callee.expression) &&
392
+ callee.expression.text === "Object" &&
393
+ !isLocal("Object") &&
394
+ PURE_OBJECT_CALLS.has(callee.name.text) &&
395
+ n.questionDotToken === undefined &&
396
+ n.typeArguments === undefined
397
+ return objectRead ? every(n.arguments) : ""
398
+ }
399
+ return ""
400
+ }
401
+ return data(node)
402
+ }
403
+
404
+ /**
405
+ * Split one route module's source into its frontend and backend halves. `backendSpecifier` is how the
406
+ * frontend refers to the backend half in an `import type` (`./index.backend.ts`).
407
+ */
408
+ export function splitRouteSource(
409
+ ts: typeof TS,
410
+ source: string,
411
+ fileName: string,
412
+ backendSpecifier: string,
413
+ options: SplitOptions = {},
414
+ ): SplitResult {
415
+ const kind = fileName.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
416
+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, kind)
417
+ const statements = describeStatements(ts, sf)
418
+ const issues: string[] = []
419
+ const exportsOf = (info: StatementInfo): string[] => [...info.exports.values()].flat()
420
+ const isBackendStatement = (info: StatementInfo): boolean =>
421
+ exportsOf(info).some((name) => BACKEND_EXPORTS.has(name))
422
+ const moved = statements.flatMap(exportsOf).filter((name) => BACKEND_EXPORTS.has(name))
423
+ if (moved.length === 0) return { frontend: source, backend: undefined, moved: [], issues: [] }
424
+
425
+ const declaredBy = new Map<string, StatementInfo>()
426
+ const importedBy = new Map<string, StatementInfo>()
427
+ for (const info of statements) {
428
+ const into = ts.isImportDeclaration(info.node) ? importedBy : declaredBy
429
+ for (const name of info.declares) into.set(name, info)
430
+ }
431
+ const isTypeDeclaration = (info: StatementInfo): boolean =>
432
+ ts.isInterfaceDeclaration(info.node) || ts.isTypeAliasDeclaration(info.node)
433
+ /** What `info` reads for one half: an export list reads only the locals it exports there. */
434
+ const readsFor = (info: StatementInfo, backend: boolean): Uses => {
435
+ if (info.listed.length === 0) return { value: info.valueRefs, type: info.typeRefs }
436
+ const mine = info.listed.filter((entry) => BACKEND_EXPORTS.has(entry.exported) === backend)
437
+ return {
438
+ value: new Set(mine.filter((entry) => !entry.type).map((entry) => entry.local)),
439
+ type: new Set(mine.filter((entry) => entry.type).map((entry) => entry.local)),
440
+ }
441
+ }
442
+ const movedLocals = new Set<string>()
443
+ for (const info of statements) {
444
+ for (const [local, names] of info.exports)
445
+ if (names.some((name) => BACKEND_EXPORTS.has(name))) movedLocals.add(local)
446
+ }
447
+
448
+ /** Each half's statements. What `shared` holds, both import, so neither half keeps a copy. */
449
+ const partition = (
450
+ shared: ReadonlySet<StatementInfo>,
451
+ ): { backendSet: Set<StatementInfo>; frontendKeep: Set<StatementInfo> } => {
452
+ const local = (name: string): StatementInfo | undefined => {
453
+ const target = declaredBy.get(name)
454
+ return target === undefined || shared.has(target) ? undefined : target
455
+ }
456
+ // The backend half: its export statements plus every top-level declaration they reach.
457
+ const backendSet = new Set<StatementInfo>()
458
+ const queue: StatementInfo[] = statements.filter(isBackendStatement)
459
+ for (const info of queue) backendSet.add(info)
460
+ while (queue.length > 0) {
461
+ const info = queue.pop()
462
+ if (info === undefined) continue
463
+ const reads = readsFor(info, true)
464
+ for (const name of [...reads.value, ...reads.type]) {
465
+ const target = local(name)
466
+ if (target !== undefined && !backendSet.has(target)) {
467
+ backendSet.add(target)
468
+ queue.push(target)
469
+ }
470
+ }
471
+ }
472
+
473
+ // The frontend half: everything that is not a backend export statement, minus declarations that
474
+ // only the backend half needs. An export list that also names backend exports keeps the rest.
475
+ const frontendKeep = new Set<StatementInfo>()
476
+ const seed = statements.filter(
477
+ (info) =>
478
+ !ts.isImportDeclaration(info.node) &&
479
+ !shared.has(info) &&
480
+ (!backendSet.has(info) ||
481
+ exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name)) ||
482
+ // a statement with no declaration (a side effect) stays where it ran
483
+ (info.declares.size === 0 && info.exports.size === 0)),
484
+ )
485
+ const fqueue = [...seed]
486
+ for (const info of fqueue) frontendKeep.add(info)
487
+ while (fqueue.length > 0) {
488
+ const info = fqueue.pop()
489
+ if (info === undefined) continue
490
+ const reads = readsFor(info, false)
491
+ for (const name of reads.value) {
492
+ if (movedLocals.has(name) && !info.declares.has(name)) continue
493
+ const target = local(name)
494
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
495
+ frontendKeep.add(target)
496
+ fqueue.push(target)
497
+ }
498
+ }
499
+ for (const name of reads.type) {
500
+ if (movedLocals.has(name)) continue
501
+ const target = local(name)
502
+ if (target !== undefined && !frontendKeep.has(target) && !isBackendStatement(target)) {
503
+ frontendKeep.add(target)
504
+ fqueue.push(target)
505
+ }
506
+ }
507
+ }
508
+ return { backendSet, frontendKeep }
509
+ }
510
+ let { backendSet, frontendKeep } = partition(new Set())
511
+ const copies = (): StatementInfo[] =>
512
+ [...frontendKeep].filter(
513
+ (info) =>
514
+ backendSet.has(info) &&
515
+ !isBackendStatement(info) &&
516
+ info.declares.size > 0 &&
517
+ !isTypeDeclaration(info),
518
+ )
519
+
520
+ // Constant data both halves read moves to a module beside the route, with the declarations it
521
+ // needs: one definition, which neither half's bundle can drift from.
522
+ const shared = new Set<StatementInfo>()
523
+ const sharedTypes = new Set<StatementInfo>()
524
+ const sharedImports = new Set<string>()
525
+ const unshared = new Map<StatementInfo, string>()
526
+ if (options.sharedFile !== undefined) {
527
+ interface Closure {
528
+ readonly values: Set<StatementInfo>
529
+ readonly types: Set<StatementInfo>
530
+ readonly imports: Set<string>
531
+ }
532
+ /** Why `info` cannot move to the shared module, or `undefined` once it and what it needs are in `closure`. */
533
+ const gather = (info: StatementInfo, closure: Closure): string | undefined => {
534
+ if (closure.values.has(info) || shared.has(info)) return undefined
535
+ const node = info.node
536
+ const reads = new Set<string>()
537
+ let blocker: string | undefined = ""
538
+ if (
539
+ !isBackendStatement(info) &&
540
+ ts.isVariableStatement(node) &&
541
+ (node.declarationList.flags & ts.NodeFlags.Const) !== 0 &&
542
+ !hasModifier(ts, node, ts.SyntaxKind.DeclareKeyword)
543
+ ) {
544
+ blocker = undefined
545
+ for (const declaration of node.declarationList.declarations) {
546
+ blocker =
547
+ ts.isIdentifier(declaration.name) && declaration.initializer !== undefined
548
+ ? dataBlocker(ts, declaration.initializer, (name) => declaredBy.has(name), reads)
549
+ : ""
550
+ if (blocker !== undefined) break
551
+ }
552
+ }
553
+ if (blocker !== undefined)
554
+ return blocker !== "" && importedBy.has(blocker)
555
+ ? `it reads the import "${blocker}"`
556
+ : "it is not constant data"
557
+ closure.values.add(info)
558
+ for (const name of reads) {
559
+ const target = declaredBy.get(name)
560
+ const why = target === undefined ? undefined : gather(target, closure)
561
+ if (why !== undefined) return `it reads "${name}", which ${why.slice(3)}`
562
+ }
563
+ for (const name of info.typeRefs) {
564
+ const why = gatherType(name, closure)
565
+ if (why !== undefined) return why
566
+ }
567
+ return undefined
568
+ }
569
+ const gatherType = (name: string, closure: Closure): string | undefined => {
570
+ const local = declaredBy.get(name)
571
+ if (local === undefined) {
572
+ if (importedBy.has(name)) closure.imports.add(name)
573
+ return undefined
574
+ }
575
+ if (!isTypeDeclaration(local)) {
576
+ const why = gather(local, closure)
577
+ return why === undefined ? undefined : `its type reads "${name}", which ${why.slice(3)}`
578
+ }
579
+ if (closure.types.has(local) || sharedTypes.has(local)) return undefined
580
+ closure.types.add(local)
581
+ for (const ref of [...local.typeRefs, ...local.valueRefs]) {
582
+ const why = gatherType(ref, closure)
583
+ if (why !== undefined) return why
584
+ }
585
+ return undefined
586
+ }
587
+ for (const info of copies()) {
588
+ const closure: Closure = { values: new Set(), types: new Set(), imports: new Set() }
589
+ const why = gather(info, closure)
590
+ if (why !== undefined) {
591
+ unshared.set(info, why)
592
+ continue
593
+ }
594
+ for (const value of closure.values) shared.add(value)
595
+ for (const type of closure.types) sharedTypes.add(type)
596
+ for (const name of closure.imports) sharedImports.add(name)
597
+ }
598
+ if (shared.size > 0) ({ backendSet, frontendKeep } = partition(shared))
599
+ }
600
+
601
+ // A moved name the frontend still mentions: in a type it becomes `import type`; at runtime it is an
602
+ // error the author has to resolve.
603
+ const typeImports = new Set<string>()
604
+ for (const info of frontendKeep) {
605
+ if (isBackendStatement(info)) continue
606
+ const reads = readsFor(info, false)
607
+ for (const name of movedLocals) {
608
+ if (info.declares.has(name)) continue
609
+ if (reads.value.has(name))
610
+ issues.push(`the frontend uses "${name}" at runtime, but it runs on the server only`)
611
+ if (reads.type.has(name) || reads.value.has(name)) typeImports.add(name)
612
+ }
613
+ }
614
+ for (const info of copies()) {
615
+ const why = unshared.get(info)
616
+ issues.push(
617
+ `"${[...info.declares].join(", ")}" is needed by both halves and was copied into each${why === undefined ? "" : `, since ${why}`}; consider moving it to shared/`,
618
+ )
619
+ }
620
+
621
+ const uses = (infos: Iterable<StatementInfo>, backend: boolean): Uses => {
622
+ const value = new Set<string>()
623
+ const type = new Set<string>()
624
+ for (const info of infos) {
625
+ const reads = readsFor(info, backend)
626
+ for (const name of reads.value) value.add(name)
627
+ for (const name of reads.type) type.add(name)
628
+ }
629
+ return { value, type }
630
+ }
631
+ const backendUses = uses(backendSet, true)
632
+ const frontendUses = uses(frontendKeep, false)
633
+
634
+ const semi = statements.some((info) => terminatorOf(sf, info.node) !== "") ? ";" : ""
635
+ // The imports the split writes quote the way the file's own imports do.
636
+ const firstImport = statements.find((info) => ts.isImportDeclaration(info.node))?.node
637
+ const quote =
638
+ firstImport !== undefined && ts.isImportDeclaration(firstImport)
639
+ ? (firstImport.moduleSpecifier.getText(sf)[0] ?? '"')
640
+ : '"'
641
+ const sharedNames = [...shared].flatMap((info) => [...info.declares])
642
+ const sharedSpecifier = (() => {
643
+ const file = options.sharedFile ?? ""
644
+ // The halves name the module the way the route names its other relative imports.
645
+ const relative = statements.flatMap((info) =>
646
+ ts.isImportDeclaration(info.node) &&
647
+ ts.isStringLiteral(info.node.moduleSpecifier) &&
648
+ info.node.moduleSpecifier.text.startsWith(".")
649
+ ? [info.node.moduleSpecifier.text]
650
+ : [],
651
+ )
652
+ const extension = relative
653
+ .map((specifier) => /\.(ts|tsx|js|jsx)$/.exec(specifier)?.[1])
654
+ .find((found) => found !== undefined)
655
+ const suffix = extension === undefined ? "" : extension.startsWith("t") ? ".ts" : ".js"
656
+ return `./${file.replace(/\.ts$/, "")}${suffix}`
657
+ })()
658
+ const sharedImport = (half: Uses): string[] => {
659
+ const names = sharedNames
660
+ .filter((name) => half.value.has(name) || half.type.has(name))
661
+ .sort(codeUnitOrder)
662
+ if (names.length === 0) return []
663
+ const typeOnly = names.every((name) => !half.value.has(name))
664
+ return [
665
+ `\nimport ${typeOnly ? "type " : ""}{ ${names.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
666
+ ]
667
+ }
668
+ // The page still exports what it exported, now from the shared module.
669
+ const reexported = [...shared].flatMap((info) =>
670
+ [...info.exports].flatMap(([local, names]) =>
671
+ names.map((name) => (name === local ? local : `${local} as ${name}`)),
672
+ ),
673
+ )
674
+
675
+ const backendTexts: string[] = []
676
+ const frontendTexts: string[] = []
677
+ let afterImports = 0
678
+ let backendAfterImports = 0
679
+ for (const info of statements) {
680
+ const node = info.node
681
+ if (ts.isImportDeclaration(node)) {
682
+ const back = filterImport(ts, sf, node, backendUses, true)
683
+ if (back !== undefined) backendTexts.push(node.importClause ? back : "")
684
+ const front = filterImport(ts, sf, node, frontendUses, false)
685
+ if (front !== undefined) frontendTexts.push(front)
686
+ afterImports = frontendTexts.length
687
+ backendAfterImports = backendTexts.length
688
+ continue
689
+ }
690
+ if (isBackendStatement(info)) {
691
+ if (
692
+ ts.isExportDeclaration(node) &&
693
+ exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name))
694
+ ) {
695
+ backendTexts.push(filterExportList(ts, sf, node, (name) => BACKEND_EXPORTS.has(name)) ?? "")
696
+ frontendTexts.push(
697
+ filterExportList(ts, sf, node, (name) => !BACKEND_EXPORTS.has(name)) ?? "",
698
+ )
699
+ continue
700
+ }
701
+ if (exportsOf(info).some((name) => !BACKEND_EXPORTS.has(name))) {
702
+ issues.push(
703
+ `one statement exports both "${exportsOf(info).join('", "')}"; split it by hand`,
704
+ )
705
+ }
706
+ backendTexts.push(info.text)
707
+ continue
708
+ }
709
+ if (backendSet.has(info)) backendTexts.push(stripExport(ts, sf, info))
710
+ if (frontendKeep.has(info)) frontendTexts.push(info.text)
711
+ }
712
+ // After the other imports: the nearest relative path sorts last.
713
+ const frontendImports = sharedImport(frontendUses)
714
+ if (reexported.length > 0)
715
+ frontendImports.push(
716
+ `\nexport { ${reexported.join(", ")} } from ${quote}${sharedSpecifier}${quote}${semi}`,
717
+ )
718
+ if (typeImports.size > 0)
719
+ frontendImports.push(
720
+ `\nimport type { ${[...typeImports].sort().join(", ")} } from ${quote}${backendSpecifier}${quote}${semi}`,
721
+ )
722
+ frontendTexts.splice(afterImports, 0, ...frontendImports)
723
+ backendTexts.splice(backendAfterImports, 0, ...sharedImport(backendUses))
724
+ // A JSX pragma counts only in the file's leading comments, and the backend half has no JSX.
725
+ const pragmas = (ts.getLeadingCommentRanges(source, 0) ?? [])
726
+ .map((range) => source.slice(range.pos, range.end))
727
+ .filter((comment) => /@jsx/.test(comment))
728
+ const lift = (text: string): string =>
729
+ pragmas.reduce(
730
+ (out, pragma) => out.replace(new RegExp(`${escapeRegExp(pragma)}[ \\t]*\\n?`), ""),
731
+ text,
732
+ )
733
+ const frontend = lift(joinStatements(frontendTexts))
734
+ let sharedText: string | undefined
735
+ if (shared.size > 0) {
736
+ const texts: string[] = []
737
+ const typeUses: Uses = { value: new Set(), type: sharedImports }
738
+ for (const info of statements) {
739
+ if (ts.isImportDeclaration(info.node)) {
740
+ const kept = filterImport(ts, sf, info.node, typeUses, true)
741
+ if (kept !== undefined && info.node.importClause !== undefined) texts.push(kept)
742
+ } else if (shared.has(info) || sharedTypes.has(info)) {
743
+ texts.push(withExport(ts, sf, info))
744
+ }
745
+ }
746
+ sharedText = lift(joinStatements(texts))
747
+ }
748
+ const result: SplitResult = {
749
+ frontend: pragmas.length > 0 ? `${pragmas.join("\n")}\n${frontend}` : frontend,
750
+ backend: lift(joinStatements(backendTexts)),
751
+ moved: [...new Set(moved)].sort(),
752
+ issues,
753
+ }
754
+ return sharedText === undefined ? result : { ...result, shared: sharedText }
755
+ }
756
+
757
+ /** A declaration the shared module holds is exported, so either half can import it. */
758
+ function withExport(ts: typeof TS, sf: TS.SourceFile, info: StatementInfo): string {
759
+ if (hasModifier(ts, info.node, ts.SyntaxKind.ExportKeyword)) return info.text
760
+ const at = info.node.getStart(sf) - info.node.getFullStart()
761
+ return `${info.text.slice(0, at)}export ${info.text.slice(at)}`
762
+ }
763
+
764
+ /** A helper the backend half copies keeps its declaration; an `export` on it would add a backend export. */
765
+ function stripExport(ts: typeof TS, sf: TS.SourceFile, info: StatementInfo): string {
766
+ if (info.exports.size === 0) return info.text
767
+ const node = info.node
768
+ const exportKeyword = (ts.canHaveModifiers(node) ? (ts.getModifiers(node) ?? []) : []).find(
769
+ (m) => m.kind === ts.SyntaxKind.ExportKeyword,
770
+ )
771
+ if (exportKeyword === undefined) return info.text
772
+ const start = exportKeyword.getStart(sf) - node.getFullStart()
773
+ const end = exportKeyword.getEnd() - node.getFullStart()
774
+ return info.text.slice(0, start) + info.text.slice(end).replace(/^\s+/, "")
775
+ }
776
+
777
+ /** `_middleware.ts`'s default export, as the `middleware` export of a `_layout.backend.ts`. */
778
+ export function middlewareSource(ts: typeof TS, source: string, fileName: string): string {
779
+ const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
780
+ let out = source
781
+ // Edit from the end so earlier offsets stay valid.
782
+ for (const node of [...sf.statements].reverse()) {
783
+ if (ts.isExportAssignment(node) && !node.isExportEquals) {
784
+ out = `${out.slice(0, node.getStart(sf))}export const middleware = ${node.expression.getText(sf)}${terminatorOf(sf, node)}${out.slice(node.getEnd())}`
785
+ } else if (
786
+ ts.isFunctionDeclaration(node) &&
787
+ hasModifier(ts, node, ts.SyntaxKind.DefaultKeyword)
788
+ ) {
789
+ const modifiers = (ts.getModifiers(node) ?? []).filter(
790
+ (m) => m.kind === ts.SyntaxKind.ExportKeyword || m.kind === ts.SyntaxKind.DefaultKeyword,
791
+ )
792
+ const first = modifiers[0]
793
+ const last = modifiers[modifiers.length - 1]
794
+ if (first === undefined || last === undefined) continue
795
+ if (node.name === undefined) {
796
+ const text = out
797
+ .slice(last.getEnd(), node.getEnd())
798
+ .replace(/^(\s*(?:async\s+)?function\s*\*?)\s*/, "$1 middleware")
799
+ out = `${out.slice(0, first.getStart(sf))}export${text}${out.slice(node.getEnd())}`
800
+ } else {
801
+ out = `${out.slice(0, first.getStart(sf))}${out.slice(last.getEnd()).replace(/^\s+/, "")}`
802
+ const semi = sf.statements.some((s) => terminatorOf(sf, s) !== "") ? ";" : ""
803
+ out = `${out.trimEnd()}\nexport { ${node.name.text} as middleware }${semi}\n`
804
+ }
805
+ }
806
+ }
807
+ return out
808
+ }
809
+
810
+ /** Merge two backend modules: imports first (identical ones once), then the rest of each in order. */
811
+ export function mergeModules(ts: typeof TS, first: string, second: string): string {
812
+ if (first.trim() === "") return second
813
+ const split = (text: string): { imports: string[]; body: string[] } => {
814
+ const sf = ts.createSourceFile("merge.ts", text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
815
+ const imports: string[] = []
816
+ const body: string[] = []
817
+ for (const node of sf.statements) {
818
+ ;(ts.isImportDeclaration(node) ? imports : body).push(
819
+ node.getFullText(sf).replace(/^\s*\n/, ""),
820
+ )
821
+ }
822
+ return { imports, body }
823
+ }
824
+ const a = split(first)
825
+ const b = split(second)
826
+ const imports = [...new Set([...a.imports, ...b.imports].map((text) => text.trim()))]
827
+ const body = [...a.body, ...b.body].map((text) => text.trim()).join("\n\n")
828
+ return `${imports.join("\n")}${imports.length > 0 ? "\n\n" : ""}${body}\n`
829
+ }
830
+
831
+ // ---------------------------------------------------------------------------------------------------
832
+ // SFC script blocks
833
+ // ---------------------------------------------------------------------------------------------------
834
+
835
+ /** The `<script>` blocks of a Svelte/Vue file: their content range and whether it is the module script. */
836
+ export function scriptBlocks(
837
+ source: string,
838
+ ): Array<{ start: number; end: number; module: boolean; setup: boolean }> {
839
+ const blocks: Array<{ start: number; end: number; module: boolean; setup: boolean }> = []
840
+ // A closing tag ends at any space, slash or `>` after its name, as the compilers read it.
841
+ const pattern = /<script\b([^>]*)>([\s\S]*?)<\/script(?=[\s/>])[^>]*>/gi
842
+ // A `<script>` written inside an HTML comment is prose, not a block; blank comments out, keeping offsets.
843
+ const visible = source.replace(/<!--[\s\S]*?-->/g, (comment) => comment.replace(/[^\n]/g, " "))
844
+ for (const match of visible.matchAll(pattern)) {
845
+ const attrs = match[1] ?? ""
846
+ const start = (match.index ?? 0) + match[0].indexOf(">") + 1
847
+ blocks.push({
848
+ start,
849
+ end: start + (match[2] ?? "").length,
850
+ module: /\bmodule\b|context=["']module["']/.test(attrs),
851
+ setup: /\bsetup\b/.test(attrs),
852
+ })
853
+ }
854
+ return blocks
855
+ }
856
+
857
+ /** A replacement of the source between `start` and `end`. */
858
+ export interface TextEdit {
859
+ start: number
860
+ end: number
861
+ text: string
862
+ }
863
+
864
+ /** `text` with every edit made, last offset first so the ones before it still point where they did. */
865
+ export function applyEdits(text: string, edits: TextEdit[]): string {
866
+ let out = text
867
+ for (const edit of edits.sort((a, b) => b.start - a.start))
868
+ out = out.slice(0, edit.start) + edit.text + out.slice(edit.end)
869
+ return out
870
+ }