@revenexx/app-sdk 1.3.0 → 1.5.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.
@@ -145,7 +145,7 @@ interface Adapter {
145
145
  * the two into an effective map:
146
146
  *
147
147
  * GET {gateway}/v1/settings/apps/{app}[?market={code}]
148
- * -> { app, market, settings: { … }, masked: [ … ] }
148
+ * -> { app, market, settings: { … }, masked: [ … ], stored: [ … ] }
149
149
  *
150
150
  * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.
151
151
  * Per key, the gateway applies (api/internal/gateway/settings.go,
@@ -177,6 +177,25 @@ interface Adapter {
177
177
  * Or let the router own it — `createApp({ name, settings: { defaults } })`
178
178
  * gives every handler `await c.settings()`.
179
179
  *
180
+ * ## Writing the app's OWN settings
181
+ *
182
+ * Some values have to be STORED, not merely declared — a platform service may
183
+ * refuse to act on a default it cannot tell from "nobody decided". The app can
184
+ * store them itself:
185
+ *
186
+ * const result = await settings.set(c, { locale_granularity: 'language' }, { ifAbsent: true });
187
+ * // PATCH {gateway}/v1/settings/apps/{app}
188
+ * // -> { ok, written: [...], kept: [...], ignored: [...] }
189
+ *
190
+ * The gateway lets an app write only its own settings, for the tenant its
191
+ * request belongs to: it reads the app from the platform-signed
192
+ * `x-revenexx-app-context` header the router hands every HTTP invocation, which
193
+ * this reader forwards. A run started by an event or a schedule carries none,
194
+ * so a write from there comes back `ok: false` — write from an HTTP route.
195
+ * `ifAbsent` keeps every key the tenant already stored: use it for defaults,
196
+ * so an install hook never undoes a merchant's choice. `stored` on a snapshot
197
+ * says which keys are stored rather than defaulted.
198
+ *
180
199
  * Two properties make this safe to call on every request:
181
200
  *
182
201
  * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that
@@ -278,6 +297,13 @@ interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {
278
297
  settings: ResolvedSettings<D>;
279
298
  /** Keys that exist but are `sensitive`, so their values were withheld. */
280
299
  masked: string[];
300
+ /**
301
+ * Keys whose value the tenant STORED (a tenant value, or the market's
302
+ * override), as opposed to the declared default. A stored default and an
303
+ * unset key resolve to the same value; this tells them apart. Empty on a
304
+ * fallback, and from a gateway too old to say.
305
+ */
306
+ stored: string[];
281
307
  /** true when these values came from the gateway (fresh or cached). */
282
308
  resolved: boolean;
283
309
  /** Why the fallback happened, when `resolved` is false. */
@@ -287,11 +313,36 @@ interface ReadOptions {
287
313
  /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */
288
314
  market?: string;
289
315
  }
316
+ interface WriteOptions {
317
+ /** Keep every key the tenant already stored; write only the missing ones. */
318
+ ifAbsent?: boolean;
319
+ }
320
+ /** The outcome of `set()`. Key names only — the gateway never echoes values. */
321
+ interface SettingsWriteResult {
322
+ /** true when the gateway accepted the write (even if it wrote nothing). */
323
+ ok: boolean;
324
+ /** HTTP status of the gateway's answer; 0 when it was never asked or unreachable. */
325
+ status: number;
326
+ /** Keys stored by this write. */
327
+ written: string[];
328
+ /** Keys left alone because they were already stored (`ifAbsent`). */
329
+ kept: string[];
330
+ /** Keys dropped because the app's settings.json does not declare them. */
331
+ ignored: string[];
332
+ /** Why the write did not happen, when `ok` is false. */
333
+ error?: string;
334
+ }
290
335
  interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
291
336
  /** The effective settings for this request. Never throws. */
292
337
  get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;
293
- /** The same read, plus market/masked/provenance. */
338
+ /** The same read, plus market/masked/stored/provenance. */
294
339
  load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;
340
+ /**
341
+ * Store this app's OWN tenant-level settings for the request's tenant.
342
+ * Never throws: a refusal or an unreachable gateway is `ok: false`, also
343
+ * reported to `onError`. A successful write drops the tenant's cached reads.
344
+ */
345
+ set(source: SettingsSource | undefined, values: Record<string, unknown>, options?: WriteOptions): Promise<SettingsWriteResult>;
295
346
  /** Drop the cache (tests, or right after writing settings). */
296
347
  clear(): void;
297
348
  }
@@ -301,6 +352,114 @@ interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
301
352
  */
302
353
  declare function createSettings<D extends SettingsDefaults = SettingsDefaults>(options?: SettingsOptions<D>): SettingsReader<D>;
303
354
 
355
+ /**
356
+ * Backdating — replaying history into a test tenant (RAD-311).
357
+ *
358
+ * A simulator fills a test tenant with months of orders, payments and stock
359
+ * movements. Everything an App stamps is "now", so without help the whole
360
+ * history would land on the afternoon the simulator ran. An App that opts in
361
+ * (`createApp({ backdating: true })`) lets a mutating request carry a past
362
+ * moment in its body (`at`, or a route's own field) and runs the WHOLE request
363
+ * on that clock: every `now()` the handler reads, every timestamp it writes,
364
+ * and — through `backdatingDb` — the `created_at` of every row it creates.
365
+ *
366
+ * Only for a tenant whose admin switched it on: the App setting
367
+ * `allow_backdating` (scope tenant, default off), read through `c.settings()`.
368
+ * A settings service that cannot be reached hands back the declared defaults,
369
+ * so an unreadable setting means off. The tenant has to be named twice and
370
+ * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the
371
+ * forwarded identity token (`x-revenexx-context`). The header alone is not
372
+ * enough — a caller reaching the function URL directly can set it. The claim is
373
+ * not verified here; the data plane verifies the token on every read and write,
374
+ * so a token claiming another tenant writes nothing at all.
375
+ *
376
+ * Without the gate the field is ignored, unread and unvalidated. With it the
377
+ * moment must be an ISO 8601 date-time with a zone, not in the future and not
378
+ * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code
379
+ * `backdating_invalid`.
380
+ *
381
+ * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two
382
+ * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate
383
+ * bundles, each in ESM and CJS) read one and the same clock.
384
+ */
385
+ /** How far back a backdated request may reach, in months. */
386
+ declare const MAX_MONTHS_BACK = 24;
387
+ /** The App setting that opens backdating for a tenant. */
388
+ declare const BACKDATING_SETTING = "allow_backdating";
389
+ /** The body field every backdated route accepts. Reserved in Apps that opt in. */
390
+ declare const BACKDATING_FIELD = "at";
391
+ /** The refusal code of a moment that cannot be honoured. */
392
+ declare const BACKDATING_INVALID = "backdating_invalid";
393
+ /**
394
+ * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,
395
+ * PATCH, DELETE) accept `at`; the object form does the same and refines it.
396
+ */
397
+ interface BackdatingOptions {
398
+ /**
399
+ * Per-route body fields that carry the moment, in precedence order, keyed
400
+ * `METHOD /template` exactly as the route was registered:
401
+ * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —
402
+ * appended last when the list does not name it. A route named here is
403
+ * backdatable whatever its method.
404
+ */
405
+ routes?: Record<string, readonly string[]>;
406
+ /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */
407
+ exclude?: readonly string[];
408
+ /**
409
+ * Remove the moment's fields from `c.body` before the handler runs, on a
410
+ * backdated request only. Default false: the body is left as it came. Set it
411
+ * when a handler spreads its body into a row and no table has an `at` column.
412
+ */
413
+ strip?: boolean;
414
+ }
415
+ /** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */
416
+ declare const now: () => string;
417
+ /** The request's clock as a Date, for code that does arithmetic on it. */
418
+ declare const clock: () => Date;
419
+ /** True while a backdated request (or `runAt`) is running. */
420
+ declare const backdated: () => boolean;
421
+ /**
422
+ * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the
423
+ * wall clock. Everything `fn` awaits sees the same clock. For a job outside a
424
+ * route — a replay worker — and for tests.
425
+ */
426
+ declare function runAt<T>(at: string | null | undefined, fn: () => T): T;
427
+ /**
428
+ * Check one requested moment and answer it normalized (UTC, `toISOString`).
429
+ * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601
430
+ * date-time with a zone, lies in the future, or lies more than
431
+ * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure
432
+ * against (tests).
433
+ */
434
+ declare function parseBackdate(field: string, value: unknown, reference?: Date): string;
435
+ /** What the gate reads off a request: the router's route context fits. */
436
+ interface BackdatingSource {
437
+ header?(name: string): string;
438
+ contextToken?: string;
439
+ settings?(): Promise<Record<string, unknown>>;
440
+ }
441
+ /**
442
+ * Whether this request's tenant may backdate: the tenant header and the
443
+ * identity token's `tenant_id` claim name the same tenant, and that tenant's
444
+ * `allow_backdating` setting is on. Never throws; anything unreadable is false.
445
+ */
446
+ declare function backdatingAllowed(c: BackdatingSource): Promise<boolean>;
447
+ /** The part of an entity descriptor `backdatingDb` reads: does it have the column? */
448
+ interface BackdatingEntity {
449
+ columns?: Record<string, unknown>;
450
+ }
451
+ /**
452
+ * The data client, with `created_at` (and `updated_at`, when the entity has
453
+ * it) stamped on every row a backdated request creates. Outside a backdated
454
+ * request it changes nothing: the database default stamps the row as always.
455
+ * A value the caller set is kept. Only entities whose descriptor in `entities`
456
+ * declares a `created_at` column are touched; pass the generated `ENTITIES`.
457
+ *
458
+ * const { createDb, ENTITIES } = require('./db.generated');
459
+ * const db = backdatingDb(createDb(), ENTITIES);
460
+ */
461
+ declare function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T;
462
+
304
463
  /**
305
464
  * The one error representation every layer of the SDK agrees on.
306
465
  *
@@ -367,4 +526,4 @@ interface Refusal {
367
526
  */
368
527
  declare function refusalOf(err: unknown): Refusal | null;
369
528
 
370
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type Where as W, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type Refusal as l, type ResolvedSettings as m, type SettingsDefaults as n, type SettingsOptions as o, type SettingsReader as p, type SettingsSnapshot as q, type SettingsSource as r, createSettings as s, isHttpError as t, refusalOf as u, badRequest as v, conflict as w, forbidden as x, notFound as y };
529
+ export { type Adapter as A, type BackdatingEntity as B, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, now as G, HttpError as H, parseBackdate as I, refusalOf as J, runAt as K, BACKDATING_FIELD as L, MAX_MONTHS_BACK as M, BACKDATING_INVALID as N, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, BACKDATING_SETTING as T, type BackdatingSource as U, backdatingAllowed as V, type Where as W, badRequest as X, conflict as Y, forbidden as Z, notFound as _, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, type BackdatingOptions as e, DEFAULT_SETTINGS_ERROR_TTL_MS as f, DEFAULT_SETTINGS_TIMEOUT_MS as g, DEFAULT_SETTINGS_TTL_MS as h, type EmitTarget as i, type FilterOp as j, type HttpErrorOptions as k, type ReadOptions as l, type Refusal as m, type ResolvedSettings as n, type SettingsDefaults as o, type SettingsOptions as p, type SettingsReader as q, type SettingsSnapshot as r, type SettingsSource as s, type SettingsWriteResult as t, type WriteOptions as u, backdated as v, backdatingDb as w, clock as x, createSettings as y, isHttpError as z };
@@ -145,7 +145,7 @@ interface Adapter {
145
145
  * the two into an effective map:
146
146
  *
147
147
  * GET {gateway}/v1/settings/apps/{app}[?market={code}]
148
- * -> { app, market, settings: { … }, masked: [ … ] }
148
+ * -> { app, market, settings: { … }, masked: [ … ], stored: [ … ] }
149
149
  *
150
150
  * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.
151
151
  * Per key, the gateway applies (api/internal/gateway/settings.go,
@@ -177,6 +177,25 @@ interface Adapter {
177
177
  * Or let the router own it — `createApp({ name, settings: { defaults } })`
178
178
  * gives every handler `await c.settings()`.
179
179
  *
180
+ * ## Writing the app's OWN settings
181
+ *
182
+ * Some values have to be STORED, not merely declared — a platform service may
183
+ * refuse to act on a default it cannot tell from "nobody decided". The app can
184
+ * store them itself:
185
+ *
186
+ * const result = await settings.set(c, { locale_granularity: 'language' }, { ifAbsent: true });
187
+ * // PATCH {gateway}/v1/settings/apps/{app}
188
+ * // -> { ok, written: [...], kept: [...], ignored: [...] }
189
+ *
190
+ * The gateway lets an app write only its own settings, for the tenant its
191
+ * request belongs to: it reads the app from the platform-signed
192
+ * `x-revenexx-app-context` header the router hands every HTTP invocation, which
193
+ * this reader forwards. A run started by an event or a schedule carries none,
194
+ * so a write from there comes back `ok: false` — write from an HTTP route.
195
+ * `ifAbsent` keeps every key the tenant already stored: use it for defaults,
196
+ * so an install hook never undoes a merchant's choice. `stored` on a snapshot
197
+ * says which keys are stored rather than defaulted.
198
+ *
180
199
  * Two properties make this safe to call on every request:
181
200
  *
182
201
  * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that
@@ -278,6 +297,13 @@ interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {
278
297
  settings: ResolvedSettings<D>;
279
298
  /** Keys that exist but are `sensitive`, so their values were withheld. */
280
299
  masked: string[];
300
+ /**
301
+ * Keys whose value the tenant STORED (a tenant value, or the market's
302
+ * override), as opposed to the declared default. A stored default and an
303
+ * unset key resolve to the same value; this tells them apart. Empty on a
304
+ * fallback, and from a gateway too old to say.
305
+ */
306
+ stored: string[];
281
307
  /** true when these values came from the gateway (fresh or cached). */
282
308
  resolved: boolean;
283
309
  /** Why the fallback happened, when `resolved` is false. */
@@ -287,11 +313,36 @@ interface ReadOptions {
287
313
  /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */
288
314
  market?: string;
289
315
  }
316
+ interface WriteOptions {
317
+ /** Keep every key the tenant already stored; write only the missing ones. */
318
+ ifAbsent?: boolean;
319
+ }
320
+ /** The outcome of `set()`. Key names only — the gateway never echoes values. */
321
+ interface SettingsWriteResult {
322
+ /** true when the gateway accepted the write (even if it wrote nothing). */
323
+ ok: boolean;
324
+ /** HTTP status of the gateway's answer; 0 when it was never asked or unreachable. */
325
+ status: number;
326
+ /** Keys stored by this write. */
327
+ written: string[];
328
+ /** Keys left alone because they were already stored (`ifAbsent`). */
329
+ kept: string[];
330
+ /** Keys dropped because the app's settings.json does not declare them. */
331
+ ignored: string[];
332
+ /** Why the write did not happen, when `ok` is false. */
333
+ error?: string;
334
+ }
290
335
  interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
291
336
  /** The effective settings for this request. Never throws. */
292
337
  get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;
293
- /** The same read, plus market/masked/provenance. */
338
+ /** The same read, plus market/masked/stored/provenance. */
294
339
  load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;
340
+ /**
341
+ * Store this app's OWN tenant-level settings for the request's tenant.
342
+ * Never throws: a refusal or an unreachable gateway is `ok: false`, also
343
+ * reported to `onError`. A successful write drops the tenant's cached reads.
344
+ */
345
+ set(source: SettingsSource | undefined, values: Record<string, unknown>, options?: WriteOptions): Promise<SettingsWriteResult>;
295
346
  /** Drop the cache (tests, or right after writing settings). */
296
347
  clear(): void;
297
348
  }
@@ -301,6 +352,114 @@ interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
301
352
  */
302
353
  declare function createSettings<D extends SettingsDefaults = SettingsDefaults>(options?: SettingsOptions<D>): SettingsReader<D>;
303
354
 
355
+ /**
356
+ * Backdating — replaying history into a test tenant (RAD-311).
357
+ *
358
+ * A simulator fills a test tenant with months of orders, payments and stock
359
+ * movements. Everything an App stamps is "now", so without help the whole
360
+ * history would land on the afternoon the simulator ran. An App that opts in
361
+ * (`createApp({ backdating: true })`) lets a mutating request carry a past
362
+ * moment in its body (`at`, or a route's own field) and runs the WHOLE request
363
+ * on that clock: every `now()` the handler reads, every timestamp it writes,
364
+ * and — through `backdatingDb` — the `created_at` of every row it creates.
365
+ *
366
+ * Only for a tenant whose admin switched it on: the App setting
367
+ * `allow_backdating` (scope tenant, default off), read through `c.settings()`.
368
+ * A settings service that cannot be reached hands back the declared defaults,
369
+ * so an unreadable setting means off. The tenant has to be named twice and
370
+ * agree: the `x-revenexx-tenant` header AND the `tenant_id` claim of the
371
+ * forwarded identity token (`x-revenexx-context`). The header alone is not
372
+ * enough — a caller reaching the function URL directly can set it. The claim is
373
+ * not verified here; the data plane verifies the token on every read and write,
374
+ * so a token claiming another tenant writes nothing at all.
375
+ *
376
+ * Without the gate the field is ignored, unread and unvalidated. With it the
377
+ * moment must be an ISO 8601 date-time with a zone, not in the future and not
378
+ * more than `MAX_MONTHS_BACK` months back; anything else is a 400 with code
379
+ * `backdating_invalid`.
380
+ *
381
+ * The clock lives in an AsyncLocalStorage kept on `globalThis`, so the two
382
+ * entry points (`@revenexx/app-sdk` and `@revenexx/app-sdk/router`, separate
383
+ * bundles, each in ESM and CJS) read one and the same clock.
384
+ */
385
+ /** How far back a backdated request may reach, in months. */
386
+ declare const MAX_MONTHS_BACK = 24;
387
+ /** The App setting that opens backdating for a tenant. */
388
+ declare const BACKDATING_SETTING = "allow_backdating";
389
+ /** The body field every backdated route accepts. Reserved in Apps that opt in. */
390
+ declare const BACKDATING_FIELD = "at";
391
+ /** The refusal code of a moment that cannot be honoured. */
392
+ declare const BACKDATING_INVALID = "backdating_invalid";
393
+ /**
394
+ * `createApp({ backdating })`. `true` lets every mutating route (POST, PUT,
395
+ * PATCH, DELETE) accept `at`; the object form does the same and refines it.
396
+ */
397
+ interface BackdatingOptions {
398
+ /**
399
+ * Per-route body fields that carry the moment, in precedence order, keyed
400
+ * `METHOD /template` exactly as the route was registered:
401
+ * `{ 'POST /orders/place': ['placed_at', 'at'] }`. `at` is always accepted —
402
+ * appended last when the list does not name it. A route named here is
403
+ * backdatable whatever its method.
404
+ */
405
+ routes?: Record<string, readonly string[]>;
406
+ /** Routes (`METHOD /template`) that are never backdated. Wins over `routes`. */
407
+ exclude?: readonly string[];
408
+ /**
409
+ * Remove the moment's fields from `c.body` before the handler runs, on a
410
+ * backdated request only. Default false: the body is left as it came. Set it
411
+ * when a handler spreads its body into a row and no table has an `at` column.
412
+ */
413
+ strip?: boolean;
414
+ }
415
+ /** The request's clock as an ISO string: the backdated moment while one runs, the wall clock otherwise. */
416
+ declare const now: () => string;
417
+ /** The request's clock as a Date, for code that does arithmetic on it. */
418
+ declare const clock: () => Date;
419
+ /** True while a backdated request (or `runAt`) is running. */
420
+ declare const backdated: () => boolean;
421
+ /**
422
+ * Run `fn` on the clock `at` (a normalized ISO string). `null` runs it on the
423
+ * wall clock. Everything `fn` awaits sees the same clock. For a job outside a
424
+ * route — a replay worker — and for tests.
425
+ */
426
+ declare function runAt<T>(at: string | null | undefined, fn: () => T): T;
427
+ /**
428
+ * Check one requested moment and answer it normalized (UTC, `toISOString`).
429
+ * Throws a 400 `backdating_invalid` naming `field` when it is not an ISO 8601
430
+ * date-time with a zone, lies in the future, or lies more than
431
+ * `MAX_MONTHS_BACK` months back. `reference` is the wall clock to measure
432
+ * against (tests).
433
+ */
434
+ declare function parseBackdate(field: string, value: unknown, reference?: Date): string;
435
+ /** What the gate reads off a request: the router's route context fits. */
436
+ interface BackdatingSource {
437
+ header?(name: string): string;
438
+ contextToken?: string;
439
+ settings?(): Promise<Record<string, unknown>>;
440
+ }
441
+ /**
442
+ * Whether this request's tenant may backdate: the tenant header and the
443
+ * identity token's `tenant_id` claim name the same tenant, and that tenant's
444
+ * `allow_backdating` setting is on. Never throws; anything unreadable is false.
445
+ */
446
+ declare function backdatingAllowed(c: BackdatingSource): Promise<boolean>;
447
+ /** The part of an entity descriptor `backdatingDb` reads: does it have the column? */
448
+ interface BackdatingEntity {
449
+ columns?: Record<string, unknown>;
450
+ }
451
+ /**
452
+ * The data client, with `created_at` (and `updated_at`, when the entity has
453
+ * it) stamped on every row a backdated request creates. Outside a backdated
454
+ * request it changes nothing: the database default stamps the row as always.
455
+ * A value the caller set is kept. Only entities whose descriptor in `entities`
456
+ * declares a `created_at` column are touched; pass the generated `ENTITIES`.
457
+ *
458
+ * const { createDb, ENTITIES } = require('./db.generated');
459
+ * const db = backdatingDb(createDb(), ENTITIES);
460
+ */
461
+ declare function backdatingDb<T extends object>(db: T, entities: Record<string, BackdatingEntity | undefined>): T;
462
+
304
463
  /**
305
464
  * The one error representation every layer of the SDK agrees on.
306
465
  *
@@ -367,4 +526,4 @@ interface Refusal {
367
526
  */
368
527
  declare function refusalOf(err: unknown): Refusal | null;
369
528
 
370
- export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, HttpError as H, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, type Where as W, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, DEFAULT_SETTINGS_ERROR_TTL_MS as e, DEFAULT_SETTINGS_TIMEOUT_MS as f, DEFAULT_SETTINGS_TTL_MS as g, type EmitTarget as h, type FilterOp as i, type HttpErrorOptions as j, type ReadOptions as k, type Refusal as l, type ResolvedSettings as m, type SettingsDefaults as n, type SettingsOptions as o, type SettingsReader as p, type SettingsSnapshot as q, type SettingsSource as r, createSettings as s, isHttpError as t, refusalOf as u, badRequest as v, conflict as w, forbidden as x, notFound as y };
529
+ export { type Adapter as A, type BackdatingEntity as B, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type EmitOptions as E, type Filter as F, now as G, HttpError as H, parseBackdate as I, refusalOf as J, runAt as K, BACKDATING_FIELD as L, MAX_MONTHS_BACK as M, BACKDATING_INVALID as N, type Op as O, type Page as P, type Query as Q, type Row as R, type Scalar as S, BACKDATING_SETTING as T, type BackdatingSource as U, backdatingAllowed as V, type Where as W, badRequest as X, conflict as Y, forbidden as Z, notFound as _, type EmitResult as a, type EmittedEvent as b, type EventDescriptor as c, type Entity as d, type BackdatingOptions as e, DEFAULT_SETTINGS_ERROR_TTL_MS as f, DEFAULT_SETTINGS_TIMEOUT_MS as g, DEFAULT_SETTINGS_TTL_MS as h, type EmitTarget as i, type FilterOp as j, type HttpErrorOptions as k, type ReadOptions as l, type Refusal as m, type ResolvedSettings as n, type SettingsDefaults as o, type SettingsOptions as p, type SettingsReader as q, type SettingsSnapshot as r, type SettingsSource as s, type SettingsWriteResult as t, type WriteOptions as u, backdated as v, backdatingDb as w, clock as x, createSettings as y, isHttpError as z };
package/dist/index.cjs CHANGED
@@ -26,8 +26,12 @@ __export(src_exports, {
26
26
  DEFAULT_SETTINGS_TIMEOUT_MS: () => DEFAULT_SETTINGS_TIMEOUT_MS,
27
27
  DEFAULT_SETTINGS_TTL_MS: () => DEFAULT_SETTINGS_TTL_MS,
28
28
  HttpError: () => HttpError,
29
+ MAX_MONTHS_BACK: () => MAX_MONTHS_BACK,
29
30
  adapterKinds: () => adapterKinds,
30
31
  applyDefaults: () => applyDefaults,
32
+ backdated: () => backdated,
33
+ backdatingDb: () => backdatingDb,
34
+ clock: () => clock,
31
35
  createAdapter: () => createAdapter,
32
36
  createClient: () => createClient,
33
37
  createMockAdapter: () => createMockAdapter,
@@ -36,9 +40,12 @@ __export(src_exports, {
36
40
  createSettings: () => createSettings,
37
41
  isHttpError: () => isHttpError,
38
42
  matches: () => matches,
43
+ now: () => now,
39
44
  opsFromAccess: () => opsFromAccess,
45
+ parseBackdate: () => parseBackdate,
40
46
  refusalOf: () => refusalOf,
41
47
  registerAdapter: () => registerAdapter,
48
+ runAt: () => runAt,
42
49
  toParams: () => toParams
43
50
  });
44
51
  module.exports = __toCommonJS(src_exports);
@@ -735,6 +742,9 @@ var DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
735
742
  var DEFAULT_SETTINGS_TTL_MS = 6e4;
736
743
  var DEFAULT_SETTINGS_ERROR_TTL_MS = 5e3;
737
744
  var DEFAULT_SETTINGS_TIMEOUT_MS = 2e3;
745
+ function stringList(value) {
746
+ return Array.isArray(value) ? value.filter((k) => typeof k === "string") : [];
747
+ }
738
748
  function headerOf(source, name) {
739
749
  if (!source) return "";
740
750
  if (typeof source.header === "function") {
@@ -788,6 +798,7 @@ function createSettings(options = {}) {
788
798
  market,
789
799
  settings: mergeSettings(defaults, void 0),
790
800
  masked: [],
801
+ stored: [],
791
802
  resolved: false,
792
803
  error
793
804
  });
@@ -821,10 +832,81 @@ function createSettings(options = {}) {
821
832
  tenant,
822
833
  market,
823
834
  settings: mergeSettings(defaults, body.settings),
824
- masked: Array.isArray(body.masked) ? body.masked.filter((k) => typeof k === "string") : [],
835
+ masked: stringList(body.masked),
836
+ stored: stringList(body.stored),
825
837
  resolved: true
826
838
  };
827
839
  }
840
+ const forgetTenant = (tenant, app) => {
841
+ const prefix = `${tenant}\0${app}\0`;
842
+ for (const key of [...cache.keys()]) if (key.startsWith(prefix)) cache.delete(key);
843
+ for (const key of [...lastGood.keys()]) if (key.startsWith(prefix)) lastGood.delete(key);
844
+ };
845
+ async function set(source, values, writeOptions = {}) {
846
+ const app = appName();
847
+ const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
848
+ const refused = (status, error) => ({
849
+ ok: false,
850
+ status,
851
+ written: [],
852
+ kept: [],
853
+ ignored: [],
854
+ error
855
+ });
856
+ if (!app) return refused(0, "no app name (pass `app` or set REVENEXX_APP_NAME)");
857
+ if (!tenant) return refused(0, "no tenant on the request");
858
+ const appContext = headerOf(source, "x-revenexx-app-context");
859
+ if (!appContext) {
860
+ return refused(0, "no app context on the request \u2014 settings are written from an HTTP route, not an event or schedule run");
861
+ }
862
+ if (!values || typeof values !== "object" || Array.isArray(values)) return refused(0, "values must be an object");
863
+ const f = options.fetchImpl ?? globalThis.fetch;
864
+ if (typeof f !== "function") return refused(0, "settings: no fetch available (Node >=18 or pass fetchImpl)");
865
+ const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
866
+ const headers = {
867
+ Accept: "application/json",
868
+ "Content-Type": "application/json",
869
+ "X-Revenexx-Tenant": tenant,
870
+ "X-Revenexx-App-Context": appContext
871
+ };
872
+ if (token) headers.Authorization = `Bearer ${token}`;
873
+ try {
874
+ const signal = timeoutSignal(timeoutMs);
875
+ const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}`, {
876
+ method: "PATCH",
877
+ headers,
878
+ body: JSON.stringify({ data: values, if_absent: writeOptions.ifAbsent === true }),
879
+ ...signal ? { signal } : {}
880
+ });
881
+ const text = await res.text();
882
+ let body = {};
883
+ try {
884
+ body = text ? JSON.parse(text) : {};
885
+ } catch {
886
+ body = {};
887
+ }
888
+ if (!res.ok) {
889
+ const reason = typeof body.error === "string" ? body.error : typeof body.message === "string" ? body.message : "";
890
+ const err = new Error(`settings: write ${res.status} for ${app}${reason ? ` \u2014 ${reason}` : ""}`);
891
+ err.status = res.status;
892
+ report(err, { app, tenant, market: null });
893
+ return refused(res.status, err.message);
894
+ }
895
+ const result = {
896
+ ok: true,
897
+ status: res.status,
898
+ written: stringList(body.written),
899
+ kept: stringList(body.kept),
900
+ ignored: stringList(body.ignored)
901
+ };
902
+ if (result.written.length > 0) forgetTenant(tenant, app);
903
+ return result;
904
+ } catch (err) {
905
+ const error = err instanceof Error ? err : new Error(String(err));
906
+ report(error, { app, tenant, market: null });
907
+ return refused(0, error.message);
908
+ }
909
+ }
828
910
  async function load(source, readOptions = {}) {
829
911
  const app = appName();
830
912
  const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
@@ -832,11 +914,11 @@ function createSettings(options = {}) {
832
914
  if (!app) return fallback("", tenant, market, "no app name (pass `app` or set REVENEXX_APP_NAME)");
833
915
  if (!tenant) return fallback(app, "", market, "no tenant on the request");
834
916
  const key = `${tenant}\0${app}\0${market ?? ""}`;
835
- const now = Date.now();
917
+ const now2 = Date.now();
836
918
  const hit = cache.get(key);
837
- if (hit && now - hit.at < hit.ttl) return hit.promise;
919
+ if (hit && now2 - hit.at < hit.ttl) return hit.promise;
838
920
  const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
839
- const entry = { at: now, ttl: ttlMs, promise: void 0 };
921
+ const entry = { at: now2, ttl: ttlMs, promise: void 0 };
840
922
  entry.promise = request(app, tenant, token, market).then((snapshot) => {
841
923
  lastGood.set(key, snapshot);
842
924
  return snapshot;
@@ -854,6 +936,7 @@ function createSettings(options = {}) {
854
936
  }
855
937
  return {
856
938
  load,
939
+ set,
857
940
  async get(source, readOptions) {
858
941
  return (await load(source, readOptions)).settings;
859
942
  },
@@ -863,6 +946,78 @@ function createSettings(options = {}) {
863
946
  }
864
947
  };
865
948
  }
949
+
950
+ // src/backdating.ts
951
+ var import_node_async_hooks = require("async_hooks");
952
+ var MAX_MONTHS_BACK = 24;
953
+ var BACKDATING_INVALID = "backdating_invalid";
954
+ var STORE_KEY = /* @__PURE__ */ Symbol.for("@revenexx/app-sdk/backdating-clock");
955
+ function clockStorage() {
956
+ const g = globalThis;
957
+ let storage = g[STORE_KEY];
958
+ if (!storage) {
959
+ storage = new import_node_async_hooks.AsyncLocalStorage();
960
+ g[STORE_KEY] = storage;
961
+ }
962
+ return storage;
963
+ }
964
+ var CLOCK = clockStorage();
965
+ var now = () => CLOCK.getStore()?.at ?? (/* @__PURE__ */ new Date()).toISOString();
966
+ var clock = () => new Date(now());
967
+ var backdated = () => Boolean(CLOCK.getStore()?.at);
968
+ function runAt(at, fn) {
969
+ return at ? CLOCK.run({ at }, fn) : fn();
970
+ }
971
+ var ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/;
972
+ var invalid = (field, message) => new HttpError(400, `'${field}' ${message}`, { field }, { code: BACKDATING_INVALID });
973
+ function parseBackdate(field, value, reference = /* @__PURE__ */ new Date()) {
974
+ const text = typeof value === "string" ? value.trim() : "";
975
+ if (!ISO_DATE_TIME.test(text)) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
976
+ const at = new Date(text);
977
+ if (Number.isNaN(at.getTime())) throw invalid(field, "must be an ISO 8601 date-time with a time zone");
978
+ if (at.getTime() > reference.getTime()) throw invalid(field, "must not be in the future");
979
+ const earliest = new Date(reference.getTime());
980
+ earliest.setUTCMonth(earliest.getUTCMonth() - MAX_MONTHS_BACK);
981
+ if (at.getTime() < earliest.getTime()) {
982
+ throw invalid(field, `must not be more than ${MAX_MONTHS_BACK} months back`);
983
+ }
984
+ return at.toISOString();
985
+ }
986
+ function backdatingDb(db, entities) {
987
+ const wrapped = /* @__PURE__ */ new Map();
988
+ return new Proxy(db, {
989
+ get(target, prop, receiver) {
990
+ const value = Reflect.get(target, prop, receiver);
991
+ if (typeof prop !== "string") return value;
992
+ const columns = entities?.[prop]?.columns;
993
+ if (!columns || !("created_at" in columns) || !value || typeof value !== "object") return value;
994
+ const repo = value;
995
+ if (typeof repo.create !== "function") return value;
996
+ if (!wrapped.has(prop)) {
997
+ wrapped.set(
998
+ prop,
999
+ new Proxy(repo, {
1000
+ get(r, key, rr) {
1001
+ const member = Reflect.get(r, key, rr);
1002
+ if (key !== "create" || typeof member !== "function") return member;
1003
+ return (data, ...rest) => {
1004
+ if (!backdated() || !data || typeof data !== "object" || Array.isArray(data)) {
1005
+ return member.call(r, data, ...rest);
1006
+ }
1007
+ const at = now();
1008
+ const row = { ...data };
1009
+ if (row.created_at === void 0) row.created_at = at;
1010
+ if ("updated_at" in columns && row.updated_at === void 0) row.updated_at = at;
1011
+ return member.call(r, row, ...rest);
1012
+ };
1013
+ }
1014
+ })
1015
+ );
1016
+ }
1017
+ return wrapped.get(prop);
1018
+ }
1019
+ });
1020
+ }
866
1021
  // Annotate the CommonJS export names for ESM import in node:
867
1022
  0 && (module.exports = {
868
1023
  DEFAULT_DATA_ENDPOINT,
@@ -871,8 +1026,12 @@ function createSettings(options = {}) {
871
1026
  DEFAULT_SETTINGS_TIMEOUT_MS,
872
1027
  DEFAULT_SETTINGS_TTL_MS,
873
1028
  HttpError,
1029
+ MAX_MONTHS_BACK,
874
1030
  adapterKinds,
875
1031
  applyDefaults,
1032
+ backdated,
1033
+ backdatingDb,
1034
+ clock,
876
1035
  createAdapter,
877
1036
  createClient,
878
1037
  createMockAdapter,
@@ -881,9 +1040,12 @@ function createSettings(options = {}) {
881
1040
  createSettings,
882
1041
  isHttpError,
883
1042
  matches,
1043
+ now,
884
1044
  opsFromAccess,
1045
+ parseBackdate,
885
1046
  refusalOf,
886
1047
  registerAdapter,
1048
+ runAt,
887
1049
  toParams
888
1050
  });
889
1051
  //# sourceMappingURL=index.cjs.map