@open-document/core 0.10.0 → 0.11.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.
@@ -1935,32 +1935,31 @@ function slotText(slot, edit) {
1935
1935
  if (!slot.jsx || !edit.segments) return slot.escape(edit.text);
1936
1936
  return renderSegments(mergeSegments(edit.segments), slot.escape);
1937
1937
  }
1938
- /**
1939
- * Applies several run replacements as one write.
1940
- *
1941
- * Every edit is located against the source as the caller last saw it, before
1942
- * any of them lands: an edit's `line:column` is only true of that source, and
1943
- * resolving each against the output of the previous one would find elements
1944
- * shifted by whatever was typed above them. The splices then go in back to
1945
- * front so none moves another.
1946
- *
1947
- * A failed edit is reported and skipped; the rest still land. Two edits that
1948
- * reach the same span — one prop rendered by two elements — must agree, or the
1949
- * later one is refused rather than silently winning.
1950
- */
1938
+ const SYNTAX_ERROR = {
1939
+ ok: false,
1940
+ status: 422,
1941
+ error: "the document has a syntax error — fix it in source before editing here"
1942
+ };
1943
+ /** Applies non-overlapping splices, all located against the same source, back to front. */
1944
+ function applySplices(source, splices) {
1945
+ let next = source;
1946
+ for (const splice of [...splices].sort((a, b) => b.start - a.start)) next = next.slice(0, splice.start) + splice.text + next.slice(splice.end);
1947
+ return next;
1948
+ }
1951
1949
  function replaceTextsAt(source, edits) {
1952
1950
  const ast = parseStrict(source);
1953
- if (!ast) {
1954
- const error = {
1955
- ok: false,
1956
- status: 422,
1957
- error: "the document has a syntax error — fix it in source before editing here"
1958
- };
1959
- return {
1960
- source,
1961
- results: edits.map(() => error)
1962
- };
1963
- }
1951
+ if (!ast) return {
1952
+ source,
1953
+ results: edits.map(() => SYNTAX_ERROR)
1954
+ };
1955
+ const { splices, results } = planTextEdits(ast, source, edits);
1956
+ return {
1957
+ source: applySplices(source, splices),
1958
+ results
1959
+ };
1960
+ }
1961
+ /** Where each text edit lands in `source`, without writing any of them. */
1962
+ function planTextEdits(ast, source, edits) {
1964
1963
  const results = [];
1965
1964
  const planned = [];
1966
1965
  for (const edit of edits) {
@@ -2010,14 +2009,506 @@ function replaceTextsAt(source, edits) {
2010
2009
  });
2011
2010
  results.push({ ok: true });
2012
2011
  }
2013
- let next = source;
2014
- for (const { slot, text } of [...planned].sort((a, b) => b.slot.start - a.slot.start)) next = next.slice(0, slot.start) + text + next.slice(slot.end);
2015
2012
  return {
2016
- source: next,
2013
+ splices: planned.map(({ slot, text }) => ({
2014
+ start: slot.start,
2015
+ end: slot.end,
2016
+ text
2017
+ })),
2017
2018
  results
2018
2019
  };
2019
2020
  }
2020
2021
  //#endregion
