@watchtowerobservability/activity-render 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,336 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ render: () => render,
24
+ runVectors: () => runVectors,
25
+ supportsTimeZone: () => supportsTimeZone
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/format.ts
30
+ function decompose(n) {
31
+ const view = new DataView(new ArrayBuffer(8));
32
+ view.setFloat64(0, n);
33
+ const hi = view.getUint32(0);
34
+ const mantissa = BigInt(hi & 1048575) << 32n | BigInt(view.getUint32(4));
35
+ const biased = hi >>> 20 & 2047;
36
+ return biased === 0 ? [mantissa, -1074] : [mantissa | 1n << 52n, biased - 1075];
37
+ }
38
+ function fixed(n, dec) {
39
+ const [m, e] = decompose(n);
40
+ const scale = 10n ** BigInt(dec);
41
+ let q;
42
+ if (e >= 0) {
43
+ q = (m << BigInt(e)) * scale;
44
+ } else {
45
+ const num = m * scale;
46
+ const den = 1n << BigInt(-e);
47
+ q = num / den;
48
+ const twice = num % den * 2n;
49
+ if (twice > den || twice === den && (q & 1n) === 1n) q += 1n;
50
+ }
51
+ const s = q.toString().padStart(dec + 1, "0");
52
+ return dec > 0 ? `${s.slice(0, s.length - dec)}.${s.slice(s.length - dec)}` : s;
53
+ }
54
+ function ryu(n) {
55
+ if (n === 0) return Object.is(n, -0) ? "-0.0" : "0.0";
56
+ const [mant, ex] = Math.abs(n).toExponential().split("e");
57
+ const digits = mant.replace(".", "");
58
+ const kk = Number(ex) + 1;
59
+ const pad = kk - digits.length;
60
+ let out;
61
+ if (pad >= 0 && kk <= 16) out = `${digits}${"0".repeat(pad)}.0`;
62
+ else if (kk > 0 && kk <= 16) out = `${digits.slice(0, kk)}.${digits.slice(kk)}`;
63
+ else if (kk > -5 && kk <= 0) out = `0.${"0".repeat(-kk)}${digits}`;
64
+ else {
65
+ const e = kk - 1 > 0 ? `e+${kk - 1}` : `e${kk - 1}`;
66
+ out = digits.length === 1 ? `${digits}${e}` : `${digits.slice(0, 1)}.${digits.slice(1)}${e}`;
67
+ }
68
+ return n < 0 ? `-${out}` : out;
69
+ }
70
+ function numberText(n) {
71
+ if (!Number.isFinite(n)) return String(n);
72
+ if (Object.is(n, -0)) return "-0.0";
73
+ if (Number.isInteger(n) && n >= -(2 ** 63) && n < 2 ** 64) return BigInt(n).toString();
74
+ return ryu(n);
75
+ }
76
+ var ISO = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/;
77
+ var STAMP = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$/;
78
+ function asWritten(v, kind) {
79
+ const m = ISO.exec(v);
80
+ const cut = (n) => m && m[0].length >= n ? v.slice(0, n) : v;
81
+ if (kind === "date") return cut(10);
82
+ if (kind === "datetime") return cut(16).split("T").join(" ");
83
+ const t = m?.[1];
84
+ return t !== void 0 ? t.slice(1) : v;
85
+ }
86
+ var zones = /* @__PURE__ */ new Map();
87
+ function zoneClock(zone) {
88
+ let f = zones.get(zone);
89
+ if (f === void 0) {
90
+ try {
91
+ f = new Intl.DateTimeFormat("en-US", {
92
+ timeZone: zone,
93
+ hourCycle: "h23",
94
+ year: "numeric",
95
+ month: "numeric",
96
+ day: "numeric",
97
+ hour: "numeric",
98
+ minute: "numeric",
99
+ second: "numeric"
100
+ });
101
+ } catch {
102
+ f = null;
103
+ }
104
+ zones.set(zone, f);
105
+ }
106
+ return f;
107
+ }
108
+ function supportsTimeZone(zone) {
109
+ return zoneClock(zone) !== null;
110
+ }
111
+ function offsetSeconds(clock, utcMs) {
112
+ const p = {};
113
+ for (const part of clock.formatToParts(new Date(utcMs))) if (part.type !== "literal") p[part.type] = Number(part.value);
114
+ const wall = Date.UTC(p.year, p.month - 1, p.day, p.hour % 24, p.minute, p.second);
115
+ return (wall - utcMs) / 1e3;
116
+ }
117
+ var two = (n) => String(n).padStart(2, "0");
118
+ function inZone(v, kind, zone) {
119
+ const clock = zoneClock(zone);
120
+ const m = STAMP.exec(v);
121
+ if (clock === null || m === null) return void 0;
122
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i]));
123
+ const stamp = Date.UTC(year, month - 1, day, hour, minute, second);
124
+ const check = new Date(stamp);
125
+ if (check.getUTCFullYear() !== year || check.getUTCMonth() + 1 !== month || check.getUTCDate() !== day || hour > 23 || minute > 59 || second > 59) return void 0;
126
+ const zoneText = m[7];
127
+ let shift = 0;
128
+ if (zoneText !== "Z") {
129
+ const [oh, om] = [Number(zoneText.slice(1, 3)), Number(zoneText.slice(4, 6))];
130
+ if (oh > 23 || om > 59) return void 0;
131
+ shift = (zoneText.startsWith("-") ? -1 : 1) * (oh * 3600 + om * 60);
132
+ }
133
+ const utcMs = stamp - shift * 1e3;
134
+ const utcYear = new Date(utcMs).getUTCFullYear();
135
+ if (utcYear < 1970 || utcYear > 2037) return void 0;
136
+ const local = new Date(utcMs + offsetSeconds(clock, utcMs) * 1e3);
137
+ const ymd = `${String(local.getUTCFullYear()).padStart(4, "0")}-${two(local.getUTCMonth() + 1)}-${two(local.getUTCDate())}`;
138
+ const hm = `${two(local.getUTCHours())}:${two(local.getUTCMinutes())}`;
139
+ return kind === "date" ? ymd : kind === "time" ? hm : `${ymd} ${hm}`;
140
+ }
141
+ function formatTime(v, kind, zone) {
142
+ return (zone ? inZone(v, kind, zone) : void 0) ?? asWritten(v, kind);
143
+ }
144
+
145
+ // src/vectors.ts
146
+ function runVectors(render2, vectors) {
147
+ const failures = [];
148
+ for (const c of vectors.cases) {
149
+ const expected = JSON.stringify(c.display);
150
+ let actual;
151
+ try {
152
+ actual = JSON.stringify(render2(c.event, c.theme, c.options));
153
+ } catch (e) {
154
+ actual = `threw ${String(e)}`;
155
+ }
156
+ if (actual !== expected) failures.push({ name: c.name, expected, actual });
157
+ }
158
+ return failures;
159
+ }
160
+
161
+ // src/index.ts
162
+ var MAX_VALUE_CHARS = 200;
163
+ var HOLE = /\{([A-Za-z0-9_.\-]+)((?:\|[a-z]+(?::[A-Za-z0-9_ .\-]*)?)*)\}/g;
164
+ var NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
165
+ var CONTROL = /^[\u0000-\u001f\u007f-\u009f]$/;
166
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
167
+ var has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
168
+ function actionParts(action) {
169
+ const segs = action.split(".");
170
+ return [segs[0] ?? "", (segs[segs.length - 1] ?? "").split("_").join(" ")];
171
+ }
172
+ function text(v) {
173
+ if (typeof v === "string") return v;
174
+ if (typeof v === "number") return numberText(v);
175
+ if (typeof v === "boolean") return String(v);
176
+ return void 0;
177
+ }
178
+ function lookup(e, path) {
179
+ if (path === "action.verb" || path === "action.noun") {
180
+ const a = isObj(e) ? e.action : void 0;
181
+ if (typeof a !== "string") return void 0;
182
+ const [noun, verb] = actionParts(a);
183
+ return path === "action.noun" ? noun : verb;
184
+ }
185
+ if (path.startsWith("changes.")) {
186
+ const rest = path.slice("changes.".length);
187
+ const list = isObj(e) ? e.changes : void 0;
188
+ if (!Array.isArray(list)) return void 0;
189
+ if (rest === "count") return String(list.length);
190
+ const i = rest.lastIndexOf(".");
191
+ const side = rest.slice(i + 1);
192
+ if (i >= 0 && (side === "old" || side === "new")) {
193
+ const field = rest.slice(0, i);
194
+ const c = list.find((c2) => isObj(c2) && c2.field === field);
195
+ return isObj(c) && has(c, side) ? text(c[side]) : void 0;
196
+ }
197
+ }
198
+ let cur = e;
199
+ for (const k of path.split(".")) {
200
+ if (Array.isArray(cur)) {
201
+ if (!/^\d+$/.test(k)) return void 0;
202
+ cur = cur[Number(k)];
203
+ } else if (isObj(cur) && has(cur, k)) {
204
+ cur = cur[k];
205
+ } else {
206
+ return void 0;
207
+ }
208
+ }
209
+ return text(cur);
210
+ }
211
+ function clean(v) {
212
+ return Array.from(v).slice(0, MAX_VALUE_CHARS).map((c) => CONTROL.test(c) ? " " : c).join("");
213
+ }
214
+ function parseNumber(s) {
215
+ if (!NUMBER.test(s)) return void 0;
216
+ const n = Number(s);
217
+ return Number.isFinite(n) ? n : void 0;
218
+ }
219
+ function group(s) {
220
+ const neg = s.startsWith("-");
221
+ const body = neg ? s.slice(1) : s;
222
+ const dot = body.indexOf(".");
223
+ const int = dot >= 0 ? body.slice(0, dot) : body;
224
+ const frac = dot >= 0 ? body.slice(dot + 1) : "";
225
+ let out = "";
226
+ for (let i = 0; i < int.length; i++) {
227
+ if (i > 0 && (int.length - i) % 3 === 0) out += ",";
228
+ out += int[i];
229
+ }
230
+ return `${neg ? "-" : ""}${out}${frac === "" ? "" : "."}${frac}`;
231
+ }
232
+ function money(v, cur) {
233
+ const n = parseNumber(v);
234
+ if (n === void 0) return v;
235
+ const code = cur.trim().toUpperCase();
236
+ const [sym, dec] = code === "USD" ? ["$", 2] : code === "EUR" ? ["\u20AC", 2] : code === "GBP" ? ["\xA3", 2] : code === "JPY" ? ["\xA5", 0] : ["", 2];
237
+ const g = group(fixed(Math.abs(n), dec));
238
+ const body = sym !== "" ? `${sym}${g}` : code === "" ? g : `${g} ${code}`;
239
+ return n < 0 ? `-${body}` : body;
240
+ }
241
+ function count(v) {
242
+ const n = parseNumber(v);
243
+ if (n === void 0) return v;
244
+ return group(`${n < 0 || Object.is(n, -0) ? "-" : ""}${fixed(Math.abs(n), 0)}`);
245
+ }
246
+ function interpolate(tpl, event, zone) {
247
+ return tpl.replace(HOLE, (_m, path, fmts) => {
248
+ let v = lookup(event, path) ?? "";
249
+ for (const f of fmts.split("|")) {
250
+ if (f === "") continue;
251
+ const c = f.indexOf(":");
252
+ const name = c >= 0 ? f.slice(0, c) : f;
253
+ const arg = c >= 0 ? f.slice(c + 1) : "";
254
+ if (name === "money") v = money(v, arg);
255
+ else if (name === "count") v = count(v);
256
+ else if (name === "date" || name === "datetime" || name === "time") v = formatTime(v, name, zone);
257
+ }
258
+ return clean(v);
259
+ });
260
+ }
261
+ function templateFor(actions, action) {
262
+ if (has(actions, action)) return actions[action];
263
+ let best;
264
+ let bestLen = -1;
265
+ for (const k of Object.keys(actions)) {
266
+ if (!k.endsWith("*")) continue;
267
+ const stem = k.slice(0, -1);
268
+ if (action.startsWith(stem) && stem.length > bestLen) {
269
+ best = actions[k];
270
+ bestLen = stem.length;
271
+ }
272
+ }
273
+ return best;
274
+ }
275
+ function fallbackTitle(e) {
276
+ const s = (p) => {
277
+ const v = lookup(e, p);
278
+ return v === void 0 || v === "" ? void 0 : v;
279
+ };
280
+ return [s("actor.name") ?? s("actor.id"), s("action"), s("target.name") ?? s("target.id")].filter((x) => x !== void 0).join(" ");
281
+ }
282
+ function tags(locale) {
283
+ return locale == null ? [] : [locale, locale.split("-")[0] ?? locale];
284
+ }
285
+ function renderTemplate(tpl, event, locale, zone) {
286
+ if (!tpl) return { title: fallbackTitle(event) };
287
+ const chain = [];
288
+ for (const k of tags(locale)) if (tpl.locales && has(tpl.locales, k)) chain.push(tpl.locales[k]);
289
+ chain.push(tpl);
290
+ const outcome = isObj(event) && typeof event.outcome === "string" ? event.outcome : void 0;
291
+ let label;
292
+ for (const l of chain) {
293
+ const v = (outcome === "failure" ? l.label_failure : outcome === "denied" ? l.label_denied : void 0) ?? l.label;
294
+ if (v != null) {
295
+ label = v;
296
+ break;
297
+ }
298
+ }
299
+ const out = { title: label === void 0 ? fallbackTitle(event) : interpolate(label, event, zone) };
300
+ const subtitle = chain.find((l) => l.subtitle != null)?.subtitle;
301
+ if (subtitle != null) out.subtitle = interpolate(subtitle, event, zone);
302
+ const fields = (chain.find((l) => l.fields != null)?.fields ?? []).map((f) => ({
303
+ label: interpolate(f.label, event, zone),
304
+ value: interpolate(f.value, event, zone)
305
+ }));
306
+ if (fields.length > 0) out.fields = fields;
307
+ return out;
308
+ }
309
+ function failureReason(theme, event, locale, zone) {
310
+ if (!isObj(event) || event.outcome !== "failure") return void 0;
311
+ const path = theme.failureReasonPath ?? theme.failure_reason_path;
312
+ const reasons = theme.failureReasons ?? theme.failure_reasons;
313
+ if (reasons == null) return void 0;
314
+ const flag = (v) => v === true;
315
+ const abandoned = flag(event.abandoned) || isObj(event.ext) && flag(event.ext.abandoned);
316
+ let code;
317
+ if (abandoned && has(reasons, "abandoned")) code = "abandoned";
318
+ else if (path != null) code = lookup(event, path);
319
+ if (code === void 0 || code === "" || !has(reasons, code)) return void 0;
320
+ const r = reasons[code];
321
+ const chain = [];
322
+ for (const k of tags(locale)) if (r.locales && has(r.locales, k)) chain.push(r.locales[k]);
323
+ const t = chain.find((l) => l.text != null)?.text ?? r.text;
324
+ const a = chain.find((l) => l.action != null)?.action ?? r.action;
325
+ const out = { code, text: interpolate(t, event, zone) };
326
+ if (a != null) out.action = { label: interpolate(a.label, event, zone), url: a.url };
327
+ return out;
328
+ }
329
+ function render(event, theme, options = {}) {
330
+ const action = isObj(event) && typeof event.action === "string" ? event.action : void 0;
331
+ const found = action !== void 0 && theme.actions ? templateFor(theme.actions, action) : void 0;
332
+ const out = renderTemplate(found ?? theme.fallbackTemplate ?? theme.fallback_template ?? void 0, event, options.locale, options.timeZone);
333
+ const reason = failureReason(theme, event, options.locale, options.timeZone);
334
+ if (reason) out.failure_reason = reason;
335
+ return out;
336
+ }
@@ -0,0 +1,68 @@
1
+ export { supportsTimeZone } from './format.cjs';
2
+ export { runVectors, type VectorCase, type VectorFailure, type VectorFile } from './vectors.cjs';
3
+ export interface DisplayField {
4
+ label: string;
5
+ value: string;
6
+ }
7
+ export interface ReasonAction {
8
+ label: string;
9
+ url: string;
10
+ }
11
+ export interface ActionLocale {
12
+ label?: string | null;
13
+ label_failure?: string | null;
14
+ label_denied?: string | null;
15
+ subtitle?: string | null;
16
+ fields?: DisplayField[] | null;
17
+ }
18
+ export interface ActionTemplate extends ActionLocale {
19
+ locales?: Record<string, ActionLocale> | null;
20
+ icon?: string | null;
21
+ tone?: string | null;
22
+ }
23
+ export interface ReasonLocale {
24
+ text?: string | null;
25
+ action?: ReasonAction | null;
26
+ }
27
+ export interface FailureReason {
28
+ text: string;
29
+ action?: ReasonAction | null;
30
+ locales?: Record<string, ReasonLocale> | null;
31
+ }
32
+ /** The parts of a theme the renderer reads (the rest of the theme is ignored). The snake_case spellings are accepted like the API does. */
33
+ export interface RenderTheme {
34
+ actions?: Record<string, ActionTemplate> | null;
35
+ fallbackTemplate?: ActionTemplate | null;
36
+ fallback_template?: ActionTemplate | null;
37
+ failureReasonPath?: string | null;
38
+ failure_reason_path?: string | null;
39
+ failureReasons?: Record<string, FailureReason> | null;
40
+ failure_reasons?: Record<string, FailureReason> | null;
41
+ }
42
+ export interface FailureReasonDisplay {
43
+ code: string;
44
+ text: string;
45
+ action?: ReasonAction;
46
+ }
47
+ /** The `display` object of the API. */
48
+ export interface Display {
49
+ title: string;
50
+ subtitle?: string;
51
+ fields?: DisplayField[];
52
+ failure_reason?: FailureReasonDisplay;
53
+ }
54
+ export interface RenderOptions {
55
+ /** Tag such as `pt-BR`; `pt-BR`, then `pt`, then the template's own copy. */
56
+ locale?: string | null;
57
+ /**
58
+ * IANA zone (`America/New_York`) the `date`, `time` and `datetime` formatters print an RFC 3339 timestamp in, as the API does for a session
59
+ * minted with `time_zone`. Without it, with a zone `supportsTimeZone` refuses, or for text that is not such a timestamp, they print the text as written.
60
+ */
61
+ timeZone?: string | null;
62
+ }
63
+ /**
64
+ * Render `event` (as the API returns it) with `theme` (as the API returns it): the template of its
65
+ * action (exact key, longest prefix key, then `fallbackTemplate`), outcome and locale variants,
66
+ * and `failure_reason`. Pure; the result serializes like the API's `display`.
67
+ */
68
+ export declare function render(event: unknown, theme: RenderTheme, options?: RenderOptions): Display;
@@ -0,0 +1,68 @@
1
+ export { supportsTimeZone } from './format.js';
2
+ export { runVectors, type VectorCase, type VectorFailure, type VectorFile } from './vectors.js';
3
+ export interface DisplayField {
4
+ label: string;
5
+ value: string;
6
+ }
7
+ export interface ReasonAction {
8
+ label: string;
9
+ url: string;
10
+ }
11
+ export interface ActionLocale {
12
+ label?: string | null;
13
+ label_failure?: string | null;
14
+ label_denied?: string | null;
15
+ subtitle?: string | null;
16
+ fields?: DisplayField[] | null;
17
+ }
18
+ export interface ActionTemplate extends ActionLocale {
19
+ locales?: Record<string, ActionLocale> | null;
20
+ icon?: string | null;
21
+ tone?: string | null;
22
+ }
23
+ export interface ReasonLocale {
24
+ text?: string | null;
25
+ action?: ReasonAction | null;
26
+ }
27
+ export interface FailureReason {
28
+ text: string;
29
+ action?: ReasonAction | null;
30
+ locales?: Record<string, ReasonLocale> | null;
31
+ }
32
+ /** The parts of a theme the renderer reads (the rest of the theme is ignored). The snake_case spellings are accepted like the API does. */
33
+ export interface RenderTheme {
34
+ actions?: Record<string, ActionTemplate> | null;
35
+ fallbackTemplate?: ActionTemplate | null;
36
+ fallback_template?: ActionTemplate | null;
37
+ failureReasonPath?: string | null;
38
+ failure_reason_path?: string | null;
39
+ failureReasons?: Record<string, FailureReason> | null;
40
+ failure_reasons?: Record<string, FailureReason> | null;
41
+ }
42
+ export interface FailureReasonDisplay {
43
+ code: string;
44
+ text: string;
45
+ action?: ReasonAction;
46
+ }
47
+ /** The `display` object of the API. */
48
+ export interface Display {
49
+ title: string;
50
+ subtitle?: string;
51
+ fields?: DisplayField[];
52
+ failure_reason?: FailureReasonDisplay;
53
+ }
54
+ export interface RenderOptions {
55
+ /** Tag such as `pt-BR`; `pt-BR`, then `pt`, then the template's own copy. */
56
+ locale?: string | null;
57
+ /**
58
+ * IANA zone (`America/New_York`) the `date`, `time` and `datetime` formatters print an RFC 3339 timestamp in, as the API does for a session
59
+ * minted with `time_zone`. Without it, with a zone `supportsTimeZone` refuses, or for text that is not such a timestamp, they print the text as written.
60
+ */
61
+ timeZone?: string | null;
62
+ }
63
+ /**
64
+ * Render `event` (as the API returns it) with `theme` (as the API returns it): the template of its
65
+ * action (exact key, longest prefix key, then `fallbackTemplate`), outcome and locale variants,
66
+ * and `failure_reason`. Pure; the result serializes like the API's `display`.
67
+ */
68
+ export declare function render(event: unknown, theme: RenderTheme, options?: RenderOptions): Display;