@kamilio/wire 0.1.56 → 0.1.57

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 (124) hide show
  1. package/README.md +44 -1
  2. package/dist/adapters/document-shell.d.ts +7 -0
  3. package/dist/adapters/document-shell.d.ts.map +1 -0
  4. package/dist/adapters/document-shell.js +51 -0
  5. package/dist/adapters/document-shell.js.map +1 -0
  6. package/dist/adapters/root.d.ts.map +1 -1
  7. package/dist/adapters/root.js +69 -4
  8. package/dist/adapters/root.js.map +1 -1
  9. package/dist/cli.d.ts.map +1 -1
  10. package/dist/cli.js +8 -2
  11. package/dist/cli.js.map +1 -1
  12. package/dist/document-shell-engine.mjs +1880 -0
  13. package/dist/executable.js +1 -1
  14. package/dist/executable.js.map +1 -1
  15. package/dist/hooks.d.ts.map +1 -1
  16. package/dist/hooks.js +19 -19
  17. package/dist/hooks.js.map +1 -1
  18. package/node_modules/provider-asana/dist/asana-project.d.ts +7 -1
  19. package/node_modules/provider-asana/dist/asana-project.d.ts.map +1 -1
  20. package/node_modules/provider-asana/dist/asana-task.d.ts +7 -1
  21. package/node_modules/provider-asana/dist/asana-task.d.ts.map +1 -1
  22. package/node_modules/provider-asana/dist/index.d.ts +14 -2
  23. package/node_modules/provider-asana/dist/index.d.ts.map +1 -1
  24. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts +7 -1
  25. package/node_modules/provider-chatgpt/dist/chatgpt.d.ts.map +1 -1
  26. package/node_modules/provider-chatgpt/dist/index.d.ts +7 -1
  27. package/node_modules/provider-chatgpt/dist/index.d.ts.map +1 -1
  28. package/node_modules/provider-gmail/dist/gmail.d.ts +7 -1
  29. package/node_modules/provider-gmail/dist/gmail.d.ts.map +1 -1
  30. package/node_modules/provider-gmail/dist/index.d.ts +7 -1
  31. package/node_modules/provider-gmail/dist/index.d.ts.map +1 -1
  32. package/node_modules/provider-google-docs/dist/doc-blocks.d.ts.map +1 -1
  33. package/node_modules/provider-google-docs/dist/doc-blocks.js +6 -2
  34. package/node_modules/provider-google-docs/dist/doc-blocks.js.map +1 -1
  35. package/node_modules/provider-google-docs/dist/google-docs.d.ts +7 -1
  36. package/node_modules/provider-google-docs/dist/google-docs.d.ts.map +1 -1
  37. package/node_modules/provider-google-docs/dist/google-docs.js +31 -10
  38. package/node_modules/provider-google-docs/dist/google-docs.js.map +1 -1
  39. package/node_modules/provider-google-docs/dist/google-forms.d.ts +7 -1
  40. package/node_modules/provider-google-docs/dist/google-forms.d.ts.map +1 -1
  41. package/node_modules/provider-google-docs/dist/index.d.ts +14 -2
  42. package/node_modules/provider-google-docs/dist/index.d.ts.map +1 -1
  43. package/node_modules/provider-google-docs/src/doc-blocks.ts +8 -2
  44. package/node_modules/provider-google-docs/src/google-docs.ts +26 -10
  45. package/node_modules/provider-lattice/dist/index.d.ts +14 -2
  46. package/node_modules/provider-lattice/dist/index.d.ts.map +1 -1
  47. package/node_modules/provider-notion/dist/index.d.ts +7 -1
  48. package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
  49. package/node_modules/provider-notion/dist/notion-sync.d.ts +2 -2
  50. package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
  51. package/node_modules/provider-notion/dist/notion-sync.js +24 -15
  52. package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
  53. package/node_modules/provider-notion/dist/notion.d.ts +7 -1
  54. package/node_modules/provider-notion/dist/notion.d.ts.map +1 -1
  55. package/node_modules/provider-notion/dist/notion.js +1 -1
  56. package/node_modules/provider-notion/dist/notion.js.map +1 -1
  57. package/node_modules/provider-notion/src/notion-sync.ts +23 -15
  58. package/node_modules/provider-notion/src/notion.ts +1 -1
  59. package/node_modules/provider-slack/dist/index.d.ts +7 -1
  60. package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
  61. package/node_modules/provider-slack/dist/slack.d.ts +7 -1
  62. package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
  63. package/node_modules/provider-zoom/dist/index.d.ts +7 -1
  64. package/node_modules/provider-zoom/dist/index.d.ts.map +1 -1
  65. package/node_modules/provider-zoom/dist/zoom-hub.d.ts +7 -1
  66. package/node_modules/provider-zoom/dist/zoom-hub.d.ts.map +1 -1
  67. package/node_modules/wire-core/dist/core/editor-receipts.d.ts +5 -0
  68. package/node_modules/wire-core/dist/core/editor-receipts.d.ts.map +1 -0
  69. package/node_modules/wire-core/dist/core/editor-receipts.js +9 -0
  70. package/node_modules/wire-core/dist/core/editor-receipts.js.map +1 -0
  71. package/node_modules/wire-core/dist/core/model.d.ts +4 -1
  72. package/node_modules/wire-core/dist/core/model.d.ts.map +1 -1
  73. package/node_modules/wire-core/dist/core/owner.d.ts +3 -0
  74. package/node_modules/wire-core/dist/core/owner.d.ts.map +1 -0
  75. package/node_modules/wire-core/dist/core/owner.js +16 -0
  76. package/node_modules/wire-core/dist/core/owner.js.map +1 -0
  77. package/node_modules/wire-core/dist/core/source.d.ts +4 -1
  78. package/node_modules/wire-core/dist/core/source.d.ts.map +1 -1
  79. package/node_modules/wire-core/dist/core/source.js +12 -2
  80. package/node_modules/wire-core/dist/core/source.js.map +1 -1
  81. package/node_modules/wire-core/dist/index.d.ts +1 -1
  82. package/node_modules/wire-core/dist/index.d.ts.map +1 -1
  83. package/node_modules/wire-core/dist/index.js +1 -1
  84. package/node_modules/wire-core/dist/index.js.map +1 -1
  85. package/node_modules/wire-core/dist/operations.d.ts +11 -2
  86. package/node_modules/wire-core/dist/operations.d.ts.map +1 -1
  87. package/node_modules/wire-core/dist/operations.js +399 -31
  88. package/node_modules/wire-core/dist/operations.js.map +1 -1
  89. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts +17 -0
  90. package/node_modules/wire-core/dist/storage/editor-receipts.d.ts.map +1 -0
  91. package/node_modules/wire-core/dist/storage/editor-receipts.js +27 -0
  92. package/node_modules/wire-core/dist/storage/editor-receipts.js.map +1 -0
  93. package/node_modules/wire-core/dist/storage/history-integrity.d.ts +4 -0
  94. package/node_modules/wire-core/dist/storage/history-integrity.d.ts.map +1 -0
  95. package/node_modules/wire-core/dist/storage/history-integrity.js +32 -0
  96. package/node_modules/wire-core/dist/storage/history-integrity.js.map +1 -0
  97. package/node_modules/wire-core/dist/storage/history.d.ts +93 -0
  98. package/node_modules/wire-core/dist/storage/history.d.ts.map +1 -0
  99. package/node_modules/wire-core/dist/storage/history.js +450 -0
  100. package/node_modules/wire-core/dist/storage/history.js.map +1 -0
  101. package/node_modules/wire-core/dist/storage/registry.d.ts +2 -2
  102. package/node_modules/wire-core/dist/storage/registry.d.ts.map +1 -1
  103. package/node_modules/wire-core/dist/storage/registry.js +34 -14
  104. package/node_modules/wire-core/dist/storage/registry.js.map +1 -1
  105. package/node_modules/wire-core/dist/storage/workspace.d.ts.map +1 -1
  106. package/node_modules/wire-core/dist/storage/workspace.js +183 -40
  107. package/node_modules/wire-core/dist/storage/workspace.js.map +1 -1
  108. package/node_modules/wire-core/src/core/editor-receipts.ts +8 -0
  109. package/node_modules/wire-core/src/core/model.ts +4 -1
  110. package/node_modules/wire-core/src/core/owner.ts +16 -0
  111. package/node_modules/wire-core/src/core/source.ts +13 -1
  112. package/node_modules/wire-core/src/index.ts +1 -1
  113. package/node_modules/wire-core/src/operations.ts +339 -33
  114. package/node_modules/wire-core/src/storage/editor-receipts.ts +27 -0
  115. package/node_modules/wire-core/src/storage/history-integrity.ts +25 -0
  116. package/node_modules/wire-core/src/storage/history.ts +331 -0
  117. package/node_modules/wire-core/src/storage/registry.ts +22 -15
  118. package/node_modules/wire-core/src/storage/workspace.ts +129 -34
  119. package/package.json +6 -2
  120. package/src/adapters/document-shell.ts +43 -0
  121. package/src/adapters/root.ts +71 -4
  122. package/src/cli.ts +8 -2
  123. package/src/executable.ts +1 -1
  124. package/src/hooks.ts +19 -18
