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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
import express from 'express'
import {
  existsSync,
  readFileSync,
  unlinkSync,
  writeFileSync,
  createReadStream,
} from 'fs'
import { promisify } from 'util'
import http from 'http'
import path from 'path'

import type cheerio from 'cheerio'
import spawn from 'cross-spawn'
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import { getRandomPort } from 'get-port-please'
import fetch from 'node-fetch'
import qs from 'querystring'
import treeKill from 'tree-kill'
import { once } from 'events'

import server from 'next/dist/server/next'
import _pkg from 'next/package.json'

import type { SpawnOptions, ChildProcess } from 'child_process'
import type { RequestInit, Response } from 'node-fetch'
import type { NextServer } from 'next/dist/server/next'
import { Playwright } from 'next-webdriver'

import { getTurbopackFlag, shouldRunTurboDevTest } from './turbo'
import stripAnsi from 'strip-ansi'
// TODO: Create dedicated Jest environment that sets up these matchers
// Edge Runtime unit tests fail with "EvalError: Code generation from strings disallowed for this context" if these matchers are imported in those tests.
import './add-redbox-matchers'

export { shouldRunTurboDevTest }

export const nextServer = server
export const pkg = _pkg

export function initNextServerScript(
  scriptPath: string,
  successRegexp: RegExp,
  env: NodeJS.ProcessEnv,
  failRegexp?: RegExp,
  opts?: {
    cwd?: string
    nodeArgs?: string[]
    onStdout?: (data: any) => void
    onStderr?: (data: any) => void
    // If true, the promise will reject if the process exits with a non-zero code
    shouldRejectOnError?: boolean
  }
): Promise<ChildProcess> {
  return new Promise((resolve, reject) => {
    const instance = spawn(
      'node',
      [...((opts && opts.nodeArgs) || []), '--no-deprecation', scriptPath],
      {
        env: { HOSTNAME: '::', ...env },
        cwd: opts && opts.cwd,
      }
    )

    function handleStdout(data) {
      const message = data.toString()
      if (successRegexp.test(message)) {
        resolve(instance)
      }
      process.stdout.write(message)

      if (opts && opts.onStdout) {
        opts.onStdout(message.toString())
      }
    }

    function handleStderr(data) {
      const message = data.toString()
      if (failRegexp && failRegexp.test(message)) {
        instance.kill()
        return reject(new Error('received failRegexp'))
      }
      process.stderr.write(message)

      if (opts && opts.onStderr) {
        opts.onStderr(message.toString())
      }
    }

    if (opts?.shouldRejectOnError) {
      instance.on('exit', (code) => {
        if (code !== 0) {
          reject(new Error('exited with code: ' + code))
        }
      })
    }

    instance.stdout!.on('data', handleStdout)
    instance.stderr!.on('data', handleStderr)

    instance.on('close', () => {
      instance.stdout!.removeListener('data', handleStdout)
      instance.stderr!.removeListener('data', handleStderr)
    })

    instance.on('error', (err) => {
      reject(err)
    })
  })
}

export function getFullUrl(
  appPortOrUrl: string | number,
  url?: string,
  hostname?: string
) {
  let fullUrl =
    typeof appPortOrUrl === 'string' && appPortOrUrl.startsWith('http')
      ? appPortOrUrl
      : `http://${hostname ? hostname : 'localhost'}:${appPortOrUrl}${url}`

  if (typeof appPortOrUrl === 'string' && url) {
    const parsedUrl = new URL(fullUrl)
    const parsedPathQuery = new URL(url, fullUrl)

    parsedUrl.hash = parsedPathQuery.hash
    parsedUrl.search = parsedPathQuery.search
    parsedUrl.pathname = parsedPathQuery.pathname

    if (hostname && parsedUrl.hostname === 'localhost') {
      parsedUrl.hostname = hostname
    }
    fullUrl = parsedUrl.toString()
  }
  return fullUrl
}

/**
 * Appends the querystring to the url
 *
 * @param pathname the pathname
 * @param query the query object to add to the pathname
 * @returns the pathname with the query
 */
export function withQuery(
  pathname: string,
  query: Record<string, any> | string
) {
  const querystring = typeof query === 'string' ? query : qs.stringify(query)
  if (querystring.length === 0) {
    return pathname
  }

  // If there's a `?` between the pathname and the querystring already, then
  // don't add another one.
  if (querystring.startsWith('?') || pathname.endsWith('?')) {
    return `${pathname}${querystring}`
  }

  return `${pathname}?${querystring}`
}

export function getFetchUrl(
  appPort: string | number,
  pathname: string,
  query?: Record<string, any> | string | null | undefined
) {
  const url = query ? withQuery(pathname, query) : pathname
  return getFullUrl(appPort, url)
}

export function fetchViaHTTP(
  appPort: string | number,
  pathname: string,
  query?: Record<string, any> | string | null | undefined,
  opts?: RequestInit
): Promise<Response> {
  const url = query ? withQuery(pathname, query) : pathname
  return fetch(getFullUrl(appPort, url), opts)
}

export function renderViaHTTP(
  appPort: string | number,
  pathname: string,
  query?: Record<string, any> | string | undefined,
  opts?: RequestInit
) {
  return fetchViaHTTP(appPort, pathname, query, opts).then((res) => res.text())
}

export function findPort() {
  // [NOTE] What are we doing here?
  // There are some flaky tests failures caused by `No available ports found` from 'get-port'.
  // This may be related / fixed by upstream https://github.com/sindresorhus/get-port/pull/56,
  // however it happened after get-port switched to pure esm which is not easy to adapt by bump.
  // get-port-please seems to offer the feature parity so we'll try to use it, and leave get-port as fallback
  // for a while until we are certain to switch to get-port-please entirely.
  try {
    return getRandomPort()
  } catch (e) {
    require('console').warn('get-port-please failed, falling back to get-port')
    return getPort()
  }
}

export interface NextOptions {
  cwd?: string
  env?: NodeJS.Dict<string>
  nodeArgs?: string[]

  spawnOptions?: SpawnOptions
  instance?: (instance: ChildProcess) => void
  stderr?: true | 'log'
  stdout?: true | 'log'
  ignoreFail?: boolean

