@naosystem/cf-workers-status-page 0.1.2 → 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/admin.html CHANGED
@@ -5,10 +5,10 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <meta name="robots" content="noindex" />
7
7
  <title>Status admin</title>
8
- <script type="module" crossorigin src="/assets/admin-BBJxKTF6.js"></script>
9
- <link rel="modulepreload" crossorigin href="/assets/src-BDi4qpij.js">
8
+ <script type="module" crossorigin src="/assets/admin-BiljT5iG.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/src-seeRRxzL.js">
10
10
  <link rel="stylesheet" crossorigin href="/assets/src-C6ZFz-Gu.css">
11
- <link rel="stylesheet" crossorigin href="/assets/admin-Be4X0WFj.css">
11
+ <link rel="stylesheet" crossorigin href="/assets/admin-F_WwOjdr.css">
12
12
  </head>
13
13
  <body>
14
14
  <!-- The admin UI. Served only by the Worker, after authentication. -->
@@ -248,6 +248,186 @@ var LOCATION_HINTS = [
248
248
  "afr",
249
249
  "me"
250
250
  ];
251
+ // ../core/src/frame.ts
252
+ /**
253
+ * What surrounds a status page's content, its "frame": the heading's texts (title,
254
+ * description), the logo and the website it links to, the header's navigation and the footer.
255
+ * Written in status.config.ts (`pages[]`), and replaceable per field in the admin UI, which
256
+ * validates with the same schemas (shared/admin-api.ts).
257
+ *
258
+ * Data only, never HTML or components, so that the page keeps its Content-Security-Policy
259
+ * (`script-src 'self'`, `style-src 'self'`) and the prebuilt client of the npm package can
260
+ * show it.
261
+ */
262
+ /** Limits of a frame's texts and links. Lengths are in characters (UTF-16 code units). */
263
+ var FRAME_LIMITS = {
264
+ title: 100,
265
+ description: 1e3,
266
+ /** Entries of the header's navigation: links and menus. */
267
+ navItems: 6,
268
+ /** Links in a menu of the header's navigation. */
269
+ menuItems: 10,
270
+ footerColumns: 4,
271
+ /** Links in a column of the footer. */
272
+ columnLinks: 10,
273
+ /** Links in the footer's line of links. */
274
+ footerLinks: 10,
275
+ /** A link's label, a menu's label, a column's title. */
276
+ label: 50,
277
+ url: 500,
278
+ footerText: 500,
279
+ /** Languages of a text written per language. */
280
+ languages: 10,
281
+ /**
282
+ * Largest admin API request that sets a page's appearance (`PUT
283
+ * /api/admin/pages/:pageId/appearance`), in bytes: above the largest frame these limits allow
284
+ * (FRAME_LIMITS tests check it), which other requests' 64 KiB is not.
285
+ */
286
+ appearanceRequestBytes: 524288
287
+ };
288
+ /** Whether a navigation entry is a menu (has `items`) rather than a link. */
289
+ function isNavMenu(item) {
290
+ return "items" in item;
291
+ }
292
+ /** A header without navigation. */
293
+ var EMPTY_HEADER = { nav: [] };
294
+ /** A footer with nothing but the page's own lines (time zone, language). */
295
+ var EMPTY_FOOTER = {
296
+ columns: [],
297
+ links: [],
298
+ text: null
299
+ };
300
+ /** A refinement's issue, with a code the admin UI translates (shared/admin-api.ts `ApiIssue`). */
301
+ function issue(message, code, path = []) {
302
+ return {
303
+ code: "custom",
304
+ message,
305
+ path,
306
+ params: { code }
307
+ };
308
+ }
309
+ /**
310
+ * Control characters but tabs and line breaks: nothing a text needs, and JSON writes each as six
311
+ * bytes (`\u0001`), which would let a text grow six times its length in the status response.
312
+ */
313
+ var CONTROL_CHARACTER = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
314
+ /**
315
+ * A {@link LocalizedText} of at most `maxLength` characters per language, trimmed. Language
316
+ * tags are written in their canonical form (`pt-br` → `pt-BR`). With `allowEmpty`, `""` is
317
+ * accepted (an administrator clearing a text that status.config.ts sets); never an empty
318
+ * text in one language: leave that language out instead.
319
+ */
320
+ function localizedTextSchema(maxLength, { allowEmpty = false } = {}) {
321
+ const text = z.string().trim().max(maxLength).refine((value) => !CONTROL_CHARACTER.test(value), {
322
+ message: "must not contain control characters (other than tabs and line breaks)",
323
+ params: { code: "control_character" }
324
+ });
325
+ const byLanguage = z.record(z.string(), text.min(1)).superRefine((texts, ctx) => {
326
+ const tags = Object.keys(texts);
327
+ if (tags.length === 0) ctx.addIssue(issue("must have a text in at least one language", "no_language"));
328
+ if (tags.length > FRAME_LIMITS.languages) ctx.addIssue(issue(`must have at most ${FRAME_LIMITS.languages} languages`, "too_many_languages"));
329
+ const seen = /* @__PURE__ */ new Set();
330
+ for (const tag of tags) {
331
+ const name = canonicalTag(tag);
332
+ if (name === void 0) ctx.addIssue(issue(`"${tag}" is not a language tag; use one such as "en" or "ja"`, "language_tag", [tag]));
333
+ else if (seen.has(name)) ctx.addIssue(issue(`language "${name}" is written twice`, "duplicate_language", [tag]));
334
+ if (name !== void 0) seen.add(name);
335
+ }
336
+ });
337
+ return z.union([allowEmpty ? text : text.min(1), byLanguage]).transform((value) => typeof value === "string" ? value : Object.fromEntries(Object.entries(value).map(([tag, item]) => [canonicalTag(tag) ?? tag, item])));
338
+ }
339
+ /** The canonical form of a BCP 47 tag (`pt-br` → `pt-BR`), or `undefined` when it is not one. */
340
+ function canonicalTag(tag) {
341
+ try {
342
+ return Intl.getCanonicalLocales(tag)[0];
343
+ } catch {
344
+ return;
345
+ }
346
+ }
347
+ var SITE = "https://site.invalid";
348
+ function parseUrl(value, base) {
349
+ try {
350
+ return new URL(value, base);
351
+ } catch {
352
+ return null;
353
+ }
354
+ }
355
+ /**
356
+ * A link's URL: `https:`, `http:` or `mailto:` (never `javascript:` and the like), without
357
+ * credentials, or a path on this site (`/`, `/pages/other`, but not `//host`, which is another
358
+ * site). Written back as the URL parser normalises it, and limited in that form: encoding can
359
+ * make a URL several times longer ("あ" is "%E3%81%82"), and the encoded URL is what is stored
360
+ * and served.
361
+ */
362
+ var navUrlSchema = z.string().trim().min(1).max(FRAME_LIMITS.url).transform((value, ctx) => {
363
+ if (value.startsWith("/")) {
364
+ const url = parseUrl(value, SITE);
365
+ const path = url?.href.slice(20);
366
+ if (url === null || url.origin !== SITE || path === void 0 || parseUrl(path, SITE)?.href !== url.href || path.startsWith("//")) {
367
+ ctx.addIssue(issue("must be a path on this site, such as \"/pages/other\", or a full URL", "nav_url"));
368
+ return z.NEVER;
369
+ }
370
+ return encodedLength(path, ctx);
371
+ }
372
+ const url = parseUrl(value);
373
+ if (url === null || url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "mailto:") {
374
+ ctx.addIssue(issue("must be an https, http or mailto URL, or a path on this site starting with \"/\"", "nav_url"));
375
+ return z.NEVER;
376
+ }
377
+ if (url.username !== "" || url.password !== "") {
378
+ ctx.addIssue(issue("must not contain credentials", "url_credentials"));
379
+ return z.NEVER;
380
+ }
381
+ return encodedLength(url.href, ctx);
382
+ });
383
+ /** `url` when it is at most `FRAME_LIMITS.url` characters once encoded; else an issue. */
384
+ function encodedLength(url, ctx) {
385
+ if (url.length <= FRAME_LIMITS.url) return url;
386
+ ctx.addIssue({
387
+ ...issue(`must be at most ${FRAME_LIMITS.url} characters once encoded (it is ${url.length}; a character other than ASCII counts as its encoding, such as "%E3%81%82")`, "url_too_long"),
388
+ params: {
389
+ code: "url_too_long",
390
+ maximum: FRAME_LIMITS.url
391
+ }
392
+ });
393
+ return z.NEVER;
394
+ }
395
+ var labelSchema = localizedTextSchema(FRAME_LIMITS.label);
396
+ var navLinkSchema = z.strictObject({
397
+ label: labelSchema,
398
+ url: navUrlSchema
399
+ });
400
+ /**
401
+ * A link (`url`) or a menu (`items`). One object schema with both, rather than a union, so that
402
+ * a problem in either is reported where it is (a union reports only that neither matched).
403
+ */
404
+ var navItemSchema = z.strictObject({
405
+ label: labelSchema,
406
+ url: navUrlSchema.optional(),
407
+ items: z.array(navLinkSchema).min(1).max(FRAME_LIMITS.menuItems).optional()
408
+ }).superRefine((item, ctx) => {
409
+ if (item.url === void 0 === (item.items === void 0)) ctx.addIssue(issue("needs either \"url\" (a link) or \"items\" (a menu), not both", "link_or_menu"));
410
+ }).transform((item) => item.items === void 0 ? {
411
+ label: item.label,
412
+ url: item.url ?? ""
413
+ } : {
414
+ label: item.label,
415
+ items: item.items
416
+ });
417
+ var headerSchema = z.strictObject({ nav: z.array(navItemSchema).max(FRAME_LIMITS.navItems).default([]) });
418
+ var footerColumnSchema = z.strictObject({
419
+ title: labelSchema,
420
+ links: z.array(navLinkSchema).min(1).max(FRAME_LIMITS.columnLinks)
421
+ });
422
+ var footerSchema = z.strictObject({
423
+ columns: z.array(footerColumnSchema).max(FRAME_LIMITS.footerColumns).default([]),
424
+ links: z.array(navLinkSchema).max(FRAME_LIMITS.footerLinks).default([]),
425
+ text: localizedTextSchema(FRAME_LIMITS.footerText).nullish()
426
+ }).transform((footer) => ({
427
+ columns: footer.columns,
428
+ links: footer.links,
429
+ text: footer.text ?? null
430
+ }));
251
431
  // ../core/src/runner.ts
252
432
  /** Returns the capabilities in `required` that `runner` does not provide. */
253
433
  function missingCapabilities(required, runner) {
@@ -359,6 +539,27 @@ var reportUrlSchema = z.string().max(2e3).transform((value, ctx) => {
359
539
  }
360
540
  return url.href;
361
541
  });
542
+ /** `https:`, or also `http:` with `http`; never with credentials. */
543
+ function webUrlSchema({ http }) {
544
+ return z.string().trim().max(2e3).transform((value, ctx) => {
545
+ let url;
546
+ try {
547
+ url = new URL(value);
548
+ } catch {
549
+ ctx.addIssue("must be a URL such as \"https://example.com/\"");
550
+ return z.NEVER;
551
+ }
552
+ if (url.protocol !== "https:" && !(http && url.protocol === "http:")) {
553
+ ctx.addIssue(http ? "must be an https or http URL" : "must be an https URL (the page's Content-Security-Policy loads https images only)");
554
+ return z.NEVER;
555
+ }
556
+ if (url.username !== "" || url.password !== "") {
557
+ ctx.addIssue("must not contain credentials");
558
+ return z.NEVER;
559
+ }
560
+ return url.href;
561
+ });
562
+ }
362
563
  var PLACEHOLDER = /\{([^{}]*)\}/g;
363
564
  var KNOWN_PLACEHOLDERS = new Set(INCIDENT_TEMPLATE_PLACEHOLDERS);
