File size: 8,399 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Based on https://github.com/webpack-contrib/webpack-hot-middleware/blob/9708d781ae0e46179cf8ea1a94719de4679aaf53/middleware.js
// Included License below

// Copyright JS Foundation and other contributors

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type ws from 'next/dist/compiled/ws'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import { isMiddlewareFilename } from '../../build/utils'
import type { VersionInfo } from './parse-version-info'
import type { HMR_ACTION_TYPES } from './hot-reloader-types'
import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'
import { devIndicatorServerState } from './dev-indicator-server-state'

function isMiddlewareStats(stats: webpack.Stats) {
  for (const key of stats.compilation.entrypoints.keys()) {
    if (isMiddlewareFilename(key)) {
      return true
    }
  }

  return false
}

function statsToJson(stats?: webpack.Stats | null) {
  if (!stats) return {}
  return stats.toJson({
    all: false,
    errors: true,
    hash: true,
    warnings: true,
  })
}

function getStatsForSyncEvent(
  clientStats: { ts: number; stats: webpack.Stats } | null,
  serverStats: { ts: number; stats: webpack.Stats } | null
) {
  if (!clientStats) return serverStats?.stats
  if (!serverStats) return clientStats?.stats

  // Prefer the server compiler stats if it has errors.
  // Otherwise we may end up in a state where the client compilation is the latest but without errors.
  // This causes the error overlay to not display the build error.
  if (serverStats.stats.hasErrors()) {
    return serverStats.stats
  }

  // Return the latest stats
  return serverStats.ts > clientStats.ts ? serverStats.stats : clientStats.stats
}

class EventStream {
  clients: Set<ws>
  constructor() {
    this.clients = new Set()
  }

  close() {
    for (const wsClient of this.clients) {
      // it's okay to not cleanly close these websocket connections, this is dev
      wsClient.terminate()
    }
    this.clients.clear()
  }

  handler(client: ws) {
    this.clients.add(client)
    client.addEventListener('close', () => {
      this.clients.delete(client)
    })
  }

  publish(payload: any) {
    for (const wsClient of this.clients) {
      wsClient.send(JSON.stringify(payload))
    }
  }
}

export class WebpackHotMiddleware {
  eventStream: EventStream
  clientLatestStats: { ts: number; stats: webpack.Stats } | null
  middlewareLatestStats: { ts: number; stats: webpack.Stats } | null
  serverLatestStats: { ts: number; stats: webpack.Stats } | null
  closed: boolean
  versionInfo: VersionInfo
  devtoolsFrontendUrl: string | undefined
  devToolsConfig: DevToolsConfig

  constructor(
    compilers: webpack.Compiler[],
    versionInfo: VersionInfo,
    devtoolsFrontendUrl: string | undefined,
    devToolsConfig: DevToolsConfig
  ) {
    this.eventStream = new EventStream()
    this.clientLatestStats = null
    this.middlewareLatestStats = null
    this.serverLatestStats = null
    this.closed = false
    this.versionInfo = versionInfo
    this.devtoolsFrontendUrl = devtoolsFrontendUrl
    this.devToolsConfig = devToolsConfig || ({} as DevToolsConfig)

    compilers[0].hooks.invalid.tap(
      'webpack-hot-middleware',
      this.onClientInvalid
    )
    compilers[0].hooks.done.tap('webpack-hot-middleware', this.onClientDone)
    compilers[1].hooks.invalid.tap(
      'webpack-hot-middleware',
      this.onServerInvalid
    )
    compilers[1].hooks.done.tap('webpack-hot-middleware', this.onServerDone)
    compilers[2].hooks.done.tap('webpack-hot-middleware', this.onEdgeServerDone)
    compilers[2].hooks.invalid.tap(
      'webpack-hot-middleware',
      this.onEdgeServerInvalid
    )
  }

  onClientInvalid = () => {
    if (this.closed || this.serverLatestStats?.stats.hasErrors()) return
    this.publish({
      action: HMR_ACTIONS_SENT_TO_BROWSER.BUILDING,
    })
  }

  onClientDone = (statsResult: webpack.Stats) => {
    this.clientLatestStats = { ts: Date.now(), stats: statsResult }
    if (this.closed || this.serverLatestStats?.stats.hasErrors()) return
    this.publishStats(statsResult)
  }

  onServerInvalid = () => {
    if (!this.serverLatestStats?.stats.hasErrors()) return
    this.serverLatestStats = null
    if (this.clientLatestStats?.stats) {
      this.publishStats(this.clientLatestStats.stats)
    }
  }

  onServerDone = (statsResult: webpack.Stats) => {
    if (this.closed) return
    if (statsResult.hasErrors()) {
      this.serverLatestStats = { ts: Date.now(), stats: statsResult }
      this.publishStats(statsResult)
    }
  }

  onEdgeServerInvalid = () => {
    if (!this.middlewareLatestStats?.stats.hasErrors()) return
    this.middlewareLatestStats = null
    if (this.clientLatestStats?.stats) {
      this.publishStats(this.clientLatestStats.stats)
    }
  }

  onEdgeServerDone = (statsResult: webpack.Stats) => {
    if (this.closed) return
    if (!isMiddlewareStats(statsResult)) {
      this.onServerInvalid()
      this.onServerDone(statsResult)
    }

    if (statsResult.hasErrors()) {
      this.middlewareLatestStats = { ts: Date.now(), stats: statsResult }
      this.publishStats(statsResult)
    }
  }

  public updateDevToolsConfig(newConfig: DevToolsConfig): void {
    this.devToolsConfig = newConfig
  }

  /**
   * To sync we use the most recent stats but also we append middleware
   * errors. This is because it is possible that middleware fails to compile
   * and we still want to show the client overlay with the error while
   * the error page should be rendered just fine.
   */
  onHMR = (client: ws) => {
    if (this.closed) return
    this.eventStream.handler(client)

    const syncStats = getStatsForSyncEvent(
      this.clientLatestStats,
      this.serverLatestStats
    )

    if (syncStats) {
      const stats = statsToJson(syncStats)
      const middlewareStats = statsToJson(this.middlewareLatestStats?.stats)

      if (devIndicatorServerState.disabledUntil < Date.now()) {
        devIndicatorServerState.disabledUntil = 0
      }

      this.publish({
        action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
        hash: stats.hash!,
        errors: [...(stats.errors || []), ...(middlewareStats.errors || [])],
        warnings: [
          ...(stats.warnings || []),
          ...(middlewareStats.warnings || []),
        ],
        versionInfo: this.versionInfo,
        debug: {
          devtoolsFrontendUrl: this.devtoolsFrontendUrl,
        },
        devIndicator: devIndicatorServerState,
        devToolsConfig: this.devToolsConfig,
      })
    }
  }

  publishStats = (statsResult: webpack.Stats) => {
    const stats = statsResult.toJson({
      all: false,
      hash: true,
      warnings: true,
      errors: true,
      moduleTrace: true,
    })

    this.publish({
      action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT,
      hash: stats.hash!,
      warnings: stats.warnings || [],
      errors: stats.errors || [],
    })
  }

  publish = (payload: HMR_ACTION_TYPES) => {
    if (this.closed) return
    this.eventStream.publish(payload)
  }
  close = () => {
    if (this.closed) return
    // Can't remove compiler plugins, so we just set a flag and noop if closed
    // https://github.com/webpack/tapable/issues/32#issuecomment-350644466
    this.closed = true
    this.eventStream.close()
  }
}