@atlaspack/reporter-dev-server 2.14.21 → 2.14.22-typescript-17c3d1dec.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright (c) 2024 Atlassian US., Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,54 @@
1
+ import type { Asset, BundleGraph, NamedBundle, PackagedBundle, PluginOptions } from '@atlaspack/types';
2
+ import type { Diagnostic } from '@atlaspack/diagnostic';
3
+ import type { AnsiDiagnosticResult } from '@atlaspack/utils';
4
+ import type { ServerError, HMRServerOptions, Request, Response } from './types.js.flow';
5
+ import WebSocket from 'ws';
6
+ export type SetComplement<A, B extends A> = A extends B ? never : A;
7
+ export type Diff<T extends U, U extends object> = Pick<T, SetComplement<keyof T, keyof U>>;
8
+ export type HMRAsset = {
9
+ id: string;
10
+ url: string;
11
+ type: string;
12
+ output: string;
13
+ envHash: string;
14
+ outputFormat: string;
15
+ depsByBundle: {
16
+ [key: string]: {
17
+ [key: string]: string;
18
+ };
19
+ };
20
+ };
21
+ export type HMRMessage = {
22
+ type: 'update';
23
+ assets: Array<HMRAsset>;
24
+ } | {
25
+ type: 'reload';
26
+ } | {
27
+ type: 'error';
28
+ diagnostics: {
29
+ ansi: Array<AnsiDiagnosticResult>;
30
+ html: Array<Partial<Diff<AnsiDiagnosticResult, {
31
+ codeframe: string;
32
+ }>>>;
33
+ };
34
+ };
35
+ export default class HMRServer {
36
+ wss: WebSocket.Server;
37
+ unresolvedError: HMRMessage | null;
38
+ options: HMRServerOptions;
39
+ bundleGraph: BundleGraph<PackagedBundle> | BundleGraph<NamedBundle> | null;
40
+ stopServer: (() => Promise<void>) | null | undefined;
41
+ constructor(options: HMRServerOptions);
42
+ start(): Promise<void>;
43
+ handle(req: Request, res: Response): boolean;
44
+ stop(): Promise<void>;
45
+ emitError(options: PluginOptions, diagnostics: Array<Diagnostic>): Promise<void>;
46
+ emitUpdate(event: {
47
+ readonly bundleGraph: BundleGraph<PackagedBundle> | BundleGraph<NamedBundle>;
48
+ readonly changedAssets: Map<string, Asset>;
49
+ }): Promise<void>;
50
+ getHotAssetContents(asset: Asset): Promise<string>;
51
+ getSourceURL(asset: Asset): string;
52
+ handleSocketError(err: ServerError): void;
53
+ broadcast(msg: HMRMessage): void;
54
+ }
package/lib/HMRServer.js CHANGED
@@ -48,6 +48,14 @@ function _utils() {
48
48
  return data;
49
49
  }
50
50
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
51
+ // @ts-expect-error TS7016
52
+
53
+ // @ts-expect-error TS7016
54
+
55
+ // flow-to-ts helpers
56
+
57
+ // /flow-to-ts helpers
58
+
51
59
  const FS_CONCURRENCY = 64;
52
60
  const HMR_ENDPOINT = '/__parcel_hmr';
53
61
  const BROADCAST_MAX_ASSETS = 10000;
@@ -88,8 +96,6 @@ class HMRServer {
88
96
  ws.send(JSON.stringify(this.unresolvedError));
89
97
  }
90
98
  });
91
-
92
- // $FlowFixMe[incompatible-exact]
93
99
  this.wss.on('error', err => this.handleSocketError(err));
94
100
  }
95
101
  handle(req, res) {
@@ -165,6 +171,7 @@ class HMRServer {
165
171
  });