  /**
   * If true, this enables the linting step in the build process. If false or
   * undefined, it adds a `--no-lint` flag to the build command.
   */
  lint?: boolean

  onStdout?: (data: any) => void
  onStderr?: (data: any) => void
}

export function runNextCommand(
  argv: string[],
  options: NextOptions = {}
): Promise<{
  code: number | null
  signal: NodeJS.Signals | null
  stdout: string
  stderr: string
}> {
  const nextDir = path.dirname(require.resolve('next/package'))
  const nextBin = path.join(nextDir, 'dist/bin/next')
  const cwd = options.cwd || nextDir
  // Let Next.js decide the environment
  const env = {
    ...process.env,
    // @ts-ignore packages/next/types/global.d.ts should allow undefined NODE_ENV
    NODE_ENV: undefined as NodeJS.ProcessEnv['NODE_ENV'],
    __NEXT_TEST_MODE: 'true',
    ...options.env,
  }

  return new Promise((resolve, reject) => {
    console.log(`Running command "next ${argv.join(' ')}"`)
    const instance = spawn(
      'node',
      [...(options.nodeArgs || []), '--no-deprecation', nextBin, ...argv],
      {
        ...options.spawnOptions,
        cwd,
        env,
        stdio: ['ignore', 'pipe', 'pipe'],
      }
    )

    if (typeof options.instance === 'function') {
      options.instance(instance)
    }

    let mergedStdio = ''

    let stderrOutput = ''
    if (options.stderr || options.onStderr) {
      instance.stderr!.on('data', function (chunk) {
        mergedStdio += chunk
        stderrOutput += chunk

        if (options.stderr === 'log') {
          console.log(chunk.toString())
        }
        if (typeof options.onStderr === 'function') {
          options.onStderr(chunk.toString())
        }
      })
    } else {
      instance.stderr!.on('data', function (chunk) {
        mergedStdio += chunk
      })
    }

    let stdoutOutput = ''
    if (options.stdout || options.onStdout) {
      instance.stdout!.on('data', function (chunk) {
        mergedStdio += chunk
        stdoutOutput += chunk

        if (options.stdout === 'log') {
          console.log(chunk.toString())
        }
        if (typeof options.onStdout === 'function') {
          options.onStdout(chunk.toString())
        }
      })
    } else {
      instance.stdout!.on('data', function (chunk) {
        mergedStdio += chunk
      })
    }

    instance.on('close', (code, signal) => {
      if (
        !options.stderr &&
        !options.stdout &&
        !options.ignoreFail &&
        (code !== 0 || signal)
      ) {
        return reject(
          new Error(
            `command failed with code ${code} signal ${signal}\n${mergedStdio}`
          )
        )
      }

      if (code || signal) {
        console.error(`process exited with code ${code} and signal ${signal}`)
      }
      resolve({
        code,
        signal,
        stdout: stdoutOutput,
        stderr: stderrOutput,
      })
    })

    instance.on('error', (err) => {
      err['stdout'] = stdoutOutput
      err['stderr'] = stderrOutput
      reject(err)
    })
  })
}

export interface NextDevOptions {
  cwd?: string
  env?: NodeJS.Dict<string>
  nodeArgs?: string[]
  nextBin?: string

  bootupMarker?: RegExp
  nextStart?: boolean
  turbo?: boolean

  stderr?: false
  stdout?: false

  onStdout?: (data: any) => void
  onStderr?: (data: any) => void
}

export function runNextCommandDev(
  argv: string[],
  stdOut?: boolean,
  opts: NextDevOptions = {}
): Promise<(typeof stdOut extends true ? string : ChildProcess) | undefined> {
  const nextDir = path.dirname(require.resolve('next/package'))
  const nextBin = opts.nextBin || path.join(nextDir, 'dist/bin/next')
  const cwd = opts.cwd || nextDir
  const env = {
    ...process.env,
    // @ts-ignore packages/next/types/global.d.ts should allow undefined NODE_ENV
    NODE_ENV: undefined as NodeJS.ProcessEnv['NODE_ENV'],
    __NEXT_TEST_MODE: 'true',
    ...opts.env,
  }

  const nodeArgs = opts.nodeArgs || []
  return new Promise((resolve, reject) => {
    const instance = spawn(
      'node',
      [...nodeArgs, '--no-deprecation', nextBin, ...argv],
      {
        cwd,
        env,
      }
    )
    let didResolve = false

    const bootType =
      opts.nextStart || stdOut ? 'start' : opts?.turbo ? 'turbo' : 'dev'

    function handleStdout(data) {
      const message = data.toString()
      const bootupMarkers = {
        dev: /✓ ready/i,
        turbo: /✓ ready/i,
        start: /✓ ready/i,
      }

      const strippedMessage = stripAnsi(message) as any

      if (
        (opts.bootupMarker && opts.bootupMarker.test(strippedMessage)) ||
        bootupMarkers[bootType].test(strippedMessage)
      ) {
        if (!didResolve) {
          didResolve = true
          // Pass down the original message
          resolve(stdOut ? message : instance)
        }
      }

      if (typeof opts.onStdout === 'function') {
        opts.onStdout(message)
      }

      if (opts.stdout !== false) {
        process.stdout.write(message)
      }
    }

    function handleStderr(data) {
      const message = data.toString()

      if (typeof opts.onStderr === 'function') {
        opts.onStderr(message)
      }

      if (opts.stderr !== false) {
        process.stderr.write(message)
      }
    }

    instance.stderr!.on('data', handleStderr)
    instance.stdout!.on('data', handleStdout)

    instance.on('close', () => {
      instance.stderr!.removeListener('data', handleStderr)
      instance.stdout!.removeListener('data', handleStdout)
      if (!didResolve) {
        didResolve = true
        resolve(undefined)
      }
    })

    instance.on('error', (err) => {
      reject(err)
    })
  })
}

// Launch the app in development mode.
export function launchApp(
  dir: string,
  port: string | number,
  opts?: NextDevOptions
) {
  const options = opts ?? {}
  const useTurbo = shouldRunTurboDevTest()

  return runNextCommandDev(
    [
      useTurbo ? getTurbopackFlag() : undefined,
      dir,
      '-p',
      port as string,
      '--hostname',
      '::',
    ].filter((flag: string | undefined): flag is string => Boolean(flag)),
    undefined,
    { ...options, turbo: useTurbo }
  )
}

