@revenexx/app-sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -17
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -66
- package/dist/index.d.ts +4 -66
- package/dist/index.js.map +1 -1
- package/dist/router/index.cjs +299 -0
- package/dist/router/index.cjs.map +1 -0
- package/dist/router/index.d.cts +151 -0
- package/dist/router/index.d.ts +151 -0
- package/dist/router/index.js +266 -0
- package/dist/router/index.js.map +1 -0
- package/dist/types-BMd8t8Pi.d.cts +66 -0
- package/dist/types-BMd8t8Pi.d.ts +66 -0
- package/package.json +8 -3
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { Q as Query, R as Row, P as Page } from '../types-BMd8t8Pi.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal HTTP router for revenexx App functions.
|
|
5
|
+
*
|
|
6
|
+
* App functions receive a single invocation context ({ req, res, log, error })
|
|
7
|
+
* and are expected to answer every route the App's manifest declares. This
|
|
8
|
+
* router turns that into declarative, testable handlers:
|
|
9
|
+
*
|
|
10
|
+
* const app = createApp({ name: 'markets' });
|
|
11
|
+
* app.get('/markets', (c) => c.json({ items: [] }));
|
|
12
|
+
* app.get('/markets/{id}', (c) => c.json({ id: c.params.id }));
|
|
13
|
+
* module.exports = app.handler();
|
|
14
|
+
*
|
|
15
|
+
* Matching is literal-first: `/markets/locales` always wins over
|
|
16
|
+
* `/markets/{id}` regardless of registration order. Path templates use the
|
|
17
|
+
* same `{param}` syntax as manifest capability routes (`:param` also works).
|
|
18
|
+
*/
|
|
19
|
+
interface FnRequest {
|
|
20
|
+
method?: string;
|
|
21
|
+
path?: string;
|
|
22
|
+
url?: string;
|
|
23
|
+
headers?: Record<string, string>;
|
|
24
|
+
query?: Record<string, unknown>;
|
|
25
|
+
body?: unknown;
|
|
26
|
+
bodyText?: string;
|
|
27
|
+
bodyRaw?: string;
|
|
28
|
+
}
|
|
29
|
+
interface FnResponse {
|
|
30
|
+
json(data: unknown, statusCode?: number, headers?: Record<string, string>): unknown;
|
|
31
|
+
send?(body: string, statusCode?: number, headers?: Record<string, string>): unknown;
|
|
32
|
+
}
|
|
33
|
+
/** The invocation context an App function receives from the runtime. */
|
|
34
|
+
interface FnContext {
|
|
35
|
+
req: FnRequest;
|
|
36
|
+
res: FnResponse;
|
|
37
|
+
log?: (message: string) => void;
|
|
38
|
+
error?: (message: string) => void;
|
|
39
|
+
}
|
|
40
|
+
/** Per-request context handed to route handlers. */
|
|
41
|
+
interface RouteContext {
|
|
42
|
+
/** Raw invocation context (escape hatch). */
|
|
43
|
+
ctx: FnContext;
|
|
44
|
+
req: FnRequest;
|
|
45
|
+
method: string;
|
|
46
|
+
/** Normalised path (no trailing slash, no query string). */
|
|
47
|
+
path: string;
|
|
48
|
+
/** Path parameters from the matched route template (e.g. `{id}`). */
|
|
49
|
+
params: Record<string, string>;
|
|
50
|
+
/** Query string parameters (string values). */
|
|
51
|
+
query: Record<string, string>;
|
|
52
|
+
/** Parsed JSON body, or `{}` when absent/unparsable. */
|
|
53
|
+
body: Record<string, unknown>;
|
|
54
|
+
/** Tenant slug from the `x-revenexx-tenant` header (or token claim). */
|
|
55
|
+
tenant: string | null;
|
|
56
|
+
/** The forwarded identity token (`x-revenexx-context`), if present. */
|
|
57
|
+
contextToken: string;
|
|
58
|
+
/** Case-insensitive header lookup. */
|
|
59
|
+
header(name: string): string;
|
|
60
|
+
log(message: string): void;
|
|
61
|
+
/** Respond with JSON. Returning `c.json(...)` ends the request. */
|
|
62
|
+
json(data: unknown, statusCode?: number): unknown;
|
|
63
|
+
}
|
|
64
|
+
type Handler = (c: RouteContext) => unknown | Promise<unknown>;
|
|
65
|
+
/** Throw inside a handler to answer with a specific HTTP status. */
|
|
66
|
+
declare class HttpError extends Error {
|
|
67
|
+
readonly status: number;
|
|
68
|
+
readonly details?: unknown;
|
|
69
|
+
constructor(status: number, message: string, details?: unknown);
|
|
70
|
+
}
|
|
71
|
+
declare const notFound: (message?: string) => HttpError;
|
|
72
|
+
declare const badRequest: (message?: string, details?: unknown) => HttpError;
|
|
73
|
+
declare const forbidden: (message?: string) => HttpError;
|
|
74
|
+
declare const conflict: (message?: string) => HttpError;
|
|
75
|
+
interface AppOptions {
|
|
76
|
+
/** App name reported on the built-in health route. */
|
|
77
|
+
name?: string;
|
|
78
|
+
/**
|
|
79
|
+
* Built-in `GET /` health route (default true). Responds with the app
|
|
80
|
+
* identity (from the runtime env), status and the registered routes.
|
|
81
|
+
*/
|
|
82
|
+
health?: boolean;
|
|
83
|
+
/** Extra payload merged into the health response. */
|
|
84
|
+
healthExtra?: () => Record<string, unknown>;
|
|
85
|
+
}
|
|
86
|
+
interface App {
|
|
87
|
+
get(template: string, handler: Handler): App;
|
|
88
|
+
post(template: string, handler: Handler): App;
|
|
89
|
+
put(template: string, handler: Handler): App;
|
|
90
|
+
patch(template: string, handler: Handler): App;
|
|
91
|
+
delete(template: string, handler: Handler): App;
|
|
92
|
+
on(method: string, template: string, handler: Handler): App;
|
|
93
|
+
/** Registered routes (e.g. for docs or the health response). */
|
|
94
|
+
routes(): {
|
|
95
|
+
method: string;
|
|
96
|
+
path: string;
|
|
97
|
+
}[];
|
|
98
|
+
/** Build the function entrypoint: `module.exports = app.handler()`. */
|
|
99
|
+
handler(): (context: FnContext) => Promise<unknown>;
|
|
100
|
+
}
|
|
101
|
+
declare function createApp(options?: AppOptions): App;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* CRUD route mounting: wire a generated entity client to REST routes in one
|
|
105
|
+
* call, with the platform's standard list/get/create/update/delete semantics.
|
|
106
|
+
*
|
|
107
|
+
* const app = createApp({ name: 'markets' });
|
|
108
|
+
* const db = createDb({ adapter: 'runtime', context });
|
|
109
|
+
*
|
|
110
|
+
* mountCrud(app, db.markets, { path: '/markets', columns: ENTITIES.markets.columns });
|
|
111
|
+
* mountCrud(app, db.locales, {
|
|
112
|
+
* path: '/markets/{marketId}/locales',
|
|
113
|
+
* columns: ENTITIES.locales.columns,
|
|
114
|
+
* parent: { param: 'marketId', column: 'market_id' },
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* Nested resources (a `parent` option) scope every operation to the parent row:
|
|
118
|
+
* lists filter by the parent column, creates inject it, and reads/writes 404
|
|
119
|
+
* when the row belongs to a different parent.
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
/** Structural subset of the SDK's EntityClient — any compatible repo works. */
|
|
123
|
+
interface RepoLike {
|
|
124
|
+
list(query?: Query): Promise<Row[]>;
|
|
125
|
+
page?(query?: Query): Promise<Page>;
|
|
126
|
+
get(id: string | number): Promise<Row | null>;
|
|
127
|
+
create(data: Row): Promise<Row>;
|
|
128
|
+
update(id: string | number, patch: Row): Promise<Row>;
|
|
129
|
+
delete(id: string | number): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
interface CrudOptions {
|
|
132
|
+
/** Route base path, e.g. `/markets` or `/markets/{marketId}/locales`. */
|
|
133
|
+
path: string;
|
|
134
|
+
/** Column metadata (from the generated ENTITIES) — enables `?col=value` list filters. */
|
|
135
|
+
columns?: Record<string, unknown>;
|
|
136
|
+
/** Nested-resource scoping: path param name + the FK column it maps to. */
|
|
137
|
+
parent?: {
|
|
138
|
+
param: string;
|
|
139
|
+
column: string;
|
|
140
|
+
};
|
|
141
|
+
/** Path param for the row id (default `id`). */
|
|
142
|
+
idParam?: string;
|
|
143
|
+
/** Pagination bounds for list (defaults: 50, max 200). */
|
|
144
|
+
defaultLimit?: number;
|
|
145
|
+
maxLimit?: number;
|
|
146
|
+
/** Restrict which routes are mounted (default: all five). */
|
|
147
|
+
only?: ('list' | 'get' | 'create' | 'update' | 'delete')[];
|
|
148
|
+
}
|
|
149
|
+
declare function mountCrud(app: App, repo: RepoLike, opts: CrudOptions): App;
|
|
150
|
+
|
|
151
|
+
export { type App, type AppOptions, type CrudOptions, type FnContext, type FnRequest, type FnResponse, type Handler, HttpError, type RepoLike, type RouteContext, badRequest, conflict, createApp, forbidden, mountCrud, notFound };
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// src/router/router.ts
|
|
2
|
+
var HttpError = class extends Error {
|
|
3
|
+
status;
|
|
4
|
+
details;
|
|
5
|
+
constructor(status, message, details) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "HttpError";
|
|
8
|
+
this.status = status;
|
|
9
|
+
this.details = details;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var notFound = (message = "not found") => new HttpError(404, message);
|
|
13
|
+
var badRequest = (message = "bad request", details) => new HttpError(400, message, details);
|
|
14
|
+
var forbidden = (message = "forbidden") => new HttpError(403, message);
|
|
15
|
+
var conflict = (message = "conflict") => new HttpError(409, message);
|
|
16
|
+
var splitPath = (path) => path.split("/").filter(Boolean);
|
|
17
|
+
function compileTemplate(template) {
|
|
18
|
+
return splitPath(template).map((seg) => {
|
|
19
|
+
const braced = /^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(seg);
|
|
20
|
+
if (braced) return { param: braced[1] };
|
|
21
|
+
if (seg.startsWith(":") && seg.length > 1) return { param: seg.slice(1) };
|
|
22
|
+
return { lit: seg };
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function matchSegments(segments, reqSegs) {
|
|
26
|
+
if (segments.length !== reqSegs.length) return null;
|
|
27
|
+
const params = {};
|
|
28
|
+
for (let i = 0; i < segments.length; i++) {
|
|
29
|
+
const s = segments[i];
|
|
30
|
+
if (s.param) params[s.param] = decodeURIComponent(reqSegs[i]);
|
|
31
|
+
else if (s.lit !== reqSegs[i]) return null;
|
|
32
|
+
}
|
|
33
|
+
return params;
|
|
34
|
+
}
|
|
35
|
+
function headerOf(headers, name) {
|
|
36
|
+
if (!headers) return "";
|
|
37
|
+
const direct = headers[name] ?? headers[name.toLowerCase()];
|
|
38
|
+
if (typeof direct === "string") return direct;
|
|
39
|
+
const want = name.toLowerCase();
|
|
40
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
41
|
+
if (k.toLowerCase() === want && typeof v === "string") return v;
|
|
42
|
+
}
|
|
43
|
+
return "";
|
|
44
|
+
}
|
|
45
|
+
function decodeClaims(token) {
|
|
46
|
+
if (!token || token.split(".").length < 2) return {};
|
|
47
|
+
try {
|
|
48
|
+
const payload = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
49
|
+
const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
|
|
50
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
51
|
+
} catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function parseBody(req) {
|
|
56
|
+
const candidate = req.body ?? req.bodyText ?? req.bodyRaw;
|
|
57
|
+
if (candidate == null || candidate === "") return {};
|
|
58
|
+
if (typeof candidate === "object") return candidate;
|
|
59
|
+
if (typeof candidate === "string") {
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(candidate);
|
|
62
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
63
|
+
} catch {
|
|
64
|
+
return {};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return {};
|
|
68
|
+
}
|
|
69
|
+
function parseQuery(req) {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const [k, v] of Object.entries(req.query ?? {})) {
|
|
72
|
+
if (typeof v === "string") out[k] = v;
|
|
73
|
+
else if (v != null) out[k] = String(v);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
function createApp(options = {}) {
|
|
78
|
+
const routes = [];
|
|
79
|
+
const health = options.health !== false;
|
|
80
|
+
const app = {
|
|
81
|
+
get: (t, h) => app.on("GET", t, h),
|
|
82
|
+
post: (t, h) => app.on("POST", t, h),
|
|
83
|
+
put: (t, h) => app.on("PUT", t, h),
|
|
84
|
+
patch: (t, h) => app.on("PATCH", t, h),
|
|
85
|
+
delete: (t, h) => app.on("DELETE", t, h),
|
|
86
|
+
on(method, template, handler) {
|
|
87
|
+
const segments = compileTemplate(template);
|
|
88
|
+
routes.push({
|
|
89
|
+
method: method.toUpperCase(),
|
|
90
|
+
template,
|
|
91
|
+
segments,
|
|
92
|
+
literals: segments.filter((s) => s.lit !== void 0).length,
|
|
93
|
+
handler
|
|
94
|
+
});
|
|
95
|
+
routes.sort((a, b) => b.literals - a.literals);
|
|
96
|
+
return app;
|
|
97
|
+
},
|
|
98
|
+
routes: () => routes.map((r) => ({ method: r.method, path: r.template })).sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method)),
|
|
99
|
+
handler() {
|
|
100
|
+
return async (context) => {
|
|
101
|
+
const { req, res } = context;
|
|
102
|
+
const headers = req.headers ?? {};
|
|
103
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
104
|
+
const rawPath = String(req.path ?? "/").split("?")[0];
|
|
105
|
+
const path = rawPath.replace(/\/+$/, "") || "/";
|
|
106
|
+
const contextToken = headerOf(headers, "x-revenexx-context");
|
|
107
|
+
const tenant = headerOf(headers, "x-revenexx-tenant") || decodeClaims(contextToken).tenant_id || null;
|
|
108
|
+
const log = (m) => context.log?.(m);
|
|
109
|
+
log(`${options.name ?? "app"} ${method} ${path} \u2014 tenant=${tenant ?? "none"}`);
|
|
110
|
+
if (health && path === "/" && method === "GET") {
|
|
111
|
+
return res.json({
|
|
112
|
+
app: {
|
|
113
|
+
id: process.env.REVENEXX_APP_ID ?? null,
|
|
114
|
+
name: options.name ?? process.env.REVENEXX_APP_NAME ?? null,
|
|
115
|
+
deployment: process.env.REVENEXX_APP_DEPLOYMENT ?? null,
|
|
116
|
+
runtime: `${process.env.REVENEXX_APP_RUNTIME_NAME ?? ""}-${process.env.REVENEXX_APP_RUNTIME_VERSION ?? ""}`
|
|
117
|
+
},
|
|
118
|
+
status: "ok",
|
|
119
|
+
routes: app.routes(),
|
|
120
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
121
|
+
...options.healthExtra?.() ?? {}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const reqSegs = splitPath(path);
|
|
125
|
+
let matched = null;
|
|
126
|
+
let pathExists = false;
|
|
127
|
+
for (const route of routes) {
|
|
128
|
+
const params = matchSegments(route.segments, reqSegs);
|
|
129
|
+
if (!params) continue;
|
|
130
|
+
pathExists = true;
|
|
131
|
+
if (route.method === method) {
|
|
132
|
+
matched = { route, params };
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!matched) {
|
|
137
|
+
if (pathExists) {
|
|
138
|
+
return res.json({ error: `method ${method} not allowed for ${path}` }, 405);
|
|
139
|
+
}
|
|
140
|
+
return res.json({ error: `no route for ${method} ${path}`, routes: app.routes() }, 404);
|
|
141
|
+
}
|
|
142
|
+
let gatewayParams = {};
|
|
143
|
+
try {
|
|
144
|
+
gatewayParams = JSON.parse(headerOf(headers, "x-capability-params") || "{}");
|
|
145
|
+
} catch {
|
|
146
|
+
gatewayParams = {};
|
|
147
|
+
}
|
|
148
|
+
const c = {
|
|
149
|
+
ctx: context,
|
|
150
|
+
req,
|
|
151
|
+
method,
|
|
152
|
+
path,
|
|
153
|
+
params: { ...matched.params, ...gatewayParams },
|
|
154
|
+
query: parseQuery(req),
|
|
155
|
+
body: parseBody(req),
|
|
156
|
+
tenant,
|
|
157
|
+
contextToken,
|
|
158
|
+
header: (name) => headerOf(headers, name),
|
|
159
|
+
log,
|
|
160
|
+
json: (data, statusCode = 200) => res.json(data, statusCode)
|
|
161
|
+
};
|
|
162
|
+
try {
|
|
163
|
+
return await matched.route.handler(c);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
if (err instanceof HttpError) {
|
|
166
|
+
return res.json({ error: err.message, ...err.details != null ? { details: err.details } : {} }, err.status);
|
|
167
|
+
}
|
|
168
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
169
|
+
if (/not permitted/.test(msg)) return res.json({ error: msg }, 403);
|
|
170
|
+
context.error?.(`unhandled error on ${method} ${path}: ${msg}`);
|
|
171
|
+
return res.json({ error: msg }, 500);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
return app;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// src/router/crud.ts
|
|
180
|
+
var INT = (v, d) => {
|
|
181
|
+
const n = parseInt(String(v), 10);
|
|
182
|
+
return Number.isFinite(n) ? n : d;
|
|
183
|
+
};
|
|
184
|
+
function parentWhere(c, parent) {
|
|
185
|
+
if (!parent) return {};
|
|
186
|
+
const value = c.params[parent.param];
|
|
187
|
+
if (!value) throw new HttpError(400, `missing path parameter '${parent.param}'`);
|
|
188
|
+
return { [parent.column]: value };
|
|
189
|
+
}
|
|
190
|
+
async function fetchOwned(repo, c, opts) {
|
|
191
|
+
const id = c.params[opts.idParam ?? "id"] ?? "";
|
|
192
|
+
if (!id) throw new HttpError(400, `missing path parameter '${opts.idParam ?? "id"}'`);
|
|
193
|
+
const row = await repo.get(id);
|
|
194
|
+
if (!row) throw notFound();
|
|
195
|
+
if (opts.parent) {
|
|
196
|
+
const expected = c.params[opts.parent.param];
|
|
197
|
+
if (String(row[opts.parent.column] ?? "") !== String(expected ?? "")) throw notFound();
|
|
198
|
+
}
|
|
199
|
+
return { id, row };
|
|
200
|
+
}
|
|
201
|
+
function mountCrud(app, repo, opts) {
|
|
202
|
+
const base = opts.path.replace(/\/+$/, "");
|
|
203
|
+
const idTemplate = `${base}/{${opts.idParam ?? "id"}}`;
|
|
204
|
+
const enabled = new Set(opts.only ?? ["list", "get", "create", "update", "delete"]);
|
|
205
|
+
const defaultLimit = opts.defaultLimit ?? 50;
|
|
206
|
+
const maxLimit = opts.maxLimit ?? 200;
|
|
207
|
+
if (enabled.has("list")) {
|
|
208
|
+
app.get(base, async (c) => {
|
|
209
|
+
const where = { ...parentWhere(c, opts.parent) };
|
|
210
|
+
for (const [k, v] of Object.entries(c.query)) {
|
|
211
|
+
if (opts.columns && k in opts.columns) where[k] = v;
|
|
212
|
+
}
|
|
213
|
+
const limit = Math.min(Math.max(INT(c.query.limit, defaultLimit), 1), maxLimit);
|
|
214
|
+
const offset = Math.max(INT(c.query.offset, 0), 0);
|
|
215
|
+
const order = typeof c.query.order === "string" && c.query.order ? c.query.order : void 0;
|
|
216
|
+
const query = { where, limit, offset, ...order ? { order } : {} };
|
|
217
|
+
if (repo.page) {
|
|
218
|
+
const { items: items2, total } = await repo.page(query);
|
|
219
|
+
return c.json({
|
|
220
|
+
items: items2,
|
|
221
|
+
page: { limit, offset, total, returned: items2.length, hasMore: offset + items2.length < total },
|
|
222
|
+
filter: where
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
const items = await repo.list(query);
|
|
226
|
+
return c.json({ items, page: { limit, offset, returned: items.length }, filter: where });
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
if (enabled.has("create")) {
|
|
230
|
+
app.post(base, async (c) => {
|
|
231
|
+
const data = { ...c.body, ...parentWhere(c, opts.parent) };
|
|
232
|
+
return c.json(await repo.create(data), 201);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
if (enabled.has("get")) {
|
|
236
|
+
app.get(idTemplate, async (c) => {
|
|
237
|
+
const { row } = await fetchOwned(repo, c, opts);
|
|
238
|
+
return c.json(row);
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
if (enabled.has("update")) {
|
|
242
|
+
app.put(idTemplate, async (c) => {
|
|
243
|
+
const { id } = await fetchOwned(repo, c, opts);
|
|
244
|
+
const patch = { ...c.body, ...parentWhere(c, opts.parent) };
|
|
245
|
+
return c.json(await repo.update(id, patch));
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
if (enabled.has("delete")) {
|
|
249
|
+
app.delete(idTemplate, async (c) => {
|
|
250
|
+
const { id } = await fetchOwned(repo, c, opts);
|
|
251
|
+
await repo.delete(id);
|
|
252
|
+
return c.json({ deleted: true, id });
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
return app;
|
|
256
|
+
}
|
|
257
|
+
export {
|
|
258
|
+
HttpError,
|
|
259
|
+
badRequest,
|
|
260
|
+
conflict,
|
|
261
|
+
createApp,
|
|
262
|
+
forbidden,
|
|
263
|
+
mountCrud,
|
|
264
|
+
notFound
|
|
265
|
+
};
|
|
266
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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\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 {\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\nexport type Handler = (c: RouteContext) => unknown | Promise<unknown>;\n\n/** Throw inside a handler to answer with a specific HTTP status. */\nexport class HttpError extends Error {\n readonly status: number;\n readonly details?: unknown;\n constructor(status: number, message: string, details?: unknown) {\n super(message);\n this.name = 'HttpError';\n this.status = status;\n this.details = details;\n }\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\ninterface Segment {\n lit?: string;\n param?: string;\n}\n\ninterface CompiledRoute {\n method: string;\n template: string;\n segments: Segment[];\n literals: number;\n handler: Handler;\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\nfunction parseQuery(req: FnRequest): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(req.query ?? {})) {\n if (typeof v === 'string') out[k] = v;\n else if (v != null) out[k] = String(v);\n }\n return out;\n}\n\nexport interface AppOptions {\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\nexport interface App {\n get(template: string, handler: Handler): App;\n post(template: string, handler: Handler): App;\n put(template: string, handler: Handler): App;\n patch(template: string, handler: Handler): App;\n delete(template: string, handler: Handler): App;\n on(method: string, template: string, handler: Handler): App;\n /** Registered routes (e.g. for docs or the health response). */\n routes(): { method: string; path: string }[];\n /** Build the function entrypoint: `module.exports = app.handler()`. */\n handler(): (context: FnContext) => Promise<unknown>;\n}\n\nexport function createApp(options: AppOptions = {}): App {\n const routes: CompiledRoute[] = [];\n const health = options.health !== false;\n\n const app: App = {\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 async (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 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 const log = (m: string) => context.log?.(m);\n\n log(`${options.name ?? 'app'} ${method} ${path} — tenant=${tenant ?? 'none'}`);\n\n if (health && path === '/' && method === 'GET') {\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; 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 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 // 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 = {\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 };\n\n try {\n return await matched.route.handler(c);\n } catch (err) {\n if (err instanceof HttpError) {\n return res.json({ error: err.message, ...(err.details != null ? { details: err.details } : {}) }, err.status);\n }\n const msg = err instanceof Error ? err.message : String(err);\n if (/not permitted/.test(msg)) return res.json({ error: msg }, 403);\n context.error?.(`unhandled error on ${method} ${path}: ${msg}`);\n return res.json({ error: msg }, 500);\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';\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 /** Nested-resource scoping: path param name + the FK column it maps to. */\n parent?: { param: string; column: string };\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/** 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(app: App, repo: RepoLike, opts: CrudOptions): App {\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 const where: Record<string, string> = { ...parentWhere(c, opts.parent) };\n for (const [k, v] of Object.entries(c.query)) {\n if (opts.columns && k in opts.columns) where[k] = v;\n }\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 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 // 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":";AAqEO,IAAM,YAAN,cAAwB,MAAM;AAAA,EAC1B;AAAA,EACA;AAAA,EACT,YAAY,QAAgB,SAAiB,SAAmB;AAC9D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,WAAW,CAAC,UAAU,gBAA2B,IAAI,UAAU,KAAK,OAAO;AACjF,IAAM,aAAa,CAAC,UAAU,eAAe,YAClD,IAAI,UAAU,KAAK,SAAS,OAAO;AA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,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"]}
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
export type { Adapter as A, ColumnDef as C, Entity as E, Filter as F, Op as O, Page as P, Query as Q, Row as R, Scalar as S, FilterOp as a };
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
export type { Adapter as A, ColumnDef as C, Entity as E, Filter as F, Op as O, Page as P, Query as Q, Row as R, Scalar as S, FilterOp as a };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@revenexx/app-sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Typed
|
|
3
|
+
"version": "0.3.0",
|
|
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",
|
|
7
7
|
"main": "./dist/index.cjs",
|
|
@@ -12,6 +12,11 @@
|
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.js",
|
|
14
14
|
"require": "./dist/index.cjs"
|
|
15
|
+
},
|
|
16
|
+
"./router": {
|
|
17
|
+
"types": "./dist/router/index.d.ts",
|
|
18
|
+
"import": "./dist/router/index.js",
|
|
19
|
+
"require": "./dist/router/index.cjs"
|
|
15
20
|
}
|
|
16
21
|
},
|
|
17
22
|
"files": [
|
|
@@ -22,7 +27,7 @@
|
|
|
22
27
|
},
|
|
23
28
|
"publishConfig": {
|
|
24
29
|
"registry": "https://registry.npmjs.org",
|
|
25
|
-
"access": "
|
|
30
|
+
"access": "public"
|
|
26
31
|
},
|
|
27
32
|
"repository": {
|
|
28
33
|
"type": "git",
|