bizdays-toolkit 0.32.6 → 0.32.8

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/CHANGELOG.md CHANGED
@@ -6,6 +6,26 @@ Entries from 0.31.0 are in English. Earlier entries remain in Japanese (their **
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.32.8] - 2026-11-23
10
+
11
+ ### Fixed
12
+
13
+ - The option diagnostics of a calendar could report a rule as `never-matches` or `redundant` although removing it changed the results, breaking the promise that the reported rules can be removed all together (design decisions 31). This happened in calendar options with an nth-business-day rule that counts the calendar's own business days (`businessDayOfMonth` or `businessDayOfWeek` in `closedRecurringRules` or `openRecurringRules`) and specific dates (`closedDates`, `openDates`), because a specific date changes the count in its month and week: when a date lies outside the years the diagnostics scan (2001–2028 without a holiday provider, so any date from 2029 on or before 2001), or when a long date range covers those years (for example `{ from: "1000-01-01", to: "2029-03-31" }` before opening). The diagnostics now check the scanned years without the specific dates and, in addition, the month and the six days around it at both ends of every specific date, also outside the scanned years. Most such options get fewer items; in some, the incorrect item is replaced by a correct one (a rule that matches only days decided by a specific date is reported as `redundant` instead of `never-matches`, a duplicate rule as `shadowed` instead of `never-matches`, or another rule as `redundant`). In such options, a rule that is used only on days inside a long specific date range is no longer reported as unused, as in options without such an nth-business-day rule. Options with many specific dates outside the scanned years take longer to diagnose (on the maintainer's machine, about two to four times as long as 0.32.7 with 1,000 such dates)
14
+ - For the same reason, `no-business-day` could be reported for such options although they have business days (a closed date moves the nth business day of its month to a day that the rules alone close)
15
+ - With `unconfirmedHolidayPolicy: "throw"`, the diagnostics of calendars and schedules could report a rule as `redundant` although removing it made a day throw `unconfirmed-holiday` (the remaining rules, such as the origin of an `"after-holiday"` rule, then look up an unconfirmed holiday on that day). Such a rule is no longer reported
16
+ - `counting-basis` was reported for a weekly weekday rule that does not change how its weekday is counted: a closed rule on a weekday in `closedWeekdays`, or an open rule on a weekday not in it. The count already treats that weekday the same way
17
+ - Documentation: the guide and the design decisions (31) now say that `relatedPath` of `redundant` is found with all reported rules removed, that with `outOfRangePolicy: "throw"` the rules reported as `out-of-range` with "so this rule is never used" are removed together with the others, and that the promise covers the days that can be judged before the removal (a day that already throws can be judged after it). The design decisions (30) now describe the range checked for `no-business-day`. Results are unchanged
18
+ - None of these fixes changes the results of calendars and schedules. If you removed rules because an earlier version reported them as `redundant` or `never-matches`, check that the results you rely on have not changed. A test that compares the whole diagnostics of the options above (such as `assert.deepEqual`) needs the new items
19
+
20
+ ## [0.32.7] - 2026-11-21
21
+
22
+ ### Changed
23
+
24
+ - The option diagnostics of a schedule are faster when a business-day rule counts on a calendar with a holiday provider and the scan reaches years outside the provider's supported years (for example, a schedule without a provider counting on the Japanese holiday calendar). A month in which that calendar throws is now evaluated once per rule in a diagnosis, instead of every time the scan looks at it. On the maintainer's machine, such a schedule is diagnosed in about 40% of the time of 0.32.6. Results, exceptions and diagnostics are unchanged
25
+ - Judging days and the option diagnostics are faster: a date that was just converted to a day number (or built from one) is not parsed again, and the rules for the nth business day of a week, the days before and after holidays (`dayBeforeHoliday`, `dayAfterHoliday`) and holiday shifts (`holidayOverlapPolicy: "after-holiday"`) step through day numbers instead of building date strings. On the maintainer's machine, calling `isBusinessDay` or `valueOn` for the days of 2020–2029 in random order takes about 85–100% of the time of 0.32.6 depending on the settings (about 85–90% for a calendar with a holiday-shift rule and for `valueOn`; for a store calendar without such rules the difference was sometimes not measurable; measured alternately with 0.32.6 in one process), and, together with the change above, diagnosing a schedule counted on the Japanese holiday calendar takes about 30% of the time of 0.32.6. Results, exceptions and diagnostics are unchanged
26
+ - Creating a calendar or a schedule, and `toDateString`, are faster when the time zone is a name the runtime returned (for example the time zone of a holiday provider): the name is no longer normalized again on every call. On the maintainer's machine, `createCalendar({ holidayProvider: jp, closedWeekdays: [0] })` takes about 80–85% of the time of 0.32.6. Results are unchanged
27
+ - Judging days of a calendar or a schedule with many individual dates (`closedDates`, `openDates`, `dates`) is faster when no two of them overlap: the dates are looked up by binary search in start order, instead of being checked one by one for every day. Dates already written in start order are used as they are; otherwise they are sorted once the number of judgments reaches about twice the base-2 logarithm of the number of dates (for example, 18 judgments for 500 dates), so creating a calendar and judging only a few days does not pay for sorting. When some dates overlap, they are still checked in the order written, so the entry written first still decides. On the maintainer's machine (measured alternately with 0.32.6 in one process), `diffBusinessDays` over one year for a calendar with 500 closed dates takes about 30% of the time of 0.32.6, diagnosing a schedule counted on a calendar with 300 closed dates about 35%, and creating a calendar with 100–2,000 closed dates in mixed order and judging one day about the same time (100–106%). When the dates are not written in start order, creating a calendar and judging a few dozen days, around the point where the dates get sorted, can take up to about 20% longer than 0.32.6 (for example, about 25 days for 2,000 dates, or about 8 days for 10 dates); judging fewer days takes about the same time, and judging more days is faster. Results, exceptions and diagnostics are unchanged
28
+
9
29
  ## [0.32.6] - 2026-11-20
10
30
 
11
31
  ### Fixed
@@ -1044,7 +1064,9 @@ This version rebuilds the `redundant` diagnostic so that the reported rules can
1044
1064
 
1045
1065
  - 日本: 2026 年 2 月の官報(2027 年の春分・秋分の日)まで反映(`dataVersion: "2026-02"`、`confirmedThrough: 2027`)
1046
1066
 
