neramjs 0.0.0-stage → 0.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.
@@ -0,0 +1,69 @@
1
+ import { type RelativeTimeOptions } from './relative.ts';
2
+ import { type UnitInput } from './units.ts';
3
+ export declare const DURATION_UNITS: readonly ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds'];
4
+ export type DurationUnit = (typeof DURATION_UNITS)[number];
5
+ export type DurationObject = Partial<Record<DurationUnit, number>>;
6
+ export type DurationInput = Duration | DurationObject | string | number;
7
+ /**
8
+ * An immutable length of time. Calendar units (years, months) are kept apart from exact
9
+ * units so `neram().add(duration)` stays calendar-correct; conversions like `asDays()`
10
+ * use average lengths.
11
+ */
12
+ export declare class Duration {
13
+ #private;
14
+ constructor(input?: DurationInput, unit?: UnitInput | DurationUnit);
15
+ /** False when any part is NaN or infinite, e.g. neram.duration(NaN) or the durationTo() of an invalid date. */
16
+ isValid(): boolean;
17
+ get years(): number;
18
+ get months(): number;
19
+ get weeks(): number;
20
+ get days(): number;
21
+ get hours(): number;
22
+ get minutes(): number;
23
+ get seconds(): number;
24
+ get milliseconds(): number;
25
+ get(unit: UnitInput | DurationUnit): number;
26
+ /** Total length expressed in one unit (years/months use average lengths). */
27
+ as(unit: UnitInput | DurationUnit): number;
28
+ asMilliseconds(): number;
29
+ asSeconds(): number;
30
+ asMinutes(): number;
31
+ asHours(): number;
32
+ asDays(): number;
33
+ asWeeks(): number;
34
+ asMonths(): number;
35
+ asYears(): number;
36
+ /** Approximate total in milliseconds. */
37
+ valueOf(): number;
38
+ add(input: DurationInput, unit?: UnitInput | DurationUnit): Duration;
39
+ subtract(input: DurationInput, unit?: UnitInput | DurationUnit): Duration;
40
+ negate(): Duration;
41
+ abs(): Duration;
42
+ sign(): -1 | 0 | 1;
43
+ isZero(): boolean;
44
+ /**
45
+ * Balance overflowing units: 90 minutes → 1 h 30 min, 14 months → 1 y 2 mo.
46
+ * Exact units roll up to days; months roll up to years. Weeks fold into days.
47
+ */
48
+ normalize(): Duration;
49
+ /** "2 hours", or with suffix "in 2 hours" / "2 hours ago". Locale-aware via Intl. */
50
+ humanize(withSuffix?: boolean | RelativeTimeOptions, locale?: string): string;
51
+ /**
52
+ * Every non-zero unit, written out the way the locale lists them:
53
+ * "1 hour, 30 minutes" / "1 Stunde und 30 Minuten". Uses Intl.DurationFormat when present.
54
+ */
55
+ toLocaleString(locale?: string, style?: 'long' | 'short' | 'narrow' | 'digital'): string;
56
+ /**
57
+ * Format with tokens: Y M W D H HH m mm s ss SSS (the units of the normalized duration).
58
+ * `[text]` is literal. Example: neram.duration(5025000).format('H[h] mm[m]') → "1h 23m".
59
+ */
60
+ format(fmt?: string): string;
61
+ /** ISO 8601, e.g. "P1Y2M3DT4H5M6.5S". Weeks are folded into days. */
62
+ toISOString(): string;
63
+ /** ISO string, or null when invalid (like an invalid date). */
64
+ toJSON(): string | null;
65
+ toString(): string;
66
+ toObject(): Record<DurationUnit, number>;
67
+ }
68
+ export declare function duration(input?: DurationInput, unit?: UnitInput | DurationUnit): Duration;
69
+ export declare function isDuration(x: unknown): x is Duration;
@@ -0,0 +1,271 @@
1
+ import { clean, formatList, formatUnit } from './intl.js';
2
+ import { formatRelative, pickUnit } from './relative.js';
3
+ import { MS_DAY, MS_HOUR, MS_MINUTE, MS_MONTH, MS_SECOND, MS_WEEK, MS_YEAR, normalizeUnit } from './units.js';
4
+ export const DURATION_UNITS = [
5
+ 'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds',
6
+ ];
7
+ const INVALID = 'Invalid Duration';
8
+ const UNIT_MS = {
9
+ years: MS_YEAR,
10
+ months: MS_MONTH,
11
+ weeks: MS_WEEK,
12
+ days: MS_DAY,
13
+ hours: MS_HOUR,
14
+ minutes: MS_MINUTE,
15
+ seconds: MS_SECOND,
16
+ milliseconds: 1,
17
+ };
18
+ const ISO_DURATION = /^([+-])?P(?:(-?[\d.,]+)Y)?(?:(-?[\d.,]+)M)?(?:(-?[\d.,]+)W)?(?:(-?[\d.,]+)D)?(?:T(?:(-?[\d.,]+)H)?(?:(-?[\d.,]+)M)?(?:(-?[\d.,]+)S)?)?$/i;
19
+ function toDurationUnit(u) {
20
+ if (DURATION_UNITS.includes(u))
21
+ return u;
22
+ const n = normalizeUnit(u);
23
+ switch (n) {
24
+ case 'year': return 'years';
25
+ case 'quarter': throw new RangeError('neram: use months for quarter durations');
26
+ case 'month': return 'months';
27
+ case 'week':
28
+ case 'isoWeek': return 'weeks';
29
+ case 'day':
30
+ case 'date': return 'days';
31
+ case 'hour': return 'hours';
32
+ case 'minute': return 'minutes';
33
+ case 'second': return 'seconds';
34
+ default: return 'milliseconds';
35
+ }
36
+ }
37
+ /**
38
+ * An immutable length of time. Calendar units (years, months) are kept apart from exact
39
+ * units so `neram().add(duration)` stays calendar-correct; conversions like `asDays()`
40
+ * use average lengths.
41
+ */
42
+ export class Duration {
43
+ #v;
44
+ constructor(input, unit = 'milliseconds') {
45
+ const v = {
46
+ years: 0, months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds: 0,
47
+ };
48
+ if (input instanceof Duration) {
49
+ Object.assign(v, input.toObject());
50
+ }
51
+ else if (typeof input === 'number') {
52
+ v[toDurationUnit(unit)] = input;
53
+ }
54
+ else if (typeof input === 'string') {
55
+ const m = ISO_DURATION.exec(input.trim());
56
+ if (!m || input.trim().toUpperCase() === 'P' || /T$/i.test(input.trim())) {
57
+ throw new RangeError(`neram: invalid ISO 8601 duration "${input}"`);
58
+ }
59
+ const sign = m[1] === '-' ? -1 : 1;
60
+ DURATION_UNITS.forEach((u, i) => {
61
+ if (u === 'milliseconds')
62
+ return;
63
+ const raw = m[i + 2];
64
+ if (raw)
65
+ v[u] = sign * Number(raw.replace(',', '.'));
66
+ });
67
+ // move fractional seconds into milliseconds
68
+ const whole = Math.trunc(v.seconds);
69
+ v.milliseconds = Math.round((v.seconds - whole) * 1000);
70
+ v.seconds = whole;
71
+ }
72
+ else if (input) {
73
+ for (const [k, n] of Object.entries(input)) {
74
+ if (n != null)
75
+ v[toDurationUnit(k)] += n;
76
+ }
77
+ }
78
+ this.#v = v;
79
+ }
80
+ /** False when any part is NaN or infinite, e.g. neram.duration(NaN) or the durationTo() of an invalid date. */
81
+ isValid() {
82
+ return DURATION_UNITS.every((u) => Number.isFinite(this.#v[u]));
83
+ }
84
+ get years() { return this.#v.years; }
85
+ get months() { return this.#v.months; }
86
+ get weeks() { return this.#v.weeks; }
87
+ get days() { return this.#v.days; }
88
+ get hours() { return this.#v.hours; }
89
+ get minutes() { return this.#v.minutes; }
90
+ get seconds() { return this.#v.seconds; }
91
+ get milliseconds() { return this.#v.milliseconds; }
92
+ get(unit) {
93
+ return this.#v[toDurationUnit(unit)];
94
+ }
95
+ /** Total length expressed in one unit (years/months use average lengths). */
96
+ as(unit) {
97
+ return this.valueOf() / UNIT_MS[toDurationUnit(unit)];
98
+ }
99
+ asMilliseconds() { return this.as('milliseconds'); }
100
+ asSeconds() { return this.as('seconds'); }
101
+ asMinutes() { return this.as('minutes'); }
102
+ asHours() { return this.as('hours'); }
103
+ asDays() { return this.as('days'); }
104
+ asWeeks() { return this.as('weeks'); }
105
+ asMonths() { return this.as('months'); }
106
+ asYears() { return this.as('years'); }
107
+ /** Approximate total in milliseconds. */
108
+ valueOf() {
109
+ if (!this.isValid())
110
+ return NaN;
111
+ let total = 0;
112
+ for (const u of DURATION_UNITS)
113
+ total += this.#v[u] * UNIT_MS[u];
114
+ return total;
115
+ }
116
+ add(input, unit) {
117
+ const other = input instanceof Duration ? input : new Duration(input, unit);
118
+ const out = {};
119
+ for (const u of DURATION_UNITS)
120
+ out[u] = this.#v[u] + other.get(u);
121
+ return new Duration(out);
122
+ }
123
+ subtract(input, unit) {
124
+ const other = input instanceof Duration ? input : new Duration(input, unit);
125
+ return this.add(other.negate());
126
+ }
127
+ negate() {
128
+ const out = {};
129
+ for (const u of DURATION_UNITS)
130
+ out[u] = -this.#v[u] || 0;
131
+ return new Duration(out);
132
+ }
133
+ abs() {
134
+ return this.valueOf() < 0 ? this.negate() : this;
135
+ }
136
+ sign() {
137
+ const v = this.valueOf();
138
+ return v === 0 ? 0 : v < 0 ? -1 : 1;
139
+ }
140
+ isZero() {
141
+ return DURATION_UNITS.every((u) => this.#v[u] === 0);
142
+ }
143
+ /**
144
+ * Balance overflowing units: 90 minutes → 1 h 30 min, 14 months → 1 y 2 mo.
145
+ * Exact units roll up to days; months roll up to years. Weeks fold into days.
146
+ */
147
+ normalize() {
148
+ if (!this.isValid())
149
+ return this;
150
+ const v = this.#v;
151
+ const exact = v.weeks * MS_WEEK + v.days * MS_DAY + v.hours * MS_HOUR + v.minutes * MS_MINUTE + v.seconds * MS_SECOND + v.milliseconds;
152
+ const totalMonths = v.years * 12 + v.months;
153
+ const sign = exact < 0 ? -1 : 1;
154
+ let rest = Math.abs(exact);
155
+ const take = (size) => {
156
+ const n = Math.floor(rest / size);
157
+ rest -= n * size;
158
+ return sign * n || 0;
159
+ };
160
+ const days = take(MS_DAY);
161
+ const hours = take(MS_HOUR);
162
+ const minutes = take(MS_MINUTE);
163
+ const seconds = take(MS_SECOND);
164
+ const milliseconds = sign * Math.round(rest) || 0;
165
+ return new Duration({
166
+ years: Math.trunc(totalMonths / 12) || 0,
167
+ months: totalMonths % 12 || 0,
168
+ days, hours, minutes, seconds, milliseconds,
169
+ });
170
+ }
171
+ /** "2 hours", or with suffix "in 2 hours" / "2 hours ago". Locale-aware via Intl. */
172
+ humanize(withSuffix = false, locale = 'en') {
173
+ if (!this.isValid())
174
+ return INVALID;
175
+ const opts = typeof withSuffix === 'object' ? withSuffix : { withoutSuffix: !withSuffix };
176
+ const months = this.#v.years * 12 + this.#v.months;
177
+ const exact = this.valueOf() - months * MS_MONTH;
178
+ const { value, unit } = pickUnit(this.valueOf(), exact === 0 && months !== 0 ? months : undefined);
179
+ return formatRelative(value, unit, opts.locale ?? locale, { numeric: 'always', ...opts });
180
+ }
181
+ /**
182
+ * Every non-zero unit, written out the way the locale lists them:
183
+ * "1 hour, 30 minutes" / "1 Stunde und 30 Minuten". Uses Intl.DurationFormat when present.
184
+ */
185
+ toLocaleString(locale = 'en', style = 'long') {
186
+ if (!this.isValid())
187
+ return INVALID;
188
+ const DF = Intl.DurationFormat;
189
+ if (DF)
190
+ return clean(new DF(locale, { style }).format(this.toObject()));
191
+ const display = style === 'digital' ? 'narrow' : style;
192
+ const parts = DURATION_UNITS.filter((u) => this.#v[u] !== 0).map((u) => formatUnit(this.#v[u], u.slice(0, -1), locale, display));
193
+ if (!parts.length)
194
+ return formatUnit(0, 'second', locale, display);
195
+ return formatList(parts, locale, 'unit', display);
196
+ }
197
+ /**
198
+ * Format with tokens: Y M W D H HH m mm s ss SSS (the units of the normalized duration).
199
+ * `[text]` is literal. Example: neram.duration(5025000).format('H[h] mm[m]') → "1h 23m".
200
+ */
201
+ format(fmt = 'HH:mm:ss') {
202
+ if (!this.isValid())
203
+ return INVALID;
204
+ const n = this.abs().normalize();
205
+ const pad = (x, l = 2) => String(x).padStart(l, '0');
206
+ const out = fmt.replace(/\[([^\]]*)\]|YYYY|Y|MM|M|DD|D|HH|H|mm|m|ss|s|SSS/g, (tok, lit) => {
207
+ if (lit !== undefined)
208
+ return lit;
209
+ switch (tok) {
210
+ case 'Y': return String(n.years);
211
+ case 'YYYY': return pad(n.years, 4);
212
+ case 'M': return String(n.months);
213
+ case 'MM': return pad(n.months);
214
+ case 'D': return String(n.days);
215
+ case 'DD': return pad(n.days);
216
+ case 'H': return String(n.hours);
217
+ case 'HH': return pad(n.hours);
218
+ case 'm': return String(n.minutes);
219
+ case 'mm': return pad(n.minutes);
220
+ case 's': return String(n.seconds);
221
+ case 'ss': return pad(n.seconds);
222
+ default: return pad(n.milliseconds, 3);
223
+ }
224
+ });
225
+ return this.sign() < 0 ? `-${out}` : out;
226
+ }
227
+ /** ISO 8601, e.g. "P1Y2M3DT4H5M6.5S". Weeks are folded into days. */
228
+ toISOString() {
229
+ if (!this.isValid())
230
+ throw new RangeError('neram: invalid duration');
231
+ const v = { ...this.#v };
232
+ v.days += v.weeks * 7;
233
+ const values = [v.years, v.months, v.days, v.hours, v.minutes, v.seconds + v.milliseconds / 1000];
234
+ const allNeg = values.every((x) => x <= 0) && values.some((x) => x < 0);
235
+ const s = allNeg ? -1 : 1;
236
+ const n = (x) => String(Math.round(s * x * 1000) / 1000);
237
+ let date = '';
238
+ if (v.years)
239
+ date += `${n(v.years)}Y`;
240
+ if (v.months)
241
+ date += `${n(v.months)}M`;
242
+ if (v.days)
243
+ date += `${n(v.days)}D`;
244
+ let time = '';
245
+ if (v.hours)
246
+ time += `${n(v.hours)}H`;
247
+ if (v.minutes)
248
+ time += `${n(v.minutes)}M`;
249
+ if (v.seconds || v.milliseconds)
250
+ time += `${n(v.seconds + v.milliseconds / 1000)}S`;
251
+ if (!date && !time)
252
+ return 'PT0S';
253
+ return `${allNeg ? '-' : ''}P${date}${time ? `T${time}` : ''}`;
254
+ }
255
+ /** ISO string, or null when invalid (like an invalid date). */
256
+ toJSON() {
257
+ return this.isValid() ? this.toISOString() : null;
258
+ }
259
+ toString() {
260
+ return this.isValid() ? this.toISOString() : INVALID;
261
+ }
262
+ toObject() {
263
+ return { ...this.#v };
264
+ }
265
+ }
266
+ export function duration(input, unit) {
267
+ return new Duration(input, unit);
268
+ }
269
+ export function isDuration(x) {
270
+ return x instanceof Duration;
271
+ }
@@ -0,0 +1,13 @@
1
+ import { type Wall } from './zone.ts';
2
+ export interface FormatContext {
3
+ wall: Wall & {
4
+ dow: number;
5
+ };
6
+ ms: number;
7
+ offset: number;
8
+ locale: string;
9
+ weekStart: number;
10
+ /** Format with Intl in this instant's zone. */
11
+ intl: (opts: Intl.DateTimeFormatOptions) => string;
12
+ }
13
+ export declare function formatDate(ctx: FormatContext, fmt: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,115 @@
1
+ import { dayOfYear, weekOfYear } from './calendar.js';
2
+ import { localeData, ordinal } from './locale.js';
3
+ import { formatOffset } from './zone.js';
4
+ const TOKEN = /\[([^\]]*)\]|LTS|LT|LLLL|LLL|LL|L|llll|lll|ll|l|YYYY|YY|GGGG|gggg|MMMM|MMM|MM|M|Qo|Q|DDDD|DDD|Do|DD|D|dddd|ddd|dd|d|E|HH|H|hh|h|kk|k|mm|m|ss|s|S{1,9}|A|a|ZZ|Z|X|x|WW|W|ww|w|zzz|z/g;
5
+ const pad = (n, len = 2) => {
6
+ const s = String(Math.abs(n)).padStart(len, '0');
7
+ return n < 0 ? `-${s}` : s;
8
+ };
9
+ const LOCALIZED = {
10
+ LT: { timeStyle: 'short' },
11
+ LTS: { timeStyle: 'medium' },
12
+ L: { year: 'numeric', month: '2-digit', day: '2-digit' },
13
+ LL: { dateStyle: 'long' },
14
+ LLL: { dateStyle: 'long', timeStyle: 'short' },
15
+ LLLL: { dateStyle: 'full', timeStyle: 'short' },
16
+ l: { year: 'numeric', month: 'numeric', day: 'numeric' },
17
+ ll: { dateStyle: 'medium' },
18
+ lll: { dateStyle: 'medium', timeStyle: 'short' },
19
+ llll: { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' },
20
+ };
21
+ export function formatDate(ctx, fmt) {
22
+ const { wall: w, locale } = ctx;
23
+ let ld;
24
+ const names = () => (ld ??= localeData(locale));
25
+ const iso = () => weekOfYear(w.y, w.M, w.D, 1, 4);
26
+ const loc = () => weekOfYear(w.y, w.M, w.D, ctx.weekStart, names().week.minimalDays);
27
+ const h12 = w.h % 12 || 12;
28
+ const value = (tok) => {
29
+ if (LOCALIZED[tok])
30
+ return ctx.intl(LOCALIZED[tok]);
31
+ switch (tok) {
32
+ case 'YYYY': return w.y >= 0 && w.y <= 9999 ? pad(w.y, 4) : (w.y < 0 ? '-' : '+') + pad(Math.abs(w.y), 6);
33
+ case 'YY': return pad(((w.y % 100) + 100) % 100);
34
+ case 'GGGG': return pad(iso().year, 4);
35
+ case 'gggg': return pad(loc().year, 4);
36
+ case 'M': return String(w.M + 1);
37
+ case 'MM': return pad(w.M + 1);
38
+ case 'MMM': return names().monthsShort[w.M];
39
+ case 'MMMM': return names().months[w.M];
40
+ case 'Q': return String(Math.floor(w.M / 3) + 1);
41
+ case 'Qo': return ordinal(Math.floor(w.M / 3) + 1, locale);
42
+ case 'D': return String(w.D);
43
+ case 'DD': return pad(w.D);
44
+ case 'Do': return ordinal(w.D, locale);
45
+ case 'DDD': return String(dayOfYear(w.y, w.M, w.D));
46
+ case 'DDDD': return pad(dayOfYear(w.y, w.M, w.D), 3);
47
+ case 'd': return String(w.dow);
48
+ case 'E': return String(w.dow || 7);
49
+ case 'dd': return names().weekdaysMin[w.dow];
50
+ case 'ddd': return names().weekdaysShort[w.dow];
51
+ case 'dddd': return names().weekdays[w.dow];
52
+ case 'H': return String(w.h);
53
+ case 'HH': return pad(w.h);
54
+ case 'h': return String(h12);
55
+ case 'hh': return pad(h12);
56
+ case 'k': return String(w.h || 24);
57
+ case 'kk': return pad(w.h || 24);
58
+ case 'm': return String(w.m);
59
+ case 'mm': return pad(w.m);
60
+ case 's': return String(w.s);
61
+ case 'ss': return pad(w.s);
62
+ case 'A': return names().meridiem[w.h < 12 ? 0 : 1];
63
+ case 'a': return names().meridiem[w.h < 12 ? 0 : 1].toLowerCase();
64
+ case 'Z': return formatOffset(ctx.offset);
65
+ case 'ZZ': return formatOffset(ctx.offset, '');
66
+ case 'X': return String(Math.floor(ctx.ms / 1000));
67
+ case 'x': return String(ctx.ms);
68
+ case 'W': return String(iso().week);
69
+ case 'WW': return pad(iso().week);
70
+ case 'w': return String(loc().week);
71
+ case 'ww': return pad(loc().week);
72
+ case 'z': return ctx.intl({ timeZoneName: 'short' }).split(/,?\s/).pop() ?? '';
73
+ case 'zzz': return zoneLongName(ctx);
74
+ default: // S… fractional seconds
75
+ return pad(w.ms, 3).padEnd(tok.length, '0').slice(0, tok.length);
76
+ }
77
+ };
78
+ // Compiled parts alternate literal text (even index) and tokens (odd index).
79
+ const parts = compile(fmt);
80
+ let out = parts[0];
81
+ for (let i = 1; i < parts.length; i += 2)
82
+ out += value(parts[i]) + parts[i + 1];
83
+ return out;
84
+ }
85
+ const compiled = new Map();
86
+ /** Split a format string once into [literal, token, literal, token, …, literal] and cache it. */
87
+ function compile(fmt) {
88
+ let parts = compiled.get(fmt);
89
+ if (parts)
90
+ return parts;
91
+ parts = [];
92
+ let lit = '';
93
+ let last = 0;
94
+ for (const m of fmt.matchAll(TOKEN)) {
95
+ lit += fmt.slice(last, m.index);
96
+ last = m.index + m[0].length;
97
+ if (m[1] !== undefined) {
98
+ lit += m[1]; // [escaped] text
99
+ }
100
+ else {
101
+ parts.push(lit, m[0]);
102
+ lit = '';
103
+ }
104
+ }
105
+ parts.push(lit + fmt.slice(last));
106
+ if (compiled.size > 500)
107
+ compiled.clear();
108
+ compiled.set(fmt, parts);
109
+ return parts;
110
+ }
111
+ function zoneLongName(ctx) {
112
+ const full = ctx.intl({ year: 'numeric', timeZoneName: 'long' });
113
+ const year = ctx.intl({ year: 'numeric' });
114
+ return full.replace(year, '').replace(/^[\s,]+|[\s,]+$/g, '');
115
+ }
package/dist/index.cjs ADDED
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+ const lib = require('./cjs/neram.cjs')
3
+ const neram = lib.neram
4
+ for (const key of ['Neram', 'Duration', 'duration', 'isDuration']) {
5
+ Object.defineProperty(neram, key, { value: lib[key], writable: true, configurable: true })
6
+ }
7
+ Object.defineProperty(neram, 'neram', { value: neram, writable: true, configurable: true })
8
+ Object.defineProperty(neram, 'default', { value: neram, writable: true, configurable: true })
9
+ module.exports = neram
@@ -0,0 +1,35 @@
1
+ import type * as M from './index.js' with { 'resolution-mode': 'import' }
2
+
3
+ type NeramExport = typeof M.neram & {
4
+ readonly neram: NeramExport
5
+ readonly default: NeramExport
6
+ readonly Neram: typeof M.Neram
7
+ readonly Duration: typeof M.Duration
8
+ readonly duration: typeof M.duration
9
+ readonly isDuration: typeof M.isDuration
10
+ }
11
+ declare const neram: NeramExport
12
+ declare namespace neram {
13
+ export type Neram = M.Neram
14
+ export type Duration = M.Duration
15
+ export type BusinessDayOptions = M.BusinessDayOptions
16
+ export type CalendarOptions = M.CalendarOptions
17
+ export type DateObject = M.DateObject
18
+ export type EpochLike = M.EpochLike
19
+ export type NeramConfig = M.NeramConfig
20
+ export type NeramEnvironment = M.NeramEnvironment
21
+ export type NeramInput = M.NeramInput
22
+ export type ParseOptions = M.ParseOptions
23
+ export type Plugin = M.Plugin
24
+ export type DurationInput = M.DurationInput
25
+ export type DurationObject = M.DurationObject
26
+ export type DurationUnit = M.DurationUnit
27
+ export type RelativeTimeOptions = M.RelativeTimeOptions
28
+ export type Unit = M.Unit
29
+ export type UnitInput = M.UnitInput
30
+ export type MonthOf = M.MonthOf
31
+ export type NeramLocaleData = M.NeramLocaleData
32
+ export type WeekdayOf = M.WeekdayOf
33
+ export type WeekInfo = M.WeekInfo
34
+ }
35
+ export = neram
@@ -0,0 +1,7 @@
1
+ export { neram, neram as default, Neram } from './neram.ts';
2
+ export type { BusinessDayOptions, CalendarOptions, DateObject, EpochLike, NeramConfig, NeramEnvironment, NeramInput, ParseOptions, Plugin, } from './neram.ts';
3
+ export { Duration, duration, isDuration } from './duration.ts';
4
+ export type { DurationInput, DurationObject, DurationUnit } from './duration.ts';
5
+ export type { RelativeTimeOptions } from './relative.ts';
6
+ export type { Unit, UnitInput } from './units.ts';
7
+ export type { MonthOf, NeramLocaleData, WeekdayOf, WeekInfo } from './locale.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { neram, neram as default, Neram } from './neram.js';
2
+ export { Duration, duration, isDuration } from './duration.js';
package/dist/intl.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Thin wrappers around Intl so server and browser output stays comparable:
3
+ * - Unicode spaces (U+202F before AM/PM, U+00A0 inside dates) become plain spaces by default.
4
+ * - Missing Intl APIs fall back to English instead of throwing (older engines, slim ICU builds).
5
+ */
6
+ export declare const intlSettings: {
7
+ normalizeSpaces: boolean;
8
+ };
9
+ /** Apply the space setting to any Intl output. */
10
+ export declare function clean(s: string): string;
11
+ export declare function formatList(items: string[], locale?: string, type?: 'conjunction' | 'disjunction' | 'unit', style?: 'long' | 'short' | 'narrow'): string;
12
+ /** "3 hours", "3 hr", "3h" — Intl.NumberFormat unit style, with an English fallback. */
13
+ export declare function formatUnit(value: number, unit: string, locale: string, display?: 'long' | 'short' | 'narrow'): string;
14
+ /** Intl.RelativeTimeFormat with an English fallback. */
15
+ export declare function formatRelativeTime(value: number, unit: Intl.RelativeTimeFormatUnit, locale: string, style: Intl.RelativeTimeFormatStyle, numeric: Intl.RelativeTimeFormatNumeric): string;
package/dist/intl.js ADDED
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Thin wrappers around Intl so server and browser output stays comparable:
3
+ * - Unicode spaces (U+202F before AM/PM, U+00A0 inside dates) become plain spaces by default.
4
+ * - Missing Intl APIs fall back to English instead of throwing (older engines, slim ICU builds).
5
+ */
6
+ export const intlSettings = { normalizeSpaces: true };
7
+ const SPACES = /[\u00a0\u2007\u2009\u202f]/g;
8
+ /** Apply the space setting to any Intl output. */
9
+ export function clean(s) {
10
+ return intlSettings.normalizeSpaces ? s.replace(SPACES, ' ') : s;
11
+ }
12
+ const I = Intl;
13
+ const listCache = new Map();
14
+ export function formatList(items, locale = 'en', type = 'conjunction', style = 'long') {
15
+ if (I.ListFormat) {
16
+ const key = `${locale}|${type}|${style}`;
17
+ let lf = listCache.get(key);
18
+ if (!lf) {
19
+ lf = new I.ListFormat(locale, { type, style });
20
+ listCache.set(key, lf);
21
+ }
22
+ return clean(lf.format(items));
23
+ }
24
+ if (items.length <= 1)
25
+ return items.join('');
26
+ if (type === 'unit')
27
+ return items.join(', ');
28
+ const word = type === 'disjunction' ? 'or' : 'and';
29
+ return items.length === 2 ? `${items[0]} ${word} ${items[1]}` : `${items.slice(0, -1).join(', ')}, ${word} ${items.at(-1)}`;
30
+ }
31
+ const unitCache = new Map();
32
+ /** "3 hours", "3 hr", "3h" — Intl.NumberFormat unit style, with an English fallback. */
33
+ export function formatUnit(value, unit, locale, display = 'long') {
34
+ const key = `${locale}|${unit}|${display}`;
35
+ let nf = unitCache.get(key);
36
+ if (nf === undefined) {
37
+ try {
38
+ nf = new Intl.NumberFormat(locale, { style: 'unit', unit, unitDisplay: display });
39
+ }
40
+ catch {
41
+ nf = null;
42
+ }
43
+ unitCache.set(key, nf);
44
+ }
45
+ if (nf)
46
+ return clean(nf.format(value));
47
+ return `${value} ${unit}${Math.abs(value) === 1 ? '' : 's'}`;
48
+ }
49
+ const rtfCache = new Map();
50
+ /** Intl.RelativeTimeFormat with an English fallback. */
51
+ export function formatRelativeTime(value, unit, locale, style, numeric) {
52
+ if (I.RelativeTimeFormat) {
53
+ const key = `${locale}|${style}|${numeric}`;
54
+ let rtf = rtfCache.get(key);
55
+ if (!rtf) {
56
+ rtf = new I.RelativeTimeFormat(locale, { style, numeric });
57
+ rtfCache.set(key, rtf);
58
+ }
59
+ return clean(rtf.format(value, unit));
60
+ }
61
+ if (numeric === 'auto') {
62
+ if (value === 0)
63
+ return unit === 'day' ? 'today' : 'now';
64
+ if (unit === 'day' && value === 1)
65
+ return 'tomorrow';
66
+ if (unit === 'day' && value === -1)
67
+ return 'yesterday';
68
+ }
69
+ const abs = Math.abs(value);
70
+ const text = `${abs} ${unit}${abs === 1 ? '' : 's'}`;
71
+ return value < 0 || Object.is(value, -0) ? `${text} ago` : `in ${text}`;
72
+ }
@@ -0,0 +1,53 @@
1
+ export interface WeekInfo {
2
+ /** 0 = Sunday … 6 = Saturday */
3
+ firstDay: number;
4
+ minimalDays: number;
5
+ /** weekday numbers (0-6) that are weekend days */
6
+ weekend: number[];
7
+ }
8
+ export interface LocaleData {
9
+ months: string[];
10
+ monthsShort: string[];
11
+ weekdays: string[];
12
+ weekdaysShort: string[];
13
+ weekdaysMin: string[];
14
+ meridiem: [string, string];
15
+ week: WeekInfo;
16
+ }
17
+ export declare function canonicalLocale(locale: string): string;
18
+ export declare function localeData(locale: string): LocaleData;
19
+ export declare function ordinal(n: number, locale: string): string;
20
+ /** Anything with Day.js-style `month()` / `day()` getters: a neram value, or a Day.js one. */
21
+ export interface MonthOf {
22
+ month(): number;
23
+ }
24
+ export interface WeekdayOf {
25
+ day(): number;
26
+ }
27
+ /**
28
+ * The public, Day.js-compatible view of a locale. Lists come back as fresh arrays, so callers cannot
29
+ * change the shared cache; pass a date to get the single name for that date instead.
30
+ */
31
+ export interface NeramLocaleData {
32
+ /** The canonical locale name, e.g. "en-GB". */
33
+ readonly name: string;
34
+ /** 0 = Sunday … 6 = Saturday. */
35
+ firstDayOfWeek(): number;
36
+ months(): string[];
37
+ months(date: MonthOf): string;
38
+ monthsShort(): string[];
39
+ monthsShort(date: MonthOf): string;
40
+ weekdays(): string[];
41
+ weekdays(date: WeekdayOf): string;
42
+ weekdaysShort(): string[];
43
+ weekdaysShort(date: WeekdayOf): string;
44
+ weekdaysMin(): string[];
45
+ weekdaysMin(date: WeekdayOf): string;
46
+ /** The AM/PM marker for an hour (0-23), as Day.js's `meridiem(hour, minute, isLowercase)`. */
47
+ meridiem(hour: number, minute?: number, isLowercase?: boolean): string;
48
+ /** "1st", "2nd" in English; "1." elsewhere. */
49
+ ordinal(n: number): string;
50
+ /** Week rules: first day, the minimum days in week 1, and the weekend days. */
51
+ week(): WeekInfo;
52
+ }
53
+ export declare function publicLocaleData(locale: string): NeramLocaleData;