@revenexx/app-sdk 0.6.0 → 0.7.1
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 +90 -0
- package/dist/chunk-2BOFXTTC.js +195 -0
- package/dist/chunk-2BOFXTTC.js.map +1 -0
- package/dist/errors-Co6JSseO.d.cts +276 -0
- package/dist/errors-Co6JSseO.d.ts +276 -0
- package/dist/index.cjs +213 -32
- 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 +41 -6
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +177 -11
- 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 +32 -7
- 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
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared runtime types. The generated per-App client (emitted by
|
|
3
|
+
* @revenexx/app-sdk-cli) layers strongly-typed entity interfaces on top of
|
|
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 };
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var src_exports = {};
|
|
22
22
|
__export(src_exports, {
|
|
23
23
|
DEFAULT_DATA_ENDPOINT: () => DEFAULT_DATA_ENDPOINT,
|
|
24
|
+
DEFAULT_GATEWAY_ENDPOINT: () => DEFAULT_GATEWAY_ENDPOINT,
|
|
25
|
+
DEFAULT_SETTINGS_ERROR_TTL_MS: () => DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
26
|
+
DEFAULT_SETTINGS_TIMEOUT_MS: () => DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
27
|
+
DEFAULT_SETTINGS_TTL_MS: () => DEFAULT_SETTINGS_TTL_MS,
|
|
24
28
|
HttpError: () => HttpError,
|
|
25
29
|
adapterKinds: () => adapterKinds,
|
|
26
30
|
applyDefaults: () => applyDefaults,
|
|
@@ -29,6 +33,7 @@ __export(src_exports, {
|
|
|
29
33
|
createMockAdapter: () => createMockAdapter,
|
|
30
34
|
createRemoteAdapter: () => createRemoteAdapter,
|
|
31
35
|
createRuntimeAdapter: () => createRuntimeAdapter,
|
|
36
|
+
createSettings: () => createSettings,
|
|
32
37
|
isHttpError: () => isHttpError,
|
|
33
38
|
matches: () => matches,
|
|
34
39
|
opsFromAccess: () => opsFromAccess,
|
|
@@ -40,6 +45,36 @@ module.exports = __toCommonJS(src_exports);
|
|
|
40
45
|
// src/adapters/mock.ts
|
|
41
46
|
var import_node_crypto = require("crypto");
|
|
42
47
|
|
|
48
|
+
// src/errors.ts
|
|
49
|
+
var HttpError = class extends Error {
|
|
50
|
+
status;
|
|
51
|
+
details;
|
|
52
|
+
code;
|
|
53
|
+
serverDetail;
|
|
54
|
+
/**
|
|
55
|
+
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
56
|
+
* bundles, so an error thrown by the data client and caught by the router is
|
|
57
|
+
* an instance of a *different* copy of this class — `instanceof` would be
|
|
58
|
+
* false. Everything checks this flag via `isHttpError` instead.
|
|
59
|
+
*/
|
|
60
|
+
__isHttpError = true;
|
|
61
|
+
constructor(status, message, details, options = {}) {
|
|
62
|
+
super(message);
|
|
63
|
+
this.name = "HttpError";
|
|
64
|
+
this.status = status;
|
|
65
|
+
if (details !== void 0) this.details = details;
|
|
66
|
+
if (options.code !== void 0) this.code = options.code;
|
|
67
|
+
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
function isHttpError(err) {
|
|
71
|
+
if (!err || typeof err !== "object") return false;
|
|
72
|
+
const e = err;
|
|
73
|
+
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
74
|
+
}
|
|
75
|
+
var notFound = (message = "not found") => new HttpError(404, message);
|
|
76
|
+
var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
|
|
77
|
+
|
|
43
78
|
// src/query.ts
|
|
44
79
|
var OPS = /* @__PURE__ */ new Set(["eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "in", "is"]);
|
|
45
80
|
function toParams(query = {}) {
|
|
@@ -173,7 +208,7 @@ function createMockAdapter(seed = {}) {
|
|
|
173
208
|
},
|
|
174
209
|
async update(entity, id, patch) {
|
|
175
210
|
const cur = tbl(entity).get(id);
|
|
176
|
-
if (!cur) throw
|
|
211
|
+
if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
|
|
177
212
|
const row = { ...cur, ...patch };
|
|
178
213
|
if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
179
214
|
tbl(entity).set(id, row);
|
|
@@ -185,34 +220,6 @@ function createMockAdapter(seed = {}) {
|
|
|
185
220
|
};
|
|
186
221
|
}
|
|
187
222
|
|
|
188
|
-
// src/errors.ts
|
|
189
|
-
var HttpError = class extends Error {
|
|
190
|
-
status;
|
|
191
|
-
details;
|
|
192
|
-
code;
|
|
193
|
-
serverDetail;
|
|
194
|
-
/**
|
|
195
|
-
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
196
|
-
* bundles, so an error thrown by the data client and caught by the router is
|
|
197
|
-
* an instance of a *different* copy of this class — `instanceof` would be
|
|
198
|
-
* false. Everything checks this flag via `isHttpError` instead.
|
|
199
|
-
*/
|
|
200
|
-
__isHttpError = true;
|
|
201
|
-
constructor(status, message, details, options = {}) {
|
|
202
|
-
super(message);
|
|
203
|
-
this.name = "HttpError";
|
|
204
|
-
this.status = status;
|
|
205
|
-
if (details !== void 0) this.details = details;
|
|
206
|
-
if (options.code !== void 0) this.code = options.code;
|
|
207
|
-
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
208
|
-
}
|
|
209
|
-
};
|
|
210
|
-
function isHttpError(err) {
|
|
211
|
-
if (!err || typeof err !== "object") return false;
|
|
212
|
-
const e = err;
|
|
213
|
-
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
214
|
-
}
|
|
215
|
-
|
|
216
223
|
// src/adapters/postgrest-error.ts
|
|
217
224
|
function parseBody(body) {
|
|
218
225
|
if (!body) return {};
|
|
@@ -326,6 +333,11 @@ function createRemoteAdapter(config) {
|
|
|
326
333
|
if (!ok) throw postgrestError(status, text, { method, table: opts.table });
|
|
327
334
|
return text ? JSON.parse(text) : null;
|
|
328
335
|
}
|
|
336
|
+
const oneRow = (rows, onMissing) => {
|
|
337
|
+
const row = Array.isArray(rows) ? rows[0] : rows;
|
|
338
|
+
if (row == null) throw onMissing();
|
|
339
|
+
return row;
|
|
340
|
+
};
|
|
329
341
|
return {
|
|
330
342
|
kind: "remote",
|
|
331
343
|
async list(entity, query = {}) {
|
|
@@ -351,7 +363,13 @@ function createRemoteAdapter(config) {
|
|
|
351
363
|
prefer: "return=representation",
|
|
352
364
|
table: entity.table
|
|
353
365
|
});
|
|
354
|
-
return
|
|
366
|
+
return oneRow(
|
|
367
|
+
rows,
|
|
368
|
+
() => new HttpError(500, "the record was created but could not be read back", void 0, {
|
|
369
|
+
code: "empty_representation",
|
|
370
|
+
serverDetail: { source: "postgrest", method: "POST", table: entity.table }
|
|
371
|
+
})
|
|
372
|
+
);
|
|
355
373
|
},
|
|
356
374
|
async update(entity, id, patch) {
|
|
357
375
|
const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
@@ -359,7 +377,7 @@ function createRemoteAdapter(config) {
|
|
|
359
377
|
prefer: "return=representation",
|
|
360
378
|
table: entity.table
|
|
361
379
|
});
|
|
362
|
-
return
|
|
380
|
+
return oneRow(rows, () => notFound());
|
|
363
381
|
},
|
|
364
382
|
async remove(entity, id) {
|
|
365
383
|
await req("DELETE", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
@@ -428,6 +446,18 @@ registerAdapter("mock", (c) => createMockAdapter(c.seed));
|
|
|
428
446
|
registerAdapter("remote", (c) => createRemoteAdapter(c));
|
|
429
447
|
registerAdapter("runtime", (c) => createRuntimeAdapter(c));
|
|
430
448
|
|
|
449
|
+
// src/patch.ts
|
|
450
|
+
var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
|
|
451
|
+
function updateFields(patch) {
|
|
452
|
+
if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
|
|
453
|
+
return Object.keys(patch).filter(
|
|
454
|
+
(key) => patch[key] !== void 0
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
function assertUpdatable(patch) {
|
|
458
|
+
if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);
|
|
459
|
+
}
|
|
460
|
+
|
|
431
461
|
// src/client.ts
|
|
432
462
|
var ACCESS_TO_OPS = {
|
|
433
463
|
read: ["list", "get"],
|
|
@@ -457,7 +487,19 @@ function entityClient(adapter, entity) {
|
|
|
457
487
|
}),
|
|
458
488
|
get: guard("get", (id) => adapter.get(entity, id)),
|
|
459
489
|
create: guard("create", (data) => adapter.create(entity, data)),
|
|
460
|
-
|
|
490
|
+
// A patch with no fields is a malformed request, not a write: PostgREST
|
|
491
|
+
// performs no update and returns no row, which used to leave the App
|
|
492
|
+
// serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
|
|
493
|
+
// rather than in `mountCrud` so every App gets it — hand-written PUT
|
|
494
|
+
// handlers that call `update()` directly were the ones that broke.
|
|
495
|
+
//
|
|
496
|
+
// `async` on purpose: a rejected promise, not a synchronous throw, so a bad
|
|
497
|
+
// patch is handled like any other data-plane failure (`await` / `.catch()`)
|
|
498
|
+
// and the declared `Promise<T>` stays honest.
|
|
499
|
+
update: guard("update", async (id, patch) => {
|
|
500
|
+
assertUpdatable(patch);
|
|
501
|
+
return adapter.update(entity, id, patch);
|
|
502
|
+
}),
|
|
461
503
|
delete: guard("delete", (id) => adapter.remove(entity, id))
|
|
462
504
|
};
|
|
463
505
|
}
|
|
@@ -470,9 +512,147 @@ function createClient(config) {
|
|
|
470
512
|
}
|
|
471
513
|
return db;
|
|
472
514
|
}
|
|
515
|
+
|
|
516
|
+
// src/settings.ts
|
|
517
|
+
var DEFAULT_GATEWAY_ENDPOINT = "https://api.revenexx.com";
|
|
518
|
+
var DEFAULT_SETTINGS_TTL_MS = 6e4;
|
|
519
|
+
var DEFAULT_SETTINGS_ERROR_TTL_MS = 5e3;
|
|
520
|
+
var DEFAULT_SETTINGS_TIMEOUT_MS = 2e3;
|
|
521
|
+
function headerOf(source, name) {
|
|
522
|
+
if (!source) return "";
|
|
523
|
+
if (typeof source.header === "function") {
|
|
524
|
+
const v = source.header(name);
|
|
525
|
+
if (typeof v === "string" && v !== "") return v;
|
|
526
|
+
}
|
|
527
|
+
const bags = [source.req?.headers, source.headers];
|
|
528
|
+
const want = name.toLowerCase();
|
|
529
|
+
for (const bag of bags) {
|
|
530
|
+
if (!bag) continue;
|
|
531
|
+
const direct = bag[name] ?? bag[want];
|
|
532
|
+
if (typeof direct === "string" && direct !== "") return direct;
|
|
533
|
+
for (const [k, v] of Object.entries(bag)) {
|
|
534
|
+
if (k.toLowerCase() === want && typeof v === "string" && v !== "") return v;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return "";
|
|
538
|
+
}
|
|
539
|
+
function mergeSettings(defaults, resolved) {
|
|
540
|
+
const out = { ...defaults ?? {} };
|
|
541
|
+
for (const [key, value] of Object.entries(resolved ?? {})) {
|
|
542
|
+
if (value !== null && value !== void 0) out[key] = value;
|
|
543
|
+
else if (!(key in out)) out[key] = value ?? null;
|
|
544
|
+
}
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
function timeoutSignal(ms) {
|
|
548
|
+
const factory = AbortSignal.timeout;
|
|
549
|
+
if (typeof factory === "function") return factory(ms);
|
|
550
|
+
if (typeof AbortController !== "function") return void 0;
|
|
551
|
+
const controller = new AbortController();
|
|
552
|
+
setTimeout(() => controller.abort(), ms).unref?.();
|
|
553
|
+
return controller.signal;
|
|
554
|
+
}
|
|
555
|
+
function createSettings(options = {}) {
|
|
556
|
+
const env = options.env ?? process.env;
|
|
557
|
+
const defaults = options.defaults;
|
|
558
|
+
const ttlMs = options.ttlMs ?? Number(env.REVENEXX_SETTINGS_TTL_MS ?? DEFAULT_SETTINGS_TTL_MS);
|
|
559
|
+
const errorTtlMs = options.errorTtlMs ?? DEFAULT_SETTINGS_ERROR_TTL_MS;
|
|
560
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_SETTINGS_TIMEOUT_MS;
|
|
561
|
+
const endpoint = String(options.endpoint || env.REVENEXX_GATEWAY_ENDPOINT || DEFAULT_GATEWAY_ENDPOINT).replace(
|
|
562
|
+
/\/+$/,
|
|
563
|
+
""
|
|
564
|
+
);
|
|
565
|
+
const cache = /* @__PURE__ */ new Map();
|
|
566
|
+
const lastGood = /* @__PURE__ */ new Map();
|
|
567
|
+
const appName = () => String(options.app || env.REVENEXX_APP_NAME || "").trim();
|
|
568
|
+
const fallback = (app, tenant, market, error) => ({
|
|
569
|
+
app,
|
|
570
|
+
tenant,
|
|
571
|
+
market,
|
|
572
|
+
settings: mergeSettings(defaults, void 0),
|
|
573
|
+
masked: [],
|
|
574
|
+
resolved: false,
|
|
575
|
+
error
|
|
576
|
+
});
|
|
577
|
+
const report = (err, info) => {
|
|
578
|
+
try {
|
|
579
|
+
options.onError?.(err, info);
|
|
580
|
+
} catch {
|
|
581
|
+
}
|
|
582
|
+
};
|
|
583
|
+
async function request(app, tenant, token, market) {
|
|
584
|
+
const f = options.fetchImpl ?? globalThis.fetch;
|
|
585
|
+
if (typeof f !== "function") throw new Error("settings: no fetch available (Node >=18 or pass fetchImpl)");
|
|
586
|
+
const qs = market ? `?market=${encodeURIComponent(market)}` : "";
|
|
587
|
+
const headers = { Accept: "application/json", "X-Revenexx-Tenant": tenant };
|
|
588
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
589
|
+
const signal = timeoutSignal(timeoutMs);
|
|
590
|
+
const res = await f(`${endpoint}/v1/settings/apps/${encodeURIComponent(app)}${qs}`, {
|
|
591
|
+
method: "GET",
|
|
592
|
+
headers,
|
|
593
|
+
...signal ? { signal } : {}
|
|
594
|
+
});
|
|
595
|
+
const text = await res.text();
|
|
596
|
+
if (!res.ok) {
|
|
597
|
+
const err = new Error(`settings: ${res.status} for ${app}`);
|
|
598
|
+
err.status = res.status;
|
|
599
|
+
throw err;
|
|
600
|
+
}
|
|
601
|
+
const body = text ? JSON.parse(text) : {};
|
|
602
|
+
return {
|
|
603
|
+
app,
|
|
604
|
+
tenant,
|
|
605
|
+
market,
|
|
606
|
+
settings: mergeSettings(defaults, body.settings),
|
|
607
|
+
masked: Array.isArray(body.masked) ? body.masked.filter((k) => typeof k === "string") : [],
|
|
608
|
+
resolved: true
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
async function load(source, readOptions = {}) {
|
|
612
|
+
const app = appName();
|
|
613
|
+
const tenant = (source?.tenant ?? "") || headerOf(source, "x-revenexx-tenant");
|
|
614
|
+
const market = (readOptions.market ?? headerOf(source, "x-revenexx-market")).trim() || null;
|
|
615
|
+
if (!app) return fallback("", tenant, market, "no app name (pass `app` or set REVENEXX_APP_NAME)");
|
|
616
|
+
if (!tenant) return fallback(app, "", market, "no tenant on the request");
|
|
617
|
+
const key = `${tenant}\0${app}\0${market ?? ""}`;
|
|
618
|
+
const now = Date.now();
|
|
619
|
+
const hit = cache.get(key);
|
|
620
|
+
if (hit && now - hit.at < hit.ttl) return hit.promise;
|
|
621
|
+
const token = (source?.contextToken ?? "") || headerOf(source, "x-revenexx-context");
|
|
622
|
+
const entry = { at: now, ttl: ttlMs, promise: void 0 };
|
|
623
|
+
entry.promise = request(app, tenant, token, market).then((snapshot) => {
|
|
624
|
+
lastGood.set(key, snapshot);
|
|
625
|
+
return snapshot;
|
|
626
|
+
}).catch((err) => {
|
|
627
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
628
|
+
const status = error.status;
|
|
629
|
+
entry.ttl = status === 404 ? ttlMs : errorTtlMs;
|
|
630
|
+
report(error, { app, tenant, market });
|
|
631
|
+
const stale = lastGood.get(key);
|
|
632
|
+
if (stale) return { ...stale, resolved: false, error: error.message };
|
|
633
|
+
return fallback(app, tenant, market, error.message);
|
|
634
|
+
});
|
|
635
|
+
cache.set(key, entry);
|
|
636
|
+
return entry.promise;
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
load,
|
|
640
|
+
async get(source, readOptions) {
|
|
641
|
+
return (await load(source, readOptions)).settings;
|
|
642
|
+
},
|
|
643
|
+
clear() {
|
|
644
|
+
cache.clear();
|
|
645
|
+
lastGood.clear();
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
}
|
|
473
649
|
// Annotate the CommonJS export names for ESM import in node:
|
|
474
650
|
0 && (module.exports = {
|
|
475
651
|
DEFAULT_DATA_ENDPOINT,
|
|
652
|
+
DEFAULT_GATEWAY_ENDPOINT,
|
|
653
|
+
DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
654
|
+
DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
655
|
+
DEFAULT_SETTINGS_TTL_MS,
|
|
476
656
|
HttpError,
|
|
477
657
|
adapterKinds,
|
|
478
658
|
applyDefaults,
|
|
@@ -481,6 +661,7 @@ function createClient(config) {
|
|
|
481
661
|
createMockAdapter,
|
|
482
662
|
createRemoteAdapter,
|
|
483
663
|
createRuntimeAdapter,
|
|
664
|
+
createSettings,
|
|
484
665
|
isHttpError,
|
|
485
666
|
matches,
|
|
486
667
|
opsFromAccess,
|