@sdxc/natural-dates 0.0.0-pre.1 → 0.0.0-stage

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 CHANGED
@@ -1,193 +1,3 @@
1
- # @sdxc/natural-dates
1
+ # Temporary Holding Version
2
2
 
3
- Find English date, time, duration and repeat phrases in text, resolved against a clock and a time zone.
4
-
5
- ## Installation
6
-
7
- ```sh
8
- npm add @sdxc/natural-dates
9
- ```
10
-
11
- Results come back as a `Result` from [`@sdxc/result`](https://www.npmjs.com/package/@sdxc/result), which installs alongside.
12
-
13
- ## Usage
14
-
15
- ### Read a date and time from a sentence
16
-
17
- ```typescript
18
- import { find } from "@sdxc/natural-dates";
19
- import { unwrap } from "@sdxc/result";
20
-
21
- let found = unwrap(
22
- find("Lunch with Ana tomorrow 1pm", { now: new Date(), timeZone: "Europe/Lisbon" }),
23
- );
24
-
25
- found.date; // "2026-11-19", tomorrow on a Lisbon calendar
26
- found.start; // "13:00"
27
- ```
28
-
29
- Dates come back as `YYYY-MM-DD` and times as `HH:MM`, on the zone's own calendar. A field is set only when the text says it, so you choose the defaults (today, an hour long).
30
-
31
- ### Take the phrases out of the text
32
-
33
- ```typescript
34
- import { find, strip } from "@sdxc/natural-dates";
35
- import { unwrap } from "@sdxc/result";
36
-
37
- let text = "Dentist on Friday at 8:30am";
38
- let found = unwrap(find(text, { now: new Date(), timeZone: "America/New_York" }));
39
-
40
- strip(text, found.matches); // "Dentist"
41
- ```
42
-
43
- Every match carries its `index` and `end`, so you can also highlight phrases as someone types.
44
-
45
- ### Read ranges, lengths and all-day spans
46
-
47
- ```typescript
48
- let { start, end, duration } = unwrap(find("Review 9:30–11", options)); // "09:30", "11:00", 90
49
- let standup = unwrap(find("Standup at 9:30 for 15 minutes", options)); // end "09:45"
50
- let trip = unwrap(find("Offsite Dec 3-5", options)); // date "2026-12-03", endDate "2026-12-05"
51
- let block = unwrap(find("Planning all day Friday", options)); // allDay true, no times
52
- ```
53
-
54
- ### Read a repeat
55
-
56
- ```typescript
57
- import { find, toRRule } from "@sdxc/natural-dates";
58
-
59
- let { repeat, date } = unwrap(find("Design sync every other Tuesday until March", options));
60
- // repeat: { frequency: "weekly", interval: 2, byDay: [{ day: "tu" }], until: "2027-03-31T23:59:59" }
61
- // date: the first Tuesday on or after today
62
-
63
- toRRule(repeat); // "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU;UNTIL=20270331T235959"
64
- ```
65
-
66
- `repeat` has the shape of a JSCalendar `RecurrenceRule`, so it drops into an event's `recurrenceRules` as is. `toRRule` writes it for iCalendar.
67
-
68
- ## API
69
-
70
- ### `find(text: string, options: FindOptions): Result<Found, NaturalDatesError>`
71
-
72
- Finds every phrase in `text` and adds them up. Text without a date phrase succeeds with no matches. Only an unknown `timeZone` or an invalid `now` fails. Longer phrases are read first and matches never overlap, so "every other Tuesday until March" is one repeat.
73
-
74
- It reads:
75
-
76
- - **Dates:** today, tonight, tomorrow, yesterday, the day after tomorrow; weekdays ("Friday", "this Friday", "next Friday"); month days ("Dec 3", "December 3rd, 2027", "the 5th of January"); `YYYY-MM-DD`; "in 2 weeks", "in a month"; "next week" and "next month"; spans ("Dec 3-5", "Dec 3 to Dec 7").
77
- - **Times:** "1pm", "9:30 am", "13:45", "at 3", noon, midnight, and morning, afternoon or evening.
78
- - **Ranges:** "9:30–11", "9-10am", "11 to 1pm", "from 2 to 4", "between 1 and 2pm".
79
- - **Durations:** "for 45 minutes", "for an hour", "for 1.5 hours", "for 1 hour 30 minutes", "for 3 days".
80
- - **All-day:** "all day", "all-day".
81
- - **Repeats:** daily, weekly, biweekly, monthly, yearly; "every day", "every 3 weeks", "every weekday", "every weekend", "every Tuesday and Thursday", "every other Tuesday"; each with an optional "until <date or month>" or "N times".
82
-
83
- How it resolves them:
84
-
85
- - A weekday names the next one on or after today, and "next Friday" the first one after today.
86
- - A month day without a year is the next one on or after today.
87
- - A bare hour after "at" reads as a working-day hour: 1 to 7 is afternoon, 8 to 11 is morning, and after "tonight" every hour is evening.
88
- - A number range with no meridiem, colon or "from" ("2-3 people") is left alone.
89
-
90
- ### `strip(text: string, matches: Array<{ index: number; end: number }>): string`
91
-
92
- The text without the given ranges. Whitespace collapses, and an "on", "at", "from", "for", "by", colon, comma or dash stranded at either end goes with them.
93
-
94
- ### `toRRule(rule: RepeatRule): string`
95
-
96
- The rule as an iCalendar `RRULE` value, without the `RRULE:` name. `UNTIL` is written as a floating date-time, the end of that day on the event's own clock. Convert it to UTC yourself if the event's `DTSTART` carries a `TZID`.
97
-
98
- ### `NaturalDatesError`
99
-
100
- What `find` fails with. Its `problem` is `"timeZone"` or `"now"`.
101
-
102
- ### Types
103
-
104
- - `FindOptions`: `{ now: Date; timeZone: string }`.
105
- - `Found`: `{ matches, date?, endDate?, start?, end?, duration?, allDay, repeat? }`, with `duration` in minutes.
106
- - `Match`: a `MatchValue` plus `index`, `end` and `text`.
107
- - `MatchValue`, discriminated by `kind`:
108
- - `date` (`date`)
109
- - `dateRange` (`from`, `to`)
110
- - `time` (`time`)
111
- - `timeRange` (`from`, `to`)
112
- - `duration` (`minutes`)
113
- - `allDay`
114
- - `repeat` (`rule`)
115
- - `RepeatRule`: `{ frequency: "daily" | "weekly" | "monthly" | "yearly"; interval?; byDay?: Array<{ day: Weekday }>; until?; count? }`.
116
- - `Weekday`: `"mo" | "tu" | "we" | "th" | "fr" | "sa" | "su"`.
117
-
118
- ## Pattern: A Quick-Add Box That Creates an Event
119
-
120
- Read the line, take the phrases out for the title, and fill the defaults the text left open.
121
-
122
- ```typescript
123
- import { find, strip } from "@sdxc/natural-dates";
124
- import { isFailure } from "@sdxc/result";
125
-
126
- function quickAdd(line: string, timeZone: string, now = new Date()) {
127
- let found = find(line, { now, timeZone });
128
- if (isFailure(found)) return null;
129
- let { date, start, end, allDay, repeat, matches } = found.data;
130
- let title = strip(line, matches) || "New event";
131
- let day = date ?? now.toISOString().slice(0, 10);
132
- if (allDay || start === undefined) return { title, day, allDay: true, repeat };
133
- return { title, day, start, end: end ?? addHour(start), repeat };
134
- }
135
-
136
- function addHour(time: string): string {
137
- let minutes = (Number(time.slice(0, 2)) * 60 + Number(time.slice(3)) + 60) % 1440;
138
- return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
139
- }
140
- ```
141
-
142
- ## Pattern: A JSCalendar Event From a Sentence
143
-
144
- `found.repeat` is already a JSCalendar `RecurrenceRule`, so the event only needs its start and length written out.
145
-
146
- ```typescript
147
- import { find, strip } from "@sdxc/natural-dates";
148
- import { unwrap } from "@sdxc/result";
149
- import { generateUUID } from "@sdxc/uuid/v7";
150
-
151
- let line = "Yoga every Monday and Wednesday at 7am for an hour";
152
- let found = unwrap(find(line, { now: new Date(), timeZone: "America/Chicago" }));
153
-
154
- let event = {
155
- "@type": "Event",
156
- uid: generateUUID(),
157
- title: strip(line, found.matches), // "Yoga"
158
- start: `${found.date}T${found.start}:00`,
159
- timeZone: "America/Chicago",
160
- duration: `PT${found.duration}M`,
161
- recurrenceRules: found.repeat ? [found.repeat] : undefined,
162
- };
163
- ```
164
-
165
- ## Versioning
166
-
167
- Releases are dated rather than semantic. A version is the UTC date it was published,
168
- written `YYYY.M.D`, so `2026.9.4` is the release from 4 September 2026. At most one
169
- release goes out per day.
170
-
171
- Those numbers say when, not what: a later date means a later release and carries no
172
- compatibility promise. Any release may change or remove an export.
173
-
174
- Depend on one exact date, and move it when you are ready to take the change:
175
-
176
- ```json
177
- {
178
- "dependencies": {
179
- "@sdxc/natural-dates": "2026.9.4"
180
- }
181
- }
182
- ```
183
-
184
- A caret or tilde range reads the date as major, minor and patch, so it accepts every
185
- later release in the same year. An exact version keeps the upgrade yours to schedule.
186
-
187
- ## License
188
-
189
- MIT
190
-
191
- ## Author
192
-
193
- [Sergio Xalambrí](https://sergiodxa.com)
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.
package/package.json CHANGED
@@ -1,32 +1,6 @@
1
1
  {
2
- "name": "@sdxc/natural-dates",
3
- "version": "0.0.0-pre.1",
4
- "description": "Find English date, time, duration and repeat phrases in text, resolved against a clock and a time zone",
5
- "license": "MIT",
6
- "type": "module",
7
- "exports": {
8
- ".": "./dist/index.js"
9
- },
10
- "dependencies": {
11
- "@sdxc/dates": "2026.10.25",
12
- "@sdxc/result": "2026.10.13"
13
- },
14
- "gitHead": "c54c505b48e46748d5d8d663304136c26a1987ec",
15
- "publishConfig": {
16
- "access": "public"
17
- },
18
- "repository": {
19
- "type": "git",
20
- "url": "git+https://github.com/sergiodxa/monorepo.git",
21
- "directory": "packages/natural-dates"
22
- },
23
- "homepage": "https://sdxc.dev/api/natural-dates",
24
- "author": {
25
- "name": "Sergio Xalambrí",
26
- "url": "https://sergiodxa.com"
27
- },
28
- "funding": {
29
- "type": "github",
30
- "url": "https://github.com/sponsors/sergiodxa"
31
- }
32
- }
2
+ "name": "@sdxc/natural-dates",
3
+ "version": "0.0.0-stage",
4
+ "stub": true,
5
+ "description": "Temporary package placeholder for staged publishing"
6
+ }
package/LICENSE.md DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Sergio Xalambrí
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.
@@ -1,30 +0,0 @@
1
- /**
2
- * Day arithmetic on `YYYY-MM-DD` strings, read as plain calendar days with no zone, which is what
3
- * every phrase resolves to once "today" is known in the caller's zone. Months clamp to their
4
- * last day, so "in a month" from January 31 lands on the end of February.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /** A `YYYY-MM-DD` day from its parts. */
10
- export declare function dayOf(year: number, month: number, day: number): string;
11
- /** The day a zone's calendar shows at an instant. */
12
- export declare function todayIn(now: Date, timeZone: string): string;
13
- /** A day's year, month and day. */
14
- export declare function partsOf(date: string): {
15
- year: number;
16
- month: number;
17
- day: number;
18
- };
19
- /** A day moved by whole days. */
20
- export declare function addDays(date: string, count: number): string;
21
- /** The days in a month, `month` counted from 1. */
22
- export declare function daysIn(year: number, month: number): number;
23
- /** A day moved by whole months, its day clamped to the target month's last. */
24
- export declare function addMonths(date: string, count: number): string;
25
- /** A day's weekday, `0` for Sunday through `6` for Saturday. */
26
- export declare function weekdayOf(date: string): number;
27
- /** The first day on or after `date` that falls on `weekday`. */
28
- export declare function onOrAfter(date: string, weekday: number): string;
29
- /** Whether a day exists, so "Feb 30" is refused rather than rolled into March. */
30
- export declare function isRealDay(year: number, month: number, day: number): boolean;
package/dist/calendar.js DELETED
@@ -1,56 +0,0 @@
1
- /**
2
- * Day arithmetic on `YYYY-MM-DD` strings, read as plain calendar days with no zone, which is what
3
- * every phrase resolves to once "today" is known in the caller's zone. Months clamp to their
4
- * last day, so "in a month" from January 31 lands on the end of February.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import { calendarDayAt } from "@sdxc/dates/zone";
10
- /** Milliseconds in a day. */
11
- const DAY_MS = 86_400_000;
12
- /** A `YYYY-MM-DD` day from its parts. */
13
- export function dayOf(year, month, day) {
14
- return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
15
- }
16
- /** The day a zone's calendar shows at an instant. */
17
- export function todayIn(now, timeZone) {
18
- let day = calendarDayAt(now.getTime(), timeZone);
19
- return dayOf(day.year, day.month, day.day);
20
- }
21
- /** A day's year, month and day. */
22
- export function partsOf(date) {
23
- return {
24
- year: Number(date.slice(0, 4)),
25
- month: Number(date.slice(5, 7)),
26
- day: Number(date.slice(8, 10)),
27
- };
28
- }
29
- /** A day moved by whole days. */
30
- export function addDays(date, count) {
31
- return new Date(Date.parse(`${date}T00:00:00Z`) + count * DAY_MS).toISOString().slice(0, 10);
32
- }
33
- /** The days in a month, `month` counted from 1. */
34
- export function daysIn(year, month) {
35
- return new Date(Date.UTC(year, month, 0)).getUTCDate();
36
- }
37
- /** A day moved by whole months, its day clamped to the target month's last. */
38
- export function addMonths(date, count) {
39
- let { year, month, day } = partsOf(date);
40
- let index = year * 12 + (month - 1) + count;
41
- let targetYear = Math.floor(index / 12);
42
- let targetMonth = (index % 12) + 1;
43
- return dayOf(targetYear, targetMonth, Math.min(day, daysIn(targetYear, targetMonth)));
44
- }
45
- /** A day's weekday, `0` for Sunday through `6` for Saturday. */
46
- export function weekdayOf(date) {
47
- return new Date(`${date}T00:00:00Z`).getUTCDay();
48
- }
49
- /** The first day on or after `date` that falls on `weekday`. */
50
- export function onOrAfter(date, weekday) {
51
- return addDays(date, (weekday - weekdayOf(date) + 7) % 7);
52
- }
53
- /** Whether a day exists, so "Feb 30" is refused rather than rolled into March. */
54
- export function isRealDay(year, month, day) {
55
- return month >= 1 && month <= 12 && day >= 1 && day <= daysIn(year, month);
56
- }
package/dist/find.d.ts DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * Finds the date, time, duration and repeat phrases in a piece of English text and adds them up
3
- * to what an event would read from them. Longer phrases are matched first and no two matches
4
- * overlap, so "every other Tuesday until March" is one repeat, not a weekday and a month.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import type { Result } from "@sdxc/result";
10
- import type { FindOptions, Found } from "./types.js";
11
- import { NaturalDatesError } from "./natural-dates-error.js";
12
- /**
13
- * Finds every date, time, duration and repeat phrase in `text`, resolved against `now` on the
14
- * calendar of `timeZone`, and what they add up to. Text without any such phrase succeeds with
15
- * no matches; only an unknown zone or an invalid `now` fails.
16
- *
17
- * @param text English text, such as a quick-add line.
18
- * @param options The present and the zone the dates are on.
19
- * @returns The matches and their summary, or why the options could not be read.
20
- * @example find("Lunch with Ana tomorrow 1pm", { now: new Date(), timeZone: "Europe/Lisbon" })
21
- */
22
- export declare function find(text: string, options: FindOptions): Result<Found, NaturalDatesError>;
package/dist/find.js DELETED
@@ -1,351 +0,0 @@
1
- /**
2
- * Finds the date, time, duration and repeat phrases in a piece of English text and adds them up
3
- * to what an event would read from them. Longer phrases are matched first and no two matches
4
- * overlap, so "every other Tuesday until March" is one repeat, not a weekday and a month.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import { isValidTimeZone } from "@sdxc/dates";
10
- import { failure, success } from "@sdxc/result";
11
- import { addDays, todayIn } from "./calendar.js";
12
- import { NaturalDatesError } from "./natural-dates-error.js";
13
- import { CLOCK, DATE_PATTERNS, MONTH_ALONE, NUMBER, WEEKDAY, clock, count, endOfMonthNamed, firstOccurrence, minutesOf, repeatOf, workingHour, } from "./phrases.js";
14
- /** The repeat phrase's core: "every other Tuesday and Thursday", "every 3 weeks", "daily". */
15
- const REPEAT = new RegExp(`\\b(?:(?:every|each)\\s+(other\\s+)?(?:(${NUMBER})\\s+)?(days?|weekdays?|weekends?|weeks?|months?|years?|${WEEKDAY}s?(?:\\s*(?:,\\s*and|,|and|&)\\s*${WEEKDAY}s?)*)|(daily|weekly|biweekly|fortnightly|monthly|yearly|annually))\\b`, "gi");
16
- /** What may follow a repeat: an end date, a month, or a number of times. */
17
- const UNTIL = /\s+(?:until|till|through)\s+/iy;
18
- const TIMES = new RegExp(`\\s+(?:for\\s+)?(${NUMBER})\\s+times\\b`, "iy");
19
- /** "all day", "all-day". */
20
- const ALL_DAY = /\ball[\s-]day\b/gi;
21
- /** A time range: "9:30–11", "1pm to 3pm", "from 2 to 4pm", "between 1 and 2pm". */
22
- const RANGE = new RegExp(`\\b(from\\s+|between\\s+)?${CLOCK}\\s*(?:-|–|—|to|until|till|and)\\s*${CLOCK}(?![\\w:])`, "gi");
23
- /** A duration: "for 45 minutes", "for an hour", "for 1.5 hours", "for 1 hour 30 minutes". */
24
- const DURATION = new RegExp(`\\bfor\\s+(half\\s+an\\s+hour|(${NUMBER}|\\d+\\.\\d+)\\s*(minutes?|mins?|m|hours?|hrs?|hr|h|days?|d)(?:\\s*(?:and\\s+)?(\\d+)\\s*(minutes?|mins?|m))?)\\b`, "gi");
25
- /** A time with am or pm, or on a 24-hour clock with minutes: "1pm", "9:30 am", "13:00". */
26
- const TIME = /\b(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*(a\.?m\.?|p\.?m\.?)(?=\W|$)|\b(?:at\s+)?(\d{1,2}):(\d{2})\b/gi;
27
- /** A bare hour after "at": "at 3", read as a working-day hour. */
28
- const AT_HOUR = /\bat\s+(\d{1,2})\b(?!\s*(?::|am|pm|a\.m|p\.m|%|days?|weeks?))/gi;
29
- /** A named time of day. */
30
- const PART_OF_DAY = /\b(?:at\s+|in\s+the\s+|this\s+)?(noon|midday|midnight|morning|afternoon|evening|eod|end\s+of\s+day)\b/gi;
31
- /** The minute of the day each named time stands for. */
32
- const PARTS_OF_DAY = {
33
- noon: 720,
34
- midday: 720,
35
- midnight: 0,
36
- morning: 540,
37
- afternoon: 840,
38
- evening: 1080,
39
- eod: 1020,
40
- "end of day": 1020,
41
- };
42
- /** What "tonight" starts at when no time is given. */
43
- const TONIGHT = 1200;
44
- /** Reads one date phrase starting exactly at `index`, for the date after "until". */
45
- function dateAt(text, index, today) {
46
- for (let pattern of DATE_PATTERNS) {
47
- let regex = new RegExp(pattern.source, "iy");
48
- regex.lastIndex = index;
49
- let match = regex.exec(text);
50
- if (!match || /\w/.test(text[regex.lastIndex] ?? ""))
51
- continue;
52
- let resolved = pattern.resolve(match, today);
53
- if (resolved)
54
- return { date: resolved.end ?? resolved.start, end: regex.lastIndex };
55
- }
56
- let month = new RegExp(MONTH_ALONE, "iy");
57
- month.lastIndex = index;
58
- let match = month.exec(text);
59
- if (match)
60
- return { date: endOfMonthNamed(today, match[1] ?? "", match[2]), end: month.lastIndex };
61
- return null;
62
- }
63
- /** Repeat phrases, with an "until …" or "N times" tail when one follows. */
64
- function repeats(text, today) {
65
- let found = [];
66
- for (let match of text.matchAll(REPEAT)) {
67
- let word = match[3] ?? match[4] ?? "";
68
- let rule = repeatOf(word, match[1] !== undefined, match[2]);
69
- if (!rule)
70
- continue;
71
- let index = match.index;
72
- let end = index + match[0].length;
73
- UNTIL.lastIndex = end;
74
- if (UNTIL.exec(text)) {
75
- let until = dateAt(text, UNTIL.lastIndex, today);
76
- if (until) {
77
- rule = { ...rule, until: `${until.date}T23:59:59` };
78
- end = until.end;
79
- }
80
- }
81
- TIMES.lastIndex = end;
82
- let times = TIMES.exec(text);
83
- if (times) {
84
- rule = { ...rule, count: count(times[1] ?? "1") };
85
- end = TIMES.lastIndex;
86
- }
87
- found.push({ index, end, value: { kind: "repeat", rule } });
88
- }
89
- return found;
90
- }
91
- /** Date phrases, and spans of two dates joined by "to" or a dash. */
92
- function dates(text, today) {
93
- let found = [];
94
- for (let pattern of DATE_PATTERNS) {
95
- for (let match of text.matchAll(new RegExp(`\\b${pattern.source}\\b`, "gi"))) {
96
- let resolved = pattern.resolve(match, today);
97
- if (!resolved)
98
- continue;
99
- let value = resolved.end
100
- ? { kind: "dateRange", from: resolved.start, to: resolved.end }
101
- : { kind: "date", date: resolved.start };
102
- found.push({ index: match.index, end: match.index + match[0].length, value });
103
- }
104
- }
105
- return found;
106
- }
107
- /** Minutes of a range's two ends, sharing a meridiem written once ("9-10am", "11 to 1pm"). */
108
- function rangeMinutes(match) {
109
- let [, prefix, h1, m1, mer1, h2, m2, mer2] = match;
110
- let hasColon = m1 !== undefined || m2 !== undefined;
111
- if (!mer1 && !mer2 && !hasColon && !prefix)
112
- return null;
113
- let start = Number(h1);
114
- let end = Number(h2);
115
- let startMinute = Number(m1 ?? 0);
116
- let endMinute = Number(m2 ?? 0);
117
- let endValue = minutesOf(end, endMinute, mer2);
118
- if (mer2 && !mer1) {
119
- let same = minutesOf(start, startMinute, mer2);
120
- let other = minutesOf(start, startMinute, mer2.toLowerCase().startsWith("p") ? "am" : "pm");
121
- let startValue = same !== null && endValue !== null && same < endValue ? same : other;
122
- return startValue === null || endValue === null ? null : { start: startValue, end: endValue };
123
- }
124
- if (mer1 && !mer2) {
125
- let startValue = minutesOf(start, startMinute, mer1);
126
- let same = minutesOf(end, endMinute, mer1);
127
- let other = minutesOf(end, endMinute, mer1.toLowerCase().startsWith("p") ? "am" : "pm");
128
- let endPicked = same !== null && startValue !== null && same > startValue ? same : other;
129
- return startValue === null || endPicked === null ? null : { start: startValue, end: endPicked };
130
- }
131
- if (mer1 && mer2) {
132
- let startValue = minutesOf(start, startMinute, mer1);
133
- return startValue === null || endValue === null ? null : { start: startValue, end: endValue };
134
- }
135
- let startHour = hasColon ? start : workingHour(start);
136
- let endHour = hasColon ? end : workingHour(end);
137
- let startValue = minutesOf(startHour, startMinute, undefined);
138
- let finish = minutesOf(endHour, endMinute, undefined);
139
- return startValue === null || finish === null ? null : { start: startValue, end: finish };
140
- }
141
- /** Time ranges. */
142
- function ranges(text) {
143
- let found = [];
144
- for (let match of text.matchAll(RANGE)) {
145
- let minutes = rangeMinutes(match);
146
- if (!minutes)
147
- continue;
148
- found.push({
149
- index: match.index,
150
- end: match.index + match[0].length,
151
- value: { kind: "timeRange", from: clock(minutes.start), to: clock(minutes.end) },
152
- });
153
- }
154
- return found;
155
- }
156
- /** Minutes in one of a duration's units: a day, an hour or a minute. */
157
- function unitMinutes(unit) {
158
- if (unit.startsWith("d"))
159
- return 1440;
160
- if (unit.startsWith("h"))
161
- return 60;
162
- return 1;
163
- }
164
- /** Durations, in minutes. */
165
- function durations(text) {
166
- let found = [];
167
- for (let match of text.matchAll(DURATION)) {
168
- let minutes;
169
- if ((match[1] ?? "").toLowerCase().startsWith("half")) {
170
- minutes = 30;
171
- }
172
- else {
173
- let amount = /\./.test(match[2] ?? "") ? Number(match[2]) : count(match[2] ?? "1");
174
- let unit = (match[3] ?? "m").toLowerCase();
175
- minutes = Math.round(amount * unitMinutes(unit)) + Number(match[4] ?? 0);
176
- }
177
- if (minutes <= 0)
178
- continue;
179
- found.push({
180
- index: match.index,
181
- end: match.index + match[0].length,
182
- value: { kind: "duration", minutes },
183
- });
184
- }
185
- return found;
186
- }
187
- /**
188
- * Single times: clock times, bare hours after "at", and named times of day. A bare hour in a text
189
- * about the evening ("tonight at 9") reads as the evening's.
190
- */
191
- function times(text) {
192
- let evening = /\b(?:tonight|evening)\b/i.test(text);
193
- let found = [];
194
- for (let match of text.matchAll(TIME)) {
195
- let minutes = match[3] === undefined
196
- ? minutesOf(Number(match[4]), Number(match[5]), undefined)
197
- : minutesOf(Number(match[1]), Number(match[2] ?? 0), match[3]);
198
- if (minutes === null)
199
- continue;
200
- found.push({
201
- index: match.index,
202
- end: match.index + match[0].length,
203
- value: { kind: "time", time: clock(minutes) },
204
- });
205
- }
206
- for (let match of text.matchAll(AT_HOUR)) {
207
- let hour = Number(match[1]);
208
- let minutes = minutesOf(evening && hour < 12 ? hour + 12 : workingHour(hour), 0, undefined);
209
- if (minutes === null)
210
- continue;
211
- found.push({
212
- index: match.index,
213
- end: match.index + match[0].length,
214
- value: { kind: "time", time: clock(minutes) },
215
- });
216
- }
217
- for (let match of text.matchAll(PART_OF_DAY)) {
218
- let minutes = PARTS_OF_DAY[(match[1] ?? "").toLowerCase().replace(/\s+/g, " ")];
219
- if (minutes === undefined)
220
- continue;
221
- found.push({
222
- index: match.index,
223
- end: match.index + match[0].length,
224
- value: { kind: "time", time: clock(minutes) },
225
- });
226
- }
227
- return found;
228
- }
229
- /** Keeps the candidates that overlap nothing already kept, in the order given. */
230
- function place(candidates, taken) {
231
- for (let candidate of candidates) {
232
- if (taken.some((kept) => candidate.index < kept.end && kept.index < candidate.end))
233
- continue;
234
- taken.push(candidate);
235
- }
236
- return taken;
237
- }
238
- /** Joins two date matches separated only by "to", "through" or a dash into one span. */
239
- function joinDates(text, matches) {
240
- let joined = [];
241
- for (let match of matches) {
242
- let last = joined.at(-1);
243
- let between = last ? text.slice(last.end, match.index) : "";
244
- if (last?.kind === "date" &&
245
- match.kind === "date" &&
246
- /^\s*(?:-|–|—|to|through|thru|until)\s*$/i.test(between) &&
247
- match.date >= last.date) {
248
- joined[joined.length - 1] = {
249
- kind: "dateRange",
250
- from: last.date,
251
- to: match.date,
252
- index: last.index,
253
- end: match.end,
254
- text: text.slice(last.index, match.end),
255
- };
256
- continue;
257
- }
258
- joined.push(match);
259
- }
260
- return joined;
261
- }
262
- /** Minutes of the day from an `HH:MM` time. */
263
- function minutesFrom(time) {
264
- return Number(time.slice(0, 2)) * 60 + Number(time.slice(3, 5));
265
- }
266
- /** Adds the matches up to an event's date, times, length and repeat. */
267
- function summarize(text, matches, today) {
268
- let found = { matches, allDay: false };
269
- for (let match of matches) {
270
- if (match.kind === "date" && found.date === undefined)
271
- found.date = match.date;
272
- if (match.kind === "dateRange" && found.date === undefined) {
273
- found.date = match.from;
274
- found.endDate = match.to;
275
- }
276
- if (match.kind === "time" && found.start === undefined)
277
- found.start = match.time;
278
- if (match.kind === "timeRange" && found.start === undefined) {
279
- found.start = match.from;
280
- found.end = match.to;
281
- }
282
- if (match.kind === "duration" && found.duration === undefined)
283
- found.duration = match.minutes;
284
- if (match.kind === "allDay")
285
- found.allDay = true;
286
- if (match.kind === "repeat" && found.repeat === undefined)
287
- found.repeat = match.rule;
288
- }
289
- if (found.start === undefined && /\btonight\b/i.test(text))
290
- found.start = clock(TONIGHT);
291
- if (found.start !== undefined && found.end !== undefined && found.duration === undefined) {
292
- let length = minutesFrom(found.end) - minutesFrom(found.start);
293
- found.duration = length > 0 ? length : length + 1440;
294
- }
295
- if (found.start !== undefined &&
296
- found.end === undefined &&
297
- found.duration !== undefined &&
298
- found.duration < 1440) {
299
- found.end = clock(minutesFrom(found.start) + found.duration);
300
- }
301
- if (found.start === undefined && found.duration !== undefined && found.duration >= 1440) {
302
- found.allDay = true;
303
- found.date ??= today;
304
- found.endDate ??= addDays(found.date, Math.ceil(found.duration / 1440) - 1);
305
- }
306
- if (found.allDay) {
307
- delete found.start;
308
- delete found.end;
309
- }
310
- if (found.repeat && found.date === undefined)
311
- found.date = firstOccurrence(today, found.repeat);
312
- return found;
313
- }
314
- /**
315
- * Finds every date, time, duration and repeat phrase in `text`, resolved against `now` on the
316
- * calendar of `timeZone`, and what they add up to. Text without any such phrase succeeds with
317
- * no matches; only an unknown zone or an invalid `now` fails.
318
- *
319
- * @param text English text, such as a quick-add line.
320
- * @param options The present and the zone the dates are on.
321
- * @returns The matches and their summary, or why the options could not be read.
322
- * @example find("Lunch with Ana tomorrow 1pm", { now: new Date(), timeZone: "Europe/Lisbon" })
323
- */
324
- export function find(text, options) {
325
- if (Number.isNaN(options.now.getTime()))
326
- return failure(new NaturalDatesError("now", "`now` is not a valid date."));
327
- if (!isValidTimeZone(options.timeZone))
328
- return failure(new NaturalDatesError("timeZone", `${options.timeZone} is not a time zone this runtime knows.`));
329
- let today = todayIn(options.now, options.timeZone);
330
- let allDay = [...text.matchAll(ALL_DAY)].map((match) => ({
331
- index: match.index,
332
- end: match.index + match[0].length,
333
- value: { kind: "allDay" },
334
- }));
335
- let taken = [];
336
- place(repeats(text, today), taken);
337
- place(allDay, taken);
338
- place(ranges(text), taken);
339
- place(durations(text), taken);
340
- place(dates(text, today), taken);
341
- place(times(text), taken);
342
- let matches = taken
343
- .sort((a, b) => a.index - b.index)
344
- .map((candidate) => ({
345
- ...candidate.value,
346
- index: candidate.index,
347
- end: candidate.end,
348
- text: text.slice(candidate.index, candidate.end),
349
- }));
350
- return success(summarize(text, joinDates(text, matches), today));
351
- }
package/dist/index.d.ts DELETED
@@ -1,13 +0,0 @@
1
- /**
2
- * Public surface of natural-dates: `find` reads the English date, time, duration and repeat
3
- * phrases in a text against a clock and a zone, `strip` takes them back out, and `toRRule` writes
4
- * a found repeat for iCalendar.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- export type { FindOptions, Found, Match, MatchValue, RepeatRule, Weekday } from "./types.js";
10
- export { find } from "./find.js";
11
- export { NaturalDatesError } from "./natural-dates-error.js";
12
- export { toRRule } from "./rrule.js";
13
- export { strip } from "./strip.js";
package/dist/index.js DELETED
@@ -1,12 +0,0 @@
1
- /**
2
- * Public surface of natural-dates: `find` reads the English date, time, duration and repeat
3
- * phrases in a text against a clock and a zone, `strip` takes them back out, and `toRRule` writes
4
- * a found repeat for iCalendar.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- export { find } from "./find.js";
10
- export { NaturalDatesError } from "./natural-dates-error.js";
11
- export { toRRule } from "./rrule.js";
12
- export { strip } from "./strip.js";
@@ -1,18 +0,0 @@
1
- /**
2
- * The failure `find` answers with when it cannot read a text at all, which only its options
3
- * cause: an unknown time zone, or a `now` that is not a valid date. Text without any date phrase
4
- * is not a failure; it finds nothing.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /** Why `find` could not run: which option was wrong. */
10
- export declare class NaturalDatesError extends Error {
11
- readonly problem: "timeZone" | "now";
12
- name: string;
13
- /**
14
- * @param problem The option at fault.
15
- * @param message What was wrong with it.
16
- */
17
- constructor(problem: "timeZone" | "now", message: string);
18
- }
@@ -1,21 +0,0 @@
1
- /**
2
- * The failure `find` answers with when it cannot read a text at all, which only its options
3
- * cause: an unknown time zone, or a `now` that is not a valid date. Text without any date phrase
4
- * is not a failure; it finds nothing.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /** Why `find` could not run: which option was wrong. */
10
- export class NaturalDatesError extends Error {
11
- problem;
12
- name = "NaturalDatesError";
13
- /**
14
- * @param problem The option at fault.
15
- * @param message What was wrong with it.
16
- */
17
- constructor(problem, message) {
18
- super(message);
19
- this.problem = problem;
20
- }
21
- }
package/dist/phrases.d.ts DELETED
@@ -1,61 +0,0 @@
1
- /**
2
- * The English phrases `find` recognizes, each a pattern and the value it resolves to against
3
- * today: dates ("tomorrow", "next Friday", "Dec 3", "in 2 weeks"), times and ranges ("1pm",
4
- * "9:30–11"), durations ("for 45 minutes") and repeats ("every other Tuesday until March").
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import type { RepeatRule, Weekday } from "./types.js";
10
- /** A count, as digits or a word. */
11
- export declare const NUMBER: string;
12
- /** A weekday's name, full or a common short form; "sat" and "sun" need their full names. */
13
- export declare const WEEKDAY = "(?:mon(?:day)?|tue(?:s(?:day)?)?|wed(?:nesday)?|thu(?:r(?:s(?:day)?)?)?|fri(?:day)?|saturday|sunday)";
14
- /** A month's name, full or short. */
15
- export declare const MONTH = "(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)";
16
- /** A clock time: an hour, optional minutes, and an optional am or pm. */
17
- export declare const CLOCK = "(\\d{1,2})(?::(\\d{2}))?\\s*(a\\.?m\\.?|p\\.?m\\.?)?";
18
- /** A count read from digits or a word. */
19
- export declare function count(text: string): number;
20
- /** A weekday name's index, `0` for Sunday. */
21
- export declare function weekdayIndex(name: string): number;
22
- /** A weekday name's JSCalendar code. */
23
- export declare function weekdayCode(name: string): Weekday;
24
- /** A month name's number, `1` for January. */
25
- export declare function monthIndex(name: string): number;
26
- /** An `HH:MM` time from minutes of the day. */
27
- export declare function clock(minutes: number): string;
28
- /**
29
- * Minutes of the day for an hour, minutes and meridiem, or `null` for a time no clock shows.
30
- * Without a meridiem the hour reads on a 24-hour clock.
31
- */
32
- export declare function minutesOf(hour: number, minute: number, meridiem: string | undefined): number | null;
33
- /**
34
- * The hour a bare number after "at" means on a working day: 1 to 7 read as afternoon or
35
- * evening, 8 to 11 as morning, and 12 as noon, the way "lunch at 1" is meant.
36
- */
37
- export declare function workingHour(hour: number): number;
38
- /** A pattern for one kind of date phrase, and what a match of it resolves to. */
39
- interface DatePattern {
40
- /** The regular expression source, without flags. */
41
- source: string;
42
- /** The day or days the match names, against today; `null` when it names no real day. */
43
- resolve(match: RegExpExecArray, today: string): {
44
- start: string;
45
- end?: string;
46
- } | null;
47
- }
48
- /**
49
- * Every date phrase, most specific first, so "next Friday" is read whole before "Friday" and a
50
- * month day range before a single day.
51
- */
52
- export declare const DATE_PATTERNS: DatePattern[];
53
- /** A month named alone, as "until March" ends a repeat with that month's last day. */
54
- export declare const MONTH_ALONE = "((?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?))(?:\\s+(\\d{4}))?";
55
- /** The last day of the next month named on or after today, for "until March". */
56
- export declare function endOfMonthNamed(today: string, name: string, year: string | undefined): string;
57
- /** The repeat a phrase's core names: its frequency, interval and weekdays. */
58
- export declare function repeatOf(word: string, other: boolean, amount: string | undefined): RepeatRule | null;
59
- /** The first day on or after today that a repeat falls on, for "every Tuesday" with no date. */
60
- export declare function firstOccurrence(today: string, rule: RepeatRule): string;
61
- export {};
package/dist/phrases.js DELETED
@@ -1,243 +0,0 @@
1
- /**
2
- * The English phrases `find` recognizes, each a pattern and the value it resolves to against
3
- * today: dates ("tomorrow", "next Friday", "Dec 3", "in 2 weeks"), times and ranges ("1pm",
4
- * "9:30–11"), durations ("for 45 minutes") and repeats ("every other Tuesday until March").
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import { addDays, addMonths, dayOf, daysIn, isRealDay, onOrAfter, partsOf, weekdayOf, } from "./calendar.js";
10
- /** Small numbers written as words, as "in two weeks" and "every three days" use them. */
11
- const NUMBER_WORDS = {
12
- a: 1,
13
- an: 1,
14
- one: 1,
15
- two: 2,
16
- three: 3,
17
- four: 4,
18
- five: 5,
19
- six: 6,
20
- seven: 7,
21
- eight: 8,
22
- nine: 9,
23
- ten: 10,
24
- eleven: 11,
25
- twelve: 12,
26
- };
27
- /** A count, as digits or a word. */
28
- export const NUMBER = `(?:\\d+|${Object.keys(NUMBER_WORDS).join("|")})`;
29
- /** A weekday's name, full or a common short form; "sat" and "sun" need their full names. */
30
- export const WEEKDAY = "(?:mon(?:day)?|tue(?:s(?:day)?)?|wed(?:nesday)?|thu(?:r(?:s(?:day)?)?)?|fri(?:day)?|saturday|sunday)";
31
- /** A month's name, full or short. */
32
- export const MONTH = "(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)";
33
- /** A clock time: an hour, optional minutes, and an optional am or pm. */
34
- export const CLOCK = "(\\d{1,2})(?::(\\d{2}))?\\s*(a\\.?m\\.?|p\\.?m\\.?)?";
35
- /** The weekdays in `Date#getUTCDay` order, as JSCalendar spells them. */
36
- const WEEKDAY_CODES = ["su", "mo", "tu", "we", "th", "fr", "sa"];
37
- /** A count read from digits or a word. */
38
- export function count(text) {
39
- return NUMBER_WORDS[text.toLowerCase()] ?? Number(text);
40
- }
41
- /** A weekday name's index, `0` for Sunday. */
42
- export function weekdayIndex(name) {
43
- return ["sun", "mon", "tue", "wed", "thu", "fri", "sat"].indexOf(name.slice(0, 3).toLowerCase());
44
- }
45
- /** A weekday name's JSCalendar code. */
46
- export function weekdayCode(name) {
47
- return WEEKDAY_CODES[weekdayIndex(name)] ?? "mo";
48
- }
49
- /** A month name's number, `1` for January. */
50
- export function monthIndex(name) {
51
- return (["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].indexOf(name.slice(0, 3).toLowerCase()) + 1);
52
- }
53
- /** An `HH:MM` time from minutes of the day. */
54
- export function clock(minutes) {
55
- let wrapped = ((minutes % 1440) + 1440) % 1440;
56
- return `${String(Math.floor(wrapped / 60)).padStart(2, "0")}:${String(wrapped % 60).padStart(2, "0")}`;
57
- }
58
- /**
59
- * Minutes of the day for an hour, minutes and meridiem, or `null` for a time no clock shows.
60
- * Without a meridiem the hour reads on a 24-hour clock.
61
- */
62
- export function minutesOf(hour, minute, meridiem) {
63
- if (minute > 59)
64
- return null;
65
- let mer = meridiem?.replaceAll(".", "").toLowerCase();
66
- if (mer === "am" || mer === "pm") {
67
- if (hour < 1 || hour > 12)
68
- return null;
69
- let base = hour % 12;
70
- return (mer === "pm" ? base + 12 : base) * 60 + minute;
71
- }
72
- if (hour > 23)
73
- return null;
74
- return hour * 60 + minute;
75
- }
76
- /**
77
- * The hour a bare number after "at" means on a working day: 1 to 7 read as afternoon or
78
- * evening, 8 to 11 as morning, and 12 as noon, the way "lunch at 1" is meant.
79
- */
80
- export function workingHour(hour) {
81
- return hour >= 1 && hour <= 7 ? hour + 12 : hour;
82
- }
83
- /** The first month day on or after today, rolling into next year when it has passed. */
84
- function upcoming(today, month, day) {
85
- let { year } = partsOf(today);
86
- for (let candidate of [year, year + 1]) {
87
- if (!isRealDay(candidate, month, day))
88
- continue;
89
- let date = dayOf(candidate, month, day);
90
- if (date >= today)
91
- return date;
92
- }
93
- return isRealDay(year + 1, month, day) ? dayOf(year + 1, month, day) : null;
94
- }
95
- /** A day with its year written out, or `null` when it does not exist. */
96
- function exact(year, month, day) {
97
- return isRealDay(year, month, day) ? dayOf(year, month, day) : null;
98
- }
99
- /**
100
- * Every date phrase, most specific first, so "next Friday" is read whole before "Friday" and a
101
- * month day range before a single day.
102
- */
103
- export const DATE_PATTERNS = [
104
- {
105
- source: "(\\d{4})-(\\d{2})-(\\d{2})",
106
- resolve(match) {
107
- let [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
108
- return isRealDay(year, month, day) ? { start: dayOf(year, month, day) } : null;
109
- },
110
- },
111
- {
112
- source: `(?:on\\s+)?(${MONTH})\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:\\s*(?:-|–|—|to|through|thru)\\s*(\\d{1,2})(?:st|nd|rd|th)?)?(?:,?\\s+(\\d{4}))?`,
113
- resolve(match, today) {
114
- let month = monthIndex(match[1] ?? "");
115
- let day = Number(match[2]);
116
- let year = match[4] === undefined ? null : Number(match[4]);
117
- let start = year === null ? upcoming(today, month, day) : exact(year, month, day);
118
- if (start === null)
119
- return null;
120
- if (match[3] === undefined)
121
- return { start };
122
- let last = Number(match[3]);
123
- let { year: startYear } = partsOf(start);
124
- if (last < day || !isRealDay(startYear, month, last))
125
- return null;
126
- return { start, end: dayOf(startYear, month, last) };
127
- },
128
- },
129
- {
130
- source: `(?:on\\s+)?(?:the\\s+)?(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?(${MONTH})(?:,?\\s+(\\d{4}))?`,
131
- resolve(match, today) {
132
- let day = Number(match[1]);
133
- let month = monthIndex(match[2] ?? "");
134
- if (match[3] !== undefined) {
135
- let year = Number(match[3]);
136
- return isRealDay(year, month, day) ? { start: dayOf(year, month, day) } : null;
137
- }
138
- let start = upcoming(today, month, day);
139
- return start === null ? null : { start };
140
- },
141
- },
142
- {
143
- source: "(?:on\\s+)?(?:the\\s+)?day\\s+after\\s+tomorrow",
144
- resolve: (_match, today) => ({ start: addDays(today, 2) }),
145
- },
146
- {
147
- source: "(?:on\\s+)?(today|tonight|tomorrow|tmrw|yesterday)",
148
- resolve(match, today) {
149
- let word = (match[1] ?? "").toLowerCase();
150
- if (word === "tomorrow" || word === "tmrw")
151
- return { start: addDays(today, 1) };
152
- if (word === "yesterday")
153
- return { start: addDays(today, -1) };
154
- return { start: today };
155
- },
156
- },
157
- {
158
- source: `in\\s+(${NUMBER})\\s+(days?|weeks?|months?|years?)`,
159
- resolve(match, today) {
160
- let amount = count(match[1] ?? "1");
161
- let unit = (match[2] ?? "day").toLowerCase();
162
- if (unit.startsWith("day"))
163
- return { start: addDays(today, amount) };
164
- if (unit.startsWith("week"))
165
- return { start: addDays(today, amount * 7) };
166
- if (unit.startsWith("month"))
167
- return { start: addMonths(today, amount) };
168
- return { start: addMonths(today, amount * 12) };
169
- },
170
- },
171
- {
172
- source: "next\\s+(week|month|year)",
173
- resolve(match, today) {
174
- let unit = (match[1] ?? "week").toLowerCase();
175
- if (unit === "week")
176
- return { start: onOrAfter(addDays(today, 1), 1) };
177
- let { year, month } = partsOf(today);
178
- if (unit === "month")
179
- return { start: addMonths(dayOf(year, month, 1), 1) };
180
- return { start: dayOf(year + 1, 1, 1) };
181
- },
182
- },
183
- {
184
- source: `(?:on\\s+)?(?:(this|next|coming)\\s+)?(${WEEKDAY})`,
185
- resolve(match, today) {
186
- let weekday = weekdayIndex(match[2] ?? "");
187
- let next = (match[1] ?? "").toLowerCase() === "next";
188
- return { start: onOrAfter(next ? addDays(today, 1) : today, weekday) };
189
- },
190
- },
191
- ];
192
- /** A month named alone, as "until March" ends a repeat with that month's last day. */
193
- export const MONTH_ALONE = `(${MONTH})(?:\\s+(\\d{4}))?`;
194
- /** The last day of the next month named on or after today, for "until March". */
195
- export function endOfMonthNamed(today, name, year) {
196
- let month = monthIndex(name);
197
- let { year: thisYear, month: thisMonth } = partsOf(today);
198
- let target = Number(year ?? (month >= thisMonth ? thisYear : thisYear + 1));
199
- return dayOf(target, month, daysIn(target, month));
200
- }
201
- /** The repeat a phrase's core names: its frequency, interval and weekdays. */
202
- export function repeatOf(word, other, amount) {
203
- let interval = (other ? 2 : 1) * (amount === undefined ? 1 : count(amount));
204
- let lower = word.toLowerCase();
205
- let withInterval = (rule) => interval > 1 ? { ...rule, interval } : rule;
206
- if (lower === "daily" || lower.startsWith("day"))
207
- return withInterval({ frequency: "daily" });
208
- if (lower.startsWith("weekday"))
209
- return withInterval({
210
- frequency: "weekly",
211
- byDay: ["mo", "tu", "we", "th", "fr"].map((day) => ({ day })),
212
- });
213
- if (lower.startsWith("weekend"))
214
- return withInterval({ frequency: "weekly", byDay: [{ day: "sa" }, { day: "su" }] });
215
- if (lower === "weekly" || lower.startsWith("week"))
216
- return withInterval({ frequency: "weekly" });
217
- if (lower === "biweekly" || lower === "fortnightly")
218
- return { frequency: "weekly", interval: 2 };
219
- if (lower === "monthly" || lower.startsWith("month"))
220
- return withInterval({ frequency: "monthly" });
221
- if (lower === "yearly" || lower === "annually" || lower.startsWith("year"))
222
- return withInterval({ frequency: "yearly" });
223
- let days = lower
224
- .split(/\s*(?:,|&|\band\b)\s*/)
225
- .map((part) => part.trim())
226
- .filter((part) => part !== "");
227
- if (days.length === 0 || days.some((day) => weekdayIndex(day) === -1))
228
- return null;
229
- let codes = [...new Set(days.map(weekdayCode))];
230
- return withInterval({ frequency: "weekly", byDay: codes.map((day) => ({ day })) });
231
- }
232
- /** The first day on or after today that a repeat falls on, for "every Tuesday" with no date. */
233
- export function firstOccurrence(today, rule) {
234
- if (!rule.byDay || rule.byDay.length === 0)
235
- return today;
236
- let wanted = new Set(rule.byDay.map((entry) => WEEKDAY_CODES.indexOf(entry.day)));
237
- for (let offset = 0; offset < 7; offset += 1) {
238
- let date = addDays(today, offset);
239
- if (wanted.has(weekdayOf(date)))
240
- return date;
241
- }
242
- return today;
243
- }
package/dist/rrule.d.ts DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * Writes a found repeat as an iCalendar `RRULE` value, for a calendar stored as iCalendar rather
3
- * than JSCalendar. `UNTIL` is written as a floating date-time, the day's end on the event's own
4
- * clock, which RFC 5545 accepts beside a floating `DTSTART`.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import type { RepeatRule } from "./types.js";
10
- /**
11
- * The rule as an `RRULE` value: `FREQ`, then `INTERVAL`, `BYDAY`, `UNTIL` and `COUNT` when set.
12
- *
13
- * @param rule A repeat `find` returned.
14
- * @returns The value, without the `RRULE:` name.
15
- * @example toRRule({ frequency: "weekly", interval: 2, byDay: [{ day: "tu" }] }) // "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU"
16
- */
17
- export declare function toRRule(rule: RepeatRule): string;
package/dist/rrule.js DELETED
@@ -1,27 +0,0 @@
1
- /**
2
- * Writes a found repeat as an iCalendar `RRULE` value, for a calendar stored as iCalendar rather
3
- * than JSCalendar. `UNTIL` is written as a floating date-time, the day's end on the event's own
4
- * clock, which RFC 5545 accepts beside a floating `DTSTART`.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /**
10
- * The rule as an `RRULE` value: `FREQ`, then `INTERVAL`, `BYDAY`, `UNTIL` and `COUNT` when set.
11
- *
12
- * @param rule A repeat `find` returned.
13
- * @returns The value, without the `RRULE:` name.
14
- * @example toRRule({ frequency: "weekly", interval: 2, byDay: [{ day: "tu" }] }) // "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU"
15
- */
16
- export function toRRule(rule) {
17
- let parts = [`FREQ=${rule.frequency.toUpperCase()}`];
18
- if (rule.interval !== undefined && rule.interval > 1)
19
- parts.push(`INTERVAL=${rule.interval}`);
20
- if (rule.byDay && rule.byDay.length > 0)
21
- parts.push(`BYDAY=${rule.byDay.map((entry) => entry.day.toUpperCase()).join(",")}`);
22
- if (rule.until !== undefined)
23
- parts.push(`UNTIL=${rule.until.replaceAll("-", "").replaceAll(":", "")}`);
24
- if (rule.count !== undefined)
25
- parts.push(`COUNT=${rule.count}`);
26
- return parts.join(";");
27
- }
package/dist/strip.d.ts DELETED
@@ -1,18 +0,0 @@
1
- /**
2
- * Removes matched phrases from the text they were found in, so what is left reads as the rest of
3
- * the sentence: a quick-add line's title once its dates are taken out. Spaces left behind collapse,
4
- * and a dangling "on", "at", "from", colon or comma at either end goes with them.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- import type { Match } from "./types.js";
10
- /**
11
- * The text without the given matches.
12
- *
13
- * @param text The text the matches were found in.
14
- * @param matches The matches to remove, such as every one `find` returned.
15
- * @returns The rest of the text, its whitespace collapsed and its edges trimmed.
16
- * @example strip("Lunch with Ana tomorrow 1pm", found.matches) // "Lunch with Ana"
17
- */
18
- export declare function strip(text: string, matches: Array<Pick<Match, "index" | "end">>): string;
package/dist/strip.js DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * Removes matched phrases from the text they were found in, so what is left reads as the rest of
3
- * the sentence: a quick-add line's title once its dates are taken out. Spaces left behind collapse,
4
- * and a dangling "on", "at", "from", colon or comma at either end goes with them.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /** Words that only introduce a removed phrase, left stranded at an edge once it is gone. */
10
- const STRANDED = /^(?:\s*(?:on|at|from|for|by|,|:|-|–|—))+\s*(?=\w)|\s+(?:(?:on|at|from|for|by|,|:|-|–|—)\s*)+$/gi;
11
- /**
12
- * The text without the given matches.
13
- *
14
- * @param text The text the matches were found in.
15
- * @param matches The matches to remove, such as every one `find` returned.
16
- * @returns The rest of the text, its whitespace collapsed and its edges trimmed.
17
- * @example strip("Lunch with Ana tomorrow 1pm", found.matches) // "Lunch with Ana"
18
- */
19
- export function strip(text, matches) {
20
- let rest = "";
21
- let cursor = 0;
22
- for (let match of [...matches].sort((a, b) => a.index - b.index)) {
23
- if (match.index < cursor)
24
- continue;
25
- rest += `${text.slice(cursor, match.index)} `;
26
- cursor = match.end;
27
- }
28
- rest += text.slice(cursor);
29
- return rest
30
- .replace(/\s+/g, " ")
31
- .trim()
32
- .replace(STRANDED, "")
33
- .replace(/\s+([,.;:!?])/g, "$1")
34
- .trim();
35
- }
package/dist/types.d.ts DELETED
@@ -1,88 +0,0 @@
1
- /**
2
- * The shapes `find` answers with: each phrase it matched, where it sits in the text and what it
3
- * means, and the event-shaped summary the matches add up to. Dates are `YYYY-MM-DD` and times
4
- * `HH:MM` on the given zone's clock, so a caller decides how to turn them into instants.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */
9
- /** A weekday as JSCalendar and iCalendar's `BYDAY` spell it, lowercase. */
10
- export type Weekday = "mo" | "tu" | "we" | "th" | "fr" | "sa" | "su";
11
- /**
12
- * A repeat, in the shape of a JSCalendar `RecurrenceRule`, so it can be set as an event's
13
- * `recurrenceRules` entry as is; `toRRule` writes the same rule as an iCalendar `RRULE` value.
14
- */
15
- export interface RepeatRule {
16
- frequency: "daily" | "weekly" | "monthly" | "yearly";
17
- /** Every `interval` periods; absent means every one. */
18
- interval?: number;
19
- /** The weekdays a weekly rule falls on; absent means the start's own weekday. */
20
- byDay?: Array<{
21
- day: Weekday;
22
- }>;
23
- /** The last day a repeat may start, inclusive, as a LocalDateTime at the day's end. */
24
- until?: string;
25
- /** How many occurrences, the first included. */
26
- count?: number;
27
- }
28
- /** What one matched phrase means. */
29
- export type MatchValue = {
30
- kind: "date";
31
- date: string;
32
- } | {
33
- kind: "dateRange";
34
- from: string;
35
- to: string;
36
- } | {
37
- kind: "time";
38
- time: string;
39
- } | {
40
- kind: "timeRange";
41
- from: string;
42
- to: string;
43
- } | {
44
- kind: "duration";
45
- minutes: number;
46
- } | {
47
- kind: "allDay";
48
- } | {
49
- kind: "repeat";
50
- rule: RepeatRule;
51
- };
52
- /** One phrase found in the text: its kind and value, and the half-open range it covers. */
53
- export type Match = MatchValue & {
54
- /** The index of its first character. */
55
- index: number;
56
- /** The index after its last character, so `text.slice(index, end)` is the phrase. */
57
- end: number;
58
- /** The phrase as written. */
59
- text: string;
60
- };
61
- /**
62
- * What the matches add up to, as an event would read them. A field is set only when the text
63
- * says it, so a caller fills its own defaults (today, an hour long) for the rest.
64
- */
65
- export interface Found {
66
- /** Every phrase found, in text order. */
67
- matches: Match[];
68
- /** The first day, `YYYY-MM-DD`; set too when only a repeat names it ("every Tuesday"). */
69
- date?: string;
70
- /** The last day of a span, inclusive, for "Dec 3 to Dec 5" or "for 3 days". */
71
- endDate?: string;
72
- /** The start time, `HH:MM`. */
73
- start?: string;
74
- /** The end time, `HH:MM`, from a range or from a start and a duration. */
75
- end?: string;
76
- /** Minutes long, when a duration or a range gives it. */
77
- duration?: number;
78
- /** Whether the text asks for an all-day event. */
79
- allDay: boolean;
80
- repeat?: RepeatRule;
81
- }
82
- /** What `find` reads the text against. */
83
- export interface FindOptions {
84
- /** The present, which "tomorrow", "next Friday" and "in 2 weeks" count from. */
85
- now: Date;
86
- /** The IANA zone whose calendar the dates are on. */
87
- timeZone: string;
88
- }
package/dist/types.js DELETED
@@ -1,8 +0,0 @@
1
- /**
2
- * The shapes `find` answers with: each phrase it matched, where it sits in the text and what it
3
- * means, and the event-shaped summary the matches add up to. Dates are `YYYY-MM-DD` and times
4
- * `HH:MM` on the given zone's clock, so a caller decides how to turn them into instants.
5
- *
6
- * @author [Sergio Xalambrí](https://sergiodxa.com)
7
- * @copyright Sergio Xalambrí 2026
8
- */