|
1 | 1 | import envPaths from 'env-paths'; |
2 | | -import {rm} from 'node:fs/promises'; |
| 2 | +import {opendir, rm} from 'node:fs/promises'; |
3 | 3 | import path from 'node:path'; |
4 | 4 | import {BaseItem} from './base-item'; |
5 | 5 | import {slugify} from './util'; |
@@ -106,7 +106,7 @@ export type ItemCtor< |
106 | 106 | * |
107 | 107 | * Manages multiple {@linkcode Item}s. |
108 | 108 | */ |
109 | | -export class Strongbox<Options extends StrongboxOpts = StrongboxOpts> { |
| 109 | +export class Strongbox<Options extends StrongboxOpts = StrongboxOpts> implements AsyncIterable<Item<any>> { |
110 | 110 | /** |
111 | 111 | * Default {@linkcode ItemCtor} to use when creating new {@linkcode Item}s |
112 | 112 | */ |
@@ -204,7 +204,7 @@ export class Strongbox<Options extends StrongboxOpts = StrongboxOpts> { |
204 | 204 | this, |
205 | 205 | encoding |
206 | 206 | ); |
207 | | - if (this.items.has(item.id)) { |
| 207 | + if (this.getLiveItem(item.id)) { |
208 | 208 | throw new ReferenceError(`Item with id "${item.id}" already exists`); |
209 | 209 | } |
210 | 210 | try { |
@@ -254,12 +254,64 @@ export class Strongbox<Options extends StrongboxOpts = StrongboxOpts> { |
254 | 254 |
|
255 | 255 | /** |
256 | 256 | * Attempts to retrieve an {@linkcode Item} by its `id`. |
| 257 | + * Drops stale {@linkcode WeakRef} map entries when the value was collected. |
257 | 258 | * @param id ID of item |
258 | 259 | * @returns An `Item`, if found |
259 | 260 | */ |
260 | 261 | public getItem(id: string): Item<any> | undefined { |
| 262 | + return this.getLiveItem(id); |
| 263 | + } |
| 264 | + |
| 265 | + /** |
| 266 | + * Returns a live {@linkcode Item} or removes a stale {@linkcode WeakRef} from {@linkcode Strongbox.items}. |
| 267 | + */ |
| 268 | + private getLiveItem(id: string): Item<any> | undefined { |
261 | 269 | const ref = this.items.get(id); |
262 | | - return ref?.deref(); |
| 270 | + if (!ref) { |
| 271 | + return undefined; |
| 272 | + } |
| 273 | + const item = ref.deref(); |
| 274 | + if (!item) { |
| 275 | + this.items.delete(id); |
| 276 | + return undefined; |
| 277 | + } |
| 278 | + return item; |
| 279 | + } |
| 280 | + |
| 281 | + /** |
| 282 | + * Lists persisted items by scanning the container directory (one regular file per item). |
| 283 | + * |
| 284 | + * Filenames are matched to items by path; if an item was already registered (e.g. via |
| 285 | + * {@linkcode Strongbox.createItem}), that instance is returned and keeps its original `name`. |
| 286 | + * Otherwise a new item is created using the filename as `name` (see {@linkcode BaseItem}). |
| 287 | + * |
| 288 | + * @remarks Builds one array of every {@linkcode Item} reference. Does not read file contents; |
| 289 | + * call {@linkcode Item.read} on each item as needed. Order follows directory iteration |
| 290 | + * ({@linkcode opendir}), not lexicographic sort. For many items, `for await (const item of box)` |
| 291 | + * ({@linkcode Symbol.asyncIterator}) streams entries without allocating a full {@linkcode Item}[] |
| 292 | + * first. |
| 293 | + * |
| 294 | + * @returns Items in directory iteration order; empty if the container directory does not exist yet |
| 295 | + */ |
| 296 | + public async listItems(): Promise<Item<any>[]> { |
| 297 | + const items: Item<any>[] = []; |
| 298 | + for await (const basename of this.iterateFileBasenames()) { |
| 299 | + items.push(this.resolveItemForBasename(basename)); |
| 300 | + } |
| 301 | + return items; |
| 302 | + } |
| 303 | + |
| 304 | + /** |
| 305 | + * Yields each persisted item in the same order as {@linkcode Strongbox.listItems}. Use |
| 306 | + * `for await (const item of box)`. |
| 307 | + * |
| 308 | + * @remarks Walks the container with {@linkcode opendir} and yields one {@linkcode Item} per file |
| 309 | + * as basenames are seen (no full-name buffer and no sort). |
| 310 | + */ |
| 311 | + public async *[Symbol.asyncIterator](): AsyncIterableIterator<Item<any>> { |
| 312 | + for await (const basename of this.iterateFileBasenames()) { |
| 313 | + yield this.resolveItemForBasename(basename); |
| 314 | + } |
263 | 315 | } |
264 | 316 |
|
265 | 317 | /** |
@@ -298,6 +350,46 @@ export class Strongbox<Options extends StrongboxOpts = StrongboxOpts> { |
298 | 350 | newOpts.defaultItemCtor = opts.defaultItemCtor ?? BaseItem; |
299 | 351 | return newOpts; |
300 | 352 | } |
| 353 | + |
| 354 | + /** |
| 355 | + * Streams regular-file basenames from the container using {@linkcode opendir} (order is |
| 356 | + * filesystem-defined, not sorted). |
| 357 | + */ |
| 358 | + private async *iterateFileBasenames(): AsyncIterableIterator<string> { |
| 359 | + let dir: Awaited<ReturnType<typeof opendir>>; |
| 360 | + try { |
| 361 | + dir = await opendir(this.container); |
| 362 | + } catch (e) { |
| 363 | + if ((e as NodeJS.ErrnoException).code === 'ENOENT') { |
| 364 | + return; |
| 365 | + } |
| 366 | + throw e; |
| 367 | + } |
| 368 | + for await (const ent of dir) { |
| 369 | + if (ent.isFile()) { |
| 370 | + yield ent.name; |
| 371 | + } |
| 372 | + } |
| 373 | + } |
| 374 | + |
| 375 | + /** |
| 376 | + * Registers an {@linkcode Item} for a filename on disk without reading the file (see |
| 377 | + * {@linkcode Strongbox.createItem}, which loads persisted contents eagerly). Uses the same |
| 378 | + * constructor arity as {@linkcode Strongbox.createItem} when no encoding is given. |
| 379 | + */ |
| 380 | + private registerItemWithoutRead(name: string): Item<any> { |
| 381 | + const item = new (this.defaultItemCtor as ItemCtor<any>)(name, this, undefined); |
| 382 | + if (this.getLiveItem(item.id)) { |
| 383 | + throw new ReferenceError(`Item with id "${item.id}" already exists`); |
| 384 | + } |
| 385 | + this.items.set(item.id, new WeakRef(item)); |
| 386 | + return item; |
| 387 | + } |
| 388 | + |
| 389 | + private resolveItemForBasename(basename: string): Item<any> { |
| 390 | + const id = BaseItem.toFilePath(this.container, basename); |
| 391 | + return this.getItem(id) ?? this.registerItemWithoutRead(basename); |
| 392 | + } |
301 | 393 | } |
302 | 394 |
|
303 | 395 | /** |
|
0 commit comments