@kamilio/wire 0.1.56 → 0.1.58
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.
- package/README.md +44 -1
- package/dist/adapters/document-shell.d.ts +7 -0
- package/dist/adapters/document-shell.d.ts.map +1 -0
- package/dist/adapters/document-shell.js +51 -0
- package/dist/adapters/document-shell.js.map +1 -0
- package/dist/adapters/root.d.ts.map +1 -1
- package/dist/adapters/root.js +69 -4
- package/dist/adapters/root.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +8 -2
- package/dist/cli.js.map +1 -1
- package/dist/document-shell-engine.mjs +1880 -0
- package/dist/executable.js +1 -1
- package/dist/executable.js.map +1 -1
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js +19 -19
- package/dist/hooks.js.map +1 -1
- package/node_modules/provider-asana/dist/asana-project.d.ts +8 -1
- package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/asana-task.d.ts +8 -1
- package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
- package/node_modules/provider-asana/dist/index.d.ts +16 -2
- package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
- package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +8 -1
- package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
- package/node_modules/provider-chatgpt/dist/index.d.ts +8 -1
- package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
- package/node_modules/provider-gmail/dist/gmail.d.ts +8 -1
- package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
- package/node_modules/provider-gmail/dist/index.d.ts +8 -1
- package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/doc-blocks.js +6 -2
- package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -1
- package/node_modules/provider-google-docs/dist/google-docs.d.ts +8 -1
- package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/google-docs.js +31 -10
- package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
- package/node_modules/provider-google-docs/dist/google-forms.d.ts +8 -1
- package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
- package/node_modules/provider-google-docs/dist/index.d.ts +16 -2
- package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
- package/node_modules/provider-google-docs/src/doc-blocks.ts +8 -2
- package/node_modules/provider-google-docs/src/google-docs.ts +26 -10
- package/node_modules/provider-lattice/dist/index.d.ts +16 -2
- package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/index.d.ts +8 -1
- package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.d.ts +2 -2
- package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.js +24 -15
- package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
- package/node_modules/provider-notion/dist/notion.d.ts +8 -1
- package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion.js +1 -1
- package/node_modules/provider-notion/dist/notion.js.map +1 -1
- package/node_modules/provider-notion/src/notion-sync.ts +23 -15
- package/node_modules/provider-notion/src/notion.ts +1 -1
- package/node_modules/provider-slack/dist/index.d.ts +8 -1
- package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
- package/node_modules/provider-slack/dist/slack.d.ts +8 -1
- package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
- package/node_modules/provider-zoom/dist/index.d.ts +8 -1
- package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
- package/node_modules/provider-zoom/dist/zoom-hub.d.ts +8 -1
- package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
- package/node_modules/wire-core/dist/core/editor-receipts.d.ts +5 -0
- package/node_modules/wire-core/dist/core/editor-receipts.d.ts.map +1 -0
- package/node_modules/wire-core/dist/core/editor-receipts.js +9 -0
- package/node_modules/wire-core/dist/core/editor-receipts.js.map +1 -0
- package/node_modules/wire-core/dist/core/model.d.ts +6 -1
- package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
- package/node_modules/wire-core/dist/core/owner.d.ts +3 -0
- package/node_modules/wire-core/dist/core/owner.d.ts.map +1 -0
- package/node_modules/wire-core/dist/core/owner.js +16 -0
- package/node_modules/wire-core/dist/core/owner.js.map +1 -0
- package/node_modules/wire-core/dist/core/source.d.ts +4 -1
- package/node_modules/wire-core/dist/core/source.d.ts.map +1 -1
- package/node_modules/wire-core/dist/core/source.js +15 -2
- package/node_modules/wire-core/dist/core/source.js.map +1 -1
- package/node_modules/wire-core/dist/index.d.ts +1 -1
- package/node_modules/wire-core/dist/index.d.ts.map +1 -1
- package/node_modules/wire-core/dist/index.js +1 -1
- package/node_modules/wire-core/dist/index.js.map +1 -1
- package/node_modules/wire-core/dist/operations.d.ts +11 -2
- package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
- package/node_modules/wire-core/dist/operations.js +404 -31
- package/node_modules/wire-core/dist/operations.js.map +1 -1
- package/node_modules/wire-core/dist/storage/editor-receipts.d.ts +17 -0
- package/node_modules/wire-core/dist/storage/editor-receipts.d.ts.map +1 -0
- package/node_modules/wire-core/dist/storage/editor-receipts.js +27 -0
- package/node_modules/wire-core/dist/storage/editor-receipts.js.map +1 -0
- package/node_modules/wire-core/dist/storage/history-integrity.d.ts +4 -0
- package/node_modules/wire-core/dist/storage/history-integrity.d.ts.map +1 -0
- package/node_modules/wire-core/dist/storage/history-integrity.js +32 -0
- package/node_modules/wire-core/dist/storage/history-integrity.js.map +1 -0
- package/node_modules/wire-core/dist/storage/history.d.ts +93 -0
- package/node_modules/wire-core/dist/storage/history.d.ts.map +1 -0
- package/node_modules/wire-core/dist/storage/history.js +450 -0
- package/node_modules/wire-core/dist/storage/history.js.map +1 -0
- package/node_modules/wire-core/dist/storage/registry.d.ts +2 -2
- package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
- package/node_modules/wire-core/dist/storage/registry.js +34 -14
- package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
- package/node_modules/wire-core/dist/storage/workspace.d.ts.map +1 -1
- package/node_modules/wire-core/dist/storage/workspace.js +183 -40
- package/node_modules/wire-core/dist/storage/workspace.js.map +1 -1
- package/node_modules/wire-core/src/core/editor-receipts.ts +8 -0
- package/node_modules/wire-core/src/core/model.ts +6 -1
- package/node_modules/wire-core/src/core/owner.ts +16 -0
- package/node_modules/wire-core/src/core/source.ts +17 -1
- package/node_modules/wire-core/src/index.ts +1 -1
- package/node_modules/wire-core/src/operations.ts +344 -33
- package/node_modules/wire-core/src/storage/editor-receipts.ts +27 -0
- package/node_modules/wire-core/src/storage/history-integrity.ts +25 -0
- package/node_modules/wire-core/src/storage/history.ts +331 -0
- package/node_modules/wire-core/src/storage/registry.ts +22 -15
- package/node_modules/wire-core/src/storage/workspace.ts +129 -34
- package/package.json +6 -2
- package/src/adapters/document-shell.ts +43 -0
- package/src/adapters/root.ts +71 -4
- package/src/cli.ts +8 -2
- package/src/executable.ts +1 -1
- package/src/hooks.ts +19 -18
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
3
3
|
|
|
4
|
+
import { FileRegistry, SqliteRegistry } from "./storage/registry.js";
|
|
5
|
+
import { DocumentHistory, requireHistoryVolume, withHistoryLock, working, type HistoryDiff, type HistoryEntry, type HistoryStatus } from "./storage/history.js";
|
|
6
|
+
import { editorFile, editorView, plainMarkdown } from "./storage/editor-receipts.js";
|
|
7
|
+
import { assertWireOwner } from "./core/owner.js";
|
|
4
8
|
import { stableJsonCompact } from "./core/json.js";
|
|
5
9
|
import { extractRelationships, markdownFilename } from "./core/transform.js";
|
|
6
10
|
import type { FetchedDocument, JsonObject, JsonValue, Registry, Resource, ResourceData, ServiceCatalog, Source } from "./core/model.js";
|
|
7
11
|
import { resourceId } from "./core/resource.js";
|
|
8
|
-
import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource } from "./core/source.js";
|
|
12
|
+
import { fetchSource, parseSourceUrl, synchronizeSource, uploadSource, WireMergeConflict } from "./core/source.js";
|
|
9
13
|
import type { InitializedWire, SwitchedWireBackend, WatchCapability, WatchHandle, WireBackend, WireConfig, WireWatchConfig, WireWorkspace } from "./ports.js";
|
|
10
14
|
|
|
11
15
|
export type { WireWorkspace } from "./ports.js";
|
|
@@ -63,7 +67,13 @@ export type WireWatchSyncHook = (command: WireWatchSyncCommand, result: WireResu
|
|
|
63
67
|
export const wireWatchHooks = Symbol("wireWatchHooks");
|
|
64
68
|
|
|
65
69
|
export type Wire = Readonly<{
|
|
66
|
-
attach(url: string, path: string): Promise<WireResult>;
|
|
70
|
+
attach(url: string, path: string, editorReceipts?: boolean): Promise<WireResult>;
|
|
71
|
+
adopt(url: string, existingFilePath: string, editorReceipts?: boolean): Promise<WireResult>;
|
|
72
|
+
historyStatus(value: string, path: string): Promise<HistoryStatus>;
|
|
73
|
+
historyLog(value: string, path: string): Promise<readonly HistoryEntry[]>;
|
|
74
|
+
historyDiff(value: string, path: string, from?: string, to?: string): Promise<HistoryDiff>;
|
|
75
|
+
resolveConflict(value: string, path: string, choice: "local" | "remote" | "working" | "editor" | "shell"): Promise<HistoryStatus>;
|
|
76
|
+
checkpoint(value: string, path: string, expected: string, markdown: string, token: string): Promise<HistoryStatus>;
|
|
67
77
|
create(url: string, path: string): Promise<WireResult>;
|
|
68
78
|
view(url: string): Promise<FetchedDocument>;
|
|
69
79
|
downloadSource(url: string, path: string): Promise<WireResult>;
|
|
@@ -210,9 +220,32 @@ function errorMessage(error: unknown): string {
|
|
|
210
220
|
return String(error);
|
|
211
221
|
}
|
|
212
222
|
|
|
223
|
+
export { withHistoryLock };
|
|
224
|
+
export const sourceLock = (source: Source) => source.service === "google-docs" && source.type === "document" ? "google-docs:" + String(source["document_id"] ?? source.identifier.split("#tab=")[0]) : resourceId(source);
|
|
225
|
+
|
|
213
226
|
export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInput>): Wire {
|
|
214
|
-
const
|
|
227
|
+
const durable = (registry: Registry) => registry instanceof FileRegistry || registry instanceof SqliteRegistry;
|
|
228
|
+
const locked = async <T>(root: string, registry: Registry, key: string, fn: () => Promise<T>) => durable(registry) ? withHistoryLock(root, key, fn) : fn();
|
|
229
|
+
const owner = async (registry: Registry, source: Source, url: string) => assertWireOwner(await registry.listResources(), source, dependencies.catalog.find(s => s.matches(new URL(url)))!);
|
|
230
|
+
const historyFor = async (root: string, registry: Registry, source: Source) => durable(registry) ? DocumentHistory.load(root, resourceId(source), dependencies.now) : null;
|
|
231
|
+
const removeDetached = (registry: Registry) => async (before: Resource) => {
|
|
232
|
+
const current = (await registry.listResources()).find(r => r.id === before.id);
|
|
233
|
+
if (!current) return;
|
|
234
|
+
if (stableJsonCompact(current) !== stableJsonCompact(before)) throw new Error("Registration changed during detach. The newer registration was kept.");
|
|
235
|
+
await registry.delete(before.id);
|
|
236
|
+
};
|
|
237
|
+
const restore = async (root: string, registry: Registry, source: Source, path?: string) => {
|
|
238
|
+
const history = await historyFor(root, registry, source);
|
|
239
|
+
await history?.recover(path, r => registry.put(r), removeDetached(registry));
|
|
240
|
+
return history;
|
|
241
|
+
};
|
|
242
|
+
const checkReceiptLink = (resource: Resource | null, h?: DocumentHistory | null) => {
|
|
243
|
+
if (resource && (primaryLink(resource).data["editor_receipts"] === true) !== !!h?.refs.editorReceipts) throw new Error("Missing Wire editor receipt history or link registration. Restore the link and its private history before syncing.");
|
|
244
|
+
};
|
|
245
|
+
const store = async (url: string, path: string, fetched: FetchedDocument, previousMarkdown: string | null | undefined, action: WireAction, fixedOutputPath: string | undefined, summaryMarkdown: string | undefined, summaryAfterMarkdown: string, history?: DocumentHistory | null, enableReceipts = false, expectedRaw?: string | null): Promise<WireResult> => {
|
|
215
246
|
const source = parseSourceUrl(url, dependencies.catalog);
|
|
247
|
+
const service = dependencies.catalog.find(s => s.matches(new URL(url)))!;
|
|
248
|
+
if (service.owner !== undefined && (!jsonObject(fetched.data) || fetched.data["wire_owner"] !== service.owner)) throw new Error("Provider returned a snapshot without its registered owner. The existing registration was kept.");
|
|
216
249
|
const root = await wireRoot(dependencies, path);
|
|
217
250
|
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
218
251
|
const current = findResource(await registry.listResources(), source, dependencies.catalog);
|
|
@@ -225,32 +258,42 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
225
258
|
await dependencies.filesystem.exists(candidate) || (await registry.findByPath(dependencies.workspace.relativePath(candidate, root))).length > 0);
|
|
226
259
|
}
|
|
227
260
|
const relativePath = dependencies.workspace.relativePath(outputPath, root);
|
|
228
|
-
|
|
261
|
+
checkReceiptLink(current, history);
|
|
262
|
+
plainMarkdown(fetched.markdown);
|
|
263
|
+
const raw = history ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
|
|
264
|
+
const view = raw === null ? null : history ? history.view(raw) : editorView(raw);
|
|
265
|
+
const onDisk = view?.markdown ?? null;
|
|
266
|
+
if (expectedRaw !== undefined && raw !== expectedRaw && (enableReceipts || history?.refs.editorReceipts)) throw new Error("Local file changed during sync; run wire sync again.");
|
|
267
|
+
if (!current && fixedOutputPath === undefined && onDisk !== null) throw new Error("Another file appeared at the proposed attachment path; retry attach.");
|
|
229
268
|
const previous = (previousMarkdown === undefined ? onDisk : previousMarkdown) ?? "";
|
|
230
269
|
const concurrentEdit = previousMarkdown !== undefined && onDisk !== previousMarkdown && onDisk !== fetched.markdown;
|
|
231
270
|
const retry = `Local file changed during sync: ${relativePath}. Local changes were preserved. Run wire sync again.`;
|
|
232
271
|
// Only advance the common base if the editor saw that version. Otherwise a retry
|
|
233
272
|
// could mistake remote additions that never reached disk for local deletions.
|
|
234
|
-
if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown)
|
|
273
|
+
if (concurrentEdit && current !== null && fetched.markdown !== previousMarkdown) {
|
|
274
|
+
if (history) { await history.observe(fetched); await history.save(); }
|
|
275
|
+
throw new Error(retry);
|
|
276
|
+
}
|
|
235
277
|
if (action === "attached" && current !== null) {
|
|
236
278
|
const snapshot = current.data.find((item) => item.namespace === source.service && item.key === "snapshot")!.value;
|
|
237
|
-
const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data));
|
|
279
|
+
const baseMarkdown = markdownSnapshot(syncBase(source.service, snapshot, current.data)) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
|
|
238
280
|
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.`);
|
|
239
281
|
}
|
|
240
|
-
|
|
282
|
+
|
|
241
283
|
const id = resourceId(source);
|
|
242
284
|
const primary = current?.filesystem_links.find((link) => link.path === relativePath && link.role === "primary");
|
|
285
|
+
const link = { path: relativePath, role: "primary", data: { ...(primary?.data ?? { format: "markdown" }), ...(enableReceipts ? {editor_receipts: true} : {}) } };
|
|
243
286
|
const resource: Resource = {
|
|
244
287
|
id,
|
|
245
288
|
type: source.type,
|
|
246
289
|
identifiers: [{ service: source.service, identifier: source.identifier }],
|
|
247
290
|
urls: [url],
|
|
248
291
|
filesystem_links: current === null
|
|
249
|
-
? [
|
|
292
|
+
? [link]
|
|
250
293
|
: [
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
294
|
+
...current.filesystem_links.filter((link) => !(link.path === relativePath && link.role === "primary")),
|
|
295
|
+
link,
|
|
296
|
+
],
|
|
254
297
|
data: [
|
|
255
298
|
...(current?.data.filter((item) => item.namespace !== "wire" && !(item.namespace === source.service && item.key === "snapshot")) ?? []),
|
|
256
299
|
{ namespace: "wire", key: "title", value: fetched.title },
|
|
@@ -259,16 +302,81 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
259
302
|
],
|
|
260
303
|
relationships: extractRelationships(fetched.markdown, id, dependencies.catalog),
|
|
261
304
|
};
|
|
262
|
-
|
|
305
|
+
let stored: Resource;
|
|
306
|
+
if (history) {
|
|
307
|
+
if (history.refs.conflict) throw new Error("Unresolved Wire conflict. Review the saved revisions and use wire resolve.");
|
|
308
|
+
const currentBase = history.refs.base;
|
|
309
|
+
if (onDisk !== null && currentBase !== null && onDisk !== await history.text(currentBase) && (previousMarkdown === undefined || previousMarkdown === onDisk)) await history.captureLocal(onDisk, view?.shown ?? undefined);
|
|
310
|
+
const draft = history.refs.draft;
|
|
311
|
+
let next: string;
|
|
312
|
+
if (currentBase === null) {
|
|
313
|
+
const input = previousMarkdown === undefined || previousMarkdown === null || previousMarkdown === fetched.markdown ? null : await history.revision("local", previousMarkdown, []);
|
|
314
|
+
next = await history.revision("attach", fetched.markdown, [input]);
|
|
315
|
+
}
|
|
316
|
+
else if (draft !== null && draft !== currentBase && action !== "downloaded") {
|
|
317
|
+
const remote = history.refs.remote;
|
|
318
|
+
const merged = remote !== null && (remote !== currentBase || (view?.base != null && view.base !== currentBase));
|
|
319
|
+
next = await history.revision(merged ? "merge" : "local", fetched.markdown, merged ? [draft, remote] : [draft]);
|
|
320
|
+
} else next = await history.observe(fetched);
|
|
321
|
+
const refs: typeof history.refs = { ...history.refs, base: next, remote: next, draft: null, strict: false, resolution: null, resolutionParent: null, conflict: null };
|
|
322
|
+
delete refs.editorDraft;
|
|
323
|
+
// A confirmed push of the exact draft the editor already saw is safe to
|
|
324
|
+
// acknowledge even if another save arrived while it was in flight.
|
|
325
|
+
if (concurrentEdit && previousMarkdown === fetched.markdown) {
|
|
326
|
+
await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
|
|
327
|
+
stored = await registry.get(resource.id);
|
|
328
|
+
} else if (concurrentEdit) {
|
|
329
|
+
if (current !== null) throw new Error(retry);
|
|
330
|
+
refs.base = previousMarkdown == null ? next : await history.revision("local", previousMarkdown, []);
|
|
331
|
+
refs.resolution = fetched;
|
|
332
|
+
refs.resolutionParent = next;
|
|
333
|
+
await history.publish(outputPath, onDisk ?? "", onDisk ?? "", refs, resource, r => registry.put(r), true);
|
|
334
|
+
stored = await registry.get(resource.id);
|
|
335
|
+
} else {
|
|
336
|
+
if (enableReceipts || refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
|
|
337
|
+
const materialized = refs.editorReceipts ? editorFile(fetched.markdown, refs.editorReceipts, next, next) : fetched.markdown;
|
|
338
|
+
await history.publish(outputPath, raw, materialized, refs, resource, r => registry.put(r));
|
|
339
|
+
stored = await registry.get(resource.id);
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
if (!concurrentEdit && onDisk !== fetched.markdown) await dependencies.filesystem.writeText(outputPath, fetched.markdown);
|
|
343
|
+
stored = await registry.put(resource);
|
|
344
|
+
}
|
|
263
345
|
if (concurrentEdit) throw new Error(retry);
|
|
264
346
|
const changes = changeSummary(summaryMarkdown ?? previous, summaryAfterMarkdown);
|
|
265
347
|
const resolvedAction = action === "attached" && current !== null && previous !== "" ? changes.added === 0 && changes.modified === 0 && changes.removed === 0 ? "synced" : "downloaded" : action;
|
|
266
348
|
return { resource: stored, path: outputPath, markdown: fetched.markdown, summary: { action: resolvedAction, ...changes, remote: url, local: outputPath } };
|
|
267
349
|
};
|
|
268
350
|
|
|
269
|
-
const attach = async (url: string, path: string): Promise<WireResult> => {
|
|
270
|
-
|
|
271
|
-
|
|
351
|
+
const attach = async (url: string, path: string, editorReceipts = false): Promise<WireResult> => {
|
|
352
|
+
return attachAt(url, path, undefined, editorReceipts);
|
|
353
|
+
};
|
|
354
|
+
const attachAt = async (url: string, path: string, fixed?: string, editorReceipts = false): Promise<WireResult> => {
|
|
355
|
+
const root = await wireRoot(dependencies, path), initial = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
356
|
+
const source = parseSourceUrl(url, dependencies.catalog);
|
|
357
|
+
return locked(root, initial, sourceLock(source), async () => {
|
|
358
|
+
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
359
|
+
await owner(registry, source, url);
|
|
360
|
+
const h = await restore(root, registry, source);
|
|
361
|
+
const current = findResource(await registry.listResources(), source, dependencies.catalog);
|
|
362
|
+
checkReceiptLink(current, h);
|
|
363
|
+
const service = dependencies.catalog.find(s => s.matches(new URL(url)))!;
|
|
364
|
+
if (editorReceipts && (!h || source.service !== "google-docs" || source.type !== "document" || (service.owner !== undefined && (!service.supportsEditorReceipts || fixed === undefined)))) {
|
|
365
|
+
throw new Error("Editor receipts require a Google Docs Markdown link with durable history. An owned provider must explicitly support receipts and adopt the existing file.");
|
|
366
|
+
}
|
|
367
|
+
if (current && fixed !== undefined && join(dirname(root), primaryLink(current).path) !== fixed) throw new Error("This URL is already attached at another path.");
|
|
368
|
+
if (fixed !== undefined && (await registry.findByPath(dependencies.workspace.relativePath(fixed, root))).some(r => r.id !== resourceId(source))) throw new Error("This file already has another registration.");
|
|
369
|
+
if (h && current) await h.seed(markdownSnapshot(current.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
|
|
370
|
+
if (h?.refs.conflict) throw new Error("Unresolved Wire conflict. Use wire resolve.");
|
|
371
|
+
if (h?.refs.strict) throw new Error("Sync the pending Wire draft before attaching again.");
|
|
372
|
+
const trackedPath = current ? join(dirname(root), primaryLink(current).path) : fixed;
|
|
373
|
+
if (h) await requireHistoryVolume(h.dir, trackedPath ? dirname(trackedPath) : path);
|
|
374
|
+
const raw = trackedPath && h ? await working(trackedPath) : undefined;
|
|
375
|
+
const existing = raw == null ? raw : h!.view(raw).markdown;
|
|
376
|
+
const fetched = await fetchSource(dependencies.fetchInput, url, dependencies.catalog);
|
|
377
|
+
if (fixed !== undefined && (h ? existing : await dependencies.filesystem.readText(fixed)) !== fetched.markdown) throw new Error("Cannot adopt: the existing file differs from the remote document.");
|
|
378
|
+
return store(url, path, fetched, fixed === undefined ? undefined : fetched.markdown, "attached", fixed, undefined, fetched.markdown, h, editorReceipts, raw);
|
|
379
|
+
});
|
|
272
380
|
};
|
|
273
381
|
const create = attach;
|
|
274
382
|
|
|
@@ -353,29 +461,67 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
353
461
|
return registry.get(value);
|
|
354
462
|
};
|
|
355
463
|
|
|
356
|
-
const
|
|
464
|
+
const syncInner = async (value: string, path: string): Promise<WireResult> => {
|
|
357
465
|
const candidatePath = resolve(path, value);
|
|
358
466
|
const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
|
|
359
467
|
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
360
468
|
const relativePath = dependencies.workspace.relativePath(candidatePath, root);
|
|
361
469
|
const pathResources = await registry.findByPath(relativePath);
|
|
362
470
|
if (pathResources.length === 0 && await dependencies.filesystem.exists(candidatePath)) {
|
|
363
|
-
|
|
364
|
-
const
|
|
365
|
-
|
|
471
|
+
if (durable(registry)) await requireHistoryVolume(join(root, "history"), dirname(candidatePath));
|
|
472
|
+
const markdown = durable(registry) ? await working(candidatePath) : await dependencies.filesystem.readText(candidatePath);
|
|
473
|
+
if (markdown === null) throw new Error("Cannot upload a missing Markdown file.");
|
|
474
|
+
const uploaded = await uploadSource(dependencies.fetchInput, dependencies.catalog, plainMarkdown(markdown), candidatePath);
|
|
475
|
+
const source = parseSourceUrl(uploaded.url, dependencies.catalog);
|
|
476
|
+
return locked(root, registry, sourceLock(source), async () => store(uploaded.url, dirname(candidatePath), uploaded, markdown, "uploaded", candidatePath, undefined, uploaded.markdown, await restore(root, registry, source)));
|
|
366
477
|
}
|
|
367
|
-
|
|
478
|
+
let resource = await resolveResource(registry, value, root, path);
|
|
368
479
|
const outputPath = join(dirname(root), primaryLink(resource).path);
|
|
369
480
|
const outputDirectory = dirname(outputPath);
|
|
370
481
|
const source = legacyDefaultTab(resource, dependencies.catalog) ?? parseSourceUrl(resource.urls[0]!, dependencies.catalog);
|
|
482
|
+
await owner(registry, source, resource.urls[0]!);
|
|
483
|
+
const history = await restore(root, registry, source, outputPath);
|
|
484
|
+
resource = await registry.get(resource.id);
|
|
485
|
+
if (history) await requireHistoryVolume(history.dir, outputDirectory);
|
|
486
|
+
if (history?.refs.conflict && !("editor" in history.refs.conflict)) throw new Error("Unresolved Wire conflict. Inspect wire conflicts and use wire resolve.");
|
|
371
487
|
const snapshot = resource.data.find((item) => item.namespace === source.service && item.key === "snapshot")?.value;
|
|
372
488
|
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.`);
|
|
373
489
|
if (!(await dependencies.filesystem.exists(outputPath))) throw new Error(`Linked file missing: ${primaryLink(resource).path} - restore it or run wire detach`);
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
490
|
+
checkReceiptLink(resource, history);
|
|
491
|
+
let raw = history ? await working(outputPath) : await dependencies.filesystem.readText(outputPath);
|
|
492
|
+
if (raw === null) throw new Error("Linked file missing: " + outputPath);
|
|
493
|
+
let view = history ? history.view(raw) : editorView(raw);
|
|
494
|
+
await history?.checkPendingDraft(view);
|
|
495
|
+
if (history?.refs.conflict && "editor" in history.refs.conflict) {
|
|
496
|
+
const c = history.refs.conflict;
|
|
497
|
+
const merge = dependencies.catalog.find(s => s.matches(new URL(resource.urls[0]!)))?.mergeDrafts;
|
|
498
|
+
const base = c.editorBase === c.shellBase ? history.commonAncestor(c.editor, c.shell) : null;
|
|
499
|
+
let merged: string | undefined;
|
|
500
|
+
// A user may already be reconciling the file. Never overwrite edits
|
|
501
|
+
// that arrived after the two local versions were captured.
|
|
502
|
+
const editor = await history.text(c.editor);
|
|
503
|
+
if (merge && base && view.markdown === editor && view.base === c.editorBase) {
|
|
504
|
+
const before = await history.text(base), shell = await history.text(c.shell);
|
|
505
|
+
try { merged = merge(before, editor, shell); } catch { /* retain the saved conflict */ }
|
|
506
|
+
}
|
|
507
|
+
if (merged === undefined) throw new Error("Unresolved Wire conflict. The editor save and shell draft are both local. Compare them with wire diff <resource> --from editor --to shell, then use wire resolve <resource> <choice>.");
|
|
508
|
+
const draft = await history.revision("merge", merged, [c.editor,c.shell]);
|
|
509
|
+
const receipts = { ...history.refs.editorReceipts! };
|
|
510
|
+
const next = editorFile(merged, receipts, draft, c.editorBase);
|
|
511
|
+
await history.publish(outputPath, raw, next, { ...history.refs, conflict: null, editorReceipts: receipts, editorDraft: draft, draft, strict: true }, null, r => registry.put(r));
|
|
512
|
+
raw = next;
|
|
513
|
+
view = history.view(raw);
|
|
514
|
+
}
|
|
515
|
+
const markdown = view.markdown;
|
|
516
|
+
// A stale receipt proves Markdown ancestry, not native paragraph positions.
|
|
517
|
+
// Never attach a newer snapshot's verified revision or IDs to older bytes.
|
|
518
|
+
const base = view.base && history && view.base !== history.refs.base && view.base !== history.refs.resolutionParent
|
|
519
|
+
? { markdown: await history.text(view.base) }
|
|
520
|
+
: history?.refs.resolution && (!view.base || view.base === history.refs.resolutionParent) ? storedSnapshot(history.refs.resolution) : syncBase(source.service, snapshot, resource.data);
|
|
521
|
+
if (history) await history.seed(markdownSnapshot(snapshot));
|
|
522
|
+
const baseMarkdown = markdownSnapshot(base) ?? (history?.refs.base ? await history.text(history.refs.base) : null);
|
|
377
523
|
const localChanged = baseMarkdown !== null && markdown !== baseMarkdown;
|
|
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.`);
|
|
524
|
+
if (localChanged && !history?.refs.strict && !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
525
|
if (source.service === "google-docs" && source["document_tab"] === "t.0") {
|
|
380
526
|
const registered = findResource(await registry.listResources(), source, dependencies.catalog);
|
|
381
527
|
if (registered && legacyDefaultTab(registered, dependencies.catalog)) {
|
|
@@ -388,35 +534,108 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
388
534
|
await registry.rekey(registered, { service: source.service, identifier: source.identifier });
|
|
389
535
|
}
|
|
390
536
|
}
|
|
391
|
-
|
|
537
|
+
if (history && (localChanged || history.refs.draft !== null)) await history.captureLocal(markdown, view.shown ?? undefined);
|
|
538
|
+
const strict = (history?.refs.strict === true || view.base !== null) && localChanged;
|
|
539
|
+
if (history && strict && source.service !== "notion" && !(source.service === "google-docs" && source.type === "document")) {
|
|
540
|
+
const remote = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
|
|
541
|
+
await history.observe(remote); await history.save();
|
|
542
|
+
if (remote.markdown !== markdown) throw new Error("This provider cannot conditionally publish a Wire draft. The local revision was kept. Apply it in the provider, then sync to verify.");
|
|
543
|
+
return store(resource.urls[0]!, outputDirectory, remote, markdown, "synced", undefined, undefined, remote.markdown, history);
|
|
544
|
+
}
|
|
545
|
+
const observed: { remote?: FetchedDocument } = {};
|
|
546
|
+
let observations = Promise.resolve();
|
|
547
|
+
const fork = view.base ?? (history?.refs.resolution ? history.refs.resolutionParent : history?.refs.base);
|
|
548
|
+
let fetched;
|
|
549
|
+
try {
|
|
550
|
+
fetched = await synchronizeSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog, base, markdown, outputPath, remote => {
|
|
551
|
+
plainMarkdown(remote.markdown);
|
|
552
|
+
observed.remote = remote;
|
|
553
|
+
observations = observations.then(async () => { if (history) { await history.observe(remote); await history.save(); } });
|
|
554
|
+
return observations;
|
|
555
|
+
}, strict, raw);
|
|
556
|
+
await observations;
|
|
557
|
+
} catch (error) {
|
|
558
|
+
await observations;
|
|
559
|
+
if (history && error instanceof WireMergeConflict && observed.remote && history.refs.draft && history.refs.remote) {
|
|
560
|
+
if (fork) {
|
|
561
|
+
history.refs.conflict = { base: fork, local: history.refs.draft, remote: history.refs.remote };
|
|
562
|
+
history.refs.resolution = observed.remote;
|
|
563
|
+
history.refs.resolutionParent = history.refs.remote;
|
|
564
|
+
await history.save();
|
|
565
|
+
throw new Error("Unresolved Wire conflict. " + error.message + " Inspect wire conflicts and use wire resolve.", { cause: error });
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
throw error;
|
|
569
|
+
}
|
|
570
|
+
if (history && !observed.remote && fetched.markdown !== markdown) { await history.observe(fetched); await history.save(); }
|
|
392
571
|
const uploaded = fetched.wroteRemote ?? (localChanged && fetched.markdown !== baseMarkdown);
|
|
393
572
|
const action = uploaded ? "uploaded" : fetched.markdown === markdown || (localChanged && fetched.markdown === baseMarkdown) ? "synced" : "downloaded";
|
|
394
|
-
return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown);
|
|
573
|
+
return store(resource.urls[0]!, outputDirectory, fetched, markdown, action, undefined, action === "uploaded" && baseMarkdown !== null ? baseMarkdown : undefined, action === "uploaded" ? markdown : fetched.markdown, history, false, raw);
|
|
395
574
|
};
|
|
396
575
|
|
|
397
|
-
const
|
|
576
|
+
const underResourceLock = async <T>(value: string, path: string, fn: () => Promise<T>) => {
|
|
577
|
+
const candidate = resolve(path, value);
|
|
578
|
+
const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : path), registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
579
|
+
const ids = await registry.findByPath(dependencies.workspace.relativePath(candidate, root));
|
|
580
|
+
const key = !ids.length && await dependencies.filesystem.exists(candidate) ? "path:" + dependencies.workspace.relativePath(candidate, root) : sourceLock(parseSourceUrl((await resolveResource(registry, value, root, path)).urls[0]!, dependencies.catalog));
|
|
581
|
+
return locked(root, registry, key, fn);
|
|
582
|
+
};
|
|
583
|
+
const sync = (v: string, p: string) => underResourceLock(v, p, () => syncInner(v, p));
|
|
584
|
+
const downloadInner = async (value: string, path: string): Promise<WireResult> => {
|
|
398
585
|
const candidatePath = resolve(path, value);
|
|
399
586
|
const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
|
|
400
587
|
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
401
588
|
const resource = await resolveResource(registry, value, root, path);
|
|
402
589
|
const outputPath = join(dirname(root), primaryLink(resource).path);
|
|
403
|
-
const
|
|
590
|
+
const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
|
|
591
|
+
await owner(registry, source, resource.urls[0]!);
|
|
592
|
+
const h = await restore(root, registry, source, outputPath);
|
|
593
|
+
await h?.seed(markdownSnapshot(resource.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
|
|
594
|
+
if (h?.refs.conflict) throw new Error("Unresolved Wire conflict. Use wire resolve.");
|
|
595
|
+
checkReceiptLink(resource, h);
|
|
596
|
+
const raw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
|
|
597
|
+
const markdown = raw === null ? null : (h ? h.view(raw) : editorView(raw)).markdown;
|
|
598
|
+
if (h?.refs.strict && h.refs.draft) throw new Error("Sync the pending Wire draft before downloading over it.");
|
|
404
599
|
const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
|
|
405
|
-
return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown);
|
|
600
|
+
return store(resource.urls[0]!, dirname(outputPath), fetched, markdown, "downloaded", undefined, undefined, fetched.markdown, h, false, raw);
|
|
406
601
|
};
|
|
407
602
|
|
|
408
|
-
const
|
|
603
|
+
const download = (v: string, p: string) => underResourceLock(v, p, () => downloadInner(v, p));
|
|
604
|
+
const detachInner = async (value: string, path: string): Promise<WireResult> => {
|
|
409
605
|
const candidatePath = resolve(path, value);
|
|
410
606
|
const root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidatePath) ? candidatePath : path);
|
|
411
607
|
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
412
608
|
const resource = await resolveResource(registry, value, root, path);
|
|
413
609
|
const outputPath = join(dirname(root), primaryLink(resource).path);
|
|
414
|
-
const
|
|
610
|
+
const source = parseSourceUrl(resource.urls[0]!, dependencies.catalog);
|
|
611
|
+
await owner(registry, source, resource.urls[0]!);
|
|
612
|
+
const h = await historyFor(root, registry, source);
|
|
613
|
+
const recovered = await h?.recover(outputPath, r => registry.put(r), removeDetached(registry));
|
|
614
|
+
if (recovered) {
|
|
615
|
+
const markdown = await h!.text(h!.refs.base!);
|
|
616
|
+
return { resource: recovered, path: outputPath, markdown, summary: { action: "detached", added: 0, modified: 0, removed: 0, remote: recovered.urls[0]!, local: outputPath } };
|
|
617
|
+
}
|
|
618
|
+
checkReceiptLink(resource, h);
|
|
619
|
+
const initialRaw = h ? await working(outputPath) : await dependencies.filesystem.exists(outputPath) ? await dependencies.filesystem.readText(outputPath) : null;
|
|
620
|
+
const previousView = initialRaw === null ? null : (h ? h.view(initialRaw) : editorView(initialRaw));
|
|
621
|
+
const previous = previousView?.markdown ?? "";
|
|
622
|
+
if (h?.refs.conflict || h?.refs.strict) throw new Error("Resolve and sync the Wire draft before detaching.");
|
|
415
623
|
const fetched = await fetchSource(dependencies.fetchInput, resource.urls[0]!, dependencies.catalog);
|
|
416
|
-
|
|
417
|
-
|
|
624
|
+
if (h) {
|
|
625
|
+
const onDisk = await working(outputPath);
|
|
626
|
+
if (onDisk !== initialRaw) throw new Error("Local file changed during detach; retry.");
|
|
627
|
+
if (previousView) await h.captureLocal(previousView.markdown, previousView.shown ?? undefined);
|
|
628
|
+
const next = await h.observe(fetched);
|
|
629
|
+
const {editorReceipts, ...plainRefs} = h.refs;
|
|
630
|
+
if (editorReceipts) plainRefs.retiredEditorReceipts = { ...plainRefs.retiredEditorReceipts, ...editorReceipts };
|
|
631
|
+
await h.detach(outputPath, onDisk, fetched.markdown, { ...plainRefs, base: next, remote: next, draft: null }, resource, removeDetached(registry));
|
|
632
|
+
} else {
|
|
633
|
+
await dependencies.filesystem.writeText(outputPath, fetched.markdown);
|
|
634
|
+
await registry.delete(resource.id);
|
|
635
|
+
}
|
|
418
636
|
return { resource, path: outputPath, markdown: fetched.markdown, summary: { action: "detached", ...changeSummary(previous, fetched.markdown), remote: resource.urls[0]!, local: outputPath } };
|
|
419
637
|
};
|
|
638
|
+
const detach = (v: string, p: string) => underResourceLock(v, p, () => detachInner(v, p));
|
|
420
639
|
const unlink = detach;
|
|
421
640
|
|
|
422
641
|
const runWatchHooks = async (hooks: readonly WireWatchSyncHook[], command: WireWatchSyncCommand, result: WireResult): Promise<WireResult> => {
|
|
@@ -453,6 +672,12 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
453
672
|
if (!checkRemote && await dependencies.filesystem.readText(outputPath) === lastSyncedMarkdown) continue;
|
|
454
673
|
const result = config.mode === "download" ? await runWatchHooks(hooks, "download", await download(value, path)) : await runWatchHooks(hooks, "sync", await sync(value, path));
|
|
455
674
|
lastSyncedMarkdown = result.markdown;
|
|
675
|
+
if (primaryLink(result.resource).data["editor_receipts"] === true) {
|
|
676
|
+
const h = await historyFor(root, registry, parseSourceUrl(result.resource.urls[0]!, dependencies.catalog));
|
|
677
|
+
if (h?.refs.editorReceipts && h.refs.base && await h.text(h.refs.base) === result.markdown) {
|
|
678
|
+
lastSyncedMarkdown = editorFile(result.markdown, h.refs.editorReceipts, h.refs.base, h.refs.base);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
456
681
|
} catch (error) {
|
|
457
682
|
console.warn(`Wire watch: ${errorMessage(error)}`);
|
|
458
683
|
}
|
|
@@ -530,8 +755,94 @@ export function composeWire<FetchInput>(dependencies: WireDependencies<FetchInpu
|
|
|
530
755
|
return resolveResource(registry, value, root, path);
|
|
531
756
|
};
|
|
532
757
|
|
|
758
|
+
const withDocument = async <T>(v: string, p: string, run: (h: DocumentHistory, path: string, registry: Registry, resource: Resource) => Promise<T>) => underResourceLock(v, p, async () => {
|
|
759
|
+
const candidate = resolve(p, v), root = await wireRoot(dependencies, await dependencies.filesystem.exists(candidate) ? candidate : p);
|
|
760
|
+
const registry = await dependencies.workspace.openRegistry(root, dependencies.home);
|
|
761
|
+
let r = await resolveResource(registry, v, root, p);
|
|
762
|
+
const path = join(dirname(root), primaryLink(r).path);
|
|
763
|
+
const source = parseSourceUrl(r.urls[0]!, dependencies.catalog);
|
|
764
|
+
const h = await restore(root, registry, source, path);
|
|
765
|
+
if (!h) throw new Error("This registry does not provide durable document history.");
|
|
766
|
+
r = await registry.get(r.id);
|
|
767
|
+
checkReceiptLink(r, h);
|
|
768
|
+
await h.seed(markdownSnapshot(r.data.find(i => i.namespace === source.service && i.key === "snapshot")?.value ?? null));
|
|
769
|
+
return run(h, path, registry, r);
|
|
770
|
+
});
|
|
771
|
+
const historyStatus = (v: string, p: string) => withDocument(v, p, async (h, path) => {
|
|
772
|
+
const raw = await working(path);
|
|
773
|
+
if (raw !== null) await h.checkPendingDraft(h.view(raw));
|
|
774
|
+
return h.status(path);
|
|
775
|
+
});
|
|
776
|
+
const historyLog = (v: string, p: string) => withDocument(v, p, h => h.log());
|
|
777
|
+
const historyDiff = (v: string, p: string, from = "base", to = "working") => withDocument(v, p, async (h, path) => {
|
|
778
|
+
const raw = await working(path);
|
|
779
|
+
const current = raw === null ? null : h.view(raw).markdown;
|
|
780
|
+
const text = async (ref: string) => {
|
|
781
|
+
if (ref === "working") { if (current === null) throw new Error("Linked Markdown is missing."); return current; }
|
|
782
|
+
const c = h.refs.conflict;
|
|
783
|
+
const id = c && "editor" in c && (ref === "editor" || ref === "shell") ? c[ref]
|
|
784
|
+
: ref === "base" ? (c && "base" in c ? c.base : h.refs.base)
|
|
785
|
+
: ref === "remote" ? h.refs.remote : ref === "local" ? (c && "local" in c ? c.local : h.refs.draft ?? h.refs.base) : ref;
|
|
786
|
+
if (!id) throw new Error("No saved " + ref + " revision.");
|
|
787
|
+
return h.text(id);
|
|
788
|
+
};
|
|
789
|
+
return { from, to, before: await text(from), after: await text(to), token: h.token(raw) };
|
|
790
|
+
});
|
|
791
|
+
const checkpoint = (v: string, p: string, expected: string, markdown: string, token: string) => withDocument(v, p, async (h, path, reg) => {
|
|
792
|
+
const raw = await working(path);
|
|
793
|
+
const view = raw === null ? null : h.view(raw);
|
|
794
|
+
if (!view || view.markdown !== expected || token !== h.token(raw)) throw new Error("Stale shell edit. The document changed; rerun the command.");
|
|
795
|
+
if (expected !== markdown) {
|
|
796
|
+
await h.checkPendingDraft(view);
|
|
797
|
+
if (h.refs.conflict && "editor" in h.refs.conflict) throw new Error("Unresolved Wire conflict. Edit the working file and run wire resolve <resource> working, or choose editor or shell before using wire shell.");
|
|
798
|
+
plainMarkdown(markdown);
|
|
799
|
+
const prior = await h.captureLocal(expected, view.shown ?? undefined);
|
|
800
|
+
const draft = await h.revision("local", markdown, [prior]);
|
|
801
|
+
const refs = { ...h.refs, draft, strict: true, ...(view.base ? {editorDraft: draft} : {}) };
|
|
802
|
+
if (refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
|
|
803
|
+
const next = refs.editorReceipts && view.base ? editorFile(markdown, refs.editorReceipts, draft, view.base) : markdown;
|
|
804
|
+
await h.publish(path, raw, next, refs, null, r => reg.put(r));
|
|
805
|
+
}
|
|
806
|
+
return h.status(path);
|
|
807
|
+
});
|
|
808
|
+
const resolveConflict = (v: string, p: string, choice: "local" | "remote" | "working" | "editor" | "shell") => withDocument(v, p, async (h, path, reg) => {
|
|
809
|
+
const raw = await working(path);
|
|
810
|
+
if (raw === null) throw new Error("Linked Markdown is missing.");
|
|
811
|
+
const view = h.view(raw), current = view.markdown;
|
|
812
|
+
await h.checkPendingDraft(view);
|
|
813
|
+
const conflict = h.refs.conflict;
|
|
814
|
+
if (!conflict) throw new Error("No saved conflict for this document.");
|
|
815
|
+
let next: string, basis: string, parents: string[];
|
|
816
|
+
if ("editor" in conflict) {
|
|
817
|
+
if (!["working","editor","shell"].includes(choice)) throw new Error("Both drafts are local. Choose editor, shell or working.");
|
|
818
|
+
if (choice !== "working" && current !== await h.text(conflict.editor)) throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
|
|
819
|
+
// The file being reconciled is the editor branch. Keep its remote basis
|
|
820
|
+
// for an edited working resolution; never silently adopt a later base.
|
|
821
|
+
basis = choice === "shell" ? conflict.shellBase : conflict.editorBase;
|
|
822
|
+
if (choice === "working" && view.base !== conflict.editorBase) throw new Error("The working file has a different receipt. Restore the conflicted editor receipt before resolving.");
|
|
823
|
+
next = choice === "working" ? current : await h.text(choice === "shell" ? conflict.shell : conflict.editor);
|
|
824
|
+
parents = [conflict.editor, conflict.shell];
|
|
825
|
+
} else {
|
|
826
|
+
if (!h.refs.resolution) throw new Error("Missing saved provider conflict snapshot.");
|
|
827
|
+
if (!["working","local","remote"].includes(choice)) throw new Error("Choose local, remote or working.");
|
|
828
|
+
const local = await h.text(conflict.local);
|
|
829
|
+
if (choice !== "working" && current !== local) throw new Error("Working file changed since the conflict. Choose working to retain those edits.");
|
|
830
|
+
next = choice === "working" ? current : choice === "local" ? local : await h.text(conflict.remote);
|
|
831
|
+
basis = conflict.remote;
|
|
832
|
+
parents = [conflict.local, conflict.remote];
|
|
833
|
+
}
|
|
834
|
+
const draft = await h.revision("resolve", next, parents);
|
|
835
|
+
const refs = { ...h.refs, draft, strict: true, conflict: null, ...(h.refs.editorReceipts ? {editorDraft: draft} : {}) };
|
|
836
|
+
if (refs.editorReceipts) refs.editorReceipts = { ...refs.editorReceipts };
|
|
837
|
+
const materialized = refs.editorReceipts ? editorFile(next, refs.editorReceipts, draft, basis) : next;
|
|
838
|
+
await h.publish(path, raw, materialized, refs, null, r => reg.put(r));
|
|
839
|
+
return h.status(path);
|
|
840
|
+
});
|
|
841
|
+
|
|
533
842
|
return Object.freeze({
|
|
534
843
|
attach,
|
|
844
|
+
adopt: (url: string, path: string, editorReceipts = false) => attachAt(url, dirname(resolve(path)), resolve(path), editorReceipts),
|
|
845
|
+
historyStatus, historyDiff, historyLog, checkpoint, resolveConflict,
|
|
535
846
|
create,
|
|
536
847
|
view,
|
|
537
848
|
downloadSource,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { invalidReceipt, plainMarkdown, receiptEnvelope } from "../core/editor-receipts.js";
|
|
3
|
+
export { hasEditorReceipt, plainMarkdown } from "../core/editor-receipts.js";
|
|
4
|
+
|
|
5
|
+
// Receipts travel with an editor's buffer. Only this link's private history
|
|
6
|
+
// can associate one with the text shown and the remote base that text used.
|
|
7
|
+
export type EditorReceipts = Record<string, { shown: string; base: string; crlf: boolean }>;
|
|
8
|
+
const prefix = "wire-editor-basis:";
|
|
9
|
+
export function editorView(raw: string, receipts?: EditorReceipts) {
|
|
10
|
+
if (!receipts) return { markdown: plainMarkdown(raw), shown: null, base: null };
|
|
11
|
+
const mark = /\n<!-- wire-editor-basis:v1:([a-f0-9]{48}) -->/.exec(raw);
|
|
12
|
+
if (!mark || raw.match(receiptEnvelope)?.length !== 1) throw invalidReceipt();
|
|
13
|
+
const record = receipts[mark[1]!];
|
|
14
|
+
if (!record || record.crlf !== (raw[mark.index - 1] === "\r")) throw invalidReceipt();
|
|
15
|
+
const suffix = raw.slice(mark.index + mark[0].length);
|
|
16
|
+
if (suffix && !/^(?:\r\n|\n)/.test(suffix)) throw invalidReceipt();
|
|
17
|
+
return { markdown: raw.slice(0, mark.index - Number(record.crlf)) + suffix, shown: record.shown, base: record.base };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function editorFile(text: string, receipts: EditorReceipts, shown: string, base: string) {
|
|
21
|
+
plainMarkdown(text);
|
|
22
|
+
const crlf = text.endsWith("\r") || text.includes("\r\n");
|
|
23
|
+
const existing = Object.entries(receipts).find(([, r]) => r.shown === shown && r.base === base && r.crlf === crlf);
|
|
24
|
+
const key = existing?.[0] ?? randomBytes(24).toString("hex");
|
|
25
|
+
receipts[key] = { shown, base, crlf };
|
|
26
|
+
return text + (crlf ? "\r\n" : "\n") + "<!-- " + prefix + "v1:" + key + " -->";
|
|
27
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { HistoryRefs } from "./history.js";
|
|
3
|
+
|
|
4
|
+
const digest = /^[a-f0-9]{64}$/;
|
|
5
|
+
export const transactionId = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
|
|
6
|
+
|
|
7
|
+
export function validateRefs(refs: HistoryRefs) {
|
|
8
|
+
const corrupt = () => { throw new Error("Corrupt Wire history references. Restore the private history from a backup before syncing."); };
|
|
9
|
+
const known = new Set<string>();
|
|
10
|
+
if (!refs || !Array.isArray(refs.revisions)) return corrupt();
|
|
11
|
+
for (const r of refs.revisions) {
|
|
12
|
+
if (!r || !digest.test(r.blob) || !Array.isArray(r.parents) || r.parents.some(p => !known.has(p)) || known.has(r.id)) return corrupt();
|
|
13
|
+
if (createHash("sha256").update(JSON.stringify([r.kind,r.blob,r.parents])).digest("hex") !== r.id) return corrupt();
|
|
14
|
+
known.add(r.id);
|
|
15
|
+
}
|
|
16
|
+
for (const ref of [refs.base, refs.remote, refs.draft, refs.resolutionParent, refs.editorDraft]) if (ref != null && !known.has(ref)) return corrupt();
|
|
17
|
+
for (const receipts of [refs.editorReceipts, refs.retiredEditorReceipts]) if (receipts !== undefined) {
|
|
18
|
+
if (!receipts || typeof receipts !== "object" || Array.isArray(receipts)) return corrupt();
|
|
19
|
+
for (const [key, record] of Object.entries(receipts)) {
|
|
20
|
+
if (!/^[a-f0-9]{48}$/.test(key) || !record || typeof record.crlf !== "boolean" || !known.has(record.shown) || !known.has(record.base)) return corrupt();
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const c = refs.conflict;
|
|
24
|
+
if (c && !("editor" in c ? [c.editor,c.shell,c.editorBase,c.shellBase] : [c.base,c.local,c.remote]).every(ref => known.has(ref))) return corrupt();
|
|
25
|
+
}
|