@prezly/theme-kit-core 10.9.1 → 10.9.3

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,280 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createMetricsCollector = createMetricsCollector;
7
+ exports.getMetricsCollector = getMetricsCollector;
8
+ var _telemetry = require("./telemetry.cjs");
9
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
10
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
11
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
12
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
13
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
14
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
15
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
16
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
17
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
18
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
19
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
20
+ var BUCKETS = [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, Number.POSITIVE_INFINITY];
21
+ function choice(value, values, fallback) {
22
+ return typeof value === 'string' && values.includes(value) ? value : fallback;
23
+ }
24
+ class Family {
25
+ constructor(name, help) {
26
+ var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'counter';
27
+ this.name = name;
28
+ this.help = help;
29
+ this.type = type;
30
+ _defineProperty(this, "samples", new Map());
31
+ }
32
+ touch(labels) {
33
+ var key = JSON.stringify(labels);
34
+ var sample = this.samples.get(key);
35
+ if (!sample) {
36
+ sample = {
37
+ labels,
38
+ count: 0,
39
+ sum: 0,
40
+ buckets: this.type === 'histogram' ? BUCKETS.map(() => 0) : []
41
+ };
42
+ this.samples.set(key, sample);
43
+ }
44
+ return sample;
45
+ }
46
+ add(labels, seconds) {
47
+ var sample = this.touch(labels);
48
+ sample.count += 1;
49
+ if (this.type === 'histogram' && seconds !== undefined) {
50
+ sample.sum += seconds;
51
+ BUCKETS.forEach((bound, i) => {
52
+ if (seconds <= bound) sample.buckets[i] += 1;
53
+ });
54
+ }
55
+ }
56
+ render(runtime) {
57
+ var _this = this;
58
+ var name = "theme_kit_".concat(this.name);
59
+ var lines = ["# HELP ".concat(name, " ").concat(this.help), "# TYPE ".concat(name, " ").concat(this.type)];
60
+ var labels = values => "{".concat(Object.entries(_objectSpread({
61
+ runtime
62
+ }, values)).map(_ref => {
63
+ var _ref2 = _slicedToArray(_ref, 2),
64
+ k = _ref2[0],
65
+ v = _ref2[1];
66
+ return "".concat(k, "=\"").concat(v, "\"");
67
+ }).join(','), "}");
68
+ var _loop = function _loop(sample) {
69
+ if (_this.type === 'counter') lines.push("".concat(name).concat(labels(sample.labels), " ").concat(sample.count));else {
70
+ BUCKETS.forEach((bound, i) => {
71
+ lines.push("".concat(name, "_bucket").concat(labels(_objectSpread(_objectSpread({}, sample.labels), {}, {
72
+ le: bound === Number.POSITIVE_INFINITY ? '+Inf' : String(bound)
73
+ })), " ").concat(sample.buckets[i]));
74
+ });
75
+ lines.push("".concat(name, "_sum").concat(labels(sample.labels), " ").concat(sample.sum), "".concat(name, "_count").concat(labels(sample.labels), " ").concat(sample.count));
76
+ }
77
+ };
78
+ for (var sample of this.samples.values()) {
79
+ _loop(sample);
80
+ }
81
+ return lines;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * One collector per serving runtime. No sockets, timers, retained events or
87
+ * unbounded labels. Instantiate once and pass `observe` to every local adapter.
88
+ */
89
+ function createMetricsCollector() {
90
+ var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
91
+ _ref3$runtime = _ref3.runtime,
92
+ runtime = _ref3$runtime === void 0 ? 'unknown' : _ref3$runtime;
93
+ var families = {
94
+ requests: new Family('content_requests_total', 'Content method invocations, including coalesced callers.'),
95
+ hits: new Family('content_cache_hits_total', 'Cache entries accepted after version and source-scope validation.'),
96
+ misses: new Family('content_cache_misses_total', 'Cache lookups that require origin fallback.'),
97
+ cacheErrors: new Family('content_cache_errors_total', 'Observed cache read or write failures.'),
98
+ coalesced: new Family('content_coalesced_total', 'Callers joining an existing pending result.'),
99
+ rejected: new Family('content_rejected_total', 'Calls rejected by the pending-content limit.'),
100
+ origin: new Family('content_origin_total', 'Content method executions against the SDK, not physical HTTP requests.'),
101
+ originTime: new Family('content_origin_duration_seconds', 'Content origin execution duration including SDK decoding and aggregate work.', 'histogram'),
102
+ upstream: new Family('upstream_requests_total', 'Fetch attempts that reached a response-header or transport-error outcome.'),
103
+ upstreamTime: new Family('upstream_headers_duration_seconds', 'Fetch duration to headers or transport failure; excludes body consumption.', 'histogram'),
104
+ queue: new Family('fetch_queue_events_total', 'Bounded content transport admission and queue events.'),
105
+ queueTime: new Family('fetch_queue_wait_seconds', 'Completed admission wait; immediate admission has zero wait.', 'histogram'),
106
+ timeouts: new Family('fetch_timeouts_total', 'Content transport deadlines, including response-body consumption.'),
107
+ redis: new Family('redis_command_attempts_total', 'Redis command attempts by application-visible outcome, including deadlines.'),
108
+ redisTime: new Family('redis_command_duration_seconds', 'Redis command duration to application-visible completion.', 'histogram'),
109
+ redisUnavailable: new Family('redis_unavailable_total', 'Cache operations skipped because the shared Redis connection is not ready.')
110
+ };
111
+ var contents = new Set();
112
+ var routes = new Set();
113
+ var redis = new Set();
114
+ var contentLabels = (operation, source) => {
115
+ var labels = {
116
+ operation: choice(operation, _telemetry.CONTENT_OPERATIONS, 'other'),
117
+ source
118
+ };
119
+ var key = JSON.stringify(labels);
120
+ if (!contents.has(key)) {
121
+ contents.add(key);
122
+ for (var family of [families.requests, families.misses, families.coalesced, families.rejected, families.originTime]) family.touch(labels);
123
+ for (var layer of ['memory', 'redis', 'custom']) families.hits.touch(_objectSpread(_objectSpread({}, labels), {}, {
124
+ layer
125
+ }));
126
+ for (var action of ['read', 'write']) families.cacheErrors.touch(_objectSpread(_objectSpread({}, labels), {}, {
127
+ action
128
+ }));
129
+ for (var outcome of ['success', 'error']) families.origin.touch(_objectSpread(_objectSpread({}, labels), {}, {
130
+ outcome
131
+ }));
132
+ }
133
+ return labels;
134
+ };
135
+ var routeLabels = (route, source) => {
136
+ var labels = {
137
+ route: choice(route, _telemetry.UPSTREAM_ROUTES, 'other'),
138
+ source
139
+ };
140
+ var key = JSON.stringify(labels);
141
+ if (!routes.has(key)) {
142
+ routes.add(key);
143
+ for (var client of ['raw', 'content']) {
144
+ families.upstreamTime.touch(_objectSpread(_objectSpread({}, labels), {}, {
145
+ client
146
+ }));
147
+ for (var status of ['2xx', '3xx', '4xx', '5xx', 'other', 'error']) families.upstream.touch(_objectSpread(_objectSpread({}, labels), {}, {
148
+ client,
149
+ status_class: status
150
+ }));
151
+ }
152
+ for (var outcome of ['queued', 'accepted', 'full', 'wait_timeout', 'aborted']) families.queue.touch(_objectSpread(_objectSpread({}, labels), {}, {
153
+ outcome
154
+ }));
155
+ families.queueTime.touch(labels);
156
+ families.timeouts.touch(labels);
157
+ }
158
+ return labels;
159
+ };
160
+ var redisLabels = (command, source) => {
161
+ var labels = {
162
+ command: choice(command, ['get', 'set', 'expire'], 'get'),
163
+ source
164
+ };
165
+ var key = JSON.stringify(labels);
166
+ if (!redis.has(key)) {
167
+ redis.add(key);
168
+ for (var outcome of ['success', 'error']) families.redis.touch(_objectSpread(_objectSpread({}, labels), {}, {
169
+ outcome
170
+ }));
171
+ families.redisTime.touch(labels);
172
+ families.redisUnavailable.touch(labels);
173
+ }
174
+ return labels;
175
+ };
176
+ // An installed, idle collector must expose aggregate zeros, not look absent.
177
+ // Detailed operation/route combinations are initialized on first observation.
178
+ for (var source of ['prezly', 'custom', 'unknown']) {
179
+ contentLabels('other', source);
180
+ routeLabels('other', source);
181
+ for (var command of ['get', 'set', 'expire']) redisLabels(command, source);
182
+ }
183
+ var observe = event => {
184
+ if (!event || typeof event !== 'object') return;
185
+ if (['origin', 'upstream', 'redis_command'].includes(event.type) && (!('seconds' in event) || typeof event.seconds !== 'number')) return;
186
+ if ('seconds' in event && event.seconds !== undefined && (typeof event.seconds !== 'number' || !Number.isFinite(event.seconds) || event.seconds < 0 || event.seconds > Number.MAX_SAFE_INTEGER)) return;
187
+ var source = choice(event.source, ['prezly', 'custom', 'unknown'], 'unknown');
188
+ if ('operation' in event) {
189
+ var labels = contentLabels(event.operation, source);
190
+ switch (event.type) {
191
+ case 'content_request':
192
+ families.requests.add(labels);
193
+ break;
194
+ case 'cache_miss':
195
+ families.misses.add(labels);
196
+ break;
197
+ case 'cache_hit':
198
+ families.hits.add(_objectSpread(_objectSpread({}, labels), {}, {
199
+ layer: choice(event.layer, ['memory', 'redis', 'custom'], 'custom')
200
+ }));
201
+ break;
202
+ case 'cache_error':
203
+ families.cacheErrors.add(_objectSpread(_objectSpread({}, labels), {}, {
204
+ action: choice(event.action, ['read', 'write'], 'read')
205
+ }));
206
+ break;
207
+ case 'coalesced':
208
+ families.coalesced.add(labels);
209
+ break;
210
+ case 'content_rejected':
211
+ families.rejected.add(labels);
212
+ break;
213
+ case 'origin':
214
+ families.origin.add(_objectSpread(_objectSpread({}, labels), {}, {
215
+ outcome: choice(event.outcome, ['success', 'error'], 'error')
216
+ }));
217
+ families.originTime.add(labels, event.seconds);
218
+ break;
219
+ }
220
+ } else if ('route' in event) {
221
+ var _labels = routeLabels(event.route, source);
222
+ switch (event.type) {
223
+ case 'upstream':
224
+ {
225
+ var client = choice(event.client, ['raw', 'content'], 'raw');
226
+ families.upstream.add(_objectSpread(_objectSpread({}, _labels), {}, {
227
+ client,
228
+ status_class: choice(event.status, ['2xx', '3xx', '4xx', '5xx', 'other', 'error'], 'other')
229
+ }));
230
+ families.upstreamTime.add(_objectSpread(_objectSpread({}, _labels), {}, {
231
+ client
232
+ }), event.seconds);
233
+ break;
234
+ }
235
+ case 'fetch_queue':
236
+ families.queue.add(_objectSpread(_objectSpread({}, _labels), {}, {
237
+ outcome: choice(event.outcome, ['queued', 'accepted', 'full', 'wait_timeout', 'aborted'], 'aborted')
238
+ }));
239
+ if (event.seconds !== undefined) families.queueTime.add(_labels, event.seconds);
240
+ break;
241
+ case 'fetch_timeout':
242
+ families.timeouts.add(_labels);
243
+ break;
244
+ }
245
+ } else if ('command' in event) {
246
+ var _labels2 = redisLabels(event.command, source);
247
+ if (event.type === 'redis_unavailable') families.redisUnavailable.add(_labels2);else if (event.type === 'redis_command') {
248
+ families.redis.add(_objectSpread(_objectSpread({}, _labels2), {}, {
249
+ outcome: choice(event.outcome, ['success', 'error'], 'error')
250
+ }));
251
+ families.redisTime.add(_labels2, event.seconds);
252
+ }
253
+ }
254
+ };
255
+ return {
256
+ observe,
257
+ contentType: 'text/plain; version=0.0.4; charset=utf-8',
258
+ render() {
259
+ return ['# HELP theme_kit_metrics_info Runtime-local Theme Kit instrumentation schema.', '# TYPE theme_kit_metrics_info gauge', "theme_kit_metrics_info{runtime=\"".concat(choice(runtime, ['node', 'edge', 'unknown'], 'unknown'), "\",schema=\"1\"} 1"), ...Object.values(families).flatMap(family => family.render(choice(runtime, ['node', 'edge', 'unknown'], 'unknown'))), ''].join('\n');
260
+ }
261
+ };
262
+ }
263
+
264
+ /** Share across server chunks and ESM/CJS copies within the same JS realm. */
265
+ function getMetricsCollector() {
266
+ var _registry$key;
267
+ var runtime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'unknown';
268
+ var key = Symbol.for('@prezly/theme-kit-core/metrics/v1');
269
+ var registry = globalThis;
270
+ var collectors = (_registry$key = registry[key]) !== null && _registry$key !== void 0 ? _registry$key : registry[key] = new Map();
271
+ var name = choice(runtime, ['node', 'edge', 'unknown'], 'unknown');
272
+ var collector = collectors.get(name);
273
+ if (!collector) {
274
+ collector = createMetricsCollector({
275
+ runtime: name
276
+ });
277
+ collectors.set(name, collector);
278
+ }
279
+ return collector;
280
+ }
@@ -0,0 +1,14 @@
1
+ import { type TelemetryObserver } from './telemetry';
2
+ /**
3
+ * One collector per serving runtime. No sockets, timers, retained events or
4
+ * unbounded labels. Instantiate once and pass `observe` to every local adapter.
5
+ */
6
+ export declare function createMetricsCollector({ runtime, }?: {
7
+ runtime?: 'node' | 'edge' | 'unknown';
8
+ }): {
9
+ observe: TelemetryObserver;
10
+ contentType: string;
11
+ render(): string;
12
+ };
13
+ /** Share across server chunks and ESM/CJS copies within the same JS realm. */
14
+ export declare function getMetricsCollector(runtime?: 'node' | 'edge' | 'unknown'): any;
@@ -0,0 +1,273 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
8
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
9
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
10
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
11
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
12
+ import { CONTENT_OPERATIONS, UPSTREAM_ROUTES } from "./telemetry.mjs";
13
+ var BUCKETS = [0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, Number.POSITIVE_INFINITY];
14
+ function choice(value, values, fallback) {
15
+ return typeof value === 'string' && values.includes(value) ? value : fallback;
16
+ }
17
+ class Family {
18
+ constructor(name, help) {
19
+ var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'counter';
20
+ this.name = name;
21
+ this.help = help;
22
+ this.type = type;
23
+ _defineProperty(this, "samples", new Map());
24
+ }
25
+ touch(labels) {
26
+ var key = JSON.stringify(labels);
27
+ var sample = this.samples.get(key);
28
+ if (!sample) {
29
+ sample = {
30
+ labels,
31
+ count: 0,
32
+ sum: 0,
33
+ buckets: this.type === 'histogram' ? BUCKETS.map(() => 0) : []
34
+ };
35
+ this.samples.set(key, sample);
36
+ }
37
+ return sample;
38
+ }
39
+ add(labels, seconds) {
40
+ var sample = this.touch(labels);
41
+ sample.count += 1;
42
+ if (this.type === 'histogram' && seconds !== undefined) {
43
+ sample.sum += seconds;
44
+ BUCKETS.forEach((bound, i) => {
45
+ if (seconds <= bound) sample.buckets[i] += 1;
46
+ });
47
+ }
48
+ }
49
+ render(runtime) {
50
+ var _this = this;
51
+ var name = "theme_kit_".concat(this.name);
52
+ var lines = ["# HELP ".concat(name, " ").concat(this.help), "# TYPE ".concat(name, " ").concat(this.type)];
53
+ var labels = values => "{".concat(Object.entries(_objectSpread({
54
+ runtime
55
+ }, values)).map(_ref => {
56
+ var _ref2 = _slicedToArray(_ref, 2),
57
+ k = _ref2[0],
58
+ v = _ref2[1];
59
+ return "".concat(k, "=\"").concat(v, "\"");
60
+ }).join(','), "}");
61
+ var _loop = function _loop(sample) {
62
+ if (_this.type === 'counter') lines.push("".concat(name).concat(labels(sample.labels), " ").concat(sample.count));else {
63
+ BUCKETS.forEach((bound, i) => {
64
+ lines.push("".concat(name, "_bucket").concat(labels(_objectSpread(_objectSpread({}, sample.labels), {}, {
65
+ le: bound === Number.POSITIVE_INFINITY ? '+Inf' : String(bound)
66
+ })), " ").concat(sample.buckets[i]));
67
+ });
68
+ lines.push("".concat(name, "_sum").concat(labels(sample.labels), " ").concat(sample.sum), "".concat(name, "_count").concat(labels(sample.labels), " ").concat(sample.count));
69
+ }
70
+ };
71
+ for (var sample of this.samples.values()) {
72
+ _loop(sample);
73
+ }
74
+ return lines;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * One collector per serving runtime. No sockets, timers, retained events or
80
+ * unbounded labels. Instantiate once and pass `observe` to every local adapter.
81
+ */
82
+ export function createMetricsCollector() {
83
+ var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
84
+ _ref3$runtime = _ref3.runtime,
85
+ runtime = _ref3$runtime === void 0 ? 'unknown' : _ref3$runtime;
86
+ var families = {
87
+ requests: new Family('content_requests_total', 'Content method invocations, including coalesced callers.'),
88
+ hits: new Family('content_cache_hits_total', 'Cache entries accepted after version and source-scope validation.'),
89
+ misses: new Family('content_cache_misses_total', 'Cache lookups that require origin fallback.'),
90
+ cacheErrors: new Family('content_cache_errors_total', 'Observed cache read or write failures.'),
91
+ coalesced: new Family('content_coalesced_total', 'Callers joining an existing pending result.'),
92
+ rejected: new Family('content_rejected_total', 'Calls rejected by the pending-content limit.'),
93
+ origin: new Family('content_origin_total', 'Content method executions against the SDK, not physical HTTP requests.'),
94
+ originTime: new Family('content_origin_duration_seconds', 'Content origin execution duration including SDK decoding and aggregate work.', 'histogram'),
95
+ upstream: new Family('upstream_requests_total', 'Fetch attempts that reached a response-header or transport-error outcome.'),
96
+ upstreamTime: new Family('upstream_headers_duration_seconds', 'Fetch duration to headers or transport failure; excludes body consumption.', 'histogram'),
97
+ queue: new Family('fetch_queue_events_total', 'Bounded content transport admission and queue events.'),
98
+ queueTime: new Family('fetch_queue_wait_seconds', 'Completed admission wait; immediate admission has zero wait.', 'histogram'),
99
+ timeouts: new Family('fetch_timeouts_total', 'Content transport deadlines, including response-body consumption.'),
100
+ redis: new Family('redis_command_attempts_total', 'Redis command attempts by application-visible outcome, including deadlines.'),
101
+ redisTime: new Family('redis_command_duration_seconds', 'Redis command duration to application-visible completion.', 'histogram'),
102
+ redisUnavailable: new Family('redis_unavailable_total', 'Cache operations skipped because the shared Redis connection is not ready.')
103
+ };
104
+ var contents = new Set();
105
+ var routes = new Set();
106
+ var redis = new Set();
107
+ var contentLabels = (operation, source) => {
108
+ var labels = {
109
+ operation: choice(operation, CONTENT_OPERATIONS, 'other'),
110
+ source
111
+ };
112
+ var key = JSON.stringify(labels);
113
+ if (!contents.has(key)) {
114
+ contents.add(key);
115
+ for (var family of [families.requests, families.misses, families.coalesced, families.rejected, families.originTime]) family.touch(labels);
116
+ for (var layer of ['memory', 'redis', 'custom']) families.hits.touch(_objectSpread(_objectSpread({}, labels), {}, {
117
+ layer
118
+ }));
119
+ for (var action of ['read', 'write']) families.cacheErrors.touch(_objectSpread(_objectSpread({}, labels), {}, {
120
+ action
121
+ }));
122
+ for (var outcome of ['success', 'error']) families.origin.touch(_objectSpread(_objectSpread({}, labels), {}, {
123
+ outcome
124
+ }));
125
+ }
126
+ return labels;
127
+ };
128
+ var routeLabels = (route, source) => {
129
+ var labels = {
130
+ route: choice(route, UPSTREAM_ROUTES, 'other'),
131
+ source
132
+ };
133
+ var key = JSON.stringify(labels);
134
+ if (!routes.has(key)) {
135
+ routes.add(key);
136
+ for (var client of ['raw', 'content']) {
137
+ families.upstreamTime.touch(_objectSpread(_objectSpread({}, labels), {}, {
138
+ client
139
+ }));
140
+ for (var status of ['2xx', '3xx', '4xx', '5xx', 'other', 'error']) families.upstream.touch(_objectSpread(_objectSpread({}, labels), {}, {
141
+ client,
142
+ status_class: status
143
+ }));
144
+ }
145
+ for (var outcome of ['queued', 'accepted', 'full', 'wait_timeout', 'aborted']) families.queue.touch(_objectSpread(_objectSpread({}, labels), {}, {
146
+ outcome
147
+ }));
148
+ families.queueTime.touch(labels);
149
+ families.timeouts.touch(labels);
150
+ }
151
+ return labels;
152
+ };
153
+ var redisLabels = (command, source) => {
154
+ var labels = {
155
+ command: choice(command, ['get', 'set', 'expire'], 'get'),
156
+ source
157
+ };
158
+ var key = JSON.stringify(labels);
159
+ if (!redis.has(key)) {
160
+ redis.add(key);
161
+ for (var outcome of ['success', 'error']) families.redis.touch(_objectSpread(_objectSpread({}, labels), {}, {
162
+ outcome
163
+ }));
164
+ families.redisTime.touch(labels);
165
+ families.redisUnavailable.touch(labels);
166
+ }
167
+ return labels;
168
+ };
169
+ // An installed, idle collector must expose aggregate zeros, not look absent.
170
+ // Detailed operation/route combinations are initialized on first observation.
171
+ for (var source of ['prezly', 'custom', 'unknown']) {
172
+ contentLabels('other', source);
173
+ routeLabels('other', source);
174
+ for (var command of ['get', 'set', 'expire']) redisLabels(command, source);
175
+ }
176
+ var observe = event => {
177
+ if (!event || typeof event !== 'object') return;
178
+ if (['origin', 'upstream', 'redis_command'].includes(event.type) && (!('seconds' in event) || typeof event.seconds !== 'number')) return;
179
+ if ('seconds' in event && event.seconds !== undefined && (typeof event.seconds !== 'number' || !Number.isFinite(event.seconds) || event.seconds < 0 || event.seconds > Number.MAX_SAFE_INTEGER)) return;
180
+ var source = choice(event.source, ['prezly', 'custom', 'unknown'], 'unknown');
181
+ if ('operation' in event) {
182
+ var labels = contentLabels(event.operation, source);
183
+ switch (event.type) {
184
+ case 'content_request':
185
+ families.requests.add(labels);
186
+ break;
187
+ case 'cache_miss':
188
+ families.misses.add(labels);
189
+ break;
190
+ case 'cache_hit':
191
+ families.hits.add(_objectSpread(_objectSpread({}, labels), {}, {
192
+ layer: choice(event.layer, ['memory', 'redis', 'custom'], 'custom')
193
+ }));
194
+ break;
195
+ case 'cache_error':
196
+ families.cacheErrors.add(_objectSpread(_objectSpread({}, labels), {}, {
197
+ action: choice(event.action, ['read', 'write'], 'read')
198
+ }));
199
+ break;
200
+ case 'coalesced':
201
+ families.coalesced.add(labels);
202
+ break;
203
+ case 'content_rejected':
204
+ families.rejected.add(labels);
205
+ break;
206
+ case 'origin':
207
+ families.origin.add(_objectSpread(_objectSpread({}, labels), {}, {
208
+ outcome: choice(event.outcome, ['success', 'error'], 'error')
209
+ }));
210
+ families.originTime.add(labels, event.seconds);
211
+ break;
212
+ }
213
+ } else if ('route' in event) {
214
+ var _labels = routeLabels(event.route, source);
215
+ switch (event.type) {
216
+ case 'upstream':
217
+ {
218
+ var client = choice(event.client, ['raw', 'content'], 'raw');
219
+ families.upstream.add(_objectSpread(_objectSpread({}, _labels), {}, {
220
+ client,
221
+ status_class: choice(event.status, ['2xx', '3xx', '4xx', '5xx', 'other', 'error'], 'other')
222
+ }));
223
+ families.upstreamTime.add(_objectSpread(_objectSpread({}, _labels), {}, {
224
+ client
225
+ }), event.seconds);
226
+ break;
227
+ }
228
+ case 'fetch_queue':
229
+ families.queue.add(_objectSpread(_objectSpread({}, _labels), {}, {
230
+ outcome: choice(event.outcome, ['queued', 'accepted', 'full', 'wait_timeout', 'aborted'], 'aborted')
231
+ }));
232
+ if (event.seconds !== undefined) families.queueTime.add(_labels, event.seconds);
233
+ break;
234
+ case 'fetch_timeout':
235
+ families.timeouts.add(_labels);
236
+ break;
237
+ }
238
+ } else if ('command' in event) {
239
+ var _labels2 = redisLabels(event.command, source);
240
+ if (event.type === 'redis_unavailable') families.redisUnavailable.add(_labels2);else if (event.type === 'redis_command') {
241
+ families.redis.add(_objectSpread(_objectSpread({}, _labels2), {}, {
242
+ outcome: choice(event.outcome, ['success', 'error'], 'error')
243
+ }));
244
+ families.redisTime.add(_labels2, event.seconds);
245
+ }
246
+ }
247
+ };
248
+ return {
249
+ observe,
250
+ contentType: 'text/plain; version=0.0.4; charset=utf-8',
251
+ render() {
252
+ return ['# HELP theme_kit_metrics_info Runtime-local Theme Kit instrumentation schema.', '# TYPE theme_kit_metrics_info gauge', "theme_kit_metrics_info{runtime=\"".concat(choice(runtime, ['node', 'edge', 'unknown'], 'unknown'), "\",schema=\"1\"} 1"), ...Object.values(families).flatMap(family => family.render(choice(runtime, ['node', 'edge', 'unknown'], 'unknown'))), ''].join('\n');
253
+ }
254
+ };
255
+ }
256
+
257
+ /** Share across server chunks and ESM/CJS copies within the same JS realm. */
258
+ export function getMetricsCollector() {
259
+ var _registry$key;
260
+ var runtime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'unknown';
261
+ var key = Symbol.for('@prezly/theme-kit-core/metrics/v1');
262
+ var registry = globalThis;
263
+ var collectors = (_registry$key = registry[key]) !== null && _registry$key !== void 0 ? _registry$key : registry[key] = new Map();
264
+ var name = choice(runtime, ['node', 'edge', 'unknown'], 'unknown');
265
+ var collector = collectors.get(name);
266
+ if (!collector) {
267
+ collector = createMetricsCollector({
268
+ runtime: name
269
+ });
270
+ collectors.set(name, collector);
271
+ }
272
+ return collector;
273
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.UPSTREAM_ROUTES = exports.CONTENT_OPERATIONS = void 0;
7
+ exports.elapsedSeconds = elapsedSeconds;
8
+ exports.emit = emit;
9
+ exports.notify = notify;
10
+ exports.telemetryNow = telemetryNow;
11
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
14
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
15
+ function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
16
+ var CONTENT_OPERATIONS = exports.CONTENT_OPERATIONS = ['newsroom', 'theme', 'languages', 'categories', 'featuredContacts', 'galleries', 'gallery', 'stories', 'allStories', 'story', 'other'];
17
+ var UPSTREAM_ROUTES = exports.UPSTREAM_ROUTES = ['newsroom', 'theme', 'languages', 'categories', 'contacts', 'galleries', 'gallery', 'stories', 'story', 'story_by_slug', 'other'];
18
+
19
+ /** Only bounded classifications and numeric observations; never payloads or keys. */
20
+
21
+ function notify(observer, event) {
22
+ try {
23
+ var result = observer === null || observer === void 0 ? void 0 : observer(event);
24
+ // TypeScript permits async callbacks where a void callback is expected.
25
+ // Observe a rejection without awaiting or retaining a metrics queue.
26
+ if (result && typeof result.then === 'function') {
27
+ void Promise.resolve(result).catch(() => undefined);
28
+ }
29
+ } catch (_unused) {
30
+ // Instrumentation must not change the application's result.
31
+ }
32
+ }
33
+ function emit(telemetry, event) {
34
+ if (telemetry) {
35
+ try {
36
+ var candidate = telemetry.source;
37
+ var source = candidate === 'prezly' || candidate === 'custom' ? candidate : 'unknown';
38
+ notify(telemetry.observe, _objectSpread(_objectSpread({}, event), {}, {
39
+ source
40
+ }));
41
+ } catch (_unused2) {
42
+ // A malformed observer configuration must also remain non-fatal.
43
+ }
44
+ }
45
+ }
46
+ function telemetryNow() {
47
+ var _globalThis$performan, _globalThis$performan2;
48
+ return (_globalThis$performan = (_globalThis$performan2 = globalThis.performance) === null || _globalThis$performan2 === void 0 ? void 0 : _globalThis$performan2.now()) !== null && _globalThis$performan !== void 0 ? _globalThis$performan : Date.now();
49
+ }
50
+ function elapsedSeconds(start) {
51
+ return Math.max(0, (telemetryNow() - start) / 1000);
52
+ }