Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(mcp): expose methodMaterial storageUnitIds as an object map (#1623)

Brad Barbin9e8d2ffa4b13
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 37c7e9bda7..3538c2a5c9 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -445,13 +445,27 @@ export const methodMaterialValidator = z.object({
unitOfMeasureCode: z
.string()
.min(1, { message: "Unit of Measure is required" }),
- storageUnitIds: z.string().transform((val) => {
- try {
- return JSON.parse(val) as Record<string, string>;
- } catch {
- return {};
- }
- })
+ // A location → storageUnitId map. The BoM web form submits it as a JSON string
+ // (`<Hidden value={JSON.stringify(...)} />`); the MCP/API layer sends the object
+ // map directly. `preprocess` accepts both — a string is JSON-parsed (a malformed
+ // string stays a string and is REJECTED by the record below, never silently
+ // stored) — and the input JSON Schema published to MCP is a clean object map.
+ // `nullish` lets a caller omit it or send `null` to clear (the service applies
+ // the create/update semantics: omitted → preserve on update / {} on create,
+ // explicit null/{} → clear).
+ storageUnitIds: z
+ .preprocess(
+ (val) => {
+ if (typeof val !== "string") return val;
+ try {
+ return JSON.parse(val);
+ } catch {
+ return val;
+ }
+ },
+ z.record(z.string(), z.string())
+ )
+ .nullish()
});
export const methodOperationValidator = z
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 6c8160eee0..cbee52079a 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -4009,6 +4009,42 @@ export async function upsertMakeMethodVersion(
* where an item can be stocked across multiple locations, each with its
* own preferred bin.
*/
+/**
+ * Coerce whatever a caller supplied for `storageUnitIds` into the
+ * location → storageUnitId map the column stores. The web form pre-parses its
+ * JSON string through `methodMaterialValidator`, but the MCP/API dispatch path
+ * bypasses that validator and hands the service the raw value, so normalize
+ * defensively here too: an object map is kept (string values only), a JSON
+ * string is parsed, and null/undefined/anything-else collapses to `{}`. A bare
+ * string used to be spread character-by-character into the JSONB column
+ * (`"false"` → `{"0":"f","1":"a",…}`) — this is where that is stopped.
+ */
+function normalizeStorageUnitIds(value: unknown): Record<string, string> {
+ const fromObject = (obj: Record<string, unknown>): Record<string, string> => {
+ const out: Record<string, string> = {};
+ for (const [key, v] of Object.entries(obj)) {
+ if (typeof v === "string") out[key] = v;
+ }
+ return out;
+ };
+
+ if (value == null) return {};
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? fromObject(parsed as Record<string, unknown>)
+ : {};
+ } catch {
+ return {};
+ }
+ }
+ if (typeof value === "object" && !Array.isArray(value)) {
+ return fromObject(value as Record<string, unknown>);
+ }
+ return {};
+}
+
async function resolveMethodMaterialStorageUnitIds(
client: SupabaseClient<Database>,
args: {
@@ -4082,16 +4118,14 @@ export async function upsertMethodMaterial(
}
if ("createdBy" in methodMaterial) {
- // Seed storageUnitIds from the child item's default location/storage-unit
- // if the caller didn't already provide one for that location. Respects
- // the form value when supplied, adds a sensible default otherwise.
+ // On create, an omitted / null storageUnitIds normalizes to `{}`, then the
+ // child item's default location/storage-unit picks seed any locations the
+ // caller didn't specify. Respects supplied values; adds sensible defaults.
const seededStorageUnitIds = await resolveMethodMaterialStorageUnitIds(
client,
{
itemId: methodMaterial.itemId,
- current: methodMaterial.storageUnitIds as
- | Record<string, string>
- | undefined
+ current: normalizeStorageUnitIds(methodMaterial.storageUnitIds)
}
);
return client
@@ -4107,9 +4141,28 @@ export async function upsertMethodMaterial(
.select("id")
.single();
}
+ // On update, an OMITTED storageUnitIds preserves the stored value (drop the key
+ // so `sanitize` can't null it), while an explicit null / {} / map is written —
+ // null and {} both clear it. The web form always submits the field, so its
+ // behavior is unchanged; only the MCP/API caller can omit it.
+ if (methodMaterial.storageUnitIds === undefined) {
+ const { storageUnitIds: _omitted, ...preserved } = methodMaterial;
+ return client
+ .from("methodMaterial")
+ .update(sanitize({ ...preserved, materialMakeMethodId }))
+ .eq("id", methodMaterial.id)
+ .select("id")
+ .single();
+ }
return client
.from("methodMaterial")
- .update(sanitize({ ...methodMaterial, materialMakeMethodId }))
+ .update(
+ sanitize({
+ ...methodMaterial,
+ materialMakeMethodId,
+ storageUnitIds: normalizeStorageUnitIds(methodMaterial.storageUnitIds)
+ })
+ )
.eq("id", methodMaterial.id)
.select("id")
.single();
diff --git a/apps/erp/app/modules/items/method-material-storage-units.test.ts b/apps/erp/app/modules/items/method-material-storage-units.test.ts
new file mode 100644
index 0000000000..e628be1808
--- /dev/null
+++ b/apps/erp/app/modules/items/method-material-storage-units.test.ts
@@ -0,0 +1,161 @@
+import { describe, expect, it, vi } from "vitest";
+
+// Importing the real items.service graph transitively loads @carbon/glossary,
+// whose module-load-time Lingui `msg` macro isn't transformed under plain vitest
+// and throws. The code under test needs none of it, so stub glossary; the service
+// under test stays the genuine implementation. (Mirrors items.service.test.ts.)
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn()
+}));
+
+const { upsertMethodMaterial } = await import("./items.service");
+const { methodMaterialValidator } = await import("./items.models");
+
+// A valid methodMaterial payload minus storageUnitIds. No itemId + a non-Make
+// methodType keeps upsertMethodMaterial down to a single write call, so the mock
+// client below only has to answer the insert/update.
+const base = {
+ id: "mm1",
+ makeMethodId: "mk1",
+ order: 1,
+ itemType: "Part" as const,
+ methodType: "Pull from Inventory" as const,
+ sourcingType: "Specified" as const,
+ quantity: 2,
+ unitOfMeasureCode: "EA"
+};
+
+/**
+ * Minimal chainable Supabase stub that records the row handed to insert()/update()
+ * so a test can assert what upsertMethodMaterial persisted for `storageUnitIds`.
+ */
+function mockClient() {
+ const captured: { insert?: any; update?: any } = {};
+ const builder: any = {
+ insert: (rows: any[]) => {
+ captured.insert = rows[0];
+ return builder;
+ },
+ update: (payload: any) => {
+ captured.update = payload;
+ return builder;
+ },
+ select: () => builder,
+ eq: () => builder,
+ single: async () => ({ data: { id: "mm1" }, error: null })
+ };
+ const client: any = { from: () => builder };
+ return { client, captured };
+}
+
+describe("methodMaterialValidator.storageUnitIds", () => {
+ const parse = (storageUnitIds: unknown) =>
+ methodMaterialValidator.safeParse({ ...base, storageUnitIds });
+
+ it("parses the web form's JSON-string map to an object", () => {
+ const r = parse('{"loc1":"su1"}');
+ expect(r.success && r.data.storageUnitIds).toEqual({ loc1: "su1" });
+ });
+
+ it("accepts a JSON-string {} and an already-parsed object map", () => {
+ expect(parse("{}").success && parse("{}").data?.storageUnitIds).toEqual({});
+ const r = parse({ loc1: "su1" });
+ expect(r.success && r.data.storageUnitIds).toEqual({ loc1: "su1" });
+ });
+
+ it("accepts null and an omitted field", () => {
+ expect(parse(null).success && parse(null).data?.storageUnitIds).toBeNull();
+ const omitted = methodMaterialValidator.safeParse({ ...base });
+ expect(omitted.success && omitted.data.storageUnitIds).toBeUndefined();
+ });
+
+ it("rejects malformed strings and non-object JSON", () => {
+ for (const bad of ["not json", "false", "123", '["a"]']) {
+ expect(parse(bad).success).toBe(false);
+ }
+ });
+});
+
+describe("upsertMethodMaterial storageUnitIds normalization", () => {
+ it("create: an omitted storageUnitIds is stored as {}", async () => {
+ const { client, captured } = mockClient();
+ await upsertMethodMaterial(client, {
+ ...base,
+ companyId: "c1",
+ createdBy: "u1"
+ } as any);
+ expect(captured.insert.storageUnitIds).toEqual({});
+ });
+
+ it("create: null and a populated map are stored verbatim", async () => {
+ const withNull = mockClient();
+ await upsertMethodMaterial(withNull.client, {
+ ...base,
+ storageUnitIds: null,
+ companyId: "c1",
+ createdBy: "u1"
+ } as any);
+ expect(withNull.captured.insert.storageUnitIds).toEqual({});
+
+ const withMap = mockClient();
+ await upsertMethodMaterial(withMap.client, {
+ ...base,
+ storageUnitIds: { loc1: "su1" },
+ companyId: "c1",
+ createdBy: "u1"
+ } as any);
+ expect(withMap.captured.insert.storageUnitIds).toEqual({ loc1: "su1" });
+ });
+
+ it("update: an omitted storageUnitIds is NOT written (preserves stored value)", async () => {
+ const { client, captured } = mockClient();
+ await upsertMethodMaterial(client, {
+ ...base,
+ updatedBy: "u1"
+ } as any);
+ expect(captured.update).toBeDefined();
+ expect("storageUnitIds" in captured.update).toBe(false);
+ });
+
+ it("update: explicit null or {} clears it, a map replaces it", async () => {
+ const cleared = mockClient();
+ await upsertMethodMaterial(cleared.client, {
+ ...base,
+ storageUnitIds: null,
+ updatedBy: "u1"
+ } as any);
+ expect(cleared.captured.update.storageUnitIds).toEqual({});
+
+ const emptied = mockClient();
+ await upsertMethodMaterial(emptied.client, {
+ ...base,
+ storageUnitIds: {},
+ updatedBy: "u1"
+ } as any);
+ expect(emptied.captured.update.storageUnitIds).toEqual({});
+
+ const replaced = mockClient();
+ await upsertMethodMaterial(replaced.client, {
+ ...base,
+ storageUnitIds: { loc1: "su1" },
+ updatedBy: "u1"
+ } as any);
+ expect(replaced.captured.update.storageUnitIds).toEqual({ loc1: "su1" });
+ });
+
+ it("never spreads a bare string into a character map", async () => {
+ // The original bug: MCP sent "false", the service spread it into
+ // {"0":"f","1":"a",…}. A stray string now normalizes to {}.
+ const { client, captured } = mockClient();
+ await upsertMethodMaterial(client, {
+ ...base,
+ storageUnitIds: "false",
+ updatedBy: "u1"
+ } as any);
+ expect(captured.update.storageUnitIds).toEqual({});
+ });
+});
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index fb3ac94bca..593c946a69 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -545,7 +545,7 @@
{"name":"items_upsertMaterialGrade","classification":"WRITE","paramCount":3,"schema":"d23a9b1a2253","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMaterialSubstance","classification":"WRITE","paramCount":4,"schema":"50ac0c460dd0","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMaterialType","classification":"WRITE","paramCount":5,"schema":"c033d56db90c","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
- {"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"dfab6801328b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
+ {"name":"items_upsertMethodMaterial","classification":"WRITE","paramCount":13,"schema":"d52e20f3488d","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodOperation","classification":"WRITE","paramCount":22,"schema":"1bab96040db4","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodOperationParameter","classification":"WRITE","paramCount":5,"schema":"7886eea4515f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
{"name":"items_upsertMethodOperationStep","classification":"WRITE","paramCount":11,"schema":"b00e13983658","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false},
@@ -1060,16 +1060,16 @@
{"name":"quality_updateQualityDocumentStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},
{"name":"quality_updateRiskStatus","classification":"WRITE","paramCount":2,"schema":"27ac2e505123","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"quality:update","paginates":false},
{"name":"quality_upsertGauge","classification":"WRITE","paramCount":16,"schema":"6969c2f67b33","response":"3ec91e2c9200","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
- {"name":"quality_upsertGaugeCalibrationRecord","classification":"WRITE","paramCount":15,"schema":"e6ad1b1bbe93","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
+ {"name":"quality_upsertGaugeCalibrationRecord","classification":"WRITE","paramCount":15,"schema":"80febac2c711","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertGaugeType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertIssue","classification":"WRITE","paramCount":21,"schema":"5a6a8f4280d9","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertIssueType","classification":"WRITE","paramCount":3,"schema":"f47f137a8607","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
- {"name":"quality_upsertIssueWorkflow","classification":"WRITE","paramCount":7,"schema":"1b3f273e498f","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
+ {"name":"quality_upsertIssueWorkflow","classification":"WRITE","paramCount":7,"schema":"ed37ccdc2f7a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertItemInspectionDocumentAssignment","classification":"DESTRUCTIVE","paramCount":3,"schema":"3e4ebfc49e2a","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertQualityDocument","classification":"WRITE","paramCount":5,"schema":"6ddca1e4a601","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertQualityDocumentStep","classification":"WRITE","paramCount":10,"schema":"cd38e003477a","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"quality_upsertRequiredAction","classification":"WRITE","paramCount":3,"schema":"33e654329126","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
- {"name":"quality_upsertRisk","classification":"WRITE","paramCount":12,"schema":"94273afe4449","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
+ {"name":"quality_upsertRisk","classification":"WRITE","paramCount":12,"schema":"6cdac0001c75","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"quality:create+update","paginates":false},
{"name":"resources_activateProcess","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},
{"name":"resources_activateWorkCenter","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},
{"name":"resources_deleteAbility","classification":"DESTRUCTIVE","paramCount":2,"schema":"f642be0f483d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:delete","paginates":false},
diff --git a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
index 601d7c6eb4..9bfe33faff 100644
--- a/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
+++ b/apps/erp/app/routes/api+/v1+/lib/dispatch-parity.test.ts
@@ -14,6 +14,7 @@ const spies = vi.hoisted(() => ({
getTrialBalance: vi.fn(),
upsertAccount: vi.fn(),
upsertJobMaterial: vi.fn(),
+ upsertMethodMaterial: vi.fn(),
upsertQuoteLinePrices: vi.fn(),
generateInventoryCountLines: vi.fn(),
upsertNotificationPreference: vi.fn(),
@@ -46,7 +47,9 @@ vi.mock("~/modules/invoicing/invoicing.service", () => ({
replaceInvoiceSettlements: spies.replaceInvoiceSettlements,
applyCreditsToInvoices: spies.applyCreditsToInvoices
}));
-vi.mock("~/modules/items/items.service", () => ({}));
+vi.mock("~/modules/items/items.service", () => ({
+ upsertMethodMaterial: spies.upsertMethodMaterial
+}));
vi.mock("~/modules/people/people.service", () => ({}));
vi.mock("~/modules/production/production.mcp.server", () => ({}));
vi.mock("~/modules/production/production.service", () => ({
@@ -132,6 +135,7 @@ const allSpies = [
spies.getTrialBalance,
spies.upsertAccount,
spies.upsertJobMaterial,
+ spies.upsertMethodMaterial,
spies.upsertQuoteLinePrices,
spies.generateInventoryCountLines,
spies.upsertNotificationPreference,
@@ -151,6 +155,68 @@ beforeEach(() => {
});
describe("dispatchOperation service-call contract (golden, ex-executeFunction parity)", () => {
+ // items_upsertMethodMaterial exposes storageUnitIds as a proper object map. The
+ // MCP path (unlike the web form) does NOT run the zod transform, so the object
+ // must reach the service verbatim — the old required-string-enum schema made a
+ // caller send "false", which the service spread into {"0":"f",…}.
+ const methodMaterialFields = {
+ id: "mm1",
+ makeMethodId: "mk1",
+ order: 1,
+ itemType: "Part",
+ methodType: "Pull from Inventory",
+ sourcingType: "Specified",
+ quantity: 2,
+ unitOfMeasureCode: "EA"
+ };
+
+ it("passes an object storageUnitIds map straight through on create", async () => {
+ const result = await runDispatch(
+ "items_upsertMethodMaterial",
+ spies.upsertMethodMaterial,
+ {
+ ...methodMaterialFields,
+ storageUnitIds: { loc1: "su1" },
+ _operation: "create"
+ }
+ );
+ expect(result.dispatchError).toBeUndefined();
+ expect(result.calls).toEqual([
+ [
+ spies.FAKE_CLIENT,
+ {
+ ...methodMaterialFields,
+ storageUnitIds: { loc1: "su1" },
+ companyId: "c1",
+ createdBy: "u1"
+ }
+ ]
+ ]);
+ });
+
+ it("omits storageUnitIds from the service payload when the caller omits it (update preserves)", async () => {
+ const result = await runDispatch(
+ "items_upsertMethodMaterial",
+ spies.upsertMethodMaterial,
+ { ...methodMaterialFields, _operation: "update" }
+ );
+ expect(result.dispatchError).toBeUndefined();
+ const [, payload] = result.calls[0] as [unknown, Record<string, unknown>];
+ expect("storageUnitIds" in payload).toBe(false);
+ expect(payload).toMatchObject({ companyId: "c1", updatedBy: "u1" });
+ });
+
+ it("forwards an explicit null storageUnitIds to clear on update", async () => {
+ const result = await runDispatch(
+ "items_upsertMethodMaterial",
+ spies.upsertMethodMaterial,
+ { ...methodMaterialFields, storageUnitIds: null, _operation: "update" }
+ );
+ expect(result.dispatchError).toBeUndefined();
+ const [, payload] = result.calls[0] as [unknown, Record<string, unknown>];
+ expect(payload.storageUnitIds).toBeNull();
+ });
+
it.each([
undefined,
"forged-user"
diff --git a/apps/erp/test/mcp-tool-metadata.test.ts b/apps/erp/test/mcp-tool-metadata.test.ts
index a5043dfb0c..c29ed3489b 100644
--- a/apps/erp/test/mcp-tool-metadata.test.ts
+++ b/apps/erp/test/mcp-tool-metadata.test.ts
@@ -188,6 +188,42 @@ describe("mcp tool-metadata generator", () => {
expect(p.requiresSerialTracking?.enum).toEqual(["true", "false"]);
});
+ // A JSON-string-transform field ALSO maps "true"/"false" to the booleans
+ // (`JSON.parse("true") === true`), which used to false-positive the
+ // string-encoded-boolean annotator and publish a bogus `enum: ["true","false"]`
+ // — so `{}` and `null` failed input validation and `"false"` corrupted the row.
+ // Guard the whole class: none of these JSON-payload fields is a boolean enum.
+ it("does not mistake JSON-string fields for string-encoded booleans", () => {
+ const boolEnum = (field: any) =>
+ Array.isArray(field?.enum) &&
+ field.enum.length === 2 &&
+ field.enum.includes("true") &&
+ field.enum.includes("false");
+
+ // methodMaterial.storageUnitIds is a location→bin map, published as a proper
+ // object map (or null to clear), and no longer a required field.
+ const mm = get("items_upsertMethodMaterial");
+ const storageUnitIds = props(mm).storageUnitIds;
+ expect(boolEnum(storageUnitIds)).toBe(false);
+ const objectBranch = (storageUnitIds?.anyOf ?? [storageUnitIds]).find(
+ (b: any) => b?.type === "object"
+ );
+ expect(objectBranch?.additionalProperties?.type).toBe("string");
+ expect(mm.schema.required ?? []).not.toContain("storageUnitIds");
+
+ // The other JSON-string transforms found in the audit.
+ expect(boolEnum(props(get("quality_upsertIssueWorkflow")).content)).toBe(
+ false
+ );
+ expect(
+ boolEnum(props(get("quality_upsertIssueWorkflow")).requiredActionIds)
+ ).toBe(false);
+ expect(boolEnum(props(get("quality_upsertGaugeCalibrationRecord")).notes)).toBe(
+ false
+ );
+ expect(boolEnum(props(get("quality_upsertRisk")).notes)).toBe(false);
+ });
+
// A parenthesized discriminated-upsert union branch resolves instead of
// publishing an opaque {} member (and the leading-pipe union style must not
// contribute an empty first member).
diff --git a/scripts/lib/validator-to-json-schema.ts b/scripts/lib/validator-to-json-schema.ts
index 346690fd8a..eaabbecfc3 100644
--- a/scripts/lib/validator-to-json-schema.ts
+++ b/scripts/lib/validator-to-json-schema.ts
@@ -83,11 +83,21 @@ function isStringEncodedBoolean(field: unknown): boolean {
try {
const asTrue = f.safeParse("true");
const asFalse = f.safeParse("false");
+ // A JSON-parsing transform ALSO maps "true"/"false" to the booleans —
+ // `JSON.parse("true") === true` — so those two probes alone false-positive on
+ // fields whose string is a JSON payload (methodMaterial.storageUnitIds's
+ // location→bin map, the issue-workflow `content`, gauge/risk `notes`), which
+ // then published a bogus `enum: ["true","false"]` and rejected any real value.
+ // A genuine string-encoded boolean maps EVERY string to a boolean; a JSON
+ // parser maps an arbitrary non-JSON string to a non-boolean (its object/array
+ // fallback) or rejects it. One extra probe tells the two apart.
+ const asOther = f.safeParse("__carbon_not_a_boolean__");
return (
asTrue.success &&
asTrue.data === true &&
asFalse.success &&
- asFalse.data === false
+ asFalse.data === false &&
+ (!asOther.success || typeof asOther.data === "boolean")
);
} catch {
return false;