@vielzeug/tempo 2.0.0 → 2.1.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.
- package/dist/_convert.cjs.map +1 -1
- package/dist/_convert.d.ts.map +1 -1
- package/dist/_convert.js.map +1 -1
- package/dist/_floor.cjs +1 -1
- package/dist/_floor.cjs.map +1 -1
- package/dist/_floor.d.ts +3 -3
- package/dist/_floor.d.ts.map +1 -1
- package/dist/_floor.js +0 -1
- package/dist/_floor.js.map +1 -1
- package/dist/_tz.cjs +1 -1
- package/dist/_tz.cjs.map +1 -1
- package/dist/_tz.d.ts +0 -2
- package/dist/_tz.d.ts.map +1 -1
- package/dist/_tz.js +2 -5
- package/dist/_tz.js.map +1 -1
- package/dist/boundary.cjs +1 -1
- package/dist/boundary.cjs.map +1 -1
- package/dist/boundary.d.ts +1 -1
- package/dist/boundary.d.ts.map +1 -1
- package/dist/boundary.js +0 -1
- package/dist/boundary.js.map +1 -1
- package/dist/classify.cjs.map +1 -1
- package/dist/classify.d.ts.map +1 -1
- package/dist/classify.js.map +1 -1
- package/dist/compare.cjs +1 -1
- package/dist/compare.cjs.map +1 -1
- package/dist/compare.d.ts +1 -1
- package/dist/compare.d.ts.map +1 -1
- package/dist/compare.js +20 -17
- package/dist/compare.js.map +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js.map +1 -1
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +0 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -4
- package/dist/errors.js.map +1 -1
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.ts +10 -4
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -6
- package/dist/range.cjs.map +1 -1
- package/dist/range.d.ts.map +1 -1
- package/dist/range.js.map +1 -1
- package/dist/tempo.cjs +1 -1
- package/dist/tempo.cjs.map +1 -1
- package/dist/tempo.iife.js +1 -1
- package/dist/tempo.iife.js.map +1 -1
- package/dist/tempo.js +1 -1
- package/dist/tempo.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +23 -18
package/dist/format.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeZoneOptions,\n} from './types';\n\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const timeZone = options.timeZone ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${timeZone ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = timeZone !== undefined ? { ...options.intl, timeZone: timeZone } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${timeZone ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: timeZone }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.timeZone` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.timeZone) return options.timeZone;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.\n *\n * @example\n * ```ts\n * format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).format(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const timeZone = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRange(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const timeZone = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n * Requires `options.timeZone` when input is a `PlainDate` or `PlainDateTime`.\n *\n * @example\n * ```ts\n * formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeZoneOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.timeZone - Required when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred automatically from a `ZonedDateTime` or `Instant` input.\n *\n * @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.\n *\n * @example\n * ```ts\n * formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeZoneOptions = {}): string {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { timeZone }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {\n * base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).formatToParts(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.NumberFormat(options.locale).format(value) : String(value);\n\n return `${formatted} ${value === 1 ? unit : `${unit}s`}`;\n}\n"],"mappings":"0HA2BA,IAAM,EAAsB,IAE5B,SAAS,EAAqB,EAAuB,EAAa,EAAqB,CACrF,IAAM,EAAS,EAAM,IAAI,CAAG,EAE5B,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,GAAI,EAAM,MAAQ,EAAqB,CACrC,IAAM,EAAS,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAE/B,IAAW,IAAA,IAAW,EAAM,OAAO,CAAM,CAC/C,CAEA,IAAM,EAAQ,EAAQ,EAItB,OAFA,EAAM,IAAI,EAAK,CAAK,EAEb,CACT,CAEA,IAAM,EAA4B,IAAI,IAChC,EAAgC,IAAI,IACpC,EAA2B,IAAI,IAI/B,EAAoE,CACxE,YAAa,CAAE,UAAW,OAAQ,EAClC,KAAM,CAAE,UAAW,OAAQ,UAAW,MAAO,EAC7C,OAAQ,CAAE,UAAW,SAAU,UAAW,OAAQ,EAClD,MAAO,CAAE,UAAW,QAAS,UAAW,OAAQ,EAChD,YAAa,CAAE,UAAW,OAAQ,CACpC,EAIA,SAAS,EAAqB,EAA6C,CACzE,OAAO,KAAK,UACV,OAAO,QAAQ,CAAO,CAAC,CACpB,QAAQ,EAAG,KAAW,IAAU,IAAA,EAAS,CAAC,CAC1C,MAAM,CAAC,GAAI,CAAC,KAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,EAAK,KAAW,C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1
|
+
{"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeZoneOptions,\n} from './types';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const timeZone = options.timeZone ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${timeZone ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = timeZone !== undefined ? { ...options.intl, timeZone: timeZone } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${timeZone ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: timeZone }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.timeZone` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.timeZone) return options.timeZone;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.\n *\n * @example\n * ```ts\n * format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).format(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const timeZone = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRange(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const timeZone = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n *\n * Pass `options.timeZone` when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred from `ZonedDateTime`; ignored for `Instant`.\n *\n * @throws {TempoMissingTzError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.\n * @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.\n *\n * @example\n * ```ts\n * formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeZoneOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.timeZone - Required when `input` is a `PlainDate`, `PlainDateTime`, or `Instant`.\n * Inferred automatically from a `ZonedDateTime` input.\n *\n * @throws {TempoMissingTzError} When `input` is not a `ZonedDateTime` and `options.timeZone` is omitted.\n * @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.\n *\n * @example\n * ```ts\n * formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeZoneOptions = {}): string {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { timeZone }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {\n * base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).formatToParts(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.NumberFormat(options.locale).format(value) : String(value);\n\n return `${formatted} ${value === 1 ? unit : `${unit}s`}`;\n}\n"],"mappings":"0HAyBA,IAAM,EAAsB,IAE5B,SAAS,EAAqB,EAAuB,EAAa,EAAqB,CACrF,IAAM,EAAS,EAAM,IAAI,CAAG,EAE5B,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,GAAI,EAAM,MAAQ,EAAqB,CACrC,IAAM,EAAS,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAE/B,IAAW,IAAA,IAAW,EAAM,OAAO,CAAM,CAC/C,CAEA,IAAM,EAAQ,EAAQ,EAItB,OAFA,EAAM,IAAI,EAAK,CAAK,EAEb,CACT,CAEA,IAAM,EAA4B,IAAI,IAChC,EAAgC,IAAI,IACpC,EAA2B,IAAI,IAI/B,EAAoE,CACxE,YAAa,CAAE,UAAW,OAAQ,EAClC,KAAM,CAAE,UAAW,OAAQ,UAAW,MAAO,EAC7C,OAAQ,CAAE,UAAW,SAAU,UAAW,OAAQ,EAClD,MAAO,CAAE,UAAW,QAAS,UAAW,OAAQ,EAChD,YAAa,CAAE,UAAW,OAAQ,CACpC,EAIA,SAAS,EAAqB,EAA6C,CACzE,OAAO,KAAK,UACV,OAAO,QAAQ,CAAO,CAAC,CACpB,QAAQ,EAAG,KAAW,IAAU,IAAA,EAAS,CAAC,CAC1C,MAAM,CAAC,GAAI,CAAC,KAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,EAAK,KAAW,CAAC,EAAK,OAAO,CAAK,CAAC,CAAC,CAC/C,CACF,CAEA,SAAS,EAAc,E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imeInput, options?:
|
|
|
36
36
|
export declare function formatRangeParts(start: TimeInput, end: TimeInput, options?: FormatOptions): ReturnType<Intl.DateTimeFormat['formatRangeToParts']>;
|
|
37
37
|
/**
|
|
38
38
|
* Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).
|
|
39
|
-
*
|
|
39
|
+
*
|
|
40
|
+
* Pass `options.timeZone` when `input` is a `PlainDate` or `PlainDateTime`.
|
|
41
|
+
* Inferred from `ZonedDateTime`; ignored for `Instant`.
|
|
42
|
+
*
|
|
43
|
+
* @throws {TempoMissingTzError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.
|
|
44
|
+
* @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.
|
|
40
45
|
*
|
|
41
46
|
* @example
|
|
42
47
|
* ```ts
|
|
@@ -48,10 +53,11 @@ export declare function formatInstant(input: TimeInput, options?: TimeZoneOption
|
|
|
48
53
|
/**
|
|
49
54
|
* Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).
|
|
50
55
|
*
|
|
51
|
-
* @param options.timeZone - Required when `input` is a `PlainDate` or `
|
|
52
|
-
* Inferred automatically from a `ZonedDateTime`
|
|
56
|
+
* @param options.timeZone - Required when `input` is a `PlainDate`, `PlainDateTime`, or `Instant`.
|
|
57
|
+
* Inferred automatically from a `ZonedDateTime` input.
|
|
53
58
|
*
|
|
54
|
-
* @throws {
|
|
59
|
+
* @throws {TempoMissingTzError} When `input` is not a `ZonedDateTime` and `options.timeZone` is omitted.
|
|
60
|
+
* @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.
|
|
55
61
|
*
|
|
56
62
|
* @example
|
|
57
63
|
* ```ts
|
package/dist/format.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,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,KAAK,EAAE,MAAM,GAAG,QAAQ,CAAC,YAAY,EAAE,OAAO,GAAE,qBAA0B,GAAG,MAAM,CAOjH;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,SAAS,EAAE,OAAO,GAAE,aAAkB,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAIpG;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,GAAE;IAAE,MAAM,CAAC,EAAE,IAAI,CAAC,eAAe,CAAA;CAAO,GAAG,MAAM,CAKtG"}
|
package/dist/format.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeZoneOptions,\n} from './types';\n\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const timeZone = options.timeZone ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${timeZone ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = timeZone !== undefined ? { ...options.intl, timeZone: timeZone } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${timeZone ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: timeZone }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.timeZone` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.timeZone) return options.timeZone;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.\n *\n * @example\n * ```ts\n * format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).format(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const timeZone = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRange(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const timeZone = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n * Requires `options.timeZone` when input is a `PlainDate` or `PlainDateTime`.\n *\n * @example\n * ```ts\n * formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeZoneOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.timeZone - Required when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred automatically from a `ZonedDateTime` or `Instant` input.\n *\n * @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.\n *\n * @example\n * ```ts\n * formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeZoneOptions = {}): string {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { timeZone }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {\n * base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).formatToParts(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.NumberFormat(options.locale).format(value) : String(value);\n\n return `${formatted} ${value === 1 ? unit : `${unit}s`}`;\n}\n"],"mappings":";;;;;AA2BA,IAAM,IAAsB;AAE5B,SAAS,EAAqB,GAAuB,GAAa,GAAqB;CACrF,IAAM,IAAS,EAAM,IAAI,CAAG;CAE5B,IAAI,MAAW,KAAA,GAAW,OAAO;CAEjC,IAAI,EAAM,QAAQ,GAAqB;EACrC,IAAM,IAAS,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EAEnC,AAAI,MAAW,KAAA,KAAW,EAAM,OAAO,CAAM;CAC/C;CAEA,IAAM,IAAQ,EAAQ;CAItB,OAFA,EAAM,IAAI,GAAK,CAAK,GAEb;AACT;AAEA,IAAM,oBAA4B,IAAI,IAAiC,GACjE,oBAAgC,IAAI,IAAqC,GACzE,oBAA2B,IAAI,IAA+B,GAI9D,IAAoE;CACxE,aAAa,EAAE,WAAW,QAAQ;CAClC,MAAM;EAAE,WAAW;EAAQ,WAAW;CAAO;CAC7C,QAAQ;EAAE,WAAW;EAAU,WAAW;CAAQ;CAClD,OAAO;EAAE,WAAW;EAAS,WAAW;CAAQ;CAChD,aAAa,EAAE,WAAW,QAAQ;AACpC;AAIA,SAAS,EAAqB,GAA6C;CACzE,OAA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OAAO,CAAK,IAAI,OAAO,CAAK,EAEjF,GAAG,MAAU,IAAI,IAAO,GAAG,EAAK;AACtD"}
|
|
1
|
+
{"version":3,"file":"format.js","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeZoneOptions,\n} from './types';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const timeZone = options.timeZone ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${timeZone ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = timeZone !== undefined ? { ...options.intl, timeZone: timeZone } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${timeZone ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: timeZone }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.timeZone` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.timeZone) return options.timeZone;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.\n *\n * @example\n * ```ts\n * format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).format(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const timeZone = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRange(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const timeZone = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n *\n * Pass `options.timeZone` when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred from `ZonedDateTime`; ignored for `Instant`.\n *\n * @throws {TempoMissingTzError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.\n * @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.\n *\n * @example\n * ```ts\n * formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeZoneOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.timeZone - Required when `input` is a `PlainDate`, `PlainDateTime`, or `Instant`.\n * Inferred automatically from a `ZonedDateTime` input.\n *\n * @throws {TempoMissingTzError} When `input` is not a `ZonedDateTime` and `options.timeZone` is omitted.\n * @throws {TempoInvalidTzError} When `options.timeZone` is not a valid IANA timezone or UTC offset.\n *\n * @example\n * ```ts\n * formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeZoneOptions = {}): string {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { timeZone }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {\n * base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).formatToParts(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.NumberFormat(options.locale).format(value) : String(value);\n\n return `${formatted} ${value === 1 ? unit : `${unit}s`}`;\n}\n"],"mappings":";;;;;AAyBA,IAAM,IAAsB;AAE5B,SAAS,EAAqB,GAAuB,GAAa,GAAqB;CACrF,IAAM,IAAS,EAAM,IAAI,CAAG;CAE5B,IAAI,MAAW,KAAA,GAAW,OAAO;CAEjC,IAAI,EAAM,QAAQ,GAAqB;EACrC,IAAM,IAAS,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC;EAEnC,AAAI,MAAW,KAAA,KAAW,EAAM,OAAO,CAAM;CAC/C;CAEA,IAAM,IAAQ,EAAQ;CAItB,OAFA,EAAM,IAAI,GAAK,CAAK,GAEb;AACT;AAEA,IAAM,oBAA4B,IAAI,IAAiC,GACjE,oBAAgC,IAAI,IAAqC,GACzE,oBAA2B,IAAI,IAA+B,GAI9D,IAAoE;CACxE,aAAa,EAAE,WAAW,QAAQ;CAClC,MAAM;EAAE,WAAW;EAAQ,WAAW;CAAO;CAC7C,QAAQ;EAAE,WAAW;EAAU,WAAW;CAAQ;CAClD,OAAO;EAAE,WAAW;EAAS,WAAW;CAAQ;CAChD,aAAa,EAAE,WAAW,QAAQ;AACpC;AAIA,SAAS,EAAqB,GAA6C;CACzE,OAAO,KAAK,UACV,OAAO,QAAQ,CAAO,CAAC,CACpB,QAAQ,GAAG,OAAW,MAAU,KAAA,CAAS,CAAC,CAC1C,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cA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
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./_convert.cjs"),n=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./_convert.cjs"),n=require("./boundary.cjs"),r=require("./classify.cjs"),i=require("./compare.cjs"),a=require("./core.cjs"),o=require("./format.cjs"),s=require("./range.cjs");let c=require("@js-temporal/polyfill");exports.TempoError=e.TempoError,exports.TempoInvalidInputError=e.TempoInvalidInputError,exports.TempoInvalidTzError=e.TempoInvalidTzError,exports.TempoMissingTzError=e.TempoMissingTzError,exports.TempoUnsupportedInputError=e.TempoUnsupportedInputError,Object.defineProperty(exports,"Temporal",{enumerable:!0,get:function(){return c.Temporal}}),exports.clamp=i.clamp,exports.classifyExpiry=r.classifyExpiry,exports.contains=i.contains,exports.dateRange=s.dateRange,exports.difference=a.difference,exports.endOf=n.endOf,exports.format=o.format,exports.formatDuration=o.formatDuration,exports.formatInstant=o.formatInstant,exports.formatParts=o.formatParts,exports.formatRange=o.formatRange,exports.formatRangeParts=o.formatRangeParts,exports.formatRelative=o.formatRelative,exports.formatZoned=o.formatZoned,exports.humanize=o.humanize,exports.inTimeZone=t.inTimeZone,exports.isAfter=i.isAfter,exports.isBefore=i.isBefore,exports.isSame=i.isSame,exports.isValid=a.isValid,exports.now=a.now,exports.nowInstant=a.nowInstant,exports.parse=a.parse,exports.parseDuration=o.parseDuration,exports.recurrence=s.recurrence,exports.shift=a.shift,exports.startOf=n.startOf,exports.timeDiff=r.timeDiff,exports.toInstant=t.toInstant;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export { Temporal } from '@js-temporal/polyfill';
|
|
2
|
-
export { TempoError, TempoInvalidInputError, TempoInvalidTzError, TempoMissingTzError, TempoUnsupportedInputError, } from './errors';
|
|
3
|
-
export { difference, isValid, now, nowInstant, parse, shift } from './core';
|
|
4
2
|
export { inTimeZone, toInstant } from './_convert';
|
|
5
3
|
export { endOf, startOf } from './boundary';
|
|
4
|
+
export { classifyExpiry, timeDiff } from './classify';
|
|
6
5
|
export { clamp, contains, isAfter, isBefore, isSame } from './compare';
|
|
6
|
+
export { difference, isValid, now, nowInstant, parse, shift } from './core';
|
|
7
|
+
export { TempoError, TempoInvalidInputError, TempoInvalidTzError, TempoMissingTzError, TempoUnsupportedInputError, } from './errors';
|
|
7
8
|
export { format, formatDuration, formatInstant, formatParts, formatRange, formatRangeParts, formatRelative, formatZoned, humanize, parseDuration, } from './format';
|
|
8
|
-
export { classifyExpiry, timeDiff } from './classify';
|
|
9
9
|
export { dateRange, recurrence } from './range';
|
|
10
10
|
export type { AbsoluteTime, BoundaryOptions, BoundaryUnit, CalendarUnit, ClampInput, ClassifyExpiryInput, CompareOptions, ContainsInput, DifferenceInput, Disambiguation, DisambiguationOptions, DurationFormatOptions, ExpiryThresholds, FixedDuration, FormatOptions, FormatPattern, ParseAs, RecurrenceRule, RelativeFormatOptions, RelativeTimeInput, ShiftOptions, TempoUnit, TimeDiffResult, TimeDiffUnit, TimeInput, TimeZoneOptions, WallTime, WeekStartDay, } from './types';
|
|
11
11
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC5E,OAAO,EACL,UAAU,EACV,sBAAsB,EACtB,mBAAmB,EACnB,mBAAmB,EACnB,0BAA0B,GAC3B,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,MAAM,EACN,cAAc,EACd,aAAa,EACb,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,QAAQ,EACR,aAAa,GACd,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAChD,YAAY,EACV,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,mBAAmB,EACnB,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,EACb,aAAa,EACb,aAAa,EACb,OAAO,EACP,cAAc,EACd,qBAAqB,EACrB,iBAAiB,EACjB,YAAY,EACZ,SAAS,EACT,cAAc,EACd,YAAY,EACZ,SAAS,EACT,eAAe,EACf,QAAQ,EACR,YAAY,GACb,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { TempoError as e, TempoInvalidInputError as t, TempoInvalidTzError as n, TempoMissingTzError as r, TempoUnsupportedInputError as i } from "./errors.js";
|
|
2
2
|
import { inTimeZone as a, toInstant as o } from "./_convert.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { clamp as
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
3
|
+
import { endOf as s, startOf as c } from "./boundary.js";
|
|
4
|
+
import { classifyExpiry as l, timeDiff as u } from "./classify.js";
|
|
5
|
+
import { clamp as d, contains as f, isAfter as p, isBefore as m, isSame as h } from "./compare.js";
|
|
6
|
+
import { difference as g, isValid as _, now as v, nowInstant as y, parse as b, shift as x } from "./core.js";
|
|
7
|
+
import { format as S, formatDuration as C, formatInstant as w, formatParts as T, formatRange as E, formatRangeParts as D, formatRelative as O, formatZoned as k, humanize as A, parseDuration as j } from "./format.js";
|
|
8
8
|
import { dateRange as M, recurrence as N } from "./range.js";
|
|
9
9
|
import { Temporal as P } from "@js-temporal/polyfill";
|
|
10
|
-
export { e as TempoError, t as TempoInvalidInputError, n as TempoInvalidTzError, r as TempoMissingTzError, i as TempoUnsupportedInputError, P as Temporal,
|
|
10
|
+
export { e as TempoError, t as TempoInvalidInputError, n as TempoInvalidTzError, r as TempoMissingTzError, i as TempoUnsupportedInputError, P as Temporal, d as clamp, l as classifyExpiry, f as contains, M as dateRange, g as difference, s as endOf, S as format, C as formatDuration, w as formatInstant, T as formatParts, E as formatRange, D as formatRangeParts, O as formatRelative, k as formatZoned, A as humanize, a as inTimeZone, p as isAfter, m as isBefore, h as isSame, _ as isValid, v as now, y as nowInstant, b as parse, j as parseDuration, N as recurrence, x as shift, c as startOf, u as timeDiff, o as toInstant };
|
package/dist/range.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"range.cjs","names":[],"sources":["../src/range.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\
|
|
1
|
+
{"version":3,"file":"range.cjs","names":[],"sources":["../src/range.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { TempoInvalidInputError } from './errors';\nimport type { RecurrenceRule, TimeInput, TimeZoneOptions } from './types';\n\nexport function dateRange(\n start: TimeInput,\n end: TimeInput,\n step: Temporal.DurationLike,\n options: TimeZoneOptions = {},\n): Generator<Temporal.ZonedDateTime> {\n const timeZone = inferTimeZone(start, options);\n const startZoned = toZoned(start, { timeZone });\n const endZoned = toZoned(end, { timeZone });\n\n if (Temporal.ZonedDateTime.compare(startZoned.add(step), startZoned) <= 0) {\n throw new TempoInvalidInputError('dateRange: step must advance time forward.');\n }\n\n return generateRange(startZoned, endZoned, step);\n}\n\nfunction* generateRange(\n start: Temporal.ZonedDateTime,\n end: Temporal.ZonedDateTime,\n step: Temporal.DurationLike,\n): Generator<Temporal.ZonedDateTime> {\n for (let current = start; Temporal.ZonedDateTime.compare(current, end) <= 0; current = current.add(step)) {\n yield current;\n }\n}\n\nexport function recurrence(\n start: TimeInput,\n rule: RecurrenceRule,\n options: TimeZoneOptions = {},\n): Generator<Temporal.ZonedDateTime> {\n const timeZone = inferTimeZone(start, options);\n const step =\n rule.frequency === 'daily'\n ? { days: rule.interval ?? 1 }\n : rule.frequency === 'weekly'\n ? { weeks: rule.interval ?? 1 }\n : rule.frequency === 'monthly'\n ? { months: rule.interval ?? 1 }\n : { years: rule.interval ?? 1 };\n const until = rule.until ? toInstant(rule.until, { timeZone }) : undefined;\n\n return generateRecurrence(toZoned(start, { timeZone }), step, rule.count, until);\n}\n\nfunction* generateRecurrence(\n start: Temporal.ZonedDateTime,\n step: Temporal.DurationLike,\n count: number | undefined,\n until: Temporal.Instant | undefined,\n): Generator<Temporal.ZonedDateTime> {\n for (\n let current = start, emitted = 0;\n count === undefined || emitted < count;\n current = current.add(step), emitted++\n ) {\n if (until && Temporal.Instant.compare(current.toInstant(), until) > 0) return;\n\n yield current;\n }\n}\n"],"mappings":"0HAMA,SAAgB,EACd,EACA,EACA,EACA,EAA2B,CAAC,EACO,CACnC,IAAM,EAAW,EAAA,cAAc,EAAO,CAAO,EACvC,EAAa,EAAA,QAAQ,EAAO,CAAE,UAAS,CAAC,EACxC,EAAW,EAAA,QAAQ,EAAK,CAAE,UAAS,CAAC,EAE1C,GAAI,EAAA,SAAS,cAAc,QAAQ,EAAW,IAAI,CAAI,EAAG,CAAU,GAAK,EACtE,MAAM,IAAI,EAAA,uBAAuB,4CAA4C,EAG/E,OAAO,EAAc,EAAY,EAAU,CAAI,CACjD,CAEA,SAAU,EACR,EACA,EACA,EACmC,CACnC,IAAK,IAAI,EAAU,EAAO,EAAA,SAAS,cAAc,QAAQ,EAAS,CAAG,GAAK,EAAG,EAAU,EAAQ,IAAI,CAAI,EACrG,MAAM,CAEV,CAEA,SAAgB,EACd,EACA,EACA,EAA2B,CAAC,EACO,CACnC,IAAM,EAAW,EAAA,cAAc,EAAO,CAAO,EACvC,EACJ,EAAK,YAAc,QACf,CAAE,KAAM,EAAK,UAAY,CAAE,EAC3B,EAAK,YAAc,SACjB,CAAE,MAAO,EAAK,UAAY,CAAE,EAC5B,EAAK,YAAc,UACjB,CAAE,OAAQ,EAAK,UAAY,CAAE,EAC7B,CAAE,MAAO,EAAK,UAAY,CAAE,EAChC,EAAQ,EAAK,MAAQ,EAAA,UAAU,EAAK,MAAO,CAAE,UAAS,CAAC,EAAI,IAAA,GAEjE,OAAO,EAAmB,EAAA,QAAQ,EAAO,CAAE,UAAS,CAAC,EAAG,EAAM,EAAK,MAAO,CAAK,CACjF,CAEA,SAAU,EACR,EACA,EACA,EACA,EACmC,CACnC,IACE,IAAI,EAAU,EAAO,EAAU,EAC/B,IAAU,IAAA,IAAa,EAAU,EACjC,EAAU,EAAQ,IAAI,CAAI,EAAG,IAC7B,CACA,GAAI,GAAS,EAAA,SAAS,QAAQ,QAAQ,EAAQ,UAAU,EAAG,CAAK,EAAI,EAAG,OAEvE,MAAM,CACR,CACF"}
|
package/dist/range.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"range.d.ts","sourceRoot":"","sources":["../src/range.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"range.d.ts","sourceRoot":"","sources":["../src/range.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAIjD,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1E,wBAAgB,SAAS,CACvB,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,QAAQ,CAAC,YAAY,EAC3B,OAAO,GAAE,eAAoB,GAC5B,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,CAUnC;AAYD,wBAAgB,UAAU,CACxB,KAAK,EAAE,SAAS,EAChB,IAAI,EAAE,cAAc,EACpB,OAAO,GAAE,eAAoB,GAC5B,SAAS,CAAC,QAAQ,CAAC,aAAa,CAAC,CAanC"}
|
package/dist/range.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"range.js","names":[],"sources":["../src/range.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\
|
|
1
|
+
{"version":3,"file":"range.js","names":[],"sources":["../src/range.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { TempoInvalidInputError } from './errors';\nimport type { RecurrenceRule, TimeInput, TimeZoneOptions } from './types';\n\nexport function dateRange(\n start: TimeInput,\n end: TimeInput,\n step: Temporal.DurationLike,\n options: TimeZoneOptions = {},\n): Generator<Temporal.ZonedDateTime> {\n const timeZone = inferTimeZone(start, options);\n const startZoned = toZoned(start, { timeZone });\n const endZoned = toZoned(end, { timeZone });\n\n if (Temporal.ZonedDateTime.compare(startZoned.add(step), startZoned) <= 0) {\n throw new TempoInvalidInputError('dateRange: step must advance time forward.');\n }\n\n return generateRange(startZoned, endZoned, step);\n}\n\nfunction* generateRange(\n start: Temporal.ZonedDateTime,\n end: Temporal.ZonedDateTime,\n step: Temporal.DurationLike,\n): Generator<Temporal.ZonedDateTime> {\n for (let current = start; Temporal.ZonedDateTime.compare(current, end) <= 0; current = current.add(step)) {\n yield current;\n }\n}\n\nexport function recurrence(\n start: TimeInput,\n rule: RecurrenceRule,\n options: TimeZoneOptions = {},\n): Generator<Temporal.ZonedDateTime> {\n const timeZone = inferTimeZone(start, options);\n const step =\n rule.frequency === 'daily'\n ? { days: rule.interval ?? 1 }\n : rule.frequency === 'weekly'\n ? { weeks: rule.interval ?? 1 }\n : rule.frequency === 'monthly'\n ? { months: rule.interval ?? 1 }\n : { years: rule.interval ?? 1 };\n const until = rule.until ? toInstant(rule.until, { timeZone }) : undefined;\n\n return generateRecurrence(toZoned(start, { timeZone }), step, rule.count, until);\n}\n\nfunction* generateRecurrence(\n start: Temporal.ZonedDateTime,\n step: Temporal.DurationLike,\n count: number | undefined,\n until: Temporal.Instant | undefined,\n): Generator<Temporal.ZonedDateTime> {\n for (\n let current = start, emitted = 0;\n count === undefined || emitted < count;\n current = current.add(step), emitted++\n ) {\n if (until && Temporal.Instant.compare(current.toInstant(), until) > 0) return;\n\n yield current;\n }\n}\n"],"mappings":";;;;;AAMA,SAAgB,EACd,GACA,GACA,GACA,IAA2B,CAAC,GACO;CACnC,IAAM,IAAW,EAAc,GAAO,CAAO,GACvC,IAAa,EAAQ,GAAO,EAAE,YAAS,CAAC,GACxC,IAAW,EAAQ,GAAK,EAAE,YAAS,CAAC;CAE1C,IAAI,EAAS,cAAc,QAAQ,EAAW,IAAI,CAAI,GAAG,CAAU,KAAK,GACtE,MAAM,IAAI,EAAuB,4CAA4C;CAG/E,OAAO,EAAc,GAAY,GAAU,CAAI;AACjD;AAEA,UAAU,EACR,GACA,GACA,GACmC;CACnC,KAAK,IAAI,IAAU,GAAO,EAAS,cAAc,QAAQ,GAAS,CAAG,KAAK,GAAG,IAAU,EAAQ,IAAI,CAAI,GACrG,MAAM;AAEV;AAEA,SAAgB,EACd,GACA,GACA,IAA2B,CAAC,GACO;CACnC,IAAM,IAAW,EAAc,GAAO,CAAO,GACvC,IACJ,EAAK,cAAc,UACf,EAAE,MAAM,EAAK,YAAY,EAAE,IAC3B,EAAK,cAAc,WACjB,EAAE,OAAO,EAAK,YAAY,EAAE,IAC5B,EAAK,cAAc,YACjB,EAAE,QAAQ,EAAK,YAAY,EAAE,IAC7B,EAAE,OAAO,EAAK,YAAY,EAAE,GAChC,IAAQ,EAAK,QAAQ,EAAU,EAAK,OAAO,EAAE,YAAS,CAAC,IAAI,KAAA;CAEjE,OAAO,EAAmB,EAAQ,GAAO,EAAE,YAAS,CAAC,GAAG,GAAM,EAAK,OAAO,CAAK;AACjF;AAEA,UAAU,EACR,GACA,GACA,GACA,GACmC;CACnC,KACE,IAAI,IAAU,GAAO,IAAU,GAC/B,MAAU,KAAA,KAAa,IAAU,GACjC,IAAU,EAAQ,IAAI,CAAI,GAAG,KAC7B;EACA,IAAI,KAAS,EAAS,QAAQ,QAAQ,EAAQ,UAAU,GAAG,CAAK,IAAI,GAAG;EAEvE,MAAM;CACR;AACF"}
|
package/dist/tempo.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@js-temporal/polyfill");var t=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},n=class extends t{},r=class extends t{},i=class extends t{},a=class extends t{};function o(e,t=n){throw new t(e)}function s(t){try{e.Temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(t)}catch{o(`Unknown or invalid timezone: "${t}". Expected an IANA timezone name or UTC offset.`,r)}return t}function c(t,n){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return r||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i),s(r)}function l(t,n){if(n.timeZone)return s(n.timeZone);let r;for(let n of t)n instanceof e.Temporal.ZonedDateTime&&(r?r!==n.timeZoneId&&o(`Inputs use different time zones. Pass options.timeZone explicitly.`):r=n.timeZoneId);return r||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i),r}function u(t,n){return e.Temporal.Instant.compare(t,n)<=0?[t,n]:[n,t]}var d=new Set([`day`,`month`,`week`,`year`]);function f(t,n={}){if(t instanceof e.Temporal.Instant)return t;if(t instanceof e.Temporal.ZonedDateTime)return t.toInstant();n.timeZone||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i);let r=s(n.timeZone);if(t instanceof e.Temporal.PlainDateTime)return t.toZonedDateTime(r,{disambiguation:n.disambiguation}).toInstant();if(t instanceof e.Temporal.PlainDate)return t.toZonedDateTime({timeZone:r}).toInstant();o(`Unsupported time input type: ${String(t)}`,a)}function p(t,n){let r=s(n.timeZone);if(t instanceof e.Temporal.ZonedDateTime)return t.withTimeZone(r);if(t instanceof e.Temporal.Instant)return t.toZonedDateTimeISO(r);if(t instanceof e.Temporal.PlainDateTime)return t.toZonedDateTime(r,{disambiguation:n.disambiguation});if(t instanceof e.Temporal.PlainDate)return t.toZonedDateTime({timeZone:r});o(`Unsupported time input type: ${String(t)}`,a)}function m(e,t){return p(e,{timeZone:t})}function h(t,n){try{return n.as===`zonedDateTime`?e.Temporal.ZonedDateTime.from(t):n.as===`instant`?e.Temporal.Instant.from(t):n.as===`plainDateTime`?e.Temporal.PlainDateTime.from(t):e.Temporal.PlainDate.from(t)}catch{o(`Invalid ${n.as} ISO 8601 string: "${t}".`)}}function g(t){return e.Temporal.Now.zonedDateTimeISO(s(t.timeZone))}function ee(){return e.Temporal.Now.instant()}function _(e,t,n={}){let r=c(e,n);return p(e,{disambiguation:n.disambiguation,timeZone:r}).add(t)}function v(t){let{end:n,largestUnit:r,roundingIncrement:i,roundingMode:a,smallestUnit:o,start:s}=t,c={largestUnit:r,roundingIncrement:i,roundingMode:a,smallestUnit:o};if(!(r!==void 0&&d.has(r)||o!==void 0&&d.has(o))&&s instanceof e.Temporal.Instant&&n instanceof e.Temporal.Instant)return n.since(s,c);let u=l([s,n],t),f={disambiguation:t.disambiguation,timeZone:u};return p(n,f).since(p(s,f),c)}function y(t){return t instanceof e.Temporal.Instant||t instanceof e.Temporal.ZonedDateTime||t instanceof e.Temporal.PlainDateTime||t instanceof e.Temporal.PlainDate}var b={hour:0,microsecond:0,millisecond:0,minute:0,nanosecond:0,second:0},x={day:b,hour:{microsecond:0,millisecond:0,minute:0,nanosecond:0,second:0},minute:{microsecond:0,millisecond:0,nanosecond:0,second:0},month:{...b,day:1},year:{...b,day:1,month:1}};function S(e,t,n){let r=p(e,n);if(t===`week`){let e=(r.dayOfWeek-(n.weekStartsOn??1)+7)%7;return r.subtract({days:e}).with(b).toInstant()}return r.with(x[t]).toInstant()}var C={day:{days:1},hour:{hours:1},minute:{minutes:1},month:{months:1},week:{weeks:1},year:{years:1}};function w(e,t,n={}){let r=c(e,n);return S(e,t,{timeZone:r,weekStartsOn:n.weekStartsOn}).toZonedDateTimeISO(r)}function T(e,t,n={}){let r=c(e,n);return S(e,t,{timeZone:r,weekStartsOn:n.weekStartsOn}).toZonedDateTimeISO(r).add(C[t]).subtract({nanoseconds:1})}function E(t,n,r){if(!r.unit)return e.Temporal.Instant.compare(f(t,r),f(n,r));let i={timeZone:l([t,n],r),weekStartsOn:r.weekStartsOn};return e.Temporal.Instant.compare(S(t,r.unit,i),S(n,r.unit,i))}function D({end:e,start:t,value:n,...r}){if(!r.unit){let i=f(n,r),[a,o]=u(f(t,r),f(e,r));return{lower:a,target:i,upper:o}}let i={timeZone:l([n,t,e],r),weekStartsOn:r.weekStartsOn},a=S(n,r.unit,i),[o,s]=u(S(t,r.unit,i),S(e,r.unit,i));return{lower:o,target:a,upper:s}}function te(e,t,n={}){return E(e,t,n)<0}function ne(e,t,n={}){return E(e,t,n)>0}function re(e,t,n={}){return E(e,t,n)===0}function O(t){let{lower:n,target:r,upper:i}=D(t);return e.Temporal.Instant.compare(n,r)<=0&&e.Temporal.Instant.compare(r,i)<=0}function k(t){let{lower:n,target:r,upper:i}=D(t),a=e.Temporal.Instant.compare(r,n)<0?n:e.Temporal.Instant.compare(r,i)>0?i:r;return t.value instanceof e.Temporal.ZonedDateTime?a.toZonedDateTimeISO(t.timeZone??t.value.timeZoneId):a}var A=128;function j(e,t,n){let r=e.get(t);if(r!==void 0)return r;if(e.size>=A){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let i=n();return e.set(t,i),i}var M=new Map,N=new Map,P=new Map,F={"date-only":{dateStyle:`short`},long:{dateStyle:`full`,timeStyle:`long`},medium:{dateStyle:`medium`,timeStyle:`short`},short:{dateStyle:`short`,timeStyle:`short`},"time-only":{timeStyle:`short`}};function I(e){return JSON.stringify(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,String(t)]))}function L(e,t){let n=e.timeZone??t,r=e.locale;if(e.intl!==void 0)return j(M,`${String(r??``)}|intl|${n??``}|${I(e.intl)}`,()=>{let t=n===void 0?e.intl:{...e.intl,timeZone:n};return new Intl.DateTimeFormat(r,t)});let i=e.pattern??`medium`;return j(M,`${String(r??``)}|${i}|${n??``}`,()=>new Intl.DateTimeFormat(r,{...F[i],timeZone:n}))}function R(e){return j(N,`${String(e.locale??``)}|${e.numeric??`auto`}|${e.style??`long`}`,()=>new Intl.RelativeTimeFormat(e.locale,{numeric:e.numeric??`auto`,style:e.style??`long`}))}function z(e){let t=Intl;return t.DurationFormat?j(P,`${String(e.locale??``)}|${e.style??``}`,()=>new t.DurationFormat(e.locale,{style:e.style})):null}var B=60,V=3600,H=86400,U=604800,W=2629800,G=31557600,K=[{scale:1,thresholdToPromote:B,unit:`second`},{scale:B,thresholdToPromote:V/B,unit:`minute`},{scale:V,thresholdToPromote:H/V,unit:`hour`},{scale:H,thresholdToPromote:U/H,unit:`day`},{scale:U,thresholdToPromote:W/U,unit:`week`},{scale:W,thresholdToPromote:12,unit:`month`},{scale:G,thresholdToPromote:1/0,unit:`year`}];function q(e){Number.isFinite(e)||o(`formatRelative received a non-finite time difference.`);let t=Math.round(e);for(let{scale:e,thresholdToPromote:n,unit:r}of K){let i=Math.round(t/e);if(Math.abs(i)<n)return{unit:r,value:i}}return{unit:`year`,value:Math.round(t/G)}}var ie=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`];function J(e){let t=[];for(let n of ie){let r=Math.abs(e[n]);r!==0&&t.push(`${r} ${r===1?n.slice(0,-1):n}`)}return t.length===0?`0 seconds`:t.join(`, `)}function Y(t,n,r,i){if(r.timeZone)return r.timeZone;let a=t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0,s=n instanceof e.Temporal.ZonedDateTime?n.timeZoneId:void 0;return a&&s&&a!==s&&o(`${i} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`),a??s}function ae(t,n={}){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return L(n,r).format(new Date(f(t,{timeZone:r}).epochMilliseconds))}function oe(e,t,n={}){let r=Y(e,t,n,`formatRange`);return L(n,r).formatRange(new Date(f(e,{timeZone:r}).epochMilliseconds),new Date(f(t,{timeZone:r}).epochMilliseconds))}function se(e,t,n={}){let r=Y(e,t,n,`formatRangeParts`);return L(n,r).formatRangeToParts(new Date(f(e,{timeZone:r}).epochMilliseconds),new Date(f(t,{timeZone:r}).epochMilliseconds))}function ce(e,t={}){return f(e,t).toString()}function le(e,t={}){return p(e,{timeZone:c(e,t)}).toString()}function ue(t,n={}){let r=t instanceof e.Temporal.Instant?t:t.toInstant(),i=n.base?n.base instanceof e.Temporal.Instant?n.base:n.base.toInstant():e.Temporal.Now.instant(),{unit:a,value:o}=q((r.epochMilliseconds-i.epochMilliseconds)/1e3);return R(n).format(o,a)}function X(t){try{return e.Temporal.Duration.from(t)}catch{o(`Invalid duration input: "${String(t)}". Expected an ISO 8601 duration string or Temporal.DurationLike.`)}}function de(e,t={}){let n=X(e),r=z(t);return r?r.format(n):J(n)}function fe(t,n={}){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return L(n,r).formatToParts(new Date(f(t,{timeZone:r}).epochMilliseconds))}function pe(e,t={}){let{unit:n,value:r}=e;return`${t.locale?new Intl.NumberFormat(t.locale).format(r):String(r)} ${r===1?n:`${n}s`}`}var Z={day:864e5,hour:36e5,microsecond:1/1e3,millisecond:1,minute:6e4,nanosecond:1/1e6,second:1e3,week:6048e5},me=[{field:`years`,unit:`year`},{field:`months`,unit:`month`},{field:`weeks`,unit:`week`},{field:`days`,unit:`day`},{field:`hours`,unit:`hour`},{field:`minutes`,unit:`minute`},{field:`seconds`,unit:`second`},{field:`milliseconds`,unit:`millisecond`}];function Q(t){let r=e.Temporal.Duration.from(t);if(r.years||r.months)throw new n(`classifyExpiry thresholds cannot contain months or years. Use fixed elapsed-time units.`);return r.weeks*Z.week+r.days*Z.day+r.hours*Z.hour+r.minutes*Z.minute+r.seconds*Z.second+r.milliseconds+r.microseconds*Z.microsecond+r.nanoseconds*Z.nanosecond}function he(t){let n=t.relativeTo??e.Temporal.Now.instant(),r=f(t.value,t).epochMilliseconds-n.epochMilliseconds;return Object.entries(t.thresholds).map(([e,t])=>({key:e,max:Q(t)})).sort((e,t)=>e.max-t.max).find(({max:e})=>r<=e)?.key??null}function $(e){for(let{field:t,unit:n}of me){let r=Math.abs(e[t]);if(r>0)return{unit:n,value:r}}return{unit:`millisecond`,value:0}}function ge(t,n=e.Temporal.Now.instant(),r={}){if(!r.timeZone&&t instanceof e.Temporal.Instant&&n instanceof e.Temporal.Instant){let r=t.toZonedDateTimeISO(`UTC`),i=n.toZonedDateTimeISO(`UTC`);return $(e.Temporal.ZonedDateTime.compare(r,i)<=0?i.since(r,{largestUnit:`year`}):r.since(i,{largestUnit:`year`}))}let i=l([t,n],r),a=p(t,{timeZone:i}),o=p(n,{timeZone:i});return $(e.Temporal.ZonedDateTime.compare(a,o)<=0?o.since(a,{largestUnit:`year`}):a.since(o,{largestUnit:`year`}))}function _e(t,r,i,a={}){let o=c(t,a),s=p(t,{timeZone:o}),l=p(r,{timeZone:o});if(e.Temporal.ZonedDateTime.compare(s.add(i),s)<=0)throw new n(`dateRange: step must advance time forward.`);return ve(s,l,i)}function*ve(t,n,r){for(let i=t;e.Temporal.ZonedDateTime.compare(i,n)<=0;i=i.add(r))yield i}function ye(e,t,n={}){let r=c(e,n),i=t.frequency===`daily`?{days:t.interval??1}:t.frequency===`weekly`?{weeks:t.interval??1}:t.frequency===`monthly`?{months:t.interval??1}:{years:t.interval??1},a=t.until?f(t.until,{timeZone:r}):void 0;return be(p(e,{timeZone:r}),i,t.count,a)}function*be(t,n,r,i){for(let a=t,o=0;r===void 0||o<r;a=a.add(n),o++){if(i&&e.Temporal.Instant.compare(a.toInstant(),i)>0)return;yield a}}exports.TempoError=t,exports.TempoInvalidInputError=n,exports.TempoInvalidTzError=r,exports.TempoMissingTzError=i,exports.TempoUnsupportedInputError=a,Object.defineProperty(exports,"Temporal",{enumerable:!0,get:function(){return e.Temporal}}),exports.clamp=k,exports.classifyExpiry=he,exports.contains=O,exports.dateRange=_e,exports.difference=v,exports.endOf=T,exports.format=ae,exports.formatDuration=de,exports.formatInstant=ce,exports.formatParts=fe,exports.formatRange=oe,exports.formatRangeParts=se,exports.formatRelative=ue,exports.formatZoned=le,exports.humanize=pe,exports.inTimeZone=m,exports.isAfter=ne,exports.isBefore=te,exports.isSame=re,exports.isValid=y,exports.now=g,exports.nowInstant=ee,exports.parse=h,exports.parseDuration=X,exports.recurrence=ye,exports.shift=_,exports.startOf=w,exports.timeDiff=ge,exports.toInstant=f;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@js-temporal/polyfill");var t=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},n=class extends t{},r=class extends t{},i=class extends t{},a=class extends t{};function o(e,t=n){throw new t(e)}function s(t){try{e.Temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(t)}catch{o(`Unknown or invalid timezone: "${t}". Expected an IANA timezone name or UTC offset.`,r)}return t}function c(t,n){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return r||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i),s(r)}function l(t,n){if(n.timeZone)return s(n.timeZone);let r;for(let n of t)n instanceof e.Temporal.ZonedDateTime&&(r?r!==n.timeZoneId&&o(`Inputs use different time zones. Pass options.timeZone explicitly.`):r=n.timeZoneId);return r||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i),r}var u=new Set([`day`,`month`,`week`,`year`]);function d(t,n={}){if(t instanceof e.Temporal.Instant)return t;if(t instanceof e.Temporal.ZonedDateTime)return t.toInstant();n.timeZone||o(`This operation requires a timeZone. Pass options.timeZone or use a ZonedDateTime input.`,i);let r=s(n.timeZone);if(t instanceof e.Temporal.PlainDateTime)return t.toZonedDateTime(r,{disambiguation:n.disambiguation}).toInstant();if(t instanceof e.Temporal.PlainDate)return t.toZonedDateTime({timeZone:r}).toInstant();o(`Unsupported time input type: ${String(t)}`,a)}function f(t,n){let r=s(n.timeZone);if(t instanceof e.Temporal.ZonedDateTime)return t.withTimeZone(r);if(t instanceof e.Temporal.Instant)return t.toZonedDateTimeISO(r);if(t instanceof e.Temporal.PlainDateTime)return t.toZonedDateTime(r,{disambiguation:n.disambiguation});if(t instanceof e.Temporal.PlainDate)return t.toZonedDateTime({timeZone:r});o(`Unsupported time input type: ${String(t)}`,a)}function p(e,t){return f(e,{timeZone:t})}var m={hour:0,microsecond:0,millisecond:0,minute:0,nanosecond:0,second:0},h={day:m,hour:{microsecond:0,millisecond:0,minute:0,nanosecond:0,second:0},minute:{microsecond:0,millisecond:0,nanosecond:0,second:0},month:{...m,day:1},year:{...m,day:1,month:1}};function g(e,t,n){let r=f(e,n);if(t===`week`){let e=(r.dayOfWeek-(n.weekStartsOn??1)+7)%7;return r.subtract({days:e}).with(m).toInstant()}return r.with(h[t]).toInstant()}var _={day:{days:1},hour:{hours:1},minute:{minutes:1},month:{months:1},week:{weeks:1},year:{years:1}};function v(e,t,n={}){let r=c(e,n);return g(e,t,{timeZone:r,weekStartsOn:n.weekStartsOn}).toZonedDateTimeISO(r)}function ee(e,t,n={}){let r=c(e,n);return g(e,t,{timeZone:r,weekStartsOn:n.weekStartsOn}).toZonedDateTimeISO(r).add(_[t]).subtract({nanoseconds:1})}var y={day:864e5,hour:36e5,microsecond:1/1e3,millisecond:1,minute:6e4,nanosecond:1/1e6,second:1e3,week:6048e5},b=[{field:`years`,unit:`year`},{field:`months`,unit:`month`},{field:`weeks`,unit:`week`},{field:`days`,unit:`day`},{field:`hours`,unit:`hour`},{field:`minutes`,unit:`minute`},{field:`seconds`,unit:`second`},{field:`milliseconds`,unit:`millisecond`}];function x(t){let r=e.Temporal.Duration.from(t);if(r.years||r.months)throw new n(`classifyExpiry thresholds cannot contain months or years. Use fixed elapsed-time units.`);return r.weeks*y.week+r.days*y.day+r.hours*y.hour+r.minutes*y.minute+r.seconds*y.second+r.milliseconds+r.microseconds*y.microsecond+r.nanoseconds*y.nanosecond}function S(t){let n=t.relativeTo??e.Temporal.Now.instant(),r=d(t.value,t).epochMilliseconds-n.epochMilliseconds;return Object.entries(t.thresholds).map(([e,t])=>({key:e,max:x(t)})).sort((e,t)=>e.max-t.max).find(({max:e})=>r<=e)?.key??null}function C(e){for(let{field:t,unit:n}of b){let r=Math.abs(e[t]);if(r>0)return{unit:n,value:r}}return{unit:`millisecond`,value:0}}function w(t,n=e.Temporal.Now.instant(),r={}){if(!r.timeZone&&t instanceof e.Temporal.Instant&&n instanceof e.Temporal.Instant){let r=t.toZonedDateTimeISO(`UTC`),i=n.toZonedDateTimeISO(`UTC`);return C(e.Temporal.ZonedDateTime.compare(r,i)<=0?i.since(r,{largestUnit:`year`}):r.since(i,{largestUnit:`year`}))}let i=l([t,n],r),a=f(t,{timeZone:i}),o=f(n,{timeZone:i});return C(e.Temporal.ZonedDateTime.compare(a,o)<=0?o.since(a,{largestUnit:`year`}):a.since(o,{largestUnit:`year`}))}function T(t,n){return e.Temporal.Instant.compare(t,n)<=0?[t,n]:[n,t]}function E(t,n,r){if(!r.unit)return e.Temporal.Instant.compare(d(t,r),d(n,r));let i={timeZone:l([t,n],r),weekStartsOn:r.weekStartsOn};return e.Temporal.Instant.compare(g(t,r.unit,i),g(n,r.unit,i))}function D({end:e,start:t,value:n,...r}){if(!r.unit){let i=d(n,r),[a,o]=T(d(t,r),d(e,r));return{lower:a,target:i,upper:o}}let i={timeZone:l([n,t,e],r),weekStartsOn:r.weekStartsOn},a=g(n,r.unit,i),[o,s]=T(g(t,r.unit,i),g(e,r.unit,i));return{lower:o,target:a,upper:s}}function te(e,t,n={}){return E(e,t,n)<0}function ne(e,t,n={}){return E(e,t,n)>0}function re(e,t,n={}){return E(e,t,n)===0}function ie(t){let{lower:n,target:r,upper:i}=D(t);return e.Temporal.Instant.compare(n,r)<=0&&e.Temporal.Instant.compare(r,i)<=0}function O(t){let{lower:n,target:r,upper:i}=D(t),a=e.Temporal.Instant.compare(r,n)<0?n:e.Temporal.Instant.compare(r,i)>0?i:r;return t.value instanceof e.Temporal.ZonedDateTime?a.toZonedDateTimeISO(t.timeZone??t.value.timeZoneId):a}function k(t,n){try{return n.as===`zonedDateTime`?e.Temporal.ZonedDateTime.from(t):n.as===`instant`?e.Temporal.Instant.from(t):n.as===`plainDateTime`?e.Temporal.PlainDateTime.from(t):e.Temporal.PlainDate.from(t)}catch{o(`Invalid ${n.as} ISO 8601 string: "${t}".`)}}function A(t){return e.Temporal.Now.zonedDateTimeISO(s(t.timeZone))}function j(){return e.Temporal.Now.instant()}function M(e,t,n={}){let r=c(e,n);return f(e,{disambiguation:n.disambiguation,timeZone:r}).add(t)}function N(t){let{end:n,largestUnit:r,roundingIncrement:i,roundingMode:a,smallestUnit:o,start:s}=t,c={largestUnit:r,roundingIncrement:i,roundingMode:a,smallestUnit:o};if(!(r!==void 0&&u.has(r)||o!==void 0&&u.has(o))&&s instanceof e.Temporal.Instant&&n instanceof e.Temporal.Instant)return n.since(s,c);let d=l([s,n],t),p={disambiguation:t.disambiguation,timeZone:d};return f(n,p).since(f(s,p),c)}function P(t){return t instanceof e.Temporal.Instant||t instanceof e.Temporal.ZonedDateTime||t instanceof e.Temporal.PlainDateTime||t instanceof e.Temporal.PlainDate}var F=128;function I(e,t,n){let r=e.get(t);if(r!==void 0)return r;if(e.size>=F){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let i=n();return e.set(t,i),i}var L=new Map,R=new Map,z=new Map,B={"date-only":{dateStyle:`short`},long:{dateStyle:`full`,timeStyle:`long`},medium:{dateStyle:`medium`,timeStyle:`short`},short:{dateStyle:`short`,timeStyle:`short`},"time-only":{timeStyle:`short`}};function V(e){return JSON.stringify(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,String(t)]))}function H(e,t){let n=e.timeZone??t,r=e.locale;if(e.intl!==void 0)return I(L,`${String(r??``)}|intl|${n??``}|${V(e.intl)}`,()=>{let t=n===void 0?e.intl:{...e.intl,timeZone:n};return new Intl.DateTimeFormat(r,t)});let i=e.pattern??`medium`;return I(L,`${String(r??``)}|${i}|${n??``}`,()=>new Intl.DateTimeFormat(r,{...B[i],timeZone:n}))}function U(e){return I(R,`${String(e.locale??``)}|${e.numeric??`auto`}|${e.style??`long`}`,()=>new Intl.RelativeTimeFormat(e.locale,{numeric:e.numeric??`auto`,style:e.style??`long`}))}function W(e){let t=Intl;return t.DurationFormat?I(z,`${String(e.locale??``)}|${e.style??``}`,()=>new t.DurationFormat(e.locale,{style:e.style})):null}var G=60,K=3600,q=86400,J=604800,Y=2629800,X=31557600,ae=[{scale:1,thresholdToPromote:G,unit:`second`},{scale:G,thresholdToPromote:K/G,unit:`minute`},{scale:K,thresholdToPromote:q/K,unit:`hour`},{scale:q,thresholdToPromote:J/q,unit:`day`},{scale:J,thresholdToPromote:Y/J,unit:`week`},{scale:Y,thresholdToPromote:12,unit:`month`},{scale:X,thresholdToPromote:1/0,unit:`year`}];function oe(e){Number.isFinite(e)||o(`formatRelative received a non-finite time difference.`);let t=Math.round(e);for(let{scale:e,thresholdToPromote:n,unit:r}of ae){let i=Math.round(t/e);if(Math.abs(i)<n)return{unit:r,value:i}}return{unit:`year`,value:Math.round(t/X)}}var se=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`];function ce(e){let t=[];for(let n of se){let r=Math.abs(e[n]);r!==0&&t.push(`${r} ${r===1?n.slice(0,-1):n}`)}return t.length===0?`0 seconds`:t.join(`, `)}function Z(t,n,r,i){if(r.timeZone)return r.timeZone;let a=t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0,s=n instanceof e.Temporal.ZonedDateTime?n.timeZoneId:void 0;return a&&s&&a!==s&&o(`${i} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`),a??s}function le(t,n={}){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return H(n,r).format(new Date(d(t,{timeZone:r}).epochMilliseconds))}function ue(e,t,n={}){let r=Z(e,t,n,`formatRange`);return H(n,r).formatRange(new Date(d(e,{timeZone:r}).epochMilliseconds),new Date(d(t,{timeZone:r}).epochMilliseconds))}function de(e,t,n={}){let r=Z(e,t,n,`formatRangeParts`);return H(n,r).formatRangeToParts(new Date(d(e,{timeZone:r}).epochMilliseconds),new Date(d(t,{timeZone:r}).epochMilliseconds))}function fe(e,t={}){return d(e,t).toString()}function pe(e,t={}){return f(e,{timeZone:c(e,t)}).toString()}function me(t,n={}){let r=t instanceof e.Temporal.Instant?t:t.toInstant(),i=n.base?n.base instanceof e.Temporal.Instant?n.base:n.base.toInstant():e.Temporal.Now.instant(),{unit:a,value:o}=oe((r.epochMilliseconds-i.epochMilliseconds)/1e3);return U(n).format(o,a)}function Q(t){try{return e.Temporal.Duration.from(t)}catch{o(`Invalid duration input: "${String(t)}". Expected an ISO 8601 duration string or Temporal.DurationLike.`)}}function he(e,t={}){let n=Q(e),r=W(t);return r?r.format(n):ce(n)}function ge(t,n={}){let r=n.timeZone??(t instanceof e.Temporal.ZonedDateTime?t.timeZoneId:void 0);return H(n,r).formatToParts(new Date(d(t,{timeZone:r}).epochMilliseconds))}function $(e,t={}){let{unit:n,value:r}=e;return`${t.locale?new Intl.NumberFormat(t.locale).format(r):String(r)} ${r===1?n:`${n}s`}`}function _e(t,r,i,a={}){let o=c(t,a),s=f(t,{timeZone:o}),l=f(r,{timeZone:o});if(e.Temporal.ZonedDateTime.compare(s.add(i),s)<=0)throw new n(`dateRange: step must advance time forward.`);return ve(s,l,i)}function*ve(t,n,r){for(let i=t;e.Temporal.ZonedDateTime.compare(i,n)<=0;i=i.add(r))yield i}function ye(e,t,n={}){let r=c(e,n),i=t.frequency===`daily`?{days:t.interval??1}:t.frequency===`weekly`?{weeks:t.interval??1}:t.frequency===`monthly`?{months:t.interval??1}:{years:t.interval??1},a=t.until?d(t.until,{timeZone:r}):void 0;return be(f(e,{timeZone:r}),i,t.count,a)}function*be(t,n,r,i){for(let a=t,o=0;r===void 0||o<r;a=a.add(n),o++){if(i&&e.Temporal.Instant.compare(a.toInstant(),i)>0)return;yield a}}exports.TempoError=t,exports.TempoInvalidInputError=n,exports.TempoInvalidTzError=r,exports.TempoMissingTzError=i,exports.TempoUnsupportedInputError=a,Object.defineProperty(exports,"Temporal",{enumerable:!0,get:function(){return e.Temporal}}),exports.clamp=O,exports.classifyExpiry=S,exports.contains=ie,exports.dateRange=_e,exports.difference=N,exports.endOf=ee,exports.format=le,exports.formatDuration=he,exports.formatInstant=fe,exports.formatParts=ge,exports.formatRange=ue,exports.formatRangeParts=de,exports.formatRelative=me,exports.formatZoned=pe,exports.humanize=$,exports.inTimeZone=p,exports.isAfter=ne,exports.isBefore=te,exports.isSame=re,exports.isValid=P,exports.now=A,exports.nowInstant=j,exports.parse=k,exports.parseDuration=Q,exports.recurrence=ye,exports.shift=M,exports.startOf=v,exports.timeDiff=w,exports.toInstant=d;
|
|
2
2
|
//# sourceMappingURL=tempo.cjs.map
|