@revenexx/app-sdk 0.6.0 → 0.7.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/README.md +68 -0
- package/dist/chunk-SRCDME4M.js +180 -0
- package/dist/chunk-SRCDME4M.js.map +1 -0
- package/dist/errors-Co6JSseO.d.cts +276 -0
- package/dist/errors-Co6JSseO.d.ts +276 -0
- package/dist/index.cjs +144 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +167 -9
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +41 -15
- package/dist/router/index.d.ts +41 -15
- package/dist/router/index.js +28 -4
- package/dist/router/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-WJ7QJ3NU.js +0 -41
- package/dist/chunk-WJ7QJ3NU.js.map +0 -1
- package/dist/errors-DrxYD96C.d.cts +0 -111
- package/dist/errors-DrxYD96C.d.ts +0 -111
package/README.md
CHANGED
|
@@ -180,6 +180,74 @@ Catching these outside the router: `import { isHttpError } from '@revenexx/app-s
|
|
|
180
180
|
Use `isHttpError(err)`, not `instanceof` — the package's two entrypoints are
|
|
181
181
|
separate bundles, so each carries its own copy of the class.
|
|
182
182
|
|
|
183
|
+
## App settings
|
|
184
|
+
|
|
185
|
+
An App declares the knobs a merchant may turn in `settings.json`; the Cockpit
|
|
186
|
+
renders them and Console stores the tenant's choices. `c.settings()` is how the
|
|
187
|
+
App reads them back at runtime:
|
|
188
|
+
|
|
189
|
+
```js
|
|
190
|
+
const app = createApp({
|
|
191
|
+
name: 'orders',
|
|
192
|
+
settings: { defaults: { auto_reserve: true, reservation_minutes: 30 } },
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
app.post('/orders', async (c) => {
|
|
196
|
+
const s = await c.settings();
|
|
197
|
+
if (s.auto_reserve) await reserve(c.body, s.reservation_minutes);
|
|
198
|
+
// …
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
`defaults` mirrors the defaults in your `settings.json`. They type the resolved
|
|
203
|
+
object and are what the App runs on if the settings service cannot be reached —
|
|
204
|
+
they never override a value the merchant actually set.
|
|
205
|
+
|
|
206
|
+
Outside a handler, build the reader yourself. Create it **once**, at module
|
|
207
|
+
scope: the cache lives on it.
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
const { createSettings } = require('@revenexx/app-sdk');
|
|
211
|
+
const settings = createSettings({ app: 'orders', defaults: { auto_reserve: true } });
|
|
212
|
+
|
|
213
|
+
const s = await settings.get(c); // c = RouteContext, FnContext or { headers }
|
|
214
|
+
const full = await settings.load(c); // { settings, masked, market, resolved }
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### Resolution
|
|
218
|
+
|
|
219
|
+
Values are resolved by the gateway (`GET /v1/settings/apps/{app}?market=`), not
|
|
220
|
+
here. Per key, highest wins:
|
|
221
|
+
|
|
222
|
+
| | source |
|
|
223
|
+
|---|---|
|
|
224
|
+
| 1 | per-market override — only for settings declared `"scope": "market"`, and only when the request carries a market |
|
|
225
|
+
| 2 | the stored tenant value |
|
|
226
|
+
| 3 | the `default` in `settings.json` |
|
|
227
|
+
| 4 | the `defaults` you passed here — the offline fallback, and only where 1–3 produced nothing |
|
|
228
|
+
|
|
229
|
+
The market comes off the request's `X-Revenexx-Market`, so a market-scoped
|
|
230
|
+
setting resolves for the market the call is for without being asked. Override
|
|
231
|
+
it per read with `c.settings({ market: 'fr' })`.
|
|
232
|
+
|
|
233
|
+
Settings declared `sensitive` are never returned; their keys are listed in
|
|
234
|
+
`masked` on `load()`, so an App can tell "not configured" from "not for you".
|
|
235
|
+
|
|
236
|
+
### Failing open, and staying cheap
|
|
237
|
+
|
|
238
|
+
A settings read sits on the hot path of every request, so it must cost nothing
|
|
239
|
+
and break nothing:
|
|
240
|
+
|
|
241
|
+
- **Fail open.** An unreachable gateway, a timeout (2s), a missing tenant, an
|
|
242
|
+
App that declares no settings — you get the last values that did resolve, or
|
|
243
|
+
your declared defaults. `settings()` never throws. Pass `onError` (wire it to
|
|
244
|
+
the function's `error()`) to keep the fallback visible.
|
|
245
|
+
- **Cache.** Per `(tenant, app, market)`, 60s by default, with concurrent reads
|
|
246
|
+
sharing one in-flight request — a warm read is a `Map` lookup. The gateway
|
|
247
|
+
keeps its own 30s cache and drops it when values change, so a Cockpit edit
|
|
248
|
+
takes effect within about a minute. Tune with `ttlMs` or
|
|
249
|
+
`REVENEXX_SETTINGS_TTL_MS`; a failed read is retried after 5s, not 60.
|
|
250
|
+
|
|
183
251
|
### Testing your App
|
|
184
252
|
|
|
185
253
|
Handlers are plain functions over a context object, so tests don't need any
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var HttpError = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
details;
|
|
5
|
+
code;
|
|
6
|
+
serverDetail;
|
|
7
|
+
/**
|
|
8
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
9
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
10
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
11
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
12
|
+
*/
|
|
13
|
+
__isHttpError = true;
|
|
14
|
+
constructor(status, message, details, options = {}) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "HttpError";
|
|
17
|
+
this.status = status;
|
|
18
|
+
if (details !== void 0) this.details = details;
|
|
19
|
+
if (options.code !== void 0) this.code = options.code;
|
|
20
|
+
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function isHttpError(err) {
|
|
24
|
+
if (!err || typeof err !== "object") return false;
|
|
25
|
+
const e = err;
|
|
26
|
+
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
27
|
+
}
|
|
28
|
+
var notFound = (message = "not found") => new HttpError(404, message);
|
|
29
|
+
var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
|
|
30
|
+
var forbidden = (message = "forbidden") => new HttpError(403, message);
|
|
31
|
+
var conflict = (message = "conflict") => new HttpError(409, message);
|
|
32
|
+
|
|
33
|
+
// src/settings.ts
|
|
34
|
+
var DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
|
|
35
|
+
var DEFAULT_SETTINGS_TTL_MS = 6e4;
|
|
36
|
+
var DEFAULT_SETTINGS_ERROR_TTL_MS = 5e3;
|
|
37
|
+
var DEFAULT_SETTINGS_TIMEOUT_MS = 2e3;
|
|
38
|
+
function headerOf(source, name) {
|
|
39
|
+
if (!source) return "";
|
|
40
|
+
if (typeof source.header === "function") {
|
|
41
|
+
const v = source.header(name);
|
|
42
|
+
if (typeof v === "string" && v !== "") return v;
|
|
43
|
+
}
|
|
44
|
+
const bags = [source.req?.headers, source.headers];
|
|
45
|
+
const want = name.toLowerCase();
|
|
46
|
+
for (const bag of bags) {
|
|
47
|
+
if (!bag) continue;
|
|
48
|
+
const direct = bag[name] ?? bag[want];
|
|
49
|
+
if (typeof direct === "string" && direct !== "") return direct;
|
|
50
|
+
for (const [k, v] of Object.entries(bag)) {
|
|
51
|
+
if (k.toLowerCase() === want && typeof v === "string" && v !== "") return v;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return "";
|
|
55
|
+
}
|
|
56
|
+
function mergeSettings(defaults, resolved) {
|
|
57
|
+
const out = { ...defaults ?? {} };
|
|
58
|
+
for (const [key, value] of Object.entries(resolved ?? {})) {
|
|
59
|
+
if (value !== null && value !== void 0) out[key] = value;
|
|
60
|
+
else if (!(key in out)) out[key] = value ?? null;
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
function timeoutSignal(ms) {
|
|
65
|
+
const factory = AbortSignal.timeout;
|
|
66
|
+
if (typeof factory === "function") return factory(ms);
|
|
67
|
+
if (typeof AbortController !== "function") return void 0;
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
setTimeout(() => controller.abort(), ms).unref?.();
|
|
70
|
+
return controller.signal;
|
|
71
|
+
}
|
|
72
|
+
function createSettings(options = {}) {
|
|
73
|
+
const env = options.env ?? process.env;
|
|
74
|
+
const defaults = options.defaults;
|
|
75
|
+
const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);
|
|
76
|
+
const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;
|
|
77
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;
|
|
78
|
+
const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(
|
|
79
|
+
/\/+$/,
|
|
80
|
+
""
|
|
81
|
+
);
|
|
82
|
+
const cache = /* @__PURE__ */ new Map();
|
|
83
|
+
const lastGood = /* @__PURE__ */ new Map();
|
|
84
|
+
const appName = () => String(options.app || env.REVENEXX_APP_NAME || "").trim();
|
|
85
|
+
const fallback = (app, tenant, market, error) => ({
|
|
86
|
+
app,
|
|
87
|
+
tenant,
|
|
88
|
+
market,
|
|
89
|
+
settings: mergeSettings(defaults, void 0),
|
|
90
|
+
masked: [],
|
|
91
|
+
resolved: false,
|
|
92
|
+
error
|
|
93
|
+
});
|
|
94
|
+
const report = (err, info) => {
|
|
95
|
+
try {
|
|
96
|
+
options.onError?.(err, info);
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
async function request(app, tenant, token, market) {
|
|
101
|
+
const f = options.fetchImpl ?? globalThis.fetch;
|
|
102
|
+
if (typeof f !== "function") throw new Error("settings: no fetch available (Node >=18 or pass fetchImpl)");
|
|
103
|
+
const qs = market ? `?market=${encodeURIComponent(market)}` : "";
|
|
104
|
+
const headers = { Accept: "application/json", "X-Revenexx-Tenant": tenant };
|
|
105
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
106
|
+
const signal = timeoutSignal(timeoutMs);
|
|
107
|
+
const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {
|
|
108
|
+
method: "GET",
|
|
109
|
+
headers,
|
|
110
|
+
...signal ? { signal } : {}
|
|
111
|
+
});
|
|
112
|
+
const text = await res.text();
|
|
113
|
+
if (!res.ok) {
|
|
114
|
+
const err = new Error(`settings: ${res.status} for ${app}`);
|
|
115
|
+
err.status = res.status;
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
const body = text ? JSON.parse(text) : {};
|
|
119
|
+
return {
|
|
120
|
+
app,
|
|
121
|
+
tenant,
|
|
122
|
+
market,
|
|
123
|
+
settings: mergeSettings(defaults, body.settings),
|
|
124
|
+
masked: Array.isArray(body.masked) ? body.masked.filter((k) => typeof k === "string") : [],
|
|
125
|
+
resolved: true
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async function load(source, readOptions = {}) {
|
|
129
|
+
const app = appName();
|
|
130
|
+
const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
|
|
131
|
+
const market = (readOptions.market ?? headerOf(source, "x-revenexx-market")).trim() || null;
|
|
132
|
+
if (!app) return fallback("", tenant, market, "no app name (pass `app` or set REVENEXX_APP_NAME)");
|
|
133
|
+
if (!tenant) return fallback(app, "", market, "no tenant on the request");
|
|
134
|
+
const key = `${tenant}\0${app}\0${market ?? ""}`;
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const hit = cache.get(key);
|
|
137
|
+
if (hit && now - hit.at < hit.ttl) return hit.promise;
|
|
138
|
+
const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
|
|
139
|
+
const entry = { at: now, ttl: ttlMs, promise: void 0 };
|
|
140
|
+
entry.promise = request(app, tenant, token, market).then((snapshot) => {
|
|
141
|
+
lastGood.set(key, snapshot);
|
|
142
|
+
return snapshot;
|
|
143
|
+
}).catch((err) => {
|
|
144
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
145
|
+
const status = error.status;
|
|
146
|
+
entry.ttl = status === 404 ? ttlMs : errorTtlMs;
|
|
147
|
+
report(error, { app, tenant, market });
|
|
148
|
+
const stale = lastGood.get(key);
|
|
149
|
+
if (stale) return { ...stale, resolved: false, error: error.message };
|
|
150
|
+
return fallback(app, tenant, market, error.message);
|
|
151
|
+
});
|
|
152
|
+
cache.set(key, entry);
|
|
153
|
+
return entry.promise;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
load,
|
|
157
|
+
async get(source, readOptions) {
|
|
158
|
+
return (await load(source, readOptions)).settings;
|
|
159
|
+
},
|
|
160
|
+
clear() {
|
|
161
|
+
cache.clear();
|
|
162
|
+
lastGood.clear();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export {
|
|
168
|
+
HttpError,
|
|
169
|
+
isHttpError,
|
|
170
|
+
notFound,
|
|
171
|
+
badRequest,
|
|
172
|
+
forbidden,
|
|
173
|
+
conflict,
|
|
174
|
+
DEFAULT_GATEWAY_ENDPOINT,
|
|
175
|
+
DEFAULT_SETTINGS_TTL_MS,
|
|
176
|
+
DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
177
|
+
DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
178
|
+
createSettings
|
|
179
|
+
};
|
|
180
|
+
//# sourceMappingURL=chunk-SRCDME4M.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/settings.ts"],"sourcesContent":["/**\n * The one error representation every layer of the SDK agrees on.\n *\n * `HttpError` used to live in `./router/router.ts`. It moved here so the data\n * adapters can raise it too: an adapter that knows a PostgREST failure is a\n * duplicate key can say \"409\" without the router having to guess from a\n * message string.\n *\n * Two fields exist purely to keep internal database detail out of responses:\n * - `message` / `details` are the *client-facing* payload — always safe,\n * never derived from a database error body.\n * - `serverDetail` is the raw diagnosis. The router logs it and drops it; it\n * is never serialised into a response.\n */\n\nexport interface HttpErrorOptions {\n /** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */\n code?: string;\n /**\n * Raw diagnosis for server-side logs and traces only — may contain table and\n * constraint names. Never included in the HTTP response.\n */\n serverDetail?: unknown;\n}\n\n/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n readonly code?: string;\n readonly serverDetail?: unknown;\n /**\n * Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate\n * bundles, so an error thrown by the data client and caught by the router is\n * an instance of a *different* copy of this class — `instanceof` would be\n * false. Everything checks this flag via `isHttpError` instead.\n */\n readonly __isHttpError = true as const;\n\n constructor(status: number, message: string, details?: unknown, options: HttpErrorOptions = {}) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n if (details !== undefined) this.details = details;\n if (options.code !== undefined) this.code = options.code;\n if (options.serverDetail !== undefined) this.serverDetail = options.serverDetail;\n }\n}\n\n/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */\nexport function isHttpError(err: unknown): err is HttpError {\n if (!err || typeof err !== 'object') return false;\n const e = err as { __isHttpError?: unknown; name?: unknown; status?: unknown };\n return e.__isHttpError === true || (e.name === 'HttpError' && typeof e.status === 'number');\n}\n\nexport const notFound = (message = 'not found'): HttpError => new HttpError(404, message);\nexport const badRequest = (message = 'bad request', details?: unknown): HttpError =>\n new HttpError(400, message, details);\nexport const forbidden = (message = 'forbidden'): HttpError => new HttpError(403, message);\nexport const conflict = (message = 'conflict'): HttpError => new HttpError(409, message);\n","/**\n * App settings — the tenant's configuration for THIS app, read at runtime.\n *\n * An App declares its settings in `settings.json` (`{ settings: { <key>:\n * { type, scope, default, sensitive, ... } } }`). The cockpit renders that\n * schema, Console stores the tenant's chosen values, and the gateway resolves\n * the two into an effective map:\n *\n * GET {gateway}/v1/settings/apps/{app}[?market={code}]\n * -> { app, market, settings: { … }, masked: [ … ] }\n *\n * Resolution happens ON THE GATEWAY, and this reader does not second-guess it.\n * Per key, the gateway applies (api/internal/gateway/settings.go,\n * `resolveSettings`):\n *\n * 1. per-market override — only for settings declared `\"scope\": \"market\"`,\n * and only when `?market=` is sent\n * 2. stored tenant value — the flat value in `settings_values`\n * 3. schema default — the `default` from settings.json\n *\n * Settings flagged `sensitive` are never in `settings`; their keys are listed\n * in `masked` so a caller can tell \"not configured\" from \"not for you\".\n *\n * The `defaults` you pass here are a *fourth*, last-resort layer: they are what\n * the app runs on when the settings service cannot be reached, and they are\n * what types the resolved object. They never override a value the gateway\n * actually resolved — only a `null`/absent one.\n *\n * const settings = createSettings({\n * app: 'orders',\n * defaults: { auto_reserve: true, reservation_minutes: 30 },\n * });\n *\n * app.post('/orders', async (c) => {\n * const s = await settings.get(c); // market taken from the request\n * if (s.auto_reserve) { … }\n * });\n *\n * Or let the router own it — `createApp({ name, settings: { defaults } })`\n * gives every handler `await c.settings()`.\n *\n * Two properties make this safe to call on every request:\n *\n * - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that\n * declares no settings at all: you get the last good values if there are\n * any, otherwise your declared defaults. It never throws and never takes\n * the app down. Availability is the default; switching something off is\n * the deliberate act, and a deliberate act must not be the accident.\n * - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent\n * reads sharing one in-flight request. A warm read is a Map lookup.\n */\n\n/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */\nexport const DEFAULT_GATEWAY_ENDPOINT = 'https://api.revenexx.com';\n\n/**\n * How long a resolved settings map stays warm in the process (ms).\n *\n * Settings are configuration, not data: a merchant flips one every few weeks.\n * The gateway keeps its own 30s cache in front of Console and drops it on a\n * NATS invalidation when values change, so this second layer is the only real\n * staleness — a cockpit change takes effect within a minute. That is the right\n * trade against the alternative, which is a gateway round trip on the hot path\n * of every single request.\n *\n * Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).\n */\nexport const DEFAULT_SETTINGS_TTL_MS = 60_000;\n\n/**\n * How long a FAILED read stays cached (ms). Short, because the failure is\n * usually transient and we want to recover quickly — but not zero, or an\n * unreachable gateway would put a doomed round trip on every request, which is\n * exactly the outage the fail-open is supposed to absorb.\n *\n * A 404 (\"app not installed or declares no settings\") is not a failure but a\n * stable answer, and is cached for the full TTL.\n */\nexport const DEFAULT_SETTINGS_ERROR_TTL_MS = 5_000;\n\n/** Request timeout (ms). A hung settings service must not hang the app. */\nexport const DEFAULT_SETTINGS_TIMEOUT_MS = 2_000;\n\nexport type SettingsDefaults = Record<string, unknown>;\n\n/**\n * The resolved map. Keys you declared in `defaults` keep their type; anything\n * else the manifest declares is still there, as `unknown`.\n */\nexport type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;\n\n/**\n * Anything a request's tenant/token/market can be read from: the router's\n * `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare\n * headers object.\n */\nexport interface SettingsSource {\n header?(name: string): string;\n tenant?: string | null;\n contextToken?: string;\n req?: { headers?: Record<string, string> | undefined } | undefined;\n headers?: Record<string, string> | undefined;\n}\n\nexport interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {\n /**\n * The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the\n * runtime sets — a deployed app usually needs no value here. `createApp`\n * passes its own `name`.\n */\n app?: string;\n /**\n * Last-resort values, and the type source. Use the same defaults your\n * settings.json declares: they are what the app runs on if the settings\n * service is unreachable.\n */\n defaults?: D;\n /** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */\n endpoint?: string;\n /** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */\n ttlMs?: number;\n /** How long a failed read is cached, in ms. Default 5_000. */\n errorTtlMs?: number;\n /** Per-request timeout in ms. Default 2_000. */\n timeoutMs?: number;\n /** Environment to read from (tests). Default `process.env`. */\n env?: Record<string, string | undefined>;\n /** Fetch implementation (tests). Default `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /**\n * Called when a read fails and the app falls back. Wire it to the function's\n * `error()` so a silent fallback is still visible. Must not throw.\n */\n onError?: (error: Error, info: { app: string; tenant: string; market: string | null }) => void;\n}\n\n/** A resolved read, with the provenance a caller occasionally needs. */\nexport interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {\n app: string;\n tenant: string;\n /** The market the values were resolved for, or null for the tenant baseline. */\n market: string | null;\n settings: ResolvedSettings<D>;\n /** Keys that exist but are `sensitive`, so their values were withheld. */\n masked: string[];\n /** true when these values came from the gateway (fresh or cached). */\n resolved: boolean;\n /** Why the fallback happened, when `resolved` is false. */\n error?: string;\n}\n\nexport interface ReadOptions {\n /** Resolve for this market instead of the one on the request. `''` = tenant baseline. */\n market?: string;\n}\n\nexport interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {\n /** The effective settings for this request. Never throws. */\n get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n /** Drop the cache (tests, or right after writing settings). */\n clear(): void;\n}\n\ninterface Entry<D extends SettingsDefaults> {\n at: number;\n ttl: number;\n promise: Promise<SettingsSnapshot<D>>;\n}\n\ninterface GatewayResponse {\n settings?: Record<string, unknown>;\n masked?: unknown;\n}\n\n/** Case-insensitive header read across the three shapes we accept. */\nfunction headerOf(source: SettingsSource | undefined, name: string): string {\n if (!source) return '';\n if (typeof source.header === 'function') {\n const v = source.header(name);\n if (typeof v === 'string' && v !== '') return v;\n }\n const bags = [source.req?.headers, source.headers];\n const want = name.toLowerCase();\n for (const bag of bags) {\n if (!bag) continue;\n const direct = bag[name] ?? bag[want];\n if (typeof direct === 'string' && direct !== '') return direct;\n for (const [k, v] of Object.entries(bag)) {\n if (k.toLowerCase() === want && typeof v === 'string' && v !== '') return v;\n }\n }\n return '';\n}\n\n/**\n * Merge the gateway's resolved map over the declared defaults.\n *\n * A `null` from the gateway does NOT clobber a default: a setting the merchant\n * never touched and whose schema carries no default resolves to `null`, and a\n * caller should not have to null-check a key it declared a default for. A real\n * stored value — including `false`, `0` and `''` — always wins.\n */\nfunction mergeSettings<D extends SettingsDefaults>(\n defaults: D | undefined,\n resolved: Record<string, unknown> | undefined,\n): ResolvedSettings<D> {\n const out: Record<string, unknown> = { ...(defaults ?? {}) };\n for (const [key, value] of Object.entries(resolved ?? {})) {\n if (value !== null && value !== undefined) out[key] = value;\n else if (!(key in out)) out[key] = value ?? null;\n }\n return out as ResolvedSettings<D>;\n}\n\nfunction timeoutSignal(ms: number): AbortSignal | undefined {\n const factory = (AbortSignal as { timeout?: (ms: number) => AbortSignal }).timeout;\n if (typeof factory === 'function') return factory(ms);\n if (typeof AbortController !== 'function') return undefined;\n const controller = new AbortController();\n setTimeout(() => controller.abort(), ms).unref?.();\n return controller.signal;\n}\n\n/**\n * Build a settings reader for one app. Create it once at module scope — the\n * cache lives on the reader, and a per-request reader would cache nothing.\n */\nexport function createSettings<D extends SettingsDefaults = SettingsDefaults>(\n options: SettingsOptions<D> = {},\n): SettingsReader<D> {\n const env = options.env ?? process.env;\n const defaults = options.defaults;\n const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);\n const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;\n const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(\n /\\/+$/,\n '',\n );\n\n const cache = new Map<string, Entry<D>>();\n /** Last successful snapshot per key — served instead of defaults on a blip. */\n const lastGood = new Map<string, SettingsSnapshot<D>>();\n\n const appName = (): string => String(options.app || env.REVENEXX_APP_NAME || '').trim();\n\n const fallback = (app: string, tenant: string, market: string | null, error: string): SettingsSnapshot<D> => ({\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, undefined),\n masked: [],\n resolved: false,\n error,\n });\n\n const report = (err: Error, info: { app: string; tenant: string; market: string | null }): void => {\n try {\n options.onError?.(err, info);\n } catch {\n /* an error reporter must never be the reason a request fails */\n }\n };\n\n async function request(app: string, tenant: string, token: string, market: string | null): Promise<SettingsSnapshot<D>> {\n const f = options.fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') throw new Error('settings: no fetch available (Node >=18 or pass fetchImpl)');\n\n const qs = market ? `?market=${encodeURIComponent(market)}` : '';\n const headers: Record<string, string> = { Accept: 'application/json', 'X-Revenexx-Tenant': tenant };\n if (token) headers.Authorization = `Bearer ${token}`;\n\n const signal = timeoutSignal(timeoutMs);\n const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {\n method: 'GET',\n headers,\n ...(signal ? { signal } : {}),\n });\n const text = await res.text();\n if (!res.ok) {\n const err = new Error(`settings: ${res.status} for ${app}`) as Error & { status?: number };\n err.status = res.status;\n throw err;\n }\n const body = (text ? JSON.parse(text) : {}) as GatewayResponse;\n return {\n app,\n tenant,\n market,\n settings: mergeSettings(defaults, body.settings),\n masked: Array.isArray(body.masked) ? body.masked.filter((k): k is string => typeof k === 'string') : [],\n resolved: true,\n };\n }\n\n async function load(source?: SettingsSource, readOptions: ReadOptions = {}): Promise<SettingsSnapshot<D>> {\n const app = appName();\n const tenant = (source?.tenant ?? '') || headerOf(source, 'x-revenexx-tenant');\n const market = (readOptions.market ?? headerOf(source, 'x-revenexx-market')).trim() || null;\n\n // Nothing to ask with — answer from the defaults without a round trip.\n if (!app) return fallback('', tenant, market, 'no app name (pass `app` or set REVENEXX_APP_NAME)');\n if (!tenant) return fallback(app, '', market, 'no tenant on the request');\n\n const key = `${tenant}\u0000${app}\u0000${market ?? ''}`;\n const now = Date.now();\n const hit = cache.get(key);\n if (hit && now - hit.at < hit.ttl) return hit.promise;\n\n const token = (source?.contextToken ?? '') || headerOf(source, 'x-revenexx-context');\n const entry: Entry<D> = { at: now, ttl: ttlMs, promise: undefined as unknown as Promise<SettingsSnapshot<D>> };\n entry.promise = request(app, tenant, token, market)\n .then((snapshot) => {\n lastGood.set(key, snapshot);\n return snapshot;\n })\n .catch((err: unknown) => {\n const error = err instanceof Error ? err : new Error(String(err));\n // A 404 is the gateway saying \"this app is not installed, or declares\n // no settings\" — a stable answer, not a blip. Cache it for the full TTL\n // so an app without settings does not re-ask every five seconds.\n const status = (error as { status?: number }).status;\n entry.ttl = status === 404 ? ttlMs : errorTtlMs;\n report(error, { app, tenant, market });\n // Prefer the last values we genuinely resolved over the defaults: they\n // are the tenant's actual configuration, and a gateway blip is no\n // reason to silently revert a merchant's choices.\n const stale = lastGood.get(key);\n if (stale) return { ...stale, resolved: false, error: error.message };\n return fallback(app, tenant, market, error.message);\n });\n\n // Cached before it settles, so concurrent requests share one fetch.\n cache.set(key, entry);\n return entry.promise;\n }\n\n return {\n load,\n async get(source?: SettingsSource, readOptions?: ReadOptions): Promise<ResolvedSettings<D>> {\n return (await load(source, readOptions)).settings;\n },\n clear(): void {\n cache.clear();\n lastGood.clear();\n },\n };\n}\n"],"mappings":";AA0BO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,gBAAgB;AAAA,EAEzB,YAAY,QAAgB,SAAiB,SAAmB,UAA4B,CAAC,GAAG;AAC9F,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,QAAI,YAAY,OAAW,MAAK,UAAU;AAC1C,QAAI,QAAQ,SAAS,OAAW,MAAK,OAAO,QAAQ;AACpD,QAAI,QAAQ,iBAAiB,OAAW,MAAK,eAAe,QAAQ;AAAA,EACtE;AACF;AAGO,SAAS,YAAY,KAAgC;AAC1D,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5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
|
|
4
|
+
* these loose runtime shapes.
|
|
5
|
+
*/
|
|
6
|
+
type FilterOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'in' | 'is';
|
|
7
|
+
type Scalar = string | number | boolean | null;
|
|
8
|
+
/** A PostgREST filter: equality, an `in` list, or an explicit operator. */
|
|
9
|
+
type Filter = Scalar | Scalar[] | {
|
|
10
|
+
op: FilterOp;
|
|
11
|
+
value: unknown;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The query object is the one interface shared by every adapter: remote/runtime
|
|
15
|
+
* serialise it to a PostgREST querystring, mock applies it in memory — so App
|
|
16
|
+
* code is identical regardless of where the data lives.
|
|
17
|
+
*/
|
|
18
|
+
interface Query<T = Record<string, unknown>> {
|
|
19
|
+
where?: Partial<Record<keyof T & string, Filter>> & Record<string, Filter>;
|
|
20
|
+
select?: (keyof T & string)[] | string[];
|
|
21
|
+
order?: string;
|
|
22
|
+
limit?: number;
|
|
23
|
+
offset?: number;
|
|
24
|
+
}
|
|
25
|
+
type Op = 'list' | 'get' | 'create' | 'update' | 'delete';
|
|
26
|
+
interface ColumnDef {
|
|
27
|
+
type: string;
|
|
28
|
+
pk?: boolean;
|
|
29
|
+
notNull?: boolean;
|
|
30
|
+
default?: string | null;
|
|
31
|
+
check?: string;
|
|
32
|
+
}
|
|
33
|
+
/** A generated entity descriptor: maps an App entity to its real table + ops. */
|
|
34
|
+
interface Entity {
|
|
35
|
+
name: string;
|
|
36
|
+
table: string;
|
|
37
|
+
pk: string;
|
|
38
|
+
columns?: Record<string, ColumnDef>;
|
|
39
|
+
ops?: Op[] | Set<Op>;
|
|
40
|
+
}
|
|
41
|
+
type Row = Record<string, unknown>;
|
|
42
|
+
/** A page of rows plus the total count of matching rows (ignoring limit/offset). */
|
|
43
|
+
interface Page<T = Row> {
|
|
44
|
+
items: T[];
|
|
45
|
+
total: number;
|
|
46
|
+
limit?: number;
|
|
47
|
+
offset?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The data-plane contract. Implement this to add a new backend (e.g. GraphQL,
|
|
51
|
+
* a local SQLite file) and register it with `registerAdapter`.
|
|
52
|
+
*
|
|
53
|
+
* `page` is optional: adapters that can report a total (PostgREST `count=exact`,
|
|
54
|
+
* an in-memory store) implement it; others fall back to `list` only.
|
|
55
|
+
*/
|
|
56
|
+
interface Adapter {
|
|
57
|
+
readonly kind: string;
|
|
58
|
+
list(entity: Entity, query?: Query): Promise<Row[]>;
|
|
59
|
+
get(entity: Entity, id: string | number): Promise<Row | null>;
|
|
60
|
+
create(entity: Entity, data: Row): Promise<Row>;
|
|
61
|
+
update(entity: Entity, id: string | number, patch: Row): Promise<Row>;
|
|
62
|
+
remove(entity: Entity, id: string | number): Promise<void>;
|
|
63
|
+
page?(entity: Entity, query?: Query): Promise<Page>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* App settings — the tenant's configuration for THIS app, read at runtime.
|
|
68
|
+
*
|
|
69
|
+
* An App declares its settings in `settings.json` (`{ settings: { <key>:
|
|
70
|
+
* { type, scope, default, sensitive, ... } } }`). The cockpit renders that
|
|
71
|
+
* schema, Console stores the tenant's chosen values, and the gateway resolves
|
|
72
|
+
* the two into an effective map:
|
|
73
|
+
*
|
|
74
|
+
* GET {gateway}/v1/settings/apps/{app}[?market={code}]
|
|
75
|
+
* -> { app, market, settings: { … }, masked: [ … ] }
|
|
76
|
+
*
|
|
77
|
+
* Resolution happens ON THE GATEWAY, and this reader does not second-guess it.
|
|
78
|
+
* Per key, the gateway applies (api/internal/gateway/settings.go,
|
|
79
|
+
* `resolveSettings`):
|
|
80
|
+
*
|
|
81
|
+
* 1. per-market override — only for settings declared `"scope": "market"`,
|
|
82
|
+
* and only when `?market=` is sent
|
|
83
|
+
* 2. stored tenant value — the flat value in `settings_values`
|
|
84
|
+
* 3. schema default — the `default` from settings.json
|
|
85
|
+
*
|
|
86
|
+
* Settings flagged `sensitive` are never in `settings`; their keys are listed
|
|
87
|
+
* in `masked` so a caller can tell "not configured" from "not for you".
|
|
88
|
+
*
|
|
89
|
+
* The `defaults` you pass here are a *fourth*, last-resort layer: they are what
|
|
90
|
+
* the app runs on when the settings service cannot be reached, and they are
|
|
91
|
+
* what types the resolved object. They never override a value the gateway
|
|
92
|
+
* actually resolved — only a `null`/absent one.
|
|
93
|
+
*
|
|
94
|
+
* const settings = createSettings({
|
|
95
|
+
* app: 'orders',
|
|
96
|
+
* defaults: { auto_reserve: true, reservation_minutes: 30 },
|
|
97
|
+
* });
|
|
98
|
+
*
|
|
99
|
+
* app.post('/orders', async (c) => {
|
|
100
|
+
* const s = await settings.get(c); // market taken from the request
|
|
101
|
+
* if (s.auto_reserve) { … }
|
|
102
|
+
* });
|
|
103
|
+
*
|
|
104
|
+
* Or let the router own it — `createApp({ name, settings: { defaults } })`
|
|
105
|
+
* gives every handler `await c.settings()`.
|
|
106
|
+
*
|
|
107
|
+
* Two properties make this safe to call on every request:
|
|
108
|
+
*
|
|
109
|
+
* - it FAILS OPEN. A gateway blip, a missing tenant, a timeout, an app that
|
|
110
|
+
* declares no settings at all: you get the last good values if there are
|
|
111
|
+
* any, otherwise your declared defaults. It never throws and never takes
|
|
112
|
+
* the app down. Availability is the default; switching something off is
|
|
113
|
+
* the deliberate act, and a deliberate act must not be the accident.
|
|
114
|
+
* - it CACHES. Per (tenant, app, market), for a short TTL, with concurrent
|
|
115
|
+
* reads sharing one in-flight request. A warm read is a Map lookup.
|
|
116
|
+
*/
|
|
117
|
+
/** The platform gateway. Override with REVENEXX_GATEWAY_ENDPOINT. */
|
|
118
|
+
declare const DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
|
|
119
|
+
/**
|
|
120
|
+
* How long a resolved settings map stays warm in the process (ms).
|
|
121
|
+
*
|
|
122
|
+
* Settings are configuration, not data: a merchant flips one every few weeks.
|
|
123
|
+
* The gateway keeps its own 30s cache in front of Console and drops it on a
|
|
124
|
+
* NATS invalidation when values change, so this second layer is the only real
|
|
125
|
+
* staleness — a cockpit change takes effect within a minute. That is the right
|
|
126
|
+
* trade against the alternative, which is a gateway round trip on the hot path
|
|
127
|
+
* of every single request.
|
|
128
|
+
*
|
|
129
|
+
* Override per reader (`ttlMs`) or per deployment (REVENEXX_SETTINGS_TTL_MS).
|
|
130
|
+
*/
|
|
131
|
+
declare const DEFAULT_SETTINGS_TTL_MS = 60000;
|
|
132
|
+
/**
|
|
133
|
+
* How long a FAILED read stays cached (ms). Short, because the failure is
|
|
134
|
+
* usually transient and we want to recover quickly — but not zero, or an
|
|
135
|
+
* unreachable gateway would put a doomed round trip on every request, which is
|
|
136
|
+
* exactly the outage the fail-open is supposed to absorb.
|
|
137
|
+
*
|
|
138
|
+
* A 404 ("app not installed or declares no settings") is not a failure but a
|
|
139
|
+
* stable answer, and is cached for the full TTL.
|
|
140
|
+
*/
|
|
141
|
+
declare const DEFAULT_SETTINGS_ERROR_TTL_MS = 5000;
|
|
142
|
+
/** Request timeout (ms). A hung settings service must not hang the app. */
|
|
143
|
+
declare const DEFAULT_SETTINGS_TIMEOUT_MS = 2000;
|
|
144
|
+
type SettingsDefaults = Record<string, unknown>;
|
|
145
|
+
/**
|
|
146
|
+
* The resolved map. Keys you declared in `defaults` keep their type; anything
|
|
147
|
+
* else the manifest declares is still there, as `unknown`.
|
|
148
|
+
*/
|
|
149
|
+
type ResolvedSettings<D extends SettingsDefaults = SettingsDefaults> = D & Record<string, unknown>;
|
|
150
|
+
/**
|
|
151
|
+
* Anything a request's tenant/token/market can be read from: the router's
|
|
152
|
+
* `RouteContext`, the raw function context (`{ req: { headers } }`), or a bare
|
|
153
|
+
* headers object.
|
|
154
|
+
*/
|
|
155
|
+
interface SettingsSource {
|
|
156
|
+
header?(name: string): string;
|
|
157
|
+
tenant?: string | null;
|
|
158
|
+
contextToken?: string;
|
|
159
|
+
req?: {
|
|
160
|
+
headers?: Record<string, string> | undefined;
|
|
161
|
+
} | undefined;
|
|
162
|
+
headers?: Record<string, string> | undefined;
|
|
163
|
+
}
|
|
164
|
+
interface SettingsOptions<D extends SettingsDefaults = SettingsDefaults> {
|
|
165
|
+
/**
|
|
166
|
+
* The app whose settings to read. Defaults to REVENEXX_APP_NAME, which the
|
|
167
|
+
* runtime sets — a deployed app usually needs no value here. `createApp`
|
|
168
|
+
* passes its own `name`.
|
|
169
|
+
*/
|
|
170
|
+
app?: string;
|
|
171
|
+
/**
|
|
172
|
+
* Last-resort values, and the type source. Use the same defaults your
|
|
173
|
+
* settings.json declares: they are what the app runs on if the settings
|
|
174
|
+
* service is unreachable.
|
|
175
|
+
*/
|
|
176
|
+
defaults?: D;
|
|
177
|
+
/** Gateway base URL. Default: REVENEXX_GATEWAY_ENDPOINT or the platform gateway. */
|
|
178
|
+
endpoint?: string;
|
|
179
|
+
/** Cache TTL in ms. Default: REVENEXX_SETTINGS_TTL_MS or 60_000. */
|
|
180
|
+
ttlMs?: number;
|
|
181
|
+
/** How long a failed read is cached, in ms. Default 5_000. */
|
|
182
|
+
errorTtlMs?: number;
|
|
183
|
+
/** Per-request timeout in ms. Default 2_000. */
|
|
184
|
+
timeoutMs?: number;
|
|
185
|
+
/** Environment to read from (tests). Default `process.env`. */
|
|
186
|
+
env?: Record<string, string | undefined>;
|
|
187
|
+
/** Fetch implementation (tests). Default `globalThis.fetch`. */
|
|
188
|
+
fetchImpl?: typeof fetch;
|
|
189
|
+
/**
|
|
190
|
+
* Called when a read fails and the app falls back. Wire it to the function's
|
|
191
|
+
* `error()` so a silent fallback is still visible. Must not throw.
|
|
192
|
+
*/
|
|
193
|
+
onError?: (error: Error, info: {
|
|
194
|
+
app: string;
|
|
195
|
+
tenant: string;
|
|
196
|
+
market: string | null;
|
|
197
|
+
}) => void;
|
|
198
|
+
}
|
|
199
|
+
/** A resolved read, with the provenance a caller occasionally needs. */
|
|
200
|
+
interface SettingsSnapshot<D extends SettingsDefaults = SettingsDefaults> {
|
|
201
|
+
app: string;
|
|
202
|
+
tenant: string;
|
|
203
|
+
/** The market the values were resolved for, or null for the tenant baseline. */
|
|
204
|
+
market: string | null;
|
|
205
|
+
settings: ResolvedSettings<D>;
|
|
206
|
+
/** Keys that exist but are `sensitive`, so their values were withheld. */
|
|
207
|
+
masked: string[];
|
|
208
|
+
/** true when these values came from the gateway (fresh or cached). */
|
|
209
|
+
resolved: boolean;
|
|
210
|
+
/** Why the fallback happened, when `resolved` is false. */
|
|
211
|
+
error?: string;
|
|
212
|
+
}
|
|
213
|
+
interface ReadOptions {
|
|
214
|
+
/** Resolve for this market instead of the one on the request. `''` = tenant baseline. */
|
|
215
|
+
market?: string;
|
|
216
|
+
}
|
|
217
|
+
interface SettingsReader<D extends SettingsDefaults = SettingsDefaults> {
|
|
218
|
+
/** The effective settings for this request. Never throws. */
|
|
219
|
+
get(source?: SettingsSource, options?: ReadOptions): Promise<ResolvedSettings<D>>;
|
|
220
|
+
/** The same read, plus market/masked/provenance. */
|
|
221
|
+
load(source?: SettingsSource, options?: ReadOptions): Promise<SettingsSnapshot<D>>;
|
|
222
|
+
/** Drop the cache (tests, or right after writing settings). */
|
|
223
|
+
clear(): void;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Build a settings reader for one app. Create it once at module scope — the
|
|
227
|
+
* cache lives on the reader, and a per-request reader would cache nothing.
|
|
228
|
+
*/
|
|
229
|
+
declare function createSettings<D extends SettingsDefaults = SettingsDefaults>(options?: SettingsOptions<D>): SettingsReader<D>;
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The one error representation every layer of the SDK agrees on.
|
|
233
|
+
*
|
|
234
|
+
* `HttpError` used to live in `./router/router.ts`. It moved here so the data
|
|
235
|
+
* adapters can raise it too: an adapter that knows a PostgREST failure is a
|
|
236
|
+
* duplicate key can say "409" without the router having to guess from a
|
|
237
|
+
* message string.
|
|
238
|
+
*
|
|
239
|
+
* Two fields exist purely to keep internal database detail out of responses:
|
|
240
|
+
* - `message` / `details` are the *client-facing* payload — always safe,
|
|
241
|
+
* never derived from a database error body.
|
|
242
|
+
* - `serverDetail` is the raw diagnosis. The router logs it and drops it; it
|
|
243
|
+
* is never serialised into a response.
|
|
244
|
+
*/
|
|
245
|
+
interface HttpErrorOptions {
|
|
246
|
+
/** Stable machine-readable code (e.g. `unique_violation`). Safe to expose. */
|
|
247
|
+
code?: string;
|
|
248
|
+
/**
|
|
249
|
+
* Raw diagnosis for server-side logs and traces only — may contain table and
|
|
250
|
+
* constraint names. Never included in the HTTP response.
|
|
251
|
+
*/
|
|
252
|
+
serverDetail?: unknown;
|
|
253
|
+
}
|
|
254
|
+
/** Throw inside a handler (or an adapter) to answer with a specific HTTP status. */
|
|
255
|
+
declare class HttpError extends Error {
|
|
256
|
+
readonly status: number;
|
|
257
|
+
readonly details?: unknown;
|
|
258
|
+
readonly code?: string;
|
|
259
|
+
readonly serverDetail?: unknown;
|
|
260
|
+
/**
|
|
261
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
262
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
263
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
264
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
265
|
+
*/
|
|
266
|
+
readonly __isHttpError: true;
|
|
267
|
+
constructor(status: number, message: string, details?: unknown, options?: HttpErrorOptions);
|
|
268
|
+
}
|
|
269
|
+
/** Duck-typed `instanceof HttpError` — survives the bundle split (see above). */
|
|
270
|
+
declare function isHttpError(err: unknown): err is HttpError;
|
|
271
|
+
declare const notFound: (message?: string) => HttpError;
|
|
272
|
+
declare const badRequest: (message?: string, details?: unknown) => HttpError;
|
|
273
|
+
declare const forbidden: (message?: string) => HttpError;
|
|
274
|
+
declare const conflict: (message?: string) => HttpError;
|
|
275
|
+
|
|
276
|
+
export { type Adapter as A, type ColumnDef as C, DEFAULT_GATEWAY_ENDPOINT as D, type Entity 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, DEFAULT_SETTINGS_ERROR_TTL_MS as a, DEFAULT_SETTINGS_TIMEOUT_MS as b, DEFAULT_SETTINGS_TTL_MS as c, type FilterOp as d, type HttpErrorOptions as e, type ReadOptions as f, type ResolvedSettings as g, type SettingsDefaults as h, type SettingsOptions as i, type SettingsReader as j, type SettingsSnapshot as k, type SettingsSource as l, createSettings as m, isHttpError as n, badRequest as o, conflict as p, forbidden as q, notFound as r };
|