export function nextBuild(
  dir: string,
  args: string[] = [],
  opts: NextOptions = {}
) {
  // If the build hasn't requested it to be linted explicitly, disable linting
  // if it's not already disabled.
  if (!opts.lint && !args.includes('--no-lint')) {
    args.push('--no-lint')
  }

  return runNextCommand(['build', dir, ...args], opts)
}

export function nextLint(
  dir: string,
  args: string[] = [],
  opts: NextOptions = {}
) {
  return runNextCommand(['lint', dir, ...args], opts)
}

export function nextTest(
  dir: string,
  args: string[] = [],
  opts: NextOptions = {}
) {
  return runNextCommand(['experimental-test', dir, ...args], {
    ...opts,
    env: {
      JEST_WORKER_ID: undefined, // Playwright complains about being executed by Jest
      ...opts.env,
    },
  })
}

export function nextStart(
  dir: string,
  port: string | number,
  opts: NextDevOptions = {}
) {
  return runNextCommandDev(
    ['start', '-p', port as string, '--hostname', '::', dir],
    undefined,
    { ...opts, nextStart: true }
  )
}

export function buildTS(
  args: string[] = [],
  cwd?: string,
  env?: any
): Promise<void> {
  cwd = cwd || path.dirname(require.resolve('next/package'))
  env = { ...process.env, NODE_ENV: undefined, ...env }

  return new Promise((resolve, reject) => {
    const instance = spawn(
      'node',
      ['--no-deprecation', require.resolve('typescript/lib/tsc'), ...args],
      { cwd, env }
    )
    let output = ''

    const handleData = (chunk) => {
      output += chunk.toString()
    }

    instance.stdout!.on('data', handleData)
    instance.stderr!.on('data', handleData)

    instance.on('exit', (code) => {
      if (code) {
        return reject(new Error('exited with code: ' + code + '\n' + output))
      }
      resolve()
    })
  })
}

export async function killProcess(
  pid: number,
  signal: NodeJS.Signals | number = 'SIGTERM'
): Promise<void> {
  return await new Promise((resolve, reject) => {
    treeKill(pid, signal, (err) => {
      if (err) {
        if (
          process.platform === 'win32' &&
          typeof err.message === 'string' &&
          (err.message.includes(`no running instance of the task`) ||
            err.message.includes(`not found`))
        ) {
          // Windows throws an error if the process is already dead
          //
          // Command failed: taskkill /pid 6924 /T /F
          // ERROR: The process with PID 6924 (child process of PID 6736) could not be terminated.
          // Reason: There is no running instance of the task.
          return resolve()
        }
        return reject(err)
      }

      resolve()
    })
  })
}

// Kill a launched app
export async function killApp(
  instance?: ChildProcess,
  signal: NodeJS.Signals | number = 'SIGKILL'
) {
  if (!instance) {
    return
  }
  if (
    instance?.pid &&
    instance.exitCode === null &&
    instance.signalCode === null
  ) {
    const exitPromise = once(instance, 'exit')
    await killProcess(instance.pid, signal)
    await exitPromise
  }
}

async function startListen(server: http.Server, port?: number) {
  const listenerPromise = new Promise((resolve) => {
    server['__socketSet'] = new Set()
    const listener = server.listen(port, () => {
      resolve(null)
    })

    listener.on('connection', function (socket) {
      server['__socketSet'].add(socket)
      socket.on('close', () => {
        server['__socketSet'].delete(socket)
      })
    })
  })
  await listenerPromise
}

export async function startApp(app: NextServer) {
  // force require usage instead of dynamic import in jest
  // x-ref: https://github.com/nodejs/node/issues/35889
  process.env.__NEXT_TEST_MODE = 'jest'

  // TODO: tests that use this should be migrated to use
  // the nextStart test function instead as it tests outside
  // of jest's context
  await app.prepare()
  const handler = app.getRequestHandler()
  const server = http.createServer(handler)
  server['__app'] = app

  await startListen(server)

  return server
}

export async function stopApp(server: http.Server | undefined) {
  if (!server) {
    return
  }

  if (server['__app']) {
    await server['__app'].close()
  }

  // Node.js's http::close() prevents new connections from being accepted,
  // but doesn't close existing connections and if there are any leftover
  // whole process teardown will wait until it's being closed.
  // Instead, force close connections since this is teardown fn that we expect
  // any connections to be closed already.
  server['__socketSet']?.forEach(function (socket) {
    if (!socket.closed && !socket.destroyed) {
      socket.destroy()
    }
  })

  await promisify(server.close).apply(server)
}

export async function waitFor(
  millisOrCondition: number | (() => boolean)
): Promise<void> {
  if (typeof millisOrCondition === 'number') {
    return new Promise((resolve) => setTimeout(resolve, millisOrCondition))
  }

  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (millisOrCondition()) {
        clearInterval(interval)
        resolve()
      }
    }, 100)
  })
}

export async function startStaticServer(
  dir: string,
  notFoundFile?: string,
  fixedPort?: number
) {
  const app = express()
  const server = http.createServer(app)
  app.use(express.static(dir))

  if (notFoundFile) {
    app.use((req, res) => {
      createReadStream(notFoundFile).pipe(res)
    })
  }

  await startListen(server, fixedPort)
  return server
}

export async function startCleanStaticServer(dir: string) {
  const app = express()
  const server = http.createServer(app)
  app.use(express.static(dir, { extensions: ['html'] }))

  await startListen(server)
  return server
}

/**
 * Check for content in 1 second intervals timing out after 30 seconds.
 * @deprecated use retry + expect instead
 * @param {() => Promise<unknown> | unknown} contentFn
 * @param {RegExp | string | number} regex
 * @param {boolean} hardError
 * @param {number} maxRetries
 * @returns {Promise<boolean>}
 */
