diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index 600dfe92..4dfdb9b6 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -31,8 +31,8 @@ Active package decisions grouped by area, newest first. ### Arithmetic, Boundaries, and Weekdays -- **D19:** `isWeekend()` and `isWeekday()` follow the locale (2026-11-22) [L113-L117](decisions/package.md#d19-isweekend-and-isweekday-follow-the-locale-2026-11-22) - - Reopen: bug reports show `.locale()` unexpectedly changing `isWeekend()`, `isWeekday()`, or `count('weekdays')`, or users ask for a `configure()` weekend override. +- **D27:** `isWeekend()` and `isWeekday()` follow the locale, but `configure({ weekend })` overrides instance locales (2026-11-25) [L161-L165](decisions/package.md#d27-isweekend-and-isweekday-follow-the-locale-but-configure-weekend--overrides-instance-locales-2026-11-25) + - Reopen: apps serving regions with different workweeks in one process ask for a per-call or per-instance weekend override. - **D17:** Adjacent unit boundaries use `startOfNext()` and `startOfPrevious()` instead of overloading `next()` and `previous()` (2026-11-19) [L101-L105](decisions/package.md#d17-adjacent-unit-boundaries-use-startofnext-and-startofprevious-instead-of-overloading-next-and-previous-2026-11-19) - Reopen: cold-reader studies or user issues show developers trying unit names in `next()` and `previous()`, or passing numeric weekdays to `startOfNext()`. - **D14:** Numeric day of the week is `dayOfWeek` (`1`-`7`) while token `d` keeps Moment's `0`-`6` (2026-11-17) [L83-L87](decisions/package.md#d14-numeric-day-of-the-week-is-dayofweek-1-7-while-token-d-keeps-moments-0-6-2026-11-17) @@ -119,7 +119,7 @@ Every package decision (`D1`..`Dn`) in file order. - **D18:** `native-dates/helpers/*` stays open for official plugins without semver guarantees (2026-11-20) [L107-L111](decisions/package.md#d18-native-dateshelpers-stays-open-for-official-plugins-without-semver-guarantees-2026-11-20) - Reopen: external packages depend on `native-dates/helpers/*` directly and report breakage across minor releases. - **D19:** `isWeekend()` and `isWeekday()` follow the locale (2026-11-22) [L113-L117](decisions/package.md#d19-isweekend-and-isweekday-follow-the-locale-2026-11-22) - - Reopen: bug reports show `.locale()` unexpectedly changing `isWeekend()`, `isWeekday()`, or `count('weekdays')`, or users ask for a `configure()` weekend override. + - Superseded by D27 (2026-11-25) - **D20:** Loose parsing follows the locale while `monthDay()` and `dayMonth()` keep function-name order (2026-11-22) [L119-L123](decisions/package.md#d20-loose-parsing-follows-the-locale-while-monthday-and-daymonth-keep-function-name-order-2026-11-22) - Reopen: speakers report a locale's `Intl` short date order diverging from typed input, or unconfigured host locales cause inconsistent `{ loose: true }` results across environments. - **D21:** Time zone abbreviations inside `{ loose: true }` strings resolve like `{ zone }` rather than `Date.parse()` (2026-11-22) [L125-L129](decisions/package.md#d21-time-zone-abbreviations-inside--loose-true--strings-resolve-like--zone--rather-than-dateparse-2026-11-22) @@ -134,3 +134,5 @@ Every package decision (`D1`..`Dn`) in file order. - Reopen: server apps passing per-request `Accept-Language` headers alongside `configure({ dayFirst: true })` report wanting the configured `dayFirst` setting to override per-call `locale`. - **D26:** Loose parsing returns `null` unless year, month, and day are all written (2026-11-23) [L155-L159](decisions/package.md#d26-loose-parsing-returns-null-unless-year-month-and-day-are-all-written-2026-11-23) - Reopen: callers report friction from human-typed current-year dates like `'Nov 16'` returning `null`. +- **D27:** `isWeekend()` and `isWeekday()` follow the locale, but `configure({ weekend })` overrides instance locales (2026-11-25) [L161-L165](decisions/package.md#d27-isweekend-and-isweekday-follow-the-locale-but-configure-weekend--overrides-instance-locales-2026-11-25) + - Reopen: apps serving regions with different workweeks in one process ask for a per-call or per-instance weekend override. diff --git a/ai/contributing/decisions/package.md b/ai/contributing/decisions/package.md index 582de7b6..4e852519 100644 --- a/ai/contributing/decisions/package.md +++ b/ai/contributing/decisions/package.md @@ -114,7 +114,7 @@ Reopen: external packages depend on `native-dates/helpers/*` directly and report Hardcoding Saturday and Sunday (`dayOfWeek >= 6`, as in Moment, Day.js, and date-fns) gets weekends wrong in Friday-Saturday (`ar-SA`, `he-IL`), Friday-only (`fa-IR`), and Sunday-only (`hi-IN`) locales even though `startOf('week')` already localizes via `Intl.Locale.prototype.getWeekInfo` (`D7`). The tradeoff is that `.locale()` changes `isWeekend()`, `isWeekday()`, and `DateRange.prototype.count('weekdays')`, so code needing fixed Saturday-Sunday rules has to check `dayOfWeek >= 6`. -Reopen: bug reports show `.locale()` unexpectedly changing `isWeekend()`, `isWeekday()`, or `count('weekdays')`, or users ask for a `configure()` weekend override. +Superseded by D27 (2026-11-25). ## D20: Loose parsing follows the locale while `monthDay()` and `dayMonth()` keep function-name order (2026-11-22) @@ -157,3 +157,9 @@ Reopen: server apps passing per-request `Accept-Language` headers alongside `con Delegating partial or noisy strings to `Date.parse()` fabricated V8's default year `2001` and day `01` (`'Room 12'` -> `2001-12-01`, `'Nov 16'` -> `2001-11-16`, `'May 2026'` -> `2026-05-01`). Requiring all three date parts in `date()` and `datetime()` under `{ loose: true }` returns `null` instead of invented dates, while partial dates use dedicated factories (`monthDay('Nov 16', { loose: true })`, `yearMonth('May 2026', { loose: true })`). Reopen: callers report friction from human-typed current-year dates like `'Nov 16'` returning `null`. + +## D27: `isWeekend()` and `isWeekday()` follow the locale, but `configure({ weekend })` overrides instance locales (2026-11-25) + +Supersedes D19. Weekend checks and weekday range counts follow the active locale by default, while `configure({ weekend })` sets fixed weekend days for the whole process. Letting an instance locale win instead would silently change business-day rules whenever a server formats a date for a visitor. This follows the same priority as `weekStart` and keeps workweeks consistent across requests. + +Reopen: apps serving regions with different workweeks in one process ask for a per-call or per-instance weekend override. diff --git a/ai/skills/native-dates.md b/ai/skills/native-dates.md index 4ee02606..3c6d83ac 100644 --- a/ai/skills/native-dates.md +++ b/ai/skills/native-dates.md @@ -30,7 +30,7 @@ datetime('2026-03-08T04:30:00Z', 'UTC'); datetime('2026-03-08T04:30:00Z', 'America/New_York').plus(1, 'day').toJSON(); // '2026-03-09T03:30:00.000Z' ``` -**2. `month` is `1`–`12`, `dayOfWeek` is ISO `1`–`7` (`7` = Sun), `isWeekend()`/`isWeekday()` follow the locale, and tokens use Moment casing (`YYYY-MM-DD`, not `yyyy-MM-dd`).** Weekends vary by locale (`ar-SA`/`ar-EG`/`he-IL` Fri–Sat, `fa-IR` Fri, `hi-IN` Sun). In `format()`, `'yyyy'` throws `unknownFormat` (absent noun token like `'HH'` on `CalendarDate` throws `unsupportedToken`), `'dd'` is 2-letter weekday (`'Mo'`), `'E'` is `'1'`–`'7'`, `'d'` is `'0'`–`'6'` (`0` = Sun), and literals glued to accented letters (`'às'`) or `h` after `H` (`'HHhmm'`) need `[brackets]`. +**2. `month` is `1`–`12`, `dayOfWeek` is ISO `1`–`7` (`7` = Sun), `isWeekend()`/`isWeekday()` follow the locale (unless pinned via `configure({ weekend })`), and tokens use Moment casing (`YYYY-MM-DD`, not `yyyy-MM-dd`).** Weekends vary by locale (`ar-SA`/`ar-EG`/`he-IL` Fri–Sat, `fa-IR` Fri, `hi-IN` Sun). In `format()`, `'yyyy'` throws `unknownFormat` (absent noun token like `'HH'` on `CalendarDate` throws `unsupportedToken`), `'dd'` is 2-letter weekday (`'Mo'`), `'E'` is `'1'`–`'7'`, `'d'` is `'0'`–`'6'` (`0` = Sun), and literals glued to accented letters (`'às'`) or `h` after `H` (`'HHhmm'`) need `[brackets]`. ```js // ❌ date(2026, 0, 15) -> invalidDate; date('2026-11-16').format('yyyy-MM-dd') -> unknownFormat @@ -223,6 +223,7 @@ configure({ zone: 'America/New_York', // null resets locale: 'en-US', // null resets weekStart: 'monday', // 1..7 or name (null -> locale) + weekend: ['saturday', 'sunday'], // weekday array, [] for none (null -> locale) formats: { sql: 'YYYY-MM-DD HH:mm:ss' }, // null clears weekdayNames: { lv: { narrow: { fri: 'Pk', sun: 'Sv' } } }, ordinals: { fr: (day) => (day === 1 ? '1er' : day) }, @@ -243,7 +244,7 @@ configure({ | Error codes | Thrown when | |---|---| | `missingDateTime`, `missingDate`, `missingTime`, `missingMonthDay`, `missingYearMonth`, `missingDay`, `missingPoints`, `missingAnchor`, `missingPlugin`, `missingTemporal` | Nullish input, `date(2026, 11)`, unanchored `months(2).total('days')`, unloaded plugin option, or missing `globalThis.Temporal` in development (`RangeError`; production throws native `ReferenceError`) | -| `invalidDateTime`, `invalidDate`, `invalidTime`, `invalidDuration`, `invalidMonthDay`, `invalidYearMonth`, `invalidRange`, `invalidStep`, `invalidNumber`, `invalidFraction`, `invalidYear`, `invalidDay`, `invalidPoint` | Malformed input, `Feb 30`, rejected DST gap/fold, non-positive step, or `end < start` | +| `invalidDateTime`, `invalidDate`, `invalidTime`, `invalidDuration`, `invalidMonthDay`, `invalidYearMonth`, `invalidRange`, `invalidStep`, `invalidNumber`, `invalidFraction`, `invalidYear`, `invalidDay`, `invalidPoint`, `invalidWeekend` | Malformed input, `Feb 30`, rejected DST gap/fold, non-positive step, `end < start`, or non-array `configure({ weekend })` | | `cannotAdd`, `cannotSubtract`, `cannotSet`, `cannotRound`, `cannotBalance`, `cannotTotal` | Overflow, invalid `set()` field, or bad rounding increment (`round(7, 'minutes')`) | | `unknownZone`, `unknownLocale`, `unknownDisambiguation`, `unknownUnit`, `unknownDayOfWeek`, `unknownFormat`, `unknownKind`, `unknownSetting`, `unknownWidth` | Bad zone, BCP 47 tag, `disambiguation`, unit, weekday, token/preset (`'yyyy'`), `as()`/`count()` target, or `configure()` key | | `unsupportedUnit`, `unsupportedToken`, `unsupportedComparison`, `unsupportedZone`, `unsupportedCalendar`, `unsupportedIntersection` | Absent unit/token, `<`/`-` on non-`DateTime`, `timeRange.in()`, non-ISO partial, or double overnight overlap | diff --git a/docs/src/content/docs/api/calendar-date.md b/docs/src/content/docs/api/calendar-date.md index 9159ab30..8ea7e983 100644 --- a/docs/src/content/docs/api/calendar-date.md +++ b/docs/src/content/docs/api/calendar-date.md @@ -537,7 +537,7 @@ Relative day checks accept an optional time zone because which calendar day is t |---|---|---| | `isToday(zone?)`, `isTomorrow(zone?)`, `isYesterday(zone?)` | `boolean` | Whether this date matches today, tomorrow, or yesterday in the given or configured zone. | | `isPast(zone?)`, `isFuture(zone?)` | `boolean` | Whether this date is earlier or later than today in the given or configured zone. | -| `isWeekday()`, `isWeekend()` | `boolean` | Working day vs. weekend day in the active locale, such as Saturday and Sunday in `en-US` or Friday and Saturday in `ar-SA`. | +| `isWeekday()`, `isWeekend()` | `boolean` | Working day vs. weekend day from [`configure({ weekend })`](/api/configure/) or the active locale, such as Saturday and Sunday in `en-US` or Friday and Saturday in `ar-SA`. | | `isLeapYear()` | `boolean` | Whether this date's year has 366 days. | ## Measuring spans diff --git a/docs/src/content/docs/api/configure.md b/docs/src/content/docs/api/configure.md index fcaed5e2..704db4e7 100644 --- a/docs/src/content/docs/api/configure.md +++ b/docs/src/content/docs/api/configure.md @@ -32,12 +32,13 @@ datetime('2026-11-16T17:30:00Z').zone; // 'Europe/Berlin' date('2026-11-18').startOf('week').toString(); // '2026-11-16' configure().weekStart; // undefined -configure({ weekStart: 'sunday' }); +configure({ weekStart: 'sunday', weekend: ['saturday', 'sunday'] }); date('2026-11-18').startOf('week').toString(); // '2026-11-15' configure().weekStart; // 7 +configure().weekend; // [6, 7] -// reset back to the runtime zone, runtime locale, and locale week start -configure({ zone: null, locale: null, weekStart: null }); +// reset back to the runtime zone, runtime locale, and locale week rules +configure({ zone: null, locale: null, weekStart: null, weekend: null }); ``` **Parameters** @@ -56,6 +57,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: First day of the week for week boundaries and `weekdayNames()`, from 1 for Monday through 7 for Sunday. Unset or `null` follows the active locale. + - name: weekend + type: readonly DayOfWeek[] | null + description: Weekend days used by `isWeekend()`, `isWeekday()`, and `DateRange.count('weekdays' | 'weekends')`. Overrides per-instance `.locale()` when set; pass `[]` for no weekend days, or `null` to follow the locale. - name: weekdayNames type: "Record | null" description: "Custom weekday labels keyed by language, width (`narrow`, `short`, or `long`), and day name. Regional tags layer over their base language, and an empty value restores runtime names." @@ -76,7 +80,7 @@ configure({ zone: null, locale: null, weekStart: null }); **Returns** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: A shallow copy of the active settings after applying updates. Unset keys return `undefined`. ``` diff --git a/docs/src/content/docs/api/date-time.md b/docs/src/content/docs/api/date-time.md index 3757e819..037e5f5d 100644 --- a/docs/src/content/docs/api/date-time.md +++ b/docs/src/content/docs/api/date-time.md @@ -646,7 +646,7 @@ Zero-argument checks evaluated in the instance's time zone: |---|---|---| | `isPast()`, `isFuture()` | `boolean` | Whether this instant is earlier or later than the current time. | | `isToday()`, `isTomorrow()`, `isYesterday()` | `boolean` | Whether the local calendar date matches today, tomorrow, or yesterday in this zone. | -| `isWeekday()`, `isWeekend()` | `boolean` | Working day vs. weekend day in the active locale, such as Saturday and Sunday in `en-US` or Friday and Saturday in `ar-SA`. | +| `isWeekday()`, `isWeekend()` | `boolean` | Working day vs. weekend day from [`configure({ weekend })`](/api/configure/) or the active locale, such as Saturday and Sunday in `en-US` or Friday and Saturday in `ar-SA`. | | `isLeapYear()` | `boolean` | Whether the local year is a leap year. | ## Measuring time diff --git a/docs/src/content/docs/api/errors.md b/docs/src/content/docs/api/errors.md index 61f558f5..784c23c8 100644 --- a/docs/src/content/docs/api/errors.md +++ b/docs/src/content/docs/api/errors.md @@ -115,6 +115,7 @@ Range errors indicate that a value cannot be parsed, falls outside valid bounds, | `unknownSetting` | `configure()` | Setting key passed to `configure()` is not recognized. | | `unknownWidth` | `configure()` | A `weekdayNames` entry names a width other than `narrow`, `short`, or `long`, or leaves the width out. | | `unknownZone` | Factories, `in()`, `configure()` | Unknown IANA time zone ID, non-string zone, or malformed UTC offset. | +| `invalidWeekend` | `configure()` | `weekend` is neither an array of weekdays nor `null`. | | `invalidZoneAliases` | `configure()` | `zoneAliases` is neither a plain object nor `null`. | | `unknownLocale` | `locale()`, factories, `format()`, `monthNames()`, `weekdayNames()`, `configure()` | Locale tag, tag list, or `Accept-Language` header contains an invalid language tag. | | `unknownFormat` | `format()`, `monthNames()`, `weekdayNames()` | Invalid format spec or `Intl` options, unsupported duration or label style, or unrecognized or glued tokens outside `[brackets]`. | diff --git a/docs/src/content/docs/api/ranges.md b/docs/src/content/docs/api/ranges.md index 17af4c20..d3cde5f3 100644 --- a/docs/src/content/docs/api/ranges.md +++ b/docs/src/content/docs/api/ranges.md @@ -365,7 +365,7 @@ timeRange('22:00', '02:00').every(1, 'hour').map(String); dateRange.count(kind?): number ``` -Counts calendar days inside a [`DateRange`](#daterange) without allocating intermediate date instances. Pass `'days'` (the default), `'weekdays'`, `'weekends'`, or a weekday name such as `'mondays'`. `'weekdays'` and `'weekends'` follow the active locale's weekend days. +Counts calendar days inside a [`DateRange`](#daterange) without allocating intermediate date instances. Pass `'days'` (the default), `'weekdays'`, `'weekends'`, or a weekday name such as `'mondays'`. `'weekdays'` and `'weekends'` follow [`configure({ weekend })`](/api/configure/) when set, or the active locale's weekend days. **Parameters** diff --git a/docs/src/content/docs/guides/localization.md b/docs/src/content/docs/guides/localization.md index 465414f3..1096dad3 100644 --- a/docs/src/content/docs/guides/localization.md +++ b/docs/src/content/docs/guides/localization.md @@ -181,6 +181,15 @@ friday.locale('en-US').isWeekend(); // false friday.locale('ar-SA').isWeekend(); // true ``` +Set `weekend` in [`configure()`](/api/configure/) when an app needs fixed business-day rules across every locale, even on values formatted with `.locale()` for a different region. Pass an array of weekday names or ISO numbers (or `[]` for a seven-day workweek), and pass `null` to follow the locale again: + +```js +configure({ weekend: ['saturday', 'sunday'] }); + +friday.locale('ar-SA').isWeekend(); // false +configure({ weekend: null }); +``` + ## Custom weekday names and ordinals Month and weekday names come from the runtime, matching what the reader's device prints. Two format tokens have no standard platform field: two-letter weekdays with `dd`, and day ordinals with `Do`. diff --git a/docs/src/content/translations/ar/docs/api/configure.md b/docs/src/content/translations/ar/docs/api/configure.md index ca5e85e2..69976a6d 100644 --- a/docs/src/content/translations/ar/docs/api/configure.md +++ b/docs/src/content/translations/ar/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: اليوم الأول في الأسبوع لحدود الأسابيع و`weekdayNames()`، باسم يوم من أيام الأسبوع بالإنجليزية أو رقم من 1 ليوم الاثنين حتى 7 ليوم الأحد؛ ويتبع عدم ضبطه أو تمرير `null` الإعداد المحلي النشط. + - name: weekend + type: readonly DayOfWeek[] | null + description: "أيام عطلة نهاية الأسبوع المستخدمة في `isWeekend()` و`isWeekday()` و`DateRange.count('weekdays' | 'weekends')`. يتغلب ضبطها على `.locale()` لكل مثيل؛ مرر `[]` لعدم وجود عطلة أو `null` لاتباع الإعداد المحلي." - name: weekdayNames type: "Record | null" description: تسميات مخصّصة لأيام الأسبوع مفهرسة بوسم الإعداد المحلي وعرض التسمية (`narrow` أو `short` أو `long`) واسم اليوم بالإنجليزية؛ وتتراكب الوسوم الإقليمية فوق وسم لغتها الأساسي، بينما تستعيد القيمة الفارغة أسماء بيئة التشغيل. @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **القيمة المُرجَعة** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: نسخة سطحية من الإعدادات النشطة بعد تطبيق التحديثات، مع القيمة `undefined` للمفاتيح غير المضبوطة. ``` diff --git a/docs/src/content/translations/es/docs/api/configure.md b/docs/src/content/translations/es/docs/api/configure.md index 812b1540..3465b1c7 100644 --- a/docs/src/content/translations/es/docs/api/configure.md +++ b/docs/src/content/translations/es/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: Primer día de la semana para límites semanales y `weekdayNames()`, como nombre de día en inglés o número del 1 (lunes) al 7 (domingo). Si se omite o es `null`, sigue el locale activo. + - name: weekend + type: readonly DayOfWeek[] | null + description: "Días de fin de semana usados por `isWeekend()`, `isWeekday()` y `DateRange.count('weekdays' | 'weekends')`. Prevalece sobre `.locale()` de cada instancia; pasa `[]` para ningún día de fin de semana o `null` para seguir el locale." - name: weekdayNames type: "Record | null" description: "Etiquetas personalizadas de días de la semana indexadas por locale, anchura (`narrow`, `short` o `long`) y nombre de día en inglés. Las etiquetas regionales se superponen al idioma base y un valor vacío restablece los nombres del entorno." @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **Devuelve** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: Copia superficial de la configuración activa tras aplicar los cambios. Las claves sin configurar tienen el valor `undefined`. ``` diff --git a/docs/src/content/translations/fr/docs/api/configure.md b/docs/src/content/translations/fr/docs/api/configure.md index cc4da04a..d868ffc3 100644 --- a/docs/src/content/translations/fr/docs/api/configure.md +++ b/docs/src/content/translations/fr/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: Premier jour de la semaine pour les bornes de semaine et `weekdayNames()`, en nom de jour en anglais ou entier de 1 pour lundi à 7 pour dimanche, ou `null` pour suivre la locale active. + - name: weekend + type: readonly DayOfWeek[] | null + description: "Jours de week-end utilisés par `isWeekend()`, `isWeekday()` et `DateRange.count('weekdays' | 'weekends')`. Prend le pas sur `.locale()` par instance ; passez `[]` pour aucun jour de week-end ou `null` pour suivre la locale." - name: weekdayNames type: "Record | null" description: "Libellés de jours personnalisés indexés par étiquette de locale, largeur (`narrow`, `short` ou `long`) et nom de jour en anglais, les étiquettes régionales se superposant à leur locale de base et une valeur vide rétablissant les noms de l’environnement." @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **Valeur de retour** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: Copie superficielle des réglages actifs après application des mises à jour, avec `undefined` pour les clés non définies. ``` diff --git a/docs/src/content/translations/ja/docs/api/configure.md b/docs/src/content/translations/ja/docs/api/configure.md index 572d31fb..f532f85f 100644 --- a/docs/src/content/translations/ja/docs/api/configure.md +++ b/docs/src/content/translations/ja/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: "週の境界と `weekdayNames()` の基準となる週の開始曜日(月曜を1、日曜を7とする数値、または英語の曜日名)。未設定または `null` の場合はアクティブなロケールを適用。" + - name: weekend + type: readonly DayOfWeek[] | null + description: "`isWeekend()`、`isWeekday()`、`DateRange.count('weekdays' | 'weekends')` で使う週末の曜日。設定時はインスタンスの `.locale()` より優先され、`[]` で週末なし、`null` でロケール準拠に戻ります。" - name: weekdayNames type: "Record | null" description: "言語、幅(`narrow`、`short`、`long`)、および英語の曜日名をキーとするカスタム曜日ラベル。地域付きタグは基本言語の設定に重ねて適用され、空の値を渡すと実行環境のラベルにリセット。" @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **戻り値** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: "更新適用後のアクティブな設定の浅いコピー。未設定のキーは `undefined`。" ``` diff --git a/docs/src/content/translations/ko/docs/api/configure.md b/docs/src/content/translations/ko/docs/api/configure.md index 7e3f0f07..4dc521b7 100644 --- a/docs/src/content/translations/ko/docs/api/configure.md +++ b/docs/src/content/translations/ko/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: "주 경계와 `weekdayNames()`에 사용할 주 시작 요일(영어 요일명 또는 월요일 `1`부터 일요일 `7`까지의 ISO 숫자). 미지정이거나 `null`이면 활성 로케일을 따릅니다." + - name: weekend + type: readonly DayOfWeek[] | null + description: "`isWeekend()`, `isWeekday()`, `DateRange.count('weekdays' | 'weekends')`에서 사용하는 주말 요일. 설정 시 인스턴스 `.locale()`보다 우선하며, `[]`은 주말 없음, `null`은 활성 로케일을 따릅니다." - name: weekdayNames type: "Record | null" description: "로케일 태그, 너비(`narrow`, `short`, `long`), 영어 요일명 순으로 키를 구성한 사용자 지정 요일 레이블. 지역 로케일 태그는 기본 언어 로케일 설정 위에 덧씌워지며, 빈 값이나 `null`을 전달하면 런타임 기본 이름으로 복원합니다." @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **반환값** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: "갱신이 반영된 활성 설정의 얕은 복사본. 설정되지 않은 키는 `undefined`입니다." ``` diff --git a/docs/src/content/translations/pt-br/docs/api/configure.md b/docs/src/content/translations/pt-br/docs/api/configure.md index 0118429a..89697ce9 100644 --- a/docs/src/content/translations/pt-br/docs/api/configure.md +++ b/docs/src/content/translations/pt-br/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: Primeiro dia da semana para limites semanais e `weekdayNames()`, como nome em inglês ou número de 1 (segunda-feira) a 7 (domingo), seguindo o locale ativo quando ausente ou `null`. + - name: weekend + type: readonly DayOfWeek[] | null + description: "Dias de fim de semana usados por `isWeekend()`, `isWeekday()` e `DateRange.count('weekdays' | 'weekends')`. Prevalece sobre `.locale()` de cada instância; passe `[]` para nenhum dia de fim de semana ou `null` para seguir o locale." - name: weekdayNames type: "Record | null" description: "Rótulos personalizados de dias da semana indexados por idioma, largura (`narrow`, `short` ou `long`) e nome do dia em inglês, com tags regionais sobrepondo o idioma base e valor vazio restaurando os nomes do runtime." @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **Retorno** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: Cópia rasa das configurações ativas após aplicar as atualizações, com chaves não definidas retornando `undefined`. ``` diff --git a/docs/src/content/translations/ru/docs/api/configure.md b/docs/src/content/translations/ru/docs/api/configure.md index dee2f4cb..71bce94f 100644 --- a/docs/src/content/translations/ru/docs/api/configure.md +++ b/docs/src/content/translations/ru/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: Первый день недели для границ недели и `weekdayNames()` — английское название дня недели или число от 1 (понедельник) до 7 (воскресенье). Если значение не задано или равно `null`, используется правило активной локали. + - name: weekend + type: readonly DayOfWeek[] | null + description: "Выходные дни для `isWeekend()`, `isWeekday()` и `DateRange.count('weekdays' | 'weekends')`. При задании перекрывает `.locale()` экземпляра; передайте `[]`, чтобы убрать выходные, или `null`, чтобы следовать локали." - name: weekdayNames type: "Record | null" description: "Пользовательские подписи дней недели по тегу локали, ширине (`narrow`, `short` или `long`) и английскому названию дня недели. Региональные теги дополняют базовую локаль, а пустое значение восстанавливает системные названия." @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **Возвращает** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: Поверхностная копия активных настроек после применения обновлений. Незаданные ключи содержат `undefined`. ``` diff --git a/docs/src/content/translations/zh-cn/docs/api/configure.md b/docs/src/content/translations/zh-cn/docs/api/configure.md index 56c5d483..3ad0700e 100644 --- a/docs/src/content/translations/zh-cn/docs/api/configure.md +++ b/docs/src/content/translations/zh-cn/docs/api/configure.md @@ -53,6 +53,9 @@ configure({ zone: null, locale: null, weekStart: null }); - name: weekStart type: DayOfWeek | null description: 周边界与 `weekdayNames()` 的每周起始日,从 1(周一)到 7(周日)。未设置或传入 `null` 时遵循当前区域。 + - name: weekend + type: readonly DayOfWeek[] | null + description: "`isWeekend()`、`isWeekday()` 与 `DateRange.count('weekdays' | 'weekends')` 使用的周末日期。设置后优先于实例的 `.locale()`;传入 `[]` 表示无周末,传入 `null` 恢复遵循区域设置。" - name: weekdayNames type: "Record | null" description: "按语言、宽度(`narrow`、`short` 或 `long`)与英文星期名索引的自定义星期标签。地区标签会叠加在基础语言之上,传空值可恢复运行时默认名称。" @@ -73,7 +76,7 @@ configure({ zone: null, locale: null, weekStart: null }); **返回值** ```returns -type: "{ zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" +type: "{ zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats }" description: 应用更新后当前生效配置的浅拷贝;未设置的键返回 `undefined`。 ``` diff --git a/src/helpers/zones.js b/src/helpers/zones.js index 6450d1d9..ac9ab4b0 100644 --- a/src/helpers/zones.js +++ b/src/helpers/zones.js @@ -19,6 +19,7 @@ export const settings = { zone: undefined, locale: undefined, weekStart: undefined, + weekend: undefined, dayFirst: undefined, zoneAliases: {}, weekdayNames: undefined, @@ -81,7 +82,7 @@ export const zoneId = (id, tag) => { }; export const configure = (options) => { - const { zone, locale, weekStart, dayFirst, zoneAliases, weekdayNames, ordinals, formats } = options ??= {}; + const { zone, locale, weekStart, weekend, dayFirst, zoneAliases, weekdayNames, ordinals, formats } = options ??= {}; each(options, (value, name) => { if (!Object.hasOwn(settings, name)) { refuse('unknownSetting', name, { @@ -127,6 +128,17 @@ export const configure = (options) => { if (weekStart !== undefined) { settings.weekStart = weekStart === null ? undefined : dayOfWeek(weekStart); } + if (weekend !== undefined) { + settings.weekend = weekend === null + ? undefined + : Array.isArray(weekend) + ? Object.freeze([...new Set(Array.from(weekend, dayOfWeek))]) + : refuse('invalidWeekend', String(weekend), { + explanation: isDevelopment + ? "expected an array of weekday names or ISO numbers 1-7 such as `['saturday', 'sunday']`, or `null` to follow the locale" + : 0, + }); + } // validate widths and day keys eagerly in configure() rather than failing later on first format() each(weekdayNames, (widths) => each(widths, (days, width) => { @@ -249,6 +261,6 @@ const weekInfo = (tag) => { export const weekStart = (override, tag) => override !== undefined ? dayOfWeek(override) : settings.weekStart ?? weekInfo(tag).firstDay; -export const weekendDays = (tag) => weekInfo(tag).weekend; +export const weekendDays = (tag) => settings.weekend ?? weekInfo(tag).weekend; export const isWeekend = (day, tag) => weekendDays(tag).includes(day); diff --git a/test/calendar-date.test.js b/test/calendar-date.test.js index 15174b7a..f3588744 100644 --- a/test/calendar-date.test.js +++ b/test/calendar-date.test.js @@ -1335,7 +1335,7 @@ describe('CalendarDate.isWeekend() and isWeekday() by locale', () => { ); afterEach(() => { - configure({ locale: null }); + configure({ locale: null, weekend: null }); }); it.each([ @@ -1360,4 +1360,29 @@ describe('CalendarDate.isWeekend() and isWeekday() by locale', () => { configure({ locale: 'ar-EG' }); expect([friday.isWeekend(), sunday.isWeekend()]).toEqual([true, false]); }); + + it('prefers configure({ weekend }) over per-instance .locale() and configure({ locale })', () => { + configure({ locale: 'ar-EG', weekend: ['saturday', 'sunday'] }); + for (const tag of ['ar-SA', 'hi-IN', 'fa-IR', 'en-US']) { + const days = [thursday, friday, saturday, sunday].map((day) => day.locale(tag)); + expect(days.map((day) => day.isWeekend())).toEqual([false, false, true, true]); + expect(days.map((day) => day.isWeekday())).toEqual([true, true, false, false]); + } + expect([friday.isWeekend(), sunday.isWeekend()]).toEqual([false, true]); + + configure({ weekend: ['friday', 'saturday'] }); + expect([friday.locale('en-US').isWeekend(), sunday.locale('en-US').isWeekend()]).toEqual([true, false]); + + configure({ weekend: [] }); + expect([thursday, friday, saturday, sunday].map((day) => day.locale('en-US').isWeekend())).toEqual([ + false, + false, + false, + false, + ]); + + configure({ weekend: null }); + expect([friday.locale('ar-SA').isWeekend(), sunday.locale('ar-SA').isWeekend()]).toEqual([true, false]); + expect([friday.locale('hi-IN').isWeekend(), sunday.locale('hi-IN').isWeekend()]).toEqual([false, true]); + }); }); diff --git a/test/date-time.test.js b/test/date-time.test.js index 897c4e25..06dafcfc 100644 --- a/test/date-time.test.js +++ b/test/date-time.test.js @@ -1664,10 +1664,31 @@ describe('datetime() from Temporal values and strings in another calendar', () = }); describe('DateTime.isWeekend() and isWeekday() by locale', () => { + afterEach(() => { + configure({ locale: null, weekend: null }); + }); + it('returns true on Friday and false on Sunday for ar-SA in the instance timezone', () => { const friday = datetime('2026-11-20T12:00', 'Asia/Riyadh').locale('ar-SA'); expect([friday.isWeekend(), friday.isWeekday()]).toEqual([true, false]); expect(friday.plus(2, 'days').isWeekend()).toBe(false); expect(friday.locale('en-US').isWeekend()).toBe(false); }); + + it('prefers configure({ weekend }) over per-instance .locale() and reverts when set to null', () => { + const friday = datetime('2026-11-20T12:00', 'Asia/Riyadh').locale('ar-SA'); + const sunday = friday.plus(2, 'days'); + configure({ weekend: ['saturday', 'sunday'] }); + expect([friday.isWeekend(), friday.isWeekday()]).toEqual([false, true]); + expect([sunday.isWeekend(), sunday.isWeekday()]).toEqual([true, false]); + + configure({ weekend: ['friday', 'saturday'] }); + expect(friday.locale('en-US').isWeekend()).toBe(true); + expect(sunday.locale('en-US').isWeekend()).toBe(false); + + configure({ weekend: null }); + expect(friday.isWeekend()).toBe(true); + expect(sunday.isWeekend()).toBe(false); + expect(friday.locale('en-US').isWeekend()).toBe(false); + }); }); diff --git a/test/helpers/configure.test.js b/test/helpers/configure.test.js index 0d543b80..cb213505 100644 --- a/test/helpers/configure.test.js +++ b/test/helpers/configure.test.js @@ -4,12 +4,12 @@ import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, it } from 'vitest'; afterEach(() => { - configure({ zone: null, locale: null, weekStart: null }); + configure({ zone: null, locale: null, weekStart: null, weekend: null }); }); describe('configure()', () => { - it('returns undefined for zone, locale, and weekStart before configuration', () => { - expect(configure()).toMatchObject({ zone: undefined, locale: undefined, weekStart: undefined }); + it('returns undefined for zone, locale, weekStart, and weekend before configuration', () => { + expect(configure()).toMatchObject({ zone: undefined, locale: undefined, weekStart: undefined, weekend: undefined }); }); it('returns default plugin settings when no plugins are imported', () => { @@ -224,6 +224,70 @@ describe('configure({ weekStart })', () => { ); }); +describe('configure({ weekend })', () => { + it.each([ + [['saturday', 'sunday'], [6, 7]], + [['Fri', 'Sat'], [5, 6]], + [[5, 6], [5, 6]], + [[6, 0], [6, 7]], + [['friday'], [5]], + [[], []], + ])('normalizes %j to ISO weekday numbers %j', (input, expected) => { + expect(configure({ weekend: input }).weekend).toEqual(expected); + }); + + it('deduplicates repeated weekdays written in different forms', () => { + expect(configure({ weekend: ['sat', 6, 'SUN', 0, 'saturday'] }).weekend).toEqual([6, 7]); + }); + + it('freezes the returned weekend array so callers cannot mutate active settings', () => { + const snapshot = configure({ weekend: ['saturday', 'sunday'] }); + expect(Object.isFrozen(snapshot.weekend)).toBe(true); + expect(() => snapshot.weekend.push(5)).toThrow(TypeError); + expect(configure().weekend).toEqual([6, 7]); + }); + + it('preserves active weekend when omitted or passed undefined in later calls', () => { + configure({ weekend: ['friday', 'saturday'] }); + expect(configure({ locale: 'en-US', weekend: undefined }).weekend).toEqual([5, 6]); + }); + + it('reverts to locale-derived weekend days when set to null', () => { + const friday = date('2026-11-20').locale('ar-SA'); + configure({ weekend: ['saturday', 'sunday'] }); + expect(friday.isWeekend()).toBe(false); + expect(configure({ weekend: null }).weekend).toBeUndefined(); + expect(friday.isWeekend()).toBe(true); + }); + + it.each([['saturday'], [6], [{}], [true], ['']])( + 'throws invalidWeekend RangeError for non-array value %j and preserves the previous weekend', + (bad) => { + configure({ weekend: ['friday', 'saturday'] }); + expect(() => configure({ weekend: bad })).toThrowError( + expect.objectContaining({ name: 'RangeError', code: 'invalidWeekend', at: String(bad) }), + ); + expect(configure().weekend).toEqual([5, 6]); + }, + ); + + it.each([ + [['saturday', 'funday'], 'funday'], + [[6, 8], '8'], + // eslint-disable-next-line no-sparse-arrays + [[, 'sunday'], 'undefined'], + ])( + 'throws unknownDayOfWeek RangeError for invalid entry in %j and preserves the previous weekend', + (bad, expectedAt) => { + configure({ weekend: ['friday', 'saturday'] }); + expect(() => configure({ weekend: bad })).toThrowError( + expect.objectContaining({ name: 'RangeError', code: 'unknownDayOfWeek', at: expectedAt }), + ); + expect(configure().weekend).toEqual([5, 6]); + }, + ); +}); + describe('default zone, locale, and weekStart from process environment', () => { // spawn a child process because TZ and LC_ALL are read at startup (skipped on Windows where LC_ALL is ignored) it.skipIf(process.platform === 'win32')('inherits the default zone, locale, and weekStart from TZ and LC_ALL', () => { diff --git a/test/range.test.js b/test/range.test.js index bcc40f96..960ff627 100644 --- a/test/range.test.js +++ b/test/range.test.js @@ -1081,6 +1081,44 @@ describe('DateRange count()', () => { expect(dateRange('2026-05-01', '2026-05-03', { locale: 'en-IN' }).count('weekends')).toBe(1); }); + describe('with configure({ weekend })', () => { + afterEach(() => { + configure({ locale: null, weekend: null }); + }); + + it('overrides per-range locale weekend days and reverts on null', () => { + // 2026-05-01..2026-05-03 is Friday, Saturday, Sunday + const arabic = dateRange('2026-05-01', '2026-05-03', { locale: 'ar-SA' }); + const indian = dateRange('2026-05-01', '2026-05-03', { locale: 'hi-IN' }); + const american = dateRange('2026-05-01', '2026-05-03', { locale: 'en-US' }); + + configure({ weekend: ['saturday', 'sunday'] }); + expect([arabic.count('weekends'), arabic.count('weekdays')]).toEqual([2, 1]); + expect([indian.count('weekends'), indian.count('weekdays')]).toEqual([2, 1]); + // 2026-05-01 (Fri) is a weekday under sat/sun even in ar-SA + expect(dateRange('2026-05-01', '2026-05-01', { locale: 'ar-SA' }).count('weekdays')).toBe(1); + + configure({ weekend: ['friday', 'saturday'] }); + expect([american.count('weekends'), american.count('weekdays')]).toEqual([2, 1]); + expect(dateRange('2026-05-03', '2026-05-03', { locale: 'en-US' }).count('weekdays')).toBe(1); + + configure({ weekend: [] }); + expect([american.count('weekends'), american.count('weekdays')]).toEqual([0, 3]); + + configure({ weekend: null }); + expect(dateRange('2026-05-01', '2026-05-01', { locale: 'ar-SA' }).count('weekends')).toBe(1); + expect([indian.count('weekends'), indian.count('weekdays')]).toEqual([1, 2]); + expect([american.count('weekends'), american.count('weekdays')]).toEqual([2, 1]); + }); + + it('does not double-count duplicate weekdays configured in weekend', () => { + configure({ weekend: ['sat', 6, 'sunday', 0] }); + const span = dateRange('2026-05-01', '2 weeks', { locale: 'ar-SA' }); + expect(span.count('weekends')).toBe(4); + expect(span.count('weekdays')).toBe(10); + }); + }); + it('throws unknownKind for unrecognized or non-string count kinds', () => { const sprint = dateRange('2026-05-01', '2 weeks'); expect(() => sprint.count('weeks')).toThrowError( diff --git a/test/types.ts b/test/types.ts index 89d19de6..c4227ba7 100644 --- a/test/types.ts +++ b/test/types.ts @@ -141,9 +141,26 @@ export const heldSpan: DateRange = dateRange('TBD', 'TBD', held); // zones adds zoneAliases to settings and exports its abbreviation table timezones.IST = 'Asia/Jerusalem'; -const settings: Settings = { zoneAliases: { hq: 'Europe/Berlin' }, dayFirst: true, weekStart: 'monday' }; +const settings: Settings = { + zoneAliases: { hq: 'Europe/Berlin' }, + dayFirst: true, + weekStart: 'monday', + weekend: ['saturday', 'sunday'], +}; const active: ActiveSettings = configure(settings); export const configured: Record = active.zoneAliases; +export const activeWeekend: readonly number[] | undefined = active.weekend; +export const clearedWeekend: ActiveSettings = configure({ weekend: null }); +export const emptyWeekend: ActiveSettings = configure({ weekend: [] }); +export const numericWeekend: ActiveSettings = configure({ weekend: [5, 6] }); +export const invalidWeekendCode: ErrorCode = 'invalidWeekend'; + +// @ts-expect-error weekend requires an array of weekdays or null +configure({ weekend: 'saturday' }); +// @ts-expect-error weekend rejects unrecognized weekday names +configure({ weekend: ['funday'] }); +// @ts-expect-error configured weekend snapshot is readonly +active.weekend?.push(1); // locale accepts a tag, an Accept-Language header, or a tag list such as navigator.languages declare const languages: readonly string[]; diff --git a/types/helpers/errors.d.ts b/types/helpers/errors.d.ts index c66f85ae..bc32ca1b 100644 --- a/types/helpers/errors.d.ts +++ b/types/helpers/errors.d.ts @@ -28,6 +28,7 @@ export type ErrorCode = | 'invalidYear' | 'invalidDay' | 'invalidPoint' + | 'invalidWeekend' | 'invalidZoneAliases' | 'cannotAdd' | 'cannotSubtract' diff --git a/types/helpers/zones.d.ts b/types/helpers/zones.d.ts index 04e953d6..abd190ea 100644 --- a/types/helpers/zones.d.ts +++ b/types/helpers/zones.d.ts @@ -82,6 +82,12 @@ export interface Settings { */ weekStart?: DayOfWeek | null; + /** + * Weekend days used by `isWeekend()`, `isWeekday()`, and `DateRange.count('weekdays' | 'weekends')`. + * Overrides the active locale when set (pass `[]` for no weekend days, or `null` to follow the locale). + */ + weekend?: readonly DayOfWeek[] | null; + /** * Custom weekday labels keyed by language tag, width (narrow, short, or long), and any weekday name or * three-or-more-letter prefix such as `'fri'` or `'friday'`. @@ -138,6 +144,8 @@ export interface ActiveSettings { locale: Locale | undefined; /** Active ISO week-start number (1–7), or `undefined` when following the locale. */ weekStart: number | undefined; + /** Active frozen ISO weekend day numbers (1–7), or `undefined` when following the locale. */ + weekend: readonly number[] | undefined; /** Loose numeric date order set with `@native-dates/plugins/loose`, or `undefined` when following the locale. */ dayFirst: boolean | undefined; /** Active custom zone alias map registered via `@native-dates/plugins/zones`. */ @@ -159,7 +167,7 @@ export interface ActiveSettings { * * @param settings - Process-wide defaults to update, leaving omitted keys unchanged * @returns A shallow copy of the active settings after applying any updates - * @throws {RangeError} When an unrecognized setting key (`unknownSetting`), time zone (`unknownZone`), locale (`unknownLocale`), weekday (`unknownDayOfWeek`), width (`unknownWidth`), invalid alias map (`invalidZoneAliases`), or unimported plugin option (`missingPlugin`) is passed + * @throws {RangeError} When an unrecognized setting key (`unknownSetting`), time zone (`unknownZone`), locale (`unknownLocale`), weekday (`unknownDayOfWeek`), weekend list (`invalidWeekend`), width (`unknownWidth`), invalid alias map (`invalidZoneAliases`), or unimported plugin option (`missingPlugin`) is passed * * @example * ```ts