@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
  import type { FetchedDocument, JsonObject, JsonValue, RuntimeCapabilities, Source } from "wire-core";
4
7
 
@@ -21,21 +24,49 @@ function filenameTitle(value: string, label: string): string {
21
24
  return filename.replace(/\.(csv|html|md|pptx|txt|xlsx)$/i, "");
22
25
  }
23
26
 
24
- async function googleExport(runtime: RuntimeCapabilities, url: string, label: string): Promise<Readonly<{ title: string; text: string }>> {
25
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
26
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
27
+ async function docExportRequest(runtime: RuntimeCapabilities, url: string, token: string | null): Promise<Response> {
28
+ if (token === null) {
29
+ const init = { headers: { Cookie: await cookieHeader(runtime) } };
30
+ return url.startsWith("https://docs.google.com/document/") ? googleRead(runtime, url, init) : runtime.http.request(url, init);
31
+ }
32
+ // The tab-specific export accepts OAuth and returns a signed download URL.
33
+ // Never forward the access token to the download host or to a login page.
34
+ const first = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + token }, redirect: "manual" });
35
+ if (first.status < 300 || first.status >= 400) return first;
36
+ const location = first.headers.get("location");
37
+ if (!location) throw new Error("Google Docs export did not include a download URL");
38
+ const target = new URL(location);
39
+ if (target.protocol !== "https:" || !target.hostname.endsWith(".googleusercontent.com") || target.username || target.password || target.port) throw new Error("Google Docs export returned an unexpected download URL");
40
+ return googleRead(runtime, target, { redirect: "error" });
41
+ }
42
+
43
+ async function googleExport(runtime: RuntimeCapabilities, url: string, label: string, token: string | null = null): Promise<Readonly<{ title: string; text: string }>> {
44
+ const response = await docExportRequest(runtime, url, token);
45
+ if (response.status === 401 || response.status === 403) {
46
+ if (token !== null) throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
47
+ throw cookieAuthenticationError();
48
+ }
27
49
  if (!response.ok) throw new Error(`Google ${label} failed: HTTP ${response.status}`);
28
50
  const disposition = response.headers.get("content-disposition");
29
- if (disposition === null) throw cookieAuthenticationError();
51
+ if (disposition === null) {
52
+ if (token !== null) throw new Error(`Google ${label} did not include a filename`);
53
+ throw cookieAuthenticationError();
54
+ }
30
55
  return Object.freeze({ title: filenameTitle(disposition, label), text: await response.text() });
31
56
  }
32
57
 
