bizdays-toolkit 0.31.3 → 0.31.5

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,37 @@ Entries from 0.31.0 are in English. Earlier entries remain in Japanese (their **
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.31.5] - 2026-11-11
10
+
11
+ This version fixes results and errors that did not keep the guide, the type descriptions and the design decisions, and corrects documents. Schedules with `value: undefined` in a specific date, an annual date or a recurring rule now return `undefined` on those days, a wrong weekday number in three places now throws `invalid-weekday` instead of `invalid-option`, a schedule with both `sameAs` and `value` in `holidayPolicy` now throws, and calls that took an instant in the years BC or a year outside 1000–9999 now throw `out-of-range`. Other results do not change.
12
+
13
+ ### Fixed
14
+
15
+ - Schedules: a specific date, an annual date or a recurring rule written with `value: undefined` was dropped, so the day took the value of its weekday (for example, `dates: [{ date: "2026-12-31", value: undefined }]` returned the usual weekday value on 31 December, and a calendar made from the schedule with `(v) => v !== undefined` treated the day as open), while the guide says that `value: undefined` is the value `undefined` (as it already was in `weekdayValues` and `holidayPolicy`). These rules now apply and return `undefined` with their `reason` and `optionPath`. A rule without a `value` key still throws `invalid-option`. If you wrote `value: undefined` to mean "no rule", remove the rule
16
+ - A wrong weekday number in `weekStart`, and in an element of `weekdays` or `skipWeekdays` of a recurring rule (such as `7`, `-1`, `1.5` or `"1"`), threw `invalid-option`, while the same mistake in `closedWeekdays`, `weekday` and `holidayPolicy.sameAs` threw `invalid-weekday`. They now all throw `invalid-weekday` (the diagnostics report the same code); an empty array, a missing `weekStart` and a list with every weekday or with the rule's own weekday are still `invalid-option`. The rule is now written in the design decisions (8). If you branch on `invalid-option` for these, branch on `invalid-weekday`
17
+ - Schedules: `holidayPolicy` with both `sameAs` and `value` (such as `{ sameAs: 0, value: 99 }`, which can come from merging shared options deeply) silently used `sameAs`. It now throws `invalid-option`, as the design decisions (8) say for conflicting options. An explicit `sameAs: undefined` is now the same as leaving it out (design decisions 6): `{ sameAs: undefined, value: 9 }` uses the value, and `{ sameAs: undefined }` alone throws `invalid-option` (it threw `invalid-weekday`). `value: undefined` is still a value
18
+ - A Temporal-like date with a calendar other than ISO (such as `{ year: 2026, month: 11, day: 23, calendarId: "japanese" }`) threw `invalid-input` as a `RangeError`, while the design decisions (3) and the guide say that `invalid-input` is a `TypeError`. It is now a `TypeError` (the code is unchanged). If you caught it with `instanceof RangeError`, use `isBizdaysError` and `code`
19
+ - `migrateCalendarOptions` and `migrateScheduleOptions` treated an old name and its new name as a conflict when one of them was an explicit `undefined` (such as `{ closedAnnual: ["12-31"], closedAnnualDates: undefined }`), so they left the old name, which `createCalendar` reads without a conflict (design decisions 6). They now keep the one with a value under the new name, in either order of the keys. The elements of `changes` are now frozen, as the design decisions (4) say for returned objects
20
+ - An instant (a `Date` or a Temporal `Instant`) in the years 1000–9999 BC was converted to a date in the same year AD (for example, 15 January 1501 BC became `"1501-01-15"`), because the year was read without its era. It now throws `out-of-range`, as the design decisions (1) say. This affects every call that takes an instant, such as `toDateString`, `today`, `dateOf` and `isBusinessDay`, also with `outOfRangePolicy: "ignore"`
21
+ - `toInstant` and `instantOf` threw `out-of-range` for 1000-01-01 and 9999-12-31 (and, in some time zones, 1000-01-02 and 9999-12-30), although the date is within the years 1000–9999 (design decisions 1 limit dates; the instant itself may fall just outside those years in UTC, such as `+010000-01-01T10:59:00.000Z` for 9999-12-31 23:59 in `Pacific/Pago_Pago`). They now return the instant
22
+ - `holidaysInYear` of a calendar or a schedule without a holiday provider, or with `outOfRangePolicy: "ignore"` (and of calendars combined from them or made from such a schedule), returned an empty list for a year outside 1000–9999, while a calendar with the default policy threw `out-of-range`. It now throws `out-of-range` in every case; the rule is now written in the design decisions (1). If you relied on the empty list, check the year first
23
+ - Type descriptions: `searchDayLimit` (of `createCalendar`, `combineCalendars` and `createCalendarFromSchedule`) mentioned only the search for a business day; it now also says that `nextClosedDay` and `previousClosedDay` throw `no-closed-day` past the limit. `KnownErrorCode` now says that `out-of-range` also covers an instant outside the years 1000–9999 and a year outside them passed to `holidaysInYear`. `AnnualDate`, `AnnualRange`, `ScheduleAnnualDate` and `ScheduleAnnualRange` now say that a month and day that exists in no year (such as `"11-31"`) is `invalid-annual-date` and that `"02-29"` matches only in leap years. `wales` said that every holiday has a Welsh name; one-off bank holidays without a Welsh name on GOV.UK (such as the 2002 Golden Jubilee) have no `names.cy`
24
+ - Documentation: the README did not list `dataVersion` among the members of a holiday provider, although it is required (a provider without it throws `invalid-provider`). The guide and the design decisions (17) said that, with `unconfirmedHolidayPolicy: "throw"`, an nth-business-day rule evaluates every day of its month unless the options do not use holidays at all; in fact the count follows the calendar it is made on: a calendar counts on its options without its recurring rules, so its count looks up holidays only when `holidayPolicy` is not `"ignore"`, and a schedule's rule follows its `calendar`. The documents now say so; the behaviour is kept because it is the one that does not throw on days a prediction cannot affect (results are unchanged)
25
+ - Documentation: the design decisions (12) could be read as moving an annual date `"02-29"` to February 28 in other years; they now say that annual dates are not moved (as before, `"02-29"` matches only in leap years, and a month and day that exists in no year is `invalid-annual-date`), and the guide says the same. The guide's table of UK providers now says that Welsh names are included where GOV.UK has them, and the guide's section on the supported years now covers instants and the year of `holidaysInYear`. The design decisions (28) gave 1998 instead of 2000 as the first year of the government lists, and (4) now lists the returned objects that are not frozen (the `options` of the migration functions and the `Date` of `toInstant`). Results are unchanged
26
+
27
+ ## [0.31.4] - 2026-11-10
28
+
29
+ This version fixes calls that threw on days that do not affect their result, makes duplicate holiday providers count once as the design decisions say, and corrects type descriptions, messages and documents. Results of calls that did not throw do not change.
30
+
31
+ ### Fixed
32
+
33
+ - `adjust` with `"modified-following"` or `"modified-preceding"`, and `dueDate`, `closingMonth` and `closingPeriod` that use these conventions, looked at the next (or previous) month before searching the current month, so they threw on a day outside the month that cannot change the result: for example, `adjust("2028-12-30", { convention: "modified-following" })` on an English calendar with `unconfirmedHolidayPolicy: "throw"` threw `unconfirmed-holiday` for 1 January 2029, and on a Japanese calendar closed from 29 December to 3 January the same call for 2099-12-31 threw `out-of-range`; with a small `searchDayLimit`, a call threw `no-business-day` while searching a closed next month although the current month had a business day. They now search the current month first and cross the month only when it has no business day (design decisions 21). Returned dates are unchanged. A call that still throws may now throw a different code (`unconfirmed-holiday`, `out-of-range` or `no-business-day`), because the days are evaluated in a different order
34
+ - A calendar or a schedule given the same holiday provider object more than once (such as `[jp, jp]`) counted it twice, while the design decisions (24) say it is counted once: `providers` listed it twice and the option diagnostics reported the same provider error for each occurrence. Duplicates are now removed; diagnostics keep the position you wrote (`holidayProvider[2]` for the third entry), and when only one provider remains, as with `[jp, jp]`, they use `holidayProvider` as for a single provider. Holidays and business days are unchanged
35
+ - Error messages: `unconfirmed-holiday` said that "the result would depend on a predicted holiday", which is not always true (a search or an nth-business-day rule may look up a predicted holiday that does not change the result); it now says that the evaluation looked up a predicted holiday. The guide lists the days an nth-business-day rule evaluates
36
+ - Type descriptions: `unconfirmedHolidayPolicy` described when it matters with an outdated condition; it now refers to the guide. `ScheduleDayInfo.name` and `holiday` used option names from before 0.30.0. `outOfRangePolicy` and `unconfirmedHolidayPolicy` of `HolidayLookup` now say that a combined calendar shows a summary. `closedRecurringRules` and `recurringRules` listed only some of the rule forms; they now refer to the guide. `renameSubstitute` now says that `names` are kept even when the names are changed, as the design decisions (26) say
37
+ - Documentation: the provider guide and `withSubstituteDays` said only that a substitute day can move into the next year; with `"previous"` it can also move into the previous year, and the provider returns it as part of the year it falls in. The design decisions (2) now explain why the policies of a combined calendar have the closed type of the options
38
+ - Documentation: the type description of `combineCalendars` and the design decisions (18) still described the holidays of a combined calendar as the union of the providers; they now describe the current behaviour (each calendar is asked, and the holiday of the earlier calendar is taken). The design decisions (24) now state that the holidays of several providers given to one calendar are their union, keeping the holiday of the earlier provider on the same date. Results are unchanged
39
+
9
40
  ## [0.31.3] - 2026-11-09
