@nanobpm/urban 0.96.3 → 0.98.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.
Files changed (46) hide show
  1. package/README.md +60 -0
  2. package/dist/runtime/connector-worker-sdk.d.ts +2 -0
  3. package/dist/runtime/connector-worker-sdk.js +6 -1
  4. package/dist/runtime/core/host.d.ts +15 -5
  5. package/dist/runtime/core/manifest.d.ts +23 -0
  6. package/dist/runtime/core/manifest.js +8 -0
  7. package/dist/runtime/core/modules/connectors.d.ts +3 -0
  8. package/dist/runtime/core/modules/connectors.js +32 -1
  9. package/dist/runtime/core/modules/formjs.gen.js +1 -1
  10. package/dist/runtime/core/modules/forms.d.ts +20 -0
  11. package/dist/runtime/core/modules/forms.js +47 -0
  12. package/dist/runtime/core/modules/pages.js +12 -1
  13. package/dist/runtime/core/modules/runtime.gen.js +1 -1
  14. package/dist/runtime/core/modules/surfaces.js +57 -4
  15. package/dist/runtime/core/modules/workers.js +5 -1
  16. package/dist/runtime/core/validate.js +12 -0
  17. package/dist/runtime/engine/nanosdk.d.ts +1 -0
  18. package/dist/runtime/engine/nanosdk.js +3 -0
  19. package/dist/runtime/index.d.ts +3 -3
  20. package/dist/runtime/index.js +1 -1
  21. package/package.json +2 -2
  22. package/src/runtime/browser/fake-dom.test-utils.ts +16 -1
  23. package/src/runtime/browser/formjs.browser.js +258 -7
  24. package/src/runtime/browser/formjs.browser.test.ts +690 -0
  25. package/src/runtime/browser/runtime.browser.js +25 -3
  26. package/src/runtime/browser/runtime.engineform.test.ts +203 -0
  27. package/src/runtime/connector-worker-sdk.test.ts +9 -0
  28. package/src/runtime/connector-worker-sdk.ts +8 -1
  29. package/src/runtime/core/host.ts +16 -1
  30. package/src/runtime/core/manifest.ts +28 -0
  31. package/src/runtime/core/modules/connectors.test.ts +158 -1
  32. package/src/runtime/core/modules/connectors.ts +44 -1
  33. package/src/runtime/core/modules/formjs.gen.ts +1 -1
  34. package/src/runtime/core/modules/forms.ts +47 -0
  35. package/src/runtime/core/modules/pages.test.ts +21 -0
  36. package/src/runtime/core/modules/pages.ts +13 -1
  37. package/src/runtime/core/modules/runtime.gen.ts +1 -1
  38. package/src/runtime/core/modules/surfaces.test.ts +308 -0
  39. package/src/runtime/core/modules/surfaces.ts +58 -4
  40. package/src/runtime/core/modules/workers.test.ts +45 -1
  41. package/src/runtime/core/modules/workers.ts +5 -1
  42. package/src/runtime/core/validate.test.ts +19 -0
  43. package/src/runtime/core/validate.ts +12 -0
  44. package/src/runtime/engine/nanosdk.test.ts +17 -0
  45. package/src/runtime/engine/nanosdk.ts +4 -1
  46. package/src/runtime/index.ts +3 -0
@@ -8,7 +8,7 @@
8
8
  // Surfaces contribute routes to the shared server.
9
9
  import { html, json, normalizeRoutePath } from "../router.js";
10
10
  import { FORMJS_JS } from "./formjs.gen.js";
11
- import { completeUserTaskResponse, resolveFormResponse } from "./forms.js";
11
+ import { completeUserTaskResponse, resolveFormResponse, taskVariablesResponse } from "./forms.js";
12
12
  import { mountActions } from "./actions.js";
13
13
  import { mountAgent } from "./agent.js";
14
14
  import { mountApi } from "./api.js";
@@ -18,7 +18,7 @@ import { mountPages } from "./pages.js";
18
18
  function escapeHtml(s) {
19
19
  return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
20
20
  }
