@nanobpm/urban 0.97.0 → 0.98.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -331,6 +331,34 @@ deploy-time string substitution (`{{name}}` templating has been removed).
331
331
  > model per environment. Pass the value as a process variable and reference it
332
332
  > with FEEL instead.
333
333
 
334
+ ### Task forms — what the `taskInbox` (and pages `engineForm`) renders
335
+
336
+ A user task linked to a deployed `.form` is rendered by the ONE shared form-js
337
+ renderer (`NanoFormJs`) in both human surfaces — the `taskInbox` page and a
338
+ pages `dataGrid` `detail.engineForm` drawer. When a task is opened, the surface
339
+ also loads the task's **variables** (the engine's variables search by the task's
340
+ process instance) and passes them to the renderer as its **context**, so a
341
+ reviewer sees what they are reviewing.
342
+
343
+ The context holds only **process-level** variables (task-local variables of
344
+ other element instances are excluded, so a sibling task's value can never leak
345
+ in) and omits **truncated** previews (so a clipped value is never prefilled and
346
+ resubmitted over the original). Lookups use the context's own properties only.
347
+
348
+ Supported form-js components:
349
+
350
+ | Component | Behaviour |
351
+ | --- | --- |
352
+ | `text` | Static paragraph; `{{name}}` placeholders interpolate from the context (objects as JSON, unknown names empty). Rendered as **text only** — a variable holding markup renders literally, never as HTML. |
353
+ | `image` | `<img class="njf-image">` (max-width 100%). `source` is a literal URL or `=varName` (a plain variable reference — full FEEL is not evaluated). Only `http(s):` URLs, app-relative paths, and `data:image/(png|jpeg|gif|webp)` URLs are allowed (the data-URL mediatype may be followed directly by `,` — parameters and `;base64` are optional); anything else (`javascript:`, other schemes, protocol-relative, or any URL containing whitespace, control characters, or backslashes) renders nothing. A root-relative source (`/app/…`) is rebased onto the app's mount root, so it resolves correctly behind the console's path-prefixed proxy; the allowlist is re-checked on the **rebased** URL, and only an `http(s)`/same-origin result is ever set — a resolver output that comes back as a forbidden or non-fetchable scheme renders nothing. `alt` sets the alt text. |
354
+ | `textfield` / `textarea` / `number` / `datetime` | Keyed inputs; submitted as the completion `variables[key]`. A key present in the context **prefills** the input; clearing a prefilled input submits an empty string (an explicit clear), while a never-prefilled blank input is omitted. A prefill the control cannot hold (e.g. a timezone-bearing timestamp in a `datetime` field) counts as **no prefill** — an untouched submit omits the key rather than overwriting the variable with `""`. |
355
+ | `select` / `radio` | Keyed choice inputs from `values[]`; prefilled when the context value matches an option. Choosing a select's blank option after a prefill submits an empty string. A context value matching **no** option counts as no prefill — an untouched submit omits the key. |
356
+ | `checkbox` | Keyed boolean; pre-checked when the context value is `true`. |
357
+ | other / keyless layout components | Skipped. |
358
+
359
+ Forms with no templating, images, or matching context keys render exactly as
360
+ before — the context is additive.
361
+
334
362
  ### Triggers — the inbound I/O edge
335
363
 
336
364
  Declare `triggers[]` in the app manifest to turn outside events into engine
@@ -2,4 +2,4 @@
2
2
  // Source: src/runtime/browser/formjs.browser.js (the shared, type-checked/linted/tested
3
3
  // form-js renderer). Regenerate with `npm run gen:runtime`; CI enforces this file
4
4
  // is byte-identical to a fresh generation via `git diff --exit-code` (npm run check:runtime).
