@kamilio/wire 0.1.42 → 0.1.44

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 (37) hide show
  1. package/README.md +1 -1
  2. package/dist/adapters/drive-docx.d.ts +3 -0
  3. package/dist/adapters/drive-docx.d.ts.map +1 -0
  4. package/dist/adapters/drive-docx.js +25 -0
  5. package/dist/adapters/drive-docx.js.map +1 -0
  6. package/dist/adapters/gdrive.d.ts +1 -1
  7. package/dist/adapters/gdrive.d.ts.map +1 -1
  8. package/dist/adapters/gdrive.js +59 -29
  9. package/dist/adapters/gdrive.js.map +1 -1
  10. package/dist/adapters/root.d.ts +1 -1
  11. package/dist/adapters/root.d.ts.map +1 -1
  12. package/dist/adapters/root.js +2 -2
  13. package/dist/adapters/root.js.map +1 -1
  14. package/dist/adapters/sheet-markdown.d.ts +48 -0
  15. package/dist/adapters/sheet-markdown.d.ts.map +1 -0
  16. package/dist/adapters/sheet-markdown.js +89 -0
  17. package/dist/adapters/sheet-markdown.js.map +1 -0
  18. package/dist/docx-converter.LICENSE +21 -0
  19. package/dist/docx-converter.mjs +1794 -0
  20. package/dist/executable.js +1 -1
  21. package/dist/executable.js.map +1 -1
  22. package/node_modules/provider-google-docs/dist/google-docs.d.ts +1 -0
  23. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  24. package/node_modules/provider-google-docs/dist/google-docs.js +44 -1
  25. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  26. package/node_modules/provider-google-docs/dist/index.d.ts +1 -1
  27. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  28. package/node_modules/provider-google-docs/dist/index.js +1 -1
  29. package/node_modules/provider-google-docs/dist/index.js.map +1 -1
  30. package/node_modules/provider-google-docs/src/google-docs.ts +41 -1
  31. package/node_modules/provider-google-docs/src/index.ts +1 -1
  32. package/package.json +6 -2
  33. package/src/adapters/drive-docx.ts +24 -0
  34. package/src/adapters/gdrive.ts +58 -35
  35. package/src/adapters/root.ts +3 -3
  36. package/src/adapters/sheet-markdown.ts +89 -0
  37. package/src/executable.ts +1 -1
@@ -1,9 +1,11 @@
1
+ import { readSheetTabs, sheetMarkdown } from "./sheet-markdown.js";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
4
  import { basename, dirname, extname, join } from "node:path";
4
- import { googleDocOriginalImages } from "provider-google-docs";
5
+ import { googleDocListMarkdown, googleDocOriginalImages } from "provider-google-docs";
5
6
  import type { RuntimeCapabilities } from "wire-core";
6
7
 
8
+ const docxType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
7
9
  const google = "application/vnd.google-apps.";
