-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
254 lines (221 loc) Β· 9.04 KB
/
build.js
File metadata and controls
254 lines (221 loc) Β· 9.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#!/usr/bin/env node
/**
* Multi-entry build script for Hygraph Preview SDK
*/
import { build } from 'vite';
import { execSync } from 'child_process';
import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
async function buildAll() {
console.log('π Building Hygraph Preview SDK...\n');
try {
// Clean dist directory
console.log('π§Ή Cleaning dist directory...');
rmSync('dist', { recursive: true, force: true });
mkdirSync('dist', { recursive: true });
mkdirSync('dist/core', { recursive: true });
mkdirSync('dist/react', { recursive: true });
// Build main entry with the existing vite config
console.log('π¦ Building main entry (ESM, CJS, UMD)...');
execSync('npx vite build', { stdio: 'inherit' });
console.log('π¦ Building core entry...');
// Build core entry - ESM and CJS only
await build({
build: {
lib: {
entry: resolve(__dirname, 'src/core/index.ts'),
name: 'HygraphPreviewCore',
formats: ['es', 'cjs'],
fileName: (format) => format === 'es' ? 'index.esm.js' : 'index.cjs.js',
},
outDir: 'dist/core',
rollupOptions: {
external: ['react', 'react-dom'],
output: {
exports: 'named',
},
},
sourcemap: true,
minify: 'terser',
emptyOutDir: false,
},
});
console.log('π¦ Building React entry...');
// Build React entry - ESM and CJS only
// Note: We generate types manually below, so we don't use vite-plugin-dts here
await build({
build: {
lib: {
entry: resolve(__dirname, 'src/react/index.ts'),
name: 'HygraphPreviewReact',
formats: ['es', 'cjs'],
fileName: (format) => format === 'es' ? 'index.esm.js' : 'index.cjs.js',
},
outDir: 'dist/react',
rollupOptions: {
external: (id) => {
// Externalize React and its JSX runtime
return id === 'react' ||
id === 'react-dom' ||
id === 'react/jsx-runtime' ||
id === 'react/jsx-dev-runtime' ||
id.startsWith('react/');
},
output: {
globals: {
react: 'React',
'react-dom': 'ReactDOM',
'react/jsx-runtime': 'React',
'react/jsx-dev-runtime': 'React',
},
exports: 'named',
},
},
sourcemap: true,
minify: 'terser',
emptyOutDir: false,
},
});
// Generate type definitions
console.log('π¦ Creating TypeScript declarations...');
// Core types - re-export from main index
writeFileSync('dist/core/index.d.ts', `export * from '../index';
`);
// React types - manually maintained to match src/react/index.ts exports
// IMPORTANT: If you change exports in src/react/index.ts, update these types!
console.log('π¦ Generating React type definitions...');
const reactDtsPath = resolve(__dirname, 'dist/react/index.d.ts');
// Read source to validate exports match
const reactIndexSource = readFileSync(resolve(__dirname, 'src/react/index.ts'), 'utf-8');
const expectedExports = [
'HygraphPreview',
'HygraphPreviewNextjs',
'usePreview',
'usePreviewSave',
'usePreviewEvent',
'usePreviewRefresh',
'usePreviewRemix',
'usePreviewFieldUpdates',
'usePreviewConnection',
'usePreviewActions',
'usePreviewDebug',
'Preview',
];
// Check that all expected exports are in the source
const missingExports = expectedExports.filter(exp => !reactIndexSource.includes(exp));
if (missingExports.length > 0) {
console.error(`β Missing exports in src/react/index.ts: ${missingExports.join(', ')}`);
process.exit(1);
}
// Create type definitions that match the source exports
const reactTypeDefs = `// Auto-generated - manually maintained to match src/react/index.ts
// IMPORTANT: If you change exports in src/react/index.ts, update these types!
// Run the build to validate that all exports are present.
export * from '../index';
// Re-export types from main index
export type {
PreviewConfig,
FieldUpdate,
SaveCallback,
SubscriptionConfig,
StudioMessage,
SDKMessage,
FieldType,
PreviewEvents,
} from '../index';
// Re-export Preview class
export type { Preview } from '../index';
// React-specific component and hook exports
// These types must match the actual exports in src/react/index.ts
import type { PreviewConfig, SaveCallback, FieldUpdate, PreviewEvents, Preview } from '../index';
import type React from 'react';
export interface HygraphPreviewProps extends PreviewConfig {
children: React.ReactNode;
onReady?: (preview: Preview) => void;
onConnected?: (studioOrigin: string) => void;
onDisconnected?: () => void;
onSave?: SaveCallback;
onError?: (error: Error) => void;
onFieldFocus?: (fieldApiId: string, locale?: string) => void;
onFieldUpdate?: (update: FieldUpdate) => void;
}
export interface HygraphPreviewNextjsProps extends Omit<HygraphPreviewProps, 'onSave'> {
refresh: () => void | Promise<void>;
onSave?: SaveCallback;
}
export declare const HygraphPreview: React.FC<HygraphPreviewProps>;
export declare const HygraphPreviewNextjs: React.FC<HygraphPreviewNextjsProps>;
export declare function usePreview(): { preview: Preview | null; isReady: boolean; isConnected: boolean };
export declare function usePreviewSave(callback: SaveCallback): void;
export declare function usePreviewEvent<K extends keyof PreviewEvents>(
eventType: K,
handler: (event: PreviewEvents[K]) => void
): void;
export declare function usePreviewRefresh(): { refresh: () => void | Promise<void>; framework: string | null };
export declare function usePreviewRemix(): void;
export declare function usePreviewFieldUpdates(onUpdate?: (update: FieldUpdate) => void, onError?: (error: Error) => void): void;
export declare function usePreviewConnection(): { isConnected: boolean; isReady: boolean; mode: 'iframe' | 'standalone' | null };
export declare function usePreviewActions(): { refresh: () => void; destroy: () => void; getVersion: () => string | null };
export declare function usePreviewDebug(): { preview: Preview | null; mode: 'iframe' | 'standalone' | null; events: string[] };
`;
writeFileSync(reactDtsPath, reactTypeDefs);
// Validate that all expected exports are declared in the type definitions
const typeDefsContent = reactTypeDefs;
// React-specific exports that must be explicitly declared (not in main index)
const reactSpecificExports = [
'HygraphPreview',
'HygraphPreviewNextjs',
'usePreview',
'usePreviewSave',
'usePreviewEvent',
'usePreviewRefresh',
'usePreviewRemix',
'usePreviewFieldUpdates',
'usePreviewConnection',
'usePreviewActions',
'usePreviewDebug',
];
// Check that React-specific exports are explicitly declared
const missingTypeExports = reactSpecificExports.filter(exp => {
// Check if export is explicitly declared (not just via export *)
const patterns = [
`export declare const ${exp}`,
`export declare function ${exp}`,
`export interface ${exp}`,
`export type { ${exp}`,
`export const ${exp}`,
`export function ${exp}`,
];
return !patterns.some(pattern => typeDefsContent.includes(pattern));
});
// Preview is re-exported from main index, so it's fine if it's via export *
// But we check it's at least mentioned
if (!typeDefsContent.includes('Preview') && !typeDefsContent.includes('export type { Preview }')) {
missingTypeExports.push('Preview');
}
if (missingTypeExports.length > 0) {
console.error(`β Missing type declarations for: ${missingTypeExports.join(', ')}`);
console.error(' Please update dist/react/index.d.ts to include all exports from src/react/index.ts');
process.exit(1);
}
console.log(' β React type definitions validated');
console.log('\nβ
Build completed successfully!');
console.log('\nπ Output files:');
console.log(' dist/index.esm.js - Main ESM bundle');
console.log(' dist/index.cjs.js - Main CommonJS bundle');
console.log(' dist/index.umd.js - Main UMD bundle');
console.log(' dist/index.d.ts - Main TypeScript definitions');
console.log(' dist/core/index.esm.js - Core ESM bundle');
console.log(' dist/core/index.cjs.js - Core CommonJS bundle');
console.log(' dist/core/index.d.ts - Core TypeScript definitions');
console.log(' dist/react/index.esm.js - React ESM bundle');
console.log(' dist/react/index.cjs.js - React CommonJS bundle');
console.log(' dist/react/index.d.ts - React TypeScript definitions');
} catch (error) {
console.error('β Build failed:', error);
process.exit(1);
}
}
buildAll();