@kamilio/wire 0.1.43 → 0.1.45

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 (56) hide show
  1. package/README.md +8 -2
  2. package/dist/adapters/gdrive.d.ts.map +1 -1
  3. package/dist/adapters/gdrive.js +31 -15
  4. package/dist/adapters/gdrive.js.map +1 -1
  5. package/dist/adapters/root.d.ts.map +1 -1
  6. package/dist/adapters/root.js +5 -2
  7. package/dist/adapters/root.js.map +1 -1
  8. package/dist/adapters/sheet-markdown.d.ts +48 -0
  9. package/dist/adapters/sheet-markdown.d.ts.map +1 -0
  10. package/dist/adapters/sheet-markdown.js +89 -0
  11. package/dist/adapters/sheet-markdown.js.map +1 -0
  12. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts +10 -0
  13. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -0
  14. package/node_modules/provider-google-docs/dist/doc-blocks.js +142 -0
  15. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -0
  16. package/node_modules/provider-google-docs/dist/google-docs.d.ts +1 -0
  17. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  18. package/node_modules/provider-google-docs/dist/google-docs.js +166 -241
  19. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  20. package/node_modules/provider-google-docs/dist/google-read.d.ts +6 -0
  21. package/node_modules/provider-google-docs/dist/google-read.d.ts.map +1 -0
  22. package/node_modules/provider-google-docs/dist/google-read.js +22 -0
  23. package/node_modules/provider-google-docs/dist/google-read.js.map +1 -0
  24. package/node_modules/provider-google-docs/dist/index.d.ts +1 -1
  25. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  26. package/node_modules/provider-google-docs/dist/index.js +1 -1
  27. package/node_modules/provider-google-docs/dist/index.js.map +1 -1
  28. package/node_modules/provider-google-docs/dist/native-docs.d.ts +9 -0
  29. package/node_modules/provider-google-docs/dist/native-docs.d.ts.map +1 -0
  30. package/node_modules/provider-google-docs/dist/native-docs.js +593 -0
  31. package/node_modules/provider-google-docs/dist/native-docs.js.map +1 -0
  32. package/node_modules/provider-google-docs/src/doc-blocks.ts +119 -0
  33. package/node_modules/provider-google-docs/src/google-docs.ts +156 -227
  34. package/node_modules/provider-google-docs/src/google-read.ts +22 -0
  35. package/node_modules/provider-google-docs/src/index.ts +1 -1
  36. package/node_modules/provider-google-docs/src/native-docs.ts +476 -0
  37. package/node_modules/wire-core/dist/core/model.d.ts +1 -0
  38. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  39. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  40. package/node_modules/wire-core/dist/operations.js +108 -28
  41. package/node_modules/wire-core/dist/operations.js.map +1 -1
  42. package/node_modules/wire-core/dist/runtime/node.d.ts.map +1 -1
  43. package/node_modules/wire-core/dist/runtime/node.js +7 -2
  44. package/node_modules/wire-core/dist/runtime/node.js.map +1 -1
  45. package/node_modules/wire-core/dist/storage/registry.d.ts +3 -1
  46. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  47. package/node_modules/wire-core/dist/storage/registry.js +50 -1
  48. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  49. package/node_modules/wire-core/src/core/model.ts +1 -0
  50. package/node_modules/wire-core/src/operations.ts +91 -28
  51. package/node_modules/wire-core/src/runtime/node.ts +6 -2
  52. package/node_modules/wire-core/src/storage/registry.ts +41 -2
  53. package/package.json +1 -1
  54. package/src/adapters/gdrive.ts +34 -22
  55. package/src/adapters/root.ts +5 -2
  56. package/src/adapters/sheet-markdown.ts +89 -0
@@ -1,4 +1,7 @@
1
1
  import { defineService } from "wire-core";
2
+ import { mergeDocBlocks } from "./doc-blocks.js";
3
+ import { googleRead } from "./google-read.js";
4
+ import { nativeDocMarkdownEqual, nativeDocsGrant, tryUploadDocBlocks } from "./native-docs.js";
2
5
  import { inflateRawSync } from "node:zlib";
