@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,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
 
4
+ import { stableJsonCompact } from "./core/json.js";
4
5
  import { extractRelationships, markdownFilename } from "./core/transform.js";
5
- import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog } from "./core/model.js";
6
+ import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog, Source } from "./core/model.js";
6
7
  import { resourceId } from "./core/resource.js";
7
8
  import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
8
9
  import type { InitializedWire, SwitchedWireBackend, WatchCapability, WatchHandle, WireBackend, WireConfig, WireWatchConfig, WireWorkspace } from "./ports.js";
@@ -139,9 +140,28 @@ function changeSummary(before: string, after: string) {
139
140
  return { added: added - modified, removed: removed - modified, modified };
140
141
  }
141
142
 
142
- async function existingResource(registry: Registry, service: string, identifier: string): Promise<Resource | null> {
143
- const resources = await registry.listResources();
144
- return resources.find((resource) => resource.identifiers.some((item) => item.service === service && item.identifier === identifier)) ?? null;
143
+ function legacyDefaultTab<FetchInput>(resource: Resource, catalog: ServiceCatalog<FetchInput>): Source | null {
144
+ if (resource.type !== "document" || !resource.id.startsWith("google-docs:") || resource.id.includes("#tab=")) return null;
145
+ for (const url of resource.urls) {
146
+ const parsed = new URL(url);
147
+ const service = catalog.find((item) => item.name === "google-docs" && item.matches(parsed));
148
+ const source = service?.parse(parsed);
149
+ if (source && source["document_tab"] === "t.0" && resource.id === `google-docs:${source["document_id"]}`) return source;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ function findResource<FetchInput>(resources: readonly Resource[], source: Source, catalog: ServiceCatalog<FetchInput>): Resource | null {
155
+ const current = resources.find((item) => item.identifiers.some((identifier) => identifier.service === source.service && identifier.identifier === source.identifier));
156
+ if (source.service !== "google-docs" || source.type !== "document") return current ?? null;
157
+ if (current && legacyDefaultTab(current, catalog) && !source["document_tab"]) throw new Error(`The existing file ${primaryLink(current).path} is registered to the explicit default tab. Sync that path before attaching the whole document.`);
158
+ if (source["document_tab"] !== "t.0") return current ?? null;
159
+ const legacy = resources.find((item) => item.id === `google-docs:${source["document_id"]}` && legacyDefaultTab(item, catalog) !== null);
160
+ if (!legacy) return current ?? null;
161
+ if (current && stableJsonCompact({ ...legacy, id: resourceId(source), identifiers: [{ service: source.service, identifier: source.identifier }] }) !== stableJsonCompact(current)) {
162
+ throw new Error(`Two Wire records point to the default tab: ${primaryLink(legacy).path} and ${primaryLink(current).path}. Back up both files and reconcile them before detaching the duplicate by its resource ID (${current.id}). No files were changed.`);
163
+ }
164
+ return legacy;
145
165
  }
146
166
 
147
167
  function jsonObject(value: JsonValue): value is JsonObject {
@@ -191,11 +211,12 @@ function errorMessage(error: unknown): string {
191
211
  }
192
212
 
193
213
  export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInput>): Wire {
194
- const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string): Promise<WireResult> => {
214
+ const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null | undefined, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string): Promise<WireResult> => {
195
215
  const source = parseSourceUrl(url, dependencies.catalog);
196
216
  const root = await wireRoot(dependencies, path);
197
217
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
198
- const current = await existingResource(registry, source.service, source.identifier);
218
+ const current = findResource(await registry.listResources(), source, dependencies.catalog);
219
+ if (current && legacyDefaultTab(current, dependencies.catalog)) throw new Error(`Sync ${primaryLink(current).path} first to migrate its default-tab registration.`);
199
220
  let outputPath: string;
200
221
  if (current !== null) outputPath = join(dirname(root), primaryLink(current).path);
201
222
  else if (fixedOutputPath !== undefined) outputPath = fixedOutputPath;
@@ -204,13 +225,19 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
204
225
  await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
205
226
  }
206
227
  const relativePath = dependencies.workspace.relativePath(outputPath, root);
207
- const previous = previousMarkdown === null ? await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "" : previousMarkdown;
228
+ const onDisk = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
229
+ const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
230
+ const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
231
+ const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
232
+ // Only advance the common base if the editor saw that version. Otherwise a retry
233
+ // could mistake remote additions that never reached disk for local deletions.
234
+ if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) throw new Error(retry);
208
235
  if (action === "attached" && current !== null) {
209
236
  const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
210
237
  const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
211
238
  if (baseMarkdown !== null && previous !== baseMarkdown) throw new Error(`Local edits exist for ${primaryLink(current).path}. Run \`wire sync ${primaryLink(current).path}\` before attaching this URL again.`);
212
239
  }
213
- await dependencies.filesystem.writeText(outputPath, fetched.markdown);
240
+ if (!concurrentEdit && onDisk !== fetched.markdown) await dependencies.filesystem.writeText(outputPath, fetched.markdown);
214
241
  const id = resourceId(source);
215
242
  const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
216
243
  const resource: Resource = {
@@ -233,6 +260,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
233
260
  relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
234
261
  };
235
262
  const stored = await registry.put(resource);
263
+ if (concurrentEdit) throw new Error(retry);
236
264
  const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
237
265
  const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
238
266
  return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
@@ -240,7 +268,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
240
268
 
241
269
  const attach = async (url: string, path: string): Promise<WireResult> => {
242
270
  const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
243
- return store(url, path, fetched, null, "attached", undefined, undefined, fetched.markdown);
271
+ return store(url, path, fetched, undefined, "attached", undefined, undefined, fetched.markdown);
244
272
  };
245
273
  const create = attach;
246
274
 
@@ -305,8 +333,8 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
305
333
  if (value.startsWith("http://") || value.startsWith("https://")) {
306
334
  const source = parseSourceUrl(value, dependencies.catalog);
307
335
  const resources = await registry.listResources();
308
- const resource = resources.find((item) => item.identifiers.some((identifier) => identifier.service === source.service && identifier.identifier === source.identifier));
309
- if (resource === undefined) throw new Error(`Resource URL not found: ${value}`);
336
+ const resource = findResource(resources, source, dependencies.catalog);
337
+ if (resource === null) throw new Error(`Resource URL not found: ${value}`);
310
338
  return resource;
311
339
  }
312
340
  const candidatePath = resolve(path, value);
@@ -314,6 +342,10 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
314
342
  const resources = await registry.findByPath(relativePath);
315
343
  if (resources.length > 0 || await dependencies.filesystem.exists(candidatePath)) {
316
344
  if (resources.length === 0) throw new Error(`Resource path is not registered: ${value}`);
345
+ if (resources.length === 2) {
346
+ const tab = resources.map((item) => legacyDefaultTab(item, dependencies.catalog)).find((item) => item !== null);
347
+ if (tab && resources.some((item) => item.id === resourceId(tab))) return findResource(resources, tab, dependencies.catalog)!;
348
+ }
317
349
  if (resources.length > 1) throw new Error(`Ambiguous resource path ${relativePath}: ${resources.map((resource) => resource.id).join(", ")}. Use a resource id or URL.`);
318
350
  return resources[0]!;
319
351
  }
@@ -335,14 +367,27 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
335
367
  const resource = await resolveResource(registry, value, root, path);
336
368
  const outputPath = join(dirname(root), primaryLink(resource).path);
337
369
  const outputDirectory = dirname(outputPath);
338
- const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
339
- const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
370
+ const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0]!, dependencies.catalog);
371
+ const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
372
+ if (snapshot === undefined) throw new Error(`Missing saved snapshot for ${primaryLink(resource).path}. Keep the local file and download a separate copy to reconcile before syncing.`);
340
373
  if (!(await dependencies.filesystem.exists(outputPath))) throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
