h2lean 0.11.1 → 0.16.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/lib/stream.js CHANGED
@@ -249,7 +249,7 @@ function autoCloseNT(stream) {
249
249
  return;
250
250
  }
251
251
  stream._tick(emitEndNT, stream);
252
- stream._destroy(NO_ERROR, undefined, true);
252
+ stream._destroy(NO_ERROR, true);
253
253
  }
254
254
 
255
255
  // node's onFileUnpipe closes an owned descriptor without caring about the error; the
@@ -398,6 +398,7 @@ class Http2Stream extends Stream {
398
398
  // lib/fast-tick.js; every deferred callback of this stream goes through it.
399
399
  this._tick = session._tick;
400
400
  this.rstCode = 0;
401
+ this._closedFlag = false;
401
402
  // What respond() put on the wire, for the `sentHeaders` getter below: the caller's map
402
403
  // plus the two values the encoder resolved. node keeps the same three pieces
403
404
  // (kRawHeaders / kSentHeaders, internal/http2/core.js:2225).
@@ -405,8 +406,21 @@ class Http2Stream extends Stream {
405
406
  this._sentStatus = 0;
406
407
  this._sentDate = undefined;
407
408
  this._sentView = undefined;
408
- this.sentInfoHeaders = [];
409
+ // sentInfoHeaders stays unset until the first informational block: node's
410
+ // kInfoHeaders is created by the first additionalHeaders() call
411
+ // (internal/http2/core.js:3285) and the getter reads undefined before it.
409
412
  this.sentTrailers = undefined;
413
+ // The inbound request, as the session's accept path scanned it off the
414
+ // field list in one pass (lib/session.js): the :method the HEAD checks
415
+ // here and the compat CONNECT check read, :path for req.url, and the
416
+ // stable list the compat request object builds from at the first read
417
+ // (OPTIMIZATION.md item 49). _reqFields is null when no compat server
418
+ // owns the session and no raw list was asked for; _requestHeaders above
419
+ // stays unset until the object exists.
420
+ this._reqFields = null;
421
+ this._reqMethod = undefined;
422
+ this._reqPath = undefined;
423
+ this._reqSensitive = undefined;
410
424
  this.headersSent = false;
411
425
  this.pending = true;
412
426
  this.aborted = false;
@@ -489,7 +503,10 @@ class Http2Stream extends Stream {
489
503
  return this._destroyed;
490
504
  }
491
505
  get closed() {
492
- return this._state.state === ST_CLOSED;
506
+ // node's STREAM_FLAGS_CLOSED (core.js:2458) -- set by close() at entry, so the
507
+ // second-call guard holds even while the teardown waits on 'finish'; the state
508
+ // check keeps the machinery paths (peer RST, destroy) answering as they did.
509
+ return this._closedFlag === true || this._state.state === ST_CLOSED;
493
510
  }
494
511
  // node's public state getter answers {} once the stream is destroyed
495
512
  // (internal/http2/core.js:2304, `if (this.destroyed || id === undefined)`);
@@ -670,7 +687,7 @@ class Http2Stream extends Stream {
670
687
  // request line. Same fact in h2lean, read where respond() tests it already: the flag
671
688
  // source is the request map, so there is no state to keep out of sync.
672
689
  get headRequest() {
673
- return this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
690
+ return this._reqMethod === 'HEAD';
674
691
  }
675
692
 
676
693
  respond(headers, options) {
@@ -699,7 +716,7 @@ class Http2Stream extends Stream {
699
716
  // HEADERS. Measured on the wire against live node: node puts
700
717
  // HEADERS/ES/EH and no DATA for both shapes; h2lean used to leave a regular
701
718
  // HEAD answer open and send the body, which nghttp2 reads as a protocol error.
702
- const head = this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
719
+ const head = this._reqMethod === 'HEAD';
703
720
  // node puts a `date` on every response of this API too: prepareResponseHeadersObject()
704
721
  // (internal/http2/core.js:2702) adds one unless the application set one itself or
705
722
  // `options.sendDate` says otherwise -- and its test is `sendDate == null || sendDate`,
@@ -781,8 +798,7 @@ class Http2Stream extends Stream {
781
798
  this.ownsFd = false;
782
799
  const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
783
800
  const { headers: prepared, statusCode } = prepareResponseHeadersObject(headers);
784
- const head =
785
- this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
801
+ const head = this._reqMethod === 'HEAD';
786
802
  if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
787
803
  throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
788
804
  `Responses with ${statusCode} status must not have a payload`);
@@ -834,8 +850,7 @@ class Http2Stream extends Stream {
834
850
  const sendDate = opts.sendDate == null ? true : !!opts.sendDate;
835
851
  const { headers: prepared, statusCode, isArray } =
836
852
  prepareResponseHeadersObject(headers);
837
- const head =
838
- this._requestHeaders !== undefined && this._requestHeaders[':method'] === 'HEAD';
853
+ const head = this._reqMethod === 'HEAD';
839
854
  if (statusCode === 204 || statusCode === 205 || statusCode === 304 || head) {
840
855
  throw errorOf('ERR_HTTP2_PAYLOAD_FORBIDDEN',
841
856
  `Responses with ${statusCode} status must not have a payload`);
@@ -1296,17 +1311,48 @@ class Http2Stream extends Stream {
1296
1311
  this._endLocalSide();
1297
1312
  }
1298
1313
 
1299
- close(code = NO_ERROR, reason) {
1300
- this._destroy(code, reason, true);
1314
+ close(code = NO_ERROR, callback) {
1315
+ // node: Http2Stream.close (internal/http2/core.js:2474) -- validateInteger 0..2^32-1,
1316
+ // validateFunction, a second call on a closed stream is a silent no-op, and the
1317
+ // callback rides 'close' with no arguments (measured: cb(0)). The old (code, reason)
1318
+ // shape was h2lean's invention: RST_STREAM carries no reason text (RFC 9113 6.4) and
1319
+ // node's second argument is this callback.
1320
+ validateRstCode(code, callback);
1321
+ if (this.closed) {
1322
+ return;
1323
+ }
1324
+ if (callback !== undefined) {
1325
+ this.once('close', callback);
1326
+ }
1327
+ // closeStream (core.js:2071-2101) is the base method both sides share. It sets
1328
+ // STREAM_FLAGS_CLOSED and rstCode at ENTRY, before the abort and the RST decision
1329
+ // -- a second close() is a no-op even while the teardown still waits on 'finish'.
1330
+ // h2lean sets the flag after the end() below instead: this end() is the one place
1331
+ // the auto-respond runs, and respond() refuses a closed stream -- setting the flag
1332
+ // first would throw out of close() on the unresponded shape node's plain end()
1333
+ // never reaches (AGENTS.md section 10).
1334
+ const ending = this._ending;
1335
+ if (!ending) {
1336
+ this.aborted = true;
1337
+ this.emit('aborted');
1338
+ this.end();
1339
+ }
1340
+ this._closedFlag = true;
1341
+ this.rstCode = code;
1342
+ if (ending && this._writableFinished !== true && code === NO_ERROR) {
1343
+ this.once('finish', () => this._destroy(code, true));
1344
+ } else {
1345
+ this._destroy(code, true);
1346
+ }
1301
1347
  }
1302
1348
 
1303
- destroy(codeOrError, reason) {
1349
+ destroy(codeOrError) {
1304
1350
  // node: an Error argument means NGHTTP2_INTERNAL_ERROR on the wire
1305
1351
  // (Http2Stream._destroy, internal/http2/core.js:2518); a number is the RST
1306
1352
  // code itself, and no argument at all is a graceful NO_ERROR close.
1307
1353
  const code = typeof codeOrError === 'number' ? codeOrError
1308
1354
  : (codeOrError != null ? INTERNAL_ERROR : NO_ERROR);
1309
- this._destroy(code, reason, true, typeof codeOrError === 'object' ? codeOrError : null);
1355
+ this._destroy(code, true, typeof codeOrError === 'object' ? codeOrError : null);
1310
1356
  }
1311
1357
 
1312
1358
  // An informational (1xx) HEADERS block, sent before the final response.
@@ -1321,7 +1367,15 @@ class Http2Stream extends Stream {
1321
1367
  // (101 has its own error), there is no default status and no generated date.
1322
1368
  const block = hdr.block(headers, { info: true }, this.session);
1323
1369
  const bound = hdr.sent.bound;
1324
- this.sentInfoHeaders.push(headers);
1370
+ // node stores a null-proto copy of each informational block, created at the
1371
+ // first call (internal/http2/core.js:3265, 3285) -- the caller's object is
1372
+ // not retained, and the array does not exist before the first call.
1373
+ const copy = Object.assign({ __proto__: null }, headers);
1374
+ if (this.sentInfoHeaders === undefined) {
1375
+ this.sentInfoHeaders = [copy];
1376
+ } else {
1377
+ this.sentInfoHeaders.push(copy);
1378
+ }
1325
1379
  this.session.sendHeaders(this.id, block, false, bound);
1326
1380
  return this;
1327
1381
  }
@@ -1397,17 +1451,36 @@ class Http2Stream extends Stream {
1397
1451
 
1398
1452
  // Defaults from the parent request (node: core.js pushStream fills :method GET,
1399
1453
  // :authority and :scheme from the request, :path '/'). The headers object is copied
1400
- // into a null-proto map so the application's object is not mutated.
1401
- const req = this._requestHeaders || {};
1454
+ // into a null-proto map so the application's object is not mutated. The parent's
1455
+ // values come off the request object when it exists and off the stable field list
1456
+ // otherwise -- the compat request object may not have been built at all
1457
+ // (OPTIMIZATION.md item 49), and a pseudo-header cannot repeat, so a first match
1458
+ // on the list is the value the object would carry.
1402
1459
  const h = Object.assign(Object.create(null), headers);
1403
1460
  if (h[':method'] === undefined) {
1404
1461
  h[':method'] = 'GET';
1405
1462
  }
1406
- if (h[':authority'] === undefined && req[':authority'] !== undefined) {
1407
- h[':authority'] = req[':authority'];
1463
+ let parentAuthority;
1464
+ let parentScheme;
1465
+ const src = this._requestHeaders;
1466
+ if (src !== undefined) {
1467
+ parentAuthority = src[':authority'];
1468
+ parentScheme = src[':scheme'];
1469
+ } else {
1470
+ const fields = this._reqFields;
1471
+ for (let i = 0; i < fields.length; i += 2) {
1472
+ if (fields[i] === ':authority') {
1473
+ parentAuthority = fields[i + 1];
1474
+ } else if (fields[i] === ':scheme') {
1475
+ parentScheme = fields[i + 1];
1476
+ }
1477
+ }
1478
+ }
1479
+ if (h[':authority'] === undefined && parentAuthority !== undefined) {
1480
+ h[':authority'] = parentAuthority;
1408
1481
  }
1409
- if (h[':scheme'] === undefined && req[':scheme'] !== undefined) {
1410
- h[':scheme'] = req[':scheme'];
1482
+ if (h[':scheme'] === undefined && parentScheme !== undefined) {
1483
+ h[':scheme'] = parentScheme;
1411
1484
  }
1412
1485
  if (h[':path'] === undefined) {
1413
1486
  h[':path'] = '/';
@@ -1448,6 +1521,7 @@ class Http2Stream extends Stream {
1448
1521
  // the getter above hands it back unchanged.
1449
1522
  stream._sentView = h;
1450
1523
  stream._requestHeaders = h;
1524
+ stream._reqMethod = h[':method'];
1451
1525
  this.session._streams.set(promisedId, stream);
1452
1526
  this.session._liveStreams++;
1453
1527
  stream._remoteEnded();
@@ -1683,7 +1757,7 @@ class Http2Stream extends Stream {
1683
1757
  const c = pending[i];
1684
1758
  const buf = c.length === undefined ? c.data : c;
1685
1759
  const take = buf.length <= n - off ? buf.length : n - off;
1686
- buf.copy(out, off, 0, take);
1760
+ frames.copyInto(out, off, buf, 0, take);
1687
1761
  off += take;
1688
1762
  if (c.length !== undefined) {
1689
1763
  wire += take;
@@ -2556,7 +2630,7 @@ class Http2Stream extends Stream {
2556
2630
  // inside the read batch.
2557
2631
  }
2558
2632
 
2559
- _destroy(code, reason, sendRst, err) {
2633
+ _destroy(code, sendRst, err) {
2560
2634
  if (this._destroyed) {
2561
2635
  return;
2562
2636
  }
@@ -2595,7 +2669,7 @@ class Http2Stream extends Stream {
2595
2669
  this._state.localClose = 1;
2596
2670
  this._state.state = ST_CLOSED;
2597
2671
  if (sendRst && this.session._open) {
2598
- this.session.sendRst(this.id, code, reason);
2672
+ this.session.sendRst(this.id, code);
2599
2673
  }
2600
2674
  this._pending = null;
2601
2675
  this.session._dropStream(this, true);
@@ -2848,6 +2922,104 @@ function errorOf(code, msg) {
2848
2922
  return err;
2849
2923
  }
2850
2924
 
2925
+ // node's Http2Stream.close validates its code with validateInteger(code, 'code', 0,
2926
+ // kMaxInt) and the callback with validateFunction (internal/http2/core.js:2474,
2927
+ // kMaxInt = 2^32 - 1 at core.js:239). The messages are internal/validators', read
2928
+ // out of it in the same session: a non-number is ERR_INVALID_ARG_TYPE, a
2929
+ // non-integer or an out-of-range integer is ERR_OUT_OF_RANGE.
2930
+ // The Received-tail is determineSpecificType (internal/errors.js), ported from the
2931
+ // bundled source and measured through Http2Stream.close on a live v26.12.1 client:
2932
+ // strings quote with '' and flip to JSON.stringify when the value itself carries a
2933
+ // quote, both truncated at 28 octets to 25 plus '...'; -0/NaN/Infinity are named;
2934
+ // an object reports `an instance of ${constructor.name}` only when that name is a
2935
+ // non-empty string, else the inspect fallback at depth -1; `function ${name}` keeps
2936
+ // the trailing space for an anonymous function; the generic tail inspects, it does
2937
+ // not String().
2938
+ function specType(v) {
2939
+ if (v === null) {
2940
+ return 'null';
2941
+ }
2942
+ if (v === undefined) {
2943
+ return 'undefined';
2944
+ }
2945
+ const t = typeof v;
2946
+ if (t === 'string') {
2947
+ if (v.length > 28) {
2948
+ v = `${v.slice(0, 25)}...`;
2949
+ }
2950
+ return v.indexOf("'") === -1 ? `type string ('${v}')`
2951
+ : `type string (${JSON.stringify(v)})`;
2952
+ }
2953
+ if (t === 'number') {
2954
+ if (v === 0) {
2955
+ return 1 / v === -Infinity ? 'type number (-0)' : 'type number (0)';
2956
+ }
2957
+ if (v !== v) {
2958
+ return 'type number (NaN)';
2959
+ }
2960
+ if (v === Infinity) {
2961
+ return 'type number (Infinity)';
2962
+ }
2963
+ if (v === -Infinity) {
2964
+ return 'type number (-Infinity)';
2965
+ }
2966
+ return `type number (${v})`;
2967
+ }
2968
+ if (t === 'boolean') {
2969
+ return v ? 'type boolean (true)' : 'type boolean (false)';
2970
+ }
2971
+ if (t === 'bigint') {
2972
+ return `type bigint (${v}n)`;
2973
+ }
2974
+ if (t === 'symbol') {
2975
+ return `type symbol (${String(v)})`;
2976
+ }
2977
+ if (t === 'function') {
2978
+ return `function ${v.name}`;
2979
+ }
2980
+ if (t === 'object') {
2981
+ // `constructor` may be user-controlled: node reads it once and only trusts a
2982
+ // non-empty string name (internal/errors.js).
2983
+ const name = v.constructor?.name;
2984
+ if (typeof name === 'string' && name !== '') {
2985
+ return `an instance of ${name}`;
2986
+ }
2987
+ return inspect(v, { depth: -1 });
2988
+ }
2989
+ let shown = inspect(v, { colors: false });
2990
+ if (shown.length > 28) {
2991
+ shown = `${shown.slice(0, 25)}...`;
2992
+ }
2993
+ return `type ${t} (${shown})`;
2994
+ }
2995
+
2996
+ // node's Http2Stream.close (core.js:2474) validates its code through
2997
+ // validateInteger(code, 'code', 0, kMaxInt) -- kMaxInt is 2^32-1 (core.js:239) -- and
2998
+ // its callback through validateFunction; the three verdicts and their exact texts are
2999
+ // measured on a live v26.12.1 client: a non-number code is ERR_INVALID_ARG_TYPE
3000
+ // ("must be of type number"), a non-integer number is ERR_OUT_OF_RANGE ("It must be an
3001
+ // integer"), and a code outside [0, 2^32-1] is ERR_OUT_OF_RANGE ("It must be >= 0 &&
3002
+ // <= 4294967295"). The callback's own message names "callback" and follows the same
3003
+ // determineSpecificType shapes (measured: string, null, number).
3004
+ function validateRstCode(code, callback) {
3005
+ if (typeof code !== 'number') {
3006
+ throw errorOf('ERR_INVALID_ARG_TYPE',
3007
+ `The "code" argument must be of type number. Received ${specType(code)}`);
3008
+ }
3009
+ if (!Number.isInteger(code)) {
3010
+ throw errorOf('ERR_OUT_OF_RANGE',
3011
+ `The value of "code" is out of range. It must be an integer. Received ${code}`);
3012
+ }
3013
+ if (code < 0 || code > 4294967295) {
3014
+ throw errorOf('ERR_OUT_OF_RANGE',
3015
+ `The value of "code" is out of range. It must be >= 0 && <= 4294967295. Received ${code}`);
3016
+ }
3017
+ if (callback !== undefined && typeof callback !== 'function') {
3018
+ throw errorOf('ERR_INVALID_ARG_TYPE',
3019
+ `The "callback" argument must be of type function. Received ${specType(callback)}`);
3020
+ }
3021
+ }
3022
+
2851
3023
  // --- the async-iteration machinery ----------------------------------------------
2852
3024
  // Everything below reproduces node's internal/streams/readable.js:1552-1805
2853
3025
  // (streamToAsyncIterator/createAsyncIterator) and internal/streams/operators,
@@ -2963,22 +3135,26 @@ function createStreamIterator(stream, options) {
2963
3135
  function start() {
2964
3136
  started = true;
2965
3137
  stream.on('readable', fire);
2966
- let settled = false;
3138
+ // node's eos(stream, { writable: false }, cb), adapted: the verdict
3139
+ // handlers record the FIRST verdict and wake the pump (node's once-wrapped
3140
+ // callback suppresses the rest -- an 'end' followed by a destroy(err) is
3141
+ // swallowed on node, measured off a live client), and the LISTENERS stay
3142
+ // attached until finalize's detach branch -- the part that matters here:
3143
+ // node's eos keeps its 'error' handler attached through the teardown, so a
3144
+ // destroy that races a natural end does not turn into an unhandled
3145
+ // 'error'. A close with neither end nor error is node's eos verdict
3146
+ // ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
3147
+ // internal/errors with --expose-internals).
2967
3148
  const settle = (err) => {
2968
- if (settled) {
3149
+ if (error !== undefined) {
2969
3150
  return;
2970
3151
  }
2971
- settled = true;
2972
- detach();
2973
3152
  error = err;
2974
3153
  fire();
2975
3154
  };
2976
3155
  const onEnd = () => {
2977
3156
  settle(null);
2978
3157
  };
2979
- // a close with neither end nor error is node's eos verdict
2980
- // ERR_STREAM_PREMATURE_CLOSE ('Premature close', read out of
2981
- // internal/errors with --expose-internals).
2982
3158
  const onClose = () => {
2983
3159
  settle(errorOf('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'));
2984
3160
  };
@@ -2991,13 +3167,11 @@ function createStreamIterator(stream, options) {
2991
3167
  stream.removeListener('end', onEnd);
2992
3168
  stream.removeListener('close', onClose);
2993
3169
  };
2994
- // node's start() hooks eos, not raw 'end'/'close', and an eos on a
2995
- // stream that has ALREADY settled calls back on the next tick: a second
2996
- // iterator over an ended stream gets `{done:true}` (measured on live
2997
- // node: every() after some() on the same stream answers true without
2998
- // hanging), and over a destroyed one gets the premature-close error.
2999
- // The one-shot trio below can never fire again, so this is where that
3000
- // verdict is reproduced.
3170
+ // node's eos settles immediately (on the next tick) when the stream has
3171
+ // ALREADY reached its verdict at start(): a second iterator over an ended
3172
+ // stream gets `{done:true}` (measured on live node: every() after some()
3173
+ // on the same stream answers true without hanging), and over a destroyed
3174
+ // one gets the premature-close error.
3001
3175
  if (stream.readableEnded === true) {
3002
3176
  stream._tick(() => settle(null));
3003
3177
  } else if (stream.destroyed === true) {
@@ -3019,7 +3193,7 @@ function createStreamIterator(stream, options) {
3019
3193
  // error:ABORT_ERR, close; natural end -- destroyed stays false.
3020
3194
  if ((error || options?.destroyOnReturn !== false) && error === undefined) {
3021
3195
  if (!stream.destroyed) {
3022
- stream._destroy(frames.CANCEL, undefined, true, abortError());
3196
+ stream._destroy(frames.CANCEL, true, abortError());
3023
3197
  }
3024
3198
  } else {
3025
3199
  stream.removeListener('readable', fire);
@@ -3483,4 +3657,4 @@ function streamErrorOf(code) {
3483
3657
  `Stream closed with error code ${frames.ERROR_NAMES[code] || code}`);
3484
3658
  }
3485
3659
 
3486
- module.exports = { Http2Stream, errorOf, streamErrorOf, emitNT, emitCloseNT, emitDrainNT };
3660
+ module.exports = { Http2Stream, errorOf, streamErrorOf, validateRstCode, emitNT, emitCloseNT, emitDrainNT };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h2lean",
3
- "version": "0.11.1",
3
+ "version": "0.16.0",
4
4
  "description": "Pure-JavaScript HTTP/2 for Node.js — a drop-in node:http2 replacement (server and client, h2c and TLS) with zero dependencies",
5
5
  "main": "index.js",
6
6
  "files": [