bizdays-toolkit 0.31.9 → 0.32.1

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,39 @@ Entries from 0.31.0 are in English. Earlier entries remain in Japanese (their **
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.32.1] - 2026-11-14
10
+
11
+ ### Fixed
12
+
13
+ - The option diagnostics reported an item as `redundant` (removing it does not change any result) although removing it made a day throw. This happened only with a holiday provider that returns holidays on more than 31 consecutive days and a `holidayOverlapPolicy: "after-holiday"` rule whose day cannot be moved past that run (the case that throws `holiday-run-too-long` since 0.32.0): when another item decided the first day after the run before the rule was reached (a date in `closedDates` or `openDates`, an annual date, or an earlier recurring rule), the calendar evaluated that day without an exception, the diagnostics reported that item as `redundant`, and removing it as suggested made the day throw `holiday-run-too-long`. The diagnostics now treat a day on which the evaluation throws `holiday-run-too-long` as a day that cannot be judged (an item is not reported as `redundant` when removing it changes whether a day can be judged), so such an item is no longer reported. A wrong diagnostic disappears; no result of a calendar or schedule changes, and the `warning` with code `holiday-run-too-long` is reported as before. The opposite direction remains and is documented (design decisions 31): the `"after-holiday"` rule that loses its day can itself be reported as `redundant`, and removing it makes the exception disappear
14
+
15
+ ## [0.32.0] - 2026-11-14
16
+
17
+ This minor version stops one silent loss of closed days, makes aliases of a time zone the same time zone on runtimes with Temporal, and makes one mistaken call a type error. Some code needs a check; see Migration.
18
+
19
+ ### Changed
20
+
21
+ - A day of a `holidayOverlapPolicy: "after-holiday"` rule that cannot be moved past a long run of holidays now throws instead of being silently lost. When a holiday provider returns holidays on more than 31 consecutive days and the rule's own day is more than 31 days before the first day after the run, the rule was not moved and the closed day did not appear at all (documented since 0.31.8). Evaluating that first day now throws a `RangeError` with the new code `holiday-run-too-long`, as do searches that pass the day (`addBusinessDays`, `nextBusinessDay` and the like) and calculations over a range that contains it (`diffBusinessDays`, `daysBetween`, `businessDatesBetween`, `nthBusinessDayOfMonth` and the like). Days inside the run and other days are evaluated as before, a rule whose day is within 31 days is moved as before, and weekly rules and rules for the day before or after a holiday are not affected. The same code is thrown when a run goes on for more than 367 days, because the day to move cannot be determined. Because the search for that day now goes further back than 31 days, the first day after a run of 31 or more days that starts on the first day of the provider's supported years throws `out-of-range` with `outOfRangePolicy: "throw"` (the default), even when no day is lost: the days before the run are not known. Shorter runs there already did. The bundled providers are not affected (their longest run is 8 days). Write a long closure with `closedDates` or `closedAnnualDates`, not as holidays (design decisions 24)
22
+ - Whether two time zones are the same (calendars combined with `combineCalendars`, the holiday providers of one set of options, and a schedule and the counting calendar of its nth-business-day rule) is now decided with the runtime's `Temporal` when their names differ and the runtime has one. Aliases of one time zone, such as `"UTC"` and `"Etc/UTC"` or `"Asia/Kolkata"` and `"Asia/Calcutta"`, are therefore the same time zone on every runtime with Temporal: Bun no longer throws `time-zone-conflict` for them, and on Node.js 26, Chrome and Edge a few more pairs are accepted (such as `"CST6CDT"` and `"America/Chicago"`). Runtimes without Temporal compare the names `Intl` reports, as before; on Safari without Temporal, aliases remain a `time-zone-conflict`. The name `timeZone` returns is unchanged. Only exceptions disappear; no result of a calendar or schedule changes (design decisions 18)
23
+ - TypeScript: passing a holiday provider, a calendar or a schedule itself as the options of `createCalendar` (`createCalendar(jp)`) is now a type error. It compiled until 0.31.9 and made a calendar without holidays. The options types have `holidaysInYear?: never` for this; at run time such a key is still an unknown option that the diagnostics report (design decisions 8). Pass the provider as `createCalendar({ holidayProvider: jp })`
24
+
25
+ ### Added
26
+
27
+ - The error code `holiday-run-too-long` (`KnownErrorCode`), and the same code as a `warning` of the option diagnostics: `diagnoseCalendar` and `diagnoseSchedule` report each `"after-holiday"` rule that loses a day this way, at the rule, with `relatedPath` pointing to the holiday provider when there is only one. The options can still be created, as with `out-of-range` and `no-business-day`
28
+
29
+ ### Fixed
30
+
31
+ - Documentation: the guide and the design decisions (18) now describe offsets from UTC as time zones. `"+09:00"`, `"+0900"` and `"+09"` are accepted and returned as `"+09:00"` on every runtime tested (Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno); other forms such as `"UTC+9"` are an `invalid-time-zone`, and an offset and a named time zone are different time zones. The README now notes the Safari limitation above. The design decisions (18) now say that duplicate providers and duplicate calendars are deliberately treated differently. Results are unchanged
32
+
33
+ ### Migration
34
+
35
+ Check your code if one of these applies; otherwise no work is needed. The same steps are in [docs/migration.md](./docs/migration.md) (in Japanese).
36
+
37
+ - **You use your own holiday provider that returns holidays on more than 31 consecutive days, together with `"after-holiday"` rules.** Run `diagnoseCalendar` or `diagnoseSchedule` on your options and look for a `warning` with code `holiday-run-too-long`. If there is one, the first day after the run now throws, and so does every search that passes it and every calculation over a range that contains it: one lost day stops a count over the whole year. Write the long closure with `closedDates` or `closedAnnualDates` instead of returning it as holidays
38
+ - **You branch on `time-zone-conflict`.** Aliases of one time zone no longer throw on runtimes with Temporal. Remove code that relies on the exception
39
+ - **You pass a holiday provider, a calendar or a schedule directly to `createCalendar` in TypeScript.** Pass the provider as `{ holidayProvider: provider }`; a calendar or schedule was never read as options
40
+ - **You branch on error codes.** Make sure the new `holiday-run-too-long` falls into your default branch
41
+
9
42
  ## [0.31.9] - 2026-11-14
