| 35 | // arktype's changed, or undefined where they changed what arktype's wrote |
| 36 | // or it can't be read |
| 37 | export const unwrite = ({ |
| 38 | id, |
| 39 | reached, |
| 40 | written, |
| 41 | built |
| 42 | }: BuiltModule): string | undefined => { |
| 43 | // one arktype's left as it was reads as it was built, unless a comment |
| 44 | // there marks a definition, which a transform printing the module drops |
| 45 | if (!written && !reached.includes(marker)) return built |
| 46 | const read = tokensOf(id, reached) |
| 47 | const ours = tokensOf(id, built) |
| 48 | // one arktype's left as it was is the module as built |
| 49 | if (!read || !ours) return written ? undefined : built |
| 50 | const base = written ? tokensOf(id, written.code) : read |
| 51 | if (!base) return |
| 52 | // each token arktype's wrote, as the index of the one it read there, or -1 |
| 53 | // where it read none |
| 54 | const readAt = |
| 55 | written ? |
| 56 | readAtOf(base, read, written, reached) |
| 57 | : Int32Array.from(read.tokens.keys()) |
| 58 | const edits: Edit[] = [] |
| 59 | const hunks = diff(base, ours) |
| 60 | for (const [h, [start, end, builtStart, builtEnd]] of hunks.entries()) { |
| 61 | if (builtStart === builtEnd) { |
| 62 | // removed: what reached arktype's of it goes too, as a type does |
| 63 | // that TypeScript's transform erases |
| 64 | const kept: number[] = [] |
| 65 | for (let i = start; i < end; i++) if (readAt[i] >= 0) kept.push(readAt[i]) |
| 66 | if (!kept.length) continue |
| 67 | edits.push({ |
| 68 | start: read.tokens[kept[0]].start, |
| 69 | end: read.tokens[kept[kept.length - 1]].end, |
| 70 | text: "" |
| 71 | }) |
| 72 | continue |
| 73 | } |
| 74 | if (start === end) { |
| 75 | // added, with what separates it from the tokens around it |
| 76 | let [at, from, to] = [start, builtStart, builtEnd] |
| 77 | const isWritten = () => |
| 78 | at > 0 && readAt[at - 1] === -1 && readAt[at] === -1 |
| 79 | // Among the tokens arktype's wrote, it's as much added past the next |
| 80 | // of them where that's the first it adds, as the `)` closing a call |
| 81 | // around one arktype's wrote is either of the two then ending it. So |
| 82 | // it's read as added past the last such token, or else ahead of the |
| 83 | // first, up to the next thing a transform changed |
| 84 | const next = h + 1 < hunks.length ? hunks[h + 1][0] : base.tokens.length |
| 85 | while ( |
| 86 | isWritten() && |
| 87 | at < next && |
| 88 | base.texts[at] === ours.texts[from] && |
| 89 | base.texts[at] === ours.texts[to] |
| 90 | ) { |
| 91 | at++ |
| 92 | from++ |
| 93 | to++ |
| 94 | } |