ticlo-tsdb 0.0.0-stage → 0.2.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,80 @@
1
+ import type { StorageBackend } from './backend.ts';
2
+ import type { ChunkSizeOptions, EncodedValueRecord, RollupTier, SeriesMeta, StorageChunkInfo } from './types.ts';
3
+ export interface RollupTierStore {
4
+ readonly hasData: boolean;
5
+ readonly baseSlotId: number;
6
+ readonly slotCount: number;
7
+ readonly endSlotId: number;
8
+ readonly byteSize?: number;
9
+ open(): Promise<void>;
10
+ readLastSlot(): Promise<{
11
+ slotId: number;
12
+ data: Float64Array;
13
+ } | null>;
14
+ writeSlots(startSlotId: number, data: Float64Array, numSlots: number): Promise<void>;
15
+ readSlotRange(fromSlotId: number, toSlotIdInclusive: number): Promise<{
16
+ firstSlotId: number;
17
+ data: Float64Array;
18
+ count: number;
19
+ }>;
20
+ compact(keepFromSlotId: number): Promise<void>;
21
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
22
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
23
+ close(): Promise<void>;
24
+ }
25
+ export interface NumericRawStore {
26
+ readonly recordCount: number;
27
+ readonly byteSize?: number;
28
+ open(): Promise<void>;
29
+ appendBatch(interleaved: Float64Array, count: number): Promise<void>;
30
+ readRange(startMs: number, endMs: number, limit?: number, stripNaN?: boolean): Promise<{
31
+ timestamps: Float64Array;
32
+ values: Float64Array;
33
+ length: number;
34
+ truncated: boolean;
35
+ }>;
36
+ readLastBefore(tsMs: number, inclusive?: boolean): Promise<{
37
+ ts: number;
38
+ value: number;
39
+ } | null>;
40
+ compact(minTsKeep?: number, maxRecords?: number): Promise<void>;
41
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
42
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
43
+ close(): Promise<void>;
44
+ }
45
+ export interface ValueRawStore {
46
+ readonly recordCount: number;
47
+ readonly byteSize?: number;
48
+ open(): Promise<void>;
49
+ appendBatch(entries: ReadonlyArray<EncodedValueRecord>): Promise<void>;
50
+ readRange(startMs: number, endMs: number, limit?: number, order?: 'asc' | 'desc'): Promise<{
51
+ records: EncodedValueRecord[];
52
+ truncated: boolean;
53
+ }>;
54
+ compact?(minTsKeep?: number, maxRecords?: number): Promise<void>;
55
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
56
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
57
+ close(): Promise<void>;
58
+ }
59
+ export interface TsdbStore {
60
+ open(): Promise<void>;
61
+ readCatalog<T>(): Promise<T | null>;
62
+ writeCatalog(catalog: unknown): Promise<void>;
63
+ openNumericRaw(meta: SeriesMeta): Promise<NumericRawStore>;
64
+ openRollupTier(meta: SeriesMeta, tier: RollupTier): Promise<RollupTierStore>;
65
+ openValueRaw(meta: SeriesMeta): Promise<ValueRawStore>;
66
+ deleteSeriesData(meta: SeriesMeta): Promise<void>;
67
+ close?(): Promise<void>;
68
+ }
69
+ export declare class FileTsdbStore implements TsdbStore {
70
+ private readonly backend;
71
+ private readonly chunkSize;
72
+ constructor(backend: StorageBackend, chunkSize?: ChunkSizeOptions);
73
+ open(): Promise<void>;
74
+ readCatalog<T>(): Promise<T | null>;
75
+ writeCatalog(catalog: unknown): Promise<void>;
76
+ openNumericRaw(meta: SeriesMeta): Promise<NumericRawStore>;
77
+ openRollupTier(meta: SeriesMeta, tier: RollupTier): Promise<RollupTierStore>;
78
+ openValueRaw(meta: SeriesMeta): Promise<ValueRawStore>;
79
+ deleteSeriesData(meta: SeriesMeta): Promise<void>;
80
+ }
package/dist/store.js ADDED
@@ -0,0 +1,42 @@
1
+ import { NumericRawFile, ValueRawFile } from './rawFile.js';
2
+ import { resolveChunkSizes } from './retention.js';
3
+ import { RollupFile } from './rollupFile.js';
4
+ const CATALOG_PATH = 'catalog.json';
5
+ export class FileTsdbStore {
6
+ backend;
7
+ chunkSize;
8
+ constructor(backend, chunkSize) {
9
+ this.backend = backend;
10
+ this.chunkSize = resolveChunkSizes(chunkSize);
11
+ }
12
+ async open() {
13
+ await this.backend.ensureDir('');
14
+ }
15
+ readCatalog() {
16
+ return this.backend.readJson(CATALOG_PATH);
17
+ }
18
+ writeCatalog(catalog) {
19
+ return this.backend.writeJsonAtomic(CATALOG_PATH, catalog);
20
+ }
21
+ async openNumericRaw(meta) {
22
+ await this.backend.ensureDir(`series/${meta.dirKey}`);
23
+ const file = new NumericRawFile(this.backend, `series/${meta.dirKey}/raw`, this.chunkSize.rawNumericChunkBytes);
24
+ await file.open();
25
+ return file;
26
+ }
27
+ async openRollupTier(meta, tier) {
28
+ await this.backend.ensureDir(`series/${meta.dirKey}`);
29
+ const file = new RollupFile(this.backend, `series/${meta.dirKey}/rollup_${tier}`, tier, this.chunkSize.rollupChunkSlots);
30
+ await file.open();
31
+ return file;
32
+ }
33
+ async openValueRaw(meta) {
34
+ await this.backend.ensureDir(`series/${meta.dirKey}`);
35
+ const file = new ValueRawFile(this.backend, `series/${meta.dirKey}/val`, this.chunkSize.rawValueChunkBytes);
36
+ await file.open();
37
+ return file;
38
+ }
39
+ deleteSeriesData(meta) {
40
+ return this.backend.removeDir(`series/${meta.dirKey}`);
41
+ }
42
+ }
package/dist/time.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { IntervalString, IntervalUnit, RollupTier, StandardInterval, TimestampInput } from './types.ts';
2
+ export declare const STANDARD_INTERVALS: readonly StandardInterval[];
3
+ export declare const TIER_STEP_MS: Record<RollupTier, number>;
4
+ export interface ParsedInterval {
5
+ raw: IntervalString;
6
+ count: number;
7
+ unit: IntervalUnit;
8
+ fixedMs?: number;
9
+ approxMs: number;
10
+ }
11
+ export declare function toEpochMs(input: TimestampInput): number;
12
+ export declare function parseInterval(interval: string): ParsedInterval;
13
+ export declare function selectAutoInterval(startMs: number, endMs: number, minPoints?: number): StandardInterval;
14
+ export declare function canTierServeInterval(tier: RollupTier, interval: ParsedInterval): boolean;
15
+ export declare class ServerCalendar {
16
+ readonly timezone: string;
17
+ readonly weekStartsOn: 0 | 1;
18
+ private readonly isUtc;
19
+ private readonly formatter;
20
+ private readonly hourAnchorMs;
21
+ private readonly dayMidnightCache;
22
+ private readonly monthStartCache;
23
+ private cachedDayOrd;
24
+ private cachedDayStart;
25
+ private cachedDayEnd;
26
+ constructor(timezone?: string, weekStartsOn?: 0 | 1);
27
+ private getLocalParts;
28
+ private computeHourStart;
29
+ floorHourMs(tsMs: number): number;
30
+ localDayOrdinal(tsMs: number): number;
31
+ dayOrdinalToUtcMs(dayOrd: number): number;
32
+ monthIndexToUtcMs(monthIdx: number): number;
33
+ private localMonthIndex;
34
+ tierToSlotId(tier: RollupTier, tsMs: number): number;
35
+ tierSlotToUtcMs(tier: RollupTier, slotId: number): number;
36
+ floorInterval(tsMs: number, interval: ParsedInterval): number;
37
+ nextInterval(bucketStartMs: number, interval: ParsedInterval): number;
38
+ ceilInterval(tsMs: number, interval: ParsedInterval): number;
39
+ }
package/dist/time.js ADDED
@@ -0,0 +1,459 @@
1
+ export const STANDARD_INTERVALS = [
2
+ '15s',
3
+ '30s',
4
+ '1m',
5
+ '5m',
6
+ '10m',
7
+ '15m',
8
+ '30m',
9
+ '1h',
10
+ '3h',
11
+ '6h',
12
+ '12h',
13
+ '1d',
14
+ '1w',
15
+ '2w',
16
+ '1n',
17
+ '3n',
18
+ '6n',
19
+ '1y',
20
+ ];
21
+ const UNIT_APPROX_MS = {
22
+ s: 1_000,
23
+ m: 60_000,
24
+ h: 3_600_000,
25
+ d: 86_400_000,
26
+ w: 7 * 86_400_000,
27
+ n: 30 * 86_400_000,
28
+ y: 365 * 86_400_000,
29
+ };
30
+ const STANDARD_INTERVAL_APPROX_MS = [
31
+ 15_000,
32
+ 30_000,
33
+ 60_000,
34
+ 300_000,
35
+ 600_000,
36
+ 900_000,
37
+ 1_800_000,
38
+ 3_600_000,
39
+ 10_800_000,
40
+ 21_600_000,
41
+ 43_200_000,
42
+ 86_400_000,
43
+ 7 * 86_400_000,
44
+ 14 * 86_400_000,
45
+ 30 * 86_400_000,
46
+ 90 * 86_400_000,
47
+ 180 * 86_400_000,
48
+ 365 * 86_400_000,
49
+ ];
50
+ export const TIER_STEP_MS = {
51
+ '15s': 15_000,
52
+ '5m': 300_000,
53
+ '1h': 3_600_000,
54
+ '1d': 86_400_000,
55
+ };
56
+ const intervalRegex = /^([1-9]\d*)(s|m|h|d|w|n|y)$/;
57
+ const parsedIntervalCache = new Map();
58
+ export function toEpochMs(input) {
59
+ if (typeof input === 'number') {
60
+ if (!Number.isFinite(input))
61
+ throw new Error(`Invalid timestamp: ${input}`);
62
+ return Math.trunc(input);
63
+ }
64
+ if (input instanceof Date) {
65
+ const ms = input.getTime();
66
+ if (!Number.isFinite(ms))
67
+ throw new Error('Invalid Date timestamp');
68
+ return Math.trunc(ms);
69
+ }
70
+ if (input && typeof input.toMillis === 'function') {
71
+ const ms = input.toMillis();
72
+ if (!Number.isFinite(ms))
73
+ throw new Error('Invalid DateTime timestamp');
74
+ return Math.trunc(ms);
75
+ }
76
+ throw new Error('Unsupported timestamp input');
77
+ }
78
+ export function parseInterval(interval) {
79
+ let parsed = parsedIntervalCache.get(interval);
80
+ if (parsed)
81
+ return parsed;
82
+ const match = intervalRegex.exec(interval);
83
+ if (!match) {
84
+ throw new Error(`Invalid interval: ${interval}`);
85
+ }
86
+ const count = Number(match[1]);
87
+ const unit = match[2];
88
+ const approxMs = count * UNIT_APPROX_MS[unit];
89
+ const fixedMs = unit === 's' || unit === 'm' ? approxMs : undefined;
90
+ parsed = {
91
+ raw: interval,
92
+ count,
93
+ unit,
94
+ fixedMs,
95
+ approxMs,
96
+ };
97
+ parsedIntervalCache.set(interval, parsed);
98
+ return parsed;
99
+ }
100
+ export function selectAutoInterval(startMs, endMs, minPoints = 64) {
101
+ const spanMs = Math.max(1, endMs - startMs + 1);
102
+ for (let i = STANDARD_INTERVALS.length - 1; i >= 0; --i) {
103
+ if (spanMs / STANDARD_INTERVAL_APPROX_MS[i] > minPoints) {
104
+ return STANDARD_INTERVALS[i];
105
+ }
106
+ }
107
+ return STANDARD_INTERVALS[0];
108
+ }
109
+ export function canTierServeInterval(tier, interval) {
110
+ const { unit, count } = interval;
111
+ switch (tier) {
112
+ case '15s':
113
+ return (unit === 's' && count % 15 === 0) || unit === 'm' || unit === 'h';
114
+ case '5m':
115
+ return (unit === 'm' && count % 5 === 0) || unit === 'h';
116
+ case '1h':
117
+ return unit === 'h' || unit === 'd' || unit === 'w' || unit === 'n' || unit === 'y';
118
+ case '1d':
119
+ return unit === 'd' || unit === 'w' || unit === 'n' || unit === 'y';
120
+ }
121
+ }
122
+ function ymdToEpochDay(year, month, day) {
123
+ return Math.floor(Date.UTC(year, month - 1, day) / 86_400_000);
124
+ }
125
+ function epochDayToYmd(dayOrd) {
126
+ const d = new Date(dayOrd * 86_400_000);
127
+ return {
128
+ year: d.getUTCFullYear(),
129
+ month: d.getUTCMonth() + 1,
130
+ day: d.getUTCDate(),
131
+ };
132
+ }
133
+ export class ServerCalendar {
134
+ timezone;
135
+ weekStartsOn;
136
+ isUtc;
137
+ formatter;
138
+ hourAnchorMs;
139
+ dayMidnightCache = new Map();
140
+ monthStartCache = new Map();
141
+ // Single-entry hot caches for sequential writes/reads in the same day/hour.
142
+ cachedDayOrd = 0;
143
+ cachedDayStart = 0;
144
+ cachedDayEnd = -1;
145
+ constructor(timezone, weekStartsOn = 1) {
146
+ this.timezone = timezone || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
147
+ this.weekStartsOn = weekStartsOn;
148
+ this.isUtc = this.timezone === 'UTC' || this.timezone === 'Etc/UTC' || this.timezone === 'GMT';
149
+ this.formatter = this.isUtc
150
+ ? null
151
+ : new Intl.DateTimeFormat('en-CA', {
152
+ timeZone: this.timezone,
153
+ year: 'numeric',
154
+ month: '2-digit',
155
+ day: '2-digit',
156
+ hour: '2-digit',
157
+ minute: '2-digit',
158
+ second: '2-digit',
159
+ hourCycle: 'h23',
160
+ });
161
+ this.hourAnchorMs = this.isUtc ? 0 : this.computeHourStart(0);
162
+ }
163
+ getLocalParts(tsMs) {
164
+ const parts = this.formatter.formatToParts(tsMs);
165
+ let year = 0;
166
+ let month = 0;
167
+ let day = 0;
168
+ let hour = 0;
169
+ let minute = 0;
170
+ let second = 0;
171
+ for (let i = 0; i < parts.length; ++i) {
172
+ const part = parts[i];
173
+ switch (part.type) {
174
+ case 'year':
175
+ year = Number(part.value);
176
+ break;
177
+ case 'month':
178
+ month = Number(part.value);
179
+ break;
180
+ case 'day':
181
+ day = Number(part.value);
182
+ break;
183
+ case 'hour':
184
+ hour = Number(part.value);
185
+ break;
186
+ case 'minute':
187
+ minute = Number(part.value);
188
+ break;
189
+ case 'second':
190
+ second = Number(part.value);
191
+ break;
192
+ }
193
+ }
194
+ return { year, month, day, hour, minute, second };
195
+ }
196
+ computeHourStart(tsMs) {
197
+ const subSec = ((tsMs % 1000) + 1000) % 1000;
198
+ const secStart = tsMs - subSec;
199
+ const p = this.getLocalParts(secStart);
200
+ let candidate = secStart - (p.minute * 60 + p.second) * 1000;
201
+ const p2 = this.getLocalParts(candidate);
202
+ if (p2.minute !== 0 || p2.second !== 0) {
203
+ // Half-hour / unusual DST fallback: align to exact minute boundary.
204
+ candidate -= (p2.minute * 60 + p2.second) * 1000;
205
+ }
206
+ return candidate;
207
+ }
208
+ floorHourMs(tsMs) {
209
+ if (this.isUtc) {
210
+ return Math.floor(tsMs / 3_600_000) * 3_600_000;
211
+ }
212
+ return this.hourAnchorMs + Math.floor((tsMs - this.hourAnchorMs) / 3_600_000) * 3_600_000;
213
+ }
214
+ localDayOrdinal(tsMs) {
215
+ if (this.isUtc) {
216
+ return Math.floor(tsMs / 86_400_000);
217
+ }
218
+ if (tsMs >= this.cachedDayStart && tsMs < this.cachedDayEnd) {
219
+ return this.cachedDayOrd;
220
+ }
221
+ const p = this.getLocalParts(tsMs);
222
+ const dayOrd = ymdToEpochDay(p.year, p.month, p.day);
223
+ const start = this.dayOrdinalToUtcMs(dayOrd);
224
+ const end = this.dayOrdinalToUtcMs(dayOrd + 1);
225
+ this.cachedDayOrd = dayOrd;
226
+ this.cachedDayStart = start;
227
+ this.cachedDayEnd = end;
228
+ return dayOrd;
229
+ }
230
+ dayOrdinalToUtcMs(dayOrd) {
231
+ if (this.isUtc) {
232
+ return dayOrd * 86_400_000;
233
+ }
234
+ const cached = this.dayMidnightCache.get(dayOrd);
235
+ if (cached !== undefined)
236
+ return cached;
237
+ let guess = dayOrd * 86_400_000;
238
+ for (let iter = 0; iter < 4; ++iter) {
239
+ const p = this.getLocalParts(guess);
240
+ const curOrd = ymdToEpochDay(p.year, p.month, p.day);
241
+ const todMs = ((p.hour * 60 + p.minute) * 60 + p.second) * 1000;
242
+ if (curOrd === dayOrd && todMs === 0) {
243
+ break;
244
+ }
245
+ if (curOrd === dayOrd && todMs > 0) {
246
+ const before = guess - todMs;
247
+ const pb = this.getLocalParts(before);
248
+ if (ymdToEpochDay(pb.year, pb.month, pb.day) < dayOrd) {
249
+ // DST midnight skip (00:00 jumps directly to 01:00): scan exact boundary at minute/hour resolution.
250
+ let lo = before;
251
+ let hi = guess;
252
+ while (hi - lo > 60_000) {
253
+ const mid = Math.floor((lo + hi) / 2);
254
+ const pm = this.getLocalParts(mid);
255
+ if (ymdToEpochDay(pm.year, pm.month, pm.day) >= dayOrd)
256
+ hi = mid;
257
+ else
258
+ lo = mid;
259
+ }
260
+ guess = Math.floor(hi / 60_000) * 60_000;
261
+ break;
262
+ }
263
+ guess = before;
264
+ }
265
+ else {
266
+ guess += (dayOrd - curOrd) * 86_400_000 - todMs;
267
+ }
268
+ }
269
+ const subSec = ((guess % 1000) + 1000) % 1000;
270
+ guess -= subSec;
271
+ this.dayMidnightCache.set(dayOrd, guess);
272
+ return guess;
273
+ }
274
+ monthIndexToUtcMs(monthIdx) {
275
+ if (this.isUtc) {
276
+ const year = Math.floor(monthIdx / 12);
277
+ const month = ((monthIdx % 12) + 12) % 12;
278
+ return Date.UTC(year, month, 1);
279
+ }
280
+ const cached = this.monthStartCache.get(monthIdx);
281
+ if (cached !== undefined)
282
+ return cached;
283
+ const year = Math.floor(monthIdx / 12);
284
+ const month = (((monthIdx % 12) + 12) % 12) + 1;
285
+ const dayOrd = ymdToEpochDay(year, month, 1);
286
+ const ms = this.dayOrdinalToUtcMs(dayOrd);
287
+ this.monthStartCache.set(monthIdx, ms);
288
+ return ms;
289
+ }
290
+ localMonthIndex(tsMs) {
291
+ if (this.isUtc) {
292
+ const d = new Date(tsMs);
293
+ return d.getUTCFullYear() * 12 + d.getUTCMonth();
294
+ }
295
+ const dayOrd = this.localDayOrdinal(tsMs);
296
+ const { year, month } = epochDayToYmd(dayOrd);
297
+ return year * 12 + (month - 1);
298
+ }
299
+ tierToSlotId(tier, tsMs) {
300
+ switch (tier) {
301
+ case '15s':
302
+ return Math.floor(tsMs / 15_000);
303
+ case '5m':
304
+ return Math.floor(tsMs / 300_000);
305
+ case '1h':
306
+ return this.isUtc ? Math.floor(tsMs / 3_600_000) : Math.floor((tsMs - this.hourAnchorMs) / 3_600_000);
307
+ case '1d':
308
+ return this.localDayOrdinal(tsMs);
309
+ }
310
+ }
311
+ tierSlotToUtcMs(tier, slotId) {
312
+ switch (tier) {
313
+ case '15s':
314
+ return slotId * 15_000;
315
+ case '5m':
316
+ return slotId * 300_000;
317
+ case '1h':
318
+ return this.isUtc ? slotId * 3_600_000 : this.hourAnchorMs + slotId * 3_600_000;
319
+ case '1d':
320
+ return this.dayOrdinalToUtcMs(slotId);
321
+ }
322
+ }
323
+ floorInterval(tsMs, interval) {
324
+ const { unit, count, fixedMs } = interval;
325
+ if (fixedMs !== undefined) {
326
+ return Math.floor(tsMs / fixedMs) * fixedMs;
327
+ }
328
+ switch (unit) {
329
+ case 'h': {
330
+ if (count === 1) {
331
+ return this.floorHourMs(tsMs);
332
+ }
333
+ if (this.isUtc) {
334
+ const step = count * 3_600_000;
335
+ return Math.floor(tsMs / step) * step;
336
+ }
337
+ const dayOrd = this.localDayOrdinal(tsMs);
338
+ const dayStart = this.dayOrdinalToUtcMs(dayOrd);
339
+ const p = this.getLocalParts(this.floorHourMs(tsMs));
340
+ const bucketHour = Math.floor(p.hour / count) * count;
341
+ if (bucketHour === 0) {
342
+ return dayStart;
343
+ }
344
+ // Step from dayStart until local hour reaches bucketHour (handles DST days accurately).
345
+ let cursor = dayStart + bucketHour * 3_600_000;
346
+ if (cursor > tsMs) {
347
+ cursor -= 3_600_000;
348
+ }
349
+ const pCursor = this.getLocalParts(cursor);
350
+ if (pCursor.hour > bucketHour) {
351
+ const prev = cursor - 3_600_000;
352
+ if (prev >= dayStart && this.getLocalParts(prev).hour >= bucketHour) {
353
+ cursor = prev;
354
+ }
355
+ }
356
+ else if (pCursor.hour < bucketHour) {
357
+ cursor += 3_600_000;
358
+ }
359
+ // If fall-back DST repeated the bucketHour, land on the first occurrence.
360
+ if (cursor - 3_600_000 >= dayStart && this.getLocalParts(cursor - 3_600_000).hour === bucketHour) {
361
+ cursor -= 3_600_000;
362
+ }
363
+ return cursor;
364
+ }
365
+ case 'd': {
366
+ const dayOrd = this.localDayOrdinal(tsMs);
367
+ const alignedOrd = count === 1 ? dayOrd : Math.floor(dayOrd / count) * count;
368
+ return this.dayOrdinalToUtcMs(alignedOrd);
369
+ }
370
+ case 'w': {
371
+ const dayOrd = this.localDayOrdinal(tsMs);
372
+ // 1970-01-01 was Thursday (dow = 4).
373
+ const weekAnchor = this.weekStartsOn === 1 ? 4 : 3;
374
+ const weekDay = (((dayOrd + weekAnchor) % 7) + 7) % 7;
375
+ const weekStartOrd = dayOrd - weekDay;
376
+ const weekIndex = Math.floor((weekStartOrd + weekAnchor) / 7);
377
+ const alignedWeekIndex = count === 1 ? weekIndex : Math.floor(weekIndex / count) * count;
378
+ const alignedOrd = alignedWeekIndex * 7 - weekAnchor;
379
+ return this.dayOrdinalToUtcMs(alignedOrd);
380
+ }
381
+ case 'n': {
382
+ const monthIdx = this.localMonthIndex(tsMs);
383
+ const alignedIdx = count === 1 ? monthIdx : Math.floor(monthIdx / count) * count;
384
+ return this.monthIndexToUtcMs(alignedIdx);
385
+ }
386
+ case 'y': {
387
+ const monthIdx = this.localMonthIndex(tsMs);
388
+ const year = Math.floor(monthIdx / 12);
389
+ const alignedYear = count === 1 ? year : Math.floor(year / count) * count;
390
+ return this.monthIndexToUtcMs(alignedYear * 12);
391
+ }
392
+ default:
393
+ return Math.floor(tsMs / interval.approxMs) * interval.approxMs;
394
+ }
395
+ }
396
+ nextInterval(bucketStartMs, interval) {
397
+ const { unit, count, fixedMs } = interval;
398
+ if (fixedMs !== undefined) {
399
+ return bucketStartMs + fixedMs;
400
+ }
401
+ switch (unit) {
402
+ case 'h': {
403
+ if (count === 1) {
404
+ return bucketStartMs + 3_600_000;
405
+ }
406
+ if (this.isUtc) {
407
+ return bucketStartMs + count * 3_600_000;
408
+ }
409
+ const dayOrd = this.localDayOrdinal(bucketStartMs);
410
+ const nextDayStart = this.dayOrdinalToUtcMs(dayOrd + 1);
411
+ const p = this.getLocalParts(bucketStartMs);
412
+ const targetHour = Math.floor(p.hour / count) * count + count;
413
+ if (targetHour >= 24) {
414
+ return nextDayStart;
415
+ }
416
+ let next = bucketStartMs + count * 3_600_000;
417
+ if (next >= nextDayStart)
418
+ return nextDayStart;
419
+ const pn = this.getLocalParts(next);
420
+ if (pn.hour > targetHour) {
421
+ // Spring forward skipped an hour -> step back 1h to targetHour (or stay if targetHour was skipped).
422
+ const prev = next - 3_600_000;
423
+ if (this.getLocalParts(prev).hour === targetHour)
424
+ next = prev;
425
+ }
426
+ else if (pn.hour < targetHour) {
427
+ // Fall back repeated an hour -> step forward 1h.
428
+ const ahead = next + 3_600_000;
429
+ if (ahead < nextDayStart && this.getLocalParts(ahead).hour === targetHour)
430
+ next = ahead;
431
+ }
432
+ return next;
433
+ }
434
+ case 'd': {
435
+ const dayOrd = this.localDayOrdinal(bucketStartMs);
436
+ return this.dayOrdinalToUtcMs(dayOrd + count);
437
+ }
438
+ case 'w': {
439
+ const dayOrd = this.localDayOrdinal(bucketStartMs);
440
+ return this.dayOrdinalToUtcMs(dayOrd + count * 7);
441
+ }
442
+ case 'n': {
443
+ const monthIdx = this.localMonthIndex(bucketStartMs);
444
+ return this.monthIndexToUtcMs(monthIdx + count);
445
+ }
446
+ case 'y': {
447
+ const monthIdx = this.localMonthIndex(bucketStartMs);
448
+ const year = Math.floor(monthIdx / 12);
449
+ return this.monthIndexToUtcMs((year + count) * 12);
450
+ }
451
+ default:
452
+ return bucketStartMs + interval.approxMs;
453
+ }
454
+ }
455
+ ceilInterval(tsMs, interval) {
456
+ const floored = this.floorInterval(tsMs, interval);
457
+ return floored === tsMs ? floored : this.nextInterval(floored, interval);
458
+ }
459
+ }