8
10
  const formats: Record<string, [string, string]> = {
9
11
  document: [".md", "text/markdown"],
@@ -12,7 +14,7 @@ const formats: Record<string, [string, string]> = {
12
14
  drawing: [".svg", "image/svg+xml"],
13
15
  };
14
16
  type File = { id: string; name: string; mimeType: string; version: string };
15
- type Entry = { id: string; path?: string; version?: string; hash?: string; noText?: true; markdownOnly?: true; images?: string[]; originalImages?: true };
17
+ type Entry = { id: string; path?: string; version?: string; hash?: string; noText?: true; markdownOnly?: true; images?: string[]; originalImages?: true; listMarkdown?: true };
16
18
  type State = { folder?: string; spreadsheet?: string; links?: Record<string, string[]>; entries: Record<string, Entry> };
17
19
  const digest = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
18
20
  async function stat(path: string) {
@@ -52,6 +54,11 @@ async function checkDocImage(folder: string, name: string) {
52
54
  return true;
53
55
  }
54
56
 
57
+ async function docLists(runtime: DriveRuntime, id: string, text: string) {
58
+ return googleDocListMarkdown(text, async () => new Uint8Array(await
59
+ (await drive(runtime, "/" + id + "/export", { mimeType: docxType })).arrayBuffer()));
60
+ }
61
+
55
62
  async function extractDocImages(runtime: DriveRuntime, id: string, full: string, text: string) {
56
63
  const labels = new Set([...text.matchAll(imageDefinition)].map(m => m[1]));
57
64
  const images = [...text.matchAll(imageUse)].filter(m => m[2] === undefined || labels.has(m[2]));
@@ -139,7 +146,10 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
139
146
  : item.mimeType === google + "presentation"
140
147
  ? "text/plain"
141
148
  : undefined;
142
- if (format) return (await drive(runtime, "/" + id + "/export", { mimeType: format })).text();
149
+ if (format) {
150
+ const text = await (await drive(runtime, "/" + id + "/export", { mimeType: format })).text();
151
+ return format === "text/markdown" ? docLists(runtime, id, text) : text;
152
+ }
143
153
  if (item.mimeType === "application/pdf" || /\.pdf$/i.test(item.name)) {
144
154
  const response = await drive(runtime, "/" + id, { alt: "media", supportsAllDrives: "true" });
145
155
  return (
@@ -147,25 +157,16 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
147
157
  item.name + ": image-only PDF (no text layer)."
148
158
  );
149
159
  }
160
+ if (item.mimeType === docxType || /\.docx$/i.test(item.name)) {
161
+ const response = await drive(runtime, "/" + id, { alt: "media", supportsAllDrives: "true" });
162
+ return (await import("./drive-docx.js")).docxMarkdown(new Uint8Array(await response.arrayBuffer()));
163
+ }
150
164
  if (item.mimeType.startsWith("text/"))
151
165
  return (await drive(runtime, "/" + id, { alt: "media", supportsAllDrives: "true" })).text();
152
166
  return "# " + item.name + "\n\n" + item.mimeType;
153
167
  }
154
168
 
155
- type SheetCell = {
156
- formattedValue?: string; hyperlink?: string; userEnteredValue?: { stringValue?: string; formulaValue?: string };
157
- textFormatRuns?: { format?: { link?: { uri?: string } } }[];
158
- userEnteredFormat?: { textFormat?: { link?: { uri?: string } } };
159
- chipRuns?: { chip?: { richLinkProperties?: { uri?: string } } }[];
160
- };
161
-
162
- async function sheetLinks(runtime: DriveRuntime, id: string) {
163
- const fields = "sheets(properties(title),data(startRow,startColumn,rowData(values(formattedValue,hyperlink,userEnteredValue,textFormatRuns(format/link),userEnteredFormat/textFormat/link,chipRuns(chip/richLinkProperties/uri)))))";
164
- const token = await runtime.googleFormsTokens.load();
165
- const response = await runtime.http.request("https://sheets.googleapis.com/v4/spreadsheets/" + encodeURIComponent(id) + "?" + new URLSearchParams({ fields }), { headers: { authorization: "Bearer " + token.token } });
166
- if (!response.ok) throw new Error("Sheets HTTP " + response.status + ": " + (await response.text()).slice(0, 600));
167
- type Sheet = { properties: { title: string }; data?: { startRow?: number; startColumn?: number; rowData?: { values?: SheetCell[] }[] }[] };
168
- const { sheets } = await response.json() as { sheets: Sheet[] };
169
+ function sheetLinks(sheets: Awaited<ReturnType<typeof readSheetTabs>>, id: string) {
169
170
  const links: Record<string, string[]> = Object.create(null);
170
171
  const labels = new Map<string, string>();
171
172
  for (const tab of sheets) for (const grid of tab.data ?? []) {
@@ -198,7 +199,7 @@ async function sheetLinks(runtime: DriveRuntime, id: string) {
198
199
  return { links, labels };
199
200
  }
200
201
 
201
- export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string, deleteVerifiedPdfs = false) {
202
+ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string, deleteVerifiedPdfs = false, deleteVerifiedDocx = false) {
202
203
  const sheet = url?.match(sheetUrl)?.[1], folder = url?.match(folderUrl)?.[1];
203
204
  if (url && !sheet && !folder) throw new Error("Expected a Google Drive folder or Google Sheets URL.");
204
205
  const metadata = async (id: string): Promise<File> => (await drive(runtime, "/" + encodeURIComponent(id), { fields: "id,name,mimeType,version", supportsAllDrives: "true" })).json();
@@ -223,18 +224,22 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
223
224
  root ??= await metadata(source);
224
225
  let downloaded = 0,
225
226
  unchanged = 0,
226
- removed = 0;
227
+ removed = 0, removedDocx = 0;
227
228
  const errors: string[] = [],
228
229
  skipped: string[] = [],
230
+ retainedDocx: string[] = [],
229
231
  images: string[] = [];
230
232
  const priorPaths = new Map(Object.values(state.entries).filter(e => e.path).map(e => [e.id, e.path!]));
231
233
  let labels = new Map<string, string>();
234
+ const rootTabs = state.spreadsheet ? await readSheetTabs(runtime, source) : undefined;
232
235
  async function visit(files: AsyncIterable<File> | Iterable<File>, dir: string) {
233
236
  for await (const f of files) {
234
237
  try {
235
238
  if (f.name.endsWith(".cannedSearch") || f.name === ".DS_Store") continue;
236
239
  const folder = f.mimeType === google + "folder",
237
- pdf = f.mimeType === "application/pdf" || /\.pdf$/i.test(f.name);
240
+ pdf = !f.mimeType.startsWith(google) && (f.mimeType === "application/pdf" || /\.pdf$/i.test(f.name)),
241
+ docx = !f.mimeType.startsWith(google) && (f.mimeType === docxType || /\.docx$/i.test(f.name)),
242
+ cleanup = (pdf && deleteVerifiedPdfs) || (docx && deleteVerifiedDocx);
238
243
  const format = formats[f.mimeType.slice(google.length)];
239
244
  if (!folder && !format && f.mimeType.startsWith(google)) {
240
245
  skipped.push(f.name);
@@ -244,12 +249,13 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
244
249
  const opaque = title === f.id || /^(?:[a-f\d]{24,}|[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12})$/i.test(title);
245
250
  const label = labels.get(f.id);
246
251
  const name = safeName(opaque && label ? label + (label.toLowerCase().endsWith(extension.toLowerCase()) ? "" : extension) : f.name);
247
- const suff = format?.[0] ?? (pdf && !/\.pdf$/i.test(name) ? ".pdf" : "");
252
+ const suff = format?.[0] ?? (pdf && !/\.pdf$/i.test(name) ? ".pdf" : docx && !/\.docx$/i.test(name) ? ".docx" : "");
248
253
  let path = join(dir, name + (name.endsWith(suff) ? "" : suff));
249
254
  // Existing scrapes keep their original sidecar paths.
250
- const markdownPath = () => state.entries[key(path + ".md")]?.id !== f.id && /\.pdf$/i.test(path)
251
- ? path.slice(0, -4) + ".md" : path + ".md";
252
- const paths = () => (pdf ? [path, markdownPath()] : [path]);
255
+ const spreadsheet = f.mimeType === google + "spreadsheet";
256
+ const markdownPath = () => state.entries[key(path + ".md")]?.id !== f.id && /\.(pdf|docx|xlsx)$/i.test(path)
257
+ ? path.slice(0, -extname(path).length) + ".md" : path + ".md";
258
+ const paths = () => (pdf || docx || spreadsheet ? [path, markdownPath()] : [path]);
253
259
  const key = (p: string) => "./" + p.normalize("NFC").toLowerCase();
254
260
  const occupied = async () => {
255
261
  for (const p of paths()) {
@@ -280,8 +286,9 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
280
286
  }
281
287
  const original = state.entries[key(path)];
282
288
  const removeVerified = async (bytes: Uint8Array, md: Buffer) => {
283
- const { verifiedPdf } = await import("./drive-pdf.js");
284
- if (!verifiedPdf(bytes, md.toString("utf8"))) return;
289
+ const verified = docx ? (await import("./drive-docx.js")).verifiedDocx(full, bytes, md.toString("utf8"))
290
+ : (await import("./drive-pdf.js")).verifiedPdf(bytes, md.toString("utf8"));
291
+ if (!verified) { if (docx) retainedDocx.push(path); return; }
285
292
  // Recheck both local files after verification, before removing the managed copy.
286
293
  for (const p of paths()) {
287
294
  const local = join(cwd, p);
@@ -290,7 +297,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
290
297
  }
291
298
  await unlink(full);
292
299
  state.entries[key(path)]!.markdownOnly = true;
293
- removed++;
300
+ if (docx) removedDocx++; else removed++;
294
301
  };
295
302
  let current = true;
296
303
  for (const p of paths()) {
@@ -303,6 +310,15 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
303
310
  if (!info || entry?.version !== f.version) current = false;
304
311
  }
305
312
  if (current && f.mimeType === google + "document") {
313
+ if (original && !original.listMarkdown) {
314
+ const old = await readFile(full, "utf8");
315
+ const normalized = await docLists(runtime, f.id, old);
316
+ if (old !== normalized) {
317
+ await save(full, normalized);
318
+ original.hash = digest(Buffer.from(normalized));
319
+ }
320
+ original.listMarkdown = true;
321
+ }
306
322
  if (original?.images?.length) {
307
323
  const dir = await docImageDir(full, false);
308
324
  for (const image of original.images) if (!(await checkDocImage(dir, image))) current = false;
@@ -320,7 +336,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
320
336
  }
321
337
  if (current) {
322
338
  if (state.entries[key(path)]?.noText) images.push(path);
323
- if (pdf && deleteVerifiedPdfs && !original?.noText && (await stat(full)))
339
+ if (cleanup && !original?.noText && (await stat(full)))
324
340
  await removeVerified(await readFile(full), await readFile(join(cwd, markdownPath())));
325
341
  original!.path = path;
326
342
  unchanged++;
@@ -330,13 +346,18 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
330
346
  ? await drive(runtime, "/" + f.id + "/export", { mimeType: format[1] })
331
347
  : await drive(runtime, "/" + f.id, { alt: "media", supportsAllDrives: "true" });
332
348
  const raw = new Uint8Array(await response.arrayBuffer());
333
- const doc = f.mimeType === google + "document" ? await extractDocImages(runtime, f.id, full, Buffer.from(raw).toString("utf8")) : undefined;
349
+ const doc = f.mimeType === google + "document" ? await extractDocImages(runtime, f.id, full, await docLists(runtime, f.id, Buffer.from(raw).toString("utf8"))) : undefined;
334
350
  const bytes = doc?.bytes ?? raw;
351
+ const table = spreadsheet ? Buffer.from(sheetMarkdown((f.id === source ? rootTabs : undefined) ?? await readSheetTabs(runtime, f.id))) : undefined;
335
352
  await save(full, bytes);
336
- state.entries[key(path)] = { id: f.id, path, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true } : {}) };
337
- if (pdf) {
338
- const { pdfMarkdown } = await import("./drive-pdf.js");
339
- const text = pdfMarkdown(bytes);
353
+ if (table) {
354
+ await save(join(cwd, markdownPath()), table);
355
+ state.entries[key(markdownPath())] = { id: f.id, version: f.version, hash: digest(table) };
356
+ }
357
+ state.entries[key(path)] = { id: f.id, path, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true, listMarkdown: true } : {}) };
358
+ if (pdf || docx) {
359
+ const text = docx ? await (await import("./drive-docx.js")).docxMarkdown(bytes)
360
+ : (await import("./drive-pdf.js")).pdfMarkdown(bytes);
340
361
  if (text === null) {
341
362
  state.entries[key(path)]!.noText = true;
342
363
  images.push(path);
@@ -347,7 +368,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
347
368
  const sidecar = markdownPath();
348
369
  await save(join(cwd, sidecar), md);
349
370
  state.entries[key(sidecar)] = { id: f.id, version: f.version, hash: digest(md) };
350
- if (deleteVerifiedPdfs) await removeVerified(bytes, md);
371
+ if (cleanup) await removeVerified(bytes, md);
351
372
  }
352
373
  downloaded++;
353
374
  } catch (e) {
@@ -358,7 +379,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
358
379
  try {
359
380
  if (state.spreadsheet) {
360
381
  await visit([root], "");
361
- const cells = await sheetLinks(runtime, source);
382
+ const cells = sheetLinks(rootTabs!, source);
362
383
  state.links = cells.links;
363
384
  labels = cells.labels;
364
385
  for (const [id, refs] of Object.entries(state.links)) {
@@ -379,6 +400,8 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
379
400
  unchanged +
380
401
  " unchanged." +
381
402
  (removed ? " Verified Markdown; removed " + removed + " local PDF copies." : "") +
403
+ (removedDocx ? " Verified Markdown; removed " + removedDocx + " local DOCX copies." : "") +
404
+ (retainedDocx.length ? "\nDOCX originals kept because Markdown verification was incomplete: " + retainedDocx.join(", ") : "") +
382
405
  (images.length ? "\nPDFs with no text layer (originals kept): " + images.join(", ") : "") +
383
406
  (skipped.length ? "\nUnsupported Drive items: " + skipped.join(", ") : "");
384
407
  if (errors.length) throw new Error(summary + "\n" + errors.join("\n"));
@@ -10,7 +10,7 @@ import { formatAgenda, type readAgenda } from "./calendar.js";
10
10
 
11
11
  export type WireRoot = Group;
12
12
  export type TextInputReader = () => Promise<string>;
13
- export type WireRootOptions = Readonly<{ allowPaste: boolean; ashby?: (action: string, arg?: string) => Promise<string>; previewDrive?: (url: string) => Promise<string>; scrapeDrive?: (url?: string, deleteVerifiedPdfs?: boolean) => Promise<string>; calendarAgenda?: (date?: string, calendarId?: string) => ReturnType<typeof readAgenda>; latticeSync?: (url: string | undefined, file?: string) => Promise<string>; latticeRequests?: (url: string) => Promise<string>; latticeTemplate?: (url: string) => Promise<string>; latticeFill?: (url: string, file: string) => Promise<string>; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
13
+ export type WireRootOptions = Readonly<{ allowPaste: boolean; ashby?: (action: string, arg?: string) => Promise<string>; previewDrive?: (url: string) => Promise<string>; scrapeDrive?: (url?: string, deleteVerifiedPdfs?: boolean, deleteVerifiedDocx?: boolean) => Promise<string>; calendarAgenda?: (date?: string, calendarId?: string) => ReturnType<typeof readAgenda>; latticeSync?: (url: string | undefined, file?: string) => Promise<string>; latticeRequests?: (url: string) => Promise<string>; latticeTemplate?: (url: string) => Promise<string>; latticeFill?: (url: string, file: string) => Promise<string>; scrapeZoom?: () => ReturnType<typeof zoomProvider.scrape> }>;
14
14
 
15
15
  const authServices = ["ashby", "asana", "chatgpt", "gmail", "google-docs", "notion", "slack", "zoom"] as const;
16
16
  const removedCliCommandNames = Object.freeze({
@@ -608,8 +608,8 @@ export function createRoot(wire: Wire, currentDirectory: string, auth?: Auth, re
608
608
  handler: ({ params }) => userFacing(() => options.previewDrive!(params.url)), render: render<string>(v => v),
609
609
  })] : []),
610
610
  defineCommand({ name: "scrape", description: "Download a folder, or a spreadsheet and its linked Drive files, into its own directory. Run there without a URL to refresh.", scope: ["cli"], positional: ["url"],
611
- params: S.Object({ url: S.Optional(S.String({ description: "Google Drive folder or Google Sheets URL." })), "delete-verified-pdfs": S.Optional(S.Boolean({ description: "Remove local PDFs only after verifying their Markdown independently. Originals are kept by default." })) }),
612
- handler: ({ params }) => userFacing(() => options.scrapeDrive!(params.url, params["delete-verified-pdfs"])), render: render<string>(v => v),
611
+ params: S.Object({ url: S.Optional(S.String({ description: "Google Drive folder or Google Sheets URL." })), "delete-verified-docx": S.Optional(S.Boolean({ description: "Remove local DOCX files only after independently verifying their Markdown." })), "delete-verified-pdfs": S.Optional(S.Boolean({ description: "Remove local PDFs only after verifying their Markdown independently. Originals are kept by default." })) }),
612
+ handler: ({ params }) => userFacing(() => options.scrapeDrive!(params.url, params["delete-verified-pdfs"], params["delete-verified-docx"])), render: render<string>(v => v),
613
613
  }),
614
614
  ] })] : []),
615
615
  ...(options.calendarAgenda ? [defineGroup({ name: "google-calendar", description: "Read Google Calendar.", scope: ["cli"], children: [
@@ -0,0 +1,89 @@
1
+ import type { RuntimeCapabilities } from "wire-core";
2
+
3
+ type Cell = {
4
+ formattedValue?: string; hyperlink?: string;
5
+ userEnteredValue?: { stringValue?: string; formulaValue?: string };
6
+ textFormatRuns?: { startIndex?: number; format?: { link?: { uri?: string } } }[];
7
+ userEnteredFormat?: { textFormat?: { link?: { uri?: string } } };
8
+ chipRuns?: { startIndex?: number; chip?: { richLinkProperties?: { uri?: string } } }[];
9
+ };
10
+ type Tab = { properties: { title: string }; data?: { startRow?: number; startColumn?: number; rowData?: { values?: Cell[] }[] }[] };
11
+
12
+ export async function readSheetTabs(runtime: Pick<RuntimeCapabilities, "googleFormsTokens" | "http">, id: string): Promise<Tab[]> {
13
+ const fields = "sheets(properties(title),data(startRow,startColumn,rowData(values(formattedValue,hyperlink,userEnteredValue,textFormatRuns(startIndex,format/link),userEnteredFormat/textFormat/link,chipRuns(startIndex,chip/richLinkProperties/uri)))))";
14
+ const token = await runtime.googleFormsTokens.load();
15
+ const response = await runtime.http.request("https://sheets.googleapis.com/v4/spreadsheets/" + encodeURIComponent(id) + "?" + new URLSearchParams({ fields }), { headers: { authorization: "Bearer " + token.token } });
16
+ if (!response.ok) throw new Error("Sheets HTTP " + response.status + ": " + (await response.text()).slice(0, 600));
17
+ const { sheets } = await response.json() as { sheets: Tab[] };
18
+ return sheets;
19
+ }
20
+
21
+ const literal = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
22
+ .replace(/([\\*`_~\[\]])/g, "\\$1").replace(/\|/g, "&#124;").replace(/\r\n?|\n/g, "<br>");
23
+ function linked(label: string, url?: string) {
24
+ if (!url || !/^(?:https?:\/\/|mailto:|#)/i.test(url)) return literal(label);
25
+ const target = url.replace(/[\s<>|()\\]/g, c => encodeURIComponent(c).replace("(", "%28").replace(")", "%29"));
26
+ return "[" + literal(label) + "](" + target + ")";
27
+ }
28
+ function cellText(cell: Cell) {
29
+ const text = cell.formattedValue ?? cell.userEnteredValue?.stringValue ?? "";
30
+ if (!text) return "";
31
+ const fullLink = cell.hyperlink ?? cell.userEnteredFormat?.textFormat?.link?.uri;
32
+ const formulaLink = /^=HYPERLINK\(\s*"([^"]+)"/i.exec(cell.userEnteredValue?.formulaValue ?? "")?.[1];
33
+ const entered = cell.userEnteredValue?.stringValue;
34
+ const chips = (cell.chipRuns ?? []).filter(r => r.chip?.richLinkProperties?.uri);
35
+ if (chips.length && entered === text) {
36
+ // Some older Sheets use chip start/end runs over the full displayed title.
37
+ const runs = cell.chipRuns!;
38
+ let result = literal(text.slice(0, runs[0]?.startIndex ?? 0));
39
+ for (const [i, run] of runs.entries()) result += linked(text.slice(run.startIndex ?? 0, runs[i + 1]?.startIndex ?? text.length), run.chip?.richLinkProperties?.uri);
40
+ return result;
41
+ }
42
+ if (chips.length && entered !== undefined) {
43
+ // Chips occupy one @ in the raw string but expand to a title in the displayed value.
44
+ // Use the text between chips as boundaries; preserve the display text on ambiguity.
45
+ let rawAt = 0, displayAt = 0, result = "";
46
+ for (const [i, chip] of chips.entries()) {
47
+ const at = chip.startIndex ?? 0, prefix = entered.slice(rawAt, at), nextAt = chips[i + 1]?.startIndex ?? entered.length;
48
+ const suffix = entered.slice(at + 1, nextAt);
49
+ if (entered[at] !== "@" || !text.startsWith(prefix, displayAt) || (!suffix && i + 1 < chips.length)) break;
50
+ displayAt += prefix.length;
51
+ const end = i + 1 === chips.length ? text.length - suffix.length : text.indexOf(suffix, displayAt);
52
+ if (end < displayAt || !text.startsWith(suffix, end)) break;
53
+ result += literal(prefix) + linked(text.slice(displayAt, end), chip.chip?.richLinkProperties?.uri);
54
+ displayAt = end; rawAt = at + 1;
55
+ if (i + 1 === chips.length) return result + literal(suffix);
56
+ }
57
+ }
58
+ const runs = cell.textFormatRuns ?? [];
59
+ if (runs.some(r => r.format?.link?.uri)) {
60
+ let result = linked(text.slice(0, runs[0]?.startIndex ?? 0), fullLink);
61
+ for (const [i, run] of runs.entries()) result += linked(text.slice(run.startIndex ?? 0, runs[i + 1]?.startIndex ?? text.length), run.format?.link?.uri ?? cell.userEnteredFormat?.textFormat?.link?.uri);
62
+ return result;
63
+ }
64
+ return linked(text, fullLink ?? formulaLink ?? (chips.length === 1 ? chips[0]?.chip?.richLinkProperties?.uri : undefined));
65
+ }
66
+
67
+ export function sheetMarkdown(tabs: Tab[]) {
68
+ const blocks: string[] = [];
69
+ for (const tab of tabs) {
70
+ const rows: string[][] = [];
71
+ let width = 1;
72
+ for (const grid of tab.data ?? []) {
73
+ for (const [r, row] of (grid.rowData ?? []).entries()) for (const [c, cell] of (row.values ?? []).entries()) {
74
+ const value = cellText(cell);
75
+ if (!value && !cell.userEnteredValue?.formulaValue) continue;
76
+ const col = c + (grid.startColumn ?? 0);
77
+ (rows[r + (grid.startRow ?? 0)] ??= [])[col] = value;
78
+ width = Math.max(width, col + 1);
79
+ }
80
+ }
81
+ const lines = ["## " + literal(tab.properties.title), ""];
82
+ for (let r = 0; r < Math.max(1, rows.length); r++) {
83
+ lines.push("| " + Array.from({ length: width }, (_, c) => rows[r]?.[c] ?? "").join(" | ") + " |");
84
+ if (!r) lines.push("| " + Array(width).fill("---").join(" | ") + " |");
85
+ }
86
+ blocks.push(lines.join("\n"));
87
+ }
88
+ return blocks.join("\n\n") + "\n";
89
+ }
package/src/executable.ts CHANGED
@@ -141,7 +141,7 @@ export function createExecutableRoot(environment: NodeEnvironment, currentDirect
141
141
  switchBackend: baseWire.switchBackend,
142
142
  });
143
143
  const wire = withWireHooks(configuredWire, { currentDirectory, home, environment: configuredEnvironment() });
144
- return createRoot(wire, currentDirectory, auth, readStandardInput, { ...options, ashby: (action,arg) => ashby(runtime,action,action === "sync" ? resolve(currentDirectory,arg!) : arg), previewDrive: url => previewDrive(runtime,url), scrapeDrive: (url, deleteVerifiedPdfs) => scrapeDrive(runtime, currentDirectory, url, deleteVerifiedPdfs), calendarAgenda: (date, id) => readAgenda(processCapability, configuration.get("WIRE_REPOSITORY_ROOT"), date, id), latticeSync: (url,file) => syncLatticeDrafts(runtime,url,currentDirectory,file), latticeRequests: url => listLatticeReviewRequests(runtime,url), latticeTemplate: url => latticeReviewDraft(runtime,url), latticeFill: async (url,file) => latticeReviewDraft(runtime,url,await runtime.filesystem.readText(resolve(currentDirectory,file))), scrapeZoom: () => zoomProvider.scrape(runtime, currentDirectory) }, (destination, markdown) => sendSlackMessage(runtime, destination, markdown), (query) => lookupSlackUsers(runtime, query), (url, markdown) => editSlackMessage(runtime, url, markdown), (query) => lookupNotionUsers(runtime, query), {
144
+ return createRoot(wire, currentDirectory, auth, readStandardInput, { ...options, ashby: (action,arg) => ashby(runtime,action,action === "sync" ? resolve(currentDirectory,arg!) : arg), previewDrive: url => previewDrive(runtime,url), scrapeDrive: (url, deleteVerifiedPdfs, deleteVerifiedDocx) => scrapeDrive(runtime, currentDirectory, url, deleteVerifiedPdfs, deleteVerifiedDocx), calendarAgenda: (date, id) => readAgenda(processCapability, configuration.get("WIRE_REPOSITORY_ROOT"), date, id), latticeSync: (url,file) => syncLatticeDrafts(runtime,url,currentDirectory,file), latticeRequests: url => listLatticeReviewRequests(runtime,url), latticeTemplate: url => latticeReviewDraft(runtime,url), latticeFill: async (url,file) => latticeReviewDraft(runtime,url,await runtime.filesystem.readText(resolve(currentDirectory,file))), scrapeZoom: () => zoomProvider.scrape(runtime, currentDirectory) }, (destination, markdown) => sendSlackMessage(runtime, destination, markdown), (query) => lookupSlackUsers(runtime, query), (url, markdown) => editSlackMessage(runtime, url, markdown), (query) => lookupNotionUsers(runtime, query), {
145
145
  lookup: (query) => lookupAsanaUsers(runtime, query), projects: () => listAsanaProjects(runtime), project: (project) => showAsanaProject(runtime, project), tasks: (project) => listAsanaTasks(runtime, project), show: (task) => showAsanaTask(runtime, task),
146
146
  writes: { move: (task, project, section) => moveAsanaTask(runtime, task, project, section), create: (project, title, section, body, assignee) => createAsanaTask(runtime, project, title, section, body, assignee), edit: (task, fields) => editAsanaTask(runtime, task, fields), comment: (task, body) => addAsanaComment(runtime, task, body), editComment: (comment, body) => editAsanaComment(runtime, comment, body) },
147
147
  }, async () => {