export async function check(
  contentFn: () => any | Promise<any>,
  regex: any,
  hardError = true,
  maxRetries = 30
) {
  let content
  let lastErr

  for (let tries = 0; tries < maxRetries; tries++) {
    try {
      content = await contentFn()
      if (typeof regex !== typeof /regex/) {
        if (regex === content) {
          return true
        }
      } else if (regex.test(content)) {
        // found the content
        return true
      }
      await waitFor(1000)
    } catch (err) {
      await waitFor(1000)
      lastErr = err
    }
  }
  console.error('TIMED OUT CHECK: ', { regex, content, lastErr })

  if (hardError) {
    throw new Error('TIMED OUT: ' + regex + '\n\n' + content + '\n\n' + lastErr)
  }
  return false
}

export class File {
  path: string
  originalContent: string | null

  constructor(path: string) {
    this.path = path
    this.originalContent = existsSync(this.path)
      ? readFileSync(this.path, 'utf8')
      : null
  }

  write(content: string) {
    if (!this.originalContent) {
      this.originalContent = content
    }
    writeFileSync(this.path, content, 'utf8')
  }

  replace(pattern: RegExp | string, newValue: string) {
    const currentContent = readFileSync(this.path, 'utf8')
    if (pattern instanceof RegExp) {
      if (!pattern.test(currentContent)) {
        throw new Error(
          `Failed to replace content.\n\nPattern: ${pattern.toString()}\n\nContent: ${currentContent}`
        )
      }
    } else if (typeof pattern === 'string') {
      if (!currentContent.includes(pattern)) {
        throw new Error(
          `Failed to replace content.\n\nPattern: ${pattern}\n\nContent: ${currentContent}`
        )
      }
    } else {
      throw new Error(`Unknown replacement attempt type: ${pattern}`)
    }

    const newContent = currentContent.replace(pattern, newValue)
    this.write(newContent)
  }

  prepend(str: string) {
    const content = readFileSync(this.path, 'utf8')
    this.write(str + content)
  }

  delete() {
    unlinkSync(this.path)
  }

  restore() {
    this.write(this.originalContent!)
  }
}

export async function retry<T>(
  fn: () => T | Promise<T>,
  duration: number = 3000,
  interval: number = 500,
  description?: string
): Promise<T> {
  if (duration % interval !== 0) {
    throw new Error(
      `invalid duration ${duration} and interval ${interval} mix, duration must be evenly divisible by interval`
    )
  }

  for (let i = duration; i >= 0; i -= interval) {
    try {
      return await fn()
    } catch (err) {
      if (i === 0) {
        console.error(
          `Failed to retry${
            description ? ` ${description}` : ''
          } within ${duration}ms`
        )
        throw err
      }
      console.log(
        `Retrying${description ? ` ${description}` : ''} in ${interval}ms`
      )
      await waitFor(interval)
    }
  }

  throw new Error('Duration cannot be less than 0.')
}

export async function assertHasRedbox(browser: Playwright) {
  const redbox = browser.locateRedbox()
  try {
    await redbox.waitFor({ timeout: 5000 })
  } catch (errorCause) {
    const error = new Error('Expected Redbox but found no visible one.')
    Error.captureStackTrace(error, assertHasRedbox)
    throw error
  }

  try {
    await redbox
      .locator('[data-nextjs-error-suspended]')
      .waitFor({ state: 'detached', timeout: 10000 })
  } catch (cause) {
    const error = new Error('Redbox still had suspended content after 10s', {
      cause,
    })
    Error.captureStackTrace(error, assertHasRedbox)
    throw error
  }
}

export async function assertNoRedbox(
  browser: Playwright,
  { waitInMs = 5000 }: { waitInMs?: number } = {}
) {
  await waitFor(waitInMs)
  const redbox = browser.locateRedbox()

  if (await redbox.isVisible()) {
    const [redboxHeader, redboxDescription, redboxSource] = await Promise.all([
      getRedboxHeader(browser).catch(() => '<missing>'),
      getRedboxDescription(browser).catch(() => '<missing>'),
      getRedboxSource(browser).catch(() => '<missing>'),
    ])

    const error = new Error(
      'Expected no visible Redbox but found one\n' +
        `header: ${redboxHeader}\n` +
        `description: ${redboxDescription}\n` +
        `source: ${redboxSource}`
    )
    Error.captureStackTrace(error, assertNoRedbox)
    throw error
  }
}

export async function assertNoErrorToast(browser: Playwright): Promise<void> {
  let didOpenRedbox = false

  try {
    await browser.waitForElementByCss('[data-issues]').click()
    didOpenRedbox = true
  } catch {
    // We expect this to fail.
  }

  if (didOpenRedbox) {
    // If a redbox was opened unexpectedly, we use the `assertNoRedbox` helper
    // to print a useful error message containing the redbox contents.
    await assertNoRedbox(browser, {
      // We already know the redbox is open, so we can skip waiting for it.
      waitInMs: 0,
    })
  }
}

export async function hasErrorToast(browser: Playwright): Promise<boolean> {
  return Boolean(
    await browser.eval(() => {
      const portal = [].slice
        .call(document.querySelectorAll('nextjs-portal'))
        .find((p) => p.shadowRoot.querySelector('[data-issues]'))

      const root = portal?.shadowRoot
      const node = root?.querySelector('[data-issues-count]')
      return !!node
    })
  )
}

export async function getToastErrorCount(browser: Playwright): Promise<number> {
  return parseInt(
    (await browser.eval(() => {
      const portal = [].slice
        .call(document.querySelectorAll('nextjs-portal'))
        .find((p) => p.shadowRoot.querySelector('[data-issues]'))

      const root = portal?.shadowRoot
      const node = root?.querySelector('[data-issues-count]')
      return node?.innerText || '0'
    })) ?? '0'
  )
}

/**
 * Has retried version of {@link hasErrorToast} built-in.
 * Success implies {@link assertHasRedbox}.
 */
export async function openRedbox(browser: Playwright): Promise<void> {
  const redbox = browser.locateRedbox()
  if (await redbox.isVisible()) {
    const error = new Error(
      'Redbox is already open. Use `assertHasRedbox` instead.'
    )
    Error.captureStackTrace(error, openRedbox)
    throw error
  }

  try {
    await browser.waitForElementByCss('[data-issues]').click()
  } catch (cause) {
    const error = new Error('Redbox did not open.')
    Error.captureStackTrace(error, openRedbox)
    throw error
  }
  await assertHasRedbox(browser)
}

