@kamilio/wire 0.1.40 → 0.1.42

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,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { lstat, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
3
  import { basename, dirname, extname, join } from "node:path";
4
+ import { googleDocOriginalImages } from "provider-google-docs";
4
5
  import type { RuntimeCapabilities } from "wire-core";
5
6
 
6
7
  const google = "application/vnd.google-apps.";
@@ -11,8 +12,8 @@ const formats: Record<string, [string, string]> = {
11
12
  drawing: [".svg", "image/svg+xml"],
12
13
  };
13
14
  type File = { id: string; name: string; mimeType: string; version: string };
14
- type Entry = { id: string; version?: string; hash?: string; noText?: true; markdownOnly?: true; images?: string[] };
15
- type State = { folder: string; entries: Record<string, Entry> };
15
+ type Entry = { id: string; path?: string; version?: string; hash?: string; noText?: true; markdownOnly?: true; images?: string[]; originalImages?: true };
16
+ type State = { folder?: string; spreadsheet?: string; links?: Record<string, string[]>; entries: Record<string, Entry> };
16
17
  const digest = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
17
18
  async function stat(path: string) {
18
19
  try {
@@ -29,7 +30,7 @@ async function save(path: string, data: string | Uint8Array) {
29
30
 
30
31
  const imageData = /data:image\/(png|jpeg|gif|webp);base64,([a-zA-Z0-9+/]+=*)/;
31
32
  const imageDefinition = new RegExp("^\\[(image\\d+)\\]:[ \\t]*<?(" + imageData.source + ")>?[ \\t]*\\r?$", "gm");
32
- const inlineImage = new RegExp("(!\\[(?:\\\\.|[^\\]\\\\\\n])*\\])\\(<?(" + imageData.source + ")>?\\)", "g");
33
+ const imageUse = new RegExp("(!\\[(?:\\\\.|[^\\]\\\\\\n])*\\])(?:\\[(image\\d+)\\]|\\(<?" + imageData.source + ">?\\))", "g");
33
34
 
34
35
  async function docImageDir(full: string, create: boolean) {
35
36
  const root = join(dirname(full), "attachments"), folder = join(root, basename(full, ".md"));
@@ -51,36 +52,40 @@ async function checkDocImage(folder: string, name: string) {
51
52
  return true;
52
53
  }
53
54
 
54
- async function extractDocImages(full: string, text: string) {
55
- const files = new Map<string, Buffer>(), links = new Map<string, string>();
56
- const link = (ext: string, base64: string) => {
57
- const data = Buffer.from(base64, "base64");
58
- if (data.toString("base64") !== base64) throw new Error("Invalid image encoding.");
59
- const name = digest(data) + "." + ext;
55
+ async function extractDocImages(runtime: DriveRuntime, id: string, full: string, text: string) {
56
+ const labels = new Set([...text.matchAll(imageDefinition)].map(m => m[1]));
57
+ const images = [...text.matchAll(imageUse)].filter(m => m[2] === undefined || labels.has(m[2]));
58
+ if (!images.length) return { bytes: Buffer.from(text), images: [] };
59
+ const response = await drive(runtime, "/" + id + "/export", { mimeType: "application/zip" });
60
+ const originals = googleDocOriginalImages(new Uint8Array(await response.arrayBuffer()));
61
+ if (images.length !== originals.length) throw new Error("Image count differs between Google Docs Markdown and HTML exports; kept local copy.");
62
+ const files = new Map<string, Uint8Array>(), links = new Map<string, string>();
63
+ const dir = encodeURIComponent(basename(full, ".md")).replace(/[()]/g, c => c === "(" ? "%28" : "%29");
64
+ let index = 0;
65
+ text = text.replace(imageUse, (all, alt, label) => {
66
+ if (label !== undefined && !labels.has(label)) return all;
67
+ const { data, ext } = originals[index++]!;
68
+ const name = digest(data) + "." + ext, url = "attachments/" + dir + "/" + name;
60
69
  files.set(name, data);
61
- return "attachments/" + encodeURIComponent(basename(full, ".md")).replace(/[()]/g, c => c === "(" ? "%28" : "%29") + "/" + name;
62
- };
63
- for (const m of text.matchAll(imageDefinition)) links.set(m[1]!, link(m[3]!, m[4]!));
64
- text = text.replace(inlineImage, (_, alt, _uri, ext, data) => alt + "(" + link(ext, data) + ")");
65
- if (links.size) {
66
- text = text.replace(/(!\[(?:\\.|[^\]\\\n])*\])\[(image\d+)\]/g, (all, alt, id) =>
67
- links.has(id) ? alt + "(" + links.get(id) + ")" : all);
68
- // Keep a relative definition for ordinary links that use the same reference.
69
- text = text.replace(imageDefinition, (line, id, _uri, _ext, _data, offset) =>
70
- (text.slice(0, offset) + text.slice(offset + line.length)).includes("[" + id + "]")
71
- ? "[" + id + "]: <" + links.get(id) + ">" : "");
72
- }
73
- if (files.size) {
74
- const folder = await docImageDir(full, true);
75
- for (const [name, data] of files) {
76
- if (!(await checkDocImage(folder, name))) await writeFile(join(folder, name), data, { flag: "wx", mode: 0o600 });
77
- }
70
+ if (label) links.set(label, url);
71
+ return alt + "(" + url + ")";
72
+ });
73
+ text = text.replace(imageDefinition, (line, label, _uri, _ext, _data, offset) => {
74
+ const url = links.get(label);
75
+ if (!url) return line;
76
+ return (text.slice(0, offset) + text.slice(offset + line.length)).includes("[" + label + "]")
77
+ ? "[" + label + "]: <" + url + ">" : "";
78
+ });
79
+ const folder = await docImageDir(full, true);
80
+ for (const [name, data] of files) {
81
+ if (!(await checkDocImage(folder, name))) await writeFile(join(folder, name), data, { flag: "wx", mode: 0o600 });
78
82
  }
79
83
  return { bytes: Buffer.from(text), images: [...files.keys()] };
80
84
  }
81
85
 
82
86
  type DriveRuntime = Pick<RuntimeCapabilities, "googleFormsTokens" | "http">;
83
87
  const folderUrl = /^https:\/\/drive\.google\.com\/drive\/(?:u\/\d+\/)?folders\/([\w-]+)\/?(?:[?#].*)?$/;
88
+ const sheetUrl = /^https:\/\/docs\.google\.com\/spreadsheets\/(?:u\/\d+\/)?d\/([\w-]+)(?:[/?#].*)?$/;
84
89
  const safeName = (name: string) => name.replace(/[/\\:\x00-\x1f]/g, "_").replace(/^\.+/, "_") || "_";
85
90
  async function drive(runtime: DriveRuntime, path: string, params: Record<string, string>) {
86
91
  const token = await runtime.googleFormsTokens.load();
@@ -147,12 +152,60 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
147
152
  return "# " + item.name + "\n\n" + item.mimeType;
148
153
  }
149
154
 
150
- export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string) {
151
- const match = url?.match(folderUrl);
152
- if (url && !match) throw new Error("Expected a Google Drive folder URL.");
153
- if (match) {
154
- const root = await (await drive(runtime, "/" + match[1], { fields: "name,mimeType", supportsAllDrives: "true" })).json();
155
- if (root.mimeType !== google + "folder") throw new Error("The URL must identify a Drive folder.");
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
+ const links: Record<string, string[]> = Object.create(null);
170
+ const labels = new Map<string, string>();
171
+ for (const tab of sheets) for (const grid of tab.data ?? []) {
172
+ for (const [r, row] of (grid.rowData ?? []).entries()) for (const [c, cell] of (row.values ?? []).entries()) {
173
+ const texts = [cell.hyperlink, cell.formattedValue, cell.userEnteredValue?.stringValue, cell.userEnteredValue?.formulaValue,
174
+ cell.userEnteredFormat?.textFormat?.link?.uri,
175
+ ...(cell.textFormatRuns ?? []).map(run => run.format?.link?.uri),
176
+ ...(cell.chipRuns ?? []).map(run => run.chip?.richLinkProperties?.uri)];
177
+ const targets = new Set<string>();
178
+ for (const text of texts) for (const m of (text ?? "").matchAll(/https?:\/\/[^\s"'<>]+/gi)) {
179
+ let url: URL;
180
+ try { url = new URL(m[0]); } catch { continue; }
181
+ if (url.hostname !== "docs.google.com" && url.hostname !== "drive.google.com") continue;
182
+ const target = /\/(?:d|folders)\/([\w-]+)(?:\/|$)/.exec(url.pathname)?.[1] ?? url.searchParams.get("id");
183
+ if (!target || !/^[\w-]+$/.test(target) || target === id) continue;
184
+ targets.add(target);
185
+ let n = c + (grid.startColumn ?? 0) + 1, col = "";
186
+ while (n) { n--; col = String.fromCharCode(65 + n % 26) + col; n = Math.floor(n / 26); }
187
+ const ref = tab.properties.title + "!" + col + (r + (grid.startRow ?? 0) + 1);
188
+ const refs = links[target] ??= [];
189
+ if (!refs.includes(ref)) refs.push(ref);
190
+ }
191
+ const label = cell.formattedValue?.trim();
192
+ if (targets.size === 1 && label && label.length <= 120 && !/https?:\/\//i.test(label)) {
193
+ const [target] = targets;
194
+ if (!labels.has(target!)) labels.set(target!, label);
195
+ }
196
+ }
197
+ }
198
+ return { links, labels };
199
+ }
200
+
201
+ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: string, deleteVerifiedPdfs = false) {
202
+ const sheet = url?.match(sheetUrl)?.[1], folder = url?.match(folderUrl)?.[1];
203
+ if (url && !sheet && !folder) throw new Error("Expected a Google Drive folder or Google Sheets URL.");
204
+ const metadata = async (id: string): Promise<File> => (await drive(runtime, "/" + encodeURIComponent(id), { fields: "id,name,mimeType,version", supportsAllDrives: "true" })).json();
205
+ let root: File | undefined;
206
+ if (sheet || folder) {
207
+ root = await metadata((sheet ?? folder)!);
208
+ if (root.mimeType !== google + (sheet ? "spreadsheet" : "folder")) throw new Error("Drive file type does not match the URL.");
156
209
  const name = safeName(root.name);
157
210
  if (basename(cwd) !== name) {
158
211
  cwd = join(cwd, name);
@@ -163,18 +216,21 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
163
216
  const manifest = join(cwd, ".wire-gdrive.json");
164
217
  const state: State = (await stat(manifest))?.isFile()
165
218
  ? JSON.parse(await readFile(manifest, "utf8"))
166
- : { folder: match?.[1], entries: {} };
167
- if (!state.folder) throw new Error("Pass a Drive folder URL on the first scrape.");
168
- if (!match) await drive(runtime, "/" + encodeURIComponent(state.folder), { fields: "id", supportsAllDrives: "true" });
169
- if (match && state.folder !== match[1]) throw new Error("This directory tracks a different Drive folder.");
219
+ : { ...(sheet ? { spreadsheet: sheet } : { folder }), entries: {} };
220
+ const source = state.spreadsheet ?? state.folder;
221
+ if (!source) throw new Error("Pass a Drive folder or Google Sheets URL on the first scrape.");
222
+ if ((sheet && sheet !== state.spreadsheet) || (folder && folder !== state.folder)) throw new Error("This directory tracks a different Drive source.");
223
+ root ??= await metadata(source);
170
224
  let downloaded = 0,
171
225
  unchanged = 0,
172
226
  removed = 0;
173
227
  const errors: string[] = [],
174
228
  skipped: string[] = [],
175
229
  images: string[] = [];
176
- async function visit(parent: string, dir: string) {
177
- for await (const f of children(runtime, parent)) {
230
+ const priorPaths = new Map(Object.values(state.entries).filter(e => e.path).map(e => [e.id, e.path!]));
231
+ let labels = new Map<string, string>();
232
+ async function visit(files: AsyncIterable<File> | Iterable<File>, dir: string) {
233
+ for await (const f of files) {
178
234
  try {
179
235
  if (f.name.endsWith(".cannedSearch") || f.name === ".DS_Store") continue;
180
236
  const folder = f.mimeType === google + "folder",
@@ -184,10 +240,16 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
184
240
  skipped.push(f.name);
185
241
  continue;
186
242
  }
187
- const name = safeName(f.name);
188
- const suff = format?.[0] ?? "";
243
+ const extension = extname(f.name), title = basename(f.name, extension);
244
+ 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
+ const label = labels.get(f.id);
246
+ 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" : "");
189
248
  let path = join(dir, name + (name.endsWith(suff) ? "" : suff));
190
- const paths = () => (pdf ? [path, path + ".md"] : [path]);
249
+ // 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]);
191
253
  const key = (p: string) => "./" + p.normalize("NFC").toLowerCase();
192
254
  const occupied = async () => {
193
255
  for (const p of paths()) {
@@ -196,17 +258,24 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
196
258
  }
197
259
  return false;
198
260
  };
199
- if (await occupied()) {
200
- const ext = extname(path);
201
- path = (ext ? path.slice(0, -ext.length) : path) + " (" + f.id + ")" + ext;
202
- if (await occupied()) throw new Error("Destination name is already in use.");
261
+ const base = path, ext = extname(base), stem = base.slice(0, base.length - ext.length);
262
+ const prior = priorPaths.get(f.id);
263
+ const oldName = safeName(f.name), oldExt = format?.[0] ?? "";
264
+ const oldBase = join(dir, oldName + (oldName.endsWith(oldExt) ? "" : oldExt));
265
+ const oldSuffix = extname(oldBase);
266
+ const legacy = [oldBase, oldBase.slice(0, oldBase.length - oldSuffix.length) + " (" + f.id + ")" + oldSuffix];
267
+ const saved = prior && dirname(prior) === dirname(base) ? prior : legacy.find(p => state.entries[key(p)]?.id === f.id);
268
+ if (saved) path = saved;
269
+ for (let n = 2; await occupied(); n++) {
270
+ if (saved) throw new Error("Destination name is already in use.");
271
+ path = stem + " (" + n + ")" + ext;
203
272
  }
204
273
  const full = join(cwd, path);
205
274
  if (folder) {
206
275
  if (!(await stat(full))) await mkdir(full, { mode: 0o700 });
207
276
  if (!(await lstat(full)).isDirectory()) throw new Error("Expected a local directory.");
208
- state.entries[key(path)] = { id: f.id };
209
- await visit(f.id, path);
277
+ state.entries[key(path)] = { id: f.id, path };
278
+ await visit(children(runtime, f.id), path);
210
279
  continue;
211
280
  }
212
281
  const original = state.entries[key(path)];
@@ -237,20 +306,23 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
237
306
  if (original?.images?.length) {
238
307
  const dir = await docImageDir(full, false);
239
308
  for (const image of original.images) if (!(await checkDocImage(dir, image))) current = false;
309
+ if (!original.originalImages) current = false;
240
310
  } else if (!original?.images) {
241
- // Upgrade prior exports on refresh, without another network request.
242
- const local = await extractDocImages(full, await readFile(full, "utf8"));
311
+ // Upgrade prior exports using their Markdown and the original HTML media.
312
+ const local = await extractDocImages(runtime, f.id, full, await readFile(full, "utf8"));
243
313
  if (local.images.length) {
244
314
  await save(full, local.bytes);
245
315
  original!.hash = digest(local.bytes);
246
316
  }
247
317
  original!.images = local.images;
318
+ original!.originalImages = true;
248
319
  }
249
320
  }
250
321
  if (current) {
251
322
  if (state.entries[key(path)]?.noText) images.push(path);
252
- if (pdf && !original?.noText && (await stat(full)))
253
- await removeVerified(await readFile(full), await readFile(full + ".md"));
323
+ if (pdf && deleteVerifiedPdfs && !original?.noText && (await stat(full)))
324
+ await removeVerified(await readFile(full), await readFile(join(cwd, markdownPath())));
325
+ original!.path = path;
254
326
  unchanged++;
255
327
  continue;
256
328
  }
@@ -258,10 +330,10 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
258
330
  ? await drive(runtime, "/" + f.id + "/export", { mimeType: format[1] })
259
331
  : await drive(runtime, "/" + f.id, { alt: "media", supportsAllDrives: "true" });
260
332
  const raw = new Uint8Array(await response.arrayBuffer());
261
- const doc = f.mimeType === google + "document" ? await extractDocImages(full, Buffer.from(raw).toString("utf8")) : undefined;
333
+ const doc = f.mimeType === google + "document" ? await extractDocImages(runtime, f.id, full, Buffer.from(raw).toString("utf8")) : undefined;
262
334
  const bytes = doc?.bytes ?? raw;
263
335
  await save(full, bytes);
264
- state.entries[key(path)] = { id: f.id, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images } : {}) };
336
+ state.entries[key(path)] = { id: f.id, path, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true } : {}) };
265
337
  if (pdf) {
266
338
  const { pdfMarkdown } = await import("./drive-pdf.js");
267
339
  const text = pdfMarkdown(bytes);
@@ -272,9 +344,10 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
272
344
  continue;
273
345
  }
274
346
  const md = Buffer.from(text);
275
- await save(full + ".md", md);
276
- state.entries[key(path + ".md")] = { id: f.id, version: f.version, hash: digest(md) };
277
- await removeVerified(bytes, md);
347
+ const sidecar = markdownPath();
348
+ await save(join(cwd, sidecar), md);
349
+ state.entries[key(sidecar)] = { id: f.id, version: f.version, hash: digest(md) };
350
+ if (deleteVerifiedPdfs) await removeVerified(bytes, md);
278
351
  }
279
352
  downloaded++;
280
353
  } catch (e) {
@@ -283,7 +356,19 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
283
356
  }
284
357
  }
285
358
  try {
286
- await visit(state.folder, "");
359
+ if (state.spreadsheet) {
360
+ await visit([root], "");
361
+ const cells = await sheetLinks(runtime, source);
362
+ state.links = cells.links;
363
+ labels = cells.labels;
364
+ for (const [id, refs] of Object.entries(state.links)) {
365
+ try {
366
+ const file = await metadata(id);
367
+ if (file.mimeType === google + "folder") skipped.push(file.name + " (linked folder)");
368
+ else await visit([file], "");
369
+ } catch (e) { errors.push(refs.join(", ") + " (" + id + "): " + (e as Error).message); }
370
+ }
371
+ } else await visit(children(runtime, source), "");
287
372
  } finally {
288
373
  await save(manifest, JSON.stringify(state, null, 2) + "\n");
289
374
  }
@@ -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) => 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) => 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({
@@ -602,14 +602,14 @@ export function createRoot(wire: Wire, currentDirectory: string, auth?: Auth, re
602
602
  scope: ["cli", "mcp", "sdk"],
603
603
  children: [
604
604
  defaultAttach,
605
- ...(options.scrapeDrive ? [defineGroup({ name: "gdrive", description: "Download Google Drive folders.", scope: ["cli"], children: [
605
+ ...(options.scrapeDrive ? [defineGroup({ name: "gdrive", description: "Download Google Drive folders and spreadsheets.", scope: ["cli"], children: [
606
606
  ...(options.previewDrive ? [defineCommand({ name: "preview", description: "List a Drive folder or read a file without saving it.", scope: ["cli"], positional: ["url"],
607
607
  params: S.Object({ url: S.String({description: "Google Drive folder or file URL."}) }),
608
608
  handler: ({ params }) => userFacing(() => options.previewDrive!(params.url)), render: render<string>(v => v),
609
609
  })] : []),
610
- defineCommand({ name: "scrape", description: "Download into a directory named after the Drive folder. Run there without a URL to refresh.", scope: ["cli"], positional: ["url"],
611
- params: S.Object({ url: S.Optional(S.String({ description: "Google Drive folder URL." })) }),
612
- handler: ({ params }) => userFacing(() => options.scrapeDrive!(params.url)), render: render<string>(v => v),
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),
613
613
  }),
614
614
  ] })] : []),
615
615
  ...(options.calendarAgenda ? [defineGroup({ name: "google-calendar", description: "Read Google Calendar.", scope: ["cli"], children: [
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 => scrapeDrive(runtime, currentDirectory, url), 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) => 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), {
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 () => {
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export * from "provider-asana";
3
3
  export * from "provider-notion";
4
4
  export * from "provider-chatgpt";
5
5
  export * from "provider-gmail";
6
- export * from "provider-google-docs";
6
+ export { googleDocsProvider, googleDocsService, googleFormsService } from "provider-google-docs";
7
7
  export * from "provider-slack";
8
8
  export * from "provider-zoom";
9
9
  export { composeAuth } from "./auth.js";