3
6
  async function cookieHeader(runtime) {
4
7
  const cookies = await runtime.cookies.loadSaved("google-docs");
@@ -18,26 +21,56 @@ function filenameTitle(value, label) {
18
21
  const filename = encoded !== null ? decodeURIComponent(encoded[1]) : quoted !== null ? quoted[1] : bare[1].trim();
19
22
  return filename.replace(/\.(csv|html|md|pptx|txt|xlsx)$/i, "");
20
23
  }
21
- async function googleExport(runtime, url, label) {
22
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
23
- if (response.status === 401 || response.status === 403)
24
+ async function docExportRequest(runtime, url, token) {
25
+ if (token === null) {
26
+ const init = { headers: { Cookie: await cookieHeader(runtime) } };
27
+ return url.startsWith("https://docs.google.com/document/") ? googleRead(runtime, url, init) : runtime.http.request(url, init);
28
+ }
29
+ // The tab-specific export accepts OAuth and returns a signed download URL.
30
+ // Never forward the access token to the download host or to a login page.
31
+ const first = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + token }, redirect: "manual" });
32
+ if (first.status < 300 || first.status >= 400)
33
+ return first;
34
+ const location = first.headers.get("location");
35
+ if (!location)
36
+ throw new Error("Google Docs export did not include a download URL");
37
+ const target = new URL(location);
38
+ if (target.protocol !== "https:" || !target.hostname.endsWith(".googleusercontent.com") || target.username || target.password || target.port)
39
+ throw new Error("Google Docs export returned an unexpected download URL");
40
+ return googleRead(runtime, target, { redirect: "error" });
41
+ }
42
+ async function googleExport(runtime, url, label, token = null) {
43
+ const response = await docExportRequest(runtime, url, token);
44
+ if (response.status === 401 || response.status === 403) {
45
+ if (token !== null)
46
+ throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
24
47
  throw cookieAuthenticationError();
48
+ }
25
49
  if (!response.ok)
26
50
  throw new Error(`Google ${label} failed: HTTP ${response.status}`);
27
51
  const disposition = response.headers.get("content-disposition");
28
- if (disposition === null)
52
+ if (disposition === null) {
53
+ if (token !== null)
54
+ throw new Error(`Google ${label} did not include a filename`);
29
55
  throw cookieAuthenticationError();
56
+ }
30
57
  return Object.freeze({ title: filenameTitle(disposition, label), text: await response.text() });
31
58
  }