2022
+ //#region src/app/lib/inspector/format.ts
2023
+ /**
2024
+ * The element panel's Format section, shared by the viewer and the dev server:
2025
+ * which style keys it may write, which design tokens each one offers, and what
2026
+ * a value has to look like before it is spliced into a document's source.
2027
+ */
2028
+ const STYLE_PROPS = [
2029
+ "fontFamily",
2030
+ "fontSize",
2031
+ "fontWeight",
2032
+ "fontStyle",
2033
+ "textAlign",
2034
+ "lineHeight",
2035
+ "letterSpacing",
2036
+ "color",
2037
+ "background"
2038
+ ];
2039
+ function isStyleProp(value) {
2040
+ return typeof value === "string" && STYLE_PROPS.includes(value);
2041
+ }
2042
+ /** The `--od-*` variables a document's design const defines, by what they can stand for. */
2043
+ const TOKENS = {
2044
+ font: [
2045
+ {
2046
+ token: "font-heading",
2047
+ label: "Heading"
2048
+ },
2049
+ {
2050
+ token: "font-body",
2051
+ label: "Body"
2052
+ },
2053
+ {
2054
+ token: "font-mono",
2055
+ label: "Mono"
2056
+ }
2057
+ ],
2058
+ size: [
2059
+ {
2060
+ token: "size-title",
2061
+ label: "Title"
2062
+ },
2063
+ {
2064
+ token: "size-h1",
2065
+ label: "H1"
2066
+ },
2067
+ {
2068
+ token: "size-h2",
2069
+ label: "H2"
2070
+ },
2071
+ {
2072
+ token: "size-h3",
2073
+ label: "H3"
2074
+ },
2075
+ {
2076
+ token: "size-body",
2077
+ label: "Body"
2078
+ },
2079
+ {
2080
+ token: "size-caption",
2081
+ label: "Caption"
2082
+ }
2083
+ ],
2084
+ color: [
2085
+ {
2086
+ token: "text",
2087
+ label: "Text"
2088
+ },
2089
+ {
2090
+ token: "muted",
2091
+ label: "Muted"
2092
+ },
2093
+ {
2094
+ token: "accent",
2095
+ label: "Accent"
2096
+ },
2097
+ {
2098
+ token: "rule",
2099
+ label: "Rule"
2100
+ },
2101
+ {
2102
+ token: "bg",
2103
+ label: "Background"
2104
+ }
2105
+ ],
2106
+ leading: [{
2107
+ token: "leading",
2108
+ label: "Leading"
2109
+ }]
2110
+ };
2111
+ const PROP_TOKENS = {
2112
+ fontFamily: "font",
2113
+ fontSize: "size",
2114
+ color: "color",
2115
+ background: "color",
2116
+ lineHeight: "leading"
2117
+ };
2118
+ const TOKEN_VALUE = /^var\(\s*--od-([a-z0-9-]+)\s*\)$/;
2119
+ /** `var(--od-accent)` → `accent`; anything else is not a token reference. */
2120
+ function tokenOf(value) {
2121
+ return TOKEN_VALUE.exec(value.trim())?.[1] ?? null;
2122
+ }
2123
+ function isToken(prop, value) {
2124
+ const group = PROP_TOKENS[prop];
2125
+ const token = tokenOf(value);
2126
+ return group !== void 0 && token !== null && TOKENS[group].some((t) => t.token === token);
2127
+ }
2128
+ const LENGTH = /^-?\d+(\.\d+)?(px|em|rem)$/;
2129
+ const HEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
2130
+ const PLAIN = /^[^;{}<>\\\n\r]{1,200}$/;
2131
+ /** Whether the panel may write this value for this key — the server's check, run again in the viewer. */
2132
+ function isValidStyleValue(prop, value) {
2133
+ if (value === null) return true;
2134
+ if (typeof value === "number") {
2135
+ if (!Number.isFinite(value)) return false;
2136
+ if (prop === "fontWeight") return value >= 100 && value <= 900 && value % 100 === 0;
2137
+ if (prop === "lineHeight") return value > 0 && value <= 10;
2138
+ return false;
2139
+ }
2140
+ if (!PLAIN.test(value)) return false;
2141
+ if (isToken(prop, value)) return true;
2142
+ switch (prop) {
2143
+ case "fontFamily": return tokenOf(value) === null;
2144
+ case "fontSize": return LENGTH.test(value) && !value.startsWith("-");
2145
+ case "letterSpacing": return LENGTH.test(value) || value === "normal";
2146
+ case "fontWeight": return value === "normal" || value === "bold";
2147
+ case "fontStyle": return value === "normal" || value === "italic";
2148
+ case "textAlign": return [
2149
+ "left",
2150
+ "center",
2151
+ "right",
2152
+ "justify",
2153
+ "start",
2154
+ "end"
2155
+ ].includes(value);
2156
+ case "lineHeight": return value === "normal";
2157
+ case "color":
2158
+ case "background": return HEX.test(value) || value === "transparent";
2159
+ }
2160
+ }
2161
+ //#endregion
2162
+ //#region src/editing/style-ops.ts
2163
+ function unwrap(node) {
2164
+ let current = node;
2165
+ while (current && (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression" || current.type === "ParenthesizedExpression")) current = current.expression;
2166
+ return current;
2167
+ }
2168
+ function keyOf(property) {
2169
+ if (property.type !== "ObjectProperty" || property.computed) return null;
2170
+ const key = property.key;
2171
+ if (key.type === "Identifier") return key.name;
2172
+ if (key.type === "StringLiteral") return key.value;
2173
+ return null;
2174
+ }
2175
+ function sourceOf$1(value, source) {
2176
+ const node = unwrap(value) ?? value;
2177
+ if (node.type === "StringLiteral") {
2178
+ const text = node.value;
2179
+ const token = tokenOf(text);
2180
+ return token ? {
2181
+ kind: "token",
2182
+ token
2183
+ } : {
2184
+ kind: "literal",
2185
+ value: text
2186
+ };
2187
+ }
2188
+ if (node.type === "NumericLiteral") return {
2189
+ kind: "literal",
2190
+ value: node.value
2191
+ };
2192
+ if (node.type === "TemplateLiteral" && node.expressions.length === 0) {
2193
+ const text = (node.quasis[0]?.value)?.cooked ?? "";
2194
+ const token = tokenOf(text);
2195
+ return token ? {
2196
+ kind: "token",
2197
+ token
2198
+ } : {
2199
+ kind: "literal",
2200
+ value: text
2201
+ };
2202
+ }
2203
+ return {
2204
+ kind: "code",
2205
+ code: source.slice(value.start, value.end)
2206
+ };
2207
+ }
2208
+ /** A top-level `const name = { … }` — the shared style objects documents are written with. */
2209
+ function sharedObject(ast, name) {
2210
+ const body = ast.program?.body ?? [];
2211
+ for (const statement of body) {
2212
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
2213
+ if (declaration?.type !== "VariableDeclaration") continue;
2214
+ for (const declarator of declaration.declarations) {
2215
+ const id = declarator.id;
2216
+ if (id.type !== "Identifier" || id.name !== name) continue;
2217
+ const init = unwrap(declarator.init);
2218
+ return init?.type === "ObjectExpression" ? init : null;
2219
+ }
2220
+ }
2221
+ return null;
2222
+ }
2223
+ /** Folds an object's keys into `props`, later keys over earlier ones, as the spread would. */
2224
+ function readObject(ast, object, source, from, props, depth) {
2225
+ for (const property of object.properties) {
2226
+ if (property.type === "SpreadElement") {
2227
+ const argument = unwrap(property.argument);
2228
+ if (argument?.type !== "Identifier" || depth > 3) continue;
2229
+ const shared = sharedObject(ast, argument.name);
2230
+ if (shared) readObject(ast, shared, source, argument.name, props, depth + 1);
2231
+ continue;
2232
+ }
2233
+ const key = keyOf(property);
2234
+ const prop = key === "backgroundColor" ? "background" : key;
2235
+ if (!isStyleProp(prop)) continue;
2236
+ const origin = sourceOf$1(property.value, source);
2237
+ props[prop] = from ? {
2238
+ ...origin,
2239
+ from
2240
+ } : origin;
2241
+ }
2242
+ }
2243
+ function locate(ast, loc, tag) {
2244
+ const element = findJsxAt(ast, loc.line, loc.column);
2245
+ if (!element) return {
2246
+ ok: false,
2247
+ status: 404,
2248
+ error: "element not found"
2249
+ };
2250
+ const opening = element.openingElement;
2251
+ const name = opening.name;
2252
+ if (name.type !== "JSXIdentifier" || !/^[a-z]/.test(name.name)) return {
2253
+ ok: false,
2254
+ status: 422,
2255
+ error: "This is a component — its styles are set inside it, not here."
2256
+ };
2257
+ if (name.name !== tag) return {
2258
+ ok: false,
2259
+ status: 409,
2260
+ error: "source does not match this element"
2261
+ };
2262
+ const attrs = opening.attributes.filter((attr) => attr.type === "JSXAttribute" && attr.name.name === "style");
2263
+ const attr = attrs[attrs.length - 1] ?? null;
2264
+ if (!attr) return {
2265
+ ok: true,
2266
+ opening,
2267
+ attr: null,
2268
+ expression: null
2269
+ };
2270
+ const value = attr.value;
2271
+ if (value?.type !== "JSXExpressionContainer") return {
2272
+ ok: false,
2273
+ status: 422,
2274
+ error: "This element’s style is not written as an object."
2275
+ };
2276
+ return {
2277
+ ok: true,
2278
+ opening,
2279
+ attr,
2280
+ expression: value.expression
2281
+ };
2282
+ }
2283
+ function readProps(ast, source, expression) {
2284
+ const props = {};
2285
+ const node = unwrap(expression ?? void 0);
2286
+ if (node?.type === "ObjectExpression") readObject(ast, node, source, void 0, props, 0);
2287
+ else if (node?.type === "Identifier") {
2288
+ const shared = sharedObject(ast, node.name);
2289
+ if (shared) readObject(ast, shared, source, node.name, props, 1);
2290
+ }
2291
+ return props;
2292
+ }
2293
+ /** What the element at `loc` sets, key by key, for the panel to show before anything is written. */
2294
+ function readStyleAt(source, loc, tag) {
2295
+ const ast = parseSource(source);
2296
+ if (!ast) return {
2297
+ editable: false,
2298
+ reason: "could not read source"
2299
+ };
2300
+ const found = locate(ast, loc, tag);
2301
+ if (!found.ok) return {
2302
+ editable: false,
2303
+ reason: found.error
2304
+ };
2305
+ return {
2306
+ editable: true,
2307
+ props: readProps(ast, source, found.expression)
2308
+ };
2309
+ }
2310
+ function literal(value) {
2311
+ if (typeof value === "number") return String(value);
2312
+ return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
2313
+ }
2314
+ function lineIndent(source, offset) {
2315
+ const lineStart = source.lastIndexOf("\n", offset - 1) + 1;
2316
+ return /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? "";
2317
+ }
2318
+ function lineOf(source, offset) {
2319
+ let line = 0;
2320
+ for (let i = source.indexOf("\n"); i !== -1 && i < offset; i = source.indexOf("\n", i + 1)) line++;
2321
+ return line;
2322
+ }
2323
+ /** Writes the keys into an object literal, touching only what changes. */
2324
+ function planObject(source, object, sets, removes, attr) {
2325
+ const properties = object.properties;
2326
+ const lastSpread = properties.reduce((at, property, index) => property.type === "SpreadElement" ? index : at, -1);
2327
+ const ownIndex = (prop) => {
2328
+ for (let i = properties.length - 1; i > lastSpread; i--) {
2329
+ const key = keyOf(properties[i]);
2330
+ if (key === prop || prop === "background" && key === "backgroundColor") return i;
2331
+ }
2332
+ return -1;
2333
+ };
2334
+ const replaced = /* @__PURE__ */ new Map();
2335
+ const appended = [];
2336
+ for (const [prop, value] of sets) {
2337
+ const index = ownIndex(prop);
2338
+ if (index === -1) appended.push(`${prop}: ${literal(value)}`);
2339
+ else replaced.set(index, literal(value));
2340
+ }
2341
+ const removed = new Set(removes.map(ownIndex).filter((index) => index !== -1));
2342
+ if (removed.size === 0) {
2343
+ const splices = [];
2344
+ for (const [index, text] of replaced) {
2345
+ const value = properties[index].value;
2346
+ const shorthand = properties[index].shorthand === true;
2347
+ splices.push(shorthand ? {
2348
+ start: properties[index].start,
2349
+ end: properties[index].end,
2350
+ text: `${keyOf(properties[index])}: ${text}`
2351
+ } : {
2352
+ start: value.start,
2353
+ end: value.end,
2354
+ text
2355
+ });
2356
+ }
2357
+ if (appended.length > 0) {
2358
+ const last = properties[properties.length - 1];
2359
+ if (!last) splices.push({
2360
+ start: object.start,
2361
+ end: object.end,
2362
+ text: `{ ${appended.join(", ")} }`
2363
+ });
2364
+ else if (lineOf(source, last.start) > lineOf(source, object.start)) {
2365
+ const indent = lineIndent(source, last.start);
2366
+ const after = /^\s*,/.exec(source.slice(last.end));
2367
+ splices.push(after ? {
2368
+ start: last.end + after[0].length,
2369
+ end: last.end + after[0].length,
2370
+ text: appended.map((item) => `\n${indent}${item},`).join("")
2371
+ } : {
2372
+ start: last.end,
2373
+ end: last.end,
2374
+ text: appended.map((item) => `,\n${indent}${item}`).join("")
2375
+ });
2376
+ } else splices.push({
2377
+ start: last.end,
2378
+ end: last.end,
2379
+ text: `, ${appended.join(", ")}`
2380
+ });
2381
+ }
2382
+ return splices;
2383
+ }
2384
+ const items = [];
2385
+ properties.forEach((property, index) => {
2386
+ if (removed.has(index)) return;
2387
+ const text = replaced.get(index);
2388
+ items.push(text === void 0 ? source.slice(property.start, property.end) : `${keyOf(property)}: ${text}`);
2389
+ });
2390
+ items.push(...appended);
2391
+ if (items.length === 0) return [{
2392
+ start: /\s*$/.exec(source.slice(0, attr.start))?.index ?? attr.start,
2393
+ end: attr.end,
2394
+ text: ""
2395
+ }];
2396
+ const first = properties[0];
2397
+ if (lineOf(source, first.start) > lineOf(source, object.start)) {
2398
+ const indent = lineIndent(source, first.start);
2399
+ const closing = lineIndent(source, object.end - 1);
2400
+ return [{
2401
+ start: object.start,
2402
+ end: object.end,
2403
+ text: `{\n${items.map((item) => `${indent}${item},\n`).join("")}${closing}}`
2404
+ }];
2405
+ }
2406
+ return [{
2407
+ start: object.start,
2408
+ end: object.end,
2409
+ text: `{ ${items.join(", ")} }`
2410
+ }];
2411
+ }
2412
+ function planStyle(ast, source, edit) {
2413
+ const found = locate(ast, edit, edit.tag);
2414
+ if (!found.ok) return found;
2415
+ const sets = [];
2416
+ const removes = [];
2417
+ const current = readProps(ast, source, found.expression);
2418
+ for (const [prop, value] of Object.entries(edit.changes)) {
2419
+ if (!isStyleProp(prop)) return {
2420
+ ok: false,
2421
+ status: 400,
2422
+ error: `not a style the panel writes: ${prop}`
2423
+ };
2424
+ if (!isValidStyleValue(prop, value)) return {
2425
+ ok: false,
2426
+ status: 422,
2427
+ error: `not a value ${prop} can take: ${String(value)}`
2428
+ };
2429
+ if (edit.expected && prop in edit.expected) {
2430
+ if (JSON.stringify(current[prop] ?? null) !== JSON.stringify(edit.expected[prop] ?? null)) return {
2431
+ ok: false,
2432
+ status: 409,
2433
+ error: "this element’s style changed in source since it was selected"
2434
+ };
2435
+ }
2436
+ if (value === null) removes.push(prop);
2437
+ else sets.push([prop, value]);
2438
+ }
2439
+ const { opening, attr, expression } = found;
2440
+ const object = unwrap(expression ?? void 0);
2441
+ if (attr && object?.type === "ObjectExpression") return {
2442
+ ok: true,
2443
+ splices: planObject(source, object, sets, removes, attr)
2444
+ };
2445
+ if (sets.length === 0) return {
2446
+ ok: true,
2447
+ splices: []
2448
+ };
2449
+ const items = sets.map(([prop, value]) => `${prop}: ${literal(value)}`).join(", ");
2450
+ if (attr && expression) return {
2451
+ ok: true,
2452
+ splices: [{
2453
+ start: expression.start,
2454
+ end: expression.end,
2455
+ text: `{ ...${source.slice(expression.start, expression.end)}, ${items} }`
2456
+ }]
2457
+ };
2458
+ const attributes = opening.attributes;
2459
+ const after = attributes[attributes.length - 1] ?? opening.name;
2460
+ return {
2461
+ ok: true,
2462
+ splices: [{
2463
+ start: after.end,
2464
+ end: after.end,
2465
+ text: ` style={{ ${items} }}`
2466
+ }]
2467
+ };
2468
+ }
2469
+ function overlaps(a, b) {
2470
+ return a.start < b.end && b.start < a.end;
2471
+ }
2472
+ /**
2473
+ * Text and style changes from one save, located against the same source and
2474
+ * written as one splice pass — so a save that retyped a heading and resized it
2475
+ * is one write and one hot reload, and neither edit's location is moved by
2476
+ * the other before it is found.
2477
+ */
2478
+ function replaceEditsAt(source, texts, styles) {
2479
+ const ast = parseStrict(source);
2480
+ if (!ast) return {
2481
+ source,
2482
+ texts: texts.map(() => SYNTAX_ERROR),
2483
+ styles: styles.map(() => SYNTAX_ERROR)
2484
+ };
2485
+ const text = planTextEdits(ast, source, texts);
2486
+ const splices = [...text.splices];
2487
+ const results = [];
2488
+ for (const edit of styles) {
2489
+ const planned = planStyle(ast, source, edit);
2490
+ if (!planned.ok) {
2491
+ results.push(planned);
2492
+ continue;
2493
+ }
2494
+ if (planned.splices.some((splice) => splices.some((other) => overlaps(splice, other)))) {
2495
+ results.push({
2496
+ ok: false,
2497
+ status: 409,
2498
+ error: "another edit in this save rewrites the same source"
2499
+ });
2500
+ continue;
2501
+ }
2502
+ splices.push(...planned.splices);
2503
+ results.push({ ok: true });
2504
+ }
2505
+ return {
2506
+ source: applySplices(source, splices),
2507
+ texts: text.results,
2508
+ styles: results
2509
+ };
2510
+ }
2511
+ //#endregion
2021
2512
  //#region src/ops/text.ts
2022
2513
  async function sourceOf(ctx, docId) {
2023
2514
  const entry = resolveEntry(ctx, docId);
@@ -2066,6 +2557,26 @@ async function writeTexts(ctx, docId, edits) {
2066
2557
  if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
2067
2558
  return { results: result.results };
2068
2559
  }
2560
+ /** What the element at `loc` sets in its `style`, key by key, for the element panel's Format section. */
2561
+ async function readStyle(ctx, docId, loc, tag) {
2562
+ const { source } = await sourceOf(ctx, docId);
2563
+ return readStyleAt(source, loc, tag);
2564
+ }
2565
+ /**
2566
+ * One save from the element panel: retyped text and style changes, located
2567
+ * against the same read of the file and written once. Per-edit failures are
2568
+ * reported, not thrown, like `writeTexts`.
2569
+ */
2570
+ async function writeEdits(ctx, docId, texts, styles) {
2571
+ if (texts.length + styles.length === 0) throw new OpsError(400, "at least one edit is required");
2572
+ const { entry, source } = await sourceOf(ctx, docId);
2573
+ const result = replaceEditsAt(source, texts, styles);
2574
+ if (result.source !== source) await fs.writeFile(entry, result.source, "utf8");
2575
+ return {
2576
+ texts: result.texts,
2577
+ styles: result.styles
2578
+ };
2579
+ }
2069
2580
  /** Leaves a `@doc-comment` marker in the source for a later agent pass to act on. */
2070
2581
  async function addComment(ctx, docId, loc, note, hint) {
2071
2582
  if (note.trim() === "") throw new OpsError(400, "note is empty");
@@ -2102,6 +2613,54 @@ function readSegments(value) {
2102
2613
  }
2103
2614
  return segments;
2104
2615
  }
2616
+ function readTextEdits(docId, value) {
2617
+ if (!Array.isArray(value)) return null;
2618
+ const edits = [];
2619
+ for (const raw of value) {
2620
+ const loc = readLoc({
2621
+ ...raw,
2622
+ docId
2623
+ });
2624
+ if (!loc || typeof raw.text !== "string") return null;
2625
+ edits.push({
2626
+ line: loc.line,
2627
+ column: loc.column,
2628
+ text: raw.text,
2629
+ segments: readSegments(raw.segments),
2630
+ index: typeof raw.index === "number" ? raw.index : void 0,
2631
+ prop: typeof raw.prop === "string" ? raw.prop : void 0,
2632
+ expected: typeof raw.expected === "string" ? raw.expected : void 0,
2633
+ shown: typeof raw.shown === "string" ? raw.shown : void 0
2634
+ });
2635
+ }
2636
+ return edits;
2637
+ }
2638
+ function readStyleEdits(docId, value) {
2639
+ if (!Array.isArray(value)) return null;
2640
+ const edits = [];
2641
+ for (const raw of value) {
2642
+ const loc = readLoc({
2643
+ ...raw,
2644
+ docId
2645
+ });
2646
+ const changes = raw.changes;
2647
+ if (!loc || typeof raw.tag !== "string" || typeof changes !== "object" || !changes) return null;
2648
+ const clean = {};
2649
+ for (const [key, change] of Object.entries(changes)) {
2650
+ if (change !== null && typeof change !== "string" && typeof change !== "number") return null;
2651
+ clean[key] = change;
2652
+ }
2653
+ const expected = typeof raw.expected === "object" && raw.expected !== null ? raw.expected : void 0;
2654
+ edits.push({
2655
+ line: loc.line,
2656
+ column: loc.column,
2657
+ tag: raw.tag,
2658
+ changes: clean,
2659
+ ...expected ? { expected } : {}
2660
+ });
2661
+ }
2662
+ return edits;
2663
+ }
2105
2664
  function registerEditRoutes(server, ctx) {
2106
2665
  const entryFor = (docId) => resolveDocEntry(ctx.docsRoot, docId);
2107
2666
  server.middlewares.use("/__edit", async (req, res, next) => {
@@ -2145,26 +2704,30 @@ function registerEditRoutes(server, ctx) {
2145
2704
  if (!check.ok) return json(res, check.status, { error: check.error });
2146
2705
  const body = await readBody(req);
2147
2706
  if (typeof body.docId !== "string" || !Array.isArray(body.edits)) return json(res, 400, { error: "invalid payload" });
2148
- const edits = [];
2149
- for (const raw of body.edits) {
2150
- const loc = readLoc({
2151
- ...raw,
2152
- docId: body.docId
2153
- });
2154
- if (!loc || typeof raw.text !== "string") return json(res, 400, { error: "invalid payload" });
2155
- edits.push({
2156
- line: loc.line,
2157
- column: loc.column,
2158
- text: raw.text,
2159
- segments: readSegments(raw.segments),
2160
- index: typeof raw.index === "number" ? raw.index : void 0,
2161
- prop: typeof raw.prop === "string" ? raw.prop : void 0,
2162
- expected: typeof raw.expected === "string" ? raw.expected : void 0,
2163
- shown: typeof raw.shown === "string" ? raw.shown : void 0
2164
- });
2165
- }
2707
+ const edits = readTextEdits(body.docId, body.edits);
2708
+ if (!edits) return json(res, 400, { error: "invalid payload" });
2166
2709
  return json(res, 200, await writeTexts(ctx, body.docId, edits));
2167
2710
  }
2711
+ if (method === "GET" && url.pathname === "/style") {
2712
+ const loc = readLoc({
2713
+ docId: url.searchParams.get("docId"),
2714
+ line: Number(url.searchParams.get("line")),
2715
+ column: Number(url.searchParams.get("column"))
2716
+ });
2717
+ const tag = url.searchParams.get("tag") ?? "";
2718
+ if (!loc || !Number.isFinite(loc.line) || !Number.isFinite(loc.column) || tag === "") return json(res, 400, { error: "invalid target" });
2719
+ return json(res, 200, await readStyle(ctx, loc.docId, loc, tag));
2720
+ }
2721
+ if (method === "PUT" && url.pathname === "/batch") {
2722
+ const check = validateMutationRequest(req, { requireJsonBody: true });
2723
+ if (!check.ok) return json(res, check.status, { error: check.error });
2724
+ const body = await readBody(req);
2725
+ if (typeof body.docId !== "string") return json(res, 400, { error: "invalid payload" });
2726
+ const texts = readTextEdits(body.docId, body.texts ?? []);
2727
+ const styles = readStyleEdits(body.docId, body.styles ?? []);
2728
+ if (!texts || !styles) return json(res, 400, { error: "invalid payload" });
2729
+ return json(res, 200, await writeEdits(ctx, body.docId, texts, styles));
2730
+ }
2168
2731
  if (method === "POST" && url.pathname === "/comment") {
2169
2732
  const check = validateMutationRequest(req, { requireJsonBody: true });
2170
2733
  if (!check.ok) return json(res, check.status, { error: check.error });
@@ -1,5 +1,5 @@
1
1
  import { t as readCoreVersion } from "./cli/bin.js";
2
- import { A as loadUserConfig, O as makeContext } from "./config-CvzpyAUA.js";
2
+ import { A as loadUserConfig, O as makeContext } from "./config-B_pdNbYg.js";
3
3
  //#region src/cli/context.ts
4
4
  /** The same context the dev API and the MCP server run on, for commands that call `ops/`. */
5
5
  async function cliContext(userCwd = process.cwd()) {