@revenexx/app-sdk 0.7.1 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { h as SettingsDefaults, f as ReadOptions, g as ResolvedSettings, k as SettingsSnapshot, j as SettingsReader, i as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-Co6JSseO.js';
2
- export { D as DEFAULT_GATEWAY_ENDPOINT, a as DEFAULT_SETTINGS_ERROR_TTL_MS, b as DEFAULT_SETTINGS_TIMEOUT_MS, c as DEFAULT_SETTINGS_TTL_MS, H as HttpError, e as HttpErrorOptions, l as SettingsSource, o as badRequest, p as conflict, m as createSettings, q as forbidden, n as isHttpError, r as notFound } from '../errors-Co6JSseO.js';
1
+ import { h as SettingsDefaults, f as ReadOptions, g as ResolvedSettings, k as SettingsSnapshot, j as SettingsReader, i as SettingsOptions, Q as Query, R as Row, P as Page } from '../errors-CeQxIhQn.js';
2
+ export { D as DEFAULT_GATEWAY_ENDPOINT, a as DEFAULT_SETTINGS_ERROR_TTL_MS, b as DEFAULT_SETTINGS_TIMEOUT_MS, c as DEFAULT_SETTINGS_TTL_MS, H as HttpError, e as HttpErrorOptions, l as SettingsSource, o as badRequest, p as conflict, m as createSettings, q as forbidden, n as isHttpError, r as notFound } from '../errors-CeQxIhQn.js';
3
3
 
4
4
  /**
5
5
  * Minimal HTTP router for revenexx App functions.
@@ -254,6 +254,19 @@ var INT = (v, d) => {
254
254
  const n = parseInt(String(v), 10);
255
255
  return Number.isFinite(n) ? n : d;
256
256
  };
257
+ var isJsonColumn = (def) => /^jsonb?\b/i.test(String(def?.type ?? ""));
258
+ function assertJsonFilter(column, value) {
259
+ try {
260
+ JSON.parse(value);
261
+ } catch {
262
+ throw new HttpError(
263
+ 400,
264
+ `filter '${column}' must be a whole JSON document, serialized exactly as stored and compared for equality \u2014 not a path or containment query. This parameter's example in the API contract shows the shape this column holds.`,
265
+ void 0,
266
+ { code: "invalid_value" }
267
+ );
268
+ }
269
+ }
257
270
  function parentWhere(c, parent) {
258
271
  if (!parent) return {};
259
272
  const value = c.params[parent.param];
@@ -288,7 +301,9 @@ function mountCrud(app, repo, opts) {
288
301
  await assertParentExists(c, opts.parent);
289
302
  const where = {};
290
303
  for (const [k, v] of Object.entries(c.query)) {
291
- if (opts.columns && k in opts.columns) where[k] = v;
304
+ if (!opts.columns || !(k in opts.columns)) continue;
305
+ if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);
306
+ where[k] = v;
292
307
  }
293
308
  Object.assign(where, parentWhere(c, opts.parent));
294
309
  const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/router/router.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { createSettings } from '../settings.js';\nimport type {\n ReadOptions,\n ResolvedSettings,\n SettingsDefaults,\n SettingsOptions,\n SettingsReader,\n SettingsSnapshot,\n} from '../settings.js';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n /**\n * This tenant's effective settings for the app, resolved for the request's\n * market. Cached and fail-open — see `createSettings`. Available on every\n * app; pass `settings` to `createApp` to declare defaults and get them typed.\n */\n settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n}\n\nexport type Handler<D extends SettingsDefaults = SettingsDefaults> = (\n c: RouteContext<D>,\n) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute<D extends SettingsDefaults> {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler<D>;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n // The runtime hands `req.query` through UNDECODED — measured in production\n // against every one of the 13 apps after 0.6.0 shipped:\n //\n // GET /v1/customers/organizations?name=ACME%20GmbH\n // -> returned 0, filter {\"name\":\"ACME%20GmbH\"} (the row 'ACME GmbH' exists)\n //\n // 0.6.0 only decoded when the query rode on `req.path`, which this runtime\n // does not do, so the fix was inert. Decode here as well; each source is\n // still decoded exactly once, because the branch above returns.\n for (const [k, v] of Object.entries(req.query ?? {})) {\n const raw = typeof v === 'string' ? v : v == null ? null : String(v);\n if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);\n }\n return out;\n}\n\n/**\n * Percent-decode one query key or value, treating `+` as a space the way a\n * form-encoded query requires.\n *\n * Falls back to the input when it is not valid percent-encoding — a lone `%`\n * is a legitimate character in a search term, and throwing a URIError on it\n * would turn a harmless filter into a 500.\n */\nfunction decodeComponent(value: string): string {\n try {\n return decodeURIComponent(value.replace(/\\+/g, ' '));\n } catch {\n return value;\n }\n}\n\nexport interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n /**\n * App settings behind `c.settings()`. Pass the defaults your settings.json\n * declares — they type the resolved object and are what the app runs on if\n * the settings service is unreachable:\n *\n * createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })\n *\n * `app` defaults to this app's `name`. Pass a reader built with\n * `createSettings` instead when you want to share it with code outside the\n * router. Omit entirely and `c.settings()` still works — it just has no\n * declared defaults to fall back on.\n */\n settings?: Omit<SettingsOptions<D>, 'app'> & { app?: string } | SettingsReader<D>;\n}\n\nexport interface App<D extends SettingsDefaults = SettingsDefaults> {\n get(template: string, handler: Handler<D>): App<D>;\n post(template: string, handler: Handler<D>): App<D>;\n put(template: string, handler: Handler<D>): App<D>;\n patch(template: string, handler: Handler<D>): App<D>;\n delete(template: string, handler: Handler<D>): App<D>;\n on(method: string, template: string, handler: Handler<D>): App<D>;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** The settings reader backing `c.settings()` (e.g. to clear its cache). */\n settings: SettingsReader<D>;\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst isSettingsReader = <D extends SettingsDefaults>(\n value: NonNullable<AppOptions<D>['settings']>,\n): value is SettingsReader<D> => typeof (value as SettingsReader<D>).get === 'function';\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp<D extends SettingsDefaults = SettingsDefaults>(options: AppOptions<D> = {}): App<D> {\n const routes: CompiledRoute<D>[] = [];\n const health = options.health !== false;\n // The app knows its own name, so the settings reader does not have to be told\n // it. One reader per app, created once: the cache lives on it.\n const settings: SettingsReader<D> =\n options.settings && isSettingsReader(options.settings)\n ? options.settings\n : createSettings<D>({ app: options.name, ...(options.settings ?? {}) });\n\n const app: App<D> = {\n settings,\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute<D>; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext<D> = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n // The market rides on the request, so a market-scoped setting\n // resolves for the market this call is for — no argument needed.\n settings: (readOptions) => settings.get(c, readOptions),\n settingsSnapshot: (readOptions) => settings.load(c, readOptions),\n };\n\n return await matched.route.handler(c);\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\nimport { EMPTY_UPDATE_MESSAGE, updateFields } from '../patch.js';\nimport type { SettingsDefaults } from '../settings.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`);\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: CrudOptions,\n): App<D> {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n if (opts.columns && k in opts.columns) where[k] = v;\n }\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. The rule itself\n // lives in ../patch.ts and is enforced by the data client, so Apps that\n // hand-write their PUT handler get it too; this check stays because it is\n // the only one that can see the *body* rather than the merged patch —\n // with a nested parent the merge always carries the FK, so the patch is\n // never literally empty — and because it answers without a round trip.\n if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE);\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAmGP,IAAM,YAAY,CAAC,SAA2B,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAE5E,SAAS,gBAAgB,UAA6B;AACpD,SAAO,UAAU,QAAQ,EAAE,IAAI,CAAC,QAAQ;AACtC,UAAM,SAAS,iCAAiC,KAAK,GAAG;AACxD,QAAI,OAAQ,QAAO,EAAE,OAAO,OAAO,CAAC,EAAE;AACtC,QAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,EAAG,QAAO,EAAE,OAAO,IAAI,MAAM,CAAC,EAAE;AACxE,WAAO,EAAE,KAAK,IAAI;AAAA,EACpB,CAAC;AACH;AAEA,SAAS,cAAc,UAAqB,SAAkD;AAC5F,MAAI,SAAS,WAAW,QAAQ,OAAQ,QAAO;AAC/C,QAAM,SAAiC,C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C,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAC7C,YAAM,KAAK,OAAO,EAAE;AACpB,aAAO,EAAE,KAAK,EAAE,SAAS,MAAM,GAAG,CAAC;AAAA,IACrC,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["items"]}
1
+ {"version":3,"sources":["../../src/router/router.ts","../../src/router/crud.ts"],"sourcesContent":["/**\n * Minimal HTTP router for revenexx App functions.\n *\n * App functions receive a single invocation context ({ req, res, log, error })\n * and are expected to answer every route the App's manifest declares. This\n * router turns that into declarative, testable handlers:\n *\n * const app = createApp({ name: 'markets' });\n * app.get('/markets', (c) => c.json({ items: [] }));\n * app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));\n * module.exports = app.handler();\n *\n * Matching is literal-first: `/markets/locales` always wins over\n * `/markets/{id}` regardless of registration order. Path templates use the\n * same `{param}` syntax as manifest capability routes (`:param` also works).\n */\n\nimport {\n trace,\n context as otelContext,\n propagation,\n SpanKind,\n SpanStatusCode,\n type Span,\n type TextMapGetter,\n} from '@opentelemetry/api';\nimport { createSettings } from '../settings.js';\nimport type {\n ReadOptions,\n ResolvedSettings,\n SettingsDefaults,\n SettingsOptions,\n SettingsReader,\n SettingsSnapshot,\n} from '../settings.js';\n\nexport interface FnRequest {\n method?: string;\n path?: string;\n url?: string;\n headers?: Record<string, string>;\n query?: Record<string, unknown>;\n body?: unknown;\n bodyText?: string;\n bodyRaw?: string;\n}\n\nexport interface FnResponse {\n json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;\n send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;\n}\n\n/** The invocation context an App function receives from the runtime. */\nexport interface FnContext {\n req: FnRequest;\n res: FnResponse;\n log?: (message: string) => void;\n error?: (message: string) => void;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteContext<D extends SettingsDefaults = SettingsDefaults> {\n /** Raw invocation context (escape hatch). */\n ctx: FnContext;\n req: FnRequest;\n method: string;\n /** Normalised path (no trailing slash, no query string). */\n path: string;\n /** Path parameters from the matched route template (e.g. `{id}`). */\n params: Record<string, string>;\n /** Query string parameters (string values). */\n query: Record<string, string>;\n /** Parsed JSON body, or `{}` when absent/unparsable. */\n body: Record<string, unknown>;\n /** Tenant slug from the `x-revenexx-tenant` header (or token claim). */\n tenant: string | null;\n /** The forwarded identity token (`x-revenexx-context`), if present. */\n contextToken: string;\n /** Case-insensitive header lookup. */\n header(name: string): string;\n log(message: string): void;\n /** Respond with JSON. Returning `c.json(...)` ends the request. */\n json(data: unknown, statusCode?: number): unknown;\n /**\n * This tenant's effective settings for the app, resolved for the request's\n * market. Cached and fail-open — see `createSettings`. Available on every\n * app; pass `settings` to `createApp` to declare defaults and get them typed.\n */\n settings(options?: ReadOptions): Promise<ResolvedSettings<D>>;\n /** The same read, plus market/masked/provenance. */\n settingsSnapshot(options?: ReadOptions): Promise<SettingsSnapshot<D>>;\n}\n\nexport type Handler<D extends SettingsDefaults = SettingsDefaults> = (\n c: RouteContext<D>,\n) => unknown | Promise<unknown>;\n\n// `HttpError` lives in ../errors.js so the data adapters can raise it too — a\n// PostgREST unique violation answers 409 without the router guessing from a\n// message string. Re-exported here so `@revenexx/app-sdk/router` is unchanged.\nexport {\n HttpError,\n isHttpError,\n notFound,\n badRequest,\n forbidden,\n conflict,\n type HttpErrorOptions,\n} from '../errors.js';\nimport { isHttpError } from '../errors.js';\n\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute<D extends SettingsDefaults> {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler<D>;\n}\n\nconst splitPath = (path: string): string[] => path.split('/').filter(Boolean);\n\nfunction compileTemplate(template: string): Segment[] {\n return splitPath(template).map((seg) => {\n const braced = /^\\{([A-Za-z_][A-Za-z0-9_]*)\\}$/.exec(seg);\n if (braced) return { param: braced[1] };\n if (seg.startsWith(':') && seg.length > 1) return { param: seg.slice(1) };\n return { lit: seg };\n });\n}\n\nfunction matchSegments(segments: Segment[], reqSegs: string[]): Record<string, string> | null {\n if (segments.length !== reqSegs.length) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < segments.length; i++) {\n const s = segments[i]!;\n if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]!);\n else if (s.lit !== reqSegs[i]) return null;\n }\n return params;\n}\n\nfunction headerOf(headers: Record<string, string> | undefined, name: string): string {\n if (!headers) return '';\n const direct = headers[name] ?? headers[name.toLowerCase()];\n if (typeof direct === 'string') return direct;\n const want = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === want && typeof v === 'string') return v;\n }\n return '';\n}\n\nfunction decodeClaims(token: string): Record<string, unknown> {\n if (!token || token.split('.').length < 2) return {};\n try {\n const payload = token.split('.')[1]!.replace(/-/g, '+').replace(/_/g, '/');\n const parsed: unknown = JSON.parse(Buffer.from(payload, 'base64').toString('utf8'));\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nfunction parseBody(req: FnRequest): Record<string, unknown> {\n const candidate = req.body ?? req.bodyText ?? req.bodyRaw;\n if (candidate == null || candidate === '') return {};\n if (typeof candidate === 'object') return candidate as Record<string, unknown>;\n if (typeof candidate === 'string') {\n try {\n const parsed: unknown = JSON.parse(candidate);\n return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n }\n return {};\n}\n\n/**\n * Request query, percent-DECODED exactly once.\n *\n * `req.path` carries the query string verbatim as the gateway forwarded it, so\n * it is the authoritative source: `URLSearchParams` decodes it once, correctly,\n * and treats `+` as a space the way a form-encoded query requires.\n *\n * The runtime's own `req.query` hands values through *undecoded*. A filter of\n * `?code=m%61in` arrived as the literal `m%61in` and matched nothing, when per\n * RFC 3986 it simply means `main`. That broke every filter value needing an\n * escape — spaces, `&`, `+`, `/`, commas, anything non-ASCII — so \"Müller & Co\"\n * could not be filtered for at all. It also let the gateway's response cache\n * merge two spellings the app answered differently (revenexx/api#32).\n *\n * `req.query` stays the fallback for callers that populate it without a query\n * string on the path (the mock adapter and direct unit tests do this). Decoding\n * that again here would be wrong — a double decode turns `%2520` into a space —\n * so each source is decoded by exactly one owner.\n */\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n const rawPath = String(req.path ?? '');\n const qmark = rawPath.indexOf('?');\n if (qmark >= 0) {\n for (const [k, v] of new URLSearchParams(rawPath.slice(qmark + 1))) out[k] = v;\n return out;\n }\n // The runtime hands `req.query` through UNDECODED — measured in production\n // against every one of the 13 apps after 0.6.0 shipped:\n //\n // GET /v1/customers/organizations?name=ACME%20GmbH\n // -> returned 0, filter {\"name\":\"ACME%20GmbH\"} (the row 'ACME GmbH' exists)\n //\n // 0.6.0 only decoded when the query rode on `req.path`, which this runtime\n // does not do, so the fix was inert. Decode here as well; each source is\n // still decoded exactly once, because the branch above returns.\n for (const [k, v] of Object.entries(req.query ?? {})) {\n const raw = typeof v === 'string' ? v : v == null ? null : String(v);\n if (raw !== null) out[decodeComponent(k)] = decodeComponent(raw);\n }\n return out;\n}\n\n/**\n * Percent-decode one query key or value, treating `+` as a space the way a\n * form-encoded query requires.\n *\n * Falls back to the input when it is not valid percent-encoding — a lone `%`\n * is a legitimate character in a search term, and throwing a URIError on it\n * would turn a harmless filter into a 500.\n */\nfunction decodeComponent(value: string): string {\n try {\n return decodeURIComponent(value.replace(/\\+/g, ' '));\n } catch {\n return value;\n }\n}\n\nexport interface AppOptions<D extends SettingsDefaults = SettingsDefaults> {\n /** App name reported on the built-in health route. */\n name?: string;\n /**\n * Built-in `GET /` health route (default true). Responds with the app\n * identity (from the runtime env), status and the registered routes.\n */\n health?: boolean;\n /** Extra payload merged into the health response. */\n healthExtra?: () => Record<string, unknown>;\n /**\n * App settings behind `c.settings()`. Pass the defaults your settings.json\n * declares — they type the resolved object and are what the app runs on if\n * the settings service is unreachable:\n *\n * createApp({ name: 'orders', settings: { defaults: { auto_reserve: true } } })\n *\n * `app` defaults to this app's `name`. Pass a reader built with\n * `createSettings` instead when you want to share it with code outside the\n * router. Omit entirely and `c.settings()` still works — it just has no\n * declared defaults to fall back on.\n */\n settings?: Omit<SettingsOptions<D>, 'app'> & { app?: string } | SettingsReader<D>;\n}\n\nexport interface App<D extends SettingsDefaults = SettingsDefaults> {\n get(template: string, handler: Handler<D>): App<D>;\n post(template: string, handler: Handler<D>): App<D>;\n put(template: string, handler: Handler<D>): App<D>;\n patch(template: string, handler: Handler<D>): App<D>;\n delete(template: string, handler: Handler<D>): App<D>;\n on(method: string, template: string, handler: Handler<D>): App<D>;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** The settings reader backing `c.settings()` (e.g. to clear its cache). */\n settings: SettingsReader<D>;\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nconst isSettingsReader = <D extends SettingsDefaults>(\n value: NonNullable<AppOptions<D>['settings']>,\n): value is SettingsReader<D> => typeof (value as SettingsReader<D>).get === 'function';\n\nconst tracer = trace.getTracer('@revenexx/app-sdk');\n\n/** Case-insensitive W3C trace-context extraction from the function's headers. */\nconst headerGetter: TextMapGetter<Record<string, string>> = {\n keys: (carrier) => Object.keys(carrier ?? {}),\n get: (carrier, key) => headerOf(carrier, key) || undefined,\n};\n\nexport function createApp<D extends SettingsDefaults = SettingsDefaults>(options: AppOptions<D> = {}): App<D> {\n const routes: CompiledRoute<D>[] = [];\n const health = options.health !== false;\n // The app knows its own name, so the settings reader does not have to be told\n // it. One reader per app, created once: the cache lives on it.\n const settings: SettingsReader<D> =\n options.settings && isSettingsReader(options.settings)\n ? options.settings\n : createSettings<D>({ app: options.name, ...(options.settings ?? {}) });\n\n const app: App<D> = {\n settings,\n get: (t, h) => app.on('GET', t, h),\n post: (t, h) => app.on('POST', t, h),\n put: (t, h) => app.on('PUT', t, h),\n patch: (t, h) => app.on('PATCH', t, h),\n delete: (t, h) => app.on('DELETE', t, h),\n on(method, template, handler) {\n const segments = compileTemplate(template);\n routes.push({\n method: method.toUpperCase(),\n template,\n segments,\n literals: segments.filter((s) => s.lit !== undefined).length,\n handler,\n });\n // Literal-first: more literal segments = more specific = tried first.\n routes.sort((a, b) => b.literals - a.literals);\n return app;\n },\n routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),\n handler() {\n return (context: FnContext) => {\n const { req, res } = context;\n const headers = req.headers ?? {};\n const method = (req.method ?? 'GET').toUpperCase();\n const rawPath = String(req.path ?? '/').split('?')[0]!;\n const path = rawPath.replace(/\\/+$/, '') || '/';\n\n // Continue the caller's trace (gateway/site) when a traceparent is forwarded;\n // otherwise this SERVER span roots a fresh trace. Outbound PostgREST fetches\n // become child CLIENT spans via the undici instrumentation (see ./instrument).\n const parentCtx = propagation.extract(otelContext.active(), headers, headerGetter);\n\n return tracer.startActiveSpan(\n `${method} ${path}`,\n { kind: SpanKind.SERVER, attributes: { 'http.request.method': method, 'url.path': path } },\n parentCtx,\n async (span: Span) => {\n const contextToken = headerOf(headers, 'x-revenexx-context');\n const tenant =\n headerOf(headers, 'x-revenexx-tenant') ||\n (decodeClaims(contextToken).tenant_id as string | undefined) ||\n null;\n if (options.name) span.setAttribute('revenexx.app', options.name);\n if (tenant) span.setAttribute('revenexx.tenant', tenant);\n const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n try {\n if (health && path === '/' && method === 'GET') {\n span.setAttribute('http.route', '/');\n return res.json({\n app: {\n id: process.env.REVENEXX_APP_ID ?? null,\n name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,\n deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,\n runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ''}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ''}`,\n },\n status: 'ok',\n routes: app.routes(),\n timestamp: new Date().toISOString(),\n ...(options.healthExtra?.() ?? {}),\n });\n }\n\n const reqSegs = splitPath(path);\n let matched: { route: CompiledRoute<D>; params: Record<string, string> } | null = null;\n let pathExists = false;\n for (const route of routes) {\n const params = matchSegments(route.segments, reqSegs);\n if (!params) continue;\n pathExists = true;\n if (route.method === method) {\n matched = { route, params };\n break;\n }\n }\n\n if (!matched) {\n const status = pathExists ? 405 : 404;\n span.setAttribute('http.response.status_code', status);\n span.setStatus({ code: SpanStatusCode.ERROR, message: pathExists ? 'method not allowed' : 'no route' });\n if (pathExists) {\n return res.json({ error: `method ${method} not allowed for ${path}` }, 405);\n }\n return res.json({ error: `no route for ${method} ${path}`, routes: app.routes() }, 404);\n }\n\n span.updateName(`${method} ${matched.route.template}`);\n span.setAttribute('http.route', matched.route.template);\n\n // Gateway-extracted params (x-capability-params) win over our own match\n // for safety, but they should always agree.\n let gatewayParams: Record<string, string> = {};\n try {\n gatewayParams = JSON.parse(headerOf(headers, 'x-capability-params') || '{}') as Record<string, string>;\n } catch {\n gatewayParams = {};\n }\n\n const c: RouteContext<D> = {\n ctx: context,\n req,\n method,\n path,\n params: { ...matched.params, ...gatewayParams },\n query: parseQuery(req),\n body: parseBody(req),\n tenant,\n contextToken,\n header: (name) => headerOf(headers, name),\n log,\n json: (data, statusCode = 200) => res.json(data, statusCode),\n // The market rides on the request, so a market-scoped setting\n // resolves for the market this call is for — no argument needed.\n settings: (readOptions) => settings.get(c, readOptions),\n settingsSnapshot: (readOptions) => settings.load(c, readOptions),\n };\n\n return await matched.route.handler(c);\n } catch (err) {\n if (isHttpError(err)) {\n span.setAttribute('http.response.status_code', err.status);\n if (err.code) span.setAttribute('revenexx.error.code', err.code);\n if (err.status >= 500) span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n // The diagnosis (table names, constraint names, the raw\n // PostgREST body) stays on this side of the wire: logged and\n // traced, never serialised into the response.\n if (err.serverDetail !== undefined) {\n const detail =\n typeof err.serverDetail === 'string' ? err.serverDetail : JSON.stringify(err.serverDetail);\n span.setAttribute('revenexx.error.detail', detail);\n context.error?.(`${method} ${path} — ${err.status} ${err.message}: ${detail}`);\n }\n return res.json(\n {\n error: err.message,\n ...(err.code ? { code: err.code } : {}),\n ...(err.details != null ? { details: err.details } : {}),\n },\n err.status,\n );\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) {\n span.setAttribute('http.response.status_code', 403);\n return res.json({ error: msg }, 403);\n }\n span.recordException(err instanceof Error ? err : new Error(msg));\n span.setStatus({ code: SpanStatusCode.ERROR, message: msg });\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json({ error: msg }, 500);\n } finally {\n span.end();\n }\n },\n );\n };\n },\n };\n\n return app;\n}\n","/**\n * CRUD route mounting: wire a generated entity client to REST routes in one\n * call, with the platform's standard list/get/create/update/delete semantics.\n *\n * const app = createApp({ name: 'markets' });\n * const db = createDb({ adapter: 'runtime', context });\n *\n * mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });\n * mountCrud(app, db.locales, {\n * path: '/markets/{marketId}/locales',\n * columns: ENTITIES.locales.columns,\n * parent: { param: 'marketId', column: 'market_id' },\n * });\n *\n * Nested resources (a `parent` option) scope every operation to the parent row:\n * lists filter by the parent column, creates inject it, and reads/writes 404\n * when the row belongs to a different parent.\n */\n\nimport type { Page, Query, Row } from '../types.js';\nimport { HttpError, notFound, type App, type RouteContext } from './router.js';\nimport { EMPTY_UPDATE_MESSAGE, updateFields } from '../patch.js';\nimport type { SettingsDefaults } from '../settings.js';\n\n/** Structural subset of the SDK's EntityClient — any compatible repo works. */\nexport interface RepoLike {\n list(query?: Query): Promise<Row[]>;\n page?(query?: Query): Promise<Page>;\n get(id: string | number): Promise<Row | null>;\n create(data: Row): Promise<Row>;\n update(id: string | number, patch: Row): Promise<Row>;\n delete(id: string | number): Promise<void>;\n}\n\nexport interface CrudOptions {\n /** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */\n path: string;\n /** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */\n columns?: Record<string, unknown>;\n /**\n * Nested-resource scoping: path param name + the FK column it maps to.\n *\n * Pass `repo` (the PARENT's repo) to make the collection routes verify the\n * parent exists. Without it, `GET /lists/{unknown-id}/entries` answers `200`\n * with an empty page, which a client cannot tell apart from a parent that\n * genuinely has no children — and `POST` would attach a row to a parent that\n * is not there. The single-row routes never had this gap: `fetchOwned`\n * already 404s on an ownership mismatch.\n *\n * Optional to stay backwards compatible; it costs one extra read per\n * collection request, so it is the app's call.\n */\n parent?: { param: string; column: string; repo?: Pick<RepoLike, 'get'> };\n /** Path param for the row id (default `id`). */\n idParam?: string;\n /** Pagination bounds for list (defaults: 50, max 200). */\n defaultLimit?: number;\n maxLimit?: number;\n /** Restrict which routes are mounted (default: all five). */\n only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];\n}\n\nconst INT = (v: unknown, d: number): number => {\n const n = parseInt(String(v), 10);\n return Number.isFinite(n) ? n : d;\n};\n\n/** `json` / `jsonb`, read off the generated ENTITIES column metadata. */\nconst isJsonColumn = (def: unknown): boolean =>\n /^jsonb?\\b/i.test(String((def as { type?: unknown } | null | undefined)?.type ?? ''));\n\n/**\n * A filter on a jsonb column is a whole-document equality, so the value has to\n * be a JSON document. `k in opts.columns` never looked at the column *type*, so\n * anything else went to the data plane as `col=eq.<junk>`; Postgres failed the\n * cast (SQLSTATE 22P02) and the caller got a 400 that named neither the\n * parameter nor what a good value looks like:\n *\n * GET /v1/forms?definition=x -> 400 {\"error\":\"a value in the request has\n * the wrong format\",\"code\":\"invalid_value\"}\n *\n * It is our query parameter, so it is our 400. Same status and same `code` as\n * before — only the message becomes actionable, and the round trip disappears.\n * The rule is exactly the data plane's: it must parse as JSON. Postgres compares\n * jsonb semantically, so key order and whitespace stay irrelevant and nothing\n * that worked before stops working — a whole, exactly-serialised document is\n * still forwarded unchanged.\n *\n * Deliberately NOT a containment (`cs.`) filter: `?labels={\"de\":\"Hauptlager\"}`\n * matches one exact document today, and turning that into \"contains\" would\n * silently widen a filter three apps already declare, with examples, as\n * equality. Widening it is a product decision, not a bug fix.\n *\n * The message states the rule and does NOT show an instance of the document.\n * It cannot: the generated column metadata carries `type`, `notNull` and\n * sometimes `default`, and nothing about the shape — 22 of the 25 jsonb\n * columns in `products` have no default at all. The first version borrowed\n * one column's example for every column, so a filter on an array-shaped\n * document (`family_variants.axes`, `measurement_families.units`) was\n * illustrated with an object. A caller who copies that shape sends valid JSON,\n * so there is no 400 — the answer is 200 with zero rows, which is the worst\n * failure this API has. The honest example is per column, the app knows it,\n * and it is already published on the parameter; so point there instead of\n * inventing one here.\n */\nfunction assertJsonFilter(column: string, value: string): void {\n try {\n JSON.parse(value);\n } catch {\n throw new HttpError(\n 400,\n `filter '${column}' must be a whole JSON document, serialized exactly as stored ` +\n `and compared for equality — not a path or containment query. ` +\n `This parameter's example in the API contract shows the shape this column holds.`,\n undefined,\n { code: 'invalid_value' },\n );\n }\n}\n\nfunction parentWhere(c: RouteContext, parent?: CrudOptions['parent']): Record<string, string> {\n if (!parent) return {};\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n return { [parent.column]: value };\n}\n\n/**\n * 404 when the nested parent does not exist, so an unknown parent is not\n * reported as an empty collection. No-op unless the app supplied `parent.repo`.\n */\nasync function assertParentExists(c: RouteContext, parent?: CrudOptions['parent']): Promise<void> {\n if (!parent?.repo) return;\n const value = c.params[parent.param];\n if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);\n if (!(await parent.repo.get(value))) throw notFound();\n}\n\n/** Fetch a row and enforce nested-parent ownership; throws 404 when absent. */\nasync function fetchOwned(\n repo: RepoLike,\n c: RouteContext,\n opts: CrudOptions,\n): Promise<{ id: string; row: Row }> {\n const id = c.params[opts.idParam ?? 'id'] ?? '';\n if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? 'id'}'`);\n const row = await repo.get(id);\n if (!row) throw notFound();\n if (opts.parent) {\n const expected = c.params[opts.parent.param];\n if (String(row[opts.parent.column] ?? '') !== String(expected ?? '')) throw notFound();\n }\n return { id, row };\n}\n\nexport function mountCrud<D extends SettingsDefaults = SettingsDefaults>(\n app: App<D>,\n repo: RepoLike,\n opts: CrudOptions,\n): App<D> {\n const base = opts.path.replace(/\\/+$/, '');\n const idTemplate = `${base}/{${opts.idParam ?? 'id'}}`;\n const enabled = new Set(opts.only ?? ['list', 'get', 'create', 'update', 'delete']);\n const defaultLimit = opts.defaultLimit ?? 50;\n const maxLimit = opts.maxLimit ?? 200;\n\n if (enabled.has('list')) {\n app.get(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const where: Record<string, string> = {};\n for (const [k, v] of Object.entries(c.query)) {\n // A key naming no column is dropped, not refused: `filter` below echoes\n // exactly the keys that were honoured, so `filter: {}` next to a full\n // page is how a caller tells \"not filtered\" from \"filtered to nothing\".\n // Thirteen live apps document that, and 400ing instead would break every\n // client that carries a stray parameter.\n if (!opts.columns || !(k in opts.columns)) continue;\n if (isJsonColumn(opts.columns[k])) assertJsonFilter(k, v);\n where[k] = v;\n }\n // The nested-parent filter always wins — a query param must not widen\n // the scope beyond the parent in the path.\n Object.assign(where, parentWhere(c, opts.parent));\n const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);\n const offset = Math.max(INT(c.query.offset, 0), 0);\n const order = typeof c.query.order === 'string' && c.query.order ? c.query.order : undefined;\n const query: Query = { where, limit, offset, ...(order ? { order } : {}) };\n\n if (repo.page) {\n const { items, total } = await repo.page(query);\n return c.json({\n items,\n page: { limit, offset, total, returned: items.length, hasMore: offset + items.length < total },\n filter: where,\n });\n }\n const items = await repo.list(query);\n return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });\n });\n }\n\n if (enabled.has('create')) {\n app.post(base, async (c) => {\n await assertParentExists(c, opts.parent);\n const data = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.create(data), 201);\n });\n }\n\n if (enabled.has('get')) {\n app.get(idTemplate, async (c) => {\n const { row } = await fetchOwned(repo, c, opts);\n return c.json(row);\n });\n }\n\n if (enabled.has('update')) {\n app.put(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n // A body carrying no fields of its own is not an update. The rule itself\n // lives in ../patch.ts and is enforced by the data client, so Apps that\n // hand-write their PUT handler get it too; this check stays because it is\n // the only one that can see the *body* rather than the merged patch —\n // with a nested parent the merge always carries the FK, so the patch is\n // never literally empty — and because it answers without a round trip.\n if (updateFields(c.body).length === 0) throw new HttpError(400, EMPTY_UPDATE_MESSAGE);\n // Never let a body overwrite the nested-parent FK.\n const patch = { ...c.body, ...parentWhere(c, opts.parent) };\n return c.json(await repo.update(id, patch));\n });\n }\n\n if (enabled.has('delete')) {\n app.delete(idTemplate, async (c) => {\n const { id } = await fetchOwned(repo, c, opts);\n await repo.delete(id);\n return c.json({ deleted: true, id });\n });\n }\n\n return app;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA;AAAA,EACE;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAmGP,IAAM,YAAY,CAAC,SAA2B,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAE5E,SAAS,gBAAgB,UAA6B;AACpD,SAAO,UAAU,QAAQ,EAAE,IAAI,CAAC,QAAQ;AACtC,UAAM,SAAS,iCAAiC,KAAK,GAAG;AACxD,QAAI,OAAQ,QAAO,EAAE,OAAO,OAAO,CAAC,EAAE;AACtC,QAAI,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS,EAAG,QAAO,EAAE,OAAO,IAAI,MAAM,CAAC,EAAE;AACxE,WAAO,EAAE,KAAK,IAAI;AAAA,EACpB,CAAC;AACH;AAEA,SAAS,cAAc,UAAqB,SAAkD;AAC5F,MAAI,SAAS,WAAW,QAAQ,OAAQ,QAAO;AAC/C,QAAM,SAAiC,CAAC;AACxC,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,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,aAAa,EAAE,IAAI,EAAE,WAAW,EAAG,OAAM,IAAI,UAAU,KAAK,oBAAoB;AAEpF,YAAM,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,GAAG,KAAK,MAAM,EAAE;AAC1D,aAAO,EAAE,KAAK,MAAM,KAAK,OAAO,IAAI,KAAK,CAAC;AAAA,IAC5C,CAAC;AAAA,EACH;AAEA,MAAI,QAAQ,IAAI,QAAQ,GAAG;AACzB,QAAI,OAAO,YAAY,OAAO,MAAM;AAClC,YAAM,EAAE,GAAG,IAAI,MAAM,WAAW,MAAM,GAAG,IAAI;AAC7C,YAAM,KAAK,OAAO,EAAE;AACpB,aAAO,EAAE,KAAK,EAAE,SAAS,MAAM,GAAG,CAAC;AAAA,IACrC,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["items"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@revenexx/app-sdk",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Typed data client + HTTP router for revenexx Apps. Swappable adapters (mock | remote | runtime) so the same App code runs against in-memory fixtures locally and the real data plane in production.",
5
5
  "license": "MIT",
6
6
  "type": "module",