@revenexx/app-sdk 1.1.0 → 1.3.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.
@@ -1,5 +1,5 @@
1
- import { n as SettingsDefaults, k as ReadOptions, m as ResolvedSettings, q as SettingsSnapshot, p as SettingsReader, o as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-CtrtCOoG.cjs';
2
- export { D as DEFAULT_GATEWAY_ENDPOINT, e as DEFAULT_SETTINGS_ERROR_TTL_MS, f as DEFAULT_SETTINGS_TIMEOUT_MS, g as DEFAULT_SETTINGS_TTL_MS, H as HttpError, j as HttpErrorOptions, l as Refusal, r as SettingsSource, v as badRequest, w as conflict, s as createSettings, x as forbidden, t as isHttpError, y as notFound, u as refusalOf } from '../errors-CtrtCOoG.cjs';
1
+ import { n as SettingsDefaults, k as ReadOptions, m as ResolvedSettings, q as SettingsSnapshot, p as SettingsReader, o as SettingsOptions, Q as Query, R as Row, P as Page, r as SettingsSource } from '../errors-CtrtCOoG.cjs';
2
+ export { D as DEFAULT_GATEWAY_ENDPOINT, e as DEFAULT_SETTINGS_ERROR_TTL_MS, f as DEFAULT_SETTINGS_TIMEOUT_MS, g as DEFAULT_SETTINGS_TTL_MS, H as HttpError, j as HttpErrorOptions, l as Refusal, v as badRequest, w as conflict, s as createSettings, x as forbidden, t as isHttpError, y as notFound, u as refusalOf } from '../errors-CtrtCOoG.cjs';
3
3
 
4
4
  /**
5
5
  * Who is acting — the person behind a request, as the platform established
@@ -98,6 +98,42 @@ declare const ACTOR_HEADERS: {
98
98
  */
99
99
  declare function actorFrom(header: (name: string) => string | undefined): Actor;
100
100
 
101
+ /**
102
+ * The market a request is for, and the country that market ships from.
103
+ *
104
+ * The gateway forwards the caller's market as `X-Revenexx-Market` and, since
105
+ * PE-1010, resolves the market's `ship_from_country` (markets app, RAD-246)
106
+ * and sets it as `X-Revenexx-Market-Country`. The country header is
107
+ * gateway-injected: a caller's copy never reaches the App, so it can be read
108
+ * the way the tenant is read.
109
+ *
110
+ * An App prints a document's addresses for the sender country — the
111
+ * document's own sender address when it has one, else `c.market.country`.
112
+ * When the gateway could not resolve one (no markets app, a market that names
113
+ * no country yet, an older gateway), `country` is null and the App falls back
114
+ * to its own rule.
115
+ */
116
+ /** The market a request is for. */
117
+ interface Market {
118
+ /** The market code (`X-Revenexx-Market`), or null when the call names none. */
119
+ code: string | null;
120
+ /**
121
+ * The ISO 3166-1 alpha-2 country the market ships from
122
+ * (`X-Revenexx-Market-Country`), or null. Never set without a market.
123
+ */
124
+ country: string | null;
125
+ }
126
+ /** The two headers, as the gateway sets them. */
127
+ declare const MARKET_HEADERS: {
128
+ readonly code: "x-revenexx-market";
129
+ readonly country: "x-revenexx-market-country";
130
+ };
131
+ /**
132
+ * Read the market off a header reader. A blank market is no market; a country
133
+ * that is not two upper-case letters, or one without a market, is null.
134
+ */
135
+ declare function marketFrom(header: (name: string) => string | undefined | null): Market;
136
+
101
137
  /**
102
138
  * Minimal HTTP router for revenexx App functions.
103
139
  *
@@ -165,6 +201,12 @@ interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {
165
201
  * token's claims: those describe the calling SYSTEM.
166
202
  */
167
203
  actor: Actor;
204
+ /**
205
+ * The market this request is for, and the country it ships from — both
206
+ * set by the gateway (see ./market.ts). `country` is what a document
207
+ * without a sender address of its own prints addresses for.
208
+ */
209
+ market: Market;
168
210
  /** Case-insensitive header lookup. */
169
211
  header(name: string): string;
170
212
  log(message: string): void;
@@ -310,4 +352,238 @@ interface CrudOptions {
310
352
  declare const RESERVED_LIST_QUERY_KEYS: readonly string[];
311
353
  declare function mountCrud<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: CrudOptions): App<D>;
312
354
 
313
- export { ACTOR_HEADERS, type Actor, type ActorPlane, type ActorTrust, type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, RESERVED_LIST_QUERY_KEYS, ReadOptions, type RepoLike, ResolvedSettings, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, actorFrom, createApp, mountCrud };
355
+ /**
356
+ * The trash, as one helper: `mountTrash` gives an entity the three routes and
357
+ * the purge job every trash needs (PE-1022).
358
+ *
359
+ * const trash = mountTrash(app, db.organizations, {
360
+ * path: '/organizations',
361
+ * children: [{ name: 'contacts', repo: db.contacts, column: 'organization_id' }],
362
+ * guard: (org) => (org.is_default ? { reason: 'The default organization stays.' } : null),
363
+ * blockers: async (org, c) => [
364
+ * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),
365
+ * ],
366
+ * });
367
+ *
368
+ * // the scheduled job (ADR-0103), once per tenant:
369
+ * await trash.purge(c);
370
+ *
371
+ * The routes:
372
+ *
373
+ * DELETE <path>/{id} live row → into the trash, with its children
374
+ * trashed row → deleted for good, through `blockers`
375
+ * POST <path>/{id}/restore back out of the trash, with the children it took
376
+ *
377
+ * The entity needs `trash: true` in schema.json, which gives it `deleted_at`,
378
+ * `deleted_by`, `deleted_by_id`, `trash_batch` and `purge_blocked_reason`.
379
+ * Baseline does the rest of the
380
+ * platform side: lookups leave trashed rows out, the event trigger says
381
+ * `*.trashed` / `*.restored` (declare them with `on: ["trash"]` /
382
+ * `on: ["restore"]`), and a real DELETE is `*.deleted`.
383
+ *
384
+ * Two rules this helper exists to keep:
385
+ *
386
+ * - The final delete has ONE code path. The second DELETE and the purge job
387
+ * both go through `deleteForGood`, so a blocker the app declares cannot be
388
+ * bypassed by waiting 90 days.
389
+ * - A blocker that cannot be checked blocks. A guard that throws, or a count
390
+ * the gateway would not answer, is a reason to keep the row, never a
391
+ * reason to delete it.
392
+ */
393
+
394
+ /** The column whose value says "in the trash". */
395
+ declare const TRASH_COLUMN = "deleted_at";
396
+ /** Trash retention when Baseline holds no value for the tenant (RAD-247, ADR-0114). */
397
+ declare const DEFAULT_TRASH_RETENTION_DAYS = 90;
398
+ /** The column `trash: true` gives an entity for why the purge left a row in the trash. */
399
+ declare const PURGE_REASON_COLUMN = "purge_blocked_reason";
400
+ /** The gateway route the tenant's retention is read from (PE-1022). */
401
+ declare const AUDIT_SETTINGS_PATH = "/v1/audit/settings";
402
+ /** Why a row may not go into the trash, or may not be deleted for good. */
403
+ interface Blocker {
404
+ /** One sentence for the person who asked. */
405
+ reason: string;
406
+ /** How many records stand in the way, when it is a count. */
407
+ count?: number;
408
+ /** `unverifiable` when the check itself failed; anything else is the app's. */
409
+ code?: string;
410
+ details?: unknown;
411
+ }
412
+ /**
413
+ * Who asks, as far as a check needs it. A handler's `c` is one; so is the
414
+ * purge job's source.
415
+ */
416
+ interface TrashCaller extends SettingsSource {
417
+ tenant?: string | null;
418
+ actor?: Actor;
419
+ header?(name: string): string;
420
+ }
421
+ /** A guard or blocker check. Return nothing, one blocker or several. */
422
+ type BlockerCheck = (row: Row, caller: TrashCaller) => Blocker | null | undefined | (Blocker | null | undefined)[] | Promise<Blocker | null | undefined | (Blocker | null | undefined)[]>;
423
+ /** Rows that go into the trash with their parent and come back with it. */
424
+ interface TrashChild {
425
+ /** Key in the answer's `took`, e.g. `contacts`. */
426
+ name: string;
427
+ repo: Pick<RepoLike, 'list' | 'update' | 'delete'>;
428
+ /** The child's column holding the parent id. */
429
+ column: string;
430
+ }
431
+ interface TrashOptions {
432
+ /** Base path of the entity, e.g. `/organizations`. */
433
+ path: string;
434
+ /** Path param for the row id (default `id`). */
435
+ idParam?: string;
436
+ /** Dependent rows that form one group with the parent (contacts, sub-categories, variants). */
437
+ children?: TrashChild[];
438
+ /**
439
+ * May the row go into the trash? Only the default record and a running
440
+ * process that would break (an open approval, an active punchout account)
441
+ * belong here; everything else is a warning for the dialog, not a blocker.
442
+ */
443
+ guard?: BlockerCheck;
444
+ /**
445
+ * May the row be deleted for good? Checked on the second DELETE and by the
446
+ * purge job alike: references from open processes, configuration that names
447
+ * the row. Cross-app references are counted through the gateway
448
+ * (`createGatewayCounter`).
449
+ */
450
+ blockers?: BlockerCheck;
451
+ /** Who may delete for good. Default: whoever may call the route. */
452
+ canDeleteForGood?: (caller: TrashCaller) => boolean;
453
+ /**
454
+ * A parent that has to be live for this row to come back, e.g. a contact's
455
+ * organization. Restoring a row whose parent is in the trash is refused.
456
+ */
457
+ parent?: {
458
+ repo: Pick<RepoLike, 'get'>;
459
+ column: string;
460
+ };
461
+ /**
462
+ * The final delete of the row itself. Default `repo.delete(id)`. Children
463
+ * of the row's group are deleted before it either way.
464
+ */
465
+ deleteRow?: (row: Row, caller: TrashCaller) => Promise<void>;
466
+ /**
467
+ * The text column the purge writes the blocked reason into, and a restore
468
+ * clears. Default `purge_blocked_reason`, which `trash: true` creates; `false`
469
+ * for an entity that has no such column.
470
+ */
471
+ purgeReasonColumn?: string | false;
472
+ /**
473
+ * App-fired events. Prefer Baseline's trigger for `trashed` / `restored`
474
+ * (`on: ["trash"]` / `on: ["restore"]`) — it is transactional. Name them
475
+ * here only for an entity that has no such trigger; declaring both
476
+ * publishes twice. `purged` is one summary per purge run.
477
+ */
478
+ events?: {
479
+ emit: (name: string, data: Row, options?: {
480
+ topicId?: string | null;
481
+ eventId?: string;
482
+ }) => Promise<unknown>;
483
+ trashed?: string;
484
+ restored?: string;
485
+ purged?: string;
486
+ };
487
+ /** Reading the tenant's trash retention through the gateway. */
488
+ retention?: RetentionOptions;
489
+ /** Clock (tests). */
490
+ now?: () => Date;
491
+ }
492
+ /**
493
+ * Where and how the retention is read. The URL is, first match wins: `url`,
494
+ * REVENEXX_AUDIT_SETTINGS_URL, or `{endpoint}/v1/audit/settings` with
495
+ * `endpoint` defaulting to REVENEXX_GATEWAY_ENDPOINT or the platform gateway.
496
+ */
497
+ interface RetentionOptions {
498
+ /** The full settings URL. */
499
+ url?: string;
500
+ /** Gateway base URL. */
501
+ endpoint?: string;
502
+ timeoutMs?: number;
503
+ fetchImpl?: typeof fetch;
504
+ env?: Record<string, string | undefined>;
505
+ }
506
+ /** What one purge run did. */
507
+ interface PurgeResult {
508
+ /** True when the run did nothing because the retention could not be read. */
509
+ skipped: boolean;
510
+ reason?: string;
511
+ retentionDays?: number;
512
+ /** Rows trashed before this instant were due. */
513
+ cutoff?: string;
514
+ purged: string[];
515
+ blocked: {
516
+ id: string;
517
+ blockers: Blocker[];
518
+ }[];
519
+ }
520
+ interface TrashHandle {
521
+ /** Put a row into the trash, with its children. Throws the same refusals as the route. */
522
+ trash(id: string, caller: TrashCaller): Promise<{
523
+ id: string;
524
+ batch: string;
525
+ took: Record<string, number>;
526
+ }>;
527
+ /** Take a row and its group back out of the trash. */
528
+ restore(id: string, caller: TrashCaller): Promise<{
529
+ id: string;
530
+ took: Record<string, number>;
531
+ }>;
532
+ /** Delete a trashed row for good, through the blockers. */
533
+ deleteForGood(id: string, caller: TrashCaller): Promise<{
534
+ id: string;
535
+ took: Record<string, number>;
536
+ }>;
537
+ /** The purge job: delete for good what is past the tenant's retention. Never throws for a single row. */
538
+ purge(caller: TrashCaller, options?: {
539
+ max?: number;
540
+ }): Promise<PurgeResult>;
541
+ }
542
+ /** The URL the retention is read from; see `RetentionOptions`. */
543
+ declare function auditSettingsUrl(options?: RetentionOptions): string;
544
+ /**
545
+ * The tenant's trash retention in days, read through the gateway
546
+ * (`GET /v1/audit/settings`, which Baseline answers). An App holds no Baseline
547
+ * credential; the gateway takes the request's own.
548
+ *
549
+ * Throws when the settings cannot be read: guessing would be the dangerous
550
+ * direction — a tenant that keeps its trash for a year must not lose it after
551
+ * 90 days because a request timed out. The default applies only when the
552
+ * settings answer and hold no value.
553
+ */
554
+ declare function readTrashRetention(caller: TrashCaller, options?: RetentionOptions): Promise<number>;
555
+ /**
556
+ * Mount the trash routes for one entity and return the handle the purge job
557
+ * (and any hand-written route) uses.
558
+ */
559
+ declare function mountTrash<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: TrashOptions): TrashHandle;
560
+ /**
561
+ * Count another App's records through the gateway, for a blocker that crosses
562
+ * an App boundary ("open orders of this organization"). Apps never read each
563
+ * other's tables; the owning App's list route answers, and its `page.total` is
564
+ * the count.
565
+ *
566
+ * const refs = createGatewayCounter();
567
+ * blockers: async (org, c) => [
568
+ * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),
569
+ * ]
570
+ *
571
+ * A count the gateway does not give — an error, a timeout, a route that does
572
+ * not report `total` — is `null`, and `blocker` turns `null` into an
573
+ * `unverifiable` blocker. Not knowing is never a pass.
574
+ */
575
+ declare function createGatewayCounter(options?: {
576
+ endpoint?: string;
577
+ timeoutMs?: number;
578
+ fetchImpl?: typeof fetch;
579
+ env?: Record<string, string | undefined>;
580
+ }): {
581
+ count: (caller: TrashCaller, path: string, where?: Record<string, string | number | boolean>) => Promise<number | null>;
582
+ blocker: (caller: TrashCaller, check: {
583
+ path: string;
584
+ where?: Record<string, string | number | boolean>;
585
+ reason: string;
586
+ }) => Promise<Blocker | null>;
587
+ };
588
+
589
+ export { ACTOR_HEADERS, AUDIT_SETTINGS_PATH, type Actor, type ActorPlane, type ActorTrust, type App, type AppOptions, type Blocker, type BlockerCheck, type CrudOptions, DEFAULT_TRASH_RETENTION_DAYS, type FnContext, type FnRequest, type FnResponse, type Handler, MARKET_HEADERS, type Market, PURGE_REASON_COLUMN, type PurgeResult, RESERVED_LIST_QUERY_KEYS, ReadOptions, type RepoLike, ResolvedSettings, type RetentionOptions, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, SettingsSource, TRASH_COLUMN, type TrashCaller, type TrashChild, type TrashHandle, type TrashOptions, actorFrom, auditSettingsUrl, createApp, createGatewayCounter, marketFrom, mountCrud, mountTrash, readTrashRetention };
@@ -1,5 +1,5 @@
1
- import { n as SettingsDefaults, k as ReadOptions, m as ResolvedSettings, q as SettingsSnapshot, p as SettingsReader, o as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-CtrtCOoG.js';
2
- export { D as DEFAULT_GATEWAY_ENDPOINT, e as DEFAULT_SETTINGS_ERROR_TTL_MS, f as DEFAULT_SETTINGS_TIMEOUT_MS, g as DEFAULT_SETTINGS_TTL_MS, H as HttpError, j as HttpErrorOptions, l as Refusal, r as SettingsSource, v as badRequest, w as conflict, s as createSettings, x as forbidden, t as isHttpError, y as notFound, u as refusalOf } from '../errors-CtrtCOoG.js';
1
+ import { n as SettingsDefaults, k as ReadOptions, m as ResolvedSettings, q as SettingsSnapshot, p as SettingsReader, o as SettingsOptions, Q as Query, R as Row, P as Page, r as SettingsSource } from '../errors-CtrtCOoG.js';
2
+ export { D as DEFAULT_GATEWAY_ENDPOINT, e as DEFAULT_SETTINGS_ERROR_TTL_MS, f as DEFAULT_SETTINGS_TIMEOUT_MS, g as DEFAULT_SETTINGS_TTL_MS, H as HttpError, j as HttpErrorOptions, l as Refusal, v as badRequest, w as conflict, s as createSettings, x as forbidden, t as isHttpError, y as notFound, u as refusalOf } from '../errors-CtrtCOoG.js';
3
3
 
4
4
  /**
5
5
  * Who is acting — the person behind a request, as the platform established
@@ -98,6 +98,42 @@ declare const ACTOR_HEADERS: {
98
98
  */
99
99
  declare function actorFrom(header: (name: string) => string | undefined): Actor;
100
100
 
101
+ /**
102
+ * The market a request is for, and the country that market ships from.
103
+ *
104
+ * The gateway forwards the caller's market as `X-Revenexx-Market` and, since
105
+ * PE-1010, resolves the market's `ship_from_country` (markets app, RAD-246)
106
+ * and sets it as `X-Revenexx-Market-Country`. The country header is
107
+ * gateway-injected: a caller's copy never reaches the App, so it can be read
108
+ * the way the tenant is read.
109
+ *
110
+ * An App prints a document's addresses for the sender country — the
111
+ * document's own sender address when it has one, else `c.market.country`.
112
+ * When the gateway could not resolve one (no markets app, a market that names
113
+ * no country yet, an older gateway), `country` is null and the App falls back
114
+ * to its own rule.
115
+ */
116
+ /** The market a request is for. */
117
+ interface Market {
118
+ /** The market code (`X-Revenexx-Market`), or null when the call names none. */
119
+ code: string | null;
120
+ /**
121
+ * The ISO 3166-1 alpha-2 country the market ships from
122
+ * (`X-Revenexx-Market-Country`), or null. Never set without a market.
123
+ */
124
+ country: string | null;
125
+ }
126
+ /** The two headers, as the gateway sets them. */
127
+ declare const MARKET_HEADERS: {
128
+ readonly code: "x-revenexx-market";
129
+ readonly country: "x-revenexx-market-country";
130
+ };
131
+ /**
132
+ * Read the market off a header reader. A blank market is no market; a country
133
+ * that is not two upper-case letters, or one without a market, is null.
134
+ */
135
+ declare function marketFrom(header: (name: string) => string | undefined | null): Market;
136
+
101
137
  /**
102
138
  * Minimal HTTP router for revenexx App functions.
103
139
  *
@@ -165,6 +201,12 @@ interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {
165
201
  * token's claims: those describe the calling SYSTEM.
166
202
  */
167
203
  actor: Actor;
204
+ /**
205
+ * The market this request is for, and the country it ships from — both
206
+ * set by the gateway (see ./market.ts). `country` is what a document
207
+ * without a sender address of its own prints addresses for.
208
+ */
209
+ market: Market;
168
210
  /** Case-insensitive header lookup. */
169
211
  header(name: string): string;
170
212
  log(message: string): void;
@@ -310,4 +352,238 @@ interface CrudOptions {
310
352
  declare const RESERVED_LIST_QUERY_KEYS: readonly string[];
311
353
  declare function mountCrud<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: CrudOptions): App<D>;
312
354
 
313
- export { ACTOR_HEADERS, type Actor, type ActorPlane, type ActorTrust, type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, RESERVED_LIST_QUERY_KEYS, ReadOptions, type RepoLike, ResolvedSettings, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, actorFrom, createApp, mountCrud };
355
+ /**
356
+ * The trash, as one helper: `mountTrash` gives an entity the three routes and
357
+ * the purge job every trash needs (PE-1022).
358
+ *
359
+ * const trash = mountTrash(app, db.organizations, {
360
+ * path: '/organizations',
361
+ * children: [{ name: 'contacts', repo: db.contacts, column: 'organization_id' }],
362
+ * guard: (org) => (org.is_default ? { reason: 'The default organization stays.' } : null),
363
+ * blockers: async (org, c) => [
364
+ * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),
365
+ * ],
366
+ * });
367
+ *
368
+ * // the scheduled job (ADR-0103), once per tenant:
369
+ * await trash.purge(c);
370
+ *
371
+ * The routes:
372
+ *
373
+ * DELETE <path>/{id} live row → into the trash, with its children
374
+ * trashed row → deleted for good, through `blockers`
375
+ * POST <path>/{id}/restore back out of the trash, with the children it took
376
+ *
377
+ * The entity needs `trash: true` in schema.json, which gives it `deleted_at`,
378
+ * `deleted_by`, `deleted_by_id`, `trash_batch` and `purge_blocked_reason`.
379
+ * Baseline does the rest of the
380
+ * platform side: lookups leave trashed rows out, the event trigger says
381
+ * `*.trashed` / `*.restored` (declare them with `on: ["trash"]` /
382
+ * `on: ["restore"]`), and a real DELETE is `*.deleted`.
383
+ *
384
+ * Two rules this helper exists to keep:
385
+ *
386
+ * - The final delete has ONE code path. The second DELETE and the purge job
387
+ * both go through `deleteForGood`, so a blocker the app declares cannot be
388
+ * bypassed by waiting 90 days.
389
+ * - A blocker that cannot be checked blocks. A guard that throws, or a count
390
+ * the gateway would not answer, is a reason to keep the row, never a
391
+ * reason to delete it.
392
+ */
393
+
394
+ /** The column whose value says "in the trash". */
395
+ declare const TRASH_COLUMN = "deleted_at";
396
+ /** Trash retention when Baseline holds no value for the tenant (RAD-247, ADR-0114). */
397
+ declare const DEFAULT_TRASH_RETENTION_DAYS = 90;
398
+ /** The column `trash: true` gives an entity for why the purge left a row in the trash. */
399
+ declare const PURGE_REASON_COLUMN = "purge_blocked_reason";
400
+ /** The gateway route the tenant's retention is read from (PE-1022). */
401
+ declare const AUDIT_SETTINGS_PATH = "/v1/audit/settings";
402
+ /** Why a row may not go into the trash, or may not be deleted for good. */
403
+ interface Blocker {
404
+ /** One sentence for the person who asked. */
405
+ reason: string;
406
+ /** How many records stand in the way, when it is a count. */
407
+ count?: number;
408
+ /** `unverifiable` when the check itself failed; anything else is the app's. */
409
+ code?: string;
410
+ details?: unknown;
411
+ }
412
+ /**
413
+ * Who asks, as far as a check needs it. A handler's `c` is one; so is the
414
+ * purge job's source.
415
+ */
416
+ interface TrashCaller extends SettingsSource {
417
+ tenant?: string | null;
418
+ actor?: Actor;
419
+ header?(name: string): string;
420
+ }
421
+ /** A guard or blocker check. Return nothing, one blocker or several. */
422
+ type BlockerCheck = (row: Row, caller: TrashCaller) => Blocker | null | undefined | (Blocker | null | undefined)[] | Promise<Blocker | null | undefined | (Blocker | null | undefined)[]>;
423
+ /** Rows that go into the trash with their parent and come back with it. */
424
+ interface TrashChild {
425
+ /** Key in the answer's `took`, e.g. `contacts`. */
426
+ name: string;
427
+ repo: Pick<RepoLike, 'list' | 'update' | 'delete'>;
428
+ /** The child's column holding the parent id. */
429
+ column: string;
430
+ }
431
+ interface TrashOptions {
432
+ /** Base path of the entity, e.g. `/organizations`. */
433
+ path: string;
434
+ /** Path param for the row id (default `id`). */
435
+ idParam?: string;
436
+ /** Dependent rows that form one group with the parent (contacts, sub-categories, variants). */
437
+ children?: TrashChild[];
438
+ /**
439
+ * May the row go into the trash? Only the default record and a running
440
+ * process that would break (an open approval, an active punchout account)
441
+ * belong here; everything else is a warning for the dialog, not a blocker.
442
+ */
443
+ guard?: BlockerCheck;
444
+ /**
445
+ * May the row be deleted for good? Checked on the second DELETE and by the
446
+ * purge job alike: references from open processes, configuration that names
447
+ * the row. Cross-app references are counted through the gateway
448
+ * (`createGatewayCounter`).
449
+ */
450
+ blockers?: BlockerCheck;
451
+ /** Who may delete for good. Default: whoever may call the route. */
452
+ canDeleteForGood?: (caller: TrashCaller) => boolean;
453
+ /**
454
+ * A parent that has to be live for this row to come back, e.g. a contact's
455
+ * organization. Restoring a row whose parent is in the trash is refused.
456
+ */
457
+ parent?: {
458
+ repo: Pick<RepoLike, 'get'>;
459
+ column: string;
460
+ };
461
+ /**
462
+ * The final delete of the row itself. Default `repo.delete(id)`. Children
463
+ * of the row's group are deleted before it either way.
464
+ */
465
+ deleteRow?: (row: Row, caller: TrashCaller) => Promise<void>;
466
+ /**
467
+ * The text column the purge writes the blocked reason into, and a restore
468
+ * clears. Default `purge_blocked_reason`, which `trash: true` creates; `false`
469
+ * for an entity that has no such column.
470
+ */
471
+ purgeReasonColumn?: string | false;
472
+ /**
473
+ * App-fired events. Prefer Baseline's trigger for `trashed` / `restored`
474
+ * (`on: ["trash"]` / `on: ["restore"]`) — it is transactional. Name them
475
+ * here only for an entity that has no such trigger; declaring both
476
+ * publishes twice. `purged` is one summary per purge run.
477
+ */
478
+ events?: {
479
+ emit: (name: string, data: Row, options?: {
480
+ topicId?: string | null;
481
+ eventId?: string;
482
+ }) => Promise<unknown>;
483
+ trashed?: string;
484
+ restored?: string;
485
+ purged?: string;
486
+ };
487
+ /** Reading the tenant's trash retention through the gateway. */
488
+ retention?: RetentionOptions;
489
+ /** Clock (tests). */
490
+ now?: () => Date;
491
+ }
492
+ /**
493
+ * Where and how the retention is read. The URL is, first match wins: `url`,
494
+ * REVENEXX_AUDIT_SETTINGS_URL, or `{endpoint}/v1/audit/settings` with
495
+ * `endpoint` defaulting to REVENEXX_GATEWAY_ENDPOINT or the platform gateway.
496
+ */
497
+ interface RetentionOptions {
498
+ /** The full settings URL. */
499
+ url?: string;
500
+ /** Gateway base URL. */
501
+ endpoint?: string;
502
+ timeoutMs?: number;
503
+ fetchImpl?: typeof fetch;
504
+ env?: Record<string, string | undefined>;
505
+ }
506
+ /** What one purge run did. */
507
+ interface PurgeResult {
508
+ /** True when the run did nothing because the retention could not be read. */
509
+ skipped: boolean;
510
+ reason?: string;
511
+ retentionDays?: number;
512
+ /** Rows trashed before this instant were due. */
513
+ cutoff?: string;
514
+ purged: string[];
515
+ blocked: {
516
+ id: string;
517
+ blockers: Blocker[];
518
+ }[];
519
+ }
520
+ interface TrashHandle {
521
+ /** Put a row into the trash, with its children. Throws the same refusals as the route. */
522
+ trash(id: string, caller: TrashCaller): Promise<{
523
+ id: string;
524
+ batch: string;
525
+ took: Record<string, number>;
526
+ }>;
527
+ /** Take a row and its group back out of the trash. */
528
+ restore(id: string, caller: TrashCaller): Promise<{
529
+ id: string;
530
+ took: Record<string, number>;
531
+ }>;
532
+ /** Delete a trashed row for good, through the blockers. */
533
+ deleteForGood(id: string, caller: TrashCaller): Promise<{
534
+ id: string;
535
+ took: Record<string, number>;
536
+ }>;
537
+ /** The purge job: delete for good what is past the tenant's retention. Never throws for a single row. */
538
+ purge(caller: TrashCaller, options?: {
539
+ max?: number;
540
+ }): Promise<PurgeResult>;
541
+ }
542
+ /** The URL the retention is read from; see `RetentionOptions`. */
543
+ declare function auditSettingsUrl(options?: RetentionOptions): string;
544
+ /**
545
+ * The tenant's trash retention in days, read through the gateway
546
+ * (`GET /v1/audit/settings`, which Baseline answers). An App holds no Baseline
547
+ * credential; the gateway takes the request's own.
548
+ *
549
+ * Throws when the settings cannot be read: guessing would be the dangerous
550
+ * direction — a tenant that keeps its trash for a year must not lose it after
551
+ * 90 days because a request timed out. The default applies only when the
552
+ * settings answer and hold no value.
553
+ */
554
+ declare function readTrashRetention(caller: TrashCaller, options?: RetentionOptions): Promise<number>;
555
+ /**
556
+ * Mount the trash routes for one entity and return the handle the purge job
557
+ * (and any hand-written route) uses.
558
+ */
559
+ declare function mountTrash<D extends SettingsDefaults = SettingsDefaults>(app: App<D>, repo: RepoLike, opts: TrashOptions): TrashHandle;
560
+ /**
561
+ * Count another App's records through the gateway, for a blocker that crosses
562
+ * an App boundary ("open orders of this organization"). Apps never read each
563
+ * other's tables; the owning App's list route answers, and its `page.total` is
564
+ * the count.
565
+ *
566
+ * const refs = createGatewayCounter();
567
+ * blockers: async (org, c) => [
568
+ * await refs.blocker(c, { path: '/v1/orders/open_orders', where: { organization_id: org.id }, reason: 'open orders' }),
569
+ * ]
570
+ *
571
+ * A count the gateway does not give — an error, a timeout, a route that does
572
+ * not report `total` — is `null`, and `blocker` turns `null` into an
573
+ * `unverifiable` blocker. Not knowing is never a pass.
574
+ */
575
+ declare function createGatewayCounter(options?: {
576
+ endpoint?: string;
577
+ timeoutMs?: number;
578
+ fetchImpl?: typeof fetch;
579
+ env?: Record<string, string | undefined>;
580
+ }): {
581
+ count: (caller: TrashCaller, path: string, where?: Record<string, string | number | boolean>) => Promise<number | null>;
582
+ blocker: (caller: TrashCaller, check: {
583
+ path: string;
584
+ where?: Record<string, string | number | boolean>;
585
+ reason: string;
586
+ }) => Promise<Blocker | null>;
587
+ };
588
+
589
+ export { ACTOR_HEADERS, AUDIT_SETTINGS_PATH, type Actor, type ActorPlane, type ActorTrust, type App, type AppOptions, type Blocker, type BlockerCheck, type CrudOptions, DEFAULT_TRASH_RETENTION_DAYS, type FnContext, type FnRequest, type FnResponse, type Handler, MARKET_HEADERS, type Market, PURGE_REASON_COLUMN, type PurgeResult, RESERVED_LIST_QUERY_KEYS, ReadOptions, type RepoLike, ResolvedSettings, type RetentionOptions, type RouteContext, SettingsDefaults, SettingsOptions, SettingsReader, SettingsSnapshot, SettingsSource, TRASH_COLUMN, type TrashCaller, type TrashChild, type TrashHandle, type TrashOptions, actorFrom, auditSettingsUrl, createApp, createGatewayCounter, marketFrom, mountCrud, mountTrash, readTrashRetention };