@revenexx/app-sdk 0.7.0 → 0.7.2
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 +22 -0
- package/dist/{chunk-SRCDME4M.js → chunk-2BOFXTTC.js} +16 -1
- package/dist/chunk-2BOFXTTC.js.map +1 -0
- package/dist/{errors-Co6JSseO.d.cts → errors-CeQxIhQn.d.cts} +1 -1
- package/dist/{errors-Co6JSseO.d.ts → errors-CeQxIhQn.d.ts} +1 -1
- package/dist/index.cjs +74 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +22 -6
- package/dist/index.d.ts +22 -6
- package/dist/index.js +36 -8
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +26 -3
- package/dist/router/index.cjs.map +1 -1
- package/dist/router/index.d.cts +2 -2
- package/dist/router/index.d.ts +2 -2
- package/dist/router/index.js +21 -5
- package/dist/router/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-SRCDME4M.js.map +0 -1
package/README.md
CHANGED
|
@@ -180,6 +180,28 @@ 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
|
+
### Writes always answer with a record, or an error
|
|
184
|
+
|
|
185
|
+
`create` and `update` are typed `Promise<Row>` and now keep that promise —
|
|
186
|
+
PostgREST reports a write that touched no row as `200 []`, and handing the
|
|
187
|
+
missing element back as if it were the record put an `undefined` into App code
|
|
188
|
+
that only blew up at `res.json()` time, as a 500 with a raw Node message:
|
|
189
|
+
|
|
190
|
+
| condition | answer | message |
|
|
191
|
+
|---|---|---|
|
|
192
|
+
| `update` with a patch carrying no fields | `400` | `request body must contain at least one field to update` |
|
|
193
|
+
| `update` matched no row (deleted, or invisible under RLS) | `404` | `not found` |
|
|
194
|
+
| `create` returned no representation | `500` | `the record was created but could not be read back` |
|
|
195
|
+
|
|
196
|
+
The empty-patch rule lives in the data client, not in `mountCrud`, so it holds
|
|
197
|
+
for hand-written route handlers too. It is enforced before the request leaves
|
|
198
|
+
the App — an empty patch costs no round trip.
|
|
199
|
+
|
|
200
|
+
These are `HttpError`s: `@revenexx/app-sdk/router` turns them into the response
|
|
201
|
+
automatically. An App that routes itself must honour `err.status` in its
|
|
202
|
+
catch-all (`isHttpError(err) ? err.status : 500`), or it will report a 400 as a
|
|
203
|
+
500 no matter what the SDK raises.
|
|
204
|
+
|
|
183
205
|
## App settings
|
|
184
206
|
|
|
185
207
|
An App declares the knobs a merchant may turn in `settings.json`; the Cockpit
|
|
@@ -164,6 +164,18 @@ function createSettings(options = {}) {
|
|
|
164
164
|
};
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
+
// src/patch.ts
|
|
168
|
+
var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
|
|
169
|
+
function updateFields(patch) {
|
|
170
|
+
if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
|
|
171
|
+
return Object.keys(patch).filter(
|
|
172
|
+
(key) => patch[key] !== void 0
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
function assertUpdatable(patch) {
|
|
176
|
+
if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);
|
|
177
|
+
}
|
|
178
|
+
|
|
167
179
|
export {
|
|
168
180
|
HttpError,
|
|
169
181
|
isHttpError,
|
|
@@ -171,10 +183,13 @@ export {
|
|
|
171
183
|
badRequest,
|
|
172
184
|
forbidden,
|
|
173
185
|
conflict,
|
|
186
|
+
EMPTY_UPDATE_MESSAGE,
|
|
187
|
+
updateFields,
|
|
188
|
+
assertUpdatable,
|
|
174
189
|
DEFAULT_GATEWAY_ENDPOINT,
|
|
175
190
|
DEFAULT_SETTINGS_TTL_MS,
|
|
176
191
|
DEFAULT_SETTINGS_ERROR_TTL_MS,
|
|
177
192
|
DEFAULT_SETTINGS_TIMEOUT_MS,
|
|
178
193
|
createSettings
|
|
179
194
|
};
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
195
|
+
//# sourceMappingURL=chunk-2BOFXTTC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/settings.ts","../src/patch.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","/**\n * What counts as an update.\n *\n * PostgREST answers a `PATCH` whose body carries no columns with `200 []` — no\n * error, no representation. The adapter then hands `rows[0]` (i.e. `undefined`)\n * back as the updated row, and the App serialises it: open-runtimes does\n * `Buffer.from(JSON.stringify(obj), 'utf8')`, and `JSON.stringify(undefined)`\n * is `undefined`, so Node throws\n *\n * TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string\n * or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object.\n * Received undefined\n *\n * which the App reports as a 500. A caller who sent nothing to update is told\n * the service is broken instead of what to send.\n *\n * The rule lives here, one level below the router, because not every App routes\n * its writes through `mountCrud`: `PUT /v1/greetings/{id}` and\n * `PUT /v1/payments/providers/{id}` are hand-written handlers that call\n * `db.<entity>.update()` directly, and they were the two endpoints that 500ed.\n * A guard in `mountCrud` alone only protects the Apps that happen to use it.\n */\n\nimport { badRequest } from './errors.js';\n\n/** The one wording every layer uses for \"you sent nothing to update\". */\nexport const EMPTY_UPDATE_MESSAGE = 'request body must contain at least one field to update';\n\n/**\n * The fields a patch would actually send. `undefined` values are excluded\n * because `JSON.stringify` drops them: `{ name: undefined }` reaches PostgREST\n * as `{}` and is exactly as empty as `{}` itself.\n */\nexport function updateFields(patch: unknown): string[] {\n if (!patch || typeof patch !== 'object' || Array.isArray(patch)) return [];\n return Object.keys(patch as Record<string, unknown>).filter(\n (key) => (patch as Record<string, unknown>)[key] !== undefined,\n );\n}\n\n/** Throw a 400 when a patch carries nothing to write. */\nexport function assertUpdatable(patch: unknown): void {\n if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);\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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M;AAAA,IACjB;AAAA,EACF;AACF;;;ACnUO,IAAM,uBAAuB;AAO7B,SAAS,aAAa,OAA0B;AACrD,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,QAAO,CAAC;AACzE,SAAO,OAAO,KAAK,KAAgC,EAAE;AAAA,IACnD,CAAC,QAAS,MAAkC,GAAG,MAAM;AAAA,EACvD;AACF;AAGO,SAAS,gBAAgB,OAAsB;AACpD,MAAI,aAAa,KAAK,EAAE,WAAW,EAAG,OAAM,WAAW,oBAAoB;AAC7E;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared runtime types. The generated per-App client (emitted by
|
|
3
|
-
*
|
|
3
|
+
* `revenexx apps generate`) layers strongly-typed entity interfaces on top of
|
|
4
4
|
* these loose runtime shapes.
|
|
5
5
|
*/
|
|
6
6
|
type FilterOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'in' | 'is';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Shared runtime types. The generated per-App client (emitted by
|
|
3
|
-
*
|
|
3
|
+
* `revenexx apps generate`) layers strongly-typed entity interfaces on top of
|
|
4
4
|
* these loose runtime shapes.
|
|
5
5
|
*/
|
|
6
6
|
type FilterOp = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'in' | 'is';
|
package/dist/index.cjs
CHANGED
|
@@ -45,6 +45,36 @@ module.exports = __toCommonJS(src_exports);
|
|
|
45
45
|
// src/adapters/mock.ts
|
|
46
46
|
var import_node_crypto = require("crypto");
|
|
47
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
|
+
|
|
48
78
|
// src/query.ts
|
|
49
79
|
var OPS = /* @__PURE__ */ new Set(["eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "in", "is"]);
|
|
50
80
|
function toParams(query = {}) {
|
|
@@ -178,7 +208,7 @@ function createMockAdapter(seed = {}) {
|
|
|
178
208
|
},
|
|
179
209
|
async update(entity, id, patch) {
|
|
180
210
|
const cur = tbl(entity).get(id);
|
|
181
|
-
if (!cur) throw
|
|
211
|
+
if (!cur) throw notFound(`mock: ${entity.name}/${String(id)} not found`);
|
|
182
212
|
const row = { ...cur, ...patch };
|
|
183
213
|
if (entity.columns?.updated_at) row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
184
214
|
tbl(entity).set(id, row);
|
|
@@ -190,34 +220,6 @@ function createMockAdapter(seed = {}) {
|
|
|
190
220
|
};
|
|
191
221
|
}
|
|
192
222
|
|
|
193
|
-
// src/errors.ts
|
|
194
|
-
var HttpError = class extends Error {
|
|
195
|
-
status;
|
|
196
|
-
details;
|
|
197
|
-
code;
|
|
198
|
-
serverDetail;
|
|
199
|
-
/**
|
|
200
|
-
* Structural marker. `dist/index.cjs` and `dist/router/index.cjs` are separate
|
|
201
|
-
* bundles, so an error thrown by the data client and caught by the router is
|
|
202
|
-
* an instance of a *different* copy of this class — `instanceof` would be
|
|
203
|
-
* false. Everything checks this flag via `isHttpError` instead.
|
|
204
|
-
*/
|
|
205
|
-
__isHttpError = true;
|
|
206
|
-
constructor(status, message, details, options = {}) {
|
|
207
|
-
super(message);
|
|
208
|
-
this.name = "HttpError";
|
|
209
|
-
this.status = status;
|
|
210
|
-
if (details !== void 0) this.details = details;
|
|
211
|
-
if (options.code !== void 0) this.code = options.code;
|
|
212
|
-
if (options.serverDetail !== void 0) this.serverDetail = options.serverDetail;
|
|
213
|
-
}
|
|
214
|
-
};
|
|
215
|
-
function isHttpError(err) {
|
|
216
|
-
if (!err || typeof err !== "object") return false;
|
|
217
|
-
const e = err;
|
|
218
|
-
return e.__isHttpError === true || e.name === "HttpError" && typeof e.status === "number";
|
|
219
|
-
}
|
|
220
|
-
|
|
221
223
|
// src/adapters/postgrest-error.ts
|
|
222
224
|
function parseBody(body) {
|
|
223
225
|
if (!body) return {};
|
|
@@ -331,6 +333,11 @@ function createRemoteAdapter(config) {
|
|
|
331
333
|
if (!ok) throw postgrestError(status, text, { method, table: opts.table });
|
|
332
334
|
return text ? JSON.parse(text) : null;
|
|
333
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
|
+
};
|
|
334
341
|
return {
|
|
335
342
|
kind: "remote",
|
|
336
343
|
async list(entity, query = {}) {
|
|
@@ -356,7 +363,13 @@ function createRemoteAdapter(config) {
|
|
|
356
363
|
prefer: "return=representation",
|
|
357
364
|
table: entity.table
|
|
358
365
|
});
|
|
359
|
-
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
|
+
);
|
|
360
373
|
},
|
|
361
374
|
async update(entity, id, patch) {
|
|
362
375
|
const rows = await req("PATCH", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
@@ -364,7 +377,7 @@ function createRemoteAdapter(config) {
|
|
|
364
377
|
prefer: "return=representation",
|
|
365
378
|
table: entity.table
|
|
366
379
|
});
|
|
367
|
-
return
|
|
380
|
+
return oneRow(rows, () => notFound());
|
|
368
381
|
},
|
|
369
382
|
async remove(entity, id) {
|
|
370
383
|
await req("DELETE", `/${entity.table}?${entity.pk}=eq.${encodeURIComponent(String(id))}`, {
|
|
@@ -405,8 +418,11 @@ function createRuntimeAdapter(config = {}) {
|
|
|
405
418
|
endpoint: env.REVENEXX_DATA_ENDPOINT || DEFAULT_DATA_ENDPOINT,
|
|
406
419
|
token: get("x-revenexx-context") || env.REVENEXX_CONTEXT || "",
|
|
407
420
|
tenant: get("x-revenexx-tenant") || env.REVENEXX_TENANT || "",
|
|
408
|
-
// Active market
|
|
409
|
-
//
|
|
421
|
+
// Active market forwarded to the data layer. It ASSIGNS the market on
|
|
422
|
+
// insert and filters reads only through a `*_scoped` view — generated
|
|
423
|
+
// entities read the base table, so on the app path a list is unaffected by
|
|
424
|
+
// it. See RemoteConfig.market; absent is a no-op on reads, not a narrower
|
|
425
|
+
// default.
|
|
410
426
|
market: get("x-revenexx-market") || env.REVENEXX_MARKET || ""
|
|
411
427
|
});
|
|
412
428
|
return { ...remote, kind: "runtime" };
|
|
@@ -433,6 +449,18 @@ registerAdapter("mock", (c) => createMockAdapter(c.seed));
|
|
|
433
449
|
registerAdapter("remote", (c) => createRemoteAdapter(c));
|
|
434
450
|
registerAdapter("runtime", (c) => createRuntimeAdapter(c));
|
|
435
451
|
|
|
452
|
+
// src/patch.ts
|
|
453
|
+
var EMPTY_UPDATE_MESSAGE = "request body must contain at least one field to update";
|
|
454
|
+
function updateFields(patch) {
|
|
455
|
+
if (!patch || typeof patch !== "object" || Array.isArray(patch)) return [];
|
|
456
|
+
return Object.keys(patch).filter(
|
|
457
|
+
(key) => patch[key] !== void 0
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
function assertUpdatable(patch) {
|
|
461
|
+
if (updateFields(patch).length === 0) throw badRequest(EMPTY_UPDATE_MESSAGE);
|
|
462
|
+
}
|
|
463
|
+
|
|
436
464
|
// src/client.ts
|
|
437
465
|
var ACCESS_TO_OPS = {
|
|
438
466
|
read: ["list", "get"],
|
|
@@ -462,7 +490,19 @@ function entityClient(adapter, entity) {
|
|
|
462
490
|
}),
|
|
463
491
|
get: guard("get", (id) => adapter.get(entity, id)),
|
|
464
492
|
create: guard("create", (data) => adapter.create(entity, data)),
|
|
465
|
-
|
|
493
|
+
// A patch with no fields is a malformed request, not a write: PostgREST
|
|
494
|
+
// performs no update and returns no row, which used to leave the App
|
|
495
|
+
// serialising `undefined` and answering 500 (see ./patch.ts). Rejected here
|
|
496
|
+
// rather than in `mountCrud` so every App gets it — hand-written PUT
|
|
497
|
+
// handlers that call `update()` directly were the ones that broke.
|
|
498
|
+
//
|
|
499
|
+
// `async` on purpose: a rejected promise, not a synchronous throw, so a bad
|
|
500
|
+
// patch is handled like any other data-plane failure (`await` / `.catch()`)
|
|
501
|
+
// and the declared `Promise<T>` stays honest.
|
|
502
|
+
update: guard("update", async (id, patch) => {
|
|
503
|
+
assertUpdatable(patch);
|
|
504
|
+
return adapter.update(entity, id, patch);
|
|
505
|
+
}),
|
|
466
506
|
delete: guard("delete", (id) => adapter.remove(entity, id))
|
|
467
507
|
};
|
|
468
508
|
}
|