@objectstack/metadata-fs 17.0.0-rc.5 → 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 +323 -0
- package/README.md +16 -1
- package/dist/index.cjs +142 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +115 -2
- package/dist/index.d.ts +115 -2
- package/dist/index.js +142 -19
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
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;
|
|
@@ -222,15 +220,42 @@ var FileSystemRepository = class {
|
|
|
222
220
|
this.log = new JsonlLog(logFile(this.layout));
|
|
223
221
|
}
|
|
224
222
|
// ── Lifecycle ───────────────────────────────────────────────────────
|
|
223
|
+
/**
|
|
224
|
+
* Attach the repository. **Creates nothing on disk** (#7000).
|
|
225
|
+
*
|
|
226
|
+
* Attaching is not a write. `start()` used to `mkdir` both the root and
|
|
227
|
+
* `<root>/.objectstack/.log` unconditionally, which meant every read-only
|
|
228
|
+
* boot that merely attaches a repository left a skeleton behind — most
|
|
229
|
+
* visibly `os migrate plan`, a declared dry run, on a project that has
|
|
230
|
+
* never been started. That is the same property #6743 ruled on for
|
|
231
|
+
* `.objectstack/data/`: a dry run leaves nothing behind, and the existence
|
|
232
|
+
* of `.objectstack/` has to stay a usable "this project has been started"
|
|
233
|
+
* signal.
|
|
234
|
+
*
|
|
235
|
+
* Every read path below already treats a missing root as an empty
|
|
236
|
+
* repository (`scanHeads` swallows ENOENT, `JsonlLog` guards on
|
|
237
|
+
* `existsSync`, `get` guards on `existsSync`), so the root is materialized
|
|
238
|
+
* by `ensureRoot()` on the first write instead.
|
|
239
|
+
*/
|
|
225
240
|
async start() {
|
|
226
241
|
if (this.started) return;
|
|
227
242
|
this.started = true;
|
|
228
|
-
await fs2.mkdir(this.layout.root, { recursive: true });
|
|
229
|
-
await fs2.mkdir(logDir(this.layout), { recursive: true });
|
|
230
243
|
await this.scanHeads();
|
|
231
244
|
const highest = await this.log.highestSeq();
|
|
232
245
|
this.nextSeq = highest + 1;
|
|
233
|
-
if (!this.disableWatch) this.startWatcher();
|
|
246
|
+
if (!this.disableWatch && existsSync2(this.layout.root)) this.startWatcher();
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Bring the repository root into existence. Called by every write path
|
|
250
|
+
* immediately before it touches the disk — `start()` deliberately does not
|
|
251
|
+
* create it (#7000), so this is the single seam where the root appears.
|
|
252
|
+
*
|
|
253
|
+
* It is also where a watcher that `start()` could not arm (missing root)
|
|
254
|
+
* gets armed, so "external edits are detected" survives the change.
|
|
255
|
+
*/
|
|
256
|
+
async ensureRoot() {
|
|
257
|
+
await fs2.mkdir(this.layout.root, { recursive: true });
|
|
258
|
+
if (this.started && !this.disableWatch && !this.watcher) this.startWatcher();
|
|
234
259
|
}
|
|
235
260
|
async close() {
|
|
236
261
|
if (this.watcher) {
|
|
@@ -348,13 +373,10 @@ var FileSystemRepository = class {
|
|
|
348
373
|
const seq = this.nextSeq++;
|
|
349
374
|
const ts = this.now().toISOString();
|
|
350
375
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
376
|
+
await this.ensureRoot();
|
|
351
377
|
await fs2.mkdir(typeDir(this.layout, ref.type), { recursive: true });
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
await writeJsonAtomic(file, spec);
|
|
355
|
-
} finally {
|
|
356
|
-
setTimeout(() => this.selfWrites.delete(file), 200);
|
|
357
|
-
}
|
|
378
|
+
await writeJsonAtomic(file, spec);
|
|
379
|
+
this.trackWrittenPath(file);
|
|
358
380
|
this.heads.set(key, hash);
|
|
359
381
|
const evt = {
|
|
360
382
|
seq,
|
|
@@ -394,13 +416,14 @@ var FileSystemRepository = class {
|
|
|
394
416
|
throw new ConflictError(ref, opts.parentVersion, currentHead);
|
|
395
417
|
}
|
|
396
418
|
const file = itemPath(this.layout, ref.type, ref.name);
|
|
397
|
-
this.
|
|
419
|
+
await this.ensureRoot();
|
|
420
|
+
this.heads.delete(key);
|
|
398
421
|
try {
|
|
399
422
|
if (existsSync2(file)) await fs2.unlink(file);
|
|
400
|
-
}
|
|
401
|
-
|
|
423
|
+
} catch (err) {
|
|
424
|
+
if (currentHead !== null) this.heads.set(key, currentHead);
|
|
425
|
+
throw err;
|
|
402
426
|
}
|
|
403
|
-
this.heads.delete(key);
|
|
404
427
|
const seq = this.nextSeq++;
|
|
405
428
|
const ts = this.now().toISOString();
|
|
406
429
|
const evt = {
|
|
@@ -469,10 +492,58 @@ var FileSystemRepository = class {
|
|
|
469
492
|
}
|
|
470
493
|
return last;
|
|
471
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Register a path this repository just wrote with the watcher (#7282).
|
|
497
|
+
*
|
|
498
|
+
* chokidar's initial scan is asynchronous, and every write path here can be
|
|
499
|
+
* running **while it is still walking the tree** — `start()` arms the watcher
|
|
500
|
+
* and the caller may `put()` on the next tick, and `ensureRoot()` arms it in
|
|
501
|
+
* the middle of the very first write. With `usePolling` that combination has
|
|
502
|
+
* a permanently-blinding interleaving, measured on chokidar 5 with this
|
|
503
|
+
* repository's own options:
|
|
504
|
+
*
|
|
505
|
+
* 1. chokidar reads `<root>/<type>/` and finds it EMPTY — the atomic
|
|
506
|
+
* `rename` in `writeJsonAtomic` has not landed yet.
|
|
507
|
+
* 2. the rename lands; the directory's mtime changes.
|
|
508
|
+
* 3. chokidar calls `watchFile()` on that directory, and libuv takes its
|
|
509
|
+
* polling baseline stat — which already reflects step 2.
|
|
510
|
+
*
|
|
511
|
+
* From then on the directory's stat never changes again, so no poll ever
|
|
512
|
+
* fires for it, `_handleRead` never re-runs, the item file is never added to
|
|
513
|
+
* the watched set, and no per-file watcher is ever created. chokidar emits
|
|
514
|
+
* neither `add` nor `change` for that path **for the life of the process** —
|
|
515
|
+
* `getWatched()` reports the type directory as `[]` forever while the file
|
|
516
|
+
* sits in it. That is the whole of #7282: the four merge-queue ejections all
|
|
517
|
+
* waited out their deadlines (20s, then 25541ms against 25s) on an event that
|
|
518
|
+
* was never going to be delivered, which is why widening the deadline and
|
|
519
|
+
* widening the pre-edit sleep both changed nothing, and why lowering
|
|
520
|
+
* `interval` would change nothing either — a shorter poll re-compares against
|
|
521
|
+
* the same unchanged directory stat.
|
|
522
|
+
*
|
|
523
|
+
* The window is exactly "files that exist at baseline time but were absent
|
|
524
|
+
* from the snapshot read a moment earlier", and the only writer that can be
|
|
525
|
+
* inside it is us. So we close it at the source: tell the watcher explicitly
|
|
526
|
+
* about every path we create, instead of hoping its scan happened to see it.
|
|
527
|
+
*
|
|
528
|
+
* `add()` is idempotent here — `_handleFile` returns early when the parent
|
|
529
|
+
* directory already tracks the basename — and it emits nothing, because
|
|
530
|
+
* chokidar treats an explicit `add()` as an initial add and `ignoreInitial`
|
|
531
|
+
* is set. Its effect is the one we need: `_watchWithNodeFs` registers the
|
|
532
|
+
* basename with the parent directory (without which chokidar drops `change`
|
|
533
|
+
* events for the file) and starts the per-file poll.
|
|
534
|
+
*/
|
|
535
|
+
trackWrittenPath(file) {
|
|
536
|
+
const w = this.watcher;
|
|
537
|
+
if (!w || w.closed) return;
|
|
538
|
+
w.add(file);
|
|
539
|
+
}
|
|
472
540
|
startWatcher() {
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
//
|
|
541
|
+
const root = this.layout.root;
|
|
542
|
+
const w = chokidar.watch(root, {
|
|
543
|
+
// Skip dotfiles under the root — including the repository's own
|
|
544
|
+
// `.objectstack/` bookkeeping subtree — matched on the path RELATIVE
|
|
545
|
+
// to the watch root (#7150). See `isIgnoredWatchPath`.
|
|
546
|
+
ignored: (p) => isIgnoredWatchPath(root, p),
|
|
476
547
|
ignoreInitial: true,
|
|
477
548
|
depth: 2,
|
|
478
549
|
awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 20 },
|
|
@@ -488,8 +559,55 @@ var FileSystemRepository = class {
|
|
|
488
559
|
w.on("unlink", (p) => void this.handleFsChange(p, "unlink"));
|
|
489
560
|
this.watcher = w;
|
|
490
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
|
+
*/
|
|
491
610
|
async handleFsChange(absPath, kind) {
|
|
492
|
-
if (this.selfWrites.has(absPath)) return;
|
|
493
611
|
const parsed = parseItemPath(this.layout, absPath);
|
|
494
612
|
if (!parsed) return;
|
|
495
613
|
const ref = {
|
|
@@ -540,6 +658,11 @@ var FileSystemRepository = class {
|
|
|
540
658
|
});
|
|
541
659
|
}
|
|
542
660
|
};
|
|
661
|
+
function isIgnoredWatchPath(root, absPath) {
|
|
662
|
+
const rel = path3.relative(root, absPath);
|
|
663
|
+
if (rel === "" || rel.startsWith("..")) return false;
|
|
664
|
+
return rel.split(/[\\/]/).some((segment) => segment.startsWith("."));
|
|
665
|
+
}
|
|
543
666
|
async function readJson(file) {
|
|
544
667
|
try {
|
|
545
668
|
const text = await fs2.readFile(file, "utf8");
|
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 */\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 logDir,\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 async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n await fs.mkdir(this.layout.root, { recursive: true });\n await fs.mkdir(logDir(this.layout), { recursive: true });\n\n // 1) Scan body files to build the head index.\n await this.scanHeads();\n\n // 2) Hydrate nextSeq from the existing log.\n const highest = await this.log.highestSeq();\n this.nextSeq = highest + 1;\n\n // 3) Start the watcher (unless disabled).\n if (!this.disableWatch) 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 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 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 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 private startWatcher(): void {\n const w = chokidar.watch(this.layout.root, {\n ignored: [/(^|[\\\\/])\\../], // skip dotfiles incl. .objectstack\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\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":";AAoBA,OAAOA,SAAQ;AACf,SAAS,cAAAC,mBAAkB;AAC3B,OAAOC,WAAU;AAEjB,OAAO,cAAc;AACrB;AAAA,EAcE;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACjCP,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;A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,WAAW,MAAM;AACvB,oBAAQ,SAAS,OAAO,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":["fs","existsSync","path","path","path","fs","existsSync","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,Q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,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":["fs","existsSync","path","path","path","existsSync","fs","currentHead","seq","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
|
}
|