export async function openDevToolsIndicatorPopover(
  browser: Playwright
): Promise<void> {
  const devToolsIndicator = await assertHasDevToolsIndicator(browser)

  try {
    await devToolsIndicator.click()
  } catch (cause) {
    const error = new Error('No DevTools Indicator to open.', { cause })
    Error.captureStackTrace(error, openDevToolsIndicatorPopover)
    throw error
  }
}

export async function getSegmentExplorerRoute(browser: Playwright) {
  return await browser
    .elementByCss('.segment-explorer-page-route-bar-path')
    .text()
}

export async function getSegmentExplorerContent(browser: Playwright) {
  // open the devtool button
  await openDevToolsIndicatorPopover(browser)

  // open the segment explorer
  await browser.elementByCss('[data-segment-explorer]').click()

  //  wait for the segment explorer to be visible
  await browser.waitForElementByCss('[data-nextjs-devtool-segment-explorer]')

  const rows = await browser.elementsByCss('.segment-explorer-item')
  let result: string[] = []
  for (const row of rows) {
    // query filename of row: segment-explorer-filename
    const segment = (
      (await (await row.$('.segment-explorer-filename--path'))?.innerText()) ||
      ''
    ).trim()
    const files = (
      (await (await row.$('.segment-explorer-files'))?.innerText()) || ''
    )
      .split(/\n+/)
      .map((file) => file.trim())

    // line format: segment [files]
    result.push(`${segment} [${files.join(', ')}]`)
  }
  return result.join('\n')
}

export async function hasDevToolsPanel(browser: Playwright) {
  const result = await browser.eval(() => {
    const portal = document.querySelector('nextjs-portal')
    return (
      portal?.shadowRoot?.querySelector('[data-nextjs-dialog-overlay]') != null
    )
  })
  return result
}

export async function assertHasDevToolsIndicator(browser: Playwright) {
  const devToolsIndicator = browser.locateDevToolsIndicator()
  try {
    await devToolsIndicator.waitFor({ timeout: 5000 })
  } catch (errorCause) {
    const error = new Error(
      'Expected DevTools Indicator but found no visible one.'
    )
    Error.captureStackTrace(error, assertHasDevToolsIndicator)
    throw error
  }

  return devToolsIndicator
}

export async function assertNoDevToolsIndicator(browser: Playwright) {
  const devToolsIndicator = browser.locateDevToolsIndicator()

  if (await devToolsIndicator.isVisible()) {
    const error = new Error(
      'Expected no visible DevTools Indicator but found one.'
    )
    Error.captureStackTrace(error, assertNoDevToolsIndicator)
    throw error
  }
}

export async function getRouteTypeFromDevToolsIndicator(
  browser: Playwright
): Promise<'Static' | 'Dynamic'> {
  await openDevToolsIndicatorPopover(browser)

  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-toast]'))

    const root = portal?.shadowRoot

    // 'Route\nStatic' || 'Route\nDynamic'
    const routeTypeText = root?.querySelector(
      '[data-nextjs-route-type]'
    )?.innerText

    if (!routeTypeText) {
      throw new Error('No Route Type Text Found')
    }

    // 'Static' || 'Dynamic'
    const routeType = routeTypeText.split('\n').pop()
    if (routeType !== 'Static' && routeType !== 'Dynamic') {
      throw new Error(`Invalid Route Type: ${routeType}`)
    }

    return routeType as 'Static' | 'Dynamic'
  })
}

export function getRedboxHeader(browser: Playwright): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal?.shadowRoot
    return root?.querySelector('[data-nextjs-dialog-header]')?.innerText ?? null
  })
}

export async function getRedboxTotalErrorCount(
  browser: Playwright
): Promise<number> {
  const text = await browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) =>
        p.shadowRoot.querySelector('[data-nextjs-dialog-header-total-count]')
      )

    const root = portal?.shadowRoot
    return root?.querySelector('[data-nextjs-dialog-header-total-count]')
      ?.innerText
  })
  return parseInt(text || '-1')
}

export function getRedboxSource(browser: Playwright): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) =>
        p.shadowRoot.querySelector(
          '#nextjs__container_errors_label, #nextjs__container_errors_label'
        )
      )
    const root = portal.shadowRoot
    return (
      root.querySelector('[data-nextjs-codeframe], [data-nextjs-terminal]')
        ?.innerText ?? null
    )
  })
}

export function getRedboxTitle(browser: Playwright): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector(
        '[data-nextjs-dialog-header] .nextjs__container_errors__error_title'
      )?.innerText ?? null
    )
  })
}

export function getRedboxLabel(browser: Playwright): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector('#nextjs__container_errors_label')?.innerText ?? null
    )
  })
}

export function getRedboxEnvironmentLabel(
  browser: Playwright
): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector('[data-nextjs-environment-name-label]')?.innerText ??
      null
    )
  })
}

export function getRedboxDescription(
  browser: Playwright
): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector('#nextjs__container_errors_desc')?.innerText ?? null
    )
  })
}

export function getRedboxDescriptionWarning(
  browser: Playwright
): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector('#nextjs__container_errors__notes')?.innerText ?? null
    )
  })
}

export function getRedboxErrorLink(
  browser: Playwright
): Promise<string | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-header]'))
    const root = portal.shadowRoot
    return (
      root.querySelector('#nextjs__container_errors__link')?.innerText ?? null
    )
  })
}

export function getBrowserBodyText(browser: Playwright) {
  return browser.eval<string>(
    'document.getElementsByTagName("body")[0].innerText'
  )
}

