@pipelex/mthds-form 0.5.0 → 0.6.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 (38) hide show
  1. package/dist/chunk-2JWRG53S.js +33 -0
  2. package/dist/chunk-2JWRG53S.js.map +1 -0
  3. package/dist/chunk-45C2MKK6.js +94 -0
  4. package/dist/chunk-45C2MKK6.js.map +1 -0
  5. package/dist/chunk-4BSBBG2T.js +80 -0
  6. package/dist/chunk-4BSBBG2T.js.map +1 -0
  7. package/dist/chunk-IIU3YK4O.js +16 -0
  8. package/dist/chunk-IIU3YK4O.js.map +1 -0
  9. package/dist/{chunk-IIJRJGZQ.js → chunk-J4L32LD6.js} +14 -5
  10. package/dist/chunk-J4L32LD6.js.map +1 -0
  11. package/dist/{chunk-IM2AHWBR.js → chunk-R7B7ID25.js} +3 -3
  12. package/dist/{chunk-IM2AHWBR.js.map → chunk-R7B7ID25.js.map} +1 -1
  13. package/dist/{chunk-5Q2W6HBA.js → chunk-T4NSAGOS.js} +3 -3
  14. package/dist/{chunk-5Q2W6HBA.js.map → chunk-T4NSAGOS.js.map} +1 -1
  15. package/dist/core/derive.d.ts +35 -2
  16. package/dist/core/derive.js +2 -1
  17. package/dist/core/file-formats.d.ts +102 -0
  18. package/dist/core/file-formats.js +3 -0
  19. package/dist/core/file-formats.js.map +1 -0
  20. package/dist/core/gate.js +2 -2
  21. package/dist/core/index.d.ts +6 -2
  22. package/dist/core/index.js +8 -4
  23. package/dist/core/native-content.d.ts +219 -0
  24. package/dist/core/native-content.js +4 -0
  25. package/dist/core/native-content.js.map +1 -0
  26. package/dist/core/output-form.d.ts +45 -0
  27. package/dist/core/output-form.js +5 -0
  28. package/dist/core/output-form.js.map +1 -0
  29. package/dist/core/stuff-files.d.ts +52 -0
  30. package/dist/core/stuff-files.js +5 -0
  31. package/dist/core/stuff-files.js.map +1 -0
  32. package/dist/core/values.js +3 -2
  33. package/dist/react/index.d.ts +258 -1
  34. package/dist/react/index.js +1339 -12
  35. package/dist/react/index.js.map +1 -1
  36. package/dist/styles.css +1 -1
  37. package/package.json +17 -5
  38. package/dist/chunk-IIJRJGZQ.js.map +0 -1
