Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

index.ts

85 lines2.8 KB

1/**
2 * Vite plugin (PLAN.md task 12.4). Dev server (`serve`): pull whatever is
3 * missing, then *report* upstream schema drift — never rewrite existing
4 * files (a teammate booting dev must not mutate the build; `modelschemas
5 * update` is the explicit refresh, and the git diff is the review).
6 * Production (`build`): zero network — verify the committed files match the
7 * manifest and fail with remediation otherwise.
8 */
9import { isAbsolute, resolve } from 'node:path'
10import { checkUpdates, pull, verify } from '@modelschemas/codegen'
11import type { PullConfig } from '@modelschemas/codegen'
12import type { Plugin, ResolvedConfig } from 'vite'
13​
14export interface ModelschemasOptions extends Omit<
15 PullConfig,
16 'outDir' | 'log'
17> {
18 /** Where generated files live, relative to the vite root (committed).
19 * Default `src/modelschemas`. */
20 outDir?: string
22​
23export function modelschemas(options: ModelschemasOptions): Plugin {
24 let command: ResolvedConfig['command'] = 'build'
25 let root = process.cwd()
26 let logger: ResolvedConfig['logger'] | undefined
27​
28 const pullConfig = (): PullConfig => {
29 const outDir = options.outDir ?? 'src/modelschemas'
30 return {
31 ...options,
32 outDir: isAbsolute(outDir) ? outDir : resolve(root, outDir),
33 log: (message) => logger?.info(`[modelschemas] ${message}`),
34 }
35 }
36​
37 return {
38 name: 'modelschemas',
39​
40 configResolved(config) {
41 command = config.command
42 root = config.root
43 logger = config.logger
44 },
45​
46 async buildStart() {
47 const config = pullConfig()
48​
49 if (command === 'serve') {
50 const summary = await pull(config, { missingOnly: true })
51 if (summary.written.length > 0) {
52 logger?.info(
53 `[modelschemas] pulled ${String(summary.written.length)} schema module(s) into ${String(options.outDir ?? 'src/modelschemas')} — commit them.`,
54 )
55 }
56 for (const failure of summary.failed) {
57 logger?.warn(`[modelschemas] ${failure.key}: ${failure.reason}`)
58 }
59 const updates = await checkUpdates(config).catch((error: unknown) => {
60 logger?.warn(
61 `[modelschemas] update check failed: ${error instanceof Error ? error.message : String(error)}`,
62 )
63 return []
64 })
65 if (updates.length > 0) {
66 logger?.info(
67 `[modelschemas] ${String(updates.length)} upstream schema update(s) available — run \`modelschemas update\`:\n` +
68 updates.map((u) => ` ${u.key} — ${u.summary}`).join('\n'),
69 )
70 }
71 return
72 }
73​
74 // build: offline verification only.
75 const result = await verify(config)
76 if (!result.ok) {
77 throw new Error(
78 `[modelschemas] generated schema files are not ready:\n${result.problems.map((p) => ` - ${p}`).join('\n')}`,
79 )
80 }
81 },
82 }
84​
85export default modelschemas