export function normalizeRegEx(src: string) {
  return new RegExp(src).source.replace(/\^\//g, '^\\/')
}

function readJson(path: string) {
  return JSON.parse(readFileSync(path, 'utf-8'))
}

export function getBuildManifest(dir: string) {
  return readJson(path.join(dir, '.next/build-manifest.json'))
}

export function getImagesManifest(dir: string) {
  return readJson(path.join(dir, '.next/images-manifest.json'))
}

export function getPageFilesFromBuildManifest(dir: string, page: string) {
  const buildManifest = getBuildManifest(dir)
  const pageFiles = buildManifest.pages[page]
  if (!pageFiles) {
    throw new Error(`No files for page ${page}`)
  }

  return pageFiles
}

export function getContentOfPageFilesFromBuildManifest(
  dir: string,
  page: string
): string {
  const pageFiles = getPageFilesFromBuildManifest(dir, page)

  return pageFiles
    .map((file) => readFileSync(path.join(dir, '.next', file), 'utf8'))
    .join('\n')
}

export function getPageFileFromBuildManifest(dir: string, page: string) {
  const pageFiles = getPageFilesFromBuildManifest(dir, page)

  const pageFile = pageFiles[pageFiles.length - 1]
  expect(pageFile).toEndWith('.js')
  if (!process.env.IS_TURBOPACK_TEST) {
    expect(pageFile).toInclude(`pages${page === '' ? '/index' : page}`)
  }
  if (!pageFile) {
    throw new Error(`No page file for page ${page}`)
  }

  return pageFile
}

export function readNextBuildClientPageFile(appDir: string, page: string) {
  const pageFile = getPageFileFromBuildManifest(appDir, page)
  return readFileSync(path.join(appDir, '.next', pageFile), 'utf8')
}

export function getPagesManifest(dir: string) {
  const serverFile = path.join(dir, '.next/server/pages-manifest.json')

  return readJson(serverFile)
}

export function updatePagesManifest(dir: string, content: any) {
  const serverFile = path.join(dir, '.next/server/pages-manifest.json')

  return writeFile(serverFile, content)
}

export function getPageFileFromPagesManifest(dir: string, page: string) {
  const pagesManifest = getPagesManifest(dir)
  const pageFile = pagesManifest[page]
  if (!pageFile) {
    throw new Error(`No file for page ${page}`)
  }

  return pageFile
}

export function readNextBuildServerPageFile(appDir: string, page: string) {
  const pageFile = getPageFileFromPagesManifest(appDir, page)
  return readFileSync(path.join(appDir, '.next', 'server', pageFile), 'utf8')
}

export function getClientBuildManifest(dir: string) {
  let buildId = readFileSync(path.join(dir, '.next/BUILD_ID'), 'utf8')
  let code = readFileSync(
    path.join(dir, '.next/static', buildId, '_buildManifest.js'),
    'utf8'
  )
  // eslint-disable-next-line no-eval
  let manifest = (0, eval)(`var self = global;${code};self.__BUILD_MANIFEST`)
  return manifest
}

export function getClientBuildManifestLoaderChunkUrlPath(
  dir: string,
  page: string
) {
  let manifest = getClientBuildManifest(dir)
  let chunk: string[] | undefined = manifest[page]
  if (chunk == null) {
    throw new Error(`Couldn't find page "${page}" in _buildManifest.js`)
  }
  if (chunk.length !== 1) {
    throw new Error(
      `Expected a single chunk, but found ${chunk.length} for "${page}" in _buildManifest.js`
    )
  }
  // Remove leading './' so that this can be used in a `url.contains(chunk)` check.
  return encodeURI(chunk[0].replace(/^\.\//, ''))
}

function runSuite(
  suiteName: string,
  context: { env: 'prod' | 'dev'; appDir: string } & Partial<{
    stderr: string
    stdout: string
    appPort: number
    code: number | null
    server: ChildProcess
  }>,
  options: {
    beforeAll?: Function
    afterAll?: Function
    runTests: Function
  } & NextDevOptions
) {
  const { appDir, env } = context
  describe(`${suiteName} ${env}`, () => {
    beforeAll(async () => {
      options.beforeAll?.(env)
      context.stderr = ''
      const onStderr = (msg) => {
        context.stderr += msg
      }
      context.stdout = ''
      const onStdout = (msg) => {
        context.stdout += msg
      }
      if (env === 'prod') {
        context.appPort = await findPort()
        const { stdout, stderr, code } = await nextBuild(appDir, [], {
          stderr: true,
          stdout: true,
          env: options.env || {},
          nodeArgs: options.nodeArgs,
        })
        context.stdout = stdout
        context.stderr = stderr
        context.code = code
        context.server = await nextStart(context.appDir, context.appPort, {
          onStderr,
          onStdout,
          env: options.env || {},
          nodeArgs: options.nodeArgs,
        })
      } else if (env === 'dev') {
        context.appPort = await findPort()
        context.server = await launchApp(context.appDir, context.appPort, {
          onStderr,
          onStdout,
          env: options.env || {},
          nodeArgs: options.nodeArgs,
        })
      }
    })
    afterAll(async () => {
      options.afterAll?.(env)
      if (context.server) {
        await killApp(context.server)
      }
    })
    options.runTests(context, env)
  })
}

export function runDevSuite(
  suiteName: string,
  appDir: string,
  options: {
    beforeAll?: Function
    afterAll?: Function
    runTests: Function
    env?: NodeJS.ProcessEnv
  }
) {
  return runSuite(suiteName, { appDir, env: 'dev' }, options)
}

export function runProdSuite(
  suiteName: string,
  appDir: string,
  options: {
    beforeAll?: Function
    afterAll?: Function
    runTests: Function
    env?: NodeJS.ProcessEnv
  }
) {
  ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
    'production mode',
    () => {
      runSuite(suiteName, { appDir, env: 'prod' }, options)
    }
  )
}

/**
 * Parse the output and return all entries that match the provided `eventName`
 * @param {string} output output of the console
 * @param {string} eventName
 * @returns {Array<{}>}
 */
export function findAllTelemetryEvents(output: string, eventName: string) {
  const regex = /\[telemetry\] ({.+?^})/gms
  // Pop the last element of each entry to retrieve contents of the capturing group
  const events = [...output.matchAll(regex)].map((entry) =>
    JSON.parse(entry.pop()!)
  )
  return events.filter((e) => e.eventName === eventName).map((e) => e.payload)
}

type TestVariants = 'default' | 'turbo'

// WEB-168: There are some differences / incompletes in turbopack implementation enforces jest requires to update
// test snapshot when run against turbo. This fn returns describe, or describe.skip dependes on the running context
// to avoid force-snapshot update per each runs until turbopack update includes all the changes.
export function getSnapshotTestDescribe(variant: TestVariants) {
  const runningEnv = variant ?? 'default'
  if (runningEnv !== 'default' && runningEnv !== 'turbo') {
    throw new Error(
      `An invalid test env was passed: ${variant} (only "default" and "turbo" are valid options)`
    )
  }

  const shouldRunTurboDev = shouldRunTurboDevTest()
  const shouldSkip =
    (runningEnv === 'turbo' && !shouldRunTurboDev) ||
    (runningEnv === 'default' && shouldRunTurboDev)

  return shouldSkip ? describe.skip : describe
}

/**
 * @returns `null` if there are no frames
 */
export async function getRedboxComponentStack(
  browser: Playwright
): Promise<string | null> {
  const componentStackFrameElements = await browser.elementsByCss(
    '[data-nextjs-container-errors-pseudo-html] code'
  )
  if (componentStackFrameElements.length === 0) {
    return null
  }

  const componentStackFrameTexts = await Promise.all(
    componentStackFrameElements.map((f) => f.innerText())
  )

  return componentStackFrameTexts.join('\n').trim()
}

export async function hasRedboxCallStack(browser: Playwright) {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-dialog-body]'))
    const root = portal?.shadowRoot

    return root?.querySelectorAll('[data-nextjs-call-stack-frame]').length > 0
  })
}