1047
- [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.6...HEAD
1067
+ [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.8...HEAD
1068
+ [0.32.8]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.7...v0.32.8
1069
+ [0.32.7]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.6...v0.32.7
1048
1070
  [0.32.6]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.5...v0.32.6
1049
1071
  [0.32.5]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.4...v0.32.5
1050
1072
  [0.32.4]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.3...v0.32.4
package/README.md CHANGED
@@ -23,7 +23,7 @@ A business-day calendar that combines public holidays with company or store clos
23
23
  - **Recurring rules**: "closed on the 3rd Wednesday", "every other Wednesday", "stocktaking on the last day of the month", "closed on Mondays, moved to the next non-holiday when Monday is a holiday", "the day after (or before) a holiday", "the last weekday before a bank holiday", shift cycles such as four days on and two days off, each with its own behaviour on holidays and an optional effective period
24
24
  - **Day-by-day values and combined calendars**: store hours that change by weekday, holiday and date; a business-day calendar made from such a schedule; and the days on which all (or any) of several calendars are open
25
25
  - **Option diagnostics**: `bizdays-toolkit/diagnose` lists rules that never apply, rules that are shadowed or redundant, rules that have ended, typos in option names and options with no business day at all, without throwing. One line in a test keeps options honest
26
- - **Lightweight, zero dependencies, time-zone safe**: about 14.5 KB min+gzip (about 16.3 KB with Japanese holidays, about 16.7 KB with UK bank holidays, about 15.4 KB with French holidays, about 15.5 KB with Singapore holidays; measured for 0.32.0). Standard JavaScript and `Intl` only, ESM with bundled types; tested on Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno (on Safari without Temporal, aliases of one time zone such as `"UTC"` and `"Etc/UTC"` are a `time-zone-conflict`: write the same spelling). Instants such as `Date` are converted to a civil date in the calendar's time zone before evaluation
26
+ - **Lightweight, zero dependencies, time-zone safe**: about 15.2 KB min+gzip (about 16.9 KB with Japanese holidays, about 17.4 KB with UK bank holidays, about 16.1 KB with French holidays, about 16.1 KB with Singapore holidays; measured for 0.32.8). Standard JavaScript and `Intl` only, ESM with bundled types; tested on Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno (on Safari without Temporal, aliases of one time zone such as `"UTC"` and `"Etc/UTC"` are a `time-zone-conflict`: write the same spelling). Instants such as `Date` are converted to a civil date in the calendar's time zone before evaluation
27
27
  - **Extensible to other countries and regions**: holiday providers are pluggable through the `HolidayProvider` interface, and `bizdays-toolkit/provider` exposes the calendar arithmetic (nth weekday of a month, Easter, substitute days for holidays on a weekend) that most countries' holidays are built from
28
28
 
29
29
  ## Installation
@@ -1,10 +1,10 @@
1
- import { addDays, lengthOfMonth, formatDate, fromDayNumber, toDayNumber, } from "./date.js";
1
+ import { addDays, lengthOfMonth, formatDate } from "./date.js";
2
2
  import { checkUnknownKeys, internalError, IssueCollector, describeValue, rangeError, withoutUndefined, } from "./errors.js";
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { renameKeys, writtenKey } from "./renamed.js";
5
5
  import { distinctTimeZones, parseTimeOfDaySeconds, toCivil } from "./input.js";
6
6
  import { checkClosingDay, closingDayIn, closingMonth as calendarClosingMonth, dayOfMonth, formatMonth, isDayOfMonthValue, parseMonth, readsAsDate, shiftMonth, } from "./month.js";
7
- import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, PARTS, partsHolder, partsOf, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, } from "./schedule.js";
7
+ import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, PARTS, partsHolder, partsOf, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, dateOfDayNumber, dayNumberOf, } from "./schedule.js";
8
8
  export const CALENDAR_OPTION_KEYS = [
9
9
  "holidayProvider",
10
10
  "timeZone",
@@ -128,9 +128,9 @@ function dayInfoFromScheduleDay(day, open, fromSchedule) {
128
128
  function buildCalendar(lookup, isOpen, info, searchDayLimit) {
129
129
  const dateOf = lookup.dateOf;
130
130
  function search(start, step, open = true) {
131
- let n = toDayNumber(start);
131
+ let n = dayNumberOf(start);
132
132
  for (let i = 0; i < searchDayLimit; i++, n += step) {
133
- const date = fromDayNumber(n);
133
+ const date = dateOfDayNumber(n);
134
134
  if (isOpen(date) === open)
135
135
  return date;
136
136
  }
@@ -144,7 +144,7 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
144
144
  function countOpen(from, toExclusive) {
145
145
  let count = 0;
146
146
  for (let n = from; n < toExclusive; n++)
147
- if (isOpen(fromDayNumber(n)))
147
+ if (isOpen(dateOfDayNumber(n)))
148
148
  count++;
149
149
  return count;
150
150
  }
@@ -189,13 +189,13 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
189
189
  }
190
190
  function searchInMonth(start, step, limited) {
191
191
  const { year, month } = parseMonth(start.slice(0, 7));
192
- const first = toDayNumber(formatDate(year, month, 1));
192
+ const first = dayNumberOf(formatDate(year, month, 1));
193
193
  const last = first + lengthOfMonth(year, month) - 1;
194
- let n = toDayNumber(start);
194
+ let n = dayNumberOf(start);
195
195
  for (let i = 0; n >= first && n <= last; i++, n += step) {
196
196
  if (limited && i >= searchDayLimit)
197
197
  throw noBusinessDay(start);
198
- const date = fromDayNumber(n);
198
+ const date = dateOfDayNumber(n);
199
199
  if (isOpen(date))
200
200
  return date;
201
201
  }
@@ -276,8 +276,8 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
276
276
  return date;
277
277
  },
278
278
  diffBusinessDays(from, to) {
279
- const a = toDayNumber(dateOf(from));
280
- const b = toDayNumber(dateOf(to));
279
+ const a = dayNumberOf(dateOf(from));
280
+ const b = dayNumberOf(dateOf(to));
281
281
  return a <= b ? countOpen(a, b) : 0 - countOpen(b, a);
282
282
  },
283
283
  businessDatesBetween(from, to) {
@@ -286,8 +286,8 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
286
286
  if (a > b)
287
287
  throw rangeError("invalid-range", `"from" must not be after "to" (${a} > ${b})`);
288
288
  const result = [];
289
- for (let n = toDayNumber(a); n <= toDayNumber(b); n++) {
290
- const date = fromDayNumber(n);
289
+ for (let n = dayNumberOf(a); n <= dayNumberOf(b); n++) {
290
+ const date = dateOfDayNumber(n);
291
291
  if (isOpen(date))
292
292
  result.push(date);
293
293
  }
@@ -1,9 +1,9 @@
1
- import { formatDate, lengthOfMonth, fromDayNumber, isValidDate, parseDate, toDayNumber, weekdayOf, } from "./date.js";
1
+ import { formatDate, lengthOfMonth, isValidDate, parseDate, weekdayOf, } from "./date.js";
2
2
  import { compileCalendarOptions } from "./calendar.js";
3
3
  import { internalError, InternalError, describeValue, IssueCollector, rangeError, } from "./errors.js";
4
4
  import { isOptionsObject } from "./options.js";
5
5
  import { RENAMED_KEYS, RENAMED_VALUES } from "./renamed.js";
6
- import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, lostShiftMessage, throwLostShift, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, partsOf, isHolidayBasedRule, resultIgnoresHolidays, } from "./schedule.js";
6
+ import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, lostShiftMessage, throwLostShift, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, partsOf, isHolidayBasedRule, resultIgnoresHolidays, dateOfDayNumber, dayNumberOf, } from "./schedule.js";
7
7
  function editDistance(a, b) {
8
8
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
9
9
  for (let i = 1; i <= a.length; i++) {
@@ -45,10 +45,10 @@ function closestOf(key, known) {
45
45
  }
46
46
  return best;
47
47
  }
48
- const PATTERN_FROM = toDayNumber("2001-01-01");
49
- const PATTERN_DAYS = toDayNumber("2028-12-31") - PATTERN_FROM + 1;
50
- const MIN_DAY = toDayNumber("1000-01-01");
51
- const MAX_DAY = toDayNumber("9999-12-31");
48
+ const PATTERN_FROM = dayNumberOf("2001-01-01");
49
+ const PATTERN_DAYS = dayNumberOf("2028-12-31") - PATTERN_FROM + 1;
50
+ const MIN_DAY = dayNumberOf("1000-01-01");
51
+ const MAX_DAY = dayNumberOf("9999-12-31");
52
52
  const MAX_WINDOW_YEARS = 200;
53
53
  const MAX_DATE_RULE_DAYS = 366 * MAX_WINDOW_YEARS;
54
54
  const isLostShift = (error) => error?.code === "holiday-run-too-long";
@@ -64,17 +64,18 @@ const atEdge = (n, error, window) => {
64
64
  const last = window.ranges[window.ranges.length - 1].to;
65
65
  return n < first + PROVIDER_EDGE_DAYS || n > last - PROVIDER_EDGE_DAYS;
66
66
  };
67
- function openEndedDays(from, days) {
67
+ function crossesShortCentury(from, to) {
68
68
  const lo = Math.max(from, MIN_DAY);
69
- const hi = Math.min(from + days - 1, MAX_DAY);
69
+ const hi = Math.min(to, MAX_DAY);
70
70
  if (lo > hi)
71
- return days;
71
+ return false;
72
72
  const last = yearOf(hi);
73
73
  for (let y = Math.ceil(yearOf(lo) / 100) * 100; y <= last; y += 100)
74
74
  if (y % 400 !== 0)
75
- return Math.max(days, 2 * PATTERN_DAYS);
76
- return days;
75
+ return true;
76
+ return false;
77
77
  }
78
+ const openEndedDays = (from, days) => crossesShortCentury(from, from + days - 1) ? Math.max(days, 2 * PATTERN_DAYS) : days;
78
79
  function periodSpan(rule, cycle) {
79
80
  const { effectiveFrom, effectiveTo } = rule;
80
81
  if (effectiveFrom === null) {
@@ -107,7 +108,7 @@ function clipYears(from, to) {
107
108
  const b = Math.min(to, 2099);
108
109
  return a <= b ? [a, b] : [from, from + MAX_WINDOW_YEARS - 1];
109
110
  }
110
- const dayOfYear = (year, last) => toDayNumber(`${String(year).padStart(4, "0")}-${last ? "12-31" : "01-01"}`);
111
+ const dayOfYear = (year, last) => dayNumberOf(`${String(year).padStart(4, "0")}-${last ? "12-31" : "01-01"}`);
111
112
  function collectBasis(calendar, inside) {
112
113
  const parts = partsOf(calendar);
113
114
  if (parts === undefined)
@@ -131,13 +132,6 @@ function collectBasis(calendar, inside) {
131
132
  inside.rules.push(...recurring);
132
133
  return recurring.every((r) => r.calendar === null || collectBasis(r.calendar, inside));
133
134
  }
134
- const crossesShortCentury = ({ from, to }) => {
135
- const last = yearOf(Math.min(to, MAX_DAY));
136
- for (let y = Math.ceil(yearOf(Math.max(from, MIN_DAY)) / 100) * 100; y <= last; y += 100)
137
- if (y % 400 !== 0)
138
- return true;
139
- return false;
140
- };
141
135
  function scanWindow(source, rules, cycle, inside) {
142
136
  const ranges = [];
143
137
  const side = (day, before) => before
@@ -201,7 +195,7 @@ function scanWindow(source, rules, cycle, inside) {
201
195
  else
202
196
  merged.push(r);
203
197
  }
204
- const yearOf = (n) => parseDate(fromDayNumber(n)).year;
198
+ const yearOf = (n) => parseDate(dateOfDayNumber(n)).year;
205
199
  const label = merged.map((r) => `${yearOf(r.from)}-${yearOf(r.to)}`).join(", ");
206
200
  return { ranges: merged, label, blind: false };
207
201
  }
@@ -221,7 +215,7 @@ export function rulesScanWindow(compiled) {
221
215
  (cycle >= max && own < max) ||
222
216
  days > MAX_SCAN_DAYS ||
223
217
  (inside.rules.some((r) => r.interval !== null || r.cycle !== null) &&
224
- window.ranges.some(crossesShortCentury));
218
+ window.ranges.some((r) => crossesShortCentury(r.from, r.to)));
225
219
  if (!blind)
226
220
  return window;
227
221
  return { ...(known ? scanWindow(source, rules, own) : window), blind };
@@ -237,7 +231,7 @@ function patternBits(rule) {
237
231
  const bits = new Uint8Array(PATTERN_DAYS);
238
232
  const weekly = rule.interval === null ? rule : { ...rule, interval: null, anchor: null };
239
233
  for (let i = 0; i < PATTERN_DAYS; i++) {
240
- if (matchPattern(weekly, fromDayNumber(PATTERN_FROM + i)))
234
+ if (matchPattern(weekly, dateOfDayNumber(PATTERN_FROM + i)))
241
235
  bits[i] = 1;
242
236
  }
243
237
  return bits;
@@ -250,7 +244,7 @@ function matchesAnyDay(rule, cycle) {
250
244
  ? Math.min(span.to, span.from + openEndedDays(span.from, cycle) - 1)
251
245
  : span.to;
252
246
  for (let n = Math.max(span.from, MIN_DAY); n <= Math.min(to, MAX_DAY); n++)
253
- if (matchPattern(rule, fromDayNumber(n)))
247
+ if (matchPattern(rule, dateOfDayNumber(n)))
254
248
  return true;
255
249
  return false;
256
250
  }
@@ -344,7 +338,7 @@ function sameValueIn(a, b, seen) {
344
338
  ka.every((k) => Object.hasOwn(b, k) &&
345
339
  sameValueIn(a[k], b[k], seen)));
346
340
  }
347
- const yearOf = (dayNumber) => parseDate(fromDayNumber(dayNumber)).year;
341
+ const yearOf = (dayNumber) => parseDate(dateOfDayNumber(dayNumber)).year;
348
342
  function without(compiled, rule, dropDates) {
349
343
  return {
350
344
  ...compiled,
@@ -387,16 +381,21 @@ function guardBases(compiled, unknownMonths) {
387
381
  const basis = r.basis;
388
382
  if (basis === null || r.calendar === null)
389
383
  return r;
384
+ const thrown = new Set();
390
385
  return {
391
386
  ...r,
392
387
  basis: (year, month) => {
388
+ const m = year * 12 + month - 1;
389
+ if (thrown.has(m))
390
+ return [];
393
391
  try {
394
392
  return basis(year, month);
395
393
  }
396
394
  catch (error) {
397
395
  if (!UNJUDGEABLE.has(String(error.code)))
398
396
  throw error;
399
- unknownMonths.add(year * 12 + month - 1);
397
+ unknownMonths.add(m);
398
+ thrown.add(m);
400
399
  return [];
401
400
  }
402
401
  },
@@ -412,8 +411,12 @@ export function unjudgeableDays(compiled, window) {
412
411
  if (!window || bases.length === 0)
413
412
  return { days, months };
414
413
  const monthOf = (day) => {
415
- const { year, month } = parseDate(fromDayNumber(day));
416
- return year * 12 + month - 1;
414
+ if (day < MIN_DAY || day > MAX_DAY) {
415
+ const { year, month } = parseDate(dateOfDayNumber(day));
416
+ return year * 12 + month - 1;
417
+ }
418
+ const d = new Date(day * 86_400_000);
419
+ return d.getUTCFullYear() * 12 + d.getUTCMonth();
417
420
  };
418
421
  for (const r of bases) {
419
422
  const thrown = new Map();
@@ -440,12 +443,14 @@ export function unjudgeableDays(compiled, window) {
440
443
  if (from > to)
441
444
  continue;
442
445
  if (r.weekStart === null) {
443
- for (let n = from; n <= to; n++)
444
- if (inMonths(monthOf(n)) && throws(monthOf(n)))
446
+ for (let n = from; n <= to; n++) {
447
+ const m = monthOf(n);
448
+ if (inMonths(m) && throws(m))
445
449
  days.add(n);
450
+ }
446
451
  continue;
447
452
  }
448
- const start = from - ((weekdayOf(fromDayNumber(from)) - r.weekStart + 7) % 7);
453
+ const start = from - ((weekdayOf(dateOfDayNumber(from)) - r.weekStart + 7) % 7);
449
454
  for (let w = start; w <= to; w += 7) {
450
455
  const all = [0, 1, 2, 3, 4, 5, 6].map((i) => w + i);
451
456
  const week = all.filter((n) => n >= MIN_DAY && n <= MAX_DAY);
@@ -507,6 +512,38 @@ export function unsureOf(compiled, unknown, blind = false) {
507
512
  return overlaps(item.effectiveFrom, item.effectiveTo);
508
513
  };
509
514
  }
515
+ function dateUnitsOf(window, compiled) {
516
+ const { dates, recurring, source } = compiled;
517
+ if (!window || dates.length === 0)
518
+ return [];
519
+ if (!recurring.some((r) => r.businessDays !== null && r.calendar === null))
520
+ return [];
521
+ const throws = source.providers.length > 0 && source.outOfRangePolicy !== "ignore";
522
+ const lo = throws ? window.ranges[0].from : MIN_DAY;
523
+ const hi = throws ? window.ranges[window.ranges.length - 1].to : MAX_DAY;
524
+ const ranges = [];
525
+ for (const d of dates) {
526
+ for (const edge of d.from === d.to ? [d.from] : [d.from, d.to]) {
527
+ const { year, month, day } = parseDate(dateOfDayNumber(edge));
528
+ const from = Math.max(edge - day + 1 - 6, lo);
529
+ const to = Math.min(edge - day + lengthOfMonth(year, month) + 6, hi);
530
+ if (from <= to)
531
+ ranges.push({ from, to });
532
+ }
533
+ }
534
+ return mergeRanges(ranges);
535
+ }
536
+ function mergeRanges(ranges) {
537
+ const merged = [];
538
+ for (const r of [...ranges].sort((x, y) => x.from - y.from)) {
539
+ const last = merged[merged.length - 1];
540
+ if (last && r.from <= last.to + 1)
541
+ merged[merged.length - 1] = { from: last.from, to: Math.max(last.to, r.to) };
542
+ else
543
+ merged.push(r);
544
+ }
545
+ return merged;
546
+ }
510
547
  function checkLostShifts(c, compiled, lookup, window) {
511
548
  const { source, recurring } = compiled;
512
549
  const shifting = recurring.filter((r) => r.holidayOverlapPolicy === "after-holiday");
@@ -522,7 +559,7 @@ function checkLostShifts(c, compiled, lookup, window) {
522
559
  const days = [];
523
560
  for (let y = yearOf(from); y <= yearOf(to); y++)
524
561
  for (const h of lookup.holidaysInYear(y))
525
- days.push(toDayNumber(h.date));
562
+ days.push(dayNumberOf(h.date));
526
563
  for (let i = 0; i < days.length; i++) {
527
564
  const back = MAX_HOLIDAY_RUN - 1;
528
565
  if (!skipping && days[i - back] !== days[i] - back)
@@ -530,7 +567,7 @@ function checkLostShifts(c, compiled, lookup, window) {
530
567
  const last = Math.min(days[i] + 7, (days[i + 1] ?? Infinity) - 1, to, MAX_DAY);
531
568
  for (let n = days[i] + 1; n <= last; n++) {
532
569
  try {
533
- resolve(fromDayNumber(n), false);
570
+ resolve(dateOfDayNumber(n), false);
534
571
  }
535
572
  catch (error) {
536
573
  if (!atEdge(n, error, window))
@@ -569,10 +606,24 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
569
606
  unconfirmedHolidayPolicy: "accept",
570
607
  });
571
608
  const basis = createBasis(compiled, lookup);
609
+ const strictLookup = source.unconfirmedHolidayPolicy === "throw" ? createHolidayLookup({ ...source }) : null;
572
610
  const cycle = patternCycle(recurring);
573
- const window = rulesScanWindow(compiled);
611
+ const rulesWindow = rulesScanWindow(compiled);
612
+ const dateUnits = dateUnitsOf(rulesWindow, compiled);
613
+ const window = rulesWindow && dateUnits.length > 0
614
+ ? { ...rulesWindow, ranges: mergeRanges([...rulesWindow.ranges, ...dateUnits]) }
615
+ : rulesWindow;
616
+ const inDateUnits = (n) => dateUnits.some((r) => r.from <= n && n <= r.to);
617
+ const resolverIn = (base, using = lookup) => {
618
+ const withDates = createResolver(base, using, throwLostShift);
619
+ if (dateUnits.length === 0)
620
+ return withDates;
621
+ const noDates = createResolver({ ...base, dates: [] }, using, throwLostShift);
622
+ return (date, withHoliday) => (inDateUnits(dayNumberOf(date)) ? withDates : noDates)(date, withHoliday);
623
+ };
624
+ const basisNoDates = dateUnits.length > 0 ? createBasis({ ...compiled, dates: [] }, lookup) : basis;
574
625
  const unused = new Set();
575
- checkLostShifts(c, compiled, lookup, window);
626
+ checkLostShifts(c, compiled, lookup, rulesWindow);
576
627
  dates.forEach((rule, j) => {
577
628
  const fromYear = yearOf(rule.from);
578
629
  const toYear = yearOf(rule.to);
@@ -637,7 +688,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
637
688
  if (!inPeriod(rule, n))
638
689
  return false;
639
690
  try {
640
- found = matchPattern(rule, fromDayNumber(n), holidayOfSafe, undefined, lookup.fromJp);
691
+ found = matchPattern(rule, dateOfDayNumber(n), holidayOfSafe, undefined, lookup.fromJp);
641
692
  }
642
693
  catch (error) {
643
694
  if (!atCalendarEdge(n, error))
@@ -656,7 +707,12 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
656
707
  if (!inPeriod(rule, n))
657
708
  return false;
658
709
  try {
659
- found = matchPattern(rule, fromDayNumber(n), holidayOfSafe, basis, lookup.fromJp);
710
+ const date = dateOfDayNumber(n);
711
+ found =
712
+ matchPattern(rule, date, holidayOfSafe, basis, lookup.fromJp) ||
713
+ (basisNoDates !== basis &&
714
+ !inDateUnits(n) &&
715
+ matchPattern(rule, date, holidayOfSafe, basisNoDates, lookup.fromJp));
660
716
  }
661
717
  catch {
662
718
  found = false;
@@ -674,7 +730,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
674
730
  if (nationalAsRegular === undefined) {
675
731
  let found = false;
676
732
  if (window && jpUsage(source) === "only") {
677
- eachDay(window, (n) => (found = holidayOfSafe(fromDayNumber(n))?.kind === renamedKind.from));
733
+ eachDay(window, (n) => (found = holidayOfSafe(dateOfDayNumber(n))?.kind === renamedKind.from));
678
734
  nationalAsRegular = !found;
679
735
  }
680
736
  else
@@ -776,6 +832,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
776
832
  r.interval === null &&
777
833
  r.months === null &&
778
834
  !unused.has(r) &&
835
+ !sameValue(compiled.weekly[r.weekday], r.value) &&
779
836
  periodsOverlap(rule, r));
780
837
  for (const weekly of weeklies) {
781
838
  c.info("counting-basis", rule.path, weekly.value === true
@@ -784,18 +841,25 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
784
841
  "write regular closed weekdays as closedWeekdays if they should not be counted", weekly.path);
785
842
  }
786
843
  }
787
- if (isCalendar && window && !dates.some((r) => r.value === true)) {
788
- const resolve = createResolver(without(compiled, null, true), lookup, throwLostShift);
789
- let found = false;
790
- eachDay(window, (n) => {
844
+ if (isCalendar && window && rulesWindow && !dates.some((r) => r.value === true)) {
845
+ const noDates = createResolver(without(compiled, null, true), lookup, throwLostShift);
846
+ const withDates = dateUnits.length > 0 ? createResolver(compiled, lookup, throwLostShift) : null;
847
+ const inRules = (n) => rulesWindow.ranges.some((r) => r.from <= n && n <= r.to);
848
+ const open = (resolve, n) => {
791
849
  try {
792
- found = resolve(fromDayNumber(n)).day.value === true;
850
+ return resolve(dateOfDayNumber(n)).day.value === true;
793
851
  }
794
852
  catch (error) {
795
853
  if (!atEdge(n, error, window) && !isLostShift(error))
796
854
  throw error;
797
- found = false;
855
+ return false;
798
856
  }
857
+ };
858
+ let found = false;
859
+ eachDay(window, (n) => {
860
+ found =
861
+ (inRules(n) && open(noDates, n)) ||
862
+ (withDates !== null && inDateUnits(n) && open(withDates, n));
799
863
  return found;
800
864
  });
801
865
  if (!found) {
@@ -813,12 +877,12 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
813
877
  for (const n of days) {
814
878
  out.add(n);
815
879
  if (countsMonth) {
816
- const { year, month, day } = parseDate(fromDayNumber(n));
880
+ const { year, month, day } = parseDate(dateOfDayNumber(n));
817
881
  for (let k = 0; k < lengthOfMonth(year, month); k++)
818
882
  out.add(n - day + 1 + k);
819
883
  }
820
884
  for (const start of weekStarts) {
821
- const first = n - ((weekdayOf(fromDayNumber(n)) - start + 7) % 7);
885
+ const first = n - ((weekdayOf(dateOfDayNumber(n)) - start + 7) % 7);
822
886
  for (let k = 0; k < 7; k++)
823
887
  out.add(first + k);
824
888
  }
@@ -832,7 +896,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
832
896
  if (!values.has(n)) {
833
897
  let value;
834
898
  try {
835
- value = resolve(fromDayNumber(n)).day.value;
899
+ value = resolve(dateOfDayNumber(n)).day.value;
836
900
  }
837
901
  catch {
838
902
  value = FAILED;
@@ -842,12 +906,24 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
842
906
  return values.get(n);
843
907
  };
844
908
  };
845
- const redundant = (rule, base, days, original) => {
846
- const resolve = createResolver(without(base, rule, false), lookup, throwLostShift);
909
+ const redundant = (rule, base, days, original, split = false) => {
910
+ const make = (b, using) => split ? resolverIn(b, using) : createResolver(b, using, throwLostShift);
911
+ const resolve = make(without(base, rule, false), lookup);
912
+ const strictAfter = strictLookup ? make(without(base, rule, false), strictLookup) : null;
913
+ const strictBefore = strictLookup ? make(base, strictLookup) : null;
914
+ const throwsUnconfirmed = (r, n) => {
915
+ try {
916
+ r(dateOfDayNumber(n));
917
+ return false;
918
+ }
919
+ catch (error) {
920
+ return error.code === "unconfirmed-holiday";
921
+ }
922
+ };
847
923
  for (const n of days) {
848
924
  let value;
849
925
  try {
850
- value = resolve(fromDayNumber(n)).day.value;
926
+ value = resolve(dateOfDayNumber(n)).day.value;
851
927
  }
852
928
  catch {
853
929
  value = FAILED;
@@ -859,6 +935,10 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
859
935
  }
860
936
  else if (!sameValue(before, value))
861
937
  return false;
938
+ if (strictAfter &&
939
+ strictBefore &&
940
+ throwsUnconfirmed(strictBefore, n) !== throwsUnconfirmed(strictAfter, n))
941
+ return false;
862
942
  }
863
943
  return true;
864
944
  };
@@ -883,7 +963,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
883
963
  span.push(n);
884
964
  let decidedBy;
885
965
  try {
886
- decidedBy = resolve(fromDayNumber(n)).rule;
966
+ decidedBy = resolve(dateOfDayNumber(n)).rule;
887
967
  }
888
968
  catch {
889
969
  continue;
@@ -915,11 +995,11 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
915
995
  const decidedIn = (rule) => {
916
996
  if (!decided && window) {
917
997
  const map = new Map(candidates.map((r) => [r, new Set()]));
918
- const resolveNow = createResolver(current(counting.length > 0), lookup, throwLostShift);
998
+ const resolveNow = resolverIn(current(counting.length > 0));
919
999
  eachDay(window, (n) => {
920
1000
  let by;
921
1001
  try {
922
- by = resolveNow(fromDayNumber(n)).rule;
1002
+ by = resolveNow(dateOfDayNumber(n)).rule;
923
1003
  }
924
1004
  catch {
925
1005
  unjudged.add(n);
@@ -935,18 +1015,18 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
935
1015
  const refresh = (affected) => {
936
1016
  if (!decided)
937
1017
  return;
938
- const resolveNow = createResolver(current(counting.length > 0), lookup, throwLostShift);
1018
+ const resolveNow = resolverIn(current(counting.length > 0));
939
1019
  for (const n of affected) {
940
1020
  if (!inWindow(n) || unjudged.has(n))
941
1021
  continue;
942
1022
  for (const days of decided.values())
943
1023
  days.delete(n);
944
- const by = resolveNow(fromDayNumber(n)).rule;
1024
+ const by = resolveNow(dateOfDayNumber(n)).rule;
945
1025
  if (by)
946
1026
  decided.get(by)?.add(n);
947
1027
  }
948
1028
  };
949
- const originalNow = originalOf(createResolver(current(counting.length > 0), lookup, throwLostShift));
1029
+ const originalNow = originalOf(resolverIn(current(counting.length > 0)));
950
1030
  const unitsOf = new Map();
951
1031
  const annualUnits = (rule) => {
952
1032
  const known = unitsOf.get(rule);
@@ -955,7 +1035,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
955
1035
  const matched = [];
956
1036
  if (window)
957
1037
  eachDay(window, (n) => {
958
- if (matchMonthDay(rule, fromDayNumber(n).slice(5)))
1038
+ if (matchMonthDay(rule, dateOfDayNumber(n).slice(5)))
959
1039
  matched.push(n);
960
1040
  });
961
1041
  const units = countingUnits(matched);
@@ -971,8 +1051,8 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
971
1051
  ? annualUnits(rule)
972
1052
  : days;
973
1053
  const ok = checkedDays === days
974
- ? redundant(rule, base, days, () => rule.value)
975
- : redundant(rule, base, checkedDays, originalNow);
1054
+ ? redundant(rule, base, days, () => rule.value, true)
1055
+ : redundant(rule, base, checkedDays, originalNow, true);
976
1056
  if (!ok)
977
1057
  return false;
978
1058
  affected = [...days, ...checkedDays];
@@ -1009,12 +1089,12 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
1009
1089
  }
1010
1090
  if (reported.size === 0)
1011
1091
  return;
1012
- const resolveFinal = createResolver(current(true), lookup, throwLostShift);
1092
+ const resolveFinal = resolverIn(current(true));
1013
1093
  const relatedOf = (days) => {
1014
1094
  const paths = new Set();
1015
1095
  for (const n of days) {
1016
1096
  try {
1017
- paths.add(resolveFinal(fromDayNumber(n)).rule?.path ?? null);
1097
+ paths.add(resolveFinal(dateOfDayNumber(n)).rule?.path ?? null);
1018
1098
  }
1019
1099
  catch {
1020
1100
  paths.add(null);
@@ -1041,13 +1121,13 @@ function compileDiagnoseOptions(options) {
1041
1121
  if (!isValidDate(asOf)) {
1042
1122
  throw rangeError("invalid-date", `asOf must be a date string "YYYY-MM-DD": ${describeValue(asOf)}`);
1043
1123
  }
1044
- return { asOf: toDayNumber(asOf) };
1124
+ return { asOf: dayNumberOf(asOf) };
1045
1125
  }
1046
1126
  function checkExpired(c, compiled, asOf) {
1047
1127
  const ended = (path, last, what, reach = last, why = "") => {
1048
1128
  if (reach < asOf) {
1049
- const until = reach > last ? ` (it could affect results until ${fromDayNumber(reach)}: ${why})` : "";
1050
- c.info("expired", path, `This ${what} ended on ${fromDayNumber(last)}${until}, before ${fromDayNumber(asOf)}; it no longer affects results and can be removed if the past need not be reproduced`);
1129
+ const until = reach > last ? ` (it could affect results until ${dateOfDayNumber(reach)}: ${why})` : "";
1130
+ c.info("expired", path, `This ${what} ended on ${dateOfDayNumber(last)}${until}, before ${dateOfDayNumber(asOf)}; it no longer affects results and can be removed if the past need not be reproduced`);
1051
1131
  }
1052
1132
  };
1053
1133
  const counting = compiled.recurring.filter((r) => r.businessDays !== null && r.basis === null);
@@ -1056,8 +1136,8 @@ function checkExpired(c, compiled, asOf) {
1056
1136
  const countedReach = (last) => {
1057
1137
  let reach = last;
1058
1138
  if (byMonth) {
1059
- const { year, month } = parseDate(fromDayNumber(last));
1060
- reach = toDayNumber(formatDate(year, month, lengthOfMonth(year, month)));
1139
+ const { year, month } = parseDate(dateOfDayNumber(last));
1140
+ reach = dayNumberOf(formatDate(year, month, lengthOfMonth(year, month)));
1061
1141
  }
1062
1142
  return byWeek ? Math.max(reach, last + 6) : reach;
1063
1143
  };
@@ -21,6 +21,8 @@ function formatterFor(timeZone) {
21
21
  return f;
22
22
  }
23
23
  function zoneNameOf(timeZone) {
24
+ if (zoneNames.get(timeZone) === timeZone)
25
+ return timeZone;
24
26
  const key = timeZone.replace(/[A-Z]+/g, (s) => s.toLowerCase());
25
27
  let name = zoneNames.get(key);
26
28
  if (name === undefined) {
@@ -64,7 +66,7 @@ export function distinctTimeZones(zones) {
64
66
  return out;
65
67
  }
66
68
  function wallParts(epochMilliseconds, timeZone) {
67
- const zone = zoneNames.get(timeZone) === timeZone ? timeZone : zoneNameOf(timeZone);
69
+ const zone = zoneNameOf(timeZone);
68
70
  const offset = OFFSET_ZONE_RE.exec(zone);
69
71
  const parts = formatterFor(offset ? "UTC" : zone).formatToParts(new Date(epochMilliseconds +
70
72
  (offset
@@ -1,10 +1,27 @@
1
- import { addDays, lengthOfMonth, formatDate, fromDayNumber, isValidDate, parseDate, toDayNumber, weekdayOf, } from "./date.js";
1
+ import { lengthOfMonth, formatDate, fromDayNumber, isValidDate, parseDate, toDayNumber, } from "./date.js";
2
2
  import { checkUnknownKeys, describeValue, IssueCollector, rangeError, withoutUndefined, } from "./errors.js";
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { checkNames } from "./names.js";
5
5
  import { RENAMED_VALUES, renameKeys, renameValue, writtenKey } from "./renamed.js";
6
6
  import { distinctTimeZones, instantToCivil, isDate, sameTimeZone, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
7
7
  import { HOLIDAY_KEY_PATTERN } from "./types.js";
8
+ let memoDate = "1970-01-01";
9
+ let memoDay = 0;
10
+ export function dayNumberOf(date) {
11
+ if (date !== memoDate) {
12
+ memoDay = toDayNumber(date);
13
+ memoDate = date;
14
+ }
15
+ return memoDay;
16
+ }
17
+ export function dateOfDayNumber(dayNumber) {
18
+ const date = fromDayNumber(dayNumber);
19
+ memoDate = date;
20
+ memoDay = Math.floor(dayNumber);
21
+ return date;
22
+ }
23
+ const weekdayOfDayNumber = (dayNumber) => ((((dayNumber + 4) % 7) + 7) % 7);
24
+ const weekdayOfDate = (date) => weekdayOfDayNumber(dayNumberOf(date));
8
25
  const MONTH_DAY_RE = /^(\d{2})-(\d{2})$/;
9
26
  const MAX_DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
10
27
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -56,7 +73,7 @@ function checkDate(c, path, value) {
56
73
  c.error("invalid-date", path, `Invalid date ${describeValue(value)} (expected YYYY-MM-DD)`);
57
74
  return undefined;
58
75
  }
59
- return toDayNumber(value);
76
+ return dayNumberOf(value);
60
77
  }
61
78
  function checkMonthDay(c, path, value) {
62
79
  if (!isValidMonthDay(value)) {
@@ -179,7 +196,7 @@ export function basisFromPredicate(isOpen) {
179
196
  const list = [];
180
197
  const dim = lengthOfMonth(year, month);
181
198
  for (let d = 1; d <= dim; d++)
182
- if (isOpen(formatDate(year, month, d)))
199
+ if (isOpen(formatDate(year, month, d, true)))
183
200
  list.push(d);
184
201
  days = Object.freeze(list);
185
202
  if (cache.size >= 240)
@@ -296,8 +313,8 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
296
313
  const a = checkDate(c, `${p}.anchor`, entry["anchor"]);
297
314
  if (a === undefined)
298
315
  ok = false;
299
- else if (weekday !== null && weekdayOf(entry["anchor"]) !== weekday) {
300
- c.error("invalid-option", `${p}.anchor`, `must be on the same weekday as "weekday" (${String(entry["anchor"])} is weekday ${weekdayOf(entry["anchor"])})`);
316
+ else if (weekday !== null && weekdayOfDate(entry["anchor"]) !== weekday) {
317
+ c.error("invalid-option", `${p}.anchor`, `must be on the same weekday as "weekday" (${String(entry["anchor"])} is weekday ${weekdayOfDate(entry["anchor"])})`);
301
318
  ok = false;
302
319
  }
303
320
  else
@@ -581,15 +598,15 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
581
598
  if (b === undefined)
582
599
  return false;
583
600
  if (rule.weekStart !== null) {
584
- const start = addDays(date, -((weekdayOf(date) - rule.weekStart + 7) % 7));
601
+ const self = dayNumberOf(date);
602
+ const start = self - ((weekdayOfDayNumber(self) - rule.weekStart + 7) % 7);
585
603
  const week = [];
586
- for (let i = 0; i < 7; i++) {
587
- const d = addDays(start, i);
588
- const at = parseDate(d);
604
+ for (let n = start; n < start + 7; n++) {
605
+ const at = parseDate(dateOfDayNumber(n));
589
606
  if (b(at.year, at.month).includes(at.day))
590
- week.push(d);
607
+ week.push(n);
591
608
  }
592
- const at = week.indexOf(date);
609
+ const at = week.indexOf(self);
593
610
  if (at < 0)
594
611
  return false;
595
612
  return rule.businessDays.has(at + 1) || rule.businessDays.has(at - week.length);
@@ -603,7 +620,7 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
603
620
  if (rule.holiday || rule.dayAfterHoliday || rule.dayBeforeHoliday) {
604
621
  if (holidayOf === undefined)
605
622
  return false;
606
- if (rule.weekdays && !rule.weekdays.has(weekdayOf(date)))
623
+ if (rule.weekdays && !rule.weekdays.has(weekdayOfDate(date)))
607
624
  return false;
608
625
  const selected = (h) => (rule.kinds === null ||
609
626
  rule.kinds.has(h.kind) ||
@@ -614,29 +631,29 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
614
631
  return h !== undefined && selected(h);
615
632
  }
616
633
  const skip = rule.skipWeekdays;
617
- if (holidayOf(date) !== undefined || skip?.has(weekdayOf(date)))
634
+ if (holidayOf(date) !== undefined || skip?.has(weekdayOfDate(date)))
618
635
  return false;
619
636
  const step = rule.dayAfterHoliday ? -1 : 1;
637
+ const self = dayNumberOf(date);
620
638
  for (let k = 1; k <= MAX_HOLIDAY_RUN; k++) {
621
- const next = addDays(date, step * k);
622
- const h = holidayOf(next);
639
+ const h = holidayOf(dateOfDayNumber(self + step * k));
623
640
  if (h !== undefined)
624
641
  return selected(h);
625
- if (!skip?.has(weekdayOf(next)))
642
+ if (!skip?.has(weekdayOfDayNumber(self + step * k)))
626
643
  return false;
627
644
  }
628
645
  return false;
629
646
  }
630
647
  if (rule.cycle !== null) {
631
- const offset = (toDayNumber(date) - rule.anchor) % rule.cycle;
648
+ const offset = (dayNumberOf(date) - rule.anchor) % rule.cycle;
632
649
  return rule.positions.has(((offset + rule.cycle) % rule.cycle) + 1);
633
650
  }
634
651
  const dim = lengthOfMonth(year, month);
635
652
  if (rule.weekday !== null) {
636
- if (weekdayOf(date) !== rule.weekday)
653
+ if (weekdayOfDate(date) !== rule.weekday)
637
654
  return false;
638
655
  if (rule.interval !== null)
639
- return (toDayNumber(date) - rule.anchor) % (7 * rule.interval) === 0;
656
+ return (dayNumberOf(date) - rule.anchor) % (7 * rule.interval) === 0;
640
657
  if (rule.nth === null)
641
658
  return true;
642
659
  return rule.nth.has(Math.ceil(day / 7)) || (rule.nth.has(-1) && day + 7 > dim);
@@ -644,7 +661,7 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
644
661
  return rule.days.has(day) || (rule.days.has(-1) && day === dim);
645
662
  }
646
663
  export function matchRecurring(rule, date, holidayOf, basis, fromJp) {
647
- return inPeriod(rule, toDayNumber(date)) && matchPattern(rule, date, holidayOf, basis, fromJp);
664
+ return inPeriod(rule, dayNumberOf(date)) && matchPattern(rule, date, holidayOf, basis, fromJp);
648
665
  }
649
666
  export function createBasis(compiled, lookup) {
650
667
  if (!compiled.recurring.some((r) => r.businessDays !== null && r.basis === null))
@@ -1016,7 +1033,7 @@ export function matchMonthDay(rule, monthDay) {
1016
1033
  : monthDay >= rule.from || monthDay <= rule.to;
1017
1034
  }
1018
1035
  export function matchAnnual(rule, date) {
1019
- return inPeriod(rule, toDayNumber(date)) && matchMonthDay(rule, date.slice(5));
1036
+ return inPeriod(rule, dayNumberOf(date)) && matchMonthDay(rule, date.slice(5));
1020
1037
  }
1021
1038
  export const isHolidayBasedRule = (rule) => rule.holiday === true || rule.dayAfterHoliday === true || rule.dayBeforeHoliday === true;
1022
1039
  export function resultIgnoresHolidays(compiled) {
@@ -1028,26 +1045,68 @@ export function resultIgnoresHolidays(compiled) {
1028
1045
  export function createResolver(compiled, lookup, onLostShift) {
1029
1046
  const { weekly, holiday: holidayRule, annual, dates, recurring } = compiled;
1030
1047
  const hasShift = recurring.some((r) => r.holidayOverlapPolicy === "after-holiday");
1048
+ let sorted;
1049
+ let lookups = 0;
1050
+ const dateRuleOf = (n) => {
1051
+ if (sorted === undefined) {
1052
+ const count = dates.length;
1053
+ if (lookups++ === 0) {
1054
+ let ordered = 1;
1055
+ while (ordered < count && dates[ordered].from > dates[ordered - 1].to)
1056
+ ordered++;
1057
+ if (ordered >= count)
1058
+ sorted = dates;
1059
+ }
1060
+ else if (lookups > 2 * Math.log2(count + 1)) {
1061
+ const keys = new Float64Array(count);
1062
+ for (let i = 0; i < count; i++)
1063
+ keys[i] = (dates[i].from - MIN_DAY_NUMBER) * count + i;
1064
+ keys.sort();
1065
+ const s = [];
1066
+ for (let i = 0; i < count; i++) {
1067
+ const r = dates[keys[i] % count];
1068
+ if (i > 0 && r.from <= s[i - 1].to)
1069
+ break;
1070
+ s.push(r);
1071
+ }
1072
+ sorted = s.length === count ? s : null;
1073
+ }
1074
+ }
1075
+ if (!sorted)
1076
+ return dates.find((r) => n >= r.from && n <= r.to);
1077
+ let lo = 0;
1078
+ let hi = sorted.length;
1079
+ while (lo < hi) {
1080
+ const mid = (lo + hi) >> 1;
1081
+ if (sorted[mid].from <= n)
1082
+ lo = mid + 1;
1083
+ else
1084
+ hi = mid;
1085
+ }
1086
+ const r = lo > 0 ? sorted[lo - 1] : undefined;
1087
+ return r !== undefined && n <= r.to ? r : undefined;
1088
+ };
1031
1089
  const holidayUnused = resultIgnoresHolidays(compiled);
1032
1090
  const basis = createBasis(compiled, lookup);
1033
1091
  const holidayOfNeighbour = (date) => lookup.holidayOfDate(date);
1034
1092
  const isHolidayOfNeighbour = (date) => holidayOfNeighbour(date) !== undefined;
1035
1093
  function shiftedOrigin(rule, date) {
1094
+ const self = dayNumberOf(date);
1036
1095
  for (let k = 1; k <= MAX_HOLIDAY_RUN; k++) {
1037
- const prev = addDays(date, -k);
1038
- if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1096
+ const prev = dateOfDayNumber(self - k);
1097
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOfDayNumber(self - k)))
1039
1098
  return undefined;
1040
1099
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp))
1041
1100
  return prev;
1042
1101
  }
1043
- const first = toDayNumber(date) - MAX_HOLIDAY_RUN_SCAN;
1044
- for (let n = toDayNumber(date) - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1102
+ const first = self - MAX_HOLIDAY_RUN_SCAN;
1103
+ for (let n = self - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1045
1104
  if (n < first) {
1046
1105
  onLostShift(rule, date, undefined);
1047
1106
  return undefined;
1048
1107
  }
1049
- const prev = fromDayNumber(n);
1050
- if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1108
+ const prev = dateOfDayNumber(n);
1109
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOfDayNumber(n)))
1051
1110
  return undefined;
1052
1111
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp)) {
1053
1112
  onLostShift(rule, date, prev);
@@ -1057,8 +1116,8 @@ export function createResolver(compiled, lookup, onLostShift) {
1057
1116
  return undefined;
1058
1117
  }
1059
1118
  return function resolve(date, withHoliday = true) {
1060
- const dayNumber = toDayNumber(date);
1061
- const weekday = weekdayOf(date);
1119
+ const dayNumber = dayNumberOf(date);
1120
+ const weekday = weekdayOfDate(date);
1062
1121
  const holiday = lookup.holidayOfDate(date, holidayUnused && !withHoliday);
1063
1122
  const make = (value, reason, rule, name, shiftedFrom) => {
1064
1123
  const result = {
@@ -1077,7 +1136,7 @@ export function createResolver(compiled, lookup, onLostShift) {
1077
1136
  result.optionPath = result.rulePath = rule.path;
1078
1137
  return { day: Object.freeze(result), rule };
1079
1138
  };
1080
- const byDate = dates.find((r) => dayNumber >= r.from && dayNumber <= r.to);
1139
+ const byDate = dateRuleOf(dayNumber);
1081
1140
  if (byDate)
1082
1141
  return make(byDate.value, "date", byDate, byDate.name);
1083
1142
  const byAnnual = annual.find((r) => matchAnnual(r, date));
@@ -1117,8 +1176,8 @@ export function mapDays(from, to, fn) {
1117
1176
  throw rangeError("invalid-range", `"from" must not be after "to" (${from} > ${to})`);
1118
1177
  }
1119
1178
  const result = [];
1120
- for (let n = toDayNumber(from); n <= toDayNumber(to); n++)
1121
- result.push(fn(fromDayNumber(n)));
1179
+ for (let n = dayNumberOf(from); n <= dayNumberOf(to); n++)
1180
+ result.push(fn(dateOfDayNumber(n)));
1122
1181
  return Object.freeze(result);
1123
1182
  }
1124
1183
  const INTERNAL_INFO = Symbol("bizdays-toolkit.scheduleInfo");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bizdays-toolkit",
3
- "version": "0.32.6",
3
+ "version": "0.32.8",
4
4
  "description": "Holidays, business-day calendar and day-by-day schedules (e.g. store hours) with time zone support. Japanese holidays verified against the Cabinet Office data; UK bank holidays (England, Wales, Scotland, Northern Ireland) verified against GOV.UK and The Gazette; French public holidays (metropole, Alsace-Moselle) verified against data.gouv.fr; Singapore public holidays verified against data.gov.sg. / 祝日と営業日のカレンダー(タイムゾーン対応・日本の祝日は内閣府、英国の bank holidays は GOV.UK と The Gazette、フランスの祝日は data.gouv.fr、シンガポールの祝日は data.gov.sg のデータで全日照合)",
5
5
  "keywords": [
6
6
  "bank-holidays",
@@ -92,8 +92,8 @@
92
92
  },
93
93
  "devDependencies": {
94
94
  "@types/node": "26.6.6",
95
- "oxfmt": "0.78.0",
96
- "oxlint": "1.93.0",
95
+ "oxfmt": "0.79.0",
96
+ "oxlint": "1.94.0",
97
97
  "typescript": "6.0.3"
98
98
  },
99
99
  "engines": {