@jibone/todotxt-core 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -8
- package/dist/index.d.ts +147 -13
- package/dist/index.js +221 -20
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -115,14 +115,24 @@ 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
|
|
126
136
|
```
|
|
127
137
|
|
|
128
138
|
Filters compose, so they can be combined in any order:
|
|
@@ -131,6 +141,8 @@ Filters compose, so they can be combined in any order:
|
|
|
131
141
|
await todos.project("TodoTxt").pending();
|
|
132
142
|
await todos.project("TodoTxt").context("computer");
|
|
133
143
|
await todos.pending().project("OpenSource").context("github");
|
|
144
|
+
await todos.priority("A").search("mom");
|
|
145
|
+
await todos.project(["Garden", "Moving"]).sortBy("priority");
|
|
134
146
|
```
|
|
135
147
|
|
|
136
148
|
### Caching and refresh
|
|
@@ -193,8 +205,10 @@ await todos.context("home").pending().projects();
|
|
|
193
205
|
await todos.context("home").completed().projects();
|
|
194
206
|
```
|
|
195
207
|
|
|
196
|
-
Names are matched exactly and case-sensitively. An unknown project
|
|
197
|
-
resolves to an empty array.
|
|
208
|
+
Names are matched exactly and case-sensitively by default. An unknown project
|
|
209
|
+
or context resolves to an empty array. An empty array argument also matches
|
|
210
|
+
nothing; see [Case-insensitive matching](#case-insensitive-matching) for the
|
|
211
|
+
per-call and client-wide options.
|
|
198
212
|
|
|
199
213
|
### Status semantics
|
|
200
214
|
|
|
@@ -207,6 +221,98 @@ Filters are applied in sequence:
|
|
|
207
221
|
completed record. A project with both pending and completed items appears in
|
|
208
222
|
both `pending().projects()` and `completed().projects()`.
|
|
209
223
|
|
|
224
|
+
### Priority, search, and metadata
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
await todos.priority("A"); // exactly (A); "a" matches nothing
|
|
228
|
+
await todos.priority(["A", "B"]); // either letter
|
|
229
|
+
|
|
230
|
+
await todos.search("PR"); // substring of description,
|
|
231
|
+
// case-insensitive by default
|
|
232
|
+
await todos.search("pr", { caseSensitive: true }); // exact-case substring
|
|
233
|
+
|
|
234
|
+
await todos.meta("due"); // has due, whatever the value
|
|
235
|
+
await todos.meta("due", "2024-04-01"); // exact value
|
|
236
|
+
await todos.hasMeta("due"); // same as meta("due"), more readable
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`search` only looks at `description`. Projects, contexts, and `key:value` tags
|
|
240
|
+
have their own filters.
|
|
241
|
+
|
|
242
|
+
### Date filters
|
|
243
|
+
|
|
244
|
+
Date filters compare strictly against validated `YYYY-MM-DD` values, so plain
|
|
245
|
+
string comparison is safe. Records without the date never match. Invalid
|
|
246
|
+
arguments throw a `TypeError` when the query is built, before any read happens:
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
await todos.createdAfter("2024-01-01"); // createdAt strictly later
|
|
250
|
+
await todos.createdBefore("2024-01-01"); // createdAt strictly earlier
|
|
251
|
+
await todos.completedAfter("2024-01-01"); // completedAt strictly later
|
|
252
|
+
await todos.completedBefore("2024-01-01");// completedAt strictly earlier
|
|
253
|
+
|
|
254
|
+
todos.createdAfter("2024-02-30");
|
|
255
|
+
// TypeError: createdAfter() expected a real calendar date in YYYY-MM-DD form
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
### Negation
|
|
259
|
+
|
|
260
|
+
`notProject` and `notContext` keep the records without a name. An array
|
|
261
|
+
excludes every listed name; an empty array excludes nothing:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
await todos.notProject("Garden");
|
|
265
|
+
await todos.notContext(["phone", "computer"]);
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Sorting
|
|
269
|
+
|
|
270
|
+
`sortBy` appends an ordering step after filtering. The sort is stable, so
|
|
271
|
+
records with equal keys keep file order. Missing values — `null` priorities or
|
|
272
|
+
dates, and missing or invalid `due` values — sort last in both directions;
|
|
273
|
+
`"desc"` reverses only the value comparison. Calling `sortBy` twice keeps the
|
|
274
|
+
last call.
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
await todos.pending().sortBy("priority"); // A first, then B–Z, no priority last
|
|
278
|
+
await todos.sortBy("createdAt"); // earliest first, nulls last
|
|
279
|
+
await todos.sortBy("completedAt", "desc"); // latest first, nulls still last
|
|
280
|
+
await todos.sortBy("due"); // reads data.due; invalid or missing last
|
|
281
|
+
await todos.sortBy("description"); // localeCompare ordering
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### count() and first()
|
|
285
|
+
|
|
286
|
+
`count()` and `first()` resolve through the same loader and cache as every
|
|
287
|
+
other query. `first()` returns the first record of the filtered (and sorted)
|
|
288
|
+
result, or `undefined` when nothing matches, and it is a copy:
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
await todos.pending().count(); // 12
|
|
292
|
+
await todos.sortBy("priority").first(); // first (A) task
|
|
293
|
+
await todos.project("Missing").first(); // undefined
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
### Case-insensitive matching
|
|
297
|
+
|
|
298
|
+
Name matching is exact by default. Change the default for a whole client, or
|
|
299
|
+
for a single call:
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
const todos = createTodoTxt({
|
|
303
|
+
read: () => Bun.file("todo.txt").text(),
|
|
304
|
+
caseSensitive: false,
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
await todos.project("garden"); // matches +Garden
|
|
308
|
+
await todos.project("TodoTxt", { caseSensitive: true }); // back to exact
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Case-insensitive comparison uses `toLowerCase()`, which is deterministic across
|
|
312
|
+
machines and locales but is not full Unicode case folding. `projects()` and
|
|
313
|
+
`contexts()` always preserve original casing. `search` is independent of this
|
|
314
|
+
setting: it is case-insensitive by default whatever the client says.
|
|
315
|
+
|
|
210
316
|
## Logging
|
|
211
317
|
|
|
212
318
|
`createTodoTxt` is silent by default. Pass a `logger` to receive diagnostics.
|
|
@@ -278,6 +384,8 @@ bun examples/todo-cross.ts
|
|
|
278
384
|
bun examples/todo-logger.ts
|
|
279
385
|
bun examples/todo-try.ts
|
|
280
386
|
bun examples/todo-source.ts
|
|
387
|
+
bun examples/todo-filters.ts
|
|
388
|
+
bun examples/todo-sort.ts
|
|
281
389
|
```
|
|
282
390
|
|
|
283
391
|
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,120 @@ 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
|
+
}
|
|
138
164
|
/**
|
|
139
165
|
* A lazy query over parsed todo records.
|
|
140
166
|
*
|
|
141
167
|
* Filters return a new query and perform no IO. Awaiting a query resolves
|
|
142
168
|
* through the supplied loader; the client caches parsed records, so only the
|
|
143
|
-
* first query reads the file.
|
|
144
|
-
*
|
|
145
|
-
*
|
|
169
|
+
* first query reads the file. Filters compose with AND: every predicate added
|
|
170
|
+
* to the chain must match. Array arguments are OR within a single call, so
|
|
171
|
+
* `project(["A", "B"])` matches either name while `project("A").project("B")`
|
|
172
|
+
* requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}
|
|
173
|
+
* are terminal plucks that resolve to unique, alphabetically sorted names;
|
|
174
|
+
* {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.
|
|
146
175
|
*/
|
|
147
176
|
interface TodoQuery extends PromiseLike<TodoRecord[]> {
|
|
148
177
|
/** Only records that are not completed. */
|
|
149
178
|
pending: () => TodoQuery;
|
|
150
179
|
/** Only records that are completed. */
|
|
151
180
|
completed: () => TodoQuery;
|
|
152
|
-
/**
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
181
|
+
/**
|
|
182
|
+
* Only records tagged with the project `name`.
|
|
183
|
+
*
|
|
184
|
+
* An array matches any listed name (OR); repeated calls require every name
|
|
185
|
+
* (AND). An empty array matches nothing. Matching is exact and
|
|
186
|
+
* case-sensitive unless the client-level `caseSensitive` option or the
|
|
187
|
+
* per-call override says otherwise; case-insensitive comparison uses
|
|
188
|
+
* `toLowerCase()`, which is not full Unicode case folding.
|
|
189
|
+
*/
|
|
190
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
191
|
+
/** Only records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
192
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
193
|
+
/**
|
|
194
|
+
* Only records not tagged with the project `name`.
|
|
195
|
+
*
|
|
196
|
+
* An array excludes every listed name; an empty array excludes nothing.
|
|
197
|
+
* This is not a replacement for `pending()`/`completed()`.
|
|
198
|
+
*/
|
|
199
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
200
|
+
/** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
201
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
202
|
+
/**
|
|
203
|
+
* Only records with priority `letter`.
|
|
204
|
+
*
|
|
205
|
+
* Matching is exact against the uppercase letter the parser stores, so
|
|
206
|
+
* `priority("a")` matches nothing. An array matches any listed letter.
|
|
207
|
+
*/
|
|
208
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
209
|
+
/**
|
|
210
|
+
* Only records whose description contains `text` as a substring.
|
|
211
|
+
*
|
|
212
|
+
* Case-insensitive by default, independently of the client-level matching
|
|
213
|
+
* option. Only `description` is searched; projects, contexts, and metadata
|
|
214
|
+
* have their own filters.
|
|
215
|
+
*/
|
|
216
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
217
|
+
/**
|
|
218
|
+
* Only records with the metadata `key`.
|
|
219
|
+
*
|
|
220
|
+
* With a `value`, the record's value must match it exactly.
|
|
221
|
+
*/
|
|
222
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
223
|
+
/** Only records that have the metadata `key`, whatever its value. */
|
|
224
|
+
hasMeta: (key: string) => TodoQuery;
|
|
225
|
+
/**
|
|
226
|
+
* Only records created strictly after `date`.
|
|
227
|
+
*
|
|
228
|
+
* The argument must be a real calendar date in `YYYY-MM-DD` form; anything
|
|
229
|
+
* else throws a `TypeError` when the query is built, before any IO.
|
|
230
|
+
* Records without a creation date never match.
|
|
231
|
+
*/
|
|
232
|
+
createdAfter: (date: string) => TodoQuery;
|
|
233
|
+
/** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
234
|
+
createdBefore: (date: string) => TodoQuery;
|
|
235
|
+
/** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
236
|
+
completedAfter: (date: string) => TodoQuery;
|
|
237
|
+
/** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
238
|
+
completedBefore: (date: string) => TodoQuery;
|
|
239
|
+
/**
|
|
240
|
+
* Sort the filtered records by `field`; default direction is `"asc"`.
|
|
241
|
+
*
|
|
242
|
+
* The sort is stable: records with equal keys keep file order. Missing
|
|
243
|
+
* values (`null` priorities or dates, and missing or invalid `due` values)
|
|
244
|
+
* sort last in both directions; `"desc"` reverses only the value
|
|
245
|
+
* comparison, never the missing-value placement. Calling `sortBy` twice
|
|
246
|
+
* keeps only the last call. Description ordering uses `localeCompare`, so
|
|
247
|
+
* it follows the host locale for equal-ignoring-case ties.
|
|
248
|
+
*/
|
|
249
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
156
250
|
/** Unique project names in the current result, alphabetically sorted. */
|
|
157
251
|
projects: () => Promise<string[]>;
|
|
158
252
|
/** Unique context names in the current result, alphabetically sorted. */
|
|
159
253
|
contexts: () => Promise<string[]>;
|
|
254
|
+
/** Number of records in the current result; equal to `(await query).length`. */
|
|
255
|
+
count: () => Promise<number>;
|
|
256
|
+
/**
|
|
257
|
+
* The first record of the filtered (and sorted) result, or `undefined`
|
|
258
|
+
* when nothing matches. The record is a copy, so mutating it cannot affect
|
|
259
|
+
* the client's cache.
|
|
260
|
+
*/
|
|
261
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
160
262
|
}
|
|
161
263
|
/** The read interface returned by {@link createTodoTxt}. */
|
|
162
264
|
interface TodoTxtClient {
|
|
@@ -166,10 +268,40 @@ interface TodoTxtClient {
|
|
|
166
268
|
pending: () => TodoQuery;
|
|
167
269
|
/** Query only records that are completed, using the cached snapshot. */
|
|
168
270
|
completed: () => TodoQuery;
|
|
169
|
-
/**
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
271
|
+
/**
|
|
272
|
+
* Query records tagged with the project `name`, using the cache.
|
|
273
|
+
*
|
|
274
|
+
* An array matches any listed name; see {@link TodoQuery.project}.
|
|
275
|
+
*/
|
|
276
|
+
project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
277
|
+
/** Query records tagged with the context `name`; see {@link TodoQuery.project}. */
|
|
278
|
+
context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
279
|
+
/** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */
|
|
280
|
+
notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
281
|
+
/** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */
|
|
282
|
+
notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;
|
|
283
|
+
/** Query records with the priority `letter`; see {@link TodoQuery.priority}. */
|
|
284
|
+
priority: (letter: string | string[]) => TodoQuery;
|
|
285
|
+
/** Query records whose description contains `text`; see {@link TodoQuery.search}. */
|
|
286
|
+
search: (text: string, options?: TodoMatchOptions) => TodoQuery;
|
|
287
|
+
/** Query records with the metadata `key`; see {@link TodoQuery.meta}. */
|
|
288
|
+
meta: (key: string, value?: string) => TodoQuery;
|
|
289
|
+
/** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */
|
|
290
|
+
hasMeta: (key: string) => TodoQuery;
|
|
291
|
+
/** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
292
|
+
createdAfter: (date: string) => TodoQuery;
|
|
293
|
+
/** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
294
|
+
createdBefore: (date: string) => TodoQuery;
|
|
295
|
+
/** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */
|
|
296
|
+
completedAfter: (date: string) => TodoQuery;
|
|
297
|
+
/** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */
|
|
298
|
+
completedBefore: (date: string) => TodoQuery;
|
|
299
|
+
/** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */
|
|
300
|
+
sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;
|
|
301
|
+
/** Count records in the cached snapshot; see {@link TodoQuery.count}. */
|
|
302
|
+
count: () => Promise<number>;
|
|
303
|
+
/** First record of the cached snapshot; see {@link TodoQuery.first}. */
|
|
304
|
+
first: () => Promise<TodoRecord | undefined>;
|
|
173
305
|
/** List unique project names from the cached snapshot, alphabetically sorted. */
|
|
174
306
|
projects: () => Promise<string[]>;
|
|
175
307
|
/** List unique context names from the cached snapshot, alphabetically sorted. */
|
|
@@ -183,7 +315,9 @@ interface TodoTxtClient {
|
|
|
183
315
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
184
316
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
185
317
|
* diagnostics. With `options.includeSource`, every record also carries the
|
|
186
|
-
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
318
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
319
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
320
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
187
321
|
*
|
|
188
322
|
* Parsed records are cached in memory per client. The first query loads and
|
|
189
323
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -236,4 +370,4 @@ export declare function parseLine(line: string, onWarning: ParseWarningHandler):
|
|
|
236
370
|
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
237
371
|
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
238
372
|
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
239
|
-
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoQuery, TodoRecord, TodoTxtClient };
|
|
373
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoMatchOptions, TodoQuery, TodoRecord, TodoSortDirection, TodoSortField, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -233,33 +233,216 @@ 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);
|
|
330
|
+
}
|
|
331
|
+
async function resolveRecords(load, state) {
|
|
332
|
+
return cloneRecords(await resolveRaw(load, state));
|
|
240
333
|
}
|
|
241
|
-
|
|
242
|
-
return
|
|
334
|
+
function pluckNames(load, state, pick) {
|
|
335
|
+
return resolveRaw(load, {
|
|
336
|
+
...state,
|
|
337
|
+
sort: void 0
|
|
338
|
+
}).then((records) => uniqueSorted(records.flatMap(pick)));
|
|
243
339
|
}
|
|
244
|
-
function
|
|
245
|
-
return resolveRaw(load,
|
|
340
|
+
function resolveCount(load, state) {
|
|
341
|
+
return resolveRaw(load, {
|
|
342
|
+
...state,
|
|
343
|
+
sort: void 0
|
|
344
|
+
}).then((records) => records.length);
|
|
345
|
+
}
|
|
346
|
+
async function resolveFirst(load, state) {
|
|
347
|
+
const first = (await resolveRaw(load, state))[0];
|
|
348
|
+
return first === void 0 ? void 0 : cloneRecord(first);
|
|
246
349
|
}
|
|
247
350
|
/**
|
|
248
351
|
* Create a lazy query over the records loaded by `load`.
|
|
249
352
|
*
|
|
250
|
-
* Each filter method appends a predicate, so chained calls compose
|
|
251
|
-
*
|
|
252
|
-
* `
|
|
353
|
+
* Each filter method appends a predicate, so chained calls compose with AND,
|
|
354
|
+
* while array arguments match any listed value. `sortBy` appends an ordering
|
|
355
|
+
* step instead of a predicate; the last `sortBy` call wins. For example,
|
|
356
|
+
* `pending().completed()` matches nothing, while
|
|
357
|
+
* `project("Work").pending()` matches pending records in `Work`, and
|
|
358
|
+
* `pending().sortBy("priority")` lists them A first.
|
|
253
359
|
*/
|
|
254
|
-
function createTodoQuery(load,
|
|
360
|
+
function createTodoQuery(load, state = {
|
|
361
|
+
filters: [],
|
|
362
|
+
caseSensitive: true
|
|
363
|
+
}) {
|
|
364
|
+
const nameOptions = (options) => options?.caseSensitive ?? state.caseSensitive;
|
|
255
365
|
return {
|
|
256
|
-
pending: () => createTodoQuery(load,
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
366
|
+
pending: () => createTodoQuery(load, {
|
|
367
|
+
...state,
|
|
368
|
+
filters: [...state.filters, (todo) => !todo.completed]
|
|
369
|
+
}),
|
|
370
|
+
completed: () => createTodoQuery(load, {
|
|
371
|
+
...state,
|
|
372
|
+
filters: [...state.filters, (todo) => todo.completed]
|
|
373
|
+
}),
|
|
374
|
+
project: (name, options) => createTodoQuery(load, {
|
|
375
|
+
...state,
|
|
376
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), false)]
|
|
377
|
+
}),
|
|
378
|
+
context: (name, options) => createTodoQuery(load, {
|
|
379
|
+
...state,
|
|
380
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), false)]
|
|
381
|
+
}),
|
|
382
|
+
notProject: (name, options) => createTodoQuery(load, {
|
|
383
|
+
...state,
|
|
384
|
+
filters: [...state.filters, nameFilter((todo) => todo.projects, toArray(name), nameOptions(options), true)]
|
|
385
|
+
}),
|
|
386
|
+
notContext: (name, options) => createTodoQuery(load, {
|
|
387
|
+
...state,
|
|
388
|
+
filters: [...state.filters, nameFilter((todo) => todo.contexts, toArray(name), nameOptions(options), true)]
|
|
389
|
+
}),
|
|
390
|
+
priority: (letter) => {
|
|
391
|
+
const letters = toArray(letter);
|
|
392
|
+
return createTodoQuery(load, {
|
|
393
|
+
...state,
|
|
394
|
+
filters: [...state.filters, (todo) => todo.priority !== null && letters.includes(todo.priority)]
|
|
395
|
+
});
|
|
396
|
+
},
|
|
397
|
+
search: (text, options) => {
|
|
398
|
+
const caseSensitive = options?.caseSensitive ?? false;
|
|
399
|
+
const needle = caseSensitive ? text : text.toLowerCase();
|
|
400
|
+
return createTodoQuery(load, {
|
|
401
|
+
...state,
|
|
402
|
+
filters: [...state.filters, (todo) => {
|
|
403
|
+
return (caseSensitive ? todo.description : todo.description.toLowerCase()).includes(needle);
|
|
404
|
+
}]
|
|
405
|
+
});
|
|
406
|
+
},
|
|
407
|
+
meta: (key, value) => {
|
|
408
|
+
const filter = value === void 0 ? (todo) => Object.hasOwn(todo.data, key) : (todo) => todo.data[key] === value;
|
|
409
|
+
return createTodoQuery(load, {
|
|
410
|
+
...state,
|
|
411
|
+
filters: [...state.filters, filter]
|
|
412
|
+
});
|
|
413
|
+
},
|
|
414
|
+
hasMeta: (key) => createTodoQuery(load, {
|
|
415
|
+
...state,
|
|
416
|
+
filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)]
|
|
417
|
+
}),
|
|
418
|
+
createdAfter: (date) => createTodoQuery(load, {
|
|
419
|
+
...state,
|
|
420
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdAfter", (a, b) => a > b)]
|
|
421
|
+
}),
|
|
422
|
+
createdBefore: (date) => createTodoQuery(load, {
|
|
423
|
+
...state,
|
|
424
|
+
filters: [...state.filters, dateFilter("createdAt", date, "createdBefore", (a, b) => a < b)]
|
|
425
|
+
}),
|
|
426
|
+
completedAfter: (date) => createTodoQuery(load, {
|
|
427
|
+
...state,
|
|
428
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedAfter", (a, b) => a > b)]
|
|
429
|
+
}),
|
|
430
|
+
completedBefore: (date) => createTodoQuery(load, {
|
|
431
|
+
...state,
|
|
432
|
+
filters: [...state.filters, dateFilter("completedAt", date, "completedBefore", (a, b) => a < b)]
|
|
433
|
+
}),
|
|
434
|
+
sortBy: (field, direction = "asc") => createTodoQuery(load, {
|
|
435
|
+
...state,
|
|
436
|
+
sort: {
|
|
437
|
+
field,
|
|
438
|
+
direction
|
|
439
|
+
}
|
|
440
|
+
}),
|
|
441
|
+
projects: () => pluckNames(load, state, (todo) => todo.projects),
|
|
442
|
+
contexts: () => pluckNames(load, state, (todo) => todo.contexts),
|
|
443
|
+
count: () => resolveCount(load, state),
|
|
444
|
+
first: () => resolveFirst(load, state),
|
|
445
|
+
then: (onfulfilled, onrejected) => resolveRecords(load, state).then(onfulfilled, onrejected)
|
|
263
446
|
};
|
|
264
447
|
}
|
|
265
448
|
// src/client.ts
|
|
@@ -271,7 +454,9 @@ function createTodoQuery(load, filters = []) {
|
|
|
271
454
|
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
272
455
|
* default; when supplied, it receives read lifecycle and parse warning
|
|
273
456
|
* diagnostics. With `options.includeSource`, every record also carries the
|
|
274
|
-
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
457
|
+
* 1-based `line` number and the exact `raw` line it was parsed from. With
|
|
458
|
+
* `options.caseSensitive: false`, project and context matching compares
|
|
459
|
+
* names through `toLowerCase()`; the default is exact matching.
|
|
275
460
|
*
|
|
276
461
|
* Parsed records are cached in memory per client. The first query loads and
|
|
277
462
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -328,13 +513,29 @@ function createTodoTxt(options) {
|
|
|
328
513
|
return refresh();
|
|
329
514
|
};
|
|
330
515
|
const all = async () => cloneRecords(await refresh());
|
|
331
|
-
const query = createTodoQuery(loadCached
|
|
516
|
+
const query = createTodoQuery(loadCached, {
|
|
517
|
+
filters: [],
|
|
518
|
+
caseSensitive: options.caseSensitive ?? true
|
|
519
|
+
});
|
|
332
520
|
return {
|
|
333
521
|
all,
|
|
334
522
|
pending: query.pending,
|
|
335
523
|
completed: query.completed,
|
|
336
524
|
project: query.project,
|
|
337
525
|
context: query.context,
|
|
526
|
+
notProject: query.notProject,
|
|
527
|
+
notContext: query.notContext,
|
|
528
|
+
priority: query.priority,
|
|
529
|
+
search: query.search,
|
|
530
|
+
meta: query.meta,
|
|
531
|
+
hasMeta: query.hasMeta,
|
|
532
|
+
createdAfter: query.createdAfter,
|
|
533
|
+
createdBefore: query.createdBefore,
|
|
534
|
+
completedAfter: query.completedAfter,
|
|
535
|
+
completedBefore: query.completedBefore,
|
|
536
|
+
sortBy: query.sortBy,
|
|
537
|
+
count: query.count,
|
|
538
|
+
first: query.first,
|
|
338
539
|
projects: query.projects,
|
|
339
540
|
contexts: query.contexts
|
|
340
541
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/date.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n 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;CACvB;CAEA,IAAI,KAAK,SAAS,KAAA,GAChB,KAAK,OAAO,KAAK;CAGnB,IAAI,KAAK,QAAQ,KAAA,GACf,KAAK,MAAM,KAAK;CAGlB,OAAO;AACT;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;;AC7BA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;CAAC;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;AAAE;AAErE,SAAS,WAAW,MAAuB;CACzC,OAAQ,OAAO,MAAM,KAAK,OAAO,QAAQ,KAAM,OAAO,QAAQ;AAChE;;;;;;;;AASA,SAAgB,YAAY,OAAwB;CAClD,MAAM,QAAQ,mBAAmB,KAAK,KAAK;CAC3C,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,OAAO,OAAO,MAAM,EAAE;CAC5B,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,MAAM,MAAM,OAAO,MAAM,EAAE;CAE3B,IAAI,QAAQ,KAAK,QAAQ,MAAM,MAAM,G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AAoB,EAAE;EAE5B,IAAI,SAAS,mBAAmB;EAEhC,MAAM,UAAU,cAAc,MADP,QAAQ,KAAK,GACI;GACtC,eAAe,QAAQ;GACvB,YAAY,YAAY;IACtB,IAAI,QAAQ,QAAQ,SAAS;KAC3B,GAAG,QAAQ;KACX,MAAM,QAAQ;KACd,MAAM,QAAQ;IAChB,CAAC;GACH;EACF,CAAC;EACD,IAAI,SAAS,oBAAoB,EAAE,SAAS,QAAQ,OAAO,CAAC;EAE5D,IAAI,sBAAsB,YACxB,QAAQ;EAGV,OAAO;CACT;CAEA,MAAM,gBAAuC;EAC3C,MAAM,UAAU,UAAU;EAC1B,WAAW;EAEX,QACG,cAAc;GACb,IAAI,aAAa,SACf,WAAW,KAAA;EAEf,CAAC,CAAC,CACD,YAAY,CAAC,CAAC;EAEjB,OAAO;CACT;CAEA,MAAM,mBAA0C;EAC9C,IAAI,UACF,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/** Internal query state: AND-composed filters plus one optional sort step. */\nexport interface TodoQueryState {\n filters: TodoFilter[];\n sort?: TodoSortSpec;\n /**\n * Client-level default for name matching. Search is unaffected: it stays\n * case-insensitive by default no matter what this says.\n */\n caseSensitive: boolean;\n}\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. Filters compose with AND: every predicate added\n * to the chain must match. Array arguments are OR within a single call, so\n * `project([\"A\", \"B\"])` matches either name while `project(\"A\").project(\"B\")`\n * requires both. {@link TodoQuery.projects} and {@link TodoQuery.contexts}\n * are terminal plucks that resolve to unique, alphabetically sorted names;\n * {@link TodoQuery.count} and {@link TodoQuery.first} are terminal shortcuts.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /**\n * Only records tagged with the project `name`.\n *\n * An array matches any listed name (OR); repeated calls require every name\n * (AND). An empty array matches nothing. Matching is exact and\n * case-sensitive unless the client-level `caseSensitive` option or the\n * per-call override says otherwise; case-insensitive comparison uses\n * `toLowerCase()`, which is not full Unicode case folding.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records not tagged with the project `name`.\n *\n * An array excludes every listed name; an empty array excludes nothing.\n * This is not a replacement for `pending()`/`completed()`.\n */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Only records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with priority `letter`.\n *\n * Matching is exact against the uppercase letter the parser stores, so\n * `priority(\"a\")` matches nothing. An array matches any listed letter.\n */\n priority: (letter: string | string[]) => TodoQuery;\n /**\n * Only records whose description contains `text` as a substring.\n *\n * Case-insensitive by default, independently of the client-level matching\n * option. Only `description` is searched; projects, contexts, and metadata\n * have their own filters.\n */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /**\n * Only records with the metadata `key`.\n *\n * With a `value`, the record's value must match it exactly.\n */\n meta: (key: string, value?: string) => TodoQuery;\n /** Only records that have the metadata `key`, whatever its value. */\n hasMeta: (key: string) => TodoQuery;\n /**\n * Only records created strictly after `date`.\n *\n * The argument must be a real calendar date in `YYYY-MM-DD` form; anything\n * else throws a `TypeError` when the query is built, before any IO.\n * Records without a creation date never match.\n */\n createdAfter: (date: string) => TodoQuery;\n /** Only records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Only records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Only records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /**\n * Sort the filtered records by `field`; default direction is `\"asc\"`.\n *\n * The sort is stable: records with equal keys keep file order. Missing\n * values (`null` priorities or dates, and missing or invalid `due` values)\n * sort last in both directions; `\"desc\"` reverses only the value\n * comparison, never the missing-value placement. Calling `sortBy` twice\n * keeps only the last call. Description ordering uses `localeCompare`, so\n * it follows the host locale for equal-ignoring-case ties.\n */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n /** Number of records in the current result; equal to `(await query).length`. */\n count: () => Promise<number>;\n /**\n * The first record of the filtered (and sorted) result, or `undefined`\n * when nothing matches. The record is a copy, so mutating it cannot affect\n * the client's cache.\n */\n first: () => Promise<TodoRecord | undefined>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nfunction toArray(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\n/**\n * Build a name-matching predicate for projects or contexts.\n *\n * Case-insensitive comparison normalizes both sides with `toLowerCase()`,\n * which is deterministic across machines and locales but not full Unicode\n * case folding. `invert` turns the predicate into a negation filter.\n */\nfunction nameFilter(\n pick: (todo: TodoRecord) => string[],\n names: string[],\n caseSensitive: boolean,\n invert: boolean,\n): TodoFilter {\n const wanted = caseSensitive\n ? names\n : names.map((name) => name.toLowerCase());\n\n const matches = (todo: TodoRecord): boolean =>\n pick(todo).some((value) =>\n wanted.includes(caseSensitive ? value : value.toLowerCase()),\n );\n\n return invert ? (todo) => !matches(todo) : matches;\n}\n\n/**\n * Validate a date-filter argument at query-build time.\n *\n * Invalid arguments throw instead of silently matching nothing, so a typo in\n * a bound cannot hide behind an empty result.\n */\nfunction requireValidDate(date: string, method: string): string {\n if (!isValidDate(date)) {\n throw new TypeError(\n `${method}() expected a real calendar date in YYYY-MM-DD form, got \"${date}\".`,\n );\n }\n\n return date;\n}\n\n/**\n * Build a date-comparison predicate on a record date field.\n *\n * Records with `null` dates never match; validated `YYYY-MM-DD` values\n * compare correctly as plain strings.\n */\nfunction dateFilter(\n field: \"createdAt\" | \"completedAt\",\n date: string,\n method: string,\n keep: (recordDate: string, bound: string) => boolean,\n): TodoFilter {\n const bound = requireValidDate(date, method);\n\n return (todo) => {\n const recordDate = todo[field];\n return recordDate !== null && keep(recordDate, bound);\n };\n}\n\n/** Read `data.due` when it is a real calendar date; otherwise `null`. */\nfunction dueDateOf(todo: TodoRecord): string | null {\n const due = todo.data[\"due\"];\n return due !== undefined && isValidDate(due) ? due : null;\n}\n\ntype NullableSortField = Exclude<TodoSortField, \"description\">;\n\n/** Extract the nullable sort key for every field except `description`. */\nfunction sortKey(todo: TodoRecord, field: NullableSortField): string | null {\n switch (field) {\n case \"priority\":\n return todo.priority;\n case \"createdAt\":\n return todo.createdAt;\n case \"completedAt\":\n return todo.completedAt;\n case \"due\":\n return dueDateOf(todo);\n }\n}\n\n/**\n * Compare nullable keys with missing values last in both directions.\n *\n * `desc` negates only the value comparison, never the missing-value\n * placement; equal keys compare as `0` so the stable sort keeps file order.\n */\nfunction compareNullableKeys(\n a: string | null,\n b: string | null,\n direction: TodoSortDirection,\n): number {\n if (a === null) {\n return b === null ? 0 : 1;\n }\n\n if (b === null) {\n return -1;\n }\n\n const result = a < b ? -1 : a > b ? 1 : 0;\n return direction === \"asc\" ? result : -result;\n}\n\n/** Build the sort comparator for one ordering step. */\nfunction makeComparator(\n spec: TodoSortSpec,\n): (a: TodoRecord, b: TodoRecord) => number {\n if (spec.field === \"description\") {\n return (a, b) => {\n const result = a.description.localeCompare(b.description);\n return spec.direction === \"asc\" ? result : -result;\n };\n }\n\n const field: NullableSortField = spec.field;\n\n return (a, b) =>\n compareNullableKeys(\n sortKey(a, field),\n sortKey(b, field),\n spec.direction,\n );\n}\n\n/**\n * Sort in place and return the same array.\n *\n * `Array#sort` is stable, so records with equal keys keep file order.\n */\nfunction applySort(records: TodoRecord[], sort: TodoSortSpec): TodoRecord[] {\n return records.sort(makeComparator(sort));\n}\n\n/**\n * Load, filter, and sort records without cloning them.\n *\n * The returned array is safe to sort because it is always a fresh copy when\n * a sort step exists; without one the loader's own array is returned as-is.\n */\nasync function resolveRaw(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (state.sort === undefined) {\n if (state.filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n }\n\n // Never sort the loader's array in place: the client's cache must keep\n // file order for later queries.\n const matches =\n state.filters.length === 0\n ? records.slice()\n : records.filter((record) =>\n state.filters.every((filter) => filter(record)),\n );\n\n return applySort(matches, state.sort);\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, state));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n state: TodoQueryState,\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n // Sorting never applies to name plucks; they alphabetize themselves.\n return resolveRaw(load, { ...state, sort: undefined }).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\nfunction resolveCount(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<number> {\n return resolveRaw(load, { ...state, sort: undefined }).then(\n (records) => records.length,\n );\n}\n\nasync function resolveFirst(\n load: LoadRecords,\n state: TodoQueryState,\n): Promise<TodoRecord | undefined> {\n const first = (await resolveRaw(load, state))[0];\n return first === undefined ? undefined : cloneRecord(first);\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose with AND,\n * while array arguments match any listed value. `sortBy` appends an ordering\n * step instead of a predicate; the last `sortBy` call wins. For example,\n * `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`, and\n * `pending().sortBy(\"priority\")` lists them A first.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n state: TodoQueryState = { filters: [], caseSensitive: true },\n): TodoQuery {\n const nameOptions = (options?: TodoMatchOptions): boolean =>\n options?.caseSensitive ?? state.caseSensitive;\n\n return {\n pending: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => !todo.completed],\n }),\n completed: () =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => todo.completed],\n }),\n project: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n context: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n false,\n ),\n ],\n }),\n notProject: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.projects,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n notContext: (name, options) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n nameFilter(\n (todo) => todo.contexts,\n toArray(name),\n nameOptions(options),\n true,\n ),\n ],\n }),\n priority: (letter) => {\n const letters = toArray(letter);\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => todo.priority !== null && letters.includes(todo.priority),\n ],\n });\n },\n search: (text, options) => {\n const caseSensitive = options?.caseSensitive ?? false;\n const needle = caseSensitive ? text : text.toLowerCase();\n\n return createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n (todo) => {\n const haystack = caseSensitive\n ? todo.description\n : todo.description.toLowerCase();\n return haystack.includes(needle);\n },\n ],\n });\n },\n meta: (key, value) => {\n const filter: TodoFilter =\n value === undefined\n ? (todo) => Object.hasOwn(todo.data, key)\n : (todo) => todo.data[key] === value;\n\n return createTodoQuery(load, { ...state, filters: [...state.filters, filter] });\n },\n hasMeta: (key) =>\n createTodoQuery(load, {\n ...state,\n filters: [...state.filters, (todo) => Object.hasOwn(todo.data, key)],\n }),\n createdAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdAfter\", (a, b) => a > b),\n ],\n }),\n createdBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"createdAt\", date, \"createdBefore\", (a, b) => a < b),\n ],\n }),\n completedAfter: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedAfter\", (a, b) => a > b),\n ],\n }),\n completedBefore: (date) =>\n createTodoQuery(load, {\n ...state,\n filters: [\n ...state.filters,\n dateFilter(\"completedAt\", date, \"completedBefore\", (a, b) => a < b),\n ],\n }),\n sortBy: (field, direction = \"asc\") =>\n createTodoQuery(load, { ...state, sort: { field, direction } }),\n projects: () => pluckNames(load, state, (todo) => todo.projects),\n contexts: () => pluckNames(load, state, (todo) => todo.contexts),\n count: () => resolveCount(load, state),\n first: () => resolveFirst(load, state),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, state).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type {\n TodoMatchOptions,\n TodoQuery,\n TodoSortDirection,\n TodoSortField,\n} from \"./query.ts\";\nimport type {\n TodoClientOptions,\n TodoLogger,\n TodoRecord,\n} from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /**\n * Query records tagged with the project `name`, using the cache.\n *\n * An array matches any listed name; see {@link TodoQuery.project}.\n */\n project: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records tagged with the context `name`; see {@link TodoQuery.project}. */\n context: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the project `name`; see {@link TodoQuery.notProject}. */\n notProject: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records not tagged with the context `name`; see {@link TodoQuery.notProject}. */\n notContext: (name: string | string[], options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the priority `letter`; see {@link TodoQuery.priority}. */\n priority: (letter: string | string[]) => TodoQuery;\n /** Query records whose description contains `text`; see {@link TodoQuery.search}. */\n search: (text: string, options?: TodoMatchOptions) => TodoQuery;\n /** Query records with the metadata `key`; see {@link TodoQuery.meta}. */\n meta: (key: string, value?: string) => TodoQuery;\n /** Query records that have the metadata `key`; see {@link TodoQuery.hasMeta}. */\n hasMeta: (key: string) => TodoQuery;\n /** Query records created strictly after `date`; see {@link TodoQuery.createdAfter}. */\n createdAfter: (date: string) => TodoQuery;\n /** Query records created strictly before `date`; see {@link TodoQuery.createdAfter}. */\n createdBefore: (date: string) => TodoQuery;\n /** Query records completed strictly after `date`; see {@link TodoQuery.createdAfter}. */\n completedAfter: (date: string) => TodoQuery;\n /** Query records completed strictly before `date`; see {@link TodoQuery.createdAfter}. */\n completedBefore: (date: string) => TodoQuery;\n /** Sort the whole cached snapshot; see {@link TodoQuery.sortBy}. */\n sortBy: (field: TodoSortField, direction?: TodoSortDirection) => TodoQuery;\n /** Count records in the cached snapshot; see {@link TodoQuery.count}. */\n count: () => Promise<number>;\n /** First record of the cached snapshot; see {@link TodoQuery.first}. */\n first: () => Promise<TodoRecord | undefined>;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `options.read` is responsible for\n * producing the file contents and `options.write` will be used by the write\n * APIs once they are implemented. `options.logger` is optional and silent by\n * default; when supplied, it receives read lifecycle and parse warning\n * diagnostics. With `options.includeSource`, every record also carries the\n * 1-based `line` number and the exact `raw` line it was parsed from. With\n * `options.caseSensitive: false`, project and context matching compares\n * names through `toLowerCase()`; the default is exact matching.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, and plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names.\n * Returned records are copies, so callers may mutate them without affecting the\n * cache.\n */\nexport function createTodoTxt(options: TodoClientOptions): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = options.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await options.read();\n const records = parseDocument(contents, {\n includeSource: options.includeSource,\n onWarning: (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n },\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached, {\n filters: [],\n caseSensitive: options.caseSensitive ?? true,\n });\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n notProject: query.notProject,\n notContext: query.notContext,\n priority: query.priority,\n search: query.search,\n meta: query.meta,\n hasMeta: query.hasMeta,\n createdAfter: query.createdAfter,\n createdBefore: query.createdBefore,\n completedAfter: query.completedAfter,\n completedBefore: query.completedBefore,\n sortBy: query.sortBy,\n count: query.count,\n first: query.first,\n projects: query.projects,\n contexts: query.contexts,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,MAAM,OAAmB;EACvB,WAAW,KAAK;EAChB,UAAU,KAAK;EACf,aAAa,KAAK;EAClB,WAAW,KAAK;EAChB,aAAa,KAAK;EAClB,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,UAAU,CAAC,GAAG,KAAK,QAAQ;EAC3B,MAAM,EAAE,GAAG,KAAK,KAAK;CACvB;CAEA,IAAI,KAAK,SAAS,KAAA,GAChB,KAAK,OAAO,KAAK;CAGnB,IAAI,KAAK,QAAQ,KAAA,GACf,KAAK,MAAM,KAAK;CAGlB,OAAO;AACT;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;;AC7BA,MAAM,qBAAqB;AAC3B,MAAM,gBAAgB;CAAC;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;CAAI;AAAE;AAErE,SAAS,WAAW,MAAuB;CACzC,OAAQ,OAAO,MAAM,KAAK,OAAO,QAAQ,KAAM,OAAO,QAAQ;AAChE;;;;;;;;AASA,SAAgB,YAAY,OAAwB;CAClD,MAAM,QAAQ,mBAAmB,KAAK,KAAK;CAC3C,IAAI,CAAC,OACH,OAAO;CAGT,MAAM,OAAO,OAAO,MAAM,EAAE;CAC5B,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,MAAM,MAAM,OAAO,MAAM,EAAE;CAE3B,IAAI,QAAQ,KAAK,QAAQ,MAAM,MAAM,GACnC,OAAO;CAMT,OAAO,QAFL,UAAU,KAAK,WAAW,IAAI,IAAI,KAAM,cAAc,QAAQ,MAAM;AAGxE;;AC9BA,MAAM,oBAAoB;AAc1B,SAAS,SAAS,MAAwB;CACxC,MAAM,UAAU,KAAK,KAAK;CAC1B,IAAI,YAAY,IACd,OAAO,CAAC;CA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