tempest-express-sdk 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { z, looseBoolean, toDict } from './chunk-HC3TIN4M.js';
2
- export { PasswordUtils, VERSION, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, centsField, corsSettingsShape, databaseSettingsShape, looseBoolean as envBoolean, hexColorField, latitudeField, loadSettings, longitudeField, looseBoolean, nonEmptyStrField, nonNegativeFloatField, nonNegativeIntField, percentField, portField, positiveFloatField, positiveIntField, priceField, ratingField, ratioField, serverSettingsShape, slugField, toDict, z } from './chunk-HC3TIN4M.js';
1
+ import { z, looseBoolean, toDict, PasswordUtils } from './chunk-TIW2KPT2.js';
2
+ export { PasswordUtils, VERSION, baseAppSettingsSchema, baseAppSettingsShape, baseResponseSchema, centsField, corsSettingsShape, databaseSettingsShape, looseBoolean as envBoolean, hexColorField, latitudeField, loadSettings, longitudeField, looseBoolean, nonEmptyStrField, nonNegativeFloatField, nonNegativeIntField, percentField, portField, positiveFloatField, positiveIntField, priceField, ratingField, ratioField, serverSettingsShape, slugField, toDict, z } from './chunk-TIW2KPT2.js';
3
3
  import { AsyncLocalStorage } from 'async_hooks';
4
- import { Model, column, sql, BaseRepository, RecordNotFound, detectDialect, NodeSqliteDriver, AsyncEngine } from 'tempest-db-js';
4
+ import { Model, column, sql, BaseRepository, RecordNotFound, detectDialect, columnsOf, NodeSqliteDriver, AsyncEngine, or, and } from 'tempest-db-js';
5
5
  export { AsyncEngine, AsyncResult, AsyncSession, BaseRepository, Column, DeleteBuilder, InsertBuilder, Model, NoResultError, NodeSqliteDriver, PostgresDialect, RecordNotFound, SelectBuilder, SqliteDialect, SyncEngine, SyncSession, UpdateBuilder, and, belongsTo, column, columnsOf, createEngine, createSyncEngine, del, detectDialect, getDialect, hasMany, insert, join, loadRelations, not, or, parseDatabaseUrl, select, sql, update } from 'tempest-db-js';
6
6
  import { execFile, spawn } from 'child_process';
7
7
  import { copyFile, mkdir, writeFile, readFile, rm, stat } from 'fs/promises';
@@ -10,7 +10,7 @@ import { createReadStream, mkdirSync, createWriteStream } from 'fs';
10
10
  import { join, dirname, normalize, relative, isAbsolute } from 'path';
11
11
  import { cpus, loadavg, totalmem, freemem } from 'os';
12
12
  import { promisify } from 'util';
13
- import express2, { Router } from 'express';
13
+ import express3, { Router } from 'express';
14
14
  import { ZodError } from 'zod';
15
15
  import { OpenAPIRegistry, OpenApiGeneratorV31, OpenApiGeneratorV3 } from '@asteasolutions/zod-to-openapi';
16
16
  export { OpenAPIRegistry } from '@asteasolutions/zod-to-openapi';