10
41
 
11
42
  This version fixes results that did not keep what the guide, the type descriptions and the design decisions promise. The results of valid calendars and schedules do not change, except that combined calendars no longer throw on days when none of their calendars throws.
@@ -885,7 +916,9 @@ This version rebuilds the `redundant` diagnostic so that the reported rules can
885
916
 
886
917
  - 日本: 2026 年 2 月の官報(2027 年の春分・秋分の日)まで反映(`dataVersion: "2026-02"`、`confirmedThrough: 2027`)
887
918
 
888
- [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.3...HEAD
919
+ [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.5...HEAD
920
+ [0.31.5]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.4...v0.31.5
921
+ [0.31.4]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.3...v0.31.4
889
922
  [0.31.3]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.2...v0.31.3
890
923
  [0.31.2]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.1...v0.31.2
891
924
  [0.31.1]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.0...v0.31.1
package/README.md CHANGED
@@ -116,7 +116,7 @@ diagnoseCalendar({
116
116
 
117
117
  ### Other countries and regions
118
118
 
119
- A holiday provider is an object with `id`, `timeZone`, `supportedYears` and `holidaysInYear(year)`. `bizdays-toolkit/provider` exposes `nthWeekdayOfMonth` and `easterSunday`, which most countries' holidays are built from. See [providers.md](https://github.com/inohan77/bizdays-toolkit/blob/main/docs/providers.md).
119
+ A holiday provider is an object with `id`, `timeZone`, `supportedYears`, `dataVersion` (a string) and `holidaysInYear(year)`. `bizdays-toolkit/provider` exposes `nthWeekdayOfMonth` and `easterSunday`, which most countries' holidays are built from. See [providers.md](https://github.com/inohan77/bizdays-toolkit/blob/main/docs/providers.md).
120
120
 
121
121
  ## Documentation
122
122
 
@@ -17,7 +17,8 @@ import type { Holiday } from "./types.ts";
17
17
  */
18
18
  export type HolidayPolicy = "closed" | "open" | "ignore";
19
19
  /**
20
- * 毎年の月日 "MM-DD"(名前付き・有効期間付きも可)。
20
+ * 毎年の月日 "MM-DD"(名前付き・有効期間付きも可)。どの年にもない月日("11-31" など)は invalid-annual-date。
21
+ * "02-29" はうるう年だけに当たる(ほかの年の 2 月 28 日・3 月 1 日に読み替えない。decisions.md の 12 番)。
21
22
  * @public
22
23
  */
23
24
  export type AnnualDate = string | ({
@@ -25,7 +26,8 @@ export type AnnualDate = string | ({
25
26
  readonly name?: string;
26
27
  } & EffectivePeriod);
27
28
  /**
28
- * 毎年の月日の期間(from > to なら年をまたぐ。例: 12-31 〜 01-03)。
29
+ * 毎年の月日の期間(from > to なら年をまたぐ。例: 12-31 〜 01-03)。端の月日は AnnualDate と同じ。
30
+ * うるう年でない年は、端の "02-29" を除いた間の日だけを含む(from: "02-20", to: "02-29" は 2 月 28 日まで)。
29
31
  * @public
30
32
  */
31
33
  export interface AnnualRange extends EffectivePeriod {
@@ -64,7 +66,7 @@ export interface CalendarOptions<Kind extends string = string> extends HolidaySo
64
66
  /** 臨時営業日(ほかのすべての規則より優先) */
65
67
  readonly openDates?: readonly (SpecificDate | DateRange)[];
66
68
  /**
67
- * 繰り返しの休業日(毎週・隔週などの周期・毎月の第 n 曜日・毎月の日)。
69
+ * 繰り返しの休業日。書ける規則の形はガイドの「Recurring rules」の表(曜日・周期・月の日・第 n 営業日・祝日・祝日の前後など)。
68
70
  * 祝日に当たったときの扱いは規則ごとに holidayOverlapPolicy で指定する(既定: "under-holiday")。
69
71
  * 有効期間(effectiveFrom・effectiveTo)を付けると、期間の外では書かれていないのと同じに扱う
70
72
  */
@@ -73,7 +75,10 @@ export interface CalendarOptions<Kind extends string = string> extends HolidaySo
73
75
  readonly openRecurringRules?: readonly RecurringRule<Kind>[];
74
76
  /** 祝日の扱い(既定: "closed") */
75
77
  readonly holidayPolicy?: HolidayPolicy;
76
- /** 営業日を探すときに調べる最大日数(既定: 3660)。超えたら code: "no-business-day" の RangeError */
78
+ /**
79
+ * 営業日・休業日を探すときに調べる最大日数(既定: 3660)。超えたら、営業日の探索は code: "no-business-day"、
80
+ * 休業日の探索(nextClosedDay・previousClosedDay)は code: "no-closed-day" の RangeError
81
+ */
77
82
  readonly searchDayLimit?: number;
78
83
  /** @deprecated 0.30.0 で closedAnnualDates に改名した。1.0.0 で削除する */
79
84
  readonly closedAnnual?: readonly (AnnualDate | AnnualRange)[];
@@ -147,7 +152,10 @@ export interface CombineCalendarsOptions {
147
152
  * "any": いずれかのカレンダーが営業日(例: 複数の店舗のどこかが開いている日)
148
153
  */
149
154
  readonly open: "all" | "any";
150
- /** 営業日を探すときに調べる最大日数(既定: 3660)。超えたら code: "no-business-day" の RangeError */
155
+ /**
156
+ * 営業日・休業日を探すときに調べる最大日数(既定: 3660)。超えたら、営業日の探索は code: "no-business-day"、
157
+ * 休業日の探索(nextClosedDay・previousClosedDay)は code: "no-closed-day" の RangeError
158
+ */
151
159
  readonly searchDayLimit?: number;
152
160
  /** @deprecated 0.30.0 で searchDayLimit に改名した。1.0.0 で削除する */
153
161
  readonly maxSearchDays?: number;
@@ -290,8 +298,8 @@ export declare function createCalendar<Kind extends string = string>(options?: C
290
298
  *
291
299
  * - dayInfoOn の reason・name・shiftedFrom・optionPath は、合成結果と同じ判定をした最初のカレンダーの結果で、
292
300
  * その番号を decidedBy で返す。入れ子の合成では、内側の番号まで含めた列を decidedByPath で返す。
293
- * holiday・isHoliday・holidaysInYear などは、すべてのカレンダーの同じ参照を呼び、日付ごとに先のカレンダーの祝日を採る
294
- * (同じ提供元は 1 回だけ数え、同じ日付なら先のカレンダーの提供元の祝日)。どれかのカレンダーが投げる日だけ投げる
301
+ * holiday・isHoliday・holidaysInYear などは、すべてのカレンダーの同じ参照を呼び、日付ごとに先のカレンダー
302
+ * (その中では先の提供元)の祝日を採る。方針は各カレンダーのもので、どれかのカレンダーが投げる日だけ投げる
295
303
  * - タイムゾーンはすべてのカレンダーで同じでなければならない(time-zone-conflict)。
296
304
  * 2 つ未満、同じカレンダーを 2 回渡した場合は invalid-argument
297
305
  * - 合成したカレンダーをさらに合成することもできる。規則の診断(diagnoseCalendar)の対象にはならないので、
@@ -304,7 +312,10 @@ export declare function combineCalendars<Kind extends string = string>(calendars
304
312
  * @public
305
313
  */
306
314
  export interface CalendarFromScheduleOptions {
307
- /** 営業日を探すときに調べる最大日数(既定: 3660)。超えたら code: "no-business-day" の RangeError */
315
+ /**
316
+ * 営業日・休業日を探すときに調べる最大日数(既定: 3660)。超えたら、営業日の探索は code: "no-business-day"、
317
+ * 休業日の探索(nextClosedDay・previousClosedDay)は code: "no-closed-day" の RangeError
318
+ */
308
319
  readonly searchDayLimit?: number;
309
320
  /** @deprecated 0.30.0 で searchDayLimit に改名した。1.0.0 で削除する */
310
321
  readonly maxSearchDays?: number;
@@ -53,11 +53,13 @@ export function compileCalendarOptions(c, options) {
53
53
  if (!Number.isInteger(searchDayLimit) || searchDayLimit < 1) {
54
54
  c.error("invalid-option", "searchDayLimit", "must be a positive integer");
55
55
  }
56
- const annual = compileAnnualRules(c, "closedAnnualDates", o["closedAnnualDates"], () => false, true, false);
57
- const open = compileDateRules(c, "openDates", o["openDates"], () => true, true, false);
58
- const closed = compileDateRules(c, "closedDates", o["closedDates"], () => false, true, false);
59
- const openRecurringRules = compileRecurringRules(c, "openRecurringRules", o["openRecurringRules"], () => true, RECURRING_RULE_KEYS, "calendar", writtenKey(places, written, "openRecurringRules"), jpUsage(source));
60
- const closedRecurringRules = compileRecurringRules(c, "closedRecurringRules", o["closedRecurringRules"], () => false, RECURRING_RULE_KEYS, "calendar", writtenKey(places, written, "closedRecurringRules"), jpUsage(source));
56
+ const OPEN = { value: true };
57
+ const CLOSED = { value: false };
58
+ const annual = compileAnnualRules(c, "closedAnnualDates", o["closedAnnualDates"], () => CLOSED, true, false);
59
+ const open = compileDateRules(c, "openDates", o["openDates"], () => OPEN, true, false);
60
+ const closed = compileDateRules(c, "closedDates", o["closedDates"], () => CLOSED, true, false);
61
+ const openRecurringRules = compileRecurringRules(c, "openRecurringRules", o["openRecurringRules"], () => OPEN, RECURRING_RULE_KEYS, "calendar", writtenKey(places, written, "openRecurringRules"), jpUsage(source));
62
+ const closedRecurringRules = compileRecurringRules(c, "closedRecurringRules", o["closedRecurringRules"], () => CLOSED, RECURRING_RULE_KEYS, "calendar", writtenKey(places, written, "closedRecurringRules"), jpUsage(source));
61
63
  return {
62
64
  schedule: {
63
65
  source,
@@ -133,9 +135,12 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
133
135
  return date;
134
136
  }
135
137
  throw open
136
- ? rangeError("no-business-day", `No business day found within ${searchDayLimit} days from ${start}`)
138
+ ? noBusinessDay(start)
137
139
  : rangeError("no-closed-day", `No closed day found within ${searchDayLimit} days from ${start}`);
138
140
  }
141
+ function noBusinessDay(start) {
142
+ return rangeError("no-business-day", `No business day found within ${searchDayLimit} days from ${start}`);
143
+ }
139
144
  function countOpen(from, toExclusive) {
140
145
  let count = 0;
141
146
  for (let n = from; n < toExclusive; n++)
@@ -169,32 +174,28 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
169
174
  }
170
175
  if (isOpen(date))
171
176
  return date;
172
- const month = date.slice(0, 7);
173
177
  switch (convention) {
174
178
  case "following":
175
179
  return search(date, 1);
176
180
  case "preceding":
177
181
  return search(date, -1);
178
- case "modified-following": {
179
- const next = search(date, 1);
180
- if (next.startsWith(month))
181
- return next;
182
- const previous = searchWithin(date, -1, month);
183
- return previous ?? next;
184
- }
185
- case "modified-preceding": {
186
- const previous = search(date, -1);
187
- if (previous.startsWith(month))
188
- return previous;
189
- const next = searchWithin(date, 1, month);
190
- return next ?? previous;
191
- }
182
+ case "modified-following":
183
+ return searchInMonth(date, 1, true) ?? searchInMonth(date, -1, false) ?? search(date, 1);
184
+ case "modified-preceding":
185
+ return searchInMonth(date, -1, true) ?? searchInMonth(date, 1, false) ?? search(date, -1);
192
186
  default:
193
187
  throw rangeError("invalid-argument", `Unknown convention: ${String(convention)}`);
194
188
  }
195
189
  }
196
- function searchWithin(start, step, month) {
197
- for (let date = start; date.startsWith(month); date = addDays(date, step)) {
190
+ function searchInMonth(start, step, limited) {
191
+ const { year, month } = parseMonth(start.slice(0, 7));
192
+ const first = toDayNumber(formatDate(year, month, 1));
193
+ const last = first + lengthOfMonth(year, month) - 1;
194
+ let n = toDayNumber(start);
195
+ for (let i = 0; n >= first && n <= last; i++, n += step) {
196
+ if (limited && i >= searchDayLimit)
197
+ throw noBusinessDay(start);
198
+ const date = fromDayNumber(n);
198
199
  if (isOpen(date))
199
200
  return date;
200
201
  }
@@ -4,25 +4,14 @@
4
4
  * 設定を作るときと同じ検証(IssueCollector)で誤りと知らないキーを集め、誤りがなければ
5
5
  * 規則どうしの関係を調べる。例外は投げず、見つけた問題を配列で返す。
6
6
  *
7
- * - error … createCalendar・createSchedule で例外になる誤り(code は例外と同じ)
8
- * - warning … 作れるが、意図と違う可能性が高いもの
9
- * unknown-option … 知らないキー(作成時は無視される)。近い既知のキーがあれば message に候補を挙げる
10
- * shadowed … 同じ種類の先の規則に完全に覆われ、決して使われない(relatedPath に先の規則)
11
- * never-matches … 当てはまる日がない繰り返しの規則(2 月 30 日、有効期間の中に第 5 水曜日がない、提供元のない設定の祝日の翌日・祝前日、など)
12
- * out-of-range … 個別の日付、または規則の有効期間が祝日の提供元の対応年の外にある(relatedPath に提供元)
13
- * no-business-day … 営業日が 1 日もない設定(営業日カレンダーのみ)
14
- * - info … redundant: 取り除いても結果が変わらない規則・設定(判定に祝日を使わない設定の unconfirmedHolidayPolicy: "throw" を含む)。
15
- * 出た規則はまとめて取り除ける(逐次除去。relatedPath に代わりに決める規則、1 つに定まるときだけ。decisions.md の 31 番)
16
- * expired: 第 2 引数の asOf より前に終わった規則・日付(asOf を渡したときだけ)
17
- * counting-basis: 第 n 営業日の規則(businessDayOfMonth・businessDayOfWeek)の数える基準は繰り返しの規則を除くので、
18
- * 同じ設定の毎週の曜日の規則({ weekday })の曜日は営業日として数えられる(relatedPath にその規則)。
19
- * 有効期間が重なり、使われている曜日の規則ごとに 1 件
7
+ * 重さは error(createCalendar・createSchedule で例外になる誤り。code は例外と同じ)・warning(作れるが、意図と違う可能性が
8
+ * 高いもの)・info(知らせ)の 3 つ。診断のコードと重さの一覧はガイドの診断の表(docs/guide.md の「Option diagnostics」)、
9
+ * redundant の逐次除去と relatedPath は decisions.md の 31 番
20
10
  *
21
11
  * 未確定の祝日の扱い(unconfirmedHolidayPolicy)は診断では常に "accept" で評価する。診断は設定の形を調べるもので、
22
12
  * 祝日が確定しているかどうかは関係がなく、"throw" のまま評価すると例外を握りつぶして「当てはまらない」と誤判定するため
23
13
  *
24
- * 判定の順番(個別の日付 → 毎年の月日 → 繰り返し(over)→ 祝日 → 繰り返し(under・振替先)→ 曜日)は
25
- * 固定なので、shadowed は同じ種類の規則どうしに限って調べる。種類をまたいで使われない規則は
14
+ * 判定の順番は固定(decisions.md の 11 番)なので、shadowed は同じ種類の規則どうしに限って調べる。種類をまたいで使われない規則は
26
15
  * redundant(取り除いても結果が変わらない)として見つかる。
27
16
  * 有効期間(effectiveFrom・effectiveTo)のある規則は期間の包含も、周期(interval・cycle)のある規則は周期の包含も
28
17
  * shadowed の条件にする。redundant の走査の範囲は、周期がそろう長さと、範囲の外にある有効期間まで広げる
@@ -78,7 +67,6 @@ export interface Diagnostic {
78
67
  /** 関係する別の位置(shadowed では覆っている先の規則、out-of-range では祝日の提供元) */
79
68
  readonly relatedPath?: string;
80
69
  }
81
- /** 診断を実行する。祝日の提供元の誤り(年ごとに初めて使うときに分かる)も error として返す */
82
70
  /**
83
71
  * 診断のオプション(第 2 引数)。
84
72
  * @public
@@ -225,10 +225,13 @@ function without(compiled, rule, dropDates) {
225
225
  recurring: compiled.recurring.filter((r) => r !== rule),
226
226
  };
227
227
  }
228
+ const providerPath = (source, i) => source.providers.length === 1
229
+ ? "holidayProvider"
230
+ : `holidayProvider[${source.providerIndexes?.[i] ?? i}]`;
228
231
  function checkProviderData(c, source) {
229
232
  let ok = true;
230
233
  source.providers.forEach((provider, i) => {
231
- const path = source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`;
234
+ const path = providerPath(source, i);
232
235
  const lookup = createHolidayLookup({
233
236
  ...source,
234
237
  providers: [provider],
@@ -405,7 +408,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
405
408
  const { from, to } = p.supportedYears;
406
409
  if (fromYear >= from && toYear <= to)
407
410
  return;
408
- const related = source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`;
411
+ const related = providerPath(source, i);
409
412
  c.warning("out-of-range", rule.path, `The date is outside the years supported by holiday provider ${p.id} (${from}-${to}); ` +
410
413
  (source.outOfRangePolicy === "throw"
411
414
  ? "looking up this date throws"
@@ -431,7 +434,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
431
434
  c.warning("out-of-range", rule.path, `The effective period is outside the years supported by holiday provider ${p.id} (${from}-${to}); ` +
432
435
  (source.outOfRangePolicy === "throw"
433
436
  ? "looking up these dates throws, so this rule is never used"
434
- : "holidays are not considered for these dates"), source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`);
437
+ : "holidays are not considered for these dates"), providerPath(source, i));
435
438
  });
436
439
  }
437
440
  const annualMatches = annual.map(annualBits);
@@ -32,7 +32,10 @@ export type KnownErrorCode =
32
32
  | "invalid-option"
33
33
  /** 祝日の提供元どうしのタイムゾーンが異なり、timeZone の指定が必要 */
34
34
  | "time-zone-conflict"
35
- /** 対応している年の範囲の外(提供元の対応年、または日付の計算が 1000〜9999 年の外に出た)。bizdays-toolkit/provider の関数の年の引数の誤りは invalid-argument */
35
+ /**
36
+ * 対応している年の範囲の外(提供元の対応年、日付の計算や瞬間の変換が 1000〜9999 年の外に出た、祝日の一覧に渡した年が
37
+ * 1000〜9999 の外)。bizdays-toolkit/provider の関数の年の引数の誤りは invalid-argument
38
+ */
36
39
  | "out-of-range"
37
40
  /** 判定が未確定の祝日(confirmed: false)に触れた(unconfirmedHolidayPolicy: "throw") */
38
41
  | "unconfirmed-holiday"
@@ -29,9 +29,7 @@ export function validateTimeZone(timeZone) {
29
29
  throw rangeError("invalid-time-zone", `Invalid time zone: ${describeValue(timeZone)}`);
30
30
  }
31
31
  }
32
- export function instantToCivil(epochMilliseconds, timeZone) {
33
- if (!Number.isFinite(epochMilliseconds))
34
- throw rangeError("invalid-time", "Invalid instant");
32
+ function wallParts(epochMilliseconds, timeZone) {
35
33
  const parts = formatterFor(timeZone).formatToParts(new Date(epochMilliseconds));
36
34
  const get = (type) => {
37
35
  const p = parts.find((x) => x.type === type);
@@ -40,10 +38,22 @@ export function instantToCivil(epochMilliseconds, timeZone) {
40
38
  return Number(p.value);
41
39
  };
42
40
  return {
43
- date: formatDate(get("year"), get("month"), get("day")),
44
- minutes: get("hour") * 60 + get("minute"),
41
+ year: get("year"),
42
+ month: get("month"),
43
+ day: get("day"),
44
+ hour: get("hour"),
45
+ minute: get("minute"),
45
46
  };
46
47
  }
48
+ export function instantToCivil(epochMilliseconds, timeZone) {
49
+ if (!Number.isFinite(epochMilliseconds))
50
+ throw rangeError("invalid-time", "Invalid instant");
51
+ if (new Date(epochMilliseconds).getUTCFullYear() < 999) {
52
+ throw rangeError("out-of-range", "Instant out of range (1000-9999)");
53
+ }
54
+ const { year, month, day, hour, minute } = wallParts(epochMilliseconds, timeZone);
55
+ return { date: formatDate(year, month, day), minutes: hour * 60 + minute };
56
+ }
47
57
  function wallTime(hour, minute) {
48
58
  if (!Number.isInteger(hour) ||
49
59
  hour < 0 ||
@@ -101,7 +111,7 @@ export function toCivil(input, timeZone) {
101
111
  return instantToCivil(input.epochMilliseconds, timeZone);
102
112
  if (isDateLike(input)) {
103
113
  if (input.calendarId !== undefined && input.calendarId !== "iso8601") {
104
- throw rangeError("invalid-input", `Unsupported calendar: ${input.calendarId} (only iso8601)`);
114
+ throw typeError("invalid-input", `Unsupported calendar: ${input.calendarId} (only iso8601)`);
105
115
  }
106
116
  if (!Number.isInteger(input.year) || input.year < 1000 || input.year > 9999) {
107
117
  throw rangeError("invalid-date", `Invalid date: year must be an integer from 1000 to 9999: ${describeValue(input.year)}`);
@@ -129,10 +139,8 @@ export function civilToInstant(date, minutes, timeZone) {
129
139
  const { year, month, day } = parseDate(date);
130
140
  const wall = Date.UTC(year, month - 1, day, Math.floor(minutes / 60), minutes % 60);
131
141
  const offsetAt = (ms) => {
132
- const civil = instantToCivil(ms, timeZone);
133
- const c = parseDate(civil.date);
134
- const m = civil.minutes ?? 0;
135
- return Date.UTC(c.year, c.month - 1, c.day, Math.floor(m / 60), m % 60) - ms;
142
+ const w = wallParts(ms, timeZone);
143
+ return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute) - ms;
136
144
  };
137
145
  const before = offsetAt(wall - 86_400_000);
138
146
  const after = offsetAt(wall + 86_400_000);
@@ -30,16 +30,20 @@ function renameObject(value, places, path, changes) {
30
30
  for (const [key, v] of Object.entries(value)) {
31
31
  const r = RENAMED_KEYS.find((x) => places.includes(x.place) && x.from === key);
32
32
  if (r === undefined) {
33
- out[key] = v;
33
+ const renamedFrom = RENAMED_KEYS.some((x) => places.includes(x.place) && x.to === key && Object.hasOwn(value, x.from));
34
+ if (!(renamedFrom && v === undefined))
35
+ out[key] = v;
34
36
  continue;
35
37
  }
36
- if (Object.hasOwn(value, r.to)) {
37
- changes.push({ path: join(path, key), from: r.from, to: r.to, conflicting: true });
38
+ const hasTo = Object.hasOwn(value, r.to);
39
+ if (v !== undefined && hasTo && value[r.to] !== undefined) {
40
+ changes.push(Object.freeze({ path: join(path, key), from: r.from, to: r.to, conflicting: true }));
38
41
  out[key] = v;
39
42
  continue;
40
43
  }
41
- changes.push({ path: join(path, key), from: r.from, to: r.to });
42
- out[r.to] = v;
44
+ changes.push(Object.freeze({ path: join(path, key), from: r.from, to: r.to }));
45
+ if (v !== undefined || !hasTo)
46
+ out[r.to] = v;
43
47
  }
44
48
  return out;
45
49
  }
@@ -49,7 +53,7 @@ function renameValues(value, place, key, path, changes) {
49
53
  const r = rules.find((x) => x.from === v);
50
54
  if (!r)
51
55
  return v;
52
- changes.push({ path: at, from: r.from, to: r.to });
56
+ changes.push(Object.freeze({ path: at, from: r.from, to: r.to }));
53
57
  return r.to;
54
58
  };
55
59
  return Array.isArray(value) ? value.map((v, i) => one(v, `${path}[${i}]`)) : one(value, path);
@@ -403,7 +403,7 @@ export type ScheduleRecurringRule<Value, Kind extends string = string> = (Exclud
403
403
  readonly value: Value;
404
404
  };
405
405
  /**
406
- * 毎年の月日 "MM-DD" の値。
406
+ * 毎年の月日 "MM-DD" の値。月日は AnnualDate と同じ(どの年にもない月日は invalid-annual-date、"02-29" はうるう年だけ)。
407
407
  * @public
408
408
  */
409
409
  export interface ScheduleAnnualDate<Value> extends EffectivePeriod {
@@ -412,7 +412,7 @@ export interface ScheduleAnnualDate<Value> extends EffectivePeriod {
412
412
  readonly name?: string;
413
413
  }
414
414
  /**
415
- * 毎年の月日の期間の値(from > to なら年をまたぐ。例: 12-31 〜 01-03)。
415
+ * 毎年の月日の期間の値(from > to なら年をまたぐ。例: 12-31 〜 01-03)。端の月日と "02-29" の扱いは AnnualRange と同じ。
416
416
  * @public
417
417
  */
418
418
  export interface ScheduleAnnualRange<Value> extends EffectivePeriod {
@@ -465,7 +465,7 @@ export interface HolidaySourceOptions<Kind extends string = string> {
465
465
  * "throw" にすると、dayInfoOn・isBusinessDay に限らず、営業日の探索・調整・期日の計算の途中で評価した日や、祝日の翌日・祝前日の
466
466
  * 規則が見る隣の日を含め、祝日を引いた日が未確定の祝日なら unconfirmed-holiday の RangeError を投げる。
467
467
  * holidaysInYear・holidaysBetween は投げないので、影響する日の列挙に使える。
468
- * 判定に祝日を使う設定(holidayPolicy が "ignore" でない、または祝日に従属する規則がある)でだけ意味がある
468
+ * 判定が祝日に依存する設定でだけ意味がある(条件はガイドの「Unconfirmed holidays」。decisions.md の 17 番)
469
469
  */
470
470
  readonly unconfirmedHolidayPolicy?: "accept" | "throw";
471
471
  }
@@ -478,7 +478,7 @@ export interface ScheduleOptions<Value, Kind extends string = string> extends Ho
478
478
  readonly weekdayValues: readonly [Value, Value, Value, Value, Value, Value, Value];
479
479
  /** 祝日の値の決め方(既定: "ignore") */
480
480
  readonly holidayPolicy?: ScheduleHolidayPolicy<Value>;
481
- /** 繰り返しの規則(毎週・毎月の第 n 曜日・毎月の日)の値 */
481
+ /** 繰り返しの規則の値(書ける規則の形はガイドの「Recurring rules」の表) */
482
482
  readonly recurringRules?: readonly ScheduleRecurringRule<Value, Kind>[];
483
483
  /** 毎年の月日の値 */
484
484
  readonly annualDates?: readonly (ScheduleAnnualDate<Value> | ScheduleAnnualRange<Value>)[];
@@ -512,9 +512,9 @@ export interface ScheduleDayInfo<Value, Kind extends string = string> {
512
512
  readonly value: Value;
513
513
  /** 値を決めた規則 */
514
514
  readonly reason: ScheduleDayReason;
515
- /** 値を決めた規則の名前(dates・annual・recurring の name、祝日なら祝日名) */
515
+ /** 値を決めた規則の名前(dates・annualDates・recurringRules の name、祝日なら祝日名) */
516
516
  readonly name?: string;
517
- /** その日が祝日なら祝日(holiday の規則に関係なく付く) */
517
+ /** その日が祝日なら祝日(holidayPolicy に関係なく付く) */
518
518
  readonly holiday?: Holiday<Kind>;
519
519
  /** 祝日から振り替えられた規則で値が決まった場合、振替の元の日付(holidayOverlapPolicy: "after-holiday") */
520
520
  readonly shiftedFrom?: DateString;
@@ -536,9 +536,9 @@ export interface HolidayLookup<Kind extends string = string> {
536
536
  readonly timeZone: string;
537
537
  /** 祝日の提供元 */
538
538
  readonly providers: readonly HolidayProvider<Kind>[];
539
- /** 祝日の提供元の対応年を外れた日付の扱い(設定の outOfRangePolicy) */
539
+ /** 祝日の提供元の対応年を外れた日付の扱い(設定の値。合成したカレンダーでは構成カレンダーの要約で、どれかが "throw" なら "throw"。decisions.md の 17 番) */
540
540
  readonly outOfRangePolicy: "throw" | "ignore";
541
- /** 未確定の祝日に触れたときの扱い(設定の unconfirmedHolidayPolicy) */
541
+ /** 未確定の祝日に触れたときの扱い(設定の値。合成したカレンダーでは構成カレンダーの要約で、どれかが "throw" なら "throw"。decisions.md の 17 番) */
542
542
  readonly unconfirmedHolidayPolicy: "accept" | "throw";
543
543
  /** @deprecated 0.30.0 で outOfRangePolicy に改名した(同じ値)。1.0.0 で削除する */
544
544
  readonly outOfRange: "throw" | "ignore";
@@ -80,14 +80,14 @@ export function compileDateRules(c, path, entries, valueOf, allowString, valueKe
80
80
  c.error("invalid-option", p, allowString ? "must be a date string or an object" : "must be an object");
81
81
  return;
82
82
  }
83
- const value = valueOf(entry, p);
83
+ const got = valueOf(entry, p);
84
84
  const name = checkName(c, p, entry["name"]);
85
85
  const defined = withoutUndefined(entry, DATE_SHAPE_KEYS);
86
86
  if ("date" in defined) {
87
87
  checkUnknownKeys(c, p, defined, ["date", "name", ...(valueKey ? ["value"] : [])]);
88
88
  const n = checkDate(c, `${p}.date`, entry["date"]);
89
- if (n !== undefined && value !== undefined)
90
- rules.push({ path: p, from: n, to: n, value, name });
89
+ if (n !== undefined && got !== undefined)
90
+ rules.push({ path: p, from: n, to: n, value: got.value, name });
91
91
  return;
92
92
  }
93
93
  if (!("from" in defined) || !("to" in defined)) {
@@ -103,8 +103,8 @@ export function compileDateRules(c, path, entries, valueOf, allowString, valueKe
103
103
  c.error("invalid-range", p, `"from" must not be after "to" (${String(entry["from"])} > ${String(entry["to"])})`);
104
104
  return;
105
105
  }
106
- if (value !== undefined)
107
- rules.push({ path: p, from, to, value, name });
106
+ if (got !== undefined)
107
+ rules.push({ path: p, from, to, value: got.value, name });
108
108
  });
109
109
  return rules;
110
110
  }
@@ -123,7 +123,7 @@ export function compileAnnualRules(c, path, entries, valueOf, allowString, value
123
123
  c.error("invalid-option", p, allowString ? "must be an annual date string (MM-DD) or an object" : "must be an object");
124
124
  return;
125
125
  }
126
- const value = valueOf(entry, p);
126
+ const got = valueOf(entry, p);
127
127
  const name = checkName(c, p, entry["name"]);
128
128
  const period = checkPeriod(c, p, entry);
129
129
  const defined = withoutUndefined(entry, DATE_SHAPE_KEYS);
@@ -135,8 +135,8 @@ export function compileAnnualRules(c, path, entries, valueOf, allowString, value
135
135
  ...PERIOD_KEYS,
136
136
  ]);
137
137
  const md = checkMonthDay(c, `${p}.date`, entry["date"]);
138
- if (md !== undefined && value !== undefined && period) {
139
- rules.push({ path: p, from: md, to: md, value, name, ...period });
138
+ if (md !== undefined && got !== undefined && period) {
139
+ rules.push({ path: p, from: md, to: md, value: got.value, name, ...period });
140
140
  }
141
141
  return;
142
142
  }
@@ -153,8 +153,8 @@ export function compileAnnualRules(c, path, entries, valueOf, allowString, value
153
153
  ]);
154
154
  const from = checkMonthDay(c, `${p}.from`, entry["from"]);
155
155
  const to = checkMonthDay(c, `${p}.to`, entry["to"]);
156
- if (from !== undefined && to !== undefined && value !== undefined && period) {
157
- rules.push({ path: p, from, to, value, name, ...period });
156
+ if (from !== undefined && to !== undefined && got !== undefined && period) {
157
+ rules.push({ path: p, from, to, value: got.value, name, ...period });
158
158
  }
159
159
  });
160
160
  return rules;
@@ -189,10 +189,10 @@ const ON_HOLIDAY_RULES = [
189
189
  ];
190
190
  const isDayOfMonth = (v) => v === -1 || (Number.isInteger(v) && v >= 1 && v <= 31);
191
191
  const isMonth = (v) => Number.isInteger(v) && v >= 1 && v <= 12;
192
- function checkSet(c, path, raw, valid, expected) {
192
+ function checkSet(c, path, raw, valid, expected, elementCode = "invalid-option") {
193
193
  const list = Array.isArray(raw) ? raw : [raw];
194
194
  if (list.length === 0 || !list.every(valid)) {
195
- c.error("invalid-option", path, `must be ${expected}, or a non-empty array of them`);
195
+ c.error(list.length === 0 ? "invalid-option" : elementCode, path, `must be ${expected}, or a non-empty array of them`);
196
196
  return undefined;
197
197
  }
198
198
  return new Set(list);
@@ -216,7 +216,7 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
216
216
  checkUnknownKeys(c, p, renamedEntry, keys);
217
217
  const entry = withoutUndefined(renamedEntry);
218
218
  const nationalOfJp = jp !== "none" && reportNational(c, `${written}.kinds`, entry["kinds"], jp === "mixed");
219
- const value = valueOf(entry, p);
219
+ const got = valueOf(entry, p);
220
220
  const name = checkName(c, p, entry["name"]);
221
221
  const hasWeekday = "weekday" in entry;
222
222
  const hasDay = "dayOfMonth" in entry;
@@ -372,10 +372,14 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
372
372
  if (hasBusinessWeek) {
373
373
  if (isWeekday(entry["weekStart"]))
374
374
  weekStart = entry["weekStart"];
375
- else {
375
+ else if (!("weekStart" in entry)) {
376
376
  c.error("invalid-option", `${p}.weekStart`, 'is required with "businessDayOfWeek": an integer from 0 (Sunday) to 6 (Saturday) (the first day of the week)');
377
377
  ok = false;
378
378
  }
379
+ else {
380
+ c.error("invalid-weekday", `${p}.weekStart`, "must be an integer from 0 (Sunday) to 6 (Saturday) (the first day of the week)");
381
+ ok = false;
382
+ }
379
383
  }
380
384
  if (entry["holidayOverlapPolicy"] === "after-holiday") {
381
385
  c.error("invalid-option", `${p}.holidayOverlapPolicy`, `"after-holiday" cannot be used with "${key}" (shifting the nth business day has no meaning; use "under-holiday" or "over-holiday")`);
@@ -469,7 +473,7 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
469
473
  ok = false;
470
474
  }
471
475
  else {
472
- const set = checkSet(c, `${p}.weekdays`, entry["weekdays"], isWeekday, "a weekday (0 = Sunday to 6 = Saturday)");
476
+ const set = checkSet(c, `${p}.weekdays`, entry["weekdays"], isWeekday, "a weekday (0 = Sunday to 6 = Saturday)", "invalid-weekday");
473
477
  if (set)
474
478
  weekdays = set;
475
479
  else
@@ -508,7 +512,7 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
508
512
  ok = false;
509
513
  }
510
514
  else {
511
- const set = checkSet(c, `${p}.skipWeekdays`, entry["skipWeekdays"], isWeekday, "a weekday (0 = Sunday to 6 = Saturday)");
515
+ const set = checkSet(c, `${p}.skipWeekdays`, entry["skipWeekdays"], isWeekday, "a weekday (0 = Sunday to 6 = Saturday)", "invalid-weekday");
512
516
  if (set === undefined)
513
517
  ok = false;
514
518
  else if (set.size === 7) {
@@ -524,7 +528,7 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
524
528
  }
525
529
  }
526
530
  const period = checkPeriod(c, p, entry);
527
- if (ok && period && value !== undefined) {
531
+ if (ok && period && got !== undefined) {
528
532
  rules.push(Object.freeze({
529
533
  path: p,
530
534
  weekday,
@@ -548,7 +552,7 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
548
552
  weekdays,
549
553
  months,
550
554
  holidayOverlapPolicy: onHoliday,
551
- value,
555
+ value: got.value,
552
556
  name,
553
557
  ...period,
554
558
  }));
@@ -642,7 +646,7 @@ function requiredValue(c) {
642
646
  c.error("invalid-option", path, 'must have "value"');
643
647
  return undefined;
644
648
  }
645
- return entry["value"];
649
+ return { value: entry["value"] };
646
650
  };
647
651
  }
648
652
  function validateProvider(c, path, p) {
@@ -707,10 +711,13 @@ export function compileHolidaySource(c, options) {
707
711
  const raw = options["holidayProvider"];
708
712
  const list = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw];
709
713
  const providers = [];
714
+ const providerIndexes = [];
710
715
  list.forEach((p, i) => {
711
716
  const path = Array.isArray(raw) ? `holidayProvider[${i}]` : "holidayProvider";
712
- if (validateProvider(c, path, p))
717
+ if (validateProvider(c, path, p) && !providers.includes(p)) {
713
718
  providers.push(p);
719
+ providerIndexes.push(i);
720
+ }
714
721
  });
715
722
  let timeZone = "UTC";
716
723
  if (options["timeZone"] !== undefined) {
@@ -738,6 +745,7 @@ export function compileHolidaySource(c, options) {
738
745
  }
739
746
  return {
740
747
  providers: Object.freeze(providers),
748
+ providerIndexes: Object.freeze(providerIndexes),
741
749
  timeZone,
742
750
  outOfRangePolicy: outOfRangePolicy === "ignore" ? "ignore" : "throw",
743
751
  unconfirmedHolidayPolicy: unconfirmed === "throw" ? "throw" : "accept",
@@ -833,7 +841,7 @@ export function createHolidayLookup(source) {
833
841
  const through = provider?.confirmedThrough === undefined
834
842
  ? ""
835
843
  : ` (${provider.id} is confirmed through ${provider.confirmedThrough})`;
836
- throw rangeError("unconfirmed-holiday", `${date} ${h.name} is not yet confirmed${through}; the result would depend on a predicted holiday`);
844
+ throw rangeError("unconfirmed-holiday", `${date} ${h.name} is not yet confirmed${through}; this evaluation looked up a predicted holiday`);
837
845
  }
838
846
  return h;
839
847
  }
@@ -841,6 +849,8 @@ export function createHolidayLookup(source) {
841
849
  function holidaysInYear(year) {
842
850
  if (!Number.isInteger(year))
843
851
  throw rangeError("invalid-argument", `Invalid year: ${describeValue(year)}`);
852
+ if (year < 1000 || year > 9999)
853
+ throw rangeError("out-of-range", `Year out of range (1000-9999): ${year}`);
844
854
  return Object.freeze([...holidayMap(year).values()].sort((a, b) => a.date < b.date ? -1 : a.date > b.date ? 1 : 0));
845
855
  }
846
856
  return {
@@ -937,16 +947,22 @@ export function compileScheduleOptions(c, options) {
937
947
  }
938
948
  let holiday = "ignore";
939
949
  const holidayRaw = renameValue(c, "schedule", "holidayPolicy", writtenKey(["source", "schedule"], written, "holidayPolicy"), o["holidayPolicy"]);
950
+ const hasSameAs = isObject(holidayRaw) && holidayRaw["sameAs"] !== undefined;
951
+ const hasValue = isObject(holidayRaw) && "value" in holidayRaw;
940
952
  if (holidayRaw === undefined || holidayRaw === "ignore") {
941
953
  holiday = "ignore";
942
954
  }
943
- else if (isObject(holidayRaw) && "sameAs" in holidayRaw) {
944
- if (isWeekday(holidayRaw["sameAs"]))
945
- holiday = Object.freeze({ sameAs: holidayRaw["sameAs"] });
955
+ else if (hasSameAs && hasValue) {
956
+ c.error("invalid-option", "holidayPolicy", 'cannot have both "sameAs" and "value"');
957
+ }
958
+ else if (hasSameAs) {
959
+ const sameAs = holidayRaw["sameAs"];
960
+ if (isWeekday(sameAs))
961
+ holiday = Object.freeze({ sameAs });
946
962
  else
947
963
  c.error("invalid-weekday", "holidayPolicy.sameAs", "must be an integer from 0 (Sunday) to 6 (Saturday)");
948
964
  }
949
- else if (isObject(holidayRaw) && "value" in holidayRaw) {
965
+ else if (hasValue) {
950
966
  holiday = Object.freeze({ value: holidayRaw["value"] });
951
967
  }
952
968
  else {
@@ -54,7 +54,8 @@ export interface WithSubstituteDaysOptions<Kind extends string> {
54
54
  /** 振替日に付ける種別(Holiday.kind。例: "substitute"、"observed") */
55
55
  readonly kind: Kind;
56
56
  /**
57
- * 振替日の名称。省略時は元の祝日の name・nameEn(と names)を引き継ぐ(GOV.UK・MOM の流儀)。
57
+ * 振替日の名称(name・nameEn)。省略時は元の祝日のものを引き継ぐ(GOV.UK・MOM の流儀)。names は、名称を変えたときも
58
+ * 元の祝日のものを引き継ぐ(decisions.md の 26 番)。
58
59
  * 変えるなら元の祝日を受け取って返す関数で(例: 日本の「振替休日」、米国の "(observed)")
59
60
  */
60
61
  readonly renameSubstitute?: (holiday: Holiday<Kind>) => {
@@ -83,8 +84,8 @@ export interface WithSubstituteDaysOptions<Kind extends string> {
83
84
  * 振替日は元の祝日の key・names・confirmed を引き継ぎ、kind は options.kind、名称は省略時は元の祝日のもの。
84
85
  *
85
86
  * 入力は同じ年の祝日で、日付が有効・重複がないこと(誤りは invalid-argument・invalid-date・invalid-weekday の例外)。
86
- * 振替日は年をまたぐことがある(12 月 31 日が祝日の国で日曜日なら翌年の 1 月 1 日)。提供元の holidaysInYear は
87
- * その年の日付だけを返す契約なので、そうなる国では翌年の分として扱うこと。
87
+ * 振替日は前後の年に移ることがある(日曜日の 12 月 31 日の振替は翌年の 1 月 1 日、"previous" で土曜日の 1 月 1 日の振替は
88
+ * 前年の 12 月 31 日)。提供元の holidaysInYear はその年の日付だけを返す契約なので、振替日はその日が属する年の分として返すこと。
88
89
  * 国民の休日(2 つの祝日に挟まれた日)のような国に固有の規則は含まない。
89
90
  * 返す祝日はどれも凍結している(入力のまま返す祝日も、契約の項目だけを持つ複製)。
90
91
  *
@@ -23,7 +23,8 @@ export type UkHoliday = Holiday<UkHolidayKind>;
23
23
  */
24
24
  export declare const england: HolidayProvider<UkHolidayKind>;
25
25
  /**
26
- * Wales の bank holidays の提供元(GOV.UK の England and Wales)。名称にウェールズ語(names.cy)が付く。
26
+ * Wales の bank holidays の提供元(GOV.UK の England and Wales)。GOV.UK のウェールズ語版に名称がある祝日には、
27
+ * ウェールズ語の名称(names.cy)が付く(公式の名称がない臨時の祝日には付かない)。
27
28
  * @public
28
29
  */
29
30
  export declare const wales: HolidayProvider<UkHolidayKind>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bizdays-toolkit",
3
- "version": "0.31.3",
3
+ "version": "0.31.5",
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",