bizdays-toolkit 0.22.2 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
- import { daysInMonth, fromDayNumber, isValidDate, parseDate, toDayNumber, } from "./date.js";
1
+ import { lengthOfMonth, fromDayNumber, isValidDate, parseDate, toDayNumber, } from "./date.js";
2
2
  import { compileCalendarOptions } from "./calendar.js";
3
3
  import { IssueCollector, rangeError } from "./errors.js";
4
+ import { RENAMED_KEYS } from "./renamed.js";
4
5
  import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, inPeriod, matchMonthDay, matchPattern, } from "./schedule.js";
5
6
  function editDistance(a, b) {
6
7
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
@@ -17,6 +18,11 @@ function editDistance(a, b) {
17
18
  return d[a.length][b.length];
18
19
  }
19
20
  function closestKey(key, known) {
21
+ const renamed = RENAMED_KEYS.filter((r) => known.includes(r.to));
22
+ const found = closestOf(key, [...known, ...renamed.map((r) => r.from)]);
23
+ return renamed.find((r) => r.from === found && !known.includes(found))?.to ?? found;
24
+ }
25
+ function closestOf(key, known) {
20
26
  const lower = key.toLowerCase();
21
27
  const sameCase = known.find((k) => k.toLowerCase() === lower);
22
28
  if (sameCase !== undefined)
@@ -73,7 +79,7 @@ function scanWindow(source, rules, cycle) {
73
79
  const years = source.providers.map((p) => p.supportedYears);
74
80
  let from;
75
81
  let to;
76
- if (source.outOfRange === "ignore") {
82
+ if (source.outOfRangePolicy === "ignore") {
77
83
  from = Math.min(...years.map((r) => r.from));
78
84
  to = Math.max(...years.map((r) => r.to));
79
85
  }
@@ -136,7 +142,7 @@ function matchesAnyDay(rule, cycle) {
136
142
  const LEAP_MONTH_DAYS = (() => {
137
143
  const list = [];
138
144
  for (let m = 1; m <= 12; m++) {
139
- for (let d = 1; d <= daysInMonth(2028, m); d++) {
145
+ for (let d = 1; d <= lengthOfMonth(2028, m); d++) {
140
146
  list.push(`${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`);
141
147
  }
142
148
  }
@@ -168,15 +174,15 @@ function cycleCovers(earlier, later) {
168
174
  });
169
175
  }
170
176
  function canCover(earlier, later) {
171
- switch (later.onHolidayRule) {
177
+ switch (later.holidayOverlapPolicy) {
172
178
  case "over-holiday":
173
- return earlier.onHolidayRule === "over-holiday";
179
+ return earlier.holidayOverlapPolicy === "over-holiday";
174
180
  case "under-holiday":
175
- return earlier.onHolidayRule !== "after-holiday";
181
+ return earlier.holidayOverlapPolicy !== "after-holiday";
176
182
  case "after-holiday":
177
- return earlier.onHolidayRule === "after-holiday";
183
+ return earlier.holidayOverlapPolicy === "after-holiday";
178
184
  default: {
179
- const unreachable = later.onHolidayRule;
185
+ const unreachable = later.holidayOverlapPolicy;
180
186
  return unreachable;
181
187
  }
182
188
  }
@@ -216,8 +222,12 @@ function without(compiled, rule, dropDates) {
216
222
  function checkProviderData(c, source) {
217
223
  let ok = true;
218
224
  source.providers.forEach((provider, i) => {
219
- const path = source.providers.length === 1 ? "holidays" : `holidays[${i}]`;
220
- const lookup = createHolidayLookup({ ...source, providers: [provider], outOfRange: "ignore" });
225
+ const path = source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`;
226
+ const lookup = createHolidayLookup({
227
+ ...source,
228
+ providers: [provider],
229
+ outOfRangePolicy: "ignore",
230
+ });
221
231
  const [from, to] = clipYears(provider.supportedYears.from, provider.supportedYears.to);
222
232
  try {
223
233
  for (let y = from; y <= to; y++)
@@ -234,7 +244,11 @@ function analyze(c, compiled, isCalendar) {
234
244
  const { source, dates, annual, recurring } = compiled;
235
245
  if (!checkProviderData(c, source))
236
246
  return;
237
- const lookup = createHolidayLookup({ ...source, unconfirmedHolidays: "accept" });
247
+ const lookup = createHolidayLookup({
248
+ ...source,
249
+ outOfRangePolicy: "ignore",
250
+ unconfirmedHolidayPolicy: "accept",
251
+ });
238
252
  const basis = createBasis(compiled, lookup);
239
253
  const cycle = patternCycle(recurring);
240
254
  const window = scanWindow(source, [...annual, ...recurring], cycle);
@@ -246,9 +260,9 @@ function analyze(c, compiled, isCalendar) {
246
260
  const { from, to } = p.supportedYears;
247
261
  if (fromYear >= from && toYear <= to)
248
262
  return;
249
- const related = source.providers.length === 1 ? "holidays" : `holidays[${i}]`;
263
+ const related = source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`;
250
264
  c.warning("out-of-range", rule.path, `The date is outside the years supported by holiday provider ${p.id} (${from}-${to}); ` +
251
- (source.outOfRange === "throw"
265
+ (source.outOfRangePolicy === "throw"
252
266
  ? "looking up this date throws"
253
267
  : "holidays are not considered for this date"), related);
254
268
  });
@@ -267,12 +281,12 @@ function analyze(c, compiled, isCalendar) {
267
281
  const before = rule.effectiveTo !== null && yearOf(rule.effectiveTo) < from;
268
282
  if (!after && !before)
269
283
  return;
270
- if (source.outOfRange === "throw")
284
+ if (source.outOfRangePolicy === "throw")
271
285
  unused.add(rule);
272
286
  c.warning("out-of-range", rule.path, `The effective period is outside the years supported by holiday provider ${p.id} (${from}-${to}); ` +
273
- (source.outOfRange === "throw"
287
+ (source.outOfRangePolicy === "throw"
274
288
  ? "looking up these dates throws, so this rule is never used"
275
- : "holidays are not considered for these dates"), source.providers.length === 1 ? "holidays" : `holidays[${i}]`);
289
+ : "holidays are not considered for these dates"), source.providers.length === 1 ? "holidayProvider" : `holidayProvider[${i}]`);
276
290
  });
277
291
  }
278
292
  const annualMatches = annual.map(annualBits);
@@ -286,7 +300,7 @@ function analyze(c, compiled, isCalendar) {
286
300
  const recurringBits = recurring.map(patternBits);
287
301
  const holidayOfSafe = (date) => {
288
302
  try {
289
- return lookup.holidayOn(date);
303
+ return lookup.holidayOfDate(date);
290
304
  }
291
305
  catch {
292
306
  return undefined;
@@ -342,7 +356,9 @@ function analyze(c, compiled, isCalendar) {
342
356
  ? "This rule matches no day: no day after a holiday of the selected kinds and keys on the selected weekdays and months within its effective period"
343
357
  : "This rule matches no day: no day before a holiday of the selected kinds and keys on the selected weekdays and months within its effective period"
344
358
  : businessDayBased
345
- ? "This rule matches no day: no month has that many business days of the counting basis in the selected months within its effective period"
359
+ ? rule.weekStart !== null
360
+ ? "This rule matches no day: no week has that many business days of the counting basis in the selected months within its effective period"
361
+ : "This rule matches no day: no month has that many business days of the counting basis in the selected months within its effective period"
346
362
  : rule.effectiveFrom === null && rule.effectiveTo === null
347
363
  ? "This rule matches no day (for example, a day that does not exist in the selected months)"
348
364
  : "This rule matches no day within its effective period");
@@ -350,11 +366,11 @@ function analyze(c, compiled, isCalendar) {
350
366
  }
351
367
  if (businessDayBased &&
352
368
  rule.basis === null &&
353
- rule.onHolidayRule === "over-holiday" &&
369
+ rule.holidayOverlapPolicy === "over-holiday" &&
354
370
  typeof compiled.holiday === "object" &&
355
371
  "value" in compiled.holiday &&
356
372
  compiled.holiday.value === false) {
357
- c.info("redundant", `${rule.path}.onHolidayRule`, 'This option does not change the result: holidays are closed (holidayPolicy: "closed"), so an nth business day is never a holiday');
373
+ c.info("redundant", `${rule.path}.holidayOverlapPolicy`, 'This option does not change the result: holidays are closed (holidayPolicy: "closed"), so an nth business day is never a holiday');
358
374
  }
359
375
  if (businessDayBased && rule.basis === null) {
360
376
  const weekly = recurring.find((r) => r.weekday !== null && r.nth === null && r.interval === null && r.months === null);
@@ -384,6 +400,7 @@ function analyze(c, compiled, isCalendar) {
384
400
  ? r.cycle !== null && cycleCovers(r, rule) && setCovers(r.months, rule.months)
385
401
  : rule.businessDays !== null
386
402
  ? r.businessDays !== null &&
403
+ r.weekStart === rule.weekStart &&
387
404
  r.calendar === rule.calendar &&
388
405
  setCovers(r.businessDays, rule.businessDays) &&
389
406
  setCovers(r.months, rule.months)
@@ -488,23 +505,26 @@ function checkExpired(c, compiled, asOf) {
488
505
  if (r.effectiveTo !== null)
489
506
  ended(r.path, r.effectiveTo, "rule");
490
507
  }
491
- function checkUnconfirmedOption(c, compiled, isCalendar) {
492
- if (compiled.source.unconfirmedHolidays !== "throw")
508
+ function checkUnconfirmedOption(c, compiled) {
509
+ if (compiled.source.unconfirmedHolidayPolicy !== "throw")
493
510
  return;
494
511
  const noProvider = compiled.source.providers.length === 0;
495
- const holidayUnused = compiled.holiday === "weekday" &&
496
- !compiled.recurring.some((r) => r.holiday || r.dayAfterHoliday || r.dayBeforeHoliday || r.onHolidayRule === "after-holiday");
512
+ const holidayUnused = compiled.holiday === "ignore" &&
513
+ !compiled.recurring.some((r) => r.holiday ||
514
+ r.dayAfterHoliday ||
515
+ r.dayBeforeHoliday ||
516
+ r.holidayOverlapPolicy === "after-holiday");
497
517
  if (!noProvider && !holidayUnused)
498
518
  return;
499
- c.info("redundant", "unconfirmedHolidays", noProvider
500
- ? 'unconfirmedHolidays: "throw" has no effect: there is no holiday provider'
501
- : `unconfirmedHolidays: "throw" has no effect on results: holidays are not used (${isCalendar ? 'holidayPolicy: "ignore"' : 'holiday: "weekday"'} and no holiday-based rule); dayInfo still throws when it looks up the holiday to report`);
519
+ c.info("redundant", "unconfirmedHolidayPolicy", noProvider
520
+ ? 'unconfirmedHolidayPolicy: "throw" has no effect: there is no holiday provider'
521
+ : `unconfirmedHolidayPolicy: "throw" has no effect on results: holidays are not used (holidayPolicy: "ignore" and no holiday-based rule); dayInfoOn still throws when it looks up the holiday to report`);
502
522
  }
503
523
  function run(c, compiled, isCalendar, asOf) {
504
524
  if (compiled && !c.hasErrors) {
505
525
  if (asOf !== null)
506
526
  checkExpired(c, compiled, asOf);
507
- checkUnconfirmedOption(c, compiled, isCalendar);
527
+ checkUnconfirmedOption(c, compiled);
508
528
  const before = c.issues.length;
509
529
  try {
510
530
  analyze(c, compiled, isCalendar);
@@ -512,7 +532,7 @@ function run(c, compiled, isCalendar, asOf) {
512
532
  catch (error) {
513
533
  c.issues.length = before;
514
534
  const code = error?.code;
515
- c.error(code === "out-of-range" ? "out-of-range" : "invalid-provider-data", "holidays", error instanceof Error ? error.message : String(error));
535
+ c.error(code === "out-of-range" ? "out-of-range" : "invalid-provider-data", "holidayProvider", error instanceof Error ? error.message : String(error));
516
536
  }
517
537
  }
518
538
  return Object.freeze(c.issues.map(({ unknownKey, knownKeys, ...issue }) => {
@@ -15,7 +15,7 @@ export type KnownErrorCode =
15
15
  /** 月 "YYYY-MM" の形式・値の誤り */
16
16
  | "invalid-month"
17
17
  /** 毎年の月日 "MM-DD" の形式・値の誤り */
18
- | "invalid-month-day"
18
+ | "invalid-annual-date"
19
19
  /** 時刻・日時の形式・値の誤り */
20
20
  | "invalid-time"
21
21
  /** 受け付けない種類の入力 */
@@ -34,7 +34,7 @@ export type KnownErrorCode =
34
34
  | "time-zone-conflict"
35
35
  /** 対応している年の範囲の外 */
36
36
  | "out-of-range"
37
- /** 判定が未確定の祝日(confirmed: false)に触れた(unconfirmedHolidays: "throw") */
37
+ /** 判定が未確定の祝日(confirmed: false)に触れた(unconfirmedHolidayPolicy: "throw") */
38
38
  | "unconfirmed-holiday"
39
39
  /** 祝日の提供元の形式の誤り */
40
40
  | "invalid-provider"
@@ -11,6 +11,7 @@
11
11
  import { type DateString } from "./date.ts";
12
12
  /**
13
13
  * Temporal.PlainDate / PlainDateTime として受け付ける最小限の形。
14
+ * @namingSource temporal
14
15
  * @public
15
16
  */
16
17
  export interface TemporalDateLike {
@@ -23,6 +24,7 @@ export interface TemporalDateLike {
23
24
  }
24
25
  /**
25
26
  * Temporal.Instant / ZonedDateTime として受け付ける最小限の形。
27
+ * @namingSource temporal
26
28
  * @public
27
29
  */
28
30
  export interface TemporalInstantLike {
@@ -35,6 +37,7 @@ export interface TemporalInstantLike {
35
37
  export type DateInput = string | Date | TemporalDateLike | TemporalInstantLike;
36
38
  /**
37
39
  * Temporal.PlainDateTime として受け付ける最小限の形(時刻を持つ TemporalDateLike)。
40
+ * @namingSource temporal
38
41
  * @public
39
42
  */
40
43
  export interface TemporalDateTimeLike extends TemporalDateLike {
@@ -0,0 +1,37 @@
1
+ /**
2
+ * 保存済みの設定を、0.30.0 で改名した新しい名前に書き換える(bizdays-toolkit/diagnose)。
3
+ * 改名の表(renamed.ts)だけを使い、検証はしない(設定の中身の誤りは診断で調べる)。
4
+ */
5
+ import type { CalendarOptions } from "./calendar.ts";
6
+ import type { ScheduleOptions } from "./schedule.ts";
7
+ /**
8
+ * 設定の書き換えの 1 件。path は元の設定の中の位置(旧名のまま)、from・to は書き換える前と後のキーの名前か値。
9
+ * conflicting は、旧名と新しい名前の両方が書かれていて書き換えなかったキー(どちらを使うか読み取れないため)。
10
+ * @public
11
+ */
12
+ export interface OptionChange {
13
+ readonly path: string;
14
+ readonly from: string;
15
+ readonly to: string;
16
+ readonly conflicting?: boolean;
17
+ }
18
+ /**
19
+ * 設定の書き換えの結果。options は新しい普通のオブジェクトで、凍結しない(保存し直すため)。
20
+ * @public
21
+ */
22
+ export interface OptionsMigration<Options> {
23
+ readonly options: Options;
24
+ readonly changes: readonly OptionChange[];
25
+ }
26
+ /**
27
+ * 保存済みの営業日カレンダーの設定の旧名(0.30.0 で改名したキーと値)を、新しい名前に書き換える。
28
+ * 例外を投げるのは options が普通のオブジェクトでないときだけで、設定の中身は検証しない(diagnoseCalendar で調べる)。
29
+ * 新しい名前だけの設定に当てると changes は空で、何度当てても同じ結果になる。知らないキーはそのまま写す。
30
+ * @public
31
+ */
32
+ export declare function migrateCalendarOptions(options: object): OptionsMigration<CalendarOptions>;
33
+ /**
34
+ * 保存済みのスケジュールの設定の旧名(0.30.0 で改名したキーと値)を、新しい名前に書き換える(migrateCalendarOptions と同じ扱い)。
35
+ * @public
36
+ */
37
+ export declare function migrateScheduleOptions<Value>(options: object): OptionsMigration<ScheduleOptions<Value>>;
@@ -0,0 +1,95 @@
1
+ import { typeError } from "./errors.js";
2
+ import { RENAMED_KEYS, RENAMED_VALUES } from "./renamed.js";
3
+ const isPlain = (v) => typeof v === "object" &&
4
+ v !== null &&
5
+ !Array.isArray(v) &&
6
+ (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
7
+ const SHARED_KEYS = new Set(["holidayProvider", "holidays", "calendar", "value"]);
8
+ const VALUE_LISTS = new Set(["weekdayValues", "weekly"]);
9
+ function clone(v) {
10
+ if (Array.isArray(v))
11
+ return v.map(clone);
12
+ if (!isPlain(v))
13
+ return v;
14
+ const out = {};
15
+ for (const [k, x] of Object.entries(v)) {
16
+ out[k] = SHARED_KEYS.has(k)
17
+ ? x
18
+ : VALUE_LISTS.has(k) && Array.isArray(x)
19
+ ? [...x]
20
+ : clone(x);
21
+ }
22
+ return out;
23
+ }
24
+ const join = (path, key) => (path ? `${path}.${key}` : key);
25
+ function usesJp(options) {
26
+ const raw = options["holidayProvider"] ?? options["holidays"];
27
+ const list = Array.isArray(raw) ? raw : [raw];
28
+ return list.some((p) => typeof p === "object" && p !== null && p.id === "JP");
29
+ }
30
+ function renameObject(value, places, path, changes) {
31
+ const out = {};
32
+ for (const [key, v] of Object.entries(value)) {
33
+ const r = RENAMED_KEYS.find((x) => places.includes(x.place) && x.from === key);
34
+ if (r === undefined) {
35
+ out[key] = v;
36
+ continue;
37
+ }
38
+ if (Object.hasOwn(value, r.to)) {
39
+ changes.push({ path: join(path, key), from: r.from, to: r.to, conflicting: true });
40
+ out[key] = v;
41
+ continue;
42
+ }
43
+ changes.push({ path: join(path, key), from: r.from, to: r.to });
44
+ out[r.to] = v;
45
+ }
46
+ return out;
47
+ }
48
+ function renameValues(value, place, key, path, changes) {
49
+ const rules = RENAMED_VALUES.filter((r) => r.place === place && r.key === key);
50
+ const one = (v, at) => {
51
+ const r = rules.find((x) => x.from === v);
52
+ if (!r)
53
+ return v;
54
+ changes.push({ path: at, from: r.from, to: r.to });
55
+ return r.to;
56
+ };
57
+ return Array.isArray(value) ? value.map((v, i) => one(v, `${path}[${i}]`)) : one(value, path);
58
+ }
59
+ function migrate(input, places, ruleLists, policyValueKey) {
60
+ if (!isPlain(input))
61
+ throw typeError("invalid-argument", "options must be a plain object");
62
+ const changes = [];
63
+ const copied = clone(input);
64
+ const jp = usesJp(copied);
65
+ const written = new Map();
66
+ for (const key of Object.keys(copied)) {
67
+ const r = RENAMED_KEYS.find((x) => places.includes(x.place) && x.from === key);
68
+ written.set(r && !Object.hasOwn(copied, r.to) ? r.to : key, key);
69
+ }
70
+ const out = renameObject(copied, places, "", changes);
71
+ for (const list of ruleLists) {
72
+ const rules = out[list];
73
+ if (!Array.isArray(rules))
74
+ continue;
75
+ const at = written.get(list) ?? list;
76
+ out[list] = rules.map((rule, i) => {
77
+ if (!isPlain(rule))
78
+ return rule;
79
+ const renamed = renameObject(rule, ["rule"], `${at}[${i}]`, changes);
80
+ if (jp && renamed["kinds"] !== undefined)
81
+ renamed["kinds"] = renameValues(renamed["kinds"], "rule", "kinds", `${at}[${i}].kinds`, changes);
82
+ return renamed;
83
+ });
84
+ }
85
+ if (policyValueKey !== null && out[policyValueKey] !== undefined) {
86
+ out[policyValueKey] = renameValues(out[policyValueKey], "schedule", policyValueKey, written.get(policyValueKey) ?? policyValueKey, changes);
87
+ }
88
+ return Object.freeze({ options: out, changes: Object.freeze(changes) });
89
+ }
90
+ export function migrateCalendarOptions(options) {
91
+ return migrate(options, ["source", "calendar"], ["closedRecurringRules", "openRecurringRules"], null);
92
+ }
93
+ export function migrateScheduleOptions(options) {
94
+ return migrate(options, ["source", "schedule"], ["recurringRules"], "holidayPolicy");
95
+ }
@@ -39,7 +39,7 @@ export declare function monthOf(input: DateString | MonthString, offset?: number
39
39
  * 締め日で区切ったときに、日付が属する月 "YYYY-MM"。
40
40
  *
41
41
  * 締め日の翌日から次の締め日までを、次の締め日の月とする(例: 20 日締めなら 10 月 21 日〜11 月 20 日が 11 月分)。
42
- * closingDay が -1 またはその月の日数以上なら、締め日はその月の末日(例: 31 日締めの 2 月は 28 日か 29 日締め)。
42
+ * closingDayOfMonth が -1 またはその月の日数以上なら、締め日はその月の末日(例: 31 日締めの 2 月は 28 日か 29 日締め)。
43
43
  *
44
44
  * @example
45
45
  * closingMonth("2026-10-20", 20); // "2026-10"
@@ -47,11 +47,11 @@ export declare function monthOf(input: DateString | MonthString, offset?: number
47
47
  * closingMonth("2026-10-31", -1); // "2026-10"(末日締め)
48
48
  * @public
49
49
  */
50
- export declare function closingMonth(date: DateString, closingDay: number): MonthString;
50
+ export declare function closingMonth(date: DateString, closingDayOfMonth: number): MonthString;
51
51
  /** @internal 締め日の検証(closingMonth・closingPeriod・営業日カレンダーの締め日で共用) */
52
- export declare function checkClosingDay(closingDay: number): void;
52
+ export declare function checkClosingDay(closingDayOfMonth: number): void;
53
53
  /** @internal その月の締め日(日)。-1 またはその月の日数以上なら末日(decisions.md の 16 番の読み替えはここだけで行う) */
54
- export declare function closingDayIn({ year, month }: YearMonth, closingDay: number): number;
54
+ export declare function closingDayIn({ year, month }: YearMonth, closingDayOfMonth: number): number;
55
55
  /**
56
56
  * 締め日で区切ったときの、その月分の期間(両端を含む暦日)。closingMonth の逆算。
57
57
  *
@@ -65,7 +65,7 @@ export declare function closingDayIn({ year, month }: YearMonth, closingDay: num
65
65
  * closingPeriod("2026-11-05", 20); // { from: "2026-10-21", to: "2026-11-20" }(この日が属する期間)
66
66
  * @public
67
67
  */
68
- export declare function closingPeriod(input: DateString | MonthString, closingDay: number): {
68
+ export declare function closingPeriod(input: DateString | MonthString, closingDayOfMonth: number): {
69
69
  readonly from: DateString;
70
70
  readonly to: DateString;
71
71
  };
@@ -1,4 +1,4 @@
1
- import { addDays, daysInMonth, formatDate, parseDate } from "./date.js";
1
+ import { addDays, lengthOfMonth, formatDate, parseDate } from "./date.js";
2
2
  import { rangeError } from "./errors.js";
3
3
  const MONTH_RE = /^(\d{4})-(\d{2})$/;
4
4
  export function parseMonth(value) {
@@ -21,7 +21,7 @@ export function shiftMonth({ year, month }, offset) {
21
21
  return { year: Math.floor(index / 12), month: (index % 12) + 1 };
22
22
  }
23
23
  export function dayOfMonth({ year, month }, day) {
24
- const last = daysInMonth(year, month);
24
+ const last = lengthOfMonth(year, month);
25
25
  return formatDate(year, month, day === -1 || day > last ? last : day);
26
26
  }
27
27
  export const isDayOfMonthValue = (v) => v === -1 || (Number.isInteger(v) && v >= 1 && v <= 31);
@@ -34,27 +34,27 @@ export function monthOf(input, offset = 0) {
34
34
  : parseMonth(input);
35
35
  return formatMonth(shiftMonth(base, offset));
36
36
  }
37
- export function closingMonth(date, closingDay) {
38
- checkClosingDay(closingDay);
37
+ export function closingMonth(date, closingDayOfMonth) {
38
+ checkClosingDay(closingDayOfMonth);
39
39
  const { year, month, day } = parseDate(date);
40
- return formatMonth(shiftMonth({ year, month }, day <= closingDayIn({ year, month }, closingDay) ? 0 : 1));
40
+ return formatMonth(shiftMonth({ year, month }, day <= closingDayIn({ year, month }, closingDayOfMonth) ? 0 : 1));
41
41
  }
42
- export function checkClosingDay(closingDay) {
43
- if (!isDayOfMonthValue(closingDay)) {
44
- throw rangeError("invalid-argument", `closingDay must be an integer from 1 to 31, or -1 (last day): ${closingDay}`);
42
+ export function checkClosingDay(closingDayOfMonth) {
43
+ if (!isDayOfMonthValue(closingDayOfMonth)) {
44
+ throw rangeError("invalid-argument", `closingDayOfMonth must be an integer from 1 to 31, or -1 (last day): ${closingDayOfMonth}`);
45
45
  }
46
46
  }
47
- export function closingDayIn({ year, month }, closingDay) {
48
- const last = daysInMonth(year, month);
49
- return closingDay === -1 || closingDay > last ? last : closingDay;
47
+ export function closingDayIn({ year, month }, closingDayOfMonth) {
48
+ const last = lengthOfMonth(year, month);
49
+ return closingDayOfMonth === -1 || closingDayOfMonth > last ? last : closingDayOfMonth;
50
50
  }
51
- export function closingPeriod(input, closingDay) {
52
- checkClosingDay(closingDay);
51
+ export function closingPeriod(input, closingDayOfMonth) {
52
+ checkClosingDay(closingDayOfMonth);
53
53
  const month = typeof input === "string" && input.split("-").length === 3
54
- ? parseMonth(closingMonth(input, closingDay))
54
+ ? parseMonth(closingMonth(input, closingDayOfMonth))
55
55
  : parseMonth(input);
56
56
  const previous = shiftMonth(month, -1);
57
- const to = dayOfMonth(month, closingDayIn(month, closingDay));
58
- const from = addDays(dayOfMonth(previous, closingDayIn(previous, closingDay)), 1);
57
+ const to = dayOfMonth(month, closingDayIn(month, closingDayOfMonth));
58
+ const from = addDays(dayOfMonth(previous, closingDayIn(previous, closingDayOfMonth)), 1);
59
59
  return Object.freeze({ from, to });
60
60
  }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 0.30.0 で改名した設定のキーと値の表(docs/decisions.md の 54 番、docs/migration.md の 0.30.0)。
3
+ * 検証の入口での読み替え・診断の deprecated-option・migrate… 関数が、この表だけを使う。
4
+ */
5
+ import { type IssueCollector } from "./errors.ts";
6
+ /** @internal 改名したキーがある設定の場所 */
7
+ export type RenamedPlace = "source" | "calendar" | "schedule" | "rule" | "combine" | "fromSchedule" | "dueDate" | "substitute";
8
+ /** @internal 改名したキー */
9
+ export interface RenamedKey {
10
+ readonly place: RenamedPlace;
11
+ readonly from: string;
12
+ readonly to: string;
13
+ }
14
+ /** @internal 改名したキーの表(0.30.0) */
15
+ export declare const RENAMED_KEYS: readonly RenamedKey[];
16
+ /** @internal 改名した値 */
17
+ export interface RenamedValue {
18
+ readonly place: RenamedPlace;
19
+ /** 新しいキーの名前 */
20
+ readonly key: string;
21
+ readonly from: string;
22
+ readonly to: string;
23
+ }
24
+ /**
25
+ * @internal 改名した値の表(0.30.0)。kinds の "national" は、ID が "JP" の祝日の提供元を使う設定でだけ読み替える
26
+ */
27
+ export declare const RENAMED_VALUES: readonly RenamedValue[];
28
+ /** @internal 改名を見つけたときの扱い(作成・診断は記録して読み替える。合成などの記録先がない設定は読み替えるだけ) */
29
+ export type RenameReport = IssueCollector | "throw";
30
+ /**
31
+ * @internal 設定のオブジェクト 1 つの旧名のキーを新しい名前に読み替えた複製を返す(利用者のオブジェクトは変えない)。
32
+ * writtenPath は利用者が書いた位置(旧名を含む)で、deprecated-option と invalid-option の位置に使う。
33
+ * 旧名と新しい名前の両方があれば invalid-option(どちらを使うか読み取れないため)
34
+ */
35
+ export declare function renameKeys(report: RenameReport, places: readonly RenamedPlace[], writtenPath: string, value: Record<string, unknown>): Record<string, unknown>;
36
+ /** @internal 読み替えたオブジェクトのキーについて、利用者が書いた名前(旧名ならその名前) */
37
+ export declare function writtenKey(places: readonly RenamedPlace[], value: Record<string, unknown>, key: string): string;
38
+ /**
39
+ * @internal 改名した値を読み替える(読み替えたら deprecated-option を記録する)。
40
+ * 文字列ならその値、配列なら要素ごとに読み替えた複製を返す
41
+ */
42
+ export declare function renameValue(report: RenameReport, place: RenamedPlace, key: string, writtenPath: string, value: unknown): unknown;
@@ -0,0 +1,73 @@
1
+ import { rangeError } from "./errors.js";
2
+ export const RENAMED_KEYS = [
3
+ { place: "source", from: "holidays", to: "holidayProvider" },
4
+ { place: "source", from: "outOfRange", to: "outOfRangePolicy" },
5
+ { place: "source", from: "unconfirmedHolidays", to: "unconfirmedHolidayPolicy" },
6
+ { place: "calendar", from: "closedAnnual", to: "closedAnnualDates" },
7
+ { place: "calendar", from: "closedRecurring", to: "closedRecurringRules" },
8
+ { place: "calendar", from: "openRecurring", to: "openRecurringRules" },
9
+ { place: "calendar", from: "maxSearchDays", to: "searchDayLimit" },
10
+ { place: "schedule", from: "weekly", to: "weekdayValues" },
11
+ { place: "schedule", from: "holiday", to: "holidayPolicy" },
12
+ { place: "schedule", from: "annual", to: "annualDates" },
13
+ { place: "schedule", from: "recurring", to: "recurringRules" },
14
+ { place: "rule", from: "day", to: "dayOfMonth" },
15
+ { place: "rule", from: "onHolidayRule", to: "holidayOverlapPolicy" },
16
+ { place: "combine", from: "businessDay", to: "open" },
17
+ { place: "combine", from: "maxSearchDays", to: "searchDayLimit" },
18
+ { place: "fromSchedule", from: "maxSearchDays", to: "searchDayLimit" },
19
+ { place: "dueDate", from: "day", to: "dayOfMonth" },
20
+ { place: "substitute", from: "rules", to: "directions" },
21
+ { place: "substitute", from: "name", to: "renameSubstitute" },
22
+ { place: "substitute", from: "original", to: "originalPolicy" },
23
+ ];
24
+ export const RENAMED_VALUES = [
25
+ { place: "schedule", key: "holidayPolicy", from: "weekday", to: "ignore" },
26
+ { place: "rule", key: "kinds", from: "national", to: "regular" },
27
+ ];
28
+ const VERSION = "0.30.0";
29
+ const join = (path, key) => (path ? `${path}.${key}` : key);
30
+ function conflict(report, path, from, to) {
31
+ const message = `use only ${JSON.stringify(to)} (${JSON.stringify(from)} was renamed in ${VERSION})`;
32
+ if (report === "throw")
33
+ throw rangeError("invalid-option", `${path}: ${message}`);
34
+ report.error("invalid-option", path, message);
35
+ }
36
+ export function renameKeys(report, places, writtenPath, value) {
37
+ const out = { ...value };
38
+ for (const r of RENAMED_KEYS) {
39
+ if (!places.includes(r.place) || !Object.hasOwn(value, r.from))
40
+ continue;
41
+ const at = join(writtenPath, r.from);
42
+ if (Object.hasOwn(value, r.to)) {
43
+ conflict(report, at, r.from, r.to);
44
+ delete out[r.from];
45
+ continue;
46
+ }
47
+ out[r.to] = value[r.from];
48
+ delete out[r.from];
49
+ if (report !== "throw")
50
+ report.warning("deprecated-option", at, `${JSON.stringify(r.from)} was renamed to ${JSON.stringify(r.to)} in ${VERSION}`);
51
+ }
52
+ return out;
53
+ }
54
+ export function writtenKey(places, value, key) {
55
+ const r = RENAMED_KEYS.find((x) => places.includes(x.place) && x.to === key && Object.hasOwn(value, x.from));
56
+ return r ? r.from : key;
57
+ }
58
+ export function renameValue(report, place, key, writtenPath, value) {
59
+ const rules = RENAMED_VALUES.filter((r) => r.place === place && r.key === key);
60
+ if (rules.length === 0)
61
+ return value;
62
+ const one = (v, at) => {
63
+ const r = rules.find((x) => x.from === v);
64
+ if (!r)
65
+ return v;
66
+ if (report !== "throw")
67
+ report.warning("deprecated-option", at, `${JSON.stringify(r.from)} was renamed to ${JSON.stringify(r.to)} in ${VERSION}`);
68
+ return r.to;
69
+ };
70
+ if (Array.isArray(value))
71
+ return value.map((v, i) => one(v, `${writtenPath}[${i}]`));
72
+ return one(value, writtenPath);
73
+ }