@jibone/todotxt-core 0.2.0 → 0.4.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 +87 -20
- package/dist/index.d.ts +86 -15
- package/dist/index.js +132 -50
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -55,25 +55,62 @@ const todos = createTodoTxt({
|
|
|
55
55
|
|
|
56
56
|
`write` is optional until the write APIs are implemented, so read-only clients
|
|
57
57
|
can omit it. `logger` is optional too and silent when omitted; see
|
|
58
|
-
[Logging](#logging).
|
|
58
|
+
[Logging](#logging). `includeSource` is optional as well; see
|
|
59
|
+
[Source metadata](#source-metadata). The runnable Node version is
|
|
60
|
+
[`examples/node/todo-all.ts`](https://github.com/jibone/todotxt-core/blob/master/examples/node/todo-all.ts).
|
|
59
61
|
|
|
60
62
|
`all()` returns a `TodoRecord` for each non-empty line:
|
|
61
63
|
|
|
62
|
-
| Field | Description
|
|
63
|
-
| ------------- |
|
|
64
|
-
| `completed` | `true` when the line starts with `x `
|
|
65
|
-
| `priority` | Uppercase letter from `(A)`–`(Z)`, or `null`
|
|
66
|
-
| `completedAt` | `YYYY-MM-DD` completion date, or `null`
|
|
67
|
-
| `createdAt` | `YYYY-MM-DD` creation date, or `null`
|
|
68
|
-
| `description` | Task text with projects, contexts, and `key:value` tags removed
|
|
69
|
-
| `projects` | Projects without the `+` prefix
|
|
70
|
-
| `contexts` | Contexts without the `@` prefix
|
|
71
|
-
| `data` | `key:value` metadata (`{ due: "2011-03-05" }`)
|
|
64
|
+
| Field | Description |
|
|
65
|
+
| ------------- | ------------------------------------------------------------------- |
|
|
66
|
+
| `completed` | `true` when the line starts with `x ` |
|
|
67
|
+
| `priority` | Uppercase letter from `(A)`–`(Z)`, or `null` |
|
|
68
|
+
| `completedAt` | `YYYY-MM-DD` completion date that exists on the calendar, or `null` |
|
|
69
|
+
| `createdAt` | `YYYY-MM-DD` creation date that exists on the calendar, or `null` |
|
|
70
|
+
| `description` | Task text with projects, contexts, and `key:value` tags removed |
|
|
71
|
+
| `projects` | Projects without the `+` prefix |
|
|
72
|
+
| `contexts` | Contexts without the `@` prefix |
|
|
73
|
+
| `data` | `key:value` metadata (`{ due: "2011-03-05" }`) |
|
|
74
|
+
| `line` | 1-based physical line number, when `includeSource` is on |
|
|
75
|
+
| `raw` | Exact original line, when `includeSource` is on |
|
|
72
76
|
|
|
73
77
|
If a `key:value` key appears more than once, the last value wins. With a
|
|
74
78
|
[logger](#logging) configured, the parser also emits a `warn` for each duplicate
|
|
75
79
|
key.
|
|
76
80
|
|
|
81
|
+
See [How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md)
|
|
82
|
+
for the complete rule-by-rule interpretation, including date validation and
|
|
83
|
+
deliberate leniencies.
|
|
84
|
+
|
|
85
|
+
### Source metadata
|
|
86
|
+
|
|
87
|
+
By default records stay JSON-lean and the original line is not retained. Pass
|
|
88
|
+
`includeSource` to opt into source metadata: every record then carries `line`,
|
|
89
|
+
the 1-based physical line number (blank lines count), and `raw`, the exact
|
|
90
|
+
original line without a trailing newline or `\r`.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
const todos = createTodoTxt({
|
|
94
|
+
read: () => Bun.file("todo.txt").text(),
|
|
95
|
+
includeSource: true,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
for (const todo of await todos.pending()) {
|
|
99
|
+
console.log(todo.line, todo.raw);
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Source fields survive filters, plucks, and the cache-protecting copies that
|
|
104
|
+
queries return. The same option works for the standalone parser:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
parseDocument(contents, { includeSource: true });
|
|
108
|
+
parseLine("(A) Call Mom", { includeSource: true, line: 7 });
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
`parseLine` only attaches `line` when you supply it via `ParseOptions.line`;
|
|
112
|
+
`parseDocument` numbers lines itself.
|
|
113
|
+
|
|
77
114
|
## Querying
|
|
78
115
|
|
|
79
116
|
Queries are lazy: chaining filters does no IO. The first query on a client reads
|
|
@@ -200,11 +237,13 @@ Currently the client emits:
|
|
|
200
237
|
|
|
201
238
|
- `debug` when a read starts and when it finishes, with `{ records }`.
|
|
202
239
|
- `warn` for each duplicate `key:value` key; the last value still wins.
|
|
240
|
+
- `warn` for each leading date that is not a real calendar date; the value stays
|
|
241
|
+
in the description.
|
|
203
242
|
|
|
204
243
|
Cached queries do not log. Read failures stay promise rejections and are not
|
|
205
244
|
logged as `error`; the other levels are reserved for the write APIs. Logging is
|
|
206
245
|
best-effort: a logger that throws or rejects never breaks a read or query. See
|
|
207
|
-
`
|
|
246
|
+
`examples/todo-logger.ts`.
|
|
208
247
|
|
|
209
248
|
## Parser
|
|
210
249
|
|
|
@@ -217,22 +256,50 @@ const record = parseLine("(A) Call Mom +Family @phone due:2011-03-05");
|
|
|
217
256
|
const records = parseDocument(contents);
|
|
218
257
|
```
|
|
219
258
|
|
|
220
|
-
`parseLine` returns a `TodoRecord` directly.
|
|
221
|
-
|
|
259
|
+
`parseLine` returns a `TodoRecord` directly. Records keep no copy of the
|
|
260
|
+
original line unless [source metadata](#source-metadata) is enabled. Dates must
|
|
261
|
+
be real calendar dates in `YYYY-MM-DD` form; a shape-valid but nonexistent date
|
|
262
|
+
such as `2011-99-99` is treated as text and reported as an `invalid-date`
|
|
263
|
+
warning. Collect warnings by passing `onWarning` in a `ParseOptions` object;
|
|
264
|
+
passing the handler directly as the second argument is deprecated but still
|
|
265
|
+
supported. The full rule-by-rule interpretation is documented in
|
|
266
|
+
[How todotxt-core parses todo.txt](https://github.com/jibone/todotxt-core/blob/master/docs/todo-txt-rules.md).
|
|
222
267
|
|
|
223
268
|
Writing is not implemented yet. The `write` hook is optional for now and will
|
|
224
269
|
become required for the write APIs when they land.
|
|
225
270
|
|
|
226
|
-
##
|
|
271
|
+
## Examples
|
|
272
|
+
|
|
273
|
+
```sh
|
|
274
|
+
bun examples/todo-all.ts
|
|
275
|
+
bun examples/todo-project.ts
|
|
276
|
+
bun examples/todo-context.ts
|
|
277
|
+
bun examples/todo-cross.ts
|
|
278
|
+
bun examples/todo-logger.ts
|
|
279
|
+
bun examples/todo-try.ts
|
|
280
|
+
bun examples/todo-source.ts
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Each format rule also has a runnable example:
|
|
284
|
+
|
|
285
|
+
```sh
|
|
286
|
+
bun examples/rules/rule-1-priority.ts
|
|
287
|
+
bun examples/rules/rule-2-creation-date.ts
|
|
288
|
+
bun examples/rules/rule-3-projects-contexts.ts
|
|
289
|
+
bun examples/rules/rule-4-completed.ts
|
|
290
|
+
bun examples/rules/rule-5-metadata.ts
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Node.js examples show the same API with `node:fs/promises` hooks:
|
|
227
294
|
|
|
228
295
|
```sh
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
bun example/todo-context.ts
|
|
232
|
-
bun example/todo-cross.ts
|
|
233
|
-
bun example/todo-logger.ts
|
|
296
|
+
node examples/node/todo-all.ts
|
|
297
|
+
node examples/node/todo-logger.ts
|
|
234
298
|
```
|
|
235
299
|
|
|
300
|
+
These require Node 22.18+ for native TypeScript type stripping; the library
|
|
301
|
+
itself still runs on Node 20+.
|
|
302
|
+
|
|
236
303
|
## Development
|
|
237
304
|
|
|
238
305
|
```sh
|
package/dist/index.d.ts
CHANGED
|
@@ -20,10 +20,15 @@ type TodoLogger = (level: LogLevel, message: string, meta?: Record<string, unkno
|
|
|
20
20
|
* A non-fatal issue found while parsing.
|
|
21
21
|
*
|
|
22
22
|
* Warnings describe recoverable conditions; the parser still returns a record.
|
|
23
|
+
*
|
|
24
|
+
* - `duplicate-metadata-key`: a `key:value` key appears more than once; the
|
|
25
|
+
* last value wins.
|
|
26
|
+
* - `invalid-date`: a leading `YYYY-MM-DD` value is not a real calendar date.
|
|
27
|
+
* The value is not used as a date and remains part of the description.
|
|
23
28
|
*/
|
|
24
29
|
interface ParseWarning {
|
|
25
30
|
/** Stable identifier for programmatic handling. */
|
|
26
|
-
code: "duplicate-metadata-key";
|
|
31
|
+
code: "duplicate-metadata-key" | "invalid-date";
|
|
27
32
|
/** Human-readable description of the issue. */
|
|
28
33
|
message: string;
|
|
29
34
|
/** 1-based physical line number, when called through {@link parseDocument}. */
|
|
@@ -33,6 +38,20 @@ interface ParseWarning {
|
|
|
33
38
|
}
|
|
34
39
|
/** Receives parse warnings. */
|
|
35
40
|
type ParseWarningHandler = (warning: ParseWarning) => void;
|
|
41
|
+
/**
|
|
42
|
+
* Options for {@link parseLine} and {@link parseDocument}.
|
|
43
|
+
*/
|
|
44
|
+
interface ParseOptions {
|
|
45
|
+
/** Include `line` and `raw` on returned records. Default: `false`. */
|
|
46
|
+
includeSource?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* 1-based line number attached to the record when {@link includeSource} is
|
|
49
|
+
* on. Ignored by {@link parseDocument}, which numbers physical lines itself.
|
|
50
|
+
*/
|
|
51
|
+
line?: number;
|
|
52
|
+
/** Receives parse warnings. */
|
|
53
|
+
onWarning?: ParseWarningHandler;
|
|
54
|
+
}
|
|
36
55
|
/**
|
|
37
56
|
* Callbacks supplied by the consumer.
|
|
38
57
|
*
|
|
@@ -51,21 +70,41 @@ interface TodoHooks {
|
|
|
51
70
|
}
|
|
52
71
|
/** @deprecated Use {@link TodoHooks}. */
|
|
53
72
|
type TodoFileHooks = TodoHooks;
|
|
73
|
+
/**
|
|
74
|
+
* Options for creating a todo.txt client with {@link createTodoTxt}.
|
|
75
|
+
*
|
|
76
|
+
* Extends the file hooks with client behaviour switches.
|
|
77
|
+
*/
|
|
78
|
+
interface TodoClientOptions extends TodoHooks {
|
|
79
|
+
/** Include `line` and `raw` on every record. Default: `false`. */
|
|
80
|
+
includeSource?: boolean;
|
|
81
|
+
}
|
|
54
82
|
/**
|
|
55
83
|
* A single todo.txt line parsed into a JSON-friendly record.
|
|
56
84
|
*
|
|
57
85
|
* This is the only parsed representation. Inline metadata is separated out of
|
|
58
|
-
* {@link TodoRecord.description} into dedicated fields
|
|
59
|
-
*
|
|
86
|
+
* {@link TodoRecord.description} into dedicated fields. The original line is
|
|
87
|
+
* not retained unless the caller opts in with `includeSource`, which adds the
|
|
88
|
+
* {@link TodoRecord.line} and {@link TodoRecord.raw} source fields.
|
|
60
89
|
*/
|
|
61
90
|
interface TodoRecord {
|
|
62
91
|
/** True when the line starts with `x ` (lowercase and followed by a space). */
|
|
63
92
|
completed: boolean;
|
|
64
93
|
/** Uppercase priority letter, e.g. `"A"` for `(A)`, or `null`. */
|
|
65
94
|
priority: string | null;
|
|
66
|
-
/**
|
|
95
|
+
/**
|
|
96
|
+
* Completion date in `YYYY-MM-DD` form, or `null`.
|
|
97
|
+
*
|
|
98
|
+
* The value is always a real calendar date. A shape-valid but nonexistent
|
|
99
|
+
* date (such as `2011-99-99`) is left in the description instead.
|
|
100
|
+
*/
|
|
67
101
|
completedAt: string | null;
|
|
68
|
-
/**
|
|
102
|
+
/**
|
|
103
|
+
* Creation date in `YYYY-MM-DD` form, or `null`.
|
|
104
|
+
*
|
|
105
|
+
* The value is always a real calendar date. A shape-valid but nonexistent
|
|
106
|
+
* date (such as `2011-99-99`) is left in the description instead.
|
|
107
|
+
*/
|
|
69
108
|
createdAt: string | null;
|
|
70
109
|
/** Task text with projects, contexts, and `key:value` metadata removed. */
|
|
71
110
|
description: string;
|
|
@@ -79,6 +118,22 @@ interface TodoRecord {
|
|
|
79
118
|
* If a key appears more than once, the last value wins.
|
|
80
119
|
*/
|
|
81
120
|
data: Record<string, string>;
|
|
121
|
+
/**
|
|
122
|
+
* 1-based physical line number in the source document.
|
|
123
|
+
*
|
|
124
|
+
* Present only when parsing with `includeSource`. For a whole document it
|
|
125
|
+
* counts every physical line, including blank ones. For a single line it is
|
|
126
|
+
* the number supplied via `ParseOptions.line`.
|
|
127
|
+
*/
|
|
128
|
+
line?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Exact original line, without a trailing newline or a trailing `\r`.
|
|
131
|
+
*
|
|
132
|
+
* Present only when parsing with `includeSource`. Leading and trailing
|
|
133
|
+
* whitespace and tag order are preserved, unlike
|
|
134
|
+
* {@link TodoRecord.description}.
|
|
135
|
+
*/
|
|
136
|
+
raw?: string;
|
|
82
137
|
}
|
|
83
138
|
/**
|
|
84
139
|
* A lazy query over parsed todo records.
|
|
@@ -123,10 +178,12 @@ interface TodoTxtClient {
|
|
|
123
178
|
/**
|
|
124
179
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
125
180
|
*
|
|
126
|
-
* The library performs no IO of its own: `
|
|
127
|
-
* producing the file contents and `
|
|
128
|
-
* once they are implemented. `
|
|
129
|
-
* when supplied, it receives read lifecycle and parse warning
|
|
181
|
+
* The library performs no IO of its own: `options.read` is responsible for
|
|
182
|
+
* producing the file contents and `options.write` will be used by the write
|
|
183
|
+
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
184
|
+
* default; when supplied, it receives read lifecycle and parse warning
|
|
185
|
+
* diagnostics. With `options.includeSource`, every record also carries the
|
|
186
|
+
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
130
187
|
*
|
|
131
188
|
* Parsed records are cached in memory per client. The first query loads and
|
|
132
189
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -140,7 +197,7 @@ interface TodoTxtClient {
|
|
|
140
197
|
* Returned records are copies, so callers may mutate them without affecting the
|
|
141
198
|
* cache.
|
|
142
199
|
*/
|
|
143
|
-
export declare function createTodoTxt(
|
|
200
|
+
export declare function createTodoTxt(options: TodoClientOptions): TodoTxtClient;
|
|
144
201
|
/**
|
|
145
202
|
* Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
|
|
146
203
|
*
|
|
@@ -150,19 +207,33 @@ export declare function createTodoTxt(hooks: TodoHooks): TodoTxtClient;
|
|
|
150
207
|
* and then a creation date.
|
|
151
208
|
* - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
|
|
152
209
|
* creation date.
|
|
210
|
+
* - Dates must be real calendar dates in `YYYY-MM-DD` form. A shape-valid but
|
|
211
|
+
* nonexistent date is treated as text.
|
|
153
212
|
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
154
213
|
* remaining text.
|
|
155
214
|
*
|
|
156
|
-
* Recoverable issues are reported to `onWarning` when supplied;
|
|
157
|
-
* produces a record.
|
|
215
|
+
* Recoverable issues are reported to `options.onWarning` when supplied;
|
|
216
|
+
* parsing still produces a record.
|
|
217
|
+
*
|
|
218
|
+
* With `options.includeSource`, the record carries `raw` (the exact input
|
|
219
|
+
* line, minus a trailing `\r`) and `line` (the number supplied via
|
|
220
|
+
* `options.line`, when given).
|
|
158
221
|
*/
|
|
159
|
-
export declare function parseLine(line: string,
|
|
222
|
+
export declare function parseLine(line: string, options?: ParseOptions): TodoRecord;
|
|
223
|
+
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
224
|
+
export declare function parseLine(line: string, onWarning: ParseWarningHandler): TodoRecord;
|
|
160
225
|
/**
|
|
161
226
|
* Parse the contents of a todo.txt file.
|
|
162
227
|
*
|
|
163
228
|
* Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
|
|
164
229
|
* skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
|
|
165
230
|
* annotated with the 1-based physical line number.
|
|
231
|
+
*
|
|
232
|
+
* With `options.includeSource`, every record carries `raw` (the exact line,
|
|
233
|
+
* minus a trailing `\r`) and `line` (the 1-based physical line number,
|
|
234
|
+
* counting blank lines).
|
|
166
235
|
*/
|
|
167
|
-
export declare function parseDocument(contents: string,
|
|
168
|
-
|
|
236
|
+
export declare function parseDocument(contents: string, options?: ParseOptions): TodoRecord[];
|
|
237
|
+
/** @deprecated Pass {@link ParseOptions} with `onWarning` instead. */
|
|
238
|
+
export declare function parseDocument(contents: string, onWarning: ParseWarningHandler): TodoRecord[];
|
|
239
|
+
export type { LogLevel, MaybePromise, ParseOptions, ParseWarning, ParseWarningHandler, TodoClientOptions, TodoFileHooks, TodoHooks, TodoLogger, TodoQuery, TodoRecord, TodoTxtClient };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/clone.ts
|
|
2
2
|
/** Copy a record so callers cannot mutate the client's cached snapshot. */
|
|
3
3
|
function cloneRecord(todo) {
|
|
4
|
-
|
|
4
|
+
const copy = {
|
|
5
5
|
completed: todo.completed,
|
|
6
6
|
priority: todo.priority,
|
|
7
7
|
completedAt: todo.completedAt,
|
|
@@ -11,11 +11,49 @@ function cloneRecord(todo) {
|
|
|
11
11
|
contexts: [...todo.contexts],
|
|
12
12
|
data: { ...todo.data }
|
|
13
13
|
};
|
|
14
|
+
if (todo.line !== void 0) copy.line = todo.line;
|
|
15
|
+
if (todo.raw !== void 0) copy.raw = todo.raw;
|
|
16
|
+
return copy;
|
|
14
17
|
}
|
|
15
18
|
/** Copy every record in `records`. */
|
|
16
19
|
function cloneRecords(records) {
|
|
17
20
|
return records.map(cloneRecord);
|
|
18
21
|
}
|
|
22
|
+
// src/date.ts
|
|
23
|
+
const DATE_SHAPE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
24
|
+
const DAYS_IN_MONTH = [
|
|
25
|
+
31,
|
|
26
|
+
28,
|
|
27
|
+
31,
|
|
28
|
+
30,
|
|
29
|
+
31,
|
|
30
|
+
30,
|
|
31
|
+
31,
|
|
32
|
+
31,
|
|
33
|
+
30,
|
|
34
|
+
31,
|
|
35
|
+
30,
|
|
36
|
+
31
|
|
37
|
+
];
|
|
38
|
+
function isLeapYear(year) {
|
|
39
|
+
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* True when `value` is a real calendar date in `YYYY-MM-DD` form.
|
|
43
|
+
*
|
|
44
|
+
* The check is purely arithmetic so it does not depend on the host timezone and
|
|
45
|
+
* does not let JavaScript's `Date` roll invalid values over (for example,
|
|
46
|
+
* `2011-02-30` must not become March 2).
|
|
47
|
+
*/
|
|
48
|
+
function isValidDate(value) {
|
|
49
|
+
const match = DATE_SHAPE_PATTERN.exec(value);
|
|
50
|
+
if (!match) return false;
|
|
51
|
+
const year = Number(match[1]);
|
|
52
|
+
const month = Number(match[2]);
|
|
53
|
+
const day = Number(match[3]);
|
|
54
|
+
if (month < 1 || month > 12 || day < 1) return false;
|
|
55
|
+
return day <= (month === 2 && isLeapYear(year) ? 29 : DAYS_IN_MONTH[month - 1] ?? 0);
|
|
56
|
+
}
|
|
19
57
|
// src/metadata.ts
|
|
20
58
|
const EXTENSION_PATTERN = /^([^:\s]+):([^:\s]+)$/;
|
|
21
59
|
function tokenize(text) {
|
|
@@ -75,34 +113,58 @@ function parseText(text, onWarning) {
|
|
|
75
113
|
const PRIORITY_PATTERN = /^\(([A-Z])\) /;
|
|
76
114
|
const LEADING_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})(?: |$)/;
|
|
77
115
|
/**
|
|
78
|
-
*
|
|
116
|
+
* Inspect a `YYYY-MM-DD` token at the start of `input`.
|
|
79
117
|
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
118
|
+
* A value with the right shape that does not exist on the calendar is reported
|
|
119
|
+
* as `invalid`. In that case `rest` is the original input, so callers leave the
|
|
120
|
+
* token in the description instead of consuming it.
|
|
82
121
|
*/
|
|
83
122
|
function takeLeadingDate(input) {
|
|
84
123
|
const match = LEADING_DATE_PATTERN.exec(input);
|
|
85
|
-
if (!match) return
|
|
124
|
+
if (!match) return {
|
|
125
|
+
kind: "absent",
|
|
126
|
+
rest: input
|
|
127
|
+
};
|
|
86
128
|
const date = match[1];
|
|
87
|
-
if (date === void 0) return
|
|
88
|
-
|
|
129
|
+
if (date === void 0) return {
|
|
130
|
+
kind: "absent",
|
|
131
|
+
rest: input
|
|
132
|
+
};
|
|
133
|
+
if (!isValidDate(date)) return {
|
|
134
|
+
kind: "invalid",
|
|
135
|
+
value: date,
|
|
136
|
+
rest: input
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
kind: "valid",
|
|
140
|
+
date,
|
|
141
|
+
rest: input.slice(match[0].length)
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
function warnInvalidDate(value, field, onWarning) {
|
|
145
|
+
onWarning?.({
|
|
146
|
+
code: "invalid-date",
|
|
147
|
+
message: `Invalid ${field === "completedAt" ? "completion" : "creation"} date "${value}"; treating it as text.`,
|
|
148
|
+
meta: {
|
|
149
|
+
value,
|
|
150
|
+
field
|
|
151
|
+
}
|
|
152
|
+
});
|
|
89
153
|
}
|
|
90
154
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* The parser follows the todo.txt format rules:
|
|
94
|
-
*
|
|
95
|
-
* - Completed tasks start with `x `, optionally followed by a completion date
|
|
96
|
-
* and then a creation date.
|
|
97
|
-
* - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
|
|
98
|
-
* creation date.
|
|
99
|
-
* - Projects, contexts, and `key:value` metadata may appear anywhere in the
|
|
100
|
-
* remaining text.
|
|
101
|
-
*
|
|
102
|
-
* Recoverable issues are reported to `onWarning` when supplied; parsing still
|
|
103
|
-
* produces a record.
|
|
155
|
+
* Accept either a {@link ParseWarningHandler} (deprecated) or
|
|
156
|
+
* {@link ParseOptions} as the second argument.
|
|
104
157
|
*/
|
|
105
|
-
function
|
|
158
|
+
function normalizeParseOptions(onWarningOrOptions) {
|
|
159
|
+
if (typeof onWarningOrOptions === "function") return { onWarning: onWarningOrOptions };
|
|
160
|
+
return onWarningOrOptions ?? {};
|
|
161
|
+
}
|
|
162
|
+
/** Remove one trailing `\r`, so `raw` has no carriage return for CRLF input. */
|
|
163
|
+
function stripTrailingCarriageReturn(line) {
|
|
164
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
165
|
+
}
|
|
166
|
+
function parseLine(line, onWarningOrOptions) {
|
|
167
|
+
const options = normalizeParseOptions(onWarningOrOptions);
|
|
106
168
|
let rest = line;
|
|
107
169
|
let completed = false;
|
|
108
170
|
let priority = null;
|
|
@@ -111,18 +173,30 @@ function parseLine(line, onWarning) {
|
|
|
111
173
|
if (rest.startsWith("x ")) {
|
|
112
174
|
completed = true;
|
|
113
175
|
rest = rest.slice(2);
|
|
114
|
-
|
|
115
|
-
|
|
176
|
+
const completedDate = takeLeadingDate(rest);
|
|
177
|
+
if (completedDate.kind === "valid") {
|
|
178
|
+
completedAt = completedDate.date;
|
|
179
|
+
rest = completedDate.rest;
|
|
180
|
+
const createdDate = takeLeadingDate(rest);
|
|
181
|
+
if (createdDate.kind === "valid") {
|
|
182
|
+
createdAt = createdDate.date;
|
|
183
|
+
rest = createdDate.rest;
|
|
184
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", options.onWarning);
|
|
185
|
+
} else if (completedDate.kind === "invalid") warnInvalidDate(completedDate.value, "completedAt", options.onWarning);
|
|
116
186
|
} else {
|
|
117
187
|
const priorityMatch = PRIORITY_PATTERN.exec(rest);
|
|
118
188
|
if (priorityMatch) {
|
|
119
189
|
priority = priorityMatch[1];
|
|
120
190
|
rest = rest.slice(priorityMatch[0].length);
|
|
121
191
|
}
|
|
122
|
-
|
|
192
|
+
const createdDate = takeLeadingDate(rest);
|
|
193
|
+
if (createdDate.kind === "valid") {
|
|
194
|
+
createdAt = createdDate.date;
|
|
195
|
+
rest = createdDate.rest;
|
|
196
|
+
} else if (createdDate.kind === "invalid") warnInvalidDate(createdDate.value, "createdAt", options.onWarning);
|
|
123
197
|
}
|
|
124
|
-
const { description, projects, contexts, data } = parseText(rest.trim(), onWarning);
|
|
125
|
-
|
|
198
|
+
const { description, projects, contexts, data } = parseText(rest.trim(), options.onWarning);
|
|
199
|
+
const record = {
|
|
126
200
|
completed,
|
|
127
201
|
priority,
|
|
128
202
|
completedAt,
|
|
@@ -132,23 +206,26 @@ function parseLine(line, onWarning) {
|
|
|
132
206
|
contexts,
|
|
133
207
|
data
|
|
134
208
|
};
|
|
209
|
+
if (options.includeSource) {
|
|
210
|
+
if (options.line !== void 0) record.line = options.line;
|
|
211
|
+
record.raw = stripTrailingCarriageReturn(line);
|
|
212
|
+
}
|
|
213
|
+
return record;
|
|
135
214
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
*
|
|
139
|
-
* Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
|
|
140
|
-
* skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are
|
|
141
|
-
* annotated with the 1-based physical line number.
|
|
142
|
-
*/
|
|
143
|
-
function parseDocument(contents, onWarning) {
|
|
215
|
+
function parseDocument(contents, onWarningOrOptions) {
|
|
216
|
+
const { includeSource, onWarning } = normalizeParseOptions(onWarningOrOptions);
|
|
144
217
|
const records = [];
|
|
145
218
|
let lineNumber = 0;
|
|
146
219
|
for (const line of contents.split(/\r?\n/)) {
|
|
147
220
|
lineNumber += 1;
|
|
148
|
-
if (line.trim() !== "") records.push(parseLine(line,
|
|
149
|
-
|
|
150
|
-
line: lineNumber
|
|
151
|
-
|
|
221
|
+
if (line.trim() !== "") records.push(parseLine(line, {
|
|
222
|
+
includeSource,
|
|
223
|
+
line: lineNumber,
|
|
224
|
+
onWarning: onWarning ? (warning) => onWarning({
|
|
225
|
+
...warning,
|
|
226
|
+
line: lineNumber
|
|
227
|
+
}) : void 0
|
|
228
|
+
}));
|
|
152
229
|
}
|
|
153
230
|
return records;
|
|
154
231
|
}
|
|
@@ -189,10 +266,12 @@ function createTodoQuery(load, filters = []) {
|
|
|
189
266
|
/**
|
|
190
267
|
* Create a todo.txt client backed by consumer-supplied file hooks.
|
|
191
268
|
*
|
|
192
|
-
* The library performs no IO of its own: `
|
|
193
|
-
* producing the file contents and `
|
|
194
|
-
* once they are implemented. `
|
|
195
|
-
* when supplied, it receives read lifecycle and parse warning
|
|
269
|
+
* The library performs no IO of its own: `options.read` is responsible for
|
|
270
|
+
* producing the file contents and `options.write` will be used by the write
|
|
271
|
+
* APIs once they are implemented. `options.logger` is optional and silent by
|
|
272
|
+
* default; when supplied, it receives read lifecycle and parse warning
|
|
273
|
+
* diagnostics. With `options.includeSource`, every record also carries the
|
|
274
|
+
* 1-based `line` number and the exact `raw` line it was parsed from.
|
|
196
275
|
*
|
|
197
276
|
* Parsed records are cached in memory per client. The first query loads and
|
|
198
277
|
* parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
|
|
@@ -206,11 +285,11 @@ function createTodoQuery(load, filters = []) {
|
|
|
206
285
|
* Returned records are copies, so callers may mutate them without affecting the
|
|
207
286
|
* cache.
|
|
208
287
|
*/
|
|
209
|
-
function createTodoTxt(
|
|
288
|
+
function createTodoTxt(options) {
|
|
210
289
|
let cache;
|
|
211
290
|
let inFlight;
|
|
212
291
|
let generation = 0;
|
|
213
|
-
const logger =
|
|
292
|
+
const logger = options.logger;
|
|
214
293
|
const log = (level, message, meta) => {
|
|
215
294
|
if (!logger) return;
|
|
216
295
|
try {
|
|
@@ -221,12 +300,15 @@ function createTodoTxt(hooks) {
|
|
|
221
300
|
const readFresh = async () => {
|
|
222
301
|
const currentGeneration = ++generation;
|
|
223
302
|
log("debug", "Reading todo file");
|
|
224
|
-
const records = parseDocument(await
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
303
|
+
const records = parseDocument(await options.read(), {
|
|
304
|
+
includeSource: options.includeSource,
|
|
305
|
+
onWarning: (warning) => {
|
|
306
|
+
log("warn", warning.message, {
|
|
307
|
+
...warning.meta,
|
|
308
|
+
code: warning.code,
|
|
309
|
+
line: warning.line
|
|
310
|
+
});
|
|
311
|
+
}
|
|
230
312
|
});
|
|
231
313
|
log("debug", "Parsed todo file", { records: records.length });
|
|
232
314
|
if (currentGeneration === generation) cache = records;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/clone.ts","../src/metadata.ts","../src/parse.ts","../src/query.ts","../src/client.ts"],"sourcesContent":["import type { TodoRecord } from \"./types.ts\";\n\n/** Copy a record so callers cannot mutate the client's cached snapshot. */\nexport function cloneRecord(todo: TodoRecord): TodoRecord {\n return {\n completed: todo.completed,\n priority: todo.priority,\n completedAt: todo.completedAt,\n createdAt: todo.createdAt,\n description: todo.description,\n projects: [...todo.projects],\n contexts: [...todo.contexts],\n data: { ...todo.data },\n };\n}\n\n/** Copy every record in `records`. */\nexport function cloneRecords(records: readonly TodoRecord[]): TodoRecord[] {\n return records.map(cloneRecord);\n}\n","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 { parseText } from \"./metadata.ts\";\nimport type { ParseWarningHandler, TodoRecord } from \"./types.ts\";\n\nconst PRIORITY_PATTERN = /^\\(([A-Z])\\) /;\nconst LEADING_DATE_PATTERN = /^(\\d{4}-\\d{2}-\\d{2})(?: |$)/;\n\n/**\n * Consume a `YYYY-MM-DD` date from the start of `input`.\n *\n * Only the shape is validated; the date does not have to exist on a calendar\n * (matching the literal format rules).\n */\nfunction takeLeadingDate(input: string): [date: string | null, rest: string] {\n const match = LEADING_DATE_PATTERN.exec(input);\n if (!match) {\n return [null, input];\n }\n\n const date = match[1];\n if (date === undefined) {\n return [null, input];\n }\n\n return [date, input.slice(match[0]!.length)];\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 * - Projects, contexts, and `key:value` metadata may appear anywhere in the\n * remaining text.\n *\n * Recoverable issues are reported to `onWarning` when supplied; parsing still\n * produces a record.\n */\nexport function parseLine(\n line: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord {\n let rest = line;\n let completed = false;\n let priority: string | null = null;\n let completedAt: string | null = null;\n let createdAt: string | null = null;\n\n if (rest.startsWith(\"x \")) {\n completed = true;\n rest = rest.slice(2);\n [completedAt, rest] = takeLeadingDate(rest);\n [createdAt, rest] = takeLeadingDate(rest);\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 [createdAt, rest] = takeLeadingDate(rest);\n }\n\n const text = rest.trim();\n const { description, projects, contexts, data } = parseText(text, onWarning);\n\n return {\n completed,\n priority,\n completedAt,\n createdAt,\n description,\n projects,\n contexts,\n data,\n };\n}\n\n/**\n * Parse the contents of a todo.txt file.\n *\n * Lines are split on `\\n` or `\\r\\n`; blank and whitespace-only lines are\n * skipped. Every remaining line becomes a {@link TodoRecord}. Warnings are\n * annotated with the 1-based physical line number.\n */\nexport function parseDocument(\n contents: string,\n onWarning?: ParseWarningHandler,\n): TodoRecord[] {\n const records: TodoRecord[] = [];\n let lineNumber = 0;\n\n for (const line of contents.split(/\\r?\\n/)) {\n lineNumber += 1;\n\n if (line.trim() !== \"\") {\n records.push(\n parseLine(\n line,\n onWarning\n ? (warning) => onWarning({ ...warning, line: lineNumber })\n : undefined,\n ),\n );\n }\n }\n\n return records;\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport type { TodoRecord } from \"./types.ts\";\n\n/** A predicate applied to every record in a query. */\nexport type TodoFilter = (todo: TodoRecord) => boolean;\n\n/** Loads and parses every todo.txt record. */\nexport type LoadRecords = () => Promise<TodoRecord[]>;\n\n/**\n * A lazy query over parsed todo records.\n *\n * Filters return a new query and perform no IO. Awaiting a query resolves\n * through the supplied loader; the client caches parsed records, so only the\n * first query reads the file. {@link TodoQuery.projects} and\n * {@link TodoQuery.contexts} are terminal plucks that resolve to unique,\n * alphabetically sorted names.\n */\nexport interface TodoQuery extends PromiseLike<TodoRecord[]> {\n /** Only records that are not completed. */\n pending: () => TodoQuery;\n /** Only records that are completed. */\n completed: () => TodoQuery;\n /** Only records tagged with the project `name`. */\n project: (name: string) => TodoQuery;\n /** Only records tagged with the context `name`. */\n context: (name: string) => TodoQuery;\n /** Unique project names in the current result, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** Unique context names in the current result, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n}\n\nfunction uniqueSorted(values: string[]): string[] {\n return [...new Set(values)].sort();\n}\n\nasync function resolveRaw(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n const records = await load();\n\n if (filters.length === 0) {\n return records;\n }\n\n return records.filter((record) =>\n filters.every((filter) => filter(record)),\n );\n}\n\nasync function resolveRecords(\n load: LoadRecords,\n filters: TodoFilter[],\n): Promise<TodoRecord[]> {\n return cloneRecords(await resolveRaw(load, filters));\n}\n\nfunction pluckNames(\n load: LoadRecords,\n filters: TodoFilter[],\n pick: (todo: TodoRecord) => string[],\n): Promise<string[]> {\n return resolveRaw(load, filters).then((records) =>\n uniqueSorted(records.flatMap(pick)),\n );\n}\n\n/**\n * Create a lazy query over the records loaded by `load`.\n *\n * Each filter method appends a predicate, so chained calls compose. For\n * example, `pending().completed()` matches nothing, while\n * `project(\"Work\").pending()` matches pending records in `Work`.\n */\nexport function createTodoQuery(\n load: LoadRecords,\n filters: TodoFilter[] = [],\n): TodoQuery {\n return {\n pending: () =>\n createTodoQuery(load, [...filters, (todo) => !todo.completed]),\n completed: () =>\n createTodoQuery(load, [...filters, (todo) => todo.completed]),\n project: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.projects.includes(name),\n ]),\n context: (name) =>\n createTodoQuery(load, [\n ...filters,\n (todo) => todo.contexts.includes(name),\n ]),\n projects: () => pluckNames(load, filters, (todo) => todo.projects),\n contexts: () => pluckNames(load, filters, (todo) => todo.contexts),\n then: (onfulfilled, onrejected) =>\n resolveRecords(load, filters).then(onfulfilled, onrejected),\n };\n}\n","import { cloneRecords } from \"./clone.ts\";\nimport { parseDocument } from \"./parse.ts\";\nimport { createTodoQuery } from \"./query.ts\";\nimport type { TodoQuery } from \"./query.ts\";\nimport type { TodoHooks, TodoLogger, TodoRecord } from \"./types.ts\";\n\n/** The read interface returned by {@link createTodoTxt}. */\nexport interface TodoTxtClient {\n /** Read fresh todo.txt contents, replace the cache, and return every record. */\n all: () => Promise<TodoRecord[]>;\n /** Query only records that are not completed, using the cached snapshot. */\n pending: () => TodoQuery;\n /** Query only records that are completed, using the cached snapshot. */\n completed: () => TodoQuery;\n /** Query records tagged with a single project name, using the cache. */\n project: (name: string) => TodoQuery;\n /** Query records tagged with a single context name, using the cache. */\n context: (name: string) => TodoQuery;\n /** List unique project names from the cached snapshot, alphabetically sorted. */\n projects: () => Promise<string[]>;\n /** List unique context names from the cached snapshot, alphabetically sorted. */\n contexts: () => Promise<string[]>;\n}\n\n/**\n * Create a todo.txt client backed by consumer-supplied file hooks.\n *\n * The library performs no IO of its own: `hooks.read` is responsible for\n * producing the file contents and `hooks.write` will be used by the write APIs\n * once they are implemented. `hooks.logger` is optional and silent by default;\n * when supplied, it receives read lifecycle and parse warning diagnostics.\n *\n * Parsed records are cached in memory per client. The first query loads and\n * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}\n * always reads fresh contents and replaces the cache, so it can be used to\n * refresh after the underlying file changes.\n *\n * Every line is parsed into a {@link TodoRecord} when the cache is populated.\n * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}\n * operate on that array of JSON records, and plucks such as\n * {@link TodoQuery.projects} return unique, alphabetically sorted names.\n * Returned records are copies, so callers may mutate them without affecting the\n * cache.\n */\nexport function createTodoTxt(hooks: TodoHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const logger = hooks.logger;\n\n const log: TodoLogger = (level, message, meta) => {\n if (!logger) {\n return;\n }\n\n try {\n const result = logger(level, message, meta);\n\n if (\n result &&\n typeof (result as PromiseLike<unknown>).then === \"function\"\n ) {\n void Promise.resolve(result).catch(() => {});\n }\n } catch {\n // Logging is best-effort and must never break reads or queries.\n }\n };\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n\n log(\"debug\", \"Reading todo file\");\n const contents = await hooks.read();\n const records = parseDocument(contents, (warning) => {\n log(\"warn\", warning.message, {\n ...warning.meta,\n code: warning.code,\n line: warning.line,\n });\n });\n log(\"debug\", \"Parsed todo file\", { records: records.length });\n\n if (currentGeneration === generation) {\n cache = records;\n }\n\n return records;\n };\n\n const refresh = (): Promise<TodoRecord[]> => {\n const promise = readFresh();\n inFlight = promise;\n\n void promise\n .finally(() => {\n if (inFlight === promise) {\n inFlight = undefined;\n }\n })\n .catch(() => {});\n\n return promise;\n };\n\n const loadCached = (): Promise<TodoRecord[]> => {\n if (inFlight) {\n return inFlight;\n }\n\n if (cache) {\n return Promise.resolve(cache);\n }\n\n return refresh();\n };\n\n const all = async (): Promise<TodoRecord[]> =>\n cloneRecords(await refresh());\n\n const query = createTodoQuery(loadCached);\n\n return {\n all,\n pending: query.pending,\n completed: query.completed,\n project: query.project,\n context: query.context,\n projects: query.projects,\n contexts: query.contexts,\n };\n}\n"],"mappings":";;AAGA,SAAgB,YAAY,MAA8B;CACxD,OAAO;EACL,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;AACF;;AAGA,SAAgB,aAAa,SAA8C;CACzE,OAAO,QAAQ,IAAI,WAAW;AAChC;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AI,SAAS,mBAAmB;EAEhC,MAAM,UAAU,cAAc,MADP,MAAM,KAAK,IACO,YAAY;GACnD,IAAI,QAAQ,QAAQ,SAAS;IAC3B,GAAG,QAAQ;IACX,MAAM,QAAQ;IACd,MAAM,QAAQ;GAChB,CAAC;EACH,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 { 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;AACh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