166
172
  if (isOnlyReferencedByRuntimes) {
167
173
  for (let runtime of runtimes) {
174
+ // @ts-expect-error TS2345
168
175
  changedAssets.add(runtime);
169
176
  }
170
177
  continue;
@@ -204,6 +211,7 @@ class HMRServer {
204
211
  } else {
205
212
  this.broadcast({
206
213
  type: 'update',
214
+ // @ts-expect-error TS2322
207
215
  assets
208
216
  });
209
217
  }
@@ -220,7 +228,6 @@ class HMRServer {
220
228
  let sourcemapStringified = await sourcemap.stringify({
221
229
  format: 'inline',
222
230
  sourceRoot: _Server.SOURCES_ENDPOINT + '/',
223
- // $FlowFixMe
224
231
  fs: asset.fs
225
232
  });
226
233
  (0, _assert().default)(typeof sourcemapStringified === 'string');
@@ -0,0 +1,45 @@
1
+ import type { DevServerOptions, Request, Response } from './types.js.flow';
2
+ import type { BuildSuccessEvent, BundleGraph, FilePath, PluginOptions, PackagedBundle } from '@atlaspack/types';
3
+ import type { Diagnostic } from '@atlaspack/diagnostic';
4
+ import type { FileSystem } from '@atlaspack/fs';
5
+ import type { HTTPServer, FormattedCodeFrame } from '@atlaspack/utils';
6
+ export declare function setHeaders(res: Response): void;
7
+ export declare const SOURCES_ENDPOINT = "/__parcel_source_root";
8
+ type NextFunction = (req: Request, res: Response, next?: (arg1?: any) => any) => any;
9
+ export default class Server {
10
+ pending: boolean;
11
+ pendingRequests: Array<[Request, Response]>;
12
+ middleware: Array<(req: Request, res: Response) => boolean>;
13
+ options: DevServerOptions;
14
+ rootPath: string;
15
+ bundleGraph: BundleGraph<PackagedBundle> | null;
16
+ requestBundle: ((bundle: PackagedBundle) => Promise<BuildSuccessEvent>) | null | undefined;
17
+ errors: Array<{
18
+ message: string;
19
+ stack: string | null | undefined;
20
+ frames: Array<FormattedCodeFrame>;
21
+ hints: Array<string>;
22
+ documentation: string;
23
+ }> | null;
24
+ stopServer: (() => Promise<void>) | null | undefined;
25
+ constructor(options: DevServerOptions);
26
+ buildStart(): void;
27
+ buildSuccess(bundleGraph: BundleGraph<PackagedBundle>, requestBundle: (bundle: PackagedBundle) => Promise<BuildSuccessEvent>): void;
28
+ buildError(options: PluginOptions, diagnostics: Array<Diagnostic>): Promise<void>;
29
+ respond(req: Request, res: Response): unknown;
30
+ sendIndex(req: Request, res: Response): void;
31
+ serveBundle(req: Request, res: Response, next: NextFunction): Promise<void>;
32
+ serveDist(req: Request, res: Response, next: NextFunction): Promise<undefined> | Promise<unknown>;
33
+ serve(fs: FileSystem, root: FilePath, req: Request, res: Response, next: NextFunction): Promise<unknown>;
34
+ sendError(res: Response, statusCode: number): void;
35
+ send404(req: Request, res: Response): void;
36
+ send500(req: Request, res: Response): undefined | Response;
37
+ logAccessIfVerbose(req: Request): void;
38
+ /**
39
+ * Load proxy table from package.json and apply them.
40
+ */
41
+ applyProxyTable(app: any): Promise<Server>;
42
+ start(): Promise<HTTPServer>;
43
+ stop(): Promise<void>;
44
+ }
45
+ export {};
package/lib/Server.js CHANGED
@@ -86,6 +86,18 @@ function _fresh() {
86
86
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
87
87
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
88
88
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
89
+ // @ts-expect-error TS2307
90
+
91
+ // @ts-expect-error TS7016
92
+
93
+ // @ts-expect-error TS7016
94
+
95
+ // @ts-expect-error TS7016
96
+
97
+ // @ts-expect-error TS7016
98
+
99
+ // @ts-expect-error TS7016
100
+
89
101
  function setHeaders(res) {
90
102
  res.setHeader('Access-Control-Allow-Origin', '*');
91
103
  res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, PUT, PATCH, POST, DELETE');
@@ -324,9 +336,13 @@ class Server {
324
336
  public: root,
325
337
  cleanUrls: false
326
338
  }, {
339
+ // @ts-expect-error TS7006
327
340
  lstat: path => fs.stat(path),
341
+ // @ts-expect-error TS7006
328
342
  realpath: path => fs.realpath(path),
343
+ // @ts-expect-error TS7006
329
344
  createReadStream: (path, options) => fs.createReadStream(path, options),
345
+ // @ts-expect-error TS7006
330
346
  readdir: path => fs.readdir(path)
331
347
  });
332
348
  }
@@ -379,13 +395,12 @@ class Server {
379
395
  }
380
396
  for (const [context, options] of Object.entries(cfg)) {
381
397
  // each key is interpreted as context, and value as middleware options
398
+ // @ts-expect-error TS2345
382
399
  app.use((0, _httpProxyMiddleware().createProxyMiddleware)(context, options));
383
400
  }
384
401
  } else {
385
402
  let cfg = await this.options.packageManager.require(configFilePath, fileInRoot);
386
- if (
387
- // $FlowFixMe
388
- Object.prototype.toString.call(cfg) === '[object Module]') {
403
+ if (Object.prototype.toString.call(cfg) === '[object Module]') {
389
404
  cfg = cfg.default;
390
405
  }
391
406
  if (typeof cfg !== 'function') {
@@ -410,10 +425,13 @@ class Server {
410
425
  }
411
426
  };
412
427
  const app = (0, _connect().default)();
428
+ // @ts-expect-error TS7006
413
429
  app.use((req, res, next) => {
414
430
  setHeaders(res);
415
431
  next();
416
432
  });
433
+
434
+ // @ts-expect-error TS7006
417
435
  app.use((req, res, next) => {
418
436
  if (req.url === '/__parcel_healthcheck') {
419
437
  res.statusCode = 200;
@@ -438,14 +456,17 @@ class Server {
438
456
  });
439
457
  this.stopServer = stop;
440
458
  server.listen(this.options.port, this.options.host);
459
+ // @ts-expect-error TS2322
441
460
  return new Promise((resolve, reject) => {
442
461
  server.once('error', err => {
443
462
  this.options.logger.error({
463
+ // @ts-expect-error TS2345
444
464
  message: (0, _serverErrors.default)(err, this.options.port)
445
465
  });
446
466
  reject(err);
447
467
  });
448
468
  server.once('listening', () => {
469
+ // @ts-expect-error TS2345
449
470
  resolve(server);
450
471
  });
451
472
  });
@@ -0,0 +1,3 @@
1
+ import { Reporter } from '@atlaspack/plugin';
2
+ declare const _default: Reporter;
3
+ export default _default;
@@ -61,6 +61,7 @@ var _default = exports.default = new (_plugin().Reporter)({
61
61
  port: serveOptions.port,
62
62
  host: hmrOptions.host,
63
63
  devServer,
64
+ // @ts-expect-error TS7006
64
65
  addMiddleware: handler => {
65
66
  var _server;
66
67
  (_server = server) === null || _server === void 0 || _server.middleware.push(handler);
@@ -106,7 +107,6 @@ var _default = exports.default = new (_plugin().Reporter)({
106
107
  }
107
108
  if (hmrOptions && hmrServer) {
108
109
  await hmrServer.stop();
109
- // $FlowFixMe[prop-missing]
110
110
  hmrServers.delete(hmrServer.wss.options.port);
111
111
  }
112
112
  break;
@@ -0,0 +1,4 @@
1
+ export type ServerError = Error & {
2
+ code: string;
3
+ };
4
+ export default function serverErrors(err: ServerError, port: number): string;
@@ -10,7 +10,10 @@ const serverErrorList = {
10
10
  };
11
11
  function serverErrors(err, port) {
12
12
  let desc = `Error: ${err.code} occurred while setting up server on port ${port.toString()}.`;
13
+
14
+ // @ts-expect-error TS7053
13
15
  if (serverErrorList[err.code]) {
16
+ // @ts-expect-error TS7053
14
17
  desc = serverErrorList[err.code].replace(/{port}/g, port);
15
18
  }
16
19
  return desc;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atlaspack/reporter-dev-server",
3
- "version": "2.14.21",
3
+ "version": "2.14.22-typescript-17c3d1dec.0",
4
4
  "description": "Blazing fast, zero configuration web application bundler",
5
5
  "license": "(MIT OR Apache-2.0)",
6
6
  "type": "commonjs",
@@ -11,8 +11,9 @@
11
11
  "type": "git",
12
12
  "url": "https://github.com/atlassian-labs/atlaspack.git"
13
13
  },
14
- "main": "lib/ServerReporter.js",
15
- "source": "src/ServerReporter.js",
14
+ "main": "./lib/ServerReporter.js",
15
+ "source": "./src/ServerReporter.ts",
16
+ "types": "./lib/ServerReporter.d.ts",
16
17
  "engines": {
17
18
  "node": ">= 16.0.0"
18
19
  },
@@ -25,9 +26,9 @@
25
26
  }
26
27
  },
27
28
  "dependencies": {
28
- "@atlaspack/plugin": "2.14.21",
29
- "@atlaspack/utils": "2.17.3",
30
- "@atlaspack/types": "2.15.11",
29
+ "@atlaspack/plugin": "2.14.22-typescript-17c3d1dec.0",
30
+ "@atlaspack/types": "2.15.12-typescript-17c3d1dec.0",
31
+ "@atlaspack/utils": "2.17.4-typescript-17c3d1dec.0",
31
32
  "connect": "^3.7.0",
32
33
  "ejs": "^3.1.6",
33
34
  "fresh": "^0.5.2",
@@ -39,6 +40,10 @@
39
40
  "ws": "^7.0.0"
40
41
  },
41
42
  "devDependencies": {
42
- "@atlaspack/babel-preset": "2.14.1"
43
- }
44
- }
43
+ "@atlaspack/babel-preset": "2.14.2-typescript-17c3d1dec.0"
44
+ },
45
+ "scripts": {
46
+ "check-ts": "tsc --emitDeclarationOnly --rootDir src"
47
+ },
48
+ "gitHead": "17c3d1decf641e688fcfe3ca985e80e9897b7573"
49
+ }
@@ -1,4 +1,3 @@
1
- // @flow
2
1
  import type {
3
2
  Asset,
4
3
  BundleGraph,
@@ -14,12 +13,15 @@ import type {
14
13
  HMRServerOptions,
15
14
  Request,
16
15
  Response,
16
+ // @ts-expect-error TS2307
17
17
  } from './types.js.flow';
18
18
  import {setHeaders, SOURCES_ENDPOINT} from './Server';
19
19
 
20
20
  import nullthrows from 'nullthrows';
21
21
  import url from 'url';
22
+ // @ts-expect-error TS7016
22
23
  import mime from 'mime-types';
24
+ // @ts-expect-error TS7016
23
25
  import WebSocket from 'ws';
24
26
  import invariant from 'assert';
25
27
  import {
@@ -29,31 +31,52 @@ import {
29
31
  PromiseQueue,
30
32
  } from '@atlaspack/utils';
31
33
 
32
- export type HMRAsset = {|
33
- id: string,
34
- url: string,
35
- type: string,
36
- output: string,
37
- envHash: string,
38
- outputFormat: string,
39
- depsByBundle: {[string]: {[string]: string, ...}, ...},
40
- |};
34
+ // flow-to-ts helpers
35
+ export type SetComplement<A, B extends A> = A extends B ? never : A;
36
+ export type Diff<T extends U, U extends object> = Pick<
37
+ T,
38
+ SetComplement<keyof T, keyof U>
39
+ >;
40
+ // /flow-to-ts helpers
41
+
42
+ export type HMRAsset = {
43
+ id: string;
44
+ url: string;
45
+ type: string;
46
+ output: string;
47
+ envHash: string;
48
+ outputFormat: string;
49
+ depsByBundle: {
50
+ [key: string]: {
51
+ [key: string]: string;
52
+ };
53
+ };
54
+ };
41
55
 
42
56
  export type HMRMessage =
43
- | {|
44
- type: 'update',
45
- assets: Array<HMRAsset>,
46
- |}
47
- | {|
48
- type: 'reload',
49
- |}
50
- | {|
51
- type: 'error',
52
- diagnostics: {|
53
- ansi: Array<AnsiDiagnosticResult>,
54
- html: Array<$Rest<AnsiDiagnosticResult, {|codeframe: string|}>>,
55
- |},
56
- |};
57
+ | {
58
+ type: 'update';
59
+ assets: Array<HMRAsset>;
60
+ }
61
+ | {
62
+ type: 'reload';
63
+ }
64
+ | {
65
+ type: 'error';
66
+ diagnostics: {
67
+ ansi: Array<AnsiDiagnosticResult>;
68
+ html: Array<
69
+ Partial<
70
+ Diff<
71
+ AnsiDiagnosticResult,
72
+ {
73
+ codeframe: string;
74
+ }
75
+ >
76
+ >
77
+ >;
78
+ };
79
+ };
57
80
 
58
81
  const FS_CONCURRENCY = 64;
59
82
  const HMR_ENDPOINT = '/__parcel_hmr';
@@ -65,7 +88,7 @@ export default class HMRServer {
65
88
  options: HMRServerOptions;
66
89
  bundleGraph: BundleGraph<PackagedBundle> | BundleGraph<NamedBundle> | null =
67
90
  null;
68
- stopServer: ?() => Promise<void>;
91
+ stopServer: (() => Promise<void>) | null | undefined;
69
92
 
70
93
  constructor(options: HMRServerOptions) {
71
94
  this.options = options;
@@ -91,18 +114,19 @@ export default class HMRServer {
91
114
  server.listen(this.options.port, this.options.host);
92
115
  this.stopServer = result.stop;
93
116
  } else {
94
- this.options.addMiddleware?.((req, res) => this.handle(req, res));
117
+ this.options.addMiddleware?.((req: Request, res: Response) =>
118
+ this.handle(req, res),
119
+ );
95
120
  }
96
121
  this.wss = new WebSocket.Server({server});
97
122
 
98
- this.wss.on('connection', (ws) => {
123
+ this.wss.on('connection', (ws: any) => {
99
124
  if (this.unresolvedError) {
100
125
  ws.send(JSON.stringify(this.unresolvedError));
101
126
  }
102
127
  });
103
128
 
104
- // $FlowFixMe[incompatible-exact]
105
- this.wss.on('error', (err) => this.handleSocketError(err));
129
+ this.wss.on('error', (err: any) => this.handleSocketError(err));
106
130
  }
107
131
 
108
132
  handle(req: Request, res: Response): boolean {
@@ -158,9 +182,10 @@ export default class HMRServer {
158
182
  }
159
183
 
160
184
  async emitUpdate(event: {
161
- +bundleGraph: BundleGraph<PackagedBundle> | BundleGraph<NamedBundle>,
162
- +changedAssets: Map<string, Asset>,
163
- ...
185
+ readonly bundleGraph:
186
+ | BundleGraph<PackagedBundle>
187
+ | BundleGraph<NamedBundle>;
188
+ readonly changedAssets: Map<string, Asset>;
164
189
  }) {
165
190
  this.unresolvedError = null;
166
191
  this.bundleGraph = event.bundleGraph;
@@ -187,6 +212,7 @@ export default class HMRServer {
187
212
 
188
213
  if (isOnlyReferencedByRuntimes) {
189
214
  for (let runtime of runtimes) {
215
+ // @ts-expect-error TS2345
190
216
  changedAssets.add(runtime);
191
217
  }
192
218
 
@@ -196,9 +222,9 @@ export default class HMRServer {
196
222
 
197
223
  queue.add(async () => {
198
224
  let dependencies = event.bundleGraph.getDependencies(asset);
199
- let depsByBundle = {};
225
+ let depsByBundle: Record<string, any> = {};
200
226
  for (let bundle of event.bundleGraph.getBundlesWithAsset(asset)) {
201
- let deps = {};
227
+ let deps: Record<string, any> = {};
202
228
  for (let dep of dependencies) {
203
229
  let resolved = event.bundleGraph.getResolvedAsset(dep, bundle);
204
230
  if (resolved) {
@@ -231,6 +257,7 @@ export default class HMRServer {
231
257
  } else {
232
258
  this.broadcast({
233
259
  type: 'update',
260
+ // @ts-expect-error TS2322
234
261
  assets,
235
262
  });
236
263
  }
@@ -249,7 +276,6 @@ export default class HMRServer {
249
276
  let sourcemapStringified = await sourcemap.stringify({
250
277
  format: 'inline',
251
278
  sourceRoot: SOURCES_ENDPOINT + '/',
252
- // $FlowFixMe
253
279
  fs: asset.fs,
254
280
  });
255
281
 
@@ -1,5 +1,4 @@
1
- // @flow
2
-
1
+ // @ts-expect-error TS2307
3
2
  import type {DevServerOptions, Request, Response} from './types.js.flow';
4
3
  import type {
5
4
  BuildSuccessEvent,
@@ -25,12 +24,17 @@ import {
25
24
  } from '@atlaspack/utils';
26
25
  import serverErrors from './serverErrors';
27
26
  import fs from 'fs';
27
+ // @ts-expect-error TS7016
28
28
  import ejs from 'ejs';
29
+ // @ts-expect-error TS7016
29
30
  import connect from 'connect';
31
+ // @ts-expect-error TS7016
30
32
  import serveHandler from 'serve-handler';
31
33
  import {createProxyMiddleware} from 'http-proxy-middleware';
32
34
  import {URL, URLSearchParams} from 'url';
35
+ // @ts-expect-error TS7016
33
36
  import launchEditor from 'launch-editor';
37
+ // @ts-expect-error TS7016
34
38
  import fresh from 'fresh';
35
39
 
36
40
  export function setHeaders(res: Response) {
@@ -59,7 +63,11 @@ const TEMPLATE_500 = fs.readFileSync(
59
63
  path.join(__dirname, '..', 'templates/500.html'),
60
64
  'utf8',
61
65
  );
62
- type NextFunction = (req: Request, res: Response, next?: (any) => any) => any;
66
+ type NextFunction = (
67
+ req: Request,
68
+ res: Response,
69
+ next?: (arg1?: any) => any,
70
+ ) => any;
63
71
 
64
72
  export default class Server {
65
73
  pending: boolean;
@@ -68,21 +76,24 @@ export default class Server {
68
76
  options: DevServerOptions;
69
77
  rootPath: string;
70
78
  bundleGraph: BundleGraph<PackagedBundle> | null;
71
- requestBundle: ?(bundle: PackagedBundle) => Promise<BuildSuccessEvent>;
72
- errors: Array<{|
73
- message: string,
74
- stack: ?string,
75
- frames: Array<FormattedCodeFrame>,
76
- hints: Array<string>,
77
- documentation: string,
78
- |}> | null;
79
- stopServer: ?() => Promise<void>;
79
+ requestBundle:
80
+ | ((bundle: PackagedBundle) => Promise<BuildSuccessEvent>)
81
+ | null
82
+ | undefined;
83
+ errors: Array<{
84
+ message: string;
85
+ stack: string | null | undefined;
86
+ frames: Array<FormattedCodeFrame>;
87
+ hints: Array<string>;
88
+ documentation: string;
89
+ }> | null;
90
+ stopServer: (() => Promise<void>) | null | undefined;
80
91
 
81
92
  constructor(options: DevServerOptions) {
82
93
  this.options = options;
83
94
  try {
84
95
  this.rootPath = new URL(options.publicUrl).pathname;
85
- } catch (e) {
96
+ } catch (e: any) {
86
97
  this.rootPath = options.publicUrl;
87
98
  }
88
99
  this.pending = true;
@@ -135,7 +146,7 @@ export default class Server {
135
146
  );
136
147
  }
137
148
 
138
- respond(req: Request, res: Response): mixed {
149
+ respond(req: Request, res: Response): unknown {
139
150
  if (this.middleware.some((handler) => handler(req, res))) return;
140
151
  let {pathname, search} = url.parse(req.originalUrl || req.url);
141
152
  if (pathname == null) {
@@ -281,7 +292,7 @@ export default class Server {
281
292
  invariant(this.requestBundle != null);
282
293
  try {
283
294
  await this.requestBundle(bundle);
284
- } catch (err) {
295
+ } catch (err: any) {
285
296
  this.send500(req, res);
286
297
  return;
287
298
  }
@@ -296,7 +307,7 @@ export default class Server {
296
307
  req: Request,
297
308
  res: Response,
298
309
  next: NextFunction,
299
- ): Promise<void> | Promise<mixed> {
310
+ ): Promise<undefined> | Promise<unknown> {
300
311
  return this.serve(
301
312
  this.options.outputFS,
302
313
  this.options.distDir,
@@ -312,7 +323,7 @@ export default class Server {
312
323
  req: Request,
313
324
  res: Response,
314
325
  next: NextFunction,
315
- ): Promise<mixed> {
326
+ ): Promise<unknown> {
316
327
  if (req.method !== 'GET' && req.method !== 'HEAD') {
317
328
  // method not allowed
318
329
  res.statusCode = 405;
@@ -325,7 +336,7 @@ export default class Server {
325
336
  try {
326
337
  var filePath = url.parse(req.url).pathname || '';
327
338
  filePath = decodeURIComponent(filePath);
328
- } catch (err) {
339
+ } catch (err: any) {
329
340
  return this.sendError(res, 400);
330
341
  }
331
342
 
@@ -343,7 +354,7 @@ export default class Server {
343
354
 
344
355
  try {
345
356
  var stat = await fs.stat(filePath);
346
- } catch (err) {
357
+ } catch (err: any) {
347
358
  if (err.code === 'ENOENT') {
348
359
  return next(req, res);
349
360
  }
@@ -370,9 +381,13 @@ export default class Server {
370
381
  cleanUrls: false,
371
382
  },
372
383
  {
384
+ // @ts-expect-error TS7006
373
385
  lstat: (path) => fs.stat(path),
386
+ // @ts-expect-error TS7006
374
387
  realpath: (path) => fs.realpath(path),
388
+ // @ts-expect-error TS7006
375
389
  createReadStream: (path, options) => fs.createReadStream(path, options),
390
+ // @ts-expect-error TS7006
376
391
  readdir: (path) => fs.readdir(path),
377
392
  },
378
393
  );
@@ -388,7 +403,7 @@ export default class Server {
388
403
  res.end(TEMPLATE_404);
389
404
  }
390
405
 
391
- send500(req: Request, res: Response): void | Response {
406
+ send500(req: Request, res: Response): undefined | Response {
392
407
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
393
408
  res.writeHead(500);
394
409
 
@@ -452,6 +467,7 @@ export default class Server {
452
467
  }
453
468
  for (const [context, options] of Object.entries(cfg)) {
454
469
  // each key is interpreted as context, and value as middleware options
470
+ // @ts-expect-error TS2345
455
471
  app.use(createProxyMiddleware(context, options));
456
472
  }
457
473
  } else {
@@ -459,10 +475,7 @@ export default class Server {
459
475
  configFilePath,
460
476
  fileInRoot,
461
477
  );
462
- if (
463
- // $FlowFixMe
464
- Object.prototype.toString.call(cfg) === '[object Module]'
465
- ) {
478
+ if (Object.prototype.toString.call(cfg) === '[object Module]') {
466
479
  cfg = cfg.default;
467
480
  }
468
481
 
@@ -491,11 +504,13 @@ export default class Server {
491
504
  };
492
505
 
493
506
  const app = connect();
507
+ // @ts-expect-error TS7006
494
508
  app.use((req, res, next) => {
495
509
  setHeaders(res);
496
510
  next();
497
511
  });
498
512
 
513
+ // @ts-expect-error TS7006
499
514
  app.use((req, res, next) => {
500
515
  if (req.url === '/__parcel_healthcheck') {
501
516
  res.statusCode = 200;
@@ -520,20 +535,26 @@ export default class Server {
520
535
  this.stopServer = stop;
521
536
 
522
537
  server.listen(this.options.port, this.options.host);
523
- return new Promise((resolve, reject) => {
524
- server.once('error', (err) => {
525
- this.options.logger.error(
526
- ({
538
+ // @ts-expect-error TS2322
539
+ return new Promise(
540
+ (
541
+ resolve: (result: Promise<Server> | Server) => void,
542
+ reject: (error?: any) => void,
543
+ ) => {
544
+ server.once('error', (err) => {
545
+ this.options.logger.error({
546
+ // @ts-expect-error TS2345
527
547
  message: serverErrors(err, this.options.port),
528
- }: Diagnostic),
529
- );
530
- reject(err);
531
- });
548
+ } as Diagnostic);
549
+ reject(err);
550
+ });
532
551
 
533
- server.once('listening', () => {
534
- resolve(server);
535
- });
536
- });
552
+ server.once('listening', () => {
553
+ // @ts-expect-error TS2345
554
+ resolve(server);
555
+ });
556
+ },
557
+ );
537
558
  }
538
559
 
539
560
  async stop(): Promise<void> {
@@ -1,12 +1,10 @@
1
- // @flow
2
-
3
1
  import {Reporter} from '@atlaspack/plugin';
4
2
  import HMRServer from './HMRServer';
5
3
  import Server from './Server';
6
4
 
7
5
  let servers: Map<number, Server> = new Map();
8
6
  let hmrServers: Map<number, HMRServer> = new Map();
9
- export default (new Reporter({
7
+ export default new Reporter({
10
8
  async report({event, options, logger}) {
11
9
  let {serveOptions, hmrOptions} = options;
12
10
  let server = serveOptions ? servers.get(serveOptions.port) : undefined;
@@ -47,6 +45,7 @@ export default (new Reporter({
47
45
  port: serveOptions.port,
48
46
  host: hmrOptions.host,
49
47
  devServer,
48
+ // @ts-expect-error TS7006
50
49
  addMiddleware: (handler) => {
51
50
  server?.middleware.push(handler);
52
51
  },
@@ -93,7 +92,6 @@ export default (new Reporter({
93
92
  }
94
93
  if (hmrOptions && hmrServer) {
95
94
  await hmrServer.stop();
96
- // $FlowFixMe[prop-missing]
97
95
  hmrServers.delete(hmrServer.wss.options.port);
98
96
  }
99
97
  break;
@@ -140,4 +138,4 @@ export default (new Reporter({
140
138
  break;
141
139
  }
142
140
  },
143
- }): Reporter);
141
+ }) as Reporter;
@@ -1,19 +1,20 @@
1
- // @flow
2
- export type ServerError = Error & {|
3
- code: string,
4
- |};
1
+ export type ServerError = Error & {
2
+ code: string;
3
+ };
5
4
 
6
5
  const serverErrorList = {
7
6
  EACCES: "You don't have access to bind the server to port {port}.",
8
7
  EADDRINUSE: 'There is already a process listening on port {port}.',
9
- };
8
+ } as const;
10
9
 
11
10
  export default function serverErrors(err: ServerError, port: number): string {
12
11
  let desc = `Error: ${
13
12
  err.code
14
13
  } occurred while setting up server on port ${port.toString()}.`;
15
14
 
15
+ // @ts-expect-error TS7053
16
16
  if (serverErrorList[err.code]) {
17
+ // @ts-expect-error TS7053
17
18
  desc = serverErrorList[err.code].replace(/{port}/g, port);
18
19
  }
19
20
 
@@ -1,4 +1,4 @@
1
- <!DOCTYPE html>
1
+ <!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8" />
@@ -1,4 +1,4 @@
1
- <!DOCTYPE html>
1
+ <!doctype html>
2
2
  <html lang="en">
3
3
  <head>
4
4
  <meta charset="UTF-8" />
package/tsconfig.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../../../tsconfig.json",
3
+ "include": ["src"]
4
+ }
package/src/types.js.flow DELETED
@@ -1,56 +0,0 @@
1
- // @flow
2
- import type {
3
- ServerOptions,
4
- PluginLogger,
5
- HMROptions,
6
- HTTPSOptions,
7
- FilePath,
8
- } from '@atlaspack/types';
9
- import type {FileSystem} from '@atlaspack/fs';
10
- import type {HTTPServer} from '@atlaspack/utils';
11
- import type {PackageManager} from '@atlaspack/package-manager';
12
- import {
13
- IncomingMessage as HTTPIncomingMessage,
14
- ServerResponse as HTTPServerResponse,
15
- } from 'http';
16
- import {
17
- IncomingMessage as HTTPSIncomingMessage,
18
- ServerResponse as HTTPSServerResponse,
19
- } from 'https';
20
-
21
- interface HTTPRequest extends HTTPIncomingMessage {
22
- originalUrl?: string;
23
- }
24
- interface HTTPSRequest extends HTTPSIncomingMessage {
25
- originalUrl?: string;
26
- }
27
- export type Request = HTTPRequest | HTTPSRequest;
28
- export type Response = HTTPServerResponse | HTTPSServerResponse;
29
- export type DevServerOptions = {|
30
- ...ServerOptions,
31
- projectRoot: string,
32
- publicUrl: string,
33
- cacheDir: string,
34
- inputFS: FileSystem,
35
- outputFS: FileSystem,
36
- logger: PluginLogger,
37
- hmrOptions: ?HMROptions,
38
- packageManager: PackageManager,
39
- |};
40
-
41
- // TODO: Figure out if there is a node.js type that could be imported with a complete ServerError
42
- export type ServerError = Error & {|
43
- code: string,
44
- |};
45
-
46
- export type HMRServerOptions = {|
47
- devServer?: HTTPServer,
48
- addMiddleware?: (handler: (req: Request, res: Response) => boolean) => void,
49
- port: number,
50
- host: ?string,
51
- logger: PluginLogger,
52
- https?: HTTPSOptions | boolean,
53
- cacheDir: FilePath,
54
- inputFS: FileSystem,
55
- outputFS: FileSystem,
56
- |};