@@ -0,0 +1,33 @@
1
+ // src/core/file-formats.ts
2
+ var DOCUMENT_FORMATS = [
3
+ { mimeType: "application/pdf", extensions: [".pdf"], label: "PDF" },
4
+ { mimeType: "image/jpeg", extensions: [".jpg", ".jpeg"], label: "JPG" },
5
+ { mimeType: "image/png", extensions: [".png"], label: "PNG" }
6
+ ];
7
+ var IMAGE_FORMATS = [
8
+ { mimeType: "image/png", extensions: [".png"], label: "PNG" },
9
+ { mimeType: "image/jpeg", extensions: [".jpg", ".jpeg"], label: "JPG" },
10
+ { mimeType: "image/webp", extensions: [".webp"], label: "WEBP" }
11
+ ];
12
+ function formatsForKind(kind) {
13
+ return kind === "image" ? IMAGE_FORMATS : DOCUMENT_FORMATS;
14
+ }
15
+ function acceptLabelForKind(kind) {
16
+ return formatsForKind(kind).map((format) => format.label).join(", ");
17
+ }
18
+ function isAcceptedFile(kind, file) {
19
+ const formats = formatsForKind(kind);
20
+ const mimeType = file.type.split(";", 1)[0]?.trim().toLowerCase() ?? "";
21
+ if (mimeType) return formats.some((format) => format.mimeType === mimeType);
22
+ const name = file.name.toLowerCase();
23
+ return formats.some((format) => format.extensions.some((ext) => name.endsWith(ext)));
24
+ }
25
+ function acceptMapForKind(kind) {
26
+ const map = {};
27
+ for (const format of formatsForKind(kind)) map[format.mimeType] = [...format.extensions];
28
+ return map;
29
+ }
30
+
31
+ export { DOCUMENT_FORMATS, IMAGE_FORMATS, acceptLabelForKind, acceptMapForKind, formatsForKind, isAcceptedFile };
32
+ //# sourceMappingURL=chunk-2JWRG53S.js.map
33
+ //# sourceMappingURL=chunk-2JWRG53S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/file-formats.ts"],"names":[],"mappings":";AAoEO,IAAM,gBAAA,GAA0C;AAAA,EACrD,EAAE,UA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AA,CAAK,IAAA,CAAK,WAAA,EAAY;AACnC,EAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,CAAC,MAAA,KAAW,MAAA,CAAO,UAAA,CAAW,IAAA,CAAK,CAAC,GAAA,KAAQ,IAAA,CAAK,QAAA,CAAS,GAAG,CAAC,CAAC,CAAA;AACrF;AASO,SAAS,iBAAiB,IAAA,EAAsD;AACrF,EAAA,MAAM,MAAgC,EAAC;AACvC,EAAA,KAAA,MAAW,MAAA,IAAU,cAAA,CAAe,IAAI,CAAA,EAAG,GAAA,CAAI,MAAA,CAAO,QAAQ,CAAA,GAAI,CAAC,GAAG,MAAA,CAAO,UAAU,CAAA;AACvF,EAAA,OAAO,GAAA;AACT","file":"chunk-2JWRG53S.js","sourcesContent":["/**\n * What a `document` or an `image` slot actually accepts.\n *\n * **This is a client-side mirror of a runtime fact, and the fact was measured\n * rather than read off a list.** The wire says a slot's kind is `document` or\n * `image` and stops there — which bytes a runtime can decode is a property of\n * that runtime, not of the method — so the list has to live on this side, and\n * the only honest place is one module that says where it came from.\n *\n * There is no single enum to copy. In `pipelex`, what a slot accepts is derived\n * per model:\n *\n * ModelSpec.supported_document_types = {\"pdf\",\"docx\",\"pptx\"} & set(inputs)\n * ModelSpec.is_vision_supported = \"images\" in inputs\n *\n * so the effective set is that vocabulary intersected with the **model deck's**\n * declared `inputs`. No model in the shipped deck declares `docx` or `pptx`;\n * every LLM entry is `[\"text\", \"images\", \"pdf\"]`, and the default extract model\n * (`azure-document-intelligence`) is `[\"image\", \"pdf\"]`.\n *\n * Confirmed by running each format end to end:\n *\n * | Format | PipeExtract | PipeLLM |\n * | --- | --- | --- |\n * | PDF | yes | yes |\n * | PNG | yes | n/a |\n * | JPEG | yes | n/a |\n * | WEBP | no | no |\n * | DOCX | no | no — `does not support docx documents` |\n * | PPTX | no | no — detected as `zip`, so it never even reaches the check |\n *\n * The gateway states its own list in the failure: *\"Supported formats:\n * application/pdf, image/jpeg, image/png as base64 data URLs.\"*\n *\n * Images were measured the same way: PNG, JPEG and WEBP pass; BMP and TIFF fail\n * on the provider's image enum; GIF fails too, though it is *in* that enum — it\n * arrives at the provider as a document block rather than an image one, which\n * looks like a routing bug upstream rather than an unsupported format.\n *\n * **A document slot's PNG and JPEG only work in an extract pipe.** The\n * descriptor never says which operator consumes the slot, so this table cannot\n * distinguish them; it matches the extract model's declared inputs, because\n * extraction is the operator that actually reads a document's bytes.\n *\n * What was here before was built on `DocumentFormat` (PDF/DOCX/PPTX), an enum\n * that is referenced nowhere in the runtime outside commented-out code and is\n * being deleted. A dead enum is the worst kind of source: it reads exactly like\n * a live one.\n *\n * A stale entry here is worse than no list at all, because it refuses a file the\n * runtime would have taken. If the deck grows a format, this table moves with it.\n *\n * Pure data. No React, no ajv, nothing imported.\n */\n\n/** One accepted format: its MIME type and the extensions that carry it. */\nexport interface FileFormat {\n mimeType: string;\n /** Leading dot, lowercase — the shape a file input's `accept` wants. */\n extensions: string[];\n /** How the format is named to a user, uppercase. */\n label: string;\n}\n\n/**\n * What a `document` slot takes: PDF, plus the two image formats the extract\n * model reads as a single-page document.\n */\nexport const DOCUMENT_FORMATS: readonly FileFormat[] = [\n { mimeType: 'application/pdf', extensions: ['.pdf'], label: 'PDF' },\n { mimeType: 'image/jpeg', extensions: ['.jpg', '.jpeg'], label: 'JPG' },\n { mimeType: 'image/png', extensions: ['.png'], label: 'PNG' },\n];\n\n/**\n * What an `image` slot takes: PNG, JPEG, WEBP — all three measured through the\n * vision path.\n *\n * `.jpg` and `.jpeg` both ride `image/jpeg`. `JPG` is the label because that is\n * the spelling the runtime uses, but a file named `.jpeg` is the same bytes and\n * must not be refused over its spelling.\n */\nexport const IMAGE_FORMATS: readonly FileFormat[] = [\n { mimeType: 'image/png', extensions: ['.png'], label: 'PNG' },\n { mimeType: 'image/jpeg', extensions: ['.jpg', '.jpeg'], label: 'JPG' },\n { mimeType: 'image/webp', extensions: ['.webp'], label: 'WEBP' },\n];\n\nexport function formatsForKind(kind: 'document' | 'image'): readonly FileFormat[] {\n return kind === 'image' ? IMAGE_FORMATS : DOCUMENT_FORMATS;\n}\n\n/** `\"PDF, DOCX, PPTX\"` — the hint shown under a dropzone. */\nexport function acceptLabelForKind(kind: 'document' | 'image'): string {\n return formatsForKind(kind)\n .map((format) => format.label)\n .join(', ');\n}\n\n/**\n * Whether a picked file is one this kind accepts.\n *\n * Checks the MIME type first and falls back to the extension, because a\n * browser's `File.type` is empty often enough to matter: an OS with no handler\n * registered for `.docx` reports `''`, and refusing that file would be refusing\n * a valid one over a fact about the user's machine. A wrong-but-present MIME\n * type is still a rejection — that is the case this exists for.\n */\nexport function isAcceptedFile(\n kind: 'document' | 'image',\n file: { name: string; type: string },\n): boolean {\n const formats = formatsForKind(kind);\n const mimeType = file.type.split(';', 1)[0]?.trim().toLowerCase() ?? '';\n if (mimeType) return formats.some((format) => format.mimeType === mimeType);\n const name = file.name.toLowerCase();\n return formats.some((format) => format.extensions.some((ext) => name.endsWith(ext)));\n}\n\n/**\n * The accept map a file input wants: MIME type to extensions.\n *\n * Shaped for `react-dropzone`'s `accept`, which is the same shape the DOM's\n * `accept` attribute is built from. Listing extensions BESIDE the MIME type is\n * what makes the empty-`File.type` case above work in the OS picker too.\n */\nexport function acceptMapForKind(kind: 'document' | 'image'): Record<string, string[]> {\n const map: Record<string, string[]> = {};\n for (const format of formatsForKind(kind)) map[format.mimeType] = [...format.extensions];\n return map;\n}\n"]}
@@ -0,0 +1,94 @@
1
+ import { ownProp, hasOwnProp } from './chunk-V3OV2XQT.js';
2
+
3
+ // src/core/native-content.ts
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ function readText(record, key) {
8
+ const value = ownProp(record, key);
9
+ return typeof value === "string" && value.length > 0 ? value : void 0;
10
+ }
11
+ function readNumber(record, key) {
12
+ const value = ownProp(record, key);
13
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
14
+ }
15
+ function readDocumentContent(value) {
16
+ if (!isRecord(value)) return void 0;
17
+ const url = readText(value, "url");
18
+ if (url === void 0) return void 0;
19
+ return {
20
+ url,
21
+ publicUrl: readText(value, "public_url"),
22
+ mimeType: readText(value, "mime_type"),
23
+ filename: readText(value, "filename"),
24
+ title: readText(value, "title"),
25
+ snippet: readText(value, "snippet")
26
+ };
27
+ }
28
+ function readImageContent(value) {
29
+ if (!isRecord(value)) return void 0;
30
+ const url = readText(value, "url");
31
+ if (url === void 0) return void 0;
32
+ return {
33
+ url,
34
+ publicUrl: readText(value, "public_url"),
35
+ caption: readText(value, "caption"),
36
+ mimeType: readText(value, "mime_type"),
37
+ filename: readText(value, "filename"),
38
+ width: readNumber(value, "width"),
39
+ height: readNumber(value, "height"),
40
+ sourcePrompt: readText(value, "source_prompt")
41
+ };
42
+ }
43
+ function readHtmlContent(value) {
44
+ if (!isRecord(value)) return void 0;
45
+ const innerHtml = readText(value, "inner_html");
46
+ if (innerHtml === void 0) return void 0;
47
+ return { innerHtml, cssClass: readText(value, "css_class") };
48
+ }
49
+ var NATIVE_HTML_CONCEPT_REF = "native.Html";
50
+ var NATIVE_DATE_CONCEPT_REF = "native.Date";
51
+ var NATIVE_COMPOSITE_CONCEPT_REF = "native.Composite";
52
+ function readCompositeContent(value) {
53
+ if (!isRecord(value)) return void 0;
54
+ return Object.entries(value).map(([name, member]) => ({ name, value: member }));
55
+ }
56
+ function isNativeHtmlNode(node) {
57
+ return refinesNative(node, NATIVE_HTML_CONCEPT_REF);
58
+ }
59
+ function isNativeDateNode(node) {
60
+ return refinesNative(node, NATIVE_DATE_CONCEPT_REF);
61
+ }
62
+ function isNativeCompositeNode(node) {
63
+ return refinesNative(node, NATIVE_COMPOSITE_CONCEPT_REF);
64
+ }
65
+ function refinesNative(node, ref) {
66
+ if (node.conceptRef === ref) return true;
67
+ return node.refines?.includes(ref) ?? false;
68
+ }
69
+ function readDateContent(value) {
70
+ if (typeof value === "string") {
71
+ return value.length > 0 ? { date: value } : void 0;
72
+ }
73
+ if (!isRecord(value)) return void 0;
74
+ const inner = ownProp(value, "date");
75
+ const date = typeof inner === "string" ? inner : isRecord(inner) ? readText(inner, "date") : void 0;
76
+ if (date === void 0) return void 0;
77
+ return { date, time: readText(value, "time") };
78
+ }
79
+ function formatDateContent(content) {
80
+ return content.time ? `${content.date} ${content.time}` : content.date;
81
+ }
82
+ function isViewableUrl(url) {
83
+ if (!url) return false;
84
+ if (/^\/(?!\/)/.test(url)) return true;
85
+ return /^https?:/i.test(url) || /^data:/i.test(url) || /^blob:/i.test(url);
86
+ }
87
+ var TYPED_SCALAR_MARKERS = ["__class__", "__module__"];
88
+ function hasTypedScalarMarkers(value) {
89
+ return isRecord(value) && TYPED_SCALAR_MARKERS.every((marker) => hasOwnProp(value, marker));
90
+ }
91
+
92
+ export { NATIVE_COMPOSITE_CONCEPT_REF, NATIVE_DATE_CONCEPT_REF, NATIVE_HTML_CONCEPT_REF, TYPED_SCALAR_MARKERS, formatDateContent, hasTypedScalarMarkers, isNativeCompositeNode, isNativeDateNode, isNativeHtmlNode, isViewableUrl, readCompositeContent, readDateContent, readDocumentContent, readHtmlContent, readImageContent };
93
+ //# sourceMappingURL=chunk-45C2MKK6.js.map
94
+ //# sourceMappingURL=chunk-45C2MKK6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/native-content.ts"],"names":[],"mappings":";;;AA4CA,SAAS,SAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAGA,SAAS,QAAA,CAAS,QAAiC,GAAA,EAAiC;AAClF,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,MAAA,EAAQ,GAAG,CAAA;AACjC,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,MAAA,GAAS,IAAI,KAAA,GAAQ,MAAA;AACjE;AAEA,SAAS,UAAA,CAAW,QAAiC,GAAA,EAAiC;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KAAA,EAAyB;AAC7D,EAAA,OAAO,QAAA,CAAS,KAAK,CAAA,IAAK,oBAAA,CAAqB,KAAA,CAAM,CAAC,MAAA,KAAW,UAAA,CAAW,KAAA,EAAO,MAAM,CAAC,CAAA;AAC5F","file":"chunk-45C2MKK6.js","sourcesContent":["/**\n * How to READ the native content models — the result side's twin of\n * `./file-formats`.\n *\n * A renderer handed a result knows the field's `kind` from the descriptor, and\n * for the kinds whose value is a structured content model rather than a bare\n * scalar (`document`, `image`, `date`) it must then read that model's members.\n * **That is reading the standard, not sniffing at it.** The distinction is the\n * whole reason this module exists as data rather than as heuristics inside a\n * control: a reader keyed by a STATED kind consults a pinned definition, where\n * a reader that works out *which* kind it is holding by counting properties is\n * guessing — and guessing is exactly what [../../docs/derivation-swap.md]\n * records removing from the input side.\n *\n * ## Where each shape comes from\n *\n * `native.Image` and `native.Document` are pinned by the standard, in\n * `docs/spec/native-concepts.md` § \"The Pinned Set (MTHDS 1.0.0)\". Both carry a\n * required `url` — a storage URI, an HTTP(S) URL, or a base64 data URL — and\n * optional presentation members beside it. Nothing here adds a member the spec\n * does not state.\n *\n * `native.Date` is pinned the same way (`{date, time}`), but a `date` FIELD\n * inside a structured concept is not a `native.Date` value: it is a python\n * `datetime.date`, and the serialization layer stamps it with its class. So a\n * date arrives in one of three legal shapes, all three of which a run really\n * produces:\n *\n * \"2026-03-14\" a plain ISO string\n * { date: \"2026-03-14\", __class__: \"date\", … } a typed scalar\n * { date: \"2026-03-14\", time: \"15:40:00\" } native.Date\n *\n * The typed-scalar envelope is the one shape the standard does NOT pin — it is\n * a serialization fact, measured off a real run rather than read off a spec —\n * and it is called out as such here so nobody mistakes it for normative.\n *\n * This module lives in core, not beside the control that renders it, for the\n * reason `file-formats.ts` established: a host that shows a result its own way\n * needs the same answer the control uses, and two copies of an answer is two\n * places for it to drift. Pure data and pure functions — no React.\n */\n\nimport { hasOwnProp, ownProp } from './own-property';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** A member the content models declare as `type = \"text\"`, when it is one. */\nfunction readText(record: Record<string, unknown>, key: string): string | undefined {\n const value = ownProp(record, key);\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction readNumber(record: Record<string, unknown>, key: string): number | undefined {\n const value = ownProp(record, key);\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * `native.Document`, read.\n *\n * `url` is the only required member; everything else is a producer's courtesy,\n * so a reader that demands any of them describes a value the standard permits\n * as malformed.\n */\nexport interface DocumentContentView {\n url: string;\n publicUrl?: string;\n mimeType?: string;\n filename?: string;\n title?: string;\n snippet?: string;\n}\n\n/** `native.Image`, read. `width`/`height` are optional but PAIRED by the spec. */\nexport interface ImageContentView {\n url: string;\n publicUrl?: string;\n caption?: string;\n mimeType?: string;\n filename?: string;\n width?: number;\n height?: number;\n sourcePrompt?: string;\n}\n\n/** `native.Date` (and the typed-scalar envelope a nested `date` field arrives in). */\nexport interface DateContentView {\n /** ISO 8601 calendar date, `YYYY-MM-DD`. */\n date: string;\n /** ISO 8601 time of day, present only when the source stated one. */\n time?: string;\n}\n\n/**\n * Read a `document`-kind value. `undefined` when the value carries no `url`,\n * which is the one member the standard requires — a caller renders its own\n * absence rather than being handed a half-value to test.\n */\nexport function readDocumentContent(value: unknown): DocumentContentView | undefined {\n if (!isRecord(value)) return undefined;\n const url = readText(value, 'url');\n if (url === undefined) return undefined;\n return {\n url,\n publicUrl: readText(value, 'public_url'),\n mimeType: readText(value, 'mime_type'),\n filename: readText(value, 'filename'),\n title: readText(value, 'title'),\n snippet: readText(value, 'snippet'),\n };\n}\n\n/** Read an `image`-kind value. Same contract as `readDocumentContent`. */\nexport function readImageContent(value: unknown): ImageContentView | undefined {\n if (!isRecord(value)) return undefined;\n const url = readText(value, 'url');\n if (url === undefined) return undefined;\n return {\n url,\n publicUrl: readText(value, 'public_url'),\n caption: readText(value, 'caption'),\n mimeType: readText(value, 'mime_type'),\n filename: readText(value, 'filename'),\n width: readNumber(value, 'width'),\n height: readNumber(value, 'height'),\n sourcePrompt: readText(value, 'source_prompt'),\n };\n}\n\n/**\n * `native.Html`, read.\n *\n * The only content model here that is NOT reached by a field kind, and the\n * reason is a deliberate decision of the standard: the kind vocabulary has no\n * `html` member, so a `native.Html` value is an `object` node over its two\n * declared fields. That is right for the descriptor — the kinds name how a value\n * is ENTERED, and markup is entered as text — and wrong for a result view, which\n * would otherwise print a page's source at a reader.\n *\n * So this one is keyed by CONCEPT rather than by kind, through\n * `isNativeHtmlNode` below. That is a membership test on facts the descriptor\n * states (`concept_ref`, `refines`), which the standard's own page calls out as\n * the supported way to ask \"does this refine `native.X`?\" — the opposite of\n * inspecting a value to guess what it is.\n */\nexport interface HtmlContentView {\n /** The markup itself. The one required member. */\n innerHtml: string;\n /** A class name for a wrapper a consumer may put around it, when stated. */\n cssClass?: string;\n}\n\n/** Read an `native.Html` value. `undefined` when it carries no markup. */\nexport function readHtmlContent(value: unknown): HtmlContentView | undefined {\n if (!isRecord(value)) return undefined;\n const innerHtml = readText(value, 'inner_html');\n if (innerHtml === undefined) return undefined;\n return { innerHtml, cssClass: readText(value, 'css_class') };\n}\n\n/** The concept refs whose content model is multi-property, spelled once each. */\nexport const NATIVE_HTML_CONCEPT_REF = 'native.Html';\nexport const NATIVE_DATE_CONCEPT_REF = 'native.Date';\nexport const NATIVE_COMPOSITE_CONCEPT_REF = 'native.Composite';\n\n/** One member of a composite: the name it was composed under, and its content. */\nexport interface CompositeMember {\n name: string;\n value: unknown;\n}\n\n/**\n * Read a `native.Composite` — a named composition of contents.\n *\n * The members are returned in the order the payload states them, which is the\n * order the method composed them in and the only order there is: a composite\n * declares no fields, so there is no authored order to prefer over it.\n *\n * `undefined` for anything that is not a record, so the caller falls back.\n */\nexport function readCompositeContent(value: unknown): CompositeMember[] | undefined {\n if (!isRecord(value)) return undefined;\n return Object.entries(value).map(([name, member]) => ({ name, value: member }));\n}\n\n/**\n * Whether a descriptor node carries markup — its concept IS `native.Html`, or\n * refines it.\n *\n * The refinement chain is checked, not just the leaf, because a method may\n * declare `legal.ClauseMarkup` refining `native.Html` and a reader of that result\n * wants the markup rendered just the same. `refines` is on the wire for exactly\n * this question.\n */\nexport function isNativeHtmlNode(node: {\n conceptRef?: string;\n refines?: readonly string[];\n}): boolean {\n return refinesNative(node, NATIVE_HTML_CONCEPT_REF);\n}\n\n/**\n * Whether a node IS a `native.Date` — the other content model the kind\n * vocabulary cannot name.\n *\n * `native.Date` is `{date, time}`, two properties, so nothing unwraps it and its\n * node is an `object`. Correct for the descriptor and wrong for a reader: a date\n * result rendered structurally is a two-field card whose second field says \"not\n * provided\", where the answer is a date. The `date` ARM already reads exactly\n * this model — `readDateContent` takes `{date, time}` — it just never fires,\n * because the kind says `object`.\n *\n * A `date` FIELD inside a structure is a different thing and needs none of this:\n * it carries `kind: \"date\"` already.\n */\nexport function isNativeDateNode(node: {\n conceptRef?: string;\n refines?: readonly string[];\n}): boolean {\n return refinesNative(node, NATIVE_DATE_CONCEPT_REF);\n}\n\n/**\n * Whether a node is a `native.Composite` — a named bag of contents.\n *\n * The third concept the kind vocabulary cannot name, and the one where it is\n * least able to: a composite declares no members at all, so its descriptor is\n * `kind: \"unknown\"` and its payload schema is `{additionalProperties: true}`\n * with no properties. Both are TRUE — the standard's escape hatch, honestly\n * used — and both leave a renderer with nothing to read, so the default\n * fallback prints the whole thing as a JSON blob.\n *\n * That is the worst available answer to a value that is, by definition, a map\n * of ordinary `StuffContent`s. Keyed by concept, a renderer can at least show\n * the members as the named things they are. See `CompositeValue`.\n */\nexport function isNativeCompositeNode(node: {\n conceptRef?: string;\n refines?: readonly string[];\n}): boolean {\n return refinesNative(node, NATIVE_COMPOSITE_CONCEPT_REF);\n}\n\n/** Its concept IS the named native, or refines it. */\nfunction refinesNative(\n node: { conceptRef?: string; refines?: readonly string[] },\n ref: string,\n): boolean {\n if (node.conceptRef === ref) return true;\n return node.refines?.includes(ref) ?? false;\n}\n\n/**\n * Read a `date`-kind value, in any of the three shapes a run produces.\n *\n * The `date` member is read one level deep, because `native.Date`'s own `date`\n * member is a `datetime.date` and therefore arrives inside the same typed-scalar\n * envelope the whole value may already be wrapped in. One level is enough and\n * the recursion is bounded on purpose: a second envelope would be a\n * serialization bug, and following it forever would turn one into a hang.\n */\nexport function readDateContent(value: unknown): DateContentView | undefined {\n if (typeof value === 'string') {\n return value.length > 0 ? { date: value } : undefined;\n }\n if (!isRecord(value)) return undefined;\n\n const inner = ownProp(value, 'date');\n const date =\n typeof inner === 'string' ? inner : isRecord(inner) ? readText(inner, 'date') : undefined;\n if (date === undefined) return undefined;\n return { date, time: readText(value, 'time') };\n}\n\n/** `{date}` / `{date, time}` as one line, which is how both are read aloud. */\nexport function formatDateContent(content: DateContentView): string {\n return content.time ? `${content.date} ${content.time}` : content.date;\n}\n\n/**\n * Whether a browser can paint this URL as-is.\n *\n * A `pipelex-storage://` reference cannot be resolved client-side — that is the\n * upload seam's job (see [../../docs/upload-seam.md]) — so a renderer with no\n * resolver must show the reference rather than a broken `<img>`. `file:` is\n * deliberately NOT viewable: a run on a developer's machine writes one, and a\n * browser refuses to load it from a page served over http.\n *\n * **A root-relative path counts**, and leaving it out was a real bug rather\n * than an omission. A host's URL resolver naturally hands back a path on its\n * OWN origin — `/api/assets/…`, an authenticated route that streams the object\n * — which is the whole point of resolving rather than exposing storage. This\n * predicate rejected it for having no scheme, so the resolved URL was thrown\n * away and the arms fell back to the payload's `public_url`: a presigned URL\n * that had already expired. The image stayed broken with the fix in place.\n *\n * `//host/path` is deliberately excluded. It is protocol-relative, so it points\n * at another origin while looking like a path.\n */\nexport function isViewableUrl(url: string | undefined): url is string {\n if (!url) return false;\n if (/^\\/(?!\\/)/.test(url)) return true;\n return /^https?:/i.test(url) || /^data:/i.test(url) || /^blob:/i.test(url);\n}\n\n/**\n * The typed-scalar markers the serialization layer stamps onto a value.\n *\n * Exported so a host can recognise (and strip) them; nothing in the kernel\n * BRANCHES on them, which is the point — a reader keyed by these would be\n * reading the serializer instead of the standard.\n */\nexport const TYPED_SCALAR_MARKERS = ['__class__', '__module__'] as const;\n\n/** Whether a record carries the typed-scalar markers. Informational. */\nexport function hasTypedScalarMarkers(value: unknown): boolean {\n return isRecord(value) && TYPED_SCALAR_MARKERS.every((marker) => hasOwnProp(value, marker));\n}\n"]}
@@ -0,0 +1,80 @@
1
+ import { isNativeHtmlNode, readHtmlContent, readDocumentContent, readImageContent } from './chunk-45C2MKK6.js';
2
+ import { ownProp } from './chunk-V3OV2XQT.js';
3
+
4
+ // src/core/stuff-files.ts
5
+ function collectStuffFiles(field, value) {
6
+ const found = [];
7
+ walk(field, value, [], found);
8
+ return found;
9
+ }
10
+ function walk(field, raw, path, out) {
11
+ const value = unwrapContent(field, raw);
12
+ const here = path.length > 0 ? path : [field.name];
13
+ if (isNativeHtmlNode(field)) {
14
+ const content = readHtmlContent(value);
15
+ if (content?.innerHtml) {
16
+ out.push({
17
+ text: content.innerHtml,
18
+ extension: "html",
19
+ path: here.join("."),
20
+ kind: "markup"
21
+ });
22
+ }
23
+ return;
24
+ }
25
+ switch (field.kind) {
26
+ case "image": {
27
+ const content = readImageContent(value);
28
+ if (content?.url) {
29
+ out.push({
30
+ url: content.url,
31
+ publicUrl: content.publicUrl,
32
+ filename: content.filename,
33
+ mimeType: content.mimeType,
34
+ path: here.join("."),
35
+ kind: "image"
36
+ });
37
+ }
38
+ return;
39
+ }
40
+ case "document": {
41
+ const content = readDocumentContent(value);
42
+ if (content?.url) {
43
+ out.push({
44
+ url: content.url,
45
+ publicUrl: content.publicUrl,
46
+ filename: content.filename,
47
+ mimeType: content.mimeType,
48
+ path: here.join("."),
49
+ kind: "document"
50
+ });
51
+ }
52
+ return;
53
+ }
54
+ case "object": {
55
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
56
+ const record = value;
57
+ for (const child of field.fields) {
58
+ walk(child, ownProp(record, child.name), [...here, child.name], out);
59
+ }
60
+ return;
61
+ }
62
+ case "list": {
63
+ if (!Array.isArray(value)) return;
64
+ value.forEach((entry, index) => walk(field.item, entry, [...here, String(index)], out));
65
+ return;
66
+ }
67
+ default:
68
+ return;
69
+ }
70
+ }
71
+ function unwrapContent(field, value) {
72
+ if (!field.contentKey) return value;
73
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
74
+ const unwrapped = ownProp(value, field.contentKey);
75
+ return unwrapped === void 0 ? value : unwrapped;
76
+ }
77
+
78
+ export { collectStuffFiles };
79
+ //# sourceMappingURL=chunk-4BSBBG2T.js.map
80
+ //# sourceMappingURL=chunk-4BSBBG2T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/stuff-files.ts"],"names":[],"mappings":";;;;AAuDO,SAAS,iBAAA,CAAkB,OAAiB,KAAA,EAA6B;AAC9E,EAAA,MAAM,QAAqB,EAAC;AAC5B,EAAA,IAAA,CAAK,KAAA,EAAO,KAAA,EAAO,EAAC,EAAG,KAAK,CAAA;AAC5B,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,IAAA,CAAK,KAAA,EAAiB,GAAA,EAAc,IAAA,EAAgB,GAAA,EAAwB;AACnF,EAAA,MAAM,KAAA,GAAQ,aAAA,CAAc,KAAA,EAAO,GAAG,CAAA;AACtC,EAAA,MAAM,OAAO,IAAA,CAAK,MAAA,GAAS,IAAI,IAAA,GAAO,CAAC,MAAM,IAAI,CAAA;AAYjD,EAAA,IAAI,gBAAA,CAAiB,KAAK,CAAA,EAAG;AAC3B,IAAA,MAAM,OAAA,GAAU,gBAAgB,KAAK,CAAA;AACrC,IAAA,IAAI,SAAS,SAAA,EAAW;AACtB,MAAA,GAAA,CAAI,IAAA,CAAK;AAAA,QACP,MAAM,OAAA,CAAQ,SAAA;AAAA,QACd,SAAA,EAAW,MAAA;AAAA,QACX,IAAA,EAAM,IAAA,CAAK,IAAA,CAAK,GAAG,CAAA;AAAA,QACnB,IAAA,EAAM;AAAA,OACP,CAAA;AAAA,IACH;AAC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AC,GAAG,IAAA,EAAM,KAAA,CAAM,IAAI,CAAA,EAAG,GAAG,CAAA;AAAA,MACrE;AACA,MAAA;AAAA,IACF;AAAA,IACA,KAAK,MAAA,EAAQ;AACX,MAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AAI3B,MAAA,KAAA,CAAM,QAAQ,CAAC,KAAA,EAAO,KAAA,KAAU,IAAA,CAAK,MAAM,IAAA,EAAM,KAAA,EAAO,CAAC,GAAG,MAAM,MAAA,CAAO,KAAK,CAAC,CAAA,EAAG,GAAG,CAAC,CAAA;AACtF,MAAA;AAAA,IACF;AAAA,IACA;AAIE,MAAA;AAAA;AAEN;AAMA,SAAS,aAAA,CAAc,OAAiB,KAAA,EAAyB;AAC/D,EAAA,IAAI,CAAC,KAAA,CAAM,UAAA,EAAY,OAAO,KAAA;AAC9B,EAAA,IAAI,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG,OAAO,KAAA;AAChF,EAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,KAAA,EAAkC,KAAA,CAAM,UAAU,CAAA;AAC5E,EAAA,OAAO,SAAA,KAAc,SAAY,KAAA,GAAQ,SAAA;AAC3C","file":"chunk-4BSBBG2T.js","sourcesContent":["import { ownProp } from './own-property';\nimport {\n isNativeHtmlNode,\n readDocumentContent,\n readHtmlContent,\n readImageContent,\n} from './native-content';\nimport type { RunField } from './descriptor';\n\n/**\n * One file a stuff carries: what to fetch, and what to call it once saved.\n */\nexport interface StuffFile {\n /**\n * The durable reference or URL the value states, for a file held BY\n * REFERENCE. Absent for inline content, which needs no fetch.\n */\n url?: string;\n /**\n * The content itself, for a file the stuff carries INLINE — markup, today.\n * Exactly one of `url` and `text` is set.\n */\n text?: string;\n /** The extension to save inline content under, without the dot. */\n extension?: string;\n /**\n * The URL that works outside this session, when the value carries one. A host\n * whose display URL is session-scoped (an owner-checked proxy route) needs\n * this for anything that leaves the browser.\n */\n publicUrl?: string;\n /** The file's own name when it states one — otherwise the caller derives it. */\n filename?: string;\n mimeType?: string;\n /** Where it sat, dotted: `report.attachments.2.scan`. Names a saved file. */\n path: string;\n kind: 'image' | 'document' | 'markup';\n}\n\n/**\n * Every file inside a stuff, found by walking the DESCRIPTOR — never the value.\n *\n * The distinction is the whole point. A payload walk would have to decide what\n * a file is by looking at it: an object with a `url`, a string that ends in\n * `.pdf`. That is the guessing this package exists to remove, and it is wrong in\n * both directions — a method whose output legitimately has a `url` field of its\n * own is not a document, and a stored image whose reference carries no extension\n * is. The descriptor already states `kind: \"image\"` or `kind: \"document\"`, so\n * the walk reads the declaration and consults the value only for the members\n * that declaration promises.\n *\n * Ordering is the authored one, depth-first, which is the order the rendered\n * view puts them in — so a download of three images numbers them the way the\n * reader saw them.\n */\nexport function collectStuffFiles(field: RunField, value: unknown): StuffFile[] {\n const found: StuffFile[] = [];\n walk(field, value, [], found);\n return found;\n}\n\nfunction walk(field: RunField, raw: unknown, path: string[], out: StuffFile[]): void {\n const value = unwrapContent(field, raw);\n const here = path.length > 0 ? path : [field.name];\n\n // Markup, before the kind switch, exactly as the renderer takes it: a\n // `native.Html` node's KIND is `object` (its content model has two members),\n // so the switch below would walk into it looking for files and find none.\n //\n // It is a file even though nothing stores it as one. The stuff IS a page —\n // the reader is looking at a rendered report — and handing them a JSON\n // envelope with the page inside it as a string is the same mistake as handing\n // them a URL instead of a picture. `isNativeHtmlNode` asks the descriptor\n // whether the concept refines `native.Html`, which is the standard's own way\n // to ask; it never looks at the value to decide.\n if (isNativeHtmlNode(field)) {\n const content = readHtmlContent(value);\n if (content?.innerHtml) {\n out.push({\n text: content.innerHtml,\n extension: 'html',\n path: here.join('.'),\n kind: 'markup',\n });\n }\n return;\n }\n\n switch (field.kind) {\n case 'image': {\n const content = readImageContent(value);\n if (content?.url) {\n out.push({\n url: content.url,\n publicUrl: content.publicUrl,\n filename: content.filename,\n mimeType: content.mimeType,\n path: here.join('.'),\n kind: 'image',\n });\n }\n return;\n }\n case 'document': {\n const content = readDocumentContent(value);\n if (content?.url) {\n out.push({\n url: content.url,\n publicUrl: content.publicUrl,\n filename: content.filename,\n mimeType: content.mimeType,\n path: here.join('.'),\n kind: 'document',\n });\n }\n return;\n }\n case 'object': {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return;\n const record = value as Record<string, unknown>;\n for (const child of field.fields) {\n walk(child, ownProp(record, child.name), [...here, child.name], out);\n }\n return;\n }\n case 'list': {\n if (!Array.isArray(value)) return;\n // The element descriptor's own `name` is unused by the standard, so the\n // index is what identifies an entry — the same thing the rendered list\n // shows beside each row.\n value.forEach((entry, index) => walk(field.item, entry, [...here, String(index)], out));\n return;\n }\n default:\n // Every other kind is a scalar. It cannot contain a file, and a `native`\n // node with no declared members (an `unknown` kind — a composite, say)\n // states nothing a walk could follow, so there is nothing to look at.\n return;\n }\n}\n\n/**\n * The one unwrap path, matching the renderer's: a content model is opened by\n * the property the schema named, and by nothing else.\n */\nfunction unwrapContent(field: RunField, value: unknown): unknown {\n if (!field.contentKey) return value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;\n const unwrapped = ownProp(value as Record<string, unknown>, field.contentKey);\n return unwrapped === undefined ? value : unwrapped;\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import { buildPipeRef } from './chunk-XYQ7NXQZ.js';
2
+ import { ownProp } from './chunk-V3OV2XQT.js';
3
+
4
+ // src/core/output-form.ts
5
+ function getPipeOutputForm(outputForm, domain, pipeCode) {
6
+ if (!outputForm || !pipeCode) return void 0;
7
+ if (domain) {
8
+ const byRef = ownProp(outputForm, buildPipeRef(domain, pipeCode));
9
+ if (byRef) return byRef;
10
+ }
11
+ return ownProp(outputForm, pipeCode);
12
+ }
13
+
14
+ export { getPipeOutputForm };
15
+ //# sourceMappingURL=chunk-IIU3YK4O.js.map
16
+ //# sourceMappingURL=chunk-IIU3YK4O.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/output-form.ts"],"names":[],"mappings":";;;;AA6CO,SAAS,iBAAA,CACd,UAAA,EACA,MAAA,EACA,QAAA,EACsC;AACtC,EAAA,IAAI,CAAC,UAAA,IAAc,CAAC,QAAA,EAAU,OAAO,MAAA;AACrC,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,MAAM,QAAQ,OAAA,CAAQ,UAAA,EAAY,YAAA,CAAa,MAAA,EAAQ,QAAQ,CAAC,CAAA;AAChE,IAAA,IAAI,OAAO,OAAO,KAAA;AAAA,EACpB;AACA,EAAA,OAAO,OAAA,CAAQ,YAAY,QAAQ,CAAA;AACrC","file":"chunk-IIU3YK4O.js","sourcesContent":["/**\n * The output-form descriptor lookup.\n *\n * **This module used to declare the artifact; now it only addresses it.** The\n * types come from `mthds/protocol`, exactly as the input side's do — the\n * standard grew `output_form` as a page of its own, and grew `json_schema` on\n * the output contract in the same version, so a renderer reads both off the wire\n * instead of having them supplied beside it. What is left here is the twin of\n * `getPipeInputForm`: the lookup, and the tolerance for the same two key\n * conventions. [docs/contract-mirror.md](../../docs/contract-mirror.md) states\n * the rule this now obeys — the contract types are the standard's, not this\n * package's, and a member this package wants on one is a change to the standard\n * before it is a change here.\n *\n * **An output is a concept ref exactly like an input is.** Same concept, same\n * structure, same field kinds, same nesting; what differs is only the three SLOT\n * facts an output has none of (an authored `name`, the three-valued `presence`,\n * `gating`), all three optional on the standard's node precisely so a node can\n * exist without them. That is why `buildResultField` maps an output node through\n * the very mapper `buildRunFields` uses, and why there is no second node union\n * anywhere in this package.\n *\n * | | Inputs | Outputs |\n * | --- | --- | --- |\n * | identity, plurality, optionality | `pipe_io_contracts` | `pipe_io_contracts` |\n * | shape / JSON Schema | `json_schema` on the input contract | `json_schema` on the output contract |\n * | presentation view | `input_form` | `output_form` |\n *\n * The two rows that used to read \"nothing\" are the change this package was built\n * against while it was still a proposal; `wip/output-form-standard-change.md` is\n * the argument that landed it. The one asymmetry the language keeps is\n * `presence` versus `optional`: `!` MUST NOT appear on an output, so a\n * three-valued output marker would have an arm nothing could ever produce.\n */\n\nimport type { OutputForm, PipeOutputFormDescriptor } from 'mthds/protocol';\nimport { buildPipeRef } from './contracts';\nimport { ownProp } from './own-property';\n\nexport type { OutputForm, PipeOutputFormDescriptor };\n\n/**\n * Look a pipe's output descriptor up by code — the exact twin of\n * `getPipeInputForm`, tolerant of the same two key conventions.\n */\nexport function getPipeOutputForm(\n outputForm: OutputForm | null | undefined,\n domain: string | null | undefined,\n pipeCode: string | null | undefined,\n): PipeOutputFormDescriptor | undefined {\n if (!outputForm || !pipeCode) return undefined;\n if (domain) {\n const byRef = ownProp(outputForm, buildPipeRef(domain, pipeCode));\n if (byRef) return byRef;\n }\n return ownProp(outputForm, pipeCode);\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { acceptLabelForKind } from './chunk-2JWRG53S.js';
1
2
  import { collectSchemaDefs, resolveSchemaNode } from './chunk-OD3VYXUY.js';
