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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
import type { NextConfigComplete } from '../config-shared'
import type { CustomRoutes } from '../../lib/load-custom-routes'
import type { Duplex } from 'stream'
import type { Telemetry } from '../../telemetry/storage'
import type { IncomingMessage, ServerResponse } from 'http'
import type { UrlObject } from 'url'
import type { RouteDefinition } from '../route-definitions/route-definition'

import { type webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import {
  getOverlayMiddleware,
  getSourceMapMiddleware,
} from './middleware-webpack'
import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute, posix, dirname } from 'path'
import {
  createEntrypoints,
  createPagesMapping,
  finalizeEntrypoint,
  getClientEntry,
  getEdgeServerEntry,
  getAppEntry,
  runDependingOnPageType,
  getStaticInfoIncludingLayouts,
  getInstrumentationEntry,
} from '../../build/entries'
import { watchCompilers } from '../../build/output'
import * as Log from '../../build/output/log'
import getBaseWebpackConfig, {
  getCacheDirectories,
  loadProjectInfo,
} from '../../build/webpack-config'
import { APP_DIR_ALIAS, WEBPACK_LAYERS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete'
import {
  BLOCKED_PAGES,
  CLIENT_STATIC_FILES_RUNTIME_AMP,
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
  CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
  CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
  COMPILER_NAMES,
  RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
import type { __ApiPreviewProps } from '../api-utils'
import { getPathMatch } from '../../shared/lib/router/utils/path-match'
import { findPageFile } from '../lib/find-page-file'
import {
  BUILDING,
  getEntries,
  EntryTypes,
  getInvalidator,
  onDemandEntryHandler,
} from './on-demand-entry-handler'
import { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path'
import { normalizePathSep } from '../../shared/lib/page-path/normalize-path-sep'
import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import {
  difference,
  isInstrumentationHookFile,
  isMiddlewareFile,
  isMiddlewareFilename,
} from '../../build/utils'
import { DecodeError } from '../../shared/lib/utils'
import { type Span, trace } from '../../trace'
import { getProperError } from '../../lib/is-error'
import ws from 'next/dist/compiled/ws'
import { existsSync, promises as fs } from 'fs'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import { parseVersionInfo } from './parse-version-info'
import type { VersionInfo } from './parse-version-info'
import { isAPIRoute } from '../../lib/is-api-route'
import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader'
import {
  isInternalComponent,
  isNonRoutePagesPage,
} from '../../lib/is-internal-component'
import { RouteKind } from '../route-kind'
import {
  HMR_ACTIONS_SENT_TO_BROWSER,
  type NextJsHotReloaderInterface,
} from './hot-reloader-types'
import type { HMR_ACTION_TYPES } from './hot-reloader-types'
import type { WebpackError } from 'webpack'
import { PAGE_TYPES } from '../../lib/page-types'
import { FAST_REFRESH_RUNTIME_RELOAD } from './messages'
import { getNodeDebugType } from '../lib/utils'
import { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'
import { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'
import { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'
import getWebpackBundler from '../../shared/lib/get-webpack-bundler'
import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'
import { checkPersistentCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation'
import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs'
import {
  devToolsConfigMiddleware,
  getDevToolsConfig,
} from '../../next-devtools/server/devtools-config-middleware'

const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)

function diff(a: Set<any>, b: Set<any>) {
  return new Set([...a].filter((v) => !b.has(v)))
}

const wsServer = new ws.Server({ noServer: true })

export async function renderScriptError(
  res: ServerResponse,
  error: Error,
  { verbose = true } = {}
): Promise<{ finished: true | undefined }> {
  // Asks CDNs and others to not to cache the errored page
  res.setHeader(
    'Cache-Control',
    'no-cache, no-store, max-age=0, must-revalidate'
  )

  if ((error as any).code === 'ENOENT') {
    return { finished: undefined }
  }

  if (verbose) {
    console.error(error.stack)
  }
  res.statusCode = 500
  res.end('500 - Internal Error')
  return { finished: true }
}

function addCorsSupport(req: IncomingMessage, res: ServerResponse) {
  // Only rewrite CORS handling when URL matches a hot-reloader middleware
  if (!req.url!.startsWith('/__next')) {
    return { preflight: false }
  }

  if (!req.headers.origin) {
    return { preflight: false }
  }

  res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
  res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET')
  // Based on https://github.com/primus/access-control/blob/4cf1bc0e54b086c91e6aa44fb14966fa5ef7549c/index.js#L158
  if (req.headers['access-control-request-headers']) {
    res.setHeader(
      'Access-Control-Allow-Headers',
      req.headers['access-control-request-headers'] as string
    )
  }

  if (req.method === 'OPTIONS') {
    res.writeHead(200)
    res.end()
    return { preflight: true }
  }

  return { preflight: false }
}

export const matchNextPageBundleRequest = getPathMatch(
  '/_next/static/chunks/pages/:path*.js(\\.map|)'
)

// Iteratively look up the issuer till it ends up at the root
function findEntryModule(
  module: webpack.Module,
  compilation: webpack.Compilation
): any {
  for (;;) {
    const issuer = compilation.moduleGraph.getIssuer(module)
    if (!issuer) return module
    module = issuer
  }
}

function erroredPages(compilation: webpack.Compilation) {
  const failedPages: { [page: string]: WebpackError[] } = {}
  for (const error of compilation.errors) {
    if (!error.module) {
      continue
    }

    const entryModule = findEntryModule(error.module, compilation)
    const { name } = entryModule
    if (!name) {
      continue
    }

    // Only pages have to be reloaded
    const enhancedName = getRouteFromEntrypoint(name)

    if (!enhancedName) {
      continue
    }

    if (!failedPages[enhancedName]) {
      failedPages[enhancedName] = []
    }

    failedPages[enhancedName].push(error)
  }

  return failedPages
}

export async function getVersionInfo(): Promise<VersionInfo> {
  let installed = '0.0.0'

  try {
    installed = require('next/package.json').version

    let res

    try {
      // use NPM registry regardless user using Yarn
      res = await fetch('https://registry.npmjs.org/-/package/next/dist-tags')
    } catch {
      // ignore fetch errors
    }

    if (!res || !res.ok) return { installed, staleness: 'unknown' }

    const { latest, canary } = await res.json()

    return parseVersionInfo({ installed, latest, canary })
  } catch (e: any) {
    console.error(e)
    return { installed, staleness: 'unknown' }
  }
}

export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
  private hasAmpEntrypoints: boolean
  private hasAppRouterEntrypoints: boolean
  private hasPagesRouterEntrypoints: boolean
  private dir: string
  private buildId: string
  private encryptionKey: string
  private middlewares: ((
    req: IncomingMessage,
    res: ServerResponse,
    next: () => void
  ) => Promise<void>)[]
  private pagesDir?: string
  private distDir: string
  private webpackHotMiddleware?: WebpackHotMiddleware
  private config: NextConfigComplete
  private clientStats: webpack.Stats | null
  private clientError: Error | null = null
  private serverError: Error | null = null
  private hmrServerError: Error | null = null
  private serverPrevDocumentHash: string | null
  private serverChunkNames?: Set<string>
  private prevChunkNames?: Set<any>
  private onDemandEntries?: ReturnType<typeof onDemandEntryHandler>
  private previewProps: __ApiPreviewProps
  private watcher: any
  private rewrites: CustomRoutes['rewrites']
  private fallbackWatcher: any
  private hotReloaderSpan: Span
  private pagesMapping: { [key: string]: string } = {}
  private appDir?: string
  private telemetry: Telemetry
  private resetFetch: () => void
  private versionInfo: VersionInfo = {
    staleness: 'unknown',
    installed: '0.0.0',
  }
  private devtoolsFrontendUrl: string | undefined
  private reloadAfterInvalidation: boolean = false
  private isSrcDir: boolean

  public serverStats: webpack.Stats | null
  public edgeServerStats: webpack.Stats | null
  public multiCompiler?: webpack.MultiCompiler
  public activeWebpackConfigs?: Array<
    UnwrapPromise<ReturnType<typeof getBaseWebpackConfig>>
  >

  constructor(
    dir: string,
    {
      config,
      isSrcDir,
      pagesDir,
      distDir,
      buildId,
      encryptionKey,
      previewProps,
      rewrites,
      appDir,
      telemetry,
      resetFetch,
    }: {
      config: NextConfigComplete
      isSrcDir: boolean
      pagesDir?: string
      distDir: string
      buildId: string
      encryptionKey: string
      previewProps: __ApiPreviewProps
      rewrites: CustomRoutes['rewrites']
      appDir?: string
      telemetry: Telemetry
      resetFetch: () => void
    }
  ) {
    this.hasAmpEntrypoints = false
    this.hasAppRouterEntrypoints = false
    this.hasPagesRouterEntrypoints = false
    this.buildId = buildId
    this.encryptionKey = encryptionKey
    this.dir = dir
    this.isSrcDir = isSrcDir
    this.middlewares = []
    this.pagesDir = pagesDir
    this.appDir = appDir
    this.distDir = distDir
    this.clientStats = null
    this.serverStats = null
    this.edgeServerStats = null
    this.serverPrevDocumentHash = null
    this.telemetry = telemetry
    this.resetFetch = resetFetch

    this.config = config
    this.previewProps = previewProps
    this.rewrites = rewrites
    this.hotReloaderSpan = trace('hot-reloader', undefined, {
      version: process.env.__NEXT_VERSION as string,
    })
    // Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing
    // of the current `next dev` invocation.
    this.hotReloaderSpan.stop()
  }

  public async run(
    req: IncomingMessage,
    res: ServerResponse,
    parsedUrl: UrlObject
  ): Promise<{ finished?: true }> {
    // Usually CORS support is not needed for the hot-reloader (this is dev only feature)
    // With when the app runs for multi-zones support behind a proxy,
    // the current page is trying to access this URL via assetPrefix.
    // That's when the CORS support is needed.
    const { preflight } = addCorsSupport(req, res)
    if (preflight) {
      return {}
    }

    // When a request comes in that is a page bundle, e.g. /_next/static/<buildid>/pages/index.js
    // we have to compile the page using on-demand-entries, this middleware will handle doing that
    // by adding the page to on-demand-entries, waiting till it's done
    // and then the bundle will be served like usual by the actual route in server/index.js
    const handlePageBundleRequest = async (
      pageBundleRes: ServerResponse,
      parsedPageBundleUrl: UrlObject
    ): Promise<{ finished?: true }> => {
      const { pathname } = parsedPageBundleUrl
      if (!pathname) return {}

      const params = matchNextPageBundleRequest(pathname)
      if (!params) return {}

      let decodedPagePath: string

      try {
        decodedPagePath = `/${params.path
          .map((param: string) => decodeURIComponent(param))
          .join('/')}`
      } catch (_) {
        throw new DecodeError('failed to decode param')
      }

      const page = denormalizePagePath(decodedPagePath)

      if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) {
        try {
          await this.ensurePage({ page, clientOnly: true, url: req.url })
        } catch (error) {
          return await renderScriptError(pageBundleRes, getProperError(error))
        }

        const errors = await this.getCompilationErrors(page)
        if (errors.length > 0) {
          return await renderScriptError(pageBundleRes, errors[0], {
            verbose: false,
          })
        }
      }

      return {}
    }

    const { finished } = await handlePageBundleRequest(res, parsedUrl)

    for (const middleware of this.middlewares) {
      let calledNext = false

      await middleware(req, res, () => {
        calledNext = true
      })

      if (!calledNext) {
        return { finished: true }
      }
    }

    return { finished }
  }

  public setHmrServerError(error: Error | null): void {
    this.hmrServerError = error
  }

  public clearHmrServerError(): void {
    if (this.hmrServerError) {
      this.setHmrServerError(null)
      this.send({
        action: HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE,
        data: 'clear hmr server error',
      })
    }
  }

  protected async refreshServerComponents(hash: string): Promise<void> {
    this.send({
      action: HMR_ACTIONS_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
      hash,
      // TODO: granular reloading of changes
      // entrypoints: serverComponentChanges,
    })
  }

  public onHMR(
    req: IncomingMessage,
    _socket: Duplex,
    head: Buffer,
    callback: (client: ws.WebSocket) => void
  ) {
    wsServer.handleUpgrade(req, req.socket, head, (client) => {
      this.webpackHotMiddleware?.onHMR(client)
      this.onDemandEntries?.onHMR(client, () => this.hmrServerError)
      callback(client)

      client.addEventListener('message', async ({ data }) => {
        data = typeof data !== 'string' ? data.toString() : data

        try {
          const payload = JSON.parse(data)

          let traceChild:
            | {
                name: string
                startTime?: bigint
                endTime?: bigint
                attrs?: Record<string, number | string | undefined | string[]>
              }
            | undefined

          switch (payload.event) {
            case 'span-end': {
              traceChild = {
                name: payload.spanName,
                startTime:
                  BigInt(Math.floor(payload.startTime)) *
                  MILLISECONDS_IN_NANOSECOND,
                attrs: payload.attributes,
                endTime:
                  BigInt(Math.floor(payload.endTime)) *
                  MILLISECONDS_IN_NANOSECOND,
              }
              break
            }
            case 'client-hmr-latency': {
              traceChild = {
                name: payload.event,
                startTime:
                  BigInt(payload.startTime) * MILLISECONDS_IN_NANOSECOND,
                endTime: BigInt(payload.endTime) * MILLISECONDS_IN_NANOSECOND,
                attrs: {
                  updatedModules: payload.updatedModules.map((m: string) =>
                    m
                      .replace(`(${WEBPACK_LAYERS.appPagesBrowser})/`, '')
                      .replace(/^\.\//, '[project]/')
                  ),
                  page: payload.page,
                  isPageHidden: payload.isPageHidden,
                },
              }
              break
            }
            case 'client-reload-page':
            case 'client-success': {
              traceChild = {
                name: payload.event,
              }
              break
            }
            case 'client-error': {
              traceChild = {
                name: payload.event,
                attrs: { errorCount: payload.errorCount },
              }
              break
            }
            case 'client-warning': {
              traceChild = {
                name: payload.event,
                attrs: { warningCount: payload.warningCount },
              }
              break
            }
            case 'client-removed-page':
            case 'client-added-page': {
              traceChild = {
                name: payload.event,
                attrs: { page: payload.page || '' },
              }
              break
            }
            case 'client-full-reload': {
              const { event, stackTrace, hadRuntimeError } = payload

              traceChild = {
                name: event,
                attrs: { stackTrace: stackTrace ?? '' },
              }

              if (hadRuntimeError) {
                Log.warn(FAST_REFRESH_RUNTIME_RELOAD)
                break
              }

              let fileMessage = ''
              if (stackTrace) {
                const file = /Aborted because (.+) is not accepted/.exec(
                  stackTrace
                )?.[1]
                if (file) {
                  // `file` is filepath in `pages/` but it can be a webpack url.
                  // If it's a webpack loader URL, it will include the app-pages layer
                  if (file.startsWith(`(${WEBPACK_LAYERS.appPagesBrowser})/`)) {
                    const fileUrl = new URL(file, 'file://')
                    const cwd = process.cwd()
                    const modules = fileUrl.searchParams
                      .getAll('modules')
                      .map((filepath) => filepath.slice(cwd.length + 1))
                      .filter(
                        (filepath) => !filepath.startsWith('node_modules')
                      )

                    if (modules.length > 0) {
                      fileMessage = ` when ${modules.join(', ')} changed`
                    }
                  } else if (
                    // Handle known webpack layers
                    file.startsWith(`(${WEBPACK_LAYERS.pagesDirBrowser})/`)
                  ) {
                    const cleanedFilePath = file.slice(
                      `(${WEBPACK_LAYERS.pagesDirBrowser})/`.length
                    )

                    fileMessage = ` when ${cleanedFilePath} changed`
                  } else {
                    fileMessage = ` when ${file} changed`
                  }
                }
              }

              Log.warn(
                `Fast Refresh had to perform a full reload${fileMessage}. Read more: https://nextjs.org/docs/messages/fast-refresh-reload`
              )
              break
            }
            case 'browser-logs': {
              if (this.config.experimental.browserDebugInfoInTerminal) {
                await receiveBrowserLogsWebpack({
                  entries: payload.entries,
                  router: payload.router,
                  sourceType: payload.sourceType,
                  clientStats: () => this.clientStats,
                  serverStats: () => this.serverStats,
                  edgeServerStats: () => this.edgeServerStats,
                  rootDirectory: this.dir,
                  distDir: this.distDir,
                  config: this.config.experimental.browserDebugInfoInTerminal,
                })
              }
              break
            }
            default: {
              break
            }
          }

          if (traceChild) {
            this.hotReloaderSpan.manualTraceChild(
              traceChild.name,
              traceChild.startTime,
              traceChild.endTime,
              { ...traceChild.attrs, clientId: payload.id }
            )
          }
        } catch (_) {
          // invalid WebSocket message
        }
      })
    })
  }

  private async clean(span: Span): Promise<void> {
    return span
      .traceChild('clean')
      .traceAsyncFn(() =>
        recursiveDelete(join(this.dir, this.config.distDir), /^cache/)
      )
  }

  private async getWebpackConfig(span: Span) {
    const webpackConfigSpan = span.traceChild('get-webpack-config')

    const pageExtensions = this.config.pageExtensions

    return webpackConfigSpan.traceAsyncFn(async () => {
      const pagePaths = !this.pagesDir
        ? ([] as (string | null)[])
        : await webpackConfigSpan
            .traceChild('get-page-paths')
            .traceAsyncFn(() =>
              Promise.all([
                findPageFile(this.pagesDir!, '/_app', pageExtensions, false),
                findPageFile(
                  this.pagesDir!,
                  '/_document',
                  pageExtensions,
                  false
                ),
              ])
            )

      this.pagesMapping = await webpackConfigSpan
        .traceChild('create-pages-mapping')
        .traceAsyncFn(() =>
          createPagesMapping({
            isDev: true,
            pageExtensions: this.config.pageExtensions,
            pagesType: PAGE_TYPES.PAGES,
            pagePaths: pagePaths.filter(
              (i: string | null): i is string => typeof i === 'string'
            ),
            pagesDir: this.pagesDir,
            appDir: this.appDir,
          })
        )

      const entrypoints = await webpackConfigSpan
        .traceChild('create-entrypoints')
        .traceAsyncFn(() =>
          createEntrypoints({
            appDir: this.appDir,
            buildId: this.buildId,
            config: this.config,
            envFiles: [],
            isDev: true,
            pages: this.pagesMapping,
            pagesDir: this.pagesDir,
            previewMode: this.previewProps,
            rootDir: this.dir,
            pageExtensions: this.config.pageExtensions,
          })
        )

      const commonWebpackOptions = {
        dev: true,
        buildId: this.buildId,
        encryptionKey: this.encryptionKey,
        config: this.config,
        pagesDir: this.pagesDir,
        rewrites: this.rewrites,
        originalRewrites: this.config._originalRewrites,
        originalRedirects: this.config._originalRedirects,
        runWebpackSpan: this.hotReloaderSpan,
        appDir: this.appDir,
        previewProps: this.previewProps,
      }

      return webpackConfigSpan
        .traceChild('generate-webpack-config')
        .traceAsyncFn(async () => {
          const info = await loadProjectInfo({
            dir: this.dir,
            config: commonWebpackOptions.config,
            dev: true,
          })
          return Promise.all([
            // order is important here
            getBaseWebpackConfig(this.dir, {
              ...commonWebpackOptions,
              compilerType: COMPILER_NAMES.client,
              entrypoints: entrypoints.client,
              ...info,
            }),
            getBaseWebpackConfig(this.dir, {
              ...commonWebpackOptions,
              compilerType: COMPILER_NAMES.server,
              entrypoints: entrypoints.server,
              ...info,
            }),
            getBaseWebpackConfig(this.dir, {
              ...commonWebpackOptions,
              compilerType: COMPILER_NAMES.edgeServer,
              entrypoints: entrypoints.edgeServer,
              ...info,
            }),
          ])
        })
    })
  }

  public async buildFallbackError(): Promise<void> {
    if (this.fallbackWatcher) return

    const info = await loadProjectInfo({
      dir: this.dir,
      config: this.config,
      dev: true,
    })
    const fallbackConfig = await getBaseWebpackConfig(this.dir, {
      previewProps: this.previewProps,
      runWebpackSpan: this.hotReloaderSpan,
      dev: true,
      compilerType: COMPILER_NAMES.client,
      config: this.config,
      buildId: this.buildId,
      encryptionKey: this.encryptionKey,
      appDir: this.appDir,
      pagesDir: this.pagesDir,
      rewrites: {
        beforeFiles: [],
        afterFiles: [],
        fallback: [],
      },
      originalRewrites: {
        beforeFiles: [],
        afterFiles: [],
        fallback: [],
      },
      originalRedirects: [],
      isDevFallback: true,
      entrypoints: (
        await createEntrypoints({
          appDir: this.appDir,
          buildId: this.buildId,
          config: this.config,
          envFiles: [],
          isDev: true,
          pages: {
            '/_app': 'next/dist/pages/_app',
            '/_error': 'next/dist/pages/_error',
          },
          pagesDir: this.pagesDir,
          previewMode: this.previewProps,
          rootDir: this.dir,
          pageExtensions: this.config.pageExtensions,
        })
      ).client,
      ...info,
    })

    const fallbackCompiler = getWebpackBundler()(fallbackConfig)

    this.fallbackWatcher = await new Promise((resolve) => {
      let bootedFallbackCompiler = false
      fallbackCompiler.watch(
        // @ts-ignore webpack supports an array of watchOptions when using a multiCompiler
        fallbackConfig.watchOptions,
        // Errors are handled separately
        (_err: any) => {
          if (!bootedFallbackCompiler) {
            bootedFallbackCompiler = true
            resolve(true)
          }
        }
      )
    })
  }

  private async tracedGetVersionInfo(span: Span) {
    const versionInfoSpan = span.traceChild('get-version-info')
    return versionInfoSpan.traceAsyncFn<VersionInfo>(async () =>
      getVersionInfo()
    )
  }

  public async start(): Promise<void> {
    const startSpan = this.hotReloaderSpan.traceChild('start')
    startSpan.stop() // Stop immediately to create an artificial parent span

    this.versionInfo = await this.tracedGetVersionInfo(startSpan)

    const nodeDebugType = getNodeDebugType()
    if (nodeDebugType && !this.devtoolsFrontendUrl) {
      const debugPort = process.debugPort
      let debugInfo
      try {
        // It requires to use 127.0.0.1 instead of localhost for server-side fetching.
        const debugInfoList = await fetch(
          `http://127.0.0.1:${debugPort}/json/list`
        ).then((res) => res.json())
        // There will be only one item for current process, so always get the first item.
        debugInfo = debugInfoList[0]
      } catch {}
      if (debugInfo) {
        this.devtoolsFrontendUrl = debugInfo.devtoolsFrontendUrl
      }
    }

    await this.clean(startSpan)
    // Ensure distDir exists before writing package.json
    await fs.mkdir(this.distDir, { recursive: true })

    const initialDevToolsConfig = await getDevToolsConfig(this.distDir)

    const distPackageJsonPath = join(this.distDir, 'package.json')
    // Ensure commonjs handling is used for files in the distDir (generally .next)
    // Files outside of the distDir can be "type": "module"
    await fs.writeFile(distPackageJsonPath, '{"type": "commonjs"}')

    this.activeWebpackConfigs = await this.getWebpackConfig(startSpan)

    for (const config of this.activeWebpackConfigs) {
      const defaultEntry = config.entry
      config.entry = async (...args) => {
        const outputPath = this.multiCompiler?.outputPath || ''
        const entries = getEntries(outputPath)
        // @ts-ignore entry is always a function
        const entrypoints = await defaultEntry(...args)
        const isClientCompilation = config.name === COMPILER_NAMES.client
        const isNodeServerCompilation = config.name === COMPILER_NAMES.server
        const isEdgeServerCompilation =
          config.name === COMPILER_NAMES.edgeServer

        await Promise.all(
          Object.keys(entries).map(async (entryKey) => {
            const entryData = entries[entryKey]
            const { bundlePath, dispose } = entryData

            const result =
              /^(client|server|edge-server)@(app|pages|root)@(.*)/g.exec(
                entryKey
              )
            const [, key /* pageType */, , page] = result! // this match should always happen

            if (key === COMPILER_NAMES.client && !isClientCompilation) return
            if (key === COMPILER_NAMES.server && !isNodeServerCompilation)
              return
            if (key === COMPILER_NAMES.edgeServer && !isEdgeServerCompilation)
              return

            const isEntry = entryData.type === EntryTypes.ENTRY
            const isChildEntry = entryData.type === EntryTypes.CHILD_ENTRY

            // Check if the page was removed or disposed and remove it
            if (isEntry) {
              const pageExists =
                !dispose && existsSync(entryData.absolutePagePath)
              if (!pageExists) {
                delete entries[entryKey]
                return
              }
            }

            // For child entries, if it has an entry file and it's gone, remove it
            if (isChildEntry) {
              if (entryData.absoluteEntryFilePath) {
                const pageExists =
                  !dispose && existsSync(entryData.absoluteEntryFilePath)
                if (!pageExists) {
                  delete entries[entryKey]
                  return
                }
              }
            }

            // Ensure _error is considered a `pages` page.
            if (page === '/_error') {
              this.hasPagesRouterEntrypoints = true
            }

            const hasAppDir = !!this.appDir
            const isAppPath = hasAppDir && bundlePath.startsWith('app/')
            const staticInfo = isEntry
              ? await getStaticInfoIncludingLayouts({
                  isInsideAppDir: isAppPath,
                  pageExtensions: this.config.pageExtensions,
                  pageFilePath: entryData.absolutePagePath,
                  appDir: this.appDir,
                  config: this.config,
                  isDev: true,
                  page,
                })
              : undefined

            if (staticInfo?.type === PAGE_TYPES.PAGES) {
              if (
                staticInfo.config?.config?.amp === true ||
                staticInfo.config?.config?.amp === 'hybrid'
              ) {
                this.hasAmpEntrypoints = true
              }
            }

            const isServerComponent =
              isAppPath && staticInfo?.rsc !== RSC_MODULE_TYPES.client

            const pageType: PAGE_TYPES = entryData.bundlePath.startsWith(
              'pages/'
            )
              ? PAGE_TYPES.PAGES
              : entryData.bundlePath.startsWith('app/')
                ? PAGE_TYPES.APP
                : PAGE_TYPES.ROOT

            if (pageType === 'pages') {
              this.hasPagesRouterEntrypoints = true
            }
            if (pageType === 'app') {
              this.hasAppRouterEntrypoints = true
            }

            const isInstrumentation =
              isInstrumentationHookFile(page) && pageType === PAGE_TYPES.ROOT

            let pageRuntime = staticInfo?.runtime

            runDependingOnPageType({
              page,
              pageRuntime,
              pageType,
              onEdgeServer: () => {
                // TODO-APP: verify if child entry should support.
                if (!isEdgeServerCompilation || !isEntry) return
                entries[entryKey].status = BUILDING

                if (isInstrumentation) {
                  const normalizedBundlePath = bundlePath.replace('src/', '')
                  entrypoints[normalizedBundlePath] = finalizeEntrypoint({
                    compilerType: COMPILER_NAMES.edgeServer,
                    name: normalizedBundlePath,
                    value: getInstrumentationEntry({
                      absolutePagePath: entryData.absolutePagePath,
                      isEdgeServer: true,
                      isDev: true,
                    }),
                    isServerComponent: true,
                    hasAppDir,
                  })
                  return
                }
                const appDirLoader = isAppPath
                  ? getAppEntry({
                      name: bundlePath,
                      page,
                      appPaths: entryData.appPaths,
                      pagePath: posix.join(
                        APP_DIR_ALIAS,
                        relative(
                          this.appDir!,
                          entryData.absolutePagePath
                        ).replace(/\\/g, '/')
                      ),
                      appDir: this.appDir!,
                      pageExtensions: this.config.pageExtensions,
                      rootDir: this.dir,
                      isDev: true,
                      tsconfigPath: this.config.typescript.tsconfigPath,
                      basePath: this.config.basePath,
                      assetPrefix: this.config.assetPrefix,
                      nextConfigOutput: this.config.output,
                      preferredRegion: staticInfo?.preferredRegion,
                      middlewareConfig: Buffer.from(
                        JSON.stringify(staticInfo?.middleware || {})
                      ).toString('base64'),
                      isGlobalNotFoundEnabled: this.config.experimental
                        .globalNotFound
                        ? true
                        : undefined,
                    }).import
                  : undefined

                entrypoints[bundlePath] = finalizeEntrypoint({
                  compilerType: COMPILER_NAMES.edgeServer,
                  name: bundlePath,
                  value: getEdgeServerEntry({
                    absolutePagePath: entryData.absolutePagePath,
                    rootDir: this.dir,
                    buildId: this.buildId,
                    bundlePath,
                    config: this.config,
                    isDev: true,
                    page,
                    pages: this.pagesMapping,
                    isServerComponent,
                    appDirLoader,
                    pagesType: isAppPath ? PAGE_TYPES.APP : PAGE_TYPES.PAGES,
                    preferredRegion: staticInfo?.preferredRegion,
                  }),
                  hasAppDir,
                })
              },
              onClient: () => {
                if (!isClientCompilation) return
                if (isChildEntry) {
                  entries[entryKey].status = BUILDING
                  entrypoints[bundlePath] = finalizeEntrypoint({
                    name: bundlePath,
                    compilerType: COMPILER_NAMES.client,
                    value: entryData.request,
                    hasAppDir,
                  })
                } else {
                  entries[entryKey].status = BUILDING
                  entrypoints[bundlePath] = finalizeEntrypoint({
                    name: bundlePath,
                    compilerType: COMPILER_NAMES.client,
                    value: getClientEntry({
                      absolutePagePath: entryData.absolutePagePath,
                      page,
                    }),
                    hasAppDir,
                  })
                }
              },
              onServer: () => {
                // TODO-APP: verify if child entry should support.
                if (!isNodeServerCompilation || !isEntry) return
                entries[entryKey].status = BUILDING
                let relativeRequest = relative(
                  config.context!,
                  entryData.absolutePagePath
                )
                if (
                  !isAbsolute(relativeRequest) &&
                  !relativeRequest.startsWith('../')
                ) {
                  relativeRequest = `./${relativeRequest}`
                }

                let value: { import: string; layer?: string } | string
                if (isInstrumentation) {
                  value = getInstrumentationEntry({
                    absolutePagePath: entryData.absolutePagePath,
                    isEdgeServer: false,
                    isDev: true,
                  })
                  entrypoints[bundlePath] = finalizeEntrypoint({
                    compilerType: COMPILER_NAMES.server,
                    name: bundlePath,
                    isServerComponent: true,
                    value,
                    hasAppDir,
                  })
                } else if (isMiddlewareFile(page)) {
                  value = getEdgeServerEntry({
                    absolutePagePath: entryData.absolutePagePath,
                    rootDir: this.dir,
                    buildId: this.buildId,
                    bundlePath,
                    config: this.config,
                    isDev: true,
                    page,
                    pages: this.pagesMapping,
                    isServerComponent,
                    pagesType: PAGE_TYPES.PAGES,
                    preferredRegion: staticInfo?.preferredRegion,
                  })
                } else if (isAppPath) {
                  // This path normalization is critical for webpack to resolve the next internals as entry.
                  const pagePath = entryData.absolutePagePath.startsWith(
                    dirname(require.resolve('next/package.json'))
                  )
                    ? entryData.absolutePagePath
                    : posix.join(
                        APP_DIR_ALIAS,
                        relative(
                          this.appDir!,
                          entryData.absolutePagePath
                        ).replace(/\\/g, '/')
                      )
                  value = getAppEntry({
                    name: bundlePath,
                    page,
                    appPaths: entryData.appPaths,
                    pagePath,
                    appDir: this.appDir!,
                    pageExtensions: this.config.pageExtensions,
                    rootDir: this.dir,
                    isDev: true,
                    tsconfigPath: this.config.typescript.tsconfigPath,
                    basePath: this.config.basePath,
                    assetPrefix: this.config.assetPrefix,
                    nextConfigOutput: this.config.output,
                    preferredRegion: staticInfo?.preferredRegion,
                    middlewareConfig: Buffer.from(
                      JSON.stringify(staticInfo?.middleware || {})
                    ).toString('base64'),
                    isGlobalNotFoundEnabled: this.config.experimental
                      .globalNotFound
                      ? true
                      : undefined,
                  })
                } else if (isAPIRoute(page)) {
                  value = getRouteLoaderEntry({
                    kind: RouteKind.PAGES_API,
                    page,
                    absolutePagePath: relativeRequest,
                    preferredRegion: staticInfo?.preferredRegion,
                    middlewareConfig: staticInfo?.middleware || {},
                  })
                } else if (
                  !isMiddlewareFile(page) &&
                  !isInternalComponent(relativeRequest) &&
                  !isNonRoutePagesPage(page) &&
                  !isInstrumentation
                ) {
                  value = getRouteLoaderEntry({
                    kind: RouteKind.PAGES,
                    page,
                    pages: this.pagesMapping,
                    absolutePagePath: relativeRequest,
                    preferredRegion: staticInfo?.preferredRegion,
                    middlewareConfig: staticInfo?.middleware ?? {},
                  })
                } else {
                  value = relativeRequest
                }

                entrypoints[bundlePath] = finalizeEntrypoint({
                  compilerType: COMPILER_NAMES.server,
                  name: bundlePath,
                  isServerComponent,
                  value,
                  hasAppDir,
                })
              },
            })
          })
        )

        if (!this.hasAmpEntrypoints) {
          delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_AMP]
        }
        if (!this.hasPagesRouterEntrypoints) {
          delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_MAIN]
          delete entrypoints['pages/_app']
          delete entrypoints['pages/_error']
          delete entrypoints['/_error']
          delete entrypoints['pages/_document']
        }
        // Remove React Refresh entrypoint chunk as `app` doesn't require it.
        if (!this.hasAmpEntrypoints && !this.hasPagesRouterEntrypoints) {
          delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]
        }
        if (!this.hasAppRouterEntrypoints) {
          delete entrypoints[CLIENT_STATIC_FILES_RUNTIME_MAIN_APP]
        }

        return entrypoints
      }
    }

    // Enable building of client compilation before server compilation in development
    // @ts-ignore webpack 5
    this.activeWebpackConfigs.parallelism = 1

    await Promise.all(
      Array.from(getCacheDirectories(this.activeWebpackConfigs)).map(
        checkPersistentCacheInvalidationAndCleanup
      )
    )
    this.multiCompiler = getWebpackBundler()(
      this.activeWebpackConfigs
    ) as unknown as webpack.MultiCompiler

    // Copy over the filesystem so that it is shared between all compilers.
    const inputFileSystem = this.multiCompiler.compilers[0].inputFileSystem
    for (const compiler of this.multiCompiler.compilers) {
      compiler.inputFileSystem = inputFileSystem
      // This is set for the initial compile. After that Watching class in webpack adds it.
      compiler.fsStartTime = Date.now()
      // Ensure NodeEnvironmentPlugin doesn't purge the inputFileSystem. Purging is handled in `done` below.
      compiler.hooks.beforeRun.intercept({
        register(tapInfo: any) {
          if (tapInfo.name === 'NodeEnvironmentPlugin') {
            return null
          }
          return tapInfo
        },
      })
    }

    this.multiCompiler.hooks.done.tap('NextjsHotReloader', () => {
      inputFileSystem?.purge?.()
    })
    watchCompilers(
      this.multiCompiler.compilers[0],
      this.multiCompiler.compilers[1],
      this.multiCompiler.compilers[2]
    )

    // Watch for changes to client/server page files so we can tell when just
    // the server file changes and trigger a reload for GS(S)P pages
    const changedClientPages = new Set<string>()
    const changedServerPages = new Set<string>()
    const changedEdgeServerPages = new Set<string>()

    const changedServerComponentPages = new Set<string>()
    const changedCSSImportPages = new Set<string>()

    const prevClientPageHashes = new Map<string, string>()
    const prevServerPageHashes = new Map<string, string>()
    const prevEdgeServerPageHashes = new Map<string, string>()
    const prevCSSImportModuleHashes = new Map<string, string>()

    const pageExtensionRegex = new RegExp(
      `\\.(?:${this.config.pageExtensions.join('|')})$`
    )

    const trackPageChanges =
      (
        pageHashMap: Map<string, string>,
        changedItems: Set<string>,
        serverComponentChangedItems?: Set<string>
      ) =>
      (stats: webpack.Compilation) => {
        try {
          stats.entrypoints.forEach((entry, key) => {
            if (
              key.startsWith('pages/') ||
              key.startsWith('app/') ||
              isMiddlewareFilename(key)
            ) {
              // TODO this doesn't handle on demand loaded chunks
              entry.chunks.forEach((chunk) => {
                if (chunk.id === key) {
                  const modsIterable: any =
                    stats.chunkGraph.getChunkModulesIterable(chunk)

                  let hasCSSModuleChanges = false
                  let chunksHash = new StringXor()
                  let chunksHashServerLayer = new StringXor()

                  modsIterable.forEach((mod: any) => {
                    if (
                      mod.resource &&
                      mod.resource.replace(/\\/g, '/').includes(key) &&
                      // Shouldn't match CSS modules, etc.
                      pageExtensionRegex.test(mod.resource)
                    ) {
                      // use original source to calculate hash since mod.hash
                      // includes the source map in development which changes
                      // every time for both server and client so we calculate
                      // the hash without the source map for the page module
                      const hash = (
                        require('crypto') as typeof import('crypto')
                      )
                        .createHash('sha1')
                        .update(mod.originalSource().buffer())
                        .digest()
                        .toString('hex')

                      if (
                        mod.layer === WEBPACK_LAYERS.reactServerComponents &&
                        mod?.buildInfo?.rsc?.type !== 'client'
                      ) {
                        chunksHashServerLayer.add(hash)
                      }

                      chunksHash.add(hash)
                    } else {
                      // for non-pages we can use the module hash directly
                      const hash = stats.chunkGraph.getModuleHash(
                        mod,
                        chunk.runtime
                      )

                      if (
                        mod.layer === WEBPACK_LAYERS.reactServerComponents &&
                        mod?.buildInfo?.rsc?.type !== 'client'
                      ) {
                        chunksHashServerLayer.add(hash)
                      }

                      chunksHash.add(hash)

                      // Both CSS import changes from server and client
                      // components are tracked.
                      if (
                        key.startsWith('app/') &&
                        /\.(css|scss|sass)$/.test(mod.resource || '')
                      ) {
                        const resourceKey = mod.layer + ':' + mod.resource
                        const prevHash =
                          prevCSSImportModuleHashes.get(resourceKey)
                        if (prevHash && prevHash !== hash) {
                          hasCSSModuleChanges = true
                        }
                        prevCSSImportModuleHashes.set(resourceKey, hash)
                      }
                    }
                  })

                  const prevHash = pageHashMap.get(key)
                  const curHash = chunksHash.toString()
                  if (prevHash && prevHash !== curHash) {
                    changedItems.add(key)
                  }
                  pageHashMap.set(key, curHash)

                  if (serverComponentChangedItems) {
                    const serverKey =
                      WEBPACK_LAYERS.reactServerComponents + ':' + key
                    const prevServerHash = pageHashMap.get(serverKey)
                    const curServerHash = chunksHashServerLayer.toString()
                    if (prevServerHash && prevServerHash !== curServerHash) {
                      serverComponentChangedItems.add(key)
                    }
                    pageHashMap.set(serverKey, curServerHash)
                  }

                  if (hasCSSModuleChanges) {
                    changedCSSImportPages.add(key)
                  }
                }
              })
            }
          })
        } catch (err) {
          console.error(err)
        }
      }

    this.multiCompiler.compilers[0].hooks.emit.tap(
      'NextjsHotReloaderForClient',
      trackPageChanges(prevClientPageHashes, changedClientPages)
    )
    this.multiCompiler.compilers[1].hooks.emit.tap(
      'NextjsHotReloaderForServer',
      trackPageChanges(
        prevServerPageHashes,
        changedServerPages,
        changedServerComponentPages
      )
    )
    this.multiCompiler.compilers[2].hooks.emit.tap(
      'NextjsHotReloaderForServer',
      trackPageChanges(
        prevEdgeServerPageHashes,
        changedEdgeServerPages,
        changedServerComponentPages
      )
    )

    // This plugin watches for changes to _document.js and notifies the client side that it should reload the page
    this.multiCompiler.compilers[1].hooks.failed.tap(
      'NextjsHotReloaderForServer',
      (err: Error) => {
        this.serverError = err
        this.serverStats = null
        this.serverChunkNames = undefined
      }
    )

    this.multiCompiler.compilers[2].hooks.done.tap(
      'NextjsHotReloaderForServer',
      (stats) => {
        this.serverError = null
        this.edgeServerStats = stats
      }
    )

    this.multiCompiler.compilers[1].hooks.done.tap(
      'NextjsHotReloaderForServer',
      (stats) => {
        this.serverError = null
        this.serverStats = stats

        if (!this.pagesDir) {
          return
        }

        const { compilation } = stats

        // We only watch `_document` for changes on the server compilation
        // the rest of the files will be triggered by the client compilation
        const documentChunk = compilation.namedChunks.get('pages/_document')
        // If the document chunk can't be found we do nothing
        if (!documentChunk) {
          return
        }

        // Initial value
        if (this.serverPrevDocumentHash === null) {
          this.serverPrevDocumentHash = documentChunk.hash || null
          return
        }

        // If _document.js didn't change we don't trigger a reload.
        if (documentChunk.hash === this.serverPrevDocumentHash) {
          return
        }

        // As document chunk will change if new app pages are joined,
        // since react bundle is different it will effect the chunk hash.
        // So we diff the chunk changes, if there's only new app page chunk joins,
        // then we don't trigger a reload by checking pages/_document chunk change.
        if (this.appDir) {
          const chunkNames = new Set(compilation.namedChunks.keys())
          const diffChunkNames = difference<string>(
            this.serverChunkNames || new Set(),
            chunkNames
          )

          if (
            diffChunkNames.length === 0 ||
            diffChunkNames.every((chunkName) => chunkName.startsWith('app/'))
          ) {
            return
          }
          this.serverChunkNames = chunkNames
        }

        this.serverPrevDocumentHash = documentChunk.hash || null

        // Notify reload to reload the page, as _document.js was changed (different hash)
        this.send({
          action: HMR_ACTIONS_SENT_TO_BROWSER.RELOAD_PAGE,
          data: '_document has changed',
        })
      }
    )

    this.multiCompiler.hooks.done.tap('NextjsHotReloaderForServer', (stats) => {
      const reloadAfterInvalidation = this.reloadAfterInvalidation
      this.reloadAfterInvalidation = false

      const serverOnlyChanges = difference<string>(
        changedServerPages,
        changedClientPages
      )

      const edgeServerOnlyChanges = difference<string>(
        changedEdgeServerPages,
        changedClientPages
      )

      const pageChanges = serverOnlyChanges
        .concat(edgeServerOnlyChanges)
        .filter((key) => key.startsWith('pages/'))

      const middlewareChanges = [
        ...Array.from(changedEdgeServerPages),
        ...Array.from(changedServerPages),
      ].filter((name) => isMiddlewareFilename(name))

      if (middlewareChanges.length > 0) {
        this.send({
          event: HMR_ACTIONS_SENT_TO_BROWSER.MIDDLEWARE_CHANGES,
        })
      }

      if (pageChanges.length > 0) {
        this.send({
          event: HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ONLY_CHANGES,
          pages: serverOnlyChanges.map((pg) =>
            denormalizePagePath(pg.slice('pages'.length))
          ),
        })
      }

      if (
        changedServerComponentPages.size ||
        changedCSSImportPages.size ||
        reloadAfterInvalidation
      ) {
        this.resetFetch()
        this.refreshServerComponents(stats.hash)
      }

      changedClientPages.clear()
      changedServerPages.clear()
      changedEdgeServerPages.clear()
      changedServerComponentPages.clear()
      changedCSSImportPages.clear()
    })

    this.multiCompiler.compilers[0].hooks.failed.tap(
      'NextjsHotReloaderForClient',
      (err: Error) => {
        this.clientError = err
        this.clientStats = null
      }
    )
    this.multiCompiler.compilers[0].hooks.done.tap(
      'NextjsHotReloaderForClient',
      (stats) => {
        this.clientError = null
        this.clientStats = stats

        const { compilation } = stats
        const chunkNames = new Set(
          [...compilation.namedChunks.keys()].filter(
            (name) => !!getRouteFromEntrypoint(name)
          )
        )

        if (this.prevChunkNames) {
          // detect chunks which have to be replaced with a new template
          // e.g, pages/index.js <-> pages/_error.js
          const addedPages = diff(chunkNames, this.prevChunkNames!)
          const removedPages = diff(this.prevChunkNames!, chunkNames)

          if (addedPages.size > 0) {
            for (const addedPage of addedPages) {
              const page = getRouteFromEntrypoint(addedPage)
              this.send({
                action: HMR_ACTIONS_SENT_TO_BROWSER.ADDED_PAGE,
                data: [page],
              })
            }
          }

          if (removedPages.size > 0) {
            for (const removedPage of removedPages) {
              const page = getRouteFromEntrypoint(removedPage)
              this.send({
                action: HMR_ACTIONS_SENT_TO_BROWSER.REMOVED_PAGE,
                data: [page],
              })
            }
          }
        }

        this.prevChunkNames = chunkNames
      }
    )

    this.webpackHotMiddleware = new WebpackHotMiddleware(
      this.multiCompiler.compilers,
      this.versionInfo,
      this.devtoolsFrontendUrl,
      initialDevToolsConfig
    )

    let booted = false

    this.watcher = await new Promise((resolve) => {
      const watcher = this.multiCompiler?.watch(
        // @ts-ignore webpack supports an array of watchOptions when using a multiCompiler
        this.activeWebpackConfigs.map((config) => config.watchOptions!),
        // Errors are handled separately
        (_err: any) => {
          if (!booted) {
            booted = true
            resolve(watcher)
          }
        }
      )
    })

    this.onDemandEntries = onDemandEntryHandler({
      hotReloader: this,
      multiCompiler: this.multiCompiler,
      pagesDir: this.pagesDir,
      appDir: this.appDir,
      rootDir: this.dir,
      nextConfig: this.config,
      ...(this.config.onDemandEntries as {
        maxInactiveAge: number
        pagesBufferLength: number
      }),
    })

    this.middlewares = [
      getOverlayMiddleware({
        rootDirectory: this.dir,
        isSrcDir: this.isSrcDir,
        clientStats: () => this.clientStats,
        serverStats: () => this.serverStats,
        edgeServerStats: () => this.edgeServerStats,
      }),
      getSourceMapMiddleware({
        clientStats: () => this.clientStats,
        serverStats: () => this.serverStats,
        edgeServerStats: () => this.edgeServerStats,
      }),
      getNextErrorFeedbackMiddleware(this.telemetry),
      getDevOverlayFontMiddleware(),
      getDisableDevIndicatorMiddleware(),
      getRestartDevServerMiddleware({
        telemetry: this.telemetry,
        webpackCacheDirectories:
          this.activeWebpackConfigs != null
            ? getCacheDirectories(this.activeWebpackConfigs)
            : undefined,
      }),
      devToolsConfigMiddleware({
        distDir: this.distDir,
        sendUpdateSignal: (data) => {
          // Update the in-memory devToolsConfig value
          // which will be used for the next onHMR call.
          this.webpackHotMiddleware?.updateDevToolsConfig(data)

          this.send({
            action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG,
            data,
          })
        },
      }),
    ]
  }

  public invalidate(
    { reloadAfterInvalidation }: { reloadAfterInvalidation: boolean } = {
      reloadAfterInvalidation: false,
    }
  ) {
    // Cache the `reloadAfterInvalidation` flag, and use it to reload the page when compilation is done
    this.reloadAfterInvalidation = reloadAfterInvalidation
    const outputPath = this.multiCompiler?.outputPath
    if (outputPath) {
      getInvalidator(outputPath)?.invalidate()
    }
  }

  public async getCompilationErrors(page: string) {
    const getErrors = ({ compilation }: webpack.Stats) => {
      const failedPages = erroredPages(compilation)
      const normalizedPage = normalizePathSep(page)
      // If there is an error related to the requesting page we display it instead of the first error
      return failedPages[normalizedPage]?.length > 0
        ? failedPages[normalizedPage]
        : compilation.errors
    }

    if (this.clientError) {
      return [this.clientError]
    } else if (this.serverError) {
      return [this.serverError]
    } else if (this.clientStats?.hasErrors()) {
      return getErrors(this.clientStats)
    } else if (this.serverStats?.hasErrors()) {
      return getErrors(this.serverStats)
    } else if (this.edgeServerStats?.hasErrors()) {
      return getErrors(this.edgeServerStats)
    } else {
      return []
    }
  }

  public send(action: HMR_ACTION_TYPES): void {
    this.webpackHotMiddleware!.publish(action)
  }

  public async ensurePage({
    page,
    clientOnly,
    appPaths,
    definition,
    isApp,
    url,
  }: {
    page: string
    clientOnly: boolean
    appPaths?: ReadonlyArray<string> | null
    isApp?: boolean
    definition?: RouteDefinition
    url?: string
  }): Promise<void> {
    return this.hotReloaderSpan
      .traceChild('ensure-page', {
        inputPage: page,
      })
      .traceAsyncFn(async () => {
        // Make sure we don't re-build or dispose prebuilt pages
        if (page !== '/_error' && BLOCKED_PAGES.indexOf(page) !== -1) {
          return
        }
        const error = clientOnly
          ? this.clientError
          : this.serverError || this.clientError
        if (error) {
          throw error
        }

        return this.onDemandEntries?.ensurePage({
          page,
          appPaths,
          definition,
          isApp,
          url,
        })
      })
  }

  public close() {
    this.webpackHotMiddleware?.close()
  }
}