@kamilio/wire 0.1.53 → 0.1.54

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.
@@ -1,7 +1,8 @@
1
1
  import { createGoogleTokensCapability, googleTokenExpired, parseGoogleToken } from "wire-core";
2
2
  import type { RuntimeCapabilities } from "wire-core";
3
3
  import { googleRead } from "./google-read.js";
4
- import { docBlocks, docChanges } from "./doc-blocks.js";
4
+ import { createHash } from "node:crypto";
5
+ import { boundedDeletion, docBlocks, docChanges } from "./doc-blocks.js";
5
6
 
6
7
  function eligible(scopes: readonly string[] | undefined, requireWrite: boolean): boolean {
7
8
  const has = (name: string) => scopes?.includes("https://www.googleapis.com/auth/"+name);
@@ -138,6 +139,64 @@ type Element = { startIndex?: number; endIndex: number; paragraph?: {
138
139
  [k: string]: unknown;
139
140
  } };
140
141
  type Tab = { tabProperties: { tabId: string }; childTabs?: Tab[]; documentTab: { body: { content: Element[] }; namedRanges?: Record<string, {namedRanges?: {ranges: {startIndex: number; endIndex: number}[]}[]}>; lists?: Record<string, { listProperties: { nestingLevels: { glyphType?: string; glyphSymbol?: string; glyphFormat?: string }[] } }> } };
142
+ // Only store digests of addressable repeated paragraphs. Include both neighbors,
143
+ // native formatting and list definitions. Numeric run offsets shift when a
144
+ // separate paragraph changes and are the only fields omitted from the digest.
145
+ const digest = (s: string) => createHash("sha256").update(s).digest("hex");
146
+ const labels = (md: string) => spacedBlocks(md).map(line => {
147
+ try { return paragraph(line).text; } catch { return ""; }
148
+ });
149
+ const counts = (rows: string[]) => {
150
+ const map = new Map<string,number>();
151
+ for (const row of rows) map.set(row,(map.get(row) ?? 0)+1);
152
+ return map;
153
+ };
154
+ const slot = (rows: string[], freq: Map<string,number>, i: number, target?:string) =>
155
+ !!rows[i] && (target ? rows[i]===target : freq.get(rows[i]!)! > 1) && !!rows[i-1] && !!rows[i+1]
156
+ && freq.get(rows[i-1]!) === 1 && freq.get(rows[i+1]!) === 1;
157
+ export function hasDuplicateSlots(md: string): boolean {
158
+ const rows=labels(md), freq=counts(rows);
159
+ return rows.some((_,i)=>slot(rows,freq,i));
160
+ }
161
+ type Identity = { revision: string; tab: string; markdown: string; slots: string[] };
162
+ function nativeSlots(tab: Tab, target?: string) {
163
+ const body=tab.documentTab.body.content;
164
+ const names=body.map(e=>e.paragraph?.elements.every(run=>run.textRun)
165
+ ? e.paragraph.elements.map(run=>run.textRun!.content).join("").replace(/\n$/,"") : "");
166
+ const freq=counts(names);
167
+ const result=new Map<Element,string>();
168
+ const canonical=(_key: string,v: unknown) => v && typeof v==="object" && !Array.isArray(v)
169
+ ? Object.fromEntries(Object.entries(v).sort(([a],[b])=>a<b?-1:a>b?1:0)) : v;
170
+ for (let i=1;i<body.length-1;i++) {
171
+ if (!slot(names,freq,i,target)) continue;
172
+ const triple=body.slice(i-1,i+2);
173
+ if (triple.some(e=>!e.paragraph || hasSuggestion(e.paragraph) || e.paragraph.elements.some(el=>!el.textRun) ||
174
+ e.paragraph.bullet && !tab.documentTab.lists?.[e.paragraph.bullet.listId]?.listProperties?.nestingLevels?.[e.paragraph.bullet.nestingLevel??0])) continue;
175
+ const shape=triple.map(e=>{
176
+ const {elements,...p}=e.paragraph!;
177
+ return [p,elements.map(({startIndex,endIndex,...rest})=>rest),p.bullet && tab.documentTab.lists![p.bullet.listId]];
178
+ });
179
+ result.set(body[i]!,digest(JSON.stringify(shape,canonical)));
180
+ }
181
+ return result;
182
+ }
183
+ export type NativeDocument = {documentId?:string;revisionId?:string;tabs?:Tab[]};
184
+ export function captureDuplicateIdentity(data: NativeDocument, id: string, revision: string, tabId: string|null, md: string): Identity {
185
+ if (data.documentId!==id || data.revisionId!==revision) throw new StaleDocRevision("Google Docs changed during duplicate paragraph lookup; sync again.");
186
+ const tabs: Tab[]=[];
187
+ const visit=(items:Tab[])=>{for (const t of items) { tabs.push(t); visit(t.childTabs??[]); }};
188
+ visit(data.tabs??[]);
189
+ const tab=tabId ? tabs.find(t=>t.tabProperties.tabId===tabId) : tabs.length===1 ? tabs[0] : undefined;
190
+ return {revision,tab:tab?.tabProperties.tabId ?? "",markdown:digest(md),
191
+ slots:tab?.documentTab?.body?.content ? [...nativeSlots(tab).values()] : []};
192
+ }
193
+ type DeleteContext = {base:string;local:string;identity:Identity | undefined};
194
+ export function duplicateContext(base:string,local:string,revision:unknown,raw:unknown): DeleteContext {
195
+ const proof=raw as Partial<Identity>|null;
196
+ const identity=typeof revision==="string" && proof && proof.revision===revision && typeof proof.tab==="string"
197
+ && proof.markdown===digest(base) && Array.isArray(proof.slots) && proof.slots.every(s=>typeof s==="string" && /^[a-f0-9]{64}$/.test(s)) ? proof as Identity : undefined;
198
+ return {base,local,identity};
199
+ }
141
200
  type DocsRequest = Record<string, unknown>;
142
201
 
143
202
  // Keep disjoint unchanged runs in place, including their native formatting
@@ -324,7 +383,7 @@ function movePlainLabel(tab: Tab, oldMd: string, newMd: string, guard: (a: numbe
324
383
  return dest<from?[cut,...insert]:[...insert,cut];
325
384
  }
326
385
 
327
- function plan(tab: Tab, previous: string, desired: string, comments: IndexedRange[], allowDuplicatePosition: boolean): DocsRequest[] {
386
+ function plan(tab: Tab, previous: string, desired: string, comments: IndexedRange[], allowDuplicatePosition: boolean, context?: DeleteContext): DocsRequest[] {
328
387
  const named = Object.values(tab.documentTab.namedRanges ?? {}).flatMap(n => n.namedRanges?.flatMap(n => n.ranges) ?? []);
329
388
  const protectedRanges = [...named,...comments];
330
389
  const guardText = (start: number, end: number) => {
@@ -386,11 +445,35 @@ function plan(tab: Tab, previous: string, desired: string, comments: IndexedRang
386
445
  }
387
446
  return ordered[i]!;
388
447
  }
389
- const locate = (i: number) => {
448
+ let oldLabels: string[] | undefined, oldCounts: Map<string,number> | undefined;
449
+ function boundedTarget(i: number, candidates: Element[], deleted: number): Element | undefined {
450
+ if (!context || !deleted) return;
451
+ const old=oldLabels??=labels(context.base);
452
+ // before[] excludes blanks, whereas certified slots require no intervening
453
+ // blank or opaque block. Align by both unique labels, never by array index.
454
+ const name=paragraph(before[i]!).text;
455
+ if (((oldCounts??=counts(old)).get(name)??0)<2) return;
456
+ if (deleted!==1) return unsafe("duplicate paragraph deletion needs an isolated block");
457
+ const local=labels(context.local), live=labels(previous);
458
+ const left=before[i-1], right=before[i+1];
459
+ if (!left || !right) return unsafe("duplicate paragraph deletion needs two unique neighbors");
460
+ const a=paragraph(left), b=paragraph(right);
461
+ const pos=old.indexOf(a.text)+1;
462
+ if (pos<1 || old[pos]!==name || old[pos+1]!==b.text || !boundedDeletion(old,local,live,pos)) return unsafe("duplicate paragraph identity is ambiguous");
463
+ const proof=context.identity;
464
+ if (!allowDuplicatePosition && proof?.tab!==tabId) return unsafe("missing baseline for duplicate paragraph deletion");
465
+ const marks=nativeSlots(tab,name);
466
+ return candidates.find(e=>{
467
+ const n=body.indexOf(e), mark=marks.get(e);
468
+ return mark && (allowDuplicatePosition || proof!.slots.includes(mark)) &&
469
+ n>0 && n+1<body.length && matches(body[n-1]!,a) && matches(body[n+1]!,b);
470
+ }) ?? unsafe("native identity of duplicate paragraph changed");
471
+ }
472
+ const locate = (i: number, deleted=0) => {
390
473
  const block = paragraph(before[i]!);
391
474
  const candidates = body.filter(e => matches(e,block));
392
475
  if (!candidates.length) return unsafe("paragraph is missing");
393
- const e = candidates.length === 1 ? candidates[0]! : byPosition(i);
476
+ const e = boundedTarget(i,candidates,deleted) ?? (candidates.length === 1 ? candidates[0]! : byPosition(i));
394
477
  if (!Number.isInteger(e.startIndex) || e.endIndex - e.startIndex! !== block.text.length + 1) return unsafe("unrecognized paragraph range");
395
478
  return { block, e, start: e.startIndex!, end: e.endIndex };
396
479
  };
@@ -492,7 +575,7 @@ function plan(tab: Tab, previous: string, desired: string, comments: IndexedRang
492
575
  }
493
576
  }
494
577
  for (const c of [...changes].reverse()) {
495
- const old = before.slice(c.start, c.end).map((_line, i) => locate(c.start + i));
578
+ const old = before.slice(c.start, c.end).map((_line, i) => locate(c.start + i,c.replacement.length ? 0 : c.end-c.start));
496
579
  const added = c.replacement.map(paragraph);
497
580
  for (const [i,b] of added.entries()) {
498
581
  if (b.level === null || b.level === 0 || old.length === added.length && old[i]?.block.level === b.level && old[i]?.block.numbered === b.numbered) continue;
@@ -660,14 +743,17 @@ async function anchoredComments(runtime: RuntimeCapabilities, id: string, header
660
743
  // Only raise this when no mutation was sent or Google explicitly rejected it.
661
744
  export class StaleDocRevision extends Error {}
662
745
 
663
- export async function tryUploadDocBlocks(runtime: RuntimeCapabilities, documentId: string, key: string | null, tabId: string | null, remoteMarkdown: string, desiredMarkdown: string, confirmRemote: (revision: string) => Promise<string>, onWrite?: (revision: string | undefined) => void, positionRevision?: string): Promise<boolean> {
746
+ export async function tryUploadDocBlocks(runtime: RuntimeCapabilities, documentId: string, key: string | null, tabId: string | null, remoteMarkdown: string, desiredMarkdown: string, confirmRemote: (revision: string) => Promise<string>, onWrite?: (revision: string | undefined) => void, positionRevision?: string, context?: DeleteContext, knownDocument?: NativeDocument): Promise<boolean> {
664
747
  const token = (await nativeDocsGrant(runtime))?.token;
665
748
  if (!token) return false;
666
749
  const url = "https://docs.googleapis.com/v1/documents/" + encodeURIComponent(documentId);
667
750
  const headers = { authorization: "Bearer " + token, ...(key && { "X-Goog-Drive-Resource-Keys": documentId + "/" + key }) };
668
- const response = await googleRead(runtime, url + "?includeTabsContent=true&suggestionsViewMode=SUGGESTIONS_INLINE", { headers, redirect: "error" });
669
- if (!response.ok) throw new Error("Google Docs block read failed: HTTP " + response.status);
670
- const data = await response.json() as { documentId?: string; revisionId?: string; tabs?: Tab[] };
751
+ let data=knownDocument;
752
+ if (!data) {
753
+ const response = await googleRead(runtime, url + "?includeTabsContent=true&suggestionsViewMode=SUGGESTIONS_INLINE", { headers, redirect: "error" });
754
+ if (!response.ok) throw new Error("Google Docs block read failed: HTTP " + response.status);
755
+ data=await response.json() as NativeDocument;
756
+ }
671
757
  if (data.documentId !== documentId || !data.revisionId) return unsafe("missing document identity or revision");
672
758
  const tabs: Tab[] = [];
673
759
  function visit(items: Tab[]) { for (const t of items) { tabs.push(t); visit(t.childTabs ?? []); } }
@@ -677,7 +763,7 @@ export async function tryUploadDocBlocks(runtime: RuntimeCapabilities, documentI
677
763
  if (!tab?.documentTab?.body?.content) return unsafe("missing target tab");
678
764
  const comments = await anchoredComments(runtime,documentId,headers,tab,tabs);
679
765
  if (await confirmRemote(data.revisionId) !== remoteMarkdown) throw new StaleDocRevision("Google Docs changed before writing; sync again.");
680
- const requests = plan(tab, remoteMarkdown, desiredMarkdown,comments,positionRevision === data.revisionId);
766
+ const requests = plan(tab, remoteMarkdown, desiredMarkdown,comments,positionRevision === data.revisionId,context);
681
767
  if (!requests.length) return true;
682
768
  const update = await runtime.http.request(url + ":batchUpdate", { method: "POST", headers: { ...headers, "content-type": "application/json" }, redirect: "error", body: JSON.stringify({ writeControl: { requiredRevisionId: data.revisionId }, requests }) });
683
769
  if (!update.ok) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kamilio/wire",
3
- "version": "0.1.53",
3
+ "version": "0.1.54",
4
4
  "description": "Attach Notion, Google Docs, Slack, Gmail, Asana, ChatGPT, and Zoom resources as local Markdown you can sync.",
5
5
  "keywords": [
6
6
  "markdown",