export async function getRedboxCallStack(
  browser: Playwright
): Promise<string[] | null> {
  return browser.eval(() => {
    const portal = [].slice
      .call(document.querySelectorAll('nextjs-portal'))
      .find((p) => p.shadowRoot.querySelector('[data-nextjs-call-stack-frame]'))
    const root = portal?.shadowRoot
    const frameElements = root?.querySelectorAll(
      '[data-nextjs-call-stack-frame]'
    )

    const stack: string[] = []
    if (frameElements !== undefined) {
      let foundInternalFrame = false
      for (const frameElement of frameElements) {
        // `innerText` will be "${methodName}\n${location}".
        // Ideally `innerText` would be "${methodName} ${location}"
        // so that c&p automatically does the right thing.
        const frame = frameElement.innerText.replace('\n', ' ')

        // TODO: Special marker if source-mapping fails.

        // Feel free to adjust this heuristic if it accidentally hides too much.
        const isInternalFrame =
          // likely https://linear.app/vercel/issue/NDX-464
          // location starts with `./dist` e.g. "NotFoundBoundary ./dist/esm/[...]"
          / .\/dist\//.test(frame)

        if (isInternalFrame) {
          // We only add one of these frames.
          // If we'd add all of them, the stack would change during refactorings which is annoying.
          if (!foundInternalFrame) {
            stack.push('<FIXME-internal-frame>')
          }
          foundInternalFrame = true
        } else if (frame.includes('file://')) {
          stack.push('<FIXME-file-protocol>')
        } else if (frame.includes('.next/')) {
          stack.push('<FIXME-next-dist-dir>')
        } else {
          stack.push(frame)
        }
      }
    }

    return stack
  })
}

export async function getRedboxCallStackCollapsed(
  browser: Playwright
): Promise<string> {
  const callStackFrameElements = await browser.elementsByCss(
    '.nextjs-container-errors-body > [data-nextjs-codeframe] > :first-child, ' +
      '.nextjs-container-errors-body > [data-nextjs-call-stack-frame], ' +
      '.nextjs-container-errors-body > [data-nextjs-collapsed-call-stack-details] > summary'
  )
  const callStackFrameTexts = await Promise.all(
    callStackFrameElements.map((f) => f.innerText())
  )

  return callStackFrameTexts.join('\n---\n').trim()
}

export async function getVersionCheckerText(
  browser: Playwright
): Promise<string> {
  await browser.waitForElementByCss('[data-nextjs-version-checker]', 30000)
  const versionCheckerElement = await browser.elementByCss(
    '[data-nextjs-version-checker]'
  )
  const versionCheckerText = await versionCheckerElement.innerText()
  return versionCheckerText.trim()
}

export function colorToRgb(color) {
  switch (color) {
    case 'blue':
      return 'rgb(0, 0, 255)'
    case 'red':
      return 'rgb(255, 0, 0)'
    case 'green':
      return 'rgb(0, 128, 0)'
    case 'yellow':
      return 'rgb(255, 255, 0)'
    case 'purple':
      return 'rgb(128, 0, 128)'
    case 'black':
      return 'rgb(0, 0, 0)'
    default:
      throw new Error('Unknown color')
  }
}

export function getUrlFromBackgroundImage(backgroundImage: string) {
  const matches = backgroundImage.match(/url\("[^)]+"\)/g)!.map((match) => {
    // Extract the URL part from each match. The match includes 'url("' and '"")', so we remove those.
    return match.slice(5, -2)
  })

  return matches
}

export const getTitle = (browser: Playwright) =>
  browser.elementByCss('title').text()

async function checkMeta(
  browser: Playwright,
  queryValue: string,
  expected: RegExp | string | string[] | undefined | null,
  queryKey: string = 'property',
  tag: string = 'meta',
  domAttributeField: string = 'content'
) {
  const values = await browser.eval<(string | null)[]>(
    `[...document.querySelectorAll('${tag}[${queryKey}="${queryValue}"]')].map((el) => el.getAttribute("${domAttributeField}"))`
  )
  if (expected instanceof RegExp) {
    expect(values[0]).toMatch(expected)
  } else {
    if (Array.isArray(expected)) {
      expect(values).toEqual(expected)
    } else {
      // If expected is undefined, then it should not exist.
      // Otherwise, it should exist in the matched values.
      if (expected === undefined) {
        expect(values).not.toContain(undefined)
      } else {
        expect(values).toContain(expected)
      }
    }
  }
}

