@mcpc-tech/cli 0.1.49 → 0.1.51

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.
Files changed (11) hide show
  1. package/app.cjs +463 -267
  2. package/app.mjs +465 -267
  3. package/bin/mcpc.cjs +443 -265
  4. package/bin/mcpc.mjs +443 -265
  5. package/bin.cjs +443 -265
  6. package/bin.mjs +445 -265
  7. package/index.cjs +463 -267
  8. package/index.mjs +465 -267
  9. package/package.json +1 -1
  10. package/server.cjs +463 -267
  11. package/server.mjs +465 -267
package/server.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { createRequire } from 'node:module';
2
+ const require = createRequire(import.meta.url);
1
3
  var __create = Object.create;
2
4
  var __defProp = Object.defineProperty;
3
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -3031,6 +3033,7 @@ data:
3031
3033
  async handleGetRequest(req) {
3032
3034
  const acceptHeader = req.headers.get("accept");
3033
3035
  if (!acceptHeader?.includes("text/event-stream")) {
3036
+ this.onerror?.(new Error("Not Acceptable: Client must accept text/event-stream"));
3034
3037
  return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream");
3035
3038
  }
3036
3039
  const sessionError = this.validateSession(req);
@@ -3048,6 +3051,7 @@ data:
3048
3051
  }
3049
3052
  }
3050
3053
  if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) {
3054
+ this.onerror?.(new Error("Conflict: Only one SSE stream is allowed per session"));
3051
3055
  return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session");
3052
3056
  }
3053
3057
  const encoder2 = new TextEncoder();
@@ -3087,6 +3091,7 @@ data:
3087
3091
  */