5
- export const FORMJS_JS = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * @param {any} c\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c) {\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n return { field: fjEl(\"p\", { class: \"njf-text\" }, typeof c.text === \"string\" ? c.text : \"\") };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n for (const o of Array.isArray(c.values) ? c.values : []) {\n input.appendChild(fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value)));\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n return sel ? { key, value: sel.value } : null;\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n if (raw === \"\" || raw == null) return null;\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button.\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c);\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
5
+ export const FORMJS_JS = "// @ts-check\n// ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────\n// This is the ONE client implementation of \"render a deployed `.form`'s form-js\n// schema and collect its field values\", shared verbatim by BOTH:\n// • the `taskInbox` surface (surfaces.ts `inboxPage`), and\n// • the pages `dataGrid` engine-form detail (runtime.browser.js).\n// It used to live inline in surfaces.ts; factoring it here means the two surfaces\n// can never fork the renderer or drift on how a form-js component maps to an input\n// and its submitted value.\n//\n// Like the rest of the browser runtime it is authored/type-checked/linted/tested\n// as real source and served as a generated string artifact (formjs.gen.ts, emitted\n// by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch\n// is inside a function — so it is import-safe under Node/Deno for unit testing.\n//\n// SECURITY: every value the engine returns is placed via textContent / setAttribute\n// (never innerHTML), so nothing in the form schema can inject markup. The submitted\n// `variables` bag is null-prototype so an engine-supplied component key of\n// `__proto__`/`constructor` lands as a plain own property and can never mutate a\n// prototype (prototype-pollution class).\n//\n// VARIABLES CONTEXT (#603): both surfaces pass the task's variables as the render\n// `context`. `text` components interpolate `{{name}}` against it (textContent-only,\n// never markup), `image` components resolve a `=varName` source from it, and a\n// keyed input whose key is present is prefilled — the form-js/Camunda Tasklist\n// behaviour, so a reviewer sees what they are reviewing.\n\n/** Create an element, setting attributes via setAttribute and text via textContent only.\n * @param {string} tag\n * @param {Record<string, string>} [attrs]\n * @param {string} [text]\n * @returns {any}\n */\nfunction fjEl(tag, attrs, text) {\n const e = document.createElement(tag);\n if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);\n if (text != null) e.textContent = text;\n return e;\n}\n\n/** A plain type=\"button\" with an optional click handler.\n * @param {string} label\n * @param {(() => void) | null} [onClick]\n * @returns {any}\n */\nfunction fjBtn(label, onClick) {\n const b = document.createElement(\"button\");\n b.type = \"button\";\n b.textContent = label;\n if (onClick) b.addEventListener(\"click\", onClick);\n return b;\n}\n\n/** Interpolate `{{name}}` placeholders in a `text` component against the render\n * context (the task's variables), following form-js/Camunda Tasklist. A present\n * value is stringified (objects/arrays as JSON); an unknown name becomes the empty\n * string. The result is placed via textContent only — a variable holding markup\n * (`<img onerror=…>`) renders as literal text, never as HTML (the XSS rule holds\n * for templated text exactly as for static text).\n * @param {string} text\n * @param {Record<string, any>} context\n * @returns {string}\n */\nfunction fjTemplate(text, context) {\n return text.replace(/\\{\\{\\s*([^{}\\s]+)\\s*\\}\\}/g, (_m, name) => {\n const v = context[name];\n if (v == null) return \"\";\n return typeof v === \"string\" ? v : JSON.stringify(v);\n });\n}\n\n/** Copy only the context's OWN enumerable properties into a null-prototype\n * dictionary, so lookups like `ctx[\"constructor\"]` or `ctx[\"__proto__\"]` never\n * resolve to inherited members (which would template/prefill bogus values), while\n * an explicitly supplied own value with such a name is still honoured.\n * @param {any} context\n * @returns {Record<string, any>}\n */\nfunction fjOwnContext(context) {\n /** @type {Record<string, any>} */\n const out = Object.create(null);\n if (context == null || typeof context !== \"object\") return out;\n for (const k of Object.keys(context)) {\n Object.defineProperty(out, k, { value: context[k], enumerable: true, writable: true, configurable: true });\n }\n return out;\n}\n\n/** The image-source allowlist, applied to BOTH the raw source and — when a\n * `resolveUrl` rewrote it — the RESOLVED URL. A resolver is same-origin trusted\n * code, but it TRANSFORMS the string (the pages runtime's `apiUrl` strips the\n * leading slash before `new URL(...)`), and a transformation can mint a forbidden\n * shape from an accepted one: a root-prefixed script-scheme path passes below as\n * an app-relative path (the leading slash defeats the scheme check), then\n * resolves to the bare forbidden-scheme URL. Re-running the allowlist on the\n * resolver's result closes that laundering class at the single choke point every\n * surface flows through, so no resolver — present or future — can widen the\n * accepted set.\n * @param {string} url\n * @returns {string | null} the URL when allowed, null when rejected\n */\nfunction fjAllowImageUrl(url) {\n // Browsers strip/normalise whitespace and control characters and treat `\\` as\n // `/` before interpreting a URL, so `java\\tscript:` or ` data:image/svg+xml` or\n // `/\\\\host` could slip past the allowlist below. Fail closed on any of them.\n if (/[\\s\\u0000-\\u001f\\u007f\\\\]/.test(url)) return null;\n // data:image — RFC 2397 lets the mediatype be followed directly by `,`\n // (parameters and `;base64` are both optional), so accept `;` OR `,` after the\n // subtype or a percent-encoded payload silently never renders.\n if (/^data:image\\/(png|jpeg|gif|webp)[;,]/i.test(url)) return url;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) {\n // A scheme: only http(s) is allowed (javascript:/data-text-html/etc. rejected).\n return /^https?:\\/\\//i.test(url) ? url : null;\n }\n if (url.startsWith(\"//\")) return null; // protocol-relative → off-origin, reject\n return url; // app-relative path\n}\n\n/** Resolve an `image` component's `source` to a URL the renderer will put on the\n * <img>, or null to reject it. `source` is either a literal URL or `=varName` — a\n * PLAIN variable reference into the render context (full FEEL is intentionally not\n * supported: anything after `=` that is not a bare identifier is rejected). Only\n * `http(s):` URLs, app-relative paths (no scheme, no `//host` protocol-relative),\n * and `data:image/(png|jpeg|gif|webp)` URLs are allowed — never `javascript:` or\n * any other scheme. The URL is set with setAttribute (never innerHTML).\n * `resolveUrl`, when supplied, rewrites an ACCEPTED URL just before it is set —\n * both surfaces pass their app-mount-aware resolver (the pages runtime's `apiUrl`,\n * the inbox page's mount prefix) so a root-relative `/app/…` source requests the\n * app's own path even behind the console's path-prefixed proxy. The allowlist runs\n * on the raw source AND again on the resolver's result (see fjAllowImageUrl), so a\n * resolver can never launder a rejected URL — including one it minted itself by\n * rebasing a disguised path.\n * @param {any} source\n * @param {Record<string, any>} context\n * @param {(url: string) => string} [resolveUrl]\n * @returns {string | null}\n */\nfunction fjImageSrc(source, context, resolveUrl) {\n let url = source;\n if (typeof url === \"string\" && url.startsWith(\"=\")) {\n const name = url.slice(1).trim();\n // A plain variable reference only — reject anything that isn't a bare\n // identifier (a FEEL expression, a call, a path) rather than evaluating it.\n if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return null;\n url = context[name];\n }\n if (typeof url !== \"string\" || url === \"\") return null;\n const allowed = fjAllowImageUrl(url);\n if (allowed == null) return null;\n // App-relative path. A root-relative one (\"/app/…\") is only correct when the app\n // is served at the origin root; behind the console's path-prefixed proxy it must\n // be rebased onto the app mount (the resolver both surfaces pass). Absolute\n // http(s)/data: URLs pass through untouched (the resolvers only rewrite\n // single-leading-slash paths), but revalidate the result regardless — a resolver\n // that strips the leading slash (the pages `apiUrl`) turns \"/javascript:…\" into\n // a forbidden-scheme URL, which must not reach the <img>.\n if (!resolveUrl) return allowed;\n // A resolver can THROW on an allowlist-accepted source: the pages `apiUrl`\n // strips the leading slash and calls `new URL(...)`, which throws `Invalid URL`\n // on a path that is not URL-path-shaped (e.g. \"/http://\"). Uncaught, that\n // exception escapes buildField and the WHOLE task form fails to render. A\n // failed resolution rejects just this image (null), exactly like a resolver\n // that returned a rejected URL.\n let resolved;\n try {\n resolved = resolveUrl(allowed);\n } catch {\n return null;\n }\n if (typeof resolved !== \"string\" || resolved === \"\") return null;\n // Re-run the SAME allowlist on the resolver's output (one source of truth):\n // app-relative paths, http(s) and data:image survive; a forbidden scheme the\n // resolver minted (e.g. \"/javascript:…\" stripped to \"javascript:…\"), a file:\n // URL, or a protocol-relative URL is rejected.\n return fjAllowImageUrl(resolved);\n}\n\n/** The value a keyed input is prefilled with when its key is present in the render\n * context (form-js prefill semantics): strings as-is, other scalars stringified,\n * objects/arrays as JSON. `undefined`/`null` mean \"no prefill\".\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {string | undefined}\n */\nfunction fjPrefill(context, key) {\n const v = context[key];\n if (v == null) return undefined;\n return typeof v === \"string\" ? v : typeof v === \"object\" ? JSON.stringify(v) : String(v);\n}\n\n/** The prefill pair for a keyed input: `display` is the string the control shows\n * (fjPrefill's rendering); `original` is the context value itself, captured at\n * prefill time. An UNTOUCHED control — one that still shows exactly `display` —\n * submits `original`, never `display`: the completion endpoint forwards submitted\n * values verbatim, so forwarding the stringified rendering would retype the\n * variable (a prefilled `{ approved: true }` textarea would overwrite the object\n * with the STRING '{\"approved\":true}'; a numeric select/radio prefill would\n * overwrite the number with \"1\"). Once the operator changes the control away\n * from `display` the edited string (or its number coercion) submits instead.\n * @param {Record<string, any>} context\n * @param {string} key\n * @returns {{ display: string, original: any } | undefined}\n */\nfunction fjPrefillPair(context, key) {\n const display = fjPrefill(context, key);\n return display === undefined ? undefined : { display, original: context[key] };\n}\n\n/** Build one form-js component into its field element and (for keyed inputs) a reader\n * that returns the entered `{ key, value }` or null when blank. Static (keyless)\n * components render as inert text; layout-only components are skipped (null).\n * `context` carries the task's variables: `text` components interpolate `{{name}}`\n * against it, `image` components resolve a `=varName` source from it, and a keyed\n * input whose key is present is prefilled with its value.\n * @param {any} c\n * @param {Record<string, any>} [context]\n * @param {{ resolveUrl?: (url: string) => string }} [opts]\n * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}\n */\nfunction buildField(c, context, opts) {\n const ctx = fjOwnContext(context);\n const type = c && c.type;\n // Static (keyless) components: show text as a paragraph, ignore layout-only ones.\n if (type === \"text\") {\n const raw = typeof c.text === \"string\" ? c.text : \"\";\n return { field: fjEl(\"p\", { class: \"njf-text\" }, fjTemplate(raw, ctx)) };\n }\n // An image component (form-js `{ type: \"image\", source, alt }`) — keyless, renders\n // an <img> whose src is resolved + scheme-gated by fjImageSrc. A rejected/absent\n // source renders nothing (null) rather than a broken or unsafe <img>.\n if (type === \"image\") {\n const src = fjImageSrc(c.source, ctx, opts && opts.resolveUrl);\n if (src == null) return null;\n const attrs = { class: \"njf-image\", src, alt: typeof c.alt === \"string\" ? c.alt : \"\" };\n return { field: fjEl(\"img\", attrs) };\n }\n const key = c && c.key;\n if (!key) return null;\n const wrap = fjEl(\"div\", { class: \"njf-field\" });\n const label = typeof c.label === \"string\" && c.label ? c.label : key;\n if (type === \"checkbox\") {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n // Prefill: a boolean context value checks the box.\n if (ctx[key] === true) input.checked = true;\n const lab = fjEl(\"label\", {});\n lab.appendChild(input);\n lab.appendChild(document.createTextNode(\" \" + label));\n wrap.appendChild(lab);\n return { field: wrap, read: () => ({ key, value: input.checked }) };\n }\n const labelEl = fjEl(\"label\", {}, label);\n wrap.appendChild(labelEl);\n let input;\n // Was this field prefilled from the context — AND did the control ACCEPT the\n // value? Only a successful prefill counts: a prefilled field the operator CLEARS\n // (empties the text input, picks the blank select option) must submit an empty\n // string — returning null would omit the key and silently leave the original\n // variable unchanged. But a REJECTED prefill (a select value matching no option,\n // a timezone-bearing timestamp a datetime-local control blanks) leaves the\n // control empty through no operator action; treating that as prefilled would\n // submit \"\" from an untouched form and overwrite the original variable. A\n // rejected prefill behaves like no prefill: blank means \"not entered\", so the\n // key is omitted.\n let prefilled = false;\n /** @type {{ display: string, original: any } | undefined} */\n let prefillPair;\n if (type === \"textarea\") {\n input = document.createElement(\"textarea\");\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n prefilled = true;\n }\n } else if (type === \"select\") {\n input = document.createElement(\"select\");\n input.appendChild(fjEl(\"option\", { value: \"\" }, \"\\u2014\"));\n prefillPair = fjPrefillPair(ctx, key);\n const pre = prefillPair === undefined ? undefined : prefillPair.display;\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const opt = fjEl(\"option\", { value: String(o.value) }, String(o.label != null ? o.label : o.value));\n // Prefill: mark the option matching the context value as selected.\n if (pre !== undefined && String(o.value) === pre) opt.setAttribute(\"selected\", \"\");\n input.appendChild(opt);\n }\n if (pre !== undefined) {\n input.value = pre;\n // The select ACCEPTS the prefill only when it matches a declared option —\n // otherwise the DOM snaps the value back to \"\" and the control sits blank.\n // Check acceptance structurally (against the option list), not by reading\n // the value back: the control must not be treated as prefilled when it\n // could not take the value, or an untouched submit would overwrite the\n // original variable with \"\".\n const accepted = (Array.isArray(c.values) ? c.values : []).some((/** @type {any} */ o) => String(o.value) === pre);\n prefilled = pre !== \"\" && accepted;\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n } else if (type === \"radio\") {\n const name = \"r\" + Math.random().toString(36).slice(2);\n const prefillRadio = fjPrefillPair(ctx, key);\n const pre = prefillRadio === undefined ? undefined : prefillRadio.display;\n const group = fjEl(\"div\", {});\n for (const o of Array.isArray(c.values) ? c.values : []) {\n const rlab = fjEl(\"label\", {});\n const r = document.createElement(\"input\");\n r.type = \"radio\";\n r.name = name;\n r.value = String(o.value);\n // Prefill: check the option matching the context value.\n if (pre !== undefined && r.value === pre) r.checked = true;\n rlab.appendChild(r);\n rlab.appendChild(document.createTextNode(\" \" + String(o.label != null ? o.label : o.value)));\n group.appendChild(rlab);\n }\n wrap.appendChild(group);\n return {\n field: wrap,\n read: () => {\n const sel = group.querySelector(\"input:checked\");\n if (!sel) return null;\n // Untouched (the checked option is still the prefill's): submit the\n // ORIGINAL value so a numeric prefill stays a number — the completion\n // endpoint forwards submitted values verbatim, and a radio option's\n // value is always a string.\n if (prefillRadio !== undefined && sel.value === prefillRadio.display) return { key, value: prefillRadio.original };\n return { key, value: sel.value };\n },\n };\n } else {\n input = document.createElement(\"input\");\n input.type = type === \"number\" ? \"number\" : type === \"datetime\" ? \"datetime-local\" : \"text\";\n prefillPair = fjPrefillPair(ctx, key);\n if (prefillPair !== undefined) {\n input.value = prefillPair.display;\n // A typed control (number/datetime-local) sanitizes a value it cannot hold\n // to \"\" — e.g. a timezone-bearing timestamp assigned to datetime-local. Only\n // a value that survived counts as a successful prefill.\n prefilled = input.value !== \"\";\n if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill\n }\n }\n // Associate the label with the input (for/id) so screen readers announce it on focus.\n const fieldId = \"f\" + Math.random().toString(36).slice(2);\n input.id = fieldId;\n labelEl.setAttribute(\"for\", fieldId);\n wrap.appendChild(input);\n const isNumber = type === \"number\";\n return {\n field: wrap,\n read: () => {\n const raw = input.value;\n // A prefilled field the operator cleared submits an empty string (an explicit\n // \"set this variable to empty\"), never an omission that would leave the\n // original value in place. A never-prefilled blank field is still omitted.\n if (raw === \"\" || raw == null) return prefilled ? { key, value: \"\" } : null;\n // Untouched (the control still shows exactly the prefill's rendering):\n // submit the ORIGINAL context value, never the stringified display — the\n // completion endpoint forwards submitted values verbatim, so the string\n // would retype the variable (an object prefill would become its JSON\n // string; a numeric prefill would become \"3\"). Once the operator changes\n // the control away from the prefill, the edited value submits below.\n if (prefillPair !== undefined && raw === prefillPair.display) return { key, value: prefillPair.original };\n if (isNumber) {\n const n = Number(raw);\n // A non-numeric value in a number field is only reachable via tampering (the browser\n // blanks invalid type=number input). Treat it as absent rather than silently submitting\n // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.\n return Number.isFinite(n) ? { key, value: n } : null;\n }\n return { key, value: raw };\n },\n };\n}\n\n/**\n * Render a form-js schema into a `<form>` element with a submit + optional cancel.\n * On submit it assembles every keyed field's value into one null-prototype\n * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables\n * the button so the operator can retry. `opts.onCancel`, when supplied, wires a\n * cancel button. `opts.context` carries the task's variables — `{{name}}` text\n * templating, `=varName` image sources, and keyed-input prefill all resolve\n * against it (see buildField). `opts.resolveUrl`, when supplied, rewrites each\n * ACCEPTED image source before it is set — both surfaces pass their app-mount-aware\n * resolver so a root-relative `/app/…` image survives the console's path-prefixed\n * proxy (see fjImageSrc).\n * @param {any} schema the parsed form-js document (`{ components: [...] }`)\n * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,\n * context?: Record<string, any>,\n * resolveUrl?: (url: string) => string,\n * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),\n * onCancel?: () => void }} opts\n * @returns {any} the built <form> element\n */\nfunction renderForm(schema, opts) {\n const form = document.createElement(\"form\");\n form.className = \"njf-form\";\n if (opts.heading) form.appendChild(fjEl(\"h2\", { class: \"njf-heading\" }, opts.heading));\n const context = fjOwnContext(opts.context);\n const components = schema && Array.isArray(schema.components) ? schema.components : [];\n /** @type {Array<() => ({ key: string, value: any } | null)>} */\n const inputs = [];\n for (const c of components) {\n const built = buildField(c, context, { resolveUrl: opts.resolveUrl });\n if (!built) continue;\n form.appendChild(built.field);\n if (built.read) inputs.push(built.read);\n }\n const submit = fjBtn(opts.submitLabel || \"Submit\", null);\n submit.type = \"submit\";\n const bar = fjEl(\"div\", { class: \"njf-actions\" });\n bar.appendChild(submit);\n if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || \"Cancel\", opts.onCancel));\n form.appendChild(bar);\n form.addEventListener(\"submit\", (e) => {\n e.preventDefault();\n // Null-prototype: field keys come from the engine-supplied form schema. A component\n // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip\n // through JSON), never mutate a prototype — no prototype pollution in the page runtime.\n const variables = Object.create(null);\n for (const read of inputs) {\n const kv = read();\n if (kv) variables[kv.key] = kv.value;\n }\n submit.disabled = true;\n Promise.resolve()\n .then(() => opts.onSubmit(variables))\n .catch(() => {\n submit.disabled = false;\n });\n });\n return form;\n}\n\n\n// Expose the renderer as a browser global so both self-contained page bundles can\n// reach the ONE implementation without importing it: the taskInbox page embeds this\n// module inline and the pages shell does the same before loading the ES-module\n// runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.\n// Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.\nif (typeof globalThis !== \"undefined\") {\n /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };\n}\n";
@@ -20,3 +20,23 @@ export declare function resolveFormResponse(engine: Pick<EngineClient, "getForm"
20
20
  * contract can't drift between them.
21
21
  */
22
22
  export declare function completeUserTaskResponse(engine: Pick<EngineClient, "completeUserTask">, bodyText: string): Promise<HttpResponse>;
23
+ /**
24
+ * The shared task-variables endpoint (#603). Responds with the variables of one
25
+ * process instance as a plain `{ name: value }` object — the render context both
26
+ * form surfaces (taskInbox, pages `dataGrid` engine-form detail) pass to the
27
+ * shared form-js renderer for `{{name}}` text templating, `=varName` image
28
+ * sources, and keyed-input prefill. Sourced from `EngineClient.searchVariables`
29
+ * (the engine's user-task/process variables search), so the two surfaces can
30
+ * never drift on where the context comes from.
31
+ *
32
+ * Each `VariableSummary.value` is the variable's serialized JSON (a string); it
33
+ * is `JSON.parse`d here so the client receives real values (numbers, objects),
34
+ * not double-encoded strings. A value that fails to parse is passed through as
35
+ * the raw string rather than failing the whole read. Only PROCESS-level variables
36
+ * (`scopeKey === processInstanceKey`) are included — task-local variables of other
37
+ * element instances never leak into the context — and truncated previews
38
+ * (`isTruncated`) are omitted so they can never be prefilled and resubmitted over
39
+ * the full value. A missing/blank
40
+ * `processInstanceKey` 400s — without it there is no well-defined scope to read.
41
+ */
42
+ export declare function taskVariablesResponse(engine: Pick<EngineClient, "searchVariables">, processInstanceKey: string | undefined): Promise<HttpResponse>;
@@ -57,3 +57,50 @@ export async function completeUserTaskResponse(engine, bodyText) {
57
57
  await engine.completeUserTask(userTaskKey, variables);
58
58
  return json({ ok: true });
59
59
  }
60
+ /**
61
+ * The shared task-variables endpoint (#603). Responds with the variables of one
62
+ * process instance as a plain `{ name: value }` object — the render context both
63
+ * form surfaces (taskInbox, pages `dataGrid` engine-form detail) pass to the
64
+ * shared form-js renderer for `{{name}}` text templating, `=varName` image
65
+ * sources, and keyed-input prefill. Sourced from `EngineClient.searchVariables`
66
+ * (the engine's user-task/process variables search), so the two surfaces can
67
+ * never drift on where the context comes from.
68
+ *
69
+ * Each `VariableSummary.value` is the variable's serialized JSON (a string); it
70
+ * is `JSON.parse`d here so the client receives real values (numbers, objects),
71
+ * not double-encoded strings. A value that fails to parse is passed through as
72
+ * the raw string rather than failing the whole read. Only PROCESS-level variables
73
+ * (`scopeKey === processInstanceKey`) are included — task-local variables of other
74
+ * element instances never leak into the context — and truncated previews
75
+ * (`isTruncated`) are omitted so they can never be prefilled and resubmitted over
76
+ * the full value. A missing/blank
77
+ * `processInstanceKey` 400s — without it there is no well-defined scope to read.
78
+ */
79
+ export async function taskVariablesResponse(engine, processInstanceKey) {
80
+ const key = processInstanceKey?.trim();
81
+ if (!key)
82
+ return json({ error: "processInstanceKey required" }, 400);
83
+ const rows = await engine.searchVariables({ processInstanceKey: key });
84
+ // A null-prototype bag: a variable named `__proto__` (or `constructor`) is stored
85
+ // as an own data property instead of invoking an inherited setter, so every
86
+ // variable name round-trips through `json()` as data.
87
+ const variables = Object.create(null);
88
+ for (const row of rows) {
89
+ // Process-level scope only: a row whose scopeKey is an element instance is a
90
+ // task-LOCAL variable of some (possibly sibling) task. Flattening those by name
91
+ // would let another task's value win, so they are excluded outright.
92
+ if (row.scopeKey !== key)
93
+ continue;
94
+ // A truncated row's `value` is a preview, not the variable. Prefilling it would
95
+ // let an untouched form submit clipped text over the original — omit it.
96
+ if (row.isTruncated)
97
+ continue;
98
+ try {
99
+ variables[row.name] = JSON.parse(row.value);
100
+ }
101
+ catch {
102
+ variables[row.name] = row.value;
103
+ }
104
+ }
105
+ return json(variables);
106
+ }
@@ -29,7 +29,7 @@ import { html, json } from "../router.js";
29
29
  import { cancelInstanceReconciling } from "./cancel.js";
30
30
  import { apiDocsPath } from "./api.js";
31
31
  import { FORMJS_JS } from "./formjs.gen.js";
32
- import { completeUserTaskResponse, resolveFormResponse } from "./forms.js";
32
+ import { completeUserTaskResponse, resolveFormResponse, taskVariablesResponse } from "./forms.js";
33
33
  import { quoteIdent } from "./gateway.js";
34
34
  import { RENDERER_JS } from "./runtime.gen.js";
35
35
  import { isSqlIdentifier } from "../read-model.js";
@@ -546,6 +546,16 @@ export function createPagesRoutes(opts, deps) {
546
546
  source: "surface:pages",
547
547
  handler: async (req) => completeUserTaskResponse(engine, await req.text()),
548
548
  });
549
+ // The selected row's task variables (#603) — the render context the engineForm
550
+ // drawer passes to the shared form-js renderer (text `{{name}}` templating,
551
+ // `=varName` image sources, keyed-input prefill). The SAME seam the taskInbox
552
+ // surface uses, reused via forms.ts so the context source can't drift.
553
+ routes.push({
554
+ method: "GET",
555
+ path: "/app/actions/variables",
556
+ source: "surface:pages",
557
+ handler: async (req) => taskVariablesResponse(engine, req.query.get("processInstanceKey") ?? undefined),
558
+ });
549
559
  // ── nested (multi-appView) sidecars (#442) ──────────────────────────────
550
560
  // An app with more than one `appView` cannot share the four FLAT sidecar names above:
551
561
  // each view ships its own SUBDIR sidecar — e.g. `pages/cockpit.page.json` →
@@ -813,6 +823,7 @@ body { margin:0; font:15px/1.5 system-ui,sans-serif; padding:2rem; max-width:64r
813
823
  .njf-form { display:flex; flex-direction:column; gap:.4rem; margin-top:.5rem; }
814
824
  .njf-heading { font-size:1rem; margin:0 0 .25rem; }
815
825
  .njf-text { color:var(--nano-text-muted); margin:.25rem 0; }
826
+ .njf-image { display:block; max-width:100%; height:auto; margin:.4rem 0; }
816
827
  .njf-field { display:flex; flex-direction:column; gap:.25rem; }
817
828
  .njf-field label { font-size:.8rem; color:var(--nano-text-muted); }
818
829
  .njf-field input:not([type=checkbox]):not([type=radio]), .njf-field textarea, .njf-field select { padding:.5rem .6rem; border:1px solid var(--nano-edge); border-radius:.4rem; font:inherit; background:var(--nano-inset); color:var(--nano-text); max-width:24rem; }