@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.js ADDED
@@ -0,0 +1,313 @@
1
+ // src/format.ts
2
+ function decompose(n) {
3
+ const view = new DataView(new ArrayBuffer(8));
4
+ view.setFloat64(0, n);
5
+ const hi = view.getUint32(0);
6
+ const mantissa = BigInt(hi & 1048575) << 32n | BigInt(view.getUint32(4));
7
+ const biased = hi >>> 20 & 2047;
8
+ return biased === 0 ? [mantissa, -1074] : [mantissa | 1n << 52n, biased - 1075];
9
+ }
10
+ function fixed(n, dec) {
11
+ const [m, e] = decompose(n);
12
+ const scale = 10n ** BigInt(dec);
13
+ let q;
14
+ if (e >= 0) {
15
+ q = (m << BigInt(e)) * scale;
16
+ } else {
17
+ const num = m * scale;
18
+ const den = 1n << BigInt(-e);
19
+ q = num / den;
20
+ const twice = num % den * 2n;
21
+ if (twice > den || twice === den && (q & 1n) === 1n) q += 1n;
22
+ }
23
+ const s = q.toString().padStart(dec + 1, "0");
24
+ return dec > 0 ? `${s.slice(0, s.length - dec)}.${s.slice(s.length - dec)}` : s;
25
+ }
26
+ function ryu(n) {
27
+ if (n === 0) return Object.is(n, -0) ? "-0.0" : "0.0";
28
+ const [mant, ex] = Math.abs(n).toExponential().split("e");
29
+ const digits = mant.replace(".", "");
30
+ const kk = Number(ex) + 1;
31
+ const pad = kk - digits.length;
32
+ let out;
33
+ if (pad >= 0 && kk <= 16) out = `${digits}${"0".repeat(pad)}.0`;
34
+ else if (kk > 0 && kk <= 16) out = `${digits.slice(0, kk)}.${digits.slice(kk)}`;
35
+ else if (kk > -5 && kk <= 0) out = `0.${"0".repeat(-kk)}${digits}`;
36
+ else {
37
+ const e = kk - 1 > 0 ? `e+${kk - 1}` : `e${kk - 1}`;
38
+ out = digits.length === 1 ? `${digits}${e}` : `${digits.slice(0, 1)}.${digits.slice(1)}${e}`;
39
+ }
40
+ return n < 0 ? `-${out}` : out;
41
+ }
42
+ function numberText(n) {
43
+ if (!Number.isFinite(n)) return String(n);
44
+ if (Object.is(n, -0)) return "-0.0";
45
+ if (Number.isInteger(n) && n >= -(2 ** 63) && n < 2 ** 64) return BigInt(n).toString();
46
+ return ryu(n);
47
+ }
48
+ var ISO = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2})?/;
49
+ 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})$/;
50
+ function asWritten(v, kind) {
51
+ const m = ISO.exec(v);
52
+ const cut = (n) => m && m[0].length >= n ? v.slice(0, n) : v;
53
+ if (kind === "date") return cut(10);
54
+ if (kind === "datetime") return cut(16).split("T").join(" ");
55
+ const t = m?.[1];
56
+ return t !== void 0 ? t.slice(1) : v;
57
+ }
58
+ var zones = /* @__PURE__ */ new Map();
59
+ function zoneClock(zone) {
60
+ let f = zones.get(zone);
61
+ if (f === void 0) {
62
+ try {
63
+ f = new Intl.DateTimeFormat("en-US", {
64
+ timeZone: zone,
65
+ hourCycle: "h23",
66
+ year: "numeric",
67
+ month: "numeric",
68
+ day: "numeric",
69
+ hour: "numeric",
70
+ minute: "numeric",
71
+ second: "numeric"
72
+ });
73
+ } catch {
74
+ f = null;
75
+ }
76
+ zones.set(zone, f);
77
+ }
78
+ return f;
79
+ }
80
+ function supportsTimeZone(zone) {
81
+ return zoneClock(zone) !== null;
82
+ }
83
+ function offsetSeconds(clock, utcMs) {
84
+ const p = {};
85
+ for (const part of clock.formatToParts(new Date(utcMs))) if (part.type !== "literal") p[part.type] = Number(part.value);
86
+ const wall = Date.UTC(p.year, p.month - 1, p.day, p.hour % 24, p.minute, p.second);
87
+ return (wall - utcMs) / 1e3;
88
+ }
89
+ var two = (n) => String(n).padStart(2, "0");
90
+ function inZone(v, kind, zone) {
91
+ const clock = zoneClock(zone);
92
+ const m = STAMP.exec(v);
93
+ if (clock === null || m === null) return void 0;
94
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = [1, 2, 3, 4, 5, 6].map((i) => Number(m[i]));
95
+ const stamp = Date.UTC(year, month - 1, day, hour, minute, second);
96
+ const check = new Date(stamp);
97
+ if (check.getUTCFullYear() !== year || check.getUTCMonth() + 1 !== month || check.getUTCDate() !== day || hour > 23 || minute > 59 || second > 59) return void 0;
98
+ const zoneText = m[7];
99
+ let shift = 0;
100
+ if (zoneText !== "Z") {
101
+ const [oh, om] = [Number(zoneText.slice(1, 3)), Number(zoneText.slice(4, 6))];
102
+ if (oh > 23 || om > 59) return void 0;
103
+ shift = (zoneText.startsWith("-") ? -1 : 1) * (oh * 3600 + om * 60);
104
+ }
105
+ const utcMs = stamp - shift * 1e3;
106
+ const utcYear = new Date(utcMs).getUTCFullYear();
107
+ if (utcYear < 1970 || utcYear > 2037) return void 0;
108
+ const local = new Date(utcMs + offsetSeconds(clock, utcMs) * 1e3);
109
+ const ymd = `${String(local.getUTCFullYear()).padStart(4, "0")}-${two(local.getUTCMonth() + 1)}-${two(local.getUTCDate())}`;
110
+ const hm = `${two(local.getUTCHours())}:${two(local.getUTCMinutes())}`;
111
+ return kind === "date" ? ymd : kind === "time" ? hm : `${ymd} ${hm}`;
112
+ }
113
+ function formatTime(v, kind, zone) {
114
+ return (zone ? inZone(v, kind, zone) : void 0) ?? asWritten(v, kind);
115
+ }
116
+
117
+ // src/vectors.ts
118
+ function runVectors(render2, vectors) {
119
+ const failures = [];
120
+ for (const c of vectors.cases) {
121
+ const expected = JSON.stringify(c.display);
122
+ let actual;
123
+ try {
124
+ actual = JSON.stringify(render2(c.event, c.theme, c.options));
125
+ } catch (e) {
126
+ actual = `threw ${String(e)}`;
127
+ }
128
+ if (actual !== expected) failures.push({ name: c.name, expected, actual });
129
+ }
130
+ return failures;
131
+ }
132
+
133
+ // src/index.ts
134
+ var MAX_VALUE_CHARS = 200;
135
+ var HOLE = /\{([A-Za-z0-9_.\-]+)((?:\|[a-z]+(?::[A-Za-z0-9_ .\-]*)?)*)\}/g;
136
+ var NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
137
+ var CONTROL = /^[\u0000-\u001f\u007f-\u009f]$/;
138
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
139
+ var has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
140
+ function actionParts(action) {
141
+ const segs = action.split(".");
142
+ return [segs[0] ?? "", (segs[segs.length - 1] ?? "").split("_").join(" ")];
143
+ }
144
+ function text(v) {
145
+ if (typeof v === "string") return v;
146
+ if (typeof v === "number") return numberText(v);
147
+ if (typeof v === "boolean") return String(v);
148
+ return void 0;
149
+ }
150
+ function lookup(e, path) {
151
+ if (path === "action.verb" || path === "action.noun") {
152
+ const a = isObj(e) ? e.action : void 0;
153
+ if (typeof a !== "string") return void 0;
154
+ const [noun, verb] = actionParts(a);
155
+ return path === "action.noun" ? noun : verb;
156
+ }
157
+ if (path.startsWith("changes.")) {
158
+ const rest = path.slice("changes.".length);
159
+ const list = isObj(e) ? e.changes : void 0;
160
+ if (!Array.isArray(list)) return void 0;
161
+ if (rest === "count") return String(list.length);
162
+ const i = rest.lastIndexOf(".");
163
+ const side = rest.slice(i + 1);
164
+ if (i >= 0 && (side === "old" || side === "new")) {
165
+ const field = rest.slice(0, i);
166
+ const c = list.find((c2) => isObj(c2) && c2.field === field);
167
+ return isObj(c) && has(c, side) ? text(c[side]) : void 0;
168
+ }
169
+ }
170
+ let cur = e;
171
+ for (const k of path.split(".")) {
172
+ if (Array.isArray(cur)) {
173
+ if (!/^\d+$/.test(k)) return void 0;
174
+ cur = cur[Number(k)];
175
+ } else if (isObj(cur) && has(cur, k)) {
176
+ cur = cur[k];
177
+ } else {
178
+ return void 0;
179
+ }
180
+ }
181
+ return text(cur);
182
+ }
183
+ function clean(v) {
184
+ return Array.from(v).slice(0, MAX_VALUE_CHARS).map((c) => CONTROL.test(c) ? " " : c).join("");
185
+ }
186
+ function parseNumber(s) {
187
+ if (!NUMBER.test(s)) return void 0;
188
+ const n = Number(s);
189
+ return Number.isFinite(n) ? n : void 0;
190
+ }
191
+ function group(s) {
192
+ const neg = s.startsWith("-");
193
+ const body = neg ? s.slice(1) : s;
194
+ const dot = body.indexOf(".");
195
+ const int = dot >= 0 ? body.slice(0, dot) : body;
196
+ const frac = dot >= 0 ? body.slice(dot + 1) : "";
197
+ let out = "";
198
+ for (let i = 0; i < int.length; i++) {
199
+ if (i > 0 && (int.length - i) % 3 === 0) out += ",";
200
+ out += int[i];
201
+ }
202
+ return `${neg ? "-" : ""}${out}${frac === "" ? "" : "."}${frac}`;
203
+ }
204
+ function money(v, cur) {
205
+ const n = parseNumber(v);
206
+ if (n === void 0) return v;
207
+ const code = cur.trim().toUpperCase();
208
+ const [sym, dec] = code === "USD" ? ["$", 2] : code === "EUR" ? ["\u20AC", 2] : code === "GBP" ? ["\xA3", 2] : code === "JPY" ? ["\xA5", 0] : ["", 2];
209
+ const g = group(fixed(Math.abs(n), dec));
210
+ const body = sym !== "" ? `${sym}${g}` : code === "" ? g : `${g} ${code}`;
211
+ return n < 0 ? `-${body}` : body;
212
+ }
213
+ function count(v) {
214
+ const n = parseNumber(v);
215
+ if (n === void 0) return v;
216
+ return group(`${n < 0 || Object.is(n, -0) ? "-" : ""}${fixed(Math.abs(n), 0)}`);
217
+ }
218
+ function interpolate(tpl, event, zone) {
219
+ return tpl.replace(HOLE, (_m, path, fmts) => {
220
+ let v = lookup(event, path) ?? "";
221
+ for (const f of fmts.split("|")) {
222
+ if (f === "") continue;
223
+ const c = f.indexOf(":");
224
+ const name = c >= 0 ? f.slice(0, c) : f;
225
+ const arg = c >= 0 ? f.slice(c + 1) : "";
226
+ if (name === "money") v = money(v, arg);
227
+ else if (name === "count") v = count(v);
228
+ else if (name === "date" || name === "datetime" || name === "time") v = formatTime(v, name, zone);
229
+ }
230
+ return clean(v);
231
+ });
232
+ }
233
+ function templateFor(actions, action) {
234
+ if (has(actions, action)) return actions[action];
235
+ let best;
236
+ let bestLen = -1;
237
+ for (const k of Object.keys(actions)) {
238
+ if (!k.endsWith("*")) continue;
239
+ const stem = k.slice(0, -1);
240
+ if (action.startsWith(stem) && stem.length > bestLen) {
241
+ best = actions[k];
242
+ bestLen = stem.length;
243
+ }
244
+ }
245
+ return best;
246
+ }
247
+ function fallbackTitle(e) {
248
+ const s = (p) => {
249
+ const v = lookup(e, p);
250
+ return v === void 0 || v === "" ? void 0 : v;
251
+ };
252
+ return [s("actor.name") ?? s("actor.id"), s("action"), s("target.name") ?? s("target.id")].filter((x) => x !== void 0).join(" ");
253
+ }
254
+ function tags(locale) {
255
+ return locale == null ? [] : [locale, locale.split("-")[0] ?? locale];
256
+ }
257
+ function renderTemplate(tpl, event, locale, zone) {
258
+ if (!tpl) return { title: fallbackTitle(event) };
259
+ const chain = [];
260
+ for (const k of tags(locale)) if (tpl.locales && has(tpl.locales, k)) chain.push(tpl.locales[k]);
261
+ chain.push(tpl);
262
+ const outcome = isObj(event) && typeof event.outcome === "string" ? event.outcome : void 0;
263
+ let label;
264
+ for (const l of chain) {
265
+ const v = (outcome === "failure" ? l.label_failure : outcome === "denied" ? l.label_denied : void 0) ?? l.label;
266
+ if (v != null) {
267
+ label = v;
268
+ break;
269
+ }
270
+ }
271
+ const out = { title: label === void 0 ? fallbackTitle(event) : interpolate(label, event, zone) };
272
+ const subtitle = chain.find((l) => l.subtitle != null)?.subtitle;
273
+ if (subtitle != null) out.subtitle = interpolate(subtitle, event, zone);
274
+ const fields = (chain.find((l) => l.fields != null)?.fields ?? []).map((f) => ({
275
+ label: interpolate(f.label, event, zone),
276
+ value: interpolate(f.value, event, zone)
277
+ }));
278
+ if (fields.length > 0) out.fields = fields;
279
+ return out;
280
+ }
281
+ function failureReason(theme, event, locale, zone) {
282
+ if (!isObj(event) || event.outcome !== "failure") return void 0;
283
+ const path = theme.failureReasonPath ?? theme.failure_reason_path;
284
+ const reasons = theme.failureReasons ?? theme.failure_reasons;
285
+ if (reasons == null) return void 0;
286
+ const flag = (v) => v === true;
287
+ const abandoned = flag(event.abandoned) || isObj(event.ext) && flag(event.ext.abandoned);
288
+ let code;
289
+ if (abandoned && has(reasons, "abandoned")) code = "abandoned";
290
+ else if (path != null) code = lookup(event, path);
291
+ if (code === void 0 || code === "" || !has(reasons, code)) return void 0;
292
+ const r = reasons[code];
293
+ const chain = [];
294
+ for (const k of tags(locale)) if (r.locales && has(r.locales, k)) chain.push(r.locales[k]);
295
+ const t = chain.find((l) => l.text != null)?.text ?? r.text;
296
+ const a = chain.find((l) => l.action != null)?.action ?? r.action;
297
+ const out = { code, text: interpolate(t, event, zone) };
298
+ if (a != null) out.action = { label: interpolate(a.label, event, zone), url: a.url };
299
+ return out;
300
+ }
301
+ function render(event, theme, options = {}) {
302
+ const action = isObj(event) && typeof event.action === "string" ? event.action : void 0;
303
+ const found = action !== void 0 && theme.actions ? templateFor(theme.actions, action) : void 0;
304
+ const out = renderTemplate(found ?? theme.fallbackTemplate ?? theme.fallback_template ?? void 0, event, options.locale, options.timeZone);
305
+ const reason = failureReason(theme, event, options.locale, options.timeZone);
306
+ if (reason) out.failure_reason = reason;
307
+ return out;
308
+ }
309
+ export {
310
+ render,
311
+ runVectors,
312
+ supportsTimeZone
313
+ };
@@ -0,0 +1,33 @@
1
+ /** One case: render `event` with `theme` and `options` and the result must be exactly `display`. */
2
+ export interface VectorCase {
3
+ name: string;
4
+ event: unknown;
5
+ theme: unknown;
6
+ options: {
7
+ locale?: string | null;
8
+ timeZone?: string | null;
9
+ };
10
+ /** The `display` object of the API: compared as JSON text, so key order and omitted keys count. */
11
+ display: unknown;
12
+ /** `true` when the Rust renderer is known to produce `display` (a CI run passed on it); `false` when it was traced by hand. */
13
+ verified: boolean;
14
+ }
15
+ /** The shape of `vectors.json`. */
16
+ export interface VectorFile {
17
+ about?: string;
18
+ format?: string;
19
+ cases: VectorCase[];
20
+ }
21
+ export interface VectorFailure {
22
+ name: string;
23
+ expected: string;
24
+ actual: string;
25
+ }
26
+ /**
27
+ * Run `vectors` (the parsed `vectors.json`) through `render` and return the cases that differ: `[]` means the renderer conforms.
28
+ * A renderer that throws fails its case with the error text as `actual`.
29
+ */
30
+ export declare function runVectors(render: (event: unknown, theme: never, options?: {
31
+ locale?: string | null;
32
+ timeZone?: string | null;
33
+ }) => unknown, vectors: VectorFile): VectorFailure[];
@@ -0,0 +1,33 @@
1
+ /** One case: render `event` with `theme` and `options` and the result must be exactly `display`. */
2
+ export interface VectorCase {
3
+ name: string;
4
+ event: unknown;
5
+ theme: unknown;
6
+ options: {
7
+ locale?: string | null;
8
+ timeZone?: string | null;
9
+ };
10
+ /** The `display` object of the API: compared as JSON text, so key order and omitted keys count. */
11
+ display: unknown;
12
+ /** `true` when the Rust renderer is known to produce `display` (a CI run passed on it); `false` when it was traced by hand. */
13
+ verified: boolean;
14
+ }
15
+ /** The shape of `vectors.json`. */
16
+ export interface VectorFile {
17
+ about?: string;
18
+ format?: string;
19
+ cases: VectorCase[];
20
+ }
21
+ export interface VectorFailure {
22
+ name: string;
23
+ expected: string;
24
+ actual: string;
25
+ }
26
+ /**
27
+ * Run `vectors` (the parsed `vectors.json`) through `render` and return the cases that differ: `[]` means the renderer conforms.
28
+ * A renderer that throws fails its case with the error text as `actual`.
29
+ */
30
+ export declare function runVectors(render: (event: unknown, theme: never, options?: {
31
+ locale?: string | null;
32
+ timeZone?: string | null;
33
+ }) => unknown, vectors: VectorFile): VectorFailure[];
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@watchtowerobservability/activity-render",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Watchtower activity renderer: the same display the API returns (templates, formatters, locales, failure reasons), client side, zero dependencies",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "default": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "./vectors.json": "./vectors.json"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "vectors.json",
27
+ "CHANGELOG.md"
28
+ ],
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "typecheck": "tsc --noEmit -p tsconfig.json",
35
+ "test": "vitest run",
36
+ "prepack": "node scripts/prepack.mjs"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "22.15.0",
40
+ "esbuild": "0.28.2",
41
+ "typescript": "5.7.2",
42
+ "vitest": "5.0.5"
43
+ },
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/watchtowerobservability/watchtower-activity-render.git"
47
+ },
48
+ "homepage": "https://github.com/watchtowerobservability/watchtower-activity-render#readme",
49
+ "publishConfig": {
50
+ "access": "public",
51
+ "registry": "https://registry.npmjs.org/"
52
+ }
53
+ }