@nanobpm/urban 0.79.0 → 0.80.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.
@@ -6,8 +6,9 @@
6
6
  // base/api/complete`). A task with no linked form keeps the bare key-list + raw-complete
7
7
  // behavior. The `chat` surface is stubbed as a mount point (LLM wiring is a separate concern).
8
8
  // Surfaces contribute routes to the shared server.
9
- import { presentFormIdentifier } from "../host.js";
10
- import { html, json, noContent, normalizeRoutePath } from "../router.js";
9
+ import { html, json, normalizeRoutePath } from "../router.js";
10
+ import { FORMJS_JS } from "./formjs.gen.js";
11
+ import { completeUserTaskResponse, resolveFormResponse } from "./forms.js";
11
12
  import { mountActions } from "./actions.js";
12
13
  import { mountAgent } from "./agent.js";
13
14
  import { mountApi } from "./api.js";
@@ -30,13 +31,15 @@ function inboxPage() {
30
31
  ul{list-style:none;padding:0}li{margin:.4rem 0;display:flex;align-items:center;gap:.5rem}
31
32
  code{background:#f4f4f4;padding:.1rem .3rem;border-radius:3px}
32
33
  button{font:inherit;padding:.2rem .6rem;cursor:pointer}
33
- form label{display:block;margin:.6rem 0 .2rem;font-weight:600}
34
- form .field input,form .field textarea,form .field select{font:inherit;padding:.3rem;width:100%;box-sizing:border-box;max-width:24rem}
35
- form .field input[type=checkbox],form .field input[type=radio]{width:auto}
34
+ .njf-field label{display:block;margin:.6rem 0 .2rem;font-weight:600}
35
+ .njf-field input,.njf-field textarea,.njf-field select{font:inherit;padding:.3rem;width:100%;box-sizing:border-box;max-width:24rem}
36
+ .njf-field input[type=checkbox],.njf-field input[type=radio]{width:auto}
37
+ .njf-actions{margin-top:.6rem}
36
38
  #form{margin-top:1.5rem;border-top:1px solid #ddd;padding-top:1rem}
37
39
  .muted{color:#666}</style>
38
40
  <h1>Task inbox</h1><ul id="tasks"><li>loading…</li></ul>
39
41
  <div id="form"></div>
42
+ <script>${FORMJS_JS}</script>
40
43
  <script>
41
44
  const BASE=location.pathname.replace(/[/]+$/,'');
42
45
  const tasksEl=document.getElementById('tasks');
@@ -71,7 +74,14 @@ function openForm(t){
71
74
  api('/api/form?'+q).then(f=>{
72
75
  formEl.replaceChildren();
73
76
  if(!f||!f.schema){renderNoForm(t);return;}
74
- renderForm(t,f.schema);
77
+ // Reuse the ONE shared form-js renderer (NanoFormJs) — no fork with the pages surface.
78
+ formEl.appendChild(NanoFormJs.renderForm(f.schema,{
79
+ heading:'Task '+(t.elementId||t.userTaskKey),
80
+ submitLabel:'Submit',
81
+ cancelLabel:'Cancel',
82
+ onSubmit:(variables)=>complete(t.userTaskKey,variables),
83
+ onCancel:loadTasks,
84
+ }));
75
85
  }).catch(err=>{formEl.replaceChildren(el('p',{class:'muted'},'Failed to load form: '+err.message));});
76
86
  }
77
87
 
@@ -83,93 +93,6 @@ function renderNoForm(t){
83
93
  formEl.appendChild(bar);
84
94
  }
85
95
 
86
- function renderForm(t,schema){
87
- const form=document.createElement('form');
88
- form.appendChild(el('h2',{},'Task '+(t.elementId||t.userTaskKey)));
89
- const components=Array.isArray(schema.components)?schema.components:[];
90
- const inputs=[];
91
- for(const c of components){
92
- const built=buildField(c);
93
- if(!built)continue;
94
- form.appendChild(built.field);
95
- if(built.read)inputs.push(built.read);
96
- }
97
- const submit=btn('Submit',null);submit.type='submit';
98
- const bar=el('div',{});bar.appendChild(submit);bar.appendChild(btn('Cancel',loadTasks));
99
- form.appendChild(bar);
100
- form.addEventListener('submit',e=>{
101
- e.preventDefault();
102
- // Null-prototype: field keys come from the engine-supplied form schema. A component
103
- // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip
104
- // through JSON), never mutate a prototype — no prototype pollution in the page runtime.
105
- const variables=Object.create(null);
106
- for(const read of inputs){const kv=read();if(kv)variables[kv.key]=kv.value;}
107
- submit.disabled=true;
108
- complete(t.userTaskKey,variables).catch(()=>{submit.disabled=false;});
109
- });
110
- formEl.appendChild(form);
111
- }
112
-
113
- function buildField(c){
114
- const type=c&&c.type;
115
- // Static (keyless) components: show text as a paragraph, ignore layout-only ones.
116
- if(type==='text'){return {field:el('p',{class:'muted'},typeof c.text==='string'?c.text:'')};}
117
- const key=c&&c.key;
118
- if(!key)return null;
119
- const wrap=el('div',{class:'field'});
120
- const label=typeof c.label==='string'&&c.label?c.label:key;
121
- if(type==='checkbox'){
122
- const input=document.createElement('input');input.type='checkbox';
123
- const lab=el('label',{});lab.appendChild(input);lab.appendChild(document.createTextNode(' '+label));
124
- wrap.appendChild(lab);
125
- return {field:wrap,read:()=>({key,value:input.checked})};
126
- }
127
- const labelEl=el('label',{},label);
128
- wrap.appendChild(labelEl);
129
- let input;
130
- if(type==='textarea'){input=document.createElement('textarea');}
131
- else if(type==='select'){
132
- input=document.createElement('select');
133
- input.appendChild(el('option',{value:''},'—'));
134
- for(const o of (Array.isArray(c.values)?c.values:[])){
135
- input.appendChild(el('option',{value:String(o.value)},String(o.label!=null?o.label:o.value)));
136
- }
137
- }
138
- else if(type==='radio'){
139
- const name='r'+Math.random().toString(36).slice(2);
140
- const group=el('div',{});
141
- for(const o of (Array.isArray(c.values)?c.values:[])){
142
- const rlab=el('label',{});
143
- const r=document.createElement('input');r.type='radio';r.name=name;r.value=String(o.value);
144
- rlab.appendChild(r);rlab.appendChild(document.createTextNode(' '+String(o.label!=null?o.label:o.value)));
145
- group.appendChild(rlab);
146
- }
147
- wrap.appendChild(group);
148
- return {field:wrap,read:()=>{const sel=group.querySelector('input:checked');return sel?{key,value:sel.value}:null;}};
149
- }
150
- else{
151
- input=document.createElement('input');
152
- input.type=(type==='number')?'number':(type==='datetime'?'datetime-local':'text');
153
- }
154
- // Associate the label with the input (for/id) so screen readers announce it on focus.
155
- const fieldId='f'+Math.random().toString(36).slice(2);
156
- input.id=fieldId;labelEl.setAttribute('for',fieldId);
157
- wrap.appendChild(input);
158
- const isNumber=type==='number';
159
- return {field:wrap,read:()=>{
160
- const raw=input.value;
161
- if(raw===''||raw==null)return null;
162
- if(isNumber){
163
- const n=Number(raw);
164
- // A non-numeric value in a number field is only reachable via tampering (the browser
165
- // blanks invalid type=number input). Treat it as absent rather than silently submitting
166
- // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.
167
- return Number.isFinite(n)?{key,value:n}:null;
168
- }
169
- return {key,value:raw};
170
- }};
171
- }
172
-
173
96
  function complete(userTaskKey,variables){
174
97
  return api('/api/complete',{method:'POST',headers:{'content-type':'application/json'},
175
98
  body:JSON.stringify({userTaskKey,variables})}).then(loadTasks);
@@ -222,42 +145,13 @@ export function mountSurfaces(ctx, app) {
222
145
  method: "GET",
223
146
  path: `${base}/api/form`,
224
147
  source: "surface:taskInbox",
225
- handler: async (req) => {
226
- const formKey = req.query.get("formKey") ?? undefined;
227
- const formId = req.query.get("formId") ?? undefined;
228
- // Reject only when *neither* identifier is present. Presence follows getForm's
229
- // canonical rule (`presentFormIdentifier`: empty/whitespace = absent) so a
230
- // whitespace-only `?formKey= ` request 400s here instead of slipping past a raw
231
- // truthiness check and returning a spurious 204. The raw values are still passed
232
- // through unchanged — resolving a blank key to its `formId` fallback is getForm's
233
- // single responsibility.
234
- if (!presentFormIdentifier(formKey) && !presentFormIdentifier(formId))
235
- return json({ error: "formKey or formId required" }, 400);
236
- const form = await app.engine.getForm({ formKey, formId });
237
- // A task whose form can't be resolved returns 204: the client renders the
238
- // no-form fallback rather than erroring.
239
- if (!form)
240
- return noContent();
241
- return json(form);
242
- },
148
+ handler: async (req) => resolveFormResponse(app.engine, req.query.get("formKey") ?? undefined, req.query.get("formId") ?? undefined),
243
149
  });
244
150
  routes.push({
245
151
  method: "POST",
246
152
  path: `${base}/api/complete`,
247
153
  source: "surface:taskInbox",
248
- handler: async (req) => {
249
- let body;
250
- try {
251
- body = JSON.parse((await req.text()) || "{}");
252
- }
253
- catch {
254
- return json({ error: "invalid JSON body" }, 400);
255
- }
256
- if (!body.userTaskKey)
257
- return json({ error: "userTaskKey required" }, 400);
258
- await app.engine.completeUserTask(body.userTaskKey, body.variables);
259
- return json({ ok: true });
260
- },
154
+ handler: async (req) => completeUserTaskResponse(app.engine, await req.text()),
261
155
  });
262
156
  }
263
157
  const chat = surfaces.chat;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/urban",
3
- "version": "0.79.0",
3
+ "version": "0.80.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",
@@ -0,0 +1,114 @@
1
+ // A small fake DOM for unit-testing the browser runtime's element-building code
2
+ // (the shared form-js renderer and the dataGrid engine-form path) under Node,
3
+ // without a real browser. Records every created node so a test can grab an input
4
+ // or button and fire its listeners. Kept intentionally minimal — it supports only
5
+ // the DOM surface those functions touch.
6
+
7
+ export class FakeElement {
8
+ tagName: string;
9
+ attributes: Record<string, string> = {};
10
+ className = "";
11
+ children: Array<FakeElement | { text: string }> = [];
12
+ textContent = "";
13
+ hidden = false;
14
+ disabled = false;
15
+ value = "";
16
+ checked = false;
17
+ type = "";
18
+ name = "";
19
+ id = "";
20
+ listeners: Record<string, Array<(ev: unknown) => unknown>> = {};
21
+
22
+ constructor(tag: string) {
23
+ this.tagName = String(tag).toUpperCase();
24
+ }
25
+ setAttribute(k: string, v: unknown): void {
26
+ this.attributes[k] = String(v);
27
+ if (k === "class") this.className = String(v);
28
+ }
29
+ getAttribute(k: string): string | null {
30
+ return k in this.attributes ? this.attributes[k] : null;
31
+ }
32
+ addEventListener(type: string, fn: (ev: unknown) => unknown): void {
33
+ (this.listeners[type] ||= []).push(fn);
34
+ }
35
+ async fire(type: string, ev: unknown = { preventDefault() {}, stopPropagation() {} }): Promise<void> {
36
+ for (const fn of this.listeners[type] || []) await fn(ev);
37
+ }
38
+ append(...kids: Array<FakeElement | { text: string } | string>): void {
39
+ for (const kid of kids) {
40
+ if (typeof kid === "string") {
41
+ this.children.push({ text: kid });
42
+ this.textContent += kid;
43
+ } else if ("text" in kid) {
44
+ this.children.push(kid);
45
+ this.textContent += kid.text;
46
+ } else {
47
+ this.children.push(kid);
48
+ this.textContent += kid.textContent || "";
49
+ }
50
+ }
51
+ }
52
+ appendChild(kid: FakeElement | { text: string }): void {
53
+ this.append(kid);
54
+ }
55
+ replaceChildren(...kids: Array<FakeElement | { text: string } | string>): void {
56
+ this.children = [];
57
+ this.textContent = "";
58
+ this.append(...kids);
59
+ }
60
+ get firstChild(): FakeElement | { text: string } | null {
61
+ return this.children[0] ?? null;
62
+ }
63
+ querySelector(selector: string): FakeElement | null {
64
+ const walk = (nodes: Array<FakeElement | { text: string }>): FakeElement | null => {
65
+ for (const kid of nodes) {
66
+ if (kid instanceof FakeElement) {
67
+ if (fakeSelectorMatches(kid, selector)) return kid;
68
+ const found = walk(kid.children);
69
+ if (found) return found;
70
+ }
71
+ }
72
+ return null;
73
+ };
74
+ return walk(this.children);
75
+ }
76
+ }
77
+
78
+ // Minimal CSS-selector matcher for the DOM surface the browser runtime touches
79
+ // (currently the radio group's `input:checked` lookup). Supports an optional tag
80
+ // name plus `:checked`; any other pseudo/selector deliberately fails to match so
81
+ // unsupported queries surface rather than silently returning a wrong node.
82
+ function fakeSelectorMatches(node: FakeElement, selector: string): boolean {
83
+ const parts = selector.trim().split(":");
84
+ const tag = parts[0];
85
+ if (tag && node.tagName !== tag.toUpperCase()) return false;
86
+ for (const pseudo of parts.slice(1)) {
87
+ if (pseudo === "checked") {
88
+ if (!node.checked) return false;
89
+ } else {
90
+ return false;
91
+ }
92
+ }
93
+ return true;
94
+ }
95
+
96
+ /** Install a fake `document` on globalThis; returns a restore function. */
97
+ export function installFakeDom(created: FakeElement[]): () => void {
98
+ const doc = {
99
+ createElement: (tag: string) => {
100
+ const n = new FakeElement(tag);
101
+ created.push(n);
102
+ return n;
103
+ },
104
+ createTextNode: (text: string) => ({ text: String(text) }),
105
+ getElementById: () => null,
106
+ dispatchEvent: () => true,
107
+ };
108
+ const prior = Reflect.getOwnPropertyDescriptor(globalThis, "document");
109
+ Reflect.set(globalThis, "document", doc);
110
+ return () => {
111
+ if (prior) Reflect.defineProperty(globalThis, "document", prior);
112
+ else Reflect.deleteProperty(globalThis, "document");
113
+ };
114
+ }
@@ -0,0 +1,192 @@
1
+ // @ts-check
2
+ // ── Shared, XSS-safe form-js schema renderer (ADR 0026, extended by #457) ─────
3
+ // This is the ONE client implementation of "render a deployed `.form`'s form-js
4
+ // schema and collect its field values", shared verbatim by BOTH:
5
+ // • the `taskInbox` surface (surfaces.ts `inboxPage`), and
6
+ // • the pages `dataGrid` engine-form detail (runtime.browser.js).
7
+ // It used to live inline in surfaces.ts; factoring it here means the two surfaces
8
+ // can never fork the renderer or drift on how a form-js component maps to an input
9
+ // and its submitted value.
10
+ //
11
+ // Like the rest of the browser runtime it is authored/type-checked/linted/tested
12
+ // as real source and served as a generated string artifact (formjs.gen.ts, emitted
13
+ // by scripts/gen-runtime.mjs). It performs NO DOM access at load — every DOM touch
14
+ // is inside a function — so it is import-safe under Node/Deno for unit testing.
15
+ //
16
+ // SECURITY: every value the engine returns is placed via textContent / setAttribute
17
+ // (never innerHTML), so nothing in the form schema can inject markup. The submitted
18
+ // `variables` bag is null-prototype so an engine-supplied component key of
19
+ // `__proto__`/`constructor` lands as a plain own property and can never mutate a
20
+ // prototype (prototype-pollution class).
21
+
22
+ /** Create an element, setting attributes via setAttribute and text via textContent only.
23
+ * @param {string} tag
24
+ * @param {Record<string, string>} [attrs]
25
+ * @param {string} [text]
26
+ * @returns {any}
27
+ */
28
+ function fjEl(tag, attrs, text) {
29
+ const e = document.createElement(tag);
30
+ if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);
31
+ if (text != null) e.textContent = text;
32
+ return e;
33
+ }
34
+
35
+ /** A plain type="button" with an optional click handler.
36
+ * @param {string} label
37
+ * @param {(() => void) | null} [onClick]
38
+ * @returns {any}
39
+ */
40
+ function fjBtn(label, onClick) {
41
+ const b = document.createElement("button");
42
+ b.type = "button";
43
+ b.textContent = label;
44
+ if (onClick) b.addEventListener("click", onClick);
45
+ return b;
46
+ }
47
+
48
+ /** Build one form-js component into its field element and (for keyed inputs) a reader
49
+ * that returns the entered `{ key, value }` or null when blank. Static (keyless)
50
+ * components render as inert text; layout-only components are skipped (null).
51
+ * @param {any} c
52
+ * @returns {{ field: any, read?: () => ({ key: string, value: any } | null) } | null}
53
+ */
54
+ function buildField(c) {
55
+ const type = c && c.type;
56
+ // Static (keyless) components: show text as a paragraph, ignore layout-only ones.
57
+ if (type === "text") {
58
+ return { field: fjEl("p", { class: "njf-text" }, typeof c.text === "string" ? c.text : "") };
59
+ }
60
+ const key = c && c.key;
61
+ if (!key) return null;
62
+ const wrap = fjEl("div", { class: "njf-field" });
63
+ const label = typeof c.label === "string" && c.label ? c.label : key;
64
+ if (type === "checkbox") {
65
+ const input = document.createElement("input");
66
+ input.type = "checkbox";
67
+ const lab = fjEl("label", {});
68
+ lab.appendChild(input);
69
+ lab.appendChild(document.createTextNode(" " + label));
70
+ wrap.appendChild(lab);
71
+ return { field: wrap, read: () => ({ key, value: input.checked }) };
72
+ }
73
+ const labelEl = fjEl("label", {}, label);
74
+ wrap.appendChild(labelEl);
75
+ let input;
76
+ if (type === "textarea") {
77
+ input = document.createElement("textarea");
78
+ } else if (type === "select") {
79
+ input = document.createElement("select");
80
+ input.appendChild(fjEl("option", { value: "" }, "\u2014"));
81
+ 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)));
83
+ }
84
+ } else if (type === "radio") {
85
+ const name = "r" + Math.random().toString(36).slice(2);
86
+ const group = fjEl("div", {});
87
+ for (const o of Array.isArray(c.values) ? c.values : []) {
88
+ const rlab = fjEl("label", {});
89
+ const r = document.createElement("input");
90
+ r.type = "radio";
91
+ r.name = name;
92
+ r.value = String(o.value);
93
+ rlab.appendChild(r);
94
+ rlab.appendChild(document.createTextNode(" " + String(o.label != null ? o.label : o.value)));
95
+ group.appendChild(rlab);
96
+ }
97
+ wrap.appendChild(group);
98
+ return {
99
+ field: wrap,
100
+ read: () => {
101
+ const sel = group.querySelector("input:checked");
102
+ return sel ? { key, value: sel.value } : null;
103
+ },
104
+ };
105
+ } else {
106
+ input = document.createElement("input");
107
+ input.type = type === "number" ? "number" : type === "datetime" ? "datetime-local" : "text";
108
+ }
109
+ // Associate the label with the input (for/id) so screen readers announce it on focus.
110
+ const fieldId = "f" + Math.random().toString(36).slice(2);
111
+ input.id = fieldId;
112
+ labelEl.setAttribute("for", fieldId);
113
+ wrap.appendChild(input);
114
+ const isNumber = type === "number";
115
+ return {
116
+ field: wrap,
117
+ read: () => {
118
+ const raw = input.value;
119
+ if (raw === "" || raw == null) return null;
120
+ if (isNumber) {
121
+ const n = Number(raw);
122
+ // A non-numeric value in a number field is only reachable via tampering (the browser
123
+ // blanks invalid type=number input). Treat it as absent rather than silently submitting
124
+ // NaN, which JSON.stringify serializes as null — quietly changing the submitted value.
125
+ return Number.isFinite(n) ? { key, value: n } : null;
126
+ }
127
+ return { key, value: raw };
128
+ },
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Render a form-js schema into a `<form>` element with a submit + optional cancel.
134
+ * On submit it assembles every keyed field's value into one null-prototype
135
+ * `variables` bag and calls `opts.onSubmit(variables)`; a rejected submit re-enables
136
+ * the button so the operator can retry. `opts.onCancel`, when supplied, wires a
137
+ * cancel button.
138
+ * @param {any} schema the parsed form-js document (`{ components: [...] }`)
139
+ * @param {{ heading?: string, submitLabel?: string, cancelLabel?: string,
140
+ * onSubmit: (variables: Record<string, any>) => (void | Promise<void>),
141
+ * onCancel?: () => void }} opts
142
+ * @returns {any} the built <form> element
143
+ */
144
+ function renderForm(schema, opts) {
145
+ const form = document.createElement("form");
146
+ form.className = "njf-form";
147
+ if (opts.heading) form.appendChild(fjEl("h2", { class: "njf-heading" }, opts.heading));
148
+ const components = schema && Array.isArray(schema.components) ? schema.components : [];
149
+ /** @type {Array<() => ({ key: string, value: any } | null)>} */
150
+ const inputs = [];
151
+ for (const c of components) {
152
+ const built = buildField(c);
153
+ if (!built) continue;
154
+ form.appendChild(built.field);
155
+ if (built.read) inputs.push(built.read);
156
+ }
157
+ const submit = fjBtn(opts.submitLabel || "Submit", null);
158
+ submit.type = "submit";
159
+ const bar = fjEl("div", { class: "njf-actions" });
160
+ bar.appendChild(submit);
161
+ if (opts.onCancel) bar.appendChild(fjBtn(opts.cancelLabel || "Cancel", opts.onCancel));
162
+ form.appendChild(bar);
163
+ form.addEventListener("submit", (e) => {
164
+ e.preventDefault();
165
+ // Null-prototype: field keys come from the engine-supplied form schema. A component
166
+ // keyed '__proto__'/'constructor' must land as a plain own property (and round-trip
167
+ // through JSON), never mutate a prototype — no prototype pollution in the page runtime.
168
+ const variables = Object.create(null);
169
+ for (const read of inputs) {
170
+ const kv = read();
171
+ if (kv) variables[kv.key] = kv.value;
172
+ }
173
+ submit.disabled = true;
174
+ Promise.resolve()
175
+ .then(() => opts.onSubmit(variables))
176
+ .catch(() => {
177
+ submit.disabled = false;
178
+ });
179
+ });
180
+ return form;
181
+ }
182
+
183
+ export { buildField, renderForm };
184
+
185
+ // Expose the renderer as a browser global so both self-contained page bundles can
186
+ // reach the ONE implementation without importing it: the taskInbox page embeds this
187
+ // module inline and the pages shell does the same before loading the ES-module
188
+ // runtime, which reads `globalThis.NanoFormJs` lazily when it renders an engine form.
189
+ // Guarded so importing under Node/Deno for tests is a harmless no-op-ish assignment.
190
+ if (typeof globalThis !== "undefined") {
191
+ /** @type {any} */ (globalThis).NanoFormJs = { buildField, renderForm };
192
+ }
@@ -0,0 +1,136 @@
1
+ // Unit tests for the shared form-js renderer (formjs.browser.js, ADR 0026/#457):
2
+ // the ONE client implementation of "render a deployed .form's form-js schema and
3
+ // collect its field values", shared by BOTH the taskInbox surface and the pages
4
+ // dataGrid engine-form detail. Importing the module also registers it as the
5
+ // `globalThis.NanoFormJs` global that the pages runtime consumes.
6
+
7
+ import { test } from "node:test";
8
+ import assert from "node:assert/strict";
9
+ import { buildField, renderForm } from "./formjs.browser.js";
10
+ import { type FakeElement, installFakeDom } from "./fake-dom.test-utils.ts";
11
+
12
+ test("NanoFormJs is registered as a browser global on import", () => {
13
+ const g = Reflect.get(globalThis, "NanoFormJs");
14
+ assert.ok(g, "importing the module exposes globalThis.NanoFormJs");
15
+ });
16
+
17
+ test("buildField skips keyless layout components and renders static text", (t) => {
18
+ const created: FakeElement[] = [];
19
+ t.after(installFakeDom(created));
20
+ assert.equal(buildField({ type: "spacer" }), null, "a keyless, non-text component is skipped");
21
+ const textOnly = buildField({ type: "text", text: "Read me" });
22
+ assert.ok(textOnly && !textOnly.read, "a static text component has no reader");
23
+ assert.equal(textOnly!.field.textContent, "Read me");
24
+ });
25
+
26
+ test("buildField reads a textfield's entered value, and omits a blank one", (t) => {
27
+ const created: FakeElement[] = [];
28
+ t.after(installFakeDom(created));
29
+ const built = buildField({ type: "textfield", key: "note", label: "Note" });
30
+ assert.ok(built?.read);
31
+ const input = created.find((n) => n.tagName === "INPUT");
32
+ assert.ok(input);
33
+ input!.value = "hello";
34
+ assert.deepEqual(built!.read!(), { key: "note", value: "hello" });
35
+ input!.value = "";
36
+ assert.equal(built!.read!(), null, "a blank field is omitted from the submitted variables");
37
+ });
38
+
39
+ test("buildField coerces a number field and drops a non-finite value", (t) => {
40
+ const created: FakeElement[] = [];
41
+ t.after(installFakeDom(created));
42
+ const built = buildField({ type: "number", key: "qty" });
43
+ const input = created.find((n) => n.tagName === "INPUT");
44
+ input!.value = "42";
45
+ assert.deepEqual(built!.read!(), { key: "qty", value: 42 });
46
+ input!.value = "not-a-number";
47
+ assert.equal(built!.read!(), null, "a tampered non-numeric number field is treated as absent, never NaN→null");
48
+ });
49
+
50
+ test("buildField maps a checkbox to a boolean value", (t) => {
51
+ const created: FakeElement[] = [];
52
+ t.after(installFakeDom(created));
53
+ const built = buildField({ type: "checkbox", key: "agree", label: "Agree" });
54
+ const input = created.find((n) => n.tagName === "INPUT");
55
+ input!.checked = true;
56
+ assert.deepEqual(built!.read!(), { key: "agree", value: true });
57
+ });
58
+
59
+ test("buildField reads the checked radio option (and omits an unselected group)", (t) => {
60
+ const created: FakeElement[] = [];
61
+ t.after(installFakeDom(created));
62
+ const built = buildField({
63
+ type: "radio",
64
+ key: "size",
65
+ label: "Size",
66
+ values: [
67
+ { value: "s", label: "Small" },
68
+ { value: "l", label: "Large" },
69
+ ],
70
+ });
71
+ assert.ok(built?.read);
72
+ assert.equal(built!.read!(), null, "an unselected radio group is omitted from the submitted variables");
73
+ const radios = created.filter((n) => n.tagName === "INPUT" && n.type === "radio");
74
+ assert.equal(radios.length, 2);
75
+ radios[1].checked = true;
76
+ assert.deepEqual(built!.read!(), { key: "size", value: "l" }, "read() finds the checked option via querySelector('input:checked')");
77
+ });
78
+
79
+ test("renderForm submits a null-prototype variables bag (prototype-pollution safe)", async (t) => {
80
+ const created: FakeElement[] = [];
81
+ t.after(installFakeDom(created));
82
+ const schema = {
83
+ components: [
84
+ { type: "textfield", key: "note" },
85
+ { type: "textfield", key: "__proto__" },
86
+ ],
87
+ };
88
+ let submitted: Record<string, unknown> | undefined;
89
+ const form = renderForm(schema, {
90
+ heading: "Task A",
91
+ onSubmit: (variables) => {
92
+ submitted = variables;
93
+ },
94
+ });
95
+ const inputs = created.filter((n) => n.tagName === "INPUT");
96
+ inputs[0].value = "hi";
97
+ inputs[1].value = "evil";
98
+ await form.fire("submit");
99
+ assert.ok(submitted);
100
+ assert.equal(Object.getPrototypeOf(submitted!), null, "the variables bag has a null prototype");
101
+ assert.equal(submitted!.note, "hi");
102
+ assert.equal(Object.prototype.hasOwnProperty.call(submitted!, "__proto__"), true, "an untrusted key lands as an own property");
103
+ assert.equal(Object.getPrototypeOf({}), Object.prototype, "no prototype was mutated");
104
+ });
105
+
106
+ test("renderForm re-enables the submit button when onSubmit rejects (retryable)", async (t) => {
107
+ const created: FakeElement[] = [];
108
+ t.after(installFakeDom(created));
109
+ const form = renderForm(
110
+ { components: [{ type: "textfield", key: "x" }] },
111
+ {
112
+ onSubmit: () => Promise.reject(new Error("boom")),
113
+ },
114
+ );
115
+ const submit = created.find((n) => n.tagName === "BUTTON" && n.type === "submit");
116
+ assert.ok(submit);
117
+ await form.fire("submit");
118
+ // The rejected onSubmit settles a microtask later; flush it.
119
+ await Promise.resolve();
120
+ await Promise.resolve();
121
+ assert.equal(submit!.disabled, false, "a failed submit re-enables the button so the operator can retry");
122
+ });
123
+
124
+ test("renderForm wires a cancel button only when onCancel is supplied", async (t) => {
125
+ const created: FakeElement[] = [];
126
+ t.after(installFakeDom(created));
127
+ renderForm({ components: [] }, { onSubmit: () => {} });
128
+ assert.equal(created.filter((n) => n.tagName === "BUTTON").length, 1, "no cancel button without onCancel");
129
+ created.length = 0;
130
+ let cancelled = false;
131
+ renderForm({ components: [] }, { onSubmit: () => {}, onCancel: () => (cancelled = true) });
132
+ const buttons = created.filter((n) => n.tagName === "BUTTON");
133
+ assert.equal(buttons.length, 2, "a cancel button is added when onCancel is supplied");
134
+ await buttons[1].fire("click");
135
+ assert.equal(cancelled, true, "clicking cancel invokes onCancel");
136
+ });