@jibone/todotxt-core 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 J Shamsul Bahri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # todotxt-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A parser for the [todo.txt format](https://github.com/todotxt/todo.txt).
4
+
5
+ Every non-empty line is parsed directly into a JSON-friendly `TodoRecord`. The
6
+ library performs no IO. You provide callbacks for reading and writing the file,
7
+ so it works with Bun, Node, a database, or anything else.
8
+
9
+ > [!WARNING]
10
+ > This library is under active development and is not yet recommended for
11
+ > production use. Its API may change without notice.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @jibone/todotxt-core
17
+ # or
18
+ bun add @jibone/todotxt-core
19
+ ```
20
+
21
+ The package has no runtime dependencies and uses no Node-specific APIs. It runs
22
+ in Node 20+, Bun, Deno, and any other runtime that can provide the read/write
23
+ hooks. Browser support is not officially targeted, but hooks can be backed by
24
+ any storage you like.
25
+
26
+ ## Usage
27
+
28
+ ```ts
29
+ import { createTodoTxt } from "@jibone/todotxt-core";
30
+
31
+ const todos = createTodoTxt({
32
+ read: () => Bun.file("todo.txt").text(),
33
+ write: (contents) => Bun.write("todo.txt", contents),
34
+ });
35
+
36
+ const records = await todos.all();
37
+
38
+ for (const todo of records) {
39
+ console.log(todo.completed, todo.priority, todo.description);
40
+ console.log(todo.projects, todo.contexts, todo.data);
41
+ }
42
+ ```
43
+
44
+ The same client in Node, using `node:fs/promises`:
45
+
46
+ ```ts
47
+ import { readFile, writeFile } from "node:fs/promises";
48
+ import { createTodoTxt } from "@jibone/todotxt-core";
49
+
50
+ const todos = createTodoTxt({
51
+ read: () => readFile("todo.txt", "utf8"),
52
+ write: (contents) => writeFile("todo.txt", contents),
53
+ });
54
+ ```
55
+
56
+ `write` is optional until the write APIs are implemented, so read-only clients
57
+ can omit it.
58
+
59
+ `all()` returns a `TodoRecord` for each non-empty line:
60
+
61
+ | Field | Description |
62
+ | ------------- | --------------------------------------------------------------- |
63
+ | `completed` | `true` when the line starts with `x ` |
64
+ | `priority` | Uppercase letter from `(A)`–`(Z)`, or `null` |
65
+ | `completedAt` | `YYYY-MM-DD` completion date, or `null` |
66
+ | `createdAt` | `YYYY-MM-DD` creation date, or `null` |
67
+ | `description` | Task text with projects, contexts, and `key:value` tags removed |
68
+ | `projects` | Projects without the `+` prefix |
69
+ | `contexts` | Contexts without the `@` prefix |
70
+ | `data` | `key:value` metadata (`{ due: "2011-03-05" }`) |
71
+
72
+ ## Querying
73
+
74
+ Queries are lazy: chaining filters does no IO. The first query on a client reads
75
+ and parses the file once, then later queries reuse that in-memory snapshot.
76
+ Every filter operates on the array of parsed JSON records.
77
+
78
+ ```ts
79
+ await todos.all(); // TodoRecord[] (always reloads)
80
+ await todos.pending(); // TodoRecord[]
81
+ await todos.completed(); // TodoRecord[]
82
+ await todos.project("TodoTxt"); // TodoRecord[]
83
+ await todos.context("phone"); // TodoRecord[]
84
+ ```
85
+
86
+ Filters compose, so they can be combined in any order:
87
+
88
+ ```ts
89
+ await todos.project("TodoTxt").pending();
90
+ await todos.project("TodoTxt").context("computer");
91
+ await todos.pending().project("OpenSource").context("github");
92
+ ```
93
+
94
+ ### Caching and refresh
95
+
96
+ A client caches its parsed records in memory. The first query reads and parses
97
+ the file; later queries reuse the same snapshot, even if they use different
98
+ filters.
99
+
100
+ ```ts
101
+ const projects = await todos.projects(); // reads and caches once
102
+
103
+ for (const project of projects) {
104
+ const done = await todos.project(project).completed(); // cached
105
+ const pending = await todos.project(project).pending(); // cached
106
+ }
107
+ ```
108
+
109
+ `all()` always performs a fresh read and replaces the cache:
110
+
111
+ ```ts
112
+ await todos.pending(); // may load the cache
113
+ await todos.all(); // always reloads
114
+ await todos.pending(); // uses the refreshed cache
115
+ ```
116
+
117
+ There is no TTL or background refresh. If the file changes outside the client,
118
+ call `await todos.all()` before querying again. Returned records are independent
119
+ copies, so mutating them does not affect later queries.
120
+
121
+ ### Projects and contexts
122
+
123
+ `projects()` and `contexts()` are terminal plucks. They return unique names,
124
+ alphabetically sorted.
125
+
126
+ ```ts
127
+ await todos.projects();
128
+ // ["GarageSale", "Garden", "Moving", "OpenSource", "TodoTxt", "TodoTxtTouch"]
129
+
130
+ await todos.contexts();
131
+ // ["archive", "computer", "errands", "github", "hardware", "home", "phone"]
132
+
133
+ // Names from pending or completed records.
134
+ await todos.pending().projects();
135
+ await todos.completed().projects();
136
+ await todos.pending().contexts();
137
+ await todos.completed().contexts();
138
+ ```
139
+
140
+ Plucks can follow any filter chain:
141
+
142
+ ```ts
143
+ // Contexts used by items in a project.
144
+ await todos.project("GarageSale").contexts();
145
+ await todos.project("GarageSale").pending().contexts();
146
+ await todos.project("GarageSale").completed().contexts();
147
+
148
+ // Projects used by items in a context.
149
+ await todos.context("home").projects();
150
+ await todos.context("home").pending().projects();
151
+ await todos.context("home").completed().projects();
152
+ ```
153
+
154
+ Names are matched exactly and case-sensitively. An unknown project or context
155
+ resolves to an empty array.
156
+
157
+ ### Status semantics
158
+
159
+ Filters are applied in sequence:
160
+
161
+ - `pending()` keeps records that are not completed.
162
+ - `completed()` keeps records that are completed.
163
+ - `pending().completed()` therefore resolves to `[]`.
164
+ - `completed().projects()` returns projects that appear on at least one
165
+ completed record. A project with both pending and completed items appears in
166
+ both `pending().projects()` and `completed().projects()`.
167
+
168
+ ## Parser
169
+
170
+ The parser also works without the client wrapper:
171
+
172
+ ```ts
173
+ import { parseDocument, parseLine } from "@jibone/todotxt-core";
174
+
175
+ const record = parseLine("(A) Call Mom +Family @phone due:2011-03-05");
176
+ const records = parseDocument(contents);
177
+ ```
178
+
179
+ `parseLine` returns a `TodoRecord` directly. The original raw line is not
180
+ retained.
181
+
182
+ Writing is not implemented yet. The `write` hook is optional for now and will
183
+ become required for the write APIs when they land.
184
+
185
+ ## Example
186
+
187
+ ```sh
188
+ bun example/todo-all.ts
189
+ bun example/todo-project.ts
190
+ bun example/todo-context.ts
191
+ bun example/todo-cross.ts
192
+ ```
193
+
194
+ ## Development
195
+
196
+ ```sh
197
+ bun install
198
+ bun test
199
+ bunx tsc
200
+ bun run build
201
+ ```
@@ -0,0 +1,130 @@
1
+ /**
2
+ * A value that may or may not be wrapped in a Promise.
3
+ *
4
+ * Hooks use this so consumers can supply either synchronous or asynchronous
5
+ * implementations.
6
+ */
7
+ type MaybePromise<T> = T | Promise<T>;
8
+ /**
9
+ * File access callbacks supplied by the consumer.
10
+ *
11
+ * The library itself never touches the filesystem. `read` is used by
12
+ * {@link createTodoTxt}. `write` is optional until the write APIs land; when
13
+ * they do, callers that mutate todos will need to provide it. The write hook's
14
+ * return value is ignored, so it may return anything (for example
15
+ * `Bun.write`'s `Promise<number>`).
16
+ */
17
+ interface TodoFileHooks {
18
+ read: () => MaybePromise<string>;
19
+ write?: (contents: string) => MaybePromise<unknown>;
20
+ }
21
+ /**
22
+ * A single todo.txt line parsed into a JSON-friendly record.
23
+ *
24
+ * This is the only parsed representation. Inline metadata is separated out of
25
+ * {@link TodoRecord.description} into dedicated fields, and the original raw
26
+ * line is not retained.
27
+ */
28
+ interface TodoRecord {
29
+ /** True when the line starts with `x ` (lowercase and followed by a space). */
30
+ completed: boolean;
31
+ /** Uppercase priority letter, e.g. `"A"` for `(A)`, or `null`. */
32
+ priority: string | null;
33
+ /** Completion date in `YYYY-MM-DD` form, or `null`. */
34
+ completedAt: string | null;
35
+ /** Creation date in `YYYY-MM-DD` form, or `null`. */
36
+ createdAt: string | null;
37
+ /** Task text with projects, contexts, and `key:value` metadata removed. */
38
+ description: string;
39
+ /** Projects found in the text, without the leading `+`. */
40
+ projects: string[];
41
+ /** Contexts found in the text, without the leading `@`. */
42
+ contexts: string[];
43
+ /**
44
+ * Additional `key:value` metadata found in the text.
45
+ *
46
+ * If a key appears more than once, the last value wins.
47
+ */
48
+ data: Record<string, string>;
49
+ }
50
+ /**
51
+ * A lazy query over parsed todo records.
52
+ *
53
+ * Filters return a new query and perform no IO. Awaiting a query resolves
54
+ * through the supplied loader; the client caches parsed records, so only the
55
+ * first query reads the file. {@link TodoQuery.projects} and
56
+ * {@link TodoQuery.contexts} are terminal plucks that resolve to unique,
57
+ * alphabetically sorted names.
58
+ */
59
+ interface TodoQuery extends PromiseLike<TodoRecord[]> {
60
+ /** Only records that are not completed. */
61
+ pending: () => TodoQuery;
62
+ /** Only records that are completed. */
63
+ completed: () => TodoQuery;
64
+ /** Only records tagged with the project `name`. */
65
+ project: (name: string) => TodoQuery;
66
+ /** Only records tagged with the context `name`. */
67
+ context: (name: string) => TodoQuery;
68
+ /** Unique project names in the current result, alphabetically sorted. */
69
+ projects: () => Promise<string[]>;
70
+ /** Unique context names in the current result, alphabetically sorted. */
71
+ contexts: () => Promise<string[]>;
72
+ }
73
+ /** The read interface returned by {@link createTodoTxt}. */
74
+ interface TodoTxtClient {
75
+ /** Read fresh todo.txt contents, replace the cache, and return every record. */
76
+ all: () => Promise<TodoRecord[]>;
77
+ /** Query only records that are not completed, using the cached snapshot. */
78
+ pending: () => TodoQuery;
79
+ /** Query only records that are completed, using the cached snapshot. */
80
+ completed: () => TodoQuery;
81
+ /** Query records tagged with a single project name, using the cache. */
82
+ project: (name: string) => TodoQuery;
83
+ /** Query records tagged with a single context name, using the cache. */
84
+ context: (name: string) => TodoQuery;
85
+ /** List unique project names from the cached snapshot, alphabetically sorted. */
86
+ projects: () => Promise<string[]>;
87
+ /** List unique context names from the cached snapshot, alphabetically sorted. */
88
+ contexts: () => Promise<string[]>;
89
+ }
90
+ /**
91
+ * Create a todo.txt client backed by consumer-supplied file hooks.
92
+ *
93
+ * The library performs no IO of its own: `hooks.read` is responsible for
94
+ * producing the file contents and `hooks.write` will be used by the write APIs
95
+ * once they are implemented.
96
+ *
97
+ * Parsed records are cached in memory per client. The first query loads and
98
+ * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
99
+ * always reads fresh contents and replaces the cache, so it can be used to
100
+ * refresh after the underlying file changes.
101
+ *
102
+ * Every line is parsed into a {@link TodoRecord} when the cache is populated.
103
+ * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
104
+ * operate on that array of JSON records, and plucks such as
105
+ * {@link TodoQuery.projects} return unique, alphabetically sorted names.
106
+ * Returned records are copies, so callers may mutate them without affecting the
107
+ * cache.
108
+ */
109
+ export declare function createTodoTxt(hooks: TodoFileHooks): TodoTxtClient;
110
+ /**
111
+ * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
112
+ *
113
+ * The parser follows the todo.txt format rules:
114
+ *
115
+ * - Completed tasks start with `x `, optionally followed by a completion date
116
+ * and then a creation date.
117
+ * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
118
+ * creation date.
119
+ * - Projects, contexts, and `key:value` metadata may appear anywhere in the
120
+ * remaining text.
121
+ */
122
+ export declare function parseLine(line: string): TodoRecord;
123
+ /**
124
+ * Parse the contents of a todo.txt file.
125
+ *
126
+ * Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
127
+ * skipped. Every remaining line becomes a {@link TodoRecord}.
128
+ */
129
+ export declare function parseDocument(contents: string): TodoRecord[];
130
+ export type { MaybePromise, TodoFileHooks, TodoQuery, TodoRecord, TodoTxtClient };
package/dist/index.js ADDED
@@ -0,0 +1,222 @@
1
+ // src/clone.ts
2
+ /** Copy a record so callers cannot mutate the client's cached snapshot. */
3
+ function cloneRecord(todo) {
4
+ return {
5
+ completed: todo.completed,
6
+ priority: todo.priority,
7
+ completedAt: todo.completedAt,
8
+ createdAt: todo.createdAt,
9
+ description: todo.description,
10
+ projects: [...todo.projects],
11
+ contexts: [...todo.contexts],
12
+ data: { ...todo.data }
13
+ };
14
+ }
15
+ /** Copy every record in `records`. */
16
+ function cloneRecords(records) {
17
+ return records.map(cloneRecord);
18
+ }
19
+ // src/metadata.ts
20
+ const EXTENSION_PATTERN = /^([^:\s]+):([^:\s]+)$/;
21
+ function tokenize(text) {
22
+ const trimmed = text.trim();
23
+ if (trimmed === "") return [];
24
+ return trimmed.split(/\s+/);
25
+ }
26
+ /**
27
+ * Collect a task's description, projects, contexts, and extensions in one pass.
28
+ *
29
+ * Previous versions tokenized the text once for metadata and again to strip it;
30
+ * doing both here keeps parsing to a single split per line.
31
+ */
32
+ function parseText(text) {
33
+ const projects = [];
34
+ const contexts = [];
35
+ const data = {};
36
+ const descriptionTokens = [];
37
+ for (const token of tokenize(text)) {
38
+ if (token.startsWith("+") && token.length > 1) {
39
+ projects.push(token.slice(1));
40
+ continue;
41
+ }
42
+ if (token.startsWith("@") && token.length > 1) {
43
+ contexts.push(token.slice(1));
44
+ continue;
45
+ }
46
+ const extension = EXTENSION_PATTERN.exec(token);
47
+ const key = extension?.[1];
48
+ const value = extension?.[2];
49
+ if (key !== void 0 && value !== void 0) {
50
+ data[key] = value;
51
+ continue;
52
+ }
53
+ descriptionTokens.push(token);
54
+ }
55
+ return {
56
+ description: descriptionTokens.join(" "),
57
+ projects,
58
+ contexts,
59
+ data
60
+ };
61
+ }
62
+ // src/parse.ts
63
+ const PRIORITY_PATTERN = /^\(([A-Z])\) /;
64
+ const LEADING_DATE_PATTERN = /^(\d{4}-\d{2}-\d{2})(?: |$)/;
65
+ /**
66
+ * Consume a `YYYY-MM-DD` date from the start of `input`.
67
+ *
68
+ * Only the shape is validated; the date does not have to exist on a calendar
69
+ * (matching the literal format rules).
70
+ */
71
+ function takeLeadingDate(input) {
72
+ const match = LEADING_DATE_PATTERN.exec(input);
73
+ if (!match) return [null, input];
74
+ const date = match[1];
75
+ if (date === void 0) return [null, input];
76
+ return [date, input.slice(match[0].length)];
77
+ }
78
+ /**
79
+ * Parse a single todo.txt line directly into a JSON-friendly {@link TodoRecord}.
80
+ *
81
+ * The parser follows the todo.txt format rules:
82
+ *
83
+ * - Completed tasks start with `x `, optionally followed by a completion date
84
+ * and then a creation date.
85
+ * - Incomplete tasks may start with an `(A)`–`(Z)` priority and an optional
86
+ * creation date.
87
+ * - Projects, contexts, and `key:value` metadata may appear anywhere in the
88
+ * remaining text.
89
+ */
90
+ function parseLine(line) {
91
+ let rest = line;
92
+ let completed = false;
93
+ let priority = null;
94
+ let completedAt = null;
95
+ let createdAt = null;
96
+ if (rest.startsWith("x ")) {
97
+ completed = true;
98
+ rest = rest.slice(2);
99
+ [completedAt, rest] = takeLeadingDate(rest);
100
+ [createdAt, rest] = takeLeadingDate(rest);
101
+ } else {
102
+ const priorityMatch = PRIORITY_PATTERN.exec(rest);
103
+ if (priorityMatch) {
104
+ priority = priorityMatch[1];
105
+ rest = rest.slice(priorityMatch[0].length);
106
+ }
107
+ [createdAt, rest] = takeLeadingDate(rest);
108
+ }
109
+ const { description, projects, contexts, data } = parseText(rest.trim());
110
+ return {
111
+ completed,
112
+ priority,
113
+ completedAt,
114
+ createdAt,
115
+ description,
116
+ projects,
117
+ contexts,
118
+ data
119
+ };
120
+ }
121
+ /**
122
+ * Parse the contents of a todo.txt file.
123
+ *
124
+ * Lines are split on `\n` or `\r\n`; blank and whitespace-only lines are
125
+ * skipped. Every remaining line becomes a {@link TodoRecord}.
126
+ */
127
+ function parseDocument(contents) {
128
+ const records = [];
129
+ for (const line of contents.split(/\r?\n/)) if (line.trim() !== "") records.push(parseLine(line));
130
+ return records;
131
+ }
132
+ // src/query.ts
133
+ function uniqueSorted(values) {
134
+ return [...new Set(values)].sort();
135
+ }
136
+ async function resolveRaw(load, filters) {
137
+ const records = await load();
138
+ if (filters.length === 0) return records;
139
+ return records.filter((record) => filters.every((filter) => filter(record)));
140
+ }
141
+ async function resolveRecords(load, filters) {
142
+ return cloneRecords(await resolveRaw(load, filters));
143
+ }
144
+ function pluckNames(load, filters, pick) {
145
+ return resolveRaw(load, filters).then((records) => uniqueSorted(records.flatMap(pick)));
146
+ }
147
+ /**
148
+ * Create a lazy query over the records loaded by `load`.
149
+ *
150
+ * Each filter method appends a predicate, so chained calls compose. For
151
+ * example, `pending().completed()` matches nothing, while
152
+ * `project("Work").pending()` matches pending records in `Work`.
153
+ */
154
+ function createTodoQuery(load, filters = []) {
155
+ return {
156
+ pending: () => createTodoQuery(load, [...filters, (todo) => !todo.completed]),
157
+ completed: () => createTodoQuery(load, [...filters, (todo) => todo.completed]),
158
+ project: (name) => createTodoQuery(load, [...filters, (todo) => todo.projects.includes(name)]),
159
+ context: (name) => createTodoQuery(load, [...filters, (todo) => todo.contexts.includes(name)]),
160
+ projects: () => pluckNames(load, filters, (todo) => todo.projects),
161
+ contexts: () => pluckNames(load, filters, (todo) => todo.contexts),
162
+ then: (onfulfilled, onrejected) => resolveRecords(load, filters).then(onfulfilled, onrejected)
163
+ };
164
+ }
165
+ // src/client.ts
166
+ /**
167
+ * Create a todo.txt client backed by consumer-supplied file hooks.
168
+ *
169
+ * The library performs no IO of its own: `hooks.read` is responsible for
170
+ * producing the file contents and `hooks.write` will be used by the write APIs
171
+ * once they are implemented.
172
+ *
173
+ * Parsed records are cached in memory per client. The first query loads and
174
+ * parses the file; later queries reuse that snapshot. {@link TodoTxtClient.all}
175
+ * always reads fresh contents and replaces the cache, so it can be used to
176
+ * refresh after the underlying file changes.
177
+ *
178
+ * Every line is parsed into a {@link TodoRecord} when the cache is populated.
179
+ * Filters such as {@link TodoQuery.pending} and {@link TodoQuery.project}
180
+ * operate on that array of JSON records, and plucks such as
181
+ * {@link TodoQuery.projects} return unique, alphabetically sorted names.
182
+ * Returned records are copies, so callers may mutate them without affecting the
183
+ * cache.
184
+ */
185
+ function createTodoTxt(hooks) {
186
+ let cache;
187
+ let inFlight;
188
+ let generation = 0;
189
+ const readFresh = async () => {
190
+ const currentGeneration = ++generation;
191
+ const records = parseDocument(await hooks.read());
192
+ if (currentGeneration === generation) cache = records;
193
+ return records;
194
+ };
195
+ const refresh = () => {
196
+ const promise = readFresh();
197
+ inFlight = promise;
198
+ promise.finally(() => {
199
+ if (inFlight === promise) inFlight = void 0;
200
+ }).catch(() => {});
201
+ return promise;
202
+ };
203
+ const loadCached = () => {
204
+ if (inFlight) return inFlight;
205
+ if (cache) return Promise.resolve(cache);
206
+ return refresh();
207
+ };
208
+ const all = async () => cloneRecords(await refresh());
209
+ const query = createTodoQuery(loadCached);
210
+ return {
211
+ all,
212
+ pending: query.pending,
213
+ completed: query.completed,
214
+ project: query.project,
215
+ context: query.context,
216
+ projects: query.projects,
217
+ contexts: query.contexts
218
+ };
219
+ }
220
+ export { createTodoTxt, parseDocument, parseLine };
221
+
222
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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","const 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 */\nexport function parseText(text: string): 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 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 { 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 */\nexport function parseLine(line: string): 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);\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}.\n */\nexport function parseDocument(contents: string): TodoRecord[] {\n const records: TodoRecord[] = [];\n\n for (const line of contents.split(/\\r?\\n/)) {\n if (line.trim() !== \"\") {\n records.push(parseLine(line));\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 { TodoFileHooks, 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.\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: TodoFileHooks): TodoTxtClient {\n let cache: TodoRecord[] | undefined;\n let inFlight: Promise<TodoRecord[]> | undefined;\n let generation = 0;\n\n const readFresh = async (): Promise<TodoRecord[]> => {\n const currentGeneration = ++generation;\n const records = parseDocument(await hooks.read());\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,W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,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"}
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@jibone/todotxt-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Parse and query todo.txt files with runtime-agnostic file hooks.",
5
+ "license": "MIT",
6
+ "author": "J Shamsul Bahri",
7
+ "homepage": "https://github.com/jibone/todotxt-core#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/jibone/todotxt-core.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/jibone/todotxt-core/issues"
14
+ },
15
+ "keywords": [
16
+ "todo.txt",
17
+ "todotxt",
18
+ "todo",
19
+ "parser",
20
+ "typescript"
21
+ ],
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "main": "./dist/index.js",
36
+ "module": "./dist/index.js",
37
+ "types": "./dist/index.d.ts",
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "bun test",
48
+ "prepack": "bun run build",
49
+ "prepublishOnly": "bun test && bunx tsc"
50
+ },
51
+ "devDependencies": {
52
+ "@types/bun": "latest",
53
+ "tsdown": "^0.23.7",
54
+ "typescript": "^7"
55
+ }
56
+ }