21
- function inboxPage() {
21
+ function inboxPage(inboxBase) {
22
22
  // Reverse-proxy safe: the client derives its API base from location.pathname
23
23
  // (where THIS page was actually served) rather than an embedded absolute
24
24
  // route base. A hardcoded "/tasks" would escape the Nano console's
@@ -27,6 +27,20 @@ function inboxPage() {
27
27
  // <script> injection surface entirely: nothing manifest-supplied is embedded.
28
28
  // All task/form values are rendered via textContent / setAttribute — never
29
29
  // innerHTML — so nothing the engine returns can inject markup.
30
+ //
31
+ // The ONE manifest-derived value the page does embed is the configured inbox
32
+ // path's SEGMENT COUNT — numeric metadata, never the path string, so the
33
+ // injection surface stays closed. The client strips that many segments from
34
+ // BASE to derive the app mount: stripping a fixed single segment would retain
35
+ // a nested configured path (an inbox mounted at review+tasks would rebase
36
+ // '/app/thumb.png' to '…/review/app/thumb.png', which has no handler).
37
+ // normalizeRoutePath guarantees a leading slash and no trailing one, but
38
+ // PRESERVES interior repeated slashes (router.ts) — so count every slot the
39
+ // client's BASE.split('/') produces after the leading slash (split.length - 1),
40
+ // including the empty slots a configured '/review//tasks' yields. Counting only
41
+ // non-empty segments would strip too few: the client's split retains the empty
42
+ // slot, so APP_BASE would keep a segment that is not the app mount.
43
+ const inboxSegments = inboxBase.split("/").length - 1;
30
44
  return `<!doctype html><meta charset="utf-8"><title>Task inbox</title>
31
45
  <style>body{font:14px system-ui,sans-serif;margin:2rem;max-width:52rem}
32
46
  ul{list-style:none;padding:0}li{margin:.4rem 0;display:flex;align-items:center;gap:.5rem}
@@ -36,6 +50,7 @@ button{font:inherit;padding:.2rem .6rem;cursor:pointer}
36
50
  .njf-field input,.njf-field textarea,.njf-field select{font:inherit;padding:.3rem;width:100%;box-sizing:border-box;max-width:24rem}
37
51
  .njf-field input[type=checkbox],.njf-field input[type=radio]{width:auto}
38
52
  .njf-actions{margin-top:.6rem}
53
+ .njf-image{display:block;max-width:100%;height:auto;margin:.6rem 0}
39
54
  #form{margin-top:1.5rem;border-top:1px solid #ddd;padding-top:1rem}
40
55
  .muted{color:#666}</style>
41
56
  <h1>Task inbox</h1><ul id="tasks"><li>loading…</li></ul>
@@ -43,6 +58,16 @@ button{font:inherit;padding:.2rem .6rem;cursor:pointer}
43
58
  <script>${FORMJS_JS}</script>
44
59
  <script>
45
60
  const BASE=location.pathname.replace(/[/]+$/,'');
61
+ // The app-mount prefix: BASE ends with the WHOLE configured inbox route (this
62
+ // page IS the inbox), so strip exactly that many segments — not a fixed one, or
63
+ // a nested inbox path (e.g. review+tasks) would leave its leading segments
64
+ // behind and '/app/thumb.png' would resolve under them (no handler there).
65
+ // Root-relative APP paths ('/app/…') rebase onto APP_BASE — not BASE — otherwise
66
+ // the URL keeps the inbox route ('/tasks/app/…'). Direct run: BASE='/tasks' →
67
+ // APP_BASE=''. Proxied: BASE='/console/app-view/<name>/tasks' →
68
+ // APP_BASE='/console/app-view/<name>'.
69
+ const INBOX_SEGMENTS=${inboxSegments};
70
+ const APP_BASE=BASE.split('/').slice(0,-INBOX_SEGMENTS).join('/');
46
71
  const tasksEl=document.getElementById('tasks');
47
72
  const formEl=document.getElementById('form');
48
73
 
@@ -72,7 +97,16 @@ function loadTasks(){
72
97
  function openForm(t){
73
98
  formEl.replaceChildren(el('p',{class:'muted'},'loading form…'));
74
99
  const q='formKey='+encodeURIComponent(t.formKey);
75
- api('/api/form?'+q).then(f=>{
100
+ // Load the form schema AND the task's variables together (#603): the variables
101
+ // are the renderer's context — {{name}} text templating, =varName image
102
+ // sources, and keyed-input prefill all resolve against them, so the reviewer
103
+ // sees what they are reviewing. A variables fetch that fails degrades to an
104
+ // empty context (the form still renders, untemplated/unprefilled) rather than
105
+ // blocking the form.
106
+ const varsP=t.processInstanceKey
107
+ ?api('/api/variables?processInstanceKey='+encodeURIComponent(t.processInstanceKey)).catch(()=>({}))
108
+ :Promise.resolve({});
109
+ Promise.all([api('/api/form?'+q),varsP]).then(([f,context])=>{
76
110
  formEl.replaceChildren();
77
111
  if(!f||!f.schema){renderNoForm(t);return;}
78
112
  // Reuse the ONE shared form-js renderer (NanoFormJs) — no fork with the pages surface.
@@ -80,6 +114,16 @@ function openForm(t){
80
114
  heading:'Task '+(t.elementId||t.userTaskKey),
81
115
  submitLabel:'Submit',
82
116
  cancelLabel:'Cancel',
117
+ context:context||{},
118
+ // Rebase root-relative image sources ('/app/…' — any single-leading-slash app
119
+ // path) onto the APP mount (APP_BASE = BASE minus the inbox route), so they
120
+ // survive the console's path-prefixed proxy without keeping the inbox segment.
121
+ // A scheme-less RELATIVE source ('app/thumb.png') would otherwise resolve
122
+ // against the page URL — under a nested inbox mount that requests
123
+ // <inbox>/app/thumb.png, which has no handler — so rebase those onto
124
+ // APP_BASE too. Any scheme-bearing source (http(s):, data:) and a protocol-relative
125
+ // '//host' (already rejected by the renderer's allowlist) pass through verbatim.
126
+ resolveUrl:(u)=>u.startsWith('//')||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(u)?u:u.startsWith('/')?APP_BASE+u:APP_BASE+'/'+u,
83
127
  onSubmit:(variables)=>complete(t.userTaskKey,variables),
84
128
  onCancel:loadTasks,
85
129
  }));
@@ -118,7 +162,7 @@ export function mountSurfaces(ctx, app) {
118
162
  method: "GET",
119
163
  path: base,
120
164
  source: "surface:taskInbox",
121
- handler: () => html(inboxPage()),
165
+ handler: () => html(inboxPage(base)),
122
166
  });
123
167
  routes.push({
124
168
  method: "GET",
@@ -148,6 +192,15 @@ export function mountSurfaces(ctx, app) {
148
192
  source: "surface:taskInbox",
149
193
  handler: async (req) => resolveFormResponse(app.engine, req.query.get("formKey") ?? undefined, req.query.get("formId") ?? undefined),
150
194
  });
195
+ // The task's variables (#603) — the render context the shared form-js renderer
196
+ // templates/prefills from. Same source as the pages surface's variables route
197
+ // (forms.ts `taskVariablesResponse`), so the two can never drift.
198
+ routes.push({
199
+ method: "GET",
200
+ path: `${base}/api/variables`,
201
+ source: "surface:taskInbox",
202
+ handler: async (req) => taskVariablesResponse(app.engine, req.query.get("processInstanceKey") ?? undefined),
203
+ });
151
204
  routes.push({
152
205
  method: "POST",
153
206
  path: `${base}/api/complete`,
@@ -2,7 +2,7 @@
2
2
  // on the engine. Handlers are resolved by a small, documented contract and are injected
3
3
  // with the app's runtime API (datasource + engine + host utils).
4
4
  import { isRecord } from "../guards.js";
5
- import { workerJobType } from "../manifest.js";
5
+ import { workerJobType, workerTimeoutMs } from "../manifest.js";
6
6
  import { runLlmJob } from "./llm.js";
7
7
  import { runInJobContext } from "../execContext.js";
8
8
  import { readLineage } from "../lineage.js";
@@ -274,6 +274,8 @@ export async function mountWorkers(ctx, app, sched = defaultScheduler()) {
274
274
  };
275
275
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
276
276
  workerName: `${ctx.manifest.id}:${jobType}`,
277
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
278
+ timeoutMs: workerTimeoutMs(decl),
277
279
  });
278
280
  subs.push(sub);
279
281
  jobTypes.push(jobType);
@@ -293,6 +295,8 @@ export async function mountWorkers(ctx, app, sched = defaultScheduler()) {
293
295
  };
294
296
  const sub = await ctx.engine.registerWorker(jobType, wrapped, {
295
297
  workerName: `${ctx.manifest.id}:${jobType}`,
298
+ // The declared job lock timeout (issue #596) — absent ⇒ the engine/SDK default.
299
+ timeoutMs: workerTimeoutMs(decl),
296
300
  });
297
301
  subs.push(sub);
298
302
  jobTypes.push(jobType);
@@ -125,6 +125,18 @@ export function collectManifestIssues(m) {
125
125
  });
126
126
  }
127
127
  }
128
+ // The pending-schema job lock timeout (issue #596): when present it must be a
129
+ // positive integer of ms — a zero/negative lock would expire instantly (the job
130
+ // re-activated mid-handler), and a non-integer is a manifest typo to fail fast on.
131
+ if (worker !== undefined && "timeoutMs" in worker) {
132
+ const t = worker.timeoutMs;
133
+ if (typeof t !== "number" || !Number.isInteger(t) || t <= 0) {
134
+ issues.push({
135
+ path: `workers[${i}].timeoutMs`,
136
+ message: "timeoutMs must be a positive integer (ms)",
137
+ });
138
+ }
139
+ }
128
140
  });
129
141
  }
130
142
  const data = isRecord(obj.data) ? obj.data : undefined;
@@ -286,6 +286,7 @@ export declare class SdkEngineClient implements EngineClient {
286
286
  registerWorker(jobType: string, handler: JobHandler, options?: {
287
287
  workerName?: string;
288
288
  maxParallelJobs?: number;
289
+ timeoutMs?: number;
289
290
  fetchVariables?: string[];
290
291
  }): Promise<WorkerSubscription>;
291
292
  /** Stop one worker, tolerating a Falcon worker whose transport never bound
@@ -1074,6 +1074,9 @@ export class SdkEngineClient {
1074
1074
  jobType,
1075
1075
  workerName: options?.workerName ?? `urban:${jobType}`,
1076
1076
  maxParallelJobs: options?.maxParallelJobs ?? 8,
1077
+ // The job lock timeout (issue #596): pass it through only when declared, so an
1078
+ // undeclared worker keeps the SDK's default lock rather than an explicit value.
1079
+ ...(options?.timeoutMs !== undefined ? { jobTimeoutMs: options.timeoutMs } : {}),
1077
1080
  fetchVariables: options?.fetchVariables,
1078
1081
  jobHandler: async (job) => {
1079
1082
  const rawKey = job.jobKey;
@@ -4,11 +4,11 @@ export { EventBus } from "./core/events.ts";
4
4
  export type { DispatchMode, Disposer, EmitChannel, ErrorSink, EventBusOptions, Listener, Middleware, ParallelChannel, SerialChannel, WaterfallChannel, } from "./core/events.ts";
5
5
  export { URBAN_EVENT_MODES, createUrbanEvents, mountExtensions, urbanEventMode } from "./core/extensions.ts";
6
6
  export type { DispatchRequest, DispatchResponse, ExtensionHost, ExtensionRegistered, ExtensionSetupContext, GateDecision, GateRequest, LifecycleEvent, MountExtensionsOptions, ReconcileEvent, UrbanEventName, UrbanEvents, UrbanExtension, } from "./core/extensions.ts";
7
- export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.ts";
8
- export type { ActionDecl, AppManifest, BindMode, ChatSurface, DataSource, DomainField, DomainType, InstanceTracking, LlmBinding, NetworkConfig, PagesSurface, Surfaces, TaskInboxSurface, Trigger, Worker, } from "./core/manifest.ts";
7
+ export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, workerTimeoutMs, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.ts";
8
+ export type { ActionDecl, AppManifest, BindMode, ChatSurface, DataSource, DomainField, DomainType, InstanceTracking, LlmBinding, NetworkConfig, PagesSurface, Surfaces, TaskInboxSurface, Trigger, Worker, WorkerDecl, } from "./core/manifest.ts";
9
9
  export { collectManifestIssues, ManifestValidationError, validateManifest, } from "./core/validate.ts";
10
10
  export type { ValidationIssue } from "./core/validate.ts";
11
- export type { EngineClient, AgentHistoryFilter, AgentHistoryRecord, AgentInstanceFilter, AgentInstanceMetrics, AgentInstanceSummary, ElementInstanceState, ElementInstanceSummary, ElementInstanceFilter, ElementInstanceWaitState, ElementInstanceWaitStateFilter, WaitStateType, EngineJob, FormSchema, HostContext, HttpHandler, HttpRequest, HttpResponse, HttpServer, IncidentState, EngineIncidentState, IncidentFilter, IncidentSummary, JobFilter, JobHandler, JobSummary, CreatedProcessInstance, ProcessDefinitionIdentity, ProcessInstanceSnapshot, ProcessInstanceState, SqliteDb, UserTaskState, UserTaskSummary, UserTaskFilter, VariableFilter, VariableSummary, WatchHandle, WorkerSubscription, } from "./core/host.ts";
11
+ export type { EngineClient, AgentHistoryFilter, AgentHistoryRecord, AgentInstanceFilter, AgentInstanceMetrics, AgentInstanceSummary, ElementInstanceState, ElementInstanceSummary, ElementInstanceFilter, ElementInstanceWaitState, ElementInstanceWaitStateFilter, WaitStateType, EngineJob, FormSchema, HostContext, HttpHandler, HttpRequest, HttpResponse, HttpServer, IncidentState, EngineIncidentState, IncidentFilter, IncidentSummary, JobFilter, JobHandler, JobSummary, CreatedProcessInstance, ProcessDefinitionIdentity, ProcessInstanceSnapshot, ProcessInstanceState, RegisterWorkerOptions, SqliteDb, UserTaskState, UserTaskSummary, UserTaskFilter, VariableFilter, VariableSummary, WatchHandle, WorkerSubscription, } from "./core/host.ts";
12
12
  export type { TranscriptContentBlock, TranscriptContentType, TranscriptToolCall, TranscriptTurnMetrics, TranscriptTurnRole, } from "@nanobpm/agentic/transcript";
13
13
  export { buildFormSchema, parseFormSchema, pickFormLinkage, presentFormIdentifier, resolveFormIdentifier, } from "./core/form-contract.ts";
14
14
  export { pickProcessDefinitionIdentity, presentEngineKey, presentString, } from "./core/process-identity.ts";
@@ -5,7 +5,7 @@ export { createUrbanApp } from "./core/runtime.js";
5
5
  export { EventBus } from "./core/events.js";
6
6
  export { URBAN_EVENT_MODES, createUrbanEvents, mountExtensions, urbanEventMode } from "./core/extensions.js";
7
7
  // Manifest
8
- export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.js";
8
+ export { bindModeToHost, expandEnv, expandEnvString, isBindMode, loadManifest, parseManifest, resolveBindHost, resolveBindMode, workerJobType, workerTimeoutMs, ALL_INTERFACES_HOST, BIND_ENV_VAR, LOOPBACK_HOST, } from "./core/manifest.js";
9
9
  // Validation
10
10
  export { collectManifestIssues, ManifestValidationError, validateManifest, } from "./core/validate.js";
11
11
  // Shared form/user-task contract normalization (issue #252): the single source of truth
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.96.3",
3
+ "version": "0.98.0",
4
4
  "description": "Urban: build and run code-first apps on Nano — runtime, derivation toolkit, and CLI in one. Author durable processes with @nanobpm/workflow (defineFlow), a typed datasource, forms, triggers and surfaces from a nano.app.json manifest, on Node or Deno.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -106,7 +106,7 @@
106
106
  "@nanobpm/agentic": "^0.15.0",
107
107
  "@nanobpm/nano-app-schema": "^0.11.0",
108
108
  "@nanobpm/nano-sdk": "^1.2.5",
109
- "@nanobpm/workflow": "^0.15.1",
109
+ "@nanobpm/workflow": "^0.16.0",
110
110
  "bpmn-auto-layout": "^2.0.0-alpha.2",
111
111
  "create-urban-app": "^0.15.3",
112
112
  "yaml": "^2.9.0"
@@ -12,12 +12,27 @@ export class FakeElement {
12
12
  textContent = "";
13
13
  hidden = false;
14
14
  disabled = false;
15
- value = "";
16
15
  checked = false;
17
16
  type = "";
18
17
  name = "";
19
18
  id = "";
20
19
  listeners: Record<string, Array<(ev: unknown) => unknown>> = {};
20
+ private _value = "";
21
+
22
+ // Model the one piece of native value sanitization the renderer depends on:
23
+ // a datetime-local control rejects a value it cannot hold (e.g. a
24
+ // timezone-bearing timestamp) by blanking it AT ASSIGNMENT time. Every other
25
+ // input type stores the string verbatim.
26
+ get value(): string {
27
+ return this._value;
28
+ }
29
+ set value(v: string) {
30
+ const s = String(v);
31
+ this._value =
32
+ this.type === "datetime-local" && s !== "" && !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(\.\d+)?$/.test(s)
33
+ ? ""
34
+ : s;
35
+ }
21
36
 
22
37
  constructor(tag: string) {
23
38
  this.tagName = String(tag).toUpperCase();
@@ -18,6 +18,12 @@
18
18
  // `variables` bag is null-prototype so an engine-supplied component key of
19
19
  // `__proto__`/`constructor` lands as a plain own property and can never mutate a
20
20
  // prototype (prototype-pollution class).
21
+ //
22
+ // VARIABLES CONTEXT (#603): both surfaces pass the task's variables as the render
23
+ // `context`. `text` components interpolate `{{name}}` against it (textContent-only,
24
+ // never markup), `image` components resolve a `=varName` source from it, and a
25
+ // keyed input whose key is present is prefilled — the form-js/Camunda Tasklist
26
+ // behaviour, so a reviewer sees what they are reviewing.
21
27
 
22
28
  /** Create an element, setting attributes via setAttribute and text via textContent only.
23
29
  * @param {string} tag
@@ -45,17 +51,188 @@ function fjBtn(label, onClick) {
45
51
  return b;
46
52
  }
47
53
 
54
+ /** Interpolate `{{name}}` placeholders in a `text` component against the render
55
+ * context (the task's variables), following form-js/Camunda Tasklist. A present
56
+ * value is stringified (objects/arrays as JSON); an unknown name becomes the empty
57
+ * string. The result is placed via textContent only — a variable holding markup
58
+ * (`<img onerror=…>`) renders as literal text, never as HTML (the XSS rule holds
59
+ * for templated text exactly as for static text).
60
+ * @param {string} text
61
+ * @param {Record<string, any>} context
62
+ * @returns {string}
63
+ */
64
+ function fjTemplate(text, context) {
65
+ return text.replace(/\{\{\s*([^{}\s]+)\s*\}\}/g, (_m, name) => {
66
+ const v = context[name];
67
+ if (v == null) return "";
68
+ return typeof v === "string" ? v : JSON.stringify(v);
69
+ });
70
+ }
71
+
72
+ /** Copy only the context's OWN enumerable properties into a null-prototype
73
+ * dictionary, so lookups like `ctx["constructor"]` or `ctx["__proto__"]` never
74
+ * resolve to inherited members (which would template/prefill bogus values), while
75
+ * an explicitly supplied own value with such a name is still honoured.
76
+ * @param {any} context
77
+ * @returns {Record<string, any>}
78
+ */
79
+ function fjOwnContext(context) {
80
+ /** @type {Record<string, any>} */
81
+ const out = Object.create(null);
82
+ if (context == null || typeof context !== "object") return out;
83
+ for (const k of Object.keys(context)) {
84
+ Object.defineProperty(out, k, { value: context[k], enumerable: true, writable: true, configurable: true });
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /** The image-source allowlist, applied to BOTH the raw source and — when a
90
+ * `resolveUrl` rewrote it — the RESOLVED URL. A resolver is same-origin trusted
91
+ * code, but it TRANSFORMS the string (the pages runtime's `apiUrl` strips the
92
+ * leading slash before `new URL(...)`), and a transformation can mint a forbidden
93
+ * shape from an accepted one: a root-prefixed script-scheme path passes below as
94
+ * an app-relative path (the leading slash defeats the scheme check), then
95
+ * resolves to the bare forbidden-scheme URL. Re-running the allowlist on the
96
+ * resolver's result closes that laundering class at the single choke point every
97
+ * surface flows through, so no resolver — present or future — can widen the
98
+ * accepted set.
99
+ * @param {string} url
100
+ * @returns {string | null} the URL when allowed, null when rejected
101
+ */
102
+ function fjAllowImageUrl(url) {
103
+ // Browsers strip/normalise whitespace and control characters and treat `\` as
104
+ // `/` before interpreting a URL, so `java\tscript:` or ` data:image/svg+xml` or
105
+ // `/\\host` could slip past the allowlist below. Fail closed on any of them.
106
+ if (/[\s\u0000-\u001f\u007f\\]/.test(url)) return null;
107
+ // data:image — RFC 2397 lets the mediatype be followed directly by `,`
108
+ // (parameters and `;base64` are both optional), so accept `;` OR `,` after the
109
+ // subtype or a percent-encoded payload silently never renders.
110
+ if (/^data:image\/(png|jpeg|gif|webp)[;,]/i.test(url)) return url;
111
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)) {
112
+ // A scheme: only http(s) is allowed (javascript:/data-text-html/etc. rejected).
113
+ return /^https?:\/\//i.test(url) ? url : null;
114
+ }
115
+ if (url.startsWith("//")) return null; // protocol-relative → off-origin, reject
116
+ return url; // app-relative path
117
+ }
118
+
119
+ /** Resolve an `image` component's `source` to a URL the renderer will put on the
120
+ * <img>, or null to reject it. `source` is either a literal URL or `=varName` — a
121
+ * PLAIN variable reference into the render context (full FEEL is intentionally not
122
+ * supported: anything after `=` that is not a bare identifier is rejected). Only
123
+ * `http(s):` URLs, app-relative paths (no scheme, no `//host` protocol-relative),
124
+ * and `data:image/(png|jpeg|gif|webp)` URLs are allowed — never `javascript:` or
125
+ * any other scheme. The URL is set with setAttribute (never innerHTML).
126
+ * `resolveUrl`, when supplied, rewrites an ACCEPTED URL just before it is set —
127
+ * both surfaces pass their app-mount-aware resolver (the pages runtime's `apiUrl`,
128
+ * the inbox page's mount prefix) so a root-relative `/app/…` source requests the
129
+ * app's own path even behind the console's path-prefixed proxy. The allowlist runs
130
+ * on the raw source AND again on the resolver's result (see fjAllowImageUrl), so a
131
+ * resolver can never launder a rejected URL — including one it minted itself by
132
+ * rebasing a disguised path.
133
+ * @param {any} source
134
+ * @param {Record<string, any>} context
135
+ * @param {(url: string) => string} [resolveUrl]
136
+ * @returns {string | null}
137
+ */
138
+ function fjImageSrc(source, context, resolveUrl) {
139
+ let url = source;
140
+ if (typeof url === "string" && url.startsWith("=")) {
141
+ const name = url.slice(1).trim();
142
+ // A plain variable reference only — reject anything that isn't a bare
143
+ // identifier (a FEEL expression, a call, a path) rather than evaluating it.
144
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) return null;
145
+ url = context[name];
146
+ }
147
+ if (typeof url !== "string" || url === "") return null;
148
+ const allowed = fjAllowImageUrl(url);
149
+ if (allowed == null) return null;
150
+ // App-relative path. A root-relative one ("/app/…") is only correct when the app
151
+ // is served at the origin root; behind the console's path-prefixed proxy it must
152
+ // be rebased onto the app mount (the resolver both surfaces pass). Absolute
153
+ // http(s)/data: URLs pass through untouched (the resolvers only rewrite
154
+ // single-leading-slash paths), but revalidate the result regardless — a resolver
155
+ // that strips the leading slash (the pages `apiUrl`) turns "/javascript:…" into
156
+ // a forbidden-scheme URL, which must not reach the <img>.
157
+ if (!resolveUrl) return allowed;
158
+ // A resolver can THROW on an allowlist-accepted source: the pages `apiUrl`
159
+ // strips the leading slash and calls `new URL(...)`, which throws `Invalid URL`
160
+ // on a path that is not URL-path-shaped (e.g. "/http://"). Uncaught, that
161
+ // exception escapes buildField and the WHOLE task form fails to render. A
162
+ // failed resolution rejects just this image (null), exactly like a resolver
163
+ // that returned a rejected URL.
164
+ let resolved;
165
+ try {
166
+ resolved = resolveUrl(allowed);
167
+ } catch {
168
+ return null;
169
+ }
170
+ if (typeof resolved !== "string" || resolved === "") return null;
171
+ // Re-run the SAME allowlist on the resolver's output (one source of truth):
172
+ // app-relative paths, http(s) and data:image survive; a forbidden scheme the
173
+ // resolver minted (e.g. "/javascript:…" stripped to "javascript:…"), a file:
174
+ // URL, or a protocol-relative URL is rejected.
175
+ return fjAllowImageUrl(resolved);
176
+ }
177
+
178
+ /** The value a keyed input is prefilled with when its key is present in the render
179
+ * context (form-js prefill semantics): strings as-is, other scalars stringified,
180
+ * objects/arrays as JSON. `undefined`/`null` mean "no prefill".
181
+ * @param {Record<string, any>} context
182
+ * @param {string} key
183
+ * @returns {string | undefined}
184
+ */
185
+ function fjPrefill(context, key) {
186
+ const v = context[key];
187
+ if (v == null) return undefined;
188
+ return typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v);
189
+ }
190
+
191
+ /** The prefill pair for a keyed input: `display` is the string the control shows
192
+ * (fjPrefill's rendering); `original` is the context value itself, captured at
193
+ * prefill time. An UNTOUCHED control — one that still shows exactly `display` —
194
+ * submits `original`, never `display`: the completion endpoint forwards submitted
195
+ * values verbatim, so forwarding the stringified rendering would retype the
196
+ * variable (a prefilled `{ approved: true }` textarea would overwrite the object
197
+ * with the STRING '{"approved":true}'; a numeric select/radio prefill would
198
+ * overwrite the number with "1"). Once the operator changes the control away
199
+ * from `display` the edited string (or its number coercion) submits instead.
200
+ * @param {Record<string, any>} context
201
+ * @param {string} key
202
+ * @returns {{ display: string, original: any } | undefined}
203
+ */
204
+ function fjPrefillPair(context, key) {
205
+ const display = fjPrefill(context, key);
206
+ return display === undefined ? undefined : { display, original: context[key] };
207
+ }
208
+
48
209
  /** Build one form-js component into its field element and (for keyed inputs) a reader
49
210
  * that returns the entered `{ key, value }` or null when blank. Static (keyless)
50
211
  * components render as inert text; layout-only components are skipped (null).
212
+ * `context` carries the task's variables: `text` components interpolate `{{name}}`
213
+ * against it, `image` components resolve a `=varName` source from it, and a keyed
214
+ * input whose key is present is prefilled with its value.
51
215
  * @param {any} c
216
+ * @param {Record<string, any>} [context]
217
+ * @param {{ resolveUrl?: (url: string) => string }} [opts]
52
218
  * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}
53
219
  */
54
- function buildField(c) {
220
+ function buildField(c, context, opts) {
221
+ const ctx = fjOwnContext(context);
55
222
  const type = c && c.type;
56
223
  // Static (keyless) components: show text as a paragraph, ignore layout-only ones.
57
224
  if (type === "text") {
58
- return { field: fjEl("p", { class: "njf-text" }, typeof c.text === "string" ? c.text : "") };
225
+ const raw = typeof c.text === "string" ? c.text : "";
226
+ return { field: fjEl("p", { class: "njf-text" }, fjTemplate(raw, ctx)) };
227
+ }
228
+ // An image component (form-js `{ type: "image", source, alt }`) — keyless, renders
229
+ // an <img> whose src is resolved + scheme-gated by fjImageSrc. A rejected/absent
230
+ // source renders nothing (null) rather than a broken or unsafe <img>.
231
+ if (type === "image") {
232
+ const src = fjImageSrc(c.source, ctx, opts && opts.resolveUrl);
233
+ if (src == null) return null;
234
+ const attrs = { class: "njf-image", src, alt: typeof c.alt === "string" ? c.alt : "" };
235
+ return { field: fjEl("img", attrs) };
59
236
  }
60
237
  const key = c && c.key;
61
238
  if (!key) return null;
@@ -64,6 +241,8 @@ function buildField(c) {
64
241
  if (type === "checkbox") {
65
242
  const input = document.createElement("input");
66
243
  input.type = "checkbox";
244
+ // Prefill: a boolean context value checks the box.
245
+ if (ctx[key] === true) input.checked = true;
67
246
  const lab = fjEl("label", {});
68
247
  lab.appendChild(input);
69
248
  lab.appendChild(document.createTextNode(" " + label));
@@ -73,16 +252,53 @@ function buildField(c) {
73
252
  const labelEl = fjEl("label", {}, label);
74
253
  wrap.appendChild(labelEl);
75
254
  let input;
255
+ // Was this field prefilled from the context — AND did the control ACCEPT the
256
+ // value? Only a successful prefill counts: a prefilled field the operator CLEARS
257
+ // (empties the text input, picks the blank select option) must submit an empty
258
+ // string — returning null would omit the key and silently leave the original
259
+ // variable unchanged. But a REJECTED prefill (a select value matching no option,
260
+ // a timezone-bearing timestamp a datetime-local control blanks) leaves the
261
+ // control empty through no operator action; treating that as prefilled would
262
+ // submit "" from an untouched form and overwrite the original variable. A
263
+ // rejected prefill behaves like no prefill: blank means "not entered", so the
264
+ // key is omitted.
265
+ let prefilled = false;
266
+ /** @type {{ display: string, original: any } | undefined} */
267
+ let prefillPair;
76
268
  if (type === "textarea") {
77
269
  input = document.createElement("textarea");
270
+ prefillPair = fjPrefillPair(ctx, key);
271
+ if (prefillPair !== undefined) {
272
+ input.value = prefillPair.display;
273
+ prefilled = true;
274
+ }
78
275
  } else if (type === "select") {
79
276
  input = document.createElement("select");
80
277
  input.appendChild(fjEl("option", { value: "" }, "\u2014"));
278
+ prefillPair = fjPrefillPair(ctx, key);
279
+ const pre = prefillPair === undefined ? undefined : prefillPair.display;
81
280
  for (const o of Array.isArray(c.values) ? c.values : []) {
82
- input.appendChild(fjEl("option", { value: String(o.value) }, String(o.label != null ? o.label : o.value)));
281
+ const opt = fjEl("option", { value: String(o.value) }, String(o.label != null ? o.label : o.value));
282
+ // Prefill: mark the option matching the context value as selected.
283
+ if (pre !== undefined && String(o.value) === pre) opt.setAttribute("selected", "");
284
+ input.appendChild(opt);
285
+ }
286
+ if (pre !== undefined) {
287
+ input.value = pre;
288
+ // The select ACCEPTS the prefill only when it matches a declared option —
289
+ // otherwise the DOM snaps the value back to "" and the control sits blank.
290
+ // Check acceptance structurally (against the option list), not by reading
291
+ // the value back: the control must not be treated as prefilled when it
292
+ // could not take the value, or an untouched submit would overwrite the
293
+ // original variable with "".
294
+ const accepted = (Array.isArray(c.values) ? c.values : []).some((/** @type {any} */ o) => String(o.value) === pre);
295
+ prefilled = pre !== "" && accepted;
296
+ if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill
83
297
  }
84
298
  } else if (type === "radio") {
85
299
  const name = "r" + Math.random().toString(36).slice(2);
300
+ const prefillRadio = fjPrefillPair(ctx, key);
301
+ const pre = prefillRadio === undefined ? undefined : prefillRadio.display;
86
302
  const group = fjEl("div", {});
87
303
  for (const o of Array.isArray(c.values) ? c.values : []) {
88
304
  const rlab = fjEl("label", {});
@@ -90,6 +306,8 @@ function buildField(c) {
90
306
  r.type = "radio";
91
307
  r.name = name;
92
308
  r.value = String(o.value);
309
+ // Prefill: check the option matching the context value.
310
+ if (pre !== undefined && r.value === pre) r.checked = true;
93
311
  rlab.appendChild(r);
94
312
  rlab.appendChild(document.createTextNode(" " + String(o.label != null ? o.label : o.value)));
95
313
  group.appendChild(rlab);
@@ -99,12 +317,27 @@ function buildField(c) {
99
317
  field: wrap,
100
318
  read: () => {
101
319
  const sel = group.querySelector("input:checked");
102
- return sel ? { key, value: sel.value } : null;
320
+ if (!sel) return null;
321
+ // Untouched (the checked option is still the prefill's): submit the
322
+ // ORIGINAL value so a numeric prefill stays a number — the completion
323
+ // endpoint forwards submitted values verbatim, and a radio option's
324
+ // value is always a string.
325
+ if (prefillRadio !== undefined && sel.value === prefillRadio.display) return { key, value: prefillRadio.original };
326
+ return { key, value: sel.value };
103
327
  },
104
328
  };
105
329
  } else {
106
330
  input = document.createElement("input");
107
331
  input.type = type === "number" ? "number" : type === "datetime" ? "datetime-local" : "text";
332
+ prefillPair = fjPrefillPair(ctx, key);
333
+ if (prefillPair !== undefined) {
334
+ input.value = prefillPair.display;
335
+ // A typed control (number/datetime-local) sanitizes a value it cannot hold
336
+ // to "" — e.g. a timezone-bearing timestamp assigned to datetime-local. Only
337
+ // a value that survived counts as a successful prefill.
338
+ prefilled = input.value !== "";
339
+ if (!prefilled) prefillPair = undefined; // a rejected prefill is not a prefill
340
+ }
108
341
  }
109
342
  // Associate the label with the input (for/id) so screen readers announce it on focus.
110
343
  const fieldId = "f" + Math.random().toString(36).slice(2);
@@ -116,7 +349,17 @@ function buildField(c) {
116
349
  field: wrap,
117
350
  read: () => {
118
351
  const raw = input.value;
119
- if (raw === "" || raw == null) return null;
352
+ // A prefilled field the operator cleared submits an empty string (an explicit
353
+ // "set this variable to empty"), never an omission that would leave the
354
+ // original value in place. A never-prefilled blank field is still omitted.
355
+ if (raw === "" || raw == null) return prefilled ? { key, value: "" } : null;
356
+ // Untouched (the control still shows exactly the prefill's rendering):
357
+ // submit the ORIGINAL context value, never the stringified display — the
358
+ // completion endpoint forwards submitted values verbatim, so the string
359
+ // would retype the variable (an object prefill would become its JSON
360
+ // string; a numeric prefill would become "3"). Once the operator changes
361
+ // the control away from the prefill, the edited value submits below.
362
+ if (prefillPair !== undefined && raw === prefillPair.display) return { key, value: prefillPair.original };
120
363
  if (isNumber) {
121
364
  const n = Number(raw);
122
365
  // A non-numeric value in a number field is only reachable via tampering (the browser
@@ -134,9 +377,16 @@ function buildField(c) {
134
377
  * On submit it assembles every keyed field's value into one null-prototype
135
378
  * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables
136
379
  * the button so the operator can retry. `opts.onCancel`, when supplied, wires a
137
- * cancel button.
380
+ * cancel button. `opts.context` carries the task's variables — `{{name}}` text
381
+ * templating, `=varName` image sources, and keyed-input prefill all resolve
382
+ * against it (see buildField). `opts.resolveUrl`, when supplied, rewrites each
383
+ * ACCEPTED image source before it is set — both surfaces pass their app-mount-aware
384
+ * resolver so a root-relative `/app/…` image survives the console's path-prefixed
385
+ * proxy (see fjImageSrc).
138
386
  * @param {any} schema the parsed form-js document (`{ components: [...] }`)
139
387
  * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,
388
+ * context?: Record<string, any>,
389
+ * resolveUrl?: (url: string) => string,
140
390
  * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),
141
391
  * onCancel?: () => void }} opts
142
392
  * @returns {any} the built <form> element
@@ -145,11 +395,12 @@ function renderForm(schema, opts) {
145
395
  const form = document.createElement("form");
146
396
  form.className = "njf-form";
147
397
  if (opts.heading) form.appendChild(fjEl("h2", { class: "njf-heading" }, opts.heading));
398
+ const context = fjOwnContext(opts.context);
148
399
  const components = schema && Array.isArray(schema.components) ? schema.components : [];
149
400
  /** @type {Array<() => ({ key: string, value: any } | null)>} */
150
401
  const inputs = [];
151
402
  for (const c of components) {
152
- const built = buildField(c);
403
+ const built = buildField(c, context, { resolveUrl: opts.resolveUrl });
153
404
  if (!built) continue;
154
405
  form.appendChild(built.field);
155
406
  if (built.read) inputs.push(built.read);