File size: 5,706 Bytes
37a34fd a1ee6c1 37a34fd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | // Position-faithful edit sessions: byte-offset splices against ONE file's
// original text, applied right-to-left so earlier offsets stay valid, with
// forced verification before anything is written to disk.
//
// This module (together with node.mjs, which is the only thing that should
// be calling `splice`) is what makes "never regenerate text from a tree"
// actually enforceable: an EditSession never has access to a serialized tree
// form, only to the original text plus a list of {index, length,
// replacement} edits. There is no code path here that could reformat
// anything the caller didn't explicitly touch.
import { tokenize } from './lexer.mjs';
import { writeGameText } from './codec.mjs';
/**
* Strip comments using the lexer's own state machine (not a second,
* independently-written regex) and count brace characters in what's left.
* This is deliberate: a naive `{`/`}` scan over raw text is fooled by a
* comment that itself contains a brace (real case in this data:
* `# The Eden Agreement }`), and a second regex for "strip comments" risks
* silently diverging from the lexer's actual handling of `#` inside strings
* and `"` inside comments.
*
* @param {string} text
* @returns {{ open: number, close: number }}
*/
export function countBraces(text) {
const tokens = tokenize(text);
let open = 0;
let close = 0;
for (const t of tokens) {
if (t.kind === 'comment') continue;
if (t.kind === 'lbrace') open += 1;
else if (t.kind === 'rbrace') close += 1;
}
return { open, close };
}
export class EditSession {
/**
* @param {string} path
* @param {string} text - original decoded text (from codec.mjs's readGameText)
* @param {import('./lexer.mjs').Token[]} tokens - tokenize(text), handed in so
* callers who already tokenized don't pay for it twice
* @param {{ bom?: boolean, encoding?: string }} [meta]
*/
constructor(path, text, tokens, meta = {}) {
this.path = path;
this.originalText = text;
this.tokens = tokens;
this.meta = meta;
/** @type {{index:number, length:number, replacement:string}[]} */
this.splices = [];
this._originalBraces = countBraces(text);
}
get dirty() {
return this.splices.length > 0;
}
/**
* Record one splice. Does not apply or validate anything yet — multiple
* splices from unrelated edits accumulate here and are only reconciled
* (for overlap) at apply() time, so callers can register edits in any
* order.
*
* @param {number} index
* @param {number} length
* @param {string} replacement
*/
splice(index, length, replacement) {
if (index < 0 || length < 0) {
throw new RangeError(`EditSession.splice: invalid range index=${index} length=${length}`);
}
this.splices.push({ index, length, replacement });
}
/**
* Apply all recorded splices right-to-left against the original text.
* Pure function of the recorded splices; does not write or verify
* anything. Throws if any two splices target overlapping ranges — that is
* always a caller bug (each Node method targets a distinct token/entry
* span), never a legitimate case.
*
* @returns {string}
*/
apply() {
if (this.splices.length === 0) return this.originalText;
const sorted = [...this.splices].sort((a, b) => b.index - a.index);
for (let i = 0; i < sorted.length - 1; i += 1) {
const later = sorted[i];
const earlier = sorted[i + 1];
if (earlier.index + earlier.length > later.index) {
throw new Error(
`EditSession.apply: overlapping splices in ${this.path} `
+ `(one at [${earlier.index}, ${earlier.index + earlier.length}), `
+ `another at [${later.index}, ${later.index + later.length}))`,
);
}
}
let result = this.originalText;
for (const { index, length, replacement } of sorted) {
result = result.slice(0, index) + replacement + result.slice(index + length);
}
return result;
}
/**
* Apply + verify + write. A session with no splices is a true no-op: it
* must never touch the file's bytes or mtime, which is why this checks
* `dirty` itself rather than relying on every caller to check first.
*
* Verification order matches the spec exactly:
* 1. apply splices
* 2. tokenize(out) round-trips to out
* 3. comment-aware brace balance unchanged from before the edit
* 4. writeGameText (which itself re-reads and verifies)
*/
async save() {
if (!this.dirty) return;
const out = this.apply();
const tokens = tokenize(out);
const rebuilt = tokens.map((t) => t.raw).join('');
if (rebuilt !== out) {
throw new Error(
`EditSession.save: ${this.path} failed post-edit tokenize round-trip — `
+ 'the applied splices produced text the lexer cannot reproduce exactly',
);
}
const after = countBraces(out);
const before = this._originalBraces;
if (after.open !== before.open || after.close !== before.close) {
// Opt-out for callers that delete WHOLE AST items (pair + its block
// value): that removes matched brace pairs by construction, so the
// counts legitimately change while the text stays balanced. The
// caller must set this flag explicitly; balance is still verified.
if (!(this.allowBalancedBraceChange && after.open === after.close)) {
throw new Error(
`EditSession.save: ${this.path} brace balance changed — `
+ `before={open:${before.open},close:${before.close}} `
+ `after={open:${after.open},close:${after.close}}`,
);
}
}
await writeGameText(this.path, out, this.meta);
}
}
|