32
- async function googleExportBytes(runtime, url, label) {
33
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
34
- if (response.status === 401 || response.status === 403)
59
+ async function googleExportBytes(runtime, url, label, token = null) {
60
+ const response = await docExportRequest(runtime, url, token);
61
+ if (response.status === 401 || response.status === 403) {
62
+ if (token !== null)
63
+ throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
35
64
  throw cookieAuthenticationError();
65
+ }
36
66
  if (!response.ok)
37
67
  throw new Error(`Google ${label} failed: HTTP ${response.status}`);
38
68
  const disposition = response.headers.get("content-disposition");
39
- if (disposition === null)
69
+ if (disposition === null) {
70
+ if (token !== null)
71
+ throw new Error(`Google ${label} did not include a filename`);
40
72
  throw cookieAuthenticationError();
73
+ }
41
74
  return Object.freeze({ title: filenameTitle(disposition, label), bytes: new Uint8Array(await response.arrayBuffer()) });
42
75
  }
43
76
  async function googleText(runtime, url, label) {
@@ -215,13 +248,6 @@ function sheetEditUrl(documentId, gid, key) {
215
248
  url.searchParams.set("resourcekey", key);
216
249
  return url.toString();
217
250
  }
218
- function docEditUrl(documentId, key, tab) {
219
- const url = new URL(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/edit`);
220
- url.searchParams.set("tab", tab);
221
- if (key !== null)
222
- url.searchParams.set("resourcekey", key);
223
- return url.toString();
224
- }
225
251
  function documentTab(source) {
226
252
  const tab = source["document_tab"];
227
253
  return typeof tab === "string" && tab !== "" ? tab : null;
@@ -593,29 +619,6 @@ async function uploadSheetRows(runtime, documentId, gid, key, cells) {
593
619
  if (result["revisionRanges"] === undefined)
594
620
  throw new Error("Google Sheets save failed: missing revision ranges");
595
621
  }
596
- function docSession(html) {
597
- const tokenMatch = /"info_params":\{"token":"([^"]+)"/.exec(html);
598
- if (tokenMatch === null)
599
- throw cookieAuthenticationError();
600
- const token = tokenMatch[1];
601
- const ouidMatch = /"ouid":"([^"]+)"/.exec(html);
602
- const revisionMatch = /DOCS_warmStartDocumentLoader\.startLoad\(\s*([0-9.]+)/.exec(html);
603
- if (ouidMatch === null || revisionMatch === null)
604
- throw new Error("Google Docs editor did not include save metadata");
605
- const ouid = ouidMatch[1];
606
- const revision = Number(revisionMatch[1]);
607
- const chunks = [];
608
- const pattern = /DOCS_modelChunk = (\{[\s\S]*?\}); DOCS_modelChunkLoadStart/g;
609
- let match = pattern.exec(html);
610
- while (match !== null) {
611
- const chunk = JSON.parse(match[1]);
612
- for (const command of chunk.chunk)
613
- if (command["ty"] === "is")
614
- chunks.push(command["s"]);
615
- match = pattern.exec(html);
616
- }
617
- return Object.freeze({ token, ouid, revision, text: chunks.join("") });
618
- }
619
622
  function markdownDocTable(value) {
620
623
  const lines = value.trimEnd().split(/\r?\n/);
621
624
  const separator = lines.findIndex((line) => markdownTableRow(line).every((cell) => /^:?-{3,}:?$/.test(cell)));
@@ -635,211 +638,119 @@ function markdownCombinedEmphasis(value) {
635
638
  function markdownText(value) {
636
639
  return markdownEntities(markdownHtmlTags(markdownCombinedEmphasis(value.replace(/[ \t]{2,}(?=\r?\n|$)/g, "").replace(/(?:^[ \t]*\|.*\|[ \t]*(?:\r?\n|$)){2,}/gm, markdownDocTable).replace(/^```[^\n]*\r?\n([\s\S]*?)\r?\n```[ \t]*$/gm, "$1").replace(/^[ \t]*!\[[^\]\n]*\]\([^)]+\)[ \t]*(?:\r?\n)?/gm, "").replace(/^[ \t]{0,3}\[[^\]\n]+\]:[ \t]+[^\n]*(?:\r?\n)?/gm, "").replace(/^[ \t]{0,3}(?:-{3,}|\*{3,}|_{3,})[ \t]*(?:\r?\n)*/gm, "").replace(/[ \t]*!\[[^\]\n]*\]\([^)]+\)[ \t]*/g, " ").replace(/[ \t]*!\[[^\]\n]*\]\[[^\]\n]*\][ \t]*/g, " ").replace(/\\([\\`*_{}\[\]()#+\-.!|=~])/g, "$1").replace(/^[ \t]*>+[ \t]?/gm, "").replace(/^[ \t]*(?:[-*+]|\d+[.)])[ \t]+/gm, "").replace(/^\[(?: |x|X)\][ \t]+/gm, "").replace(/`([^`\n]+)`/g, "$1").replace(/~~([^~\n]+)~~/g, "$1").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/\*([^*\n]+)\*/g, "$1").replace(/(^|[^\w])__([^_\n]+?)__(?=[^\w]|$)/g, "$1$2").replace(/(^|[^\w])_([^_\n]+?)_(?=[^\w]|$)/g, "$1$2").replace(/^#+ /gm, "").replace(/<((?:https?|mailto):[^>\s]+)>/g, "$1").replace(/\[([^\]\n]+)\]\[[^\]\n]*\]/g, "$1").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1"))));
637
640
  }
638
- function comparableDocMarkdown(value) {
639
- return markdownEntities(markdownHtmlTags(markdownCombinedEmphasis(value.replace(/[ \t]{2,}(?=\r?\n|$)/g, "").replace(/\\([\\`*_{}\[\]()#+\-.!|=~])/g, "$1").replace(/\s+$/g, ""))));
640
- }
641
- function docMarkdownEqual(left, right) {
642
- return comparableDocMarkdown(left) === comparableDocMarkdown(right);
643
- }
644
- function textEdit(base, local) {
645
- let start = 0;
646
- while (start < base.length && start < local.length && base[start] === local[start])
647
- start += 1;
648
- for (let window = 80; window >= 10; window -= 10) {
649
- for (let baseEnd = start; baseEnd <= Math.min(base.length - window, start + 2000); baseEnd += 1) {
650
- const anchor = base.slice(baseEnd, baseEnd + window);
651
- const localEnd = local.indexOf(anchor, start);
652
- if (localEnd !== -1 && localEnd <= start + 2000)
653
- return Object.freeze({ base: base.slice(start, baseEnd), local: local.slice(start, localEnd), before: base.slice(0, start), localBefore: "", after: base.slice(baseEnd), localAfter: local.slice(localEnd) });
654
- }
655
- }
656
- let baseEnd = base.length;
657
- let localEnd = local.length;
658
- while (baseEnd > start && localEnd > start && base[baseEnd - 1] === local[localEnd - 1]) {
659
- baseEnd -= 1;
660
- localEnd -= 1;
641
+ // Docs can export a real outer bullet as "> *" while leaving its children
642
+ // unquoted. A Markdown quote looks identical, so consult the native paragraphs.
643
+ export async function googleDocListMarkdown(markdown, wordExport) {
644
+ if (!/^> (?:\*|\d+\.) /m.test(markdown))
645
+ return markdown;
646
+ const doc = parseXml(zipText(unzipFiles(await wordExport()), "word/document.xml"));
647
+ const outer = new Set(), other = new Set();
648
+ const key = (s) => s.replace(/\s+/g, " ").trim();
649
+ for (const p of xmlDescendants(doc, "w:p")) {
650
+ const props = xmlChildren(p, "w:pPr")[0];
651
+ const numbering = props && xmlChildren(props, "w:numPr")[0];
652
+ const level = numbering && xmlChildren(numbering, "w:ilvl")[0]?.attributes.get("w:val");
653
+ const style = props && xmlChildren(props, "w:pStyle")[0]?.attributes.get("w:val");
654
+ const text = key(xmlDescendants(p, "w:t").map(xmlText).join(""));
655
+ (level === "0" && !/quote/i.test(style ?? "") ? outer : other).add(text);
661
656
  }
662
- return Object.freeze({ base: base.slice(start, baseEnd), local: local.slice(start, localEnd), before: base.slice(0, start), localBefore: "", after: base.slice(baseEnd), localAfter: local.slice(localEnd) });
663
- }
664
- function textEdits(base, local) {
665
- const edits = [];
666
- let basePrefix = "";
667
- let localPrefix = "";
668
- let baseRest = base;
669
- let localRest = local;
670
- while (baseRest !== localRest) {
671
- const edit = textEdit(baseRest, localRest);
672
- const before = `${basePrefix}${edit.before}`;
673
- const localBefore = `${localPrefix}${edit.before}`;
674
- edits.push(Object.freeze({ ...edit, before, localBefore }));
675
- basePrefix = base.slice(0, base.length - edit.after.length);
676
- localPrefix = local.slice(0, local.length - edit.localAfter.length);
677
- baseRest = edit.after;
678
- localRest = edit.localAfter;
679
- }
680
- return edits;
681
- }
682
- function inlineMarkdownSpans(value) {
683
- const spans = [];
684
- for (const pattern of [/\[[^\]\n]+\]\([^)]+\)/g, /!\[[^\]\n]*\]\([^)]+\)/g, /`[^`\n]+`/g, /~~[^~\n]+~~/g, /\*\*[^*\n]+\*\*/g, /\*[^*\n]+\*/g, /(^|[^\w])__[^_\n]+__(?=[^\w]|$)/g, /(^|[^\w])_[^_\n]+_(?=[^\w]|$)/g, /<((?:https?|mailto):[^>\s]+)>/g, /<\/?(?:u|sup|sub|mark|span)(?:\s+[^>]*)?>/gi]) {
685
- let match = pattern.exec(value);
686
- while (match !== null) {
687
- spans.push(Object.freeze({ start: match.index, end: match.index + match[0].length }));
688
- match = pattern.exec(value);
689
- }
690
- }
691
- return spans;
692
- }
693
- function editTouchesMarkdownSpan(before, value, edited) {
694
- const start = before.length;
695
- const end = start + edited.length;
696
- return inlineMarkdownSpans(value).some((span) => start === end ? start > span.start && start < span.end : start < span.end && end > span.start);
697
- }
698
- function context(value, side, length) {
699
- return side === "before" ? value.slice(Math.max(0, value.length - length)) : value.slice(0, length);
700
- }
701
- function followingWhitespaceEnd(text, index) {
702
- let end = index;
703
- while (end < text.length && /\s/.test(text[end]))
704
- end += 1;
705
- return end;
706
- }
707
- function docTextRange(text, edit) {
708
- const base = markdownText(edit.base);
709
- const beforeText = markdownText(edit.before);
710
- const afterText = markdownText(edit.after);
711
- const candidates = [];
712
- if (base === "") {
713
- if (beforeText !== "") {
714
- const anchor = context(beforeText, "before", Math.min(80, beforeText.length));
715
- const trimmed = anchor.replace(/\s+$/g, "");
716
- let index = 0;
717
- for (;;) {
718
- const found = text.indexOf(anchor, index);
719
- if (found === -1)
720
- break;
721
- candidates.push(found + anchor.length);
722
- index = found + 1;
723
- }
724
- if (trimmed !== anchor) {
725
- index = 0;
726
- for (;;) {
727
- const found = text.indexOf(trimmed, index);
728
- if (found === -1)
729
- break;
730
- candidates.push(followingWhitespaceEnd(text, found + trimmed.length));
731
- index = found + 1;
732
- }
733
- }
734
- }
735
- if (afterText === "") {
736
- candidates.push(text.length);
657
+ let fence = "";
658
+ return markdown.split("\n").map(line => {
659
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
660
+ if (marker) {
661
+ if (!fence)
662
+ fence = marker[1];
663
+ else if (marker[1].startsWith(fence) && !marker[2].trim())
664
+ fence = "";
665
+ return line;
737
666
  }
738
- else {
739
- const anchor = context(afterText, "after", Math.min(80, afterText.length));
740
- let index = 0;
741
- for (;;) {
742
- const found = text.indexOf(anchor, index);
743
- if (found === -1)
744
- break;
745
- candidates.push(found);
746
- index = found + 1;
747
- }
667
+ if (fence || !/^> (?:\*|\d+\.) /.test(line))
668
+ return line;
669
+ const text = key(markdownText(line));
670
+ return text && outer.has(text) && !other.has(text) ? line.slice(2) : line;
671
+ }).join("\n");
672
+ }
673
+ async function fetchGoogleDocument(runtime, source, previous) {
674
+ const id = source["document_id"] ?? source.identifier;
675
+ const key = resourceKey(source);
676
+ const gid = source["sheet_gid"];
677
+ const tab = documentTab(source);
678
+ const query = new URLSearchParams();
679
+ if (gid !== undefined || source.type === "presentation") {
680
+ const slide = source.type === "presentation";
681
+ query.set("format", slide ? "pptx" : "csv");
682
+ if (gid != null)
683
+ query.set("gid", gid);
684
+ if (key)
685
+ query.set("resourcekey", key);
686
+ const url = `https://docs.google.com/${slide ? "presentation" : "spreadsheets"}/d/${encodeURIComponent(id)}/export?${query}`;
687
+ if (slide) {
688
+ const { bytes, title } = await googleExportBytes(runtime, url, "Slides PPTX export");
689
+ const markdown = slidesMarkdown(bytes);
690
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, presentation: true } };
748
691
  }
692
+ const { text, title } = await googleExport(runtime, url, "Sheets CSV export");
693
+ const rows = parseCsv(text), markdown = sheetMarkdown(rows);
694
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: gid ?? null, markdown, rows } };
749
695
  }
750
- else {
751
- let index = 0;
752
- for (;;) {
753
- const found = text.indexOf(base, index);
754
- if (found === -1)
755
- break;
756
- candidates.push(found);
757
- index = found + 1;
696
+ const grant = await nativeDocsGrant(runtime, true);
697
+ const read = async (url) => {
698
+ const response = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + grant.token, ...(key && { "X-Goog-Drive-Resource-Keys": id + "/" + key }) }, redirect: "error" });
699
+ if (!response.ok)
700
+ throw new Error("Google Docs export failed: HTTP " + response.status);
701
+ return response;
702
+ };
703
+ let readRevision, docTitle;
704
+ if (grant && (previous !== undefined || grant.canWrite)) {
705
+ const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(id) + "?fields=documentId,title,revisionId";
706
+ const meta = await (await read(url)).json();
707
+ if (meta.documentId !== id || typeof meta.title !== "string")
708
+ throw new Error("Google Docs export returned unexpected document metadata");
709
+ readRevision = meta.revisionId;
710
+ docTitle = meta.title;
711
+ const snapshot = previous === undefined ? {} : objectValue(previous);
712
+ // Only a successfully verified, revision-controlled batch sets this key.
713
+ // Never use Drive's version, ETag, or modifiedTime as a document revision.
714
+ if (readRevision && snapshot["verified_revision"] === readRevision && snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && typeof snapshot["markdown"] === "string") {
715
+ return { title: docTitle, markdown: snapshot["markdown"], readRevision, data: { ...snapshot, title: docTitle } };
758
716
  }
759
717
  }
760
- const uniqueCandidates = [...new Set(candidates)];
761
- for (const length of [80, 40, 20, 10, 0]) {
762
- const before = context(beforeText, "before", length);
763
- const after = context(afterText, "after", length);
764
- const matched = uniqueCandidates.filter((index) => text.slice(Math.max(0, index - before.length), index) === before && text.slice(index + base.length, index + base.length + after.length) === after);
765
- if (matched.length === 1)
766
- return Object.freeze({ start: matched[0], end: matched[0] + base.length });
767
- }
768
- throw new Error("Google Docs local edit cannot be mapped to the live document text");
769
- }
770
- async function uploadDocText(runtime, documentId, key, tab, baseMarkdown, localMarkdown) {
771
- const edits = textEdits(baseMarkdown, localMarkdown);
772
- if (edits.some((edit) => editTouchesMarkdownSpan(edit.before, baseMarkdown, edit.base) || editTouchesMarkdownSpan(edit.localBefore, localMarkdown, edit.local)))
773
- throw new Error("Google Docs sync cannot preserve formatting in edited text");
774
- const editUrl = docEditUrl(documentId, key, tab);
775
- const session = docSession(await googleText(runtime, editUrl, "Docs editor"));
776
- const ranges = edits.map((edit) => ({ edit, range: docTextRange(session.text, edit) })).sort((left, right) => right.range.start - left.range.start);
777
- const sid = runtime.clock.now().getTime().toString(16).padStart(16, "0").slice(-16);
778
- const commands = ranges.flatMap(({ edit, range }) => [
779
- ...(range.start === range.end ? [] : [{ ty: "ds", si: range.start + 1, ei: range.end }]),
780
- ...(edit.local === "" ? [] : [{ ty: "is", ibi: range.start + 1, s: markdownText(edit.local) }]),
781
- ]);
782
- const params = new URLSearchParams({ id: documentId, sid, vc: "1", c: "1", w: "1", flr: "0", smv: "2147483647", smb: "[2147483647, AAE=]", token: session.token, ouid: session.ouid, includes_info_params: "true", cros_files: "false", nded: "false", tab });
783
- const body = new URLSearchParams({ rev: String(session.revision), bundles: JSON.stringify([{ commands, sid, reqId: 0 }]) });
784
- const response = await runtime.http.request(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/save?${params}`, { method: "POST", headers: { Cookie: await cookieHeader(runtime), "content-type": "application/x-www-form-urlencoded;charset=UTF-8", origin: "https://docs.google.com", referer: editUrl }, body: body.toString() });
785
- if (response.status === 401 || response.status === 403)
786
- throw cookieAuthenticationError();
787
- if (!response.ok)
788
- throw new Error(`Google Docs save failed: HTTP ${response.status}`);
789
- const text = await response.text();
790
- const result = saveResult(text, "Docs");
791
- if (result["revisionRanges"] === undefined)
792
- throw new Error("Google Docs save failed: missing revision ranges");
793
- }
794
- async function fetchGoogleDocument(runtime, source) {
795
- const documentId = source["document_id"] ?? source.identifier;
796
- let sheetGid = null;
797
- let exportUrl;
798
- let label;
799
- if (source["sheet_gid"] !== undefined) {
800
- const gid = source["sheet_gid"];
801
- const query = new URLSearchParams({ format: "csv" });
802
- if (gid !== null)
803
- query.set("gid", gid);
804
- const key = resourceKey(source);
805
- if (key !== null)
806
- query.set("resourcekey", key);
807
- exportUrl = `https://docs.google.com/spreadsheets/d/${encodeURIComponent(documentId)}/export?${query}`;
808
- label = "Sheets CSV export";
809
- sheetGid = gid;
810
- }
811
- else if (source.type === "presentation") {
812
- const query = new URLSearchParams({ format: "pptx" });
813
- const key = resourceKey(source);
814
- if (key !== null)
815
- query.set("resourcekey", key);
816
- exportUrl = `https://docs.google.com/presentation/d/${encodeURIComponent(documentId)}/export?${query}`;
817
- label = "Slides PPTX export";
718
+ let title, markdown;
719
+ if (grant?.driveExport && tab === null) {
720
+ // Drive export is unscoped and includes every tab. Never route an explicit
721
+ // tab, including t.0, through this endpoint.
722
+ const url = "https://www.googleapis.com/drive/v3/files/" + encodeURIComponent(id);
723
+ if (docTitle !== undefined)
724
+ title = docTitle;
725
+ else {
726
+ const meta = await (await read(url + "?fields=id,name&supportsAllDrives=true")).json();
727
+ if (meta.id !== id || typeof meta.name !== "string")
728
+ throw new Error("Google Docs export returned unexpected Drive file metadata");
729
+ title = meta.name;
730
+ }
731
+ const format = (mime) => read(url + "/export?" + new URLSearchParams({ mimeType: mime }));
732
+ const text = await (await format("text/markdown")).text();
733
+ markdown = await googleDocListMarkdown(text, async () => new Uint8Array(await (await format("application/vnd.openxmlformats-officedocument.wordprocessingml.document")).arrayBuffer()));
818
734
  }
819
735
  else {
820
- const query = new URLSearchParams({ format: "md" });
821
- const key = resourceKey(source);
822
- if (key !== null)
736
+ query.set("format", "md");
737
+ if (key)
823
738
  query.set("resourcekey", key);
824
- const tab = documentTab(source);
825
- if (tab !== null)
739
+ if (tab)
826
740
  query.set("tab", tab);
827
- exportUrl = `https://docs.google.com/document/d/${encodeURIComponent(documentId)}/export?${query}`;
828
- label = "Docs Markdown export";
829
- }
830
- if (source.type === "presentation") {
831
- const exported = await googleExportBytes(runtime, exportUrl, label);
832
- const markdown = slidesMarkdown(exported.bytes);
833
- return Object.freeze({ title: exported.title, markdown, data: { document_id: documentId, title: exported.title, output_path: null, sheet_gid: sheetGid, markdown, rows: null, presentation: true } });
741
+ const url = `https://docs.google.com/document/d/${encodeURIComponent(id)}/export?${query}`;
742
+ const exp = await googleExport(runtime, url, "Docs Markdown export", grant?.token ?? null);
743
+ title = exp.title;
744
+ markdown = await googleDocListMarkdown(exp.text, async () => {
745
+ const word = new URL(url);
746
+ word.searchParams.set("format", "docx");
747
+ return (await googleExportBytes(runtime, word.toString(), "Docs Word export", grant?.token ?? null)).bytes;
748
+ });
834
749
  }
835
- const exported = await googleExport(runtime, exportUrl, label);
836
- const rows = source["sheet_gid"] === undefined ? null : parseCsv(exported.text);
837
- const markdown = rows === null ? exported.text : sheetMarkdown(rows);
838
- const tab = source["sheet_gid"] === undefined ? documentTab(source) : null;
839
- return Object.freeze({ title: exported.title, markdown, data: { document_id: documentId, title: exported.title, output_path: null, sheet_gid: sheetGid, markdown, rows, ...(tab === null ? {} : { document_tab: tab }) } });
750
+ return { title, markdown, ...(readRevision ? { readRevision } : {}), data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, ...(readRevision ? { position_revision: readRevision } : {}), ...(tab === null ? {} : { document_tab: tab }) } };
840
751
  }
841
752
  async function synchronizeGoogleDocument(runtime, _url, source, base, markdown) {
842
- const remote = await fetchGoogleDocument(runtime, source);
753
+ const remote = await fetchGoogleDocument(runtime, source, base);
843
754
  if (source.type === "presentation") {
844
755
  const baseMarkdown = objectValue(base)["markdown"];
845
756
  if (typeof baseMarkdown !== "string")
@@ -854,7 +765,7 @@ async function synchronizeGoogleDocument(runtime, _url, source, base, markdown)
854
765
  const label = source["sheet_gid"] === undefined ? "Google Docs" : "Google Sheets";
855
766
  if (typeof baseMarkdown !== "string")
856
767
  throw new Error("Google sync base must include markdown");
857
- if (source["sheet_gid"] === undefined && (docMarkdownEqual(markdown, baseMarkdown) || docMarkdownEqual(markdown, remote.markdown)))
768
+ if (source["sheet_gid"] === undefined && (markdown.trimEnd() === baseMarkdown.trimEnd() || markdown.trimEnd() === remote.markdown.trimEnd()))
858
769
  return remote;
859
770
  if (source["sheet_gid"] !== undefined) {
860
771
  const baseObject = objectValue(base);
@@ -883,16 +794,30 @@ async function synchronizeGoogleDocument(runtime, _url, source, base, markdown)
883
794
  throw new Error("Google Sheets save verification failed");
884
795
  return uploaded;
885
796
  }
886
- if (source["sheet_gid"] === undefined && docMarkdownEqual(remote.markdown, baseMarkdown)) {
887
- if (markdownText(markdown) === markdownText(baseMarkdown))
888
- throw new Error("Google Docs sync cannot upload formatting-only Markdown edits");
889
- await uploadDocText(runtime, source["document_id"] ?? source.identifier, resourceKey(source), documentTab(source) ?? "t.0", baseMarkdown, markdown);
890
- const uploaded = await fetchGoogleDocument(runtime, source);
891
- if (!docMarkdownEqual(uploaded.markdown, markdown))
892
- throw new Error("Google Docs save verification failed");
893
- return uploaded;
797
+ if (documentTab(source) === "t.0" && objectValue(base)["document_id"] && !objectValue(base)["document_tab"] && baseMarkdown !== remote.markdown) {
798
+ throw new Error("Google Docs saved snapshot predates explicit tab selection. Keep the local edits and reconcile them with a fresh download of this tab.");
799
+ }
800
+ const merged = mergeDocBlocks(baseMarkdown, markdown, remote.markdown, nativeDocMarkdownEqual);
801
+ if (merged === remote.markdown)
802
+ return remote;
803
+ const id = source["document_id"] ?? source.identifier;
804
+ const key = resourceKey(source), tab = documentTab(source);
805
+ const snapshot = objectValue(base);
806
+ // A same-looking paragraph can move (or be recreated) without changing
807
+ // Markdown. Positional lookup needs the actual revision of the local base.
808
+ const positionRevision = snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && baseMarkdown === remote.markdown
809
+ ? snapshot["position_revision"] ?? snapshot["verified_revision"] : undefined;
810
+ let writtenRevision;
811
+ const native = await tryUploadDocBlocks(runtime, id, key, tab, remote.markdown, merged, async (revision) => remote.readRevision === revision ? remote.markdown : (await fetchGoogleDocument(runtime, source)).markdown, revision => { writtenRevision = revision; }, typeof positionRevision === "string" ? positionRevision : undefined);
812
+ if (!native)
813
+ throw new Error("Google Docs uploads require an OAuth token with drive, drive.file, or both documents and drive.readonly scopes. Set GOOGLE_DOCS_TOKEN_FILE or GOOGLE_FORMS_TOKEN_FILE. Browser login supports downloads only.");
814
+ const uploaded = await fetchGoogleDocument(runtime, source, {});
815
+ if (!nativeDocMarkdownEqual(uploaded.markdown, merged))
816
+ throw new Error("Google Docs save verification failed");
817
+ if (writtenRevision && writtenRevision === uploaded.readRevision) {
818
+ return { ...uploaded, data: { ...objectValue(uploaded.data), verified_revision: writtenRevision } };
894
819
  }
895
- throw new Error(`${label} changed remotely and locally. Resolve the conflict in ${label} or the local Markdown file before syncing again.`);
820
+ return uploaded;
896
821
  }
897
822
  export const googleDocsService = defineService({
898
823
  name: "google-docs",
@@ -911,7 +836,7 @@ export const googleDocsService = defineService({
911
836
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#gid=${gid ?? "default"}`, type: "spreadsheet", document_id: documentId, sheet_gid: gid, ...resource_key });
912
837
  }
913
838
  const tab = urlParam(url, "tab");
914
- if (tab !== null && tab !== "" && tab !== "t.0")
839
+ if (tab !== null && tab !== "")
915
840
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
916
841
  return Object.freeze({ service: "google-docs", identifier: documentId, type: "document", ...resource_key });
917
842
  },