341
374
  const markdown = await dependencies.filesystem.readText(outputPath);
342
375
  const base = syncBase(source.service, snapshot, resource.data);
343
376
  const baseMarkdown = markdownSnapshot(base);
344
377
  const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
345
378
  if (localChanged && !serviceCanSynchronize(resource.urls[0]!, dependencies.catalog)) throw new Error(`${source.service} is download-only and the local file has edits. Run \`wire download ${primaryLink(resource).path}\` to discard them.`);
379
+ if (source.service === "google-docs" && source["document_tab"] === "t.0") {
380
+ const registered = findResource(await registry.listResources(), source, dependencies.catalog);
381
+ if (registered && legacyDefaultTab(registered, dependencies.catalog)) {
382
+ if (registered.urls.length !== 1 || registered.identifiers.length !== 1 || registered.identifiers[0]!.identifier !== source["document_id"] || registered.filesystem_links.filter((link) => link.role === "primary").length !== 1 || !registry.rekey) {
383
+ throw new Error(`Cannot migrate the ambiguous default-tab registration ${registered.id}. Back up the linked files and check the URLs, primary paths, and registry backend before syncing. No files were changed.`);
384
+ }
385
+ if (baseMarkdown === null || markdown !== baseMarkdown) {
386
+ throw new Error(`Cannot migrate the old default-tab registration for ${primaryLink(registered).path}. Copy the local file somewhere safe, restore the linked file to its saved snapshot, then sync it and reapply only the edits for this tab. The local file and saved snapshot were kept.`);
387
+ }
388
+ await registry.rekey(registered, { service: source.service, identifier: source.identifier });
389
+ }
390
+ }
346
391
  const fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog, base, markdown, outputPath);
