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