33
- async function googleExportBytes(runtime: RuntimeCapabilities, url: string, label: string): Promise<Readonly<{ title: string; bytes: Uint8Array }>> {
34
- const response = await runtime.http.request(url, { headers: { Cookie: await cookieHeader(runtime) } });
35
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
58
+ async function googleExportBytes(runtime: RuntimeCapabilities, url: string, label: string, token: string | null = null): Promise<Readonly<{ title: string; bytes: Uint8Array }>> {
59
+ const response = await docExportRequest(runtime, url, token);
60
+ if (response.status === 401 || response.status === 403) {
61
+ if (token !== null) throw new Error(`Google ${label} failed: OAuth access denied (HTTP ${response.status})`);
62
+ throw cookieAuthenticationError();
63
+ }
36
64
  if (!response.ok) throw new Error(`Google ${label} failed: HTTP ${response.status}`);
37
65
  const disposition = response.headers.get("content-disposition");
38
- if (disposition === null) throw cookieAuthenticationError();
66
+ if (disposition === null) {
67
+ if (token !== null) throw new Error(`Google ${label} did not include a filename`);
68
+ throw cookieAuthenticationError();
69
+ }
39
70
  return Object.freeze({ title: filenameTitle(disposition, label), bytes: new Uint8Array(await response.arrayBuffer()) });
40
71
  }
41
72
 
@@ -199,13 +230,6 @@ function sheetEditUrl(documentId: string, gid: string | null, key: string | null
199
230
  return url.toString();
200
231
  }
201
232
 
202
- function docEditUrl(documentId: string, key: string | null, tab: string): string {
203
- const url = new URL(`https://docs.google.com/document/d/${encodeURIComponent(documentId)}/edit`);
204
- url.searchParams.set("tab", tab);
205
- if (key !== null) url.searchParams.set("resourcekey", key);
206
- return url.toString();
207
- }
208
-
209
233
  function documentTab(source: Source): string | null {
210
234
  const tab = source["document_tab"];
211
235
  return typeof tab === "string" && tab !== "" ? tab : null;
@@ -546,26 +570,6 @@ async function uploadSheetRows(runtime: RuntimeCapabilities, documentId: string,
546
570
  if (result["revisionRanges"] === undefined) throw new Error("Google Sheets save failed: missing revision ranges");
547
571
  }
548
572
 
549
- function docSession(html: string): Readonly<{ token: string; ouid: string; revision: number; text: string }> {
550
- const tokenMatch = /"info_params":\{"token":"([^"]+)"/.exec(html);
551
- if (tokenMatch === null) throw cookieAuthenticationError();
552
- const token = tokenMatch[1]!;
553
- const ouidMatch = /"ouid":"([^"]+)"/.exec(html);
554
- const revisionMatch = /DOCS_warmStartDocumentLoader\.startLoad\(\s*([0-9.]+)/.exec(html);
555
- if (ouidMatch === null || revisionMatch === null) throw new Error("Google Docs editor did not include save metadata");
556
- const ouid = ouidMatch[1]!;
557
- const revision = Number(revisionMatch[1]!);
558
- const chunks: string[] = [];
559
- const pattern = /DOCS_modelChunk = (\{[\s\S]*?\}); DOCS_modelChunkLoadStart/g;
560
- let match = pattern.exec(html);
561
- while (match !== null) {
562
- const chunk = JSON.parse(match[1]!) as { readonly chunk: readonly JsonObject[] };
563
- for (const command of chunk.chunk) if (command["ty"] === "is") chunks.push(command["s"] as string);
564
- match = pattern.exec(html);
565
- }
566
- return Object.freeze({ token, ouid, revision, text: chunks.join("") });
567
- }
568
-
569
573
  function markdownDocTable(value: string): string {
570
574
  const lines = value.trimEnd().split(/\r?\n/);
571
575
  const separator = lines.findIndex((line) => markdownTableRow(line).every((cell) => /^:?-{3,}:?$/.test(cell)));
@@ -589,201 +593,111 @@ function markdownText(value: string): string {
589
593
  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"))));
590
594
  }
591
595
 
592
- function comparableDocMarkdown(value: string): string {
593
- return markdownEntities(markdownHtmlTags(markdownCombinedEmphasis(value.replace(/[ \t]{2,}(?=\r?\n|$)/g, "").replace(/\\([\\`*_{}\[\]()#+\-.!|=~])/g, "$1").replace(/\s+$/g, ""))));
594
- }
595
-
596
- function docMarkdownEqual(left: string, right: string): boolean {
597
- return comparableDocMarkdown(left) === comparableDocMarkdown(right);
598
- }
599
-
600
- type TextEdit = Readonly<{ base: string; local: string; before: string; localBefore: string; after: string; localAfter: string }>;
601
- type MarkdownSpan = Readonly<{ start: number; end: number }>;
602
-
603
- function textEdit(base: string, local: string): TextEdit {
604
- let start = 0;
605
- while (start < base.length && start < local.length && base[start] === local[start]) start += 1;
606
- for (let window = 80; window >= 10; window -= 10) {
607
- for (let baseEnd = start; baseEnd <= Math.min(base.length - window, start + 2000); baseEnd += 1) {
608
- const anchor = base.slice(baseEnd, baseEnd + window);
609
- const localEnd = local.indexOf(anchor, start);
610
- if (localEnd !== -1 && localEnd <= start + 2000) 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) });
611
- }
596
+ // Docs can export a real outer bullet as "> *" while leaving its children
597
+ // unquoted. A Markdown quote looks identical, so consult the native paragraphs.
598
+ export async function googleDocListMarkdown(markdown: string, wordExport: () => Promise<Uint8Array>): Promise<string> {
599
+ if (!/^> (?:\*|\d+\.) /m.test(markdown)) return markdown;
600
+ const doc = parseXml(zipText(unzipFiles(await wordExport()), "word/document.xml"));
601
+ const outer = new Set<string>(), other = new Set<string>();
602
+ const key = (s: string) => s.replace(/\s+/g, " ").trim();
603
+ for (const p of xmlDescendants(doc, "w:p")) {
604
+ const props = xmlChildren(p, "w:pPr")[0];
605
+ const numbering = props && xmlChildren(props, "w:numPr")[0];
606
+ const level = numbering && xmlChildren(numbering, "w:ilvl")[0]?.attributes.get("w:val");
607
+ const style = props && xmlChildren(props, "w:pStyle")[0]?.attributes.get("w:val");
608
+ const text = key(xmlDescendants(p, "w:t").map(xmlText).join(""));
609
+ (level === "0" && !/quote/i.test(style ?? "") ? outer : other).add(text);
612
610
  }
613
- let baseEnd = base.length;
614
- let localEnd = local.length;
615
- while (baseEnd > start && localEnd > start && base[baseEnd - 1] === local[localEnd - 1]) { baseEnd -= 1; localEnd -= 1; }
616
- 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) });
617
- }
618
-
619
- function textEdits(base: string, local: string): readonly TextEdit[] {
620
- const edits: TextEdit[] = [];
621
- let basePrefix = "";
622
- let localPrefix = "";
623
- let baseRest = base;
624
- let localRest = local;
625
- while (baseRest !== localRest) {
626
- const edit = textEdit(baseRest, localRest);
627
- const before = `${basePrefix}${edit.before}`;
628
- const localBefore = `${localPrefix}${edit.before}`;
629
- edits.push(Object.freeze({ ...edit, before, localBefore }));
630
- basePrefix = base.slice(0, base.length - edit.after.length);
631
- localPrefix = local.slice(0, local.length - edit.localAfter.length);
632
- baseRest = edit.after;
633
- localRest = edit.localAfter;
634
- }
635
- return edits;
636
- }
637
-
638
- function inlineMarkdownSpans(value: string): readonly MarkdownSpan[] {
639
- const spans: MarkdownSpan[] = [];
640
- 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]) {
641
- let match = pattern.exec(value);
642
- while (match !== null) {
643
- spans.push(Object.freeze({ start: match.index, end: match.index + match[0]!.length }));
644
- match = pattern.exec(value);
611
+ let fence = "";
612
+ return markdown.split("\n").map(line => {
613
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
614
+ if (marker) {
615
+ if (!fence) fence = marker[1]!;
616
+ else if (marker[1]!.startsWith(fence) && !marker[2]!.trim()) fence = "";
617
+ return line;
645
618
  }
619
+ if (fence || !/^> (?:\*|\d+\.) /.test(line)) return line;
620
+ const text = key(markdownText(line));
621
+ return text && outer.has(text) && !other.has(text) ? line.slice(2) : line;
622
+ }).join("\n");
623
+ }
624
+
625
+ type GoogleReadResult = FetchedDocument & { readRevision?: string };
626
+
627
+ async function fetchGoogleDocument(runtime: RuntimeCapabilities, source: Source, previous?: JsonValue): Promise<GoogleReadResult> {
628
+ const id = (source["document_id"] as string | undefined) ?? source.identifier;
629
+ const key = resourceKey(source);
630
+ const gid = source["sheet_gid"] as string | null | undefined;
631
+ const tab = documentTab(source);
632
+ const query = new URLSearchParams();
633
+ if (gid !== undefined || source.type === "presentation") {
634
+ const slide = source.type === "presentation";
635
+ query.set("format", slide ? "pptx" : "csv");
636
+ if (gid != null) query.set("gid", gid);
637
+ if (key) query.set("resourcekey", key);
638
+ const url = `https://docs.google.com/${slide ? "presentation" : "spreadsheets"}/d/${encodeURIComponent(id)}/export?${query}`;
639
+ if (slide) {
640
+ const { bytes, title } = await googleExportBytes(runtime, url, "Slides PPTX export");
641
+ const markdown = slidesMarkdown(bytes);
642
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: null, markdown, rows: null, presentation: true } };
643
+ }
644
+ const { text, title } = await googleExport(runtime, url, "Sheets CSV export");
645
+ const rows = parseCsv(text), markdown = sheetMarkdown(rows);
646
+ return { title, markdown, data: { document_id: id, title, output_path: null, sheet_gid: gid ?? null, markdown, rows } };
646
647
  }
647
- return spans;
648
- }
649
-
650
- function editTouchesMarkdownSpan(before: string, value: string, edited: string): boolean {
651
- const start = before.length;
652
- const end = start + edited.length;
653
- return inlineMarkdownSpans(value).some((span) => start === end ? start > span.start && start < span.end : start < span.end && end > span.start);
654
- }
655
-
656
- function context(value: string, side: "before" | "after", length: number): string {
657
- return side === "before" ? value.slice(Math.max(0, value.length - length)) : value.slice(0, length);
658
- }
659
-
660
- function followingWhitespaceEnd(text: string, index: number): number {
661
- let end = index;
662
- while (end < text.length && /\s/.test(text[end]!)) end += 1;
663
- return end;
664
- }
665
648
 
666
- function docTextRange(text: string, edit: Readonly<{ base: string; before: string; after: string }>): Readonly<{ start: number; end: number }> {
667
- const base = markdownText(edit.base);
668
- const beforeText = markdownText(edit.before);
669
- const afterText = markdownText(edit.after);
670
- const candidates: number[] = [];
671
- if (base === "") {
672
- if (beforeText !== "") {
673
- const anchor = context(beforeText, "before", Math.min(80, beforeText.length));
674
- const trimmed = anchor.replace(/\s+$/g, "");
675
- let index = 0;
676
- for (;;) {
677
- const found = text.indexOf(anchor, index);
678
- if (found === -1) break;
679
- candidates.push(found + anchor.length);
680
- index = found + 1;
681
- }
682
- if (trimmed !== anchor) {
683
- index = 0;
684
- for (;;) {
685
- const found = text.indexOf(trimmed, index);
686
- if (found === -1) break;
687
- candidates.push(followingWhitespaceEnd(text, found + trimmed.length));
688
- index = found + 1;
689
- }
690
- }
649
+ const grant = await nativeDocsGrant(runtime, true);
650
+ const read = async (url: string) => {
651
+ const response = await googleRead(runtime, url, { headers: { Authorization: "Bearer " + grant!.token, ...(key && { "X-Goog-Drive-Resource-Keys": id + "/" + key }) }, redirect: "error" });
652
+ if (!response.ok) throw new Error("Google Docs export failed: HTTP " + response.status);
653
+ return response;
654
+ };
655
+ let readRevision: string | undefined, docTitle: string | undefined;
656
+ if (grant && (previous !== undefined || grant.canWrite)) {
657
+ const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(id) + "?fields=documentId,title,revisionId";
658
+ const meta = await (await read(url)).json() as { documentId?: string; title?: string; revisionId?: string };
659
+ if (meta.documentId !== id || typeof meta.title !== "string") throw new Error("Google Docs export returned unexpected document metadata");
660
+ readRevision = meta.revisionId; docTitle = meta.title;
661
+ const snapshot = previous === undefined ? {} : objectValue(previous);
662
+ // Only a successfully verified, revision-controlled batch sets this key.
663
+ // Never use Drive's version, ETag, or modifiedTime as a document revision.
664
+ if (readRevision && snapshot["verified_revision"] === readRevision && snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && typeof snapshot["markdown"] === "string") {
665
+ return { title: docTitle, markdown: snapshot["markdown"], readRevision, data: { ...snapshot, title: docTitle } };
691
666
  }
692
- if (afterText === "") {
693
- candidates.push(text.length);
694
- } else {
695
- const anchor = context(afterText, "after", Math.min(80, afterText.length));
696
- let index = 0;
697
- for (;;) {
698
- const found = text.indexOf(anchor, index);
699
- if (found === -1) break;
700
- candidates.push(found);
701
- index = found + 1;
702
- }
703
- }
704
- } else {
705
- let index = 0;
706
- for (;;) {
707
- const found = text.indexOf(base, index);
708
- if (found === -1) break;
709
- candidates.push(found);
710
- index = found + 1;
711
- }
712
- }
713
- const uniqueCandidates = [...new Set(candidates)];
714
- for (const length of [80, 40, 20, 10, 0]) {
715
- const before = context(beforeText, "before", length);
716
- const after = context(afterText, "after", length);
717
- 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);
718
- if (matched.length === 1) return Object.freeze({ start: matched[0]!, end: matched[0]! + base.length });
719
667
  }
720
- throw new Error("Google Docs local edit cannot be mapped to the live document text");
721
- }
722
-
723
- async function uploadDocText(runtime: RuntimeCapabilities, documentId: string, key: string | null, tab: string, baseMarkdown: string, localMarkdown: string): Promise<void> {
724
- const edits = textEdits(baseMarkdown, localMarkdown);
725
- if (edits.some((edit) => editTouchesMarkdownSpan(edit.before, baseMarkdown, edit.base) || editTouchesMarkdownSpan(edit.localBefore, localMarkdown, edit.local))) throw new Error("Google Docs sync cannot preserve formatting in edited text");
726
- const editUrl = docEditUrl(documentId, key, tab);
727
- const session = docSession(await googleText(runtime, editUrl, "Docs editor"));
728
- const ranges = edits.map((edit) => ({ edit, range: docTextRange(session.text, edit) })).sort((left, right) => right.range.start - left.range.start);
729
- const sid = runtime.clock.now().getTime().toString(16).padStart(16, "0").slice(-16);
730
- const commands = ranges.flatMap(({ edit, range }) => [
731
- ...(range.start === range.end ? [] : [{ ty: "ds", si: range.start + 1, ei: range.end }]),
732
- ...(edit.local === "" ? [] : [{ ty: "is", ibi: range.start + 1, s: markdownText(edit.local) }]),
733
- ]);
734
- 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 });
735
- const body = new URLSearchParams({ rev: String(session.revision), bundles: JSON.stringify([{ commands, sid, reqId: 0 }]) });
736
- 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() });
737
- if (response.status === 401 || response.status === 403) throw cookieAuthenticationError();
738
- if (!response.ok) throw new Error(`Google Docs save failed: HTTP ${response.status}`);
739
- const text = await response.text();
740
- const result = saveResult(text, "Docs");
741
- if (result["revisionRanges"] === undefined) throw new Error("Google Docs save failed: missing revision ranges");
742
- }
743
668
 
744
- async function fetchGoogleDocument(runtime: RuntimeCapabilities, source: Source): Promise<FetchedDocument> {
745
- const documentId = (source["document_id"] as string | undefined) ?? source.identifier;
746
- let sheetGid: string | null = null;
747
- let exportUrl: string;
748
- let label: string;
749
- if (source["sheet_gid"] !== undefined) {
750
- const gid = source["sheet_gid"] as string | null;
751
- const query = new URLSearchParams({ format: "csv" });
752
- if (gid !== null) query.set("gid", gid);
753
- const key = resourceKey(source);
754
- if (key !== null) query.set("resourcekey", key);
755
- exportUrl = `https://docs.google.com/spreadsheets/d/${encodeURIComponent(documentId)}/export?${query}`;
756
- label = "Sheets CSV export";
757
- sheetGid = gid;
758
- } else if (source.type === "presentation") {
759
- const query = new URLSearchParams({ format: "pptx" });
760
- const key = resourceKey(source);
761
- if (key !== null) query.set("resourcekey", key);
762
- exportUrl = `https://docs.google.com/presentation/d/${encodeURIComponent(documentId)}/export?${query}`;
763
- label = "Slides PPTX export";
669
+ let title: string, markdown: string;
670
+ if (grant?.driveExport && tab === null) {
671
+ // Drive export is unscoped and includes every tab. Never route an explicit
672
+ // tab, including t.0, through this endpoint.
673
+ const url = "https://www.googleapis.com/drive/v3/files/" + encodeURIComponent(id);
674
+ if (docTitle !== undefined) title = docTitle;
675
+ else {
676
+ const meta = await (await read(url + "?fields=id,name&supportsAllDrives=true")).json() as { id?: string; name?: string };
677
+ if (meta.id !== id || typeof meta.name !== "string") throw new Error("Google Docs export returned unexpected Drive file metadata");
678
+ title = meta.name;
679
+ }
680
+ const format = (mime: string) => read(url + "/export?" + new URLSearchParams({ mimeType: mime }));
681
+ const text = await (await format("text/markdown")).text();
682
+ markdown = await googleDocListMarkdown(text, async () => new Uint8Array(await (await format("application/vnd.openxmlformats-officedocument.wordprocessingml.document")).arrayBuffer()));
764
683
  } else {
765
- const query = new URLSearchParams({ format: "md" });
766
- const key = resourceKey(source);
767
- if (key !== null) query.set("resourcekey", key);
768
- const tab = documentTab(source);
769
- if (tab !== null) query.set("tab", tab);
770
- exportUrl = `https://docs.google.com/document/d/${encodeURIComponent(documentId)}/export?${query}`;
771
- label = "Docs Markdown export";
772
- }
773
- if (source.type === "presentation") {
774
- const exported = await googleExportBytes(runtime, exportUrl, label);
775
- const markdown = slidesMarkdown(exported.bytes);
776
- 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 } });
684
+ query.set("format", "md");
685
+ if (key) query.set("resourcekey", key);
686
+ if (tab) query.set("tab", tab);
687
+ const url = `https://docs.google.com/document/d/${encodeURIComponent(id)}/export?${query}`;
688
+ const exp = await googleExport(runtime, url, "Docs Markdown export", grant?.token ?? null);
689
+ title = exp.title;
690
+ markdown = await googleDocListMarkdown(exp.text, async () => {
691
+ const word = new URL(url);
692
+ word.searchParams.set("format", "docx");
693
+ return (await googleExportBytes(runtime, word.toString(), "Docs Word export", grant?.token ?? null)).bytes;
694
+ });
777
695
  }
