@jibone/todotxt-core 0.3.0 → 0.5.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 +157 -13
- package/dist/index.d.ts +211 -23
- package/dist/index.js +273 -65
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,7 +55,8 @@ const todos = createTodoTxt({
|
|
|
55
55
|
|
|
56
56
|
`write` is optional until the write APIs are implemented, so read-only clients
|
|
57
57
|
can omit it. `logger` is optional too and silent when omitted; see
|
|
58
|
-
[Logging](#logging).
|
|
58
|
+
[Logging](#logging). `includeSource` is optional as well; see
|
|
59
|
+
[Source metadata](#source-metadata). The runnable Node version is
|
|
59
60
|
[`examples/node/todo-all.ts`](https://github.com/jibone/todotxt-core/blob/master/examples/node/todo-all.ts).
|
|
60
61
|
|
|
61
62
|
`all()` returns a `TodoRecord` for each non-empty line:
|
|
@@ -70,6 +71,8 @@ can omit it. `logger` is optional too and silent when omitted; see
|
|
|
70
71
|
| `projects` | Projects without the `+` prefix |
|
|
71
72
|
| `contexts` | Contexts without the `@` prefix |
|
|
72
73
|
| `data` | `key:value` metadata (`{ due: "2011-03-05" }`) |
|
|
74
|
+
| `line` | 1-based physical line number, when `includeSource` is on |
|
|
75
|
+
| `raw` | Exact original line, when `includeSource` is on |
|
|
73
76
|
|
|
74
77
|
If a `key:value` key appears more than once, the last value wins. With a
|
|
75
78
|
[logger](#logging) configured, the parser also emits a `warn` for each duplicate
|
|
@@ -79,18 +82,57 @@ See [How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/bl
|
|
|
79
82
|
for the complete rule-by-rule interpretation, including date validation and
|
|
80
83
|
deliberate leniencies.
|
|
81
84
|
|
|
85
|
+
### Source metadata
|
|
86
|
+
|
|
87
|
+
By default records stay JSON-lean and the original line is not retained. Pass
|
|
88
|
+
`includeSource` to opt into source metadata: every record then carries `line`,
|
|
89
|
+
the 1-based physical line number (blank lines count), and `raw`, the exact
|
|
90
|
+
original line without a trailing newline or `\r`.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const todos = createTodoTxt({
|
|
94
|
+
read: () => Bun.file("todo.txt").text(),
|
|
95
|
+
includeSource: true,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
for (const todo of await todos.pending()) {
|
|
99
|
+
console.log(todo.line, todo.raw);
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Source fields survive filters, plucks, and the cache-protecting copies that
|
|
104
|
+
queries return. The same option works for the standalone parser:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
parseDocument(contents, { includeSource: true });
|
|
108
|
+
parseLine("(A) Call Mom", { includeSource: true, line: 7 });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`parseLine` only attaches `line` when you supply it via `ParseOptions.line`;
|
|
112
|
+
`parseDocument` numbers lines itself.
|
|
113
|
+
|
|
82
114
|
## Querying
|
|
83
115
|
|
|
84
116
|
Queries are lazy: chaining filters does no IO. The first query on a client reads
|
|
85
117
|
and parses the file once, then later queries reuse that in-memory snapshot.
|
|
86
|
-
Every filter operates on the array of parsed JSON records.
|
|
118
|
+
Every filter operates on the array of parsed JSON records. Filters compose
|
|
119
|
+
with AND: each call narrows the result. Array arguments are OR within a single
|
|
120
|
+
call, so `project(["Garden", "Moving"])` matches either name while
|
|
121
|
+
`project("Garden").project("Moving")` requires both.
|
|
87
122
|
|
|
88
123
|
```ts
|
|
89
|
-
await todos.all();
|
|
90
|
-
await todos.pending();
|
|
91
|
-
await todos.completed();
|
|
92
|
-
await todos.project("TodoTxt");
|
|
93
|
-
await todos.context("phone");
|
|
124
|
+
await todos.all(); // TodoRecord[] (always reloads)
|
|
125
|
+
await todos.pending(); // TodoRecord[]
|
|
126
|
+
await todos.completed(); // TodoRecord[]
|
|
127
|
+
await todos.project("TodoTxt"); // TodoRecord[]
|
|
128
|
+
await todos.context("phone"); // TodoRecord[]
|
|
129
|
+
await todos.priority("A"); // TodoRecord[]
|
|
130
|
+
await todos.search("meatballs"); // TodoRecord[]
|
|
131
|
+
await todos.meta("due"); // TodoRecord[]
|
|
132
|
+
await todos.createdAfter("2024-01-01"); // TodoRecord[]
|
|
133
|
+
await todos.notProject("Garden"); // TodoRecord[]
|
|
134
|
+
await todos.count(); // number
|
|
135
|
+
await todos.first(); // TodoRecord | undefined
|
|
94
136
|
```
|
|
95
137
|
|
|
96
138
|
Filters compose, so they can be combined in any order:
|
|
@@ -99,6 +141,8 @@ Filters compose, so they can be combined in any order:
|
|
|
99
141
|
await todos.project("TodoTxt").pending();
|
|
100
142
|
await todos.project("TodoTxt").context("computer");
|
|
101
143
|
await todos.pending().project("OpenSource").context("github");
|
|
144
|
+
await todos.priority("A").search("mom");
|
|
145
|
+
await todos.project(["Garden", "Moving"]).sortBy("priority");
|
|
102
146
|
```
|
|
103
147
|
|
|
104
148
|
### Caching and refresh
|
|
@@ -161,8 +205,10 @@ await todos.context("home").pending().projects();
|
|
|
161
205
|
await todos.context("home").completed().projects();
|
|
162
206
|
```
|
|
163
207
|
|
|
164
|
-
Names are matched exactly and case-sensitively. An unknown project
|
|
165
|
-
resolves to an empty array.
|
|
208
|
+
Names are matched exactly and case-sensitively by default. An unknown project
|
|
209
|
+
or context resolves to an empty array. An empty array argument also matches
|
|
210
|
+
nothing; see [Case-insensitive matching](#case-insensitive-matching) for the
|
|
211
|
+
per-call and client-wide options.
|
|
166
212
|
|
|
167
213
|
### Status semantics
|
|
168
214
|
|
|
@@ -175,6 +221,98 @@ Filters are applied in sequence:
|
|
|
175
221
|
completed record. A project with both pending and completed items appears in
|
|
176
222
|
both `pending().projects()` and `completed().projects()`.
|
|
177
223
|
|
|
224
|
+
### Priority, search, and metadata
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
await todos.priority("A"); // exactly (A); "a" matches nothing
|
|
228
|
+
await todos.priority(["A", "B"]); // either letter
|
|
229
|
+
|
|
230
|
+
await todos.search("PR"); // substring of description,
|
|
231
|
+
// case-insensitive by default
|
|
232
|
+
await todos.search("pr", { caseSensitive: true }); // exact-case substring
|
|
233
|
+
|
|
234
|
+
await todos.meta("due"); // has due, whatever the value
|
|
235
|
+
await todos.meta("due", "2024-04-01"); // exact value
|
|
236
|
+
await todos.hasMeta("due"); // same as meta("due"), more readable
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`search` only looks at `description`. Projects, contexts, and `key:value` tags
|
|
240
|
+
have their own filters.
|
|
241
|
+
|
|
242
|
+
### Date filters
|
|
243
|
+
|
|
244
|
+
Date filters compare strictly against validated `YYYY-MM-DD` values, so plain
|
|
245
|
+
string comparison is safe. Records without the date never match. Invalid
|
|
246
|
+
arguments throw a `TypeError` when the query is built, before any read happens:
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
await todos.createdAfter("2024-01-01"); // createdAt strictly later
|
|
250
|
+
await todos.createdBefore("2024-01-01"); // createdAt strictly earlier
|
|
251
|
+
await todos.completedAfter("2024-01-01"); // completedAt strictly later
|
|
252
|
+
await todos.completedBefore("2024-01-01");// completedAt strictly earlier
|
|
253
|
+
|
|
254
|
+
todos.createdAfter("2024-02-30");
|
|
255
|
+
// TypeError: createdAfter() expected a real calendar date in YYYY-MM-DD form
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Negation
|
|
259
|
+
|
|
260
|
+
`notProject` and `notContext` keep the records without a name. An array
|
|
261
|
+
excludes every listed name; an empty array excludes nothing:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
await todos.notProject("Garden");
|
|
265
|
+
await todos.notContext(["phone", "computer"]);
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Sorting
|
|
269
|
+
|
|
270
|
+
`sortBy` appends an ordering step after filtering. The sort is stable, so
|
|
271
|
+
records with equal keys keep file order. Missing values — `null` priorities or
|
|
272
|
+
dates, and missing or invalid `due` values — sort last in both directions;
|
|
273
|
+
`"desc"` reverses only the value comparison. Calling `sortBy` twice keeps the
|
|
274
|
+
last call.
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
await todos.pending().sortBy("priority"); // A first, then B–Z, no priority last
|
|
278
|
+
await todos.sortBy("createdAt"); // earliest first, nulls last
|
|
279
|
+
await todos.sortBy("completedAt", "desc"); // latest first, nulls still last
|
|
280
|
+
await todos.sortBy("due"); // reads data.due; invalid or missing last
|
|
281
|
+
await todos.sortBy("description"); // localeCompare ordering
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### count() and first()
|
|
285
|
+
|
|
286
|
+
`count()` and `first()` resolve through the same loader and cache as every
|
|
287
|
+
other query. `first()` returns the first record of the filtered (and sorted)
|
|
288
|
+
result, or `undefined` when nothing matches, and it is a copy:
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
await todos.pending().count(); // 12
|
|
292
|
+
await todos.sortBy("priority").first(); // first (A) task
|
|
293
|
+
await todos.project("Missing").first(); // undefined
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
### Case-insensitive matching
|
|
297
|
+
|
|
298
|
+
Name matching is exact by default. Change the default for a whole client, or
|
|
299
|
+
for a single call:
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
const todos = createTodoTxt({
|
|
303
|
+
read: () => Bun.file("todo.txt").text(),
|
|
304
|
+
caseSensitive: false,
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
await todos.project("garden"); // matches +Garden
|
|
308
|
+
await todos.project("TodoTxt", { caseSensitive: true }); // back to exact
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Case-insensitive comparison uses `toLowerCase()`, which is deterministic across
|
|
312
|
+
machines and locales but is not full Unicode case folding. `projects()` and
|
|
313
|
+
`contexts()` always preserve original casing. `search` is independent of this
|
|
314
|
+
setting: it is case-insensitive by default whatever the client says.
|
|
315
|
+
|
|
178
316
|
## Logging
|
|
179
317
|
|
|
180
318
|
`createTodoTxt` is silent by default. Pass a `logger` to receive diagnostics.
|
|
@@ -224,10 +362,13 @@ const record = parseLine("(A) Call Mom +Family @phone due:2011-03-05");
|
|
|
224
362
|
const records = parseDocument(contents);
|
|
225
363
|
```
|
|
226
364
|
|
|
227
|
-
`parseLine` returns a `TodoRecord` directly.
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
`
|
|
365
|
+
`parseLine` returns a `TodoRecord` directly. Records keep no copy of the
|
|
366
|
+
original line unless [source metadata](#source-metadata) is enabled. Dates must
|
|
367
|
+
be real calendar dates in `YYYY-MM-DD` form; a shape-valid but nonexistent date
|
|
368
|
+
such as `2011-99-99` is treated as text and reported as an `invalid-date`
|
|
369
|
+
warning. Collect warnings by passing `onWarning` in a `ParseOptions` object;
|
|
370
|
+
passing the handler directly as the second argument is deprecated but still
|
|
371
|
+
supported. The full rule-by-rule interpretation is documented in
|
|
231
372
|
[How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md).
|
|
232
373
|
|
|
233
374
|
Writing is not implemented yet. The `write` hook is optional for now and will
|
|
@@ -242,6 +383,9 @@ bun examples/todo-context.ts
|
|
|
242
383
|
bun examples/todo-cross.ts
|
|
243
384
|
bun examples/todo-logger.ts
|
|
244
385
|
bun examples/todo-try.ts
|
|
386
|
+
bun examples/todo-source.ts
|
|
387
|
+
bun examples/todo-filters.ts
|
|
388
|
+
bun examples/todo-sort.ts
|
|
245
389
|
```
|
|
246
390
|
|
|
247
391
|
Each format rule also has a runnable example:
|
package/dist/index.d.ts
CHANGED
|
@@ -38,6 +38,20 @@ interface ParseWarning {
|
|
|
38
38
|
}
|
|
39
39
|
/** Receives parse warnings. */
|
|
40
40
|
type ParseWarningHandler = (warning: ParseWarning) => void;
|
|
41
|
+
/**
|
|
42
|
+
* Options for {@link parseLine} and {@link parseDocument}.
|
|
43
|
+
*/
|
|
44
|
+
interface ParseOptions {
|
|
45
|
+
/** Include `line` and `raw` on returned records. Default: `false`. */
|
|
46
|
+
includeSource?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* 1-based line number attached to the record when {@link includeSource} is
|
|
49
|
+
* on. Ignored by {@link parseDocument}, which numbers physical lines itself.
|
|
50
|
+
*/
|
|
51
|
+
line?: number;
|
|
52
|
+
/** Receives parse warnings. */
|
|
53
|
+
onWarning?: ParseWarningHandler;
|
|
54
|
+
}
|
|
41
55
|
/**
|
|
42
56
|
* Callbacks supplied by the consumer.
|
|
43
57
|
*
|
|
@@ -56,12 +70,32 @@ interface TodoHooks {
|
|
|
56
70
|
}
|
|
57
71
|
/** @deprecated Use {@link TodoHooks}. */
|
|
58
72
|
type TodoFileHooks = TodoHooks;
|
|
73
|
+
/**
|
|
74
|
+
* Options for creating a todo.txt client with {@link createTodoTxt}.
|
|
75
|
+
*
|
|
76
|
+
* Extends the file hooks with client behaviour switches.
|
|
77
|
+
*/
|
|
78
|
+
interface TodoClientOptions extends TodoHooks {
|
|
79
|
+
/** Include `line` and `raw` on every record. Default: `false`. */
|
|
80
|
+
includeSource?: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* Default matching behavior for project and context queries, including
|
|
83
|
+
* their negations. Default: `true` (exact, case-sensitive).
|
|
84
|
+
*
|
|
85
|
+
* When `false`, names are compared with `toLowerCase()`, which is
|
|
86
|
+
* deterministic across machines and locales but not full Unicode case
|
|
87
|
+
* folding. Search is unaffected: it is case-insensitive by default. Name
|
|
88
|
+
* plucks such as `projects()` always preserve original casing.
|
|
89
|
+
*/
|
|
90
|
+
caseSensitive?: boolean;
|
|
91
|
+
}
|
|
59
92
|
/**
|
|
60
93
|
* A single todo.txt line parsed into a JSON-friendly record.
|
|
61
94
|
*
|
|
62
95
|
* This is the only parsed representation. Inline metadata is separated out of
|
|
63
|
-
* {@link TodoRecord.description} into dedicated fields
|
|
64
|
-
*
|
|
96
|
+
* {@link TodoRecord.description} into dedicated fields. The original line is
|
|
97
|
+
* not retained unless the caller opts in with `includeSource`, which adds the
|
|
98
|
+
* {@link TodoRecord.line} and {@link TodoRecord.raw} source fields.
|
|
65
99
|
*/
|
|
66
100
|
interface TodoRecord {
|
|
67
101
|
/** True when the line starts with `x ` (lowercase and followed by a space). */
|
|
@@ -94,29 +128,137 @@ interface TodoRecord {
|
|
|
94
128
|
* If a key appears more than once, the last value wins.
|
|
95
129
|
*/
|
|
96
130
|
data: Record<string, string>;
|
|
131
|
+
/**
|
|
132
|
+
* 1-based physical line number in the source document.
|
|
133
|
+
*
|
|
134
|
+
* Present only when parsing with `includeSource`. For a whole document it
|
|
135
|
+
* counts every physical line, including blank ones. For a single line it is
|
|
136
|
+
* the number supplied via `ParseOptions.line`.
|
|
137
|
+
*/
|
|
138
|
+
line?: number;
|
|
139
|
+
/**
|
|
140
|
+
* Exact original line, without a trailing newline or a trailing `\r`.
|
|
141
|
+
*
|
|
142
|
+
* Present only when parsing with `includeSource`. Leading and trailing
|
|
143
|
+
* whitespace and tag order are preserved, unlike
|
|
144
|
+
* {@link TodoRecord.description}.
|
|
145
|
+
*/
|
|
146
|
+
raw?: string;
|
|
147
|
+
}
|
|
148
|
+
/** Fields that {@link TodoQuery.sortBy} can order results by. */
|
|
149
|
+
type TodoSortField = "priority" | "createdAt" | "completedAt" | "description" | "due";
|
|
150
|
+
/** Sort direction for {@link TodoQuery.sortBy}. Default: `"asc"`. */
|
|
151
|
+
type TodoSortDirection = "asc" | "desc";
|
|
152
|
+
/**
|
|
153
|
+
* Per-call matching options.
|
|
154
|
+
*
|
|
155
|
+
* `caseSensitive` overrides the client-level default for one call. The default
|
|
156
|
+
* differs per method: project and context matching is exact and case-sensitive
|
|
157
|
+
* unless the option says otherwise, while search is case-insensitive unless the
|
|
158
|
+
* option says otherwise.
|
|
159
|
+
*/
|
|
160
|
+
interface TodoMatchOptions {
|
|
161
|
+
/** Compare case-sensitively (or, for search, insensitively) for this call. */
|
|
162
|
+
caseSensitive?: boolean;
|
|
97
163
|
}
|
|
98
164
|
/**
|
|
99
165
|
* A lazy query over parsed todo records.
|
|
100
166
|
*
|
|
101
167
|
* Filters return a new query and perform no IO. Awaiting a query resolves
|
|
102
168
|
* through the supplied loader; the client caches parsed records, so only the
|
|
103
|
-
* first query reads the file.
|
|
104
|
-
*
|
|
105
|
-
*
|
|
169
|
+
* first query reads the file. Filters compose with AND: every predicate added
|
|
170
|
+
* to the chain must match. Array arguments are OR within a single call, so
|
|
171
|
+
* `project(["A", "B"])` matches either name while `project("A").project("B")`
|
|
172
|
+
* requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}
|
|
173
|
+
* are terminal plucks that resolve to unique, alphabetically sorted names;
|
|
174
|
+
* {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.
|
|
106
175
|
*/
|
|
107
176
|
interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
108
177
|
/** Only records that are not completed. */
|
|
109
178
|
pending: () => TodoQuery;
|
|
110
179
|
/** Only records that are completed. */
|
|
111
180
|
completed: () => TodoQuery;
|
|
112
|
-
/**
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
181
|
+
/**
|
|
182
|
+
* Only records tagged with the project `name`.
|
|
183
|
+
*
|
|
184
|
+
* An array matches any listed name (OR); repeated calls require every name
|
|
185
|
+
* (AND). An empty array matches nothing. Matching is exact and
|
|
186
|
+
* case-sensitive unless the client-level `caseSensitive` option or the
|
|
187
|
+
* per-call override says otherwise; case-insensitive comparison uses
|
|
188
|
+
* `toLowerCase()`, which is not full Unicode case folding.
|
|
189
|
+
*/
|
|
190
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
191
|
+
/** Only records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
192
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
193
|
+
/**
|
|
194
|
+
* Only records not tagged with the project `name`.
|
|
195
|
+
*
|
|
196
|
+
* An array excludes every listed name; an empty array excludes nothing.
|
|
197
|
+
* This is not a replacement for `pending()`/`completed()`.
|
|
198
|
+
*/
|
|
199
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
200
|
+
/** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
201
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
202
|
+
/**
|
|
203
|
+
* Only records with priority `letter`.
|
|
204
|
+
*
|
|
205
|
+
* Matching is exact against the uppercase letter the parser stores, so
|
|
206
|
+
* `priority("a")` matches nothing. An array matches any listed letter.
|
|
207
|
+
*/
|
|
208
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
209
|
+
/**
|
|
210
|
+
* Only records whose description contains `text` as a substring.
|
|
211
|
+
*
|
|
212
|
+
* Case-insensitive by default, independently of the client-level matching
|
|
213
|
+
* option. Only `description` is searched; projects, contexts, and metadata
|
|
214
|
+
* have their own filters.
|
|
215
|
+
*/
|
|
216
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
217
|
+
/**
|
|
218
|
+
* Only records with the metadata `key`.
|
|
219
|
+
*
|
|
220
|
+
* With a `value`, the record's value must match it exactly.
|
|
221
|
+
*/
|
|
222
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
223
|
+
/** Only records that have the metadata `key`, whatever its value. */
|
|
224
|
+
hasMeta: (key: string) => TodoQuery;
|
|
225
|
+
/**
|
|
226
|
+
* Only records created strictly after `date`.
|
|
227
|
+
*
|
|
228
|
+
* The argument must be a real calendar date in `YYYY-MM-DD` form; anything
|
|
229
|
+
* else throws a `TypeError` when the query is built, before any IO.
|
|
230
|
+
* Records without a creation date never match.
|
|
231
|
+
*/
|
|
232
|
+
createdAfter: (date: string) => TodoQuery;
|
|
233
|
+
/** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
234
|
+
createdBefore: (date: string) => TodoQuery;
|
|
235
|
+
/** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
236
|
+
completedAfter: (date: string) => TodoQuery;
|
|
237
|
+
/** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
238
|
+
completedBefore: (date: string) => TodoQuery;
|
|
239
|
+
/**
|
|
240
|
+
* Sort the filtered records by `field`; default direction is `"asc"`.
|
|
241
|
+
*
|
|
242
|
+
* The sort is stable: records with equal keys keep file order. Missing
|
|
243
|
+
* values (`null` priorities or dates, and missing or invalid `due` values)
|
|
244
|
+
* sort last in both directions; `"desc"` reverses only the value
|
|
245
|
+
* comparison, never the missing-value placement. Calling `sortBy` twice
|
|
246
|
+
* keeps only the last call. Description ordering uses `localeCompare`, so
|
|
247
|
+
* it follows the host locale for equal-ignoring-case ties.
|
|
248
|
+
*/
|
|
249
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
116
250
|
/** Unique project names in the current result, alphabetically sorted. */
|
|
117
251
|
projects: () => Promise<string[]>;
|
|
118
252
|
/** Unique context names in the current result, alphabetically sorted. */
|
|
119
253
|
contexts: () => Promise<string[]>;
|
|
254
|
+
/** Number of records in the current result; equal to `(await query).length`. */
|
|
255
|
+
count: () => Promise<number>;
|
|
256
|
+
/**
|
|
257
|
+
* The first record of the filtered (and sorted) result, or `undefined`
|
|
258
|
+
* when nothing matches. The record is a copy, so mutating it cannot affect
|
|
259
|
+
* the client's cache.
|
|
260
|
+
*/
|
|
261
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
120
262
|
}
|
|
121
263
|
/** The read interface returned by {@link createTodoTxt}. */
|
|
122
264
|
interface TodoTxtClient {
|
|
@@ -126,10 +268,40 @@ interface TodoTxtClient {
|
|
|
126
268
|
pending: () => TodoQuery;
|
|
127
269
|
/** Query only records that are completed, using the cached snapshot. */
|
|
128
270
|
completed: () => TodoQuery;
|
|
129
|
-
/**
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
271
|
+
/**
|
|
272
|
+
* Query records tagged with the project `name`, using the cache.
|
|
273
|
+
*
|
|
274
|
+
* An array matches any listed name; see {@link TodoQuery.project}.
|
|
275
|
+
*/
|
|
276
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
277
|
+
/** Query records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
278
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
279
|
+
/** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */
|
|
280
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
281
|
+
/** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
282
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
283
|
+
/** Query records with the priority `letter`; see {@link TodoQuery.priority}. */
|
|
284
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
285
|
+
/** Query records whose description contains `text`; see {@link TodoQuery.search}. */
|
|
286
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
287
|
+
/** Query records with the metadata `key`; see {@link TodoQuery.meta}. */
|
|
288
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
289
|
+
/** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */
|
|
290
|
+
hasMeta: (key: string) => TodoQuery;
|
|
291
|
+
/** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
292
|
+
createdAfter: (date: string) => TodoQuery;
|
|
293
|
+
/** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
294
|
+
createdBefore: (date: string) => TodoQuery;
|
|
295
|
+
/** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
296
|
+
completedAfter: (date: string) => TodoQuery;
|
|
297
|
+
/** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
298
|
+
completedBefore: (date: string) => TodoQuery;
|
|
299
|
+
/** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */
|
|
300
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
301
|
+
/** Count records in the cached snapshot; see {@link TodoQuery.count}. */
|
|
302
|
+
count: () => Promise<number>;
|
|
303
|
+
/** First record of the cached snapshot; see {@link TodoQuery.first}. */
|
|
304
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
133
305
|
/** List unique project names from the cached snapshot, alphabetically sorted. */
|
|
134
306
|
projects: () => Promise<string[]>;
|
|
135
307
|
/** List unique context names from the cached snapshot, alphabetically sorted. */
|
|
@@ -138,10 +310,14 @@ interface TodoTxtClient {
|
|
|
138
310
|
/**
|
|
139
311
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
140
312
|
*
|
|
141
|
-
* The library performs no IO of its own: `
|
|
142
|
-
* producing the file contents and `
|
|
143
|
-
* once they are implemented. `
|
|
144
|
-
* when supplied, it receives read lifecycle and parse warning
|
|
313
|
+
* The library performs no IO of its own: `options.read` is responsible for
|
|
314
|
+
* producing the file contents and `options.write` will be used by the write
|
|
315
|
+
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
316
|
+
* default; when supplied, it receives read lifecycle and parse warning
|
|
317
|
+
* diagnostics. With `options.includeSource`, every record also carries the
|
|
318
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
319
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
320
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
145
321
|
*
|
|
146
322
|
* Parsed records are cached in memory per client. The first query loads and
|
|
147
323
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -155,7 +331,7 @@ interface TodoTxtClient {
|
|
|
155
331
|
* Returned records are copies, so callers may mutate them without affecting the
|
|
156
332
|
* cache.
|
|
157
333
|
*/
|
|
158
|
-
export declare function createTodoTxt(
|
|
334
|
+
export declare function createTodoTxt(options: TodoClientOptions): TodoTxtClient;
|
|
159
335
|
/**
|
|
160
336
|
* Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
|
|
161
337
|
*
|
|
@@ -170,16 +346,28 @@ export declare function createTodoTxt(hooks: TodoHooks): TodoTxtClient;
|
|
|
170
346
|
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
171
347
|
* remaining text.
|
|
172
348
|
*
|
|
173
|
-
* Recoverable issues are reported to `onWarning` when supplied;
|
|
174
|
-
* produces a record.
|
|
349
|
+
* Recoverable issues are reported to `options.onWarning` when supplied;
|
|
350
|
+
* parsing still produces a record.
|
|
351
|
+
*
|
|
352
|
+
* With `options.includeSource`, the record carries `raw` (the exact input
|
|
353
|
+
* line, minus a trailing `\r`) and `line` (the number supplied via
|
|
354
|
+
* `options.line`, when given).
|
|
175
355
|
*/
|
|
176
|
-
export declare function parseLine(line: string,
|
|
356
|
+
export declare function parseLine(line: string, options?: ParseOptions): TodoRecord;
|
|
357
|
+
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
358
|
+
export declare function parseLine(line: string, onWarning: ParseWarningHandler): TodoRecord;
|
|
177
359
|
/**
|
|
178
360
|
* Parse the contents of a todo.txt file.
|
|
179
361
|
*
|
|
180
362
|
* Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
|
|
181
363
|
* skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
|
|
182
364
|
* annotated with the 1-based physical line number.
|
|
365
|
+
*
|
|
366
|
+
* With `options.includeSource`, every record carries `raw` (the exact line,
|
|
367
|
+
* minus a trailing `\r`) and `line` (the 1-based physical line number,
|
|
368
|
+
* counting blank lines).
|
|
183
369
|
*/
|
|
184
|
-
export declare function parseDocument(contents: string,
|
|
185
|
-
|
|
370
|
+
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
371
|
+
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
372
|
+
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
373
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/clone.ts
|
|
2
2
|
/** Copy a record so callers cannot mutate the client's cached snapshot. */
|
|
3
3
|
function cloneRecord(todo) {
|
|
4
|
-
|
|
4
|
+
const copy = {
|
|
5
5
|
completed: todo.completed,
|
|
6
6
|
priority: todo.priority,
|
|
7
7
|
completedAt: todo.completedAt,
|
|
@@ -11,6 +11,9 @@ function cloneRecord(todo) {
|
|
|
11
11
|
contexts: [...todo.contexts],
|
|
12
12
|
data: { ...todo.data }
|
|
13
13
|
};
|
|
14
|
+
if (todo.line !== void 0) copy.line = todo.line;
|
|
15
|
+
if (todo.raw !== void 0) copy.raw = todo.raw;
|
|
16
|
+
return copy;
|
|
14
17
|
}
|
|
15
18
|
/** Copy every record in `records`. */
|
|
16
19
|
function cloneRecords(records) {
|
|
@@ -149,23 +152,19 @@ function warnInvalidDate(value, field, onWarning) {
|
|
|
149
152
|
});
|
|
150
153
|
}
|
|
151
154
|
/**
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* The parser follows the todo.txt format rules:
|
|
155
|
-
*
|
|
156
|
-
* - Completed tasks start with `x `, optionally followed by a completion date
|
|
157
|
-
* and then a creation date.
|
|
158
|
-
* - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
|
|
159
|
-
* creation date.
|
|
160
|
-
* - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but
|
|
161
|
-
* nonexistent date is treated as text.
|
|
162
|
-
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
163
|
-
* remaining text.
|
|
164
|
-
*
|
|
165
|
-
* Recoverable issues are reported to `onWarning` when supplied; parsing still
|
|
166
|
-
* produces a record.
|
|
155
|
+
* Accept either a {@link ParseWarningHandler} (deprecated) or
|
|
156
|
+
* {@link ParseOptions} as the second argument.
|
|
167
157
|
*/
|
|
168
|
-
function
|
|
158
|
+
function normalizeParseOptions(onWarningOrOptions) {
|
|
159
|
+
if (typeof onWarningOrOptions === "function") return { onWarning: onWarningOrOptions };
|
|
160
|
+
return onWarningOrOptions ?? {};
|
|
161
|
+
}
|
|
162
|
+
/** Remove one trailing `\r`, so `raw` has no carriage return for CRLF input. */
|
|
163
|
+
function stripTrailingCarriageReturn(line) {
|
|
164
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
165
|
+
}
|
|
166
|
+
function parseLine(line, onWarningOrOptions) {
|
|
167
|
+
const options = normalizeParseOptions(onWarningOrOptions);
|
|
169
168
|
let rest = line;
|
|
170
169
|
let completed = false;
|
|
171
170
|
let priority = null;
|
|
@@ -182,8 +181,8 @@ function parseLine(line, onWarning) {
|
|
|
182
181
|
if (createdDate.kind === "valid") {
|
|
183
182
|
createdAt = createdDate.date;
|
|
184
183
|
rest = createdDate.rest;
|
|
185
|
-
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", onWarning);
|
|
186
|
-
} else if (completedDate.kind === "invalid") warnInvalidDate(completedDate.value, "completedAt", onWarning);
|
|
184
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", options.onWarning);
|
|
185
|
+
} else if (completedDate.kind === "invalid") warnInvalidDate(completedDate.value, "completedAt", options.onWarning);
|
|
187
186
|
} else {
|
|
188
187
|
const priorityMatch = PRIORITY_PATTERN.exec(rest);
|
|
189
188
|
if (priorityMatch) {
|
|
@@ -194,10 +193,10 @@ function parseLine(line, onWarning) {
|
|
|
194
193
|
if (createdDate.kind === "valid") {
|
|
195
194
|
createdAt = createdDate.date;
|
|
196
195
|
rest = createdDate.rest;
|
|
197
|
-
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", onWarning);
|
|
196
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", options.onWarning);
|
|
198
197
|
}
|
|
199
|
-
const { description, projects, contexts, data } = parseText(rest.trim(), onWarning);
|
|
200
|
-
|
|
198
|
+
const { description, projects, contexts, data } = parseText(rest.trim(), options.onWarning);
|
|
199
|
+
const record = {
|
|
201
200
|
completed,
|
|
202
201
|
priority,
|
|
203
202
|
completedAt,
|
|
@@ -207,23 +206,26 @@ function parseLine(line, onWarning) {
|
|
|
207
206
|
contexts,
|
|
208
207
|
data
|
|
209
208
|
};
|
|
209
|
+
if (options.includeSource) {
|
|
210
|
+
if (options.line !== void 0) record.line = options.line;
|
|
211
|
+
record.raw = stripTrailingCarriageReturn(line);
|
|
212
|
+
}
|
|
213
|
+
return record;
|
|
210
214
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
*
|
|
214
|
-
* Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
|
|
215
|
-
* skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
|
|
216
|
-
* annotated with the 1-based physical line number.
|
|
217
|
-
*/
|
|
218
|
-
function parseDocument(contents, onWarning) {
|
|
215
|
+
function parseDocument(contents, onWarningOrOptions) {
|
|
216
|
+
const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);
|
|
219
217
|
const records = [];
|
|
220
218
|
let lineNumber = 0;
|
|
221
219
|
for (const line of contents.split(/\r?\n/)) {
|
|
222
220
|
lineNumber += 1;
|
|
223
|
-
if (line.trim() !== "") records.push(parseLine(line,
|
|
224
|
-
|
|
225
|
-
line: lineNumber
|
|
226
|
-
|
|
221
|
+
if (line.trim() !== "") records.push(parseLine(line, {
|
|
222
|
+
includeSource,
|
|
223
|
+
line: lineNumber,
|
|
224
|
+
onWarning: onWarning ? (warning) => onWarning({
|
|
225
|
+
...warning,
|
|
226
|
+
line: lineNumber
|
|
227
|
+
}) : void 0
|
|
228
|
+
}));
|
|
227
229
|
}
|
|
228
230
|
return records;
|
|
229
231
|
}
|
|
@@ -231,43 +233,230 @@ function parseDocument(contents, onWarning) {
|
|
|
231
233
|
function uniqueSorted(values) {
|
|
232
234
|
return [...new Set(values)].sort();
|
|
233
235
|
}
|
|
234
|
-
|
|
236
|
+
function toArray(value) {
|
|
237
|
+
return Array.isArray(value) ? value : [value];
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Build a name-matching predicate for projects or contexts.
|
|
241
|
+
*
|
|
242
|
+
* Case-insensitive comparison normalizes both sides with `toLowerCase()`,
|
|
243
|
+
* which is deterministic across machines and locales but not full Unicode
|
|
244
|
+
* case folding. `invert` turns the predicate into a negation filter.
|
|
245
|
+
*/
|
|
246
|
+
function nameFilter(pick, names, caseSensitive, invert) {
|
|
247
|
+
const wanted = caseSensitive ? names : names.map((name) => name.toLowerCase());
|
|
248
|
+
const matches = (todo) => pick(todo).some((value) => wanted.includes(caseSensitive ? value : value.toLowerCase()));
|
|
249
|
+
return invert ? (todo) => !matches(todo) : matches;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Validate a date-filter argument at query-build time.
|
|
253
|
+
*
|
|
254
|
+
* Invalid arguments throw instead of silently matching nothing, so a typo in
|
|
255
|
+
* a bound cannot hide behind an empty result.
|
|
256
|
+
*/
|
|
257
|
+
function requireValidDate(date, method) {
|
|
258
|
+
if (!isValidDate(date)) throw new TypeError(`${method}() expected a real calendar date in YYYY-MM-DD form, got "${date}".`);
|
|
259
|
+
return date;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Build a date-comparison predicate on a record date field.
|
|
263
|
+
*
|
|
264
|
+
* Records with `null` dates never match; validated `YYYY-MM-DD` values
|
|
265
|
+
* compare correctly as plain strings.
|
|
266
|
+
*/
|
|
267
|
+
function dateFilter(field, date, method, keep) {
|
|
268
|
+
const bound = requireValidDate(date, method);
|
|
269
|
+
return (todo) => {
|
|
270
|
+
const recordDate = todo[field];
|
|
271
|
+
return recordDate !== null && keep(recordDate, bound);
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
/** Read `data.due` when it is a real calendar date; otherwise `null`. */
|
|
275
|
+
function dueDateOf(todo) {
|
|
276
|
+
const due = todo.data["due"];
|
|
277
|
+
return due !== void 0 && isValidDate(due) ? due : null;
|
|
278
|
+
}
|
|
279
|
+
/** Extract the nullable sort key for every field except `description`. */
|
|
280
|
+
function sortKey(todo, field) {
|
|
281
|
+
switch (field) {
|
|
282
|
+
case "priority": return todo.priority;
|
|
283
|
+
case "createdAt": return todo.createdAt;
|
|
284
|
+
case "completedAt": return todo.completedAt;
|
|
285
|
+
case "due": return dueDateOf(todo);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Compare nullable keys with missing values last in both directions.
|
|
290
|
+
*
|
|
291
|
+
* `desc` negates only the value comparison, never the missing-value
|
|
292
|
+
* placement; equal keys compare as `0` so the stable sort keeps file order.
|
|
293
|
+
*/
|
|
294
|
+
function compareNullableKeys(a, b, direction) {
|
|
295
|
+
if (a === null) return b === null ? 0 : 1;
|
|
296
|
+
if (b === null) return -1;
|
|
297
|
+
const result = a < b ? -1 : a > b ? 1 : 0;
|
|
298
|
+
return direction === "asc" ? result : -result;
|
|
299
|
+
}
|
|
300
|
+
/** Build the sort comparator for one ordering step. */
|
|
301
|
+
function makeComparator(spec) {
|
|
302
|
+
if (spec.field === "description") return (a, b) => {
|
|
303
|
+
const result = a.description.localeCompare(b.description);
|
|
304
|
+
return spec.direction === "asc" ? result : -result;
|
|
305
|
+
};
|
|
306
|
+
const field = spec.field;
|
|
307
|
+
return (a, b) => compareNullableKeys(sortKey(a, field), sortKey(b, field), spec.direction);
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Sort in place and return the same array.
|
|
311
|
+
*
|
|
312
|
+
* `Array#sort` is stable, so records with equal keys keep file order.
|
|
313
|
+
*/
|
|
314
|
+
function applySort(records, sort) {
|
|
315
|
+
return records.sort(makeComparator(sort));
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Load, filter, and sort records without cloning them.
|
|
319
|
+
*
|
|
320
|
+
* The returned array is safe to sort because it is always a fresh copy when
|
|
321
|
+
* a sort step exists; without one the loader's own array is returned as-is.
|
|
322
|
+
*/
|
|
323
|
+
async function resolveRaw(load, state) {
|
|
235
324
|
const records = await load();
|
|
236
|
-
if (
|
|
237
|
-
|
|
325
|
+
if (state.sort === void 0) {
|
|
326
|
+
if (state.filters.length === 0) return records;
|
|
327
|
+
return records.filter((record) => state.filters.every((filter) => filter(record)));
|
|
328
|
+
}
|
|
329
|
+
return applySort(state.filters.length === 0 ? records.slice() : records.filter((record) => state.filters.every((filter) => filter(record))), state.sort);
|
|
330
|
+
}
|
|
331
|
+
async function resolveRecords(load, state) {
|
|
332
|
+
return cloneRecords(await resolveRaw(load, state));
|
|
238
333
|
}
|
|
239
|
-
|
|
240
|
-
return
|
|
334
|
+
function pluckNames(load, state, pick) {
|
|
335
|
+
return resolveRaw(load, {
|
|
336
|
+
...state,
|
|
337
|
+
sort: void 0
|
|
338
|
+
}).then((records) => uniqueSorted(records.flatMap(pick)));
|
|
241
339
|
}
|
|
242
|
-
function
|
|
243
|
-
return resolveRaw(load,
|
|
340
|
+
function resolveCount(load, state) {
|
|
341
|
+
return resolveRaw(load, {
|
|
342
|
+
...state,
|
|
343
|
+
sort: void 0
|
|
344
|
+
}).then((records) => records.length);
|
|
345
|
+
}
|
|
346
|
+
async function resolveFirst(load, state) {
|
|
347
|
+
const first = (await resolveRaw(load, state))[0];
|
|
348
|
+
return first === void 0 ? void 0 : cloneRecord(first);
|
|
244
349
|
}
|
|
245
350
|
/**
|
|
246
351
|
* Create a lazy query over the records loaded by `load`.
|
|
247
352
|
*
|
|
248
|
-
* Each filter method appends a predicate, so chained calls compose
|
|
249
|
-
*
|
|
250
|
-
* `
|
|
353
|
+
* Each filter method appends a predicate, so chained calls compose with AND,
|
|
354
|
+
* while array arguments match any listed value. `sortBy` appends an ordering
|
|
355
|
+
* step instead of a predicate; the last `sortBy` call wins. For example,
|
|
356
|
+
* `pending().completed()` matches nothing, while
|
|
357
|
+
* `project("Work").pending()` matches pending records in `Work`, and
|
|
358
|
+
* `pending().sortBy("priority")` lists them A first.
|
|
251
359
|
*/
|
|
252
|
-
function createTodoQuery(load,
|
|
360
|
+
function createTodoQuery(load, state = {
|
|
361
|
+
filters: [],
|
|
362
|
+
caseSensitive: true
|
|
363
|
+
}) {
|
|
364
|
+
const nameOptions = (options) => options?.caseSensitive ?? state.caseSensitive;
|
|
253
365
|
return {
|
|
254
|
-
pending: () => createTodoQuery(load,
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
366
|
+
pending: () => createTodoQuery(load, {
|
|
367
|
+
...state,
|
|
368
|
+
filters: [...state.filters, (todo) => !todo.completed]
|
|
369
|
+
}),
|
|
370
|
+
completed: () => createTodoQuery(load, {
|
|
371
|
+
...state,
|
|
372
|
+
filters: [...state.filters, (todo) => todo.completed]
|
|
373
|
+
}),
|
|
374
|
+
project: (name, options) => createTodoQuery(load, {
|
|
375
|
+
...state,
|
|
376
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), false)]
|
|
377
|
+
}),
|
|
378
|
+
context: (name, options) => createTodoQuery(load, {
|
|
379
|
+
...state,
|
|
380
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), false)]
|
|
381
|
+
}),
|
|
382
|
+
notProject: (name, options) => createTodoQuery(load, {
|
|
383
|
+
...state,
|
|
384
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), true)]
|
|
385
|
+
}),
|
|
386
|
+
notContext: (name, options) => createTodoQuery(load, {
|
|
387
|
+
...state,
|
|
388
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), true)]
|
|
389
|
+
}),
|
|
390
|
+
priority: (letter) => {
|
|
391
|
+
const letters = toArray(letter);
|
|
392
|
+
return createTodoQuery(load, {
|
|
393
|
+
...state,
|
|
394
|
+
filters: [...state.filters, (todo) => todo.priority !== null && letters.includes(todo.priority)]
|
|
395
|
+
});
|
|
396
|
+
},
|
|
397
|
+
search: (text, options) => {
|
|
398
|
+
const caseSensitive = options?.caseSensitive ?? false;
|
|
399
|
+
const needle = caseSensitive ? text : text.toLowerCase();
|
|
400
|
+
return createTodoQuery(load, {
|
|
401
|
+
...state,
|
|
402
|
+
filters: [...state.filters, (todo) => {
|
|
403
|
+
return (caseSensitive ? todo.description : todo.description.toLowerCase()).includes(needle);
|
|
404
|
+
}]
|
|
405
|
+
});
|
|
406
|
+
},
|
|
407
|
+
meta: (key, value) => {
|
|
408
|
+
const filter = value === void 0 ? (todo) => Object.hasOwn(todo.data, key) : (todo) => todo.data[key] === value;
|
|
409
|
+
return createTodoQuery(load, {
|
|
410
|
+
...state,
|
|
411
|
+
filters: [...state.filters, filter]
|
|
412
|
+
});
|
|
413
|
+
},
|
|
414
|
+
hasMeta: (key) => createTodoQuery(load, {
|
|
415
|
+
...state,
|
|
416
|
+
filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)]
|
|
417
|
+
}),
|
|
418
|
+
createdAfter: (date) => createTodoQuery(load, {
|
|
419
|
+
...state,
|
|
420
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdAfter", (a, b) => a > b)]
|
|
421
|
+
}),
|
|
422
|
+
createdBefore: (date) => createTodoQuery(load, {
|
|
423
|
+
...state,
|
|
424
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdBefore", (a, b) => a < b)]
|
|
425
|
+
}),
|
|
426
|
+
completedAfter: (date) => createTodoQuery(load, {
|
|
427
|
+
...state,
|
|
428
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedAfter", (a, b) => a > b)]
|
|
429
|
+
}),
|
|
430
|
+
completedBefore: (date) => createTodoQuery(load, {
|
|
431
|
+
...state,
|
|
432
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedBefore", (a, b) => a < b)]
|
|
433
|
+
}),
|
|
434
|
+
sortBy: (field, direction = "asc") => createTodoQuery(load, {
|
|
435
|
+
...state,
|
|
436
|
+
sort: {
|
|
437
|
+
field,
|
|
438
|
+
direction
|
|
439
|
+
}
|
|
440
|
+
}),
|
|
441
|
+
projects: () => pluckNames(load, state, (todo) => todo.projects),
|
|
442
|
+
contexts: () => pluckNames(load, state, (todo) => todo.contexts),
|
|
443
|
+
count: () => resolveCount(load, state),
|
|
444
|
+
first: () => resolveFirst(load, state),
|
|
445
|
+
then: (onfulfilled, onrejected) => resolveRecords(load, state).then(onfulfilled, onrejected)
|
|
261
446
|
};
|
|
262
447
|
}
|
|
263
448
|
// src/client.ts
|
|
264
449
|
/**
|
|
265
450
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
266
451
|
*
|
|
267
|
-
* The library performs no IO of its own: `
|
|
268
|
-
* producing the file contents and `
|
|
269
|
-
* once they are implemented. `
|
|
270
|
-
* when supplied, it receives read lifecycle and parse warning
|
|
452
|
+
* The library performs no IO of its own: `options.read` is responsible for
|
|
453
|
+
* producing the file contents and `options.write` will be used by the write
|
|
454
|
+
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
455
|
+
* default; when supplied, it receives read lifecycle and parse warning
|
|
456
|
+
* diagnostics. With `options.includeSource`, every record also carries the
|
|
457
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
458
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
459
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
271
460
|
*
|
|
272
461
|
* Parsed records are cached in memory per client. The first query loads and
|
|
273
462
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -281,11 +470,11 @@ function createTodoQuery(load, filters = []) {
|
|
|
281
470
|
* Returned records are copies, so callers may mutate them without affecting the
|
|
282
471
|
* cache.
|
|
283
472
|
*/
|
|
284
|
-
function createTodoTxt(
|
|
473
|
+
function createTodoTxt(options) {
|
|
285
474
|
let cache;
|
|
286
475
|
let inFlight;
|
|
287
476
|
let generation = 0;
|
|
288
|
-
const logger =
|
|
477
|
+
const logger = options.logger;
|
|
289
478
|
const log = (level, message, meta) => {
|
|
290
479
|
if (!logger) return;
|
|
291
480
|
try {
|
|
@@ -296,12 +485,15 @@ function createTodoTxt(hooks) {
|
|
|
296
485
|
const readFresh = async () => {
|
|
297
486
|
const currentGeneration = ++generation;
|
|
298
487
|
log("debug", "Reading todo file");
|
|
299
|
-
const records = parseDocument(await
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
488
|
+
const records = parseDocument(await options.read(), {
|
|
489
|
+
includeSource: options.includeSource,
|
|
490
|
+
onWarning: (warning) => {
|
|
491
|
+
log("warn", warning.message, {
|
|
492
|
+
...warning.meta,
|
|
493
|
+
code: warning.code,
|
|
494
|
+
line: warning.line
|
|
495
|
+
});
|
|
496
|
+
}
|
|
305
497
|
});
|
|
306
498
|
log("debug", "Parsed todo file", { records: records.length });
|
|
307
499
|
if (currentGeneration === generation) cache = records;
|
|
@@ -321,13 +513,29 @@ function createTodoTxt(hooks) {
|
|
|
321
513
|
return refresh();
|
|
322
514
|
};
|
|
323
515
|
const all = async () => cloneRecords(await refresh());
|
|
324
|
-
const query = createTodoQuery(loadCached
|
|
516
|
+
const query = createTodoQuery(loadCached, {
|
|
517
|
+
filters: [],
|
|
518
|
+
caseSensitive: options.caseSensitive ?? true
|
|
519
|
+
});
|
|
325
520
|
return {
|
|
326
521
|
all,
|
|
327
522
|
pending: query.pending,
|
|
328
523
|
completed: query.completed,
|
|
329
524
|
project: query.project,
|
|
330
525
|
context: query.context,
|
|
526
|
+
notProject: query.notProject,
|
|
527
|
+
notContext: query.notContext,
|
|
528
|
+
priority: query.priority,
|
|
529
|
+
search: query.search,
|
|
530
|
+
meta: query.meta,
|
|
531
|
+
hasMeta: query.hasMeta,
|
|
532
|
+
createdAfter: query.createdAfter,
|
|
533
|
+
createdBefore: query.createdBefore,
|
|
534
|
+
completedAfter: query.completedAfter,
|
|
535
|
+
completedBefore: query.completedBefore,
|
|
536
|
+
sortBy: query.sortBy,
|
|
537
|
+
count: query.count,
|
|
538
|
+
first: query.first,
|
|
331
539
|
projects: query.projects,
|
|
332
540
|
contexts: query.contexts
|
|
333
541
|
};
|
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 return {\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\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 { ParseWarningHandler, TodoRecord } 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 * 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 `onWarning` when supplied; parsing still\n * produces a record.\n */\nexport function parseLine(\n line: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord {\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\", 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\", 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\", onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(text, onWarning);\n\n return {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\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 */\nexport function parseDocument(\n contents: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord[] {\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(\n line,\n onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n ),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecords } from \"./clone.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/**\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. {@link TodoQuery.projects} and\n * {@link TodoQuery.contexts} are terminal plucks that resolve to unique,\n * alphabetically sorted names.\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 /** Only records tagged with the project `name`. */\n project: (name: string) => TodoQuery;\n /** Only records tagged with the context `name`. */\n context: (name: string) => 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\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nasync function resolveRaw(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n filters.every((filter) => filter(record)),\n );\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, filters));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n filters: TodoFilter[],\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n return resolveRaw(load, filters).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\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. For\n * example, `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n filters: TodoFilter[] = [],\n): TodoQuery {\n return {\n pending: () =>\n createTodoQuery(load, [...filters, (todo) => !todo.completed]),\n completed: () =>\n createTodoQuery(load, [...filters, (todo) => todo.completed]),\n project: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.projects.includes(name),\n ]),\n context: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.contexts.includes(name),\n ]),\n projects: () => pluckNames(load, filters, (todo) => todo.projects),\n contexts: () => pluckNames(load, filters, (todo) => todo.contexts),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, filters).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type { TodoQuery } from \"./query.ts\";\nimport type { TodoHooks, TodoLogger, TodoRecord } 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 /** Query records tagged with a single project name, using the cache. */\n project: (name: string) => TodoQuery;\n /** Query records tagged with a single context name, using the cache. */\n context: (name: string) => TodoQuery;\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}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `hooks.read` is responsible for\n * producing the file contents and `hooks.write` will be used by the write APIs\n * once they are implemented. `hooks.logger` is optional and silent by default;\n * when supplied, it receives read lifecycle and parse warning diagnostics.\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, and plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names.\n * Returned records are copies, so callers may mutate them without affecting the\n * cache.\n */\nexport function createTodoTxt(hooks: TodoHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = hooks.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 hooks.read();\n const records = parseDocument(contents, (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\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\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: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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/** 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.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 /** 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\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\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 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 TodoQuery,\n TodoSortDirection,\n TodoSortField,\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}\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, and plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names.\n * Returned records are copies, so callers may mutate them without affecting the\n * 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 };\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;;AC7BA,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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