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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(api): MCP writes Markdown into notes and work instructions (#1964)
Sid370bb8487a03
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 33e7fb8509..36c23ae28b 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -4010,6 +4010,16 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Applies to:** every `useFetcher` used from a layout or provider, every background timer that submits or loads, `packages/react/src/ErrorBoundary/`.+## A field edited in a plain textarea must not read its text as Markdown++**Context:** MCP rich-text inputs (notes, work instructions) are read as Markdown through `toTiptapDoc` / `TiptapText`. Contract notes share that input, but the app edits them in a plain `TextArea` (`ContractDetailsForm`, `ContractProperties`) and shows the saved document with `TiptapText(doc).toString()`.++**Problem:** `TiptapText(doc).toString()` drops what Markdown turned into structure. "1. Ship" became an ordered list and read back as "Ship"; "a*b*c" read back as "abc". The textarea showed the stripped text at once, and the next save stored it.++**Rule:** A rich-text field whose UI is a plain textarea read back with `TiptapText(doc).toString()` stores text as typed: `optionalPlainTextDoc` / `TiptapText(text, { format: "text" })`, not `optionalTiptapDoc` / the Markdown default. Markdown is for fields a rich editor shows, where the formatting survives.++**Applies to:** `apps/erp/app/modules/shared/shared.models.ts` (`toTiptapDoc`, `optionalTiptapDoc`, `optionalPlainTextDoc`), contract notes (`customerContractValidator`, `setContractTerm`), any new textarea over a `json` column.+## A posting's refusal only reaches the dialog when it is thrown as a 4xx**Context:** A refused receipt void showed "Failed to void receipt" with no reason. The guards inside the `post-receipt` posting said exactly why ("stock received on this receipt was moved, picked or shipped since it was received").diff --git a/.claude/rules/linear-integration.md b/.claude/rules/linear-integration.mdindex d74112a66b..574b6bbadd 100644--- a/.claude/rules/linear-integration.md+++ b/.claude/rules/linear-integration.md@@ -36,9 +36,9 @@ type, not just `action`.`mapLinearStatusToCarbonStatus` / `mapCarbonStatusToLinearStatus`. `started`→"InProgress", `completed`→"Completed", `canceled`→"Skipped", else (triage/backlog/todo/unstarted)→"Pending".-- **Rich text:** `lib/richtext.ts` — `markdownToTiptap` / `tiptapToMarkdown`- (+ `tiptapDocumentsEqual`, `isTiptapEmpty`). Linear description (markdown) ↔ Carbon- task `notes` (Tiptap JSON).+- **Rich text:** `TiptapText` (`@carbon/files/markdown`) — `TiptapText(description).toDocument()`+ reads a Linear description (Markdown) into Carbon task `notes` (Tiptap JSON);+ `TiptapText(notes).toMarkdown()` writes it back.- **Types:** `lib/types.ts` — `LinearIssueSchema` (zod): `id, title, description?, url,state{name,color,type}, identifier, dueDate?, assignee{email}?`.@@ -98,7 +98,7 @@ actionId)` looks up by **`entityId`** (the action id, despite the name) and pars- **Create new** `api+/integrations.linear.issue.create.ts`: GET teams (+ team membersfiltered to matching Carbon employees when `?teamId`); POST create issue, link, attach.- **Sync notes** `api+/integrations.linear.issue.sync-notes.ts`: POST `{actionId, notes}`- → `tiptapToMarkdown` → `updateIssue({description})`.+ → `TiptapText(notes).toMarkdown()` → `updateIssue({description})`.- **Notification service** `packages/ee/src/notifications/services/linear.ts`(`LinearNotificationService`, id `"linear"`, registered in`packages/ee/src/notifications/index.ts`). Reacts to events (`notifications/types.ts`):diff --git a/.claude/rules/mcp-tools-reference.md b/.claude/rules/mcp-tools-reference.mdindex 05f8f089c1..463d0c5c95 100644--- a/.claude/rules/mcp-tools-reference.md+++ b/.claude/rules/mcp-tools-reference.md@@ -356,6 +356,24 @@ salesOrderLineId?, convert? }`). The `temp-staging` storage policies read the kescopes (`parts_create` / `parts_update`), so an API key with those scopes can mintthe URL and upload — unlike the document pair above, which signs into a company bucket.+## Rich text is Markdown++A rich-text column (notes, work instructions, change-notice text) holds a+TipTap document. A tool takes it as Markdown and stores it with+`TiptapText(text).toDocument()` (`@carbon/files/markdown`, CommonMark, raw HTML+kept as text, no DOM), so headings, bold, italic, lists, links, quotes and code render+in the editor. The entry points: `toTiptapDoc` / `optionalTiptapDoc`+(`shared.models.ts`; a JSON document string or object passes through), the+three `set…WorkInstruction` tools, and `shared_setNotes`, which writes the+notes a person edits in the app (`noteFields`: internal / external notes on+sales and purchasing documents and lines, `notes` on jobs, items, fixed+assets, picking lists and stock transfers) as the caller, like the editors.+Empty text stores `{}`. `TiptapText(text, { format: "text" })` stores text as+typed, for imported text that is not ours to read as Markdown (Paperless Parts)+and for contract notes (`optionalPlainTextDoc`): the app edits them in a plain+textarea read back with `TiptapText(doc).toString()`, which would drop the+Markdown markers.+## Gotchas- **Renaming or moving a service function renames its tool**, and there are no@@ -366,5 +384,13 @@ the URL and upload — unlike the document pair above, which signs into a companruns the gate and `run`; nothing a route does around the call.- A function gated on several modules publishes `module: null` in themanifest; its own gate decides, as for every function.+- **A form validator's `.refine()` checks are invisible in the published+ schema**: the manifest says a field is optional, and the call refuses it+ anyway. Give the API input the base object and fill or keep what a caller+ leaves out. The job and quote operations do: `baseJobOperationValidator` /+ `baseQuoteOperationValidator`, a create filled by `withOperationStandards`+ (`shared.service.ts`, as the bill of process form fills it), an update+ leaving out what it was not sent; only the inspection plan stays required+ (`inspectionPlanRequired`). Pinned by `apps/erp/test/operation-api-input.test.ts`.- "Shelf" was renamed to **storage unit** (`inventory_*StorageUnit*`). "Shelflife" (`*ShelfLife*`) is a different, current concept.diff --git a/.claude/rules/pdf-generation-patterns.md b/.claude/rules/pdf-generation-patterns.mdindex eee9342d21..4850f37cff 100644--- a/.claude/rules/pdf-generation-patterns.md+++ b/.claude/rules/pdf-generation-patterns.md@@ -126,7 +126,8 @@ Times-Roman / Courier are PDF built-ins (no registration).calls `registerDocumentFonts()`. The `family` arg is ignored (all registered up front).- `getSafeFontFamily(family)` — returns the family if built-in/registered, else`"Helvetica"`. **Every render path must route the settings font through this**- (both `Template` and the hand-built `file+/job+/$jobId.traveler[.]pdf.tsx` route)+ (both `Template` and the hand-built job traveler, `renderJobTravelerPdf` in+ `apps/erp/app/modules/production/production.pdf.tsx`, which both traveler routes call)so an unregistered family can never throw.## Serving — the file route (`apps/*/app/routes/file+/<doc>+/$id[.]pdf.tsx`)diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex 1fe1c7d620..dc20b05e92 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -4856,8 +4856,8 @@ export const updateMethodOperation = defineServiceFn({* release lock applies, as in the bill of process editor.** @param id - The method operation's id.- * @param text - The work instruction as plain text: each line is a paragraph,- * `**text**` is bold. Empty text clears it.+ * @param text - The work instruction as Markdown: headings, **bold**,+ * _italic_, lists, links, quotes and code. Empty text clears it.** @mcp*/diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex a0d82e99b7..3af1ed0c3f 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -32,6 +32,7 @@ import {TEMP_STAGING_BUCKET} from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";+import { TiptapText } from "@carbon/files/markdown";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { oncePerRead } from "@carbon/logger/middleware.server";@@ -43,7 +44,6 @@ import {pick,pluckUnique,searchFilter,- textToTiptap,withPathIds} from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";@@ -10157,11 +10157,11 @@ export const isMakeMethodId = (id: string) => id.startsWith("make_");// ── Change notices ──────────────────────────────────────────────────────────-// Reason and description arrive as plain text; the columns are tiptap JSON, so+// Reason and description arrive as Markdown; the columns are tiptap JSON, so// non-empty text becomes a doc the detail page's editor can edit.export function toRichText(value: string | undefined): Json | undefined {if (!value) return undefined;- return textToTiptap(value) as unknown as Json;+ return TiptapText(value).toDocument() as unknown as Json;}const onShapeDataValidator = z.object({diff --git a/apps/erp/app/modules/production/production.pdf.tsx b/apps/erp/app/modules/production/production.pdf.tsxnew file mode 100644index 0000000000..0170e18a7b--- /dev/null+++ b/apps/erp/app/modules/production/production.pdf.tsx@@ -0,0 +1,350 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import type { JobTravelerMaterial } from "@carbon/documents/pdf";+import {+ ensureFont,+ Footer,+ getSafeFontFamily,+ JobTravelerPageContent+} from "@carbon/documents/pdf";+import {+ collectSectionIds,+ interpolateContent,+ resolveTemplate,+ toDocumentTemplate+} from "@carbon/documents/template";+import { getLogger } from "@carbon/logger";+import type { JSONContent } from "@carbon/react";+import {+ flattenTree,+ generateBomIds,+ groupBy,+ indexBy,+ pluckUnique+} from "@carbon/utils";+import {+ Document,+ Page,+ renderToStream,+ StyleSheet+} from "@react-pdf/renderer";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplate,+ resolveSections+} from "~/modules/settings/settings.service";+import { getBase64ImageFromSupabase } from "~/modules/shared/shared.service";+import {+ getJob,+ getJobOperationsByMethodIds,+ getTrackedEntityByJobId+} from "./production.service";+import { getJobMethodTree } from "./production.utils";++const logger = getLogger("erp", "production", "pdf");++/**+ * A job's traveler: one page per make method, or only `jobMakeMethodId`'s page.+ * Both traveler routes render through here, so the company's Job Traveler+ * template (blocks, work instructions, header, footer, font) and its traveler+ * settings apply to every link. Throws a 404 for a job or method of another+ * company, and an error when a record cannot be read.+ */+export async function renderJobTravelerPdf(+ client: SupabaseClient<Database>,+ {+ companyId,+ jobId,+ jobMakeMethodId,+ locale+ }: {+ companyId: string;+ jobId: string;+ jobMakeMethodId?: string;+ locale: string;+ }+): Promise<{ body: Buffer; fileName: string }> {+ const job = await getJob(client, jobId);+ if (job.error || !job.data) {+ logger.error("Failed to load job", { error: job.error });+ throw new Error("Failed to load job");+ }+ // Every read below is keyed off this job and runs as the service role.+ if (job.data.companyId !== companyId) {+ logger.error("Job does not belong to this company", { companyId, jobId });+ throw new Response("Not found", { status: 404 });+ }++ let makeMethodQuery = client+ .from("jobMakeMethod")+ .select("*, ...item(itemType:type)")+ .eq("jobId", jobId)+ .eq("companyId", companyId);+ if (jobMakeMethodId) {+ makeMethodQuery = makeMethodQuery.eq("id", jobMakeMethodId);+ }+ const jobMakeMethods = await makeMethodQuery.order("createdAt", {+ ascending: true+ });+ if (jobMakeMethods.error) {+ logger.error("Failed to load jobMakeMethods", {+ error: jobMakeMethods.error+ });+ throw new Error("Failed to load job make methods");+ }+ if (jobMakeMethods.data.length === 0) {+ throw new Response("Not found", { status: 404 });+ }++ const makeMethodIds = jobMakeMethods.data.map((method) => method.id);+ const itemIds = pluckUnique(jobMakeMethods.data, (method) => method.itemId);+ const rootMethod = jobMakeMethods.data.find(+ (method) => method.parentMaterialId === null+ );++ const [+ company,+ companySettings,+ customer,+ methodTree,+ documentTemplate,+ operations,+ items+ ] = await Promise.all([+ getCompany(client, companyId),+ getCompanySettings(client, companyId),+ client+ .from("customer")+ .select("*")+ .eq("id", job.data.customerId ?? "")+ .eq("companyId", companyId)+ .maybeSingle(),+ getJobMethodTree(client, jobId),+ getDocumentTemplate(client, companyId, "jobTraveler"),+ getJobOperationsByMethodIds(client, makeMethodIds, companyId),+ client+ .from("item")+ .select("*, modelUpload(thumbnailPath)")+ .in("id", itemIds)+ .eq("companyId", companyId)+ ]);+ if (company.error) {+ logger.error("Failed to load company", { error: company.error });+ throw new Error("Failed to load company");+ }+ if (companySettings.error) {+ logger.error("Failed to load company settings", {+ error: companySettings.error+ });+ throw new Error("Failed to load company settings");+ }+ if (operations.error) {+ logger.error("Failed to load operations", { error: operations.error });+ throw new Error("Failed to load job operations");+ }+ if (items.error) {+ logger.error("Failed to load items", { error: items.error });+ throw new Error("Failed to load the job's items");+ }+ // Without its template the traveler prints the default one, which leaves+ // out work instructions; say so rather than print it silently.+ if (documentTemplate.error) {+ logger.error(+ "Failed to load the Job Traveler template; using the default",+ {+ companyId,+ jobId,+ error: documentTemplate.error+ }+ );+ }+ if (customer.error) {+ logger.error("Failed to load the job's customer", {+ companyId,+ jobId,+ error: customer.error+ });+ }++ const settings = companySettings.data as {+ includeMaterialsOnTraveler?: boolean | null;+ includeOperationsOnTraveler?: boolean | null;+ } | null;+ // Opt-in: a materials (BOM) section. Opt-out (defaults on): the operations.+ const includeMaterials = settings?.includeMaterialsOnTraveler ?? false;+ const includeOperations = settings?.includeOperationsOnTraveler ?? true;++ const itemById = indexBy(items.data, (item) => item.id);+ const rootItem = rootMethod ? itemById.get(rootMethod.itemId ?? "") : null;++ // Only loaded when the materials section is on; the batch or serial number+ // belongs to the item the job makes.+ const [jobMaterials, trackedEntity] = await Promise.all([+ includeMaterials+ ? client+ .from("jobMaterial")+ .select(+ "id, jobMakeMethodId, description, quantity, unitOfMeasureCode, methodType, item(readableIdWithRevision)"+ )+ .in("jobMakeMethodId", makeMethodIds)+ .eq("companyId", companyId)+ .order("order", { ascending: true })+ : null,+ rootItem && ["Batch", "Serial"].includes(rootItem.itemTrackingType)+ ? getTrackedEntityByJobId(client, jobId)+ : null+ ]);+ if (jobMaterials?.error) {+ logger.error("Failed to load job materials", { error: jobMaterials.error });+ throw new Error("Failed to load job materials");+ }+ const batchNumber = trackedEntity?.data?.readableId ?? undefined;++ const jobNotes = job.data.notes as JSONContent | undefined;++ const bomIdMap = new Map<string, string>();+ if (!methodTree.error && methodTree.data?.length > 0) {+ const flatMethods = flattenTree(methodTree.data[0]);+ const bomIds = generateBomIds(flatMethods);+ flatMethods.forEach((node, index) => {+ bomIdMap.set(node.data.jobMaterialMakeMethodId, bomIds[index]);+ });+ }++ const operationsByMethod = groupBy(+ operations.data ?? [],+ (operation) => operation.jobMakeMethodId ?? ""+ );+ const materialsByMethod = groupBy(+ jobMaterials?.data ?? [],+ (material) => material.jobMakeMethodId ?? ""+ );++ const makeMethodsWithData = await Promise.all(+ jobMakeMethods.data.map(async (makeMethod) => {+ const item = itemById.get(makeMethod.itemId ?? "");+ if (!item) {+ logger.error("Failed to load item", { itemId: makeMethod.itemId });+ throw new Error(`Failed to load item for make method ${makeMethod.id}`);+ }++ const thumbnailPath =+ item.thumbnailPath ?? item.modelUpload?.thumbnailPath ?? null;+ const thumbnail = thumbnailPath+ ? await getBase64ImageFromSupabase(client, thumbnailPath)+ : null;++ const materials: JobTravelerMaterial[] = (+ materialsByMethod[makeMethod.id] ?? []+ ).map((material) => ({+ id: material.id,+ itemReadableId: material.item?.readableIdWithRevision,+ description: material.description,+ quantity: material.quantity,+ unitOfMeasureCode: material.unitOfMeasureCode,+ methodType: material.methodType+ }));++ return {+ makeMethod,+ operations: operationsByMethod[makeMethod.id] ?? [],+ item,+ thumbnail,+ batchNumber: makeMethod === rootMethod ? batchNumber : undefined,+ materials,+ bomId: bomIdMap.get(makeMethod.id)+ };+ })+ );++ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "jobTraveler"+ );+ const resolved = resolveTemplate("jobTraveler", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);++ const footerSectionContent = resolved.footerSectionId+ ? sections[resolved.footerSectionId]?.content+ : undefined;+ const footerContent = footerSectionContent+ ? interpolateContent(footerSectionContent, {+ "job.number": job.data.jobId ?? "",+ "company.name": company.data.name ?? ""+ })+ : undefined;+ const showFooter = resolved.footerSectionId !== null;++ const styles = StyleSheet.create({+ body: {+ fontFamily: getSafeFontFamily(resolved.settings.fontFamily),+ padding: "20px 40px 50px 40px",+ color: "#000000",+ backgroundColor: "#FFFFFF"+ }+ });++ const stream = await renderToStream(+ <Document+ title="Job Traveler"+ author="Carbon"+ subject="Job Traveler"+ keywords="job traveler, manufacturing"+ >+ {makeMethodsWithData.map((data, index) => (+ <Page key={data.makeMethod.id} size="A4" style={styles.body}>+ <JobTravelerPageContent+ company={company.data as any}+ job={job.data}+ jobOperations={data.operations}+ customer={customer.data}+ item={data.item}+ batchNumber={data.batchNumber}+ bomId={data.bomId}+ locale={locale}+ notes={index === 0 ? jobNotes : undefined}+ thumbnail={data.thumbnail}+ includeMaterials={includeMaterials}+ includeOperations={includeOperations}+ materials={data.materials}+ methodRevision={data.makeMethod.version?.toString()}+ template={templateConfig}+ sections={sections}+ />+ {showFooter && (+ <Footer+ documentId={job.data.jobId}+ content={footerContent}+ showPageNumbers={resolved.settings.showPageNumbers}+ pageNumberFormat={resolved.settings.pageNumberFormat}+ showRegistrationLine={resolved.settings.showRegistrationLine}+ />+ )}+ </Page>+ ))}+ </Document>+ );++ const body: Buffer = await new Promise((resolve, reject) => {+ const buffers: Uint8Array[] = [];+ stream.on("data", (data) => {+ buffers.push(data);+ });+ stream.on("end", () => {+ resolve(Buffer.concat(buffers));+ });+ stream.on("error", reject);+ });++ return { body, fileName: `${company.data.name} - ${job.data.jobId}.pdf` };+}diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex ba3c5a2cfb..b62c187c51 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -22,6 +22,7 @@ import {} from "@carbon/utils";import { sql } from "kysely";import { z } from "zod";+import { zfd } from "zod-form-data";import {cancelOpenPickingListsForJob,issueMaterial,@@ -40,7 +41,11 @@ import {} from "~/modules/items/items.service";import { isSalesOrderClosed } from "~/modules/sales/sales.models";import { resolveJobConfiguration } from "~/modules/sales/sales.utils";-import { methodItemType, methodType } from "~/modules/shared/shared.models";+import {+ inspectionPlanRequired,+ methodItemType,+ methodType+} from "~/modules/shared/shared.models";import {getCompanyTimeZone,isActiveCompanyEmployee@@ -48,12 +53,14 @@ import {import {invokeCreate,invokePosting,- setOperationWorkInstruction+ setOperationWorkInstruction,+ withOperationStandards} from "../shared/shared.service";import { updateSortOrder } from "../shared/sort-order";import {type AssemblyModelState,assemblyStepComponentsReassignValidator,+ baseJobOperationValidator,bulkJobValidator,CANCELLABLE_JOB_STATUSES,copyPeopleBoardValidator,@@ -67,7 +74,6 @@ import {JOB_LOCKED_MESSAGE,JOB_LOCKED_STATUSES,jobOperationStatus,- jobOperationValidator,jobStatus,jobValidator,makeToAssetItemError,@@ -2488,23 +2494,37 @@ export const deleteJobMaterials = defineServiceFn({}});+// The bill of process form requires times, units and rates; the API fills a+// new operation's from its work center or process, and an update leaves out+// what it was not sent.+const jobOperationInput = baseJobOperationValidator+ .extend({+ workCenterId: zfd.text(z.string().optional()),+ jobId: z.string(),+ customFields: customFieldsInput+ })+ .refine(...inspectionPlanRequired);+/*** Add an operation to a job's method.** @remarks- * The make method must be this job's. Then the method's requirements and the+ * The make method must be this job's. Times, units and rates left out are+ * filled as the bill of process form fills them: from the work center, else+ * the process's default standard factor and the average of its active work+ * centers, with times 0; an outside operation's minimum cost and lead time+ * come from its supplier process. Then the method's requirements and the* job's operation dependencies are recalculated.** @mcp*/export const createJobOperation = defineServiceFn({- input: jobOperationValidator.extend({- jobId: z.string(),- customFields: customFieldsInput- }),+ input: jobOperationInput,permission: { create: "production" },- async run(ctx, operation) {+ async run(ctx, input) {+ const operation = await withOperationStandards(ctx, input);+ if (operation instanceof CarbonError) return operation;const job = await service.requireJob(ctx, operation.jobId);if (job instanceof CarbonError) return job;const parents = await service.requireJobChildren(ctx, operation.jobId, {@@ -2540,16 +2560,13 @@ export const createJobOperation = defineServiceFn({** @remarks* Writes the operation's process, type, times, rates, work center, outside- * processing costs and links; it never moves to another job or method.- * Nothing is recalculated.+ * processing costs and links; a field left out keeps its value. It never+ * moves to another job or method. Nothing is recalculated.** @mcp*/export const updateJobOperation = defineServiceFn({- input: jobOperationValidator.extend({- jobId: z.string(),- customFields: customFieldsInput- }),+ input: jobOperationInput,permission: { create: "production" },async run(ctx, operation) {@@ -2580,8 +2597,8 @@ export const updateJobOperation = defineServiceFn({* the job's editor is.** @param id - The job operation's id.- * @param text - The work instruction as plain text: each line is a paragraph,- * `**text**` is bold. Empty text clears it.+ * @param text - The work instruction as Markdown: headings, **bold**,+ * _italic_, lists, links, quotes and code. Empty text clears it.** @mcp*/diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 052642b0d7..73d35bab04 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -94,6 +94,7 @@ import {} from "@carbon/database/supersession-pick";import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";import { storage } from "@carbon/files";+import { TiptapText } from "@carbon/files/markdown";import { trigger } from "@carbon/jobs";import type { JobSource } from "@carbon/lib/telemetry";import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";@@ -129,8 +130,6 @@ import {round,scrapAllowance,searchFilter,- textToTiptap,- tiptapToText,unchecked} from "@carbon/utils";import type {@@ -2062,19 +2061,34 @@ export async function getJobOperationsList(.order("order", { ascending: true });}+const JOB_OPERATION_DETAIL_COLUMNS =+ "*, jobOperationBatch(id, readableId, status), jobOperationTool(*, jobOperationToolStep(jobOperationStepId)), jobOperationParameter(*), jobOperationStep(*, jobOperationStepRecord(*), jobOperationStepSlide(*))" as const;+export async function getJobOperationsByMethodId(client: SupabaseClient<Database>,jobMakeMethodId: string) {return client.from("jobOperation")- .select(- "*, jobOperationBatch(id, readableId, status), jobOperationTool(*, jobOperationToolStep(jobOperationStepId)), jobOperationParameter(*), jobOperationStep(*, jobOperationStepRecord(*), jobOperationStepSlide(*))"- )+ .select(JOB_OPERATION_DETAIL_COLUMNS).eq("jobMakeMethodId", jobMakeMethodId).order("order", { ascending: true });}+/** `getJobOperationsByMethodId` for several make methods of one company. */+export async function getJobOperationsByMethodIds(+ client: SupabaseClient<Database>,+ jobMakeMethodIds: string[],+ companyId: string+) {+ return client+ .from("jobOperation")+ .select(JOB_OPERATION_DETAIL_COLUMNS)+ .in("jobMakeMethodId", jobMakeMethodIds)+ .eq("companyId", companyId)+ .order("order", { ascending: true });+}+export async function getJobOperationStepRecords(client: SupabaseClient<Database>,jobId: string,@@ -8022,7 +8036,7 @@ function newAssemblyStepColumns(data: AssemblyStepFields) {description: data.description ?? {},instructionText:data.description !== undefined- ? tiptapToText(data.description as JSONContent) || null+ ? TiptapText(data.description).toString() || null: null,required: data.required ?? false,unitOfMeasureCode:@@ -8054,7 +8068,7 @@ export async function upsertAssemblyInstructionStep(const derivedInstructionText =data.description !== undefined? {- instructionText: tiptapToText(data.description as JSONContent) || null+ instructionText: TiptapText(data.description).toString() || null}: {};@@ -12758,7 +12772,7 @@ const getMethodLogger = getLogger("erp", "get-method");function toTiptapDoc(value: unknown): Json {if (value && typeof value === "object") return value as Json;if (typeof value === "string" && value.length > 0) {- return textToTiptap(value) as Json;+ return TiptapText(value, { format: "text" }).toDocument() as Json;}return {};}diff --git a/apps/erp/app/modules/sales/sales.models.ts b/apps/erp/app/modules/sales/sales.models.tsindex 73407aac63..60833c4cfc 100644--- a/apps/erp/app/modules/sales/sales.models.ts+++ b/apps/erp/app/modules/sales/sales.models.ts@@ -25,6 +25,7 @@ import {methodOperationOrders,methodType,operationTypes,+ optionalPlainTextDoc,optionalTiptapDoc,standardFactorType,taxExemptionReasons@@ -583,53 +584,55 @@ export const quoteMaterialValidator = z});-export const quoteOperationValidator = z- .object({- id: z.string().min(1, { message: "Operation ID is required" }),- quoteMakeMethodId: z- .string()- .min(1, { message: "Quote Make Method is required" }),- order: zfd.numeric(z.number().min(0)),- operationOrder: z.enum(methodOperationOrders, {- error: "Operation order is required"- }),- operationType: z.enum(operationTypes, {- error: "Operation type is required"- }),- processId: z.string().min(1, { message: "Process is required" }),- procedureId: zfd.text(z.string().optional()),- assemblyInstructionId: zfd.text(z.string().optional()),- inspectionDocumentId: zfd.text(z.string().optional()),- workCenterId: zfd.text(z.string().optional()),- description: zfd.text(- z.string().min(0, { message: "Description is required" })- ),- setupUnit: z- .enum(standardFactorType, {- error: "Setup unit is required"- })- .optional(),- setupTime: zfd.numeric(z.number().min(0).optional()),- laborUnit: z- .enum(standardFactorType, {- error: "Labor unit is required"- })- .optional(),- laborTime: zfd.numeric(z.number().min(0).optional()),- machineUnit: z- .enum(standardFactorType, {- error: "Machine unit is required"- })- .optional(),- machineTime: zfd.numeric(z.number().min(0).optional()),- machineRate: zfd.numeric(z.number().min(0).optional()),- overheadRate: zfd.numeric(z.number().min(0).optional()),- laborRate: zfd.numeric(z.number().min(0).optional()),- operationSupplierProcessId: zfd.text(z.string().optional()),- operationMinimumCost: zfd.numeric(z.number().min(0).optional()),- operationUnitCost: zfd.numeric(z.number().min(0).optional()),- operationLeadTime: zfd.numeric(z.number().min(0).optional())- })+/** The quote operation's fields, without the bill of process form's checks. */+export const baseQuoteOperationValidator = z.object({+ id: z.string().min(1, { message: "Operation ID is required" }),+ quoteMakeMethodId: z+ .string()+ .min(1, { message: "Quote Make Method is required" }),+ order: zfd.numeric(z.number().min(0)),+ operationOrder: z.enum(methodOperationOrders, {+ error: "Operation order is required"+ }),+ operationType: z.enum(operationTypes, {+ error: "Operation type is required"+ }),+ processId: z.string().min(1, { message: "Process is required" }),+ procedureId: zfd.text(z.string().optional()),+ assemblyInstructionId: zfd.text(z.string().optional()),+ inspectionDocumentId: zfd.text(z.string().optional()),+ workCenterId: zfd.text(z.string().optional()),+ description: zfd.text(+ z.string().min(0, { message: "Description is required" })+ ),+ setupUnit: z+ .enum(standardFactorType, {+ error: "Setup unit is required"+ })+ .optional(),+ setupTime: zfd.numeric(z.number().min(0).optional()),+ laborUnit: z+ .enum(standardFactorType, {+ error: "Labor unit is required"+ })+ .optional(),+ laborTime: zfd.numeric(z.number().min(0).optional()),+ machineUnit: z+ .enum(standardFactorType, {+ error: "Machine unit is required"+ })+ .optional(),+ machineTime: zfd.numeric(z.number().min(0).optional()),+ machineRate: zfd.numeric(z.number().min(0).optional()),+ overheadRate: zfd.numeric(z.number().min(0).optional()),+ laborRate: zfd.numeric(z.number().min(0).optional()),+ operationSupplierProcessId: zfd.text(z.string().optional()),+ operationMinimumCost: zfd.numeric(z.number().min(0).optional()),+ operationUnitCost: zfd.numeric(z.number().min(0).optional()),+ operationLeadTime: zfd.numeric(z.number().min(0).optional())+});++export const quoteOperationValidator = baseQuoteOperationValidator.refine((data) => {if (data.operationType === "Outside Processing") {@@ -1110,8 +1113,8 @@ export const salesRfqValidator = z.object({customerId: z.string().min(1, { message: "Customer is required" }),customerReference: zfd.text(z.string().optional()),expirationDate: zfd.text(z.string().optional()),- externalNotes: zfd.text(z.string().optional()),- internalNotes: zfd.text(z.string().optional()),+ externalNotes: optionalTiptapDoc,+ internalNotes: optionalTiptapDoc,locationId: zfd.text(z.string().optional()),rfqDate: z.string().min(1, { message: "Order Date is required" }),status: z.enum(salesRFQStatusType).optional(),@@ -1845,7 +1848,7 @@ export const customerContractValidator = zpaymentTermId: zfd.text(z.string().optional()),currencyCode: z.string().min(1, { message: "Currency is required" }),exchangeRate: zfd.numeric(z.number().optional()),- notes: optionalTiptapDoc+ notes: optionalPlainTextDoc}).refine((data) => (data.duration === "custom" ? !!data.endDate : true), {message: "End date is required",diff --git a/apps/erp/app/modules/sales/sales.server.ts b/apps/erp/app/modules/sales/sales.server.tsindex e918a40a69..d0c9a702d7 100644--- a/apps/erp/app/modules/sales/sales.server.ts+++ b/apps/erp/app/modules/sales/sales.server.ts@@ -9,6 +9,7 @@ import { getQuoteDisplayId } from "@carbon/documents/pdf";import { insertAuditLogEntries } from "@carbon/ee/audit.server";import { safeStorageFileName, storage } from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";+import { TiptapText } from "@carbon/files/markdown";import { validator } from "@carbon/form";import { batchTrigger, trigger } from "@carbon/jobs";import { checkPartyContactRequirement } from "@carbon/lib/party-contact.server";@@ -23,7 +24,6 @@ import {getSalesOrderStatus,round,suggestContractType,- textToTiptap,unchecked} from "@carbon/utils";import { z } from "zod";@@ -47,6 +47,10 @@ import {getCompanySettings,getNextSequence as getNextSequenceNumber} from "~/modules/settings/settings.service";+import {+ inspectionPlanRequired,+ optionalTiptapDoc+} from "~/modules/shared/shared.models";import {getCompanyTimeZone,getLocationTimeZone,@@ -61,9 +65,11 @@ import { sanitize } from "~/utils/supabase";import {invokeCreate,invokePosting,- setOperationWorkInstruction+ setOperationWorkInstruction,+ withOperationStandards} from "../shared/shared.service";import {+ baseQuoteOperationValidator,contractAmendmentChangeValidator,contractDurationOf,customerContractAmendmentValidator,@@ -76,7 +82,6 @@ import {isSalesRfqLocked,quoteLineValidator,quoteMaterialValidator,- quoteOperationValidator,quoteStatusType,quoteValidator,rentalAgreementLineClassificationValidator,@@ -3271,17 +3276,26 @@ export const deleteQuoteMaterialsAndReprice = defineServiceFn({return { ids };}});-const quoteOperationInput = quoteOperationValidator.safeExtend({- quoteId: z.string(),- quoteLineId: z.string(),- customFields: customFieldValues.optional()-});+// The bill of process form requires times, units and rates; the API fills a+// new operation's from its work center or process, and an update leaves out+// what it was not sent.+const quoteOperationInput = baseQuoteOperationValidator+ .extend({+ quoteId: z.string(),+ quoteLineId: z.string(),+ customFields: customFieldValues.optional()+ })+ .refine(...inspectionPlanRequired);/*** Add an operation to a quote line's method, then reprice the line.** @remarks- * The line and its make method must be this company's and the line's.+ * The line and its make method must be this company's and the line's. Times,+ * units and rates left out are filled as the bill of process form fills them:+ * from the work center, else the process's default standard factor and the+ * average of its active work centers, with times 0; an outside operation's+ * minimum cost and lead time come from its supplier process.** @mcp*/@@ -3289,7 +3303,9 @@ export const createQuoteOperation = defineServiceFn({input: quoteOperationInput,permission: { create: "sales" },- async run(ctx, { customFields, ...operation }) {+ async run(ctx, { customFields, ...input }) {+ const operation = await withOperationStandards(ctx, input);+ if (operation instanceof CarbonError) return operation;const { quoteId, quoteLineId } = operation;const refused = await service.refuseUnlessQuoteMethodRows(ctx, {quoteId,@@ -3319,6 +3335,9 @@ export const createQuoteOperation = defineServiceFn({/*** Change an operation on a quote line's method, then reprice the line.*+ * @remarks+ * A field left out keeps its value.+ ** @mcp*/export const updateQuoteOperation = defineServiceFn({@@ -3342,7 +3361,8 @@ export const updateQuoteOperation = defineServiceFn({...operation,companyId: ctx.company.id,updatedBy: ctx.auditUserId,- customFields+ // Left out, the custom fields are kept (sanitize writes undefined as null).+ ...(customFields !== undefined && { customFields })});if (updated.error || !updated.data?.id) {return ctx.error(@@ -3364,8 +3384,8 @@ export const updateQuoteOperation = defineServiceFn({* the line's price are unchanged.** @param id - The quote operation's id.- * @param text - The work instruction as plain text: each line is a paragraph,- * `**text**` is bold. Empty text clears it.+ * @param text - The work instruction as Markdown: headings, **bold**,+ * _italic_, lists, links, quotes and code. Empty text clears it.** @mcp*/@@ -3710,7 +3730,11 @@ export const setContractTerm = defineServiceFn({return ctx.error("notFound", "Contract not found");}const contract = current.data;- const notesDoc = value ? textToTiptap(value) : null;+ // Notes are a plain textarea read back with `TiptapText(…).toString()`,+ // so they are stored as typed: Markdown would not survive the round trip.+ const notesDoc = value+ ? TiptapText(value, { format: "text" }).toDocument()+ : null;if (contract.status !== "Draft") {if (field !== "notes") {@@ -8642,8 +8666,8 @@ export const createSalesRFQ = defineServiceFn({customerId: z.string().min(1),customerReference: z.string().optional(),expirationDate: z.string().optional(),- externalNotes: z.string().optional(),- internalNotes: z.string().optional(),+ externalNotes: optionalTiptapDoc,+ internalNotes: optionalTiptapDoc,locationId: z.string().optional(),rfqDate: z.string().min(1),status: z.enum(["Draft", "Ready for Quote", "Quoted", "Closed"]).optional(),@@ -8684,8 +8708,8 @@ export const updateSalesRFQ = defineServiceFn({customerId: z.string().min(1),customerReference: z.string().optional(),expirationDate: z.string().optional(),- externalNotes: z.string().optional(),- internalNotes: z.string().optional(),+ externalNotes: optionalTiptapDoc,+ internalNotes: optionalTiptapDoc,locationId: z.string().optional(),rfqDate: z.string().min(1),status: zdiff --git a/apps/erp/app/modules/sales/ui/Contracts/ContractProperties.tsx b/apps/erp/app/modules/sales/ui/Contracts/ContractProperties.tsxindex 97e8ea380a..f80ca68cfc 100644--- a/apps/erp/app/modules/sales/ui/Contracts/ContractProperties.tsx+++ b/apps/erp/app/modules/sales/ui/Contracts/ContractProperties.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Json } from "@carbon/database";+import { TiptapText } from "@carbon/files/markdown";import {DatePicker,InputControlled,@@ -18,7 +19,7 @@ import {toast,VStack} from "@carbon/react";-import { INPUT_FORMAT, INPUT_STEP, round, tiptapToText } from "@carbon/utils";+import { INPUT_FORMAT, INPUT_STEP, round } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";import { useCallback, useEffect, useState } from "react";@@ -182,9 +183,7 @@ const ContractProperties = () => {const isDisabled = contract.status !== "Draft" || !canUpdate;const isEnded = contract.status === "Ended";const billTo = contract.invoiceCustomerId ?? contract.customerId ?? "";- const notesText = tiptapToText(- (contract.notes ?? null) as Parameters<typeof tiptapToText>[0]- );+ const notesText = TiptapText(contract.notes).toString();const renewalUpliftPoints = round(Number(contract.renewalUplift ?? 0) * 100);return (diff --git a/apps/erp/app/modules/shared/shared.models.test.ts b/apps/erp/app/modules/shared/shared.models.test.tsindex 4411d954c8..6a980ccd41 100644--- a/apps/erp/app/modules/shared/shared.models.test.ts+++ b/apps/erp/app/modules/shared/shared.models.test.ts@@ -2,9 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { TiptapText } from "@carbon/files/markdown";import { describe, expect, it } from "vitest";import {normalizeOperationSourceIds,+ optionalPlainTextDoc,optionalTiptapDoc,toTiptapDoc} from "./shared.models";@@ -24,12 +26,56 @@ describe("toTiptapDoc", () => {expect(toTiptapDoc("hi")).toEqual(doc);});- it("keeps line breaks as paragraphs", () => {+ it("keeps a line break inside the paragraph, as Markdown does", () => {expect(toTiptapDoc("a\nb")).toEqual({type: "doc",content: [- { type: "paragraph", content: [{ type: "text", text: "a" }] },- { type: "paragraph", content: [{ type: "text", text: "b" }] }+ {+ type: "paragraph",+ content: [+ { type: "text", text: "a" },+ { type: "hardBreak" },+ { type: "text", text: "b" }+ ]+ }+ ]+ });+ });++ it("reads text as Markdown", () => {+ expect(toTiptapDoc("## Setup\n\n- [Spec](https://x.test)")).toEqual({+ type: "doc",+ content: [+ {+ type: "heading",+ attrs: { level: 2 },+ content: [{ type: "text", text: "Setup" }]+ },+ {+ type: "bulletList",+ content: [+ {+ type: "listItem",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Spec",+ marks: [+ {+ type: "link",+ attrs: { href: "https://x.test", title: null }+ }+ ]+ }+ ]+ }+ ]+ }+ ]+ }]});});@@ -83,6 +129,46 @@ describe("optionalTiptapDoc", () => {expect(optionalTiptapDoc.safeParse(["x"]).success).toBe(false);expect(optionalTiptapDoc.safeParse(null).success).toBe(false);});++ // A malformed object reached the column and the editor's initial content.+ it("rejects an object that is not a document", () => {+ expect(optionalTiptapDoc.safeParse({ a: 1 }).success).toBe(false);+ expect(optionalTiptapDoc.safeParse({ type: "paragraph" }).success).toBe(+ false+ );+ });++ it("rejects a document whose content is not a list of nodes", () => {+ expect(+ optionalTiptapDoc.safeParse({ type: "doc", content: "bad" }).success+ ).toBe(false);+ expect(+ optionalTiptapDoc.safeParse({+ type: "doc",+ content: [{ type: "paragraph", content: [{ text: "no type" }] }]+ }).success+ ).toBe(false);+ });++ it("takes `{}` as an empty document", () => {+ expect(optionalTiptapDoc.parse({})).toEqual({+ type: "doc",+ content: [{ type: "paragraph" }]+ });+ });+});++describe("optionalPlainTextDoc", () => {+ // Contract notes are a textarea read back with `TiptapText(…).toString()`: a Markdown+ // list there came back without its numbers, and the next save kept that.+ it("stores text as typed, so it reads back unchanged", () => {+ const text = "1. Ship\n2. Install a*b*c";+ expect(TiptapText(optionalPlainTextDoc.parse(text)).toString()).toBe(text);+ });++ it("still accepts a document object", () => {+ expect(optionalPlainTextDoc.parse(doc)).toEqual(doc);+ });});// Outside Processing is done at the supplier, so it has no work center. The@@ -116,6 +202,37 @@ describe("normalizeOperationSourceIds", () => {).toBe("wc1");});+ // A partial update (API) that left the type's own link out kept nothing:+ // the link was written as null and the procedure came off the operation.+ it("keeps the type's own link when it was left out", () => {+ expect(+ normalizeOperationSourceIds<{+ operationType?: string;+ procedureId?: string | null;+ }>({ operationType: "Process" })+ ).not.toHaveProperty("procedureId");+ });++ it("clears the type's own link when it was sent empty", () => {+ expect(+ normalizeOperationSourceIds({+ operationType: "Process",+ procedureId: undefined+ }).procedureId+ ).toBeNull();+ });++ it("clears the other types' links", () => {+ const normalized = normalizeOperationSourceIds<{+ operationType?: string;+ procedureId?: string | null;+ assemblyInstructionId?: string | null;+ }>({ operationType: "Assembly", procedureId: "proc1" });+ expect(normalized.procedureId).toBeNull();+ expect(normalized).not.toHaveProperty("assemblyInstructionId");+ expect(normalized).toHaveProperty("inspectionDocumentId", null);+ });+it("does not add a work center to an in-house operation that omitted it", () => {expect(normalizeOperationSourceIds({ operationType: "Process" })diff --git a/apps/erp/app/modules/shared/shared.models.ts b/apps/erp/app/modules/shared/shared.models.tsindex e6e295056c..07029b44ff 100644--- a/apps/erp/app/modules/shared/shared.models.ts+++ b/apps/erp/app/modules/shared/shared.models.ts@@ -2,13 +2,14 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { Database } from "@carbon/database";import type {BuyPriceBreak,CurrencyRate,SupplierPriceBreak,SupplierPriceMap} from "@carbon/database/supplier-part-price";-import { textToTiptap } from "@carbon/utils";+import { TiptapText } from "@carbon/files/markdown";import { z } from "zod";import { zfd } from "zod-form-data";@@ -165,23 +166,22 @@ export function normalizeOperationSourceIds<workCenterId?: string | null;}>(operation: T): T {+ // The type's own pointer is written only when the caller sent it (a form+ // clearing it sends the key); a partial update that left it out keeps it.+ const own = <K extends keyof T>(key: K, type: string) =>+ operation.operationType !== type+ ? { [key]: null }+ : key in operation+ ? { [key]: operation[key] || null }+ : {};return {...operation,...(operation.operationType === "Outside Processing"? { workCenterId: null }: {}),- procedureId:- operation.operationType === "Process"- ? operation.procedureId || null- : null,- assemblyInstructionId:- operation.operationType === "Assembly"- ? operation.assemblyInstructionId || null- : null,- inspectionDocumentId:- operation.operationType === "Inspection"- ? operation.inspectionDocumentId || null- : null+ ...own("procedureId", "Process"),+ ...own("assemblyInstructionId", "Assembly"),+ ...own("inspectionDocumentId", "Inspection")};}@@ -227,8 +227,9 @@ export const oAuthCallbackSchema = z.object({/*** Coerces whatever a caller sent for a rich-text column into a tiptap document- * object. Accepts plain text, a JSON-encoded document (a form post), or the- * document itself (an MCP / API JSON body).+ * object. Accepts Markdown text, a JSON-encoded document (a form post), or the+ * document itself (an MCP / API JSON body). `format: "text"` stores text as+ * typed instead of reading it as Markdown.** Rich-text columns (`internalNotes`, `externalNotes`, step descriptions) are* `json`, and they MUST hold an object. A JSON string scalar stored there is@@ -242,24 +243,11 @@ export const oAuthCallbackSchema = z.object({* Returns `any`: the doc is consumed both as a DB Json value and as editor* JSONContent, and a narrower type breaks one of the two call sites.*/-export function toTiptapDoc(value: unknown): any {- if (typeof value === "string") {- let parsed: unknown = value;- try {- parsed = JSON.parse(value);- } catch {- // raw text, not JSON- }- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {- return parsed;- }- // Anything else the caller typed is literal text — including text that- // happens to parse as JSON (`"quoted"`, `123`, `[1,2]`). Wrap the ORIGINAL- // value so no characters are lost to the parse.- return textToTiptap(value);- }- if (value && typeof value === "object" && !Array.isArray(value)) return value;- return textToTiptap(String(value));+export function toTiptapDoc(+ value: unknown,+ format: "markdown" | "text" = "markdown"+): any {+ return TiptapText(value, { format }).toDocument();}/**@@ -269,13 +257,47 @@ export function toTiptapDoc(value: unknown): any {* INPUT schema) tells a caller both shapes are accepted, instead of the bare* `{}` a `z.any()` produced.*/-export const optionalTiptapDoc = z- .union([z.string(), z.record(z.string(), z.unknown())])- .transform((value): any => (value === "" ? undefined : toTiptapDoc(value)))- // `.optional()` LAST so the inferred key is optional (`notes?:`) — placing it- // before the transform makes zod infer a required key and every caller that- // omits `notes` stops compiling.- .optional();+// A node's `content` must be a list of nodes, at every depth: a document+// whose content was a string reached the editor and RichTextView, which walk+// it as an array.+type TiptapNodeInput = { type: string; content?: TiptapNodeInput[] };+const tiptapNodeInput: z.ZodType<TiptapNodeInput> = z.lazy(() =>+ z.looseObject({+ type: z.string().min(1),+ text: z.string().optional(),+ content: z.array(tiptapNodeInput).optional()+ })+);+const tiptapDocumentInput = z.looseObject({+ type: z.literal("doc"),+ content: z.array(tiptapNodeInput).optional()+});++const tiptapDocInput = (format?: "markdown" | "text") =>+ z+ .union([+ z.string(),+ // A Tiptap document, or `{}` to clear; any other object is refused.+ tiptapDocumentInput,+ z.strictObject({})+ ])+ .transform((value): any =>+ value === "" ? undefined : toTiptapDoc(value, format)+ )+ // `.optional()` LAST so the inferred key is optional (`notes?:`) — placing+ // it before the transform makes zod infer a required key and every caller+ // that omits `notes` stops compiling.+ .optional();++/** Text read as Markdown. */+export const optionalTiptapDoc = tiptapDocInput();++/**+ * Text stored as typed, for a field edited in a plain textarea that reads it+ * back with `TiptapText(…).toString()`: Markdown markers would not survive that+ * round trip (`1. Ship` would come back as `Ship`).+ */+export const optionalPlainTextDoc = tiptapDocInput("text");export const operationStepValidator = z.object({@@ -436,6 +458,23 @@ export const savedViewStateValidator = z.object({sorts: z.array(z.string()).optional()});+/**+ * An Inspection operation needs its inspection plan: unlike times, units and+ * rates, nothing can fill it in. Spread into `.refine(...)`.+ */+export const inspectionPlanRequired: [+ (operation: {+ operationType: string;+ inspectionDocumentId?: string;+ }) => boolean,+ { message: string; path: string[] }+] = [+ (operation) =>+ operation.operationType !== "Inspection" ||+ !!operation.inspectionDocumentId,+ { message: "Inspection Plan is required", path: ["inspectionDocumentId"] }+];+export const standardFactorType = ["Hours/Piece","Hours/100 Pieces",@@ -465,6 +504,48 @@ export type SupplierPartPricing = {currency: CurrencyRate;};+export type NoteField = "internalNotes" | "externalNotes" | "notes";+type PublicTables = Database["public"]["Tables"];++/**+ * The notes fields a person edits in the app, per table: what `setNotes` may+ * set. Each one is a column of its table (checked below).+ */+export const noteFields = {+ salesRfq: ["internalNotes", "externalNotes"],+ salesRfqLine: ["internalNotes", "externalNotes"],+ quote: ["internalNotes", "externalNotes"],+ quoteLine: ["internalNotes", "externalNotes"],+ salesOrder: ["internalNotes", "externalNotes"],+ salesOrderLine: ["internalNotes", "externalNotes"],+ salesInvoice: ["internalNotes", "externalNotes"],+ salesInvoiceLine: ["internalNotes", "externalNotes"],+ purchasingRfq: ["internalNotes"],+ purchasingRfqLine: ["internalNotes", "externalNotes"],+ supplierQuote: ["internalNotes", "externalNotes"],+ supplierQuoteLine: ["internalNotes", "externalNotes"],+ purchaseOrder: ["internalNotes", "externalNotes"],+ purchaseOrderLine: ["internalNotes", "externalNotes"],+ purchaseInvoice: ["internalNotes"],+ purchaseInvoiceLine: ["internalNotes"],+ receipt: ["internalNotes"],+ shipment: ["internalNotes", "externalNotes"],+ job: ["notes"],+ item: ["notes"],+ fixedAsset: ["notes"],+ pickingList: ["notes"],+ stockTransfer: ["notes"]+} as const satisfies {+ readonly [T in keyof PublicTables]?: readonly (keyof PublicTables[T]["Row"] &+ NoteField)[];+};++export type NoteTable = keyof typeof noteFields;+export const noteTables = Object.keys(noteFields) as [+ NoteTable,+ ...NoteTable[]+];+/** The tables with an `assignee` column: what `assignRecord` may assign. */export const assignableTables = ["changeOrder",diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.tsindex d40128a8d7..520ebb244a 100644--- a/apps/erp/app/modules/shared/shared.server.ts+++ b/apps/erp/app/modules/shared/shared.server.ts@@ -58,7 +58,7 @@ import {importRequiresCreate,importSchemas} from "./imports.models";-import { assignableTables } from "./shared.models";+import { assignableTables, noteFields, noteTables } from "./shared.models";import * as service from "./shared.service";import { invokeCreate } from "./shared.service";@@ -150,6 +150,61 @@ export const assignRecord = defineServiceFn({}});+/**+ * Set a record's internal, external or general notes.+ *+ * @remarks+ * Replaces one notes field of the record of `table` with `id`, as the caller:+ * row-level security decides what they may change, and a row they cannot+ * change is `notFound`. The tables and fields are the notes a person edits in+ * the app: internal and external notes on sales and purchasing documents and+ * their lines, internal notes on purchase invoices and receipts, and notes on+ * jobs, items, fixed assets, picking lists and stock transfers.+ *+ * @param table - The record's table, e.g. `salesOrder` or `purchaseOrderLine`.+ * @param id - The record's id.+ * @param field - `internalNotes` or `externalNotes`, or `notes` on a job,+ * item, fixed asset, picking list or stock transfer.+ * @param text - The notes as Markdown: headings, **bold**, _italic_, lists,+ * links, quotes and code. Empty text clears them.+ *+ * @mcp+ */+export const setNotes = defineServiceFn({+ input: z.object({+ table: z.enum(noteTables),+ id: z.string().min(1),+ field: z.enum(["internalNotes", "externalNotes", "notes"]),+ text: z.string()+ }),+ permission: {},++ async run(ctx, { table, id, field, text }) {+ const fields: readonly string[] = noteFields[table];+ if (!fields.includes(field)) {+ return ctx.error(+ "validation",+ `${table} has no ${field}; it takes ${fields.join(" or ")}`+ );+ }+ const updated = await service.setRecordNotes(ctx.asCaller.supabase, {+ table,+ id,+ field,+ text,+ companyId: ctx.company.id,+ userId: ctx.auditUserId+ });+ if (updated.error) {+ return ctx.error("internal", "Failed to save the notes", updated.error);+ }+ if (!updated.data?.length) {+ return ctx.error("notFound", "No record was found to update");+ }+ return { id };+ }+});+type ImportTable = keyof typeof importPermissions;const importTables = Object.keys(importPermissions) as [diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 5a379c88e6..9b50984afc 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -113,6 +113,7 @@ import {storage} from "@carbon/files";import { parseCsv } from "@carbon/files/csv";+import { TiptapText } from "@carbon/files/markdown";import { trigger } from "@carbon/jobs";import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";@@ -139,8 +140,7 @@ import {resolveTrackedEntityBins,round,settleQuantity,- type TrackedEntityBin,- textToTiptap+ type TrackedEntityBin} from "@carbon/utils";import {type CalendarDate,@@ -185,7 +185,12 @@ import {setGenericQueryFilters} from "~/utils/query";import type { CustomFieldsTableType } from "../settings/types";-import type { assignableTables } from "./shared.models";+import type {+ assignableTables,+ NoteField,+ NoteTable,+ standardFactorType+} from "./shared.models";import { assertMethodHasPullFrom, isStrictBackflush } from "./strict-backflush";import type { ItemModelUpload } from "./types";@@ -816,16 +821,191 @@ export async function assign(}/**- * The stored work instruction for plain text. Empty text is `{}`, as the+ * Replaces one notes field of a record, as the caller: row-level security+ * decides what they may change. Markdown text becomes the editor's document;+ * empty text clears it to `{}`, as the editor does.+ */+export async function setRecordNotes(+ client: SupabaseClient<Database>,+ args: {+ table: NoteTable;+ id: string;+ field: NoteField;+ text: string;+ companyId: string;+ userId: string;+ }+) {+ const { table, id, field, text, companyId, userId } = args;+ // Every notes table has `id`, `companyId` and the audit columns; one stands+ // in for the union, and `noteFields` pins the field to a column of the table.+ return client+ .from(table as "job")+ .update({+ [field]: text.trim() ? TiptapText(text).toDocument() : {},+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ } as never)+ .eq("id", id)+ .eq("companyId", companyId)+ .select("id");+}++type StandardFactor = (typeof standardFactorType)[number];++type OperationStandards = {+ processId: string;+ workCenterId?: string;+ operationSupplierProcessId?: string;+ setupUnit?: StandardFactor;+ setupTime?: number;+ laborUnit?: StandardFactor;+ laborTime?: number;+ laborRate?: number;+ machineUnit?: StandardFactor;+ machineTime?: number;+ machineRate?: number;+ overheadRate?: number;+ operationMinimumCost?: number;+ operationUnitCost?: number;+ operationLeadTime?: number;+};++type FilledStandards = Required<+ Omit<+ OperationStandards,+ "processId" | "workCenterId" | "operationSupplierProcessId"+ >+>;++type WorkCenterStandards = {+ laborRate: number | null;+ machineRate: number | null;+ overheadRate: number | null;+ defaultStandardFactor: StandardFactor | null;+};++/**+ * What the bill of process form fills in for the fields a caller left out of+ * a new operation: units and rates from the chosen work center, else the+ * process's default standard factor and the average of its active work+ * centers; an outside operation's minimum cost and lead time from its+ * supplier process; times 0. A field the caller sent is kept as sent.+ */+export function fillOperationStandards<T extends OperationStandards>(+ operation: T,+ facts: {+ processStandardFactor: StandardFactor | null;+ workCenters: WorkCenterStandards[];+ supplierProcess: {+ minimumCost: number | null;+ leadTime: number | null;+ } | null;+ }+): T & FilledStandards {+ const { workCenters, supplierProcess } = facts;+ const average = (rate: "laborRate" | "machineRate" | "overheadRate") =>+ workCenters.length+ ? workCenters.reduce((sum, center) => sum + (center[rate] ?? 0), 0) /+ workCenters.length+ : 0;+ const unit =+ (operation.workCenterId ? workCenters[0]?.defaultStandardFactor : null) ??+ facts.processStandardFactor ??+ "Hours/Piece";++ return {+ ...operation,+ setupUnit: operation.setupUnit ?? "Total Minutes",+ setupTime: operation.setupTime ?? 0,+ laborUnit: operation.laborUnit ?? unit,+ laborTime: operation.laborTime ?? 0,+ laborRate: operation.laborRate ?? average("laborRate"),+ machineUnit: operation.machineUnit ?? unit,+ machineTime: operation.machineTime ?? 0,+ machineRate: operation.machineRate ?? average("machineRate"),+ overheadRate: operation.overheadRate ?? average("overheadRate"),+ operationMinimumCost:+ operation.operationMinimumCost ?? supplierProcess?.minimumCost ?? 0,+ operationUnitCost: operation.operationUnitCost ?? 0,+ operationLeadTime:+ operation.operationLeadTime ?? supplierProcess?.leadTime ?? 0+ };+}++/**+ * `fillOperationStandards` with the facts read: the process, the chosen work+ * center (or the process's active ones) and the supplier process, all of+ * this company.+ */+export async function withOperationStandards<T extends OperationStandards>(+ ctx: ServiceContext,+ operation: T+): Promise<(T & FilledStandards) | CarbonError> {+ const db = ctx.asSystem.supabase;+ const companyId = ctx.company.id;+ const [process, workCenters, supplierProcess] = await Promise.all([+ db+ .from("process")+ .select("defaultStandardFactor")+ .eq("id", operation.processId)+ .eq("companyId", companyId)+ .maybeSingle(),+ operation.workCenterId+ ? db+ .from("workCenter")+ .select("laborRate, machineRate, overheadRate, defaultStandardFactor")+ .eq("id", operation.workCenterId)+ .eq("companyId", companyId)+ : db+ .from("workCenterProcess")+ .select(+ "workCenter!inner(laborRate, machineRate, overheadRate, defaultStandardFactor)"+ )+ .eq("processId", operation.processId)+ .eq("companyId", companyId)+ .eq("workCenter.active", true),+ operation.operationSupplierProcessId+ ? db+ .from("supplierProcess")+ .select("minimumCost, leadTime")+ .eq("id", operation.operationSupplierProcessId)+ .eq("companyId", companyId)+ .maybeSingle()+ : null+ ]);+ const failed = process.error ?? workCenters.error ?? supplierProcess?.error;+ if (failed) {+ return ctx.error("internal", "Failed to read the process defaults", failed);+ }+ if (!process.data) return ctx.error("notFound", "Process not found");++ const centers = (workCenters.data ?? []).map((row) =>+ "workCenter" in row+ ? (row.workCenter as WorkCenterStandards)+ : (row as WorkCenterStandards)+ );+ if (operation.workCenterId && centers.length === 0) {+ return ctx.error("notFound", "Work center not found");+ }+ return fillOperationStandards(operation, {+ processStandardFactor: process.data.defaultStandardFactor,+ workCenters: centers,+ supplierProcess: supplierProcess?.data ?? null+ });+}++/**+ * The stored work instruction for Markdown text. Empty text is `{}`, as the* editor stores it: the column is NOT NULL, so `null` refused every clear.*/export function workInstructionFromText(text: string) {- return text.trim() ? textToTiptap(text) : {};+ return text.trim() ? TiptapText(text).toDocument() : {};}/**- * Replaces one operation's work instruction, as the caller. The text becomes- * the editor's document (`textToTiptap`); empty text clears it. An id the+ * Replaces one operation's work instruction, as the caller. The text is+ * Markdown, stored as the editor's document; empty text clears it. An id the* caller cannot see, or of another company, is `notFound`.*/export async function setOperationWorkInstruction(diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.tsindex 1aa286ab3f..74a33c54dc 100644--- a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts+++ b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts@@ -7,12 +7,11 @@ import {actionTaskPermissions,isActionTaskEntityType} from "@carbon/ee/action-task-entity";-import type { TiptapDocument } from "@carbon/ee/linear.server";import {getLinearClient,- getLinearIssueFromExternalId,- tiptapToMarkdown+ getLinearIssueFromExternalId} from "@carbon/ee/linear.server";+import { type JSONContent, TiptapText } from "@carbon/files/markdown";import { getLogger } from "@carbon/logger";import type { ActionFunction } from "react-router";import { data } from "react-router";@@ -68,7 +67,7 @@ export const action: ActionFunction = async ({ request }) => {}// Parse the notes JSON- let notes: TiptapDocument | null = null;+ let notes: JSONContent | null = null;try {notes = notesStr ? JSON.parse(notesStr) : null;} catch {@@ -93,7 +92,7 @@ export const action: ActionFunction = async ({ request }) => {try {// Convert Tiptap notes to markdown for Linear- const description = tiptapToMarkdown(notes);+ const description = TiptapText(notes).toMarkdown();await linear.updateIssue(companyId, {id: issue.id,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.jsonindex 9a002b5d39..c5a1d90ee2 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@@ -1,5 +1,5 @@{- "totalTools": 1616,+ "totalTools": 1617,"modules": 14,"tools": [{"name":"accounting_closePeriod","classification":"WRITE","schema":"7e5905ac5974","response":"7e5905ac5974","permission":"accounting:update","paginates":false},@@ -548,7 +548,7 @@{"name":"items_setMaterialProperties","classification":"WRITE","schema":"b768c3d49572","response":"94b3f717a27e","permission":"parts:update","paginates":false},{"name":"items_setMethodMaterialStepLink","classification":"DESTRUCTIVE","schema":"17d57d014843","response":"bcde375ebd4c","permission":"parts:update","paginates":false},{"name":"items_setMethodOperationToolStepLink","classification":"DESTRUCTIVE","schema":"0205115c2a9c","response":"bcde375ebd4c","permission":"parts:update","paginates":false},- {"name":"items_setMethodOperationWorkInstruction","classification":"WRITE","schema":"cd227d437f44","response":"3797626bd17e","permission":"parts:update","paginates":false},+ {"name":"items_setMethodOperationWorkInstruction","classification":"WRITE","schema":"72bf0481bc32","response":"3797626bd17e","permission":"parts:update","paginates":false},{"name":"items_updateChangeNotice","classification":"WRITE","schema":"bc0a8bcfbdb8","response":"3797626bd17e","permission":"parts:update","paginates":false},{"name":"items_updateChangeNoticeActionOrder","classification":"WRITE","schema":"582d2c771eaa","response":"none","permission":"parts:update","paginates":false},{"name":"items_updateChangeNoticeActionStatus","classification":"WRITE","schema":"7f9d94960d15","response":"3797626bd17e","permission":"parts:update","paginates":false},@@ -836,7 +836,7 @@{"name":"production_setJobOperationDueDate","classification":"WRITE","schema":"e04478fc58f7","response":"3797626bd17e","permission":"production:update","paginates":false},{"name":"production_setJobOperationStatus","classification":"WRITE","schema":"c7c4e9005478","response":"a443ac9aa1f1","permission":"production:update","paginates":false},{"name":"production_setJobOperationToolStepLink","classification":"DESTRUCTIVE","schema":"b48f94032fe6","response":"bcde375ebd4c","permission":"production:update","paginates":false},- {"name":"production_setJobOperationWorkInstruction","classification":"WRITE","schema":"1bede8f4a4f5","response":"3797626bd17e","permission":"production:update","paginates":false},+ {"name":"production_setJobOperationWorkInstruction","classification":"WRITE","schema":"5c977b058996","response":"3797626bd17e","permission":"production:update","paginates":false},{"name":"production_setJobQuantity","classification":"WRITE","schema":"14db87743cc7","response":"0eb0c2be01ed","permission":"production:update","paginates":false},{"name":"production_setJobSalesOrderLine","classification":"WRITE","schema":"9b91d34f8382","response":"0eb0c2be01ed","permission":"production:update","paginates":false},{"name":"production_setPeopleOvertime","classification":"WRITE","schema":"89851b04ba54","response":"393a0d83325c","permission":"production:update","paginates":false},@@ -1272,7 +1272,7 @@{"name":"sales_copyItemMethodToQuoteMaterial","classification":"WRITE","schema":"c9fd44bf9a70","response":"bfcaa45eb18e","permission":"sales:update","paginates":false},{"name":"sales_copyQuote","classification":"WRITE","schema":"06f2835dfed0","response":"4e1a8f1febce","permission":"sales:create","paginates":false},{"name":"sales_copyQuoteLineMethod","classification":"WRITE","schema":"e2d617e47e0a","response":"e0050938a2c8","permission":"sales:update","paginates":false},- {"name":"sales_createContract","classification":"WRITE","schema":"249368eaeb19","response":"3797626bd17e","permission":"sales:create","paginates":false},+ {"name":"sales_createContract","classification":"WRITE","schema":"c48868d74277","response":"3797626bd17e","permission":"sales:create","paginates":false},{"name":"sales_createContractLine","classification":"WRITE","schema":"e2eb6d46f182","response":"3797626bd17e","permission":"sales:create","paginates":false},{"name":"sales_createCustomer","classification":"WRITE","schema":"1169094678e4","response":"3797626bd17e","permission":"sales:create","paginates":false},{"name":"sales_createCustomerBankAccount","classification":"WRITE","schema":"c5394895361c","response":"3797626bd17e","permission":"accounting:create","paginates":false},@@ -1296,8 +1296,8 @@{"name":"sales_createReturnReason","classification":"WRITE","schema":"5607534c1255","response":"3797626bd17e","permission":"sales:create","paginates":false},{"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"91896427de3a","response":"8f061af39e95","permission":"sales:create","paginates":false},{"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","schema":"a752775acc57","response":"00404e686415","permission":"invoicing:create","paginates":false},- {"name":"sales_createSalesRfq","classification":"WRITE","schema":"ef914612528f","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},- {"name":"sales_createSalesRFQ","classification":"WRITE","schema":"782bcc5a7778","response":"2e56e1180d37","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRfq","classification":"WRITE","schema":"38323ad62e6d","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},+ {"name":"sales_createSalesRFQ","classification":"WRITE","schema":"bd0f125f410c","response":"2e56e1180d37","permission":"sales:create","paginates":false},{"name":"sales_createSalesRFQLine","classification":"WRITE","schema":"c5b3b3cfaa0d","response":"3797626bd17e","permission":"sales:create","paginates":false},{"name":"sales_deleteCustomer","classification":"DESTRUCTIVE","schema":"9671bf9bdd53","response":"bcde375ebd4c","permission":"sales:delete","paginates":false},{"name":"sales_deleteCustomerBankAccount","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"accounting:delete","paginates":false},@@ -1451,7 +1451,7 @@{"name":"sales_setContractInvoiceAutomation","classification":"WRITE","schema":"321dd5c5e689","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_setContractTerm","classification":"WRITE","schema":"3db861398453","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_setContractType","classification":"WRITE","schema":"4899de777529","response":"3797626bd17e","permission":"sales:update","paginates":false},- {"name":"sales_setQuoteOperationWorkInstruction","classification":"WRITE","schema":"85f02e862122","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_setQuoteOperationWorkInstruction","classification":"WRITE","schema":"104e54c8a620","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_setQuoteStatus","classification":"WRITE","schema":"1ea4822e0e18","response":"1ea4822e0e18","permission":"sales:update","paginates":false},{"name":"sales_setRentalAgreementStatus","classification":"WRITE","schema":"18addd891e4a","response":"18addd891e4a","permission":"sales:update","paginates":false},{"name":"sales_setRentalAgreementTerm","classification":"WRITE","schema":"2aff228d5443","response":"3797626bd17e","permission":"sales:update","paginates":false},@@ -1462,7 +1462,7 @@{"name":"sales_shipSalesOrderLine","classification":"WRITE","schema":"58e3c9762923","response":"2e39a760a5ca","permission":"inventory:create","paginates":false},{"name":"sales_shortCloseSalesReturnOrderLine","classification":"WRITE","schema":"b212fe8e50fb","response":"none","permission":"sales:update","paginates":false},{"name":"sales_updateContractLine","classification":"WRITE","schema":"c6d281a5793a","response":"3797626bd17e","permission":"sales:update","paginates":false},- {"name":"sales_updateContractTerms","classification":"WRITE","schema":"7cdb0bcfea29","response":"3797626bd17e","permission":"sales:update","paginates":false},+ {"name":"sales_updateContractTerms","classification":"WRITE","schema":"d84bebf9a949","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_updateCustomer","classification":"WRITE","schema":"6d8f73c8814f","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_updateCustomerBankAccount","classification":"WRITE","schema":"8bd701af67a3","response":"3797626bd17e","permission":"accounting:update","paginates":false},{"name":"sales_updateCustomerContact","classification":"WRITE","schema":"713c7de4f8a2","response":"3797626bd17e","permission":"sales:update","paginates":false},@@ -1474,7 +1474,7 @@{"name":"sales_updateCustomerType","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"sales:update","paginates":false},{"name":"sales_updateNoQuoteReason","classification":"WRITE","schema":"afedffe2be69","response":"8394fbabd845","permission":"sales:update","paginates":false},{"name":"sales_updatePricingRule","classification":"WRITE","schema":"a558835d70d7","response":"3797626bd17e","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteDetails","classification":"WRITE","schema":"97e47673eb0b","response":"c726ae407913","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteDetails","classification":"WRITE","schema":"a3980b202b22","response":"c726ae407913","permission":"sales:update","paginates":false},{"name":"sales_updateQuoteExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},{"name":"sales_updateQuoteLine","classification":"WRITE","schema":"29659b4ffe67","response":"8529f8fc63c9","permission":"sales:create","paginates":false},{"name":"sales_updateQuoteLineOrder","classification":"WRITE","schema":"323824b4392c","response":"none","permission":"sales:update","paginates":false},@@ -1494,7 +1494,7 @@{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},{"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"1f7aae174849","response":"8f061af39e95","permission":"sales:create","paginates":false},{"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","schema":"bc4baf1732ad","response":"none","permission":"sales:update","paginates":false},- {"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"00ea9309a858","response":"2e56e1180d37","permission":"sales:update","paginates":false},+ {"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"2cb421dde994","response":"2e56e1180d37","permission":"sales:update","paginates":false},{"name":"sales_updateSalesRFQLine","classification":"WRITE","schema":"827ecf864e53","response":"3797626bd17e","permission":"sales:update","paginates":false},{"name":"sales_updateSalesRFQLineOrder","classification":"WRITE","schema":"fa6fee3c7515","response":"none","permission":"sales:update","paginates":false},{"name":"sales_upsertCustomerItemPriceOverride","classification":"DESTRUCTIVE","schema":"c74a2a58d6cf","response":"3797626bd17e","permission":"sales:create+update","paginates":false},@@ -1585,6 +1585,7 @@{"name":"shared_getTagsList","classification":"READ","schema":"af4eca956117","response":"b837740e18f4","permission":"none","paginates":false},{"name":"shared_insertNote","classification":"WRITE","schema":"6b735d93fae1","response":"c2fb0e5225f8","permission":"none","paginates":false},{"name":"shared_insertTag","classification":"WRITE","schema":"9fd690c21fa5","response":"27f67ae1958c","permission":"none","paginates":false},+ {"name":"shared_setNotes","classification":"WRITE","schema":"f39827fefbe7","response":"3797626bd17e","permission":"none","paginates":false},{"name":"shared_updateSavedViewOrder","classification":"WRITE","schema":"33fd534d3ffe","response":"393a0d83325c","permission":"none","paginates":false},{"name":"shared_upsertSavedView","classification":"WRITE","schema":"0bfaff189d21","response":"3797626bd17e","permission":"none","paginates":false},{"name":"users_deleteGroup","classification":"DESTRUCTIVE","schema":"6624f3863074","response":"bcde375ebd4c","permission":"users:delete","paginates":false},diff --git a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsxindex 4f9e1bed3d..1dbf098a38 100644--- a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx+++ b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx@@ -4,323 +4,25 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import type { JobTravelerMaterial } from "@carbon/documents/pdf";-import {- ensureFont,- Footer,- getSafeFontFamily,- JobTravelerPageContent-} from "@carbon/documents/pdf";-import {- collectSectionIds,- interpolateContent,- resolveTemplate,- toDocumentTemplate-} from "@carbon/documents/template";-import { getLogger } from "@carbon/logger";-import type { JSONContent } from "@carbon/react";-import {- flattenTree,- generateBomIds,- getPreferenceHeaders-} from "@carbon/utils";-import {- Document,- Page,- renderToStream,- StyleSheet-} from "@react-pdf/renderer";+import { getPreferenceHeaders } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";-import {- getJob,- getJobOperationsByMethodId,- getTrackedEntityByJobId-} from "~/modules/production/production.service";-import { getJobMethodTree } from "~/modules/production/production.utils";-import {- getCompany,- getCompanySettings,- getDocumentTemplate,- resolveSections-} from "~/modules/settings/settings.service";-import { getBase64ImageFromSupabase } from "~/modules/shared/shared.service";--const logger = getLogger("erp", "job-traveler", "pdf");+import { renderJobTravelerPdf } from "~/modules/production/production.pdf";export async function loader({ request, params }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {});- const { locale } = getPreferenceHeaders(request);-const { jobId } = params;if (!jobId) throw new Error("Could not find job id");- const serviceRole = await getCarbonServiceRole();-- // Get the job first- const job = await getJob(serviceRole, jobId);- if (job.error || !job.data) {- logger.error("Failed to load job", { error: job.error });- throw new Error("Failed to load job");- }-- // Verify job belongs to this company before anything else is read with the- // service role (every query below is keyed off this job).- if (job.data.companyId !== companyId) {- logger.error("Job does not belong to this company", { companyId, jobId });- throw new Response("Not found", { status: 404 });- }-- // Get all make methods for this job- const jobMakeMethods = await serviceRole- .from("jobMakeMethod")- .select("*, ...item(itemType:type)")- .eq("jobId", jobId)- .order("createdAt", { ascending: true });-- if (jobMakeMethods.error || !jobMakeMethods.data) {- logger.error("Failed to load jobMakeMethods", {- error: jobMakeMethods.error- });- throw new Error("Failed to load job make methods");- }-- const company = await getCompany(serviceRole, job.data.companyId ?? "");- if (company.error) {- logger.error("Failed to load company", { error: company.error });- throw new Error("Failed to load company");- }-- // Opt-in company setting: render a materials (BOM) section on the traveler.- const companySettings = await getCompanySettings(serviceRole, companyId);- if (companySettings.error) {- logger.error("Failed to load company settings", {- error: companySettings.error- });- throw new Error("Failed to load company settings");- }- const includeMaterials =- (- companySettings.data as {- includeMaterialsOnTraveler?: boolean | null;- } | null- )?.includeMaterialsOnTraveler ?? false;-- // Opt-out company setting (defaults on): render the operations (routing +- // scan barcodes) section on the traveler.- const includeOperations =- (- companySettings.data as {- includeOperationsOnTraveler?: boolean | null;- } | null- )?.includeOperationsOnTraveler ?? true;-- const customer = await serviceRole- .from("customer")- .select("*")- .eq("id", job.data.customerId ?? "")- .maybeSingle();-- // Get job notes if they exist- const jobNotes = job.data.notes as JSONContent | undefined;-- // Compute BOM IDs for all make methods- const bomIdMap = new Map<string, string>();- const methodTree = await getJobMethodTree(serviceRole, jobId);- if (!methodTree.error && methodTree.data?.length > 0) {- const flatMethods = flattenTree(methodTree.data[0]);- const bomIds = generateBomIds(flatMethods);- flatMethods.forEach((node, index) => {- bomIdMap.set(node.data.jobMaterialMakeMethodId, bomIds[index]);- });- }-- // For each make method, get operations and item data- const makeMethodsWithData = await Promise.all(- jobMakeMethods.data.map(async (makeMethod) => {- const [operations, item] = await Promise.all([- getJobOperationsByMethodId(serviceRole, makeMethod.id),- serviceRole- .from("item")- .select("*, modelUpload(thumbnailPath)")- .eq("id", makeMethod.itemId ?? "")- .single()- ]);-- if (operations.error || !operations.data) {- logger.error("Failed to load operations", { error: operations.error });- throw new Error(- `Failed to load operations for make method ${makeMethod.id}`- );- }-- if (item.error || !item.data) {- logger.error("Failed to load item", { error: item.error });- throw new Error(`Failed to load item for make method ${makeMethod.id}`);- }-- // Get thumbnail if it exists- let thumbnail: string | null = null;- if (item.data.thumbnailPath || item.data.modelUpload?.thumbnailPath) {- thumbnail = await getBase64ImageFromSupabase(- serviceRole,- item.data.thumbnailPath ?? item.data.modelUpload?.thumbnailPath ?? ""- );- }-- // Get batch number if item is tracked- let batchNumber: string | undefined;- if (- ["Batch", "Serial"].includes(item.data.itemTrackingType) &&- makeMethod.parentMaterialId === null- ) {- const trackedEntity = await getTrackedEntityByJobId(- serviceRole,- job.data!.id!- );- if (!trackedEntity.error && trackedEntity.data) {- batchNumber = trackedEntity.data.readableId ?? undefined;- }- }-- // Only load BOM lines when the company has opted into the materials- // section — otherwise this query is wasted work.- let materials: JobTravelerMaterial[] = [];- if (includeMaterials) {- const jobMaterials = await serviceRole- .from("jobMaterial")- .select(- "id, description, quantity, unitOfMeasureCode, methodType, item(readableIdWithRevision)"- )- .eq("jobMakeMethodId", makeMethod.id)- .eq("companyId", companyId)- .order("order", { ascending: true });-- if (jobMaterials.error) {- logger.error("Failed to load job materials", {- error: jobMaterials.error- });- throw new Error(- `Failed to load materials for make method ${makeMethod.id}`- );- }-- materials = (jobMaterials.data ?? []).map((material) => ({- id: material.id,- itemReadableId: material.item?.readableIdWithRevision,- description: material.description,- quantity: material.quantity,- unitOfMeasureCode: material.unitOfMeasureCode,- methodType: material.methodType- }));- }-- return {- makeMethod,- operations: operations.data,- item: item.data,- thumbnail,- batchNumber,- materials,- bomId: bomIdMap.get(makeMethod.id)- };- })- );-- // Resolve the customizable template (block order / visibility / font /- // footer) and the shared header/footer sections.- const documentTemplate = await getDocumentTemplate(- serviceRole,- companyId,- "jobTraveler"- );- const templateConfig = toDocumentTemplate(- documentTemplate.data,- "jobTraveler"- );- const resolved = resolveTemplate("jobTraveler", templateConfig);- const sections = await resolveSections(- serviceRole,- companyId,- collectSectionIds(resolved)+ const { body, fileName } = await renderJobTravelerPdf(+ await getCarbonServiceRole(),+ { companyId, jobId, locale: getPreferenceHeaders(request).locale });- await ensureFont(resolved.settings.fontFamily);- const footerSectionContent = resolved.footerSectionId- ? sections[resolved.footerSectionId]?.content- : undefined;- const footerContent = footerSectionContent- ? interpolateContent(footerSectionContent, {- "job.number": job.data.jobId ?? "",- "company.name": company.data.name ?? ""- })- : undefined;- const showFooter = resolved.footerSectionId !== null;-- const styles = StyleSheet.create({- body: {- fontFamily: getSafeFontFamily(resolved.settings.fontFamily),- padding: "20px 40px 50px 40px",- color: "#000000",- backgroundColor: "#FFFFFF"- }- });-- // Render multiple pages - one per make method- const stream = await renderToStream(- <Document- title="Job Traveler"- author="Carbon"- subject="Job Traveler"- keywords="job traveler, manufacturing"- >- {makeMethodsWithData.map((data, index) => (- <Page key={data.makeMethod.id} size="A4" style={styles.body}>- <JobTravelerPageContent- company={company.data as any}- job={job.data}- jobOperations={data.operations}- customer={customer.data}- item={data.item}- batchNumber={data.batchNumber}- bomId={data.bomId}- locale={locale}- notes={index === 0 ? jobNotes : undefined}- thumbnail={data.thumbnail}- includeMaterials={includeMaterials}- includeOperations={includeOperations}- materials={data.materials}- methodRevision={data.makeMethod.version?.toString()}- template={templateConfig}- sections={sections}- />- {showFooter && (- <Footer- documentId={job.data.jobId}- content={footerContent}- showPageNumbers={resolved.settings.showPageNumbers}- pageNumberFormat={resolved.settings.pageNumberFormat}- showRegistrationLine={resolved.settings.showRegistrationLine}- />- )}- </Page>- ))}- </Document>- );-- const body: Buffer = await new Promise((resolve, reject) => {- const buffers: Uint8Array[] = [];- stream.on("data", (data) => {- buffers.push(data);- });- stream.on("end", () => {- resolve(Buffer.concat(buffers));- });- stream.on("error", reject);- });-- const headers = new Headers({- "Content-Type": "application/pdf",- "Content-Disposition": `inline; filename="${company.data.name} - ${job.data.jobId}.pdf"`+ return new Response(new Uint8Array(body), {+ status: 200,+ headers: new Headers({+ "Content-Type": "application/pdf",+ "Content-Disposition": `inline; filename="${fileName}"`+ })});- return new Response(new Uint8Array(body), { status: 200, headers });}diff --git a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsxindex a4927497f1..766b3835f4 100644--- a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx@@ -4,181 +4,43 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { JobTravelerPDF } from "@carbon/documents/pdf";import { getLogger } from "@carbon/logger";-import type { JSONContent } from "@carbon/react";-import {- flattenTree,- generateBomIds,- getPreferenceHeaders-} from "@carbon/utils";-import { renderToStream } from "@react-pdf/renderer";+import { getPreferenceHeaders } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";-import {- getJob,- getJobMakeMethodById,- getJobOperationsByMethodId,- getTrackedEntityByJobId-} from "~/modules/production/production.service";-import { getJobMethodTree } from "~/modules/production/production.utils";-import {- getCompany,- getCompanySettings-} from "~/modules/settings/settings.service";-import { getBase64ImageFromSupabase } from "~/modules/shared/shared.service";+import { renderJobTravelerPdf } from "~/modules/production/production.pdf";+import { getJobMakeMethodById } from "~/modules/production/production.service";const logger = getLogger("erp", "traveler", "pdf");+/** One make method's page of the job traveler (the MES operation link). */export async function loader({ request, params }: LoaderFunctionArgs) {const { companyId } = await requirePermissions(request, {});-const { id } = params;if (!id) throw new Error("Could not find job make method id");const serviceRole = await getCarbonServiceRole();-- // we add the companyId to make sure we belong to the company- // while allowing guys on the shop floor with no permissions to download the traveler+ // Scoped by companyId, so a make method of another company is not found,+ // while operators with no permissions can still download the traveler.const jobMakeMethod = await getJobMakeMethodById(serviceRole, id, companyId);- if (jobMakeMethod.error) {+ if (jobMakeMethod.error || !jobMakeMethod.data?.jobId) {logger.error("Failed to load jobMakeMethod", {error: jobMakeMethod.error});throw new Error("Failed to load job make method");}- const [company, companySettings, job] = await Promise.all([- getCompany(serviceRole, jobMakeMethod.data?.companyId ?? ""),- getCompanySettings(serviceRole, companyId),- getJob(serviceRole, jobMakeMethod.data?.jobId ?? "")- ]);-- if (company.error) {- logger.error("Failed to load company", { error: company.error });- throw new Error("Failed to load company");- }-- // Opt-out company setting (defaults on): render the operations section on the- // traveler. Mirrors the job traveler route.- const includeOperations =- (- companySettings.data as {- includeOperationsOnTraveler?: boolean | null;- } | null- )?.includeOperationsOnTraveler ?? true;-- if (job.error || !job.data) {- logger.error("Failed to load job", { error: job.error });- throw new Error("Failed to load job");- }-- const [jobOperations, customer, item] = await Promise.all([- getJobOperationsByMethodId(serviceRole, id),- serviceRole- .from("customer")- .select("*")- .eq("id", job.data.customerId ?? "")- .maybeSingle(),- serviceRole- .from("item")- .select("*, modelUpload(thumbnailPath)")- .eq("id", jobMakeMethod.data.itemId ?? "")- .single()- ]);-- if (jobOperations.error || !jobOperations.data) {- logger.error("Failed to load jobOperations", {- error: jobOperations.error- });- throw new Error("Failed to load job operations");- }-- if (item.error || !item.data) {- logger.error("Failed to load item", { error: item.error });- throw new Error("Failed to load item");- }-- let batchNumber: string | undefined;- if (["Batch", "Serial"].includes(item.data.itemTrackingType)) {- const trackedEntity = await getTrackedEntityByJobId(- serviceRole,- job.data.id!- );- if (trackedEntity.error) {- logger.error("Failed to load trackedEntity", {- error: trackedEntity.error- });- throw new Error("Failed to load tracked entity");- }- batchNumber = trackedEntity.data?.readableId ?? undefined;- }-- // Get job notes if they exist- const jobNotes = job.data.notes as JSONContent | undefined;-- // Compute BOM ID for this make method- let bomId: string | undefined;- const methodTree = await getJobMethodTree(serviceRole, job.data.id!);- if (!methodTree.error && methodTree.data?.length > 0) {- const flatMethods = flattenTree(methodTree.data[0]);- const bomIds = generateBomIds(flatMethods);- // Find the node matching this make method- const nodeIndex = flatMethods.findIndex(- (node) => node.data.jobMaterialMakeMethodId === id- );- if (nodeIndex >= 0) {- bomId = bomIds[nodeIndex];- }- }-- // Get thumbnail if it exists- let thumbnail: string | null = null;- if (item.data.thumbnailPath || item.data.modelUpload?.thumbnailPath) {- thumbnail = await getBase64ImageFromSupabase(- serviceRole,- item.data.thumbnailPath ?? item.data.modelUpload?.thumbnailPath ?? ""- );- }-- const { locale } = getPreferenceHeaders(request);-- const stream = await renderToStream(- <JobTravelerPDF- company={company.data as any}- job={job.data}- jobMakeMethod={jobMakeMethod.data}- jobOperations={jobOperations.data}- customer={customer.data}- item={item.data}- batchNumber={batchNumber}- bomId={bomId}- locale={locale}- meta={{- author: "Carbon",- keywords: "job traveler, manufacturing",- subject: "Job Traveler"- }}- notes={jobNotes}- thumbnail={thumbnail}- includeOperations={includeOperations}- title="Job Traveler"- />- );-- const body: Buffer = await new Promise((resolve, reject) => {- const buffers: Uint8Array[] = [];- stream.on("data", (data) => {- buffers.push(data);- });- stream.on("end", () => {- resolve(Buffer.concat(buffers));- });- stream.on("error", reject);+ const { body, fileName } = await renderJobTravelerPdf(serviceRole, {+ companyId,+ jobId: jobMakeMethod.data.jobId,+ jobMakeMethodId: id,+ locale: getPreferenceHeaders(request).locale});- const headers = new Headers({- "Content-Type": "application/pdf",- "Content-Disposition": `inline; filename="${company.data.name} - ${job.data.jobId}.pdf"`+ return new Response(new Uint8Array(body), {+ status: 200,+ headers: new Headers({+ "Content-Type": "application/pdf",+ "Content-Disposition": `inline; filename="${fileName}"`+ })});- return new Response(new Uint8Array(body), { status: 200, headers });}diff --git a/apps/erp/app/routes/x+/contract+/$id.setup.details.tsx b/apps/erp/app/routes/x+/contract+/$id.setup.details.tsxindex 7b44b7bd6c..ebb088c529 100644--- a/apps/erp/app/routes/x+/contract+/$id.setup.details.tsx+++ b/apps/erp/app/routes/x+/contract+/$id.setup.details.tsx@@ -3,8 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { carbon, respond } from "@carbon/api/carbon.server";+import { TiptapText } from "@carbon/files/markdown";import { validator } from "@carbon/form";-import { redirect, round, tiptapToText } from "@carbon/utils";+import { redirect, round } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { useParams } from "react-router";import { useRouteData } from "~/hooks";@@ -90,10 +91,7 @@ export default function ContractSetupDetailsRoute() {invoiceAutomation: contract.invoiceAutomation ?? undefined,paymentTermId: contract.paymentTermId ?? undefined,currencyCode: contract.currencyCode,- notes:- tiptapToText(- (contract.notes ?? null) as Parameters<typeof tiptapToText>[0]- ) || undefined,+ notes: TiptapText(contract.notes).toString() || undefined,...getCustomFields(contract.customFields)}}/>diff --git a/apps/erp/test/operation-api-input.test.ts b/apps/erp/test/operation-api-input.test.tsnew file mode 100644index 0000000000..be9f24ae33--- /dev/null+++ b/apps/erp/test/operation-api-input.test.ts@@ -0,0 +1,155 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// Only so the server modules load in a test process.+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })+}));+vi.mock("@carbon/env", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@carbon/env")>()),+ ASSEMBLER_SERVICE_URL: ""+}));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ error: vi.fn(), warn: vi.fn(), info: vi.fn() })+}));+vi.mock("@carbon/jobs", () => ({ trigger: vi.fn(), batchTrigger: vi.fn() }));+vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));++const { createJobOperation, updateJobOperation } = await import(+ "../app/modules/production/production.server"+);+const { createQuoteOperation, updateQuoteOperation } = await import(+ "../app/modules/sales/sales.server"+);+const { fillOperationStandards } = await import(+ "../app/modules/shared/shared.service"+);++// Only the fields the published schema marks required. The API refused this+// with "Setup unit is required" and eight more, for fields it lists as+// optional: the bill of process form's checks came along with its validator.+const operation = {+ id: "op1",+ order: 1,+ operationOrder: "After Previous",+ operationType: "Process",+ processId: "proc1",+ description: "Weld"+};+const jobOperation = { ...operation, jobId: "job1", jobMakeMethodId: "jmm1" };+const quoteOperation = {+ ...operation,+ quoteId: "q1",+ quoteLineId: "ql1",+ quoteMakeMethodId: "qmm1"+};++describe("operation API input", () => {+ it.each([+ ["createJobOperation", createJobOperation, jobOperation],+ ["updateJobOperation", updateJobOperation, jobOperation],+ ["createQuoteOperation", createQuoteOperation, quoteOperation],+ ["updateQuoteOperation", updateQuoteOperation, quoteOperation]+ ])("%s takes an operation without times, units or rates", (_, fn, input) => {+ expect(fn.input.safeParse(input).success).toBe(true);+ });++ it.each([+ ["createJobOperation", createJobOperation, jobOperation],+ ["createQuoteOperation", createQuoteOperation, quoteOperation]+ ])("%s still needs an inspection plan", (_, fn, input) => {+ const parsed = fn.input.safeParse({ ...input, operationType: "Inspection" });+ expect(parsed.success).toBe(false);+ expect(parsed.error?.issues[0]?.path).toEqual(["inspectionDocumentId"]);+ });+});++describe("fillOperationStandards", () => {+ const centers = [+ {+ laborRate: 40,+ machineRate: 100,+ overheadRate: 10,+ defaultStandardFactor: "Minutes/Piece" as const+ },+ {+ laborRate: 60,+ machineRate: 200,+ overheadRate: 20,+ defaultStandardFactor: "Hours/Piece" as const+ }+ ];++ it("averages the process's work centers and takes the process's unit", () => {+ const filled = fillOperationStandards(+ { processId: "proc1" },+ {+ processStandardFactor: "Pieces/Hour",+ workCenters: centers,+ supplierProcess: null+ }+ );+ expect(filled).toMatchObject({+ setupUnit: "Total Minutes",+ setupTime: 0,+ laborUnit: "Pieces/Hour",+ machineUnit: "Pieces/Hour",+ laborTime: 0,+ machineTime: 0,+ laborRate: 50,+ machineRate: 150,+ overheadRate: 15+ });+ });++ it("takes the chosen work center's rates and unit", () => {+ const filled = fillOperationStandards(+ { processId: "proc1", workCenterId: "wc1" },+ {+ processStandardFactor: "Pieces/Hour",+ workCenters: [centers[0]!],+ supplierProcess: null+ }+ );+ expect(filled).toMatchObject({+ laborUnit: "Minutes/Piece",+ laborRate: 40,+ machineRate: 100,+ overheadRate: 10+ });+ });++ it("keeps what the caller sent, 0 included", () => {+ const filled = fillOperationStandards(+ { processId: "proc1", laborRate: 0, laborUnit: "Total Hours" },+ {+ processStandardFactor: null,+ workCenters: centers,+ supplierProcess: null+ }+ );+ expect(filled.laborRate).toBe(0);+ expect(filled.laborUnit).toBe("Total Hours");+ expect(filled.machineUnit).toBe("Hours/Piece");+ });++ it("takes an outside operation's costs from its supplier process", () => {+ const filled = fillOperationStandards(+ { processId: "proc1", operationSupplierProcessId: "sp1" },+ {+ processStandardFactor: null,+ workCenters: [],+ supplierProcess: { minimumCost: 75, leadTime: 5 }+ }+ );+ expect(filled).toMatchObject({+ operationMinimumCost: 75,+ operationLeadTime: 5,+ operationUnitCost: 0,+ laborRate: 0+ });+ });+});diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsxindex a823e0695f..8734f1145b 100644--- a/apps/mes/app/components/JobOperation/components/Step.tsx+++ b/apps/mes/app/components/JobOperation/components/Step.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { storage } from "@carbon/files";+import { TiptapText } from "@carbon/files/markdown";import {Combobox,DateTimePicker,@@ -42,8 +43,7 @@ import {import {documentHasImages,parseMentionsFromDocument,- stripSpecialCharacters,- tiptapToText+ stripSpecialCharacters} from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";@@ -89,7 +89,7 @@ export function hasStepDescription(): boolean {if (!description) return false;const doc = description as JSONContent;- const text = tiptapToText(doc).trim();+ const text = TiptapText(doc).toString().trim();if (text.length > 0 && text !== "{}") return true;if (parseMentionsFromDocument(doc).length > 0) return true;// A step's reference imagery is frequently an image-only description (no text,diff --git a/packages/documents/src/pdf/JobTravelerPDF.test.ts b/packages/documents/src/pdf/JobTravelerPDF.test.tsnew file mode 100644index 0000000000..d601b9de0e--- /dev/null+++ b/packages/documents/src/pdf/JobTravelerPDF.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ReactElement, ReactNode } from "react";+import { Children, isValidElement } from "react";+import { describe, expect, it } from "vitest";+import { getDefaultTemplate } from "../template";+import { JobTravelerPageContent } from "./JobTravelerPDF";+import { SAMPLE_JOB_TRAVELER } from "./jobTraveler.samples";++type Block = { type: string; showWorkInstructions?: boolean };++// The page renders one Fragment per visible block, each wrapping the element+// its registry entry returned; the operations entry passes `block` through.+function operationsBlock(template: unknown): Block | undefined {+ const page = (JobTravelerPageContent as (p: never) => ReactElement)({+ ...SAMPLE_JOB_TRAVELER,+ template+ } as never);+ const found: Block[] = [];+ const walk = (node: ReactNode) =>+ Children.forEach(node, (child) => {+ if (!isValidElement(child)) return;+ const props = child.props as { block?: Block; children?: ReactNode };+ if (props.block?.type === "operations") found.push(props.block);+ walk(props.children);+ });+ walk((page.props as { children?: ReactNode }).children);+ return found[0];+}++// The MES traveler link once rendered without the company's template, so the+// default (instructions off) won over "Show work instructions".+describe("Job Traveler work instructions", () => {+ it("follow the template's operations block", () => {+ const template = getDefaultTemplate("jobTraveler");+ const withInstructions = {+ ...template,+ blocks: template.blocks.map((block) =>+ block.type === "operations"+ ? { ...block, showWorkInstructions: true }+ : block+ )+ };+ expect(operationsBlock(withInstructions)?.showWorkInstructions).toBe(true);+ });++ it("are off without a template", () => {+ expect(operationsBlock(null)?.showWorkInstructions).toBe(false);+ });+});diff --git a/packages/ee/src/linear/lib/index.server.ts b/packages/ee/src/linear/lib/index.server.tsindex 77d1824ff5..3042937e1b 100644--- a/packages/ee/src/linear/lib/index.server.ts+++ b/packages/ee/src/linear/lib/index.server.ts@@ -3,7 +3,6 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.export * from "./client";-export * from "./richtext";export * from "./service";export * from "./types";export * from "./utils";diff --git a/packages/ee/src/linear/lib/index.ts b/packages/ee/src/linear/lib/index.tsindex 2494a420cc..2565f76082 100644--- a/packages/ee/src/linear/lib/index.ts+++ b/packages/ee/src/linear/lib/index.ts@@ -2,6 +2,5 @@// Carbon Enterprise file, licensed only under the Carbon Commercial License// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.-export * from "./richtext";export * from "./types";export * from "./utils";diff --git a/packages/ee/src/linear/lib/richtext.ts b/packages/ee/src/linear/lib/richtext.tsdeleted file mode 100644index 5c219402ae..0000000000--- a/packages/ee/src/linear/lib/richtext.ts+++ /dev/null@@ -1,392 +0,0 @@-// SPDX-License-Identifier: LicenseRef-Carbon-Commercial-// Carbon Enterprise file, licensed only under the Carbon Commercial License-// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.--/**- * Utilities for bidirectional conversion between Markdown (Linear description format)- * and Tiptap JSON (Carbon's rich text format).- *- * Linear's API uses plain markdown for the `description` field.- * Carbon uses Tiptap/ProseMirror JSON for rich text editing.- */--// Tiptap (ProseMirror) JSON format-export type TiptapNode = {- type: string;- attrs?: Record<string, any>;- content?: TiptapNode[];- text?: string;- marks?: { type: string; attrs?: Record<string, any> }[];-};--export type TiptapDocument = {- type: "doc";- content: TiptapNode[];-};--/**- * Convert Markdown to Tiptap JSON format.- * This is used when syncing from Linear → Carbon.- */-export function markdownToTiptap(- markdown: string | null | undefined-): TiptapDocument {- if (!markdown || !markdown.trim()) {- return { type: "doc", content: [{ type: "paragraph" }] };- }-- const lines = markdown.split("\n");- const content: TiptapNode[] = [];- let i = 0;-- while (i < lines.length) {- const line = lines[i]!;-- // Heading- const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);- if (headingMatch) {- const level = headingMatch[1]!.length as 1 | 2 | 3 | 4 | 5 | 6;- content.push({- type: "heading",- attrs: { level },- content: parseInlineMarkdown(headingMatch[2]!)- });- i++;- continue;- }-- // Horizontal rule- if (/^(-{3,}|\*{3,}|_{3,})$/.test(line.trim())) {- content.push({ type: "horizontalRule" });- i++;- continue;- }-- // Code block- if (line.startsWith("```")) {- const language = line.slice(3).trim() || undefined;- const codeLines: string[] = [];- i++;- while (i < lines.length && !lines[i]!.startsWith("```")) {- codeLines.push(lines[i]!);- i++;- }- content.push({- type: "codeBlock",- attrs: language ? { language } : undefined,- content:- codeLines.length > 0- ? [{ type: "text", text: codeLines.join("\n") }]- : undefined- });- i++; // Skip closing ```- continue;- }-- // Blockquote- if (line.startsWith("> ")) {- const quoteLines: string[] = [];- while (i < lines.length && lines[i]!.startsWith("> ")) {- quoteLines.push(lines[i]!.slice(2));- i++;- }- content.push({- type: "blockquote",- content: [- {- type: "paragraph",- content: parseInlineMarkdown(quoteLines.join("\n"))- }- ]- });- continue;- }-- // Unordered list- if (/^[-*+]\s+/.test(line)) {- const listItems: TiptapNode[] = [];- while (i < lines.length && /^[-*+]\s+/.test(lines[i]!)) {- const itemText = lines[i]!.replace(/^[-*+]\s+/, "");- listItems.push({- type: "listItem",- content: [- {- type: "paragraph",- content: parseInlineMarkdown(itemText)- }- ]- });- i++;- }- content.push({- type: "bulletList",- content: listItems- });- continue;- }-- // Ordered list- if (/^\d+\.\s+/.test(line)) {- const listItems: TiptapNode[] = [];- while (i < lines.length && /^\d+\.\s+/.test(lines[i]!)) {- const itemText = lines[i]!.replace(/^\d+\.\s+/, "");- listItems.push({- type: "listItem",- content: [- {- type: "paragraph",- content: parseInlineMarkdown(itemText)- }- ]- });- i++;- }- content.push({- type: "orderedList",- content: listItems- });- continue;- }-- // Empty line or regular paragraph- if (line.trim() === "") {- i++;- continue;- }-- // Regular paragraph- content.push({- type: "paragraph",- content: parseInlineMarkdown(line)- });- i++;- }-- if (content.length === 0) {- return { type: "doc", content: [{ type: "paragraph" }] };- }-- return { type: "doc", content };-}--/**- * Parse inline markdown (bold, italic, links, code) into Tiptap nodes.- */-function parseInlineMarkdown(text: string): TiptapNode[] {- if (!text) return [];-- const nodes: TiptapNode[] = [];- let remaining = text;-- while (remaining.length > 0) {- // Link: [text](url)- const linkMatch = remaining.match(/^\[([^\]]+)\]\(([^)]+)\)/);- if (linkMatch) {- nodes.push({- type: "text",- text: linkMatch[1],- marks: [{ type: "link", attrs: { href: linkMatch[2] } }]- });- remaining = remaining.slice(linkMatch[0].length);- continue;- }-- // Bold: **text** or __text__- const boldMatch = remaining.match(/^(\*\*|__)(.+?)\1/);- if (boldMatch) {- nodes.push({- type: "text",- text: boldMatch[2],- marks: [{ type: "bold" }]- });- remaining = remaining.slice(boldMatch[0].length);- continue;- }-- // Italic: *text* or _text_- const italicMatch = remaining.match(/^(\*|_)([^*_]+)\1/);- if (italicMatch) {- nodes.push({- type: "text",- text: italicMatch[2],- marks: [{ type: "italic" }]- });- remaining = remaining.slice(italicMatch[0].length);- continue;- }-- // Strikethrough: ~~text~~- const strikeMatch = remaining.match(/^~~(.+?)~~/);- if (strikeMatch) {- nodes.push({- type: "text",- text: strikeMatch[1],- marks: [{ type: "strike" }]- });- remaining = remaining.slice(strikeMatch[0].length);- continue;- }-- // Inline code: `text`- const codeMatch = remaining.match(/^`([^`]+)`/);- if (codeMatch) {- nodes.push({- type: "text",- text: codeMatch[1],- marks: [{ type: "code" }]- });- remaining = remaining.slice(codeMatch[0].length);- continue;- }-- // Plain text (find next special character or end)- const nextSpecial = remaining.search(/[[*_~`]/);- if (nextSpecial === -1) {- nodes.push({ type: "text", text: remaining });- break;- } else if (nextSpecial === 0) {- // The special character didn't match a pattern, treat as literal- nodes.push({ type: "text", text: remaining[0] });- remaining = remaining.slice(1);- } else {- nodes.push({ type: "text", text: remaining.slice(0, nextSpecial) });- remaining = remaining.slice(nextSpecial);- }- }-- return nodes;-}--/**- * Convert Tiptap JSON to Markdown format.- * This is used when syncing from Carbon → Linear.- */-export function tiptapToMarkdown(- tiptapDoc: TiptapDocument | null | undefined-): string {- if (!tiptapDoc || !tiptapDoc.content) return "";-- return tiptapDoc.content.map(nodeToMarkdown).join("\n\n");-}--function nodeToMarkdown(node: TiptapNode): string {- switch (node.type) {- case "paragraph":- return node.content ? node.content.map(inlineToMarkdown).join("") : "";-- case "heading": {- const level = node.attrs?.level ?? 1;- const prefix = "#".repeat(level);- const text = node.content- ? node.content.map(inlineToMarkdown).join("")- : "";- return `${prefix} ${text}`;- }-- case "bulletList":- return (node.content ?? [])- .map((item) => {- const itemContent =- item.content?.map(nodeToMarkdown).join("\n") ?? "";- return `- ${itemContent}`;- })- .join("\n");-- case "orderedList":- return (node.content ?? [])- .map((item, index) => {- const itemContent =- item.content?.map(nodeToMarkdown).join("\n") ?? "";- return `${index + 1}. ${itemContent}`;- })- .join("\n");-- case "blockquote":- return (node.content ?? [])- .map((child) => `> ${nodeToMarkdown(child)}`)- .join("\n");-- case "codeBlock": {- const language = node.attrs?.language ?? "";- const code = node.content?.[0]?.text ?? "";- return `\`\`\`${language}\n${code}\n\`\`\``;- }-- case "horizontalRule":- return "---";-- case "listItem":- return node.content?.map(nodeToMarkdown).join("\n") ?? "";-- default:- return node.content ? node.content.map(inlineToMarkdown).join("") : "";- }-}--function inlineToMarkdown(node: TiptapNode): string {- if (node.type === "text") {- let text = node.text ?? "";-- if (node.marks) {- for (const mark of node.marks) {- switch (mark.type) {- case "bold":- text = `**${text}**`;- break;- case "italic":- text = `*${text}*`;- break;- case "strike":- text = `~~${text}~~`;- break;- case "code":- text = `\`${text}\``;- break;- case "link":- text = `[${text}](${mark.attrs?.href ?? ""})`;- break;- }- }- }-- return text;- }-- if (node.type === "hardBreak") {- return "\n";- }-- return "";-}--/**- * Check if two Tiptap documents have the same content.- * Used to prevent unnecessary syncs when content hasn't changed.- */-export function tiptapDocumentsEqual(- a: TiptapDocument | null | undefined,- b: TiptapDocument | null | undefined-): boolean {- if (!a && !b) return true;- if (!a || !b) return false;-- return JSON.stringify(a) === JSON.stringify(b);-}--/**- * Check if a Tiptap document is empty (no meaningful content).- */-export function isTiptapEmpty(doc: TiptapDocument | null | undefined): boolean {- if (!doc || !doc.content) return true;-- const hasContent = doc.content.some((node) => {- if (node.type === "paragraph" && node.content) {- return node.content.some(- (inline) => inline.type === "text" && inline.text?.trim()- );- }- return node.content && node.content.length > 0;- });-- return !hasContent;-}diff --git a/packages/ee/src/linear/lib/service.ts b/packages/ee/src/linear/lib/service.tsindex 397b403d55..d850dff563 100644--- a/packages/ee/src/linear/lib/service.ts+++ b/packages/ee/src/linear/lib/service.ts@@ -4,13 +4,13 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";+import { TiptapText } from "@carbon/files/markdown";import { getLogger } from "@carbon/logger";import { unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type z from "zod";import type { ActionTaskEntityType } from "../../lib/actionTaskEntity";import { actionTaskEntities } from "../../lib/actionTaskEntity";-import { markdownToTiptap } from "./richtext";import { LinearIssueSchema } from "./types";import { mapLinearStatusToCarbonStatus } from "./utils";@@ -48,7 +48,7 @@ export async function linkActionToLinearIssue(let notes: any = undefined;if (input.syncNotes && data.description) {try {- notes = markdownToTiptap(data.description);+ notes = TiptapText(data.description).toDocument();} catch (e) {logger.error("Failed to convert Linear description to Tiptap", {error: ediff --git a/packages/ee/src/notifications/services/linear.ts b/packages/ee/src/notifications/services/linear.tsindex cb9e777e40..94a1ebe434 100644--- a/packages/ee/src/notifications/services/linear.ts+++ b/packages/ee/src/notifications/services/linear.ts@@ -4,14 +4,13 @@import { getUser } from "@carbon/auth";import type { Database } from "@carbon/database";+import { TiptapText } from "@carbon/files/markdown";import { getLogger } from "@carbon/logger";import type { SupabaseClient } from "@supabase/supabase-js";-import type { TiptapDocument } from "../../linear/lib/index.server";import {getLinearClient,getLinearIssueFromExternalId,- mapCarbonStatusToLinearStatus,- tiptapToMarkdown+ mapCarbonStatusToLinearStatus} from "../../linear/lib/index.server";import type { NotificationEvent, NotificationService } from "../types";@@ -107,11 +106,11 @@ export class LinearNotificationService implements NotificationService {if (!issue) return; // No linked Linear issue// Convert Tiptap notes to markdown for Linear- const notes = event.data.notes as TiptapDocument | null | undefined;+ const notes = event.data.notes;if (!notes) return;try {- const description = tiptapToMarkdown(notes);+ const description = TiptapText(notes).toMarkdown();await linear.updateIssue(event.companyId, {id: issue.id,diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.tsindex 4a190d0141..4050839d54 100644--- a/packages/ee/src/paperless-parts/lib/lib.ts+++ b/packages/ee/src/paperless-parts/lib/lib.ts@@ -7,14 +7,14 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { storage } from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";+import { TiptapText } from "@carbon/files/markdown";import { processImage } from "@carbon/files/media";import { initNodeImageCodecs } from "@carbon/files/media/node";import { getLogger } from "@carbon/logger";import {getMaterialDescription,getMaterialId,- openAiCategorizationModel,- textToTiptap+ openAiCategorizationModel} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { generateText, Output } from "ai";@@ -2120,7 +2120,7 @@ export async function createPartFromComponent(machineTime: (operation.runtime ?? 0) * 60,machineUnit: "Minutes/Piece",workInstruction: operation.notes- ? textToTiptap(operation.notes)+ ? TiptapText(operation.notes, { format: "text" }).toDocument(): {}});}@@ -2757,10 +2757,14 @@ export async function insertOrderLines(? new Date(promisedDate ?? orderItem.ships_on!).toISOString(): null,internalNotes: orderItem.private_notes- ? textToTiptap(orderItem.private_notes)+ ? TiptapText(orderItem.private_notes, {+ format: "text"+ }).toDocument(): null,externalNotes: orderItem.public_notes- ? textToTiptap(orderItem.public_notes)+ ? TiptapText(orderItem.public_notes, {+ format: "text"+ }).toDocument(): null};@@ -3010,10 +3014,14 @@ export async function insertQuoteLines(companyId,createdBy,internalNotes: quoteItem.private_notes- ? textToTiptap(quoteItem.private_notes)+ ? TiptapText(quoteItem.private_notes, {+ format: "text"+ }).toDocument(): null,externalNotes: quoteItem.public_notes- ? textToTiptap(quoteItem.public_notes)+ ? TiptapText(quoteItem.public_notes, {+ format: "text"+ }).toDocument(): null};@@ -3138,7 +3146,9 @@ export async function insertQuoteLines(overheadRate: operationRates.overheadRate,machineRate: operationRates.machineRate,workInstruction: operation.notes- ? textToTiptap(operation.notes)+ ? TiptapText(operation.notes, {+ format: "text"+ }).toDocument(): {},companyId,createdBydiff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex 30da847945..7b745053be 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -8,6 +8,7 @@ in the codebase, shared by the browser and Node.|---------|----------|| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, `downloadUrl(url, filename)` (fetches first and throws on a failed response, so an expired session never saves an error page under the file's name), and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id). Every read and write goes to the company bucket only; there is no shared `private` bucket. `list(folder)` takes no options: it reads the cursor-paged `listV2` endpoint to the end and returns every entry directly inside the folder, sorted by name, in the old `list` shape (`name` is the entry's own name; a sub-folder has a null `id`). Every key must sit under `${companyId}/` and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. `getCompanyPrivateBucket` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver). `PRIVATE_PREVIEW_ALIAS` (`"private"`) is a stored URL segment, not a bucket: `/file/preview/private/<path>` links in rich text and inspection documents are served from the caller's own company bucket || `./csv` | `encodeCsv` (object rows; `header: false` encodes a later page of a streamed file — pages join with `\r\n`, see the Sync Activity export) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell; `formulaSafe: false` turns that off for CSV a program reads and no spreadsheet opens, which today is only the MCP server's tool results); `parseCsv` (text) / `parseCsvFile` (browser File, streamed) / `parseCsvLines` (text → records with the line each starts on, blank and delimiter-only records left out; for messages that name a line); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection |+| `./markdown` | `TiptapText(value, { format? })` — the ONE place a rich-text document is turned into text or read from it, with no DOM (server and browser). `value` is a stored document, a document encoded as text, or text. `.toDocument()` (text read as CommonMark through `@tiptap/pm/markdown`, raw HTML kept as text, the editor's node and mark names; `format: "text"` stores it as typed: a paragraph per line, `**bold**`), `.toString()` (plain text), `.toMarkdown()` (editor-only nodes such as mentions become text, unknown wrappers keep their children). Used by every API / MCP rich-text input (`toTiptapDoc`), the Linear sync, Paperless notes, and the shared `generateHTML` (`@carbon/react`), which reads a JSON string scalar an older API stored instead of crashing on it || `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` || `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). The wasm comes from the BUNDLER (`?inline` data URIs), never off disk — so this module is consumable only from a Vite pipeline, and that pipeline needs `assetsInclude: ["**/*.wasm"]` (already set in `apps/erp/vite.config.ts` and `@carbon/config/vitest`). `renderLabelLogo(bytes, ext, { widthDots, threshold?, crop? })` — a logo as a mono PNG data URL + ZPL `^GFA` field (inits the codecs itself; `@carbon/documents/labels` calls it). Never import from client code || `./cad` | CAD/model formats: `supportedModelTypes`, `optimizableModelFormat`, `modelPathOptimizeFormat`, `isModelRawDownloadable` |diff --git a/packages/files/package.json b/packages/files/package.jsonindex d31e35150c..3e0e9a9067 100644--- a/packages/files/package.json+++ b/packages/files/package.json@@ -9,6 +9,7 @@"./media/node": "./src/media/node.ts","./cad": "./src/cad/index.ts","./csv": "./src/csv/index.ts",+ "./markdown": "./src/markdown/index.ts","./pdf": "./src/pdf/index.ts","./pdf/worker": "./src/pdf/worker.ts"},@@ -27,6 +28,7 @@"@jsquash/webp": "1.5.0","@supabase/storage-js": "catalog:","@supabase/supabase-js": "catalog:",+ "@tiptap/pm": "catalog:","libheif-js": "1.23.2","nanoid": "catalog:","papaparse": "5.3.2",diff --git a/packages/files/src/markdown/index.ts b/packages/files/src/markdown/index.tsnew file mode 100644index 0000000000..280c2fbf61--- /dev/null+++ b/packages/files/src/markdown/index.ts@@ -0,0 +1,5 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++export * from "./markdown";diff --git a/packages/files/src/markdown/markdown.test.ts b/packages/files/src/markdown/markdown.test.tsnew file mode 100644index 0000000000..7add925576--- /dev/null+++ b/packages/files/src/markdown/markdown.test.ts@@ -0,0 +1,275 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { TiptapText } from "./markdown";++describe("markdownToTiptap", () => {+ it("turns plain text into paragraphs, keeping single line breaks", () => {+ expect(+ TiptapText("First line\nSecond line\n\nNew paragraph").toDocument()+ ).toEqual({+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "First line" },+ { type: "hardBreak" },+ { type: "text", text: "Second line" }+ ]+ },+ {+ type: "paragraph",+ content: [{ type: "text", text: "New paragraph" }]+ }+ ]+ });+ });++ it("uses the editor's node and mark names", () => {+ const doc = TiptapText(+ [+ "## Inspection",+ "",+ "Check **torque** and _finish_, see [spec](https://example.com).",+ "",+ "- one",+ "- two",+ "",+ "3. three",+ "",+ "> quoted",+ "",+ "```ts",+ "const x = 1;",+ "```",+ "",+ "---",+ "",+ "`inline`"+ ].join("\n")+ ).toDocument();+ expect(doc.content?.map((node) => node.type)).toEqual([+ "heading",+ "paragraph",+ "bulletList",+ "orderedList",+ "blockquote",+ "codeBlock",+ "horizontalRule",+ "paragraph"+ ]);+ expect(doc.content?.[0]?.attrs).toEqual({ level: 2 });+ expect(doc.content?.[1]?.content).toEqual([+ { type: "text", text: "Check " },+ { type: "text", text: "torque", marks: [{ type: "bold" }] },+ { type: "text", text: " and " },+ { type: "text", text: "finish", marks: [{ type: "italic" }] },+ { type: "text", text: ", see " },+ {+ type: "text",+ text: "spec",+ marks: [+ { type: "link", attrs: { href: "https://example.com", title: null } }+ ]+ },+ { type: "text", text: "." }+ ]);+ expect(doc.content?.[2]?.content?.[0]?.type).toBe("listItem");+ expect(doc.content?.[3]?.attrs).toEqual({ start: 3 });+ expect(doc.content?.[5]).toEqual({+ type: "codeBlock",+ attrs: { language: "ts" },+ content: [{ type: "text", text: "const x = 1;" }]+ });+ expect(doc.content?.[7]?.content?.[0]?.marks).toEqual([{ type: "code" }]);+ });++ it("keeps raw HTML as literal text", () => {+ expect(TiptapText("<script>alert(1)</script>").toDocument()).toEqual({+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "<script>alert(1)</script>" }]+ }+ ]+ });+ });++ it("does not link a javascript: URL", () => {+ const doc = TiptapText("[x](javascript:alert(1))").toDocument();+ expect(JSON.stringify(doc)).not.toContain('"link"');+ });++ it("returns a loadable document for an empty string", () => {+ expect(TiptapText("").toDocument()).toEqual({+ type: "doc",+ content: [{ type: "paragraph" }]+ });+ });+});++describe("TiptapText format: text", () => {+ it("makes each line a paragraph and **text** bold", () => {+ expect(+ TiptapText("Tap with **TiN-coated** tap.\n\nChase a ** b", {+ format: "text"+ }).toDocument()+ ).toEqual({+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "Tap with " },+ { type: "text", text: "TiN-coated", marks: [{ type: "bold" }] },+ { type: "text", text: " tap." }+ ]+ },+ { type: "paragraph" },+ { type: "paragraph", content: [{ type: "text", text: "Chase a ** b" }] }+ ]+ });+ });++ it("splits on CRLF, LF and CR alike, and keeps asterisks inside bold", () => {+ for (const text of [+ "a\r\n**M6*1 tap**",+ "a\n**M6*1 tap**",+ "a\r**M6*1 tap**"+ ]) {+ expect(TiptapText(text, { format: "text" }).toDocument().content).toEqual(+ [+ { type: "paragraph", content: [{ type: "text", text: "a" }] },+ {+ type: "paragraph",+ content: [+ { type: "text", text: "M6*1 tap", marks: [{ type: "bold" }] }+ ]+ }+ ]+ );+ }+ });+});++describe("TiptapText reads stored values", () => {+ const doc = {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: "hi" }] }]+ };++ it("passes a document through", () => {+ expect(TiptapText(doc).toDocument()).toBe(doc);+ });++ it("reads a document encoded as text", () => {+ expect(TiptapText(JSON.stringify(doc)).toDocument()).toEqual(doc);+ });++ it("reads JSON that is not an object as text", () => {+ expect(TiptapText("123").toString()).toBe("123");+ });++ it("reads JSON that is not a document as text", () => {+ expect(TiptapText('{"a":1}').toString()).toBe('{"a":1}');+ });++ it("reads `{}` as an empty document, stored or encoded", () => {+ expect(TiptapText({}).toString()).toBe("");+ expect(TiptapText("{}").toString()).toBe("");+ });++ it("reads null as an empty document", () => {+ expect(TiptapText(null).toDocument()).toEqual({+ type: "doc",+ content: [{ type: "paragraph" }]+ });+ });+});++describe("TiptapText.toString", () => {+ it("joins blocks as lines and drops marks", () => {+ expect(+ TiptapText("# Title\n\n- **one**\n- two\n\n---\n\nend").toString()+ ).toBe("Title\none\ntwo\nend");+ });++ it("round-trips plain text read as typed", () => {+ const text = "1. Ship\n**not bold markers**";+ expect(TiptapText(text, { format: "text" }).toString()).toBe(+ "1. Ship\nnot bold markers"+ );+ });+});++describe("TiptapText.toMarkdown", () => {+ it("round-trips Markdown", () => {+ const markdown = [+ "## Setup",+ "",+ "Check **torque** and *finish*, see [spec](https://example.com).",+ "",+ "- one",+ "- two",+ "",+ "3. three",+ "",+ "> quoted",+ "",+ "```ts",+ "const x = 1;",+ "```",+ "",+ "---",+ "",+ "`inline` code"+ ].join("\n");+ expect(TiptapText(markdown).toMarkdown()).toBe(markdown);+ });++ it("writes editor-only nodes as text instead of throwing", () => {+ const doc = {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "Ask " },+ { type: "mention", attrs: { id: "u1", label: "Nick" } },+ {+ type: "text",+ text: " now",+ marks: [+ { type: "underline" },+ { type: "bold" },+ { type: "strike" }+ ]+ }+ ]+ },+ {+ type: "taskList",+ content: [+ {+ type: "taskItem",+ attrs: { checked: true },+ content: [+ { type: "paragraph", content: [{ type: "text", text: "Tack" }] }+ ]+ }+ ]+ }+ ]+ };+ expect(TiptapText(doc).toMarkdown()).toBe("Ask @Nick **~~now~~**\n\nTack");+ });++ it("is empty for an empty document", () => {+ expect(TiptapText({ type: "doc", content: [] }).toMarkdown()).toBe("");+ expect(TiptapText(null).toMarkdown()).toBe("");+ });+});diff --git a/packages/files/src/markdown/markdown.ts b/packages/files/src/markdown/markdown.tsnew file mode 100644index 0000000000..804a48273e--- /dev/null+++ b/packages/files/src/markdown/markdown.ts@@ -0,0 +1,307 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Tiptap documents to and from text, with no DOM, so it runs on the server and+// in the browser. Markdown goes through prosemirror-markdown's CommonMark+// tokenizer (raw HTML off) against a schema that uses the editor's node and+// mark names, so a parsed document loads in the editor as if typed there.++import {+ defaultMarkdownParser,+ defaultMarkdownSerializer,+ MarkdownParser,+ MarkdownSerializer+} from "@tiptap/pm/markdown";+import { Schema } from "@tiptap/pm/model";++/** Tiptap's JSON document shape (structurally `JSONContent` from @tiptap/core). */+export type JSONContent = {+ type?: string;+ attrs?: Record<string, any>;+ content?: JSONContent[];+ marks?: { type: string; attrs?: Record<string, any> }[];+ text?: string;+ [key: string]: any;+};++type Format = "markdown" | "text";++const schema = new Schema({+ nodes: {+ doc: { content: "block+" },+ paragraph: { content: "inline*", group: "block" },+ blockquote: { content: "block+", group: "block" },+ horizontalRule: { group: "block" },+ heading: {+ attrs: { level: { default: 1 } },+ content: "inline*",+ group: "block"+ },+ codeBlock: {+ attrs: { language: { default: null } },+ content: "text*",+ marks: "",+ group: "block",+ code: true+ },+ bulletList: { content: "listItem+", group: "block" },+ orderedList: {+ attrs: { start: { default: 1 } },+ content: "listItem+",+ group: "block"+ },+ listItem: { content: "paragraph block*" },+ text: { group: "inline" },+ image: {+ attrs: {+ src: {},+ alt: { default: null },+ title: { default: null }+ },+ inline: true,+ group: "inline"+ },+ hardBreak: { inline: true, group: "inline", selectable: false }+ },+ marks: {+ bold: {},+ italic: {},+ strike: {},+ code: {},+ link: {+ attrs: { href: {}, title: { default: null } },+ inclusive: false+ }+ }+});++const parser = new MarkdownParser(+ schema,+ // Read-only reuse of the CommonMark tokenizer: `parse` does not mutate it.+ defaultMarkdownParser.tokenizer,+ {+ blockquote: { block: "blockquote" },+ paragraph: { block: "paragraph" },+ list_item: { block: "listItem" },+ bullet_list: { block: "bulletList" },+ ordered_list: {+ block: "orderedList",+ getAttrs: (tok) => ({ start: Number(tok.attrGet("start")) || 1 })+ },+ heading: {+ block: "heading",+ getAttrs: (tok) => ({ level: Number(tok.tag.slice(1)) })+ },+ code_block: { block: "codeBlock", noCloseToken: true },+ fence: {+ block: "codeBlock",+ getAttrs: (tok) => ({ language: tok.info.trim() || null }),+ noCloseToken: true+ },+ hr: { node: "horizontalRule" },+ image: {+ node: "image",+ getAttrs: (tok) => ({+ src: tok.attrGet("src"),+ title: tok.attrGet("title") || null,+ alt: tok.children?.[0]?.content || null+ })+ },+ hardbreak: { node: "hardBreak" },+ // A single newline is kept as a line break rather than collapsed to a+ // space, so plain text with line breaks reads back the way it was written.+ softbreak: { node: "hardBreak" },+ em: { mark: "italic" },+ strong: { mark: "bold" },+ link: {+ mark: "link",+ getAttrs: (tok) => ({+ href: tok.attrGet("href"),+ title: tok.attrGet("title") || null+ })+ },+ code_inline: { mark: "code", noCloseToken: true }+ }+);++const md = defaultMarkdownSerializer;+const serializer = new MarkdownSerializer(+ {+ doc: (state, node) => state.renderContent(node),+ paragraph: md.nodes.paragraph!,+ blockquote: md.nodes.blockquote!,+ horizontalRule: md.nodes.horizontal_rule!,+ heading: md.nodes.heading!,+ codeBlock: (state, node) => {+ state.write(`\`\`\`${node.attrs.language ?? ""}\n`);+ state.text(node.textContent, false);+ state.write("\n```");+ state.closeBlock(node);+ },+ bulletList: (state, node) => state.renderList(node, " ", () => "- "),+ orderedList: (state, node) => {+ const start = node.attrs.start ?? 1;+ state.renderList(node, " ", (i) => `${start + i}. `);+ },+ listItem: md.nodes.list_item!,+ image: md.nodes.image!,+ hardBreak: md.nodes.hard_break!,+ text: md.nodes.text!+ },+ {+ bold: md.marks.strong!,+ italic: md.marks.em!,+ code: md.marks.code!,+ link: md.marks.link!,+ strike: {+ open: "~~",+ close: "~~",+ mixable: true,+ expelEnclosingWhitespace: true+ }+ }+);++const emptyDocument = (): JSONContent => ({+ type: "doc",+ content: [{ type: "paragraph" }]+});++/** Plain text as typed: one paragraph per line, `**text**` bold. */+function textDocument(text: string): JSONContent {+ const content = text.split(/\r\n|\r|\n/).map((line) =>+ // ProseMirror text nodes cannot be empty, so blank lines become a bare paragraph+ line === ""+ ? { type: "paragraph" }+ : {+ type: "paragraph",+ content: line+ .split(/(\*\*.+?\*\*)/)+ .filter(Boolean)+ .map((part) =>+ part.length > 4 && part.startsWith("**") && part.endsWith("**")+ ? {+ type: "text",+ text: part.slice(2, -2),+ marks: [{ type: "bold" }]+ }+ : { type: "text", text: part }+ )+ }+ );+ return { type: "doc", content };+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ !!value && typeof value === "object" && !Array.isArray(value);++/** A Tiptap document: an object whose `type` is `doc`. */+export const isTiptapDocument = (value: unknown): value is JSONContent =>+ isRecord(value) && value.type === "doc";++function readDocument(value: unknown, format: Format): JSONContent {+ if (isTiptapDocument(value)) return value;+ // Any other object is not a document. `{}` is how the editor stores an+ // empty one; stringifying it would read as "[object Object]".+ if (isRecord(value) || value === null || value === undefined) {+ return emptyDocument();+ }+ const text = String(value);+ // A document encoded as text (a form post, or a JSON string scalar stored by+ // an older API), or `{}`. Anything else that parses (`123`, `"quoted"`,+ // `{"a":1}`) is text.+ try {+ const parsed: unknown = JSON.parse(text);+ if (isTiptapDocument(parsed)) return parsed;+ if (isRecord(parsed) && Object.keys(parsed).length === 0) {+ return emptyDocument();+ }+ } catch {+ // Not JSON: read as text below.+ }+ if (!text.trim()) return emptyDocument();+ return format === "text"+ ? textDocument(text)+ : (parser.parse(text).toJSON() as JSONContent);+}++/** Plain text: blocks become lines; marks and non-text inline nodes drop. */+function documentText(doc: JSONContent): string {+ const inline = (node: JSONContent): string => {+ if (node.type === "text") return node.text ?? "";+ if (node.type === "hardBreak") return "\n";+ return (node.content ?? []).map(inline).join("");+ };+ const block = (node: JSONContent): string[] => {+ switch (node.type) {+ case "bulletList":+ case "orderedList":+ case "blockquote":+ case "listItem":+ return (node.content ?? []).flatMap(block);+ case "horizontalRule":+ return [];+ default:+ return [(node.content ?? []).map(inline).join("")];+ }+ };+ return (doc.content ?? [])+ .flatMap(block)+ .join("\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++/**+ * Reduce an editor document to the nodes and marks Markdown can say. A mention+ * becomes `@label`, an unknown wrapper (task list, table) keeps its children,+ * anything else unknown drops.+ */+function toMarkdownSchema(node: JSONContent): JSONContent[] {+ const type = node.type ?? "";+ if (type === "text") {+ if (!node.text) return [];+ const marks = node.marks?.filter((mark) => schema.marks[mark.type]);+ return [{ ...node, marks }];+ }+ if (type === "mention") {+ const label = node.attrs?.label ?? node.attrs?.id;+ return label ? [{ type: "text", text: `@${label}` }] : [];+ }+ if ((type === "image" || type === "updatedImage") && node.attrs?.src) {+ return [{ type: "image", attrs: node.attrs }];+ }+ const content = (node.content ?? []).flatMap(toMarkdownSchema);+ if (schema.nodes[type] && type !== "image") {+ return [{ type, attrs: node.attrs, content }];+ }+ return content;+}++function documentMarkdown(doc: JSONContent): string {+ const [normalized] = toMarkdownSchema({ ...doc, type: "doc" });+ if (!normalized?.content?.length) return "";+ return serializer+ .serialize(schema.nodeFromJSON(normalized), { tightLists: true })+ .trim();+}++/**+ * Rich text in one place: give it a stored document, a document encoded as+ * text, or text, and ask for the form you need.+ *+ * `format: "text"` reads text as typed (a field edited in a plain textarea and+ * read back with `toString`); the default reads it as Markdown.+ */+export function TiptapText(+ value: unknown,+ { format = "markdown" }: { format?: Format } = {}+) {+ const doc = readDocument(value, format);+ return {+ toDocument: () => doc,+ toString: () => documentText(doc),+ toMarkdown: () => documentMarkdown(doc)+ };+}diff --git a/packages/jobs/src/inngest/functions/events/diff.ts b/packages/jobs/src/inngest/functions/events/diff.tsindex 92bcd626d0..e722749d84 100644--- a/packages/jobs/src/inngest/functions/events/diff.ts+++ b/packages/jobs/src/inngest/functions/events/diff.ts@@ -4,7 +4,7 @@import { auditConfig } from "@carbon/database/audit.config";import type { AuditDiff } from "@carbon/database/audit.types";-import { tiptapToText } from "@carbon/utils";+import { TiptapText } from "@carbon/files/markdown";// Pure diff computation for the audit handler. Kept free of Inngest / auth// imports (which require env vars at import time) so it can be unit-tested@@ -50,7 +50,7 @@ function richTextToText(value: unknown): string {// Malformed doc JSON must degrade to "", not throw — an unhandled throw// here poisons the event batch and Inngest retries it forever.try {- return tiptapToText(value as Parameters<typeof tiptapToText>[0]);+ return TiptapText(value).toString();} catch {return "";}diff --git a/packages/react/package.json b/packages/react/package.jsonindex 2e415072c5..835957818b 100644--- a/packages/react/package.json+++ b/packages/react/package.json@@ -3,6 +3,7 @@"dependencies": {"@carbon/database": "workspace:*","@carbon/env": "workspace:*",+ "@carbon/files": "workspace:*","@carbon/content": "workspace:*","@carbon/logger": "workspace:*","@carbon/tiptap": "workspace:*",@@ -99,6 +100,7 @@"@types/react": "catalog:","@types/react-dom": "catalog:","@types/react-window": "1.8.8",+ "jsdom": "26.1.0","react": "catalog:","sst": "catalog:","tailwindcss": "catalog:",diff --git a/packages/react/src/HTML.test.tsx b/packages/react/src/HTML.test.tsxnew file mode 100644index 0000000000..9ad39014b8--- /dev/null+++ b/packages/react/src/HTML.test.tsx@@ -0,0 +1,36 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// @vitest-environment jsdom++import { describe, expect, it } from "vitest";+import { generateHTML, isRichTextEmpty } from "./HTML";++// A work instruction stored as a JSON string scalar crashed the MES operation+// page: `"type" in "<text>"` throws. Strings are now read as documents.+describe("rich text stored as a string", () => {+ const note = "Check the fit-up before tacking.";++ it("renders plain text instead of throwing", () => {+ expect(generateHTML(note as never)).toBe(`<p>${note}</p>`);+ expect(isRichTextEmpty(note as never)).toBe(false);+ });++ it("reads a document encoded as text", () => {+ const doc = {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: note }] }]+ };+ expect(generateHTML(JSON.stringify(doc) as never)).toBe(`<p>${note}</p>`);+ expect(isRichTextEmpty(JSON.stringify(doc) as never)).toBe(false);+ expect(isRichTextEmpty(JSON.stringify({ type: "doc" }) as never)).toBe(+ true+ );+ });++ it("treats an empty string as empty", () => {+ expect(generateHTML("" as never)).toBe("");+ expect(isRichTextEmpty("" as never)).toBe(true);+ });+});diff --git a/packages/react/src/HTML.tsx b/packages/react/src/HTML.tsxindex b3f1cb9437..58478bd122 100644--- a/packages/react/src/HTML.tsx+++ b/packages/react/src/HTML.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { TiptapText } from "@carbon/files/markdown";import { Mention } from "@carbon/tiptap";import TextStyle from "@tiptap/extension-text-style";import Underline from "@tiptap/extension-underline";@@ -15,14 +16,25 @@ import { cn } from "./utils/cn";const { sanitize } = pkg;+// Rows written before the API stored documents can hold a JSON string scalar.+// `"type" in "text"` throws and crashes the page, so read strings as documents.+// Objects pass as they are: `isRichTextEmpty` walks child nodes through here.+const toRichTextDoc = (content: unknown): JSONContent | null =>+ typeof content === "string"+ ? content.trim()+ ? TiptapText(content).toDocument()+ : null+ : ((content as JSONContent | null | undefined) ?? null);+const generateHTML = (content: JSONContent) => {if (typeof window === "undefined") {return "";}- if (!content || !("type" in content)) {+ const doc = toRichTextDoc(content);+ if (!doc || !("type" in doc)) {return "";}- const raw = DefaultGenerateHTML(content, [+ const raw = DefaultGenerateHTML(doc, [...defaultExtensions,TextStyle,StarterKit,@@ -71,7 +83,8 @@ const CONTAINER_NODES = new Set([* other leaf. Reads the JSON, not the HTML, so the server (where* `generateHTML` returns "") agrees with the browser.*/-const isRichTextEmpty = (content?: JSONContent | null): boolean => {+const isRichTextEmpty = (value?: JSONContent | null): boolean => {+ const content = toRichTextDoc(value);if (!content) return true;if (content.type === "text") return !content.text?.trim();if (content.type && !CONTAINER_NODES.has(content.type)) return false;diff --git a/packages/tiptap/AGENTS.md b/packages/tiptap/AGENTS.mdindex 8bdeda56db..53b24ef118 100644--- a/packages/tiptap/AGENTS.md+++ b/packages/tiptap/AGENTS.md@@ -37,6 +37,8 @@ pnpm --filter @carbon/tiptap lint**Utils**: `getPrevText`, `getAllContent`, `isValidUrl`, `getUrlFromString`+Converting a document to or from text (Markdown, plain text) is not here: it is `TiptapText` in `@carbon/files/markdown`, which runs with no DOM.+## Cross-References- `@carbon/react` — wraps TipTap in `Editor/` and `RichText/` sub-exportsdiff --git a/packages/tiptap/package.json b/packages/tiptap/package.jsonindex 26ae9c85c7..b27411811a 100644--- a/packages/tiptap/package.json+++ b/packages/tiptap/package.json@@ -28,7 +28,6 @@"dompurify": "catalog:","linkifyjs": "4.3.2","nanoid": "catalog:",- "react-markdown": "9.1.0","react-moveable": "0.56.0","tippy.js": "6.3.7","tiptap-extension-global-drag-handle": "0.1.18",diff --git a/packages/utils/src/tiptap.test.ts b/packages/utils/src/tiptap.test.tsindex a17fa27677..d9344ec271 100644--- a/packages/utils/src/tiptap.test.ts+++ b/packages/utils/src/tiptap.test.ts@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { describe, expect, it } from "vitest";-import { documentHasImages, textToTiptap } from "./tiptap";+import { documentHasImages } from "./tiptap";describe("documentHasImages", () => {it("returns false for empty / textless documents", () => {@@ -57,43 +57,3 @@ describe("documentHasImages", () => {).toBe(true);});});--describe("textToTiptap", () => {- it("makes each line a paragraph and **text** bold", () => {- expect(- textToTiptap("Tap with **TiN-coated** tap.\n\nChase a ** b")- ).toEqual({- type: "doc",- content: [- {- type: "paragraph",- content: [- { type: "text", text: "Tap with " },- { type: "text", text: "TiN-coated", marks: [{ type: "bold" }] },- { type: "text", text: " tap." }- ]- },- { type: "paragraph" },- { type: "paragraph", content: [{ type: "text", text: "Chase a ** b" }] }- ]- });- });-- it("splits on CRLF, LF and CR alike, and keeps asterisks inside bold", () => {- for (const text of [- "a\r\n**M6*1 tap**",- "a\n**M6*1 tap**",- "a\r**M6*1 tap**"- ]) {- expect(textToTiptap(text).content).toEqual([- { type: "paragraph", content: [{ type: "text", text: "a" }] },- {- type: "paragraph",- content: [- { type: "text", text: "M6*1 tap", marks: [{ type: "bold" }] }- ]- }- ]);- }- });-});diff --git a/packages/utils/src/tiptap.ts b/packages/utils/src/tiptap.tsindex 8def152ef5..4baef2b669 100644--- a/packages/utils/src/tiptap.ts+++ b/packages/utils/src/tiptap.ts@@ -62,66 +62,6 @@ export function documentHasImages(return traverse(content);}-/** Plain text as a Tiptap document: one paragraph per line, `**text**` bold. */-export const textToTiptap = (text: string) => {- const lines = text.split(/\r\n|\r|\n/);- const content = lines.map((line) =>- // ProseMirror text nodes cannot be empty, so blank lines become a bare paragraph- line === ""- ? { type: "paragraph" }- : { type: "paragraph", content: boldRuns(line) }- );- return { type: "doc", content };-};--function boldRuns(line: string) {- return line- .split(/(\*\*.+?\*\*)/)- .filter(Boolean)- .map((part) =>- part.length > 4 && part.startsWith("**") && part.endsWith("**")- ? { type: "text", text: part.slice(2, -2), marks: [{ type: "bold" }] }- : { type: "text", text: part }- );-}--/**- * Convert a Tiptap JSON document to plain text (inverse of textToTiptap).- * Block nodes become newline-separated lines; marks and non-text inline- * content are dropped.- */-export function tiptapToText(doc: JSONContent | null | undefined): string {- if (!doc || !doc.content) return "";-- function inlineText(node: JSONContent): string {- if (node.type === "text") return node.text ?? "";- if (node.type === "hardBreak") return "\n";- if (node.content) return node.content.map(inlineText).join("");- return "";- }-- function blockText(node: JSONContent): string[] {- switch (node.type) {- case "bulletList":- case "orderedList":- case "blockquote":- return (node.content ?? []).flatMap(blockText);- case "listItem":- return (node.content ?? []).flatMap(blockText);- case "horizontalRule":- return [];- default:- return [node.content ? node.content.map(inlineText).join("") : ""];- }- }-- return doc.content- .flatMap(blockText)- .join("\n")- .replace(/\n{3,}/g, "\n\n")- .trim();-}-/*** Convert a Tiptap JSON document to an HTML string.* Works server-side without DOM dependencies.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6244c8ced8..534bc08910 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1176,7 +1176,7 @@ importers:version: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: 'catalog:'+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])apps/mes:dependencies:@@ -1498,7 +1498,7 @@ importers:version: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: 'catalog:'+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])wait-on:specifier: 'catalog:'version: 7.2.0@@ -1969,7 +1969,7 @@ importers:version: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: 'catalog:'+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])packages/account:dependencies:@@ -2088,7 +2088,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/auth:dependencies:@@ -2188,7 +2188,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/checks:devDependencies:@@ -2218,7 +2218,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/config:dependencies:@@ -2251,7 +2251,7 @@ importers:version: 1.0.7([email protected])vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))devDependencies:tsup:specifier: 'catalog:'@@ -2346,7 +2346,7 @@ importers:version: 9.0.0vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/dev:dependencies:@@ -2413,7 +2413,7 @@ importers:version: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: 'catalog:'+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected])packages/documents:dependencies:@@ -2528,7 +2528,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/ee:dependencies:@@ -2676,7 +2676,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/env:dependencies:@@ -2698,7 +2698,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/files:dependencies:@@ -2726,6 +2726,9 @@ importers:'@supabase/supabase-js':specifier: 'catalog:'version: 2.117.2(@opentelemetry/[email protected])+ '@tiptap/pm':+ specifier: 'catalog:'+ version: 2.27.2libheif-js:specifier: 1.23.2version: 1.23.2@@ -2753,7 +2756,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/form:dependencies:@@ -2850,7 +2853,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))zod-form-data:specifier: 'catalog:'version: 3.0.3([email protected])@@ -2874,7 +2877,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/jobs:dependencies:@@ -3013,7 +3016,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/kv:dependencies:@@ -3068,7 +3071,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/lib:dependencies:@@ -3156,7 +3159,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/locale:dependencies:@@ -3187,7 +3190,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/logger:dependencies:@@ -3242,7 +3245,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/notifications:devDependencies:@@ -3260,7 +3263,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/onboarding:dependencies:@@ -3318,7 +3321,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/planning:dependencies:@@ -3352,7 +3355,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/printing:dependencies:@@ -3444,7 +3447,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/react:dependencies:@@ -3460,6 +3463,9 @@ importers:'@carbon/env':specifier: workspace:*version: link:../env+ '@carbon/files':+ specifier: workspace:*+ version: link:../files'@carbon/logger':specifier: workspace:*version: link:../logger@@ -3755,6 +3761,9 @@ importers:'@types/react-window':specifier: 1.8.8version: 1.8.8+ jsdom:+ specifier: 26.1.0+ version: 26.1.0react:specifier: 18.3.1version: 18.3.1@@ -3772,7 +3781,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/serve:dependencies:@@ -3812,7 +3821,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/stripe:dependencies:@@ -3967,9 +3976,6 @@ importers:react-icons:specifier: 'catalog:'version: 5.6.0([email protected])- react-markdown:- specifier: 9.1.0- version: 9.1.0(@types/[email protected])([email protected])react-moveable:specifier: 0.56.0version: 0.56.0@@ -4027,7 +4033,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/utils:dependencies:@@ -4091,7 +4097,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/viewer:dependencies:@@ -4155,7 +4161,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/workflows-core:dependencies:@@ -4171,7 +4177,7 @@ importers:version: 5.8.3vitest:specifier: 'catalog:'- version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages:@@ -4267,6 +4273,9 @@ packages:resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}+ '@asamuzakjp/[email protected]':+ resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}+'@aws-crypto/[email protected]':resolution: {integrity: sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==}@@ -4727,6 +4736,34 @@ packages:peerDependencies:solid-js: ^1.8+ '@csstools/[email protected]':+ resolution: {integrity: sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==}+ engines: {node: '>=18'}++ '@csstools/[email protected]':+ resolution: {integrity: sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==}+ engines: {node: '>=18'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^3.0.5+ '@csstools/css-tokenizer': ^3.0.4++ '@csstools/[email protected]':+ resolution: {integrity: sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==}+ engines: {node: '>=18'}+ peerDependencies:+ '@csstools/css-parser-algorithms': ^3.0.5+ '@csstools/css-tokenizer': ^3.0.4++ '@csstools/[email protected]':+ resolution: {integrity: sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==}+ engines: {node: '>=18'}+ peerDependencies:+ '@csstools/css-tokenizer': ^3.0.4++ '@csstools/[email protected]':+ resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}+ engines: {node: '>=18'}+'@dagrejs/[email protected]':resolution: {integrity: sha512-5SEDlndt4W/LaVzPYJW+bSmSEZc9EzTf8rJ20WCKvjS5EAZAN0b+x0Yww7VMT4R3Wootkg+X9bUfUxazYw6Blw==}@@ -12206,6 +12243,10 @@ packages:engines: {node: '>=4'}hasBin: true+ resolution: {integrity: sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}@@ -12368,6 +12409,10 @@ packages:resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}engines: {node: '>= 12'}+ resolution: {integrity: sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}engines: {node: '>= 0.4'}@@ -13422,6 +13467,10 @@ packages:resolution: {integrity: sha512-LgOWAkrN0rFaQpfdWBQlv/VhkOxb5AsBjk6NQVx4yEzWS923T07X0M1Y0VNko2H52HeSpZrZNNMJ0aFqsdVzQg==}+ resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg==}engines: {node: '>=14'}@@ -13439,6 +13488,10 @@ packages:resolution: {integrity: sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==}engines: {node: '>= 0.8'}+ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==}engines: {node: '>=16'}@@ -13760,6 +13813,9 @@ packages:resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}engines: {node: '>=12'}+ resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}+resolution: {integrity: sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==}@@ -13934,6 +13990,15 @@ packages:resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==}hasBin: true+ resolution: {integrity: sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==}+ engines: {node: '>=18'}+ peerDependencies:+ canvas: ^3.0.0+ peerDependenciesMeta:+ canvas:+ optional: true+resolution: {integrity: sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==}engines: {node: '>=6'}@@ -15079,6 +15144,9 @@ packages:resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==}+ resolution: {integrity: sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==}+resolution: {integrity: sha512-mn8wBFV9G9+UFHIrq+pZ2r2zL4aPau/by3kJb3cM7+5tQHMt6HGQB8FDIeKFYp8o0D2pnH6nVsO88N4AmUxIWg==}engines: {node: ^14.16.0 || >=16.10.0}@@ -16241,6 +16309,9 @@ packages:resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}engines: {node: '>= 18'}+ resolution: {integrity: sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==}+resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}@@ -16279,6 +16350,10 @@ packages:resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}+ resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}+ engines: {node: '>=v12.22.7'}+resolution: {integrity: sha512-7rro8Io3tnCPuY4la/NuI5F2yfESpnfZyT6TtkXnSWVkcu0BCDJ+8gk5ozUaFaxpIyNuWAPXrH0yFcSi28fnDA==}@@ -16812,6 +16887,9 @@ packages:peerDependencies:react: 18.3.1+ resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}+resolution: {integrity: sha512-s5RloL0F7xhN0ZjfHtLGnbf7EW74EI0N8NFL+1xR7Oxz9QA33obNZsl7lyfnJOhN04E/kGFPoJPlvY7TZ5fzmw==}engines: {node: '>=10.0.0'}@@ -16966,6 +17044,13 @@ packages:peerDependencies:'@tiptap/core': ^2.0.3+ resolution: {integrity: sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==}++ resolution: {integrity: sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==}+ hasBin: true+resolution: {integrity: sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==}engines: {node: '>=14.14'}@@ -16986,9 +17071,17 @@ packages:resolution: {integrity: sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==}hasBin: true+ resolution: {integrity: sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==}+ engines: {node: '>=16'}+resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}+ resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}hasBin: true@@ -17461,6 +17554,10 @@ packages:resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}+ resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-wCQcHkRazgjG5XoAq9jbTMLpNIjoSlZslrJ2+N9MxDsGEv1HnFoVjOCexL0ESva7Y9cu350j+DWADdk54s4AFQ==}engines: {node: '>=12.0.0'}@@ -17506,6 +17603,10 @@ packages:resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}+ resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}+ engines: {node: '>=12'}+resolution: {integrity: sha512-jyuiGJdtvY434z5bUZrjz67v76/ePNvFZTp9Mdz29IlH4+GPsgyGjiv0fKI+M7BdkU6ADjulUcKAd3tUK3WlEw==}engines: {node: '>=10.13.0'}@@ -17523,6 +17624,19 @@ packages:webpack-cli:optional: true+ resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==}+ engines: {node: '>=18'}+ deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation++ resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}@@ -17618,6 +17732,13 @@ packages:resolution: {integrity: sha512-sqMMuL1rc0FmMBOzCpd0yuy9trqF2yTTVe+E9ogwCSWQCdDEtQUwrZPT6AxqtsFGRNxycgncbP/xmOOSPw5ZUw==}engines: {node: '>= 6.0'}+ resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}+resolution: {integrity: sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==}engines: {node: '>=0.4.0'}@@ -17870,6 +17991,14 @@ snapshots:'@alloc/[email protected]': {}+ '@asamuzakjp/[email protected]':+ dependencies:+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-color-parser': 3.1.0(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])+ '@csstools/css-tokenizer': 3.0.4+ lru-cache: 10.4.3+'@aws-crypto/[email protected]':dependencies:'@aws-crypto/sha256-js': 5.2.0@@ -18603,6 +18732,26 @@ snapshots:'@floating-ui/dom': 1.7.6solid-js: 1.9.17+ '@csstools/[email protected]': {}++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])+ '@csstools/css-tokenizer': 3.0.4++ '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':+ dependencies:+ '@csstools/color-helpers': 5.1.0+ '@csstools/css-calc': 2.1.4(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])+ '@csstools/css-parser-algorithms': 3.0.5(@csstools/[email protected])+ '@csstools/css-tokenizer': 3.0.4++ '@csstools/[email protected](@csstools/[email protected])':+ dependencies:+ '@csstools/css-tokenizer': 3.0.4++ '@csstools/[email protected]': {}+'@dagrejs/[email protected]':dependencies:'@dagrejs/graphlib': 2.2.4@@ -26993,6 +27142,11 @@ snapshots:+ dependencies:+ '@asamuzakjp/css-color': 3.2.0+ rrweb-cssom: 0.8.0+@@ -27173,6 +27327,11 @@ snapshots:+ dependencies:+ whatwg-mimetype: 4.0.0+ whatwg-url: 14.2.0+dependencies:call-bound: 1.0.4@@ -28575,6 +28734,10 @@ snapshots:+ dependencies:+ whatwg-encoding: 3.1.1+dependencies:'@selderee/plugin-htmlparser2': 0.11.0@@ -28602,6 +28765,13 @@ snapshots:statuses: 2.0.2toidentifier: 1.0.1+ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color+@@ -28973,6 +29143,8 @@ snapshots:+ [email protected]: {}+@@ -29132,6 +29304,33 @@ snapshots:dependencies:argparse: 2.0.1+ dependencies:+ cssstyle: 4.6.0+ data-urls: 5.0.0+ decimal.js: 10.6.0+ html-encoding-sniffer: 4.0.0+ http-proxy-agent: 7.0.2+ https-proxy-agent: 7.0.6+ is-potential-custom-element-name: 1.0.1+ nwsapi: 2.2.28+ parse5: 7.3.0+ rrweb-cssom: 0.8.0+ saxes: 6.0.0+ symbol-tree: 3.2.4+ tough-cookie: 5.1.2+ w3c-xmlserializer: 5.0.0+ webidl-conversions: 7.0.0+ whatwg-encoding: 3.1.1+ whatwg-mimetype: 4.0.0+ whatwg-url: 14.2.0+ ws: 8.21.0+ xml-name-validator: 5.0.0+ transitivePeerDependencies:+ - bufferutil+ - supports-color+ - utf-8-validate+@@ -30426,6 +30625,8 @@ snapshots:dependencies:boolbase: 1.0.0+ [email protected]: {}+dependencies:citty: 0.1.6@@ -31870,6 +32071,8 @@ snapshots:transitivePeerDependencies:- supports-color+ [email protected]: {}+dependencies:queue-microtask: 1.2.3@@ -31912,6 +32115,10 @@ snapshots:+ dependencies:+ xmlchars: 2.2.0+dependencies:loose-envify: 1.4.0@@ -32662,6 +32869,8 @@ snapshots:react: 18.3.1use-sync-external-store: 1.6.0([email protected])+ [email protected]: {}+@@ -32860,6 +33069,12 @@ snapshots:markdown-it-task-lists: 2.1.1prosemirror-markdown: 1.13.4+ [email protected]: {}++ dependencies:+ tldts-core: 6.1.86+@@ -32872,8 +33087,16 @@ snapshots:+ dependencies:+ tldts: 6.1.86++ dependencies:+ punycode: 2.3.1+@@ -33484,7 +33707,7 @@ snapshots:tsx: 4.21.0yaml: 2.9.1- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -33509,10 +33732,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 20.19.39+ jsdom: 26.1.0transitivePeerDependencies:- msw+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected])@@ -33537,10 +33761,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 20.19.39+ jsdom: 26.1.0transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -33565,10 +33790,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 22.19.7+ jsdom: 26.1.0transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -33593,10 +33819,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 24.12.2+ jsdom: 26.1.0transitivePeerDependencies:- msw+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected])@@ -33621,10 +33848,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 24.12.2+ jsdom: 26.1.0transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -33649,10 +33877,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 26.6.5+ jsdom: 26.1.0transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -33677,10 +33906,11 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 26.6.5+ jsdom: 26.1.0transitivePeerDependencies:- msw+ [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected])([email protected]):dependencies:'@vitest/expect': 4.1.11'@vitest/mocker': 4.1.11([email protected])@@ -33705,11 +33935,16 @@ snapshots:optionalDependencies:'@opentelemetry/api': 1.9.0'@types/node': 26.6.5+ jsdom: 26.1.0transitivePeerDependencies:- msw+ dependencies:+ xml-name-validator: 5.0.0+dependencies:axios: 1.20.0@@ -33759,6 +33994,8 @@ snapshots:+ [email protected]: {}+@@ -33801,6 +34038,17 @@ snapshots:- postcss- uglify-js+ dependencies:+ iconv-lite: 0.6.3++ [email protected]: {}++ dependencies:+ tr46: 5.1.1+ webidl-conversions: 7.0.0+dependencies:tr46: 0.0.3@@ -33913,6 +34161,10 @@ snapshots:dependencies:os-paths: 4.4.0+ [email protected]: {}++ [email protected]: {}+