10
43
 
11
44
  This version removes two wrong diagnostics, makes evaluation and the option diagnostics faster, and documents how time zone names are compared. Results of calendars and schedules do not change.
@@ -974,7 +1007,9 @@ This version rebuilds the `redundant` diagnostic so that the reported rules can
974
1007
 
975
1008
  - 日本: 2026 年 2 月の官報(2027 年の春分・秋分の日)まで反映(`dataVersion: "2026-02"`、`confirmedThrough: 2027`)
976
1009
 
977
- [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.9...HEAD
1010
+ [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.1...HEAD
1011
+ [0.32.1]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.0...v0.32.1
1012
+ [0.32.0]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.9...v0.32.0
978
1013
  [0.31.9]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.8...v0.31.9
979
1014
  [0.31.8]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.7...v0.31.8
980
1015
  [0.31.7]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.6...v0.31.7
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.2 KB min+gzip (about 15.9 KB with Japanese holidays, about 16.4 KB with UK bank holidays, about 15.1 KB with French holidays, about 15.1 KB with Singapore holidays; measured for 0.31.9). Standard JavaScript and `Intl` only, ESM with bundled types; tested on Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno. 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 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
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
@@ -2,7 +2,7 @@ import { addDays, lengthOfMonth, formatDate, fromDayNumber, toDayNumber, } from
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
- import { parseTimeOfDaySeconds, toCivil } from "./input.js";
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
7
  import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, } from "./schedule.js";
8
8
  export const CALENDAR_OPTION_KEYS = [
@@ -361,7 +361,7 @@ export function combineCalendars(calendars, options) {
361
361
  if (!Number.isInteger(searchDayLimit) || searchDayLimit < 1) {
362
362
  throw rangeError("invalid-option", "searchDayLimit must be a positive integer");
363
363
  }
364
- const zones = [...new Set(calendars.map((c) => c.timeZone))];
364
+ const zones = distinctTimeZones(calendars.map((c) => c.timeZone));
365
365
  if (zones.length > 1) {
366
366
  throw rangeError("time-zone-conflict", `Calendars use different time zones (${zones.join(", ")}); combine calendars with the same time zone`);
367
367
  }
@@ -3,7 +3,7 @@ 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, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, isHolidayBasedRule, resultIgnoresHolidays, } from "./schedule.js";
6
+ import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, lostShiftMessage, throwLostShift, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, isHolidayBasedRule, resultIgnoresHolidays, } 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++) {
@@ -51,6 +51,7 @@ const MIN_DAY = toDayNumber("1000-01-01");
51
51
  const MAX_DAY = toDayNumber("9999-12-31");
52
52
  const MAX_WINDOW_YEARS = 200;
53
53
  const MAX_DATE_RULE_DAYS = 366 * MAX_WINDOW_YEARS;
54
+ const isLostShift = (error) => error?.code === "holiday-run-too-long";
54
55
  const atCalendarEdge = (n, error) => (n < MIN_DAY + MAX_HOLIDAY_RUN || n > MAX_DAY - MAX_HOLIDAY_RUN) &&
55
56
  error?.code === "out-of-range";
56
57
  function openEndedDays(from, days) {
@@ -296,7 +297,7 @@ function checkProviderData(c, source) {
296
297
  });
297
298
  return ok;
298
299
  }