364
565
  function templateSchema(maxLength) {
@@ -379,6 +580,12 @@ var pageSchema = z.strictObject({
379
580
  id: idSchema,
380
581
  template: z.enum(PAGE_TEMPLATES).default(DEFAULT_PAGE_TEMPLATE),
381
582
  reportUrl: reportUrlSchema.optional(),
583
+ title: localizedTextSchema(FRAME_LIMITS.title).optional(),
584
+ description: localizedTextSchema(FRAME_LIMITS.description).optional(),
585
+ logoUrl: webUrlSchema({ http: false }).optional(),
586
+ websiteUrl: webUrlSchema({ http: true }).optional(),
587
+ header: headerSchema.prefault({}),
588
+ footer: footerSchema.prefault({}),
382
589
  incidents: z.strictObject({
383
590
  auto: z.boolean().default(false),
384
591
  templates: templatesSchema.default({}),
@@ -686,6 +893,14 @@ function resolveConfig(config, { runners, reservedSecrets = [] }) {
686
893
  id: page.id,
687
894
  template: page.template,
688
895
  reportUrl: page.reportUrl ?? null,
896
+ frame: {
897
+ title: page.title ?? null,
898
+ description: page.description ?? null,
899
+ logoUrl: page.logoUrl ?? null,
900
+ websiteUrl: page.websiteUrl ?? null,
901
+ header: page.header,
902
+ footer: page.footer
903
+ },
689
904
  incidents: {
690
905
  auto: page.incidents.auto,
691
906
  templates: stripUndefined(page.incidents.templates),
@@ -1076,6 +1291,6 @@ function mergeDownPeriods(periods) {
1076
1291
  }
1077
1292
  return merged;
1078
1293
  }
1079
- export { addDays as A, resolveConfig as C, parseDuration as D, durationSchema as E, localDate as M, recentDays as N, confirmState as O, startOfLocalDay as P, defineConfig as S, LOCATION_HINTS as T, worseOf as _, excludeWindows as a, INCIDENT_TEMPLATE_PLACEHOLDERS as b, mergeRanges as c, uptimeRatio as d, LATE_GRACE_MS as f, staleAfterMs as g, isCheckState as h, downPeriods as i, calendarDay as j, observationsNeeded as k, monitorTimeline as l, displayState as m, concatSegments as n, lateSpans as o, componentState as p, coverageRatio as r, mergeDownPeriods as s, combineTimelines as t, summarize as u, worstState as v, missingCapabilities as w, component as x, ConfigError as y };
1294
+ export { isNavMenu as A, calendarDay as B, resolveConfig as C, FRAME_LIMITS as D, EMPTY_HEADER as E, durationSchema as F, recentDays as H, parseDuration as I, confirmState as L, navLinkSchema as M, navUrlSchema as N, footerSchema as O, LOCATION_HINTS as P, observationsNeeded as R, defineConfig as S, EMPTY_FOOTER as T, startOfLocalDay as U, localDate as V, worseOf as _, excludeWindows as a, INCIDENT_TEMPLATE_PLACEHOLDERS as b, mergeRanges as c, uptimeRatio as d, LATE_GRACE_MS as f, staleAfterMs as g, isCheckState as h, downPeriods as i, localizedTextSchema as j, headerSchema as k, monitorTimeline as l, displayState as m, concatSegments as n, lateSpans as o, componentState as p, coverageRatio as r, mergeDownPeriods as s, combineTimelines as t, summarize as u, worstState as v, missingCapabilities as w, component as x, ConfigError as y, addDays as z };
1080
1295
 
1081
- //# sourceMappingURL=timeline-YJXjehRf.js.map
1296
+ //# sourceMappingURL=timeline-CsHxR6qb.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timeline-CsHxR6qb.js","names":[],"sources":["../../../core/src/calendar.ts","../../../core/src/confirmation.ts","../../../core/src/duration.ts","../../../core/src/location.ts","../../../core/src/frame.ts","../../../core/src/runner.ts","../../../core/src/config.ts","../../../core/src/display.ts","../../../core/src/timeline.ts"],"sourcesContent":["/**\n * Days in the configured time zone, with correct boundaries on days that\n * daylight saving time makes 23 or 25 hours long (or 23.5, or that start at 01:00 because\n * midnight is skipped). Uses `Intl.DateTimeFormat` with IANA zone names.\n */\nimport type { TimeRange } from \"./timeline\";\n\n/** A local calendar day: `[from, to)` runs from its first instant to the next day's. */\nexport interface CalendarDay extends TimeRange {\n\t/** `YYYY-MM-DD` in the time zone. */\n\treadonly date: string;\n}\n\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatter(timeZone: string): Intl.DateTimeFormat {\n\tlet found = formatters.get(timeZone);\n\tif (found === undefined) {\n\t\tfound = new Intl.DateTimeFormat(\"en-US\", {\n\t\t\ttimeZone,\n\t\t\thourCycle: \"h23\",\n\t\t\tyear: \"numeric\",\n\t\t\tmonth: \"2-digit\",\n\t\t\tday: \"2-digit\",\n\t\t\thour: \"2-digit\",\n\t\t\tminute: \"2-digit\",\n\t\t\tsecond: \"2-digit\",\n\t\t});\n\t\tformatters.set(timeZone, found);\n\t}\n\treturn found;\n}\n\ninterface WallClock {\n\treadonly year: number;\n\treadonly month: number;\n\treadonly day: number;\n\treadonly hour: number;\n\treadonly minute: number;\n\treadonly second: number;\n}\n\nfunction wallClock(at: number, timeZone: string): WallClock {\n\tconst parts: Record<string, number> = {};\n\tfor (const part of formatter(timeZone).formatToParts(at)) {\n\t\tif (part.type !== \"literal\") parts[part.type] = Number(part.value);\n\t}\n\treturn {\n\t\tyear: parts[\"year\"] ?? 0,\n\t\tmonth: parts[\"month\"] ?? 1,\n\t\tday: parts[\"day\"] ?? 1,\n\t\thour: parts[\"hour\"] ?? 0,\n\t\tminute: parts[\"minute\"] ?? 0,\n\t\tsecond: parts[\"second\"] ?? 0,\n\t};\n}\n\nfunction pad(value: number, length = 2): string {\n\treturn String(value).padStart(length, \"0\");\n}\n\nfunction formatDate(year: number, month: number, day: number): string {\n\treturn `${pad(year, 4)}-${pad(month)}-${pad(day)}`;\n}\n\nfunction parseDate(date: string): [number, number, number] {\n\tconst match = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(date);\n\tif (match === null) throw new RangeError(`Not a YYYY-MM-DD date: ${date}`);\n\treturn [Number(match[1]), Number(match[2]), Number(match[3])];\n}\n\n/** The date `days` after `date` (negative: before), in the proleptic Gregorian calendar. */\nexport function addDays(date: string, days: number): string {\n\tconst [year, month, day] = parseDate(date);\n\tconst shifted = new Date(Date.UTC(year, month - 1, day + days));\n\treturn formatDate(shifted.getUTCFullYear(), shifted.getUTCMonth() + 1, shifted.getUTCDate());\n}\n\n/** The local date (`YYYY-MM-DD`) at instant `at` in `timeZone`. */\nexport function localDate(at: number, timeZone: string): string {\n\tconst clock = wallClock(at, timeZone);\n\treturn formatDate(clock.year, clock.month, clock.day);\n}\n\n/** Local wall-clock time minus UTC at `at`, in milliseconds (whole seconds). */\nfunction offsetAt(at: number, timeZone: string): number {\n\tconst seconds = Math.floor(at / 1000) * 1000;\n\tconst clock = wallClock(seconds, timeZone);\n\treturn Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute, clock.second) - seconds;\n}\n\nconst starts = new Map<string, number>();\nconst MAX_MEMO = 4_096;\nconst HOUR_MS = 3_600_000;\n\n/**\n * The first instant of local date `date` in `timeZone`: local midnight, or the first\n * instant after a transition that skips midnight, or the earlier of two midnights when the\n * clock goes back across it.\n */\nexport function startOfLocalDay(date: string, timeZone: string): number {\n\tconst key = `${timeZone} ${date}`;\n\tconst memo = starts.get(key);\n\tif (memo !== undefined) return memo;\n\n\tconst [year, month, day] = parseDate(date);\n\tconst midnightUtc = Date.UTC(year, month - 1, day);\n\t// Two rounds find the offset in effect at local midnight in all but the cases checked below.\n\tlet start = midnightUtc - offsetAt(midnightUtc, timeZone);\n\tstart = midnightUtc - offsetAt(start, timeZone);\n\tif (localDate(start, timeZone) !== date || localDate(start - 1, timeZone) >= date) {\n\t\t// Midnight was skipped or repeated: search for the first instant of the date. Offsets\n\t\t// are between -12 and +14 hours, so it is within 15 hours of midnight UTC.\n\t\tlet low = midnightUtc - 15 * HOUR_MS;\n\t\tlet high = midnightUtc + 15 * HOUR_MS;\n\t\twhile (high - low > 1000) {\n\t\t\tconst middle = low + Math.floor((high - low) / 2000) * 1000;\n\t\t\tif (localDate(middle, timeZone) >= date) high = middle;\n\t\t\telse low = middle;\n\t\t}\n\t\tstart = high;\n\t}\n\tif (starts.size >= MAX_MEMO) starts.clear();\n\tstarts.set(key, start);\n\treturn start;\n}\n\n/** The local day of `date`. */\nexport function calendarDay(date: string, timeZone: string): CalendarDay {\n\treturn { date, from: startOfLocalDay(date, timeZone), to: startOfLocalDay(addDays(date, 1), timeZone) };\n}\n\n/** The last `count` local days up to and including the one containing `now`, oldest first. */\nexport function recentDays(now: number, timeZone: string, count: number): CalendarDay[] {\n\tconst today = localDate(now, timeZone);\n\tconst days: CalendarDay[] = [];\n\tfor (let offset = count - 1; offset >= 0; offset--) days.push(calendarDay(addDays(today, -offset), timeZone));\n\treturn days;\n}\n","import type { CheckState } from \"./provider\";\n\n/**\n * A state confirmed by the confirmation rule. Confirmed states, not individual\n * results, drive uptime, notifications and the stoppage history.\n */\nexport interface ConfirmedState {\n\treadonly state: CheckState;\n\t/**\n\t * When the run of results that confirmed this state began (ms since the epoch). Uptime\n\t * counts the state from here. Strictly greater than the previous confirmed state's `since`.\n\t */\n\treadonly since: number;\n\t/** When the result that completed the run was taken. Notifications report this time. */\n\treadonly confirmedAt: number;\n}\n\n/**\n * One check that produced a state. Checks that produced no result (a missing secret, a\n * provider exception, a runner that gave up) are not observations: leave them out, so they\n * neither confirm a state nor break a run.\n */\nexport interface Observation {\n\treadonly state: CheckState;\n\t/** When the check was taken (ms since the epoch). */\n\treadonly at: number;\n}\n\nexport interface ConfirmationThresholds {\n\t/** Consecutive non-`up` results needed to confirm a non-`up` state. At least 1. */\n\treadonly failureThreshold: number;\n\t/** Consecutive `up` results needed to confirm `up`. At least 1. */\n\treadonly successThreshold: number;\n}\n\nexport interface Confirmation {\n\t/** The confirmed state after the latest observation; `null` until a state has been confirmed. */\n\treadonly current: ConfirmedState | null;\n\t/** Whether the latest observation confirmed a new state, which `current` then is. */\n\treadonly changed: boolean;\n\t/**\n\t * The state the latest results point to while it is not confirmed yet, or `null` when\n\t * they agree with `current`. A non-`up` pending state is what calls for a re-check.\n\t */\n\treadonly pending: CheckState | null;\n}\n\n/** Lower is less severe. */\nconst SEVERITY: Readonly<Record<CheckState, number>> = { up: 0, degraded: 1, down: 2 };\n\n/**\n * How many of the latest observations {@link confirmState} needs to see: enough for the\n * longer threshold, plus one to see where the run started.\n */\nexport function observationsNeeded(thresholds: ConfirmationThresholds): number {\n\treturn Math.max(thresholds.failureThreshold, thresholds.successThreshold) + 1;\n}\n\n/** The trailing observations that satisfy `matches`, oldest first. */\nfunction trailingRun(recent: readonly Observation[], matches: (state: CheckState) => boolean): Observation[] {\n\tlet start = recent.length;\n\twhile (start > 0 && matches((recent[start - 1] as Observation).state)) start--;\n\treturn recent.slice(start);\n}\n\nfunction leastSevere(run: readonly Observation[]): CheckState {\n\treturn run.reduce<CheckState>(\n\t\t(least, { state }) => (SEVERITY[state] < SEVERITY[least] ? state : least),\n\t\t\"down\",\n\t);\n}\n\n/**\n * The confirmation rule, as a pure function of the confirmed state before the\n * latest observation and the latest observations.\n *\n * - `successThreshold` consecutive `up` results confirm `up`.\n * - From `up` (or before anything is confirmed), `failureThreshold` consecutive non-`up`\n * results confirm a non-`up` state: the least severe state in that run, so\n * `[down, degraded]` confirms `degraded`.\n * - While a non-`up` state is confirmed, moving between `degraded` and `down` needs\n * `failureThreshold` consecutive results of the new state.\n *\n * `since` is the start of the run that confirmed the state, as far back as `recent` reaches,\n * and is kept strictly after the previous state's `since`.\n *\n * @param previous The confirmed state before the latest observation, or `null`.\n * @param recent The latest observations, oldest first, ending with the newest one. Pass at\n * least {@link observationsNeeded} of them when that many exist.\n */\nexport function confirmState(\n\tprevious: ConfirmedState | null,\n\trecent: readonly Observation[],\n\tthresholds: ConfirmationThresholds,\n): Confirmation {\n\tconst latest = recent.at(-1);\n\tconst unchanged = (pending: CheckState | null): Confirmation => ({ current: previous, changed: false, pending });\n\tif (latest === undefined) return unchanged(null);\n\n\tlet target: CheckState;\n\tlet run: Observation[];\n\tlet threshold: number;\n\tif (latest.state === \"up\") {\n\t\tif (previous?.state === \"up\") return unchanged(null);\n\t\trun = trailingRun(recent, (state) => state === \"up\");\n\t\ttarget = \"up\";\n\t\tthreshold = thresholds.successThreshold;\n\t} else if (previous === null || previous.state === \"up\") {\n\t\trun = trailingRun(recent, (state) => state !== \"up\");\n\t\ttarget = leastSevere(run);\n\t\tthreshold = thresholds.failureThreshold;\n\t} else {\n\t\tif (latest.state === previous.state) return unchanged(null);\n\t\trun = trailingRun(recent, (state) => state === latest.state);\n\t\ttarget = latest.state;\n\t\tthreshold = thresholds.failureThreshold;\n\t}\n\n\tif (run.length < threshold) return unchanged(target);\n\tconst runStart = (run[0] as Observation).at;\n\tconst since = previous === null ? runStart : Math.max(runStart, previous.since + 1);\n\treturn {\n\t\tcurrent: { state: target, since, confirmedAt: latest.at },\n\t\tchanged: true,\n\t\t// [degraded, down] confirms degraded, and the latest down already points to down.\n\t\tpending: latest.state === target ? null : latest.state,\n\t};\n}\n","import * as z from \"zod\";\n\n/** Units accepted in a {@link Duration}. */\nexport type DurationUnit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\n\n/**\n * A length of time written as a non-negative integer followed by a unit,\n * for example `\"500ms\"`, `\"15s\"`, `\"1m\"`, `\"12h\"` or `\"180d\"`.\n * Compound forms such as `\"1h30m\"` and fractions such as `\"1.5h\"` are not accepted.\n */\nexport type Duration = `${number}${DurationUnit}`;\n\nconst UNIT_MS: Record<DurationUnit, number> = {\n\tms: 1,\n\ts: 1_000,\n\tm: 60_000,\n\th: 3_600_000,\n\td: 86_400_000,\n};\n\nconst DURATION_PATTERN = /^(\\d+)(ms|s|m|h|d)$/;\n\nconst FORMAT_HINT =\n\t'expected an integer followed by ms, s, m, h or d (for example \"15s\", \"1m\" or \"180d\")';\n\n/**\n * Converts a duration string to milliseconds.\n * @throws RangeError if the string is not a valid {@link Duration}.\n */\nexport function parseDuration(value: string): number {\n\tconst match = DURATION_PATTERN.exec(value);\n\tconst amount = match?.[1];\n\tconst unit = match?.[2] as DurationUnit | undefined;\n\tif (amount === undefined || unit === undefined) {\n\t\tthrow new RangeError(`Invalid duration \"${value}\": ${FORMAT_HINT}`);\n\t}\n\tconst ms = Number(amount) * UNIT_MS[unit];\n\tif (!Number.isSafeInteger(ms)) {\n\t\tthrow new RangeError(`Invalid duration \"${value}\": too large`);\n\t}\n\treturn ms;\n}\n\n/**\n * Zod schema that accepts a {@link Duration} string and outputs milliseconds.\n * Use `.prefault(\"10s\")` (not `.default()`) to give a default written as a duration string.\n */\nexport function durationSchema(): z.ZodType<number, Duration> {\n\treturn z.string().transform((value, ctx) => {\n\t\ttry {\n\t\t\treturn parseDuration(value);\n\t\t} catch (error) {\n\t\t\tctx.addIssue((error as Error).message);\n\t\t\treturn z.NEVER;\n\t\t}\n\t}) as z.ZodType<number, Duration>;\n}\n","/**\n * Where the hub places a monitor's Durable Object, and so where the built-in runner\n * checks from. Values are Durable Object location hints.\n *\n * The Worker verifies at type-check time that this list matches the runtime's\n * `DurableObjectLocationHint`, so core stays free of Cloudflare runtime types.\n */\nexport const LOCATION_HINTS = [\n\t\"wnam\",\n\t\"enam\",\n\t\"sam\",\n\t\"weur\",\n\t\"eeur\",\n\t\"apac\",\n\t\"apac-ne\",\n\t\"apac-se\",\n\t\"oc\",\n\t\"afr\",\n\t\"me\",\n] as const;\n\nexport type LocationHint = (typeof LOCATION_HINTS)[number];\n","/**\n * What surrounds a status page's content, its \"frame\": the heading's texts (title,\n * description), the logo and the website it links to, the header's navigation and the footer.\n * Written in status.config.ts (`pages[]`), and replaceable per field in the admin UI, which\n * validates with the same schemas (shared/admin-api.ts).\n *\n * Data only, never HTML or components, so that the page keeps its Content-Security-Policy\n * (`script-src 'self'`, `style-src 'self'`) and the prebuilt client of the npm package can\n * show it.\n */\nimport * as z from \"zod\";\n\n/**\n * A text an operator writes: one for every language (`\"Docs\"`), or one per language, by BCP 47\n * tag (`{ en: \"Docs\", ja: \"ドキュメント\" }`). A page shows the visitor's language, else English,\n * else the first one written.\n */\nexport type LocalizedText = string | { readonly [languageTag: string]: string };\n\n/** Limits of a frame's texts and links. Lengths are in characters (UTF-16 code units). */\nexport const FRAME_LIMITS = {\n\ttitle: 100,\n\tdescription: 1_000,\n\t/** Entries of the header's navigation: links and menus. */\n\tnavItems: 6,\n\t/** Links in a menu of the header's navigation. */\n\tmenuItems: 10,\n\tfooterColumns: 4,\n\t/** Links in a column of the footer. */\n\tcolumnLinks: 10,\n\t/** Links in the footer's line of links. */\n\tfooterLinks: 10,\n\t/** A link's label, a menu's label, a column's title. */\n\tlabel: 50,\n\turl: 500,\n\tfooterText: 500,\n\t/** Languages of a text written per language. */\n\tlanguages: 10,\n\t/**\n\t * Largest admin API request that sets a page's appearance (`PUT\n\t * /api/admin/pages/:pageId/appearance`), in bytes: above the largest frame these limits allow\n\t * (FRAME_LIMITS tests check it), which other requests' 64 KiB is not.\n\t */\n\tappearanceRequestBytes: 512 * 1024,\n} as const;\n\nexport interface NavLink {\n\tlabel: LocalizedText;\n\t/**\n\t * An `https:`, `http:` or `mailto:` URL, or a path on this site starting with `/` (another\n\t * status page, say).\n\t */\n\turl: string;\n}\n\n/** A button in the header's navigation that opens a list of links. Menus do not nest. */\nexport interface NavMenu {\n\tlabel: LocalizedText;\n\t/** At least one. */\n\titems: readonly NavLink[];\n}\n\nexport type NavItem = NavLink | NavMenu;\n\nexport interface HeaderConfig {\n\t/** Links and menus, in order, at most 6. */\n\tnav?: readonly NavItem[];\n}\n\nexport interface FooterColumn {\n\ttitle: LocalizedText;\n\t/** At least one, at most 10. */\n\tlinks: readonly NavLink[];\n}\n\nexport interface FooterConfig {\n\t/** Columns of links under a title, at most 4. */\n\tcolumns?: readonly FooterColumn[];\n\t/** A line of links, at most 10. */\n\tlinks?: readonly NavLink[];\n\t/** A line of text, such as a copyright notice, at most 500 characters. */\n\ttext?: LocalizedText;\n}\n\nexport interface ResolvedNavLink {\n\treadonly label: LocalizedText;\n\treadonly url: string;\n}\n\nexport interface ResolvedNavMenu {\n\treadonly label: LocalizedText;\n\treadonly items: readonly ResolvedNavLink[];\n}\n\nexport type ResolvedNavItem = ResolvedNavLink | ResolvedNavMenu;\n\nexport interface ResolvedHeader {\n\treadonly nav: readonly ResolvedNavItem[];\n}\n\nexport interface ResolvedFooterColumn {\n\treadonly title: LocalizedText;\n\treadonly links: readonly ResolvedNavLink[];\n}\n\nexport interface ResolvedFooter {\n\treadonly columns: readonly ResolvedFooterColumn[];\n\treadonly links: readonly ResolvedNavLink[];\n\treadonly text: LocalizedText | null;\n}\n\n/**\n * A page's frame as status.config.ts sets it, before the administrators' changes. `null`:\n * not set (the default: the page's ID for the title, nothing for the others).\n */\nexport interface ResolvedFrame {\n\treadonly title: LocalizedText | null;\n\treadonly description: LocalizedText | null;\n\t/** https only. */\n\treadonly logoUrl: string | null;\n\treadonly websiteUrl: string | null;\n\treadonly header: ResolvedHeader;\n\treadonly footer: ResolvedFooter;\n}\n\n/** Whether a navigation entry is a menu (has `items`) rather than a link. */\nexport function isNavMenu(item: ResolvedNavItem): item is ResolvedNavMenu {\n\treturn \"items\" in item;\n}\n\n/** A header without navigation. */\nexport const EMPTY_HEADER: ResolvedHeader = { nav: [] };\n\n/** A footer with nothing but the page's own lines (time zone, language). */\nexport const EMPTY_FOOTER: ResolvedFooter = { columns: [], links: [], text: null };\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\n/** A refinement's issue, with a code the admin UI translates (shared/admin-api.ts `ApiIssue`). */\nfunction issue(message: string, code: string, path: PropertyKey[] = []) {\n\treturn { code: \"custom\" as const, message, path, params: { code } };\n}\n\n/**\n * Control characters but tabs and line breaks: nothing a text needs, and JSON writes each as six\n * bytes (`\\u0001`), which would let a text grow six times its length in the status response.\n */\nconst CONTROL_CHARACTER = /[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/;\n\n/**\n * A {@link LocalizedText} of at most `maxLength` characters per language, trimmed. Language\n * tags are written in their canonical form (`pt-br` → `pt-BR`). With `allowEmpty`, `\"\"` is\n * accepted (an administrator clearing a text that status.config.ts sets); never an empty\n * text in one language: leave that language out instead.\n */\nexport function localizedTextSchema(maxLength: number, { allowEmpty = false }: { readonly allowEmpty?: boolean } = {}) {\n\tconst text = z.string().trim().max(maxLength).refine((value) => !CONTROL_CHARACTER.test(value), {\n\t\tmessage: \"must not contain control characters (other than tabs and line breaks)\",\n\t\tparams: { code: \"control_character\" },\n\t});\n\t// No transform in the options: a union reports the issues of the one option whose issues do\n\t// not abort, where they are, and a transform (a pipe) aborts. Otherwise it says \"Invalid input\".\n\tconst byLanguage = z\n\t\t.record(z.string(), text.min(1))\n\t\t.superRefine((texts, ctx) => {\n\t\t\tconst tags = Object.keys(texts);\n\t\t\tif (tags.length === 0) ctx.addIssue(issue(\"must have a text in at least one language\", \"no_language\"));\n\t\t\tif (tags.length > FRAME_LIMITS.languages) {\n\t\t\t\tctx.addIssue(issue(`must have at most ${FRAME_LIMITS.languages} languages`, \"too_many_languages\"));\n\t\t\t}\n\t\t\tconst seen = new Set<string>();\n\t\t\tfor (const tag of tags) {\n\t\t\t\tconst name = canonicalTag(tag);\n\t\t\t\tif (name === undefined) {\n\t\t\t\t\tctx.addIssue(issue(`\"${tag}\" is not a language tag; use one such as \"en\" or \"ja\"`, \"language_tag\", [tag]));\n\t\t\t\t} else if (seen.has(name)) {\n\t\t\t\t\tctx.addIssue(issue(`language \"${name}\" is written twice`, \"duplicate_language\", [tag]));\n\t\t\t\t}\n\t\t\t\tif (name !== undefined) seen.add(name);\n\t\t\t}\n\t\t});\n\treturn z\n\t\t.union([allowEmpty ? text : text.min(1), byLanguage])\n\t\t.transform((value): LocalizedText =>\n\t\t\ttypeof value === \"string\" ? value : Object.fromEntries(Object.entries(value).map(([tag, item]) => [canonicalTag(tag) ?? tag, item])),\n\t\t);\n}\n\n/** The canonical form of a BCP 47 tag (`pt-br` → `pt-BR`), or `undefined` when it is not one. */\nfunction canonicalTag(tag: string): string | undefined {\n\ttry {\n\t\treturn Intl.getCanonicalLocales(tag)[0];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nconst SITE = \"https://site.invalid\";\n\nfunction parseUrl(value: string, base?: string): URL | null {\n\ttry {\n\t\treturn new URL(value, base);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * A link's URL: `https:`, `http:` or `mailto:` (never `javascript:` and the like), without\n * credentials, or a path on this site (`/`, `/pages/other`, but not `//host`, which is another\n * site). Written back as the URL parser normalises it, and limited in that form: encoding can\n * make a URL several times longer (\"あ\" is \"%E3%81%82\"), and the encoded URL is what is stored\n * and served.\n */\nexport const navUrlSchema = z\n\t.string()\n\t.trim()\n\t.min(1)\n\t.max(FRAME_LIMITS.url)\n\t.transform((value, ctx) => {\n\t\tif (value.startsWith(\"/\")) {\n\t\t\t// Resolved against a placeholder: a path that leaves this site (\"//host\", \"/\\host\") changes the origin.\n\t\t\tconst url = parseUrl(value, SITE);\n\t\t\tconst path = url?.href.slice(SITE.length);\n\t\t\t// The path as normalised must stay on this site too: removing dot segments can leave\n\t\t\t// one that starts with \"//\" (\"/a/..//host\", \"/.//host\"), another site. Resolving it\n\t\t\t// again must give the same URL, which is also what reading it back from D1 does.\n\t\t\tif (url === null || url.origin !== SITE || path === undefined || parseUrl(path, SITE)?.href !== url.href || path.startsWith(\"//\")) {\n\t\t\t\tctx.addIssue(issue('must be a path on this site, such as \"/pages/other\", or a full URL', \"nav_url\"));\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\treturn encodedLength(path, ctx);\n\t\t}\n\t\tconst url = parseUrl(value);\n\t\tif (url === null || (url.protocol !== \"https:\" && url.protocol !== \"http:\" && url.protocol !== \"mailto:\")) {\n\t\t\tctx.addIssue(issue('must be an https, http or mailto URL, or a path on this site starting with \"/\"', \"nav_url\"));\n\t\t\treturn z.NEVER;\n\t\t}\n\t\tif (url.username !== \"\" || url.password !== \"\") {\n\t\t\tctx.addIssue(issue(\"must not contain credentials\", \"url_credentials\"));\n\t\t\treturn z.NEVER;\n\t\t}\n\t\treturn encodedLength(url.href, ctx);\n\t});\n\n/** `url` when it is at most `FRAME_LIMITS.url` characters once encoded; else an issue. */\nfunction encodedLength(url: string, ctx: z.core.$RefinementCtx): string {\n\tif (url.length <= FRAME_LIMITS.url) return url;\n\tctx.addIssue({\n\t\t...issue(`must be at most ${FRAME_LIMITS.url} characters once encoded (it is ${url.length}; a character other than ASCII counts as its encoding, such as \"%E3%81%82\")`, \"url_too_long\"),\n\t\tparams: { code: \"url_too_long\", maximum: FRAME_LIMITS.url },\n\t});\n\treturn z.NEVER;\n}\n\nconst labelSchema = localizedTextSchema(FRAME_LIMITS.label);\n\nexport const navLinkSchema = z.strictObject({ label: labelSchema, url: navUrlSchema });\n\n/**\n * A link (`url`) or a menu (`items`). One object schema with both, rather than a union, so that\n * a problem in either is reported where it is (a union reports only that neither matched).\n */\nconst navItemSchema = z\n\t.strictObject({\n\t\tlabel: labelSchema,\n\t\turl: navUrlSchema.optional(),\n\t\titems: z.array(navLinkSchema).min(1).max(FRAME_LIMITS.menuItems).optional(),\n\t})\n\t.superRefine((item, ctx) => {\n\t\tif ((item.url === undefined) === (item.items === undefined)) {\n\t\t\tctx.addIssue(issue('needs either \"url\" (a link) or \"items\" (a menu), not both', \"link_or_menu\"));\n\t\t}\n\t})\n\t.transform((item): ResolvedNavItem => (item.items === undefined ? { label: item.label, url: item.url ?? \"\" } : { label: item.label, items: item.items }));\n\nexport const headerSchema = z.strictObject({\n\tnav: z.array(navItemSchema).max(FRAME_LIMITS.navItems).default([]),\n});\n\nconst footerColumnSchema = z.strictObject({\n\ttitle: labelSchema,\n\tlinks: z.array(navLinkSchema).min(1).max(FRAME_LIMITS.columnLinks),\n});\n\nexport const footerSchema = z\n\t.strictObject({\n\t\tcolumns: z.array(footerColumnSchema).max(FRAME_LIMITS.footerColumns).default([]),\n\t\tlinks: z.array(navLinkSchema).max(FRAME_LIMITS.footerLinks).default([]),\n\t\t// `null` as the resolved footer has it: worker/db/appearance.ts stores that, and reads it\n\t\t// back with this schema.\n\t\ttext: localizedTextSchema(FRAME_LIMITS.footerText).nullish(),\n\t})\n\t.transform((footer): ResolvedFooter => ({ columns: footer.columns, links: footer.links, text: footer.text ?? null }));\n","import type { Capability } from \"./provider\";\n\n/**\n * Declares a runner (the environment that executes checks) and what it can do.\n * Results are stored per monitor × runner, so `id` must be stable.\n */\nexport interface RunnerDeclaration {\n\t/** Stable identifier, for example `\"cloudflare\"` for the built-in runner. */\n\treadonly id: string;\n\treadonly capabilities: readonly Capability[];\n\t/**\n\t * The longest monitor `timeout` this runner accepts, in milliseconds. A monitor with a\n\t * longer timeout is rejected when the configuration is loaded. Omit for no limit.\n\t */\n\treadonly maxTimeoutMs?: number;\n}\n\n/** Returns the capabilities in `required` that `runner` does not provide. */\nexport function missingCapabilities(\n\trequired: readonly Capability[],\n\trunner: RunnerDeclaration,\n): Capability[] {\n\treturn required.filter((capability) => !runner.capabilities.includes(capability));\n}\n","import * as z from \"zod\";\nimport type { AuthProvider } from \"./auth\";\nimport { type Duration, durationSchema } from \"./duration\";\nimport { LOCATION_HINTS, type LocationHint } from \"./location\";\nimport { type MonitorDefinition, RESERVED_MONITOR_KEYS } from \"./monitor\";\nimport type { NotifierKind } from \"./notifier\";\nimport {\n\tFRAME_LIMITS,\n\ttype FooterConfig,\n\tfooterSchema,\n\ttype HeaderConfig,\n\theaderSchema,\n\ttype LocalizedText,\n\tlocalizedTextSchema,\n\ttype ResolvedFrame,\n} from \"./frame\";\nimport { DEFAULT_PAGE_TEMPLATE, PAGE_TEMPLATES, type PageTemplate } from \"./page-templates\";\nimport type { CheckProvider } from \"./provider\";\nimport { missingCapabilities, type RunnerDeclaration } from \"./runner\";\nimport { secretNames } from \"./secret\";\n\n// ---------------------------------------------------------------------------\n// Input: what users write in status.config.ts\n// ---------------------------------------------------------------------------\n\nexport interface StatusConfig {\n\t/** IANA time zone that decides where each day starts for daily uptime. Default: `\"UTC\"`. */\n\ttimezone?: string;\n\t/** Default location for monitors; each monitor can override it. When omitted, Cloudflare chooses. */\n\tlocation?: LocationHint;\n\t/**\n\t * How long check results are kept: at least `\"1d\"`, and at least 10 times every monitor's\n\t * `interval`. Default: forever. Shortening it deletes older results, gradually, and they\n\t * cannot be recovered.\n\t */\n\tretention?: Duration;\n\t/**\n\t * Authentication for the admin UI and admin API.\n\t * When omitted, both reject every request.\n\t */\n\tauth?: AuthProvider;\n\t/** Notifier kinds offered in the admin UI. Targets and their secrets are not configured here. */\n\tnotifiers?: readonly NotifierKind[];\n\t/**\n\t * Language of notifications and of the text of automatic incidents, as a BCP 47 tag\n\t * such as `\"ja\"`. Default: `\"en\"`. A language without a translation falls back to English.\n\t */\n\tlocale?: string;\n\t/**\n\t * Where this deployment is reachable, such as `\"https://status.example.com\"`, for links in\n\t * notifications (the admin UI's \"create an incident\" form). Without it, notifications\n\t * have no links.\n\t */\n\tbaseUrl?: string;\n\t/** Notification settings that are not per target (targets are managed in the admin UI). */\n\tnotifications?: NotificationsConfig;\n\t/** Monitors, each created by a provider factory such as `http({ … })`. */\n\tmonitors?: readonly MonitorDefinition[];\n\t/** Public status pages. */\n\tpages?: readonly PageConfig[];\n\t/** The public API that status pages read. */\n\tpublicApi?: PublicApiConfig;\n\t/**\n\t * Host names (with the port, if not the default) on which the admin UI and admin API answer,\n\t * such as `[\"status.example.com\"]`, or `\"baseUrl\"` for the host of `baseUrl`. Requests for\n\t * them on any other host name (a `*.workers.dev` URL without Cloudflare Access, say) get the\n\t * same 403 as a failed sign-in. Default: any host name.\n\t */\n\tadminHosts?: \"baseUrl\" | readonly string[];\n}\n\nexport interface NotificationsConfig {\n\t/**\n\t * How often the every-minute Cron looks for monitors whose results stopped arriving\n\t * (`unknown`) to notify administrators. Whole minutes from `\"1m\"` (the default) to\n\t * `\"1h\"`. A longer interval delays those notifications but saves Durable Object requests,\n\t * which the Free plan limits per day.\n\t */\n\tunknownCheckInterval?: Duration;\n}\n\n/** Placeholders the texts of automatic incidents may use. */\nexport const INCIDENT_TEMPLATE_PLACEHOLDERS = [\"components\", \"monitor\", \"time\"] as const;\n\n/**\n * Texts of automatic incidents (`incidents.auto`), replacing the translated defaults.\n * They may use `{components}` (the affected components' names), `{monitor}` (the monitor's\n * name) and `{time}` (when it happened, in `timezone`).\n */\nexport interface IncidentTemplates {\n\t/** Title of a new incident. */\n\ttitle?: string;\n\t/** First update of a new incident (stage \"investigating\"). */\n\tinvestigating?: string;\n\t/** Update added to an unresolved incident of the same component. */\n\tupdate?: string;\n\t/** Update that resolves an automatic incident on recovery. */\n\tresolved?: string;\n\t/** Update that resolves an automatic incident when its monitor leaves the configuration while down. */\n\tstopped?: string;\n\t/** Update that reopens an automatic incident resolved less than `reopenWithin` ago. */\n\treopened?: string;\n\t/** Update when a monitor goes from `down` to `degraded`: the incident stays open. */\n\tpartial?: string;\n}\n\n/** Where public API responses are kept for 30 seconds. */\nexport type PublicApiCache = \"durable-object\" | \"workers-cache\";\n\nexport interface PublicApiConfig {\n\t/**\n\t * Where responses are kept for 30 seconds. Default: `\"durable-object\"`.\n\t *\n\t * - `\"durable-object\"`: in the memory of each page's Durable Object. One Worker request and\n\t * one Durable Object request per API call; an administrator's change shows at once\n\t * everywhere. A page's object takes about 1,000 requests per second at most.\n\t * - `\"workers-cache\"`: in Cloudflare's Workers Cache, in front of the Worker, near visitors.\n\t * Scales without limit, but every API call is billed as two Worker requests, and\n\t * purging after a change is rate-limited (a refused purge expires within 30 seconds).\n\t */\n\tcache?: PublicApiCache;\n\t/**\n\t * Web pages on other sites whose scripts may read the public API (CORS): `\"*\"` for any,\n\t * or exact origins such as `\"https://www.example.com\"`. Default: none. Never applies to the\n\t * admin API.\n\t */\n\tallowedOrigins?: \"*\" | readonly string[];\n}\n\nexport interface PageConfig {\n\t/** Unique identifier, with the same rules as monitor IDs. */\n\tid: string;\n\t/**\n\t * How the page looks: `\"default\"`, or `\"modern\"` (a dark header over one card, with\n\t * component groups, response times and a light/dark switch). Default: `\"default\"`. Both show\n\t * the same data from the same public API.\n\t */\n\ttemplate?: PageTemplate;\n\t/**\n\t * Where visitors report a problem, linked from the page's header (\"Report a problem\"): an\n\t * `https:` or `http:` URL, or `mailto:`. Shown by the `\"modern\"` template. Default: none.\n\t */\n\treportUrl?: string;\n\t/**\n\t * The heading and the browser tab's title: a text, or texts by language\n\t * (`{ en: \"Example Status\", ja: \"Example ステータス\" }`). Default: the page's ID. The admin\n\t * UI can replace it.\n\t */\n\ttitle?: LocalizedText;\n\t/** A line under the heading, as `title`. The admin UI can replace or clear it. */\n\tdescription?: LocalizedText;\n\t/**\n\t * An image shown instead of the title text: an `https:` URL. An image uploaded in the admin UI\n\t * is shown instead; the admin UI can also replace or clear this URL.\n\t */\n\tlogoUrl?: string;\n\t/**\n\t * Where the heading links to, such as the organisation's website (`https:` or `http:`).\n\t * Default: the status page itself. The admin UI can replace or clear it.\n\t */\n\twebsiteUrl?: string;\n\t/** The header's navigation: links, and menus of links. The admin UI can replace it as a whole. */\n\theader?: HeaderConfig;\n\t/**\n\t * Columns of links, a line of links and a line of text (a copyright notice, say), above the\n\t * time zone and the language. The admin UI can replace it as a whole.\n\t */\n\tfooter?: FooterConfig;\n\tincidents?: {\n\t\t/** Publish an \"investigating\" incident automatically when `down` is confirmed. Default: `false`. */\n\t\tauto?: boolean;\n\t\t/** Texts of automatic incidents, replacing the translated defaults. */\n\t\ttemplates?: IncidentTemplates;\n\t\t/**\n\t\t * A component confirmed `down` again within this long after automation resolved its\n\t\t * incident reopens that incident (with an update) instead of publishing a new one, so\n\t\t * that a flapping service does not fill the page with incidents. Never an incident an\n\t\t * administrator edited. `\"0m\"` turns it off. Default: `\"30m\"`; at most `\"1d\"`.\n\t\t */\n\t\treopenWithin?: Duration;\n\t};\n\t/**\n\t * What the page lists, in order: components, and groups of components. Monitors that are in\n\t * no component are not public.\n\t */\n\tcomponents?: readonly (ComponentConfig | ComponentGroupConfig)[];\n}\n\nexport interface ComponentConfig {\n\t/**\n\t * Identifier, unique within the page, with the same rules as monitor IDs. Incidents and\n\t * maintenance refer to components by ID, so keep it when renaming the component.\n\t */\n\tid: string;\n\t/** Display name. Optional only for a component with exactly one monitor, whose name is used. */\n\tname?: string;\n\t/** The component shows the worst state of these monitors. Without monitors, only incidents set its state. */\n\tmonitors?: readonly string[];\n\t/**\n\t * Publish the response times of its monitors: averages over the last 24 hours, 7 days and\n\t * 30 days, with the 95th percentile. Needs at least one monitor. Shown by the `\"modern\"`\n\t * template. Default: `false`.\n\t */\n\tlatency?: boolean;\n}\n\n/**\n * Components shown together under one name, folded by default (the `\"modern\"` template; the\n * `\"default\"` template lists the components one by one). Display only: incidents and\n * maintenance still affect components, and the group shows the worst of its components.\n */\nexport interface ComponentGroupConfig {\n\t/** Identifier, with the same rules as component IDs, unique among the page's components and groups. */\n\tid: string;\n\tname: string;\n\t/** At least one; groups do not nest. */\n\tcomponents: readonly ComponentConfig[];\n}\n\n/** Gives `status.config.ts` type checking and completion. Validation happens when the Worker loads it. */\nexport function defineConfig(config: StatusConfig): StatusConfig {\n\treturn config;\n}\n\n/**\n * Shorthand for a component made of a single monitor. Its ID is the monitor ID and its\n * name is the monitor's name unless `name` is given.\n */\nexport function component(monitorId: string, options: { name?: string; latency?: boolean } = {}): ComponentConfig {\n\treturn { id: monitorId, ...options, monitors: [monitorId] };\n}\n\n// ---------------------------------------------------------------------------\n// Output: the validated configuration with defaults applied\n// ---------------------------------------------------------------------------\n\nexport interface ResolvedConfirmation {\n\treadonly failureThreshold: number;\n\treadonly successThreshold: number;\n\treadonly recheckIntervalMs: number;\n}\n\nexport interface ResolvedMonitor {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly provider: CheckProvider;\n\t/**\n\t * Provider options after validation and defaults. May contain `secret()` references;\n\t * run checks with `runCheck`, which resolves them.\n\t */\n\treadonly options: unknown;\n\t/** Names of the secrets the options reference. */\n\treadonly secrets: readonly string[];\n\treadonly intervalMs: number;\n\treadonly timeoutMs: number;\n\treadonly location: LocationHint | undefined;\n\treadonly confirmation: ResolvedConfirmation;\n\t/** IDs of the runners that check this monitor. Results are kept per monitor × runner. */\n\treadonly runners: readonly string[];\n}\n\nexport interface ResolvedComponent {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly monitors: readonly string[];\n\t/** Whether its monitors' response times are public. */\n\treadonly latency: boolean;\n}\n\nexport interface ResolvedGroup {\n\treadonly id: string;\n\treadonly name: string;\n\t/** IDs of its components, in order; they are next to each other in the page's `components`. */\n\treadonly components: readonly string[];\n}\n\nexport interface ResolvedPage {\n\treadonly id: string;\n\treadonly template: PageTemplate;\n\t/** `null` when not configured. */\n\treadonly reportUrl: string | null;\n\t/** Heading, header and footer as status.config.ts sets them; the admin UI's changes apply over them. */\n\treadonly frame: ResolvedFrame;\n\treadonly incidents: {\n\t\treadonly auto: boolean;\n\t\treadonly templates: Readonly<IncidentTemplates>;\n\t\t/** 0: never reopen. */\n\t\treadonly reopenWithinMs: number;\n\t};\n\t/** Every component, those of groups included, in the order of the page. */\n\treadonly components: readonly ResolvedComponent[];\n\treadonly groups: readonly ResolvedGroup[];\n}\n\nexport interface ResolvedPublicApi {\n\treadonly cache: PublicApiCache;\n\t/** `\"*\"`, or the exact origins allowed (empty: CORS is off). */\n\treadonly allowedOrigins: \"*\" | readonly string[];\n}\n\nexport interface ResolvedConfig {\n\treadonly timezone: string;\n\t/** `null` keeps results forever. */\n\treadonly retentionMs: number | null;\n\t/** `undefined`: no auth provider, so the admin UI and admin API reject every request. */\n\treadonly auth: AuthProvider | undefined;\n\treadonly notifiers: readonly NotifierKind[];\n\t/** Canonical BCP 47 tag. */\n\treadonly locale: string;\n\t/** Without a trailing slash; `null` when not configured. */\n\treadonly baseUrl: string | null;\n\treadonly notifications: { readonly unknownCheckIntervalMs: number };\n\treadonly monitors: readonly ResolvedMonitor[];\n\treadonly pages: readonly ResolvedPage[];\n\treadonly publicApi: ResolvedPublicApi;\n\t/** Lowercase hosts (`host[:port]`) the admin UI and API answer on; `null` for any. */\n\treadonly adminHosts: readonly string[] | null;\n}\n\nexport interface ConfigIssue {\n\t/** Where the problem is, such as `monitors[0] (\"api\").url`. Empty for the configuration as a whole. */\n\treadonly path: string;\n\treadonly message: string;\n}\n\n/** Thrown by {@link resolveConfig} with every problem found, not just the first. */\nexport class ConfigError extends Error {\n\toverride readonly name = \"ConfigError\";\n\treadonly issues: readonly ConfigIssue[];\n\n\tconstructor(issues: readonly ConfigIssue[]) {\n\t\tconst lines = issues.map((issue) =>\n\t\t\tissue.path === \"\" ? ` - ${issue.message}` : ` - ${issue.path}: ${issue.message}`,\n\t\t);\n\t\tsuper([\"Invalid status.config.ts:\", ...lines].join(\"\\n\"));\n\t\tthis.issues = issues;\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;\nconst DAY_MS = 86_400_000;\nconst DEFAULT_TIMEOUT: Duration = \"10s\";\n/** `retention` must cover at least this many intervals of every monitor. */\nconst MIN_INTERVALS_RETAINED = 10;\n\nconst idSchema = z\n\t.string()\n\t.regex(\n\t\tID_PATTERN,\n\t\t'must be 1-64 characters of lowercase letters, digits, \"-\" or \"_\", starting with a letter or digit',\n\t);\n\nfunction positiveDuration(): z.ZodType<number, Duration> {\n\treturn durationSchema().refine((ms) => ms > 0, \"must be longer than 0\");\n}\n\nconst UNITS: readonly [string, number][] = [\n\t[\"d\", DAY_MS],\n\t[\"h\", 3_600_000],\n\t[\"m\", 60_000],\n\t[\"s\", 1_000],\n];\n\n/** Milliseconds back to the largest exact unit, for messages: 90000 -> \"90s\". */\nfunction formatDuration(ms: number): string {\n\tconst unit = UNITS.find(([, size]) => ms % size === 0);\n\treturn unit ? `${ms / unit[1]}${unit[0]}` : `${ms}ms`;\n}\n\nconst timezoneSchema = z.string().transform((value, ctx) => {\n\ttry {\n\t\t// Also normalizes the spelling, e.g. \"asia/tokyo\" -> \"Asia/Tokyo\".\n\t\treturn new Intl.DateTimeFormat(\"en-US\", { timeZone: value }).resolvedOptions().timeZone;\n\t} catch {\n\t\tctx.addIssue(`unknown time zone \"${value}\"; use an IANA name such as \"Asia/Tokyo\"`);\n\t\treturn z.NEVER;\n\t}\n});\n\nconst confirmationSchema = z.strictObject({\n\tfailureThreshold: z.int().min(1).default(2),\n\tsuccessThreshold: z.int().min(1).default(1),\n\trecheckInterval: positiveDuration().prefault(\"15s\"),\n});\n\nconst monitorSettingsSchema = z.strictObject({\n\tid: idSchema,\n\tname: z.string().min(1).optional(),\n\tinterval: positiveDuration(),\n\ttimeout: positiveDuration().prefault(DEFAULT_TIMEOUT),\n\tlocation: z.enum(LOCATION_HINTS).optional(),\n\tconfirmation: confirmationSchema.prefault({}),\n});\n\nconst componentSchema = z.strictObject({\n\tid: idSchema,\n\tname: z.string().min(1).optional(),\n\tmonitors: z.array(z.string()).default([]),\n\tlatency: z.boolean().default(false),\n});\n\nconst groupSchema = z.strictObject({\n\tid: idSchema,\n\tname: z.string().trim().min(1),\n\t// Validated one by one, as the page's components.\n\tcomponents: z.array(z.unknown()).min(1, \"must list at least one component\"),\n});\n\n/** An entry of `components` that is a group (it has `components` of its own). */\nfunction isGroupEntry(value: unknown): boolean {\n\treturn isObject(value) && \"components\" in value;\n}\n\nconst reportUrlSchema = z\n\t.string()\n\t.max(2_000)\n\t.transform((value, ctx) => {\n\t\tlet url: URL;\n\t\ttry {\n\t\t\turl = new URL(value);\n\t\t} catch {\n\t\t\tctx.addIssue('must be a URL such as \"https://example.com/support\" or \"mailto:support@example.com\"');\n\t\t\treturn z.NEVER;\n\t\t}\n\t\tif (url.protocol !== \"https:\" && url.protocol !== \"http:\" && url.protocol !== \"mailto:\") {\n\t\t\tctx.addIssue(\"must be an https, http or mailto URL\");\n\t\t\treturn z.NEVER;\n\t\t}\n\t\tif (url.username !== \"\" || url.password !== \"\") {\n\t\t\tctx.addIssue(\"must not contain credentials\");\n\t\t\treturn z.NEVER;\n\t\t}\n\t\treturn url.href;\n\t});\n\n/** `https:`, or also `http:` with `http`; never with credentials. */\nfunction webUrlSchema({ http }: { readonly http: boolean }) {\n\treturn z\n\t\t.string()\n\t\t.trim()\n\t\t.max(2_000)\n\t\t.transform((value, ctx) => {\n\t\t\tlet url: URL;\n\t\t\ttry {\n\t\t\t\turl = new URL(value);\n\t\t\t} catch {\n\t\t\t\tctx.addIssue('must be a URL such as \"https://example.com/\"');\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\tif (url.protocol !== \"https:\" && !(http && url.protocol === \"http:\")) {\n\t\t\t\tctx.addIssue(http ? \"must be an https or http URL\" : \"must be an https URL (the page's Content-Security-Policy loads https images only)\");\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\tif (url.username !== \"\" || url.password !== \"\") {\n\t\t\t\tctx.addIssue(\"must not contain credentials\");\n\t\t\t\treturn z.NEVER;\n\t\t\t}\n\t\t\treturn url.href;\n\t\t});\n}\n\nconst PLACEHOLDER = /\\{([^{}]*)\\}/g;\nconst KNOWN_PLACEHOLDERS: ReadonlySet<string> = new Set(INCIDENT_TEMPLATE_PLACEHOLDERS);\n\nfunction templateSchema(maxLength: number) {\n\treturn z\n\t\t.string()\n\t\t.trim()\n\t\t.min(1)\n\t\t.max(maxLength)\n\t\t.superRefine((text, ctx) => {\n\t\t\tfor (const match of text.matchAll(PLACEHOLDER)) {\n\t\t\t\tif (!KNOWN_PLACEHOLDERS.has(match[1] as string)) {\n\t\t\t\t\tctx.addIssue(\n\t\t\t\t\t\t`unknown placeholder ${match[0]}; use ${INCIDENT_TEMPLATE_PLACEHOLDERS.map((name) => `{${name}}`).join(\", \")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n}\n\nconst templatesSchema = z.strictObject({\n\ttitle: templateSchema(200).optional(),\n\tinvestigating: templateSchema(2_000).optional(),\n\tupdate: templateSchema(2_000).optional(),\n\tresolved: templateSchema(2_000).optional(),\n\tstopped: templateSchema(2_000).optional(),\n\treopened: templateSchema(2_000).optional(),\n\tpartial: templateSchema(2_000).optional(),\n});\n\nconst DEFAULT_REOPEN_WITHIN: Duration = \"30m\";\n\nconst pageSchema = z.strictObject({\n\tid: idSchema,\n\ttemplate: z.enum(PAGE_TEMPLATES).default(DEFAULT_PAGE_TEMPLATE),\n\treportUrl: reportUrlSchema.optional(),\n\ttitle: localizedTextSchema(FRAME_LIMITS.title).optional(),\n\tdescription: localizedTextSchema(FRAME_LIMITS.description).optional(),\n\tlogoUrl: webUrlSchema({ http: false }).optional(),\n\twebsiteUrl: webUrlSchema({ http: true }).optional(),\n\theader: headerSchema.prefault({}),\n\tfooter: footerSchema.prefault({}),\n\tincidents: z\n\t\t.strictObject({\n\t\t\tauto: z.boolean().default(false),\n\t\t\ttemplates: templatesSchema.default({}),\n\t\t\treopenWithin: durationSchema()\n\t\t\t\t.refine((ms) => ms <= DAY_MS, \"must be at most 1d\")\n\t\t\t\t.prefault(DEFAULT_REOPEN_WITHIN),\n\t\t})\n\t\t.prefault({}),\n\t// Components are validated one by one, so that one bad entry does not hide the others.\n\tcomponents: z.array(z.unknown()).default([]),\n});\n\n/** An origin as browsers send it in `Origin`: scheme, host and port if not the default, lowercase. */\nconst originSchema = z.string().refine((value) => {\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn (url.protocol === \"https:\" || url.protocol === \"http:\") && url.origin === value;\n\t} catch {\n\t\treturn false;\n\t}\n}, 'must be an origin such as \"https://www.example.com\": lowercase, with no path, query or trailing slash, and no default port');\n\nconst publicApiSchema = z\n\t.strictObject({\n\t\tcache: z.enum([\"durable-object\", \"workers-cache\"]).default(\"durable-object\"),\n\t\tallowedOrigins: z\n\t\t\t.union([\n\t\t\t\tz.literal(\"*\"),\n\t\t\t\tz.array(originSchema).superRefine((origins, ctx) => {\n\t\t\t\t\torigins.forEach((origin, index) => {\n\t\t\t\t\t\tif (origins.indexOf(origin) !== index) {\n\t\t\t\t\t\t\tctx.addIssue({ code: \"custom\", message: `\"${origin}\" is listed twice`, path: [index] });\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}),\n\t\t\t])\n\t\t\t.default([]),\n\t})\n\t.prefault({});\n\nconst localeSchema = z.string().transform((value, ctx) => {\n\ttry {\n\t\tconst [canonical] = Intl.getCanonicalLocales(value);\n\t\tif (canonical !== undefined) return canonical;\n\t} catch {\n\t\t// Reported below.\n\t}\n\tctx.addIssue(`\"${value}\" is not a language tag; use one such as \"en\" or \"ja\"`);\n\treturn z.NEVER;\n});\n\nconst baseUrlSchema = z.string().transform((value, ctx) => {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tctx.addIssue('must be a URL such as \"https://status.example.com\"');\n\t\treturn z.NEVER;\n\t}\n\tif (url.protocol !== \"https:\" && url.protocol !== \"http:\") ctx.addIssue(\"must be an http or https URL\");\n\tif (url.username !== \"\" || url.password !== \"\") ctx.addIssue(\"must not contain credentials\");\n\tif (url.search !== \"\" || url.hash !== \"\") ctx.addIssue(\"must not have a query or fragment\");\n\treturn `${url.origin}${url.pathname}`.replace(/\\/+$/, \"\");\n});\n\nconst MINUTE_MS = 60_000;\n\n/** A host as `URL.host` gives it: lowercase name (or bracketed IPv6) and a port if not the default. */\nconst hostSchema = z.string().refine((value) => {\n\ttry {\n\t\tconst url = new URL(`https://${value}`);\n\t\treturn url.host === value && url.pathname === \"/\" && url.username === \"\" && url.password === \"\";\n\t} catch {\n\t\treturn false;\n\t}\n}, 'must be a host name such as \"status.example.com\" (lowercase, with a port only if it is not 443), without a scheme or path');\n\nconst adminHostsSchema = z.union([\n\tz.literal(\"baseUrl\"),\n\tz\n\t\t.array(hostSchema)\n\t\t.min(1, 'must list at least one host name, or be \"baseUrl\"')\n\t\t.superRefine((hosts, ctx) => {\n\t\t\thosts.forEach((host, index) => {\n\t\t\t\tif (hosts.indexOf(host) !== index) ctx.addIssue({ code: \"custom\", message: `\"${host}\" is listed twice`, path: [index] });\n\t\t\t});\n\t\t}),\n]);\n\nconst notificationsSchema = z\n\t.strictObject({\n\t\tunknownCheckInterval: durationSchema()\n\t\t\t.refine((ms) => ms % MINUTE_MS === 0 && ms >= MINUTE_MS && ms <= 60 * MINUTE_MS, {\n\t\t\t\tmessage: 'must be whole minutes from \"1m\" to \"1h\" (the Cron runs every minute)',\n\t\t\t})\n\t\t\t.prefault(\"1m\"),\n\t})\n\t.prefault({});\n\nconst authSchema = z.custom<AuthProvider>(\n\t(value) =>\n\t\tisObject(value) && typeof value[\"type\"] === \"string\" && typeof value[\"authenticate\"] === \"function\",\n\t\"must be an auth provider (an object with `type` and `authenticate()`)\",\n);\n\nconst TOP_LEVEL_KEYS: ReadonlySet<string> = new Set([\n\t\"timezone\",\n\t\"location\",\n\t\"retention\",\n\t\"auth\",\n\t\"notifiers\",\n\t\"locale\",\n\t\"baseUrl\",\n\t\"notifications\",\n\t\"monitors\",\n\t\"pages\",\n\t\"publicApi\",\n\t\"adminHosts\",\n] satisfies (keyof StatusConfig)[]);\n\nconst RESERVED_SETTING_KEYS: ReadonlySet<string> = new Set(RESERVED_MONITOR_KEYS);\n\n/** `value` without its `undefined` properties, so that resolved objects compare equal to what was written. */\nfunction stripUndefined<T extends object>(value: T): T {\n\treturn Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isSchema(value: unknown): boolean {\n\treturn isObject(value) && typeof value[\"safeParse\"] === \"function\";\n}\n\nfunction isNotifierKind(value: unknown): value is NotifierKind {\n\treturn (\n\t\tisObject(value) &&\n\t\ttypeof value[\"type\"] === \"string\" &&\n\t\tisSchema(value[\"options\"]) &&\n\t\tArray.isArray(value[\"secretOptions\"]) &&\n\t\ttypeof value[\"send\"] === \"function\"\n\t);\n}\n\nfunction isMonitorDefinition(value: unknown): value is MonitorDefinition {\n\tif (!isObject(value)) return false;\n\tconst provider = value[\"provider\"];\n\treturn (\n\t\tisObject(provider) &&\n\t\ttypeof provider[\"type\"] === \"string\" &&\n\t\ttypeof provider[\"check\"] === \"function\" &&\n\t\tArray.isArray(provider[\"requires\"]) &&\n\t\tisSchema(provider[\"options\"]) &&\n\t\tisObject(value[\"settings\"]) &&\n\t\tisObject(value[\"options\"])\n\t);\n}\n\ninterface IssueLike {\n\treadonly path: readonly PropertyKey[];\n\treadonly message: string;\n}\n\nfunction joinPath(base: string, segments: readonly PropertyKey[]): string {\n\tlet path = base;\n\tfor (const segment of segments) {\n\t\tif (typeof segment === \"number\") path += `[${segment}]`;\n\t\telse path += path === \"\" ? String(segment) : `.${String(segment)}`;\n\t}\n\treturn path;\n}\n\nexport interface ResolveOptions {\n\t/**\n\t * Runners available to the hub. Every monitor is assigned to the first one for now;\n\t * choosing runners per monitor arrives with external runners.\n\t */\n\treadonly runners: readonly RunnerDeclaration[];\n\t/**\n\t * Secrets of the hub itself, which a monitor must never reference with `secret()`: they\n\t * would be sent to the monitored endpoint (such as the key that encrypts notification\n\t * targets' secrets).\n\t */\n\treadonly reservedSecrets?: readonly string[];\n}\n\n/**\n * Validates a configuration and applies defaults. Call it when the Worker loads, so that a\n * broken configuration fails the deployment instead of failing at run time.\n * @throws ConfigError listing every problem found.\n */\nexport function resolveConfig(config: StatusConfig, { runners, reservedSecrets = [] }: ResolveOptions): ResolvedConfig {\n\tconst issues: ConfigIssue[] = [];\n\tconst report = (path: string, message: string) => issues.push({ path, message });\n\tconst collect = (base: string, found: readonly IssueLike[]) => {\n\t\tfor (const issue of found) report(joinPath(base, issue.path), issue.message);\n\t};\n\t// Each part is validated on its own, so one problem does not hide the others.\n\tconst parse = <T>(schema: z.ZodType<T, unknown>, value: unknown, path: string): T | undefined => {\n\t\tconst result = schema.safeParse(value);\n\t\tif (result.success) return result.data;\n\t\tcollect(path, result.error.issues);\n\t\treturn undefined;\n\t};\n\n\tif (!isObject(config)) {\n\t\tthrow new ConfigError([{ path: \"\", message: \"must be an object passed to defineConfig()\" }]);\n\t}\n\tconst input: Record<string, unknown> = config;\n\tfor (const key of Object.keys(input)) {\n\t\tif (!TOP_LEVEL_KEYS.has(key)) report(\"\", `Unrecognized key: \"${key}\"`);\n\t}\n\n\tconst timezone = parse(timezoneSchema.prefault(\"UTC\"), input[\"timezone\"], \"timezone\");\n\tconst location = parse(z.enum(LOCATION_HINTS).optional(), input[\"location\"], \"location\");\n\tconst retention = parse(\n\t\tdurationSchema()\n\t\t\t.refine((ms) => ms >= DAY_MS, \"must be at least 1d\")\n\t\t\t.optional(),\n\t\tinput[\"retention\"],\n\t\t\"retention\",\n\t);\n\tconst auth = parse(authSchema.optional(), input[\"auth\"], \"auth\");\n\tconst notifierEntries = parse(z.array(z.unknown()).default([]), input[\"notifiers\"], \"notifiers\") ?? [];\n\tconst monitorEntries = parse(z.array(z.unknown()).default([]), input[\"monitors\"], \"monitors\") ?? [];\n\tconst pageEntries = parse(z.array(z.unknown()).default([]), input[\"pages\"], \"pages\") ?? [];\n\tconst publicApi = parse(publicApiSchema, input[\"publicApi\"], \"publicApi\");\n\tconst locale = parse(localeSchema.prefault(\"en\"), input[\"locale\"], \"locale\");\n\tconst baseUrl = parse(baseUrlSchema.optional(), input[\"baseUrl\"], \"baseUrl\");\n\tconst notifications = parse(notificationsSchema, input[\"notifications\"], \"notifications\");\n\tconst adminHostsInput = parse(adminHostsSchema.optional(), input[\"adminHosts\"], \"adminHosts\");\n\tlet adminHosts: readonly string[] | null = null;\n\tif (adminHostsInput === \"baseUrl\") {\n\t\tif (baseUrl === undefined) {\n\t\t\tif (input[\"baseUrl\"] === undefined) report(\"adminHosts\", '\"baseUrl\" needs `baseUrl` to be set');\n\t\t} else adminHosts = [new URL(baseUrl).host];\n\t} else if (adminHostsInput !== undefined) adminHosts = adminHostsInput;\n\n\tconst runnerIds = new Set<string>();\n\tfor (const runner of runners) {\n\t\tif (runnerIds.has(runner.id)) report(\"\", `duplicate runner ID \"${runner.id}\"`);\n\t\trunnerIds.add(runner.id);\n\t}\n\tconst defaultRunner = runners[0];\n\tif (defaultRunner === undefined && monitorEntries.length > 0) {\n\t\treport(\"\", \"no runner is available to run monitors\");\n\t}\n\n\t// ---- Notifiers\n\tconst notifiers: NotifierKind[] = [];\n\tconst firstIndexOfNotifier = new Map<string, number>();\n\tnotifierEntries.forEach((notifier, index) => {\n\t\tconst path = `notifiers[${index}]`;\n\t\tif (!isNotifierKind(notifier)) {\n\t\t\treport(path, \"must be a notifier kind (an object with `type`, an `options` schema, `secretOptions` and `send()`)\");\n\t\t\treturn;\n\t\t}\n\t\tconst first = firstIndexOfNotifier.get(notifier.type);\n\t\tif (first !== undefined) {\n\t\t\treport(path, `duplicate notifier type \"${notifier.type}\" (also used by notifiers[${first}])`);\n\t\t\treturn;\n\t\t}\n\t\tfirstIndexOfNotifier.set(notifier.type, index);\n\t\tnotifiers.push(notifier);\n\t});\n\n\t// ---- Monitors\n\tconst definitions = monitorEntries.filter(isMonitorDefinition);\n\t// IDs as written, so that a monitor with other errors does not also show up as unknown.\n\tconst declaredMonitorIds = new Set(\n\t\tdefinitions.flatMap((definition) =>\n\t\t\ttypeof definition.settings.id === \"string\" ? [definition.settings.id] : [],\n\t\t),\n\t);\n\tconst firstIndexOfMonitor = new Map<string, number>();\n\tconst monitors: ResolvedMonitor[] = [];\n\n\tmonitorEntries.forEach((entry, index) => {\n\t\tif (!isMonitorDefinition(entry)) {\n\t\t\treport(`monitors[${index}]`, \"must be created by a provider factory such as http({ … })\");\n\t\t\treturn;\n\t\t}\n\t\tconst rawSettings: Record<string, unknown> = { ...entry.settings };\n\t\tconst rawId = rawSettings[\"id\"];\n\t\tconst base =\n\t\t\ttypeof rawId === \"string\" ? `monitors[${index}] (\"${rawId}\")` : `monitors[${index}]`;\n\t\tconst { provider } = entry;\n\n\t\tfor (const key of Object.keys(rawSettings)) {\n\t\t\tif (RESERVED_SETTING_KEYS.has(key)) {\n\t\t\t\treport(`${base}.${key}`, `\"${key}\" is reserved for a future monitor setting`);\n\t\t\t}\n\t\t}\n\t\tconst settings = parse(\n\t\t\tmonitorSettingsSchema,\n\t\t\tObject.fromEntries(Object.entries(rawSettings).filter(([key]) => !RESERVED_SETTING_KEYS.has(key))),\n\t\t\tbase,\n\t\t);\n\t\tconst options = parse(provider.options, entry.options, base);\n\n\t\tconst assigned = defaultRunner === undefined ? [] : [defaultRunner];\n\t\tfor (const runner of assigned) {\n\t\t\tconst missing = missingCapabilities(provider.requires, runner);\n\t\t\tif (missing.length > 0) {\n\t\t\t\treport(\n\t\t\t\t\tbase,\n\t\t\t\t\t`provider \"${provider.type}\" requires ${missing.map((c) => `\"${c}\"`).join(\", \")}, ` +\n\t\t\t\t\t\t`which runner \"${runner.id}\" does not provide`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tif (settings === undefined) return;\n\t\tconst { id, interval, timeout, confirmation } = settings;\n\t\tconst first = firstIndexOfMonitor.get(id);\n\t\tif (first !== undefined) {\n\t\t\treport(`${base}.id`, `duplicate monitor ID (also used by monitors[${first}])`);\n\t\t\treturn;\n\t\t}\n\t\tfirstIndexOfMonitor.set(id, index);\n\n\t\tif (confirmation.recheckInterval > interval) {\n\t\t\treport(\n\t\t\t\t`${base}.confirmation.recheckInterval`,\n\t\t\t\t`must not be longer than interval (${formatDuration(interval)})`,\n\t\t\t);\n\t\t}\n\t\tif (timeout >= interval) {\n\t\t\treport(\n\t\t\t\t`${base}.timeout`,\n\t\t\t\trawSettings[\"timeout\"] === undefined\n\t\t\t\t\t? `the default timeout (${DEFAULT_TIMEOUT}) must be shorter than interval (${formatDuration(interval)}); set a shorter timeout`\n\t\t\t\t\t: `must be shorter than interval (${formatDuration(interval)})`,\n\t\t\t);\n\t\t}\n\t\t// Scheduling and the confirmation rule read the last few results: keep many intervals' worth.\n\t\tif (retention !== undefined && interval * MIN_INTERVALS_RETAINED > retention) {\n\t\t\treport(\n\t\t\t\t`${base}.interval`,\n\t\t\t\t`must be at most 1/${MIN_INTERVALS_RETAINED} of retention (${formatDuration(retention)}), so that retention keeps enough results`,\n\t\t\t);\n\t\t}\n\t\tfor (const runner of assigned) {\n\t\t\tif (runner.maxTimeoutMs !== undefined && timeout > runner.maxTimeoutMs) {\n\t\t\t\treport(\n\t\t\t\t\t`${base}.timeout`,\n\t\t\t\t\t`must not be longer than ${formatDuration(runner.maxTimeoutMs)}, the limit of runner \"${runner.id}\"`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (options === undefined) return;\n\t\tfor (const name of secretNames(options)) {\n\t\t\tif (reservedSecrets.includes(name)) {\n\t\t\t\treport(base, `must not use secret(\"${name}\"): it is the hub's own secret and must never be sent to a monitored endpoint`);\n\t\t\t}\n\t\t}\n\n\t\tmonitors.push({\n\t\t\tid,\n\t\t\tname: settings.name ?? id,\n\t\t\tprovider,\n\t\t\toptions,\n\t\t\tsecrets: secretNames(options),\n\t\t\tintervalMs: interval,\n\t\t\ttimeoutMs: timeout,\n\t\t\tlocation: settings.location ?? location,\n\t\t\tconfirmation: {\n\t\t\t\tfailureThreshold: confirmation.failureThreshold,\n\t\t\t\tsuccessThreshold: confirmation.successThreshold,\n\t\t\t\trecheckIntervalMs: confirmation.recheckInterval,\n\t\t\t},\n\t\t\trunners: assigned.map((runner) => runner.id),\n\t\t});\n\t});\n\n\t// ---- Pages\n\tconst monitorNames = new Map(monitors.map((monitor) => [monitor.id, monitor.name]));\n\tconst firstIndexOfPage = new Map<string, number>();\n\tconst pages: ResolvedPage[] = [];\n\n\tpageEntries.forEach((entry, pageIndex) => {\n\t\tconst pageBase = `pages[${pageIndex}]`;\n\t\tconst page = parse(pageSchema, entry, pageBase);\n\t\tif (page !== undefined) {\n\t\t\tconst firstPage = firstIndexOfPage.get(page.id);\n\t\t\tif (firstPage === undefined) firstIndexOfPage.set(page.id, pageIndex);\n\t\t\telse report(`${pageBase}.id`, `duplicate page ID \"${page.id}\" (also used by pages[${firstPage}])`);\n\t\t}\n\t\t// Check components even when the page itself is invalid.\n\t\tconst componentEntries =\n\t\t\tpage?.components ??\n\t\t\t(isObject(entry) && Array.isArray(entry[\"components\"]) ? (entry[\"components\"] as unknown[]) : []);\n\n\t\t// Components and groups share one namespace of IDs: where each ID was first used.\n\t\tconst firstUseOfId = new Map<string, { readonly where: string; readonly group: boolean }>();\n\t\tconst components: ResolvedComponent[] = [];\n\t\tconst groups: ResolvedGroup[] = [];\n\t\tconst claimId = (id: string, path: string, where: string, group: boolean): boolean => {\n\t\t\tconst first = firstUseOfId.get(id);\n\t\t\tif (first === undefined) {\n\t\t\t\tfirstUseOfId.set(id, { where, group });\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treport(\n\t\t\t\t`${path}.id`,\n\t\t\t\t!group && !first.group\n\t\t\t\t\t? `duplicate component ID \"${id}\" (also used by ${first.where})`\n\t\t\t\t\t: `duplicate ID \"${id}\" (also used by ${first.where}): components and groups need different IDs`,\n\t\t\t);\n\t\t\treturn false;\n\t\t};\n\n\t\tconst resolveComponent = (componentEntry: unknown, where: string): ResolvedComponent | undefined => {\n\t\t\tconst base = `${pageBase}.${where}`;\n\t\t\tif (isGroupEntry(componentEntry)) {\n\t\t\t\treport(base, \"groups cannot contain groups\");\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tconst parsed = parse(componentSchema, componentEntry, base);\n\t\t\tif (parsed === undefined) return undefined;\n\t\t\tconst { id, monitors: monitorIds } = parsed;\n\n\t\t\tmonitorIds.forEach((monitorId, monitorIndex) => {\n\t\t\t\tif (!declaredMonitorIds.has(monitorId)) {\n\t\t\t\t\treport(`${base}.monitors[${monitorIndex}]`, `unknown monitor \"${monitorId}\"`);\n\t\t\t\t} else if (monitorIds.indexOf(monitorId) !== monitorIndex) {\n\t\t\t\t\treport(`${base}.monitors[${monitorIndex}]`, `monitor \"${monitorId}\" is listed twice`);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (parsed.latency && monitorIds.length === 0) {\n\t\t\t\treport(`${base}.latency`, \"needs at least one monitor: response times come from the component's monitors\");\n\t\t\t}\n\n\t\t\tconst only = monitorIds.length === 1 ? monitorIds[0] : undefined;\n\t\t\tconst name = parsed.name ?? (only === undefined ? undefined : (monitorNames.get(only) ?? only));\n\t\t\tif (name === undefined) {\n\t\t\t\treport(`${base}.name`, \"is required unless the component has exactly one monitor\");\n\t\t\t}\n\n\t\t\tif (!claimId(id, base, where, false)) return undefined;\n\t\t\treturn { id, name: name ?? id, monitors: monitorIds, latency: parsed.latency };\n\t\t};\n\n\t\tcomponentEntries.forEach((componentEntry, componentIndex) => {\n\t\t\tconst where = `components[${componentIndex}]`;\n\t\t\tif (!isGroupEntry(componentEntry)) {\n\t\t\t\tconst resolved = resolveComponent(componentEntry, where);\n\t\t\t\tif (resolved !== undefined) components.push(resolved);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst base = `${pageBase}.${where}`;\n\t\t\tconst group = parse(groupSchema, componentEntry, base);\n\t\t\t// Check its components even when the group itself is invalid.\n\t\t\tconst memberEntries =\n\t\t\t\tgroup?.components ??\n\t\t\t\t(isObject(componentEntry) && Array.isArray(componentEntry[\"components\"]) ? (componentEntry[\"components\"] as unknown[]) : []);\n\t\t\tconst claimed = group !== undefined && claimId(group.id, base, where, true);\n\t\t\tconst members: string[] = [];\n\t\t\tmemberEntries.forEach((memberEntry, memberIndex) => {\n\t\t\t\tconst resolved = resolveComponent(memberEntry, `${where}.components[${memberIndex}]`);\n\t\t\t\tif (resolved === undefined) return;\n\t\t\t\tcomponents.push(resolved);\n\t\t\t\tmembers.push(resolved.id);\n\t\t\t});\n\t\t\tif (group !== undefined && claimed && members.length > 0) {\n\t\t\t\tgroups.push({ id: group.id, name: group.name, components: members });\n\t\t\t}\n\t\t});\n\n\t\tif (page !== undefined) {\n\t\t\tpages.push({\n\t\t\t\tid: page.id,\n\t\t\t\ttemplate: page.template,\n\t\t\t\treportUrl: page.reportUrl ?? null,\n\t\t\t\tframe: {\n\t\t\t\t\ttitle: page.title ?? null,\n\t\t\t\t\tdescription: page.description ?? null,\n\t\t\t\t\tlogoUrl: page.logoUrl ?? null,\n\t\t\t\t\twebsiteUrl: page.websiteUrl ?? null,\n\t\t\t\t\theader: page.header,\n\t\t\t\t\tfooter: page.footer,\n\t\t\t\t},\n\t\t\t\tincidents: {\n\t\t\t\t\tauto: page.incidents.auto,\n\t\t\t\t\ttemplates: stripUndefined(page.incidents.templates),\n\t\t\t\t\treopenWithinMs: page.incidents.reopenWithin,\n\t\t\t\t},\n\t\t\t\tcomponents,\n\t\t\t\tgroups,\n\t\t\t});\n\t\t}\n\t});\n\n\tif (\n\t\tissues.length > 0 ||\n\t\ttimezone === undefined ||\n\t\tpublicApi === undefined ||\n\t\tlocale === undefined ||\n\t\tnotifications === undefined\n\t) {\n\t\tthrow new ConfigError(issues);\n\t}\n\n\treturn {\n\t\ttimezone,\n\t\tretentionMs: retention ?? null,\n\t\tauth,\n\t\tnotifiers,\n\t\tlocale,\n\t\tbaseUrl: baseUrl ?? null,\n\t\tnotifications: { unknownCheckIntervalMs: notifications.unknownCheckInterval },\n\t\tmonitors,\n\t\tpages,\n\t\tpublicApi: { cache: publicApi.cache, allowedOrigins: publicApi.allowedOrigins },\n\t\tadminHosts,\n\t};\n}\n","/**\n * States as the status page shows them: `unknown` derived at display time,\n * the precedence between states, and a component's state from its monitors and incidents.\n */\nimport type { CheckState } from \"./provider\";\nimport type { RecordedState } from \"./timeline\";\n\n/** A state as displayed: a confirmed state, or `unknown` when results are missing or late. */\nexport type DisplayState = CheckState | \"unknown\";\n\n/**\n * Severity for \"the worst state\": `down` > `degraded` > `unknown` > `up`. `unknown`\n * means results are missing, which is not necessarily an outage, so a known problem\n * (`degraded`) outranks it.\n */\nconst RANK: Readonly<Record<DisplayState, number>> = { up: 0, unknown: 1, degraded: 2, down: 3 };\n\nexport function isCheckState(state: string): state is CheckState {\n\treturn state === \"up\" || state === \"degraded\" || state === \"down\";\n}\n\n/** The worse of two states. */\nexport function worseOf(a: DisplayState, b: DisplayState): DisplayState {\n\treturn RANK[b] > RANK[a] ? b : a;\n}\n\n/** The worst of `states`, or `empty` when there are none. */\nexport function worstState(states: Iterable<DisplayState>, empty: DisplayState): DisplayState {\n\tlet worst: DisplayState | undefined;\n\tfor (const state of states) worst = worst === undefined ? state : worseOf(worst, state);\n\treturn worst ?? empty;\n}\n\n/**\n * Slack on top of the schedule before a monitor counts as late: the runner's and the Monitor\n * DO's grace periods after a check's timeout (10 seconds), alarms that fire late, and clock\n * differences between Durable Objects.\n */\nexport const LATE_GRACE_MS = 60_000;\n\n/**\n * How long a monitor may go without a check that produced a state before it is `unknown`: two intervals, plus the check's timeout and {@link LATE_GRACE_MS}.\n *\n * A check's result is recorded when the check ends, up to its timeout (plus grace) after the\n * slot it ran for. Two intervals tolerate one missed result (a transient runner error, a\n * check that produced no result) without flapping to `unknown`; the second missed result in\n * a row makes the monitor `unknown`, before the third slot is due. With a 1-minute interval\n * and a 10-second timeout that is 3 minutes 10 seconds.\n *\n * The status page uses this for the live state and for every past moment of the history,\n * and the every-minute Cron uses it to notify `unknown`, so the three agree.\n */\nexport function staleAfterMs(intervalMs: number, timeoutMs: number): number {\n\treturn 2 * intervalMs + timeoutMs + LATE_GRACE_MS;\n}\n\n/** What {@link displayState} needs from a monitor. A Monitor DO's snapshot has this shape. */\nexport interface MonitorReading {\n\t/** The latest record of the state history; `null` before any. */\n\treadonly current: { readonly state: RecordedState } | null;\n\t/** The current schedule period; `null` before the monitor first started. */\n\treadonly period: { readonly from: number; readonly status: \"active\" | \"stopped\"; readonly intervalMs: number | null } | null;\n\t/** Start of the latest recent check that produced a state; `null` when none did. */\n\treadonly lastResultAt: number | null;\n}\n\nexport interface DisplayStateResult {\n\treadonly state: DisplayState;\n\t/**\n\t * Why the state is `unknown`, `null` otherwise:\n\t * - `stopped`: the monitor is not running (it left the configuration, or has not started);\n\t * - `late`: no result for longer than {@link staleAfterMs}, whether or not a state was\n\t * confirmed (a new monitor whose checks never produce a result is late too);\n\t * - `unconfirmed`: results arrive, but no state is confirmed yet (new, or resumed after a stop).\n\t *\n\t * The every-minute Cron notifies administrators of `late`.\n\t */\n\treadonly unknownReason: \"unconfirmed\" | \"stopped\" | \"late\" | null;\n}\n\n/**\n * A monitor's state at display time: its confirmed state, unless its latest result\n * is late for its schedule or it has no confirmed state (including `unconfirmed` after\n * resuming). Lateness counts from the later of the latest result and the start of the\n * current schedule period, so a new interval gets a fresh allowance, and it is checked\n * before the confirmed state, so that a monitor that never produces a result is `late`.\n */\nexport function displayState(reading: MonitorReading, timeoutMs: number, now: number): DisplayStateResult {\n\tconst { current, period } = reading;\n\tif (period === null || period.status !== \"active\" || period.intervalMs === null || current?.state === \"stopped\") {\n\t\treturn { state: \"unknown\", unknownReason: \"stopped\" };\n\t}\n\tconst anchor = Math.max(reading.lastResultAt ?? Number.NEGATIVE_INFINITY, period.from);\n\tif (now - anchor > staleAfterMs(period.intervalMs, timeoutMs)) return { state: \"unknown\", unknownReason: \"late\" };\n\tif (current === null || !isCheckState(current.state)) return { state: \"unknown\", unknownReason: \"unconfirmed\" };\n\treturn { state: current.state, unknownReason: null };\n}\n\n/** Impact of an open incident on a component. `none` lists it without changing its state. */\nexport type IncidentImpact = \"none\" | \"degraded\" | \"down\";\n\n/**\n * A component's current state: the worst of its monitors' display states and the\n * impacts of the unresolved incidents that affect it, so that a person's judgement can\n * override the automatic one. A component without monitors takes its state from incidents\n * alone, and is `up` without any. Maintenance is not a state: it is shown next to it.\n */\nexport function componentState(\n\tmonitorStates: Iterable<DisplayState>,\n\topenIncidentImpacts: Iterable<IncidentImpact>,\n): DisplayState {\n\tconst states: DisplayState[] = [...monitorStates];\n\tfor (const impact of openIncidentImpacts) {\n\t\tif (impact !== \"none\") states.push(impact);\n\t}\n\treturn worstState(states, \"up\");\n}\n","/**\n * Timelines of states for history and uptime: what a monitor's confirmed states,\n * schedule and results say about each moment, combined per component. Pure functions, so\n * that the Worker, the status pages and tests share one definition.\n */\nimport { type DisplayState, isCheckState, worseOf } from \"./display\";\nimport type { CheckState } from \"./provider\";\n\n/** A half-open time range `[from, to)` in milliseconds since the epoch. */\nexport interface TimeRange {\n\treadonly from: number;\n\treadonly to: number;\n}\n\n/**\n * A stretch of time with one schedule. A monitor's periods are contiguous: each one ends\n * where the next begins. A new period starts only when something changes (the monitor\n * starts, its interval changes, it leaves or returns to the configuration).\n */\nexport interface SchedulePeriod {\n\t/** Start, inclusive. */\n\treadonly from: number;\n\t/** End, exclusive; `null` for the current period. */\n\treadonly to: number | null;\n\t/**\n\t * `active`: scheduled checks every `intervalMs`, from `from` (the grid's anchor).\n\t * `stopped`: the monitor was not in the configuration. A stopped period is neither\n\t * uptime nor downtime, and its slots are not missed checks.\n\t */\n\treadonly status: \"active\" | \"stopped\";\n\t/** `null` when stopped. */\n\treadonly intervalMs: number | null;\n}\n\n/**\n * A state in a monitor's history: a confirmed state; `stopped` while the monitor was not in\n * the configuration; `unconfirmed` from when it resumed until a state is confirmed again. At\n * display time, `unconfirmed` (like no record at all) is `unknown`; neither `stopped` nor\n * `unconfirmed` counts as uptime or downtime.\n */\nexport type RecordedState = CheckState | \"stopped\" | \"unconfirmed\";\n\n/** One record of the state history. Each record lasts until the next one's `since`. */\nexport interface StateRecord {\n\treadonly state: RecordedState;\n\t/** When it began. For a confirmed state, when the run of results that confirmed it began. */\n\treadonly since: number;\n\t/** When it was recorded: for a confirmed state, the time of the result that confirmed it. */\n\treadonly confirmedAt: number;\n}\n\n/** A stretch of time in one display state. Lists of segments are sorted and never overlap. */\nexport interface Segment extends TimeRange {\n\treadonly state: DisplayState;\n}\n\n/** What a monitor's storage says about a time range. */\nexport interface TimelineSource {\n\t/** Schedule periods that overlap the range, oldest first. */\n\treadonly periods: readonly SchedulePeriod[];\n\t/** The state record in effect at the start of the range. */\n\treadonly atStart: StateRecord | null;\n\t/** State records that begin inside the range, oldest first. */\n\treadonly changes: readonly StateRecord[];\n\t/**\n\t * Start times of the checks that produced a state, ascending: at least those from\n\t * `staleAfter(interval)` before the range up to its end, so that lateness at the start of\n\t * the range is judged from the results before it.\n\t */\n\treadonly resultTimes: readonly number[];\n}\n\n/** Index of the first value `>= target` in a sorted array. */\nfunction lowerBound(values: readonly number[], target: number): number {\n\tlet low = 0;\n\tlet high = values.length;\n\twhile (low < high) {\n\t\tconst middle = (low + high) >>> 1;\n\t\tif ((values[middle] as number) < target) low = middle + 1;\n\t\telse high = middle;\n\t}\n\treturn low;\n}\n\n/** Appends a segment, merging it into the previous one when they touch and have the same state. */\nfunction append(segments: Segment[], from: number, to: number, state: DisplayState): void {\n\tif (to <= from) return;\n\tconst last = segments.at(-1);\n\tif (last !== undefined && last.to === from && last.state === state) {\n\t\tsegments[segments.length - 1] = { from: last.from, to, state };\n\t} else {\n\t\tsegments.push({ from, to, state });\n\t}\n}\n\n/** `a` followed by `b` (which starts where `a` ends, or later), merging at the seam. */\nexport function concatSegments(a: readonly Segment[], b: readonly Segment[]): Segment[] {\n\tconst result = [...a];\n\tfor (const segment of b) append(result, segment.from, segment.to, segment.state);\n\treturn result;\n}\n\n/**\n * Where a monitor is late inside one active schedule period and `range`: from\n * `staleAfterMs` after the latest anchor until the next one, where an anchor is the start of\n * the period or a check that produced a state. This is the display-time rule (see\n * `displayState`) applied to every past moment, so the history shows `unknown` exactly when\n * the live page did.\n *\n * Results from before the range are needed to judge its start: with none in the\n * `staleAfterMs` before it, the monitor is late from the range's start on.\n */\nexport function lateSpans(\n\tperiod: Pick<SchedulePeriod, \"from\" | \"to\">,\n\trange: TimeRange,\n\tresultTimes: readonly number[],\n\tstaleAfterMs: number,\n): TimeRange[] {\n\tconst low = Math.max(period.from, range.from);\n\tconst high = Math.min(period.to ?? Number.POSITIVE_INFINITY, range.to);\n\tif (low >= high) return [];\n\tconst spans: TimeRange[] = [];\n\tconst push = (from: number, to: number) => {\n\t\tconst clippedFrom = Math.max(from, low);\n\t\tconst clippedTo = Math.min(to, high);\n\t\tif (clippedFrom < clippedTo) spans.push({ from: clippedFrom, to: clippedTo });\n\t};\n\t// The latest anchor at or before `range.from - staleAfterMs` is at least that early, so\n\t// starting from there judges the range's start correctly whatever came before.\n\tlet anchor = Math.max(period.from, range.from - staleAfterMs);\n\tfor (let index = lowerBound(resultTimes, anchor); index < resultTimes.length; index++) {\n\t\tconst at = resultTimes[index] as number;\n\t\tif (at >= high) break;\n\t\tif (at - anchor > staleAfterMs) push(anchor + staleAfterMs, at);\n\t\tanchor = at;\n\t}\n\tif (high - anchor > staleAfterMs) push(anchor + staleAfterMs, high);\n\treturn spans;\n}\n\n/**\n * The display state of a monitor at every moment of `range`:\n *\n * - outside active schedule periods (before it started, or `stopped`): no segment, which is\n * neither uptime nor downtime;\n * - while late (see {@link lateSpans}): `unknown`;\n * - otherwise the confirmed state in effect, or `unknown` before any is confirmed and while\n * `unconfirmed` after resuming.\n *\n * `staleAfter` gives the lateness threshold for a period's interval (see `staleAfterMs`).\n */\nexport function monitorTimeline(\n\trange: TimeRange,\n\tsource: TimelineSource,\n\tstaleAfter: (intervalMs: number) => number,\n): Segment[] {\n\tconst active: TimeRange[] = [];\n\tconst late: TimeRange[] = [];\n\tfor (const period of source.periods) {\n\t\tif (period.status !== \"active\" || period.intervalMs === null) continue;\n\t\tconst from = Math.max(range.from, period.from);\n\t\tconst to = Math.min(range.to, period.to ?? Number.POSITIVE_INFINITY);\n\t\tif (from >= to) continue;\n\t\tactive.push({ from, to });\n\t\tlate.push(...lateSpans(period, range, source.resultTimes, staleAfter(period.intervalMs)));\n\t}\n\tif (active.length === 0) return [];\n\n\tconst records = [...(source.atStart === null ? [] : [source.atStart]), ...source.changes];\n\tconst points = new Set<number>();\n\tfor (const list of [active, late]) {\n\t\tfor (const part of list) {\n\t\t\tpoints.add(part.from);\n\t\t\tpoints.add(part.to);\n\t\t}\n\t}\n\tfor (const record of records) {\n\t\tif (record.since > range.from && record.since < range.to) points.add(record.since);\n\t}\n\tconst sorted = [...points].sort((a, b) => a - b);\n\n\tconst segments: Segment[] = [];\n\tlet activeIndex = 0;\n\tlet lateIndex = 0;\n\tlet recordIndex = -1;\n\tfor (let index = 0; index + 1 < sorted.length; index++) {\n\t\tconst from = sorted[index] as number;\n\t\tconst to = sorted[index + 1] as number;\n\t\twhile (activeIndex < active.length && (active[activeIndex] as TimeRange).to <= from) activeIndex++;\n\t\tconst part = active[activeIndex];\n\t\tif (part === undefined || part.from > from) continue;\n\t\twhile (lateIndex < late.length && (late[lateIndex] as TimeRange).to <= from) lateIndex++;\n\t\tconst span = late[lateIndex];\n\t\tif (span !== undefined && span.from <= from) {\n\t\t\tappend(segments, from, to, \"unknown\");\n\t\t\tcontinue;\n\t\t}\n\t\twhile (recordIndex + 1 < records.length && (records[recordIndex + 1] as StateRecord).since <= from) recordIndex++;\n\t\tconst state = records[recordIndex]?.state;\n\t\tappend(segments, from, to, state !== undefined && isCheckState(state) ? state : \"unknown\");\n\t}\n\treturn segments;\n}\n\n/**\n * A component's timeline from its monitors': at each moment, the worst state of\n * the monitors that have data then (`down` > `degraded` > `unknown` > `up`). Moments where\n * none of them has data have no segment.\n */\nexport function combineTimelines(timelines: readonly (readonly Segment[])[]): Segment[] {\n\tif (timelines.length === 1) return [...(timelines[0] as readonly Segment[])];\n\tconst points = new Set<number>();\n\tfor (const timeline of timelines) {\n\t\tfor (const segment of timeline) {\n\t\t\tpoints.add(segment.from);\n\t\t\tpoints.add(segment.to);\n\t\t}\n\t}\n\tconst sorted = [...points].sort((a, b) => a - b);\n\tconst cursors = timelines.map(() => 0);\n\tconst result: Segment[] = [];\n\tfor (let index = 0; index + 1 < sorted.length; index++) {\n\t\tconst from = sorted[index] as number;\n\t\tconst to = sorted[index + 1] as number;\n\t\tlet worst: DisplayState | undefined;\n\t\ttimelines.forEach((timeline, which) => {\n\t\t\tlet cursor = cursors[which] as number;\n\t\t\twhile (cursor < timeline.length && (timeline[cursor] as Segment).to <= from) cursor++;\n\t\t\tcursors[which] = cursor;\n\t\t\tconst segment = timeline[cursor];\n\t\t\tif (segment !== undefined && segment.from <= from) {\n\t\t\t\tworst = worst === undefined ? segment.state : worseOf(worst, segment.state);\n\t\t\t}\n\t\t});\n\t\tif (worst !== undefined) append(result, from, to, worst);\n\t}\n\treturn result;\n}\n\n/** Sorted, non-overlapping ranges covering the same time as `ranges`. */\nexport function mergeRanges(ranges: readonly TimeRange[]): TimeRange[] {\n\tconst sorted = ranges.filter((range) => range.from < range.to).sort((a, b) => a.from - b.from);\n\tconst merged: TimeRange[] = [];\n\tfor (const range of sorted) {\n\t\tconst last = merged.at(-1);\n\t\tif (last !== undefined && range.from <= last.to) {\n\t\t\tmerged[merged.length - 1] = { from: last.from, to: Math.max(last.to, range.to) };\n\t\t} else {\n\t\t\tmerged.push(range);\n\t\t}\n\t}\n\treturn merged;\n}\n\n/** `segments` without the time inside `windows` (maintenance: excluded from uptime). */\nexport function excludeWindows(segments: readonly Segment[], windows: readonly TimeRange[]): Segment[] {\n\tconst cuts = mergeRanges(windows);\n\tif (cuts.length === 0) return [...segments];\n\tconst result: Segment[] = [];\n\tfor (const segment of segments) {\n\t\tlet from = segment.from;\n\t\tfor (const cut of cuts) {\n\t\t\tif (cut.to <= from) continue;\n\t\t\tif (cut.from >= segment.to) break;\n\t\t\tif (cut.from > from) result.push({ from, to: cut.from, state: segment.state });\n\t\t\tfrom = Math.max(from, cut.to);\n\t\t\tif (from >= segment.to) break;\n\t\t}\n\t\tif (from < segment.to) result.push({ from, to: segment.to, state: segment.state });\n\t}\n\treturn result;\n}\n\nexport interface TimelineSummary {\n\t/** Time in `up` or `degraded`: `degraded` counts as uptime. */\n\treadonly upMs: number;\n\t/** Time in `down`, the only state that counts as an outage. */\n\treadonly downMs: number;\n\t/** Time in `degraded`, part of `upMs`. */\n\treadonly degradedMs: number;\n\t/** Time in `unknown`, excluded from uptime. */\n\treadonly unknownMs: number;\n\t/** The worst confirmed state (`down` > `degraded` > `up`), or `null` when there is none. */\n\treadonly worst: CheckState | null;\n}\n\nconst CONFIRMED_RANK: Readonly<Record<CheckState, number>> = { up: 0, degraded: 1, down: 2 };\n\nexport function summarize(segments: readonly Segment[]): TimelineSummary {\n\tlet upMs = 0;\n\tlet downMs = 0;\n\tlet degradedMs = 0;\n\tlet unknownMs = 0;\n\tlet worst: CheckState | null = null;\n\tfor (const segment of segments) {\n\t\tconst length = segment.to - segment.from;\n\t\tif (segment.state === \"unknown\") {\n\t\t\tunknownMs += length;\n\t\t\tcontinue;\n\t\t}\n\t\tif (segment.state === \"down\") downMs += length;\n\t\telse upMs += length;\n\t\tif (segment.state === \"degraded\") degradedMs += length;\n\t\tif (worst === null || CONFIRMED_RANK[segment.state] > CONFIRMED_RANK[worst]) worst = segment.state;\n\t}\n\treturn { upMs, downMs, degradedMs, unknownMs, worst };\n}\n\n/**\n * Uptime as a ratio: time `up` or `degraded` over time with a confirmed state. `null`\n * when no time had a confirmed state (everything unknown, stopped or under maintenance).\n */\nexport function uptimeRatio(upMs: number, downMs: number): number | null {\n\tconst known = upMs + downMs;\n\treturn known > 0 ? upMs / known : null;\n}\n\n/**\n * Coverage: scheduled checks that produced a state over the checks the schedule\n * expected. At most 1 (a check near a range boundary can land in the next range). `null`\n * when nothing was expected.\n */\nexport function coverageRatio(obtained: number, expected: number): number | null {\n\treturn expected > 0 ? Math.min(1, obtained / expected) : null;\n}\n\n/** A stretch of confirmed `down`. `to` is `null` while it lasts. */\nexport interface DownPeriod {\n\treadonly from: number;\n\treadonly to: number | null;\n}\n\n/**\n * The confirmed `down` periods in a state history (records oldest first): each lasts from its\n * record's `since` until the next record, whatever that is (recovery, `degraded`, a stop).\n */\nexport function downPeriods(records: readonly StateRecord[]): DownPeriod[] {\n\tconst periods: DownPeriod[] = [];\n\trecords.forEach((record, index) => {\n\t\tif (record.state !== \"down\") return;\n\t\tconst next = records[index + 1];\n\t\tconst last = periods.at(-1);\n\t\t// Two `down` records in a row (not written today, but harmless) make one period.\n\t\tif (last !== undefined && last.to === record.since) {\n\t\t\tperiods[periods.length - 1] = { from: last.from, to: next?.since ?? null };\n\t\t} else {\n\t\t\tperiods.push({ from: record.since, to: next?.since ?? null });\n\t\t}\n\t});\n\treturn periods;\n}\n\n/** The union of `periods` (from several monitors), oldest first; an open period absorbs what follows it. */\nexport function mergeDownPeriods(periods: readonly DownPeriod[]): DownPeriod[] {\n\tconst sorted = [...periods].sort((a, b) => a.from - b.from);\n\tconst merged: DownPeriod[] = [];\n\tfor (const period of sorted) {\n\t\tconst last = merged.at(-1);\n\t\tif (last !== undefined && (last.to === null || period.from <= last.to)) {\n\t\t\tconst to = last.to === null || period.to === null ? null : Math.max(last.to, period.to);\n\t\t\tmerged[merged.length - 1] = { from: last.from, to };\n\t\t} else {\n\t\t\tmerged.push(period);\n\t\t}\n\t}\n\treturn merged;\n}\n"],"mappings":";;;;;AAaA,IAAM,6BAAa,IAAI,IAAiC;AAExD,SAAS,UAAU,UAAuC;CACzD,IAAI,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