@nanobpm/urban-pr-review-codefirst 0.1.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 +141 -0
- package/components/review-round.json +69 -0
- package/db/migrations/001_init.sql +46 -0
- package/db/migrations/002_transcript.sql +7 -0
- package/db/migrations/003_open_escalation.sql +8 -0
- package/deno.json +22 -0
- package/deno.lock +77 -0
- package/main.ts +352 -0
- package/nano-generated/app-pages.ts +676 -0
- package/nano-generated/data-cli.ts +552 -0
- package/nano-generated/data-sdk.ts +536 -0
- package/nano-generated/domain-rows.d.ts +87 -0
- package/nano-generated/domain-types.ts +1418 -0
- package/nano-generated/domain.ts +36 -0
- package/nano-generated/llm-worker.ts +403 -0
- package/nano-generated/message-io.d.ts +17 -0
- package/nano-generated/messages.ts +26 -0
- package/nano-generated/meta.ts +18 -0
- package/nano-generated/node-deno-shim.mjs +250 -0
- package/nano-generated/node-loader.mjs +60 -0
- package/nano-generated/node-register.mjs +11 -0
- package/nano-generated/worker-io.d.ts +28 -0
- package/nano-generated/worker-sdk.ts +468 -0
- package/nano-generated/workers.ts +29 -0
- package/nano.app.json +17 -0
- package/nanobpm.project.json +22 -0
- package/package.json +28 -0
- package/pages/home.page.json +127 -0
- package/prompts/review-round.md +119 -0
- package/scripts/answer.ts +20 -0
- package/scripts/purge-db.ts +70 -0
- package/scripts/review-ready.ts +20 -0
- package/scripts/submit.ts +32 -0
- package/tsconfig.json +14 -0
- package/workflows/convergence-loop.ts +299 -0
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
// The Urban App page runtime (ADR 0042 §3) — materialised into an app as
|
|
2
|
+
// `nano-generated/app-pages.ts` and imported as `@nanobpm/app`. It turns a composed
|
|
3
|
+
// `page.json` (authored in the console Page Composer) into a served, data-bound
|
|
4
|
+
// screen with no hand-written frontend or API.
|
|
5
|
+
//
|
|
6
|
+
// It imports neither `@nanobpm/data` nor `@nanobpm/nano-sdk`: the app's `main.ts`
|
|
7
|
+
// passes the already-opened datasource + engine client in, so this module stays
|
|
8
|
+
// self-contained, testable (`app_pages_test.ts`), and free of the hyphenated
|
|
9
|
+
// emit-time specifiers that make `data-cli.ts` un-typecheckable in-tree.
|
|
10
|
+
//
|
|
11
|
+
// Endpoints (ADR 0026 §1 action API):
|
|
12
|
+
// GET /app/pages/<id> → the page's page.json
|
|
13
|
+
// GET /app/data/<source>/<table>[?where&order]→ rows (filtered/ordered, whitelisted)
|
|
14
|
+
// POST /app/actions/start/<process> → createProcessInstance (attended-sync)
|
|
15
|
+
// POST /app/actions/cancel → cancelProcessInstance (row cancel)
|
|
16
|
+
// POST /app/actions/message → publishMessage (row/detail answer)
|
|
17
|
+
// GET / (+ /app/runtime.js) → the schema-driven browser renderer
|
|
18
|
+
|
|
19
|
+
/** The subset of the `@nanobpm/data` DataSource the runtime needs. */
|
|
20
|
+
export interface PagesDataSource {
|
|
21
|
+
query(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]>;
|
|
22
|
+
schema(): Promise<{ name: string }[]>;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The subset of the `@nanobpm/nano-sdk` engine client the runtime needs. */
|
|
26
|
+
export interface PagesEngine {
|
|
27
|
+
createProcessInstance(
|
|
28
|
+
input: { processDefinitionId: string; variables?: Record<string, unknown> },
|
|
29
|
+
): Promise<{ processInstanceKey?: string | number }>;
|
|
30
|
+
/** Cancel a running instance (row cancel action). */
|
|
31
|
+
cancelProcessInstance(
|
|
32
|
+
input: { processInstanceKey: string | number },
|
|
33
|
+
): Promise<unknown>;
|
|
34
|
+
/** Publish a correlated message (row/detail publishMessage action). */
|
|
35
|
+
publishMessage(
|
|
36
|
+
input: {
|
|
37
|
+
name: string;
|
|
38
|
+
correlationKey: string;
|
|
39
|
+
variables?: Record<string, unknown>;
|
|
40
|
+
},
|
|
41
|
+
): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PagesContext {
|
|
45
|
+
db: PagesDataSource;
|
|
46
|
+
nano: PagesEngine;
|
|
47
|
+
/** Directory holding `*.page.json` (relative to the app root). Default `pages`. */
|
|
48
|
+
pagesDir?: string;
|
|
49
|
+
/** The page served at `/`. Default `home`. */
|
|
50
|
+
homePage?: string;
|
|
51
|
+
/** Max rows a `dataGrid` fetch returns. Default 200. */
|
|
52
|
+
rowLimit?: number;
|
|
53
|
+
/** The name of the injected default datasource (the alias apps bind to). Default `app`. */
|
|
54
|
+
sourceName?: string;
|
|
55
|
+
/** Read a page file; injectable for tests. Defaults to `Deno.readTextFile`. */
|
|
56
|
+
readPage?: (path: string) => Promise<string>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const json = (body: unknown, status = 200): Response =>
|
|
60
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
61
|
+
|
|
62
|
+
/** A SQL identifier guard — a table name must be a bare identifier *and* a known
|
|
63
|
+
* table (checked against `schema()`), so `/app/data/:table` can never inject SQL. */
|
|
64
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The request handler, factored out of `servePages` so it is pure over its context
|
|
68
|
+
* (injected `db`/`nano`/`readPage`) and unit-testable without a real `Deno.serve`.
|
|
69
|
+
*/
|
|
70
|
+
export function createPagesHandler(ctx: PagesContext): (req: Request) => Promise<Response> {
|
|
71
|
+
const pagesDir = ctx.pagesDir ?? "pages";
|
|
72
|
+
const homePage = ctx.homePage ?? "home";
|
|
73
|
+
const rowLimit = Math.max(0, Math.floor(Number(ctx.rowLimit) || 200));
|
|
74
|
+
const sourceName = ctx.sourceName ?? "app";
|
|
75
|
+
const readPage = ctx.readPage ?? ((p: string) => Deno.readTextFile(p));
|
|
76
|
+
|
|
77
|
+
// The table-name whitelist is memoised: an Urban app runs its migrations at
|
|
78
|
+
// boot (before `servePages`), so the schema is stable for the process lifetime,
|
|
79
|
+
// and the renderer refreshes grids repeatedly — re-introspecting the sqlite
|
|
80
|
+
// schema (multiple PRAGMAs per table) on every `/app/data` hit would be a hot
|
|
81
|
+
// path. Introspect once, lazily, and reuse. A rejected introspection is NOT
|
|
82
|
+
// cached (the in-flight promise is cleared on failure) so a transient error
|
|
83
|
+
// (locked/unavailable datasource) doesn't wedge every future request.
|
|
84
|
+
let tableNames: Promise<Set<string>> | null = null;
|
|
85
|
+
const knownTables = (): Promise<Set<string>> =>
|
|
86
|
+
(tableNames ??= ctx.db.schema().then(
|
|
87
|
+
(t) => new Set(t.map((x) => x.name)),
|
|
88
|
+
(err) => {
|
|
89
|
+
tableNames = null;
|
|
90
|
+
throw err;
|
|
91
|
+
},
|
|
92
|
+
));
|
|
93
|
+
|
|
94
|
+
// Per-table column whitelist, introspected once per table via `PRAGMA
|
|
95
|
+
// table_info`. Every filter/order column named in a `/app/data` query is checked
|
|
96
|
+
// against this set before it reaches the SQL, so — like the table whitelist —
|
|
97
|
+
// an attacker-supplied `where`/`order` can never inject. `table` is already
|
|
98
|
+
// IDENT-guarded and table-whitelisted before we get here.
|
|
99
|
+
const tableColumns = new Map<string, Promise<Set<string>>>();
|
|
100
|
+
const knownColumns = (table: string): Promise<Set<string>> => {
|
|
101
|
+
const cached = tableColumns.get(table);
|
|
102
|
+
if (cached) return cached;
|
|
103
|
+
const p = ctx.db
|
|
104
|
+
.query(`PRAGMA table_info(${table})`)
|
|
105
|
+
.then((rows) => new Set(rows.map((r) => String(r.name))))
|
|
106
|
+
.catch((err) => {
|
|
107
|
+
tableColumns.delete(table);
|
|
108
|
+
throw err;
|
|
109
|
+
});
|
|
110
|
+
tableColumns.set(table, p);
|
|
111
|
+
return p;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
return async function handle(req: Request): Promise<Response> {
|
|
115
|
+
const url = new URL(req.url);
|
|
116
|
+
const { pathname } = url;
|
|
117
|
+
|
|
118
|
+
// ── the renderer shell ────────────────────────────────────────────────
|
|
119
|
+
if (req.method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
120
|
+
return new Response(rendererShell(homePage), {
|
|
121
|
+
headers: { "content-type": "text/html; charset=utf-8" },
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
if (req.method === "GET" && pathname === "/app/runtime.js") {
|
|
125
|
+
return new Response(RENDERER_JS, {
|
|
126
|
+
headers: { "content-type": "text/javascript; charset=utf-8" },
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// ── GET /app/pages/<id> ───────────────────────────────────────────────
|
|
131
|
+
const pageMatch = pathname.match(/^\/app\/pages\/([A-Za-z0-9_-]+)$/);
|
|
132
|
+
if (req.method === "GET" && pageMatch) {
|
|
133
|
+
const id = pageMatch[1];
|
|
134
|
+
try {
|
|
135
|
+
const text = await readPage(`${pagesDir}/${id}.page.json`);
|
|
136
|
+
return new Response(text, { headers: { "content-type": "application/json" } });
|
|
137
|
+
} catch {
|
|
138
|
+
return json({ error: `page "${id}" not found` }, 404);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── GET /app/data/<source>/<table> ────────────────────────────────────
|
|
143
|
+
const dataMatch = pathname.match(/^\/app\/data\/([A-Za-z0-9_-]+)\/([A-Za-z0-9_]+)$/);
|
|
144
|
+
if (req.method === "GET" && dataMatch) {
|
|
145
|
+
const source = dataMatch[1];
|
|
146
|
+
const table = dataMatch[2];
|
|
147
|
+
// v1 exposes only the injected default datasource; a request naming any
|
|
148
|
+
// other source is rejected rather than silently served off the default.
|
|
149
|
+
if (source !== sourceName) {
|
|
150
|
+
return json({ error: `unknown datasource "${source}"` }, 404);
|
|
151
|
+
}
|
|
152
|
+
if (!IDENT.test(table)) return json({ error: "invalid table name" }, 400);
|
|
153
|
+
let tables: Set<string>;
|
|
154
|
+
try {
|
|
155
|
+
tables = await knownTables();
|
|
156
|
+
} catch {
|
|
157
|
+
// A transient introspection failure isn't cached (see knownTables) — the
|
|
158
|
+
// next request retries. Surface it as a 500 so the renderer can retry too.
|
|
159
|
+
return json({ error: "schema introspection failed" }, 500);
|
|
160
|
+
}
|
|
161
|
+
if (!tables.has(table)) {
|
|
162
|
+
return json({ error: `unknown table "${table}"` }, 404);
|
|
163
|
+
}
|
|
164
|
+
// Parse ?where=col:value (equality) or ?where=col:in:v1,v2 (set membership),
|
|
165
|
+
// repeatable and ANDed, plus ?order=col:dir. Every column is whitelisted
|
|
166
|
+
// against the table's real columns before it reaches the SQL; values are
|
|
167
|
+
// always bound as `?` parameters (commas in an `in` list split values).
|
|
168
|
+
let columns: Set<string>;
|
|
169
|
+
try {
|
|
170
|
+
columns = await knownColumns(table);
|
|
171
|
+
} catch {
|
|
172
|
+
return json({ error: "schema introspection failed" }, 500);
|
|
173
|
+
}
|
|
174
|
+
const params: unknown[] = [];
|
|
175
|
+
const clauses: string[] = [];
|
|
176
|
+
for (const raw of url.searchParams.getAll("where")) {
|
|
177
|
+
const colon = raw.indexOf(":");
|
|
178
|
+
if (colon <= 0) return json({ error: "invalid where clause" }, 400);
|
|
179
|
+
const field = raw.slice(0, colon);
|
|
180
|
+
const rest = raw.slice(colon + 1);
|
|
181
|
+
if (!columns.has(field)) {
|
|
182
|
+
return json({ error: `unknown column "${field}"` }, 400);
|
|
183
|
+
}
|
|
184
|
+
if (rest.startsWith("in:")) {
|
|
185
|
+
const values = rest.slice(3).split(",");
|
|
186
|
+
clauses.push(`${field} IN (${values.map(() => "?").join(", ")})`);
|
|
187
|
+
for (const v of values) params.push(v);
|
|
188
|
+
} else {
|
|
189
|
+
clauses.push(`${field} = ?`);
|
|
190
|
+
params.push(rest);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
let orderSql = "";
|
|
194
|
+
const orderRaw = url.searchParams.get("order");
|
|
195
|
+
if (orderRaw) {
|
|
196
|
+
const colon = orderRaw.indexOf(":");
|
|
197
|
+
const field = colon > 0 ? orderRaw.slice(0, colon) : orderRaw;
|
|
198
|
+
const dir =
|
|
199
|
+
colon > 0 && orderRaw.slice(colon + 1).toLowerCase() === "desc"
|
|
200
|
+
? "DESC"
|
|
201
|
+
: "ASC";
|
|
202
|
+
if (!columns.has(field)) {
|
|
203
|
+
return json({ error: `unknown column "${field}"` }, 400);
|
|
204
|
+
}
|
|
205
|
+
orderSql = ` ORDER BY ${field} ${dir}`;
|
|
206
|
+
}
|
|
207
|
+
const whereSql = clauses.length ? ` WHERE ${clauses.join(" AND ")}` : "";
|
|
208
|
+
const rows = await ctx.db.query(
|
|
209
|
+
`SELECT * FROM ${table}${whereSql}${orderSql} LIMIT ${rowLimit}`,
|
|
210
|
+
params,
|
|
211
|
+
);
|
|
212
|
+
return json({ rows });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── POST /app/actions/start/<process> ─────────────────────────────────
|
|
216
|
+
const startMatch = pathname.match(/^\/app\/actions\/start\/([A-Za-z0-9_.-]+)$/);
|
|
217
|
+
if (req.method === "POST" && startMatch) {
|
|
218
|
+
const process = startMatch[1];
|
|
219
|
+
let variables: Record<string, unknown> = {};
|
|
220
|
+
try {
|
|
221
|
+
const body = await req.json();
|
|
222
|
+
if (body && typeof body === "object") {
|
|
223
|
+
const v = (body as { variables?: unknown }).variables;
|
|
224
|
+
// Only a plain object is a valid variable map — reject arrays/scalars/null
|
|
225
|
+
// so a malformed body can't reach the engine as bad `variables`.
|
|
226
|
+
if (v && typeof v === "object" && !Array.isArray(v)) {
|
|
227
|
+
variables = v as Record<string, unknown>;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch {
|
|
231
|
+
return json({ error: "body must be JSON" }, 400);
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
const res = await ctx.nano.createProcessInstance({ processDefinitionId: process, variables });
|
|
235
|
+
return json({ processInstanceKey: res.processInstanceKey ?? null });
|
|
236
|
+
} catch (e) {
|
|
237
|
+
return json({ error: String((e as Error)?.message ?? e) }, 502);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// ── POST /app/actions/cancel ──────────────────────────────────────────
|
|
242
|
+
if (req.method === "POST" && pathname === "/app/actions/cancel") {
|
|
243
|
+
let key: string | number | undefined;
|
|
244
|
+
try {
|
|
245
|
+
const body = await req.json();
|
|
246
|
+
const k = (body as { processInstanceKey?: unknown })?.processInstanceKey;
|
|
247
|
+
if (typeof k === "string" || typeof k === "number") key = k;
|
|
248
|
+
} catch {
|
|
249
|
+
return json({ error: "body must be JSON" }, 400);
|
|
250
|
+
}
|
|
251
|
+
if (key === undefined || key === "") {
|
|
252
|
+
return json({ error: "processInstanceKey is required" }, 400);
|
|
253
|
+
}
|
|
254
|
+
try {
|
|
255
|
+
await ctx.nano.cancelProcessInstance({ processInstanceKey: key });
|
|
256
|
+
return json({ ok: true });
|
|
257
|
+
} catch (e) {
|
|
258
|
+
return json({ error: String((e as Error)?.message ?? e) }, 502);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ── POST /app/actions/message ─────────────────────────────────────────
|
|
263
|
+
if (req.method === "POST" && pathname === "/app/actions/message") {
|
|
264
|
+
let name = "";
|
|
265
|
+
let correlationKey = "";
|
|
266
|
+
let variables: Record<string, unknown> = {};
|
|
267
|
+
try {
|
|
268
|
+
const body = (await req.json()) as {
|
|
269
|
+
name?: unknown;
|
|
270
|
+
correlationKey?: unknown;
|
|
271
|
+
variables?: unknown;
|
|
272
|
+
};
|
|
273
|
+
if (typeof body?.name === "string") name = body.name;
|
|
274
|
+
if (typeof body?.correlationKey === "string" || typeof body?.correlationKey === "number") {
|
|
275
|
+
correlationKey = String(body.correlationKey);
|
|
276
|
+
}
|
|
277
|
+
const v = body?.variables;
|
|
278
|
+
if (v && typeof v === "object" && !Array.isArray(v)) {
|
|
279
|
+
variables = v as Record<string, unknown>;
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
return json({ error: "body must be JSON" }, 400);
|
|
283
|
+
}
|
|
284
|
+
if (!name) return json({ error: "message name is required" }, 400);
|
|
285
|
+
if (!correlationKey) {
|
|
286
|
+
return json({ error: "correlationKey is required" }, 400);
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
await ctx.nano.publishMessage({ name, correlationKey, variables });
|
|
290
|
+
return json({ ok: true });
|
|
291
|
+
} catch (e) {
|
|
292
|
+
return json({ error: String((e as Error)?.message ?? e) }, 502);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return json({ error: "not found" }, 404);
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Start the page runtime on `port`. Returns the `Deno.HttpServer` handle. The app's
|
|
302
|
+
* `main.ts` typically does: `servePages({ db, nano, port })`.
|
|
303
|
+
*/
|
|
304
|
+
export function servePages(ctx: PagesContext & { port?: number }): Deno.HttpServer {
|
|
305
|
+
const handle = createPagesHandler(ctx);
|
|
306
|
+
return Deno.serve({ port: ctx.port ?? 8090 }, handle);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function escapeAttr(s: string): string {
|
|
310
|
+
return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function rendererShell(homePage: string): string {
|
|
314
|
+
return `<!doctype html>
|
|
315
|
+
<html lang="en">
|
|
316
|
+
<head>
|
|
317
|
+
<meta charset="utf-8" />
|
|
318
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
319
|
+
<title>Urban App</title>
|
|
320
|
+
<style>${RENDERER_CSS}</style>
|
|
321
|
+
</head>
|
|
322
|
+
<body>
|
|
323
|
+
<main id="page" data-home="${escapeAttr(homePage)}"><p class="pc-empty">Loading…</p></main>
|
|
324
|
+
<script type="module" src="/app/runtime.js"></script>
|
|
325
|
+
</body>
|
|
326
|
+
</html>`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const RENDERER_CSS = `
|
|
330
|
+
:root { color-scheme: light dark; --pc-edge:#d0d0d8; --pc-accent:#3b5bdb; }
|
|
331
|
+
* { box-sizing: border-box; }
|
|
332
|
+
body { margin:0; font:15px/1.5 system-ui,sans-serif; padding:2rem; max-width:64rem; margin-inline:auto; }
|
|
333
|
+
.pc-empty { opacity:.6; }
|
|
334
|
+
.pc-heading { font-size:1.6rem; font-weight:650; margin:0 0 .25rem; }
|
|
335
|
+
.pc-sub { opacity:.7; margin:.25rem 0 1rem; }
|
|
336
|
+
.pc-body { margin:.5rem 0; }
|
|
337
|
+
.pc-card { border:1px solid var(--pc-edge); border-radius:.6rem; padding:1rem 1.15rem; margin:1rem 0; }
|
|
338
|
+
.pc-card h2 { font-size:1rem; margin:0 0 .75rem; }
|
|
339
|
+
.pc-field { display:flex; flex-direction:column; gap:.25rem; margin-bottom:.6rem; }
|
|
340
|
+
.pc-field label { font-size:.8rem; opacity:.75; }
|
|
341
|
+
.pc-field input { padding:.5rem .6rem; border:1px solid var(--pc-edge); border-radius:.4rem; font:inherit; }
|
|
342
|
+
.pc-btn { padding:.5rem .9rem; border:0; border-radius:.4rem; background:var(--pc-accent); color:#fff; font:inherit; cursor:pointer; }
|
|
343
|
+
.pc-btn:disabled { opacity:.5; cursor:default; }
|
|
344
|
+
.pc-msg { font-size:.85rem; margin-top:.5rem; min-height:1.2em; }
|
|
345
|
+
.pc-msg.err { color:#c0392b; }
|
|
346
|
+
.pc-msg.ok { color:#2b8a3e; }
|
|
347
|
+
table.pc-grid { width:100%; border-collapse:collapse; font-size:.9rem; }
|
|
348
|
+
table.pc-grid th, table.pc-grid td { text-align:left; padding:.4rem .6rem; border-bottom:1px solid var(--pc-edge); }
|
|
349
|
+
table.pc-grid th { font-weight:600; opacity:.75; }
|
|
350
|
+
.pc-tabs { display:flex; gap:.5rem; margin-bottom:.75rem; }
|
|
351
|
+
.pc-tab { padding:.35rem .8rem; border:1px solid var(--pc-edge); border-radius:.4rem; background:transparent; color:inherit; font:inherit; cursor:pointer; }
|
|
352
|
+
.pc-tab.active { background:var(--pc-accent); color:#fff; border-color:var(--pc-accent); }
|
|
353
|
+
.pc-btn-sm { padding:.25rem .55rem; font-size:.8rem; margin-right:.3rem; }
|
|
354
|
+
.pc-chevron { background:transparent; color:inherit; border:1px solid var(--pc-edge); }
|
|
355
|
+
.pc-row-actions { white-space:nowrap; text-align:right; }
|
|
356
|
+
.pc-detail { padding:.75rem .25rem; }
|
|
357
|
+
.pc-detail-field { display:flex; gap:.5rem; font-size:.85rem; margin:.15rem 0; }
|
|
358
|
+
.pc-detail-label { opacity:.7; min-width:8rem; }
|
|
359
|
+
.pc-link { color:var(--pc-accent); }
|
|
360
|
+
.pc-child { margin:.6rem 0; }
|
|
361
|
+
.pc-child-title { font-size:.8rem; font-weight:600; opacity:.7; margin-bottom:.25rem; }
|
|
362
|
+
.pc-transcript { white-space:pre-wrap; max-height:22rem; overflow:auto; background:rgba(120,120,160,.08); padding:.5rem; border-radius:.4rem; font-size:.8rem; margin-top:.4rem; }
|
|
363
|
+
.pc-subform { margin-top:.75rem; padding:.6rem; border:1px dashed var(--pc-edge); border-radius:.5rem; }
|
|
364
|
+
.pc-subform-title { font-weight:600; font-size:.85rem; margin-bottom:.4rem; }
|
|
365
|
+
.pc-prompt { font-size:.85rem; opacity:.8; margin-bottom:.4rem; white-space:pre-wrap; }
|
|
366
|
+
.pc-textarea { width:100%; min-height:4rem; padding:.5rem; border:1px solid var(--pc-edge); border-radius:.4rem; font:inherit; }
|
|
367
|
+
`;
|
|
368
|
+
|
|
369
|
+
// The schema-driven browser renderer (ADR 0042 §3). Plain ES module string served at
|
|
370
|
+
// /app/runtime.js — it does NOT ship Craft.js (authoring is console-side only). It
|
|
371
|
+
// fetches the home page's page.json and renders text / actionForm / dataGrid nodes,
|
|
372
|
+
// wiring actionForm → /app/actions/start and dataGrid → /app/data (with a refresh).
|
|
373
|
+
const RENDERER_JS = String.raw`
|
|
374
|
+
const root = document.getElementById("page");
|
|
375
|
+
const HOME = root.dataset.home || "home";
|
|
376
|
+
|
|
377
|
+
async function getJSON(url, opts) {
|
|
378
|
+
const r = await fetch(url, opts);
|
|
379
|
+
const body = await r.json().catch(() => ({}));
|
|
380
|
+
if (!r.ok) throw new Error(body.error || ("HTTP " + r.status));
|
|
381
|
+
return body;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function el(tag, attrs = {}, ...kids) {
|
|
385
|
+
const n = document.createElement(tag);
|
|
386
|
+
for (const [k, v] of Object.entries(attrs)) {
|
|
387
|
+
if (k === "class") n.className = v;
|
|
388
|
+
else if (k.startsWith("on") && typeof v === "function") n.addEventListener(k.slice(2), v);
|
|
389
|
+
else if (v != null) n.setAttribute(k, v);
|
|
390
|
+
}
|
|
391
|
+
for (const kid of kids) n.append(kid);
|
|
392
|
+
return n;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function renderText(node) {
|
|
396
|
+
const v = node.props.variant;
|
|
397
|
+
const cls = v === "heading" ? "pc-heading" : v === "sub" ? "pc-sub" : "pc-body";
|
|
398
|
+
return el(v === "heading" ? "h1" : "p", { class: cls }, node.props.text || "");
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function renderActionForm(node) {
|
|
402
|
+
const p = node.props;
|
|
403
|
+
const card = el("section", { class: "pc-card" });
|
|
404
|
+
if (p.title) card.append(el("h2", {}, p.title));
|
|
405
|
+
const inputs = {};
|
|
406
|
+
for (const f of p.fields || []) {
|
|
407
|
+
const input = el("input", { type: "text", placeholder: f.label || f.key });
|
|
408
|
+
inputs[f.key] = input;
|
|
409
|
+
card.append(el("div", { class: "pc-field" }, el("label", {}, f.label || f.key), input));
|
|
410
|
+
}
|
|
411
|
+
const msg = el("p", { class: "pc-msg" });
|
|
412
|
+
const btn = el("button", { class: "pc-btn" }, p.submitLabel || "Submit");
|
|
413
|
+
btn.addEventListener("click", async () => {
|
|
414
|
+
const variables = {};
|
|
415
|
+
for (const [k, input] of Object.entries(inputs)) variables[k] = input.value;
|
|
416
|
+
btn.disabled = true; msg.className = "pc-msg"; msg.textContent = "Submitting…";
|
|
417
|
+
try {
|
|
418
|
+
const res = await getJSON("/app/actions/start/" + encodeURIComponent(p.action.process),
|
|
419
|
+
{ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ variables }) });
|
|
420
|
+
msg.className = "pc-msg ok";
|
|
421
|
+
msg.textContent = "Started (instance " + (res.processInstanceKey ?? "?") + ")";
|
|
422
|
+
for (const input of Object.values(inputs)) input.value = "";
|
|
423
|
+
document.dispatchEvent(new CustomEvent("pc:refresh"));
|
|
424
|
+
} catch (e) {
|
|
425
|
+
msg.className = "pc-msg err"; msg.textContent = String(e.message || e);
|
|
426
|
+
} finally { btn.disabled = false; }
|
|
427
|
+
});
|
|
428
|
+
card.append(btn, msg);
|
|
429
|
+
return card;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function renderDataGrid(node) {
|
|
433
|
+
const p = node.props;
|
|
434
|
+
const card = el("section", { class: "pc-card" });
|
|
435
|
+
if (p.title) card.append(el("h2", {}, p.title));
|
|
436
|
+
const cols = p.columns || [];
|
|
437
|
+
const tabs = p.tabs || [];
|
|
438
|
+
const rowActions = p.rowActions || [];
|
|
439
|
+
const detail = p.detail || null;
|
|
440
|
+
const hasExtra = rowActions.length > 0 || detail != null;
|
|
441
|
+
let activeFilter = p.data.filter || [];
|
|
442
|
+
|
|
443
|
+
if (tabs.length) {
|
|
444
|
+
const bar = el("div", { class: "pc-tabs" });
|
|
445
|
+
activeFilter = tabs[0].filter || [];
|
|
446
|
+
tabs.forEach((t, i) => {
|
|
447
|
+
const b = el("button", { class: "pc-tab" + (i === 0 ? " active" : "") }, t.label);
|
|
448
|
+
b.addEventListener("click", () => {
|
|
449
|
+
activeFilter = t.filter || [];
|
|
450
|
+
for (const c of bar.children) c.classList.remove("active");
|
|
451
|
+
b.classList.add("active");
|
|
452
|
+
refresh();
|
|
453
|
+
});
|
|
454
|
+
bar.append(b);
|
|
455
|
+
});
|
|
456
|
+
card.append(bar);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const headCells = cols.map((c) => el("th", {}, c.header || c.field));
|
|
460
|
+
if (hasExtra) headCells.push(el("th", {}, ""));
|
|
461
|
+
const thead = el("thead", {}, el("tr", {}, ...headCells));
|
|
462
|
+
const tbody = el("tbody", {});
|
|
463
|
+
const table = el("table", { class: "pc-grid" }, thead, tbody);
|
|
464
|
+
card.append(table);
|
|
465
|
+
const span = String((cols.length || 1) + (hasExtra ? 1 : 0));
|
|
466
|
+
|
|
467
|
+
function dataUrl(source, tbl, filters, order) {
|
|
468
|
+
let u = "/app/data/" + encodeURIComponent(source) + "/" + encodeURIComponent(tbl);
|
|
469
|
+
const qs = [];
|
|
470
|
+
for (const f of filters || []) {
|
|
471
|
+
if (Array.isArray(f.in)) qs.push("where=" + encodeURIComponent(f.field + ":in:" + f.in.join(",")));
|
|
472
|
+
else qs.push("where=" + encodeURIComponent(f.field + ":" + f.eq));
|
|
473
|
+
}
|
|
474
|
+
if (order && order.field) qs.push("order=" + encodeURIComponent(order.field + ":" + (order.dir || "asc")));
|
|
475
|
+
return qs.length ? u + "?" + qs.join("&") : u;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async function fireAction(action, row) {
|
|
479
|
+
if (action.kind === "cancelProcess") {
|
|
480
|
+
return getJSON("/app/actions/cancel", { method: "POST",
|
|
481
|
+
headers: { "content-type": "application/json" },
|
|
482
|
+
body: JSON.stringify({ processInstanceKey: row[action.keyField] }) });
|
|
483
|
+
}
|
|
484
|
+
if (action.kind === "publishMessage") {
|
|
485
|
+
return getJSON("/app/actions/message", { method: "POST",
|
|
486
|
+
headers: { "content-type": "application/json" },
|
|
487
|
+
body: JSON.stringify({ name: action.message, correlationKey: row[action.correlationKeyField],
|
|
488
|
+
variables: { ...(action.variables || {}) } }) });
|
|
489
|
+
}
|
|
490
|
+
if (action.kind === "startProcess") {
|
|
491
|
+
return getJSON("/app/actions/start/" + encodeURIComponent(action.process), { method: "POST",
|
|
492
|
+
headers: { "content-type": "application/json" },
|
|
493
|
+
body: JSON.stringify({ variables: { ...(action.variables || {}) } }) });
|
|
494
|
+
}
|
|
495
|
+
throw new Error("unknown action");
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function rowActionButton(row, ra) {
|
|
499
|
+
if (ra.showWhenField && !row[ra.showWhenField]) return null;
|
|
500
|
+
const b = el("button", { class: "pc-btn pc-btn-sm" }, ra.label);
|
|
501
|
+
b.addEventListener("click", async (ev) => {
|
|
502
|
+
ev.stopPropagation();
|
|
503
|
+
if (ra.confirm && !confirm(ra.confirm)) return;
|
|
504
|
+
b.disabled = true;
|
|
505
|
+
try {
|
|
506
|
+
await fireAction(ra.action, row);
|
|
507
|
+
document.dispatchEvent(new CustomEvent("pc:refresh"));
|
|
508
|
+
} catch (e) {
|
|
509
|
+
b.disabled = false;
|
|
510
|
+
alert(String(e.message || e));
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
return b;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
function detailForm(row) {
|
|
517
|
+
const f = detail.form;
|
|
518
|
+
if (!f || !row[f.showWhenField]) return null;
|
|
519
|
+
const box = el("div", { class: "pc-subform" });
|
|
520
|
+
if (f.title) box.append(el("div", { class: "pc-subform-title" }, f.title));
|
|
521
|
+
if (f.promptField && row[f.promptField] != null) {
|
|
522
|
+
box.append(el("div", { class: "pc-prompt" }, String(row[f.promptField])));
|
|
523
|
+
}
|
|
524
|
+
const input = el("textarea", { class: "pc-textarea", placeholder: f.inputLabel || f.inputKey });
|
|
525
|
+
const msg = el("p", { class: "pc-msg" });
|
|
526
|
+
const btn = el("button", { class: "pc-btn pc-btn-sm" }, f.submitLabel || "Submit");
|
|
527
|
+
btn.addEventListener("click", async () => {
|
|
528
|
+
btn.disabled = true; msg.className = "pc-msg"; msg.textContent = "Sending…";
|
|
529
|
+
try {
|
|
530
|
+
await getJSON("/app/actions/message", { method: "POST",
|
|
531
|
+
headers: { "content-type": "application/json" },
|
|
532
|
+
body: JSON.stringify({ name: f.action.message, correlationKey: row[f.action.correlationKeyField],
|
|
533
|
+
variables: { [f.inputKey]: input.value, ...(f.action.variables || {}) } }) });
|
|
534
|
+
msg.className = "pc-msg ok"; msg.textContent = "Sent";
|
|
535
|
+
document.dispatchEvent(new CustomEvent("pc:refresh"));
|
|
536
|
+
} catch (e) {
|
|
537
|
+
btn.disabled = false; msg.className = "pc-msg err"; msg.textContent = String(e.message || e);
|
|
538
|
+
}
|
|
539
|
+
});
|
|
540
|
+
box.append(el("div", { class: "pc-field" }, input), btn, msg);
|
|
541
|
+
return box;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
async function childGrid(cg, row) {
|
|
545
|
+
const wrap = el("div", { class: "pc-child" });
|
|
546
|
+
if (cg.title) wrap.append(el("div", { class: "pc-child-title" }, cg.title));
|
|
547
|
+
const ccols = cg.columns || [];
|
|
548
|
+
const cbody = el("tbody", {});
|
|
549
|
+
const ctable = el("table", { class: "pc-grid" },
|
|
550
|
+
el("thead", {}, el("tr", {}, ...ccols.map((c) => el("th", {}, c.header || c.field)),
|
|
551
|
+
...(cg.lazyField ? [el("th", {}, "")] : []))), cbody);
|
|
552
|
+
wrap.append(ctable);
|
|
553
|
+
try {
|
|
554
|
+
const { rows } = await getJSON(dataUrl(cg.source || "app", cg.table,
|
|
555
|
+
[{ field: cg.childField, eq: row[cg.parentField] }], cg.orderBy));
|
|
556
|
+
const cspan = String((ccols.length || 1) + (cg.lazyField ? 1 : 0));
|
|
557
|
+
if (!rows.length) {
|
|
558
|
+
cbody.append(el("tr", {}, el("td", { colspan: cspan }, "None")));
|
|
559
|
+
}
|
|
560
|
+
for (const cr of rows) {
|
|
561
|
+
const cells = ccols.map((c) => el("td", {}, cr[c.field] == null ? "" : String(cr[c.field])));
|
|
562
|
+
if (cg.lazyField) {
|
|
563
|
+
const lf = cg.lazyField;
|
|
564
|
+
const has = cr[lf.field] != null && String(cr[lf.field]).trim() !== "";
|
|
565
|
+
const cell = el("td", {});
|
|
566
|
+
if (has) {
|
|
567
|
+
const toggle = el("button", { class: "pc-btn pc-btn-sm" }, lf.label || "Show");
|
|
568
|
+
const pre = el("pre", { class: "pc-transcript", hidden: "" });
|
|
569
|
+
pre.textContent = String(cr[lf.field]);
|
|
570
|
+
toggle.addEventListener("click", () => {
|
|
571
|
+
pre.hidden = !pre.hidden;
|
|
572
|
+
toggle.textContent = pre.hidden ? (lf.label || "Show") : "Hide";
|
|
573
|
+
});
|
|
574
|
+
cell.append(toggle, pre);
|
|
575
|
+
}
|
|
576
|
+
cells.push(cell);
|
|
577
|
+
}
|
|
578
|
+
cbody.append(el("tr", {}, ...cells));
|
|
579
|
+
}
|
|
580
|
+
} catch (e) {
|
|
581
|
+
cbody.append(el("tr", {}, el("td", { colspan: cspan }, String(e.message || e))));
|
|
582
|
+
}
|
|
583
|
+
return wrap;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function detailPanel(row) {
|
|
587
|
+
const box = el("div", { class: "pc-detail" });
|
|
588
|
+
if (detail.linkField && row[detail.linkField]) {
|
|
589
|
+
const href = String(row[detail.linkField]);
|
|
590
|
+
// Render as a link only for http(s); anything else (e.g. a javascript: URL
|
|
591
|
+
// smuggled through row data) is shown as inert text. External links get
|
|
592
|
+
// rel="noopener noreferrer" so the opened page can't reach window.opener.
|
|
593
|
+
if (/^https?:\/\//i.test(href)) {
|
|
594
|
+
box.append(el("a", { class: "pc-link", href, target: "_blank", rel: "noopener noreferrer" }, href));
|
|
595
|
+
} else {
|
|
596
|
+
box.append(el("span", { class: "pc-link" }, href));
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
for (const df of detail.fields || []) {
|
|
600
|
+
box.append(el("div", { class: "pc-detail-field" },
|
|
601
|
+
el("span", { class: "pc-detail-label" }, df.label || df.field),
|
|
602
|
+
el("span", {}, row[df.field] == null ? "" : String(row[df.field]))));
|
|
603
|
+
}
|
|
604
|
+
for (const cg of detail.children || []) {
|
|
605
|
+
const holder = el("div", {});
|
|
606
|
+
box.append(holder);
|
|
607
|
+
childGrid(cg, row).then((w) => holder.replaceChildren(w));
|
|
608
|
+
}
|
|
609
|
+
const form = detailForm(row);
|
|
610
|
+
if (form) box.append(form);
|
|
611
|
+
return box;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function renderRow(row) {
|
|
615
|
+
const cells = cols.map((c) => el("td", {}, row[c.field] == null ? "" : String(row[c.field])));
|
|
616
|
+
let toggle = null;
|
|
617
|
+
if (hasExtra) {
|
|
618
|
+
const actionCell = el("td", { class: "pc-row-actions" });
|
|
619
|
+
if (detail) {
|
|
620
|
+
toggle = el("button", { class: "pc-btn pc-btn-sm pc-chevron" }, "▸");
|
|
621
|
+
actionCell.append(toggle);
|
|
622
|
+
}
|
|
623
|
+
for (const ra of rowActions) {
|
|
624
|
+
const b = rowActionButton(row, ra);
|
|
625
|
+
if (b) actionCell.append(b);
|
|
626
|
+
}
|
|
627
|
+
cells.push(actionCell);
|
|
628
|
+
}
|
|
629
|
+
const tr = el("tr", {}, ...cells);
|
|
630
|
+
tbody.append(tr);
|
|
631
|
+
if (detail && toggle) {
|
|
632
|
+
const dtr = el("tr", { hidden: "" }, el("td", { colspan: span }));
|
|
633
|
+
let built = false;
|
|
634
|
+
toggle.addEventListener("click", (ev) => {
|
|
635
|
+
ev.stopPropagation();
|
|
636
|
+
const open = dtr.hidden;
|
|
637
|
+
dtr.hidden = !open;
|
|
638
|
+
toggle.textContent = open ? "▾" : "▸";
|
|
639
|
+
if (open && !built) {
|
|
640
|
+
built = true;
|
|
641
|
+
dtr.firstChild.append(detailPanel(row));
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
tbody.append(dtr);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
async function refresh() {
|
|
649
|
+
try {
|
|
650
|
+
const { rows } = await getJSON(dataUrl(p.data.source, p.data.table, activeFilter, p.data.orderBy));
|
|
651
|
+
tbody.replaceChildren();
|
|
652
|
+
for (const row of rows) renderRow(row);
|
|
653
|
+
if (!rows.length) tbody.append(el("tr", {}, el("td", { colspan: span }, "No rows")));
|
|
654
|
+
} catch (e) {
|
|
655
|
+
tbody.replaceChildren(el("tr", {}, el("td", { colspan: span }, String(e.message || e))));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
document.addEventListener("pc:refresh", refresh);
|
|
659
|
+
if (p.refreshMs && p.refreshMs > 0) setInterval(refresh, p.refreshMs);
|
|
660
|
+
refresh();
|
|
661
|
+
return card;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const RENDERERS = { text: renderText, actionForm: renderActionForm, dataGrid: renderDataGrid };
|
|
665
|
+
|
|
666
|
+
async function main() {
|
|
667
|
+
try {
|
|
668
|
+
const doc = await getJSON("/app/pages/" + encodeURIComponent(HOME));
|
|
669
|
+
if (doc.title) document.title = doc.title;
|
|
670
|
+
root.replaceChildren(...(doc.nodes || []).map((n) => (RENDERERS[n.type] || (() => el("div")))(n)));
|
|
671
|
+
} catch (e) {
|
|
672
|
+
root.replaceChildren(el("p", { class: "pc-msg err" }, "Failed to load page: " + String(e.message || e)));
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
main();
|
|
676
|
+
`;
|