export function createDomMatcher(browser: Playwright) {
  /**
   * @param tag - tag name, e.g. 'meta'
   * @param query - query string, e.g. 'name="description"'
   * @param expectedObject - expected object, e.g. { content: 'my description' }
   * @returns {Promise<void>} - promise that resolves when the check is done
   *
   * @example
   * const matchDom = createDomMatcher(browser)
   * await matchDom('meta', 'name="description"', { content: 'description' })
   */
  return async (
    tag: string,
    query: string,
    expectedObject: Record<string, string | null | undefined>
  ) => {
    const props = await browser.eval(`
      const el = document.querySelector('${tag}[${query}]');
      const res = {}
      const keys = ${JSON.stringify(Object.keys(expectedObject))}
      for (const k of keys) {
        res[k] = el?.getAttribute(k)
      }
      res
    `)
    expect(props).toEqual(expectedObject)
  }
}

export function createMultiHtmlMatcher($: ReturnType<typeof cheerio.load>) {
  /**
   * @param tag - tag name, e.g. 'meta'
   * @param queryKey - query key, e.g. 'property'
   * @param domAttributeField - dom attribute field, e.g. 'content'
   * @param expected - expected object, e.g. { description: 'my description' }
   * @returns {void} - void when the check is done
   *
   * @example
   *
   * const $ = await next.render$('html')
   * const matchHtml = createMultiHtmlMatcher($)
   * matchHtml('meta', 'name', 'property', {
   *   description: 'description',
   *   og: 'og:description'
   * })
   *
   */
  return (
    tag: string,
    queryKey: string,
    domAttributeField: string,
    expected: Record<string, string | string[] | undefined>
  ) => {
    const res = {}
    for (const key of Object.keys(expected)) {
      const el = $(`${tag}[${queryKey}="${key}"]`)
      if (el.length > 1) {
        res[key] = el.toArray().map((el) => el.attribs[domAttributeField])
      } else {
        res[key] = el.attr(domAttributeField)
      }
    }
    expect(res).toEqual(expected)
  }
}

export function createMultiDomMatcher(browser: Playwright) {
  /**
   * @param tag - tag name, e.g. 'meta'
   * @param queryKey - query key, e.g. 'property'
   * @param domAttributeField - dom attribute field, e.g. 'content'
   * @param expected - expected object, e.g. { description: 'my description' }
   * @returns {Promise<void>} - promise that resolves when the check is done
   *
   * @example
   * const matchMultiDom = createMultiDomMatcher(browser)
   * await matchMultiDom('meta', 'property', 'content', {
   *   description: 'description',
   *   'og:title': 'title',
   *   'twitter:title': 'title'
   * })
   *
   */
  return async (
    tag: string,
    queryKey: string,
    domAttributeField: string,
    expected: Record<string, string | string[] | undefined | null>
  ) => {
    await Promise.all(
      Object.keys(expected).map(async (key) => {
        return checkMeta(
          browser,
          key,
          expected[key],
          queryKey,
          tag,
          domAttributeField
        )
      })
    )
  }
}

export const checkMetaNameContentPair = (
  browser: Playwright,
  name: string,
  content: string | string[]
) => checkMeta(browser, name, content, 'name')

export const checkLink = (
  browser: Playwright,
  rel: string,
  content: string | string[]
) => checkMeta(browser, rel, content, 'rel', 'link', 'href')

export async function getStackFramesContent(browser) {
  const stackFrameElements = await browser.elementsByCss(
    '[data-nextjs-call-stack-frame]'
  )
  const stackFramesContent = (
    await Promise.all(
      stackFrameElements.map(async (frame) => {
        const functionNameEl = await frame.$('.call-stack-frame-method-name')
        const sourceEl = await frame.$('[data-has-source="true"]')
        const functionName = functionNameEl
          ? await functionNameEl.innerText()
          : ''
        const source = sourceEl ? await sourceEl.innerText() : ''

        if (!functionName) {
          return ''
        }
        return `at ${functionName} (${source})`
      })
    )
  )
    .filter(Boolean)
    .join('\n')

  return stackFramesContent
}

export async function toggleCollapseCallStackFrames(browser: Playwright) {
  const button = await browser.elementByCss(
    '[data-nextjs-call-stack-ignored-list-toggle-button]'
  )
  const lastExpanded = await button.getAttribute(
    'data-nextjs-call-stack-ignored-list-toggle-button'
  )
  await button.click()

  await retry(async () => {
    const currExpanded = await button.getAttribute(
      'data-nextjs-call-stack-ignored-list-toggle-button'
    )
    expect(currExpanded).not.toBe(lastExpanded)
  })
}

/**
 * Encodes the params into a URLSearchParams object using the format that the
 * now builder uses for route matches (adding the `nxtP` prefix to the keys).
 *
 * @param params - The params to encode.
 * @param extraQueryParams - The extra query params to encode (without the `nxtP` prefix).
 * @returns The encoded URLSearchParams object.
 */
export function createNowRouteMatches(
  params: Record<string, string>,
  extraQueryParams: Record<string, string> = {}
): URLSearchParams {
  const urlSearchParams = new URLSearchParams()
  for (const [key, value] of Object.entries(params)) {
    urlSearchParams.append(`nxtP${key}`, value)
  }
  for (const [key, value] of Object.entries(extraQueryParams)) {
    urlSearchParams.append(key, value)
  }

  return urlSearchParams
}

export async function assertNoConsoleErrors(browser: Playwright) {
  const logs = await browser.log()
  const warningsAndErrors = logs.filter((log) => {
    return (
      log.source === 'warning' ||
      (log.source === 'error' &&
        // These are expected when we visit 404 pages.
        !log.message.startsWith(
          'Failed to load resource: the server responded with a status of 404'
        ))
    )
  })

  expect(warningsAndErrors).toEqual([])
}

export async function getHighlightedDiffLines(
  browser: Playwright
): Promise<[string, string][]> {
  const lines = await browser.elementsByCss(
    '[data-nextjs-container-errors-pseudo-html--diff]'
  )
  return Promise.all(
    lines.map(async (line) => [
      (await line.getAttribute(
        'data-nextjs-container-errors-pseudo-html--diff'
      ))!,
      (await line.innerText())[0],
    ])
  )
}

export function trimEndMultiline(str: string) {
  return str
    .split('\n')
    .map((line) => line.trimEnd())
    .join('\n')
}