Open History to see the last commit
1import type { MigrationAnnotation } from "./Annotations.ts"
2import type { ApiChange, ApiDiff, ChangeClassification } from "./Model.ts"
3
4const breakingClassifications = new Set<ChangeClassification>([
5 "bucket-changed",
6 "declaration-kind-changed",
7 "overload-removed",
8 "overload-reordered",
9 "parameter-removed",
10 "parameter-reordered",
11 "parameter-changed",
12 "return-type-changed",
13 "generic-parameter-changed",
14 "member-removed",
15 "member-changed",
16 "heritage-changed",
17 "union-member-changed",
18 "intersection-member-changed",
19 "structural-change"
20])
21
22const stableApiId = (id: string): string => id.replace(/#(?:type|value)$/, "")
23
24const displayApiId = (id: string): string => {
25 const separator = id.indexOf("#")
26 if (separator === -1) {
27 return id
28 }
29 const module = id.slice(0, separator).split("/").at(-1)!
30 return `${module}.${id.slice(separator + 1)}`
31}
32
33const backtickDelimiter = (value: string, minimum: number): string => {
34 let length = minimum
35 for (const match of value.matchAll(/`+/g)) {
36 length = Math.max(length, match[0].length + 1)
37 }
38 return "`".repeat(length)
39}
40
41const codeSpan = (value: string): string => {
42 const delimiter = backtickDelimiter(value, 1)
43 const content = value.startsWith("`") || value.endsWith("`") ? ` ${value} ` : value
44 return `${delimiter}${content}${delimiter}`
45}
46
47const escapeMarkdownText = (value: string): string => value.replace(/\\/g, "\\\\").replace(/[~<>*_]/g, "\\$&")
48
49const escapeAnnotationText = (value: string): string => {
50 const output: Array<string> = []
51 let index = 0
52 while (index < value.length) {
53 const start = value.indexOf("`", index)
54 if (start === -1) {
55 output.push(escapeMarkdownText(value.slice(index)))
56 break
57 }
58 output.push(escapeMarkdownText(value.slice(index, start)))
59 let end = start + 1
60 while (value[end] === "`") {
61 end++
62 }
63 const delimiter = value.slice(start, end)
64 const close = value.indexOf(delimiter, end)
65 if (close === -1) {
66 output.push("\\`".repeat(delimiter.length))
67 index = end
68 } else {
69 output.push(value.slice(start, close + delimiter.length))
70 index = close + delimiter.length
71 }
72 }
73 return output.join("")
74}
75
76const compareStrings = (left: string, right: string): number => left < right ? -1 : left > right ? 1 : 0
77
78const isBreakingChange = (change: ApiChange): boolean => {
79 if (change.classification !== "parameter-added") {
80 return breakingClassifications.has(change.classification)
81 }
82 const delta = change.delta as {
83 readonly before?: ReadonlyArray<unknown>
84 readonly after?: ReadonlyArray<{ readonly optional?: boolean; readonly rest?: boolean }>
85 } | undefined
86 const beforeLength = delta?.before?.length ?? 0
87 return delta?.after?.slice(beforeLength).some((parameter) => !parameter.optional && !parameter.rest) ?? true
88}
89
90interface MigrationEntry {
91 readonly id: string
92 readonly module: string
93 readonly rename: ApiChange | undefined
94}
95
96const importMapReplacements = (importMapSections: string): ReadonlyMap<string, ReadonlyArray<string>> => {
97 const replacements = new Map<string, Array<string>>()
98 for (const line of importMapSections.split(/\r?\n/)) {
99 const match = /^(\S+) -> (\S+)(?: \(barrel: [^)]+\))?$/.exec(line)
100 if (match === null) {
101 continue
102 }
103 const targets = replacements.get(match[1]!)
104 if (targets === undefined) {
105 replacements.set(match[1]!, [match[2]!])
106 } else if (!targets.includes(match[2]!)) {
107 targets.push(match[2]!)
108 }
109 }
110 return replacements
111}
112
113const removedModules = (diff: ApiDiff): ReadonlyArray<string> =>
114 [
115 ...new Set(diff.changes.flatMap((change) => {
116 if (change.classification !== "module-removed") {
117 return []
118 }
119 const from = (change.delta as { readonly from?: unknown } | undefined)?.from
120 return typeof from === "string" ? [from] : []
121 }))
122 ].sort(compareStrings)
123
124const sameStrings = (left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean =>
125 left.length === right.length && left.every((value, index) => value === right[index])
126
127const addedApiSignatures = (diff: ApiDiff): ReadonlyMap<string, ReadonlyArray<string>> => {
128 const signatures = new Map<string, Array<string>>()
129 for (const change of diff.changes) {
130 if (change.classification !== "api-added" || change.headApiId === undefined || change.after === undefined) {
131 continue
132 }
133 const id = stableApiId(change.headApiId)
134 const group = signatures.get(id)
135 if (group === undefined) {
136 signatures.set(id, [change.after])
137 } else {
138 group.push(change.after)
139 }
140 }
141 for (const group of signatures.values()) {
142 group.sort(compareStrings)
143 }
144 return signatures
145}
146
147const isUnchangedModuleMove = (
148 id: string,
149 changes: ReadonlyArray<ApiChange>,
150 removed: ReadonlySet<string>,
151 replacements: ReadonlyMap<string, ReadonlyArray<string>>,
152 addedSignatures: ReadonlyMap<string, ReadonlyArray<string>>
153): boolean => {
154 const separator = id.indexOf("#")
155 const module = id.slice(0, separator)
156 const targets = replacements.get(module)
157 if (separator === -1 || !removed.has(module) || targets === undefined) {
158 return false
159 }
160 const before = changes
161 .filter((change) => change.classification === "api-removed" && change.before !== undefined)
162 .map((change) => change.before!)
163 .sort(compareStrings)
164 if (before.length === 0) {
165 return false
166 }
167 const path = id.slice(separator + 1)
168 return targets.some((target) => {
169 const after = addedSignatures.get(`${target}#${path}`)
170 return after !== undefined && sameStrings(before, after)
171 })
172}
173
174const isRemovalCoveredByModule = (
175 id: string,
176 removed: ReadonlySet<string>,
177 annotations: ReadonlyMap<string, MigrationAnnotation>
178): boolean => {
179 const separator = id.indexOf("#")
180 const module = id.slice(0, separator)
181 if (separator === -1 || !removed.has(module) || annotations.get(module)?.replacement !== "none") {
182 return false
183 }
184 const annotation = annotations.get(id)
185 return annotation === undefined || annotation.replacement === "none"
186}
187
188const migrationEntries = (
189 diff: ApiDiff,
190 annotations: ReadonlyMap<string, MigrationAnnotation>,
191 importMapSections: string
192): ReadonlyArray<MigrationEntry> => {
193 const grouped = new Map<string, Array<ApiChange>>()
194 for (const change of diff.changes) {
195 if (change.baseApiId === undefined) {
196 continue
197 }
198 const id = stableApiId(change.baseApiId)
199 const changes = grouped.get(id)
200 if (changes === undefined) {
201 grouped.set(id, [change])
202 } else {
203 changes.push(change)
204 }
205 }
206
207 const entries: Array<MigrationEntry> = []
208 const removedModuleSet = new Set(removedModules(diff))
209 const replacements = importMapReplacements(importMapSections)
210 const addedSignatures = addedApiSignatures(diff)
211 for (const [id, changes] of grouped) {
212 const rename = changes.find((change) => change.classification === "api-renamed")
213 const breaking = changes.some(isBreakingChange)
214 const removed = changes.some((change) => change.classification === "api-removed")
215 const importMove = changes.some((change) => change.classification === "api-moved")
216 if (
217 isUnchangedModuleMove(id, changes, removedModuleSet, replacements, addedSignatures) ||
218 (removed && isRemovalCoveredByModule(id, removedModuleSet, annotations)) ||
219 (!breaking && rename === undefined && !removed) ||
220 (importMove && rename === undefined && !breaking && !annotations.has(id))
221 ) {
222 continue
223 }
224 entries.push({
225 id,
226 module: id.split("#")[0]!,
227 rename
228 })
229 }
230 return entries.sort((left, right) => compareStrings(left.module, right.module) || compareStrings(left.id, right.id))
231}
232
233const renderDetailedEntry = (
234 entry: MigrationEntry,
235 annotation: MigrationAnnotation,
236 example: string
237): ReadonlyArray<string> => {
238 const fence = backtickDelimiter(example, 3)
239 return [
240 `#### ${codeSpan(displayApiId(entry.id))}`,
241 "",
242 `**Replacement:** ${codeSpan(annotation.replacement)}`,
243 "",
244 escapeAnnotationText(annotation.note),
245 "",
246 "**Example**",
247 "",
248 `${fence}ts`,
249 example,
250 fence,
251 ""
252 ]
253}
254
255const renderCompactEntry = (
256 entry: MigrationEntry,
257 annotation: MigrationAnnotation | undefined
258): string => {
259 if (annotation !== undefined) {
260 return `- ${codeSpan(displayApiId(entry.id))} -> ${codeSpan(annotation.replacement)}: ${
261 escapeAnnotationText(annotation.note)
262 }`
263 }
264 const target = entry.rename?.headApiId
265 return target === undefined
266 ? `- ${codeSpan(displayApiId(entry.id))}: TODO: needs guidance`
267 : `- ${codeSpan(displayApiId(entry.id))} -> ${codeSpan(displayApiId(stableApiId(target)))}: TODO: needs guidance`
268}
269
270export const extractImportMapSections = (document: string): string => {
271 const start = document.indexOf("## Import Map")
272 if (start === -1) {
273 return "## Import Map\n\nNo import map is available.\n"
274 }
275 const apiRenames = document.indexOf("\n## API Renames", start)
276 const removedModules = document.indexOf("\n## Removed Modules", start)
277 const apiReference = document.indexOf("\n## API Reference", start)
278 const ends = [apiRenames, removedModules, apiReference].filter((index) => index !== -1)
279 const end = ends.length === 0 ? document.length : Math.min(...ends)
280 return `${document.slice(start, end).trim()}\n`
281}
282
283export const renderMigrationDocument = (
284 diff: ApiDiff,
285 annotations: ReadonlyMap<string, MigrationAnnotation>,
286 importMapSections: string
287): string => {
288 const entries = migrationEntries(diff, annotations, importMapSections)
289 const replacements = importMapReplacements(importMapSections)
290 const modulesRemoved = removedModules(diff)
291 const modules = new Map<string, Array<MigrationEntry>>()
292 for (const entry of entries) {
293 const group = modules.get(entry.module)
294 if (group === undefined) {
295 modules.set(entry.module, [entry])
296 } else {
297 group.push(entry)
298 }
299 }
300 const lines = [
301 "<!-- dprint-ignore-file -->",
302 "",
303 "# v3 to v4 Migration Reference",
304 "",
305 `Base: \`${diff.base.ref}\` (\`${diff.base.sha}\`)`,
306 "",
307 `Head: \`${diff.head.ref}\` (\`${diff.head.sha}\`)`,
308 "",
309 "This file is generated from the API diff and `migration/annotations/*.yaml`.",
310 "",
311 importMapSections.trim(),
312 "",
313 "## Removed Modules",
314 ""
315 ]
316 for (const module of modulesRemoved) {
317 const annotation = annotations.get(module)
318 const targets = replacements.get(module)
319 if (annotation !== undefined) {
320 lines.push(
321 `- ${codeSpan(module)} -> ${codeSpan(annotation.replacement)}: ${escapeAnnotationText(annotation.note)}`
322 )
323 } else if (targets !== undefined) {
324 lines.push(`- ${codeSpan(module)} -> ${targets.map(codeSpan).join(", ")}`)
325 } else if ([...annotations.keys()].some((id) => id.startsWith(`${module}#`))) {
326 lines.push(`- ${codeSpan(module)}: No single module replacement; follow the curated per-API guidance below.`)
327 } else {
328 lines.push(`- ${codeSpan(module)}: TODO: needs module guidance`)
329 }
330 }
331 if (modulesRemoved.length === 0) {
332 lines.push("No modules were removed.")
333 }
334 lines.push(
335 "",
336 "## API Reference",
337 ""
338 )
339 for (const [module, moduleEntries] of modules) {
340 lines.push(`### ${codeSpan(module)}`, "")
341 for (const entry of moduleEntries) {
342 const annotation = annotations.get(entry.id)
343 if (annotation?.example !== undefined) {
344 lines.push(...renderDetailedEntry(entry, annotation, annotation.example))
345 } else {
346 lines.push(renderCompactEntry(entry, annotation), "")
347 }
348 }
349 }
350 return `${lines.join("\n").trim()}\n`
351}
352
353export const markdownSafetyIssues = (document: string): ReadonlyArray<string> => {
354 const issues: Array<string> = []
355 let fence: string | undefined
356 const lines = document.split("\n")
357 for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
358 const line = lines[lineIndex]!
359 const fenceMatch = /^\s*(`{3,})(?:[^`]*)$/.exec(line)
360 if (fence !== undefined) {
361 if (line.trim() === fence) {
362 fence = undefined
363 }
364 continue
365 }
366 if (fenceMatch !== null) {
367 fence = fenceMatch[1]!
368 continue
369 }
370 if (
371 line === "<!-- dprint-ignore-file -->" ||
372 line.startsWith("**Replacement:** ") ||
373 line === "**Example**"
374 ) {
375 continue
376 }
377 let index = 0
378 while (index < line.length) {
379 const character = line[index]!
380 if (character === "\\") {
381 index += 2
382 continue
383 }
384 if (character === "`") {
385 let end = index + 1
386 while (line[end] === "`") {
387 end++
388 }
389 const delimiter = line.slice(index, end)
390 const close = line.indexOf(delimiter, end)
391 if (close === -1) {
392 issues.push(`line ${lineIndex + 1}: unclosed inline code span`)
393 break
394 }
395 index = close + delimiter.length
396 continue
397 }
398 if (character === "~" || character === "<" || character === "*" || character === "_") {
399 issues.push(`line ${lineIndex + 1}: unescaped ${JSON.stringify(character)}`)
400 }
401 index++
402 }
403 }
404 if (fence !== undefined) {
405 issues.push(`unclosed ${fence} code fence`)
406 }
407 return issues
408}
409
410export const unannotatedApiIds = (
411 diff: ApiDiff,
412 annotations: ReadonlyMap<string, MigrationAnnotation>,
413 importMapSections = ""
414): ReadonlyMap<string, ReadonlyArray<string>> => {
415 const modules = new Map<string, Array<string>>()
416 for (const entry of migrationEntries(diff, annotations, importMapSections)) {
417 if (annotations.has(entry.id)) {
418 continue
419 }
420 const ids = modules.get(entry.module)
421 if (ids === undefined) {
422 modules.set(entry.module, [entry.id])
423 } else {
424 ids.push(entry.id)
425 }
426 }
427 return modules
428}
429
430export const unannotatedModuleIds = (
431 diff: ApiDiff,
432 annotations: ReadonlyMap<string, MigrationAnnotation>,
433 importMapSections: string
434): ReadonlyArray<string> => {
435 const replacements = importMapReplacements(importMapSections)
436 return removedModules(diff).filter((module) =>
437 !annotations.has(module) &&
438 !replacements.has(module) &&
439 ![...annotations.keys()].some((id) => id.startsWith(`${module}#`))
440 )
441}
442
443export const renderMissingAnnotations = (
444 diff: ApiDiff,
445 annotations: ReadonlyMap<string, MigrationAnnotation>,
446 importMapSections = ""
447): string => {
448 const missingApis = unannotatedApiIds(diff, annotations, importMapSections)
449 const missingModules = unannotatedModuleIds(diff, annotations, importMapSections)
450 if (missingApis.size === 0 && missingModules.length === 0) {
451 return "All migration APIs and removed modules have guidance.\n"
452 }
453 return `${
454 [
455 ...(missingModules.length === 0 ? [] : ["Removed modules:", ...missingModules.map((module) => ` - ${module}`)]),
456 ...[...missingApis].flatMap(([module, ids]) => [
457 `${module}:`,
458 ...ids.map((id) => ` - ${id}`)
459 ])
460 ].join("\n")
461 }\n`
462}