2
3
  import { buildPipeRef } from './chunk-XYQ7NXQZ.js';
3
4
  import { ownProp } from './chunk-V3OV2XQT.js';
@@ -83,9 +84,8 @@ function mapNode(node, name, rawSchema, defs) {
83
84
  case "enum":
84
85
  return { ...common, kind: "enum", options: node.choices.map(String) };
85
86
  case "document":
86
- return { ...common, kind: "document", accept: "PDF, DOCX, TXT" };
87
87
  case "image":
88
- return { ...common, kind: "image", accept: "PNG, JPG, WEBP" };
88
+ return { ...common, kind: node.kind, accept: acceptLabelForKind(node.kind) };
89
89
  case "object": {
90
90
  const props = schema?.properties;
91
91
  return {
@@ -113,6 +113,15 @@ function mapNode(node, name, rawSchema, defs) {
113
113
  }
114
114
  return { ...common, kind: "unknown" };
115
115
  }
116
+ function buildResultField(descriptor, schema) {
117
+ const node = descriptor.field;
118
+ const defs = {};
119
+ collectSchemaDefs(schema, defs, { traverseArrays: true });
120
+ const wrapperKey = node.kind === "object" ? void 0 : scalarWrapperKey(schema);
121
+ const inner = wrapperKey === void 0 ? schema : schema.properties[wrapperKey];
122
+ const field = mapNode(node, node.name, inner, defs);
123
+ return wrapperKey === void 0 ? field : { ...field, contentKey: wrapperKey };
124
+ }
116
125
  function buildRunFields(descriptor, inputs) {
117
126
  return descriptor.fields.map((node) => {
118
127
  const input = ownProp(inputs, node.name);
@@ -123,6 +132,6 @@ function buildRunFields(descriptor, inputs) {
123
132
  });
124
133
  }
125
134
 
126
- export { buildRunFields, getPipeInputForm };
127
- //# sourceMappingURL=chunk-IIJRJGZQ.js.map
128
- //# sourceMappingURL=chunk-IIJRJGZQ.js.map
135
+ export { buildResultField, buildRunFields, getPipeInputForm };
136
+ //# sourceMappingURL=chunk-J4L32LD6.js.map
137
+ //# sourceMappingURL=chunk-J4L32LD6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/derive.ts"],"names":[],"mappings":";;;;;;AA8CO,SAAS,gBAAA,CACd,SAAA,EACA,MAAA,EACA,QAAA,EACqC;AACrC,EAAA,IAAI,CAAC,SAAA,IAAa,CAAC,QAAA,EAAU,OAAO,MAAA;AACpC,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,MAAM,QAAQ,OAAA,CAAQ,SAAA,EAAW,YAAA,CAAa,MAAA,EAAQ,QAAQ,CAAC,CAAA;AAC/D,IAAA,IAAI,OAAO,OAAO,KAAA;AAAA,EACpB;AACA,EAAA,OAAO,OAAA,CAAQ,WAAW,QAAQ,CAAA;AACpC;AAaA,SAAS,iBAAiB,MAAA,EAAoD;AAC5E,EAAA,MAAM,QAAQ,MAAA,EAAQ,UAAA;AACtB,EAAA,MAAM,OAAO,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,KAAK,IAAI,EAAC;AAC3C,EAAA,OAAO,IAAA,CAAK,MAAA,KAAW,CAAA,GAAI,IAAA,CAAK,CAAC,CAAA,GAAI,MAAA;AACvC;AAEA,SAAS,WAAW,CAAA,EAAgC;AAClD,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC;AAWA,SAA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K,IAAA,KAAS,QAAA,GAAW,MAAA,GAAY,iBAAiB,MAAoB,CAAA;AAC7F,EAAA,MAAM,QACJ,UAAA,KAAe,MAAA,GACV,MAAA,GACC,MAAA,CAAsB,WAA0C,UAAU,CAAA;AAElF,EAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,OAAO,IAAI,CAAA;AAClD,EAAA,OAAO,eAAe,MAAA,GAAY,KAAA,GAAQ,EAAE,GAAG,KAAA,EAAO,YAAY,UAAA,EAAW;AAC/E;AAEO,SAAS,cAAA,CACd,YACA,MAAA,EACY;AACZ,EAAA,OAAO,UAAA,CAAW,MAAA,CAAO,GAAA,CAAI,CAAC,IAAA,KAAS;AACrC,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,MAAA,EAAQ,IAAA,CAAK,IAAI,CAAA;AACvC,IAAA,MAAM,OAAmC,EAAC;AAC1C,IAAA,IAAI,KAAA,oBAAyB,KAAA,CAAM,WAAA,EAAa,MAAM,EAAE,cAAA,EAAgB,MAAM,CAAA;AAC9E,IAAA,MAAM,QAAQ,OAAA,CAAQ,IAAA,EAAM,KAAK,IAAA,EAAM,KAAA,EAAO,aAAuC,IAAI,CAAA;AACzF,IAAA,OAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAU,KAAK,QAAA,EAAU,MAAA,EAAQ,KAAK,MAAA,EAAO;AAAA,EAClE,CAAC,CAAA;AACH","file":"chunk-J4L32LD6.js","sourcesContent":["/**\n * The ONE derivation function: wire input-form descriptor → `RunField[]`.\n *\n * `buildRunFields` maps the standard's per-pipe descriptor STRUCTURALLY onto\n * the kernel's `RunField` shape. It decides nothing: what a field IS - its\n * kind, its constraints, its refinement chain, whether Run gates on it - is\n * stated by the wire, derived by the engine from the resolved library. The\n * heuristics that used to live here (native-concept sets, the url-bearing\n * object test, the depth-based prose/label rule) are deleted, not bypassed;\n * docs/derivation-swap.md is the record of that swap and of every behaviour\n * that moved with it.\n *\n * The contract is still consulted, for exactly two facts the wire deliberately\n * does not carry:\n *\n * - **`contentKey`** - the single property a native scalar's value sits inside\n * on the wire (`TextContent {text}`, `NumberContent {number}`). A renderer\n * holds the bare scalar; the value bridge wraps by this name. It is read off\n * the contract's `json_schema` because it is a fact about the PAYLOAD shape,\n * which is the schema's job - the descriptor describes the form, never the\n * payload.\n * - **Nested list bounds** - the wire puts `item_count` only on a top-level\n * fixed `[N]` slot, but the model behind a structured concept may state\n * `minItems`/`maxItems` on an array property of its own, and ajv enforces\n * them. Reading them off the schema is what keeps readiness from being more\n * permissive than the gate.\n *\n * Both are structural reads (a property count, two keywords ajv itself\n * enforces), not judgements - the mapper stays honest about owning no taxonomy.\n */\n\nimport type { PipeInputFormDescriptor } from 'mthds/protocol';\nimport type { InputForm, InputFormField, InputFormItem } from 'mthds/protocol';\n\nimport { buildPipeRef, type PipeInputContract } from './contracts';\nimport { acceptLabelForKind } from './file-formats';\nimport type { RunField, RunFieldCommon } from './descriptor';\nimport { ownProp } from './own-property';\nimport { collectSchemaDefs, resolveSchemaNode, type JsonSchema } from './schema-utils';\n\n/**\n * Look up a pipe's input-form descriptor by pipe code, tolerant of both key\n * conventions - the exact mirror of `getPipeIOContract`, because the standard\n * keys `input_form` by the same `pipe_ref` set as `pipe_io_contracts` and a\n * host tracks the same bare codes either way.\n */\nexport function getPipeInputForm(\n inputForm: InputForm | null | undefined,\n domain: string | null | undefined,\n pipeCode: string | null | undefined,\n): PipeInputFormDescriptor | undefined {\n if (!inputForm || !pipeCode) return undefined;\n if (domain) {\n const byRef = ownProp(inputForm, buildPipeRef(domain, pipeCode));\n if (byRef) return byRef;\n }\n return ownProp(inputForm, pipeCode);\n}\n\n/**\n * The single property a scalar content model holds its value in - `TextContent\n * {text}`, `NumberContent {number}`, `YesNoContent {yes_no}`.\n *\n * A wrapper is a schema declaring EXACTLY ONE property. A multi-property\n * content model (`DateContent {date, time}`, `HtmlContent {inner_html,\n * css_class}`) is not one and deliberately answers `undefined` - those travel\n * as the structures they are, which the wire now also says by giving them\n * `kind: \"object\"`. Reading the declared shape rather than keeping a list of\n * wrapping concepts is what covers a concept nobody remembered to add.\n */\nfunction scalarWrapperKey(schema: JsonSchema | undefined): string | undefined {\n const props = schema?.properties as Record<string, JsonSchema> | undefined;\n const keys = props ? Object.keys(props) : [];\n return keys.length === 1 ? keys[0] : undefined;\n}\n\nfunction numOrUndef(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\n/** The inclusive bound a control can express for a wire-stated exclusive one.\n * On an integer the open interval has a nearest neighbour and the conversion\n * is exact (`> 0` IS `>= 1`), so `toNearest` steps off the endpoint onto it.\n * It rounds rather than adding one, because the endpoint need not be integral\n * - JSON Schema allows `> 0.5` on an integer node, whose nearest neighbour is\n * `1`, not `1.5`. On a float the interval has no nearest neighbour, and the\n * answer is to publish no bound at all: a control that only clamps cannot\n * express an open interval, and naming the excluded endpoint would advertise\n * the one value the gate is about to refuse. */\nfunction inclusiveFrom(\n bound: number | undefined,\n integer: boolean | undefined,\n toNearest: (endpoint: number) => number,\n): number | undefined {\n return typeof bound === 'number' && integer === true ? toNearest(bound) : undefined;\n}\n\n/** Resolve one schema node the same way the gate's validator will see it -\n * to the FIXPOINT, so a nullable `$ref` (pydantic's Optional concept-typed\n * field) yields its definition rather than an unresolved reference. */\nfunction resolveSchema(\n schema: JsonSchema | undefined,\n defs: Record<string, JsonSchema>,\n): JsonSchema | undefined {\n return schema ? resolveSchemaNode(schema, defs) : undefined;\n}\n\n/** The slots every wire node carries, mapped onto the descriptor's names. */\nfunction commonOf(node: InputFormItem, name: string): RunFieldCommon {\n return {\n name,\n title: node.title,\n conceptRef: node.concept_ref,\n refines: node.refines,\n description: node.description,\n required: node.required,\n defaultValue: node.default_value,\n examples: node.examples,\n hints: node.hints,\n };\n}\n\n/**\n * Map one wire node onto a `RunField`, walking the aligned `json_schema` node\n * beside it. The schema walk supplies only `contentKey` and list bounds (see\n * the module header); a missing or misaligned schema degrades to their absence,\n * never to a different field.\n */\nfunction mapNode(\n node: InputFormItem,\n name: string,\n rawSchema: JsonSchema | undefined,\n defs: Record<string, JsonSchema>,\n): RunField {\n const schema = resolveSchema(rawSchema, defs);\n const common = commonOf(node, name);\n\n switch (node.kind) {\n case 'text':\n case 'prose':\n return {\n ...common,\n contentKey: scalarWrapperKey(schema),\n kind: node.kind,\n minLength: node.min_length,\n maxLength: node.max_length,\n pattern: node.pattern,\n format: node.format,\n };\n case 'date':\n return { ...common, kind: 'date', datetime: node.datetime };\n case 'number':\n return {\n ...common,\n contentKey: scalarWrapperKey(schema),\n kind: 'number',\n integer: node.integer,\n // A number control clamps; it does not express open intervals. So an\n // exclusive bound becomes the nearest inclusive one where that is\n // exact (integers) and is dropped where it is not (floats) - never\n // the excluded endpoint itself, which the control would clamp onto\n // and the gate would then refuse. ajv enforces the exact keyword off\n // the schema either way, so the bound is a hint, never the rule.\n min:\n node.minimum ??\n inclusiveFrom(\n node.exclusive_minimum,\n node.integer,\n (endpoint) => Math.floor(endpoint) + 1,\n ),\n max:\n node.maximum ??\n inclusiveFrom(\n node.exclusive_maximum,\n node.integer,\n (endpoint) => Math.ceil(endpoint) - 1,\n ),\n };\n case 'boolean':\n return { ...common, contentKey: scalarWrapperKey(schema), kind: 'boolean' };\n case 'enum':\n // The wire carries the authored `choices` verbatim (`unknown[]`); the\n // control set renders and stores strings, as it always has.\n return { ...common, kind: 'enum', options: node.choices.map(String) };\n case 'document':\n case 'image':\n // `accept` is a renderer-side affordance the wire deliberately does not\n // state - which bytes a runtime can decode is a property of the runtime,\n // not of the method. The list is therefore ours, and it is one table\n // (`./file-formats`) rather than a literal here, so the label a user reads\n // and the filter the dropzone enforces cannot disagree. They used to: this\n // line advertised `TXT`, which no DocumentFormat covers, and omitted PPTX,\n // which is one.\n return { ...common, kind: node.kind, accept: acceptLabelForKind(node.kind) };\n case 'object': {\n const props = schema?.properties as Record<string, JsonSchema> | undefined;\n return {\n ...common,\n kind: 'object',\n fields: node.fields.map((child: InputFormField) =>\n mapNode(child, child.name, props ? ownProp(props, child.name) : undefined, defs),\n ),\n };\n }\n case 'list': {\n // The item keeps the parent's name (unused for labels - the index labels\n // items), exactly as the wire's `item` carries no `name` of its own.\n const item = mapNode(node.item, name, schema?.items as JsonSchema | undefined, defs);\n const itemCount = node.item_count ?? numOrUndef(schema?.minItems);\n const maxItemCount = numOrUndef(schema?.maxItems) ?? node.item_count;\n return {\n ...common,\n kind: 'list',\n item,\n ...(itemCount === undefined ? {} : { itemCount }),\n ...(maxItemCount === undefined ? {} : { maxItemCount }),\n };\n }\n case 'unknown':\n return { ...common, kind: 'unknown' };\n }\n // Version drift: the wire states a kind this build's pinned peer does not\n // define. The switch above is exhaustive over `InputFormItem`, so\n // `satisfies never` keeps the build LOUD when the PEER grows a kind - and\n // this return keeps the mapper TOTAL when a SERVER is ahead of the peer,\n // which no type can rule out. The standard's own escape hatch is the honest\n // answer (`unknown` exists so a derivation can be total truthfully): the\n // field keeps its name and falls back to raw entry against the contract's\n // `json_schema`. Returning nothing produced a field with no `name` at all -\n // unaddressable by the value bridge and unnameable by readiness.\n node satisfies never;\n return { ...common, kind: 'unknown' };\n}\n\n/**\n * Map a pipe's wire input-form descriptor onto the kernel's field descriptors,\n * with the pipe's input contracts beside it for the two schema-derived facts.\n *\n * The order is the DESCRIPTOR's - authored input order, the fact the contract's\n * `inputs` map deliberately does not carry. `required`, `presence` and `gating`\n * are taken from the wire verbatim: the standard's top-level type ties\n * `required` to the presence marker, and `gating` is the producer-derived\n * answer `mustBeFilled` reads - the kernel re-derives none of them.\n */\n/**\n * The same mapping, for a single node that belongs to no slot — a pipe's OUTPUT.\n *\n * `buildRunFields` maps a descriptor's fields and then stamps each with the slot\n * facts (`presence`, `gating`) the wire states per input. An output has no slot,\n * so this stamps nothing: the node arrives without them and leaves without them,\n * which is exactly what the standard's optional members are for.\n *\n * Everything else is shared, deliberately. An output is a concept ref like an\n * input is, so its kinds, its nesting, its list bounds and its `contentKey` are\n * the same questions with the same answers — and a second mapper would be a\n * second place for them to drift.\n *\n * ## `schema` is REQUIRED, and that is the whole point\n *\n * It was optional once, and the renderer paid for it: with no schema it could\n * not know that `native.Text`'s payload sits under `text`, so it worked the\n * unwrapping out by COUNTING the value's properties, and worked a plural payload\n * out by looking for an `items` key. Both are shape sniffing — the exact pattern\n * [../../docs/derivation-swap.md] records deleting from the input side, where\n * `contentKey` is read off a schema and handed to a control as a property NAME.\n *\n * So the parameter is required, the two heuristics are gone, and what the\n * argument must be is stated precisely: **the schema of the PAYLOAD**, which for\n * every kind but `object` is the content model that wraps it —\n * `TextContent {text}` for a `native.Text` output, `ListContent {items}` for a\n * plural one. That is a change the standard has to make on the output contract\n * (see `./output-form`); until it does, a producer supplies it beside the\n * descriptor.\n */\nexport function buildResultField(\n descriptor: { field: InputFormField },\n schema: Record<string, unknown>,\n): RunField {\n const node = descriptor.field;\n const defs: Record<string, JsonSchema> = {};\n collectSchemaDefs(schema as JsonSchema, defs, { traverseArrays: true });\n\n // Unwrap the content model, ONCE, at the top.\n //\n // A result's payload is its concept's content model, and for every kind but\n // `object` that model is a wrapper: the value sits under a single property the\n // schema names. Reading it here rather than in `mapNode` is what keeps the\n // schema walk ALIGNED with the descriptor beneath it — a plural output's node\n // is a `list`, so the schema it must be walked against is the `items` array,\n // not the `ListContent` object around it.\n //\n // Gated on the node's stated KIND, never on the value: an `object` output IS\n // its content model, and a structured concept that happens to declare exactly\n // one field would otherwise be mistaken for a wrapper. The kind comes from the\n // descriptor, so this is a read of what the field is, not a guess at it.\n const wrapperKey = node.kind === 'object' ? undefined : scalarWrapperKey(schema as JsonSchema);\n const inner =\n wrapperKey === undefined\n ? (schema as JsonSchema)\n : ((schema as JsonSchema).properties as Record<string, JsonSchema>)[wrapperKey];\n\n const field = mapNode(node, node.name, inner, defs);\n return wrapperKey === undefined ? field : { ...field, contentKey: wrapperKey };\n}\n\nexport function buildRunFields(\n descriptor: PipeInputFormDescriptor,\n inputs: Record<string, PipeInputContract>,\n): RunField[] {\n return descriptor.fields.map((node) => {\n const input = ownProp(inputs, node.name);\n const defs: Record<string, JsonSchema> = {};\n if (input) collectSchemaDefs(input.json_schema, defs, { traverseArrays: true });\n const field = mapNode(node, node.name, input?.json_schema as JsonSchema | undefined, defs);\n return { ...field, presence: node.presence, gating: node.gating };\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { prepareSchemaForRjsf } from './chunk-LBFZXYCY.js';
2
1
  import { pruneEmptyOptionals, healStringWrappers } from './chunk-GCXV76WU.js';
2
+ import { prepareSchemaForRjsf } from './chunk-LBFZXYCY.js';
3
3
  import { isFilled, mustBeFilled, fieldFilled } from './chunk-PM55AHRO.js';
4
4
  import { validateRunInputsSchema } from './chunk-VTPUDBSJ.js';
5
5
  import { gatingFieldsFromInputs } from './chunk-YEVVR6FE.js';
@@ -95,5 +95,5 @@ function gateRunInputs(contract, data) {
95
95
  }
96
96
 
97
97
  export { apiInputsFromSchemaData, buildRunInputsSchema, gateRunInputs, prepareRunInputs, validateRunInputs };
98
- //# sourceMappingURL=chunk-IM2AHWBR.js.map
99
- //# sourceMappingURL=chunk-IM2AHWBR.js.map
98
+ //# sourceMappingURL=chunk-R7B7ID25.js.map
99
+ //# sourceMappingURL=chunk-R7B7ID25.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/gate.ts"],"names":[],"mappings":";;;;;;;;;AAqDO,SAAS,qBAAqB,MAAA,EAAiD;AACpF,EAAA,MAAM,aAAmB,EAAC;AAC1B,EAAA,MAAM,WAAqB,EAAC;AAE5B,EAAA,KAAA,MAAW,CAAC,OAAA,EAAS,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AACrD,IAAA,MAAM,WAAA,GAAc,EAAE,GAAG,KAAA,CAAM,WAAA,EAAY;AAC3C,IAAA,WAAA,CAAY,KAAA,GAAQ,OAAA;AACpB,IAAA,IAAI,KAAA,CAAM,WAAA,IAAe,KAAA,CAAM,WAAA,KAAgB,OAAA,EA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,CAAQ,YAAA,EAAc,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACpF,MAAA,CAAO,CAAC,KAAA,KAAU,CAAC,WAAA,CAAY,KAAA,EAAO,QAAQ,YAAA,EAAc,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACxE,GAAA,CAAI,CAAC,KAAA,KAAU,MAAM,IAAI,CAAA;AAC5B,EAAA,IAAI,aAAA,CAAc,MAAA,EAAQ,OAAO,EAAE,EAAA,EAAI,OAAO,aAAA,EAAe,MAAA,EAAQ,EAAC,EAAG,YAAA,EAAa;AAEtF,EAAA,OAAO,EAAE,IAAI,IAAA,EAAM,MAAA,EAAQ,wBAAwB,YAAA,EAAc,QAAA,CAAS,MAAM,CAAA,EAAE;AACpF","file":"chunk-IM2AHWBR.js","sourcesContent":["/**\n * The gate every run passes through, whichever surface starts it.\n *\n * A host may offer more than one place to run a method - a schema-driven\n * inputs panel (an RJSF form) and a standalone run page (a bespoke field\n * renderer), say. **Only the rendering of inputs differs.** Everything between\n * \"the user pressed Run\" and \"the payload goes on the wire\" lives here, so\n * those surfaces cannot drift:\n *\n * 1. `buildRunInputsSchema` - the combined JSON Schema, whose `required` list\n * is `inputMustBeFilled` (optional `?` and variable-plural `[]` never\n * block; a fixed-count `[N]` list does).\n * 2. `prepareRunInputs` - heal legacy wrappers, then prune empty optionals.\n * 3. `validateRunInputs` - ajv, plus the missing-input scan that names the\n * VARIABLE at fault.\n * 4. `apiInputsFromSchemaData` - the `{concept, content}` payload, built from\n * the PREPARED data so the pruning reaches the wire too.\n *\n * **`gateRunInputs` is that whole chain as one call**, and it is what a server\n * should use. The four steps stay exported because a host that renders its own\n * panel needs the schema and the verdict separately, but assembling them is not\n * a host's job: the step between validation and the payload is an emptiness\n * check with four look-alike predicates to choose from, only two of which are\n * the ones the Run button reads, and choosing the near-miss pair produces a\n * server that is more permissive than the button in front of it.\n *\n * This module is pure: no React, no toasts, no i18n. Each caller renders the\n * verdict in its own idiom.\n */\nimport { inputMustBeFilled, isOptionalInput, isPluralInput } from './contracts';\nimport { gatingFieldsFromInputs } from './gating-fields';\nimport { fieldFilled, isFilled, mustBeFilled } from './readiness';\nimport { validateRunInputsSchema, type RunInputError } from './gate-validator';\nimport { healStringWrappers, pruneEmptyOptionals } from './wire-format';\nimport { prepareSchemaForRjsf } from './normalize-schema';\nimport { ownProp } from './own-property';\nimport type { PipeIOContract, PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\n\n/**\n * Combine the per-input schemas into one object schema.\n *\n * Each input variable becomes a property, titled with the variable name and\n * described with the concept code. Only the inputs the method actually demands\n * land in `required` - an optional (`?`) or variable-plural (`[]`) input must\n * not block the form (see `inputMustBeFilled`).\n *\n * The per-input schema travels verbatim, which is how a fixed-count (`[N]`)\n * list's declared count reaches ajv: pipelex states it as `minItems`/`maxItems`\n * on the array wrapper, so the count is enforced here without the kernel\n * restating it.\n */\nexport function buildRunInputsSchema(inputs: Record<string, PipeInputContract>): Dict {\n const properties: Dict = {};\n const required: string[] = [];\n\n for (const [varName, input] of Object.entries(inputs)) {\n const inputSchema = { ...input.json_schema } as Dict;\n inputSchema.title = varName;\n if (input.concept_ref && input.concept_ref !== varName) {\n inputSchema.description = input.concept_ref;\n }\n properties[varName] = inputSchema;\n if (inputMustBeFilled(input)) required.push(varName);\n }\n\n return prepareSchemaForRjsf({ type: 'object', properties, required });\n}\n\n/**\n * Last-gate repair, in two passes against the exact schema ajv validates.\n *\n * 1. **HEAL** - persisted `inputData` may still carry the legacy double-wrapped\n * `{ text: { text } }` shape (or a form's state may lag a store fix).\n * 2. **PRUNE** - RJSF fills every unset string with `\"\"` on mount, which an\n * optional CONSTRAINED field rejects (`DateContent.time` is `format: \"time\"`)\n * - blocking a run on a field the user never opened. An absent optional field\n * is what pipelex means by `None` anyway, so dropping it is the semantically\n * correct repair, not a validation dodge.\n */\nexport function prepareRunInputs(data: Dict, schema: Dict): Dict {\n return pruneEmptyOptionals(healStringWrappers(data, schema), schema) as Dict;\n}\n\nexport interface RunInputsVerdict {\n isValid: boolean;\n /** Variable names the scan could pin a missing required field on. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n}\n\n/**\n * Validate PREPARED data against the combined schema.\n *\n * `missingInputs` is reported by VARIABLE NAME - the name on the node the user\n * clicks - never by `concept_ref`, which used to produce \"Missing required\n * fields in: native.Text\" and named neither the input at fault nor, when several\n * inputs share a concept, which of them. Inputs the method declared omittable\n * are skipped: an empty `?` input is not a missing one.\n *\n * The scan can come up empty even on an invalid form (a wrong value shape, a\n * nested mismatch); `errors` is what the caller falls back to then, so a failure\n * is never undiagnosable.\n *\n * `preparedData` is `unknown` for the same reason `gateRunInputs`' `data` is: on\n * a public endpoint the body is whatever was sent, and ajv must be shown that\n * rather than a repair of it, or `must be object` is a verdict no caller can\n * ever receive. The name-the-variable scan below needs something indexable, so\n * a body that is not a record scans against nothing and names every input the\n * method demands - which is the honest answer for a body that carried none.\n */\nexport function validateRunInputs(\n preparedData: unknown,\n inputs: Record<string, PipeInputContract>,\n schema: Dict,\n): RunInputsVerdict {\n const errors = validateRunInputsSchema(preparedData, schema);\n if (errors.length === 0) return { isValid: true, missingInputs: [], errors: [] };\n\n const record0 =\n typeof preparedData === 'object' && preparedData !== null && !Array.isArray(preparedData)\n ? (preparedData as Dict)\n : undefined;\n const missingInputs: string[] = [];\n for (const [varName, input] of Object.entries(inputs)) {\n if (!inputMustBeFilled(input)) continue;\n const varData = ownProp(record0, varName);\n // A demanded input that is not there at all is missing whatever its concept\n // declares inside. The check has to come BEFORE the required-children one:\n // a struct whose concept demands no child used to fall out of the scan\n // here, so the run was refused by the combined schema's `required` list\n // while the scan named nothing and the caller could only quote ajv.\n if (varData == null) {\n missingInputs.push(varName);\n continue;\n }\n const inputSchema = input.json_schema as Dict;\n const requiredFields = (inputSchema.required as string[]) || [];\n if (requiredFields.length === 0) continue;\n if (typeof varData !== 'object') {\n missingInputs.push(varName);\n continue;\n }\n const record = varData as Dict;\n if (\n requiredFields.some((f) => {\n const child = ownProp(record, f);\n return child === undefined || child === '';\n })\n ) {\n missingInputs.push(varName);\n }\n }\n\n return { isValid: false, missingInputs, errors };\n}\n\n/**\n * Build the `{ concept, content }` map a run expects, from PREPARED data.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n *\n * A fixed-count (`[N]`) list takes that same empty-list path, and an empty one\n * is not a payload the method can accept. It is unreachable through the gate,\n * which demands the input and rejects a short list on `minItems`; building the\n * payload straight from unvalidated data is what would reach it, and inventing\n * a different absence here would only hide that.\n */\nexport function apiInputsFromSchemaData(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n): Dict {\n const out: Dict = {};\n for (const [varName, input] of Object.entries(inputs)) {\n const raw = ownProp(preparedData, varName);\n if (isOptionalInput(input) && !isFilled(raw)) continue;\n if (isPluralInput(input) && !isFilled(raw)) {\n out[varName] = [];\n continue;\n }\n const content = isPluralInput(input) && !Array.isArray(raw) ? [] : raw;\n out[varName] = { concept: input.concept_ref, content };\n }\n return out;\n}\n\n// ─── The whole chain, as one call ────────────────────────────────────────────\n\n/** The gate's verdict: the payload to send, or why the run may not start. */\nexport type RunInputsGateResult =\n | { ok: true; inputs: Dict }\n | {\n ok: false;\n /** Variable names the caller left empty or short. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n /** The repaired data the verdict was reached on - what\n * `describeValidationError` needs to quote the value it received. */\n preparedData: Dict;\n };\n\n/**\n * One schema object per contract, for the lifetime of the process.\n *\n * `buildRunInputsSchema` is a pure function of the contract, so rebuilding it is\n * *semantically* free - but validation runs through a module-level ajv whose\n * compiled-schema cache is keyed on **schema object identity** and is never\n * evicted. A fresh object per call therefore misses every time and retains\n * another compiled validator. On a publicly callable server endpoint that is\n * unbounded growth driven by the cheapest request there is: an empty body,\n * rejected in a fraction of a millisecond, costing nothing to send.\n *\n * Weakly keyed so the map never pins a contract that goes out of scope. The\n * schema a run has been gated against is pinned for the process lifetime anyway\n * by ajv's own cache; the point is that the NUMBER of them is bounded by the\n * number of distinct contracts rather than by traffic.\n */\nconst SCHEMA_CACHE = new WeakMap<PipeIOContract, Dict>();\n\nfunction schemaForContract(contract: PipeIOContract): Dict {\n const cached = SCHEMA_CACHE.get(contract);\n if (cached) return cached;\n const schema = buildRunInputsSchema(contract.inputs);\n SCHEMA_CACHE.set(contract, schema);\n return schema;\n}\n\n/**\n * Gate a run: repair the caller's data, validate it against the contract,\n * refuse anything the Run button would have refused, and build the payload.\n *\n * Returns a verdict rather than throwing. A server endpoint must not throw\n * across the boundary to its client - frameworks routinely strip the message to\n * an opaque digest in a production build - and a rejection here is an ordinary\n * outcome, not an exceptional one.\n *\n * **`data` is `unknown` because that is what it is.** A run endpoint is public\n * and no framework enforces a declared parameter type, so the argument is\n * whatever the caller put in the body. The chain indexes the payload by\n * variable name without first checking it is indexable, so a `null` body would\n * throw *after* ajv had already reported `must be object` and before any\n * verdict came back.\n *\n * So the two uses are separated rather than collapsed into one repair. **ajv\n * judges the value the caller actually sent**, which is what makes `must be\n * object` the verdict for a body that is not one; the indexing that follows\n * uses a safe `{}` stand-in, which is what keeps the gate from throwing. Repair\n * FIRST - coercing a non-object to `{}` before validating - is the shape that\n * looks equivalent and is not: a contract whose inputs are all optional has an\n * empty `required` list, so `{}` validates, and `gateRunInputs(\"garbage\", …)`\n * came back `ok: true` on a body the caller never meant as a run. Fail-closed\n * costs a malformed caller an error it earned; the other direction bills a run.\n *\n * **The schema alone is not the rule.** ajv's `required` asserts only that a\n * key is PRESENT, and a content model carries no `minLength` - so a required\n * input that arrived empty (`{document: {url: \"\"}}`, `{text: {text: \"\"}}`)\n * satisfies the schema. That is the natural payload, not a contrived one:\n * `rjsfDataFromRunValues({}, fields)` emits exactly that when nothing is\n * selected. So the gate re-applies the emptiness rule using\n * `computeReadiness`'s OWN two functions over the same derived fields, which is\n * the only way to be sure the two sides cannot disagree.\n *\n * Picking a pair that merely looks equivalent is not enough, and this is the\n * whole reason the assembly lives here rather than in each host: the obvious\n * choice, `inputMustBeFilled` + `isFilled`, agrees on every leaf kind and\n * diverges on a structured concept in BOTH directions - `isFilled` on an object\n * is `some(child filled)` where `fieldFilled` is `every(required child\n * filled)`. That accepts a half-filled struct the browser refuses (a paid run\n * past a disabled button) and rejects a filled all-optional struct the browser\n * accepts. A host whose methods happen to use only native concepts has no test\n * that can catch either.\n */\nexport function gateRunInputs(contract: PipeIOContract, data: unknown): RunInputsGateResult {\n const isRecord = typeof data === 'object' && data !== null && !Array.isArray(data);\n const payload = isRecord ? (data as Dict) : {};\n const schema = schemaForContract(contract);\n const preparedData = prepareRunInputs(payload, schema);\n\n // The value ajv is shown is the caller's, not the stand-in - see above.\n const verdict = validateRunInputs(isRecord ? preparedData : data, contract.inputs, schema);\n if (!verdict.isValid) {\n return {\n ok: false,\n missingInputs: verdict.missingInputs,\n errors: verdict.errors,\n preparedData,\n };\n }\n\n // The SELECTION is half the rule, and leaving it out is what made the two\n // halves disagree. `computeReadiness` reckons with an input the method\n // demands AND one it left optional that the user has touched - because a\n // structure with something in it owes its concept every field the concept\n // declares. Filtering on `mustBeFilled` alone dropped the second kind, so a\n // half-filled optional struct was refused by the button and accepted here.\n //\n // ajv cannot cover for it: a required child that is a plain string arrives as\n // `''`, which satisfies `required`. And the payload builder below then SENDS\n // that input, because `isFilled` is exactly what it tests. Which is the rule\n // stated properly: the gate holds to its concept precisely the inputs it is\n // about to put on the wire, and nothing it will omit.\n //\n // The tree the predicates run over is the gate's own, walked structurally\n // from the same `json_schema` ajv just validated - NOT the render tree, which\n // is built from the input-form descriptor. A server validating a payload must\n // never need that presentation artifact; see `gating-fields.ts`.\n const missingInputs = gatingFieldsFromInputs(contract.inputs)\n .filter((field) => mustBeFilled(field) || isFilled(ownProp(preparedData, field.name)))\n .filter((field) => !fieldFilled(field, ownProp(preparedData, field.name)))\n .map((field) => field.name);\n if (missingInputs.length) return { ok: false, missingInputs, errors: [], preparedData };\n\n return { ok: true, inputs: apiInputsFromSchemaData(preparedData, contract.inputs) };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/gate.ts"],"names":[],"mappings":";;;;;;;;;AAqDO,SAAS,qBAAqB,MAAA,EAAiD;AACpF,EAAA,MAAM,aAAmB,EAAC;AAC1B,EAAA,MAAM,WAAqB,EAAC;AAE5B,EAAA,KAAA,MAAW,CAAC,OAAA,EAAS,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,MAAM,CAAA,EAAG;AACrD,IAAA,MAAM,WAAA,GAAc,EAAE,GAAG,KAAA,CAAM,WAAA,EAAY;AAC3C,IAAA,WAAA,CAAY,KAAA,GAAQ,OAAA;AACpB,IAAA,IAAI,KAAA,CAAM,WAAA,IAAe,KAAA,CAAM,WAAA,KAAgB,OAAA,EAAS;AACtD,MAAA,WAAA,CAAY,cAAc,KAAA,CAAM,WAAA;AAAA,IAClC;AACA,IAAA,UAAA,CAAW,OAAO,CAAA,GAAI,WAAA;AACtB,IAAA,IAAI,iBAAA,CAAkB,KAAK,CAAA,EAAG,QAAA,CAAS,KAAK,OAAO,CAAA;AAAA,EACrD;AAEA,EAAA,OAAO,qBAAqB,EAAE,IAAA,EAAM,QAAA,EAAU,UAAA,EAAY,UAAU,CAAA;AACtE;AAaO,SAAS,gBAAA,CAAiB,MAAY,MAAA,EAAoB;AAC/D,EAAA,O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EAAa;AAEtF,EAAA,OAAO,EAAE,IAAI,IAAA,EAAM,MAAA,EAAQ,wBAAwB,YAAA,EAAc,QAAA,CAAS,MAAM,CAAA,EAAE;AACpF","file":"chunk-R7B7ID25.js","sourcesContent":["/**\n * The gate every run passes through, whichever surface starts it.\n *\n * A host may offer more than one place to run a method - a schema-driven\n * inputs panel (an RJSF form) and a standalone run page (a bespoke field\n * renderer), say. **Only the rendering of inputs differs.** Everything between\n * \"the user pressed Run\" and \"the payload goes on the wire\" lives here, so\n * those surfaces cannot drift:\n *\n * 1. `buildRunInputsSchema` - the combined JSON Schema, whose `required` list\n * is `inputMustBeFilled` (optional `?` and variable-plural `[]` never\n * block; a fixed-count `[N]` list does).\n * 2. `prepareRunInputs` - heal legacy wrappers, then prune empty optionals.\n * 3. `validateRunInputs` - ajv, plus the missing-input scan that names the\n * VARIABLE at fault.\n * 4. `apiInputsFromSchemaData` - the `{concept, content}` payload, built from\n * the PREPARED data so the pruning reaches the wire too.\n *\n * **`gateRunInputs` is that whole chain as one call**, and it is what a server\n * should use. The four steps stay exported because a host that renders its own\n * panel needs the schema and the verdict separately, but assembling them is not\n * a host's job: the step between validation and the payload is an emptiness\n * check with four look-alike predicates to choose from, only two of which are\n * the ones the Run button reads, and choosing the near-miss pair produces a\n * server that is more permissive than the button in front of it.\n *\n * This module is pure: no React, no toasts, no i18n. Each caller renders the\n * verdict in its own idiom.\n */\nimport { inputMustBeFilled, isOptionalInput, isPluralInput } from './contracts';\nimport { gatingFieldsFromInputs } from './gating-fields';\nimport { fieldFilled, isFilled, mustBeFilled } from './readiness';\nimport { validateRunInputsSchema, type RunInputError } from './gate-validator';\nimport { healStringWrappers, pruneEmptyOptionals } from './wire-format';\nimport { prepareSchemaForRjsf } from './normalize-schema';\nimport { ownProp } from './own-property';\nimport type { PipeIOContract, PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\n\n/**\n * Combine the per-input schemas into one object schema.\n *\n * Each input variable becomes a property, titled with the variable name and\n * described with the concept code. Only the inputs the method actually demands\n * land in `required` - an optional (`?`) or variable-plural (`[]`) input must\n * not block the form (see `inputMustBeFilled`).\n *\n * The per-input schema travels verbatim, which is how a fixed-count (`[N]`)\n * list's declared count reaches ajv: pipelex states it as `minItems`/`maxItems`\n * on the array wrapper, so the count is enforced here without the kernel\n * restating it.\n */\nexport function buildRunInputsSchema(inputs: Record<string, PipeInputContract>): Dict {\n const properties: Dict = {};\n const required: string[] = [];\n\n for (const [varName, input] of Object.entries(inputs)) {\n const inputSchema = { ...input.json_schema } as Dict;\n inputSchema.title = varName;\n if (input.concept_ref && input.concept_ref !== varName) {\n inputSchema.description = input.concept_ref;\n }\n properties[varName] = inputSchema;\n if (inputMustBeFilled(input)) required.push(varName);\n }\n\n return prepareSchemaForRjsf({ type: 'object', properties, required });\n}\n\n/**\n * Last-gate repair, in two passes against the exact schema ajv validates.\n *\n * 1. **HEAL** - persisted `inputData` may still carry the legacy double-wrapped\n * `{ text: { text } }` shape (or a form's state may lag a store fix).\n * 2. **PRUNE** - RJSF fills every unset string with `\"\"` on mount, which an\n * optional CONSTRAINED field rejects (`DateContent.time` is `format: \"time\"`)\n * - blocking a run on a field the user never opened. An absent optional field\n * is what pipelex means by `None` anyway, so dropping it is the semantically\n * correct repair, not a validation dodge.\n */\nexport function prepareRunInputs(data: Dict, schema: Dict): Dict {\n return pruneEmptyOptionals(healStringWrappers(data, schema), schema) as Dict;\n}\n\nexport interface RunInputsVerdict {\n isValid: boolean;\n /** Variable names the scan could pin a missing required field on. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n}\n\n/**\n * Validate PREPARED data against the combined schema.\n *\n * `missingInputs` is reported by VARIABLE NAME - the name on the node the user\n * clicks - never by `concept_ref`, which used to produce \"Missing required\n * fields in: native.Text\" and named neither the input at fault nor, when several\n * inputs share a concept, which of them. Inputs the method declared omittable\n * are skipped: an empty `?` input is not a missing one.\n *\n * The scan can come up empty even on an invalid form (a wrong value shape, a\n * nested mismatch); `errors` is what the caller falls back to then, so a failure\n * is never undiagnosable.\n *\n * `preparedData` is `unknown` for the same reason `gateRunInputs`' `data` is: on\n * a public endpoint the body is whatever was sent, and ajv must be shown that\n * rather than a repair of it, or `must be object` is a verdict no caller can\n * ever receive. The name-the-variable scan below needs something indexable, so\n * a body that is not a record scans against nothing and names every input the\n * method demands - which is the honest answer for a body that carried none.\n */\nexport function validateRunInputs(\n preparedData: unknown,\n inputs: Record<string, PipeInputContract>,\n schema: Dict,\n): RunInputsVerdict {\n const errors = validateRunInputsSchema(preparedData, schema);\n if (errors.length === 0) return { isValid: true, missingInputs: [], errors: [] };\n\n const record0 =\n typeof preparedData === 'object' && preparedData !== null && !Array.isArray(preparedData)\n ? (preparedData as Dict)\n : undefined;\n const missingInputs: string[] = [];\n for (const [varName, input] of Object.entries(inputs)) {\n if (!inputMustBeFilled(input)) continue;\n const varData = ownProp(record0, varName);\n // A demanded input that is not there at all is missing whatever its concept\n // declares inside. The check has to come BEFORE the required-children one:\n // a struct whose concept demands no child used to fall out of the scan\n // here, so the run was refused by the combined schema's `required` list\n // while the scan named nothing and the caller could only quote ajv.\n if (varData == null) {\n missingInputs.push(varName);\n continue;\n }\n const inputSchema = input.json_schema as Dict;\n const requiredFields = (inputSchema.required as string[]) || [];\n if (requiredFields.length === 0) continue;\n if (typeof varData !== 'object') {\n missingInputs.push(varName);\n continue;\n }\n const record = varData as Dict;\n if (\n requiredFields.some((f) => {\n const child = ownProp(record, f);\n return child === undefined || child === '';\n })\n ) {\n missingInputs.push(varName);\n }\n }\n\n return { isValid: false, missingInputs, errors };\n}\n\n/**\n * Build the `{ concept, content }` map a run expects, from PREPARED data.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n *\n * A fixed-count (`[N]`) list takes that same empty-list path, and an empty one\n * is not a payload the method can accept. It is unreachable through the gate,\n * which demands the input and rejects a short list on `minItems`; building the\n * payload straight from unvalidated data is what would reach it, and inventing\n * a different absence here would only hide that.\n */\nexport function apiInputsFromSchemaData(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n): Dict {\n const out: Dict = {};\n for (const [varName, input] of Object.entries(inputs)) {\n const raw = ownProp(preparedData, varName);\n if (isOptionalInput(input) && !isFilled(raw)) continue;\n if (isPluralInput(input) && !isFilled(raw)) {\n out[varName] = [];\n continue;\n }\n const content = isPluralInput(input) && !Array.isArray(raw) ? [] : raw;\n out[varName] = { concept: input.concept_ref, content };\n }\n return out;\n}\n\n// ─── The whole chain, as one call ────────────────────────────────────────────\n\n/** The gate's verdict: the payload to send, or why the run may not start. */\nexport type RunInputsGateResult =\n | { ok: true; inputs: Dict }\n | {\n ok: false;\n /** Variable names the caller left empty or short. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n /** The repaired data the verdict was reached on - what\n * `describeValidationError` needs to quote the value it received. */\n preparedData: Dict;\n };\n\n/**\n * One schema object per contract, for the lifetime of the process.\n *\n * `buildRunInputsSchema` is a pure function of the contract, so rebuilding it is\n * *semantically* free - but validation runs through a module-level ajv whose\n * compiled-schema cache is keyed on **schema object identity** and is never\n * evicted. A fresh object per call therefore misses every time and retains\n * another compiled validator. On a publicly callable server endpoint that is\n * unbounded growth driven by the cheapest request there is: an empty body,\n * rejected in a fraction of a millisecond, costing nothing to send.\n *\n * Weakly keyed so the map never pins a contract that goes out of scope. The\n * schema a run has been gated against is pinned for the process lifetime anyway\n * by ajv's own cache; the point is that the NUMBER of them is bounded by the\n * number of distinct contracts rather than by traffic.\n */\nconst SCHEMA_CACHE = new WeakMap<PipeIOContract, Dict>();\n\nfunction schemaForContract(contract: PipeIOContract): Dict {\n const cached = SCHEMA_CACHE.get(contract);\n if (cached) return cached;\n const schema = buildRunInputsSchema(contract.inputs);\n SCHEMA_CACHE.set(contract, schema);\n return schema;\n}\n\n/**\n * Gate a run: repair the caller's data, validate it against the contract,\n * refuse anything the Run button would have refused, and build the payload.\n *\n * Returns a verdict rather than throwing. A server endpoint must not throw\n * across the boundary to its client - frameworks routinely strip the message to\n * an opaque digest in a production build - and a rejection here is an ordinary\n * outcome, not an exceptional one.\n *\n * **`data` is `unknown` because that is what it is.** A run endpoint is public\n * and no framework enforces a declared parameter type, so the argument is\n * whatever the caller put in the body. The chain indexes the payload by\n * variable name without first checking it is indexable, so a `null` body would\n * throw *after* ajv had already reported `must be object` and before any\n * verdict came back.\n *\n * So the two uses are separated rather than collapsed into one repair. **ajv\n * judges the value the caller actually sent**, which is what makes `must be\n * object` the verdict for a body that is not one; the indexing that follows\n * uses a safe `{}` stand-in, which is what keeps the gate from throwing. Repair\n * FIRST - coercing a non-object to `{}` before validating - is the shape that\n * looks equivalent and is not: a contract whose inputs are all optional has an\n * empty `required` list, so `{}` validates, and `gateRunInputs(\"garbage\", …)`\n * came back `ok: true` on a body the caller never meant as a run. Fail-closed\n * costs a malformed caller an error it earned; the other direction bills a run.\n *\n * **The schema alone is not the rule.** ajv's `required` asserts only that a\n * key is PRESENT, and a content model carries no `minLength` - so a required\n * input that arrived empty (`{document: {url: \"\"}}`, `{text: {text: \"\"}}`)\n * satisfies the schema. That is the natural payload, not a contrived one:\n * `rjsfDataFromRunValues({}, fields)` emits exactly that when nothing is\n * selected. So the gate re-applies the emptiness rule using\n * `computeReadiness`'s OWN two functions over the same derived fields, which is\n * the only way to be sure the two sides cannot disagree.\n *\n * Picking a pair that merely looks equivalent is not enough, and this is the\n * whole reason the assembly lives here rather than in each host: the obvious\n * choice, `inputMustBeFilled` + `isFilled`, agrees on every leaf kind and\n * diverges on a structured concept in BOTH directions - `isFilled` on an object\n * is `some(child filled)` where `fieldFilled` is `every(required child\n * filled)`. That accepts a half-filled struct the browser refuses (a paid run\n * past a disabled button) and rejects a filled all-optional struct the browser\n * accepts. A host whose methods happen to use only native concepts has no test\n * that can catch either.\n */\nexport function gateRunInputs(contract: PipeIOContract, data: unknown): RunInputsGateResult {\n const isRecord = typeof data === 'object' && data !== null && !Array.isArray(data);\n const payload = isRecord ? (data as Dict) : {};\n const schema = schemaForContract(contract);\n const preparedData = prepareRunInputs(payload, schema);\n\n // The value ajv is shown is the caller's, not the stand-in - see above.\n const verdict = validateRunInputs(isRecord ? preparedData : data, contract.inputs, schema);\n if (!verdict.isValid) {\n return {\n ok: false,\n missingInputs: verdict.missingInputs,\n errors: verdict.errors,\n preparedData,\n };\n }\n\n // The SELECTION is half the rule, and leaving it out is what made the two\n // halves disagree. `computeReadiness` reckons with an input the method\n // demands AND one it left optional that the user has touched - because a\n // structure with something in it owes its concept every field the concept\n // declares. Filtering on `mustBeFilled` alone dropped the second kind, so a\n // half-filled optional struct was refused by the button and accepted here.\n //\n // ajv cannot cover for it: a required child that is a plain string arrives as\n // `''`, which satisfies `required`. And the payload builder below then SENDS\n // that input, because `isFilled` is exactly what it tests. Which is the rule\n // stated properly: the gate holds to its concept precisely the inputs it is\n // about to put on the wire, and nothing it will omit.\n //\n // The tree the predicates run over is the gate's own, walked structurally\n // from the same `json_schema` ajv just validated - NOT the render tree, which\n // is built from the input-form descriptor. A server validating a payload must\n // never need that presentation artifact; see `gating-fields.ts`.\n const missingInputs = gatingFieldsFromInputs(contract.inputs)\n .filter((field) => mustBeFilled(field) || isFilled(ownProp(preparedData, field.name)))\n .filter((field) => !fieldFilled(field, ownProp(preparedData, field.name)))\n .map((field) => field.name);\n if (missingInputs.length) return { ok: false, missingInputs, errors: [], preparedData };\n\n return { ok: true, inputs: apiInputsFromSchemaData(preparedData, contract.inputs) };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { buildRunFields } from './chunk-IIJRJGZQ.js';
1
+ import { buildRunFields } from './chunk-J4L32LD6.js';
2
2
  import { inflateAllInputs, deflateAllInputs } from './chunk-GCXV76WU.js';
3
3
  import { isFilled } from './chunk-PM55AHRO.js';
4
4
  import { isOptionalInput, isPluralInput } from './chunk-XYQ7NXQZ.js';
@@ -197,5 +197,5 @@ function setValueAtPath(root, path, value) {
197
197
  }
198
198
 
199
199
  export { apiInputsFromRunValues, fieldsForContract, inputDataFromWorkingMemory, outputsFromPipeOutput, rjsfDataFromRunValues, runValuesFromStore, setValueAtPath, storeInputDataFromRunValues };
200
- //# sourceMappingURL=chunk-5Q2W6HBA.js.map
201
- //# sourceMappingURL=chunk-5Q2W6HBA.js.map
200
+ //# sourceMappingURL=chunk-T4NSAGOS.js.map
201
+ //# sourceMappingURL=chunk-T4NSAGOS.js.map