347
392
  const action = localChanged ? fetched.markdown === baseMarkdown ? "synced" : "uploaded" : fetched.markdown === markdown ? "synced" : "downloaded";
348
393
  return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
@@ -354,7 +399,7 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
354
399
  const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
355
400
  const resource = await resolveResource(registry, value, root, path);
356
401
  const outputPath = join(dirname(root), primaryLink(resource).path);
357
- const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : "";
402
+ const markdown = await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
358
403
  const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
359
404
  return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
360
405
  };
@@ -392,21 +437,38 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
392
437
  let resolveClosed!: () => void;
393
438
  const closed = new Promise<void>((resolveClosedPromise) => { resolveClosed = resolveClosedPromise; });
394
439
  const handles: WatchHandle[] = [];
395
- const synchronize = async () => {
396
- const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
397
- lastSyncedMarkdown = result.markdown;
398
- };
399
- const schedule = () => {
400
- if (debounce !== undefined) clearTimeout(debounce);
401
- debounce = setTimeout(() => {
402
- debounce = undefined;
403
- void synchronize();
404
- }, config.debounceMs);
440
+ let active = false, pending = false, poll = false, stopped = false;
441
+ const synchronize = async (forcePoll: boolean) => {
442
+ if (stopped) return;
443
+ pending = true;
444
+ poll ||= forcePoll;
445
+ if (active) return;
446
+ active = true;
447
+ try {
448
+ while (pending && !stopped) {
449
+ const checkRemote = poll;
450
+ pending = poll = false;
451
+ try {
452
+ if (!checkRemote && await dependencies.filesystem.readText(outputPath) === lastSyncedMarkdown) continue;
453
+ const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
454
+ lastSyncedMarkdown = result.markdown;
455
+ } catch (error) {
456
+ console.warn(`Wire watch: ${errorMessage(error)}`);
457
+ }
458
+ }
459
+ } finally {
460
+ active = false;
461
+ if (stopped) resolveClosed();
462
+ }
405
463
  };
406
- handles.push(dependencies.watch!.every(config.pollMs, synchronize));
464
+ handles.push(dependencies.watch!.every(config.pollMs, () => synchronize(true)));
407
465
  if (config.mode === "two-way") {
408
- handles.push(dependencies.watch!.watchFile(outputPath, async () => {
409
- if (await dependencies.filesystem.readText(outputPath) !== lastSyncedMarkdown) schedule();
466
+ handles.push(dependencies.watch!.watchFile(outputPath, () => {
467
+ if (debounce !== undefined) clearTimeout(debounce);
468
+ debounce = setTimeout(() => {
469
+ debounce = undefined;
470
+ void synchronize(false);
471
+ }, config.debounceMs);
410
472
  }));
411
473
  }
412
474
  return Object.freeze({
@@ -417,9 +479,10 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
417
479
  pollMs: config.pollMs,
418
480
  closed,
419
481
  close: () => {
482
+ stopped = true;
420
483
  if (debounce !== undefined) clearTimeout(debounce);
421
484
  for (const handle of handles) handle.close();
422
- resolveClosed();
485
+ if (!active) resolveClosed();
423
486
  },
424
487
  });
425
488
  };
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { existsSync, watch } from "node:fs";
3
3
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
- import { dirname } from "node:path";
4
+ import { basename, dirname } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { createCookiesCapability } from "./cookies.js";
7
7
  import { createGoogleTokensCapability } from "./google.js";
@@ -57,7 +57,11 @@ export function createNodeOpenFiles(processCapability: ProcessCapability): OpenF
57
57
  export function createNodeWatch(): WatchCapability {
58
58
  return Object.freeze({
59
59
  watchFile: (path: string, onChange: () => void | Promise<void>) => {
60
- const watcher = watch(path, () => { void onChange(); });
60
+ // Editors often replace the inode on save. Watch its name in the directory.
61
+ const name = basename(path);
62
+ const watcher = watch(dirname(path), (_event, filename) => {
63
+ if (filename === null || filename === name) void onChange();
64
+ });
61
65
  return Object.freeze({ close: () => watcher.close() });
62
66
  },
63
67
  every: (milliseconds: number, onTick: () => void | Promise<void>) => {
@@ -1,12 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync, mkdirSync, realpathSync } from "node:fs";
3
- import { open, readdir, readFile, rename, unlink } from "node:fs/promises";
3
+ import { link, open, readdir, readFile, rename, unlink } from "node:fs/promises";
4
4
  import { createRequire } from "node:module";
5
5
  import { basename, dirname, extname, join, sep } from "node:path";
6
6
  import type { DatabaseSync } from "node:sqlite";
7
7
 
8
8
  import { stableJsonCompact, stableJsonPretty } from "../core/json.js";
9
- import type { JsonObject, JsonValue, Registry, Resource, ResourceType } from "../core/model.js";
9
+ import type { Identifier, JsonObject, JsonValue, Registry, Resource, ResourceType } from "../core/model.js";
10
10
  import { normalizeResource } from "../core/resource.js";
11
11
 
12
12
  type ResourceRow = Readonly<{ id: string; type: ResourceType }>;
@@ -164,6 +164,24 @@ export class SqliteRegistry implements Registry {
164
164
  return normalized;
165
165
  }
166
166
 
167
+ async rekey(previous: Resource, identifier: Identifier): Promise<Resource> {
168
+ const database = this.connect();
169
+ const id = `${identifier.service}:${identifier.identifier}`;
170
+ try {
171
+ database.exec("BEGIN IMMEDIATE; PRAGMA defer_foreign_keys=ON");
172
+ if (stableJsonCompact(this.getResource(database, previous.id)) !== stableJsonCompact(previous)) throw new Error("The Wire record changed during migration. Retry sync.");
173
+ database.prepare("UPDATE resources SET id = ? WHERE id = ?").run(id, previous.id);
174
+ database.prepare("UPDATE resource_identifiers SET resource_id = ?, identifier = ? WHERE resource_id = ?").run(id, identifier.identifier, previous.id);
175
+ for (const table of ["resource_urls", "filesystem_links", "resource_data"]) database.prepare(`UPDATE ${table} SET resource_id = ? WHERE resource_id = ?`).run(id, previous.id);
176
+ database.prepare("UPDATE resource_relationships SET source_id = ? WHERE source_id = ?").run(id, previous.id);
177
+ const migrated = this.getResource(database, id);
178
+ database.exec("COMMIT");
179
+ return migrated;
180
+ } finally {
181
+ database.close();
182
+ }
183
+ }
184
+
167
185
  async get(resourceId: string): Promise<Resource> {
168
186
  const database = this.connect();
169
187
  const row = database.prepare("SELECT id FROM resources WHERE id = ?").get(resourceId) as IdRow | undefined;
@@ -286,6 +304,27 @@ export class FileRegistry implements Registry {
286
304
  return normalized;
287
305
  }
288
306
 
307
+ async rekey(previous: Resource, identifier: Identifier): Promise<Resource> {
308
+ const migrated = storageResource({ ...previous, id: `${identifier.service}:${identifier.identifier}`, identifiers: [identifier] });
309
+ if (stableJsonCompact(await this.get(previous.id)) !== stableJsonCompact(previous)) throw new Error("The Wire record changed during migration. Retry sync.");
310
+ // Publish a complete replacement without overwriting another record. If the
311
+ // process stops before unlinking the old file, a retry recognizes its exact copy.
312
+ const temp = join(this.path, randomUUID());
313
+ const handle = await open(temp, "wx", 0o600);
314
+ try {
315
+ try { await handle.writeFile(`${stableJsonPretty(migrated)}\n`, "utf8"); } finally { await handle.close(); }
316
+ try {
317
+ await link(temp, this.resourcePath(migrated.id));
318
+ } catch (error) {
319
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST" || stableJsonCompact(await this.get(migrated.id)) !== stableJsonCompact(migrated)) throw error;
320
+ }
321
+ await unlink(this.resourcePath(previous.id));
322
+ } finally {
323
+ await unlink(temp);
324
+ }
325
+ return migrated;
326
+ }
327
+
289
328
  async get(resourceId: string): Promise<Resource> {
290
329
  if (!existsSync(this.resourcePath(resourceId))) throw missingResource(resourceId);
291
330
  return parseResource(await readFile(this.resourcePath(resourceId), "utf8"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kamilio/wire",
3
- "version": "0.1.43",
3
+ "version": "0.1.45",
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",
@@ -1,7 +1,8 @@
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
 
7
8
  const docxType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
@@ -13,7 +14,7 @@ const formats: Record<string, [string, string]> = {
13
14
  drawing: [".svg", "image/svg+xml"],
14
15
  };
15
16
  type File = { id: string; name: string; mimeType: string; version: string };
16
- 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 };
17
18
  type State = { folder?: string; spreadsheet?: string; links?: Record<string, string[]>; entries: Record<string, Entry> };
18
19
  const digest = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
19
20
  async function stat(path: string) {
@@ -53,6 +54,11 @@ async function checkDocImage(folder: string, name: string) {
53
54
  return true;
54
55
  }
55
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
+
56
62
  async function extractDocImages(runtime: DriveRuntime, id: string, full: string, text: string) {
57
63
  const labels = new Set([...text.matchAll(imageDefinition)].map(m => m[1]));
58
64
  const images = [...text.matchAll(imageUse)].filter(m => m[2] === undefined || labels.has(m[2]));
@@ -140,7 +146,10 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
140
146
  : item.mimeType === google + "presentation"
141
147
  ? "text/plain"
142
148
  : undefined;
143
- 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
+ }
144
153
  if (item.mimeType === "application/pdf" || /\.pdf$/i.test(item.name)) {
145
154
  const response = await drive(runtime, "/" + id, { alt: "media", supportsAllDrives: "true" });
146
155
  return (
@@ -157,20 +166,7 @@ export async function previewDrive(runtime: DriveRuntime, url: string) {
157
166
  return "# " + item.name + "\n\n" + item.mimeType;
158
167
  }
159
168
 
160
- type SheetCell = {
161
- formattedValue?: string; hyperlink?: string; userEnteredValue?: { stringValue?: string; formulaValue?: string };
162
- textFormatRuns?: { format?: { link?: { uri?: string } } }[];
163
- userEnteredFormat?: { textFormat?: { link?: { uri?: string } } };
164
- chipRuns?: { chip?: { richLinkProperties?: { uri?: string } } }[];
165
- };
166
-
167
- async function sheetLinks(runtime: DriveRuntime, id: string) {
168
- const fields = "sheets(properties(title),data(startRow,startColumn,rowData(values(formattedValue,hyperlink,userEnteredValue,textFormatRuns(format/link),userEnteredFormat/textFormat/link,chipRuns(chip/richLinkProperties/uri)))))";
169
- const token = await runtime.googleFormsTokens.load();
170
- const response = await runtime.http.request("https://sheets.googleapis.com/v4/spreadsheets/" + encodeURIComponent(id) + "?" + new URLSearchParams({ fields }), { headers: { authorization: "Bearer " + token.token } });
171
- if (!response.ok) throw new Error("Sheets HTTP " + response.status + ": " + (await response.text()).slice(0, 600));
172
- type Sheet = { properties: { title: string }; data?: { startRow?: number; startColumn?: number; rowData?: { values?: SheetCell[] }[] }[] };
173
- const { sheets } = await response.json() as { sheets: Sheet[] };
169
+ function sheetLinks(sheets: Awaited<ReturnType<typeof readSheetTabs>>, id: string) {
174
170
  const links: Record<string, string[]> = Object.create(null);
175
171
  const labels = new Map<string, string>();
176
172
  for (const tab of sheets) for (const grid of tab.data ?? []) {
@@ -235,6 +231,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
235
231
  images: string[] = [];
236
232
  const priorPaths = new Map(Object.values(state.entries).filter(e => e.path).map(e => [e.id, e.path!]));
237
233
  let labels = new Map<string, string>();
234
+ const rootTabs = state.spreadsheet ? await readSheetTabs(runtime, source) : undefined;
238
235
  async function visit(files: AsyncIterable<File> | Iterable<File>, dir: string) {
239
236
  for await (const f of files) {
240
237
  try {
@@ -255,9 +252,10 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
255
252
  const suff = format?.[0] ?? (pdf && !/\.pdf$/i.test(name) ? ".pdf" : docx && !/\.docx$/i.test(name) ? ".docx" : "");
256
253
  let path = join(dir, name + (name.endsWith(suff) ? "" : suff));
257
254
  // Existing scrapes keep their original sidecar paths.
258
- const markdownPath = () => state.entries[key(path + ".md")]?.id !== f.id && /\.(pdf|docx)$/i.test(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)
259
257
  ? path.slice(0, -extname(path).length) + ".md" : path + ".md";
260
- const paths = () => (pdf || docx ? [path, markdownPath()] : [path]);
258
+ const paths = () => (pdf || docx || spreadsheet ? [path, markdownPath()] : [path]);
261
259
  const key = (p: string) => "./" + p.normalize("NFC").toLowerCase();
262
260
  const occupied = async () => {
263
261
  for (const p of paths()) {
@@ -312,6 +310,15 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
312
310
  if (!info || entry?.version !== f.version) current = false;
313
311
  }
314
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
+ }
315
322
  if (original?.images?.length) {
316
323
  const dir = await docImageDir(full, false);
317
324
  for (const image of original.images) if (!(await checkDocImage(dir, image))) current = false;
@@ -339,10 +346,15 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
339
346
  ? await drive(runtime, "/" + f.id + "/export", { mimeType: format[1] })
340
347
  : await drive(runtime, "/" + f.id, { alt: "media", supportsAllDrives: "true" });
341
348
  const raw = new Uint8Array(await response.arrayBuffer());
342
- 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;
343
350
  const bytes = doc?.bytes ?? raw;
351
+ const table = spreadsheet ? Buffer.from(sheetMarkdown((f.id === source ? rootTabs : undefined) ?? await readSheetTabs(runtime, f.id))) : undefined;
344
352
  await save(full, bytes);
345
- state.entries[key(path)] = { id: f.id, path, version: f.version, hash: digest(bytes), ...(doc ? { images: doc.images, originalImages: true } : {}) };
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 } : {}) };
346
358
  if (pdf || docx) {
347
359
  const text = docx ? await (await import("./drive-docx.js")).docxMarkdown(bytes)
348
360
  : (await import("./drive-pdf.js")).pdfMarkdown(bytes);
@@ -367,7 +379,7 @@ export async function scrapeDrive(runtime: DriveRuntime, cwd: string, url?: stri
367
379
  try {
368
380
  if (state.spreadsheet) {
369
381
  await visit([root], "");
370
- const cells = await sheetLinks(runtime, source);
382
+ const cells = sheetLinks(rootTabs!, source);
371
383
  state.links = cells.links;
372
384
  labels = cells.labels;
373
385
  for (const [id, refs] of Object.entries(state.links)) {
@@ -220,6 +220,9 @@ function wireUserErrorMessage(message: string): boolean {
220
220
  || /^Indented Notion Markdown block has no parent at indent \d+$/.test(message)
221
221
  || /^POST [A-Za-z0-9]+ failed: \d+ /.test(message)
222
222
  || /^Google (Docs|Sheets|Slides) changed remotely and locally\./.test(message)
223
+ || /^Google Docs (uploads require|saved snapshot predates|OAuth |block |read rate limited|changed before|export (?:did not include|returned an unexpected))/.test(message)
224
+ || /^Google Drive comment check failed: HTTP/.test(message)
225
+ || /^Google Docs (?:Markdown|Word) export failed: OAuth access denied/.test(message)
223
226
  || /^Google Docs local edit cannot be mapped to the live document text$/.test(message)
224
227
  || /^Google Docs sync cannot upload formatting-only Markdown edits$/.test(message)
225
228
  || /^Google Docs sync cannot preserve formatting in edited text$/.test(message)
@@ -288,8 +291,8 @@ function wireUserErrorDisplayMessage(message: string): string {
288
291
  if (googleSaveFailed !== null) return `save failed\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleSaveFailed[1]!}\ndetail: ${lineText(googleSaveFailed[2]!)}`;
289
292
  const googleSaveVerification = /^Google (Docs|Sheets) save verification failed$/.exec(message);
290
293
  if (googleSaveVerification !== null) return `save verification failed\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleSaveVerification[1]!}`;
291
- const googleConflict = /^Google (Docs|Sheets|Slides) changed remotely and locally\. Resolve the conflict in Google (Docs|Sheets|Slides) or the local Markdown file before syncing again\.$/.exec(message);
292
- if (googleConflict !== null) return `sync conflict\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleConflict[1]!}\nresolve: edit Google ${googleConflict[2]!} or local Markdown, then sync again`;
294
+ const googleConflict = /^Google (Docs|Sheets|Slides) changed remotely and locally\.(?: Local Markdown (lines?) (\d+(?:-\d+)?(?: \(start of block\))?)\.)? Resolve the conflict in Google (Docs|Sheets|Slides) or the local Markdown file before syncing again\.$/.exec(message);
295
+ if (googleConflict !== null) return `sync conflict\nservice: Google Docs/Sheets/Slides\nsource: Google ${googleConflict[1]!}${googleConflict[2] ? `\nlocal Markdown ${googleConflict[2]}: ${googleConflict[3]}` : ""}\nresolve: edit Google ${googleConflict[4]!} or local Markdown, then sync again`;
293
296
  const googleDocsMapping = /^Google Docs local edit cannot be mapped to the live document text$/.exec(message);
294
297
  if (googleDocsMapping !== null) return "local edit not mappable\nservice: Google Docs/Sheets/Slides\nsource: Google Docs\nresolve: edit Google Docs or simplify local Markdown";
295
298
  const googleFormattingOnly = /^Google Docs sync cannot upload formatting-only Markdown edits$/.exec(message);
@@ -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
+ }