@altertable/data-app 0.73.0 → 0.75.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.
Files changed (53) hide show
  1. package/AGENTS.md +11 -3
  2. package/CONTRIBUTING.md +54 -7
  3. package/REFERENCE.md +178 -24
  4. package/dist/chunks/{contract-BeLPJwlO.js → contract-B3s0ybE2.js} +179 -34
  5. package/dist/chunks/contract-B3s0ybE2.js.map +1 -0
  6. package/dist/chunks/{contract-Di8SP74I.js → contract-DcPjfm0R.js} +255 -4
  7. package/dist/chunks/contract-DcPjfm0R.js.map +1 -0
  8. package/dist/chunks/{iframe-C3uCZEXh.js → diagnostics-DVwQ5PDK.js} +161 -3
  9. package/dist/chunks/diagnostics-DVwQ5PDK.js.map +1 -0
  10. package/dist/chunks/format-5hMYUWk3.js +793 -0
  11. package/dist/chunks/format-5hMYUWk3.js.map +1 -0
  12. package/dist/chunks/{operation-CBxhjNhK.js → operation-CGuN7Zcb.js} +10 -7
  13. package/dist/chunks/operation-CGuN7Zcb.js.map +1 -0
  14. package/dist/client/index.js +73 -7
  15. package/dist/client/index.js.map +1 -1
  16. package/dist/core/config.js +4 -3
  17. package/dist/core/config.js.map +1 -1
  18. package/dist/core/contract.js +4 -3
  19. package/dist/core/format.js +1 -1
  20. package/dist/internal.js +8 -7
  21. package/dist/internal.js.map +1 -1
  22. package/dist/server/index.js +3 -3
  23. package/dist/server/index.js.map +1 -1
  24. package/dist/types/chunks/contract.d.ts +168 -10
  25. package/dist/types/chunks/date-time-range-value.d.ts +46 -0
  26. package/dist/types/chunks/index.d.ts +64 -2
  27. package/dist/types/client/index.d.ts +3 -3
  28. package/dist/types/core/config.d.ts +6 -4
  29. package/dist/types/core/contract.d.ts +3 -2
  30. package/dist/types/core/format.d.ts +20 -1
  31. package/dist/types/index.d.ts +3 -2
  32. package/dist/types/internal.d.ts +9 -4
  33. package/dist/types/server/index.d.ts +2 -2
  34. package/docs/app-authoring.md +51 -14
  35. package/docs/composition.md +4 -23
  36. package/docs/contract.md +41 -9
  37. package/docs/diagnostics.md +82 -0
  38. package/docs/embed.md +41 -0
  39. package/docs/hosted-apps.md +7 -4
  40. package/docs/local-data-apps.md +17 -2
  41. package/docs/react.md +6 -3
  42. package/docs/stories-and-export.md +14 -5
  43. package/docs/ui-quality.md +3 -2
  44. package/docs/ui.md +77 -1
  45. package/docs/variables.md +61 -0
  46. package/docs/views.md +2 -2
  47. package/package.json +3 -2
  48. package/dist/chunks/contract-BeLPJwlO.js.map +0 -1
  49. package/dist/chunks/contract-Di8SP74I.js.map +0 -1
  50. package/dist/chunks/format-BdFlv_xa.js +0 -148
  51. package/dist/chunks/format-BdFlv_xa.js.map +0 -1
  52. package/dist/chunks/iframe-C3uCZEXh.js.map +0 -1
  53. package/dist/chunks/operation-CBxhjNhK.js.map +0 -1
