Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(print): expose the Materialize quote and order endpoints
nirholas06ede33690f0
diff --git a/api/_lib/print-store.js b/api/_lib/print-store.jsindex a70ad0c34..dddd71a5a 100644--- a/api/_lib/print-store.js+++ b/api/_lib/print-store.js@@ -1,486 +1,233 @@// @ts-check-// Materialize order store: the one module that owns a physical print order's-// status.+// The Materialize order state machine: the one module allowed to move a print+// order from one status to the next.//-// An order's status is a state machine. Every surface that moves an order-// (checkout, the operator console, a provider webhook, the reconciliation-// sweep) calls transitionOrder() and nothing else; no handler writes `status`-// directly. Two properties fall out of that and both are load-bearing:+// The database carries the vocabulary as a check constraint so no handler can+// invent a state; the legal MOVES live here, next to the events they emit,+// because a transition is never just a column write. Every accepted move+// appends a print_order_events row (the timeline is that table, never a mutated+// column) and, where the buyer is a signed-in human, publishes one user+// notification. An illegal move throws rather than silently no-ops, because a+// silently ignored transition is how an order goes quiet forever.//-// 1. An illegal move throws instead of corrupting the order. A provider that-// reports "shipped" for a job we never submitted, or a double-clicked-// operator button, is refused at the one place that can see the current-// state.-// 2. The move is atomic. The UPDATE carries `where status = <expected>`, so-// two concurrent callers racing the same transition produce exactly one-// winner and one PrintTransitionError, without a lock or a transaction-// spanning the event insert.+// Reaching `shipped` also issues the order's certificate: the SHA-256 of the+// printed bytes, the edition number, and a Solana memo attesting both+// (api/_lib/print/certificate.js). That side effect is deliberately hung off+// the transition rather than polled, so the certificate exists the moment the+// box does. It is fail-soft: a certificate that cannot attest right now is+// retried by api/cron/print-orders-sync.js, and a shipment is never blocked by+// an RPC having a bad minute.//-// History lives in print_order_events, appended per transition. No column is-// ever mutated to represent the past, so an order's story is reconstructable-// and an operator's note cannot be overwritten by the next status change.+// Scope note for whoever extends this: order creation, quoting and the payment+// path are not here yet. Add them beside `transition()`, not around it.-import { sql, isDbUnavailableError } from './db.js';-import { databaseConfigured } from './env.js';+import { sql } from './db.js';import { publishUserEvent } from './feed.js';+import { issueCertificateForOrder } from './print/certificate.js';+import { assertEditionAvailable } from './print/editions.js';-/** Every status the DB check constraint allows, in lifecycle order. */+/** Every status the print_orders check constraint accepts. */export const PRINT_STATUSES = Object.freeze([- 'created',- 'quoted',- 'paid',- 'screening',- 'submitted',- 'printing',- 'quality_check',- 'shipped',- 'delivered',- 'rejected',- 'canceled',- 'refunded',+ 'created', 'quoted', 'paid', 'screening', 'submitted', 'printing',+ 'quality_check', 'shipped', 'delivered', 'rejected', 'canceled', 'refunded',]);-/** Who caused a transition. Mirrors the print_order_events check constraint. */-export const PRINT_ACTORS = Object.freeze(['system', 'operator', 'provider', 'buyer']);--// The whitelist. Read it as "from → the only places it can go next".-//-// Money-relevant edges, spelled out because they are the ones people get wrong:-// • `paid → screening` is automatic; screening is the fabrication-safety gate-// that runs a second time after payment (00-CONTEXT, order 06).-// • `screening → rejected` is the refusal path. `rejected → refunded` is the-// operator closing it out; the on-chain send itself is owner-gated and-// never happens inside this module.-// • `quality_check → printing` exists because a failed QC is a re-print, not-// a dead order. It is the one backwards edge and it is deliberate.-// • `delivered → refunded` exists because returns happen after delivery.-// Everything else out of `delivered` is closed.-const TRANSITIONS = Object.freeze({- created: ['quoted', 'canceled'],- quoted: ['paid', 'canceled'],- paid: ['screening', 'canceled', 'refunded'],- screening: ['submitted', 'rejected', 'canceled'],- submitted: ['printing', 'canceled', 'rejected'],- printing: ['quality_check', 'canceled', 'rejected'],- quality_check: ['shipped', 'printing', 'rejected'],- shipped: ['delivered', 'refunded'],- delivered: ['refunded'],- rejected: ['refunded'],- canceled: ['refunded'],- refunded: [],+/** Statuses nothing moves out of. */+export const TERMINAL_STATUSES = Object.freeze(['delivered', 'rejected', 'canceled', 'refunded']);++/**+ * The whitelist, as data. Read it as "from this status, only these are legal".+ * Anything absent is illegal, including a same-status write.+ * @type {Readonly<Record<string, readonly string[]>>}+ */+export const LEGAL_TRANSITIONS = Object.freeze({+ created: ['quoted', 'canceled'],+ quoted: ['paid', 'canceled'],+ // A paid order is screened before a provider ever sees it; a failed screen+ // goes to rejected, which is the refund path's entry point.+ paid: ['screening', 'canceled', 'refunded'],+ screening: ['submitted', 'rejected', 'refunded'],+ submitted: ['printing', 'quality_check', 'canceled', 'refunded'],+ printing: ['quality_check', 'refunded'],+ quality_check: ['shipped', 'printing', 'refunded'],+ shipped: ['delivered', 'refunded'],+ delivered: [],+ rejected: ['refunded'],+ canceled: ['refunded'],+ refunded: [],});-/** Statuses from which nothing can move. Terminal in the strict sense. */-export const TERMINAL_STATUSES = Object.freeze(- PRINT_STATUSES.filter((s) => TRANSITIONS[s].length === 0),-);--/**- * Statuses where a fulfillment provider owns the job and the reconciliation- * sweep should keep polling. Matches the print_orders_open_idx partial index.- */-export const OPEN_PROVIDER_STATUSES = Object.freeze([- 'submitted',- 'printing',- 'quality_check',- 'shipped',-]);+/** Who caused a transition. Matches the print_order_events actor constraint. */+export const ACTORS = Object.freeze(['system', 'operator', 'provider', 'buyer']);-/** Thrown when a caller asks for a move the machine does not allow. */-export class PrintTransitionError extends Error {+/** Typed failure so handlers map a cause to a status code. */+export class PrintStoreError extends Error {/**- * @param {string} from- * @param {string} to- * @param {string} [detail]+ * @param {string} code+ * @param {string} message+ * @param {Record<string, unknown>} [extra]*/- constructor(from, to, detail = '') {- super(`illegal print order transition ${from} → ${to}${detail ? `: ${detail}` : ''}`);- this.name = 'PrintTransitionError';- this.code = 'illegal_transition';- this.from = from;- this.to = to;+ constructor(code, message, extra = {}) {+ super(message);+ this.name = 'PrintStoreError';+ this.code = code;+ Object.assign(this, extra);}}-/** Thrown when the order id does not resolve. Separated so handlers can 404. */-export class PrintOrderNotFoundError extends Error {- /** @param {string} orderId */- constructor(orderId) {- super(`print order not found: ${orderId}`);- this.name = 'PrintOrderNotFoundError';- this.code = 'not_found';- this.orderId = orderId;- }-}--/** True when this deployment can persist orders at all. */-export function printStoreEnabled() {- return Boolean(databaseConfigured());-}--/** @param {string} status */-export function isPrintStatus(status) {- return PRINT_STATUSES.includes(status);-}--/** @param {string} status */-export function isTerminalStatus(status) {- return TERMINAL_STATUSES.includes(status);-}--/**- * The moves allowed out of a status. Returns a copy so a caller cannot mutate- * the machine; an unknown status yields an empty list rather than throwing,- * because the console renders this to build its action buttons.- * @param {string} status- * @returns {string[]}- */-export function allowedTransitions(status) {- return [...(TRANSITIONS[status] || [])];-}-/*** @param {string} from* @param {string} to+ * @returns {boolean}*/export function canTransition(from, to) {- return allowedTransitions(from).includes(to);+ return (LEGAL_TRANSITIONS[from] || []).includes(to);}-/**- * Throws PrintTransitionError unless `from → to` is on the whitelist. Exported- * so callers (and tests) can check a move without touching the database.- * @param {string} from- * @param {string} to- */-export function assertTransition(from, to) {- if (!isPrintStatus(to)) throw new PrintTransitionError(from, to, 'unknown status');- if (!canTransition(from, to)) throw new PrintTransitionError(from, to);+/** @param {string} id */+export async function getOrder(id) {+ const [row] = await sql`select * from print_orders where id = ${id} limit 1`;+ return row || null;}-// Columns a transition is allowed to set alongside the status. Anything else a-// caller passes in `patch` is dropped rather than interpolated: this list is-// the whole write surface of a status change, so a provider payload can never-// reach a column nobody vetted.-const PATCHABLE = Object.freeze([- 'provider',- 'provider_order_id',- 'provider_state',- 'tracking_number',- 'carrier',- 'lead_time_days',- 'submitted_at',- 'stall_alerted_at',- 'shipping',-]);--const JSONB_COLUMNS = new Set(['provider_state', 'shipping', 'quote', 'analysis', 'prepared_asset_urls']);--// Literal column expressions for every patchable key. Keeping them as data-// (rather than interpolating `key`) means a future patchable column has to be-// added here on purpose, and a typo fails loudly at import instead of emitting-// a query with an attacker-shaped identifier.-const COLUMN_SQL = Object.freeze({- provider: 'provider',- provider_order_id: 'provider_order_id',- provider_state: 'provider_state',- tracking_number: 'tracking_number',- carrier: 'carrier',- lead_time_days: 'lead_time_days',- submitted_at: 'submitted_at',- stall_alerted_at: 'stall_alerted_at',- shipping: 'shipping',-});--/**- * Build the `set` fragment for the patched columns. Returns null when nothing- * survives the whitelist, which the caller reads as "status only".- * @param {Record<string, unknown>} patch- */-function patchFragment(patch) {- const entries = Object.entries(patch || {}).filter(([k]) => PATCHABLE.includes(k));- if (entries.length === 0) return null;- return entries.reduce((acc, [key, value], i) => {- const bound = JSONB_COLUMNS.has(key) ? JSON.stringify(value ?? {}) : value;- // sql.unsafe is not available on the Neon HTTP driver, and the key here is- // never caller-controlled (it survived the PATCHABLE whitelist above), so- // the column name is spliced by an explicit switch-free lookup instead.- const frag = sql([`, ${COLUMN_SQL[key]} = `, ''], bound);- return i === 0 ? frag : sql(['', ''], acc, frag);- }, null);-}--/** Columns every read returns. Excludes nothing: the console needs all of it. */-const ORDER_COLUMNS = sql([- `id, user_id, payer_wallet, creation_id, source_glb_url, prepared_asset_urls, analysis,- material_id, target_height_mm, quantity, quote, price_usdc, status, provider,- provider_order_id, provider_state, shipping, tracking_number, carrier, lead_time_days,- submitted_at, stall_alerted_at, created_at, updated_at`,-]);--/**- * @param {string} orderId- * @returns {Promise<object|null>}- */-export async function getOrder(orderId) {- if (!printStoreEnabled() || !orderId) return null;- const rows = await sql`select ${ORDER_COLUMNS} from print_orders where id = ${orderId}`;- return rows[0] || null;-}--/**- * Resolve an order by the provider's own identifier. This is how a webhook- * finds the job: a partner knows their id, never ours.- * @param {string} provider- * @param {string} providerOrderId- */-export async function getOrderByProviderId(provider, providerOrderId) {- if (!printStoreEnabled() || !provider || !providerOrderId) return null;- const rows = await sql`- select ${ORDER_COLUMNS} from print_orders- where provider = ${provider} and provider_order_id = ${providerOrderId}`;- return rows[0] || null;+/** The order plus its timeline, oldest first. @param {string} id */+export async function getOrderWithEvents(id) {+ const order = await getOrder(id);+ if (!order) return null;+ const events = await sql`+ select status, note, actor, created_at+ from print_order_events where order_id = ${id} order by created_at asc+ `;+ return { ...order, events };}/**- * The operator queue. `status` may be a single status, a list, or omitted for- * everything. Newest first, which is the order the console renders.- * @param {{ status?: string|string[], limit?: number, offset?: number }} [opts]+ * Append a timeline row. Exported because an operator note about an order that+ * did not change status is still part of its story.+ * @param {{ orderId: string, status: string, note?: string|null, actor?: string, actorId?: string|null }} input*/-export async function listOrders({ status, limit = 50, offset = 0 } = {}) {- if (!printStoreEnabled()) return [];- const statuses = (Array.isArray(status) ? status : status ? [status] : []).filter(isPrintStatus);- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);- const skip = Math.max(Number(offset) || 0, 0);- const where = statuses.length ? sql`where status = any(${statuses})` : sql`where true`;- return sql`- select ${ORDER_COLUMNS} from print_orders- ${where}- order by created_at desc- limit ${cap} offset ${skip}`;-}--/** Per-status counts for the console's queue rail. Returns a plain object. */-export async function countOrdersByStatus() {- if (!printStoreEnabled()) return {};- const rows = await sql`select status, count(*)::int as n from print_orders group by status`;- /** @type {Record<string, number>} */- const out = {};- for (const s of PRINT_STATUSES) out[s] = 0;- for (const r of rows) out[r.status] = r.n;- return out;-}--/**- * The timeline, oldest first: the order in which a human reads a story.- * @param {string} orderId- */-export async function listOrderEvents(orderId) {- if (!printStoreEnabled() || !orderId) return [];- return sql`- select id, order_id, status, note, actor, actor_id, created_at- from print_order_events- where order_id = ${orderId}- order by created_at asc, id asc`;-}--/**- * Append a timeline row without changing the order's status. Used for notes an- * operator leaves on a job that is not moving yet, and for the provider's- * "still printing" heartbeats.- * @param {{ orderId: string, status: string, note?: string, actor?: string, actorId?: string|null }} input- */-export async function appendOrderEvent({ orderId, status, note = '', actor = 'system', actorId = null }) {- if (!printStoreEnabled()) return null;- const safeActor = PRINT_ACTORS.includes(actor) ? actor : 'system';- const rows = await sql`+export async function appendEvent({ orderId, status, note = null, actor = 'system', actorId = null }) {+ const who = ACTORS.includes(actor) ? actor : 'system';+ const [row] = await sql`insert into print_order_events (order_id, status, note, actor, actor_id)- values (${orderId}, ${status}, ${note ? String(note).slice(0, 2000) : null}, ${safeActor}, ${actorId})- returning id, order_id, status, note, actor, actor_id, created_at`;- return rows[0] || null;+ values (${orderId}, ${status}, ${note}, ${who}, ${actorId})+ returning id, status, note, actor, created_at+ `;+ return row;+}++/** Human-readable line for the buyer's notification bell. */+function notificationLine(status) {+ switch (status) {+ case 'paid': return 'Payment received. Your print is queued for screening.';+ case 'screening': return 'Your model is being checked for printability and safety.';+ case 'submitted': return 'Your print has been sent to the production floor.';+ case 'printing': return 'Your print is on the printer.';+ case 'quality_check': return 'Your print is finished and in quality check.';+ case 'shipped': return 'Your print has shipped, with its certificate of authenticity.';+ case 'delivered': return 'Your print was delivered.';+ case 'rejected': return 'Your print could not be produced. A refund is being arranged.';+ case 'canceled': return 'Your print order was canceled.';+ case 'refunded': return 'Your print order was refunded.';+ default: return null;+ }}-// What a buyer is told, per status. A status with no line here is internal-// plumbing the buyer has no reason to see (`screening` is deliberately quiet:-// telling someone their model is being safety-checked invites a fight with a-// gate that has already decided).-const BUYER_NOTICE = Object.freeze({- submitted: 'Your print is with the fulfillment lane.',- printing: 'Your print is on the machine.',- quality_check: 'Your print is finished and in quality check.',- shipped: 'Your print has shipped.',- delivered: 'Your print was delivered.',- rejected: 'Your print order could not be fulfilled.',- canceled: 'Your print order was canceled.',- refunded: 'Your print order was refunded.',-});-/**- * Move an order. The whole write surface of a status change.- *- * Concurrency: the UPDATE matches on the expected current status, so a lost- * race updates zero rows and raises PrintTransitionError with the state the- * winner left behind. Callers that legitimately race (a webhook and the- * reconciliation sweep reporting the same provider event) treat that as a- * no-op, which is why `expect` is separable from `to`.+ * Move an order to a new status.** @param {object} input* @param {string} input.orderId- * @param {string} input.to target status- * @param {string} [input.note] free text stored on the timeline row- * @param {string} [input.actor] system | operator | provider | buyer- * @param {string|null} [input.actorId] the operator's user id, when actor='operator'- * @param {Record<string, unknown>} [input.patch] whitelisted columns to set with the move- * @returns {Promise<{ order: object, event: object|null }>}- */-export async function transitionOrder({ orderId, to, note = '', actor = 'system', actorId = null, patch = {} }) {- if (!printStoreEnabled()) throw new Error('print store requires a configured database');- const current = await getOrder(orderId);- if (!current) throw new PrintOrderNotFoundError(orderId);-- assertTransition(current.status, to);-- const extra = patchFragment(patch);- const rows = await sql`- update print_orders- set status = ${to}${extra || sql([''])}- where id = ${orderId} and status = ${current.status}- returning ${ORDER_COLUMNS}`;-- if (rows.length === 0) {- // Somebody else moved it between our read and our write.- const now = await getOrder(orderId);- throw new PrintTransitionError(current.status, to, `order is now '${now?.status || 'gone'}'`);+ * @param {string} input.to target status+ * @param {string} [input.note] timeline note+ * @param {string} [input.actor] system | operator | provider | buyer+ * @param {string|null} [input.actorId] the operator's user id, when actor is 'operator'+ * @param {Record<string, unknown>} [input.patch] columns to write with the move+ * (tracking_number, carrier, provider, provider_order_id, submitted_at)+ * @returns {Promise<{ order: any, event: any, certificate: any|null }>}+ */+export async function transition({ orderId, to, note = null, actor = 'system', actorId = null, patch = {} }) {+ if (!PRINT_STATUSES.includes(to)) {+ throw new PrintStoreError('unknown_status', `${to} is not a print order status`);+ }+ const order = await getOrder(orderId);+ if (!order) throw new PrintStoreError('order_not_found', `no print order ${orderId}`);+ if (!canTransition(order.status, to)) {+ throw new PrintStoreError(+ 'illegal_transition',+ `a print order cannot go from ${order.status} to ${to}`,+ { from: order.status, to },+ );}- const order = rows[0];- const event = await appendOrderEvent({ orderId, status: to, note, actor, actorId });- notifyBuyer(order, to);- return { order, event };-}--/**- * Tell the buyer, in their notification bell, that their order moved. Silent- * for agent orders (no user id to notify) and for statuses with no buyer-facing- * line. Fire-and-forget by contract: publishUserEvent never throws.- * @param {object} order- * @param {string} status- */-function notifyBuyer(order, status) {- const line = BUYER_NOTICE[status];- if (!line || !order?.user_id) return;- publishUserEvent(order.user_id, {- type: 'print',- status,- order_id: order.id,- message: line,- tracking_number: order.tracking_number || null,- link: `/materialize/orders/${order.id}`,- });-}--/**- * Orders a provider owns that have been quiet longer than their declared lead- * time. The reconciliation sweep's working set.- *- * `graceDays` is added on top of the order's own lead_time_days, so a job is- * only a stall once it is late by a margin, not the moment it hits its- * estimate. Orders already alerted within `realertHours` are excluded, which is- * what stops a stuck job paging the operator every five minutes.- *- * @param {{ graceDays?: number, realertHours?: number, limit?: number }} [opts]- */-export async function listStalledOrders({ graceDays = 2, realertHours = 24, limit = 50 } = {}) {- if (!printStoreEnabled()) return [];- const grace = Math.max(Number(graceDays) || 0, 0);- const realert = Math.max(Number(realertHours) || 0, 0);- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);- return sql`- select ${ORDER_COLUMNS} from print_orders- where status = any(${[...OPEN_PROVIDER_STATUSES]})- and submitted_at is not null- and submitted_at < now() - make_interval(days => (coalesce(lead_time_days, 0) + ${grace})::int)- and (stall_alerted_at is null or stall_alerted_at < now() - make_interval(hours => ${realert}::int))- order by submitted_at asc- limit ${cap}`;-}--/**- * Orders a provider owns, for the reconciliation poll. Unlike listStalledOrders- * this returns everything live, late or not: polling is how we learn a job- * shipped when a webhook was lost.- * @param {{ limit?: number }} [opts]- */-export async function listOpenProviderOrders({ limit = 100 } = {}) {- if (!printStoreEnabled()) return [];- const cap = Math.min(Math.max(Number(limit) || 100, 1), 500);- return sql`- select ${ORDER_COLUMNS} from print_orders- where status = any(${[...OPEN_PROVIDER_STATUSES]})- and provider is not null- and provider_order_id is not null- order by submitted_at asc nulls first- limit ${cap}`;-}+ // Scarcity is enforced where the price is set, so a sold-out edition is+ // refused before a buyer is ever asked for money.+ if (to === 'quoted') {+ await assertEditionAvailable({+ creationId: order.creation_id,+ quantity: order.quantity || 1,+ });+ }-/**- * Record that the operator has been told about a stalled order, so the next- * sweep stays quiet. Deliberately not a transition: nothing about the order's- * lifecycle changed.- * @param {string[]} orderIds- */-export async function markStallAlerted(orderIds) {- if (!printStoreEnabled() || !orderIds?.length) return 0;- const rows = await sql`- update print_orders set stall_alerted_at = now()- where id = any(${orderIds})- returning id`;- return rows.length;-}+ const [updated] = await sql`+ update print_orders set+ status = ${to},+ provider = coalesce(${patch.provider ?? null}, provider),+ provider_order_id = coalesce(${patch.provider_order_id ?? null}, provider_order_id),+ tracking_number = coalesce(${patch.tracking_number ?? null}, tracking_number),+ carrier = coalesce(${patch.carrier ?? null}, carrier),+ lead_time_days = coalesce(${patch.lead_time_days ?? null}, lead_time_days),+ submitted_at = case when ${to} = 'submitted' then coalesce(submitted_at, now()) else submitted_at end,+ stall_alerted_at = null,+ updated_at = now()+ where id = ${orderId} and status = ${order.status}+ returning *+ `;+ // The status guard in the WHERE clause is the concurrency lock: whoever+ // moved the order first wins, and the loser is told what actually happened+ // rather than overwriting it.+ if (!updated) {+ const current = await getOrder(orderId);+ throw new PrintStoreError(+ 'transition_raced',+ `this order moved to ${current?.status} while the change to ${to} was in flight`,+ { from: order.status, to, current: current?.status ?? null },+ );+ }-/**- * Claim a webhook delivery. Returns true exactly once per (provider,- * delivery_id) pair: the insert is the lock, so a provider retrying a delivery- * (every serious one does) cannot append the timeline row twice even if two- * retries land concurrently on two containers.- *- * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input- * @returns {Promise<{ fresh: boolean }>}- */-export async function claimWebhookDelivery({ provider, deliveryId, orderId = null }) {- if (!printStoreEnabled()) throw new Error('webhook idempotency requires a configured database');- const rows = await sql`- insert into print_webhook_deliveries (provider, delivery_id, order_id)- values (${provider}, ${deliveryId}, ${orderId})- on conflict (provider, delivery_id) do nothing- returning delivery_id`;- return { fresh: rows.length > 0 };-}+ const event = await appendEvent({ orderId, status: to, note, actor, actorId });++ let certificate = null;+ if (to === 'shipped') {+ try {+ const issued = await issueCertificateForOrder({ orderId });+ certificate = issued.certificate;+ } catch (err) {+ // A shipment is a physical fact; it is never rolled back because a+ // certificate could not be minted. The sweep picks this up.+ console.error('[print-store] certificate issuance failed for', orderId, err?.message);+ await appendEvent({+ orderId,+ status: to,+ note: `certificate issuance deferred: ${String(err?.message || err).slice(0, 300)}`,+ actor: 'system',+ });+ }+ }-/**- * Mark a claimed delivery as having actually driven a state change, so an- * operator reading the ledger can tell "we saw it and it was a duplicate" from- * "we saw it and it moved the order".- * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input- */-export async function markWebhookApplied({ provider, deliveryId, orderId = null }) {- if (!printStoreEnabled()) return;- await sql`- update print_webhook_deliveries- set applied = true, order_id = coalesce(${orderId}, order_id)- where provider = ${provider} and delivery_id = ${deliveryId}`;-}+ if (updated.user_id) {+ const line = notificationLine(to);+ if (line) {+ publishUserEvent(updated.user_id, {+ type: 'print_update',+ status: to,+ order_id: orderId,+ message: line,+ certificate_id: certificate?.id ?? null,+ link: certificate?.id ? `/cert/${certificate.id}` : `/materialize/orders/${orderId}`,+ });+ }+ }-/** Deliveries recorded for an order, newest first. Diagnostic read. */-export async function listWebhookDeliveries(orderId, limit = 50) {- if (!printStoreEnabled() || !orderId) return [];- const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);- return sql`- select provider, delivery_id, applied, received_at- from print_webhook_deliveries- where order_id = ${orderId}- order by received_at desc- limit ${cap}`;+ return { order: updated, event, certificate };}--export { isDbUnavailableError };diff --git a/api/_lib/print/analyze.js b/api/_lib/print/analyze.jsindex f3aa21072..2c73a6d07 100644--- a/api/_lib/print/analyze.js+++ b/api/_lib/print/analyze.js@@ -3,202 +3,68 @@// Quotes multiply money by `volume_cm3`. The materialize page renders `score`// and its named deductions. The fabrication gate reads the geometry summary.// The operator console shows the frozen copy taken at order time. So this-// module has two hard properties, and both are tested:+// module has two hard properties://-// 1. DETERMINISTIC. The same bytes produce byte-identical numbers. Every-// sample here is taken on a fixed stride, never a random draw, and every-// float that reaches the wire is rounded at a declared precision.+// 1. DETERMINISTIC. The same bytes produce the same numbers. Every sample+// below is a fixed stride, never a random draw, and every float that+// reaches the wire is rounded at a declared precision.// 2. HONEST ABOUT ITS LIMITS. A metric that was sampled rather than-// exhaustively computed says so in `sampling`, and a number the manifold-// kernel could not vouch for is labelled with its `source`. A print-// report that quietly guesses is how a buyer gets a hollow shell they-// paid solid-resin prices for.+// exhaustively computed says so, and a volume the manifold kernel could+// not vouch for is labelled with its source. A report that quietly+// guesses is how a buyer pays solid-resin prices for a hollow shell.//-// Units: glTF geometry is in meters. Everything the report publishes is in-// millimeters, cubic centimeters, or square centimeters, because those are-// the units a print bureau quotes in.+// The geometry itself lives in the modules this composes: topology.js counts+// edges and shells, bvh.js probes walls and self-intersections, and+// manifold-kernel.js is the arbiter of "is this a closed solid, and what is+// its volume". Nothing is re-implemented here.+//+// Units: glTF geometry is meters. Everything published is millimeters, cubic+// centimeters, or square centimeters, because those are the units a print+// bureau quotes in.-import * as THREE from 'three';-import { MeshBVH, ExtendedTriangle } from 'three-mesh-bvh';import { boundsOf, weldPositions } from './mesh-io.js';-import { edgeTopology, connectedShells, signedVolume, surfaceArea } from './topology.js';+import { edgeTopology, connectedShells, dropDegenerate, signedVolume, surfaceArea } from './topology.js';+import { buildBvh, sampleWallThickness, countSelfIntersections } from './bvh.js';import { toSolid } from './manifold-kernel.js';export const REPORT_VERSION = 1;// Weld tolerance in meters. 10 microns is far below any printable feature and// far above the float32 rounding a GLB's POSITION accessor introduces, so it-// closes seams without merging genuinely distinct geometry.+// closes UV seams without merging genuinely distinct geometry. Without it a+// perfectly closed cube exported from any DCC tool reads as 24 vertices whose+// every edge is a hole.const WELD_TOLERANCE_M = 1e-5;-// How many surface points the wall-thickness probe casts from. 2,000 BVH-// raycasts is single-digit milliseconds and is dense enough that a thin-// feature larger than a few percent of the surface cannot hide from it. The-// number is fixed rather than scaled so two analyses of the same mesh agree.+// 2,000 BVH raycasts is single-digit milliseconds and dense enough that a thin+// feature covering more than a fraction of a percent of the surface cannot+// hide. Fixed rather than scaled so two analyses of one mesh agree exactly.const WALL_SAMPLES = 2000;-// Triangle budget for the exhaustive self-intersection scan. Above it the scan-// runs on a deterministic stride and the report says so, because an O(n log n)-// pass over a million triangles is not a request-time operation.-const SELF_INTERSECTION_FULL_LIMIT = 120_000;-const SELF_INTERSECTION_SAMPLES = 40_000;-// Minimum printable wall per material class, millimeters. These are process// limits (what the machine can resolve), not vendor prices, which is why they// live beside the analyzer rather than in the tunable price catalog. The// catalog carries each material's own min wall for quoting; these drive the-// "how big must I print this" recommendation, which exists before any-// material is chosen.-export const CLASS_MIN_WALL_MM = {+// "how big must I print this" recommendation, which exists before any material+// has been chosen.+export const CLASS_MIN_WALL_MM = Object.freeze({resin: 0.6,sls_nylon: 0.8,full_color: 2.0,fdm_draft: 1.2,metal: 1.0,-};+});const round = (v, places) => {+ if (v === null || !Number.isFinite(v)) return null;const f = 10 ** places;return Math.round(v * f) / f;};/**- * Deterministic surface sampling: walk triangles on a fixed stride and probe- * the barycentric point that is offset from the centroid, so a ray never- * leaves exactly along a shared edge (which returns a doubled hit and a- * meaningless distance).- */-function sampleTriangles(triangleCount, wanted) {- const n = Math.min(triangleCount, wanted);- if (n <= 0) return [];- const stride = Math.max(1, Math.floor(triangleCount / n));- const out = [];- for (let t = 0; t < triangleCount && out.length < n; t += stride) out.push(t);- return out;-}--/**- * Wall thickness at a surface point: fire a ray along the inward normal and- * measure the distance to the first back-facing surface it meets. A hit at- * effectively zero distance is the origin triangle itself and is discarded.- *- * Returns the sorted thickness samples in meters.- */-function sampleWallThickness(bvh, positions, indices, triangleIds, diagonal) {- const ray = new THREE.Ray();- const origin = new THREE.Vector3();- const dir = new THREE.Vector3();- const ab = new THREE.Vector3();- const ac = new THREE.Vector3();- const va = new THREE.Vector3();- const vb = new THREE.Vector3();- const vc = new THREE.Vector3();- // Push the ray origin just under the surface so the source triangle is- // behind it. One part in 100,000 of the model diagonal is well below any- // printable feature and well above float precision.- const epsilon = diagonal * 1e-5;- const samples = [];-- for (const t of triangleIds) {- const a = indices[t * 3] * 3;- const b = indices[t * 3 + 1] * 3;- const c = indices[t * 3 + 2] * 3;- va.set(positions[a], positions[a + 1], positions[a + 2]);- vb.set(positions[b], positions[b + 1], positions[b + 2]);- vc.set(positions[c], positions[c + 1], positions[c + 2]);- ab.subVectors(vb, va);- ac.subVectors(vc, va);- dir.crossVectors(ab, ac);- if (dir.lengthSq() === 0) continue;- dir.normalize().negate();- // Barycentric (0.4, 0.35, 0.25): interior, and never the centroid, so a- // symmetric mesh does not concentrate every probe on one axis.- origin- .copy(va)- .multiplyScalar(0.4)- .addScaledVector(vb, 0.35)- .addScaledVector(vc, 0.25)- .addScaledVector(dir, epsilon);- ray.set(origin, dir);- const hit = bvh.raycastFirst(ray, THREE.DoubleSide, 0, diagonal * 2);- if (!hit) continue;- const thickness = hit.distance + epsilon;- if (thickness > epsilon * 2) samples.push(thickness);- }- samples.sort((x, y) => x - y);- return samples;-}--/** Value at a percentile of an ascending sample array. */-function percentile(sorted, p) {- if (sorted.length === 0) return null;- const i = Math.min(sorted.length - 1, Math.max(0, Math.round((p / 100) * (sorted.length - 1))));- return sorted[i];-}--/**- * Count triangle pairs that pass through each other. Adjacent triangles (any- * shared welded vertex) are skipped: they meet by construction and are not a- * defect.- */-function countSelfIntersections(bvh, positions, indices, triangleIds) {- const query = new ExtendedTriangle();- const box = new THREE.Box3();- let count = 0;- const seen = new Set();-- for (const t of triangleIds) {- const ia = indices[t * 3];- const ib = indices[t * 3 + 1];- const ic = indices[t * 3 + 2];- query.a.set(positions[ia * 3], positions[ia * 3 + 1], positions[ia * 3 + 2]);- query.b.set(positions[ib * 3], positions[ib * 3 + 1], positions[ib * 3 + 2]);- query.c.set(positions[ic * 3], positions[ic * 3 + 1], positions[ic * 3 + 2]);- query.needsUpdate = true;- box.makeEmpty().expandByPoint(query.a).expandByPoint(query.b).expandByPoint(query.c);-- bvh.shapecast({- intersectsBounds: (bounds) => bounds.intersectsBox(box),- intersectsTriangle: (other, otherIndex) => {- if (otherIndex === t) return false;- const oa = indices[otherIndex * 3];- const ob = indices[otherIndex * 3 + 1];- const oc = indices[otherIndex * 3 + 2];- if (- oa === ia || oa === ib || oa === ic ||- ob === ia || ob === ib || ob === ic ||- oc === ia || oc === ib || oc === ic- ) {- return false;- }- const key = t < otherIndex ? `${t}:${otherIndex}` : `${otherIndex}:${t}`;- if (seen.has(key)) return false;- if (other.intersectsTriangle(query)) {- seen.add(key);- count += 1;- }- return false;- },- });- }- return count;-}--/**- * Build a BVH over a welded soup. three-mesh-bvh wants a BufferGeometry, and- * its raycasts run in float32, which is why every distance it returns is- * treated as a sample rather than an exact measurement.- */-function buildBvh(positions, indices) {- const geometry = new THREE.BufferGeometry();- geometry.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(positions), 3));- geometry.setIndex(new THREE.BufferAttribute(Uint32Array.from(indices), 1));- return new MeshBVH(geometry);-}--/**- * Score the mesh 0-100 with named, individually explainable deductions. The UI- * renders this list verbatim, so every `detail` string is buyer-readable.+ * Score 0-100 with named, individually explainable deductions. The UI renders+ * this list verbatim, so every `detail` string is buyer-readable and says what+ * the defect means for the printed object rather than naming a mesh property.*/function scoreReport(facts) {const deductions = [];@@ -207,33 +73,33 @@ function scoreReport(facts) {};if (!facts.manifold) {- deduct('non_manifold', 30, 'The surface is not a closed solid, so it has to be reconstructed before printing.');+ deduct('non_manifold', 30, 'The surface is not a closed solid, so it has to be reconstructed before it can be printed.');}if (facts.open_edges > 0) {- // A handful of boundary edges is a small hole; thousands is a mesh that- // is really a surface. Scale the penalty by how much of the perimeter is- // open, capped so it can never dominate the whole score on its own.+ // A handful of boundary edges is a small hole; thousands means the model+ // is really a surface, not an object. Scale by the share of the perimeter+ // that is open, capped so this alone can never dominate the score.const share = facts.edge_count > 0 ? facts.open_edges / facts.edge_count : 0;- deduct('open_edges', Math.min(20, 4 + share * 200), `${facts.open_edges} boundary edges form holes in the surface.`);+ deduct('open_edges', Math.min(20, 4 + share * 200), `${facts.open_edges} boundary edges leave holes in the surface.`);}if (facts.non_manifold_edges > 0) {- deduct('non_manifold_edges', Math.min(12, 3 + facts.non_manifold_edges / 50), `${facts.non_manifold_edges} edges are shared by more than two faces.`);+ deduct('non_manifold_edges', Math.min(12, 3 + facts.non_manifold_edges / 50), `${facts.non_manifold_edges} edges are shared by more than two faces, so the surface has no single inside.`);}if (facts.self_intersections > 0) {deduct('self_intersections', Math.min(15, 5 + facts.self_intersections / 200), `${facts.self_intersections} pairs of faces pass through each other.`);}if (facts.shells > 1) {- deduct('multiple_shells', Math.min(10, 3 + facts.shells), `The model is ${facts.shells} separate bodies, which print as ${facts.shells} loose pieces.`);+ deduct('multiple_shells', Math.min(10, 3 + facts.shells), `The model is ${facts.shells} separate bodies, which arrive as ${facts.shells} loose pieces unless they are joined.`);}if (facts.degenerate_triangles > 0) {- deduct('degenerate_triangles', Math.min(5, facts.degenerate_triangles / 100), `${facts.degenerate_triangles} triangles have zero area.`);+ deduct('degenerate_triangles', Math.min(5, facts.degenerate_triangles / 100), `${facts.degenerate_triangles} triangles have no area and confuse a slicer.`);}if (facts.min_wall_mm !== null && facts.min_wall_mm < CLASS_MIN_WALL_MM.resin) {const ratio = facts.min_wall_mm / CLASS_MIN_WALL_MM.resin;- deduct('thin_walls', Math.min(18, 6 + (1 - ratio) * 12), `The thinnest measured wall is ${facts.min_wall_mm} mm, below the ${CLASS_MIN_WALL_MM.resin} mm a resin printer can hold at this size.`);+ deduct('thin_walls', Math.min(18, 6 + (1 - ratio) * 12), `The thinnest wall measures ${facts.min_wall_mm} mm at this size, under the ${CLASS_MIN_WALL_MM.resin} mm a resin printer can hold. Printing it larger fixes this.`);}if (facts.triangles > 1_000_000) {- deduct('triangle_budget', 4, `${facts.triangles} triangles is heavier than any printer needs; it will be decimated during preparation.`);+ deduct('triangle_budget', 4, `${facts.triangles} triangles is heavier than any printer needs; preparation will decimate it.`);}const total = deductions.reduce((sum, d) => sum + d.points, 0);@@ -241,9 +107,9 @@ function scoreReport(facts) {}/**- * Recommended minimum print height per material class: how tall the object has- * to be printed for its thinnest wall to clear that process's resolution.- * Null when no wall could be measured (an open surface with nothing behind it).+ * How tall the object must be printed for its thinnest wall to clear each+ * process's resolution. Null when no wall could be measured, which happens on+ * an open surface with nothing behind it.*/function recommendedHeights(minWallMm, heightMm) {if (!minWallMm || !heightMm || minWallMm <= 0) return null;@@ -255,73 +121,64 @@ function recommendedHeights(minWallMm, heightMm) {}/**- * Produce the printability report for a loaded mesh.+ * Produce the printability report for a mesh loaded by mesh-io.js.*- * @param {{ positions: Float64Array, indices: Uint32Array, triangleCount: number,- * vertexCount: number, hasTextures: boolean, colorSource: string, sizeBytes: number,- * materials: number, skippedPrimitives: number }} mesh from loadMesh()- * @param {{ sourceUrl?: string|null }} [opts]+ * @param {object} mesh the loadMesh() result+ * @param {{ sourceUrl?: string|null, wallSamples?: number }} [opts]*/export async function analyzeMesh(mesh, opts = {}) {const welded = weldPositions(mesh.positions, mesh.indices, WELD_TOLERANCE_M);- const bounds = boundsOf(welded.positions);- if (!bounds) {- throw new Error('mesh has no finite bounds');+ const cleaned = dropDegenerate(welded.positions, welded.indices);+ const positions = welded.positions;+ const indices = cleaned.indices;++ const bounds = boundsOf(positions);+ if (!bounds || indices.length < 3) {+ throw new Error('mesh has no printable geometry after welding');}- const topology = edgeTopology(welded.indices);- const shellList = connectedShells(welded.indices, topology.edges);- const census = {- openEdges: topology.openEdges,- nonManifoldEdges: topology.nonManifoldEdges,- edgeCount: topology.edgeCount,- degenerateTriangles: 0,- };- const shellInfo = { count: shellList.length };- const triangleCount = welded.indices.length / 3;+ const topology = edgeTopology(indices);+ const shellList = connectedShells(indices, topology.edges);+ const triangleCount = indices.length / 3;// The manifold kernel is the arbiter of "is this a solid". When it accepts// the mesh its volume is exact; when it refuses, the divergence-theorem sum- // over the soup is the best available number and is labelled as such.- let manifold = false;- let volumeM3 = null;+ // over the soup is the best number available and is labelled as such so no+ // downstream reader mistakes an estimate for a measurement.+ let manifoldSolid = false;+ let volumeM3;let volumeSource = 'signed_sum';let genus = null;- const solid = await toSolid(welded.positions, welded.indices);+ const solid = await toSolid(positions, indices);if (solid) {- manifold = true;+ manifoldSolid = true;volumeM3 = Math.abs(solid.volume());volumeSource = 'manifold';genus = solid.genus();solid.delete?.();} else {- volumeM3 = Math.abs(signedVolume(welded.positions, welded.indices));+ volumeM3 = Math.abs(signedVolume(positions, indices));}- const bvh = buildBvh(welded.positions, welded.indices);- const wallIds = sampleTriangles(triangleCount, WALL_SAMPLES);- const wallSamples = sampleWallThickness(bvh, welded.positions, welded.indices, wallIds, bounds.diagonal);-- const fullScan = triangleCount <= SELF_INTERSECTION_FULL_LIMIT;- const siIds = fullScan- ? sampleTriangles(triangleCount, triangleCount)- : sampleTriangles(triangleCount, SELF_INTERSECTION_SAMPLES);- const selfIntersections = countSelfIntersections(bvh, welded.positions, welded.indices, siIds);+ const { geometry, bvh } = buildBvh(positions, indices);+ const walls = sampleWallThickness(+ { positions, indices, bvh },+ { samples: opts.wallSamples ?? WALL_SAMPLES, diagonal: bounds.diagonal },+ );+ const selfIntersections = countSelfIntersections({ positions, indices, bvh, geometry });- const areaM2 = surfaceArea(welded.positions, welded.indices);const heightMm = round(bounds.size[1] * 1000, 2);- const minWallM = percentile(wallSamples, 1);- const minWallMm = minWallM === null ? null : round(minWallM * 1000, 3);- const medianWallMm = wallSamples.length ? round(percentile(wallSamples, 50) * 1000, 3) : null;+ const minWallMm = round(walls.p05 === null ? null : walls.p05 * 1000, 3);+ const medianWallMm = round(walls.median === null ? null : walls.median * 1000, 3);const facts = {- manifold,- shells: shellInfo.count,- open_edges: census.openEdges,- non_manifold_edges: census.nonManifoldEdges,- edge_count: census.edgeCount,- degenerate_triangles: census.degenerateTriangles,- self_intersections: selfIntersections,+ manifold: manifoldSolid,+ shells: shellList.length,+ open_edges: topology.openEdges,+ non_manifold_edges: topology.nonManifoldEdges,+ edge_count: topology.edgeCount,+ degenerate_triangles: cleaned.removed,+ self_intersections: selfIntersections.count,min_wall_mm: minWallMm,triangles: triangleCount,};@@ -329,17 +186,18 @@ export async function analyzeMesh(mesh, opts = {}) {return {version: REPORT_VERSION,- manifold,- watertight: manifold && census.openEdges === 0,- shells: shellInfo.count,- open_edges: census.openEdges,- non_manifold_edges: census.nonManifoldEdges,- degenerate_triangles: census.degenerateTriangles,- self_intersections: selfIntersections,- self_intersections_exhaustive: fullScan,+ manifold: manifoldSolid,+ watertight: manifoldSolid && topology.openEdges === 0,+ shells: shellList.length,+ open_edges: topology.openEdges,+ non_manifold_edges: topology.nonManifoldEdges,+ flipped_edges: topology.flippedEdges,+ degenerate_triangles: cleaned.removed,+ self_intersections: selfIntersections.count,+ self_intersections_scan: selfIntersections.scanned,genus,triangles: triangleCount,- vertices: welded.positions.length / 3,+ vertices: positions.length / 3,source_triangles: mesh.triangleCount,source_vertices: mesh.vertexCount,bbox_mm: {@@ -350,7 +208,7 @@ export async function analyzeMesh(mesh, opts = {}) {},volume_cm3: round(volumeM3 * 1e6, 4),volume_source: volumeSource,- surface_area_cm2: round(areaM2 * 1e4, 3),+ surface_area_cm2: round(surfaceArea(positions, indices) * 1e4, 3),min_wall_mm: minWallMm,median_wall_mm: medianWallMm,recommended_min_height_mm: recommendedHeights(minWallMm, heightMm),@@ -361,10 +219,11 @@ export async function analyzeMesh(mesh, opts = {}) {size_bytes: mesh.sizeBytes ?? null,sampling: {weld_tolerance_mm: round(WELD_TOLERANCE_M * 1000, 4),- wall_rays_requested: WALL_SAMPLES,- wall_rays_hit: wallSamples.length,- wall_percentile: 1,- self_intersection_triangles_scanned: siIds.length,+ wall_rays_cast: walls.samples,+ wall_rays_hit: walls.measured,+ wall_percentile: 5,+ self_intersection_triangles_tested: selfIntersections.tested,+ self_intersection_capped: selfIntersections.capped,},score,deductions,diff --git a/api/_lib/print/quote.js b/api/_lib/print/quote.jsnew file mode 100644index 000000000..3fe411d79--- /dev/null+++ b/api/_lib/print/quote.js@@ -0,0 +1,447 @@+// The Materialize quote engine: the only place a print price is ever computed.+//+// Pure by construction. It takes a printability report (api/_lib/print/analyze.js),+// a material id, a target height, a quantity and a destination, and returns an+// itemization or a named rejection. No I/O, no clock beyond the expiry stamp, no+// database. Every surface that shows a buyer a number reads that number from+// here: the page, the operator console, the x402 challenge and the order row all+// call this function or read the itemization it produced. Nothing recomputes.+//+// Scaling is the heart of it. The analyzer measures the mesh at its native glTF+// size; the buyer chooses a height in millimetres. Volume goes as the cube of the+// scale factor and wall thickness goes linearly, so a figure that is too thin for+// resin at 60 mm is fine at 120 mm and costs eight times as much. Both facts are+// derived here, and both are shown to the buyer rather than being applied behind+// the price.++import { readFileSync } from 'node:fs';+import { createHmac, timingSafeEqual } from 'node:crypto';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';++import { env } from '../env.js';++const HERE = dirname(fileURLToPath(import.meta.url));++// Fields that exist for the owner tuning prices, not for the buyer reading them.+// The public catalog handler and every itemization strip these.+const INTERNAL_KEYS = new Set(['_sources', '_note', '_marginNote', '_quantityNote', '_volumetricNote', 'marginFraction']);++let cached = null;++function catalogPath() {+ // In dev and tests this module sits in api/_lib/print/; in the Cloud Run image+ // the whole repo is present, so the repo-relative path is the reliable one.+ return join(HERE, '..', '..', '..', 'data', 'print-catalog.json');+}++/** The full catalog, including owner-only fields. Read once per process. */+export function loadCatalog({ force = false } = {}) {+ if (!cached || force) cached = JSON.parse(readFileSync(catalogPath(), 'utf8'));+ return cached;+}++function stripInternal(value) {+ if (Array.isArray(value)) return value.map(stripInternal);+ if (value && typeof value === 'object') {+ const out = {};+ for (const [k, v] of Object.entries(value)) {+ if (INTERNAL_KEYS.has(k)) continue;+ out[k] = stripInternal(v);+ }+ return out;+ }+ return value;+}++/** The buyer-facing catalog: same data, minus margin and sourcing notes. */+export function publicCatalog(catalog = loadCatalog()) {+ return stripInternal(catalog);+}++export function findMaterial(materialId, catalog = loadCatalog()) {+ return catalog.materials.find((m) => m.id === materialId) || null;+}++export function findFinish(material, finishId) {+ if (!material) return null;+ if (!finishId) return material.finishes.find((f) => f.default) || material.finishes[0] || null;+ return material.finishes.find((f) => f.id === finishId) || null;+}++/** Destination country to shipping zone, falling back to the zone marked default. */+export function zoneForCountry(country, catalog = loadCatalog()) {+ const code = String(country || '').trim().toUpperCase();+ const zones = catalog.shipping.zones;+ return zones.find((z) => z.countries.includes(code)) || zones.find((z) => z.default) || zones[zones.length - 1];+}++function round(value, places = 2) {+ const f = 10 ** places;+ return Math.round((value + Number.EPSILON) * f) / f;+}++/**+ * What one unit weighs and how much box it takes, at the ordered size. Shipping+ * is charged on whichever is larger, which is why both are computed here rather+ * than in the shipping line.+ */+function unitPhysicals({ report, material, scale, volumeCm3, catalog }) {+ const packMm = catalog.shipping.packagingMm;+ const box = {+ x: report.bbox_mm.x * scale + packMm * 2,+ y: report.bbox_mm.y * scale + packMm * 2,+ z: report.bbox_mm.z * scale + packMm * 2,+ };+ return {+ massGrams: volumeCm3 * material.densityGramsPerCm3,+ boxCm3: (box.x / 10) * (box.y / 10) * (box.z / 10),+ boxMm: { x: round(box.x, 1), y: round(box.y, 1), z: round(box.z, 1) },+ };+}++/**+ * Every reason a mesh cannot be printed in a material, with the fix attached.+ * A rejection that only says "no" makes the buyer guess; each one here names the+ * measured number, the required number, and the action that resolves it.+ */+function constraintFailures({ report, material, targetHeightMm, scale }) {+ const failures = [];+ const scaledWall = report.min_wall_mm === null || report.min_wall_mm === undefined+ ? null+ : report.min_wall_mm * scale;++ if (targetHeightMm < material.minHeightMm) {+ failures.push({+ code: 'below_min_height',+ message: `${material.name} cannot hold detail below ${material.minHeightMm} mm tall.`,+ fix: `Raise the size to at least ${material.minHeightMm} mm.`,+ measured: round(targetHeightMm, 1),+ required: material.minHeightMm,+ });+ }+ if (targetHeightMm > material.maxHeightMm) {+ failures.push({+ code: 'above_max_height',+ message: `${material.name} builds up to ${material.maxHeightMm} mm tall.`,+ fix: `Lower the size to ${material.maxHeightMm} mm or under, or choose a material with a larger bed.`,+ measured: round(targetHeightMm, 1),+ required: material.maxHeightMm,+ });+ }+ const box = material.maxBoundingBoxMm;+ for (const axis of ['x', 'z']) {+ const value = report.bbox_mm[axis] * scale;+ if (value > box[axis]) {+ failures.push({+ code: 'exceeds_build_volume',+ message: `At this size the model is ${round(value, 1)} mm across, over the ${box[axis]} mm build volume for ${material.name}.`,+ fix: 'Reduce the size, or choose a material with a larger build volume.',+ measured: round(value, 1),+ required: box[axis],+ });+ break;+ }+ }+ if (scaledWall !== null && scaledWall < material.minWallMm) {+ failures.push({+ code: 'walls_too_thin',+ message: `The thinnest wall would be ${round(scaledWall, 2)} mm, under the ${material.minWallMm} mm ${material.name} needs.`,+ fix: `Repair thickens thin walls automatically, or print at ${Math.ceil((material.minWallMm / scaledWall) * targetHeightMm)} mm tall or larger.`,+ measured: round(scaledWall, 2),+ required: material.minWallMm,+ });+ }+ if (material.requiresTexture && !report.has_textures) {+ failures.push({+ code: 'no_colour_data',+ message: `${material.name} prints the model's own colours, and this model carries no texture.`,+ fix: 'Choose a single-colour material, or print a textured version of this model.',+ measured: report.color_source || 'none',+ required: 'texture',+ });+ }+ return failures;+}++/**+ * Materials that would accept this mesh at this height. A rejection hands the+ * buyer this list so the next click is a working order rather than a retry.+ */+function alternativesFor({ report, targetHeightMm, catalog, excludeId }) {+ const out = [];+ for (const material of catalog.materials) {+ if (material.id === excludeId) continue;+ const scale = targetHeightMm / report.bbox_mm.y;+ if (constraintFailures({ report, material, targetHeightMm, scale }).length) continue;+ out.push({ id: material.id, name: material.name, class: material.class });+ }+ return out;+}++/**+ * Price a print.+ *+ * @param {object} args+ * @param {object} args.report printability report, version 1+ * @param {string} args.materialId+ * @param {string} [args.finishId]+ * @param {number} args.targetHeightMm+ * @param {number} [args.quantity]+ * @param {string} args.country ISO-3166 alpha-2 destination+ * @param {boolean} [args.hollow] hollow when the material supports it+ * @param {number} [args.holderDiscountBps] from api/_lib/three-tier.js, capped here+ * @returns {{ ok: true, quote: object } | { ok: false, rejection: object }}+ */+export function quotePrint({+ report,+ materialId,+ finishId = null,+ targetHeightMm,+ quantity = 1,+ country,+ hollow = false,+ holderDiscountBps = 0,+ catalog = loadCatalog(),+}) {+ if (!report || report.version !== 1 || !report.bbox_mm?.y || !(report.volume_cm3 > 0)) {+ return { ok: false, rejection: { code: 'invalid_report', message: 'A version-1 printability report with a positive volume is required to quote.', failures: [] } };+ }+ const material = findMaterial(materialId, catalog);+ if (!material) {+ return { ok: false, rejection: { code: 'unknown_material', message: `No material with id "${materialId}".`, failures: [] } };+ }+ const finish = findFinish(material, finishId);+ if (!finish) {+ return { ok: false, rejection: { code: 'unknown_finish', message: `No finish "${finishId}" for ${material.name}.`, failures: [] } };+ }+ const qty = Math.floor(Number(quantity) || 1);+ if (!(qty >= 1 && qty <= 500)) {+ return { ok: false, rejection: { code: 'invalid_quantity', message: 'Quantity must be between 1 and 500.', failures: [] } };+ }+ const height = Number(targetHeightMm);+ if (!(height > 0)) {+ return { ok: false, rejection: { code: 'invalid_height', message: 'A positive target height in millimetres is required.', failures: [] } };+ }++ const scale = height / report.bbox_mm.y;+ const failures = constraintFailures({ report, material, targetHeightMm: height, scale });+ if (failures.length) {+ return {+ ok: false,+ rejection: {+ code: failures[0].code,+ message: failures[0].message,+ failures,+ alternatives: alternativesFor({ report, targetHeightMm: height, catalog, excludeId: material.id }),+ },+ };+ }++ // Volume scales with the cube of the linear scale; surface area with the square.+ const solidVolumeCm3 = report.volume_cm3 * scale ** 3;+ const surfaceCm2 = (report.surface_area_cm2 ?? 0) * scale ** 2;+ const canHollow = Boolean(hollow && material.hollow?.supported);+ // A shell's volume is its surface times its wall thickness, which is the same+ // number the prepare step's erosion produces to within the wall's own curvature.+ // Never above the solid it came from, and never below a floor that keeps a tiny+ // print from quoting as free.+ const hollowVolumeCm3 = canHollow+ ? Math.min(solidVolumeCm3, Math.max(surfaceCm2 * (material.hollow.wallMm / 10), solidVolumeCm3 * 0.15))+ : solidVolumeCm3;+ const volumeCm3 = round(hollowVolumeCm3, 3);++ const physicals = unitPhysicals({ report, material, scale, volumeCm3, catalog });++ const lines = [];+ const setup = round(material.setupFee, 2);+ lines.push({+ id: 'setup',+ label: `Build setup, ${material.name}`,+ detail: 'Machine preparation and file staging, charged once per model.',+ amount: setup,+ });++ const materialAmount = round(material.ratePerCm3 * volumeCm3 * qty, 2);+ lines.push({+ id: 'material',+ label: material.name,+ detail: `${volumeCm3} cm3 at ${material.ratePerCm3.toFixed(2)} USDC per cm3${canHollow ? `, hollowed to a ${material.hollow.wallMm} mm wall` : ''}${qty > 1 ? ` x ${qty}` : ''}.`,+ amount: materialAmount,+ volumeCm3,+ estimate: Boolean(material.rateEstimate),+ });++ const finishAmount = round((finish.fee || 0) * qty, 2);+ if (finishAmount > 0) {+ lines.push({+ id: 'finish',+ label: finish.name,+ detail: qty > 1 ? `Applied to all ${qty} pieces.` : 'Applied after printing.',+ amount: finishAmount,+ });+ }++ const discountable = setup + materialAmount + finishAmount;++ const breaks = catalog.pricing.quantityBreaks+ .filter((b) => qty >= b.minQuantity)+ .sort((a, b) => b.discountBps - a.discountBps);+ let quantityAmount = 0;+ if (breaks.length) {+ quantityAmount = -round((discountable * breaks[0].discountBps) / 10_000, 2);+ lines.push({+ id: 'quantity_break',+ label: `Quantity break, ${breaks[0].minQuantity}+`,+ detail: `One setup and one prepared file serve the whole run, so ${breaks[0].discountBps / 100} percent comes off.`,+ amount: quantityAmount,+ });+ }++ const cappedBps = Math.max(0, Math.min(Number(holderDiscountBps) || 0, catalog.pricing.holderDiscount.maxBps));+ let holderAmount = 0;+ if (cappedBps > 0) {+ holderAmount = -round(((discountable + quantityAmount) * cappedBps) / 10_000, 2);+ lines.push({+ id: 'holder_discount',+ label: `$THREE holder discount, ${cappedBps / 100} percent`,+ detail: 'Applied to setup, material and finish. Shipping is passed through at cost.',+ amount: holderAmount,+ bps: cappedBps,+ });+ }++ const zone = zoneForCountry(country, catalog);+ const volumetricKg = (physicals.boxCm3 * qty) / catalog.shipping.volumetricDivisor;+ const realKg = (physicals.massGrams * qty) / 1000;+ const chargeableKg = Math.max(catalog.shipping.minChargeableKg, volumetricKg, realKg);+ const shippingAmount = round(zone.baseFee + zone.perKg * chargeableKg, 2);+ lines.push({+ id: 'shipping',+ label: `Shipping to ${zone.name}`,+ detail: `${round(chargeableKg, 2)} chargeable kg${volumetricKg > realKg ? ' (volumetric)' : ''}, ${zone.transitDays} days in transit.`,+ amount: shippingAmount,+ zone: zone.id,+ });++ const subtotal = round(lines.reduce((sum, l) => sum + l.amount, 0), 2);+ const minimum = catalog.pricing.minOrderUsdc;+ let total = subtotal;+ if (subtotal < minimum) {+ const topUp = round(minimum - subtotal, 2);+ lines.push({+ id: 'minimum',+ label: 'Order minimum',+ detail: `Every order carries a ${minimum} USDC floor; this one came in under it.`,+ amount: topUp,+ });+ total = minimum;+ }++ const leadTimeDays = material.leadTimeDays + (finish.leadTimeDays || 0) + zone.transitDays;++ return {+ ok: true,+ quote: {+ version: 1,+ currency: catalog.currency,+ chain: catalog.chain,+ material: { id: material.id, name: material.name, class: material.class },+ finish: { id: finish.id, name: finish.name },+ targetHeightMm: round(height, 1),+ quantity: qty,+ hollow: canHollow,+ country: String(country || '').trim().toUpperCase() || null,+ shippingZone: zone.id,+ geometry: {+ scale: round(scale, 6),+ volumeCm3,+ solidVolumeCm3: round(solidVolumeCm3, 3),+ massGramsEach: round(physicals.massGrams, 1),+ boxMm: physicals.boxMm,+ chargeableKg: round(chargeableKg, 2),+ minWallAtSizeMm: report.min_wall_mm === null || report.min_wall_mm === undefined ? null : round(report.min_wall_mm * scale, 2),+ },+ lines,+ subtotal,+ total,+ leadTimeDays,+ quoteOnRequest: Boolean(material.quoteOnRequest),+ estimate: Boolean(material.rateEstimate),+ },+ };+}++// Quote tokens. Same construction and the same secret as the forge job handles:+// an HMAC over a compact payload, prefix-tagged so a token's kind is readable+// before it is verified. The token carries every priced parameter, so checkout+// re-derives what it charges from the token and never from the request body.+const TOKEN_PREFIX = 'pq1';++function sign(payload) {+ return createHmac('sha256', env.JWT_SECRET).update(payload).digest('base64url');+}++/**+ * @param {object} quote the itemization from quotePrint+ * @param {{ reportHash: string, sourceUrl?: string, creationId?: string, ttlSeconds?: number }} context+ */+export function signQuote(quote, context) {+ const ttl = context.ttlSeconds ?? loadCatalog().pricing.quoteTtlSeconds;+ const body = {+ v: 1,+ m: quote.material.id,+ f: quote.finish.id,+ h: quote.targetHeightMm,+ q: quote.quantity,+ w: quote.hollow ? 1 : 0,+ c: quote.country,+ t: quote.total,+ g: quote.geometry.volumeCm3,+ l: quote.leadTimeDays,+ r: context.reportHash,+ u: context.sourceUrl || null,+ i: context.creationId || null,+ exp: Math.floor(Date.now() / 1000) + ttl,+ };+ const payload = Buffer.from(JSON.stringify(body), 'utf8').toString('base64url');+ return `${TOKEN_PREFIX}.${payload}.${sign(payload)}`;+}++/**+ * Verify and decode a quote token. Returns null for anything that is not a+ * currently-valid token this server signed, which is the single check checkout+ * makes before it charges: a tampered price, a stale price and a forged token+ * all fail here identically.+ */+export function verifyQuote(token, { now = Date.now() } = {}) {+ if (typeof token !== 'string' || !token.startsWith(`${TOKEN_PREFIX}.`)) return null;+ const parts = token.split('.');+ if (parts.length !== 3) return null;+ const [, payload, signature] = parts;+ if (!payload || !signature) return null;+ try {+ const expected = Buffer.from(sign(payload), 'utf8');+ const actual = Buffer.from(signature, 'utf8');+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return null;+ const body = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (body.v !== 1 || !body.exp || body.exp * 1000 < now) return null;+ return {+ materialId: body.m,+ finishId: body.f,+ targetHeightMm: body.h,+ quantity: body.q,+ hollow: body.w === 1,+ country: body.c,+ total: body.t,+ volumeCm3: body.g,+ leadTimeDays: body.l,+ reportHash: body.r,+ sourceUrl: body.u,+ creationId: body.i,+ expiresAt: body.exp * 1000,+ };+ } catch {+ return null;+ }+}diff --git a/api/_lib/print/repair.js b/api/_lib/print/repair.jsindex f326db858..dae54c548 100644--- a/api/_lib/print/repair.js+++ b/api/_lib/print/repair.js@@ -1,419 +1,321 @@-// Turn a triangle soup into a solid a printer can fill, then put it at the size-// and wall thickness the buyer paid for.+// Turning a generated mesh into a solid a printer will accept.//-// The pipeline has a strict order because each stage removes a class of defect-// the next one cannot survive:+// The order of operations is the whole design. Cheap topology first, because it+// fixes the failures forge output actually has (UV seams read as holes, mirrored+// duplicate shells, patches wound backwards, an open bottom where the generator+// never closed the base), and it preserves the artist's triangles exactly. Only+// when that is not enough does the voxel reconstruction run, which always+// produces a manifold but resamples the surface and therefore softens detail.//-// 1. weld seams split by UV/normal authoring read as holes-// 2. de-degenerate a zero-area face is a hole the reconstruction cannot close-// 3. orient a mirrored face inverts "inside" for half the shell-// 4. fill holes a centroid fan closes every boundary loop-// 5. reconstruct Manifold takes each closed shell, union merges them-// 6. offset shell the fallback when a shell is still not 2-manifold-//-// Stage 6 exists because "we could not fix it" is not an answer a buyer can-// act on. When a shell has non-manifold junctions that filling cannot resolve-// (self-touching hair, a fan of coincident faces, a Klein-bottle artefact of-// generation), the surface is rebuilt from its distance field as a closed shell-// at a bounded voxel resolution. It costs fidelity and says so in the metrics;-// it never fails.-//-// Every stage returns before/after numbers so the surface can show the buyer-// exactly what the platform changed about their model before they pay for it.+// Every stage records before/after metrics. A repair the buyer cannot see is a+// repair the buyer cannot trust, and the /materialize page renders these numbers+// as the "what changed" list next to the model.++import Module from 'manifold-3d';-import { weldPositions, boundsOf } from './mesh-io.js';+import { boundsOf, weldPositions } from './mesh-io.js';import {+ boundaryLoops,+ connectedShells,dropDegenerate,edgeTopology,- connectedShells,- orientShell,- fillHoles,- extractShell,+ orientConsistently,signedVolume,- triangleArea,+ surfaceArea,} from './topology.js';-import { makeSignedDistance, makeUnsignedDistance } from './sampling.js';+import { buildSignedDistance, extractLevelSet } from './voxel-sdf.js';-// glTF is metres by the spec; every print number a human reads is millimetres.-export const MM_PER_UNIT = 1000;+// Weld tolerance as a fraction of the bounding-box diagonal. Loose enough to+// merge the duplicated vertices a UV seam creates, tight enough to leave two+// genuinely distinct surfaces a hair apart alone.+const WELD_FRACTION = 1e-5;-// Voxel budget for the level-set stages. 250k samples is roughly 2.5 s of BVH-// closest-point work on this runtime, which keeps a fallback repair inside a-// request while still resolving features around 1/60th of the model's height.-const LEVEL_SET_SAMPLES = 250_000;--// A shell smaller than this fraction of the largest shell's triangle count is-// generation debris (a stray quad, an orphaned eyelash) and is dropped rather-// than unioned, which keeps the solid's bounding box honest.-const DEBRIS_SHELL_RATIO = 0.0005;--let modulePromise = null;+let wasmPromise = null;/**- * One initialised Manifold WASM module per process. The library ships plain- * WASM with no native binding, so it loads in the API container exactly as it- * does locally; the async setup is memoised because instantiating the module- * per request would dominate the cost of a small mesh.+ * The Manifold WASM module, initialized once per process. It is plain+ * WebAssembly with no native binding, which is why it runs in the API container+ * at all; the same single-instance pattern the Draco decoders use.*/-export async function manifoldModule() {- if (!modulePromise) {- modulePromise = (async () => {- const mod = await import('manifold-3d');- const factory = mod.default ?? mod;- const wasm = await factory();+export async function getManifold() {+ if (!wasmPromise) {+ wasmPromise = (async () => {+ const wasm = await Module();wasm.setup();return wasm;- })();+ })().catch((err) => {+ wasmPromise = null;+ throw err;+ });}- return modulePromise;+ return wasmPromise;}-export class RepairError extends Error {- constructor(code, message) {- super(message);- this.name = 'RepairError';- this.code = code;+/** Flat arrays out of a Manifold solid, in the representation everything else here speaks. */+export function solidToArrays(solid) {+ const mesh = solid.getMesh();+ const stride = mesh.numProp;+ const count = mesh.vertProperties.length / stride;+ const positions = new Float64Array(count * 3);+ for (let i = 0; i < count; i += 1) {+ positions[i * 3] = mesh.vertProperties[i * stride];+ positions[i * 3 + 1] = mesh.vertProperties[i * stride + 1];+ positions[i * 3 + 2] = mesh.vertProperties[i * stride + 2];}-}--function toManifoldMesh(wasm, positions, indices) {- return new wasm.Mesh({- numProp: 3,- vertProperties: Float32Array.from(positions),- triVerts: Uint32Array.from(indices),- });+ return { positions, indices: Uint32Array.from(mesh.triVerts) };}/**- * Rebuild a closed surface from the distance field of an arbitrary soup.- *- * `level` is what makes it work on open geometry: sampling the UNSIGNED- * distance and extracting the surface at a small positive level produces the- * offset shell around whatever was there, so a single open plane becomes a thin- * closed slab rather than nothing. On geometry that is already closed the- * signed field is used instead, which reproduces the original surface without- * the offset's thickening.+ * Hand a triangle soup to Manifold. Returns null rather than throwing when the+ * soup is not a closed, non-self-intersecting 2-manifold, because "not yet a+ * solid" is the normal case this pipeline exists to fix, not an error.*/-function levelSetSolid(wasm, positions, indices, { closed, bounds, offset }) {- const sample = closed- ? makeSignedDistance(positions, indices)- : makeUnsignedDistance(positions, indices);- const pad = offset * 3;- const min = [bounds.min[0] - pad, bounds.min[1] - pad, bounds.min[2] - pad];- const max = [bounds.max[0] + pad, bounds.max[1] + pad, bounds.max[2] + pad];- const span = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];- const volume = Math.max(span[0] * span[1] * span[2], Number.MIN_VALUE);- // Solve for the edge length that spends the sample budget on this box.- let edge = Math.cbrt(volume / LEVEL_SET_SAMPLES);- edge = Math.min(edge, Math.max(span[0], span[1], span[2]) / 8);- // Manifold's level set takes the field as "positive inside", so an unsigned- // distance is negated and shifted by the offset to give the shell.- const field = closed- ? (p) => -sample(p[0], p[1], p[2])- : (p) => offset - sample(p[0], p[1], p[2]);- const solid = wasm.Manifold.levelSet(field, { min, max }, edge, 0);- return { solid, edge, offset: closed ? 0 : offset };+export function toSolid(wasm, positions, indices) {+ try {+ const mesh = new wasm.Mesh({+ numProp: 3,+ vertProperties: Float32Array.from(positions),+ triVerts: Uint32Array.from(indices),+ });+ const solid = wasm.Manifold.ofMesh(mesh);+ if (solid.status() !== 'NoError' || solid.isEmpty()) return null;+ return solid;+ } catch {+ return null;+ }}/**- * Reconstruct a printable solid from a loaded mesh.- *- * Returns the Manifold solid plus a metrics record describing every change- * made. The caller owns the solid and must delete() it; every intermediate is- * released here.+ * Fan-fill every boundary loop. Each hole gets one new vertex at the loop's+ * centroid and a triangle per rim edge, wound opposite to the rim so the patch+ * agrees with the surface it closes.*- * @param {{positions: Float64Array, indices: Uint32Array}} mesh- * @param {{weldTolerance?: number, fillHoles?: boolean}} [opts]+ * A centroid fan is the right tool here specifically because these holes are+ * generator artifacts (a flat open base, a missing cap) rather than designed+ * openings; it is stable, needs no projection plane, and never produces a+ * self-intersecting patch on a convex rim.*/-export async function reconstruct(mesh, opts = {}) {- const wasm = await manifoldModule();- const sourceBounds = boundsOf(mesh.positions);- if (!sourceBounds || !(sourceBounds.diagonal > 0)) {- throw new RepairError('degenerate_input', 'model has no measurable extent');- }-- // Weld tolerance scales with the model so it behaves the same whether the- // asset was authored in metres, centimetres or arbitrary units.- const tolerance = opts.weldTolerance ?? sourceBounds.diagonal * 1e-6;- const welded = weldPositions(mesh.positions, mesh.indices, tolerance);- const areaEpsilon = (sourceBounds.diagonal * 1e-7) ** 2;- const cleaned = dropDegenerate(welded.positions, welded.indices, areaEpsilon);-- const metrics = {- method: null,- tolerance,- welded_vertices: mesh.positions.length / 3 - welded.positions.length / 3,- degenerate_removed: cleaned.removed,- shells_in: 0,- shells_used: 0,- shells_dropped: 0,- holes_filled: 0,- patch_triangles: 0,- unclosed_loops: 0,- faces_reoriented: 0,- level_set_shells: 0,- level_set_edge_mm: null,- triangles_in: mesh.indices.length / 3,- triangles_out: 0,- };-- if (cleaned.indices.length < 12) {- throw new RepairError('degenerate_input', 'model has no triangles left after cleanup');- }-- const topology = edgeTopology(cleaned.indices);- const shells = connectedShells(cleaned.indices, topology.edges);- metrics.shells_in = shells.length;- const largest = shells[0]?.length ?? 0;-- const solids = [];- for (const tris of shells) {- if (tris.length < largest * DEBRIS_SHELL_RATIO || tris.length < 4) {- metrics.shells_dropped += 1;+export function fillBoundaryLoops(positions, indices) {+ // `unclosed` counts rims that could not be walked into a cycle (one vertex+ // shared by two holes). They are reported, never patched: a fan across a+ // figure-eight rim would cross itself.+ const { loops, unclosed } = boundaryLoops(indices);+ if (!loops.length) return { positions, indices, filled: 0, addedTriangles: 0, unclosedLoops: unclosed };+ const pos = Array.from(positions);+ const tris = Array.from(indices);+ let addedTriangles = 0;+ for (const loop of loops) {+ if (loop.length === 3) {+ tris.push(loop[2], loop[1], loop[0]);+ addedTriangles += 1;continue;}- const oriented = orientShell(welded.positions, cleaned.indices, tris);- metrics.faces_reoriented += oriented.flipped;- let shell = extractShell(welded.positions, oriented.indices);- if (opts.fillHoles !== false) {- const filled = fillHoles(shell.positions, shell.indices);- metrics.holes_filled += filled.filled;- metrics.patch_triangles += filled.addedTriangles;- metrics.unclosed_loops += filled.unclosedLoops;- shell = { positions: filled.positions, indices: filled.indices };- }- let solid = null;- try {- const mm = toManifoldMesh(wasm, shell.positions, shell.indices);- mm.merge();- solid = wasm.Manifold.ofMesh(mm);- if (solid.status() !== 0 || solid.isEmpty()) {- solid.delete();- solid = null;- }- } catch {- solid = null;+ let cx = 0, cy = 0, cz = 0;+ for (const v of loop) {+ cx += positions[v * 3];+ cy += positions[v * 3 + 1];+ cz += positions[v * 3 + 2];}- if (!solid) {- // Still not 2-manifold after filling: rebuild it from its distance- // field. Never a failure path, only a lower-fidelity one.- const shellBounds = boundsOf(shell.positions);- const closed = signedVolume(shell.positions, shell.indices) !== 0 && edgeTopology(shell.indices).openEdges === 0;- const offset = shellBounds.diagonal * 0.004;- const built = levelSetSolid(wasm, shell.positions, shell.indices, {- closed,- bounds: shellBounds,- offset,- });- metrics.level_set_shells += 1;- metrics.level_set_edge_mm = Math.max(- metrics.level_set_edge_mm ?? 0,- built.edge * MM_PER_UNIT,- );- solid = built.solid;- if (solid.isEmpty()) {- solid.delete();- metrics.shells_dropped += 1;- continue;- }+ const center = pos.length / 3;+ pos.push(cx / loop.length, cy / loop.length, cz / loop.length);+ for (let i = 0; i < loop.length; i += 1) {+ const u = loop[i];+ const v = loop[(i + 1) % loop.length];+ tris.push(v, u, center);+ addedTriangles += 1;}- solids.push(solid);- metrics.shells_used += 1;}+ return {+ positions: Float64Array.from(pos),+ indices: Uint32Array.from(tris),+ filled: loops.length,+ addedTriangles,+ unclosedLoops: unclosed,+ };+}- if (solids.length === 0) {- throw new RepairError('unrepairable', 'no shell of this model could be closed into a solid');- }+/**+ * The cheap repair: weld, drop what cannot hold volume, agree on a winding,+ * close the holes, and make the whole thing point outward. Pure topology, no+ * resampling, so the surface a buyer approved is the surface that prints.+ */+export function cleanTopology(mesh, opts = {}) {+ const bounds = boundsOf(mesh.positions);+ const tolerance = opts.weldTolerance ?? Math.max((bounds?.diagonal ?? 1) * WELD_FRACTION, Number.EPSILON);- // Union rather than compose: two shells that overlap in space are one object- // to a printer, and the boolean is what removes the internal wall between- // them. A single shell skips the boolean entirely.- let solid = solids[0];- if (solids.length > 1) {- solid = wasm.Manifold.union(solids);- for (const s of solids) s.delete();+ const welded = weldPositions(mesh.positions, mesh.indices, tolerance);+ const cleaned = dropDegenerate(welded.positions, welded.indices, (tolerance * tolerance) / 2);+ const oriented = orientConsistently(cleaned.indices);+ const before = edgeTopology(oriented.indices);+ const filled = fillBoundaryLoops(welded.positions, oriented.indices);+ const after = edgeTopology(filled.indices);++ // Winding is only consistent per component after orientConsistently; a+ // negative total signed volume means the biggest shell points inward.+ let indices = filled.indices;+ let volume = signedVolume(filled.positions, indices);+ let flippedAll = false;+ if (volume < 0) {+ const flipped = Uint32Array.from(indices);+ for (let i = 0; i + 2 < flipped.length; i += 3) {+ const b = flipped[i + 1];+ flipped[i + 1] = flipped[i + 2];+ flipped[i + 2] = b;+ }+ indices = flipped;+ volume = -volume;+ flippedAll = true;}- metrics.method = metrics.level_set_shells > 0 ? 'level_set' : 'manifold_union';- metrics.triangles_out = solid.numTri();- return { solid, metrics, wasm };++ return {+ positions: filled.positions,+ indices,+ metrics: {+ weldTolerance: tolerance,+ mergedVertices: mesh.positions.length / 3 - welded.positions.length / 3,+ degenerateRemoved: cleaned.degenerate,+ duplicateRemoved: cleaned.duplicate,+ trianglesFlipped: oriented.flipped,+ shellReversed: flippedAll,+ holesFilled: filled.filled,+ patchTriangles: filled.addedTriangles,+ unclosedLoops: filled.unclosedLoops ?? 0,+ openEdgesBefore: before.openEdges,+ openEdgesAfter: after.openEdges,+ nonManifoldEdgesAfter: after.nonManifoldEdges,+ signedVolume: volume,+ },+ };}/**- * Uniformly scale a solid so its Y extent (glTF is Y-up) matches the requested- * print height. Returns the new solid and the scale that was applied; the- * caller keeps the factor because every wall-thickness number measured before- * the scale must be multiplied by it.+ * Uniform scale about the mesh's own centre, then a translation that puts the+ * base on z=0 of nothing in particular; callers that need a print bed origin+ * do that in the exporter, where the up-axis convention belongs.*/-export function scaleToHeight(wasm, solid, targetHeightMm) {- const box = solid.boundingBox();- const heightUnits = box.max[1] - box.min[1];- if (!(heightUnits > 0)) {- throw new RepairError('degenerate_input', 'model has zero height and cannot be scaled');- }- const factor = targetHeightMm / (heightUnits * MM_PER_UNIT);- const scaled = solid.scale([factor, factor, factor]);- return { solid: scaled, factor };+export function scaleMesh(positions, factor) {+ const out = new Float64Array(positions.length);+ for (let i = 0; i < positions.length; i += 1) out[i] = positions[i] * factor;+ return out;}/**- * Hollow a solid into a shell of `wallMm`, with drain holes.+ * Full repair. Returns a solid whenever one can be produced, plus the metrics+ * describing how it was reached and which path ran.*- * Resin is sold by volume, so hollowing a 150 mm figurine typically removes 80%- * of its material cost. It is only safe when the wall survives the erosion- * everywhere, so the caller passes the measured minimum wall and this refuses- * (with a reason, never silently) when the model is already thinner than twice- * the requested wall.- *- * Drain holes are mandatory, not optional: a sealed resin shell traps uncured- * liquid, which is both a print failure and a chemical hazard in the box. Two- * holes are cut on the underside so the cavity can vent as it drains.+ * `strategy` is reported, never guessed at by the caller:+ * 'already-solid' the input was already a closed manifold+ * 'topology' welding, hole filling and re-winding were enough+ * 'reconstructed' the voxel level set had to rebuild the surface*/-export function hollowSolid(wasm, solid, { wallMm, minWallMm, drainHoleMm = 3.5 }) {- const box = solid.boundingBox();- const size = [box.max[0] - box.min[0], box.max[1] - box.min[1], box.max[2] - box.min[2]];- const sizeMm = size.map((v) => v * MM_PER_UNIT);- const reason = (code, message) => ({ solid: null, applied: false, code, message });+export async function repairMesh(mesh, opts = {}) {+ const wasm = opts.wasm || (await getManifold());+ const started = Date.now();+ const cleaned = cleanTopology(mesh, opts);- if (!(wallMm > 0)) return reason('invalid_wall', 'hollow wall thickness must be positive');- if (Math.min(...sizeMm) < wallMm * 6) {- return reason(- 'too_small',- `model is ${Math.min(...sizeMm).toFixed(1)} mm across its thinnest axis, too small to hollow at a ${wallMm} mm wall`,- );- }- if (Number.isFinite(minWallMm) && minWallMm > 0 && minWallMm < wallMm * 2) {- return reason(- 'too_thin',- `thinnest wall is ${minWallMm.toFixed(2)} mm, so a ${wallMm} mm hollow would break through it`,- );- }+ let solid = toSolid(wasm, cleaned.positions, cleaned.indices);+ let strategy = solid ? (cleaned.metrics.holesFilled === 0 && cleaned.metrics.degenerateRemoved === 0 ? 'already-solid' : 'topology') : null;+ let reconstruction = null;- const wallUnits = wallMm / MM_PER_UNIT;- const mesh = solid.getMesh();- const positions = Float64Array.from(mesh.vertProperties);- const indices = Uint32Array.from(mesh.triVerts);- // Strip the extra properties Manifold may carry per vertex: the distance- // field only reads positions.- const stride = mesh.numProp;- let plain = positions;- if (stride !== 3) {- plain = new Float64Array((positions.length / stride) * 3);- for (let i = 0, o = 0; i < positions.length; i += stride, o += 3) {- plain[o] = positions[i];- plain[o + 1] = positions[i + 1];- plain[o + 2] = positions[i + 2];+ if (!solid) {+ // Topology could not save it: overlapping shells, edges shared by three+ // faces, or holes whose rims do not close. Resample instead. This always+ // produces a printable solid, at the cost of the original triangulation.+ const field = buildSignedDistance(cleaned.positions, cleaned.indices, {+ maxCells: opts.maxGridCells,+ });+ const extracted = extractLevelSet(wasm, field, { maxSamples: opts.maxSamples });+ if (extracted.solid.isEmpty()) {+ throw new Error('mesh could not be reconstructed into a printable solid');}+ solid = extracted.solid;+ strategy = 'reconstructed';+ reconstruction = { gridDims: field.dims, edgeLength: extracted.edgeLength };}- const sample = makeSignedDistance(plain, indices);- const min = [box.min[0], box.min[1], box.min[2]];- const max = [box.max[0], box.max[1], box.max[2]];- const volume = Math.max(size[0] * size[1] * size[2], Number.MIN_VALUE);- let edge = Math.cbrt(volume / LEVEL_SET_SAMPLES);- // The cavity wall must be resolvable by the grid or the erosion tears.- edge = Math.min(edge, wallUnits / 1.5);- const core = wasm.Manifold.levelSet(- (p) => -(sample(p[0], p[1], p[2]) + wallUnits),- { min, max },- edge,- 0,- );- if (core.isEmpty()) {- core.delete();- return reason('no_cavity', `a ${wallMm} mm wall leaves no cavity to remove in this model`);- }-- // Two drains through the base: a single hole airlocks and will not drain.- const holeRadius = drainHoleMm / 2 / MM_PER_UNIT;- const holeDepth = size[1] * 0.5;- const offsets = [- [box.min[0] + size[0] * 0.3, box.min[2] + size[2] * 0.5],- [box.min[0] + size[0] * 0.7, box.min[2] + size[2] * 0.5],- ];- const drains = offsets.map(([x, z]) => {- const cyl = wasm.Manifold.cylinder(holeDepth, holeRadius, holeRadius, 24, false);- return cyl.translate([x, box.min[1] - holeDepth * 0.05, z]);- });- const cavity = wasm.Manifold.union([core, ...drains]);- const shell = solid.subtract(cavity);- const solidVolume = solid.volume();- const shellVolume = shell.volume();- core.delete();- for (const d of drains) d.delete();- cavity.delete();-- if (!(shellVolume > 0) || shell.isEmpty()) {- shell.delete();- return reason('hollow_failed', 'hollowing produced no printable shell');- }+ const arrays = solidToArrays(solid);+ const components = connectedShells(arrays.indices, edgeTopology(arrays.indices).edges);return {- solid: shell,- applied: true,- wall_mm: wallMm,- drain_holes: drains.length,- drain_hole_mm: drainHoleMm,- volume_saved_ratio: solidVolume > 0 ? 1 - shellVolume / solidVolume : 0,- voxel_mm: edge * MM_PER_UNIT,+ wasm,+ solid,+ positions: arrays.positions,+ indices: arrays.indices,+ strategy,+ metrics: {+ ...cleaned.metrics,+ strategy,+ reconstruction,+ trianglesBefore: mesh.indices.length / 3,+ trianglesAfter: arrays.indices.length / 3,+ shells: components.length,+ volume: solid.volume(),+ surfaceArea: solid.surfaceArea(),+ genus: solid.genus(),+ elapsedMs: Date.now() - started,+ },};}/**- * Reduce a solid to a triangle budget. Manifold's own simplify is tolerance- * based, so the tolerance is searched (a handful of doublings) until the mesh- * fits, which keeps the geometric error the smallest one that meets the budget- * rather than an arbitrary constant.+ * Hollow a solid to a wall thickness, with drain holes.+ *+ * Resin is sold by volume, so a hollow print of a 10 cm figure can cost a third+ * of the solid one. The erosion is a level-set offset of the solid's own+ * distance field; the two drain holes are mandatory, not decorative, because a+ * sealed resin shell traps uncured liquid and can burst under the vat's suction.+ *+ * Returns `{ solid, hollowed: false, reason }` rather than throwing when the+ * geometry cannot take it: a thin ornament with no interior to remove is+ * printed solid, and the buyer is quoted for a solid.*/-export function decimateSolid(solid, budget) {- const before = solid.numTri();- if (!Number.isFinite(budget) || budget <= 0 || before <= budget) {- return { solid, applied: false, triangles_before: before, triangles_after: before };- }- const box = solid.boundingBox();- const diagonal = Math.hypot(- box.max[0] - box.min[0],- box.max[1] - box.min[1],- box.max[2] - box.min[2],- );- let tolerance = diagonal * 1e-5;- let current = solid;- let applied = false;- for (let step = 0; step < 12; step += 1) {- const next = current.simplify(tolerance);- if (applied) current.delete();- current = next;- applied = true;- if (current.numTri() <= budget) break;- tolerance *= 2;+export function hollowSolid(wasm, solid, { wallThickness, drainRadius, maxSamples } = {}) {+ if (!(wallThickness > 0)) return { solid, hollowed: false, reason: 'no-wall-thickness' };+ const arrays = solidToArrays(solid);+ const bounds = boundsOf(arrays.positions);+ if (!bounds) return { solid, hollowed: false, reason: 'empty' };+ // Nothing to gain when the wall is most of the object.+ if (wallThickness * 6 > bounds.longest) {+ return { solid, hollowed: false, reason: 'too-small-to-hollow' };}- return {- solid: current,- applied,- tolerance,- triangles_before: before,- triangles_after: current.numTri(),- };-}-/** Manifold solid to the plain indexed soup every exporter in this directory reads. */-export function solidToMesh(solid) {- const mesh = solid.getMesh();- const stride = mesh.numProp;- const source = mesh.vertProperties;- const count = source.length / stride;- const positions = new Float64Array(count * 3);- for (let i = 0; i < count; i += 1) {- positions[i * 3] = source[i * stride];- positions[i * 3 + 1] = source[i * stride + 1];- positions[i * 3 + 2] = source[i * stride + 2];+ const field = buildSignedDistance(arrays.positions, arrays.indices);+ const eroded = extractLevelSet(wasm, field, { level: wallThickness, maxSamples });+ if (eroded.solid.isEmpty()) {+ return { solid, hollowed: false, reason: 'no-interior-at-this-wall-thickness' };}- return { positions, indices: Uint32Array.from(mesh.triVerts) };-}-/** Total area of an indexed soup, used for the print-time surface estimate. */-export function meshArea(positions, indices) {- let total = 0;- for (let i = 0; i + 2 < indices.length; i += 3) {- total += triangleArea(positions, indices[i], indices[i + 1], indices[i + 2]);+ const shell = solid.subtract(eroded.solid);+ if (shell.isEmpty() || shell.status() !== 'NoError') {+ return { solid, hollowed: false, reason: 'shell-subtraction-failed' };}- return total;++ // Two drain holes on the lowest face, offset from each other so the resin has+ // somewhere to leave and air somewhere to enter.+ const r = drainRadius ?? Math.max(wallThickness * 1.5, bounds.longest * 0.012);+ const depth = bounds.size[1] * 0.5;+ const punch = (x, z) =>+ wasm.Manifold.cylinder(depth, r, r, 24, true).translate([+ bounds.center[0] + x,+ bounds.min[1] + depth * 0.25,+ bounds.center[2] + z,+ ]);+ const offset = Math.max(r * 2.5, bounds.longest * 0.05);+ const drained = shell.subtract(punch(-offset, 0)).subtract(punch(offset, 0));+ const finalSolid = drained.isEmpty() || drained.status() !== 'NoError' ? shell : drained;++ return {+ solid: finalSolid,+ hollowed: true,+ reason: null,+ metrics: {+ solidVolume: solid.volume(),+ hollowVolume: finalSolid.volume(),+ wallThickness,+ drainHoles: finalSolid === shell ? 0 : 2,+ drainRadius: r,+ },+ };}++/** Analytic helpers the quote engine and the report share. */+export const geometry = { boundsOf, signedVolume, surfaceArea };diff --git a/api/_lib/print/topology.js b/api/_lib/print/topology.jsindex cf6a7b465..220d01b3e 100644--- a/api/_lib/print/topology.js+++ b/api/_lib/print/topology.js@@ -37,22 +37,85 @@ function edgeKey(a, b) {*/export function dropDegenerate(positions, indices, areaEpsilon = 0) {const kept = [];- let removed = 0;+ // The two causes are counted apart because they mean different things about+ // the source: a repeated corner is a sliver the weld collapsed, a zero-area+ // face is geometry the generator emitted flat. A repair report that merges+ // them cannot tell a buyer which one happened to their model.+ let duplicate = 0;+ let degenerate = 0;for (let i = 0; i + 2 < indices.length; i += 3) {const a = indices[i];const b = indices[i + 1];const c = indices[i + 2];if (a === b || b === c || a === c) {- removed += 1;+ duplicate += 1;continue;}if (areaEpsilon > 0 && triangleArea(positions, a, b, c) <= areaEpsilon) {- removed += 1;+ degenerate += 1;continue;}kept.push(a, b, c);}- return { indices: Uint32Array.from(kept), removed };+ return {+ indices: Uint32Array.from(kept),+ removed: duplicate + degenerate,+ duplicate,+ degenerate,+ };+}++/**+ * Whole-mesh winding agreement. Same propagation as orientShell, but it works+ * on the full index buffer and takes no positions, so it is the pass to run+ * before anything has been split into shells or measured for volume: it makes+ * neighbours agree, and leaves the question of which way is "out" to the caller+ * that has the geometry to answer it.+ *+ * Every connected patch is seeded independently, so a mesh whose parts do not+ * touch still comes back internally consistent within each part.+ */+export function orientConsistently(indices) {+ const out = Uint32Array.from(indices);+ const { edges } = edgeTopology(out);+ const triCount = out.length / 3;+ const visited = new Uint8Array(triCount);+ let flipped = 0;+ for (let seed = 0; seed < triCount; seed += 1) {+ if (visited[seed]) continue;+ visited[seed] = 1;+ const stack = [seed];+ while (stack.length) {+ const t = stack.pop();+ const a = out[t * 3];+ const b = out[t * 3 + 1];+ const c = out[t * 3 + 2];+ const corners = [+ [a, b],+ [b, c],+ [c, a],+ ];+ for (const [u, v] of corners) {+ const list = edges.get(edgeKey(u, v));+ if (!list || list.length !== 2) continue;+ const other = list[0] === t ? list[1] : list[0];+ if (visited[other]) continue;+ visited[other] = 1;+ const oa = out[other * 3];+ const ob = out[other * 3 + 1];+ const oc = out[other * 3 + 2];+ const sameDirection =+ (oa === u && ob === v) || (ob === u && oc === v) || (oc === u && oa === v);+ if (sameDirection) {+ out[other * 3 + 1] = oc;+ out[other * 3 + 2] = ob;+ flipped += 1;+ }+ stack.push(other);+ }+ }+ }+ return { indices: out, flipped };}export function triangleArea(positions, a, b, c) {diff --git a/api/print/certs/[id].js b/api/print/certs/[id].jsnew file mode 100644index 000000000..2a5987d65--- /dev/null+++ b/api/print/certs/[id].js@@ -0,0 +1,51 @@+/**+ * GET /api/print/certs/:id — one Materialize certificate, publicly readable.+ *+ * A certificate is a public proof by design: the QR printed on the box has to+ * resolve for whoever is holding the box, which is frequently not the buyer and+ * never a signed-in session. So this endpoint takes no credentials and returns+ * no PII: no shipping address, no buyer, no order id beyond the certificate's+ * own identity.+ *+ * One field is conditional. A print of a PRIVATE forge creation renders its+ * certificate in full (the holder owns the object and deserves the proof) but+ * withholds the prompt, which is the creator's, and reports+ * `creation.prompt_withheld: true` so the page can say so instead of showing a+ * blank where the lineage should be.+ *+ * The response carries the raw `memo` string that was signed on-chain, so a+ * verifier can compare hashes without trusting this endpoint, this database, or+ * any block explorer.+ */++import { cors, json, method, wrap, rateLimited } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { getPublicCertificate, CERT_ID_RE } from '../../_lib/print/certificate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://localhost');+ const raw = url.searchParams.get('id') || '';+ const id = String(raw).trim().toLowerCase();+ if (!CERT_ID_RE.test(id)) {+ return json(res, 400, { error: 'invalid certificate id' });+ }++ const certificate = await getPublicCertificate(id);+ if (!certificate) {+ return json(res, 404, { error: 'certificate not found' });+ }++ // Certificates are immutable except for the attestation landing, so a short+ // public cache is safe and keeps a scanned QR fast on a phone network.+ return json(res, 200, { certificate }, {+ 'cache-control': certificate.solana_signature+ ? 'public, max-age=300, s-maxage=3600'+ : 'public, max-age=15, s-maxage=15',+ });+});diff --git a/api/print/editions.js b/api/print/editions.jsnew file mode 100644index 000000000..b95512a03--- /dev/null+++ b/api/print/editions.js@@ -0,0 +1,81 @@+/**+ * Edition scarcity for a forge model.+ *+ * GET /api/print/editions?creation_id=<uuid>+ * → { edition: { limit, issued, remaining, soldOut } } (public)+ * POST /api/print/editions { creation_id, edition_of }+ * → { edition } (creator only)+ *+ * `edition_of: null` is an open edition and is every model's default. A number+ * caps how many physical copies may ever exist; the cap is enforced when a+ * print is quoted (so a sold-out model never takes money) and frozen onto each+ * certificate at ship time (so a later change cannot rewrite what a shipped+ * certificate already promised).+ *+ * A cap below what has already shipped is refused rather than clamped: an+ * edition cannot be shrunk under its own history.+ */++import { cors, json, method, wrap, rateLimited, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';+import { getSessionUser } from '../_lib/auth.js';+import { hashClient } from '../_lib/forge-store.js';+import { editionState, setEditionLimit, PrintEditionError } from '../_lib/print/editions.js';++const STATUS_BY_CODE = {+ creation_not_found: 404,+ not_creation_owner: 403,+ edition_limit_invalid: 400,+ edition_limit_out_of_range: 400,+ edition_limit_below_issued: 409,+ series_key_underivable: 400,+};++function clientKeyFrom(req) {+ const raw = req.headers['x-forge-client'];+ const header = Array.isArray(raw) ? raw[0] : raw;+ return header ? hashClient(header) : null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ try {+ if (req.method === 'GET') {+ const url = new URL(req.url, 'http://localhost');+ const creationId = url.searchParams.get('creation_id') || '';+ if (!isUuid(creationId)) return json(res, 400, { error: 'invalid creation_id' });+ return json(res, 200, { edition: await editionState({ creationId }) });+ }++ const body = await readJson(req);+ const creationId = String(body?.creation_id || '');+ if (!isUuid(creationId)) return json(res, 400, { error: 'invalid creation_id' });++ const user = await getSessionUser(req, res);+ const clientKey = clientKeyFrom(req);+ if (!user && !clientKey) {+ return json(res, 401, { error: 'sign in to set the edition size for your model' });+ }++ const edition = await setEditionLimit({+ creationId,+ userId: user?.id ?? null,+ clientKey,+ limit: Object.prototype.hasOwnProperty.call(body || {}, 'edition_of')+ ? body.edition_of+ : body?.limit,+ });+ return json(res, 200, { edition });+ } catch (err) {+ if (err instanceof PrintEditionError) {+ return json(res, STATUS_BY_CODE[err.code] || 400, { error: err.message, code: err.code });+ }+ throw err;+ }+});diff --git a/api/print/ops/[action].js b/api/print/ops/[action].jsnew file mode 100644index 000000000..36b2a7753--- /dev/null+++ b/api/print/ops/[action].js@@ -0,0 +1,362 @@+// @ts-check+// Materialize operator console API: /api/print/ops/{queue,order,transition,+// submit,tracking,cancel,refund,adapters}.+//+// This is the working surface of the manual fulfillment lane. A human takes a+// paid, screened order off the queue here, hands the prepared files to a print+// bureau, and reports back what happened; every report is a transition through+// api/_lib/print-store.js, attributed to them on the order's timeline.+//+// AUTHORIZATION: every action calls requireOperator() before it reads anything.+// The page at /materialize/ops is a client of this API, never a gate in front+// of it. The gate fails closed in development too, because these responses+// carry shipping addresses.+//+// MONEY: `refund` marks the order refunded and records who decided it. It does+// NOT move funds. Sending USDC is a CLAUDE.md gate-1 action and stays with the+// owner, so the response renders the exact recipient and amount for them to+// execute and the timeline carries the decision either way.++import { error, json, method, readJson, wrap } from '../../_lib/http.js';+import { sql } from '../../_lib/db.js';+import { requireOperator } from '../../_lib/print/ops-auth.js';+import {+ PrintOrderNotFoundError,+ PrintTransitionError,+ allowedTransitions,+ appendOrderEvent,+ countOrdersByStatus,+ getOrder,+ listOrderEvents,+ listOrders,+ listWebhookDeliveries,+ printStoreEnabled,+ transitionOrder,+} from '../../_lib/print-store.js';+import { adapterSummaries } from '../../_lib/print/adapters/index.js';+import { FulfillmentError, cancelWithProvider, submitOrder } from '../../_lib/print/fulfillment.js';+import { AdapterContractError, AdapterUpstreamError } from '../../_lib/print/adapters/contract.js';+import { notifyOperators } from '../../_lib/print/ops-notify.js';++/** Guard shared by every action: no database, no console. */+function requireStore(res) {+ if (printStoreEnabled()) return true;+ error(res, 503, 'not_configured', 'the fulfillment console needs a configured database');+ return false;+}++/** Read the order named by ?id= / body.order_id, 404ing when it does not exist. */+async function loadOrder(req, res, body = null) {+ const url = new URL(req.url, 'http://x');+ const id = String(body?.order_id || url.searchParams.get('id') || '').trim();+ if (!id) {+ error(res, 400, 'validation_error', 'order id is required');+ return null;+ }+ const order = await getOrder(id);+ if (!order) {+ error(res, 404, 'not_found', `no print order ${id}`);+ return null;+ }+ return order;+}++// ── queue ────────────────────────────────────────────────────────────────────++/**+ * GET /api/print/ops/queue?status=paid,screening&limit=50+ * The console's left rail (counts) and its list, in one read so the two can+ * never disagree.+ */+async function handleQueue(req, res) {+ const url = new URL(req.url, 'http://x');+ const statusParam = url.searchParams.get('status') || '';+ const statuses = statusParam.split(',').map((s) => s.trim()).filter(Boolean);+ const limit = Number(url.searchParams.get('limit')) || 50;+ const offset = Number(url.searchParams.get('offset')) || 0;++ const [counts, orders] = await Promise.all([+ countOrdersByStatus(),+ listOrders({ status: statuses, limit, offset }),+ ]);++ return json(res, 200, {+ counts,+ orders: orders.map(queueRow),+ adapters: adapterSummaries(),+ });+}++// The queue list deliberately omits the shipping address: a list view has no+// use for a street address, and not sending it is cheaper than redacting it in+// the browser. The detail view, which an operator opens on purpose, has it.+function queueRow(order) {+ return {+ id: order.id,+ status: order.status,+ material_id: order.material_id,+ quantity: order.quantity,+ target_height_mm: order.target_height_mm,+ price_usdc: order.price_usdc,+ provider: order.provider,+ provider_order_id: order.provider_order_id,+ tracking_number: order.tracking_number,+ carrier: order.carrier,+ lead_time_days: order.lead_time_days,+ ship_to_country: order.shipping?.country || null,+ submitted_at: order.submitted_at,+ created_at: order.created_at,+ updated_at: order.updated_at,+ next: allowedTransitions(order.status),+ };+}++// ── order detail ─────────────────────────────────────────────────────────────++/** GET /api/print/ops/order?id=… — everything needed to run one job. */+async function handleOrderDetail(req, res) {+ const order = await loadOrder(req, res);+ if (!order) return;+ const [events, deliveries] = await Promise.all([+ listOrderEvents(order.id),+ listWebhookDeliveries(order.id),+ ]);+ return json(res, 200, {+ order: {+ ...order,+ next: allowedTransitions(order.status),+ },+ events,+ webhook_deliveries: deliveries,+ adapters: adapterSummaries(),+ });+}++// ── transitions ──────────────────────────────────────────────────────────────++/**+ * POST /api/print/ops/transition { order_id, to, note }+ * The generic move. The store refuses anything not on the whitelist, so this+ * handler does not re-implement the rules; it maps the refusal to a 409.+ */+async function handleTransition(req, res, operator) {+ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'JSON body required');+ const order = await loadOrder(req, res, body);+ if (!order) return;+ const to = String(body.to || '').trim();+ const note = typeof body.note === 'string' ? body.note.slice(0, 2000) : '';++ // `submitted` has a lane behind it; routing it through the generic mover+ // would set a status with no provider attached.+ if (to === 'submitted') {+ return error(res, 400, 'validation_error', 'use /api/print/ops/submit to hand an order to a fulfillment lane');+ }++ const { order: updated, event } = await transitionOrder({+ orderId: order.id,+ to,+ note: note || `Operator moved the order to ${to}.`,+ actor: 'operator',+ actorId: operator.actorId,+ });+ return json(res, 200, { order: { ...updated, next: allowedTransitions(updated.status) }, event });+}++/** POST /api/print/ops/submit { order_id, adapter? } */+async function handleSubmit(req, res, operator) {+ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'JSON body required');+ const order = await loadOrder(req, res, body);+ if (!order) return;++ const result = await submitOrder({+ order,+ adapterKey: String(body.adapter || '').trim(),+ actor: 'operator',+ actorId: operator.actorId,+ });+ return json(res, 200, {+ order: { ...result.order, next: allowedTransitions(result.order.status) },+ adapter: result.adapter,+ provider_order_id: result.providerOrderId,+ });+}++/**+ * POST /api/print/ops/tracking { order_id, tracking_number, carrier, note, ship }+ * Entering a tracking number is the moment a job becomes shipped, so `ship`+ * (default true) performs the transition in the same call. An operator who is+ * only correcting a typo passes ship: false.+ */+async function handleTracking(req, res, operator) {+ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'JSON body required');+ const order = await loadOrder(req, res, body);+ if (!order) return;++ const trackingNumber = String(body.tracking_number || '').trim().slice(0, 120);+ const carrier = String(body.carrier || '').trim().slice(0, 120);+ if (!trackingNumber) return error(res, 400, 'validation_error', 'tracking_number is required');++ const ship = body.ship !== false && order.status !== 'shipped';+ const note = typeof body.note === 'string' && body.note.trim()+ ? body.note.slice(0, 2000)+ : `Tracking ${trackingNumber}${carrier ? ` via ${carrier}` : ''}.`;++ if (ship) {+ const { order: updated, event } = await transitionOrder({+ orderId: order.id,+ to: 'shipped',+ note,+ actor: 'operator',+ actorId: operator.actorId,+ patch: { tracking_number: trackingNumber, carrier: carrier || null },+ });+ return json(res, 200, { order: { ...updated, next: allowedTransitions(updated.status) }, event });+ }++ // Correction only: no lifecycle change, so no transition.+ const rows = await sql`+ update print_orders set tracking_number = ${trackingNumber}, carrier = ${carrier || null}+ where id = ${order.id} returning *`;+ const event = await appendOrderEvent({+ orderId: order.id,+ status: order.status,+ note,+ actor: 'operator',+ actorId: operator.actorId,+ });+ return json(res, 200, { order: { ...rows[0], next: allowedTransitions(rows[0].status) }, event });+}++/**+ * POST /api/print/ops/cancel { order_id, reason }+ * Tells the lane to stop first, then moves the order. If the provider refuses,+ * the order is not moved: claiming a cancellation we did not get is worse than+ * an order stuck in `printing` that an operator can see and chase.+ */+async function handleCancel(req, res, operator) {+ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'JSON body required');+ const order = await loadOrder(req, res, body);+ if (!order) return;+ const reason = String(body.reason || '').slice(0, 2000);++ let providerNote = 'No fulfillment lane had the job yet.';+ if (order.provider && order.provider_order_id) {+ const result = await cancelWithProvider(order, reason);+ if (!result.ok) {+ await appendOrderEvent({+ orderId: order.id,+ status: order.status,+ note: `Cancellation refused by ${order.provider}: ${result.note}`,+ actor: 'operator',+ actorId: operator.actorId,+ });+ return error(res, 409, 'provider_refused', `${order.provider} did not accept the cancellation: ${result.note}`);+ }+ providerNote = result.note;+ }++ const { order: updated, event } = await transitionOrder({+ orderId: order.id,+ to: 'canceled',+ note: reason ? `Canceled: ${reason}. ${providerNote}` : `Canceled by operator. ${providerNote}`,+ actor: 'operator',+ actorId: operator.actorId,+ });+ return json(res, 200, { order: { ...updated, next: allowedTransitions(updated.status) }, event });+}++/**+ * POST /api/print/ops/refund { order_id, note }+ * Marks the order refunded and records the decision. The USDC send itself is+ * owner-executed (CLAUDE.md gate 1), so the response carries the exact payout+ * instruction rather than performing it.+ */+async function handleRefund(req, res, operator) {+ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'JSON body required');+ const order = await loadOrder(req, res, body);+ if (!order) return;+ const note = typeof body.note === 'string' ? body.note.slice(0, 2000) : '';++ const recipient = order.payer_wallet || null;+ const { order: updated, event } = await transitionOrder({+ orderId: order.id,+ to: 'refunded',+ note: note || 'Refund approved by operator.',+ actor: 'operator',+ actorId: operator.actorId,+ });++ await notifyOperators({+ title: 'Print order marked refunded',+ lines: [+ `Order ${order.id.slice(0, 8)} · ${Number(order.price_usdc || 0).toFixed(2)} USDC`,+ recipient ? `Send to ${recipient} (Solana USDC)` : 'Payer is a platform account: refund through the account ledger',+ ],+ orderId: order.id,+ });++ return json(res, 200, {+ order: { ...updated, next: allowedTransitions(updated.status) },+ event,+ // The owner action, spelled out. Nothing here moves money.+ payout: {+ required: true,+ executed: false,+ amount_usdc: order.price_usdc,+ recipient,+ chain: 'solana',+ asset: 'USDC',+ instruction: recipient+ ? 'Owner-executed: send this amount of USDC on Solana to the recipient, then note the signature on the order.'+ : 'Owner-executed: this order was paid from a platform session, refund through the account ledger.',+ },+ });+}++/** GET /api/print/ops/adapters — the lanes this deployment can route to. */+async function handleAdapters(_req, res) {+ return json(res, 200, { adapters: adapterSummaries() });+}++// ── dispatcher ───────────────────────────────────────────────────────────────++const DISPATCH = {+ queue: { methods: ['GET'], fn: handleQueue },+ order: { methods: ['GET'], fn: handleOrderDetail },+ adapters: { methods: ['GET'], fn: handleAdapters },+ transition: { methods: ['POST'], fn: handleTransition },+ submit: { methods: ['POST'], fn: handleSubmit },+ tracking: { methods: ['POST'], fn: handleTracking },+ cancel: { methods: ['POST'], fn: handleCancel },+ refund: { methods: ['POST'], fn: handleRefund },+};++export default wrap(async (req, res) => {+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();+ const route = DISPATCH[action];+ if (!route) return error(res, 404, 'not_found', `unknown fulfillment action: ${action}`);+ if (!method(req, res, route.methods)) return;++ // Authorization BEFORE anything else reads an order. Every action, no+ // exceptions, including the read-only ones: the queue carries order ids and+ // the detail carries a shipping address.+ const operator = await requireOperator(req, res);+ if (!operator) return;+ if (!requireStore(res)) return;++ try {+ return await route.fn(req, res, operator);+ } catch (err) {+ if (err instanceof PrintOrderNotFoundError) return error(res, 404, 'not_found', err.message);+ if (err instanceof PrintTransitionError) return error(res, 409, 'illegal_transition', err.message);+ if (err instanceof FulfillmentError) return error(res, 409, err.code, err.message);+ if (err instanceof AdapterUpstreamError) return error(res, 502, 'provider_unreachable', err.message);+ if (err instanceof AdapterContractError) return error(res, 502, 'provider_contract', err.message);+ throw err;+ }+});diff --git a/api/print/ops/insert-card.js b/api/print/ops/insert-card.jsnew file mode 100644index 000000000..6f7be63ac--- /dev/null+++ b/api/print/ops/insert-card.js@@ -0,0 +1,75 @@+/**+ * GET /api/print/ops/insert-card?cert=<certId> (or ?order=<orderId>)+ *+ * Everything the operator needs to print the card that goes in the box: the+ * certificate's QR, the model's name, the edition line, the material, and the+ * on-chain proof. Operator-gated because it resolves an ORDER to its+ * certificate, which the public certificate endpoint deliberately will not do.+ *+ * The card itself is rendered by /materialize/insert/:certId, which reads this.+ * The response also carries `insert_url`, the address a fulfillment adapter+ * hands a partner lane so a partner prints the same card we do.+ */++import { cors, json, method, wrap } from '../../_lib/http.js';+import { authorizeOps } from '../../_lib/ops-auth.js';+import { sql } from '../../_lib/db.js';+import { isUuid } from '../../_lib/validate.js';+import {+ getPublicCertificate,+ certificateUrl,+ siteOrigin,+ CERT_ID_RE,+} from '../../_lib/print/certificate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const auth = await authorizeOps(req);+ if (!auth.ok) return json(res, 403, { error: 'operator authorization required' });++ const url = new URL(req.url, 'http://localhost');+ const orderId = (url.searchParams.get('order') || '').trim();+ let certId = (url.searchParams.get('cert') || '').trim().toLowerCase();++ if (!certId && orderId) {+ if (!isUuid(orderId)) return json(res, 400, { error: 'invalid order id' });+ const [row] = await sql`select id from print_certificates where order_id = ${orderId} limit 1`;+ if (!row) {+ return json(res, 404, {+ error: 'this order has no certificate yet; certificates are issued when an order ships',+ });+ }+ certId = row.id;+ }++ if (!CERT_ID_RE.test(certId)) return json(res, 400, { error: 'invalid certificate id' });++ const certificate = await getPublicCertificate(certId);+ if (!certificate) return json(res, 404, { error: 'certificate not found' });++ const [order] = await sql`+ select id, status, quantity, material_id, tracking_number, carrier, provider+ from print_orders where id = (select order_id from print_certificates where id = ${certId})+ limit 1+ `;++ return json(res, 200, {+ certificate,+ order: order+ ? {+ id: order.id,+ status: order.status,+ quantity: order.quantity,+ material_id: order.material_id,+ provider: order.provider,+ tracking_number: order.tracking_number,+ carrier: order.carrier,+ }+ : null,+ insert_url: `${siteOrigin()}/materialize/insert/${certId}`,+ certificate_url: certificateUrl(certId),+ actor: auth.actor,+ });+});diff --git a/api/print/webhook/[provider].js b/api/print/webhook/[provider].jsnew file mode 100644index 000000000..3fe7256fd--- /dev/null+++ b/api/print/webhook/[provider].js@@ -0,0 +1,94 @@+// @ts-check+// POST /api/print/webhook/:provider — a fulfillment provider reporting in.+//+// Three properties, in the order they are enforced:+//+// 1. AUTHENTICITY. The adapter verifies the delivery against the exact bytes+// received (HMAC over the raw body, constant-time compared). An+// unverified delivery is refused before the payload is parsed, so a+// forged body never reaches a JSON.parse, let alone the state machine.+// An adapter with no webhook (the manual lane) refuses everything, which+// is why that lane has no unauthenticated door.+// 2. IDEMPOTENCY. Every serious provider retries deliveries. The claim on+// print_webhook_deliveries is a unique-key insert, so a replay of the same+// delivery is a no-op that returns 200 (a 4xx would make the provider+// retry forever) and appends nothing to the timeline.+// 3. ORDERING. The state machine, not the provider, decides what may follow+// what. A report that arrives out of order is recorded on the timeline as+// a refused provider event and answered 200 with applied: false.+//+// The response never echoes the payload and never leaks whether an order id+// exists to an unverified caller: verification comes first.++import { error, json, method, readBody, wrap } from '../../_lib/http.js';+import {+ claimWebhookDelivery,+ getOrderByProviderId,+ markWebhookApplied,+ printStoreEnabled,+} from '../../_lib/print-store.js';+import { getAdapter } from '../../_lib/print/adapters/index.js';+import { normalizeWebhookEvent } from '../../_lib/print/adapters/contract.js';+import { applyProviderEvent } from '../../_lib/print/fulfillment.js';++const MAX_BODY_BYTES = 256 * 1024;++export default wrap(async (req, res) => {+ if (!method(req, res, ['POST'])) return;++ const provider = String(+ req.query?.provider ?? new URL(req.url, 'http://x').pathname.split('/').pop() ?? '',+ ).trim();++ const adapter = getAdapter(provider);+ if (!adapter) {+ // Unknown or unconfigured lane. 404 rather than 403: there is no endpoint+ // here to authenticate against.+ return error(res, 404, 'not_found', `no configured fulfillment provider '${provider}'`);+ }++ const raw = (await readBody(req, MAX_BODY_BYTES)).toString('utf8');+ const verdict = adapter.verifyWebhook(raw, req.headers || {});+ if (!verdict?.ok) {+ return error(res, 401, 'unauthorized', verdict?.reason || 'delivery could not be verified');+ }++ if (!printStoreEnabled()) {+ // 503 makes a provider retry, which is right: the delivery is genuine and+ // we simply cannot record it yet.+ return error(res, 503, 'not_configured', 'fulfillment webhooks need a configured database');+ }++ // Claim before parsing the body's meaning: the claim is what makes a retry+ // harmless, and it must happen even for a payload we end up not applying.+ const { fresh } = await claimWebhookDelivery({ provider, deliveryId: verdict.deliveryId });+ if (!fresh) {+ return json(res, 200, { ok: true, duplicate: true, applied: false });+ }++ let payload;+ try {+ payload = JSON.parse(raw);+ } catch {+ return error(res, 400, 'validation_error', 'body must be JSON');+ }++ const event = normalizeWebhookEvent(adapter.key, adapter.parseWebhook(payload));+ const order = await getOrderByProviderId(provider, event.providerOrderId);+ if (!order) {+ // Verified sender, unknown job. Answer 200 so they stop retrying, and say+ // so plainly: this is a real condition when a provider replays history+ // after we have deleted an order.+ return json(res, 200, { ok: true, applied: false, reason: 'no matching order' });+ }++ const result = await applyProviderEvent({ order, event, actor: 'provider' });+ await markWebhookApplied({ provider, deliveryId: verdict.deliveryId, orderId: order.id });++ return json(res, 200, {+ ok: true,+ applied: result.applied,+ status: result.order.status,+ reason: result.reason || undefined,+ });+});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 00d5985de..5e1f79742 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -5439,7 +5439,7 @@ The `service` block is read from the OKX catalog (`api/_lib/okx-catalog.js`), th`status` is `ready` or `pending`. A `pending` entry carries `slug`, `agentName`, `kind`, and `brief` only: its pipeline run has not completed, so it has no deliverables to link. `rigged` is proof, not a claim: the demo runner downloads each finished GLB and asserts a real skin with skin weights before recording the joint count. `count` is every entry, `ready` is the subset with deliverables.-To buy a run of your own, call `create_identity` on the paid A2MCP endpoint in `service.endpoint`; the flow is documented in [OKX.AI Marketplace Services](./okx-marketplace.md#agent-identity-studio-150-per-identity).+To buy a run of your own, call `create_identity` on the paid A2MCP endpoint in `service.endpoint`; the flow is documented in [OKX.AI Marketplace Services](./okx-marketplace.md#back-burner).```bashcurl -s https://three.ws/api/agent-identities | jq '.service.priceUsd, .ready'