@@ -819,7 +819,7 @@ function wrapWithSlowQueryLog(driver, options = {}) {
819
819
  const thresholdMs = options.thresholdMs ?? 500;
820
820
  const level = options.level ?? "warning";
821
821
  const logParameters = options.logParameters ?? false;
822
- const logger4 = new JSONLogger(
822
+ const logger5 = new JSONLogger(
823
823
  options.loggerName ?? "tempest_express_sdk.db.slow_query"
824
824
  );
825
825
  const timed = (exec) => {
@@ -830,7 +830,7 @@ function wrapWithSlowQueryLog(driver, options = {}) {
830
830
  } finally {
831
831
  const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
832
832
  if (durationMs >= thresholdMs) {
833
- logger4.log(level, "slow query", {
833
+ logger5.log(level, "slow query", {
834
834
  sql: sql5,
835
835
  durationMs: Math.round(durationMs * 1e3) / 1e3,
836
836
  ...logParameters ? { params } : {}
@@ -9317,8 +9317,3508 @@ var MessagingHub = class {
9317
9317
  }
9318
9318
  };
9319
9319
 
9320
+ // src/admin/actions.ts
9321
+ function slugify(label) {
9322
+ return label.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "action";
9323
+ }
9324
+ function adminAction(options, handler) {
9325
+ const name = options.name ?? slugify(options.label);
9326
+ if (name === "") throw new Error("adminAction requires a non-empty name or label");
9327
+ return {
9328
+ name,
9329
+ label: options.label,
9330
+ handler,
9331
+ dangerous: options.dangerous ?? false
9332
+ };
9333
+ }
9334
+
9335
+ // src/admin/columns.ts
9336
+ function humanizeField(name) {
9337
+ return name.replace(/[_-]+/g, " ").replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim().split(/\s+/).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
9338
+ }
9339
+ function adminColumns(model) {
9340
+ return columnsOf(model);
9341
+ }
9342
+ function widgetForColumn(column6) {
9343
+ const { kind, meta } = column6.type;
9344
+ const plain = (widget) => ({
9345
+ widget,
9346
+ step: null,
9347
+ options: []
9348
+ });
9349
+ switch (kind) {
9350
+ case "json":
9351
+ return plain("json");
9352
+ case "boolean":
9353
+ return plain("checkbox");
9354
+ case "enum":
9355
+ return {
9356
+ widget: "select",
9357
+ step: null,
9358
+ options: (meta.values ?? []).map((value) => ({
9359
+ value,
9360
+ label: humanizeField(value)
9361
+ }))
9362
+ };
9363
+ case "smallint":
9364
+ case "integer":
9365
+ case "bigint":
9366
+ return { widget: "number", step: "1", options: [] };
9367
+ case "numeric":
9368
+ case "real":
9369
+ case "double":
9370
+ return { widget: "number", step: "any", options: [] };
9371
+ case "datetime":
9372
+ case "timestamp":
9373
+ return plain("datetime");
9374
+ case "date":
9375
+ return plain("date");
9376
+ case "time":
9377
+ return plain("time");
9378
+ case "text":
9379
+ return plain("textarea");
9380
+ case "varchar":
9381
+ case "char":
9382
+ return plain(meta.length !== void 0 && meta.length > 255 ? "textarea" : "text");
9383
+ default:
9384
+ return plain("text");
9385
+ }
9386
+ }
9387
+ function isColumnOptional(column6) {
9388
+ return !column6.flags.notNull || column6.flags.hasDefault || column6.flags.primaryKey;
9389
+ }
9390
+ function filterForColumn(column6) {
9391
+ const { kind, meta } = column6.type;
9392
+ if (kind === "boolean") {
9393
+ return {
9394
+ kind: "select",
9395
+ options: [
9396
+ { value: "true", label: "Yes" },
9397
+ { value: "false", label: "No" }
9398
+ ]
9399
+ };
9400
+ }
9401
+ if (kind === "enum") {
9402
+ return {
9403
+ kind: "select",
9404
+ options: (meta.values ?? []).map((value) => ({
9405
+ value,
9406
+ label: humanizeField(value)
9407
+ }))
9408
+ };
9409
+ }
9410
+ if (kind === "date" || kind === "datetime" || kind === "timestamp") {
9411
+ return { kind: "daterange", options: [] };
9412
+ }
9413
+ return { kind: "text", options: [] };
9414
+ }
9415
+ function foreignKeyTable(column6) {
9416
+ return column6.reference?.table ?? null;
9417
+ }
9418
+ function isSearchableColumn(column6) {
9419
+ const { kind } = column6.type;
9420
+ return kind === "varchar" || kind === "text" || kind === "char";
9421
+ }
9422
+
9423
+ // src/admin/config.ts
9424
+ var NEVER_EDITABLE = [
9425
+ "id",
9426
+ "createdAt",
9427
+ "updatedAt",
9428
+ "hashedPassword"
9429
+ ];
9430
+ var NEVER_LISTED = ["hashedPassword"];
9431
+ var AdminModel = class {
9432
+ /** The managed model class. */
9433
+ model;
9434
+ /** Columns surfaced as filter controls. */
9435
+ listFilter;
9436
+ /** Text columns the search box matches against. */
9437
+ searchFields;
9438
+ /** Columns locked in the create/edit form. */
9439
+ readonlyFields;
9440
+ /** Default ordering column, or `null` to leave it to the repository. */
9441
+ orderKey;
9442
+ /** Whether {@link AdminModel.orderKey} sorts ascending. */
9443
+ orderAscending;
9444
+ /** Rows per page in the list view. */
9445
+ pageSize;
9446
+ /** Column used to look a single row up from the detail URL. */
9447
+ identityField;
9448
+ /** Whether the create form is exposed. */
9449
+ canCreate;
9450
+ /** Whether the edit form is exposed. */
9451
+ canEdit;
9452
+ /** Whether the delete action is exposed. */
9453
+ canDelete;
9454
+ actions = /* @__PURE__ */ new Map();
9455
+ slugOverride;
9456
+ listDisplayOverride;
9457
+ verboseNameOverride;
9458
+ verboseNamePluralOverride;
9459
+ /**
9460
+ * Build and validate the configuration.
9461
+ *
9462
+ * @param options - The declarative configuration. See {@link AdminModelOptions}.
9463
+ * @throws Error When a referenced column does not exist on the model.
9464
+ */
9465
+ constructor(options) {
9466
+ this.model = options.model;
9467
+ this.slugOverride = options.slug ?? null;
9468
+ this.listDisplayOverride = options.listDisplay === void 0 ? null : [...options.listDisplay];
9469
+ this.listFilter = [...options.listFilter ?? []];
9470
+ this.searchFields = [...options.searchFields ?? []];
9471
+ this.readonlyFields = [...options.readonlyFields ?? []];
9472
+ this.pageSize = options.pageSize ?? 25;
9473
+ this.identityField = options.identityField ?? "id";
9474
+ this.verboseNameOverride = options.verboseName ?? null;
9475
+ this.verboseNamePluralOverride = options.verboseNamePlural ?? null;
9476
+ this.canCreate = options.canCreate ?? true;
9477
+ this.canEdit = options.canEdit ?? true;
9478
+ this.canDelete = options.canDelete ?? true;
9479
+ for (const action of options.actions ?? []) {
9480
+ if (this.actions.has(action.name)) {
9481
+ throw new Error(
9482
+ `Duplicate admin action name "${action.name}" on ${this.model.tablename}`
9483
+ );
9484
+ }
9485
+ this.actions.set(action.name, action);
9486
+ }
9487
+ const known = new Set(this.columnNames());
9488
+ for (const [option, names] of [
9489
+ ["listDisplay", this.listDisplayOverride ?? []],
9490
+ ["listFilter", this.listFilter],
9491
+ ["searchFields", this.searchFields],
9492
+ ["readonlyFields", this.readonlyFields],
9493
+ ["identityField", [this.identityField]]
9494
+ ]) {
9495
+ for (const name of names) {
9496
+ if (!known.has(name)) {
9497
+ throw new Error(
9498
+ `AdminModel(${this.model.tablename}).${option} references unknown column "${name}"; available: ${[...known].join(", ")}`
9499
+ );
9500
+ }
9501
+ }
9502
+ }
9503
+ const ordering = options.ordering ?? (known.has("createdAt") ? "-createdAt" : void 0);
9504
+ if (ordering === void 0) {
9505
+ this.orderKey = null;
9506
+ this.orderAscending = true;
9507
+ } else {
9508
+ const descending = ordering.startsWith("-");
9509
+ const key = descending ? ordering.slice(1) : ordering;
9510
+ if (!known.has(key)) {
9511
+ throw new Error(
9512
+ `AdminModel(${this.model.tablename}).ordering references unknown column "${key}"`
9513
+ );
9514
+ }
9515
+ this.orderKey = key;
9516
+ this.orderAscending = !descending;
9517
+ }
9518
+ }
9519
+ /**
9520
+ * Return the URL slug the model is exposed under.
9521
+ *
9522
+ * @returns The configured slug, or the model's table name.
9523
+ */
9524
+ slug() {
9525
+ return this.slugOverride ?? this.model.tablename;
9526
+ }
9527
+ /**
9528
+ * Return the singular display name.
9529
+ *
9530
+ * @returns The configured name, or the humanized class name without its
9531
+ * trailing `Model`.
9532
+ */
9533
+ verboseName() {
9534
+ if (this.verboseNameOverride !== null) return this.verboseNameOverride;
9535
+ const className = this.model.name;
9536
+ return humanizeField(className.replace(/Model$/, ""));
9537
+ }
9538
+ /**
9539
+ * Return the plural display name.
9540
+ *
9541
+ * @returns The configured plural, or the singular with an `s`.
9542
+ */
9543
+ verboseNamePlural() {
9544
+ return this.verboseNamePluralOverride ?? `${this.verboseName()}s`;
9545
+ }
9546
+ /**
9547
+ * Return every column key on the model, in declaration order.
9548
+ *
9549
+ * @returns The column keys.
9550
+ */
9551
+ columnNames() {
9552
+ return Object.keys(adminColumns(this.model));
9553
+ }
9554
+ /**
9555
+ * Return the columns the list view renders.
9556
+ *
9557
+ * @returns The configured `listDisplay`, or every column but the password hash.
9558
+ */
9559
+ listDisplayNames() {
9560
+ if (this.listDisplayOverride !== null) return [...this.listDisplayOverride];
9561
+ return this.columnNames().filter((name) => !NEVER_LISTED.includes(name));
9562
+ }
9563
+ /**
9564
+ * Return the columns the detail view renders.
9565
+ *
9566
+ * Unlike {@link AdminModel.listDisplayNames}, this is not narrowed by
9567
+ * `listDisplay`: the list view is a scannable summary, but the detail view is
9568
+ * where an operator goes to see the whole record, so trimming it there would
9569
+ * hide data with nowhere else to read it.
9570
+ *
9571
+ * @returns Every column but the password hash, in declaration order.
9572
+ */
9573
+ detailFieldNames() {
9574
+ return this.columnNames().filter((name) => !NEVER_LISTED.includes(name));
9575
+ }
9576
+ /**
9577
+ * Return the columns a create/edit form exposes.
9578
+ *
9579
+ * Excludes the primary key, the managed timestamps, the password hash and
9580
+ * anything listed in `readonlyFields` — none of which a user edits directly
9581
+ * through the generic form.
9582
+ *
9583
+ * @returns The editable column keys, in declaration order.
9584
+ */
9585
+ editableFieldNames() {
9586
+ const skip = /* @__PURE__ */ new Set([...this.readonlyFields, ...NEVER_EDITABLE]);
9587
+ return this.columnNames().filter((name) => !skip.has(name));
9588
+ }
9589
+ /**
9590
+ * Return the registered custom actions, in declaration order.
9591
+ *
9592
+ * @returns The actions passed via `actions` (empty when none). The model
9593
+ * type is erased here, the way {@link AdminSite} erases it when it stores a
9594
+ * configuration — a registry keyed by slug cannot stay generic.
9595
+ */
9596
+ customActions() {
9597
+ return [...this.actions.values()];
9598
+ }
9599
+ /**
9600
+ * Look a custom action up by name.
9601
+ *
9602
+ * @param name - The action identifier (its submitted form value).
9603
+ * @returns The action, or `null` when nothing matches.
9604
+ */
9605
+ getAction(name) {
9606
+ return this.actions.get(name) ?? null;
9607
+ }
9608
+ /**
9609
+ * Build a repository for this model bound to a session.
9610
+ *
9611
+ * @param session - The session the repository runs its statements on.
9612
+ * @returns A repository over {@link AdminModel.model}.
9613
+ */
9614
+ repository(session) {
9615
+ return new BaseRepository(this.model, session);
9616
+ }
9617
+ };
9618
+
9619
+ // src/admin/forms.ts
9620
+ function formatFieldValue(widget, value) {
9621
+ if (value === null || value === void 0) return "";
9622
+ if (widget === "json") {
9623
+ return typeof value === "string" ? value : JSON.stringify(value, null, 2);
9624
+ }
9625
+ if (value instanceof Date) {
9626
+ const iso = value.toISOString();
9627
+ if (widget === "date") return iso.slice(0, 10);
9628
+ if (widget === "time") return iso.slice(11, 19);
9629
+ return iso.slice(0, 16);
9630
+ }
9631
+ if (widget === "datetime" || widget === "date") {
9632
+ const parsed = new Date(String(value));
9633
+ if (!Number.isNaN(parsed.getTime())) {
9634
+ const iso = parsed.toISOString();
9635
+ return widget === "date" ? iso.slice(0, 10) : iso.slice(0, 16);
9636
+ }
9637
+ }
9638
+ return String(value);
9639
+ }
9640
+ function literalDefault(column6) {
9641
+ const fallback = column6.defaultValue;
9642
+ if (fallback === null || fallback.kind !== "literal") return void 0;
9643
+ return fallback.value;
9644
+ }
9645
+ function buildFormFields(admin, options = {}) {
9646
+ const columns = adminColumns(admin.model);
9647
+ const values = options.values ?? {};
9648
+ const errors = options.errors ?? {};
9649
+ const foreignKeys = options.foreignKeyOptions ?? {};
9650
+ return admin.editableFieldNames().flatMap((name) => {
9651
+ const column6 = columns[name];
9652
+ if (column6 === void 0) return [];
9653
+ const related = foreignKeys[name];
9654
+ const spec = related === void 0 ? widgetForColumn(column6) : { widget: "select", step: null, options: related };
9655
+ const raw = name in values ? values[name] : literalDefault(column6);
9656
+ return [
9657
+ {
9658
+ name,
9659
+ label: humanizeField(name),
9660
+ widget: spec.widget,
9661
+ value: spec.widget === "checkbox" ? "" : formatFieldValue(spec.widget, raw),
9662
+ required: !isColumnOptional(column6),
9663
+ checked: spec.widget === "checkbox" && toBoolean(raw),
9664
+ step: spec.step,
9665
+ options: spec.options,
9666
+ error: errors[name] ?? null
9667
+ }
9668
+ ];
9669
+ });
9670
+ }
9671
+ function toBoolean(value) {
9672
+ if (typeof value === "boolean") return value;
9673
+ if (typeof value === "number") return value !== 0;
9674
+ if (typeof value !== "string") return false;
9675
+ return ["true", "on", "yes", "1"].includes(value.trim().toLowerCase());
9676
+ }
9677
+ function coerceValue(column6, widget, raw) {
9678
+ const { kind, meta } = column6.type;
9679
+ switch (widget) {
9680
+ case "number": {
9681
+ const parsed = Number(raw);
9682
+ if (!Number.isFinite(parsed)) throw new Error("Enter a valid number.");
9683
+ if (kind === "bigint") return BigInt(raw);
9684
+ if (kind === "smallint" || kind === "integer") {
9685
+ if (!Number.isInteger(parsed)) throw new Error("Enter a whole number.");
9686
+ return parsed;
9687
+ }
9688
+ if (kind === "numeric") return raw;
9689
+ return parsed;
9690
+ }
9691
+ case "datetime":
9692
+ case "date": {
9693
+ const parsed = new Date(raw);
9694
+ if (Number.isNaN(parsed.getTime())) throw new Error("Enter a valid date.");
9695
+ return parsed;
9696
+ }
9697
+ case "json":
9698
+ try {
9699
+ return JSON.parse(raw);
9700
+ } catch {
9701
+ throw new Error("Enter valid JSON.");
9702
+ }
9703
+ case "select": {
9704
+ const allowed = kind === "enum" ? meta.values ?? [] : [];
9705
+ if (allowed.length > 0 && !allowed.includes(raw)) {
9706
+ throw new Error(`Choose one of: ${allowed.join(", ")}.`);
9707
+ }
9708
+ return raw;
9709
+ }
9710
+ default:
9711
+ return raw;
9712
+ }
9713
+ }
9714
+ function parseFormBody(admin, body) {
9715
+ const columns = adminColumns(admin.model);
9716
+ const data = {};
9717
+ const errors = {};
9718
+ for (const name of admin.editableFieldNames()) {
9719
+ const column6 = columns[name];
9720
+ if (column6 === void 0) continue;
9721
+ const { widget } = widgetForColumn(column6);
9722
+ if (widget === "checkbox") {
9723
+ data[name] = toBoolean(body[name]);
9724
+ continue;
9725
+ }
9726
+ const submitted = body[name];
9727
+ const raw = typeof submitted === "string" ? submitted.trim() : "";
9728
+ if (raw === "") {
9729
+ if (!isColumnOptional(column6)) {
9730
+ errors[name] = "This field is required.";
9731
+ continue;
9732
+ }
9733
+ if (column6.flags.hasDefault && !(name in body)) continue;
9734
+ data[name] = null;
9735
+ continue;
9736
+ }
9737
+ try {
9738
+ data[name] = coerceValue(column6, widget, raw);
9739
+ } catch (error) {
9740
+ errors[name] = error instanceof Error ? error.message : "Invalid value.";
9741
+ }
9742
+ }
9743
+ return { data, errors };
9744
+ }
9745
+ function formatCellValue(value) {
9746
+ if (value === null || value === void 0) return "";
9747
+ if (value instanceof Date) return value.toISOString().replace("T", " ").slice(0, 19);
9748
+ if (typeof value === "boolean") return value ? "Yes" : "No";
9749
+ if (typeof value === "object") return JSON.stringify(value);
9750
+ return String(value);
9751
+ }
9752
+ function foreignKeyFields(admin) {
9753
+ const columns = adminColumns(admin.model);
9754
+ const out = {};
9755
+ for (const name of admin.editableFieldNames()) {
9756
+ const column6 = columns[name];
9757
+ if (column6 === void 0) continue;
9758
+ const table = foreignKeyTable(column6);
9759
+ if (table !== null) out[name] = table;
9760
+ }
9761
+ return out;
9762
+ }
9763
+ function foreignKeyLabel(admin, row) {
9764
+ for (const field of admin.searchFields) {
9765
+ const value = row[field];
9766
+ if (typeof value === "string" && value !== "") return value;
9767
+ }
9768
+ for (const field of ["name", "title", "email", "label", "reference"]) {
9769
+ const value = row[field];
9770
+ if (typeof value === "string" && value !== "") return value;
9771
+ }
9772
+ return String(row[admin.identityField] ?? "");
9773
+ }
9774
+
9775
+ // src/admin/auth.ts
9776
+ var UserModelAuthBackend = class {
9777
+ model;
9778
+ passwords;
9779
+ mfa;
9780
+ identifierField;
9781
+ requireAdmin;
9782
+ /**
9783
+ * Build the backend.
9784
+ *
9785
+ * @param model - The user model class (a `BaseUserModel` subclass).
9786
+ * @param options - Hasher, MFA verifier and gating overrides.
9787
+ */
9788
+ constructor(model, options = {}) {
9789
+ this.model = model;
9790
+ this.passwords = options.passwords ?? new PasswordUtils();
9791
+ this.mfa = options.mfa ?? null;
9792
+ this.identifierField = options.identifierField ?? "email";
9793
+ this.requireAdmin = options.requireAdmin ?? true;
9794
+ }
9795
+ /**
9796
+ * Whether a row is allowed into the panel at all.
9797
+ *
9798
+ * @param row - The candidate row.
9799
+ * @returns `true` when the row is active and (when required) an admin.
9800
+ */
9801
+ admits(row) {
9802
+ if (row.isActive === false) return false;
9803
+ return !this.requireAdmin || row.isAdmin === true;
9804
+ }
9805
+ /**
9806
+ * Verify an identifier/password pair.
9807
+ *
9808
+ * The identifier is lowercased and trimmed before lookup, matching the
9809
+ * normalization the auth service applies on signup.
9810
+ *
9811
+ * @param session - A DB session for the current request.
9812
+ * @param identifier - The submitted identifier.
9813
+ * @param password - The submitted plaintext password.
9814
+ * @returns The matching row, or `null` when it does not qualify.
9815
+ */
9816
+ async authenticate(session, identifier, password) {
9817
+ const repository = new BaseRepository(this.model, session);
9818
+ const filters = { [this.identifierField]: identifier.trim().toLowerCase() };
9819
+ const row = await repository.first(
9820
+ filters
9821
+ );
9822
+ if (row === null || !this.admits(row)) return null;
9823
+ if (!await this.passwords.verify(password, row.hashedPassword)) return null;
9824
+ return row;
9825
+ }
9826
+ /**
9827
+ * Re-load the principal a session points at.
9828
+ *
9829
+ * @param session - A DB session for the current request.
9830
+ * @param subject - The principal id from the session cookie.
9831
+ * @returns The row, or `null` when it vanished or lost its privileges.
9832
+ */
9833
+ async loadPrincipal(session, subject) {
9834
+ const repository = new BaseRepository(this.model, session);
9835
+ const row = await repository.getByIdOrNull(
9836
+ subject
9837
+ );
9838
+ if (row === null || !this.admits(row)) return null;
9839
+ return row;
9840
+ }
9841
+ /**
9842
+ * Return the row's primary key.
9843
+ *
9844
+ * @param principal - The authenticated row.
9845
+ * @returns The principal id.
9846
+ */
9847
+ principalId(principal) {
9848
+ return String(principal.id);
9849
+ }
9850
+ /**
9851
+ * Return the label shown in the panel header.
9852
+ *
9853
+ * @param principal - The authenticated row.
9854
+ * @returns The identifier column's value.
9855
+ */
9856
+ displayName(principal) {
9857
+ const value = principal[this.identifierField];
9858
+ return typeof value === "string" ? value : String(principal.id);
9859
+ }
9860
+ /**
9861
+ * Whether the principal enrolled a second factor.
9862
+ *
9863
+ * @param principal - The authenticated row.
9864
+ * @returns `true` when an MFA verifier is configured and reports a secret.
9865
+ */
9866
+ async mfaEnabled(principal) {
9867
+ if (this.mfa === null) return false;
9868
+ return await this.mfa.isEnabled(String(principal.id));
9869
+ }
9870
+ /**
9871
+ * Verify a submitted TOTP code.
9872
+ *
9873
+ * @param principal - The authenticated row.
9874
+ * @param code - The submitted code.
9875
+ * @returns `true` when the code is valid.
9876
+ */
9877
+ async verifyMfa(principal, code) {
9878
+ if (this.mfa === null) return false;
9879
+ return await this.mfa.verify(String(principal.id), code);
9880
+ }
9881
+ };
9882
+ var MIN_SECRET_LENGTH = 32;
9883
+ function encode(value) {
9884
+ return Buffer.from(value, "utf8").toString("base64url");
9885
+ }
9886
+ var AdminSessionStore = class {
9887
+ secret;
9888
+ cookieName;
9889
+ maxAgeSeconds;
9890
+ cookieSecure;
9891
+ cookiePath;
9892
+ /**
9893
+ * Build the store.
9894
+ *
9895
+ * @param options - Secret, cookie name, lifetime and cookie flags.
9896
+ * @throws Error When the secret is shorter than 32 characters.
9897
+ */
9898
+ constructor(options) {
9899
+ if (options.secret.length < MIN_SECRET_LENGTH) {
9900
+ throw new Error(
9901
+ `Admin session secret must be at least ${MIN_SECRET_LENGTH} characters; got ${options.secret.length}`
9902
+ );
9903
+ }
9904
+ this.secret = options.secret;
9905
+ this.cookieName = options.cookieName ?? "tempest_admin_session";
9906
+ this.maxAgeSeconds = options.maxAgeSeconds ?? 8 * 60 * 60;
9907
+ this.cookieSecure = options.cookieSecure ?? true;
9908
+ this.cookiePath = options.cookiePath ?? "/";
9909
+ }
9910
+ /**
9911
+ * Sign a payload.
9912
+ *
9913
+ * @param payload - The base64url payload to sign.
9914
+ * @returns The base64url signature.
9915
+ */
9916
+ sign(payload) {
9917
+ return createHmac("sha256", this.secret).update(payload).digest("base64url");
9918
+ }
9919
+ /**
9920
+ * Mint a fresh session for an authenticated principal.
9921
+ *
9922
+ * @param subject - The principal id.
9923
+ * @param displayName - The name shown in the header.
9924
+ * @param mfaPassed - Whether the second factor is already satisfied.
9925
+ * @returns The new session payload (not yet written to a response).
9926
+ */
9927
+ issue(subject, displayName, mfaPassed = true) {
9928
+ return {
9929
+ subject,
9930
+ displayName,
9931
+ csrfToken: randomUUID(),
9932
+ expiresAt: Math.floor(Date.now() / 1e3) + this.maxAgeSeconds,
9933
+ mfaPassed
9934
+ };
9935
+ }
9936
+ /**
9937
+ * Read and verify the session carried by a request.
9938
+ *
9939
+ * @param req - The inbound request.
9940
+ * @returns The session, or `null` when absent, tampered with or expired.
9941
+ */
9942
+ load(req) {
9943
+ const raw = parseCookies(req.header("cookie") ?? void 0)[this.cookieName];
9944
+ if (raw === void 0) return null;
9945
+ const separator = raw.lastIndexOf(".");
9946
+ if (separator <= 0) return null;
9947
+ const payload = raw.slice(0, separator);
9948
+ const signature = Buffer.from(raw.slice(separator + 1), "base64url");
9949
+ const expected = Buffer.from(this.sign(payload), "base64url");
9950
+ if (signature.length !== expected.length) return null;
9951
+ if (!timingSafeEqual(signature, expected)) return null;
9952
+ let session;
9953
+ try {
9954
+ session = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
9955
+ } catch {
9956
+ return null;
9957
+ }
9958
+ if (typeof session.subject !== "string" || typeof session.csrfToken !== "string") {
9959
+ return null;
9960
+ }
9961
+ if (session.expiresAt <= Math.floor(Date.now() / 1e3)) return null;
9962
+ return session;
9963
+ }
9964
+ /**
9965
+ * Write a session to the response as a signed cookie.
9966
+ *
9967
+ * @param res - The outbound response.
9968
+ * @param session - The session to persist.
9969
+ */
9970
+ save(res, session) {
9971
+ const payload = encode(JSON.stringify(session));
9972
+ const value = `${payload}.${this.sign(payload)}`;
9973
+ const maxAge = Math.max(0, session.expiresAt - Math.floor(Date.now() / 1e3));
9974
+ res.append("set-cookie", this.cookie(value, maxAge));
9975
+ }
9976
+ /**
9977
+ * Drop the session cookie.
9978
+ *
9979
+ * @param res - The outbound response.
9980
+ */
9981
+ clear(res) {
9982
+ res.append("set-cookie", this.cookie("", 0));
9983
+ }
9984
+ /**
9985
+ * Render a `Set-Cookie` value with the configured flags.
9986
+ *
9987
+ * @param value - The cookie value.
9988
+ * @param maxAge - Lifetime in seconds (`0` expires it immediately).
9989
+ * @returns The header value.
9990
+ */
9991
+ cookie(value, maxAge) {
9992
+ const parts = [
9993
+ `${this.cookieName}=${value}`,
9994
+ `Path=${this.cookiePath}`,
9995
+ `Max-Age=${maxAge}`,
9996
+ "HttpOnly",
9997
+ "SameSite=Lax"
9998
+ ];
9999
+ if (this.cookieSecure) parts.push("Secure");
10000
+ return parts.join("; ");
10001
+ }
10002
+ };
10003
+ function csrfTokenMatches(session, submitted) {
10004
+ if (typeof submitted !== "string") return false;
10005
+ const expected = Buffer.from(session.csrfToken, "utf8");
10006
+ const actual = Buffer.from(submitted, "utf8");
10007
+ if (expected.length !== actual.length) return false;
10008
+ return timingSafeEqual(expected, actual);
10009
+ }
10010
+
9320
10011
  // src/admin/site.ts
10012
+ function isConcreteModel(value) {
10013
+ if (typeof value !== "function") return false;
10014
+ const proto = value.prototype;
10015
+ if (typeof proto !== "object" || proto === null) return false;
10016
+ if (!(proto instanceof Model)) return false;
10017
+ const tablename = value.tablename;
10018
+ return typeof tablename === "string" && tablename.length > 0;
10019
+ }
9321
10020
  var AdminSite = class {
10021
+ /** Text used in the page `<title>` and the dashboard heading. */
10022
+ title;
10023
+ /** Centered header brand, or `null` to fall back to {@link AdminSite.title}. */
10024
+ brand;
10025
+ /** Dashboard subtitle. */
10026
+ indexSubtitle;
10027
+ /** Outbound "View site" link, or `null`. */
10028
+ siteUrl;
10029
+ /** Typed appearance overrides. */
10030
+ theme;
10031
+ registry = /* @__PURE__ */ new Map();
10032
+ /**
10033
+ * Initialize the site.
10034
+ *
10035
+ * @param options - Branding and appearance. See {@link AdminSiteOptions}.
10036
+ */
10037
+ constructor(options = {}) {
10038
+ this.title = options.title ?? "Admin";
10039
+ this.brand = options.brand ?? null;
10040
+ this.indexSubtitle = options.indexSubtitle ?? "Site administration";
10041
+ this.siteUrl = options.siteUrl ?? null;
10042
+ this.theme = options.theme ?? {};
10043
+ }
10044
+ /**
10045
+ * Return the centered header brand text.
10046
+ *
10047
+ * @returns {@link AdminSite.brand} when set, otherwise {@link AdminSite.title}.
10048
+ */
10049
+ brandText() {
10050
+ return this.brand ?? this.title;
10051
+ }
10052
+ /**
10053
+ * Register a model configuration under its slug.
10054
+ *
10055
+ * @param admin - An {@link AdminModel} instance, or the options to build one.
10056
+ * @returns The registered instance, so the call can be chained or assigned.
10057
+ * @throws Error When another configuration already holds the same slug.
10058
+ */
10059
+ register(admin) {
10060
+ const config = admin instanceof AdminModel ? admin : new AdminModel(admin);
10061
+ const slug = config.slug();
10062
+ const existing = this.registry.get(slug);
10063
+ if (existing !== void 0) {
10064
+ throw new Error(
10065
+ `AdminModel for slug "${slug}" is already registered (${existing.model.tablename}); refusing to overwrite with ${config.model.tablename}`
10066
+ );
10067
+ }
10068
+ this.registry.set(slug, config);
10069
+ return config;
10070
+ }
10071
+ /**
10072
+ * Remove a previously registered configuration.
10073
+ *
10074
+ * @param slug - The slug to drop.
10075
+ * @throws Error When no configuration is registered under the slug.
10076
+ */
10077
+ unregister(slug) {
10078
+ if (!this.registry.delete(slug)) {
10079
+ throw new Error(`No AdminModel registered for slug "${slug}"`);
10080
+ }
10081
+ }
10082
+ /**
10083
+ * Look a configuration up by slug.
10084
+ *
10085
+ * @param slug - The admin slug.
10086
+ * @returns The configuration, or `null` when nothing matches.
10087
+ */
10088
+ get(slug) {
10089
+ return this.registry.get(slug) ?? null;
10090
+ }
10091
+ /**
10092
+ * Return every registered configuration, ordered by display name.
10093
+ *
10094
+ * @returns The configurations (empty when nothing is registered).
10095
+ */
10096
+ list() {
10097
+ return [...this.registry.values()].sort(
10098
+ (left, right) => left.verboseNamePlural().toLowerCase().localeCompare(right.verboseNamePlural().toLowerCase())
10099
+ );
10100
+ }
10101
+ /**
10102
+ * Register every concrete model found in `source` at once.
10103
+ *
10104
+ * The batch counterpart to {@link AdminSite.register}: instead of one call
10105
+ * per table, hand it the models barrel and every model class declaring a
10106
+ * `tablename` is wrapped in a default {@link AdminModel}.
10107
+ *
10108
+ * ```ts
10109
+ * import * as models from "./db/models";
10110
+ *
10111
+ * site.automap(models);
10112
+ * site.automap([UserModel, OrderModel], { pageSize: 50 });
10113
+ * ```
10114
+ *
10115
+ * @param source - An array of model classes, or a module namespace object
10116
+ * whose values are swept (non-model entries are ignored).
10117
+ * @param options - `exclude`, `skipRegistered` and any {@link AdminModel}
10118
+ * option applied uniformly to every model discovered here.
10119
+ * @returns The configurations newly registered by this call.
10120
+ * @throws Error When `skipRegistered` is `false` and a slug collides.
10121
+ */
10122
+ automap(source, options = {}) {
10123
+ const { exclude = [], skipRegistered = true, ...adminOptions } = options;
10124
+ const excluded = new Set(
10125
+ exclude.map((entry) => typeof entry === "string" ? entry : entry.tablename)
10126
+ );
10127
+ const candidates = Array.isArray(source) ? source : Object.values(source);
10128
+ const registered = [];
10129
+ for (const candidate of candidates) {
10130
+ if (!isConcreteModel(candidate)) continue;
10131
+ if (excluded.has(candidate.tablename)) continue;
10132
+ const config = new AdminModel({ ...adminOptions, model: candidate });
10133
+ if (skipRegistered && this.registry.get(config.slug()) !== void 0) continue;
10134
+ registered.push(this.register(config));
10135
+ }
10136
+ return registered.sort((left, right) => left.slug().localeCompare(right.slug()));
10137
+ }
10138
+ };
10139
+
10140
+ // src/admin/styles.ts
10141
+ var ADMIN_CSS = `:root {
10142
+ --tempest-bg: #0f172a;
10143
+ --tempest-bg-soft: #1e293b;
10144
+ --tempest-bg-row: #f8fafc;
10145
+ --tempest-bg-row-alt: #f1f5f9;
10146
+ --tempest-fg: #0f172a;
10147
+ --tempest-fg-soft: #475569;
10148
+ --tempest-accent: #2563eb;
10149
+ --tempest-accent-hover: #1d4ed8;
10150
+ --tempest-accent-soft: rgba(37, 99, 235, 0.1);
10151
+ --tempest-danger: #b91c1c;
10152
+ /* Light surface + hairline used by cards / tables / dropdowns on the
10153
+ (light) content area \u2014 distinct from the dark sidebar bg vars above.
10154
+ Overridable by AdminTheme for dark mode. */
10155
+ --tempest-surface: #ffffff;
10156
+ --tempest-border: #e2e8f0;
10157
+ --tempest-radius: 6px;
10158
+ --tempest-shadow: 0 1px 2px rgba(15, 23, 42, 0.08);
10159
+ }
10160
+
10161
+ * {
10162
+ box-sizing: border-box;
10163
+ }
10164
+
10165
+ body {
10166
+ margin: 0;
10167
+ font-family: var(--tempest-font, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif);
10168
+ font-size: 14px;
10169
+ color: var(--tempest-fg);
10170
+ background: var(--tempest-page-bg, #f8fafc);
10171
+ /* Sticky-footer column so the layout (and its sidebar) fills the
10172
+ viewport even when the page content is short. */
10173
+ min-height: 100vh;
10174
+ display: flex;
10175
+ flex-direction: column;
10176
+ }
10177
+
10178
+ a {
10179
+ color: var(--tempest-accent);
10180
+ text-decoration: none;
10181
+ }
10182
+
10183
+ a:hover {
10184
+ color: var(--tempest-accent-hover);
10185
+ text-decoration: underline;
10186
+ }
10187
+
10188
+ button {
10189
+ border: 0;
10190
+ background: var(--tempest-accent);
10191
+ color: #fff;
10192
+ padding: 0.5rem 1rem;
10193
+ border-radius: var(--tempest-radius);
10194
+ cursor: pointer;
10195
+ font: inherit;
10196
+ }
10197
+
10198
+ button:hover {
10199
+ background: var(--tempest-accent-hover);
10200
+ }
10201
+
10202
+ input,
10203
+ select,
10204
+ textarea {
10205
+ font: inherit;
10206
+ padding: 0.45rem 0.6rem;
10207
+ border-radius: var(--tempest-radius);
10208
+ border: 1px solid #cbd5e1;
10209
+ background: #fff;
10210
+ }
10211
+
10212
+ .tempest-admin-header {
10213
+ position: relative;
10214
+ z-index: 20;
10215
+ background: var(--tempest-bg);
10216
+ color: #f8fafc;
10217
+ padding: 0.75rem 1.5rem;
10218
+ display: flex;
10219
+ align-items: center;
10220
+ justify-content: space-between;
10221
+ box-shadow: var(--tempest-shadow);
10222
+ }
10223
+
10224
+ /* Centered brand \u2014 pinned to the middle of the header (i.e. the screen)
10225
+ regardless of the left (burger) / right (nav) cluster widths. */
10226
+ .tempest-admin-header__brand {
10227
+ position: absolute;
10228
+ left: 50%;
10229
+ transform: translateX(-50%);
10230
+ text-align: center;
10231
+ pointer-events: none;
10232
+ }
10233
+
10234
+ .tempest-admin-header__brand a {
10235
+ color: #fff;
10236
+ font-weight: 600;
10237
+ font-size: 1.1rem;
10238
+ pointer-events: auto;
10239
+ display: inline-flex;
10240
+ align-items: center;
10241
+ }
10242
+
10243
+ /* Logo image (shown instead of the brand text when theme.logo_url is
10244
+ set). Capped to the header height so any aspect ratio fits cleanly. */
10245
+ .tempest-admin-header__logo {
10246
+ display: block;
10247
+ max-height: 32px;
10248
+ width: auto;
10249
+ }
10250
+
10251
+ .tempest-admin-header__nav {
10252
+ display: flex;
10253
+ align-items: center;
10254
+ gap: 1rem;
10255
+ color: #cbd5e1;
10256
+ }
10257
+
10258
+ .tempest-admin-header__nav a {
10259
+ color: #cbd5e1;
10260
+ }
10261
+
10262
+ .tempest-admin-header__user {
10263
+ font-weight: 500;
10264
+ color: #f1f5f9;
10265
+ }
10266
+
10267
+ .tempest-admin-header__logout {
10268
+ margin: 0;
10269
+ }
10270
+
10271
+ .tempest-admin-header__logout button {
10272
+ background: transparent;
10273
+ color: #f1f5f9;
10274
+ padding: 0.25rem 0.5rem;
10275
+ border: 1px solid #475569;
10276
+ }
10277
+
10278
+ .tempest-admin-header__logout button:hover {
10279
+ background: rgba(255, 255, 255, 0.08);
10280
+ }
10281
+
10282
+ .tempest-admin-header__left {
10283
+ display: flex;
10284
+ align-items: center;
10285
+ gap: 0.75rem;
10286
+ }
10287
+
10288
+ /* ---- Layout: persistent sidebar + content ---- */
10289
+ .tempest-admin-layout {
10290
+ display: flex;
10291
+ align-items: stretch;
10292
+ flex: 1; /* fill the viewport so the sidebar is full-height */
10293
+ }
10294
+
10295
+ .tempest-admin-sidebar {
10296
+ flex: 0 0 220px;
10297
+ width: 220px;
10298
+ background: var(--tempest-bg-soft);
10299
+ color: #e2e8f0;
10300
+ padding: 1rem 0.75rem;
10301
+ }
10302
+
10303
+ .tempest-admin-sidebar__nav {
10304
+ display: flex;
10305
+ flex-direction: column;
10306
+ gap: 0.15rem;
10307
+ position: sticky;
10308
+ top: 1rem;
10309
+ }
10310
+
10311
+ .tempest-admin-sidebar__heading {
10312
+ font-size: 0.7rem;
10313
+ text-transform: uppercase;
10314
+ letter-spacing: 0.06em;
10315
+ color: #94a3b8;
10316
+ margin: 1rem 0.75rem 0.35rem;
10317
+ }
10318
+
10319
+ .tempest-admin-sidebar__link {
10320
+ display: block;
10321
+ padding: 0.5rem 0.75rem;
10322
+ border-radius: var(--tempest-radius);
10323
+ color: #cbd5e1;
10324
+ }
10325
+
10326
+ .tempest-admin-sidebar__link:hover {
10327
+ background: rgba(255, 255, 255, 0.06);
10328
+ color: #fff;
10329
+ text-decoration: none;
10330
+ }
10331
+
10332
+ .tempest-admin-sidebar__link--active,
10333
+ .tempest-admin-sidebar__link--active:hover {
10334
+ background: var(--tempest-accent);
10335
+ color: #fff;
10336
+ }
10337
+
10338
+ /* Burger toggle (CSS-only, via the hidden checkbox) \u2014 mobile only. */
10339
+ .tempest-admin-burger {
10340
+ display: none;
10341
+ flex-direction: column;
10342
+ gap: 4px;
10343
+ cursor: pointer;
10344
+ padding: 0.3rem;
10345
+ }
10346
+
10347
+ .tempest-admin-burger span {
10348
+ display: block;
10349
+ width: 22px;
10350
+ height: 2px;
10351
+ background: #f8fafc;
10352
+ border-radius: 2px;
10353
+ }
10354
+
10355
+ .tempest-admin-scrim {
10356
+ display: none;
10357
+ }
10358
+
10359
+ .tempest-admin-main {
10360
+ flex: 1 1 auto;
10361
+ min-width: 0;
10362
+ max-width: 1080px;
10363
+ margin: 2rem auto;
10364
+ padding: 0 1.5rem;
10365
+ }
10366
+
10367
+ .tempest-admin-messages {
10368
+ list-style: none;
10369
+ padding: 0;
10370
+ margin: 0 0 1.5rem;
10371
+ display: flex;
10372
+ flex-direction: column;
10373
+ gap: 0.5rem;
10374
+ }
10375
+
10376
+ .tempest-admin-messages__item {
10377
+ padding: 0.75rem 1rem;
10378
+ border-radius: var(--tempest-radius);
10379
+ border-left: 4px solid var(--tempest-accent);
10380
+ background: #eff6ff;
10381
+ }
10382
+
10383
+ .tempest-admin-messages__item--error {
10384
+ border-left-color: var(--tempest-danger);
10385
+ background: #fef2f2;
10386
+ }
10387
+
10388
+ .tempest-admin-login {
10389
+ max-width: 360px;
10390
+ margin: 4rem auto;
10391
+ background: #fff;
10392
+ border-radius: var(--tempest-radius);
10393
+ padding: 2rem;
10394
+ box-shadow: var(--tempest-shadow);
10395
+ }
10396
+
10397
+ .tempest-admin-login h1 {
10398
+ margin-top: 0;
10399
+ }
10400
+
10401
+ .tempest-admin-login__form {
10402
+ display: flex;
10403
+ flex-direction: column;
10404
+ gap: 1rem;
10405
+ }
10406
+
10407
+ .tempest-admin-login__form label {
10408
+ display: flex;
10409
+ flex-direction: column;
10410
+ gap: 0.25rem;
10411
+ }
10412
+
10413
+ .tempest-admin-login__error {
10414
+ background: #fef2f2;
10415
+ color: var(--tempest-danger);
10416
+ padding: 0.75rem 1rem;
10417
+ border-radius: var(--tempest-radius);
10418
+ }
10419
+
10420
+ .tempest-admin-dashboard__table,
10421
+ .tempest-admin-list__table {
10422
+ width: 100%;
10423
+ border-collapse: collapse;
10424
+ background: #fff;
10425
+ border-radius: var(--tempest-radius);
10426
+ overflow: hidden;
10427
+ box-shadow: var(--tempest-shadow);
10428
+ }
10429
+
10430
+ .tempest-admin-dashboard__table th,
10431
+ .tempest-admin-dashboard__table td,
10432
+ .tempest-admin-list__table th,
10433
+ .tempest-admin-list__table td {
10434
+ padding: 0.75rem 1rem;
10435
+ text-align: left;
10436
+ border-bottom: 1px solid #e2e8f0;
10437
+ vertical-align: top;
10438
+ }
10439
+
10440
+ .tempest-admin-list__table tr:nth-child(even) td {
10441
+ background: var(--tempest-bg-row-alt);
10442
+ }
10443
+
10444
+ .tempest-admin-list__header {
10445
+ display: flex;
10446
+ justify-content: space-between;
10447
+ align-items: baseline;
10448
+ margin-bottom: 1rem;
10449
+ }
10450
+
10451
+ .tempest-admin-list__filters {
10452
+ display: flex;
10453
+ gap: 0.75rem;
10454
+ align-items: end;
10455
+ margin-bottom: 1rem;
10456
+ flex-wrap: wrap;
10457
+ }
10458
+
10459
+ .tempest-admin-list__filters label {
10460
+ display: flex;
10461
+ flex-direction: column;
10462
+ gap: 0.25rem;
10463
+ }
10464
+
10465
+ .tempest-admin-list__pagination {
10466
+ display: flex;
10467
+ gap: 1rem;
10468
+ align-items: center;
10469
+ justify-content: center;
10470
+ margin-top: 1.5rem;
10471
+ color: var(--tempest-fg-soft);
10472
+ }
10473
+
10474
+ .tempest-admin-detail__fields {
10475
+ display: grid;
10476
+ grid-template-columns: 200px 1fr;
10477
+ gap: 0.5rem 1.5rem;
10478
+ background: #fff;
10479
+ border-radius: var(--tempest-radius);
10480
+ padding: 1.5rem;
10481
+ box-shadow: var(--tempest-shadow);
10482
+ }
10483
+
10484
+ .tempest-admin-detail__fields dt {
10485
+ font-weight: 600;
10486
+ color: var(--tempest-fg-soft);
10487
+ }
10488
+
10489
+ .tempest-admin-detail__fields dd {
10490
+ margin: 0;
10491
+ word-break: break-word;
10492
+ }
10493
+
10494
+ .tempest-admin-detail__audit-title {
10495
+ font-size: 1rem;
10496
+ margin: 1.5rem 0 0.5rem;
10497
+ color: var(--tempest-fg-soft);
10498
+ }
10499
+
10500
+ .tempest-admin-detail__json {
10501
+ margin: 0;
10502
+ padding: 0.5rem 0.75rem;
10503
+ background: var(--tempest-bg-row);
10504
+ border: 1px solid var(--tempest-border);
10505
+ border-radius: var(--tempest-radius);
10506
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
10507
+ font-size: 0.8rem;
10508
+ overflow-x: auto;
10509
+ }
10510
+
10511
+ .tempest-admin-history {
10512
+ list-style: none;
10513
+ margin: 0;
10514
+ padding: 0;
10515
+ border-left: 2px solid var(--tempest-border);
10516
+ }
10517
+
10518
+ .tempest-admin-history__item {
10519
+ position: relative;
10520
+ padding: 0.5rem 0 1rem 1rem;
10521
+ }
10522
+
10523
+ .tempest-admin-history__item::before {
10524
+ content: "";
10525
+ position: absolute;
10526
+ left: -0.4rem;
10527
+ top: 0.9rem;
10528
+ width: 0.6rem;
10529
+ height: 0.6rem;
10530
+ border-radius: 50%;
10531
+ background: var(--tempest-fg-soft);
10532
+ }
10533
+
10534
+ .tempest-admin-history__item--create::before { background: #16a34a; }
10535
+ .tempest-admin-history__item--update::before { background: #d97706; }
10536
+ .tempest-admin-history__item--delete::before { background: #dc2626; }
10537
+
10538
+ .tempest-admin-history__head {
10539
+ display: flex;
10540
+ gap: 0.75rem;
10541
+ align-items: baseline;
10542
+ flex-wrap: wrap;
10543
+ }
10544
+
10545
+ .tempest-admin-history__action {
10546
+ font-weight: 600;
10547
+ text-transform: uppercase;
10548
+ font-size: 0.75rem;
10549
+ letter-spacing: 0.04em;
10550
+ }
10551
+
10552
+ .tempest-admin-history__meta {
10553
+ color: var(--tempest-fg-soft);
10554
+ font-size: 0.85rem;
10555
+ }
10556
+
10557
+ .tempest-admin-history__changes {
10558
+ width: 100%;
10559
+ border-collapse: collapse;
10560
+ margin-top: 0.5rem;
10561
+ font-size: 0.85rem;
10562
+ }
10563
+
10564
+ .tempest-admin-history__changes th,
10565
+ .tempest-admin-history__changes td {
10566
+ text-align: left;
10567
+ padding: 0.25rem 0.5rem;
10568
+ border-bottom: 1px solid var(--tempest-border);
10569
+ vertical-align: top;
10570
+ word-break: break-word;
10571
+ }
10572
+
10573
+ .tempest-admin-history__changes th {
10574
+ color: var(--tempest-fg-soft);
10575
+ font-weight: 600;
10576
+ }
10577
+
10578
+ .tempest-admin-history__empty {
10579
+ color: var(--tempest-fg-soft);
10580
+ }
10581
+
10582
+ .tempest-admin-ac {
10583
+ position: relative;
10584
+ }
10585
+
10586
+ .tempest-admin-ac__search {
10587
+ width: 100%;
10588
+ }
10589
+
10590
+ .tempest-admin-ac__results {
10591
+ list-style: none;
10592
+ margin: 0.25rem 0 0;
10593
+ padding: 0;
10594
+ border: 1px solid var(--tempest-border);
10595
+ border-radius: var(--tempest-radius, 6px);
10596
+ max-height: 12rem;
10597
+ overflow-y: auto;
10598
+ background: var(--tempest-surface);
10599
+ }
10600
+
10601
+ .tempest-admin-ac__results:empty {
10602
+ display: none;
10603
+ }
10604
+
10605
+ .tempest-admin-ac__option {
10606
+ display: block;
10607
+ width: 100%;
10608
+ text-align: left;
10609
+ padding: 0.4rem 0.6rem;
10610
+ background: none;
10611
+ border: 0;
10612
+ cursor: pointer;
10613
+ color: inherit;
10614
+ font: inherit;
10615
+ }
10616
+
10617
+ .tempest-admin-ac__option:hover,
10618
+ .tempest-admin-ac__option:focus {
10619
+ background: var(--tempest-accent-soft, rgba(0, 0, 0, 0.06));
10620
+ }
10621
+
10622
+ .tempest-admin-ac__empty {
10623
+ padding: 0.4rem 0.6rem;
10624
+ color: var(--tempest-fg-soft);
10625
+ }
10626
+
10627
+ .tempest-admin-inline {
10628
+ margin-top: 2rem;
10629
+ }
10630
+
10631
+ .tempest-admin-inline__header {
10632
+ display: flex;
10633
+ align-items: center;
10634
+ justify-content: space-between;
10635
+ gap: 1rem;
10636
+ margin-bottom: 0.5rem;
10637
+ }
10638
+
10639
+ .tempest-admin-inline__header h2 {
10640
+ font-size: 1rem;
10641
+ margin: 0;
10642
+ color: var(--tempest-fg-soft);
10643
+ }
10644
+
10645
+ .tempest-admin-inline__count {
10646
+ font-weight: 400;
10647
+ }
10648
+
10649
+ .tempest-admin-inline__scroll {
10650
+ overflow-x: auto;
10651
+ }
10652
+
10653
+ .tempest-admin-inline__table {
10654
+ width: 100%;
10655
+ border-collapse: collapse;
10656
+ font-size: 0.9rem;
10657
+ }
10658
+
10659
+ .tempest-admin-inline__table th,
10660
+ .tempest-admin-inline__table td {
10661
+ text-align: left;
10662
+ padding: 0.4rem 0.6rem;
10663
+ border-bottom: 1px solid var(--tempest-border);
10664
+ white-space: nowrap;
10665
+ }
10666
+
10667
+ .tempest-admin-inline__table th {
10668
+ color: var(--tempest-fg-soft);
10669
+ font-weight: 600;
10670
+ }
10671
+
10672
+ .tempest-admin-inline__empty,
10673
+ .tempest-admin-inline__more {
10674
+ color: var(--tempest-fg-soft);
10675
+ }
10676
+
10677
+ .tempest-admin-cards {
10678
+ display: grid;
10679
+ grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr));
10680
+ gap: 1rem;
10681
+ margin: 1rem 0 2rem;
10682
+ }
10683
+
10684
+ .tempest-admin-card {
10685
+ display: flex;
10686
+ flex-direction: column;
10687
+ gap: 0.35rem;
10688
+ padding: 1rem 1.1rem;
10689
+ border: 1px solid var(--tempest-border);
10690
+ border-radius: var(--tempest-radius, 8px);
10691
+ background: var(--tempest-surface);
10692
+ }
10693
+
10694
+ .tempest-admin-card__label {
10695
+ font-size: 0.8rem;
10696
+ color: var(--tempest-fg-soft);
10697
+ text-transform: uppercase;
10698
+ letter-spacing: 0.04em;
10699
+ }
10700
+
10701
+ .tempest-admin-card__value {
10702
+ font-size: 1.7rem;
10703
+ font-weight: 700;
10704
+ line-height: 1.1;
10705
+ }
10706
+
10707
+ .tempest-admin-card__value small {
10708
+ font-size: 0.9rem;
10709
+ font-weight: 400;
10710
+ color: var(--tempest-fg-soft);
10711
+ }
10712
+
10713
+ .tempest-admin-card__trend {
10714
+ font-size: 0.9rem;
10715
+ font-weight: 600;
10716
+ }
10717
+
10718
+ .tempest-admin-card__trend small {
10719
+ font-weight: 400;
10720
+ color: var(--tempest-fg-soft);
10721
+ }
10722
+
10723
+ .tempest-admin-card__trend--up { color: #16a34a; }
10724
+ .tempest-admin-card__trend--down { color: #dc2626; }
10725
+ .tempest-admin-card__trend--flat { color: var(--tempest-fg-soft); }
10726
+
10727
+ .tempest-admin-card__parts {
10728
+ list-style: none;
10729
+ margin: 0.25rem 0 0;
10730
+ padding: 0;
10731
+ display: flex;
10732
+ flex-direction: column;
10733
+ gap: 0.3rem;
10734
+ }
10735
+
10736
+ .tempest-admin-card__parts li {
10737
+ display: grid;
10738
+ grid-template-columns: 6rem 1fr auto;
10739
+ align-items: center;
10740
+ gap: 0.5rem;
10741
+ font-size: 0.85rem;
10742
+ }
10743
+
10744
+ .tempest-admin-card__part-label {
10745
+ overflow: hidden;
10746
+ text-overflow: ellipsis;
10747
+ white-space: nowrap;
10748
+ color: var(--tempest-fg-soft);
10749
+ }
10750
+
10751
+ .tempest-admin-card__part-bar {
10752
+ display: block;
10753
+ height: 0.5rem;
10754
+ border-radius: 999px;
10755
+ background: var(--tempest-border);
10756
+ overflow: hidden;
10757
+ }
10758
+
10759
+ .tempest-admin-card__part-bar span {
10760
+ display: block;
10761
+ height: 100%;
10762
+ background: var(--tempest-accent, #2563eb);
10763
+ }
10764
+
10765
+ .tempest-admin-card__help {
10766
+ font-size: 0.8rem;
10767
+ color: var(--tempest-fg-soft);
10768
+ }
10769
+
10770
+ .tempest-admin-import__result {
10771
+ margin: 1rem 0;
10772
+ }
10773
+
10774
+ .tempest-admin-import__ok {
10775
+ color: #16a34a;
10776
+ font-weight: 600;
10777
+ }
10778
+
10779
+ .tempest-admin-import__failed {
10780
+ color: #d97706;
10781
+ font-weight: 600;
10782
+ }
10783
+
10784
+ .tempest-admin-import__errors {
10785
+ width: 100%;
10786
+ border-collapse: collapse;
10787
+ font-size: 0.85rem;
10788
+ }
10789
+
10790
+ .tempest-admin-import__errors th,
10791
+ .tempest-admin-import__errors td {
10792
+ text-align: left;
10793
+ padding: 0.3rem 0.5rem;
10794
+ border-bottom: 1px solid var(--tempest-border);
10795
+ vertical-align: top;
10796
+ }
10797
+
10798
+ .tempest-admin-import__form label {
10799
+ display: block;
10800
+ margin: 1rem 0 0.5rem;
10801
+ }
10802
+
10803
+ .tempest-admin-lenses {
10804
+ display: flex;
10805
+ flex-wrap: wrap;
10806
+ gap: 0.4rem;
10807
+ margin: 0.5rem 0 1rem;
10808
+ border-bottom: 1px solid var(--tempest-border);
10809
+ padding-bottom: 0.5rem;
10810
+ }
10811
+
10812
+ .tempest-admin-lens {
10813
+ padding: 0.3rem 0.7rem;
10814
+ border-radius: 999px;
10815
+ border: 1px solid var(--tempest-border);
10816
+ color: var(--tempest-fg-soft);
10817
+ text-decoration: none;
10818
+ font-size: 0.85rem;
10819
+ }
10820
+
10821
+ .tempest-admin-lens:hover {
10822
+ color: inherit;
10823
+ }
10824
+
10825
+ .tempest-admin-lens--active {
10826
+ background: var(--tempest-accent, #2563eb);
10827
+ border-color: var(--tempest-accent, #2563eb);
10828
+ color: #fff;
10829
+ }
10830
+
10831
+ .tempest-admin-footer {
10832
+ position: relative;
10833
+ z-index: 20;
10834
+ text-align: center;
10835
+ padding: 2rem 0;
10836
+ color: var(--tempest-fg-soft);
10837
+ }
10838
+
10839
+ /* List toolbar: search/filters on the left, actions (export) on the right. */
10840
+ .tempest-admin-list__toolbar {
10841
+ display: flex;
10842
+ flex-wrap: wrap;
10843
+ gap: 0.75rem 1rem;
10844
+ align-items: flex-end;
10845
+ justify-content: space-between;
10846
+ margin-bottom: 1rem;
10847
+ }
10848
+
10849
+ .tempest-admin-list__actions {
10850
+ display: flex;
10851
+ gap: 0.5rem;
10852
+ align-items: center;
10853
+ }
10854
+
10855
+ .tempest-admin-list__actions a {
10856
+ display: inline-block;
10857
+ padding: 0.45rem 0.8rem;
10858
+ border: 1px solid var(--tempest-accent);
10859
+ border-radius: var(--tempest-radius);
10860
+ background: #fff;
10861
+ white-space: nowrap;
10862
+ }
10863
+
10864
+ .tempest-admin-list__actions a:hover {
10865
+ background: #eff6ff;
10866
+ text-decoration: none;
10867
+ }
10868
+
10869
+ /* Dashboard: system-metric stat cards + model cards. */
10870
+ .tempest-admin-stats {
10871
+ display: grid;
10872
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
10873
+ gap: 1rem;
10874
+ margin: 1.5rem 0;
10875
+ }
10876
+
10877
+ .tempest-admin-stat {
10878
+ display: flex;
10879
+ flex-direction: column;
10880
+ gap: 0.15rem;
10881
+ background: #fff;
10882
+ border-radius: var(--tempest-radius);
10883
+ padding: 1rem 1.25rem;
10884
+ box-shadow: var(--tempest-shadow);
10885
+ }
10886
+
10887
+ .tempest-admin-stat__label {
10888
+ font-size: 0.8rem;
10889
+ text-transform: uppercase;
10890
+ letter-spacing: 0.04em;
10891
+ color: var(--tempest-fg-soft);
10892
+ }
10893
+
10894
+ .tempest-admin-stat__value {
10895
+ font-size: 1.6rem;
10896
+ font-weight: 700;
10897
+ }
10898
+
10899
+ .tempest-admin-stat__sub {
10900
+ font-size: 0.8rem;
10901
+ color: var(--tempest-fg-soft);
10902
+ }
10903
+
10904
+ .tempest-admin-models {
10905
+ display: grid;
10906
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
10907
+ gap: 1rem;
10908
+ margin-top: 1rem;
10909
+ }
10910
+
10911
+ .tempest-admin-model-card {
10912
+ background: #fff;
10913
+ border-radius: var(--tempest-radius);
10914
+ padding: 1rem 1.25rem;
10915
+ box-shadow: var(--tempest-shadow);
10916
+ display: flex;
10917
+ flex-direction: column;
10918
+ gap: 0.75rem;
10919
+ }
10920
+
10921
+ .tempest-admin-model-card__head {
10922
+ display: flex;
10923
+ align-items: baseline;
10924
+ justify-content: space-between;
10925
+ gap: 0.5rem;
10926
+ }
10927
+
10928
+ .tempest-admin-model-card__head h2 {
10929
+ margin: 0;
10930
+ font-size: 1.05rem;
10931
+ }
10932
+
10933
+ .tempest-admin-model-card__count {
10934
+ font-weight: 700;
10935
+ color: var(--tempest-accent);
10936
+ }
10937
+
10938
+ .tempest-admin-model-card__actions {
10939
+ display: flex;
10940
+ gap: 1rem;
10941
+ }
10942
+
10943
+ /* Bulk-action bar above the list table. */
10944
+ .tempest-admin-bulk {
10945
+ margin: 0;
10946
+ }
10947
+
10948
+ .tempest-admin-bulk__bar {
10949
+ display: flex;
10950
+ gap: 0.5rem;
10951
+ align-items: center;
10952
+ margin-bottom: 0.75rem;
10953
+ }
10954
+
10955
+ .tempest-admin-list__check {
10956
+ width: 1%;
10957
+ white-space: nowrap;
10958
+ text-align: center;
10959
+ }
10960
+
10961
+ .tempest-admin-list__check input {
10962
+ width: auto;
10963
+ }
10964
+
10965
+ /* Horizontal-scroll wrapper so wide tables never break the layout. */
10966
+ .tempest-admin-table-wrap {
10967
+ width: 100%;
10968
+ overflow-x: auto;
10969
+ -webkit-overflow-scrolling: touch;
10970
+ border-radius: var(--tempest-radius);
10971
+ box-shadow: var(--tempest-shadow);
10972
+ }
10973
+
10974
+ .tempest-admin-table-wrap .tempest-admin-list__table,
10975
+ .tempest-admin-table-wrap .tempest-admin-dashboard__table {
10976
+ box-shadow: none;
10977
+ }
10978
+
10979
+ /* Sortable column headers. */
10980
+ .tempest-admin-list__table th a.tempest-sort {
10981
+ color: inherit;
10982
+ display: inline-flex;
10983
+ align-items: center;
10984
+ gap: 0.3rem;
10985
+ white-space: nowrap;
10986
+ }
10987
+
10988
+ .tempest-admin-list__table th a.tempest-sort:hover {
10989
+ color: var(--tempest-accent);
10990
+ text-decoration: none;
10991
+ }
10992
+
10993
+ .tempest-sort__arrow {
10994
+ font-size: 0.75em;
10995
+ color: var(--tempest-fg-soft);
10996
+ }
10997
+
10998
+ .tempest-sort--active .tempest-sort__arrow {
10999
+ color: var(--tempest-accent);
11000
+ }
11001
+
11002
+ /* Detail header actions (back / edit / delete). */
11003
+ .tempest-admin-detail__header {
11004
+ display: flex;
11005
+ flex-wrap: wrap;
11006
+ gap: 0.5rem 1rem;
11007
+ align-items: center;
11008
+ justify-content: space-between;
11009
+ margin-bottom: 1rem;
11010
+ }
11011
+
11012
+ .tempest-admin-detail__actions {
11013
+ display: flex;
11014
+ flex-wrap: wrap;
11015
+ gap: 0.5rem;
11016
+ align-items: center;
11017
+ }
11018
+
11019
+ .tempest-admin-detail__delete {
11020
+ margin: 0;
11021
+ }
11022
+
11023
+ .tempest-admin-btn {
11024
+ display: inline-block;
11025
+ padding: 0.45rem 0.8rem;
11026
+ border: 1px solid var(--tempest-accent);
11027
+ border-radius: var(--tempest-radius);
11028
+ background: #fff;
11029
+ }
11030
+
11031
+ .tempest-admin-btn:hover {
11032
+ background: #eff6ff;
11033
+ text-decoration: none;
11034
+ }
11035
+
11036
+ .tempest-admin-btn--danger {
11037
+ background: var(--tempest-danger);
11038
+ }
11039
+
11040
+ .tempest-admin-btn--danger:hover {
11041
+ background: #991b1b;
11042
+ }
11043
+
11044
+ /* Scoped under __actions so it beats \`.tempest-admin-list__actions a\`
11045
+ (otherwise the white action-link background won + white text = invisible). */
11046
+ .tempest-admin-list__actions a.tempest-admin-list__new,
11047
+ a.tempest-admin-list__new {
11048
+ background: var(--tempest-accent);
11049
+ color: #fff;
11050
+ border-color: var(--tempest-accent);
11051
+ }
11052
+
11053
+ .tempest-admin-list__actions a.tempest-admin-list__new:hover,
11054
+ a.tempest-admin-list__new:hover {
11055
+ background: var(--tempest-accent-hover);
11056
+ color: #fff;
11057
+ }
11058
+
11059
+ /* Create / edit form. */
11060
+ .tempest-admin-form__form {
11061
+ display: grid;
11062
+ gap: 1rem;
11063
+ max-width: 640px;
11064
+ background: #fff;
11065
+ padding: 1.5rem;
11066
+ border-radius: var(--tempest-radius);
11067
+ box-shadow: var(--tempest-shadow);
11068
+ }
11069
+
11070
+ .tempest-admin-form__field {
11071
+ display: flex;
11072
+ flex-direction: column;
11073
+ gap: 0.3rem;
11074
+ }
11075
+
11076
+ .tempest-admin-form__field > label {
11077
+ display: flex;
11078
+ flex-direction: column;
11079
+ gap: 0.25rem;
11080
+ }
11081
+
11082
+ .tempest-admin-form__field > label > span {
11083
+ font-weight: 600;
11084
+ color: var(--tempest-fg-soft);
11085
+ }
11086
+
11087
+ .tempest-admin-form__field input,
11088
+ .tempest-admin-form__field select,
11089
+ .tempest-admin-form__field textarea {
11090
+ width: 100%;
11091
+ }
11092
+
11093
+ .tempest-admin-form__json {
11094
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
11095
+ font-size: 0.85rem;
11096
+ white-space: pre;
11097
+ overflow-wrap: normal;
11098
+ overflow-x: auto;
11099
+ }
11100
+
11101
+ .tempest-admin-form__check {
11102
+ flex-direction: row !important;
11103
+ align-items: center;
11104
+ gap: 0.5rem;
11105
+ }
11106
+
11107
+ .tempest-admin-form__check input {
11108
+ width: auto;
11109
+ }
11110
+
11111
+ .tempest-admin-form__field--error input,
11112
+ .tempest-admin-form__field--error select,
11113
+ .tempest-admin-form__field--error textarea {
11114
+ border-color: var(--tempest-danger);
11115
+ }
11116
+
11117
+ .tempest-admin-form__field-error {
11118
+ color: var(--tempest-danger);
11119
+ }
11120
+
11121
+ .tempest-admin-form__error {
11122
+ background: #fef2f2;
11123
+ color: var(--tempest-danger);
11124
+ padding: 0.75rem 1rem;
11125
+ border-radius: var(--tempest-radius);
11126
+ margin-bottom: 1rem;
11127
+ }
11128
+
11129
+ .tempest-admin-form__actions {
11130
+ display: flex;
11131
+ gap: 1rem;
11132
+ align-items: center;
11133
+ }
11134
+
11135
+ /* ---- Responsive ---- */
11136
+
11137
+ /* Tablet and below. */
11138
+ @media (max-width: 1023px) {
11139
+ .tempest-admin-main {
11140
+ margin: 1.25rem auto;
11141
+ padding: 0 1rem;
11142
+ }
11143
+ }
11144
+
11145
+ /* Mobile (<= 430px and small phones). */
11146
+ @media (max-width: 600px) {
11147
+ .tempest-admin-header {
11148
+ flex-direction: column;
11149
+ align-items: flex-start;
11150
+ gap: 0.5rem;
11151
+ padding: 0.75rem 1rem;
11152
+ }
11153
+
11154
+ .tempest-admin-header__nav {
11155
+ width: 100%;
11156
+ flex-wrap: wrap;
11157
+ gap: 0.5rem 0.75rem;
11158
+ }
11159
+
11160
+ .tempest-admin-main {
11161
+ margin: 1rem auto;
11162
+ padding: 0 0.75rem;
11163
+ }
11164
+
11165
+ .tempest-admin-list__header {
11166
+ flex-direction: column;
11167
+ gap: 0.25rem;
11168
+ align-items: flex-start;
11169
+ }
11170
+
11171
+ .tempest-admin-list__toolbar {
11172
+ flex-direction: column;
11173
+ align-items: stretch;
11174
+ }
11175
+
11176
+ .tempest-admin-list__filters {
11177
+ flex-direction: column;
11178
+ align-items: stretch;
11179
+ }
11180
+
11181
+ .tempest-admin-list__filters input,
11182
+ .tempest-admin-list__filters select,
11183
+ .tempest-admin-list__filters button {
11184
+ width: 100%;
11185
+ }
11186
+
11187
+ .tempest-admin-list__actions {
11188
+ justify-content: stretch;
11189
+ }
11190
+
11191
+ .tempest-admin-list__actions a {
11192
+ flex: 1;
11193
+ text-align: center;
11194
+ }
11195
+
11196
+ /* Stack the detail grid into single-column rows. */
11197
+ .tempest-admin-detail__fields {
11198
+ grid-template-columns: 1fr;
11199
+ gap: 0.15rem 0;
11200
+ padding: 1rem;
11201
+ }
11202
+
11203
+ /* The logs table becomes stacked cards. Horizontal scroll is fine for a
11204
+ list view you skim, but the logs table's fourth column carries the
11205
+ message, the request context and the traceback \u2014 everything you came to
11206
+ read \u2014 so at this width it sat off-screen behind a sideways drag, and an
11207
+ opened traceback showed up only as a tall blank row. Labels come from
11208
+ each cell's data-label, so the header can be dropped without losing
11209
+ which value is which. Scoped to this table: the other list views keep
11210
+ the scroll treatment. */
11211
+ .tempest-admin-logs .tempest-admin-table-wrap {
11212
+ overflow-x: visible;
11213
+ }
11214
+
11215
+ .tempest-admin-logs__table thead {
11216
+ display: none;
11217
+ }
11218
+
11219
+ .tempest-admin-logs__table,
11220
+ .tempest-admin-logs__table tbody,
11221
+ .tempest-admin-logs__table tr,
11222
+ .tempest-admin-logs__table td {
11223
+ display: block;
11224
+ width: 100%;
11225
+ }
11226
+
11227
+ .tempest-admin-logs__table tr {
11228
+ padding: 0.85rem 0.9rem;
11229
+ border-bottom: 1px solid #e2e8f0;
11230
+ }
11231
+
11232
+ .tempest-admin-logs__table tr:last-child {
11233
+ border-bottom: none;
11234
+ }
11235
+
11236
+ .tempest-admin-logs__table td {
11237
+ padding: 0.1rem 0;
11238
+ border: none;
11239
+ }
11240
+
11241
+ .tempest-admin-logs__table td[data-label]::before {
11242
+ content: attr(data-label);
11243
+ display: block;
11244
+ color: var(--tempest-fg-soft);
11245
+ text-transform: uppercase;
11246
+ letter-spacing: 0.04em;
11247
+ font-size: 0.64rem;
11248
+ font-weight: 600;
11249
+ }
11250
+
11251
+ /* The message is the card's body, not another labelled field. */
11252
+ .tempest-admin-logs__table td.tempest-admin-logs__msg {
11253
+ margin-top: 0.5rem;
11254
+ }
11255
+
11256
+ .tempest-admin-logs__table td.tempest-admin-logs__msg::before {
11257
+ display: none;
11258
+ }
11259
+
11260
+ .tempest-admin-logs__logger {
11261
+ white-space: normal;
11262
+ overflow-wrap: anywhere;
11263
+ }
11264
+
11265
+ .tempest-admin-detail__fields dt {
11266
+ margin-top: 0.75rem;
11267
+ }
11268
+
11269
+ .tempest-admin-detail__fields dd {
11270
+ padding-bottom: 0.5rem;
11271
+ border-bottom: 1px solid #e2e8f0;
11272
+ }
11273
+
11274
+ .tempest-admin-login {
11275
+ margin: 1.5rem auto;
11276
+ padding: 1.5rem;
11277
+ }
11278
+
11279
+ .tempest-admin-form__form {
11280
+ padding: 1rem;
11281
+ }
11282
+
11283
+ .tempest-admin-form__actions {
11284
+ flex-direction: column-reverse;
11285
+ align-items: stretch;
11286
+ }
11287
+
11288
+ .tempest-admin-form__actions button,
11289
+ .tempest-admin-form__actions .tempest-admin-form__cancel {
11290
+ width: 100%;
11291
+ text-align: center;
11292
+ }
11293
+
11294
+ .tempest-admin-bulk__bar {
11295
+ flex-direction: column;
11296
+ align-items: stretch;
11297
+ }
11298
+
11299
+ .tempest-admin-bulk__bar select,
11300
+ .tempest-admin-bulk__bar button {
11301
+ width: 100%;
11302
+ }
11303
+ }
11304
+
11305
+ /* ---- Application logs page ---- */
11306
+ .tempest-log-badge {
11307
+ display: inline-block;
11308
+ padding: 0.1rem 0.5rem;
11309
+ border-radius: 999px;
11310
+ font-size: 0.72rem;
11311
+ font-weight: 600;
11312
+ text-transform: uppercase;
11313
+ letter-spacing: 0.03em;
11314
+ background: #e2e8f0;
11315
+ color: #334155;
11316
+ }
11317
+
11318
+ .tempest-log-badge--debug {
11319
+ background: #e2e8f0;
11320
+ color: #475569;
11321
+ }
11322
+
11323
+ .tempest-log-badge--info {
11324
+ background: #dbeafe;
11325
+ color: #1e40af;
11326
+ }
11327
+
11328
+ .tempest-log-badge--warning {
11329
+ background: #fef3c7;
11330
+ color: #92400e;
11331
+ }
11332
+
11333
+ .tempest-log-badge--error {
11334
+ background: #fee2e2;
11335
+ color: #991b1b;
11336
+ }
11337
+
11338
+ .tempest-log-badge--critical {
11339
+ background: #7f1d1d;
11340
+ color: #fff;
11341
+ }
11342
+
11343
+ .tempest-admin-logs__ts {
11344
+ white-space: nowrap;
11345
+ font-variant-numeric: tabular-nums;
11346
+ color: var(--tempest-fg-soft);
11347
+ }
11348
+
11349
+ .tempest-admin-logs__logger {
11350
+ color: var(--tempest-fg-soft);
11351
+ white-space: nowrap;
11352
+ }
11353
+
11354
+ .tempest-admin-logs__msg {
11355
+ word-break: break-word;
11356
+ }
11357
+
11358
+ .tempest-admin-logs__empty {
11359
+ color: var(--tempest-fg-soft);
11360
+ background: #fff;
11361
+ padding: 1.5rem;
11362
+ border-radius: var(--tempest-radius);
11363
+ box-shadow: var(--tempest-shadow);
11364
+ }
11365
+
11366
+ .tempest-admin-logs__actions {
11367
+ display: flex;
11368
+ gap: 0.5rem;
11369
+ flex-wrap: wrap;
11370
+ }
11371
+
11372
+ .tempest-admin-logs__export {
11373
+ display: inline-block;
11374
+ padding: 0.35rem 0.75rem;
11375
+ border-radius: var(--tempest-radius);
11376
+ border: 1px solid #cbd5e1;
11377
+ background: #fff;
11378
+ color: #334155;
11379
+ font-size: 0.82rem;
11380
+ font-weight: 600;
11381
+ text-decoration: none;
11382
+ }
11383
+
11384
+ .tempest-admin-logs__export:hover {
11385
+ background: #f1f5f9;
11386
+ }
11387
+
11388
+ .tempest-admin-logs__meta {
11389
+ list-style: none;
11390
+ margin: 0.4rem 0 0;
11391
+ padding: 0;
11392
+ display: flex;
11393
+ flex-wrap: wrap;
11394
+ gap: 0.3rem 0.75rem;
11395
+ font-size: 0.75rem;
11396
+ }
11397
+
11398
+ /* The gap is layout only \u2014 it does not survive a copy, and an operator copying a
11399
+ row to paste into an issue would get "status_code404". The template keeps a
11400
+ real space between the label and the value for that; this widens the visual
11401
+ separation on top of it, since an uppercase micro-label sitting against a
11402
+ monospace value reads as one token. */
11403
+ .tempest-admin-logs__meta li {
11404
+ display: inline-flex;
11405
+ align-items: baseline;
11406
+ gap: 0.4rem;
11407
+ }
11408
+
11409
+ .tempest-admin-logs__meta span {
11410
+ color: var(--tempest-fg-soft);
11411
+ text-transform: uppercase;
11412
+ letter-spacing: 0.03em;
11413
+ font-size: 0.68rem;
11414
+ }
11415
+
11416
+ .tempest-admin-logs__meta code {
11417
+ word-break: break-all;
11418
+ }
11419
+
11420
+ /* Collapsed by default so a page full of 500s stays scannable; details/summary
11421
+ keeps that working with no JavaScript, which the admin does not ship. */
11422
+ .tempest-admin-logs__trace {
11423
+ margin-top: 0.5rem;
11424
+ }
11425
+
11426
+ /* The summary carries the record's own message, so the whole item is the click
11427
+ target instead of a separate link. It must therefore read as body text, not
11428
+ as a control \u2014 the affordance is the marker plus the hint chip. */
11429
+ .tempest-admin-logs__trace summary {
11430
+ cursor: pointer;
11431
+ list-style: none;
11432
+ display: block;
11433
+ }
11434
+
11435
+ .tempest-admin-logs__trace summary::-webkit-details-marker {
11436
+ display: none;
11437
+ }
11438
+
11439
+ .tempest-admin-logs__msg-text::before {
11440
+ content: "\u25B8";
11441
+ display: inline-block;
11442
+ width: 0.9rem;
11443
+ color: #991b1b;
11444
+ font-size: 0.7rem;
11445
+ }
11446
+
11447
+ .tempest-admin-logs__trace[open] .tempest-admin-logs__msg-text::before {
11448
+ content: "\u25BE";
11449
+ }
11450
+
11451
+ .tempest-admin-logs__trace-hint {
11452
+ display: inline-block;
11453
+ margin-top: 0.3rem;
11454
+ font-size: 0.68rem;
11455
+ font-weight: 600;
11456
+ text-transform: uppercase;
11457
+ letter-spacing: 0.04em;
11458
+ color: #991b1b;
11459
+ }
11460
+
11461
+ .tempest-admin-logs__trace[open] .tempest-admin-logs__trace-hint {
11462
+ opacity: 0.55;
11463
+ }
11464
+
11465
+ /* Lines wrap instead of extending. A <pre> is sized by its longest line and it
11466
+ sits in a table cell, which sizes to content, so \`overflow-x\` on the <pre>
11467
+ cannot shrink it: the table grew past its scroll container (measured 1364px
11468
+ against a 1012px wrap) and the trace could only be read by dragging the table
11469
+ sideways. Wrapping keeps the table at its container width. It costs the
11470
+ alignment of the caret markers on screen; the markdown export carries the
11471
+ exact unwrapped text for real analysis. */
11472
+ .tempest-admin-logs__trace pre {
11473
+ margin: 0.5rem 0 0;
11474
+ padding: 0.75rem;
11475
+ max-height: 24rem;
11476
+ overflow-y: auto;
11477
+ background: #0f172a;
11478
+ color: #e2e8f0;
11479
+ border-radius: var(--tempest-radius);
11480
+ font-size: 0.74rem;
11481
+ line-height: 1.45;
11482
+ white-space: pre-wrap;
11483
+ overflow-wrap: anywhere;
11484
+ -webkit-user-select: all;
11485
+ user-select: all;
11486
+ }
11487
+
11488
+ .tempest-admin-logs__note {
11489
+ color: var(--tempest-fg-soft);
11490
+ font-size: 0.8rem;
11491
+ margin-top: 0.75rem;
11492
+ }
11493
+
11494
+ /* ---- Sidebar off-canvas on tablet/mobile, burger reveals it ---- */
11495
+ @media (max-width: 768px) {
11496
+ .tempest-admin-burger {
11497
+ display: flex;
11498
+ }
11499
+
11500
+ .tempest-admin-sidebar {
11501
+ position: fixed;
11502
+ top: 0;
11503
+ left: 0;
11504
+ bottom: 0;
11505
+ z-index: 50;
11506
+ width: 240px;
11507
+ flex-basis: 240px;
11508
+ transform: translateX(-100%);
11509
+ transition: transform 0.2s ease;
11510
+ overflow-y: auto;
11511
+ box-shadow: 0 0 24px rgba(15, 23, 42, 0.35);
11512
+ }
11513
+
11514
+ .tempest-admin-navtoggle:checked ~ .tempest-admin-layout .tempest-admin-sidebar {
11515
+ transform: translateX(0);
11516
+ }
11517
+
11518
+ .tempest-admin-navtoggle:checked ~ .tempest-admin-layout .tempest-admin-scrim {
11519
+ display: block;
11520
+ position: fixed;
11521
+ inset: 0;
11522
+ z-index: 40;
11523
+ background: rgba(15, 23, 42, 0.45);
11524
+ }
11525
+ }
11526
+
11527
+ /* ---- Desktop: sidebar overlays the header + footer ---- */
11528
+ @media (min-width: 769px) {
11529
+ .tempest-admin-sidebar {
11530
+ position: fixed;
11531
+ top: 0;
11532
+ left: 0;
11533
+ bottom: 0;
11534
+ z-index: 100; /* above header/footer (z-index: 20) */
11535
+ overflow-y: auto;
11536
+ /* Clear the header bar so the first nav link sits below it. */
11537
+ padding-top: 3.75rem;
11538
+ }
11539
+
11540
+ /* The fixed sidebar leaves the flex flow, so reserve its gutter on
11541
+ the layout row to keep the main content from sliding underneath. */
11542
+ .tempest-admin-layout {
11543
+ padding-left: 220px;
11544
+ }
11545
+ }
11546
+
11547
+ /* Flash banner shown after a custom bulk action runs. */
11548
+ .tempest-admin-flash {
11549
+ margin: 0 0 1rem;
11550
+ padding: 0.7rem 1rem;
11551
+ border-radius: var(--tempest-radius);
11552
+ border-left: 4px solid var(--tempest-accent);
11553
+ background: var(--tempest-bg);
11554
+ color: var(--tempest-fg);
11555
+ }
11556
+
11557
+ .tempest-admin-flash--error {
11558
+ border-left-color: var(--tempest-danger);
11559
+ }
11560
+
11561
+ .tempest-admin-flash--warning {
11562
+ border-left-color: #d97706;
11563
+ }
11564
+
11565
+ /* Task panel \u2014 declared schedule and persisted runs. */
11566
+ .tempest-admin-tasks__scope {
11567
+ margin: 0 0 1.25rem;
11568
+ color: var(--tempest-fg-soft);
11569
+ font-size: 0.9rem;
11570
+ }
11571
+
11572
+ .tempest-admin-tasks__heading {
11573
+ margin: 1.75rem 0 0.75rem;
11574
+ font-size: 1.05rem;
11575
+ }
11576
+
11577
+ .tempest-admin-tasks__empty {
11578
+ padding: 1rem;
11579
+ border: 1px dashed var(--tempest-border);
11580
+ border-radius: var(--tempest-radius);
11581
+ color: var(--tempest-fg-soft);
11582
+ }
11583
+
11584
+ .tempest-admin-tasks__trigger + .tempest-admin-tasks__trigger {
11585
+ margin-top: 0.35rem;
11586
+ }
11587
+
11588
+ .tempest-admin-tasks__offset {
11589
+ color: var(--tempest-fg-soft);
11590
+ font-size: 0.85rem;
11591
+ white-space: nowrap;
11592
+ }
11593
+
11594
+ .tempest-admin-tasks__status {
11595
+ display: inline-block;
11596
+ padding: 0.1rem 0.5rem;
11597
+ border-radius: 999px;
11598
+ font-size: 0.8rem;
11599
+ border: 1px solid var(--tempest-border);
11600
+ color: var(--tempest-fg-soft);
11601
+ }
11602
+
11603
+ .tempest-admin-tasks__status--running {
11604
+ border-color: var(--tempest-accent);
11605
+ color: var(--tempest-accent);
11606
+ }
11607
+
11608
+ .tempest-admin-tasks__status--done {
11609
+ border-color: #15803d;
11610
+ color: #15803d;
11611
+ }
11612
+
11613
+ .tempest-admin-tasks__status--failed {
11614
+ border-color: var(--tempest-danger);
11615
+ color: var(--tempest-danger);
11616
+ }
11617
+
11618
+ /* Cancelled is terminal but not a failure, so it stays neutral: an
11619
+ operator scanning for red should find only what went wrong. */
11620
+ .tempest-admin-tasks__status--cancelled {
11621
+ border-color: var(--tempest-border);
11622
+ color: var(--tempest-fg-soft);
11623
+ }
11624
+
11625
+ /* The track uses the border token, not a row background: the list stripes
11626
+ rows with --tempest-bg-row-alt, so a track painted in it vanished on
11627
+ every other row \u2014 an empty progress cell reads as "no data", not as 0%. */
11628
+ .tempest-admin-tasks__bar {
11629
+ display: inline-block;
11630
+ width: 90px;
11631
+ height: 8px;
11632
+ border-radius: 999px;
11633
+ background: var(--tempest-border);
11634
+ overflow: hidden;
11635
+ vertical-align: middle;
11636
+ }
11637
+
11638
+ .tempest-admin-tasks__bar--wide {
11639
+ display: block;
11640
+ width: 100%;
11641
+ height: 12px;
11642
+ margin: 0 0 1.25rem;
11643
+ }
11644
+
11645
+ .tempest-admin-tasks__bar-fill {
11646
+ display: block;
11647
+ height: 100%;
11648
+ background: var(--tempest-accent);
11649
+ }
11650
+
11651
+ .tempest-admin-tasks__facts {
11652
+ display: grid;
11653
+ grid-template-columns: max-content 1fr;
11654
+ gap: 0.4rem 1.25rem;
11655
+ margin: 0 0 1.5rem;
11656
+ }
11657
+
11658
+ .tempest-admin-tasks__facts dt {
11659
+ color: var(--tempest-fg-soft);
11660
+ font-size: 0.85rem;
11661
+ }
11662
+
11663
+ .tempest-admin-tasks__facts dd {
11664
+ margin: 0;
11665
+ }
11666
+
11667
+ .tempest-admin-tasks__error pre {
11668
+ padding: 0.85rem;
11669
+ border-radius: var(--tempest-radius);
11670
+ border-left: 4px solid var(--tempest-danger);
11671
+ background: var(--tempest-bg-row-alt);
11672
+ overflow-x: auto;
11673
+ white-space: pre-wrap;
11674
+ }
11675
+
11676
+ .tempest-admin-tasks__cancel {
11677
+ display: flex;
11678
+ align-items: center;
11679
+ gap: 0.75rem;
11680
+ flex-wrap: wrap;
11681
+ margin: 0 0 1.5rem;
11682
+ }
11683
+
11684
+ .tempest-admin-tasks__hint {
11685
+ color: var(--tempest-fg-soft);
11686
+ font-size: 0.85rem;
11687
+ }
11688
+
11689
+ @media (max-width: 640px) {
11690
+ .tempest-admin-tasks__facts {
11691
+ grid-template-columns: 1fr;
11692
+ gap: 0.15rem;
11693
+ }
11694
+
11695
+ .tempest-admin-tasks__facts dd {
11696
+ margin: 0 0 0.6rem;
11697
+ }
11698
+ }
11699
+ `;
11700
+
11701
+ // src/admin/theme.ts
11702
+ var FORBIDDEN_CHARS = ["<", ">", "{", "}", '"'];
11703
+ function assertSafe(field, value) {
11704
+ if (value === void 0) return;
11705
+ const bad = FORBIDDEN_CHARS.filter((char) => value.includes(char));
11706
+ if (bad.length > 0) {
11707
+ throw new Error(
11708
+ `AdminTheme.${field} contains forbidden character(s) ${bad.join(" ")}; these would break the injected <style>/HTML. Got: ${value}`
11709
+ );
11710
+ }
11711
+ }
11712
+ function resolveAdminTheme(theme = {}) {
11713
+ for (const [field, value] of Object.entries(theme)) {
11714
+ if (typeof value === "string") assertSafe(field, value);
11715
+ }
11716
+ const headerBg = theme.headerBg ?? "#0f172a";
11717
+ return {
11718
+ accent: theme.accent ?? "#2563eb",
11719
+ accentHover: theme.accentHover ?? "#1d4ed8",
11720
+ danger: theme.danger ?? "#b91c1c",
11721
+ headerBg,
11722
+ sidebarBg: theme.sidebarBg ?? headerBg,
11723
+ pageBg: theme.pageBg ?? null,
11724
+ radius: theme.radius ?? "6px",
11725
+ fontFamily: theme.fontFamily ?? null,
11726
+ logoUrl: theme.logoUrl ?? null,
11727
+ logoAlt: theme.logoAlt ?? "Logo",
11728
+ faviconUrl: theme.faviconUrl ?? null,
11729
+ footerText: theme.footerText ?? "Powered by tempest-express-sdk",
11730
+ darkMode: theme.darkMode ?? false,
11731
+ customCssUrl: theme.customCssUrl ?? null
11732
+ };
11733
+ }
11734
+ function adminThemeCss(theme) {
11735
+ const variables = {
11736
+ "--tempest-accent": theme.accent,
11737
+ "--tempest-accent-hover": theme.accentHover,
11738
+ "--tempest-danger": theme.danger,
11739
+ "--tempest-bg": theme.headerBg,
11740
+ "--tempest-bg-soft": theme.sidebarBg,
11741
+ "--tempest-radius": theme.radius
11742
+ };
11743
+ if (theme.fontFamily !== null) variables["--tempest-font"] = theme.fontFamily;
11744
+ if (theme.pageBg !== null) variables["--tempest-page-bg"] = theme.pageBg;
11745
+ const rootLines = Object.entries(variables).map(([name, value]) => ` ${name}: ${value};`).join("\n");
11746
+ const blocks = [`:root {
11747
+ ${rootLines}
11748
+ }`];
11749
+ if (theme.darkMode && theme.pageBg === null) {
11750
+ blocks.push(
11751
+ [
11752
+ ":root {",
11753
+ " --tempest-page-bg: #0b1120;",
11754
+ " --tempest-bg-row: #1e293b;",
11755
+ " --tempest-bg-row-alt: #172033;",
11756
+ " --tempest-fg: #e2e8f0;",
11757
+ " --tempest-fg-soft: #94a3b8;",
11758
+ "}",
11759
+ "body { color: var(--tempest-fg); }",
11760
+ "input, select, textarea {",
11761
+ " background: #1e293b;",
11762
+ " color: var(--tempest-fg);",
11763
+ " border-color: #334155;",
11764
+ "}"
11765
+ ].join("\n")
11766
+ );
11767
+ }
11768
+ if (theme.fontFamily !== null) {
11769
+ blocks.push("body { font-family: var(--tempest-font); }");
11770
+ }
11771
+ return blocks.join("\n");
11772
+ }
11773
+
11774
+ // src/admin/templates.ts
11775
+ function escapeHtml(value) {
11776
+ return String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
11777
+ }
11778
+ function renderLayout(context, title, body) {
11779
+ const { site, theme, prefix, session, currentPath, navModels, messages } = context;
11780
+ const authed = session !== null;
11781
+ const indexUrl = `${prefix}/`;
11782
+ const navLink = (url, label, active) => `<a href="${escapeHtml(url)}" class="tempest-admin-sidebar__link${active ? " tempest-admin-sidebar__link--active" : ""}">${escapeHtml(label)}</a>`;
11783
+ const sidebar = authed ? `<label for="tempest-nav-toggle" class="tempest-admin-scrim" aria-hidden="true"></label>
11784
+ <aside class="tempest-admin-sidebar">
11785
+ <nav class="tempest-admin-sidebar__nav" aria-label="Admin navigation">
11786
+ ${navLink(indexUrl, "Dashboard", currentPath === indexUrl)}
11787
+ ${navModels.length > 0 ? `<span class="tempest-admin-sidebar__heading">Models</span>${navModels.map(
11788
+ (entry) => navLink(entry.url, entry.label, currentPath.startsWith(entry.url))
11789
+ ).join("")}` : ""}
11790
+ </nav>
11791
+ </aside>` : "";
11792
+ const brand = theme.logoUrl !== null ? `<img src="${escapeHtml(theme.logoUrl)}" alt="${escapeHtml(theme.logoAlt)}" class="tempest-admin-header__logo">` : escapeHtml(site.brandText());
11793
+ const headerNav = authed ? `<nav class="tempest-admin-header__nav">
11794
+ <span class="tempest-admin-header__user">${escapeHtml(session.displayName)}</span>
11795
+ ${site.siteUrl !== null ? `<a href="${escapeHtml(site.siteUrl)}">View site</a>` : ""}
11796
+ <form method="post" action="${escapeHtml(`${prefix}/logout`)}" class="tempest-admin-header__logout">
11797
+ <input type="hidden" name="csrf_token" value="${escapeHtml(session.csrfToken)}">
11798
+ <button type="submit">Logout</button>
11799
+ </form>
11800
+ </nav>` : "";
11801
+ const banners = messages.length > 0 ? `<ul class="tempest-admin-messages">${messages.map(
11802
+ (message) => `<li class="tempest-admin-messages__item tempest-admin-messages__item--${escapeHtml(
11803
+ message.level
11804
+ )}">${escapeHtml(message.text)}</li>`
11805
+ ).join("")}</ul>` : "";
11806
+ return `<!doctype html>
11807
+ <html lang="en">
11808
+ <head>
11809
+ <meta charset="utf-8">
11810
+ <meta name="viewport" content="width=device-width, initial-scale=1">
11811
+ <title>${escapeHtml(title)}</title>
11812
+ ${theme.faviconUrl !== null ? `<link rel="icon" href="${escapeHtml(theme.faviconUrl)}">` : ""}
11813
+ <link rel="stylesheet" href="${escapeHtml(`${prefix}/static/admin.css`)}">
11814
+ <style>${adminThemeCss(theme)}</style>
11815
+ ${theme.customCssUrl !== null ? `<link rel="stylesheet" href="${escapeHtml(theme.customCssUrl)}">` : ""}
11816
+ </head>
11817
+ <body>
11818
+ ${authed ? '<input type="checkbox" id="tempest-nav-toggle" class="tempest-admin-navtoggle" hidden>' : ""}
11819
+ <header class="tempest-admin-header">
11820
+ <div class="tempest-admin-header__left">
11821
+ ${authed ? `<label for="tempest-nav-toggle" class="tempest-admin-burger" aria-label="Toggle navigation"><span></span><span></span><span></span></label>` : ""}
11822
+ <div class="tempest-admin-header__brand"><a href="${escapeHtml(indexUrl)}">${brand}</a></div>
11823
+ </div>
11824
+ ${headerNav}
11825
+ </header>
11826
+ <div class="tempest-admin-layout">
11827
+ ${sidebar}
11828
+ <main class="tempest-admin-main">
11829
+ ${banners}
11830
+ ${body}
11831
+ </main>
11832
+ </div>
11833
+ <footer class="tempest-admin-footer"><small>${escapeHtml(theme.footerText)}</small></footer>
11834
+ </body>
11835
+ </html>`;
11836
+ }
11837
+ function renderLoginPage(context, error) {
11838
+ const body = `<section class="tempest-admin-login">
11839
+ <h1>Sign in</h1>
11840
+ <p>${escapeHtml(context.site.indexSubtitle)}</p>
11841
+ ${error !== null ? `<p class="tempest-admin-login__error" role="alert">${escapeHtml(error)}</p>` : ""}
11842
+ <form method="post" action="${escapeHtml(`${context.prefix}/login`)}" class="tempest-admin-login__form">
11843
+ <label><span>Email</span><input type="email" name="identifier" autocomplete="username" required autofocus></label>
11844
+ <label><span>Password</span><input type="password" name="password" autocomplete="current-password" required></label>
11845
+ <button type="submit">Sign in</button>
11846
+ </form>
11847
+ </section>`;
11848
+ return renderLayout(context, `Sign in \xB7 ${context.site.title}`, body);
11849
+ }
11850
+ function renderMfaPage(context, error) {
11851
+ const body = `<section class="tempest-admin-login">
11852
+ <h1>Two-factor code</h1>
11853
+ <p>Enter the 6-digit code from your authenticator app.</p>
11854
+ ${error !== null ? `<p class="tempest-admin-login__error" role="alert">${escapeHtml(error)}</p>` : ""}
11855
+ <form method="post" action="${escapeHtml(`${context.prefix}/mfa`)}" class="tempest-admin-login__form">
11856
+ <label><span>Code</span><input type="text" name="code" inputmode="numeric" autocomplete="one-time-code" required autofocus></label>
11857
+ <button type="submit">Verify</button>
11858
+ </form>
11859
+ </section>`;
11860
+ return renderLayout(context, `Two-factor \xB7 ${context.site.title}`, body);
11861
+ }
11862
+ function renderDashboardPage(context, cards, metrics) {
11863
+ const metricsPanel = metrics === null ? "" : `<div class="tempest-admin-stats" aria-label="System metrics">
11864
+ <div class="tempest-admin-stat">
11865
+ <span class="tempest-admin-stat__label">CPU</span>
11866
+ <span class="tempest-admin-stat__value">${escapeHtml(metrics.cpuPercent)}%</span>
11867
+ </div>
11868
+ <div class="tempest-admin-stat">
11869
+ <span class="tempest-admin-stat__label">Memory</span>
11870
+ <span class="tempest-admin-stat__value">${escapeHtml(metrics.memoryPercent)}%</span>
11871
+ <span class="tempest-admin-stat__sub">${escapeHtml(metrics.memoryUsedGb)} / ${escapeHtml(metrics.memoryTotalGb)} GB</span>
11872
+ </div>
11873
+ </div>`;
11874
+ const models = cards.length > 0 ? `<div class="tempest-admin-models">${cards.map(
11875
+ (card) => `<article class="tempest-admin-model-card">
11876
+ <header class="tempest-admin-model-card__head">
11877
+ <h2>${escapeHtml(card.label)}</h2>
11878
+ ${card.count !== null ? `<span class="tempest-admin-model-card__count">${escapeHtml(card.count)}</span>` : ""}
11879
+ </header>
11880
+ <div class="tempest-admin-model-card__actions">
11881
+ <a href="${escapeHtml(card.url)}">Browse</a>
11882
+ ${card.newUrl !== null ? `<a href="${escapeHtml(card.newUrl)}">+ New</a>` : ""}
11883
+ </div>
11884
+ </article>`
11885
+ ).join("")}</div>` : "<p>No models registered. Register an <code>AdminModel</code> on the <code>AdminSite</code> to populate this dashboard.</p>";
11886
+ const body = `<section class="tempest-admin-dashboard">
11887
+ <h1>${escapeHtml(context.site.title)}</h1>
11888
+ <p>${escapeHtml(context.site.indexSubtitle)}</p>
11889
+ ${metricsPanel}
11890
+ ${models}
11891
+ </section>`;
11892
+ return renderLayout(context, context.site.title, body);
11893
+ }
11894
+ function renderFilter(filter) {
11895
+ const name = `filter_${filter.field}`;
11896
+ if (filter.kind === "select") {
11897
+ const options = filter.options.map(
11898
+ (option) => `<option value="${escapeHtml(option.value)}"${option.selected ? " selected" : ""}>${escapeHtml(option.label)}</option>`
11899
+ ).join("");
11900
+ return `<label><span>${escapeHtml(filter.label)}</span><select name="${escapeHtml(name)}"><option value="">\u2014 any \u2014</option>${options}</select></label>`;
11901
+ }
11902
+ if (filter.kind === "daterange") {
11903
+ return `<label><span>${escapeHtml(filter.label)}</span><span class="tempest-admin-list__daterange">
11904
+ <input type="date" name="${escapeHtml(`${name}_from`)}" value="${escapeHtml(filter.valueFrom)}" aria-label="${escapeHtml(filter.label)} from">
11905
+ <input type="date" name="${escapeHtml(`${name}_to`)}" value="${escapeHtml(filter.valueTo)}" aria-label="${escapeHtml(filter.label)} to">
11906
+ </span></label>`;
11907
+ }
11908
+ return `<label><span>${escapeHtml(filter.label)}</span><input type="text" name="${escapeHtml(name)}" value="${escapeHtml(filter.value)}"></label>`;
11909
+ }
11910
+ function renderListPage(context, view) {
11911
+ const bulk = view.bulkActions.length > 0 && context.session !== null;
11912
+ const checkColumn = bulk ? 1 : 0;
11913
+ const headers = view.columns.map((column6) => {
11914
+ const state = view.sort[column6];
11915
+ if (state === void 0) return `<th>${escapeHtml(column6)}</th>`;
11916
+ const arrow = state.active ? state.ascending ? "\u25B2" : "\u25BC" : "\u2195";
11917
+ return `<th><a class="tempest-sort${state.active ? " tempest-sort--active" : ""}" href="${escapeHtml(state.url)}"><span>${escapeHtml(column6)}</span><span class="tempest-sort__arrow" aria-hidden="true">${arrow}</span></a></th>`;
11918
+ }).join("");
11919
+ const rows = view.rows.length > 0 ? view.rows.map((row) => {
11920
+ const check = bulk ? `<td class="tempest-admin-list__check"><input type="checkbox" name="ids" value="${escapeHtml(row.identity)}" data-row-check aria-label="Select row"></td>` : "";
11921
+ const cells = row.cells.map((cell) => `<td>${escapeHtml(cell)}</td>`).join("");
11922
+ return `<tr>${check}${cells}<td><a href="${escapeHtml(row.url)}">View</a></td></tr>`;
11923
+ }).join("") : `<tr><td colspan="${view.columns.length + 1 + checkColumn}">No records.</td></tr>`;
11924
+ const bulkBar = bulk ? `<form method="post" action="${escapeHtml(view.bulkUrl)}" class="tempest-admin-bulk" onsubmit="return confirm('Apply the selected action to the checked rows?');">
11925
+ <input type="hidden" name="csrf_token" value="${escapeHtml(context.session?.csrfToken)}">
11926
+ <div class="tempest-admin-bulk__bar">
11927
+ <select name="action" aria-label="Bulk action">
11928
+ ${view.bulkActions.map(
11929
+ (action) => `<option value="${escapeHtml(action.value)}">${escapeHtml(action.label)}${action.dangerous ? " \u26A0" : ""}</option>`
11930
+ ).join("")}
11931
+ </select>
11932
+ <button type="submit">Apply to selected</button>
11933
+ </div>` : "";
11934
+ const selectAllScript = bulk ? `<script>
11935
+ (function () {
11936
+ var master = document.querySelector('[data-select-all]');
11937
+ if (!master) return;
11938
+ master.addEventListener('change', function () {
11939
+ document.querySelectorAll('[data-row-check]').forEach(function (box) {
11940
+ box.checked = master.checked;
11941
+ });
11942
+ });
11943
+ })();
11944
+ </script>` : "";
11945
+ const hasControls = view.searchable || view.filters.length > 0;
11946
+ const body = `<section class="tempest-admin-list">
11947
+ <header class="tempest-admin-list__header">
11948
+ <h1>${escapeHtml(view.title)}</h1>
11949
+ <p>${escapeHtml(view.total)} record${view.total === 1 ? "" : "s"}.</p>
11950
+ </header>
11951
+ <div class="tempest-admin-list__toolbar">
11952
+ <form method="get" class="tempest-admin-list__filters">
11953
+ ${view.searchable ? `<input type="search" name="q" value="${escapeHtml(view.searchValue)}" placeholder="Search\u2026" aria-label="Search">` : ""}
11954
+ ${view.filters.map(renderFilter).join("")}
11955
+ ${hasControls ? '<button type="submit">Apply</button>' : ""}
11956
+ </form>
11957
+ <div class="tempest-admin-list__actions">
11958
+ ${view.newUrl !== null ? `<a class="tempest-admin-list__new" href="${escapeHtml(view.newUrl)}">+ New</a>` : ""}
11959
+ <a href="${escapeHtml(view.exportCsvUrl)}">Export CSV</a>
11960
+ <a href="${escapeHtml(view.exportJsonUrl)}">Export JSON</a>
11961
+ </div>
11962
+ </div>
11963
+ ${bulkBar}
11964
+ <div class="tempest-admin-table-wrap">
11965
+ <table class="tempest-admin-list__table">
11966
+ <thead><tr>${bulk ? '<th class="tempest-admin-list__check"><input type="checkbox" data-select-all aria-label="Select all"></th>' : ""}${headers}<th>Actions</th></tr></thead>
11967
+ <tbody>${rows}</tbody>
11968
+ </table>
11969
+ </div>
11970
+ ${bulk ? "</form>" : ""}
11971
+ ${selectAllScript}
11972
+ ${view.pages > 1 ? `<nav class="tempest-admin-list__pagination" aria-label="Pagination">
11973
+ ${view.prevUrl !== null ? `<a href="${escapeHtml(view.prevUrl)}">\u2190 Prev</a>` : ""}
11974
+ <span>Page ${escapeHtml(view.page)} of ${escapeHtml(view.pages)}</span>
11975
+ ${view.nextUrl !== null ? `<a href="${escapeHtml(view.nextUrl)}">Next \u2192</a>` : ""}
11976
+ </nav>` : ""}
11977
+ </section>`;
11978
+ return renderLayout(context, `${view.title} \xB7 ${context.site.title}`, body);
11979
+ }
11980
+ function renderDetailPage(context, view) {
11981
+ if (context.session === null) throw new Error("The detail view requires a session");
11982
+ const csrf = escapeHtml(context.session.csrfToken);
11983
+ const fields = view.fields.map(
11984
+ (field) => `<dt>${escapeHtml(field.label)}</dt><dd>${field.value === "" ? "<em>\u2014</em>" : escapeHtml(field.value)}</dd>`
11985
+ ).join("");
11986
+ const body = `<section class="tempest-admin-detail">
11987
+ <header class="tempest-admin-detail__header">
11988
+ <h1>${escapeHtml(view.title)} \xB7 ${escapeHtml(view.identity)}</h1>
11989
+ <div class="tempest-admin-detail__actions">
11990
+ <a href="${escapeHtml(view.backUrl)}">\u2190 Back to list</a>
11991
+ ${view.editUrl !== null ? `<a class="tempest-admin-btn" href="${escapeHtml(view.editUrl)}">Edit</a>` : ""}
11992
+ ${view.deleteUrl !== null ? `<form method="post" action="${escapeHtml(view.deleteUrl)}" class="tempest-admin-detail__delete" onsubmit="return confirm('Delete this record? This cannot be undone.');">
11993
+ <input type="hidden" name="csrf_token" value="${csrf}">
11994
+ <button type="submit" class="tempest-admin-btn--danger">Delete</button>
11995
+ </form>` : ""}
11996
+ </div>
11997
+ </header>
11998
+ <dl class="tempest-admin-detail__fields">${fields}</dl>
11999
+ </section>`;
12000
+ return renderLayout(context, `${view.title} \xB7 ${view.identity}`, body);
12001
+ }
12002
+ function renderFormField(field) {
12003
+ const required = field.required ? " required" : "";
12004
+ const name = escapeHtml(field.name);
12005
+ const value = escapeHtml(field.value);
12006
+ const label = escapeHtml(field.label);
12007
+ let control;
12008
+ switch (field.widget) {
12009
+ case "checkbox":
12010
+ control = `<label class="tempest-admin-form__check"><input type="checkbox" name="${name}" value="true"${field.checked ? " checked" : ""}><span>${label}</span></label>`;
12011
+ break;
12012
+ case "textarea":
12013
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><textarea name="${name}" rows="4"${required}>${value}</textarea></label>`;
12014
+ break;
12015
+ case "json":
12016
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><textarea name="${name}" rows="6" class="tempest-admin-form__json" spellcheck="false"${required}>${value}</textarea><small class="tempest-admin-form__hint">JSON \u2014 must parse (e.g. <code>{}</code>, <code>[]</code>, <code>"text"</code>).</small></label>`;
12017
+ break;
12018
+ case "select": {
12019
+ const blank = field.required ? "" : '<option value="">\u2014 none \u2014</option>';
12020
+ const options = field.options.map(
12021
+ (option) => `<option value="${escapeHtml(option.value)}"${option.value === field.value ? " selected" : ""}>${escapeHtml(option.label)}</option>`
12022
+ ).join("");
12023
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><select name="${name}"${required}>${blank}${options}</select></label>`;
12024
+ break;
12025
+ }
12026
+ case "number":
12027
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><input type="number" name="${name}" value="${value}"${field.step !== null ? ` step="${escapeHtml(field.step)}"` : ""}${required}></label>`;
12028
+ break;
12029
+ case "datetime":
12030
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><input type="datetime-local" name="${name}" value="${value}"${required}></label>`;
12031
+ break;
12032
+ case "date":
12033
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><input type="date" name="${name}" value="${value}"${required}></label>`;
12034
+ break;
12035
+ case "time":
12036
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><input type="time" name="${name}" value="${value}"${required}></label>`;
12037
+ break;
12038
+ default:
12039
+ control = `<label><span>${label}${field.required ? " *" : ""}</span><input type="text" name="${name}" value="${value}"${required}></label>`;
12040
+ }
12041
+ const error = field.error !== null ? `<small class="tempest-admin-form__field-error">${escapeHtml(field.error)}</small>` : "";
12042
+ return `<div class="tempest-admin-form__field${field.error !== null ? " tempest-admin-form__field--error" : ""}">${control}${error}</div>`;
12043
+ }
12044
+ function renderFormPage(context, view) {
12045
+ if (context.session === null) throw new Error("The admin form requires a session");
12046
+ const heading = view.mode === "create" ? `New ${view.title}` : `Edit ${view.title}`;
12047
+ const body = `<section class="tempest-admin-form">
12048
+ <header class="tempest-admin-detail__header">
12049
+ <h1>${escapeHtml(heading)}</h1>
12050
+ <a href="${escapeHtml(view.backUrl)}">\u2190 Back</a>
12051
+ </header>
12052
+ ${view.error !== null ? `<p class="tempest-admin-form__error">${escapeHtml(view.error)}</p>` : ""}
12053
+ <form method="post" action="${escapeHtml(view.actionUrl)}" class="tempest-admin-form__form">
12054
+ <input type="hidden" name="csrf_token" value="${escapeHtml(context.session.csrfToken)}">
12055
+ ${view.fields.map(renderFormField).join("")}
12056
+ <div class="tempest-admin-form__actions">
12057
+ <button type="submit">${view.mode === "create" ? "Create" : "Save"}</button>
12058
+ <a href="${escapeHtml(view.backUrl)}" class="tempest-admin-form__cancel">Cancel</a>
12059
+ </div>
12060
+ </form>
12061
+ </section>`;
12062
+ return renderLayout(context, `${heading} \xB7 ${context.site.title}`, body);
12063
+ }
12064
+ var logger2 = new JSONLogger("tempest_express_sdk.admin.router");
12065
+ var FK_OPTION_CAP = 1e3;
12066
+ var FLASH_MAX_LENGTH = 300;
12067
+ var FLASH_MESSAGES = {
12068
+ created: { text: "Record created.", level: "success" },
12069
+ updated: { text: "Record updated.", level: "success" },
12070
+ deleted: { text: "Record deleted.", level: "success" }
12071
+ };
12072
+ async function runCustomAction(action, context) {
12073
+ return await action.handler(context) ?? null;
12074
+ }
12075
+ function queryString(value) {
12076
+ if (typeof value === "string") return value.trim();
12077
+ if (Array.isArray(value) && typeof value[0] === "string") return value[0].trim();
12078
+ return "";
12079
+ }
12080
+ function buildQuery(entries) {
12081
+ const params = new URLSearchParams();
12082
+ for (const [key, value] of Object.entries(entries)) {
12083
+ if (value === void 0 || value === "") continue;
12084
+ params.set(key, String(value));
12085
+ }
12086
+ return params.toString();
12087
+ }
12088
+ function makeAdminRouter(site, options) {
12089
+ const prefix = (options.prefix ?? "/admin").replace(/\/$/, "");
12090
+ const theme = resolveAdminTheme(site.theme);
12091
+ const showMetrics = options.showMetrics ?? true;
12092
+ const exportMaxRows = options.exportMaxRows ?? 5e3;
12093
+ const sessions = new AdminSessionStore({
12094
+ secret: options.secretKey,
12095
+ ...options.cookieName === void 0 ? {} : { cookieName: options.cookieName },
12096
+ ...options.sessionMaxAgeSeconds === void 0 ? {} : { maxAgeSeconds: options.sessionMaxAgeSeconds },
12097
+ ...options.cookieSecure === void 0 ? {} : { cookieSecure: options.cookieSecure },
12098
+ cookiePath: prefix === "" ? "/" : prefix
12099
+ });
12100
+ const backend = options.authBackend;
12101
+ const router = express3.Router();
12102
+ router.use(prefix, express3.urlencoded({ extended: false }));
12103
+ const context = (req, session) => ({
12104
+ site,
12105
+ theme,
12106
+ prefix,
12107
+ session,
12108
+ currentPath: req.originalUrl.split("?")[0] ?? req.path,
12109
+ navModels: site.list().map((admin) => ({
12110
+ label: admin.verboseNamePlural(),
12111
+ url: `${prefix}/m/${admin.slug()}`
12112
+ })),
12113
+ messages: flashFor(req)
12114
+ });
12115
+ const flashFor = (req) => {
12116
+ const fixed = FLASH_MESSAGES[queryString(req.query.ok)];
12117
+ if (fixed !== void 0) return [fixed];
12118
+ const text = queryString(req.query.flash);
12119
+ if (text === "") return [];
12120
+ const level = queryString(req.query.level);
12121
+ return [
12122
+ {
12123
+ text: text.slice(0, FLASH_MAX_LENGTH),
12124
+ level: level === "error" || level === "warning" ? level : "success"
12125
+ }
12126
+ ];
12127
+ };
12128
+ const html = (res, body, status = 200) => {
12129
+ res.status(status).type("html").send(body);
12130
+ };
12131
+ const guarded = (handler) => (req, res) => {
12132
+ handler(req, res).catch((error) => {
12133
+ logger2.error("Admin request failed", {
12134
+ path: req.originalUrl,
12135
+ error: error instanceof Error ? error.message : String(error)
12136
+ });
12137
+ if (res.headersSent) return;
12138
+ html(
12139
+ res,
12140
+ renderLoginPage(context(req, null), "Something went wrong. Please try again."),
12141
+ 500
12142
+ );
12143
+ });
12144
+ };
12145
+ const authenticate = async (req, res) => {
12146
+ const session = sessions.load(req);
12147
+ if (session === null) {
12148
+ res.redirect(`${prefix}/login`);
12149
+ return null;
12150
+ }
12151
+ const dbSession = options.engine.session();
12152
+ const principal = await backend.loadPrincipal(dbSession, session.subject);
12153
+ if (principal === null) {
12154
+ sessions.clear(res);
12155
+ res.redirect(`${prefix}/login`);
12156
+ return null;
12157
+ }
12158
+ if (!session.mfaPassed) {
12159
+ res.redirect(`${prefix}/mfa`);
12160
+ return null;
12161
+ }
12162
+ return { session, dbSession, principal };
12163
+ };
12164
+ const resolveAdmin = (req, res, state) => {
12165
+ const admin = site.get(String(req.params.slug));
12166
+ if (admin === null) {
12167
+ html(res, renderNotFound(context(req, state.session)), 404);
12168
+ return null;
12169
+ }
12170
+ return admin;
12171
+ };
12172
+ const renderNotFound = (ctx) => renderDashboardPage(
12173
+ { ...ctx, messages: [{ text: "Not found.", level: "error" }] },
12174
+ [],
12175
+ null
12176
+ );
12177
+ const checkCsrf = (req, res, state) => {
12178
+ const body = req.body;
12179
+ if (csrfTokenMatches(state.session, body?.csrf_token)) return true;
12180
+ html(res, renderNotFound(context(req, state.session)), 403);
12181
+ return false;
12182
+ };
12183
+ router.get(`${prefix}/static/admin.css`, (_req, res) => {
12184
+ res.type("css").set("cache-control", "public, max-age=3600").send(ADMIN_CSS);
12185
+ });
12186
+ router.get(`${prefix}/login`, (req, res) => {
12187
+ html(res, renderLoginPage(context(req, null), null));
12188
+ });
12189
+ router.post(
12190
+ `${prefix}/login`,
12191
+ guarded(async (req, res) => {
12192
+ const body = req.body;
12193
+ const identifier = typeof body.identifier === "string" ? body.identifier : "";
12194
+ const password = typeof body.password === "string" ? body.password : "";
12195
+ const dbSession = options.engine.session();
12196
+ const principal = await backend.authenticate(dbSession, identifier, password);
12197
+ if (principal === null) {
12198
+ html(res, renderLoginPage(context(req, null), "Invalid credentials."), 401);
12199
+ return;
12200
+ }
12201
+ const needsMfa = await backend.mfaEnabled?.(principal) ?? false;
12202
+ const session = sessions.issue(
12203
+ backend.principalId(principal),
12204
+ backend.displayName(principal),
12205
+ !needsMfa
12206
+ );
12207
+ sessions.save(res, session);
12208
+ res.redirect(needsMfa ? `${prefix}/mfa` : `${prefix}/`);
12209
+ })
12210
+ );
12211
+ router.get(`${prefix}/mfa`, (req, res) => {
12212
+ const session = sessions.load(req);
12213
+ if (session === null) {
12214
+ res.redirect(`${prefix}/login`);
12215
+ return;
12216
+ }
12217
+ if (session.mfaPassed) {
12218
+ res.redirect(`${prefix}/`);
12219
+ return;
12220
+ }
12221
+ html(res, renderMfaPage(context(req, null), null));
12222
+ });
12223
+ router.post(
12224
+ `${prefix}/mfa`,
12225
+ guarded(async (req, res) => {
12226
+ const session = sessions.load(req);
12227
+ if (session === null) {
12228
+ res.redirect(`${prefix}/login`);
12229
+ return;
12230
+ }
12231
+ const body = req.body;
12232
+ const code = typeof body.code === "string" ? body.code : "";
12233
+ const dbSession = options.engine.session();
12234
+ const principal = await backend.loadPrincipal(dbSession, session.subject);
12235
+ const verified = principal !== null && (await backend.verifyMfa?.(principal, code) ?? false);
12236
+ if (!verified) {
12237
+ html(res, renderMfaPage(context(req, null), "Invalid code."), 401);
12238
+ return;
12239
+ }
12240
+ sessions.save(res, { ...session, mfaPassed: true });
12241
+ res.redirect(`${prefix}/`);
12242
+ })
12243
+ );
12244
+ router.post(
12245
+ `${prefix}/logout`,
12246
+ guarded(async (req, res) => {
12247
+ const session = sessions.load(req);
12248
+ if (session !== null && !csrfTokenMatches(session, req.body?.csrf_token)) {
12249
+ html(res, renderLoginPage(context(req, null), "Invalid request."), 403);
12250
+ return;
12251
+ }
12252
+ sessions.clear(res);
12253
+ res.redirect(`${prefix}/login`);
12254
+ })
12255
+ );
12256
+ router.get(
12257
+ `${prefix}/`,
12258
+ guarded(async (req, res) => {
12259
+ const state = await authenticate(req, res);
12260
+ if (state === null) return;
12261
+ const cards = [];
12262
+ for (const admin of site.list()) {
12263
+ let count = null;
12264
+ try {
12265
+ count = await admin.repository(state.dbSession).count();
12266
+ } catch (error) {
12267
+ logger2.warning("Admin dashboard count failed", {
12268
+ slug: admin.slug(),
12269
+ error: error instanceof Error ? error.message : String(error)
12270
+ });
12271
+ }
12272
+ cards.push({
12273
+ label: admin.verboseNamePlural(),
12274
+ count,
12275
+ url: `${prefix}/m/${admin.slug()}`,
12276
+ newUrl: admin.canCreate ? `${prefix}/m/${admin.slug()}/new` : null
12277
+ });
12278
+ }
12279
+ let metrics = null;
12280
+ if (showMetrics) {
12281
+ const snapshot2 = MetricsUtils.system();
12282
+ metrics = {
12283
+ cpuPercent: Math.round(snapshot2.cpu.loadPercent),
12284
+ memoryPercent: Math.round(snapshot2.memory.usedPercent),
12285
+ memoryUsedGb: (snapshot2.memory.used / 1024 ** 3).toFixed(1),
12286
+ memoryTotalGb: (snapshot2.memory.total / 1024 ** 3).toFixed(1)
12287
+ };
12288
+ }
12289
+ html(res, renderDashboardPage(context(req, state.session), cards, metrics));
12290
+ })
12291
+ );
12292
+ router.get(
12293
+ `${prefix}/m/:slug`,
12294
+ guarded(async (req, res) => {
12295
+ const state = await authenticate(req, res);
12296
+ if (state === null) return;
12297
+ const admin = resolveAdmin(req, res, state);
12298
+ if (admin === null) return;
12299
+ html(res, await renderList(req, admin, state));
12300
+ })
12301
+ );
12302
+ router.get(
12303
+ `${prefix}/m/:slug/new`,
12304
+ guarded(async (req, res) => {
12305
+ const state = await authenticate(req, res);
12306
+ if (state === null) return;
12307
+ const admin = resolveAdmin(req, res, state);
12308
+ if (admin === null) return;
12309
+ if (!admin.canCreate) {
12310
+ html(res, renderNotFound(context(req, state.session)), 404);
12311
+ return;
12312
+ }
12313
+ html(
12314
+ res,
12315
+ renderFormPage(context(req, state.session), {
12316
+ mode: "create",
12317
+ title: admin.verboseName(),
12318
+ fields: buildFormFields(admin, {
12319
+ foreignKeyOptions: await foreignKeyOptionsFor(admin, state.dbSession)
12320
+ }),
12321
+ actionUrl: `${prefix}/m/${admin.slug()}/new`,
12322
+ backUrl: `${prefix}/m/${admin.slug()}`,
12323
+ error: null
12324
+ })
12325
+ );
12326
+ })
12327
+ );
12328
+ router.post(
12329
+ `${prefix}/m/:slug/new`,
12330
+ guarded(async (req, res) => {
12331
+ const state = await authenticate(req, res);
12332
+ if (state === null) return;
12333
+ const admin = resolveAdmin(req, res, state);
12334
+ if (admin === null) return;
12335
+ if (!admin.canCreate) {
12336
+ html(res, renderNotFound(context(req, state.session)), 404);
12337
+ return;
12338
+ }
12339
+ if (!checkCsrf(req, res, state)) return;
12340
+ const body = req.body;
12341
+ const parsed = parseFormBody(admin, body);
12342
+ const foreignKeyOptions = await foreignKeyOptionsFor(admin, state.dbSession);
12343
+ const rerender = (error, status) => {
12344
+ html(
12345
+ res,
12346
+ renderFormPage(context(req, state.session), {
12347
+ mode: "create",
12348
+ title: admin.verboseName(),
12349
+ fields: buildFormFields(admin, {
12350
+ values: body,
12351
+ errors: parsed.errors,
12352
+ foreignKeyOptions
12353
+ }),
12354
+ actionUrl: `${prefix}/m/${admin.slug()}/new`,
12355
+ backUrl: `${prefix}/m/${admin.slug()}`,
12356
+ error
12357
+ }),
12358
+ status
12359
+ );
12360
+ };
12361
+ if (Object.keys(parsed.errors).length > 0) {
12362
+ rerender("Please fix the highlighted fields.", 400);
12363
+ return;
12364
+ }
12365
+ try {
12366
+ await admin.repository(state.dbSession).create(parsed.data);
12367
+ } catch (error) {
12368
+ rerender(describeWriteFailure(admin, error), 400);
12369
+ return;
12370
+ }
12371
+ res.redirect(`${prefix}/m/${admin.slug()}?ok=created`);
12372
+ })
12373
+ );
12374
+ router.get(
12375
+ `${prefix}/m/:slug/export.:format`,
12376
+ guarded(async (req, res) => {
12377
+ const state = await authenticate(req, res);
12378
+ if (state === null) return;
12379
+ const admin = resolveAdmin(req, res, state);
12380
+ if (admin === null) return;
12381
+ const format = String(req.params.format);
12382
+ if (format !== "csv" && format !== "json") {
12383
+ html(res, renderNotFound(context(req, state.session)), 404);
12384
+ return;
12385
+ }
12386
+ const query = await resolveListQuery(req, admin, state.dbSession);
12387
+ const result = await admin.repository(state.dbSession).paginate({
12388
+ page: 1,
12389
+ pageSize: exportMaxRows,
12390
+ ...query.orderBy === void 0 ? {} : { orderBy: query.orderBy },
12391
+ ascending: query.ascending,
12392
+ ...query.where === void 0 ? {} : { filters: query.where }
12393
+ });
12394
+ const columns = admin.listDisplayNames();
12395
+ const rows = result.items;
12396
+ const payload = format === "csv" ? toCsv(columns, rows) : toJson(columns, rows);
12397
+ res.status(200).type(format === "csv" ? "text/csv; charset=utf-8" : "application/json").set("content-disposition", `attachment; filename="${admin.slug()}.${format}"`).send(payload);
12398
+ })
12399
+ );
12400
+ router.post(
12401
+ `${prefix}/m/:slug/bulk`,
12402
+ guarded(async (req, res) => {
12403
+ const state = await authenticate(req, res);
12404
+ if (state === null) return;
12405
+ const admin = resolveAdmin(req, res, state);
12406
+ if (admin === null) return;
12407
+ if (!checkCsrf(req, res, state)) return;
12408
+ const body = req.body;
12409
+ const action = typeof body.action === "string" ? body.action : "";
12410
+ const raw = body.ids;
12411
+ const ids = (Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]).filter((value) => typeof value === "string").filter((value) => value !== "");
12412
+ const listUrl = `${prefix}/m/${admin.slug()}`;
12413
+ const back = (message, level) => {
12414
+ res.redirect(`${listUrl}?${buildQuery({ flash: message, level })}`);
12415
+ };
12416
+ if (ids.length === 0) {
12417
+ back("No rows were selected.", "warning");
12418
+ return;
12419
+ }
12420
+ if (!bulkActionsFor(admin).some((option) => option.value === action)) {
12421
+ html(res, renderNotFound(context(req, state.session)), 400);
12422
+ return;
12423
+ }
12424
+ const repository = admin.repository(state.dbSession);
12425
+ const scope = { [admin.identityField]: { in: ids } };
12426
+ if (action.startsWith("custom:")) {
12427
+ const custom = admin.getAction(action.slice("custom:".length));
12428
+ if (custom === null) {
12429
+ html(res, renderNotFound(context(req, state.session)), 400);
12430
+ return;
12431
+ }
12432
+ let result;
12433
+ try {
12434
+ result = await runCustomAction(custom, {
12435
+ ids,
12436
+ repository,
12437
+ dbSession: state.dbSession,
12438
+ request: req,
12439
+ session: state.session,
12440
+ principal: state.principal
12441
+ });
12442
+ } catch (error) {
12443
+ logger2.error("Admin action failed", {
12444
+ slug: admin.slug(),
12445
+ action: custom.name,
12446
+ error: error instanceof Error ? error.message : String(error)
12447
+ });
12448
+ back(
12449
+ `${custom.label} failed: ${error instanceof Error ? error.message : String(error)}`,
12450
+ "error"
12451
+ );
12452
+ return;
12453
+ }
12454
+ if (result === null) {
12455
+ res.redirect(listUrl);
12456
+ return;
12457
+ }
12458
+ back(result.message, result.category ?? "success");
12459
+ return;
12460
+ }
12461
+ if (action === "delete") {
12462
+ const removed = await repository.delete(scope);
12463
+ back(`Deleted ${removed} record${removed === 1 ? "" : "s"}.`, "success");
12464
+ return;
12465
+ }
12466
+ const active = action === "activate";
12467
+ const changed = await repository.update(scope, { isActive: active });
12468
+ back(
12469
+ `${active ? "Activated" : "Deactivated"} ${changed} record${changed === 1 ? "" : "s"}.`,
12470
+ "success"
12471
+ );
12472
+ })
12473
+ );
12474
+ router.get(
12475
+ `${prefix}/m/:slug/:identity`,
12476
+ guarded(async (req, res) => {
12477
+ const state = await authenticate(req, res);
12478
+ if (state === null) return;
12479
+ const admin = resolveAdmin(req, res, state);
12480
+ if (admin === null) return;
12481
+ const row = await findRow(admin, state.dbSession, String(req.params.identity));
12482
+ if (row === null) {
12483
+ html(res, renderNotFound(context(req, state.session)), 404);
12484
+ return;
12485
+ }
12486
+ const identity = String(row[admin.identityField]);
12487
+ html(
12488
+ res,
12489
+ renderDetailPage(context(req, state.session), {
12490
+ title: admin.verboseName(),
12491
+ identity,
12492
+ fields: admin.detailFieldNames().map((name) => ({ label: name, value: formatCellValue(row[name]) })),
12493
+ backUrl: `${prefix}/m/${admin.slug()}`,
12494
+ editUrl: admin.canEdit ? `${prefix}/m/${admin.slug()}/${identity}/edit` : null,
12495
+ deleteUrl: admin.canDelete ? `${prefix}/m/${admin.slug()}/${identity}/delete` : null
12496
+ })
12497
+ );
12498
+ })
12499
+ );
12500
+ router.get(
12501
+ `${prefix}/m/:slug/:identity/edit`,
12502
+ guarded(async (req, res) => {
12503
+ const state = await authenticate(req, res);
12504
+ if (state === null) return;
12505
+ const admin = resolveAdmin(req, res, state);
12506
+ if (admin === null) return;
12507
+ const identity = String(req.params.identity);
12508
+ const row = admin.canEdit ? await findRow(admin, state.dbSession, identity) : null;
12509
+ if (row === null) {
12510
+ html(res, renderNotFound(context(req, state.session)), 404);
12511
+ return;
12512
+ }
12513
+ html(
12514
+ res,
12515
+ renderFormPage(context(req, state.session), {
12516
+ mode: "edit",
12517
+ title: admin.verboseName(),
12518
+ fields: buildFormFields(admin, {
12519
+ values: row,
12520
+ foreignKeyOptions: await foreignKeyOptionsFor(admin, state.dbSession)
12521
+ }),
12522
+ actionUrl: `${prefix}/m/${admin.slug()}/${identity}/edit`,
12523
+ backUrl: `${prefix}/m/${admin.slug()}/${identity}`,
12524
+ error: null
12525
+ })
12526
+ );
12527
+ })
12528
+ );
12529
+ router.post(
12530
+ `${prefix}/m/:slug/:identity/edit`,
12531
+ guarded(async (req, res) => {
12532
+ const state = await authenticate(req, res);
12533
+ if (state === null) return;
12534
+ const admin = resolveAdmin(req, res, state);
12535
+ if (admin === null) return;
12536
+ const identity = String(req.params.identity);
12537
+ if (!admin.canEdit) {
12538
+ html(res, renderNotFound(context(req, state.session)), 404);
12539
+ return;
12540
+ }
12541
+ if (!checkCsrf(req, res, state)) return;
12542
+ const body = req.body;
12543
+ const parsed = parseFormBody(admin, body);
12544
+ const foreignKeyOptions = await foreignKeyOptionsFor(admin, state.dbSession);
12545
+ const rerender = (error, status) => {
12546
+ html(
12547
+ res,
12548
+ renderFormPage(context(req, state.session), {
12549
+ mode: "edit",
12550
+ title: admin.verboseName(),
12551
+ fields: buildFormFields(admin, {
12552
+ values: body,
12553
+ errors: parsed.errors,
12554
+ foreignKeyOptions
12555
+ }),
12556
+ actionUrl: `${prefix}/m/${admin.slug()}/${identity}/edit`,
12557
+ backUrl: `${prefix}/m/${admin.slug()}/${identity}`,
12558
+ error
12559
+ }),
12560
+ status
12561
+ );
12562
+ };
12563
+ if (Object.keys(parsed.errors).length > 0) {
12564
+ rerender("Please fix the highlighted fields.", 400);
12565
+ return;
12566
+ }
12567
+ try {
12568
+ const changed = await admin.repository(state.dbSession).update({ [admin.identityField]: identity }, parsed.data);
12569
+ if (changed === 0) {
12570
+ html(res, renderNotFound(context(req, state.session)), 404);
12571
+ return;
12572
+ }
12573
+ } catch (error) {
12574
+ rerender(describeWriteFailure(admin, error), 400);
12575
+ return;
12576
+ }
12577
+ res.redirect(`${prefix}/m/${admin.slug()}/${identity}?ok=updated`);
12578
+ })
12579
+ );
12580
+ router.post(
12581
+ `${prefix}/m/:slug/:identity/delete`,
12582
+ guarded(async (req, res) => {
12583
+ const state = await authenticate(req, res);
12584
+ if (state === null) return;
12585
+ const admin = resolveAdmin(req, res, state);
12586
+ if (admin === null) return;
12587
+ if (!admin.canDelete) {
12588
+ html(res, renderNotFound(context(req, state.session)), 404);
12589
+ return;
12590
+ }
12591
+ if (!checkCsrf(req, res, state)) return;
12592
+ await admin.repository(state.dbSession).delete({ [admin.identityField]: String(req.params.identity) });
12593
+ res.redirect(`${prefix}/m/${admin.slug()}?ok=deleted`);
12594
+ })
12595
+ );
12596
+ async function findRow(admin, dbSession, identity) {
12597
+ const row = await admin.repository(dbSession).first({ [admin.identityField]: identity });
12598
+ return row ?? null;
12599
+ }
12600
+ async function renderList(req, admin, state) {
12601
+ const columns = adminColumns(admin.model);
12602
+ const query = await resolveListQuery(req, admin, state.dbSession);
12603
+ const page2 = Math.max(1, Number.parseInt(queryString(req.query.page), 10) || 1);
12604
+ const result = await admin.repository(state.dbSession).paginate({
12605
+ page: page2,
12606
+ pageSize: admin.pageSize,
12607
+ ...query.orderBy === void 0 ? {} : { orderBy: query.orderBy },
12608
+ ascending: query.ascending,
12609
+ ...query.where === void 0 ? {} : { filters: query.where }
12610
+ });
12611
+ const displayed = admin.listDisplayNames();
12612
+ const sort = {};
12613
+ for (const column6 of displayed) {
12614
+ if (!(column6 in columns)) continue;
12615
+ const active = (query.sortColumn ?? admin.orderKey) === column6;
12616
+ const nextAscending = active ? !query.ascending : true;
12617
+ sort[column6] = {
12618
+ url: `?${buildQuery({
12619
+ ...query.baseQuery,
12620
+ sort: column6,
12621
+ dir: nextAscending ? "asc" : "desc"
12622
+ })}`,
12623
+ active,
12624
+ ascending: query.ascending
12625
+ };
12626
+ }
12627
+ const sortParams = {
12628
+ sort: query.sortColumn ?? void 0,
12629
+ dir: query.sortColumn === null ? void 0 : query.ascending ? "asc" : "desc"
12630
+ };
12631
+ const pageUrl = (target) => `?${buildQuery({ ...query.baseQuery, ...sortParams, page: target })}`;
12632
+ const exportQuery = buildQuery({ ...query.baseQuery, ...sortParams });
12633
+ const exportUrl = (format) => `${prefix}/m/${admin.slug()}/export.${format}${exportQuery === "" ? "" : `?${exportQuery}`}`;
12634
+ const view = {
12635
+ title: admin.verboseNamePlural(),
12636
+ columns: displayed,
12637
+ rows: result.items.map((row) => {
12638
+ const identity = String(row[admin.identityField]);
12639
+ return {
12640
+ identity,
12641
+ cells: displayed.map((column6) => formatCellValue(row[column6])),
12642
+ url: `${prefix}/m/${admin.slug()}/${identity}`
12643
+ };
12644
+ }),
12645
+ total: result.total,
12646
+ page: result.page,
12647
+ pages: result.pages,
12648
+ prevUrl: result.page > 1 ? pageUrl(result.page - 1) : null,
12649
+ nextUrl: result.page < result.pages ? pageUrl(result.page + 1) : null,
12650
+ searchable: query.searchable.length > 0,
12651
+ searchValue: query.search,
12652
+ filters: query.filterViews,
12653
+ sort,
12654
+ newUrl: admin.canCreate ? `${prefix}/m/${admin.slug()}/new` : null,
12655
+ bulkActions: bulkActionsFor(admin),
12656
+ bulkUrl: `${prefix}/m/${admin.slug()}/bulk`,
12657
+ exportCsvUrl: exportUrl("csv"),
12658
+ exportJsonUrl: exportUrl("json")
12659
+ };
12660
+ return renderListPage(context(req, state.session), view);
12661
+ }
12662
+ async function resolveListQuery(req, admin, dbSession) {
12663
+ const columns = adminColumns(admin.model);
12664
+ const search = queryString(req.query.q);
12665
+ const sortField = queryString(req.query.sort);
12666
+ const sortColumn = sortField in columns ? sortField : null;
12667
+ const ascending = sortColumn === null ? admin.orderAscending : queryString(req.query.dir) !== "desc";
12668
+ const conditions = [];
12669
+ const filterViews = [];
12670
+ for (const field of admin.listFilter) {
12671
+ const column6 = columns[field];
12672
+ if (column6 === void 0) continue;
12673
+ const spec = filterForColumn(column6);
12674
+ if (spec.kind === "daterange") {
12675
+ const from = queryString(req.query[`filter_${field}_from`]);
12676
+ const to = queryString(req.query[`filter_${field}_to`]);
12677
+ const bounds = {};
12678
+ if (from !== "") bounds.gte = new Date(from);
12679
+ if (to !== "") bounds.lte = /* @__PURE__ */ new Date(`${to}T23:59:59.999Z`);
12680
+ if (Object.keys(bounds).length > 0) conditions.push({ [field]: bounds });
12681
+ filterViews.push({
12682
+ field,
12683
+ label: humanizeField(field),
12684
+ kind: "daterange",
12685
+ value: "",
12686
+ valueFrom: from,
12687
+ valueTo: to,
12688
+ options: []
12689
+ });
12690
+ continue;
12691
+ }
12692
+ const related = await relatedOptions(column6, dbSession);
12693
+ const options2 = related ?? spec.options;
12694
+ const value = queryString(req.query[`filter_${field}`]);
12695
+ if (value !== "") {
12696
+ conditions.push({
12697
+ [field]: column6.type.kind === "boolean" ? value === "true" : value
12698
+ });
12699
+ }
12700
+ filterViews.push({
12701
+ field,
12702
+ label: humanizeField(field),
12703
+ kind: related === null ? spec.kind : "select",
12704
+ value,
12705
+ valueFrom: "",
12706
+ valueTo: "",
12707
+ options: options2.map((option) => ({
12708
+ value: option.value,
12709
+ label: option.label,
12710
+ selected: option.value === value
12711
+ }))
12712
+ });
12713
+ }
12714
+ const searchable = admin.searchFields.filter((field) => {
12715
+ const column6 = columns[field];
12716
+ return column6 !== void 0 && isSearchableColumn(column6);
12717
+ });
12718
+ if (search !== "" && searchable.length > 0) {
12719
+ conditions.push(
12720
+ or(...searchable.map((field) => ({ [field]: { ilike: `%${search}%` } })))
12721
+ );
12722
+ }
12723
+ const baseQuery = { q: search };
12724
+ for (const view of filterViews) {
12725
+ if (view.kind === "daterange") {
12726
+ baseQuery[`filter_${view.field}_from`] = view.valueFrom;
12727
+ baseQuery[`filter_${view.field}_to`] = view.valueTo;
12728
+ } else {
12729
+ baseQuery[`filter_${view.field}`] = view.value;
12730
+ }
12731
+ }
12732
+ return {
12733
+ search,
12734
+ searchable,
12735
+ where: conditions.length === 0 ? void 0 : and(...conditions),
12736
+ orderBy: sortColumn ?? admin.orderKey ?? void 0,
12737
+ ascending,
12738
+ sortColumn,
12739
+ filterViews,
12740
+ baseQuery
12741
+ };
12742
+ }
12743
+ async function relatedOptions(column6, dbSession) {
12744
+ const table = foreignKeyTable(column6);
12745
+ if (table === null) return null;
12746
+ const referenced = site.get(table);
12747
+ if (referenced === null) return null;
12748
+ const rows = await referenced.repository(dbSession).list();
12749
+ return rows.slice(0, FK_OPTION_CAP).map((row) => ({
12750
+ value: String(row[referenced.identityField]),
12751
+ label: foreignKeyLabel(referenced, row)
12752
+ }));
12753
+ }
12754
+ async function foreignKeyOptionsFor(admin, dbSession) {
12755
+ const columns = adminColumns(admin.model);
12756
+ const options2 = {};
12757
+ for (const field of Object.keys(foreignKeyFields(admin))) {
12758
+ const column6 = columns[field];
12759
+ if (column6 === void 0) continue;
12760
+ const related = await relatedOptions(column6, dbSession);
12761
+ if (related !== null) options2[field] = related;
12762
+ }
12763
+ return options2;
12764
+ }
12765
+ return router;
12766
+ }
12767
+ function bulkActionsFor(admin) {
12768
+ const actions = [];
12769
+ const hasActiveFlag = "isActive" in adminColumns(admin.model);
12770
+ if (admin.canEdit && hasActiveFlag) {
12771
+ actions.push({ value: "activate", label: "Activate", dangerous: false });
12772
+ actions.push({ value: "deactivate", label: "Deactivate", dangerous: false });
12773
+ }
12774
+ if (admin.canDelete) {
12775
+ actions.push({ value: "delete", label: "Delete", dangerous: true });
12776
+ }
12777
+ for (const action of admin.customActions()) {
12778
+ actions.push({
12779
+ value: `custom:${action.name}`,
12780
+ label: action.label,
12781
+ dangerous: action.dangerous
12782
+ });
12783
+ }
12784
+ return actions;
12785
+ }
12786
+ function exportValue(value) {
12787
+ if (value instanceof Date) return value.toISOString();
12788
+ if (typeof value === "bigint") return value.toString();
12789
+ if (value instanceof Uint8Array) return Buffer.from(value).toString("base64");
12790
+ return value;
12791
+ }
12792
+ function csvField(value) {
12793
+ if (value === null || value === void 0) return "";
12794
+ const text = typeof value === "object" ? JSON.stringify(value) : String(value);
12795
+ if (/[",\r\n]/.test(text)) return `"${text.replace(/"/g, '""')}"`;
12796
+ return text;
12797
+ }
12798
+ function toCsv(columns, rows) {
12799
+ const lines = [columns.map(csvField).join(",")];
12800
+ for (const row of rows) {
12801
+ lines.push(columns.map((column6) => csvField(exportValue(row[column6]))).join(","));
12802
+ }
12803
+ return `${lines.join("\r\n")}\r
12804
+ `;
12805
+ }
12806
+ function toJson(columns, rows) {
12807
+ return JSON.stringify(
12808
+ rows.map(
12809
+ (row) => Object.fromEntries(columns.map((column6) => [column6, exportValue(row[column6])]))
12810
+ ),
12811
+ null,
12812
+ 2
12813
+ );
12814
+ }
12815
+ function describeWriteFailure(admin, error) {
12816
+ const detail = error instanceof Error ? error.message : String(error);
12817
+ return `The database refused this ${admin.verboseName().toLowerCase()}: ${detail}`;
12818
+ }
12819
+
12820
+ // src/admin/json/site.ts
12821
+ var AdminJsonSite = class {
9322
12822
  /**
9323
12823
  * @param brand - Display name surfaced under `GET {prefix}/`.
9324
12824
  */
@@ -9359,7 +12859,7 @@ function requireResource(site, name) {
9359
12859
  if (!resource) throw new NotFoundException({ message: `Unknown resource: ${name}` });
9360
12860
  return resource;
9361
12861
  }
9362
- function makeAdminRouter(site, options = {}) {
12862
+ function makeAdminJsonRouter(site, options = {}) {
9363
12863
  const prefix = (options.prefix ?? "/admin").replace(/\/$/, "");
9364
12864
  const router = Router();
9365
12865
  if (options.guard) router.use(prefix, options.guard);
@@ -9998,7 +13498,7 @@ function renderPasswordResetFormPage(options) {
9998
13498
  </form>`
9999
13499
  );
10000
13500
  }
10001
- var logger2 = new JSONLogger("tempest_express_sdk.api.handlers");
13501
+ var logger3 = new JSONLogger("tempest_express_sdk.api.handlers");
10002
13502
  var REQUEST_ID_HEADER = "X-Request-ID";
10003
13503
  var VALID_REQUEST_ID = /^[A-Za-z0-9._\-:+/=]{1,128}$/;
10004
13504
  function requestIdMiddleware() {
@@ -10040,7 +13540,7 @@ function makeAppExceptionHandler(options = {}) {
10040
13540
  return;
10041
13541
  }
10042
13542
  const isServerError = exc.statusCode >= 500;
10043
- logger2.log(isServerError ? serverErrorLevel : "info", "AppException handled", {
13543
+ logger3.log(isServerError ? serverErrorLevel : "info", "AppException handled", {
10044
13544
  path: req.path,
10045
13545
  method: req.method,
10046
13546
  statusCode: exc.statusCode,
@@ -10064,7 +13564,7 @@ function makeUnhandledExceptionHandler(options = {}) {
10064
13564
  const { includeStack = false, logLevel = "error" } = options;
10065
13565
  return (err, req, res, _next) => {
10066
13566
  const error = err instanceof Error ? err : new Error(String(err));
10067
- logger2.log(logLevel, "Unhandled exception", {
13567
+ logger3.log(logLevel, "Unhandled exception", {
10068
13568
  path: req.path,
10069
13569
  method: req.method,
10070
13570
  [HTTP_500_MARKER]: true,
@@ -10118,7 +13618,7 @@ function generateOpenApiDocument(registry, options) {
10118
13618
  var DEFAULT_DOCS_FAVICON = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMiAzMiI+PHJlY3Qgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIiByeD0iNyIgZmlsbD0iIzRjNmVmNSIvPjxwYXRoIGQ9Ik0xNy45IDQuNSA4LjYgMTguNGg1LjJMMTMgMjcuNWw5LjQtMTMuOWgtNS4zeiIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg==";
10119
13619
  var REDOC_CDN_URL = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js";
10120
13620
  var REDOC_BUNDLE_SPECIFIER = "redoc/bundles/redoc.standalone.js";
10121
- function escapeHtml(value) {
13621
+ function escapeHtml2(value) {
10122
13622
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
10123
13623
  }
10124
13624
  function scriptLiteral(value) {
@@ -10127,7 +13627,7 @@ function scriptLiteral(value) {
10127
13627
  function faviconTag(favicon) {
10128
13628
  if (favicon === false) return "";
10129
13629
  return `
10130
- <link rel="icon" href="${escapeHtml(favicon)}" />`;
13630
+ <link rel="icon" href="${escapeHtml2(favicon)}" />`;
10131
13631
  }
10132
13632
  function mountOpenApiJson(app, path, document) {
10133
13633
  app.get(path, (_req, res) => {
@@ -10171,19 +13671,19 @@ function swaggerHtml(options) {
10171
13671
  };
10172
13672
  const standalone = merged.layout === "StandaloneLayout";
10173
13673
  const presetScript = standalone ? `
10174
- <script src="${escapeHtml(assetsBase)}/swagger-ui-standalone-preset.js"></script>` : "";
13674
+ <script src="${escapeHtml2(assetsBase)}/swagger-ui-standalone-preset.js"></script>` : "";
10175
13675
  const presets = standalone ? "[SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]" : "[SwaggerUIBundle.presets.apis]";
10176
13676
  return `<!doctype html>
10177
13677
  <html lang="en">
10178
13678
  <head>
10179
13679
  <meta charset="utf-8" />
10180
13680
  <meta name="viewport" content="width=device-width, initial-scale=1" />
10181
- <title>${escapeHtml(title)}</title>${faviconTag(favicon)}
10182
- <link rel="stylesheet" href="${escapeHtml(assetsBase)}/swagger-ui.css" />
13681
+ <title>${escapeHtml2(title)}</title>${faviconTag(favicon)}
13682
+ <link rel="stylesheet" href="${escapeHtml2(assetsBase)}/swagger-ui.css" />
10183
13683
  </head>
10184
13684
  <body>
10185
13685
  <div id="swagger-ui"></div>
10186
- <script src="${escapeHtml(assetsBase)}/swagger-ui-bundle.js"></script>${presetScript}
13686
+ <script src="${escapeHtml2(assetsBase)}/swagger-ui-bundle.js"></script>${presetScript}
10187
13687
  <script>
10188
13688
  var options = ${scriptLiteral(merged)};
10189
13689
  options.presets = ${presets};
@@ -10198,7 +13698,7 @@ function mountSwaggerUi(app, path, specUrl, options = {}) {
10198
13698
  const ui = options.ui ?? {};
10199
13699
  assertSerializableUiOptions(ui);
10200
13700
  const assetsPath = `${path.replace(/\/$/, "")}/assets`;
10201
- app.use(assetsPath, express2.static(getAbsoluteFSPath()));
13701
+ app.use(assetsPath, express3.static(getAbsoluteFSPath()));
10202
13702
  const handler = (_req, res) => {
10203
13703
  res.type("html").send(swaggerHtml({ specUrl, title, assetsBase: assetsPath, favicon, ui }));
10204
13704
  };
@@ -10218,7 +13718,7 @@ function redocHtml(specUrl, title, scriptUrl, favicon) {
10218
13718
  <head>
10219
13719
  <meta charset="utf-8" />
10220
13720
  <meta name="viewport" content="width=device-width, initial-scale=1" />
10221
- <title>${escapeHtml(title)}</title>${faviconTag(favicon)}
13721
+ <title>${escapeHtml2(title)}</title>${faviconTag(favicon)}
10222
13722
  <style>
10223
13723
  body { margin: 0; padding: 0; }
10224
13724
  #redoc-load-error {
@@ -10250,7 +13750,7 @@ function redocHtml(specUrl, title, scriptUrl, favicon) {
10250
13750
  <code>scriptUrl</code> at a copy you host.
10251
13751
  </p>
10252
13752
  </div>
10253
- <redoc spec-url="${escapeHtml(specUrl)}"></redoc>
13753
+ <redoc spec-url="${escapeHtml2(specUrl)}"></redoc>
10254
13754
  <script>
10255
13755
  window.__redocLoadFailed = function () {
10256
13756
  document.getElementById("redoc-script-url").textContent = ${scriptLiteral(scriptUrl)};
@@ -10260,7 +13760,7 @@ function redocHtml(specUrl, title, scriptUrl, favicon) {
10260
13760
  if (element) element.style.display = "none";
10261
13761
  };
10262
13762
  </script>
10263
- <script src="${escapeHtml(scriptUrl)}" onerror="window.__redocLoadFailed()"></script>
13763
+ <script src="${escapeHtml2(scriptUrl)}" onerror="window.__redocLoadFailed()"></script>
10264
13764
  </body>
10265
13765
  </html>`;
10266
13766
  }
@@ -10323,7 +13823,7 @@ function makeMetricsRouter(options = {}) {
10323
13823
  });
10324
13824
  return router;
10325
13825
  }
10326
- var logger3 = new JSONLogger("tempest_express_sdk.api.server");
13826
+ var logger4 = new JSONLogger("tempest_express_sdk.api.server");
10327
13827
  function corsMiddleware(origins) {
10328
13828
  const allowAll = origins === "*";
10329
13829
  const allowList = new Set(Array.isArray(origins) ? origins : [origins]);
@@ -10348,9 +13848,9 @@ function corsMiddleware(origins) {
10348
13848
  };
10349
13849
  }
10350
13850
  async function createApp(options = {}) {
10351
- const app = express2();
10352
- app.use(express2.json({ limit: options.jsonLimit ?? "100kb" }));
10353
- app.use(express2.urlencoded({ extended: true }));
13851
+ const app = express3();
13852
+ app.use(express3.json({ limit: options.jsonLimit ?? "100kb" }));
13853
+ app.use(express3.urlencoded({ extended: true }));
10354
13854
  app.use(requestIdMiddleware());
10355
13855
  if (options.corsOrigins) {
10356
13856
  app.use(corsMiddleware(options.corsOrigins));
@@ -10382,7 +13882,7 @@ function runServer(app, options = {}) {
10382
13882
  const port = options.port ?? 8e3;
10383
13883
  return new Promise((resolve) => {
10384
13884
  const server = app.listen(port, host, () => {
10385
- logger3.info("Server listening", { host, port });
13885
+ logger4.info("Server listening", { host, port });
10386
13886
  resolve(server);
10387
13887
  });
10388
13888
  });
@@ -10924,7 +14424,7 @@ function rateLimitMiddleware(options = {}) {
10924
14424
 
10925
14425
  // src/api/middlewares/tracing.ts
10926
14426
  function requestTracingMiddleware(options = {}) {
10927
- const logger4 = new JSONLogger(options.loggerName ?? "tempest_express_sdk.api.tracing");
14427
+ const logger5 = new JSONLogger(options.loggerName ?? "tempest_express_sdk.api.tracing");
10928
14428
  const level = options.level ?? "info";
10929
14429
  const exempt = new Set(options.exemptPaths ?? []);
10930
14430
  return (req, res, next) => {
@@ -10935,7 +14435,7 @@ function requestTracingMiddleware(options = {}) {
10935
14435
  const start = process.hrtime.bigint();
10936
14436
  res.on("finish", () => {
10937
14437
  const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
10938
- logger4.log(level, "request", {
14438
+ logger5.log(level, "request", {
10939
14439
  method: req.method,
10940
14440
  path: req.path,
10941
14441
  statusCode: res.statusCode,
@@ -11315,6 +14815,6 @@ async function withTestDatabase(models, fn) {
11315
14815
  }
11316
14816
  }
11317
14817
 
11318
- export { ActivationService, AdminSite, AppException, AttemptThrottle, AuditAction, BaseAuditLogModel, BaseController, BaseModel, BaseOAuthClient, BaseOutboxModel, BaseService, BaseUserModel, BaseUserRefreshTokenModel, BaseUserTokenModel, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_DOCS_FAVICON, DEFAULT_LOCALE, EmailProvider, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, GitHubOAuthClient, GoogleOAuthClient, GracefulShutdown, HTTPClient, HTTP_500_LOG_FILE, HTTP_500_MARKER, HttpMetrics, IDEMPOTENCY_HEADER, InvalidTokenException, JSONLogger, JWTUtils, LEVEL_LOG_FILES, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemoryIdempotencyStore, MemoryRateLimitStore, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MessagingHub, MetricsUtils, MfaService, NotFoundException, OAuthError, OIDCProvider, OutboxRelay, OutboxStatus, PHONE_BR_PATTERN, PasswordResetService, REDOC_CDN_URL, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, RedisIdempotencyStore, RedisRateLimitStore, RedisSSEBroker, RedisSessionStore, Region, RetryPolicy, S3UploadStorage, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TelegramProvider, TenantScopedRepository, TooManyRequestsException, TwilioSmsProvider, UF, UnauthorizedException, UserAuthService, UserTokenPurpose, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WebhookSignatureVerifier, WhatsAppProvider, activationSchema, addLogSink, attachWebSocketHub, authResponseSchema, authSettingsShape, backupDatabase, bearerToken, bodySizeLimitMiddleware, broadcastText, buildContentDisposition, buildPaginationLinkHeader, cached2 as cached, cepField, citiesByUf, cnpjField, coerceFlag, configureFileLogging, configureLogging, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createTestDatabase, createdByColumn, csrfMiddleware, cursorPaginationFilterSchema, cursorPaginationSchema, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, diffSnapshots, emailSettingsShape, encodeCursor, envList, generateCsrfToken, generateOAuthState, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, idempotencyMiddleware, inboundMessageSchema, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, jwtSettingsShape, keyByHeader, keyByIp, keyByJwtClaim, keyByJwtSubject, listStates, logEntrySchema, logSettingsShape, loginSchema, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeLogsRouter, makeMetricsRouter, makeSessionMiddleware, makeToolSpecRouter, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaChallengeSchema, mfaCodeSchema, mfaEnrollResponseSchema, minioSettingsShape, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, prometheusMiddleware, rabbitmqSettingsShape, rateLimitMiddleware, redisSettingsShape, refreshSchema, registerExceptionHandlers, renderAuthResultPage, renderPasswordResetFormPage, requestIdMiddleware, requestTracingMiddleware, requireRoles, resolveDownloadPath, resolveRedocBundle, runServer, runWithRequestContext, sendBytesDownload, sendFileDownload, sessionCookie, sessionSettingsShape, setRequestId, signupSchema, snapshot, sseResponse, statesByRegion, syncFilterSchema, syncPaginationSchema, tableNameFor, toUtc, tokenFromUrl, tokenPairSchema, tokenSettingsShape, ufField, updatedByColumn, uploadSettingsShape, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSettingsShape, webPushSubscriptionSchema, webSocketSettingsShape, withTestDatabase, wrapWithSlowQueryLog, wsEnvelopeSchema };
14818
+ export { ADMIN_CSS, ActivationService, AdminJsonSite, AdminModel, AdminSessionStore, AdminSite, AppException, AttemptThrottle, AuditAction, BaseAuditLogModel, BaseController, BaseModel, BaseOAuthClient, BaseOutboxModel, BaseService, BaseUserModel, BaseUserRefreshTokenModel, BaseUserTokenModel, CEP_PATTERN, CNPJ_PATTERN, CPF_PATTERN, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, CircuitOpenError, CompositeFeatureFlagBackend, ConflictException, DEFAULT_DOCS_FAVICON, DEFAULT_LOCALE, EmailProvider, EmailUtils, EnvFeatureFlagBackend, EventStream, ExpiredTokenException, FeatureFlags, ForbiddenException, GitHubOAuthClient, GoogleOAuthClient, GracefulShutdown, HTTPClient, HTTP_500_LOG_FILE, HTTP_500_MARKER, HttpMetrics, IDEMPOTENCY_HEADER, InvalidTokenException, JSONLogger, JWTUtils, LEVEL_LOG_FILES, LocalUploadStorage, MemoryBroker, MemoryCacheManager, MemoryFeatureFlagBackend, MemoryIdempotencyStore, MemoryRateLimitStore, MemorySessionStore, MemoryThrottleBackend, MessageCatalog, MessagingHub, MetricsUtils, MfaService, NotFoundException, OAuthError, OIDCProvider, OutboxRelay, OutboxStatus, PHONE_BR_PATTERN, PasswordResetService, REDOC_CDN_URL, REQUEST_ID_HEADER, RabbitBroker, RedisCacheManager, RedisIdempotencyStore, RedisRateLimitStore, RedisSSEBroker, RedisSessionStore, Region, RetryPolicy, S3UploadStorage, SSEBroker, ServerSentEvent, SessionService, TOTPHelper, TaskManager, TelegramProvider, TenantScopedRepository, TooManyRequestsException, TwilioSmsProvider, UF, UnauthorizedException, UserAuthService, UserModelAuthBackend, UserTokenPurpose, ValidationException, WebPushDispatcher, WebPushError, WebPushGoneError, WebSocketHub, WebhookSignatureVerifier, WhatsAppProvider, activationSchema, addLogSink, adminAction, adminColumns, adminThemeCss, attachWebSocketHub, authResponseSchema, authSettingsShape, backupDatabase, bearerToken, bodySizeLimitMiddleware, broadcastText, buildContentDisposition, buildFormFields, buildPaginationLinkHeader, cached2 as cached, cepField, citiesByUf, cnpjField, coerceFlag, configureFileLogging, configureLogging, cpfField, cpfOrCnpjField, createApp, createOpenApiRegistry, createTestDatabase, createdByColumn, csrfMiddleware, csrfTokenMatches, cursorPaginationFilterSchema, cursorPaginationSchema, decodeCursor, defaultMessageCatalog, defineEnum, deletedAtColumn, diffSnapshots, emailSettingsShape, encodeCursor, envList, escapeHtml, filterForColumn, foreignKeyFields, foreignKeyLabel, foreignKeyTable, formatCellValue, formatFieldValue, generateCsrfToken, generateOAuthState, generateOpaqueToken, generateOpenApiDocument, getAuth, getClientIp, getConditions, getPaginationConditions, getRequestId, getState, hashOpaqueToken, humanizeField, idempotencyMiddleware, inboundMessageSchema, isColumnOptional, isSearchableColumn, isValidCep, isValidCity, isValidCnpj, isValidCpf, isValidCpfCnpj, isValidPhoneBr, isValidUf, jwtSettingsShape, keyByHeader, keyByIp, keyByJwtClaim, keyByJwtSubject, listStates, logEntrySchema, logSettingsShape, loginSchema, makeAdminJsonRouter, makeAdminRouter, makeAppExceptionHandler, makeAuthRouter, makeFlagGuard, makeHealthRouter, makeJwtAuthMiddleware, makeLogsRouter, makeMetricsRouter, makeSessionMiddleware, makeToolSpecRouter, makeTwilioWebhookRouter, makeUnhandledExceptionHandler, makeWhatsAppWebhookRouter, mfaChallengeSchema, mfaCodeSchema, mfaEnrollResponseSchema, minioSettingsShape, modifyDict, mountOpenApiJson, mountRedoc, mountSwaggerUi, normalizeCep, normalizeCnpj, normalizeCpf, normalizeCpfCnpj, normalizePhoneBr, normalizeUf, notFoundHandler, onlyDigits, paginationFilterSchema, paginationSchema, parseAcceptLanguage, parseCookies, parseFormBody, passwordResetConfirmSchema, passwordResetRequestSchema, phoneBrField, prometheusMiddleware, rabbitmqSettingsShape, rateLimitMiddleware, redisSettingsShape, refreshSchema, registerExceptionHandlers, renderAuthResultPage, renderDashboardPage, renderDetailPage, renderFormPage, renderLayout, renderListPage, renderLoginPage, renderMfaPage, renderPasswordResetFormPage, requestIdMiddleware, requestTracingMiddleware, requireRoles, resolveAdminTheme, resolveDownloadPath, resolveRedocBundle, runServer, runWithRequestContext, sendBytesDownload, sendFileDownload, sessionCookie, sessionSettingsShape, setRequestId, signupSchema, snapshot, sseResponse, statesByRegion, syncFilterSchema, syncPaginationSchema, tableNameFor, toUtc, tokenFromUrl, tokenPairSchema, tokenSettingsShape, ufField, updatedByColumn, uploadSettingsShape, userPublicSchema, utcnow, validateTwilioSignature, verifyOpaqueToken, webPushKeysSchema, webPushPayloadSchema, webPushSettingsShape, webPushSubscriptionSchema, webSocketSettingsShape, widgetForColumn, withTestDatabase, wrapWithSlowQueryLog, wsEnvelopeSchema };
11319
14819
  //# sourceMappingURL=index.js.map
11320
14820
  //# sourceMappingURL=index.js.map