@@ -0,0 +1,793 @@
1
+ import { CalendarDateTime } from "@internationalized/date";
2
+ import * as chrono from "chrono-node";
3
+ //#region src/core/date-time-range-parser.ts
4
+ const RANGE_SEPARATOR_PATTERN = / ?(?:-|–|—| to ) ?/i;
5
+ const RELATIVE_UNIT_BY_PATTERN = new Map([
6
+ {
7
+ unit: "SECOND",
8
+ patterns: [
9
+ "seconds",
10
+ "second",
11
+ "secs",
12
+ "sec",
13
+ "s"
14
+ ]
15
+ },
16
+ {
17
+ unit: "MINUTE",
18
+ patterns: [
19
+ "minutes",
20
+ "minute",
21
+ "mins",
22
+ "min",
23
+ "mn",
24
+ "m"
25
+ ]
26
+ },
27
+ {
28
+ unit: "HOUR",
29
+ patterns: [
30
+ "hours",
31
+ "hour",
32
+ "hrs",
33
+ "hr",
34
+ "h"
35
+ ]
36
+ },
37
+ {
38
+ unit: "DAY",
39
+ patterns: [
40
+ "days",
41
+ "day",
42
+ "d"
43
+ ]
44
+ },
45
+ {
46
+ unit: "WEEK",
47
+ patterns: [
48
+ "weeks",
49
+ "week",
50
+ "wks",
51
+ "wk",
52
+ "w"
53
+ ]
54
+ },
55
+ {
56
+ unit: "MONTH",
57
+ patterns: [
58
+ "months",
59
+ "month",
60
+ "mos",
61
+ "mo",
62
+ "mon"
63
+ ]
64
+ },
65
+ {
66
+ unit: "YEAR",
67
+ patterns: [
68
+ "years",
69
+ "year",
70
+ "yrs",
71
+ "yr",
72
+ "y"
73
+ ]
74
+ }
75
+ ].flatMap(({ unit, patterns }) => patterns.map((pattern) => [pattern, unit])));
76
+ function escapeRegex(value) {
77
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
78
+ }
79
+ const RELATIVE_UNIT_PATTERN = [...RELATIVE_UNIT_BY_PATTERN.keys()].sort((left, right) => right.length - left.length).map(escapeRegex).join("|");
80
+ const SLIDING_RELATIVE_PATTERN = new RegExp(`^(?:last|past)\\s+(?:(\\d+)\\s*)?(${RELATIVE_UNIT_PATTERN})$`, "i");
81
+ const AGO_RELATIVE_PATTERN = new RegExp(`^(\\d+)\\s*(${RELATIVE_UNIT_PATTERN})\\s+ago$`, "i");
82
+ const BARE_RELATIVE_PATTERN = new RegExp(`^(\\d+)\\s*(${RELATIVE_UNIT_PATTERN})$`, "i");
83
+ const SINCE_PREFIX_PATTERN = /^(?:since|from) (.+)$/i;
84
+ const UNIX_TIMESTAMP_PATTERN = /^\d+$/;
85
+ const NOW_KEYWORDS = /* @__PURE__ */ new Set(["now", "today"]);
86
+ function normalizeInput(input) {
87
+ return input.trim().replace(/\s+/g, " ");
88
+ }
89
+ function getParserContext(options) {
90
+ const now = options?.now ?? /* @__PURE__ */ new Date();
91
+ return {
92
+ now,
93
+ reference: {
94
+ instant: now,
95
+ timezone: "UTC"
96
+ }
97
+ };
98
+ }
99
+ /** Construct wall-clock fields without interpreting the runtime timezone. */
100
+ function utcDate(year, month, day, hour = 0, minute = 0, second = 0, millisecond = 0) {
101
+ const date = /* @__PURE__ */ new Date(0);
102
+ date.setUTCFullYear(year, month, day);
103
+ date.setUTCHours(hour, minute, second, millisecond);
104
+ return date;
105
+ }
106
+ function parseRelativeUnit(rawUnit) {
107
+ return RELATIVE_UNIT_BY_PATTERN.get(rawUnit.toLowerCase()) ?? null;
108
+ }
109
+ function relativeFromNowOffset(amount, unit) {
110
+ return {
111
+ anchor: "RELATIVE_ANCHOR_NOW",
112
+ offset: [{
113
+ amount: -amount,
114
+ unit
115
+ }]
116
+ };
117
+ }
118
+ function success(range, normalizedInput, parser) {
119
+ return {
120
+ ok: true,
121
+ range,
122
+ normalizedInput,
123
+ parser
124
+ };
125
+ }
126
+ function failure(reason, normalizedInput) {
127
+ return {
128
+ ok: false,
129
+ reason,
130
+ normalizedInput
131
+ };
132
+ }
133
+ function parseUnixTimestamp(raw) {
134
+ const trimmed = raw.trim();
135
+ if (!UNIX_TIMESTAMP_PATTERN.test(trimmed)) return null;
136
+ const value = Number(trimmed);
137
+ if (!Number.isFinite(value)) return null;
138
+ const date = trimmed.length <= 10 ? /* @__PURE__ */ new Date(value * 1e3) : new Date(value);
139
+ return Number.isFinite(date.getTime()) ? date : null;
140
+ }
141
+ function dateFromChronoComponents(components) {
142
+ const year = components.get("year");
143
+ const month = components.get("month");
144
+ const day = components.get("day");
145
+ const hour = components.get("hour");
146
+ const minute = components.get("minute");
147
+ const second = components.get("second");
148
+ const millisecond = components.get("millisecond");
149
+ if (year === null || month === null || day === null) return null;
150
+ return utcDate(year, month - 1, day, hour ?? 0, minute ?? 0, second ?? 0, millisecond ?? 0);
151
+ }
152
+ const wallClockParser = chrono.casual.clone();
153
+ wallClockParser.refiners = wallClockParser.refiners.map((refiner) => ({ refine(context, results) {
154
+ for (const result of results) for (const components of [result.start, result.end]) {
155
+ if (!components) continue;
156
+ components.isValidDate = () => {
157
+ const date = dateFromChronoComponents(components);
158
+ return date !== null && Number.isFinite(date.getTime()) && date.getUTCFullYear() === components.get("year") && date.getUTCMonth() + 1 === components.get("month") && date.getUTCDate() === components.get("day") && date.getUTCHours() === (components.get("hour") ?? 0) && date.getUTCMinutes() === (components.get("minute") ?? 0);
159
+ };
160
+ }
161
+ return refiner.refine(context, results);
162
+ } }));
163
+ function parseAbsoluteResult(text, reference) {
164
+ const trimmed = text.trim();
165
+ if (!trimmed) return null;
166
+ const results = wallClockParser.parse(trimmed, reference, { forwardDate: false });
167
+ if (results.length === 0) return null;
168
+ const parsed = results[0];
169
+ if (!parsed) return null;
170
+ if (parsed.index !== 0 || parsed.text.length !== trimmed.length) return null;
171
+ if (results.length > 1) {
172
+ const firstStart = parsed.start.date().getTime();
173
+ if (results.some((result) => result.start.date().getTime() !== firstStart)) return "ambiguous";
174
+ }
175
+ return parsed;
176
+ }
177
+ function parseAbsoluteDateTime(text, reference, end = false) {
178
+ const parsed = parseAbsoluteResult(text, reference);
179
+ if (!parsed || parsed === "ambiguous") return parsed;
180
+ if (parsed.end) return null;
181
+ return absoluteBoundary(parsed.start, end);
182
+ }
183
+ function absoluteBoundary(components, end = false) {
184
+ const date = dateFromChronoComponents(components);
185
+ if (date && !components.isCertain("hour")) {
186
+ date.setUTCHours(0, 0, 0, 0);
187
+ if (end) date.setUTCDate(date.getUTCDate() + 1);
188
+ }
189
+ return date;
190
+ }
191
+ function isNowKeyword(text) {
192
+ return NOW_KEYWORDS.has(text.trim().toLowerCase());
193
+ }
194
+ const CALENDAR_MONTH_PATTERN = /^(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)(?:\s+(\d{4}))?$/i;
195
+ const CALENDAR_MONTHS = [
196
+ "jan",
197
+ "feb",
198
+ "mar",
199
+ "apr",
200
+ "may",
201
+ "jun",
202
+ "jul",
203
+ "aug",
204
+ "sep",
205
+ "oct",
206
+ "nov",
207
+ "dec"
208
+ ];
209
+ function parseCalendarPeriod(text) {
210
+ if (/^\d{4}$/.test(text)) return {
211
+ year: Number(text),
212
+ month: 0,
213
+ months: 12
214
+ };
215
+ const match = text.match(CALENDAR_MONTH_PATTERN);
216
+ if (!match?.[1]) return null;
217
+ return {
218
+ year: match[2] ? Number(match[2]) : null,
219
+ month: CALENDAR_MONTHS.indexOf(match[1].slice(0, 3).toLowerCase()),
220
+ months: 1
221
+ };
222
+ }
223
+ function tryParseCalendarRange(normalized, now) {
224
+ const parts = normalized.split(RANGE_SEPARATOR_PATTERN);
225
+ if (parts.length > 2) return null;
226
+ const first = parseCalendarPeriod(parts[0] ?? "");
227
+ const last = parts.length === 1 ? first : parseCalendarPeriod(parts[1] ?? "");
228
+ if (!first || !last || first.months !== last.months) return null;
229
+ const currentYear = now.getUTCFullYear();
230
+ const fromYear = first.year ?? last.year ?? currentYear;
231
+ const toYear = last.year ?? first.year ?? currentYear;
232
+ const from = utcDate(fromYear, first.month, 1);
233
+ const to = utcDate(toYear, last.month + last.months, 1);
234
+ if (from.getTime() >= to.getTime()) return failure("invalid-range", normalized);
235
+ return success({
236
+ from,
237
+ to
238
+ }, normalized, "calendar-range");
239
+ }
240
+ function tryParseUnixRange(normalized) {
241
+ const parts = normalized.split(RANGE_SEPARATOR_PATTERN);
242
+ if (parts.length !== 2) return null;
243
+ const fromPart = parts.at(0);
244
+ const toPart = parts.at(1);
245
+ if (!fromPart || !toPart) return null;
246
+ const from = parseUnixTimestamp(fromPart);
247
+ if (from && isNowKeyword(toPart)) return success({
248
+ from,
249
+ to: null
250
+ }, normalized, "unix");
251
+ const to = parseUnixTimestamp(toPart);
252
+ if (!from || !to) return null;
253
+ if (from.getTime() > to.getTime()) return failure("invalid-range", normalized);
254
+ return success({
255
+ from,
256
+ to
257
+ }, normalized, "unix");
258
+ }
259
+ function tryParseSlidingRelative(normalized) {
260
+ const match = normalized.match(SLIDING_RELATIVE_PATTERN);
261
+ if (!match) return null;
262
+ const amount = match[1] ? Number(match[1]) : 1;
263
+ const unit = parseRelativeUnit(match[2] ?? "");
264
+ if (!Number.isSafeInteger(amount) || amount <= 0 || !unit) return null;
265
+ return success({
266
+ from: relativeFromNowOffset(amount, unit),
267
+ to: null
268
+ }, normalized, "relative");
269
+ }
270
+ function tryParseCalendarPreset(normalized) {
271
+ const lower = normalized.toLowerCase();
272
+ if (lower === "today") return success({
273
+ from: {
274
+ anchor: "RELATIVE_ANCHOR_START_OF_TODAY",
275
+ offset: []
276
+ },
277
+ to: null
278
+ }, normalized, "calendar-preset");
279
+ if (lower === "yesterday") return success({
280
+ from: {
281
+ anchor: "RELATIVE_ANCHOR_START_OF_YESTERDAY",
282
+ offset: []
283
+ },
284
+ to: {
285
+ anchor: "RELATIVE_ANCHOR_START_OF_TODAY",
286
+ offset: []
287
+ }
288
+ }, normalized, "calendar-preset");
289
+ if (lower === "week to date" || lower === "wtd") return success({
290
+ from: {
291
+ anchor: "RELATIVE_ANCHOR_START_OF_WEEK",
292
+ offset: []
293
+ },
294
+ to: null
295
+ }, normalized, "calendar-preset");
296
+ if (lower === "month to date" || lower === "mtd") return success({
297
+ from: {
298
+ anchor: "RELATIVE_ANCHOR_START_OF_MONTH",
299
+ offset: []
300
+ },
301
+ to: null
302
+ }, normalized, "calendar-preset");
303
+ if (lower === "year to date" || lower === "ytd") return success({
304
+ from: {
305
+ anchor: "RELATIVE_ANCHOR_START_OF_YEAR",
306
+ offset: []
307
+ },
308
+ to: null
309
+ }, normalized, "calendar-preset");
310
+ return null;
311
+ }
312
+ function tryParseAgoRelative(normalized) {
313
+ const match = normalized.match(AGO_RELATIVE_PATTERN);
314
+ if (!match) return null;
315
+ const amount = Number(match[1]);
316
+ const unit = parseRelativeUnit(match[2] ?? "");
317
+ if (!Number.isSafeInteger(amount) || amount <= 0 || !unit) return null;
318
+ return success({
319
+ from: relativeFromNowOffset(amount, unit),
320
+ to: null
321
+ }, normalized, "relative");
322
+ }
323
+ function tryParseBareRelative(normalized) {
324
+ const match = normalized.match(BARE_RELATIVE_PATTERN);
325
+ if (!match) return null;
326
+ const amount = Number(match[1]);
327
+ const unit = parseRelativeUnit(match[2] ?? "");
328
+ if (!Number.isSafeInteger(amount) || amount <= 0 || !unit) return null;
329
+ return success({
330
+ from: relativeFromNowOffset(amount, unit),
331
+ to: null
332
+ }, normalized, "relative");
333
+ }
334
+ function tryParseSinceRelative(normalized) {
335
+ const match = normalized.match(SINCE_PREFIX_PATTERN);
336
+ if (!match) return null;
337
+ const remainder = match[1]?.trim();
338
+ if (!remainder) return failure("unrecognized", normalized);
339
+ const agoMatch = remainder.match(AGO_RELATIVE_PATTERN);
340
+ if (agoMatch) {
341
+ const amount = Number(agoMatch[1]);
342
+ const unit = parseRelativeUnit(agoMatch[2] ?? "");
343
+ if (!Number.isSafeInteger(amount) || amount <= 0 || !unit) return failure("unrecognized", normalized);
344
+ return success({
345
+ from: relativeFromNowOffset(amount, unit),
346
+ to: null
347
+ }, normalized, "relative");
348
+ }
349
+ return null;
350
+ }
351
+ function tryParseSinceAbsolute(normalized, reference) {
352
+ const match = normalized.match(SINCE_PREFIX_PATTERN);
353
+ if (!match) return null;
354
+ const remainder = match[1]?.trim();
355
+ if (!remainder) return failure("unrecognized", normalized);
356
+ const range = tryParseAbsoluteRange(remainder, reference);
357
+ if (range) return {
358
+ ...range,
359
+ normalizedInput: normalized
360
+ };
361
+ const absolute = parseAbsoluteDateTime(remainder, reference);
362
+ if (absolute === "ambiguous") return failure("ambiguous", normalized);
363
+ if (!absolute) return failure("unrecognized", normalized);
364
+ return success({
365
+ from: absolute,
366
+ to: null
367
+ }, normalized, "chrono");
368
+ }
369
+ function tryParseAbsoluteRange(normalized, reference) {
370
+ const parts = normalized.split(RANGE_SEPARATOR_PATTERN);
371
+ if (parts.length !== 2) return null;
372
+ const fromPart = parts.at(0)?.trim();
373
+ const toPart = parts.at(1)?.trim();
374
+ if (!fromPart || !toPart) return null;
375
+ if (isNowKeyword(toPart)) {
376
+ const from = parseAbsoluteDateTime(fromPart, reference);
377
+ if (from === "ambiguous") return failure("ambiguous", normalized);
378
+ if (!from) return null;
379
+ return success({
380
+ from,
381
+ to: null
382
+ }, normalized, "chrono");
383
+ }
384
+ const paired = parseAbsoluteResult(normalized, reference);
385
+ if (paired === "ambiguous") return failure("ambiguous", normalized);
386
+ if (paired?.end) {
387
+ const from = absoluteBoundary(paired.start);
388
+ const to = absoluteBoundary(paired.end, true);
389
+ if (!from || !to) return null;
390
+ if (from.getTime() >= to.getTime()) return failure("invalid-range", normalized);
391
+ return success({
392
+ from,
393
+ to
394
+ }, normalized, "chrono");
395
+ }
396
+ const from = parseAbsoluteDateTime(fromPart, reference);
397
+ if (from === "ambiguous") return failure("ambiguous", normalized);
398
+ const to = parseAbsoluteDateTime(toPart, reference, true);
399
+ if (to === "ambiguous") return failure("ambiguous", normalized);
400
+ if (!from || !to) return null;
401
+ if (from.getTime() > to.getTime()) return failure("invalid-range", normalized);
402
+ return success({
403
+ from,
404
+ to
405
+ }, normalized, "chrono");
406
+ }
407
+ function tryParseAbsoluteDay(normalized, reference) {
408
+ const parsed = parseAbsoluteResult(normalized, reference);
409
+ if (parsed === "ambiguous") return failure("ambiguous", normalized);
410
+ if (!parsed || parsed.end || !parsed.start.isCertain("month") || !parsed.start.isCertain("day") || parsed.start.isCertain("hour")) return null;
411
+ const year = parsed.start.get("year");
412
+ const month = parsed.start.get("month");
413
+ const day = parsed.start.get("day");
414
+ if (year === null || month === null || day === null) return null;
415
+ return success({
416
+ from: utcDate(year, month - 1, day),
417
+ to: utcDate(year, month - 1, day + 1)
418
+ }, normalized, "chrono");
419
+ }
420
+ function parseDateTimeRangeInput(input, options) {
421
+ const normalizedInput = normalizeInput(input);
422
+ if (!normalizedInput) return failure("empty", normalizedInput);
423
+ const { reference, now } = getParserContext(options);
424
+ if (!Number.isFinite(now.getTime())) return failure("invalid-range", normalizedInput);
425
+ const attempts = [
426
+ () => tryParseCalendarRange(normalizedInput, now),
427
+ () => tryParseUnixRange(normalizedInput),
428
+ () => tryParseSlidingRelative(normalizedInput),
429
+ () => tryParseCalendarPreset(normalizedInput),
430
+ () => tryParseAgoRelative(normalizedInput),
431
+ () => tryParseBareRelative(normalizedInput),
432
+ () => tryParseSinceRelative(normalizedInput),
433
+ () => tryParseSinceAbsolute(normalizedInput, reference),
434
+ () => tryParseAbsoluteRange(normalizedInput, reference),
435
+ () => tryParseAbsoluteDay(normalizedInput, reference)
436
+ ];
437
+ for (const attempt of attempts) {
438
+ const result = attempt();
439
+ if (!result) continue;
440
+ if (!result.ok) return result;
441
+ return result;
442
+ }
443
+ return failure("unrecognized", normalizedInput);
444
+ }
445
+ //#endregion
446
+ //#region src/core/invariant.ts
447
+ /** Assert an author or data contract while preserving a useful failure message. */
448
+ function invariant(condition, message) {
449
+ if (!condition) throw new Error(`Invariant failed: ${message}`);
450
+ }
451
+ //#endregion
452
+ //#region src/core/time-units.ts
453
+ const second = 1e3;
454
+ const minute = 60 * second;
455
+ const hour = 60 * minute;
456
+ const day = 24 * hour;
457
+ /** Fixed durations in UTC-rebased arithmetic; months and years are calendar-dependent. */
458
+ const fixedUnitMilliseconds = {
459
+ SECOND: second,
460
+ MINUTE: minute,
461
+ HOUR: hour,
462
+ DAY: day,
463
+ WEEK: 7 * day
464
+ };
465
+ //#endregion
466
+ //#region src/core/date-time-range-value.ts
467
+ const anchors = {
468
+ RELATIVE_ANCHOR_NOW: "Now",
469
+ RELATIVE_ANCHOR_START_OF_TODAY: "Start of today",
470
+ RELATIVE_ANCHOR_START_OF_YESTERDAY: "Start of yesterday",
471
+ RELATIVE_ANCHOR_START_OF_TOMORROW: "Start of tomorrow",
472
+ RELATIVE_ANCHOR_START_OF_WEEK: "Start of week",
473
+ RELATIVE_ANCHOR_START_OF_MONTH: "Start of month",
474
+ RELATIVE_ANCHOR_START_OF_YEAR: "Start of year"
475
+ };
476
+ const units = {
477
+ SECOND: "s",
478
+ MINUTE: "m",
479
+ HOUR: "h",
480
+ DAY: "d",
481
+ WEEK: "w",
482
+ MONTH: "mo",
483
+ YEAR: "y"
484
+ };
485
+ /** Validate and restore UTC-rebased dates from JSON, without resolving relative bounds. */
486
+ function parseDateTimeRange(value, { maxRangeDays } = {}) {
487
+ invariant(!!value && typeof value === "object" && !Array.isArray(value), "Choose a datetime range.");
488
+ const record = value;
489
+ invariant(Object.keys(record).every((key) => key === "from" || key === "to"), "Unknown datetime range field.");
490
+ function bound(raw) {
491
+ if (raw == null) return null;
492
+ if (raw instanceof Date || typeof raw === "string") {
493
+ const date = new Date(raw);
494
+ invariant(Number.isFinite(date.getTime()) && (raw instanceof Date || date.toISOString() === raw), "Absolute bounds must be UTC ISO dates.");
495
+ return date;
496
+ }
497
+ invariant(typeof raw === "object" && !Array.isArray(raw), "Invalid datetime bound.");
498
+ const r = raw;
499
+ invariant(Object.keys(r).every((key) => key === "anchor" || key === "offset") && typeof r.anchor === "string" && Object.hasOwn(anchors, r.anchor), "Invalid relative anchor.");
500
+ invariant(Array.isArray(r.offset) && r.offset.length <= 16, "Use at most 16 relative offsets.");
501
+ const offset = r.offset.map((o) => {
502
+ invariant(!!o && typeof o === "object" && !Array.isArray(o), "Invalid relative offset.");
503
+ const v = o;
504
+ invariant(Object.keys(v).every((key) => key === "amount" || key === "unit") && typeof v.amount === "number" && Number.isSafeInteger(v.amount) && Math.abs(v.amount) <= 1e6 && typeof v.unit === "string" && Object.hasOwn(units, v.unit), "Invalid relative offset.");
505
+ return {
506
+ amount: v.amount,
507
+ unit: v.unit
508
+ };
509
+ });
510
+ return {
511
+ anchor: r.anchor,
512
+ offset
513
+ };
514
+ }
515
+ const range = {
516
+ from: bound(record.from),
517
+ to: bound(record.to)
518
+ };
519
+ if (range.from instanceof Date && range.to instanceof Date) invariant(range.from < range.to, "Start must be before end.");
520
+ invariant(maxRangeDays === void 0 || Number.isFinite(maxRangeDays) && maxRangeDays > 0, "Maximum range days must be positive.");
521
+ let duration;
522
+ if (range.from instanceof Date && range.to instanceof Date) duration = range.to.getTime() - range.from.getTime();
523
+ else if (range.from && !(range.from instanceof Date) && !(range.to instanceof Date)) {
524
+ const to = range.to ?? {
525
+ anchor: "RELATIVE_ANCHOR_NOW",
526
+ offset: []
527
+ };
528
+ if (range.from.anchor === to.anchor) {
529
+ function offset(bound) {
530
+ let total = 0;
531
+ for (const item of bound.offset) {
532
+ const unit = fixedUnitMilliseconds[item.unit];
533
+ if (unit === void 0) return void 0;
534
+ total += item.amount * unit;
535
+ }
536
+ return total;
537
+ }
538
+ const start = offset(range.from);
539
+ const end = offset(to);
540
+ if (start !== void 0 && end !== void 0) duration = end - start;
541
+ }
542
+ }
543
+ invariant(duration === void 0 || duration > 0, "Start must be before end.");
544
+ invariant(maxRangeDays === void 0 || !!range.from && (duration === void 0 || duration <= maxRangeDays * fixedUnitMilliseconds.DAY), `Choose a range of at most ${maxRangeDays} days.`);
545
+ return range;
546
+ }
547
+ /** Canonical URL/JSON representation. Dates retain their encoded UTC fields. */
548
+ function serializeDateTimeRange(value) {
549
+ return JSON.stringify(parseDateTimeRange(value));
550
+ }
551
+ /** UTC preview only. Backend execution owns reporting-timezone interpretation. Null start is unbounded; null end is now. */
552
+ function resolveDateTimeRange(value, now = /* @__PURE__ */ new Date()) {
553
+ const range = parseDateTimeRange(value);
554
+ invariant(Number.isFinite(now.getTime()), "Invalid reference date.");
555
+ function resolve(bound) {
556
+ if (bound instanceof Date) return new Date(bound);
557
+ let date = new CalendarDateTime(now.getUTCFullYear(), now.getUTCMonth() + 1, now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
558
+ if (bound.anchor !== "RELATIVE_ANCHOR_NOW") date = date.set({
559
+ hour: 0,
560
+ minute: 0,
561
+ second: 0,
562
+ millisecond: 0
563
+ });
564
+ switch (bound.anchor) {
565
+ case "RELATIVE_ANCHOR_START_OF_YESTERDAY":
566
+ date = date.subtract({ days: 1 });
567
+ break;
568
+ case "RELATIVE_ANCHOR_START_OF_TOMORROW":
569
+ date = date.add({ days: 1 });
570
+ break;
571
+ case "RELATIVE_ANCHOR_START_OF_WEEK":
572
+ date = date.subtract({ days: (now.getUTCDay() + 6) % 7 });
573
+ break;
574
+ case "RELATIVE_ANCHOR_START_OF_MONTH":
575
+ date = date.set({ day: 1 });
576
+ break;
577
+ case "RELATIVE_ANCHOR_START_OF_YEAR": date = date.set({
578
+ month: 1,
579
+ day: 1
580
+ });
581
+ }
582
+ const durations = {
583
+ SECOND: "seconds",
584
+ MINUTE: "minutes",
585
+ HOUR: "hours",
586
+ DAY: "days",
587
+ WEEK: "weeks",
588
+ MONTH: "months",
589
+ YEAR: "years"
590
+ };
591
+ for (const offset of bound.offset) date = date.add({ [durations[offset.unit]]: offset.amount });
592
+ return date.toDate("UTC");
593
+ }
594
+ const from = range.from ? resolve(range.from) : null;
595
+ const to = range.to ? resolve(range.to) : new Date(now);
596
+ invariant(!from || from < to, "Start must be before end.");
597
+ return {
598
+ from,
599
+ to
600
+ };
601
+ }
602
+ function formatDateTimeBound(value, fallback = "Now") {
603
+ if (!value) return fallback;
604
+ if (value instanceof Date) return value.toISOString().replace("T", " ").replace(/:00\.000Z$/, "").replace(/Z$/, "");
605
+ const offsets = value.offset.map((o) => `${o.amount >= 0 ? "+" : "−"} ${Math.abs(o.amount)}${units[o.unit]}`).join(" ");
606
+ return `${anchors[value.anchor]}${offsets ? ` ${offsets}` : ""}`;
607
+ }
608
+ function formatDateTimeRange(value) {
609
+ const range = parseDateTimeRange(value);
610
+ const from = range.from;
611
+ if (from && !(from instanceof Date) && from.anchor === "RELATIVE_ANCHOR_NOW" && from.offset.length === 1 && from.offset[0].amount < 0 && !range.to) {
612
+ const offset = from.offset[0];
613
+ return `Last ${Math.abs(offset.amount)}${units[offset.unit]}`;
614
+ }
615
+ return `${formatDateTimeBound(from, "Any time")} → ${formatDateTimeBound(range.to)}`;
616
+ }
617
+ /** Parse one bound without resolving relative anchors or offsets. */
618
+ function parseDateTimeBound(text) {
619
+ const input = text.trim();
620
+ invariant(!!input, "Enter a date, time, or relative expression.");
621
+ for (const [anchor, label] of Object.entries(anchors)) {
622
+ if (!input.toLowerCase().startsWith(label.toLowerCase())) continue;
623
+ const suffix = input.slice(label.length).trim();
624
+ if (!/^(?:[+−-]\s*\d+\s*(?:mo|[smhdwy])\s*)*$/.test(suffix)) continue;
625
+ return parseDateTimeRange({ to: {
626
+ anchor,
627
+ offset: Array.from(suffix.matchAll(/([+−-])\s*(\d+)\s*(mo|[smhdwy])/g), (match) => ({
628
+ amount: Number(match[2]) * (match[1] === "+" ? 1 : -1),
629
+ unit: Object.entries(units).find(([, abbreviation]) => abbreviation === match[3])[0]
630
+ }))
631
+ } }).to;
632
+ }
633
+ if (/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d{3})?)?)?Z?$/.test(input)) {
634
+ const encoded = input.includes("T") ? input.replace(/Z$/, "") : `${input}T00:00`;
635
+ const date = /* @__PURE__ */ new Date(`${encoded}Z`);
636
+ invariant(Number.isFinite(date.getTime()) && date.toISOString().startsWith(encoded), "Choose a valid date and time.");
637
+ return date;
638
+ }
639
+ const parsed = parseDateTimeRangeInput(input);
640
+ if (parsed.ok && parsed.range.from) return parsed.range.from;
641
+ const since = parseDateTimeRangeInput(`since ${input}`);
642
+ invariant(since.ok && !!since.range.from, "Enter a date, time, or relative expression.");
643
+ return since.range.from;
644
+ }
645
+ //#endregion
646
+ //#region src/core/date-format.ts
647
+ const calendarDate = /^\d{4}-\d{2}-\d{2}$/;
648
+ const timestamp = /^(\d{4}-\d{2}-\d{2})T(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d{1,9})?)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
649
+ function missing(options) {
650
+ return options.missing ?? "—";
651
+ }
652
+ function parseCalendarDate(value) {
653
+ if (!calendarDate.test(value)) return null;
654
+ const date = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
655
+ return Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value ? null : date;
656
+ }
657
+ function formatter(locale, options) {
658
+ try {
659
+ return new Intl.DateTimeFormat(locale, options);
660
+ } catch {
661
+ return null;
662
+ }
663
+ }
664
+ /** Format an ISO calendar date as a date, never as a browser-local instant. */
665
+ function formatDate(value, options = {}) {
666
+ if (value === null || value === void 0) return missing(options);
667
+ const date = parseCalendarDate(value);
668
+ const format = formatter(options.locale ?? "en-US", {
669
+ dateStyle: "medium",
670
+ timeZone: "UTC"
671
+ });
672
+ return date && format ? format.format(date) : missing(options);
673
+ }
674
+ /** Parse only unambiguous instants. String values must include `Z` or an explicit offset. */
675
+ function parseDateTime(value) {
676
+ if (value === null || value === void 0) return null;
677
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
678
+ if (typeof value === "number") {
679
+ const date = new Date(value);
680
+ return Number.isNaN(date.getTime()) ? null : date;
681
+ }
682
+ const match = timestamp.exec(value);
683
+ if (!match || !parseCalendarDate(match[1])) return null;
684
+ const date = new Date(value);
685
+ return Number.isNaN(date.getTime()) ? null : date;
686
+ }
687
+ /** Format an instant in an explicit reporting zone. Defaults use UTC and 24-hour minutes. */
688
+ function formatDateTime(value, options = {}) {
689
+ const date = parseDateTime(value);
690
+ const format = formatter(options.locale ?? "en-US", {
691
+ dateStyle: "medium",
692
+ timeStyle: options.precision === "second" ? "medium" : "short",
693
+ hourCycle: "h23",
694
+ timeZone: options.timeZone ?? "UTC"
695
+ });
696
+ return date && format ? format.format(date) : missing(options);
697
+ }
698
+ /** Format an instant's time for intraday chart axes using the same zone and precision policy. */
699
+ function formatTime(value, options = {}) {
700
+ const date = parseDateTime(value);
701
+ const format = formatter(options.locale ?? "en-US", {
702
+ hour: "2-digit",
703
+ minute: "2-digit",
704
+ ...options.precision === "second" ? { second: "2-digit" } : {},
705
+ hourCycle: "h23",
706
+ timeZone: options.timeZone ?? "UTC"
707
+ });
708
+ return date && format ? format.format(date) : missing(options);
709
+ }
710
+ //#endregion
711
+ //#region src/core/format.ts
712
+ /** Compact, unambiguous calendar dates for labels and request status. */
713
+ function formatDateRange({ start, end }, options = {}) {
714
+ const first = parseDateTime(`${start}T00:00:00Z`);
715
+ const last = parseDateTime(`${end}T00:00:00Z`);
716
+ if (!first || !last || start > end) return options.missing ?? "—";
717
+ if (options.locale && options.locale !== "en-US") try {
718
+ return new Intl.DateTimeFormat(options.locale, {
719
+ dateStyle: "medium",
720
+ timeZone: "UTC"
721
+ }).formatRange(first, last);
722
+ } catch {
723
+ return options.missing ?? "—";
724
+ }
725
+ function format(date, options) {
726
+ return new Intl.DateTimeFormat("en-US", {
727
+ ...options,
728
+ timeZone: "UTC"
729
+ }).format(date);
730
+ }
731
+ function formatFullDate(date) {
732
+ return format(date, {
733
+ month: "short",
734
+ day: "numeric",
735
+ year: "numeric"
736
+ });
737
+ }
738
+ if (start === end) return formatFullDate(first);
739
+ if (first.getUTCFullYear() !== last.getUTCFullYear()) return `${formatFullDate(first)}–${formatFullDate(last)}`;
740
+ const firstMonth = format(first, { month: "short" });
741
+ const lastMonth = format(last, { month: "short" });
742
+ const firstDay = first.getUTCDate();
743
+ const lastDay = last.getUTCDate();
744
+ return firstMonth === lastMonth ? `${firstMonth} ${firstDay}–${lastDay}, ${last.getUTCFullYear()}` : `${firstMonth} ${firstDay}–${lastMonth} ${lastDay}, ${last.getUTCFullYear()}`;
745
+ }
746
+ function formatMetric(value, format) {
747
+ if (format.kind === "count") return formatCount(value, format);
748
+ if (format.kind === "ratio") return formatPercent(value, format);
749
+ return formatNumber(value, {
750
+ style: "currency",
751
+ currency: format.currency,
752
+ locale: format.locale
753
+ });
754
+ }
755
+ /** Missing and non-finite values use the `missing` label; negative zero renders as zero. */
756
+ function formatNumber(value, options = {}) {
757
+ const { locale = "en-US", missing = "—", ...numberOptions } = options;
758
+ return value === null || value === void 0 || !Number.isFinite(value) ? missing : new Intl.NumberFormat(locale, numberOptions).format(Object.is(value, -0) ? 0 : value);
759
+ }
760
+ /** Negative and fractional counts render as missing. Compact notation is opt-in. */
761
+ function formatCount(value, options = {}) {
762
+ const { compact = false, ...common } = options;
763
+ if (value !== null && value !== void 0 && (!Number.isInteger(value) || value < 0)) return common.missing ?? "—";
764
+ return formatNumber(value, {
765
+ ...common,
766
+ notation: compact ? "compact" : "standard",
767
+ maximumFractionDigits: compact ? 1 : 0
768
+ });
769
+ }
770
+ const pluralRules = new Intl.PluralRules();
771
+ function pluralize(count, singular, plural = `${singular}s`) {
772
+ return pluralRules.select(count) === "one" ? singular : plural;
773
+ }
774
+ /** Accepts a ratio (0.116), not a percentage (11.6). */
775
+ function formatPercent(ratio, options = {}) {
776
+ if (ratio === null || ratio === void 0 || !Number.isFinite(ratio)) return options.missing ?? "—";
777
+ const digits = options.maximumFractionDigits ?? (Math.abs(ratio) < .01 ? 2 : 1);
778
+ const percentOptions = {
779
+ locale: options.locale,
780
+ style: "percent",
781
+ maximumFractionDigits: digits
782
+ };
783
+ const smallestVisibleRatio = 10 ** -digits / 100;
784
+ if (ratio !== 0 && Math.round(Math.abs(ratio) / smallestVisibleRatio) === 0) {
785
+ const boundary = formatNumber(smallestVisibleRatio, percentOptions);
786
+ return ratio > 0 ? `<${boundary}` : `>−${boundary}`;
787
+ }
788
+ return formatNumber(ratio, percentOptions);
789
+ }
790
+ //#endregion
791
+ export { fixedUnitMilliseconds as _, formatPercent as a, formatDateTime as c, formatDateTimeBound as d, formatDateTimeRange as f, serializeDateTimeRange as g, resolveDateTimeRange as h, formatNumber as i, formatTime as l, parseDateTimeRange as m, formatDateRange as n, pluralize as o, parseDateTimeBound as p, formatMetric as r, formatDate as s, formatCount as t, parseDateTime as u, invariant as v, parseDateTimeRangeInput as y };
792
+
793
+ //# sourceMappingURL=format-5hMYUWk3.js.map