forked from react-querybuilder/react-querybuilder
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generateExamples.ts
297 lines (268 loc) · 11 KB
/
generateExamples.ts
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import stableStringify from 'fast-json-stable-stringify';
import { mkdir, rm } from 'node:fs/promises';
import path from 'node:path';
import type { Options as PrettierOptions } from 'prettier';
import prettier from 'prettier';
import * as prettierPluginOrganizeImports from 'prettier-plugin-organize-imports';
import * as prettierPluginEstree from 'prettier/plugins/estree';
import { transformWithEsbuild } from 'vite';
import { configs } from './exampleConfigs.js';
interface PackageJSON {
name: string;
description: string;
dependencies: Record<string, string>;
devDependencies: Record<string, string>;
peerDependencies: Record<string, string>;
}
console.log('Generating/updating examples');
const rootPrettierConfig = await prettier.resolveConfig(import.meta.file);
const lernaJson = Bun.file(path.join(import.meta.dir, '../lerna.json'));
const { version } = await lernaJson.json();
const compileToJS = async (code: string, fileName: string) => {
const compiled = await transformWithEsbuild(code, fileName, {
minify: false,
minifyWhitespace: false,
jsx: 'preserve',
});
return compiled.code.replaceAll(/^(const|createRoot|\s+return)/gm, '\n\n$1');
};
const packagesPath = path.join(import.meta.dir, '../packages');
const templatePath = path.join(import.meta.dir, '_template');
const templateDotCS = path.join(templatePath, '.codesandbox');
const templateSrc = path.join(templatePath, 'src');
const templateDotCSTemplateJSON = await Bun.file(path.join(templateDotCS, 'template.json')).json();
const templateIndexHTML = await Bun.file(path.join(templatePath, 'index.html')).text();
const templateIndexTSX = await Bun.file(path.join(templateSrc, 'index.tsx')).text();
const templateAppTSX = await Bun.file(path.join(templateSrc, 'App.tsx')).text();
const templateStylesSCSS = await Bun.file(path.join(templateSrc, 'styles.scss')).text();
const templateREADMEmd = await Bun.file(path.join(templatePath, 'README.md')).text();
const templatePkgJsonNewTextRaw = await Bun.file(path.join(templatePath, 'package.json')).text();
const templatePkgJsonNewText = templatePkgJsonNewTextRaw.replaceAll(
/("@?react-querybuilder(?:\/\w+)?": ").*?"/g,
`$1${version}"`
);
await Bun.write(path.join(templatePath, 'package.json'), templatePkgJsonNewText);
const templatePkgJSON: PackageJSON = await Bun.file(path.join(templatePath, 'package.json')).json();
const generateExampleFromTemplate = async (exampleID: string) => {
const exampleConfig = configs[exampleID];
const examplePath = path.join(import.meta.dir, exampleID);
const exampleDotCS = path.join(examplePath, '.codesandbox');
const exampleSrc = path.join(examplePath, 'src');
const exampleBaseTitle = `React Query Builder ${exampleConfig.name}`;
const exampleTitle = `${exampleBaseTitle} Example`;
const exampleTemplateName = `${exampleBaseTitle} Template`;
await rm(examplePath, { recursive: true, force: true });
await mkdir(examplePath);
await Promise.all([mkdir(exampleDotCS), mkdir(exampleSrc)]);
await Bun.write(
path.join(examplePath, 'prettier.config.mjs'),
Bun.file(path.join(templatePath, 'prettier.config.mjs'))
);
const examplePrettierConfig = await prettier.resolveConfig(
path.join(examplePath, 'package.json')
);
const formatAndWrite = async (filepath: string, fileContents: string) => {
let printWidth = examplePrettierConfig?.printWidth;
if (filepath.endsWith('css')) {
printWidth = rootPrettierConfig?.printWidth;
}
const prettierOptions: PrettierOptions = {
...examplePrettierConfig,
...(printWidth ? { printWidth } : {}),
filepath,
plugins: [prettierPluginOrganizeImports, prettierPluginEstree],
};
return Bun.write(
filepath,
(await prettier.check(fileContents, prettierOptions))
? fileContents
: await prettier.format(fileContents, prettierOptions)
);
};
// Array of Bun.write promises
const toWrite: ReturnType<typeof Bun.write>[] = [];
// #region Straight copies
toWrite.push(
Bun.write(
path.join(exampleDotCS, 'tasks.json'),
Bun.file(path.join(templateDotCS, 'tasks.json'))
),
Bun.write(
path.join(exampleDotCS, 'workspace.json'),
Bun.file(path.join(templateDotCS, 'workspace.json'))
),
Bun.write(
path.join(examplePath, '.gitignore'),
Bun.file(path.join(templatePath, '.gitignore'))
),
Bun.write(
path.join(examplePath, `vite.config.${exampleConfig.compileToJS ? 'j' : 't'}s`),
Bun.file(path.join(templatePath, 'vite.config.ts'))
),
...(exampleConfig.compileToJS
? []
: [
Bun.write(
path.join(exampleSrc, 'vite-env.d.ts'),
Bun.file(path.join(templateSrc, 'vite-env.d.ts'))
),
Bun.write(
path.join(examplePath, 'tsconfig.json'),
Bun.file(path.join(templatePath, 'tsconfig.json'))
),
])
);
// #endregion
// #region /index.html
const exampleIndexHTML = templateIndexHTML
.replace('__TITLE__', exampleTitle)
.replace('index.tsx', exampleConfig.compileToJS ? 'index.jsx' : 'index.tsx');
toWrite.push(formatAndWrite(path.join(examplePath, 'index.html'), exampleIndexHTML));
// #endregion
// #region src/index.scss
const processedTemplateSCSS = templateStylesSCSS
.replace('// __SCSS_PRE__', exampleConfig.scssPre.join('\n'))
.replace('// __SCSS_POST__', exampleConfig.scssPost.join('\n'))
.replaceAll(/((query-builder\.)s(css))/g, exampleConfig.compileToJS ? '$2$3' : '$1');
toWrite.push(
formatAndWrite(
path.join(exampleSrc, `styles.${exampleConfig.compileToJS ? '' : 's'}css`),
processedTemplateSCSS
)
);
// #endregion
// #region src/index.tsx
const processedTemplateIndexTSX = templateIndexTSX.replaceAll(
'styles.scss',
exampleConfig.compileToJS ? 'styles.css' : '$&'
);
const exampleIndexSourceCode = exampleConfig.compileToJS
? await compileToJS(processedTemplateIndexTSX, 'index.tsx')
: processedTemplateIndexTSX;
toWrite.push(
formatAndWrite(
path.join(exampleSrc, `index.${exampleConfig.compileToJS ? 'j' : 't'}sx`),
exampleIndexSourceCode
)
);
// #endregion
// #region src/App.tsx
const processedTemplateAppTSX = templateAppTSX
.replace('// __IMPORTS__', exampleConfig.tsxImports.join('\n'))
.replace('// __ADDITIONAL_DECLARATIONS__', exampleConfig.additionalDeclarations.join('\n'))
.replace('{/* __WRAPPER_OPEN__ */}', exampleConfig.wrapper?.[0] ?? '')
.replace('{/* __WRAPPER_CLOSE__ */}', exampleConfig.wrapper?.[1] ?? '')
.replace('// __RQB_PROPS__', exampleConfig.props.join('\n'))
.replaceAll('styles.scss', exampleConfig.compileToJS ? 'styles.css' : '$&');
const exampleAppSourceCode = exampleConfig.compileToJS
? await compileToJS(processedTemplateAppTSX, 'App.tsx')
: processedTemplateAppTSX;
toWrite.push(
formatAndWrite(
path.join(exampleSrc, `App.${exampleConfig.compileToJS ? 'j' : 't'}sx`),
exampleAppSourceCode
)
);
// #endregion
// #region package.json
const examplePkgJSON = structuredClone(templatePkgJSON);
examplePkgJSON.name = `react-querybuilder-${exampleID}-example`;
examplePkgJSON.description = exampleTitle;
if (exampleConfig.isCompatPackage || exampleConfig.enableDnD) {
examplePkgJSON.dependencies[`@react-querybuilder/${exampleID}`] =
templatePkgJSON.dependencies['react-querybuilder'];
}
if (exampleConfig.compileToJS) {
delete examplePkgJSON.devDependencies['sass'];
delete examplePkgJSON.devDependencies['typescript'];
for (const devDep of Object.keys(examplePkgJSON.devDependencies)) {
if (devDep.startsWith('@types/')) {
delete examplePkgJSON.devDependencies[devDep];
}
}
}
for (const depKey of exampleConfig.dependencyKeys) {
const compatPkgJson: PackageJSON = await Bun.file(
path.join(packagesPath, `${exampleID}/package.json`)
).json();
if (Array.isArray(depKey)) {
examplePkgJSON.dependencies[depKey[0]] = depKey[1];
} else {
examplePkgJSON.dependencies[depKey] = compatPkgJson.peerDependencies[depKey];
}
}
toWrite.push(
formatAndWrite(path.join(examplePath, 'package.json'), stableStringify(examplePkgJSON))
);
// #endregion
// #region .codesandbox/template.json
const exampleDotCSTemplateJSON = {
...templateDotCSTemplateJSON,
title: exampleTemplateName,
description: exampleTemplateName,
};
toWrite.push(
formatAndWrite(
path.join(exampleDotCS, 'template.json'),
stableStringify(exampleDotCSTemplateJSON)
)
);
// #endregion
// #region README.md
const exampleREADMEmd =
`## ${exampleTitle}` +
'\n\n' +
templateREADMEmd
.replaceAll(/(\/?examples?[/-])?_template/g, `$1${exampleID}`)
.replaceAll('App.tsx', exampleConfig.compileToJS ? 'App.jsx' : '$&') +
'\n\n' +
'> _Development note: Do not modify the files in this folder directly. Edit corresponding ' +
'files in the [_template](../_template) folder and/or [exampleConfigs.ts](../exampleConfigs.ts), ' +
'then run `bun generate-examples` from the repository root directory (requires [Bun](https://bun.sh/))._';
toWrite.push(formatAndWrite(path.join(examplePath, 'README.md'), exampleREADMEmd));
// #endregion
console.log(`Generated "${exampleConfig.name}" example code (${exampleID})`);
return Promise.all(toWrite);
};
// #region Other examples' package.json
const otherExamples = ['ci', 'native', 'next', 'tremor'] as const;
const updateOtherExample = async (otherExampleName: string) => {
const otherExamplePkgJSON: PackageJSON = await Bun.file(
path.join(import.meta.dir, `${otherExampleName}/package.json`)
).json();
for (const dep of Object.keys(otherExamplePkgJSON.dependencies)) {
if (/^@?react-querybuilder(\/[a-z]+)?/.test(dep)) {
otherExamplePkgJSON.dependencies[dep] = templatePkgJSON.dependencies['react-querybuilder'];
}
}
const otherExamplePkgJsonPath = path.join(import.meta.dir, `${otherExampleName}/package.json`);
const otherExamplePrettierOptions = await prettier.resolveConfig(otherExamplePkgJsonPath);
const otherExamplePkgJsonFileContents = await prettier.format(
stableStringify(otherExamplePkgJSON),
{
...otherExamplePrettierOptions,
filepath: otherExamplePkgJsonPath,
plugins: [prettierPluginOrganizeImports, prettierPluginEstree],
}
);
console.log(`Updated package.json for "${otherExampleName}" example`);
return Bun.write(otherExamplePkgJsonPath, otherExamplePkgJsonFileContents);
};
// #endregion
const templateExamples = Object.keys(configs);
const results = await Promise.allSettled([
...templateExamples.map(v => generateExampleFromTemplate(v)),
...otherExamples.map(v => updateOtherExample(v)),
]);
for (const [idx, result] of results.entries()) {
if (result.status === 'rejected') {
const exampleName =
idx >= templateExamples.length
? otherExamples[idx - templateExamples.length]
: templateExamples[idx];
console.log(
`Failed to generate or format "${exampleName}" example. Reason: "${result.reason}"`
);
}
}
console.log('Finished generating/updating examples');