@studio8collective/patent-render 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/LICENSE +9 -0
- package/README.md +246 -2
- package/dist/core.d.ts +1105 -0
- package/dist/core.js +1144 -0
- package/dist/core.js.map +1 -0
- package/dist/index.d.ts +1295 -0
- package/dist/index.js +5887 -0
- package/dist/index.js.map +1 -0
- package/dist/server-actions.d.ts +342 -0
- package/dist/server-actions.js +1150 -0
- package/dist/server-actions.js.map +1 -0
- package/dist/server.d.ts +414 -0
- package/dist/server.js +3238 -0
- package/dist/server.js.map +1 -0
- package/dist/theme.css +110 -0
- package/docs/nextjs.md +717 -0
- package/package.json +80 -4
package/docs/nextjs.md
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
# Using PatentRender in a Next.js app
|
|
2
|
+
|
|
3
|
+
A complete guide to adding `@studio8collective/patent-render` to a Next.js App Router project: install, styling, the agent route, PNG export, the editor UI, saving and reopening figures, auth and deployment.
|
|
4
|
+
|
|
5
|
+
If you only want the shortest path, follow sections 1 to 7 and you have a working editor. Sections 8 onward cover production concerns.
|
|
6
|
+
|
|
7
|
+
## Contents
|
|
8
|
+
|
|
9
|
+
1. [How it fits together](#1-how-it-fits-together)
|
|
10
|
+
2. [Requirements](#2-requirements)
|
|
11
|
+
3. [Install](#3-install)
|
|
12
|
+
4. [API key](#4-api-key)
|
|
13
|
+
5. [next.config.ts](#5-nextconfigts)
|
|
14
|
+
6. [Styles and theme](#6-styles-and-theme)
|
|
15
|
+
7. [Minimal working integration](#7-minimal-working-integration)
|
|
16
|
+
8. [Choosing the LLM](#8-choosing-the-llm)
|
|
17
|
+
9. [Protecting the route and the action](#9-protecting-the-route-and-the-action)
|
|
18
|
+
10. [Saving and reopening figures](#10-saving-and-reopening-figures)
|
|
19
|
+
11. [Handling the embed result](#11-handling-the-embed-result)
|
|
20
|
+
12. [Patent context and numeral consistency](#12-patent-context-and-numeral-consistency)
|
|
21
|
+
13. [Using the core in server code](#13-using-the-core-in-server-code)
|
|
22
|
+
14. [Deploying to Vercel and serverless hosts](#14-deploying-to-vercel-and-serverless-hosts)
|
|
23
|
+
15. [Complete example file tree](#15-complete-example-file-tree)
|
|
24
|
+
16. [Troubleshooting](#16-troubleshooting)
|
|
25
|
+
17. [Upgrading](#17-upgrading)
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 1. How it fits together
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
Browser Your Next.js server
|
|
33
|
+
------- -------------------
|
|
34
|
+
<PatentRender endpoint="/api/..."> ---> app/api/patent-render/route.ts
|
|
35
|
+
canvas, layers, inspector, chat createPatentRenderHandler()
|
|
36
|
+
planner -> drawer -> critic (LLM)
|
|
37
|
+
streams drawing patches back (SSE)
|
|
38
|
+
|
|
39
|
+
"Export PNG" / embed ---> server action exportPatentPng()
|
|
40
|
+
renders 300 dpi PNG with resvg
|
|
41
|
+
|
|
42
|
+
onChange(doc) -> your autosave (your DB)
|
|
43
|
+
onEmbed(result) -> your app (your DB / blob storage)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- The **editor** is a client component. It holds the drawing as a JSON `PatentDocument`.
|
|
47
|
+
- The **route handler** runs the AI agents and streams edits back. It never stores anything.
|
|
48
|
+
- The **server action** turns a document into a PNG on the server (native renderer, never in the browser).
|
|
49
|
+
- **You own persistence.** The package hands you the document and the final SVG/PNG; you decide where they live.
|
|
50
|
+
|
|
51
|
+
## 2. Requirements
|
|
52
|
+
|
|
53
|
+
| | Supported |
|
|
54
|
+
|---|---|
|
|
55
|
+
| Next.js | 15 or later, **App Router**. A Pages Router app can still use it: add an `app/` directory for the route and the page that hosts the editor; both routers coexist. |
|
|
56
|
+
| React | 19 |
|
|
57
|
+
| Tailwind CSS | 4 |
|
|
58
|
+
| Node.js | 20 or later |
|
|
59
|
+
| Runtime | **Node.js runtime only.** The Edge runtime is not supported (PNG rendering uses a native module). Node is the default, so you do not need to set anything. |
|
|
60
|
+
|
|
61
|
+
## 3. Install
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
npm install @studio8collective/patent-render
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
`react`, `react-dom` and `next` are peer dependencies and come from your app. Everything else (TanStack AI, provider SDKs, zod, Radix, resvg) is installed automatically.
|
|
68
|
+
|
|
69
|
+
## 4. API key
|
|
70
|
+
|
|
71
|
+
Add one key to `.env.local`:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
PATENT_GFX_LLM_KEY=sk-ant-...
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
It must match the provider you choose in the route (section 8):
|
|
78
|
+
|
|
79
|
+
| Provider | Key looks like |
|
|
80
|
+
|---|---|
|
|
81
|
+
| `anthropic` | `sk-ant-...` |
|
|
82
|
+
| `openrouter` | `sk-or-...` |
|
|
83
|
+
| `openai` | `sk-...` |
|
|
84
|
+
|
|
85
|
+
If the key belongs to a different provider, the route refuses with a `503` and logs exactly which mismatch it found. Restart `next dev` after changing env files.
|
|
86
|
+
|
|
87
|
+
For deployed environments, set the same variable in your host (Vercel: `vercel env add PATENT_GFX_LLM_KEY`). Never prefix it with `NEXT_PUBLIC_`: that would ship the key to the browser.
|
|
88
|
+
|
|
89
|
+
## 5. `next.config.ts`
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import type { NextConfig } from "next";
|
|
93
|
+
|
|
94
|
+
const nextConfig: NextConfig = {
|
|
95
|
+
// Native PNG renderer: must be loaded by Node, not bundled.
|
|
96
|
+
serverExternalPackages: ["@resvg/resvg-js"],
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
export default nextConfig;
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Without this you get build errors mentioning `resvg` or `.node` files.
|
|
103
|
+
|
|
104
|
+
## 6. Styles and theme
|
|
105
|
+
|
|
106
|
+
The editor is styled with Tailwind utility classes that ship inside the package. Your Tailwind build has to scan the package so those classes get generated.
|
|
107
|
+
|
|
108
|
+
### 6.1 Tell Tailwind to scan the package
|
|
109
|
+
|
|
110
|
+
In your global stylesheet (usually `app/globals.css`):
|
|
111
|
+
|
|
112
|
+
```css
|
|
113
|
+
@import "tailwindcss";
|
|
114
|
+
@source "../node_modules/@studio8collective/patent-render/dist";
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
The `@source` path is **relative to the CSS file**:
|
|
118
|
+
|
|
119
|
+
| Your CSS file | `@source` line |
|
|
120
|
+
|---|---|
|
|
121
|
+
| `app/globals.css` | `@source "../node_modules/@studio8collective/patent-render/dist";` |
|
|
122
|
+
| `src/app/globals.css` | `@source "../../node_modules/@studio8collective/patent-render/dist";` |
|
|
123
|
+
| `apps/web/app/globals.css` in a monorepo with hoisted deps | `@source "../../../node_modules/@studio8collective/patent-render/dist";` |
|
|
124
|
+
|
|
125
|
+
If the editor renders as unstyled stacked boxes, this path is wrong.
|
|
126
|
+
|
|
127
|
+
### 6.2 Theme tokens
|
|
128
|
+
|
|
129
|
+
The editor uses shadcn/ui design tokens as CSS variables:
|
|
130
|
+
|
|
131
|
+
`--background`, `--foreground`, `--card`, `--card-foreground`, `--popover`, `--popover-foreground`, `--primary`, `--primary-foreground`, `--secondary`, `--secondary-foreground`, `--muted`, `--muted-foreground`, `--accent`, `--accent-foreground`, `--destructive`, `--destructive-foreground`, `--border`, `--input`, `--ring`, `--radius`
|
|
132
|
+
|
|
133
|
+
plus three extensions: `--warning`, `--success`, `--info` (each with a `-foreground` pair).
|
|
134
|
+
|
|
135
|
+
**Your app already uses shadcn/ui:** the editor picks up your theme automatically. Add the three extension tokens to your `:root` (and `.dark`) if you do not have them, for example:
|
|
136
|
+
|
|
137
|
+
```css
|
|
138
|
+
:root {
|
|
139
|
+
--warning: oklch(0.77 0.16 70);
|
|
140
|
+
--warning-foreground: oklch(0.28 0.07 46);
|
|
141
|
+
--success: oklch(0.6 0.13 163);
|
|
142
|
+
--success-foreground: oklch(1 0 0);
|
|
143
|
+
--info: oklch(0.6 0.12 240);
|
|
144
|
+
--info-foreground: oklch(1 0 0);
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
and register them with Tailwind so classes like `bg-warning` exist:
|
|
149
|
+
|
|
150
|
+
```css
|
|
151
|
+
@theme inline {
|
|
152
|
+
--color-warning: var(--warning);
|
|
153
|
+
--color-warning-foreground: var(--warning-foreground);
|
|
154
|
+
--color-success: var(--success);
|
|
155
|
+
--color-success-foreground: var(--success-foreground);
|
|
156
|
+
--color-info: var(--info);
|
|
157
|
+
--color-info-foreground: var(--info-foreground);
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
**Your app has no shadcn theme:** import the bundled one, which defines every token above for light and dark:
|
|
162
|
+
|
|
163
|
+
```css
|
|
164
|
+
@import "tailwindcss";
|
|
165
|
+
@source "../node_modules/@studio8collective/patent-render/dist";
|
|
166
|
+
@import "@studio8collective/patent-render/theme.css";
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Note that `theme.css` sets variables on `:root`, so it also restyles any of your own shadcn components. Skip it if you have your own theme.
|
|
170
|
+
|
|
171
|
+
### 6.3 Dark mode
|
|
172
|
+
|
|
173
|
+
Dark mode follows the `.dark` class on an ancestor element (the shadcn / `next-themes` convention). Nothing else to configure.
|
|
174
|
+
|
|
175
|
+
## 7. Minimal working integration
|
|
176
|
+
|
|
177
|
+
Three files give you a working editor.
|
|
178
|
+
|
|
179
|
+
### 7.1 The agent route
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
// app/api/patent-render/route.ts
|
|
183
|
+
import { createPatentRenderHandler, llmModels } from "@studio8collective/patent-render/server";
|
|
184
|
+
|
|
185
|
+
// A full draw plus review passes can take a few minutes.
|
|
186
|
+
export const maxDuration = 300;
|
|
187
|
+
|
|
188
|
+
export const POST = createPatentRenderHandler({
|
|
189
|
+
models: llmModels({ provider: "anthropic" }),
|
|
190
|
+
});
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### 7.2 The page (server component)
|
|
194
|
+
|
|
195
|
+
The PNG exporter is a server action. Server actions can only be passed to client components from a server component, so the page imports it and hands it down:
|
|
196
|
+
|
|
197
|
+
```tsx
|
|
198
|
+
// app/drawings/page.tsx
|
|
199
|
+
import { exportPatentPng } from "@studio8collective/patent-render/server/actions";
|
|
200
|
+
import { DrawingEditor } from "./DrawingEditor";
|
|
201
|
+
|
|
202
|
+
export default function DrawingsPage() {
|
|
203
|
+
return <DrawingEditor exportPng={exportPatentPng} />;
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### 7.3 The editor (client component)
|
|
208
|
+
|
|
209
|
+
```tsx
|
|
210
|
+
// app/drawings/DrawingEditor.tsx
|
|
211
|
+
"use client";
|
|
212
|
+
|
|
213
|
+
import { PatentRender, type EmbedResult, type PatentDocument } from "@studio8collective/patent-render";
|
|
214
|
+
|
|
215
|
+
export function DrawingEditor({
|
|
216
|
+
exportPng,
|
|
217
|
+
}: {
|
|
218
|
+
exportPng: (doc: PatentDocument) => Promise<{ dataUrl: string }>;
|
|
219
|
+
}) {
|
|
220
|
+
return (
|
|
221
|
+
// The editor fills its parent. Give the parent a real height.
|
|
222
|
+
<div className="h-screen">
|
|
223
|
+
<PatentRender
|
|
224
|
+
endpoint="/api/patent-render"
|
|
225
|
+
figureNumber="1"
|
|
226
|
+
jurisdiction="uspto"
|
|
227
|
+
exportPng={exportPng}
|
|
228
|
+
onEmbed={(result: EmbedResult) => console.log("embedded", result.svg.length, "chars of SVG")}
|
|
229
|
+
className="h-full"
|
|
230
|
+
/>
|
|
231
|
+
</div>
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Run `npm run dev`, open `/drawings`, and type a prompt such as:
|
|
237
|
+
|
|
238
|
+
> USB-C hub with 2 USB-A ports, HDMI, an SD card slot and a short cable
|
|
239
|
+
|
|
240
|
+
### 7.4 Sizing
|
|
241
|
+
|
|
242
|
+
`PatentRender` fills its container (`h-full w-full`, minimum height 560px). It needs a parent with a definite height: `h-screen`, a fixed-height dialog, or a flex child with `min-h-0`. A parent with no height collapses it to the 560px minimum.
|
|
243
|
+
|
|
244
|
+
### 7.5 As a modal dialog
|
|
245
|
+
|
|
246
|
+
```tsx
|
|
247
|
+
"use client";
|
|
248
|
+
import { useState } from "react";
|
|
249
|
+
import { PatentRender, type PatentDocument } from "@studio8collective/patent-render";
|
|
250
|
+
|
|
251
|
+
export function FigureDialogButton({ exportPng }: { exportPng: (d: PatentDocument) => Promise<{ dataUrl: string }> }) {
|
|
252
|
+
const [open, setOpen] = useState(false);
|
|
253
|
+
return (
|
|
254
|
+
<>
|
|
255
|
+
<button onClick={() => setOpen(true)}>New figure</button>
|
|
256
|
+
{open && (
|
|
257
|
+
<div role="dialog" aria-modal="true" aria-label="Patent figure editor"
|
|
258
|
+
className="fixed inset-0 z-50 grid place-items-center bg-black/45 p-4">
|
|
259
|
+
<div className="h-[min(860px,94vh)] w-[min(1360px,96vw)] overflow-hidden rounded-xl shadow-2xl">
|
|
260
|
+
<PatentRender
|
|
261
|
+
endpoint="/api/patent-render"
|
|
262
|
+
figureNumber="3"
|
|
263
|
+
exportPng={exportPng}
|
|
264
|
+
onCancel={() => setOpen(false)}
|
|
265
|
+
onEmbed={() => setOpen(false)}
|
|
266
|
+
className="h-full min-h-0"
|
|
267
|
+
/>
|
|
268
|
+
</div>
|
|
269
|
+
</div>
|
|
270
|
+
)}
|
|
271
|
+
</>
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
Any dialog library (Radix Dialog, shadcn `Dialog`, Headless UI) works the same way: give the content a fixed height and put `PatentRender` inside with `className="h-full min-h-0"`.
|
|
277
|
+
|
|
278
|
+
## 8. Choosing the LLM
|
|
279
|
+
|
|
280
|
+
`llmModels()` pins the provider and a model per role. Only the key comes from the environment.
|
|
281
|
+
|
|
282
|
+
| Role | Job | Pick |
|
|
283
|
+
|---|---|---|
|
|
284
|
+
| `drawer` | Main drawing loop, many tool calls | Your strongest model |
|
|
285
|
+
| `planner` | Turns the prompt into a parts plan | Fast and cheaper is fine |
|
|
286
|
+
| `critic` | Looks at the rendered PNG and requests fixes | Must accept images |
|
|
287
|
+
|
|
288
|
+
All models must support tool calling.
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
// Anthropic direct
|
|
292
|
+
llmModels({ provider: "anthropic" }); // Opus 5.5 draws, Sonnet 5.5 plans and reviews
|
|
293
|
+
|
|
294
|
+
// Claude through OpenRouter
|
|
295
|
+
llmModels({
|
|
296
|
+
provider: "openrouter",
|
|
297
|
+
drawer: "anthropic/claude-opus-5.5",
|
|
298
|
+
planner: "anthropic/claude-sonnet-5.5",
|
|
299
|
+
critic: "anthropic/claude-sonnet-5.5",
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// Different vendors per role, one OpenRouter key
|
|
303
|
+
llmModels({
|
|
304
|
+
provider: "openrouter",
|
|
305
|
+
drawer: "openai/gpt-6-sol",
|
|
306
|
+
planner: "google/gemini-3.5-flash",
|
|
307
|
+
critic: "anthropic/claude-sonnet-5.5",
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
// OpenAI direct
|
|
311
|
+
llmModels({ provider: "openai", drawer: "gpt-6-sol", planner: "gpt-6-luna", critic: "gpt-6-luna" });
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
Model id formats differ: Anthropic uses `claude-opus-5-5`, OpenRouter uses `vendor/model` with dots (`anthropic/claude-opus-5.5`). Omitted roles use `DEFAULT_MODELS[provider]`, exported from `/server`.
|
|
315
|
+
|
|
316
|
+
You can also pass any TanStack AI text adapter yourself:
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import { createAnthropicChat } from "@tanstack/ai-anthropic";
|
|
320
|
+
createPatentRenderHandler({ models: { drawer: createAnthropicChat("claude-opus-5-5", process.env.MY_KEY!) } });
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### Other handler options
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
createPatentRenderHandler({
|
|
327
|
+
models: llmModels({ provider: "anthropic" }),
|
|
328
|
+
maxReviews: 2, // visual critic passes per run; 0 disables review
|
|
329
|
+
maxTurns: 40, // max model turns in the drawing loop
|
|
330
|
+
fontFiles: [], // font paths for PNG rendering on hosts without Arial (section 14)
|
|
331
|
+
onUsage: ({ phase, usage }) => {
|
|
332
|
+
// token usage per phase: "drawer" | "planner" | "critic"
|
|
333
|
+
// never receives prompt or drawing content
|
|
334
|
+
console.info("[patent-render]", phase, usage);
|
|
335
|
+
},
|
|
336
|
+
});
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
## 9. Protecting the route and the action
|
|
340
|
+
|
|
341
|
+
The package does **no authentication**. Both endpoints are reachable by anyone who can reach your app, and the route spends LLM tokens. Protect both.
|
|
342
|
+
|
|
343
|
+
### 9.1 Route: wrap the handler
|
|
344
|
+
|
|
345
|
+
Works with any auth library (Auth.js, Clerk, Better Auth, your own sessions):
|
|
346
|
+
|
|
347
|
+
```ts
|
|
348
|
+
// app/api/patent-render/route.ts
|
|
349
|
+
import { createPatentRenderHandler, llmModels } from "@studio8collective/patent-render/server";
|
|
350
|
+
import { auth } from "@/lib/auth"; // your auth helper
|
|
351
|
+
|
|
352
|
+
export const maxDuration = 300;
|
|
353
|
+
|
|
354
|
+
const handler = createPatentRenderHandler({
|
|
355
|
+
models: llmModels({ provider: "anthropic" }),
|
|
356
|
+
onUsage: async ({ phase, usage }) => {
|
|
357
|
+
// meter per user/tenant here if you bill for usage
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
export async function POST(request: Request) {
|
|
362
|
+
const session = await auth();
|
|
363
|
+
if (!session?.user) return new Response("Unauthorized", { status: 401 });
|
|
364
|
+
// Optional: rate limit per user here.
|
|
365
|
+
return handler(request);
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
You can protect it in Next.js middleware (`proxy.ts` in Next 16) as well, but checking inside the route is explicit and cannot be bypassed by a matcher mistake.
|
|
370
|
+
|
|
371
|
+
### 9.2 PNG export: your own server action
|
|
372
|
+
|
|
373
|
+
`exportPatentPng` is a server action, so Next.js exposes it as a callable endpoint. It does not use the LLM (CPU only), but you should still gate it. Write a thin action of your own:
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
// app/drawings/actions.ts
|
|
377
|
+
"use server";
|
|
378
|
+
|
|
379
|
+
import { renderPng } from "@studio8collective/patent-render/server";
|
|
380
|
+
import { PatentDocument, validate } from "@studio8collective/patent-render/core";
|
|
381
|
+
import { auth } from "@/lib/auth";
|
|
382
|
+
|
|
383
|
+
export async function exportPng(document: unknown, dpi = 300) {
|
|
384
|
+
const session = await auth();
|
|
385
|
+
if (!session?.user) throw new Error("Unauthorized");
|
|
386
|
+
|
|
387
|
+
const doc = PatentDocument.parse(document); // never trust client input
|
|
388
|
+
const png = renderPng(doc, { dpi: Math.min(600, Math.max(72, dpi)) });
|
|
389
|
+
return {
|
|
390
|
+
dataUrl: `data:image/png;base64,${png.toString("base64")}`,
|
|
391
|
+
report: validate(doc),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
Pass it to the editor the same way: `<DrawingEditor exportPng={exportPng} />` from a server component. Your own action is also where you add `fontFiles` for serverless hosts (section 14).
|
|
397
|
+
|
|
398
|
+
## 10. Saving and reopening figures
|
|
399
|
+
|
|
400
|
+
The `PatentDocument` is plain JSON. It contains the drawing, layers, numerals, settings and the chat history, so reopening a figure restores everything.
|
|
401
|
+
|
|
402
|
+
### 10.1 Autosave with `onChange`
|
|
403
|
+
|
|
404
|
+
`onChange` fires on **every** change, including each frame of a drag. Debounce it before writing to your database:
|
|
405
|
+
|
|
406
|
+
```tsx
|
|
407
|
+
"use client";
|
|
408
|
+
import { useMemo } from "react";
|
|
409
|
+
import { PatentRender, type PatentDocument } from "@studio8collective/patent-render";
|
|
410
|
+
import { saveFigureDraft } from "./actions";
|
|
411
|
+
|
|
412
|
+
function debounce<T extends (...a: never[]) => void>(fn: T, ms: number) {
|
|
413
|
+
let t: ReturnType<typeof setTimeout> | undefined;
|
|
414
|
+
return (...args: Parameters<T>) => {
|
|
415
|
+
clearTimeout(t);
|
|
416
|
+
t = setTimeout(() => fn(...args), ms);
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export function FigureEditor({ figureId, initial, exportPng }: {
|
|
421
|
+
figureId: string;
|
|
422
|
+
initial?: PatentDocument;
|
|
423
|
+
exportPng: (d: PatentDocument) => Promise<{ dataUrl: string }>;
|
|
424
|
+
}) {
|
|
425
|
+
const autosave = useMemo(() => debounce((doc: PatentDocument) => void saveFigureDraft(figureId, doc), 1500), [figureId]);
|
|
426
|
+
|
|
427
|
+
return (
|
|
428
|
+
<div className="h-[calc(100vh-4rem)]">
|
|
429
|
+
<PatentRender
|
|
430
|
+
endpoint="/api/patent-render"
|
|
431
|
+
document={initial}
|
|
432
|
+
figureNumber="2"
|
|
433
|
+
exportPng={exportPng}
|
|
434
|
+
onChange={autosave}
|
|
435
|
+
onEmbed={() => {}}
|
|
436
|
+
className="h-full"
|
|
437
|
+
/>
|
|
438
|
+
</div>
|
|
439
|
+
);
|
|
440
|
+
}
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
### 10.2 The save action: validate on the server
|
|
444
|
+
|
|
445
|
+
```ts
|
|
446
|
+
// app/drawings/actions.ts
|
|
447
|
+
"use server";
|
|
448
|
+
import { PatentDocument } from "@studio8collective/patent-render/core";
|
|
449
|
+
import { db } from "@/lib/db";
|
|
450
|
+
|
|
451
|
+
export async function saveFigureDraft(figureId: string, document: unknown) {
|
|
452
|
+
// ...auth check...
|
|
453
|
+
const doc = PatentDocument.parse(document); // rejects malformed or tampered JSON
|
|
454
|
+
await db.figure.update({ where: { id: figureId }, data: { document: doc } });
|
|
455
|
+
}
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
Store the document in a JSON column (Postgres `jsonb`, MySQL `json`, a document store). A typical figure is tens of kilobytes; long chat histories make it larger.
|
|
459
|
+
|
|
460
|
+
### 10.3 Reopening
|
|
461
|
+
|
|
462
|
+
Load the stored JSON in a server component and pass it as `document`:
|
|
463
|
+
|
|
464
|
+
```tsx
|
|
465
|
+
// app/drawings/[id]/page.tsx
|
|
466
|
+
import { normalizeDocument } from "@studio8collective/patent-render/core";
|
|
467
|
+
import { exportPatentPng } from "@studio8collective/patent-render/server/actions";
|
|
468
|
+
import { db } from "@/lib/db";
|
|
469
|
+
import { FigureEditor } from "../FigureEditor";
|
|
470
|
+
|
|
471
|
+
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
|
|
472
|
+
const { id } = await params;
|
|
473
|
+
const row = await db.figure.findUniqueOrThrow({ where: { id } });
|
|
474
|
+
return <FigureEditor figureId={id} initial={normalizeDocument(row.document)} exportPng={exportPatentPng} />;
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
`normalizeDocument` upgrades documents saved by older versions of the package, so always run stored JSON through it before reopening.
|
|
479
|
+
|
|
480
|
+
When you pass `document`, `figureNumber`, `jurisdiction` and `sheetLabel` are taken from the document; those props only apply to new figures.
|
|
481
|
+
|
|
482
|
+
## 11. Handling the embed result
|
|
483
|
+
|
|
484
|
+
The **Embed** button is only enabled once the compliance check reports no errors (warnings are allowed). `onEmbed` then receives:
|
|
485
|
+
|
|
486
|
+
| Field | Type | What to do with it |
|
|
487
|
+
|---|---|---|
|
|
488
|
+
| `document` | `PatentDocument` | Store it. It is the editable source of the figure. |
|
|
489
|
+
| `svg` | `string` | Final vector drawing. Store it or render it inline. |
|
|
490
|
+
| `views` | `{ composite, exploded }` | Present when the figure has an exploded view. File them as separate figures if needed. |
|
|
491
|
+
| `png` | `string` (data URL) | 300 dpi raster for filing or previews. Only present when `exportPng` was passed. |
|
|
492
|
+
| `numerals` | `Record<string, string>` | New or changed reference numerals, e.g. `{ "212": "crown" }`. Merge into your spec's numeral registry. |
|
|
493
|
+
| `complianceReport` | `ComplianceReport` | `{ ok, errors, warnings, jurisdiction }`. Show remaining warnings to the user. |
|
|
494
|
+
|
|
495
|
+
Example: upload the PNG to blob storage and save the rest:
|
|
496
|
+
|
|
497
|
+
```ts
|
|
498
|
+
// app/drawings/actions.ts
|
|
499
|
+
"use server";
|
|
500
|
+
import { PatentDocument, validate } from "@studio8collective/patent-render/core";
|
|
501
|
+
|
|
502
|
+
export async function embedFigure(figureId: string, input: { document: unknown; svg: string; png?: string }) {
|
|
503
|
+
// ...auth check...
|
|
504
|
+
const doc = PatentDocument.parse(input.document);
|
|
505
|
+
const report = validate(doc); // re-check on the server; do not trust the client's report
|
|
506
|
+
if (!report.ok) throw new Error("Figure has compliance errors");
|
|
507
|
+
|
|
508
|
+
let pngUrl: string | undefined;
|
|
509
|
+
if (input.png) {
|
|
510
|
+
const bytes = Buffer.from(input.png.split(",")[1], "base64");
|
|
511
|
+
pngUrl = await uploadToBlobStorage(`figures/${figureId}.png`, bytes, "image/png"); // your storage helper
|
|
512
|
+
}
|
|
513
|
+
await saveFigure(figureId, { document: doc, svg: input.svg, pngUrl }); // your DB helper
|
|
514
|
+
}
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
```tsx
|
|
518
|
+
onEmbed={async (r) => {
|
|
519
|
+
await embedFigure(figureId, { document: r.document, svg: r.svg, png: r.png });
|
|
520
|
+
close();
|
|
521
|
+
}}
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
PNG data URLs are large (often several MB at 300 dpi). Server actions have a default request body limit of 1 MB, so raise it in `next.config.ts` if you send the PNG back to the server:
|
|
525
|
+
|
|
526
|
+
```ts
|
|
527
|
+
const nextConfig: NextConfig = {
|
|
528
|
+
serverExternalPackages: ["@resvg/resvg-js"],
|
|
529
|
+
experimental: { serverActions: { bodySizeLimit: "20mb" } },
|
|
530
|
+
};
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
Alternatively, skip sending the PNG: store the document and re-render the PNG on the server with `renderPng` when you need it.
|
|
534
|
+
|
|
535
|
+
## 12. Patent context and numeral consistency
|
|
536
|
+
|
|
537
|
+
Give the agent the application it is drawing for. It uses the claims and spec to name parts, and reuses existing reference numerals so the same part keeps the same number across figures.
|
|
538
|
+
|
|
539
|
+
```tsx
|
|
540
|
+
<PatentRender
|
|
541
|
+
endpoint="/api/patent-render"
|
|
542
|
+
figureNumber="4A"
|
|
543
|
+
jurisdiction="epo"
|
|
544
|
+
sheetLabel="3/7"
|
|
545
|
+
context={{
|
|
546
|
+
title: "Smart wrist watch with modular strap",
|
|
547
|
+
claims: "1. A wrist watch comprising a case (208), a bezel (214) ...",
|
|
548
|
+
specExcerpt: "FIG. 4A shows the strap coupling in section ...",
|
|
549
|
+
numeralRegistry: { "202": "upper strap", "204": "lower strap", "208": "case" },
|
|
550
|
+
}}
|
|
551
|
+
exportPng={exportPng}
|
|
552
|
+
onEmbed={...}
|
|
553
|
+
/>
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
| Prop | Notes |
|
|
557
|
+
|---|---|
|
|
558
|
+
| `figureNumber` | Required for new figures: `"1"`, `"4A"`. |
|
|
559
|
+
| `jurisdiction` | `"uspto"`, `"pct"`, `"epo"` or `"ipo"`. Default `"ipo"`. Sets sheet size, margins, line and lettering rules for the validator. |
|
|
560
|
+
| `sheetLabel` | Sheet number printed top centre, e.g. `"2/5"`. |
|
|
561
|
+
| `context.numeralRegistry` | Numerals already used in the application. After embedding, merge `result.numerals` back into it before opening the next figure. |
|
|
562
|
+
|
|
563
|
+
## 13. Using the core in server code
|
|
564
|
+
|
|
565
|
+
The root import (`@studio8collective/patent-render`) is a client module. Importing functions from it inside a server component gives you client references, not callable functions. Use `/core` on the server:
|
|
566
|
+
|
|
567
|
+
```ts
|
|
568
|
+
import {
|
|
569
|
+
createDocument,
|
|
570
|
+
normalizeDocument,
|
|
571
|
+
PatentDocument,
|
|
572
|
+
validate,
|
|
573
|
+
renderSvg,
|
|
574
|
+
PROFILES,
|
|
575
|
+
} from "@studio8collective/patent-render/core";
|
|
576
|
+
import { renderPng } from "@studio8collective/patent-render/server";
|
|
577
|
+
|
|
578
|
+
const doc = createDocument({ id: crypto.randomUUID(), figureNumber: "1", jurisdiction: "uspto" });
|
|
579
|
+
const report = validate(doc); // { ok, errors, warnings, jurisdiction }
|
|
580
|
+
const svg = renderSvg(doc); // string
|
|
581
|
+
const png = renderPng(doc, { dpi: 300 }); // Buffer
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
Typical uses: server-side validation before saving, generating thumbnails, batch re-rendering all figures of an application, exporting a filing package.
|
|
585
|
+
|
|
586
|
+
### Entry point summary
|
|
587
|
+
|
|
588
|
+
| Import | Use from | Contains |
|
|
589
|
+
|---|---|---|
|
|
590
|
+
| `@studio8collective/patent-render` | Client components | `PatentRender`, `PatentRenderEditor`, `EditorProvider`, `useEditor`, plus the core exports |
|
|
591
|
+
| `@studio8collective/patent-render/core` | Anywhere | `createDocument`, `normalizeDocument`, `PatentDocument`, `validate`, `PROFILES`, `renderSvg`, types |
|
|
592
|
+
| `@studio8collective/patent-render/server` | Server only | `createPatentRenderHandler`, `llmModels`, `DEFAULT_MODELS`, `LLM_KEY_ENV`, `renderPng` |
|
|
593
|
+
| `@studio8collective/patent-render/server/actions` | Server components, passed to the editor | `exportPatentPng` |
|
|
594
|
+
| `@studio8collective/patent-render/theme.css` | Global CSS | Optional theme tokens |
|
|
595
|
+
|
|
596
|
+
## 14. Deploying to Vercel and serverless hosts
|
|
597
|
+
|
|
598
|
+
### 14.1 Function duration
|
|
599
|
+
|
|
600
|
+
A draw with review passes can run for a few minutes. Set the route's limit:
|
|
601
|
+
|
|
602
|
+
```ts
|
|
603
|
+
// app/api/patent-render/route.ts
|
|
604
|
+
export const maxDuration = 300; // seconds
|
|
605
|
+
```
|
|
606
|
+
|
|
607
|
+
### 14.2 Fonts for PNG rendering
|
|
608
|
+
|
|
609
|
+
The PNG renderer uses system fonts. Minimal Linux hosts (Vercel functions, most containers) have no Arial, so numerals and "FIG. 1" render as empty boxes. Ship a font with your app:
|
|
610
|
+
|
|
611
|
+
1. Put a sans font in your repo, e.g. `fonts/LiberationSans-Regular.ttf` and `fonts/LiberationSans-Bold.ttf` (metric-compatible with Arial, SIL Open Font License).
|
|
612
|
+
2. Make sure the files are included in the serverless bundle:
|
|
613
|
+
|
|
614
|
+
```ts
|
|
615
|
+
// next.config.ts
|
|
616
|
+
const nextConfig: NextConfig = {
|
|
617
|
+
serverExternalPackages: ["@resvg/resvg-js"],
|
|
618
|
+
outputFileTracingIncludes: {
|
|
619
|
+
"/api/patent-render": ["./fonts/**"],
|
|
620
|
+
"/drawings/**": ["./fonts/**"],
|
|
621
|
+
},
|
|
622
|
+
};
|
|
623
|
+
```
|
|
624
|
+
|
|
625
|
+
3. Pass the paths to the handler and to your PNG action:
|
|
626
|
+
|
|
627
|
+
```ts
|
|
628
|
+
import path from "node:path";
|
|
629
|
+
const fontFiles = [
|
|
630
|
+
path.join(process.cwd(), "fonts/LiberationSans-Regular.ttf"),
|
|
631
|
+
path.join(process.cwd(), "fonts/LiberationSans-Bold.ttf"),
|
|
632
|
+
];
|
|
633
|
+
|
|
634
|
+
createPatentRenderHandler({ models: llmModels({ provider: "anthropic" }), fontFiles });
|
|
635
|
+
// and in your own export action (section 9.2):
|
|
636
|
+
renderPng(doc, { dpi: 300, fontFiles });
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
The built-in `exportPatentPng` action uses system fonts only. On serverless hosts, use your own action as shown in section 9.2.
|
|
640
|
+
|
|
641
|
+
### 14.3 Environment variables
|
|
642
|
+
|
|
643
|
+
Set `PATENT_GFX_LLM_KEY` for every environment you deploy (Production, Preview, Development). On Vercel:
|
|
644
|
+
|
|
645
|
+
```bash
|
|
646
|
+
vercel env add PATENT_GFX_LLM_KEY
|
|
647
|
+
```
|
|
648
|
+
|
|
649
|
+
### 14.4 Checklist
|
|
650
|
+
|
|
651
|
+
- [ ] `PATENT_GFX_LLM_KEY` set for the deployed environment, matching the provider in the route
|
|
652
|
+
- [ ] `serverExternalPackages: ["@resvg/resvg-js"]`
|
|
653
|
+
- [ ] `maxDuration` on the route
|
|
654
|
+
- [ ] Route and PNG action behind auth
|
|
655
|
+
- [ ] Fonts bundled and passed as `fontFiles`
|
|
656
|
+
- [ ] `@source` path correct for your CSS file location
|
|
657
|
+
- [ ] Server action body limit raised if you send PNGs back to the server
|
|
658
|
+
|
|
659
|
+
## 15. Complete example file tree
|
|
660
|
+
|
|
661
|
+
```
|
|
662
|
+
app/
|
|
663
|
+
globals.css @import tailwind, @source the package, theme tokens
|
|
664
|
+
layout.tsx imports globals.css
|
|
665
|
+
api/
|
|
666
|
+
patent-render/
|
|
667
|
+
route.ts auth wrapper + createPatentRenderHandler + maxDuration
|
|
668
|
+
drawings/
|
|
669
|
+
actions.ts "use server": exportPng, saveFigureDraft, embedFigure
|
|
670
|
+
page.tsx list figures / "New figure" button
|
|
671
|
+
FigureEditor.tsx "use client": PatentRender with autosave + embed
|
|
672
|
+
[id]/
|
|
673
|
+
page.tsx loads saved document, normalizeDocument, renders FigureEditor
|
|
674
|
+
fonts/
|
|
675
|
+
LiberationSans-Regular.ttf for PNG text on serverless hosts
|
|
676
|
+
LiberationSans-Bold.ttf
|
|
677
|
+
lib/
|
|
678
|
+
auth.ts your auth helper
|
|
679
|
+
db.ts your database client
|
|
680
|
+
next.config.ts serverExternalPackages, outputFileTracingIncludes, bodySizeLimit
|
|
681
|
+
.env.local PATENT_GFX_LLM_KEY=...
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
## 16. Troubleshooting
|
|
685
|
+
|
|
686
|
+
| Symptom | Cause and fix |
|
|
687
|
+
|---|---|
|
|
688
|
+
| Editor renders as unstyled boxes | Tailwind is not scanning the package. Check the `@source` path depth (section 6.1). |
|
|
689
|
+
| Colours missing, invisible buttons | No shadcn tokens defined. Import `theme.css` or add the tokens (section 6.2). |
|
|
690
|
+
| Warning / success badges have no colour | Your theme lacks `--warning`, `--success`, `--info`. Add them (section 6.2). |
|
|
691
|
+
| Editor is squashed or 560px tall | Parent has no definite height (section 7.4). |
|
|
692
|
+
| Route returns `503 PatentRender model is not configured` | Key missing, or it belongs to another provider. The server log line `[patent-render] model configuration error:` names the exact problem. |
|
|
693
|
+
| Chat shows `401 invalid x-api-key` or similar | Key format is unrecognised (proxy or gateway key) and the provider rejected it. Check the key and provider. |
|
|
694
|
+
| Build error about `resvg`, `.node` files or `Can't resolve 'fs'` | Add `serverExternalPackages: ["@resvg/resvg-js"]`, and make sure `/server` is never imported from a client component. |
|
|
695
|
+
| "Functions cannot be passed directly to Client Components" | You passed a plain function as `exportPng`. Pass a server action (`exportPatentPng`, or your own `"use server"` function) from a server component. |
|
|
696
|
+
| "Attempted to call createDocument() from the server" | You imported from the root entry in server code. Import from `/core` (section 13). |
|
|
697
|
+
| Run stops after about a minute in production | Function timeout. Set `export const maxDuration = 300;` on the route. |
|
|
698
|
+
| PNG text shows as boxes in production | No fonts on the host. Bundle fonts and pass `fontFiles` (section 14.2). |
|
|
699
|
+
| "Body exceeded 1 MB limit" when embedding | PNG data URL sent to a server action. Raise `serverActions.bodySizeLimit` or re-render the PNG on the server (section 11). |
|
|
700
|
+
| Edge runtime error | The route must run on Node.js. Remove `export const runtime = "edge"`. |
|
|
701
|
+
|
|
702
|
+
## 17. Upgrading
|
|
703
|
+
|
|
704
|
+
The package follows semantic versioning:
|
|
705
|
+
|
|
706
|
+
- **Patch / minor** (`1.0.x`, `1.x`): safe to upgrade. New options are additive.
|
|
707
|
+
- **Major** (`2.0`): breaking changes to props, handler options or the document schema, listed in `CHANGELOG.md`.
|
|
708
|
+
|
|
709
|
+
Saved documents remain loadable across versions: always pass stored JSON through `normalizeDocument()` before reopening it.
|
|
710
|
+
|
|
711
|
+
```bash
|
|
712
|
+
npm install @studio8collective/patent-render@latest
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
---
|
|
716
|
+
|
|
717
|
+
Copyright (c) 2026 Sachin Bhatnagar (studio8collective). All rights reserved. Proprietary software; see `LICENSE` in the package.
|