@jibone/todotxt-core 0.6.0 → 0.7.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/README.md +73 -3
- package/dist/index.d.ts +69 -3
- package/dist/index.js +97 -14
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -403,6 +403,72 @@ logged as `error`; the other levels are reserved for the write APIs. Logging is
|
|
|
403
403
|
best-effort: a logger that throws or rejects never breaks a read or query. See
|
|
404
404
|
`examples/todo-logger.ts`.
|
|
405
405
|
|
|
406
|
+
Warnings are also available without a logger, as data; see
|
|
407
|
+
[Warnings and errors as data](#warnings-and-errors-as-data).
|
|
408
|
+
|
|
409
|
+
## Warnings and errors as data
|
|
410
|
+
|
|
411
|
+
`onWarning` callbacks and the [logger](#logging) are not the only way to learn
|
|
412
|
+
what was wrong with a file. `parseDocumentResult` returns the same records as
|
|
413
|
+
`parseDocument` plus the warnings and line counts as data:
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
import { parseDocumentResult } from "@jibone/todotxt-core";
|
|
417
|
+
|
|
418
|
+
const result = parseDocumentResult(contents);
|
|
419
|
+
// {
|
|
420
|
+
// records: TodoRecord[],
|
|
421
|
+
// warnings: [
|
|
422
|
+
// { code: "invalid-date", message: "...", line: 3, meta: { ... } },
|
|
423
|
+
// { code: "duplicate-metadata-key", message: "...", line: 4, meta: { ... } },
|
|
424
|
+
// ],
|
|
425
|
+
// lineCount: 4, // physical lines; a trailing newline adds none
|
|
426
|
+
// skippedLines: 1, // blank or whitespace-only lines
|
|
427
|
+
// }
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
Warnings appear in document order with 1-based physical line numbers.
|
|
431
|
+
`lineCount` counts physical lines — a single trailing newline ends the last
|
|
432
|
+
line instead of starting an empty one, and the empty input has no lines.
|
|
433
|
+
`skippedLines` counts the blank and whitespace-only lines the parser ignored.
|
|
434
|
+
Warnings are still forwarded to `options.onWarning` when supplied.
|
|
435
|
+
|
|
436
|
+
Clients expose the same data without hooks. `warnings()` returns the warnings
|
|
437
|
+
of the most recent successful read:
|
|
438
|
+
|
|
439
|
+
```ts
|
|
440
|
+
const records = await todos.all();
|
|
441
|
+
const warnings = todos.warnings();
|
|
442
|
+
// ParseWarning[] in document order, or [] after a clean read.
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
It is an additional access path: the [logger](#logging) still receives the
|
|
446
|
+
same warnings. The returned array and its warnings are copies, so callers may
|
|
447
|
+
mutate them freely. A read that fails leaves the previous read's warnings in
|
|
448
|
+
place, and `warnings()` returns `[]` before the first read.
|
|
449
|
+
|
|
450
|
+
### Read errors
|
|
451
|
+
|
|
452
|
+
Rejections from the `read` hook stay promise rejections. When the rejected
|
|
453
|
+
value is already an `Error` — including filesystem errors with a `code` such
|
|
454
|
+
as `ENOENT` — it propagates untouched, so existing error-code checks keep
|
|
455
|
+
working. A hook that rejects with anything else (a thrown string, a plain
|
|
456
|
+
object) is wrapped in a `TodoReadError` with the original value on `cause`:
|
|
457
|
+
|
|
458
|
+
```ts
|
|
459
|
+
import { TodoReadError } from "@jibone/todotxt-core";
|
|
460
|
+
|
|
461
|
+
try {
|
|
462
|
+
await todos.all();
|
|
463
|
+
} catch (error) {
|
|
464
|
+
if (error instanceof TodoReadError) {
|
|
465
|
+
// The read hook rejected with a non-Error value.
|
|
466
|
+
console.error(error.cause);
|
|
467
|
+
}
|
|
468
|
+
// A real Error (including fs errors with .code) arrives untouched.
|
|
469
|
+
}
|
|
470
|
+
```
|
|
471
|
+
|
|
406
472
|
## Parser
|
|
407
473
|
|
|
408
474
|
The parser also works without the client wrapper:
|
|
@@ -418,9 +484,11 @@ const records = parseDocument(contents);
|
|
|
418
484
|
original line unless [source metadata](#source-metadata) is enabled. Dates must
|
|
419
485
|
be real calendar dates in `YYYY-MM-DD` form; a shape-valid but nonexistent date
|
|
420
486
|
such as `2011-99-99` is treated as text and reported as an `invalid-date`
|
|
421
|
-
warning. Collect warnings by passing `onWarning` in a `ParseOptions` object
|
|
422
|
-
|
|
423
|
-
|
|
487
|
+
warning. Collect warnings by passing `onWarning` in a `ParseOptions` object, or
|
|
488
|
+
get them back as data with
|
|
489
|
+
[`parseDocumentResult`](#warnings-and-errors-as-data); passing the handler
|
|
490
|
+
directly as the second argument is deprecated but still supported. The full
|
|
491
|
+
rule-by-rule interpretation is documented in
|
|
424
492
|
[How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md).
|
|
425
493
|
|
|
426
494
|
Writing is not implemented yet. The `write` hook is optional for now and will
|
|
@@ -434,10 +502,12 @@ bun examples/todo-project.ts
|
|
|
434
502
|
bun examples/todo-context.ts
|
|
435
503
|
bun examples/todo-cross.ts
|
|
436
504
|
bun examples/todo-logger.ts
|
|
505
|
+
bun examples/todo-warnings.ts
|
|
437
506
|
bun examples/todo-try.ts
|
|
438
507
|
bun examples/todo-source.ts
|
|
439
508
|
bun examples/todo-filters.ts
|
|
440
509
|
bun examples/todo-sort.ts
|
|
510
|
+
bun examples/todo-summary.ts
|
|
441
511
|
```
|
|
442
512
|
|
|
443
513
|
Each format rule also has a runnable example:
|
package/dist/index.d.ts
CHANGED
|
@@ -52,6 +52,29 @@ interface ParseOptions {
|
|
|
52
52
|
/** Receives parse warnings. */
|
|
53
53
|
onWarning?: ParseWarningHandler;
|
|
54
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* The outcome of parsing a whole todo.txt document.
|
|
57
|
+
*
|
|
58
|
+
* Returned by {@link parseDocumentResult}. {@link parseDocument} returns the
|
|
59
|
+
* {@link ParseResult.records} alone.
|
|
60
|
+
*/
|
|
61
|
+
interface ParseResult {
|
|
62
|
+
/** Every non-empty line parsed into a {@link TodoRecord}. */
|
|
63
|
+
records: TodoRecord[];
|
|
64
|
+
/**
|
|
65
|
+
* Every warning from the document, in document order, annotated with the
|
|
66
|
+
* 1-based physical line number.
|
|
67
|
+
*/
|
|
68
|
+
warnings: ParseWarning[];
|
|
69
|
+
/**
|
|
70
|
+
* Number of physical lines in the input. A single trailing newline ends
|
|
71
|
+
* the last line rather than starting an empty one, and the empty input has
|
|
72
|
+
* no lines.
|
|
73
|
+
*/
|
|
74
|
+
lineCount: number;
|
|
75
|
+
/** Lines skipped because they were blank or whitespace-only. */
|
|
76
|
+
skippedLines: number;
|
|
77
|
+
}
|
|
55
78
|
/**
|
|
56
79
|
* Callbacks supplied by the consumer.
|
|
57
80
|
*
|
|
@@ -335,6 +358,16 @@ interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
|
335
358
|
interface TodoTxtClient {
|
|
336
359
|
/** Read fresh todo.txt contents, replace the cache, and return every record. */
|
|
337
360
|
all: () => Promise<TodoRecord[]>;
|
|
361
|
+
/**
|
|
362
|
+
* Warnings from the most recent successful read, in document order.
|
|
363
|
+
*
|
|
364
|
+
* Empty before the first read and after a read without warnings. A failed
|
|
365
|
+
* read leaves the previous read's warnings in place. The returned array and
|
|
366
|
+
* its warnings are copies, so callers may mutate them without affecting
|
|
367
|
+
* later calls. A `logger`, when supplied, still receives warnings as they
|
|
368
|
+
* are found; this is an additional access path, not a replacement.
|
|
369
|
+
*/
|
|
370
|
+
warnings: () => ParseWarning[];
|
|
338
371
|
/** Query only records that are not completed, using the cached snapshot. */
|
|
339
372
|
pending: () => TodoQuery;
|
|
340
373
|
/** Query only records that are completed, using the cached snapshot. */
|
|
@@ -391,8 +424,12 @@ interface TodoTxtClient {
|
|
|
391
424
|
* producing the file contents and `options.write` will be used by the write
|
|
392
425
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
393
426
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
394
|
-
* diagnostics.
|
|
395
|
-
*
|
|
427
|
+
* diagnostics. Warnings from the most recent read are also available as data
|
|
428
|
+
* through {@link TodoTxtClient.warnings}. A `read` hook rejection propagates
|
|
429
|
+
* untouched when the rejected value is an `Error`; any other value is wrapped
|
|
430
|
+
* in a {@link TodoReadError} that carries the original on `cause`. With
|
|
431
|
+
* `options.includeSource`, every record also carries the 1-based `line` number
|
|
432
|
+
* and the exact `raw` line it was parsed from. With
|
|
396
433
|
* `options.caseSensitive: false`, project and context matching compares
|
|
397
434
|
* names through `toLowerCase()`; the default is exact matching.
|
|
398
435
|
*
|
|
@@ -410,6 +447,20 @@ interface TodoTxtClient {
|
|
|
410
447
|
* without affecting the cache.
|
|
411
448
|
*/
|
|
412
449
|
export declare function createTodoTxt(options: TodoClientOptions): TodoTxtClient;
|
|
450
|
+
/**
|
|
451
|
+
* Thrown when a consumer-supplied read hook rejects with a value that is not
|
|
452
|
+
* an `Error`.
|
|
453
|
+
*
|
|
454
|
+
* Rejections that are already `Error` instances — including filesystem errors
|
|
455
|
+
* with a `code` such as `ENOENT` — propagate untouched, so existing
|
|
456
|
+
* error-code checks keep working. Anything else, such as a thrown string or a
|
|
457
|
+
* plain object, is wrapped; the original value is available on `cause`.
|
|
458
|
+
*/
|
|
459
|
+
export declare class TodoReadError extends Error {
|
|
460
|
+
/** The value the read hook rejected with. */
|
|
461
|
+
readonly cause: unknown;
|
|
462
|
+
constructor(message: string, cause: unknown);
|
|
463
|
+
}
|
|
413
464
|
/**
|
|
414
465
|
* Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
|
|
415
466
|
*
|
|
@@ -448,4 +499,19 @@ export declare function parseLine(line: string, onWarning: ParseWarningHandler):
|
|
|
448
499
|
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
449
500
|
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
450
501
|
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
451
|
-
|
|
502
|
+
/**
|
|
503
|
+
* Parse the contents of a todo.txt file, returning records, warnings, and
|
|
504
|
+
* line counts as data.
|
|
505
|
+
*
|
|
506
|
+
* The records are exactly what {@link parseDocument} returns. The
|
|
507
|
+
* {@link ParseResult} additionally carries every warning in document order
|
|
508
|
+
* (annotated with the 1-based physical line number), the number of physical
|
|
509
|
+
* lines, and how many of them were blank or whitespace-only. A single
|
|
510
|
+
* trailing newline ends the last line rather than starting an empty one, and
|
|
511
|
+
* the empty input has no lines.
|
|
512
|
+
*
|
|
513
|
+
* Warnings are also forwarded to `options.onWarning` when supplied, so this
|
|
514
|
+
* composes with existing warning handling.
|
|
515
|
+
*/
|
|
516
|
+
export declare function parseDocumentResult(contents: string, options?: ParseOptions): ParseResult;
|
|
517
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseResult, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoCount, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoNameCount, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoSummary, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -19,6 +19,22 @@ function cloneRecord(todo) {
|
|
|
19
19
|
function cloneRecords(records) {
|
|
20
20
|
return records.map(cloneRecord);
|
|
21
21
|
}
|
|
22
|
+
// src/errors.ts
|
|
23
|
+
/**
|
|
24
|
+
* Thrown when a consumer-supplied read hook rejects with a value that is not
|
|
25
|
+
* an `Error`.
|
|
26
|
+
*
|
|
27
|
+
* Rejections that are already `Error` instances — including filesystem errors
|
|
28
|
+
* with a `code` such as `ENOENT` — propagate untouched, so existing
|
|
29
|
+
* error-code checks keep working. Anything else, such as a thrown string or a
|
|
30
|
+
* plain object, is wrapped; the original value is available on `cause`.
|
|
31
|
+
*/
|
|
32
|
+
var TodoReadError = class extends Error {
|
|
33
|
+
constructor(message, cause) {
|
|
34
|
+
super(message, { cause });
|
|
35
|
+
this.name = "TodoReadError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
22
38
|
// src/date.ts
|
|
23
39
|
const DATE_SHAPE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
24
40
|
const DAYS_IN_MONTH = [
|
|
@@ -212,22 +228,68 @@ function parseLine(line, onWarningOrOptions) {
|
|
|
212
228
|
}
|
|
213
229
|
return record;
|
|
214
230
|
}
|
|
215
|
-
|
|
216
|
-
|
|
231
|
+
/**
|
|
232
|
+
* Shared document parser behind {@link parseDocument} and
|
|
233
|
+
* {@link parseDocumentResult}.
|
|
234
|
+
*
|
|
235
|
+
* Warnings are always collected, in document order and annotated with their
|
|
236
|
+
* 1-based physical line number, and forwarded to the consumer's `onWarning`
|
|
237
|
+
* when one is supplied. A single trailing newline ends the last line rather
|
|
238
|
+
* than starting an empty one, so it adds neither a line nor a skipped line.
|
|
239
|
+
*/
|
|
240
|
+
function parseDocumentCore(contents, options) {
|
|
241
|
+
const { includeSource, onWarning } = options;
|
|
242
|
+
const segments = contents.split(/\r?\n/);
|
|
243
|
+
const lines = contents === "" ? [] : contents.endsWith("\n") ? segments.slice(0, -1) : segments;
|
|
217
244
|
const records = [];
|
|
245
|
+
const warnings = [];
|
|
246
|
+
let skippedLines = 0;
|
|
218
247
|
let lineNumber = 0;
|
|
219
|
-
for (const line of
|
|
248
|
+
for (const line of lines) {
|
|
220
249
|
lineNumber += 1;
|
|
221
|
-
if (line.trim()
|
|
250
|
+
if (line.trim() === "") {
|
|
251
|
+
skippedLines += 1;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
records.push(parseLine(line, {
|
|
222
255
|
includeSource,
|
|
223
256
|
line: lineNumber,
|
|
224
|
-
onWarning:
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
257
|
+
onWarning: (warning) => {
|
|
258
|
+
const annotated = {
|
|
259
|
+
...warning,
|
|
260
|
+
line: lineNumber
|
|
261
|
+
};
|
|
262
|
+
warnings.push(annotated);
|
|
263
|
+
onWarning?.(annotated);
|
|
264
|
+
}
|
|
228
265
|
}));
|
|
229
266
|
}
|
|
230
|
-
return
|
|
267
|
+
return {
|
|
268
|
+
records,
|
|
269
|
+
warnings,
|
|
270
|
+
lineCount: lines.length,
|
|
271
|
+
skippedLines
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
function parseDocument(contents, onWarningOrOptions) {
|
|
275
|
+
return parseDocumentCore(contents, normalizeParseOptions(onWarningOrOptions)).records;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Parse the contents of a todo.txt file, returning records, warnings, and
|
|
279
|
+
* line counts as data.
|
|
280
|
+
*
|
|
281
|
+
* The records are exactly what {@link parseDocument} returns. The
|
|
282
|
+
* {@link ParseResult} additionally carries every warning in document order
|
|
283
|
+
* (annotated with the 1-based physical line number), the number of physical
|
|
284
|
+
* lines, and how many of them were blank or whitespace-only. A single
|
|
285
|
+
* trailing newline ends the last line rather than starting an empty one, and
|
|
286
|
+
* the empty input has no lines.
|
|
287
|
+
*
|
|
288
|
+
* Warnings are also forwarded to `options.onWarning` when supplied, so this
|
|
289
|
+
* composes with existing warning handling.
|
|
290
|
+
*/
|
|
291
|
+
function parseDocumentResult(contents, options) {
|
|
292
|
+
return parseDocumentCore(contents, normalizeParseOptions(options));
|
|
231
293
|
}
|
|
232
294
|
// src/query.ts
|
|
233
295
|
function uniqueSorted(values) {
|
|
@@ -513,8 +575,12 @@ function createTodoQuery(load, state = {
|
|
|
513
575
|
* producing the file contents and `options.write` will be used by the write
|
|
514
576
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
515
577
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
516
|
-
* diagnostics.
|
|
517
|
-
*
|
|
578
|
+
* diagnostics. Warnings from the most recent read are also available as data
|
|
579
|
+
* through {@link TodoTxtClient.warnings}. A `read` hook rejection propagates
|
|
580
|
+
* untouched when the rejected value is an `Error`; any other value is wrapped
|
|
581
|
+
* in a {@link TodoReadError} that carries the original on `cause`. With
|
|
582
|
+
* `options.includeSource`, every record also carries the 1-based `line` number
|
|
583
|
+
* and the exact `raw` line it was parsed from. With
|
|
518
584
|
* `options.caseSensitive: false`, project and context matching compares
|
|
519
585
|
* names through `toLowerCase()`; the default is exact matching.
|
|
520
586
|
*
|
|
@@ -533,6 +599,7 @@ function createTodoQuery(load, state = {
|
|
|
533
599
|
*/
|
|
534
600
|
function createTodoTxt(options) {
|
|
535
601
|
let cache;
|
|
602
|
+
let lastWarnings = [];
|
|
536
603
|
let inFlight;
|
|
537
604
|
let generation = 0;
|
|
538
605
|
const logger = options.logger;
|
|
@@ -546,7 +613,14 @@ function createTodoTxt(options) {
|
|
|
546
613
|
const readFresh = async () => {
|
|
547
614
|
const currentGeneration = ++generation;
|
|
548
615
|
log("debug", "Reading todo file");
|
|
549
|
-
|
|
616
|
+
let contents;
|
|
617
|
+
try {
|
|
618
|
+
contents = await options.read();
|
|
619
|
+
} catch (cause) {
|
|
620
|
+
if (cause instanceof Error) throw cause;
|
|
621
|
+
throw new TodoReadError("The read hook rejected with a non-Error value.", cause);
|
|
622
|
+
}
|
|
623
|
+
const result = parseDocumentResult(contents, {
|
|
550
624
|
includeSource: options.includeSource,
|
|
551
625
|
onWarning: (warning) => {
|
|
552
626
|
log("warn", warning.message, {
|
|
@@ -556,8 +630,12 @@ function createTodoTxt(options) {
|
|
|
556
630
|
});
|
|
557
631
|
}
|
|
558
632
|
});
|
|
633
|
+
const records = result.records;
|
|
559
634
|
log("debug", "Parsed todo file", { records: records.length });
|
|
560
|
-
if (currentGeneration === generation)
|
|
635
|
+
if (currentGeneration === generation) {
|
|
636
|
+
cache = records;
|
|
637
|
+
lastWarnings = result.warnings;
|
|
638
|
+
}
|
|
561
639
|
return records;
|
|
562
640
|
};
|
|
563
641
|
const refresh = () => {
|
|
@@ -574,12 +652,17 @@ function createTodoTxt(options) {
|
|
|
574
652
|
return refresh();
|
|
575
653
|
};
|
|
576
654
|
const all = async () => cloneRecords(await refresh());
|
|
655
|
+
const warnings = () => lastWarnings.map((warning) => ({
|
|
656
|
+
...warning,
|
|
657
|
+
meta: { ...warning.meta }
|
|
658
|
+
}));
|
|
577
659
|
const query = createTodoQuery(loadCached, {
|
|
578
660
|
filters: [],
|
|
579
661
|
caseSensitive: options.caseSensitive ?? true
|
|
580
662
|
});
|
|
581
663
|
return {
|
|
582
664
|
all,
|
|
665
|
+
warnings,
|
|
583
666
|
pending: query.pending,
|
|
584
667
|
completed: query.completed,
|
|
585
668
|
project: query.project,
|
|
@@ -604,6 +687,6 @@ function createTodoTxt(options) {
|
|
|
604
687
|
countsByContext: query.countsByContext
|
|
605
688
|
};
|
|
606
689
|
}
|
|
607
|
-
export { createTodoTxt, parseDocument, parseLine };
|
|
690
|
+
export { TodoReadError, createTodoTxt, parseDocument, parseDocumentResult, parseLine };
|
|
608
691
|
|
|
609
692
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n }),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecord, cloneRecords } from \"./clone.ts\";\nimport { isValidDate } from \"./date.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/** Fields that {@link TodoQuery.sortBy} can order results by. */\nexport type TodoSortField =\n | \"priority\"\n | \"createdAt\"\n | \"completedAt\"\n | \"description\"\n | \"due\";\n\n/** Sort direction for {@link TodoQuery.sortBy}. Default: `\"asc\"`. */\nexport type TodoSortDirection = \"asc\" | \"desc\";\n\n/**\n * Per-call matching options.\n *\n * `caseSensitive` overrides the client-level default for one call. The default\n * differs per method: project and context matching is exact and case-sensitive\n * unless the option says otherwise, while search is case-insensitive unless the\n * option says otherwise.\n */\nexport interface TodoMatchOptions {\n /** Compare case-sensitively (or, for search, insensitively) for this call. */\n caseSensitive?: boolean;\n}\n\n/** One ordering step appended by {@link TodoQuery.sortBy}. */\nexport interface TodoSortSpec {\n field: TodoSortField;\n direction: TodoSortDirection;\n}\n\n/**\n * Pending/completed/total counts for one bucket of records.\n *\n * `total` is always `pending + completed`.\n */\nexport interface TodoCount {\n /** Records that are not completed. */\n pending: number;\n /** Records marked completed. */\n completed: number;\n /** Every record in the bucket. */\n total: number;\n}\n\n/**\n * One named bucket with its counts, from the aggregate query methods.\n *\n * The name is the project or context exactly as parsed, without the `+` or\n * `@` prefix and with its original casing.\n */\nexport interface TodoNameCount {\n /** Project or context name from the matching records. */\n name: string;\n /** Counts over the matching records that carry the name. */\n counts: TodoCount;\n}\n\n/**\n * Result of {@link TodoQuery.summary}: totals for the matching records plus\n * per-name counts.\n *\n * Per-name totals count multi-tag records once per name, so they do not sum\n * to the top-level `total` when multi-tag records or untagged records\n * exist.\n */\nexport interface TodoSummary {\n /** Every record matching the query. */\n total: number;\n /** Matching records that are not completed. */\n pending: number;\n /** Matching records that are completed. */\n completed: number;\n /** Per-project counts over the matching records. */\n projects: TodoNameCount[];\n /** Per-context counts over the matching records. */\n contexts: TodoNameCount[];\n}\n\n/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and\n * {@link TodoQuery.countsByContext} are terminal aggregates; and\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /**\n * Aggregate counts for the records matching this query.\n *\n * `total`, `pending`, and `completed` count matching records, while\n * `projects` and `contexts` count each matching record once per distinct\n * name it carries, so a record tagged `+A +B` adds one to each name.\n * Per-name totals therefore do not sum to the top-level `total` when\n * multi-tag records or untagged records exist. Names are unique, keep\n * their original casing, and sort alphabetically like\n * {@link TodoQuery.projects}; completed-only records still contribute\n * their names. A `sortBy` step is ignored, and the summary loads through\n * the cache like every other query.\n */\n summary: () => Promise<TodoSummary>;\n /**\n * Unique project names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByProject: () => Promise<TodoNameCount[]>;\n /**\n * Unique context names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByContext: () => Promise<TodoNameCount[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\n/**\n * Count pending/completed/total per unique name over `records`.\n *\n * Each record contributes at most once per name, so a record tagged\n * `+A +A` counts `A` once. Names keep their original casing and sort\n * like the name plucks, so buckets line up with `projects()`/`contexts()`.\n */\nfunction countNames(\n records: TodoRecord[],\n pick: (todo: TodoRecord) => string[],\n): TodoNameCount[] {\n const buckets = new Map<string, TodoCount>();\n\n for (const record of records) {\n for (const name of new Set(pick(record))) {\n const bucket = buckets.get(name);\n\n if (bucket === undefined) {\n buckets.set(name, {\n pending: record.completed ? 0 : 1,\n completed: record.completed ? 1 : 0,\n total: 1,\n });\n } else if (record.completed) {\n bucket.completed += 1;\n bucket.total += 1;\n } else {\n bucket.pending += 1;\n bucket.total += 1;\n }\n }\n }\n\n return [...buckets]\n .map(([name, counts]) => ({ name, counts }))\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\n/**\n * Aggregate the current result into a summary.\n *\n * Sorting never applies to aggregates; they count records, not order them.\n */\nasync function resolveSummary(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoSummary> {\n const records = await resolveRaw(load, { ...state, sort: undefined });\n let pending = 0;\n let completed = 0;\n\n for (const record of records) {\n if (record.completed) {\n completed += 1;\n } else {\n pending += 1;\n }\n }\n\n return {\n total: records.length,\n pending,\n completed,\n projects: countNames(records, (todo) => todo.projects),\n contexts: countNames(records, (todo) => todo.contexts),\n };\n}\n\nfunction resolveCountsBy(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<TodoNameCount[]> {\n // Sorting never applies to aggregates; they count records, not order them.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n countNames(records, pick),\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n summary: () => resolveSummary(load, state),\n countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),\n countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoNameCount,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n TodoSummary,\n} from \"./query.ts\";\nimport type {\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */\n summary: () => Promise<TodoSummary>;\n /** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */\n countsByProject: () => Promise<TodoNameCount[]>;\n /** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */\n countsByContext: () => Promise<TodoNameCount[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. With `options.includeSource`, every record also carries the\n * 1-based `line` number and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names, and\n * aggregates such as {@link TodoQuery.summary} count pending and completed\n * records per name. Returned records are copies, so callers may mutate them\n * without affecting the cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await options.read();\n const records = parseDocument(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n summary: query.summary,\n countsByProject: query.countsByProject,\n countsByContext: query.countsByContext,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,OAAmB;EACvB,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,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EACd,OAAO,MAAM;EACb,OAAO,MAAM;EACb,UAAU,MAAM;EAChB,UAAU,MAAM;EAChB,SAAS,MAAM;EACf,iBAAiB,MAAM;EACvB,iBAAiB,MAAM;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/errors.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","/**\n * Thrown when a consumer-supplied read hook rejects with a value that is not\n * an `Error`.\n *\n * Rejections that are already `Error` instances — including filesystem errors\n * with a `code` such as `ENOENT` — propagate untouched, so existing\n * error-code checks keep working. Anything else, such as a thrown string or a\n * plain object, is wrapped; the original value is available on `cause`.\n */\nexport class TodoReadError extends Error {\n /** The value the read hook rejected with. */\n declare readonly cause: unknown;\n\n constructor(message: string, cause: unknown) {\n super(message, { cause });\n this.name = \"TodoReadError\";\n }\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseResult,\n ParseWarning,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Shared document parser behind {@link parseDocument} and\n * {@link parseDocumentResult}.\n *\n * Warnings are always collected, in document order and annotated with their\n * 1-based physical line number, and forwarded to the consumer's `onWarning`\n * when one is supplied. A single trailing newline ends the last line rather\n * than starting an empty one, so it adds neither a line nor a skipped line.\n */\nfunction parseDocumentCore(\n contents: string,\n options: ParseOptions,\n): ParseResult {\n const { includeSource, onWarning } = options;\n const segments = contents.split(/\\r?\\n/);\n const lines =\n contents === \"\"\n ? []\n : contents.endsWith(\"\\n\")\n ? segments.slice(0, -1)\n : segments;\n\n const records: TodoRecord[] = [];\n const warnings: ParseWarning[] = [];\n let skippedLines = 0;\n let lineNumber = 0;\n\n for (const line of lines) {\n lineNumber += 1;\n\n if (line.trim() === \"\") {\n skippedLines += 1;\n continue;\n }\n\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: (warning) => {\n const annotated = { ...warning, line: lineNumber };\n warnings.push(annotated);\n onWarning?.(annotated);\n },\n }),\n );\n }\n\n return { records, warnings, lineCount: lines.length, skippedLines };\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n return parseDocumentCore(\n contents,\n normalizeParseOptions(onWarningOrOptions),\n ).records;\n}\n\n/**\n * Parse the contents of a todo.txt file, returning records, warnings, and\n * line counts as data.\n *\n * The records are exactly what {@link parseDocument} returns. The\n * {@link ParseResult} additionally carries every warning in document order\n * (annotated with the 1-based physical line number), the number of physical\n * lines, and how many of them were blank or whitespace-only. A single\n * trailing newline ends the last line rather than starting an empty one, and\n * the empty input has no lines.\n *\n * Warnings are also forwarded to `options.onWarning` when supplied, so this\n * composes with existing warning handling.\n */\nexport function parseDocumentResult(\n contents: string,\n options?: ParseOptions,\n): ParseResult {\n return parseDocumentCore(contents, normalizeParseOptions(options));\n}\n","import { cloneRecord, cloneRecords } from \"./clone.ts\";\nimport { isValidDate } from \"./date.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/** Fields that {@link TodoQuery.sortBy} can order results by. */\nexport type TodoSortField =\n | \"priority\"\n | \"createdAt\"\n | \"completedAt\"\n | \"description\"\n | \"due\";\n\n/** Sort direction for {@link TodoQuery.sortBy}. Default: `\"asc\"`. */\nexport type TodoSortDirection = \"asc\" | \"desc\";\n\n/**\n * Per-call matching options.\n *\n * `caseSensitive` overrides the client-level default for one call. The default\n * differs per method: project and context matching is exact and case-sensitive\n * unless the option says otherwise, while search is case-insensitive unless the\n * option says otherwise.\n */\nexport interface TodoMatchOptions {\n /** Compare case-sensitively (or, for search, insensitively) for this call. */\n caseSensitive?: boolean;\n}\n\n/** One ordering step appended by {@link TodoQuery.sortBy}. */\nexport interface TodoSortSpec {\n field: TodoSortField;\n direction: TodoSortDirection;\n}\n\n/**\n * Pending/completed/total counts for one bucket of records.\n *\n * `total` is always `pending + completed`.\n */\nexport interface TodoCount {\n /** Records that are not completed. */\n pending: number;\n /** Records marked completed. */\n completed: number;\n /** Every record in the bucket. */\n total: number;\n}\n\n/**\n * One named bucket with its counts, from the aggregate query methods.\n *\n * The name is the project or context exactly as parsed, without the `+` or\n * `@` prefix and with its original casing.\n */\nexport interface TodoNameCount {\n /** Project or context name from the matching records. */\n name: string;\n /** Counts over the matching records that carry the name. */\n counts: TodoCount;\n}\n\n/**\n * Result of {@link TodoQuery.summary}: totals for the matching records plus\n * per-name counts.\n *\n * Per-name totals count multi-tag records once per name, so they do not sum\n * to the top-level `total` when multi-tag records or untagged records\n * exist.\n */\nexport interface TodoSummary {\n /** Every record matching the query. */\n total: number;\n /** Matching records that are not completed. */\n pending: number;\n /** Matching records that are completed. */\n completed: number;\n /** Per-project counts over the matching records. */\n projects: TodoNameCount[];\n /** Per-context counts over the matching records. */\n contexts: TodoNameCount[];\n}\n\n/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and\n * {@link TodoQuery.countsByContext} are terminal aggregates; and\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /**\n * Aggregate counts for the records matching this query.\n *\n * `total`, `pending`, and `completed` count matching records, while\n * `projects` and `contexts` count each matching record once per distinct\n * name it carries, so a record tagged `+A +B` adds one to each name.\n * Per-name totals therefore do not sum to the top-level `total` when\n * multi-tag records or untagged records exist. Names are unique, keep\n * their original casing, and sort alphabetically like\n * {@link TodoQuery.projects}; completed-only records still contribute\n * their names. A `sortBy` step is ignored, and the summary loads through\n * the cache like every other query.\n */\n summary: () => Promise<TodoSummary>;\n /**\n * Unique project names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByProject: () => Promise<TodoNameCount[]>;\n /**\n * Unique context names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByContext: () => Promise<TodoNameCount[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\n/**\n * Count pending/completed/total per unique name over `records`.\n *\n * Each record contributes at most once per name, so a record tagged\n * `+A +A` counts `A` once. Names keep their original casing and sort\n * like the name plucks, so buckets line up with `projects()`/`contexts()`.\n */\nfunction countNames(\n records: TodoRecord[],\n pick: (todo: TodoRecord) => string[],\n): TodoNameCount[] {\n const buckets = new Map<string, TodoCount>();\n\n for (const record of records) {\n for (const name of new Set(pick(record))) {\n const bucket = buckets.get(name);\n\n if (bucket === undefined) {\n buckets.set(name, {\n pending: record.completed ? 0 : 1,\n completed: record.completed ? 1 : 0,\n total: 1,\n });\n } else if (record.completed) {\n bucket.completed += 1;\n bucket.total += 1;\n } else {\n bucket.pending += 1;\n bucket.total += 1;\n }\n }\n }\n\n return [...buckets]\n .map(([name, counts]) => ({ name, counts }))\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\n/**\n * Aggregate the current result into a summary.\n *\n * Sorting never applies to aggregates; they count records, not order them.\n */\nasync function resolveSummary(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoSummary> {\n const records = await resolveRaw(load, { ...state, sort: undefined });\n let pending = 0;\n let completed = 0;\n\n for (const record of records) {\n if (record.completed) {\n completed += 1;\n } else {\n pending += 1;\n }\n }\n\n return {\n total: records.length,\n pending,\n completed,\n projects: countNames(records, (todo) => todo.projects),\n contexts: countNames(records, (todo) => todo.contexts),\n };\n}\n\nfunction resolveCountsBy(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<TodoNameCount[]> {\n // Sorting never applies to aggregates; they count records, not order them.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n countNames(records, pick),\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n summary: () => resolveSummary(load, state),\n countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),\n countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { TodoReadError } from \"./errors.ts\";\nimport { parseDocumentResult } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoNameCount,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n TodoSummary,\n} from \"./query.ts\";\nimport type {\n ParseWarning,\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /**\n * Warnings from the most recent successful read, in document order.\n *\n * Empty before the first read and after a read without warnings. A failed\n * read leaves the previous read's warnings in place. The returned array and\n * its warnings are copies, so callers may mutate them without affecting\n * later calls. A `logger`, when supplied, still receives warnings as they\n * are found; this is an additional access path, not a replacement.\n */\n warnings: () => ParseWarning[];\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */\n summary: () => Promise<TodoSummary>;\n /** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */\n countsByProject: () => Promise<TodoNameCount[]>;\n /** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */\n countsByContext: () => Promise<TodoNameCount[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. Warnings from the most recent read are also available as data\n * through {@link TodoTxtClient.warnings}. A `read` hook rejection propagates\n * untouched when the rejected value is an `Error`; any other value is wrapped\n * in a {@link TodoReadError} that carries the original on `cause`. With\n * `options.includeSource`, every record also carries the 1-based `line` number\n * and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names, and\n * aggregates such as {@link TodoQuery.summary} count pending and completed\n * records per name. Returned records are copies, so callers may mutate them\n * without affecting the cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let lastWarnings: ParseWarning[] = [];\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n\n let contents: string;\n try {\n contents = await options.read();\n } catch (cause) {\n // Real errors (including fs errors with a code such as ENOENT)\n // propagate untouched so existing error checks keep working; anything\n // else is wrapped so every read failure has a typed shape.\n if (cause instanceof Error) {\n throw cause;\n }\n\n throw new TodoReadError(\n \"The read hook rejected with a non-Error value.\",\n cause,\n );\n }\n\n const result = parseDocumentResult(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n const records = result.records;\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n lastWarnings = result.warnings;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const warnings = (): ParseWarning[] =>\n lastWarnings.map((warning) => ({\n ...warning,\n meta: { ...warning.meta },\n }));\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n warnings,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n summary: query.summary,\n countsByProject: query.countsByProject,\n countsByContext: query.countsByContext,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,OAAmB;EACvB,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,MAAM,EAAE,GAAG,KAAK,KAAK;CACvB;CAEA,IAAI,KAAK,SAAS,KAAA,GAChB,KAAK,OAAO,KAAK;CAGnB,IAAI,KAAK,QAAQ,KAAA,GACf,KAAK,MAAM,KAAK;CAGlB,OAAO;AACT;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;;;;;;;;;;;ACpBA,IAAa,gBAAb,cAAmC,MAAM;CAIvC,YAAY,SAAiB,OAAgB;EAC3C,MAAM,SAAS,EAAE,MAAM,CAAC;EACxB,KAAK,OAAO;CACd;AACF;;ACjBA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;CAAC;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;AAAE;AAErE,SAAS,WAAW,MAAuB;CACzC,OAAQ,OAAO,MAAM,KAAK,OAAO,QAAQ,KAAM,OAAO,QAAQ;AAChE;;;;;;;;AASA,SAAgB,YAAY,OAAwB;CAClD,MAAM,QAAQ,mBAAmB,KAAK,KAAK;CAC3C,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,OAAO,OAAO,MAAM,EAAE;CAC5B,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,MAAM,MAAM,OAAO,MAAM,EAAE;CAE3B,IAAI,QAAQ,KAAK,QAAQ,MAAM,MA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