@jibone/todotxt-core 0.4.0 → 0.6.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 +168 -8
- package/dist/index.d.ts +229 -17
- package/dist/index.js +290 -25
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -115,14 +115,25 @@ parseLine("(A) Call Mom", { includeSource: true, line: 7 });
|
|
|
115
115
|
|
|
116
116
|
Queries are lazy: chaining filters does no IO. The first query on a client reads
|
|
117
117
|
and parses the file once, then later queries reuse that in-memory snapshot.
|
|
118
|
-
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.
|
|
119
122
|
|
|
120
123
|
```ts
|
|
121
|
-
await todos.all();
|
|
122
|
-
await todos.pending();
|
|
123
|
-
await todos.completed();
|
|
124
|
-
await todos.project("TodoTxt");
|
|
125
|
-
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
|
|
136
|
+
await todos.summary(); // TodoSummary
|
|
126
137
|
```
|
|
127
138
|
|
|
128
139
|
Filters compose, so they can be combined in any order:
|
|
@@ -131,6 +142,8 @@ Filters compose, so they can be combined in any order:
|
|
|
131
142
|
await todos.project("TodoTxt").pending();
|
|
132
143
|
await todos.project("TodoTxt").context("computer");
|
|
133
144
|
await todos.pending().project("OpenSource").context("github");
|
|
145
|
+
await todos.priority("A").search("mom");
|
|
146
|
+
await todos.project(["Garden", "Moving"]).sortBy("priority");
|
|
134
147
|
```
|
|
135
148
|
|
|
136
149
|
### Caching and refresh
|
|
@@ -193,8 +206,10 @@ await todos.context("home").pending().projects();
|
|
|
193
206
|
await todos.context("home").completed().projects();
|
|
194
207
|
```
|
|
195
208
|
|
|
196
|
-
Names are matched exactly and case-sensitively. An unknown project
|
|
197
|
-
resolves to an empty array.
|
|
209
|
+
Names are matched exactly and case-sensitively by default. An unknown project
|
|
210
|
+
or context resolves to an empty array. An empty array argument also matches
|
|
211
|
+
nothing; see [Case-insensitive matching](#case-insensitive-matching) for the
|
|
212
|
+
per-call and client-wide options.
|
|
198
213
|
|
|
199
214
|
### Status semantics
|
|
200
215
|
|
|
@@ -207,6 +222,149 @@ Filters are applied in sequence:
|
|
|
207
222
|
completed record. A project with both pending and completed items appears in
|
|
208
223
|
both `pending().projects()` and `completed().projects()`.
|
|
209
224
|
|
|
225
|
+
### Priority, search, and metadata
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
await todos.priority("A"); // exactly (A); "a" matches nothing
|
|
229
|
+
await todos.priority(["A", "B"]); // either letter
|
|
230
|
+
|
|
231
|
+
await todos.search("PR"); // substring of description,
|
|
232
|
+
// case-insensitive by default
|
|
233
|
+
await todos.search("pr", { caseSensitive: true }); // exact-case substring
|
|
234
|
+
|
|
235
|
+
await todos.meta("due"); // has due, whatever the value
|
|
236
|
+
await todos.meta("due", "2024-04-01"); // exact value
|
|
237
|
+
await todos.hasMeta("due"); // same as meta("due"), more readable
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
`search` only looks at `description`. Projects, contexts, and `key:value` tags
|
|
241
|
+
have their own filters.
|
|
242
|
+
|
|
243
|
+
### Date filters
|
|
244
|
+
|
|
245
|
+
Date filters compare strictly against validated `YYYY-MM-DD` values, so plain
|
|
246
|
+
string comparison is safe. Records without the date never match. Invalid
|
|
247
|
+
arguments throw a `TypeError` when the query is built, before any read happens:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
await todos.createdAfter("2024-01-01"); // createdAt strictly later
|
|
251
|
+
await todos.createdBefore("2024-01-01"); // createdAt strictly earlier
|
|
252
|
+
await todos.completedAfter("2024-01-01"); // completedAt strictly later
|
|
253
|
+
await todos.completedBefore("2024-01-01");// completedAt strictly earlier
|
|
254
|
+
|
|
255
|
+
todos.createdAfter("2024-02-30");
|
|
256
|
+
// TypeError: createdAfter() expected a real calendar date in YYYY-MM-DD form
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### Negation
|
|
260
|
+
|
|
261
|
+
`notProject` and `notContext` keep the records without a name. An array
|
|
262
|
+
excludes every listed name; an empty array excludes nothing:
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
await todos.notProject("Garden");
|
|
266
|
+
await todos.notContext(["phone", "computer"]);
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
### Sorting
|
|
270
|
+
|
|
271
|
+
`sortBy` appends an ordering step after filtering. The sort is stable, so
|
|
272
|
+
records with equal keys keep file order. Missing values — `null` priorities or
|
|
273
|
+
dates, and missing or invalid `due` values — sort last in both directions;
|
|
274
|
+
`"desc"` reverses only the value comparison. Calling `sortBy` twice keeps the
|
|
275
|
+
last call.
|
|
276
|
+
|
|
277
|
+
```ts
|
|
278
|
+
await todos.pending().sortBy("priority"); // A first, then B–Z, no priority last
|
|
279
|
+
await todos.sortBy("createdAt"); // earliest first, nulls last
|
|
280
|
+
await todos.sortBy("completedAt", "desc"); // latest first, nulls still last
|
|
281
|
+
await todos.sortBy("due"); // reads data.due; invalid or missing last
|
|
282
|
+
await todos.sortBy("description"); // localeCompare ordering
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### count() and first()
|
|
286
|
+
|
|
287
|
+
`count()` and `first()` resolve through the same loader and cache as every
|
|
288
|
+
other query. `first()` returns the first record of the filtered (and sorted)
|
|
289
|
+
result, or `undefined` when nothing matches, and it is a copy:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
await todos.pending().count(); // 12
|
|
293
|
+
await todos.sortBy("priority").first(); // first (A) task
|
|
294
|
+
await todos.project("Missing").first(); // undefined
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
### Aggregates and counts
|
|
298
|
+
|
|
299
|
+
`summary()` returns top-level totals plus per-name counts in one query, and
|
|
300
|
+
`countsByProject()` / `countsByContext()` return the per-name counts alone:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const summary = await todos.summary();
|
|
304
|
+
// {
|
|
305
|
+
// total: 19, pending: 12, completed: 7,
|
|
306
|
+
// projects: [
|
|
307
|
+
// { name: "GarageSale", counts: { pending: 3, completed: 1, total: 4 } },
|
|
308
|
+
// { name: "Garden", counts: { pending: 2, completed: 0, total: 2 } },
|
|
309
|
+
// { name: "Moving", counts: { pending: 1, completed: 1, total: 2 } },
|
|
310
|
+
// { name: "OpenSource", counts: { pending: 2, completed: 2, total: 4 } },
|
|
311
|
+
// { name: "TodoTxt", counts: { pending: 2, completed: 2, total: 4 } },
|
|
312
|
+
// { name: "TodoTxtTouch", counts: { pending: 0, completed: 1, total: 1 } },
|
|
313
|
+
// ],
|
|
314
|
+
// contexts: [
|
|
315
|
+
// { name: "archive", counts: { pending: 0, completed: 2, total: 2 } },
|
|
316
|
+
// { name: "computer", counts: { pending: 2, completed: 2, total: 4 } },
|
|
317
|
+
// { name: "errands", counts: { pending: 2, completed: 1, total: 3 } },
|
|
318
|
+
// { name: "github", counts: { pending: 1, completed: 2, total: 3 } },
|
|
319
|
+
// { name: "hardware", counts: { pending: 2, completed: 0, total: 2 } },
|
|
320
|
+
// { name: "home", counts: { pending: 3, completed: 1, total: 4 } },
|
|
321
|
+
// { name: "phone", counts: { pending: 2, completed: 1, total: 3 } },
|
|
322
|
+
// ],
|
|
323
|
+
// }
|
|
324
|
+
|
|
325
|
+
await todos.countsByProject(); // summary.projects on its own
|
|
326
|
+
await todos.countsByContext(); // summary.contexts on its own
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Aggregates respect filter chains, so they can be scoped like any other query:
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
await todos.pending().summary(); // pending records only
|
|
333
|
+
await todos.project("GarageSale").summary(); // one project's dashboard
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
The counting rules:
|
|
337
|
+
|
|
338
|
+
- A record tagged with several names counts once per name, so per-name
|
|
339
|
+
totals do **not** sum to the top-level `total`: multi-tag records make the
|
|
340
|
+
sum larger and untagged records make it smaller.
|
|
341
|
+
- Names are unique and alphabetically sorted, matching `projects()` and
|
|
342
|
+
`contexts()`. Completed-only records still contribute their names; use
|
|
343
|
+
`pending().summary()` (or `pending().countsByProject()`) to count pending
|
|
344
|
+
work only.
|
|
345
|
+
- `sortBy` steps are ignored, like the name plucks.
|
|
346
|
+
- Aggregates load through the cache like every other query.
|
|
347
|
+
|
|
348
|
+
### Case-insensitive matching
|
|
349
|
+
|
|
350
|
+
Name matching is exact by default. Change the default for a whole client, or
|
|
351
|
+
for a single call:
|
|
352
|
+
|
|
353
|
+
```ts
|
|
354
|
+
const todos = createTodoTxt({
|
|
355
|
+
read: () => Bun.file("todo.txt").text(),
|
|
356
|
+
caseSensitive: false,
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
await todos.project("garden"); // matches +Garden
|
|
360
|
+
await todos.project("TodoTxt", { caseSensitive: true }); // back to exact
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
Case-insensitive comparison uses `toLowerCase()`, which is deterministic across
|
|
364
|
+
machines and locales but is not full Unicode case folding. `projects()` and
|
|
365
|
+
`contexts()` always preserve original casing. `search` is independent of this
|
|
366
|
+
setting: it is case-insensitive by default whatever the client says.
|
|
367
|
+
|
|
210
368
|
## Logging
|
|
211
369
|
|
|
212
370
|
`createTodoTxt` is silent by default. Pass a `logger` to receive diagnostics.
|
|
@@ -278,6 +436,8 @@ bun examples/todo-cross.ts
|
|
|
278
436
|
bun examples/todo-logger.ts
|
|
279
437
|
bun examples/todo-try.ts
|
|
280
438
|
bun examples/todo-source.ts
|
|
439
|
+
bun examples/todo-filters.ts
|
|
440
|
+
bun examples/todo-sort.ts
|
|
281
441
|
```
|
|
282
442
|
|
|
283
443
|
Each format rule also has a runnable example:
|
package/dist/index.d.ts
CHANGED
|
@@ -78,6 +78,16 @@ type TodoFileHooks = TodoHooks;
|
|
|
78
78
|
interface TodoClientOptions extends TodoHooks {
|
|
79
79
|
/** Include `line` and `raw` on every record. Default: `false`. */
|
|
80
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;
|
|
81
91
|
}
|
|
82
92
|
/**
|
|
83
93
|
* A single todo.txt line parsed into a JSON-friendly record.
|
|
@@ -135,28 +145,191 @@ interface TodoRecord {
|
|
|
135
145
|
*/
|
|
136
146
|
raw?: string;
|
|
137
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;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Pending/completed/total counts for one bucket of records.
|
|
166
|
+
*
|
|
167
|
+
* `total` is always `pending + completed`.
|
|
168
|
+
*/
|
|
169
|
+
interface TodoCount {
|
|
170
|
+
/** Records that are not completed. */
|
|
171
|
+
pending: number;
|
|
172
|
+
/** Records marked completed. */
|
|
173
|
+
completed: number;
|
|
174
|
+
/** Every record in the bucket. */
|
|
175
|
+
total: number;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* One named bucket with its counts, from the aggregate query methods.
|
|
179
|
+
*
|
|
180
|
+
* The name is the project or context exactly as parsed, without the `+` or
|
|
181
|
+
* `@` prefix and with its original casing.
|
|
182
|
+
*/
|
|
183
|
+
interface TodoNameCount {
|
|
184
|
+
/** Project or context name from the matching records. */
|
|
185
|
+
name: string;
|
|
186
|
+
/** Counts over the matching records that carry the name. */
|
|
187
|
+
counts: TodoCount;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Result of {@link TodoQuery.summary}: totals for the matching records plus
|
|
191
|
+
* per-name counts.
|
|
192
|
+
*
|
|
193
|
+
* Per-name totals count multi-tag records once per name, so they do not sum
|
|
194
|
+
* to the top-level `total` when multi-tag records or untagged records
|
|
195
|
+
* exist.
|
|
196
|
+
*/
|
|
197
|
+
interface TodoSummary {
|
|
198
|
+
/** Every record matching the query. */
|
|
199
|
+
total: number;
|
|
200
|
+
/** Matching records that are not completed. */
|
|
201
|
+
pending: number;
|
|
202
|
+
/** Matching records that are completed. */
|
|
203
|
+
completed: number;
|
|
204
|
+
/** Per-project counts over the matching records. */
|
|
205
|
+
projects: TodoNameCount[];
|
|
206
|
+
/** Per-context counts over the matching records. */
|
|
207
|
+
contexts: TodoNameCount[];
|
|
208
|
+
}
|
|
138
209
|
/**
|
|
139
210
|
* A lazy query over parsed todo records.
|
|
140
211
|
*
|
|
141
212
|
* Filters return a new query and perform no IO. Awaiting a query resolves
|
|
142
213
|
* through the supplied loader; the client caches parsed records, so only the
|
|
143
|
-
* first query reads the file.
|
|
144
|
-
*
|
|
145
|
-
*
|
|
214
|
+
* first query reads the file. Filters compose with AND: every predicate added
|
|
215
|
+
* to the chain must match. Array arguments are OR within a single call, so
|
|
216
|
+
* `project(["A", "B"])` matches either name while `project("A").project("B")`
|
|
217
|
+
* requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}
|
|
218
|
+
* are terminal plucks that resolve to unique, alphabetically sorted names;
|
|
219
|
+
* {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and
|
|
220
|
+
* {@link TodoQuery.countsByContext} are terminal aggregates; and
|
|
221
|
+
* {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.
|
|
146
222
|
*/
|
|
147
223
|
interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
148
224
|
/** Only records that are not completed. */
|
|
149
225
|
pending: () => TodoQuery;
|
|
150
226
|
/** Only records that are completed. */
|
|
151
227
|
completed: () => TodoQuery;
|
|
152
|
-
/**
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Only records tagged with the project `name`.
|
|
230
|
+
*
|
|
231
|
+
* An array matches any listed name (OR); repeated calls require every name
|
|
232
|
+
* (AND). An empty array matches nothing. Matching is exact and
|
|
233
|
+
* case-sensitive unless the client-level `caseSensitive` option or the
|
|
234
|
+
* per-call override says otherwise; case-insensitive comparison uses
|
|
235
|
+
* `toLowerCase()`, which is not full Unicode case folding.
|
|
236
|
+
*/
|
|
237
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
238
|
+
/** Only records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
239
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
240
|
+
/**
|
|
241
|
+
* Only records not tagged with the project `name`.
|
|
242
|
+
*
|
|
243
|
+
* An array excludes every listed name; an empty array excludes nothing.
|
|
244
|
+
* This is not a replacement for `pending()`/`completed()`.
|
|
245
|
+
*/
|
|
246
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
247
|
+
/** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
248
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
249
|
+
/**
|
|
250
|
+
* Only records with priority `letter`.
|
|
251
|
+
*
|
|
252
|
+
* Matching is exact against the uppercase letter the parser stores, so
|
|
253
|
+
* `priority("a")` matches nothing. An array matches any listed letter.
|
|
254
|
+
*/
|
|
255
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
256
|
+
/**
|
|
257
|
+
* Only records whose description contains `text` as a substring.
|
|
258
|
+
*
|
|
259
|
+
* Case-insensitive by default, independently of the client-level matching
|
|
260
|
+
* option. Only `description` is searched; projects, contexts, and metadata
|
|
261
|
+
* have their own filters.
|
|
262
|
+
*/
|
|
263
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
264
|
+
/**
|
|
265
|
+
* Only records with the metadata `key`.
|
|
266
|
+
*
|
|
267
|
+
* With a `value`, the record's value must match it exactly.
|
|
268
|
+
*/
|
|
269
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
270
|
+
/** Only records that have the metadata `key`, whatever its value. */
|
|
271
|
+
hasMeta: (key: string) => TodoQuery;
|
|
272
|
+
/**
|
|
273
|
+
* Only records created strictly after `date`.
|
|
274
|
+
*
|
|
275
|
+
* The argument must be a real calendar date in `YYYY-MM-DD` form; anything
|
|
276
|
+
* else throws a `TypeError` when the query is built, before any IO.
|
|
277
|
+
* Records without a creation date never match.
|
|
278
|
+
*/
|
|
279
|
+
createdAfter: (date: string) => TodoQuery;
|
|
280
|
+
/** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
281
|
+
createdBefore: (date: string) => TodoQuery;
|
|
282
|
+
/** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
283
|
+
completedAfter: (date: string) => TodoQuery;
|
|
284
|
+
/** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
285
|
+
completedBefore: (date: string) => TodoQuery;
|
|
286
|
+
/**
|
|
287
|
+
* Sort the filtered records by `field`; default direction is `"asc"`.
|
|
288
|
+
*
|
|
289
|
+
* The sort is stable: records with equal keys keep file order. Missing
|
|
290
|
+
* values (`null` priorities or dates, and missing or invalid `due` values)
|
|
291
|
+
* sort last in both directions; `"desc"` reverses only the value
|
|
292
|
+
* comparison, never the missing-value placement. Calling `sortBy` twice
|
|
293
|
+
* keeps only the last call. Description ordering uses `localeCompare`, so
|
|
294
|
+
* it follows the host locale for equal-ignoring-case ties.
|
|
295
|
+
*/
|
|
296
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
156
297
|
/** Unique project names in the current result, alphabetically sorted. */
|
|
157
298
|
projects: () => Promise<string[]>;
|
|
158
299
|
/** Unique context names in the current result, alphabetically sorted. */
|
|
159
300
|
contexts: () => Promise<string[]>;
|
|
301
|
+
/**
|
|
302
|
+
* Aggregate counts for the records matching this query.
|
|
303
|
+
*
|
|
304
|
+
* `total`, `pending`, and `completed` count matching records, while
|
|
305
|
+
* `projects` and `contexts` count each matching record once per distinct
|
|
306
|
+
* name it carries, so a record tagged `+A +B` adds one to each name.
|
|
307
|
+
* Per-name totals therefore do not sum to the top-level `total` when
|
|
308
|
+
* multi-tag records or untagged records exist. Names are unique, keep
|
|
309
|
+
* their original casing, and sort alphabetically like
|
|
310
|
+
* {@link TodoQuery.projects}; completed-only records still contribute
|
|
311
|
+
* their names. A `sortBy` step is ignored, and the summary loads through
|
|
312
|
+
* the cache like every other query.
|
|
313
|
+
*/
|
|
314
|
+
summary: () => Promise<TodoSummary>;
|
|
315
|
+
/**
|
|
316
|
+
* Unique project names in the current result with their counts; see
|
|
317
|
+
* {@link TodoQuery.summary} for the counting rules.
|
|
318
|
+
*/
|
|
319
|
+
countsByProject: () => Promise<TodoNameCount[]>;
|
|
320
|
+
/**
|
|
321
|
+
* Unique context names in the current result with their counts; see
|
|
322
|
+
* {@link TodoQuery.summary} for the counting rules.
|
|
323
|
+
*/
|
|
324
|
+
countsByContext: () => Promise<TodoNameCount[]>;
|
|
325
|
+
/** Number of records in the current result; equal to `(await query).length`. */
|
|
326
|
+
count: () => Promise<number>;
|
|
327
|
+
/**
|
|
328
|
+
* The first record of the filtered (and sorted) result, or `undefined`
|
|
329
|
+
* when nothing matches. The record is a copy, so mutating it cannot affect
|
|
330
|
+
* the client's cache.
|
|
331
|
+
*/
|
|
332
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
160
333
|
}
|
|
161
334
|
/** The read interface returned by {@link createTodoTxt}. */
|
|
162
335
|
interface TodoTxtClient {
|
|
@@ -166,14 +339,50 @@ interface TodoTxtClient {
|
|
|
166
339
|
pending: () => TodoQuery;
|
|
167
340
|
/** Query only records that are completed, using the cached snapshot. */
|
|
168
341
|
completed: () => TodoQuery;
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
342
|
+
/**
|
|
343
|
+
* Query records tagged with the project `name`, using the cache.
|
|
344
|
+
*
|
|
345
|
+
* An array matches any listed name; see {@link TodoQuery.project}.
|
|
346
|
+
*/
|
|
347
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
348
|
+
/** Query records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
349
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
350
|
+
/** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */
|
|
351
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
352
|
+
/** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
353
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
354
|
+
/** Query records with the priority `letter`; see {@link TodoQuery.priority}. */
|
|
355
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
356
|
+
/** Query records whose description contains `text`; see {@link TodoQuery.search}. */
|
|
357
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
358
|
+
/** Query records with the metadata `key`; see {@link TodoQuery.meta}. */
|
|
359
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
360
|
+
/** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */
|
|
361
|
+
hasMeta: (key: string) => TodoQuery;
|
|
362
|
+
/** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
363
|
+
createdAfter: (date: string) => TodoQuery;
|
|
364
|
+
/** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
365
|
+
createdBefore: (date: string) => TodoQuery;
|
|
366
|
+
/** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
367
|
+
completedAfter: (date: string) => TodoQuery;
|
|
368
|
+
/** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
369
|
+
completedBefore: (date: string) => TodoQuery;
|
|
370
|
+
/** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */
|
|
371
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
372
|
+
/** Count records in the cached snapshot; see {@link TodoQuery.count}. */
|
|
373
|
+
count: () => Promise<number>;
|
|
374
|
+
/** First record of the cached snapshot; see {@link TodoQuery.first}. */
|
|
375
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
173
376
|
/** List unique project names from the cached snapshot, alphabetically sorted. */
|
|
174
377
|
projects: () => Promise<string[]>;
|
|
175
378
|
/** List unique context names from the cached snapshot, alphabetically sorted. */
|
|
176
379
|
contexts: () => Promise<string[]>;
|
|
380
|
+
/** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */
|
|
381
|
+
summary: () => Promise<TodoSummary>;
|
|
382
|
+
/** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */
|
|
383
|
+
countsByProject: () => Promise<TodoNameCount[]>;
|
|
384
|
+
/** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */
|
|
385
|
+
countsByContext: () => Promise<TodoNameCount[]>;
|
|
177
386
|
}
|
|
178
387
|
/**
|
|
179
388
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
@@ -183,7 +392,9 @@ interface TodoTxtClient {
|
|
|
183
392
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
184
393
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
185
394
|
* diagnostics. With `options.includeSource`, every record also carries the
|
|
186
|
-
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
395
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
396
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
397
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
187
398
|
*
|
|
188
399
|
* Parsed records are cached in memory per client. The first query loads and
|
|
189
400
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -192,10 +403,11 @@ interface TodoTxtClient {
|
|
|
192
403
|
*
|
|
193
404
|
* Every line is parsed into a {@link TodoRecord} when the cache is populated.
|
|
194
405
|
* Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
|
|
195
|
-
* operate on that array of JSON records,
|
|
196
|
-
* {@link TodoQuery.projects} return unique, alphabetically sorted names
|
|
197
|
-
*
|
|
198
|
-
*
|
|
406
|
+
* operate on that array of JSON records, plucks such as
|
|
407
|
+
* {@link TodoQuery.projects} return unique, alphabetically sorted names, and
|
|
408
|
+
* aggregates such as {@link TodoQuery.summary} count pending and completed
|
|
409
|
+
* records per name. Returned records are copies, so callers may mutate them
|
|
410
|
+
* without affecting the cache.
|
|
199
411
|
*/
|
|
200
412
|
export declare function createTodoTxt(options: TodoClientOptions): TodoTxtClient;
|
|
201
413
|
/**
|
|
@@ -236,4 +448,4 @@ export declare function parseLine(line: string, onWarning: ParseWarningHandler):
|
|
|
236
448
|
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
237
449
|
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
238
450
|
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
239
|
-
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoQuery, TodoRecord, TodoTxtClient };
|
|
451
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoCount, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoNameCount, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoSummary, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -233,33 +233,276 @@ function parseDocument(contents, onWarningOrOptions) {
|
|
|
233
233
|
function uniqueSorted(values) {
|
|
234
234
|
return [...new Set(values)].sort();
|
|
235
235
|
}
|
|
236
|
-
|
|
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) {
|
|
237
324
|
const records = await load();
|
|
238
|
-
if (
|
|
239
|
-
|
|
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);
|
|
240
330
|
}
|
|
241
|
-
async function resolveRecords(load,
|
|
242
|
-
return cloneRecords(await resolveRaw(load,
|
|
331
|
+
async function resolveRecords(load, state) {
|
|
332
|
+
return cloneRecords(await resolveRaw(load, state));
|
|
333
|
+
}
|
|
334
|
+
function pluckNames(load, state, pick) {
|
|
335
|
+
return resolveRaw(load, {
|
|
336
|
+
...state,
|
|
337
|
+
sort: void 0
|
|
338
|
+
}).then((records) => uniqueSorted(records.flatMap(pick)));
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Count pending/completed/total per unique name over `records`.
|
|
342
|
+
*
|
|
343
|
+
* Each record contributes at most once per name, so a record tagged
|
|
344
|
+
* `+A +A` counts `A` once. Names keep their original casing and sort
|
|
345
|
+
* like the name plucks, so buckets line up with `projects()`/`contexts()`.
|
|
346
|
+
*/
|
|
347
|
+
function countNames(records, pick) {
|
|
348
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
349
|
+
for (const record of records) for (const name of new Set(pick(record))) {
|
|
350
|
+
const bucket = buckets.get(name);
|
|
351
|
+
if (bucket === void 0) buckets.set(name, {
|
|
352
|
+
pending: record.completed ? 0 : 1,
|
|
353
|
+
completed: record.completed ? 1 : 0,
|
|
354
|
+
total: 1
|
|
355
|
+
});
|
|
356
|
+
else if (record.completed) {
|
|
357
|
+
bucket.completed += 1;
|
|
358
|
+
bucket.total += 1;
|
|
359
|
+
} else {
|
|
360
|
+
bucket.pending += 1;
|
|
361
|
+
bucket.total += 1;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return [...buckets].map(([name, counts]) => ({
|
|
365
|
+
name,
|
|
366
|
+
counts
|
|
367
|
+
})).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
243
368
|
}
|
|
244
|
-
function
|
|
245
|
-
return resolveRaw(load,
|
|
369
|
+
function resolveCount(load, state) {
|
|
370
|
+
return resolveRaw(load, {
|
|
371
|
+
...state,
|
|
372
|
+
sort: void 0
|
|
373
|
+
}).then((records) => records.length);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* Aggregate the current result into a summary.
|
|
377
|
+
*
|
|
378
|
+
* Sorting never applies to aggregates; they count records, not order them.
|
|
379
|
+
*/
|
|
380
|
+
async function resolveSummary(load, state) {
|
|
381
|
+
const records = await resolveRaw(load, {
|
|
382
|
+
...state,
|
|
383
|
+
sort: void 0
|
|
384
|
+
});
|
|
385
|
+
let pending = 0;
|
|
386
|
+
let completed = 0;
|
|
387
|
+
for (const record of records) if (record.completed) completed += 1;
|
|
388
|
+
else pending += 1;
|
|
389
|
+
return {
|
|
390
|
+
total: records.length,
|
|
391
|
+
pending,
|
|
392
|
+
completed,
|
|
393
|
+
projects: countNames(records, (todo) => todo.projects),
|
|
394
|
+
contexts: countNames(records, (todo) => todo.contexts)
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function resolveCountsBy(load, state, pick) {
|
|
398
|
+
return resolveRaw(load, {
|
|
399
|
+
...state,
|
|
400
|
+
sort: void 0
|
|
401
|
+
}).then((records) => countNames(records, pick));
|
|
402
|
+
}
|
|
403
|
+
async function resolveFirst(load, state) {
|
|
404
|
+
const first = (await resolveRaw(load, state))[0];
|
|
405
|
+
return first === void 0 ? void 0 : cloneRecord(first);
|
|
246
406
|
}
|
|
247
407
|
/**
|
|
248
408
|
* Create a lazy query over the records loaded by `load`.
|
|
249
409
|
*
|
|
250
|
-
* Each filter method appends a predicate, so chained calls compose
|
|
251
|
-
*
|
|
252
|
-
* `
|
|
410
|
+
* Each filter method appends a predicate, so chained calls compose with AND,
|
|
411
|
+
* while array arguments match any listed value. `sortBy` appends an ordering
|
|
412
|
+
* step instead of a predicate; the last `sortBy` call wins. For example,
|
|
413
|
+
* `pending().completed()` matches nothing, while
|
|
414
|
+
* `project("Work").pending()` matches pending records in `Work`, and
|
|
415
|
+
* `pending().sortBy("priority")` lists them A first.
|
|
253
416
|
*/
|
|
254
|
-
function createTodoQuery(load,
|
|
417
|
+
function createTodoQuery(load, state = {
|
|
418
|
+
filters: [],
|
|
419
|
+
caseSensitive: true
|
|
420
|
+
}) {
|
|
421
|
+
const nameOptions = (options) => options?.caseSensitive ?? state.caseSensitive;
|
|
255
422
|
return {
|
|
256
|
-
pending: () => createTodoQuery(load,
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
423
|
+
pending: () => createTodoQuery(load, {
|
|
424
|
+
...state,
|
|
425
|
+
filters: [...state.filters, (todo) => !todo.completed]
|
|
426
|
+
}),
|
|
427
|
+
completed: () => createTodoQuery(load, {
|
|
428
|
+
...state,
|
|
429
|
+
filters: [...state.filters, (todo) => todo.completed]
|
|
430
|
+
}),
|
|
431
|
+
project: (name, options) => createTodoQuery(load, {
|
|
432
|
+
...state,
|
|
433
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), false)]
|
|
434
|
+
}),
|
|
435
|
+
context: (name, options) => createTodoQuery(load, {
|
|
436
|
+
...state,
|
|
437
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), false)]
|
|
438
|
+
}),
|
|
439
|
+
notProject: (name, options) => createTodoQuery(load, {
|
|
440
|
+
...state,
|
|
441
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), true)]
|
|
442
|
+
}),
|
|
443
|
+
notContext: (name, options) => createTodoQuery(load, {
|
|
444
|
+
...state,
|
|
445
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), true)]
|
|
446
|
+
}),
|
|
447
|
+
priority: (letter) => {
|
|
448
|
+
const letters = toArray(letter);
|
|
449
|
+
return createTodoQuery(load, {
|
|
450
|
+
...state,
|
|
451
|
+
filters: [...state.filters, (todo) => todo.priority !== null && letters.includes(todo.priority)]
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
search: (text, options) => {
|
|
455
|
+
const caseSensitive = options?.caseSensitive ?? false;
|
|
456
|
+
const needle = caseSensitive ? text : text.toLowerCase();
|
|
457
|
+
return createTodoQuery(load, {
|
|
458
|
+
...state,
|
|
459
|
+
filters: [...state.filters, (todo) => {
|
|
460
|
+
return (caseSensitive ? todo.description : todo.description.toLowerCase()).includes(needle);
|
|
461
|
+
}]
|
|
462
|
+
});
|
|
463
|
+
},
|
|
464
|
+
meta: (key, value) => {
|
|
465
|
+
const filter = value === void 0 ? (todo) => Object.hasOwn(todo.data, key) : (todo) => todo.data[key] === value;
|
|
466
|
+
return createTodoQuery(load, {
|
|
467
|
+
...state,
|
|
468
|
+
filters: [...state.filters, filter]
|
|
469
|
+
});
|
|
470
|
+
},
|
|
471
|
+
hasMeta: (key) => createTodoQuery(load, {
|
|
472
|
+
...state,
|
|
473
|
+
filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)]
|
|
474
|
+
}),
|
|
475
|
+
createdAfter: (date) => createTodoQuery(load, {
|
|
476
|
+
...state,
|
|
477
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdAfter", (a, b) => a > b)]
|
|
478
|
+
}),
|
|
479
|
+
createdBefore: (date) => createTodoQuery(load, {
|
|
480
|
+
...state,
|
|
481
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdBefore", (a, b) => a < b)]
|
|
482
|
+
}),
|
|
483
|
+
completedAfter: (date) => createTodoQuery(load, {
|
|
484
|
+
...state,
|
|
485
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedAfter", (a, b) => a > b)]
|
|
486
|
+
}),
|
|
487
|
+
completedBefore: (date) => createTodoQuery(load, {
|
|
488
|
+
...state,
|
|
489
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedBefore", (a, b) => a < b)]
|
|
490
|
+
}),
|
|
491
|
+
sortBy: (field, direction = "asc") => createTodoQuery(load, {
|
|
492
|
+
...state,
|
|
493
|
+
sort: {
|
|
494
|
+
field,
|
|
495
|
+
direction
|
|
496
|
+
}
|
|
497
|
+
}),
|
|
498
|
+
projects: () => pluckNames(load, state, (todo) => todo.projects),
|
|
499
|
+
contexts: () => pluckNames(load, state, (todo) => todo.contexts),
|
|
500
|
+
summary: () => resolveSummary(load, state),
|
|
501
|
+
countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),
|
|
502
|
+
countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),
|
|
503
|
+
count: () => resolveCount(load, state),
|
|
504
|
+
first: () => resolveFirst(load, state),
|
|
505
|
+
then: (onfulfilled, onrejected) => resolveRecords(load, state).then(onfulfilled, onrejected)
|
|
263
506
|
};
|
|
264
507
|
}
|
|
265
508
|
// src/client.ts
|
|
@@ -271,7 +514,9 @@ function createTodoQuery(load, filters = []) {
|
|
|
271
514
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
272
515
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
273
516
|
* diagnostics. With `options.includeSource`, every record also carries the
|
|
274
|
-
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
517
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
518
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
519
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
275
520
|
*
|
|
276
521
|
* Parsed records are cached in memory per client. The first query loads and
|
|
277
522
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -280,10 +525,11 @@ function createTodoQuery(load, filters = []) {
|
|
|
280
525
|
*
|
|
281
526
|
* Every line is parsed into a {@link TodoRecord} when the cache is populated.
|
|
282
527
|
* Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
|
|
283
|
-
* operate on that array of JSON records,
|
|
284
|
-
* {@link TodoQuery.projects} return unique, alphabetically sorted names
|
|
285
|
-
*
|
|
286
|
-
*
|
|
528
|
+
* operate on that array of JSON records, plucks such as
|
|
529
|
+
* {@link TodoQuery.projects} return unique, alphabetically sorted names, and
|
|
530
|
+
* aggregates such as {@link TodoQuery.summary} count pending and completed
|
|
531
|
+
* records per name. Returned records are copies, so callers may mutate them
|
|
532
|
+
* without affecting the cache.
|
|
287
533
|
*/
|
|
288
534
|
function createTodoTxt(options) {
|
|
289
535
|
let cache;
|
|
@@ -328,15 +574,34 @@ function createTodoTxt(options) {
|
|
|
328
574
|
return refresh();
|
|
329
575
|
};
|
|
330
576
|
const all = async () => cloneRecords(await refresh());
|
|
331
|
-
const query = createTodoQuery(loadCached
|
|
577
|
+
const query = createTodoQuery(loadCached, {
|
|
578
|
+
filters: [],
|
|
579
|
+
caseSensitive: options.caseSensitive ?? true
|
|
580
|
+
});
|
|
332
581
|
return {
|
|
333
582
|
all,
|
|
334
583
|
pending: query.pending,
|
|
335
584
|
completed: query.completed,
|
|
336
585
|
project: query.project,
|
|
337
586
|
context: query.context,
|
|
587
|
+
notProject: query.notProject,
|
|
588
|
+
notContext: query.notContext,
|
|
589
|
+
priority: query.priority,
|
|
590
|
+
search: query.search,
|
|
591
|
+
meta: query.meta,
|
|
592
|
+
hasMeta: query.hasMeta,
|
|
593
|
+
createdAfter: query.createdAfter,
|
|
594
|
+
createdBefore: query.createdBefore,
|
|
595
|
+
completedAfter: query.completedAfter,
|
|
596
|
+
completedBefore: query.completedBefore,
|
|
597
|
+
sortBy: query.sortBy,
|
|
598
|
+
count: query.count,
|
|
599
|
+
first: query.first,
|
|
338
600
|
projects: query.projects,
|
|
339
|
-
contexts: query.contexts
|
|
601
|
+
contexts: query.contexts,
|
|
602
|
+
summary: query.summary,
|
|
603
|
+
countsByProject: query.countsByProject,
|
|
604
|
+
countsByContext: query.countsByContext
|
|
340
605
|
};
|
|
341
606
|
}
|
|
342
607
|
export { createTodoTxt, parseDocument, parseLine };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n }),\n );\n }\n }\n\n return records;\n}\n","import { 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 {\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 /** 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: `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.\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\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\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;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ACF,OAAO;EAGT,IAAI,OACF,OAAO,QAAQ,QAAQ,KAAK;EAG9B,OAAO,QAAQ;CACjB;CAEA,MAAM,MAAM,YACV,aAAa,MAAM,QAAQ,CAAC;CAE9B,MAAM,QAAQ,gBAAgB,UAAU;CAExC,OAAO;EACL;EACA,SAAS,MAAM;EACf,WAAW,MAAM;EACjB,SAAS,MAAM;EACf,SAAS,MAAM;EACf,UAAU,MAAM;EAChB,UAAU,MAAM;CAClB;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n const copy: TodoRecord = {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n\n if (todo.line !== undefined) {\n copy.line = todo.line;\n }\n\n if (todo.raw !== undefined) {\n copy.raw = todo.raw;\n }\n\n return copy;\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","const DATE_SHAPE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\nfunction isLeapYear(year: number): boolean {\n return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n}\n\n/**\n * True when `value` is a real calendar date in `YYYY-MM-DD` form.\n *\n * The check is purely arithmetic so it does not depend on the host timezone and\n * does not let JavaScript's `Date` roll invalid values over (for example,\n * `2011-02-30` must not become March 2).\n */\nexport function isValidDate(value: string): boolean {\n const match = DATE_SHAPE_PATTERN.exec(value);\n if (!match) {\n return false;\n }\n\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n\n if (month < 1 || month > 12 || day < 1) {\n return false;\n }\n\n const maxDay =\n month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month - 1] ?? 0);\n\n return day <= maxDay;\n}\n","import type { ParseWarningHandler } from \"./types.ts\";\n\nconst EXTENSION_PATTERN = /^([^:\\s]+):([^:\\s]+)$/;\n\n/** Metadata collected from a task's text. */\nexport interface TodoMetadata {\n projects: string[];\n contexts: string[];\n data: Record<string, string>;\n}\n\n/** Everything derived from a task's text in one token pass. */\nexport interface TodoText extends TodoMetadata {\n description: string;\n}\n\nfunction tokenize(text: string): string[] {\n const trimmed = text.trim();\n if (trimmed === \"\") {\n return [];\n }\n\n return trimmed.split(/\\s+/);\n}\n\n/**\n * True when a whitespace-delimited token is inline metadata.\n *\n * Inline metadata is a project (`+name`), a context (`@name`), or a\n * `key:value` extension. Bare `+`/`@` tokens and values containing another\n * colon are not metadata.\n */\nexport function isMetadataToken(token: string): boolean {\n if (token.startsWith(\"+\") && token.length > 1) {\n return true;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n return true;\n }\n\n return EXTENSION_PATTERN.test(token);\n}\n\n/**\n * Collect a task's description, projects, contexts, and extensions in one pass.\n *\n * Previous versions tokenized the text once for metadata and again to strip it;\n * doing both here keeps parsing to a single split per line.\n *\n * When a `key:value` key is repeated, `onWarning` receives a\n * `duplicate-metadata-key` warning and the last value wins.\n */\nexport function parseText(\n text: string,\n onWarning?: ParseWarningHandler,\n): TodoText {\n const projects: string[] = [];\n const contexts: string[] = [];\n const data: Record<string, string> = {};\n const descriptionTokens: string[] = [];\n\n for (const token of tokenize(text)) {\n if (token.startsWith(\"+\") && token.length > 1) {\n projects.push(token.slice(1));\n continue;\n }\n\n if (token.startsWith(\"@\") && token.length > 1) {\n contexts.push(token.slice(1));\n continue;\n }\n\n const extension = EXTENSION_PATTERN.exec(token);\n const key = extension?.[1];\n const value = extension?.[2];\n if (key !== undefined && value !== undefined) {\n if (Object.hasOwn(data, key)) {\n onWarning?.({\n code: \"duplicate-metadata-key\",\n message: `Duplicate metadata key \"${key}\"; the last value wins.`,\n meta: { key, previousValue: data[key], value },\n });\n }\n\n data[key] = value;\n continue;\n }\n\n descriptionTokens.push(token);\n }\n\n return {\n description: descriptionTokens.join(\" \"),\n projects,\n contexts,\n data,\n };\n}\n\n/** Collect projects, contexts, and extensions from task text. */\nexport function parseMetadata(text: string): TodoMetadata {\n const { projects, contexts, data } = parseText(text);\n return { projects, contexts, data };\n}\n\n/**\n * Remove inline metadata from task text.\n *\n * Remaining tokens are rejoined with single spaces, so repeated whitespace can\n * be normalized.\n */\nexport function stripMetadata(text: string): string {\n return parseText(text).description;\n}\n","import { isValidDate } from \"./date.ts\";\nimport { parseText } from \"./metadata.ts\";\nimport type {\n ParseOptions,\n ParseWarningHandler,\n TodoRecord,\n} from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\ntype LeadingDate =\n | { kind: \"absent\"; rest: string }\n | { kind: \"valid\"; date: string; rest: string }\n | { kind: \"invalid\"; value: string; rest: string };\n\n/**\n * Inspect a `YYYY-MM-DD` token at the start of `input`.\n *\n * A value with the right shape that does not exist on the calendar is reported\n * as `invalid`. In that case `rest` is the original input, so callers leave the\n * token in the description instead of consuming it.\n */\nfunction takeLeadingDate(input: string): LeadingDate {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return { kind: \"absent\", rest: input };\n }\n\n const date = match[1];\n if (date === undefined) {\n return { kind: \"absent\", rest: input };\n }\n\n if (!isValidDate(date)) {\n return { kind: \"invalid\", value: date, rest: input };\n }\n\n return { kind: \"valid\", date, rest: input.slice(match[0]!.length) };\n}\n\nfunction warnInvalidDate(\n value: string,\n field: \"completedAt\" | \"createdAt\",\n onWarning?: ParseWarningHandler,\n): void {\n const label = field === \"completedAt\" ? \"completion\" : \"creation\";\n\n onWarning?.({\n code: \"invalid-date\",\n message: `Invalid ${label} date \"${value}\"; treating it as text.`,\n meta: { value, field },\n });\n}\n\n/**\n * Accept either a {@link ParseWarningHandler} (deprecated) or\n * {@link ParseOptions} as the second argument.\n */\nfunction normalizeParseOptions(\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): ParseOptions {\n if (typeof onWarningOrOptions === \"function\") {\n return { onWarning: onWarningOrOptions };\n }\n\n return onWarningOrOptions ?? {};\n}\n\n/** Remove one trailing `\\r`, so `raw` has no carriage return for CRLF input. */\nfunction stripTrailingCarriageReturn(line: string): string {\n return line.endsWith(\"\\r\") ? line.slice(0, -1) : line;\n}\n\n/**\n * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.\n *\n * The parser follows the todo.txt format rules:\n *\n * - Completed tasks start with `x `, optionally followed by a completion date\n * and then a creation date.\n * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional\n * creation date.\n * - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but\n * nonexistent date is treated as text.\n * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `options.onWarning` when supplied;\n * parsing still produces a record.\n *\n * With `options.includeSource`, the record carries `raw` (the exact input\n * line, minus a trailing `\\r`) and `line` (the number supplied via\n * `options.line`, when given).\n */\nexport function parseLine(\n line: string,\n options?: ParseOptions,\n): TodoRecord;\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseLine(\n line: string,\n onWarning: ParseWarningHandler,\n): TodoRecord;\nexport function parseLine(\n line: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord {\n const options = normalizeParseOptions(onWarningOrOptions);\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n\n const completedDate = takeLeadingDate(rest);\n if (completedDate.kind === \"valid\") {\n completedAt = completedDate.date;\n rest = completedDate.rest;\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n } else if (completedDate.kind === \"invalid\") {\n // The same token cannot also be a creation date, so only warn once.\n warnInvalidDate(completedDate.value, \"completedAt\", options.onWarning);\n }\n } else {\n const priorityMatch = PRIORITY_PATTERN.exec(rest);\n if (priorityMatch) {\n priority = priorityMatch[1]!;\n rest = rest.slice(priorityMatch[0]!.length);\n }\n\n const createdDate = takeLeadingDate(rest);\n if (createdDate.kind === \"valid\") {\n createdAt = createdDate.date;\n rest = createdDate.rest;\n } else if (createdDate.kind === \"invalid\") {\n warnInvalidDate(createdDate.value, \"createdAt\", options.onWarning);\n }\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(\n text,\n options.onWarning,\n );\n\n const record: TodoRecord = {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n\n if (options.includeSource) {\n if (options.line !== undefined) {\n record.line = options.line;\n }\n\n record.raw = stripTrailingCarriageReturn(line);\n }\n\n return record;\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n *\n * With `options.includeSource`, every record carries `raw` (the exact line,\n * minus a trailing `\\r`) and `line` (the 1-based physical line number,\n * counting blank lines).\n */\nexport function parseDocument(\n contents: string,\n options?: ParseOptions,\n): TodoRecord[];\n/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */\nexport function parseDocument(\n contents: string,\n onWarning: ParseWarningHandler,\n): TodoRecord[];\nexport function parseDocument(\n contents: string,\n onWarningOrOptions?: ParseWarningHandler | ParseOptions,\n): TodoRecord[] {\n const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(line, {\n includeSource,\n line: lineNumber,\n onWarning: onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n }),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecord, cloneRecords } from \"./clone.ts\";\nimport { isValidDate } from \"./date.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/** Fields that {@link TodoQuery.sortBy} can order results by. */\nexport type TodoSortField =\n | \"priority\"\n | \"createdAt\"\n | \"completedAt\"\n | \"description\"\n | \"due\";\n\n/** Sort direction for {@link TodoQuery.sortBy}. Default: `\"asc\"`. */\nexport type TodoSortDirection = \"asc\" | \"desc\";\n\n/**\n * Per-call matching options.\n *\n * `caseSensitive` overrides the client-level default for one call. The default\n * differs per method: project and context matching is exact and case-sensitive\n * unless the option says otherwise, while search is case-insensitive unless the\n * option says otherwise.\n */\nexport interface TodoMatchOptions {\n /** Compare case-sensitively (or, for search, insensitively) for this call. */\n caseSensitive?: boolean;\n}\n\n/** One ordering step appended by {@link TodoQuery.sortBy}. */\nexport interface TodoSortSpec {\n field: TodoSortField;\n direction: TodoSortDirection;\n}\n\n/**\n * Pending/completed/total counts for one bucket of records.\n *\n * `total` is always `pending + completed`.\n */\nexport interface TodoCount {\n /** Records that are not completed. */\n pending: number;\n /** Records marked completed. */\n completed: number;\n /** Every record in the bucket. */\n total: number;\n}\n\n/**\n * One named bucket with its counts, from the aggregate query methods.\n *\n * The name is the project or context exactly as parsed, without the `+` or\n * `@` prefix and with its original casing.\n */\nexport interface TodoNameCount {\n /** Project or context name from the matching records. */\n name: string;\n /** Counts over the matching records that carry the name. */\n counts: TodoCount;\n}\n\n/**\n * Result of {@link TodoQuery.summary}: totals for the matching records plus\n * per-name counts.\n *\n * Per-name totals count multi-tag records once per name, so they do not sum\n * to the top-level `total` when multi-tag records or untagged records\n * exist.\n */\nexport interface TodoSummary {\n /** Every record matching the query. */\n total: number;\n /** Matching records that are not completed. */\n pending: number;\n /** Matching records that are completed. */\n completed: number;\n /** Per-project counts over the matching records. */\n projects: TodoNameCount[];\n /** Per-context counts over the matching records. */\n contexts: TodoNameCount[];\n}\n\n/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.summary}, {@link TodoQuery.countsByProject}, and\n * {@link TodoQuery.countsByContext} are terminal aggregates; and\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /**\n * Aggregate counts for the records matching this query.\n *\n * `total`, `pending`, and `completed` count matching records, while\n * `projects` and `contexts` count each matching record once per distinct\n * name it carries, so a record tagged `+A +B` adds one to each name.\n * Per-name totals therefore do not sum to the top-level `total` when\n * multi-tag records or untagged records exist. Names are unique, keep\n * their original casing, and sort alphabetically like\n * {@link TodoQuery.projects}; completed-only records still contribute\n * their names. A `sortBy` step is ignored, and the summary loads through\n * the cache like every other query.\n */\n summary: () => Promise<TodoSummary>;\n /**\n * Unique project names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByProject: () => Promise<TodoNameCount[]>;\n /**\n * Unique context names in the current result with their counts; see\n * {@link TodoQuery.summary} for the counting rules.\n */\n countsByContext: () => Promise<TodoNameCount[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\n/**\n * Count pending/completed/total per unique name over `records`.\n *\n * Each record contributes at most once per name, so a record tagged\n * `+A +A` counts `A` once. Names keep their original casing and sort\n * like the name plucks, so buckets line up with `projects()`/`contexts()`.\n */\nfunction countNames(\n records: TodoRecord[],\n pick: (todo: TodoRecord) => string[],\n): TodoNameCount[] {\n const buckets = new Map<string, TodoCount>();\n\n for (const record of records) {\n for (const name of new Set(pick(record))) {\n const bucket = buckets.get(name);\n\n if (bucket === undefined) {\n buckets.set(name, {\n pending: record.completed ? 0 : 1,\n completed: record.completed ? 1 : 0,\n total: 1,\n });\n } else if (record.completed) {\n bucket.completed += 1;\n bucket.total += 1;\n } else {\n bucket.pending += 1;\n bucket.total += 1;\n }\n }\n }\n\n return [...buckets]\n .map(([name, counts]) => ({ name, counts }))\n .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\n/**\n * Aggregate the current result into a summary.\n *\n * Sorting never applies to aggregates; they count records, not order them.\n */\nasync function resolveSummary(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoSummary> {\n const records = await resolveRaw(load, { ...state, sort: undefined });\n let pending = 0;\n let completed = 0;\n\n for (const record of records) {\n if (record.completed) {\n completed += 1;\n } else {\n pending += 1;\n }\n }\n\n return {\n total: records.length,\n pending,\n completed,\n projects: countNames(records, (todo) => todo.projects),\n contexts: countNames(records, (todo) => todo.contexts),\n };\n}\n\nfunction resolveCountsBy(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<TodoNameCount[]> {\n // Sorting never applies to aggregates; they count records, not order them.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n countNames(records, pick),\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n summary: () => resolveSummary(load, state),\n countsByProject: () => resolveCountsBy(load, state, (todo) => todo.projects),\n countsByContext: () => resolveCountsBy(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoNameCount,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n TodoSummary,\n} from \"./query.ts\";\nimport type {\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Aggregate counts for the cached snapshot; see {@link TodoQuery.summary}. */\n summary: () => Promise<TodoSummary>;\n /** Per-project counts for the cached snapshot; see {@link TodoQuery.countsByProject}. */\n countsByProject: () => Promise<TodoNameCount[]>;\n /** Per-context counts for the cached snapshot; see {@link TodoQuery.countsByContext}. */\n countsByContext: () => Promise<TodoNameCount[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. With `options.includeSource`, every record also carries the\n * 1-based `line` number and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names, and\n * aggregates such as {@link TodoQuery.summary} count pending and completed\n * records per name. Returned records are copies, so callers may mutate them\n * without affecting the cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await options.read();\n const records = parseDocument(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n summary: query.summary,\n countsByProject: query.countsByProject,\n countsByContext: query.countsByContext,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,OAAmB;EACvB,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,MAAM,EAAE,GAAG,KAAK,KAAK;CACvB;CAEA,IAAI,K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