3088
3092
  async replayEvents(lastEventId) {
3089
3093
  if (!this._eventStore) {
3094
+ this.onerror?.(new Error("Event store not configured"));
3090
3095
  return this.createJsonErrorResponse(400, -32e3, "Event store not configured");
3091
3096
  }
3092
3097
  try {
@@ -3094,9 +3099,11 @@ data:
3094
3099
  if (this._eventStore.getStreamIdForEventId) {
3095
3100
  streamId = await this._eventStore.getStreamIdForEventId(lastEventId);
3096
3101
  if (!streamId) {
3102
+ this.onerror?.(new Error("Invalid event ID format"));
3097
3103
  return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format");
3098
3104
  }
3099
3105
  if (this._streamMapping.get(streamId) !== void 0) {
3106
+ this.onerror?.(new Error("Conflict: Stream already has an active connection"));
3100
3107
  return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection");
3101
3108
  }
3102
3109
  }
@@ -3162,7 +3169,8 @@ data:
3162
3169
  `;
3163
3170
  controller.enqueue(encoder2.encode(eventData));
3164
3171
  return true;
3165
- } catch {
3172
+ } catch (error) {
3173
+ this.onerror?.(error);
3166
3174
  return false;
3167
3175
  }
3168
3176
  }
@@ -3170,6 +3178,7 @@ data:
3170
3178
  * Handles unsupported requests (PUT, PATCH, etc.)
3171
3179
  */
3172
3180
  handleUnsupportedRequest() {
3181
+ this.onerror?.(new Error("Method not allowed."));
3173
3182
  return new Response(JSON.stringify({
3174
3183
  jsonrpc: "2.0",
3175
3184
  error: {
@@ -3192,14 +3201,17 @@ data:
3192
3201
  try {
3193
3202
  const acceptHeader = req.headers.get("accept");
3194
3203
  if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) {
3204
+ this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream"));
3195
3205
  return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream");
3196
3206
  }
3197
3207
  const ct = req.headers.get("content-type");
3198
3208
  if (!ct || !ct.includes("application/json")) {
3209
+ this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json"));
3199
3210
  return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json");
3200
3211
  }
3201
3212
  const requestInfo = {
3202
- headers: Object.fromEntries(req.headers.entries())
3213
+ headers: Object.fromEntries(req.headers.entries()),
3214
+ url: new URL(req.url)
3203
3215
  };
3204
3216
  let rawMessage;
3205
3217
  if (options?.parsedBody !== void 0) {
@@ -3208,6 +3220,7 @@ data:
3208
3220
  try {
3209
3221
  rawMessage = await req.json();
3210
3222
  } catch {
3223
+ this.onerror?.(new Error("Parse error: Invalid JSON"));
3211
3224
  return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON");
3212
3225
  }
3213
3226
  }
@@ -3219,14 +3232,17 @@ data:
3219
3232
  messages = [JSONRPCMessageSchema.parse(rawMessage)];
3220
3233
  }
3221
3234
  } catch {
3235
+ this.onerror?.(new Error("Parse error: Invalid JSON-RPC message"));
3222
3236
  return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message");
3223
3237
  }
3224
3238
  const isInitializationRequest = messages.some(isInitializeRequest);
3225
3239
  if (isInitializationRequest) {
3226
3240
  if (this._initialized && this.sessionId !== void 0) {
3241
+ this.onerror?.(new Error("Invalid Request: Server already initialized"));
3227
3242
  return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized");
3228
3243
  }
3229
3244
  if (messages.length > 1) {
3245
+ this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed"));
3230
3246
  return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed");
3231
3247
  }
3232
3248
  this.sessionId = this.sessionIdGenerator?.();
@@ -3352,13 +3368,16 @@ data:
3352
3368
  return void 0;
3353
3369
  }
3354
3370
  if (!this._initialized) {
3371
+ this.onerror?.(new Error("Bad Request: Server not initialized"));
3355
3372
  return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized");
3356
3373
  }
3357
3374
  const sessionId = req.headers.get("mcp-session-id");
3358
3375
  if (!sessionId) {
3376
+ this.onerror?.(new Error("Bad Request: Mcp-Session-Id header is required"));
3359
3377
  return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required");
3360
3378
  }
3361
3379
  if (sessionId !== this.sessionId) {
3380
+ this.onerror?.(new Error("Session not found"));
3362
3381
  return this.createJsonErrorResponse(404, -32001, "Session not found");
3363
3382
  }
3364
3383
  return void 0;
@@ -3379,6 +3398,7 @@ data:
3379
3398
  validateProtocolVersion(req) {
3380
3399
  const protocolVersion = req.headers.get("mcp-protocol-version");
3381
3400
  if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {
3401
+ this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`));
3382
3402
  return this.createJsonErrorResponse(400, -32e3, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(", ")})`);
3383
3403
  }
3384
3404
  return void 0;
@@ -3585,7 +3605,7 @@ var StreamableHTTPServerTransport = class {
3585
3605
  };
3586
3606
 
3587
3607
  // __mcpc__cli_latest/node_modules/@jsr/std__cli/parse_args.js
3588
- var FLAG_REGEXP = /^(?:-(?:(?<doubleDash>-)(?<negated>no-)?)?)(?<key>.+?)(?:=(?<value>.+?))?$/s;
3608
+ var FLAG_REGEXP = /^(?:-(?:(?<doubleDash>-)(?<negated>no-)?)?)(?<key>.+?)(?:=(?<value>.*))?$/s;
3589
3609
  var LETTER_REGEXP = /[A-Za-z]/;
3590
3610
  var NUMBER_REGEXP = /-?\d+(\.\d*)?(e-?\d+)?$/;
3591
3611
  var HYPHEN_REGEXP = /^(-|--)[^-]/;
@@ -3596,12 +3616,19 @@ var NON_WHITESPACE_REGEXP = /\S/;
3596
3616
  function isNumber(string3) {
3597
3617
  return NON_WHITESPACE_REGEXP.test(string3) && Number.isFinite(Number(string3));
3598
3618
  }
3619
+ function isConstructorOrProto(obj, key) {
3620
+ return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
3621
+ }
3599
3622
  function setNested(object5, keys, value, collect = false) {
3600
3623
  keys = [
3601
3624
  ...keys
3602
3625
  ];
3603
3626
  const key = keys.pop();
3604
- keys.forEach((key2) => object5 = object5[key2] ??= {});
3627
+ for (const k of keys) {
3628
+ if (isConstructorOrProto(object5, k)) return;
3629
+ object5 = object5[k] ??= {};
3630
+ }
3631
+ if (isConstructorOrProto(object5, key)) return;
3605
3632
  if (collect) {
3606
3633
  const v = object5[key];
3607
3634
  if (Array.isArray(v)) {
@@ -3732,7 +3759,7 @@ function parseArgs(args, options) {
3732
3759
  let key = groups.key;
3733
3760
  let value = groups.value;
3734
3761
  if (doubleDash2) {
3735
- if (value) {
3762
+ if (value != null) {
3736
3763
  if (booleanSet.has(key)) value = parseBooleanString(value);
3737
3764
  setArgument(key, value, arg, true);
3738
3765
  continue;
@@ -3770,6 +3797,10 @@ function parseArgs(args, options) {
3770
3797
  setArgument(letter, next, arg, true);
3771
3798
  continue;
3772
3799
  }
3800
+ if (next === "=") {
3801
+ setArgument(letter, "", arg, true);
3802
+ continue argsLoop;
3803
+ }
3773
3804
  if (LETTER_REGEXP.test(letter)) {
3774
3805
  const groups2 = VALUE_REGEXP.exec(next)?.groups;
3775
3806
  if (groups2) {
@@ -4264,7 +4295,7 @@ Usage:
4264
4295
  - ${toolName}({ skill: "skill-name" }) - Load main SKILL.md content
4265
4296
  - ${toolName}({ skill: "skill-name", ref: "path/to/file" }) - Load reference file
4266
4297
 
4267
- Note: For scripts/ and assets/, use appropriate tools directly.`;
4298
+ Note: For scripts/, use the bash tool with the script path to execute.`;
4268
4299
  }
4269
4300
  function createSkillsPlugin(options) {
4270
4301
  const { paths } = options;
@@ -4372,11 +4403,15 @@ Available skills: ${available.join(", ")}` : "\n\nNo skills available.";
4372
4403
  try {
4373
4404
  const content = await readFile(join2(meta.basePath, "SKILL.md"), "utf-8");
4374
4405
  const body = extractBody(content);
4406
+ const skillPathInfo = `
4407
+ ---
4408
+ Skill path: ${meta.basePath}
4409
+ `;
4375
4410
  return {
4376
4411
  content: [
4377
4412
  {
4378
4413
  type: "text",
4379
- text: body
4414
+ text: body + skillPathInfo
4380
4415
  }
4381
4416
  ]
4382
4417
  };
@@ -5247,12 +5282,29 @@ function writeFoldedLines(count) {
5247
5282
  if (count > 1) return "\n".repeat(count - 1);
5248
5283
  return "";
5249
5284
  }
5285
+ var Scanner = class {
5286
+ source;
5287
+ #length;
5288
+ position = 0;
5289
+ constructor(source) {
5290
+ source += "\0";
5291
+ this.source = source;
5292
+ this.#length = source.length;
5293
+ }
5294
+ peek(offset = 0) {
5295
+ return this.source.charCodeAt(this.position + offset);
5296
+ }
5297
+ next() {
5298
+ this.position += 1;
5299
+ }
5300
+ eof() {
5301
+ return this.position >= this.#length - 1;
5302
+ }
5303
+ };
5250
5304
  var LoaderState = class {
5251
- input;
5252
- length;
5305
+ #scanner;
5253
5306
  lineIndent = 0;
5254
5307
  lineStart = 0;
5255
- position = 0;
5256
5308
  line = 0;
5257
5309
  onWarning;
5258
5310
  allowDuplicateKeys;
@@ -5262,44 +5314,40 @@ var LoaderState = class {
5262
5314
  tagMap = /* @__PURE__ */ new Map();
5263
5315
  anchorMap = /* @__PURE__ */ new Map();
5264
5316
  constructor(input, { schema = DEFAULT_SCHEMA, onWarning, allowDuplicateKeys = false }) {
5265
- this.input = input;
5317
+ this.#scanner = new Scanner(input);
5266
5318
  this.onWarning = onWarning;
5267
5319
  this.allowDuplicateKeys = allowDuplicateKeys;
5268
5320
  this.implicitTypes = schema.implicitTypes;
5269
5321
  this.typeMap = schema.typeMap;
5270
- this.length = input.length;
5271
5322
  this.readIndent();
5272
5323
  }
5273
5324
  skipWhitespaces() {
5274
- let ch = this.peek();
5325
+ let ch = this.#scanner.peek();
5275
5326
  while (isWhiteSpace(ch)) {
5276
- ch = this.next();
5327
+ this.#scanner.next();
5328
+ ch = this.#scanner.peek();
5277
5329
  }
5278
5330
  }
5279
5331
  skipComment() {
5280
- let ch = this.peek();
5332
+ let ch = this.#scanner.peek();
5281
5333
  if (ch !== SHARP) return;
5282
- ch = this.next();
5334
+ this.#scanner.next();
5335
+ ch = this.#scanner.peek();
5283
5336
  while (ch !== 0 && !isEOL(ch)) {
5284
- ch = this.next();
5337
+ this.#scanner.next();
5338
+ ch = this.#scanner.peek();
5285
5339
  }
5286
5340
  }
5287
5341
  readIndent() {
5288
- let char = this.peek();
5289
- while (char === SPACE) {
5342
+ let ch = this.#scanner.peek();
5343
+ while (ch === SPACE) {
5290
5344
  this.lineIndent += 1;
5291
- char = this.next();
5345
+ this.#scanner.next();
5346
+ ch = this.#scanner.peek();
5292
5347
  }
5293
5348
  }
5294
- peek(offset = 0) {
5295
- return this.input.charCodeAt(this.position + offset);
5296
- }
5297
- next() {
5298
- this.position += 1;
5299
- return this.peek();
5300
- }
5301
5349
  #createError(message) {
5302
- const mark = markToString(this.input, this.position, this.line, this.position - this.lineStart);
5350
+ const mark = markToString(this.#scanner.source, this.#scanner.position, this.line, this.#scanner.position - this.lineStart);
5303
5351
  return new SyntaxError(`${message} ${mark}`);
5304
5352
  }
5305
5353
  dispatchWarning(message) {
@@ -5344,7 +5392,7 @@ var LoaderState = class {
5344
5392
  }
5345
5393
  captureSegment(start, end, checkJson) {
5346
5394
  if (start < end) {
5347
- const result = this.input.slice(start, end);
5395
+ const result = this.#scanner.source.slice(start, end);
5348
5396
  if (checkJson) {
5349
5397
  for (let position = 0; position < result.length; position++) {
5350
5398
  const character = result.charCodeAt(position);
@@ -5362,21 +5410,21 @@ var LoaderState = class {
5362
5410
  let detected = false;
5363
5411
  const result = [];
5364
5412
  if (anchor !== null) this.anchorMap.set(anchor, result);
5365
- let ch = this.peek();
5413
+ let ch = this.#scanner.peek();
5366
5414
  while (ch !== 0) {
5367
5415
  if (ch !== MINUS) {
5368
5416
  break;
5369
5417
  }
5370
- const following = this.peek(1);
5418
+ const following = this.#scanner.peek(1);
5371
5419
  if (!isWhiteSpaceOrEOL(following)) {
5372
5420
  break;
5373
5421
  }
5374
5422
  detected = true;
5375
- this.position++;
5423
+ this.#scanner.next();
5376
5424
  if (this.skipSeparationSpace(true, -1)) {
5377
5425
  if (this.lineIndent <= nodeIndent) {
5378
5426
  result.push(null);
5379
- ch = this.peek();
5427
+ ch = this.#scanner.peek();
5380
5428
  continue;
5381
5429
  }
5382
5430
  }
@@ -5389,7 +5437,7 @@ var LoaderState = class {
5389
5437
  });
5390
5438
  if (newState) result.push(newState.result);
5391
5439
  this.skipSeparationSpace(true, -1);
5392
- ch = this.peek();
5440
+ ch = this.#scanner.peek();
5393
5441
  if ((this.line === line || this.lineIndent > nodeIndent) && ch !== 0) {
5394
5442
  throw this.#createError("Cannot read block sequence: bad indentation of a sequence entry");
5395
5443
  } else if (this.lineIndent < nodeIndent) {
@@ -5445,7 +5493,7 @@ var LoaderState = class {
5445
5493
  } else {
5446
5494
  if (!this.allowDuplicateKeys && !overridableKeys.has(keyNode) && Object.hasOwn(result, keyNode)) {
5447
5495
  this.line = startLine || this.line;
5448
- this.position = startPos || this.position;
5496
+ this.#scanner.position = startPos || this.#scanner.position;
5449
5497
  throw this.#createError("Cannot store mapping pair: duplicated key");
5450
5498
  }
5451
5499
  Object.defineProperty(result, keyNode, {
@@ -5459,37 +5507,37 @@ var LoaderState = class {
5459
5507
  return result;
5460
5508
  }
5461
5509
  readLineBreak() {
5462
- const ch = this.peek();
5510
+ const ch = this.#scanner.peek();
5463
5511
  if (ch === LINE_FEED) {
5464
- this.position++;
5512
+ this.#scanner.next();
5465
5513
  } else if (ch === CARRIAGE_RETURN) {
5466
- this.position++;
5467
- if (this.peek() === LINE_FEED) {
5468
- this.position++;
5514
+ this.#scanner.next();
5515
+ if (this.#scanner.peek() === LINE_FEED) {
5516
+ this.#scanner.next();
5469
5517
  }
5470
5518
  } else {
5471
5519
  throw this.#createError("Cannot read line: line break not found");
5472
5520
  }
5473
5521
  this.line += 1;
5474
- this.lineStart = this.position;
5522
+ this.lineStart = this.#scanner.position;
5475
5523
  }
5476
5524
  skipSeparationSpace(allowComments, checkIndent) {
5477
5525
  let lineBreaks = 0;
5478
- let ch = this.peek();
5526
+ let ch = this.#scanner.peek();
5479
5527
  while (ch !== 0) {
5480
5528
  this.skipWhitespaces();
5481
- ch = this.peek();
5529
+ ch = this.#scanner.peek();
5482
5530
  if (allowComments) {
5483
5531
  this.skipComment();
5484
- ch = this.peek();
5532
+ ch = this.#scanner.peek();
5485
5533
  }
5486
5534
  if (isEOL(ch)) {
5487
5535
  this.readLineBreak();
5488
- ch = this.peek();
5536
+ ch = this.#scanner.peek();
5489
5537
  lineBreaks++;
5490
5538
  this.lineIndent = 0;
5491
5539
  this.readIndent();
5492
- ch = this.peek();
5540
+ ch = this.#scanner.peek();
5493
5541
  } else {
5494
5542
  break;
5495
5543
  }
@@ -5500,9 +5548,9 @@ var LoaderState = class {
5500
5548
  return lineBreaks;
5501
5549
  }
5502
5550
  testDocumentSeparator() {
5503
- let ch = this.peek();
5504
- if ((ch === MINUS || ch === DOT) && ch === this.peek(1) && ch === this.peek(2)) {
5505
- ch = this.peek(3);
5551
+ let ch = this.#scanner.peek();
5552
+ if ((ch === MINUS || ch === DOT) && ch === this.#scanner.peek(1) && ch === this.#scanner.peek(2)) {
5553
+ ch = this.#scanner.peek(3);
5506
5554
  if (ch === 0 || isWhiteSpaceOrEOL(ch)) {
5507
5555
  return true;
5508
5556
  }
@@ -5510,34 +5558,34 @@ var LoaderState = class {
5510
5558
  return false;
5511
5559
  }
5512
5560
  readPlainScalar(tag, anchor, nodeIndent, withinFlowCollection) {
5513
- let ch = this.peek();
5561
+ let ch = this.#scanner.peek();
5514
5562
  if (isWhiteSpaceOrEOL(ch) || isFlowIndicator(ch) || ch === SHARP || ch === AMPERSAND || ch === ASTERISK || ch === EXCLAMATION || ch === VERTICAL_LINE || ch === GREATER_THAN || ch === SINGLE_QUOTE || ch === DOUBLE_QUOTE || ch === PERCENT || ch === COMMERCIAL_AT || ch === GRAVE_ACCENT) {
5515
5563
  return;
5516
5564
  }
5517
5565
  let following;
5518
5566
  if (ch === QUESTION || ch === MINUS) {
5519
- following = this.peek(1);
5567
+ following = this.#scanner.peek(1);
5520
5568
  if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) {
5521
5569
  return;
5522
5570
  }
5523
5571
  }
5524
5572
  let result = "";
5525
- let captureEnd = this.position;
5526
- let captureStart = this.position;
5573
+ let captureEnd = this.#scanner.position;
5574
+ let captureStart = this.#scanner.position;
5527
5575
  let hasPendingContent = false;
5528
5576
  let line = 0;
5529
5577
  while (ch !== 0) {
5530
5578
  if (ch === COLON) {
5531
- following = this.peek(1);
5579
+ following = this.#scanner.peek(1);
5532
5580
  if (isWhiteSpaceOrEOL(following) || withinFlowCollection && isFlowIndicator(following)) {
5533
5581
  break;
5534
5582
  }
5535
5583
  } else if (ch === SHARP) {
5536
- const preceding = this.peek(-1);
5584
+ const preceding = this.#scanner.peek(-1);
5537
5585
  if (isWhiteSpaceOrEOL(preceding)) {
5538
5586
  break;
5539
5587
  }
5540
- } else if (this.position === this.lineStart && this.testDocumentSeparator() || withinFlowCollection && isFlowIndicator(ch)) {
5588
+ } else if (this.#scanner.position === this.lineStart && this.testDocumentSeparator() || withinFlowCollection && isFlowIndicator(ch)) {
5541
5589
  break;
5542
5590
  } else if (isEOL(ch)) {
5543
5591
  line = this.line;
@@ -5546,10 +5594,10 @@ var LoaderState = class {
5546
5594
  this.skipSeparationSpace(false, -1);
5547
5595
  if (this.lineIndent >= nodeIndent) {
5548
5596
  hasPendingContent = true;
5549
- ch = this.peek();
5597
+ ch = this.#scanner.peek();
5550
5598
  continue;
5551
5599
  } else {
5552
- this.position = captureEnd;
5600
+ this.#scanner.position = captureEnd;
5553
5601
  this.line = line;
5554
5602
  this.lineStart = lineStart;
5555
5603
  this.lineIndent = lineIndent;
@@ -5560,13 +5608,14 @@ var LoaderState = class {
5560
5608
  const segment2 = this.captureSegment(captureStart, captureEnd, false);
5561
5609
  if (segment2) result += segment2;
5562
5610
  result += writeFoldedLines(this.line - line);
5563
- captureStart = captureEnd = this.position;
5611
+ captureStart = captureEnd = this.#scanner.position;
5564
5612
  hasPendingContent = false;
5565
5613
  }
5566
5614
  if (!isWhiteSpace(ch)) {
5567
- captureEnd = this.position + 1;
5615
+ captureEnd = this.#scanner.position + 1;
5568
5616
  }
5569
- ch = this.next();
5617
+ this.#scanner.next();
5618
+ ch = this.#scanner.peek();
5570
5619
  }
5571
5620
  const segment = this.captureSegment(captureStart, captureEnd, false);
5572
5621
  if (segment) result += segment;
@@ -5579,22 +5628,23 @@ var LoaderState = class {
5579
5628
  };
5580
5629
  }
5581
5630
  readSingleQuotedScalar(tag, anchor, nodeIndent) {
5582
- let ch = this.peek();
5631
+ let ch = this.#scanner.peek();
5583
5632
  if (ch !== SINGLE_QUOTE) return;
5584
5633
  let result = "";
5585
- this.position++;
5586
- let captureStart = this.position;
5587
- let captureEnd = this.position;
5588
- ch = this.peek();
5634
+ this.#scanner.next();
5635
+ let captureStart = this.#scanner.position;
5636
+ let captureEnd = this.#scanner.position;
5637
+ ch = this.#scanner.peek();
5589
5638
  while (ch !== 0) {
5590
5639
  if (ch === SINGLE_QUOTE) {
5591
- const segment = this.captureSegment(captureStart, this.position, true);
5640
+ const segment = this.captureSegment(captureStart, this.#scanner.position, true);
5592
5641
  if (segment) result += segment;
5593
- ch = this.next();
5642
+ this.#scanner.next();
5643
+ ch = this.#scanner.peek();
5594
5644
  if (ch === SINGLE_QUOTE) {
5595
- captureStart = this.position;
5596
- this.position++;
5597
- captureEnd = this.position;
5645
+ captureStart = this.#scanner.position;
5646
+ this.#scanner.next();
5647
+ captureEnd = this.#scanner.position;
5598
5648
  } else {
5599
5649
  if (anchor !== null) this.anchorMap.set(anchor, result);
5600
5650
  return {
@@ -5608,31 +5658,31 @@ var LoaderState = class {
5608
5658
  const segment = this.captureSegment(captureStart, captureEnd, true);
5609
5659
  if (segment) result += segment;
5610
5660
  result += writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
5611
- captureStart = captureEnd = this.position;
5612
- } else if (this.position === this.lineStart && this.testDocumentSeparator()) {
5661
+ captureStart = captureEnd = this.#scanner.position;
5662
+ } else if (this.#scanner.position === this.lineStart && this.testDocumentSeparator()) {
5613
5663
  throw this.#createError("Unexpected end of the document within a single quoted scalar");
5614
5664
  } else {
5615
- this.position++;
5616
- captureEnd = this.position;
5665
+ this.#scanner.next();
5666
+ captureEnd = this.#scanner.position;
5617
5667
  }
5618
- ch = this.peek();
5668
+ ch = this.#scanner.peek();
5619
5669
  }
5620
5670
  throw this.#createError("Unexpected end of the stream within a single quoted scalar");
5621
5671
  }
5622
5672
  readDoubleQuotedScalar(tag, anchor, nodeIndent) {
5623
- let ch = this.peek();
5673
+ let ch = this.#scanner.peek();
5624
5674
  if (ch !== DOUBLE_QUOTE) return;
5625
5675
  let result = "";
5626
- this.position++;
5627
- let captureEnd = this.position;
5628
- let captureStart = this.position;
5676
+ this.#scanner.next();
5677
+ let captureEnd = this.#scanner.position;
5678
+ let captureStart = this.#scanner.position;
5629
5679
  let tmp;
5630
- ch = this.peek();
5680
+ ch = this.#scanner.peek();
5631
5681
  while (ch !== 0) {
5632
5682
  if (ch === DOUBLE_QUOTE) {
5633
- const segment = this.captureSegment(captureStart, this.position, true);
5683
+ const segment = this.captureSegment(captureStart, this.#scanner.position, true);
5634
5684
  if (segment) result += segment;
5635
- this.position++;
5685
+ this.#scanner.next();
5636
5686
  if (anchor !== null) this.anchorMap.set(anchor, result);
5637
5687
  return {
5638
5688
  tag,
@@ -5642,19 +5692,21 @@ var LoaderState = class {
5642
5692
  };
5643
5693
  }
5644
5694
  if (ch === BACKSLASH) {
5645
- const segment = this.captureSegment(captureStart, this.position, true);
5695
+ const segment = this.captureSegment(captureStart, this.#scanner.position, true);
5646
5696
  if (segment) result += segment;
5647
- ch = this.next();
5697
+ this.#scanner.next();
5698
+ ch = this.#scanner.peek();
5648
5699
  if (isEOL(ch)) {
5649
5700
  this.skipSeparationSpace(false, nodeIndent);
5650
5701
  } else if (ch < 256 && SIMPLE_ESCAPE_SEQUENCES.has(ch)) {
5651
5702
  result += SIMPLE_ESCAPE_SEQUENCES.get(ch);
5652
- this.position++;
5703
+ this.#scanner.next();
5653
5704
  } else if ((tmp = ESCAPED_HEX_LENGTHS.get(ch) ?? 0) > 0) {
5654
5705
  let hexLength = tmp;
5655
5706
  let hexResult = 0;
5656
5707
  for (; hexLength > 0; hexLength--) {
5657
- ch = this.next();
5708
+ this.#scanner.next();
5709
+ ch = this.#scanner.peek();
5658
5710
  if ((tmp = hexCharCodeToNumber(ch)) >= 0) {
5659
5711
  hexResult = (hexResult << 4) + tmp;
5660
5712
  } else {
@@ -5662,28 +5714,28 @@ var LoaderState = class {
5662
5714
  }
5663
5715
  }
5664
5716
  result += codepointToChar(hexResult);
5665
- this.position++;
5717
+ this.#scanner.next();
5666
5718
  } else {
5667
5719
  throw this.#createError("Cannot read double quoted scalar: unknown escape sequence");
5668
5720
  }
5669
- captureStart = captureEnd = this.position;
5721
+ captureStart = captureEnd = this.#scanner.position;
5670
5722
  } else if (isEOL(ch)) {
5671
5723
  const segment = this.captureSegment(captureStart, captureEnd, true);
5672
5724
  if (segment) result += segment;
5673
5725
  result += writeFoldedLines(this.skipSeparationSpace(false, nodeIndent));
5674
- captureStart = captureEnd = this.position;
5675
- } else if (this.position === this.lineStart && this.testDocumentSeparator()) {
5726
+ captureStart = captureEnd = this.#scanner.position;
5727
+ } else if (this.#scanner.position === this.lineStart && this.testDocumentSeparator()) {
5676
5728
  throw this.#createError("Unexpected end of the document within a double quoted scalar");
5677
5729
  } else {
5678
- this.position++;
5679
- captureEnd = this.position;
5730
+ this.#scanner.next();
5731
+ captureEnd = this.#scanner.position;
5680
5732
  }
5681
- ch = this.peek();
5733
+ ch = this.#scanner.peek();
5682
5734
  }
5683
5735
  throw this.#createError("Unexpected end of the stream within a double quoted scalar");
5684
5736
  }
5685
5737
  readFlowCollection(tag, anchor, nodeIndent) {
5686
- let ch = this.peek();
5738
+ let ch = this.#scanner.peek();
5687
5739
  let terminator;
5688
5740
  let isMapping = true;
5689
5741
  let result = {};
@@ -5697,7 +5749,8 @@ var LoaderState = class {
5697
5749
  return;
5698
5750
  }
5699
5751
  if (anchor !== null) this.anchorMap.set(anchor, result);
5700
- ch = this.next();
5752
+ this.#scanner.next();
5753
+ ch = this.#scanner.peek();
5701
5754
  let readNext = true;
5702
5755
  let valueNode = null;
5703
5756
  let keyNode = null;
@@ -5709,9 +5762,9 @@ var LoaderState = class {
5709
5762
  const overridableKeys = /* @__PURE__ */ new Set();
5710
5763
  while (ch !== 0) {
5711
5764
  this.skipSeparationSpace(true, nodeIndent);
5712
- ch = this.peek();
5765
+ ch = this.#scanner.peek();
5713
5766
  if (ch === terminator) {
5714
- this.position++;
5767
+ this.#scanner.next();
5715
5768
  const kind = isMapping ? "mapping" : "sequence";
5716
5769
  return {
5717
5770
  tag,
@@ -5726,10 +5779,10 @@ var LoaderState = class {
5726
5779
  keyTag = keyNode = valueNode = null;
5727
5780
  isPair = isExplicitPair = false;
5728
5781
  if (ch === QUESTION) {
5729
- following = this.peek(1);
5782
+ following = this.#scanner.peek(1);
5730
5783
  if (isWhiteSpaceOrEOL(following)) {
5731
5784
  isPair = isExplicitPair = true;
5732
- this.position++;
5785
+ this.#scanner.next();
5733
5786
  this.skipSeparationSpace(true, nodeIndent);
5734
5787
  }
5735
5788
  }
@@ -5745,10 +5798,11 @@ var LoaderState = class {
5745
5798
  keyNode = newState.result;
5746
5799
  }
5747
5800
  this.skipSeparationSpace(true, nodeIndent);
5748
- ch = this.peek();
5801
+ ch = this.#scanner.peek();
5749
5802
  if ((isExplicitPair || this.line === line) && ch === COLON) {
5750
5803
  isPair = true;
5751
- ch = this.next();
5804
+ this.#scanner.next();
5805
+ ch = this.#scanner.peek();
5752
5806
  this.skipSeparationSpace(true, nodeIndent);
5753
5807
  const newState2 = this.composeNode({
5754
5808
  parentIndent: nodeIndent,
@@ -5766,10 +5820,11 @@ var LoaderState = class {
5766
5820
  result.push(keyNode);
5767
5821
  }
5768
5822
  this.skipSeparationSpace(true, nodeIndent);
5769
- ch = this.peek();
5823
+ ch = this.#scanner.peek();
5770
5824
  if (ch === COMMA) {
5771
5825
  readNext = true;
5772
- ch = this.next();
5826
+ this.#scanner.next();
5827
+ ch = this.#scanner.peek();
5773
5828
  } else {
5774
5829
  readNext = false;
5775
5830
  }
@@ -5785,7 +5840,7 @@ var LoaderState = class {
5785
5840
  let textIndent = nodeIndent;
5786
5841
  let emptyLines = 0;
5787
5842
  let atMoreIndented = false;
5788
- let ch = this.peek();
5843
+ let ch = this.#scanner.peek();
5789
5844
  let folding = false;
5790
5845
  if (ch === VERTICAL_LINE) {
5791
5846
  folding = false;
@@ -5797,7 +5852,8 @@ var LoaderState = class {
5797
5852
  let result = "";
5798
5853
  let tmp = 0;
5799
5854
  while (ch !== 0) {
5800
- ch = this.next();
5855
+ this.#scanner.next();
5856
+ ch = this.#scanner.peek();
5801
5857
  if (ch === PLUS || ch === MINUS) {
5802
5858
  if (CHOMPING_CLIP === chomping) {
5803
5859
  chomping = ch === PLUS ? CHOMPING_KEEP : CHOMPING_STRIP;
@@ -5820,15 +5876,16 @@ var LoaderState = class {
5820
5876
  if (isWhiteSpace(ch)) {
5821
5877
  this.skipWhitespaces();
5822
5878
  this.skipComment();
5823
- ch = this.peek();
5879
+ ch = this.#scanner.peek();
5824
5880
  }
5825
5881
  while (ch !== 0) {
5826
5882
  this.readLineBreak();
5827
5883
  this.lineIndent = 0;
5828
- ch = this.peek();
5884
+ ch = this.#scanner.peek();
5829
5885
  while ((!detectedIndent || this.lineIndent < textIndent) && ch === SPACE) {
5830
5886
  this.lineIndent++;
5831
- ch = this.next();
5887
+ this.#scanner.next();
5888
+ ch = this.#scanner.peek();
5832
5889
  }
5833
5890
  if (!detectedIndent && this.lineIndent > textIndent) {
5834
5891
  textIndent = this.lineIndent;
@@ -5867,11 +5924,12 @@ var LoaderState = class {
5867
5924
  didReadContent = true;
5868
5925
  detectedIndent = true;
5869
5926
  emptyLines = 0;
5870
- const captureStart = this.position;
5927
+ const captureStart = this.#scanner.position;
5871
5928
  while (!isEOL(ch) && ch !== 0) {
5872
- ch = this.next();
5929
+ this.#scanner.next();
5930
+ ch = this.#scanner.peek();
5873
5931
  }
5874
- const segment = this.captureSegment(captureStart, this.position, false);
5932
+ const segment = this.captureSegment(captureStart, this.#scanner.position, false);
5875
5933
  if (segment) result += segment;
5876
5934
  }
5877
5935
  if (anchor !== null) this.anchorMap.set(anchor, result);
@@ -5894,11 +5952,11 @@ var LoaderState = class {
5894
5952
  let atExplicitKey = false;
5895
5953
  let detected = false;
5896
5954
  if (anchor !== null) this.anchorMap.set(anchor, result);
5897
- let ch = this.peek();
5955
+ let ch = this.#scanner.peek();
5898
5956
  while (ch !== 0) {
5899
- const following = this.peek(1);
5957
+ const following = this.#scanner.peek(1);
5900
5958
  line = this.line;
5901
- pos = this.position;
5959
+ pos = this.#scanner.position;
5902
5960
  if ((ch === QUESTION || ch === COLON) && isWhiteSpaceOrEOL(following)) {
5903
5961
  if (ch === QUESTION) {
5904
5962
  if (atExplicitKey) {
@@ -5916,7 +5974,7 @@ var LoaderState = class {
5916
5974
  } else {
5917
5975
  throw this.#createError("Cannot read block as explicit mapping pair is incomplete: a key node is missed or followed by a non-tabulated empty line");
5918
5976
  }
5919
- this.position += 1;
5977
+ this.#scanner.next();
5920
5978
  ch = following;
5921
5979
  } else {
5922
5980
  const newState = this.composeNode({
@@ -5927,11 +5985,12 @@ var LoaderState = class {
5927
5985
  });
5928
5986
  if (!newState) break;
5929
5987
  if (this.line === line) {
5930
- ch = this.peek();
5988
+ ch = this.#scanner.peek();
5931
5989
  this.skipWhitespaces();
5932
- ch = this.peek();
5990
+ ch = this.#scanner.peek();
5933
5991
  if (ch === COLON) {
5934
- ch = this.next();
5992
+ this.#scanner.next();
5993
+ ch = this.#scanner.peek();
5935
5994
  if (!isWhiteSpaceOrEOL(ch)) {
5936
5995
  throw this.#createError("Cannot read block: a whitespace character is expected after the key-value separator within a block mapping");
5937
5996
  }
@@ -5988,7 +6047,7 @@ var LoaderState = class {
5988
6047
  keyTag = keyNode = valueNode = null;
5989
6048
  }
5990
6049
  this.skipSeparationSpace(true, -1);
5991
- ch = this.peek();
6050
+ ch = this.#scanner.peek();
5992
6051
  }
5993
6052
  if (this.lineIndent > nodeIndent && ch !== 0) {
5994
6053
  throw this.#createError("Cannot read block: bad indentation of a mapping entry");
@@ -6011,30 +6070,35 @@ var LoaderState = class {
6011
6070
  let isNamed = false;
6012
6071
  let tagHandle = "";
6013
6072
  let tagName;
6014
- let ch = this.peek();
6073
+ let ch = this.#scanner.peek();
6015
6074
  if (ch !== EXCLAMATION) return;
6016
6075
  if (tag !== null) {
6017
6076
  throw this.#createError("Cannot read tag property: duplication of a tag property");
6018
6077
  }
6019
- ch = this.next();
6078
+ this.#scanner.next();
6079
+ ch = this.#scanner.peek();
6020
6080
  if (ch === SMALLER_THAN) {
6021
6081
  isVerbatim = true;
6022
- ch = this.next();
6082
+ this.#scanner.next();
6083
+ ch = this.#scanner.peek();
6023
6084
  } else if (ch === EXCLAMATION) {
6024
6085
  isNamed = true;
6025
6086
  tagHandle = "!!";
6026
- ch = this.next();
6087
+ this.#scanner.next();
6088
+ ch = this.#scanner.peek();
6027
6089
  } else {
6028
6090
  tagHandle = "!";
6029
6091
  }
6030
- let position = this.position;
6092
+ let position = this.#scanner.position;
6031
6093
  if (isVerbatim) {
6032
6094
  do {
6033
- ch = this.next();
6095
+ this.#scanner.next();
6096
+ ch = this.#scanner.peek();
6034
6097
  } while (ch !== 0 && ch !== GREATER_THAN);
6035
- if (this.position < this.length) {
6036
- tagName = this.input.slice(position, this.position);
6037
- ch = this.next();
6098
+ if (!this.#scanner.eof()) {
6099
+ tagName = this.#scanner.source.slice(position, this.#scanner.position);
6100
+ this.#scanner.next();
6101
+ ch = this.#scanner.peek();
6038
6102
  } else {
6039
6103
  throw this.#createError("Cannot read tag property: unexpected end of stream");
6040
6104
  }
@@ -6042,19 +6106,20 @@ var LoaderState = class {
6042
6106
  while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
6043
6107
  if (ch === EXCLAMATION) {
6044
6108
  if (!isNamed) {
6045
- tagHandle = this.input.slice(position - 1, this.position + 1);
6109
+ tagHandle = this.#scanner.source.slice(position - 1, this.#scanner.position + 1);
6046
6110
  if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
6047
6111
  throw this.#createError("Cannot read tag property: named tag handle contains invalid characters");
6048
6112
  }
6049
6113
  isNamed = true;
6050
- position = this.position + 1;
6114
+ position = this.#scanner.position + 1;
6051
6115
  } else {
6052
6116
  throw this.#createError("Cannot read tag property: tag suffix cannot contain an exclamation mark");
6053
6117
  }
6054
6118
  }
6055
- ch = this.next();
6119
+ this.#scanner.next();
6120
+ ch = this.#scanner.peek();
6056
6121
  }
6057
- tagName = this.input.slice(position, this.position);
6122
+ tagName = this.#scanner.source.slice(position, this.#scanner.position);
6058
6123
  if (PATTERN_FLOW_INDICATORS.test(tagName)) {
6059
6124
  throw this.#createError("Cannot read tag property: tag suffix cannot contain flow indicator characters");
6060
6125
  }
@@ -6074,32 +6139,36 @@ var LoaderState = class {
6074
6139
  throw this.#createError(`Cannot read tag property: undeclared tag handle "${tagHandle}"`);
6075
6140
  }
6076
6141
  readAnchorProperty(anchor) {
6077
- let ch = this.peek();
6142
+ let ch = this.#scanner.peek();
6078
6143
  if (ch !== AMPERSAND) return;
6079
6144
  if (anchor !== null) {
6080
6145
  throw this.#createError("Cannot read anchor property: duplicate anchor property");
6081
6146
  }
6082
- ch = this.next();
6083
- const position = this.position;
6147
+ this.#scanner.next();
6148
+ ch = this.#scanner.peek();
6149
+ const position = this.#scanner.position;
6084
6150
  while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
6085
- ch = this.next();
6151
+ this.#scanner.next();
6152
+ ch = this.#scanner.peek();
6086
6153
  }
6087
- if (this.position === position) {
6154
+ if (this.#scanner.position === position) {
6088
6155
  throw this.#createError("Cannot read anchor property: name of an anchor node must contain at least one character");
6089
6156
  }
6090
- return this.input.slice(position, this.position);
6157
+ return this.#scanner.source.slice(position, this.#scanner.position);
6091
6158
  }
6092
6159
  readAlias() {
6093
- if (this.peek() !== ASTERISK) return;
6094
- let ch = this.next();
6095
- const position = this.position;
6160
+ if (this.#scanner.peek() !== ASTERISK) return;
6161
+ this.#scanner.next();
6162
+ let ch = this.#scanner.peek();
6163
+ const position = this.#scanner.position;
6096
6164
  while (ch !== 0 && !isWhiteSpaceOrEOL(ch) && !isFlowIndicator(ch)) {
6097
- ch = this.next();
6165
+ this.#scanner.next();
6166
+ ch = this.#scanner.peek();
6098
6167
  }
6099
- if (this.position === position) {
6168
+ if (this.#scanner.position === position) {
6100
6169
  throw this.#createError("Cannot read alias: alias name must contain at least one character");
6101
6170
  }
6102
- const alias = this.input.slice(position, this.position);
6171
+ const alias = this.#scanner.source.slice(position, this.#scanner.position);
6103
6172
  if (!this.anchorMap.has(alias)) {
6104
6173
  throw this.#createError(`Cannot read alias: unidentified alias "${alias}"`);
6105
6174
  }
@@ -6182,7 +6251,7 @@ var LoaderState = class {
6182
6251
  const cond = CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext;
6183
6252
  const flowIndent = cond ? parentIndent : parentIndent + 1;
6184
6253
  if (allowBlockCollections) {
6185
- const blockIndent = this.position - this.lineStart;
6254
+ const blockIndent = this.#scanner.position - this.lineStart;
6186
6255
  const blockSequenceState = this.readBlockSequence(tag, anchor, blockIndent);
6187
6256
  if (blockSequenceState) return this.resolveTag(blockSequenceState);
6188
6257
  const blockMappingState = this.readBlockMapping(tag, anchor, blockIndent, flowIndent);
@@ -6216,7 +6285,7 @@ var LoaderState = class {
6216
6285
  return this.resolveTag(plainScalarState);
6217
6286
  }
6218
6287
  } else if (indentStatus === 0 && CONTEXT_BLOCK_OUT === nodeContext && allowBlockCollections) {
6219
- const blockIndent = this.position - this.lineStart;
6288
+ const blockIndent = this.#scanner.position - this.lineStart;
6220
6289
  const newState2 = this.readBlockSequence(tag, anchor, blockIndent);
6221
6290
  if (newState2) return this.resolveTag(newState2);
6222
6291
  }
@@ -6231,20 +6300,22 @@ var LoaderState = class {
6231
6300
  readDirectives() {
6232
6301
  let hasDirectives = false;
6233
6302
  let version = null;
6234
- let ch = this.peek();
6303
+ let ch = this.#scanner.peek();
6235
6304
  while (ch !== 0) {
6236
6305
  this.skipSeparationSpace(true, -1);
6237
- ch = this.peek();
6306
+ ch = this.#scanner.peek();
6238
6307
  if (this.lineIndent > 0 || ch !== PERCENT) {
6239
6308
  break;
6240
6309
  }
6241
6310
  hasDirectives = true;
6242
- ch = this.next();
6243
- let position = this.position;
6311
+ this.#scanner.next();
6312
+ ch = this.#scanner.peek();
6313
+ let position = this.#scanner.position;
6244
6314
  while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
6245
- ch = this.next();
6315
+ this.#scanner.next();
6316
+ ch = this.#scanner.peek();
6246
6317
  }
6247
- const directiveName = this.input.slice(position, this.position);
6318
+ const directiveName = this.#scanner.source.slice(position, this.#scanner.position);
6248
6319
  const directiveArgs = [];
6249
6320
  if (directiveName.length < 1) {
6250
6321
  throw this.#createError("Cannot read document: directive name length must be greater than zero");
@@ -6252,13 +6323,14 @@ var LoaderState = class {
6252
6323
  while (ch !== 0) {
6253
6324
  this.skipWhitespaces();
6254
6325
  this.skipComment();
6255
- ch = this.peek();
6326
+ ch = this.#scanner.peek();
6256
6327
  if (isEOL(ch)) break;
6257
- position = this.position;
6328
+ position = this.#scanner.position;
6258
6329
  while (ch !== 0 && !isWhiteSpaceOrEOL(ch)) {
6259
- ch = this.next();
6330
+ this.#scanner.next();
6331
+ ch = this.#scanner.peek();
6260
6332
  }
6261
- directiveArgs.push(this.input.slice(position, this.position));
6333
+ directiveArgs.push(this.#scanner.source.slice(position, this.#scanner.position));
6262
6334
  }
6263
6335
  if (ch !== 0) this.readLineBreak();
6264
6336
  switch (directiveName) {
@@ -6275,20 +6347,20 @@ var LoaderState = class {
6275
6347
  this.dispatchWarning(`unknown document directive "${directiveName}"`);
6276
6348
  break;
6277
6349
  }
6278
- ch = this.peek();
6350
+ ch = this.#scanner.peek();
6279
6351
  }
6280
6352
  return hasDirectives;
6281
6353
  }
6282
6354
  readDocument() {
6283
- const documentStart = this.position;
6355
+ const documentStart = this.#scanner.position;
6284
6356
  this.checkLineBreaks = false;
6285
6357
  this.tagMap = /* @__PURE__ */ new Map();
6286
6358
  this.anchorMap = /* @__PURE__ */ new Map();
6287
6359
  const hasDirectives = this.readDirectives();
6288
6360
  this.skipSeparationSpace(true, -1);
6289
6361
  let result = null;
6290
- if (this.lineIndent === 0 && this.peek() === MINUS && this.peek(1) === MINUS && this.peek(2) === MINUS) {
6291
- this.position += 3;
6362
+ if (this.lineIndent === 0 && this.#scanner.peek() === MINUS && this.#scanner.peek(1) === MINUS && this.#scanner.peek(2) === MINUS) {
6363
+ this.#scanner.position += 3;
6292
6364
  this.skipSeparationSpace(true, -1);
6293
6365
  } else if (hasDirectives) {
6294
6366
  throw this.#createError("Cannot read document: directives end mark is expected");
@@ -6301,21 +6373,21 @@ var LoaderState = class {
6301
6373
  });
6302
6374
  if (newState) result = newState.result;
6303
6375
  this.skipSeparationSpace(true, -1);
6304
- if (this.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(this.input.slice(documentStart, this.position))) {
6376
+ if (this.checkLineBreaks && PATTERN_NON_ASCII_LINE_BREAKS.test(this.#scanner.source.slice(documentStart, this.#scanner.position))) {
6305
6377
  this.dispatchWarning("non-ASCII line breaks are interpreted as content");
6306
6378
  }
6307
- if (this.position === this.lineStart && this.testDocumentSeparator()) {
6308
- if (this.peek() === DOT) {
6309
- this.position += 3;
6379
+ if (this.#scanner.position === this.lineStart && this.testDocumentSeparator()) {
6380
+ if (this.#scanner.peek() === DOT) {
6381
+ this.#scanner.position += 3;
6310
6382
  this.skipSeparationSpace(true, -1);
6311
6383
  }
6312
- } else if (this.position < this.length - 1) {
6384
+ } else if (!this.#scanner.eof()) {
6313
6385
  throw this.#createError("Cannot read document: end of the stream or a document separator is expected");
6314
6386
  }
6315
6387
  return result;
6316
6388
  }
6317
6389
  *readDocuments() {
6318
- while (this.position < this.length - 1) {
6390
+ while (!this.#scanner.eof()) {
6319
6391
  yield this.readDocument();
6320
6392
  }
6321
6393
  }
@@ -6328,7 +6400,6 @@ function sanitizeInput(input) {
6328
6400
  if (!isEOL(input.charCodeAt(input.length - 1))) input += "\n";
6329
6401
  if (input.charCodeAt(0) === 65279) input = input.slice(1);
6330
6402
  }
6331
- input += "\0";
6332
6403
  return input;
6333
6404
  }
6334
6405
  function parse(content, options = {}) {
@@ -6488,7 +6559,7 @@ function getDefaultAgents() {
6488
6559
  }
6489
6560
 
6490
6561
  // __mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
6491
- var CLI_VERSION = "0.1.44";
6562
+ var CLI_VERSION = "0.1.51";
6492
6563
  function extractServerName(command, commandArgs) {
6493
6564
  for (const arg of commandArgs) {
6494
6565
  if (!arg.startsWith("-")) {
@@ -8158,6 +8229,147 @@ var ExperimentalServerTasks = class {
8158
8229
  requestStream(request, resultSchema, options) {
8159
8230
  return this._server.requestStream(request, resultSchema, options);
8160
8231
  }
8232
+ /**
8233
+ * Sends a sampling request and returns an AsyncGenerator that yields response messages.
8234
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
8235
+ *
8236
+ * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
8237
+ * before the final result.
8238
+ *
8239
+ * @example
8240
+ * ```typescript
8241
+ * const stream = server.experimental.tasks.createMessageStream({
8242
+ * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
8243
+ * maxTokens: 100
8244
+ * }, {
8245
+ * onprogress: (progress) => {
8246
+ * // Handle streaming tokens via progress notifications
8247
+ * console.log('Progress:', progress.message);
8248
+ * }
8249
+ * });
8250
+ *
8251
+ * for await (const message of stream) {
8252
+ * switch (message.type) {
8253
+ * case 'taskCreated':
8254
+ * console.log('Task created:', message.task.taskId);
8255
+ * break;
8256
+ * case 'taskStatus':
8257
+ * console.log('Task status:', message.task.status);
8258
+ * break;
8259
+ * case 'result':
8260
+ * console.log('Final result:', message.result);
8261
+ * break;
8262
+ * case 'error':
8263
+ * console.error('Error:', message.error);
8264
+ * break;
8265
+ * }
8266
+ * }
8267
+ * ```
8268
+ *
8269
+ * @param params - The sampling request parameters
8270
+ * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
8271
+ * @returns AsyncGenerator that yields ResponseMessage objects
8272
+ *
8273
+ * @experimental
8274
+ */
8275
+ createMessageStream(params, options) {
8276
+ const clientCapabilities = this._server.getClientCapabilities();
8277
+ if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {
8278
+ throw new Error("Client does not support sampling tools capability.");
8279
+ }
8280
+ if (params.messages.length > 0) {
8281
+ const lastMessage = params.messages[params.messages.length - 1];
8282
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
8283
+ const hasToolResults = lastContent.some((c) => c.type === "tool_result");
8284
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
8285
+ const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
8286
+ const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
8287
+ if (hasToolResults) {
8288
+ if (lastContent.some((c) => c.type !== "tool_result")) {
8289
+ throw new Error("The last message must contain only tool_result content if any is present");
8290
+ }
8291
+ if (!hasPreviousToolUse) {
8292
+ throw new Error("tool_result blocks are not matching any tool_use from the previous message");
8293
+ }
8294
+ }
8295
+ if (hasPreviousToolUse) {
8296
+ const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
8297
+ const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
8298
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) {
8299
+ throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
8300
+ }
8301
+ }
8302
+ }
8303
+ return this.requestStream({
8304
+ method: "sampling/createMessage",
8305
+ params
8306
+ }, CreateMessageResultSchema, options);
8307
+ }
8308
+ /**
8309
+ * Sends an elicitation request and returns an AsyncGenerator that yields response messages.
8310
+ * The generator is guaranteed to end with either a 'result' or 'error' message.
8311
+ *
8312
+ * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
8313
+ * and 'taskStatus' messages before the final result.
8314
+ *
8315
+ * @example
8316
+ * ```typescript
8317
+ * const stream = server.experimental.tasks.elicitInputStream({
8318
+ * mode: 'url',
8319
+ * message: 'Please authenticate',
8320
+ * elicitationId: 'auth-123',
8321
+ * url: 'https://example.com/auth'
8322
+ * }, {
8323
+ * task: { ttl: 300000 } // Task-augmented for long-running auth flow
8324
+ * });
8325
+ *
8326
+ * for await (const message of stream) {
8327
+ * switch (message.type) {
8328
+ * case 'taskCreated':
8329
+ * console.log('Task created:', message.task.taskId);
8330
+ * break;
8331
+ * case 'taskStatus':
8332
+ * console.log('Task status:', message.task.status);
8333
+ * break;
8334
+ * case 'result':
8335
+ * console.log('User action:', message.result.action);
8336
+ * break;
8337
+ * case 'error':
8338
+ * console.error('Error:', message.error);
8339
+ * break;
8340
+ * }
8341
+ * }
8342
+ * ```
8343
+ *
8344
+ * @param params - The elicitation request parameters
8345
+ * @param options - Optional request options (timeout, signal, task creation params, etc.)
8346
+ * @returns AsyncGenerator that yields ResponseMessage objects
8347
+ *
8348
+ * @experimental
8349
+ */
8350
+ elicitInputStream(params, options) {
8351
+ const clientCapabilities = this._server.getClientCapabilities();
8352
+ const mode = params.mode ?? "form";
8353
+ switch (mode) {
8354
+ case "url": {
8355
+ if (!clientCapabilities?.elicitation?.url) {
8356
+ throw new Error("Client does not support url elicitation.");
8357
+ }
8358
+ break;
8359
+ }
8360
+ case "form": {
8361
+ if (!clientCapabilities?.elicitation?.form) {
8362
+ throw new Error("Client does not support form elicitation.");
8363
+ }
8364
+ break;
8365
+ }
8366
+ }
8367
+ const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params;
8368
+ return this.requestStream({
8369
+ method: "elicitation/create",
8370
+ params: normalizedParams
8371
+ }, ElicitResultSchema, options);
8372
+ }
8161
8373
  /**
8162
8374
  * Gets the current status of a task.
8163
8375
  *
@@ -10376,22 +10588,45 @@ async function auth(provider, options) {
10376
10588
  }
10377
10589
  }
10378
10590
  async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
10591
+ const cachedState = await provider.discoveryState?.();
10379
10592
  let resourceMetadata;
10380
10593
  let authorizationServerUrl;
10381
- try {
10382
- resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn);
10383
- if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
10384
- authorizationServerUrl = resourceMetadata.authorization_servers[0];
10594
+ let metadata;
10595
+ let effectiveResourceMetadataUrl = resourceMetadataUrl;
10596
+ if (!effectiveResourceMetadataUrl && cachedState?.resourceMetadataUrl) {
10597
+ effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
10598
+ }
10599
+ if (cachedState?.authorizationServerUrl) {
10600
+ authorizationServerUrl = cachedState.authorizationServerUrl;
10601
+ resourceMetadata = cachedState.resourceMetadata;
10602
+ metadata = cachedState.authorizationServerMetadata ?? await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
10603
+ if (!resourceMetadata) {
10604
+ try {
10605
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
10606
+ } catch {
10607
+ }
10385
10608
  }
10386
- } catch {
10387
- }
10388
- if (!authorizationServerUrl) {
10389
- authorizationServerUrl = new URL("/", serverUrl);
10609
+ if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
10610
+ await provider.saveDiscoveryState?.({
10611
+ authorizationServerUrl: String(authorizationServerUrl),
10612
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
10613
+ resourceMetadata,
10614
+ authorizationServerMetadata: metadata
10615
+ });
10616
+ }
10617
+ } else {
10618
+ const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
10619
+ authorizationServerUrl = serverInfo.authorizationServerUrl;
10620
+ metadata = serverInfo.authorizationServerMetadata;
10621
+ resourceMetadata = serverInfo.resourceMetadata;
10622
+ await provider.saveDiscoveryState?.({
10623
+ authorizationServerUrl: String(authorizationServerUrl),
10624
+ resourceMetadataUrl: effectiveResourceMetadataUrl?.toString(),
10625
+ resourceMetadata,
10626
+ authorizationServerMetadata: metadata
10627
+ });
10390
10628
  }
10391
10629
  const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
10392
- const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, {
10393
- fetchFn
10394
- });
10395
10630
  let clientInformation = await Promise.resolve(provider.clientInformation());
10396
10631
  if (!clientInformation) {
10397
10632
  if (authorizationCode !== void 0) {
@@ -10646,6 +10881,26 @@ async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fet
10646
10881
  }
10647
10882
  return void 0;
10648
10883
  }
10884
+ async function discoverOAuthServerInfo(serverUrl, opts) {
10885
+ let resourceMetadata;
10886
+ let authorizationServerUrl;
10887
+ try {
10888
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts?.resourceMetadataUrl }, opts?.fetchFn);
10889
+ if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
10890
+ authorizationServerUrl = resourceMetadata.authorization_servers[0];
10891
+ }
10892
+ } catch {
10893
+ }
10894
+ if (!authorizationServerUrl) {
10895
+ authorizationServerUrl = String(new URL("/", serverUrl));
10896
+ }
10897
+ const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts?.fetchFn });
10898
+ return {
10899
+ authorizationServerUrl,
10900
+ authorizationServerMetadata,
10901
+ resourceMetadata
10902
+ };
10903
+ }
10649
10904
  async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
10650
10905
  let authorizationUrl;
10651
10906
  if (metadata) {
@@ -11510,18 +11765,6 @@ var cleanToolSchema = (schema) => {
11510
11765
  import { cwd } from "node:process";
11511
11766
  import process7 from "node:process";
11512
11767
  import { createHash } from "node:crypto";
11513
- var mcpClientPool = /* @__PURE__ */ new Map();
11514
- var mcpClientConnecting = /* @__PURE__ */ new Map();
11515
- var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
11516
- function defSignature(def) {
11517
- const defCopy = {
11518
- ...def
11519
- };
11520
- if (defCopy.transportType === "memory" || defCopy.transport) {
11521
- return `memory:${Date.now()}:${Math.random()}`;
11522
- }
11523
- return JSON.stringify(defCopy);
11524
- }
11525
11768
  function createTransport(def) {
11526
11769
  const defAny = def;
11527
11770
  const explicitType = defAny.transportType || defAny.type;
@@ -11569,90 +11812,43 @@ function createTransport(def) {
11569
11812
  }
11570
11813
  throw new Error(`Unsupported transport configuration: ${JSON.stringify(def)}`);
11571
11814
  }
11572
- async function getOrCreateMcpClient(defKey, def) {
11573
- const pooled = mcpClientPool.get(defKey);
11574
- if (pooled) {
11575
- pooled.refCount += 1;
11576
- return pooled.client;
11577
- }
11578
- const existingConnecting = mcpClientConnecting.get(defKey);
11579
- if (existingConnecting) {
11580
- const client = await existingConnecting;
11581
- const entry = mcpClientPool.get(defKey);
11582
- if (entry) entry.refCount += 1;
11583
- return client;
11584
- }
11585
- const transport = createTransport(def);
11586
- const connecting = (async () => {
11587
- const client = new Client({
11588
- name: `mcp_${shortHash(defSignature(def))}`,
11589
- version: "1.0.0"
11590
- });
11591
- await client.connect(transport, {
11592
- timeout: 6e4 * 10
11593
- });
11594
- return client;
11595
- })();
11596
- mcpClientConnecting.set(defKey, connecting);
11597
- try {
11598
- const client = await connecting;
11599
- mcpClientPool.set(defKey, {
11600
- client,
11601
- refCount: 1
11602
- });
11603
- return client;
11604
- } finally {
11605
- mcpClientConnecting.delete(defKey);
11815
+ function defSignature(def) {
11816
+ const defCopy = {
11817
+ ...def
11818
+ };
11819
+ if (defCopy.transportType === "memory" || defCopy.transport) {
11820
+ return `memory:${Date.now()}:${Math.random()}`;
11606
11821
  }
11822
+ return JSON.stringify(defCopy);
11607
11823
  }
11608
- async function releaseMcpClient(defKey) {
11609
- const entry = mcpClientPool.get(defKey);
11610
- if (!entry) return;
11611
- entry.refCount -= 1;
11612
- if (entry.refCount <= 0) {
11613
- mcpClientPool.delete(defKey);
11614
- try {
11615
- await entry.client.close();
11616
- } catch (err) {
11617
- console.error("Error closing MCP client:", err);
11618
- }
11619
- }
11824
+ var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
11825
+ async function createMcpClient(def) {
11826
+ const transport = createTransport(def);
11827
+ const client = new Client({
11828
+ name: `mcp_${shortHash(defSignature(def))}`,
11829
+ version: "1.0.0"
11830
+ });
11831
+ await client.connect(transport, {
11832
+ timeout: 6e4 * 10
11833
+ });
11834
+ return client;
11620
11835
  }
11621
- var cleanupAllPooledClients = async () => {
11622
- const entries = Array.from(mcpClientPool.entries());
11623
- mcpClientPool.clear();
11624
- await Promise.all(entries.map(async ([, { client }]) => {
11625
- try {
11626
- await client.close();
11627
- } catch (err) {
11628
- console.error("Error closing MCP client:", err);
11629
- }
11630
- }));
11631
- };
11632
- process7.once?.("exit", () => {
11633
- cleanupAllPooledClients();
11634
- });
11635
- process7.once?.("SIGINT", () => {
11636
- cleanupAllPooledClients().finally(() => process7.exit(0));
11637
- });
11638
11836
  async function composeMcpDepTools(mcpConfig, filterIn) {
11639
11837
  const allTools = {};
11640
11838
  const allClients = {};
11641
- const acquiredKeys = [];
11839
+ const clientsToClose = [];
11642
11840
  for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
11643
11841
  const def = definition;
11644
11842
  if (def.disabled) continue;
11645
- const defKey = shortHash(defSignature(def));
11646
- const serverId = name;
11647
11843
  try {
11648
- const client = await getOrCreateMcpClient(defKey, def);
11649
- acquiredKeys.push(defKey);
11650
- allClients[serverId] = client;
11844
+ const client = await createMcpClient(def);
11845
+ clientsToClose.push(client);
11846
+ allClients[name] = client;
11651
11847
  const { tools } = await client.listTools();
11652
11848
  tools.forEach((tool2) => {
11653
11849
  const toolNameWithScope = `${name}.${tool2.name}`;
11654
11850
  const internalToolName = tool2.name;
11655
- const rawToolId = `${serverId}_${internalToolName}`;
11851
+ const rawToolId = `${name}_${internalToolName}`;
11656
11852
  const toolId = sanitizePropertyKey(rawToolId);
11657
11853
  if (filterIn && !filterIn({
11658
11854
  action: internalToolName,
@@ -11664,7 +11860,7 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
11664
11860
  })) {
11665
11861
  return;
11666
11862
  }
11667
- const execute = (args) => allClients[serverId].callTool({
11863
+ const execute = (args) => allClients[name].callTool({
11668
11864
  name: internalToolName,
11669
11865
  arguments: args
11670
11866
  }, void 0, {
@@ -11681,10 +11877,12 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
11681
11877
  }
11682
11878
  }
11683
11879
  const cleanupClients = async () => {
11684
- await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
11685
- acquiredKeys.length = 0;
11686
- Object.keys(allTools).forEach((key) => delete allTools[key]);
11687
- Object.keys(allClients).forEach((key) => delete allClients[key]);
11880
+ await Promise.all(clientsToClose.map((client) => {
11881
+ try {
11882
+ return client.close();
11883
+ } catch {
11884
+ }
11885
+ }));
11688
11886
  };
11689
11887
  return {
11690
11888
  tools: allTools,