@objectstack/metadata-fs 17.0.0-rc.6 → 17.0.0
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/CHANGELOG.md +244 -0
- package/dist/index.cjs +53 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +48 -2
- package/dist/index.d.ts +48 -2
- package/dist/index.js +53 -13
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,249 @@
|
|
|
1
1
|
# @objectstack/metadata-fs
|
|
2
2
|
|
|
3
|
+
## 17.0.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2e836de: chore(packaging): CHANGELOG.md ships in every npm tarball (#4261)
|
|
8
|
+
|
|
9
|
+
The AGENTS.md post-task checklist requires breaking changesets to carry their
|
|
10
|
+
FROM → TO migration because "this text ships to consumers as `CHANGELOG.md`
|
|
11
|
+
inside the npm package and is what an upgrading agent greps after the tombstone
|
|
12
|
+
error." That delivery path was severed for 68 of the 69 publishable packages:
|
|
13
|
+
npm packs `package.json` / `README*` / `LICENSE*` unconditionally but — unlike
|
|
14
|
+
older npm versions — not `CHANGELOG.md`, and the canonical
|
|
15
|
+
`"files": ["dist", "README.md"]` whitelist never named it. Measured on npm
|
|
16
|
+
10.9.7: `npm pack --dry-run` on `@objectstack/types` shipped 3 files while its
|
|
17
|
+
70KB `CHANGELOG.md` stayed behind. Only `@objectstack/spec` listed it
|
|
18
|
+
explicitly.
|
|
19
|
+
|
|
20
|
+
The tombstone-error scenario is precisely the one where the repo is out of
|
|
21
|
+
reach — the upgrading agent has `node_modules` and nothing else — so the
|
|
22
|
+
migration text has to ride in the tarball. Every publishable package now
|
|
23
|
+
declares `CHANGELOG.md` in `files`, and the canonical whitelist is
|
|
24
|
+
`["dist", "README.md", "CHANGELOG.md"]`.
|
|
25
|
+
|
|
26
|
+
The other half is the gate: `check:published-files` gains a fifth invariant,
|
|
27
|
+
COMPLETE — a whitelist that fails to cover `CHANGELOG.md` fails the
|
|
28
|
+
always-required lint job, so the next package cannot silently sever the path
|
|
29
|
+
again. `@objectstack/spec`'s per-package EXTRA_ENTRIES exemption dissolves
|
|
30
|
+
into the canonical set.
|
|
31
|
+
|
|
32
|
+
Consumer-visible change: one more file per install (the package's changelog,
|
|
33
|
+
e.g. 70.8KB for `@objectstack/types`), and `grep -r "removed key"
|
|
34
|
+
node_modules/@objectstack/*/CHANGELOG.md` now finds the migration it was
|
|
35
|
+
promised.
|
|
36
|
+
|
|
37
|
+
- a1b66ef: `FileSystemRepository` no longer creates its root directory when it is attached — only when it first writes.
|
|
38
|
+
|
|
39
|
+
`start()` used to `mkdir` both `<root>` and `<root>/.objectstack/.log` unconditionally, so merely attaching a repository was a write. Because `MetadataPlugin` attaches one at `<project>/.objectstack/metadata` during every boot, a command that never writes metadata still brought a directory skeleton into existence. The loudest case is `os migrate plan`, a declared dry run: on a project that had never been started it left
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
.objectstack/metadata/.objectstack/.log
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
behind, which also destroyed the one signal — does `.objectstack/` exist? — by which the next command can tell a fresh project from a started one. This is the filesystem half of the same property the database half already covers: a dry run leaves nothing behind.
|
|
46
|
+
|
|
47
|
+
Attaching and reading a repository whose root does not exist is now explicitly supported and answers as an empty repository (`get`, `getByHash`, `list`, `history`, `watch`). The root, the type directories and the JSONL change log all appear on the first `put` / `delete`, and nothing about the boot's read-only character changes: no metadata is written that was not written before.
|
|
48
|
+
|
|
49
|
+
One behavioural note for direct users of the package: when the root is absent at `start()`, the chokidar watcher is armed by the first write instead, because chokidar cannot watch a path that does not yet exist. A root brought into existence by a third party while the process runs — with this repository never writing — is therefore not picked up until the next `start()`.
|
|
50
|
+
|
|
51
|
+
- c7e7900: fix(metadata-core,metadata-fs): hash the serialized form, so `put().version` identifies the bytes actually stored (#7856)
|
|
52
|
+
|
|
53
|
+
`hashSpec` canonicalised a `Date` to `{}`, because `canonicalize` walked a
|
|
54
|
+
value's own enumerable keys and a `Date` has none. `JSON.stringify` — what every
|
|
55
|
+
repository actually writes — turns the same `Date` into an ISO string. So the
|
|
56
|
+
hash of the in-memory spec and the hash of the bytes on disk were **different
|
|
57
|
+
hashes for the same item**, and the version handed back to a caller did not
|
|
58
|
+
identify what had been stored.
|
|
59
|
+
|
|
60
|
+
Measured on `main`, one spec carrying one `Date`:
|
|
61
|
+
|
|
62
|
+
```
|
|
63
|
+
canonicalize(in-memory) : {"createdAt":{},"label":"Home"}
|
|
64
|
+
JSON.stringify (bytes) : {"label":"Home","createdAt":"2024-01-01T00:00:00.000Z"}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`canonicalize` now honours `toJSON` exactly as `JSON.stringify` does —
|
|
68
|
+
consulted once per position, its result serialised as-is and never
|
|
69
|
+
re-consulted — which makes a new guarantee true by construction:
|
|
70
|
+
|
|
71
|
+
```
|
|
72
|
+
canonicalize(x) === canonicalize(JSON.parse(JSON.stringify(x)))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Both repository implementations were wrong, in different places**, which is
|
|
76
|
+
why the fix is one function rather than two patches. `FileSystemRepository`
|
|
77
|
+
broke `put().version === get().hash`: it hashed the spec it was handed, wrote
|
|
78
|
+
`JSON.stringify` of it, and re-hashed the parse on the way back out.
|
|
79
|
+
`InMemoryRepository` broke the repository contract's invariant 4
|
|
80
|
+
(`item.hash === hashSpec(item.body)`): it stores `body` already serialised
|
|
81
|
+
(`clonePlain`) while hashing the in-memory spec, so the item it returns
|
|
82
|
+
disagreed with its own hash. `SysMetadataRepository` inherits the fix through
|
|
83
|
+
the same function.
|
|
84
|
+
|
|
85
|
+
Downstream, an incoherent version meant a repository could report an
|
|
86
|
+
`{op:'update', actor:'fs'}` for a file nothing outside the process had touched:
|
|
87
|
+
the head index held a hash the disk could never reproduce, so re-reading one's
|
|
88
|
+
own write looked like somebody else's edit. That surfaces without any watcher —
|
|
89
|
+
a restart rebuilds the index from disk and the version the caller was handed no
|
|
90
|
+
longer matches it.
|
|
91
|
+
|
|
92
|
+
**Ordinary specs hash exactly as before, and this is not a migration.** The new
|
|
93
|
+
path diverges only at a position carrying a callable `toJSON`; a graph without
|
|
94
|
+
one is byte-identical through `canonicalize`. Verified against this repository's
|
|
95
|
+
entire checked-in JSON corpus — 1973 files hashed under both the old and the new
|
|
96
|
+
implementation, **0 hashes changed** — and the `hashSpec({})` regression guard
|
|
97
|
+
in `metadata-core` is unmoved. Stored versions for ordinary specs keep their
|
|
98
|
+
meaning. Versions for `toJSON`-carrying specs do change, and those are exactly
|
|
99
|
+
the versions that never identified their stored bytes in the first place.
|
|
100
|
+
|
|
101
|
+
Also supported as a consequence: a class instance with a `toJSON` now hashes as
|
|
102
|
+
whatever it serialises to, rather than as its private fields. One without a
|
|
103
|
+
`toJSON` still hashes as its own enumerable keys — which is what
|
|
104
|
+
`JSON.stringify` writes for it.
|
|
105
|
+
|
|
106
|
+
The pin is table-driven and lives in the shared repository contract suite, so
|
|
107
|
+
every `MetadataRepository` implementation is held to it: `Date` at a key, `Date`
|
|
108
|
+
under an array index, a class whose `toJSON` yields a string, an object literal
|
|
109
|
+
carrying its own `toJSON`, a nested case, and a plain-JSON control row that
|
|
110
|
+
proves the fix did not simply change every hash.
|
|
111
|
+
|
|
112
|
+
- a1686f9: fix(metadata-fs): stop suppressing self-writes on a wall clock, so a poll tick can no longer swallow an external edit (#7335)
|
|
113
|
+
|
|
114
|
+
`FileSystemRepository` suppressed the watcher event its own `put()`/`delete()`
|
|
115
|
+
was about to produce by adding the path to a `selfWrites` Set and clearing it on
|
|
116
|
+
a fixed `setTimeout(…, 200)`. `handleFsChange` then dropped **any** event for a
|
|
117
|
+
path in that Set, without ever reading what the watcher had observed.
|
|
118
|
+
|
|
119
|
+
Under `usePolling: true, interval: 1000` chokidar compares state once per tick,
|
|
120
|
+
so our own write and an external edit landing between two ticks are delivered as
|
|
121
|
+
a **single** event carrying the _external_ content. Dropping that on a timer
|
|
122
|
+
destroyed the only notification the external edit would ever produce — the edit
|
|
123
|
+
was silently lost, and nothing later recovered it. The realistic trigger is a
|
|
124
|
+
`git checkout` or an editor save arriving while the process writes the same item:
|
|
125
|
+
the dev-mode authoring loop.
|
|
126
|
+
|
|
127
|
+
**Measured.** The filing recorded 0/360 instrumented iterations reaching the
|
|
128
|
+
window and called it derived rather than observed. That was a sampling artefact:
|
|
129
|
+
the delivery lag of a self-write event is
|
|
130
|
+
`(interval - (writeTime mod interval)) + awaitWriteFinish`, so a _fixed_
|
|
131
|
+
pre-edit sleep phase-locks the poll and pins the lag outside the window
|
|
132
|
+
(measured: 519–585 ms across 25 runs). Randomising the sleep so the lag samples
|
|
133
|
+
`[0, interval)` uniformly, 40 runs:
|
|
134
|
+
|
|
135
|
+
| delivery lag | runs | external edit |
|
|
136
|
+
| ------------ | ---- | ------------- |
|
|
137
|
+
| < 200 ms | 7 | **swallowed** |
|
|
138
|
+
| > 200 ms | 33 | delivered |
|
|
139
|
+
|
|
140
|
+
A perfect split on the wall-clock boundary — the mechanism, observed.
|
|
141
|
+
|
|
142
|
+
**The fix removes the pre-check rather than re-keying it**, because the
|
|
143
|
+
content-keyed suppression it was shadowing already existed one step further
|
|
144
|
+
down and needs no timer:
|
|
145
|
+
|
|
146
|
+
- `add`/`change` — `currentHead === hash` drops the event when the bytes on disk
|
|
147
|
+
are the bytes we last published. `put()` sets that head in the same
|
|
148
|
+
continuation as its `rename`, and `awaitWriteFinish` holds any event for a
|
|
149
|
+
further `stabilityThreshold`, so the index is never late.
|
|
150
|
+
- `unlink` — `!currentHead` drops the event when the index already agrees the
|
|
151
|
+
item is gone.
|
|
152
|
+
|
|
153
|
+
`delete()` additionally now retires the head **before** it unlinks rather than
|
|
154
|
+
after. `awaitWriteFinish` debounces only `add`/`change`, so that face gets no
|
|
155
|
+
stability cushion between the disk mutation and the event it produces; ordering
|
|
156
|
+
the index update first makes the downstream check a total suppression rather
|
|
157
|
+
than a race against the poll callback. A failed `unlink` restores the head
|
|
158
|
+
before rethrowing, so the error path is unchanged.
|
|
159
|
+
|
|
160
|
+
No API or configuration change; the repository publishes strictly more of the
|
|
161
|
+
external edits it was always meant to report.
|
|
162
|
+
|
|
163
|
+
One pre-existing limit is now documented rather than altered: identity is judged
|
|
164
|
+
on what round-trips through the file, so a spec whose in-memory form does not
|
|
165
|
+
(a `Date`, which canonicalises to `{}` in memory but to an ISO string once
|
|
166
|
+
written and re-read) is republished as an external `update`. Such a spec already
|
|
167
|
+
fails `put().version === get().hash` independently of the watcher, and the
|
|
168
|
+
200 ms window never covered it either — it expired some 360 ms before the event
|
|
169
|
+
it would have had to catch.
|
|
170
|
+
|
|
171
|
+
- ab07b53: fix(metadata-fs): register every written path with the watcher, so an item created while chokidar is still scanning is not invisible forever (#7282)
|
|
172
|
+
|
|
173
|
+
`FileSystemRepository`'s watcher could go **permanently blind to a single
|
|
174
|
+
item** — external edits to that file produced no `MetadataEvent` for the whole
|
|
175
|
+
life of the process, and nothing recovered short of a restart. The window is a
|
|
176
|
+
race between chokidar's asynchronous initial scan and the repository's own
|
|
177
|
+
first write, and both `start()` (which arms the watcher, after which the caller
|
|
178
|
+
may `put()` on the next tick) and `ensureRoot()` (which arms it in the middle
|
|
179
|
+
of the very first write, #7000) can open it.
|
|
180
|
+
|
|
181
|
+
Measured on chokidar 5 with this repository's options (`usePolling`,
|
|
182
|
+
`interval: 1000`):
|
|
183
|
+
|
|
184
|
+
1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic `rename` in
|
|
185
|
+
`writeJsonAtomic` has not landed yet;
|
|
186
|
+
2. the rename lands, changing the directory's mtime;
|
|
187
|
+
3. chokidar calls `watchFile()` on that directory and libuv takes its polling
|
|
188
|
+
baseline stat, which already reflects step 2.
|
|
189
|
+
|
|
190
|
+
The directory's stat then never changes again, so no poll ever fires for it,
|
|
191
|
+
the directory is never re-read, the item file is never added to the watched
|
|
192
|
+
set, and no per-file watcher is created. `getWatched()` reports the type
|
|
193
|
+
directory as `[]` while the file sits in it, and neither `add` nor `change` is
|
|
194
|
+
ever emitted for that path.
|
|
195
|
+
|
|
196
|
+
The fix does not widen any timer. The only writer that can be inside that
|
|
197
|
+
window is the repository itself, so `put()` now tells the watcher explicitly
|
|
198
|
+
about the path it created instead of depending on a directory scan that may
|
|
199
|
+
never notice it. Registration is idempotent and emits nothing.
|
|
200
|
+
|
|
201
|
+
User-visible effect: `MetadataManager.subscribe()` (and every consumer of
|
|
202
|
+
`repo.watch()`) now reliably sees out-of-process edits — a hand edit, or a
|
|
203
|
+
`git checkout` bringing metadata JSON in — to items written earlier in the same
|
|
204
|
+
process. This was also the cause of four merge-queue ejections across three
|
|
205
|
+
PRs; the two time-based mitigations tried before it (a 20s/25s event deadline
|
|
206
|
+
and a wider pre-edit sleep) could not have worked, because the event was never
|
|
207
|
+
delivered rather than late.
|
|
208
|
+
|
|
209
|
+
- 684ab22: fix(metadata-fs): the `FileSystemRepository` watcher now sees external edits in the production layout
|
|
210
|
+
|
|
211
|
+
`MetadataPlugin` attaches the repository at `<project>/.objectstack/metadata`, and the
|
|
212
|
+
watcher's `ignored` matcher was a bare dotfile regex. chokidar applies that matcher to the
|
|
213
|
+
watched root path itself, not only to entries found underneath it, so the `.objectstack`
|
|
214
|
+
segment of the root matched and the entire watch was inert — `getWatched()` returned `{}`
|
|
215
|
+
and no event ever fired. Hand edits, a `git checkout` that brings metadata JSON in, and any
|
|
216
|
+
other out-of-process writer under `.objectstack/metadata/` were invisible until the next
|
|
217
|
+
`start()`, even though `MetadataManager.setRepository()` is wired to those events and uses
|
|
218
|
+
them to invalidate the registry and the `list()` cache.
|
|
219
|
+
|
|
220
|
+
The matcher is now evaluated against the path _relative_ to the watch root, so dot segments
|
|
221
|
+
belonging to the root itself are never considered while dotfiles under the root — including
|
|
222
|
+
the repository's own `.objectstack/` bookkeeping subtree — stay ignored as before.
|
|
223
|
+
|
|
224
|
+
- Updated dependencies [f5a4ef0]
|
|
225
|
+
- Updated dependencies [2e836de]
|
|
226
|
+
- Updated dependencies [121852d]
|
|
227
|
+
- Updated dependencies [db0d53c]
|
|
228
|
+
- Updated dependencies [c7e7900]
|
|
229
|
+
- Updated dependencies [72c3c86]
|
|
230
|
+
- Updated dependencies [3670cf9]
|
|
231
|
+
- Updated dependencies [2d8dba3]
|
|
232
|
+
- Updated dependencies [7372d46]
|
|
233
|
+
- Updated dependencies [5e247fd]
|
|
234
|
+
- Updated dependencies [1a53a02]
|
|
235
|
+
- Updated dependencies [a954634]
|
|
236
|
+
- Updated dependencies [fda61e4]
|
|
237
|
+
- Updated dependencies [db48ad5]
|
|
238
|
+
- Updated dependencies [65f184b]
|
|
239
|
+
- Updated dependencies [51a587d]
|
|
240
|
+
- Updated dependencies [c073b8c]
|
|
241
|
+
- Updated dependencies [946a131]
|
|
242
|
+
- Updated dependencies [ce92674]
|
|
243
|
+
- Updated dependencies [3d4c545]
|
|
244
|
+
- Updated dependencies [bb7cb41]
|
|
245
|
+
- @objectstack/metadata-core@17.0.0
|
|
246
|
+
|
|
3
247
|
## 17.0.0-rc.6
|
|
4
248
|
|
|
5
249
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -243,8 +243,6 @@ var FileSystemRepository = class {
|
|
|
243
243
|
this.heads = /* @__PURE__ */ new Map();
|
|
244
244
|
/** Next seq counter, hydrated from the log on `start()`. */
|
|
245
245
|
this.nextSeq = 1;
|
|
246
|
-
/** Paths we wrote ourselves; suppress the resulting chokidar event. */
|
|
247
|
-
this.selfWrites = /* @__PURE__ */ new Set();
|
|
248
246
|
this.watcher = null;
|
|
249
247
|
this.started = false;
|
|
250
248
|
this.org = opts.org;
|
|
@@ -410,12 +408,7 @@ var FileSystemRepository = class {
|
|
|
410
408
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
411
409
|
await this.ensureRoot();
|
|
412
410
|
await import_promises2.default.mkdir(typeDir(this.layout, ref.type), { recursive: true });
|
|
413
|
-
|
|
414
|
-
try {
|
|
415
|
-
await writeJsonAtomic(file, spec);
|
|
416
|
-
} finally {
|
|
417
|
-
setTimeout(() => this.selfWrites.delete(file), 200);
|
|
418
|
-
}
|
|
411
|
+
await writeJsonAtomic(file, spec);
|
|
419
412
|
this.trackWrittenPath(file);
|
|
420
413
|
this.heads.set(key, hash);
|
|
421
414
|
const evt = {
|
|
@@ -457,13 +450,13 @@ var FileSystemRepository = class {
|
|
|
457
450
|
}
|
|
458
451
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
459
452
|
await this.ensureRoot();
|
|
460
|
-
this.
|
|
453
|
+
this.heads.delete(key);
|
|
461
454
|
try {
|
|
462
455
|
if ((0, import_node_fs2.existsSync)(file)) await import_promises2.default.unlink(file);
|
|
463
|
-
}
|
|
464
|
-
|
|
456
|
+
} catch (err) {
|
|
457
|
+
if (currentHead !== null) this.heads.set(key, currentHead);
|
|
458
|
+
throw err;
|
|
465
459
|
}
|
|
466
|
-
this.heads.delete(key);
|
|
467
460
|
const seq = this.nextSeq++;
|
|
468
461
|
const ts = this.now().toISOString();
|
|
469
462
|
const evt = {
|
|
@@ -599,8 +592,55 @@ var FileSystemRepository = class {
|
|
|
599
592
|
w.on("unlink", (p) => void this.handleFsChange(p, "unlink"));
|
|
600
593
|
this.watcher = w;
|
|
601
594
|
}
|
|
595
|
+
/**
|
|
596
|
+
* Translate a watcher event into a `MetadataEvent`, or drop it.
|
|
597
|
+
*
|
|
598
|
+
* ## Self-writes are suppressed by content identity, never by a clock (#7335)
|
|
599
|
+
*
|
|
600
|
+
* This used to open with `if (this.selfWrites.has(absPath)) return;` — a
|
|
601
|
+
* `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`
|
|
602
|
+
* cleared. That check discarded **every** event for a recently-written path
|
|
603
|
+
* without ever looking at what the watcher had actually observed, which is
|
|
604
|
+
* the whole defect: with `usePolling`, chokidar compares state once per
|
|
605
|
+
* `interval`, so our write and an external edit landing between two ticks
|
|
606
|
+
* are delivered as **one** event carrying the *external* content. Dropping
|
|
607
|
+
* it on a wall clock destroyed the only notification that edit would ever
|
|
608
|
+
* produce.
|
|
609
|
+
*
|
|
610
|
+
* Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase
|
|
611
|
+
* randomised so the delivery lag samples `[0, interval)` uniformly:
|
|
612
|
+
*
|
|
613
|
+
* delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time
|
|
614
|
+
* delivery lag > 200ms → 33 runs → external edit delivered, every time
|
|
615
|
+
*
|
|
616
|
+
* A perfect split on the wall-clock boundary, and the reason earlier
|
|
617
|
+
* instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,
|
|
618
|
+
* pinning the lag (measured: 519–585ms across 25 runs) safely outside the
|
|
619
|
+
* window. Nothing about the window was rare — it was unsampled.
|
|
620
|
+
*
|
|
621
|
+
* What remains is the check that was already doing the real work one step
|
|
622
|
+
* down, and it needs no timer because it compares the content the watcher
|
|
623
|
+
* **read** against the index:
|
|
624
|
+
*
|
|
625
|
+
* - `add`/`change` — `currentHead === hash` drops the event when the bytes
|
|
626
|
+
* on disk are the bytes we last published. `put()` sets that head in the
|
|
627
|
+
* same continuation as its `rename`, and `awaitWriteFinish` holds the
|
|
628
|
+
* event for a further `stabilityThreshold`, so it is never late.
|
|
629
|
+
* - `unlink` — `!currentHead` drops the event when the index already
|
|
630
|
+
* agrees the item is gone. `delete()` retires the head *before* it
|
|
631
|
+
* unlinks, precisely because this face gets no `awaitWriteFinish` delay.
|
|
632
|
+
*
|
|
633
|
+
* Both faces are pinned together in `test/self-write-suppression.test.ts`.
|
|
634
|
+
*
|
|
635
|
+
* Note the deliberate limit: identity is judged on what round-trips through
|
|
636
|
+
* the file, so a spec whose in-memory form does not (a `Date`, which
|
|
637
|
+
* canonicalises to `{}` in memory but to an ISO string once written and
|
|
638
|
+
* re-read) is republished as an external `update`. That predates this change
|
|
639
|
+
* and is independent of it — such a spec already fails `put().version ===
|
|
640
|
+
* get().hash`, and the 200ms window never covered it either, expiring some
|
|
641
|
+
* 360ms before the event it would have had to catch.
|
|
642
|
+
*/
|
|
602
643
|
async handleFsChange(absPath, kind) {
|
|
603
|
-
if (this.selfWrites.has(absPath)) return;
|
|
604
644
|
const parsed = parseItemPath(this.layout, absPath);
|
|
605
645
|
if (!parsed) return;
|
|
606
646
|
const ref = {
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/repository.ts","../src/layout.ts","../src/jsonl-log.ts","../src/sync.ts","../src/watch-iterable.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './repository.js';\nexport { JsonlLog } from './jsonl-log.js';\nexport type { FsLayout } from './layout.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `FileSystemRepository` — Node-only implementation of\n * `MetadataRepository` backed by JSON files plus a JSONL change log.\n *\n * See `README.md` for the on-disk layout and ADR-0008 §10 PR-4 for the\n * design rationale.\n *\n * Invariants\n * ──────────\n * - All `put` / `delete` ops serialize per-key via `KeyedMutex`.\n * - The change-log JSONL is the durable source of `seq`. On boot we\n * scan the log to learn the next seq value.\n * - Body files (`<type>/<name>.json`) are the source of truth; the\n * log is a denormalised history index.\n * - chokidar-driven external edits are translated into MetadataEvents\n * by hashing the new content and comparing to the last-known hash.\n * - The root directory is created **on the first write, not on attach**\n * (#7000). Attaching and reading a repository whose root does not exist\n * is legal and answers \"empty\"; see `start()` / `ensureRoot()`.\n */\n\nimport fs from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { FSWatcher } from 'chokidar';\nimport chokidar from 'chokidar';\nimport {\n type MetadataRepository,\n type MetaRef,\n type MetadataItem,\n type MetadataItemHeader,\n type MetadataEvent,\n type PutOptions,\n type PutResult,\n type DeleteOptions,\n type DeleteResult,\n type ListFilter,\n type WatchFilter,\n type HistoryOptions,\n type MetadataType,\n hashSpec,\n ConflictError,\n refKey,\n} from '@objectstack/metadata-core';\nimport {\n type FsLayout,\n itemPath,\n parseItemPath,\n typeDir,\n logFile,\n} from './layout.js';\nimport { JsonlLog } from './jsonl-log.js';\nimport { KeyedMutex, createBroker, type EventBroker } from './sync.js';\nimport { createWatchIterable } from './watch-iterable.js';\n\nexport interface FileSystemRepositoryOptions {\n /** Absolute path to the metadata root directory. */\n root: string;\n /** Tenant/org. */\n org: string;\n /** Identity reported in events that originate from external FS edits. */\n fsActor?: string;\n /** Disable chokidar watcher (e.g. for read-only contexts). */\n disableWatch?: boolean;\n /** Optional clock injection for deterministic tests. */\n now?: () => Date;\n}\n\nconst matchRefFilter = (\n ref: MetaRef,\n filter: { org?: string; type?: MetadataType; name?: string },\n): boolean => {\n if (filter.org && filter.org !== ref.org) return false;\n if (filter.type && filter.type !== ref.type) return false;\n if (filter.name && filter.name !== ref.name) return false;\n return true;\n};\n\nconst matchEvent = (evt: MetadataEvent, filter: WatchFilter): boolean => matchRefFilter(evt.ref, filter);\n\nexport class FileSystemRepository implements MetadataRepository {\n private readonly layout: FsLayout;\n private readonly org: string;\n private readonly fsActor: string;\n private readonly disableWatch: boolean;\n private readonly now: () => Date;\n private readonly log: JsonlLog;\n private readonly mutex = new KeyedMutex();\n private readonly broker: EventBroker = createBroker(matchEvent);\n\n /** In-memory index: refKey → current hash (HEAD). */\n private readonly heads = new Map<string, string>();\n /** Next seq counter, hydrated from the log on `start()`. */\n private nextSeq = 1;\n /** Paths we wrote ourselves; suppress the resulting chokidar event. */\n private readonly selfWrites = new Set<string>();\n private watcher: FSWatcher | null = null;\n private started = false;\n\n constructor(opts: FileSystemRepositoryOptions) {\n this.org = opts.org;\n this.fsActor = opts.fsActor ?? 'fs';\n this.disableWatch = opts.disableWatch ?? false;\n this.now = opts.now ?? (() => new Date());\n this.layout = { root: path.resolve(opts.root) };\n this.log = new JsonlLog(logFile(this.layout));\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Attach the repository. **Creates nothing on disk** (#7000).\n *\n * Attaching is not a write. `start()` used to `mkdir` both the root and\n * `<root>/.objectstack/.log` unconditionally, which meant every read-only\n * boot that merely attaches a repository left a skeleton behind — most\n * visibly `os migrate plan`, a declared dry run, on a project that has\n * never been started. That is the same property #6743 ruled on for\n * `.objectstack/data/`: a dry run leaves nothing behind, and the existence\n * of `.objectstack/` has to stay a usable \"this project has been started\"\n * signal.\n *\n * Every read path below already treats a missing root as an empty\n * repository (`scanHeads` swallows ENOENT, `JsonlLog` guards on\n * `existsSync`, `get` guards on `existsSync`), so the root is materialized\n * by `ensureRoot()` on the first write instead.\n */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n\n // 1) Scan body files to build the head index. No-op on a missing root.\n await this.scanHeads();\n\n // 2) Hydrate nextSeq from the existing log. No-op on a missing log.\n const highest = await this.log.highestSeq();\n this.nextSeq = highest + 1;\n\n // 3) Start the watcher (unless disabled). chokidar cannot watch a path\n // that does not exist yet: measured on chokidar 5 with `usePolling`,\n // a root created AFTER `watch()` produces no events at all, ever. So\n // when the root is absent the watcher is armed later, by the\n // `ensureRoot()` call that brings the root into existence — otherwise\n // dropping the `mkdir` above would silently kill external-edit\n // detection for the whole life of the process.\n if (!this.disableWatch && existsSync(this.layout.root)) this.startWatcher();\n }\n\n /**\n * Bring the repository root into existence. Called by every write path\n * immediately before it touches the disk — `start()` deliberately does not\n * create it (#7000), so this is the single seam where the root appears.\n *\n * It is also where a watcher that `start()` could not arm (missing root)\n * gets armed, so \"external edits are detected\" survives the change.\n */\n private async ensureRoot(): Promise<void> {\n await fs.mkdir(this.layout.root, { recursive: true });\n if (this.started && !this.disableWatch && !this.watcher) this.startWatcher();\n }\n\n async close(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = null;\n }\n this.started = false;\n }\n\n // ── Read API ────────────────────────────────────────────────────────\n\n async get(ref: MetaRef): Promise<MetadataItem | null> {\n this.assertScope(ref);\n const file = itemPath(this.layout, ref.type, ref.name);\n if (!existsSync(file)) return null;\n const body = await readJson(file);\n if (!body) return null;\n const hash = hashSpec(body);\n if (ref.version && ref.version !== hash) return null;\n // Walk back through the log to populate parent/authoredBy/seq.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n ref: { ...ref, version: undefined },\n body: body as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n }\n\n async getByHash(ref: MetaRef, hash: string): Promise<MetadataItem | null> {\n // FS repo stores only HEAD bodies on disk; the JSONL log records\n // events (hashes) but not historical bodies. Resolve only if the\n // requested hash matches HEAD.\n const head = await this.get(ref);\n if (!head || head.hash !== hash) return null;\n return head;\n }\n\n async *list(filter: ListFilter): AsyncIterable<MetadataItemHeader> {\n const limit = filter.limit ?? Infinity;\n let yielded = 0;\n for (const [key, hash] of this.heads) {\n const ref = parseRefKey(key);\n if (!ref) continue;\n if (!matchRefFilter(ref, filter)) continue;\n if (filter.nameContains && !ref.name.includes(filter.nameContains)) continue;\n const meta = await this.findMetaForHash(ref, hash);\n const header: MetadataItemHeader = {\n ref: { ...ref, version: undefined },\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n yield header;\n if (++yielded >= limit) return;\n }\n }\n\n async *history(ref: MetaRef, opts: HistoryOptions = {}): AsyncIterable<MetadataEvent> {\n this.assertScope(ref);\n const since = opts.sinceSeq ?? -1;\n const limit = opts.limit ?? Infinity;\n let yielded = 0;\n for await (const evt of this.log.readAll()) {\n if (evt.seq <= since) continue;\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n yield evt;\n if (++yielded >= limit) return;\n }\n }\n\n watch(filter: WatchFilter, since?: number): AsyncIterable<MetadataEvent> {\n // Eagerly snapshot the existing log for replay; new events route via broker.\n const replay: MetadataEvent[] = [];\n const promise = (async () => {\n for await (const evt of this.log.readAll()) {\n if (matchEvent(evt, filter)) replay.push(evt);\n }\n })();\n // We must await replay before returning, but the public API is\n // sync-returning AsyncIterable. Wrap in a deferred iterable.\n return deferredIterable(promise.then(() =>\n createWatchIterable({\n filter,\n since,\n replay,\n broker: this.broker,\n matches: matchEvent,\n branchKeyOf: (e) => e.ref.org,\n }),\n ));\n }\n\n // ── Write API ───────────────────────────────────────────────────────\n\n put(ref: MetaRef, spec: unknown, opts: PutOptions): Promise<PutResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if ((opts.parentVersion ?? null) !== currentHead) {\n throw new ConflictError(ref, opts.parentVersion ?? null, currentHead);\n }\n const hash = hashSpec(spec);\n if (currentHead === hash) {\n // No-op write — same content.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n version: hash,\n seq: meta?.seq ?? 0,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? this.now().toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n },\n };\n }\n\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const file = itemPath(this.layout, ref.type, ref.name);\n // First write of the process materializes the root (#7000).\n await this.ensureRoot();\n await fs.mkdir(typeDir(this.layout, ref.type), { recursive: true });\n this.selfWrites.add(file);\n try {\n await writeJsonAtomic(file, spec);\n } finally {\n // Hold the suppression until chokidar has had a chance to emit;\n // we keep it in selfWrites for one debounce tick.\n setTimeout(() => this.selfWrites.delete(file), 200);\n }\n // The watcher must not depend on its own directory scan to notice a\n // path we created ourselves (#7282). See `trackWrittenPath`.\n this.trackWrittenPath(file);\n this.heads.set(key, hash);\n\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n\n return {\n version: hash,\n seq,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: currentHead,\n authoredBy: opts.actor,\n authoredAt: ts,\n message: opts.message,\n seq,\n },\n };\n });\n }\n\n delete(ref: MetaRef, opts: DeleteOptions): Promise<DeleteResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead !== opts.parentVersion) {\n throw new ConflictError(ref, opts.parentVersion, currentHead);\n }\n const file = itemPath(this.layout, ref.type, ref.name);\n // A delete appends a tombstone to the change log, so it is a write too.\n await this.ensureRoot();\n this.selfWrites.add(file);\n try {\n if (existsSync(file)) await fs.unlink(file);\n } finally {\n setTimeout(() => this.selfWrites.delete(file), 200);\n }\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return { seq };\n });\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private assertScope(ref: MetaRef): void {\n if (ref.org !== this.org) {\n throw new Error(\n `FileSystemRepository scope mismatch: expected org=${this.org}, got org=${ref.org}`,\n );\n }\n }\n\n private async scanHeads(): Promise<void> {\n this.heads.clear();\n // Walk one level deep: <root>/<type>/<name>.json\n let entries: import('node:fs').Dirent[] = [];\n try {\n entries = await fs.readdir(this.layout.root, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const type = entry.name;\n const dir = path.join(this.layout.root, type);\n let files: string[] = [];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const name = file.slice(0, -'.json'.length);\n const ref: MetaRef = {\n org: this.org,\n type: type as MetadataType,\n name,\n };\n const body = await readJson(path.join(dir, file));\n if (!body) continue;\n this.heads.set(refKey(ref), hashSpec(body));\n }\n }\n }\n\n private async findMetaForHash(\n ref: MetaRef,\n hash: string,\n ): Promise<MetadataEvent | null> {\n let last: MetadataEvent | null = null;\n for await (const evt of this.log.readAll()) {\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n if (evt.hash === hash) last = evt;\n }\n return last;\n }\n\n /**\n * Register a path this repository just wrote with the watcher (#7282).\n *\n * chokidar's initial scan is asynchronous, and every write path here can be\n * running **while it is still walking the tree** — `start()` arms the watcher\n * and the caller may `put()` on the next tick, and `ensureRoot()` arms it in\n * the middle of the very first write. With `usePolling` that combination has\n * a permanently-blinding interleaving, measured on chokidar 5 with this\n * repository's own options:\n *\n * 1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic\n * `rename` in `writeJsonAtomic` has not landed yet.\n * 2. the rename lands; the directory's mtime changes.\n * 3. chokidar calls `watchFile()` on that directory, and libuv takes its\n * polling baseline stat — which already reflects step 2.\n *\n * From then on the directory's stat never changes again, so no poll ever\n * fires for it, `_handleRead` never re-runs, the item file is never added to\n * the watched set, and no per-file watcher is ever created. chokidar emits\n * neither `add` nor `change` for that path **for the life of the process** —\n * `getWatched()` reports the type directory as `[]` forever while the file\n * sits in it. That is the whole of #7282: the four merge-queue ejections all\n * waited out their deadlines (20s, then 25541ms against 25s) on an event that\n * was never going to be delivered, which is why widening the deadline and\n * widening the pre-edit sleep both changed nothing, and why lowering\n * `interval` would change nothing either — a shorter poll re-compares against\n * the same unchanged directory stat.\n *\n * The window is exactly \"files that exist at baseline time but were absent\n * from the snapshot read a moment earlier\", and the only writer that can be\n * inside it is us. So we close it at the source: tell the watcher explicitly\n * about every path we create, instead of hoping its scan happened to see it.\n *\n * `add()` is idempotent here — `_handleFile` returns early when the parent\n * directory already tracks the basename — and it emits nothing, because\n * chokidar treats an explicit `add()` as an initial add and `ignoreInitial`\n * is set. Its effect is the one we need: `_watchWithNodeFs` registers the\n * basename with the parent directory (without which chokidar drops `change`\n * events for the file) and starts the per-file poll.\n */\n private trackWrittenPath(file: string): void {\n const w = this.watcher;\n // `add()` clears `closed`, so never hand a closing watcher a new path.\n if (!w || w.closed) return;\n w.add(file);\n }\n\n private startWatcher(): void {\n const root = this.layout.root;\n const w = chokidar.watch(root, {\n // Skip dotfiles under the root — including the repository's own\n // `.objectstack/` bookkeeping subtree — matched on the path RELATIVE\n // to the watch root (#7150). See `isIgnoredWatchPath`.\n ignored: (p: string) => isIgnoredWatchPath(root, p),\n ignoreInitial: true,\n depth: 2,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n // Use polling to avoid `fs.watch` EMFILE on macOS / busy dev hosts.\n // The depth-2 recursion would otherwise wire native watches across\n // the entire customization tree.\n usePolling: true,\n interval: 1000,\n binaryInterval: 2000,\n });\n w.on('add', (p) => void this.handleFsChange(p, 'add'));\n w.on('change', (p) => void this.handleFsChange(p, 'change'));\n w.on('unlink', (p) => void this.handleFsChange(p, 'unlink'));\n this.watcher = w;\n }\n\n private async handleFsChange(absPath: string, kind: 'add' | 'change' | 'unlink'): Promise<void> {\n if (this.selfWrites.has(absPath)) return; // Suppress our own writes.\n const parsed = parseItemPath(this.layout, absPath);\n if (!parsed) return;\n const ref: MetaRef = {\n org: this.org,\n type: parsed.type as MetadataType,\n name: parsed.name,\n };\n const key = refKey(ref);\n await this.mutex.run(key, async () => {\n if (kind === 'unlink') {\n const currentHead = this.heads.get(key) ?? null;\n if (!currentHead) return;\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return;\n }\n const body = await readJson(absPath);\n if (!body) return;\n const hash = hashSpec(body);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead === hash) return; // No content change.\n this.heads.set(key, hash);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n });\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────\n\n/**\n * Watcher ignore matcher — \"everything under the root, except the\n * repository's own bookkeeping\" (#7150).\n *\n * chokidar hands its matcher **absolute** paths, and applies it to the\n * watched root itself as well as to entries discovered underneath it. The\n * previous matcher was a bare dotfile regex (`/(^|[\\\\/])\\../`), which\n * therefore matched the `.objectstack` segment of the root path the plugin\n * actually uses (`<project>/.objectstack/metadata`, `REPO_SUBDIR` in\n * `packages/metadata/src/plugin.ts`) and ignored the whole watch. Measured on\n * chokidar 5 with this repository's own options, two identical trees\n * differing only in whether the root sits under a dot-directory:\n *\n * plain root getWatched: ['<root>', 'view'] events: add+change\n * dot-rooted getWatched: [] events: none\n *\n * So the intent is kept and only the *frame of reference* is fixed: judge the\n * path relative to the root, so dot segments belonging to the root itself are\n * never considered.\n *\n * Why not drop the matcher entirely and lean on `parseItemPath`, which already\n * rejects `.objectstack`? Measured: `parseItemPath` rejects that ONE name, so\n * a dot-directory at the type level leaks — `<root>/.cache/x.json` parses as\n * type `.cache`, and `<root>/view/.scratch.json` as an item named `.scratch`.\n * Both would be published as `MetadataEvent`s while `scanHeads` skips every\n * dot entry on boot, leaving the boot scan and the watcher disagreeing about\n * what the repository contains. Dropping it also puts `.objectstack/.log/` in\n * the poll set, so every one of the repository's own log appends wakes\n * `handleFsChange` only to be discarded.\n */\nfunction isIgnoredWatchPath(root: string, absPath: string): boolean {\n const rel = path.relative(root, absPath);\n // The watched root itself, and anything outside it, are not ours to judge.\n if (rel === '' || rel.startsWith('..')) return false;\n return rel.split(/[\\\\/]/).some((segment) => segment.startsWith('.'));\n}\n\nasync function readJson(file: string): Promise<unknown | null> {\n try {\n const text = await fs.readFile(file, 'utf8');\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nasync function writeJsonAtomic(file: string, body: unknown): Promise<void> {\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(body, null, 2) + '\\n', 'utf8');\n await fs.rename(tmp, file);\n}\n\nfunction parseRefKey(key: string): MetaRef | null {\n const parts = key.split('/');\n if (parts.length !== 3) return null;\n return {\n org: parts[0]!,\n type: parts[1]! as MetadataType,\n name: parts[2]!,\n };\n}\n\n/**\n * Wrap a Promise<AsyncIterable<T>> as a sync-returning AsyncIterable<T>.\n * The first `.next()` awaits the promise.\n */\nfunction deferredIterable<T>(promise: Promise<AsyncIterable<T>>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n let inner: AsyncIterator<T> | null = null;\n return {\n async next() {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n return inner.next();\n },\n async return(value?: unknown) {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n if (inner.return) return inner.return(value);\n return { value: undefined, done: true };\n },\n } as AsyncIterator<T>;\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Disk layout helpers — see ADR-0008 §10 PR-4 / packages/metadata-fs README.\n *\n * <root>/<type>/<name>.json — canonical body\n * <root>/.objectstack/.log/main.jsonl — append-only change log\n */\n\nimport path from 'node:path';\nimport type { MetadataType } from '@objectstack/metadata-core';\n\nexport interface FsLayout {\n /** Absolute path to the metadata root. */\n root: string;\n}\n\nexport function itemPath(layout: FsLayout, type: MetadataType, name: string): string {\n return path.join(layout.root, type, `${name}.json`);\n}\n\nexport function typeDir(layout: FsLayout, type: MetadataType): string {\n return path.join(layout.root, type);\n}\n\nexport function logDir(layout: FsLayout): string {\n return path.join(layout.root, '.objectstack', '.log');\n}\n\nexport function logFile(layout: FsLayout): string {\n // Single change log per filesystem root (branching is a Git concern,\n // not a metadata-layer concern).\n return path.join(logDir(layout), `main.jsonl`);\n}\n\n/** Parse a path like \".../view/case_grid.json\" into {type, name}. */\nexport function parseItemPath(\n layout: FsLayout,\n absPath: string,\n): { type: string; name: string } | null {\n const rel = path.relative(layout.root, absPath);\n if (rel.startsWith('..') || rel.startsWith('.objectstack')) return null;\n const segments = rel.split(path.sep);\n if (segments.length !== 2) return null;\n const type = segments[0]!;\n const file = segments[1]!;\n if (!file.endsWith('.json')) return null;\n const name = file.slice(0, -'.json'.length);\n return { type, name };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Append-only JSONL change log writer / reader. Each line is a single\n * `MetadataEvent` serialized via `JSON.stringify`.\n *\n * Durability strategy\n * ───────────────────\n * - Append with `O_APPEND` semantics (Node's `fs.appendFile` is\n * atomic for sub-PIPE_BUF-sized writes; events are well under 4 KiB).\n * - Read by streaming the file line-by-line and JSON.parse-ing each.\n * - On a corrupt line we skip and continue — the body files are the\n * source of truth; the log is a denormalised history index.\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport readline from 'node:readline';\nimport { createReadStream, existsSync } from 'node:fs';\nimport type { MetadataEvent } from '@objectstack/metadata-core';\n\nexport class JsonlLog {\n constructor(private readonly file: string) {}\n\n async append(evt: MetadataEvent): Promise<void> {\n await fs.mkdir(path.dirname(this.file), { recursive: true });\n await fs.appendFile(this.file, JSON.stringify(evt) + '\\n', 'utf8');\n }\n\n /** Read all events in seq order (i.e. file order). */\n async *readAll(): AsyncIterable<MetadataEvent> {\n if (!existsSync(this.file)) return;\n const rl = readline.createInterface({\n input: createReadStream(this.file, { encoding: 'utf8' }),\n crlfDelay: Infinity,\n });\n try {\n for await (const line of rl) {\n if (!line.trim()) continue;\n try {\n yield JSON.parse(line) as MetadataEvent;\n } catch {\n // Skip corrupt line.\n }\n }\n } finally {\n rl.close();\n }\n }\n\n /** Return the highest seq number in the log, or 0 if empty. */\n async highestSeq(): Promise<number> {\n let max = 0;\n for await (const evt of this.readAll()) {\n if (typeof evt.seq === 'number' && evt.seq > max) max = evt.seq;\n }\n return max;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Mutex / event-broker primitives used by FileSystemRepository.\n *\n * `KeyedMutex` serializes operations on the same key (refKey). The\n * broker re-uses the same manual-AsyncIterator pattern as\n * InMemoryRepository so that consumer `return()` reliably unblocks.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\n\nexport class KeyedMutex {\n private readonly tails = new Map<string, Promise<unknown>>();\n\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n // Save the swallowed-error tail so successive runs don't reject on\n // an unrelated prior failure.\n const swallowed = next.catch(() => undefined);\n this.tails.set(key, swallowed);\n try {\n return await next;\n } finally {\n // Best-effort cleanup: drop the entry if nothing newer was queued.\n if (this.tails.get(key) === swallowed) {\n this.tails.delete(key);\n }\n }\n }\n}\n\nexport interface BrokerSubscriber {\n filter: WatchFilter;\n closed: boolean;\n push(evt: MetadataEvent): void;\n}\n\nexport interface EventBroker {\n subscribe(sub: BrokerSubscriber): void;\n unsubscribe(sub: BrokerSubscriber): void;\n publish(evt: MetadataEvent): void;\n}\n\nexport function createBroker(matches: (evt: MetadataEvent, filter: WatchFilter) => boolean): EventBroker {\n const subs = new Set<BrokerSubscriber>();\n return {\n subscribe: (s) => { subs.add(s); },\n unsubscribe: (s) => { subs.delete(s); },\n publish: (evt) => {\n for (const s of subs) {\n if (s.closed) continue;\n if (!matches(evt, s.filter)) continue;\n s.push(evt);\n }\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Manual `AsyncIterator` factory for `repo.watch()`. Mirrors the\n * pattern used in `@objectstack/metadata-core`'s `InMemoryRepository`:\n * async generators do NOT run `finally` when paused on an unresolved\n * `await`, so we cannot use them to implement `watch()`.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\nimport { type EventBroker, type BrokerSubscriber } from './sync.js';\n\nexport interface CreateWatchIteratorArgs {\n filter: WatchFilter;\n since: number | undefined;\n replay: MetadataEvent[];\n broker: EventBroker;\n /** Returns true if `evt.ref` matches `filter`. */\n matches: (evt: MetadataEvent, filter: WatchFilter) => boolean;\n branchKeyOf: (evt: MetadataEvent) => string;\n}\n\nexport function createWatchIterable(\n args: CreateWatchIteratorArgs,\n): AsyncIterable<MetadataEvent> {\n const queue: MetadataEvent[] = [];\n let waiter: ((evt: IteratorResult<MetadataEvent>) => void) | null = null;\n let closed = false;\n const delivered = new Set<string>();\n const evtKey = (e: MetadataEvent) => `${args.branchKeyOf(e)}#${e.seq}`;\n\n const subscriber: BrokerSubscriber = {\n filter: args.filter,\n closed: false,\n push: (evt) => {\n if (subscriber.closed) return;\n const k = evtKey(evt);\n if (delivered.has(k)) return;\n if (waiter) {\n delivered.add(k);\n const w = waiter;\n waiter = null;\n w({ value: clone(evt), done: false });\n } else {\n queue.push(evt);\n }\n },\n };\n args.broker.subscribe(subscriber);\n\n const replay = [...args.replay].sort((a, b) => a.seq - b.seq);\n let replayIdx = 0;\n\n const drain = (): IteratorResult<MetadataEvent> | null => {\n while (replayIdx < replay.length) {\n const evt = replay[replayIdx++]!;\n if (typeof args.since === 'number' && evt.seq <= args.since) continue;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n while (queue.length > 0) {\n const evt = queue.shift()!;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n return null;\n };\n\n const close = (): IteratorResult<MetadataEvent> => {\n if (!closed) {\n closed = true;\n subscriber.closed = true;\n args.broker.unsubscribe(subscriber);\n if (waiter) {\n const w = waiter;\n waiter = null;\n w({ value: undefined, done: true });\n }\n }\n return { value: undefined, done: true };\n };\n\n const iterator: AsyncIterator<MetadataEvent> = {\n next: () => {\n if (closed) return Promise.resolve({ value: undefined, done: true });\n const immediate = drain();\n if (immediate) return Promise.resolve(immediate);\n return new Promise<IteratorResult<MetadataEvent>>((resolve) => {\n waiter = resolve;\n });\n },\n return: () => Promise.resolve(close()),\n throw: (err) => {\n close();\n return Promise.reject(err);\n },\n };\n return { [Symbol.asyncIterator]: () => iterator };\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,IAAAA,mBAAe;AACf,IAAAC,kBAA2B;AAC3B,IAAAC,oBAAiB;AAEjB,sBAAqB;AACrB,2BAiBO;;;ACpCP,uBAAiB;AAQV,SAAS,SAAS,QAAkB,MAAoB,MAAsB;AACnF,SAAO,iBAAAC,QAAK,KAAK,OAAO,MAAM,MAAM,GAAG,IAAI,OAAO;AACpD;AAEO,SAAS,QAAQ,QAAkB,MAA4B;AACpE,SAAO,iBAAAA,QAAK,KAAK,OAAO,MAAM,IAAI;AACpC;AAEO,SAAS,OAAO,QAA0B;AAC/C,SAAO,iBAAAA,QAAK,KAAK,OAAO,MAAM,gBAAgB,MAAM;AACtD;AAEO,SAAS,QAAQ,QAA0B;AAGhD,SAAO,iBAAAA,QAAK,KAAK,OAAO,MAAM,GAAG,YAAY;AAC/C;AAGO,SAAS,cACd,QACA,SACuC;AACvC,QAAM,MAAM,iBAAAA,QAAK,SAAS,OAAO,MAAM,OAAO;AAC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cAAI,MAAM,OAAQ,QAAO,MAAM,OAAO,KAAK;AAC3C,iBAAO,EAAE,OAAO,QAAW,MAAM,KAAK;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["import_promises","import_node_fs","import_node_path","path","import_node_path","fs","path","readline","path","fs","chokidar","currentHead","seq","evt"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/repository.ts","../src/layout.ts","../src/jsonl-log.ts","../src/sync.ts","../src/watch-iterable.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nexport * from './repository.js';\nexport { JsonlLog } from './jsonl-log.js';\nexport type { FsLayout } from './layout.js';\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `FileSystemRepository` — Node-only implementation of\n * `MetadataRepository` backed by JSON files plus a JSONL change log.\n *\n * See `README.md` for the on-disk layout and ADR-0008 §10 PR-4 for the\n * design rationale.\n *\n * Invariants\n * ──────────\n * - All `put` / `delete` ops serialize per-key via `KeyedMutex`.\n * - The change-log JSONL is the durable source of `seq`. On boot we\n * scan the log to learn the next seq value.\n * - Body files (`<type>/<name>.json`) are the source of truth; the\n * log is a denormalised history index.\n * - chokidar-driven external edits are translated into MetadataEvents\n * by hashing the new content and comparing to the last-known hash.\n * - The root directory is created **on the first write, not on attach**\n * (#7000). Attaching and reading a repository whose root does not exist\n * is legal and answers \"empty\"; see `start()` / `ensureRoot()`.\n */\n\nimport fs from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { FSWatcher } from 'chokidar';\nimport chokidar from 'chokidar';\nimport {\n type MetadataRepository,\n type MetaRef,\n type MetadataItem,\n type MetadataItemHeader,\n type MetadataEvent,\n type PutOptions,\n type PutResult,\n type DeleteOptions,\n type DeleteResult,\n type ListFilter,\n type WatchFilter,\n type HistoryOptions,\n type MetadataType,\n hashSpec,\n ConflictError,\n refKey,\n} from '@objectstack/metadata-core';\nimport {\n type FsLayout,\n itemPath,\n parseItemPath,\n typeDir,\n logFile,\n} from './layout.js';\nimport { JsonlLog } from './jsonl-log.js';\nimport { KeyedMutex, createBroker, type EventBroker } from './sync.js';\nimport { createWatchIterable } from './watch-iterable.js';\n\nexport interface FileSystemRepositoryOptions {\n /** Absolute path to the metadata root directory. */\n root: string;\n /** Tenant/org. */\n org: string;\n /** Identity reported in events that originate from external FS edits. */\n fsActor?: string;\n /** Disable chokidar watcher (e.g. for read-only contexts). */\n disableWatch?: boolean;\n /** Optional clock injection for deterministic tests. */\n now?: () => Date;\n}\n\nconst matchRefFilter = (\n ref: MetaRef,\n filter: { org?: string; type?: MetadataType; name?: string },\n): boolean => {\n if (filter.org && filter.org !== ref.org) return false;\n if (filter.type && filter.type !== ref.type) return false;\n if (filter.name && filter.name !== ref.name) return false;\n return true;\n};\n\nconst matchEvent = (evt: MetadataEvent, filter: WatchFilter): boolean => matchRefFilter(evt.ref, filter);\n\nexport class FileSystemRepository implements MetadataRepository {\n private readonly layout: FsLayout;\n private readonly org: string;\n private readonly fsActor: string;\n private readonly disableWatch: boolean;\n private readonly now: () => Date;\n private readonly log: JsonlLog;\n private readonly mutex = new KeyedMutex();\n private readonly broker: EventBroker = createBroker(matchEvent);\n\n /** In-memory index: refKey → current hash (HEAD). */\n private readonly heads = new Map<string, string>();\n /** Next seq counter, hydrated from the log on `start()`. */\n private nextSeq = 1;\n private watcher: FSWatcher | null = null;\n private started = false;\n\n constructor(opts: FileSystemRepositoryOptions) {\n this.org = opts.org;\n this.fsActor = opts.fsActor ?? 'fs';\n this.disableWatch = opts.disableWatch ?? false;\n this.now = opts.now ?? (() => new Date());\n this.layout = { root: path.resolve(opts.root) };\n this.log = new JsonlLog(logFile(this.layout));\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Attach the repository. **Creates nothing on disk** (#7000).\n *\n * Attaching is not a write. `start()` used to `mkdir` both the root and\n * `<root>/.objectstack/.log` unconditionally, which meant every read-only\n * boot that merely attaches a repository left a skeleton behind — most\n * visibly `os migrate plan`, a declared dry run, on a project that has\n * never been started. That is the same property #6743 ruled on for\n * `.objectstack/data/`: a dry run leaves nothing behind, and the existence\n * of `.objectstack/` has to stay a usable \"this project has been started\"\n * signal.\n *\n * Every read path below already treats a missing root as an empty\n * repository (`scanHeads` swallows ENOENT, `JsonlLog` guards on\n * `existsSync`, `get` guards on `existsSync`), so the root is materialized\n * by `ensureRoot()` on the first write instead.\n */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n\n // 1) Scan body files to build the head index. No-op on a missing root.\n await this.scanHeads();\n\n // 2) Hydrate nextSeq from the existing log. No-op on a missing log.\n const highest = await this.log.highestSeq();\n this.nextSeq = highest + 1;\n\n // 3) Start the watcher (unless disabled). chokidar cannot watch a path\n // that does not exist yet: measured on chokidar 5 with `usePolling`,\n // a root created AFTER `watch()` produces no events at all, ever. So\n // when the root is absent the watcher is armed later, by the\n // `ensureRoot()` call that brings the root into existence — otherwise\n // dropping the `mkdir` above would silently kill external-edit\n // detection for the whole life of the process.\n if (!this.disableWatch && existsSync(this.layout.root)) this.startWatcher();\n }\n\n /**\n * Bring the repository root into existence. Called by every write path\n * immediately before it touches the disk — `start()` deliberately does not\n * create it (#7000), so this is the single seam where the root appears.\n *\n * It is also where a watcher that `start()` could not arm (missing root)\n * gets armed, so \"external edits are detected\" survives the change.\n */\n private async ensureRoot(): Promise<void> {\n await fs.mkdir(this.layout.root, { recursive: true });\n if (this.started && !this.disableWatch && !this.watcher) this.startWatcher();\n }\n\n async close(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = null;\n }\n this.started = false;\n }\n\n // ── Read API ────────────────────────────────────────────────────────\n\n async get(ref: MetaRef): Promise<MetadataItem | null> {\n this.assertScope(ref);\n const file = itemPath(this.layout, ref.type, ref.name);\n if (!existsSync(file)) return null;\n const body = await readJson(file);\n if (!body) return null;\n const hash = hashSpec(body);\n if (ref.version && ref.version !== hash) return null;\n // Walk back through the log to populate parent/authoredBy/seq.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n ref: { ...ref, version: undefined },\n body: body as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n }\n\n async getByHash(ref: MetaRef, hash: string): Promise<MetadataItem | null> {\n // FS repo stores only HEAD bodies on disk; the JSONL log records\n // events (hashes) but not historical bodies. Resolve only if the\n // requested hash matches HEAD.\n const head = await this.get(ref);\n if (!head || head.hash !== hash) return null;\n return head;\n }\n\n async *list(filter: ListFilter): AsyncIterable<MetadataItemHeader> {\n const limit = filter.limit ?? Infinity;\n let yielded = 0;\n for (const [key, hash] of this.heads) {\n const ref = parseRefKey(key);\n if (!ref) continue;\n if (!matchRefFilter(ref, filter)) continue;\n if (filter.nameContains && !ref.name.includes(filter.nameContains)) continue;\n const meta = await this.findMetaForHash(ref, hash);\n const header: MetadataItemHeader = {\n ref: { ...ref, version: undefined },\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n yield header;\n if (++yielded >= limit) return;\n }\n }\n\n async *history(ref: MetaRef, opts: HistoryOptions = {}): AsyncIterable<MetadataEvent> {\n this.assertScope(ref);\n const since = opts.sinceSeq ?? -1;\n const limit = opts.limit ?? Infinity;\n let yielded = 0;\n for await (const evt of this.log.readAll()) {\n if (evt.seq <= since) continue;\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n yield evt;\n if (++yielded >= limit) return;\n }\n }\n\n watch(filter: WatchFilter, since?: number): AsyncIterable<MetadataEvent> {\n // Eagerly snapshot the existing log for replay; new events route via broker.\n const replay: MetadataEvent[] = [];\n const promise = (async () => {\n for await (const evt of this.log.readAll()) {\n if (matchEvent(evt, filter)) replay.push(evt);\n }\n })();\n // We must await replay before returning, but the public API is\n // sync-returning AsyncIterable. Wrap in a deferred iterable.\n return deferredIterable(promise.then(() =>\n createWatchIterable({\n filter,\n since,\n replay,\n broker: this.broker,\n matches: matchEvent,\n branchKeyOf: (e) => e.ref.org,\n }),\n ));\n }\n\n // ── Write API ───────────────────────────────────────────────────────\n\n put(ref: MetaRef, spec: unknown, opts: PutOptions): Promise<PutResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if ((opts.parentVersion ?? null) !== currentHead) {\n throw new ConflictError(ref, opts.parentVersion ?? null, currentHead);\n }\n const hash = hashSpec(spec);\n if (currentHead === hash) {\n // No-op write — same content.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n version: hash,\n seq: meta?.seq ?? 0,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? this.now().toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n },\n };\n }\n\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const file = itemPath(this.layout, ref.type, ref.name);\n // First write of the process materializes the root (#7000).\n await this.ensureRoot();\n await fs.mkdir(typeDir(this.layout, ref.type), { recursive: true });\n await writeJsonAtomic(file, spec);\n // The watcher must not depend on its own directory scan to notice a\n // path we created ourselves (#7282). See `trackWrittenPath`.\n this.trackWrittenPath(file);\n // Publishing the new head here is what suppresses the watcher event this\n // write is about to produce — see `handleFsChange` (#7335). It runs in\n // the same continuation as the `rename` above, and `awaitWriteFinish`\n // holds any event for a further `stabilityThreshold`, so the index is\n // always current by the time an event for this path can be delivered.\n this.heads.set(key, hash);\n\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n\n return {\n version: hash,\n seq,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: currentHead,\n authoredBy: opts.actor,\n authoredAt: ts,\n message: opts.message,\n seq,\n },\n };\n });\n }\n\n delete(ref: MetaRef, opts: DeleteOptions): Promise<DeleteResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead !== opts.parentVersion) {\n throw new ConflictError(ref, opts.parentVersion, currentHead);\n }\n const file = itemPath(this.layout, ref.type, ref.name);\n // A delete appends a tombstone to the change log, so it is a write too.\n await this.ensureRoot();\n // Retire the head BEFORE touching the disk, not after (#7335).\n //\n // `awaitWriteFinish` only debounces `add`/`change`; chokidar emits\n // `unlink` with no stability delay at all, so — unlike `put()` — this\n // face has no cushion between the disk mutation and the event it\n // produces. Clearing the index first makes `handleFsChange`'s\n // `if (!currentHead) return` a total suppression for our own removal\n // rather than a race against the poll callback.\n this.heads.delete(key);\n try {\n if (existsSync(file)) await fs.unlink(file);\n } catch (err) {\n // The disk still holds the item, so the index must too — otherwise a\n // failed delete would leave the repository claiming a file it can\n // still read. Restores exactly the pre-call state before rethrowing.\n if (currentHead !== null) this.heads.set(key, currentHead);\n throw err;\n }\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return { seq };\n });\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private assertScope(ref: MetaRef): void {\n if (ref.org !== this.org) {\n throw new Error(\n `FileSystemRepository scope mismatch: expected org=${this.org}, got org=${ref.org}`,\n );\n }\n }\n\n private async scanHeads(): Promise<void> {\n this.heads.clear();\n // Walk one level deep: <root>/<type>/<name>.json\n let entries: import('node:fs').Dirent[] = [];\n try {\n entries = await fs.readdir(this.layout.root, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const type = entry.name;\n const dir = path.join(this.layout.root, type);\n let files: string[] = [];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const name = file.slice(0, -'.json'.length);\n const ref: MetaRef = {\n org: this.org,\n type: type as MetadataType,\n name,\n };\n const body = await readJson(path.join(dir, file));\n if (!body) continue;\n this.heads.set(refKey(ref), hashSpec(body));\n }\n }\n }\n\n private async findMetaForHash(\n ref: MetaRef,\n hash: string,\n ): Promise<MetadataEvent | null> {\n let last: MetadataEvent | null = null;\n for await (const evt of this.log.readAll()) {\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n if (evt.hash === hash) last = evt;\n }\n return last;\n }\n\n /**\n * Register a path this repository just wrote with the watcher (#7282).\n *\n * chokidar's initial scan is asynchronous, and every write path here can be\n * running **while it is still walking the tree** — `start()` arms the watcher\n * and the caller may `put()` on the next tick, and `ensureRoot()` arms it in\n * the middle of the very first write. With `usePolling` that combination has\n * a permanently-blinding interleaving, measured on chokidar 5 with this\n * repository's own options:\n *\n * 1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic\n * `rename` in `writeJsonAtomic` has not landed yet.\n * 2. the rename lands; the directory's mtime changes.\n * 3. chokidar calls `watchFile()` on that directory, and libuv takes its\n * polling baseline stat — which already reflects step 2.\n *\n * From then on the directory's stat never changes again, so no poll ever\n * fires for it, `_handleRead` never re-runs, the item file is never added to\n * the watched set, and no per-file watcher is ever created. chokidar emits\n * neither `add` nor `change` for that path **for the life of the process** —\n * `getWatched()` reports the type directory as `[]` forever while the file\n * sits in it. That is the whole of #7282: the four merge-queue ejections all\n * waited out their deadlines (20s, then 25541ms against 25s) on an event that\n * was never going to be delivered, which is why widening the deadline and\n * widening the pre-edit sleep both changed nothing, and why lowering\n * `interval` would change nothing either — a shorter poll re-compares against\n * the same unchanged directory stat.\n *\n * The window is exactly \"files that exist at baseline time but were absent\n * from the snapshot read a moment earlier\", and the only writer that can be\n * inside it is us. So we close it at the source: tell the watcher explicitly\n * about every path we create, instead of hoping its scan happened to see it.\n *\n * `add()` is idempotent here — `_handleFile` returns early when the parent\n * directory already tracks the basename — and it emits nothing, because\n * chokidar treats an explicit `add()` as an initial add and `ignoreInitial`\n * is set. Its effect is the one we need: `_watchWithNodeFs` registers the\n * basename with the parent directory (without which chokidar drops `change`\n * events for the file) and starts the per-file poll.\n */\n private trackWrittenPath(file: string): void {\n const w = this.watcher;\n // `add()` clears `closed`, so never hand a closing watcher a new path.\n if (!w || w.closed) return;\n w.add(file);\n }\n\n private startWatcher(): void {\n const root = this.layout.root;\n const w = chokidar.watch(root, {\n // Skip dotfiles under the root — including the repository's own\n // `.objectstack/` bookkeeping subtree — matched on the path RELATIVE\n // to the watch root (#7150). See `isIgnoredWatchPath`.\n ignored: (p: string) => isIgnoredWatchPath(root, p),\n ignoreInitial: true,\n depth: 2,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n // Use polling to avoid `fs.watch` EMFILE on macOS / busy dev hosts.\n // The depth-2 recursion would otherwise wire native watches across\n // the entire customization tree.\n usePolling: true,\n interval: 1000,\n binaryInterval: 2000,\n });\n w.on('add', (p) => void this.handleFsChange(p, 'add'));\n w.on('change', (p) => void this.handleFsChange(p, 'change'));\n w.on('unlink', (p) => void this.handleFsChange(p, 'unlink'));\n this.watcher = w;\n }\n\n /**\n * Translate a watcher event into a `MetadataEvent`, or drop it.\n *\n * ## Self-writes are suppressed by content identity, never by a clock (#7335)\n *\n * This used to open with `if (this.selfWrites.has(absPath)) return;` — a\n * `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`\n * cleared. That check discarded **every** event for a recently-written path\n * without ever looking at what the watcher had actually observed, which is\n * the whole defect: with `usePolling`, chokidar compares state once per\n * `interval`, so our write and an external edit landing between two ticks\n * are delivered as **one** event carrying the *external* content. Dropping\n * it on a wall clock destroyed the only notification that edit would ever\n * produce.\n *\n * Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase\n * randomised so the delivery lag samples `[0, interval)` uniformly:\n *\n * delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time\n * delivery lag > 200ms → 33 runs → external edit delivered, every time\n *\n * A perfect split on the wall-clock boundary, and the reason earlier\n * instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,\n * pinning the lag (measured: 519–585ms across 25 runs) safely outside the\n * window. Nothing about the window was rare — it was unsampled.\n *\n * What remains is the check that was already doing the real work one step\n * down, and it needs no timer because it compares the content the watcher\n * **read** against the index:\n *\n * - `add`/`change` — `currentHead === hash` drops the event when the bytes\n * on disk are the bytes we last published. `put()` sets that head in the\n * same continuation as its `rename`, and `awaitWriteFinish` holds the\n * event for a further `stabilityThreshold`, so it is never late.\n * - `unlink` — `!currentHead` drops the event when the index already\n * agrees the item is gone. `delete()` retires the head *before* it\n * unlinks, precisely because this face gets no `awaitWriteFinish` delay.\n *\n * Both faces are pinned together in `test/self-write-suppression.test.ts`.\n *\n * Note the deliberate limit: identity is judged on what round-trips through\n * the file, so a spec whose in-memory form does not (a `Date`, which\n * canonicalises to `{}` in memory but to an ISO string once written and\n * re-read) is republished as an external `update`. That predates this change\n * and is independent of it — such a spec already fails `put().version ===\n * get().hash`, and the 200ms window never covered it either, expiring some\n * 360ms before the event it would have had to catch.\n */\n private async handleFsChange(absPath: string, kind: 'add' | 'change' | 'unlink'): Promise<void> {\n const parsed = parseItemPath(this.layout, absPath);\n if (!parsed) return;\n const ref: MetaRef = {\n org: this.org,\n type: parsed.type as MetadataType,\n name: parsed.name,\n };\n const key = refKey(ref);\n await this.mutex.run(key, async () => {\n if (kind === 'unlink') {\n const currentHead = this.heads.get(key) ?? null;\n if (!currentHead) return;\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return;\n }\n const body = await readJson(absPath);\n if (!body) return;\n const hash = hashSpec(body);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead === hash) return; // No content change.\n this.heads.set(key, hash);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n });\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────\n\n/**\n * Watcher ignore matcher — \"everything under the root, except the\n * repository's own bookkeeping\" (#7150).\n *\n * chokidar hands its matcher **absolute** paths, and applies it to the\n * watched root itself as well as to entries discovered underneath it. The\n * previous matcher was a bare dotfile regex (`/(^|[\\\\/])\\../`), which\n * therefore matched the `.objectstack` segment of the root path the plugin\n * actually uses (`<project>/.objectstack/metadata`, `REPO_SUBDIR` in\n * `packages/metadata/src/plugin.ts`) and ignored the whole watch. Measured on\n * chokidar 5 with this repository's own options, two identical trees\n * differing only in whether the root sits under a dot-directory:\n *\n * plain root getWatched: ['<root>', 'view'] events: add+change\n * dot-rooted getWatched: [] events: none\n *\n * So the intent is kept and only the *frame of reference* is fixed: judge the\n * path relative to the root, so dot segments belonging to the root itself are\n * never considered.\n *\n * Why not drop the matcher entirely and lean on `parseItemPath`, which already\n * rejects `.objectstack`? Measured: `parseItemPath` rejects that ONE name, so\n * a dot-directory at the type level leaks — `<root>/.cache/x.json` parses as\n * type `.cache`, and `<root>/view/.scratch.json` as an item named `.scratch`.\n * Both would be published as `MetadataEvent`s while `scanHeads` skips every\n * dot entry on boot, leaving the boot scan and the watcher disagreeing about\n * what the repository contains. Dropping it also puts `.objectstack/.log/` in\n * the poll set, so every one of the repository's own log appends wakes\n * `handleFsChange` only to be discarded.\n */\nfunction isIgnoredWatchPath(root: string, absPath: string): boolean {\n const rel = path.relative(root, absPath);\n // The watched root itself, and anything outside it, are not ours to judge.\n if (rel === '' || rel.startsWith('..')) return false;\n return rel.split(/[\\\\/]/).some((segment) => segment.startsWith('.'));\n}\n\nasync function readJson(file: string): Promise<unknown | null> {\n try {\n const text = await fs.readFile(file, 'utf8');\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nasync function writeJsonAtomic(file: string, body: unknown): Promise<void> {\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(body, null, 2) + '\\n', 'utf8');\n await fs.rename(tmp, file);\n}\n\nfunction parseRefKey(key: string): MetaRef | null {\n const parts = key.split('/');\n if (parts.length !== 3) return null;\n return {\n org: parts[0]!,\n type: parts[1]! as MetadataType,\n name: parts[2]!,\n };\n}\n\n/**\n * Wrap a Promise<AsyncIterable<T>> as a sync-returning AsyncIterable<T>.\n * The first `.next()` awaits the promise.\n */\nfunction deferredIterable<T>(promise: Promise<AsyncIterable<T>>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n let inner: AsyncIterator<T> | null = null;\n return {\n async next() {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n return inner.next();\n },\n async return(value?: unknown) {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n if (inner.return) return inner.return(value);\n return { value: undefined, done: true };\n },\n } as AsyncIterator<T>;\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Disk layout helpers — see ADR-0008 §10 PR-4 / packages/metadata-fs README.\n *\n * <root>/<type>/<name>.json — canonical body\n * <root>/.objectstack/.log/main.jsonl — append-only change log\n */\n\nimport path from 'node:path';\nimport type { MetadataType } from '@objectstack/metadata-core';\n\nexport interface FsLayout {\n /** Absolute path to the metadata root. */\n root: string;\n}\n\nexport function itemPath(layout: FsLayout, type: MetadataType, name: string): string {\n return path.join(layout.root, type, `${name}.json`);\n}\n\nexport function typeDir(layout: FsLayout, type: MetadataType): string {\n return path.join(layout.root, type);\n}\n\nexport function logDir(layout: FsLayout): string {\n return path.join(layout.root, '.objectstack', '.log');\n}\n\nexport function logFile(layout: FsLayout): string {\n // Single change log per filesystem root (branching is a Git concern,\n // not a metadata-layer concern).\n return path.join(logDir(layout), `main.jsonl`);\n}\n\n/** Parse a path like \".../view/case_grid.json\" into {type, name}. */\nexport function parseItemPath(\n layout: FsLayout,\n absPath: string,\n): { type: string; name: string } | null {\n const rel = path.relative(layout.root, absPath);\n if (rel.startsWith('..') || rel.startsWith('.objectstack')) return null;\n const segments = rel.split(path.sep);\n if (segments.length !== 2) return null;\n const type = segments[0]!;\n const file = segments[1]!;\n if (!file.endsWith('.json')) return null;\n const name = file.slice(0, -'.json'.length);\n return { type, name };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Append-only JSONL change log writer / reader. Each line is a single\n * `MetadataEvent` serialized via `JSON.stringify`.\n *\n * Durability strategy\n * ───────────────────\n * - Append with `O_APPEND` semantics (Node's `fs.appendFile` is\n * atomic for sub-PIPE_BUF-sized writes; events are well under 4 KiB).\n * - Read by streaming the file line-by-line and JSON.parse-ing each.\n * - On a corrupt line we skip and continue — the body files are the\n * source of truth; the log is a denormalised history index.\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport readline from 'node:readline';\nimport { createReadStream, existsSync } from 'node:fs';\nimport type { MetadataEvent } from '@objectstack/metadata-core';\n\nexport class JsonlLog {\n constructor(private readonly file: string) {}\n\n async append(evt: MetadataEvent): Promise<void> {\n await fs.mkdir(path.dirname(this.file), { recursive: true });\n await fs.appendFile(this.file, JSON.stringify(evt) + '\\n', 'utf8');\n }\n\n /** Read all events in seq order (i.e. file order). */\n async *readAll(): AsyncIterable<MetadataEvent> {\n if (!existsSync(this.file)) return;\n const rl = readline.createInterface({\n input: createReadStream(this.file, { encoding: 'utf8' }),\n crlfDelay: Infinity,\n });\n try {\n for await (const line of rl) {\n if (!line.trim()) continue;\n try {\n yield JSON.parse(line) as MetadataEvent;\n } catch {\n // Skip corrupt line.\n }\n }\n } finally {\n rl.close();\n }\n }\n\n /** Return the highest seq number in the log, or 0 if empty. */\n async highestSeq(): Promise<number> {\n let max = 0;\n for await (const evt of this.readAll()) {\n if (typeof evt.seq === 'number' && evt.seq > max) max = evt.seq;\n }\n return max;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Mutex / event-broker primitives used by FileSystemRepository.\n *\n * `KeyedMutex` serializes operations on the same key (refKey). The\n * broker re-uses the same manual-AsyncIterator pattern as\n * InMemoryRepository so that consumer `return()` reliably unblocks.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\n\nexport class KeyedMutex {\n private readonly tails = new Map<string, Promise<unknown>>();\n\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n // Save the swallowed-error tail so successive runs don't reject on\n // an unrelated prior failure.\n const swallowed = next.catch(() => undefined);\n this.tails.set(key, swallowed);\n try {\n return await next;\n } finally {\n // Best-effort cleanup: drop the entry if nothing newer was queued.\n if (this.tails.get(key) === swallowed) {\n this.tails.delete(key);\n }\n }\n }\n}\n\nexport interface BrokerSubscriber {\n filter: WatchFilter;\n closed: boolean;\n push(evt: MetadataEvent): void;\n}\n\nexport interface EventBroker {\n subscribe(sub: BrokerSubscriber): void;\n unsubscribe(sub: BrokerSubscriber): void;\n publish(evt: MetadataEvent): void;\n}\n\nexport function createBroker(matches: (evt: MetadataEvent, filter: WatchFilter) => boolean): EventBroker {\n const subs = new Set<BrokerSubscriber>();\n return {\n subscribe: (s) => { subs.add(s); },\n unsubscribe: (s) => { subs.delete(s); },\n publish: (evt) => {\n for (const s of subs) {\n if (s.closed) continue;\n if (!matches(evt, s.filter)) continue;\n s.push(evt);\n }\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Manual `AsyncIterator` factory for `repo.watch()`. Mirrors the\n * pattern used in `@objectstack/metadata-core`'s `InMemoryRepository`:\n * async generators do NOT run `finally` when paused on an unresolved\n * `await`, so we cannot use them to implement `watch()`.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\nimport { type EventBroker, type BrokerSubscriber } from './sync.js';\n\nexport interface CreateWatchIteratorArgs {\n filter: WatchFilter;\n since: number | undefined;\n replay: MetadataEvent[];\n broker: EventBroker;\n /** Returns true if `evt.ref` matches `filter`. */\n matches: (evt: MetadataEvent, filter: WatchFilter) => boolean;\n branchKeyOf: (evt: MetadataEvent) => string;\n}\n\nexport function createWatchIterable(\n args: CreateWatchIteratorArgs,\n): AsyncIterable<MetadataEvent> {\n const queue: MetadataEvent[] = [];\n let waiter: ((evt: IteratorResult<MetadataEvent>) => void) | null = null;\n let closed = false;\n const delivered = new Set<string>();\n const evtKey = (e: MetadataEvent) => `${args.branchKeyOf(e)}#${e.seq}`;\n\n const subscriber: BrokerSubscriber = {\n filter: args.filter,\n closed: false,\n push: (evt) => {\n if (subscriber.closed) return;\n const k = evtKey(evt);\n if (delivered.has(k)) return;\n if (waiter) {\n delivered.add(k);\n const w = waiter;\n waiter = null;\n w({ value: clone(evt), done: false });\n } else {\n queue.push(evt);\n }\n },\n };\n args.broker.subscribe(subscriber);\n\n const replay = [...args.replay].sort((a, b) => a.seq - b.seq);\n let replayIdx = 0;\n\n const drain = (): IteratorResult<MetadataEvent> | null => {\n while (replayIdx < replay.length) {\n const evt = replay[replayIdx++]!;\n if (typeof args.since === 'number' && evt.seq <= args.since) continue;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n while (queue.length > 0) {\n const evt = queue.shift()!;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n return null;\n };\n\n const close = (): IteratorResult<MetadataEvent> => {\n if (!closed) {\n closed = true;\n subscriber.closed = true;\n args.broker.unsubscribe(subscriber);\n if (waiter) {\n const w = waiter;\n waiter = null;\n w({ value: undefined, done: true });\n }\n }\n return { value: undefined, done: true };\n };\n\n const iterator: AsyncIterator<MetadataEvent> = {\n next: () => {\n if (closed) return Promise.resolve({ value: undefined, done: true });\n const immediate = drain();\n if (immediate) return Promise.resolve(immediate);\n return new Promise<IteratorResult<MetadataEvent>>((resolve) => {\n waiter = resolve;\n });\n },\n return: () => Promise.resolve(close()),\n throw: (err) => {\n close();\n return Promise.reject(err);\n },\n };\n return { [Symbol.asyncIterator]: () => iterator };\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBA,IAAAA,mBAAe;AACf,IAAAC,kBAA2B;AAC3B,IAAAC,oBAAiB;AAEjB,sBAAqB;AACrB,2BAiBO;;;ACpCP,uBAAiB;AAQV,SAAS,SAAS,QAAkB,MAAoB,MAAsB;AACnF,SAAO,iBAAAC,QAAK,KAAK,OAAO,MAAM,MAAM,GAAG,IAAI,OAAO;AACpD;AAEO,SAAS,QAAQ,QAAkB,MAA4B;AACpE,SAAO,iBAAAA,QAAK,KAAK,OAAO,MAAM,IAAI;AACpC;AAEO,SAAS,OAAO,QAA0B;AAC/C,SAAO,iBAAAA,QAAK,KAAK,OAAO,MAAM,gBAAgB,MAAM;AACtD;AAEO,SAAS,QAAQ,QAA0B;AAGhD,SAAO,iBAAAA,QAAK,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O,aAAa,EAAE;AAAA,UACzC;AACA,iBAAO,MAAM,KAAK;AAAA,QACpB;AAAA,QACA,MAAM,OAAO,OAAiB;AAC5B,cAAI,CAAC,OAAO;AACV,kBAAM,WAAW,MAAM;AACvB,oBAAQ,SAAS,OAAO,aAAa,EAAE;AAAA,UACzC;AACA,cAAI,MAAM,OAAQ,QAAO,MAAM,OAAO,KAAK;AAC3C,iBAAO,EAAE,OAAO,QAAW,MAAM,KAAK;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["import_promises","import_node_fs","import_node_path","path","import_node_path","fs","path","readline","path","fs","chokidar","currentHead","seq","evt"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -25,8 +25,6 @@ declare class FileSystemRepository implements MetadataRepository {
|
|
|
25
25
|
private readonly heads;
|
|
26
26
|
/** Next seq counter, hydrated from the log on `start()`. */
|
|
27
27
|
private nextSeq;
|
|
28
|
-
/** Paths we wrote ourselves; suppress the resulting chokidar event. */
|
|
29
|
-
private readonly selfWrites;
|
|
30
28
|
private watcher;
|
|
31
29
|
private started;
|
|
32
30
|
constructor(opts: FileSystemRepositoryOptions);
|
|
@@ -110,6 +108,54 @@ declare class FileSystemRepository implements MetadataRepository {
|
|
|
110
108
|
*/
|
|
111
109
|
private trackWrittenPath;
|
|
112
110
|
private startWatcher;
|
|
111
|
+
/**
|
|
112
|
+
* Translate a watcher event into a `MetadataEvent`, or drop it.
|
|
113
|
+
*
|
|
114
|
+
* ## Self-writes are suppressed by content identity, never by a clock (#7335)
|
|
115
|
+
*
|
|
116
|
+
* This used to open with `if (this.selfWrites.has(absPath)) return;` — a
|
|
117
|
+
* `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`
|
|
118
|
+
* cleared. That check discarded **every** event for a recently-written path
|
|
119
|
+
* without ever looking at what the watcher had actually observed, which is
|
|
120
|
+
* the whole defect: with `usePolling`, chokidar compares state once per
|
|
121
|
+
* `interval`, so our write and an external edit landing between two ticks
|
|
122
|
+
* are delivered as **one** event carrying the *external* content. Dropping
|
|
123
|
+
* it on a wall clock destroyed the only notification that edit would ever
|
|
124
|
+
* produce.
|
|
125
|
+
*
|
|
126
|
+
* Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase
|
|
127
|
+
* randomised so the delivery lag samples `[0, interval)` uniformly:
|
|
128
|
+
*
|
|
129
|
+
* delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time
|
|
130
|
+
* delivery lag > 200ms → 33 runs → external edit delivered, every time
|
|
131
|
+
*
|
|
132
|
+
* A perfect split on the wall-clock boundary, and the reason earlier
|
|
133
|
+
* instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,
|
|
134
|
+
* pinning the lag (measured: 519–585ms across 25 runs) safely outside the
|
|
135
|
+
* window. Nothing about the window was rare — it was unsampled.
|
|
136
|
+
*
|
|
137
|
+
* What remains is the check that was already doing the real work one step
|
|
138
|
+
* down, and it needs no timer because it compares the content the watcher
|
|
139
|
+
* **read** against the index:
|
|
140
|
+
*
|
|
141
|
+
* - `add`/`change` — `currentHead === hash` drops the event when the bytes
|
|
142
|
+
* on disk are the bytes we last published. `put()` sets that head in the
|
|
143
|
+
* same continuation as its `rename`, and `awaitWriteFinish` holds the
|
|
144
|
+
* event for a further `stabilityThreshold`, so it is never late.
|
|
145
|
+
* - `unlink` — `!currentHead` drops the event when the index already
|
|
146
|
+
* agrees the item is gone. `delete()` retires the head *before* it
|
|
147
|
+
* unlinks, precisely because this face gets no `awaitWriteFinish` delay.
|
|
148
|
+
*
|
|
149
|
+
* Both faces are pinned together in `test/self-write-suppression.test.ts`.
|
|
150
|
+
*
|
|
151
|
+
* Note the deliberate limit: identity is judged on what round-trips through
|
|
152
|
+
* the file, so a spec whose in-memory form does not (a `Date`, which
|
|
153
|
+
* canonicalises to `{}` in memory but to an ISO string once written and
|
|
154
|
+
* re-read) is republished as an external `update`. That predates this change
|
|
155
|
+
* and is independent of it — such a spec already fails `put().version ===
|
|
156
|
+
* get().hash`, and the 200ms window never covered it either, expiring some
|
|
157
|
+
* 360ms before the event it would have had to catch.
|
|
158
|
+
*/
|
|
113
159
|
private handleFsChange;
|
|
114
160
|
}
|
|
115
161
|
|
package/dist/index.d.ts
CHANGED
|
@@ -25,8 +25,6 @@ declare class FileSystemRepository implements MetadataRepository {
|
|
|
25
25
|
private readonly heads;
|
|
26
26
|
/** Next seq counter, hydrated from the log on `start()`. */
|
|
27
27
|
private nextSeq;
|
|
28
|
-
/** Paths we wrote ourselves; suppress the resulting chokidar event. */
|
|
29
|
-
private readonly selfWrites;
|
|
30
28
|
private watcher;
|
|
31
29
|
private started;
|
|
32
30
|
constructor(opts: FileSystemRepositoryOptions);
|
|
@@ -110,6 +108,54 @@ declare class FileSystemRepository implements MetadataRepository {
|
|
|
110
108
|
*/
|
|
111
109
|
private trackWrittenPath;
|
|
112
110
|
private startWatcher;
|
|
111
|
+
/**
|
|
112
|
+
* Translate a watcher event into a `MetadataEvent`, or drop it.
|
|
113
|
+
*
|
|
114
|
+
* ## Self-writes are suppressed by content identity, never by a clock (#7335)
|
|
115
|
+
*
|
|
116
|
+
* This used to open with `if (this.selfWrites.has(absPath)) return;` — a
|
|
117
|
+
* `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`
|
|
118
|
+
* cleared. That check discarded **every** event for a recently-written path
|
|
119
|
+
* without ever looking at what the watcher had actually observed, which is
|
|
120
|
+
* the whole defect: with `usePolling`, chokidar compares state once per
|
|
121
|
+
* `interval`, so our write and an external edit landing between two ticks
|
|
122
|
+
* are delivered as **one** event carrying the *external* content. Dropping
|
|
123
|
+
* it on a wall clock destroyed the only notification that edit would ever
|
|
124
|
+
* produce.
|
|
125
|
+
*
|
|
126
|
+
* Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase
|
|
127
|
+
* randomised so the delivery lag samples `[0, interval)` uniformly:
|
|
128
|
+
*
|
|
129
|
+
* delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time
|
|
130
|
+
* delivery lag > 200ms → 33 runs → external edit delivered, every time
|
|
131
|
+
*
|
|
132
|
+
* A perfect split on the wall-clock boundary, and the reason earlier
|
|
133
|
+
* instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,
|
|
134
|
+
* pinning the lag (measured: 519–585ms across 25 runs) safely outside the
|
|
135
|
+
* window. Nothing about the window was rare — it was unsampled.
|
|
136
|
+
*
|
|
137
|
+
* What remains is the check that was already doing the real work one step
|
|
138
|
+
* down, and it needs no timer because it compares the content the watcher
|
|
139
|
+
* **read** against the index:
|
|
140
|
+
*
|
|
141
|
+
* - `add`/`change` — `currentHead === hash` drops the event when the bytes
|
|
142
|
+
* on disk are the bytes we last published. `put()` sets that head in the
|
|
143
|
+
* same continuation as its `rename`, and `awaitWriteFinish` holds the
|
|
144
|
+
* event for a further `stabilityThreshold`, so it is never late.
|
|
145
|
+
* - `unlink` — `!currentHead` drops the event when the index already
|
|
146
|
+
* agrees the item is gone. `delete()` retires the head *before* it
|
|
147
|
+
* unlinks, precisely because this face gets no `awaitWriteFinish` delay.
|
|
148
|
+
*
|
|
149
|
+
* Both faces are pinned together in `test/self-write-suppression.test.ts`.
|
|
150
|
+
*
|
|
151
|
+
* Note the deliberate limit: identity is judged on what round-trips through
|
|
152
|
+
* the file, so a spec whose in-memory form does not (a `Date`, which
|
|
153
|
+
* canonicalises to `{}` in memory but to an ISO string once written and
|
|
154
|
+
* re-read) is republished as an external `update`. That predates this change
|
|
155
|
+
* and is independent of it — such a spec already fails `put().version ===
|
|
156
|
+
* get().hash`, and the 200ms window never covered it either, expiring some
|
|
157
|
+
* 360ms before the event it would have had to catch.
|
|
158
|
+
*/
|
|
113
159
|
private handleFsChange;
|
|
114
160
|
}
|
|
115
161
|
|
package/dist/index.js
CHANGED
|
@@ -210,8 +210,6 @@ var FileSystemRepository = class {
|
|
|
210
210
|
this.heads = /* @__PURE__ */ new Map();
|
|
211
211
|
/** Next seq counter, hydrated from the log on `start()`. */
|
|
212
212
|
this.nextSeq = 1;
|
|
213
|
-
/** Paths we wrote ourselves; suppress the resulting chokidar event. */
|
|
214
|
-
this.selfWrites = /* @__PURE__ */ new Set();
|
|
215
213
|
this.watcher = null;
|
|
216
214
|
this.started = false;
|
|
217
215
|
this.org = opts.org;
|
|
@@ -377,12 +375,7 @@ var FileSystemRepository = class {
|
|
|
377
375
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
378
376
|
await this.ensureRoot();
|
|
379
377
|
await fs2.mkdir(typeDir(this.layout, ref.type), { recursive: true });
|
|
380
|
-
|
|
381
|
-
try {
|
|
382
|
-
await writeJsonAtomic(file, spec);
|
|
383
|
-
} finally {
|
|
384
|
-
setTimeout(() => this.selfWrites.delete(file), 200);
|
|
385
|
-
}
|
|
378
|
+
await writeJsonAtomic(file, spec);
|
|
386
379
|
this.trackWrittenPath(file);
|
|
387
380
|
this.heads.set(key, hash);
|
|
388
381
|
const evt = {
|
|
@@ -424,13 +417,13 @@ var FileSystemRepository = class {
|
|
|
424
417
|
}
|
|
425
418
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
426
419
|
await this.ensureRoot();
|
|
427
|
-
this.
|
|
420
|
+
this.heads.delete(key);
|
|
428
421
|
try {
|
|
429
422
|
if (existsSync2(file)) await fs2.unlink(file);
|
|
430
|
-
}
|
|
431
|
-
|
|
423
|
+
} catch (err) {
|
|
424
|
+
if (currentHead !== null) this.heads.set(key, currentHead);
|
|
425
|
+
throw err;
|
|
432
426
|
}
|
|
433
|
-
this.heads.delete(key);
|
|
434
427
|
const seq = this.nextSeq++;
|
|
435
428
|
const ts = this.now().toISOString();
|
|
436
429
|
const evt = {
|
|
@@ -566,8 +559,55 @@ var FileSystemRepository = class {
|
|
|
566
559
|
w.on("unlink", (p) => void this.handleFsChange(p, "unlink"));
|
|
567
560
|
this.watcher = w;
|
|
568
561
|
}
|
|
562
|
+
/**
|
|
563
|
+
* Translate a watcher event into a `MetadataEvent`, or drop it.
|
|
564
|
+
*
|
|
565
|
+
* ## Self-writes are suppressed by content identity, never by a clock (#7335)
|
|
566
|
+
*
|
|
567
|
+
* This used to open with `if (this.selfWrites.has(absPath)) return;` — a
|
|
568
|
+
* `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`
|
|
569
|
+
* cleared. That check discarded **every** event for a recently-written path
|
|
570
|
+
* without ever looking at what the watcher had actually observed, which is
|
|
571
|
+
* the whole defect: with `usePolling`, chokidar compares state once per
|
|
572
|
+
* `interval`, so our write and an external edit landing between two ticks
|
|
573
|
+
* are delivered as **one** event carrying the *external* content. Dropping
|
|
574
|
+
* it on a wall clock destroyed the only notification that edit would ever
|
|
575
|
+
* produce.
|
|
576
|
+
*
|
|
577
|
+
* Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase
|
|
578
|
+
* randomised so the delivery lag samples `[0, interval)` uniformly:
|
|
579
|
+
*
|
|
580
|
+
* delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time
|
|
581
|
+
* delivery lag > 200ms → 33 runs → external edit delivered, every time
|
|
582
|
+
*
|
|
583
|
+
* A perfect split on the wall-clock boundary, and the reason earlier
|
|
584
|
+
* instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,
|
|
585
|
+
* pinning the lag (measured: 519–585ms across 25 runs) safely outside the
|
|
586
|
+
* window. Nothing about the window was rare — it was unsampled.
|
|
587
|
+
*
|
|
588
|
+
* What remains is the check that was already doing the real work one step
|
|
589
|
+
* down, and it needs no timer because it compares the content the watcher
|
|
590
|
+
* **read** against the index:
|
|
591
|
+
*
|
|
592
|
+
* - `add`/`change` — `currentHead === hash` drops the event when the bytes
|
|
593
|
+
* on disk are the bytes we last published. `put()` sets that head in the
|
|
594
|
+
* same continuation as its `rename`, and `awaitWriteFinish` holds the
|
|
595
|
+
* event for a further `stabilityThreshold`, so it is never late.
|
|
596
|
+
* - `unlink` — `!currentHead` drops the event when the index already
|
|
597
|
+
* agrees the item is gone. `delete()` retires the head *before* it
|
|
598
|
+
* unlinks, precisely because this face gets no `awaitWriteFinish` delay.
|
|
599
|
+
*
|
|
600
|
+
* Both faces are pinned together in `test/self-write-suppression.test.ts`.
|
|
601
|
+
*
|
|
602
|
+
* Note the deliberate limit: identity is judged on what round-trips through
|
|
603
|
+
* the file, so a spec whose in-memory form does not (a `Date`, which
|
|
604
|
+
* canonicalises to `{}` in memory but to an ISO string once written and
|
|
605
|
+
* re-read) is republished as an external `update`. That predates this change
|
|
606
|
+
* and is independent of it — such a spec already fails `put().version ===
|
|
607
|
+
* get().hash`, and the 200ms window never covered it either, expiring some
|
|
608
|
+
* 360ms before the event it would have had to catch.
|
|
609
|
+
*/
|
|
569
610
|
async handleFsChange(absPath, kind) {
|
|
570
|
-
if (this.selfWrites.has(absPath)) return;
|
|
571
611
|
const parsed = parseItemPath(this.layout, absPath);
|
|
572
612
|
if (!parsed) return;
|
|
573
613
|
const ref = {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/repository.ts","../src/layout.ts","../src/jsonl-log.ts","../src/sync.ts","../src/watch-iterable.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `FileSystemRepository` — Node-only implementation of\n * `MetadataRepository` backed by JSON files plus a JSONL change log.\n *\n * See `README.md` for the on-disk layout and ADR-0008 §10 PR-4 for the\n * design rationale.\n *\n * Invariants\n * ──────────\n * - All `put` / `delete` ops serialize per-key via `KeyedMutex`.\n * - The change-log JSONL is the durable source of `seq`. On boot we\n * scan the log to learn the next seq value.\n * - Body files (`<type>/<name>.json`) are the source of truth; the\n * log is a denormalised history index.\n * - chokidar-driven external edits are translated into MetadataEvents\n * by hashing the new content and comparing to the last-known hash.\n * - The root directory is created **on the first write, not on attach**\n * (#7000). Attaching and reading a repository whose root does not exist\n * is legal and answers \"empty\"; see `start()` / `ensureRoot()`.\n */\n\nimport fs from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { FSWatcher } from 'chokidar';\nimport chokidar from 'chokidar';\nimport {\n type MetadataRepository,\n type MetaRef,\n type MetadataItem,\n type MetadataItemHeader,\n type MetadataEvent,\n type PutOptions,\n type PutResult,\n type DeleteOptions,\n type DeleteResult,\n type ListFilter,\n type WatchFilter,\n type HistoryOptions,\n type MetadataType,\n hashSpec,\n ConflictError,\n refKey,\n} from '@objectstack/metadata-core';\nimport {\n type FsLayout,\n itemPath,\n parseItemPath,\n typeDir,\n logFile,\n} from './layout.js';\nimport { JsonlLog } from './jsonl-log.js';\nimport { KeyedMutex, createBroker, type EventBroker } from './sync.js';\nimport { createWatchIterable } from './watch-iterable.js';\n\nexport interface FileSystemRepositoryOptions {\n /** Absolute path to the metadata root directory. */\n root: string;\n /** Tenant/org. */\n org: string;\n /** Identity reported in events that originate from external FS edits. */\n fsActor?: string;\n /** Disable chokidar watcher (e.g. for read-only contexts). */\n disableWatch?: boolean;\n /** Optional clock injection for deterministic tests. */\n now?: () => Date;\n}\n\nconst matchRefFilter = (\n ref: MetaRef,\n filter: { org?: string; type?: MetadataType; name?: string },\n): boolean => {\n if (filter.org && filter.org !== ref.org) return false;\n if (filter.type && filter.type !== ref.type) return false;\n if (filter.name && filter.name !== ref.name) return false;\n return true;\n};\n\nconst matchEvent = (evt: MetadataEvent, filter: WatchFilter): boolean => matchRefFilter(evt.ref, filter);\n\nexport class FileSystemRepository implements MetadataRepository {\n private readonly layout: FsLayout;\n private readonly org: string;\n private readonly fsActor: string;\n private readonly disableWatch: boolean;\n private readonly now: () => Date;\n private readonly log: JsonlLog;\n private readonly mutex = new KeyedMutex();\n private readonly broker: EventBroker = createBroker(matchEvent);\n\n /** In-memory index: refKey → current hash (HEAD). */\n private readonly heads = new Map<string, string>();\n /** Next seq counter, hydrated from the log on `start()`. */\n private nextSeq = 1;\n /** Paths we wrote ourselves; suppress the resulting chokidar event. */\n private readonly selfWrites = new Set<string>();\n private watcher: FSWatcher | null = null;\n private started = false;\n\n constructor(opts: FileSystemRepositoryOptions) {\n this.org = opts.org;\n this.fsActor = opts.fsActor ?? 'fs';\n this.disableWatch = opts.disableWatch ?? false;\n this.now = opts.now ?? (() => new Date());\n this.layout = { root: path.resolve(opts.root) };\n this.log = new JsonlLog(logFile(this.layout));\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Attach the repository. **Creates nothing on disk** (#7000).\n *\n * Attaching is not a write. `start()` used to `mkdir` both the root and\n * `<root>/.objectstack/.log` unconditionally, which meant every read-only\n * boot that merely attaches a repository left a skeleton behind — most\n * visibly `os migrate plan`, a declared dry run, on a project that has\n * never been started. That is the same property #6743 ruled on for\n * `.objectstack/data/`: a dry run leaves nothing behind, and the existence\n * of `.objectstack/` has to stay a usable \"this project has been started\"\n * signal.\n *\n * Every read path below already treats a missing root as an empty\n * repository (`scanHeads` swallows ENOENT, `JsonlLog` guards on\n * `existsSync`, `get` guards on `existsSync`), so the root is materialized\n * by `ensureRoot()` on the first write instead.\n */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n\n // 1) Scan body files to build the head index. No-op on a missing root.\n await this.scanHeads();\n\n // 2) Hydrate nextSeq from the existing log. No-op on a missing log.\n const highest = await this.log.highestSeq();\n this.nextSeq = highest + 1;\n\n // 3) Start the watcher (unless disabled). chokidar cannot watch a path\n // that does not exist yet: measured on chokidar 5 with `usePolling`,\n // a root created AFTER `watch()` produces no events at all, ever. So\n // when the root is absent the watcher is armed later, by the\n // `ensureRoot()` call that brings the root into existence — otherwise\n // dropping the `mkdir` above would silently kill external-edit\n // detection for the whole life of the process.\n if (!this.disableWatch && existsSync(this.layout.root)) this.startWatcher();\n }\n\n /**\n * Bring the repository root into existence. Called by every write path\n * immediately before it touches the disk — `start()` deliberately does not\n * create it (#7000), so this is the single seam where the root appears.\n *\n * It is also where a watcher that `start()` could not arm (missing root)\n * gets armed, so \"external edits are detected\" survives the change.\n */\n private async ensureRoot(): Promise<void> {\n await fs.mkdir(this.layout.root, { recursive: true });\n if (this.started && !this.disableWatch && !this.watcher) this.startWatcher();\n }\n\n async close(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = null;\n }\n this.started = false;\n }\n\n // ── Read API ────────────────────────────────────────────────────────\n\n async get(ref: MetaRef): Promise<MetadataItem | null> {\n this.assertScope(ref);\n const file = itemPath(this.layout, ref.type, ref.name);\n if (!existsSync(file)) return null;\n const body = await readJson(file);\n if (!body) return null;\n const hash = hashSpec(body);\n if (ref.version && ref.version !== hash) return null;\n // Walk back through the log to populate parent/authoredBy/seq.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n ref: { ...ref, version: undefined },\n body: body as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n }\n\n async getByHash(ref: MetaRef, hash: string): Promise<MetadataItem | null> {\n // FS repo stores only HEAD bodies on disk; the JSONL log records\n // events (hashes) but not historical bodies. Resolve only if the\n // requested hash matches HEAD.\n const head = await this.get(ref);\n if (!head || head.hash !== hash) return null;\n return head;\n }\n\n async *list(filter: ListFilter): AsyncIterable<MetadataItemHeader> {\n const limit = filter.limit ?? Infinity;\n let yielded = 0;\n for (const [key, hash] of this.heads) {\n const ref = parseRefKey(key);\n if (!ref) continue;\n if (!matchRefFilter(ref, filter)) continue;\n if (filter.nameContains && !ref.name.includes(filter.nameContains)) continue;\n const meta = await this.findMetaForHash(ref, hash);\n const header: MetadataItemHeader = {\n ref: { ...ref, version: undefined },\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n yield header;\n if (++yielded >= limit) return;\n }\n }\n\n async *history(ref: MetaRef, opts: HistoryOptions = {}): AsyncIterable<MetadataEvent> {\n this.assertScope(ref);\n const since = opts.sinceSeq ?? -1;\n const limit = opts.limit ?? Infinity;\n let yielded = 0;\n for await (const evt of this.log.readAll()) {\n if (evt.seq <= since) continue;\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n yield evt;\n if (++yielded >= limit) return;\n }\n }\n\n watch(filter: WatchFilter, since?: number): AsyncIterable<MetadataEvent> {\n // Eagerly snapshot the existing log for replay; new events route via broker.\n const replay: MetadataEvent[] = [];\n const promise = (async () => {\n for await (const evt of this.log.readAll()) {\n if (matchEvent(evt, filter)) replay.push(evt);\n }\n })();\n // We must await replay before returning, but the public API is\n // sync-returning AsyncIterable. Wrap in a deferred iterable.\n return deferredIterable(promise.then(() =>\n createWatchIterable({\n filter,\n since,\n replay,\n broker: this.broker,\n matches: matchEvent,\n branchKeyOf: (e) => e.ref.org,\n }),\n ));\n }\n\n // ── Write API ───────────────────────────────────────────────────────\n\n put(ref: MetaRef, spec: unknown, opts: PutOptions): Promise<PutResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if ((opts.parentVersion ?? null) !== currentHead) {\n throw new ConflictError(ref, opts.parentVersion ?? null, currentHead);\n }\n const hash = hashSpec(spec);\n if (currentHead === hash) {\n // No-op write — same content.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n version: hash,\n seq: meta?.seq ?? 0,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? this.now().toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n },\n };\n }\n\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const file = itemPath(this.layout, ref.type, ref.name);\n // First write of the process materializes the root (#7000).\n await this.ensureRoot();\n await fs.mkdir(typeDir(this.layout, ref.type), { recursive: true });\n this.selfWrites.add(file);\n try {\n await writeJsonAtomic(file, spec);\n } finally {\n // Hold the suppression until chokidar has had a chance to emit;\n // we keep it in selfWrites for one debounce tick.\n setTimeout(() => this.selfWrites.delete(file), 200);\n }\n // The watcher must not depend on its own directory scan to notice a\n // path we created ourselves (#7282). See `trackWrittenPath`.\n this.trackWrittenPath(file);\n this.heads.set(key, hash);\n\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n\n return {\n version: hash,\n seq,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: currentHead,\n authoredBy: opts.actor,\n authoredAt: ts,\n message: opts.message,\n seq,\n },\n };\n });\n }\n\n delete(ref: MetaRef, opts: DeleteOptions): Promise<DeleteResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead !== opts.parentVersion) {\n throw new ConflictError(ref, opts.parentVersion, currentHead);\n }\n const file = itemPath(this.layout, ref.type, ref.name);\n // A delete appends a tombstone to the change log, so it is a write too.\n await this.ensureRoot();\n this.selfWrites.add(file);\n try {\n if (existsSync(file)) await fs.unlink(file);\n } finally {\n setTimeout(() => this.selfWrites.delete(file), 200);\n }\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return { seq };\n });\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private assertScope(ref: MetaRef): void {\n if (ref.org !== this.org) {\n throw new Error(\n `FileSystemRepository scope mismatch: expected org=${this.org}, got org=${ref.org}`,\n );\n }\n }\n\n private async scanHeads(): Promise<void> {\n this.heads.clear();\n // Walk one level deep: <root>/<type>/<name>.json\n let entries: import('node:fs').Dirent[] = [];\n try {\n entries = await fs.readdir(this.layout.root, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const type = entry.name;\n const dir = path.join(this.layout.root, type);\n let files: string[] = [];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const name = file.slice(0, -'.json'.length);\n const ref: MetaRef = {\n org: this.org,\n type: type as MetadataType,\n name,\n };\n const body = await readJson(path.join(dir, file));\n if (!body) continue;\n this.heads.set(refKey(ref), hashSpec(body));\n }\n }\n }\n\n private async findMetaForHash(\n ref: MetaRef,\n hash: string,\n ): Promise<MetadataEvent | null> {\n let last: MetadataEvent | null = null;\n for await (const evt of this.log.readAll()) {\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n if (evt.hash === hash) last = evt;\n }\n return last;\n }\n\n /**\n * Register a path this repository just wrote with the watcher (#7282).\n *\n * chokidar's initial scan is asynchronous, and every write path here can be\n * running **while it is still walking the tree** — `start()` arms the watcher\n * and the caller may `put()` on the next tick, and `ensureRoot()` arms it in\n * the middle of the very first write. With `usePolling` that combination has\n * a permanently-blinding interleaving, measured on chokidar 5 with this\n * repository's own options:\n *\n * 1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic\n * `rename` in `writeJsonAtomic` has not landed yet.\n * 2. the rename lands; the directory's mtime changes.\n * 3. chokidar calls `watchFile()` on that directory, and libuv takes its\n * polling baseline stat — which already reflects step 2.\n *\n * From then on the directory's stat never changes again, so no poll ever\n * fires for it, `_handleRead` never re-runs, the item file is never added to\n * the watched set, and no per-file watcher is ever created. chokidar emits\n * neither `add` nor `change` for that path **for the life of the process** —\n * `getWatched()` reports the type directory as `[]` forever while the file\n * sits in it. That is the whole of #7282: the four merge-queue ejections all\n * waited out their deadlines (20s, then 25541ms against 25s) on an event that\n * was never going to be delivered, which is why widening the deadline and\n * widening the pre-edit sleep both changed nothing, and why lowering\n * `interval` would change nothing either — a shorter poll re-compares against\n * the same unchanged directory stat.\n *\n * The window is exactly \"files that exist at baseline time but were absent\n * from the snapshot read a moment earlier\", and the only writer that can be\n * inside it is us. So we close it at the source: tell the watcher explicitly\n * about every path we create, instead of hoping its scan happened to see it.\n *\n * `add()` is idempotent here — `_handleFile` returns early when the parent\n * directory already tracks the basename — and it emits nothing, because\n * chokidar treats an explicit `add()` as an initial add and `ignoreInitial`\n * is set. Its effect is the one we need: `_watchWithNodeFs` registers the\n * basename with the parent directory (without which chokidar drops `change`\n * events for the file) and starts the per-file poll.\n */\n private trackWrittenPath(file: string): void {\n const w = this.watcher;\n // `add()` clears `closed`, so never hand a closing watcher a new path.\n if (!w || w.closed) return;\n w.add(file);\n }\n\n private startWatcher(): void {\n const root = this.layout.root;\n const w = chokidar.watch(root, {\n // Skip dotfiles under the root — including the repository's own\n // `.objectstack/` bookkeeping subtree — matched on the path RELATIVE\n // to the watch root (#7150). See `isIgnoredWatchPath`.\n ignored: (p: string) => isIgnoredWatchPath(root, p),\n ignoreInitial: true,\n depth: 2,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n // Use polling to avoid `fs.watch` EMFILE on macOS / busy dev hosts.\n // The depth-2 recursion would otherwise wire native watches across\n // the entire customization tree.\n usePolling: true,\n interval: 1000,\n binaryInterval: 2000,\n });\n w.on('add', (p) => void this.handleFsChange(p, 'add'));\n w.on('change', (p) => void this.handleFsChange(p, 'change'));\n w.on('unlink', (p) => void this.handleFsChange(p, 'unlink'));\n this.watcher = w;\n }\n\n private async handleFsChange(absPath: string, kind: 'add' | 'change' | 'unlink'): Promise<void> {\n if (this.selfWrites.has(absPath)) return; // Suppress our own writes.\n const parsed = parseItemPath(this.layout, absPath);\n if (!parsed) return;\n const ref: MetaRef = {\n org: this.org,\n type: parsed.type as MetadataType,\n name: parsed.name,\n };\n const key = refKey(ref);\n await this.mutex.run(key, async () => {\n if (kind === 'unlink') {\n const currentHead = this.heads.get(key) ?? null;\n if (!currentHead) return;\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return;\n }\n const body = await readJson(absPath);\n if (!body) return;\n const hash = hashSpec(body);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead === hash) return; // No content change.\n this.heads.set(key, hash);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n });\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────\n\n/**\n * Watcher ignore matcher — \"everything under the root, except the\n * repository's own bookkeeping\" (#7150).\n *\n * chokidar hands its matcher **absolute** paths, and applies it to the\n * watched root itself as well as to entries discovered underneath it. The\n * previous matcher was a bare dotfile regex (`/(^|[\\\\/])\\../`), which\n * therefore matched the `.objectstack` segment of the root path the plugin\n * actually uses (`<project>/.objectstack/metadata`, `REPO_SUBDIR` in\n * `packages/metadata/src/plugin.ts`) and ignored the whole watch. Measured on\n * chokidar 5 with this repository's own options, two identical trees\n * differing only in whether the root sits under a dot-directory:\n *\n * plain root getWatched: ['<root>', 'view'] events: add+change\n * dot-rooted getWatched: [] events: none\n *\n * So the intent is kept and only the *frame of reference* is fixed: judge the\n * path relative to the root, so dot segments belonging to the root itself are\n * never considered.\n *\n * Why not drop the matcher entirely and lean on `parseItemPath`, which already\n * rejects `.objectstack`? Measured: `parseItemPath` rejects that ONE name, so\n * a dot-directory at the type level leaks — `<root>/.cache/x.json` parses as\n * type `.cache`, and `<root>/view/.scratch.json` as an item named `.scratch`.\n * Both would be published as `MetadataEvent`s while `scanHeads` skips every\n * dot entry on boot, leaving the boot scan and the watcher disagreeing about\n * what the repository contains. Dropping it also puts `.objectstack/.log/` in\n * the poll set, so every one of the repository's own log appends wakes\n * `handleFsChange` only to be discarded.\n */\nfunction isIgnoredWatchPath(root: string, absPath: string): boolean {\n const rel = path.relative(root, absPath);\n // The watched root itself, and anything outside it, are not ours to judge.\n if (rel === '' || rel.startsWith('..')) return false;\n return rel.split(/[\\\\/]/).some((segment) => segment.startsWith('.'));\n}\n\nasync function readJson(file: string): Promise<unknown | null> {\n try {\n const text = await fs.readFile(file, 'utf8');\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nasync function writeJsonAtomic(file: string, body: unknown): Promise<void> {\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(body, null, 2) + '\\n', 'utf8');\n await fs.rename(tmp, file);\n}\n\nfunction parseRefKey(key: string): MetaRef | null {\n const parts = key.split('/');\n if (parts.length !== 3) return null;\n return {\n org: parts[0]!,\n type: parts[1]! as MetadataType,\n name: parts[2]!,\n };\n}\n\n/**\n * Wrap a Promise<AsyncIterable<T>> as a sync-returning AsyncIterable<T>.\n * The first `.next()` awaits the promise.\n */\nfunction deferredIterable<T>(promise: Promise<AsyncIterable<T>>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n let inner: AsyncIterator<T> | null = null;\n return {\n async next() {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n return inner.next();\n },\n async return(value?: unknown) {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n if (inner.return) return inner.return(value);\n return { value: undefined, done: true };\n },\n } as AsyncIterator<T>;\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Disk layout helpers — see ADR-0008 §10 PR-4 / packages/metadata-fs README.\n *\n * <root>/<type>/<name>.json — canonical body\n * <root>/.objectstack/.log/main.jsonl — append-only change log\n */\n\nimport path from 'node:path';\nimport type { MetadataType } from '@objectstack/metadata-core';\n\nexport interface FsLayout {\n /** Absolute path to the metadata root. */\n root: string;\n}\n\nexport function itemPath(layout: FsLayout, type: MetadataType, name: string): string {\n return path.join(layout.root, type, `${name}.json`);\n}\n\nexport function typeDir(layout: FsLayout, type: MetadataType): string {\n return path.join(layout.root, type);\n}\n\nexport function logDir(layout: FsLayout): string {\n return path.join(layout.root, '.objectstack', '.log');\n}\n\nexport function logFile(layout: FsLayout): string {\n // Single change log per filesystem root (branching is a Git concern,\n // not a metadata-layer concern).\n return path.join(logDir(layout), `main.jsonl`);\n}\n\n/** Parse a path like \".../view/case_grid.json\" into {type, name}. */\nexport function parseItemPath(\n layout: FsLayout,\n absPath: string,\n): { type: string; name: string } | null {\n const rel = path.relative(layout.root, absPath);\n if (rel.startsWith('..') || rel.startsWith('.objectstack')) return null;\n const segments = rel.split(path.sep);\n if (segments.length !== 2) return null;\n const type = segments[0]!;\n const file = segments[1]!;\n if (!file.endsWith('.json')) return null;\n const name = file.slice(0, -'.json'.length);\n return { type, name };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Append-only JSONL change log writer / reader. Each line is a single\n * `MetadataEvent` serialized via `JSON.stringify`.\n *\n * Durability strategy\n * ───────────────────\n * - Append with `O_APPEND` semantics (Node's `fs.appendFile` is\n * atomic for sub-PIPE_BUF-sized writes; events are well under 4 KiB).\n * - Read by streaming the file line-by-line and JSON.parse-ing each.\n * - On a corrupt line we skip and continue — the body files are the\n * source of truth; the log is a denormalised history index.\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport readline from 'node:readline';\nimport { createReadStream, existsSync } from 'node:fs';\nimport type { MetadataEvent } from '@objectstack/metadata-core';\n\nexport class JsonlLog {\n constructor(private readonly file: string) {}\n\n async append(evt: MetadataEvent): Promise<void> {\n await fs.mkdir(path.dirname(this.file), { recursive: true });\n await fs.appendFile(this.file, JSON.stringify(evt) + '\\n', 'utf8');\n }\n\n /** Read all events in seq order (i.e. file order). */\n async *readAll(): AsyncIterable<MetadataEvent> {\n if (!existsSync(this.file)) return;\n const rl = readline.createInterface({\n input: createReadStream(this.file, { encoding: 'utf8' }),\n crlfDelay: Infinity,\n });\n try {\n for await (const line of rl) {\n if (!line.trim()) continue;\n try {\n yield JSON.parse(line) as MetadataEvent;\n } catch {\n // Skip corrupt line.\n }\n }\n } finally {\n rl.close();\n }\n }\n\n /** Return the highest seq number in the log, or 0 if empty. */\n async highestSeq(): Promise<number> {\n let max = 0;\n for await (const evt of this.readAll()) {\n if (typeof evt.seq === 'number' && evt.seq > max) max = evt.seq;\n }\n return max;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Mutex / event-broker primitives used by FileSystemRepository.\n *\n * `KeyedMutex` serializes operations on the same key (refKey). The\n * broker re-uses the same manual-AsyncIterator pattern as\n * InMemoryRepository so that consumer `return()` reliably unblocks.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\n\nexport class KeyedMutex {\n private readonly tails = new Map<string, Promise<unknown>>();\n\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n // Save the swallowed-error tail so successive runs don't reject on\n // an unrelated prior failure.\n const swallowed = next.catch(() => undefined);\n this.tails.set(key, swallowed);\n try {\n return await next;\n } finally {\n // Best-effort cleanup: drop the entry if nothing newer was queued.\n if (this.tails.get(key) === swallowed) {\n this.tails.delete(key);\n }\n }\n }\n}\n\nexport interface BrokerSubscriber {\n filter: WatchFilter;\n closed: boolean;\n push(evt: MetadataEvent): void;\n}\n\nexport interface EventBroker {\n subscribe(sub: BrokerSubscriber): void;\n unsubscribe(sub: BrokerSubscriber): void;\n publish(evt: MetadataEvent): void;\n}\n\nexport function createBroker(matches: (evt: MetadataEvent, filter: WatchFilter) => boolean): EventBroker {\n const subs = new Set<BrokerSubscriber>();\n return {\n subscribe: (s) => { subs.add(s); },\n unsubscribe: (s) => { subs.delete(s); },\n publish: (evt) => {\n for (const s of subs) {\n if (s.closed) continue;\n if (!matches(evt, s.filter)) continue;\n s.push(evt);\n }\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Manual `AsyncIterator` factory for `repo.watch()`. Mirrors the\n * pattern used in `@objectstack/metadata-core`'s `InMemoryRepository`:\n * async generators do NOT run `finally` when paused on an unresolved\n * `await`, so we cannot use them to implement `watch()`.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\nimport { type EventBroker, type BrokerSubscriber } from './sync.js';\n\nexport interface CreateWatchIteratorArgs {\n filter: WatchFilter;\n since: number | undefined;\n replay: MetadataEvent[];\n broker: EventBroker;\n /** Returns true if `evt.ref` matches `filter`. */\n matches: (evt: MetadataEvent, filter: WatchFilter) => boolean;\n branchKeyOf: (evt: MetadataEvent) => string;\n}\n\nexport function createWatchIterable(\n args: CreateWatchIteratorArgs,\n): AsyncIterable<MetadataEvent> {\n const queue: MetadataEvent[] = [];\n let waiter: ((evt: IteratorResult<MetadataEvent>) => void) | null = null;\n let closed = false;\n const delivered = new Set<string>();\n const evtKey = (e: MetadataEvent) => `${args.branchKeyOf(e)}#${e.seq}`;\n\n const subscriber: BrokerSubscriber = {\n filter: args.filter,\n closed: false,\n push: (evt) => {\n if (subscriber.closed) return;\n const k = evtKey(evt);\n if (delivered.has(k)) return;\n if (waiter) {\n delivered.add(k);\n const w = waiter;\n waiter = null;\n w({ value: clone(evt), done: false });\n } else {\n queue.push(evt);\n }\n },\n };\n args.broker.subscribe(subscriber);\n\n const replay = [...args.replay].sort((a, b) => a.seq - b.seq);\n let replayIdx = 0;\n\n const drain = (): IteratorResult<MetadataEvent> | null => {\n while (replayIdx < replay.length) {\n const evt = replay[replayIdx++]!;\n if (typeof args.since === 'number' && evt.seq <= args.since) continue;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n while (queue.length > 0) {\n const evt = queue.shift()!;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n return null;\n };\n\n const close = (): IteratorResult<MetadataEvent> => {\n if (!closed) {\n closed = true;\n subscriber.closed = true;\n args.broker.unsubscribe(subscriber);\n if (waiter) {\n const w = waiter;\n waiter = null;\n w({ value: undefined, done: true });\n }\n }\n return { value: undefined, done: true };\n };\n\n const iterator: AsyncIterator<MetadataEvent> = {\n next: () => {\n if (closed) return Promise.resolve({ value: undefined, done: true });\n const immediate = drain();\n if (immediate) return Promise.resolve(immediate);\n return new Promise<IteratorResult<MetadataEvent>>((resolve) => {\n waiter = resolve;\n });\n },\n return: () => Promise.resolve(close()),\n throw: (err) => {\n close();\n return Promise.reject(err);\n },\n };\n return { [Symbol.asyncIterator]: () => iterator };\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n"],"mappings":";AAuBA,OAAOA,SAAQ;AACf,SAAS,cAAAC,mBAAkB;AAC3B,OAAOC,WAAU;AAEjB,OAAO,cAAc;AACrB;AAAA,EAcE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACpCP,OAAO,UAAU;AAQV,SAAS,SAAS,QAAkB,MAAoB,MAAsB;AACnF,SAAO,KAAK,KAAK,OAAO,MAAM,MAAM,GAAG,IAAI,OAAO;AACpD;AAEO,SAAS,QAAQ,QAAkB,MAA4B;AACpE,SAAO,KAAK,KAAK,OAAO,MAAM,IAAI;AACpC;AAEO,SAAS,OAAO,QAA0B;AAC/C,SAAO,KAAK,KAAK,OAAO,MAAM,gBAAgB,MAAM;AACtD;AAEO,SAAS,QAAQ,QAA0B;AAGhD,SAAO,KA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,QAAO,MAAM,OAAO,KAAK;AAC3C,iBAAO,EAAE,OAAO,QAAW,MAAM,KAAK;AAAA,QACxC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["fs","existsSync","path","path","path","existsSync","fs","currentHead","seq","evt"]}
|
|
1
|
+
{"version":3,"sources":["../src/repository.ts","../src/layout.ts","../src/jsonl-log.ts","../src/sync.ts","../src/watch-iterable.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * `FileSystemRepository` — Node-only implementation of\n * `MetadataRepository` backed by JSON files plus a JSONL change log.\n *\n * See `README.md` for the on-disk layout and ADR-0008 §10 PR-4 for the\n * design rationale.\n *\n * Invariants\n * ──────────\n * - All `put` / `delete` ops serialize per-key via `KeyedMutex`.\n * - The change-log JSONL is the durable source of `seq`. On boot we\n * scan the log to learn the next seq value.\n * - Body files (`<type>/<name>.json`) are the source of truth; the\n * log is a denormalised history index.\n * - chokidar-driven external edits are translated into MetadataEvents\n * by hashing the new content and comparing to the last-known hash.\n * - The root directory is created **on the first write, not on attach**\n * (#7000). Attaching and reading a repository whose root does not exist\n * is legal and answers \"empty\"; see `start()` / `ensureRoot()`.\n */\n\nimport fs from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport type { FSWatcher } from 'chokidar';\nimport chokidar from 'chokidar';\nimport {\n type MetadataRepository,\n type MetaRef,\n type MetadataItem,\n type MetadataItemHeader,\n type MetadataEvent,\n type PutOptions,\n type PutResult,\n type DeleteOptions,\n type DeleteResult,\n type ListFilter,\n type WatchFilter,\n type HistoryOptions,\n type MetadataType,\n hashSpec,\n ConflictError,\n refKey,\n} from '@objectstack/metadata-core';\nimport {\n type FsLayout,\n itemPath,\n parseItemPath,\n typeDir,\n logFile,\n} from './layout.js';\nimport { JsonlLog } from './jsonl-log.js';\nimport { KeyedMutex, createBroker, type EventBroker } from './sync.js';\nimport { createWatchIterable } from './watch-iterable.js';\n\nexport interface FileSystemRepositoryOptions {\n /** Absolute path to the metadata root directory. */\n root: string;\n /** Tenant/org. */\n org: string;\n /** Identity reported in events that originate from external FS edits. */\n fsActor?: string;\n /** Disable chokidar watcher (e.g. for read-only contexts). */\n disableWatch?: boolean;\n /** Optional clock injection for deterministic tests. */\n now?: () => Date;\n}\n\nconst matchRefFilter = (\n ref: MetaRef,\n filter: { org?: string; type?: MetadataType; name?: string },\n): boolean => {\n if (filter.org && filter.org !== ref.org) return false;\n if (filter.type && filter.type !== ref.type) return false;\n if (filter.name && filter.name !== ref.name) return false;\n return true;\n};\n\nconst matchEvent = (evt: MetadataEvent, filter: WatchFilter): boolean => matchRefFilter(evt.ref, filter);\n\nexport class FileSystemRepository implements MetadataRepository {\n private readonly layout: FsLayout;\n private readonly org: string;\n private readonly fsActor: string;\n private readonly disableWatch: boolean;\n private readonly now: () => Date;\n private readonly log: JsonlLog;\n private readonly mutex = new KeyedMutex();\n private readonly broker: EventBroker = createBroker(matchEvent);\n\n /** In-memory index: refKey → current hash (HEAD). */\n private readonly heads = new Map<string, string>();\n /** Next seq counter, hydrated from the log on `start()`. */\n private nextSeq = 1;\n private watcher: FSWatcher | null = null;\n private started = false;\n\n constructor(opts: FileSystemRepositoryOptions) {\n this.org = opts.org;\n this.fsActor = opts.fsActor ?? 'fs';\n this.disableWatch = opts.disableWatch ?? false;\n this.now = opts.now ?? (() => new Date());\n this.layout = { root: path.resolve(opts.root) };\n this.log = new JsonlLog(logFile(this.layout));\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Attach the repository. **Creates nothing on disk** (#7000).\n *\n * Attaching is not a write. `start()` used to `mkdir` both the root and\n * `<root>/.objectstack/.log` unconditionally, which meant every read-only\n * boot that merely attaches a repository left a skeleton behind — most\n * visibly `os migrate plan`, a declared dry run, on a project that has\n * never been started. That is the same property #6743 ruled on for\n * `.objectstack/data/`: a dry run leaves nothing behind, and the existence\n * of `.objectstack/` has to stay a usable \"this project has been started\"\n * signal.\n *\n * Every read path below already treats a missing root as an empty\n * repository (`scanHeads` swallows ENOENT, `JsonlLog` guards on\n * `existsSync`, `get` guards on `existsSync`), so the root is materialized\n * by `ensureRoot()` on the first write instead.\n */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n\n // 1) Scan body files to build the head index. No-op on a missing root.\n await this.scanHeads();\n\n // 2) Hydrate nextSeq from the existing log. No-op on a missing log.\n const highest = await this.log.highestSeq();\n this.nextSeq = highest + 1;\n\n // 3) Start the watcher (unless disabled). chokidar cannot watch a path\n // that does not exist yet: measured on chokidar 5 with `usePolling`,\n // a root created AFTER `watch()` produces no events at all, ever. So\n // when the root is absent the watcher is armed later, by the\n // `ensureRoot()` call that brings the root into existence — otherwise\n // dropping the `mkdir` above would silently kill external-edit\n // detection for the whole life of the process.\n if (!this.disableWatch && existsSync(this.layout.root)) this.startWatcher();\n }\n\n /**\n * Bring the repository root into existence. Called by every write path\n * immediately before it touches the disk — `start()` deliberately does not\n * create it (#7000), so this is the single seam where the root appears.\n *\n * It is also where a watcher that `start()` could not arm (missing root)\n * gets armed, so \"external edits are detected\" survives the change.\n */\n private async ensureRoot(): Promise<void> {\n await fs.mkdir(this.layout.root, { recursive: true });\n if (this.started && !this.disableWatch && !this.watcher) this.startWatcher();\n }\n\n async close(): Promise<void> {\n if (this.watcher) {\n await this.watcher.close();\n this.watcher = null;\n }\n this.started = false;\n }\n\n // ── Read API ────────────────────────────────────────────────────────\n\n async get(ref: MetaRef): Promise<MetadataItem | null> {\n this.assertScope(ref);\n const file = itemPath(this.layout, ref.type, ref.name);\n if (!existsSync(file)) return null;\n const body = await readJson(file);\n if (!body) return null;\n const hash = hashSpec(body);\n if (ref.version && ref.version !== hash) return null;\n // Walk back through the log to populate parent/authoredBy/seq.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n ref: { ...ref, version: undefined },\n body: body as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n }\n\n async getByHash(ref: MetaRef, hash: string): Promise<MetadataItem | null> {\n // FS repo stores only HEAD bodies on disk; the JSONL log records\n // events (hashes) but not historical bodies. Resolve only if the\n // requested hash matches HEAD.\n const head = await this.get(ref);\n if (!head || head.hash !== hash) return null;\n return head;\n }\n\n async *list(filter: ListFilter): AsyncIterable<MetadataItemHeader> {\n const limit = filter.limit ?? Infinity;\n let yielded = 0;\n for (const [key, hash] of this.heads) {\n const ref = parseRefKey(key);\n if (!ref) continue;\n if (!matchRefFilter(ref, filter)) continue;\n if (filter.nameContains && !ref.name.includes(filter.nameContains)) continue;\n const meta = await this.findMetaForHash(ref, hash);\n const header: MetadataItemHeader = {\n ref: { ...ref, version: undefined },\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? new Date(0).toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n };\n yield header;\n if (++yielded >= limit) return;\n }\n }\n\n async *history(ref: MetaRef, opts: HistoryOptions = {}): AsyncIterable<MetadataEvent> {\n this.assertScope(ref);\n const since = opts.sinceSeq ?? -1;\n const limit = opts.limit ?? Infinity;\n let yielded = 0;\n for await (const evt of this.log.readAll()) {\n if (evt.seq <= since) continue;\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n yield evt;\n if (++yielded >= limit) return;\n }\n }\n\n watch(filter: WatchFilter, since?: number): AsyncIterable<MetadataEvent> {\n // Eagerly snapshot the existing log for replay; new events route via broker.\n const replay: MetadataEvent[] = [];\n const promise = (async () => {\n for await (const evt of this.log.readAll()) {\n if (matchEvent(evt, filter)) replay.push(evt);\n }\n })();\n // We must await replay before returning, but the public API is\n // sync-returning AsyncIterable. Wrap in a deferred iterable.\n return deferredIterable(promise.then(() =>\n createWatchIterable({\n filter,\n since,\n replay,\n broker: this.broker,\n matches: matchEvent,\n branchKeyOf: (e) => e.ref.org,\n }),\n ));\n }\n\n // ── Write API ───────────────────────────────────────────────────────\n\n put(ref: MetaRef, spec: unknown, opts: PutOptions): Promise<PutResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if ((opts.parentVersion ?? null) !== currentHead) {\n throw new ConflictError(ref, opts.parentVersion ?? null, currentHead);\n }\n const hash = hashSpec(spec);\n if (currentHead === hash) {\n // No-op write — same content.\n const meta = await this.findMetaForHash(ref, hash);\n return {\n version: hash,\n seq: meta?.seq ?? 0,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: meta?.parentHash ?? null,\n authoredBy: meta?.actor ?? this.fsActor,\n authoredAt: meta?.ts ?? this.now().toISOString(),\n message: meta?.message,\n seq: meta?.seq ?? 0,\n },\n };\n }\n\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const file = itemPath(this.layout, ref.type, ref.name);\n // First write of the process materializes the root (#7000).\n await this.ensureRoot();\n await fs.mkdir(typeDir(this.layout, ref.type), { recursive: true });\n await writeJsonAtomic(file, spec);\n // The watcher must not depend on its own directory scan to notice a\n // path we created ourselves (#7282). See `trackWrittenPath`.\n this.trackWrittenPath(file);\n // Publishing the new head here is what suppresses the watcher event this\n // write is about to produce — see `handleFsChange` (#7335). It runs in\n // the same continuation as the `rename` above, and `awaitWriteFinish`\n // holds any event for a further `stabilityThreshold`, so the index is\n // always current by the time an event for this path can be delivered.\n this.heads.set(key, hash);\n\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n\n return {\n version: hash,\n seq,\n item: {\n ref: { ...ref, version: undefined },\n body: spec as Record<string, unknown>,\n hash,\n parentHash: currentHead,\n authoredBy: opts.actor,\n authoredAt: ts,\n message: opts.message,\n seq,\n },\n };\n });\n }\n\n delete(ref: MetaRef, opts: DeleteOptions): Promise<DeleteResult> {\n this.assertScope(ref);\n return this.mutex.run(refKey(ref), async () => {\n const key = refKey(ref);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead !== opts.parentVersion) {\n throw new ConflictError(ref, opts.parentVersion, currentHead);\n }\n const file = itemPath(this.layout, ref.type, ref.name);\n // A delete appends a tombstone to the change log, so it is a write too.\n await this.ensureRoot();\n // Retire the head BEFORE touching the disk, not after (#7335).\n //\n // `awaitWriteFinish` only debounces `add`/`change`; chokidar emits\n // `unlink` with no stability delay at all, so — unlike `put()` — this\n // face has no cushion between the disk mutation and the event it\n // produces. Clearing the index first makes `handleFsChange`'s\n // `if (!currentHead) return` a total suppression for our own removal\n // rather than a race against the poll callback.\n this.heads.delete(key);\n try {\n if (existsSync(file)) await fs.unlink(file);\n } catch (err) {\n // The disk still holds the item, so the index must too — otherwise a\n // failed delete would leave the repository claiming a file it can\n // still read. Restores exactly the pre-call state before rethrowing.\n if (currentHead !== null) this.heads.set(key, currentHead);\n throw err;\n }\n const seq = this.nextSeq++;\n const ts = this.now().toISOString();\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: opts.actor,\n message: opts.message,\n ts,\n source: opts.source ?? 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return { seq };\n });\n }\n\n // ── Internals ───────────────────────────────────────────────────────\n\n private assertScope(ref: MetaRef): void {\n if (ref.org !== this.org) {\n throw new Error(\n `FileSystemRepository scope mismatch: expected org=${this.org}, got org=${ref.org}`,\n );\n }\n }\n\n private async scanHeads(): Promise<void> {\n this.heads.clear();\n // Walk one level deep: <root>/<type>/<name>.json\n let entries: import('node:fs').Dirent[] = [];\n try {\n entries = await fs.readdir(this.layout.root, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n if (entry.name.startsWith('.')) continue;\n const type = entry.name;\n const dir = path.join(this.layout.root, type);\n let files: string[] = [];\n try {\n files = await fs.readdir(dir);\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n const name = file.slice(0, -'.json'.length);\n const ref: MetaRef = {\n org: this.org,\n type: type as MetadataType,\n name,\n };\n const body = await readJson(path.join(dir, file));\n if (!body) continue;\n this.heads.set(refKey(ref), hashSpec(body));\n }\n }\n }\n\n private async findMetaForHash(\n ref: MetaRef,\n hash: string,\n ): Promise<MetadataEvent | null> {\n let last: MetadataEvent | null = null;\n for await (const evt of this.log.readAll()) {\n if (evt.ref.type !== ref.type || evt.ref.name !== ref.name) continue;\n if (evt.ref.org !== ref.org) continue;\n if (evt.hash === hash) last = evt;\n }\n return last;\n }\n\n /**\n * Register a path this repository just wrote with the watcher (#7282).\n *\n * chokidar's initial scan is asynchronous, and every write path here can be\n * running **while it is still walking the tree** — `start()` arms the watcher\n * and the caller may `put()` on the next tick, and `ensureRoot()` arms it in\n * the middle of the very first write. With `usePolling` that combination has\n * a permanently-blinding interleaving, measured on chokidar 5 with this\n * repository's own options:\n *\n * 1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic\n * `rename` in `writeJsonAtomic` has not landed yet.\n * 2. the rename lands; the directory's mtime changes.\n * 3. chokidar calls `watchFile()` on that directory, and libuv takes its\n * polling baseline stat — which already reflects step 2.\n *\n * From then on the directory's stat never changes again, so no poll ever\n * fires for it, `_handleRead` never re-runs, the item file is never added to\n * the watched set, and no per-file watcher is ever created. chokidar emits\n * neither `add` nor `change` for that path **for the life of the process** —\n * `getWatched()` reports the type directory as `[]` forever while the file\n * sits in it. That is the whole of #7282: the four merge-queue ejections all\n * waited out their deadlines (20s, then 25541ms against 25s) on an event that\n * was never going to be delivered, which is why widening the deadline and\n * widening the pre-edit sleep both changed nothing, and why lowering\n * `interval` would change nothing either — a shorter poll re-compares against\n * the same unchanged directory stat.\n *\n * The window is exactly \"files that exist at baseline time but were absent\n * from the snapshot read a moment earlier\", and the only writer that can be\n * inside it is us. So we close it at the source: tell the watcher explicitly\n * about every path we create, instead of hoping its scan happened to see it.\n *\n * `add()` is idempotent here — `_handleFile` returns early when the parent\n * directory already tracks the basename — and it emits nothing, because\n * chokidar treats an explicit `add()` as an initial add and `ignoreInitial`\n * is set. Its effect is the one we need: `_watchWithNodeFs` registers the\n * basename with the parent directory (without which chokidar drops `change`\n * events for the file) and starts the per-file poll.\n */\n private trackWrittenPath(file: string): void {\n const w = this.watcher;\n // `add()` clears `closed`, so never hand a closing watcher a new path.\n if (!w || w.closed) return;\n w.add(file);\n }\n\n private startWatcher(): void {\n const root = this.layout.root;\n const w = chokidar.watch(root, {\n // Skip dotfiles under the root — including the repository's own\n // `.objectstack/` bookkeeping subtree — matched on the path RELATIVE\n // to the watch root (#7150). See `isIgnoredWatchPath`.\n ignored: (p: string) => isIgnoredWatchPath(root, p),\n ignoreInitial: true,\n depth: 2,\n awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },\n // Use polling to avoid `fs.watch` EMFILE on macOS / busy dev hosts.\n // The depth-2 recursion would otherwise wire native watches across\n // the entire customization tree.\n usePolling: true,\n interval: 1000,\n binaryInterval: 2000,\n });\n w.on('add', (p) => void this.handleFsChange(p, 'add'));\n w.on('change', (p) => void this.handleFsChange(p, 'change'));\n w.on('unlink', (p) => void this.handleFsChange(p, 'unlink'));\n this.watcher = w;\n }\n\n /**\n * Translate a watcher event into a `MetadataEvent`, or drop it.\n *\n * ## Self-writes are suppressed by content identity, never by a clock (#7335)\n *\n * This used to open with `if (this.selfWrites.has(absPath)) return;` — a\n * `Set` that `put()`/`delete()` added the path to and a `setTimeout(…, 200)`\n * cleared. That check discarded **every** event for a recently-written path\n * without ever looking at what the watcher had actually observed, which is\n * the whole defect: with `usePolling`, chokidar compares state once per\n * `interval`, so our write and an external edit landing between two ticks\n * are delivered as **one** event carrying the *external* content. Dropping\n * it on a wall clock destroyed the only notification that edit would ever\n * produce.\n *\n * Measured on `origin/main` @ `69fde55`, 40 iterations, poll phase\n * randomised so the delivery lag samples `[0, interval)` uniformly:\n *\n * delivery lag < 200ms → 7 runs → external edit SWALLOWED, every time\n * delivery lag > 200ms → 33 runs → external edit delivered, every time\n *\n * A perfect split on the wall-clock boundary, and the reason earlier\n * instrumentation saw 0/360: a *fixed* pre-edit sleep phase-locks the poll,\n * pinning the lag (measured: 519–585ms across 25 runs) safely outside the\n * window. Nothing about the window was rare — it was unsampled.\n *\n * What remains is the check that was already doing the real work one step\n * down, and it needs no timer because it compares the content the watcher\n * **read** against the index:\n *\n * - `add`/`change` — `currentHead === hash` drops the event when the bytes\n * on disk are the bytes we last published. `put()` sets that head in the\n * same continuation as its `rename`, and `awaitWriteFinish` holds the\n * event for a further `stabilityThreshold`, so it is never late.\n * - `unlink` — `!currentHead` drops the event when the index already\n * agrees the item is gone. `delete()` retires the head *before* it\n * unlinks, precisely because this face gets no `awaitWriteFinish` delay.\n *\n * Both faces are pinned together in `test/self-write-suppression.test.ts`.\n *\n * Note the deliberate limit: identity is judged on what round-trips through\n * the file, so a spec whose in-memory form does not (a `Date`, which\n * canonicalises to `{}` in memory but to an ISO string once written and\n * re-read) is republished as an external `update`. That predates this change\n * and is independent of it — such a spec already fails `put().version ===\n * get().hash`, and the 200ms window never covered it either, expiring some\n * 360ms before the event it would have had to catch.\n */\n private async handleFsChange(absPath: string, kind: 'add' | 'change' | 'unlink'): Promise<void> {\n const parsed = parseItemPath(this.layout, absPath);\n if (!parsed) return;\n const ref: MetaRef = {\n org: this.org,\n type: parsed.type as MetadataType,\n name: parsed.name,\n };\n const key = refKey(ref);\n await this.mutex.run(key, async () => {\n if (kind === 'unlink') {\n const currentHead = this.heads.get(key) ?? null;\n if (!currentHead) return;\n this.heads.delete(key);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: 'delete',\n ref: { ...ref, version: undefined },\n hash: null,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n return;\n }\n const body = await readJson(absPath);\n if (!body) return;\n const hash = hashSpec(body);\n const currentHead = this.heads.get(key) ?? null;\n if (currentHead === hash) return; // No content change.\n this.heads.set(key, hash);\n const seq = this.nextSeq++;\n const evt: MetadataEvent = {\n seq,\n op: currentHead ? 'update' : 'create',\n ref: { ...ref, version: undefined },\n hash,\n parentHash: currentHead,\n actor: this.fsActor,\n ts: this.now().toISOString(),\n source: 'fs',\n };\n await this.log.append(evt);\n this.broker.publish(evt);\n });\n }\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────\n\n/**\n * Watcher ignore matcher — \"everything under the root, except the\n * repository's own bookkeeping\" (#7150).\n *\n * chokidar hands its matcher **absolute** paths, and applies it to the\n * watched root itself as well as to entries discovered underneath it. The\n * previous matcher was a bare dotfile regex (`/(^|[\\\\/])\\../`), which\n * therefore matched the `.objectstack` segment of the root path the plugin\n * actually uses (`<project>/.objectstack/metadata`, `REPO_SUBDIR` in\n * `packages/metadata/src/plugin.ts`) and ignored the whole watch. Measured on\n * chokidar 5 with this repository's own options, two identical trees\n * differing only in whether the root sits under a dot-directory:\n *\n * plain root getWatched: ['<root>', 'view'] events: add+change\n * dot-rooted getWatched: [] events: none\n *\n * So the intent is kept and only the *frame of reference* is fixed: judge the\n * path relative to the root, so dot segments belonging to the root itself are\n * never considered.\n *\n * Why not drop the matcher entirely and lean on `parseItemPath`, which already\n * rejects `.objectstack`? Measured: `parseItemPath` rejects that ONE name, so\n * a dot-directory at the type level leaks — `<root>/.cache/x.json` parses as\n * type `.cache`, and `<root>/view/.scratch.json` as an item named `.scratch`.\n * Both would be published as `MetadataEvent`s while `scanHeads` skips every\n * dot entry on boot, leaving the boot scan and the watcher disagreeing about\n * what the repository contains. Dropping it also puts `.objectstack/.log/` in\n * the poll set, so every one of the repository's own log appends wakes\n * `handleFsChange` only to be discarded.\n */\nfunction isIgnoredWatchPath(root: string, absPath: string): boolean {\n const rel = path.relative(root, absPath);\n // The watched root itself, and anything outside it, are not ours to judge.\n if (rel === '' || rel.startsWith('..')) return false;\n return rel.split(/[\\\\/]/).some((segment) => segment.startsWith('.'));\n}\n\nasync function readJson(file: string): Promise<unknown | null> {\n try {\n const text = await fs.readFile(file, 'utf8');\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nasync function writeJsonAtomic(file: string, body: unknown): Promise<void> {\n const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;\n await fs.writeFile(tmp, JSON.stringify(body, null, 2) + '\\n', 'utf8');\n await fs.rename(tmp, file);\n}\n\nfunction parseRefKey(key: string): MetaRef | null {\n const parts = key.split('/');\n if (parts.length !== 3) return null;\n return {\n org: parts[0]!,\n type: parts[1]! as MetadataType,\n name: parts[2]!,\n };\n}\n\n/**\n * Wrap a Promise<AsyncIterable<T>> as a sync-returning AsyncIterable<T>.\n * The first `.next()` awaits the promise.\n */\nfunction deferredIterable<T>(promise: Promise<AsyncIterable<T>>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n let inner: AsyncIterator<T> | null = null;\n return {\n async next() {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n return inner.next();\n },\n async return(value?: unknown) {\n if (!inner) {\n const iterable = await promise;\n inner = iterable[Symbol.asyncIterator]();\n }\n if (inner.return) return inner.return(value);\n return { value: undefined, done: true };\n },\n } as AsyncIterator<T>;\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Disk layout helpers — see ADR-0008 §10 PR-4 / packages/metadata-fs README.\n *\n * <root>/<type>/<name>.json — canonical body\n * <root>/.objectstack/.log/main.jsonl — append-only change log\n */\n\nimport path from 'node:path';\nimport type { MetadataType } from '@objectstack/metadata-core';\n\nexport interface FsLayout {\n /** Absolute path to the metadata root. */\n root: string;\n}\n\nexport function itemPath(layout: FsLayout, type: MetadataType, name: string): string {\n return path.join(layout.root, type, `${name}.json`);\n}\n\nexport function typeDir(layout: FsLayout, type: MetadataType): string {\n return path.join(layout.root, type);\n}\n\nexport function logDir(layout: FsLayout): string {\n return path.join(layout.root, '.objectstack', '.log');\n}\n\nexport function logFile(layout: FsLayout): string {\n // Single change log per filesystem root (branching is a Git concern,\n // not a metadata-layer concern).\n return path.join(logDir(layout), `main.jsonl`);\n}\n\n/** Parse a path like \".../view/case_grid.json\" into {type, name}. */\nexport function parseItemPath(\n layout: FsLayout,\n absPath: string,\n): { type: string; name: string } | null {\n const rel = path.relative(layout.root, absPath);\n if (rel.startsWith('..') || rel.startsWith('.objectstack')) return null;\n const segments = rel.split(path.sep);\n if (segments.length !== 2) return null;\n const type = segments[0]!;\n const file = segments[1]!;\n if (!file.endsWith('.json')) return null;\n const name = file.slice(0, -'.json'.length);\n return { type, name };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Append-only JSONL change log writer / reader. Each line is a single\n * `MetadataEvent` serialized via `JSON.stringify`.\n *\n * Durability strategy\n * ───────────────────\n * - Append with `O_APPEND` semantics (Node's `fs.appendFile` is\n * atomic for sub-PIPE_BUF-sized writes; events are well under 4 KiB).\n * - Read by streaming the file line-by-line and JSON.parse-ing each.\n * - On a corrupt line we skip and continue — the body files are the\n * source of truth; the log is a denormalised history index.\n */\n\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport readline from 'node:readline';\nimport { createReadStream, existsSync } from 'node:fs';\nimport type { MetadataEvent } from '@objectstack/metadata-core';\n\nexport class JsonlLog {\n constructor(private readonly file: string) {}\n\n async append(evt: MetadataEvent): Promise<void> {\n await fs.mkdir(path.dirname(this.file), { recursive: true });\n await fs.appendFile(this.file, JSON.stringify(evt) + '\\n', 'utf8');\n }\n\n /** Read all events in seq order (i.e. file order). */\n async *readAll(): AsyncIterable<MetadataEvent> {\n if (!existsSync(this.file)) return;\n const rl = readline.createInterface({\n input: createReadStream(this.file, { encoding: 'utf8' }),\n crlfDelay: Infinity,\n });\n try {\n for await (const line of rl) {\n if (!line.trim()) continue;\n try {\n yield JSON.parse(line) as MetadataEvent;\n } catch {\n // Skip corrupt line.\n }\n }\n } finally {\n rl.close();\n }\n }\n\n /** Return the highest seq number in the log, or 0 if empty. */\n async highestSeq(): Promise<number> {\n let max = 0;\n for await (const evt of this.readAll()) {\n if (typeof evt.seq === 'number' && evt.seq > max) max = evt.seq;\n }\n return max;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Mutex / event-broker primitives used by FileSystemRepository.\n *\n * `KeyedMutex` serializes operations on the same key (refKey). The\n * broker re-uses the same manual-AsyncIterator pattern as\n * InMemoryRepository so that consumer `return()` reliably unblocks.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\n\nexport class KeyedMutex {\n private readonly tails = new Map<string, Promise<unknown>>();\n\n async run<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = this.tails.get(key) ?? Promise.resolve();\n const next = prev.then(fn, fn);\n // Save the swallowed-error tail so successive runs don't reject on\n // an unrelated prior failure.\n const swallowed = next.catch(() => undefined);\n this.tails.set(key, swallowed);\n try {\n return await next;\n } finally {\n // Best-effort cleanup: drop the entry if nothing newer was queued.\n if (this.tails.get(key) === swallowed) {\n this.tails.delete(key);\n }\n }\n }\n}\n\nexport interface BrokerSubscriber {\n filter: WatchFilter;\n closed: boolean;\n push(evt: MetadataEvent): void;\n}\n\nexport interface EventBroker {\n subscribe(sub: BrokerSubscriber): void;\n unsubscribe(sub: BrokerSubscriber): void;\n publish(evt: MetadataEvent): void;\n}\n\nexport function createBroker(matches: (evt: MetadataEvent, filter: WatchFilter) => boolean): EventBroker {\n const subs = new Set<BrokerSubscriber>();\n return {\n subscribe: (s) => { subs.add(s); },\n unsubscribe: (s) => { subs.delete(s); },\n publish: (evt) => {\n for (const s of subs) {\n if (s.closed) continue;\n if (!matches(evt, s.filter)) continue;\n s.push(evt);\n }\n },\n };\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Manual `AsyncIterator` factory for `repo.watch()`. Mirrors the\n * pattern used in `@objectstack/metadata-core`'s `InMemoryRepository`:\n * async generators do NOT run `finally` when paused on an unresolved\n * `await`, so we cannot use them to implement `watch()`.\n */\n\nimport type { MetadataEvent, WatchFilter } from '@objectstack/metadata-core';\nimport { type EventBroker, type BrokerSubscriber } from './sync.js';\n\nexport interface CreateWatchIteratorArgs {\n filter: WatchFilter;\n since: number | undefined;\n replay: MetadataEvent[];\n broker: EventBroker;\n /** Returns true if `evt.ref` matches `filter`. */\n matches: (evt: MetadataEvent, filter: WatchFilter) => boolean;\n branchKeyOf: (evt: MetadataEvent) => string;\n}\n\nexport function createWatchIterable(\n args: CreateWatchIteratorArgs,\n): AsyncIterable<MetadataEvent> {\n const queue: MetadataEvent[] = [];\n let waiter: ((evt: IteratorResult<MetadataEvent>) => void) | null = null;\n let closed = false;\n const delivered = new Set<string>();\n const evtKey = (e: MetadataEvent) => `${args.branchKeyOf(e)}#${e.seq}`;\n\n const subscriber: BrokerSubscriber = {\n filter: args.filter,\n closed: false,\n push: (evt) => {\n if (subscriber.closed) return;\n const k = evtKey(evt);\n if (delivered.has(k)) return;\n if (waiter) {\n delivered.add(k);\n const w = waiter;\n waiter = null;\n w({ value: clone(evt), done: false });\n } else {\n queue.push(evt);\n }\n },\n };\n args.broker.subscribe(subscriber);\n\n const replay = [...args.replay].sort((a, b) => a.seq - b.seq);\n let replayIdx = 0;\n\n const drain = (): IteratorResult<MetadataEvent> | null => {\n while (replayIdx < replay.length) {\n const evt = replay[replayIdx++]!;\n if (typeof args.since === 'number' && evt.seq <= args.since) continue;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n while (queue.length > 0) {\n const evt = queue.shift()!;\n const k = evtKey(evt);\n if (delivered.has(k)) continue;\n delivered.add(k);\n return { value: clone(evt), done: false };\n }\n return null;\n };\n\n const close = (): IteratorResult<MetadataEvent> => {\n if (!closed) {\n closed = true;\n subscriber.closed = true;\n args.broker.unsubscribe(subscriber);\n if (waiter) {\n const w = waiter;\n waiter = null;\n w({ value: undefined, done: true });\n }\n }\n return { value: undefined, done: true };\n };\n\n const iterator: AsyncIterator<MetadataEvent> = {\n next: () => {\n if (closed) return Promise.resolve({ value: undefined, done: true });\n const immediate = drain();\n if (immediate) return Promise.resolve(immediate);\n return new Promise<IteratorResult<MetadataEvent>>((resolve) => {\n waiter = resolve;\n });\n },\n return: () => Promise.resolve(close()),\n throw: (err) => {\n close();\n return Promise.reject(err);\n },\n };\n return { [Symbol.asyncIterator]: () => iterator };\n}\n\nfunction clone<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n"],"mappings":";AAuBA,OAAOA,SAAQ;AACf,SAAS,cAAAC,mBAAkB;AAC3B,OAAOC,WAAU;AAEjB,OAAO,cAAc;AACrB;AAAA,EAcE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACpCP,OAAO,UAAU;AAQV,SAAS,SAAS,QAAkB,MAAoB,MAAsB;AACnF,SAAO,KAAK,KAAK,OAAO,MAAM,MAAM,GAAG,IAAI,OAAO;AACpD;AAEO,SAAS,QAAQ,QAAkB,MAA4B;AACpE,SAAO,KAAK,KAAK,OAAO,MAAM,IAAI;AACpC;AAEO,SAAS,OAAO,QAA0B;AAC/C,SAAO,KAAK,KAAK,OAAO,MAAM,gBAAgB,MAAM;AACtD;AAEO,SAAS,QAAQ,QAA0B;AAGhD,SAAO,KAAK,KAAK,OAAO,MAAM,GAAG,YAAY;AAC/C;AAGO,SAAS,cACd,QACA,SACuC;AACvC,QAAM,MAAM,KAAK,SAAS,OAAO,MAAM,OAAO;AAC9C,MAAI,IAAI,WAAW,IAAI,KAAK,IAAI,WAAW,cAAc,EAAG,QAAO;AACnE,QAAM,WAAW,IAAI,MAAM,KAAK,GAAG;AACnC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","evt"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@objectstack/metadata-fs",
|
|
3
|
-
"version": "17.0.0
|
|
3
|
+
"version": "17.0.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "FileSystemRepository: Node-only Repository implementation backed by JSON files and a JSONL change log (ADR-0008).",
|
|
6
6
|
"type": "module",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
],
|
|
27
27
|
"dependencies": {
|
|
28
28
|
"chokidar": "^5.0.0",
|
|
29
|
-
"@objectstack/metadata-core": "17.0.0
|
|
29
|
+
"@objectstack/metadata-core": "17.0.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@types/node": "^26.1.2",
|
|
@@ -54,6 +54,6 @@
|
|
|
54
54
|
"clean": "rm -rf dist",
|
|
55
55
|
"test": "vitest run",
|
|
56
56
|
"test:watch": "vitest",
|
|
57
|
-
"typecheck": "tsc --noEmit"
|
|
57
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json"
|
|
58
58
|
}
|
|
59
59
|
}
|