@@ -0,0 +1,331 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants, linkSync, readFileSync, renameSync, lstatSync } from "node:fs";
3
+ import { hostname } from "node:os";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+ import { link, lstat, mkdir, open, readdir, readlink, rename, rm, stat, symlink, unlink } from "node:fs/promises";
6
+ import type { FetchedDocument, Resource } from "../core/model.js";
7
+ import { editorView, hasEditorReceipt, plainMarkdown, type EditorReceipts } from "./editor-receipts.js";
8
+ import { transactionId, validateRefs } from "./history-integrity.js";
9
+ import { stableJsonCompact } from "../core/json.js";
10
+
11
+ export type HistoryEntry = { id: string; parents: string[]; kind: "attach" | "local" | "remote" | "merge" | "resolve" | "recovered"; at: string };
12
+ export type HistoryConflict = { base: string; local: string; remote: string } | { editor: string; shell: string; editorBase: string; shellBase: string };
13
+ export type HistoryStatus = { path: string; base: string | null; modified: boolean; conflict: HistoryConflict | null };
14
+ export type HistoryDiff = { from: string; to: string; before: string; after: string; token: string };
15
+ type Revision = HistoryEntry & { blob: string };
16
+ export type HistoryRefs = {
17
+ base: string | null; draft: string | null; remote: string | null; conflict: HistoryConflict | null;
18
+ editorReceipts?: EditorReceipts; retiredEditorReceipts?: EditorReceipts; editorDraft?: string;
19
+ strict: boolean; revisions: Revision[]; resolution: FetchedDocument | null; resolutionParent: string | null;
20
+ };
21
+ type Publication = { detached?: Resource; acknowledged: boolean; path: string; expected: string | null; next: string; token: string; refs: HistoryRefs; resource: Resource | null };
22
+ const hash = (value: string) => createHash("sha256").update(value).digest("hex");
23
+ const code = (error: unknown) => (error as NodeJS.ErrnoException).code;
24
+ const missing = (error: unknown) => code(error) === "ENOENT";
25
+ async function exists(path: string) { return lstat(path).then(() => true, e => { if (missing(e)) return false; throw e; }); }
26
+ async function privateDirectory(path: string) {
27
+ try { await mkdir(path, { mode: 0o700 }); } catch (e) { if (code(e) !== "EEXIST") throw e; }
28
+ const info = await lstat(path);
29
+ if (!info.isDirectory() || (info.mode & 0o077) !== 0) throw new Error('Unsafe Wire history directory: ' + path);
30
+ }
31
+ export async function requireHistoryVolume(historyDirectory: string, markdownDirectory: string) {
32
+ const [history, markdown] = await Promise.all([stat(historyDirectory), stat(markdownDirectory)]);
33
+ if (history.dev !== markdown.dev) throw new Error("Wire history and tracked Markdown must be on the same filesystem. Run wire init in the document folder on that volume, then attach the source URL there. Keep any existing edits until you have reconciled the new attachment.");
34
+ }
35
+ async function syncDir(path: string) {
36
+ const fd = await open(path, "r");
37
+ try { await fd.sync(); } finally { await fd.close(); }
38
+ }
39
+ async function write(path: string, value: string, mode = 0o600) {
40
+ const fd = await open(path, "wx", mode);
41
+ try { await fd.writeFile(value); await fd.sync(); } finally { await fd.close(); }
42
+ }
43
+ async function json(path: string, value: unknown) {
44
+ const tmp = join(dirname(path), randomUUID());
45
+ try { await write(tmp, JSON.stringify(value)); await rename(tmp, path); await syncDir(dirname(path)); }
46
+ finally { await rm(tmp, { force: true }); }
47
+ }
48
+ export async function working(path: string): Promise<string | null> {
49
+ let fd;
50
+ try { fd = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
51
+ catch (e) { if (missing(e)) return null; throw e; }
52
+ try {
53
+ if (!(await fd.stat()).isFile()) throw new Error("Expected a regular Markdown file: " + path);
54
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(await fd.readFile());
55
+ } finally { await fd.close(); }
56
+ }
57
+ const empty = (): HistoryRefs => ({ base: null, draft: null, remote: null, conflict: null, strict: false, revisions: [], resolution: null, resolutionParent: null });
58
+
59
+ // Process-owned exclusive claims. A crash leaves its immutable symlink in place.
60
+ // A contender skips only a confirmed dead, still-identical claim on this host.
61
+ // Never unlink another owner's claim: two independent recoverers cannot steal a lock.
62
+ async function claimState(path: string): Promise<"active" | "missing" | "dead"> {
63
+ let owner: string;
64
+ try { owner = await readlink(path); } catch (e) { if (missing(e)) return "missing"; throw e; }
65
+ const [host, pid] = owner.split(":");
66
+ if (host === hostname() && /^\d+$/.test(pid ?? "")) {
67
+ try { process.kill(Number(pid), 0); } catch (e) {
68
+ if (code(e) === "ESRCH" && await readlink(path).catch(() => "") === owner) return "dead";
69
+ }
70
+ }
71
+ return "active";
72
+ }
73
+
74
+ async function claim<T>(dir: string, name: string, run: () => Promise<T>): Promise<T> {
75
+ await privateDirectory(dir);
76
+ const owner = hostname() + ":" + process.pid + ":" + randomUUID();
77
+ for (let n = 0; ; n++) {
78
+ const path = join(dir, name + (n ? "." + n : ""));
79
+ try { await symlink(owner, path); }
80
+ catch (e) {
81
+ if (code(e) !== "EEXIST") throw e;
82
+ const state = await claimState(path);
83
+ if (state !== "active") {
84
+ if (state === "missing") n--;
85
+ continue;
86
+ }
87
+ throw new Error("Another Wire operation owns this document. Retry when it finishes.");
88
+ }
89
+ try { return await run(); } finally { await unlink(path); }
90
+ }
91
+ }
92
+
93
+ async function excludeClaims(dir: string, names: RegExp) {
94
+ for (const name of await readdir(dir)) {
95
+ if (names.test(name) && await claimState(join(dir, name)) === "active") throw new Error("Wire storage is busy. Retry the backend switch or document operation when it finishes.");
96
+ }
97
+ }
98
+
99
+ // Each side posts its claim before inspecting the other side. An operation
100
+ // that has passed its check remains visible until its last durable write.
101
+ export async function withHistoryLock<T>(root: string, key: string, run: () => Promise<T>): Promise<T> {
102
+ const dir = join(root, "history");
103
+ return claim(dir, "lock-" + hash(key), async () => {
104
+ await excludeClaims(dir, /^switch(?:\.\d+)?$/);
105
+ return run();
106
+ });
107
+ }
108
+
109
+ export async function withBackendSwitch<T>(root: string, run: () => Promise<T>): Promise<T> {
110
+ const dir = join(root, "history");
111
+ return claim(dir, "switch", async () => {
112
+ await excludeClaims(dir, /^lock-[a-f0-9]{64}(?:\.\d+)?$/);
113
+ return run();
114
+ });
115
+ }
116
+
117
+ export class DocumentHistory {
118
+ readonly dir: string;
119
+ refs: HistoryRefs = empty();
120
+ private constructor(root: string, private readonly id: string, private readonly now: () => Date) { this.dir = join(root, "history", hash(id)); }
121
+ static async load(root: string, id: string, now: () => Date) {
122
+ const history = new DocumentHistory(root, id, now);
123
+ await privateDirectory(join(root, "history")); await privateDirectory(history.dir);
124
+ const raw = await working(join(history.dir, "refs.json"));
125
+ if (raw !== null) {
126
+ history.refs = JSON.parse(raw) as HistoryRefs;
127
+ validateRefs(history.refs);
128
+ }
129
+ return history;
130
+ }
131
+ async save() { await json(join(this.dir, "refs.json"), this.refs); }
132
+ async revision(kind: HistoryEntry["kind"], markdown: string, parents: (string | null)[]): Promise<string> {
133
+ plainMarkdown(markdown);
134
+ const blob = hash(markdown), ancestry = [...new Set(parents.filter((p): p is string => p !== null))];
135
+ if (ancestry.length === 1 && this.refs.revisions.find(r => r.id === ancestry[0])?.blob === blob) return ancestry[0]!;
136
+ const id = hash(JSON.stringify([kind, blob, ancestry]));
137
+ if (!this.refs.revisions.some(r => r.id === id)) {
138
+ const path = join(this.dir, blob + ".md");
139
+ if (!await exists(path)) {
140
+ const tmp = join(this.dir, randomUUID());
141
+ try { await write(tmp, markdown); await rename(tmp, path); } finally { await rm(tmp, { force: true }); }
142
+ }
143
+ this.refs.revisions.push({ id, kind, at: this.now().toISOString(), blob, parents: ancestry });
144
+ }
145
+ return id;
146
+ }
147
+ token(raw: string | null = null) { return hash(stableJsonCompact([this.refs, raw])); }
148
+ view(raw: string) {
149
+ const view = editorView(raw, this.refs.editorReceipts);
150
+ for (const ref of [view.shown, view.base]) if (ref && !this.refs.revisions.some(r => r.id === ref)) throw new Error("Orphaned Wire editor receipt. The file was kept.");
151
+ return view;
152
+ }
153
+ async text(ref: string) {
154
+ const r = this.refs.revisions.find(r => r.id === ref);
155
+ if (!r) throw new Error("Unknown document revision: " + ref);
156
+ const value = await working(join(this.dir, r.blob + ".md"));
157
+ if (value === null || hash(value) !== r.blob) throw new Error("Corrupt Wire history snapshot: " + ref);
158
+ return value;
159
+ }
160
+ async log(): Promise<HistoryEntry[]> {
161
+ // An old editor can still write through an open file descriptor after
162
+ // publication. Only an explicit history request scans these retained inodes.
163
+ const known = new Set(this.refs.revisions.map(r => r.blob));
164
+ const count = this.refs.revisions.length;
165
+ for (const name of await readdir(this.dir)) {
166
+ if (!name.endsWith(".old") || !transactionId.test(name.slice(0, -4))) continue;
167
+ const path = join(this.dir, name);
168
+ let view: ReturnType<typeof editorView>;
169
+ try {
170
+ const raw = await working(path);
171
+ if (raw === null) continue;
172
+ // A pre-enrollment displaced file has no receipt. Its parent is unknown.
173
+ view = editorView(raw, hasEditorReceipt(raw) ? { ...this.refs.retiredEditorReceipts, ...this.refs.editorReceipts } : undefined);
174
+ if (view.shown && !this.refs.revisions.some(r => r.id === view.shown)) throw new Error("Orphaned receipt");
175
+ } catch (cause) {
176
+ throw new Error("A retained editor save is unreadable. Inspect the private copy: " + path, { cause });
177
+ }
178
+ const blob = hash(view.markdown);
179
+ if (!known.has(blob)) {
180
+ await this.revision("recovered", view.markdown, [view.shown]);
181
+ known.add(blob);
182
+ }
183
+ }
184
+ if (count !== this.refs.revisions.length) await this.save();
185
+ return this.refs.revisions.map(({ blob: _, ...entry }) => entry).reverse();
186
+ }
187
+ async seed(markdown: string | null) {
188
+ if (this.refs.base === null && markdown !== null) {
189
+ this.refs.base = this.refs.remote = await this.revision("attach", markdown, []);
190
+ await this.save();
191
+ }
192
+ }
193
+ async checkPendingDraft(view: ReturnType<typeof editorView>) {
194
+ const shell = this.refs.editorDraft;
195
+ if (!shell || !view.shown || !view.base || shell === view.shown || this.refs.conflict) return;
196
+ const basis = Object.values(this.refs.editorReceipts ?? {}).find(r => r.shown === shell)?.base;
197
+ if (!basis) throw new Error("Missing receipt for the saved shell draft. Both files were kept.");
198
+ const editor = await this.revision("local", view.markdown, [view.shown]);
199
+ this.refs.conflict = { editor, shell, editorBase: view.base, shellBase: basis };
200
+ await this.save();
201
+ }
202
+ commonAncestor(left: string, right: string): string | null {
203
+ const graph = new Map(this.refs.revisions.map(r => [r.id,r.parents]));
204
+ const ancestors = (start: string) => {
205
+ const seen = new Set<string>(), pending = [start];
206
+ while (pending.length) {
207
+ const id = pending.pop()!;
208
+ if (seen.has(id)) continue;
209
+ seen.add(id);
210
+ for (const parent of graph.get(id) ?? []) pending.push(parent);
211
+ }
212
+ return seen;
213
+ };
214
+ const a = ancestors(left), b = ancestors(right);
215
+ const common = new Set([...a].filter(id => b.has(id)));
216
+ const tips = new Set(common);
217
+ for (const id of common) for (const parent of graph.get(id)!) tips.delete(parent);
218
+ return tips.size === 1 ? [...tips][0]! : null;
219
+ }
220
+ async captureLocal(markdown: string, parent = this.refs.draft ?? this.refs.base) {
221
+ this.refs.draft = await this.revision("local", markdown, [parent]);
222
+ await this.save();
223
+ return this.refs.draft;
224
+ }
225
+ async observe(remote: FetchedDocument) {
226
+ this.refs.remote = await this.revision("remote", remote.markdown, [this.refs.remote ?? this.refs.base]);
227
+ return this.refs.remote;
228
+ }
229
+ async status(path: string): Promise<HistoryStatus> {
230
+ const base = this.refs.base;
231
+ const raw = await working(path);
232
+ return { path, base, modified: base === null || raw === null || this.view(raw).markdown !== await this.text(base), conflict: this.refs.conflict };
233
+ }
234
+ // Private write-ahead intent spans the worktree, registry, and revision pointers.
235
+ // Moving the actual old inode out first lets us verify what we displaced. link()
236
+ // publishes only into a vacant name; it cannot overwrite a concurrent editor save.
237
+ async publish(path: string, expected: string | null, next: string, refs: HistoryRefs, resource: Resource | null, put: (r: Resource) => Promise<Resource>, acknowledged = false) {
238
+ await requireHistoryVolume(this.dir, dirname(path));
239
+ const token = randomUUID();
240
+ const pending: Publication = { path, expected, next, refs, resource, token, acknowledged };
241
+ await json(join(this.dir, "pending.json"), pending);
242
+ await this.finish(pending, put);
243
+ }
244
+ async detach(path: string, expected: string | null, next: string, refs: HistoryRefs, detached: Resource, remove: (r: Resource) => Promise<void>) {
245
+ await requireHistoryVolume(this.dir, dirname(path));
246
+ const intent: Publication = {path, expected, next, refs, detached, resource: null, token: randomUUID(), acknowledged: false};
247
+ await json(join(this.dir, "pending.json"), intent);
248
+ await this.finish(intent, undefined, remove);
249
+ }
250
+ async recover(path: string | undefined, put: (r: Resource) => Promise<Resource>, remove?: (r: Resource) => Promise<void>) {
251
+ const file = join(this.dir, "pending.json");
252
+ const raw = await working(file);
253
+ if (raw === null) return;
254
+ const pending = JSON.parse(raw) as Publication;
255
+ if (!transactionId.test(pending.token) || typeof pending.next !== "string" || (pending.expected !== null && typeof pending.expected !== "string") || typeof pending.acknowledged !== "boolean") throw new Error("Corrupt Wire publication journal.");
256
+ validateRefs(pending.refs);
257
+ if (path !== undefined && resolve(path) !== pending.path) throw new Error("Wire publication pending at another path: " + pending.path);
258
+ if (pending.detached && (pending.detached.id !== this.id || pending.resource || pending.acknowledged || !remove)) throw new Error("Corrupt Wire detach journal.");
259
+ await this.finish(pending, put, remove);
260
+ return pending.detached;
261
+ }
262
+ private async finish(p: Publication, put?: (r: Resource) => Promise<Resource>, remove?: (r: Resource) => Promise<void>) {
263
+ const pending = join(this.dir, "pending.json"), stage = join(this.dir, p.token + ".new"), old = join(this.dir, p.token + ".old"), delivered = join(this.dir, p.token + ".ok");
264
+ const cleanup = async () => { await unlink(pending); await syncDir(this.dir); await rm(stage, { force: true }); await rm(delivered, { force: true }); };
265
+ const retry = async (): Promise<never> => {
266
+ if (await exists(old)) {
267
+ try { await link(old, p.path); } catch (e) { if (code(e) !== "EEXIST") throw e; }
268
+ if ((await lstat(old)).isFile()) {
269
+ const saved = await working(old).catch((e: unknown) => { if (e instanceof TypeError) return null; throw e; });
270
+ if (saved !== null && saved !== p.expected) {
271
+ // The displaced inode remains private even when its editor envelope
272
+ // cannot be decoded. Never publish or put envelope bytes in history.
273
+ let view;
274
+ try { view = this.view(saved); } catch { /* retain raw .old */ }
275
+ if (view) await this.captureLocal(view.markdown, view.shown ?? undefined);
276
+ }
277
+ }
278
+ }
279
+ await cleanup();
280
+ throw new Error("Local file changed during sync: " + basename(p.path) + ". Local changes were preserved. Run wire sync again.");
281
+ };
282
+ // A private hard link to the displaced inode is retained, even if another
283
+ // application still has a writable file descriptor open on it.
284
+ if (!p.acknowledged && !await exists(delivered)) {
285
+ let current = await working(p.path);
286
+ if (p.expected === null && current !== null) {
287
+ // In a recovered first attachment, only our own hard link proves delivery.
288
+ if (!await exists(stage)) return retry();
289
+ const staged = await stat(stage), installed = await stat(p.path);
290
+ if (staged.dev !== installed.dev || staged.ino !== installed.ino) return retry();
291
+ }
292
+ if (current !== p.next) {
293
+ if (!await exists(stage)) {
294
+ const mode = current === null ? 0o600 : (await stat(p.path)).mode & 0o777;
295
+ const tmp = join(this.dir, randomUUID());
296
+ try {
297
+ await write(tmp, p.next, mode);
298
+ await rename(tmp, stage);
299
+ await syncDir(this.dir);
300
+ } finally { await rm(tmp, { force: true }); }
301
+ } else if (await working(stage) !== p.next) {
302
+ throw new Error("Corrupt prepared Markdown. No file was published.");
303
+ }
304
+ if (p.expected !== null && !await exists(old)) {
305
+ if (current !== p.expected) return retry();
306
+ // Keep the name-vacant interval to the displaced-file check and
307
+ // exclusive link; no event-loop yield or fsync while the name is absent.
308
+ try { renameSync(p.path, old); } catch (e) { if (missing(e)) return retry(); throw e; }
309
+ if (!lstatSync(old).isFile() || !readFileSync(old).equals(Buffer.from(p.expected))) return retry();
310
+ try { linkSync(stage, p.path); } catch (e) { if (code(e) === "EEXIST") return retry(); throw e; }
311
+ } else {
312
+ if (await exists(old) && await working(old) !== p.expected) return retry();
313
+ current = await working(p.path);
314
+ if (current !== null && current !== p.next) return retry();
315
+ if (current === null) {
316
+ try { await link(stage, p.path); } catch (e) { if (code(e) === "EEXIST") return retry(); throw e; }
317
+ }
318
+ }
319
+ }
320
+ await syncDir(dirname(p.path));
321
+ await write(delivered, ""); await syncDir(this.dir);
322
+ }
323
+ if (p.resource) await put!(p.resource);
324
+ this.refs = p.refs; await this.save();
325
+ // An unregistered path can be uploaded as a new document. Make refs and
326
+ // plain file durable before removing its registration; retain intent until
327
+ // deletion succeeds so an interrupted detach can finish under the lock.
328
+ if (p.detached) await remove!(p.detached);
329
+ await cleanup();
330
+ }
331
+ }
@@ -17,7 +17,7 @@ type DataRow = Readonly<{ namespace: string; key: string; value_json: string }>;
17
17
  type RelationshipRow = Readonly<{ target_id: string; type: string; data_json: string }>;
18
18
  type ResourceIdRow = Readonly<{ resource_id: string }>;
19
19
  type IdRow = Readonly<{ id: string }>;
20
- type SqliteModule = Readonly<{ DatabaseSync: new (path: string) => DatabaseSync }>;
20
+ type SqliteModule = Readonly<{ DatabaseSync: new (path: string, options?: { readOnly: boolean }) => DatabaseSync }>;
21
21
 
22
22
  const require = createRequire("/wire-core/storage/registry.js");
23
23
 
@@ -75,8 +75,9 @@ function missingUrl(url: string): Error {
75
75
  export class SqliteRegistry implements Registry {
76
76
  readonly path: string;
77
77
 
78
- constructor(path: string) {
79
- this.path = realpathSyncParent(path);
78
+ constructor(path: string, create = true) {
79
+ this.path = create ? realpathSyncParent(path) : realpathSync(path);
80
+ if (!create) return;
80
81
  const database = this.connect();
81
82
  database.exec(`
82
83
  PRAGMA journal_mode=DELETE;
@@ -183,7 +184,7 @@ export class SqliteRegistry implements Registry {
183
184
  }
184
185
 
185
186
  async get(resourceId: string): Promise<Resource> {
186
- const database = this.connect();
187
+ const database = this.connect(true);
187
188
  const row = database.prepare("SELECT id FROM resources WHERE id = ?").get(resourceId) as IdRow | undefined;
188
189
  if (row === undefined) {
189
190
  database.close();
@@ -197,7 +198,7 @@ export class SqliteRegistry implements Registry {
197
198
  }
198
199
 
199
200
  async findByIdentifier(service: string, identifier: string): Promise<Resource> {
200
- const database = this.connect();
201
+ const database = this.connect(true);
201
202
  database.exec("BEGIN");
202
203
  const row = database.prepare("SELECT resource_id FROM resource_identifiers WHERE service = ? AND identifier = ?").get(service, identifier) as ResourceIdRow | undefined;
203
204
  if (row === undefined) {
@@ -211,7 +212,7 @@ export class SqliteRegistry implements Registry {
211
212
  }
212
213
 
213
214
  async findByUrl(url: string): Promise<Resource> {
214
- const database = this.connect();
215
+ const database = this.connect(true);
215
216
  database.exec("BEGIN");
216
217
  const row = database.prepare("SELECT resource_id FROM resource_urls WHERE url = ?").get(url) as ResourceIdRow | undefined;
217
218
  if (row === undefined) {
@@ -225,7 +226,7 @@ export class SqliteRegistry implements Registry {
225
226
  }
226
227
 
227
228
  async findByPath(path: string): Promise<readonly Resource[]> {
228
- const database = this.connect();
229
+ const database = this.connect(true);
229
230
  database.exec("BEGIN");
230
231
  const rows = database.prepare("SELECT DISTINCT resource_id FROM filesystem_links WHERE path = ? ORDER BY resource_id").all(path.replaceAll(sep, "/")) as ResourceIdRow[];
231
232
  const resources = rows.map((row) => this.getResource(database, row.resource_id));
@@ -235,7 +236,7 @@ export class SqliteRegistry implements Registry {
235
236
  }
236
237
 
237
238
  async listResources(): Promise<readonly Resource[]> {
238
- const database = this.connect();
239
+ const database = this.connect(true);
239
240
  database.exec("BEGIN");
240
241
  const rows = database.prepare("SELECT id FROM resources ORDER BY id").all() as IdRow[];
241
242
  const resources = rows.map((row) => this.getResource(database, row.id));
@@ -269,8 +270,8 @@ export class SqliteRegistry implements Registry {
269
270
  };
270
271
  }
271
272
 
272
- private connect(): DatabaseSync {
273
- const database = new (require("node:sqlite") as SqliteModule).DatabaseSync(this.path);
273
+ private connect(readOnly = false): DatabaseSync {
274
+ const database = new (require("node:sqlite") as SqliteModule).DatabaseSync(this.path, {readOnly});
274
275
  database.exec("PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON");
275
276
  return database;
276
277
  }
@@ -279,8 +280,8 @@ export class SqliteRegistry implements Registry {
279
280
  export class FileRegistry implements Registry {
280
281
  readonly path: string;
281
282
 
282
- constructor(path: string) {
283
- this.path = realpathSyncDirectory(path);
283
+ constructor(path: string, create = true) {
284
+ this.path = create ? realpathSyncDirectory(path) : realpathSync(path);
284
285
  }
285
286
 
286
287
  async put(resource: Resource): Promise<Resource> {
@@ -298,9 +299,15 @@ export class FileRegistry implements Registry {
298
299
  }
299
300
  const tempPath = join(this.path, randomUUID());
300
301
  const handle = await open(tempPath, "wx", 0o600);
301
- await handle.writeFile(`${stableJsonPretty(normalized)}\n`, "utf8");
302
- await handle.close();
303
- await rename(tempPath, this.resourcePath(normalized.id));
302
+ try {
303
+ try { await handle.writeFile(`${stableJsonPretty(normalized)}\n`, "utf8"); await handle.sync(); }
304
+ finally { await handle.close(); }
305
+ await rename(tempPath, this.resourcePath(normalized.id));
306
+ const directory = await open(this.path, "r");
307
+ try { await directory.sync(); } finally { await directory.close(); }
308
+ } finally {
309
+ await unlink(tempPath).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; });
310
+ }
304
311
  return normalized;
305
312
  }
306
313
 
@@ -1,7 +1,9 @@
1
1
  import { existsSync, realpathSync, statSync } from "node:fs";
2
- import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { link, lstat, mkdir, open, readFile, readdir, rename, rmdir, unlink } from "node:fs/promises";
3
3
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
 
5
+ import { randomUUID } from "node:crypto";
6
+ import { withBackendSwitch } from "./history.js";
5
7
  import { stableJsonPretty } from "../core/json.js";
6
8
  import type { Registry } from "../core/model.js";
7
9
  import type { InitializedWire, SwitchedWireBackend, WireBackend, WireConfig } from "../ports.js";
@@ -24,6 +26,11 @@ function canonicalPath(path: string): string {
24
26
  return join(canonicalPath(dirname(resolved)), basename(resolved));
25
27
  }
26
28
 
29
+ function protectHistory(root: string, path: string) {
30
+ const history = canonicalPath(join(root, "history")), registry = canonicalPath(path);
31
+ if (registry === history || registry.startsWith(history + sep) || history.startsWith(registry + sep)) throw new Error("The Wire registry must not overlap private document history.");
32
+ }
33
+
27
34
  export async function discoverWireRoot(path: string, home: string): Promise<string> {
28
35
  const homePath = canonicalPath(home);
29
36
  let currentPath = canonicalPath(path);
@@ -55,47 +62,135 @@ export async function openWireRegistry(path: string, home: string): Promise<Regi
55
62
  const wireRoot = await discoverWireRoot(path, home);
56
63
  const config = await loadWireConfig(wireRoot);
57
64
  const registryPath = join(wireRoot, config.path);
58
- if (config.backend === "sqlite") return new SqliteRegistry(registryPath);
59
- if (config.backend === "files") return new FileRegistry(registryPath);
60
- throw new Error(config.backend);
65
+ protectHistory(wireRoot, registryPath);
66
+ try {
67
+ if (config.backend === "sqlite") return new SqliteRegistry(registryPath, false);
68
+ if (config.backend === "files") return new FileRegistry(registryPath, false);
69
+ throw new Error(config.backend);
70
+ } catch (e) {
71
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
72
+ throw new Error("Configured Wire registry is missing. Restore its storage, or run wire init with the matching backend if this workspace has never stored documents.");
73
+ }
61
74
  }
62
75
 
63
76
  export async function initializeWire(path: string, backend: WireBackend, registryPath: string): Promise<InitializedWire> {
64
77
  const wireRoot = join(canonicalPath(path), ".wire");
65
78
  await mkdir(wireRoot, { recursive: true });
66
- const configPath = join(wireRoot, "config.json");
67
- if (existsSync(configPath) && statSync(configPath).isFile()) {
68
- const existing = await loadWireConfig(wireRoot);
69
- if (existing.backend !== backend || existing.path !== registryPath) throw new Error(`Wire workspace already initialized with ${existing.backend} registry at ${existing.path}. Existing registries are not overwritten.`);
70
- return { root: wireRoot, backend: existing.backend, path: join(wireRoot, existing.path), created: false };
71
- }
72
- const config = { backend, path: registryPath } satisfies WireConfig;
73
- await writeFile(configPath, `${stableJsonPretty(config)}\n`, "utf8");
79
+ protectHistory(wireRoot, join(wireRoot, registryPath));
74
80
  const fullRegistryPath = join(wireRoot, registryPath);
75
- if (backend === "sqlite") new SqliteRegistry(fullRegistryPath);
76
- else if (backend === "files") new FileRegistry(fullRegistryPath);
77
- else throw new Error(backend);
78
- return { root: wireRoot, backend, path: fullRegistryPath, created: true };
81
+ const config = { backend, path: registryPath } satisfies WireConfig;
82
+ const hasConfig = async () => {
83
+ const existing = await loadWireConfig(wireRoot).catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; });
84
+ if (existing && (existing.backend !== backend || existing.path !== registryPath)) throw new Error(`Wire workspace already initialized with ${existing.backend} registry at ${existing.path}. Existing registries are not overwritten.`);
85
+ return !!existing;
86
+ };
87
+ const occupied = async (path: string) => lstat(path).then(() => true, (e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; return false; });
88
+ const result = (created: boolean) => ({root: wireRoot, backend, path: fullRegistryPath, created});
89
+ if (await hasConfig() && await occupied(fullRegistryPath)) return result(false);
90
+
91
+ const kept = "Configured Wire registry is missing but prior workspace storage exists. Restore the registry; wire init will not replace it.";
92
+ const history = join(wireRoot, "history");
93
+ for (let attempt = 0;; attempt++) {
94
+ try {
95
+ return await withBackendSwitch(wireRoot, async () => {
96
+ const configured = await hasConfig(), storeExists = await occupied(fullRegistryPath);
97
+ if (configured && storeExists) return result(false);
98
+ if (!storeExists) {
99
+ const priorFiles = await readdir(wireRoot);
100
+ const firstNames = new Set(["config.json", "auth", "hooks", "history", registryPath.split(sep)[0]!]);
101
+ if (priorFiles.some(name => !firstNames.has(name) && !/^\.wire-init-[a-f0-9-]{36}$/.test(name)) ||
102
+ (await readdir(history)).some(name => !/^switch(?:\.\d+)?$/.test(name))) throw new Error(kept);
103
+ if (backend === "sqlite") for (const suffix of ["-journal","-wal","-shm"]) if (await occupied(fullRegistryPath + suffix)) throw new Error(kept);
104
+ await mkdir(dirname(fullRegistryPath), {recursive: true});
105
+ if (backend === "files") await mkdir(fullRegistryPath, {mode:0o700});
106
+ else if (backend === "sqlite") {
107
+ const staged = join(dirname(fullRegistryPath), ".wire-init-" + randomUUID());
108
+ try {
109
+ new SqliteRegistry(staged);
110
+ await link(staged, fullRegistryPath);
111
+ } finally { await unlink(staged).catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; }); }
112
+ } else throw new Error(backend);
113
+ const parent = await open(dirname(fullRegistryPath), "r");
114
+ try { await parent.sync(); } finally { await parent.close(); }
115
+ }
116
+ // A previous process may have completed storage creation and died
117
+ // before publishing config. Validate that storage before adoption.
118
+ if (!configured) {
119
+ const registry = backend === "sqlite" ? new SqliteRegistry(fullRegistryPath, false) : new FileRegistry(fullRegistryPath, false);
120
+ await registry.listResources();
121
+ }
122
+ await markRegistryReady(wireRoot);
123
+ if (!configured) await writeConfig(wireRoot, config);
124
+ return result(true);
125
+ });
126
+ } catch (e) {
127
+ if (!(e instanceof Error) || !e.message.startsWith("Another Wire operation owns") || attempt >= 8) throw e;
128
+ await new Promise(r => setTimeout(r, 5 * (attempt + 1)));
129
+ }
130
+ }
131
+ }
132
+
133
+ // Stays outside the registry so removal of the registry cannot be confused
134
+ // with a hand-written config that never had any storage.
135
+ async function markRegistryReady(wireRoot: string) {
136
+ const history = join(wireRoot, "history");
137
+ await mkdir(join(history, "registry-ready"), {recursive:true, mode:0o700});
138
+ const dir = await open(history, "r");
139
+ try { await dir.sync(); } finally { await dir.close(); }
140
+ }
141
+
142
+ async function writeConfig(wireRoot: string, config: WireConfig) {
143
+ const nextConfig = join(wireRoot, randomUUID());
144
+ try {
145
+ const handle = await open(nextConfig, "wx", 0o600);
146
+ try { await handle.writeFile(stableJsonPretty(config) + "\n"); await handle.sync(); }
147
+ finally { await handle.close(); }
148
+ await rename(nextConfig, join(wireRoot, "config.json"));
149
+ const directory = await open(wireRoot, "r");
150
+ try { await directory.sync(); } finally { await directory.close(); }
151
+ } finally { await unlink(nextConfig).catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; }); }
79
152
  }
80
153
 
81
154
  export async function switchWireBackend(path: string, home: string): Promise<SwitchedWireBackend> {
82
155
  const wireRoot = await discoverWireRoot(path, home);
83
- const config = await loadWireConfig(wireRoot);
84
- const fromPath = join(wireRoot, config.path);
85
- const source = config.backend === "sqlite" ? new SqliteRegistry(fromPath) : new FileRegistry(fromPath);
86
- const resources = await source.listResources();
87
- const to = config.backend === "sqlite" ? "files" : "sqlite";
88
- const targetRelativePath = registryPathForBackend(to);
89
- const toPath = join(wireRoot, targetRelativePath);
90
- const canonicalSource = canonicalPath(fromPath);
91
- const canonicalTarget = canonicalPath(toPath);
92
- if (canonicalSource === canonicalTarget || canonicalSource.startsWith(`${canonicalTarget}${sep}`) || canonicalTarget.startsWith(`${canonicalSource}${sep}`)) {
93
- throw new Error(`Cannot switch storage backends because registry paths overlap: ${fromPath} and ${toPath}. Move the source registry and update config.json before switching.`);
94
- }
95
- await rm(toPath, { recursive: true, force: true });
96
- const target = to === "sqlite" ? new SqliteRegistry(toPath) : new FileRegistry(toPath);
97
- for (const resource of resources) await target.put(resource);
98
- await writeFile(join(wireRoot, "config.json"), `${stableJsonPretty({ ...config, backend: to, path: targetRelativePath })}\n`, "utf8");
99
- await rm(fromPath, { recursive: true, force: true });
100
- return { root: wireRoot, from: config.backend, to, fromPath, toPath, resources: resources.length };
156
+ return withBackendSwitch(wireRoot, async () => {
157
+ const config = await loadWireConfig(wireRoot);
158
+ const fromPath = join(wireRoot, config.path);
159
+ protectHistory(wireRoot, fromPath);
160
+ const source = config.backend === "sqlite" ? new SqliteRegistry(fromPath, false) : new FileRegistry(fromPath, false);
161
+ const resources = await source.listResources();
162
+ const to = config.backend === "sqlite" ? "files" : "sqlite";
163
+ const targetRelativePath = registryPathForBackend(to);
164
+ const toPath = join(wireRoot, targetRelativePath);
165
+ const canonicalSource = canonicalPath(fromPath);
166
+ const canonicalTarget = canonicalPath(toPath);
167
+ protectHistory(wireRoot, toPath);
168
+ if (canonicalSource === canonicalTarget || canonicalSource.startsWith(`${canonicalTarget}${sep}`) || canonicalTarget.startsWith(`${canonicalSource}${sep}`)) {
169
+ throw new Error(`Cannot switch storage backends because registry paths overlap: ${fromPath} and ${toPath}. Move the source registry and update config.json before switching.`);
170
+ }
171
+ try {
172
+ if (to === "sqlite") {
173
+ // SQLite can recover or remove its sidecar files on open. Refuse all
174
+ // occupied destination names, including dangling symlinks.
175
+ for (const suffix of ["-journal", "-wal", "-shm"]) {
176
+ const occupied = await lstat(toPath + suffix).catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOENT") throw e; });
177
+ if (occupied) throw new Error("Wire switch destination already exists: " + toPath + suffix);
178
+ }
179
+ await (await open(toPath, "wx", 0o600)).close();
180
+ } else await mkdir(toPath, {mode: 0o700});
181
+ } catch (e) {
182
+ if ((e as NodeJS.ErrnoException).code === "EEXIST") throw new Error("Wire switch destination already exists: " + toPath);
183
+ throw e;
184
+ }
185
+ const target = to === "sqlite" ? new SqliteRegistry(toPath) : new FileRegistry(toPath);
186
+ for (const resource of resources) await target.put(resource);
187
+ await markRegistryReady(wireRoot);
188
+ await writeConfig(wireRoot, { ...config, backend: to, path: targetRelativePath });
189
+ // Remove only records we actually copied. Leave unrelated files alone.
190
+ if (source instanceof FileRegistry) {
191
+ for (const r of resources) await source.delete(r.id);
192
+ await rmdir(fromPath).catch((e: NodeJS.ErrnoException) => { if (e.code !== "ENOTEMPTY") throw e; });
193
+ } else await unlink(fromPath);
194
+ return { root: wireRoot, from: config.backend, to, fromPath, toPath, resources: resources.length };
195
+ });
101
196
  }