778
- const exported = await googleExport(runtime, exportUrl, label);
779
- const rows = source["sheet_gid"] === undefined ? null : parseCsv(exported.text);
780
- const markdown = rows === null ? exported.text : sheetMarkdown(rows);
781
- const tab = source["sheet_gid"] === undefined ? documentTab(source) : null;
782
- 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 }) } });
696
+ 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 }) } };
783
697
  }
784
698
 
785
699
  async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: string, source: Source, base: JsonValue, markdown: string): Promise<FetchedDocument> {
786
- const remote = await fetchGoogleDocument(runtime, source);
700
+ const remote = await fetchGoogleDocument(runtime, source, base);
787
701
  if (source.type === "presentation") {
788
702
  const baseMarkdown = objectValue(base)["markdown"];
789
703
  if (typeof baseMarkdown !== "string") throw new Error("Google sync base must include markdown");
@@ -794,7 +708,7 @@ async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: str
794
708
  const baseMarkdown = objectValue(base)["markdown"];
795
709
  const label = source["sheet_gid"] === undefined ? "Google Docs" : "Google Sheets";
796
710
  if (typeof baseMarkdown !== "string") throw new Error("Google sync base must include markdown");
797
- if (source["sheet_gid"] === undefined && (docMarkdownEqual(markdown, baseMarkdown) || docMarkdownEqual(markdown, remote.markdown))) return remote;
711
+ if (source["sheet_gid"] === undefined && (markdown.trimEnd() === baseMarkdown.trimEnd() || markdown.trimEnd() === remote.markdown.trimEnd())) return remote;
798
712
  if (source["sheet_gid"] !== undefined) {
799
713
  const baseObject = objectValue(base);
800
714
  if (baseObject["rows"] === undefined) {
@@ -815,14 +729,29 @@ async function synchronizeGoogleDocument(runtime: RuntimeCapabilities, _url: str
815
729
  if (!rowsEqual(stringRows(objectValue(uploaded.data)["rows"]!), localRows)) throw new Error("Google Sheets save verification failed");
816
730
  return uploaded;
817
731
  }
818
- if (source["sheet_gid"] === undefined && docMarkdownEqual(remote.markdown, baseMarkdown)) {
819
- if (markdownText(markdown) === markdownText(baseMarkdown)) throw new Error("Google Docs sync cannot upload formatting-only Markdown edits");
820
- await uploadDocText(runtime, (source["document_id"] as string | undefined) ?? source.identifier, resourceKey(source), documentTab(source) ?? "t.0", baseMarkdown, markdown);
821
- const uploaded = await fetchGoogleDocument(runtime, source);
822
- if (!docMarkdownEqual(uploaded.markdown, markdown)) throw new Error("Google Docs save verification failed");
823
- return uploaded;
732
+ if (documentTab(source) === "t.0" && objectValue(base)["document_id"] && !objectValue(base)["document_tab"] && baseMarkdown !== remote.markdown) {
733
+ 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.");
734
+ }
735
+ const merged = mergeDocBlocks(baseMarkdown, markdown, remote.markdown, nativeDocMarkdownEqual);
736
+ if (merged === remote.markdown) return remote;
737
+ const id = (source["document_id"] as string | undefined) ?? source.identifier;
738
+ const key = resourceKey(source), tab = documentTab(source);
739
+ const snapshot = objectValue(base);
740
+ // A same-looking paragraph can move (or be recreated) without changing
741
+ // Markdown. Positional lookup needs the actual revision of the local base.
742
+ const positionRevision = snapshot["document_id"] === id && (snapshot["document_tab"] ?? null) === tab && baseMarkdown === remote.markdown
743
+ ? snapshot["position_revision"] ?? snapshot["verified_revision"] : undefined;
744
+ let writtenRevision: string | undefined;
745
+ const native = await tryUploadDocBlocks(runtime, id, key, tab, remote.markdown, merged,
746
+ async revision => remote.readRevision === revision ? remote.markdown : (await fetchGoogleDocument(runtime, source)).markdown,
747
+ revision => { writtenRevision = revision; }, typeof positionRevision === "string" ? positionRevision : undefined);
748
+ if (!native) 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.");
749
+ const uploaded = await fetchGoogleDocument(runtime, source, {});
750
+ if (!nativeDocMarkdownEqual(uploaded.markdown, merged)) throw new Error("Google Docs save verification failed");
751
+ if (writtenRevision && writtenRevision === uploaded.readRevision) {
752
+ return { ...uploaded, data: { ...objectValue(uploaded.data), verified_revision: writtenRevision } };
824
753
  }
825
- throw new Error(`${label} changed remotely and locally. Resolve the conflict in ${label} or the local Markdown file before syncing again.`);
754
+ return uploaded;
826
755
  }
827
756
 
828
757
  export const googleDocsService = defineService<RuntimeCapabilities>({
@@ -841,7 +770,7 @@ export const googleDocsService = defineService<RuntimeCapabilities>({
841
770
  return Object.freeze({ service: "google-docs", identifier: `${documentId}#gid=${gid ?? "default"}`, type: "spreadsheet", document_id: documentId, sheet_gid: gid, ...resource_key });
842
771
  }
843
772
  const tab = urlParam(url, "tab");
844
- if (tab !== null && tab !== "" && tab !== "t.0") return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
773
+ if (tab !== null && tab !== "") return Object.freeze({ service: "google-docs", identifier: `${documentId}#tab=${tab}`, type: "document", document_id: documentId, document_tab: tab, ...resource_key });
845
774
  return Object.freeze({ service: "google-docs", identifier: documentId, type: "document", ...resource_key });
846
775
  },
847
776
  fetch: (runtime, _url, source) => fetchGoogleDocument(runtime, source),
@@ -0,0 +1,22 @@
1
+ import type { RuntimeCapabilities } from "wire-core";
2
+
3
+ // Only idempotent GETs. Retrying a batch or browser save can apply it twice.
4
+ export async function googleRead(runtime: RuntimeCapabilities, url: string | URL, init: { headers?: HeadersInit; redirect?: RequestRedirect }): Promise<Response> {
5
+ for (let attempt = 0; ; attempt++) {
6
+ const response = await runtime.http.request(url, init);
7
+ if (![429, 502, 503, 504].includes(response.status)) return response;
8
+ const header = response.headers.get("retry-after")?.trim();
9
+ const seconds = header && /^\d+$/.test(header) ? Number(header) : undefined;
10
+ const date = header && /^[A-Za-z]/.test(header) ? Date.parse(header) : NaN;
11
+ const delay = seconds !== undefined ? seconds * 1000 : Number.isFinite(date) ? Math.max(0, date - runtime.clock.now().getTime()) : 1000 * 2 ** attempt;
12
+ if (attempt >= 3 || delay > 30_000) {
13
+ if (response.status === 429) {
14
+ await response.body?.cancel();
15
+ throw new Error(`Google Docs read rate limited (HTTP 429); retry after ${Math.ceil(delay / 1000)} seconds.`);
16
+ }
17
+ return response;
18
+ }
19
+ await response.body?.cancel();
20
+ await new Promise(resolve => setTimeout(resolve, delay));
21
+ }
22
+ }
@@ -1,7 +1,7 @@
1
1
  import { googleDocsService } from "./google-docs.js";
2
2
  import { googleFormsService } from "./google-forms.js";
3
3
 
4
- export { googleDocOriginalImages, googleDocsService } from "./google-docs.js";
4
+ export { googleDocListMarkdown, googleDocOriginalImages, googleDocsService } from "./google-docs.js";
5
5
  export { googleFormsService } from "./google-forms.js";
6
6
  export const googleDocsProvider = Object.freeze({
7
7
  services: [googleFormsService, googleDocsService] as const,