-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathcreate-jsx.test.ts
365 lines (321 loc) · 11.2 KB
/
create-jsx.test.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import "bun";
import { expect, test, describe, beforeEach, afterAll } from "bun:test";
import { tempDirWithFiles as tempDir, bunExe, bunEnv, isCI, isWindows } from "harness";
import { cp, readdir } from "fs/promises";
import path from "path";
import puppeteer, { type Browser } from "puppeteer";
import type { Subprocess } from "bun";
import * as vm from "vm";
const env = {
...bunEnv,
};
const baseOptions = {
dumpio: !!process.env.CI_DEBUG,
args: [
"--disable-gpu",
"--disable-dev-shm-usage",
"--disable-setuid-sandbox",
"--no-sandbox",
"--ignore-certificate-errors",
"--use-fake-ui-for-media-stream",
"--use-fake-device-for-media-stream",
"--disable-sync",
],
executablePath: process.env.BROWSER_EXECUTABLE,
headless: true,
};
let puppeteerBrowser: Browser | null = null;
async function getPuppeteerBrowser() {
if (!puppeteerBrowser) {
puppeteerBrowser = await puppeteer.launch(baseOptions);
}
return puppeteerBrowser;
}
afterAll(async () => {
if (puppeteerBrowser) {
await puppeteerBrowser.close();
}
});
async function getServerUrl(process: Subprocess<any, "pipe", any>, all = { text: "" }) {
// Read the port number from stdout
const decoder = new TextDecoder();
let serverUrl = "";
all.text = "";
const reader = process.stdout.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const textChunk = decoder.decode(value, { stream: true });
all.text += textChunk;
console.log(textChunk);
if (all.text.includes("http://")) {
serverUrl = all.text.trim();
serverUrl = serverUrl.slice(serverUrl.indexOf("http://"));
serverUrl = serverUrl.slice(0, serverUrl.indexOf("\n"));
if (URL.canParse(serverUrl)) {
break;
}
serverUrl = serverUrl.slice(0, serverUrl.indexOf("/n"));
serverUrl = serverUrl.slice(0, serverUrl.lastIndexOf("/"));
serverUrl = serverUrl.trim();
if (URL.canParse(serverUrl)) {
break;
}
}
}
reader.releaseLock();
if (!serverUrl) {
throw new Error("Could not find server URL in stdout: " + all.text);
}
return serverUrl;
}
async function checkBuildOutput(dir: string) {
const distDir = path.join(dir, "dist");
const files = await readdir(distDir);
expect(files.some(f => f.endsWith(".js"))).toBe(true);
expect(files.some(f => f.endsWith(".html"))).toBe(true);
expect(files.some(f => f.endsWith(".css"))).toBe(true);
}
describe.each(["true", "false"])("development: %s", developmentString => {
const development = developmentString === "true";
const tempDirWithFiles = (name: string, files: Record<string, string>) =>
tempDir(name + (development ? "-dev" : "-prod"), files);
const normalizeHTML = normalizeHTMLFn(development);
const env = {
...bunEnv,
NODE_PORT: "0",
NODE_ENV: development ? undefined : "production",
};
const devServerLabel = development ? " dev server" : "";
describe("react spa (no tailwind)", async () => {
let dir: string;
beforeEach(async () => {
dir = tempDirWithFiles("react-spa-no-tailwind", {
"README.md": "Hello, world!",
});
await cp(path.join(__dirname, "react-spa-no-tailwind"), dir, {
recursive: true,
force: true,
});
});
test.todoIf(isCI)("dev server", async () => {
await using process = Bun.spawn([bunExe(), "create", "./index.jsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
try {
const browser = await getPuppeteerBrowser();
var page = await browser.newPage();
await page.goto(serverUrl, { waitUntil: "networkidle0" });
const content = await page.evaluate(() => document.documentElement.innerHTML);
expect(normalizeHTML(content)).toMatchSnapshot();
expect(
all.text
.replace(/v\d+\.\d+\.\d+(?:\s*\([a-f0-9]+\))?(?:-debug)?/g, "v*.*.*") // Handle version with git hash
.replace(/\[\d+\.?\d*m?s\]/g, "[*ms]")
.replace(/@\d+\.\d+\.\d+/g, "@*.*.*")
.replace(/\d+\.\d+\s*ms/g, "*.** ms")
.replace(/^\s+/gm, "") // Remove leading spaces
.replace(/installed react(-dom)?@\d+\.\d+\.\d+/g, "installed react$1@*.*.*") // Handle react versions
.trim()
.replaceAll(serverUrl, "http://[SERVER_URL]"),
).toMatchSnapshot();
} finally {
process.kill();
await Promise.resolve(page!?.close?.({ runBeforeUnload: false }));
}
});
test.todoIf(isWindows)("build", async () => {
{
const process = Bun.spawn([bunExe(), "create", "./index.jsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
process.kill();
}
const process = Bun.spawn([bunExe(), "run", "build"], {
cwd: dir,
env: env,
stdout: "pipe",
});
await process.exited;
await checkBuildOutput(dir);
});
});
describe("react spa (tailwind)", async () => {
let dir: string;
beforeEach(async () => {
dir = tempDirWithFiles("react-spa-tailwind", {
"index.tsx": await Bun.file(path.join(__dirname, "tailwind.tsx")).text(),
});
});
test.todoIf(isCI)("dev server", async () => {
const process = Bun.spawn([bunExe(), "create", "./index.tsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
console.log(serverUrl);
try {
var page = await (await getPuppeteerBrowser()).newPage();
await page.goto(serverUrl, { waitUntil: "networkidle0" });
// Check that React root exists and has Tailwind classes
const root = await page.$("#root");
expect(root).toBeTruthy();
const content = await page.evaluate(() => document.documentElement.outerHTML);
expect(normalizeHTML(content)).toMatchSnapshot();
expect(
all.text
.replace(/v\d+\.\d+\.\d+(?:\s*\([a-f0-9]+\))?(?:-debug)?/g, "v*.*.*")
.replace(/\[\d+\.?\d*m?s\]/g, "[*ms]")
.replace(/@\d+\.\d+\.\d+/g, "@*.*.*")
.replace(/\d+\.\d+\s*ms/g, "*.** ms")
.replace(/^\s+/gm, "")
.replace(/installed (react(-dom)?|tailwindcss)@\d+\.\d+\.\d+/g, "installed $1@*.*.*")
.trim()
.replaceAll(serverUrl, "http://[SERVER_URL]"),
).toMatchSnapshot();
} finally {
process.kill();
await Promise.resolve(page!?.close?.({ runBeforeUnload: false }));
}
});
test.todoIf(isWindows)("build", async () => {
{
const process = Bun.spawn([bunExe(), "create", "./index.tsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
process.kill();
}
const process = Bun.spawn([bunExe(), "run", "build"], {
cwd: dir,
env: env,
stdout: "pipe",
});
await process.exited;
await checkBuildOutput(dir);
});
});
describe(
"shadcn/ui",
async () => {
let dir: string;
beforeEach(async () => {
dir = tempDirWithFiles("shadcn-ui", {
"index.tsx": await Bun.file(path.join(__dirname, "shadcn.tsx")).text(),
});
});
test(
"dev server",
async () => {
const process = Bun.spawn([bunExe(), "create", "./index.tsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
console.log(serverUrl);
console.log(dir);
try {
var page = await (await getPuppeteerBrowser()).newPage();
await page.goto(serverUrl, { waitUntil: "networkidle0" });
// Check that React root exists and has Shadcn components
const root = await page.$("#root");
expect(root).toBeTruthy();
const content = await page.evaluate(() => document.documentElement.innerHTML);
expect(content).toContain("shadcn"); // Basic check for Shadcn classes
// Check for components.json
const componentsJson = await Bun.file(path.join(dir, "components.json")).exists();
expect(componentsJson).toBe(true);
expect(
all.text
.replace(/v\d+\.\d+\.\d+(?:\s*\([a-f0-9]+\))?(?:-debug)?/g, "v*.*.*")
.replace(/\[\d+\.?\d*m?s\]/g, "[*ms]")
.replace(/@\d+\.\d+\.\d+/g, "@*.*.*")
.replace(/\d+\.\d+\s*ms/g, "*.** ms")
.replace(/^\s+/gm, "")
.replace(
/installed (react(-dom)?|@radix-ui\/.*|tailwindcss|class-variance-authority|clsx|lucide-react|tailwind-merge)@\d+\.\d+\.\d+/g,
"installed $1@*.*.*",
)
.trim()
.replaceAll(serverUrl, "http://[SERVER_URL]"),
).toMatchSnapshot();
} finally {
process.kill();
await Promise.resolve(page!?.close?.({ runBeforeUnload: false }));
}
},
1000 * 100,
);
test.todoIf(isWindows)("build", async () => {
{
const process = Bun.spawn([bunExe(), "create", "./index.tsx"], {
cwd: dir,
env: env,
stdout: "pipe",
stdin: "ignore",
});
const all = { text: "" };
const serverUrl = await getServerUrl(process, all);
process.kill();
}
const process = Bun.spawn([bunExe(), "run", "build"], {
cwd: dir,
env: env,
stdout: "pipe",
});
await process.exited;
await checkBuildOutput(dir);
});
},
1000 * 100,
);
});
function normalizeHTMLFn(development: boolean = true) {
return (html: string) =>
html
.split("\n")
.map(line => {
// First trim the line
const trimmed = line.trim();
if (!trimmed) return "";
if (!development) {
// Replace chunk hashes in stylesheet and script tags
return trimmed.replace(
/<(link rel="stylesheet" crossorigin="" href|script type="module" crossorigin="" src)="\/chunk-[a-zA-Z0-9]+\.(css|js)("><\/script>|">)/g,
(_, tagStart, ext) => {
if (ext === "css") {
return `<${tagStart}="/chunk-[HASH].css">`;
}
return `<${tagStart}="/chunk-[HASH].js"></script>`;
},
);
}
// In development mode, replace non-deterministic generation IDs
return trimmed
.replace(/\/_bun\/client\/(.*?-[a-z0-9]{8})[a-z0-9]{8}\.js/, "/_bun/client/$1[NONDETERMINISTIC].js")
.replace(/\/_bun\/asset\/[a-z0-9]{8}[a-z0-9]{8}\.[a-z]+/, "/_bun/asset/[ASSET_HASH].css");
})
.filter(Boolean)
.join("\n")
.trim();
}