299
- const UNJUDGEABLE = new Set(["out-of-range", "unconfirmed-holiday"]);
300
+ const UNJUDGEABLE = new Set(["out-of-range", "unconfirmed-holiday", "holiday-run-too-long"]);
300
301
  function guardBases(compiled, unknownMonths) {
301
302
  if (!compiled.recurring.some((r) => r.basis !== null && r.calendar !== null))
302
303
  return compiled;
@@ -424,6 +425,41 @@ export function unsureOf(compiled, unknown) {
424
425
  return overlaps(item.effectiveFrom, item.effectiveTo);
425
426
  };
426
427
  }
428
+ function checkLostShifts(c, compiled, lookup, window) {
429
+ const { source, recurring } = compiled;
430
+ const shifting = recurring.filter((r) => r.holidayOverlapPolicy === "after-holiday");
431
+ if (!window || source.providers.length === 0 || shifting.length === 0)
432
+ return;
433
+ const found = new Map();
434
+ const resolve = createResolver(compiled, lookup, (rule, date, origin) => {
435
+ if (!found.has(rule))
436
+ found.set(rule, lostShiftMessage(date, origin));
437
+ });
438
+ const skipping = shifting.some((r) => r.skipWeekdays !== null);
439
+ for (const { from, to } of window.ranges) {
440
+ const days = [];
441
+ for (let y = yearOf(from); y <= yearOf(to); y++)
442
+ for (const h of lookup.holidaysInYear(y))
443
+ days.push(toDayNumber(h.date));
444
+ for (let i = 0; i < days.length; i++) {
445
+ const back = MAX_HOLIDAY_RUN - 1;
446
+ if (!skipping && days[i - back] !== days[i] - back)
447
+ continue;
448
+ const last = Math.min(days[i] + 7, (days[i + 1] ?? Infinity) - 1, to, MAX_DAY);
449
+ for (let n = days[i] + 1; n <= last; n++) {
450
+ try {
451
+ resolve(fromDayNumber(n), false);
452
+ }
453
+ catch (error) {
454
+ if (!atCalendarEdge(n, error))
455
+ throw error;
456
+ }
457
+ }
458
+ }
459
+ }
460
+ for (const [rule, message] of found)
461
+ c.warning("holiday-run-too-long", rule.path, message, source.providers.length === 1 ? providerPath(source, 0) : undefined);
462
+ }
427
463
  export function dropUnsure(c, from, unsure, recorded, unknown) {
428
464
  for (const m of recorded)
429
465
  if (!unknown.months.has(m))
@@ -454,6 +490,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
454
490
  const cycle = patternCycle(recurring);
455
491
  const window = rulesScanWindow(compiled, cycle);
456
492
  const unused = new Set();
493
+ checkLostShifts(c, compiled, lookup, window);
457
494
  dates.forEach((rule, j) => {
458
495
  const fromYear = yearOf(rule.from);
459
496
  const toYear = yearOf(rule.to);
@@ -665,14 +702,14 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
665
702
  }
666
703
  }
667
704
  if (isCalendar && window && !dates.some((r) => r.value === true)) {
668
- const resolve = createResolver(without(compiled, null, true), lookup);
705
+ const resolve = createResolver(without(compiled, null, true), lookup, throwLostShift);
669
706
  let found = false;
670
707
  eachDay(window, (n) => {
671
708
  try {
672
709
  found = resolve(fromDayNumber(n)).day.value === true;
673
710
  }
674
711
  catch (error) {
675
- if (!atCalendarEdge(n, error))
712
+ if (!atCalendarEdge(n, error) && !isLostShift(error))
676
713
  throw error;
677
714
  found = false;
678
715
  }
@@ -723,7 +760,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
723
760
  };
724
761
  };
725
762
  const redundant = (rule, base, days, original) => {
726
- const resolve = createResolver(without(base, rule, false), lookup);
763
+ const resolve = createResolver(without(base, rule, false), lookup, throwLostShift);
727
764
  for (const n of days) {
728
765
  let value;
729
766
  try {
@@ -752,7 +789,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
752
789
  });
753
790
  const judgeDate = (rule) => {
754
791
  const base = current(true);
755
- const resolve = createResolver(base, lookup);
792
+ const resolve = createResolver(base, lookup, throwLostShift);
756
793
  const decided = [];
757
794
  const span = [];
758
795
  let checked = 0;
@@ -793,7 +830,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
793
830
  const decidedIn = (rule) => {
794
831
  if (!decided && window) {
795
832
  const map = new Map(candidates.map((r) => [r, new Set()]));
796
- const resolveNow = createResolver(current(counting.length > 0), lookup);
833
+ const resolveNow = createResolver(current(counting.length > 0), lookup, throwLostShift);
797
834
  eachDay(window, (n) => {
798
835
  let by;
799
836
  try {
@@ -813,7 +850,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
813
850
  const refresh = (affected) => {
814
851
  if (!decided)
815
852
  return;
816
- const resolveNow = createResolver(current(counting.length > 0), lookup);
853
+ const resolveNow = createResolver(current(counting.length > 0), lookup, throwLostShift);
817
854
  for (const n of affected) {
818
855
  if (!inWindow(n) || unjudged.has(n))
819
856
  continue;
@@ -824,7 +861,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
824
861
  decided.get(by)?.add(n);
825
862
  }
826
863
  };
827
- const originalNow = originalOf(createResolver(current(counting.length > 0), lookup));
864
+ const originalNow = originalOf(createResolver(current(counting.length > 0), lookup, throwLostShift));
828
865
  const unitsOf = new Map();
829
866
  const annualUnits = (rule) => {
830
867
  const known = unitsOf.get(rule);
@@ -887,7 +924,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
887
924
  }
888
925
  if (reported.size === 0)
889
926
  return;
890
- const resolveFinal = createResolver(current(true), lookup);
927
+ const resolveFinal = createResolver(current(true), lookup, throwLostShift);
891
928
  const relatedOf = (days) => {
892
929
  const paths = new Set();
893
930
  for (const n of days) {
@@ -47,6 +47,12 @@ export type KnownErrorCode =
47
47
  | "invalid-provider"
48
48
  /** 祝日の提供元が返したデータの誤り */
49
49
  | "invalid-provider-data"
50
+ /**
51
+ * 祝日の連続が長すぎて、"after-holiday" の規則の日を連続が明けた日に振り替えられない(連続が 31 日を超えて届かない、
52
+ * または 367 日を超えて続き振替元を確かめられない)。その日の判定と、その日を通る探索・その日を含む期間の計算が投げる。
53
+ * 長い休業は祝日ではなく closedDates・closedAnnualDates で書く
54
+ */
55
+ | "holiday-run-too-long"
50
56
  /**
51
57
  * 営業日が見つからない(探索が searchDayLimit 日を超えた、月の営業日が第 n 営業日の n に足りない、カレンダーの締めの月に
52
58
  * 固有の期間がない)
@@ -29,6 +29,27 @@ export function validateTimeZone(timeZone) {
29
29
  throw rangeError("invalid-time-zone", `Invalid time zone: ${describeValue(timeZone)}`);
30
30
  }
31
31
  }
32
+ export function sameTimeZone(a, b) {
33
+ if (a === b)
34
+ return true;
35
+ const T = globalThis.Temporal;
36
+ if (T === undefined)
37
+ return false;
38
+ try {
39
+ const at = T.Instant.fromEpochMilliseconds(0);
40
+ return at.toZonedDateTimeISO(a).equals(at.toZonedDateTimeISO(b)) === true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ export function distinctTimeZones(zones) {
47
+ const out = [];
48
+ for (const z of zones)
49
+ if (!out.some((o) => sameTimeZone(o, z)))
50
+ out.push(z);
51
+ return out;
52
+ }
32
53
  function wallParts(epochMilliseconds, timeZone) {
33
54
  const parts = formatterFor(timeZone).formatToParts(new Date(epochMilliseconds));
34
55
  const get = (type) => {
@@ -442,6 +442,8 @@ export interface ScheduleDateRange<Value> {
442
442
  }
443
443
  /**
444
444
  * 祝日の提供元とタイムゾーンの設定(スケジュールと営業日カレンダーで共通)。
445
+ * 祝日の提供元・作成済みのカレンダー・スケジュールをそのまま設定として渡す誤り(createCalendar(jp) など。提供元は
446
+ * holidayProvider に渡す)を型で止めるため、その 3 つがどれも持つ項目 holidaysInYear は書けない。
445
447
  * @public
446
448
  */
447
449
  export interface HolidaySourceOptions<Kind extends string = string> {
@@ -468,6 +470,7 @@ export interface HolidaySourceOptions<Kind extends string = string> {
468
470
  * 判定が祝日に依存する設定でだけ意味がある(条件はガイドの「Unconfirmed holidays」。decisions.md の 17 番)
469
471
  */
470
472
  readonly unconfirmedHolidayPolicy?: "accept" | "throw";
473
+ readonly holidaysInYear?: never;
471
474
  }
472
475
  /**
473
476
  * スケジュールの設定。
@@ -3,7 +3,7 @@ import { checkUnknownKeys, describeValue, IssueCollector, rangeError, withoutUnd
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
- import { instantToCivil, isDate, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
6
+ import { distinctTimeZones, instantToCivil, isDate, sameTimeZone, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
7
7
  import { HOLIDAY_KEY_PATTERN } from "./types.js";
8
8
  const MONTH_DAY_RE = /^(\d{2})-(\d{2})$/;
9
9
  const MAX_DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
@@ -649,7 +649,7 @@ export function matchRecurring(rule, date, holidayOf, basis, fromJp) {
649
649
  export function createBasis(compiled, lookup) {
650
650
  if (!compiled.recurring.some((r) => r.businessDays !== null && r.basis === null))
651
651
  return undefined;
652
- const resolve = createResolver({ ...compiled, recurring: [] }, lookup);
652
+ const resolve = createResolver({ ...compiled, recurring: [] }, lookup, ignoreLostShift);
653
653
  return basisFromPredicate((date) => resolve(date, false).day.value === true);
654
654
  }
655
655
  function requiredValue(c) {
@@ -741,7 +741,7 @@ export function compileHolidaySource(c, options) {
741
741
  }
742
742
  }
743
743
  else {
744
- const zones = [...new Set(providers.map((p) => validateTimeZone(p.timeZone)))];
744
+ const zones = distinctTimeZones(providers.map((p) => validateTimeZone(p.timeZone)));
745
745
  if (zones.length > 1) {
746
746
  c.error("time-zone-conflict", "timeZone", `Holiday providers use different time zones (${zones.join(", ")}); specify timeZone`);
747
747
  }
@@ -993,13 +993,23 @@ export function compileScheduleOptions(c, options) {
993
993
  continue;
994
994
  const entry = o["recurringRules"][Number(/\[(\d+)\]$/.exec(rule.path)[1])];
995
995
  const tz = entry["calendar"].timeZone;
996
- if (tz !== source.timeZone) {
996
+ if (!sameTimeZone(tz, source.timeZone)) {
997
997
  c.error("time-zone-conflict", `${rule.path}.calendar`, `the calendar's time zone ${tz} differs from the schedule's ${source.timeZone}`);
998
998
  }
999
999
  }
1000
1000
  return { source, weekly, holiday, annual, dates, recurring };
1001
1001
  }
1002
1002
  export const MAX_HOLIDAY_RUN = 31;
1003
+ const MAX_HOLIDAY_RUN_SCAN = 367;
1004
+ const MIN_DAY_NUMBER = toDayNumber("1000-01-01");
1005
+ export const lostShiftMessage = (date, origin) => (origin === undefined
1006
+ ? `no day can be moved to ${date}: the run of holidays before it is longer than ${MAX_HOLIDAY_RUN_SCAN} days, so the day to move cannot be determined`
1007
+ : `the day ${origin} cannot be moved to ${date}: the run of holidays between them is longer than ${MAX_HOLIDAY_RUN} days`) +
1008
+ " (write a long closure with closedDates or closedAnnualDates, not as holidays)";
1009
+ export const throwLostShift = (rule, date, origin) => {
1010
+ throw rangeError("holiday-run-too-long", `${rule.path}: ${lostShiftMessage(date, origin)}`);
1011
+ };
1012
+ export const ignoreLostShift = () => { };
1003
1013
  export function matchMonthDay(rule, monthDay) {
1004
1014
  return rule.from <= rule.to
1005
1015
  ? monthDay >= rule.from && monthDay <= rule.to
@@ -1015,7 +1025,7 @@ export function resultIgnoresHolidays(compiled) {
1015
1025
  r.holidayOverlapPolicy === "after-holiday" ||
1016
1026
  r.holidayOverlapPolicy === "over-holiday"));
1017
1027
  }
1018
- export function createResolver(compiled, lookup) {
1028
+ export function createResolver(compiled, lookup, onLostShift) {
1019
1029
  const { weekly, holiday: holidayRule, annual, dates, recurring } = compiled;
1020
1030
  const hasShift = recurring.some((r) => r.holidayOverlapPolicy === "after-holiday");
1021
1031
  const holidayUnused = resultIgnoresHolidays(compiled);
@@ -1030,6 +1040,20 @@ export function createResolver(compiled, lookup) {
1030
1040
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp))
1031
1041
  return prev;
1032
1042
  }
1043
+ const first = toDayNumber(date) - MAX_HOLIDAY_RUN_SCAN;
1044
+ for (let n = toDayNumber(date) - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1045
+ if (n < first) {
1046
+ onLostShift(rule, date, undefined);
1047
+ return undefined;
1048
+ }
1049
+ const prev = fromDayNumber(n);
1050
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1051
+ return undefined;
1052
+ if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp)) {
1053
+ onLostShift(rule, date, prev);
1054
+ return undefined;
1055
+ }
1056
+ }
1033
1057
  return undefined;
1034
1058
  }
1035
1059
  return function resolve(date, withHoliday = true) {
@@ -1107,7 +1131,7 @@ export function infoOfSchedule(schedule) {
1107
1131
  }
1108
1132
  export function buildSchedule(compiled) {
1109
1133
  const lookup = createHolidayLookup(compiled.source);
1110
- const resolve = createResolver(compiled, lookup);
1134
+ const resolve = createResolver(compiled, lookup, throwLostShift);
1111
1135
  const info = (date) => resolve(date).day;
1112
1136
  const values = Object.freeze(typeof compiled.holiday === "object" && "value" in compiled.holiday
1113
1137
  ? [...compiled.weekly, compiled.holiday.value]
@@ -38,9 +38,9 @@ export interface Holiday<Kind extends string = string> {
38
38
  * holidaysInYear が返すデータは、年ごとに初めて使うときに検証され、誤りがあれば
39
39
  * code: "invalid-provider-data" の例外になる。返した祝日は、契約の項目(date・name・nameEn・names・
40
40
  * kind・confirmed・key)だけを持つ変更できないオブジェクトに複製される。
41
- * 祝日が長く続くとき、"after-holiday" の規則は、本来の日が振り替わる先の日より 31 日を超えて前にあると振り替わらない
42
- * (振替元をさかのぼるのは 31 日まで。祝日の前後の規則は連続の長さによらず当てはまる。長い休業は closedDates・
43
- * closedAnnualDates で書く。decisions.md の 24 番)。
41
+ * 祝日が長く続くとき、"after-holiday" の規則の本来の日が、振り替わる先の日より 31 日を超えて前にあると振り替えられず、
42
+ * 連続が明けた日の判定が code: "holiday-run-too-long" の例外になる(振替元をさかのぼるのは 31 日まで。祝日の前後の規則は
43
+ * 連続の長さによらず当てはまる。長い休業は closedDates・closedAnnualDates で書く。decisions.md の 24 番)。
44
44
  *
45
45
  * 項目を足すときのバージョンは RELEASING.md の区分の表による。1.0.0 以降、マイナーバージョンで足す項目は省略可能なものに限る
46
46
  * (必須にすると、自作の提供元が型エラーになるため)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bizdays-toolkit",
3
- "version": "0.31.9",
3
+ "version": "0.32.1",
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",